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.

refactor(calendar): reorganize, clean, and split files (#5713)

dev-rb1bbe49deecb7
diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsx
index ffaca07f1c..719c71c0db 100644
--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx
+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx
@@ -2,7 +2,7 @@ import { GO_TO_COMMAND_SCOPE, GO_TO_LEADER_KEY } from '@app/constants/hotkeys';
import { LIST_VIEW_PATHS, type ListView } from '@app/constants/list-views';
import { useActivityFeedFlag } from '@app/features/activity/use-activity-feed-flag';
import { SidebarActiveCallWidget } from '@app/features/block-call/sidebar/active-call-widget';
-import { useCalendarUiFlag } from '@app/features/calendar/use-calendar-ui-flag';
+import { useCalendarUiFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';
import { ChannelsRecentWidget } from '@app/features/channel/sidebar/channels-recent-widget';
import { CommandState } from '@app/features/command';
import { SidebarCreateMenu } from '@app/features/command/sidebar/sidebar-create-menu';
diff --git a/apps/web/src/components/app/mobile/MobileViewsRow.tsx b/apps/web/src/components/app/mobile/MobileViewsRow.tsx
index 57f44e9ac5..03d8f18a67 100644
--- a/apps/web/src/components/app/mobile/MobileViewsRow.tsx
+++ b/apps/web/src/components/app/mobile/MobileViewsRow.tsx
@@ -1,4 +1,4 @@
-import { useCalendarUiFlag } from '@app/features/calendar/use-calendar-ui-flag';
+import { useCalendarUiFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';
import { SearchState } from '@app/features/command/mobile/mobileSearchState';
import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
import IconGear from '@icon/macro-gear.svg';
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 74f91d3004..004ab9c3b3 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -1,7 +1,6 @@
import { useActivityFeedFlag } from '@app/features/activity/use-activity-feed-flag';
-import { EventComposer } from '@app/features/calendar/events/EventComposer';
-import type { EventEditorInitialValues } from '@app/features/calendar/events/EventEditorForm';
-import type { CalendarEvent } from '@app/features/calendar/events/types';
+import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
+import type { CalendarEvent } from '@app/features/calendar/types';
import { GettingStarted } from '@app/features/getting-started';
import { Home } from '@app/features/home';
import { queryStateFrom } from '@app/features/next-soup/filters/filter-store';
@@ -15,6 +14,7 @@ import { SettingsPanelComponentWrapper } from '@app/features/settings/Settings';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { usePosthog } from '@app/lib/analytics/posthog';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { EventComposerSplit } from '@block-calendar/components/EventComposerSplit';
import { ChannelCompose } from '@block-channel/component/Compose';
import { EmailCompose } from '@block-email/component/compose/Compose';
import { ComposeSkill } from '@block-md/component/ComposeSkill';
@@ -522,7 +522,7 @@ registerComponent('task-compose', (params) => {
registerComponent('calendar-event-compose', (params) => {
usePageViewTracking('calendar-event-compose');
return (
- <EventComposer
+ <EventComposerSplit
event={params?.event as CalendarEvent | undefined}
initialValues={
params?.initialValues as EventEditorInitialValues | undefined
diff --git a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx b/apps/web/src/features/auth/CalendarPermissionPrompt.tsx
index 56aa2316c7..e1d9f149fa 100644
--- a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx
+++ b/apps/web/src/features/auth/CalendarPermissionPrompt.tsx
@@ -1,7 +1,7 @@
import {
useCalendarPromptAllowed,
useCalendarUiFlag,
-} from '@app/features/calendar/use-calendar-ui-flag';
+} from '@app/features/calendar/hooks/use-calendar-ui-flag';
import { useKeyedPersistentToasts } from '@core/component/Toast/useKeyedPersistentToasts';
import { useAddInboxFlow } from '@core/email-link';
import { useEmailLinksQuery } from '@queries/email/link';
diff --git a/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx b/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx
index a4aa385fc2..efafe33e1f 100644
--- a/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx
+++ b/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx
@@ -1,6 +1,6 @@
-import { isCalendarRangeSupported } from '@app/features/calendar/calendar-supported-range';
-import { CalendarView } from '@app/features/calendar/calendar-view';
-import { useCalendarUiFlag } from '@app/features/calendar/use-calendar-ui-flag';
+import { CalendarViewContextProvider } from '@app/features/calendar/components/CalendarViewContext';
+import { useCalendarUiFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';
+import { isCalendarRangeSupported } from '@app/features/calendar/utils/calendar-supported-range';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { usePosthog } from '@app/lib/analytics/posthog';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
@@ -10,8 +10,10 @@ import { createMethodRegistration } from '@core/orchestrator';
import { blockHandleSignal } from '@core/signal/load';
import { useCalendarOccurrencesQuery } from '@queries/calendar/occurrences';
import { createMemo, createSignal, onMount, Show } from 'solid-js';
+import { CalendarFocusContextProvider } from './calendar-focus-target';
import { isCalendarBlockRange } from './calendar-range';
import { resolveCalendarBlockTarget } from './calendar-target';
+import { Workspace } from './components/Workspace';
import type { CalendarBlockProps, CalendarBlockTargetRequest } from './types';
function targetRequestFromParams(
@@ -47,7 +49,7 @@ function CalendarBlockDisabledRedirect() {
}
/** Bridges the singleton block lifecycle and navigation API to CalendarView. */
-export function CalendarBlockAdapter(props: CalendarBlockProps) {
+function CalendarBlockAdapter(props: CalendarBlockProps) {
const calendarUiEnabled = useCalendarUiFlag();
const posthog = usePosthog();
const userId = useUserId();
@@ -102,7 +104,11 @@ export function CalendarBlockAdapter(props: CalendarBlockProps) {
</Show>
}
>
- <CalendarView focusTarget={focusTarget()} />
+ <CalendarFocusContextProvider target={focusTarget}>
+ <CalendarViewContextProvider>
+ <Workspace />
+ </CalendarViewContextProvider>
+ </CalendarFocusContextProvider>
</Show>
);
}
diff --git a/apps/web/src/features/calendar/calendar-focus-target.ts b/apps/web/src/features/block-calendar/calendar-focus-target.ts
similarity index 100%
rename from apps/web/src/features/calendar/calendar-focus-target.ts
rename to apps/web/src/features/block-calendar/calendar-focus-target.ts
diff --git a/apps/web/src/features/block-calendar/calendar-range.ts b/apps/web/src/features/block-calendar/calendar-range.ts
index 375ae49c65..8fc468212f 100644
--- a/apps/web/src/features/block-calendar/calendar-range.ts
+++ b/apps/web/src/features/block-calendar/calendar-range.ts
@@ -1,3 +1,4 @@
+import { parseLocalDate } from '@app/features/calendar/utils/calendar-date';
import {
type CalendarOccurrenceQueryRange,
createCalendarOccurrenceQueryRange,
@@ -8,22 +9,6 @@ export type CalendarBlockEventTime =
| { kind: 'timed'; startsAt: string; endsAt?: string }
| { kind: 'allDay'; startDate: string; endDate?: string };
-function parseLocalDate(value: string): Date | undefined {
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
- if (!match) return undefined;
-
- const date = new Date(
- Number(match[1]),
- Number(match[2]) - 1,
- Number(match[3])
- );
- return date.getFullYear() === Number(match[1]) &&
- date.getMonth() === Number(match[2]) - 1 &&
- date.getDate() === Number(match[3])
- ? date
- : undefined;
-}
-
function nextLocalDay(date: Date) {
const next = new Date(date);
next.setDate(next.getDate() + 1);
diff --git a/apps/web/src/features/block-calendar/calendar-target.ts b/apps/web/src/features/block-calendar/calendar-target.ts
index cd0f880d13..2705ecfd5b 100644
--- a/apps/web/src/features/block-calendar/calendar-target.ts
+++ b/apps/web/src/features/block-calendar/calendar-target.ts
@@ -1,21 +1,8 @@
-import type { CalendarFocusTarget } from '@app/features/calendar/calendar-focus-target';
+import { parseLocalDate } from '@app/features/calendar/utils/calendar-date';
import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';
+import type { CalendarFocusTarget } from './calendar-focus-target';
import type { CalendarBlockTargetRequest } from './types';
-function parseLocalDate(value: string): Date | undefined {
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
- if (!match) return undefined;
- const year = Number(match[1]);
- const month = Number(match[2]) - 1;
- const day = Number(match[3]);
- const date = new Date(year, month, day);
- return date.getFullYear() === year &&
- date.getMonth() === month &&
- date.getDate() === day
- ? date
- : undefined;
-}
-
function occurrenceDate(item: CalendarOccurrenceItem): Date | undefined {
const time = item.occurrence.time;
const date =
diff --git a/apps/web/src/features/calendar/events/EventComposer.tsx b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx
similarity index 61%
rename from apps/web/src/features/calendar/events/EventComposer.tsx
rename to apps/web/src/features/block-calendar/components/EventComposerSplit.tsx
index 79fc78450a..b2624ce209 100644
--- a/apps/web/src/features/calendar/events/EventComposer.tsx
+++ b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx
@@ -1,13 +1,17 @@
+import { createCalendarEventFormController } from '@app/features/calendar/components/composer/create-calendar-event-form-controller';
+import { EventForm } from '@app/features/calendar/components/composer/EventForm';
+import {
+ defaultEditorInitialValues,
+ type EventEditorInitialValues,
+} from '@app/features/calendar/components/composer/event-form-model';
+import { useEventEditor } from '@app/features/calendar/hooks/use-event-editor';
+import type { CalendarEvent } from '@app/features/calendar/types';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { onMount } from 'solid-js';
-import { EventComposerForm } from './EventComposerForm';
-import type { EventEditorInitialValues } from './EventEditorForm';
-import type { CalendarEvent } from './types';
-import { useEventEditor } from './useEventEditor';
/** Standalone create/edit event composer hosted in a popover split. */
-export function EventComposer(props: {
+export function EventComposerSplit(props: {
event?: CalendarEvent;
initialValues?: EventEditorInitialValues;
onCalendarChange?: (calendarId: string, color: string) => void;
@@ -24,6 +28,14 @@ export function EventComposer(props: {
close();
},
});
+ const controller = createCalendarEventFormController({
+ initialValue:
+ editor.initialValues() ??
+ props.initialValues ??
+ defaultEditorInitialValues(),
+ calendarOptions: editor.calendarOptions,
+ guestOptions: editor.guestOptions,
+ });
const isEdit = () => props.event !== undefined;
@@ -36,12 +48,10 @@ export function EventComposer(props: {
ref={attachHotkeys}
class="portal-scope flex h-full min-h-0 flex-col p-4 text-ink"
>
- <EventComposerForm
- initialValues={editor.initialValues() ?? props.initialValues}
+ <EventForm
+ controller={controller}
isEdit={isEdit()}
disabledFields={editor.disabledFields()}
- calendarOptions={editor.calendarOptions()}
- guestOptions={editor.guestOptions}
showRecurringEditNotice={editor.showRecurringEditNotice()}
pending={editor.pending()}
onCalendarChange={props.onCalendarChange}
diff --git a/apps/web/src/features/calendar/events/EventRsvpSection.tsx b/apps/web/src/features/block-calendar/components/EventRsvpSection.tsx
similarity index 98%
rename from apps/web/src/features/calendar/events/EventRsvpSection.tsx
rename to apps/web/src/features/block-calendar/components/EventRsvpSection.tsx
index 7515a768a1..323d4c1de0 100644
--- a/apps/web/src/features/calendar/events/EventRsvpSection.tsx
+++ b/apps/web/src/features/block-calendar/components/EventRsvpSection.tsx
@@ -1,3 +1,4 @@
+import type { CalendarEvent } from '@app/features/calendar/types';
import { toast } from '@core/component/Toast/Toast';
import CloseIcon from '@phosphor/x.svg';
import { useRsvpCalendarEventMutation } from '@queries/calendar/mutations';
@@ -5,7 +6,6 @@ import type { CalendarRsvpScope } from '@service-email/client';
import type { AttendeeResponseStatus } from '@service-storage/generated/schemas/attendeeResponseStatus';
import { Button, Dialog, Panel } from '@ui';
import { createMemo, createSignal, For, Show } from 'solid-js';
-import type { CalendarEvent } from './types';
type RsvpResponse = Exclude<AttendeeResponseStatus, 'needs_action'>;
diff --git a/apps/web/src/features/calendar/calendar-view.tsx b/apps/web/src/features/block-calendar/components/Header.tsx
similarity index 53%
rename from apps/web/src/features/calendar/calendar-view.tsx
rename to apps/web/src/features/block-calendar/components/Header.tsx
index 831101b208..833032ac6d 100644
--- a/apps/web/src/features/calendar/calendar-view.tsx
+++ b/apps/web/src/features/block-calendar/components/Header.tsx
@@ -1,4 +1,14 @@
-import { SidePanel } from '@components/app/side-panel/SidePanel';
+import {
+ type CalendarPageId,
+ useCalendarPager,
+} from '@app/features/calendar/components/CalendarPagerContext';
+import { CalendarSettingsDropdown } from '@app/features/calendar/components/CalendarSettingsDropdown';
+import { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';
+import { MonthDrawer } from '@app/features/calendar/components/MonthDrawer';
+import { PeriodSelector } from '@app/features/calendar/components/PeriodSelector';
+import { useCalendarHotkeys } from '@app/features/calendar/hooks/use-calendar-hotkeys';
+import { calendarPeriodLabel } from '@app/features/calendar/utils/calendar-label';
+import { useSidePanel } from '@components/app/side-panel/SidePanel';
import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
import {
SplitHeaderLeft,
@@ -11,144 +21,16 @@ import CalendarBlankIcon from '@phosphor/calendar-blank.svg';
import CaretLeftIcon from '@phosphor/caret-left.svg';
import CaretRightIcon from '@phosphor/caret-right.svg';
import PlusIcon from '@phosphor/plus.svg';
-import { createResizeObserver } from '@solid-primitives/resize-observer';
-import { Button, Layer } from '@ui';
-import { Pager, PagerSwipeGestures, usePager } from '@ui/components/Pager';
-import {
- createMemo,
- createSignal,
- For,
- onCleanup,
- onMount,
- Show,
- Suspense,
-} from 'solid-js';
-import { CalendarMonthDrawer } from './CalendarMonthDrawer';
-import { CalendarPage } from './CalendarPage';
-import {
- CALENDAR_PAGE_IDS,
- type CalendarPageId,
- CalendarPagerContextProvider,
- useCalendarPager,
-} from './CalendarPagerContext';
-import { CalendarPeriodSelector } from './CalendarPeriodSelector';
-import { CalendarRangeUnavailableBanner } from './CalendarRangeUnavailableBanner';
-import { CalendarSettingsDropdown } from './CalendarSettingsDropdown';
-import { CalendarSetupStatus } from './CalendarSetupStatus';
-import { CalendarSidePanelSections } from './CalendarSidePanelSections';
-import {
- CalendarViewContextProvider,
- useCalendarView,
-} from './CalendarViewContext';
-import {
- CalendarFocusContextProvider,
- type CalendarFocusTarget,
-} from './calendar-focus-target';
-import { calendarPeriodLabel } from './calendar-label';
-import { SelectedEventDetails } from './events/EventDetailsPopover';
-import { useOpenEventComposer } from './events/useOpenEventComposer';
-import { useCalendarHotkeys } from './use-calendar-hotkeys';
-import './calendar.css';
-
-const CALENDAR_SWIPE_EDGE_INSET = 40;
+import { Button } from '@ui';
+import { usePager } from '@ui/components/Pager';
+import { createMemo, createSignal, onCleanup, Show } from 'solid-js';
+import { useOpenEventComposer } from './use-open-event-composer';
const formatMonthTitle = new Intl.DateTimeFormat(undefined, {
month: 'long',
year: 'numeric',
}).format;
-/** A calendar-focused workspace view backed by buffered FullCalendar pages. */
-export function CalendarView(props: { focusTarget?: CalendarFocusTarget }) {
- return (
- <CalendarFocusContextProvider target={() => props.focusTarget}>
- <CalendarViewContextProvider>
- <CalendarPagerContextProvider>
- <CalendarPagerRoot />
- </CalendarPagerContextProvider>
- </CalendarViewContextProvider>
- </CalendarFocusContextProvider>
- );
-}
-
-function CalendarPagerRoot() {
- const calendarPager = useCalendarPager();
-
- return (
- <Pager.Root controller={calendarPager.pager}>
- <SidePanel.Layout>
- <CalendarWorkspace />
- </SidePanel.Layout>
- </Pager.Root>
- );
-}
-
-function CalendarPages() {
- const calendarPager = useCalendarPager();
- const calendarView = useCalendarView();
- const [viewport, setViewport] = createSignal<HTMLDivElement>();
- let resizeFrame: number | undefined;
-
- createResizeObserver(viewport, ({ width }) => {
- if (resizeFrame !== undefined) cancelAnimationFrame(resizeFrame);
-
- resizeFrame = requestAnimationFrame(() => {
- resizeFrame = undefined;
- calendarView.setUseNarrowDayHeaders(width < 520);
- calendarPager.updateSize();
- });
- });
-
- onCleanup(() => {
- if (resizeFrame !== undefined) cancelAnimationFrame(resizeFrame);
- });
-
- return (
- <Layer depth={2}>
- <div class="flex min-w-0 min-h-0 flex-1 flex-col">
- <CalendarRangeUnavailableBanner
- class={isMobile() ? 'order-last' : undefined}
- fullWidth={isMobile()}
- />
- <div
- ref={setViewport}
- class="relative flex min-w-0 min-h-0 flex-1"
- role="region"
- aria-label="Calendar periods"
- >
- <Pager.Viewport class="size-full min-w-0 min-h-0">
- <For each={CALENDAR_PAGE_IDS}>
- {(pageId) => (
- <Pager.Page id={pageId}>
- <Suspense>
- <CalendarPage
- id={pageId}
- initialDate={calendarPager.initialDateFor(pageId)}
- />
- </Suspense>
- </Pager.Page>
- )}
- </For>
- </Pager.Viewport>
- <Show when={isMobile()}>
- <PagerSwipeGestures
- edgeInset={CALENDAR_SWIPE_EDGE_INSET}
- canStart={(event) =>
- !(
- event.target instanceof Element &&
- event.target.closest(
- 'button, input, select, textarea, [role="button"], .fc-event'
- )
- )
- }
- />
- </Show>
- <CalendarSetupStatus />
- </div>
- </div>
- </Layer>
- );
-}
-
function createLocalToday() {
const [today, setToday] = createSignal(new Date());
let refreshTimer: number | undefined;
@@ -177,8 +59,9 @@ function createLocalToday() {
return today;
}
-function CalendarWorkspace() {
+export function Header() {
const panel = useSplitPanelOrThrow();
+ const sidePanel = useSidePanel();
const calendarPager = useCalendarPager();
const pager = usePager<CalendarPageId>();
const calendarView = useCalendarView();
@@ -213,8 +96,6 @@ function CalendarWorkspace() {
return currentDay >= range.start && currentDay < range.end;
});
- onMount(() => panel.handle.setDisplayName('Calendar'));
-
return (
<>
<SplitHeaderLeft>
@@ -227,7 +108,7 @@ function CalendarWorkspace() {
</span>
}
>
- <CalendarMonthDrawer month={currentDate()} />
+ <MonthDrawer month={currentDate()} />
</Show>
</HeaderIsland>
</SplitHeaderLeft>
@@ -280,7 +161,7 @@ function CalendarWorkspace() {
<PlusIcon class="size-3.5" />
New event
</Button>
- <CalendarPeriodSelector />
+ <PeriodSelector isNarrow={sidePanel?.isNarrow()} />
<div class="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
@@ -304,25 +185,10 @@ function CalendarWorkspace() {
</Button>
</div>
</Show>
- <CalendarSettingsDropdown />
+ <CalendarSettingsDropdown isNarrow={sidePanel?.isNarrow()} />
</div>
</HeaderIsland>
</SplitHeaderRight>
-
- <CalendarSidePanelSections />
-
- <SelectedEventDetails
- anchor={calendarView.selectedEventAnchor}
- event={calendarView.selectedEvent}
- timeFormat={() => calendarView.displaySettings.timeFormat}
- onClose={calendarView.closeEventDetails}
- />
-
- <main class="calendar-view flex size-full min-h-0">
- <div class="calendar-view-content flex min-w-0 min-h-0 flex-1 flex-col">
- <CalendarPages />
- </div>
- </main>
</>
);
}
diff --git a/apps/web/src/features/block-calendar/components/Page.tsx b/apps/web/src/features/block-calendar/components/Page.tsx
new file mode 100644
index 0000000000..d35bbe69da
--- /dev/null
+++ b/apps/web/src/features/block-calendar/components/Page.tsx
@@ -0,0 +1,450 @@
+import {
+ CalendarGrid,
+ type CalendarGridHandle,
+ type CalendarGridSelection,
+ type CalendarGridSettings,
+} from '@app/features/calendar/components/CalendarGrid';
+import {
+ type CalendarPageId,
+ useCalendarPager,
+} from '@app/features/calendar/components/CalendarPagerContext';
+import { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';
+import { calendarSelectionToEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
+import {
+ type CalendarOccurrenceData,
+ useCalendarOccurrenceData,
+} from '@app/features/calendar/hooks/use-calendar-occurrence-data';
+import { useCalendarTimeGridHoverIndicator } from '@app/features/calendar/hooks/use-calendar-time-grid-hover-indicator';
+import type { CalendarEvent } from '@app/features/calendar/types';
+import { DEFAULT_CALENDAR_SOURCE } from '@app/features/calendar/types';
+import { isCalendarRangeSupported } from '@app/features/calendar/utils/calendar-supported-range';
+import {
+ type CalendarEventTimeChange,
+ calendarEventTimeFromFullCalendar,
+ canEditCalendarEventTime,
+} from '@app/features/calendar/utils/event-interaction';
+import { toast } from '@core/component/Toast/Toast';
+import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';
+import { isMobile } from '@core/mobile/isMobile';
+import type { DateSelectArg, DatesSetArg } from '@fullcalendar/core';
+import SpinnerIcon from '@phosphor/spinner-gap.svg';
+import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
+import { useUpdateCalendarEventMutation } from '@queries/calendar/mutations';
+import {
+ type CalendarOccurrenceQueryRange,
+ createCalendarOccurrenceQueryRange,
+} from '@queries/calendar/occurrences';
+import { Button } from '@ui';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import { Portal } from 'solid-js/web';
+import {
+ calendarFocusTargetId,
+ useCalendarFocus,
+} from '../calendar-focus-target';
+import { useOpenEventComposer } from './use-open-event-composer';
+
+interface CalendarScrollTarget {
+ scrollElement: HTMLElement;
+ fadeContainer: HTMLElement;
+}
+
+function CalendarScrollIndicators(props: {
+ calendarElement: Accessor<HTMLElement | undefined>;
+}) {
+ const [target, setTarget] = createSignal<CalendarScrollTarget>();
+
+ createEffect(
+ on(props.calendarElement, (element) => {
+ if (!element) {
+ setTarget(undefined);
+ return;
+ }
+
+ let updateFrame: number | undefined;
+ const updateScrollElements = () => {
+ const scrollElement = element.querySelector<HTMLElement>(
+ '.fc-timegrid .fc-scroller-harness-liquid > .fc-scroller'
+ );
+ const fadeContainer = scrollElement?.parentElement;
+ setTarget((current) => {
+ if (!scrollElement || !fadeContainer) return undefined;
+ return current?.scrollElement === scrollElement &&
+ current.fadeContainer === fadeContainer
+ ? current
+ : { scrollElement, fadeContainer };
+ });
+ };
+ const scheduleScrollElementUpdate = () => {
+ if (updateFrame !== undefined) cancelAnimationFrame(updateFrame);
+ updateFrame = requestAnimationFrame(() => {
+ updateFrame = undefined;
+ updateScrollElements();
+ });
+ };
+
+ const mutationObserver = new MutationObserver(
+ scheduleScrollElementUpdate
+ );
+ mutationObserver.observe(element, { childList: true, subtree: true });
+ scheduleScrollElementUpdate();
+
+ onCleanup(() => {
+ mutationObserver.disconnect();
+ if (updateFrame !== undefined) cancelAnimationFrame(updateFrame);
+ });
+ })
+ );
+
+ return (
+ <Show keyed when={target()}>
+ {(scrollTarget) => (
+ <Portal
+ mount={scrollTarget.fadeContainer}
+ ref={(container) => {
+ container.style.display = 'contents';
+ }}
+ >
+ <ScrollIndicators
+ scrollRef={() => scrollTarget.scrollElement}
+ appearance="gradient"
+ class="h-6"
+ />
+ </Portal>
+ )}
+ </Show>
+ );
+}
+
+function CalendarPageDataStatus(props: { data: CalendarOccurrenceData }) {
+ const isRangeUnavailable = createMemo(() => {
+ const range = props.data.range();
+ return range !== undefined && !isCalendarRangeSupported(range);
+ });
+
+ const showLoading = () =>
+ !isRangeUnavailable() &&
+ !props.data.occurrencesQuery.isError &&
+ props.data.isLoading();
+
+ const showBlockingState = () => {
+ if (isRangeUnavailable()) return false;
+ if (props.data.occurrencesQuery.isError) return true;
+ if (showLoading()) return false;
+
+ return props.data.isSyncing() && props.data.events().length === 0;
+ };
+
+ return (
+ <>
+ <Show when={showBlockingState()}>
+ <div
+ class="absolute inset-0 z-20 flex items-center justify-center rounded-xl bg-surface/90 p-6 text-center"
+ aria-live="polite"
+ >
+ <Show
+ when={!props.data.occurrencesQuery.isError}
+ fallback={
+ <div class="flex max-w-sm flex-col items-center gap-3">
+ <div class="text-sm font-semibold text-ink">
+ Calendar unavailable
+ </div>
+ <p class="text-xs text-ink-muted">
+ We couldn’t load your calendar events. Try again.
+ </p>
+ <Button
+ variant="active"
+ size="sm"
+ label="Retry loading calendar"
+ onClick={() => void props.data.occurrencesQuery.refetch()}
+ >
+ Retry
+ </Button>
+ </div>
+ }
+ >
+ <div class="flex items-center gap-2 text-xs text-ink-muted">
+ <SpinnerIcon class="size-4 animate-spin" />
+ <span>Syncing calendar…</span>
+ </div>
+ </Show>
+ </div>
+ </Show>
+
+ <Show when={showLoading()}>
+ <div class="absolute top-2 left-2 z-10 flex items-center gap-1.5 rounded-full border border-edge-muted bg-surface px-2.5 py-1 text-xs text-ink-muted shadow-menu">
+ <SpinnerIcon class="size-3 animate-spin" />
+ Loading
+ </div>
+ </Show>
+
+ <Show
+ when={
+ !isRangeUnavailable() &&
+ !showLoading() &&
+ !showBlockingState() &&
+ props.data.isSyncing() &&
+ props.data.events().length > 0
+ }
+ >
+ <div class="absolute right-2 bottom-2 z-10 flex items-center gap-1.5 rounded-full border border-edge-muted bg-surface px-2.5 py-1 text-xs text-ink-muted shadow-menu">
+ <SpinnerIcon class="size-3 animate-spin" />
+ Syncing
+ </div>
+ </Show>
+ </>
+ );
+}
+
+/** One independently rendered and queried FullCalendar page. */
+export function Page(props: {
+ id: CalendarPageId;
+ initialDate: Date;
+ useNarrowDayHeaders: boolean;
+}) {
+ const pager = useCalendarPager();
+ const calendarView = useCalendarView();
+ const openEventComposer = useOpenEventComposer();
+ const calendarsQuery = useVisibleCalendarsQuery();
+ const firstWritableCalendar = createMemo(() =>
+ calendarsQuery.data?.find((calendar) => calendar.isWritable)
+ );
+ const [range, setRange] = createSignal<CalendarOccurrenceQueryRange>();
+ const [selectionColor, setSelectionColor] = createSignal<string>();
+ const effectiveSelectionColor = () =>
+ selectionColor() ??
+ firstWritableCalendar()?.color ??
+ DEFAULT_CALENDAR_SOURCE.color;
+ const isActive = () => pager.isActive(props.id);
+ const useNarrowWeekdayHeaders = () =>
+ props.useNarrowDayHeaders && !isMobile();
+ const data = useCalendarOccurrenceData({
+ range,
+ sourceById: calendarView.sourceById,
+ isSourceVisible: calendarView.isSourceVisible,
+ queryOptions: () => ({
+ pollWhileSyncing: isActive(),
+ refetchOnWindowFocus: isActive(),
+ }),
+ });
+ const updateEventTime = useUpdateCalendarEventMutation();
+ const handleSelect = (selection: DateSelectArg) => {
+ if (!isActive()) return;
+ const calendar = firstWritableCalendar();
+ setSelectionColor(calendar?.color ?? DEFAULT_CALENDAR_SOURCE.color);
+ openEventComposer({
+ initialValues: {
+ ...calendarSelectionToEditorInitialValues(selection),
+ ...(calendar ? { calendarId: calendar.id } : {}),
+ },
+ onCalendarChange: (_calendarId: string, color: string) =>
+ setSelectionColor(color),
+ onClose: () => {
+ selection.view.calendar.unselect();
+ setSelectionColor(undefined);
+ },
+ });
+ };
+
+ const handleDatesSet = ({ end, start }: DatesSetArg) => {
+ const nextRange = createCalendarOccurrenceQueryRange(start, end);
+ const currentRange = range();
+ if (
+ currentRange?.start === nextRange.start &&
+ currentRange.end === nextRange.end &&
+ currentRange.startDate === nextRange.startDate &&
+ currentRange.endDate === nextRange.endDate
+ ) {
+ return;
+ }
+ setRange(nextRange);
+ };
+
+ const handleEventTimeChange = (
+ change: CalendarEventTimeChange,
+ event: CalendarEvent | undefined
+ ) => {
+ if (
+ !isActive() ||
+ updateEventTime.isPending ||
+ !event ||
+ !canEditCalendarEventTime(event)
+ ) {
+ change.revert();
+ return;
+ }
+
+ const time = calendarEventTimeFromFullCalendar(change.event, event);
+ if (!time) {
+ change.revert();
+ return;
+ }
+
+ updateEventTime.mutate(
+ { eventId: event.eventId, patch: { time } },
+ {
+ onError: (error) => {
+ change.revert();
+ toast.failure('Failed to update event', {
+ subtext: error.message,
+ });
+ },
+ }
+ );
+ };
+
+ const gridSettings: CalendarGridSettings = {
+ get initialView() {
+ return calendarView.displaySettings.periodView;
+ },
+ get showWeekends() {
+ return calendarView.displaySettings.showWeekends;
+ },
+ get weekStartsOn() {
+ return calendarView.displaySettings.weekStartsOn;
+ },
+ get timeFormat() {
+ return calendarView.displaySettings.timeFormat;
+ },
+ get useNarrowDayHeaders() {
+ return useNarrowWeekdayHeaders();
+ },
+ get useNarrowEventContent() {
+ return props.useNarrowDayHeaders;
+ },
+ };
+ const gridSelection: CalendarGridSelection = {
+ get color() {
+ return effectiveSelectionColor();
+ },
+ get eventId() {
+ return isActive() ? calendarView.selectedEvent()?.id : undefined;
+ },
+ onDateSelect: handleSelect,
+ onEventSelect: (event, element) => {
+ if (isActive()) calendarView.selectEvent(event, element);
+ },
+ };
+
+ return (
+ <CalendarGrid
+ initialDate={props.initialDate}
+ events={data.visibleEvents()}
+ eventsById={data.eventsById()}
+ settings={gridSettings}
+ selection={gridSelection}
+ eventTimeChangePending={updateEventTime.isPending}
+ onDatesSet={handleDatesSet}
+ onEventTimeChange={handleEventTimeChange}
+ >
+ {(grid) => <CalendarPageHost id={props.id} data={data} grid={grid} />}
+ </CalendarGrid>
+ );
+}
+
+function CalendarPageHost(props: {
+ id: CalendarPageId;
+ data: CalendarOccurrenceData;
+ grid: CalendarGridHandle;
+}) {
+ const pager = useCalendarPager();
+ const calendarView = useCalendarView();
+ const calendarFocus = useCalendarFocus();
+ const isActive = () => pager.isActive(props.id);
+
+ // A block navigation request pages this calendar instance to one occurrence
+ // and opens its details once FullCalendar has mounted the target chip.
+ let navigatedFor: number | undefined;
+ createEffect(() => {
+ props.grid.chipMounts();
+ const target = calendarFocus.pendingTarget();
+ if (!target || !isActive()) return;
+ const dateInfo = props.grid.dateInfo();
+ if (!dateInfo) return;
+ if (target.date < dateInfo.start || target.date >= dateInfo.end) {
+ // Navigate once per request; the effect re-runs as the destination
+ // page's chips mount, and by then the date is inside the view.
+ if (navigatedFor !== target.requestId) {
+ navigatedFor = target.requestId;
+ pager.navigateToDate(target.date);
+ }
+ return;
+ }
+ const targetId = calendarFocusTargetId(target);
+ const event = props.data.eventsById().get(targetId);
+ const chip = props.grid.eventElements.get(targetId);
+ if (!event || !chip?.isConnected) return;
+ calendarFocus.consume(target.requestId);
+ calendarView.selectEvent(event, chip);
+ });
+
+ useCalendarTimeGridHoverIndicator(() =>
+ isActive() ? props.grid.element() : undefined
+ );
+
+ onMount(() => {
+ const unregister = pager.registerPage({
+ id: props.id,
+ api: props.grid.api,
+ dateInfo: props.grid.dateInfo,
+ element: props.grid.element,
+ data: props.data,
+ });
+ onCleanup(unregister);
+ });
+
+ createEffect(
+ on(isActive, (active, wasActive) => {
+ if (
+ active &&
+ wasActive === false &&
+ props.data.occurrencesQuery.isSuccess &&
+ props.data.occurrencesQuery.isStale &&
+ !props.data.occurrencesQuery.isFetching &&
+ !props.data.occurrencesQuery.isPlaceholderData
+ ) {
+ void props.data.occurrencesQuery.refetch();
+ }
+ })
+ );
+
+ createEffect(
+ on(
+ () =>
+ [
+ isActive(),
+ calendarView.selectedEvent()?.id,
+ props.data.occurrencesQuery.dataUpdatedAt,
+ ] as const,
+ ([active, selectedEventId]) => {
+ if (
+ !active ||
+ !selectedEventId ||
+ !props.data.occurrencesQuery.isSuccess ||
+ props.data.occurrencesQuery.isPlaceholderData
+ ) {
+ return;
+ }
+
+ const selectedEvent = props.data.eventsById().get(selectedEventId);
+ if (selectedEvent) calendarView.refreshSelectedEvent(selectedEvent);
+ else calendarView.closeEventDetails();
+ }
+ )
+ );
+
+ return (
+ <>
+ <CalendarScrollIndicators calendarElement={props.grid.element} />
+ <CalendarPageDataStatus data={props.data} />
+ </>
+ );
+}
diff --git a/apps/web/src/features/calendar/events/EventDetailsPopover.tsx b/apps/web/src/features/block-calendar/components/SelectedEventDetails.tsx
similarity index 92%
rename from apps/web/src/features/calendar/events/EventDetailsPopover.tsx
rename to apps/web/src/features/block-calendar/components/SelectedEventDetails.tsx
index 83658641d9..d3e8ff890e 100644
--- a/apps/web/src/features/calendar/events/EventDetailsPopover.tsx
+++ b/apps/web/src/features/block-calendar/components/SelectedEventDetails.tsx
@@ -1,3 +1,11 @@
+import {
+ EventAttendeesSection,
+ EventDetails,
+} from '@app/features/calendar/components/EventDetails';
+import type {
+ CalendarEvent,
+ CalendarTimeFormat,
+} from '@app/features/calendar/types';
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
import { toast } from '@core/component/Toast/Toast';
import { isMobile } from '@core/mobile/isMobile';
@@ -5,8 +13,10 @@ import { Popover } from '@kobalte/core/popover';
import PencilSimpleIcon from '@phosphor/pencil-simple.svg';
import TrashIcon from '@phosphor/trash.svg';
import CloseIcon from '@phosphor/x.svg';
+import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
import { useDeleteCalendarEventMutation } from '@queries/calendar/mutations';
import type { CalendarDeletionScope } from '@service-email/client';
+import type { EventReminderOverride } from '@service-storage/generated/schemas/eventReminderOverride';
import {
Button,
DeleteDialog,
@@ -15,10 +25,8 @@ import {
useImperativeDialog,
} from '@ui';
import { type Accessor, createMemo, createSignal, Show } from 'solid-js';
-import { EventAttendeesSection, EventDetails } from './EventDetails';
import { EventRsvpSection } from './EventRsvpSection';
-import type { CalendarEvent, CalendarTimeFormat } from './types';
-import { useOpenEventComposer } from './useOpenEventComposer';
+import { useOpenEventComposer } from './use-open-event-composer';
interface SelectedEventDetailsProps {
anchor: Accessor<HTMLElement | undefined>;
@@ -37,6 +45,10 @@ interface SelectedEventDetailsProps {
* overlay closes rather than lingering on stale data.
*/
export function SelectedEventDetails(props: SelectedEventDetailsProps) {
+ const calendarsQuery = useVisibleCalendarsQuery();
+ const defaultReminders = (event: CalendarEvent) =>
+ calendarsQuery.data?.find((calendar) => calendar.id === event.calendarId)
+ ?.defaultReminders;
const popoverSelection = createMemo(
() => {
const event = props.event();
@@ -67,6 +79,7 @@ export function SelectedEventDetails(props: SelectedEventDetailsProps) {
anchor={selected.anchor}
event={currentEvent()}
timeFormat={props.timeFormat()}
+ defaultReminders={defaultReminders(currentEvent())}
onOpenChange={(open) => {
if (!open) props.onClose();
}}
@@ -83,6 +96,7 @@ export function SelectedEventDetails(props: SelectedEventDetailsProps) {
<EventDetailsDrawer
event={currentEvent()}
timeFormat={props.timeFormat()}
+ defaultReminders={defaultReminders(currentEvent())}
onOpenChange={(open) => {
if (!open) props.onClose();
}}
@@ -97,6 +111,7 @@ export function SelectedEventDetails(props: SelectedEventDetailsProps) {
interface EventDetailsOverlayProps {
event: CalendarEvent;
timeFormat: CalendarTimeFormat;
+ defaultReminders?: EventReminderOverride[];
onOpenChange: (open: boolean) => void;
}
@@ -168,7 +183,11 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {
</div>
<div class="flex min-h-0 flex-1 flex-col overflow-y-auto">
<div class="px-3">
- <EventDetails event={props.event} timeFormat={props.timeFormat} />
+ <EventDetails
+ event={props.event}
+ timeFormat={props.timeFormat}
+ defaultReminders={props.defaultReminders}
+ />
</div>
<EventAttendeesSection attendees={props.event.attendees} />
<EventRsvpSection event={props.event} buttonSize="md" />
@@ -386,6 +405,7 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {
<EventDetails
event={props.event}
timeFormat={props.timeFormat}
+ defaultReminders={props.defaultReminders}
/>
</div>
<EventAttendeesSection attendees={props.event.attendees} />
diff --git a/apps/web/src/features/calendar/CalendarSetupStatus.tsx b/apps/web/src/features/block-calendar/components/SetupStatus.tsx
similarity index 94%
rename from apps/web/src/features/calendar/CalendarSetupStatus.tsx
rename to apps/web/src/features/block-calendar/components/SetupStatus.tsx
index 221585fa19..6c3b88e36d 100644
--- a/apps/web/src/features/calendar/CalendarSetupStatus.tsx
+++ b/apps/web/src/features/block-calendar/components/SetupStatus.tsx
@@ -1,9 +1,9 @@
+import { useCalendarPager } from '@app/features/calendar/components/CalendarPagerContext';
+import { isCalendarRangeSupported } from '@app/features/calendar/utils/calendar-supported-range';
import { useAddInboxFlow } from '@core/email-link';
import { useEmailLinksQuery } from '@queries/email/link';
import { Button } from '@ui';
import { createMemo, Show } from 'solid-js';
-import { useCalendarPager } from './CalendarPagerContext';
-import { isCalendarRangeSupported } from './calendar-supported-range';
const SETUP_MESSAGES = {
connect: {
@@ -29,7 +29,7 @@ const SETUP_MESSAGES = {
} as const;
/** Displays account setup actions above the complete calendar pager. */
-export function CalendarSetupStatus() {
+export function SetupStatus() {
const calendarPager = useCalendarPager();
const linksQuery = useEmailLinksQuery();
const startAddInbox = useAddInboxFlow();
diff --git a/apps/web/src/features/calendar/CalendarSidePanelSections.tsx b/apps/web/src/features/block-calendar/components/SidePanelSections.tsx
similarity index 88%
rename from apps/web/src/features/calendar/CalendarSidePanelSections.tsx
rename to apps/web/src/features/block-calendar/components/SidePanelSections.tsx
index 45b82f8dc9..a5b25be0da 100644
--- a/apps/web/src/features/calendar/CalendarSidePanelSections.tsx
+++ b/apps/web/src/features/block-calendar/components/SidePanelSections.tsx
@@ -1,9 +1,9 @@
+import { useCalendarPager } from '@app/features/calendar/components/CalendarPagerContext';
+import { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';
+import { SourceControls } from '@app/features/calendar/components/SourceControls';
import { SidePanel, useSidePanel } from '@components/app/side-panel/SidePanel';
import { Calendar as MiniCalendar } from '@ui';
import { createEffect, createMemo, createSignal, on, Show } from 'solid-js';
-import { useCalendarPager } from './CalendarPagerContext';
-import { useCalendarView } from './CalendarViewContext';
-import { CalendarControls } from './events/CalendarControls';
function CalendarMiniCalendarSidePanelSection() {
const calendarView = useCalendarView();
@@ -75,7 +75,7 @@ function CalendarSourcesSidePanelSection() {
order={20}
defaultOpen
>
- <CalendarControls
+ <SourceControls
sources={calendarView.sources()}
isVisible={calendarView.isSourceVisible}
onVisibilityChange={calendarView.setSourceVisibility}
@@ -86,7 +86,7 @@ function CalendarSourcesSidePanelSection() {
}
/** Registers the calendar's contextual right-side panel sections. */
-export function CalendarSidePanelSections() {
+export function SidePanelSections() {
const sidePanel = useSidePanel();
return (
diff --git a/apps/web/src/features/block-calendar/components/Workspace.tsx b/apps/web/src/features/block-calendar/components/Workspace.tsx
new file mode 100644
index 0000000000..a48df1995e
--- /dev/null
+++ b/apps/web/src/features/block-calendar/components/Workspace.tsx
@@ -0,0 +1,151 @@
+import {
+ CALENDAR_PAGE_IDS,
+ CalendarPagerContextProvider,
+ useCalendarPager,
+} from '@app/features/calendar/components/CalendarPagerContext';
+import { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';
+import { RangeUnavailableBanner } from '@app/features/calendar/components/RangeUnavailableBanner';
+import { SidePanel } from '@components/app/side-panel/SidePanel';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { isMobile } from '@core/mobile/isMobile';
+import { createResizeObserver } from '@solid-primitives/resize-observer';
+import { Layer } from '@ui';
+import { Pager, PagerSwipeGestures } from '@ui/components/Pager';
+import {
+ createSignal,
+ For,
+ onCleanup,
+ onMount,
+ Show,
+ Suspense,
+} from 'solid-js';
+import { Header } from './Header';
+import { Page } from './Page';
+import { SelectedEventDetails } from './SelectedEventDetails';
+import { SetupStatus } from './SetupStatus';
+import { SidePanelSections } from './SidePanelSections';
+
+const CALENDAR_SWIPE_EDGE_INSET = 40;
+
+function CalendarPages() {
+ const calendarPager = useCalendarPager();
+ const [viewport, setViewport] = createSignal<HTMLDivElement>();
+ const [useNarrowDayHeaders, setUseNarrowDayHeaders] = createSignal(false);
+ let resizeFrame: number | undefined;
+
+ createResizeObserver(viewport, ({ width }) => {
+ if (resizeFrame !== undefined) cancelAnimationFrame(resizeFrame);
+
+ resizeFrame = requestAnimationFrame(() => {
+ resizeFrame = undefined;
+ setUseNarrowDayHeaders(width < 520);
+ calendarPager.updateSize();
+ });
+ });
+
+ onCleanup(() => {
+ if (resizeFrame !== undefined) cancelAnimationFrame(resizeFrame);
+ });
+
+ return (
+ <Layer depth={2}>
+ <div class="flex min-w-0 min-h-0 flex-1 flex-col">
+ <RangeUnavailableBanner
+ class={isMobile() ? 'order-last' : undefined}
+ fullWidth={isMobile()}
+ />
+ <div
+ ref={setViewport}
+ class="relative flex min-w-0 min-h-0 flex-1"
+ role="region"
+ aria-label="Calendar periods"
+ >
+ <Pager.Viewport class="size-full min-w-0 min-h-0">
+ <For each={CALENDAR_PAGE_IDS}>
+ {(pageId) => (
+ <Pager.Page id={pageId}>
+ <Suspense>
+ <Page
+ id={pageId}
+ initialDate={calendarPager.initialDateFor(pageId)}
+ useNarrowDayHeaders={useNarrowDayHeaders()}
+ />
+ </Suspense>
+ </Pager.Page>
+ )}
+ </For>
+ </Pager.Viewport>
+ <Show when={isMobile()}>
+ <PagerSwipeGestures
+ edgeInset={CALENDAR_SWIPE_EDGE_INSET}
+ canStart={(event) =>
+ !(
+ event.target instanceof Element &&
+ event.target.closest(
+ 'button, input, select, textarea, [role="button"], .fc-event'
+ )
+ )
+ }
+ />
+ </Show>
+ <SetupStatus />
+ </div>
+ </div>
+ </Layer>
+ );
+}
+
+function WorkspaceContent() {
+ const panel = useSplitPanelOrThrow();
+ const calendarView = useCalendarView();
+
+ onMount(() => panel.handle.setDisplayName('Calendar'));
+
+ return (
+ <>
+ <Header />
+ <SidePanelSections />
+
+ <SelectedEventDetails
+ anchor={calendarView.selectedEventAnchor}
+ event={calendarView.selectedEvent}
+ timeFormat={() => calendarView.displaySettings.timeFormat}
+ onClose={calendarView.closeEventDetails}
+ />
+
+ <main class="flex size-full min-h-0">
+ <div class="calendar-view-content flex min-w-0 min-h-0 flex-1 flex-col">
+ <CalendarPages />
+ </div>
+ </main>
+ </>
+ );
+}
+
+function CalendarPagerWorkspace() {
+ const calendarPager = useCalendarPager();
+
+ return (
+ <Pager.Root controller={calendarPager.pager}>
+ <SidePanel.Layout>
+ <WorkspaceContent />
+ </SidePanel.Layout>
+ </Pager.Root>
+ );
+}
+
+export function Workspace() {
+ const calendarView = useCalendarView();
+
+ return (
+ <CalendarPagerContextProvider
+ initialView={calendarView.displaySettings.periodView}
+ showWeekends={() => calendarView.displaySettings.showWeekends}
+ weekStartsOn={() => calendarView.displaySettings.weekStartsOn}
+ onNavigate={calendarView.closeEventDetails}
+ onViewChange={calendarView.setPeriodView}
+ >
+ <CalendarPagerWorkspace />
+ </CalendarPagerContextProvider>
+ );
+}
diff --git a/apps/web/src/features/calendar/events/useOpenEventComposer.ts b/apps/web/src/features/block-calendar/components/use-open-event-composer.ts
similarity index 92%
rename from apps/web/src/features/calendar/events/useOpenEventComposer.ts
rename to apps/web/src/features/block-calendar/components/use-open-event-composer.ts
index 9c6c77b0af..f4281a5299 100644
--- a/apps/web/src/features/calendar/events/useOpenEventComposer.ts
+++ b/apps/web/src/features/block-calendar/components/use-open-event-composer.ts
@@ -1,8 +1,8 @@
+import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
+import type { CalendarEvent } from '@app/features/calendar/types';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { confirmDialog } from '@ui';
import { getOwner } from 'solid-js';
-import type { EventEditorInitialValues } from './EventEditorForm';
-import type { CalendarEvent } from './types';
/** Values and lifecycle callbacks used to open an event composer. */
export interface OpenEventComposerOptions {
diff --git a/apps/web/src/features/calendar/CalendarPage.tsx b/apps/web/src/features/calendar/CalendarPage.tsx
deleted file mode 100644
index 17ef08adb9..0000000000
--- a/apps/web/src/features/calendar/CalendarPage.tsx
+++ /dev/null
@@ -1,736 +0,0 @@
-import { toast } from '@core/component/Toast/Toast';
-import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';
-import { useUserId } from '@core/context/user';
-import { isMobile } from '@core/mobile/isMobile';
-import type {
- DateSelectArg,
- DatesSetArg,
- EventInput,
-} from '@fullcalendar/core';
-import dayGridPlugin from '@fullcalendar/daygrid';
-import interactionPlugin from '@fullcalendar/interaction';
-import timeGridPlugin from '@fullcalendar/timegrid';
-import SpinnerIcon from '@phosphor/spinner-gap.svg';
-import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
-import { useUpdateCalendarEventMutation } from '@queries/calendar/mutations';
-import {
- type CalendarOccurrenceQueryRange,
- createCalendarOccurrenceQueryRange,
- useCalendarOccurrencesQuery,
-} from '@queries/calendar/occurrences';
-import { CalendarSyncStatus } from '@service-storage/generated/schemas/calendarSyncStatus';
-import { Button } from '@ui';
-import {
- type Accessor,
- createEffect,
- createMemo,
- createSignal,
- on,
- onCleanup,
- onMount,
- Show,
-} from 'solid-js';
-import { Portal } from 'solid-js/web';
-import {
- type CalendarPageData,
- type CalendarPageId,
- useCalendarPager,
-} from './CalendarPagerContext';
-import { useCalendarView } from './CalendarViewContext';
-import {
- calendarFocusTargetId,
- useCalendarFocus,
-} from './calendar-focus-target';
-import { isCalendarRangeSupported } from './calendar-supported-range';
-import {
- DEFAULT_CALENDAR_SOURCE,
- mapCalendarOccurrence,
-} from './events/calendar-occurrence-mapper';
-import { CalendarEventContent } from './events/EventContent';
-import { calendarSelectionToEditorInitialValues } from './events/EventEditorForm';
-import {
- type CalendarEventTimeChange,
- calendarEventRenderId,
- calendarEventTimeFromFullCalendar,
- canEditCalendarEventTime,
-} from './events/event-interaction';
-import { mapCalendarEventToFullCalendar } from './events/event-mapper';
-import {
- isMultiDaySelectionPreview,
- multiDaySelectionRenderingPlugin,
-} from './events/multi-day-selection-rendering';
-import type { CalendarTimeFormat } from './events/types';
-import { useOpenEventComposer } from './events/useOpenEventComposer';
-import { FullCalendar, useFullCalendar } from './fullcalendar-solid';
-import {
- CALENDAR_TIME_FORMAT_OPTIONS,
- formatCalendarTime,
- formatCompactCalendarTime,
-} from './time-format';
-import { useCalendarTimeGridHoverIndicator } from './useCalendarTimeGridHoverIndicator';
-
-const formatWeekdayHeader = {
- narrow: new Intl.DateTimeFormat(undefined, {
- weekday: 'narrow',
- }).format,
- short: new Intl.DateTimeFormat(undefined, {
- weekday: 'short',
- }).format,
-};
-
-const formatDayNumber = new Intl.DateTimeFormat(undefined, {
- day: 'numeric',
-}).format;
-
-const isSameLocalDate = (first: Date, second: Date) =>
- first.getFullYear() === second.getFullYear() &&
- first.getMonth() === second.getMonth() &&
- first.getDate() === second.getDate();
-
-function CurrentTimeAxisIndicator(props: {
- date: Date;
- timeFormat: CalendarTimeFormat;
-}) {
- return (
- <span class="calendar-now-axis-indicator">
- <span class="calendar-now-time">
- {formatCalendarTime(props.date, props.timeFormat)}
- </span>
- </span>
- );
-}
-
-function getLocalScrollTime() {
- const now = new Date();
- const minutesSinceMidnight = now.getHours() * 60 + now.getMinutes();
- const scrollMinutes = Math.max(
- 0,
- Math.floor((minutesSinceMidnight - 60) / 30) * 30
- );
- const hours = Math.floor(scrollMinutes / 60);
- const minutes = scrollMinutes % 60;
-
- return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:00`;
-}
-
-interface CalendarScrollTarget {
- scrollElement: HTMLElement;
- fadeContainer: HTMLElement;
-}
-
-function CalendarScrollIndicators(props: {
- calendarElement: Accessor<HTMLElement | undefined>;
-}) {
- const [target, setTarget] = createSignal<CalendarScrollTarget>();
-
- createEffect(
- on(props.calendarElement, (element) => {
- if (!element) {
- setTarget(undefined);
- return;
- }
-
- let updateFrame: number | undefined;
- const updateScrollElements = () => {
- const scrollElement = element.querySelector<HTMLElement>(
- '.fc-timegrid .fc-scroller-harness-liquid > .fc-scroller'
- );
- const fadeContainer = scrollElement?.parentElement;
- setTarget((current) => {
- if (!scrollElement || !fadeContainer) return undefined;
- return current?.scrollElement === scrollElement &&
- current.fadeContainer === fadeContainer
- ? current
- : { scrollElement, fadeContainer };
- });
- };
- const scheduleScrollElementUpdate = () => {
- if (updateFrame !== undefined) cancelAnimationFrame(updateFrame);
- updateFrame = requestAnimationFrame(() => {
- updateFrame = undefined;
- updateScrollElements();
- });
- };
-
- const mutationObserver = new MutationObserver(
- scheduleScrollElementUpdate
- );
- mutationObserver.observe(element, { childList: true, subtree: true });
- scheduleScrollElementUpdate();
-
- onCleanup(() => {
- mutationObserver.disconnect();
- if (updateFrame !== undefined) cancelAnimationFrame(updateFrame);
- });
- })
- );
-
- return (
- <Show keyed when={target()}>
- {(scrollTarget) => (
- <Portal
- mount={scrollTarget.fadeContainer}
- ref={(container) => {
- container.style.display = 'contents';
- }}
- >
- <ScrollIndicators
- scrollRef={() => scrollTarget.scrollElement}
- appearance="gradient"
- class="h-6"
- />
- </Portal>
- )}
- </Show>
- );
-}
-
-function CalendarPageDataStatus(props: { data: CalendarPageData }) {
- const isRangeUnavailable = createMemo(() => {
- const range = props.data.range();
- return range !== undefined && !isCalendarRangeSupported(range);
- });
-
- const showLoading = () =>
- !isRangeUnavailable() &&
- !props.data.occurrencesQuery.isError &&
- props.data.isLoading();
-
- const showBlockingState = () => {
- if (isRangeUnavailable()) return false;
- if (props.data.occurrencesQuery.isError) return true;
- if (showLoading()) return false;
-
- return props.data.isSyncing() && props.data.events().length === 0;
- };
-
- return (
- <>
- <Show when={showBlockingState()}>
- <div
- class="absolute inset-0 z-20 flex items-center justify-center rounded-xl bg-surface/90 p-6 text-center"
- aria-live="polite"
- >
- <Show
- when={!props.data.occurrencesQuery.isError}
- fallback={
- <div class="flex max-w-sm flex-col items-center gap-3">
- <div class="text-sm font-semibold text-ink">
- Calendar unavailable
- </div>
- <p class="text-xs text-ink-muted">
- We couldn’t load your calendar events. Try again.
- </p>
- <Button
- variant="active"
- size="sm"
- label="Retry loading calendar"
- onClick={() => void props.data.occurrencesQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- }
- >
- <div class="flex items-center gap-2 text-xs text-ink-muted">
- <SpinnerIcon class="size-4 animate-spin" />
- <span>Syncing calendar…</span>
- </div>
- </Show>
- </div>
- </Show>
-
- <Show when={showLoading()}>
- <div class="absolute top-2 left-2 z-10 flex items-center gap-1.5 rounded-full border border-edge-muted bg-surface px-2.5 py-1 text-xs text-ink-muted shadow-menu">
- <SpinnerIcon class="size-3 animate-spin" />
- Loading
- </div>
- </Show>
-
- <Show
- when={
- !isRangeUnavailable() &&
- !showLoading() &&
- !showBlockingState() &&
- props.data.isSyncing() &&
- props.data.events().length > 0
- }
- >
- <div class="absolute right-2 bottom-2 z-10 flex items-center gap-1.5 rounded-full border border-edge-muted bg-surface px-2.5 py-1 text-xs text-ink-muted shadow-menu">
- <SpinnerIcon class="size-3 animate-spin" />
- Syncing
- </div>
- </Show>
- </>
- );
-}
-
-function createCalendarPageData(
- range: Accessor<CalendarOccurrenceQueryRange | undefined>,
- isActive: Accessor<boolean>
-): CalendarPageData {
- const userId = useUserId();
- const calendarView = useCalendarView();
- const isRangeSupported = createMemo(() => {
- const currentRange = range();
- return currentRange !== undefined && isCalendarRangeSupported(currentRange);
- });
- const occurrencesQuery = useCalendarOccurrencesQuery(
- () => ({ userId: userId(), range: range() }),
- () => ({
- enabled: isRangeSupported(),
- pollWhileSyncing: isActive(),
- refetchOnWindowFocus: isActive(),
- })
- );
- const events = createMemo(() => {
- if (!isRangeSupported()) return [];
- const sourceById = calendarView.sourceById();
- return (occurrencesQuery.data?.items ?? []).map((item) =>
- mapCalendarOccurrence(
- item,
- item.event.calendarId != null
- ? sourceById.get(item.event.calendarId)
- : undefined
- )
- );
- });
- const visibleEvents = createMemo(() =>
- events().filter((event) => calendarView.isSourceVisible(event.calendar.id))
- );
- const eventsById = createMemo(
- () => new Map(events().map((event) => [event.id, event]))
- );
- const fullCalendarEvents = createMemo(() =>
- visibleEvents().map(mapCalendarEventToFullCalendar)
- );
- const isLoading = () =>
- range() === undefined ||
- (isRangeSupported() &&
- (occurrencesQuery.isPending || occurrencesQuery.isPlaceholderData));
- const isSyncing = () =>
- occurrencesQuery.data?.syncStatus === CalendarSyncStatus.syncing;
-
- return {
- range,
- occurrencesQuery,
- events,
- eventsById,
- fullCalendarEvents,
- isLoading,
- isSyncing,
- };
-}
-
-/** One independently rendered and queried FullCalendar page. */
-export function CalendarPage(props: { id: CalendarPageId; initialDate: Date }) {
- const pager = useCalendarPager();
- const calendarView = useCalendarView();
- const openEventComposer = useOpenEventComposer();
- const calendarsQuery = useVisibleCalendarsQuery();
- const firstWritableCalendar = createMemo(() =>
- calendarsQuery.data?.find((calendar) => calendar.isWritable)
- );
- const [range, setRange] = createSignal<CalendarOccurrenceQueryRange>();
- const [selectionColor, setSelectionColor] = createSignal<string>();
- const effectiveSelectionColor = () =>
- selectionColor() ??
- firstWritableCalendar()?.color ??
- DEFAULT_CALENDAR_SOURCE.color;
- const isActive = () => pager.isActive(props.id);
- const useNarrowWeekdayHeaders = () =>
- calendarView.useNarrowDayHeaders() && !isMobile();
- const data = createCalendarPageData(range, isActive);
- const updateEventTime = useUpdateCalendarEventMutation();
- // FullCalendar owns temporary drag/resize state imperatively. Replacing its
- // event inputs mid-interaction clears that state and turns the pointer drag
- // into a date-selection mirror, so hold a stable query snapshot until stop.
- const [eventInteractionActive, setEventInteractionActive] =
- createSignal(false);
- const renderedFullCalendarEvents = createMemo<EventInput[]>(
- (current) =>
- eventInteractionActive() ? current : data.fullCalendarEvents(),
- data.fullCalendarEvents()
- );
- let interactionEventsById: ReturnType<typeof data.eventsById> | undefined;
-
- const eventByRenderId = (id: string) =>
- interactionEventsById?.get(id) ?? data.eventsById().get(id);
- const handleEventInteractionStart = () => {
- interactionEventsById = data.eventsById();
- setEventInteractionActive(true);
- };
- const handleEventInteractionStop = () => {
- // FullCalendar emits drop/resize immediately after stop, so defer clearing
- // the snapshot until those callbacks have consumed it.
- queueMicrotask(() => {
- interactionEventsById = undefined;
- setEventInteractionActive(false);
- });
- };
-
- // Rendered chip elements by view-model id, so a deep link can anchor the
- // details popover to the real chip. The signal bumps on every mount
- // because FullCalendar renders chips outside Solid's reactive graph.
- const eventElements = new Map<string, HTMLElement>();
- const [chipMounts, notifyChipMount] = createSignal(undefined, {
- equals: false,
- });
-
- const handleSelect = (selection: DateSelectArg) => {
- if (!isActive()) return;
- const calendar = firstWritableCalendar();
- setSelectionColor(calendar?.color ?? DEFAULT_CALENDAR_SOURCE.color);
- openEventComposer({
- initialValues: {
- ...calendarSelectionToEditorInitialValues(selection),
- ...(calendar ? { calendarId: calendar.id } : {}),
- },
- onCalendarChange: (_calendarId: string, color: string) =>
- setSelectionColor(color),
- onClose: () => {
- selection.view.calendar.unselect();
- setSelectionColor(undefined);
- },
- });
- };
-
- const handleDatesSet = ({ end, start }: DatesSetArg) => {
- const nextRange = createCalendarOccurrenceQueryRange(start, end);
- const currentRange = range();
- if (
- currentRange?.start === nextRange.start &&
- currentRange.end === nextRange.end &&
- currentRange.startDate === nextRange.startDate &&
- currentRange.endDate === nextRange.endDate
- ) {
- return;
- }
- setRange(nextRange);
- };
-
- const handleEventTimeChange = (change: CalendarEventTimeChange) => {
- const event = eventByRenderId(calendarEventRenderId(change.event));
- if (
- !isActive() ||
- updateEventTime.isPending ||
- !event ||
- !canEditCalendarEventTime(event)
- ) {
- change.revert();
- return;
- }
-
- const time = calendarEventTimeFromFullCalendar(change.event, event);
- if (!time) {
- change.revert();
- return;
- }
-
- updateEventTime.mutate(
- { eventId: event.eventId, patch: { time } },
- {
- onError: (error) => {
- change.revert();
- toast.failure('Failed to update event', {
- subtext: error.message,
- });
- },
- }
- );
- };
-
- return (
- <FullCalendar.Root
- plugins={[
- dayGridPlugin,
- interactionPlugin,
- timeGridPlugin,
- multiDaySelectionRenderingPlugin,
- ]}
- initialView={calendarView.displaySettings.periodView}
- initialDate={props.initialDate}
- height="100%"
- expandRows
- fixedWeekCount={false}
- handleWindowResize={false}
- allDayText="All day"
- nowIndicator
- headerToolbar={false}
- scrollTime={getLocalScrollTime()}
- scrollTimeReset={false}
- weekends={calendarView.displaySettings.showWeekends}
- firstDay={calendarView.displaySettings.weekStartsOn}
- slotLabelFormat={
- CALENDAR_TIME_FORMAT_OPTIONS[calendarView.displaySettings.timeFormat]
- }
- eventTimeFormat={
- CALENDAR_TIME_FORMAT_OPTIONS[calendarView.displaySettings.timeFormat]
- }
- events={renderedFullCalendarEvents()}
- eventAllow={() => !updateEventTime.isPending}
- eventResizableFromStart
- eventDragStart={handleEventInteractionStart}
- eventDragStop={handleEventInteractionStop}
- eventDrop={handleEventTimeChange}
- eventResizeStart={handleEventInteractionStart}
- eventResizeStop={handleEventInteractionStop}
- eventResize={handleEventTimeChange}
- selectable={!isMobile()}
- unselectAuto={false}
- selectMirror
- selectMinDistance={5}
- select={handleSelect}
- eventClick={({ el, event, jsEvent }) => {
- jsEvent.preventDefault();
- if (!isActive()) return;
- const selectedEvent = eventByRenderId(calendarEventRenderId(event));
- if (selectedEvent) calendarView.selectEvent(selectedEvent, el);
- }}
- eventDidMount={({ el, event, isMirror }) => {
- const eventId = calendarEventRenderId(event);
- const calendarEvent = eventByRenderId(eventId);
- if (calendarEvent) {
- el.style.setProperty(
- '--event-calendar-color',
- calendarEvent.calendar.color
- );
- }
- if (isMirror || isMultiDaySelectionPreview(event)) return;
-
- eventElements.set(eventId, el);
- // A re-render (query settling, live refresh) replaces chip elements.
- // Re-anchor an open details popover to the remounted chip — its old
- // anchor is a disconnected node the popover can't position against.
- if (isActive() && calendarView.eventState.selectedEventId === eventId) {
- const selected = eventByRenderId(eventId);
- if (selected) calendarView.selectEvent(selected, el);
- }
- notifyChipMount();
- }}
- eventWillUnmount={({ el, event, isMirror }) => {
- if (isMirror || isMultiDaySelectionPreview(event)) return;
-
- const eventId = calendarEventRenderId(event);
- if (eventElements.get(eventId) === el) {
- eventElements.delete(eventId);
- }
- }}
- datesSet={handleDatesSet}
- dayHeaderFormat={{
- weekday: useNarrowWeekdayHeaders() ? 'narrow' : 'short',
- }}
- dayCellClassNames={({ date, view }) =>
- isSameLocalDate(date, view.calendar.getDate())
- ? ['calendar-day-selected']
- : []
- }
- >
- <FullCalendar.DayHeaderContent>
- {({ date, text, view }) => {
- if (view.type === 'timeGridWeek' || view.type === 'timeGridDay') {
- const weekday =
- view.type === 'timeGridDay'
- ? formatWeekdayHeader.short(date)
- : formatWeekdayHeader[
- useNarrowWeekdayHeaders() ? 'narrow' : 'short'
- ](date);
-
- return (
- <>
- <span class="calendar-day-header-weekday">{weekday}</span>{' '}
- <span
- class="calendar-day-header-date"
- classList={{
- 'calendar-day-header-date-selected': isSameLocalDate(
- date,
- view.calendar.getDate()
- ),
- }}
- >
- {formatDayNumber(date)}
- </span>
- </>
- );
- }
- return text;
- }}
- </FullCalendar.DayHeaderContent>
-
- <FullCalendar.SlotLabelContent>
- {({ date }) =>
- formatCompactCalendarTime(
- date,
- calendarView.displaySettings.timeFormat
- )
- }
- </FullCalendar.SlotLabelContent>
-
- <FullCalendar.EventContent>
- {(renderProps) => {
- const event = eventByRenderId(
- calendarEventRenderId(renderProps.event)
- );
- if (
- !event &&
- (isMultiDaySelectionPreview(renderProps.event) ||
- (renderProps.isMirror &&
- !renderProps.isDragging &&
- !renderProps.isResizing))
- ) {
- return (
- <div class="calendar-event-selection-preview flex h-full min-w-0 flex-col overflow-hidden px-1 py-0.5 text-xs leading-tight">
- <span class="truncate font-semibold">New event</span>
- <Show when={renderProps.timeText}>
- <span class="truncate">{renderProps.timeText}</span>
- </Show>
- </div>
- );
- }
- if (!event) return null;
-
- return (
- <CalendarEventContent
- event={event}
- renderProps={renderProps}
- isSelected={
- isActive() &&
- calendarView.eventState.selectedEventId === event.id
- }
- timeFormat={calendarView.displaySettings.timeFormat}
- isNarrow={calendarView.useNarrowDayHeaders()}
- />
- );
- }}
- </FullCalendar.EventContent>
-
- <FullCalendar.NowIndicatorContent>
- {({ isAxis }) => {
- if (isAxis) return null;
-
- return (
- <CurrentTimeAxisIndicator
- date={new Date()}
- timeFormat={calendarView.displaySettings.timeFormat}
- />
- );
- }}
- </FullCalendar.NowIndicatorContent>
-
- <CalendarPageHost
- id={props.id}
- data={data}
- eventElements={eventElements}
- chipMounts={chipMounts}
- selectionColor={effectiveSelectionColor()}
- />
- </FullCalendar.Root>
- );
-}
-
-function CalendarPageHost(props: {
- id: CalendarPageId;
- data: CalendarPageData;
- eventElements: Map<string, HTMLElement>;
- chipMounts: Accessor<undefined>;
- selectionColor: string;
-}) {
- const calendar = useFullCalendar();
- const pager = useCalendarPager();
- const calendarView = useCalendarView();
- const calendarFocus = useCalendarFocus();
- const [element, setElement] = createSignal<HTMLDivElement>();
- const isActive = () => pager.isActive(props.id);
-
- // A block navigation request pages this calendar instance to one occurrence
- // and opens its details once FullCalendar has mounted the target chip.
- let navigatedFor: number | undefined;
- createEffect(() => {
- props.chipMounts();
- const target = calendarFocus.pendingTarget();
- if (!target || !isActive()) return;
- const dateInfo = calendar.dateInfo();
- if (!dateInfo) return;
- if (target.date < dateInfo.start || target.date >= dateInfo.end) {
- // Navigate once per request; the effect re-runs as the destination
- // page's chips mount, and by then the date is inside the view.
- if (navigatedFor !== target.requestId) {
- navigatedFor = target.requestId;
- pager.navigateToDate(target.date);
- }
- return;
- }
- const targetId = calendarFocusTargetId(target);
- const event = props.data.eventsById().get(targetId);
- const chip = props.eventElements.get(targetId);
- if (!event || !chip?.isConnected) return;
- calendarFocus.consume(target.requestId);
- calendarView.selectEvent(event, chip);
- });
-
- useCalendarTimeGridHoverIndicator(() => (isActive() ? element() : undefined));
-
- onMount(() => {
- const unregister = pager.registerPage({
- id: props.id,
- api: calendar.api,
- dateInfo: calendar.dateInfo,
- element,
- data: props.data,
- });
- onCleanup(unregister);
- });
-
- createEffect(
- on(isActive, (active, wasActive) => {
- if (
- active &&
- wasActive === false &&
- props.data.occurrencesQuery.isSuccess &&
- props.data.occurrencesQuery.isStale &&
- !props.data.occurrencesQuery.isFetching &&
- !props.data.occurrencesQuery.isPlaceholderData
- ) {
- void props.data.occurrencesQuery.refetch();
- }
- })
- );
-
- createEffect(
- on(
- () =>
- [
- isActive(),
- calendarView.eventState.selectedEventId,
- props.data.occurrencesQuery.dataUpdatedAt,
- ] as const,
- ([active, selectedEventId]) => {
- if (
- !active ||
- !selectedEventId ||
- !props.data.occurrencesQuery.isSuccess ||
- props.data.occurrencesQuery.isPlaceholderData
- ) {
- return;
- }
-
- const selectedEvent = props.data.eventsById().get(selectedEventId);
- if (selectedEvent) calendarView.refreshSelectedEvent(selectedEvent);
- else calendarView.closeEventDetails();
- }
- )
- );
-
- return (
- <>
- <FullCalendar.Host
- tabIndex={-1}
- ref={setElement}
- style={{ '--calendar-selection-color': props.selectionColor }}
- class="calendar-view-host size-full min-w-0 min-h-0 overflow-hidden"
- />
- <CalendarScrollIndicators calendarElement={element} />
- <CalendarPageDataStatus data={props.data} />
- </>
- );
-}
diff --git a/apps/web/src/features/calendar/CalendarPagerContext.tsx b/apps/web/src/features/calendar/CalendarPagerContext.tsx
deleted file mode 100644
index 60b45d156d..0000000000
--- a/apps/web/src/features/calendar/CalendarPagerContext.tsx
+++ /dev/null
@@ -1,315 +0,0 @@
-import { createAssertedContextProvider } from '@core/context/createContext';
-import type { Calendar, DatesSetArg, EventInput } from '@fullcalendar/core';
-import type {
- CalendarOccurrenceQueryRange,
- useCalendarOccurrencesQuery,
-} from '@queries/calendar/occurrences';
-import { createPager, type PagerController } from '@ui/components/Pager';
-import {
- type Accessor,
- batch,
- createEffect,
- createMemo,
- createSignal,
- on,
- onCleanup,
-} from 'solid-js';
-import { useCalendarView } from './CalendarViewContext';
-import type { CalendarEvent, CalendarPeriodView } from './events/types';
-
-export const CALENDAR_PAGE_IDS = ['previous', 'current', 'next'] as const;
-export type CalendarPageId = (typeof CALENDAR_PAGE_IDS)[number];
-
-const TIME_GRID_SCROLLER_SELECTOR =
- '.fc-timegrid .fc-scroller-harness-liquid > .fc-scroller';
-
-export interface CalendarPageData {
- range: Accessor<CalendarOccurrenceQueryRange | undefined>;
- occurrencesQuery: ReturnType<typeof useCalendarOccurrencesQuery>;
- events: Accessor<CalendarEvent[]>;
- eventsById: Accessor<Map<string, CalendarEvent>>;
- fullCalendarEvents: Accessor<EventInput[]>;
- isLoading: Accessor<boolean>;
- isSyncing: Accessor<boolean>;
-}
-
-export interface CalendarPageHandle {
- id: CalendarPageId;
- api: Accessor<Calendar | undefined>;
- dateInfo: Accessor<DatesSetArg | undefined>;
- element: Accessor<HTMLDivElement | undefined>;
- data: CalendarPageData;
-}
-
-const shiftedDateForView = (
- date: Date,
- view: CalendarPeriodView,
- offset: -1 | 1
-) => {
- const shifted = new Date(date);
- if (view === 'dayGridMonth') {
- shifted.setDate(1);
- shifted.setMonth(shifted.getMonth() + offset);
- } else {
- shifted.setDate(
- shifted.getDate() + (view === 'timeGridDay' ? offset : offset * 7)
- );
- }
- return shifted;
-};
-
-export const [CalendarPagerContextProvider, useCalendarPager] =
- createAssertedContextProvider('CalendarPagerContext', () => {
- const calendarView = useCalendarView();
-
- const initialDate = new Date();
- const initialView = calendarView.displaySettings.periodView;
- const initialDates: Record<CalendarPageId, Date> = {
- previous: shiftedDateForView(initialDate, initialView, -1),
- current: initialDate,
- next: shiftedDateForView(initialDate, initialView, 1),
- };
-
- const [pageOrder, setPageOrder] =
- createSignal<readonly CalendarPageId[]>(CALENDAR_PAGE_IDS);
-
- const [activePageId, setActivePageId] =
- createSignal<CalendarPageId>('current');
-
- const [listenForPageRegistryChange, notifyPageRegistryChange] =
- createSignal<void>(undefined, { equals: false });
-
- const pageHandles = new Map<CalendarPageId, CalendarPageHandle>();
-
- const pageHandle = (id: CalendarPageId) => {
- listenForPageRegistryChange();
- return pageHandles.get(id);
- };
-
- const activePage = createMemo(() => pageHandle(activePageId()));
- const activeData = createMemo(() => activePage()?.data);
- const activeDateInfo = createMemo(() => activePage()?.dateInfo());
-
- const scrollElementFor = (handle: CalendarPageHandle | undefined) => {
- const element = handle?.element();
- if (!element) return undefined;
-
- return element.querySelector<HTMLElement>(TIME_GRID_SCROLLER_SELECTOR);
- };
-
- const copyActiveScrollPosition = () => {
- const activeScrollElement = scrollElementFor(activePage());
- if (!activeScrollElement) return;
-
- for (const id of pageOrder()) {
- if (id === activePageId()) continue;
- const scrollElement = scrollElementFor(pageHandle(id));
- if (!scrollElement) continue;
-
- scrollElement.scrollTop = activeScrollElement.scrollTop;
- }
- };
-
- const synchronizePage = (
- handle: CalendarPageHandle | undefined,
- source: CalendarPageHandle | undefined,
- direction: 'previous' | 'next'
- ) => {
- const api = handle?.api();
- const sourceApi = source?.api();
- if (!api || !sourceApi) return;
-
- const date = sourceApi.getDate();
- const view = sourceApi.view.type;
- api.batchRendering(() => {
- if (api.view.type === view) {
- api.gotoDate(date);
- } else {
- api.changeView(view, date);
- }
-
- if (direction === 'previous') {
- api.prev();
- } else {
- api.next();
- }
- });
- };
-
- const synchronizeBuffers = () => {
- const order = pageOrder();
- const activeIndex = order.indexOf(activePageId());
- const current = activePage();
- const previousId = order[activeIndex - 1];
- const nextId = order[activeIndex + 1];
- if (previousId) {
- synchronizePage(pageHandle(previousId), current, 'previous');
- }
-
- if (nextId) {
- synchronizePage(pageHandle(nextId), current, 'next');
- }
-
- requestAnimationFrame(copyActiveScrollPosition);
- };
-
- const rotatePages = (
- destination: CalendarPageId,
- direction: 'previous' | 'next'
- ) => {
- const order = pageOrder();
- const recycledId =
- direction === 'next' ? order[0] : order[order.length - 1];
- const nextOrder =
- direction === 'next'
- ? [...order.slice(1), order[0]]
- : [order[order.length - 1], ...order.slice(0, -1)];
-
- calendarView.closeEventDetails();
- batch(() => {
- setPageOrder(nextOrder);
- setActivePageId(() => destination);
- });
-
- const current = pageHandle(destination);
- synchronizePage(pageHandle(recycledId), current, direction);
- requestAnimationFrame(copyActiveScrollPosition);
- };
-
- const pager: PagerController<CalendarPageId> = createPager({
- pageOrder,
- activePage: activePageId,
- canChangePage: ({ to }) => pageHandle(to)?.api() !== undefined,
- onDragStart: copyActiveScrollPosition,
- onTransitionStart: () => {
- calendarView.closeEventDetails();
- copyActiveScrollPosition();
- },
- onPageChange: (destination, { direction }) =>
- rotatePages(destination, direction),
- });
-
- const registerPage = (handle: CalendarPageHandle) => {
- pageHandles.set(handle.id, handle);
- notifyPageRegistryChange();
-
- return () => {
- if (pageHandles.get(handle.id) !== handle) return;
- pageHandles.delete(handle.id);
- notifyPageRegistryChange();
- };
- };
-
- let settingsSyncFrame: number | undefined;
- createEffect(
- on(
- () => [
- calendarView.displaySettings.showWeekends,
- calendarView.displaySettings.weekStartsOn,
- ],
- (_settings, previousSettings) => {
- if (previousSettings === undefined) return;
- if (settingsSyncFrame !== undefined) {
- cancelAnimationFrame(settingsSyncFrame);
- }
- settingsSyncFrame = requestAnimationFrame(() => {
- settingsSyncFrame = undefined;
- synchronizeBuffers();
- });
- }
- )
- );
- onCleanup(() => {
- if (settingsSyncFrame !== undefined) {
- cancelAnimationFrame(settingsSyncFrame);
- }
- });
-
- const updateSize = () => {
- listenForPageRegistryChange();
-
- for (const handle of pageHandles.values()) {
- handle.api()?.updateSize();
- }
- };
-
- const gotoDate = (date: Date) => {
- pager.cancel();
- calendarView.closeEventDetails();
- activePage()?.api()?.gotoDate(date);
- synchronizeBuffers();
- };
-
- const navigateToDate = (date: Date) => {
- pager.cancel();
-
- const sourceApi = activePage()?.api();
- if (!sourceApi) return;
-
- if (
- date >= sourceApi.view.currentStart &&
- date < sourceApi.view.currentEnd
- ) {
- gotoDate(date);
- return;
- }
-
- const direction =
- date < sourceApi.view.currentStart ? 'previous' : 'next';
- const order = pageOrder();
- const activeIndex = order.indexOf(activePageId());
- const destinationId =
- direction === 'previous'
- ? order[activeIndex - 1]
- : order[activeIndex + 1];
- const destinationApi = destinationId
- ? pageHandle(destinationId)?.api()
- : undefined;
-
- if (!destinationApi) {
- gotoDate(date);
- return;
- }
-
- destinationApi.batchRendering(() => {
- if (destinationApi.view.type === sourceApi.view.type) {
- destinationApi.gotoDate(date);
- } else {
- destinationApi.changeView(sourceApi.view.type, date);
- }
- });
-
- const transition =
- direction === 'previous' ? pager.previous() : pager.next();
- void transition.then(synchronizeBuffers);
- };
-
- const changeView = (view: CalendarPeriodView) => {
- calendarView.setPeriodView(view);
-
- const api = activePage()?.api();
- if (!api || api.view.type === view) return;
- pager.cancel();
- calendarView.closeEventDetails();
- api.changeView(view);
- synchronizeBuffers();
- };
-
- return {
- pager,
- pageOrder,
- activePageId,
- activePage,
- activeData,
- activeDateInfo,
- visibleRange: () => activeData()?.range(),
- initialDateFor: (id: CalendarPageId) => initialDates[id],
- isActive: (id: CalendarPageId) => activePageId() === id,
- registerPage,
- updateSize,
- gotoDate,
- navigateToDate,
- navigateToToday: () => navigateToDate(new Date()),
- changeView,
- };
- });
diff --git a/apps/web/src/features/calendar/calendar.css b/apps/web/src/features/calendar/calendar.css
index 6f1691e7c8..9883bbe90f 100644
--- a/apps/web/src/features/calendar/calendar.css
+++ b/apps/web/src/features/calendar/calendar.css
@@ -221,14 +221,8 @@
var(--event-calendar-color, var(--color-calendar)) 5%,
var(--color-surface)
);
- --fc-event-border-color: var(
- --event-calendar-color,
- var(--color-calendar)
- );
- --fc-event-text-color: var(
- --event-calendar-color,
- var(--color-calendar)
- );
+ --fc-event-border-color: var(--event-calendar-color, var(--color-calendar));
+ --fc-event-text-color: var(--event-calendar-color, var(--color-calendar));
border-color: var(--fc-event-border-color);
background-color: var(--fc-event-bg-color);
color: var(--fc-event-text-color);
@@ -351,10 +345,7 @@
font-size: clamp(0.625rem, min(6cqi, 20cqh), 0.75rem);
}
-.calendar-view
- .fc
- .calendar-event-content-compact
- .calendar-event-title {
+.calendar-view .fc .calendar-event-content-compact .calendar-event-title {
font-size: inherit;
}
@@ -437,11 +428,7 @@
.calendar-view .fc .fc-event:hover .calendar-event-content,
.calendar-view .fc .fc-event:focus-visible .calendar-event-content {
- background-color: color-mix(
- in oklch,
- var(--color-accent) 10%,
- transparent
- );
+ background-color: color-mix(in oklch, var(--color-accent) 10%, transparent);
}
.calendar-view .fc .fc-event:has(.calendar-event-content-selected) {
diff --git a/apps/web/src/features/calendar/components/CalendarGrid.tsx b/apps/web/src/features/calendar/components/CalendarGrid.tsx
new file mode 100644
index 0000000000..c9927c1971
--- /dev/null
+++ b/apps/web/src/features/calendar/components/CalendarGrid.tsx
@@ -0,0 +1,374 @@
+import {
+ FullCalendar,
+ type FullCalendarContextValue,
+ useFullCalendar,
+} from '@app/lib/fullcalendar-solid';
+import { isMobile } from '@core/mobile/isMobile';
+import type {
+ DateSelectArg,
+ DatesSetArg,
+ EventInput,
+} from '@fullcalendar/core';
+import dayGridPlugin from '@fullcalendar/daygrid';
+import interactionPlugin from '@fullcalendar/interaction';
+import timeGridPlugin from '@fullcalendar/timegrid';
+import {
+ type Accessor,
+ createMemo,
+ createSignal,
+ type JSX,
+ Show,
+} from 'solid-js';
+import {
+ type CalendarEvent,
+ type CalendarPeriodView,
+ type CalendarTimeFormat,
+ type CalendarWeekStart,
+ mapCalendarEventToFullCalendar,
+} from '../types';
+import { isSameLocalDate } from '../utils/calendar-date';
+import {
+ type CalendarEventTimeChange,
+ calendarEventRenderId,
+} from '../utils/event-interaction';
+import {
+ isMultiDaySelectionPreview,
+ multiDaySelectionRenderingPlugin,
+} from '../utils/fullcalendar-multi-day-selection';
+import {
+ CALENDAR_TIME_FORMAT_OPTIONS,
+ formatCalendarTime,
+ formatCompactCalendarTime,
+} from '../utils/time-format';
+import { EventContent } from './EventContent';
+import '../calendar.css';
+
+const formatWeekdayHeader = {
+ narrow: new Intl.DateTimeFormat(undefined, {
+ weekday: 'narrow',
+ }).format,
+ short: new Intl.DateTimeFormat(undefined, {
+ weekday: 'short',
+ }).format,
+};
+
+const formatDayNumber = new Intl.DateTimeFormat(undefined, {
+ day: 'numeric',
+}).format;
+
+function CurrentTimeAxisIndicator(props: {
+ date: Date;
+ timeFormat: CalendarTimeFormat;
+}) {
+ return (
+ <span class="calendar-now-axis-indicator">
+ <span class="calendar-now-time">
+ {formatCalendarTime(props.date, props.timeFormat)}
+ </span>
+ </span>
+ );
+}
+
+function getLocalScrollTime() {
+ const now = new Date();
+ const minutesSinceMidnight = now.getHours() * 60 + now.getMinutes();
+ const scrollMinutes = Math.max(
+ 0,
+ Math.floor((minutesSinceMidnight - 60) / 30) * 30
+ );
+ const hours = Math.floor(scrollMinutes / 60);
+ const minutes = scrollMinutes % 60;
+
+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:00`;
+}
+
+export interface CalendarGridHandle extends FullCalendarContextValue {
+ element: Accessor<HTMLDivElement | undefined>;
+ eventElements: Map<string, HTMLElement>;
+ chipMounts: Accessor<undefined>;
+}
+
+export interface CalendarGridSettings {
+ initialView: CalendarPeriodView;
+ showWeekends: boolean;
+ weekStartsOn: CalendarWeekStart;
+ timeFormat: CalendarTimeFormat;
+ useNarrowDayHeaders: boolean;
+ useNarrowEventContent: boolean;
+}
+
+export interface CalendarGridSelection {
+ color: string;
+ eventId?: string;
+ onDateSelect?: (selection: DateSelectArg) => void;
+ onEventSelect?: (event: CalendarEvent, element: HTMLElement) => void;
+}
+
+export interface CalendarGridProps {
+ initialDate: Date;
+ events: CalendarEvent[];
+ eventsById: Map<string, CalendarEvent>;
+ settings: CalendarGridSettings;
+ selection: CalendarGridSelection;
+ eventTimeChangePending?: boolean;
+ onDatesSet?: (info: DatesSetArg) => void;
+ onEventTimeChange?: (
+ change: CalendarEventTimeChange,
+ event: CalendarEvent | undefined
+ ) => void;
+ children?: (handle: CalendarGridHandle) => JSX.Element;
+}
+
+function CalendarGridHost(props: {
+ selectionColor: string;
+ eventElements: Map<string, HTMLElement>;
+ chipMounts: Accessor<undefined>;
+ children?: CalendarGridProps['children'];
+}) {
+ const calendar = useFullCalendar();
+ const [element, setElement] = createSignal<HTMLDivElement>();
+
+ const handle: CalendarGridHandle = {
+ api: calendar.api,
+ dateInfo: calendar.dateInfo,
+ element,
+ eventElements: props.eventElements,
+ chipMounts: props.chipMounts,
+ };
+
+ return (
+ <>
+ <div class="calendar-view size-full min-w-0 min-h-0 overflow-hidden">
+ <FullCalendar.Host
+ tabIndex={-1}
+ ref={setElement}
+ style={{ '--calendar-selection-color': props.selectionColor }}
+ class="calendar-view-host size-full min-w-0 min-h-0 overflow-hidden"
+ />
+ </div>
+ {props.children?.(handle)}
+ </>
+ );
+}
+
+/** Query-free, single-page calendar grid. */
+export function CalendarGrid(props: CalendarGridProps) {
+ const mappedEvents = createMemo<EventInput[]>(() =>
+ props.events.map((event) => {
+ const mapped = mapCalendarEventToFullCalendar(event);
+ return props.onEventTimeChange
+ ? mapped
+ : { ...mapped, startEditable: false, durationEditable: false };
+ })
+ );
+ const [eventInteractionActive, setEventInteractionActive] =
+ createSignal(false);
+ const renderedEvents = createMemo<EventInput[]>(
+ (current) => (eventInteractionActive() ? current : mappedEvents()),
+ mappedEvents()
+ );
+ let interactionEventsById: Map<string, CalendarEvent> | undefined;
+
+ const eventByRenderId = (id: string) =>
+ interactionEventsById?.get(id) ?? props.eventsById.get(id);
+ const handleEventInteractionStart = () => {
+ interactionEventsById = props.eventsById;
+ setEventInteractionActive(true);
+ };
+ const handleEventInteractionStop = () => {
+ queueMicrotask(() => {
+ interactionEventsById = undefined;
+ setEventInteractionActive(false);
+ });
+ };
+
+ const eventElements = new Map<string, HTMLElement>();
+ const [chipMounts, notifyChipMount] = createSignal(undefined, {
+ equals: false,
+ });
+
+ return (
+ <FullCalendar.Root
+ plugins={[
+ dayGridPlugin,
+ interactionPlugin,
+ timeGridPlugin,
+ multiDaySelectionRenderingPlugin,
+ ]}
+ initialView={props.settings.initialView}
+ initialDate={props.initialDate}
+ height="100%"
+ expandRows
+ fixedWeekCount={false}
+ handleWindowResize={false}
+ allDayText="All day"
+ nowIndicator
+ headerToolbar={false}
+ scrollTime={getLocalScrollTime()}
+ scrollTimeReset={false}
+ weekends={props.settings.showWeekends}
+ firstDay={props.settings.weekStartsOn}
+ slotLabelFormat={CALENDAR_TIME_FORMAT_OPTIONS[props.settings.timeFormat]}
+ eventTimeFormat={CALENDAR_TIME_FORMAT_OPTIONS[props.settings.timeFormat]}
+ events={renderedEvents()}
+ eventAllow={() =>
+ props.onEventTimeChange !== undefined &&
+ props.eventTimeChangePending !== true
+ }
+ eventResizableFromStart
+ eventDragStart={handleEventInteractionStart}
+ eventDragStop={handleEventInteractionStop}
+ eventDrop={(change) =>
+ props.onEventTimeChange?.(
+ change,
+ eventByRenderId(calendarEventRenderId(change.event))
+ )
+ }
+ eventResizeStart={handleEventInteractionStart}
+ eventResizeStop={handleEventInteractionStop}
+ eventResize={(change) =>
+ props.onEventTimeChange?.(
+ change,
+ eventByRenderId(calendarEventRenderId(change.event))
+ )
+ }
+ selectable={props.selection.onDateSelect !== undefined && !isMobile()}
+ unselectAuto={false}
+ selectMirror
+ selectMinDistance={5}
+ select={(selection) => props.selection.onDateSelect?.(selection)}
+ eventClick={({ el, event, jsEvent }) => {
+ jsEvent.preventDefault();
+ const selectedEvent = eventByRenderId(calendarEventRenderId(event));
+ if (selectedEvent) props.selection.onEventSelect?.(selectedEvent, el);
+ }}
+ eventDidMount={({ el, event, isMirror }) => {
+ const eventId = calendarEventRenderId(event);
+ const calendarEvent = eventByRenderId(eventId);
+ if (calendarEvent) {
+ el.style.setProperty(
+ '--event-calendar-color',
+ calendarEvent.calendar.color
+ );
+ }
+ if (isMirror || isMultiDaySelectionPreview(event)) return;
+
+ eventElements.set(eventId, el);
+ if (props.selection.eventId === eventId) {
+ const selected = eventByRenderId(eventId);
+ if (selected) props.selection.onEventSelect?.(selected, el);
+ }
+ notifyChipMount();
+ }}
+ eventWillUnmount={({ el, event, isMirror }) => {
+ if (isMirror || isMultiDaySelectionPreview(event)) return;
+
+ const eventId = calendarEventRenderId(event);
+ if (eventElements.get(eventId) === el) {
+ eventElements.delete(eventId);
+ }
+ }}
+ datesSet={(info) => props.onDatesSet?.(info)}
+ dayHeaderFormat={{
+ weekday: props.settings.useNarrowDayHeaders ? 'narrow' : 'short',
+ }}
+ dayCellClassNames={({ date, view }) =>
+ isSameLocalDate(date, view.calendar.getDate())
+ ? ['calendar-day-selected']
+ : []
+ }
+ >
+ <FullCalendar.DayHeaderContent>
+ {({ date, text, view }) => {
+ if (view.type === 'timeGridWeek' || view.type === 'timeGridDay') {
+ const weekday =
+ view.type === 'timeGridDay'
+ ? formatWeekdayHeader.short(date)
+ : formatWeekdayHeader[
+ props.settings.useNarrowDayHeaders ? 'narrow' : 'short'
+ ](date);
+
+ return (
+ <>
+ <span class="calendar-day-header-weekday">{weekday}</span>{' '}
+ <span
+ class="calendar-day-header-date"
+ classList={{
+ 'calendar-day-header-date-selected': isSameLocalDate(
+ date,
+ view.calendar.getDate()
+ ),
+ }}
+ >
+ {formatDayNumber(date)}
+ </span>
+ </>
+ );
+ }
+ return text;
+ }}
+ </FullCalendar.DayHeaderContent>
+
+ <FullCalendar.SlotLabelContent>
+ {({ date }) =>
+ formatCompactCalendarTime(date, props.settings.timeFormat)
+ }
+ </FullCalendar.SlotLabelContent>
+
+ <FullCalendar.EventContent>
+ {(renderProps) => {
+ const event = eventByRenderId(
+ calendarEventRenderId(renderProps.event)
+ );
+ if (
+ !event &&
+ (isMultiDaySelectionPreview(renderProps.event) ||
+ (renderProps.isMirror &&
+ !renderProps.isDragging &&
+ !renderProps.isResizing))
+ ) {
+ return (
+ <div class="calendar-event-selection-preview flex h-full min-w-0 flex-col overflow-hidden px-1 py-0.5 text-xs leading-tight">
+ <span class="truncate font-semibold">New event</span>
+ <Show when={renderProps.timeText}>
+ <span class="truncate">{renderProps.timeText}</span>
+ </Show>
+ </div>
+ );
+ }
+ if (!event) return null;
+
+ return (
+ <EventContent
+ event={event}
+ renderProps={renderProps}
+ isSelected={props.selection.eventId === event.id}
+ timeFormat={props.settings.timeFormat}
+ isNarrow={props.settings.useNarrowEventContent}
+ />
+ );
+ }}
+ </FullCalendar.EventContent>
+
+ <FullCalendar.NowIndicatorContent>
+ {({ isAxis }) => {
+ if (isAxis) return null;
+
+ return (
+ <CurrentTimeAxisIndicator
+ date={new Date()}
+ timeFormat={props.settings.timeFormat}
+ />
+ );
+ }}
+ </FullCalendar.NowIndicatorContent>
+
+ <CalendarGridHost
+ selectionColor={props.selection.color}
+ eventElements={eventElements}
+ chipMounts={chipMounts}
+ children={props.children}
+ />
+ </FullCalendar.Root>
+ );
+}
diff --git a/apps/web/src/features/calendar/components/CalendarPagerContext.tsx b/apps/web/src/features/calendar/components/CalendarPagerContext.tsx
new file mode 100644
index 0000000000..7034b71af4
--- /dev/null
+++ b/apps/web/src/features/calendar/components/CalendarPagerContext.tsx
@@ -0,0 +1,310 @@
+import { createAssertedContextProvider } from '@core/context/createContext';
+import type { Calendar, DatesSetArg } from '@fullcalendar/core';
+import { createPager, type PagerController } from '@ui/components/Pager';
+import {
+ type Accessor,
+ batch,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+ type ParentProps,
+} from 'solid-js';
+import type { CalendarOccurrenceData } from '../hooks/use-calendar-occurrence-data';
+import type { CalendarPeriodView } from '../types';
+
+export const CALENDAR_PAGE_IDS = ['previous', 'current', 'next'] as const;
+export type CalendarPageId = (typeof CALENDAR_PAGE_IDS)[number];
+
+const TIME_GRID_SCROLLER_SELECTOR =
+ '.fc-timegrid .fc-scroller-harness-liquid > .fc-scroller';
+
+interface CalendarPageHandle {
+ id: CalendarPageId;
+ api: Accessor<Calendar | undefined>;
+ dateInfo: Accessor<DatesSetArg | undefined>;
+ element: Accessor<HTMLDivElement | undefined>;
+ data: CalendarOccurrenceData;
+}
+
+const shiftedDateForView = (
+ date: Date,
+ view: CalendarPeriodView,
+ offset: -1 | 1
+) => {
+ const shifted = new Date(date);
+ if (view === 'dayGridMonth') {
+ shifted.setDate(1);
+ shifted.setMonth(shifted.getMonth() + offset);
+ } else {
+ shifted.setDate(
+ shifted.getDate() + (view === 'timeGridDay' ? offset : offset * 7)
+ );
+ }
+ return shifted;
+};
+
+interface CalendarPagerContextProps extends ParentProps {
+ [key: string]: unknown;
+ initialView: CalendarPeriodView;
+ showWeekends: Accessor<boolean>;
+ weekStartsOn: Accessor<number>;
+ onNavigate: () => void;
+ onViewChange: (view: CalendarPeriodView) => void;
+}
+
+function createCalendarPagerContext(props: CalendarPagerContextProps) {
+ const initialDate = new Date();
+ const initialView = props.initialView;
+ const initialDates: Record<CalendarPageId, Date> = {
+ previous: shiftedDateForView(initialDate, initialView, -1),
+ current: initialDate,
+ next: shiftedDateForView(initialDate, initialView, 1),
+ };
+
+ const [pageOrder, setPageOrder] =
+ createSignal<readonly CalendarPageId[]>(CALENDAR_PAGE_IDS);
+
+ const [activePageId, setActivePageId] =
+ createSignal<CalendarPageId>('current');
+
+ const [listenForPageRegistryChange, notifyPageRegistryChange] =
+ createSignal<void>(undefined, { equals: false });
+
+ const pageHandles = new Map<CalendarPageId, CalendarPageHandle>();
+
+ const pageHandle = (id: CalendarPageId) => {
+ listenForPageRegistryChange();
+ return pageHandles.get(id);
+ };
+
+ const activePage = createMemo(() => pageHandle(activePageId()));
+ const activeData = createMemo(() => activePage()?.data);
+ const activeDateInfo = createMemo(() => activePage()?.dateInfo());
+
+ const scrollElementFor = (handle: CalendarPageHandle | undefined) => {
+ const element = handle?.element();
+ if (!element) return undefined;
+
+ return element.querySelector<HTMLElement>(TIME_GRID_SCROLLER_SELECTOR);
+ };
+
+ const copyActiveScrollPosition = () => {
+ const activeScrollElement = scrollElementFor(activePage());
+ if (!activeScrollElement) return;
+
+ for (const id of pageOrder()) {
+ if (id === activePageId()) continue;
+ const scrollElement = scrollElementFor(pageHandle(id));
+ if (!scrollElement) continue;
+
+ scrollElement.scrollTop = activeScrollElement.scrollTop;
+ }
+ };
+
+ const synchronizePage = (
+ handle: CalendarPageHandle | undefined,
+ source: CalendarPageHandle | undefined,
+ direction: 'previous' | 'next'
+ ) => {
+ const api = handle?.api();
+ const sourceApi = source?.api();
+ if (!api || !sourceApi) return;
+
+ const date = sourceApi.getDate();
+ const view = sourceApi.view.type;
+ api.batchRendering(() => {
+ if (api.view.type === view) {
+ api.gotoDate(date);
+ } else {
+ api.changeView(view, date);
+ }
+
+ if (direction === 'previous') {
+ api.prev();
+ } else {
+ api.next();
+ }
+ });
+ };
+
+ const synchronizeBuffers = () => {
+ const order = pageOrder();
+ const activeIndex = order.indexOf(activePageId());
+ const current = activePage();
+ const previousId = order[activeIndex - 1];
+ const nextId = order[activeIndex + 1];
+ if (previousId) {
+ synchronizePage(pageHandle(previousId), current, 'previous');
+ }
+
+ if (nextId) {
+ synchronizePage(pageHandle(nextId), current, 'next');
+ }
+
+ requestAnimationFrame(copyActiveScrollPosition);
+ };
+
+ const rotatePages = (
+ destination: CalendarPageId,
+ direction: 'previous' | 'next'
+ ) => {
+ const order = pageOrder();
+ const recycledId =
+ direction === 'next' ? order[0] : order[order.length - 1];
+ const nextOrder =
+ direction === 'next'
+ ? [...order.slice(1), order[0]]
+ : [order[order.length - 1], ...order.slice(0, -1)];
+
+ props.onNavigate();
+ batch(() => {
+ setPageOrder(nextOrder);
+ setActivePageId(() => destination);
+ });
+
+ const current = pageHandle(destination);
+ synchronizePage(pageHandle(recycledId), current, direction);
+ requestAnimationFrame(copyActiveScrollPosition);
+ };
+
+ const pager: PagerController<CalendarPageId> = createPager({
+ pageOrder,
+ activePage: activePageId,
+ canChangePage: ({ to }) => pageHandle(to)?.api() !== undefined,
+ onDragStart: copyActiveScrollPosition,
+ onTransitionStart: () => {
+ props.onNavigate();
+ copyActiveScrollPosition();
+ },
+ onPageChange: (destination, { direction }) =>
+ rotatePages(destination, direction),
+ });
+
+ const registerPage = (handle: CalendarPageHandle) => {
+ pageHandles.set(handle.id, handle);
+ notifyPageRegistryChange();
+
+ return () => {
+ if (pageHandles.get(handle.id) !== handle) return;
+ pageHandles.delete(handle.id);
+ notifyPageRegistryChange();
+ };
+ };
+
+ let settingsSyncFrame: number | undefined;
+ createEffect(
+ on(
+ () => [props.showWeekends(), props.weekStartsOn()],
+ (_settings, previousSettings) => {
+ if (previousSettings === undefined) return;
+ if (settingsSyncFrame !== undefined) {
+ cancelAnimationFrame(settingsSyncFrame);
+ }
+ settingsSyncFrame = requestAnimationFrame(() => {
+ settingsSyncFrame = undefined;
+ synchronizeBuffers();
+ });
+ }
+ )
+ );
+ onCleanup(() => {
+ if (settingsSyncFrame !== undefined) {
+ cancelAnimationFrame(settingsSyncFrame);
+ }
+ });
+
+ const updateSize = () => {
+ listenForPageRegistryChange();
+
+ for (const handle of pageHandles.values()) {
+ handle.api()?.updateSize();
+ }
+ };
+
+ const gotoDate = (date: Date) => {
+ pager.cancel();
+ props.onNavigate();
+ activePage()?.api()?.gotoDate(date);
+ synchronizeBuffers();
+ };
+
+ const navigateToDate = (date: Date) => {
+ pager.cancel();
+
+ const sourceApi = activePage()?.api();
+ if (!sourceApi) return;
+
+ if (
+ date >= sourceApi.view.currentStart &&
+ date < sourceApi.view.currentEnd
+ ) {
+ gotoDate(date);
+ return;
+ }
+
+ const direction = date < sourceApi.view.currentStart ? 'previous' : 'next';
+ const order = pageOrder();
+ const activeIndex = order.indexOf(activePageId());
+ const destinationId =
+ direction === 'previous'
+ ? order[activeIndex - 1]
+ : order[activeIndex + 1];
+ const destinationApi = destinationId
+ ? pageHandle(destinationId)?.api()
+ : undefined;
+
+ if (!destinationApi) {
+ gotoDate(date);
+ return;
+ }
+
+ destinationApi.batchRendering(() => {
+ if (destinationApi.view.type === sourceApi.view.type) {
+ destinationApi.gotoDate(date);
+ } else {
+ destinationApi.changeView(sourceApi.view.type, date);
+ }
+ });
+
+ const transition =
+ direction === 'previous' ? pager.previous() : pager.next();
+ void transition.then(synchronizeBuffers);
+ };
+
+ const changeView = (view: CalendarPeriodView) => {
+ props.onViewChange(view);
+
+ const api = activePage()?.api();
+ if (!api || api.view.type === view) return;
+ pager.cancel();
+ props.onNavigate();
+ api.changeView(view);
+ synchronizeBuffers();
+ };
+
+ return {
+ pager,
+ pageOrder,
+ activePageId,
+ activePage,
+ activeData,
+ activeDateInfo,
+ visibleRange: () => activeData()?.range(),
+ initialDateFor: (id: CalendarPageId) => initialDates[id],
+ isActive: (id: CalendarPageId) => activePageId() === id,
+ registerPage,
+ updateSize,
+ gotoDate,
+ navigateToDate,
+ navigateToToday: () => navigateToDate(new Date()),
+ changeView,
+ };
+}
+
+export const [CalendarPagerContextProvider, useCalendarPager] =
+ createAssertedContextProvider<
+ ReturnType<typeof createCalendarPagerContext>,
+ CalendarPagerContextProps
+ >('CalendarPagerContext', createCalendarPagerContext);
diff --git a/apps/web/src/features/calendar/CalendarSettingsDropdown.tsx b/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx
similarity index 96%
rename from apps/web/src/features/calendar/CalendarSettingsDropdown.tsx
rename to apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx
index 0e6e64c231..5c164db4ea 100644
--- a/apps/web/src/features/calendar/CalendarSettingsDropdown.tsx
+++ b/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx
@@ -1,18 +1,17 @@
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
-import { useSidePanel } from '@components/app/side-panel/SidePanel';
import { isMobile } from '@core/mobile/isMobile';
import CaretRightIcon from '@phosphor/caret-right.svg';
import CheckIcon from '@phosphor/check.svg';
import GearIcon from '@phosphor/gear.svg';
import { Button, Checkbox, Dropdown } from '@ui';
import { createMemo, createSignal, For, Show } from 'solid-js';
-import { MobileCalendarPeriodControls } from './CalendarPeriodSelector';
+import { useCalendarConnectedInboxes } from '../hooks/use-calendar-connected-inboxes';
+import type { CalendarTimeFormat, CalendarWeekStart } from '../types';
import { useCalendarView } from './CalendarViewContext';
-import type { CalendarTimeFormat, CalendarWeekStart } from './events/types';
+import { MobilePeriodControls } from './PeriodSelector';
import {
TurnOffCalendarDialog,
type TurnOffCalendarTarget,
- useCalendarConnectedInboxes,
} from './TurnOffCalendarDialog';
const WEEK_START_OPTIONS: Array<{
@@ -31,15 +30,14 @@ const TIME_FORMAT_OPTIONS: Array<{
{ value: '24-hour', label: '24-hour' },
];
-function createCalendarSettingsControls() {
+function createCalendarSettingsControls(isNarrow: () => boolean) {
const calendarView = useCalendarView();
- const sidePanel = useSidePanel();
const connectedInboxes = useCalendarConnectedInboxes();
const [turnOffTarget, setTurnOffTarget] =
createSignal<TurnOffCalendarTarget | null>(null);
const showCalendarVisibility = () =>
- (sidePanel?.isNarrow() ?? false) && calendarView.sources().length > 1;
+ isNarrow() && calendarView.sources().length > 1;
const weekStartLabel = createMemo(
() =>
@@ -291,7 +289,7 @@ function MobileCalendarSettings(props: { controls: CalendarSettingsControls }) {
class="overflow-y-auto"
>
<MobileDrawer.Handle />
- <MobileCalendarPeriodControls onSelect={() => setOpen(false)} />
+ <MobilePeriodControls onSelect={() => setOpen(false)} />
<Show when={controls.showCalendarVisibility()}>
<MobileDrawer.Label>Calendars</MobileDrawer.Label>
@@ -418,8 +416,10 @@ function MobileCalendarSettings(props: { controls: CalendarSettingsControls }) {
* Responsive calendar display settings menu. The turn-off confirmation lives
* outside the menu so it survives the menu closing on select.
*/
-export function CalendarSettingsDropdown() {
- const controls = createCalendarSettingsControls();
+export function CalendarSettingsDropdown(props: { isNarrow?: boolean }) {
+ const controls = createCalendarSettingsControls(
+ () => props.isNarrow ?? false
+ );
return (
<>
diff --git a/apps/web/src/features/calendar/CalendarViewContext.tsx b/apps/web/src/features/calendar/components/CalendarViewContext.tsx
similarity index 54%
rename from apps/web/src/features/calendar/CalendarViewContext.tsx
rename to apps/web/src/features/calendar/components/CalendarViewContext.tsx
index f129b4dce9..85e7278943 100644
--- a/apps/web/src/features/calendar/CalendarViewContext.tsx
+++ b/apps/web/src/features/calendar/components/CalendarViewContext.tsx
@@ -1,24 +1,16 @@
import { createAssertedContextProvider } from '@core/context/createContext';
import { isMobile } from '@core/mobile/isMobile';
-import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
import { makePersisted } from '@solid-primitives/storage';
-import { batch, createMemo, createSignal } from 'solid-js';
+import { batch, createSignal } from 'solid-js';
import { createStore } from 'solid-js/store';
-import { calendarDisplayLabel, spansMultipleInboxes } from './calendar-label';
-import { DEFAULT_CALENDAR_SOURCE } from './events/calendar-occurrence-mapper';
+import { useCalendarSources } from '../hooks/use-calendar-sources';
import type {
CalendarEvent,
CalendarPeriodView,
- CalendarSource,
CalendarTimeFormat,
CalendarWeekStart,
-} from './events/types';
-import { getDefaultCalendarTimeFormat } from './time-format';
-
-interface CalendarEventState {
- readonly visibleSourceIds: string[];
- readonly selectedEventId: string | undefined;
-}
+} from '../types';
+import { getDefaultCalendarTimeFormat } from '../utils/time-format';
interface CalendarDisplaySettings {
readonly periodView: CalendarPeriodView;
@@ -37,6 +29,29 @@ interface CalendarPreferences {
const CALENDAR_PREFERENCES_KEY = 'macro:pref:calendar:settings';
+function createCalendarEventSelection() {
+ const [event, setEvent] = createSignal<CalendarEvent>();
+ const [anchor, setAnchor] = createSignal<HTMLElement>();
+
+ const close = () => {
+ batch(() => {
+ setEvent(undefined);
+ setAnchor(undefined);
+ });
+ };
+ const select = (nextEvent: CalendarEvent, nextAnchor: HTMLElement) => {
+ batch(() => {
+ setEvent(() => nextEvent);
+ setAnchor(nextAnchor);
+ });
+ };
+ const refresh = (nextEvent: CalendarEvent) => {
+ if (event()?.id === nextEvent.id) setEvent(nextEvent);
+ };
+
+ return { anchor, close, event, refresh, select };
+}
+
export const [CalendarViewContextProvider, useCalendarView] =
createAssertedContextProvider('CalendarViewContext', () => {
const defaultPreferences: CalendarPreferences = {
@@ -56,39 +71,14 @@ export const [CalendarViewContextProvider, useCalendarView] =
}),
}
);
- const calendarsQuery = useVisibleCalendarsQuery();
- const sources = createMemo<CalendarSource[]>(() => {
- const calendars = calendarsQuery.data;
- if (!calendars || calendars.length === 0) {
- return [DEFAULT_CALENDAR_SOURCE];
- }
- const spansInboxes = spansMultipleInboxes(calendars);
- return calendars.map((calendar) => ({
- id: calendar.id,
- name: calendarDisplayLabel(calendar, spansInboxes),
- color: calendar.color ?? DEFAULT_CALENDAR_SOURCE.color,
- }));
- });
- const sourceById = createMemo(
- () => new Map(sources().map((source) => [source.id, source]))
- );
+ const { sources, sourceById } = useCalendarSources();
// Sources default to visible, so calendars discovered after a
// preference was saved (or events whose calendar is still loading)
// never silently disappear.
const isSourceVisible = (sourceId: string) =>
!preferences.hiddenSourceIds.includes(sourceId);
- const [selectedEventId, setSelectedEventId] = createSignal<string>();
- const eventState: CalendarEventState = {
- get visibleSourceIds() {
- return sources()
- .filter((source) => isSourceVisible(source.id))
- .map((source) => source.id);
- },
- get selectedEventId() {
- return selectedEventId();
- },
- };
+ const selection = createCalendarEventSelection();
const displaySettings: CalendarDisplaySettings = {
get periodView() {
return preferences.periodView;
@@ -104,18 +94,7 @@ export const [CalendarViewContextProvider, useCalendarView] =
},
};
- const [selectedEvent, setSelectedEvent] = createSignal<CalendarEvent>();
- const [selectedEventAnchor, setSelectedEventAnchor] =
- createSignal<HTMLElement>();
- const [useNarrowDayHeaders, setUseNarrowDayHeaders] = createSignal(false);
-
- const closeEventDetails = () => {
- batch(() => {
- setSelectedEventId(undefined);
- setSelectedEvent(undefined);
- setSelectedEventAnchor(undefined);
- });
- };
+ const closeEventDetails = selection.close;
const setSourceVisibility = (sourceId: string, visible: boolean) => {
setPreferences('hiddenSourceIds', (current) =>
@@ -126,35 +105,19 @@ export const [CalendarViewContextProvider, useCalendarView] =
: [...current, sourceId]
);
- if (!visible && selectedEvent()?.calendar.id === sourceId) {
+ if (!visible && selection.event()?.calendar.id === sourceId) {
closeEventDetails();
}
};
- const selectEvent = (event: CalendarEvent, anchor: HTMLElement) => {
- batch(() => {
- setSelectedEventId(event.id);
- setSelectedEvent(() => event);
- setSelectedEventAnchor(anchor);
- });
- };
-
- const refreshSelectedEvent = (event: CalendarEvent) => {
- if (eventState.selectedEventId !== event.id) return;
- setSelectedEvent(event);
- };
-
return {
- eventState,
displaySettings,
sources,
sourceById,
isSourceVisible,
setSourceVisibility,
- selectedEvent,
- selectedEventAnchor,
- useNarrowDayHeaders,
- setUseNarrowDayHeaders,
+ selectedEvent: selection.event,
+ selectedEventAnchor: selection.anchor,
setPeriodView: (periodView: CalendarPeriodView) =>
setPreferences('periodView', periodView),
setShowWeekends: (showWeekends: boolean) =>
@@ -164,7 +127,7 @@ export const [CalendarViewContextProvider, useCalendarView] =
setTimeFormat: (timeFormat: CalendarTimeFormat) =>
setPreferences('timeFormat', timeFormat),
closeEventDetails,
- selectEvent,
- refreshSelectedEvent,
+ selectEvent: selection.select,
+ refreshSelectedEvent: selection.refresh,
};
});
diff --git a/apps/web/src/features/calendar/events/EventContent.tsx b/apps/web/src/features/calendar/components/EventContent.tsx
similarity index 93%
rename from apps/web/src/features/calendar/events/EventContent.tsx
rename to apps/web/src/features/calendar/components/EventContent.tsx
index 7f4e7946ab..24a3a04ff2 100644
--- a/apps/web/src/features/calendar/events/EventContent.tsx
+++ b/apps/web/src/features/calendar/components/EventContent.tsx
@@ -1,13 +1,13 @@
import type { EventContentArg } from '@fullcalendar/core';
import { cn } from '@ui';
import { Show } from 'solid-js';
+import type { CalendarEvent, CalendarTimeFormat } from '../types';
import {
formatCompactCalendarTime,
formatCompactCalendarTimeRange,
-} from '../time-format';
-import type { CalendarEvent, CalendarTimeFormat } from './types';
+} from '../utils/time-format';
-interface CalendarEventContentProps {
+interface EventContentProps {
event: CalendarEvent;
renderProps: EventContentArg;
isSelected: boolean;
@@ -18,7 +18,7 @@ interface CalendarEventContentProps {
const SINGLE_LINE_EVENT_DURATION_MS = 15 * 60 * 1000;
/** Renders responsive event content for FullCalendar. */
-export function CalendarEventContent(props: CalendarEventContentProps) {
+export function EventContent(props: EventContentProps) {
const isRenderedAllDay = () => props.renderProps.event.allDay;
const isCompact = () =>
isRenderedAllDay() || props.renderProps.view.type === 'dayGridMonth';
diff --git a/apps/web/src/features/calendar/events/EventDetails.tsx b/apps/web/src/features/calendar/components/EventDetails.tsx
similarity index 92%
rename from apps/web/src/features/calendar/events/EventDetails.tsx
rename to apps/web/src/features/calendar/components/EventDetails.tsx
index 5b7233da22..7015fadaca 100644
--- a/apps/web/src/features/calendar/events/EventDetails.tsx
+++ b/apps/web/src/features/calendar/components/EventDetails.tsx
@@ -20,9 +20,9 @@ import PersonIcon from '@phosphor/user.svg';
import UsersIcon from '@phosphor/users.svg';
import VideoCameraIcon from '@phosphor/video-camera.svg';
import XIcon from '@phosphor/x.svg';
-import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
import type { AttendeeResponseStatus } from '@service-storage/generated/schemas/attendeeResponseStatus';
import type { CalendarAttendee } from '@service-storage/generated/schemas/calendarAttendee';
+import type { EventReminderOverride } from '@service-storage/generated/schemas/eventReminderOverride';
import { Avatar, Button, cn } from '@ui';
import {
type Accessor,
@@ -33,17 +33,18 @@ import {
Show,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
-import {
- CALENDAR_TIME_FORMAT_OPTIONS,
- formatCalendarTime,
-} from '../time-format';
+import type { CalendarEvent, CalendarTimeFormat } from '../types';
+import { isSameLocalDate, parseLocalDate } from '../utils/calendar-date';
import {
formatReminderOffset,
REMINDER_METHOD_POPUP,
resolveReminderOverrides,
-} from './event-reminders';
-import { formatRecurrenceDescription } from './recurrence-description';
-import type { CalendarEvent, CalendarTimeFormat } from './types';
+} from '../utils/event-reminders';
+import { formatRecurrenceDescription } from '../utils/recurrence';
+import {
+ CALENDAR_TIME_FORMAT_OPTIONS,
+ formatCalendarTime,
+} from '../utils/time-format';
const formatDate = new Intl.DateTimeFormat(undefined, {
weekday: 'short',
@@ -54,9 +55,6 @@ const formatShortDate = new Intl.DateTimeFormat(undefined, {
month: 'short',
day: 'numeric',
});
-const DATE_ONLY_REGEX = /^\d{4}-\d{2}-\d{2}$/;
-const isDateOnly = (value: string) => DATE_ONLY_REGEX.test(value);
-
const ATTENDEE_RESPONSE = {
accepted: {
label: 'Accepted',
@@ -224,7 +222,7 @@ function CalendarAttendeeItem(props: {
);
}
-export interface CalendarAttendeeListProps {
+interface CalendarAttendeeListProps {
attendees: CalendarAttendee[];
organizerFirst?: boolean;
itemClass?: (attendee: CalendarAttendee) => string | undefined;
@@ -232,7 +230,7 @@ export interface CalendarAttendeeListProps {
}
/** Resolved attendee rows shared by event details and read-only guest views. */
-export function CalendarAttendeeList(props: CalendarAttendeeListProps) {
+function CalendarAttendeeList(props: CalendarAttendeeListProps) {
const sortedAttendees = createMemo(() =>
props.attendees
.map(resolveCalendarAttendee)
@@ -282,17 +280,9 @@ function ScrollableAttendeeList(props: { attendees: CalendarAttendee[] }) {
}
function parseCalendarDate(value: string) {
- if (!isDateOnly(value)) return new Date(value);
-
- const [year, month, day] = value.split('-').map(Number);
- return new Date(year ?? 0, (month ?? 1) - 1, day ?? 1);
+ return parseLocalDate(value) ?? new Date(value);
}
-const isSameLocalDate = (first: Date, second: Date) =>
- first.getFullYear() === second.getFullYear() &&
- first.getMonth() === second.getMonth() &&
- first.getDate() === second.getDate();
-
function formatEventSchedule(
event: CalendarEvent,
timeFormat: CalendarTimeFormat
@@ -350,17 +340,16 @@ function findOrganizer(event: CalendarEvent): CalendarOrganizer | undefined {
* it departed from the calendar defaults, the calendar defaults otherwise.
* Nothing renders while the calendar (and so its defaults) is unknown.
*/
-function EventRemindersItem(props: { event: CalendarEvent }) {
- const calendarsQuery = useVisibleCalendarsQuery();
- const reminders = createMemo(() => {
- const calendar = calendarsQuery.data?.find(
- (candidate) => candidate.id === props.event.calendarId
- );
- return resolveReminderOverrides(
+function EventRemindersItem(props: {
+ event: CalendarEvent;
+ defaultReminders?: EventReminderOverride[];
+}) {
+ const reminders = createMemo(() =>
+ resolveReminderOverrides(
props.event.reminders,
- calendar?.defaultReminders
- ).toSorted((a, b) => a.minutes - b.minutes);
- });
+ props.defaultReminders
+ ).toSorted((a, b) => a.minutes - b.minutes)
+ );
return (
<Show when={reminders().length > 0}>
@@ -442,6 +431,7 @@ function formatOriginalTimeZone(
export function EventDetails(props: {
event: CalendarEvent;
timeFormat: CalendarTimeFormat;
+ defaultReminders?: EventReminderOverride[];
}) {
const conferenceUrl = createMemo(() =>
safeConferenceUrl(props.event.conferenceUrl)
@@ -539,7 +529,10 @@ export function EventDetails(props: {
)}
</Show>
- <EventRemindersItem event={props.event} />
+ <EventRemindersItem
+ event={props.event}
+ defaultReminders={props.defaultReminders}
+ />
<Show when={organizer()}>
{(eventOrganizer) => (
diff --git a/apps/web/src/features/calendar/CalendarMonthDrawer.tsx b/apps/web/src/features/calendar/components/MonthDrawer.tsx
similarity index 94%
rename from apps/web/src/features/calendar/CalendarMonthDrawer.tsx
rename to apps/web/src/features/calendar/components/MonthDrawer.tsx
index a1e469e78b..a83b0523d9 100644
--- a/apps/web/src/features/calendar/CalendarMonthDrawer.tsx
+++ b/apps/web/src/features/calendar/components/MonthDrawer.tsx
@@ -4,12 +4,12 @@ import { Button, CalendarMonthMenu, formatCalendarMonth } from '@ui';
import { createSignal } from 'solid-js';
import { useCalendarPager } from './CalendarPagerContext';
-type CalendarMonthDrawerProps = {
+type MonthDrawerProps = {
month: Date;
};
/** Drawer presentation for navigating the calendar to a month. */
-export function CalendarMonthDrawer(props: CalendarMonthDrawerProps) {
+export function MonthDrawer(props: MonthDrawerProps) {
const calendarPager = useCalendarPager();
const [open, setOpen] = createSignal(false);
diff --git a/apps/web/src/features/calendar/CalendarPeriodSelector.tsx b/apps/web/src/features/calendar/components/PeriodSelector.tsx
similarity index 94%
rename from apps/web/src/features/calendar/CalendarPeriodSelector.tsx
rename to apps/web/src/features/calendar/components/PeriodSelector.tsx
index e8dcab7f77..bf87acea41 100644
--- a/apps/web/src/features/calendar/CalendarPeriodSelector.tsx
+++ b/apps/web/src/features/calendar/components/PeriodSelector.tsx
@@ -1,5 +1,4 @@
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
-import { useSidePanel } from '@components/app/side-panel/SidePanel';
import { type HotkeyToken, TOKENS } from '@core/hotkey/tokens';
import CalendarIcon from '@phosphor/calendar-blank.svg';
import CaretDownIcon from '@phosphor/caret-down.svg';
@@ -8,10 +7,10 @@ import CheckIcon from '@phosphor/check.svg';
import { Dropdown, Hotkey, Calendar as MiniCalendar } from '@ui';
import { createMemo, For, Show } from 'solid-js';
import { createStore } from 'solid-js/store';
+import type { CalendarPeriodView } from '../types';
+import { calendarPeriodLabel } from '../utils/calendar-label';
import { useCalendarPager } from './CalendarPagerContext';
import { useCalendarView } from './CalendarViewContext';
-import { calendarPeriodLabel } from './calendar-label';
-import type { CalendarPeriodView } from './events/types';
const CALENDAR_VIEWS = [
{
@@ -139,10 +138,8 @@ function CustomDatePicker(props: { controls: CalendarPeriodControls }) {
}
/** Desktop calendar period selector and custom-date dropdown. */
-export function CalendarPeriodSelector() {
- const sidePanel = useSidePanel();
+export function PeriodSelector(props: { isNarrow?: boolean }) {
const controls = createCalendarPeriodControls();
- const isNarrow = () => sidePanel?.isNarrow() ?? false;
return (
<Dropdown
@@ -180,7 +177,7 @@ export function CalendarPeriodSelector() {
</For>
</Dropdown.RadioGroup>
</Dropdown.Group>
- <Show when={isNarrow()}>
+ <Show when={props.isNarrow}>
<Dropdown.Group>
<Dropdown.Sub>
<Dropdown.SubTrigger>
@@ -202,7 +199,7 @@ export function CalendarPeriodSelector() {
}
/** Period controls embedded in the mobile settings drawer. */
-export function MobileCalendarPeriodControls(props: { onSelect: () => void }) {
+export function MobilePeriodControls(props: { onSelect: () => void }) {
const controls = createCalendarPeriodControls(props.onSelect);
return (
diff --git a/apps/web/src/features/calendar/CalendarRangeUnavailableBanner.tsx b/apps/web/src/features/calendar/components/RangeUnavailableBanner.tsx
similarity index 93%
rename from apps/web/src/features/calendar/CalendarRangeUnavailableBanner.tsx
rename to apps/web/src/features/calendar/components/RangeUnavailableBanner.tsx
index 9e8153efbc..0850313a01 100644
--- a/apps/web/src/features/calendar/CalendarRangeUnavailableBanner.tsx
+++ b/apps/web/src/features/calendar/components/RangeUnavailableBanner.tsx
@@ -2,11 +2,11 @@ import InfoIcon from '@phosphor/info.svg';
import { cn } from '@ui';
import { createMemo, Show } from 'solid-js';
import { Transition } from 'solid-transition-group';
+import { isCalendarRangeSupported } from '../utils/calendar-supported-range';
import { useCalendarPager } from './CalendarPagerContext';
-import { isCalendarRangeSupported } from './calendar-supported-range';
/** Announces when the visible viewport is outside backend occurrence coverage. */
-export function CalendarRangeUnavailableBanner(props: {
+export function RangeUnavailableBanner(props: {
class?: string;
fullWidth?: boolean;
}) {
diff --git a/apps/web/src/features/calendar/events/CalendarControls.tsx b/apps/web/src/features/calendar/components/SourceControls.tsx
similarity index 87%
rename from apps/web/src/features/calendar/events/CalendarControls.tsx
rename to apps/web/src/features/calendar/components/SourceControls.tsx
index 757542a791..d4d377d288 100644
--- a/apps/web/src/features/calendar/events/CalendarControls.tsx
+++ b/apps/web/src/features/calendar/components/SourceControls.tsx
@@ -1,15 +1,15 @@
import { Checkbox } from '@ui';
import { For } from 'solid-js';
-import type { CalendarSource } from './types';
+import type { CalendarSource } from '../types';
-interface CalendarControlsProps {
+interface SourceControlsProps {
sources: CalendarSource[];
isVisible: (sourceId: string) => boolean;
onVisibilityChange: (sourceId: string, visible: boolean) => void;
}
/** Controls which calendar sources are visible in the calendar. */
-export function CalendarControls(props: CalendarControlsProps) {
+export function SourceControls(props: SourceControlsProps) {
return (
<div class="flex flex-col gap-0.5">
<For each={props.sources}>
diff --git a/apps/web/src/features/calendar/TurnOffCalendarDialog.test.tsx b/apps/web/src/features/calendar/components/TurnOffCalendarDialog.test.tsx
similarity index 100%
rename from apps/web/src/features/calendar/TurnOffCalendarDialog.test.tsx
rename to apps/web/src/features/calendar/components/TurnOffCalendarDialog.test.tsx
diff --git a/apps/web/src/features/calendar/TurnOffCalendarDialog.tsx b/apps/web/src/features/calendar/components/TurnOffCalendarDialog.tsx
similarity index 68%
rename from apps/web/src/features/calendar/TurnOffCalendarDialog.tsx
rename to apps/web/src/features/calendar/components/TurnOffCalendarDialog.tsx
index 0a969d223f..9b21efc7c9 100644
--- a/apps/web/src/features/calendar/TurnOffCalendarDialog.tsx
+++ b/apps/web/src/features/calendar/components/TurnOffCalendarDialog.tsx
@@ -1,12 +1,6 @@
import { toast } from '@core/component/Toast/Toast';
-import { useUserId } from '@core/context/user';
-import {
- useDisableCalendarMutation,
- useEmailLinksQuery,
-} from '@queries/email/link';
-import type { Link as EmailLink } from '@service-email/generated/schemas';
+import { useDisableCalendarMutation } from '@queries/email/link';
import { Button, Dialog, Panel } from '@ui';
-import { createMemo } from 'solid-js';
/** The inbox a turn-off confirmation is about. */
export interface TurnOffCalendarTarget {
@@ -14,27 +8,6 @@ export interface TurnOffCalendarTarget {
emailAddress: string;
}
-/**
- * The viewer's own inboxes whose calendar Macro can still remove, in the order
- * the links list returns them. Delegated inboxes are excluded: the viewer can
- * read the owner's calendar but must not be able to delete the owner's data.
- *
- * An inbox needing reauth still counts, and so does one whose grant no longer
- * satisfies today's capability check — in both cases its events are still in
- * Macro, and turning calendar off is the way to remove them.
- */
-export function useCalendarConnectedInboxes() {
- const linksQuery = useEmailLinksQuery();
- const userId = useUserId();
- return createMemo<EmailLink[]>(() =>
- (linksQuery.data?.links ?? []).filter(
- (link) =>
- link.macro_id === userId() &&
- (!link.needs_calendar_permission || link.has_calendar_data)
- )
- );
-}
-
/**
* Confirms turning calendar off for one inbox and runs the disable. Shared by
* the connected-accounts settings row and the calendar view's settings menu so
diff --git a/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx b/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx
new file mode 100644
index 0000000000..83e190cce3
--- /dev/null
+++ b/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx
@@ -0,0 +1,280 @@
+import type { CollectionNode } from '@kobalte/core';
+import { Listbox } from '@kobalte/core/listbox';
+import { Popover } from '@kobalte/core/popover';
+import CalendarBlankIcon from '@phosphor/calendar-blank.svg';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+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 { formatLocalDate, parseLocalDate } from '../../utils/calendar-date';
+
+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"
+ >
+ <Listbox.ItemLabel>{props.rawValue.label}</Listbox.ItemLabel>
+ <Listbox.ItemIndicator class="text-accent">
+ <CheckIcon class="size-3.5" />
+ </Listbox.ItemIndicator>
+ </Listbox.Item>
+ );
+}
+
+interface EventTimeInputProps {
+ id: string;
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ onFocus?: () => void;
+ disabled?: boolean;
+ hideLabel?: boolean;
+ class?: string;
+}
+
+export function EventTimeInput(props: EventTimeInputProps) {
+ const [open, setOpen] = createSignal(false);
+ let control: HTMLDivElement | undefined;
+ let listbox: HTMLElement | undefined;
+
+ const selectedTime = createMemo(() => [props.value]);
+ const scrollToSelectedTime = () => {
+ requestAnimationFrame(() => {
+ listbox
+ ?.querySelector<HTMLElement>('[data-selected]')
+ ?.scrollIntoView({ block: 'center' });
+ });
+ };
+ const setDropdownOpen = (nextOpen: boolean) => {
+ if (props.disabled) return;
+ setOpen(nextOpen);
+ 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);
+ setOpen(false);
+ };
+
+ return (
+ <Popover
+ anchorRef={() => control}
+ open={open() && !props.disabled}
+ onOpenChange={setDropdownOpen}
+ placement="bottom-start"
+ gutter={4}
+ flip
+ slide
+ >
+ {!props.hideLabel && (
+ <label for={props.id} class="block text-xxs font-medium text-ink-muted">
+ {props.label}
+ </label>
+ )}
+ <div
+ ref={control}
+ class={cn('relative', !props.hideLabel && 'mt-1', props.class)}
+ >
+ <input
+ id={props.id}
+ type="time"
+ step={900}
+ value={props.value}
+ disabled={props.disabled}
+ aria-expanded={open()}
+ aria-haspopup="listbox"
+ class="w-full appearance-none rounded-md border border-edge-muted bg-surface py-1.5 pr-7 pl-2 text-xs text-ink outline-none focus:border-accent disabled:opacity-50 [&::-webkit-calendar-picker-indicator]:hidden"
+ onFocus={() => {
+ props.onFocus?.();
+ setDropdownOpen(true);
+ }}
+ onClick={() => setDropdownOpen(true)}
+ onInput={(event) => {
+ const value = event.currentTarget.value;
+ if (value && value !== props.value) props.onChange(value);
+ }}
+ onKeyDown={(event) => {
+ if (event.key !== 'Escape' || !open()) return;
+ event.preventDefault();
+ event.stopPropagation();
+ setOpen(false);
+ }}
+ />
+ <CaretDownIcon
+ aria-hidden="true"
+ class="pointer-events-none absolute top-1/2 right-2 size-3 -translate-y-1/2 text-ink-extra-muted"
+ />
+ </div>
+
+ <Popover.Portal>
+ <Layer depth={4}>
+ <Popover.Content
+ class="z-action-menu max-h-64 min-w-[var(--kb-popper-anchor-width)] overflow-y-auto rounded-xl border border-edge bg-menu p-1.5 shadow-menu menu-open-animation"
+ style={{
+ 'z-index': 'calc(var(--z-index-action-menu) + 1)',
+ }}
+ onOpenAutoFocus={(event) => event.preventDefault()}
+ onCloseAutoFocus={(event) => event.preventDefault()}
+ onInteractOutside={(event) => {
+ const target = event.detail.originalEvent.target;
+ if (target instanceof Node && control?.contains(target)) {
+ event.preventDefault();
+ }
+ }}
+ on:keydown={(event: KeyboardEvent) => {
+ if (event.key !== 'Escape') return;
+ event.preventDefault();
+ event.stopPropagation();
+ setOpen(false);
+ }}
+ >
+ <Popover.Title class="sr-only">
+ Choose {props.label.toLowerCase()}
+ </Popover.Title>
+ <Listbox<EventTimeOption>
+ ref={(element) => {
+ listbox = element;
+ }}
+ options={EVENT_TIME_OPTIONS}
+ optionValue="value"
+ optionTextValue="label"
+ value={selectedTime()}
+ onChange={selectTime}
+ selectionMode="single"
+ disallowEmptySelection
+ shouldFocusWrap
+ renderItem={(item) => <TimeOptionItem {...item} />}
+ />
+ </Popover.Content>
+ </Layer>
+ </Popover.Portal>
+ </Popover>
+ );
+}
+
+interface EventDateFieldProps {
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ disabled?: boolean;
+ invalid?: boolean;
+ describedBy?: string;
+ class?: string;
+ portalScope?: 'local';
+ appearance?: 'underline' | 'bare';
+}
+
+/** Compact calendar date selector used by event date/time ranges. */
+export function EventDateField(props: EventDateFieldProps) {
+ const [open, setOpen] = createSignal(false);
+ const [portalSearchRef, setPortalSearchRef] = createSignal<HTMLDivElement>();
+ const selectedDate = () => parseLocalDate(props.value);
+ const portalMount = () => {
+ if (props.portalScope !== 'local') return undefined;
+ return (
+ portalSearchRef()?.closest<HTMLElement>('.portal-scope') ?? undefined
+ );
+ };
+
+ return (
+ <Popover
+ open={open() && !props.disabled}
+ onOpenChange={(next) => setOpen(!props.disabled && next)}
+ placement="bottom-start"
+ gutter={4}
+ flip
+ slide
+ >
+ <Popover.Trigger
+ aria-label={`${props.label} date`}
+ aria-describedby={props.describedBy}
+ aria-invalid={props.invalid || undefined}
+ title={selectedDate() ? dateLabelFormatter.format(selectedDate()) : ''}
+ disabled={props.disabled}
+ class={cn(
+ 'flex min-w-0 items-center justify-start gap-1 truncate bg-transparent text-xs font-normal outline-none disabled:cursor-not-allowed',
+ props.appearance === 'bare'
+ ? 'px-0'
+ : 'h-9 border-b border-edge-muted px-1 focus-visible:border-accent',
+ props.invalid && 'border-failure',
+ props.class
+ )}
+ >
+ <CalendarBlankIcon class="size-3 shrink-0 text-ink-extra-muted" />
+ <span class="truncate">
+ {selectedDate() ? dateLabelFormatter.format(selectedDate()) : 'Date'}
+ </span>
+ </Popover.Trigger>
+
+ <div class="hidden" ref={setPortalSearchRef} />
+ <Popover.Portal mount={portalMount()}>
+ <Layer depth={3}>
+ <Popover.Content class="z-action-menu w-72 max-w-[calc(100vw-1rem)] rounded-xl border border-edge bg-menu p-3 shadow-menu menu-open-animation">
+ <Popover.Title class="sr-only">
+ Choose {props.label.toLowerCase()} date
+ </Popover.Title>
+ <Calendar
+ required
+ fixedWeeks
+ value={selectedDate()}
+ onValueChange={(date) => {
+ if (!date) return;
+ props.onChange(formatLocalDate(date));
+ setOpen(false);
+ }}
+ />
+ </Popover.Content>
+ </Layer>
+ </Popover.Portal>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/features/calendar/events/EventComposerDateTimeRangeFields.tsx b/apps/web/src/features/calendar/components/composer/EventDateTimeRangeFields.tsx
similarity index 96%
rename from apps/web/src/features/calendar/events/EventComposerDateTimeRangeFields.tsx
rename to apps/web/src/features/calendar/components/composer/EventDateTimeRangeFields.tsx
index 62a4630f71..b7fcb4b0a5 100644
--- a/apps/web/src/features/calendar/events/EventComposerDateTimeRangeFields.tsx
+++ b/apps/web/src/features/calendar/components/composer/EventDateTimeRangeFields.tsx
@@ -7,16 +7,15 @@ import { Layer } from '@ui/components/Layer';
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,
- formatLocalDate,
- parseLocalDate,
splitLocalDateTime,
timeLabelFormatter,
withLocalDate,
withLocalTime,
-} from './EventDateTimeField';
+} from './EventDateTimeInputs';
function formatTime(value: string) {
const [hour, minute] = value.split(':').map(Number);
@@ -24,7 +23,7 @@ function formatTime(value: string) {
return timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute));
}
-export interface EventComposerDateTimeRangeFieldsProps {
+export interface EventDateTimeRangeFieldsProps {
start: string;
end: string;
allDay: boolean;
@@ -39,9 +38,7 @@ export interface EventComposerDateTimeRangeFieldsProps {
}
/** Combined date-range display with start/end calendar and time controls. */
-export function EventComposerDateTimeRangeFields(
- props: EventComposerDateTimeRangeFieldsProps
-) {
+export function EventDateTimeRangeFields(props: EventDateTimeRangeFieldsProps) {
const fieldId = createUniqueId();
const [open, setOpen] = createSignal(false);
let trigger: HTMLButtonElement | undefined;
diff --git a/apps/web/src/features/calendar/components/composer/EventForm.tsx b/apps/web/src/features/calendar/components/composer/EventForm.tsx
new file mode 100644
index 0000000000..3e044de612
--- /dev/null
+++ b/apps/web/src/features/calendar/components/composer/EventForm.tsx
@@ -0,0 +1,216 @@
+import SpinnerIcon from '@phosphor/spinner.svg';
+import { Button, cn, Layer } from '@ui';
+import { createEffect, createUniqueId, Show } from 'solid-js';
+import type { CalendarEventFormController } from './create-calendar-event-form-controller';
+import { EventDateTimeRangeFields } from './EventDateTimeRangeFields';
+import {
+ EventComposerCalendarPill,
+ EventComposerGuestsPill,
+ EventComposerLocationPill,
+ EventComposerRecurrencePill,
+} from './EventPropertyPills';
+import type {
+ EventEditorDisabledFields,
+ EventEditorSubmitValues,
+} from './event-form-model';
+import { RecurrenceBuilder } from './RecurrenceBuilder';
+
+export interface EventFormProps {
+ controller: CalendarEventFormController;
+ isEdit?: boolean;
+ disabledFields?: EventEditorDisabledFields;
+ showRecurringEditNotice?: boolean;
+ pending: boolean;
+ class?: string;
+ onCalendarChange?: (calendarId: string, color: string) => void;
+ onDirtyChange?: (dirty: boolean) => void;
+ onCancel: () => void;
+ onSubmit: (values: EventEditorSubmitValues) => void;
+}
+
+/** Create/edit event form laid out like the standalone task composer. */
+export function EventForm(props: EventFormProps) {
+ const formId = createUniqueId();
+
+ const dateRangeErrorId = `event-composer-date-range-error-${formId}`;
+
+ const controller = props.controller;
+ const state = controller.state;
+ const isEdit = () => props.isEdit ?? false;
+
+ const fieldIsReadOnly = (field: keyof EventEditorDisabledFields) =>
+ props.disabledFields?.[field] === true;
+ const fieldIsDisabled = (field: keyof EventEditorDisabledFields) =>
+ props.pending || fieldIsReadOnly(field);
+
+ createEffect(() => {
+ const option = controller.selectedCalendarOption();
+ if (option) props.onCalendarChange?.(option.id, option.color);
+ });
+ createEffect(() => props.onDirtyChange?.(controller.isDirty()));
+
+ const submit = () => {
+ const values = controller.submitValues();
+ if (!values || props.pending) return;
+ props.onSubmit(values);
+ };
+
+ return (
+ <form
+ class={cn(
+ 'flex min-h-0 flex-1 flex-col gap-4 text-sm text-ink-muted [&_:disabled]:cursor-not-allowed',
+ props.class
+ )}
+ onSubmit={(event) => {
+ event.preventDefault();
+ submit();
+ }}
+ >
+ <div class="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto scrollbar-hidden">
+ <div class="flex min-w-0 flex-col gap-6 text-sm text-ink-muted">
+ <div class="flex min-w-0 flex-col gap-1">
+ <div class="flex min-w-0 flex-col gap-0">
+ <EventDateTimeRangeFields
+ start={state().start}
+ end={state().end}
+ allDay={state().allDay}
+ onStartChange={controller.setStart}
+ onEndChange={(end) => controller.setField('end', end)}
+ onAllDayChange={controller.setAllDay}
+ startDisabled={fieldIsDisabled('start')}
+ endDisabled={fieldIsDisabled('end')}
+ allDayDisabled={fieldIsDisabled('allDay')}
+ invalid={controller.dateRangeError() !== undefined}
+ describedBy={
+ controller.dateRangeError() ? dateRangeErrorId : undefined
+ }
+ />
+ <Show when={controller.dateRangeError()}>
+ {(error) => (
+ <p
+ id={dateRangeErrorId}
+ role="alert"
+ class="px-2 text-xs text-failure"
+ >
+ {error()}
+ </p>
+ )}
+ </Show>
+ </div>
+
+ <input
+ type="text"
+ value={state().title}
+ onInput={(event) =>
+ controller.setField('title', event.currentTarget.value)
+ }
+ placeholder="New event"
+ aria-label="Title"
+ autofocus={!isEdit()}
+ disabled={fieldIsDisabled('title')}
+ class="h-9 w-full bg-transparent px-2 text-lg font-semibold leading-snug text-ink outline-none placeholder:text-ink-placeholder"
+ />
+
+ <div class="h-12">
+ <textarea
+ value={state().description}
+ onInput={(event) =>
+ controller.setField(
+ 'description',
+ event.currentTarget.value.replaceAll(/[\r\n]+/g, ' ')
+ )
+ }
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') event.preventDefault();
+ }}
+ placeholder="Add description..."
+ aria-label="Description"
+ rows={1}
+ wrap="off"
+ disabled={fieldIsDisabled('description')}
+ class="h-full w-full resize-none overflow-x-auto bg-transparent px-2 text-sm text-ink outline-none placeholder:text-ink-placeholder"
+ />
+ </div>
+ </div>
+
+ <div class="flex min-w-0 flex-wrap items-center gap-2">
+ <EventComposerCalendarPill
+ options={controller.calendarOptions()}
+ value={controller.selectedCalendarOption()}
+ onChange={(calendarId) =>
+ controller.setField('calendarId', calendarId)
+ }
+ disabled={props.pending}
+ readOnly={fieldIsReadOnly('calendar')}
+ />
+ <EventComposerRecurrencePill
+ options={controller.recurrenceOptions()}
+ value={controller.selectedRecurrenceOption()}
+ onChange={controller.changeRecurrenceChoice}
+ disabled={props.pending}
+ readOnly={fieldIsReadOnly('recurrence')}
+ />
+ <EventComposerGuestsPill
+ options={controller.guestOptions}
+ selected={controller.selectedGuests()}
+ onChange={controller.setSelectedGuests}
+ disabled={props.pending}
+ readOnly={fieldIsReadOnly('guests')}
+ />
+ <EventComposerLocationPill
+ value={state().location}
+ onChange={(location) => controller.setField('location', location)}
+ disabled={fieldIsDisabled('location')}
+ />
+ </div>
+ </div>
+
+ <Show when={controller.recurrenceChoice() === 'custom'}>
+ <Layer depth={3}>
+ <div class="rounded-xl bg-surface p-4 text-ink">
+ <RecurrenceBuilder
+ value={controller.customConfig()}
+ start={controller.startForRecurrence()}
+ allDay={state().allDay}
+ disabled={fieldIsDisabled('recurrence')}
+ onChange={controller.setCustomConfig}
+ />
+ </div>
+ </Layer>
+ </Show>
+ </div>
+
+ <div class="flex shrink-0 items-center justify-end gap-3">
+ <Show when={props.showRecurringEditNotice}>
+ <p class="mr-auto text-xs text-ink-extra-muted">
+ Changes apply to all occurrences
+ </p>
+ </Show>
+ <Button
+ type="button"
+ variant="ghost"
+ class="rounded-lg"
+ disabled={props.pending}
+ onClick={props.onCancel}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant={controller.canSave() ? 'active' : 'ghost'}
+ depth={3}
+ class="rounded-lg border-0"
+ disabled={!controller.canSave() || props.pending}
+ aria-label={isEdit() ? 'Save' : 'Create event'}
+ >
+ <Show
+ when={props.pending}
+ fallback={isEdit() ? 'Save' : 'Create event'}
+ >
+ <SpinnerIcon class="size-4 animate-spin" />
+ </Show>
+ </Button>
+ </div>
+ </form>
+ );
+}
diff --git a/apps/web/src/features/calendar/events/EventComposerPropertyPills.tsx b/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx
similarity index 99%
rename from apps/web/src/features/calendar/events/EventComposerPropertyPills.tsx
rename to apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx
index 44249b5742..95a64fb9b6 100644
--- a/apps/web/src/features/calendar/events/EventComposerPropertyPills.tsx
+++ b/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx
@@ -25,7 +25,7 @@ import {
type EventEditorGuestOption,
guestEmail,
type SelectedEventEditorGuest,
-} from './EventEditorForm';
+} from './event-form-model';
const GUEST_NAME_COLLATOR = new Intl.Collator(undefined, {
sensitivity: 'base',
diff --git a/apps/web/src/features/calendar/events/RecurrenceBuilder.tsx b/apps/web/src/features/calendar/components/composer/RecurrenceBuilder.tsx
similarity index 91%
rename from apps/web/src/features/calendar/events/RecurrenceBuilder.tsx
rename to apps/web/src/features/calendar/components/composer/RecurrenceBuilder.tsx
index 6b4932540d..2758e3911e 100644
--- a/apps/web/src/features/calendar/events/RecurrenceBuilder.tsx
+++ b/apps/web/src/features/calendar/components/composer/RecurrenceBuilder.tsx
@@ -2,15 +2,15 @@ import { RadioGroup } from '@kobalte/core/radio-group';
import { Button, Select } from '@ui';
import { addMonths, format } from 'date-fns';
import { createMemo, For, Show } from 'solid-js';
-import { EventDateField } from './EventDateTimeField';
-import { formatRecurrenceDescription } from './recurrence-description';
import {
buildRecurrenceLines,
+ formatRecurrenceDescription,
type RecurrenceConfig,
type RecurrenceFrequency,
WEEKDAY_CODES,
type WeekdayCode,
-} from './recurrence-editor';
+} from '../../utils/recurrence';
+import { EventDateField } from './EventDateTimeInputs';
const DATE_VALUE = 'yyyy-MM-dd';
@@ -26,18 +26,12 @@ const FREQUENCY_OPTIONS: FrequencyOption[] = [
{ value: 'YEARLY', label: 'year' },
];
-/** Value emitted whenever the recurrence builder changes. */
-export interface RecurrenceBuilderValue extends RecurrenceConfig {
- /** Human-readable description formed from the individual recurrence parts. */
- recurrenceDescription: string;
-}
-
export interface RecurrenceBuilderProps {
value: RecurrenceConfig;
start: Date;
allDay: boolean;
disabled?: boolean;
- onChange: (value: RecurrenceBuilderValue) => void;
+ onChange: (value: RecurrenceConfig) => void;
}
/** Builds an RFC 5545 recurrence rule from individually editable parts. */
@@ -56,16 +50,8 @@ export function RecurrenceBuilder(props: RecurrenceBuilderProps) {
) ?? 'Recurring event'
);
- const changeConfig = (next: RecurrenceConfig) => {
- const recurrenceLines = buildRecurrenceLines(next, props.allDay);
- props.onChange({
- ...next,
- recurrenceDescription:
- formatRecurrenceDescription(recurrenceLines) ?? 'Recurring event',
- });
- };
const patchConfig = (patch: Partial<RecurrenceConfig>) =>
- changeConfig({ ...props.value, ...patch });
+ props.onChange({ ...props.value, ...patch });
const setEnds = (ends: RecurrenceConfig['ends']) => patchConfig({ ends });
const toggleWeekday = (code: WeekdayCode) =>
patchConfig({
diff --git a/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.ts b/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.ts
new file mode 100644
index 0000000000..0837d48280
--- /dev/null
+++ b/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.ts
@@ -0,0 +1,259 @@
+import { type Accessor, batch, createMemo, createSignal } from 'solid-js';
+import {
+ parseRecurrenceConfig,
+ recurrenceConfigsEqual,
+} from '../../utils/recurrence';
+import {
+ convertTimesForAllDay,
+ createEventEditorState,
+ type EventEditorCalendarOption,
+ type EventEditorGuestOption,
+ type EventEditorInitialValues,
+ type EventEditorSubmitValues,
+ guestEmail,
+ initialGuestOptions,
+ moveAllDayRange,
+ type SelectedEventEditorGuest,
+} from './event-form-model';
+
+interface EventComposerFormSnapshot {
+ title: string;
+ allDay: boolean;
+ start: string;
+ end: string;
+ recurrenceLines: readonly string[];
+ calendarId?: string;
+ guestEmails: readonly string[];
+ location: string;
+ description: string;
+}
+
+function normalizedGuestEmails(emails: readonly string[]) {
+ return emails.map((email) => email.trim().toLowerCase()).sort();
+}
+
+function arraysEqual(first: readonly string[], second: readonly string[]) {
+ return (
+ first.length === second.length &&
+ first.every((value, index) => value === second[index])
+ );
+}
+
+function recurrenceLinesEqual(
+ first: readonly string[],
+ second: readonly string[]
+) {
+ if (arraysEqual(first, second)) return true;
+
+ const firstConfig = parseRecurrenceConfig([...first]);
+ const secondConfig = parseRecurrenceConfig([...second]);
+ return (
+ firstConfig !== undefined &&
+ secondConfig !== undefined &&
+ recurrenceConfigsEqual(firstConfig, secondConfig)
+ );
+}
+
+function isEventComposerFormDirty(
+ initial: EventComposerFormSnapshot,
+ current: EventComposerFormSnapshot
+) {
+ return (
+ initial.title !== current.title ||
+ initial.allDay !== current.allDay ||
+ initial.start !== current.start ||
+ initial.end !== current.end ||
+ initial.calendarId !== current.calendarId ||
+ initial.location !== current.location ||
+ initial.description !== current.description ||
+ !arraysEqual(
+ normalizedGuestEmails(initial.guestEmails),
+ normalizedGuestEmails(current.guestEmails)
+ ) ||
+ !recurrenceLinesEqual(initial.recurrenceLines, current.recurrenceLines)
+ );
+}
+
+export interface CreateCalendarEventFormControllerOptions {
+ initialValue: EventEditorInitialValues;
+ calendarOptions: Accessor<EventEditorCalendarOption[]>;
+ guestOptions: Accessor<EventEditorGuestOption[]>;
+ onChange?: (value: EventEditorInitialValues) => void;
+}
+
+function cloneValue(value: EventEditorInitialValues): EventEditorInitialValues {
+ return { ...value, recurrenceLines: [...value.recurrenceLines] };
+}
+
+/** Caller-owned state and commands for the reusable calendar event form. */
+export function createCalendarEventFormController(
+ options: CreateCalendarEventFormControllerOptions
+) {
+ const [initialValue, setInitialValue] = createSignal(
+ cloneValue(options.initialValue)
+ );
+ const [state, setState] = createSignal(cloneValue(options.initialValue));
+
+ const initialGuests = initialGuestOptions(
+ options.initialValue.guests,
+ options.guestOptions()
+ );
+
+ const [initialGuestEmails, setInitialGuestEmails] = createSignal(
+ initialGuests.map(guestEmail)
+ );
+
+ const [selectedGuests, setSelectedGuestsState] =
+ createSignal<SelectedEventEditorGuest[]>(initialGuests);
+
+ const recurrence = createEventEditorState({
+ initialValues: options.initialValue,
+ state,
+ });
+
+ const effectiveCalendarId = () =>
+ state().calendarId ?? options.calendarOptions()[0]?.id;
+
+ const selectedCalendarOption = () =>
+ options
+ .calendarOptions()
+ .find((option) => option.id === effectiveCalendarId()) ??
+ options.calendarOptions()[0];
+
+ const effectiveRecurrenceLines = () =>
+ recurrence.recurrenceLines() ?? initialValue().recurrenceLines;
+
+ const value = createMemo<EventEditorInitialValues>(() => ({
+ ...state(),
+ recurrenceLines: [...effectiveRecurrenceLines()],
+ guests: selectedGuests().map(guestEmail).join(', '),
+ }));
+
+ const snapshot = (): EventComposerFormSnapshot => ({
+ title: state().title,
+ allDay: state().allDay,
+ start: state().start,
+ end: state().end,
+ recurrenceLines: effectiveRecurrenceLines(),
+ calendarId: effectiveCalendarId(),
+ guestEmails: selectedGuests().map(guestEmail),
+ location: state().location,
+ description: state().description,
+ });
+
+ const initialSnapshot = (): EventComposerFormSnapshot => ({
+ title: initialValue().title,
+ allDay: initialValue().allDay,
+ start: initialValue().start,
+ end: initialValue().end,
+ recurrenceLines: initialValue().recurrenceLines,
+ calendarId: initialValue().calendarId ?? options.calendarOptions()[0]?.id,
+ guestEmails: initialGuestEmails(),
+ location: initialValue().location,
+ description: initialValue().description,
+ });
+
+ const isDirty = createMemo(() =>
+ isEventComposerFormDirty(initialSnapshot(), snapshot())
+ );
+
+ const notifyChange = () => options.onChange?.(value());
+ const replaceState = (next: EventEditorInitialValues) => {
+ setState(cloneValue(next));
+ notifyChange();
+ };
+
+ const setField = <Key extends keyof EventEditorInitialValues>(
+ field: Key,
+ next: EventEditorInitialValues[Key]
+ ) => replaceState({ ...state(), [field]: next });
+
+ const setStart = (start: string) =>
+ replaceState(
+ state().allDay ? moveAllDayRange(state(), start) : { ...state(), start }
+ );
+
+ const setAllDay = (allDay: boolean) =>
+ replaceState(convertTimesForAllDay(state(), allDay));
+
+ const setSelectedGuests = (guests: SelectedEventEditorGuest[]) => {
+ batch(() => {
+ setSelectedGuestsState(guests);
+ setState({
+ ...state(),
+ guests: guests.map(guestEmail).join(', '),
+ });
+ });
+ notifyChange();
+ };
+
+ const changeRecurrenceChoice = (choice: string) => {
+ recurrence.changeRecurrenceChoice(choice);
+ notifyChange();
+ };
+
+ const setCustomConfig: typeof recurrence.setCustomConfig = (next) => {
+ recurrence.setCustomConfig(next);
+ notifyChange();
+ };
+
+ const submitValues = (): EventEditorSubmitValues | undefined => {
+ const time = recurrence.eventTime();
+ if (!time || !recurrence.canSave()) return undefined;
+ const current = state();
+ return {
+ title: current.title,
+ time,
+ recurrenceLines: recurrence.recurrenceLines(),
+ calendarId: effectiveCalendarId(),
+ guestEmails: selectedGuests().map(guestEmail),
+ location: current.location,
+ description: current.description,
+ };
+ };
+
+ const replaceFromExternal = (next: EventEditorInitialValues) => {
+ const cloned = cloneValue(next);
+ const guests = initialGuestOptions(next.guests, options.guestOptions());
+ batch(() => {
+ setInitialValue(cloned);
+ setState(cloned);
+ setInitialGuestEmails(guests.map(guestEmail));
+ setSelectedGuestsState(guests);
+ recurrence.replaceInitialValues(cloned);
+ });
+ };
+
+ return {
+ state,
+ value,
+ calendarOptions: options.calendarOptions,
+ guestOptions: options.guestOptions,
+ selectedGuests,
+ effectiveCalendarId,
+ selectedCalendarOption,
+ setField,
+ setStart,
+ setAllDay,
+ setSelectedGuests,
+ startForRecurrence: recurrence.startForRecurrence,
+ recurrenceChoice: recurrence.recurrenceChoice,
+ recurrenceOptions: recurrence.recurrenceOptions,
+ selectedRecurrenceOption: recurrence.selectedRecurrenceOption,
+ customConfig: recurrence.customConfig,
+ setCustomConfig,
+ changeRecurrenceChoice,
+ recurrenceLines: recurrence.recurrenceLines,
+ dateRangeError: recurrence.dateRangeError,
+ eventTime: recurrence.eventTime,
+ canSave: recurrence.canSave,
+ snapshot,
+ isDirty,
+ submitValues,
+ replaceFromExternal,
+ };
+}
+
+export type CalendarEventFormController = ReturnType<
+ typeof createCalendarEventFormController
+>;
diff --git a/apps/web/src/features/calendar/components/composer/event-form-model.ts b/apps/web/src/features/calendar/components/composer/event-form-model.ts
new file mode 100644
index 0000000000..5aa7cb2c3f
--- /dev/null
+++ b/apps/web/src/features/calendar/components/composer/event-form-model.ts
@@ -0,0 +1,430 @@
+import {
+ type CombinedRecipientItem,
+ recipientEntityMapper,
+ type WithCustomUserInput,
+} from '@core/user/combinedRecipient';
+import type { EventTime } from '@service-email/generated/schemas/eventTime';
+import {
+ addDays,
+ addHours,
+ differenceInCalendarDays,
+ format,
+ parseISO,
+ startOfHour,
+} from 'date-fns';
+import { type Accessor, batch, createMemo, createSignal } from 'solid-js';
+import type { CalendarEvent } from '../../types';
+import { parseLocalDate } from '../../utils/calendar-date';
+import {
+ buildRecurrenceLines,
+ defaultCustomConfig,
+ formatRecurrenceDescription,
+ parseRecurrenceConfig,
+ type RecurrenceConfig,
+ recurrenceConfigsEqual,
+ recurrencePresetsFor,
+} from '../../utils/recurrence';
+
+/** `<input type="date">` value. */
+const DATE_VALUE = 'yyyy-MM-dd';
+/** `<input type="datetime-local">` value. */
+const DATETIME_VALUE = "yyyy-MM-dd'T'HH:mm";
+
+const isDateOnly = (value: string) => parseLocalDate(value) !== undefined;
+
+/** Option displayed by an event editor recurrence selector. */
+export interface EventEditorRecurrenceOption {
+ value: string;
+ label: string;
+}
+
+function shiftDateValue(value: string, days: number) {
+ return format(addDays(parseISO(value), days), DATE_VALUE);
+}
+
+/** Default editor slot: the next full hour, one hour long. */
+function defaultEditorTimes(reference: Date) {
+ const start = addHours(startOfHour(reference), 1);
+ return { start, end: addHours(start, 1) };
+}
+
+/** Values used to initialize the shared event editor form. */
+export interface EventEditorInitialValues {
+ title: string;
+ allDay: boolean;
+ /** `datetime-local` value, or `date` value in all-day mode. */
+ start: string;
+ /** Inclusive end shown to the user; all-day submissions add the exclusive day. */
+ end: string;
+ recurrenceLines: string[];
+ calendarId?: string;
+ guests: string;
+ location: string;
+ description: string;
+}
+
+/** Calendar option displayed by the event editor. */
+export interface EventEditorCalendarOption {
+ id: string;
+ label: string;
+ color: string;
+}
+
+/** Editable fields that a create/edit owner may disable. */
+type EventEditorField =
+ | 'title'
+ | 'allDay'
+ | 'start'
+ | 'end'
+ | 'recurrence'
+ | 'calendar'
+ | 'guests'
+ | 'location'
+ | 'description';
+
+/** Field-level disabled state supplied by a create/edit owner. */
+export type EventEditorDisabledFields = Partial<
+ Record<EventEditorField, boolean>
+>;
+
+/** Validated values emitted by the shared event editor form. */
+export interface EventEditorSubmitValues {
+ title: string;
+ time: EventTime;
+ recurrenceLines?: string[];
+ calendarId?: string;
+ guestEmails: string[];
+ location: string;
+ description: string;
+}
+
+export function defaultEditorInitialValues(
+ reference = new Date()
+): EventEditorInitialValues {
+ const { start, end } = defaultEditorTimes(reference);
+ return {
+ title: '',
+ allDay: false,
+ start: format(start, DATETIME_VALUE),
+ end: format(end, DATETIME_VALUE),
+ recurrenceLines: [],
+ calendarId: undefined,
+ guests: '',
+ location: '',
+ description: '',
+ };
+}
+
+/** Converts a FullCalendar-style selected range into create-event values. */
+export function calendarSelectionToEditorInitialValues(selection: {
+ start: Date;
+ end: Date;
+ allDay: boolean;
+}): EventEditorInitialValues {
+ const initialValues = defaultEditorInitialValues(selection.start);
+ if (selection.allDay) {
+ return {
+ ...initialValues,
+ allDay: true,
+ start: format(selection.start, DATE_VALUE),
+ end: format(addDays(selection.end, -1), DATE_VALUE),
+ };
+ }
+
+ return {
+ ...initialValues,
+ start: format(selection.start, DATETIME_VALUE),
+ end: format(selection.end, DATETIME_VALUE),
+ };
+}
+
+/** Converts an existing event into values for the shared editor. */
+export function calendarEventToEditorInitialValues(
+ event: CalendarEvent
+): EventEditorInitialValues {
+ const guests = event.attendees
+ .filter((attendee) => attendee.isOrganizer || !attendee.isSelf)
+ .map((attendee) => attendee.email)
+ .join(', ');
+
+ if (event.allDay) {
+ const start = isDateOnly(event.start)
+ ? event.start
+ : format(new Date(event.start), DATE_VALUE);
+ const exclusiveEnd = isDateOnly(event.end)
+ ? event.end
+ : format(new Date(event.end), DATE_VALUE);
+ return {
+ title: event.title,
+ allDay: true,
+ start,
+ end: shiftDateValue(exclusiveEnd, -1),
+ recurrenceLines: [...event.recurrenceLines],
+ calendarId: event.calendar.id,
+ guests,
+ location: event.location ?? '',
+ description: event.description ?? '',
+ };
+ }
+
+ return {
+ title: event.title,
+ allDay: false,
+ start: format(new Date(event.start), DATETIME_VALUE),
+ end: format(new Date(event.end), DATETIME_VALUE),
+ recurrenceLines: [...event.recurrenceLines],
+ calendarId: event.calendar.id,
+ guests,
+ location: event.location ?? '',
+ description: event.description ?? '',
+ };
+}
+
+export function buildEventTime(
+ state: EventEditorInitialValues
+): EventTime | undefined {
+ if (state.allDay) {
+ if (!state.start || !state.end || state.end < state.start) {
+ return undefined;
+ }
+ return {
+ kind: 'allDay',
+ startDate: state.start,
+ endDate: shiftDateValue(state.end, 1),
+ };
+ }
+
+ const start = new Date(state.start);
+ const end = new Date(state.end);
+ if (
+ Number.isNaN(start.getTime()) ||
+ Number.isNaN(end.getTime()) ||
+ end <= start
+ ) {
+ return undefined;
+ }
+ return {
+ kind: 'timed',
+ startsAt: start.toISOString(),
+ endsAt: end.toISOString(),
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ };
+}
+
+function parseGuestEmails(value: string) {
+ return [...new Set(value.split(/[\s,;]+/).filter((email) => email !== ''))];
+}
+
+type EventEditorGuestKind = 'user' | 'contact';
+export type EventEditorGuestOption =
+ CombinedRecipientItem<EventEditorGuestKind>;
+export type SelectedEventEditorGuest =
+ WithCustomUserInput<EventEditorGuestKind>;
+
+export function guestEmail(option: SelectedEventEditorGuest) {
+ return option.data.email;
+}
+
+export function initialGuestOptions(
+ value: string,
+ options: EventEditorGuestOption[]
+): SelectedEventEditorGuest[] {
+ return parseGuestEmails(value).map((email) => {
+ const existing = options.find(
+ (option) => guestEmail(option).toLowerCase() === email.toLowerCase()
+ );
+ return (
+ existing ??
+ recipientEntityMapper('custom')({
+ id: `macro|${email}`,
+ email,
+ invalid: false,
+ })
+ );
+ });
+}
+
+/** Both editor times switch representation when all-day toggles. */
+export function convertTimesForAllDay(
+ state: EventEditorInitialValues,
+ allDay: boolean
+) {
+ if (allDay === state.allDay) return state;
+ if (allDay) {
+ return {
+ ...state,
+ allDay,
+ start: state.start.slice(0, 10),
+ end: state.end.slice(0, 10),
+ };
+ }
+ const { start, end } = defaultEditorTimes(parseISO(state.start));
+ return {
+ ...state,
+ allDay,
+ start: format(start, DATETIME_VALUE),
+ end: format(end, DATETIME_VALUE),
+ };
+}
+
+export function moveAllDayRange(
+ state: EventEditorInitialValues,
+ nextStart: string
+): EventEditorInitialValues {
+ if (nextStart === '') return { ...state, start: '', end: '' };
+ const duration = differenceInCalendarDays(
+ parseISO(state.end),
+ parseISO(state.start)
+ );
+ const durationDays = Number.isFinite(duration) ? Math.max(0, duration) : 0;
+ return {
+ ...state,
+ start: nextStart,
+ end: shiftDateValue(nextStart, durationDays),
+ };
+}
+
+export interface CreateEventEditorStateOptions {
+ initialValues: EventEditorInitialValues;
+ state: Accessor<EventEditorInitialValues>;
+}
+
+function recurrenceConfigFor(values: EventEditorInitialValues) {
+ return values.recurrenceLines.length > 0
+ ? parseRecurrenceConfig(values.recurrenceLines)
+ : undefined;
+}
+
+function recurrenceChoiceFor(values: EventEditorInitialValues) {
+ if (values.recurrenceLines.length === 0) return 'none';
+ const config = recurrenceConfigFor(values);
+ if (!config) return 'existing';
+ const start = values.allDay ? parseISO(values.start) : new Date(values.start);
+ const preset = recurrencePresetsFor(start).find((candidate) =>
+ recurrenceConfigsEqual(candidate.config, config)
+ );
+ return preset?.id ?? 'custom';
+}
+
+/** Shared recurrence and validation state used by event editor layouts. */
+export function createEventEditorState(options: CreateEventEditorStateOptions) {
+ const [initialValues, setInitialValues] = createSignal(options.initialValues);
+ const initialConfig = createMemo(() => recurrenceConfigFor(initialValues()));
+ const hasUnrepresentableRule = () =>
+ initialValues().recurrenceLines.length > 0 && !initialConfig();
+
+ const startForRecurrence = createMemo(() => {
+ const start = options.state().start;
+ const parsed = options.state().allDay ? parseISO(start) : new Date(start);
+ return Number.isNaN(parsed.getTime()) ? new Date() : parsed;
+ });
+ const presets = createMemo(() => recurrencePresetsFor(startForRecurrence()));
+ const [recurrenceChoice, setRecurrenceChoice] = createSignal(
+ recurrenceChoiceFor(options.initialValues)
+ );
+ const recurrenceOptions = createMemo<EventEditorRecurrenceOption[]>(() => {
+ const values = [
+ { value: 'none', label: 'Does not repeat' },
+ ...presets().map((preset) => ({
+ value: preset.id,
+ label: preset.label,
+ })),
+ ];
+ if (hasUnrepresentableRule()) {
+ values.push({
+ value: 'existing',
+ label: `Custom: ${
+ formatRecurrenceDescription(initialValues().recurrenceLines) ??
+ 'existing rule'
+ } (unchanged)`,
+ });
+ }
+ values.push({ value: 'custom', label: 'Custom' });
+ return values;
+ });
+ const selectedRecurrenceOption = () =>
+ recurrenceOptions().find((option) => option.value === recurrenceChoice()) ??
+ recurrenceOptions()[0];
+ const [customConfig, setCustomConfig] = createSignal<RecurrenceConfig>(
+ initialConfig() ?? defaultCustomConfig(startForRecurrence())
+ );
+ const changeRecurrenceChoice = (choice: string) => {
+ if (choice === 'custom') {
+ const seed =
+ presets().find((preset) => preset.id === recurrenceChoice())?.config ??
+ initialConfig() ??
+ defaultCustomConfig(startForRecurrence());
+ setCustomConfig(seed);
+ }
+ setRecurrenceChoice(choice);
+ };
+ const customValid = createMemo(() => {
+ if (recurrenceChoice() !== 'custom') return true;
+ const config = customConfig();
+ if (!Number.isInteger(config.interval) || config.interval < 1) return false;
+ if (config.frequency === 'WEEKLY' && config.byDay.length === 0) {
+ return false;
+ }
+ if (config.ends.kind === 'on') return config.ends.date !== '';
+ if (config.ends.kind === 'after') {
+ return Number.isInteger(config.ends.count) && config.ends.count >= 1;
+ }
+ return true;
+ });
+ const recurrenceLines = (): string[] | undefined => {
+ const choice = recurrenceChoice();
+ if (choice === 'existing') return undefined;
+ if (choice === 'none') return [];
+ if (choice === 'custom') {
+ return buildRecurrenceLines(customConfig(), options.state().allDay);
+ }
+ const preset = presets().find((candidate) => candidate.id === choice);
+ return preset
+ ? buildRecurrenceLines(preset.config, options.state().allDay)
+ : undefined;
+ };
+ const dateRangeError = createMemo(() => {
+ const current = options.state();
+ if (!current.start || !current.end) return undefined;
+ if (current.allDay) {
+ return current.end < current.start
+ ? 'End date cannot be before the start date.'
+ : undefined;
+ }
+ const start = new Date(current.start);
+ const end = new Date(current.end);
+ if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
+ return undefined;
+ }
+ return end <= start ? 'End time must be after the start time.' : undefined;
+ });
+ const eventTime = createMemo(() => buildEventTime(options.state()));
+ const canSave = () =>
+ options.state().title.trim() !== '' &&
+ eventTime() !== undefined &&
+ customValid();
+ const replaceInitialValues = (next: EventEditorInitialValues) => {
+ batch(() => {
+ setInitialValues(() => next);
+ setRecurrenceChoice(recurrenceChoiceFor(next));
+ setCustomConfig(
+ recurrenceConfigFor(next) ?? defaultCustomConfig(startForRecurrence())
+ );
+ });
+ };
+
+ return {
+ startForRecurrence,
+ recurrenceChoice,
+ recurrenceOptions,
+ selectedRecurrenceOption,
+ customConfig,
+ setCustomConfig,
+ changeRecurrenceChoice,
+ recurrenceLines,
+ dateRangeError,
+ eventTime,
+ canSave,
+ replaceInitialValues,
+ };
+}
diff --git a/apps/web/src/features/calendar/events/EventComposerForm.tsx b/apps/web/src/features/calendar/events/EventComposerForm.tsx
deleted file mode 100644
index c2af227274..0000000000
--- a/apps/web/src/features/calendar/events/EventComposerForm.tsx
+++ /dev/null
@@ -1,324 +0,0 @@
-import SpinnerIcon from '@phosphor/spinner.svg';
-import { Button, cn, Layer } from '@ui';
-import {
- type Accessor,
- createEffect,
- createMemo,
- createSignal,
- createUniqueId,
- Show,
-} from 'solid-js';
-import { EventComposerDateTimeRangeFields } from './EventComposerDateTimeRangeFields';
-import {
- EventComposerCalendarPill,
- EventComposerGuestsPill,
- EventComposerLocationPill,
- EventComposerRecurrencePill,
-} from './EventComposerPropertyPills';
-import {
- convertTimesForAllDay,
- createEventEditorState,
- defaultEditorInitialValues,
- type EventEditorCalendarOption,
- type EventEditorDisabledFields,
- type EventEditorGuestOption,
- type EventEditorInitialValues,
- type EventEditorSubmitValues,
- guestEmail,
- initialGuestOptions,
- moveAllDayRange,
- type SelectedEventEditorGuest,
-} from './EventEditorForm';
-import {
- type EventComposerFormSnapshot,
- isEventComposerFormDirty,
-} from './event-composer-dirty';
-import { RecurrenceBuilder } from './RecurrenceBuilder';
-
-export interface EventComposerFormProps {
- initialValues?: EventEditorInitialValues;
- isEdit?: boolean;
- disabledFields?: EventEditorDisabledFields;
- calendarOptions: EventEditorCalendarOption[];
- guestOptions: Accessor<EventEditorGuestOption[]>;
- showRecurringEditNotice?: boolean;
- pending: boolean;
- class?: string;
- onCalendarChange?: (calendarId: string, color: string) => void;
- onDirtyChange?: (dirty: boolean) => void;
- onCancel: () => void;
- onSubmit: (values: EventEditorSubmitValues) => void;
-}
-
-/** Create/edit event form laid out like the standalone task composer. */
-export function EventComposerForm(props: EventComposerFormProps) {
- const formId = createUniqueId();
-
- const dateRangeErrorId = `event-composer-date-range-error-${formId}`;
-
- const isEdit = () => props.isEdit ?? false;
- const initialValues =
- props.initialValues ?? defaultEditorInitialValues(new Date());
- const [state, setState] = createSignal<EventEditorInitialValues>({
- ...initialValues,
- recurrenceLines: [...initialValues.recurrenceLines],
- });
-
- const initialSelectedGuests = initialGuestOptions(
- initialValues.guests,
- props.guestOptions()
- );
- const initialGuestEmails = initialSelectedGuests.map(guestEmail);
- const [selectedGuests, setSelectedGuests] = createSignal<
- SelectedEventEditorGuest[]
- >(initialSelectedGuests);
-
- const fieldIsReadOnly = (field: keyof EventEditorDisabledFields) =>
- props.disabledFields?.[field] === true;
- const fieldIsDisabled = (field: keyof EventEditorDisabledFields) =>
- props.pending || fieldIsReadOnly(field);
-
- const {
- startForRecurrence,
- recurrenceChoice,
- recurrenceOptions,
- selectedRecurrenceOption,
- customConfig,
- setCustomConfig,
- changeRecurrenceChoice,
- recurrenceLines,
- dateRangeError,
- eventTime,
- canSave,
- } = createEventEditorState({ initialValues, state });
-
- const effectiveCalendarId = () =>
- state().calendarId ?? props.calendarOptions[0]?.id;
-
- const selectedCalendarOption = () =>
- props.calendarOptions.find(
- (option) => option.id === effectiveCalendarId()
- ) ?? props.calendarOptions[0];
-
- const initialSnapshot = (): EventComposerFormSnapshot => ({
- title: initialValues.title,
- allDay: initialValues.allDay,
- start: initialValues.start,
- end: initialValues.end,
- recurrenceLines: initialValues.recurrenceLines,
- calendarId: initialValues.calendarId ?? props.calendarOptions[0]?.id,
- guestEmails: initialGuestEmails,
- location: initialValues.location,
- description: initialValues.description,
- });
- const currentSnapshot = (): EventComposerFormSnapshot => {
- const current = state();
- return {
- title: current.title,
- allDay: current.allDay,
- start: current.start,
- end: current.end,
- recurrenceLines: recurrenceLines() ?? initialValues.recurrenceLines,
- calendarId: effectiveCalendarId(),
- guestEmails: selectedGuests().map(guestEmail),
- location: current.location,
- description: current.description,
- };
- };
- const isDirty = createMemo(() =>
- isEventComposerFormDirty(initialSnapshot(), currentSnapshot())
- );
-
- createEffect(() => {
- const option = selectedCalendarOption();
- if (option) props.onCalendarChange?.(option.id, option.color);
- });
- createEffect(() => props.onDirtyChange?.(isDirty()));
-
- const changeCalendar = (calendarId: string) =>
- setState({ ...state(), calendarId });
-
- const submit = () => {
- const time = eventTime();
- if (!time || !canSave() || props.pending) return;
- const current = state();
- props.onSubmit({
- title: current.title,
- time,
- recurrenceLines: recurrenceLines(),
- calendarId: effectiveCalendarId(),
- guestEmails: selectedGuests().map(guestEmail),
- location: current.location,
- description: current.description,
- });
- };
-
- return (
- <form
- class={cn(
- 'flex min-h-0 flex-1 flex-col gap-4 text-sm text-ink-muted [&_:disabled]:cursor-not-allowed',
- props.class
- )}
- onSubmit={(event) => {
- event.preventDefault();
- submit();
- }}
- >
- <div class="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto scrollbar-hidden">
- <div class="flex min-w-0 flex-col gap-6 text-sm text-ink-muted">
- <div class="flex min-w-0 flex-col gap-1">
- <div class="flex min-w-0 flex-col gap-0">
- <EventComposerDateTimeRangeFields
- start={state().start}
- end={state().end}
- allDay={state().allDay}
- onStartChange={(start) =>
- setState(
- state().allDay
- ? moveAllDayRange(state(), start)
- : { ...state(), start }
- )
- }
- onEndChange={(end) => setState({ ...state(), end })}
- onAllDayChange={(allDay) =>
- setState(convertTimesForAllDay(state(), allDay))
- }
- startDisabled={fieldIsDisabled('start')}
- endDisabled={fieldIsDisabled('end')}
- allDayDisabled={fieldIsDisabled('allDay')}
- invalid={dateRangeError() !== undefined}
- describedBy={dateRangeError() ? dateRangeErrorId : undefined}
- />
- <Show when={dateRangeError()}>
- {(error) => (
- <p
- id={dateRangeErrorId}
- role="alert"
- class="px-2 text-xs text-failure"
- >
- {error()}
- </p>
- )}
- </Show>
- </div>
-
- <input
- type="text"
- value={state().title}
- onInput={(event) =>
- setState({ ...state(), title: event.currentTarget.value })
- }
- placeholder="New event"
- aria-label="Title"
- autofocus={!isEdit()}
- disabled={fieldIsDisabled('title')}
- class="h-9 w-full bg-transparent px-2 text-lg font-semibold leading-snug text-ink outline-none placeholder:text-ink-placeholder"
- />
-
- <div class="h-12">
- <textarea
- value={state().description}
- onInput={(event) =>
- setState({
- ...state(),
- description: event.currentTarget.value.replaceAll(
- /[\r\n]+/g,
- ' '
- ),
- })
- }
- onKeyDown={(event) => {
- if (event.key === 'Enter') event.preventDefault();
- }}
- placeholder="Add description..."
- aria-label="Description"
- rows={1}
- wrap="off"
- disabled={fieldIsDisabled('description')}
- class="h-full w-full resize-none overflow-x-auto bg-transparent px-2 text-sm text-ink outline-none placeholder:text-ink-placeholder"
- />
- </div>
- </div>
-
- <div class="flex min-w-0 flex-wrap items-center gap-2">
- <EventComposerCalendarPill
- options={props.calendarOptions}
- value={selectedCalendarOption()}
- onChange={changeCalendar}
- disabled={props.pending}
- readOnly={fieldIsReadOnly('calendar')}
- />
- <EventComposerRecurrencePill
- options={recurrenceOptions()}
- value={selectedRecurrenceOption()}
- onChange={changeRecurrenceChoice}
- disabled={props.pending}
- readOnly={fieldIsReadOnly('recurrence')}
- />
- <EventComposerGuestsPill
- options={props.guestOptions}
- selected={selectedGuests()}
- onChange={setSelectedGuests}
- disabled={props.pending}
- readOnly={fieldIsReadOnly('guests')}
- />
- <EventComposerLocationPill
- value={state().location}
- onChange={(location) => setState({ ...state(), location })}
- disabled={fieldIsDisabled('location')}
- />
- </div>
- </div>
-
- <Show when={recurrenceChoice() === 'custom'}>
- <Layer depth={3}>
- <div class="rounded-xl bg-surface p-4 text-ink">
- <RecurrenceBuilder
- value={customConfig()}
- start={startForRecurrence()}
- allDay={state().allDay}
- disabled={fieldIsDisabled('recurrence')}
- onChange={({
- recurrenceDescription: _recurrenceDescription,
- ...config
- }) => setCustomConfig(config)}
- />
- </div>
- </Layer>
- </Show>
- </div>
-
- <div class="flex shrink-0 items-center justify-end gap-3">
- <Show when={props.showRecurringEditNotice}>
- <p class="mr-auto text-xs text-ink-extra-muted">
- Changes apply to all occurrences
- </p>
- </Show>
- <Button
- type="button"
- variant="ghost"
- class="rounded-lg"
- disabled={props.pending}
- onClick={props.onCancel}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- variant={canSave() ? 'active' : 'ghost'}
- depth={3}
- class="rounded-lg border-0"
- disabled={!canSave() || props.pending}
- aria-label={isEdit() ? 'Save' : 'Create event'}
- >
- <Show
- when={props.pending}
- fallback={isEdit() ? 'Save' : 'Create event'}
- >
- <SpinnerIcon class="size-4 animate-spin" />
- </Show>
- </Button>
- </div>
- </form>
- );
-}
diff --git a/apps/web/src/features/calendar/events/EventContent.test.tsx b/apps/web/src/features/calendar/events/EventContent.test.tsx
deleted file mode 100644
index 948951bb41..0000000000
--- a/apps/web/src/features/calendar/events/EventContent.test.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- * @vitest-environment jsdom
- */
-
-import type { EventContentArg } from '@fullcalendar/core';
-import { render, screen } from '@solidjs/testing-library';
-import { describe, expect, it } from 'vitest';
-import {
- formatCompactCalendarTime,
- formatCompactCalendarTimeRange,
-} from '../time-format';
-import { CalendarEventContent } from './EventContent';
-import type { CalendarEvent } from './types';
-
-const start = new Date(2025, 0, 15, 9);
-
-function calendarEvent(durationMinutes: number): CalendarEvent {
- return {
- id: 'occurrence-1',
- eventId: 'event-1',
- occurrenceKey: 'occurrence-1',
- isReadOnly: false,
- isCancelled: false,
- attendees: [],
- recurrenceLines: [],
- title: 'Planning',
- start: start.toISOString(),
- end: new Date(start.getTime() + durationMinutes * 60 * 1000).toISOString(),
- allDay: false,
- calendar: {
- id: 'calendar-1',
- name: 'Work',
- color: 'red',
- },
- };
-}
-
-function renderProps(
- timeText: string,
- options: { allDay?: boolean; viewType?: string } = {}
-): EventContentArg {
- return {
- event: { allDay: options.allDay ?? false, start },
- timeText,
- view: { type: options.viewType ?? 'timeGridWeek' },
- } as EventContentArg;
-}
-
-describe('CalendarEventContent', () => {
- it('shows only the start time for a 15-minute event', () => {
- render(() => (
- <CalendarEventContent
- event={calendarEvent(15)}
- renderProps={renderProps('9:00 AM - 9:15 AM')}
- isSelected={false}
- timeFormat="12-hour"
- />
- ));
-
- expect(
- screen.getByText(formatCompactCalendarTime(start, '12-hour'))
- ).toBeTruthy();
- expect(screen.queryByText('9:00 AM - 9:15 AM')).toBeNull();
- });
-
- it('preserves the time range for longer events', () => {
- render(() => (
- <CalendarEventContent
- event={calendarEvent(30)}
- renderProps={renderProps('9:00 AM - 9:30 AM')}
- isSelected={false}
- timeFormat="12-hour"
- />
- ));
-
- expect(
- screen.getByText(
- formatCompactCalendarTimeRange(
- start,
- new Date(start.getTime() + 30 * 60 * 1000),
- '12-hour'
- )
- )
- ).toBeTruthy();
- });
-
- it('uses compact content when a timed event is rendered in the all-day row', () => {
- const event = {
- ...calendarEvent(24 * 60),
- location: 'Conference room',
- };
- const { container } = render(() => (
- <CalendarEventContent
- event={event}
- renderProps={renderProps('', {
- allDay: true,
- viewType: 'timeGridDay',
- })}
- isSelected={false}
- timeFormat="12-hour"
- />
- ));
-
- expect(
- container.querySelector('.calendar-event-content-compact')
- ).toBeTruthy();
- expect(
- container.querySelector('.calendar-event-content-layout-single-line')
- ).toBeTruthy();
- expect(
- screen.getByText(formatCompactCalendarTime(start, '12-hour'))
- ).toBeTruthy();
- expect(screen.queryByText('Conference room')).toBeNull();
- });
-});
diff --git a/apps/web/src/features/calendar/events/EventDateTimeField.tsx b/apps/web/src/features/calendar/events/EventDateTimeField.tsx
deleted file mode 100644
index d2f12527f6..0000000000
--- a/apps/web/src/features/calendar/events/EventDateTimeField.tsx
+++ /dev/null
@@ -1,568 +0,0 @@
-import type { CollectionNode } from '@kobalte/core';
-import { Listbox } from '@kobalte/core/listbox';
-import { Popover } from '@kobalte/core/popover';
-import CalendarBlankIcon from '@phosphor/calendar-blank.svg';
-import CaretDownIcon from '@phosphor/caret-down.svg';
-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, createUniqueId } from 'solid-js';
-
-export 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. */
-export 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 parseLocalDate(value: string) {
- const [year, month, day] = value.split('-').map(Number);
- if (!year || !month || !day) return undefined;
- const date = new Date(year, month - 1, day);
- if (
- Number.isNaN(date.getTime()) ||
- date.getFullYear() !== year ||
- date.getMonth() !== month - 1 ||
- date.getDate() !== day
- ) {
- return undefined;
- }
- return date;
-}
-
-export function formatLocalDate(date: Date) {
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
-}
-
-function parseDateInput(value: string) {
- const localDate = parseLocalDate(value.trim());
- if (localDate) return formatLocalDate(localDate);
-
- const parsed = new Date(value.trim());
- return Number.isNaN(parsed.getTime()) ? undefined : formatLocalDate(parsed);
-}
-
-export function withLocalTime(value: string, time: string) {
- return `${splitLocalDateTime(value).date}T${time}`;
-}
-
-function parseTimeInput(value: string) {
- const match = /^(\d{1,2})(?::(\d{1,2}))?\s*(am|pm)?$/i.exec(
- value.trim().replaceAll('.', '')
- );
- if (!match) return undefined;
-
- let hour = Number(match[1]);
- const minute = Number(match[2] ?? 0);
- const period = match[3]?.toLowerCase();
- if (minute > 59) return undefined;
-
- if (period) {
- if (hour < 1 || hour > 12) return undefined;
- if (period === 'am' && hour === 12) hour = 0;
- if (period === 'pm' && hour !== 12) hour += 12;
- } else if (hour > 23) {
- return undefined;
- }
-
- return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
-}
-
-function formatTimeLabel(value: string) {
- const parsed = parseTimeInput(value);
- if (!parsed) return 'Time';
- const [hour = 0, minute = 0] = parsed.split(':').map(Number);
- return timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute));
-}
-
-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"
- >
- <Listbox.ItemLabel>{props.rawValue.label}</Listbox.ItemLabel>
- <Listbox.ItemIndicator class="text-accent">
- <CheckIcon class="size-3.5" />
- </Listbox.ItemIndicator>
- </Listbox.Item>
- );
-}
-
-export interface EventTimeInputProps {
- id: string;
- label: string;
- value: string;
- onChange: (value: string) => void;
- onFocus?: () => void;
- disabled?: boolean;
- hideLabel?: boolean;
- class?: string;
-}
-
-export function EventTimeInput(props: EventTimeInputProps) {
- const [open, setOpen] = createSignal(false);
- let control: HTMLDivElement | undefined;
- let listbox: HTMLElement | undefined;
-
- const selectedTime = createMemo(() => [props.value]);
- const scrollToSelectedTime = () => {
- requestAnimationFrame(() => {
- listbox
- ?.querySelector<HTMLElement>('[data-selected]')
- ?.scrollIntoView({ block: 'center' });
- });
- };
- const setDropdownOpen = (nextOpen: boolean) => {
- if (props.disabled) return;
- setOpen(nextOpen);
- 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);
- setOpen(false);
- };
-
- return (
- <Popover
- anchorRef={() => control}
- open={open() && !props.disabled}
- onOpenChange={setDropdownOpen}
- placement="bottom-start"
- gutter={4}
- flip
- slide
- >
- {!props.hideLabel && (
- <label for={props.id} class="block text-xxs font-medium text-ink-muted">
- {props.label}
- </label>
- )}
- <div
- ref={control}
- class={cn('relative', !props.hideLabel && 'mt-1', props.class)}
- >
- <input
- id={props.id}
- type="time"
- step={900}
- value={props.value}
- disabled={props.disabled}
- aria-expanded={open()}
- aria-haspopup="listbox"
- class="w-full appearance-none rounded-md border border-edge-muted bg-surface py-1.5 pr-7 pl-2 text-xs text-ink outline-none focus:border-accent disabled:opacity-50 [&::-webkit-calendar-picker-indicator]:hidden"
- onFocus={() => {
- props.onFocus?.();
- setDropdownOpen(true);
- }}
- onClick={() => setDropdownOpen(true)}
- onInput={(event) => {
- const value = event.currentTarget.value;
- if (value && value !== props.value) props.onChange(value);
- }}
- onKeyDown={(event) => {
- if (event.key !== 'Escape' || !open()) return;
- event.preventDefault();
- event.stopPropagation();
- setOpen(false);
- }}
- />
- <CaretDownIcon
- aria-hidden="true"
- class="pointer-events-none absolute top-1/2 right-2 size-3 -translate-y-1/2 text-ink-extra-muted"
- />
- </div>
-
- <Popover.Portal>
- <Layer depth={4}>
- <Popover.Content
- class="z-action-menu max-h-64 min-w-[var(--kb-popper-anchor-width)] overflow-y-auto rounded-xl border border-edge bg-menu p-1.5 shadow-menu menu-open-animation"
- style={{
- 'z-index': 'calc(var(--z-index-action-menu) + 1)',
- }}
- onOpenAutoFocus={(event) => event.preventDefault()}
- onCloseAutoFocus={(event) => event.preventDefault()}
- onInteractOutside={(event) => {
- const target = event.detail.originalEvent.target;
- if (target instanceof Node && control?.contains(target)) {
- event.preventDefault();
- }
- }}
- on:keydown={(event: KeyboardEvent) => {
- if (event.key !== 'Escape') return;
- event.preventDefault();
- event.stopPropagation();
- setOpen(false);
- }}
- >
- <Popover.Title class="sr-only">
- Choose {props.label.toLowerCase()}
- </Popover.Title>
- <Listbox<EventTimeOption>
- ref={(element) => {
- listbox = element;
- }}
- options={EVENT_TIME_OPTIONS}
- optionValue="value"
- optionTextValue="label"
- value={selectedTime()}
- onChange={selectTime}
- selectionMode="single"
- disallowEmptySelection
- shouldFocusWrap
- renderItem={(item) => <TimeOptionItem {...item} />}
- />
- </Popover.Content>
- </Layer>
- </Popover.Portal>
- </Popover>
- );
-}
-
-export interface EventDateTimePopoverContentProps {
- label: string;
- date: string;
- time?: string;
- onDateChange: (date: string) => void;
- onTimeChange?: (time: string) => void;
- disabled?: boolean;
-}
-
-/** Calendar and optional native time input shared by event date/time popovers. */
-export function EventDateTimePopoverContent(
- props: EventDateTimePopoverContentProps
-) {
- const fieldId = createUniqueId();
- const selectedDate = createMemo(
- () => parseLocalDate(props.date) ?? new Date()
- );
-
- return (
- <div
- class={cn(
- props.time !== undefined && 'grid grid-cols-[minmax(0,1fr)_11rem]'
- )}
- >
- <div class="min-w-0 p-3">
- <Calendar
- required
- value={selectedDate()}
- onValueChange={(date) => {
- if (date) props.onDateChange(formatLocalDate(date));
- }}
- />
- </div>
- {props.time !== undefined && (
- <div class="min-w-0 border-l border-edge p-3">
- <EventTimeInput
- id={`event-${props.label.toLowerCase()}-time-${fieldId}`}
- label={`${props.label} time`}
- value={props.time ?? ''}
- onChange={(time) => props.onTimeChange?.(time)}
- disabled={props.disabled}
- />
- </div>
- )}
- </div>
- );
-}
-
-export interface EventDateFieldProps {
- label: string;
- value: string;
- onChange: (value: string) => void;
- disabled?: boolean;
- invalid?: boolean;
- describedBy?: string;
- class?: string;
- portalScope?: 'local';
- appearance?: 'underline' | 'bare';
-}
-
-/** Compact calendar date selector used by event date/time ranges. */
-export function EventDateField(props: EventDateFieldProps) {
- const [open, setOpen] = createSignal(false);
- const [portalSearchRef, setPortalSearchRef] = createSignal<HTMLDivElement>();
- const selectedDate = () => parseLocalDate(props.value);
- const portalMount = () => {
- if (props.portalScope !== 'local') return undefined;
- return (
- portalSearchRef()?.closest<HTMLElement>('.portal-scope') ?? undefined
- );
- };
-
- return (
- <Popover
- open={open() && !props.disabled}
- onOpenChange={(next) => setOpen(!props.disabled && next)}
- placement="bottom-start"
- gutter={4}
- flip
- slide
- >
- <Popover.Trigger
- aria-label={`${props.label} date`}
- aria-describedby={props.describedBy}
- aria-invalid={props.invalid || undefined}
- title={selectedDate() ? dateLabelFormatter.format(selectedDate()) : ''}
- disabled={props.disabled}
- class={cn(
- 'flex min-w-0 items-center justify-start gap-1 truncate bg-transparent text-xs font-normal outline-none disabled:cursor-not-allowed',
- props.appearance === 'bare'
- ? 'px-0'
- : 'h-9 border-b border-edge-muted px-1 focus-visible:border-accent',
- props.invalid && 'border-failure',
- props.class
- )}
- >
- <CalendarBlankIcon class="size-3 shrink-0 text-ink-extra-muted" />
- <span class="truncate">
- {selectedDate() ? dateLabelFormatter.format(selectedDate()) : 'Date'}
- </span>
- </Popover.Trigger>
-
- <div class="hidden" ref={setPortalSearchRef} />
- <Popover.Portal mount={portalMount()}>
- <Layer depth={3}>
- <Popover.Content class="z-action-menu w-72 max-w-[calc(100vw-1rem)] rounded-xl border border-edge bg-menu p-3 shadow-menu menu-open-animation">
- <Popover.Title class="sr-only">
- Choose {props.label.toLowerCase()} date
- </Popover.Title>
- <Calendar
- required
- fixedWeeks
- value={selectedDate()}
- onValueChange={(date) => {
- if (!date) return;
- props.onChange(formatLocalDate(date));
- setOpen(false);
- }}
- />
- </Popover.Content>
- </Layer>
- </Popover.Portal>
- </Popover>
- );
-}
-
-export interface EventDateTimeFieldProps {
- label: string;
- value: string;
- onChange: (value: string) => void;
- disabled?: boolean;
- invalid?: boolean;
- describedBy?: string;
- class?: string;
- portalScope?: 'local';
- appearance?: 'underline' | 'bare';
-}
-
-/** Editable date/time fields with one popup for calendar and time selection. */
-export function EventDateTimeField(props: EventDateTimeFieldProps) {
- const [open, setOpen] = createSignal(false);
- const [dateDraft, setDateDraft] = createSignal<string>();
- const [dateDraftDirty, setDateDraftDirty] = createSignal(false);
- const [timeDraft, setTimeDraft] = createSignal<string>();
- const [portalSearchRef, setPortalSearchRef] = createSignal<HTMLDivElement>();
- let anchorRef: HTMLDivElement | undefined;
-
- const date = () => splitLocalDateTime(props.value).date;
- const time = () => splitLocalDateTime(props.value).time;
- const selectedDate = () => parseLocalDate(date());
- const dateInputLabel = () =>
- selectedDate() ? dateLabelFormatter.format(selectedDate()) : 'Date';
- const portalMount = () => {
- if (props.portalScope !== 'local') return undefined;
- return (
- portalSearchRef()?.closest<HTMLElement>('.portal-scope') ?? undefined
- );
- };
- const openPopup = () => {
- if (props.disabled) return;
- setOpen(true);
- };
- const close = () => {
- setOpen(false);
- setDateDraft(undefined);
- setDateDraftDirty(false);
- setTimeDraft(undefined);
- };
- const updateDateInput = (value: string) => {
- setDateDraft(value);
- setDateDraftDirty(true);
- const parsed = parseDateInput(value);
- if (parsed) props.onChange(withLocalDate(props.value, parsed));
- };
- const commitDateInput = (value: string) => {
- if (dateDraftDirty()) {
- const parsed = parseDateInput(value);
- if (parsed) props.onChange(withLocalDate(props.value, parsed));
- }
- setDateDraft(undefined);
- setDateDraftDirty(false);
- };
- const updateTimeInput = (value: string) => {
- setTimeDraft(value);
- const parsed = parseTimeInput(value);
- if (parsed) props.onChange(withLocalTime(props.value, parsed));
- };
- const commitTimeInput = (value: string) => {
- updateTimeInput(value);
- setTimeDraft(undefined);
- };
- return (
- <Popover
- anchorRef={() => anchorRef}
- open={open() && !props.disabled}
- onOpenChange={(next) => {
- if (next) openPopup();
- else close();
- }}
- placement="bottom-start"
- gutter={4}
- flip
- slide
- >
- <div
- ref={anchorRef}
- role="group"
- aria-label={props.label}
- aria-describedby={props.describedBy}
- aria-invalid={props.invalid || undefined}
- class={cn(
- 'grid min-w-0 grid-cols-[minmax(0,1fr)_4.75rem] items-center gap-1 bg-transparent',
- props.appearance === 'bare'
- ? 'px-0'
- : 'h-9 border-b border-edge-muted px-0 focus-within:border-accent',
- props.invalid && 'border-failure',
- props.class
- )}
- onKeyDown={(event) => {
- if (event.key === 'Escape') close();
- }}
- >
- <span class="flex min-w-0 items-center gap-1 px-1">
- <CalendarBlankIcon class="size-3 shrink-0 text-ink-extra-muted" />
- <input
- type="text"
- value={dateDraft() ?? dateInputLabel()}
- aria-label={`${props.label} date`}
- aria-expanded={open()}
- aria-haspopup="dialog"
- disabled={props.disabled}
- class="min-w-0 flex-1 bg-transparent text-left text-xs text-ink outline-none disabled:cursor-not-allowed"
- onFocus={(event) => {
- openPopup();
- setDateDraft(dateInputLabel());
- setDateDraftDirty(false);
- event.currentTarget.select();
- }}
- onClick={openPopup}
- onInput={(event) => updateDateInput(event.currentTarget.value)}
- onBlur={(event) => commitDateInput(event.currentTarget.value)}
- onKeyDown={(event) => {
- if (event.key === 'Enter') {
- commitDateInput(event.currentTarget.value);
- }
- }}
- />
- </span>
- <input
- type="text"
- value={timeDraft() ?? formatTimeLabel(time())}
- aria-label={`${props.label} time`}
- aria-expanded={open()}
- aria-haspopup="listbox"
- disabled={props.disabled}
- class="min-w-0 bg-transparent text-left text-xs text-ink outline-none disabled:cursor-not-allowed"
- onFocus={(event) => {
- openPopup();
- setTimeDraft(formatTimeLabel(time()));
- event.currentTarget.select();
- }}
- onClick={openPopup}
- onInput={(event) => updateTimeInput(event.currentTarget.value)}
- onBlur={(event) => commitTimeInput(event.currentTarget.value)}
- onKeyDown={(event) => {
- if (event.key === 'Enter') {
- commitTimeInput(event.currentTarget.value);
- }
- }}
- />
- </div>
-
- <div class="hidden" ref={setPortalSearchRef} />
- <Popover.Portal mount={portalMount()}>
- <Layer depth={3}>
- <Popover.Content
- class="portal-scope z-action-menu w-[31rem] max-w-[calc(100vw-1rem)] rounded-xl border border-edge bg-menu shadow-menu menu-open-animation"
- onInteractOutside={(event) => {
- const target = event.detail.originalEvent.target;
- if (target instanceof Node && anchorRef?.contains(target)) {
- event.preventDefault();
- }
- }}
- onOpenAutoFocus={(event) => event.preventDefault()}
- onCloseAutoFocus={(event) => event.preventDefault()}
- >
- <Popover.Title class="sr-only">
- Choose {props.label.toLowerCase()} date and time
- </Popover.Title>
- <EventDateTimePopoverContent
- label={props.label}
- date={date()}
- time={time()}
- onDateChange={(nextDate) => {
- props.onChange(withLocalDate(props.value, nextDate));
- setDateDraft(undefined);
- setDateDraftDirty(false);
- }}
- onTimeChange={(nextTime) => {
- props.onChange(withLocalTime(props.value, nextTime));
- setTimeDraft(undefined);
- }}
- disabled={props.disabled}
- />
- </Popover.Content>
- </Layer>
- </Popover.Portal>
- </Popover>
- );
-}
diff --git a/apps/web/src/features/calendar/events/EventEditorForm.tsx b/apps/web/src/features/calendar/events/EventEditorForm.tsx
deleted file mode 100644
index 4707e859eb..0000000000
--- a/apps/web/src/features/calendar/events/EventEditorForm.tsx
+++ /dev/null
@@ -1,1000 +0,0 @@
-import { RecipientSelector } from '@core/component/RecipientSelector';
-import {
- type CombinedRecipientItem,
- recipientEntityMapper,
- type WithCustomUserInput,
-} from '@core/user/combinedRecipient';
-import CalendarBlankIcon from '@phosphor/calendar-blank.svg';
-import CalendarDotsIcon from '@phosphor/calendar-dots.svg';
-import MapPinIcon from '@phosphor/map-pin.svg';
-import SpinnerIcon from '@phosphor/spinner.svg';
-import TextAlignLeftIcon from '@phosphor/text-align-left.svg';
-import UsersIcon from '@phosphor/users.svg';
-import type { EventTime } from '@service-email/generated/schemas/eventTime';
-import { Button, Checkbox, cn, Select, Tooltip } from '@ui';
-import {
- addDays,
- addHours,
- addMonths,
- differenceInCalendarDays,
- format,
- isMatch,
- parseISO,
- startOfHour,
-} from 'date-fns';
-import {
- type Accessor,
- createMemo,
- createSignal,
- createUniqueId,
- For,
- Show,
-} from 'solid-js';
-import { EventDateField, EventDateTimeField } from './EventDateTimeField';
-import { formatRecurrenceDescription } from './recurrence-description';
-import {
- buildRecurrenceLines,
- defaultCustomConfig,
- parseRecurrenceConfig,
- type RecurrenceConfig,
- recurrenceConfigsEqual,
- recurrencePresetsFor,
- WEEKDAY_CODES,
- type WeekdayCode,
-} from './recurrence-editor';
-import type { CalendarEvent } from './types';
-
-/** `<input type="date">` value. */
-const DATE_VALUE = 'yyyy-MM-dd';
-/** `<input type="datetime-local">` value. */
-const DATETIME_VALUE = "yyyy-MM-dd'T'HH:mm";
-
-const EDITOR_INPUT_CLASS =
- 'rounded-none! border-x-0! border-t-0! border-b! px-0! sm:text-xs!';
-const EDITOR_TITLE_INPUT_CLASS =
- 'rounded-none! border-x-0! border-t-0! border-b! px-0!';
-
-const isDateOnly = (value: string) => isMatch(value, DATE_VALUE);
-
-type EditorSelectOption<Value extends string = string> = {
- value: Value;
- label: string;
-};
-
-/** Option displayed by an event editor recurrence selector. */
-export type EventEditorRecurrenceOption = EditorSelectOption;
-
-const REPEAT_FREQUENCY_OPTIONS: EditorSelectOption<
- RecurrenceConfig['frequency']
->[] = [
- { value: 'DAILY', label: 'day' },
- { value: 'WEEKLY', label: 'week' },
- { value: 'MONTHLY', label: 'month' },
- { value: 'YEARLY', label: 'year' },
-];
-
-function shiftDateValue(value: string, days: number) {
- return format(addDays(parseISO(value), days), DATE_VALUE);
-}
-
-/** Default editor slot: the next full hour, one hour long. */
-function defaultEditorTimes(reference: Date) {
- const start = addHours(startOfHour(reference), 1);
- return { start, end: addHours(start, 1) };
-}
-
-/** Values used to initialize the shared event editor form. */
-export interface EventEditorInitialValues {
- title: string;
- allDay: boolean;
- /** `datetime-local` value, or `date` value in all-day mode. */
- start: string;
- /** Inclusive end shown to the user; all-day submissions add the exclusive day. */
- end: string;
- recurrenceLines: string[];
- calendarId?: string;
- guests: string;
- location: string;
- description: string;
-}
-
-/** Calendar option displayed by the event editor. */
-export interface EventEditorCalendarOption {
- id: string;
- label: string;
- color: string;
-}
-
-/** Editable fields that a create/edit owner may disable. */
-export type EventEditorField =
- | 'title'
- | 'allDay'
- | 'start'
- | 'end'
- | 'recurrence'
- | 'calendar'
- | 'guests'
- | 'location'
- | 'description';
-
-/** Field-level disabled state supplied by the create/edit owner. */
-export type EventEditorDisabledFields = Partial<
- Record<EventEditorField, boolean>
->;
-
-/** Validated values emitted by the shared event editor form. */
-export interface EventEditorSubmitValues {
- title: string;
- time: EventTime;
- recurrenceLines?: string[];
- calendarId?: string;
- guestEmails: string[];
- location: string;
- description: string;
-}
-
-export function defaultEditorInitialValues(
- reference = new Date()
-): EventEditorInitialValues {
- const { start, end } = defaultEditorTimes(reference);
- return {
- title: '',
- allDay: false,
- start: format(start, DATETIME_VALUE),
- end: format(end, DATETIME_VALUE),
- recurrenceLines: [],
- calendarId: undefined,
- guests: '',
- location: '',
- description: '',
- };
-}
-
-/** Converts a FullCalendar-style selected range into create-event values. */
-export function calendarSelectionToEditorInitialValues(selection: {
- start: Date;
- end: Date;
- allDay: boolean;
-}): EventEditorInitialValues {
- const initialValues = defaultEditorInitialValues(selection.start);
- if (selection.allDay) {
- return {
- ...initialValues,
- allDay: true,
- start: format(selection.start, DATE_VALUE),
- end: format(addDays(selection.end, -1), DATE_VALUE),
- };
- }
-
- return {
- ...initialValues,
- start: format(selection.start, DATETIME_VALUE),
- end: format(selection.end, DATETIME_VALUE),
- };
-}
-
-/** Converts an existing event into values for the shared editor. */
-export function calendarEventToEditorInitialValues(
- event: CalendarEvent
-): EventEditorInitialValues {
- const guests = event.attendees
- .filter((attendee) => attendee.isOrganizer || !attendee.isSelf)
- .map((attendee) => attendee.email)
- .join(', ');
-
- if (event.allDay) {
- const start = isDateOnly(event.start)
- ? event.start
- : format(new Date(event.start), DATE_VALUE);
- const exclusiveEnd = isDateOnly(event.end)
- ? event.end
- : format(new Date(event.end), DATE_VALUE);
- return {
- title: event.title,
- allDay: true,
- start,
- end: shiftDateValue(exclusiveEnd, -1),
- recurrenceLines: [...event.recurrenceLines],
- calendarId: event.calendar.id,
- guests,
- location: event.location ?? '',
- description: event.description ?? '',
- };
- }
-
- return {
- title: event.title,
- allDay: false,
- start: format(new Date(event.start), DATETIME_VALUE),
- end: format(new Date(event.end), DATETIME_VALUE),
- recurrenceLines: [...event.recurrenceLines],
- calendarId: event.calendar.id,
- guests,
- location: event.location ?? '',
- description: event.description ?? '',
- };
-}
-
-export function buildEventTime(
- state: EventEditorInitialValues
-): EventTime | undefined {
- if (state.allDay) {
- if (!state.start || !state.end || state.end < state.start) {
- return undefined;
- }
- return {
- kind: 'allDay',
- startDate: state.start,
- endDate: shiftDateValue(state.end, 1),
- };
- }
-
- const start = new Date(state.start);
- const end = new Date(state.end);
- if (
- Number.isNaN(start.getTime()) ||
- Number.isNaN(end.getTime()) ||
- end <= start
- ) {
- return undefined;
- }
- return {
- kind: 'timed',
- startsAt: start.toISOString(),
- endsAt: end.toISOString(),
- timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
- };
-}
-
-function parseGuestEmails(value: string) {
- return [...new Set(value.split(/[\s,;]+/).filter((email) => email !== ''))];
-}
-
-export type EventEditorGuestKind = 'user' | 'contact';
-export type EventEditorGuestOption =
- CombinedRecipientItem<EventEditorGuestKind>;
-export type SelectedEventEditorGuest =
- WithCustomUserInput<EventEditorGuestKind>;
-
-export function guestEmail(option: SelectedEventEditorGuest) {
- return option.data.email;
-}
-
-export function initialGuestOptions(
- value: string,
- options: EventEditorGuestOption[]
-): SelectedEventEditorGuest[] {
- return parseGuestEmails(value).map((email) => {
- const existing = options.find(
- (option) => guestEmail(option).toLowerCase() === email.toLowerCase()
- );
- return (
- existing ??
- recipientEntityMapper('custom')({
- id: `macro|${email}`,
- email,
- invalid: false,
- })
- );
- });
-}
-
-/** Both editor times switch representation when all-day toggles. */
-export function convertTimesForAllDay(
- state: EventEditorInitialValues,
- allDay: boolean
-) {
- if (allDay === state.allDay) return state;
- if (allDay) {
- return {
- ...state,
- allDay,
- start: state.start.slice(0, 10),
- end: state.end.slice(0, 10),
- };
- }
- const { start, end } = defaultEditorTimes(parseISO(state.start));
- return {
- ...state,
- allDay,
- start: format(start, DATETIME_VALUE),
- end: format(end, DATETIME_VALUE),
- };
-}
-
-export function moveAllDayRange(
- state: EventEditorInitialValues,
- nextStart: string
-): EventEditorInitialValues {
- if (nextStart === '') return { ...state, start: '', end: '' };
- const duration = differenceInCalendarDays(
- parseISO(state.end),
- parseISO(state.start)
- );
- const durationDays = Number.isFinite(duration) ? Math.max(0, duration) : 0;
- return {
- ...state,
- start: nextStart,
- end: shiftDateValue(nextStart, durationDays),
- };
-}
-
-export interface CreateEventEditorStateOptions {
- initialValues: EventEditorInitialValues;
- state: Accessor<EventEditorInitialValues>;
-}
-
-/** Shared recurrence and validation state used by both event editor layouts. */
-export function createEventEditorState(options: CreateEventEditorStateOptions) {
- const initialLines = [...options.initialValues.recurrenceLines];
- const initialConfig =
- initialLines.length > 0 ? parseRecurrenceConfig(initialLines) : undefined;
- const hasUnrepresentableRule = initialLines.length > 0 && !initialConfig;
-
- const startForRecurrence = createMemo(() => {
- const start = options.state().start;
- const parsed = options.state().allDay ? parseISO(start) : new Date(start);
- return Number.isNaN(parsed.getTime()) ? new Date() : parsed;
- });
- const presets = createMemo(() => recurrencePresetsFor(startForRecurrence()));
- const initialChoice = () => {
- if (initialLines.length === 0) return 'none';
- if (!initialConfig) return 'existing';
- const initialStart = options.initialValues.allDay
- ? parseISO(options.initialValues.start)
- : new Date(options.initialValues.start);
- const preset = recurrencePresetsFor(initialStart).find((candidate) =>
- recurrenceConfigsEqual(candidate.config, initialConfig)
- );
- return preset?.id ?? 'custom';
- };
- const [recurrenceChoice, setRecurrenceChoice] = createSignal(initialChoice());
- const recurrenceOptions = createMemo<EventEditorRecurrenceOption[]>(() => {
- const values = [
- { value: 'none', label: 'Does not repeat' },
- ...presets().map((preset) => ({
- value: preset.id,
- label: preset.label,
- })),
- ];
- if (hasUnrepresentableRule) {
- values.push({
- value: 'existing',
- label: `Custom: ${
- formatRecurrenceDescription(initialLines) ?? 'existing rule'
- } (unchanged)`,
- });
- }
- values.push({ value: 'custom', label: 'Custom' });
- return values;
- });
- const selectedRecurrenceOption = () =>
- recurrenceOptions().find((option) => option.value === recurrenceChoice()) ??
- recurrenceOptions()[0];
- const [customConfig, setCustomConfig] = createSignal<RecurrenceConfig>(
- initialConfig ?? defaultCustomConfig(startForRecurrence())
- );
- const changeRecurrenceChoice = (choice: string) => {
- if (choice === 'custom') {
- const seed =
- presets().find((preset) => preset.id === recurrenceChoice())?.config ??
- initialConfig ??
- defaultCustomConfig(startForRecurrence());
- setCustomConfig(seed);
- }
- setRecurrenceChoice(choice);
- };
- const customValid = createMemo(() => {
- if (recurrenceChoice() !== 'custom') return true;
- const config = customConfig();
- if (!Number.isInteger(config.interval) || config.interval < 1) return false;
- if (config.frequency === 'WEEKLY' && config.byDay.length === 0) {
- return false;
- }
- if (config.ends.kind === 'on') return config.ends.date !== '';
- if (config.ends.kind === 'after') {
- return Number.isInteger(config.ends.count) && config.ends.count >= 1;
- }
- return true;
- });
- const recurrenceLines = (): string[] | undefined => {
- const choice = recurrenceChoice();
- if (choice === 'existing') return undefined;
- if (choice === 'none') return [];
- if (choice === 'custom') {
- return buildRecurrenceLines(customConfig(), options.state().allDay);
- }
- const preset = presets().find((candidate) => candidate.id === choice);
- return preset
- ? buildRecurrenceLines(preset.config, options.state().allDay)
- : undefined;
- };
- const dateRangeError = createMemo(() => {
- const current = options.state();
- if (!current.start || !current.end) return undefined;
- if (current.allDay) {
- return current.end < current.start
- ? 'End date cannot be before the start date.'
- : undefined;
- }
- const start = new Date(current.start);
- const end = new Date(current.end);
- if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
- return undefined;
- }
- return end <= start ? 'End time must be after the start time.' : undefined;
- });
- const eventTime = createMemo(() => buildEventTime(options.state()));
- const canSave = () =>
- options.state().title.trim() !== '' &&
- eventTime() !== undefined &&
- customValid();
-
- return {
- startForRecurrence,
- recurrenceChoice,
- recurrenceOptions,
- selectedRecurrenceOption,
- customConfig,
- setCustomConfig,
- changeRecurrenceChoice,
- recurrenceLines,
- dateRangeError,
- eventTime,
- canSave,
- };
-}
-
-export interface EventEditorFormProps {
- initialValues?: EventEditorInitialValues;
- disabledFields?: EventEditorDisabledFields;
- calendarOptions: EventEditorCalendarOption[];
- guestOptions: Accessor<EventEditorGuestOption[]>;
- showRecurringEditNotice?: boolean;
- pending: boolean;
- class?: string;
- onCancel: () => void;
- onSubmit: (values: EventEditorSubmitValues) => void;
-}
-
-/** Shared create/edit event form, independent of its dialog or drawer shell. */
-export function EventEditorForm(props: EventEditorFormProps) {
- const formId = createUniqueId();
- const recurrenceEndsName = `recurrence-ends-${formId}`;
- const guestInputId = `event-guests-${formId}`;
- const dateRangeErrorId = `event-date-range-error-${formId}`;
-
- const initialValues =
- props.initialValues ?? defaultEditorInitialValues(new Date());
-
- const [state, setState] = createSignal<EventEditorInitialValues>({
- ...initialValues,
- recurrenceLines: [...initialValues.recurrenceLines],
- });
-
- const [selectedGuests, setSelectedGuests] = createSignal<
- SelectedEventEditorGuest[]
- >(initialGuestOptions(initialValues.guests, props.guestOptions()));
-
- const fieldIsDisabled = (field: EventEditorField) =>
- props.disabledFields?.[field] === true;
-
- const inputIsDisabled = (field: EventEditorField) =>
- props.pending || fieldIsDisabled(field);
-
- const effectiveCalendarId = () =>
- state().calendarId ?? props.calendarOptions[0]?.id;
-
- const editorState = createEventEditorState({ initialValues, state });
- const {
- startForRecurrence,
- recurrenceChoice,
- recurrenceOptions,
- selectedRecurrenceOption,
- customConfig,
- setCustomConfig,
- changeRecurrenceChoice,
- recurrenceLines,
- dateRangeError,
- eventTime,
- canSave,
- } = editorState;
-
- const selectedFrequencyOption = () =>
- REPEAT_FREQUENCY_OPTIONS.find(
- (option) => option.value === customConfig().frequency
- ) ?? REPEAT_FREQUENCY_OPTIONS[0];
-
- const selectedCalendarOption = () =>
- props.calendarOptions.find(
- (option) => option.id === effectiveCalendarId()
- ) ?? props.calendarOptions[0];
-
- const toggleWeekday = (code: WeekdayCode) => {
- setCustomConfig((config) => ({
- ...config,
- byDay: config.byDay.includes(code)
- ? config.byDay.filter((day) => day !== code)
- : [...config.byDay, code],
- }));
- };
-
- const setEnds = (ends: RecurrenceConfig['ends']) =>
- setCustomConfig((config) => ({ ...config, ends }));
-
- const submit = () => {
- const time = eventTime();
- if (!time || !canSave() || props.pending) return;
- const current = state();
- props.onSubmit({
- title: current.title,
- time,
- recurrenceLines: recurrenceLines(),
- calendarId: effectiveCalendarId(),
- guestEmails: selectedGuests().map(guestEmail),
- location: current.location,
- description: current.description,
- });
- };
-
- const AllDayCheckbox = () => (
- <Checkbox
- checked={state().allDay}
- disabled={inputIsDisabled('allDay')}
- onChange={(allDay) => setState(convertTimesForAllDay(state(), allDay))}
- class="shrink-0 text-xs text-ink-muted"
- >
- <Checkbox.Control />
- <Checkbox.Label>All day</Checkbox.Label>
- </Checkbox>
- );
-
- return (
- <form
- class={cn(
- 'grid grid-cols-[1.25rem_minmax(0,1fr)] gap-4 px-4 pb-4 pt-1 text-sm text-ink-muted sm:grid-cols-[1rem_minmax(0,1fr)] sm:text-xs [&_:disabled]:cursor-not-allowed',
- props.class
- )}
- onSubmit={(event) => {
- event.preventDefault();
- submit();
- }}
- >
- <CalendarBlankIcon
- aria-hidden="true"
- class="mt-2 size-5 text-ink-extra-muted sm:size-4"
- />
-
- <div class="flex min-w-0 flex-col gap-3">
- <input
- type="text"
- value={state().title}
- onInput={(event) =>
- setState({ ...state(), title: event.currentTarget.value })
- }
- placeholder="Add title"
- aria-label="Title"
- class={cn(
- 'settings-input h-auto min-h-9 w-full text-lg! font-semibold! leading-snug text-ink sm:text-base!',
- EDITOR_TITLE_INPUT_CLASS
- )}
- disabled={inputIsDisabled('title')}
- />
-
- <div class="flex min-w-0 flex-col gap-1">
- <Show
- when={state().allDay}
- fallback={
- <div class="flex min-w-0 items-center gap-1.5">
- <EventDateTimeField
- label="Start"
- value={state().start}
- onChange={(start) => setState({ ...state(), start })}
- disabled={inputIsDisabled('start')}
- portalScope="local"
- class="min-w-0 max-w-40 flex-1 basis-0"
- />
- <span aria-hidden="true" class="shrink-0 text-ink-extra-muted">
- –
- </span>
- <EventDateTimeField
- label="End"
- value={state().end}
- onChange={(end) => setState({ ...state(), end })}
- disabled={inputIsDisabled('end')}
- invalid={dateRangeError() !== undefined}
- describedBy={dateRangeError() ? dateRangeErrorId : undefined}
- portalScope="local"
- class="min-w-0 max-w-40 flex-1 basis-0"
- />
- </div>
- }
- >
- <div class="flex min-w-0 items-center gap-1.5">
- <EventDateField
- label="Start"
- value={state().start}
- onChange={(date) => setState(moveAllDayRange(state(), date))}
- disabled={inputIsDisabled('start')}
- portalScope="local"
- class="min-w-0 max-w-40 flex-1 basis-0"
- />
- <span aria-hidden="true" class="shrink-0 text-ink-extra-muted">
- –
- </span>
- <EventDateField
- label="End"
- value={state().end}
- onChange={(end) => setState({ ...state(), end })}
- disabled={inputIsDisabled('end')}
- invalid={dateRangeError() !== undefined}
- describedBy={dateRangeError() ? dateRangeErrorId : undefined}
- portalScope="local"
- class="min-w-0 max-w-40 flex-1 basis-0"
- />
- </div>
- </Show>
-
- <Show when={dateRangeError()}>
- {(error) => (
- <p
- id={dateRangeErrorId}
- role="alert"
- class="text-xs text-failure"
- >
- {error()}
- </p>
- )}
- </Show>
- </div>
-
- <div class="flex flex-col gap-2">
- <div class="flex min-w-0 items-center gap-3">
- <AllDayCheckbox />
- <Select<EditorSelectOption>
- options={recurrenceOptions()}
- value={selectedRecurrenceOption()}
- onChange={(option) =>
- option && changeRecurrenceChoice(option.value)
- }
- optionValue="value"
- optionTextValue="label"
- disabled={inputIsDisabled('recurrence')}
- class="ml-auto w-40 min-w-40 max-w-40 shrink-0"
- >
- <Select.Trigger aria-label="Repeats" class={EDITOR_INPUT_CLASS}>
- <Select.Value<EditorSelectOption>>
- {(selectState) => selectState.selectedOption().label}
- </Select.Value>
- <Select.Icon />
- </Select.Trigger>
- <Select.Content portalScope="local">
- <Select.Listbox />
- </Select.Content>
- </Select>
- </div>
-
- <Show when={recurrenceChoice() === 'custom'}>
- <div class="border-edge-muted flex flex-col gap-2.5 rounded-lg border p-2.5 text-xs text-ink-muted">
- <div class="flex items-center gap-2">
- <span>Repeat every</span>
- <input
- type="number"
- min="1"
- value={customConfig().interval}
- onInput={(event) =>
- setCustomConfig((config) => ({
- ...config,
- interval: event.currentTarget.valueAsNumber,
- }))
- }
- aria-label="Repeat interval"
- class={cn('settings-input w-16', EDITOR_INPUT_CLASS)}
- disabled={inputIsDisabled('recurrence')}
- />
- <Select<EditorSelectOption<RecurrenceConfig['frequency']>>
- options={REPEAT_FREQUENCY_OPTIONS}
- value={selectedFrequencyOption()}
- onChange={(option) =>
- option &&
- setCustomConfig((config) => ({
- ...config,
- frequency: option.value,
- }))
- }
- optionValue="value"
- optionTextValue="label"
- disabled={inputIsDisabled('recurrence')}
- >
- <Select.Trigger
- aria-label="Repeat unit"
- class={cn('w-28', EDITOR_INPUT_CLASS)}
- >
- <Select.Value<
- EditorSelectOption<RecurrenceConfig['frequency']>
- >>
- {(selectState) => selectState.selectedOption().label}
- </Select.Value>
- <Select.Icon />
- </Select.Trigger>
- <Select.Content portalScope="local">
- <Select.Listbox />
- </Select.Content>
- </Select>
- </div>
-
- <Show when={customConfig().frequency === 'WEEKLY'}>
- <div class="flex items-center gap-1.5">
- <span class="mr-1">Repeat on</span>
- <For each={WEEKDAY_CODES}>
- {(code) => (
- <Button
- type="button"
- variant={
- customConfig().byDay.includes(code)
- ? 'active'
- : 'ghost'
- }
- size="icon-sm"
- class="rounded-full text-xxs"
- aria-label={code}
- aria-pressed={customConfig().byDay.includes(code)}
- disabled={inputIsDisabled('recurrence')}
- onClick={() => toggleWeekday(code)}
- >
- {code[0]}
- </Button>
- )}
- </For>
- </div>
- </Show>
-
- <div class="flex flex-col gap-1.5">
- <span>Ends</span>
- <label class="flex items-center gap-2">
- <input
- type="radio"
- name={recurrenceEndsName}
- checked={customConfig().ends.kind === 'never'}
- onChange={() => setEnds({ kind: 'never' })}
- disabled={inputIsDisabled('recurrence')}
- />
- Never
- </label>
- <div class="flex items-center gap-2">
- <label class="flex items-center gap-2">
- <input
- type="radio"
- name={recurrenceEndsName}
- checked={customConfig().ends.kind === 'on'}
- onChange={() =>
- setEnds({
- kind: 'on',
- date: format(
- addMonths(startForRecurrence(), 3),
- DATE_VALUE
- ),
- })
- }
- disabled={inputIsDisabled('recurrence')}
- />
- On
- </label>
- <Show when={customConfig().ends.kind === 'on'}>
- <input
- type="date"
- value={
- customConfig().ends.kind === 'on'
- ? (
- customConfig().ends as {
- kind: 'on';
- date: string;
- }
- ).date
- : ''
- }
- onInput={(event) =>
- setEnds({
- kind: 'on',
- date: event.currentTarget.value,
- })
- }
- aria-label="Ends on date"
- class={cn('settings-input', EDITOR_INPUT_CLASS)}
- disabled={inputIsDisabled('recurrence')}
- />
- </Show>
- </div>
- <div class="flex items-center gap-2">
- <label class="flex items-center gap-2">
- <input
- type="radio"
- name={recurrenceEndsName}
- checked={customConfig().ends.kind === 'after'}
- onChange={() => setEnds({ kind: 'after', count: 13 })}
- disabled={inputIsDisabled('recurrence')}
- />
- After
- </label>
- <Show when={customConfig().ends.kind === 'after'}>
- <input
- type="number"
- min="1"
- value={
- customConfig().ends.kind === 'after'
- ? (
- customConfig().ends as {
- kind: 'after';
- count: number;
- }
- ).count
- : 13
- }
- onInput={(event) =>
- setEnds({
- kind: 'after',
- count: event.currentTarget.valueAsNumber,
- })
- }
- aria-label="Ends after occurrences"
- class={cn('settings-input w-20', EDITOR_INPUT_CLASS)}
- disabled={inputIsDisabled('recurrence')}
- />
- <span>occurrences</span>
- </Show>
- </div>
- </div>
- </div>
- </Show>
- </div>
- </div>
-
- <Show
- when={props.calendarOptions.length > 1 || fieldIsDisabled('calendar')}
- >
- <div class="contents">
- <CalendarDotsIcon
- aria-hidden="true"
- class="mt-2 size-5 text-ink-extra-muted sm:size-4"
- />
- <Tooltip
- label="Moving an existing event to another calendar is not currently supported"
- placement="bottom"
- disabled={!fieldIsDisabled('calendar')}
- class="w-full"
- >
- <div class="w-full">
- <Select<EventEditorCalendarOption>
- options={props.calendarOptions}
- value={selectedCalendarOption()}
- onChange={(option) =>
- option && setState({ ...state(), calendarId: option.id })
- }
- optionValue="id"
- optionTextValue="label"
- disabled={inputIsDisabled('calendar')}
- >
- <Select.Trigger
- aria-label="Calendar"
- class={EDITOR_INPUT_CLASS}
- >
- <Select.Value<EventEditorCalendarOption>>
- {(selectState) => selectState.selectedOption().label}
- </Select.Value>
- <Select.Icon />
- </Select.Trigger>
- <Select.Content portalScope="local">
- <Select.Listbox />
- </Select.Content>
- </Select>
- </div>
- </Tooltip>
- </div>
- </Show>
-
- <UsersIcon
- aria-hidden="true"
- class="mt-2 size-5 text-ink-extra-muted sm:size-4"
- />
-
- <div class="min-w-0">
- <label for={guestInputId} class="sr-only">
- Guests
- </label>
- <Tooltip
- label="Adding guests to an existing event is not currently supported"
- placement="bottom"
- disabled={!fieldIsDisabled('guests')}
- class="w-full"
- >
- <div class="w-full">
- <RecipientSelector<EventEditorGuestKind>
- inputId={guestInputId}
- options={props.guestOptions}
- selectedOptions={selectedGuests()}
- setSelectedOptions={(next) => {
- if (!inputIsDisabled('guests')) setSelectedGuests(next);
- }}
- placeholder="Add guests"
- hideBorder
- noPadding
- disabled={inputIsDisabled('guests')}
- portalScope="local"
- class={cn(
- 'min-h-9 border-edge-muted bg-transparent! py-1 text-sm focus-within:border-accent sm:text-xs [&_input]:sm:text-xs!',
- EDITOR_INPUT_CLASS,
- inputIsDisabled('guests') && 'opacity-70'
- )}
- />
- </div>
- </Tooltip>
- </div>
-
- <MapPinIcon
- aria-hidden="true"
- class="mt-2 size-5 text-ink-extra-muted sm:size-4"
- />
-
- <input
- type="text"
- value={state().location}
- onInput={(event) =>
- setState({ ...state(), location: event.currentTarget.value })
- }
- placeholder="Add location"
- aria-label="Location"
- class={cn('settings-input w-full', EDITOR_INPUT_CLASS)}
- disabled={inputIsDisabled('location')}
- />
-
- <TextAlignLeftIcon
- aria-hidden="true"
- class="mt-2 size-5 text-ink-extra-muted sm:size-4"
- />
-
- <textarea
- value={state().description}
- onInput={(event) =>
- setState({ ...state(), description: event.currentTarget.value })
- }
- placeholder="Add description"
- aria-label="Description"
- rows={3}
- class={cn(
- 'settings-input min-h-20 w-full resize-y py-2',
- EDITOR_INPUT_CLASS
- )}
- disabled={inputIsDisabled('description')}
- />
-
- <Show when={props.showRecurringEditNotice}>
- <span class="col-start-2 text-xs text-ink-extra-muted">
- Changes apply to all occurrences
- </span>
- </Show>
-
- <div class="border-edge-muted col-span-2 -mx-4 -mb-4 flex items-center justify-end gap-1 border-t bg-active px-4 py-2.5">
- <Button
- type="button"
- variant="ghost"
- class="rounded-lg"
- disabled={props.pending}
- onClick={props.onCancel}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- variant="cta"
- class="rounded-lg"
- disabled={!canSave() || props.pending}
- aria-label="Save"
- >
- <Show when={props.pending} fallback="Save">
- <SpinnerIcon class="size-4 animate-spin" />
- </Show>
- </Button>
- </div>
- </form>
- );
-}
diff --git a/apps/web/src/features/calendar/events/calendar-occurrence-mapper.test.ts b/apps/web/src/features/calendar/events/calendar-occurrence-mapper.test.ts
deleted file mode 100644
index 23f3f3e1bb..0000000000
--- a/apps/web/src/features/calendar/events/calendar-occurrence-mapper.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';
-import { describe, expect, it } from 'vitest';
-import {
- DEFAULT_CALENDAR_SOURCE,
- mapCalendarOccurrence,
-} from './calendar-occurrence-mapper';
-
-const item = (time: CalendarOccurrenceItem['occurrence']['time']) =>
- ({
- event: {
- id: 'event-1',
- title: 'Planning',
- location: null,
- description: 'Weekly planning',
- conferenceUrl: 'https://meet.example.com/planning',
- conferenceProvider: 'google_meet',
- organizerName: 'Alex Rivera',
- organizerEmail: '[email protected]',
- attendees: [
- {
- email: '[email protected]',
- displayName: 'Alex Rivera',
- responseStatus: 'accepted',
- isOrganizer: true,
- isOptional: false,
- isSelf: false,
- },
- ],
- recurrenceLines: ['RRULE:FREQ=WEEKLY'],
- isReadOnly: true,
- },
- occurrence: {
- occurrenceKey: '2026-08-04T14:00:00+00:00',
- recurrenceId: 'recurrence-1',
- isCancelled: true,
- time,
- },
- }) as CalendarOccurrenceItem;
-
-describe('mapCalendarOccurrence', () => {
- it('maps a timed occurrence using its occurrence span', () => {
- const event = mapCalendarOccurrence(
- item({
- kind: 'timed',
- startsAt: '2026-08-04T15:00:00Z',
- endsAt: '2026-08-04T16:00:00Z',
- timeZone: 'America/New_York',
- })
- );
-
- expect(event).toMatchObject({
- eventId: 'event-1',
- occurrenceKey: '2026-08-04T14:00:00+00:00',
- recurrenceId: 'recurrence-1',
- start: '2026-08-04T15:00:00Z',
- end: '2026-08-04T16:00:00Z',
- allDay: false,
- isCancelled: true,
- isReadOnly: true,
- conferenceUrl: 'https://meet.example.com/planning',
- conferenceProvider: 'google_meet',
- organizerName: 'Alex Rivera',
- organizerEmail: '[email protected]',
- recurrenceLines: ['RRULE:FREQ=WEEKLY'],
- timeZone: 'America/New_York',
- title: 'Planning',
- description: 'Weekly planning',
- location: undefined,
- calendar: DEFAULT_CALENDAR_SOURCE,
- });
- });
-
- it('preserves exclusive local dates for an all-day occurrence', () => {
- const event = mapCalendarOccurrence(
- item({
- kind: 'allDay',
- startDate: '2026-08-04',
- endDate: '2026-08-06',
- })
- );
-
- expect(event).toMatchObject({
- start: '2026-08-04',
- end: '2026-08-06',
- allDay: true,
- });
- });
-
- it('creates distinct render IDs for occurrences of the same event', () => {
- const first = item({
- kind: 'allDay',
- startDate: '2026-08-04',
- endDate: '2026-08-05',
- });
- const second = {
- ...first,
- occurrence: {
- ...first.occurrence,
- occurrenceKey: '2026-08-11',
- },
- };
-
- expect(mapCalendarOccurrence(first).id).not.toBe(
- mapCalendarOccurrence(second).id
- );
- });
-});
diff --git a/apps/web/src/features/calendar/events/calendar-occurrence-mapper.ts b/apps/web/src/features/calendar/events/calendar-occurrence-mapper.ts
deleted file mode 100644
index 8c02139765..0000000000
--- a/apps/web/src/features/calendar/events/calendar-occurrence-mapper.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';
-import type {
- CalendarEvent,
- CalendarSource,
- ConferenceProvider,
-} from './types';
-
-/** Shared presentation source until calendar/account metadata is exposed. */
-export const DEFAULT_CALENDAR_SOURCE: CalendarSource = {
- id: 'calendar',
- name: 'Calendar',
- color: 'var(--color-accent)',
-};
-
-/** Maps one backend occurrence projection into the calendar view model. */
-export function mapCalendarOccurrence(
- item: CalendarOccurrenceItem,
- source: CalendarSource = DEFAULT_CALENDAR_SOURCE
-): CalendarEvent {
- const { event, occurrence } = item;
- const time = occurrence.time;
- const range =
- time.kind === 'timed'
- ? { allDay: false, start: time.startsAt, end: time.endsAt }
- : { allDay: true, start: time.startDate, end: time.endDate };
-
- return {
- ...range,
- id: JSON.stringify([event.id, occurrence.occurrenceKey]),
- eventId: event.id,
- occurrenceKey: occurrence.occurrenceKey,
- recurrenceId: occurrence.recurrenceId ?? undefined,
- recurrenceLines: event.recurrenceLines ?? [],
- isCancelled: occurrence.isCancelled,
- isReadOnly: event.isReadOnly,
- conferenceUrl: event.conferenceUrl ?? undefined,
- conferenceProvider:
- (event.conferenceProvider as ConferenceProvider | null | undefined) ??
- undefined,
- organizerName: event.organizerName ?? undefined,
- organizerEmail: event.organizerEmail ?? undefined,
- attendees: event.attendees ?? [],
- reminders: event.reminders ?? undefined,
- calendarId: event.calendarId ?? undefined,
- timeZone: time.kind === 'timed' ? (time.timeZone ?? undefined) : undefined,
- title: event.title,
- calendar: source,
- location: event.location ?? undefined,
- description: event.description ?? undefined,
- };
-}
diff --git a/apps/web/src/features/calendar/events/event-composer-dirty.ts b/apps/web/src/features/calendar/events/event-composer-dirty.ts
deleted file mode 100644
index 9aaca3b477..0000000000
--- a/apps/web/src/features/calendar/events/event-composer-dirty.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import {
- parseRecurrenceConfig,
- recurrenceConfigsEqual,
-} from './recurrence-editor';
-
-/** Form values that participate in event-composer dirty-state detection. */
-export interface EventComposerFormSnapshot {
- title: string;
- allDay: boolean;
- start: string;
- end: string;
- recurrenceLines: readonly string[];
- calendarId?: string;
- guestEmails: readonly string[];
- location: string;
- description: string;
-}
-
-function normalizedGuestEmails(emails: readonly string[]) {
- return emails.map((email) => email.trim().toLowerCase()).sort();
-}
-
-function arraysEqual(first: readonly string[], second: readonly string[]) {
- return (
- first.length === second.length &&
- first.every((value, index) => value === second[index])
- );
-}
-
-function recurrenceLinesEqual(
- first: readonly string[],
- second: readonly string[]
-) {
- if (arraysEqual(first, second)) return true;
-
- const firstConfig = parseRecurrenceConfig([...first]);
- const secondConfig = parseRecurrenceConfig([...second]);
- return (
- firstConfig !== undefined &&
- secondConfig !== undefined &&
- recurrenceConfigsEqual(firstConfig, secondConfig)
- );
-}
-
-/** Whether the current composer values differ meaningfully from their baseline. */
-export function isEventComposerFormDirty(
- initial: EventComposerFormSnapshot,
- current: EventComposerFormSnapshot
-) {
- return (
- initial.title !== current.title ||
- initial.allDay !== current.allDay ||
- initial.start !== current.start ||
- initial.end !== current.end ||
- initial.calendarId !== current.calendarId ||
- initial.location !== current.location ||
- initial.description !== current.description ||
- !arraysEqual(
- normalizedGuestEmails(initial.guestEmails),
- normalizedGuestEmails(current.guestEmails)
- ) ||
- !recurrenceLinesEqual(initial.recurrenceLines, current.recurrenceLines)
- );
-}
diff --git a/apps/web/src/features/calendar/events/event-mapper.ts b/apps/web/src/features/calendar/events/event-mapper.ts
deleted file mode 100644
index 8fe0731a8b..0000000000
--- a/apps/web/src/features/calendar/events/event-mapper.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import type { EventInput } from '@fullcalendar/core';
-import { canEditCalendarEventTime } from './event-interaction';
-import { multiDayTimedDisplayRange } from './multi-day-rendering';
-import type { CalendarEvent } from './types';
-
-/** Maps calendar-owned event data into FullCalendar's rendering contract. */
-export function mapCalendarEventToFullCalendar(
- event: CalendarEvent
-): EventInput {
- const timeEditable = canEditCalendarEventTime(event);
- const allDayRange = event.allDay
- ? undefined
- : multiDayTimedDisplayRange(new Date(event.start), new Date(event.end));
- const isRenderedAllDay = event.allDay || allDayRange !== undefined;
- // FullCalendar reports interactions from the all-day row as true all-day
- // ranges. Keep projected timed events fixed so their timestamps are not
- // accidentally replaced with date-only API values.
- const interactionEditable = timeEditable && allDayRange === undefined;
-
- return {
- id: event.id,
- title: event.title,
- start: allDayRange?.start ?? event.start,
- end: allDayRange?.end ?? event.end,
- allDay: isRenderedAllDay,
- display: 'block',
- startEditable: interactionEditable,
- durationEditable: interactionEditable,
- extendedProps: {
- calendarEventId: event.id,
- },
- };
-}
diff --git a/apps/web/src/features/calendar/events/recurrence-description.test.ts b/apps/web/src/features/calendar/events/recurrence-description.test.ts
deleted file mode 100644
index 240cd55ddf..0000000000
--- a/apps/web/src/features/calendar/events/recurrence-description.test.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- formatRecurrenceDescription,
- parseRecurrenceLines,
-} from './recurrence-description';
-
-describe('parseRecurrenceLines', () => {
- it('parses useful rule fields and explicit recurrence dates', () => {
- expect(
- parseRecurrenceLines([
- 'RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=WE,MO;COUNT=6;UNTIL=20261231T235959Z',
- 'RDATE:20260801T090000Z,20260808T090000Z',
- 'RDATE:20260808T090000Z',
- 'EXDATE:20260815T090000Z',
- ])
- ).toEqual({
- hasRecurrenceRule: true,
- rule: {
- frequency: 'WEEKLY',
- interval: 2,
- byDay: [
- { weekday: 'WE', ordinal: undefined },
- { weekday: 'MO', ordinal: undefined },
- ],
- byMonthDay: [],
- byMonth: [],
- count: 6,
- until: '20261231T235959Z',
- },
- additionalDates: ['20260801T090000Z', '20260808T090000Z'],
- excludedDates: ['20260815T090000Z'],
- });
- });
-
- it('ignores invalid selectors and defaults invalid intervals to one', () => {
- expect(
- parseRecurrenceLines([
- 'rrule:FREQ=monthly;INTERVAL=0;BYDAY=0MO,XX,2TU;BYMONTHDAY=0,32,-1;BYMONTH=0,12,13',
- ]).rule
- ).toEqual({
- frequency: 'MONTHLY',
- interval: 1,
- byDay: [{ weekday: 'TU', ordinal: 2 }],
- byMonthDay: [-1],
- byMonth: [12],
- count: undefined,
- until: undefined,
- });
- });
-});
-
-describe('formatRecurrenceDescription', () => {
- it.each([
- {
- name: 'daily',
- lines: ['RRULE:FREQ=DAILY'],
- expected: 'Daily',
- },
- {
- name: 'multi-day interval',
- lines: ['RRULE:FREQ=DAILY;INTERVAL=3'],
- expected: 'Every 3 days',
- },
- {
- name: 'weekly',
- lines: ['RRULE:FREQ=WEEKLY'],
- expected: 'Weekly',
- },
- {
- name: 'weekly on selected days',
- lines: ['RRULE:FREQ=WEEKLY;BYDAY=FR,MO,WE'],
- expected: 'Weekly on Monday, Wednesday, and Friday',
- },
- {
- name: 'biweekly on selected days',
- lines: ['RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=TU,TH'],
- expected: 'Every 2 weeks on Tuesday and Thursday',
- },
- {
- name: 'workweek',
- lines: ['RRULE:FREQ=WEEKLY;BYDAY=FR,WE,MO,TH,TU'],
- expected: 'Every weekday',
- },
- {
- name: 'monthly on numbered days',
- lines: ['RRULE:FREQ=MONTHLY;BYMONTHDAY=1,15'],
- expected: 'Monthly on the 1st and 15th',
- },
- {
- name: 'monthly on the last day',
- lines: ['RRULE:FREQ=MONTHLY;BYMONTHDAY=-1'],
- expected: 'Monthly on the last day',
- },
- {
- name: 'monthly on an ordinal weekday',
- lines: ['RRULE:FREQ=MONTHLY;BYDAY=1MO'],
- expected: 'Monthly on the first Monday',
- },
- {
- name: 'monthly on every matching weekday',
- lines: ['RRULE:FREQ=MONTHLY;BYDAY=MO'],
- expected: 'Monthly on Monday',
- },
- {
- name: 'yearly on a date',
- lines: ['RRULE:FREQ=YEARLY;BYMONTH=1;BYMONTHDAY=1'],
- expected: 'Yearly on January 1',
- },
- {
- name: 'yearly in selected months',
- lines: ['RRULE:FREQ=YEARLY;BYMONTH=1,7'],
- expected: 'Yearly in January and July',
- },
- {
- name: 'yearly on an ordinal weekday in a month',
- lines: ['RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=-1TH'],
- expected: 'Yearly on the last Thursday in November',
- },
- {
- name: 'hourly interval',
- lines: ['RRULE:FREQ=HOURLY;INTERVAL=6'],
- expected: 'Every 6 hours',
- },
- {
- name: 'occurrence count',
- lines: ['RRULE:FREQ=DAILY;COUNT=3'],
- expected: 'Daily · 3 occurrences',
- },
- {
- name: 'single occurrence count',
- lines: ['RRULE:FREQ=DAILY;COUNT=1'],
- expected: 'Daily · 1 occurrence',
- },
- {
- name: 'end date',
- lines: ['RRULE:FREQ=WEEKLY;UNTIL=20260831T235959Z'],
- expected: 'Weekly · until August 31, 2026',
- },
- {
- name: 'additional and excluded dates',
- lines: [
- 'RRULE:FREQ=WEEKLY',
- 'RDATE:20260801,20260808',
- 'EXDATE:20260815,20260815',
- ],
- expected: 'Weekly · 2 additional dates · 1 exception',
- },
- {
- name: 'RDATE-only recurrence',
- lines: ['RDATE:20260801,20260808'],
- expected: 'Repeats on 2 additional dates',
- },
- {
- name: 'malformed rule',
- lines: ['RRULE:INTERVAL=2'],
- expected: 'Recurring event',
- },
- {
- name: 'unsupported frequency',
- lines: ['RRULE:FREQ=FORTNIGHTLY'],
- expected: 'Recurring event',
- },
- {
- name: 'invalid interval and month day values',
- lines: ['RRULE:FREQ=MONTHLY;INTERVAL=-2;BYMONTHDAY=0,35'],
- expected: 'Monthly',
- },
- ])('formats $name', ({ lines, expected }) => {
- expect(formatRecurrenceDescription(lines, { locale: 'en-US' })).toBe(
- expected
- );
- });
-
- it('returns undefined when the lines do not declare recurrence', () => {
- expect(formatRecurrenceDescription([])).toBeUndefined();
- expect(formatRecurrenceDescription(['EXDATE:20260815'])).toBeUndefined();
- expect(formatRecurrenceDescription(['UNKNOWN:value'])).toBeUndefined();
- });
-});
diff --git a/apps/web/src/features/calendar/events/recurrence-editor.ts b/apps/web/src/features/calendar/events/recurrence-editor.ts
deleted file mode 100644
index 0a2457292c..0000000000
--- a/apps/web/src/features/calendar/events/recurrence-editor.ts
+++ /dev/null
@@ -1,263 +0,0 @@
-import { format } from 'date-fns';
-import { parseRecurrenceLines } from './recurrence-description';
-
-/** Weekday codes in RFC 5545 order for a Sunday-first chip row. */
-export const WEEKDAY_CODES = [
- 'SU',
- 'MO',
- 'TU',
- 'WE',
- 'TH',
- 'FR',
- 'SA',
-] as const;
-
-export type WeekdayCode = (typeof WEEKDAY_CODES)[number];
-
-const WORKWEEK: readonly WeekdayCode[] = ['MO', 'TU', 'WE', 'TH', 'FR'];
-
-export type RecurrenceFrequency = 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'YEARLY';
-
-/** How a recurrence ends. */
-export type RecurrenceEnds =
- | { kind: 'never' }
- | { kind: 'on'; date: string }
- | { kind: 'after'; count: number };
-
-/** The recurrence shapes the editor can express and round-trip. */
-export interface RecurrenceConfig {
- frequency: RecurrenceFrequency;
- /** Every N frequency units; 1 is omitted from the rule. */
- interval: number;
- /** Weekly-only weekday selectors. */
- byDay: WeekdayCode[];
- /** Monthly-only positional weekday, e.g. first Friday = `{ 1, FR }`. */
- monthlyByDay?: { ordinal: number; weekday: WeekdayCode };
- ends: RecurrenceEnds;
-}
-
-const NEVER: RecurrenceEnds = { kind: 'never' };
-
-/**
- * RFC 5545 `UNTIL` closing an inclusive local end date, Google-style:
- * all-day rules carry the plain date, timed rules the local end-of-day
- * instant rendered in UTC.
- */
-function untilValue(date: string, allDay: boolean) {
- if (allDay) return date.replaceAll('-', '');
- const endOfDay = new Date(`${date}T23:59:59`);
- return `${endOfDay.toISOString().slice(0, 19).replaceAll(/[-:]/g, '')}Z`;
-}
-
-/** The local calendar date a stored `UNTIL` value ends on (inclusive). */
-function untilDate(value: string): string | undefined {
- const match = value.match(
- /^(\d{4})-?(\d{2})-?(\d{2})(?:T(\d{2}):?(\d{2}):?(\d{2})Z)?$/
- );
- if (!match) return undefined;
- if (match[4] === undefined) return `${match[1]}-${match[2]}-${match[3]}`;
- const instant = new Date(
- Date.UTC(
- Number(match[1]),
- Number(match[2]) - 1,
- Number(match[3]),
- Number(match[4]),
- Number(match[5]),
- Number(match[6])
- )
- );
- return format(instant, 'yyyy-MM-dd');
-}
-
-/** Serialize a config into a single-`RRULE` recurrence property list. */
-export function buildRecurrenceLines(
- config: RecurrenceConfig,
- allDay: boolean
-): string[] {
- const parts = [`FREQ=${config.frequency}`];
- if (config.interval > 1) {
- parts.push(`INTERVAL=${config.interval}`);
- }
- if (config.frequency === 'WEEKLY' && config.byDay.length > 0) {
- const ordered = WEEKDAY_CODES.filter((code) => config.byDay.includes(code));
- parts.push(`BYDAY=${ordered.join(',')}`);
- }
- if (config.frequency === 'MONTHLY' && config.monthlyByDay) {
- parts.push(
- `BYDAY=${config.monthlyByDay.ordinal}${config.monthlyByDay.weekday}`
- );
- }
- if (config.ends.kind === 'on') {
- parts.push(`UNTIL=${untilValue(config.ends.date, allDay)}`);
- } else if (config.ends.kind === 'after') {
- parts.push(`COUNT=${config.ends.count}`);
- }
- return [`RRULE:${parts.join(';')}`];
-}
-
-/**
- * Parse recurrence properties into an editable config. Returns `undefined`
- * for rules the editor cannot round-trip (extra dates, exclusions, or
- * selectors beyond its vocabulary), which the UI keeps untouched instead.
- */
-export function parseRecurrenceConfig(
- lines: string[]
-): RecurrenceConfig | undefined {
- if (lines.length === 0) return undefined;
- const parsed = parseRecurrenceLines(lines);
- const rule = parsed.rule;
- if (
- !rule ||
- parsed.additionalDates.length > 0 ||
- parsed.excludedDates.length > 0 ||
- lines.length > 1
- ) {
- return undefined;
- }
- if (
- rule.frequency !== 'DAILY' &&
- rule.frequency !== 'WEEKLY' &&
- rule.frequency !== 'MONTHLY' &&
- rule.frequency !== 'YEARLY'
- ) {
- return undefined;
- }
- if (rule.byMonthDay.length > 0 || rule.byMonth.length > 0) {
- return undefined;
- }
- if (rule.count !== undefined && rule.until !== undefined) {
- return undefined;
- }
-
- let byDay: WeekdayCode[] = [];
- let monthlyByDay: RecurrenceConfig['monthlyByDay'];
- if (rule.byDay.length > 0) {
- if (rule.frequency === 'WEEKLY') {
- if (rule.byDay.some((day) => day.ordinal !== undefined)) {
- return undefined;
- }
- byDay = rule.byDay.map((day) => day.weekday);
- } else if (rule.frequency === 'MONTHLY' && rule.byDay.length === 1) {
- const [day] = rule.byDay;
- if (day?.ordinal === undefined) return undefined;
- monthlyByDay = { ordinal: day.ordinal, weekday: day.weekday };
- } else {
- return undefined;
- }
- }
-
- let ends: RecurrenceEnds = NEVER;
- if (rule.count !== undefined) {
- ends = { kind: 'after', count: rule.count };
- } else if (rule.until !== undefined) {
- const date = untilDate(rule.until);
- if (date === undefined) return undefined;
- ends = { kind: 'on', date };
- }
-
- return {
- frequency: rule.frequency,
- interval: rule.interval,
- byDay,
- monthlyByDay,
- ends,
- };
-}
-
-/** The positional weekday Google's monthly preset uses: 1st–4th, else last. */
-export function monthlyOrdinalFor(start: Date): {
- ordinal: number;
- weekday: WeekdayCode;
-} {
- const nth = Math.ceil(start.getDate() / 7);
- return {
- ordinal: nth === 5 ? -1 : nth,
- weekday: WEEKDAY_CODES[start.getDay()] as WeekdayCode,
- };
-}
-
-/** One entry in the recurrence preset dropdown. */
-export interface RecurrencePreset {
- id: string;
- label: string;
- config: RecurrenceConfig;
-}
-
-const ORDINAL_LABELS: Record<number, string> = {
- 1: 'first',
- 2: 'second',
- 3: 'third',
- 4: 'fourth',
- [-1]: 'last',
-};
-
-/** Google Calendar's preset list, phrased from the event's start date. */
-export function recurrencePresetsFor(start: Date): RecurrencePreset[] {
- const weekday = WEEKDAY_CODES[start.getDay()] as WeekdayCode;
- const weekdayName = format(start, 'EEEE');
- const monthly = monthlyOrdinalFor(start);
- return [
- {
- id: 'daily',
- label: 'Daily',
- config: { frequency: 'DAILY', interval: 1, byDay: [], ends: NEVER },
- },
- {
- id: 'weekly',
- label: `Weekly on ${weekdayName}`,
- config: {
- frequency: 'WEEKLY',
- interval: 1,
- byDay: [weekday],
- ends: NEVER,
- },
- },
- {
- id: 'monthly',
- label: `Monthly on the ${ORDINAL_LABELS[monthly.ordinal]} ${weekdayName}`,
- config: {
- frequency: 'MONTHLY',
- interval: 1,
- byDay: [],
- monthlyByDay: monthly,
- ends: NEVER,
- },
- },
- {
- id: 'annually',
- label: `Annually on ${format(start, 'MMMM d')}`,
- config: { frequency: 'YEARLY', interval: 1, byDay: [], ends: NEVER },
- },
- {
- id: 'weekdays',
- label: 'Every weekday (Monday to Friday)',
- config: {
- frequency: 'WEEKLY',
- interval: 1,
- byDay: [...WORKWEEK],
- ends: NEVER,
- },
- },
- ];
-}
-
-/** Whether two configs produce the same rule. */
-export function recurrenceConfigsEqual(
- first: RecurrenceConfig,
- second: RecurrenceConfig
-): boolean {
- return (
- buildRecurrenceLines(first, false).join('\n') ===
- buildRecurrenceLines(second, false).join('\n')
- );
-}
-
-/** A sensible starting point for the custom editor. */
-export function defaultCustomConfig(start: Date): RecurrenceConfig {
- return {
- frequency: 'WEEKLY',
- interval: 1,
- byDay: [WEEKDAY_CODES[start.getDay()] as WeekdayCode],
- ends: NEVER,
- };
-}
diff --git a/apps/web/src/features/calendar/events/types.ts b/apps/web/src/features/calendar/events/types.ts
deleted file mode 100644
index e4e13357c0..0000000000
--- a/apps/web/src/features/calendar/events/types.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import type { CalendarAttendee } from '@service-storage/generated/schemas/calendarAttendee';
-import type { EventReminders } from '@service-storage/generated/schemas/eventReminders';
-
-/** Supported FullCalendar period views. */
-export type CalendarPeriodView =
- | 'dayGridMonth'
- | 'timeGridWeek'
- | 'timeGridDay';
-
-/** The conferencing system backing an event's join URL. */
-export type ConferenceProvider = 'google_meet' | 'other';
-
-/** Supported first day of the calendar week. */
-export type CalendarWeekStart = 0 | 1;
-
-/** Supported calendar time display formats. */
-export type CalendarTimeFormat = '12-hour' | '24-hour';
-
-/** A calendar source used to group and style events. */
-export interface CalendarSource {
- /** Stable source identifier. */
- id: string;
- /** Human-readable source name. */
- name: string;
- /** Semantic CSS color used for events from this source. */
- color: string;
-}
-
-/** Calendar occurrence data, independent from FullCalendar. */
-export interface CalendarEvent {
- /** Stable identifier for this rendered occurrence. */
- id: string;
- /** Stable canonical calendar event identifier. */
- eventId: string;
- /** Stable key for this occurrence within its event. */
- occurrenceKey: string;
- /** Provider recurrence identifier, when applicable. */
- recurrenceId?: string;
- /** Whether this materialized occurrence was cancelled. */
- isCancelled: boolean;
- /** Whether the canonical event source is read-only. */
- isReadOnly: boolean;
- /** Direct conference join URL, when available. */
- conferenceUrl?: string;
- /**
- * Which conferencing system backs `conferenceUrl`. Only `google_meet` is
- * one Macro can attach and detach; anything else is shown for joining but
- * never rewritten.
- */
- conferenceProvider?: ConferenceProvider;
- /** Event organizer display name. */
- organizerName?: string;
- /** Event organizer email address. */
- organizerEmail?: string;
- /** Attendees and their RSVP metadata. */
- attendees: CalendarAttendee[];
- /** Per-user reminder configuration; absent means the calendar default. */
- reminders?: EventReminders;
- /** Canonical calendar entity id, for resolving default reminders. */
- calendarId?: string;
- /** Raw recurrence rules attached to the canonical event. */
- recurrenceLines: string[];
- /** Original IANA timezone for a timed occurrence. */
- timeZone?: string;
- /** Event title. */
- title: string;
- /** ISO timestamp or local date string for all-day events. */
- start: string;
- /** Exclusive ISO timestamp or local date string. */
- end: string;
- /** Whether the canonical occurrence is all-day rather than timed. */
- allDay: boolean;
- /** Calendar source that owns the event. */
- calendar: CalendarSource;
- /** Optional event location. */
- location?: string;
- /** Optional event description. */
- description?: string;
-}
diff --git a/apps/web/src/features/calendar/hooks/use-calendar-connected-inboxes.ts b/apps/web/src/features/calendar/hooks/use-calendar-connected-inboxes.ts
new file mode 100644
index 0000000000..f3d4eef9ee
--- /dev/null
+++ b/apps/web/src/features/calendar/hooks/use-calendar-connected-inboxes.ts
@@ -0,0 +1,25 @@
+import { useUserId } from '@core/context/user';
+import { useEmailLinksQuery } from '@queries/email/link';
+import type { Link as EmailLink } from '@service-email/generated/schemas';
+import { createMemo } from 'solid-js';
+
+/**
+ * The viewer's own inboxes whose calendar Macro can still remove, in the order
+ * the links list returns them. Delegated inboxes are excluded: the viewer can
+ * read the owner's calendar but must not be able to delete the owner's data.
+ *
+ * An inbox needing reauth still counts, and so does one whose grant no longer
+ * satisfies today's capability check — in both cases its events are still in
+ * Macro, and turning calendar off is the way to remove them.
+ */
+export function useCalendarConnectedInboxes() {
+ const linksQuery = useEmailLinksQuery();
+ const userId = useUserId();
+ return createMemo<EmailLink[]>(() =>
+ (linksQuery.data?.links ?? []).filter(
+ (link) =>
+ link.macro_id === userId() &&
+ (!link.needs_calendar_permission || link.has_calendar_data)
+ )
+ );
+}
diff --git a/apps/web/src/features/calendar/use-calendar-hotkeys.ts b/apps/web/src/features/calendar/hooks/use-calendar-hotkeys.ts
similarity index 97%
rename from apps/web/src/features/calendar/use-calendar-hotkeys.ts
rename to apps/web/src/features/calendar/hooks/use-calendar-hotkeys.ts
index d9aebb8ac3..59d72aa4be 100644
--- a/apps/web/src/features/calendar/use-calendar-hotkeys.ts
+++ b/apps/web/src/features/calendar/hooks/use-calendar-hotkeys.ts
@@ -1,7 +1,7 @@
import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { onCleanup } from 'solid-js';
-import type { CalendarPeriodView } from './events/types';
+import type { CalendarPeriodView } from '../types';
interface CalendarHotkeyHandlers {
scopeId: string;
diff --git a/apps/web/src/features/calendar/hooks/use-calendar-occurrence-data.ts b/apps/web/src/features/calendar/hooks/use-calendar-occurrence-data.ts
new file mode 100644
index 0000000000..33ca37b8c2
--- /dev/null
+++ b/apps/web/src/features/calendar/hooks/use-calendar-occurrence-data.ts
@@ -0,0 +1,88 @@
+import { useUserId } from '@core/context/user';
+import {
+ type CalendarOccurrenceQueryRange,
+ type CalendarOccurrencesQueryOptions,
+ useCalendarOccurrencesQuery,
+} from '@queries/calendar/occurrences';
+import { CalendarSyncStatus } from '@service-storage/generated/schemas/calendarSyncStatus';
+import { type Accessor, createMemo } from 'solid-js';
+import {
+ type CalendarEvent,
+ type CalendarSource,
+ mapCalendarOccurrence,
+} from '../types';
+import { isCalendarRangeSupported } from '../utils/calendar-supported-range';
+
+export interface CalendarOccurrenceData {
+ range: Accessor<CalendarOccurrenceQueryRange | undefined>;
+ occurrencesQuery: ReturnType<typeof useCalendarOccurrencesQuery>;
+ events: Accessor<CalendarEvent[]>;
+ visibleEvents: Accessor<CalendarEvent[]>;
+ eventsById: Accessor<Map<string, CalendarEvent>>;
+ isLoading: Accessor<boolean>;
+ isSyncing: Accessor<boolean>;
+}
+
+export interface CalendarOccurrenceDataOptions {
+ range: Accessor<CalendarOccurrenceQueryRange | undefined>;
+ sourceById?: Accessor<ReadonlyMap<string, CalendarSource>>;
+ isSourceVisible?: (sourceId: string) => boolean;
+ queryOptions?: Accessor<CalendarOccurrencesQueryOptions>;
+}
+
+/** Query-backed occurrence data shared by calendar rendering surfaces. */
+export function useCalendarOccurrenceData(
+ options: CalendarOccurrenceDataOptions
+): CalendarOccurrenceData {
+ const userId = useUserId();
+ const isRangeSupported = createMemo(() => {
+ const range = options.range();
+ return range !== undefined && isCalendarRangeSupported(range);
+ });
+ const occurrencesQuery = useCalendarOccurrencesQuery(
+ () => ({ userId: userId(), range: options.range() }),
+ () => {
+ const queryOptions = options.queryOptions?.();
+ return {
+ ...queryOptions,
+ enabled: isRangeSupported() && queryOptions?.enabled !== false,
+ };
+ }
+ );
+ const events = createMemo(() => {
+ if (!isRangeSupported()) return [];
+ const sourceById = options.sourceById?.();
+ return (occurrencesQuery.data?.items ?? []).map((item) =>
+ mapCalendarOccurrence(
+ item,
+ item.event.calendarId != null
+ ? sourceById?.get(item.event.calendarId)
+ : undefined
+ )
+ );
+ });
+ const visibleEvents = createMemo(() =>
+ events().filter(
+ (event) => options.isSourceVisible?.(event.calendar.id) !== false
+ )
+ );
+ const eventsById = createMemo(
+ () => new Map(events().map((event) => [event.id, event]))
+ );
+ const isLoading = () =>
+ options.range() === undefined ||
+ (isRangeSupported() &&
+ (occurrencesQuery.isPending || occurrencesQuery.isPlaceholderData));
+ const isSyncing = () =>
+ occurrencesQuery.data?.syncStatus === CalendarSyncStatus.syncing;
+
+ return {
+ range: options.range,
+ occurrencesQuery,
+ events,
+ visibleEvents,
+ eventsById,
+ isLoading,
+ isSyncing,
+ };
+}
diff --git a/apps/web/src/features/calendar/hooks/use-calendar-sources.ts b/apps/web/src/features/calendar/hooks/use-calendar-sources.ts
new file mode 100644
index 0000000000..d136a72f65
--- /dev/null
+++ b/apps/web/src/features/calendar/hooks/use-calendar-sources.ts
@@ -0,0 +1,31 @@
+import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
+import { createMemo } from 'solid-js';
+import type { CalendarSource } from '../types';
+import { DEFAULT_CALENDAR_SOURCE } from '../types';
+import {
+ calendarDisplayLabel,
+ spansMultipleInboxes,
+} from '../utils/calendar-label';
+
+/** Query-backed calendar sources with presentation labels and colors. */
+export function useCalendarSources() {
+ const calendarsQuery = useVisibleCalendarsQuery();
+ const sources = createMemo<CalendarSource[]>(() => {
+ const calendars = calendarsQuery.data;
+ if (!calendars || calendars.length === 0) {
+ return [DEFAULT_CALENDAR_SOURCE];
+ }
+
+ const spansInboxes = spansMultipleInboxes(calendars);
+ return calendars.map((calendar) => ({
+ id: calendar.id,
+ name: calendarDisplayLabel(calendar, spansInboxes),
+ color: calendar.color ?? DEFAULT_CALENDAR_SOURCE.color,
+ }));
+ });
+ const sourceById = createMemo(
+ () => new Map(sources().map((source) => [source.id, source]))
+ );
+
+ return { calendarsQuery, sourceById, sources };
+}
diff --git a/apps/web/src/features/calendar/useCalendarTimeGridHoverIndicator.ts b/apps/web/src/features/calendar/hooks/use-calendar-time-grid-hover-indicator.ts
similarity index 100%
rename from apps/web/src/features/calendar/useCalendarTimeGridHoverIndicator.ts
rename to apps/web/src/features/calendar/hooks/use-calendar-time-grid-hover-indicator.ts
diff --git a/apps/web/src/features/calendar/use-calendar-ui-flag.ts b/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts
similarity index 100%
rename from apps/web/src/features/calendar/use-calendar-ui-flag.ts
rename to apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts
diff --git a/apps/web/src/features/calendar/events/useEventEditor.ts b/apps/web/src/features/calendar/hooks/use-event-editor.ts
similarity index 94%
rename from apps/web/src/features/calendar/events/useEventEditor.ts
rename to apps/web/src/features/calendar/hooks/use-event-editor.ts
index 011d722629..b4fec8a675 100644
--- a/apps/web/src/features/calendar/events/useEventEditor.ts
+++ b/apps/web/src/features/calendar/hooks/use-event-editor.ts
@@ -6,14 +6,17 @@ import {
useUpdateCalendarEventMutation,
} from '@queries/calendar/mutations';
import { type Accessor, createMemo } from 'solid-js';
-import { calendarDisplayLabel, spansMultipleInboxes } from '../calendar-label';
-import { DEFAULT_CALENDAR_SOURCE } from './calendar-occurrence-mapper';
import {
calendarEventToEditorInitialValues,
type EventEditorDisabledFields,
type EventEditorSubmitValues,
-} from './EventEditorForm';
-import type { CalendarEvent } from './types';
+} from '../components/composer/event-form-model';
+import type { CalendarEvent } from '../types';
+import { DEFAULT_CALENDAR_SOURCE } from '../types';
+import {
+ calendarDisplayLabel,
+ spansMultipleInboxes,
+} from '../utils/calendar-label';
const EDIT_DISABLED_FIELDS = {
calendar: true,
diff --git a/apps/web/src/features/calendar/types.ts b/apps/web/src/features/calendar/types.ts
new file mode 100644
index 0000000000..b7341498d8
--- /dev/null
+++ b/apps/web/src/features/calendar/types.ts
@@ -0,0 +1,157 @@
+import type { EventInput } from '@fullcalendar/core';
+import type { CalendarAttendee } from '@service-storage/generated/schemas/calendarAttendee';
+import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';
+import type { EventReminders } from '@service-storage/generated/schemas/eventReminders';
+import { multiDayTimedDisplayRange } from './utils/calendar-date';
+import { canEditCalendarEventTime } from './utils/event-interaction';
+
+/** Supported FullCalendar period views. */
+export type CalendarPeriodView =
+ | 'dayGridMonth'
+ | 'timeGridWeek'
+ | 'timeGridDay';
+
+/** The conferencing system backing an event's join URL. */
+type ConferenceProvider = 'google_meet' | 'other';
+
+/** Supported first day of the calendar week. */
+export type CalendarWeekStart = 0 | 1;
+
+/** Supported calendar time display formats. */
+export type CalendarTimeFormat = '12-hour' | '24-hour';
+
+/** A calendar source used to group and style events. */
+export interface CalendarSource {
+ /** Stable source identifier. */
+ id: string;
+ /** Human-readable source name. */
+ name: string;
+ /** Semantic CSS color used for events from this source. */
+ color: string;
+}
+
+/** Calendar occurrence data, independent from FullCalendar. */
+export interface CalendarEvent {
+ /** Stable identifier for this rendered occurrence. */
+ id: string;
+ /** Stable canonical calendar event identifier. */
+ eventId: string;
+ /** Stable key for this occurrence within its event. */
+ occurrenceKey: string;
+ /** Provider recurrence identifier, when applicable. */
+ recurrenceId?: string;
+ /** Whether this materialized occurrence was cancelled. */
+ isCancelled: boolean;
+ /** Whether the canonical event source is read-only. */
+ isReadOnly: boolean;
+ /** Direct conference join URL, when available. */
+ conferenceUrl?: string;
+ /**
+ * Which conferencing system backs `conferenceUrl`. Only `google_meet` is
+ * one Macro can attach and detach; anything else is shown for joining but
+ * never rewritten.
+ */
+ conferenceProvider?: ConferenceProvider;
+ /** Event organizer display name. */
+ organizerName?: string;
+ /** Event organizer email address. */
+ organizerEmail?: string;
+ /** Attendees and their RSVP metadata. */
+ attendees: CalendarAttendee[];
+ /** Per-user reminder configuration; absent means the calendar default. */
+ reminders?: EventReminders;
+ /** Canonical calendar entity id, for resolving default reminders. */
+ calendarId?: string;
+ /** Raw recurrence rules attached to the canonical event. */
+ recurrenceLines: string[];
+ /** Original IANA timezone for a timed occurrence. */
+ timeZone?: string;
+ /** Event title. */
+ title: string;
+ /** ISO timestamp or local date string for all-day events. */
+ start: string;
+ /** Exclusive ISO timestamp or local date string. */
+ end: string;
+ /** Whether the canonical occurrence is all-day rather than timed. */
+ allDay: boolean;
+ /** Calendar source that owns the event. */
+ calendar: CalendarSource;
+ /** Optional event location. */
+ location?: string;
+ /** Optional event description. */
+ description?: string;
+}
+
+/** Shared presentation source until calendar/account metadata is exposed. */
+export const DEFAULT_CALENDAR_SOURCE: CalendarSource = {
+ id: 'calendar',
+ name: 'Calendar',
+ color: 'var(--color-accent)',
+};
+
+/** Maps one backend occurrence projection into the calendar event model. */
+export function mapCalendarOccurrence(
+ item: CalendarOccurrenceItem,
+ source: CalendarSource = DEFAULT_CALENDAR_SOURCE
+): CalendarEvent {
+ const { event, occurrence } = item;
+ const time = occurrence.time;
+ const range =
+ time.kind === 'timed'
+ ? { allDay: false, start: time.startsAt, end: time.endsAt }
+ : { allDay: true, start: time.startDate, end: time.endDate };
+
+ return {
+ ...range,
+ id: JSON.stringify([event.id, occurrence.occurrenceKey]),
+ eventId: event.id,
+ occurrenceKey: occurrence.occurrenceKey,
+ recurrenceId: occurrence.recurrenceId ?? undefined,
+ recurrenceLines: event.recurrenceLines ?? [],
+ isCancelled: occurrence.isCancelled,
+ isReadOnly: event.isReadOnly,
+ conferenceUrl: event.conferenceUrl ?? undefined,
+ conferenceProvider:
+ (event.conferenceProvider as ConferenceProvider | null | undefined) ??
+ undefined,
+ organizerName: event.organizerName ?? undefined,
+ organizerEmail: event.organizerEmail ?? undefined,
+ attendees: event.attendees ?? [],
+ reminders: event.reminders ?? undefined,
+ calendarId: event.calendarId ?? undefined,
+ timeZone: time.kind === 'timed' ? (time.timeZone ?? undefined) : undefined,
+ title: event.title,
+ calendar: source,
+ location: event.location ?? undefined,
+ description: event.description ?? undefined,
+ };
+}
+
+/** Maps calendar event data into FullCalendar's rendering contract. */
+export function mapCalendarEventToFullCalendar(
+ event: CalendarEvent
+): EventInput {
+ const timeEditable = canEditCalendarEventTime(event);
+ const allDayRange = event.allDay
+ ? undefined
+ : multiDayTimedDisplayRange(new Date(event.start), new Date(event.end));
+ const isRenderedAllDay = event.allDay || allDayRange !== undefined;
+ // FullCalendar reports interactions from the all-day row as true all-day
+ // ranges. Keep projected timed events fixed so their timestamps are not
+ // accidentally replaced with date-only API values.
+ const interactionEditable = timeEditable && allDayRange === undefined;
+
+ return {
+ id: event.id,
+ title: event.title,
+ start: allDayRange?.start ?? event.start,
+ end: allDayRange?.end ?? event.end,
+ allDay: isRenderedAllDay,
+ display: 'block',
+ startEditable: interactionEditable,
+ durationEditable: interactionEditable,
+ extendedProps: {
+ calendarEventId: event.id,
+ },
+ };
+}
diff --git a/apps/web/src/features/calendar/use-calendar-ui-flag.test.ts b/apps/web/src/features/calendar/use-calendar-ui-flag.test.ts
deleted file mode 100644
index c9626f9535..0000000000
--- a/apps/web/src/features/calendar/use-calendar-ui-flag.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-
-const mocks = vi.hoisted(() => ({
- mobile: false,
- flags: {} as Record<string, boolean>,
-}));
-
-vi.mock('@app/lib/analytics/posthog', () => ({
- useFeatureFlag:
- (key: string, opts?: { enabledOverride?: boolean }) => () => ({
- enabled: opts?.enabledOverride ?? mocks.flags[key] ?? false,
- }),
-}));
-
-vi.mock('@core/mobile/isMobile', () => ({
- isMobile: () => mocks.mobile,
-}));
-
-vi.mock('@core/constant/featureFlags', () => ({
- ENABLE_CALENDAR_UI_FLAG: 'enable-calendar-ui',
- ENABLE_CALENDAR_UI_OVERRIDE: undefined,
- ENABLE_CALENDAR_PROMPT_MOBILE_FLAG: 'enable-calendar-prompt-mobile',
- ENABLE_CALENDAR_PROMPT_MOBILE_OVERRIDE: undefined,
- ENABLE_CALENDAR_PROMPT_WEB_FLAG: 'enable-calendar-prompt-web',
- ENABLE_CALENDAR_PROMPT_WEB_OVERRIDE: undefined,
-}));
-
-import { useCalendarPromptAllowed } from './use-calendar-ui-flag';
-
-describe('useCalendarPromptAllowed', () => {
- function allowed(state: {
- mobile: boolean;
- mobileFlag?: boolean;
- webFlag?: boolean;
- }): boolean {
- mocks.mobile = state.mobile;
- mocks.flags = {
- 'enable-calendar-prompt-mobile': !!state.mobileFlag,
- 'enable-calendar-prompt-web': !!state.webFlag,
- };
- return useCalendarPromptAllowed()();
- }
-
- it('suppresses the prompt on desktop while the web flag is off', () => {
- expect(allowed({ mobile: false })).toBe(false);
- expect(allowed({ mobile: false, mobileFlag: true })).toBe(false);
- });
-
- it('allows the prompt on desktop once the web flag is turned on', () => {
- expect(allowed({ mobile: false, webFlag: true })).toBe(true);
- });
-
- it('suppresses the prompt on mobile while the flag is off', () => {
- expect(allowed({ mobile: true })).toBe(false);
- expect(allowed({ mobile: true, webFlag: true })).toBe(false);
- });
-
- it('allows the prompt on mobile once the flag is turned on', () => {
- expect(allowed({ mobile: true, mobileFlag: true })).toBe(true);
- });
-});
diff --git a/apps/web/src/features/calendar/events/multi-day-rendering.ts b/apps/web/src/features/calendar/utils/calendar-date.ts
similarity index 64%
rename from apps/web/src/features/calendar/events/multi-day-rendering.ts
rename to apps/web/src/features/calendar/utils/calendar-date.ts
index 9d5f039850..18d011070b 100644
--- a/apps/web/src/features/calendar/events/multi-day-rendering.ts
+++ b/apps/web/src/features/calendar/utils/calendar-date.ts
@@ -4,7 +4,8 @@ export interface MultiDayDisplayRange {
end: string;
}
-function formatLocalDate(date: Date) {
+/** Formats a Date as a local calendar date without UTC conversion. */
+export function formatLocalDate(date: Date) {
return [
date.getFullYear(),
String(date.getMonth() + 1).padStart(2, '0'),
@@ -12,7 +13,25 @@ function formatLocalDate(date: Date) {
].join('-');
}
-function isSameLocalDate(first: Date, second: Date) {
+/** Parses a canonical local calendar date without applying UTC conversion. */
+export function parseLocalDate(value: string): Date | undefined {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
+ if (!match) return undefined;
+
+ const year = Number(match[1]);
+ const month = Number(match[2]) - 1;
+ const day = Number(match[3]);
+ const date = new Date(year, month, day);
+
+ return date.getFullYear() === year &&
+ date.getMonth() === month &&
+ date.getDate() === day
+ ? date
+ : undefined;
+}
+
+/** Whether two dates fall on the same local calendar day. */
+export function isSameLocalDate(first: Date, second: Date) {
return (
first.getFullYear() === second.getFullYear() &&
first.getMonth() === second.getMonth() &&
diff --git a/apps/web/src/features/calendar/calendar-label.ts b/apps/web/src/features/calendar/utils/calendar-label.ts
similarity index 95%
rename from apps/web/src/features/calendar/calendar-label.ts
rename to apps/web/src/features/calendar/utils/calendar-label.ts
index 7759170fa3..b57197919d 100644
--- a/apps/web/src/features/calendar/calendar-label.ts
+++ b/apps/web/src/features/calendar/utils/calendar-label.ts
@@ -1,5 +1,5 @@
import type { VisibleCalendar } from '@queries/calendar/calendars';
-import type { CalendarPeriodView } from './events/types';
+import type { CalendarPeriodView } from '../types';
const CALENDAR_PERIOD_LABELS = {
dayGridMonth: 'Month',
diff --git a/apps/web/src/features/calendar/calendar-supported-range.ts b/apps/web/src/features/calendar/utils/calendar-supported-range.ts
similarity index 100%
rename from apps/web/src/features/calendar/calendar-supported-range.ts
rename to apps/web/src/features/calendar/utils/calendar-supported-range.ts
diff --git a/apps/web/src/features/calendar/events/event-interaction.ts b/apps/web/src/features/calendar/utils/event-interaction.ts
similarity index 88%
rename from apps/web/src/features/calendar/events/event-interaction.ts
rename to apps/web/src/features/calendar/utils/event-interaction.ts
index 1e88b3e5c1..1a3a681aca 100644
--- a/apps/web/src/features/calendar/events/event-interaction.ts
+++ b/apps/web/src/features/calendar/utils/event-interaction.ts
@@ -1,6 +1,7 @@
import type { EventApi } from '@fullcalendar/core';
import type { EventTime } from '@service-email/generated/schemas/eventTime';
-import type { CalendarEvent } from './types';
+import type { CalendarEvent } from '../types';
+import { formatLocalDate } from './calendar-date';
interface FullCalendarEventRange {
allDay: boolean;
@@ -8,14 +9,6 @@ interface FullCalendarEventRange {
start: Date | null;
}
-function formatLocalDate(date: Date) {
- return [
- date.getFullYear(),
- String(date.getMonth() + 1).padStart(2, '0'),
- String(date.getDate()).padStart(2, '0'),
- ].join('-');
-}
-
/** Resolves the occurrence id retained in FullCalendar's interaction copies. */
export function calendarEventRenderId(
event: Pick<EventApi, 'extendedProps' | 'id'>
diff --git a/apps/web/src/features/calendar/events/event-reminders.ts b/apps/web/src/features/calendar/utils/event-reminders.ts
similarity index 100%
rename from apps/web/src/features/calendar/events/event-reminders.ts
rename to apps/web/src/features/calendar/utils/event-reminders.ts
diff --git a/apps/web/src/features/calendar/events/multi-day-selection-rendering.ts b/apps/web/src/features/calendar/utils/fullcalendar-multi-day-selection.ts
similarity index 97%
rename from apps/web/src/features/calendar/events/multi-day-selection-rendering.ts
rename to apps/web/src/features/calendar/utils/fullcalendar-multi-day-selection.ts
index 40ff17ad36..d8e412d4be 100644
--- a/apps/web/src/features/calendar/events/multi-day-selection-rendering.ts
+++ b/apps/web/src/features/calendar/utils/fullcalendar-multi-day-selection.ts
@@ -8,7 +8,7 @@ import type {
ViewProps,
ViewPropsTransformer,
} from '@fullcalendar/core/internal';
-import { multiDayTimedDisplayRange } from './multi-day-rendering';
+import { multiDayTimedDisplayRange } from './calendar-date';
const PREVIEW_DEF_ID = '__calendar-multi-day-selection-preview-def__';
const PREVIEW_INSTANCE_ID = '__calendar-multi-day-selection-preview-instance__';
diff --git a/apps/web/src/features/calendar/events/recurrence-editor.test.ts b/apps/web/src/features/calendar/utils/recurrence.test.ts
similarity index 51%
rename from apps/web/src/features/calendar/events/recurrence-editor.test.ts
rename to apps/web/src/features/calendar/utils/recurrence.test.ts
index 6bd57b7e7f..038cf26026 100644
--- a/apps/web/src/features/calendar/events/recurrence-editor.test.ts
+++ b/apps/web/src/features/calendar/utils/recurrence.test.ts
@@ -3,12 +3,188 @@ import { describe, expect, it } from 'vitest';
import {
buildRecurrenceLines,
defaultCustomConfig,
+ formatRecurrenceDescription,
monthlyOrdinalFor,
parseRecurrenceConfig,
+ parseRecurrenceLines,
type RecurrenceConfig,
recurrenceConfigsEqual,
recurrencePresetsFor,
-} from './recurrence-editor';
+} from './recurrence';
+
+describe('parseRecurrenceLines', () => {
+ it('parses useful rule fields and explicit recurrence dates', () => {
+ expect(
+ parseRecurrenceLines([
+ 'RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=WE,MO;COUNT=6;UNTIL=20261231T235959Z',
+ 'RDATE:20260801T090000Z,20260808T090000Z',
+ 'RDATE:20260808T090000Z',
+ 'EXDATE:20260815T090000Z',
+ ])
+ ).toEqual({
+ hasRecurrenceRule: true,
+ rule: {
+ frequency: 'WEEKLY',
+ interval: 2,
+ byDay: [
+ { weekday: 'WE', ordinal: undefined },
+ { weekday: 'MO', ordinal: undefined },
+ ],
+ byMonthDay: [],
+ byMonth: [],
+ count: 6,
+ until: '20261231T235959Z',
+ },
+ additionalDates: ['20260801T090000Z', '20260808T090000Z'],
+ excludedDates: ['20260815T090000Z'],
+ });
+ });
+
+ it('ignores invalid selectors and defaults invalid intervals to one', () => {
+ expect(
+ parseRecurrenceLines([
+ 'rrule:FREQ=monthly;INTERVAL=0;BYDAY=0MO,XX,2TU;BYMONTHDAY=0,32,-1;BYMONTH=0,12,13',
+ ]).rule
+ ).toEqual({
+ frequency: 'MONTHLY',
+ interval: 1,
+ byDay: [{ weekday: 'TU', ordinal: 2 }],
+ byMonthDay: [-1],
+ byMonth: [12],
+ count: undefined,
+ until: undefined,
+ });
+ });
+});
+
+describe('formatRecurrenceDescription', () => {
+ it.each([
+ {
+ name: 'daily',
+ lines: ['RRULE:FREQ=DAILY'],
+ expected: 'Daily',
+ },
+ {
+ name: 'multi-day interval',
+ lines: ['RRULE:FREQ=DAILY;INTERVAL=3'],
+ expected: 'Every 3 days',
+ },
+ {
+ name: 'weekly',
+ lines: ['RRULE:FREQ=WEEKLY'],
+ expected: 'Weekly',
+ },
+ {
+ name: 'weekly on selected days',
+ lines: ['RRULE:FREQ=WEEKLY;BYDAY=FR,MO,WE'],
+ expected: 'Weekly on Monday, Wednesday, and Friday',
+ },
+ {
+ name: 'biweekly on selected days',
+ lines: ['RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=TU,TH'],
+ expected: 'Every 2 weeks on Tuesday and Thursday',
+ },
+ {
+ name: 'workweek',
+ lines: ['RRULE:FREQ=WEEKLY;BYDAY=FR,WE,MO,TH,TU'],
+ expected: 'Every weekday',
+ },
+ {
+ name: 'monthly on numbered days',
+ lines: ['RRULE:FREQ=MONTHLY;BYMONTHDAY=1,15'],
+ expected: 'Monthly on the 1st and 15th',
+ },
+ {
+ name: 'monthly on the last day',
+ lines: ['RRULE:FREQ=MONTHLY;BYMONTHDAY=-1'],
+ expected: 'Monthly on the last day',
+ },
+ {
+ name: 'monthly on an ordinal weekday',
+ lines: ['RRULE:FREQ=MONTHLY;BYDAY=1MO'],
+ expected: 'Monthly on the first Monday',
+ },
+ {
+ name: 'monthly on every matching weekday',
+ lines: ['RRULE:FREQ=MONTHLY;BYDAY=MO'],
+ expected: 'Monthly on Monday',
+ },
+ {
+ name: 'yearly on a date',
+ lines: ['RRULE:FREQ=YEARLY;BYMONTH=1;BYMONTHDAY=1'],
+ expected: 'Yearly on January 1',
+ },
+ {
+ name: 'yearly in selected months',
+ lines: ['RRULE:FREQ=YEARLY;BYMONTH=1,7'],
+ expected: 'Yearly in January and July',
+ },
+ {
+ name: 'yearly on an ordinal weekday in a month',
+ lines: ['RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=-1TH'],
+ expected: 'Yearly on the last Thursday in November',
+ },
+ {
+ name: 'hourly interval',
+ lines: ['RRULE:FREQ=HOURLY;INTERVAL=6'],
+ expected: 'Every 6 hours',
+ },
+ {
+ name: 'occurrence count',
+ lines: ['RRULE:FREQ=DAILY;COUNT=3'],
+ expected: 'Daily · 3 occurrences',
+ },
+ {
+ name: 'single occurrence count',
+ lines: ['RRULE:FREQ=DAILY;COUNT=1'],
+ expected: 'Daily · 1 occurrence',
+ },
+ {
+ name: 'end date',
+ lines: ['RRULE:FREQ=WEEKLY;UNTIL=20260831T235959Z'],
+ expected: 'Weekly · until August 31, 2026',
+ },
+ {
+ name: 'additional and excluded dates',
+ lines: [
+ 'RRULE:FREQ=WEEKLY',
+ 'RDATE:20260801,20260808',
+ 'EXDATE:20260815,20260815',
+ ],
+ expected: 'Weekly · 2 additional dates · 1 exception',
+ },
+ {
+ name: 'RDATE-only recurrence',
+ lines: ['RDATE:20260801,20260808'],
+ expected: 'Repeats on 2 additional dates',
+ },
+ {
+ name: 'malformed rule',
+ lines: ['RRULE:INTERVAL=2'],
+ expected: 'Recurring event',
+ },
+ {
+ name: 'unsupported frequency',
+ lines: ['RRULE:FREQ=FORTNIGHTLY'],
+ expected: 'Recurring event',
+ },
+ {
+ name: 'invalid interval and month day values',
+ lines: ['RRULE:FREQ=MONTHLY;INTERVAL=-2;BYMONTHDAY=0,35'],
+ expected: 'Monthly',
+ },
+ ])('formats $name', ({ lines, expected }) => {
+ expect(formatRecurrenceDescription(lines, { locale: 'en-US' })).toBe(
+ expected
+ );
+ });
+
+ it('returns undefined when the lines do not declare recurrence', () => {
+ expect(formatRecurrenceDescription([])).toBeUndefined();
+ expect(formatRecurrenceDescription(['EXDATE:20260815'])).toBeUndefined();
+ expect(formatRecurrenceDescription(['UNKNOWN:value'])).toBeUndefined();
+ });
+});
// Friday, August 7 2026 (local).
const friday = new Date(2026, 7, 7, 14, 0, 0);
diff --git a/apps/web/src/features/calendar/events/recurrence-description.ts b/apps/web/src/features/calendar/utils/recurrence.ts
similarity index 60%
rename from apps/web/src/features/calendar/events/recurrence-description.ts
rename to apps/web/src/features/calendar/utils/recurrence.ts
index 735d7be779..ab79a50fd5 100644
--- a/apps/web/src/features/calendar/events/recurrence-description.ts
+++ b/apps/web/src/features/calendar/utils/recurrence.ts
@@ -1,4 +1,5 @@
import { formatOrdinal, plural } from '@core/util/string';
+import { format } from 'date-fns';
const POSITIVE_INTEGER_REGEX = /^\d+$/;
const BYDAY_VALUE_REGEX = /^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/i;
@@ -26,21 +27,21 @@ const WEEKDAYS = {
const WORKWEEK_CODES = ['MO', 'TU', 'WE', 'TH', 'FR'] as const;
-type RecurrenceFrequency = (typeof RECURRENCE_FREQUENCIES)[number];
-type WeekdayCode = keyof typeof WEEKDAYS;
+type ParsedRecurrenceFrequency = (typeof RECURRENCE_FREQUENCIES)[number];
+type ParsedWeekdayCode = keyof typeof WEEKDAYS;
/** One weekday selector from an RFC 5545 `BYDAY` rule. */
-export interface RecurrenceWeekday {
+interface RecurrenceWeekday {
/** Weekday code such as `MO` or `FR`. */
- weekday: WeekdayCode;
+ weekday: ParsedWeekdayCode;
/** Positional selector such as `1` for first or `-1` for last. */
ordinal?: number;
}
/** The recurrence fields used by the calendar event details UI. */
-export interface ParsedRecurrenceRule {
+interface ParsedRecurrenceRule {
/** RFC 5545 recurrence frequency, when supported. */
- frequency?: RecurrenceFrequency;
+ frequency?: ParsedRecurrenceFrequency;
/** Frequency interval. Defaults to one. */
interval: number;
/** Weekday selectors. */
@@ -92,7 +93,7 @@ function parseByDay(value: string | undefined): RecurrenceWeekday[] {
const match = BYDAY_VALUE_REGEX.exec(part.trim());
if (!match) return [];
- const weekday = match[2]?.toUpperCase() as WeekdayCode;
+ const weekday = match[2]?.toUpperCase() as ParsedWeekdayCode;
const ordinal = match[1] === undefined ? undefined : Number(match[1]);
if (ordinal === 0 || (ordinal !== undefined && Math.abs(ordinal) > 53)) {
return [];
@@ -178,7 +179,10 @@ export function parseRecurrenceLines(lines: string[]): ParsedRecurrenceLines {
};
}
-function formatBaseFrequency(frequency: RecurrenceFrequency, interval: number) {
+function formatBaseFrequency(
+ frequency: ParsedRecurrenceFrequency,
+ interval: number
+) {
if (interval > 1) {
const unit = {
SECONDLY: 'second',
@@ -413,3 +417,264 @@ export function formatRecurrenceDescription(
return [description, ...suffixes].join(' · ');
}
+
+/** Weekday codes in RFC 5545 order for a Sunday-first chip row. */
+export const WEEKDAY_CODES = [
+ 'SU',
+ 'MO',
+ 'TU',
+ 'WE',
+ 'TH',
+ 'FR',
+ 'SA',
+] as const;
+
+export type WeekdayCode = (typeof WEEKDAY_CODES)[number];
+
+const WORKWEEK: readonly WeekdayCode[] = ['MO', 'TU', 'WE', 'TH', 'FR'];
+
+export type RecurrenceFrequency = 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'YEARLY';
+
+/** How a recurrence ends. */
+type RecurrenceEnds =
+ | { kind: 'never' }
+ | { kind: 'on'; date: string }
+ | { kind: 'after'; count: number };
+
+/** The recurrence shapes the editor can express and round-trip. */
+export interface RecurrenceConfig {
+ frequency: RecurrenceFrequency;
+ /** Every N frequency units; 1 is omitted from the rule. */
+ interval: number;
+ /** Weekly-only weekday selectors. */
+ byDay: WeekdayCode[];
+ /** Monthly-only positional weekday, e.g. first Friday = `{ 1, FR }`. */
+ monthlyByDay?: { ordinal: number; weekday: WeekdayCode };
+ ends: RecurrenceEnds;
+}
+
+const NEVER: RecurrenceEnds = { kind: 'never' };
+
+/**
+ * RFC 5545 `UNTIL` closing an inclusive local end date, Google-style:
+ * all-day rules carry the plain date, timed rules the local end-of-day
+ * instant rendered in UTC.
+ */
+function untilValue(date: string, allDay: boolean) {
+ if (allDay) return date.replaceAll('-', '');
+ const endOfDay = new Date(`${date}T23:59:59`);
+ return `${endOfDay.toISOString().slice(0, 19).replaceAll(/[-:]/g, '')}Z`;
+}
+
+/** The local calendar date a stored `UNTIL` value ends on (inclusive). */
+function untilDate(value: string): string | undefined {
+ const match = value.match(
+ /^(\d{4})-?(\d{2})-?(\d{2})(?:T(\d{2}):?(\d{2}):?(\d{2})Z)?$/
+ );
+ if (!match) return undefined;
+ if (match[4] === undefined) return `${match[1]}-${match[2]}-${match[3]}`;
+ const instant = new Date(
+ Date.UTC(
+ Number(match[1]),
+ Number(match[2]) - 1,
+ Number(match[3]),
+ Number(match[4]),
+ Number(match[5]),
+ Number(match[6])
+ )
+ );
+ return format(instant, 'yyyy-MM-dd');
+}
+
+/** Serialize a config into a single-`RRULE` recurrence property list. */
+export function buildRecurrenceLines(
+ config: RecurrenceConfig,
+ allDay: boolean
+): string[] {
+ const parts = [`FREQ=${config.frequency}`];
+ if (config.interval > 1) {
+ parts.push(`INTERVAL=${config.interval}`);
+ }
+ if (config.frequency === 'WEEKLY' && config.byDay.length > 0) {
+ const ordered = WEEKDAY_CODES.filter((code) => config.byDay.includes(code));
+ parts.push(`BYDAY=${ordered.join(',')}`);
+ }
+ if (config.frequency === 'MONTHLY' && config.monthlyByDay) {
+ parts.push(
+ `BYDAY=${config.monthlyByDay.ordinal}${config.monthlyByDay.weekday}`
+ );
+ }
+ if (config.ends.kind === 'on') {
+ parts.push(`UNTIL=${untilValue(config.ends.date, allDay)}`);
+ } else if (config.ends.kind === 'after') {
+ parts.push(`COUNT=${config.ends.count}`);
+ }
+ return [`RRULE:${parts.join(';')}`];
+}
+
+/**
+ * Parse recurrence properties into an editable config. Returns `undefined`
+ * for rules the editor cannot round-trip (extra dates, exclusions, or
+ * selectors beyond its vocabulary), which the UI keeps untouched instead.
+ */
+export function parseRecurrenceConfig(
+ lines: string[]
+): RecurrenceConfig | undefined {
+ if (lines.length === 0) return undefined;
+ const parsed = parseRecurrenceLines(lines);
+ const rule = parsed.rule;
+ if (
+ !rule ||
+ parsed.additionalDates.length > 0 ||
+ parsed.excludedDates.length > 0 ||
+ lines.length > 1
+ ) {
+ return undefined;
+ }
+ if (
+ rule.frequency !== 'DAILY' &&
+ rule.frequency !== 'WEEKLY' &&
+ rule.frequency !== 'MONTHLY' &&
+ rule.frequency !== 'YEARLY'
+ ) {
+ return undefined;
+ }
+ if (rule.byMonthDay.length > 0 || rule.byMonth.length > 0) {
+ return undefined;
+ }
+ if (rule.count !== undefined && rule.until !== undefined) {
+ return undefined;
+ }
+
+ let byDay: WeekdayCode[] = [];
+ let monthlyByDay: RecurrenceConfig['monthlyByDay'];
+ if (rule.byDay.length > 0) {
+ if (rule.frequency === 'WEEKLY') {
+ if (rule.byDay.some((day) => day.ordinal !== undefined)) {
+ return undefined;
+ }
+ byDay = rule.byDay.map((day) => day.weekday);
+ } else if (rule.frequency === 'MONTHLY' && rule.byDay.length === 1) {
+ const [day] = rule.byDay;
+ if (day?.ordinal === undefined) return undefined;
+ monthlyByDay = { ordinal: day.ordinal, weekday: day.weekday };
+ } else {
+ return undefined;
+ }
+ }
+
+ let ends: RecurrenceEnds = NEVER;
+ if (rule.count !== undefined) {
+ ends = { kind: 'after', count: rule.count };
+ } else if (rule.until !== undefined) {
+ const date = untilDate(rule.until);
+ if (date === undefined) return undefined;
+ ends = { kind: 'on', date };
+ }
+
+ return {
+ frequency: rule.frequency,
+ interval: rule.interval,
+ byDay,
+ monthlyByDay,
+ ends,
+ };
+}
+
+/** The positional weekday Google's monthly preset uses: 1st–4th, else last. */
+export function monthlyOrdinalFor(start: Date): {
+ ordinal: number;
+ weekday: WeekdayCode;
+} {
+ const nth = Math.ceil(start.getDate() / 7);
+ return {
+ ordinal: nth === 5 ? -1 : nth,
+ weekday: WEEKDAY_CODES[start.getDay()] as WeekdayCode,
+ };
+}
+
+/** One entry in the recurrence preset dropdown. */
+export interface RecurrencePreset {
+ id: string;
+ label: string;
+ config: RecurrenceConfig;
+}
+
+const ORDINAL_LABELS: Record<number, string> = {
+ 1: 'first',
+ 2: 'second',
+ 3: 'third',
+ 4: 'fourth',
+ [-1]: 'last',
+};
+
+/** Google Calendar's preset list, phrased from the event's start date. */
+export function recurrencePresetsFor(start: Date): RecurrencePreset[] {
+ const weekday = WEEKDAY_CODES[start.getDay()] as WeekdayCode;
+ const weekdayName = format(start, 'EEEE');
+ const monthly = monthlyOrdinalFor(start);
+ return [
+ {
+ id: 'daily',
+ label: 'Daily',
+ config: { frequency: 'DAILY', interval: 1, byDay: [], ends: NEVER },
+ },
+ {
+ id: 'weekly',
+ label: `Weekly on ${weekdayName}`,
+ config: {
+ frequency: 'WEEKLY',
+ interval: 1,
+ byDay: [weekday],
+ ends: NEVER,
+ },
+ },
+ {
+ id: 'monthly',
+ label: `Monthly on the ${ORDINAL_LABELS[monthly.ordinal]} ${weekdayName}`,
+ config: {
+ frequency: 'MONTHLY',
+ interval: 1,
+ byDay: [],
+ monthlyByDay: monthly,
+ ends: NEVER,
+ },
+ },
+ {
+ id: 'annually',
+ label: `Annually on ${format(start, 'MMMM d')}`,
+ config: { frequency: 'YEARLY', interval: 1, byDay: [], ends: NEVER },
+ },
+ {
+ id: 'weekdays',
+ label: 'Every weekday (Monday to Friday)',
+ config: {
+ frequency: 'WEEKLY',
+ interval: 1,
+ byDay: [...WORKWEEK],
+ ends: NEVER,
+ },
+ },
+ ];
+}
+
+/** Whether two configs produce the same rule. */
+export function recurrenceConfigsEqual(
+ first: RecurrenceConfig,
+ second: RecurrenceConfig
+): boolean {
+ return (
+ buildRecurrenceLines(first, false).join('\n') ===
+ buildRecurrenceLines(second, false).join('\n')
+ );
+}
+
+/** A sensible starting point for the custom editor. */
+export function defaultCustomConfig(start: Date): RecurrenceConfig {
+ return {
+ frequency: 'WEEKLY',
+ interval: 1,
+ byDay: [WEEKDAY_CODES[start.getDay()] as WeekdayCode],
+ ends: NEVER,
+ };
+}
diff --git a/apps/web/src/features/calendar/time-format.ts b/apps/web/src/features/calendar/utils/time-format.ts
similarity index 98%
rename from apps/web/src/features/calendar/time-format.ts
rename to apps/web/src/features/calendar/utils/time-format.ts
index f22d78a375..60381a4910 100644
--- a/apps/web/src/features/calendar/time-format.ts
+++ b/apps/web/src/features/calendar/utils/time-format.ts
@@ -1,4 +1,4 @@
-import type { CalendarTimeFormat } from './events/types';
+import type { CalendarTimeFormat } from '../types';
/** FullCalendar and Intl options for the supported calendar time formats. */
export const CALENDAR_TIME_FORMAT_OPTIONS = {
diff --git a/apps/web/src/features/settings/Email.tsx b/apps/web/src/features/settings/Email.tsx
index 88b652e459..f3939ad9ad 100644
--- a/apps/web/src/features/settings/Email.tsx
+++ b/apps/web/src/features/settings/Email.tsx
@@ -1,8 +1,8 @@
import {
TurnOffCalendarDialog,
type TurnOffCalendarTarget,
-} from '@app/features/calendar/TurnOffCalendarDialog';
-import { useCalendarUiFlag } from '@app/features/calendar/use-calendar-ui-flag';
+} from '@app/features/calendar/components/TurnOffCalendarDialog';
+import { useCalendarUiFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';
import { openAddInboxDialog } from '@app/features/inbox/AddInboxDialog';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { toast } from '@core/component/Toast/Toast';
diff --git a/apps/web/src/features/calendar/fullcalendar-solid/FullCalendar.test.tsx b/apps/web/src/lib/fullcalendar-solid/FullCalendar.test.tsx
similarity index 100%
rename from apps/web/src/features/calendar/fullcalendar-solid/FullCalendar.test.tsx
rename to apps/web/src/lib/fullcalendar-solid/FullCalendar.test.tsx
diff --git a/apps/web/src/features/calendar/fullcalendar-solid/FullCalendar.tsx b/apps/web/src/lib/fullcalendar-solid/FullCalendar.tsx
similarity index 100%
rename from apps/web/src/features/calendar/fullcalendar-solid/FullCalendar.tsx
rename to apps/web/src/lib/fullcalendar-solid/FullCalendar.tsx
diff --git a/apps/web/src/features/calendar/fullcalendar-solid/index.ts b/apps/web/src/lib/fullcalendar-solid/index.ts
similarity index 100%
rename from apps/web/src/features/calendar/fullcalendar-solid/index.ts
rename to apps/web/src/lib/fullcalendar-solid/index.ts
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
index 60a1db0bde..b25f986dea 100644
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -178,6 +178,7 @@ export default defineConfig({
'src/components/**/*.{test,spec}.{ts,tsx}',
'src/features/**/*.{test,spec}.{ts,tsx}',
'src/lib/analytics/**/*.{test,spec}.{ts,tsx}',
+ 'src/lib/fullcalendar-solid/**/*.{test,spec}.{ts,tsx}',
'src/routes/**/*.{test,spec}.{ts,tsx}',
],
name: 'app',