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
feat(mobile): rebuild the touch event sheet and add picker sheets (#9157)
Peter Chinman73dfd23caaf7
diff --git a/.agents/rules/web/mobile.md b/.agents/rules/web/mobile.mdindex 7979a47472..771c9e59a2 100644--- a/.agents/rules/web/mobile.md+++ b/.agents/rules/web/mobile.md@@ -56,6 +56,23 @@ read their code, and follow that pattern rather than inventing a new one.- Phone drawers have a handle and no X; drag, backdrop, or Escape dismiss,and focus returns to the opener. No submenus at phone width: drill inplace with a back row.+- Actions that must stay in reach while a sheet scrolls sit in its pinned+ chrome between the handle and `MobileDrawer.ScrollBody`, never in a sticky+ band inside the scroll. A touch popover split exposes that slot as+ `drawerHeader` on its panel context; see `MobileEventForm`. Content that+ grows to fill its sheet (a composer's description) calls `fillDrawer` from+ that context to open at a fixed height; see `MobileTaskComposer`.+- Pick people, projects, tags, or other searchable lists from a touch sheet+ with `PickerSheet` (`components/app/mobile`), not a dropdown: a full-height+ sheet stacked over the current one with Cancel, a title, and Done, and no+ handle or drag. Create the draft or picker session inside it so each opening+ starts fresh, apply it only on Done, let the list fill `PickerSheet.Body`,+ and cancel `pointerdown` and `mousedown` on the rows so the search field+ keeps the keyboard. It hands focus back to the field that had it when it+ opened, so its opener cancels `pointerdown` and `mousedown` too.+ `Property.SheetEditor` (entity and date properties), `InlineTagsSheetPill`,+ and the event composer's guest pill use it. Short lists (status, priority)+ stay dropdowns: on touch, property menus leave focus where it was.- A backdrop tap only dismisses: `MobileDrawer` swallows the rest of that tap,so it never presses what the scrim covered, even when the sheet unmounts asit closes (a `<Show>` around it, or `openDialog`). It swallows only a tap@@ -84,6 +101,10 @@ read their code, and follow that pattern rather than inventing a new one.- Focus inputs on user intent only, never on mount. On touch, Enter in acomposer inserts a newline; the send button submits.+- iOS raises the keyboard only for a focus inside the tap. A tap that opens a+ composer whose field mounts later calls `triggerFocusInput` in the tap (see+ `raiseKeyboardForNewTaskTitle`), or a create menu item's `raiseKeyboard`;+ popovers and the create menu leave focus with its stand-in.- UI over an editor must not take focus: cancel `pointerdown` and`mousedown` on its root (`keepEditorFocus` in `TouchSelectionToolbar`) oruse `usePreserveFocusOnButtonTaps`; mark sibling regionsdiff --git a/apps/web/src/components/app/mobile/MobileCreateMenu.tsx b/apps/web/src/components/app/mobile/MobileCreateMenu.tsxindex 1899eb09ec..b5bccc084c 100644--- a/apps/web/src/components/app/mobile/MobileCreateMenu.tsx+++ b/apps/web/src/components/app/mobile/MobileCreateMenu.tsx@@ -1,5 +1,6 @@import './MobileCreateMenu.css';import { t } from '@app/lib/i18n';+import { focusStandInActive } from '@core/directive/focusInput';import PlusIcon from '@icon/system/regular/plus.svg';import { Dialog } from '@kobalte/core/dialog';import { Layer } from '@ui/components/Layer';@@ -18,7 +19,13 @@ import { MobileDockIsland } from './MobileDockIsland';export type MobileCreateMenuItem = {label: string;icon: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;+ /** Runs once the menu has closed, after the tap. */onSelect: () => void;+ /**+ * Runs in the tap, for an action that opens a field to type in: iOS only+ * raises the keyboard inside the tap (see `raiseKeyboardForNewTaskTitle`).+ */+ raiseKeyboard?: () => void;disabled?: boolean;};@@ -71,6 +78,7 @@ export function MobileCreateMenu(props: {const select = (item: MobileCreateMenuItem) => {selectedAction = item.onSelect;setOpen(false);+ item.raiseKeyboard?.();};return (@@ -95,9 +103,12 @@ export function MobileCreateMenu(props: {bottom: `${position().bottom}px`,'max-height': `calc(100dvh - ${position().bottom}px - var(--safe-top) - 12px)`,}}- onCloseAutoFocus={() => {- // Let the dialog restore New first, then hand focus to the next- // composer/menu after its focus trap has been removed.+ onCloseAutoFocus={(event) => {+ // A stand-in raised in the tap keeps the keyboard for the next+ // composer; otherwise let the dialog restore New first, then+ // hand focus to the next composer/menu after its focus trap+ // has been removed.+ if (focusStandInActive()) event.preventDefault();const action = selectedAction;selectedAction = undefined;if (action) queueMicrotask(action);diff --git a/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsx b/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsxindex 4f68fc0fa4..fd8eec0a4e 100644--- a/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsx+++ b/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsx@@ -11,6 +11,8 @@ const sources = vi.hoisted(() => ({blocks: vi.fn(),calendar: vi.fn(),openEvent: vi.fn(),+ openCalendarEvent: vi.fn(),+ raiseKeyboard: vi.fn(),openCompany: vi.fn(),openMenu: vi.fn(),}));@@ -31,6 +33,12 @@ vi.mock(useOpenEventComposer: () => sources.openEvent,}));+vi.mock('@app/features/calendar-view/open-calendar-event', () => ({+ openCalendarEventSplit: sources.openCalendarEvent,+}));+vi.mock('@app/features/task-composer/new-task-title-focus', () => ({+ raiseKeyboardForNewTaskTitle: sources.raiseKeyboard,+}));vi.mock('@app/features/crm/creation-adapter', () => ({openCreateCompanyModal: sources.openCompany,}));@@ -78,6 +86,27 @@ describe('mobile create availability', () => {expect(sources.openEvent).not.toHaveBeenCalled();});+ it('shows an event made from the inbox quick menu in the calendar', async () => {+ const { setCalendar } = setup();+ setCalendar(true);+ sources.openCalendarEvent.mockResolvedValue(true);+ fireEvent.click(screen.getByRole('button', { name: 'New' }));+ fireEvent.click(screen.getByRole('button', { name: 'Event' }));+ await vi.waitFor(() => expect(sources.openEvent).toHaveBeenCalledOnce());+ expect(sources.openCalendarEvent).not.toHaveBeenCalled();++ const created = {+ eventId: 'event-1',+ time: {+ kind: 'timed',+ startsAt: '2026-09-22T14:00:00Z',+ endsAt: '2026-09-22T15:00:00Z',+ },+ };+ sources.openEvent.mock.lastCall?.[0].onCreated(created);+ expect(sources.openCalendarEvent).toHaveBeenCalledExactlyOnceWith(created);+ });+it('omits Task when unavailable and invokes its launcher action when available', async () => {const { setBlocks } = setup();fireEvent.click(screen.getByRole('button', { name: 'New' }));@@ -95,6 +124,10 @@ describe('mobile create availability', () => {},]);fireEvent.click(screen.getByRole('button', { name: 'Task' }));+ // iOS raises the keyboard only inside the tap; the composer opens after+ // the menu has closed.+ expect(sources.raiseKeyboard).toHaveBeenCalledOnce();+ expect(createTask).not.toHaveBeenCalled();await vi.waitFor(() => expect(createTask).toHaveBeenCalledOnce());});diff --git a/apps/web/src/components/app/mobile/MobilePageCreateButton.tsx b/apps/web/src/components/app/mobile/MobilePageCreateButton.tsxindex 53e7d178c0..e1e6b3d911 100644--- a/apps/web/src/components/app/mobile/MobilePageCreateButton.tsx+++ b/apps/web/src/components/app/mobile/MobilePageCreateButton.tsx@@ -1,12 +1,15 @@import { useCalendarUiFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';import { useOpenEventComposer } from '@app/features/calendar-view/components/use-open-event-composer';+import { openCalendarEventSplit } from '@app/features/calendar-view/open-calendar-event';import {setCreateMenuOpen,useCreateMenuBlocks,} from '@app/features/command/Launcher';import { openCreateCompanyModal } from '@app/features/crm/creation-adapter';+import { raiseKeyboardForNewTaskTitle } from '@app/features/task-composer/new-task-title-focus';import { type TranslationKey, t } from '@app/lib/i18n';import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';+import { fireAndForget } from '@core/util/fireAndForget';import CalendarIcon from '@icon/system/regular/calendar-blank.svg';import MessageIcon from '@icon/system/regular/chat-circle.svg';import MoreIcon from '@icon/system/regular/dots-three.svg';@@ -45,7 +48,10 @@ const NEW_ITEM_LABELS: Partial<Record<MobileNavViewId, TranslationKey>> = {companies: 'mobile.newCompany',};-type PageCreateAction = Pick<MobileCreateMenuItem, 'label' | 'onSelect'>;+type PageCreateAction = Pick<+ MobileCreateMenuItem,+ 'label' | 'onSelect' | 'raiseKeyboard'+>;/** The current non-AI view's New action above the navigation dock. */export function MobilePageCreateButton() {@@ -63,11 +69,30 @@ export function MobilePageCreateButton() {}if (view === 'calendar') {return calendarEnabled()- ? { label: t('mobile.event'), onSelect: () => openEventComposer() }+ ? {+ label: t('mobile.event'),+ // Created away from the calendar, the event shows there next.+ onSelect: () =>+ openEventComposer({+ onCreated: (created) =>+ fireAndForget(+ openCalendarEventSplit(created),+ 'mobile-create'+ ),+ }),+ }: undefined;}const block = mobilePageCreateBlock(view, createBlocks());- return block && { label: block.label, onSelect: block.keyDownHandler };+ return (+ block && {+ label: block.label,+ onSelect: block.keyDownHandler,+ ...(block.blockName === 'task'+ ? { raiseKeyboard: raiseKeyboardForNewTaskTitle }+ : {}),+ }+ );};const quickActions = (): MobileCreateMenuItem[] => [diff --git a/apps/web/src/components/app/mobile/PickerSheet.test.tsx b/apps/web/src/components/app/mobile/PickerSheet.test.tsxnew file mode 100644index 0000000000..25429f8c8c--- /dev/null+++ b/apps/web/src/components/app/mobile/PickerSheet.test.tsx@@ -0,0 +1,67 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { PickerSheet } from './PickerSheet';++beforeEach(() => {+ vi.stubGlobal('scrollTo', vi.fn());+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++function renderPicker() {+ const [open, setOpen] = createSignal(false);+ render(() => (+ <>+ <input aria-label="Title" />+ <button onClick={() => setOpen(true)}>Guests</button>+ <PickerSheet.Root open={open()} onCancel={() => setOpen(false)}>+ <PickerSheet.Header title="Guests" onDone={() => setOpen(false)} />+ <PickerSheet.Body>+ <input type="text" aria-label="Search" />+ </PickerSheet.Body>+ </PickerSheet.Root>+ </>+ ));+ return { title: screen.getByLabelText<HTMLInputElement>('Title') };+}++it.each(['Cancel', 'Done'])(+ 'hands focus back to the field the opener left it in on %s',+ (action) => {+ const { title } = renderPicker();+ title.value = 'Call the venue';+ title.focus();+ title.setSelectionRange(4, 4);++ // The opener doesn't take focus, so the title still has it.+ fireEvent.click(screen.getByText('Guests'));+ screen.getByText('Cancel').focus();+ fireEvent.click(screen.getByText(action));++ expect(document.activeElement).toBe(title);+ expect(title.selectionStart).toBe(4);+ }+);++it('leaves focus alone when no field had it', () => {+ renderPicker();+ const opener = screen.getByText('Guests');++ opener.focus();+ fireEvent.click(opener);+ fireEvent.click(screen.getByText('Cancel'));++ expect(document.activeElement).not.toBe(screen.getByLabelText('Title'));+});diff --git a/apps/web/src/components/app/mobile/PickerSheet.tsx b/apps/web/src/components/app/mobile/PickerSheet.tsxnew file mode 100644index 0000000000..1684e943c3--- /dev/null+++ b/apps/web/src/components/app/mobile/PickerSheet.tsx@@ -0,0 +1,213 @@+import { t } from '@app/lib/i18n';+import { triggerFocusInput } from '@core/directive/focusInput';+import { isEditableInput } from '@core/util/isEditableInput';+import { Button } from '@ui';+import {+ type Accessor,+ createComputed,+ createContext,+ createSignal,+ type JSX,+ on,+ onCleanup,+ Show,+ useContext,+} from 'solid-js';+import { MobileDrawer } from './MobileDrawer';++const PICKER_SEARCH = 'input[type="text"]:not(:disabled)';++/** A text field with its caret, to hand focus back to. */+type TypingFocus = { field: HTMLElement; caret?: Range };++function captureTypingFocus(): TypingFocus | undefined {+ const field = document.activeElement;+ if (!(field instanceof HTMLElement) || !isEditableInput(field)) return;+ // A text input keeps its own caret; an editor's lives in the document.+ const selection = getSelection();+ const caret =+ field.isContentEditable && selection?.rangeCount+ ? selection.getRangeAt(0).cloneRange()+ : undefined;+ return { field, caret };+}++function restoreTypingFocus(focus: TypingFocus) {+ if (!focus.field.isConnected) return;+ focus.field.focus({ preventScroll: true });+ if (!focus.caret?.startContainer.isConnected) return;+ const selection = getSelection();+ selection?.removeAllRanges();+ selection?.addRange(focus.caret);+}++const PickerSheetContext = createContext<{+ onCancel: () => void;+ /** Whether the sheet has finished sliding in. */+ settled: Accessor<boolean>;+}>();++function usePickerSheet() {+ const sheet = useContext(PickerSheetContext);+ if (!sheet) throw new Error('PickerSheet parts must be rendered inside Root');+ return sheet;+}++/**+ * The sheet. It opens as tall as the touch composer sheets and does not drag:+ * a drag inside it would also reach a sheet beneath, and Cancel and Done own+ * closing. The backdrop and Escape cancel.+ *+ * Its content mounts with each opening, so a draft or picker session created+ * inside it starts from the saved value every time.+ */+function Root(props: {+ open: boolean;+ /** Close without applying the picks. */+ onCancel: () => void;+ children: JSX.Element;+}) {+ let content: HTMLElement | undefined;+ const search = () => content?.querySelector<HTMLInputElement>(PICKER_SEARCH);+ // Building a long picker list while the sheet slides in held iOS's main+ // thread for over a second, so the slide stalled and the sheet appeared late+ // and at the wrong size. The body mounts once the slide has ended instead.+ const [settled, setSettled] = createSignal(false);+ const settle = () => setSettled(true);+ // Opening runs inside the opener's tap, so the keyboard can move straight+ // to a stand-in input and on to the picker's search once it mounts. Without+ // it the keyboard drops as the composer's field blurs and rises again,+ // resizing both sheets twice. Closing hands it back to the field the opener+ // left focused, with its caret, in the closing tap for the same reason.+ let returnFocus: TypingFocus | undefined;+ const handBackFocus = () => {+ const focus = returnFocus;+ returnFocus = undefined;+ if (focus) restoreTypingFocus(focus);+ };+ createComputed(+ on(+ () => props.open,+ (open) => {+ if (!open) {+ handBackFocus();+ return;+ }+ returnFocus = captureTypingFocus();+ setSettled(false);+ triggerFocusInput(search);+ },+ { defer: true }+ )+ );+ onCleanup(handBackFocus);+ return (+ <PickerSheetContext.Provider+ value={{ onCancel: () => props.onCancel(), settled }}+ >+ <MobileDrawer+ side="bottom"+ open={props.open}+ onOpenChange={(open) => {+ if (!open) props.onCancel();+ }}+ // Focus waits for the picker's search to mount, rather than going to+ // the drawer's first control (Cancel) and dropping the keyboard.+ onInitialFocus={(event) => {+ event.preventDefault();+ // Without a slide (reduced motion) there is no transition to end.+ if (+ content &&+ parseFloat(getComputedStyle(content).transitionDuration) === 0+ )+ settle();+ }}+ >+ <MobileDrawer.Portal>+ <MobileDrawer.Overlay />+ <MobileDrawer.Content+ ref={(element: HTMLElement) => {+ content = element;+ // A listener beside the drawer's own: an onTransitionEnd prop+ // would replace the handler that finishes its slides.+ element.addEventListener('transitionend', (event) => {+ if (event.target === element && props.open) settle();+ });+ }}+ targetHeight={92}+ data-corvu-no-drag+ >+ {props.children}+ </MobileDrawer.Content>+ </MobileDrawer.Portal>+ </MobileDrawer>+ </PickerSheetContext.Provider>+ );+}++/** Cancel, the title, and Done across the top of the sheet. */+function Header(props: {+ title: string;+ /** Apply the picks and close. */+ onDone: () => void;+ doneDisabled?: boolean;+}) {+ const sheet = usePickerSheet();+ return (+ <div class="grid shrink-0 grid-cols-[1fr_auto_1fr] items-center gap-2 px-4 pt-4 pb-2">+ <Button+ variant="ghost"+ class="justify-self-start"+ onClick={sheet.onCancel}+ >+ {t('mobile.cancel')}+ </Button>+ <MobileDrawer.Title class="text-base font-semibold text-ink">+ {props.title}+ </MobileDrawer.Title>+ <Button+ variant="primary"+ class="justify-self-end"+ disabled={props.doneDisabled}+ onClick={props.onDone}+ >+ {t('mobile.done')}+ </Button>+ </div>+ );+}++/**+ * The rest of the sheet, for the picker to fill: give its list `min-h-0+ * flex-1` and its own scroll rather than a popover's capped height. It mounts+ * once the sheet has slid in, so a long list never stalls the slide; keep+ * state that must exist at once (a draft) outside it.+ */+function Body(props: { children: JSX.Element }) {+ const sheet = usePickerSheet();+ return (+ <div class="flex min-h-0 flex-auto flex-col text-sm">+ <Show when={sheet.settled()}>{props.children}</Show>+ </div>+ );+}++/**+ * A picker in a sheet stacked over the current one (a touch composer, or the+ * page): Cancel, a title, and Done across the top, and a body the picker+ * fills. Picks stay a draft until Done. Keep the picker's search field focused+ * when a row is tapped, by cancelling `pointerdown` and `mousedown` on the+ * rows, so the phone keyboard stays up. Closing returns focus to the field+ * that had it when the sheet opened, so the opener must not take focus on+ * tap either.+ *+ * ```tsx+ * <PickerSheet.Root open={open()} onCancel={close}>+ * <PickerSheet.Header title="Guests" onDone={applyAndClose} />+ * <PickerSheet.Body>+ * <GuestPicker fillHeight ... />+ * </PickerSheet.Body>+ * </PickerSheet.Root>+ * ```+ */+export const PickerSheet = { Root, Header, Body };diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex d16ab0085e..58fc68ad86 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -1,6 +1,7 @@import { parseAgentsRoute } from '@app/features/agents-view/core/route';import { useSpreadsheetAccess } from '@app/features/block-spreadsheet/primitives/use-spreadsheet-access';import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';+import type { CreatedCalendarEvent } from '@app/features/calendar/hooks/use-event-editor';import type { CalendarEvent } from '@app/features/calendar/types';import { HomeRouteView } from '@app/features/home/route-views';import { parseProjectRoute } from '@app/features/projects/core/route';@@ -471,6 +472,11 @@ registerComponent('calendar-event-compose', (params) => {params?.onDirtyChange as ((dirty: boolean) => void) | undefined}onSaveSuccess={params?.onSaveSuccess as (() => void) | undefined}+ onCreated={+ params?.onCreated as+ | ((created: CreatedCalendarEvent) => void)+ | undefined+ }/>);});diff --git a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsxindex cc46429b9d..651c413de6 100644--- a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx+++ b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx@@ -2,8 +2,15 @@ import { SoupContextProvider } from '@app/features/next-soup/soup-context';import { MobileDrawer } from '@components/app/mobile/MobileDrawer';import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { Dialog, Panel } from '@ui';-import { createMemo, createSignal, For, Show, Suspense } from 'solid-js';+import { cn, Dialog, Panel } from '@ui';+import {+ createMemo,+ createSignal,+ For,+ onCleanup,+ Show,+ Suspense,+} from 'solid-js';import { Dynamic } from 'solid-js/web';import {type SplitFileMenuActionGroups,@@ -58,6 +65,12 @@ function PopoverSplitModal(props: {const [panelRef, setPanelRef] = createSignal<HTMLElement | null>(null);const [displayName, setDisplayName] = createSignal(props.popover.content.id);const [contentOffsetTop, setContentOffsetTop] = createSignal(0);+ const [drawerHeader, setDrawerHeader] = createSignal<HTMLElement>();+ const [fillsDrawer, setFillsDrawer] = createSignal(false);+ const fillDrawer = () => {+ setFillsDrawer(true);+ onCleanup(() => setFillsDrawer(false));+ };const [titleFileMenuRef, setTitleFileMenuRef] =createSignal<HTMLDivElement>();const [titleFileMenuTrigger, setTitleFileMenuTrigger] =@@ -121,6 +134,8 @@ function PopoverSplitModal(props: {splitHotkeyScope: scopeId,isPanelActive: () => true,panelRef,+ drawerHeader,+ ...(isTouchDevice() ? { fillDrawer } : {}),panelSize: { width: null, height: null },contentOffsetTop,setContentOffsetTop,@@ -149,7 +164,7 @@ function PopoverSplitModal(props: {<SplitPanelContext.Provider value={stubPanelContext}><SoupContextProvider><Show when={props.popover.mount}>- <Panel.Body>+ <Panel.Body class={cn(fillsDrawer() && 'flex flex-auto flex-col')}><Suspense><Dynamic component={props.popover.mount.element} /></Suspense>@@ -190,12 +205,21 @@ function PopoverSplitModal(props: {ref={attachPanel}aria-label={displayName()}maxHeight={92}+ // Room to write a few paragraphs without covering the page.+ targetHeight={fillsDrawer() ? 70 : undefined}><MobileDrawer.Handle />+ {/* Before the scroll body so it exists when the content mounts;+ hidden unless the content portals its pinned actions here. */}+ <div ref={setDrawerHeader} class="shrink-0 empty:hidden" /><MobileDrawer.ScrollBody>{/* As in Dialog's drawer: at its natural height the body's- overflow-clip cannot clip the drawer's scroll body. */}- <div class="shrink-0">+ overflow-clip cannot clip the drawer's scroll body. Filling+ content grows past it but never shrinks below it, so a+ sheet the keyboard shortens still scrolls. */}+ <div+ class={fillsDrawer() ? 'flex flex-auto flex-col' : 'shrink-0'}+ ><Content /></div></MobileDrawer.ScrollBody>diff --git a/apps/web/src/components/app/split-layout/context.ts b/apps/web/src/components/app/split-layout/context.tsindex 550fe4e5b7..a422db4311 100644--- a/apps/web/src/components/app/split-layout/context.ts+++ b/apps/web/src/components/app/split-layout/context.ts@@ -97,6 +97,18 @@ export type SplitPanelContextType = {navigationCollapsed?: Signal<boolean>;bottomPanel: Accessor<SplitBottomPanelRegistration | undefined>;registerBottomPanel: (panel: SplitBottomPanelRegistration) => () => void;+ /**+ * The touch sheet's pinned chrome between its handle and scrolling content,+ * for actions that stay in reach; absent outside a touch popover.+ */+ drawerHeader?: Accessor<HTMLElement | undefined>;+ /**+ * Opens the touch sheet at a fixed 70% height while the calling owner+ * lives, for content that grows to fill it (a composer's body); other+ * content keeps the sheet at its natural height. Absent outside a touch+ * popover.+ */+ fillDrawer?: () => void;layoutRefs: {headerLeft?: HTMLDivElement;headerRight?: HTMLDivElement;diff --git a/apps/web/src/components/app/split-layout/utils/focusPopoverInput.test.ts b/apps/web/src/components/app/split-layout/utils/focusPopoverInput.test.tsnew file mode 100644index 0000000000..e4092131dd--- /dev/null+++ b/apps/web/src/components/app/split-layout/utils/focusPopoverInput.test.ts@@ -0,0 +1,56 @@+import { afterEach, expect, it } from 'vitest';+import { focusPopoverInput } from './focusPopoverInput';++afterEach(() => {+ document.body.replaceChildren();+});++function popover(markup: string) {+ const container = document.createElement('div');+ container.innerHTML = markup;+ document.body.append(container);+ return container;+}++const initialFocus = () => new Event('initial-focus', { cancelable: true });++it('focuses a declared input in place of the first control', () => {+ const container = popover('<button>Close</button><input autofocus />');+ const event = initialFocus();+ focusPopoverInput(event, container);+ expect(document.activeElement).toBe(container.querySelector('input'));+ expect(event.defaultPrevented).toBe(true);+});++it('leaves focus with a field the content already focused', () => {+ const container = popover(+ '<button>Close</button><div contenteditable="true"></div>'+ );+ const title = container.querySelector<HTMLElement>('[contenteditable]');+ title?.focus();+ const event = initialFocus();+ focusPopoverInput(event, container);+ expect(document.activeElement).toBe(title);+ expect(event.defaultPrevented).toBe(true);+});++it("leaves focus with the opening tap's stand-in input", () => {+ const container = popover('<button>Close</button>');+ const standIn = document.createElement('input');+ standIn.setAttribute('data-focus-stand-in', '');+ document.body.append(standIn);+ standIn.focus();+ const event = initialFocus();+ focusPopoverInput(event, container);+ expect(document.activeElement).toBe(standIn);+ expect(event.defaultPrevented).toBe(true);+});++it('leaves a field outside the popover to the default focus', () => {+ const outside = document.createElement('input');+ document.body.append(outside);+ outside.focus();+ const event = initialFocus();+ focusPopoverInput(event, popover('<button>Close</button>'));+ expect(event.defaultPrevented).toBe(false);+});diff --git a/apps/web/src/components/app/split-layout/utils/focusPopoverInput.ts b/apps/web/src/components/app/split-layout/utils/focusPopoverInput.tsindex 4b71054690..64b42a573f 100644--- a/apps/web/src/components/app/split-layout/utils/focusPopoverInput.ts+++ b/apps/web/src/components/app/split-layout/utils/focusPopoverInput.ts@@ -1,6 +1,20 @@+import { focusStandInActive } from '@core/directive/focusInput';+import { isEditableInput } from '@core/util/isEditableInput';+/** Honor an explicitly declared input instead of the popover's first toolbar button. */export function focusPopoverInput(event: Event, container: HTMLElement | null) {if (event.defaultPrevented) return;+ // Leave focus with the opening tap's stand-in, which holds the phone+ // keyboard until the content's own field mounts, or with that field once+ // it has focused itself.+ const active = document.activeElement;+ if (+ focusStandInActive() ||+ (container?.contains(active) && isEditableInput(active))+ ) {+ event.preventDefault();+ return;+ }const input = container?.querySelector<HTMLElement>('[autofocus]:not(:disabled)');diff --git a/apps/web/src/components/date-time-range/date-time-range-fields.tsx b/apps/web/src/components/date-time-range/date-time-range-fields.tsxindex c6ed1dd424..90ddd406c6 100644--- a/apps/web/src/components/date-time-range/date-time-range-fields.tsx+++ b/apps/web/src/components/date-time-range/date-time-range-fields.tsx@@ -8,7 +8,14 @@ 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, type JSX, Show } from 'solid-js';+import {+ createContext,+ createSignal,+ createUniqueId,+ type JSX,+ Show,+ useContext,+} from 'solid-js';import { dateLabelFormatter, TimeInput } from './time-input';import {DAY_TIME_OPTIONS,@@ -58,9 +65,10 @@ function DateField(props: DateFieldProps) {aria-describedby={props.describedBy}class={buttonClasses({variant: 'secondary',- size: 'sm',+ size: 'xs',class: cn(- 'max-w-40 justify-start',+ // A touch more room after the date than the icon has before it.+ 'max-w-40 justify-start pr-2.5',props.invalid && 'border-failure text-failure'),})}@@ -104,7 +112,7 @@ function DateField(props: DateFieldProps) {);}-export interface DateTimeRangeFieldsProps {+export interface DateTimeRangeProps {/** What the range belongs to, named in the fields' labels: `event`, a column's name. */subject: string;/** The start field's id, for a label to name or a caller to focus. */@@ -115,33 +123,82 @@ export interface DateTimeRangeFieldsProps {allDay: boolean;onStartChange: (value: string) => void;onEndChange: (value: string) => void;- /** Omit to hide the All day control for hosts that only support timed ranges. */- onAllDayChange?: (allDay: boolean) => void;startDisabled?: boolean;endDisabled?: boolean;- allDayDisabled?: boolean;invalid?: boolean;describedBy?: string;- /** A control after All day, e.g. a host's Clear. */- trailing?: JSX.Element;+}++const DateTimeRangeContext = createContext<DateTimeRangeProps>();++function useDateTimeRange() {+ const range = useContext(DateTimeRangeContext);+ if (!range)+ throw new Error('DateTimeRange parts must be rendered inside Root');+ return range;+}++function Root(props: DateTimeRangeProps & { children: JSX.Element }) {+ return (+ <DateTimeRangeContext.Provider value={props}>+ {props.children}+ </DateTimeRangeContext.Provider>+ );+}++/** The start's date and, unless all day, its time. */+function Start() {+ const range = useDateTimeRange();+ const fieldId = createUniqueId();+ const parts = () => splitLocalDateTime(range.start);+ return (+ <span class="flex items-center gap-1">+ <DateField+ id={range.id}+ subject={range.subject}+ label="Start"+ date={parts().date}+ onChange={(date) =>+ range.onStartChange(+ range.allDay ? date : withLocalDate(range.start, date)+ )+ }+ disabled={range.startDisabled}+ invalid={range.invalid}+ describedBy={range.describedBy}+ placement="bottom-start"+ />+ <Show when={!range.allDay}>+ <TimeInput+ id={`range-start-time-${fieldId}`}+ label={`${range.subject} start time`}+ value={parts().time}+ onChange={(option) =>+ range.onStartChange(withLocalTime(range.start, option.value))+ }+ disabled={range.startDisabled}+ invalid={range.invalid}+ describedBy={range.describedBy}+ />+ </Show>+ </span>+ );}/**- * Each end's date and, unless all day, its time, joined by an arrow, then an- * All day switch, as Google Calendar edits an event's time. Times are typed- * or picked; the end's list counts from the start and rolls past midnight.- * An all-day end is the last day, included.+ * The end's date and, unless all day, its time. The end's list counts from+ * the start and rolls past midnight.*/-export function DateTimeRangeFields(props: DateTimeRangeFieldsProps) {+function End() {+ const range = useDateTimeRange();const fieldId = createUniqueId();- const startParts = () => splitLocalDateTime(props.start);- const endParts = () => splitLocalDateTime(props.end);+ const parts = () => splitLocalDateTime(range.end);/** The start the end's times count from, while the end is within a day of it. */const endAnchor = () => {- if (props.allDay || !props.start) return undefined;- return withinEndTimeWindow(props.start, props.end)- ? props.start+ if (range.allDay || !range.start) return undefined;+ return withinEndTimeWindow(range.start, range.end)+ ? range.start: undefined;};const endOptions = () => {@@ -153,107 +210,105 @@ export function DateTimeRangeFields(props: DateTimeRangeFieldsProps) {const endSelectedId = () => {const start = endAnchor();return selectedTimeOptionId(- endParts().time,- start ? dayOffsetBetween(start, props.end) : 0+ parts().time,+ start ? dayOffsetBetween(start, range.end) : 0);};const changeEndTime = (option: TimeOption) => {const start = endAnchor();- props.onEndChange(+ range.onEndChange(start? endValueFor(start, option)- : withLocalTime(props.end, option.value)+ : withLocalTime(range.end, option.value));};return (- <div class="flex w-full flex-wrap items-center gap-x-3 gap-y-2">- <div class="flex min-w-0 flex-wrap items-center gap-1.5">- <span class="flex items-center gap-1">- <DateField- id={props.id}- subject={props.subject}- label="Start"- date={startParts().date}- onChange={(date) =>- props.onStartChange(- props.allDay ? date : withLocalDate(props.start, date)- )- }- disabled={props.startDisabled}- invalid={props.invalid}- describedBy={props.describedBy}- placement="bottom-start"- />- <Show when={!props.allDay}>- <TimeInput- id={`range-start-time-${fieldId}`}- label={`${props.subject} start time`}- value={startParts().time}- onChange={(option) =>- props.onStartChange(withLocalTime(props.start, option.value))- }- disabled={props.startDisabled}- invalid={props.invalid}- describedBy={props.describedBy}- />- </Show>- </span>- <ArrowRightIcon- aria-hidden={false}- aria-label="to"- class={cn(- 'size-3.5 shrink-0 text-ink-extra-muted',- props.invalid && 'text-failure'- )}+ <span class="flex items-center gap-1">+ <DateField+ subject={range.subject}+ label="End"+ date={parts().date}+ onChange={(date) =>+ range.onEndChange(+ range.allDay ? date : withLocalDate(range.end, date)+ )+ }+ disabled={range.endDisabled}+ invalid={range.invalid}+ describedBy={range.describedBy}+ placement="bottom-end"+ />+ <Show when={!range.allDay}>+ <TimeInput+ id={`range-end-time-${fieldId}`}+ label={`${range.subject} end time`}+ value={parts().time}+ options={endOptions()}+ selectedId={endSelectedId()}+ onChange={changeEndTime}+ disabled={range.endDisabled}+ invalid={range.invalid}+ describedBy={range.describedBy}/>- <span class="flex items-center gap-1">- <DateField- subject={props.subject}- label="End"- date={endParts().date}- onChange={(date) =>- props.onEndChange(- props.allDay ? date : withLocalDate(props.end, date)- )- }- disabled={props.endDisabled}- invalid={props.invalid}- describedBy={props.describedBy}- placement="bottom-end"- />- <Show when={!props.allDay}>- <TimeInput- id={`range-end-time-${fieldId}`}- label={`${props.subject} end time`}- value={endParts().time}- options={endOptions()}- selectedId={endSelectedId()}- onChange={changeEndTime}- disabled={props.endDisabled}- invalid={props.invalid}- describedBy={props.describedBy}- />- </Show>- </span>- </div>- <Show when={props.onAllDayChange || props.trailing}>- <div class="ml-auto flex shrink-0 items-center gap-2">- <Show when={props.onAllDayChange}>- {(onChange) => (- <ToggleSwitch- checked={props.allDay}- disabled={props.allDayDisabled}- onChange={onChange()}- size="sm"- label="All day"- labelClass="whitespace-nowrap text-xs text-ink-muted"- />+ </Show>+ </span>+ );+}++/**+ * Parts of a date/time range, for hosts that lay out its start and end+ * themselves; `DateTimeRangeFields` is the inline layout.+ */+export const DateTimeRange = { Root, Start, End };++export interface DateTimeRangeFieldsProps extends DateTimeRangeProps {+ /** Omit to hide the All day control for hosts that only support timed ranges. */+ onAllDayChange?: (allDay: boolean) => void;+ allDayDisabled?: boolean;+ /** A control after All day, e.g. a host's Clear. */+ trailing?: JSX.Element;+}++/**+ * Each end's date and, unless all day, its time, joined by an arrow, then an+ * All day switch, as Google Calendar edits an event's time. Times are typed+ * or picked. An all-day end is the last day, included.+ */+export function DateTimeRangeFields(props: DateTimeRangeFieldsProps) {+ return (+ <DateTimeRange.Root {...props}>+ <div class="flex w-full flex-wrap items-center gap-x-3 gap-y-2">+ <div class="flex min-w-0 flex-wrap items-center gap-1.5">+ <DateTimeRange.Start />+ <ArrowRightIcon+ aria-hidden={false}+ aria-label="to"+ class={cn(+ 'size-3.5 shrink-0 text-ink-extra-muted',+ props.invalid && 'text-failure')}- </Show>- {props.trailing}+ />+ <DateTimeRange.End /></div>- </Show>- </div>+ <Show when={props.onAllDayChange || props.trailing}>+ <div class="ml-auto flex shrink-0 items-center gap-2">+ <Show when={props.onAllDayChange}>+ {(onChange) => (+ <ToggleSwitch+ checked={props.allDay}+ disabled={props.allDayDisabled}+ onChange={onChange()}+ size="sm"+ label="All day"+ labelClass="whitespace-nowrap text-xs text-ink-muted"+ />+ )}+ </Show>+ {props.trailing}+ </div>+ </Show>+ </div>+ </DateTimeRange.Root>);}diff --git a/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsxindex 035613e358..c71ef492d8 100644--- a/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx+++ b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx@@ -4,12 +4,17 @@ import {defaultEditorInitialValues,type EventEditorInitialValues,} from '@app/features/calendar/components/composer/event-form-model';+import type { EventFormProps } from '@app/features/calendar/components/composer/event-form-state';+import { MobileEventForm } from '@app/features/calendar/components/composer/MobileEventForm';import { createGuestInviteController } from '@app/features/calendar/hooks/create-guest-invite-controller';import {useCalendarGuestInvitesFlag,useCalendarInvitationForwardFlag,} from '@app/features/calendar/hooks/use-calendar-ui-flag';-import { useEventEditor } from '@app/features/calendar/hooks/use-event-editor';+import {+ type CreatedCalendarEvent,+ useEventEditor,+} from '@app/features/calendar/hooks/use-event-editor';import { useSyncedCalendarEvent } from '@app/features/calendar/hooks/use-synced-calendar-event';import type { CalendarEvent } from '@app/features/calendar/types';import { viewerReplacesGuests } from '@app/features/calendar/utils/event-guest-editing';@@ -41,6 +46,18 @@ function EditorForwardInvitation(props: {);}+/** The touch sheet's layout wherever the panel offers the sheet's pinned chrome. */+function PanelEventForm(props: EventFormProps) {+ const panel = useSplitPanelOrThrow();+ return (+ <Show when={panel.drawerHeader?.()} fallback={<EventForm {...props} />}>+ {(headerMount) => (+ <MobileEventForm {...props} headerMount={headerMount()} />+ )}+ </Show>+ );+}+/** Standalone create/edit event composer hosted in a popover split. */type EventComposerSplitProps = {event?: CalendarEvent;@@ -48,6 +65,8 @@ type EventComposerSplitProps = {onCalendarChange?: (calendarId: string, color: string) => void;onDirtyChange?: (dirty: boolean) => void;onSaveSuccess?: () => void;+ /** Called with a new event once it exists, before the composer closes. */+ onCreated?: (created: CreatedCalendarEvent) => void;};export function EventComposerSplit(props: EventComposerSplitProps) {@@ -91,6 +110,7 @@ function EventComposerContent(invitationForwardEnabled,syncedEvent: useSyncedCalendarEvent(() => props.event),onDetailsLocked: () => controller.resetDetails(),+ onCreated: (created) => props.onCreated?.(created),onSaved: () => {props.onSaveSuccess?.();close();@@ -118,7 +138,7 @@ function EventComposerContent(return (<div ref={attachHotkeys} class="flex h-full min-h-0 flex-col p-4 text-ink">- <EventForm+ <PanelEventFormcontroller={controller}macroCallsEnabled={macroCallsEnabled()}isEdit={isEdit()}diff --git a/apps/web/src/features/block-md/component/InlinePropertyValue.tsx b/apps/web/src/features/block-md/component/InlinePropertyValue.tsxindex 67d8e0ca92..29b3b40986 100644--- a/apps/web/src/features/block-md/component/InlinePropertyValue.tsx+++ b/apps/web/src/features/block-md/component/InlinePropertyValue.tsx@@ -6,7 +6,13 @@ import { usePropertiesContext } from '@property/context/PropertiesContext';import { openPropertyEditor } from '@property/editor/state/propertyEditor';import type { Property as PropertyT } from '@property/types';import { Button } from '@ui';-import { type Component, createSignal, type JSX, Show } from 'solid-js';+import {+ type Component,+ type ComponentProps,+ createSignal,+ type JSX,+ Show,+} from 'solid-js';type InlinePropertyValueProps = {property: PropertyT;@@ -17,6 +23,8 @@ type InlinePropertyValueProps = {class?: string;canManage?: boolean;canRemove?: boolean;+ /** The editor the pill opens; see `PropertyValuePill`. */+ editor?: ComponentProps<typeof PropertyValuePill>['editor'];};/**@@ -119,6 +127,7 @@ export const InlinePropertyValue: Component<InlinePropertyValueProps> = (</Show>}entitySelfFilter={{ entityType: ctx.entityType, blockId: props.entityId }}+ editor={props.editor}/>);};diff --git a/apps/web/src/features/calendar-view/components/use-open-event-composer.ts b/apps/web/src/features/calendar-view/components/use-open-event-composer.tsindex f4281a5299..ad10eb0fad 100644--- a/apps/web/src/features/calendar-view/components/use-open-event-composer.ts+++ b/apps/web/src/features/calendar-view/components/use-open-event-composer.ts@@ -1,4 +1,5 @@import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';+import type { CreatedCalendarEvent } from '@app/features/calendar/hooks/use-event-editor';import type { CalendarEvent } from '@app/features/calendar/types';import { useSplitLayout } from '@components/app/split-layout/layout';import { confirmDialog } from '@ui';@@ -9,6 +10,8 @@ export interface OpenEventComposerOptions {event?: CalendarEvent;initialValues?: EventEditorInitialValues;onCalendarChange?: (calendarId: string, color: string) => void;+ /** Called with a new event once it exists, before the composer closes. */+ onCreated?: (created: CreatedCalendarEvent) => void;onClose?: () => void;}@@ -36,6 +39,7 @@ export function useOpenEventComposer() {onSaveSuccess: () => {eventSaved = true;},+ onCreated: options.onCreated,},},{diff --git a/apps/web/src/features/calendar/components/composer/EventForm.tsx b/apps/web/src/features/calendar/components/composer/EventForm.tsxindex 9b6ced985a..9bc234aa9a 100644--- a/apps/web/src/features/calendar/components/composer/EventForm.tsx+++ b/apps/web/src/features/calendar/components/composer/EventForm.tsx@@ -1,574 +1,33 @@-import { DateTimeRangeFields } from '@app/components/date-time-range/date-time-range-fields';-import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';-import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';-import SpinnerIcon from '@icon/system/regular/spinner.svg';-import type { CalendarUpdateScope } from '@service-email/client';-import { Button, cn, Layer, RadioGroup, Tooltip } from '@ui';-import {- createEffect,- createSignal,- createUniqueId,- For,- type JSX,- type ParentProps,- Show,-} from 'solid-js';-import {- calendarDescriptionToEditorHtml,- exportCalendarDescription,-} from '../../utils/calendar-description';-import type { CalendarEventFormController } from './create-calendar-event-form-controller';-import { EventGuestPolicyRow } from './EventGuestPolicyRow';-import {- EventComposerCalendarPill,- EventComposerConferencePill,- EventComposerDeclineMessagePill,- EventComposerDeclinePill,- EventComposerGuestsPill,- EventComposerKindPill,- EventComposerLocationPill,- EventComposerRecurrencePill,- EventComposerRemindersPill,-} from './EventPropertyPills';-import { EventTitleInput } from './EventTitleInput';-import type {- EventEditorDisabledFields,- EventEditorSubmitValues,-} from './event-form-model';-import { outOfOfficeNoticeFor } from './out-of-office';-import { RecurrenceBuilder } from './RecurrenceBuilder';--export interface EventFormProps {- controller: CalendarEventFormController;- /** Whether this host can create and attach Macro call links. */- macroCallsEnabled: boolean;- isEdit?: boolean;- disabledFields?: EventEditorDisabledFields;- /** The viewer may add guests but not remove the event's current ones. */- addOnlyGuests?: boolean;- /** Why a read-only guest list cannot change. */- guestsReadOnlyReason?: string;- /** An action beside the guests, such as forwarding the invitation. */- guestsAction?: JSX.Element;- /** The organizer hides the guest list, so the seeded guests are not all of them. */- guestListHidden?: boolean;- /** Whether the viewer may set what guests may do, as the organizer. */- guestPolicyEditable?: boolean;- /**- * Why the event's title, time, description, location, recurrence and- * conferencing cannot change.- */- detailsReadOnlyReason?: string;- showRecurringEditNotice?: boolean;- /** Disable interaction without presenting the form as an in-flight save. */- disabled?: boolean;- pending: boolean;- saveError?: string;- class?: string;- onCalendarChange?: (calendarId: string, color: string) => void;- onDirtyChange?: (dirty: boolean) => void;- onCancel: () => void;- onSubmit: (- values: EventEditorSubmitValues,- scope?: CalendarUpdateScope- ) => void;-}--/** Whether edits to a recurring event patch one occurrence or the whole series. */-const RECURRING_EDIT_SCOPE_OPTIONS = [- { scope: 'this_event', label: 'This event' },- { scope: 'all', label: 'All events' },-] as const satisfies readonly {- scope: CalendarUpdateScope;- label: string;-}[];--/** Explains a locked field on hover and keyboard focus. */-function LockedField(props: ParentProps<{ reason?: string; class?: string }>) {- return (- <Show when={props.reason} fallback={props.children}>- {(reason) => (- <Tooltip as="span" label={reason()} tabIndex={0} class={props.class}>- {props.children}- </Tooltip>- )}- </Show>- );-}+import { EventFormParts } from './event-form-parts';+import { createEventForm, type EventFormProps } from './event-form-state';/** Create/edit event form laid out like the standalone task composer. */export function EventForm(props: EventFormProps) {- const formId = createUniqueId();- const resolveAppLink = useMacroMentionLinkResolver();-- const dateRangeErrorId = `event-composer-date-range-error-${formId}`;- const recurrenceReasonId = `event-composer-recurrence-reason-${formId}`;- const pastEventWarningId = `event-composer-past-event-warning-${formId}`;-- const controller = props.controller;- const state = controller.state;- const isEdit = () => props.isEdit ?? false;- const formIsDisabled = () => props.pending || props.disabled === true;-- // Recurring edits default to the whole series, matching the long-standing- // behavior; "this event" writes a single-occurrence exception.- const [editScope, setEditScope] = createSignal<CalendarUpdateScope>('all');- // Guest permissions belong to the whole series, so an occurrence edit- // returns them to what is stored rather than keep an edit it cannot save.- const changeEditScope = (scope: CalendarUpdateScope) => {- setEditScope(scope);- if (scope === 'this_event') controller.resetGuestPolicy();- };-- // An invalid range already speaks for itself; only one line shows at a time.- const pastEventWarning = () =>- controller.dateRangeError() ? undefined : controller.pastEventWarning();- const dateRangeDescribedBy = () => {- if (controller.dateRangeError()) return dateRangeErrorId;- return pastEventWarning() ? pastEventWarningId : undefined;- };-- const fieldIsReadOnly = (field: keyof EventEditorDisabledFields) =>- props.disabledFields?.[field] === true;- const fieldIsDisabled = (field: keyof EventEditorDisabledFields) =>- formIsDisabled() || fieldIsReadOnly(field);- const detailsLocked = () => props.detailsReadOnlyReason !== undefined;- // A single occurrence has no repeat rule of its own; like the guest- // permissions, the rule belongs to the whole series. A lock already says- // why the rule cannot change.- const recurrenceScopeReason = () =>- editScope() === 'this_event' && !detailsLocked()- ? 'The repeat rule applies to all events. Choose All events to change it.'- : undefined;- const recurrenceDescribedBy = () =>- recurrenceScopeReason() ? recurrenceReasonId : undefined;-- const capabilities = () => controller.selectedCalendarOption()?.capabilities;- const conferenceLocked = () =>- isEdit() &&- capabilities()?.removeConference === false &&- ['microsoft_teams', 'existing'].includes(- controller.initialConferenceChoice()- );- const isOutOfOffice = () => controller.isOutOfOffice();- // The decline settings of an edited event are unknown until picked, and the- // disclosure must not claim behavior nobody chose.- const outOfOfficeNotice = () => {- const outOfOffice = state().outOfOffice;- if (!isOutOfOffice() || !outOfOffice) return undefined;- return outOfOfficeNoticeFor(- outOfOffice.autoDeclineMode,- outOfOffice.declineMessage- );- };-- // The editor cannot hand the provider's string back: Lexical re-serializes- // whatever it loads. Only content that exports differently from what was- // loaded counts as an edit, so an untouched description stays byte-for-byte- // what the event was opened with.- const initialDescription = state().description;- let loadedDescription: string | undefined;-- createEffect(() => {- const option = controller.selectedCalendarOption();- if (option) props.onCalendarChange?.(option.id, option.color);- });- createEffect(() => props.onDirtyChange?.(controller.isDirty()));-- const descriptionEditor = () => (- <MarkdownTextarea- resolveAppLink={resolveAppLink}- type="calendar"- initialHtml={calendarDescriptionToEditorHtml(initialDescription)}- editable={() => !fieldIsDisabled('description')}- onInitialized={(editor) => {- loadedDescription = exportCalendarDescription(editor);- }}- onChange={(_markdown, editor) => {- if (!editor) return;- const next = exportCalendarDescription(editor);- controller.setField(- 'description',- next === loadedDescription ? initialDescription : next- );- }}- placeholder="Add description..."- portalScope="local"- domRef={(element) => element.setAttribute('aria-label', 'Description')}- class="h-full w-full bg-transparent px-2 text-sm text-ink outline-none"- />- );-- const submit = () => {- const values = controller.submitValues();- if (!values || formIsDisabled()) return;- props.onSubmit(- values,- props.showRecurringEditNotice ? editScope() : undefined- );- };-+ const form = createEventForm(props);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();- }}- >+ <EventFormParts.Root form={form} class={props.class}><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-1">- <LockedField- reason={props.detailsReadOnlyReason}- class="block min-w-0"- >- <DateTimeRangeFields- subject="event"- start={state().start}- end={state().end}- allDay={state().allDay}- onStartChange={controller.setStart}- onEndChange={controller.setEnd}- onAllDayChange={controller.setAllDay}- startDisabled={fieldIsDisabled('start')}- endDisabled={fieldIsDisabled('end')}- allDayDisabled={fieldIsDisabled('allDay')}- invalid={controller.dateRangeError() !== undefined}- describedBy={dateRangeDescribedBy()}- />- </LockedField>- <Show when={controller.dateRangeError()}>- {(error) => (- <p- id={dateRangeErrorId}- role="alert"- class="text-xs text-failure"- >- {error()}- </p>- )}- </Show>- <Show when={pastEventWarning()}>- {(warning) => (- <p- id={pastEventWarningId}- role="status"- class="text-xs text-warning"- >- {warning()}- </p>- )}- </Show>- </div>-- <LockedField- reason={props.detailsReadOnlyReason}- class="flex w-full"- >- <EventTitleInput- value={state().title}- onChange={(value) => controller.setField('title', value)}- autofocus={!isEdit()}- disabled={fieldIsDisabled('title')}- />- </LockedField>-- {/* Google rejects a description on an out-of-office event. The- editor re-initializes from the kind switch's reset state, so- what it shows always matches what a save submits. */}- <Show when={!isOutOfOffice()}>- <LockedField- reason={props.detailsReadOnlyReason}- class="block w-full"- >- <div class="h-12 overflow-y-auto">- {/* The editor reads the description only when it mounts.- Details that lock after a refused save return to the- event's own, so the editor mounts again to show them. */}- <Show- when={fieldIsReadOnly('description')}- fallback={descriptionEditor()}- >- {descriptionEditor()}- </Show>- </div>- </LockedField>- </Show>+ <EventFormParts.When />+ <EventFormParts.Title />+ <EventFormParts.Description /></div>-<div class="flex min-w-0 flex-col gap-2">- <div class="flex min-w-0 flex-wrap items-center gap-2">- {/* Read-only on every edit, they open their one value as a list;- locked, they are as unavailable as the other details. */}- <LockedField reason={props.detailsReadOnlyReason}>- <EventComposerKindPill- eventType={state().eventType}- onChange={controller.setEventKind}- disabled={formIsDisabled() || detailsLocked()}- readOnly={isEdit()}- />- </LockedField>- <LockedField reason={props.detailsReadOnlyReason}>- <EventComposerCalendarPill- options={controller.calendarOptions()}- value={controller.selectedCalendarOption()}- onChange={(calendarId) =>- controller.setField('calendarId', calendarId)- }- disabled={formIsDisabled() || detailsLocked()}- readOnly={fieldIsReadOnly('calendar')}- />- </LockedField>- <LockedField reason={props.detailsReadOnlyReason}>- <EventComposerRecurrencePill- options={controller.recurrenceOptions()}- value={controller.selectedRecurrenceOption()}- onChange={controller.changeRecurrenceChoice}- disabled={fieldIsDisabled('recurrence')}- // A single occurrence has no recurrence rule of its own, so the- // recurrence cannot be edited while the scope is one event.- readOnly={editScope() === 'this_event'}- readOnlyReason={recurrenceScopeReason()}- describedBy={recurrenceDescribedBy()}- />- </LockedField>- <Show when={!isOutOfOffice()}>- <EventComposerGuestsPill- options={controller.guestOptions}- selected={controller.selectedGuests()}- onChange={controller.setSelectedGuests}- disabled={formIsDisabled()}- readOnly={fieldIsReadOnly('guests')}- readOnlyReason={props.guestsReadOnlyReason}- guestListHidden={props.guestListHidden}- currentGuests={- props.addOnlyGuests ? controller.initialGuests() : undefined- }- />- {props.guestsAction}- <LockedField reason={props.detailsReadOnlyReason}>- <EventComposerConferencePill- value={state().conference}- provider={capabilities()?.conferenceProvider}- macroCallsEnabled={props.macroCallsEnabled}- canKeepExisting={- controller.initialConferenceChoice() === 'existing'- }- onChange={(conference) =>- controller.setField('conference', conference)- }- disabled={- fieldIsDisabled('conference') || conferenceLocked()- }- />- </LockedField>- <LockedField reason={props.detailsReadOnlyReason}>- <EventComposerLocationPill- value={state().location}- onChange={(location) =>- controller.setField('location', location)- }- disabled={fieldIsDisabled('location')}- />- </LockedField>- </Show>- <Show when={isOutOfOffice()}>- <Show- when={capabilities()?.autoDecline !== false}- fallback={- <span class="text-xs text-ink-muted">- Outlook blocks this time. Configure automatic declines in- Outlook.- </span>- }- >- <EventComposerDeclinePill- value={state().outOfOffice}- onChange={controller.setOutOfOffice}- disabled={fieldIsDisabled('outOfOffice')}- />- </Show>- <Show- when={- state().outOfOffice &&- state().outOfOffice?.autoDeclineMode !== 'decline_none'- }- >- <EventComposerDeclineMessagePill- value={state().outOfOffice?.declineMessage ?? ''}- onChange={(declineMessage) =>- controller.setOutOfOffice({- autoDeclineMode:- state().outOfOffice?.autoDeclineMode ??- 'decline_none',- declineMessage,- })- }- disabled={fieldIsDisabled('outOfOffice')}- />- </Show>- </Show>- <EventComposerRemindersPill- minutes={controller.reminderMinutes()}- usedSlots={- controller.reminderMinutes().length +- controller.preservedReminderCount()- }- canAdd={controller.canAddReminder()}- onChange={controller.setReminderMinutes}- disabled={fieldIsDisabled('reminders')}- />- </div>- <Show when={recurrenceScopeReason()}>- {(reason) => (- <p id={recurrenceReasonId} class="text-xs text-ink-muted">- {reason()}- </p>- )}- </Show>+ <EventFormParts.Properties />+ <EventFormParts.RecurrenceScopeReason /></div>-- {/* Outlook has no guest permissions, and an out-of-office event- no guests. */}- <Show- when={- props.guestPolicyEditable &&- capabilities()?.guestPolicy !== false &&- !isOutOfOffice()- }- >- {/* The policy belongs to the whole series, like its recurrence. */}- <EventGuestPolicyRow- value={controller.guestPolicy()}- onChange={controller.setGuestPolicy}- disabled={formIsDisabled() || editScope() === 'this_event'}- disabledReason={- editScope() === 'this_event'- ? 'Guest permissions apply to all events. Choose All events to change them.'- : undefined- }- />- </Show>- <Show when={props.detailsReadOnlyReason}>- {(reason) => <p class="text-xs text-ink-muted">{reason()}</p>}- </Show>- <Show when={conferenceLocked()}>- <p class="text-xs text-ink-muted">- Microsoft keeps the online meeting link on an existing event. To- remove it, use “Replace event” after saving or discarding your- edits without a meeting link.- </p>- </Show>- <Show when={controller.conferenceError()}>- {(error) => (- <p role="alert" class="text-sm text-warning">- {error()}- </p>- )}- </Show>- <Show when={outOfOfficeNotice()}>- {(notice) => (- <div- role="note"- aria-label="Out-of-office event"- class="flex min-w-0 flex-col gap-1 rounded-lg border border-warning/40 bg-warning-bg p-3 text-xs text-warning-ink"- >- <span class="font-medium">Out-of-office event</span>- <span>{notice().effect}</span>- <Show- when={- controller.selectedCalendarOption()?.provider ===- 'outlook' &&- state().outOfOffice?.autoDeclineMode !== 'decline_none'- }- >- <span>- Macro checks for conflicts in the background while this- calendar is connected. Replies already sent cannot be undone- by changing this event.- </span>- </Show>- <Show when={notice().declineMessage}>- {(message) => (- <span class="italic">- Auto-decline reply: “{message()}”- </span>- )}- </Show>- </div>- )}- </Show>+ <EventFormParts.GuestPolicy />+ <EventFormParts.Notices /></div>-- <Show when={controller.recurrenceChoice() === 'custom'}>- <Layer depth={3}>- <div class="rounded-xl bg-surface p-4 text-ink">- <RecurrenceBuilder- value={controller.customConfig()}- start={controller.startForRecurrence()}- allDay={state().allDay}- disabled={- fieldIsDisabled('recurrence') || editScope() === 'this_event'- }- onChange={controller.setCustomConfig}- />- </div>- </Layer>- </Show>+ <EventFormParts.CustomRecurrence /></div>-- <Show when={props.saveError}>- <p role="alert" class="text-sm text-failure">- {props.saveError}- </p>- </Show>+ <EventFormParts.SaveError /><div class="flex shrink-0 items-center justify-end gap-3">- <Show when={props.showRecurringEditNotice}>- <RadioGroup- size="sm"- value={editScope()}- onChange={(value) => changeEditScope(value as CalendarUpdateScope)}- disabled={formIsDisabled()}- aria-label="Apply changes to"- class="mr-auto flex-row items-center gap-3 text-xs text-ink-muted"- >- <For each={RECURRING_EDIT_SCOPE_OPTIONS}>- {(option) => (- <RadioGroup.Item value={option.scope} class="gap-1.5">- <RadioGroup.ItemControl />- <RadioGroup.ItemLabel>{option.label}</RadioGroup.ItemLabel>- </RadioGroup.Item>- )}- </For>- </RadioGroup>- </Show>- <Button- type="button"- variant="ghost"- disabled={formIsDisabled()}- onClick={props.onCancel}- >- Cancel- </Button>- <Button- type="submit"- variant="primary"- disabled={!controller.canSave() || formIsDisabled()}- aria-label={isEdit() ? 'Save' : 'Create event'}- >- <Show- when={props.pending}- fallback={isEdit() ? 'Save' : 'Create event'}- >- <SpinnerIcon class="size-4 animate-spin" />- </Show>- </Button>+ <EventFormParts.EditScope class="mr-auto" />+ <EventFormParts.Cancel />+ <EventFormParts.Submit /></div>- </form>+ </EventFormParts.Root>);}diff --git a/apps/web/src/features/calendar/components/composer/EventGuestPolicyRow.tsx b/apps/web/src/features/calendar/components/composer/EventGuestPolicyRow.tsxindex f30f8706ae..566778f472 100644--- a/apps/web/src/features/calendar/components/composer/EventGuestPolicyRow.tsx+++ b/apps/web/src/features/calendar/components/composer/EventGuestPolicyRow.tsx@@ -1,3 +1,4 @@+import { MobileDrawer } from '@components/app/mobile/MobileDrawer';import type { GuestPolicy } from '@service-storage/generated/schemas/guestPolicy';import { Checkbox } from '@ui';import { createUniqueId, For, Show } from 'solid-js';@@ -17,18 +18,27 @@ export interface EventGuestPolicyRowProps {disabledReason?: string;}-/**- * What guests may do with the event. As in Google Calendar, guests who may- * modify the event may also invite others.- */-export function EventGuestPolicyRow(props: EventGuestPolicyRowProps) {+/** As in Google Calendar, guests who may modify the event may also invite others. */+function createGuestPolicyEditor(props: EventGuestPolicyRowProps) {const labelId = `event-guest-permissions-${createUniqueId()}`;- const reasonId = `${labelId}-reason`;- const change = (key: keyof GuestPolicy, checked: boolean) => {- const next = { ...props.value, [key]: checked };- if (next.canModify) next.canInviteOthers = true;- props.onChange(next);+ return {+ labelId,+ reasonId: `${labelId}-reason`,+ change: (key: keyof GuestPolicy, checked: boolean) => {+ const next = { ...props.value, [key]: checked };+ if (next.canModify) next.canInviteOthers = true;+ props.onChange(next);+ },+ isDisabled: (key: keyof GuestPolicy) =>+ props.disabled === true ||+ (key === 'canInviteOthers' && props.value.canModify),};+}++/** What guests may do with the event, on one line. */+export function EventGuestPolicyRow(props: EventGuestPolicyRowProps) {+ const { labelId, reasonId, change, isDisabled } =+ createGuestPolicyEditor(props);return (<div@@ -45,10 +55,7 @@ export function EventGuestPolicyRow(props: EventGuestPolicyRowProps) {<Checkboxchecked={props.value[permission.key]}onChange={(checked) => change(permission.key, checked)}- disabled={- props.disabled ||- (permission.key === 'canInviteOthers' && props.value.canModify)- }+ disabled={isDisabled(permission.key)}class="touch:min-h-[44px]"><Checkbox.Control />@@ -66,3 +73,46 @@ export function EventGuestPolicyRow(props: EventGuestPolicyRowProps) {</div>);}++/** What guests may do with the event, one permission per row, for a touch sheet. */+export function EventGuestPolicyRows(props: EventGuestPolicyRowProps) {+ const { labelId, reasonId, change, isDisabled } =+ createGuestPolicyEditor(props);++ return (+ <div+ role="group"+ aria-labelledby={labelId}+ aria-describedby={props.disabledReason ? reasonId : undefined}+ class="flex min-w-0 flex-col gap-1"+ >+ <span id={labelId} class="px-4 text-xs font-medium text-ink-muted">+ Guest permissions+ </span>+ <MobileDrawer.Section class="mx-0">+ <For each={GUEST_PERMISSIONS}>+ {(permission) => (+ <Checkbox+ checked={props.value[permission.key]}+ onChange={(checked) => change(permission.key, checked)}+ disabled={isDisabled(permission.key)}+ class="min-h-11 w-full justify-between px-3"+ >+ <Checkbox.Label class="text-sm text-ink">+ {permission.label}+ </Checkbox.Label>+ <Checkbox.Control />+ </Checkbox>+ )}+ </For>+ </MobileDrawer.Section>+ <Show when={props.disabledReason}>+ {(reason) => (+ <span id={reasonId} class="px-4 text-xs text-ink-extra-muted">+ {reason()}+ </span>+ )}+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/calendar/components/composer/EventGuestsEditor.tsx b/apps/web/src/features/calendar/components/composer/EventGuestsEditor.tsxindex 487b8ef2b5..9058f87c7e 100644--- a/apps/web/src/features/calendar/components/composer/EventGuestsEditor.tsx+++ b/apps/web/src/features/calendar/components/composer/EventGuestsEditor.tsx@@ -70,6 +70,8 @@ export function EventGuestPicker(props: {excluded?: SelectedEventEditorGuest[];onChange: (selected: SelectedEventEditorGuest[]) => void;onClose: () => void;+ /** Fill a sized container, such as a sheet, rather than a popover's height. */+ fillHeight?: boolean;}) {const known = () => [...(props.excluded ?? []), ...props.selected];const users = createMemo((): IUser[] => {@@ -93,6 +95,7 @@ export function EventGuestPicker(props: {users,excludedIds,allowCustomEmail: true,+ fillHeight: props.fillHeight,}}selectedOptions={() => new Set(props.selected.map((guest) => guest.id))}setSelectedOptions={(ids) => {diff --git a/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx b/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsxindex 1d86b4b89d..22a5a689b3 100644--- a/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx+++ b/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx@@ -1,3 +1,4 @@+import { PickerSheet } from '@components/app/mobile/PickerSheet';import BellSimpleIcon from '@icon/system/regular/bell-simple.svg';import CalendarDotsIcon from '@icon/system/regular/calendar-dots.svg';import CalendarXIcon from '@icon/system/regular/calendar-x.svg';@@ -17,7 +18,7 @@ import { PropertyCaret } from '@property/extractors/PropertyCaret';import { PropertyPill } from '@property/extractors/PropertyPill';import type { EntityProperty } from '@property/types';import type { EventType } from '@service-storage/generated/schemas/eventType';-import { cn, Layer, Select, Tooltip } from '@ui';+import { cn, Layer, Select, Tabs, Tooltip } from '@ui';import { type Accessor, createMemo, createSignal, For, Show } from 'solid-js';import {formatReminderOffset,@@ -233,42 +234,126 @@ function GuestsPopoverEditor(props: {return (<Show when={ctx.editorOpen()}><EditorPopover portalScope="local">- <Show- when={props.currentGuests}- fallback={- <EventGuestPicker- options={props.options}- selected={props.selected}- onChange={props.onChange}- onClose={() => ctx.closeEditor()}- />- }- >- {(currentGuests) => {- const isCurrent = (guest: SelectedEventEditorGuest) =>- currentGuests().some(- (current) =>- guestEmail(current).toLowerCase() ===- guestEmail(guest).toLowerCase()- );- return (- <AddOnlyGuestsEditor- options={props.options}- current={currentGuests()}- added={props.selected.filter((guest) => !isCurrent(guest))}- onAddedChange={(added) =>- props.onChange([...currentGuests(), ...added])- }- onClose={() => ctx.closeEditor()}- />- );- }}- </Show>+ <GuestsEditor {...props} onClose={() => ctx.closeEditor()} /></EditorPopover></Show>);}+/** The add-only editor, or the picker, for guests chosen so far. */+function GuestsEditor(props: {+ selected: SelectedEventEditorGuest[];+ currentGuests?: SelectedEventEditorGuest[];+ options: Accessor<EventEditorGuestOption[]>;+ onChange: (selected: SelectedEventEditorGuest[]) => void;+ onClose: () => void;+ /** Fill a sized container, such as a sheet, rather than a popover's height. */+ fillHeight?: boolean;+}) {+ return (+ <Show+ when={props.currentGuests}+ fallback={+ <EventGuestPicker+ options={props.options}+ selected={props.selected}+ onChange={props.onChange}+ onClose={props.onClose}+ fillHeight={props.fillHeight}+ />+ }+ >+ {(currentGuests) => {+ const isCurrent = (guest: SelectedEventEditorGuest) =>+ currentGuests().some(+ (current) =>+ guestEmail(current).toLowerCase() ===+ guestEmail(guest).toLowerCase()+ );+ return (+ <AddOnlyGuestsEditor+ options={props.options}+ current={currentGuests()}+ added={props.selected.filter((guest) => !isCurrent(guest))}+ onAddedChange={(added) =>+ props.onChange([...currentGuests(), ...added])+ }+ onClose={props.onClose}+ />+ );+ }}+ </Show>+ );+}++/**+ * The guest editor in a sheet stacked over the composer's. Picks stay a+ * draft until Done; Cancel, or dismissing the sheet, drops them.+ */+function GuestsSheetEditor(props: {+ selected: SelectedEventEditorGuest[];+ currentGuests?: SelectedEventEditorGuest[];+ options: Accessor<EventEditorGuestOption[]>;+ onChange: (selected: SelectedEventEditorGuest[]) => void;+}) {+ const ctx = useProperty();+ // Undefined until the first pick, so each opening starts from the event's guests.+ const [draft, setDraft] = createSignal<SelectedEventEditorGuest[]>();+ const shown = () => draft() ?? props.selected;+ const cancel = () => {+ setDraft(undefined);+ ctx.closeEditor();+ };+ const done = () => {+ const picked = draft();+ if (picked) props.onChange(picked);+ cancel();+ };++ return (+ <PickerSheet.Root open={ctx.editorOpen()} onCancel={cancel}>+ <PickerSheet.Header title="Guests" onDone={done} />+ <PickerSheet.Body>+ <GuestsEditor+ selected={shown()}+ currentGuests={props.currentGuests}+ options={props.options}+ onChange={setDraft}+ onClose={cancel}+ fillHeight+ />+ </PickerSheet.Body>+ </PickerSheet.Root>+ );+}++/** The guest pill for a touch sheet: it opens the guests in a sheet of their own. */+export function EventComposerGuestsSheetPill(+ props: EventComposerGuestsPillProps+) {+ return (+ <Show+ when={props.readOnly}+ fallback={+ <PropertyRoot+ property={guestsAsProperty(props.selected)}+ canEdit={!props.disabled}+ >+ <GuestsPillTrigger {...props} />+ <GuestsSheetEditor+ selected={props.selected}+ currentGuests={props.currentGuests}+ options={props.options}+ onChange={props.onChange}+ />+ </PropertyRoot>+ }+ >+ <ReadOnlyEventComposerGuestsPill {...props} />+ </Show>+ );+}+/** Compact guest property pill with editable and read-only dropdown views. */export function EventComposerGuestsPill(props: EventComposerGuestsPillProps) {return (@@ -697,11 +782,12 @@ export interface EventComposerKindPillProps {readOnly?: boolean;}-/** Compact selector for the kind of event being created. */-export function EventComposerKindPill(props: EventComposerKindPillProps) {- // A read-only pill displays whatever type the event has, including- // status types the composer cannot create.- const options = createMemo<EventComposerKindOption[]>(() =>+/**+ * The kinds the composer offers; a read-only event shows whatever type it+ * has, including status types the composer cannot create.+ */+function createEventKindOptions(props: EventComposerKindPillProps) {+ return createMemo<EventComposerKindOption[]>(() =>props.readOnly? [{@@ -711,6 +797,28 @@ export function EventComposerKindPill(props: EventComposerKindPillProps) {]: EVENT_KIND_OPTIONS);+}++/** The kinds of event as selectable labels, for a touch sheet. */+export function EventComposerKindTabs(props: EventComposerKindPillProps) {+ const options = createEventKindOptions(props);+ return (+ <Tabs+ aria-label="Event kind"+ options={options()}+ value={eventKindOf(props.eventType)}+ onChange={(kind) => {+ if (!props.readOnly) props.onChange(kind);+ }}+ disabled={props.disabled}+ touch="pills"+ />+ );+}++/** Compact selector for the kind of event being created. */+export function EventComposerKindPill(props: EventComposerKindPillProps) {+ const options = createEventKindOptions(props);const selectedOption = () =>options().find((option) => option.value === eventKindOf(props.eventType)) ??options()[0];diff --git a/apps/web/src/features/calendar/components/composer/MobileEventForm.tsx b/apps/web/src/features/calendar/components/composer/MobileEventForm.tsxnew file mode 100644index 0000000000..33a643047c--- /dev/null+++ b/apps/web/src/features/calendar/components/composer/MobileEventForm.tsx@@ -0,0 +1,118 @@+import { DateTimeRange } from '@app/components/date-time-range/date-time-range-fields';+import { MobileDrawer } from '@components/app/mobile/MobileDrawer';+import { cn, ToggleSwitch } from '@ui';+import { type JSX, Show } from 'solid-js';+import { Portal } from 'solid-js/web';+import { EventFormParts } from './event-form-parts';+import { createEventForm, type EventFormProps } from './event-form-state';++/** A labelled row of a sheet section, its control on the right. */+function SheetRow(props: { label: string; children: JSX.Element }) {+ return (+ <div class="flex min-h-11 items-center justify-between gap-3 px-3">+ <span class="shrink-0 text-sm text-ink">{props.label}</span>+ <div class="flex min-w-0 flex-1 items-center justify-end gap-1">+ {props.children}+ </div>+ </div>+ );+}++/**+ * The create/edit event form in the touch bottom sheet: what and when first,+ * then the event's details, one per row.+ */+export function MobileEventForm(+ props: EventFormProps & {+ /** The sheet's pinned chrome, which keeps the save action in reach. */+ headerMount: HTMLElement;+ }+) {+ const form = createEventForm(props);++ return (+ // -mt-4 takes back the host's top padding: the sheet's pinned chrome+ // already separates the title from the handle.+ <EventFormParts.Root form={form} class={cn('-mt-4', props.class)}>+ <Portal mount={props.headerMount}>+ <div class="flex justify-end px-4 pb-1">+ <EventFormParts.Submit />+ </div>+ {/* Under the action that failed, so it shows however far the form+ is scrolled. */}+ <EventFormParts.SaveError class="px-4 pb-2" />+ </Portal>+ <div class="flex min-w-0 flex-col gap-6">+ <div class="flex min-w-0 flex-col gap-3">+ <div class="flex min-w-0 flex-col gap-1">+ <EventFormParts.Title />+ <EventFormParts.Description />+ </div>+ <EventFormParts.KindTabs />+ </div>++ <div class="flex min-w-0 flex-col gap-1">+ <MobileDrawer.Section class="mx-0">+ <ToggleSwitch+ class="min-h-11 w-full flex-row-reverse justify-between px-3"+ size="md"+ label="All-day"+ labelClass="text-sm text-ink"+ checked={form.state().allDay}+ disabled={form.fieldIsDisabled('allDay')}+ onChange={form.controller.setAllDay}+ />+ <EventFormParts.Range>+ <SheetRow label="Starts">+ <DateTimeRange.Start />+ </SheetRow>+ <SheetRow label="Ends">+ <DateTimeRange.End />+ </SheetRow>+ </EventFormParts.Range>+ <SheetRow label="Repeat">+ <EventFormParts.RecurrencePill />+ </SheetRow>+ </MobileDrawer.Section>+ <EventFormParts.RangeMessages />+ <EventFormParts.RecurrenceScopeReason />+ </div>+ <EventFormParts.CustomRecurrence />++ <MobileDrawer.Section class="mx-0">+ <SheetRow label="Calendar">+ <EventFormParts.CalendarPill />+ </SheetRow>+ <Show when={!form.isOutOfOffice()}>+ <SheetRow label="Guests">+ <EventFormParts.GuestsSheetPill />+ </SheetRow>+ <SheetRow label="Call">+ <EventFormParts.ConferencePill />+ </SheetRow>+ <SheetRow label="Location">+ <EventFormParts.LocationInput />+ </SheetRow>+ </Show>+ <Show when={form.isOutOfOffice()}>+ <SheetRow label="Declines">+ <EventFormParts.DeclinePill />+ </SheetRow>+ <Show when={form.showsDeclineMessage()}>+ <SheetRow label="Message">+ <EventFormParts.DeclineMessagePill />+ </SheetRow>+ </Show>+ </Show>+ <SheetRow label="Reminders">+ <EventFormParts.RemindersPill />+ </SheetRow>+ </MobileDrawer.Section>++ <EventFormParts.GuestPolicyRows />+ <EventFormParts.Notices />+ </div>+ <EventFormParts.EditScope />+ </EventFormParts.Root>+ );+}diff --git a/apps/web/src/features/calendar/components/composer/event-form-parts.tsx b/apps/web/src/features/calendar/components/composer/event-form-parts.tsxnew file mode 100644index 0000000000..4ec4b4f558--- /dev/null+++ b/apps/web/src/features/calendar/components/composer/event-form-parts.tsx@@ -0,0 +1,668 @@+import {+ DateTimeRange,+ DateTimeRangeFields,+} from '@app/components/date-time-range/date-time-range-fields';+import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';+import SpinnerIcon from '@icon/system/regular/spinner.svg';+import type { CalendarUpdateScope } from '@service-email/client';+import { Button, cn, Input, Layer, RadioGroup, Tooltip } from '@ui';+import {+ createContext,+ For,+ type JSX,+ type ParentProps,+ Show,+ useContext,+} from 'solid-js';+import {+ calendarDescriptionToEditorHtml,+ exportCalendarDescription,+} from '../../utils/calendar-description';+import {+ EventGuestPolicyRow,+ EventGuestPolicyRows,+} from './EventGuestPolicyRow';+import {+ EventComposerCalendarPill,+ EventComposerConferencePill,+ EventComposerDeclineMessagePill,+ EventComposerDeclinePill,+ EventComposerGuestsPill,+ EventComposerGuestsSheetPill,+ EventComposerKindPill,+ EventComposerKindTabs,+ EventComposerLocationPill,+ EventComposerRecurrencePill,+ EventComposerRemindersPill,+} from './EventPropertyPills';+import { EventTitleInput } from './EventTitleInput';+import type { EventFormState } from './event-form-state';+import { RecurrenceBuilder } from './RecurrenceBuilder';++/** Whether edits to a recurring event patch one occurrence or the whole series. */+const RECURRING_EDIT_SCOPE_OPTIONS = [+ { scope: 'this_event', label: 'This event' },+ { scope: 'all', label: 'All events' },+] as const satisfies readonly {+ scope: CalendarUpdateScope;+ label: string;+}[];++const EventFormPartsContext = createContext<EventFormState>();++function useEventForm() {+ const form = useContext(EventFormPartsContext);+ if (!form) throw new Error('EventFormParts must be rendered inside Root');+ return form;+}++/** Explains a locked field on hover and keyboard focus. */+function LockedField(props: ParentProps<{ reason?: string; class?: string }>) {+ return (+ <Show when={props.reason} fallback={props.children}>+ {(reason) => (+ <Tooltip as="span" label={reason()} tabIndex={0} class={props.class}>+ {props.children}+ </Tooltip>+ )}+ </Show>+ );+}++function Root(props: {+ form: EventFormState;+ class?: string;+ children: JSX.Element;+}) {+ return (+ <EventFormPartsContext.Provider value={props.form}>+ <form+ id={props.form.ids.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();+ props.form.submit();+ }}+ >+ {props.children}+ </form>+ </EventFormPartsContext.Provider>+ );+}++/** The start and end inline, with the range's error or past-event warning. */+function When() {+ const form = useEventForm();+ return (+ <div class="flex min-w-0 flex-col gap-1">+ <LockedField+ reason={form.props.detailsReadOnlyReason}+ class="block min-w-0"+ >+ <DateTimeRangeFields+ {...form.range}+ onAllDayChange={form.controller.setAllDay}+ allDayDisabled={form.fieldIsDisabled('allDay')}+ />+ </LockedField>+ <RangeMessages />+ </div>+ );+}++/** The event's start and end for a layout that places `DateTimeRange` parts itself. */+function Range(props: { children: JSX.Element }) {+ const form = useEventForm();+ return (+ <DateTimeRange.Root {...form.range}>{props.children}</DateTimeRange.Root>+ );+}++/** The range's error, or else a warning that the event is in the past. */+function RangeMessages() {+ const form = useEventForm();+ return (+ <>+ <Show when={form.controller.dateRangeError()}>+ {(error) => (+ <p+ id={form.ids.dateRangeError}+ role="alert"+ class="text-xs text-failure"+ >+ {error()}+ </p>+ )}+ </Show>+ <Show when={form.pastEventWarning()}>+ {(warning) => (+ <p+ id={form.ids.pastEventWarning}+ role="status"+ class="text-xs text-warning"+ >+ {warning()}+ </p>+ )}+ </Show>+ </>+ );+}++function Title() {+ const form = useEventForm();+ return (+ <LockedField reason={form.props.detailsReadOnlyReason} class="flex w-full">+ <EventTitleInput+ value={form.state().title}+ onChange={(value) => form.controller.setField('title', value)}+ autofocus={!form.isEdit()}+ disabled={form.fieldIsDisabled('title')}+ />+ </LockedField>+ );+}++function Description() {+ const form = useEventForm();+ // The editor cannot hand the provider's string back: Lexical re-serializes+ // whatever it loads. Only content that exports differently from what was+ // loaded counts as an edit, so an untouched description stays byte-for-byte+ // what the event was opened with.+ const initialDescription = form.state().description;+ let loadedDescription: string | undefined;++ const descriptionEditor = () => (+ <MarkdownTextarea+ resolveAppLink={form.resolveAppLink}+ type="calendar"+ initialHtml={calendarDescriptionToEditorHtml(initialDescription)}+ editable={() => !form.fieldIsDisabled('description')}+ onInitialized={(editor) => {+ loadedDescription = exportCalendarDescription(editor);+ }}+ onChange={(_markdown, editor) => {+ if (!editor) return;+ const next = exportCalendarDescription(editor);+ form.controller.setField(+ 'description',+ next === loadedDescription ? initialDescription : next+ );+ }}+ placeholder="Add description..."+ portalScope="local"+ domRef={(element) => element.setAttribute('aria-label', 'Description')}+ class="h-full w-full bg-transparent px-2 text-sm text-ink outline-none"+ />+ );++ return (+ // Google rejects a description on an out-of-office event. The editor+ // re-initializes from the kind switch's reset state, so what it shows+ // always matches what a save submits.+ <Show when={!form.isOutOfOffice()}>+ <LockedField+ reason={form.props.detailsReadOnlyReason}+ class="block w-full"+ >+ <div class="h-12 overflow-y-auto">+ {/* The editor reads the description only when it mounts. Details+ that lock after a refused save return to the event's own, so+ the editor mounts again to show them. */}+ <Show+ when={form.fieldIsReadOnly('description')}+ fallback={descriptionEditor()}+ >+ {descriptionEditor()}+ </Show>+ </div>+ </LockedField>+ </Show>+ );+}++function KindPill() {+ const form = useEventForm();+ return (+ // Read-only on every edit, it opens its one value as a list; locked, it+ // is as unavailable as the other details.+ <LockedField reason={form.props.detailsReadOnlyReason}>+ <EventComposerKindPill+ eventType={form.state().eventType}+ onChange={form.controller.setEventKind}+ disabled={form.formIsDisabled() || form.detailsLocked()}+ readOnly={form.isEdit()}+ />+ </LockedField>+ );+}++/** The kinds of event as selectable labels, in place of `KindPill`. */+function KindTabs() {+ const form = useEventForm();+ return (+ <EventComposerKindTabs+ eventType={form.state().eventType}+ onChange={form.controller.setEventKind}+ disabled={form.formIsDisabled() || form.detailsLocked()}+ readOnly={form.isEdit()}+ />+ );+}++function CalendarPill() {+ const form = useEventForm();+ return (+ <LockedField reason={form.props.detailsReadOnlyReason}>+ <EventComposerCalendarPill+ options={form.controller.calendarOptions()}+ value={form.controller.selectedCalendarOption()}+ onChange={(calendarId) =>+ form.controller.setField('calendarId', calendarId)+ }+ disabled={form.formIsDisabled() || form.detailsLocked()}+ readOnly={form.fieldIsReadOnly('calendar')}+ />+ </LockedField>+ );+}++function RecurrencePill() {+ const form = useEventForm();+ return (+ <LockedField reason={form.props.detailsReadOnlyReason}>+ <EventComposerRecurrencePill+ options={form.controller.recurrenceOptions()}+ value={form.controller.selectedRecurrenceOption()}+ onChange={form.controller.changeRecurrenceChoice}+ disabled={form.fieldIsDisabled('recurrence')}+ // A single occurrence has no recurrence rule of its own, so the+ // recurrence cannot be edited while the scope is one event.+ readOnly={form.editScope() === 'this_event'}+ readOnlyReason={form.recurrenceScopeReason()}+ describedBy={form.recurrenceDescribedBy()}+ />+ </LockedField>+ );+}++/** The guests, then the host's action beside them, such as forwarding. */+function GuestsPill() {+ const form = useEventForm();+ return (+ <>+ <EventComposerGuestsPill {...form.guests} />+ {form.props.guestsAction}+ </>+ );+}++/** `GuestsPill` for a touch sheet, editing the guests in a sheet of their own. */+function GuestsSheetPill() {+ const form = useEventForm();+ return (+ <>+ <EventComposerGuestsSheetPill {...form.guests} />+ {form.props.guestsAction}+ </>+ );+}++function ConferencePill() {+ const form = useEventForm();+ return (+ <LockedField reason={form.props.detailsReadOnlyReason}>+ <EventComposerConferencePill+ value={form.state().conference}+ provider={form.capabilities()?.conferenceProvider}+ macroCallsEnabled={form.props.macroCallsEnabled}+ canKeepExisting={+ form.controller.initialConferenceChoice() === 'existing'+ }+ onChange={(conference) =>+ form.controller.setField('conference', conference)+ }+ disabled={form.fieldIsDisabled('conference') || form.conferenceLocked()}+ />+ </LockedField>+ );+}++function LocationPill() {+ const form = useEventForm();+ return (+ <LockedField reason={form.props.detailsReadOnlyReason}>+ <EventComposerLocationPill+ value={form.state().location}+ onChange={(location) => form.controller.setField('location', location)}+ disabled={form.fieldIsDisabled('location')}+ />+ </LockedField>+ );+}++/**+ * The location as a text field, for a sheet row: inside the sheet's scroll it+ * stays above the keyboard, where a popover would float off with its pill.+ */+function LocationInput() {+ const form = useEventForm();+ return (+ <Input+ size="sm"+ class="w-full"+ value={form.state().location}+ onInput={(event) =>+ form.controller.setField('location', event.currentTarget.value)+ }+ placeholder="Add location"+ aria-label="Location"+ disabled={form.fieldIsDisabled('location')}+ />+ );+}++/** How an out-of-office event declines meetings, where the calendar can. */+function DeclinePill() {+ const form = useEventForm();+ return (+ <Show+ when={form.capabilities()?.autoDecline !== false}+ fallback={+ <span class="text-xs text-ink-muted">+ Outlook blocks this time. Configure automatic declines in Outlook.+ </span>+ }+ >+ <EventComposerDeclinePill+ value={form.state().outOfOffice}+ onChange={form.controller.setOutOfOffice}+ disabled={form.fieldIsDisabled('outOfOffice')}+ />+ </Show>+ );+}++/** The reply to declined meetings; shown while `showsDeclineMessage`. */+function DeclineMessagePill() {+ const form = useEventForm();+ const state = form.state;+ return (+ <EventComposerDeclineMessagePill+ value={state().outOfOffice?.declineMessage ?? ''}+ onChange={(declineMessage) =>+ form.controller.setOutOfOffice({+ autoDeclineMode:+ state().outOfOffice?.autoDeclineMode ?? 'decline_none',+ declineMessage,+ })+ }+ disabled={form.fieldIsDisabled('outOfOffice')}+ />+ );+}++function RemindersPill() {+ const form = useEventForm();+ const controller = form.controller;+ return (+ <EventComposerRemindersPill+ minutes={controller.reminderMinutes()}+ usedSlots={+ controller.reminderMinutes().length ++ controller.preservedReminderCount()+ }+ canAdd={controller.canAddReminder()}+ onChange={controller.setReminderMinutes}+ disabled={form.fieldIsDisabled('reminders')}+ />+ );+}++/** Every event pill on one wrapping line. */+function Properties() {+ const form = useEventForm();+ return (+ <div class="flex min-w-0 flex-wrap items-center gap-2">+ <KindPill />+ <CalendarPill />+ <RecurrencePill />+ <Show when={!form.isOutOfOffice()}>+ <GuestsPill />+ <ConferencePill />+ <LocationPill />+ </Show>+ <Show when={form.isOutOfOffice()}>+ <DeclinePill />+ <Show when={form.showsDeclineMessage()}>+ <DeclineMessagePill />+ </Show>+ </Show>+ <RemindersPill />+ </div>+ );+}++function RecurrenceScopeReason() {+ const form = useEventForm();+ return (+ <Show when={form.recurrenceScopeReason()}>+ {(reason) => (+ <p id={form.ids.recurrenceReason} class="text-xs text-ink-muted">+ {reason()}+ </p>+ )}+ </Show>+ );+}++function GuestPolicy() {+ const form = useEventForm();+ return (+ <Show when={form.showsGuestPolicy()}>+ {/* The policy belongs to the whole series, like its recurrence. */}+ <EventGuestPolicyRow {...form.guestPolicy} />+ </Show>+ );+}++/** Guest permissions one per row, in place of `GuestPolicy`. */+function GuestPolicyRows() {+ const form = useEventForm();+ return (+ <Show when={form.showsGuestPolicy()}>+ <EventGuestPolicyRows {...form.guestPolicy} />+ </Show>+ );+}++/** Why details are locked, conferencing limits, and the out-of-office disclosure. */+function Notices() {+ const form = useEventForm();+ const state = form.state;+ return (+ <>+ <Show when={form.props.detailsReadOnlyReason}>+ {(reason) => <p class="text-xs text-ink-muted">{reason()}</p>}+ </Show>+ <Show when={form.conferenceLocked()}>+ <p class="text-xs text-ink-muted">+ Microsoft keeps the online meeting link on an existing event. To+ remove it, use “Replace event” after saving or discarding your edits+ without a meeting link.+ </p>+ </Show>+ <Show when={form.controller.conferenceError()}>+ {(error) => (+ <p role="alert" class="text-sm text-warning">+ {error()}+ </p>+ )}+ </Show>+ <Show when={form.outOfOfficeNotice()}>+ {(notice) => (+ <div+ role="note"+ aria-label="Out-of-office event"+ class="flex min-w-0 flex-col gap-1 rounded-lg border border-warning/40 bg-warning-bg p-3 text-xs text-warning-ink"+ >+ <span class="font-medium">Out-of-office event</span>+ <span>{notice().effect}</span>+ <Show+ when={+ form.controller.selectedCalendarOption()?.provider ===+ 'outlook' &&+ state().outOfOffice?.autoDeclineMode !== 'decline_none'+ }+ >+ <span>+ Macro checks for conflicts in the background while this calendar+ is connected. Replies already sent cannot be undone by changing+ this event.+ </span>+ </Show>+ <Show when={notice().declineMessage}>+ {(message) => (+ <span class="italic">Auto-decline reply: “{message()}”</span>+ )}+ </Show>+ </div>+ )}+ </Show>+ </>+ );+}++function CustomRecurrence() {+ const form = useEventForm();+ return (+ <Show when={form.controller.recurrenceChoice() === 'custom'}>+ <Layer depth={3}>+ <div class="rounded-xl bg-surface p-4 text-ink">+ <RecurrenceBuilder+ value={form.controller.customConfig()}+ start={form.controller.startForRecurrence()}+ allDay={form.state().allDay}+ disabled={+ form.fieldIsDisabled('recurrence') ||+ form.editScope() === 'this_event'+ }+ onChange={form.controller.setCustomConfig}+ />+ </div>+ </Layer>+ </Show>+ );+}++/** Why the last save failed; `class` places it. */+function SaveError(props: { class?: string }) {+ const form = useEventForm();+ return (+ <Show when={form.props.saveError}>+ <p role="alert" class={cn('text-sm text-failure', props.class)}>+ {form.props.saveError}+ </p>+ </Show>+ );+}++/** Whether a recurring edit applies to one event or the series; `class` places it. */+function EditScope(props: { class?: string }) {+ const form = useEventForm();+ return (+ <Show when={form.props.showRecurringEditNotice}>+ <RadioGroup+ size="sm"+ value={form.editScope()}+ onChange={(value) => form.changeEditScope(value as CalendarUpdateScope)}+ disabled={form.formIsDisabled()}+ aria-label="Apply changes to"+ class={cn(+ 'flex-row items-center gap-3 text-xs text-ink-muted',+ props.class+ )}+ >+ <For each={RECURRING_EDIT_SCOPE_OPTIONS}>+ {(option) => (+ <RadioGroup.Item value={option.scope} class="gap-1.5">+ <RadioGroup.ItemControl />+ <RadioGroup.ItemLabel>{option.label}</RadioGroup.ItemLabel>+ </RadioGroup.Item>+ )}+ </For>+ </RadioGroup>+ </Show>+ );+}++function Cancel() {+ const form = useEventForm();+ return (+ <Button+ type="button"+ variant="ghost"+ disabled={form.formIsDisabled()}+ onClick={form.props.onCancel}+ >+ Cancel+ </Button>+ );+}++function Submit() {+ const form = useEventForm();+ const label = () => (form.isEdit() ? 'Save' : 'Create event');+ return (+ <Button+ type="submit"+ // Names the form so the action submits it from pinned sheet chrome too.+ form={form.ids.form}+ variant="primary"+ disabled={!form.controller.canSave() || form.formIsDisabled()}+ aria-label={label()}+ >+ <Show when={form.props.pending} fallback={label()}>+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ );+}++/**+ * Parts of the event form. A layout creates the state with `createEventForm`,+ * hands it to `Root`, and arranges the parts it shows.+ */+export const EventFormParts = {+ Root,+ When,+ Range,+ RangeMessages,+ Title,+ Description,+ Properties,+ KindPill,+ KindTabs,+ CalendarPill,+ RecurrencePill,+ GuestsPill,+ GuestsSheetPill,+ ConferencePill,+ LocationPill,+ LocationInput,+ DeclinePill,+ DeclineMessagePill,+ RemindersPill,+ RecurrenceScopeReason,+ GuestPolicy,+ GuestPolicyRows,+ Notices,+ CustomRecurrence,+ SaveError,+ EditScope,+ Cancel,+ Submit,+};diff --git a/apps/web/src/features/calendar/components/composer/event-form-state.ts b/apps/web/src/features/calendar/components/composer/event-form-state.tsnew file mode 100644index 0000000000..e822def06f--- /dev/null+++ b/apps/web/src/features/calendar/components/composer/event-form-state.ts@@ -0,0 +1,238 @@+import type { DateTimeRangeProps } from '@app/components/date-time-range/date-time-range-fields';+import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';+import type { CalendarUpdateScope } from '@service-email/client';+import type { JSX } from 'solid-js';+import { createEffect, createSignal, createUniqueId } from 'solid-js';+import type { CalendarEventFormController } from './create-calendar-event-form-controller';+import type { EventGuestPolicyRowProps } from './EventGuestPolicyRow';+import type { EventComposerGuestsPillProps } from './EventPropertyPills';+import type {+ EventEditorDisabledFields,+ EventEditorSubmitValues,+} from './event-form-model';+import { outOfOfficeNoticeFor } from './out-of-office';++export interface EventFormProps {+ controller: CalendarEventFormController;+ /** Whether this host can create and attach Macro call links. */+ macroCallsEnabled: boolean;+ isEdit?: boolean;+ disabledFields?: EventEditorDisabledFields;+ /** The viewer may add guests but not remove the event's current ones. */+ addOnlyGuests?: boolean;+ /** Why a read-only guest list cannot change. */+ guestsReadOnlyReason?: string;+ /** An action beside the guests, such as forwarding the invitation. */+ guestsAction?: JSX.Element;+ /** The organizer hides the guest list, so the seeded guests are not all of them. */+ guestListHidden?: boolean;+ /** Whether the viewer may set what guests may do, as the organizer. */+ guestPolicyEditable?: boolean;+ /**+ * Why the event's title, time, description, location, recurrence and+ * conferencing cannot change.+ */+ detailsReadOnlyReason?: string;+ showRecurringEditNotice?: boolean;+ /** Disable interaction without presenting the form as an in-flight save. */+ disabled?: boolean;+ pending: boolean;+ saveError?: string;+ class?: string;+ onCalendarChange?: (calendarId: string, color: string) => void;+ onDirtyChange?: (dirty: boolean) => void;+ onCancel: () => void;+ onSubmit: (+ values: EventEditorSubmitValues,+ scope?: CalendarUpdateScope+ ) => void;+}++/**+ * Field locks, edit scope, and submission for one event form, shared by the+ * desktop and mobile layouts through the `EventFormParts`.+ */+export function createEventForm(props: EventFormProps) {+ const formId = createUniqueId();+ const ids = {+ form: `event-composer-${formId}`,+ dateRangeError: `event-composer-date-range-error-${formId}`,+ recurrenceReason: `event-composer-recurrence-reason-${formId}`,+ pastEventWarning: `event-composer-past-event-warning-${formId}`,+ };++ const controller = props.controller;+ const state = controller.state;+ const isEdit = () => props.isEdit ?? false;+ const formIsDisabled = () => props.pending || props.disabled === true;++ // Recurring edits default to the whole series, matching the long-standing+ // behavior; "this event" writes a single-occurrence exception.+ const [editScope, setEditScope] = createSignal<CalendarUpdateScope>('all');+ // Guest permissions belong to the whole series, so an occurrence edit+ // returns them to what is stored rather than keep an edit it cannot save.+ const changeEditScope = (scope: CalendarUpdateScope) => {+ setEditScope(scope);+ if (scope === 'this_event') controller.resetGuestPolicy();+ };++ // An invalid range already speaks for itself; only one line shows at a time.+ const pastEventWarning = () =>+ controller.dateRangeError() ? undefined : controller.pastEventWarning();+ const dateRangeDescribedBy = () => {+ if (controller.dateRangeError()) return ids.dateRangeError;+ return pastEventWarning() ? ids.pastEventWarning : undefined;+ };++ const fieldIsReadOnly = (field: keyof EventEditorDisabledFields) =>+ props.disabledFields?.[field] === true;+ const fieldIsDisabled = (field: keyof EventEditorDisabledFields) =>+ formIsDisabled() || fieldIsReadOnly(field);+ /** The event's start and end, bound for either range layout. */+ const range: DateTimeRangeProps = {+ subject: 'event',+ get start() {+ return state().start;+ },+ get end() {+ return state().end;+ },+ get allDay() {+ return state().allDay;+ },+ onStartChange: controller.setStart,+ onEndChange: controller.setEnd,+ get startDisabled() {+ return fieldIsDisabled('start');+ },+ get endDisabled() {+ return fieldIsDisabled('end');+ },+ get invalid() {+ return controller.dateRangeError() !== undefined;+ },+ get describedBy() {+ return dateRangeDescribedBy();+ },+ };+ const detailsLocked = () => props.detailsReadOnlyReason !== undefined;+ // A single occurrence has no repeat rule of its own; like the guest+ // permissions, the rule belongs to the whole series. A lock already says+ // why the rule cannot change.+ const recurrenceScopeReason = () =>+ editScope() === 'this_event' && !detailsLocked()+ ? 'The repeat rule applies to all events. Choose All events to change it.'+ : undefined;+ const recurrenceDescribedBy = () =>+ recurrenceScopeReason() ? ids.recurrenceReason : undefined;++ const capabilities = () => controller.selectedCalendarOption()?.capabilities;+ const conferenceLocked = () =>+ isEdit() &&+ capabilities()?.removeConference === false &&+ ['microsoft_teams', 'existing'].includes(+ controller.initialConferenceChoice()+ );+ const isOutOfOffice = () => controller.isOutOfOffice();+ // The decline settings of an edited event are unknown until picked, and the+ // disclosure must not claim behavior nobody chose.+ const outOfOfficeNotice = () => {+ const outOfOffice = state().outOfOffice;+ if (!isOutOfOffice() || !outOfOffice) return undefined;+ return outOfOfficeNoticeFor(+ outOfOffice.autoDeclineMode,+ outOfOffice.declineMessage+ );+ };++ const showsDeclineMessage = () =>+ !!state().outOfOffice &&+ state().outOfOffice?.autoDeclineMode !== 'decline_none';+ // Outlook has no guest permissions, and an out-of-office event no guests.+ const showsGuestPolicy = () =>+ props.guestPolicyEditable === true &&+ capabilities()?.guestPolicy !== false &&+ !isOutOfOffice();+ /** The guests, bound for either guest pill. */+ const guests: EventComposerGuestsPillProps = {+ options: controller.guestOptions,+ get selected() {+ return controller.selectedGuests();+ },+ onChange: controller.setSelectedGuests,+ get disabled() {+ return formIsDisabled();+ },+ get readOnly() {+ return fieldIsReadOnly('guests');+ },+ get readOnlyReason() {+ return props.guestsReadOnlyReason;+ },+ get guestListHidden() {+ return props.guestListHidden;+ },+ get currentGuests() {+ return props.addOnlyGuests ? controller.initialGuests() : undefined;+ },+ };+ const guestPolicy: EventGuestPolicyRowProps = {+ get value() {+ return controller.guestPolicy();+ },+ onChange: controller.setGuestPolicy,+ get disabled() {+ return formIsDisabled() || editScope() === 'this_event';+ },+ get disabledReason() {+ return editScope() === 'this_event'+ ? 'Guest permissions apply to all events. Choose All events to change them.'+ : undefined;+ },+ };++ createEffect(() => {+ const option = controller.selectedCalendarOption();+ if (option) props.onCalendarChange?.(option.id, option.color);+ });+ createEffect(() => props.onDirtyChange?.(controller.isDirty()));++ const submit = () => {+ const values = controller.submitValues();+ if (!values || formIsDisabled()) return;+ props.onSubmit(+ values,+ props.showRecurringEditNotice ? editScope() : undefined+ );+ };++ return {+ props,+ ids,+ controller,+ state,+ resolveAppLink: useMacroMentionLinkResolver(),+ isEdit,+ formIsDisabled,+ editScope,+ changeEditScope,+ pastEventWarning,+ range,+ fieldIsReadOnly,+ fieldIsDisabled,+ detailsLocked,+ recurrenceScopeReason,+ recurrenceDescribedBy,+ capabilities,+ conferenceLocked,+ isOutOfOffice,+ outOfOfficeNotice,+ showsDeclineMessage,+ showsGuestPolicy,+ guests,+ guestPolicy,+ submit,+ };+}++export type EventFormState = ReturnType<typeof createEventForm>;diff --git a/apps/web/src/features/calendar/hooks/use-event-editor.test.ts b/apps/web/src/features/calendar/hooks/use-event-editor.test.tsindex aa329ec79b..711e1aa43d 100644--- a/apps/web/src/features/calendar/hooks/use-event-editor.test.ts+++ b/apps/web/src/features/calendar/hooks/use-event-editor.test.ts@@ -504,6 +504,33 @@ describe('scheduling a Macro call', () => {}});+ it('reports the created event before it closes', async () => {+ const order: string[] = [];+ const created = vi.fn(() => order.push('created'));+ const [editor, dispose] = createRoot(+ (dispose) =>+ [+ useEventEditor({+ macroCallsEnabled: () => false,+ event: () => undefined,+ onCreated: created,+ onSaved: () => order.push('saved'),+ }),+ dispose,+ ] as const+ );+ try {+ await editor.save(values);+ expect(created).toHaveBeenCalledExactlyOnceWith({+ eventId: 'event-1',+ time: values.time,+ });+ expect(order).toEqual(['created', 'saved']);+ } finally {+ dispose();+ }+ });+it.each(['off', 'loading'] as const)('preserves an existing Macro link without syncing it while %s',async (state) => {diff --git a/apps/web/src/features/calendar/hooks/use-event-editor.ts b/apps/web/src/features/calendar/hooks/use-event-editor.tsindex 250f7f6a36..e9d24c35fb 100644--- a/apps/web/src/features/calendar/hooks/use-event-editor.ts+++ b/apps/web/src/features/calendar/hooks/use-event-editor.ts@@ -108,9 +108,17 @@ function hasTimeChanged(.otherwise(() => true);}+/** A new event's id and the time it was created with. */+export type CreatedCalendarEvent = {+ eventId: string;+ time: EventEditorSubmitValues['time'];+};+interface UseEventEditorProps {event: Accessor<CalendarEvent | undefined>;onSaved: () => void;+ /** Called with a new event once it exists, before `onSaved`. */+ onCreated?: (created: CreatedCalendarEvent) => void;macroCallsEnabled: Accessor<boolean>;/*** Whether the guest-invites rollout is on: a guest the organizer lets@@ -339,7 +347,7 @@ export function useEventEditor(props: UseEventEditorProps) {if (!event) {// The server mints the call and writes its link into the event, so// the one invitation attendees receive already carries it.- await create.mutateAsync({+ const created = await create.mutateAsync({title: values.title,time: values.time,calendarId: values.calendarId,@@ -357,6 +365,7 @@ export function useEventEditor(props: UseEventEditorProps) {...(values.outOfOffice ? { outOfOffice: values.outOfOffice } : {}),...(values.guestPolicy ? { guestPolicy: values.guestPolicy } : {}),});+ props.onCreated?.({ eventId: created.id, time: values.time });props.onSaved();return;}diff --git a/apps/web/src/features/command/Launcher.tsx b/apps/web/src/features/command/Launcher.tsxindex 47c3cb72fb..9e3eac27e9 100644--- a/apps/web/src/features/command/Launcher.tsx+++ b/apps/web/src/features/command/Launcher.tsx@@ -9,6 +9,7 @@ import { createSpreadsheetDocument } from '@app/features/block-spreadsheet/queriimport { isSpreadsheetEnabledForCurrentUser } from '@app/features/block-spreadsheet/queries/spreadsheet-access';import { EMAIL_COMPOSE_TO_INPUT_ID } from '@app/features/email-compose/core/constants';import { useQuickCallsFlag } from '@app/features/meetings/use-quick-calls-flag';+import { raiseKeyboardForNewTaskTitle } from '@app/features/task-composer/new-task-title-focus';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { t } from '@app/lib/i18n';import {@@ -380,6 +381,8 @@ export function runCreateAction(}).catch(reportCreateBlockError);return;case 'task':+ // Raise the keyboard within this gesture; the composer mounts later.+ raiseKeyboardForNewTaskTitle();createComponent({componentId: 'task-compose',asPopover: true,diff --git a/apps/web/src/features/property/component/PropertyValuePill.tsx b/apps/web/src/features/property/component/PropertyValuePill.tsxindex 8de3c4eb00..44796d15e8 100644--- a/apps/web/src/features/property/component/PropertyValuePill.tsx+++ b/apps/web/src/features/property/component/PropertyValuePill.tsx@@ -1,4 +1,5 @@import { type ComponentProps, type JSX, Match, Show, Switch } from 'solid-js';+import { Dynamic } from 'solid-js/web';import { Property } from '../property';import { getEntityValues, hasValue } from '../utils';@@ -16,6 +17,8 @@ type PropertyValuePillProps = Pick<entitySelfFilter?: ComponentProps<typeof Property.PopoverEditor>['entitySelfFilter'];+ /** The editor the pill opens; `Property.SheetEditor` inside a touch sheet. */+ editor?: typeof Property.PopoverEditor;};/** Controlled property pill shared by task and project composers. */@@ -84,7 +87,10 @@ export function PropertyValuePill(props: PropertyValuePillProps) {<Property.Caret /></Property.Pill></Property.Tooltip>- <Property.PopoverEditor entitySelfFilter={props.entitySelfFilter} />+ <Dynamic+ component={props.editor ?? Property.PopoverEditor}+ entitySelfFilter={props.entitySelfFilter}+ /></>);}}diff --git a/apps/web/src/features/property/core/Root.test.tsx b/apps/web/src/features/property/core/Root.test.tsxindex d8199420a7..20508b7466 100644--- a/apps/web/src/features/property/core/Root.test.tsx+++ b/apps/web/src/features/property/core/Root.test.tsx@@ -122,3 +122,58 @@ it('keeps a saving pick through ID assignment but not on another property', () =});expect(shown()).toBe('todo');});++function EditorToggle() {+ const ctx = useProperty();+ return (+ <>+ <button onClick={(event) => ctx.openEditor(event.currentTarget)}>+ Edit+ </button>+ <input aria-label="Search" />+ <button onClick={() => ctx.closeEditor()}>Close</button>+ </>+ );+}++function renderEditor() {+ render(() => (+ <>+ <input aria-label="Title" />+ <Root property={priority} canEdit>+ <EditorToggle />+ </Root>+ </>+ ));+ return {+ title: screen.getByLabelText('Title'),+ search: screen.getByLabelText('Search'),+ pill: screen.getByText('Edit'),+ };+}++const nextTask = () => new Promise((resolve) => setTimeout(resolve));++it('returns focus to the pill after the editor took it', async () => {+ const { search, pill } = renderEditor();++ pill.focus();+ fireEvent.click(pill);+ search.focus();+ fireEvent.click(screen.getByText('Close'));+ await nextTask();++ expect(document.activeElement).toBe(pill);+});++it('leaves focus in the field the editor found it in', async () => {+ const { title, pill } = renderEditor();++ // A touch pill opens without taking focus from the title.+ title.focus();+ fireEvent.click(pill);+ fireEvent.click(screen.getByText('Close'));+ await nextTask();++ expect(document.activeElement).toBe(title);+});diff --git a/apps/web/src/features/property/core/Root.tsx b/apps/web/src/features/property/core/Root.tsxindex c0eb0b92ad..4703c742b3 100644--- a/apps/web/src/features/property/core/Root.tsx+++ b/apps/web/src/features/property/core/Root.tsx@@ -89,14 +89,28 @@ export function Root(props: PropertyRootProps) {}};+ // A touch editor leaves focus in the field the user was typing in (a+ // composer's title), and a picker sheet hands it back there.+ let focusAtOpen: Element | null = null;+// Focus restoration helper - used by both closeEditor and onOpenChange// When a value is saved, the component may remount (due to reactive updates),// so we fall back to finding the trigger by property ID if the anchor is stale.const restoreFocusToAnchor = () => {const propertyId = local.property.propertyId;const anchor = editorAnchor();+ const focusedAtOpen = focusAtOpen;setTimeout(() => {+ // Focus is back where the editor found it; moving it to the pill would+ // drop the phone keyboard.+ if (+ focusedAtOpen &&+ focusedAtOpen !== document.body &&+ document.activeElement === focusedAtOpen+ )+ return;+// First try the stored anchor if it's still in the DOMif (anchor?.isConnected) {anchor.focus();@@ -126,6 +140,7 @@ export function Root(props: PropertyRootProps) {},editorOpen,openEditor: (anchor) => {+ focusAtOpen = document.activeElement;if (anchor) setEditorAnchor(() => anchor);setEditorOpen(true);},diff --git a/apps/web/src/features/property/editors/index.ts b/apps/web/src/features/property/editors/index.tsindex 54127ed04d..b81557d3bd 100644--- a/apps/web/src/features/property/editors/index.ts+++ b/apps/web/src/features/property/editors/index.ts@@ -6,4 +6,4 @@ export { InlineTextEditor } from './inline/InlineTextEditor';export { PropertyEditor } from './PropertyEditor';export {} from './popover/EntityEditor';-export { PopoverEditor } from './popover/PopoverEditor';+export { PopoverEditor, SheetEditor } from './popover/PopoverEditor';diff --git a/apps/web/src/features/property/editors/popover/DateEditor.tsx b/apps/web/src/features/property/editors/popover/DateEditor.tsxindex 437e02ffbb..5bee816094 100644--- a/apps/web/src/features/property/editors/popover/DateEditor.tsx+++ b/apps/web/src/features/property/editors/popover/DateEditor.tsx@@ -1,3 +1,4 @@+import { PickerSheet } from '@components/app/mobile/PickerSheet';import { fireAndForget } from '@core/util/fireAndForget';import { createSignal, Show } from 'solid-js';import { useProperty } from '../../core/context';@@ -21,7 +22,8 @@ export function DateEditor() {);}-function DateEditorBody() {+/** The date being picked, saved as soon as one is chosen. */+function createDateEditorState() {const ctx = useProperty();const property = ctx.property() as DateProperty;@@ -38,16 +40,65 @@ function DateEditorBody() {}};+ return {+ property,+ selectedDate,+ select: (date: Date | null) => {+ fireAndForget(commit(date), 'property-editor');+ },+ };+}++function DateEditorBody() {+ const ctx = useProperty();+ const state = createDateEditorState();+return (<EditorPopover><PropertyDateSelector- property={property}- selectedDate={selectedDate()}- onSelectDate={(date) => {- fireAndForget(commit(date), 'property-editor');- }}+ property={state.property}+ selectedDate={state.selectedDate()}+ onSelectDate={state.select}onClose={() => ctx.closeEditor()}/></EditorPopover>);}++/**+ * The date picker in a `PickerSheet` stacked over a touch sheet, with room for+ * its calendar above the keyboard. A pick applies at once and closes it, so+ * Done only closes.+ */+export function DateSheetEditor() {+ const ctx = useProperty();+ return (+ <Show when={isDateProperty(ctx.property())}>+ <PickerSheet.Root open={ctx.editorOpen()} onCancel={ctx.closeEditor}>+ <DateSheetBody />+ </PickerSheet.Root>+ </Show>+ );+}++function DateSheetBody() {+ const ctx = useProperty();+ const state = createDateEditorState();+ return (+ <>+ <PickerSheet.Header+ title={state.property.displayName}+ onDone={ctx.closeEditor}+ />+ <PickerSheet.Body>+ <PropertyDateSelector+ property={state.property}+ selectedDate={state.selectedDate()}+ onSelectDate={state.select}+ onClose={ctx.closeEditor}+ fillHeight+ />+ </PickerSheet.Body>+ </>+ );+}diff --git a/apps/web/src/features/property/editors/popover/EditorPopover.tsx b/apps/web/src/features/property/editors/popover/EditorPopover.tsxindex cd1e039706..e3dc814296 100644--- a/apps/web/src/features/property/editors/popover/EditorPopover.tsx+++ b/apps/web/src/features/property/editors/popover/EditorPopover.tsx@@ -1,4 +1,6 @@import { useIsInsideHoverCard } from '@core/component/HoverCard';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { isEditableInput } from '@core/util/isEditableInput';import { cn, Dropdown } from '@ui';import { type JSX, onCleanup, onMount, useContext } from 'solid-js';import { PropertyRootContext } from '../../core/context';@@ -26,8 +28,8 @@ type EditorPopoverProps = {* Floating shell for popover-style editors (date / select / entity). The* surrounding <Property.Root> (or any <Dropdown>) hosts a Kobalte DropdownMenu — this component* just renders the Content. Kobalte handles ESC, click-outside, focus- * trap, and focus return. `onClose` is invoked on dismissal so consumers can- * save-on-close.+ * trap, and focus return; on touch it leaves focus where it was. `onClose` is+ * invoked on dismissal so consumers can save-on-close.*/export function EditorPopover(props: EditorPopoverProps) {const ctx = useContext(PropertyRootContext);@@ -89,6 +91,26 @@ export function EditorPopover(props: EditorPopoverProps) {close();};+ // On touch the popover leaves focus where it was, so a phone keyboard+ // raised by the field behind it (a composer's title) stays up: opening+ // doesn't focus the menu, and taps outside its own fields don't move focus.+ const keepFocusOnOpen = (event: Event) => {+ if (isTouchDevice()) event.preventDefault();+ };+ // Kobalte's menu list also focuses the menu itself once it mounts, with no+ // option to opt out.+ const keepFocusOnMount = (content: HTMLElement) => {+ if (!isTouchDevice()) return;+ const focus = content.focus.bind(content);+ content.focus = (options) => {+ if (!isEditableInput(document.activeElement)) focus(options);+ };+ };+ const keepFocusOnTap = (event: PointerEvent | MouseEvent) => {+ if (isTouchDevice() && !isEditableInput(event.target as Element))+ event.preventDefault();+ };+return (// Virtual anchors normally use the body portal. Modal hosts opt into// their own portal scope to keep focus and outside interactions local.@@ -101,6 +123,10 @@ export function EditorPopover(props: EditorPopoverProps) {)}onInteractOutside={handleInteractOutside}onEscapeKeyDown={handleEscapeKeyDown}+ ref={keepFocusOnMount}+ onOpenAutoFocus={keepFocusOnOpen}+ onPointerDown={keepFocusOnTap}+ onMouseDown={keepFocusOnTap}depth={3}><Dropdown.Groupdiff --git a/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx b/apps/web/src/features/property/editors/popover/EntityEditor.test.tsxindex 97742b4feb..9b6e5a2940 100644--- a/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx+++ b/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx@@ -6,15 +6,15 @@ import {screen,waitFor,} from '@solidjs/testing-library';-import { createSignal, type ParentProps } from 'solid-js';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { createSignal, type ParentProps, Show } from 'solid-js';+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';import { SYSTEM_PROPERTY_IDS } from '../../constants';import {PropertyRootContext,type PropertyRootContextValue,} from '../../core/context';import type { EntityProperty } from '../../types';-import { EntityEditor } from './EntityEditor';+import { EntityEditor, EntitySheetEditor } from './EntityEditor';const agentId = 'bot|00000000-0000-0000-0000-000000000123';const userId = 'macro|[email protected]';@@ -104,6 +104,19 @@ vi.mock('../selectors/OptionCheckBox', () => ({<input type="checkbox" checked={props.checked} readOnly />),}));+vi.mock('@components/app/mobile/PickerSheet', () => ({+ PickerSheet: {+ Root: (props: ParentProps<{ open: boolean }>) => (+ <Show when={props.open}>+ <div role="dialog">{props.children}</div>+ </Show>+ ),+ Header: (props: { onDone: () => void }) => (+ <button onClick={props.onDone}>Done</button>+ ),+ Body: (props: ParentProps) => <>{props.children}</>,+ },+}));vi.mock('./EditorPopover', () => ({EditorPopover: (props: ParentProps<{ onClose: () => void }>) => (<div role="dialog">@@ -128,7 +141,8 @@ const property: EntityProperty = {function setup(selfFilter?: { entityType: EntityType; blockId?: string },- value = property+ value = property,+ Editor = EntityEditor) {const onSave = vi.fn(async () => undefined);const [editorOpen, setEditorOpen] = createSignal(true);@@ -142,12 +156,17 @@ function setup(};render(() => (<PropertyRootContext.Provider value={context}>- <EntityEditor selfFilter={selfFilter} />+ <Editor selfFilter={selfFilter} /></PropertyRootContext.Provider>));return onSave;}+beforeAll(() => {+ // A key press puts the list in keyboard mode, which scrolls its row into view.+ Element.prototype.scrollIntoView = vi.fn();+});+afterEach(cleanup);describe('assigning an agent through task and project properties', () => {@@ -233,6 +252,32 @@ describe('assigning an agent through task and project properties', () => {});});+describe('people in a picker sheet', () => {+ it('drops the picks on Escape and saves them on Done', async () => {+ const dropped = setup(undefined, property, EntitySheetEditor);+ fireEvent.click(screen.getByText('Research assistant'));+ fireEvent.keyDown(screen.getByPlaceholderText('Add assignees...'), {+ key: 'Escape',+ });+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(dropped).not.toHaveBeenCalled();+ cleanup();++ const onSave = setup(undefined, property, EntitySheetEditor);+ fireEvent.click(screen.getByText('Research assistant'));+ fireEvent.click(screen.getByText('Done'));+ await waitFor(() =>+ expect(onSave).toHaveBeenCalledExactlyOnceWith(property, {+ valueType: 'ENTITY',+ refs: [+ { entity_id: userId, entity_type: 'USER' },+ { entity_id: agentId, entity_type: 'USER' },+ ],+ })+ );+ });+});+describe('the Project property', () => {it('clears the project when the selected project is clicked again', async () => {const project: EntityProperty = {diff --git a/apps/web/src/features/property/editors/popover/EntityEditor.tsx b/apps/web/src/features/property/editors/popover/EntityEditor.tsxindex 82c8af4ddb..d3273d196d 100644--- a/apps/web/src/features/property/editors/popover/EntityEditor.tsx+++ b/apps/web/src/features/property/editors/popover/EntityEditor.tsx@@ -1,5 +1,7 @@+import { PickerSheet } from '@components/app/mobile/PickerSheet';import type { IUser } from '@core/user';import { idToDisplayName, idToEmail } from '@core/user/util';+import { fireAndForget } from '@core/util/fireAndForget';import { SYSTEM_PROPERTY_IDS } from '@property/constants';import {entityReferencesToIdSet,@@ -38,25 +40,14 @@ export function EntityEditor(props: EntityEditorProps) {);}-function EntityEditorBody(props: EntityEditorProps) {+/**+ * The staged selection for an ENTITY property, saved by `closeAndSave`. A+ * component calls it when its editor opens, so each opening starts from the+ * saved value.+ */+function createEntityEditorDraft() {const ctx = useProperty();const property = ctx.property() as EntityProperty;-- // Company owners are always teammates, so the owner picker offers the- // team roster instead of the default quick-access people pool.- const isCompanyOwner =- property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.COMPANY_OWNER;- const agents = useAgentAssignees(- () => property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.ASSIGNEES- );- const teamQuery = useCurrentTeamQuery();- const teamMembers = (): IUser[] =>- (teamQuery.data?.members ?? []).map((member) => ({- id: member.user_id,- email: idToEmail(member.user_id),- name: idToDisplayName(member.user_id),- }));-const initialRefs: EntityReference[] = property.value ?? [];const [selectedRefs, setSelectedRefs] =createSignal<EntityReference[]>(initialRefs);@@ -89,8 +80,48 @@ function EntityEditorBody(props: EntityEditorProps) {ctx.closeEditor();};+ return {+ property,+ selectedRefs,+ select: (refs: EntityReference[]) => {+ setSelectedRefs(refs);+ setDirty(true);+ },+ closeAndSave,+ };+}++type EntityEditorDraft = ReturnType<typeof createEntityEditorDraft>;++/** The entity picker over a draft, with the project-agents note. */+function EntityEditorSelector(+ props: EntityEditorProps & {+ draft: EntityEditorDraft;+ /** Fill a sized container, such as a sheet, rather than a popover's height. */+ fillHeight?: boolean;+ /** Escape in the search; saves the draft when absent, as a popover does. */+ onCancel?: () => void;+ }+) {+ const property = props.draft.property;++ // Company owners are always teammates, so the owner picker offers the+ // team roster instead of the default quick-access people pool.+ const isCompanyOwner =+ property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.COMPANY_OWNER;+ const agents = useAgentAssignees(+ () => property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.ASSIGNEES+ );+ const teamQuery = useCurrentTeamQuery();+ const teamMembers = (): IUser[] =>+ (teamQuery.data?.members ?? []).map((member) => ({+ id: member.user_id,+ email: idToEmail(member.user_id),+ name: idToDisplayName(member.user_id),+ }));+return (- <EditorPopover onClose={closeAndSave}>+ <><Suspensefallback={<div class="px-3 py-4 text-sm text-ink-muted">Loading...</div>@@ -104,18 +135,22 @@ function EntityEditorBody(props: EntityEditorProps) {selfFilter: props.selfFilter,users: isCompanyOwner ? teamMembers : undefined,additionalUsers: agents,+ fillHeight: props.fillHeight,}}- selectedOptions={() => entityReferencesToIdSet(selectedRefs())}+ selectedOptions={() =>+ entityReferencesToIdSet(props.draft.selectedRefs())+ }setSelectedOptions={(newOptions, entityInfo) => {- const updated = updateEntityReferences(- selectedRefs(),- newOptions,- entityInfo+ props.draft.select(+ updateEntityReferences(+ props.draft.selectedRefs(),+ newOptions,+ entityInfo+ ));- setSelectedRefs(updated);- setDirty(true);}}- onClose={closeAndSave}+ onClose={props.draft.closeAndSave}+ onCancel={props.onCancel}/></Suspense><Show@@ -130,6 +165,52 @@ function EntityEditorBody(props: EntityEditorProps) {teammates.</p></Show>+ </>+ );+}++function EntityEditorBody(props: EntityEditorProps) {+ const draft = createEntityEditorDraft();+ return (+ <EditorPopover onClose={draft.closeAndSave}>+ <EntityEditorSelector selfFilter={props.selfFilter} draft={draft} /></EditorPopover>);}++/**+ * ENTITY properties in a `PickerSheet` stacked over a touch sheet: picks stay+ * a draft until Done, and Cancel drops them. A single-choice picker applies+ * its pick at once.+ */+export function EntitySheetEditor(props: EntityEditorProps) {+ const ctx = useProperty();+ return (+ <Show when={isEntityProperty(ctx.property())}>+ <PickerSheet.Root open={ctx.editorOpen()} onCancel={ctx.closeEditor}>+ <EntitySheetBody selfFilter={props.selfFilter} />+ </PickerSheet.Root>+ </Show>+ );+}++function EntitySheetBody(props: EntityEditorProps) {+ const ctx = useProperty();+ const draft = createEntityEditorDraft();+ return (+ <>+ <PickerSheet.Header+ title={draft.property.displayName}+ onDone={() => fireAndForget(draft.closeAndSave(), 'property-editor')}+ />+ <PickerSheet.Body>+ <EntityEditorSelector+ selfFilter={props.selfFilter}+ draft={draft}+ fillHeight+ onCancel={ctx.closeEditor}+ />+ </PickerSheet.Body>+ </>+ );+}diff --git a/apps/web/src/features/property/editors/popover/PopoverEditor.tsx b/apps/web/src/features/property/editors/popover/PopoverEditor.tsxindex ff04b335ca..94e62e72c6 100644--- a/apps/web/src/features/property/editors/popover/PopoverEditor.tsx+++ b/apps/web/src/features/property/editors/popover/PopoverEditor.tsx@@ -1,9 +1,9 @@import type { EntityType } from '@service-properties/generated/schemas/entityType';import { Match, Switch } from 'solid-js';import { useProperty } from '../../core/context';-import { DateEditor } from './DateEditor';+import { DateEditor, DateSheetEditor } from './DateEditor';import { DateRangeEditor } from './DateRangeEditor';-import { EntityEditor } from './EntityEditor';+import { EntityEditor, EntitySheetEditor } from './EntityEditor';import { SelectEditor } from './SelectEditor';type PopoverEditorProps = {@@ -40,3 +40,25 @@ export function PopoverEditor(props: PopoverEditorProps) {</Switch>);}++/**+ * `PopoverEditor` for pills inside a touch sheet: ENTITY properties (people,+ * projects) and dates pick in a `PickerSheet` stacked over it; selects keep+ * their popovers, which fit above the keyboard.+ */+export function SheetEditor(props: PopoverEditorProps) {+ const ctx = useProperty();+ const type = () => ctx.property().valueType;+ return (+ <Switch+ fallback={<PopoverEditor entitySelfFilter={props.entitySelfFilter} />}+ >+ <Match when={type() === 'ENTITY'}>+ <EntitySheetEditor selfFilter={props.entitySelfFilter} />+ </Match>+ <Match when={type() === 'DATE'}>+ <DateSheetEditor />+ </Match>+ </Switch>+ );+}diff --git a/apps/web/src/features/property/editors/selectors/PropertyDateSelector.tsx b/apps/web/src/features/property/editors/selectors/PropertyDateSelector.tsxindex 730bc57bb4..813b673baa 100644--- a/apps/web/src/features/property/editors/selectors/PropertyDateSelector.tsx+++ b/apps/web/src/features/property/editors/selectors/PropertyDateSelector.tsx@@ -27,6 +27,8 @@ type DateSelectorProps = {initialQuery?: string;onSelectDate: (date: Date | null) => void;onClose?: () => void;+ /** Fill a sized container, such as a sheet, rather than a popover's height. */+ fillHeight?: boolean;};export const PropertyDateSelector = (props: DateSelectorProps) => {@@ -146,8 +148,12 @@ export const PropertyDateSelector = (props: DateSelectorProps) => {handleSelectDate(date);};+ const keepSearchFocus = (event: Event) => event.preventDefault();+return (- <div class="relative flex min-h-0 flex-col">+ <div+ class={cn('relative flex min-h-0 flex-col', props.fillHeight && 'flex-1')}+ ><div class="flex w-full shrink-0 items-center py-2 gap-2 px-2 border-b border-edge-muted"><SearchIcon class="size-4 text-ink-muted" /><input@@ -171,8 +177,20 @@ export const PropertyDateSelector = (props: DateSelectorProps) => {</div><Switch><Match when={mode() === 'search'}>- <div class="flex min-h-0 flex-1 p-1.5">- <div class="max-h-50 min-h-0 flex-1 overflow-y-auto overflow-x-hidden scrollbar-hidden">+ {/* Picking a row keeps focus in the date field, so the phone+ keyboard stays up. iOS devices still send mousedown after a+ cancelled pointerdown. */}+ <div+ class="flex min-h-0 flex-1 p-1.5"+ onPointerDown={keepSearchFocus}+ onMouseDown={keepSearchFocus}+ >+ <div+ class={cn(+ 'min-h-0 flex-1 overflow-y-auto overflow-x-hidden scrollbar-hidden',+ !props.fillHeight && 'max-h-50'+ )}+ ><Showwhen={visibleDateOptions().length > 0}fallback={@@ -197,7 +215,7 @@ export const PropertyDateSelector = (props: DateSelectorProps) => {<divdata-date-index={index()}class={cn(- 'group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default',+ 'group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default touch:min-h-12',index() === selectedIndex() && 'bg-hover')}onClick={() => handleSelectDate(option.date)}@@ -223,7 +241,7 @@ export const PropertyDateSelector = (props: DateSelectorProps) => {<divdata-date-index={calendarOptionIndex()}class={cn(- 'group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default',+ 'group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default touch:min-h-12',selectedIndex() === calendarOptionIndex() && 'bg-hover')}onClick={() => setMode('calendar')}@@ -248,7 +266,7 @@ export const PropertyDateSelector = (props: DateSelectorProps) => {<divdata-date-index={clearOptionIndex()}class={cn(- 'group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default',+ 'group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default touch:min-h-12',selectedIndex() === clearOptionIndex() && 'bg-hover')}onClick={() => handleClearDate()}diff --git a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsxindex 0b22bf1289..838e6e0345 100644--- a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx+++ b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx@@ -17,6 +17,7 @@ import { useSearchInputFocus } from '@property/utils';import { useSearchSoupQuery } from '@queries/soup/search';import type { EntityType } from '@service-properties/generated/schemas/entityType';import { debounce } from '@solid-primitives/scheduled';+import { cn } from '@ui';import * as EmailValidator from 'email-validator';import {createEffect,@@ -51,6 +52,8 @@ type EntityInputProps = {entityInfo?: { id: string; entity_type: EntityType }[]) => void;onClose?: () => void;+ /** Escape in the search; `onClose` when absent, as a popover saves on close. */+ onCancel?: () => void;pinnedOptions?: PinnedOption[];};@@ -454,9 +457,12 @@ export function PropertyEntitySelector(props: EntityInputProps) {useSearchInputFocus(() => searchInputRef);+ const fills = () => props.config.fillHeight === true;+ const keepSearchFocus = (event: Event) => event.preventDefault();+return (- <div>- <div class="relative">+ <div class={cn(fills() && 'flex min-h-0 flex-1 flex-col')}>+ <div class="relative shrink-0"><div class="flex w-full items-center py-2 gap-2 px-2 border-b border-edge-muted"><SearchIcon class="size-4 text-ink-muted" /><input@@ -469,9 +475,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {if (e.key === 'Escape') {e.preventDefault();e.stopPropagation();- if (props.onClose) {- props.onClose();- }+ (props.onCancel ?? props.onClose)?.();}}}placeholder={props.config.placeholder}@@ -480,7 +484,14 @@ export function PropertyEntitySelector(props: EntityInputProps) {</div><Show when={totalCount() > 0}>- <div class="p-1.5">+ {/* Picking a row keeps focus in the search field: a tap that moved+ it would drop the phone keyboard until the refocus below. iOS+ devices still send mousedown after a cancelled pointerdown. */}+ <div+ class={cn('p-1.5', fills() && 'flex min-h-0 flex-1 flex-col')}+ onPointerDown={keepSearchFocus}+ onMouseDown={keepSearchFocus}+ ><For each={visiblePinnedOptions()}>{(option, i) => {const isSelected = () => props.selectedOptions().has(option.id);@@ -488,7 +499,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {return (<div- class="group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default min-w-0"+ class="group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default min-w-0 touch:min-h-12"classList={{'bg-hover': isKeyboardSelected(),}}@@ -519,9 +530,12 @@ export function PropertyEntitySelector(props: EntityInputProps) {<divref={scrollContainerRef}style={{- 'max-height': `${MAX_LIST_HEIGHT}px`,+ 'max-height': fills() ? undefined : `${MAX_LIST_HEIGHT}px`,}}- class="overflow-y-auto overflow-x-hidden scrollbar-hidden"+ class={cn(+ 'overflow-y-auto overflow-x-hidden scrollbar-hidden',+ fills() && 'min-h-0 flex-1'+ )}><For each={sortedEntities()}>{(entity, index) => {@@ -538,7 +552,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {</Show><divdata-entity-index={index()}- class="group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default min-w-0"+ class="group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default min-w-0 touch:min-h-12"classList={{'bg-hover': isKeyboardSelected(),}}@@ -631,7 +645,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {const entity = () => customEmailEntity();return (<div- class="group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default min-w-0"+ class="group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default min-w-0 touch:min-h-12"classList={{'bg-hover': rowIndex() === selectedIndex(),}}diff --git a/apps/web/src/features/property/editors/selectors/PropertyOptionSelector.tsx b/apps/web/src/features/property/editors/selectors/PropertyOptionSelector.tsxindex be2073a241..39d6cae177 100644--- a/apps/web/src/features/property/editors/selectors/PropertyOptionSelector.tsx+++ b/apps/web/src/features/property/editors/selectors/PropertyOptionSelector.tsx@@ -1,5 +1,6 @@import { isTouchDevice } from '@core/mobile/isTouchDevice';import { fireAndForget } from '@core/util/fireAndForget';+import { isEditableInput } from '@core/util/isEditableInput';import { useKeyPressed } from '@core/util/useKeyPressed';import CircleDashedEmpty from '@icon/system/regular/circle-dashed.svg';import SearchIcon from '@icon/system/regular/magnifying-glass.svg';@@ -307,12 +308,23 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {return items;});+ // On touch the menu leaves focus in the field behind it; keys typed there+ // are text, not picks.+ const handleKeyDown = (event: KeyboardEvent) => {+ if (+ event.target !== searchInputRef &&+ isEditableInput(event.target as Element)+ )+ return;+ dropdown.handleKeyDown(event);+ };+onMount(() => {- document.addEventListener('keydown', dropdown.handleKeyDown);+ document.addEventListener('keydown', handleKeyDown);});onCleanup(() => {- document.removeEventListener('keydown', dropdown.handleKeyDown);+ document.removeEventListener('keydown', handleKeyDown);});useSearchInputFocus(diff --git a/apps/web/src/features/property/editors/selectors/types.ts b/apps/web/src/features/property/editors/selectors/types.tsindex b245efda4f..435868dafd 100644--- a/apps/web/src/features/property/editors/selectors/types.ts+++ b/apps/web/src/features/property/editors/selectors/types.ts@@ -28,4 +28,7 @@ export type EntitySelectorConfig = {/** When the query is a valid email that is not already in the pool,* offer it as an "Add {email}" row (calendar guests, share sheets). */allowCustomEmail?: boolean;+ /** Let the list fill a sized container, such as a sheet, instead of+ * capping it at the popover height. */+ fillHeight?: boolean;};diff --git a/apps/web/src/features/property/property.ts b/apps/web/src/features/property/property.tsindex 026dcdd3ad..d614557a4b 100644--- a/apps/web/src/features/property/property.ts+++ b/apps/web/src/features/property/property.ts@@ -19,6 +19,7 @@ import {InlineTextEditor,PopoverEditor,PropertyEditor,+ SheetEditor,} from './editors';import { EditorPopover } from './editors/popover/EditorPopover';import {@@ -63,6 +64,8 @@ export const Property = {Editor: PropertyEditor,InlineEditor,PopoverEditor,+ // PopoverEditor for pills inside a touch sheet: entity pickers in a sheet.+ SheetEditor,EditorPopover,// Per-type editor leaves (rare — prefer the dispatchers above).diff --git a/apps/web/src/features/property/tags/EntityRowTags.tsx b/apps/web/src/features/property/tags/EntityRowTags.tsxindex 9d24772942..2cb64e7e33 100644--- a/apps/web/src/features/property/tags/EntityRowTags.tsx+++ b/apps/web/src/features/property/tags/EntityRowTags.tsx@@ -18,7 +18,7 @@ import {import { createSignal, For, Match, Show, Switch } from 'solid-js';import { TagDot } from './TagDot';import { type EditableTag, TagEditorDialog } from './TagEditorDialog';-import { TagPicker } from './TagPicker';+import { TagPicker, TagSheetPicker } from './TagPicker';import { TagPill } from './TagPill';import { useDocTags, useSoupDocTags } from './useDocTags';import { type ResolvedTag, useSoupResolvedTags } from './useSoupResolvedTags';@@ -339,7 +339,7 @@ export function EntityRowTags(props: {);}-export function InlineTagsPill(props: {+type InlineTagsPillProps = {docTags: DocTags;class?: string;variant?: BadgeVariant;@@ -352,13 +352,90 @@ export function InlineTagsPill(props: {* the close rather than mid-interaction, which would tear down the open menu.*/onActiveChange?: (active: boolean) => void;+};++/** The applied tags as dots and a label, shared by both tag pills. */+function InlineTagsPillFace(props: {+ tags: ResolvedTag[];+ showAddButton?: boolean;}) {- const tags = () => props.docTags.appliedTags();- const first = () => tags()[0];- const dots = () => tags().slice(0, MAX_OVERFLOW_DOTS);+ const first = () => props.tags[0];+ const dots = () => props.tags.slice(0, MAX_OVERFLOW_DOTS);const label = () =>- `${tags().length} ${tags().length === 1 ? 'Tag' : 'Tags'}`;+ `${props.tags.length} ${props.tags.length === 1 ? 'Tag' : 'Tags'}`;+ return (+ <>+ <span class="inline-flex min-w-0 items-center gap-1">+ <Switch>+ <Match when={props.tags.length === 0 && props.showAddButton}>+ <PlusIcon class="size-3 shrink-0" />+ <span>Add tags</span>+ </Match>+ <Match when={props.tags.length === 0}>+ <span class="inline-flex min-w-0 items-center gap-1 opacity-50">+ <CircleDashedEmpty class="size-3 shrink-0" />+ <span class="min-w-0 truncate @max-2xl/u-list:hidden">Tags</span>+ </span>+ </Match>+ <Match when={props.tags.length === 1 && first()}>+ {(tag) => (+ <>+ <TagDot color={tag().color} class="size-2.5" />+ <span class="min-w-0 truncate @max-2xl/u-list:hidden">+ {tag().label}+ </span>+ </>+ )}+ </Match>+ <Match when={props.tags.length > 1}>+ <span class="flex items-center">+ <For each={dots()}>+ {(tag, index) => (+ <TagDot+ color={tag.color}+ class={cn(+ 'size-2.5 ring-2 ring-surface',+ index() > 0 && '-ml-1'+ )}+ />+ )}+ </For>+ </span>+ <span class="min-w-0 truncate @max-2xl/u-list:hidden">+ {label()}+ </span>+ </Match>+ </Switch>+ </span>+ <Show when={props.tags.length > 0 || !props.showAddButton}>+ <CaretDownIcon class="size-3 shrink-0 @max-2xl/u-list:hidden" />+ </Show>+ </>+ );+}++function inlineTagsTriggerClass(props: InlineTagsPillProps, count: number) {+ return badgeTriggerClasses({+ variant: props.variant ?? 'outline',+ size: props.size ?? 'xs',+ class: cn(+ // Capped so a long tag label truncates instead of squeezing+ // whatever shares the row with the pill (e.g. a task title).+ 'min-w-0 max-w-35 gap-1.5 text-left',+ count === 0 && !props.showAddButton && 'text-ink-extra-muted',+ props.class+ ),+ });+}++function inlineTagsTriggerLabel(props: InlineTagsPillProps, count: number) {+ return count === 0 && props.showAddButton+ ? 'Add tags'+ : 'Change or select tags';+}+export function InlineTagsPill(props: InlineTagsPillProps) {+ const tags = () => props.docTags.appliedTags();return (<Showwhen={tags().length > 0 || props.showPlaceholder || props.showAddButton}@@ -367,78 +444,43 @@ export function InlineTagsPill(props: {<TagPickerdocTags={props.docTags}onActiveChange={props.onActiveChange}- triggerClass={badgeTriggerClasses({- variant: props.variant ?? 'outline',- size: props.size ?? 'xs',- class: cn(- // Capped so a long tag label truncates instead of squeezing- // whatever shares the row with the pill (e.g. a task title).- 'min-w-0 max-w-35 gap-1.5 text-left',- tags().length === 0 &&- !props.showAddButton &&- 'text-ink-extra-muted',- props.class- ),- })}- triggerLabel={- tags().length === 0 && props.showAddButton- ? 'Add tags'- : 'Change or select tags'- }+ triggerClass={inlineTagsTriggerClass(props, tags().length)}+ triggerLabel={inlineTagsTriggerLabel(props, tags().length)}>- <span class="inline-flex min-w-0 items-center gap-1">- <Switch>- <Match when={tags().length === 0 && props.showAddButton}>- <PlusIcon class="size-3 shrink-0" />- <span>Add tags</span>- </Match>- <Match when={tags().length === 0}>- <span class="inline-flex min-w-0 items-center gap-1 opacity-50">- <CircleDashedEmpty class="size-3 shrink-0" />- <span class="min-w-0 truncate @max-2xl/u-list:hidden">- Tags- </span>- </span>- </Match>- <Match when={tags().length === 1 && first()}>- {(tag) => (- <>- <TagDot color={tag().color} class="size-2.5" />- <span class="min-w-0 truncate @max-2xl/u-list:hidden">- {tag().label}- </span>- </>- )}- </Match>- <Match when={tags().length > 1}>- <span class="flex items-center">- <For each={dots()}>- {(tag, index) => (- <TagDot- color={tag.color}- class={cn(- 'size-2.5 ring-2 ring-surface',- index() > 0 && '-ml-1'- )}- />- )}- </For>- </span>- <span class="min-w-0 truncate @max-2xl/u-list:hidden">- {label()}- </span>- </Match>- </Switch>- </span>- <Show when={tags().length > 0 || !props.showAddButton}>- <CaretDownIcon class="size-3 shrink-0 @max-2xl/u-list:hidden" />- </Show>+ <InlineTagsPillFace+ tags={tags()}+ showAddButton={props.showAddButton}+ /></TagPicker></Layer></Show>);}+/** `InlineTagsPill` for a touch sheet: it picks tags in a stacked sheet. */+export function InlineTagsSheetPill(props: InlineTagsPillProps) {+ const tags = () => props.docTags.appliedTags();+ return (+ <Show+ when={tags().length > 0 || props.showPlaceholder || props.showAddButton}+ >+ <Layer depth={2}>+ <TagSheetPicker+ docTags={props.docTags}+ onActiveChange={props.onActiveChange}+ triggerClass={inlineTagsTriggerClass(props, tags().length)}+ triggerLabel={inlineTagsTriggerLabel(props, tags().length)}+ >+ <InlineTagsPillFace+ tags={tags()}+ showAddButton={props.showAddButton}+ />+ </TagSheetPicker>+ </Layer>+ </Show>+ );+}+export function InlineEntityTagsPill(props: {entityId: string;entityType: EntityType;diff --git a/apps/web/src/features/property/tags/TagPicker.tsx b/apps/web/src/features/property/tags/TagPicker.tsxindex fbf855eafc..a9bf21d692 100644--- a/apps/web/src/features/property/tags/TagPicker.tsx+++ b/apps/web/src/features/property/tags/TagPicker.tsx@@ -1,5 +1,4 @@-import { useSplitLayout } from '@components/app/split-layout/layout';-import { useSplitPanel } from '@components/app/split-layout/layoutUtils';+import { PickerSheet } from '@components/app/mobile/PickerSheet';import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';import { fireAndForget } from '@core/util/fireAndForget';import CircleDashedEmpty from '@icon/system/regular/circle-dashed.svg';@@ -11,21 +10,13 @@ import { OptionCheckBox } from '@property/editors/selectors/OptionCheckBox';import {DropdownSearchInput,DropdownSelectableRow,- useDropdownSearch,} from '@property/editors/selectors/PropertyOptionSelector';-import { useAddPropertyOptionMutation } from '@queries/properties/options';-import {- type CreateTagResult,- invalidateTags,- useEnsureTagSetMutation,-} from '@queries/properties/tags';+import { useSearchInputFocus } from '@property/utils';import { useCurrentTeamQuery } from '@queries/team/teams';-import type { PropertyOptionResponse } from '@service-properties/generated/schemas/propertyOptionResponse';import type { TagScope } from '@service-properties/generated/schemas/tagScope';-import { Button, Layer } from '@ui';+import { Button, cn, Layer } from '@ui';import {createEffect,- createMemo,createSignal,For,type JSX,@@ -33,39 +24,20 @@ import {onCleanup,onMount,Show,- untrack,} from 'solid-js';import { TagDot } from './TagDot';+import { TagEditorDialog, type TagEditorDialogMode } from './TagEditorDialog';import {- type EditableTag,- TagEditorDialog,- type TagEditorDialogMode,-} from './TagEditorDialog';+ type CreateStep,+ type CreateTagSuccessHandler,+ createTagPickerSession,+ type DocTags,+ optionLabel,+ type TagOptionItem,+ type TagPickerSession,+} from './tag-picker-session';import { DEFAULT_TAG_COLOR, TAG_COLOR_OPTIONS } from './tagColors';-import { navigateToTag } from './tagNavigation';-import type { ResolvedTag, useDocTags } from './useDocTags';--type DocTags = ReturnType<typeof useDocTags>;--type TagOptionItem = {- scope: TagScope;- option: PropertyOptionResponse;-};--type CreateStep = 'color' | 'scope';-type CreateTagSuccessHandler = (- result: CreateTagResult-) => void | Promise<void>;--function optionLabel(option: PropertyOptionResponse): string {- return option.value.type === 'string' ? option.value.value : '';-}--function nextDisplayOrder(options: PropertyOptionResponse[]): number {- return (- options.reduce((max, option) => Math.max(max, option.displayOrder), -1) + 1- );-}+import type { ResolvedTag } from './useDocTags';const MAX_LIST_HEIGHT = 192;// The keyboard covers the layout viewport's bottom without shrinking it, so@@ -73,7 +45,7 @@ const MAX_LIST_HEIGHT = 192;const pickerPlacement = () =>virtualKeyboardVisible() ? 'top-start' : 'bottom-start';const tagActionButtonClass =- 'size-5 shrink-0 p-0.5 text-ink-extra-muted opacity-0 group-hover:opacity-100 focus-visible:opacity-100';+ 'size-5 shrink-0 p-0.5 text-ink-extra-muted opacity-0 group-hover:opacity-100 focus-visible:opacity-100 touch:opacity-100';export type TagPickerSourceProps =| { docTags: DocTags; createDocTags?: never }@@ -322,6 +294,92 @@ export function TagPickerPopover(props: {);}+/**+ * The tag picker for a touch sheet: its trigger opens the picker in a sheet+ * stacked over the current one, with Cancel, the Tags title, and Done. Picks+ * stay staged until Done; Cancel, the backdrop, or Escape drop them.+ */+export function TagSheetPicker(props: {+ docTags: DocTags;+ triggerClass?: string;+ triggerLabel: string;+ children: JSX.Element;+ /** As `TagPicker`'s: a session covers the sheet and the tag editor it opens. */+ onActiveChange?: (active: boolean) => void;+}) {+ const [open, setOpen] = createSignal(false);+ const [editorMode, setEditorMode] = createSignal<TagEditorDialogMode | null>(+ null+ );+ const currentTeamQuery = useCurrentTeamQuery();+ createEffect(+ on(+ () => open() || editorMode() !== null,+ (active) => props.onActiveChange?.(active),+ { defer: true }+ )+ );++ return (+ <>+ <button+ type="button"+ class={props.triggerClass}+ aria-label={props.triggerLabel}+ aria-haspopup="dialog"+ aria-expanded={open()}+ onClick={() => setOpen(true)}+ >+ {props.children}+ </button>+ <PickerSheet.Root open={open()} onCancel={() => setOpen(false)}>+ <TagPickerSheetBody+ docTags={props.docTags}+ onClose={() => setOpen(false)}+ onOpenEditEditor={(mode) => {+ setEditorMode(mode);+ setOpen(false);+ }}+ />+ </PickerSheet.Root>+ <Show when={editorMode()}>+ <TagEditorDialog+ open+ mode={editorMode()}+ teamAvailable={Boolean(currentTeamQuery.data?.team)}+ onClose={() => setEditorMode(null)}+ />+ </Show>+ </>+ );+}++function TagPickerSheetBody(props: {+ docTags: DocTags;+ onClose: () => void;+ onOpenEditEditor: (+ mode: Extract<TagEditorDialogMode, { type: 'edit' }>+ ) => void;+}) {+ const session = createTagPickerSession({+ docTags: props.docTags,+ onClose: props.onClose,+ onOpenEditEditor: props.onOpenEditEditor,+ confirmsWithDone: true,+ });+ return (+ <>+ <PickerSheet.Header+ title="Tags"+ onDone={() => fireAndForget(session.saveAndClose(), 'tag-picker')}+ />+ <PickerSheet.Body>+ <TagPickerList session={session} fillHeight />+ </PickerSheet.Body>+ </>+ );+}+function TagPickerBody(props: {docTags: DocTags;onClose: () => void;@@ -336,21 +394,12 @@ function TagPickerBody(props: {suppressInitialOutsideEvents: boolean;withClickBlock?: boolean;}) {- const [search, setSearch] = createSignal('');- const [saved, setSaved] = createSignal(false);- const [selectedIds, setSelectedIds] = createSignal<Set<string>>(- new Set(props.docTags.appliedTags().map((tag) => tag.optionId))- );- const [createStep, setCreateStep] = createSignal<CreateStep | null>(null);- const [createDraftLabel, setCreateDraftLabel] = createSignal('');- const [selectedColorIndex, setSelectedColorIndex] = createSignal(0);- const [selectedScopeIndex, setSelectedScopeIndex] = createSignal(0);- const currentTeamQuery = useCurrentTeamQuery();- const addOption = useAddPropertyOptionMutation();- const ensureTagSet = useEnsureTagSetMutation();- const split = useSplitLayout();- const panel = useSplitPanel();- let scrollContainerRef: HTMLDivElement | undefined;+ const session = createTagPickerSession({+ docTags: props.docTags,+ onClose: props.onClose,+ onOpenEditEditor: props.onOpenEditEditor,+ confirmsWithDone: false,+ });const [initialOutsideEventGuard, setInitialOutsideEventGuard] =createSignal(true);const shouldIgnoreOutsideEvent = () =>@@ -380,323 +429,8 @@ function TagPickerBody(props: {);};- const initialAppliedTags = createMemo(() => props.docTags.appliedTags());- const initialAppliedIds = createMemo(- () => new Set(initialAppliedTags().map((tag) => tag.optionId))- );- const initialTagState = createMemo(() => {- const optionScopes = new Map<string, TagScope>();- const optionsById = new Map<string, PropertyOptionResponse>();- const itemsByScope = new Map<TagScope, TagOptionItem[]>();-- for (const set of props.docTags.tagSets()) {- for (const option of set.options) {- optionsById.set(option.id, option);- }-- itemsByScope.set(- set.scope,- [...set.options]- .sort((a, b) => a.displayOrder - b.displayOrder)- .map((option) => {- optionScopes.set(option.id, set.scope);- return {- scope: set.scope,- option,- };- })- );- }-- const selectedItems = initialAppliedTags().flatMap((tag) => {- const option = optionsById.get(tag.optionId);- return option ? [{ scope: tag.scope, option }] : [];- });-- return {- optionScopes,- itemsByScope,- selectedItems,- items: [...itemsByScope.values()].flat(),- };- });-- createEffect(() => {- const appliedTags = initialAppliedTags();- if (untrack(saved)) return;- setSelectedIds(new Set(appliedTags.map((tag) => tag.optionId)));- });-- const isSelected = (optionId: string) => selectedIds().has(optionId);-- const toggleSelected = (optionId: string) => {- setSelectedIds((prev) => {- const next = new Set(prev);- if (next.has(optionId)) next.delete(optionId);- else next.add(optionId);- return next;- });- };-- const persistSelection = async () => {- if (saved()) return true;- setSaved(true);-- try {- await props.docTags.setTagSelection(selectedIds());- return true;- } catch (error) {- setSaved(false);- console.error('Failed to persist tag selection', error);- return false;- }- };-- const save = async () => {- return persistSelection();- };-- const saveAndClose = async () => {- const savePromise = save();- props.onClose();- await savePromise;- };-- const filteredItems = createMemo(() => {- const query = search().trim().toLowerCase();- const matchesSearch = (item: TagOptionItem) =>- !query || optionLabel(item.option).toLowerCase().includes(query);-- const selectedAtOpen =- initialTagState().selectedItems.filter(matchesSearch);- const remainingForScope = (scope: TagScope) =>- (initialTagState().itemsByScope.get(scope) ?? []).filter(- (item) =>- !initialAppliedIds().has(item.option.id) && matchesSearch(item)- );-- return [- ...selectedAtOpen,- ...remainingForScope('user'),- ...remainingForScope('team'),- ];- });-- const selectedAtOpenItems = createMemo(() => {- const query = search().trim().toLowerCase();- return initialTagState().selectedItems.filter(- (item) => !query || optionLabel(item.option).toLowerCase().includes(query)- );- });-- const remainingItemsForScope = (scope: TagScope) => {- const query = search().trim().toLowerCase();- return (initialTagState().itemsByScope.get(scope) ?? []).filter(- (item) =>- !initialAppliedIds().has(item.option.id) &&- (!query || optionLabel(item.option).toLowerCase().includes(query))- );- };-- const createLabel = () => search().trim();- const exactTagMatchExists = () => {- const label = createLabel().toLowerCase();- return (- !!label &&- initialTagState().items.some(- (item) => optionLabel(item.option).toLowerCase() === label- )- );- };- const showCreateRow = () =>- createLabel().length > 0 && !exactTagMatchExists();- const showClearAllRow = () =>- selectedIds().size > 0 && !search().trim() && !createStep();- const showCreateRowDivider = () =>- showCreateRow() && (filteredItems().length > 0 || showClearAllRow());- const itemIndex = (item: TagOptionItem) => filteredItems().indexOf(item);- const clearAllRowIndex = () => filteredItems().length;- const createRowIndex = () =>- filteredItems().length + (showClearAllRow() ? 1 : 0);- const teamName = () => currentTeamQuery.data?.team.name?.trim() || 'Team';- const scopeOptions = createMemo<{ scope: TagScope; label: string }[]>(() => [- { scope: 'team', label: `Shared with ${teamName()}` },- { scope: 'user', label: 'Personal' },- ]);- const selectedColor = () =>- TAG_COLOR_OPTIONS[selectedColorIndex()]?.color ?? DEFAULT_TAG_COLOR;- const createItemCount = () =>- createStep() === 'color' ? TAG_COLOR_OPTIONS.length : scopeOptions().length;-- const beginCreate = () => {- const label = createLabel();- if (!showCreateRow() || !label) return;- setCreateDraftLabel(label);- setSelectedColorIndex(0);- setSelectedScopeIndex(0);- setCreateStep('color');- };-- const editableTagForItem = (item: TagOptionItem): EditableTag => ({- scope: item.scope,- propertyDefinitionId: item.option.propertyDefinitionId,- option: item.option,- });-- const beginEdit = async (item: TagOptionItem) => {- if (!(await persistSelection())) return;- props.onOpenEditEditor({- type: 'edit',- tag: editableTagForItem(item),- });- };-- const openTaggedItems = async (item: TagOptionItem) => {- if (!(await persistSelection())) return;- props.onClose();- navigateToTag(- split.openWithSplit,- {- optionId: item.option.id,- propertyDefinitionId: item.option.propertyDefinitionId,- },- { handle: panel?.handle }- );- };-- const createTag = async (scope: TagScope) => {- const value = createDraftLabel().trim();- if (!value) return;-- try {- if (!(await persistSelection())) return;-- const provisioned = await ensureTagSet.mutateAsync({ scope });- if (!provisioned.definition) return;-- const created = await addOption.mutateAsync({- propertyDefinitionId: provisioned.definition.id,- body: {- type: 'select_string',- option: {- value,- display_order: nextDisplayOrder(provisioned.options),- color: selectedColor(),- },- },- });- invalidateTags();- await props.docTags.applyTag(scope, created.id);- props.onClose();- } catch (error) {- console.error('Failed to create tag', error);- }- };-- const handleCreateKeyDown = (event: KeyboardEvent) => {- const step = createStep();- if (!step) return;-- if (event.key === 'Escape') {- event.preventDefault();- event.stopPropagation();- if (step === 'scope') {- setCreateStep('color');- return;- }- setCreateStep(null);- return;- }-- const count = createItemCount();- if (count === 0) return;-- if (event.key === 'ArrowDown' || (event.ctrlKey && event.key === 'j')) {- event.preventDefault();- if (step === 'color') {- setSelectedColorIndex((prev) => (prev + 1) % count);- } else {- setSelectedScopeIndex((prev) => (prev + 1) % count);- }- } else if (- event.key === 'ArrowUp' ||- (event.ctrlKey && event.key === 'k')- ) {- event.preventDefault();- if (step === 'color') {- setSelectedColorIndex((prev) => (prev - 1 + count) % count);- } else {- setSelectedScopeIndex((prev) => (prev - 1 + count) % count);- }- } else if (event.key === 'Enter') {- event.preventDefault();- if (step === 'color') {- setCreateStep('scope');- } else {- const scope = scopeOptions()[selectedScopeIndex()]?.scope;- if (scope) fireAndForget(createTag(scope), 'tag-picker');- }- }- };-- const dropdown = useDropdownSearch({- itemCount: () =>- filteredItems().length +- (showClearAllRow() ? 1 : 0) +- (showCreateRow() ? 1 : 0),- onSelect: (index, event) => {- if (showCreateRow() && index === createRowIndex()) {- beginCreate();- return;- }-- if (showClearAllRow() && index === clearAllRowIndex()) {- setSelectedIds(new Set<string>());- fireAndForget(saveAndClose(), 'tag-picker');- return;- }-- const item = filteredItems()[index];- if (!item) return;-- toggleSelected(item.option.id);- if (!event?.shiftKey) fireAndForget(saveAndClose(), 'tag-picker');- },- onClose: saveAndClose,- enableNumericHotkeys: false,- });-- // Reset selected index to top when search term or list changes.- createEffect(() => {- if (createStep()) return;- search();- filteredItems().length;- dropdown.setSelectedIndex(0);- });-- createEffect(() => {- if (createStep()) return;- const index = dropdown.selectedIndex();- if (!dropdown.keyboardMode() || !scrollContainerRef) return;-- const row = scrollContainerRef.querySelector<HTMLDivElement>(- `[data-tag-index="${index}"]`- );- row?.scrollIntoView({ block: 'nearest' });- });-- const handleKeyDown = (event: KeyboardEvent) => {- if (saved()) return;- if (createStep()) {- handleCreateKeyDown(event);- return;- }- dropdown.handleKeyDown(event);- };-onMount(() => {- props.registerSave(saveAndClose);- document.addEventListener('keydown', handleKeyDown);+ props.registerSave(session.saveAndClose);const timeout = setTimeout(() => {setInitialOutsideEventGuard(false);}, 100);@@ -705,7 +439,6 @@ function TagPickerBody(props: {onCleanup(() => {props.registerSave(undefined);- document.removeEventListener('keydown', handleKeyDown);});return (@@ -725,188 +458,183 @@ function TagPickerBody(props: {blockDismissalClick();}}>- <Show- when={createStep()}- fallback={- <>- <DropdownSearchInput- value={search()}- placeholder="Change or add tags"- onInput={(value) => {- setSearch(value);- dropdown.setSearchQuery(value);- }}- />- <div class="p-1.5">- <div- ref={scrollContainerRef}- class="overflow-y-auto overflow-x-hidden scrollbar-hidden"- style={{ 'max-height': `${MAX_LIST_HEIGHT}px` }}- >- <Show- when={- showClearAllRow() ||- filteredItems().length > 0 ||- showCreateRow()- }- fallback={- <div class="px-2 py-4 text-center text-ink-muted">- {initialTagState().items.length === 0- ? 'No tags available'- : 'No tags match your search'}- </div>+ <TagPickerList session={session} />+ </Popover.Content>+ </Layer>+ </Popover.Portal>+ );+}++/** The search, tag rows, and create flow of a picker session. */+function TagPickerList(props: {+ session: TagPickerSession;+ /** Fill a sized container, such as a sheet, rather than a popover's height. */+ fillHeight?: boolean;+}) {+ const session = props.session;+ const rowProps = (item: TagOptionItem) => ({+ item,+ index: session.itemIndex(item),+ teamName: session.teamName(),+ checked: session.isSelected(item.option.id),+ selected: session.dropdown.selectedIndex() === session.itemIndex(item),+ onSelect: (event: MouseEvent) => session.pick(item, event),+ onEdit: () => fireAndForget(session.beginEdit(item), 'tag-picker'),+ onOpenTag: () => fireAndForget(session.openTaggedItems(item), 'tag-picker'),+ onMouseEnter: () => {+ if (!session.dropdown.keyboardMode()) {+ session.dropdown.setSelectedIndex(session.itemIndex(item));+ }+ },+ });+ // Picking a row keeps focus in the search field, so a phone keyboard stays+ // up; iOS devices still send mousedown after a cancelled pointerdown.+ const keepSearchFocus = (event: Event) => event.preventDefault();+ let searchInput: HTMLInputElement | undefined;+ useSearchInputFocus(() => searchInput);++ return (+ <Show+ when={session.createStep()}+ fallback={+ <>+ <DropdownSearchInput+ value={session.search()}+ placeholder="Change or add tags"+ onInput={session.setSearch}+ inputRef={(element) => {+ searchInput = element;+ }}+ />+ <div+ class={cn(+ 'p-1.5',+ props.fillHeight && 'flex min-h-0 flex-1 flex-col'+ )}+ onPointerDown={keepSearchFocus}+ onMouseDown={keepSearchFocus}+ >+ <div+ ref={session.setScrollContainer}+ class={cn(+ 'overflow-y-auto overflow-x-hidden scrollbar-hidden',+ props.fillHeight && 'min-h-0 flex-1'+ )}+ style={{+ 'max-height': props.fillHeight+ ? undefined+ : `${MAX_LIST_HEIGHT}px`,+ }}+ >+ <Show+ when={+ session.showClearAllRow() ||+ session.filteredItems().length > 0 ||+ session.showCreateRow()+ }+ fallback={+ <div class="px-2 py-4 text-center text-ink-muted">+ {session.hasTags()+ ? 'No tags match your search'+ : 'No tags available'}+ </div>+ }+ >+ <For each={session.selectedAtOpenItems()}>+ {(item) => <TagPickerRow {...rowProps(item)} />}+ </For>+ <Show+ when={+ session.selectedAtOpenItems().length > 0 &&+ (session.remainingItemsForScope('user').length > 0 ||+ session.remainingItemsForScope('team').length > 0)+ }+ >+ <div class="my-1 border-t border-edge-muted" />+ </Show>+ <For each={['user', 'team'] as const}>+ {(scope) => (+ <For each={session.remainingItemsForScope(scope)}>+ {(item) => <TagPickerRow {...rowProps(item)} />}+ </For>+ )}+ </For>+ <Show when={session.showClearAllRow()}>+ <div class="my-1 border-t border-edge-muted" />+ <div data-tag-index={session.clearAllRowIndex()}>+ <DropdownSelectableRow+ isSelected={+ session.dropdown.selectedIndex() ===+ session.clearAllRowIndex()}- >- <For each={selectedAtOpenItems()}>- {(item) => (- <TagPickerRow- item={item}- index={itemIndex(item)}- teamName={teamName()}- checked={isSelected(item.option.id)}- selected={- dropdown.selectedIndex() === itemIndex(item)- }- onSelect={(event) => {- toggleSelected(item.option.id);- if (!event.shiftKey)- fireAndForget(saveAndClose(), 'tag-picker');- }}- onEdit={() =>- fireAndForget(beginEdit(item), 'tag-picker')- }- onOpenTag={() =>- fireAndForget(openTaggedItems(item), 'tag-picker')- }- onMouseEnter={() => {- if (!dropdown.keyboardMode()) {- dropdown.setSelectedIndex(itemIndex(item));- }- }}- />- )}- </For>- <Show- when={- selectedAtOpenItems().length > 0 &&- (remainingItemsForScope('user').length > 0 ||- remainingItemsForScope('team').length > 0)+ onClick={session.clearAll}+ onMouseEnter={() => {+ if (!session.dropdown.keyboardMode()) {+ session.dropdown.setSelectedIndex(+ session.clearAllRowIndex()+ );}- >- <div class="my-1 border-t border-edge-muted" />- </Show>- <For each={['user', 'team'] as const}>- {(scope) => (- <For each={remainingItemsForScope(scope)}>- {(item) => (- <TagPickerRow- item={item}- index={itemIndex(item)}- teamName={teamName()}- checked={isSelected(item.option.id)}- selected={- dropdown.selectedIndex() === itemIndex(item)- }- onSelect={(event) => {- toggleSelected(item.option.id);- if (!event.shiftKey)- fireAndForget(saveAndClose(), 'tag-picker');- }}- onEdit={() =>- fireAndForget(beginEdit(item), 'tag-picker')- }- onOpenTag={() =>- fireAndForget(- openTaggedItems(item),- 'tag-picker'- )- }- onMouseEnter={() => {- if (!dropdown.keyboardMode()) {- dropdown.setSelectedIndex(itemIndex(item));- }- }}- />- )}- </For>- )}- </For>- <Show when={showClearAllRow()}>- <div class="my-1 border-t border-edge-muted" />- <div data-tag-index={clearAllRowIndex()}>- <DropdownSelectableRow- isSelected={- dropdown.selectedIndex() === clearAllRowIndex()- }- onClick={() => {- setSelectedIds(new Set<string>());- fireAndForget(saveAndClose(), 'tag-picker');- }}- onMouseEnter={() => {- if (!dropdown.keyboardMode()) {- dropdown.setSelectedIndex(clearAllRowIndex());- }- }}- >- <CircleDashedEmpty class="size-3 shrink-0 text-ink-extra-muted" />- <div class="min-w-0 flex-1 text-left">- <p class="truncate text-ink-muted">- Clear all tags- </p>- </div>- </DropdownSelectableRow>- </div>- </Show>- </Show>- </div>- <Show when={showCreateRow()}>- <div- classList={{- 'mt-1 border-t border-edge-muted pt-1':- showCreateRowDivider(),}}>- <CreateTagRow- index={createRowIndex()}- label={createLabel()}- selected={dropdown.selectedIndex() === createRowIndex()}- onClick={beginCreate}- onMouseEnter={() => {- if (!dropdown.keyboardMode()) {- dropdown.setSelectedIndex(createRowIndex());- }- }}- />- </div>- </Show>- </div>- </>- }- >- {(step) => (- <CreateTagFlow- step={step()}- label={createDraftLabel()}- colorOptions={TAG_COLOR_OPTIONS}- selectedColorIndex={selectedColorIndex()}- scopeOptions={scopeOptions()}- selectedScopeIndex={selectedScopeIndex()}- pending={addOption.isPending || ensureTagSet.isPending}- onColorMouseEnter={setSelectedColorIndex}- onColorSelect={(index) => {- setSelectedColorIndex(index);- setCreateStep('scope');+ <CircleDashedEmpty class="size-3 shrink-0 text-ink-extra-muted" />+ <div class="min-w-0 flex-1 text-left">+ <p class="truncate text-ink-muted">Clear all tags</p>+ </div>+ </DropdownSelectableRow>+ </div>+ </Show>+ </Show>+ </div>+ <Show when={session.showCreateRow()}>+ <div+ classList={{+ 'mt-1 border-t border-edge-muted pt-1':+ session.showCreateRowDivider(),}}- onScopeMouseEnter={setSelectedScopeIndex}- onScopeSelect={(scope) =>- fireAndForget(createTag(scope), 'tag-picker')- }- />- )}- </Show>- </Popover.Content>- </Layer>- </Popover.Portal>+ >+ <CreateTagRow+ index={session.createRowIndex()}+ label={session.createLabel()}+ selected={+ session.dropdown.selectedIndex() ===+ session.createRowIndex()+ }+ onClick={session.beginCreate}+ onMouseEnter={() => {+ if (!session.dropdown.keyboardMode()) {+ session.dropdown.setSelectedIndex(+ session.createRowIndex()+ );+ }+ }}+ />+ </div>+ </Show>+ </div>+ </>+ }+ >+ {(step) => (+ <CreateTagFlow+ step={step()}+ label={session.createDraftLabel()}+ colorOptions={TAG_COLOR_OPTIONS}+ selectedColorIndex={session.selectedColorIndex()}+ scopeOptions={session.scopeOptions()}+ selectedScopeIndex={session.selectedScopeIndex()}+ pending={session.creating()}+ onColorMouseEnter={session.setSelectedColorIndex}+ onColorSelect={(index) => {+ session.setSelectedColorIndex(index);+ session.setCreateStep('scope');+ }}+ onScopeMouseEnter={session.setSelectedScopeIndex}+ onScopeSelect={(scope) =>+ fireAndForget(session.createTag(scope), 'tag-picker')+ }+ />+ )}+ </Show>);}diff --git a/apps/web/src/features/property/tags/index.ts b/apps/web/src/features/property/tags/index.tsindex 9d513d8829..c9f9720ec4 100644--- a/apps/web/src/features/property/tags/index.ts+++ b/apps/web/src/features/property/tags/index.ts@@ -3,6 +3,7 @@ export {InlineEntityTagsPill,InlineFetchedEntityTagsPill,InlineTagsPill,+ InlineTagsSheetPill,} from './EntityRowTags';export {canTagEntity,diff --git a/apps/web/src/features/property/tags/tag-picker-session.ts b/apps/web/src/features/property/tags/tag-picker-session.tsnew file mode 100644index 0000000000..94f2bdde9f--- /dev/null+++ b/apps/web/src/features/property/tags/tag-picker-session.ts@@ -0,0 +1,455 @@+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';+import { fireAndForget } from '@core/util/fireAndForget';+import { useDropdownSearch } from '@property/editors/selectors/PropertyOptionSelector';+import { useAddPropertyOptionMutation } from '@queries/properties/options';+import {+ type CreateTagResult,+ invalidateTags,+ useEnsureTagSetMutation,+} from '@queries/properties/tags';+import { useCurrentTeamQuery } from '@queries/team/teams';+import type { PropertyOptionResponse } from '@service-properties/generated/schemas/propertyOptionResponse';+import type { TagScope } from '@service-properties/generated/schemas/tagScope';+import {+ createEffect,+ createMemo,+ createSignal,+ onCleanup,+ onMount,+ untrack,+} from 'solid-js';+import type { EditableTag, TagEditorDialogMode } from './TagEditorDialog';+import { DEFAULT_TAG_COLOR, TAG_COLOR_OPTIONS } from './tagColors';+import { navigateToTag } from './tagNavigation';+import type { useDocTags } from './useDocTags';++export type DocTags = ReturnType<typeof useDocTags>;++export type TagOptionItem = {+ scope: TagScope;+ option: PropertyOptionResponse;+};++export type CreateStep = 'color' | 'scope';+export type CreateTagSuccessHandler = (+ result: CreateTagResult+) => void | Promise<void>;++export function optionLabel(option: PropertyOptionResponse): string {+ return option.value.type === 'string' ? option.value.value : '';+}++function nextDisplayOrder(options: PropertyOptionResponse[]): number {+ return (+ options.reduce((max, option) => Math.max(max, option.displayOrder), -1) + 1+ );+}++/**+ * One tag picker session: the staged selection, search, keyboard navigation,+ * and tag creation, shared by the popover and the touch sheet.+ */+export function createTagPickerSession(props: {+ docTags: DocTags;+ onClose: () => void;+ onOpenEditEditor: (+ mode: Extract<TagEditorDialogMode, { type: 'edit' }>+ ) => void;+ /**+ * A sheet with Done: picking a tag, or clearing them all, keeps the picker+ * open, and Escape cancels. A popover instead saves and closes on a pick,+ * and Escape saves.+ */+ confirmsWithDone: boolean;+}) {+ const [search, setSearch] = createSignal('');+ const [saved, setSaved] = createSignal(false);+ const [selectedIds, setSelectedIds] = createSignal<Set<string>>(+ new Set(props.docTags.appliedTags().map((tag) => tag.optionId))+ );+ const [createStep, setCreateStep] = createSignal<CreateStep | null>(null);+ const [createDraftLabel, setCreateDraftLabel] = createSignal('');+ const [selectedColorIndex, setSelectedColorIndex] = createSignal(0);+ const [selectedScopeIndex, setSelectedScopeIndex] = createSignal(0);+ const currentTeamQuery = useCurrentTeamQuery();+ const addOption = useAddPropertyOptionMutation();+ const ensureTagSet = useEnsureTagSetMutation();+ const split = useSplitLayout();+ const panel = useSplitPanel();+ let scrollContainerRef: HTMLDivElement | undefined;++ const initialAppliedTags = createMemo(() => props.docTags.appliedTags());+ const initialAppliedIds = createMemo(+ () => new Set(initialAppliedTags().map((tag) => tag.optionId))+ );+ const initialTagState = createMemo(() => {+ const optionScopes = new Map<string, TagScope>();+ const optionsById = new Map<string, PropertyOptionResponse>();+ const itemsByScope = new Map<TagScope, TagOptionItem[]>();++ for (const set of props.docTags.tagSets()) {+ for (const option of set.options) {+ optionsById.set(option.id, option);+ }++ itemsByScope.set(+ set.scope,+ [...set.options]+ .sort((a, b) => a.displayOrder - b.displayOrder)+ .map((option) => {+ optionScopes.set(option.id, set.scope);+ return {+ scope: set.scope,+ option,+ };+ })+ );+ }++ const selectedItems = initialAppliedTags().flatMap((tag) => {+ const option = optionsById.get(tag.optionId);+ return option ? [{ scope: tag.scope, option }] : [];+ });++ return {+ optionScopes,+ itemsByScope,+ selectedItems,+ items: [...itemsByScope.values()].flat(),+ };+ });++ createEffect(() => {+ const appliedTags = initialAppliedTags();+ if (untrack(saved)) return;+ setSelectedIds(new Set(appliedTags.map((tag) => tag.optionId)));+ });++ const isSelected = (optionId: string) => selectedIds().has(optionId);++ const toggleSelected = (optionId: string) => {+ setSelectedIds((prev) => {+ const next = new Set(prev);+ if (next.has(optionId)) next.delete(optionId);+ else next.add(optionId);+ return next;+ });+ };++ const persistSelection = async () => {+ if (saved()) return true;+ setSaved(true);++ try {+ await props.docTags.setTagSelection(selectedIds());+ return true;+ } catch (error) {+ setSaved(false);+ console.error('Failed to persist tag selection', error);+ return false;+ }+ };++ const save = async () => {+ return persistSelection();+ };++ const saveAndClose = async () => {+ const savePromise = save();+ props.onClose();+ await savePromise;+ };++ /** Toggle a tag; a picker that closes on pick saves unless Shift is held. */+ const pick = (item: TagOptionItem, event?: { shiftKey?: boolean }) => {+ toggleSelected(item.option.id);+ if (!props.confirmsWithDone && !event?.shiftKey) {+ fireAndForget(saveAndClose(), 'tag-picker');+ }+ };++ const clearAll = () => {+ setSelectedIds(new Set<string>());+ if (!props.confirmsWithDone) fireAndForget(saveAndClose(), 'tag-picker');+ };++ const filteredItems = createMemo(() => {+ const query = search().trim().toLowerCase();+ const matchesSearch = (item: TagOptionItem) =>+ !query || optionLabel(item.option).toLowerCase().includes(query);++ const selectedAtOpen =+ initialTagState().selectedItems.filter(matchesSearch);+ const remainingForScope = (scope: TagScope) =>+ (initialTagState().itemsByScope.get(scope) ?? []).filter(+ (item) =>+ !initialAppliedIds().has(item.option.id) && matchesSearch(item)+ );++ return [+ ...selectedAtOpen,+ ...remainingForScope('user'),+ ...remainingForScope('team'),+ ];+ });++ const selectedAtOpenItems = createMemo(() => {+ const query = search().trim().toLowerCase();+ return initialTagState().selectedItems.filter(+ (item) => !query || optionLabel(item.option).toLowerCase().includes(query)+ );+ });++ const remainingItemsForScope = (scope: TagScope) => {+ const query = search().trim().toLowerCase();+ return (initialTagState().itemsByScope.get(scope) ?? []).filter(+ (item) =>+ !initialAppliedIds().has(item.option.id) &&+ (!query || optionLabel(item.option).toLowerCase().includes(query))+ );+ };++ const createLabel = () => search().trim();+ const exactTagMatchExists = () => {+ const label = createLabel().toLowerCase();+ return (+ !!label &&+ initialTagState().items.some(+ (item) => optionLabel(item.option).toLowerCase() === label+ )+ );+ };+ const showCreateRow = () =>+ createLabel().length > 0 && !exactTagMatchExists();+ const showClearAllRow = () =>+ selectedIds().size > 0 && !search().trim() && !createStep();+ const showCreateRowDivider = () =>+ showCreateRow() && (filteredItems().length > 0 || showClearAllRow());+ const itemIndex = (item: TagOptionItem) => filteredItems().indexOf(item);+ const clearAllRowIndex = () => filteredItems().length;+ const createRowIndex = () =>+ filteredItems().length + (showClearAllRow() ? 1 : 0);+ const teamName = () => currentTeamQuery.data?.team.name?.trim() || 'Team';+ const scopeOptions = createMemo<{ scope: TagScope; label: string }[]>(() => [+ { scope: 'team', label: `Shared with ${teamName()}` },+ { scope: 'user', label: 'Personal' },+ ]);+ const selectedColor = () =>+ TAG_COLOR_OPTIONS[selectedColorIndex()]?.color ?? DEFAULT_TAG_COLOR;+ const createItemCount = () =>+ createStep() === 'color' ? TAG_COLOR_OPTIONS.length : scopeOptions().length;++ const beginCreate = () => {+ const label = createLabel();+ if (!showCreateRow() || !label) return;+ setCreateDraftLabel(label);+ setSelectedColorIndex(0);+ setSelectedScopeIndex(0);+ setCreateStep('color');+ };++ const editableTagForItem = (item: TagOptionItem): EditableTag => ({+ scope: item.scope,+ propertyDefinitionId: item.option.propertyDefinitionId,+ option: item.option,+ });++ const beginEdit = async (item: TagOptionItem) => {+ if (!(await persistSelection())) return;+ props.onOpenEditEditor({+ type: 'edit',+ tag: editableTagForItem(item),+ });+ };++ const openTaggedItems = async (item: TagOptionItem) => {+ if (!(await persistSelection())) return;+ props.onClose();+ navigateToTag(+ split.openWithSplit,+ {+ optionId: item.option.id,+ propertyDefinitionId: item.option.propertyDefinitionId,+ },+ { handle: panel?.handle }+ );+ };++ const createTag = async (scope: TagScope) => {+ const value = createDraftLabel().trim();+ if (!value) return;++ try {+ if (!(await persistSelection())) return;++ const provisioned = await ensureTagSet.mutateAsync({ scope });+ if (!provisioned.definition) return;++ const created = await addOption.mutateAsync({+ propertyDefinitionId: provisioned.definition.id,+ body: {+ type: 'select_string',+ option: {+ value,+ display_order: nextDisplayOrder(provisioned.options),+ color: selectedColor(),+ },+ },+ });+ invalidateTags();+ await props.docTags.applyTag(scope, created.id);+ props.onClose();+ } catch (error) {+ console.error('Failed to create tag', error);+ }+ };++ const handleCreateKeyDown = (event: KeyboardEvent) => {+ const step = createStep();+ if (!step) return;++ if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ if (step === 'scope') {+ setCreateStep('color');+ return;+ }+ setCreateStep(null);+ return;+ }++ const count = createItemCount();+ if (count === 0) return;++ if (event.key === 'ArrowDown' || (event.ctrlKey && event.key === 'j')) {+ event.preventDefault();+ if (step === 'color') {+ setSelectedColorIndex((prev) => (prev + 1) % count);+ } else {+ setSelectedScopeIndex((prev) => (prev + 1) % count);+ }+ } else if (+ event.key === 'ArrowUp' ||+ (event.ctrlKey && event.key === 'k')+ ) {+ event.preventDefault();+ if (step === 'color') {+ setSelectedColorIndex((prev) => (prev - 1 + count) % count);+ } else {+ setSelectedScopeIndex((prev) => (prev - 1 + count) % count);+ }+ } else if (event.key === 'Enter') {+ event.preventDefault();+ if (step === 'color') {+ setCreateStep('scope');+ } else {+ const scope = scopeOptions()[selectedScopeIndex()]?.scope;+ if (scope) fireAndForget(createTag(scope), 'tag-picker');+ }+ }+ };++ const dropdown = useDropdownSearch({+ itemCount: () =>+ filteredItems().length ++ (showClearAllRow() ? 1 : 0) ++ (showCreateRow() ? 1 : 0),+ onSelect: (index, event) => {+ if (showCreateRow() && index === createRowIndex()) {+ beginCreate();+ return;+ }++ if (showClearAllRow() && index === clearAllRowIndex()) {+ clearAll();+ return;+ }++ const item = filteredItems()[index];+ if (item) pick(item, event);+ },+ onClose: () => (props.confirmsWithDone ? props.onClose() : saveAndClose()),+ enableNumericHotkeys: false,+ });++ // Reset selected index to top when search term or list changes.+ createEffect(() => {+ if (createStep()) return;+ search();+ filteredItems().length;+ dropdown.setSelectedIndex(0);+ });++ createEffect(() => {+ if (createStep()) return;+ const index = dropdown.selectedIndex();+ if (!dropdown.keyboardMode() || !scrollContainerRef) return;++ const row = scrollContainerRef.querySelector<HTMLDivElement>(+ `[data-tag-index="${index}"]`+ );+ row?.scrollIntoView({ block: 'nearest' });+ });++ const handleKeyDown = (event: KeyboardEvent) => {+ if (saved()) return;+ if (createStep()) {+ handleCreateKeyDown(event);+ return;+ }+ dropdown.handleKeyDown(event);+ };++ onMount(() => {+ document.addEventListener('keydown', handleKeyDown);+ });+ onCleanup(() => {+ document.removeEventListener('keydown', handleKeyDown);+ });++ return {+ search,+ setSearch: (value: string) => {+ setSearch(value);+ dropdown.setSearchQuery(value);+ },+ isSelected,+ pick,+ clearAll,+ persistSelection,+ saveAndClose,+ filteredItems,+ selectedAtOpenItems,+ remainingItemsForScope,+ hasTags: () => initialTagState().items.length > 0,+ showCreateRow,+ showClearAllRow,+ showCreateRowDivider,+ itemIndex,+ clearAllRowIndex,+ createRowIndex,+ createLabel,+ teamName,+ scopeOptions,+ createStep,+ setCreateStep,+ createDraftLabel,+ selectedColorIndex,+ setSelectedColorIndex,+ selectedScopeIndex,+ setSelectedScopeIndex,+ creating: () => addOption.isPending || ensureTagSet.isPending,+ beginCreate,+ beginEdit,+ openTaggedItems,+ createTag,+ dropdown,+ setScrollContainer: (element: HTMLDivElement) => {+ scrollContainerRef = element;+ },+ };+}++export type TagPickerSession = ReturnType<typeof createTagPickerSession>;diff --git a/apps/web/src/features/task-composer/components/title-editor.tsx b/apps/web/src/features/task-composer/components/title-editor.tsxindex d893569ffc..5f684de5e9 100644--- a/apps/web/src/features/task-composer/components/title-editor.tsx+++ b/apps/web/src/features/task-composer/components/title-editor.tsx@@ -11,6 +11,7 @@ import type { TagMentionLifecycle } from '@core/component/LexicalMarkdown/pluginimport { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';import {$getCaretRect,+ focusEditorWithoutScroll,forceSetTextContent,initializeEditorEmpty,isRectFlushWith,@@ -162,6 +163,8 @@ export function ComposeTaskTitleEditor(props: {onDeleteTagsAtStart?: () => boolean;portalScope?: PortalScope;ref?: (el: HTMLDivElement) => void;+ /** Focus the title once its editor attaches, with the caret after its text. */+ autofocus?: boolean;}) {const [state, setState] = createSignal(props.value());const [showPlaceholder, setShowPlaceholder] = createSignal(@@ -270,6 +273,10 @@ export function ComposeTaskTitleEditor(props: {const onConnect = (el: HTMLDivElement) => {editor.setRootElement(el);setRootConnected(true);+ if (props.autofocus) {+ editor.update(() => $getRoot().selectEnd(), { discrete: true });+ focusEditorWithoutScroll(editor);+ }};return (diff --git a/apps/web/src/features/task-composer/compose-task.tsx b/apps/web/src/features/task-composer/compose-task.tsxindex 3528292e29..977ba77a3d 100644--- a/apps/web/src/features/task-composer/compose-task.tsx+++ b/apps/web/src/features/task-composer/compose-task.tsx@@ -31,6 +31,7 @@ function createSplitTaskComposerHost(): TaskComposerHost {userId: useUserId(),resolveAppLink: useMacroMentionLinkResolver(),isPopover: () => splitPanel.handle.isPopover(),+ fillSheet: () => splitPanel.fillDrawer?.(),setDisplayName: (name) => splitPanel.handle.setDisplayName(name),close: () => splitPanel.handle.close(),openComposer: (params) =>diff --git a/apps/web/src/features/task-composer/new-task-title-focus.ts b/apps/web/src/features/task-composer/new-task-title-focus.tsnew file mode 100644index 0000000000..0fac1d077b--- /dev/null+++ b/apps/web/src/features/task-composer/new-task-title-focus.ts@@ -0,0 +1,28 @@+import {+ focusStandInActive,+ triggerFocusInput,+} from '@core/directive/focusInput';+import { isTouchDevice } from '@core/mobile/isTouchDevice';++/** Marks a task composer's title, so the tap that opens one can find it. */+export const TASK_COMPOSER_TITLE_ATTRIBUTE = 'data-task-composer-title';++const titleEditors = () =>+ document.querySelectorAll<HTMLElement>(+ `[${TASK_COMPOSER_TITLE_ATTRIBUTE}] [contenteditable="true"]`+ );++/**+ * Raises the phone keyboard for the title of the task composer this tap+ * opens. iOS shows it only for a focus made inside the tap, and the composer+ * mounts later, so a stand-in input holds it until the new title appears.+ * Call it synchronously in the tap; kept apart from the composer so callers+ * don't load it.+ */+export function raiseKeyboardForNewTaskTitle() {+ if (!isTouchDevice() || focusStandInActive()) return;+ const open = new Set(titleEditors());+ triggerFocusInput(() =>+ Array.from(titleEditors()).find((title) => !open.has(title))+ );+}diff --git a/apps/web/src/features/task-composer/primitives/task-composer.ts b/apps/web/src/features/task-composer/primitives/task-composer.tsindex eedc0fc98c..542f3f770c 100644--- a/apps/web/src/features/task-composer/primitives/task-composer.ts+++ b/apps/web/src/features/task-composer/primitives/task-composer.ts@@ -64,6 +64,11 @@ export type TaskComposerHost = {resolveAppLink: MentionLinkResolver | undefined;/** Whether the composer floats over the layout rather than filling a split. */isPopover: Accessor<boolean>;+ /**+ * Opens the touch sheet at a fixed height for as long as the calling owner+ * lives, so the composer's body can fill it.+ */+ fillSheet(): void;setDisplayName(name: string): void;close(): void;/** Opens another composer on a recovered submission. */@@ -582,10 +587,6 @@ export function createTaskComposer(if (container) {attachHotkeys(container);}- // An empty title (e.g. a task started from an email) waits for the user.- if (!title().trim()) {- requestAnimationFrame(() => titleEditorRoot?.focus());- }});registerHotkey({@@ -647,9 +648,17 @@ export function createTaskComposer(setTitleEditorRoot: (el: HTMLDivElement) => {titleEditorRoot = el;},+ /**+ * Whether the title takes focus as the composer opens. Always on touch,+ * where the opening tap raised the keyboard for it+ * (`raiseKeyboardForNewTaskTitle`); elsewhere a title that already has+ * text (a task started from an email) waits for the user.+ */+ autofocusTitle: isTouchDevice() || !title().trim(),editorConfig,portalScope,isPopover: host.isPopover,+ fillSheet: host.fillSheet,isCreating,errorMessage,setErrorMessage,diff --git a/apps/web/src/features/task-composer/views/mobile-task-composer.tsx b/apps/web/src/features/task-composer/views/mobile-task-composer.tsxindex a01bbcafba..1ed2a4a801 100644--- a/apps/web/src/features/task-composer/views/mobile-task-composer.tsx+++ b/apps/web/src/features/task-composer/views/mobile-task-composer.tsx@@ -1,4 +1,6 @@import { onElementConnect } from '@core/util/onElementConnect';+import { Property } from '@property';+import { InlineTagsSheetPill } from '@property/tags';import { cn, EntityComposer } from '@ui';import { createSignal, onCleanup } from 'solid-js';import type { TaskComposerController } from '../primitives/task-composer';@@ -8,6 +10,9 @@ import { TaskComposer } from './task-composer-parts';export function MobileTaskComposer(props: {composer: TaskComposerController;}) {+ // Opens taller than its content, the description taking the room above the+ // properties.+ props.composer.fillSheet();// The keyboard leaves too little room for the whole composer, so the header// pins to the top of the sheet's scroll to keep Create Task in reach. It// only takes a background while pinned over content; at rest it would show@@ -27,9 +32,18 @@ export function MobileTaskComposer(props: {onCleanup(() => observer.disconnect());});};+ // Tapping a pill leaves focus in the title or description, so the keyboard+ // stays up under a menu and a picker sheet can hand it back.+ const keepTypingFocus = (event: PointerEvent | MouseEvent) => {+ if ((event.target as Element).closest('button')) event.preventDefault();+ };return (- <TaskComposer.Root composer={props.composer}>+ <TaskComposer.Root+ composer={props.composer}+ tagsPill={InlineTagsSheetPill}+ propertyEditor={Property.SheetEditor}+ ><EntityComposer.Headerref={observeHeader}class={cn(@@ -50,9 +64,14 @@ export function MobileTaskComposer(props: {</div></EntityComposer.Header><TaskComposer.Recovery />- {/* The sheet sizes the composer to its content, so nothing needs- clipping, and the property row can scroll to the sheet's edges. */}- <EntityComposer.Main class="overflow-visible">+ {/* The sheet scrolls rather than shrinking the composer below its+ content, so nothing needs clipping, and the property row can scroll+ to the sheet's edges. */}+ <EntityComposer.Main+ class="overflow-visible"+ onPointerDown={keepTypingFocus}+ onMouseDown={keepTypingFocus}+ ><TaskComposer.Title /><TaskComposer.Body /><div class="shrink-0 flex items-center py-2">diff --git a/apps/web/src/features/task-composer/views/task-composer-parts.tsx b/apps/web/src/features/task-composer/views/task-composer-parts.tsxindex b9350d1df2..6f3f7d99c2 100644--- a/apps/web/src/features/task-composer/views/task-composer-parts.tsx+++ b/apps/web/src/features/task-composer/views/task-composer-parts.tsx@@ -8,6 +8,7 @@ import { fireAndForget } from '@core/util/fireAndForget';import ArrowsOutIcon from '@icon/system/regular/arrows-out.svg';import PaperclipIcon from '@icon/system/regular/paperclip.svg';import XIcon from '@icon/system/regular/x.svg';+import { Property } from '@property';import { Modals } from '@property/component/modal';import { PropertiesProvider } from '@property/context/PropertiesContext';import { InlineTagsPill } from '@property/tags';@@ -20,11 +21,13 @@ import {Suspense,useContext,} from 'solid-js';+import { Dynamic } from 'solid-js/web';import { tabbable } from 'tabbable';import {ComposeTaskTitleEditor,TaskTitleAccessory,} from '../components/title-editor';+import { TASK_COMPOSER_TITLE_ATTRIBUTE } from '../new-task-title-focus';import type { TaskComposerController } from '../primitives/task-composer';const TaskComposerPartsContext = createContext<TaskComposerController>();@@ -37,15 +40,40 @@ function useTaskComposer() {return composer;}+/** The pickers the parts open; a touch sheet's view picks in stacked sheets. */+type TaskComposerPickers = {+ tagsPill: typeof InlineTagsPill;+ propertyEditor: typeof Property.PopoverEditor;+};++const TaskComposerPickersContext = createContext<TaskComposerPickers>({+ tagsPill: InlineTagsPill,+ propertyEditor: Property.PopoverEditor,+});+function Root(props: {composer: TaskComposerController;+ /** The tags pill; `InlineTagsSheetPill` inside a touch sheet. */+ tagsPill?: typeof InlineTagsPill;+ /** The editor property pills open; `Property.SheetEditor` inside a touch sheet. */+ propertyEditor?: typeof Property.PopoverEditor;children: JSX.Element;}) {+ const pickers: TaskComposerPickers = {+ get tagsPill() {+ return props.tagsPill ?? InlineTagsPill;+ },+ get propertyEditor() {+ return props.propertyEditor ?? Property.PopoverEditor;+ },+ };return (<TaskComposerPartsContext.Provider value={props.composer}>- <EntityComposer.Root tabIndex={-1} ref={props.composer.setContainerRef}>- {props.children}- </EntityComposer.Root>+ <TaskComposerPickersContext.Provider value={pickers}>+ <EntityComposer.Root tabIndex={-1} ref={props.composer.setContainerRef}>+ {props.children}+ </EntityComposer.Root>+ </TaskComposerPickersContext.Provider></TaskComposerPartsContext.Provider>);}@@ -144,11 +172,13 @@ function Recovery() {function Title() {const composer = useTaskComposer();+ const pickers = useContext(TaskComposerPickersContext);return (- <EntityComposer.Title>+ <EntityComposer.Title {...{ [TASK_COMPOSER_TITLE_ATTRIBUTE]: '' }}><Show when={composer.tagLayoutMode() === 'title'}><TaskTitleAccessory>- <InlineTagsPill+ <Dynamic+ component={pickers.tagsPill}docTags={composer.composerTags}variant="secondary"size="xs"@@ -179,6 +209,7 @@ function Title() {onDeleteTagsAtStart={composer.deleteTitleTagsAtStart}portalScope={composer.portalScope()}ref={composer.setTitleEditorRoot}+ autofocus={composer.autofocusTitle}/></EntityComposer.Title>);@@ -242,6 +273,7 @@ function Attach() {/** The property pills, tags, and Add property; `class` places the row. */function Properties(props: { class?: string }) {const composer = useTaskComposer();+ const pickers = useContext(TaskComposerPickersContext);return (<Suspense fallback={<div class="h-7" />}><PropertiesProvider@@ -274,11 +306,13 @@ function Properties(props: { class?: string }) {<InlinePropertyValueproperty={property}emptyLabel={property.displayName}+ editor={pickers.propertyEditor}/>)}</For><Show when={composer.tagLayoutMode() === 'bottom'}>- <InlineTagsPill+ <Dynamic+ component={pickers.tagsPill}docTags={composer.composerTags}variant="secondary"size="xs"diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsxindex 98e0a7a133..9e5de1f796 100644--- a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsx@@ -1,4 +1,4 @@-import type { EventFormProps } from '@app/features/calendar/components/composer/EventForm';+import type { EventFormProps } from '@app/features/calendar/components/composer/event-form-state';import type { VisibleCalendar } from '@queries/calendar/calendars';import type { CreateCalendarEvent } from '@service-cognition/generated/tools/types';import type { Link } from '@service-email/generated/schemas';diff --git a/apps/web/src/lib/core/directive/focusInput.ts b/apps/web/src/lib/core/directive/focusInput.tsindex 72e4a5ff00..3a027599f5 100644--- a/apps/web/src/lib/core/directive/focusInput.ts+++ b/apps/web/src/lib/core/directive/focusInput.ts@@ -3,6 +3,17 @@ import { isPlatform } from '@core/util/platform';import { isIOS } from '@solid-primitives/platform';import { type Accessor, onCleanup } from 'solid-js';+const STAND_IN_ATTRIBUTE = 'data-focus-stand-in';++/**+ * Whether focus is on `triggerFocusInput`'s stand-in, holding the phone+ * keyboard for an input still mounting. Overlays opening meanwhile leave focus+ * there rather than taking it and dropping the keyboard.+ */+export function focusStandInActive() {+ return document.activeElement?.hasAttribute(STAND_IN_ATTRIBUTE) ?? false;+}+type FocusInputOptions = {getTarget: () => HTMLElement | null | undefined;positionNear?: HTMLElement;@@ -63,6 +74,7 @@ export function triggerFocusInput(// click gesture so the virtual keyboard opens, then transfer focus to// the real target once it appears in the DOM.tempEl = document.createElement('input');+ tempEl.setAttribute(STAND_IN_ATTRIBUTE, '');// Use fixed positioning (viewport-relative) so focusing the temp element// doesn't cause the page to scroll.const anchorRect = anchor?.getBoundingClientRect();diff --git a/apps/web/src/lib/i18n/locales/en/mobile.ts b/apps/web/src/lib/i18n/locales/en/mobile.tsindex e5ecb86ddf..ce23b36aeb 100644--- a/apps/web/src/lib/i18n/locales/en/mobile.ts+++ b/apps/web/src/lib/i18n/locales/en/mobile.ts@@ -30,4 +30,7 @@ export default {closeConfirmation: 'Close confirmation',cancel: 'Cancel',confirm: 'Confirm',++ // Picker sheet+ done: 'Done',};diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex a4824760af..e87e32d36e 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -230,13 +230,30 @@ new session from the same meeting link must start a separate chat thread.Calendar event creation and editing open in a bottom sheet on touch devices,-with scrollable content above the keyboard. When the form outgrows the sheet, as-it does with the custom repeat builder open, the sheet scrolls down to the-footer: Cancel and `Create event` or `Save`, plus `This event`/`All events` when-editing a recurring event. Desktop retains the centered dialog.-Dismissing a changed event by Cancel, swipe, backdrop tap or Escape still asks-before discarding the draft; Keep editing returns to the sheet with the edits-intact, and the prompt stays away until the next attempt to close.+with scrollable content above the keyboard. `Create event` or `Save` sits at+the top right of the sheet's pinned chrome, below the handle, so it stays in+reach while the form scrolls. The title and description come first, then+`Event` and `Out of office` as selectable labels. A section of rows holds+All-day (switch on the right), Starts and Ends (date and time), and Repeat; a+second has one row each for Calendar, Guests, Call, Location, and Reminders+(Declines and Message for out-of-office events). Location is a text field in+its row, so the sheet scrolls it above the keyboard. Guest permissions follow, one+per row. Guests opens its own sheet over the composer, as tall as the event+sheet, with Cancel, the `Guests` title, and Done; its list fills the sheet.+Picks apply only on Done, and Cancel, the backdrop, or Escape drop them; the+guest sheet has no handle and does not drag, since a drag there also reached+the event sheet beneath. Picking a guest keeps the keyboard up. The title+sits directly below the pinned chrome. The sheet has no Cancel: drag, the+backdrop, or Escape dismiss it.+`This event`/`All events` sits at the bottom when editing a recurring event.+Desktop retains the centered dialog with inline dates, wrapping pills, and its+Cancel footer; both layouts compose `EventFormParts` (`MobileEventForm` and+`EventForm`), and the range rows compose `DateTimeRange` parts.+Dismissing a changed event by swipe, backdrop tap or Escape still asks before+discarding the draft; Keep editing returns to the sheet with the edits intact,+and the prompt stays away until the next attempt to close. An event created+from Home's **+ New** → Event opens the calendar on it once it saves, with its+details showing; events created inside the calendar stay where they were made.On phones, event details use inset round action buttons and a transparent RSVPfooter. Answering a recurring invitation opens a rounded glass sheet: choosediff --git a/docs/agent-guide/tasks.md b/docs/agent-guide/tasks.mdindex 055edefe32..add4724fe4 100644--- a/docs/agent-guide/tasks.md+++ b/docs/agent-guide/tasks.md@@ -594,7 +594,10 @@ Use existing PRs and do not modify hosted data.## Create a taskOn touch devices, task creation opens in a bottom sheet with a drag handle and-scrollable, keyboard-aware content. Its glass pane has broad screen-scaled+scrollable, keyboard-aware content. It opens at 70% of the screen, with the+description filling the room above the properties; the keyboard shortens it.+Opening it from `+ Task` or Home's `+ New` raises the keyboard with the title+focused and the caret after any text. Its glass pane has broad screen-scaledcorners, an 8px outer inset, and a blurred backdrop, matching the create andfilter sheets. Its header has `Continue editing in split` on the left and`Create Task` on the right, with a text-only `Clear` 32px to its left once the@@ -604,8 +607,14 @@ top of the sheet (with a solid background only while pinned over content), so`Create Task` stays in reach. The properties sit on a single line that scrollshorizontally, with the `Share with <team name>` switch below them. The sheethas no `Create More` switch and no similar-tasks list. `Create Task` shows no-keyboard shortcut on touch. While the keyboard is up, the tag picker opens-above its trigger so its search results stay above the keyboard. Desktop uses+keyboard shortcut on touch. Assignees, Project, Tags, and Due Date open their+pickers in a full-height sheet stacked over the composer (`PickerSheet`), with+Cancel, the property's name, and Done: picks apply on Done, Cancel or the+backdrop drop them, picking keeps the keyboard up, and a single-choice Project+or a date applies its pick at once. Status and Priority keep their dropdowns,+which leave focus in the title. Tapping a pill doesn't take focus, and closing+a picker sheet returns it to the title or description with its caret, so the+keyboard stays up throughout. Desktop usesthe centered composer dialog. Both layouts are views in`apps/web/src/features/task-composer/views` composing the shared`TaskComposer` parts.