Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(web): anchor the event end-time picker on the start (#6210)

gbirmanbade187663ab
diff --git a/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx b/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx
index 83e190cce3..e18ddf7a85 100644
--- a/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx
+++ b/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx
@@ -7,64 +7,38 @@ import CheckIcon from '@phosphor/check.svg';
import { Calendar } from '@ui/components/Calendar';
import { Layer } from '@ui/components/Layer';
import { cn } from '@ui/utils/classname';
-import { createMemo, createSignal } from 'solid-js';
+import { createMemo, createSignal, Show } from 'solid-js';
import { formatLocalDate, parseLocalDate } from '../../utils/calendar-date';
+import {
+ DAY_TIME_OPTIONS,
+ type EventTimeOption,
+ resolveTimeOption,
+ selectedTimeOptionId,
+} from './event-time-options';
-interface EventTimeOption {
- value: string;
- label: string;
-}
-
-export const timeLabelFormatter = new Intl.DateTimeFormat(undefined, {
- hour: 'numeric',
- minute: '2-digit',
-});
export const dateLabelFormatter = new Intl.DateTimeFormat(undefined, {
day: 'numeric',
month: 'short',
year: 'numeric',
});
-/** Every quarter-hour in a day, with canonical values and localized labels. */
-const EVENT_TIME_OPTIONS: EventTimeOption[] = Array.from(
- { length: 24 * 4 },
- (_, index) => {
- const hour = Math.floor(index / 4);
- const minute = (index % 4) * 15;
- return {
- value: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,
- label: timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute)),
- };
- }
-);
-
-export function splitLocalDateTime(value: string) {
- const separator = value.indexOf('T');
- if (separator === -1) return { date: value, time: '' };
- return {
- date: value.slice(0, separator),
- time: value.slice(separator + 1, separator + 6),
- };
-}
-
-export function withLocalDate(value: string, date: string) {
- return `${date}T${splitLocalDateTime(value).time}`;
-}
-
-export function withLocalTime(value: string, time: string) {
- return `${splitLocalDateTime(value).date}T${time}`;
-}
-
function TimeOptionItem(props: CollectionNode<EventTimeOption>) {
return (
<Listbox.Item
item={props}
- class="group flex cursor-default items-center justify-between rounded-lg px-3 py-2 text-sm text-ink outline-none hover:bg-hover data-selected:bg-active data-highlighted:bg-hover"
+ class="group flex cursor-default items-center justify-between gap-3 rounded-lg px-3 py-2 text-sm text-ink outline-none hover:bg-hover data-selected:bg-active data-highlighted:bg-hover"
>
<Listbox.ItemLabel>{props.rawValue.label}</Listbox.ItemLabel>
- <Listbox.ItemIndicator class="text-accent">
- <CheckIcon class="size-3.5" />
- </Listbox.ItemIndicator>
+ <div class="flex shrink-0 items-center gap-2">
+ <Show when={props.rawValue.detail}>
+ {(detail) => (
+ <span class="text-xs text-ink-extra-muted">{detail()}</span>
+ )}
+ </Show>
+ <Listbox.ItemIndicator class="text-accent">
+ <CheckIcon class="size-3.5" />
+ </Listbox.ItemIndicator>
+ </div>
</Listbox.Item>
);
}
@@ -73,7 +47,11 @@ interface EventTimeInputProps {
id: string;
label: string;
value: string;
- onChange: (value: string) => void;
+ /** Selectable times; defaults to every quarter-hour in a day. */
+ options?: EventTimeOption[];
+ /** Highlighted option; defaults to `value` on the anchor day. */
+ selectedId?: string;
+ onChange: (option: EventTimeOption) => void;
onFocus?: () => void;
disabled?: boolean;
hideLabel?: boolean;
@@ -85,7 +63,10 @@ export function EventTimeInput(props: EventTimeInputProps) {
let control: HTMLDivElement | undefined;
let listbox: HTMLElement | undefined;
- const selectedTime = createMemo(() => [props.value]);
+ const options = createMemo(() => props.options ?? DAY_TIME_OPTIONS);
+ const selectedTime = createMemo(() => [
+ props.selectedId ?? selectedTimeOptionId(props.value),
+ ]);
const scrollToSelectedTime = () => {
requestAnimationFrame(() => {
listbox
@@ -99,9 +80,10 @@ export function EventTimeInput(props: EventTimeInputProps) {
if (nextOpen) scrollToSelectedTime();
};
const selectTime = (values: Set<string>) => {
- const value = values.values().next().value;
- if (typeof value !== 'string') return;
- if (value !== props.value) props.onChange(value);
+ const id = values.values().next().value;
+ if (typeof id !== 'string') return;
+ const option = options().find((candidate) => candidate.id === id);
+ if (option && id !== selectedTime()[0]) props.onChange(option);
setOpen(false);
};
@@ -140,7 +122,9 @@ export function EventTimeInput(props: EventTimeInputProps) {
onClick={() => setDropdownOpen(true)}
onInput={(event) => {
const value = event.currentTarget.value;
- if (value && value !== props.value) props.onChange(value);
+ if (value && value !== props.value) {
+ props.onChange(resolveTimeOption(options(), value));
+ }
}}
onKeyDown={(event) => {
if (event.key !== 'Escape' || !open()) return;
@@ -184,8 +168,8 @@ export function EventTimeInput(props: EventTimeInputProps) {
ref={(element) => {
listbox = element;
}}
- options={EVENT_TIME_OPTIONS}
- optionValue="value"
+ options={options()}
+ optionValue="id"
optionTextValue="label"
value={selectedTime()}
onChange={selectTime}
diff --git a/apps/web/src/features/calendar/components/composer/EventDateTimeRangeFields.tsx b/apps/web/src/features/calendar/components/composer/EventDateTimeRangeFields.tsx
index 0335297ee5..97e851f1e8 100644
--- a/apps/web/src/features/calendar/components/composer/EventDateTimeRangeFields.tsx
+++ b/apps/web/src/features/calendar/components/composer/EventDateTimeRangeFields.tsx
@@ -8,26 +8,32 @@ import { ToggleSwitch } from '@ui/components/ToggleSwitch';
import { cn } from '@ui/utils/classname';
import { createSignal, createUniqueId } from 'solid-js';
import { formatLocalDate, parseLocalDate } from '../../utils/calendar-date';
+import { dateLabelFormatter, EventTimeInput } from './EventDateTimeInputs';
import {
- dateLabelFormatter,
- EventTimeInput,
+ DAY_TIME_OPTIONS,
+ dayOffsetBetween,
+ type EventTimeOption,
+ endTimeOptions,
+ endValueFor,
+ formatTimeValue,
+ selectedTimeOptionId,
splitLocalDateTime,
- timeLabelFormatter,
+ withinEndTimeWindow,
withLocalDate,
withLocalTime,
-} from './EventDateTimeInputs';
-
-function formatTime(value: string) {
- const [hour, minute] = value.split(':').map(Number);
- if (hour === undefined || minute === undefined) return 'Time';
- return timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute));
-}
+} from './event-time-options';
interface EventDateTimeDropdownProps {
id: string;
label: 'Start' | 'End';
value: string;
allDay: boolean;
+ /**
+ * Range start the offered times are measured from, present on the end
+ * field: its options carry the duration they produce and roll into the
+ * following day past midnight.
+ */
+ anchorStart?: string;
onDateChange: (value: string) => void;
onTimeChange: (value: string) => void;
fieldDisabled?: boolean;
@@ -45,9 +51,34 @@ function EventDateTimeDropdown(props: EventDateTimeDropdownProps) {
const dateLabel = date
? dateLabelFormatter.format(date)
: `${props.label} date`;
- return props.allDay
- ? dateLabel
- : `${dateLabel} ${formatTime(parts().time)}`;
+ if (props.allDay) return dateLabel;
+ return `${dateLabel} ${formatTimeValue(parts().time) ?? 'Time'}`;
+ };
+ const anchor = () => {
+ const start = props.anchorStart;
+ if (!start || !withinEndTimeWindow(start, props.value)) return undefined;
+ return start;
+ };
+ const timeOptions = () => {
+ const start = anchor();
+ return start
+ ? endTimeOptions(splitLocalDateTime(start).time)
+ : DAY_TIME_OPTIONS;
+ };
+ const selectedTimeId = () => {
+ const start = anchor();
+ return selectedTimeOptionId(
+ parts().time,
+ start ? dayOffsetBetween(start, props.value) : 0
+ );
+ };
+ const changeTime = (option: EventTimeOption) => {
+ const start = anchor();
+ props.onTimeChange(
+ start
+ ? endValueFor(start, option)
+ : withLocalTime(props.value, option.value)
+ );
};
return (
@@ -124,7 +155,9 @@ function EventDateTimeDropdown(props: EventDateTimeDropdownProps) {
id={props.id}
label={`${props.label} time`}
value={parts().time}
- onChange={props.onTimeChange}
+ options={timeOptions()}
+ selectedId={selectedTimeId()}
+ onChange={changeTime}
disabled={props.fieldDisabled || props.allDay}
/>
</div>
@@ -167,9 +200,7 @@ export function EventDateTimeRangeFields(props: EventDateTimeRangeFieldsProps) {
props.allDay ? date : withLocalDate(props.start, date)
)
}
- onTimeChange={(time) =>
- props.onStartChange(withLocalTime(props.start, time))
- }
+ onTimeChange={props.onStartChange}
fieldDisabled={props.startDisabled}
invalid={props.invalid}
describedBy={props.describedBy}
@@ -187,14 +218,13 @@ export function EventDateTimeRangeFields(props: EventDateTimeRangeFieldsProps) {
label="End"
value={props.end}
allDay={props.allDay}
+ anchorStart={props.allDay ? undefined : props.start}
onDateChange={(date) =>
props.onEndChange(
props.allDay ? date : withLocalDate(props.end, date)
)
}
- onTimeChange={(time) =>
- props.onEndChange(withLocalTime(props.end, time))
- }
+ onTimeChange={props.onEndChange}
fieldDisabled={props.endDisabled}
invalid={props.invalid}
describedBy={props.describedBy}
diff --git a/apps/web/src/features/calendar/components/composer/event-time-options.test.ts b/apps/web/src/features/calendar/components/composer/event-time-options.test.ts
new file mode 100644
index 0000000000..e5e6fac426
--- /dev/null
+++ b/apps/web/src/features/calendar/components/composer/event-time-options.test.ts
@@ -0,0 +1,253 @@
+import { describe, expect, it } from 'vitest';
+import {
+ DAY_TIME_OPTIONS,
+ dayOffsetBetween,
+ endTimeOptions,
+ endValueFor,
+ formatEventDuration,
+ parseTimeValue,
+ resolveTimeOption,
+ selectedTimeOptionId,
+ splitLocalDateTime,
+ withinEndTimeWindow,
+} from './event-time-options';
+
+describe('DAY_TIME_OPTIONS', () => {
+ it('covers every quarter-hour of one day', () => {
+ expect(DAY_TIME_OPTIONS).toHaveLength(96);
+ expect(DAY_TIME_OPTIONS[0]?.value).toBe('00:00');
+ expect(DAY_TIME_OPTIONS.at(-1)?.value).toBe('23:45');
+ expect(DAY_TIME_OPTIONS.every((option) => option.dayOffset === 0)).toBe(
+ true
+ );
+ expect(
+ DAY_TIME_OPTIONS.every((option) => option.detail === undefined)
+ ).toBe(true);
+ });
+});
+
+describe('formatEventDuration', () => {
+ it('formats sub-hour durations in minutes', () => {
+ expect(formatEventDuration(15)).toBe('15min');
+ expect(formatEventDuration(45)).toBe('45min');
+ });
+
+ it('drops the minutes on whole hours', () => {
+ expect(formatEventDuration(60)).toBe('1h');
+ expect(formatEventDuration(180)).toBe('3h');
+ });
+
+ it('combines both units otherwise', () => {
+ expect(formatEventDuration(75)).toBe('1h 15min');
+ expect(formatEventDuration(1425)).toBe('23h 45min');
+ });
+});
+
+describe('endTimeOptions', () => {
+ it('spans 15 minutes to 23h45min after the start', () => {
+ const options = endTimeOptions('09:00');
+
+ expect(options).toHaveLength(95);
+ expect(options[0]).toMatchObject({
+ value: '09:15',
+ dayOffset: 0,
+ detail: '15min',
+ });
+ expect(options[3]).toMatchObject({ value: '10:00', detail: '1h' });
+ expect(options.at(-1)).toMatchObject({
+ value: '08:45',
+ dayOffset: 1,
+ detail: '23h 45min',
+ });
+ });
+
+ it('rolls past midnight onto the following day', () => {
+ const options = endTimeOptions('20:00');
+ const midnight = options.find((option) => option.value === '00:00');
+
+ expect(midnight).toMatchObject({ dayOffset: 1, detail: '4h' });
+ expect(options.filter((option) => option.dayOffset === 0)).toHaveLength(15);
+ });
+
+ it('never offers the start time itself, and never repeats one', () => {
+ const options = endTimeOptions('13:30');
+
+ expect(options.some((option) => option.value === '13:30')).toBe(false);
+ expect(new Set(options.map((option) => option.id)).size).toBe(
+ options.length
+ );
+ expect(new Set(options.map((option) => option.value)).size).toBe(
+ options.length
+ );
+ });
+
+ it('falls back to the plain day when the start is unusable', () => {
+ expect(endTimeOptions('')).toBe(DAY_TIME_OPTIONS);
+ expect(endTimeOptions('99:99')).toBe(DAY_TIME_OPTIONS);
+ });
+});
+
+describe('parseTimeValue', () => {
+ it('reads minutes past midnight, ignoring seconds', () => {
+ expect(parseTimeValue('00:00')).toBe(0);
+ expect(parseTimeValue('09:45')).toBe(585);
+ expect(parseTimeValue('23:45:00')).toBe(1425);
+ });
+
+ it('rejects values outside a clock', () => {
+ expect(parseTimeValue('')).toBeUndefined();
+ expect(parseTimeValue('24:00')).toBeUndefined();
+ expect(parseTimeValue('12:60')).toBeUndefined();
+ });
+});
+
+describe('resolveTimeOption', () => {
+ it('matches a typed time to the option it lands on', () => {
+ const options = endTimeOptions('20:00');
+
+ expect(resolveTimeOption(options, '09:00')).toMatchObject({
+ dayOffset: 1,
+ detail: '13h',
+ });
+ });
+
+ it('keeps an unlisted time on the anchor day', () => {
+ const options = endTimeOptions('20:00');
+
+ expect(resolveTimeOption(options, '20:07')).toMatchObject({
+ value: '20:07',
+ dayOffset: 0,
+ });
+ expect(resolveTimeOption(options, '20:07').detail).toBeUndefined();
+ });
+});
+
+describe('endValueFor', () => {
+ it('keeps the start date for same-day options', () => {
+ expect(
+ endValueFor('2026-03-10T09:00', { value: '10:30', dayOffset: 0 })
+ ).toBe('2026-03-10T10:30');
+ });
+
+ it('advances the date for options past midnight', () => {
+ expect(
+ endValueFor('2026-03-31T20:00', { value: '02:00', dayOffset: 1 })
+ ).toBe('2026-04-01T02:00');
+ });
+
+ it('pulls a multi-day end back onto the anchored day', () => {
+ expect(
+ endValueFor('2026-03-10T09:00', { value: '17:00', dayOffset: 0 })
+ ).toBe('2026-03-10T17:00');
+ });
+
+ it('rolls a hand-typed time that would precede the start', () => {
+ expect(
+ endValueFor('2026-03-10T20:00', { value: '09:07', dayOffset: 0 })
+ ).toBe('2026-03-11T09:07');
+ });
+
+ it('rolls a hand-typed time that equals the start', () => {
+ expect(
+ endValueFor('2026-03-10T20:00', { value: '20:00', dayOffset: 0 })
+ ).toBe('2026-03-11T20:00');
+ });
+});
+
+describe('an end that has fallen behind its start', () => {
+ const START = '2026-03-10T20:00';
+ const END = '2026-03-10T09:00';
+
+ it('still offers the durations measured from the start', () => {
+ expect(withinEndTimeWindow(START, END)).toBe(true);
+
+ const options = endTimeOptions(splitLocalDateTime(START).time);
+ expect(options[0]).toMatchObject({ value: '20:15', detail: '15min' });
+ expect(options.find((option) => option.value === '09:00')).toMatchObject({
+ dayOffset: 1,
+ detail: '13h',
+ });
+ });
+
+ it('highlights nothing, since no offered option describes it', () => {
+ const options = endTimeOptions(splitLocalDateTime(START).time);
+ const selected = selectedTimeOptionId(
+ splitLocalDateTime(END).time,
+ dayOffsetBetween(START, END)
+ );
+
+ expect(options.some((option) => option.id === selected)).toBe(false);
+ });
+
+ it('lands the next morning once a time is chosen or typed', () => {
+ const options = endTimeOptions(splitLocalDateTime(START).time);
+
+ expect(endValueFor(START, resolveTimeOption(options, '09:00'))).toBe(
+ '2026-03-11T09:00'
+ );
+ expect(endValueFor(START, resolveTimeOption(options, '09:07'))).toBe(
+ '2026-03-11T09:07'
+ );
+ });
+});
+
+describe('dayOffsetBetween', () => {
+ it('counts whole calendar days', () => {
+ expect(dayOffsetBetween('2026-03-10T09:00', '2026-03-10T23:45')).toBe(0);
+ expect(dayOffsetBetween('2026-03-10T09:00', '2026-03-11T00:15')).toBe(1);
+ expect(dayOffsetBetween('2026-03-10T09:00', '2026-03-09T23:45')).toBe(-1);
+ });
+
+ it('reads zero when either side is unusable', () => {
+ expect(dayOffsetBetween('', '2026-03-11T00:15')).toBe(0);
+ });
+});
+
+describe('selectedTimeOptionId', () => {
+ it('addresses the option a value currently holds', () => {
+ const options = endTimeOptions('20:00');
+ const id = selectedTimeOptionId('00:00', 1);
+
+ expect(options.find((option) => option.id === id)?.detail).toBe('4h');
+ });
+
+ it('matches nothing when the end sits outside the offered window', () => {
+ const options = endTimeOptions('20:00');
+ const id = selectedTimeOptionId('00:00', 3);
+
+ expect(options.some((option) => option.id === id)).toBe(false);
+ });
+});
+
+describe('withinEndTimeWindow', () => {
+ it('accepts spans up to 23h45min', () => {
+ expect(withinEndTimeWindow('2026-03-10T09:00', '2026-03-10T10:00')).toBe(
+ true
+ );
+ expect(withinEndTimeWindow('2026-03-10T20:00', '2026-03-11T02:00')).toBe(
+ true
+ );
+ expect(withinEndTimeWindow('2026-03-10T09:00', '2026-03-11T08:45')).toBe(
+ true
+ );
+ });
+
+ it('accepts an end that has fallen behind the start', () => {
+ expect(withinEndTimeWindow('2026-03-10T20:00', '2026-03-10T09:00')).toBe(
+ true
+ );
+ });
+
+ it('rejects longer spans, which keep their own end date', () => {
+ expect(withinEndTimeWindow('2026-03-10T09:00', '2026-03-11T09:00')).toBe(
+ false
+ );
+ expect(withinEndTimeWindow('2026-03-10T09:00', '2026-03-13T17:00')).toBe(
+ false
+ );
+ });
+
+ it('rejects unusable values', () => {
+ expect(withinEndTimeWindow('2026-03-10', '2026-03-11')).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/calendar/components/composer/event-time-options.ts b/apps/web/src/features/calendar/components/composer/event-time-options.ts
new file mode 100644
index 0000000000..13f980a0d3
--- /dev/null
+++ b/apps/web/src/features/calendar/components/composer/event-time-options.ts
@@ -0,0 +1,203 @@
+import { addDays, differenceInCalendarDays } from 'date-fns';
+import { minutesInDay, minutesInHour } from 'date-fns/constants';
+import { formatLocalDate, parseLocalDate } from '../../utils/calendar-date';
+
+/** Granularity of every event time picker. */
+const SLOT_MINUTES = 15;
+
+/**
+ * Longest event the end picker offers, matching Google Calendar: one slot
+ * short of a full day, so a same-start end time is never listed twice.
+ */
+const MAX_EVENT_MINUTES = minutesInDay - SLOT_MINUTES;
+
+const timeLabelFormatter = new Intl.DateTimeFormat(undefined, {
+ hour: 'numeric',
+ minute: '2-digit',
+});
+
+/** One selectable clock time in an event time picker. */
+export interface EventTimeOption {
+ /** Listbox key, distinguishing clock times that land on different days. */
+ id: string;
+ /** Canonical `HH:mm` value. */
+ value: string;
+ /** Localized clock label. */
+ label: string;
+ /** Days past the picker's anchor date this option lands on. */
+ dayOffset: number;
+ /** Muted trailing text, e.g. the duration the option produces. */
+ detail?: string;
+}
+
+function optionId(dayOffset: number, value: string) {
+ return `${dayOffset}|${value}`;
+}
+
+function timeValue(minutesOfDay: number) {
+ const hour = Math.floor(minutesOfDay / minutesInHour);
+ const minute = minutesOfDay % minutesInHour;
+ return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
+}
+
+/** Minutes past midnight of an `HH:mm` value, or `undefined` when unparsable. */
+export function parseTimeValue(value: string): number | undefined {
+ const match = /^(\d{1,2}):(\d{2})/.exec(value);
+ if (!match) return undefined;
+ const hour = Number(match[1]);
+ const minute = Number(match[2]);
+ if (hour > 23 || minute > 59) return undefined;
+ return hour * minutesInHour + minute;
+}
+
+/** Localized clock label for an `HH:mm` value. */
+export function formatTimeValue(value: string): string | undefined {
+ const minutesOfDay = parseTimeValue(value);
+ if (minutesOfDay === undefined) return undefined;
+ return timeLabelFormatter.format(
+ new Date(
+ 2000,
+ 0,
+ 1,
+ Math.floor(minutesOfDay / minutesInHour),
+ minutesOfDay % minutesInHour
+ )
+ );
+}
+
+/** `30min`, `1h`, `1h 15min` — Google's compact event duration. */
+export function formatEventDuration(minutes: number): string {
+ const hours = Math.floor(minutes / minutesInHour);
+ const remainder = minutes % minutesInHour;
+ if (hours === 0) return `${remainder}min`;
+ return remainder === 0 ? `${hours}h` : `${hours}h ${remainder}min`;
+}
+
+function timeOption(minutesOfDay: number, dayOffset: number, detail?: string) {
+ const value = timeValue(minutesOfDay);
+ return {
+ id: optionId(dayOffset, value),
+ value,
+ label: formatTimeValue(value) ?? value,
+ dayOffset,
+ ...(detail ? { detail } : {}),
+ };
+}
+
+/** Every quarter-hour in a day, used wherever no start anchors the choice. */
+export const DAY_TIME_OPTIONS: EventTimeOption[] = Array.from(
+ { length: minutesInDay / SLOT_MINUTES },
+ (_, index) => timeOption(index * SLOT_MINUTES, 0)
+);
+
+/**
+ * Quarter-hours from 15 minutes to 23h45min after `startTime`, each labelled
+ * with the duration it produces. Options past midnight carry the day offset
+ * they land on, so the end date follows the chosen time.
+ */
+export function endTimeOptions(startTime: string): EventTimeOption[] {
+ const startMinutes = parseTimeValue(startTime);
+ if (startMinutes === undefined) return DAY_TIME_OPTIONS;
+
+ const options: EventTimeOption[] = [];
+ for (
+ let duration = SLOT_MINUTES;
+ duration <= MAX_EVENT_MINUTES;
+ duration += SLOT_MINUTES
+ ) {
+ const total = startMinutes + duration;
+ options.push(
+ timeOption(
+ total % minutesInDay,
+ Math.floor(total / minutesInDay),
+ formatEventDuration(duration)
+ )
+ );
+ }
+ return options;
+}
+
+/** The option a picker highlights for the value it currently holds. */
+export function selectedTimeOptionId(value: string, dayOffset = 0) {
+ return optionId(dayOffset, value);
+}
+
+/** The option a typed clock time resolves to within `options`. */
+export function resolveTimeOption(
+ options: EventTimeOption[],
+ time: string
+): EventTimeOption {
+ return (
+ options.find((option) => option.value === time) ?? {
+ id: optionId(0, time),
+ value: time,
+ label: formatTimeValue(time) ?? time,
+ dayOffset: 0,
+ }
+ );
+}
+
+export function splitLocalDateTime(value: string) {
+ const separator = value.indexOf('T');
+ if (separator === -1) return { date: value, time: '' };
+ return {
+ date: value.slice(0, separator),
+ time: value.slice(separator + 1, separator + 6),
+ };
+}
+
+export function withLocalDate(value: string, date: string) {
+ return `${date}T${splitLocalDateTime(value).time}`;
+}
+
+export function withLocalTime(value: string, time: string) {
+ return `${splitLocalDateTime(value).date}T${time}`;
+}
+
+/** Whole days between two `datetime-local` values, counted by calendar date. */
+export function dayOffsetBetween(from: string, to: string) {
+ const fromDate = parseLocalDate(splitLocalDateTime(from).date);
+ const toDate = parseLocalDate(splitLocalDateTime(to).date);
+ if (!fromDate || !toDate) return 0;
+ return differenceInCalendarDays(toDate, fromDate);
+}
+
+/**
+ * Whether an end value is close enough to `start` to be described as a
+ * duration. Longer spans keep their own end date: their options are plain
+ * clock times, since no single day's list can reach them.
+ */
+export function withinEndTimeWindow(start: string, end: string) {
+ const startTime = parseTimeValue(splitLocalDateTime(start).time);
+ const endTime = parseTimeValue(splitLocalDateTime(end).time);
+ if (startTime === undefined || endTime === undefined) return false;
+ const elapsed =
+ dayOffsetBetween(start, end) * minutesInDay + endTime - startTime;
+ return elapsed <= MAX_EVENT_MINUTES;
+}
+
+/**
+ * The end value an end-time option resolves to, relative to `start`. A clock
+ * time that would land at or before the start rolls into the following day:
+ * the picker lists no such option, so this only ever describes a time typed
+ * by hand, and an end before its own start is never what the typing meant.
+ */
+export function endValueFor(
+ start: string,
+ option: Pick<EventTimeOption, 'value' | 'dayOffset'>
+) {
+ const { date, time } = splitLocalDateTime(start);
+ const startDate = parseLocalDate(date);
+ if (!startDate) return withLocalTime(start, option.value);
+
+ const startMinutes = parseTimeValue(time);
+ const optionMinutes = parseTimeValue(option.value);
+ const rollsOver =
+ option.dayOffset === 0 &&
+ startMinutes !== undefined &&
+ optionMinutes !== undefined &&
+ optionMinutes <= startMinutes;
+
+ const dayOffset = rollsOver ? 1 : option.dayOffset;
+ return `${formatLocalDate(addDays(startDate, dayOffset))}T${option.value}`;
+}