AvailabilityPage improvements (#3118)

* Share WIP

* Embed tests fixes

* AvailabilityPage improvements

* Type fixes

* Fixes Datepicker day witdth

* Update troubleshoot.tsx

* Adds local cached slots and browsingDate

* Migrating DatePicker to use Dayjs for timeZone support

* Fixed Sunday not being available

* Added comment to clarify what is going on

* Minor bugfix in DatePicker, double empty slot markup

* Change selected date with URL through ?date..

* Initialize properly w/o query params, remove minDate for now

* Remove Loader as now using Skeleton

* Handle Etc/GMT edge case (not a timeZone)

* Added dark mode bg- color to SkeletonText + made text slightly more subtle on DatePicker

Co-authored-by: zomars <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
authored and GitHub committed 2022-06-27 21:01:46 +00:00
1 parent 2c2261f085
commit 58b2a6425a
8 files changed
+245 -245

No files matched your search

+20 -2
View File
@@ -6,6 +6,7 @@ import { FC, useEffect, useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { nameOfDay } from "@calcom/lib/weekday";
import { SkeletonContainer, SkeletonText } from "@calcom/ui";
import classNames from "@lib/classNames";
import { timeZone } from "@lib/clock";
@@ -24,10 +25,12 @@ type AvailableTimesProps = {
schedulingType: SchedulingType | null;
seatsPerTimeSlot?: number | null;
slots?: Slot[];
isLoading: boolean;
};
const AvailableTimes: FC<AvailableTimesProps> = ({
slots = [],
isLoading,
date,
eventTypeId,
eventTypeSlug,
@@ -58,7 +61,7 @@ const AvailableTimes: FC<AvailableTimesProps> = ({
</span>
</div>
<div className="grid flex-grow grid-cols-2 gap-x-2 overflow-y-auto sm:block md:h-[364px]">
{slots?.length > 0 &&
{slots.length > 0 &&
slots.map((slot) => {
type BookingURL = {
pathname: string;
@@ -129,11 +132,26 @@ const AvailableTimes: FC<AvailableTimesProps> = ({
</div>
);
})}
{!slots.length && (
{!isLoading && !slots.length && (
<div className="-mt-4 flex h-full w-full flex-col content-center items-center justify-center">
<h1 className="my-6 text-xl text-black dark:text-white">{t("all_booked_today")}</h1>
</div>
)}
{isLoading && !slots.length && (
<>
<SkeletonContainer className="mb-2">
<SkeletonText width="full" height="20" />
</SkeletonContainer>
<SkeletonContainer className="mb-2">
<SkeletonText width="full" height="20" />
</SkeletonContainer>
<SkeletonContainer className="mb-2">
<SkeletonText width="full" height="20" />
</SkeletonContainer>
</>
)}
</div>
</div>
);
@@ -15,13 +15,15 @@ import {
import { EventType } from "@prisma/client";
import * as Collapsible from "@radix-ui/react-collapsible";
import { useContracts } from "contexts/contractsContext";
import dayjs from "dayjs";
import dayjs, { Dayjs } from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import timeZone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import { TFunction } from "next-i18next";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { FormattedNumber, IntlProvider } from "react-intl";
import { z } from "zod";
import { AppStoreLocationType, LocationObject, LocationType } from "@calcom/app-store/locations";
import {
@@ -36,10 +38,11 @@ import { yyyymmdd } from "@calcom/lib/date-fns";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { getRecurringFreq } from "@calcom/lib/recurringStrings";
import { localStorage } from "@calcom/lib/webstorage";
import DatePicker, { Day } from "@calcom/ui/booker/DatePicker";
import DatePicker from "@calcom/ui/booker/DatePicker";
import { asStringOrNull } from "@lib/asStringOrNull";
import { timeZone } from "@lib/clock";
import { asStringOrUndefined } from "@lib/asStringOrNull";
import { timeZone as localStorageTimeZone } from "@lib/clock";
// import { timeZone } from "@lib/clock";
import { useExposePlanGlobally } from "@lib/hooks/useExposePlanGlobally";
import useTheme from "@lib/hooks/useTheme";
import { isBrandingHidden } from "@lib/isBrandingHidden";
@@ -59,6 +62,7 @@ import type { DynamicAvailabilityPageProps } from "../../../pages/d/[link]/[slug
import type { AvailabilityTeamPageProps } from "../../../pages/team/[slug]/[type]";
dayjs.extend(utc);
dayjs.extend(timeZone);
dayjs.extend(customParseFormat);
type Props = AvailabilityTeamPageProps | AvailabilityPageProps | DynamicAvailabilityPageProps;
@@ -116,25 +120,35 @@ const useSlots = ({
eventTypeId,
startTime,
endTime,
timeZone,
}: {
eventTypeId: number;
startTime: Date;
endTime: Date;
startTime?: Dayjs;
endTime?: Dayjs;
timeZone: string;
}) => {
const { data, isLoading } = trpc.useQuery(
[
"viewer.public.slots.getSchedule",
{
eventTypeId,
startTime: startTime.toISOString(),
endTime: endTime.toISOString(),
startTime: startTime?.toISOString() || "",
timeZone,
endTime: endTime?.toISOString() || "",
},
],
/** Prevents fetching past dates */
{ enabled: dayjs(startTime).isAfter(dayjs().subtract(1, "day")) }
{ enabled: !!startTime && !!endTime }
);
return { slots: data?.slots || {}, isLoading };
const [cachedSlots, setCachedSlots] = useState<NonNullable<typeof data>["slots"]>({});
useEffect(() => {
if (data?.slots) {
setCachedSlots((c) => ({ ...c, ...data?.slots }));
}
}, [data]);
return { slots: cachedSlots, isLoading };
};
const SlotPicker = ({
@@ -149,27 +163,53 @@ const SlotPicker = ({
eventType: Pick<EventType, "id" | "schedulingType" | "slug">;
timezoneDropdown: JSX.Element;
timeFormat: string;
timeZone?: string;
timeZone: string;
seatsPerTimeSlot?: number;
recurringEventCount?: number;
weekStart?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
}) => {
const { selectedDate, setSelectedDate } = useDateSelected({ timeZone });
const [selectedDate, setSelectedDate] = useState<Dayjs>();
const [browsingDate, setBrowsingDate] = useState<Dayjs>();
const { i18n, isLocaleReady } = useLocale();
const [startDate, setStartDate] = useState(new Date());
const router = useRouter();
useEffect(() => {
if (dayjs(selectedDate).startOf("month").isAfter(dayjs())) {
setStartDate(dayjs(selectedDate).startOf("month").toDate());
if (!router.isReady) {
return;
}
}, [selectedDate]);
const month = asStringOrUndefined(router.query.month);
const date = asStringOrUndefined(router.query.date);
const { slots, isLoading } = useSlots({
// Etc/GMT is not actually a timeZone, so handle this select option explicitly to prevent a hard crash.
if (timeZone === "Etc/GMT") {
setBrowsingDate(dayjs.utc(month).startOf("month"));
if (date) {
setSelectedDate(dayjs.utc(date));
}
} else {
setBrowsingDate(dayjs(month).tz(timeZone, true).startOf("month"));
if (date) {
setSelectedDate(dayjs(date).tz(timeZone, true));
}
}
}, [router.isReady, router.query.month, router.query.date, timeZone]);
const { i18n, isLocaleReady } = useLocale();
const { slots: _1 } = useSlots({
eventTypeId: eventType.id,
startTime: dayjs(startDate).startOf("day").toDate(),
endTime: dayjs(startDate).endOf("month").toDate(),
startTime: selectedDate?.startOf("month"),
endTime: selectedDate?.endOf("month"),
timeZone,
});
const { slots: _2, isLoading } = useSlots({
eventTypeId: eventType.id,
startTime: browsingDate?.startOf("month"),
endTime: browsingDate?.endOf("month"),
timeZone,
});
const slots = useMemo(() => ({ ..._1, ..._2 }), [_1, _2]);
return (
<>
@@ -184,23 +224,39 @@ const SlotPicker = ({
includedDates={Object.keys(slots).filter((k) => slots[k].length > 0)}
locale={isLocaleReady ? i18n.language : "en"}
selected={selectedDate}
onChange={setSelectedDate}
onMonthChange={(startDate) => {
// set the minimum day to today in the current month, not the beginning of the month
setStartDate(
dayjs(startDate).isBefore(dayjs().subtract(1, "day"))
? dayjs(new Date()).startOf("day").toDate()
: startDate
onChange={(selectedDate) => {
router.replace(
{
query: {
...router.query,
date: selectedDate.format("YYYY-MM-DD"),
},
},
undefined,
{ shallow: true }
);
}}
onMonthChange={(browsingDate) => {
router.replace(
{
query: {
...router.query,
month: browsingDate.format("YYYY-MM"),
},
},
undefined,
{ shallow: true }
);
}}
browsingDate={browsingDate}
weekStart={weekStart}
// DayComponent={(props) => <DayContainer {...props} eventTypeId={eventType.id} />}
/>
{selectedDate && (
<AvailableTimes
slots={slots[yyyymmdd(selectedDate)]}
date={dayjs(selectedDate)}
isLoading={isLoading}
slots={slots[yyyymmdd(selectedDate.toDate())]}
date={selectedDate}
timeFormat={timeFormat}
eventTypeId={eventType.id}
eventTypeSlug={eventType.slug}
@@ -217,9 +273,11 @@ const SlotPicker = ({
function TimezoneDropdown({
onChangeTimeFormat,
onChangeTimeZone,
timeZone,
}: {
onChangeTimeFormat: (newTimeFormat: string) => void;
onChangeTimeZone: (newTimeZone: string) => void;
timeZone?: string;
}) {
const [isTimeOptionsOpen, setIsTimeOptionsOpen] = useState(false);
@@ -229,8 +287,8 @@ function TimezoneDropdown({
}, []);
const handleSelectTimeZone = (newTimeZone: string) => {
timeZone(newTimeZone);
onChangeTimeZone(newTimeZone);
localStorageTimeZone(newTimeZone);
setIsTimeOptionsOpen(false);
};
@@ -242,7 +300,7 @@ function TimezoneDropdown({
<Collapsible.Root open={isTimeOptionsOpen} onOpenChange={setIsTimeOptionsOpen}>
<Collapsible.Trigger className="min-w-32 text-bookinglight mb-1 -ml-2 px-2 py-1 text-left dark:text-white">
<GlobeIcon className="mr-[10px] ml-[2px] -mt-1 inline-block h-4 w-4 text-gray-400" />
{timeZone()}
{timeZone || dayjs.tz.guess()}
{isTimeOptionsOpen ? (
<ChevronUpIcon className="ml-1 -mt-1 inline-block h-4 w-4" />
) : (
@@ -256,63 +314,22 @@ function TimezoneDropdown({
);
}
const useDateSelected = ({ timeZone }: { timeZone?: string }) => {
const router = useRouter();
const [selectedDate, _setSelectedDate] = useState<Date>();
useEffect(() => {
/** TODO: router.query.date is comming as `null` even when set like this:
* `/user/type?date=2022-06-22-0600`
*/
const dateString = asStringOrNull(router.query.date);
if (dateString) {
const offsetString = dateString.substr(11, 14); // hhmm
const offsetSign = dateString.substr(10, 1); // + or -
const offsetHour = offsetString.slice(0, -2);
const offsetMinute = offsetString.slice(-2);
const utcOffsetInMinutes =
(offsetSign === "-" ? -1 : 1) *
(60 * (offsetHour !== "" ? parseInt(offsetHour) : 0) +
(offsetMinute !== "" ? parseInt(offsetMinute) : 0));
const date = dayjs(dateString.substr(0, 10)).utcOffset(utcOffsetInMinutes, true);
console.log("date.isValid()", date.isValid());
if (date.isValid()) {
setSelectedDate(date.toDate());
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [router.query.date]);
const setSelectedDate = (newDate: Date) => {
router.replace(
{
query: {
...router.query,
date: dayjs(newDate).tz(timeZone, true).format("YYYY-MM-DDZZ"),
},
},
undefined,
{ shallow: true }
);
_setSelectedDate(newDate);
};
return { selectedDate, setSelectedDate };
};
const dateQuerySchema = z.object({
rescheduleUid: z.string().optional().default(""),
date: z.string().optional().default(""),
timeZone: z.string().optional().default(""),
});
const AvailabilityPage = ({ profile, eventType }: Props) => {
const router = useRouter();
const isEmbed = useIsEmbed();
const { rescheduleUid } = router.query;
const query = dateQuerySchema.parse(router.query);
const { rescheduleUid } = query;
const { Theme } = useTheme(profile.theme);
const { t } = useLocale();
const { contracts } = useContracts();
const availabilityDatePickerEmbedStyles = useEmbedStyles("availabilityDatePicker");
const shouldAlignCentrallyInEmbed = useEmbedNonStylesConfig("align") !== "left";
const shouldAlignCentrally = !isEmbed || shouldAlignCentrallyInEmbed;
const isBackgroundTransparent = useIsBackgroundTransparent();
@@ -321,8 +338,12 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
const [isAvailableTimesVisible, setIsAvailableTimesVisible] = useState<boolean>();
useEffect(() => {
setIsAvailableTimesVisible(!!router.query.date);
}, [router.query.date]);
setTimeZone(localStorageTimeZone() || dayjs.tz.guess());
}, []);
useEffect(() => {
setIsAvailableTimesVisible(!!query.date);
}, [query.date]);
// TODO: Improve this;
useExposePlanGlobally(eventType.users.length === 1 ? eventType.users[0].plan : "PRO");
@@ -349,10 +370,6 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
}
}, [telemetry]);
// Avoid embed styling flicker. Till embed status is confirmed, don't render.
if (isEmbed === null) {
return null;
}
// Recurring event sidebar requires more space
const maxWidth = isAvailableTimesVisible
? recurringEventCount
@@ -362,8 +379,15 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
? "max-w-4xl"
: "max-w-3xl";
const timezoneDropdown = (
<TimezoneDropdown onChangeTimeFormat={setTimeFormat} onChangeTimeZone={setTimeZone} />
const timezoneDropdown = useMemo(
() => (
<TimezoneDropdown
onChangeTimeFormat={setTimeFormat}
timeZone={timeZone}
onChangeTimeZone={setTimeZone}
/>
),
[timeZone]
);
return (
@@ -374,7 +398,6 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
description={`${rescheduleUid ? t("reschedule") : ""} ${eventType.title}`}
name={profile.name || undefined}
username={profile.slug || undefined}
// avatar={profile.image || undefined}
/>
<CustomBranding lightVal={profile.brandColor} darkVal={profile.darkBrandColor} />
<div>
@@ -666,21 +689,29 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
</div>
)*/}
</div>
<SlotPicker
weekStart={
typeof profile.weekStart === "string"
? (["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"].indexOf(
profile.weekStart
) as 0 | 1 | 2 | 3 | 4 | 5 | 6)
: profile.weekStart /* Allows providing weekStart as number */
}
eventType={eventType}
timezoneDropdown={timezoneDropdown}
timeZone={timeZone}
timeFormat={timeFormat}
seatsPerTimeSlot={eventType.seatsPerTimeSlot || undefined}
recurringEventCount={recurringEventCount}
/>
{timeZone && (
<SlotPicker
weekStart={
typeof profile.weekStart === "string"
? ([
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
].indexOf(profile.weekStart) as 0 | 1 | 2 | 3 | 4 | 5 | 6)
: profile.weekStart /* Allows providing weekStart as number */
}
eventType={eventType}
timezoneDropdown={timezoneDropdown}
timeFormat={timeFormat}
timeZone={timeZone}
seatsPerTimeSlot={eventType.seatsPerTimeSlot || undefined}
recurringEventCount={recurringEventCount}
/>
)}
</div>
</div>
{(!eventType.users[0] || !isBrandingHidden(eventType.users[0])) && !isEmbed && <PoweredByCal />}
@@ -690,29 +721,4 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
);
};
const DayContainer = (props: React.ComponentProps<typeof Day> & { eventTypeId: number }) => {
const { eventTypeId, ...rest } = props;
/** :
* Fetch each individual day here. All these are batched with tRPC anyways.
**/
const { slots } = useSlots({
eventTypeId,
startTime: dayjs(props.date).startOf("day").toDate(),
endTime: dayjs(props.date).endOf("day").toDate(),
});
const includedDates = Object.keys(slots).filter((k) => slots[k].length > 0);
const disabled = includedDates.length > 0 ? !includedDates.includes(yyyymmdd(props.date)) : props.disabled;
return <Day {...{ ...rest, disabled }} />;
};
const AvailableTimesContainer = (props: React.ComponentProps<typeof AvailableTimes>) => {
const { date, eventTypeId } = props;
const { slots } = useSlots({
eventTypeId,
startTime: dayjs(date).startOf("day").toDate(),
endTime: dayjs(date).endOf("day").toDate(),
});
return <AvailableTimes {...props} slots={slots[date.format("YYYY-MM-DD")]} />;
};
export default AvailabilityPage;
+1 -1
View File
@@ -60,7 +60,7 @@ const AvailabilityView = ({ user }: { user: User }) => {
className="inline h-8 border-none p-0"
defaultValue={selectedDate.format("YYYY-MM-DD")}
onChange={(e) => {
setSelectedDate(dayjs(e.target.value));
if (e.target.value) setSelectedDate(dayjs(e.target.value));
}}
/>
<small className="block text-neutral-400">{t("hover_over_bold_times_tip")}</small>
+8 -27
View File
@@ -7,7 +7,7 @@ import { getUserAvailability } from "@calcom/core/getUserAvailability";
import { yyyymmdd } from "@calcom/lib/date-fns";
import { availabilityUserSelect } from "@calcom/prisma";
import { stringToDayjs } from "@calcom/prisma/zod-utils";
import { TimeRange, WorkingHours } from "@calcom/types/schedule";
import { TimeRange } from "@calcom/types/schedule";
import isOutOfBounds from "@lib/isOutOfBounds";
import getSlots from "@lib/slots";
@@ -23,6 +23,8 @@ const getScheduleSchema = z
endTime: stringToDayjs,
// Event type ID
eventTypeId: z.number().optional(),
// invitee timezone
timeZone: z.string().optional(),
// or list of users (for dynamic events)
usernameList: z.array(z.string()).optional(),
})
@@ -41,7 +43,6 @@ export type Slot = {
const checkForAvailability = ({
time,
busy,
workingHours,
eventLength,
beforeBufferTime,
afterBufferTime,
@@ -49,33 +50,11 @@ const checkForAvailability = ({
}: {
time: Dayjs;
busy: (TimeRange | { start: string; end: string })[];
workingHours: WorkingHours[];
eventLength: number;
beforeBufferTime: number;
afterBufferTime: number;
currentSeats?: CurrentSeats;
}) => {
if (
!workingHours.some((workingHour) => {
if (!workingHour.days.includes(time.day())) {
return false;
}
if (
!time.isBetween(
time.utc().startOf("day").add(workingHour.startTime, "minutes"),
time.utc().startOf("day").add(workingHour.endTime, "minutes"),
null,
"[)"
)
) {
return false;
}
return true;
})
) {
return false;
}
if (currentSeats?.some((booking) => booking.startTime.toISOString() === time.toISOString())) {
return true;
}
@@ -117,6 +96,7 @@ const checkForAvailability = ({
) {
return false;
}
return true;
});
};
@@ -201,6 +181,7 @@ export const slotsRouter = createRouter().query("getSchedule", {
);
const workingHours = userSchedules.flatMap((s) => s.workingHours);
const slots: Record<string, Slot[]> = {};
const availabilityCheckProps = {
eventLength: eventType.length,
@@ -217,7 +198,7 @@ export const slotsRouter = createRouter().query("getSchedule", {
periodDays: eventType.periodDays,
});
let time = dayjs(startTime);
let time = input.timeZone === "Etc/GMT" ? startTime.utc() : startTime.tz(input.timeZone);
do {
// get slots retrieves the available times for a given day
const times = getSlots({
@@ -231,8 +212,8 @@ export const slotsRouter = createRouter().query("getSchedule", {
// if ROUND_ROBIN - slots stay available on some() - if normal / COLLECTIVE - slots only stay available on every()
const filterStrategy =
!eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE
? ("every" as const)
: ("some" as const);
? "every"
: "some";
const filteredTimes = times
.filter(isWithinBounds)
.filter((time) =>
+3 -2
View File
@@ -105,9 +105,10 @@ export function getWorkingHours(
});
}
// check for overflow to the previous day
// overflowing days constraint to 0-6 day range (Sunday-Saturday)
if (startTime < MINUTES_DAY_START || endTime < MINUTES_DAY_START) {
workingHours.push({
days: schedule.days.map((day) => day - 1),
days: schedule.days.map((day) => (day - 1 >= 0 ? day - 1 : 6)),
startTime: startTime + MINUTES_IN_DAY,
endTime: Math.min(endTime + MINUTES_IN_DAY, MINUTES_DAY_END),
});
@@ -115,7 +116,7 @@ export function getWorkingHours(
// else, check for overflow in the next day
else if (startTime > MINUTES_DAY_END || endTime > MINUTES_DAY_END) {
workingHours.push({
days: schedule.days.map((day) => day + 1),
days: schedule.days.map((day) => (day + 1) % 7),
startTime: Math.max(startTime - MINUTES_IN_DAY, MINUTES_DAY_START),
endTime: endTime - MINUTES_IN_DAY,
});
+5 -3
View File
@@ -1,6 +1,8 @@
import dayjs from "dayjs";
import dayjs, { Dayjs } from "dayjs";
// converts a date to 2022-04-25 for example.
export const yyyymmdd = (date: Date) => dayjs(date).format("YYYY-MM-DD");
export const yyyymmdd = (date: Date | Dayjs) =>
date instanceof Date ? dayjs(date).format("YYYY-MM-DD") : date.format("YYYY-MM-DD");
export const daysInMonth = (date: Date) => dayjs(date).daysInMonth();
export const daysInMonth = (date: Date | Dayjs) =>
date instanceof Date ? dayjs(date).daysInMonth() : date.daysInMonth();
+66 -78
View File
@@ -1,12 +1,11 @@
import { ChevronLeftIcon, ChevronRightIcon } from "@heroicons/react/solid";
import dayjs from "dayjs";
import dayjs, { Dayjs } from "dayjs";
import isToday from "dayjs/plugin/isToday";
import { useMemo, useState } from "react";
import classNames from "@calcom/lib/classNames";
import { daysInMonth, yyyymmdd } from "@calcom/lib/date-fns";
import { weekdayNames } from "@calcom/lib/weekday";
import { SkeletonContainer } from "@calcom/ui/skeleton";
import { SkeletonContainer, SkeletonText } from "@calcom/ui/skeleton";
dayjs.extend(isToday);
@@ -14,15 +13,15 @@ export type DatePickerProps = {
/** which day of the week to render the calendar. Usually Sunday (=0) or Monday (=1) - default: Sunday */
weekStart?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
/** Fires whenever a selected date is changed. */
onChange: (date: Date) => void;
onChange: (date: Dayjs) => void;
/** Fires when the month is changed. */
onMonthChange?: (date: Date) => void;
onMonthChange?: (date: Dayjs) => void;
/** which date is currently selected (not tracked from here) */
selected?: Date;
selected?: Dayjs;
/** defaults to current date. */
minDate?: Date;
minDate?: Dayjs;
/** Furthest date selectable in the future, default = UNLIMITED */
maxDate?: Date;
maxDate?: Dayjs;
/** locale, any IETF language tag, e.g. "hu-HU" - defaults to Browser settings */
locale: string;
/** Defaults to [], which dates are not bookable. Array of valid dates like: ["2022-04-23", "2022-04-24"] */
@@ -39,11 +38,11 @@ export const Day = ({
date,
active,
...props
}: JSX.IntrinsicElements["button"] & { active: boolean; date: Date }) => {
}: JSX.IntrinsicElements["button"] & { active: boolean; date: Dayjs }) => {
return (
<button
className={classNames(
"hover:border-brand disabled:text-bookinglighter absolute top-0 left-0 right-0 bottom-0 mx-auto rounded-sm border border-transparent text-center font-medium disabled:cursor-default disabled:border-transparent disabled:font-light dark:hover:border-white disabled:dark:border-transparent",
"hover:border-brand disabled:text-bookinglighter absolute top-0 left-0 right-0 bottom-0 mx-auto w-full rounded-sm border border-transparent text-center font-medium disabled:cursor-default disabled:border-transparent disabled:font-light dark:hover:border-white disabled:dark:border-transparent",
active
? "bg-brand text-brandcontrast dark:bg-darkmodebrand dark:text-darkmodebrandcontrast"
: !props.disabled
@@ -53,16 +52,14 @@ export const Day = ({
data-testid="day"
data-disabled={props.disabled}
{...props}>
{date.getDate()}
{dayjs(date).isToday() && (
<span className="absolute left-0 bottom-0 mx-auto -mb-px w-full text-4xl">.</span>
)}
{date.date()}
{date.isToday() && <span className="absolute left-0 bottom-0 mx-auto -mb-px w-full text-4xl">.</span>}
</button>
);
};
const Days = ({
minDate,
// minDate,
excludedDates = [],
includedDates,
browsingDate,
@@ -72,60 +69,51 @@ const Days = ({
...props
}: Omit<DatePickerProps, "locale" | "className" | "weekStart"> & {
DayComponent?: React.FC<React.ComponentProps<typeof Day>>;
browsingDate: Date;
browsingDate: Dayjs;
weekStart: number;
}) => {
// Create placeholder elements for empty days in first week
const weekdayOfFirst = new Date(new Date(browsingDate).setDate(1)).getDay();
// memoize to prevent a flicker on redraw on the current day
const minDateValueOf = useMemo(() => {
return minDate?.valueOf() || new Date().valueOf();
}, [minDate]);
const weekdayOfFirst = browsingDate.day();
const days: (Date | null)[] = Array((weekdayOfFirst - weekStart + 7) % 7).fill(null);
const days: (Dayjs | null)[] = Array((weekdayOfFirst - weekStart + 7) % 7).fill(null);
for (let day = 1, dayCount = daysInMonth(browsingDate); day <= dayCount; day++) {
const date = new Date(new Date(browsingDate).setDate(day));
const date = browsingDate.set("date", day);
days.push(date);
}
return (
<>
{days.map((day, idx) =>
day === null ? (
<div key={`e-${idx}`} />
) : (
<div key={day === null ? `e-${idx}` : `day-${day}`} className="relative w-full pt-[100%]">
{day === null ? (
<div key={`e-${idx}`} />
) : props.isLoading ? (
<SkeletonContainer>
<button
className="absolute top-0 left-0 right-0 bottom-0 mx-auto w-full rounded-sm border-transparent bg-gray-50 text-gray-400 opacity-50 dark:bg-gray-900 dark:text-gray-200"
key={`e-${idx}`}>
{day.getDate()}
</button>
</SkeletonContainer>
) : (
<DayComponent
date={day}
onClick={() => {
props.onChange(day);
window.scrollTo({
top: 360,
behavior: "smooth",
});
}}
disabled={
(includedDates && !includedDates.includes(yyyymmdd(day))) ||
excludedDates.includes(yyyymmdd(day)) ||
day.valueOf() < minDateValueOf
}
active={selected ? yyyymmdd(selected) === yyyymmdd(day) : false}
/>
)}
</div>
)
)}
{days.map((day, idx) => (
<div key={day === null ? `e-${idx}` : `day-${day.format()}`} className="relative w-full pt-[100%]">
{day === null ? (
<div key={`e-${idx}`} />
) : props.isLoading ? (
<SkeletonContainer>
<button
className="absolute top-0 left-0 right-0 bottom-0 mx-auto w-full rounded-sm border-transparent bg-gray-50 text-gray-400 opacity-50 dark:bg-gray-900 dark:text-gray-400"
key={`e-${idx}`}>
{day.date()}
</button>
</SkeletonContainer>
) : (
<DayComponent
date={day}
onClick={() => {
props.onChange(day);
window.scrollTo({
top: 360,
behavior: "smooth",
});
}}
disabled={
(includedDates && !includedDates.includes(yyyymmdd(day))) ||
excludedDates.includes(yyyymmdd(day))
}
active={selected ? yyyymmdd(selected) === yyyymmdd(day) : false}
/>
)}
</div>
))}
</>
);
};
@@ -138,14 +126,11 @@ const DatePicker = ({
onMonthChange,
...passThroughProps
}: DatePickerProps & Partial<React.ComponentProps<typeof Days>>) => {
const [month, setMonth] = useState(selected ? selected.getMonth() : new Date().getMonth());
const browsingDate = passThroughProps.browsingDate || dayjs().startOf("month");
const changeMonth = (newMonth: number) => {
setMonth(newMonth);
if (onMonthChange) {
const d = new Date();
d.setMonth(newMonth, 1);
onMonthChange(d);
onMonthChange(browsingDate.add(newMonth, "month"));
}
};
@@ -153,25 +138,33 @@ const DatePicker = ({
<div className={className}>
<div className="mb-4 flex justify-between text-xl font-light">
<span className="w-1/2 dark:text-white">
<strong className="text-bookingdarker dark:text-white">
{new Date(new Date().setMonth(month)).toLocaleString(locale, { month: "long" })}
</strong>{" "}
<span className="text-bookinglight">{new Date(new Date().setMonth(month)).getFullYear()}</span>
{browsingDate ? (
<>
<strong className="text-bookingdarker dark:text-white">
{browsingDate.toDate().toLocaleString(locale, {
month: "long",
})}
</strong>{" "}
<span className="text-bookinglight">{browsingDate.format("YYYY")}</span>
</>
) : (
<SkeletonText width="24" height="8" />
)}
</span>
<div className="text-black dark:text-white">
<button
onClick={() => changeMonth(month - 1)}
onClick={() => changeMonth(-1)}
className={classNames(
"group p-1 opacity-50 hover:opacity-100 ltr:mr-2 rtl:ml-2",
month <= new Date().getMonth() && "disabled:text-bookinglighter hover:opacity-50"
!browsingDate.isAfter(dayjs()) && "disabled:text-bookinglighter hover:opacity-50"
)}
disabled={month <= new Date().getMonth()}
disabled={!browsingDate.isAfter(dayjs())}
data-testid="decrementMonth">
<ChevronLeftIcon className="h-5 w-5" />
</button>
<button
className="group p-1 opacity-50 hover:opacity-100"
onClick={() => changeMonth(month + 1)}
onClick={() => changeMonth(+1)}
data-testid="incrementMonth">
<ChevronRightIcon className="h-5 w-5" />
</button>
@@ -185,12 +178,7 @@ const DatePicker = ({
))}
</div>
<div className="grid grid-cols-7 gap-2 text-center">
<Days
browsingDate={new Date(new Date().setMonth(month))}
weekStart={weekStart}
selected={selected}
{...passThroughProps}
/>
<Days weekStart={weekStart} selected={selected} {...passThroughProps} browsingDate={browsingDate} />
</div>
</div>
);
+5 -1
View File
@@ -25,7 +25,11 @@ const SkeletonAvatar: React.FC<AvatarProps> = ({ width, height }) => {
};
const SkeletonText: React.FC<SkeletonBaseProps> = ({ width, height }) => {
return <div className={classNames(`rounded-md bg-gray-200 w-${width} h-${height}`, classNames)} />;
return (
<div
className={classNames(`rounded-md bg-gray-200 dark:bg-gray-900 w-${width} h-${height}`, classNames)}
/>
);
};
const SkeletonButton: React.FC<SkeletonBaseProps> = ({ width, height }) => {