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(calendar): UI and UX redesign (#7047)
dev-rbdce3b591bc6d
diff --git a/apps/web/src/components/app/mobile/MobilePageActionRow.test.tsx b/apps/web/src/components/app/mobile/MobilePageActionRow.test.tsxindex a1cfbae387..6fc7a1ac84 100644--- a/apps/web/src/components/app/mobile/MobilePageActionRow.test.tsx+++ b/apps/web/src/components/app/mobile/MobilePageActionRow.test.tsx@@ -310,13 +310,15 @@ describe('Mobile page action row', () => {expect(mocks.createMenu).not.toHaveBeenCalled();expect(screen.getByRole('button', { name: 'Send' })).toBeTruthy();});- it('opens the event composer from the calendar New button', () => {+ it('opens the event composer from the Calendar New menu', async () => {mocks.view = 'calendar';render(() => <MobilePageActionRow />);- const createButton = screen.getByRole('button', { name: 'New event' });- expect(createButton.textContent).toBe('Event');+ const createButton = screen.getByRole('button', { name: 'New' });+ expect(createButton.textContent).toBe('New');fireEvent.click(createButton);- expect(mocks.openEvent).toHaveBeenCalledOnce();+ const menu = await screen.findByRole('dialog', { name: 'Create new' });+ fireEvent.click(within(menu).getByRole('button', { name: 'Event' }));+ await waitFor(() => expect(mocks.openEvent).toHaveBeenCalledOnce());});it('opens the create menu on views without a specific New action', () => {mocks.view = undefined;diff --git a/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsx b/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsxindex ec83a697d6..9aff4b4055 100644--- a/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsx+++ b/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsx@@ -98,14 +98,77 @@ describe('mobile create availability', () => {await vi.waitFor(() => expect(createTask).toHaveBeenCalledOnce());});- it('uses the same calendar gate for the page action and falls back to New', () => {- const { setCalendar } = setup('calendar');+ it('uses a Calendar New menu when enabled and keeps the default fallback', async () => {+ const { setCalendar, setBlocks } = setup('calendar');fireEvent.click(screen.getByRole('button', { name: 'New' }));expect(sources.openMenu).toHaveBeenCalledWith(true);expect(sources.openEvent).not.toHaveBeenCalled();setCalendar(true);- fireEvent.click(screen.getByRole('button', { name: 'New event' }));- expect(sources.openEvent).toHaveBeenCalledOnce();+ const call = vi.fn(() => true);+ const reminder = vi.fn(() => true);+ setBlocks([+ {+ label: 'Call',+ description: 'New call',+ blockName: 'call',+ keyDownHandler: call,+ },+ {+ label: 'Reminder',+ description: 'New reminder',+ blockName: 'reminder',+ keyDownHandler: reminder,+ },+ ]);+ fireEvent.click(screen.getByRole('button', { name: 'New' }));+ const menu = await screen.findByRole('dialog', { name: 'Create new' });+ expect(+ Array.from(menu.querySelectorAll('button')).map(+ (button) => button.textContent+ )+ ).toEqual(['Event', 'Call', 'Reminder', 'New']);+ fireEvent.click(screen.getByRole('button', { name: 'Event' }));+ await vi.waitFor(() => expect(sources.openEvent).toHaveBeenCalledOnce());+ });++ it('omits unavailable Calendar Call and Reminder actions', async () => {+ const { setCalendar } = setup('calendar');+ setCalendar(true);+ fireEvent.click(screen.getByRole('button', { name: 'New' }));+ const menu = await screen.findByRole('dialog', { name: 'Create new' });+ expect(menu.querySelectorAll('button')).toHaveLength(2);+ expect(screen.getByRole('button', { name: 'Event' })).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Call' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Reminder' })).toBeNull();+ });++ it('uses the gated Call and Reminder actions in the Calendar New menu', async () => {+ const { setCalendar, setBlocks } = setup('calendar');+ setCalendar(true);+ const call = vi.fn(() => true);+ const reminder = vi.fn(() => true);+ setBlocks([+ {+ label: 'Call',+ description: 'New call',+ blockName: 'call',+ keyDownHandler: call,+ },+ {+ label: 'Reminder',+ description: 'New reminder',+ blockName: 'reminder',+ keyDownHandler: reminder,+ },+ ]);+ for (const [label, action] of [+ ['Call', call],+ ['Reminder', reminder],+ ] as const) {+ fireEvent.click(screen.getByRole('button', { name: 'New' }));+ fireEvent.click(await screen.findByRole('button', { name: label }));+ await vi.waitFor(() => expect(action).toHaveBeenCalledOnce());+ }});});diff --git a/apps/web/src/components/app/mobile/MobilePageCreateButton.tsx b/apps/web/src/components/app/mobile/MobilePageCreateButton.tsxindex e144bba898..224781d1ea 100644--- a/apps/web/src/components/app/mobile/MobilePageCreateButton.tsx+++ b/apps/web/src/components/app/mobile/MobilePageCreateButton.tsx@@ -7,12 +7,14 @@ import {import { openCreateCompanyModal } from '@app/features/companies/CreateCompanyModal';import { hapticImpact } from '@core/mobile/haptics';import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';+import BellIcon from '@phosphor/bell.svg';import CalendarIcon from '@phosphor/calendar-blank.svg';import MessageIcon from '@phosphor/chat-circle.svg';import MoreIcon from '@phosphor/dots-three.svg';import EmailIcon from '@phosphor/envelope-simple.svg';import DocumentIcon from '@phosphor/file-text.svg';import TaskIcon from '@phosphor/list-checks.svg';+import PhoneIcon from '@phosphor/phone.svg';import CreateIcon from '@phosphor/plus.svg';import { Show } from 'solid-js';import {@@ -62,6 +64,36 @@ export function MobilePageCreateButton() {}),{ label: 'More', icon: MoreIcon, onSelect: openCreateMenu },];+ const calendarActions = (): MobileCreateMenuItem[] => {+ const blocks = createBlocks();+ const call = blocks.find((block) => block.blockName === 'call');+ const reminder = blocks.find((block) => block.blockName === 'reminder');+ return [+ {+ label: 'Event',+ icon: CalendarIcon,+ onSelect: () => openEventComposer(),+ },+ ...(call+ ? [+ {+ label: 'Call',+ icon: PhoneIcon,+ onSelect: () => void call.keyDownHandler(),+ },+ ]+ : []),+ ...(reminder+ ? [+ {+ label: 'Reminder',+ icon: BellIcon,+ onSelect: () => void reminder.keyDownHandler(),+ },+ ]+ : []),+ ];+ };const action = () =>actionForView(foregroundView()) ?? {label: 'New',@@ -73,22 +105,29 @@ export function MobilePageCreateButton() {<Showwhen={foregroundView() === 'home'}fallback={- <MobileDockIsland class="shrink-0">- <button- type="button"- aria-label={- action().label === 'New'- ? 'New'- : `New ${action().label.toLowerCase()}`- }- onPointerDown={() => hapticImpact('light')}- onClick={() => action().onSelect()}- class="relative flex h-(--mobile-chrome-button-size) shrink-0 items-center justify-center gap-1.5 rounded-full pl-3 pr-4 text-base font-medium whitespace-nowrap"- >- <CreateIcon class="size-5.5 shrink-0" />- <span>{action().label}</span>- </button>- </MobileDockIsland>+ <Show+ when={foregroundView() === 'calendar' && calendarEnabled()}+ fallback={+ <MobileDockIsland class="shrink-0">+ <button+ type="button"+ aria-label={+ action().label === 'New'+ ? 'New'+ : `New ${action().label.toLowerCase()}`+ }+ onPointerDown={() => hapticImpact('light')}+ onClick={() => action().onSelect()}+ class="relative flex h-(--mobile-chrome-button-size) shrink-0 items-center justify-center gap-1.5 rounded-full pl-3 pr-4 text-base font-medium whitespace-nowrap"+ >+ <CreateIcon class="size-5.5 shrink-0" />+ <span>{action().label}</span>+ </button>+ </MobileDockIsland>+ }+ >+ <MobileCreateMenu items={calendarActions()} />+ </Show>}><MobileCreateMenu items={quickActions()} />diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex 59da755f38..2751d50003 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -177,7 +177,13 @@ registerComponent(() => <TasksRouteView />,() => composableLayout(true));-registerComponent('calendar', () => <CalendarRouteView />);+registerComponent(+ 'calendar',+ () => <CalendarRouteView />,+ // Desktop Calendar draws its own top bar. Touch still needs the split header+ // for the floating month and action controls.+ () => (isTouchDevice() ? undefined : { splitPanelLayout: 'composable' })+);registerComponent('channels',() => <ChannelsRouteView />,diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsxindex 7bac41fba7..3ed73c1efe 100644--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx@@ -7,6 +7,7 @@ const state = vi.hoisted(() => ({authenticated: (): boolean => true,enabled: (): boolean => false,flagsLoaded: (): boolean => true,+ touch: (): boolean => false,replace: vi.fn(),pageView: vi.fn(),track: vi.fn(),@@ -101,7 +102,7 @@ vi.mock('@block-md/component/ComposeTask', () => ({}));vi.mock('@companies/crm/saved-views', () => ({}));vi.mock('@core/context/user', () => ({}));vi.mock('@core/mobile/isTouchDevice', () => ({- isTouchDevice: () => false,+ isTouchDevice: () => state.touch(),}));vi.mock('@queries/agent-schedule/entities', () => ({}));vi.mock('@ui', () => ({@@ -113,6 +114,7 @@ beforeEach(() => {state.authenticated = () => true;state.enabled = () => false;state.flagsLoaded = () => true;+ state.touch = () => false;});afterEach(cleanup);@@ -120,6 +122,15 @@ function renderActivity() {const activity = resolveComponent('activity');return render(() => <Suspense>{activity.element()}</Suspense>);}+describe('calendar layout registration', () => {+ it('owns desktop chrome but keeps the floating split header on touch', () => {+ expect(resolveComponent('calendar').initialMeta).toMatchObject({+ splitPanelLayout: 'composable',+ });+ state.touch = () => true;+ expect(resolveComponent('calendar').initialMeta).toBeUndefined();+ });+});describe('activity registration', () => {it('redirects a disabled feed to inbox without mounting or tracking it', () => {diff --git a/apps/web/src/components/ui/components/Tooltip.tsx b/apps/web/src/components/ui/components/Tooltip.tsxindex 6f555d5597..c93434982b 100644--- a/apps/web/src/components/ui/components/Tooltip.tsx+++ b/apps/web/src/components/ui/components/Tooltip.tsx@@ -19,6 +19,8 @@ type TooltipProps = ParentProps<{as?: 'div' | 'span';class?: string;label: string;+ /** Allows non-interactive tooltip targets, such as disabled actions, to receive keyboard focus. */+ tabIndex?: number;disabled?: boolean;}>;@@ -126,6 +128,7 @@ export function Tooltip(props: TooltipProps) {setTriggerRef(ref);}}class={cn('inline-flex items-center', props.class)}+ tabIndex={props.tabIndex}as={props.as ?? 'div'}>{props.children}diff --git a/apps/web/src/components/view-shell/SearchBar.tsx b/apps/web/src/components/view-shell/SearchBar.tsxindex addd0eaadb..5767e4cc2a 100644--- a/apps/web/src/components/view-shell/SearchBar.tsx+++ b/apps/web/src/components/view-shell/SearchBar.tsx@@ -3,7 +3,7 @@ import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';import XIcon from '@phosphor/x.svg';import { mergeRefs } from '@solid-primitives/refs';import { Button, cn, Hotkey, Surface } from '@ui';-import type { JSX } from 'solid-js';+import type { JSX, JSXElement } from 'solid-js';import { Show, splitProps } from 'solid-js';export type SearchBarProps = Omit<@@ -19,6 +19,10 @@ export type SearchBarProps = Omit<* can restore keyboard focus to its list.*/onEscape?: () => void;+ /** Replaces the clear action with a close action in collapsible search fields. */+ onClose?: () => void;+ /** Controls shown after the input and before its clear or close action. */+ actions?: JSXElement;class?: string;inputClass?: string;};@@ -30,6 +34,8 @@ export function SearchBar(props: SearchBarProps) {'onValueChange','hotkey','onEscape',+ 'onClose',+ 'actions','class','inputClass','disabled',@@ -80,16 +86,30 @@ export function SearchBar(props: SearchBarProps) {aria-hidden="true"class="size-4 shrink-0 text-ink-extra-muted"/>- <TextField.Input- {...inputProps}- ref={mergeRefs((element) => (input = element), local.ref)}- type="search"- class={cn(- 'min-w-0 flex-1 border-0 bg-transparent text-sm text-ink outline-none placeholder:text-ink-placeholder focus:outline-none focus:ring-0 [&::-webkit-search-cancel-button]:hidden',- local.inputClass- )}- />- <Show when={!local.value && local.hotkey}>+ <div class="relative min-w-0 flex-1">+ <TextField.Input+ {...inputProps}+ ref={mergeRefs((element) => (input = element), local.ref)}+ type="search"+ class={cn(+ 'w-full min-w-0 border-0 bg-transparent text-sm text-ink outline-none placeholder:text-ink-placeholder focus:outline-none focus:ring-0 [&::-webkit-search-cancel-button]:hidden',+ local.hotkey &&+ inputProps.placeholder &&+ 'placeholder:text-transparent group-focus-within:placeholder:text-ink-placeholder',+ local.inputClass+ )}+ />+ <Show when={!local.value && local.hotkey && inputProps.placeholder}>+ <div+ aria-hidden="true"+ class="pointer-events-none absolute inset-0 flex items-center gap-2 overflow-hidden whitespace-nowrap text-sm text-ink-placeholder group-focus-within:hidden"+ >+ <span class="truncate">{inputProps.placeholder}</span>+ <Hotkey shortcut={local.hotkey} theme="subtle" class="shrink-0" />+ </div>+ </Show>+ </div>+ <Show when={!inputProps.placeholder && !local.value && local.hotkey}>{(hotkey) => (<Hotkeyshortcut={hotkey()}@@ -98,15 +118,20 @@ export function SearchBar(props: SearchBarProps) {/>)}</Show>- <Show when={local.value && !local.disabled && !local.readOnly}>+ {local.actions}+ <Show+ when={+ local.onClose || (local.value && !local.disabled && !local.readOnly)+ }+ ><Buttontype="button"size="sm"square- label="Clear search"+ label={local.onClose ? 'Close search' : 'Clear search'}class="rounded-lg"onPointerDown={(event) => event.preventDefault()}- onClick={clear}+ onClick={() => (local.onClose ?? clear)()}><XIcon /></Button>diff --git a/apps/web/src/components/view-shell/index.ts b/apps/web/src/components/view-shell/index.tsindex 390c7b82a7..0519fc501d 100644--- a/apps/web/src/components/view-shell/index.ts+++ b/apps/web/src/components/view-shell/index.ts@@ -40,6 +40,7 @@ export {} from './ViewBreadcrumbs';export {useViewShell,+ ViewNavigationControls,ViewShell,type ViewShellLayout,type ViewShellRootProps,diff --git a/apps/web/src/features/calendar-view/calendar-call-sidebar.tsx b/apps/web/src/features/calendar-view/calendar-call-sidebar.tsxindex 36d303f2c7..1433038ad2 100644--- a/apps/web/src/features/calendar-view/calendar-call-sidebar.tsx+++ b/apps/web/src/features/calendar-view/calendar-call-sidebar.tsx@@ -1,9 +1,9 @@-import { SidePanel } from '@components/app/side-panel/SidePanel';import { useUserId } from '@core/context/user';import { openExternalUrl } from '@core/util/url';import { getWebOrigin } from '@core/util/webOrigin';import { useNavigate } from '@solidjs/router';import { isSameDay, isTomorrow } from 'date-fns';+import { createDeferred } from 'solid-js';import { useCalendarView } from '../calendar/components/CalendarViewContext';import { formatCompactCalendarTime } from '../calendar/utils/time-format';import { calendarCallNavigation } from '../meetings/core/calendar-calls';@@ -14,29 +14,19 @@ import { useUpcomingCalendarEventsSource } from '../meetings/queries/upcoming-caimport { useQuickCallsFlag } from '../meetings/use-quick-calls-flag';import { CallSidebar } from '../meetings/views/call-sidebar';-export function CalendarCallsSidePanelSection() {- return (- <SidePanel.Section- id="calendar-calls"- title="Upcoming events"- order={15}- defaultOpen- >- <CalendarCallSidebar />- </SidePanel.Section>- );-}-/** Production wiring, mounted within the section's Suspense boundary. */-function CalendarCallSidebar() {+export function CalendarCallSidebar() {const calendar = useCalendarView();const userId = useUserId();const quickCalls = useQuickCallsFlag();const now = createCallSidebarClock();+ const renderedHiddenSourceIds = createDeferred(calendar.hiddenSourceIds);+ const isRenderedSourceVisible = (sourceId: string) =>+ !renderedHiddenSourceIds().has(sourceId);const upcoming = useUpcomingCalendarEventsSource({userId,sourceById: calendar.sourceById,- isSourceVisible: calendar.isSourceVisible,+ isSourceVisible: isRenderedSourceVisible,now,});const active = useActiveQuickCallsSource(() =>@@ -48,21 +38,31 @@ function CalendarCallSidebar() {const start = new Date(call.allDay ? `${call.start.slice(0, 10)}T00:00:00` : call.start);- const day = isSameDay(start, now())- ? 'Today'- : isTomorrow(start)- ? 'Tomorrow'- : start.toLocaleDateString([], {- month: 'short',- day: 'numeric',- });- if (call.allDay) return `${day} · All day`;- if (start <= now()) return 'Now';+ let day: string;+ if (isSameDay(start, now())) {+ day = 'Today';+ } else if (isTomorrow(start)) {+ day = 'Tomorrow';+ } else {+ day = start.toLocaleDateString([], {+ month: 'short',+ day: 'numeric',+ });+ }+ if (call.allDay) {+ return `${day} · All day`;+ }+ if (start <= now()) {+ return 'Now';+ }const time = formatCompactCalendarTime(start,calendar.displaySettings.timeFormat);- return isSameDay(start, now()) ? time : `${day} · ${time}`;+ if (isSameDay(start, now())) {+ return time;+ }+ return `${day} · ${time}`;}return (@@ -70,11 +70,13 @@ function CalendarCallSidebar() {sources={{ upcoming, active }}now={now}when={when}+ selectedEventId={calendar.selectedEvent()?.id}actions={{openEvent: (event, anchor) => {const calendarEvent = upcoming.findEvent(event.id);- if (calendarEvent)+ if (calendarEvent) {calendar.selectEvent(calendarEvent, anchor, 'agenda');+ }},join: (url) => {const target = calendarCallNavigation(url, getWebOrigin());diff --git a/apps/web/src/features/calendar-view/components/CalendarCreateItems.tsx b/apps/web/src/features/calendar-view/components/CalendarCreateItems.tsxnew file mode 100644index 0000000000..c8138d819a--- /dev/null+++ b/apps/web/src/features/calendar-view/components/CalendarCreateItems.tsx@@ -0,0 +1,67 @@+import { useQuickCallsFlag } from '@app/features/meetings/use-quick-calls-flag';+import { openStandaloneReminderComposer } from '@app/features/reminders/reminder-composer';+import { ShowFeatureFlag } from '@app/lib/analytics/posthog';+import { enableReminders } from '@core/constant/featureFlags';+import BellIcon from '@phosphor/bell.svg';+import CalendarIcon from '@phosphor/calendar-blank.svg';+import PhoneIcon from '@phosphor/phone.svg';+import { useNavigate } from '@solidjs/router';+import { Dropdown } from '@ui';+import { Show } from 'solid-js';+import { useOpenEventComposer } from './use-open-event-composer';++type CreateItemProps = { onSelect?: () => void };++export function CalendarCreateEventItem(props: CreateItemProps) {+ const openEventComposer = useOpenEventComposer();++ return (+ <Dropdown.Item+ closeOnSelect+ onSelect={() => {+ props.onSelect?.();+ void openEventComposer();+ }}+ >+ <CalendarIcon class="size-4" />+ Event+ </Dropdown.Item>+ );+}++export function CalendarCreateCallItem(props: CreateItemProps) {+ const quickCalls = useQuickCallsFlag();+ const navigate = useNavigate();++ return (+ <Show when={quickCalls().enabled}>+ <Dropdown.Item+ closeOnSelect+ onSelect={() => {+ props.onSelect?.();+ navigate('/meet/new');+ }}+ >+ <PhoneIcon class="size-4" />+ Call+ </Dropdown.Item>+ </Show>+ );+}++export function CalendarCreateReminderItem(props: CreateItemProps) {+ return (+ <ShowFeatureFlag flag={enableReminders}>+ <Dropdown.Item+ closeOnSelect+ onSelect={() => {+ props.onSelect?.();+ openStandaloneReminderComposer();+ }}+ >+ <BellIcon class="size-4" />+ Reminder+ </Dropdown.Item>+ </ShowFeatureFlag>+ );+}diff --git a/apps/web/src/features/calendar-view/components/CalendarCreateMenu.tsx b/apps/web/src/features/calendar-view/components/CalendarCreateMenu.tsxnew file mode 100644index 0000000000..db1f8e19c3--- /dev/null+++ b/apps/web/src/features/calendar-view/components/CalendarCreateMenu.tsx@@ -0,0 +1,27 @@+import { type ButtonSize, Dropdown } from '@ui';+import type { JSX } from 'solid-js';++/** Menu presentation; consumers compose its trigger and creation items. */+export function CalendarCreateMenu(props: {+ trigger: JSX.Element;+ children: JSX.Element;+ class?: string;+ contentClass?: string;+ size?: ButtonSize;+ label?: string;+}) {+ return (+ <Dropdown placement="bottom-start">+ <Dropdown.Trigger+ size={props.size ?? 'sm'}+ class={props.class}+ label={props.label}+ >+ {props.trigger}+ </Dropdown.Trigger>+ <Dropdown.Content class={props.contentClass ?? 'min-w-40'}>+ <Dropdown.Group>{props.children}</Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ );+}diff --git a/apps/web/src/features/calendar-view/components/CalendarPeopleFilterSubmenu.tsx b/apps/web/src/features/calendar-view/components/CalendarPeopleFilterSubmenu.tsxnew file mode 100644index 0000000000..4dfe33a577--- /dev/null+++ b/apps/web/src/features/calendar-view/components/CalendarPeopleFilterSubmenu.tsx@@ -0,0 +1,236 @@+import { UserIcon } from '@core/component/UserIcon';+import { emailToMacroId } from '@core/user/macroId';+import type { IUser } from '@core/user/types';+import CaretRightIcon from '@phosphor/caret-right.svg';+import SearchIcon from '@phosphor/magnifying-glass.svg';+import PlusIcon from '@phosphor/plus.svg';+import { Dropdown } from '@ui';+import * as EmailValidator from 'email-validator';+import {+ type Accessor,+ createEffect,+ createMemo,+ createSignal,+ onCleanup,+ Show,+} from 'solid-js';+import { Virtualizer } from 'virtua/solid';++const CONTACT_ROW_HEIGHT = 32;+const MAX_CONTACT_LIST_HEIGHT = 240;++function FilterLabel(props: { label: string; active: boolean }) {+ return (+ <>+ <span class="flex-1 text-ink">{props.label}</span>+ <Show when={props.active}>+ <span aria-hidden="true" class="size-1.5 rounded-full bg-accent" />+ </Show>+ <CaretRightIcon class="size-3 shrink-0 text-ink-muted" />+ </>+ );+}++/** Search contacts or add an email address that is not in the contact list. */+export function CalendarPeopleFilterSubmenu(props: {+ label: string;+ contacts: Accessor<IUser[]>;+ loading: Accessor<boolean>;+ error: Accessor<boolean>;+ values: Accessor<string[]>;+ onChange: (emails: string[]) => void;+}) {+ const [open, setOpen] = createSignal(false);+ const [search, setSearch] = createSignal('');+ const [inputRef, setInputRef] = createSignal<HTMLInputElement>();+ let listViewport: HTMLDivElement | undefined;+ const [contentRef, setContentRef] = createSignal<HTMLElement>();+ const normalizedSearch = () => search().trim().toLowerCase();+ const scrollToTop = () => {+ if (listViewport?.isConnected) listViewport.scrollTop = 0;+ };+ const matches = createMemo(() => {+ const text = normalizedSearch();+ const contacts = props.contacts();+ const contactEmails = new Set(+ contacts.map((contact) => contact.email.toLowerCase())+ );+ const customSelected: IUser[] = props+ .values()+ .filter((email) => !contactEmails.has(email))+ .map((email) => ({+ id: emailToMacroId(email) ?? email,+ email,+ name: email,+ }));+ return [...customSelected, ...contacts].filter(+ (contact) =>+ contact.name.toLowerCase().includes(text) ||+ contact.email.toLowerCase().includes(text)+ );+ });+ const canAddEmail = () => {+ const email = normalizedSearch();+ return (+ EmailValidator.validate(email) &&+ !props.contacts().some((contact) => contact.email.toLowerCase() === email)+ );+ };+ const toggleEmail = (email: string) => {+ const values = props.values();+ props.onChange(+ values.includes(email)+ ? values.filter((value) => value !== email)+ : [...values, email]+ );+ };+ const setMenuOpen = (next: boolean) => {+ setOpen(next);+ if (!next) setSearch('');+ };++ // Kobalte registers the nested dismissable layer after mounting the submenu.+ // Focus after that registration, and recover focus if the trigger steals it+ // while the pointer crosses into the submenu.+ createEffect(() => {+ const input = inputRef();+ if (!open() || !input) return;+ const frame = requestAnimationFrame(() => {+ if (open()) input.focus();+ });+ const handleBlur = (event: FocusEvent) => {+ const next = event.relatedTarget;+ if (next instanceof Node && contentRef()?.contains(next)) return;+ queueMicrotask(() => {+ if (open() && document.activeElement !== input) input.focus();+ });+ };+ input.addEventListener('blur', handleBlur);+ onCleanup(() => {+ cancelAnimationFrame(frame);+ input.removeEventListener('blur', handleBlur);+ });+ });++ return (+ <Dropdown.Sub open={open()} onOpenChange={setMenuOpen}>+ <Dropdown.SubTrigger+ onPointerEnter={(+ event: PointerEvent & { currentTarget: HTMLElement }+ ) => {+ if (event.pointerType !== 'mouse') return;+ event.currentTarget.focus({ preventScroll: true });+ if (!open()) setMenuOpen(true);+ }}+ >+ <FilterLabel label={props.label} active={props.values().length > 0} />+ </Dropdown.SubTrigger>+ <Dropdown.SubContent+ ref={setContentRef}+ portalScope="local"+ data-calendar-search-filters=""+ class="w-65 max-w-[90vw]"+ >+ <Dropdown.Group class="gap-0 p-0">+ <div class="flex items-center gap-2 border-b border-edge-muted px-3 py-2">+ <SearchIcon class="size-3.5 shrink-0 text-ink-muted" />+ <input+ ref={setInputRef}+ type="text"+ aria-label={`Search ${props.label.toLowerCase()} contacts`}+ placeholder="Search contacts or enter email"+ value={search()}+ onInput={(event) => {+ setSearch(event.currentTarget.value);+ scrollToTop();+ }}+ onKeyDown={(event) => {+ if (event.key === 'Escape' || event.key === 'ArrowDown') return;+ event.stopPropagation();+ }}+ class="min-w-0 flex-1 bg-transparent text-sm text-ink outline-none placeholder:text-ink-placeholder"+ />+ </div>+ <Show+ when={!props.loading()}+ fallback={+ <div+ role="status"+ aria-label="Loading contacts"+ class="space-y-1 p-1"+ >+ <div class="skeleton-shimmer h-8 rounded-md bg-skeleton" />+ <div class="skeleton-shimmer h-8 rounded-md bg-skeleton" />+ </div>+ }+ >+ <Show when={matches().length > 0}>+ <div+ ref={(element) => (listViewport = element)}+ class="overflow-y-auto p-1"+ style={{+ height: `${Math.min(+ matches().length * CONTACT_ROW_HEIGHT + 8,+ MAX_CONTACT_LIST_HEIGHT+ )}px`,+ }}+ >+ <Virtualizer data={matches()} itemSize={CONTACT_ROW_HEIGHT}>+ {(contact) => (+ <Dropdown.CheckboxItem+ class="h-8"+ closeOnSelect={false}+ checked={props+ .values()+ .includes(contact.email.toLowerCase())}+ onChange={() => toggleEmail(contact.email.toLowerCase())}+ >+ <UserIcon+ id={contact.id}+ size="sm"+ suppressClick+ showTooltip={false}+ />+ <span class="min-w-0 flex-1 truncate">+ {contact.name}+ </span>+ </Dropdown.CheckboxItem>+ )}+ </Virtualizer>+ </div>+ </Show>+ </Show>+ <Show when={canAddEmail()}>+ <Dropdown.Item+ closeOnSelect={false}+ onSelect={() => {+ const email = normalizedSearch();+ inputRef()?.focus();+ toggleEmail(email);+ setSearch('');+ queueMicrotask(scrollToTop);+ }}+ >+ <PlusIcon class="size-3.5" />+ <span class="min-w-0 flex-1 truncate">+ {props.values().includes(normalizedSearch()) ? 'Remove' : 'Add'}{' '}+ {normalizedSearch()}+ </span>+ </Dropdown.Item>+ </Show>+ <Show+ when={!props.loading() && matches().length === 0 && !canAddEmail()}+ >+ <div class="px-2 py-3 text-center text-xs text-ink-muted">+ {props.error()+ ? 'Contacts unavailable. Enter an email instead.'+ : normalizedSearch()+ ? 'No matching contacts'+ : 'No contacts available'}+ </div>+ </Show>+ </Dropdown.Group>+ </Dropdown.SubContent>+ </Dropdown.Sub>+ );+}diff --git a/apps/web/src/features/calendar-view/components/CalendarSearch.tsx b/apps/web/src/features/calendar-view/components/CalendarSearch.tsxindex be5299c28a..af49f7c314 100644--- a/apps/web/src/features/calendar-view/components/CalendarSearch.tsx+++ b/apps/web/src/features/calendar-view/components/CalendarSearch.tsx@@ -1,28 +1,47 @@+import { SearchBar } from '@app/components/view-shell';+import { useCalendarPager } from '@app/features/calendar/components/CalendarPagerContext';import { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';import { useCalendarSearchUiFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';-import type { CalendarTimeFormat } from '@app/features/calendar/types';+import {+ type CalendarTimeFormat,+ DEFAULT_CALENDAR_SOURCE,+} from '@app/features/calendar/types';import { parseLocalDate } from '@app/features/calendar/utils/calendar-date';import { isCalendarRangeSupported } from '@app/features/calendar/utils/calendar-supported-range';+import { safeConferenceUrl } from '@app/features/calendar/utils/conference-link';+import {+ calendarMacroCallUrl,+ macroCallUrl,+} from '@app/features/calendar/utils/macro-call-link';import { formatCalendarTime } from '@app/features/calendar/utils/time-format';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';-import { EntityIcon } from '@core/component/EntityIcon';import { IS_MAC } from '@core/constant/isMac';import { registerHotkey } from '@core/hotkey/hotkeys';import { TOKENS } from '@core/hotkey/tokens';import { debouncedDependent } from '@core/util/debounce';+import { openExternalUrl } from '@core/util/url';+import EmptyStateCalendarSearchGraphic from '@design/empty-state-calendar-search.svg';import type { EntityData, WithSearch } from '@entity';import { Popover } from '@kobalte/core/popover';import CaretLeftIcon from '@phosphor/caret-left.svg';import SearchIcon from '@phosphor/magnifying-glass.svg';+import QuotesIcon from '@phosphor/quotes.svg';import RepeatIcon from '@phosphor/repeat.svg';-import { useCalendarMentionPreviewQuery } from '@queries/calendar/mention-preview';+import VideoCameraIcon from '@phosphor/video-camera.svg';+import XIcon from '@phosphor/x.svg';+import {+ useCalendarMentionPreviewQuery,+ useCalendarSearchPreviewsQuery,+} from '@queries/calendar/mention-preview';import { useSearchSoupQuery } from '@queries/soup/search';import type { EntityFilters } from '@service-search/generated/models';-import { Button, cn, Layer } from '@ui';+import { Button, cn, EmptyStatePanel, Layer } from '@ui';import {+ createEffect,createMemo,createSignal,For,+ on,onCleanup,onMount,Show,@@ -32,6 +51,10 @@ import {eventTimeFromOccurrenceKey,openCalendarEventSplit,} from '../open-calendar-event';+import {+ CalendarSearchFilters,+ DEFAULT_CALENDAR_SEARCH_FILTERS,+} from './CalendarSearchFilters';type CalendarSearchResult = WithSearch<Extract<EntityData, { type: 'calendar_event' }>@@ -57,6 +80,66 @@ const CALENDAR_ONLY_FILTERS: EntityFilters = {foreign_entity_filters: { ids: [NIL_UUID] },};+const searchEventKey = (eventId: string, occurrenceKey?: string) =>+ JSON.stringify([eventId, occurrenceKey ?? null]);++type CalendarMeetingLink = {+ url: string;+ kind: 'macro' | 'google' | 'other';+ label: string;+};++type CalendarSearchEventDetails = {+ conferenceUrl?: string;+ description?: string;+ location?: string;+};++function googleMeetUrlInText(value?: string): string | undefined {+ for (const candidate of value?.match(/https?:\/\/[^\s<>"']+/gi) ?? []) {+ const url = safeConferenceUrl(candidate.replace(/&/g, '&'));+ if (url && new URL(url).hostname === 'meet.google.com') return url;+ }+ return undefined;+}++function meetingLinkForEvent(+ event: CalendarSearchResult,+ details?: CalendarSearchEventDetails+): CalendarMeetingLink | undefined {+ // Search metadata describes the series, not a selected recurring instance.+ if (event.isRecurring && (!event.occurrenceKey || !details)) return undefined;++ const description =+ details?.description ?? (event.isRecurring ? undefined : event.description);+ const macro = calendarMacroCallUrl({+ description,+ location: details?.location,+ });+ if (macro) return { url: macro, kind: 'macro', label: 'Macro call' };++ const googleContent =+ googleMeetUrlInText(details?.location) ?? googleMeetUrlInText(description);+ if (googleContent) {+ return { url: googleContent, kind: 'google', label: 'Google Meet' };+ }++ const conference = safeConferenceUrl(+ details?.conferenceUrl ?? event.conferenceUrl+ );+ if (!conference) return undefined;+ const macroConference = calendarMacroCallUrl({ conferenceUrl: conference });+ if (macroConference) {+ return { url: macroConference, kind: 'macro', label: 'Macro call' };+ }+ const google = new URL(conference).hostname === 'meet.google.com';+ return {+ url: conference,+ kind: google ? 'google' : 'other',+ label: google ? 'Google Meet' : 'meeting',+ };+}+const MIN_QUERY_LENGTH = 3;const dateWithYear = new Intl.DateTimeFormat(undefined, {@@ -96,12 +179,13 @@ function formatEventWhen(* Read-only card for a result the calendar cannot navigate to: occurrences* older than the backend's rolling materialized window aren't fetchable, so* there is nothing to focus and no editable event to open. The card's identity- * — title, when, organizer, recurrence — comes from the selected row so it- * always describes the instance the user picked; the mention preview only- * supplements the meeting-level location and guest count the row lacks.+ * comes from the selected row; the mention preview supplements the guest count.+ * A location only appears when the same occurrence resolves.*/function CalendarEventPreviewContent(props: {event: CalendarSearchResult;+ color: string;+ location?: string;timeFormat: CalendarTimeFormat;onBack: () => void;}) {@@ -120,18 +204,22 @@ function CalendarEventPreviewContent(props: {occurrenceKey: props.event.occurrenceKey,}));- const when = () => formatEventWhen(props.event.time, props.timeFormat);+ const when = () =>+ [+ formatEventWhen(props.event.time, props.timeFormat),+ props.location?.trim(),+ ]+ .filter(Boolean)+ .join(' · ');const organizer = () =>props.event.organizer?.name || props.event.organizer?.email || '';const detail = () => {if (previewQuery.isPending) return '';const preview = previewQuery.data;if (!preview) return '';- const guests =- preview.attendeeCount > 0- ? `${preview.attendeeCount} guest${preview.attendeeCount === 1 ? '' : 's'}`- : '';- return [preview.location, guests].filter(Boolean).join(' · ');+ return preview.attendeeCount > 0+ ? `${preview.attendeeCount} guest${preview.attendeeCount === 1 ? '' : 's'}`+ : '';};return (@@ -146,10 +234,12 @@ function CalendarEventPreviewContent(props: {Back to search</button><div class="flex flex-col gap-1 px-2 pb-2">- <div class="flex items-center gap-2">- <span class="flex size-4 shrink-0 items-center justify-center">- <EntityIcon targetType="calendar" size="xs" theme="monochrome" />- </span>+ <div class="flex min-w-0 items-center gap-1.5">+ <span+ aria-hidden="true"+ class="size-2.5 shrink-0 rounded-sm"+ style={{ 'background-color': props.color }}+ /><span class="min-w-0 flex-1 truncate text-sm font-medium text-ink">{props.event.name || 'Untitled event'}</span>@@ -175,7 +265,7 @@ function CalendarEventPreviewContent(props: {<span class="truncate text-xs text-ink-muted">{text()}</span>)}</Show>- <span class="mt-1 border-t border-edge-muted pt-1.5 text-[11px] text-ink-extra-muted">+ <span class="mt-1 border-t border-edge-muted pt-1.5 text-xs text-ink-extra-muted">Outside the calendar's navigable range</span></div>@@ -183,25 +273,81 @@ function CalendarEventPreviewContent(props: {);}+function CalendarSearchLoadingRows() {+ return (+ <div role="status">+ <span class="sr-only">Searching events…</span>+ <For each={[0, 1, 2, 3]}>+ {(_, index) => (+ <div+ aria-hidden="true"+ class="flex items-center gap-2 rounded-lg p-1.5 px-2"+ >+ <span class="skeleton-shimmer size-4 shrink-0 rounded bg-skeleton" />+ <span class="flex min-w-0 flex-1 flex-col gap-1.5">+ <span+ class={cn(+ 'skeleton-shimmer h-3.5 rounded bg-skeleton',+ index() % 2 === 0 ? 'w-3/5' : 'w-2/5'+ )}+ />+ <span class="skeleton-shimmer h-2.5 w-2/5 rounded bg-skeleton" />+ </span>+ </div>+ )}+ </For>+ </div>+ );+}+/*** Keyword search over the caller's calendar events, opened from the calendar* header. Selecting a result re-aims the singleton Calendar view at that* occurrence, the same navigation an event mention or soup row performs.*/-export function CalendarSearch() {+export function CalendarSearch(+ props: {+ inline?: boolean;+ compact?: boolean;+ expanded?: boolean;+ onExpand?: () => void;+ onDismiss?: () => void;+ onOpenChange?: (open: boolean) => void;+ } = {}+) {const searchEnabled = useCalendarSearchUiFlag();return (<Show when={searchEnabled()}>- <CalendarSearchControl />+ <CalendarSearchControl+ inline={props.inline}+ compact={props.compact}+ expanded={props.expanded}+ onExpand={props.onExpand}+ onDismiss={props.onDismiss}+ onOpenChange={props.onOpenChange}+ /></Show>);}-function CalendarSearchControl() {+function CalendarSearchControl(props: {+ inline?: boolean;+ compact?: boolean;+ expanded?: boolean;+ onExpand?: () => void;+ onDismiss?: () => void;+ onOpenChange?: (open: boolean) => void;+}) {const calendarView = useCalendarView();+ const calendarPager = useCalendarPager();const panel = useSplitPanelOrThrow();- const [open, setOpen] = createSignal(false);+ const [open, setOpenInternal] = createSignal(false);+ const setOpen = (next: boolean) => {+ setOpenInternal(next);+ props.onOpenChange?.(next);+ };const [rawQuery, setRawQuery] = createSignal('');+ const [filters, setFilters] = createSignal(DEFAULT_CALENDAR_SEARCH_FILTERS);let inputRef: HTMLInputElement | undefined;let listRef: HTMLDivElement | undefined;const [activeRow, setActiveRow] = createSignal(0);@@ -214,16 +360,37 @@ function CalendarSearchControl() {const debouncedQuery = debouncedDependent(query, 250);const searchQuery = useSearchSoupQuery(- () => ({- params: { page_size: 25 },- body: {- search_on: 'name_content',- match_type: 'partial',- query: debouncedQuery(),- filters: CALENDAR_ONLY_FILTERS,- },- }),- () => ({ enabled: open() })+ () => {+ const selected = filters();+ return {+ params: { page_size: 25 },+ body: {+ search_on: selected.searchOn,+ match_type: selected.matchType,+ query: debouncedQuery(),+ filters: {+ ...CALENDAR_ONLY_FILTERS,+ calendar_event_filters:+ selected.statuses.length ||+ selected.organizers.length ||+ selected.attendees.length+ ? {+ statuses: selected.statuses.length+ ? selected.statuses+ : undefined,+ organizers: selected.organizers.length+ ? selected.organizers+ : undefined,+ attendees: selected.attendees.length+ ? selected.attendees+ : undefined,+ }+ : undefined,+ },+ },+ };+ },+ () => ({ enabled: open() && query().length >= MIN_QUERY_LENGTH }));// Trust the results only once the debounce has caught up to what the user@@ -234,6 +401,7 @@ function CalendarSearchControl() {const isCurrent = () =>query().length >= MIN_QUERY_LENGTH &&query() === debouncedQuery() &&+ !searchQuery.isPending &&!(searchQuery.isFetching && !searchQuery.isFetchingNextPage);const results = createMemo<CalendarSearchResult[]>(() => {@@ -246,6 +414,85 @@ function CalendarSearchControl() {const isLoading = () => query().length >= MIN_QUERY_LENGTH && !isCurrent();+ const searchPreviews = useCalendarSearchPreviewsQuery(() =>+ open()+ ? results().map((event) => ({+ eventId: event.id,+ occurrenceKey: event.occurrenceKey,+ }))+ : []+ );+ const previewEventDetails = createMemo(() => {+ const details = new Map<string, CalendarSearchEventDetails>();+ if (!searchPreviews.isSuccess) return details;+ const previews = searchPreviews.data;+ if (!previews) return details;+ const matches = results();+ previews.forEach((item, index) => {+ const match = matches[index];+ const preview = item.event;+ if (item.type !== 'access' || !match || !preview) return;+ if (item.eventId !== match.id) return;+ // The preview can fall back to a different occurrence outside the+ // materialized range. Never attribute its links to the selected instance.+ if (match.occurrenceKey && preview.occurrenceKey !== match.occurrenceKey)+ return;+ details.set(searchEventKey(match.id, match.occurrenceKey), {+ description: preview.description ?? undefined,+ location: preview.location ?? undefined,+ });+ });+ return details;+ });++ // Search results have no calendar IDs. Match loaded occurrences for colors+ // and full instance content while the batched preview request resolves.+ const activeEventDetails = createMemo(() => {+ const byId = new Map<string, { color: string; location?: string }>();+ const byOccurrence = new Map<string, CalendarSearchEventDetails>();+ const data = calendarPager.activeData();+ if (!open() || !data?.occurrencesQuery.isSuccess) {+ return { byId, byOccurrence };+ }+ for (const event of data.events()) {+ byId.set(event.eventId, {+ color: event.calendar.color,+ location: event.location,+ });+ byOccurrence.set(searchEventKey(event.eventId, event.occurrenceKey), {+ conferenceUrl: event.conferenceUrl,+ description: event.description,+ location: event.location,+ });+ }+ return { byId, byOccurrence };+ });+ const colorForEvent = (eventId: string) =>+ activeEventDetails().byId.get(eventId)?.color ??+ DEFAULT_CALENDAR_SOURCE.color;+ const detailsForEvent = (event: CalendarSearchResult) => {+ const key = searchEventKey(event.id, event.occurrenceKey);+ return (+ activeEventDetails().byOccurrence.get(key) ??+ previewEventDetails().get(key)+ );+ };+ const locationForEvent = (event: CalendarSearchResult) => {+ const location =+ detailsForEvent(event)?.location ??+ (!event.isRecurring+ ? activeEventDetails().byId.get(event.id)?.location+ : undefined);+ return location && !macroCallUrl(location.trim()) ? location : undefined;+ };+ const subtitleForEvent = (event: CalendarSearchResult) =>+ [+ formatEventWhen(event.time, calendarView.displaySettings.timeFormat),+ locationForEvent(event)?.trim(),+ ]+ .filter(Boolean)+ .join(' · ');+// Keyboard-highlighted result, clamped so it stays valid as results change.const activeIndex = () => {const len = results().length;@@ -271,7 +518,6 @@ function CalendarSearchControl() {if (range && isCalendarRangeSupported(range)) {setOpen(false);- setRawQuery('');void openCalendarEventSplit({eventId: event.id,occurrenceKey: event.occurrenceKey,@@ -296,12 +542,76 @@ function CalendarSearchControl() {inputRef?.focus();inputRef?.select();};+ createEffect(+ on(+ () => props.expanded,+ (expanded) => {+ if (expanded === undefined) return;+ if (!expanded) {+ setOpen(false);+ return;+ }+ focusInput();+ setOpen(true);+ }+ )+ );+ const changeQuery = (value: string) => {+ setRawQuery(value);+ setActiveRow(0);+ if (props.inline) setOpen(true);+ };+ const filterActions = () => (+ <Show when={!props.inline || !props.compact || open()}>+ <div class="flex shrink-0 items-center gap-1">+ <Show when={rawQuery().trim()}>+ <Button+ type="button"+ variant="plain"+ size="icon-sm"+ square+ aria-pressed={filters().matchType === 'exact'}+ label="Exact match"+ class={+ filters().matchType === 'exact'+ ? 'rounded-full bg-active text-ink'+ : 'rounded-full'+ }+ onPointerDown={(event) => event.preventDefault()}+ onClick={() =>+ setFilters((current) => ({+ ...current,+ matchType: current.matchType === 'exact' ? 'partial' : 'exact',+ }))+ }+ >+ <QuotesIcon class="size-4" />+ </Button>+ </Show>+ <CalendarSearchFilters value={filters()} onChange={setFilters} />+ </div>+ </Show>+ );- // Cmd+F opens the search, matching the channel block's find-bar. Registered- // only while this control is mounted, which the calendar-search flag gates.- // Once the popover is open its portal holds focus outside the split scope, so- // this split-scoped handler only fires to open it — the re-select-while-open- // case is handled by `handleContentKeyDown` on the portal content instead.+ const handleSearchKeyDown = (event: KeyboardEvent) => {+ if (event.key === 'ArrowDown') {+ event.preventDefault();+ moveActive(1);+ } else if (event.key === 'ArrowUp') {+ event.preventDefault();+ moveActive(-1);+ } else if (event.key === 'Enter') {+ const active = results()[activeIndex()];+ if (active) {+ event.preventDefault();+ openResult(active);+ }+ }+ };++ // Cmd+F focuses the inline search or opens the compact search popover.+ // The compact popover's portal holds focus outside the split scope; while open,+ // handleContentKeyDown re-selects the query there.const searchHotkey = registerHotkey({hotkey: 'cmd+f',scopeId: panel.splitHotkeyScope,@@ -309,7 +619,13 @@ function CalendarSearchControl() {description: 'Search events',runWithInputFocused: true,keyDownHandler: () => {- if (open()) focusInput();+ if (props.inline) {+ if (props.expanded === false) props.onExpand?.();+ else {+ focusInput();+ setOpen(true);+ }+ } else if (open()) focusInput();else setOpen(true);return true;},@@ -337,24 +653,57 @@ function CalendarSearchControl() {onOpenChange={(next) => {setOpen(next);if (!next) {- setRawQuery('');setActiveRow(0);setPreviewTarget(null);}}}- placement="bottom-end"+ placement={props.inline ? 'bottom-start' : 'bottom-end'}gutter={6}flip>- <Popover.Trigger- as={Button}- variant="ghost"- size="icon-sm"- class="rounded-lg"- aria-label="Search events"+ <Show+ when={props.inline}+ fallback={+ <Popover.Trigger+ as={Button}+ variant="ghost"+ size="icon-lg"+ class="rounded-full"+ aria-label="Search events"+ >+ <SearchIcon class="size-5 mobile:size-6" />+ </Popover.Trigger>+ }>- <SearchIcon class="size-4 mobile:size-6" />- </Popover.Trigger>+ <div class="min-w-0 max-w-md flex-1">+ <Popover.Anchor as="div" class="w-full">+ <SearchBar+ ref={(element) => (inputRef = element)}+ label="Search events"+ onClose={+ props.onDismiss+ ? () => {+ inputRef?.blur();+ props.onDismiss?.();+ }+ : undefined+ }+ value={rawQuery()}+ onValueChange={changeQuery}+ actions={filterActions()}+ onClick={() => setOpen(true)}+ onFocus={() => setOpen(true)}+ onKeyDown={handleSearchKeyDown}+ onEscape={() => {+ setOpen(false);+ props.onDismiss?.();+ }}+ hotkey="cmd+f"+ placeholder="Search events"+ />+ </Popover.Anchor>+ </div>+ </Show><Popover.Portal><Layer depth={3}>@@ -362,103 +711,181 @@ function CalendarSearchControl() {class="portal-scope z-modal outline-none"onOpenAutoFocus={(event) => {event.preventDefault();- inputRef?.focus();+ if (!props.inline) inputRef?.focus();+ }}+ onCloseAutoFocus={(event) => {+ if (props.inline) event.preventDefault();}}onKeyDown={handleContentKeyDown}+ onInteractOutside={(event) => {+ const target = event.detail.originalEvent.target;+ if (+ target instanceof Element &&+ target.closest('[data-calendar-search-filters]')+ ) {+ event.preventDefault();+ }+ if (+ props.inline &&+ target instanceof Node &&+ inputRef?.closest('[data-search-bar]')?.contains(target)+ ) {+ event.preventDefault();+ }+ }}>- <div class="w-80 max-w-[calc(100vw-2rem)] overflow-hidden rounded-xl glass bg-menu-glass text-ink">+ <div+ class={cn(+ 'max-w-[calc(100vw-2rem)] overflow-hidden rounded-xl glass bg-menu-glass text-ink',+ props.inline ? 'w-[var(--kb-popper-anchor-width)]' : 'w-80'+ )}+ ><Showwhen={previewTarget()}fallback={<>- <div class="flex items-center gap-2 px-3 py-2">- <SearchIcon class="size-4 shrink-0 text-ink-muted" />- <input- ref={inputRef}- type="text"- value={rawQuery()}- onInput={(event) => {- setRawQuery(event.currentTarget.value);- setActiveRow(0);- }}- onKeyDown={(event) => {- if (event.key === 'ArrowDown') {- event.preventDefault();- moveActive(1);- } else if (event.key === 'ArrowUp') {- event.preventDefault();- moveActive(-1);- } else if (event.key === 'Enter') {- const active = results()[activeIndex()];- if (active) {- event.preventDefault();- openResult(active);- }+ <Show when={!props.inline}>+ <div class="flex items-center gap-2 px-3 py-2">+ <SearchIcon class="size-4 shrink-0 text-ink-muted" />+ <input+ ref={inputRef}+ type="text"+ value={rawQuery()}+ onInput={(event) =>+ changeQuery(event.currentTarget.value)}- }}- placeholder="Search by event name"- class="min-w-0 flex-1 bg-transparent text-sm caret-accent outline-none placeholder:text-ink-placeholder"+ onKeyDown={handleSearchKeyDown}+ placeholder="Search events"+ class="min-w-0 flex-1 bg-transparent text-sm caret-accent outline-none placeholder:text-ink-placeholder"+ />+ {filterActions()}+ <Show when={rawQuery()}>+ <Button+ type="button"+ variant="plain"+ size="icon-sm"+ square+ label="Clear search"+ onClick={() => {+ changeQuery('');+ inputRef?.focus();+ }}+ >+ <XIcon class="size-4" />+ </Button>+ </Show>+ </div>+ </Show>+ <Show when={query().length < MIN_QUERY_LENGTH}>+ <EmptyStatePanel+ centered+ graphic={EmptyStateCalendarSearchGraphic}+ graphicClass="size-28 -mb-3"+ title="Find an event"+ titleClass="text-sm"+ description="Type at least 3 characters to search events."+ descriptionClass="mt-0.5 text-xs leading-5"+ topSpacerClass="basis-0"+ class="h-auto min-h-44 px-4 pb-4 pt-3 touch:pt-3 @4xl:px-4"/>- </div>-+ </Show><Show when={query().length >= MIN_QUERY_LENGTH}><divref={listRef}- class="max-h-80 overflow-y-auto border-t border-edge-muted p-1"+ class={cn(+ 'max-h-80 overflow-y-auto p-1',+ !props.inline && 'border-t border-edge-muted'+ )}><Showwhen={!isLoading()}- fallback={- <div class="px-2 py-3 text-center text-xs text-ink-muted">- Searching…- </div>- }+ fallback={<CalendarSearchLoadingRows />}><Showwhen={results().length > 0}fallback={- <div class="px-2 py-3 text-center text-xs text-ink-muted">- No events found- </div>+ <EmptyStatePanel+ centered+ graphic={EmptyStateCalendarSearchGraphic}+ graphicClass="size-28 -mb-3"+ title="No matching events"+ titleClass="text-sm"+ description={`No calendar events found for “${query()}”.`}+ descriptionClass="mt-0.5 text-xs leading-5"+ topSpacerClass="basis-0"+ class="h-auto min-h-44 px-4 pb-4 pt-3 touch:pt-3 @4xl:px-4"+ />}><For each={results()}>{(event, index) => (- <button- type="button"+ <divdata-result-index={index()}class={cn(- 'flex w-full items-center gap-2 rounded-lg p-1.5 px-2 text-left outline-none',+ 'flex w-full items-center gap-1.5 rounded-lg p-1.5 px-2',index() === activeIndex() && 'bg-ink/5')}onMouseMove={() => setActiveRow(index())}- onClick={() => openResult(event)}>- <span class="flex size-4 shrink-0 items-center justify-center">- <EntityIcon- targetType="calendar"- size="xs"- theme="monochrome"- />- </span>- <span class="min-w-0 flex-1">- <span class="block truncate text-sm text-ink">- {event.name || 'Untitled event'}+ <button+ type="button"+ class="min-w-0 flex-1 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-edge-focus"+ onClick={() => openResult(event)}+ >+ <span class="flex min-w-0 items-center gap-1.5">+ <span+ aria-hidden="true"+ class="size-2.5 shrink-0 rounded-sm"+ style={{+ 'background-color': colorForEvent(+ event.id+ ),+ }}+ />+ <span class="min-w-0 truncate text-sm text-ink">+ {event.name || 'Untitled event'}+ </span></span>- <Show- when={formatEventWhen(- event.time,- calendarView.displaySettings.timeFormat- )}- >+ <Show when={subtitleForEvent(event)}>{(label) => (- <span class="block truncate text-xs text-ink-muted">+ <span class="block truncate pl-4 text-xs text-ink-muted">{label()}</span>)}</Show>- </span>- </button>+ </button>+ <Show+ when={meetingLinkForEvent(+ event,+ detailsForEvent(event)+ )}+ >+ {(link) => (+ <Button+ type="button"+ variant="plain"+ size="sm"+ label={`Join ${link().label}`}+ class={cn(+ 'rounded-full px-2',+ link().kind === 'google'+ ? 'bg-blue text-[white] light-mode:not-touch:not-disabled:hover:text-[white] dark-mode:bg-blue-bg dark-mode:text-blue-ink dark-mode:not-touch:not-disabled:hover:bg-blue-hover dark-mode:not-touch:not-disabled:hover:text-blue-ink'+ : 'bg-hover text-ink not-touch:not-disabled:hover:bg-active not-touch:not-disabled:hover:text-ink'+ )}+ onClick={() =>+ openExternalUrl(link().url)+ }+ >+ <VideoCameraIcon class="size-3.5" />+ {link().kind === 'macro'+ ? 'Macro'+ : link().kind === 'google'+ ? 'Meet'+ : 'Join'}+ </Button>+ )}+ </Show>+ </div>)}</For></Show>@@ -471,6 +898,8 @@ function CalendarSearchControl() {{(event) => (<CalendarEventPreviewContentevent={event()}+ color={colorForEvent(event().id)}+ location={locationForEvent(event())}timeFormat={calendarView.displaySettings.timeFormat}onBack={closePreview}/>diff --git a/apps/web/src/features/calendar-view/components/CalendarSearchFilters.tsx b/apps/web/src/features/calendar-view/components/CalendarSearchFilters.tsxnew file mode 100644index 0000000000..cc0bb7ddee--- /dev/null+++ b/apps/web/src/features/calendar-view/components/CalendarSearchFilters.tsx@@ -0,0 +1,191 @@+import CaretRightIcon from '@phosphor/caret-right.svg';+import CheckIcon from '@phosphor/check.svg';+import FilterIcon from '@phosphor/funnel-simple.svg';+import { useContacts, useContactsQuery } from '@queries/contacts/contacts';+import { Dropdown } from '@ui';+import { createSignal, For, Show } from 'solid-js';+import { CalendarPeopleFilterSubmenu } from './CalendarPeopleFilterSubmenu';++export interface CalendarSearchFilterValues {+ searchOn: 'name_content' | 'name' | 'content';+ matchType: 'partial' | 'exact';+ statuses: Array<'confirmed' | 'tentative' | 'cancelled'>;+ organizers: string[];+ attendees: string[];+}++export const DEFAULT_CALENDAR_SEARCH_FILTERS: CalendarSearchFilterValues = {+ searchOn: 'name_content',+ matchType: 'partial',+ statuses: [],+ organizers: [],+ attendees: [],+};++const SEARCH_FIELDS: Array<{+ value: CalendarSearchFilterValues['searchOn'];+ label: string;+}> = [+ { value: 'name_content', label: 'Title and description' },+ { value: 'name', label: 'Title only' },+ { value: 'content', label: 'Description only' },+];++const STATUSES: Array<{+ value: CalendarSearchFilterValues['statuses'][number];+ label: string;+}> = [+ { value: 'confirmed', label: 'Confirmed' },+ { value: 'tentative', label: 'Tentative' },+ { value: 'cancelled', label: 'Cancelled' },+];++function SubmenuLabel(props: { label: string; active: boolean }) {+ return (+ <>+ <span class="flex-1 text-ink">{props.label}</span>+ <Show when={props.active}>+ <span aria-hidden="true" class="size-1.5 rounded-full bg-accent" />+ </Show>+ <CaretRightIcon class="size-3 shrink-0 text-ink-muted" />+ </>+ );+}++export function CalendarSearchFilters(props: {+ value: CalendarSearchFilterValues;+ onChange: (value: CalendarSearchFilterValues) => void;+}) {+ const [open, setOpen] = createSignal(false);+ const contacts = useContacts(open);+ const contactsQuery = useContactsQuery(open);+ const updateFilters = (change: Partial<CalendarSearchFilterValues>) =>+ props.onChange({ ...props.value, ...change });+ const hasFilters = () =>+ props.value.searchOn !== DEFAULT_CALENDAR_SEARCH_FILTERS.searchOn ||+ props.value.statuses.length > 0 ||+ props.value.organizers.length > 0 ||+ props.value.attendees.length > 0;++ return (+ <Dropdown placement="bottom-end" onOpenChange={setOpen}>+ <Dropdown.Trigger+ type="button"+ variant="plain"+ size="icon-sm"+ square+ label={hasFilters() ? 'Filter events (active)' : 'Filter events'}+ class="rounded-full"+ classList={{ 'text-accent': hasFilters() }}+ >+ <FilterIcon class="size-4" />+ <Show when={hasFilters()}>+ <span+ aria-hidden="true"+ class="absolute -right-0.5 -top-0.5 size-1.5 rounded-full bg-accent"+ />+ </Show>+ </Dropdown.Trigger>+ <Dropdown.Content+ portalScope="local"+ data-calendar-search-filters=""+ class="w-44 max-w-[90vw]"+ >+ <Dropdown.Group>+ <Dropdown.Sub>+ <Dropdown.SubTrigger>+ <SubmenuLabel+ label="Search in"+ active={+ props.value.searchOn !==+ DEFAULT_CALENDAR_SEARCH_FILTERS.searchOn+ }+ />+ </Dropdown.SubTrigger>+ <Dropdown.SubContent+ portalScope="local"+ data-calendar-search-filters=""+ class="min-w-44"+ >+ <Dropdown.Group>+ <Dropdown.RadioGroup+ value={props.value.searchOn}+ onChange={(value) =>+ updateFilters({+ searchOn: value as CalendarSearchFilterValues['searchOn'],+ })+ }+ >+ <For each={SEARCH_FIELDS}>+ {(option) => (+ <Dropdown.RadioItem+ closeOnSelect={false}+ value={option.value}+ >+ <span class="flex-1">{option.label}</span>+ <Dropdown.ItemIndicator>+ <CheckIcon class="size-3.5 text-accent" />+ </Dropdown.ItemIndicator>+ </Dropdown.RadioItem>+ )}+ </For>+ </Dropdown.RadioGroup>+ </Dropdown.Group>+ </Dropdown.SubContent>+ </Dropdown.Sub>+ <Dropdown.Sub>+ <Dropdown.SubTrigger>+ <SubmenuLabel+ label="Status"+ active={props.value.statuses.length > 0}+ />+ </Dropdown.SubTrigger>+ <Dropdown.SubContent+ portalScope="local"+ data-calendar-search-filters=""+ class="min-w-40"+ >+ <Dropdown.Group>+ <For each={STATUSES}>+ {(option) => (+ <Dropdown.CheckboxItem+ closeOnSelect={false}+ checked={props.value.statuses.includes(option.value)}+ onChange={(checked) =>+ updateFilters({+ statuses: checked+ ? [...props.value.statuses, option.value]+ : props.value.statuses.filter(+ (status) => status !== option.value+ ),+ })+ }+ >+ <span class="flex-1">{option.label}</span>+ </Dropdown.CheckboxItem>+ )}+ </For>+ </Dropdown.Group>+ </Dropdown.SubContent>+ </Dropdown.Sub>+ <CalendarPeopleFilterSubmenu+ label="Organizer"+ contacts={contacts}+ loading={() => contactsQuery.isPending}+ error={() => contactsQuery.isError}+ values={() => props.value.organizers}+ onChange={(organizers) => updateFilters({ organizers })}+ />+ <CalendarPeopleFilterSubmenu+ label="Attendee"+ contacts={contacts}+ loading={() => contactsQuery.isPending}+ error={() => contactsQuery.isError}+ values={() => props.value.attendees}+ onChange={(attendees) => updateFilters({ attendees })}+ />+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ );+}diff --git a/apps/web/src/features/calendar-view/components/CalendarSidebar.tsx b/apps/web/src/features/calendar-view/components/CalendarSidebar.tsxnew file mode 100644index 0000000000..33b7a9d213--- /dev/null+++ b/apps/web/src/features/calendar-view/components/CalendarSidebar.tsx@@ -0,0 +1,331 @@+import {+ CollapsibleSection,+ useViewShell,+ ViewSidebar,+} from '@app/components/view-shell';+import { CopyAvailabilityButton } from '@app/features/calendar/availability/CopyAvailabilityButton';+import { useCalendarPager } from '@app/features/calendar/components/CalendarPagerContext';+import { CalendarSettingsDropdown } from '@app/features/calendar/components/CalendarSettingsDropdown';+import { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';+import { SourceControls } from '@app/features/calendar/components/SourceControls';+import {+ TEAM_OOO_SOURCE_ID,+ type TeamOooWindow,+ useHasTeammates,+ useUpcomingTeamOoo,+} from '@app/features/calendar/hooks/use-team-ooo';+import { ShowFeatureFlag } from '@app/lib/analytics/posthog';+import { UserIcon } from '@core/component/UserIcon';+import { enableCalendarTeamOoo } from '@core/constant/featureFlags';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import CaretDownIcon from '@phosphor/caret-down.svg';+import PlusIcon from '@phosphor/plus.svg';+import CloseIcon from '@phosphor/x.svg';+import { cn, Calendar as MiniCalendar, ToggleSwitch } from '@ui';+import { format } from 'date-fns';+import {+ createEffect,+ createMemo,+ createSignal,+ For,+ Match,+ on,+ Show,+ Switch,+} from 'solid-js';+import { CalendarCallSidebar } from '../calendar-call-sidebar';+import {+ CalendarCreateCallItem,+ CalendarCreateEventItem,+ CalendarCreateReminderItem,+} from './CalendarCreateItems';+import { CalendarCreateMenu } from './CalendarCreateMenu';++function CalendarMiniCalendar() {+ const calendarView = useCalendarView();+ const calendarPager = useCalendarPager();+ const shell = useViewShell();+ const initialDate = new Date();+ const [focusedDay, setFocusedDay] = createSignal(initialDate);++ const currentDate = createMemo(+ () => calendarPager.activeDateInfo()?.view.calendar.getDate() ?? initialDate+ );+ const highlightedRange = createMemo(() => {+ const dateInfo = calendarPager.activeDateInfo();+ if (dateInfo?.view.type !== 'timeGridWeek') return undefined;+ return { end: dateInfo.end, start: dateInfo.start };+ });++ const navigateToDate = (date: Date) => {+ setFocusedDay(date);+ calendarPager.gotoDate(date);+ if (shell.aside.isOverlay()) shell.aside.collapse();+ };+ const navigateMonth = (month: Date) => {+ const focused = focusedDay();+ const sameMonth =+ focused.getFullYear() === month.getFullYear() &&+ focused.getMonth() === month.getMonth();+ navigateToDate(sameMonth ? focused : month);+ };+ createEffect(on(currentDate, setFocusedDay));++ return (+ <MiniCalendar+ required+ fixedWeeks+ startOfWeek={calendarView.displaySettings.weekStartsOn}+ value={currentDate()}+ month={currentDate()}+ focusedDay={focusedDay()}+ highlightedRange={highlightedRange()}+ onMonthChange={navigateMonth}+ onFocusedDayChange={setFocusedDay}+ onValueChange={(date) => date && navigateToDate(date)}+ />+ );+}++function UpcomingEventsSection() {+ const [open, setOpen] = createSignal(true);++ return (+ <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>+ <CollapsibleSection.Header>+ <CollapsibleSection.Trigger class="min-w-0 flex-1">+ <span class="min-w-0 truncate">Upcoming events</span>+ <CollapsibleSection.Indicator />+ </CollapsibleSection.Trigger>+ <CopyAvailabilityButton class="size-(--sidebar-control-size) rounded-lg" />+ </CollapsibleSection.Header>+ <CollapsibleSection.Content>+ <CalendarCallSidebar />+ </CollapsibleSection.Content>+ </CollapsibleSection.Root>+ );+}++function CalendarSourcesSection() {+ const calendarView = useCalendarView();+ const [open, setOpen] = createSignal(true);++ return (+ <Show when={calendarView.sources().length > 1}>+ <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>+ <CollapsibleSection.Trigger>+ <span class="min-w-0 truncate">Calendars</span>+ <CollapsibleSection.Indicator />+ </CollapsibleSection.Trigger>+ <CollapsibleSection.Content>+ <SourceControls+ sources={calendarView.sources()}+ isVisible={calendarView.isSourceVisible}+ onVisibilityChange={calendarView.setSourceVisibility}+ onGroupVisibilityChange={calendarView.setSourcesVisibility}+ />+ </CollapsibleSection.Content>+ </CollapsibleSection.Root>+ </Show>+ );+}++const UPCOMING_SHOWN_MAX = 10;++function windowDateLabel(window: TeamOooWindow): string {+ const lastDay = new Date(window.end.getTime() - 1);+ return window.start.toDateString() === lastDay.toDateString()+ ? format(window.start, 'EEE, MMM d')+ : `${format(window.start, 'MMM d')} – ${format(lastDay, 'MMM d')}`;+}++function TeamOooSkeleton() {+ return (+ <div aria-hidden="true" class="flex flex-col gap-0.5">+ <For each={[0, 1, 2]}>+ {() => (+ <div class="skeleton-shimmer h-8 w-full rounded-lg bg-skeleton" />+ )}+ </For>+ </div>+ );+}++function TeamOooUpcomingList() {+ const calendarPager = useCalendarPager();+ const shell = useViewShell();+ const upcoming = useUpcomingTeamOoo();+ const windows = upcoming.windows;+ const calendarView = useCalendarView();+ const isActive = (window: TeamOooWindow) =>+ calendarView.selectedEvent()?.id === window.event.id;++ return (+ <div class="flex flex-col gap-0.5">+ <Switch>+ <Match when={upcoming.isPending()}>+ <TeamOooSkeleton />+ </Match>+ <Match when={upcoming.isError()}>+ <span class="px-2 py-1 text-xs text-ink-muted">+ Couldn't load time off+ </span>+ </Match>+ <Match when={windows().length === 0}>+ <span class="px-2 py-1 text-xs text-ink-muted">+ No time off in the next 90 days+ </span>+ </Match>+ <Match when={windows().length > 0}>+ <For each={windows().slice(0, UPCOMING_SHOWN_MAX)}>+ {(window) => (+ <button+ type="button"+ class={cn(+ 'flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-xs',+ isActive(window) ? 'bg-active' : 'hover:bg-hover'+ )}+ aria-current={isActive(window) ? 'true' : undefined}+ onClick={(event) => {+ calendarPager.gotoDate(window.start);+ calendarView.selectEvent(+ window.event,+ event.currentTarget,+ 'agenda'+ );+ if (shell.aside.isOverlay()) shell.aside.collapse();+ }}+ >+ <UserIcon+ id={window.ownerId}+ size="md"+ suppressClick+ showTooltip={false}+ />+ <span class="flex min-w-0 flex-1 flex-col">+ <span class="flex w-full items-baseline gap-2">+ <span class="min-w-0 flex-1 truncate text-ink">+ {window.name}+ </span>+ <span class="shrink-0 text-ink-muted">+ {windowDateLabel(window)}+ </span>+ </span>+ <Show when={window.title}>+ <span class="w-full truncate text-ink-muted">+ {window.title}+ </span>+ </Show>+ </span>+ </button>+ )}+ </For>+ <Show when={windows().length > UPCOMING_SHOWN_MAX}>+ <span class="px-2 py-1 text-xs text-ink-muted">+ +{windows().length - UPCOMING_SHOWN_MAX} more+ </span>+ </Show>+ </Match>+ </Switch>+ </div>+ );+}++function CalendarTeamOooSection() {+ const calendarView = useCalendarView();+ const hasTeammates = useHasTeammates();+ const [open, setOpen] = createSignal(true);+ const isOverlayVisible = () =>+ calendarView.isSourceVisible(TEAM_OOO_SOURCE_ID);+ const setOverlayVisible = (visible: boolean) =>+ calendarView.setSourceVisibility(TEAM_OOO_SOURCE_ID, visible);++ return (+ <Show when={hasTeammates()}>+ <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>+ <CollapsibleSection.Header>+ <CollapsibleSection.Trigger class="min-w-0 flex-1">+ <span class="min-w-0 truncate">Team out of office</span>+ <CollapsibleSection.Indicator />+ </CollapsibleSection.Trigger>+ <span title="Show on calendar">+ <ToggleSwitch+ checked={isOverlayVisible()}+ onChange={setOverlayVisible}+ aria-label="Show team out of office on the calendar"+ />+ </span>+ </CollapsibleSection.Header>+ <CollapsibleSection.Content>+ <TeamOooUpcomingList />+ </CollapsibleSection.Content>+ </CollapsibleSection.Root>+ </Show>+ );+}++function CalendarSidebarOverlayClose() {+ const shell = useViewShell();+ return (+ <Show when={shell.aside.isOverlay() && isTouchDevice()}>+ <ViewSidebar.Control+ label="Close calendar navigation"+ onClick={shell.aside.collapse}+ >+ <CloseIcon class="size-4" />+ </ViewSidebar.Control>+ </Show>+ );+}++export function CalendarSidebar() {+ const shell = useViewShell();+ const closeOverlay = () => {+ if (shell.aside.isOverlay()) shell.aside.collapse();+ };++ return (+ <ViewSidebar.Root aria-label="Calendar navigation">+ <ViewSidebar.Header>+ <div class="flex min-w-0 items-center gap-1">+ <ViewSidebar.CloseButton />+ <ViewSidebar.Title>Calendar</ViewSidebar.Title>+ </div>+ <CalendarSidebarOverlayClose />+ </ViewSidebar.Header>+ <ViewSidebar.Primary>+ <CalendarCreateMenu+ size="md"+ class="h-(--sidebar-row-height) w-full min-w-0 justify-start gap-(--sidebar-label-gap) px-(--sidebar-item-inset) text-left touch:h-11"+ contentClass="w-[var(--kb-popper-anchor-width)] min-w-40"+ trigger={+ <>+ <ViewSidebar.Icon>+ <PlusIcon class="size-4" />+ </ViewSidebar.Icon>+ <span class="min-w-0 flex-1 truncate">New</span>+ <CaretDownIcon class="size-3.5 shrink-0" />+ </>+ }+ >+ <CalendarCreateEventItem onSelect={closeOverlay} />+ <CalendarCreateCallItem onSelect={closeOverlay} />+ <CalendarCreateReminderItem onSelect={closeOverlay} />+ </CalendarCreateMenu>+ </ViewSidebar.Primary>+ <ViewSidebar.Content class="pt-2">+ <CalendarMiniCalendar />+ <UpcomingEventsSection />+ <CalendarSourcesSection />+ <ShowFeatureFlag flag={enableCalendarTeamOoo}>+ <CalendarTeamOooSection />+ </ShowFeatureFlag>+ </ViewSidebar.Content>+ <ViewSidebar.Footer class="border-0">+ <ViewSidebar.Nav aria-label="Calendar tools">+ <CalendarSettingsDropdown sidebar />+ </ViewSidebar.Nav>+ </ViewSidebar.Footer>+ </ViewSidebar.Root>+ );+}diff --git a/apps/web/src/features/calendar-view/components/Header.tsx b/apps/web/src/features/calendar-view/components/Header.tsxindex fe96edc795..ff565725fd 100644--- a/apps/web/src/features/calendar-view/components/Header.tsx+++ b/apps/web/src/features/calendar-view/components/Header.tsx@@ -1,3 +1,4 @@+import { useViewShell, ViewShell } from '@app/components/view-shell';import { CopyAvailabilityButton } from '@app/features/calendar/availability/CopyAvailabilityButton';import {type CalendarPageId,@@ -9,8 +10,7 @@ import { MonthDrawer } from '@app/features/calendar/components/MonthDrawer';import { PeriodSelector } from '@app/features/calendar/components/PeriodSelector';import { useCalendarHotkeys } from '@app/features/calendar/hooks/use-calendar-hotkeys';import { calendarPeriodLabel } from '@app/features/calendar/utils/calendar-label';-import { useQuickCallsFlag } from '@app/features/meetings/use-quick-calls-flag';-import { useSidePanel } from '@components/app/side-panel/SidePanel';+import { createSizeBreakpoints } from '@app/util/create-size-breakpoints';import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';import {SplitHeaderLeft,@@ -19,17 +19,31 @@ import {import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { TOKENS } from '@core/hotkey/tokens';import { isMobile } from '@core/mobile/isMobile';+import { isTouchDevice } from '@core/mobile/isTouchDevice';import CalendarBlankIcon from '@phosphor/calendar-blank.svg';+import CaretDownIcon from '@phosphor/caret-down.svg';import CaretLeftIcon from '@phosphor/caret-left.svg';import CaretRightIcon from '@phosphor/caret-right.svg';-import PhoneIcon from '@phosphor/phone.svg';+import ListIcon from '@phosphor/list.svg';import PlusIcon from '@phosphor/plus.svg';-import { useNavigate } from '@solidjs/router';-import { Button } from '@ui';+import { createElementSize } from '@solid-primitives/resize-observer';+import { Button, cn } from '@ui';import { usePager } from '@ui/components/Pager';-import { createMemo, createSignal, onCleanup, Show } from 'solid-js';+import {+ createMemo,+ createSignal,+ Match,+ onCleanup,+ Show,+ Switch,+} from 'solid-js';+import {+ CalendarCreateCallItem,+ CalendarCreateEventItem,+ CalendarCreateReminderItem,+} from './CalendarCreateItems';+import { CalendarCreateMenu } from './CalendarCreateMenu';import { CalendarSearch } from './CalendarSearch';-import { useOpenEventComposer } from './use-open-event-composer';const formatMonthTitle = new Intl.DateTimeFormat(undefined, {month: 'long',@@ -64,18 +78,27 @@ function createLocalToday() {return today;}-export function Header() {+export function Header(props: { presentation: 'workspace' | 'preview' }) {const panel = useSplitPanelOrThrow();- const sidePanel = useSidePanel();+ // PreviewFrame owns its own top bar and may sit inside another view shell.+ const shell = props.presentation === 'workspace' ? useViewShell() : undefined;const calendarPager = useCalendarPager();const pager = usePager<CalendarPageId>();const calendarView = useCalendarView();- const openEventComposer = useOpenEventComposer();- const navigate = useNavigate();- const quickCalls = useQuickCallsFlag();const initialDate = new Date();+ const [headerElement, setHeaderElement] = createSignal<HTMLElement>();+ const headerSize = createElementSize(headerElement);+ // The shell width includes the sidebar; use the header's own main-pane width.+ const breakpoints = createSizeBreakpoints(() => headerSize.width ?? 0, {+ fullHeader: { min: 520 },+ periodControls: { min: 460 },+ navigationArrows: { min: 260 },+ });+ const isCompactHeader = () => !breakpoints.fullHeader();+ const showPeriodControls = breakpoints.periodControls;+ const showNavigationArrows = breakpoints.navigationArrows;const today = createLocalToday();-+ const [narrowSearchOpen, setNarrowSearchOpen] = createSignal(false);useCalendarHotkeys({scopeId: panel.splitHotkeyScope,changeView: calendarPager.changeView,@@ -91,131 +114,174 @@ export function Header() {const periodLabel = createMemo(() =>calendarPeriodLabel(calendarView.displaySettings.periodView).toLowerCase());- const visibleRange = createMemo(() => {- const dateInfo = calendarPager.activeDateInfo();- return dateInfo ? { end: dateInfo.end, start: dateInfo.start } : undefined;- });- const isTodayVisible = createMemo(() => {- const range = visibleRange();- if (!range) return true;+ const isNarrow = () => shell?.aside.isCollapsed() ?? true;+ const showHeaderCreate = () =>+ isCompactHeader() ||+ (shell?.aside.isCollapsed() && !shell?.aside.isOverlay());+ const showDesktopNavigation = () => {+ if (!showNavigationArrows()) return false;+ return !isCompactHeader() || !narrowSearchOpen();+ };+ const usesSplitHeader = () =>+ props.presentation === 'preview' || isTouchDevice();+ const createItems = () => (+ <>+ <CalendarCreateEventItem />+ <CalendarCreateCallItem />+ <CalendarCreateReminderItem />+ </>+ );+ const headerCreateMenu = () => (+ <CalendarCreateMenu+ size="md"+ class="h-(--sidebar-row-height) gap-(--sidebar-label-gap) rounded-full px-(--sidebar-item-inset) touch:h-11"+ trigger={+ <>+ <PlusIcon class="size-3.5" />+ <span>New</span>+ <CaretDownIcon class="size-3.5 shrink-0" />+ </>+ }+ >+ {createItems()}+ </CalendarCreateMenu>+ );- const currentDay = today();- return currentDay >= range.start && currentDay < range.end;- });+ const previous = () => (+ <Button+ variant="ghost"+ size="icon-lg"+ class="rounded-full border-transparent bg-transparent"+ label={`Previous ${periodLabel()}`}+ hotkey={TOKENS.calendar.period.previous}+ onClick={() => void pager.previous()}+ >+ <CaretLeftIcon class="size-5" />+ </Button>+ );+ const next = () => (+ <Button+ variant="ghost"+ size="icon-lg"+ class="rounded-full border-transparent bg-transparent"+ label={`Next ${periodLabel()}`}+ hotkey={TOKENS.calendar.period.next}+ onClick={() => void pager.next()}+ >+ <CaretRightIcon class="size-5" />+ </Button>+ );+ const todayButton = (mobile: boolean) => (+ <Button+ variant={mobile ? 'ghost' : 'outline'}+ size={mobile ? 'icon-lg' : 'lg'}+ class={cn(+ 'rounded-full',+ mobile && 'relative',+ !mobile && 'border-edge-button bg-transparent px-3 text-sm'+ )}+ label="Go to today"+ hotkey={TOKENS.calendar.period.today}+ onClick={calendarPager.navigateToToday}+ >+ <Show when={mobile} fallback="Today">+ <CalendarBlankIcon aria-hidden="true" />+ <span+ aria-hidden="true"+ class="pointer-events-none absolute inset-0 flex items-center justify-center pt-1 text-[10px] font-bold leading-none"+ >+ {today().getDate()}+ </span>+ </Show>+ </Button>+ );return (- <>- <SplitHeaderLeft>- <HeaderIsland class="shrink">- <Show- when={isMobile()}- fallback={- <>- <span class="min-w-0 truncate text-base font-semibold text-ink">- {dateTitle()}- </span>- <CopyAvailabilityButton class="ml-2" />- </>- }- >- <MonthDrawer month={currentDate()} />- </Show>- </HeaderIsland>- </SplitHeaderLeft>-- <SplitHeaderRight>- <HeaderIsland class="px-1">- <div class="flex items-center gap-1">- <Show- when={isMobile()}- fallback={- <Show when={!isTodayVisible()}>- <Button- variant="accent"- size="sm"- class="rounded-lg px-3"- depth={2}- label="Go to today"- hotkey={TOKENS.calendar.period.today}- onClick={calendarPager.navigateToToday}- >- Today- </Button>- </Show>- }- >+ <Switch>+ <Match when={usesSplitHeader()}>+ <SplitHeaderLeft>+ <HeaderIsland class="min-w-0 shrink px-1">+ <Show when={!isMobile() && shell?.aside.isCollapsed()}><Buttonvariant="ghost"size="icon-sm"- class="rounded-full"- label="Go to today"- hotkey={TOKENS.calendar.period.today}- onClick={calendarPager.navigateToToday}+ class="shrink-0 rounded-full"+ label="Show calendar navigation"+ aria-expanded={shell?.aside.isOverlay() ?? false}+ onClick={() => shell?.aside.expand()}>- <CalendarBlankIcon aria-hidden="true" />- <span- aria-hidden="true"- class="pointer-events-none absolute inset-0 flex items-center justify-center pt-1 text-[8px] font-bold leading-none"- >- {today().getDate()}- </span>+ <ListIcon class="size-5" /></Button></Show>- <Button- variant="ghost"- size="sm"- class="rounded-lg px-2 @max-[520px]/split-header:size-6 @max-[520px]/split-header:p-1 touch:rounded-full"- label="New event"- onClick={() => openEventComposer()}- >- <PlusIcon class="size-3.5" />- <span class="@max-[520px]/split-header:hidden">New event</span>- </Button>- <Show when={quickCalls().enabled}>- <Button- variant="ghost"- size="sm"- class="rounded-lg px-2 @max-[520px]/split-header:size-6 @max-[520px]/split-header:p-1 touch:rounded-full"- label="New Call"- hotkey={TOKENS.create.call}- onClick={() => {- if (quickCalls().enabled) navigate('/meet/new');- }}+ <MonthDrawer month={currentDate()} />+ {todayButton(isTouchDevice())}+ <Show when={props.presentation === 'preview'}>+ <CalendarCreateMenu+ size="icon-lg"+ class="shrink-0 rounded-full border-transparent bg-transparent"+ label="New"+ trigger={<PlusIcon class="size-5" />}>- <PhoneIcon class="size-3.5" />- <span class="@max-[520px]/split-header:hidden">New Call</span>- </Button>+ {createItems()}+ </CalendarCreateMenu></Show>- <Show when={!isMobile()}>- <PeriodSelector isNarrow={sidePanel?.isNarrow()} />- <div class="flex shrink-0 items-center gap-1">- <Button- variant="ghost"- size="icon-sm"- class="rounded-lg"- label={`Previous ${periodLabel()}`}- hotkey={TOKENS.calendar.period.previous}- onClick={() => void pager.previous()}- >- <CaretLeftIcon class="size-4" />- </Button>- <Button- variant="ghost"- size="icon-sm"- class="rounded-lg"- label={`Next ${periodLabel()}`}- hotkey={TOKENS.calendar.period.next}- onClick={() => void pager.next()}- >- <CaretRightIcon class="size-4" />- </Button>+ </HeaderIsland>+ </SplitHeaderLeft>++ <SplitHeaderRight>+ <HeaderIsland class="px-1">+ <div class="flex items-center gap-1">+ <Show when={!isMobile()}>+ <PeriodSelector isNarrow={isNarrow()} />+ <div class="flex shrink-0 items-center gap-1">+ {previous()}+ {next()}+ </div>+ </Show>+ <Show when={isMobile() && props.presentation === 'workspace'}>+ <CopyAvailabilityButton size="icon-lg" />+ </Show>+ <CalendarSearch />+ <Show when={props.presentation === 'preview' || isMobile()}>+ <CalendarSettingsDropdown isNarrow={isNarrow()} />+ </Show>+ </div>+ </HeaderIsland>+ </SplitHeaderRight>+ </Match>+ <Match when={!usesSplitHeader()}>+ <ViewShell.TopBar class="py-2">+ <h1 class="min-w-0 truncate text-sm font-semibold tracking-[-0.03em] text-ink">+ {dateTitle()}+ </h1>+ <Show when={showHeaderCreate()}>+ <div class="ml-auto flex shrink-0 items-center gap-1">+ {headerCreateMenu()}+ </div>+ </Show>+ </ViewShell.TopBar>+ <ViewShell.Header ref={setHeaderElement}>+ <div class="flex h-10 min-w-0 items-center gap-2">+ <div class="min-w-0 max-w-md flex-1">+ <CalendarSearch+ inline+ compact={isCompactHeader()}+ onOpenChange={setNarrowSearchOpen}+ />+ </div>+ <Show when={showDesktopNavigation()}>+ <div class="ml-auto flex shrink-0 items-center gap-1">+ <Show when={showPeriodControls()}>+ {todayButton(false)}+ <PeriodSelector isNarrow={isNarrow()} />+ </Show>+ {previous()}+ {next()}</div></Show>- <CalendarSearch />- <CalendarSettingsDropdown isNarrow={sidePanel?.isNarrow()} /></div>- </HeaderIsland>- </SplitHeaderRight>- </>+ </ViewShell.Header>+ </Match>+ </Switch>);}diff --git a/apps/web/src/features/calendar-view/components/Page.tsx b/apps/web/src/features/calendar-view/components/Page.tsxindex fa9defcae3..3595186223 100644--- a/apps/web/src/features/calendar-view/components/Page.tsx+++ b/apps/web/src/features/calendar-view/components/Page.tsx@@ -44,6 +44,7 @@ import {import { Button } from '@ui';import {type Accessor,+ createDeferred,createEffect,createMemo,createSignal,@@ -232,10 +233,16 @@ export function Page(props: {const isActive = () => pager.isActive(props.id);const useNarrowWeekdayHeaders = () =>props.useNarrowDayHeaders && !isMobile();+ // Let the checkbox update before remapping occurrences and redrawing the grid.+ // Each page has its own deferred update, so the scheduler can yield between+ // the three FullCalendar instances.+ const renderedHiddenSourceIds = createDeferred(calendarView.hiddenSourceIds);+ const isRenderedSourceVisible = (sourceId: string) =>+ !renderedHiddenSourceIds().has(sourceId);const data = useCalendarOccurrenceData({range,sourceById: calendarView.sourceById,- isSourceVisible: calendarView.isSourceVisible,+ isSourceVisible: isRenderedSourceVisible,queryOptions: () => ({pollWhileSyncing: isActive(),refetchOnWindowFocus: isActive(),@@ -243,7 +250,7 @@ export function Page(props: {});const teamOoo = useTeamOooEvents({range,- isSourceVisible: calendarView.isSourceVisible,+ isSourceVisible: isRenderedSourceVisible,refetchOnWindowFocus: isActive,});const visibleEvents = createMemo(() => [diff --git a/apps/web/src/features/calendar-view/components/SidePanelSections.tsx b/apps/web/src/features/calendar-view/components/SidePanelSections.tsxdeleted file mode 100644index cef2a43956..0000000000--- a/apps/web/src/features/calendar-view/components/SidePanelSections.tsx+++ /dev/null@@ -1,231 +0,0 @@-import { useCalendarPager } from '@app/features/calendar/components/CalendarPagerContext';-import { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';-import { SourceControls } from '@app/features/calendar/components/SourceControls';-import {- TEAM_OOO_SOURCE_ID,- type TeamOooWindow,- useHasTeammates,- useUpcomingTeamOoo,-} from '@app/features/calendar/hooks/use-team-ooo';-import { ShowFeatureFlag } from '@app/lib/analytics/posthog';-import { SidePanel, useSidePanel } from '@components/app/side-panel/SidePanel';-import { enableCalendarTeamOoo } from '@core/constant/featureFlags';-import { Calendar as MiniCalendar, ToggleSwitch } from '@ui';-import { format } from 'date-fns';-import {- createEffect,- createMemo,- createSignal,- For,- Match,- on,- Show,- Switch,-} from 'solid-js';-import { CalendarCallsSidePanelSection } from '../calendar-call-sidebar';--function CalendarMiniCalendarSidePanelSection() {- const calendarView = useCalendarView();- const calendarPager = useCalendarPager();- const initialDate = new Date();- const [focusedDay, setFocusedDay] = createSignal(initialDate);-- const currentDate = createMemo(- () => calendarPager.activeDateInfo()?.view.calendar.getDate() ?? initialDate- );-- const highlightedRange = createMemo(() => {- const dateInfo = calendarPager.activeDateInfo();- return dateInfo?.view.type === 'timeGridWeek'- ? { end: dateInfo.end, start: dateInfo.start }- : undefined;- });-- const selectDate = (date: Date | null) => {- if (!date) return;- setFocusedDay(date);- calendarPager.gotoDate(date);- };-- const navigateMonth = (month: Date) => {- const focused = focusedDay();- const targetDate =- focused.getFullYear() === month.getFullYear() &&- focused.getMonth() === month.getMonth()- ? focused- : month;- setFocusedDay(targetDate);- calendarPager.gotoDate(targetDate);- };-- createEffect(on(currentDate, setFocusedDay));-- return (- <SidePanel.Section- id="calendar-mini-calendar"- title="Calendar"- order={10}- defaultOpen- >- <MiniCalendar- required- fixedWeeks- startOfWeek={calendarView.displaySettings.weekStartsOn}- value={currentDate()}- month={currentDate()}- focusedDay={focusedDay()}- highlightedRange={highlightedRange()}- onMonthChange={navigateMonth}- onFocusedDayChange={setFocusedDay}- onValueChange={selectDate}- />- </SidePanel.Section>- );-}--function CalendarSourcesSidePanelSection() {- const calendarView = useCalendarView();-- return (- <Show when={calendarView.sources().length > 1}>- <SidePanel.Section- id="calendar-controls"- title="Calendars"- order={20}- defaultOpen- >- <SourceControls- sources={calendarView.sources()}- isVisible={calendarView.isSourceVisible}- onVisibilityChange={calendarView.setSourceVisibility}- />- </SidePanel.Section>- </Show>- );-}--function CalendarTeamOooSidePanelSection() {- const calendarView = useCalendarView();- const hasTeammates = useHasTeammates();- const isOverlayVisible = () =>- calendarView.isSourceVisible(TEAM_OOO_SOURCE_ID);- const setOverlayVisible = (visible: boolean) =>- calendarView.setSourceVisibility(TEAM_OOO_SOURCE_ID, visible);-- return (- <Show when={hasTeammates()}>- <SidePanel.Section- id="calendar-team-ooo"- title="Team out of office"- order={30}- defaultOpen- actions={- <span title="Show on calendar">- <ToggleSwitch- checked={isOverlayVisible()}- onChange={setOverlayVisible}- aria-label="Show team out of office on the calendar"- />- </span>- }- >- <TeamOooUpcomingList />- </SidePanel.Section>- </Show>- );-}--const UPCOMING_SHOWN_MAX = 10;--function windowDateLabel(window: TeamOooWindow): string {- // The exclusive end pulled back a moment lands on the last covered day for- // both all-day dates and timed spans ending at midnight.- const lastDay = new Date(window.end.getTime() - 1);- return window.start.toDateString() === lastDay.toDateString()- ? format(window.start, 'EEE, MMM d')- : `${format(window.start, 'MMM d')} – ${format(lastDay, 'MMM d')}`;-}--function TeamOooSkeleton() {- return (- <div aria-hidden="true" class="flex flex-col gap-0.5">- <For each={[0, 1, 2]}>- {() => (- <div class="skeleton-shimmer h-8 w-full rounded-lg bg-skeleton" />- )}- </For>- </div>- );-}--function TeamOooUpcomingList() {- const calendarPager = useCalendarPager();- const upcoming = useUpcomingTeamOoo();- const windows = upcoming.windows;-- return (- <div class="flex flex-col gap-0.5">- <Switch>- <Match when={upcoming.isPending()}>- <TeamOooSkeleton />- </Match>- <Match when={upcoming.isError()}>- <span class="px-2 py-1 text-xs text-ink-muted">- Couldn't load time off- </span>- </Match>- <Match when={windows().length === 0}>- <span class="px-2 py-1 text-xs text-ink-muted">- No time off in the next 90 days- </span>- </Match>- <Match when={windows().length > 0}>- <For each={windows().slice(0, UPCOMING_SHOWN_MAX)}>- {(window) => (- <button- type="button"- class="flex w-full flex-col rounded-lg px-2 py-1.5 text-left text-xs hover:bg-hover"- onClick={() => calendarPager.gotoDate(window.start)}- >- <span class="flex w-full items-baseline gap-2">- <span class="min-w-0 flex-1 truncate text-ink">- {window.name}- </span>- <span class="shrink-0 text-ink-muted">- {windowDateLabel(window)}- </span>- </span>- <Show when={window.title}>- <span class="w-full truncate text-ink-muted">- {window.title}- </span>- </Show>- </button>- )}- </For>- <Show when={windows().length > UPCOMING_SHOWN_MAX}>- <span class="px-2 py-1 text-xs text-ink-muted">- +{windows().length - UPCOMING_SHOWN_MAX} more- </span>- </Show>- </Match>- </Switch>- </div>- );-}--/** Registers the calendar's contextual right-side panel sections. */-export function SidePanelSections() {- const sidePanel = useSidePanel();-- return (- <Show when={!sidePanel?.isNarrow()}>- <CalendarMiniCalendarSidePanelSection />- <CalendarCallsSidePanelSection />- <CalendarSourcesSidePanelSection />- <ShowFeatureFlag flag={enableCalendarTeamOoo}>- <CalendarTeamOooSidePanelSection />- </ShowFeatureFlag>- </Show>- );-}diff --git a/apps/web/src/features/calendar-view/components/Workspace.tsx b/apps/web/src/features/calendar-view/components/Workspace.tsxindex 30f883fa97..293bbe82d8 100644--- a/apps/web/src/features/calendar-view/components/Workspace.tsx+++ b/apps/web/src/features/calendar-view/components/Workspace.tsx@@ -1,3 +1,4 @@+import { ViewShell } from '@app/components/view-shell';import {CALENDAR_PAGE_IDS,CalendarPagerContextProvider,@@ -5,43 +6,60 @@ import {} from '@app/features/calendar/components/CalendarPagerContext';import { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';import { RangeUnavailableBanner } from '@app/features/calendar/components/RangeUnavailableBanner';-import { SidePanel } from '@components/app/side-panel/SidePanel';+import { createSizeBreakpoints } from '@app/util/create-size-breakpoints';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { SplitPanel } from '@components/app/split-panel';import { isMobile } from '@core/mobile/isMobile';-import { createResizeObserver } from '@solid-primitives/resize-observer';+import { createElementSize } from '@solid-primitives/resize-observer';import { Layer } from '@ui';import { Pager, PagerSwipeGestures } from '@ui/components/Pager';import {+ createEffect,createSignal,For,+ Match,+ on,onCleanup,onMount,Show,Suspense,+ Switch,} from 'solid-js';+import { CalendarSidebar } from './CalendarSidebar';import { Header } from './Header';import { Page } from './Page';import { SelectedEventDetails } from './SelectedEventDetails';import { SetupStatus } from './SetupStatus';-import { SidePanelSections } from './SidePanelSections';const CALENDAR_SWIPE_EDGE_INSET = 40;function CalendarPages() {const calendarPager = useCalendarPager();const [viewport, setViewport] = createSignal<HTMLDivElement>();- const [useNarrowDayHeaders, setUseNarrowDayHeaders] = createSignal(false);+ const viewportSize = createElementSize(viewport);+ const breakpoints = createSizeBreakpoints(+ () => viewportSize.width ?? undefined,+ {+ fullDayHeaders: { min: 520 },+ }+ );+ const useNarrowDayHeaders = () =>+ viewportSize.width !== null && !breakpoints.fullDayHeaders();let resizeFrame: number | undefined;- createResizeObserver(viewport, ({ width }) => {- if (resizeFrame !== undefined) cancelAnimationFrame(resizeFrame);-- resizeFrame = requestAnimationFrame(() => {- resizeFrame = undefined;- setUseNarrowDayHeaders(width < 520);- calendarPager.updateSize();- });- });+ createEffect(+ on(+ () => viewportSize.width,+ (width) => {+ if (width === null) return;+ if (resizeFrame !== undefined) cancelAnimationFrame(resizeFrame);+ resizeFrame = requestAnimationFrame(() => {+ resizeFrame = undefined;+ calendarPager.updateSize();+ });+ }+ )+ );onCleanup(() => {if (resizeFrame !== undefined) cancelAnimationFrame(resizeFrame);@@ -95,6 +113,14 @@ function CalendarPages() {);}+function CalendarPageContent() {+ return (+ <div class="calendar-view-content flex min-w-0 min-h-0 flex-1 flex-col">+ <CalendarPages />+ </div>+ );+}+function WorkspaceContent() {const panel = useSplitPanelOrThrow();const calendarView = useCalendarView();@@ -104,24 +130,50 @@ function WorkspaceContent() {if (!panel.isInlinePreview) panel.handle.setDisplayName('Calendar');});- return (- <>- <Header />- <SidePanelSections />-- <SelectedEventDetails- anchor={calendarView.selectedEventAnchor}- event={calendarView.selectedEvent}- timeFormat={() => calendarView.displaySettings.timeFormat}- onClose={calendarView.closeEventDetails}- />+ const eventDetails = () => (+ <SelectedEventDetails+ anchor={calendarView.selectedEventAnchor}+ event={calendarView.selectedEvent}+ timeFormat={() => calendarView.displaySettings.timeFormat}+ onClose={calendarView.closeEventDetails}+ />+ );- <main class="flex size-full min-h-0">- <div class="calendar-view-content flex min-w-0 min-h-0 flex-1 flex-col">- <CalendarPages />- </div>- </main>- </>+ return (+ <Switch>+ <Match when={panel.isInlinePreview}>+ <Header presentation="preview" />+ {eventDetails()}+ <main class="flex size-full min-h-0">+ <CalendarPageContent />+ </main>+ </Match>+ <Match when={!panel.isInlinePreview}>+ <SplitPanel.Root>+ <SplitPanel.Body>+ <ViewShell.Root+ asidePreferenceKey="calendar"+ resizable+ aside={isMobile() ? false : { preserveDuringResize: false }}+ main={{ preferredWidth: 640 }}+ >+ <Show when={!isMobile()}>+ <ViewShell.Aside>+ <CalendarSidebar />+ </ViewShell.Aside>+ </Show>+ <ViewShell.Main>+ <Header presentation="workspace" />+ <ViewShell.Content class="flex min-h-0 flex-1">+ <CalendarPageContent />+ </ViewShell.Content>+ </ViewShell.Main>+ </ViewShell.Root>+ {eventDetails()}+ </SplitPanel.Body>+ </SplitPanel.Root>+ </Match>+ </Switch>);}@@ -130,9 +182,7 @@ function CalendarPagerWorkspace() {return (<Pager.Root controller={calendarPager.pager}>- <SidePanel.Layout persistKey="calendar">- <WorkspaceContent />- </SidePanel.Layout>+ <WorkspaceContent /></Pager.Root>);}diff --git a/apps/web/src/features/calendar/availability/CopyAvailabilityButton.tsx b/apps/web/src/features/calendar/availability/CopyAvailabilityButton.tsxindex 702b46cecd..c5abeb9f34 100644--- a/apps/web/src/features/calendar/availability/CopyAvailabilityButton.tsx+++ b/apps/web/src/features/calendar/availability/CopyAvailabilityButton.tsx@@ -1,203 +1,31 @@-import { toast } from '@core/component/Toast/Toast';-import { writeClipboardData } from '@core/util/dataTransfer';import CalendarCheckIcon from '@phosphor/calendar-check.svg';-import CaretRightIcon from '@phosphor/caret-right.svg';-import CheckIcon from '@phosphor/check.svg';-import GearIcon from '@phosphor/gear.svg';-import { ButtonGroup, cn, Dropdown } from '@ui';-import { For, Show } from 'solid-js';+import { Button, type ButtonSize, useImperativeDialog } from '@ui';+import { Show } from 'solid-js';import { useCalendarConnectedInboxes } from '../hooks/use-calendar-connected-inboxes';-import {- AVAILABILITY_RANGE_OPTIONS,- type AvailabilityRangeKey,-} from './availability';-import { useAvailabilitySettings } from './settings';-import { useAvailabilityText } from './use-availability-text';+import { CopyAvailabilityDialog } from './CopyAvailabilityDialog';-interface TimeOption {- value: string;- label: string;-}--const timeLabelFormatter = new Intl.DateTimeFormat(undefined, {- hour: 'numeric',- minute: '2-digit',-});--/** Half-hour choices between two local hours (inclusive). */-function timeOptions(fromHour: number, toHour: number): TimeOption[] {- const options: TimeOption[] = [];- for (let minutes = fromHour * 60; minutes <= toHour * 60; minutes += 30) {- const hour = Math.floor(minutes / 60);- const minute = minutes % 60;- options.push({- value: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,- label: timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute)),- });- }- return options;-}--const START_TIME_OPTIONS = timeOptions(6, 12);-const END_TIME_OPTIONS = timeOptions(12, 22);--function timeOptionLabel(options: TimeOption[], value: string): string {- const known = options.find((option) => option.value === value)?.label;- if (known) return known;- const [hour = 0, minute = 0] = value.split(':').map(Number);- return timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute));-}--function TimeRadioGroup(props: {- options: TimeOption[];- value: string;- onChange: (value: string) => void;+/** Opens the shared availability dialog when a calendar account is connected. */+export function CopyAvailabilityButton(props: {+ class?: string;+ size?: ButtonSize;}) {- return (- <Dropdown.RadioGroup value={props.value} onChange={props.onChange}>- <For each={props.options}>- {(option) => (- <Dropdown.RadioItem closeOnSelect value={option.value}>- <span class="flex-1">{option.label}</span>- <Dropdown.ItemIndicator>- <CheckIcon class="size-3.5 text-accent" />- </Dropdown.ItemIndicator>- </Dropdown.RadioItem>- )}- </For>- </Dropdown.RadioGroup>- );-}--/**- * Split control for sharing availability: the labeled half opens a range- * menu ("Today" … "Next 14 days") that copies the viewer's free slots as- * text; the gear half opens the feature's settings (workday start/end,- * exclude weekends).- */-export function CopyAvailabilityButton(props: { class?: string }) {- const getAvailabilityText = useAvailabilityText();- const { settings, setStartTime, setEndTime, setExcludeWeekends } =- useAvailabilitySettings();- // Without a calendar-connected inbox every range would read as fully- // free, so the control offers nothing useful and stays hidden.+ const dialog = useImperativeDialog(CopyAvailabilityDialog);const connectedInboxes = useCalendarConnectedInboxes();-- const startTimeLabel = () =>- timeOptionLabel(START_TIME_OPTIONS, settings().startTime);- const endTimeLabel = () =>- timeOptionLabel(END_TIME_OPTIONS, settings().endTime);-- const copyRange = async (rangeKey: AvailabilityRangeKey) => {- try {- const text = await getAvailabilityText(rangeKey);- if (!text) {- toast.alert('No free time in that range');- return;- }- if (await writeClipboardData({ 'text/plain': text })) {- toast.success('Availability copied');- } else {- toast.failure('Failed to copy availability');- }- } catch {- toast.failure('Failed to load availability');- }+ const showDialog = () => {+ if (!dialog.isOpen()) dialog.open({});};return (<Show when={connectedInboxes().length > 0}>- <ButtonGroup+ <Buttonvariant="ghost"- size="sm"- class={cn('shrink-0 rounded-lg border border-edge-muted', props.class)}+ size={props.size ?? 'icon-sm'}+ class={props.class}+ label="Copy availability"+ onClick={showDialog}>- <Dropdown placement="bottom-start">- <Dropdown.Trigger class="gap-1.5 bg-transparent px-2 hover:bg-ink/[0.04]">- <CalendarCheckIcon class="size-3.5 shrink-0" />- <span class="truncate text-xs font-medium">Copy availability</span>- </Dropdown.Trigger>- <Dropdown.Content class="min-w-40">- <Dropdown.Group>- <For each={AVAILABILITY_RANGE_OPTIONS}>- {(option) => (- <Dropdown.Item- closeOnSelect- onSelect={() => void copyRange(option.key)}- >- <span class="flex-1 truncate">{option.label}</span>- </Dropdown.Item>- )}- </For>- </Dropdown.Group>- </Dropdown.Content>- </Dropdown>-- <ButtonGroup.Divider />-- <Dropdown placement="bottom-end">- <Dropdown.Trigger- class="bg-transparent p-1 hover:bg-ink/[0.04]"- label="Availability settings"- >- <GearIcon class="size-3.5" />- </Dropdown.Trigger>- <Dropdown.Content class="w-56 max-w-[calc(100vw-1rem)]">- <Dropdown.Group>- <Dropdown.GroupLabel>Availability</Dropdown.GroupLabel>- <Dropdown.CheckboxItem- checked={settings().excludeWeekends}- closeOnSelect={false}- onChange={setExcludeWeekends}- >- <span class="flex-1 truncate">Exclude weekends</span>- </Dropdown.CheckboxItem>-- <Dropdown.Sub>- <Dropdown.SubTrigger>- <span class="min-w-0 flex-1 truncate text-xs text-ink-muted">- Start time- </span>- <span class="text-sm font-medium text-ink">- {startTimeLabel()}- </span>- <CaretRightIcon class="size-3 shrink-0 text-ink-muted" />- </Dropdown.SubTrigger>- <Dropdown.SubContent class="max-h-72 min-w-36 overflow-y-auto">- <Dropdown.Group>- <TimeRadioGroup- options={START_TIME_OPTIONS}- value={settings().startTime}- onChange={setStartTime}- />- </Dropdown.Group>- </Dropdown.SubContent>- </Dropdown.Sub>-- <Dropdown.Sub>- <Dropdown.SubTrigger>- <span class="min-w-0 flex-1 truncate text-xs text-ink-muted">- End time- </span>- <span class="text-sm font-medium text-ink">- {endTimeLabel()}- </span>- <CaretRightIcon class="size-3 shrink-0 text-ink-muted" />- </Dropdown.SubTrigger>- <Dropdown.SubContent class="max-h-72 min-w-36 overflow-y-auto">- <Dropdown.Group>- <TimeRadioGroup- options={END_TIME_OPTIONS}- value={settings().endTime}- onChange={setEndTime}- />- </Dropdown.Group>- </Dropdown.SubContent>- </Dropdown.Sub>- </Dropdown.Group>- </Dropdown.Content>- </Dropdown>- </ButtonGroup>+ <CalendarCheckIcon />+ </Button></Show>);}diff --git a/apps/web/src/features/calendar/availability/CopyAvailabilityDialog.test.tsx b/apps/web/src/features/calendar/availability/CopyAvailabilityDialog.test.tsxnew file mode 100644index 0000000000..1c02fada5e--- /dev/null+++ b/apps/web/src/features/calendar/availability/CopyAvailabilityDialog.test.tsx@@ -0,0 +1,222 @@+/**+ * @vitest-environment jsdom+ */++import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { AvailabilityRangeKey } from './availability';+import { CopyAvailabilityDialog } from './CopyAvailabilityDialog';++const mocks = vi.hoisted(() => ({+ days: vi.fn(),+ refreshRange: vi.fn(),+ isError: vi.fn(),+ retry: vi.fn(),+ writeClipboardData: vi.fn(),+ failure: vi.fn(),+ alert: vi.fn(),+}));++vi.mock('./use-availability-ranges', () => ({+ useAvailabilityRanges: () => ({+ days: mocks.days,+ refreshRange: mocks.refreshRange,+ isError: mocks.isError,+ retry: mocks.retry,+ }),+}));+vi.mock('./settings', () => ({+ useAvailabilitySettings: () => ({+ settings: () => ({+ startTime: '09:00',+ endTime: '18:00',+ excludeWeekends: true,+ }),+ setStartTime: vi.fn(),+ setEndTime: vi.fn(),+ setExcludeWeekends: vi.fn(),+ }),+ getPersistedCalendarTimeFormat: () => '12-hour',+}));+vi.mock('@core/util/dataTransfer', () => ({+ writeClipboardData: mocks.writeClipboardData,+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { alert: mocks.alert, failure: mocks.failure },+}));++const availableDay = {+ date: new Date(2026, 7, 24),+ slots: [+ {+ start: new Date(2026, 7, 24, 10),+ end: new Date(2026, 7, 24, 11),+ },+ ],+};++beforeEach(() => {+ vi.stubGlobal('scrollTo', vi.fn());+ mocks.days.mockReturnValue({+ today: [availableDay],+ thisWeek: [availableDay],+ next7Days: [availableDay],+ next14Days: [availableDay],+ } satisfies Record<AvailabilityRangeKey, (typeof availableDay)[]>);+ mocks.isError.mockReturnValue(false);+ mocks.writeClipboardData.mockResolvedValue(true);+ mocks.refreshRange.mockResolvedValue({+ days: [availableDay],+ now: new Date(2026, 7, 24, 10),+ });+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++it('keeps the button neutral after copying and colors only the check', async () => {+ render(() => <CopyAvailabilityDialog open onOpenChange={vi.fn()} />);++ fireEvent.click(+ screen.getByRole('button', { name: 'Copy availability for Today' })+ );++ const copied = await screen.findByRole('button', {+ name: 'Today availability copied',+ });+ expect(copied.getAttribute('data-variant')).toBe('outline');+ expect(copied.className).not.toContain('bg-success');+ expect(copied.textContent).toContain('Copied');+ expect(copied.querySelector('svg.text-success')).toBeTruthy();+ expect(screen.getByRole('status').textContent).toBe('Availability copied');+ expect(mocks.writeClipboardData).toHaveBeenCalledWith({+ 'text/plain': expect.stringContaining('Mon, Aug 24: 10:00 AM – 11:00 AM'),+ });+ expect(mocks.refreshRange).toHaveBeenCalledWith('today');+});++it('crossfades a left spinner into the copied state without changing button width', async () => {+ let finishRefresh!: (result: {+ days: (typeof availableDay)[];+ now: Date;+ }) => void;+ mocks.refreshRange.mockImplementation(+ () =>+ new Promise((resolve) => {+ finishRefresh = resolve;+ })+ );+ render(() => <CopyAvailabilityDialog open onOpenChange={vi.fn()} />);++ const initial = screen.getByRole('button', {+ name: 'Copy availability for Today',+ });+ const idleLayer = initial.querySelector('span[aria-hidden]')?.children[0];+ fireEvent.click(initial);++ const copying = screen.getByRole('button', {+ name: 'Copying availability for Today',+ });+ const layers = copying.querySelector('span[aria-hidden]')?.children;+ expect(copying.getAttribute('aria-busy')).toBe('true');+ expect(copying).toBe(initial);+ expect(copying.querySelector('span[aria-hidden]')?.className).toContain(+ 'grid'+ );+ expect(idleLayer?.className).toContain('opacity-0');+ expect(layers?.[1].className).toContain('opacity-100');+ expect(layers?.[1].firstElementChild?.getAttribute('class')).toContain(+ 'animate-spin'+ );+ expect(screen.getByRole('status').textContent).toBe('Copying availability');++ finishRefresh({ days: [availableDay], now: new Date(2026, 7, 24, 10) });+ const copied = await screen.findByRole('button', {+ name: 'Today availability copied',+ });+ expect(copied).toBe(initial);+ expect(+ copied.querySelector('span[aria-hidden]')?.children[2].className+ ).toContain('opacity-100');+ expect(copied.getAttribute('aria-busy')).toBe('false');+});+it('does not copy when a fresh check finds no availability', async () => {+ mocks.refreshRange.mockResolvedValue({+ days: [],+ now: new Date(2026, 7, 24, 10),+ });+ render(() => <CopyAvailabilityDialog open onOpenChange={vi.fn()} />);++ fireEvent.click(+ screen.getByRole('button', { name: 'Copy availability for Today' })+ );+ await waitFor(() => {+ expect(mocks.alert).toHaveBeenCalledWith('No free time in that range');+ });+ expect(mocks.refreshRange).toHaveBeenCalledWith('today');+ expect(mocks.writeClipboardData).not.toHaveBeenCalled();+});+it('disables empty ranges with an explanation while leaving others available', () => {+ mocks.days.mockReturnValue({+ today: [],+ thisWeek: [availableDay],+ next7Days: [availableDay],+ next14Days: [availableDay],+ });+ render(() => <CopyAvailabilityDialog open onOpenChange={vi.fn()} />);++ const today = screen.getByRole('button', {+ name: 'Copy availability for Today: No free time in this range',+ });+ expect(today.hasAttribute('disabled')).toBe(true);+ expect(today.className).toContain('disabled:opacity-50');+ const idle = today.querySelector('span[aria-hidden]')?.children[0];+ expect(idle?.textContent).toBe('Today');+ expect(idle?.querySelector('svg')).toBeTruthy();+ expect(screen.queryByText('No free time', { exact: true })).toBeNull();+ expect(today.textContent).not.toContain('No free time');+ fireEvent.click(today);+ expect(mocks.writeClipboardData).not.toHaveBeenCalled();+ const thisWeek = screen.getByRole('button', {+ name: 'Copy availability for This week',+ });+ expect(thisWeek.hasAttribute('disabled')).toBe(false);+ expect(idle?.querySelector('svg')?.outerHTML).not.toEqual(+ thisWeek+ .querySelector('span[aria-hidden]')+ ?.children[0].querySelector('svg')?.outerHTML+ );+});++it('disables all options while checking availability', () => {+ mocks.days.mockReturnValue(undefined);+ render(() => <CopyAvailabilityDialog open onOpenChange={vi.fn()} />);++ const buttons = screen.getAllByRole('button', {+ name: /Checking availability/,+ });+ expect(buttons).toHaveLength(4);+ expect(buttons.every((button) => button.hasAttribute('disabled'))).toBe(true);+});+it('offers retry when loading availability fails', () => {+ mocks.days.mockReturnValue(undefined);+ mocks.isError.mockReturnValue(true);+ render(() => <CopyAvailabilityDialog open onOpenChange={vi.fn()} />);++ expect(+ screen.getAllByRole('button', { name: /Could not check availability/ })+ ).toHaveLength(4);+ expect(screen.getByRole('alert').textContent).toContain(+ 'Could not load availability'+ );+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(mocks.retry).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/features/calendar/availability/CopyAvailabilityDialog.tsx b/apps/web/src/features/calendar/availability/CopyAvailabilityDialog.tsxnew file mode 100644index 0000000000..40f9d2da1c--- /dev/null+++ b/apps/web/src/features/calendar/availability/CopyAvailabilityDialog.tsx@@ -0,0 +1,300 @@+import { toast } from '@core/component/Toast/Toast';+import { writeClipboardData } from '@core/util/dataTransfer';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CheckIcon from '@phosphor/check.svg';+import CopyIcon from '@phosphor/copy.svg';+import SpinnerIcon from '@phosphor/spinner-gap.svg';+import XIcon from '@phosphor/x.svg';+import {+ ActionDialogShell,+ Button,+ cn,+ Dialog,+ type ManagedDialogProps,+ ToggleSwitch,+ Tooltip,+} from '@ui';+import { createSignal, For, onCleanup, Show } from 'solid-js';+import {+ AVAILABILITY_RANGE_OPTIONS,+ type AvailabilityRangeKey,+ formatAvailabilityText,+} from './availability';+import {+ getPersistedCalendarTimeFormat,+ useAvailabilitySettings,+} from './settings';+import { useAvailabilityRanges } from './use-availability-ranges';++interface TimeOption {+ value: string;+ label: string;+}++const timeLabelFormatter = new Intl.DateTimeFormat(undefined, {+ hour: 'numeric',+ minute: '2-digit',+});++/** Half-hour choices between two local hours (inclusive). */+function timeOptions(fromHour: number, toHour: number): TimeOption[] {+ const options: TimeOption[] = [];+ for (let minutes = fromHour * 60; minutes <= toHour * 60; minutes += 30) {+ const hour = Math.floor(minutes / 60);+ const minute = minutes % 60;+ options.push({+ value: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,+ label: timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute)),+ });+ }+ return options;+}++const START_TIME_OPTIONS = timeOptions(6, 12);+const END_TIME_OPTIONS = timeOptions(12, 22);++/** Managed availability settings and click-to-copy ranges. */+export function CopyAvailabilityDialog(props: ManagedDialogProps) {+ const [copying, setCopying] = createSignal<AvailabilityRangeKey>();+ const [copiedRange, setCopiedRange] = createSignal<AvailabilityRangeKey>();+ const { settings, setStartTime, setEndTime, setExcludeWeekends } =+ useAvailabilitySettings();+ const availability = useAvailabilityRanges(settings);+ let disposed = false;+ let resetCopied: ReturnType<typeof setTimeout> | undefined;+ onCleanup(() => {+ disposed = true;+ clearTimeout(resetCopied);+ });++ const copyRange = async (rangeKey: AvailabilityRangeKey) => {+ if (disposed || copying()) return;+ if (!availability.days()?.[rangeKey]?.length) return;+ clearTimeout(resetCopied);+ setCopiedRange(undefined);+ setCopying(rangeKey);+ try {+ let latest;+ try {+ latest = await availability.refreshRange(rangeKey);+ } catch {+ if (!disposed) toast.failure('Failed to load availability');+ return;+ }+ if (disposed) return;+ if (!latest) {+ toast.alert('Calendar is still syncing. Try again shortly.');+ return;+ }+ if (!latest.days.length) {+ toast.alert('No free time in that range');+ return;+ }++ try {+ const text = formatAvailabilityText(+ latest.days,+ getPersistedCalendarTimeFormat(),+ latest.now+ );+ const copied = await writeClipboardData({ 'text/plain': text });+ if (disposed) return;+ if (copied) {+ setCopiedRange(rangeKey);+ resetCopied = setTimeout(() => setCopiedRange(undefined), 2500);+ } else {+ toast.failure('Failed to copy availability');+ }+ } catch {+ if (!disposed) toast.failure('Failed to copy availability');+ }+ } finally {+ if (!disposed) setCopying(undefined);+ }+ };++ return (+ <Dialog+ open={props.open}+ onOpenChange={props.onOpenChange}+ position="center"+ class="w-150"+ >+ <ActionDialogShell>+ <ActionDialogShell.Body>+ <ActionDialogShell.Header class="flex items-start justify-between gap-3">+ <ActionDialogShell.Title>Copy availability</ActionDialogShell.Title>+ <Button+ variant="navigation"+ size="icon-sm"+ label="Close availability dialog"+ onClick={() => props.onOpenChange(false)}+ >+ <XIcon class="size-4" />+ </Button>+ </ActionDialogShell.Header>+ <section class="space-y-3">+ <h3 class="text-sm font-medium text-ink">Availability settings</h3>+ <div class="flex flex-wrap items-end gap-3">+ <label class="flex min-w-32 flex-1 flex-col gap-2 text-sm font-medium text-ink-muted">+ Start time+ <span class="relative block">+ <select+ class="settings-input w-full appearance-none pr-9 text-sm text-ink hover:border-edge-button hover:bg-hover"+ value={settings().startTime}+ onChange={(event) =>+ setStartTime(event.currentTarget.value)+ }+ >+ <For each={START_TIME_OPTIONS}>+ {(option) => (+ <option value={option.value}>{option.label}</option>+ )}+ </For>+ </select>+ <CaretDownIcon+ aria-hidden="true"+ class="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-ink-muted"+ />+ </span>+ </label>+ <label class="flex min-w-32 flex-1 flex-col gap-2 text-sm font-medium text-ink-muted">+ End time+ <span class="relative block">+ <select+ class="settings-input w-full appearance-none pr-9 text-sm text-ink hover:border-edge-button hover:bg-hover"+ value={settings().endTime}+ onChange={(event) => setEndTime(event.currentTarget.value)}+ >+ <For each={END_TIME_OPTIONS}>+ {(option) => (+ <option value={option.value}>{option.label}</option>+ )}+ </For>+ </select>+ <CaretDownIcon+ aria-hidden="true"+ class="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-ink-muted"+ />+ </span>+ </label>+ </div>+ <ToggleSwitch+ size="md"+ label="Exclude weekends"+ checked={settings().excludeWeekends}+ onChange={setExcludeWeekends}+ />+ </section>+ </ActionDialogShell.Body>+ <ActionDialogShell.Footer class="justify-start gap-2 py-5">+ <Show when={availability.isError()}>+ <div+ role="alert"+ class="flex w-full items-center justify-between gap-2 text-sm text-ink-muted"+ >+ Could not load availability.+ <Button variant="outline" size="sm" onClick={availability.retry}>+ Retry+ </Button>+ </div>+ </Show>+ <For each={AVAILABILITY_RANGE_OPTIONS}>+ {(option) => {+ const copied = () => copiedRange() === option.key;+ const unavailable = () =>+ availability.days()?.[option.key]?.length === 0;+ const disabled = () =>+ copying() !== undefined ||+ !availability.days()?.[option.key]?.length;+ const reason = () => {+ if (availability.isError())+ return 'Could not check availability';+ if (!availability.days()) return 'Checking availability…';+ if (unavailable()) return 'No free time in this range';+ return '';+ };+ const isCopying = () => copying() === option.key;+ return (+ <Tooltip+ as="span"+ class="min-w-32 flex-1 flex-col rounded-lg focus-visible:ring-2 focus-visible:ring-edge-focus"+ label={reason()}+ disabled={!reason()}+ tabIndex={unavailable() ? 0 : undefined}+ >+ <Button+ variant="outline"+ size="md"+ class={cn(+ 'w-full rounded-full px-2 disabled:cursor-not-allowed disabled:opacity-50',+ isCopying() &&+ 'data-disabled:opacity-100 disabled:opacity-100'+ )}+ aria-label={+ isCopying()+ ? `Copying availability for ${option.label}`+ : copied()+ ? `${option.label} availability copied`+ : `Copy availability for ${option.label}${reason() ? `: ${reason()}` : ''}`+ }+ aria-busy={isCopying()}+ disabled={disabled()}+ onClick={() => void copyRange(option.key)}+ >+ <span aria-hidden="true" class="grid place-items-center">+ <span+ class={cn(+ 'col-start-1 row-start-1 flex items-center justify-center gap-1.5 transition-opacity duration-200 motion-reduce:transition-none',+ isCopying() || copied() ? 'opacity-0' : 'opacity-100'+ )}+ >+ {option.label}+ <Show+ when={unavailable()}+ fallback={<CopyIcon class="size-4" />}+ >+ <XIcon class="size-4" />+ </Show>+ </span>+ <span+ class={cn(+ 'col-start-1 row-start-1 flex items-center justify-center gap-1.5 transition-opacity duration-200 motion-reduce:transition-none',+ isCopying() ? 'opacity-100' : 'opacity-0'+ )}+ >+ <SpinnerIcon+ class={cn(+ 'size-4 motion-reduce:animate-none',+ isCopying() && 'animate-spin'+ )}+ />+ Copying…+ </span>+ <span+ class={cn(+ 'col-start-1 row-start-1 flex items-center justify-center gap-1.5 transition-opacity duration-200 motion-reduce:transition-none',+ copied() && !isCopying() ? 'opacity-100' : 'opacity-0'+ )}+ >+ Copied+ <CheckIcon class="size-4 text-success" />+ </span>+ </span>+ </Button>+ </Tooltip>+ );+ }}+ </For>+ <span role="status" class="sr-only">+ {copying()+ ? 'Copying availability'+ : copiedRange()+ ? 'Availability copied'+ : ''}+ </span>+ </ActionDialogShell.Footer>+ </ActionDialogShell>+ </Dialog>+ );+}diff --git a/apps/web/src/features/calendar/availability/use-availability-ranges.test.tsx b/apps/web/src/features/calendar/availability/use-availability-ranges.test.tsxnew file mode 100644index 0000000000..44191e46b8--- /dev/null+++ b/apps/web/src/features/calendar/availability/use-availability-ranges.test.tsx@@ -0,0 +1,147 @@+/**+ * @vitest-environment jsdom+ */++import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';+import { CalendarSyncStatus } from '@service-storage/generated/schemas/calendarSyncStatus';+import { cleanup, render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import {+ type AvailabilitySettings,+ DEFAULT_AVAILABILITY_SETTINGS,+} from './availability';+import { useAvailabilityRanges } from './use-availability-ranges';++const mocks = vi.hoisted(() => ({+ queryInput: vi.fn(),+ data: vi.fn(),+ fetchQuery: vi.fn(),+}));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user-1' }));+vi.mock('@queries/client', () => ({+ queryClient: { fetchQuery: mocks.fetchQuery },+}));+vi.mock('@queries/calendar/occurrences', () => ({+ createCalendarOccurrenceQueryRange: (start: Date, end: Date) => ({+ start: start.toISOString(),+ end: end.toISOString(),+ }),+ fetchCalendarOccurrences: vi.fn(),+ useCalendarOccurrencesQuery: (input: () => unknown) => {+ mocks.queryInput(input());+ return {+ isSuccess: true,+ isPlaceholderData: false,+ isError: false,+ get data() {+ return mocks.data();+ },+ refetch: vi.fn(),+ };+ },+}));++const busyToday = {+ event: { status: 'confirmed', transparency: 'opaque', attendees: [] },+ occurrence: {+ isCancelled: false,+ time: {+ kind: 'timed',+ startsAt: new Date(2026, 7, 24, 9).toISOString(),+ endsAt: new Date(2026, 7, 24, 18).toISOString(),+ },+ },+} as unknown as CalendarOccurrenceItem;++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 7, 24, 10));+ mocks.data.mockReturnValue({+ items: [busyToday],+ syncStatus: CalendarSyncStatus.ready,+ });+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.clearAllMocks();+});++it('checks all ranges from one largest-range query and recomputes when settings change', () => {+ let changeSettings!: (value: AvailabilitySettings) => void;+ render(() => {+ const [settings, setSettings] = createSignal(DEFAULT_AVAILABILITY_SETTINGS);+ changeSettings = setSettings;+ const availability = useAvailabilityRanges(settings);+ return (+ <div>+ <span data-testid="today">{availability.days()?.today.length}</span>+ <span data-testid="week">{availability.days()?.thisWeek.length}</span>+ <span data-testid="seven">{availability.days()?.next7Days.length}</span>+ <span data-testid="fourteen">+ {availability.days()?.next14Days.length}+ </span>+ </div>+ );+ });++ expect(mocks.queryInput).toHaveBeenCalledOnce();+ expect(mocks.queryInput.mock.calls[0][0].range.end).toBe(+ new Date(2026, 8, 8).toISOString()+ );+ expect(screen.getByTestId('today').textContent).toBe('0');+ expect(screen.getByTestId('week').textContent).toBe('4');+ expect(screen.getByTestId('seven').textContent).toBe('5');+ expect(screen.getByTestId('fourteen').textContent).toBe('10');++ changeSettings({ ...DEFAULT_AVAILABILITY_SETTINGS, endTime: '19:00' });+ expect(screen.getByTestId('today').textContent).toBe('1');+ expect(mocks.queryInput).toHaveBeenCalledOnce();+});+it('refetches before copying and excludes slots that have passed since opening', async () => {+ vi.setSystemTime(new Date(2026, 7, 24, 10, 14, 59));+ mocks.data.mockReturnValue({+ items: [],+ syncStatus: CalendarSyncStatus.ready,+ });+ mocks.fetchQuery.mockResolvedValue({+ items: [],+ syncStatus: CalendarSyncStatus.ready,+ });+ let refreshRange!: ReturnType<typeof useAvailabilityRanges>['refreshRange'];+ render(() => {+ refreshRange = useAvailabilityRanges(+ () => DEFAULT_AVAILABILITY_SETTINGS+ ).refreshRange;+ return <div />;+ });++ vi.setSystemTime(new Date(2026, 7, 24, 10, 15, 2));+ const result = await refreshRange('today');+ expect(result?.days[0].slots[0].start).toEqual(new Date(2026, 7, 24, 10, 30));+ expect(mocks.fetchQuery).toHaveBeenCalledWith(+ expect.objectContaining({ staleTime: 0 })+ );+});++it('uses refreshed busy events instead of the initial snapshot', async () => {+ mocks.data.mockReturnValue({+ items: [],+ syncStatus: CalendarSyncStatus.ready,+ });+ mocks.fetchQuery.mockResolvedValue({+ items: [busyToday],+ syncStatus: CalendarSyncStatus.ready,+ });+ let refreshRange!: ReturnType<typeof useAvailabilityRanges>['refreshRange'];+ render(() => {+ refreshRange = useAvailabilityRanges(+ () => DEFAULT_AVAILABILITY_SETTINGS+ ).refreshRange;+ return <div />;+ });++ expect((await refreshRange('today'))?.days).toEqual([]);+ expect(mocks.fetchQuery).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/features/calendar/availability/use-availability-ranges.ts b/apps/web/src/features/calendar/availability/use-availability-ranges.tsnew file mode 100644index 0000000000..c5f21b8378--- /dev/null+++ b/apps/web/src/features/calendar/availability/use-availability-ranges.ts@@ -0,0 +1,96 @@+import { useUserId } from '@core/context/user';+import { calendarKeys } from '@queries/calendar/keys';+import {+ createCalendarOccurrenceQueryRange,+ fetchCalendarOccurrences,+ useCalendarOccurrencesQuery,+} from '@queries/calendar/occurrences';+import { queryClient } from '@queries/client';+import { CalendarSyncStatus } from '@service-storage/generated/schemas/calendarSyncStatus';+import { createMemo, createSignal, onCleanup, onMount } from 'solid-js';+import {+ AVAILABILITY_RANGE_OPTIONS,+ type AvailabilityDay,+ type AvailabilityRangeKey,+ type AvailabilitySettings,+ busyIntervalsFromOccurrences,+ computeAvailability,+ resolveAvailabilityWindow,+} from './availability';++/** Evaluates every copy range against the same occurrence snapshot and settings. */+export function useAvailabilityRanges(settings: () => AvailabilitySettings) {+ const userId = useUserId();+ const [now, setNow] = createSignal(new Date());+ const query = useCalendarOccurrencesQuery(() => {+ const window = resolveAvailabilityWindow('next14Days', now());+ return {+ userId: userId(),+ range: createCalendarOccurrenceQueryRange(+ window.start,+ window.endExclusive+ ),+ };+ });++ // Keep the remaining portion of today current while the dialog is open.+ // The query key changes at local midnight to cover the new last day.+ onMount(() => {+ const timer = setInterval(() => setNow(new Date()), 60_000);+ onCleanup(() => clearInterval(timer));+ });++ const days = createMemo(() => {+ const data =+ query.isSuccess && !query.isPlaceholderData ? query.data : undefined;+ if (!data || data.syncStatus === CalendarSyncStatus.syncing) return;++ const busyIntervals = busyIntervalsFromOccurrences(data.items);+ const currentSettings = settings();+ const currentTime = now();+ return Object.fromEntries(+ AVAILABILITY_RANGE_OPTIONS.map(({ key }) => [+ key,+ computeAvailability({+ rangeKey: key,+ settings: currentSettings,+ busyIntervals,+ now: currentTime,+ }),+ ])+ ) as Record<AvailabilityRangeKey, AvailabilityDay[]>;+ });++ const refreshRange = async (rangeKey: AvailabilityRangeKey) => {+ const window = resolveAvailabilityWindow('next14Days', new Date());+ const range = createCalendarOccurrenceQueryRange(+ window.start,+ window.endExclusive+ );+ // A copy must use current occurrences, even when the initial query's+ // 60-second cache window has not expired yet.+ const data = await queryClient.fetchQuery({+ queryKey: calendarKeys.occurrences(userId() ?? '', range).queryKey,+ queryFn: ({ signal }) => fetchCalendarOccurrences(range, signal),+ staleTime: 0,+ });+ if (data.syncStatus === CalendarSyncStatus.syncing) return;++ const currentTime = new Date();+ return {+ days: computeAvailability({+ rangeKey,+ settings: settings(),+ busyIntervals: busyIntervalsFromOccurrences(data.items),+ now: currentTime,+ }),+ now: currentTime,+ };+ };+ return {+ days,+ refreshRange,+ isError: () => query.isError,+ retry: () => void query.refetch(),+ };+}diff --git a/apps/web/src/features/calendar/availability/use-availability-text.ts b/apps/web/src/features/calendar/availability/use-availability-text.tsdeleted file mode 100644index 31ccb9d913..0000000000--- a/apps/web/src/features/calendar/availability/use-availability-text.ts+++ /dev/null@@ -1,60 +0,0 @@-/**- * Bridges the availability domain logic to calendar occurrence data. Shares- * the calendar's occurrence query cache, so repeat copies are instant and a- * freshly viewed range never refetches.- */--import { useUserId } from '@core/context/user';-import { calendarKeys } from '@queries/calendar/keys';-import {- createCalendarOccurrenceQueryRange,- fetchCalendarOccurrences,-} from '@queries/calendar/occurrences';-import { queryClient } from '@queries/client';-import {- type AvailabilityRangeKey,- busyIntervalsFromOccurrences,- computeAvailability,- formatAvailabilityText,- resolveAvailabilityWindow,-} from './availability';-import {- getPersistedCalendarTimeFormat,- useAvailabilitySettings,-} from './settings';--const AVAILABILITY_STALE_TIME = 60_000;--/**- * Returns an async provider mapping a share range to formatted availability- * text, or `undefined` when the range holds no free time.- */-export function useAvailabilityText() {- const userId = useUserId();- const { settings } = useAvailabilitySettings();-- return async (- rangeKey: AvailabilityRangeKey- ): Promise<string | undefined> => {- const now = new Date();- const window = resolveAvailabilityWindow(rangeKey, now);- const range = createCalendarOccurrenceQueryRange(- window.start,- window.endExclusive- );- const data = await queryClient.fetchQuery({- queryKey: calendarKeys.occurrences(userId() ?? '', range).queryKey,- queryFn: ({ signal }) => fetchCalendarOccurrences(range, signal),- staleTime: AVAILABILITY_STALE_TIME,- });-- const days = computeAvailability({- rangeKey,- settings: settings(),- busyIntervals: busyIntervalsFromOccurrences(data.items),- now,- });- if (days.length === 0) return undefined;- return formatAvailabilityText(days, getPersistedCalendarTimeFormat(), now);- };-}diff --git a/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx b/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsxindex 7d955aa307..a2e948e11b 100644--- a/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx+++ b/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx@@ -74,9 +74,10 @@ function createCalendarSettingsControls(isNarrow: () => boolean) {visible: boolean) => {calendarView.closeEventDetails();- for (const source of group.calendars) {- calendarView.setSourceVisibility(source.id, visible);- }+ calendarView.setSourcesVisibility(+ group.calendars.map((source) => source.id),+ visible+ );};const isAccountVisible = (group: CalendarAccountGroup) =>group.calendars.every((source) => calendarView.isSourceVisible(source.id));@@ -153,19 +154,24 @@ type CalendarSettingsControls = ReturnType<function DesktopCalendarSettings(props: {controls: CalendarSettingsControls;+ sidebar?: boolean;}) {const controls = props.controls;const calendarView = controls.calendarView;return (- <Dropdown placement="bottom-end">+ <Dropdown placement={props.sidebar ? 'top-end' : 'bottom-end'}><Dropdown.Triggervariant="ghost"- size="icon-sm"- class="shrink-0 rounded-lg"+ size={props.sidebar ? 'md' : 'icon-md'}+ class={+ props.sidebar+ ? 'w-full rounded-full border-transparent bg-transparent'+ : 'shrink-0 rounded-full border-transparent bg-transparent'+ }aria-label="Calendar settings">- <GearIcon class="size-3.5" />+ <GearIcon class="size-5" /></Dropdown.Trigger><Dropdown.Content class="w-60 max-w-[calc(100vw-1rem)]"><Show when={controls.showCalendarVisibility()}>@@ -315,7 +321,10 @@ function DesktopCalendarSettings(props: {);}-function MobileCalendarSettings(props: { controls: CalendarSettingsControls }) {+function MobileCalendarSettings(props: {+ controls: CalendarSettingsControls;+ sidebar?: boolean;+}) {const controls = props.controls;const calendarView = controls.calendarView;const [open, setOpen] = createSignal(false);@@ -331,8 +340,8 @@ function MobileCalendarSettings(props: { controls: CalendarSettingsControls }) {<MobileDrawer.Triggeras={Button}variant="ghost"- size="icon-sm"- class="shrink-0 rounded-full"+ size={props.sidebar ? 'md' : 'icon-lg'}+ class={props.sidebar ? 'w-full rounded-full' : 'shrink-0 rounded-full'}aria-label="Calendar settings"><GearIcon class="size-6" />@@ -513,7 +522,10 @@ function MobileCalendarSettings(props: { controls: CalendarSettingsControls }) {* Responsive calendar display settings menu. The turn-off confirmation lives* outside the menu so it survives the menu closing on select.*/-export function CalendarSettingsDropdown(props: { isNarrow?: boolean }) {+export function CalendarSettingsDropdown(props: {+ isNarrow?: boolean;+ sidebar?: boolean;+}) {const controls = createCalendarSettingsControls(() => props.isNarrow ?? false);@@ -522,9 +534,14 @@ export function CalendarSettingsDropdown(props: { isNarrow?: boolean }) {<><Showwhen={isMobile()}- fallback={<DesktopCalendarSettings controls={controls} />}+ fallback={+ <DesktopCalendarSettings+ controls={controls}+ sidebar={props.sidebar}+ />+ }>- <MobileCalendarSettings controls={controls} />+ <MobileCalendarSettings controls={controls} sidebar={props.sidebar} /></Show><TurnOffCalendarDialogtarget={controls.turnOffTarget()}diff --git a/apps/web/src/features/calendar/components/CalendarViewContext.tsx b/apps/web/src/features/calendar/components/CalendarViewContext.tsxindex 1527bc0d5b..37cdbabf25 100644--- a/apps/web/src/features/calendar/components/CalendarViewContext.tsx+++ b/apps/web/src/features/calendar/components/CalendarViewContext.tsx@@ -104,7 +104,7 @@ export const [CalendarViewContextProvider, useCalendarView] =// Sources default to visible, so calendars discovered after a// preference was saved (or events whose calendar is still loading)// never silently disappear.- const hiddenSourceIds = createMemo(+ const hiddenSourceIds = createMemo<ReadonlySet<string>>(() => new Set(preferences.hiddenSourceIds));const isSourceVisible = (sourceId: string) =>@@ -169,14 +169,21 @@ export const [CalendarViewContextProvider, useCalendarView] =}};- const setSourceVisibility = (sourceId: string, visible: boolean) => {- setPreferences('hiddenSourceIds', (current) =>- visible- ? current.filter((id) => id !== sourceId)- : current.includes(sourceId)- ? current- : [...current, sourceId]- );+ const setSourcesVisibility = (+ sourceIds: readonly string[],+ visible: boolean+ ) => {+ const hidden = new Set(preferences.hiddenSourceIds);+ let changed = false;+ for (const sourceId of sourceIds) {+ if (visible) changed = hidden.delete(sourceId) || changed;+ else if (!hidden.has(sourceId)) {+ hidden.add(sourceId);+ changed = true;+ }+ }+ if (!changed) return;+ setPreferences('hiddenSourceIds', [...hidden]);const selected = selection.event();if (@@ -187,13 +194,17 @@ export const [CalendarViewContextProvider, useCalendarView] =closeEventDetails();}};+ const setSourceVisibility = (sourceId: string, visible: boolean) =>+ setSourcesVisibility([sourceId], visible);return {displaySettings,sources,sourceById,+ hiddenSourceIds,isSourceVisible,setSourceVisibility,+ setSourcesVisibility,selectedEvent: selection.event,selectedEventAnchor: selection.anchor,setPeriodView: (periodView: CalendarPeriodView) => {diff --git a/apps/web/src/features/calendar/components/MonthDrawer.tsx b/apps/web/src/features/calendar/components/MonthDrawer.tsxindex a7862c9247..73e8447fd0 100644--- a/apps/web/src/features/calendar/components/MonthDrawer.tsx+++ b/apps/web/src/features/calendar/components/MonthDrawer.tsx@@ -34,7 +34,7 @@ export function MonthDrawer(props: MonthDrawerProps) {<MobileDrawer.Triggeras={Button}aria-label="Choose month"- class="max-w-full min-w-0 justify-start gap-1 rounded-full border-none bg-transparent px-1 text-base font-semibold text-ink not-touch:hover:bg-hover"+ class="max-w-full min-w-0 shrink justify-start gap-1 rounded-full border-none bg-transparent px-1 text-base font-semibold text-ink not-touch:hover:bg-hover"><span class="min-w-0 truncate">{formatCalendarMonth(props.month)}</span><CaretDownIcon class="size-3 shrink-0 text-ink-muted" />diff --git a/apps/web/src/features/calendar/components/PeriodSelector.tsx b/apps/web/src/features/calendar/components/PeriodSelector.tsxindex de2b33ce47..e21ce12c7c 100644--- a/apps/web/src/features/calendar/components/PeriodSelector.tsx+++ b/apps/web/src/features/calendar/components/PeriodSelector.tsx@@ -145,14 +145,14 @@ export function PeriodSelector(props: { isNarrow?: boolean }) {placement="bottom-end"><Dropdown.Trigger- depth={2}aria-label="Choose calendar view"- size="sm"- class="shrink-0 gap-1 rounded-lg border-edge-muted text-xs font-medium text-ink"+ variant="ghost"+ size="lg"+ class="shrink-0 rounded-full border-transparent bg-transparent text-sm">{CALENDAR_VIEWS.find((view) => view.value === controls.activeView())?.label ?? 'Week'}- <CaretDownIcon class="size-3 text-ink-muted" />+ <CaretDownIcon class="size-4 text-ink-muted" /></Dropdown.Trigger><Dropdown.Content class="min-w-36"><Dropdown.Group>diff --git a/apps/web/src/features/calendar/components/SourceControls.test.tsx b/apps/web/src/features/calendar/components/SourceControls.test.tsxindex 63329fdc0e..0e2665b9bb 100644--- a/apps/web/src/features/calendar/components/SourceControls.test.tsx+++ b/apps/web/src/features/calendar/components/SourceControls.test.tsx@@ -2,9 +2,9 @@* @vitest-environment jsdom*/-import { fireEvent, render, within } from '@solidjs/testing-library';+import { cleanup, fireEvent, render, within } from '@solidjs/testing-library';import { createSignal } from 'solid-js';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { CalendarSource } from '../types';import { SourceControls } from './SourceControls';@@ -36,36 +36,68 @@ const SOURCES: CalendarSource[] = [},];+beforeEach(() => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});function renderControls() {const onVisibilityChange = vi.fn<(id: string, visible: boolean) => void>();+ const onGroupVisibilityChange =+ vi.fn<(ids: string[], visible: boolean) => void>();const [hidden, setHidden] = createSignal<ReadonlySet<string>>(new Set());+ const changeVisibility = (ids: readonly string[], visible: boolean) =>+ setHidden((current) => {+ const next = new Set(current);+ for (const id of ids) {+ if (visible) next.delete(id);+ else next.add(id);+ }+ return next;+ });const result = render(() => (<SourceControlssources={SOURCES}isVisible={(id) => !hidden().has(id)}onVisibilityChange={(id, visible) => {onVisibilityChange(id, visible);- setHidden((current) => {- const next = new Set(current);- if (visible) next.delete(id);- else next.add(id);- return next;- });+ changeVisibility([id], visible);+ }}+ onGroupVisibilityChange={(ids, visible) => {+ onGroupVisibilityChange(ids, visible);+ changeVisibility(ids, visible);}}/>));const expandAccount = (email: string) =>fireEvent.click(result.getByRole('button', { name: `Expand ${email}` }));const headerFor = (email: string) => {- // Works whether the group is currently collapsed or expanded.+ // Resolve the row from the account, not the disclosure button's wrappers.const caret =result.queryByRole('button', { name: `Collapse ${email}` }) ??result.getByRole('button', { name: `Expand ${email}` });- const header = caret.parentElement;- if (!header) throw new Error(`missing header for ${email}`);+ const header = caret.closest('li')?.firstElementChild;+ if (!(header instanceof HTMLElement)) {+ throw new Error(`missing header for ${email}`);+ }return header;};- return { ...result, onVisibilityChange, headerFor, expandAccount };+ return {+ ...result,+ onVisibilityChange,+ onGroupVisibilityChange,+ headerFor,+ expandAccount,+ };}describe('SourceControls', () => {@@ -79,6 +111,47 @@ describe('SourceControls', () => {expect(queryByText('Holidays in United States')).toBeNull();});+ it('shows the primary calendar color on the collapsed account header', () => {+ const { headerFor } = renderControls();+ const swatch = headerFor('[email protected]').querySelector<HTMLElement>(+ '[aria-hidden="true"][style]'+ );+ expect(swatch?.style.backgroundColor).toBe('rgb(255, 0, 0)');+ });++ it('places checkboxes before labels and keeps expansion separate from visibility', () => {+ const {+ expandAccount,+ getByRole,+ getByText,+ headerFor,+ onVisibilityChange,+ } = renderControls();+ const header = headerFor('[email protected]');+ const headerCheckbox = header.querySelector('input[type="checkbox"]');+ const headerText = header.querySelector('.truncate');+ expect(+ headerCheckbox &&+ headerText &&+ headerCheckbox.compareDocumentPosition(headerText) &+ Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy();+ const disclosure = getByRole('button', { name: 'Expand [email protected]' });+ expect(disclosure.getAttribute('aria-expanded')).toBe('false');+ expandAccount('[email protected]');+ expect(+ getByRole('button', { name: 'Collapse [email protected]' }).getAttribute(+ 'aria-expanded'+ )+ ).toBe('true');+ expect(onVisibilityChange).not.toHaveBeenCalled();+ const child = getByRole('checkbox', { name: /Holidays in United States/ });+ const childText = getByText('Holidays in United States');+ expect(+ child.compareDocumentPosition(childText) &+ Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy();+ });it('reveals an account calendars once expanded', () => {const { expandAccount, getByText } = renderControls();expandAccount('[email protected]');@@ -92,14 +165,17 @@ describe('SourceControls', () => {expect(onVisibilityChange).toHaveBeenCalledWith('gab-holidays', false);});- it('toggles every calendar in an account from its header checkbox', () => {- const { headerFor, onVisibilityChange } = renderControls();- // The header checkbox works while the group is still folded.+ it('toggles an account in one visibility update from its header checkbox', () => {+ const { headerFor, onVisibilityChange, onGroupVisibilityChange } =+ renderControls();fireEvent.click(within(headerFor('[email protected]')).getByText('[email protected]'));- expect(onVisibilityChange).toHaveBeenCalledWith('gab-primary', false);- expect(onVisibilityChange).toHaveBeenCalledWith('gab-holidays', false);+ expect(onGroupVisibilityChange).toHaveBeenCalledExactlyOnceWith(+ ['gab-primary', 'gab-holidays'],+ false+ );+ expect(onVisibilityChange).not.toHaveBeenCalled();});it('marks a subscription calendar with an indicator', () => {diff --git a/apps/web/src/features/calendar/components/SourceControls.tsx b/apps/web/src/features/calendar/components/SourceControls.tsxindex 7c26d6b0ce..eb7a18d31a 100644--- a/apps/web/src/features/calendar/components/SourceControls.tsx+++ b/apps/web/src/features/calendar/components/SourceControls.tsx@@ -1,4 +1,5 @@-import CaretRightIcon from '@phosphor/caret-right.svg';+import { ViewSidebar } from '@app/components/view-shell';+import CaretDownIcon from '@phosphor/caret-down.svg';import RssIcon from '@phosphor/rss.svg';import WarningIcon from '@phosphor/warning.svg';import { Checkbox } from '@ui';@@ -10,6 +11,7 @@ interface SourceControlsProps {sources: CalendarSource[];isVisible: (sourceId: string) => boolean;onVisibilityChange: (sourceId: string, visible: boolean) => void;+ onGroupVisibilityChange: (sourceIds: string[], visible: boolean) => void;}/**@@ -33,7 +35,7 @@ export function SourceControls(props: SourceControlsProps) {});return (- <div class="flex flex-col gap-0.5">+ <ul class="flex min-w-0 flex-col gap-(--sidebar-row-gap)"><For each={groups()}>{(group) => {const visibleCount = () =>@@ -42,97 +44,107 @@ export function SourceControls(props: SourceControlsProps) {const allVisible = () => visibleCount() === group.calendars.length;const someVisible = () => visibleCount() > 0 && !allVisible();const expanded = () => expandedKeys().has(group.key);- const setGroupVisible = (visible: boolean) => {- for (const calendar of group.calendars) {- props.onVisibilityChange(calendar.id, visible);- }- };+ const setGroupVisible = (visible: boolean) =>+ props.onGroupVisibilityChange(+ group.calendars.map((calendar) => calendar.id),+ visible+ );return (- <div class="flex flex-col">- <div class="flex w-full items-center rounded-lg pr-2 text-xs text-ink hover:bg-hover">- <button- type="button"- class="flex shrink-0 items-center justify-center rounded-md p-1 text-ink-muted hover:text-ink"- aria-label={- expanded()- ? `Collapse ${group.emailAddress}`- : `Expand ${group.emailAddress}`- }- aria-expanded={expanded()}- onClick={() => toggleExpanded(group.key)}- >- <CaretRightIcon- class="size-3 transition-transform duration-90"- classList={{ 'rotate-90': expanded() }}- />- </button>+ <li class="min-w-0">+ <div class="relative min-w-0"><Checkboxchecked={allVisible()}indeterminate={someVisible()}onChange={setGroupVisible}- class="flex min-w-0 flex-1 items-center py-1.5"+ class="flex h-(--sidebar-row-height) w-full min-w-0 gap-3 rounded-lg px-(--sidebar-item-inset) pr-9 text-sm text-ink-muted hover:bg-hover hover:text-ink touch:h-11">- <Checkbox.Label class="min-w-0 flex-1 truncate font-medium">- {group.emailAddress}+ <Checkbox.Control class="size-3.5 [&_svg]:size-2.5" />+ <Checkbox.Label class="flex min-w-0 flex-1 items-center gap-2 font-medium">+ <span+ aria-hidden="true"+ class="size-2.5 shrink-0 rounded-sm"+ style={{+ 'background-color': (+ group.calendars.find(+ (calendar) => calendar.isPrimary+ ) ?? group.calendars[0]+ )?.color,+ }}+ />+ <span class="min-w-0 flex-1 truncate">+ {group.emailAddress}+ </span></Checkbox.Label>- <Checkbox.Control /></Checkbox>+ <span class="absolute right-(--sidebar-action-inset) top-1/2 flex -translate-y-1/2">+ <ViewSidebar.Control+ label={`${expanded() ? 'Collapse' : 'Expand'} ${group.emailAddress}`}+ aria-expanded={expanded()}+ onClick={() => toggleExpanded(group.key)}+ >+ <CaretDownIcon+ class="size-3 -rotate-90 transition-transform"+ classList={{ 'rotate-0': expanded() }}+ />+ </ViewSidebar.Control>+ </span></div>-- <Show when={expanded()}>- <For each={group.calendars}>- {(source) => (- <Checkbox- checked={props.isVisible(source.id)}- onChange={(checked) =>- props.onVisibilityChange(source.id, checked)- }- class="flex w-full items-center rounded-lg py-1.5 pr-2 pl-7 text-xs text-ink hover:bg-hover"- >- <Checkbox.Label class="flex min-w-0 flex-1 items-center gap-2">- <span- aria-hidden="true"- class="size-2.5 shrink-0 rounded-sm"- style={{ 'background-color': source.color }}- />- <span class="min-w-0 flex-1 truncate">- {source.name}- </span>- <Show when={source.syncError}>- {(error) => (+ <ViewSidebar.Branch open={expanded()}>+ <div class="flex min-w-0 flex-col gap-(--sidebar-row-gap)">+ <For each={group.calendars}>+ {(source) => (+ <Checkbox+ checked={props.isVisible(source.id)}+ onChange={(checked) =>+ props.onVisibilityChange(source.id, checked)+ }+ class="flex h-(--sidebar-row-height) w-full min-w-0 gap-3 rounded-lg px-(--sidebar-item-inset) text-sm text-ink-muted hover:bg-hover hover:text-ink touch:h-11"+ >+ <Checkbox.Control class="size-3.5 [&_svg]:size-2.5" />+ <Checkbox.Label class="flex min-w-0 flex-1 items-center gap-2">+ <span+ aria-hidden="true"+ class="size-2.5 shrink-0 rounded-sm"+ style={{ 'background-color': source.color }}+ />+ <span class="min-w-0 flex-1 truncate">+ {source.name}+ </span>+ <Show when={source.syncError}>+ {(error) => (+ <span+ title={`Sync failed: ${error()}`}+ class="flex shrink-0 text-alert-ink"+ >+ <WarningIcon+ class="size-3"+ aria-label={`Sync failed: ${error()}`}+ />+ </span>+ )}+ </Show>+ <Show when={source.isSubscription}><span- title={`Sync failed: ${error()}`}- class="flex shrink-0 text-alert-ink"+ title="Subscription calendar"+ class="flex shrink-0 text-ink-muted">- <WarningIcon+ <RssIconclass="size-3"- aria-label={`Sync failed: ${error()}`}+ aria-label="Subscription calendar"/></span>- )}- </Show>- <Show when={source.isSubscription}>- <span- title="Subscription calendar"- class="flex shrink-0 text-ink-muted"- >- <RssIcon- class="size-3"- aria-label="Subscription calendar"- />- </span>- </Show>- </Checkbox.Label>- <Checkbox.Control />- </Checkbox>- )}- </For>- </Show>- </div>+ </Show>+ </Checkbox.Label>+ </Checkbox>+ )}+ </For>+ </div>+ </ViewSidebar.Branch>+ </li>);}}</For>- </div>+ </ul>);}diff --git a/apps/web/src/features/calendar/hooks/use-team-ooo.ts b/apps/web/src/features/calendar/hooks/use-team-ooo.tsindex 63491dde5f..e9ac40337c 100644--- a/apps/web/src/features/calendar/hooks/use-team-ooo.ts+++ b/apps/web/src/features/calendar/hooks/use-team-ooo.ts@@ -124,6 +124,8 @@ export function useTeamOooEvents(export interface TeamOooWindow {ownerId: string;eventId: string;+ /** Read-only event model used to open the shared event details surface. */+ event: CalendarEvent;occurrenceKey: string;/** Teammate display name, resolved reactively from the shared cache. */name: string;@@ -171,6 +173,7 @@ export function useUpcomingTeamOoo(): UpcomingTeamOoo {eventId: item.eventId,occurrenceKey: item.occurrenceKey,name: getDisplayName(tryMacroId(item.ownerId)),+ event: mapTeamOooItem(item),title: item.title ?? undefined,start,end,diff --git a/apps/web/src/features/calendar/utils/macro-call-link.test.ts b/apps/web/src/features/calendar/utils/macro-call-link.test.tsindex 11e5321230..64c5b47d57 100644--- a/apps/web/src/features/calendar/utils/macro-call-link.test.ts+++ b/apps/web/src/features/calendar/utils/macro-call-link.test.ts@@ -93,6 +93,31 @@ describe('Macro calendar call links', () => {});});+ it('hides a generated invitation with tracking parameters in its displayed URL', () => {+ const trackedUrl = `${URL}?join=true&source=calendar`;+ expect(+ removeCalendarMacroCall(+ {+ description: `<p>Agenda</p><p>Join Macro call: <a href="${trackedUrl}">${trackedUrl}</a></p>`,+ location: 'Room 2',+ },+ URL+ )+ ).toEqual({ description: '<p>Agenda</p>', location: 'Room 2' });+ });++ it('hides generated Macro invitations even when the series URL differs', () => {+ expect(+ removeCalendarMacroCall(+ {+ description: `<p>Join Macro call: <a href="${SETUP_URL}">${SETUP_URL}</a></p>`,+ location: 'Room 2',+ },+ URL+ ).description+ ).toBe('');+ });+it('preserves independently authored call links and other description content', () => {const content = {description: `<p>Related call: <a href="${URL}">prior discussion</a></p>`,diff --git a/apps/web/src/features/calendar/utils/macro-call-link.ts b/apps/web/src/features/calendar/utils/macro-call-link.tsindex 4da416a07d..5ad613285f 100644--- a/apps/web/src/features/calendar/utils/macro-call-link.ts+++ b/apps/web/src/features/calendar/utils/macro-call-link.ts@@ -66,13 +66,12 @@ export function removeCalendarMacroCall(.replace(/<[^>]+>/g, '').replace(/&/g, '&').trim();+ const linkedUrl = calendarMacroCallUrl({ description: paragraph });+ const textUrl = text.match(/^Join Macro call:\s*(\S+)$/i)?.[1];const generated =- text === `Join Macro call: ${existingUrl}` ||- text === 'Join Macro call';- return generated &&- calendarMacroCallUrl({ description: paragraph }) === existingUrl- ? ''- : paragraph;+ text === 'Join Macro call' ||+ (textUrl !== undefined && macroCallUrl(textUrl) === linkedUrl);+ return generated && linkedUrl ? '' : paragraph;}).trim(),diff --git a/apps/web/src/features/meetings/components/call-sidebar.tsx b/apps/web/src/features/meetings/components/call-sidebar.tsxindex c0e10f9eab..1d025c0e41 100644--- a/apps/web/src/features/meetings/components/call-sidebar.tsx+++ b/apps/web/src/features/meetings/components/call-sidebar.tsx@@ -1,5 +1,6 @@import PhoneIcon from '@phosphor/phone.svg';-import { Tooltip } from '@ui';+import { Key } from '@solid-primitives/keyed';+import { cn, Tooltip } from '@ui';import { For, Show } from 'solid-js';import type { ActiveQuickCall } from '../context/call-sidebar';import type { UpcomingCalendarEvent } from '../core/upcoming-calendar-events';@@ -24,6 +25,7 @@ export function CallSidebar(props: {upcomingLoading: boolean;activeError?: string;upcomingError?: string;+ selectedEventId?: string;when: (call: UpcomingCalendarEvent) => string;canJoin: (event: UpcomingCalendarEvent) => boolean;onOpenEvent: (event: UpcomingCalendarEvent, anchor: HTMLElement) => void;@@ -32,7 +34,7 @@ export function CallSidebar(props: {onRetryUpcoming: () => void;}) {return (- <div class="flex flex-col gap-1">+ <div class="flex min-w-0 flex-col gap-1 overflow-x-clip"><For each={props.active}>{(call) => (<button@@ -61,45 +63,66 @@ export function CallSidebar(props: {<CallListError message={error()} onRetry={props.onRetryActive} />)}</Show>- <For each={props.upcoming}>+ <Key each={props.upcoming} by="id">{(calendarEvent) => (- <div class="flex w-full items-center gap-2 rounded-lg px-2 py-2 hover:bg-hover">- <button- type="button"- class="flex min-w-0 flex-1 items-center gap-2 text-left focus-visible:bg-hover"- onClick={(event) =>- props.onOpenEvent(calendarEvent, event.currentTarget)- }- aria-label={`Open ${calendarEvent.title}`}- >- <Tooltip- as="span"- class="min-w-0 flex-1"- label={calendarEvent.title}+ <div+ class={cn(+ 'min-w-0 overflow-hidden rounded-lg',+ props.selectedEventId === calendarEvent().id+ ? 'bg-active'+ : 'hover:bg-hover'+ )}+ >+ <div class="flex w-full items-center gap-2 px-2 py-2">+ <button+ type="button"+ class="flex min-w-0 flex-1 items-center gap-2 text-left focus-visible:bg-hover"+ onClick={(event) =>+ props.onOpenEvent(calendarEvent(), event.currentTarget)+ }+ aria-label={`Open ${calendarEvent().title}`}+ aria-current={+ props.selectedEventId === calendarEvent().id+ ? 'true'+ : undefined+ }>- <span class="truncate text-xs text-ink">- {calendarEvent.title}- </span>- </Tooltip>- <span class="ml-auto shrink-0 text-[10px] tabular-nums text-ink-muted">- {props.when(calendarEvent)}- </span>- </button>- <Show when={props.canJoin(calendarEvent) && calendarEvent.url}>- {(url) => (- <button- type="button"- class="shrink-0 rounded-md bg-ink-muted/10 px-2 py-1 text-xs text-ink hover:bg-active"- aria-label={`Join ${calendarEvent.title}`}- onClick={() => props.onJoin(url())}+ <span+ aria-hidden="true"+ class="size-2.5 shrink-0 rounded-sm"+ style={{ 'background-color': calendarEvent().color }}+ />+ <Tooltip+ as="span"+ class="min-w-0 flex-1"+ label={calendarEvent().title}>- Join- </button>- )}- </Show>+ <span class="truncate text-xs text-ink">+ {calendarEvent().title}+ </span>+ </Tooltip>+ <span class="ml-auto shrink-0 text-xs tabular-nums text-ink-muted">+ {props.when(calendarEvent())}+ </span>+ </button>+ <Show+ when={props.canJoin(calendarEvent()) && calendarEvent().url}+ >+ {(url) => (+ <button+ type="button"+ class="shrink-0 rounded-md bg-ink-muted/10 px-2 py-1 text-xs text-ink hover:bg-active"+ aria-label={`Join ${calendarEvent().title}`}+ onClick={() => props.onJoin(url())}+ >+ Join+ </button>+ )}+ </Show>+ </div></div>)}- </For>+ </Key><Show when={props.upcomingLoading && props.upcoming.length === 0}><divrole="status"diff --git a/apps/web/src/features/meetings/core/upcoming-calendar-events.test.ts b/apps/web/src/features/meetings/core/upcoming-calendar-events.test.tsindex 91020e8af0..7046fc48c4 100644--- a/apps/web/src/features/meetings/core/upcoming-calendar-events.test.ts+++ b/apps/web/src/features/meetings/core/upcoming-calendar-events.test.ts@@ -10,6 +10,7 @@ const call = (hour: number): UpcomingCalendarEvent => ({eventId: 'recurring-event',occurrenceKey: `occurrence-${hour}`,title: 'Planning',+ color: 'var(--color-accent)',url: 'https://meet.google.com/one-room',start: `2026-09-23T${hour}:00:00Z`,end: `2026-09-23T${hour + 1}:00:00Z`,diff --git a/apps/web/src/features/meetings/core/upcoming-calendar-events.ts b/apps/web/src/features/meetings/core/upcoming-calendar-events.tsindex 07af67baf7..156c4f9752 100644--- a/apps/web/src/features/meetings/core/upcoming-calendar-events.ts+++ b/apps/web/src/features/meetings/core/upcoming-calendar-events.ts@@ -2,6 +2,7 @@export type UpcomingCalendarEvent = {id: string;title: string;+ color: string;url?: string;start: string;end: string;diff --git a/apps/web/src/features/meetings/queries/upcoming-calendar-events.test.ts b/apps/web/src/features/meetings/queries/upcoming-calendar-events.test.tsindex 6f6d672b90..395896859d 100644--- a/apps/web/src/features/meetings/queries/upcoming-calendar-events.test.ts+++ b/apps/web/src/features/meetings/queries/upcoming-calendar-events.test.ts@@ -116,6 +116,7 @@ describe('upcoming calendar events source', () => {expect(result.events().map((call) => call.title)).toEqual([1, 2, 3, 4, 5].map((day) => `event-${day}`));+ expect(result.events()[0].color).toBe(source.color);expect(list).toHaveBeenCalledTimes(1);expect(result.loading()).toBe(false);expect(result.findEvent(result.events()[0].id)).toEqual(diff --git a/apps/web/src/features/meetings/queries/upcoming-calendar-events.ts b/apps/web/src/features/meetings/queries/upcoming-calendar-events.tsindex d9c536fd09..4e506e27a8 100644--- a/apps/web/src/features/meetings/queries/upcoming-calendar-events.ts+++ b/apps/web/src/features/meetings/queries/upcoming-calendar-events.ts@@ -89,6 +89,7 @@ export function useUpcomingCalendarEventsSource(options: SourceOptions) {(event): UpcomingCalendarEvent => ({id: event.id,title: event.title,+ color: event.calendar.color,url:calendarMacroCallUrl(event) ??safeConferenceUrl(event.conferenceUrl),diff --git a/apps/web/src/features/meetings/views/call-sidebar.tsx b/apps/web/src/features/meetings/views/call-sidebar.tsxindex bc32055327..a1674268c8 100644--- a/apps/web/src/features/meetings/views/call-sidebar.tsx+++ b/apps/web/src/features/meetings/views/call-sidebar.tsx@@ -12,6 +12,7 @@ export function CallSidebar(props: {actions: CallSidebarActions;now: Accessor<Date>;when: (call: UpcomingCalendarEvent) => string;+ selectedEventId?: string;}) {return (<Content@@ -20,6 +21,7 @@ export function CallSidebar(props: {upcomingLoading={props.sources.upcoming.loading()}activeError={props.sources.active.error()}upcomingError={props.sources.upcoming.error()}+ selectedEventId={props.selectedEventId}canJoin={(event) =>Boolean(event.url) && isCalendarEventOngoing(event, props.now())}diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 1de9f35b8d..5537c432cf 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -400,6 +400,7 @@ export const ENABLE_CALLS = true;export const enableQuickCalls = defineFlag({key: 'enable-quick-calls',env: 'ENABLE_QUICK_CALLS',+ default: true,});// Email signatures: the settings editor, the compose / reply / AI-chat signaturediff --git a/apps/web/src/lib/design/empty-state-calendar-search.svg b/apps/web/src/lib/design/empty-state-calendar-search.svgnew file mode 100644index 0000000000..62194268e9--- /dev/null+++ b/apps/web/src/lib/design/empty-state-calendar-search.svg@@ -0,0 +1,28 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 52" width="100%" height="100%" fill="none" stroke="currentColor" stroke-width="0.7" stroke-linejoin="round" stroke-linecap="round">+ <style>+ .calendar-shadow { animation: calendar-fade .5s ease-out both }+ .calendar-tile { animation: calendar-drop .55s cubic-bezier(.25,.8,.4,1) both }+ .calendar-lens { animation: calendar-drop .55s .13s cubic-bezier(.25,.8,.4,1) both }+ @keyframes calendar-drop { from { opacity: 0; transform: translateY(-4px) } to { opacity: 1; transform: translateY(0) } }+ @keyframes calendar-fade { from { opacity: 0 } to { opacity: .5 } }+ @media (prefers-reduced-motion: reduce) { .calendar-shadow, .calendar-tile, .calendar-lens { animation: none } }+ </style>+ <path d="M5 30 32 44 59 30 32 16Z" opacity=".12" transform="translate(0 3)"/>+ <path class="calendar-shadow" d="M5 30 32 44 59 30 32 16Z" stroke-dasharray="2 2"/>+ <g class="calendar-tile">+ <path d="M11 20 32 9 53 20 53 26 32 37 11 26Z" fill="var(--color-surface)"/>+ <path d="M11 20 32 31 53 20 32 9Z" fill="var(--color-surface)"/>+ <path d="M11 20 32 31 32 37 11 26Z" fill="currentColor" fill-opacity=".045"/>+ <path d="M32 31 53 20 53 26 32 37Z" fill="currentColor" fill-opacity=".07"/>+ <path d="m18 20 14 7 14-7-14-7Z" stroke-opacity=".35"/>+ <path d="m22 18 14 7m-11-9 14 7m-14 7 14-7" stroke-opacity=".2"/>+ <circle cx="28" cy="21" r="1.3" fill="currentColor" fill-opacity=".45" stroke="none"/>+ <circle cx="35" cy="20" r="1.3" fill="currentColor" fill-opacity=".45" stroke="none"/>+ <path d="m18 16 14 7 14-7" stroke-opacity=".4"/>+ </g>+ <g class="calendar-lens">+ <circle cx="46" cy="10" r="5.5" fill="var(--color-surface)"/>+ <circle cx="46" cy="10" r="3.6" stroke-opacity=".6"/>+ <path d="m50.1 14.1 5 5" stroke-width="1.5"/>+ </g>+</svg>diff --git a/apps/web/src/lib/queries/calendar/keys.ts b/apps/web/src/lib/queries/calendar/keys.tsindex 1acab62b93..ca159977f4 100644--- a/apps/web/src/lib/queries/calendar/keys.ts+++ b/apps/web/src/lib/queries/calendar/keys.ts@@ -29,4 +29,7 @@ export const calendarKeys = createQueryKeys('calendar', {mentionPreview: (eventId: string, occurrenceKey: string | undefined) => ({queryKey: [eventId, occurrenceKey],}),+ searchPreviews: (+ items: readonly { eventId: string; occurrenceKey?: string | null }[]+ ) => ({ queryKey: [items] }),});diff --git a/apps/web/src/lib/queries/calendar/mention-preview.ts b/apps/web/src/lib/queries/calendar/mention-preview.tsindex befbb7b919..e425ba71aa 100644--- a/apps/web/src/lib/queries/calendar/mention-preview.ts+++ b/apps/web/src/lib/queries/calendar/mention-preview.ts@@ -3,6 +3,7 @@ import { previewKeys } from '@queries/preview/keys';import type { PreviewItem } from '@queries/preview/types';import { storageServiceClient } from '@service-storage/client';import type { CalendarMentionEvent } from '@service-storage/generated/schemas/calendarMentionEvent';+import type { CalendarMentionPreviewRequestItem } from '@service-storage/generated/schemas/calendarMentionPreviewRequestItem';import { useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import { calendarKeys } from './keys';@@ -36,6 +37,9 @@ export function invalidateCalendarEventPreviews(eventId?: string): void {},});}+ queryClient.invalidateQueries({+ queryKey: calendarKeys.searchPreviews._def,+ });queryClient.invalidateQueries({queryKey: eventId? [...calendarKeys.mentionPreview._def, eventId]@@ -106,3 +110,28 @@ export function useCalendarMentionPreviewQuery(};});}++/** Resolve search result locations in one request, scoped to each occurrence. */+export function useCalendarSearchPreviewsQuery(+ inputs: Accessor<CalendarMentionPreviewRequestItem[]>+) {+ return useQuery(() => {+ const items = inputs();+ return {+ queryKey: calendarKeys.searchPreviews(items).queryKey,+ queryFn: async () => {+ const result = await storageServiceClient.getBatchCalendarEventPreviews(+ {+ items,+ }+ );+ if (result.isErr()) {+ throw new Error('Failed to fetch calendar search previews');+ }+ return result.value.items;+ },+ enabled: items.length > 0,+ staleTime: MENTION_PREVIEW_STALE_TIME,+ };+ });+}diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 99a813e630..1fd22ab566 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2,9 +2,9 @@## Top bars-Right-aligned split-header actions (including Calendar's New event and Channel's-Call and Ask Macro) are borderless with a rounded-xl background on hover. Channel-header tabs use fully rounded tracks and selected pills.+Right-aligned split-header actions (including Calendar's touch/preview New event+and Channel's Call and Ask Macro) are borderless with a rounded-xl background on+hover. Channel header tabs use fully rounded tracks and selected pills.## User cards@@ -796,19 +796,85 @@ footer. Answering a recurring invitation opens a rounded glass sheet: choose`This event` or `All events`, then `Save response`. Cancel or Close returns tothe event details without sending a response.-The calendar header has matching `New event` and `New Call` buttons. Both stay-available in narrow splits and on phones, where compact icons have accessible-labels. `New Call` opens call setup; it is no longer in the right side panel.-Week view also has a `Choose calendar view` menu, prev/next week,-`Search events`, `Calendar settings`, and a mini month picker in the right side panel.-The mini calendar's month label opens a month picker; arrows also change months.-The right side panel has a collapsible `Upcoming events` box.+The standalone Calendar view has a left navigation sidebar. The `New` menu+above the mini calendar offers `Event`, feature-gated `Call`, and feature-gated+`Reminder`. An icon-only shortcut in the `Upcoming events` header opens the+availability dialog. Start/end time selectors and a weekend switch sit above+copy ranges that wrap on narrow screens. The dialog checks all ranges using one+calendar-occurrence query; ranges without free time are disabled, show an X+instead of the copy icon, and retain a reason tooltip that can receive keyboard+focus.+Copying rechecks the occurrences and current time, so changes since opening do+not enter the copied text. The option keeps its width while a left spinner and+`Copying…` crossfade to `Copied` with a green check icon; the button keeps its+neutral styling. Reduced-motion preferences skip the crossfade and spin.+Collapsible `Upcoming events` and `Calendars` sections follow; calendar+account rows use Drive-style trailing disclosure buttons and animated nested+branches. Their 14px visibility checkboxes precede the swatch and label, with+separate account and individual-calendar visibility controls. `Team out of office`+is feature-gated and lists teammates with 24px avatars; its section switch+toggles the entire grid overlay. Clicking a teammate's row navigates to that+date, opens read-only event details, and marks the row active. The icon-only+`Calendar settings` control fills the sidebar footer.+An account checkbox toggles its calendars together in one update. The checkbox+responds immediately; the upcoming list and each grid page refresh on deferred+tasks rather than re-rendering all pages during the click.+The sidebar can be resized or collapsed on desktop; in narrow desktop panes+it opens over the grid. Phones do not show the sidebar or its navigation drawer.+The mobile split header places a month selector and Today in its left island;+selecting the month opens the date-selection drawer. The right island keeps+full-sized Availability, Search, and Settings actions. The New menu+beside the bottom AI input offers Event, feature-gated Call, and feature-gated+Reminder. Inline Calendar previews retain their host's chrome without adding+another sidebar; their left header island has a compact New menu because the+bottom New action follows the foreground host view.++The in-view desktop Calendar header follows Drive's two-level layout: the slim+top bar shows the viewed month and year and, when the sidebar is closed, a+compact `New` menu. At wide widths, the row beneath puts `Search events` on+the left and a labeled `Today` button followed by the rounded period selector+and previous/next arrows on the right. The idle search field places its hotkey+beside the placeholder. A query reveals the icon-only Exact-match toggle at+wide widths; in narrow splits, Exact and Filters appear after focusing search.+The filter button stays before Clear. The filter menu opens below the button,+aligned to its right edge: Search in is single-select, while Status, Organizer,+and Attendee allow multiple values. Organizer and Attendee virtualize their+contact lists; selected contacts stay in place, while custom email addresses+appear first. Adding a valid email clears the contact search. Filter selections+apply immediately, and only these filters mark the filter button, not Exact+mode. Clicking search opens a calendar-search hint until at least three+characters are entered; searches show skeleton rows while loading. Empty+results show an illustrated empty state. Result titles show a calendar-color+swatch when the event is loaded in the visible range, falling back to the+default calendar color otherwise. A result shows its location after the+date/time when available. Each result offers at most one rounded Join action:+matching occurrence content takes precedence over series metadata. Macro links+use a neutral button, Google Meet uses a solid blue button in light mode and a+subtle blue button in dark mode, and other conference links use a neutral button.+All Join buttons use a camera icon. Generated Macro invitation paragraphs are+hidden from event descriptions. Google Meet URLs in an event's location or+description also supply Join actions. Recurring results wait for matching+occurrence details before showing Join. Selecting a result preserves the search+text. Availability lives in the desktop sidebar's Upcoming events section and+in the mobile header.++Resizing the split keeps the same search field mounted in the fixed-height+header row. At narrow widths the row hides `Today` and the period selector,+then the navigation arrows when space becomes scarce; focusing search also+hides the remaining controls to give the field room. Its clear button remains+available when a query is present. The `New` menu stays in the desktop top+bar. Touch devices keep the month selector and header controls without separate+create or call buttons in the right island. The desktop sidebar's mini+calendar remains navigable by date and month.+Active Quick Calls you created, participated in, or were invited to appear above yournext five events (including ones in progress), whether or not they have call links.-The active area is hidden when no calls are active. Event rows show the name and-time; click one to open its details. An event with a call link shows `Join` while-it is in progress. Upcoming events follow today's date even when you browse another week;-hidden calendars, cancelled events, and invitations you declined are omitted.+The active area is hidden when no calls are active. Upcoming event rows show a+calendar color swatch, the name, and the time; click one to open its details and+highlight the active row.+An event with a call link shows `Join` while it is in progress. Upcoming events+follow today's date even when you browse another week; hidden calendars,+cancelled events, and invitations you declined are omitted.`New Call` opens `/app/meet/new` without creating a meeting. The `Invite Teammates`button above `Start call` opens the task assignee picker with name search, profilepictures and multiple selections, without bots or external contacts. The closed@@ -853,7 +919,7 @@ Selecting `Macro call` on an owned editable event without one adds a call on savchoosing another option removes its generated Macro link from the invitation.Removing the link or deleting the calendar event does not revoke the reusable call.-The side panel's `Calendars` section folds each connected account into a collapsible+The sidebar's `Calendars` section folds each connected account into a collapsiblegroup: a caret plus the account address header with a checkbox that shows or hides all ofthat account's calendars at once, and the account's calendars listed beneath it (color dot,name, per-calendar checkbox). Accounts start collapsed. Subscribed system calendars@@ -892,7 +958,7 @@ guest but you — in a split beside the calendar on desktop, as the full-screentouch devices — and is hidden when you are the only guest.With the `enable-calendar-team-ooo` flag on, teammates' Google Calendar out-of-office events-overlay the grid as read-only chips titled `<name>: <event title>`. The side panel's+overlay the grid as read-only chips titled `<name>: <event title>`. The sidebar's`Team out of office` section (shown only when the user belongs to a team with other members)has a checkbox in its header row toggling the whole overlay on or off — all teammates ornone — and lists the next 90 days of teammate absences; clicking a row navigates the grid to