Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(calendar): create and modify ui styling (#5621)
dev-rb26e94d88ae61
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex 04eea3040e..364ccd8117 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -1,3 +1,6 @@+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 { useCalendarUiFlag } from '@app/features/calendar/use-calendar-ui-flag';import { GettingStarted } from '@app/features/getting-started';import { Home } from '@app/features/home';@@ -524,6 +527,23 @@ registerComponent('task-compose', (params) => {usePageViewTracking('task-compose');return <ComposeTask {...params} />;});+registerComponent('calendar-event-compose', (params) => {+ usePageViewTracking('calendar-event-compose');+ return (+ <EventComposer+ event={params?.event as CalendarEvent | undefined}+ initialValues={+ params?.initialValues as EventEditorInitialValues | undefined+ }+ onCalendarChange={+ params?.onCalendarChange as+ | ((calendarId: string, color: string) => void)+ | undefined+ }+ onClose={params?.onClose as (() => void) | undefined}+ />+ );+});registerComponent('skill-compose', (params) => {usePageViewTracking('skill-compose');return <ComposeSkill {...params} />;diff --git a/apps/web/src/components/ui/components/Calendar.tsx b/apps/web/src/components/ui/components/Calendar.tsxindex 83872b7e18..4802803610 100644--- a/apps/web/src/components/ui/components/Calendar.tsx+++ b/apps/web/src/components/ui/components/Calendar.tsx@@ -142,6 +142,7 @@ export function Calendar(props: CalendarProps) {><CorvuCalendar.CellTriggerday={day()}+ month={calendar.month}data-highlighted-range={isDateInRange(day(), local.highlightedRange)? ''diff --git a/apps/web/src/components/ui/components/Checkbox.tsx b/apps/web/src/components/ui/components/Checkbox.tsxindex a0b83f74fa..588eb4cb16 100644--- a/apps/web/src/components/ui/components/Checkbox.tsx+++ b/apps/web/src/components/ui/components/Checkbox.tsx@@ -23,6 +23,7 @@ check (or minus for indeterminate). Override by passing children:export type CheckboxProps = ComponentProps<typeof KobalteCheckbox>;type ControlProps = ComponentProps<typeof KobalteCheckbox.Control>;type IndicatorProps = ComponentProps<typeof KobalteCheckbox.Indicator>;+type LabelProps = ComponentProps<typeof KobalteCheckbox.Label>;const CONTROL_CLASS = cn('inline-flex items-center justify-center size-4 shrink-0 rounded-sm text-surface',@@ -30,7 +31,8 @@ const CONTROL_CLASS = cn('data-checked:bg-accent data-checked:border-accent','data-indeterminate:bg-accent data-indeterminate:border-accent','data-disabled:opacity-50 data-disabled:cursor-not-allowed',- 'data-invalid:border-failure'+ 'data-invalid:border-failure',+ 'peer-focus-visible:ring-2 peer-focus-visible:ring-accent');function CheckboxIndicator(props: IndicatorProps) {@@ -54,7 +56,7 @@ function CheckboxControl(props: ControlProps) {const [local, rest] = splitProps(props, ['class', 'children']);return (<>- <KobalteCheckbox.Input class="sr-only" />+ <KobalteCheckbox.Input class="peer sr-only" /><KobalteCheckbox.Control class={cn(CONTROL_CLASS, local.class)} {...rest}>{local.children ?? <CheckboxIndicator />}</KobalteCheckbox.Control>@@ -62,6 +64,11 @@ function CheckboxControl(props: ControlProps) {);}+function CheckboxLabel(props: LabelProps) {+ const [local, rest] = splitProps(props, ['class']);+ return <KobalteCheckbox.Label class={cn(local.class)} {...rest} />;+}+export const Checkbox = Object.assign((props: CheckboxProps) => {const [local, rest] = splitProps(props, ['class']);@@ -81,6 +88,7 @@ export const Checkbox = Object.assign(KobalteCheckbox.Input /* passthrough — Control already renders one */,Indicator: CheckboxIndicator,Control: CheckboxControl,+ Label: CheckboxLabel,});diff --git a/apps/web/src/components/ui/components/Select.tsx b/apps/web/src/components/ui/components/Select.tsxnew file mode 100644index 0000000000..7b98ad58c5--- /dev/null+++ b/apps/web/src/components/ui/components/Select.tsx@@ -0,0 +1,239 @@+import type {+ SelectContentProps as KobalteSelectContentProps,+ SelectIconProps as KobalteSelectIconProps,+ SelectItemIndicatorProps as KobalteSelectItemIndicatorProps,+ SelectItemLabelProps as KobalteSelectItemLabelProps,+ SelectItemProps as KobalteSelectItemProps,+ SelectListboxProps as KobalteSelectListboxProps,+ SelectPortalProps as KobalteSelectPortalProps,+ SelectRootProps as KobalteSelectRootProps,+ SelectTriggerProps as KobalteSelectTriggerProps,+ SelectValueProps as KobalteSelectValueProps,+ SelectRootItemComponentProps,+} from '@kobalte/core/select';+import { Select as KobalteSelect } from '@kobalte/core/select';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CheckIcon from '@phosphor/check.svg';+import { type Component, createSignal, type JSX, splitProps } from 'solid-js';+import { cn } from '../utils/classname';+import { Layer } from './Layer';+import type { SurfaceProps } from './Surface';++export type SelectTriggerProps = KobalteSelectTriggerProps & {+ class?: string;+ children?: JSX.Element;+};++function SelectTrigger(props: SelectTriggerProps) {+ const [local, rest] = splitProps(props, ['class']);+ return (+ <KobalteSelect.Trigger+ class={cn(+ 'flex w-full items-center justify-between gap-2 text-left data-expanded:bg-hover',+ local.class+ )}+ {...rest}+ />+ );+}++export type SelectValueProps<Option> = KobalteSelectValueProps<Option> & {+ class?: string;+};++function SelectValue<Option>(props: SelectValueProps<Option>) {+ const [local, rest] = splitProps(props, ['class']);+ return (+ <KobalteSelect.Value<Option>+ class={cn('min-w-0 flex-1 truncate', local.class)}+ {...rest}+ />+ );+}++export type SelectIconProps = KobalteSelectIconProps & {+ class?: string;+ children?: JSX.Element;+};++function SelectIcon(props: SelectIconProps) {+ const [local, rest] = splitProps(props, ['class', 'children']);+ return (+ <KobalteSelect.Icon+ class={cn('shrink-0 text-ink-extra-muted', local.class)}+ {...rest}+ >+ {local.children ?? <CaretDownIcon class="size-3" />}+ </KobalteSelect.Icon>+ );+}++type PortalMount = KobalteSelectPortalProps['mount'];+type SelectPortalScope = 'local';++export type SelectContentProps = KobalteSelectContentProps & {+ class?: string;+ children?: JSX.Element;+ depth?: SurfaceProps['depth'];+ mount?: PortalMount;+ portalScope?: SelectPortalScope;+};++function resolvePortalMount(+ searchRef: HTMLElement | undefined,+ mount: PortalMount,+ portalScope: SelectPortalScope | undefined+): PortalMount {+ if (mount || portalScope !== 'local') return mount;+ return searchRef?.closest<HTMLElement>('.portal-scope') ?? undefined;+}++function SelectContent(props: SelectContentProps) {+ const [searchRef, setSearchRef] = createSignal<HTMLDivElement>();+ const [local, rest] = splitProps(props, [+ 'class',+ 'children',+ 'depth',+ 'mount',+ 'portalScope',+ ]);+ return (+ <>+ <div class="hidden" ref={setSearchRef} />+ <KobalteSelect.Portal+ mount={resolvePortalMount(searchRef(), local.mount, local.portalScope)}+ >+ <Layer depth={local.depth ?? 3}>+ <KobalteSelect.Content+ class={cn(+ 'z-action-menu max-h-[var(--kb-popper-content-available-height)] 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',+ local.class+ )}+ {...rest}+ >+ {local.children}+ </KobalteSelect.Content>+ </Layer>+ </KobalteSelect.Portal>+ </>+ );+}++export type SelectListboxProps<+ Option = unknown,+ OptGroup = never,+> = KobalteSelectListboxProps<Option, OptGroup> & {+ class?: string;+};++function SelectListbox<Option, OptGroup = never>(+ props: SelectListboxProps<Option, OptGroup>+) {+ const [local, rest] = splitProps(props, ['class', 'ref']);+ return (+ <KobalteSelect.Listbox<Option, OptGroup>+ ref={(element) => {+ if (typeof local.ref === 'function') local.ref(element);+ }}+ class={cn('flex flex-col gap-(--app-border-width)', local.class)}+ {...rest}+ />+ );+}++export type SelectItemProps = KobalteSelectItemProps & {+ class?: string;+ children?: JSX.Element;+};++function SelectItem(props: SelectItemProps) {+ const [local, rest] = splitProps(props, ['class']);+ return (+ <KobalteSelect.Item+ class={cn(+ 'group flex w-full cursor-default items-center justify-between gap-2 rounded-lg px-2 py-1.5 text-left text-sm font-normal text-ink outline-none data-disabled:cursor-not-allowed data-disabled:opacity-50 data-highlighted:bg-hover',+ local.class+ )}+ {...rest}+ />+ );+}++export type SelectItemLabelProps = KobalteSelectItemLabelProps & {+ class?: string;+ children?: JSX.Element;+};++function SelectItemLabel(props: SelectItemLabelProps) {+ const [local, rest] = splitProps(props, ['class']);+ return (+ <KobalteSelect.ItemLabel+ class={cn('min-w-0 flex-1 truncate', local.class)}+ {...rest}+ />+ );+}++export type SelectItemIndicatorProps = KobalteSelectItemIndicatorProps & {+ class?: string;+ children?: JSX.Element;+};++function SelectItemIndicator(props: SelectItemIndicatorProps) {+ const [local, rest] = splitProps(props, ['class', 'children']);+ return (+ <KobalteSelect.ItemIndicator+ class={cn('shrink-0 text-accent', local.class)}+ {...rest}+ >+ {local.children ?? <CheckIcon class="size-3.5" />}+ </KobalteSelect.ItemIndicator>+ );+}++export type SelectRootProps<Option, OptGroup = never> = KobalteSelectRootProps<+ Option,+ OptGroup+> & {+ class?: string;+ children?: JSX.Element;+};++function SelectRoot<Option, OptGroup = never>(+ props: SelectRootProps<Option, OptGroup>+) {+ const DefaultItem: Component<SelectRootItemComponentProps<Option>> = (+ itemProps+ ) => (+ <SelectItem item={itemProps.item}>+ <SelectItemLabel>{itemProps.item.textValue}</SelectItemLabel>+ <SelectItemIndicator />+ </SelectItem>+ );++ return (+ <KobalteSelect<Option, OptGroup>+ gutter={props.gutter ?? 4}+ placement={props.placement ?? 'bottom-start'}+ shouldFocusWrap={props.shouldFocusWrap ?? true}+ {...props}+ itemComponent={props.itemComponent ?? DefaultItem}+ />+ );+}++/** Composable, styled single- or multi-value select built on Kobalte. */+export const Select = Object.assign(SelectRoot, {+ Content: SelectContent,+ Icon: SelectIcon,+ Item: SelectItem,+ ItemIndicator: SelectItemIndicator,+ ItemLabel: SelectItemLabel,+ Listbox: SelectListbox,+ Trigger: SelectTrigger,+ Value: SelectValue,+ Description: KobalteSelect.Description,+ ErrorMessage: KobalteSelect.ErrorMessage,+ Label: KobalteSelect.Label,+ Section: KobalteSelect.Section,+});diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.tsindex 9aab75675c..a5d5285c59 100644--- a/apps/web/src/components/ui/index.ts+++ b/apps/web/src/components/ui/index.ts@@ -61,6 +61,18 @@ export type { PillButtonProps, PillButtonTone } from './components/PillButton';export { PillButton } from './components/PillButton';export { Scroll } from './components/Scroll';export { SegmentedControl } from './components/SegmentedControl';+export type {+ SelectContentProps,+ SelectIconProps,+ SelectItemIndicatorProps,+ SelectItemLabelProps,+ SelectItemProps,+ SelectListboxProps,+ SelectRootProps,+ SelectTriggerProps,+ SelectValueProps,+} from './components/Select';+export { Select } from './components/Select';export type { SendButtonProps } from './components/SendButton';export { SendButton } from './components/SendButton';export { SideNav } from './components/SideNav';diff --git a/apps/web/src/features/calendar/CalendarPage.tsx b/apps/web/src/features/calendar/CalendarPage.tsxindex 2c7388dab9..397321d22f 100644--- a/apps/web/src/features/calendar/CalendarPage.tsx+++ b/apps/web/src/features/calendar/CalendarPage.tsx@@ -1,11 +1,13 @@+import { useSplitLayout } from '@components/app/split-layout/layout';import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';import { useUserId } from '@core/context/user';import { isMobile } from '@core/mobile/isMobile';-import type { DatesSetArg } from '@fullcalendar/core';+import type { DateSelectArg, DatesSetArg } 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 {type CalendarOccurrenceQueryRange,createCalendarOccurrenceQueryRange,@@ -36,8 +38,12 @@ import {pendingCalendarFocus,} from './calendar-focus-intent';import { isCalendarRangeSupported } from './calendar-supported-range';-import { mapCalendarOccurrence } from './events/calendar-occurrence-mapper';+import {+ DEFAULT_CALENDAR_SOURCE,+ mapCalendarOccurrence,+} from './events/calendar-occurrence-mapper';import { CalendarEventContent } from './events/EventContent';+import { calendarSelectionToEditorInitialValues } from './events/EventEditorForm';import { mapCalendarEventToFullCalendar } from './events/event-mapper';import type { CalendarTimeFormat } from './events/types';import { FullCalendar, useFullCalendar } from './fullcalendar-solid';@@ -305,7 +311,17 @@ function createCalendarPageData(export function CalendarPage(props: { id: CalendarPageId; initialDate: Date }) {const pager = useCalendarPager();const calendarView = useCalendarView();+ const { popoverSplit } = useSplitLayout();+ 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();@@ -319,6 +335,28 @@ export function CalendarPage(props: { id: CalendarPageId; initialDate: Date }) {equals: false,});+ const handleSelect = (selection: DateSelectArg) => {+ if (!isActive()) return;+ const calendar = firstWritableCalendar();+ setSelectionColor(calendar?.color ?? DEFAULT_CALENDAR_SOURCE.color);+ popoverSplit({+ type: 'component',+ id: 'calendar-event-compose',+ params: {+ 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();@@ -356,6 +394,11 @@ export function CalendarPage(props: { id: CalendarPageId; initialDate: Date }) {CALENDAR_TIME_FORMAT_OPTIONS[calendarView.displaySettings.timeFormat]}events={data.fullCalendarEvents()}+ selectable={!isMobile()}+ unselectAuto={false}+ selectMirror+ selectMinDistance={5}+ select={handleSelect}eventClick={({ el, event, jsEvent }) => {jsEvent.preventDefault();if (!isActive()) return;@@ -363,6 +406,13 @@ export function CalendarPage(props: { id: CalendarPageId; initialDate: Date }) {if (selectedEvent) calendarView.selectEvent(selectedEvent, el);}}eventDidMount={({ el, event }) => {+ const calendarEvent = data.eventsById().get(event.id);+ if (calendarEvent) {+ el.style.setProperty(+ '--event-calendar-color',+ calendarEvent.calendar.color+ );+ }eventElements.set(event.id, el);// A re-render (query settling, live refresh) replaces chip elements.// Re-anchor an open details popover to the remounted chip — its old@@ -436,6 +486,16 @@ export function CalendarPage(props: { id: CalendarPageId; initialDate: Date }) {<FullCalendar.EventContent>{(renderProps) => {const event = data.eventsById().get(renderProps.event.id);+ if (!event && renderProps.isMirror) {+ 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 (@@ -478,6 +538,7 @@ export function CalendarPage(props: { id: CalendarPageId; initialDate: Date }) {data={data}eventElements={eventElements}chipMounts={chipMounts}+ selectionColor={effectiveSelectionColor()}/></FullCalendar.Root>);@@ -488,6 +549,7 @@ function CalendarPageHost(props: {data: CalendarPageData;eventElements: Map<string, HTMLElement>;chipMounts: Accessor<undefined>;+ selectionColor: string;}) {const calendar = useFullCalendar();const pager = useCalendarPager();@@ -580,6 +642,7 @@ function CalendarPageHost(props: {<FullCalendar.HosttabIndex={-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} />diff --git a/apps/web/src/features/calendar/calendar-view.tsx b/apps/web/src/features/calendar/calendar-view.tsxindex 5ee2216345..28087f9bd3 100644--- a/apps/web/src/features/calendar/calendar-view.tsx+++ b/apps/web/src/features/calendar/calendar-view.tsx@@ -4,6 +4,7 @@ import {SplitHeaderLeft,SplitHeaderRight,} from '@components/app/split-layout/components/SplitHeader';+import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { TOKENS } from '@core/hotkey/tokens';import { isMobile } from '@core/mobile/isMobile';@@ -41,7 +42,6 @@ import {useCalendarView,} from './CalendarViewContext';import { SelectedEventDetails } from './events/EventDetailsPopover';-import { EventEditorDialog } from './events/EventEditorDialog';import { useCalendarHotkeys } from './use-calendar-hotkeys';import './calendar.css';@@ -175,9 +175,9 @@ function CalendarWorkspace() {const calendarPager = useCalendarPager();const pager = usePager<CalendarPageId>();const calendarView = useCalendarView();+ const { popoverSplit } = useSplitLayout();const initialDate = new Date();const today = createLocalToday();- const [createEventOpen, setCreateEventOpen] = createSignal(false);useCalendarHotkeys({scopeId: panel.splitHotkeyScope,@@ -266,7 +266,12 @@ function CalendarWorkspace() {size="sm"class="rounded-lg px-2"label="New event"- onClick={() => setCreateEventOpen(true)}+ onClick={() =>+ popoverSplit({+ type: 'component',+ id: 'calendar-event-compose',+ })+ }><PlusIcon class="size-3.5" />New event@@ -309,10 +314,6 @@ function CalendarWorkspace() {onClose={calendarView.closeEventDetails}/>- <Show when={createEventOpen()}>- <EventEditorDialog open onClose={() => setCreateEventOpen(false)} />- </Show>-<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 />diff --git a/apps/web/src/features/calendar/calendar.css b/apps/web/src/features/calendar/calendar.cssindex 4042093d3f..7a0dda720c 100644--- a/apps/web/src/features/calendar/calendar.css+++ b/apps/web/src/features/calendar/calendar.css@@ -12,7 +12,7 @@);--fc-event-border-color: var(--color-calendar);--fc-event-text-color: var(--color-calendar);- --fc-highlight-color: var(--color-accent-bg);+ --fc-highlight-color: transparent;--fc-today-bg-color: transparent;--fc-now-indicator-color: var(--color-accent);}@@ -216,12 +216,70 @@}.calendar-view .fc .fc-event {- transition: box-shadow 120ms ease-out;+ --fc-event-bg-color: color-mix(+ in oklch,+ 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)+ );+ border-color: var(--fc-event-border-color);+ background-color: var(--fc-event-bg-color);+ color: var(--fc-event-text-color);+ transition:+ box-shadow 120ms ease-out,+ opacity 120ms ease-out;+}++.calendar-view .fc .fc-event-mirror,+.calendar-view .fc .fc-highlight {+ border: 1px solid var(--calendar-selection-color, var(--color-accent));+ border-radius: 0.375rem;+ background: var(--calendar-selection-color, var(--color-accent));+ box-shadow: none;+}++.calendar-view .fc .fc-highlight {+ inset: 2px;+}++.calendar-view .fc .fc-dayGridMonth-view .fc-highlight {+ top: 1.5rem;+ right: 0.375rem;+ bottom: auto;+ left: 0.375rem;+ height: 1rem;+}++/* Timed selections already render an event mirror; hide its backing fill. */+.calendar-view .fc .fc-timegrid-col-bg .fc-highlight {+ inset: 0;+ border: 0;+ background: transparent;+ box-shadow: none;+}++.calendar-view .fc .fc-event-mirror {+ color: var(--calendar-selection-color, var(--color-accent));+}++.calendar-view .fc .fc-event-mirror .fc-event-main {+ color: inherit;+}++.calendar-view .fc .fc-event-mirror .calendar-event-selection-preview {+ filter: invert(1) grayscale(1) contrast(100);}.calendar-view .fc .fc-event .calendar-event-content {container-type: inline-size;- border-radius: 0.25rem;+ border-radius: inherit;transition: background-color 120ms ease-out;}@@ -277,6 +335,41 @@display: none;}+.calendar-view+ .fc+ .fc-event:has(.calendar-event-content[data-response-status="tentative"]) {+ --fc-event-bg-color: color-mix(+ in oklch,+ var(--event-calendar-color, var(--color-calendar)) 2%,+ var(--color-surface)+ );+ border-style: dashed;+}++.calendar-view+ .fc+ .fc-event:has(.calendar-event-content[data-response-status="declined"]) {+ opacity: 0.5;+}++.calendar-view+ .fc+ .calendar-event-content[data-response-status="declined"]+ .calendar-event-title {+ text-decoration: line-through;+}++.calendar-view+ .fc+ .fc-event:has(.calendar-event-content[data-response-status="needs_action"]) {+ --fc-event-bg-color: transparent;+ --fc-event-text-color: color-mix(+ in oklch,+ var(--event-calendar-color, var(--color-calendar)) 65%,+ var(--color-ink-muted)+ );+}+.calendar-view .fc .fc-event:hover {z-index: 4;}@@ -297,10 +390,12 @@.calendar-view .fc .fc-event:has(.calendar-event-content-selected) {z-index: 3;- border-color: var(--color-accent) !important;- background-color: var(--color-accent) !important;- color: var(--color-surface) !important;+ --fc-event-border-color: var(--color-accent);+ --fc-event-bg-color: var(--color-accent);+ --fc-event-text-color: var(--color-surface);box-shadow: 0 0 0 1px var(--color-accent);+ border-style: solid;+ opacity: 1;}.calendar-viewdiff --git a/apps/web/src/features/calendar/events/EventComposer.tsx b/apps/web/src/features/calendar/events/EventComposer.tsxnew file mode 100644index 0000000000..9245bff569--- /dev/null+++ b/apps/web/src/features/calendar/events/EventComposer.tsx@@ -0,0 +1,45 @@+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { onCleanup, 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: {+ event?: CalendarEvent;+ initialValues?: EventEditorInitialValues;+ onCalendarChange?: (calendarId: string, color: string) => void;+ onClose?: () => void;+}) {+ const panel = useSplitPanelOrThrow();+ const close = () => panel.handle.close();+ const editor = useEventEditor({+ event: () => props.event,+ onSaved: close,+ });++ const isEdit = () => props.event !== undefined;++ onMount(() =>+ panel.handle.setDisplayName(isEdit() ? 'Edit event' : 'New event')+ );+ onCleanup(() => props.onClose?.());++ return (+ <div class="portal-scope flex h-full min-h-0 flex-col p-4 text-ink">+ <EventComposerForm+ initialValues={editor.initialValues() ?? props.initialValues}+ isEdit={isEdit()}+ disabledFields={editor.disabledFields()}+ calendarOptions={editor.calendarOptions()}+ guestOptions={editor.guestOptions}+ showRecurringEditNotice={editor.showRecurringEditNotice()}+ pending={editor.pending()}+ onCalendarChange={props.onCalendarChange}+ onCancel={close}+ onSubmit={editor.save}+ />+ </div>+ );+}diff --git a/apps/web/src/features/calendar/events/EventComposerDateTimeRangeFields.tsx b/apps/web/src/features/calendar/events/EventComposerDateTimeRangeFields.tsxnew file mode 100644index 0000000000..62a4630f71--- /dev/null+++ b/apps/web/src/features/calendar/events/EventComposerDateTimeRangeFields.tsx@@ -0,0 +1,198 @@+import { Popover } from '@kobalte/core/popover';+import ArrowRightIcon from '@phosphor/arrow-right.svg';+import CalendarBlankIcon from '@phosphor/calendar-blank.svg';+import CaretDownIcon from '@phosphor/caret-down.svg';+import { Calendar } from '@ui/components/Calendar';+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 {+ dateLabelFormatter,+ EventTimeInput,+ formatLocalDate,+ parseLocalDate,+ splitLocalDateTime,+ timeLabelFormatter,+ withLocalDate,+ withLocalTime,+} from './EventDateTimeField';++function formatTime(value: string) {+ const [hour, minute] = value.split(':').map(Number);+ if (hour === undefined || minute === undefined) return 'Time';+ return timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute));+}++export interface EventComposerDateTimeRangeFieldsProps {+ start: string;+ end: string;+ allDay: boolean;+ onStartChange: (value: string) => void;+ onEndChange: (value: string) => void;+ onAllDayChange: (allDay: boolean) => void;+ startDisabled?: boolean;+ endDisabled?: boolean;+ allDayDisabled?: boolean;+ invalid?: boolean;+ describedBy?: string;+}++/** Combined date-range display with start/end calendar and time controls. */+export function EventComposerDateTimeRangeFields(+ props: EventComposerDateTimeRangeFieldsProps+) {+ const fieldId = createUniqueId();+ const [open, setOpen] = createSignal(false);+ let trigger: HTMLButtonElement | undefined;++ const startParts = () => splitLocalDateTime(props.start);+ const endParts = () => splitLocalDateTime(props.end);+ const startDate = () => parseLocalDate(startParts().date);+ const endDate = () => parseLocalDate(endParts().date);+ const disabled = () =>+ props.startDisabled && props.endDisabled && props.allDayDisabled;+ const rangeLabel = () => {+ const start = startDate();+ const end = endDate();+ const startLabel = start ? dateLabelFormatter.format(start) : 'Start date';+ const endLabel = end ? dateLabelFormatter.format(end) : 'End date';+ if (props.allDay) return `${startLabel} – ${endLabel}`;+ return `${startLabel} ${formatTime(startParts().time)} – ${endLabel} ${formatTime(endParts().time)}`;+ };++ return (+ <Popover+ anchorRef={() => trigger}+ open={open() && !disabled()}+ onOpenChange={(nextOpen) => setOpen(!disabled() && nextOpen)}+ placement="bottom-start"+ gutter={4}+ flip+ slide+ >+ <button+ ref={trigger}+ type="button"+ disabled={disabled()}+ aria-label="Edit event date and time range"+ aria-expanded={open()}+ aria-haspopup="dialog"+ aria-invalid={props.invalid || undefined}+ aria-describedby={props.describedBy}+ class={cn(+ 'group inline-flex min-h-8 w-fit max-w-full self-start items-center gap-2 rounded-lg bg-transparent px-2 text-left text-xs text-ink-muted transition-colors hover:bg-hover hover:text-ink focus-visible:text-ink focus-visible:ring focus-visible:ring-accent/10',+ open() && 'bg-hover',+ props.invalid && 'text-failure'+ )}+ onClick={() => setOpen((current) => !current)}+ >+ <CalendarBlankIcon+ class={cn(+ 'size-3.5 shrink-0',+ props.invalid+ ? 'text-failure'+ : 'text-ink-extra-muted group-hover:text-ink-muted group-focus-visible:text-ink-muted'+ )}+ />+ <span class="min-w-0 truncate">{rangeLabel()}</span>+ <CaretDownIcon class="size-3 shrink-0 text-ink-extra-muted group-hover:text-ink-muted group-focus-visible:text-ink-muted" />+ </button>++ <Popover.Portal>+ <Layer depth={3}>+ <Popover.Content+ class="portal-scope z-action-menu w-[38rem] max-w-[calc(100vw-1rem)] overflow-hidden rounded-xl border border-edge bg-menu shadow-menu menu-open-animation"+ on:keydown={(event: KeyboardEvent) => {+ if (event.key !== 'Escape') return;+ event.preventDefault();+ event.stopPropagation();+ setOpen(false);+ }}+ onOpenAutoFocus={(event) => event.preventDefault()}+ onCloseAutoFocus={(event) => event.preventDefault()}+ >+ <Popover.Title class="sr-only">+ Choose event date and time range+ </Popover.Title>+ <div class="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-start">+ <div class="min-w-0 p-3">+ <Calendar+ required+ fixedWeeks+ value={startDate()}+ onValueChange={(date) => {+ if (!date || props.startDisabled) return;+ const nextDate = formatLocalDate(date);+ props.onStartChange(+ props.allDay+ ? nextDate+ : withLocalDate(props.start, nextDate)+ );+ }}+ />+ </div>+ <ArrowRightIcon+ aria-label="to"+ class="mt-[1.125rem] size-4 shrink-0 text-ink-extra-muted"+ />+ <div class="min-w-0 p-3">+ <Calendar+ required+ fixedWeeks+ value={endDate()}+ onValueChange={(date) => {+ if (!date || props.endDisabled) return;+ const nextDate = formatLocalDate(date);+ props.onEndChange(+ props.allDay+ ? nextDate+ : withLocalDate(props.end, nextDate)+ );+ }}+ />+ </div>+ </div>++ <div class="border-t border-edge p-3">+ <div class="grid grid-cols-2 gap-3">+ <div class={cn(props.allDay && 'opacity-50')}>+ <EventTimeInput+ id={`composer-start-time-${fieldId}`}+ label="Start time"+ value={startParts().time}+ onChange={(time) =>+ props.onStartChange(withLocalTime(props.start, time))+ }+ disabled={props.startDisabled || props.allDay}+ />+ </div>+ <div class={cn(props.allDay && 'opacity-50')}>+ <EventTimeInput+ id={`composer-end-time-${fieldId}`}+ label="End time"+ value={endParts().time}+ onChange={(time) =>+ props.onEndChange(withLocalTime(props.end, time))+ }+ disabled={props.endDisabled || props.allDay}+ />+ </div>+ </div>+ <div class="mt-3 flex items-center gap-2">+ <ToggleSwitch+ checked={props.allDay}+ disabled={props.allDayDisabled}+ onChange={props.onAllDayChange}+ size="sm"+ aria-label="All day"+ />+ <span class="text-xs text-ink-muted">All day</span>+ </div>+ </div>+ </Popover.Content>+ </Layer>+ </Popover.Portal>+ </Popover>+ );+}diff --git a/apps/web/src/features/calendar/events/EventComposerForm.tsx b/apps/web/src/features/calendar/events/EventComposerForm.tsxnew file mode 100644index 0000000000..6ae07c3ea8--- /dev/null+++ b/apps/web/src/features/calendar/events/EventComposerForm.tsx@@ -0,0 +1,284 @@+import SpinnerIcon from '@phosphor/spinner.svg';+import { Button, cn, Layer } from '@ui';+import {+ type Accessor,+ createEffect,+ 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 { 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;+ 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 [selectedGuests, setSelectedGuests] = createSignal<+ SelectedEventEditorGuest[]+ >(initialGuestOptions(initialValues.guests, props.guestOptions()));++ 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];++ createEffect(() => {+ const option = selectedCalendarOption();+ if (option) props.onCalendarChange?.(option.id, option.color);+ });++ 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}+ label="Cancel"+ onClick={props.onCancel}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ variant={canSave() ? 'active' : 'ghost'}+ depth={3}+ class="rounded-lg border-0"+ disabled={!canSave() || props.pending}+ 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/events/EventComposerPropertyPills.tsxnew file mode 100644index 0000000000..44249b5742--- /dev/null+++ b/apps/web/src/features/calendar/events/EventComposerPropertyPills.tsx@@ -0,0 +1,634 @@+import { UserIcon } from '@core/component/UserIcon';+import { emailToId, recipientEntityMapper } from '@core/user';+import { Combobox } from '@kobalte/core/combobox';+import { Popover } from '@kobalte/core/popover';+import CalendarDotsIcon from '@phosphor/calendar-dots.svg';+import CaretDownIcon from '@phosphor/caret-down.svg';+import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';+import MapPinIcon from '@phosphor/map-pin.svg';+import RepeatIcon from '@phosphor/repeat.svg';+import UsersIcon from '@phosphor/users.svg';+import { OptionCheckBox } from '@property/editors/selectors/OptionCheckBox';+import { cn, Layer, Select, Tooltip } from '@ui';+import * as EmailValidator from 'email-validator';+import {+ type Accessor,+ createMemo,+ createSignal,+ createUniqueId,+ For,+ Show,+} from 'solid-js';+import { type VirtualizerHandle, VList } from 'virtua/solid';+import {+ type EventEditorCalendarOption,+ type EventEditorGuestOption,+ guestEmail,+ type SelectedEventEditorGuest,+} from './EventEditorForm';++const GUEST_NAME_COLLATOR = new Intl.Collator(undefined, {+ sensitivity: 'base',+});+const GUEST_OPTION_HEIGHT_PX = 36;+const GUEST_OPTION_MAX_VISIBLE_COUNT = 5;+const PROPERTY_TRIGGER_CLASS =+ 'group flex h-7 items-center justify-between gap-1.5 rounded-full border border-edge-muted bg-surface px-2 py-1 text-left text-xs leading-tight text-ink-muted hover:bg-hover hover:text-ink focus-visible:bg-active focus-visible:text-ink focus-visible:ring-accent/10 data-expanded:bg-hover data-expanded:text-ink';+const PROPERTY_VALUE_CLASS =+ 'group-hover:text-ink group-focus-visible:text-ink group-data-expanded:text-ink';++export type EventComposerSelectOption = {+ value: string;+ label: string;+};++type GuestPickerItem =+ | { kind: 'guest'; guest: SelectedEventEditorGuest }+ | { kind: 'custom'; email: string };++function guestPickerItemEmail(item: GuestPickerItem) {+ return item.kind === 'guest' ? guestEmail(item.guest) : item.email;+}++function guestPickerItemValue(item: GuestPickerItem) {+ return guestPickerItemEmail(item).toLowerCase();+}++export interface EventComposerGuestsPillProps {+ options: Accessor<EventEditorGuestOption[]>;+ selected: SelectedEventEditorGuest[];+ onChange: (selected: SelectedEventEditorGuest[]) => void;+ disabled?: boolean;+ readOnly?: boolean;+ hideIcon?: boolean;+}++function guestDisplayName(guest: SelectedEventEditorGuest) {+ return ('name' in guest.data && guest.data.name) || guest.data.email;+}++function guestPropertyLabel(selected: SelectedEventEditorGuest[]) {+ if (selected.length === 0) return 'Guests';+ if (selected.length > 1) return `${selected.length} guests`;+ return guestDisplayName(selected[0]);+}++function ReadOnlyEventComposerGuestsPill(props: EventComposerGuestsPillProps) {+ const [open, setOpen] = createSignal(false);++ return (+ <Popover+ open={open() && !props.disabled}+ onOpenChange={setOpen}+ placement="bottom-start"+ gutter={4}+ flip+ slide+ >+ <Tooltip label="View event guests" placement="bottom">+ <Popover.Trigger+ disabled={props.disabled}+ aria-label="Guests"+ aria-readonly="true"+ class={cn(PROPERTY_TRIGGER_CLASS, 'max-w-48 overflow-hidden')}+ >+ <Show when={!props.hideIcon}>+ <UsersIcon class="size-3.5 shrink-0 text-ink-extra-muted" />+ </Show>+ <span+ class={cn(+ 'min-w-0 truncate',+ PROPERTY_VALUE_CLASS,+ props.selected.length > 0+ ? 'text-current'+ : 'text-ink-extra-muted'+ )}+ >+ {guestPropertyLabel(props.selected)}+ </span>+ <CaretDownIcon class="size-3 shrink-0 text-ink-extra-muted" />+ </Popover.Trigger>+ </Tooltip>+ <Popover.Portal>+ <Layer depth={3}>+ <Popover.Content class="z-action-menu w-72 max-w-[calc(100vw-1rem)] rounded-xl border border-edge bg-menu p-1.5 text-sm shadow-menu menu-open-animation">+ <Popover.Title class="sr-only">Event guests</Popover.Title>+ <Show+ when={props.selected.length > 0}+ fallback={+ <p class="px-2 py-4 text-center text-sm text-ink-muted">+ No guests+ </p>+ }+ >+ <div class="flex max-h-64 flex-col overflow-y-auto">+ <For each={props.selected}>+ {(guest) => (+ <div class="flex min-w-0 items-center gap-2 rounded-lg px-2 py-2 text-ink">+ <UserIcon+ id={guest.id}+ size="sm"+ isDeleted={false}+ suppressClick+ />+ <div class="min-w-0 flex-1 truncate text-sm">+ {guestDisplayName(guest)}+ <Show+ when={guestDisplayName(guest) !== guestEmail(guest)}+ >+ <span class="ml-[0.5em] text-ink-muted">+ {guestEmail(guest)}+ </span>+ </Show>+ </div>+ </div>+ )}+ </For>+ </div>+ </Show>+ </Popover.Content>+ </Layer>+ </Popover.Portal>+ </Popover>+ );+}++function EditableEventComposerGuestsPill(props: EventComposerGuestsPillProps) {+ const inputId = `event-composer-guests-${createUniqueId()}`;++ const [open, setOpen] = createSignal(false);+ const [search, setSearch] = createSignal('');+ const [comboboxDisabled, setComboboxDisabled] = createSignal(false);+ const [scrollToItem, setScrollToItem] = createSignal<(key: string) => void>();++ let input: HTMLInputElement | undefined;++ const propertyLabel = () => guestPropertyLabel(props.selected);++ const pickerOptions = createMemo(() => {+ const byEmail = new Map<string, SelectedEventEditorGuest>();+ for (const guest of props.options()) {+ byEmail.set(guestEmail(guest).toLowerCase(), guest);+ }+ for (const guest of props.selected) {+ byEmail.set(guestEmail(guest).toLowerCase(), guest);+ }+ return [...byEmail.values()].sort((left, right) =>+ GUEST_NAME_COLLATOR.compare(+ guestDisplayName(left),+ guestDisplayName(right)+ )+ );+ });++ const customEmail = () => {+ const email = search().trim();+ if (!EmailValidator.validate(email)) return undefined;+ if (+ pickerOptions().some(+ (guest) => guestEmail(guest).toLowerCase() === email.toLowerCase()+ )+ ) {+ return undefined;+ }+ return email;+ };++ const visibleItems = createMemo<GuestPickerItem[]>(() => {+ const items: GuestPickerItem[] = pickerOptions().map((guest) => ({+ kind: 'guest',+ guest,+ }));+ const email = customEmail();+ if (email) items.push({ kind: 'custom', email });+ return items;+ });++ const selectedItems = () =>+ props.selected.map((guest): GuestPickerItem => ({ kind: 'guest', guest }));++ const comboboxOptions = createMemo(() => {+ const items = new Map<string, GuestPickerItem>();+ for (const item of selectedItems()) {+ items.set(guestPickerItemValue(item), item);+ }+ for (const item of visibleItems()) {+ items.set(guestPickerItemValue(item), item);+ }+ return [...items.values()];+ });++ const isSelected = (guest: SelectedEventEditorGuest) =>+ props.selected.some(+ (selected) =>+ guestEmail(selected).toLowerCase() === guestEmail(guest).toLowerCase()+ );++ const changeSelection = (items: GuestPickerItem[]) => {+ const guests = new Map<string, SelectedEventEditorGuest>();+ for (const item of items) {+ const guest =+ item.kind === 'guest'+ ? item.guest+ : recipientEntityMapper('custom')({+ id: emailToId(item.email),+ email: item.email,+ invalid: false,+ });+ guests.set(guestEmail(guest).toLowerCase(), guest);+ }+ props.onChange([...guests.values()]);+ setSearch('');+ queueMicrotask(() => input?.focus());+ };++ const changeOpen = (next: boolean) => {+ setOpen(next);+ if (!next) setSearch('');+ };++ return (+ <Combobox<GuestPickerItem>+ multiple+ virtualized+ open={open() && !props.disabled}+ onOpenChange={changeOpen}+ onInputChange={setSearch}+ options={comboboxOptions()}+ value={selectedItems()}+ onChange={changeSelection}+ optionValue={guestPickerItemValue}+ optionLabel={(item) =>+ item.kind === 'guest' ? guestDisplayName(item.guest) : item.email+ }+ optionTextValue={(item) =>+ item.kind === 'guest'+ ? `${guestDisplayName(item.guest)} ${guestEmail(item.guest)}`+ : item.email+ }+ placeholder="Add guests..."+ closeOnSelection={false}+ allowsEmptyCollection+ placement="bottom-start"+ disabled={props.disabled || comboboxDisabled()}+ >+ <Combobox.Control<GuestPickerItem> class="inline-flex min-w-0 max-w-48 shrink-0">+ <Tooltip label="Add guests to this event" placement="bottom">+ <Combobox.Trigger+ tabIndex={0}+ aria-readonly={props.readOnly || undefined}+ class={cn(PROPERTY_TRIGGER_CLASS, 'max-w-48 overflow-hidden')}+ onKeyDown={(event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ setOpen((current) => !current);+ queueMicrotask(() => input?.focus());+ }}+ >+ <Show when={!props.hideIcon}>+ <UsersIcon class="size-3.5 shrink-0 text-ink-extra-muted" />+ </Show>+ <span+ class={cn(+ 'min-w-0 truncate',+ PROPERTY_VALUE_CLASS,+ props.selected.length > 0+ ? 'text-current'+ : 'text-ink-extra-muted'+ )}+ >+ {propertyLabel()}+ </span>+ <CaretDownIcon class="size-3 shrink-0 text-ink-extra-muted" />+ </Combobox.Trigger>+ </Tooltip>+ </Combobox.Control>++ <Combobox.Portal>+ <Layer depth={3}>+ <Combobox.Content+ class="z-action-menu flex w-96 max-w-[calc(100vw-1rem)] flex-col overflow-hidden rounded-xl border border-edge bg-menu p-0 text-sm shadow-menu menu-open-animation"+ on:keydown={(event: KeyboardEvent) => {+ if (event.key !== 'Escape') return;+ event.preventDefault();+ event.stopPropagation();+ setOpen(false);+ }}+ >+ <div class="flex w-full items-center gap-2 border-b border-edge-muted px-2 py-2">+ <MagnifyingGlassIcon class="size-4 shrink-0 text-ink-muted" />+ <label for={inputId} class="sr-only">+ Search for guests+ </label>+ <Combobox.Input+ ref={input}+ id={inputId}+ class="w-full bg-transparent text-ink caret-accent outline-none placeholder:text-ink-placeholder"+ onKeyDown={(event) => {+ if (+ (event.key === 'a' && event.ctrlKey) ||+ (event.key === 'a' && event.metaKey)+ ) {+ setComboboxDisabled(true);+ queueMicrotask(() => setComboboxDisabled(false));+ }+ }}+ on:keydown={(event: KeyboardEvent) => {+ if (event.key === 'Escape' && open()) {+ event.preventDefault();+ event.stopPropagation();+ setOpen(false);+ return;+ }+ if (event.key !== 'Tab' || !open()) return;+ event.preventDefault();+ event.stopPropagation();+ input?.dispatchEvent(+ new KeyboardEvent('keydown', {+ bubbles: true,+ key: 'Enter',+ })+ );+ }}+ />+ </div>++ <div class="p-1.5">+ <Combobox.Listbox<GuestPickerItem> scrollToItem={scrollToItem()}>+ {(items) => {+ const nodes = Array.from(items());+ const visibleCount = Math.min(+ nodes.length,+ GUEST_OPTION_MAX_VISIBLE_COUNT+ );+ const [virtualizer, setVirtualizer] =+ createSignal<VirtualizerHandle | null>(null);++ setScrollToItem(() => (key: string) => {+ const index = nodes.findIndex((node) => node.key === key);+ if (index >= 0) {+ virtualizer()?.scrollToIndex(index, {+ align: 'nearest',+ });+ }+ });++ return (+ <Show+ when={nodes.length > 0}+ fallback={+ <p class="py-4 text-center text-sm text-ink-muted">+ No users found+ </p>+ }+ >+ <VList+ data={nodes}+ itemSize={GUEST_OPTION_HEIGHT_PX}+ style={{+ height: `${visibleCount * GUEST_OPTION_HEIGHT_PX}px`,+ }}+ ref={setVirtualizer}+ >+ {(node) => {+ const item = node.rawValue;+ return (+ <Combobox.Item+ item={node}+ class="group flex h-9 w-full min-w-0 cursor-default items-center justify-between gap-1.5 rounded-lg px-2 text-left font-normal text-ink outline-none hover:bg-hover data-highlighted:bg-hover"+ >+ {item.kind === 'guest' ? (+ <>+ <OptionCheckBox+ checked={isSelected(item.guest)}+ multiselect+ />+ <div class="flex min-w-0 flex-1 items-center gap-2">+ <div class="flex size-4 shrink-0 items-center">+ <UserIcon+ id={item.guest.id}+ size="sm"+ isDeleted={false}+ suppressClick+ />+ </div>+ <Combobox.ItemLabel class="min-w-0 max-w-full truncate">+ {guestDisplayName(item.guest)}+ <Show+ when={+ guestDisplayName(item.guest) !==+ guestEmail(item.guest)+ }+ >+ <span class="ml-[0.5em] opacity-50">+ {guestEmail(item.guest)}+ </span>+ </Show>+ </Combobox.ItemLabel>+ </div>+ </>+ ) : (+ <>+ <div class="size-3.5 shrink-0" />+ <div class="flex size-4 shrink-0 items-center">+ <UserIcon+ id={item.email}+ size="sm"+ isDeleted={false}+ suppressClick+ />+ </div>+ <Combobox.ItemLabel class="truncate">+ Add {item.email}+ </Combobox.ItemLabel>+ </>+ )}+ </Combobox.Item>+ );+ }}+ </VList>+ </Show>+ );+ }}+ </Combobox.Listbox>+ </div>+ </Combobox.Content>+ </Layer>+ </Combobox.Portal>+ </Combobox>+ );+}++/** Compact guest property pill with editable and read-only dropdown views. */+export function EventComposerGuestsPill(props: EventComposerGuestsPillProps) {+ return (+ <Show+ when={props.readOnly}+ fallback={<EditableEventComposerGuestsPill {...props} />}+ >+ <ReadOnlyEventComposerGuestsPill {...props} />+ </Show>+ );+}++export interface EventComposerLocationPillProps {+ value: string;+ onChange: (value: string) => void;+ disabled?: boolean;+ hideIcon?: boolean;+}++/** Compact editable location property pill. */+export function EventComposerLocationPill(+ props: EventComposerLocationPillProps+) {+ const [open, setOpen] = createSignal(false);+ let input: HTMLInputElement | undefined;++ return (+ <Popover+ open={open() && !props.disabled}+ onOpenChange={(nextOpen) => setOpen(!props.disabled && nextOpen)}+ placement="bottom-start"+ gutter={4}+ flip+ slide+ >+ <Tooltip label="Set the event location" placement="bottom">+ <Popover.Trigger+ disabled={props.disabled}+ aria-label="Location"+ class={cn(PROPERTY_TRIGGER_CLASS, 'max-w-48 overflow-hidden')}+ >+ <Show when={!props.hideIcon}>+ <MapPinIcon class="size-3.5 shrink-0 text-ink-extra-muted" />+ </Show>+ <span+ class={cn(+ 'min-w-0 truncate',+ PROPERTY_VALUE_CLASS,+ props.value ? 'text-current' : 'text-ink-extra-muted'+ )}+ >+ {props.value || 'Add location'}+ </span>+ <CaretDownIcon class="size-3 shrink-0 text-ink-extra-muted" />+ </Popover.Trigger>+ </Tooltip>+ <Popover.Portal>+ <Layer depth={3}>+ <Popover.Content+ class="z-action-menu w-72 max-w-[calc(100vw-1rem)] rounded-xl border border-edge bg-menu p-2 shadow-menu menu-open-animation"+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ queueMicrotask(() => input?.focus());+ }}+ >+ <Popover.Title class="sr-only">Event location</Popover.Title>+ <input+ ref={input}+ type="text"+ value={props.value}+ onInput={(event) => props.onChange(event.currentTarget.value)}+ placeholder="Add location..."+ aria-label="Location"+ disabled={props.disabled}+ class="h-8 w-full rounded-md border border-edge-muted bg-surface px-2 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:border-accent"+ />+ </Popover.Content>+ </Layer>+ </Popover.Portal>+ </Popover>+ );+}++export interface EventComposerRecurrencePillProps {+ options: EventComposerSelectOption[];+ value: EventComposerSelectOption;+ onChange: (value: string) => void;+ disabled?: boolean;+ readOnly?: boolean;+ hideIcon?: boolean;+}++/** Compact recurrence property pill. */+export function EventComposerRecurrencePill(+ props: EventComposerRecurrencePillProps+) {+ return (+ <Select<EventComposerSelectOption>+ options={props.options}+ value={props.value}+ onChange={(option) => {+ if (option && !props.readOnly) props.onChange(option.value);+ }}+ optionValue="value"+ optionTextValue="label"+ optionDisabled={() => props.readOnly === true}+ disabled={props.disabled}+ >+ <Tooltip label="Set how this event repeats" placement="bottom">+ <Select.Trigger+ aria-label="Repeats"+ aria-readonly={props.readOnly || undefined}+ class={cn(PROPERTY_TRIGGER_CLASS, 'max-w-48')}+ >+ <Show when={!props.hideIcon}>+ <RepeatIcon class="size-3.5 shrink-0 text-ink-extra-muted" />+ </Show>+ <Select.Value<EventComposerSelectOption>>+ {(selectState) => selectState.selectedOption().label}+ </Select.Value>+ <Select.Icon />+ </Select.Trigger>+ </Tooltip>+ <Select.Content>+ <Select.Listbox />+ </Select.Content>+ </Select>+ );+}++export interface EventComposerCalendarPillProps {+ options: EventEditorCalendarOption[];+ value: EventEditorCalendarOption;+ onChange: (calendarId: string) => void;+ disabled?: boolean;+ readOnly?: boolean;+}++/** Compact calendar property pill. */+export function EventComposerCalendarPill(+ props: EventComposerCalendarPillProps+) {+ return (+ <Select<EventEditorCalendarOption>+ options={props.options}+ value={props.value}+ onChange={(option) => {+ if (option && !props.readOnly) props.onChange(option.id);+ }}+ optionValue="id"+ optionTextValue="label"+ optionDisabled={() => props.readOnly === true}+ disabled={props.disabled}+ >+ <Tooltip label="Choose the calendar for this event" placement="bottom">+ <Select.Trigger+ aria-label="Calendar"+ aria-readonly={props.readOnly || undefined}+ class={cn(PROPERTY_TRIGGER_CLASS, 'w-40')}+ >+ <CalendarDotsIcon class="size-3.5 shrink-0 text-ink-extra-muted" />+ <Select.Value<EventEditorCalendarOption>>+ {(selectState) => selectState.selectedOption().label}+ </Select.Value>+ <Select.Icon />+ </Select.Trigger>+ </Tooltip>+ <Select.Content>+ <Select.Listbox />+ </Select.Content>+ </Select>+ );+}diff --git a/apps/web/src/features/calendar/events/EventContent.tsx b/apps/web/src/features/calendar/events/EventContent.tsxindex 0e8a45fae4..d2d3675d08 100644--- a/apps/web/src/features/calendar/events/EventContent.tsx+++ b/apps/web/src/features/calendar/events/EventContent.tsx@@ -1,4 +1,5 @@import type { EventContentArg } from '@fullcalendar/core';+import { cn } from '@ui';import { Show } from 'solid-js';import {formatCompactCalendarTime,@@ -22,6 +23,8 @@ export function CalendarEventContent(props: CalendarEventContentProps) {props.event.allDay || props.renderProps.view.type === 'dayGridMonth';const showLocation = () =>!props.event.allDay && props.renderProps.view.type === 'timeGridDay';+ const selfResponseStatus = () =>+ props.event.attendees.find((attendee) => attendee.isSelf)?.responseStatus;const usesSingleLineLayout = () => {const duration =new Date(props.event.end).getTime() -@@ -50,28 +53,27 @@ export function CalendarEventContent(props: CalendarEventContentProps) {return (<div- class="calendar-event-content w-full min-w-0 overflow-hidden"- classList={{- 'h-full': !isCompact(),- 'min-h-0': !isCompact(),- 'calendar-event-content-selected': props.isSelected,- }}+ class={cn(+ 'calendar-event-content w-full min-w-0 overflow-hidden',+ !isCompact() && 'h-full min-h-0',+ props.isSelected && 'calendar-event-content-selected'+ )}+ data-response-status={selfResponseStatus()}><div- class="calendar-event-content-layout flex w-full min-h-0 flex-col overflow-hidden"- classList={{- 'h-full': !isCompact(),- 'calendar-event-content-compact': isCompact(),- 'calendar-event-content-layout-single-line':- isCompact() || usesSingleLineLayout(),- }}+ class={cn(+ 'calendar-event-content-layout flex w-full min-h-0 flex-col overflow-hidden',+ !isCompact() && 'h-full',+ isCompact() && 'calendar-event-content-compact',+ (isCompact() || usesSingleLineLayout()) &&+ 'calendar-event-content-layout-single-line'+ )}><span- class="calendar-event-title max-w-full shrink-0 font-semibold leading-tight"- classList={{- truncate: !props.isNarrow,- 'whitespace-nowrap': props.isNarrow,- }}+ class={cn(+ 'calendar-event-title max-w-full shrink-0 font-semibold leading-tight',+ props.isNarrow ? 'whitespace-nowrap' : 'truncate'+ )}>{props.event.title}</span>diff --git a/apps/web/src/features/calendar/events/EventDateTimeField.tsx b/apps/web/src/features/calendar/events/EventDateTimeField.tsxnew file mode 100644index 0000000000..d2f12527f6--- /dev/null+++ b/apps/web/src/features/calendar/events/EventDateTimeField.tsx@@ -0,0 +1,568 @@+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/EventDetails.tsx b/apps/web/src/features/calendar/events/EventDetails.tsxindex df8bca4bac..017783f767 100644--- a/apps/web/src/features/calendar/events/EventDetails.tsx+++ b/apps/web/src/features/calendar/events/EventDetails.tsx@@ -23,7 +23,7 @@ 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 { Avatar, Button } from '@ui';+import { Avatar, Button, cn } from '@ui';import {type Accessor,createMemo,@@ -117,11 +117,12 @@ function CalendarUserItem(props: {secondaryLabelPosition?: 'above' | 'below';details?: JSX.Element;trailing?: JSX.Element;+ nameClass?: string;}) {const secondaryLabelPosition = () => props.secondaryLabelPosition ?? 'below';return (- <div class="flex min-w-0 items-center gap-3">+ <div class="flex min-w-0 items-center gap-4 sm:gap-3"><Showkeyedwhen={props.iconProps}@@ -147,18 +148,23 @@ function CalendarUserItem(props: {<Showwhen={secondaryLabelPosition() === 'above' && props.secondaryLabel}>- <div class="flex gap-1 text-xxs text-ink-extra-muted">+ <div class="flex gap-1 text-xs text-ink-extra-muted sm:text-xxs">{props.secondaryLabel}</div></Show>- <span class="block select-text truncate text-ink-muted">+ <span+ class={cn(+ 'block select-text truncate text-ink-muted',+ props.nameClass+ )}+ >{props.displayName()}<Show when={props.isSelf}> (you)</Show></span><Showwhen={secondaryLabelPosition() === 'below' && props.secondaryLabel}>- <div class="flex gap-1 text-xxs text-ink-extra-muted">+ <div class="flex gap-1 text-xs text-ink-extra-muted sm:text-xxs">{props.secondaryLabel}</div></Show>@@ -169,7 +175,10 @@ function CalendarUserItem(props: {);}-function CalendarAttendeeItem(props: { item: ResolvedCalendarAttendee }) {+function CalendarAttendeeItem(props: {+ item: ResolvedCalendarAttendee;+ nameClass?: string;+}) {const attendee = props.item.attendee;const response =attendee.responseStatus === 'needs_action'@@ -187,7 +196,7 @@ function CalendarAttendeeItem(props: { item: ResolvedCalendarAttendee }) {</>) : undefined;const details = attendee.comment ? (- <div class="line-clamp-2 select-text text-xxs italic text-ink-extra-muted">+ <div class="line-clamp-2 select-text text-xs italic text-ink-extra-muted sm:text-xxs">{attendee.comment}</div>) : undefined;@@ -210,29 +219,49 @@ function CalendarAttendeeItem(props: { item: ResolvedCalendarAttendee }) {secondaryLabel={secondaryLabel}details={details}trailing={trailing}+ nameClass={props.nameClass}/>);}-function CalendarAttendeeList(props: { attendees: CalendarAttendee[] }) {- const attendees = props.attendees.map(resolveCalendarAttendee);+export interface CalendarAttendeeListProps {+ attendees: CalendarAttendee[];+ organizerFirst?: boolean;+ itemClass?: (attendee: CalendarAttendee) => string | undefined;+ nameClass?: string;+}++/** Resolved attendee rows shared by event details and read-only guest views. */+export function CalendarAttendeeList(props: CalendarAttendeeListProps) {const sortedAttendees = createMemo(() =>- attendees+ props.attendees+ .map(resolveCalendarAttendee).map((item) => ({ item, name: item.displayName() }))- .toSorted(- (first, second) =>+ .toSorted((first, second) => {+ if (+ props.organizerFirst &&+ first.item.attendee.isOrganizer !== second.item.attendee.isOrganizer+ ) {+ return first.item.attendee.isOrganizer ? -1 : 1;+ }+ return (compareAttendeeNames(first.name, second.name) ||compareAttendeeNames(first.item.attendee.email,second.item.attendee.email)- )+ );+ }).map(({ item }) => item));return (<For each={sortedAttendees()}>- {(item) => <CalendarAttendeeItem item={item} />}+ {(item) => (+ <div class={cn(props.itemClass?.(item.attendee))}>+ <CalendarAttendeeItem item={item} nameClass={props.nameClass} />+ </div>+ )}</For>);}@@ -335,8 +364,8 @@ function EventRemindersItem(props: { event: CalendarEvent }) {return (<Show when={reminders().length > 0}>- <div class="-ml-7 flex items-start gap-3">- <BellSimpleIcon class="mt-0.5 size-4 shrink-0 text-ink-extra-muted" />+ <div class="contents">+ <BellSimpleIcon class="mt-0.5 size-5 text-ink-extra-muted sm:size-4" /><div class="flex select-text flex-col gap-0.5"><For each={reminders()}>{(reminder) => (@@ -376,9 +405,9 @@ function CalendarOrganizerItem(props: { organizer: CalendarOrganizer }) {: undefined;return (- <div class="-ml-7 flex min-w-0 items-center gap-3">- <PersonIcon class="size-4 shrink-0 text-ink-extra-muted" />- <div class="min-w-0 flex-1">+ <div class="contents">+ <PersonIcon class="size-5 self-center text-ink-extra-muted sm:size-4" />+ <div class="min-w-0"><CalendarUserItemdisplayName={displayName}iconProps={iconProps}@@ -438,92 +467,86 @@ export function EventDetails(props: {});return (- <div class="min-w-0 p-1 text-ink">- <div class="flex items-start gap-3">+ <div class="grid min-w-0 grid-cols-[1.25rem_minmax(0,1fr)] gap-x-4 gap-y-5 p-1 text-sm text-ink-muted sm:grid-cols-[1rem_minmax(0,1fr)] sm:gap-x-3 sm:gap-y-3 sm:text-xs">+ <span+ aria-hidden="true"+ class="mt-0.5 flex size-5 items-center justify-center sm:size-4"+ ><span- aria-hidden="true"- class="mt-0.5 flex size-4 shrink-0 items-center justify-center"- >- <span- class="size-2.5 rounded-sm"- style={{ 'background-color': props.event.calendar.color }}- />- </span>- <div class="min-w-0 flex-1">- <div class="flex flex-col gap-1 pr-8">- <div class="select-text text-base font-semibold leading-snug text-ink">- {props.event.title}- </div>- <div class="select-text text-xs text-ink-muted">- {formatEventSchedule(props.event, props.timeFormat)}+ class="size-4 rounded-sm sm:size-3"+ style={{ 'background-color': props.event.calendar.color }}+ />+ </span>+ <div class="flex min-w-0 flex-col gap-1">+ <div class="select-text text-lg font-semibold leading-snug text-ink sm:text-base">+ {props.event.title}+ </div>+ <div class="select-text text-sm text-ink-muted sm:text-xs">+ {formatEventSchedule(props.event, props.timeFormat)}+ </div>+ <Show when={recurrenceDescription()}>+ {(description) => (+ <div class="select-text text-sm text-ink-extra-muted sm:text-xs">+ {description()}</div>- <Show when={recurrenceDescription()}>- {(description) => (- <div class="select-text text-xs text-ink-extra-muted">- {description()}- </div>- )}- </Show>+ )}+ </Show>+ </div>++ <Show when={conferenceUrl()}>+ {(url) => (+ <div class="contents">+ <VideoCameraIcon class="size-5 self-center text-ink-extra-muted sm:size-4" />+ <Button+ fullWidth+ variant="cta"+ size="sm"+ class="h-8 rounded-lg [&_svg]:size-3.5!"+ label={conferenceLabel()}+ onClick={() => openExternalUrl(url())}+ >+ {conferenceLabel()}+ <ArrowSquareOutIcon />+ </Button></div>+ )}+ </Show>+ <Show when={originalTimeZone()}>+ {(timeZone) => (+ <div class="contents">+ <GlobeIcon class="mt-0.5 size-5 text-ink-extra-muted sm:size-4" />+ <span class="select-text">{timeZone()}</span>+ </div>+ )}+ </Show>- <div class="mt-5 flex flex-col gap-3 text-xs text-ink-muted">- <Show when={conferenceUrl()}>- {(url) => (- <div class="-ml-7 flex items-center gap-3">- <VideoCameraIcon class="size-4 shrink-0 text-ink-extra-muted" />- <Button- fullWidth- variant="cta"- size="sm"- class="h-8 rounded-lg"- label={conferenceLabel()}- onClick={() => openExternalUrl(url())}- >- {conferenceLabel()}- <ArrowSquareOutIcon class="size-3.5" />- </Button>- </div>- )}- </Show>- <Show when={originalTimeZone()}>- {(timeZone) => (- <div class="-ml-7 flex items-start gap-3">- <GlobeIcon class="mt-0.5 size-4 shrink-0 text-ink-extra-muted" />- <span class="select-text">{timeZone()}</span>- </div>- )}- </Show>-- <Show when={props.event.location}>- {(location) => (- <div class="-ml-7 flex items-start gap-3">- <MapPinIcon class="mt-0.5 size-4 shrink-0 text-ink-extra-muted" />- <span class="select-text">{location()}</span>- </div>- )}- </Show>-- <Show when={props.event.description}>- {(description) => (- <div class="-ml-7 flex items-start gap-3">- <TextAlignLeftIcon class="mt-0.5 size-4 shrink-0 text-ink-extra-muted" />- <p class="select-text leading-relaxed text-ink-muted">- {description()}- </p>- </div>- )}- </Show>-- <EventRemindersItem event={props.event} />-- <Show when={organizer()}>- {(eventOrganizer) => (- <CalendarOrganizerItem organizer={eventOrganizer()} />- )}- </Show>+ <Show when={props.event.location}>+ {(location) => (+ <div class="contents">+ <MapPinIcon class="mt-0.5 size-5 text-ink-extra-muted sm:size-4" />+ <span class="select-text">{location()}</span></div>- </div>- </div>+ )}+ </Show>++ <Show when={props.event.description}>+ {(description) => (+ <div class="contents">+ <TextAlignLeftIcon class="mt-0.5 size-5 text-ink-extra-muted sm:size-4" />+ <p class="select-text leading-relaxed text-ink-muted">+ {description()}+ </p>+ </div>+ )}+ </Show>++ <EventRemindersItem event={props.event} />++ <Show when={organizer()}>+ {(eventOrganizer) => (+ <CalendarOrganizerItem organizer={eventOrganizer()} />+ )}+ </Show></div>);}@@ -536,10 +559,10 @@ export function EventAttendeesSection(props: {<Show when={props.attendees.length > 0}><CollapsibledefaultOpen- class="border-edge-muted border-t text-xs text-ink-muted"+ class="border-edge-muted text-sm text-ink-muted sm:border-t sm:text-xs">- <Collapsible.Trigger class="group flex w-full items-center gap-3 px-4 py-4 text-left hover:bg-hover hover:text-ink">- <UsersIcon class="size-4 shrink-0 text-ink-extra-muted" />+ <Collapsible.Trigger class="group flex w-full items-center gap-4 px-4 py-4 text-left hover:bg-hover hover:text-ink sm:gap-3">+ <UsersIcon class="size-5 shrink-0 text-ink-extra-muted sm:size-4" /><span>{props.attendees.length}{' '}{plural('attendee', props.attendees.length)}@@ -550,8 +573,8 @@ export function EventAttendeesSection(props: {/></Collapsible.Trigger><Collapsible.Content class="data-closed:hidden">- <div class="flex gap-3 pb-3 pl-4 pt-1.5">- <span aria-hidden="true" class="size-4 shrink-0" />+ <div class="flex gap-4 pb-3 pl-4 pt-1.5 sm:gap-3">+ <span aria-hidden="true" class="size-5 shrink-0 sm:size-4" /><ScrollableAttendeeList attendees={props.attendees} /></div></Collapsible.Content>diff --git a/apps/web/src/features/calendar/events/EventDetailsPopover.tsx b/apps/web/src/features/calendar/events/EventDetailsPopover.tsxindex e1fa3d81b1..17974ba3f7 100644--- a/apps/web/src/features/calendar/events/EventDetailsPopover.tsx+++ b/apps/web/src/features/calendar/events/EventDetailsPopover.tsx@@ -1,4 +1,5 @@import { MobileDrawer } from '@components/app/mobile/MobileDrawer';+import { useSplitLayout } from '@components/app/split-layout/layout';import { toast } from '@core/component/Toast/Toast';import { isMobile } from '@core/mobile/isMobile';import { Popover } from '@kobalte/core/popover';@@ -11,7 +12,6 @@ import type { CalendarDeletionScope } from '@service-email/client';import { Button, Dialog, Layer, Panel } from '@ui';import { type Accessor, createMemo, createSignal, Show } from 'solid-js';import { EventAttendeesSection, EventDetails } from './EventDetails';-import { EventEditorDialog } from './EventEditorDialog';import { EventRsvpSection } from './EventRsvpSection';import type { CalendarEvent, CalendarTimeFormat } from './types';@@ -96,40 +96,98 @@ interface EventDetailsOverlayProps {}function EventDetailsDrawer(props: EventDetailsOverlayProps) {+ const { popoverSplit } = useSplitLayout();+ const [deleteOpen, setDeleteOpen] = createSignal(false);+ const canModify = () => !props.event.isReadOnly && !props.event.isCancelled;+ const openEditor = () => {+ popoverSplit({+ type: 'component',+ id: 'calendar-event-compose',+ params: { event: props.event },+ });+ props.onOpenChange(false);+ };+return (- <MobileDrawer- side="bottom"- open- onOpenChange={props.onOpenChange}- preventScroll={false}- preventScrollbarShift={false}- >- <MobileDrawer.Portal>- <MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />- <MobileDrawer.Content- aria-label={props.event.title}- class="overflow-hidden"- >- <MobileDrawer.Handle />- <div class="min-h-0 flex-1 overflow-y-auto">- <div class="px-3 pb-3">- <EventDetails event={props.event} timeFormat={props.timeFormat} />- </div>- <EventRsvpSection event={props.event} />- <EventAttendeesSection attendees={props.event.attendees} />- </div>- <MobileDrawer.Close- as={Button}- aria-label="Close event details"- variant="ghost"- size="icon-sm"- class="absolute right-2 top-2 rounded-full text-ink-muted"+ <>+ <MobileDrawer+ side="bottom"+ open+ onOpenChange={(open) => {+ if (!open && deleteOpen()) return;+ props.onOpenChange(open);+ }}+ preventScroll={false}+ preventScrollbarShift={false}+ >+ <MobileDrawer.Portal>+ <MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />+ <MobileDrawer.Content+ aria-label={props.event.title}+ class="overflow-hidden">- <CloseIcon class="size-3" />- </MobileDrawer.Close>- </MobileDrawer.Content>- </MobileDrawer.Portal>- </MobileDrawer>+ <MobileDrawer.Handle class="pointer-events-none absolute inset-x-0 top-0 z-1" />+ <div class="flex shrink-0 items-center justify-between px-2 pb-3 pt-2">+ <MobileDrawer.Close+ as={Button}+ aria-label="Close event details"+ variant="ghost"+ size="icon-md"+ depth={3}+ class="rounded-md text-ink-extra-muted [&_svg]:size-4"+ >+ <CloseIcon />+ </MobileDrawer.Close>+ <Show when={canModify()}>+ <div class="flex items-center gap-1">+ <Button+ aria-label="Edit event"+ variant="ghost"+ size="icon-md"+ depth={3}+ class="rounded-md text-ink-extra-muted [&_svg]:size-4"+ onClick={openEditor}+ >+ <PencilSimpleIcon />+ </Button>+ <Button+ aria-label="Delete event"+ variant="ghost"+ size="icon-md"+ depth={3}+ class="rounded-md text-ink-extra-muted [&_svg]:size-4"+ onClick={() => setDeleteOpen(true)}+ >+ <TrashIcon />+ </Button>+ </div>+ </Show>+ </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}+ />+ </div>+ <EventAttendeesSection attendees={props.event.attendees} />+ <EventRsvpSection event={props.event} buttonSize="md" />+ </div>+ </MobileDrawer.Content>+ </MobileDrawer.Portal>+ </MobileDrawer>+ <Show when={deleteOpen()}>+ <DeleteEventDialog+ open+ event={props.event}+ onClose={() => setDeleteOpen(false)}+ onDeleted={() => {+ setDeleteOpen(false);+ props.onOpenChange(false);+ }}+ />+ </Show>+ </>);}@@ -262,9 +320,17 @@ function DeleteEventDialog(props: {/** Anchors event details and actions to a rendered calendar event. */function EventDetailsPopover(props: EventDetailsPopoverProps) {+ const { popoverSplit } = useSplitLayout();const [deleteOpen, setDeleteOpen] = createSignal(false);- const [editorOpen, setEditorOpen] = createSignal(false);const canModify = () => !props.event.isReadOnly && !props.event.isCancelled;+ const openEditor = () => {+ popoverSplit({+ type: 'component',+ id: 'calendar-event-compose',+ params: { event: props.event },+ });+ props.onOpenChange(false);+ };return (<>@@ -272,9 +338,8 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {anchorRef={() => props.anchor}openonOpenChange={(open) => {- // Keep the popover mounted while one of its dialogs is up; the- // dialog's own close path decides what happens next.- if (!open && (deleteOpen() || editorOpen())) return;+ // Keep the popover mounted while its delete dialog is open.+ if (!open && deleteOpen()) return;props.onOpenChange(open);}}placement="right-start"@@ -285,7 +350,7 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {<Popover.Portal><Layer depth={3}><Popover.Content- class="z-modal max-w-[calc(100vw-2rem)] outline-none"+ class="portal-scope z-modal max-w-[calc(100vw-2rem)] outline-none"onInteractOutside={(event) => {// FullCalendar selects on click (pointer release), so dismissing on// pointer down would briefly close the popover before reopening it.@@ -314,37 +379,31 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {}}><Popover.Arrow class="fill-surface" />- <div class="relative w-fit min-w-[min(20rem,calc(100vw-2rem))] max-w-[min(24rem,calc(100vw-2rem))] overflow-hidden rounded-xl bg-surface text-ink shadow-menu ring ring-edge-muted">+ <div class="w-fit min-w-[min(20rem,calc(100vw-2rem))] max-w-[min(24rem,calc(100vw-2rem))] overflow-hidden rounded-xl bg-surface text-ink shadow-menu ring ring-edge-muted"><Popover.Title class="sr-only">{props.event.title}</Popover.Title>- <div class="p-3">- <EventDetails- event={props.event}- timeFormat={props.timeFormat}- />- </div>- <EventRsvpSection event={props.event} />- <EventAttendeesSection attendees={props.event.attendees} />- <div class="absolute right-2 top-2 flex items-center gap-0.5">+ <div class="flex items-center justify-end gap-1 px-2 pt-2"><Show when={canModify()}><Buttonaria-label="Edit event"variant="ghost"size="icon-sm"- class="rounded-md text-ink-muted"- onClick={() => setEditorOpen(true)}+ depth={3}+ class="rounded-md text-ink-muted [&_svg]:size-4"+ onClick={openEditor}>- <PencilSimpleIcon class="size-3" />+ <PencilSimpleIcon /></Button><Buttonaria-label="Delete event"variant="ghost"size="icon-sm"- class="rounded-md text-ink-muted"+ depth={3}+ class="rounded-md text-ink-muted [&_svg]:size-4"onClick={() => setDeleteOpen(true)}>- <TrashIcon class="size-3" />+ <TrashIcon /></Button></Show><Popover.CloseButton@@ -352,11 +411,22 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {aria-label="Close event details"variant="ghost"size="icon-sm"- class="rounded-md text-ink-muted"+ depth={3}+ class="rounded-md text-ink-muted [&_svg]:size-4">- <CloseIcon class="size-3" />+ <CloseIcon /></Popover.CloseButton></div>+ <div>+ <div class="px-3 pb-3">+ <EventDetails+ event={props.event}+ timeFormat={props.timeFormat}+ />+ </div>+ <EventAttendeesSection attendees={props.event.attendees} />+ <EventRsvpSection event={props.event} />+ </div></div></Popover.Content></Layer>@@ -373,13 +443,6 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {}}/></Show>- <Show when={editorOpen()}>- <EventEditorDialog- open- event={props.event}- onClose={() => setEditorOpen(false)}- />- </Show></>);}diff --git a/apps/web/src/features/calendar/events/EventEditorDialog.tsx b/apps/web/src/features/calendar/events/EventEditorDialog.tsxdeleted file mode 100644index ca0e487c9d..0000000000--- a/apps/web/src/features/calendar/events/EventEditorDialog.tsx+++ /dev/null@@ -1,832 +0,0 @@-import { toast } from '@core/component/Toast/Toast';-import BellSimpleIcon from '@phosphor/bell-simple.svg';-import SpinnerIcon from '@phosphor/spinner.svg';-import VideoCameraIcon from '@phosphor/video-camera.svg';-import XIcon from '@phosphor/x.svg';-import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';-import {- useCreateCalendarEventMutation,- useUpdateCalendarEventMutation,-} from '@queries/calendar/mutations';-import type { EventTime } from '@service-email/generated/schemas/eventTime';-import { Button, Dialog, Panel, ToggleSwitch } from '@ui';-import {- addDays,- addHours,- addMonths,- format,- isMatch,- parseISO,- startOfHour,-} from 'date-fns';-import { createMemo, createSignal, For, Show } from 'solid-js';-import { calendarDisplayLabel, spansMultipleInboxes } from '../calendar-label';-import {- buildReminderOverrides,- formatReminderOffset,- popupMinutes,- REMINDER_METHOD_POPUP,- REMINDER_OVERRIDES_MAX,- REMINDER_PRESET_MINUTES,-} from './event-reminders';-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 isDateOnly = (value: string) => isMatch(value, DATE_VALUE);--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) };-}--interface EditorState {- 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;- location: string;- description: string;- guests: string;- /** What conferencing the saved event should carry. */- conference: ConferenceChoice;-}--/**- * `existing` keeps a conference Macro did not create — a Zoom-style `addOn`- * conference or a legacy Hangout. Macro can detach or replace it on request,- * but cannot put one back, so leaving the editor without touching it must- * submit no conference change at all.- */-type ConferenceChoice = 'none' | 'google_meet' | 'existing';--function initialConference(event: CalendarEvent | undefined): ConferenceChoice {- if (!event?.conferenceUrl) return 'none';- return event.conferenceProvider === 'google_meet'- ? 'google_meet'- : 'existing';-}--/** Label for a conference Macro did not create, taken from its join URL. */-function foreignConferenceLabel(url: string | undefined) {- if (!url) return 'Video conferencing';- try {- return new URL(url).hostname.replace(/^www\./, '');- } catch {- return 'Video conferencing';- }-}--function initialEditorState(event: CalendarEvent | undefined): EditorState {- if (!event) {- const { start, end } = defaultEditorTimes(new Date());- return {- title: '',- allDay: false,- start: format(start, DATETIME_VALUE),- end: format(end, DATETIME_VALUE),- location: '',- description: '',- guests: '',- conference: 'none',- };- }- 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),- location: event.location ?? '',- description: event.description ?? '',- guests: '',- conference: initialConference(event),- };- }- return {- title: event.title,- allDay: false,- start: format(new Date(event.start), DATETIME_VALUE),- end: format(new Date(event.end), DATETIME_VALUE),- location: event.location ?? '',- description: event.description ?? '',- guests: '',- conference: initialConference(event),- };-}--function buildEventTime(state: EditorState): 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 !== ''))];-}--/** Both editor times switch representation when all-day toggles. */-function convertTimesForAllDay(state: EditorState, 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),- };-}--/**- * Create/edit form for a calendar event. Editing a recurring event changes- * the entire series; guests can only be invited at creation, because a- * patch replaces the whole attendee list and would reset RSVPs.- */-export function EventEditorDialog(props: {- open: boolean;- /** Present when editing; absent when creating. */- event?: CalendarEvent;- onClose: () => void;-}) {- const [state, setState] = createSignal(initialEditorState(props.event));- const isEdit = () => props.event !== undefined;- const [calendarId, setCalendarId] = createSignal<string>();- // Enabled while editing too: reminder rows resolve the calendar's default- // reminders for events that follow them.- const calendarsQuery = useVisibleCalendarsQuery();- const writableCalendars = createMemo(- () => calendarsQuery.data?.filter((calendar) => calendar.isWritable) ?? []- );- // The select displays the first writable calendar until touched, so submit- // must resolve the same fallback rather than let the server pick its own.- const effectiveCalendarId = () => calendarId() ?? writableCalendars()[0]?.id;- const spansInboxes = createMemo(() =>- spansMultipleInboxes(writableCalendars())- );- const calendarLabel = (calendar: {- name: string;- emailAddress: string;- isPrimary: boolean;- }) => calendarDisplayLabel(calendar, spansInboxes());-- const initialLines = props.event?.recurrenceLines ?? [];- const initialConfig =- initialLines.length > 0 ? parseRecurrenceConfig(initialLines) : undefined;- const hasUnrepresentableRule = initialLines.length > 0 && !initialConfig;- const startForRecurrence = createMemo(() => {- const start = state().start;- const parsed = 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 preset = recurrencePresetsFor(- props.event?.allDay- ? parseISO(props.event.start)- : new Date(props.event?.start ?? Date.now())- ).find((candidate) =>- recurrenceConfigsEqual(candidate.config, initialConfig)- );- return preset?.id ?? 'custom';- };- const [recurrenceChoice, setRecurrenceChoice] = createSignal(initialChoice());- const [customConfig, setCustomConfig] = createSignal<RecurrenceConfig>(- initialConfig ?? defaultCustomConfig(startForRecurrence())- );- 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;- });- /** `undefined` leaves the stored rule untouched. */- const recurrenceLines = (): string[] | undefined => {- const choice = recurrenceChoice();- if (choice === 'existing') return undefined;- if (choice === 'none') return [];- if (choice === 'custom') {- return buildRecurrenceLines(customConfig(), state().allDay);- }- const preset = presets().find((candidate) => candidate.id === choice);- return preset- ? buildRecurrenceLines(preset.config, state().allDay)- : undefined;- };- 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 isRecurring = () =>- (props.event?.recurrenceLines.length ?? 0) > 0 ||- props.event?.recurrenceId !== undefined;-- // Popup reminder offsets. `undefined` means untouched: the rows display- // the resolved configuration (the event's overrides, else its calendar's- // defaults) and the save omits reminders entirely, so an event following- // its calendar defaults keeps following them.- const [reminderEdits, setReminderEdits] = createSignal<number[]>();- const defaultReminderMinutes = createMemo(() => {- const forCalendar = isEdit()- ? props.event?.calendarId- : effectiveCalendarId();- const calendar = calendarsQuery.data?.find(- (candidate) => candidate.id === forCalendar- );- return popupMinutes(calendar?.defaultReminders);- });- const reminderMinutes = createMemo(() => {- const edits = reminderEdits();- if (edits) return edits;- const reminders = props.event?.reminders;- if (reminders && !reminders.useDefault) {- return popupMinutes(reminders.overrides);- }- return defaultReminderMinutes();- });- const reminderOptions = (current: number) =>- [...new Set([...REMINDER_PRESET_MINUTES, current])].sort((a, b) => a - b);- // Non-popup overrides (e.g. Google email reminders) are preserved by the- // save, so they occupy override slots the popup rows can't use.- const preservedReminderCount = createMemo(() => {- const reminders = props.event?.reminders;- if (!reminders || reminders.useDefault) return 0;- return (reminders.overrides ?? []).filter(- (reminder) => reminder.method !== REMINDER_METHOD_POPUP- ).length;- });- const addReminder = () => {- const existing = reminderMinutes();- const next =- REMINDER_PRESET_MINUTES.find((minutes) => !existing.includes(minutes)) ??- 10;- setReminderEdits([...existing, next]);- };- const setReminderAt = (index: number, minutes: number) => {- setReminderEdits(- reminderMinutes().map((value, i) => (i === index ? minutes : value))- );- };- const removeReminderAt = (index: number) => {- setReminderEdits(reminderMinutes().filter((_, i) => i !== index));- };-- const invalidGuests = createMemo(() =>- parseGuestEmails(state().guests).filter((email) => !email.includes('@'))- );- const eventTime = createMemo(() => buildEventTime(state()));- const canSave = () =>- eventTime() !== undefined && invalidGuests().length === 0 && customValid();-- const create = useCreateCalendarEventMutation({- onSuccess: () => props.onClose(),- onError: (error) => {- toast.failure('Failed to create event', { subtext: error.message });- },- });- const update = useUpdateCalendarEventMutation({- onSuccess: () => props.onClose(),- onError: (error) => {- toast.failure('Failed to update event', { subtext: error.message });- },- });- const pending = () => create.isPending || update.isPending;-- const save = () => {- const time = eventTime();- if (!time || pending()) return;-- const current = state();- const event = props.event;- const lines = recurrenceLines();- const edits = reminderEdits();- const reminders =- edits === undefined- ? undefined- : buildReminderOverrides(edits, event?.reminders);- if (event) {- const recurrenceChanged =- lines !== undefined && lines.join('\n') !== initialLines.join('\n');- // Omitting `conference` leaves the provider's conference untouched, so- // an unrelated edit never regenerates or drops a working join link.- // `existing` is therefore never submitted: it means "left alone".- const conferenceChanged =- current.conference !== 'existing' &&- current.conference !== initialConference(event);- update.mutate({- eventId: event.eventId,- patch: {- title: current.title,- time,- location: current.location,- description: current.description,- ...(recurrenceChanged ? { recurrenceLines: lines } : {}),- ...(reminders ? { reminders } : {}),- ...(conferenceChanged- ? {- conference:- current.conference === 'google_meet' ? 'google_meet' : 'none',- }- : {}),- },- });- return;- }- create.mutate({- title: current.title,- time,- calendarId: effectiveCalendarId(),- recurrenceLines: lines ?? [],- location: current.location === '' ? undefined : current.location,- description: current.description === '' ? undefined : current.description,- attendees: parseGuestEmails(current.guests).map((email) => ({ email })),- reminders,- ...(current.conference === 'google_meet'- ? { conference: 'google_meet' as const }- : {}),- });- };-- return (- <Dialog- open={props.open}- onOpenChange={(open) => !open && !pending() && props.onClose()}- >- <Panel- depth={2}- class="w-[26rem] max-w-[calc(100vw-2rem)] rounded-xl text-ink"- >- <Panel.Header class="gap-1 px-2">- <Dialog.CloseButton- as={Button}- variant="ghost"- size="icon-sm"- disabled={pending()}- >- <XIcon />- </Dialog.CloseButton>- <Dialog.Title as="span" class="m-0 p-0 text-sm font-medium">- {isEdit() ? 'Edit event' : 'New event'}- </Dialog.Title>- </Panel.Header>- <Panel.Body class="flex flex-col gap-3 p-3">- <input- type="text"- value={state().title}- onInput={(e) =>- setState({ ...state(), title: e.currentTarget.value })- }- placeholder="Add title"- class="settings-input w-full"- />- <div class="flex items-center justify-between gap-2 text-xs text-ink-muted">- <ToggleSwitch- label="All day"- checked={state().allDay}- onChange={(allDay) =>- setState(convertTimesForAllDay(state(), allDay))- }- />- <Show when={isRecurring()}>- <span class="text-ink-extra-muted">- Changes apply to all occurrences- </span>- </Show>- </div>- <div class="flex items-center gap-2">- <input- type={state().allDay ? 'date' : 'datetime-local'}- value={state().start}- onInput={(e) =>- setState({ ...state(), start: e.currentTarget.value })- }- aria-label="Start"- class="settings-input min-w-0 flex-1"- />- <span class="shrink-0 text-xs text-ink-extra-muted">to</span>- <input- type={state().allDay ? 'date' : 'datetime-local'}- value={state().end}- onInput={(e) =>- setState({ ...state(), end: e.currentTarget.value })- }- aria-label="End"- class="settings-input min-w-0 flex-1"- />- </div>- <div class="flex flex-col gap-2">- <select- value={recurrenceChoice()}- onChange={(e) => {- const choice = e.currentTarget.value;- if (choice === 'custom') {- const seed =- presets().find((preset) => preset.id === recurrenceChoice())- ?.config ??- initialConfig ??- defaultCustomConfig(startForRecurrence());- setCustomConfig(seed);- }- setRecurrenceChoice(choice);- }}- aria-label="Repeats"- class="settings-input w-full"- >- <option value="none">Does not repeat</option>- <For each={presets()}>- {(preset) => <option value={preset.id}>{preset.label}</option>}- </For>- <Show when={hasUnrepresentableRule}>- <option value="existing">- {`Custom: ${- formatRecurrenceDescription(initialLines) ?? 'existing rule'- } (unchanged)`}- </option>- </Show>- <option value="custom">Custom…</option>- </select>- <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={(e) =>- setCustomConfig((config) => ({- ...config,- interval: e.currentTarget.valueAsNumber,- }))- }- aria-label="Repeat interval"- class="settings-input w-16"- />- <select- value={customConfig().frequency}- onChange={(e) =>- setCustomConfig((config) => ({- ...config,- frequency: e.currentTarget- .value as RecurrenceConfig['frequency'],- }))- }- aria-label="Repeat unit"- class="settings-input"- >- <option value="DAILY">day</option>- <option value="WEEKLY">week</option>- <option value="MONTHLY">month</option>- <option value="YEARLY">year</option>- </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- variant={- customConfig().byDay.includes(code)- ? 'active'- : 'ghost'- }- size="icon-sm"- class="rounded-full text-xxs"- aria-label={code}- aria-pressed={customConfig().byDay.includes(code)}- 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="recurrence-ends"- checked={customConfig().ends.kind === 'never'}- onChange={() => setEnds({ kind: 'never' })}- />- Never- </label>- <label class="flex items-center gap-2">- <input- type="radio"- name="recurrence-ends"- checked={customConfig().ends.kind === 'on'}- onChange={() =>- setEnds({- kind: 'on',- date: format(- addMonths(startForRecurrence(), 3),- 'yyyy-MM-dd'- ),- })- }- />- On- <Show when={customConfig().ends.kind === 'on'}>- <input- type="date"- value={- customConfig().ends.kind === 'on'- ? (- customConfig().ends as {- kind: 'on';- date: string;- }- ).date- : ''- }- onInput={(e) =>- setEnds({ kind: 'on', date: e.currentTarget.value })- }- aria-label="Ends on date"- class="settings-input"- />- </Show>- </label>- <label class="flex items-center gap-2">- <input- type="radio"- name="recurrence-ends"- checked={customConfig().ends.kind === 'after'}- onChange={() => setEnds({ kind: 'after', count: 13 })}- />- After- <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={(e) =>- setEnds({- kind: 'after',- count: e.currentTarget.valueAsNumber,- })- }- aria-label="Ends after occurrences"- class="settings-input w-20"- />- occurrences- </Show>- </label>- </div>- </div>- </Show>- </div>- <Show when={!isEdit() && writableCalendars().length > 1}>- <select- value={effectiveCalendarId()}- onChange={(e) => setCalendarId(e.currentTarget.value)}- aria-label="Calendar"- class="settings-input w-full"- >- <For each={writableCalendars()}>- {(calendar) => (- <option value={calendar.id}>{calendarLabel(calendar)}</option>- )}- </For>- </select>- </Show>- <Show when={!isEdit()}>- <div class="flex flex-col gap-1">- <input- type="text"- value={state().guests}- onInput={(e) =>- setState({ ...state(), guests: e.currentTarget.value })- }- placeholder="Add guests (comma-separated emails)"- class="settings-input w-full"- aria-invalid={invalidGuests().length > 0}- />- <Show when={invalidGuests().length > 0}>- <span class="text-xs text-failure">- Invalid email: {invalidGuests().join(', ')}- </span>- </Show>- </div>- </Show>- <div class="flex flex-col gap-2">- <Show when={state().conference !== 'none'}>- <div class="flex items-center gap-2 rounded-lg bg-surface px-2 py-1.5 text-xs text-ink">- <VideoCameraIcon class="size-4 shrink-0 text-ink-extra-muted" />- <span class="flex-1 truncate">- {state().conference === 'google_meet'- ? 'Google Meet'- : foreignConferenceLabel(props.event?.conferenceUrl)}- </span>- <Button- variant="ghost"- size="icon-sm"- label="Remove conferencing"- onClick={() => setState({ ...state(), conference: 'none' })}- >- <XIcon />- </Button>- </div>- </Show>- <Show when={state().conference !== 'google_meet'}>- <Button- variant="base"- size="sm"- class="w-full justify-center rounded-lg"- label="Add Google Meet video conferencing"- onClick={() =>- setState({ ...state(), conference: 'google_meet' })- }- >- <VideoCameraIcon class="size-4 shrink-0" />- <span>Add Google Meet</span>- </Button>- </Show>- <Show when={state().conference === 'existing'}>- <span class="text-xs text-ink-extra-muted">- Adding Google Meet replaces the current conferencing, which- Macro cannot put back.- </span>- </Show>- </div>- <input- type="text"- value={state().location}- onInput={(e) =>- setState({ ...state(), location: e.currentTarget.value })- }- placeholder="Add location"- class="settings-input w-full"- />- <div class="flex flex-col gap-2">- <For each={reminderMinutes()}>- {(minutes, index) => (- <div class="flex items-center gap-2">- <BellSimpleIcon class="size-4 shrink-0 text-ink-extra-muted" />- <select- value={String(minutes)}- onChange={(e) =>- setReminderAt(index(), Number(e.currentTarget.value))- }- aria-label="Notification time"- class="settings-input min-w-0 flex-1"- >- <For each={reminderOptions(minutes)}>- {(option) => (- <option value={String(option)}>- {formatReminderOffset(option)}- </option>- )}- </For>- </select>- <Button- variant="ghost"- size="icon-sm"- aria-label="Remove notification"- onClick={() => removeReminderAt(index())}- >- <XIcon />- </Button>- </div>- )}- </For>- <Show- when={- reminderMinutes().length + preservedReminderCount() <- REMINDER_OVERRIDES_MAX- }- >- <Button- variant="ghost"- size="sm"- class="self-start rounded-lg text-xs text-ink-muted"- label="Add notification"- onClick={addReminder}- >- <BellSimpleIcon class="size-4" />- Add notification- </Button>- </Show>- </div>- <textarea- value={state().description}- onInput={(e) =>- setState({ ...state(), description: e.currentTarget.value })- }- placeholder="Add description"- rows={3}- class="settings-input min-h-20 w-full resize-y py-2"- />- <div class="flex justify-end gap-1 pt-1">- <Button- variant="ghost"- class="rounded-lg"- disabled={pending()}- label="Cancel"- onClick={props.onClose}- >- Cancel- </Button>- <Button- variant="cta"- class="rounded-lg"- disabled={!canSave() || pending()}- label="Save"- onClick={save}- >- <Show when={pending()} fallback="Save">- <SpinnerIcon class="size-4 animate-spin" />- </Show>- </Button>- </div>- </Panel.Body>- </Panel>- </Dialog>- );-}diff --git a/apps/web/src/features/calendar/events/EventEditorForm.tsx b/apps/web/src/features/calendar/events/EventEditorForm.tsxnew file mode 100644index 0000000000..7da77a525a--- /dev/null+++ b/apps/web/src/features/calendar/events/EventEditorForm.tsx@@ -0,0 +1,1001 @@+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}+ label="Cancel"+ onClick={props.onCancel}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ variant="cta"+ class="rounded-lg"+ disabled={!canSave() || props.pending}+ 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/EventRsvpSection.tsx b/apps/web/src/features/calendar/events/EventRsvpSection.tsxindex 8e09bf843b..4a41b99ebb 100644--- a/apps/web/src/features/calendar/events/EventRsvpSection.tsx+++ b/apps/web/src/features/calendar/events/EventRsvpSection.tsx@@ -4,7 +4,7 @@ import { useRsvpCalendarEventMutation } from '@queries/calendar/mutations';import type { CalendarRsvpScope } from '@service-email/client';import type { AttendeeResponseStatus } from '@service-storage/generated/schemas/attendeeResponseStatus';import { Button, Dialog, Panel } from '@ui';-import { createSignal, For, Show } from 'solid-js';+import { createMemo, createSignal, For, Show } from 'solid-js';import type { CalendarEvent } from './types';type RsvpResponse = Exclude<AttendeeResponseStatus, 'needs_action'>;@@ -35,9 +35,13 @@ const SCOPE_OPTIONS = [* "this and following" option: the provider API cannot express a forward* response, so it would silently expire past the synced window.*/-export function EventRsvpSection(props: { event: CalendarEvent }) {- const selfAttendee = () =>- props.event.attendees.find((attendee) => attendee.isSelf);+export function EventRsvpSection(props: {+ event: CalendarEvent;+ buttonSize?: 'sm' | 'md';+}) {+ const selfAttendee = createMemo(() =>+ props.event.attendees.find((attendee) => attendee.isSelf)+ );const isRecurring = () =>props.event.recurrenceLines.length > 0 ||props.event.recurrenceId !== undefined;@@ -91,19 +95,20 @@ export function EventRsvpSection(props: { event: CalendarEvent }) {return (<Show when={canRespond()}>- <div class="border-edge-muted flex items-center gap-3 border-t px-4 py-2.5 text-xs text-ink-muted">+ <div class="border-edge-muted flex items-center gap-3 border-t bg-active px-4 py-2.5 text-sm text-ink-muted sm:text-xs"><span>Going?</span>- <div class="ml-auto flex shrink-0 gap-1">+ <div class="ml-auto flex shrink-0 gap-3 lg:gap-2"><For each={RSVP_OPTIONS}>{(option) => (<Buttonvariant={selfAttendee()?.responseStatus === option.response? 'active'- : 'ghost'+ : 'base'}- size="sm"- class="rounded-lg px-2.5"+ size={props.buttonSize ?? 'sm'}+ depth={3}+ class="rounded-lg px-3"label={option.label}onClick={() => respond(option.response)}>diff --git a/apps/web/src/features/calendar/events/RecurrenceBuilder.tsx b/apps/web/src/features/calendar/events/RecurrenceBuilder.tsxnew file mode 100644index 0000000000..6b4932540d--- /dev/null+++ b/apps/web/src/features/calendar/events/RecurrenceBuilder.tsx@@ -0,0 +1,267 @@+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,+ type RecurrenceConfig,+ type RecurrenceFrequency,+ WEEKDAY_CODES,+ type WeekdayCode,+} from './recurrence-editor';++const DATE_VALUE = 'yyyy-MM-dd';++type FrequencyOption = {+ value: RecurrenceFrequency;+ label: string;+};++const FREQUENCY_OPTIONS: FrequencyOption[] = [+ { value: 'DAILY', label: 'day' },+ { value: 'WEEKLY', label: 'week' },+ { value: 'MONTHLY', label: 'month' },+ { 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;+}++/** Builds an RFC 5545 recurrence rule from individually editable parts. */+export function RecurrenceBuilder(props: RecurrenceBuilderProps) {+ const selectedFrequency = createMemo(+ () =>+ FREQUENCY_OPTIONS.find(+ (option) => option.value === props.value.frequency+ ) ?? FREQUENCY_OPTIONS[0]+ );+ const fallbackEndDate = () => format(addMonths(props.start, 3), DATE_VALUE);+ const recurrenceDescription = createMemo(+ () =>+ formatRecurrenceDescription(+ buildRecurrenceLines(props.value, props.allDay)+ ) ?? '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 });+ const setEnds = (ends: RecurrenceConfig['ends']) => patchConfig({ ends });+ const toggleWeekday = (code: WeekdayCode) =>+ patchConfig({+ byDay: props.value.byDay.includes(code)+ ? props.value.byDay.filter((day) => day !== code)+ : [...props.value.byDay, code],+ });+ const changeEndsKind = (kind: string) => {+ if (props.disabled) return;+ switch (kind) {+ case 'never':+ setEnds({ kind: 'never' });+ return;+ case 'on':+ setEnds({+ kind: 'on',+ date:+ props.value.ends.kind === 'on'+ ? props.value.ends.date+ : fallbackEndDate(),+ });+ return;+ case 'after':+ setEnds({+ kind: 'after',+ count:+ props.value.ends.kind === 'after' ? props.value.ends.count : 13,+ });+ }+ };++ return (+ <div class="flex flex-col gap-4 text-xs text-ink-muted">+ <p class="text-sm font-medium text-ink">{recurrenceDescription()}</p>++ <div class="flex flex-wrap items-start gap-4">+ <div class="flex flex-col gap-2">+ <span class="text-ink-extra-muted">Repeat every</span>+ <div class="flex min-w-0 flex-wrap items-center gap-2">+ <input+ type="number"+ min="1"+ value={props.value.interval}+ onInput={(event) =>+ patchConfig({ interval: event.currentTarget.valueAsNumber })+ }+ aria-label="Repeat interval"+ class="settings-input h-7 w-16"+ disabled={props.disabled}+ />+ <Select<FrequencyOption>+ options={FREQUENCY_OPTIONS}+ value={selectedFrequency()}+ onChange={(option) =>+ option && patchConfig({ frequency: option.value })+ }+ optionValue="value"+ optionTextValue="label"+ disabled={props.disabled}+ >+ <Select.Trigger+ aria-label="Repeat unit"+ class="settings-input h-7 w-28"+ >+ <Select.Value<FrequencyOption>>+ {(selectState) => selectState.selectedOption().label}+ </Select.Value>+ <Select.Icon />+ </Select.Trigger>+ <Select.Content>+ <Select.Listbox />+ </Select.Content>+ </Select>+ </div>+ </div>++ <Show when={props.value.frequency === 'WEEKLY'}>+ <div class="flex flex-col gap-2">+ <span class="text-ink-extra-muted">Repeat on</span>+ <div class="flex flex-wrap items-center gap-1.5">+ <For each={WEEKDAY_CODES}>+ {(code) => (+ <Button+ type="button"+ variant={+ props.value.byDay.includes(code) ? 'active' : 'ghost'+ }+ size="icon-sm"+ class="rounded-full text-xxs"+ aria-label={code}+ aria-pressed={props.value.byDay.includes(code)}+ disabled={props.disabled}+ onClick={() => toggleWeekday(code)}+ >+ {code[0]}+ </Button>+ )}+ </For>+ </div>+ </div>+ </Show>+ </div>++ <div class="flex flex-col gap-2">+ <span class="text-ink-extra-muted">Ends</span>+ <RadioGroup+ value={props.value.ends.kind}+ onChange={changeEndsKind}+ disabled={props.disabled}+ aria-label="Recurrence ends"+ class="grid min-w-0 grid-cols-3 gap-2"+ >+ <RadioGroup.Item+ value="never"+ class="min-w-0 rounded-lg border border-edge-muted bg-surface p-3 data-checked:border-accent data-checked:bg-accent-bg/40"+ onClick={() => changeEndsKind('never')}+ >+ <div class="flex flex-wrap items-center gap-2">+ <RadioGroup.ItemInput />+ <RadioGroup.ItemControl class="flex size-4 shrink-0 items-center justify-center rounded-full border border-edge data-checked:border-accent">+ <RadioGroup.ItemIndicator class="size-2 rounded-full bg-accent" />+ </RadioGroup.ItemControl>+ <RadioGroup.ItemLabel class="shrink-0 font-medium text-ink">+ Never+ </RadioGroup.ItemLabel>+ <span class="text-ink-extra-muted">+ The event repeats indefinitely.+ </span>+ </div>+ </RadioGroup.Item>++ <RadioGroup.Item+ value="on"+ class="min-w-0 rounded-lg border border-edge-muted bg-surface p-3 data-checked:border-accent data-checked:bg-accent-bg/40"+ onClick={() => changeEndsKind('on')}+ >+ <div class="flex min-w-0 flex-wrap items-center gap-2">+ <RadioGroup.ItemInput />+ <RadioGroup.ItemControl class="flex size-4 shrink-0 items-center justify-center rounded-full border border-edge data-checked:border-accent">+ <RadioGroup.ItemIndicator class="size-2 rounded-full bg-accent" />+ </RadioGroup.ItemControl>+ <RadioGroup.ItemLabel class="shrink-0 font-medium text-ink">+ On+ </RadioGroup.ItemLabel>+ <EventDateField+ label="Ends on"+ value={+ props.value.ends.kind === 'on'+ ? props.value.ends.date+ : fallbackEndDate()+ }+ onChange={(date) => setEnds({ kind: 'on', date })}+ disabled={props.disabled}+ portalScope="local"+ appearance="bare"+ class="min-h-7 rounded-lg px-2 hover:bg-hover"+ />+ </div>+ </RadioGroup.Item>++ <RadioGroup.Item+ value="after"+ class="min-w-0 rounded-lg border border-edge-muted bg-surface p-3 data-checked:border-accent data-checked:bg-accent-bg/40"+ onClick={() => changeEndsKind('after')}+ >+ <div class="flex flex-wrap items-center gap-2">+ <RadioGroup.ItemInput />+ <RadioGroup.ItemControl class="flex size-4 shrink-0 items-center justify-center rounded-full border border-edge data-checked:border-accent">+ <RadioGroup.ItemIndicator class="size-2 rounded-full bg-accent" />+ </RadioGroup.ItemControl>+ <RadioGroup.ItemLabel class="shrink-0 font-medium text-ink">+ After+ </RadioGroup.ItemLabel>+ <input+ type="number"+ min="1"+ value={+ props.value.ends.kind === 'after'+ ? props.value.ends.count+ : 13+ }+ onInput={(event) =>+ setEnds({+ kind: 'after',+ count: event.currentTarget.valueAsNumber,+ })+ }+ aria-label="Ends after occurrences"+ class="settings-input h-7 w-14"+ disabled={props.disabled}+ />+ <span>occurrences</span>+ </div>+ </RadioGroup.Item>+ </RadioGroup>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/calendar/events/event-mapper.ts b/apps/web/src/features/calendar/events/event-mapper.tsindex 7db89106b4..5e2b029eca 100644--- a/apps/web/src/features/calendar/events/event-mapper.ts+++ b/apps/web/src/features/calendar/events/event-mapper.ts@@ -5,17 +5,12 @@ import type { CalendarEvent } from './types';export function mapCalendarEventToFullCalendar(event: CalendarEvent): EventInput {- const eventBackground = `color-mix(in oklch, ${event.calendar.color} 5%, var(--color-surface))`;-return {id: event.id,title: event.title,start: event.start,end: event.end,allDay: event.allDay,- backgroundColor: eventBackground,- borderColor: event.calendar.color,- textColor: event.calendar.color,display: 'block',extendedProps: {calendarEventId: event.id,diff --git a/apps/web/src/features/calendar/events/useEventEditor.ts b/apps/web/src/features/calendar/events/useEventEditor.tsnew file mode 100644index 0000000000..011d722629--- /dev/null+++ b/apps/web/src/features/calendar/events/useEventEditor.ts@@ -0,0 +1,137 @@+import { toast } from '@core/component/Toast/Toast';+import { recipientEntityMapper, useContacts } from '@core/user';+import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';+import {+ useCreateCalendarEventMutation,+ 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';++const EDIT_DISABLED_FIELDS = {+ calendar: true,+ guests: true,+} satisfies EventEditorDisabledFields;++interface UseEventEditorProps {+ event: Accessor<CalendarEvent | undefined>;+ onSaved: () => void;+}++/** Shared create/edit query and mutation orchestration for any editor shell. */+export function useEventEditor(props: UseEventEditorProps) {+ const isEdit = () => props.event() !== undefined;+ const initialValues = createMemo(() => {+ const event = props.event();+ return event ? calendarEventToEditorInitialValues(event) : undefined;+ });+ const initialLines = createMemo(() => props.event()?.recurrenceLines ?? []);++ const calendarsQuery = useVisibleCalendarsQuery(() => ({+ enabled: !isEdit(),+ }));+ const contacts = useContacts();++ const guestOptions = createMemo(() =>+ contacts().map(recipientEntityMapper('user'))+ );+ const writableCalendars = createMemo(+ () => calendarsQuery.data?.filter((calendar) => calendar.isWritable) ?? []+ );+ const spansInboxes = createMemo(() =>+ spansMultipleInboxes(writableCalendars())+ );+ const calendarOptions = createMemo(() => {+ const event = props.event();+ if (event) {+ return [+ {+ id: event.calendar.id,+ label: event.calendar.name || 'Calendar',+ color: event.calendar.color,+ },+ ];+ }++ return writableCalendars().map((calendar) => ({+ id: calendar.id,+ label: calendarDisplayLabel(calendar, spansInboxes()),+ color: calendar.color ?? DEFAULT_CALENDAR_SOURCE.color,+ }));+ });++ const create = useCreateCalendarEventMutation({+ onSuccess: props.onSaved,+ onError: (error) => {+ toast.failure('Failed to create event', { subtext: error.message });+ },+ });+ const update = useUpdateCalendarEventMutation({+ onSuccess: props.onSaved,+ onError: (error) => {+ toast.failure('Failed to update event', { subtext: error.message });+ },+ });++ const pending = () => create.isPending || update.isPending;++ const save = (values: EventEditorSubmitValues) => {+ if (pending()) return;++ const event = props.event();+ if (event) {+ const recurrenceChanged =+ values.recurrenceLines !== undefined &&+ values.recurrenceLines.join('\n') !== initialLines().join('\n');++ update.mutate({+ eventId: event.eventId,+ patch: {+ title: values.title,+ time: values.time,+ location: values.location,+ description: values.description,+ ...(recurrenceChanged+ ? { recurrenceLines: values.recurrenceLines }+ : {}),+ },+ });+ return;+ }++ create.mutate({+ title: values.title,+ time: values.time,+ calendarId: values.calendarId,+ recurrenceLines: values.recurrenceLines ?? [],+ location: values.location === '' ? undefined : values.location,+ description: values.description === '' ? undefined : values.description,+ attendees: values.guestEmails.map((email) => ({ email })),+ });+ };++ const showRecurringEditNotice = () =>+ isEdit() &&+ ((props.event()?.recurrenceLines.length ?? 0) > 0 ||+ props.event()?.recurrenceId !== undefined);+ const disabledFields = createMemo(() =>+ isEdit() ? EDIT_DISABLED_FIELDS : undefined+ );++ return {+ initialValues,+ disabledFields,+ calendarOptions,+ guestOptions,+ showRecurringEditNotice,+ pending,+ save,+ };+}