feat: Assign colors to events (#15298)

* feat: Assign colors to events

* update

* final update

* update

* fix requested changes error

* Update EventAdvancedTab.tsx

* add contrast check

* update

* fix contrsterror message visibility

* fix type error

* fix

* update test

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2024-08-14 15:10:40 +02:00
1 parent 95e2ad3007
commit 528a4fbb97
23 files changed
+289 -120

No files matched your search

+81 -71
View File
@@ -18,6 +18,7 @@ import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { useBookerUrl } from "@calcom/lib/hooks/useBookerUrl";
import { useCopy } from "@calcom/lib/hooks/useCopy";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useGetTheme } from "@calcom/lib/hooks/useTheme";
import { getEveryFreqFor } from "@calcom/lib/recurringStrings";
import { BookingStatus, SchedulingType } from "@calcom/prisma/enums";
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
@@ -100,6 +101,12 @@ function BookingListItem(booking: BookingItemProps) {
const location = booking.location as ReturnType<typeof getEventLocationValue>;
const locationVideoCallUrl = bookingMetadataSchema.parse(booking?.metadata || {})?.videoCallUrl;
const { resolvedTheme, forcedTheme } = useGetTheme();
const hasDarkTheme = !forcedTheme && resolvedTheme === "dark";
const eventTypeColor =
booking.eventType.eventTypeColor &&
booking.eventType.eventTypeColor[hasDarkTheme ? "darkEventTypeColor" : "lightEventTypeColor"];
const locationToDisplay = getSuccessPageLocationMessage(
locationVideoCallUrl ? locationVideoCallUrl : location,
t,
@@ -355,79 +362,82 @@ function BookingListItem(booking: BookingItemProps) {
/>
)}
<tr data-testid="booking-item" className="hover:bg-muted group flex flex-col transition sm:flex-row">
<td className="hidden align-top ltr:pl-6 rtl:pr-6 sm:table-cell sm:min-w-[12rem]">
<Link href={bookingLink}>
<div className="cursor-pointer py-4">
<div className="text-emphasis text-sm leading-6">{startTime}</div>
<div className="text-subtle text-sm">
{formatTime(booking.startTime, userTimeFormat, userTimeZone)} -{" "}
{formatTime(booking.endTime, userTimeFormat, userTimeZone)}
<MeetingTimeInTimezones
timeFormat={userTimeFormat}
userTimezone={userTimeZone}
startTime={booking.startTime}
endTime={booking.endTime}
attendees={booking.attendees}
/>
</div>
{!isPending && (
<div>
{(provider?.label || locationToDisplay?.startsWith("https://")) &&
locationToDisplay.startsWith("http") && (
<a
href={locationToDisplay}
onClick={(e) => e.stopPropagation()}
target="_blank"
title={locationToDisplay}
rel="noreferrer"
className="text-sm leading-6 text-blue-600 hover:underline dark:text-blue-400">
<div className="flex items-center gap-2">
{provider?.iconUrl && (
<img
src={provider.iconUrl}
className="h-4 w-4 rounded-sm"
alt={`${provider?.label} logo`}
/>
)}
{provider?.label
? t("join_event_location", { eventLocationType: provider?.label })
: t("join_meeting")}
</div>
</a>
)}
</div>
)}
{isPending && (
<Badge className="ltr:mr-2 rtl:ml-2" variant="orange">
{t("unconfirmed")}
</Badge>
)}
{booking.eventType?.team && (
<Badge className="ltr:mr-2 rtl:ml-2" variant="gray">
{booking.eventType.team.name}
</Badge>
)}
{booking.paid && !booking.payment[0] ? (
<Badge className="ltr:mr-2 rtl:ml-2" variant="orange">
{t("error_collecting_card")}
</Badge>
) : booking.paid ? (
<Badge className="ltr:mr-2 rtl:ml-2" variant="green" data-testid="paid_badge">
{booking.payment[0].paymentOption === "HOLD" ? t("card_held") : t("paid")}
</Badge>
) : null}
{recurringDates !== undefined && (
<div className="text-muted mt-2 text-sm">
<RecurringBookingsTooltip
userTimeFormat={userTimeFormat}
userTimeZone={userTimeZone}
booking={booking}
recurringDates={recurringDates}
<td className="hidden align-top ltr:pl-3 rtl:pr-6 sm:table-cell sm:min-w-[12rem]">
<div className="flex h-full items-center">
{eventTypeColor && <div className="h-[70%] w-0.5" style={{ backgroundColor: eventTypeColor }} />}
<Link href={bookingLink} className="ml-3">
<div className="cursor-pointer py-4">
<div className="text-emphasis text-sm leading-6">{startTime}</div>
<div className="text-subtle text-sm">
{formatTime(booking.startTime, userTimeFormat, userTimeZone)} -{" "}
{formatTime(booking.endTime, userTimeFormat, userTimeZone)}
<MeetingTimeInTimezones
timeFormat={userTimeFormat}
userTimezone={userTimeZone}
startTime={booking.startTime}
endTime={booking.endTime}
attendees={booking.attendees}
/>
</div>
)}
</div>
</Link>
{!isPending && (
<div>
{(provider?.label || locationToDisplay?.startsWith("https://")) &&
locationToDisplay.startsWith("http") && (
<a
href={locationToDisplay}
onClick={(e) => e.stopPropagation()}
target="_blank"
title={locationToDisplay}
rel="noreferrer"
className="text-sm leading-6 text-blue-600 hover:underline dark:text-blue-400">
<div className="flex items-center gap-2">
{provider?.iconUrl && (
<img
src={provider.iconUrl}
className="h-4 w-4 rounded-sm"
alt={`${provider?.label} logo`}
/>
)}
{provider?.label
? t("join_event_location", { eventLocationType: provider?.label })
: t("join_meeting")}
</div>
</a>
)}
</div>
)}
{isPending && (
<Badge className="ltr:mr-2 rtl:ml-2" variant="orange">
{t("unconfirmed")}
</Badge>
)}
{booking.eventType?.team && (
<Badge className="ltr:mr-2 rtl:ml-2" variant="gray">
{booking.eventType.team.name}
</Badge>
)}
{booking.paid && !booking.payment[0] ? (
<Badge className="ltr:mr-2 rtl:ml-2" variant="orange">
{t("error_collecting_card")}
</Badge>
) : booking.paid ? (
<Badge className="ltr:mr-2 rtl:ml-2" variant="green" data-testid="paid_badge">
{booking.payment[0].paymentOption === "HOLD" ? t("card_held") : t("paid")}
</Badge>
) : null}
{recurringDates !== undefined && (
<div className="text-muted mt-2 text-sm">
<RecurringBookingsTooltip
userTimeFormat={userTimeFormat}
userTimeZone={userTimeZone}
booking={booking}
recurringDates={recurringDates}
/>
</div>
)}
</div>
</Link>
</div>
</td>
<td data-testid="title-and-attendees" className={`w-full px-4${isRejected ? " line-through" : ""}`}>
<Link href={bookingLink}>
@@ -19,8 +19,10 @@ import type { EditableSchema } from "@calcom/features/form-builder/schema";
import { BookerLayoutSelector } from "@calcom/features/settings/BookerLayoutSelector";
import { classNames } from "@calcom/lib";
import cx from "@calcom/lib/classNames";
import { DEFAULT_LIGHT_BRAND_COLOR, DEFAULT_DARK_BRAND_COLOR } from "@calcom/lib/constants";
import { APP_NAME, IS_VISUAL_REGRESSION_TESTING, WEBSITE_URL } from "@calcom/lib/constants";
import { generateHashedLink } from "@calcom/lib/generateHashedLink";
import { checkWCAGContrastColor } from "@calcom/lib/getBrandColours";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { Prisma } from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
@@ -38,6 +40,7 @@ import {
TextField,
Tooltip,
showToast,
ColorPicker,
} from "@calcom/ui";
import RequiresConfirmationController from "./RequiresConfirmationController";
@@ -51,6 +54,8 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
const formMethods = useFormContext<FormValues>();
const { t } = useLocale();
const [showEventNameTip, setShowEventNameTip] = useState(false);
const [darkModeError, setDarkModeError] = useState(false);
const [lightModeError, setLightModeError] = useState(false);
const [hashedLinkVisible, setHashedLinkVisible] = useState(!!formMethods.getValues("hashedLink"));
const [redirectUrlVisible, setRedirectUrlVisible] = useState(!!formMethods.getValues("successRedirectUrl"));
const [useEventTypeDestinationCalendarEmail, setUseEventTypeDestinationCalendarEmail] = useState(
@@ -131,9 +136,20 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
const seatsLocked = shouldLockDisableProps("seatsPerTimeSlotEnabled");
const requiresBookerEmailVerificationProps = shouldLockDisableProps("requiresBookerEmailVerification");
const hideCalendarNotesLocked = shouldLockDisableProps("hideCalendarNotes");
const eventTypeColorLocked = shouldLockDisableProps("eventTypeColor");
const lockTimeZoneToggleOnBookingPageLocked = shouldLockDisableProps("lockTimeZoneToggleOnBookingPage");
const closeEventNameTip = () => setShowEventNameTip(false);
const [isEventTypeColorChecked, setIsEventTypeColorChecked] = useState(!!eventType.eventTypeColor);
const [eventTypeColorState, setEventTypeColorState] = useState(
eventType.eventTypeColor || {
lightEventTypeColor: DEFAULT_LIGHT_BRAND_COLOR,
darkEventTypeColor: DEFAULT_DARK_BRAND_COLOR,
}
);
const displayDestinationCalendarSelector =
!!connectedCalendarsQuery.data?.connectedCalendars.length && (!team || isChildrenManagedEventType);
@@ -537,6 +553,82 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
/>
)}
/>
<Controller
name="eventTypeColor"
render={() => (
<SettingsToggle
labelClassName="text-sm"
toggleSwitchAtTheEnd={true}
switchContainerClassName={classNames(
"border-subtle rounded-lg border py-6 px-4 sm:px-6",
isEventTypeColorChecked && "rounded-b-none"
)}
title={t("event_type_color")}
{...eventTypeColorLocked}
description={t("event_type_color_description")}
checked={isEventTypeColorChecked}
onCheckedChange={(e) => {
const value = e ? eventTypeColorState : null;
formMethods.setValue("eventTypeColor", value, {
shouldDirty: true,
});
setIsEventTypeColorChecked(e);
}}
childrenClassName="lg:ml-0">
<div className="border-subtle flex flex-col gap-6 rounded-b-lg border border-t-0 p-6">
<div>
<p className="text-default mb-2 block text-sm font-medium">{t("light_event_type_color")}</p>
<ColorPicker
defaultValue={eventTypeColorState.lightEventTypeColor}
onChange={(value) => {
if (checkWCAGContrastColor("#ffffff", value)) {
const newVal = {
...eventTypeColorState,
lightEventTypeColor: value,
};
setLightModeError(false);
formMethods.setValue("eventTypeColor", newVal, { shouldDirty: true });
setEventTypeColorState(newVal);
} else {
setLightModeError(true);
}
}}
/>
{lightModeError ? (
<div className="mt-4">
<Alert severity="warning" message={t("event_type_color_light_theme_contrast_error")} />
</div>
) : null}
</div>
<div className="mt-6 sm:mt-0">
<p className="text-default mb-2 block text-sm font-medium">{t("dark_event_type_color")}</p>
<ColorPicker
defaultValue={eventTypeColorState.darkEventTypeColor}
onChange={(value) => {
if (checkWCAGContrastColor("#101010", value)) {
const newVal = {
...eventTypeColorState,
darkEventTypeColor: value,
};
setDarkModeError(false);
formMethods.setValue("eventTypeColor", newVal, { shouldDirty: true });
setEventTypeColorState(newVal);
} else {
setDarkModeError(true);
}
}}
/>
{darkModeError ? (
<div className="mt-4">
<Alert severity="warning" message={t("event_type_color_dark_theme_contrast_error")} />
</div>
) : null}
</div>
</div>
</SettingsToggle>
)}
/>
{isRoundRobinEventType && (
<Controller
name="rescheduleWithSameRoundRobinHost"
@@ -17,12 +17,14 @@ import { DuplicateDialog } from "@calcom/features/eventtypes/components/Duplicat
import { TeamsFilter } from "@calcom/features/filters/components/TeamsFilter";
import { getTeamsFiltersFromQuery } from "@calcom/features/filters/lib/getTeamsFiltersFromQuery";
import Shell from "@calcom/features/shell/Shell";
import { parseEventTypeColor } from "@calcom/lib";
import { APP_NAME } from "@calcom/lib/constants";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { useGetTheme } from "@calcom/lib/hooks/useTheme";
import { useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
import { HttpError } from "@calcom/lib/http-error";
import type { User } from "@calcom/prisma/client";
@@ -213,6 +215,11 @@ const Item = ({
readOnly: boolean;
}) => {
const { t } = useLocale();
const { resolvedTheme, forcedTheme } = useGetTheme();
const hasDarkTheme = !forcedTheme && resolvedTheme === "dark";
const parsedeventTypeColor = parseEventTypeColor(type.eventTypeColor);
const eventTypeColor =
parsedeventTypeColor && parsedeventTypeColor[hasDarkTheme ? "darkEventTypeColor" : "lightEventTypeColor"];
const content = () => (
<div>
@@ -238,40 +245,46 @@ const Item = ({
</div>
);
return readOnly ? (
<div className="flex-1 overflow-hidden pr-4 text-sm">
{content()}
<EventTypeDescription eventType={type} shortenDescription />
</div>
) : (
<Link
href={`/event-types/${type.id}?tabName=setup`}
className="flex-1 overflow-hidden pr-4 text-sm"
title={type.title}>
<div>
<span
className="text-default font-semibold ltr:mr-1 rtl:ml-1"
data-testid={`event-type-title-${type.id}`}>
{type.title}
</span>
{group.profile.slug ? (
<small
className="text-subtle hidden font-normal leading-4 sm:inline"
data-testid={`event-type-slug-${type.id}`}>
{`/${group.profile.slug}/${type.slug}`}
</small>
) : null}
{readOnly && (
<Badge variant="gray" className="ml-2" data-testid="readonly-badge">
{t("readonly")}
</Badge>
return (
<div className="relative flex-1 overflow-hidden pr-4 text-sm">
{eventTypeColor && (
<div className="absolute h-full w-0.5" style={{ backgroundColor: eventTypeColor }} />
)}
<div className="ml-3">
{readOnly ? (
<div>
{content()}
<EventTypeDescription eventType={type} shortenDescription />
</div>
) : (
<Link href={`/event-types/${type.id}?tabName=setup`} title={type.title}>
<div>
<span
className="text-default font-semibold ltr:mr-1 rtl:ml-1"
data-testid={`event-type-title-${type.id}`}>
{type.title}
</span>
{group.profile.slug ? (
<small
className="text-subtle hidden font-normal leading-4 sm:inline"
data-testid={`event-type-slug-${type.id}`}>
{`/${group.profile.slug}/${type.slug}`}
</small>
) : null}
{readOnly && (
<Badge variant="gray" className="ml-2" data-testid="readonly-badge">
{t("readonly")}
</Badge>
)}
</div>
<EventTypeDescription
eventType={{ ...type, descriptionAsSafeHTML: type.safeDescription }}
shortenDescription
/>
</Link>
)}
</div>
<EventTypeDescription
eventType={{ ...type, descriptionAsSafeHTML: type.safeDescription }}
shortenDescription
/>
</Link>
</div>
);
};
@@ -470,7 +483,7 @@ export const EventTypeList = ({
return (
<li key={type.id}>
<div className="hover:bg-muted flex w-full items-center justify-between transition">
<div className="group flex w-full max-w-full items-center justify-between overflow-hidden px-4 py-4 sm:px-6">
<div className="group flex w-full max-w-full items-center justify-between overflow-hidden py-4 pl-2 pr-4 sm:pl-3 sm:pr-6">
{!(firstItem && firstItem.id === type.id) && (
<ArrowButton onClick={() => moveEventType(index, -1)} arrowDirection="up" />
)}
@@ -282,6 +282,7 @@ const EventTypePage = (props: EventTypeSetupProps & { allActiveWorkflows?: Workf
length: eventType.length,
hidden: eventType.hidden,
hashedLink: eventType.hashedLink?.link || undefined,
eventTypeColor: eventType.eventTypeColor || null,
periodDates: {
startDate: periodDates.startDate,
endDate: periodDates.endDate,
@@ -518,6 +519,8 @@ const EventTypePage = (props: EventTypeSetupProps & { allActiveWorkflows?: Workf
const updatedFields: Partial<FormValues> = {};
Object.keys(dirtyFields).forEach((key) => {
const typedKey = key as keyof typeof dirtyFields;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
updatedFields[typedKey] = undefined;
const isDirty = isFieldDirty(typedKey);
if (isDirty) {
@@ -545,6 +548,7 @@ const EventTypePage = (props: EventTypeSetupProps & { allActiveWorkflows?: Workf
onlyShowFirstAvailableSlot,
durationLimits,
recurringEvent,
eventTypeColor,
locations,
metadata,
customInputs,
@@ -615,6 +619,7 @@ const EventTypePage = (props: EventTypeSetupProps & { allActiveWorkflows?: Workf
bookingLimits,
onlyShowFirstAvailableSlot,
durationLimits,
eventTypeColor,
seatsPerTimeSlot,
seatsShowAttendees,
seatsShowAvailabilityCount,
@@ -703,6 +708,7 @@ const EventTypePage = (props: EventTypeSetupProps & { allActiveWorkflows?: Workf
onlyShowFirstAvailableSlot,
durationLimits,
recurringEvent,
eventTypeColor,
locations,
metadata,
customInputs,
@@ -765,6 +771,7 @@ const EventTypePage = (props: EventTypeSetupProps & { allActiveWorkflows?: Workf
bookingLimits,
onlyShowFirstAvailableSlot,
durationLimits,
eventTypeColor,
seatsPerTimeSlot,
seatsShowAttendees,
seatsShowAvailabilityCount,
@@ -348,12 +348,11 @@ const AppearanceView = ({
defaultValue={DEFAULT_BRAND_COLOURS.light}
resetDefaultValue={DEFAULT_LIGHT_BRAND_COLOR}
onChange={(value) => {
try {
checkWCAGContrastColor("#ffffff", value);
if (checkWCAGContrastColor("#ffffff", value)) {
setLightModeError(false);
brandColorsFormMethods.setValue("brandColor", value, { shouldDirty: true });
} catch (err) {
setLightModeError(false);
} else {
setLightModeError(true);
}
}}
/>
@@ -377,11 +376,10 @@ const AppearanceView = ({
defaultValue={DEFAULT_BRAND_COLOURS.dark}
resetDefaultValue={DEFAULT_DARK_BRAND_COLOR}
onChange={(value) => {
try {
checkWCAGContrastColor("#101010", value);
if (checkWCAGContrastColor("#101010", value)) {
setDarkModeError(false);
brandColorsFormMethods.setValue("darkBrandColor", value, { shouldDirty: true });
} catch (err) {
} else {
setDarkModeError(true);
}
}}
@@ -70,6 +70,8 @@
"meeting_awaiting_payment": "Your meeting is awaiting payment",
"dark_theme_contrast_error": "Dark Theme color doesn't pass contrast check. We recommend you change this colour so your buttons will be more visible.",
"light_theme_contrast_error": "Light Theme color doesn't pass contrast check. We recommend you change this colour so your buttons will be more visible.",
"event_type_color_light_theme_contrast_error": "Light Theme color doesn't pass contrast check. We recommend you change this color so your event types color will be more visible.",
"event_type_color_dark_theme_contrast_error": "Dark Theme color doesn't pass contrast check. We recommend you change this color so your event types color will be more visible.",
"payment_not_created_error": "Payment could not be created",
"couldnt_charge_card_error": "Could not charge card for Payment",
"no_available_users_found_error": "No available users found. Could you try another time slot?",
@@ -776,6 +778,8 @@
"brand_color": "Brand Color",
"light_brand_color": "Brand Color (Light Theme)",
"dark_brand_color": "Brand Color (Dark Theme)",
"light_event_type_color": "Event Type Color (Light Theme)",
"dark_event_type_color": "Event Type Color (Dark Theme)",
"file_not_named": "File is not named [idOrSlug]/[user]",
"create_team": "Create Team",
"name": "Name",
@@ -2496,6 +2500,8 @@
"unable_to_subscribe_to_the_platform": "An error occurred while trying to subscribe to the platform plan, please try again later",
"updating_oauth_client_error": "An error occurred while updating the OAuth client, please try again later",
"creating_oauth_client_error": "An error occurred while creating the OAuth client, please try again later",
"event_type_color": "Event type color",
"event_type_color_description": "This is only used for event type & booking differentiation within the app. It is not displayed to bookers.",
"mark_as_no_show_title": "Mark as no show",
"x_marked_as_no_show": "{{x}} marked as no-show",
"x_unmarked_as_no_show": "{{x}} unmarked as no-show",
@@ -146,6 +146,7 @@ describe("handleChildrenEventTypes", () => {
bookingLimits: undefined,
durationLimits: undefined,
recurringEvent: undefined,
eventTypeColor: undefined,
userId: 4,
},
});
@@ -301,6 +302,7 @@ describe("handleChildrenEventTypes", () => {
bookingLimits: undefined,
durationLimits: undefined,
recurringEvent: undefined,
eventTypeColor: undefined,
hashedLink: undefined,
lockTimeZoneToggleOnBookingPage: false,
requiresBookerEmailVerification: false,
@@ -417,6 +419,7 @@ describe("handleChildrenEventTypes", () => {
bookingLimits: undefined,
durationLimits: undefined,
recurringEvent: undefined,
eventTypeColor: undefined,
hashedLink: undefined,
locations: [],
lockTimeZoneToggleOnBookingPage: false,