Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🐛 Pick week calendar times as floating wall-clock times across DST (#3615)
Luke Vellabc650984b766
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 3cc0e2479..7ad84fde5 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -1205,6 +1205,7 @@"webhookTestEventRespondedWith": "Endpoint responded {status}","webhookTestEventSending": "Sending test event","webhookUrl": "URL",+ "weekCalendarSkippedTime": "That time is skipped when the clocks change in {timeZone}","weekView": "Week view","whiteLabelAddon": "White Label Add-on","whiteLabelAddonDescription": "This add-on allows you to brand Rallly with your own logo and colors.",diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/poll-options-form.tsx b/apps/web/src/features/poll/components/forms/poll-options-form/poll-options-form.tsxindex f2d735bea..4756ecd2e 100644--- a/apps/web/src/features/poll/components/forms/poll-options-form/poll-options-form.tsx+++ b/apps/web/src/features/poll/components/forms/poll-options-form/poll-options-form.tsx@@ -64,6 +64,7 @@ const PollOptionsForm = ({const watchOptions = watch("options", []);const watchDuration = watch("duration");const watchTimeZone = watch("timeZone");+ const watchLockTimeZone = watch("lockTimeZone");const dateOrTimeRangeDialog = useDialog();@@ -199,6 +200,11 @@ const PollOptionsForm = ({}}}duration={watchDuration}+ timeZone={+ watchLockTimeZone+ ? undefined+ : watchTimeZone || defaultTimeZone+ }onChangeDuration={(duration) => {setValue("duration", duration);}}diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/types.ts b/apps/web/src/features/poll/components/forms/poll-options-form/types.tsindex 8f8b7892c..53c1426a5 100644--- a/apps/web/src/features/poll/components/forms/poll-options-form/types.ts+++ b/apps/web/src/features/poll/components/forms/poll-options-form/types.ts@@ -20,4 +20,6 @@ export interface DateTimePickerProps {duration: number;onChangeDuration: (duration: number) => void;scrollToTime?: Date;+ /** The poll's zone, when its times convert; undefined for floating polls. */+ timeZone?: string;}diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.test.ts b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.test.tsindex 49a419928..a50fcf629 100644--- a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.test.ts+++ b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.test.ts@@ -1,15 +1,19 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it } from "vitest";import type { DateTimeOption } from "./types";import {DURATION_CAP_MINUTES,durationMinutes,eventId,+ floatingToDate,+ floatingToInstant,+ instantToFloating,isDuplicate,optionsToEvents,+ slotExistsIn,slotToTimeOption,} from "./week-calendar-utils";-const d = (s: string) => new Date(s);+const d = floatingToDate;describe("eventId", () => {it("is stable and distinct per option identity", () => {@@ -25,42 +29,83 @@ describe("eventId", () => {});});-describe("optionsToEvents", () => {- it("maps a timeSlot to a timed event", () => {- const events = optionsToEvents([- {- type: "timeSlot",- start: "2026-07-21T14:00:00",- end: "2026-07-21T15:00:00",- },- ]);- expect(events).toHaveLength(1);- expect(events[0].allDay).toBeFalsy();- expect(events[0].start).toEqual(d("2026-07-21T14:00:00"));- expect(events[0].end).toEqual(d("2026-07-21T15:00:00"));+// The picker must not depend on the browser's zone. Each case runs with the+// process in a DST zone and in one without, across both 2026/27 US changes.+const originalTimeZone = process.env.TZ;+afterEach(() => {+ process.env.TZ = originalTimeZone;+});++describe.each([+ ["America/Chicago", 360],+ ["Asia/Kathmandu", -345],+])("with the browser in %s", (browserTimeZone, novemberOffset) => {+ const useBrowserTimeZone = () => {+ process.env.TZ = browserTimeZone;+ expect(new Date(2026, 10, 3).getTimezoneOffset()).toBe(novemberOffset);+ };++ it.each([+ "2026-11-01T10:00:00",+ "2026-11-03T10:00:00",+ "2027-03-14T10:00:00",+ ])("round trips the 10:00 slot on %s unchanged", (start) => {+ useBrowserTimeZone();+ const end = start.replace("T10:", "T11:");+ const [event] = optionsToEvents([{ type: "timeSlot", start, end }]);+ expect(event.start.toISOString()).toBe(`${start}.000Z`);+ expect(slotToTimeOption(event.start, event.end)).toEqual({+ type: "timeSlot",+ start,+ end,+ });+ expect(durationMinutes(event.start, event.end)).toBe(60);});- it("maps a date option to a local, next-day-exclusive all-day event", () => {- const events = optionsToEvents([{ type: "date", date: "2026-07-21" }]);- expect(events[0].allDay).toBe(true);- // Local midnight, not UTC (new Date("2026-07-21") would be UTC midnight).- expect(events[0].start).toEqual(d("2026-07-21T00:00:00"));- // Exclusive end at the next local day boundary, never zero-length.- expect(events[0].end).toEqual(d("2026-07-22T00:00:00"));+ it("maps a date option to a 24 hour all-day event", () => {+ useBrowserTimeZone();+ const [event] = optionsToEvents([{ type: "date", date: "2026-11-01" }]);+ expect(event.allDay).toBe(true);+ expect(event.start).toEqual(d("2026-11-01T00:00:00"));+ expect(event.end).toEqual(d("2026-11-02T00:00:00"));});});-describe("slotToTimeOption", () => {- it("round-trips through naive-local strings", () => {- const opt = slotToTimeOption(- d("2026-07-21T14:00:00"),- d("2026-07-21T15:30:00"),- );- expect(opt).toEqual({- type: "timeSlot",- start: "2026-07-21T14:00:00",- end: "2026-07-21T15:30:00",- });+describe("instantToFloating / floatingToInstant", () => {+ it("puts the viewer's clock on the floating grid and back", () => {+ const instant = new Date("2026-11-03T16:00:00Z");+ const floating = instantToFloating(instant, "America/Chicago");+ expect(floating).toEqual(d("2026-11-03T10:00:00"));+ expect(floatingToInstant(floating, "America/Chicago")).toEqual(instant);+ });+});++describe("slotExistsIn", () => {+ const springForward = {+ type: "timeSlot",+ start: "2027-03-14T02:00:00",+ end: "2027-03-14T03:00:00",+ } as const;++ it("rejects a slot that starts in a skipped hour of the poll's zone", () => {+ expect(slotExistsIn(springForward, "America/Chicago")).toBe(false);+ });++ it("accepts the same slot in a poll zone without that change", () => {+ expect(slotExistsIn(springForward, "Asia/Kathmandu")).toBe(true);+ });++ it("accepts a slot in the repeated fall back hour", () => {+ expect(+ slotExistsIn(+ {+ type: "timeSlot",+ start: "2026-11-01T01:00:00",+ end: "2026-11-01T02:00:00",+ },+ "America/Chicago",+ ),+ ).toBe(true);});});diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.ts b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.tsindex 01b29611a..2f4a36302 100644--- a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.ts+++ b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.ts@@ -1,10 +1,38 @@import type { CalendarEvent } from "@rallly/ui/event-calendar";-import { dayjs } from "@/lib/dayjs";+import {+ instantToWallTime,+ wallTimeExists,+ wallTimeToInstant,+} from "@/lib/datetime/wall-time";import type { DateTimeOption, TimeOption } from "./types";-import { formatDateWithoutTz } from "./utils";export const DURATION_CAP_MINUTES = 60 * 24;+/**+ * Option strings are floating wall-clock times with no zone of their own; the+ * poll's zone is applied once, on save. The picker lays them out in UTC, which+ * has no DST, and reads and writes every string as if it were UTC, so the row+ * that says 10:00 is always the string 10:00 whatever the browser's zone.+ */+export const FLOATING_TIME_ZONE = "UTC";++export const floatingToDate = (wallTime: string) => new Date(`${wallTime}Z`);++export const dateToFloating = (date: Date) => date.toISOString().slice(0, 19);++/** The instant `date` expressed on the floating grid as clocks read it in `timeZone`. */+export const instantToFloating = (date: Date, timeZone: string) =>+ floatingToDate(instantToWallTime(date, timeZone));++/** The instant clocks in `timeZone` read the floating `date`. */+export const floatingToInstant = (date: Date, timeZone: string) =>+ wallTimeToInstant(dateToFloating(date), timeZone);++/** Whether both ends of the slot are times clocks in `timeZone` actually read. */+export const slotExistsIn = (option: TimeOption, timeZone: string) =>+ wallTimeExists(option.start, timeZone) &&+ wallTimeExists(option.end, timeZone);+export function eventId(option: DateTimeOption): string {return option.type === "date"? `date:${option.date}`@@ -14,23 +42,21 @@ export function eventId(option: DateTimeOption): string {export function optionsToEvents(options: DateTimeOption[]): CalendarEvent[] {return options.map((option) => {if (option.type === "date") {- // Parse the date-only value as LOCAL midnight (new Date("YYYY-MM-DD")- // would parse as UTC), and give the all-day event an exclusive end at the- // next local day boundary rather than a zero-length span.- const start = dayjs(option.date).startOf("day");+ // An exclusive end at the next floating midnight, never zero-length.+ const start = floatingToDate(`${option.date}T00:00:00`);return {id: eventId(option),title: "",- start: start.toDate(),- end: start.add(1, "day").toDate(),+ start,+ end: new Date(start.getTime() + DURATION_CAP_MINUTES * 60_000),allDay: true,};}return {id: eventId(option),title: "",- start: new Date(option.start),- end: new Date(option.end),+ start: floatingToDate(option.start),+ end: floatingToDate(option.end),};});}@@ -38,8 +64,8 @@ export function optionsToEvents(options: DateTimeOption[]): CalendarEvent[] {export function slotToTimeOption(start: Date, end: Date): TimeOption {return {type: "timeSlot",- start: formatDateWithoutTz(start),- end: formatDateWithoutTz(end),+ start: dateToFloating(start),+ end: dateToFloating(end),};}@@ -56,5 +82,5 @@ export function isDuplicate(}export function durationMinutes(start: Date, end: Date): number {- return dayjs(end).diff(start, "minutes");+ return Math.round((end.getTime() - start.getTime()) / 60_000);}diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar.tsx b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar.tsxindex 3e179c6e9..98bb43e2d 100644--- a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar.tsx+++ b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar.tsx@@ -16,8 +16,10 @@ import {EventCalendarWeekView,useEventCalendarNavigation,} from "@rallly/ui/event-calendar";+import { toast } from "@rallly/ui/sonner";import React from "react";import { createBreakpoint } from "react-use";+import { useTranslation } from "@/i18n/client";import { useDateTime, useDateTimeConfig } from "@/lib/datetime/client";import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";@@ -26,8 +28,13 @@ import type { DateTimePickerProps, TimeOption } from "./types";import {DURATION_CAP_MINUTES,durationMinutes,+ FLOATING_TIME_ZONE,+ floatingToDate,+ floatingToInstant,+ instantToFloating,isDuplicate,optionsToEvents,+ slotExistsIn,slotToTimeOption,} from "./week-calendar-utils";@@ -40,13 +47,6 @@ const WeekViewNoAllDay = () => <EventCalendarWeekView showAllDay={false} />;const DayViewNoAllDay = () => <EventCalendarDayView showAllDay={false} />;const VIEW_COMPONENTS = { week: WeekViewNoAllDay, day: DayViewNoAllDay };-// ReUI's grid needs a fixed IANA zone to lay out days/hours. The poll form-// stores naive wall-clock strings with no zone of their own, so this zone is-// used purely as a rendering frame — every option <-> event conversion still-// goes through the Task 4 helpers (formatDateWithoutTz), never a real zone-// conversion of stored values.-const RENDER_TIME_ZONE = getBrowserTimeZone();-function CalendarToolbar() {const { title, next, prev, today } = useEventCalendarNavigation();return (@@ -66,10 +66,42 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({onChange,duration = 60,onChangeDuration,+ timeZone: pollTimeZone,}) => {- const { weekStart } = useDateTimeConfig();+ const { t } = useTranslation();+ const { weekStart, timeZone } = useDateTimeConfig();+ const viewerTimeZone = timeZone ?? getBrowserTimeZone();const { formatDateTime, formatDateTimeRange } = useDateTime();+ // The grid runs on floating time; today, the now line and the shared+ // navigation date come from the viewer's own clock.+ const getNow = React.useCallback(+ () => instantToFloating(new Date(), viewerTimeZone),+ [viewerTimeZone],+ );+ const floatingDate = React.useMemo(+ () => (date ? instantToFloating(date, viewerTimeZone) : undefined),+ [date, viewerTimeZone],+ );+ const handleNavigate = (next: Date) =>+ onNavigate(floatingToInstant(next, viewerTimeZone));++ // A slot whose start or end is skipped when the poll's clocks spring+ // forward would silently shift on save, so it can't be picked at all.+ const isAvailable = (option: TimeOption) =>+ !pollTimeZone || slotExistsIn(option, pollTimeZone);+ const isAvailableSlot = (start: Date, end: Date) =>+ isAvailable(slotToTimeOption(start, end));+ const rejectSkippedTime = () => {+ toast.error(+ t("weekCalendarSkippedTime", {+ defaultValue:+ "That time is skipped when the clocks change in {timeZone}",+ timeZone: pollTimeZone,+ }),+ );+ };+const apiRef = React.useRef<EventCalendarApi | null>(null);const hasScrolledRef = React.useRef(false);@@ -80,7 +112,7 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({// The form works in naive local times; format in the render-frame zone.const formatTime = React.useCallback((time: Date) =>- formatDateTime(time, "time", { timeZone: RENDER_TIME_ZONE }),+ formatDateTime(time, "time", { timeZone: FLOATING_TIME_ZONE }),[formatDateTime],);@@ -96,14 +128,14 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({ctx.activeRange.end,"date",{- timeZone: RENDER_TIME_ZONE,+ timeZone: FLOATING_TIME_ZONE,},),formatEventTime: (start: Date, _end: Date, allDay: boolean) =>allDay ? "" : formatTime(start),formatDayRange: (range: { start: Date; end: Date }) =>formatDateTimeRange(range.start, range.end, "monthDay", {- timeZone: RENDER_TIME_ZONE,+ timeZone: FLOATING_TIME_ZONE,}),},}),@@ -129,7 +161,7 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({undefined,);if (earliestSlot) {- apiRef.current?.scrollToTime(new Date(earliestSlot.start));+ apiRef.current?.scrollToTime(floatingToDate(earliestSlot.start));}}, []);@@ -140,6 +172,10 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({return;}const candidate = slotToTimeOption(slot.start, slot.end);+ if (!isAvailable(candidate)) {+ rejectSkippedTime();+ return;+ }const diff = durationMinutes(slot.start, slot.end);if (diff < DURATION_CAP_MINUTES) {onChangeDuration(diff);@@ -156,6 +192,10 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({const start = slot.date;const end = new Date(start.getTime() + (duration || 60) * 60 * 1000);const candidate = slotToTimeOption(start, end);+ if (!isAvailable(candidate)) {+ rejectSkippedTime();+ return;+ }if (!isDuplicate(options, candidate)) {onChange([...options, candidate]);}@@ -186,6 +226,9 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({update.occurrence.end,);const newOption = slotToTimeOption(update.start, update.end);+ if (!isAvailable(newOption)) {+ return false;+ }const duplicatesAnother = options.some((option) =>@@ -224,11 +267,16 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({className="absolute inset-0"apiRef={apiRef}events={events}- date={date}- onDateChange={onNavigate}+ date={floatingDate}+ onDateChange={handleNavigate}defaultView={defaultView}views={["week", "day"]}- timeZone={RENDER_TIME_ZONE}+ timeZone={FLOATING_TIME_ZONE}+ getNow={getNow}+ canSelectSlot={(slot) =>+ slot.allDay || isAvailableSlot(slot.start, slot.end)+ }+ canDropEvent={(update) => isAvailableSlot(update.start, update.end)}weekStartsOn={weekStart as 0 | 1 | 2 | 3 | 4 | 5 | 6}slotDuration={15}snapDuration={30}@@ -256,7 +304,7 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({<div><div>{formatDateTimeRange(start, end, "time", {- timeZone: RENDER_TIME_ZONE,+ timeZone: FLOATING_TIME_ZONE,})}</div></div>diff --git a/apps/web/src/lib/datetime/wall-time.test.ts b/apps/web/src/lib/datetime/wall-time.test.tsindex 0818b39fa..4e04a3b83 100644--- a/apps/web/src/lib/datetime/wall-time.test.ts+++ b/apps/web/src/lib/datetime/wall-time.test.ts@@ -3,6 +3,7 @@ import {addMinutesToWallTime,instantToWallTime,wallTimeDiffInMinutes,+ wallTimeExists,wallTimeToInstant,} from "./wall-time";@@ -123,3 +124,24 @@ describe("addMinutesToWallTime", () => {);});});++describe("wallTimeExists", () => {+ it("rejects a time skipped by spring forward", () => {+ expect(wallTimeExists("2027-03-14T02:30:00", "America/Chicago")).toBe(+ false,+ );+ expect(wallTimeExists("2027-03-14T03:00:00", "America/Chicago")).toBe(true);+ });++ it("accepts a time repeated by fall back", () => {+ expect(wallTimeExists("2026-11-01T01:30:00", "America/Chicago")).toBe(true);+ });++ it("accepts every time in a zone without DST", () => {+ expect(wallTimeExists("2027-03-14T02:30:00", "Asia/Kathmandu")).toBe(true);+ });++ it("rejects unparseable input", () => {+ expect(wallTimeExists("nope", "UTC")).toBe(false);+ });+});diff --git a/apps/web/src/lib/datetime/wall-time.ts b/apps/web/src/lib/datetime/wall-time.tsindex 3b24748e8..aaaa6f991 100644--- a/apps/web/src/lib/datetime/wall-time.ts+++ b/apps/web/src/lib/datetime/wall-time.ts@@ -115,3 +115,15 @@ export function addMinutesToWallTime(wallTime: string, minutes: number) {.toISOString().slice(0, 19);}++/**+ * Whether clocks in `timeZone` ever read `wallTime`. False for a time skipped+ * by a forward transition (02:30 on a spring-forward day).+ */+export function wallTimeExists(wallTime: string, timeZone: string) {+ const instant = wallTimeToInstant(wallTime, timeZone);+ return (+ !Number.isNaN(instant.getTime()) &&+ wallTimeDiffInMinutes(wallTime, instantToWallTime(instant, timeZone)) === 0+ );+}diff --git a/packages/ui/src/event-calendar/event-calendar-agenda-view.tsx b/packages/ui/src/event-calendar/event-calendar-agenda-view.tsxindex 942135d70..c357ef105 100644--- a/packages/ui/src/event-calendar/event-calendar-agenda-view.tsx+++ b/packages/ui/src/event-calendar/event-calendar-agenda-view.tsx@@ -78,7 +78,7 @@ function EventCalendarAgendaView({const isToday = (day: Date) =>getDayKey(day, settings.timeZone) ===- getDayKey(new Date(), settings.timeZone);+ getDayKey(settings.getNow(), settings.timeZone);const native = viewConfig.scrollbars === "native";diff --git a/packages/ui/src/event-calendar/event-calendar-month-view.tsx b/packages/ui/src/event-calendar/event-calendar-month-view.tsxindex cbe7b0a49..8e2f59470 100644--- a/packages/ui/src/event-calendar/event-calendar-month-view.tsx+++ b/packages/ui/src/event-calendar/event-calendar-month-view.tsx@@ -203,7 +203,7 @@ function EventCalendarMonthView({view: "month",isToday:getDayKey(day, settings.timeZone) ===- getDayKey(new Date(), settings.timeZone),+ getDayKey(settings.getNow(), settings.timeZone),}) ?? (<><span className="@max-[36rem]:hidden">diff --git a/packages/ui/src/event-calendar/event-calendar-nav.tsx b/packages/ui/src/event-calendar/event-calendar-nav.tsxindex 27271825a..3e0cf8bd3 100644--- a/packages/ui/src/event-calendar/event-calendar-nav.tsx+++ b/packages/ui/src/event-calendar/event-calendar-nav.tsx@@ -131,7 +131,7 @@ function EventCalendarNavToday({// display-zone "today", like every other today derivation in the calendar// (a system-zone new Date() can name a different day than Today opens)const defaultTooltip = format(- toZoned(new Date(), settings.timeZone),+ toZoned(settings.getNow(), settings.timeZone),settings.i18n.formats.dayTitle,{ locale: settings.locale },);diff --git a/packages/ui/src/event-calendar/event-calendar-now.test.tsx b/packages/ui/src/event-calendar/event-calendar-now.test.tsxnew file mode 100644index 000000000..d6a18627d--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-now.test.tsx@@ -0,0 +1,49 @@+import { render } from "@testing-library/react";+import { beforeAll, describe, expect, it } from "vitest";++import {+ EventCalendar,+ EventCalendarContent,+ EventCalendarWeekView,+} from "./event-calendar";++// jsdom has no layout APIs; the grid only needs them to exist.+beforeAll(() => {+ Element.prototype.scrollTo ??= () => {};+ Element.prototype.getAnimations ??= () => [];+ globalThis.ResizeObserver ??= class {+ observe() {}+ unobserve() {}+ disconnect() {}+ };+});++const todayColumn = (getNow?: () => Date) => {+ const { container } = render(+ <EventCalendar+ events={[]}+ date={new Date("2026-11-04T12:00:00Z")}+ defaultView="week"+ views={["week"]}+ timeZone="UTC"+ getNow={getNow}+ >+ <EventCalendarContent components={{ week: EventCalendarWeekView }} />+ </EventCalendar>,+ );+ const column = container.querySelector(+ '[data-slot="event-calendar-day-column"][data-today]',+ );+ return column ? new Date(Number(column.getAttribute("data-ec-day"))) : null;+};++describe("getNow", () => {+ it("decides which day is today", () => {+ expect(todayColumn(() => new Date("2026-11-03T23:30:00Z"))).toEqual(+ new Date("2026-11-03T00:00:00Z"),+ );+ expect(todayColumn(() => new Date("2026-11-05T00:30:00Z"))).toEqual(+ new Date("2026-11-05T00:00:00Z"),+ );+ });+});diff --git a/packages/ui/src/event-calendar/event-calendar-time-grid.tsx b/packages/ui/src/event-calendar/event-calendar-time-grid.tsxindex c1dadad07..2248a7ad4 100644--- a/packages/ui/src/event-calendar/event-calendar-time-grid.tsx+++ b/packages/ui/src/event-calendar/event-calendar-time-grid.tsx@@ -45,10 +45,12 @@ import type {} from "./event-calendar-types";/** Current time, refreshed on an interval and on tab focus. */-function useNow(intervalMs = 30_000): Date {- const [now, setNow] = useState(() => new Date());+function useNow(getNow: () => Date, intervalMs = 30_000): Date {+ const [now, setNow] = useState(getNow);useEffect(() => {- const tick = () => setNow(new Date());+ const tick = () => setNow(getNow());+ // A new clock (e.g. the viewer's zone changed) applies immediately.+ tick();const id = setInterval(tick, intervalMs);document.addEventListener("visibilitychange", tick);window.addEventListener("focus", tick);@@ -57,7 +59,7 @@ function useNow(intervalMs = 30_000): Date {document.removeEventListener("visibilitychange", tick);window.removeEventListener("focus", tick);};- }, [intervalMs]);+ }, [getNow, intervalMs]);return now;}@@ -1186,7 +1188,7 @@ function EventCalendarNowIndicator({}): ReactNode {const settings = useEventCalendarSettings();const viewConfig = useEventCalendarViewConfig();- const now = useNow(viewConfig.nowIndicatorInterval);+ const now = useNow(settings.getNow, viewConfig.nowIndicatorInterval);const timeZone = settings.timeZone;const todayKey = getDayKey(now, timeZone);diff --git a/packages/ui/src/event-calendar/event-calendar.tsx b/packages/ui/src/event-calendar/event-calendar.tsxindex 85c5a217a..a08cc9e13 100644--- a/packages/ui/src/event-calendar/event-calendar.tsx+++ b/packages/ui/src/event-calendar/event-calendar.tsx@@ -134,6 +134,12 @@ interface UseEventCalendarStateOptions<TData = unknown>loading?: boolean;views?: CalendarView[];timeZone?: string;+ /**+ * The instant the calendar treats as now, for today and the now line.+ * A calendar showing floating times in a fixed frame passes the viewer's+ * wall clock expressed in that frame. @default () => new Date()+ */+ getNow?: () => Date;locale?: Locale;weekStartsOn?: WeekStartsOn;dayStartHour?: number;@@ -182,6 +188,7 @@ interface EventCalendarActivationConfig {interface EventCalendarSettings<TData = unknown>extends EventCalendarCallbacks<TData> {timeZone: string;+ getNow: () => Date;locale?: Locale;weekStartsOn: WeekStartsOn;views: CalendarView[];@@ -296,6 +303,7 @@ function resolveSettings<TData>(...rest,timeZone:options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,+ getNow: options.getNow ?? systemNow,locale: options.locale,weekStartsOn: options.weekStartsOn ?? 0,// the resource view only makes sense with resources configured@@ -319,6 +327,9 @@ function resolveSettings<TData>(};}+// Stable, so an unset getNow never reads as a changed setting.+const systemNow = () => new Date();+const warned = new Set<string>();function warnOnce(key: string, message: string) {if (process.env.NODE_ENV !== "production" && !warned.has(key)) {@@ -355,7 +366,7 @@ function createEventCalendarStore<TData>(const internal = {view: resolveView(initial.defaultView ?? "month"),- date: initial.defaultDate ?? new Date(),+ date: initial.defaultDate ?? settings.getNow(),dayCount: initial.defaultDayCount ?? 3,events: initial.defaultEvents ?? [],selection: initial.defaultSelection ?? EMPTY_SELECTION,@@ -568,7 +579,7 @@ function createEventCalendarStore<TData>();},today() {- setField("date", new Date());+ setField("date", settings.getNow());},goTo(date) {setField("date", date);@@ -759,6 +770,7 @@ function createEventCalendarStore<TData>(] as const;const SETTINGS_KEYS = ["timeZone",+ "getNow","locale","weekStartsOn","views",@@ -932,7 +944,7 @@ function useEventCalendarNavigation(): {},);useEventCalendarSettingsVersion(instance);- const now = new Date();+ const now = settings.getNow();return {date: slice.date,title: settings.i18n.functions.formatTitle(slice.view, {@@ -1038,7 +1050,7 @@ function useEventCalendarDay<TData = unknown>(const dayStart = zonedStartOfDay(day, timeZone);return {segments: bucket,- isToday: getDayKey(new Date(), timeZone) === dayKey,+ isToday: getDayKey(instance.settings.getNow(), timeZone) === dayKey,isOutside: dayStart < activeRange.start || dayStart >= activeRange.end,};}@@ -1563,6 +1575,7 @@ const OPTION_KEYS: Array<keyof UseEventCalendarStateOptions> = ["loading","views","timeZone",+ "getNow","locale","weekStartsOn","dayStartHour",