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: email inner sidebar (#6190)
Peter Chinman734523726c57
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex e50f049c53..dfebfc9428 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -4,6 +4,7 @@ import { ComposeAgentSession } from '@app/features/block-agent/component/Composeimport type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';import type { CalendarEvent } from '@app/features/calendar/types';import { ChannelsView } from '@app/features/channels-view/channels-view';+import { EmailView } from '@app/features/email-view/email-view';import { GettingStarted } from '@app/features/getting-started';import { Home } from '@app/features/home';import { InboxView } from '@app/features/inbox-view/inbox-view';@@ -393,21 +394,34 @@ registerComponent(}));-registerComponent(- 'mail',- withAuth(() => {- usePageViewTracking('mail');- const preset = getViewPreset('mail');- return (- <SoupView- viewName="Email"- initialFilters={preset?.filters}- initialClientFilters={preset?.clientFilters}- initialGroupBy={preset?.groupBy}- />- );- })-);+function LegacyMailView() {+ const preset = getViewPreset('mail');+ return (+ <SoupView+ viewName="Email"+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}+ initialGroupBy={preset?.groupBy}+ />+ );+}++function RegisteredMailView() {+ usePageViewTracking('mail');+ const newAppViews = useNewAppViews({+ enabledLayout: () => (isTouchDevice() ? 'legacy' : 'composable'),+ });++ return (+ <Show when={newAppViews.ready()} fallback={<LoadingBlock />}>+ <Show when={newAppViews.enabled()} fallback={<LegacyMailView />}>+ <EmailView />+ </Show>+ </Show>+ );+}++registerComponent('mail', withAuth(RegisteredMailView));registerComponent('documents',diff --git a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx b/apps/web/src/components/app/split-layout/components/SplitPanel.tsxindex a610625624..586313d94e 100644--- a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx@@ -18,7 +18,6 @@ import {createEffect,createMemo,createSignal,- on,onCleanup,onMount,Show,@@ -37,6 +36,7 @@ import type { SplitHandle, SplitState } from '../layoutManager';import { shouldShowSplitCloseButton } from '../layoutUtils';import { registerSplitHotkeys } from '../registerSplitHotkeys';import { createOwnedSlots } from '../utils/createOwnedSlots';+import { createSplitAutofocus } from '../utils/createSplitAutofocus';import { createPriorityCollapseController } from './PriorityCollapseOverflowSensor';import { SplitDrawerGroup } from './SplitDrawerContext';import { SplitHeader } from './SplitHeader';@@ -115,16 +115,10 @@ export function SplitPanel(props: SplitPanelProps) {initialPredicates: { and: ['explicit-noise'] },});- createEffect(- on([panelRef], () => {- if (isTouchDevice()) return;- // Only the active split may claim focus on mount. A Preview Pair's Viewer- // is created with activate:false while its controller stays active, and- // must not steal the keyboard from it.- if (!props.active) return;- panelRef()?.focus();- })- );+ createSplitAutofocus({+ element: panelRef,+ enabled: () => props.active && !isTouchDevice(),+ });const [toolbarRef, setToolbarRef] = createSignal<HTMLDivElement | null>(null);const [headerRef, setHeaderRef] = createSignal<HTMLDivElement | null>(null);@@ -363,85 +357,77 @@ export function SplitPanel(props: SplitPanelProps) {)}depth={isTouchDevice() ? 0 : 1}>- <Show- when={usesComposableLayout()}- fallback={- <>- <Panel.Header- class={cn(- 'relative block min-h-10.25 touch:min-h-11.25 p-0 overflow-visible border-b-0!',- 'z-split-panel-chrome',- // On mobile/tablet the header collapses to a zero-height grid row;- // SplitHeader overlays the body as floating islands.- 'touch:min-h-0 touch:border-b-0',- shouldHideSplitHeader() && 'hidden'- )}- >- <SplitHeader- ref={setHeaderRef}- collapseController={headerCollapseController}- />- </Panel.Header>-- <Panel.Toolbar- class={cn(- 'items-start overflow-visible',- !hasToolbarContent() && 'hidden',- isTouchDevice() && 'hidden',- 'border-b-0'- )}- >- <SplitToolbar- ref={setToolbarRef}- collapseController={toolbarCollapseController}- />- </Panel.Toolbar>+ <Show when={!usesComposableLayout()}>+ <Panel.Header+ class={cn(+ 'relative block min-h-10.25 touch:min-h-11.25 p-0 overflow-visible border-b-0!',+ 'z-split-panel-chrome',+ // On mobile/tablet the header collapses to a zero-height grid row;+ // SplitHeader overlays the body as floating islands.+ 'touch:min-h-0 touch:border-b-0',+ shouldHideSplitHeader() && 'hidden'+ )}+ >+ <SplitHeader+ ref={setHeaderRef}+ collapseController={headerCollapseController}+ />+ </Panel.Header>- <Panel.Body>- <div class="@container/split size-full min-h-0 overflow-hidden relative flex flex-col">- <div- class={cn(- 'min-h-0 min-w-0 overflow-hidden relative',- bottomPanel() ? 'h-1/2' : 'h-full'- )}- >- <MountedContent />+ <Panel.Toolbar+ class={cn(+ 'items-start overflow-visible',+ !hasToolbarContent() && 'hidden',+ isTouchDevice() && 'hidden',+ 'border-b-0'+ )}+ >+ <SplitToolbar+ ref={setToolbarRef}+ collapseController={toolbarCollapseController}+ />+ </Panel.Toolbar>+ </Show>+ {/* Changing chrome must preserve the mounted view and its split-owned resources. */}+ <Panel.Body>+ <div class="@container/split size-full min-h-0 overflow-hidden relative flex flex-col">+ <div+ class={cn(+ 'min-h-0 min-w-0 overflow-hidden relative',+ !usesComposableLayout() && bottomPanel()+ ? 'h-1/2'+ : 'h-full'+ )}+ >+ <MountedContent />+ </div>+ <Show when={!usesComposableLayout() && bottomPanel()}>+ {(panel) => (+ <div class="h-1/2 min-h-0 min-w-0 border-t border-edge-muted bg-surface flex flex-col">+ <div class="flex h-10 shrink-0 items-center gap-2 border-b border-edge-muted px-2">+ <h3 class="min-w-0 flex-1 truncate text-sm font-medium text-ink-muted">+ {panel().title}+ </h3>+ <Button+ variant="ghost"+ size="icon-sm"+ label="Close"+ onClick={() => panel().onClose?.()}+ >+ <CloseIcon />+ </Button>+ </div>+ <div class="min-h-0 flex-1 overflow-hidden">+ {panel().content()}</div>- <Show when={bottomPanel()}>- {(panel) => (- <div class="h-1/2 min-h-0 min-w-0 border-t border-edge-muted bg-surface flex flex-col">- <div class="flex h-10 shrink-0 items-center gap-2 border-b border-edge-muted px-2">- <h3 class="min-w-0 flex-1 truncate text-sm font-medium text-ink-muted">- {panel().title}- </h3>- <Button- variant="ghost"- size="icon-sm"- label="Close"- onClick={() => panel().onClose?.()}- >- <CloseIcon />- </Button>- </div>- <div class="min-h-0 flex-1 overflow-hidden">- {panel().content()}- </div>- </div>- )}- </Show></div>- <MobileTopEdgeFade />- </Panel.Body>- </>- }- >- <div- class="size-full min-h-0 min-w-0 overflow-hidden"- style={{ 'grid-area': '1 / 1 / -1 / -1' }}- >- <MountedContent />+ )}+ </Show></div>- </Show>+ <Show when={!usesComposableLayout()}>+ <MobileTopEdgeFade />+ </Show>+ </Panel.Body></Panel></div></SplitDrawerGroup>diff --git a/apps/web/src/components/app/split-layout/tests/createSplitAutofocus.test.tsx b/apps/web/src/components/app/split-layout/tests/createSplitAutofocus.test.tsxnew file mode 100644index 0000000000..30ee18b3ea--- /dev/null+++ b/apps/web/src/components/app/split-layout/tests/createSplitAutofocus.test.tsx@@ -0,0 +1,220 @@+import {+ attachGlobalDOMScope,+ registerHotkey,+ useHotKeyRoot,+ useHotkeyDOMScope,+} from '@core/hotkey/hotkeys';+import { activeScope, setActiveScope } from '@core/hotkey/state';+import { cleanup, fireEvent, render, waitFor } from '@solidjs/testing-library';+import {+ QueryClient,+ QueryClientProvider,+ useQuery,+} from '@tanstack/solid-query';+import {+ createMemo,+ createRoot,+ createSignal,+ onCleanup,+ Suspense,+} from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createSplitAutofocus } from '../utils/createSplitAutofocus';++vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));++const disposers: (() => void)[] = [];++afterEach(() => {+ cleanup();+ for (const dispose of disposers.splice(0)) dispose();+ document.body.replaceChildren();+ setActiveScope('global');+});++function setup(connected = false, enabled = true) {+ const shell = document.createElement('div');+ shell.tabIndex = -1;+ if (connected) document.body.appendChild(shell);+ const root = createRoot((dispose) => {+ disposers.push(dispose);+ const [isEnabled, setEnabled] = createSignal(enabled);+ createSplitAutofocus({ element: () => shell, enabled: isEnabled });+ return { dispose, setEnabled };+ });+ return { shell, ...root };+}++describe('split shell autofocus', () => {+ it('focuses an attached shell once and preserves later user focus', async () => {+ const { shell } = setup(true);+ await Promise.resolve();+ expect(document.activeElement).toBe(shell);++ const button = document.createElement('button');+ document.body.appendChild(button);+ button.focus();+ document.body.appendChild(document.createElement('div'));+ await Promise.resolve();+ expect(document.activeElement).toBe(button);+ });++ it('waits for a detached shell to attach', async () => {+ const { shell } = setup();+ await Promise.resolve();+ expect(document.activeElement).toBe(document.body);++ document.body.appendChild(shell);+ await Promise.resolve();+ expect(document.activeElement).toBe(shell);+ });++ it.each(['input', 'button', 'div'] as const)(+ 'preserves a focused %s when the shell attaches',+ async (tag) => {+ const { shell } = setup();+ await Promise.resolve();+ const other = document.createElement(tag);+ other.tabIndex = 0;+ document.body.appendChild(other);+ other.focus();++ document.body.appendChild(shell);+ await Promise.resolve();+ expect(document.activeElement).toBe(other);+ }+ );++ it('preserves focus already inside the split', async () => {+ const { shell } = setup();+ const input = document.createElement('input');+ shell.appendChild(input);+ await Promise.resolve();+ document.body.appendChild(shell);+ input.focus();+ await Promise.resolve();+ expect(document.activeElement).toBe(input);+ });++ it('does not autofocus an inactive split when it is later activated', async () => {+ const { shell, setEnabled } = setup(true, false);+ await Promise.resolve();+ setEnabled(true);+ await Promise.resolve();+ expect(document.activeElement).toBe(document.body);+ expect(shell.isConnected).toBe(true);+ });++ it('rechecks activation before focusing a late attachment', async () => {+ const { shell, setEnabled } = setup();+ await Promise.resolve();+ setEnabled(false);+ document.body.appendChild(shell);+ await Promise.resolve();+ expect(document.activeElement).toBe(document.body);+ });++ it.each([false, true])(+ 'cancels on disposal with observer started=%s',+ async (started) => {+ const { shell, dispose } = setup();+ if (started) await Promise.resolve();+ dispose();+ document.body.appendChild(shell);+ await Promise.resolve();+ expect(document.activeElement).toBe(document.body);+ }+ );++ it('activates the split hotkey scope after an outer cold query attaches it', async () => {+ let resolveQuery!: (data: string[]) => void;+ const pendingQuery = new Promise<string[]>((resolve) => {+ resolveQuery = resolve;+ });+ const client = new QueryClient();+ const down = vi.fn();+ const up = vi.fn();+ let scopeId!: string;+ let shell!: HTMLDivElement;++ function Split() {+ const [attachHotkeys, scope] = useHotkeyDOMScope('fresh-load');+ scopeId = scope;+ const [element, setElement] = createSignal<HTMLDivElement | null>(null);+ createSplitAutofocus({ element, enabled: () => true });+ for (const [hotkey, handler] of [+ ['j', down],+ ['k', up],+ ] as const) {+ const hotkeyRegistration = registerHotkey({+ scopeId: scope,+ hotkey,+ description: 'Navigate list',+ keyDownHandler: () => {+ handler();+ return true;+ },+ });+ onCleanup(hotkeyRegistration.dispose);+ }+ return (+ <div+ ref={(el) => {+ shell = el;+ setElement(el);+ attachHotkeys(el);+ }}+ tabIndex={-1}+ >+ <Suspense>+ <div role="grid" aria-label="Email" tabIndex={0} />+ </Suspense>+ </div>+ );+ }++ function LoadingShell() {+ const query = useQuery(() => ({+ queryKey: ['cold-shell'],+ queryFn: () => pendingQuery,+ }));+ createMemo(() => query.data);+ return (+ <Suspense>+ <Split />+ </Suspense>+ );+ }++ function App() {+ useHotKeyRoot();+ return (+ <div ref={attachGlobalDOMScope}>+ <QueryClientProvider client={client}>+ <Suspense fallback={<div>Loading</div>}>+ <LoadingShell />+ </Suspense>+ </QueryClientProvider>+ </div>+ );+ }++ const view = render(() => <App />);+ await Promise.resolve();+ expect(shell.isConnected).toBe(false);+ expect(activeScope()).toBe('global');++ resolveQuery([]);+ await waitFor(() => expect(document.activeElement).toBe(shell));+ expect(activeScope()).toBe(scopeId);++ fireEvent.keyDown(shell, { key: 'j' });+ fireEvent.keyUp(shell, { key: 'j' });+ fireEvent.keyDown(shell, { key: 'k' });+ fireEvent.keyUp(shell, { key: 'k' });+ expect(down).toHaveBeenCalledOnce();+ expect(up).toHaveBeenCalledOnce();+ view.unmount();+ client.clear();+ });+});diff --git a/apps/web/src/components/app/split-layout/utils/createSplitAutofocus.ts b/apps/web/src/components/app/split-layout/utils/createSplitAutofocus.tsnew file mode 100644index 0000000000..097e624ef3--- /dev/null+++ b/apps/web/src/components/app/split-layout/utils/createSplitAutofocus.ts@@ -0,0 +1,51 @@+import { type Accessor, createEffect, on, onCleanup } from 'solid-js';++/** Focuses a split shell once it attaches, without taking existing focus. */+export function createSplitAutofocus(options: {+ element: Accessor<HTMLElement | null>;+ enabled: Accessor<boolean>;+}) {+ createEffect(+ on(options.element, (element) => {+ if (!element || !options.enabled()) return;++ let disposed = false;+ let observer: MutationObserver | undefined;+ onCleanup(() => {+ disposed = true;+ observer?.disconnect();+ });++ const focusWhenAttached = () => {+ if (disposed) return;+ if (!options.enabled()) {+ observer?.disconnect();+ return;+ }+ if (!element.isConnected) return;++ observer?.disconnect();+ const active = document.activeElement;+ if (+ active &&+ active !== document.body &&+ active !== document.documentElement+ ) {+ return;+ }++ element.focus({ preventScroll: true });+ };++ // Inner Suspense boundaries can finish mounting before an outer boundary attaches this shell. Wait for attachment. Defer the focus event so hotkey scope writes run outside this effect.+ queueMicrotask(() => {+ if (disposed) return;+ if (!element.isConnected) {+ observer = new MutationObserver(focusWhenAttached);+ observer.observe(document.body, { childList: true, subtree: true });+ }+ focusWhenAttached();+ });+ })+ );+}diff --git a/apps/web/src/components/view-shell/MobileFilterDrawer.tsx b/apps/web/src/components/view-shell/MobileFilterDrawer.tsxnew file mode 100644index 0000000000..6be60c7da3--- /dev/null+++ b/apps/web/src/components/view-shell/MobileFilterDrawer.tsx@@ -0,0 +1,197 @@+import {+ MobileDrawer,+ scrollToFocusedInput,+} from '@components/app/mobile/MobileDrawer';+import { pressPulse } from '@components/app/mobile/pressPulse';+import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';+import { Accordion } from '@kobalte/core/accordion';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CheckIcon from '@phosphor/check.svg';+import XIcon from '@phosphor/x.svg';+import SlidersHorizontalIcon from '@phosphor-icons/core/regular/sliders-horizontal.svg?component-solid';+import { Button, cn } from '@ui';+import {+ type Accessor,+ createContext,+ createSignal,+ type JSX,+ Show,+ useContext,+} from 'solid-js';++const ScrollContext = createContext<Accessor<HTMLElement | undefined>>();++type MobileFilterDrawerProps = {+ children: JSX.Element;+ activeCount: number;+ onClear: () => void;+ triggerLabel?: string;+ label?: string;+ class?: string;+ /** Active filter chips or other controls beside Clear all. */+ footer?: JSX.Element;+};++/** Presentation only; callers own filter state and compose the drawer contents. */+function Root(props: MobileFilterDrawerProps) {+ const [scrollRef, setScrollRef] = createSignal<HTMLElement>();++ return (+ <MobileDrawer+ side="bottom"+ preventScroll={false}+ preventScrollbarShift={false}+ breakPoints={[0.85]}+ >+ <MobileDrawer.Trigger+ as={Button}+ aria-label={props.triggerLabel ?? 'Open filters'}+ variant="ghost"+ size="sm"+ depth={3}+ class={cn(+ 'island bg-chrome pointer-events-auto relative size-10 shrink-0 rounded-full [&_svg]:size-6',+ props.class+ )}+ ref={pressPulse}+ >+ <SlidersHorizontalIcon />+ <Show when={props.activeCount > 0}>+ <span class="pointer-events-none absolute -top-0.5 right-0 flex size-4 translate-x-1/2 items-center justify-center rounded-full bg-accent text-xxs font-medium leading-none text-surface">+ {props.activeCount}+ </span>+ </Show>+ </MobileDrawer.Trigger>+ <MobileDrawer.Portal>+ <MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />+ <MobileDrawer.Content+ aria-label={props.label ?? 'Filters'}+ class="h-[80vh]"+ >+ <MobileDrawer.Handle class="pb-1" />+ <div class="relative min-h-0 flex-1">+ <ScrollIndicators scrollRef={scrollRef} noBorderStart noBorderEnd />+ <div+ ref={setScrollRef}+ onFocusIn={(e) => scrollToFocusedInput(e)}+ class="h-full overflow-y-auto pb-1 scrollbar-hidden"+ >+ <ScrollContext.Provider value={scrollRef}>+ {props.children}+ </ScrollContext.Provider>+ </div>+ </div>+ <Show when={props.activeCount > 0}>+ <div class="shrink-0 border-t border-edge-muted p-2">+ <div class="flex flex-wrap items-center gap-2">+ {props.footer}+ <Button+ variant="outline"+ size="sm"+ class="min-h-10 rounded-lg bg-active!"+ onClick={() => props.onClear()}+ >+ <XIcon class="size-3!" />+ Clear all+ </Button>+ </div>+ </div>+ </Show>+ </MobileDrawer.Content>+ </MobileDrawer.Portal>+ </MobileDrawer>+ );+}++function Section(props: {+ value: string;+ label: string;+ activeCount: number;+ class?: string;+ children: JSX.Element;+}) {+ const scrollRef = useContext(ScrollContext);+ const scrollToSection = (e: MouseEvent) => {+ const scrollEl = scrollRef?.();+ const item = (e.currentTarget as HTMLElement).closest(+ '[data-closed],[data-expanded]'+ );+ if (!scrollEl || !(item instanceof HTMLElement)) return;+ requestAnimationFrame(() => {+ if (!item.hasAttribute('data-expanded')) return;+ scrollEl.scrollTo({+ top:+ scrollEl.scrollTop ++ item.getBoundingClientRect().top -+ scrollEl.getBoundingClientRect().top,+ behavior: 'smooth',+ });+ });+ };++ return (+ <MobileDrawer.Section+ as={Accordion.Item}+ value={props.value}+ class={props.class}+ >+ <Accordion.Header>+ <Accordion.Trigger+ class="group mb-px flex w-full items-center justify-between bg-surface p-3 text-sm text-ink outline-none transition-colors hover:bg-hover"+ onClick={scrollToSection}+ >+ <span class="font-medium">{props.label}</span>+ <div class="flex items-center gap-2">+ <Show when={props.activeCount > 0}>+ <span class="group-data-expanded:hidden flex size-4 items-center justify-center rounded-full bg-accent text-xxs font-medium leading-none text-surface">+ {props.activeCount}+ </span>+ </Show>+ <CaretDownIcon class="size-3.5 text-ink-muted transition-transform duration-200 group-data-expanded:rotate-180" />+ </div>+ </Accordion.Trigger>+ </Accordion.Header>+ <Accordion.Content>{props.children}</Accordion.Content>+ </MobileDrawer.Section>+ );+}++function Option(props: {+ children: JSX.Element;+ icon?: JSX.Element;+ checked: boolean;+ onChange: (checked: boolean) => void;+ selectionMode?: 'single' | 'multiple';+}) {+ return (+ <button+ type="button"+ role={props.selectionMode === 'single' ? 'radio' : 'checkbox'}+ aria-checked={props.checked}+ class="flex w-full items-center gap-3 bg-surface px-3 py-2.5 text-left text-sm transition-colors hover:bg-hover not-last:mb-px"+ onClick={() => props.onChange(!props.checked)}+ >+ <span+ class={cn(+ 'flex size-4 shrink-0 items-center justify-center border transition-colors',+ props.selectionMode === 'single' && 'rounded-full',+ props.checked ? 'border-accent bg-accent' : 'border-edge'+ )}+ >+ <Show when={props.checked}>+ <CheckIcon class="size-2.5 text-surface" />+ </Show>+ </span>+ <Show when={props.icon}>+ {(icon) => (+ <span class="flex size-4 shrink-0 items-center justify-center">+ {icon()}+ </span>+ )}+ </Show>+ <span class="min-w-0 flex-1 truncate">{props.children}</span>+ </button>+ );+}++export const MobileFilterDrawer = Object.assign(Root, { Section, Option });diff --git a/apps/web/src/components/view-shell/SearchBar.tsx b/apps/web/src/components/view-shell/SearchBar.tsxindex 49133835a2..37a963ddc8 100644--- a/apps/web/src/components/view-shell/SearchBar.tsx+++ b/apps/web/src/components/view-shell/SearchBar.tsx@@ -14,6 +14,11 @@ export type SearchBarProps = Omit<value: string;onValueChange: (value: string) => void;hotkey?: string;+ /**+ * Called after Escape blurs the field without clearing its value. The view+ * can restore keyboard focus to its list.+ */+ onEscape?: () => void;class?: string;inputClass?: string;};@@ -24,6 +29,7 @@ export function SearchBar(props: SearchBarProps) {'value','onValueChange','hotkey',+ 'onEscape','class','inputClass','disabled',@@ -40,6 +46,14 @@ export function SearchBar(props: SearchBarProps) {queueMicrotask(() => input?.focus());};+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== 'Escape' || event.defaultPrevented) return;++ event.preventDefault();+ input?.blur();+ local.onEscape?.();+ };+return (<Surfacedepth={2}@@ -55,6 +69,7 @@ export function SearchBar(props: SearchBarProps) {readOnly={local.readOnly}required={local.required}class="group flex size-full min-w-0 items-center gap-2 px-3"+ onKeyDown={onKeyDown}><TextField.Label class="sr-only">{local.label}</TextField.Label><MagnifyingGlassIcondiff --git a/apps/web/src/components/view-shell/index.ts b/apps/web/src/components/view-shell/index.tsindex dcd468b412..b32a59099b 100644--- a/apps/web/src/components/view-shell/index.ts+++ b/apps/web/src/components/view-shell/index.ts@@ -12,6 +12,7 @@ export {ListSortDropdown,type ListSortDropdownProps,} from './ListDropdowns';+export { MobileFilterDrawer } from './MobileFilterDrawer';export { SearchBar, type SearchBarProps } from './SearchBar';export {type UseViewControlHotkeysOptions,diff --git a/apps/web/src/features/block-email/component/BaseInput.tsx b/apps/web/src/features/block-email/component/BaseInput.tsxindex 4de5bb1861..6603878d28 100644--- a/apps/web/src/features/block-email/component/BaseInput.tsx+++ b/apps/web/src/features/block-email/component/BaseInput.tsx@@ -1398,7 +1398,8 @@ export function BaseInput(props: {}return true;},- runWithInputFocused: true,+ // Let editable fields handle Escape before closing the reply.+ runWithInputFocused: false,hotkeyToken: TOKENS.email.cancelReply,displayPriority: 8,});diff --git a/apps/web/src/features/email-view/components/EmailControls.tsx b/apps/web/src/features/email-view/components/EmailControls.tsxnew file mode 100644index 0000000000..f88de80b91--- /dev/null+++ b/apps/web/src/features/email-view/components/EmailControls.tsx@@ -0,0 +1,43 @@+import { ListFilterDropdown } from '@app/components/view-shell';+import { PreviewButton } from '@components/app/split-layout/components/PreviewButton';+import { Show } from 'solid-js';+import { useEmailView } from '../email-view-context';+import { useEmailFilters } from '../filters/use-email-filters';++export type EmailControlsProps = {+ /** Controlled filter-menu state, so the header's `f` hotkey can open it. */+ filterOpen?: boolean;+ onFilterOpenChange?: (open: boolean) => void;+};++export function EmailControls(props: EmailControlsProps) {+ const { setPreviewOpen } = useEmailView();++ const filters = useEmailFilters();++ return (+ <div class="flex min-w-0 shrink-0 items-center justify-end gap-2 @max-[720px]/view-shell:gap-1">+ <div class="relative shrink-0">+ <ListFilterDropdown+ label="Filter email"+ open={props.filterOpen}+ onOpenChange={props.onFilterOpenChange}+ groups={filters.groups}+ isSelected={filters.isSelected}+ onSelectionChange={filters.setSelected}+ onClear={filters.clear}+ />+ <Show when={filters.activeCount() > 0}>+ <span class="pointer-events-none absolute -top-0.5 right-0 flex size-4 translate-x-1/2 items-center justify-center rounded-full bg-accent text-xxs font-medium leading-none text-surface">+ {filters.activeCount()}+ </span>+ </Show>+ </div>+ <PreviewButton+ iconOnly+ class="rounded-lg"+ onOpenChange={setPreviewOpen}+ />+ </div>+ );+}diff --git a/apps/web/src/features/email-view/components/EmailDateGroupHeader.tsx b/apps/web/src/features/email-view/components/EmailDateGroupHeader.tsxnew file mode 100644index 0000000000..f51bf2a549--- /dev/null+++ b/apps/web/src/features/email-view/components/EmailDateGroupHeader.tsx@@ -0,0 +1,38 @@+import { SoupSectionHeader } from '@app/features/next-soup/soup-view/section-header';+import type { SoupGroupHeaderRow } from '@app/features/soup';+import { SOUP_ROW_CLASS } from '@entity/composed/list-entity/row-geometry';+import { useListLayout } from '@entity/composed/list-entity/shared';+import { cn } from '@ui';++export function EmailDateGroupHeader(props: {+ row: SoupGroupHeaderRow;+ isFirst: boolean;+}) {+ const listLayout = useListLayout();++ // Take the geometry of the single-line rows this header sits among (they+ // split by container width off the same `isWide`), so the label starts+ // exactly where their content does — just past the unread/checkbox gutter.+ const geometryClass = () =>+ (listLayout?.isWide() ?? true)+ ? SOUP_ROW_CLASS.wide+ : SOUP_ROW_CLASS.narrow;++ return (+ <div id={props.row.id} role="row">+ <div role="gridcell">+ <SoupSectionHeader+ class={cn(+ geometryClass(),+ 'border-none my-0 bg-transparent text-ink-extra-muted/80',+ 'mx-(--soup-row-gutter) w-[calc(100%-2*var(--soup-row-gutter))]',+ 'pl-[calc(var(--soup-row-content-inset)-var(--soup-row-gutter))]',+ !props.isFirst && 'pt-5'+ )}+ >+ <span class="truncate">{props.row.label}</span>+ </SoupSectionHeader>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/email-view/components/EmailEmptyState.tsx b/apps/web/src/features/email-view/components/EmailEmptyState.tsxnew file mode 100644index 0000000000..4464c083a4--- /dev/null+++ b/apps/web/src/features/email-view/components/EmailEmptyState.tsx@@ -0,0 +1,132 @@+import { DOCS_BASE } from '@app/constants/docs-links';+import { useAddInboxFlow, useEmailLinksStatus } from '@core/email-link';+import EmptyStateEmailGraphic from '@design/empty-state-email.svg';+import EmptyStateInboxTrayGraphic from '@design/empty-state-inbox-tray.svg';+import EmptyStateNoFilterMatchGraphic from '@design/empty-state-no-filter-match.svg';+import EmptyStateNoSearchMatchGraphic from '@design/empty-state-no-search-match.svg';+import { EmptyStatePanel, FilteredHiddenBanner } from '@ui';+import { Match, Switch } from 'solid-js';+import { match } from 'ts-pattern';+import { useEmailView } from '../email-view-context';+import type { EmailTab } from '../types';++const EMAIL_DOCS_URL = `${DOCS_BASE}/product/email`;++// EmptyStatePanel only insets `centered` panels below the floating mobile+// chrome, and the list wrapper leaves the inset to the panels so the centered+// ones are not padded twice. Left-aligned panels add it themselves.+const MOBILE_TOP_INSET_CLASS = 'touch:pt-(--mobile-content-inset-top)';++function tabCopy(tab: EmailTab): { title: string; description: string } {+ return match(tab)+ .with('important', () => ({+ title: 'Inbox zero',+ description:+ "You're all caught up. New email will appear here as it arrives.",+ }))+ .with('noise', () => ({+ title: 'No noise',+ description:+ 'Low-priority email like newsletters and notifications collects here. Nothing to clear right now.',+ }))+ .with('sent', () => ({+ title: 'No sent email',+ description: 'Email you send will appear here.',+ }))+ .with('calendar', () => ({+ title: 'No calendar email',+ description: 'Invitations and event updates will appear here.',+ }))+ .with('drafts', () => ({+ title: 'No drafts',+ description: "Email you start but haven't sent will appear here.",+ }))+ .with('shared', () => ({+ title: 'No shared email',+ description: 'Threads teammates share with you will appear here.',+ }))+ .with('all', () => ({+ title: 'No email yet',+ description: 'Everything in your inbox will appear here as it arrives.',+ }))+ .exhaustive();+}++export function EmailEmptyState() {+ const { state, setFacets, setInboxIds } = useEmailView();+ const emailActive = useEmailLinksStatus();+ const startAddInbox = useAddInboxFlow();+ const searchText = () => state.search.trim();+ const noInboxesSelected = () => state.inboxIds?.length === 0;+ const hasActiveFilters = () =>+ Object.values(state.facets).some((optionIds) => optionIds.length > 0);++ return (+ <Switch>+ <Match when={!emailActive()}>+ <EmptyStatePanel+ graphic={EmptyStateEmailGraphic}+ title="Connect your email"+ description="Bring your inbox into Macro to triage signal from noise, reply faster, and let agents work alongside your mail."+ primaryAction={{+ label: 'Connect email',+ onClick: () => void startAddInbox(),+ }}+ documentationUrl={EMAIL_DOCS_URL}+ class={MOBILE_TOP_INSET_CLASS}+ />+ </Match>++ <Match when={noInboxesSelected()}>+ <EmptyStatePanel+ centered+ graphic={EmptyStateInboxTrayGraphic}+ title="No inboxes selected"+ description="Pick at least one inbox to see its email."+ primaryAction={{+ label: 'Show all inboxes',+ onClick: () => setInboxIds(undefined),+ }}+ />+ </Match>++ <Match when={searchText()}>+ {(search) => (+ <EmptyStatePanel+ centered+ graphic={EmptyStateNoSearchMatchGraphic}+ title={`No results for "${search()}"`}+ description="Search across subjects, senders, and message content. Try a different query."+ documentationUrl={`${DOCS_BASE}/product/search`}+ />+ )}+ </Match>++ <Match when={hasActiveFilters()}>+ <EmptyStatePanel+ centered+ graphic={EmptyStateNoFilterMatchGraphic}+ title="No email matching the filters"+ description="Try adjusting or clearing your filters to see more results."+ >+ <FilteredHiddenBanner+ hasHiddenItems={false}+ onClearFilters={() => setFacets({})}+ />+ </EmptyStatePanel>+ </Match>++ <Match when={tabCopy(state.tab)}>+ {(copy) => (+ <EmptyStatePanel+ graphic={EmptyStateInboxTrayGraphic}+ title={copy().title}+ description={copy().description}+ documentationUrl={EMAIL_DOCS_URL}+ class={MOBILE_TOP_INSET_CLASS}+ />+ )}+ </Match>+ </Switch>+ );+}diff --git a/apps/web/src/features/email-view/components/EmailFilterDrawer.tsx b/apps/web/src/features/email-view/components/EmailFilterDrawer.tsxnew file mode 100644index 0000000000..578149064f--- /dev/null+++ b/apps/web/src/features/email-view/components/EmailFilterDrawer.tsx@@ -0,0 +1,68 @@+import { MobileFilterDrawer } from '@app/components/view-shell/MobileFilterDrawer';+import { MobileDrawer } from '@components/app/mobile/MobileDrawer';+import { Accordion } from '@kobalte/core/accordion';+import { batch, For } from 'solid-js';+import { useEmailView } from '../email-view-context';+import { useEmailFilters } from '../filters/use-email-filters';+import { EmailInboxSelector } from './EmailInboxSelector';++export function EmailFilterDrawer() {+ const { state, setInboxIds } = useEmailView();+ const filters = useEmailFilters();++ return (+ <MobileFilterDrawer+ triggerLabel="Open email filters"+ label="Email filters"+ activeCount={+ filters.activeCount() + (state.inboxIds === undefined ? 0 : 1)+ }+ onClear={() =>+ batch(() => {+ filters.clear();+ setInboxIds(undefined);+ })+ }+ >+ <MobileDrawer.Label class="pt-4">Filters</MobileDrawer.Label>+ <div class="px-3 pb-3 empty:hidden">+ <EmailInboxSelector />+ </div>+ <Accordion multiple collapsible defaultValue={[filters.groups[0].id]}>+ <div class="flex flex-col gap-3">+ <For each={filters.groups}>+ {(group) => (+ <MobileFilterDrawer.Section+ value={group.id}+ label={group.label}+ activeCount={state.facets[group.id]?.length ?? 0}+ >+ <div+ role={+ group.selectionMode === 'single' ? 'radiogroup' : 'group'+ }+ aria-label={group.label}+ >+ <For each={group.options}>+ {(option) => (+ <MobileFilterDrawer.Option+ selectionMode={group.selectionMode}+ checked={filters.isSelected(group.id, option.id)}+ onChange={(checked) =>+ filters.setSelected(group.id, option.id, checked)+ }+ icon={option.icon?.()}+ >+ {option.label}+ </MobileFilterDrawer.Option>+ )}+ </For>+ </div>+ </MobileFilterDrawer.Section>+ )}+ </For>+ </div>+ </Accordion>+ </MobileFilterDrawer>+ );+}diff --git a/apps/web/src/features/email-view/components/EmailHeader.tsx b/apps/web/src/features/email-view/components/EmailHeader.tsxnew file mode 100644index 0000000000..c018699dc5--- /dev/null+++ b/apps/web/src/features/email-view/components/EmailHeader.tsx@@ -0,0 +1,114 @@+import { SearchBar, useViewControlHotkeys } from '@app/components/view-shell';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { SplitPanel } from '@components/app/split-panel';+import MenuIcon from '@phosphor/list.svg';+import PlusIcon from '@phosphor/plus.svg';+import { Button, Dropdown } from '@ui';+import { createSignal } from 'solid-js';+import { composeEmail } from '../compose-email';+import { useEmailView } from '../email-view-context';+import { EmailControls } from './EmailControls';+import { EmailInboxSelector } from './EmailInboxSelector';+import { EmailNavigation } from './EmailSidebar';++export type EmailHeaderProps = {+ /** Restores list focus when Escape leaves the search field. */+ onSearchEscape?: () => void;+};++export function EmailHeader(props: EmailHeaderProps) {+ const panel = useSplitPanelOrThrow();+ const { state, setState } = useEmailView();+ const [navigationOpen, setNavigationOpen] = createSignal(false);+ const [filterOpen, setFilterOpen] = createSignal(false);+ let searchInput: HTMLInputElement | undefined;++ // The view's control hotkeys are registered once, here, for the split scope.+ useViewControlHotkeys({+ scopeId: panel.splitHotkeyScope,+ enabled: panel.isPanelActive,+ search: {+ description: 'Search email',+ run: () => {+ searchInput?.focus();+ searchInput?.select();+ return true;+ },+ },+ filter: {+ description: 'Filter email',+ run: () => {+ setFilterOpen(true);+ return true;+ },+ },+ });++ return (+ <div class="flex min-w-0 flex-col">+ <SplitPanel.ControlGroup class="hidden px-2 pb-2 @max-[720px]/view-shell:flex">+ <SplitPanel.CloseButton />+ <SplitPanel.BackButton />+ <SplitPanel.ForwardButton />+ </SplitPanel.ControlGroup>++ {/* Sidebar stand-in while the aside is collapsed: the tab menu, the+ inbox selector, and compose. */}+ <div class="mb-4 hidden min-w-0 items-center gap-2 @max-[720px]/view-shell:flex">+ <Dropdown+ open={navigationOpen()}+ onOpenChange={setNavigationOpen}+ placement="bottom-start"+ >+ <Dropdown.Trigger+ variant="ghost"+ size="sm"+ square+ class="size-8 shrink-0 rounded-full"+ aria-label="Open Email navigation"+ >+ <MenuIcon class="size-4" />+ </Dropdown.Trigger>+ <Dropdown.Content class="w-72 rounded-2xl p-2">+ <div class="rounded-xl bg-menu">+ <EmailNavigation onNavigate={() => setNavigationOpen(false)} />+ </div>+ </Dropdown.Content>+ </Dropdown>+ <h1 class="min-w-0 truncate text-xl font-semibold tracking-[-0.03em] text-ink">+ </h1>+ <div class="ml-auto flex shrink-0 items-center gap-2">+ <EmailInboxSelector variant="compact" />+ <Button+ type="button"+ variant="cta"+ size="md"+ class="rounded-lg px-3"+ onClick={composeEmail}+ >+ <PlusIcon class="size-4 shrink-0" />+ New+ </Button>+ </div>+ </div>++ <div class="flex min-w-0 items-center justify-between gap-3">+ <SearchBar+ ref={(element) => (searchInput = element)}+ label="Search email"+ value={state.search}+ hotkey="cmd+f"+ onValueChange={(search) => setState('search', search)}+ onEscape={props.onSearchEscape}+ placeholder="Search email"+ class="max-w-md flex-1"+ />+ <EmailControls+ filterOpen={filterOpen()}+ onFilterOpenChange={setFilterOpen}+ />+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/email-view/components/EmailInboxSelector.tsx b/apps/web/src/features/email-view/components/EmailInboxSelector.tsxnew file mode 100644index 0000000000..680763a8e3--- /dev/null+++ b/apps/web/src/features/email-view/components/EmailInboxSelector.tsx@@ -0,0 +1,112 @@+import { useInboxPicker } from '@app/features/next-soup/soup-view/filters-bar/inbox-picker';+import { SearchableMultiSelect } from '@app/features/next-soup/soup-view/filters-bar/searchable-multi-select';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { enableMultiInbox } from '@core/constant/featureFlags';+import { useAddInboxFlow } from '@core/email-link';+import { Combobox } from '@kobalte/core/combobox';+import CaretDownIcon from '@phosphor/caret-down.svg';+import PlusIcon from '@phosphor/plus.svg';+import TrayIcon from '@phosphor/tray.svg';+import { Button, cn } from '@ui';+import { Show } from 'solid-js';+import { useEmailView } from '../email-view-context';++export type EmailInboxSelectorProps = {+ /**+ * `sidebar` is the full-width row at the top of the Email sidebar;+ * `compact` is the icon-only trigger the narrow header falls back to when+ * the sidebar is collapsed.+ */+ variant?: 'sidebar' | 'compact';+ class?: string;+};++/**+ * Scopes the list to a subset of the user's linked inboxes. Multi-select,+ * default = all. Shown whenever the multi-inbox flag is on (or the user+ * already has multiple inboxes); with a single inbox it names the account+ * and offers "Connect another account" inside the menu.+ */+export function EmailInboxSelector(props: EmailInboxSelectorProps) {+ const { state, setInboxIds } = useEmailView();+ const picker = useInboxPicker({+ selectedIds: () => state.inboxIds,+ setSelectedIds: setInboxIds,+ });+ const multiInboxFlag = useFeatureFlag(enableMultiInbox);+ const addInbox = useAddInboxFlow();++ const soleActiveInbox = () => {+ const ids = picker.activeIds();+ if (ids.length !== 1) return undefined;++ return picker.options().find((option) => option.id === ids[0]);+ };++ const label = () => {+ const sole = soleActiveInbox();+ if (sole) return sole.label;++ const ids = state.inboxIds;+ if (ids === undefined) return 'All inboxes';+ if (ids.length === 0) return 'No inboxes';+ // A lone id that no longer resolves to a linked inbox still reads as one.+ if (ids.length === 1) return '1 inbox';+ return `${ids.length} inboxes`;+ };++ const compact = () => props.variant === 'compact';++ return (+ <Show when={multiInboxFlag().enabled || picker.hasMultiple()}>+ <SearchableMultiSelect+ options={picker.options}+ activeIds={picker.activeIds}+ onChange={(ids) => (ids.length ? picker.onChange(ids) : picker.reset())}+ onOnly={picker.selectOnly}+ placeholder="Search inboxes..."+ placement="bottom-start"+ preserveOrder+ action={+ multiInboxFlag().enabled+ ? {+ label: 'Connect another account',+ icon: () => <PlusIcon class="size-4" />,+ onSelect: () => void addInbox(),+ }+ : undefined+ }+ >+ <Combobox.Trigger+ as={Button}+ variant={compact() ? 'ghost' : 'outline'}+ size={compact() ? 'sm' : 'md'}+ square={compact()}+ depth={2}+ aria-label={`Inbox: ${label()}`}+ tooltip={compact() ? label() : undefined}+ class={cn(+ compact()+ ? 'size-8 shrink-0 rounded-full'+ : 'h-9 w-full min-w-0 justify-start gap-2.5 rounded-xl bg-surface px-3 font-medium',+ props.class+ )}+ >+ <Show+ when={soleActiveInbox()?.icon}+ fallback={<TrayIcon aria-hidden="true" class="size-4 shrink-0" />}+ >+ {(icon) => icon()()}+ </Show>+ <Show when={!compact()}>+ <span class="min-w-0 flex-1 truncate text-left">{label()}</span>+ <CaretDownIcon+ aria-hidden="true"+ class="size-3 shrink-0 text-ink-extra-muted"+ />+ </Show>+ </Combobox.Trigger>+ </SearchableMultiSelect>+ </Show>+ );+}diff --git a/apps/web/src/features/email-view/components/EmailList.tsx b/apps/web/src/features/email-view/components/EmailList.tsxnew file mode 100644index 0000000000..9cbb63c41a--- /dev/null+++ b/apps/web/src/features/email-view/components/EmailList.tsx@@ -0,0 +1,699 @@+import '@entity/composed/ListEntity.css';+import {+ createListController,+ type ListActivation,+ listOwnedSlotName,+ useListInteractions,+} from '@app/components/list';+import {+ resolveEntityActionViewContext,+ toEntityActionListState,+ useEntityActionHotkeys,+} from '@app/features/next-soup/actions';+import {+ createSoupEntityActions,+ MaybeSoupEntityActionDrawerManager,+ SoupEntityContextMenu,+ useSoupListNavigationHotkeys,+ viewedProjectIdFromContent,+} from '@app/features/soup';+import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';+import { makePersistedState } from '@app/lib/persistence';+import { PullToRefresh } from '@components/app/mobile/PullToRefresh';+import { SwipableRowProvider } from '@components/app/mobile/SwipableRow';+import {+ useSplitPanelOrThrow,+ withSplitPanelOwner,+} from '@components/app/split-layout/layoutUtils';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import {+ type EntityData,+ EntitySelectionToolbar,+ ListEntity,+ ListLayoutProvider,+ type WithNotification,+} from '@entity';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CheckIcon from '@phosphor/check.svg';+import SpinnerIcon from '@phosphor/spinner.svg';+import { createElementSize } from '@solid-primitives/resize-observer';+import { Button, cn, Surface } from '@ui';+import {+ createEffect,+ createMemo,+ createSignal,+ Match,+ type Setter,+ Show,+ Suspense,+ Switch,+} from 'solid-js';+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';+import {+ persistSoupNavigationTouchHighlight,+ soupNavigationTouchHighlight,+} from '../../next-soup/soup-view/soup-navigation-touch-highlight';+import { openEntityInSplitFromUnifiedList } from '../../next-soup/utils';+import { useEmailView } from '../email-view-context';+import {+ createEmailListEntryStorage,+ DEFAULT_EMAIL_LIST_STATE,+ type EmailListStateSnapshot,+} from '../persistence';+import {+ type EmailDataSourceItem,+ useEmailDataSource,+} from '../queries/use-email-query';+import { useEmailListHotkeys } from '../use-email-list-hotkeys';+import { EmailDateGroupHeader } from './EmailDateGroupHeader';+import { EmailEmptyState } from './EmailEmptyState';++type EmailActionRow = {+ entity: WithNotification<EntityData>;+ rowId: string;+};++type EmailListActivationMetadata = {+ event?: MouseEvent;+ newSplit?: boolean;+};++export type EmailListProps = {+ /** The focusable list root, for callers that hand keyboard focus back. */+ ref?: (element: HTMLDivElement) => void;+};++export function EmailList(props: EmailListProps) {+ const { state, setOpenThreadId } = useEmailView();+ const panel = useSplitPanelOrThrow();++ const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () =>+ useEmailDataSource(state)+ );++ function openEntity(+ entity: EntityData,+ options: {+ event?: MouseEvent;+ openInNewSplit?: boolean;+ replacePreview?: boolean;+ mergeHistory?: boolean;+ } = {}+ ) {+ if (entity.type === 'email') setOpenThreadId(entity.id);++ const finishTouchHighlight = options.event+ ? persistSoupNavigationTouchHighlight(options.event)+ : undefined;++ void openEntityInSplitFromUnifiedList(entity, {+ splitHandle: panel.handle,+ referredFrom: 'mail',+ openInNewSplit: options.openInNewSplit,+ replacePreview: options.replacePreview,+ mergeHistory: options.mergeHistory,+ }).finally(() => finishTouchHighlight?.());+ }++ function onActivate({+ item,+ metadata,+ }: ListActivation<EmailDataSourceItem, EmailListActivationMetadata>) {+ if (item.kind === 'load-more') {+ if (!item.isLoading) void source.loadMore();++ return;+ }++ if (item.kind !== 'entity') return;++ const sourceRow = source.items().find((row) => row.id === item.id);++ if (sourceRow?.kind !== 'entity') return;++ const newSplit =+ metadata?.newSplit === true || metadata?.event?.shiftKey === true;++ openEntity(sourceRow.entity, {+ event: metadata?.event,+ openInNewSplit: newSplit,+ replacePreview: metadata?.event?.altKey === true && !newSplit,+ });+ }++ const list = withSplitPanelOwner(listOwnedSlotName('controller'), () =>+ createListController<EmailDataSourceItem, EmailListActivationMetadata>({+ items: source.items,+ getKey: (row) => row.id,+ selection: {+ getKey: (row) => (row.kind === 'entity' ? row.entity.id : row.id),+ },+ isNavigable: (row) => row.kind === 'entity' || row.kind === 'load-more',+ isSelectable: (row) => row.kind === 'entity',+ onActivate,+ })+ );++ withSplitPanelOwner(listOwnedSlotName('navigation-hotkeys'), () => {+ useSoupListNavigationHotkeys({+ splitHotkeyScope: panel.splitHotkeyScope,+ viewId: 'mail',+ dataSource: source,+ controller: list,+ handle: panel.handle,+ openEntityInSplit: (entity, options) => {+ openEntity(entity, { mergeHistory: options.mergeHistory });+ },+ });+ });++ const { buildActionGroups } = createSoupEntityActions();+ const entityActionViewContext = () =>+ resolveEntityActionViewContext({+ activeListView: panel.handle.content().id,+ activeTab: state.tab,+ });++ const [viewport, setViewport] = createSignal<HTMLDivElement>();+ const [topSpacer, setTopSpacer] = createSignal<HTMLDivElement>();+ const topSpacerSize = createElementSize(topSpacer);+ const [emptyViewport, setEmptyViewport] = createSignal<HTMLDivElement>();+ const [grid, setGrid] = createSignal<HTMLDivElement>();+ const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();+ const [isPullRefreshing, setIsPullRefreshing] = createSignal(false);+ const forceEmptyState = useDebugSetting(+ DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES+ );++ let scrollOffset = DEFAULT_EMAIL_LIST_STATE.scrollOffset;+ const readListState = (): EmailListStateSnapshot => ({+ focusKey: list.focus.requestedKey(),+ scrollOffset: virtualizer()?.scrollOffset ?? scrollOffset,+ });++ const applyListState: Setter<EmailListStateSnapshot> = (next) => {+ const current = readListState();+ const value = typeof next === 'function' ? next(current) : next;++ if (value.focusKey !== current.focusKey) {+ list.focus.restore(value.focusKey, { reason: 'restore' });+ }++ scrollOffset = value.scrollOffset;+ if (value.scrollOffset !== current.scrollOffset) {+ virtualizer()?.scrollTo(value.scrollOffset);+ }++ return value;+ };+ const [, setPersistedListState] = makePersistedState(+ [readListState, applyListState],+ { storages: createEmailListEntryStorage(panel.handle) }+ );++ const rows = source.items;++ const swipeRowsByEntityId = createMemo(() => {+ const entities = new Map<string, EmailActionRow>();++ for (const row of rows()) {+ if (row.kind !== 'entity') continue;++ entities.set(row.entity.id, { entity: row.entity, rowId: row.id });+ }++ return entities;+ });++ const selectedEntities = createMemo(() =>+ list.selection+ .items()+ .flatMap((row) => (row.kind === 'entity' ? [row.entity] : []))+ );++ const focusedEntity = () => {+ const row = list.focus.result()?.item;+ return row?.kind === 'entity' ? row.entity : undefined;+ };++ const [collapseEntity, setCollapseEntity] =+ createSignal<(entityId: string) => Promise<void>>();++ const actionState = toEntityActionListState({+ controller: list,+ getEntity: (row) => (row.kind === 'entity' ? row.entity : undefined),+ collapse: {+ // Signal and Noise remove archived threads; finish the row animation first.+ enabled: () =>+ isTouchDevice() && (state.tab === 'important' || state.tab === 'noise'),+ run: async (entityId) => {+ await collapseEntity()?.(entityId);+ },+ },+ onFocus: (target) => {+ if (target) {+ virtualizer()?.scrollToIndex(target.index, { align: 'nearest' });+ }++ grid()?.focus();+ },+ });++ const listInteractions = useListInteractions({+ controller: list,+ scopeId: panel.splitHotkeyScope,+ scrollHandle: virtualizer,+ enabled: panel.isPanelActive,+ navigation: {+ onNavigate: (event) => {+ const row = event.result?.item;+ if (row?.kind === 'entity' && panel.handle.isControllerSplit()) {+ openEntity(row.entity, { mergeHistory: true });+ }++ if (event.kind !== 'move' || event.direction !== 1) return;+ if (source.isLoadingMore() || !source.hasMore()) return;++ const distanceFromEnd = event.result+ ? list.items.count() - event.result.index - 1+ : 0;++ if (distanceFromEnd > 3) return;++ void source.loadMore();+ },+ },+ activation: {+ createMetadata: (intent) => ({ newSplit: intent === 'alternate' }),+ alternateDescription: 'Open in new split',+ },+ });++ useEntityActionHotkeys({+ scopeId: panel.splitHotkeyScope,+ list: actionState,+ selectedEntities,+ focusedEntity,+ restoreFocus: () => grid()?.focus(),+ viewContext: entityActionViewContext,+ splitHandle: panel.handle,+ condition: panel.isPanelActive,+ });++ useEmailListHotkeys({+ scopeId: panel.splitHotkeyScope,+ enabled: panel.isPanelActive,+ selectedEntities,+ clearSelection: listInteractions.selection.clear,+ });++ function actionGroupsFor(row: EmailActionRow) {+ const content = panel.handle.content();++ return buildActionGroups(actionState, [row.entity], {+ viewContext: entityActionViewContext(),+ viewedProjectId: viewedProjectIdFromContent(content),+ splitHandle: panel.handle,+ });+ }++ const markDoneActionFor = (row: EmailActionRow) =>+ actionGroupsFor(row)+ .flatMap((group) => group.items)+ .find((action) => action.id === 'mark-done');++ function focusActionRow(row: EmailActionRow) {+ list.focus.set(row.rowId, { reason: 'pointer', force: true });+ list.selection.setAnchor(row.rowId);+ }++ let restoredScroll = false;+ function registerVirtualizer(handle?: VirtualizerHandle) {+ setVirtualizer(handle);+ if (!handle || restoredScroll) return;++ handle.scrollTo(scrollOffset);+ restoredScroll = true;+ }++ function showsEmptyViewport() {+ return (+ forceEmptyState() ||+ (!source.isLoading() && (Boolean(source.error()) || rows().length === 0))+ );+ }++ function pullScrollContainer() {+ return showsEmptyViewport() ? emptyViewport() : viewport();+ }++ async function pullRefresh() {+ setIsPullRefreshing(true);++ try {+ await source.refresh();+ } finally {+ setIsPullRefreshing(false);+ }+ }++ // Switching tab or inbox scope is a new list: drop focus, selection, and+ // the preview, and start from the top.+ const listScope = () =>+ `${state.tab}|${state.inboxIds === undefined ? '*' : state.inboxIds.join(',')}`;+ let activeScope = listScope();+ createEffect(() => {+ const nextScope = listScope();+ if (nextScope === activeScope) return;++ activeScope = nextScope;+ listInteractions.selection.clear();+ list.focus.clear({ reason: 'programmatic' });+ panel.handle.resetPreview();+ setPersistedListState((current) => ({ ...current, scrollOffset: 0 }));+ });++ createEffect(() => {+ rows();+ if (source.isLoading()) return;++ if (list.focus.result()) return;++ const restored = list.focus.restore(list.focus.requestedKey(), {+ retainUnavailable: false,+ });+ if (restored) return;+ if (isTouchDevice()) return;+ if (panel.handle.isControllerSplit()) {+ panel.handle.resetPreview();+ return;+ }++ list.focus.first({+ isNavigable: (row) => row.kind === 'entity',+ reason: 'restore',+ });+ });++ function checkNearEnd() {+ const handle = virtualizer();+ if (!handle) return;++ if (!source.hasMore()) return;++ const distance =+ handle.scrollSize - handle.scrollOffset - handle.viewportSize;+ if (distance < 300 && !source.isLoadingMore()) {+ void source.loadMore();+ }+ }++ return (+ <MaybeSoupEntityActionDrawerManager>+ <Surface+ depth={isTouchDevice() ? 0 : 2}+ hideBorder={isTouchDevice()}+ ref={(element: HTMLDivElement) => {+ setGrid(element);+ props.ref?.(element);+ }}+ role="grid"+ aria-label="Email"+ aria-multiselectable="true"+ aria-activedescendant={list.focus.key()}+ tabIndex={0}+ class={cn(+ 'soup-list relative flex size-full min-h-0 min-w-0 flex-col overflow-hidden outline-none',+ isTouchDevice() ? 'rounded-none bg-transparent' : 'rounded-2xl p-2'+ )}+ >+ <PullToRefresh+ scrollContainer={pullScrollContainer}+ onRefresh={pullRefresh}+ />++ <ListLayoutProvider ref={grid}>+ <SwipableRowProvider+ container={viewport}+ setCollapseEntity={setCollapseEntity}+ canSwipeLeft={(entityId) => {+ const row = swipeRowsByEntityId().get(entityId);+ return row ? markDoneActionFor(row) !== undefined : false;+ }}+ onSwipeLeft={(entityId) => {+ const row = swipeRowsByEntityId().get(entityId);+ if (!row) return;++ const action = markDoneActionFor(row);+ if (!action) return;++ focusActionRow(row);+ void action.onClick();+ }}+ >+ <Switch>+ <Match+ when={+ !forceEmptyState() &&+ source.isLoading() &&+ !isPullRefreshing()+ }+ >+ <div class="grid min-h-0 flex-1 place-items-center text-ink-muted touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)">+ <SpinnerIcon+ aria-label="Loading email"+ class="size-5 animate-spin"+ />+ </div>+ </Match>++ <Match when={!forceEmptyState() && source.error()}>+ <div+ ref={setEmptyViewport}+ class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 overflow-y-auto text-sm text-ink-muted touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)"+ >+ <span>Email couldn’t be loaded.</span>+ <Button+ variant="outline"+ size="sm"+ class="rounded-lg"+ onClick={() => void source.refresh()}+ >+ Try again+ </Button>+ </div>+ </Match>++ <Match when={forceEmptyState() || rows().length === 0}>+ {/* No top inset on the wrapper: each EmptyStatePanel pads itself+ below the floating chrome (centered ones by default, the+ left-aligned ones in EmailEmptyState), so padding here too+ would double it. */}+ <div+ ref={setEmptyViewport}+ class="min-h-0 flex-1 overflow-y-auto touch:pb-(--mobile-content-inset-bottom)"+ >+ <EmailEmptyState />+ </div>+ </Match>++ <Match when={true}>+ <div+ ref={(element) => {+ setViewport(element);+ soupNavigationTouchHighlight(element);+ }}+ class="scrollbar-hidden min-h-0 flex-1 overflow-y-auto overscroll-none"+ >+ {/* Keep insets inside the scroller so rows slide under the floating chrome. */}+ <div+ ref={setTopSpacer}+ aria-hidden="true"+ class="h-0 touch:h-(--mobile-content-inset-top)"+ />+ {/* A row subtree that suspends (the project crumb's preview query, say)+ detaches only itself, not the list and its scroll position. */}+ <Suspense>+ <Virtualizer+ ref={registerVirtualizer}+ data={rows()}+ scrollRef={viewport()}+ startMargin={+ isTouchDevice() ? (topSpacerSize.height ?? 0) : 0+ }+ bufferSize={500}+ itemSize={44}+ keepMounted={+ list.focus.index() >= 0+ ? [list.focus.index()]+ : undefined+ }+ onScroll={checkNearEnd}+ >+ {(row) => (+ <Switch>+ <Match+ when={row.kind === 'group-header' ? row : undefined}+ >+ {(group) => (+ <EmailDateGroupHeader+ row={group()}+ isFirst={rows()[0]?.id === group().id}+ />+ )}+ </Match>+ <Match when={row.kind === 'entity' ? row : undefined}>+ {(entityRow) => (+ <SoupEntityContextMenu+ entity={entityRow().entity}+ list={actionState}+ selectedEntities={selectedEntities}+ viewContext={entityActionViewContext()}+ onOpenChange={(open) => {+ if (!open) return;+ focusActionRow({+ entity: entityRow().entity,+ rowId: entityRow().id,+ });+ }}+ >+ <div+ id={entityRow().id}+ role="row"+ data-soup-entity+ >+ <div role="gridcell">+ <ListEntity+ entity={entityRow().entity}+ checked={list.selection.isSelected(+ entityRow().id+ )}+ highlighted={+ !isTouchDevice() &&+ list.focus.key() === entityRow().id+ }+ onMouseMove={() =>+ list.focus.set(entityRow().id, {+ reason: 'hover',+ })+ }+ onProjectClick={(project, event) => {+ const openInNewSplit = event.shiftKey;+ openEntity(project, {+ openInNewSplit,+ replacePreview:+ event.altKey && !openInNewSplit,+ });+ }}+ onChecked={(selected, shiftKey) =>+ listInteractions.selection.set(+ entityRow().id,+ selected,+ { range: shiftKey }+ )+ }+ entityRowConfig={{+ swipeLeftColor: 'bg-success',+ swipeLeftRevealedComponent: (+ <CheckIcon class="size-8 text-surface" />+ ),+ }}+ onClick={(event) => {+ if (+ event.metaKey ||+ event.ctrlKey ||+ (isTouchDevice() &&+ list.selection.count() > 0)+ ) {+ listInteractions.selection.toggle(+ entityRow().id+ );+ return;+ }++ list.activate.key(entityRow().id, {+ reason: 'pointer',+ metadata: { event },+ });+ }}+ />+ </div>+ </div>+ </SoupEntityContextMenu>+ )}+ </Match>+ <Match+ when={row.kind === 'load-more' ? row : undefined}+ >+ {(loadMore) => (+ <div id={loadMore().id} role="row">+ <div+ role="gridcell"+ aria-busy={loadMore().isLoading}+ class={cn(+ 'my-1 flex min-h-12 items-center justify-center rounded-lg',+ !isTouchDevice() &&+ list.focus.key() === loadMore().id &&+ 'bg-active/60'+ )}+ onMouseMove={() =>+ list.focus.set(loadMore().id, {+ reason: 'hover',+ })+ }+ onClick={() =>+ list.activate.key(loadMore().id, {+ reason: 'pointer',+ })+ }+ >+ <Button+ variant="outline"+ size="sm"+ depth={2}+ disabled={loadMore().isLoading}+ class="bg-surface"+ >+ <Show+ when={!loadMore().isLoading}+ fallback={+ <SpinnerIcon class="size-3 animate-spin" />+ }+ >+ <CaretDownIcon class="size-2.5" />+ </Show>+ {loadMore().isLoading+ ? 'Loading...'+ : 'Load More'}+ </Button>+ </div>+ </div>+ )}+ </Match>+ </Switch>+ )}+ </Virtualizer>+ </Suspense>+ <Show when={isTouchDevice()}>+ <div+ aria-hidden="true"+ class="h-(--mobile-content-inset-bottom)"+ />+ </Show>+ </div>+ </Match>+ </Switch>+ </SwipableRowProvider>+ </ListLayoutProvider>++ <Show when={selectedEntities().length > 0}>+ <EntitySelectionToolbar+ selected={selectedEntities()}+ onClear={listInteractions.selection.clear}+ analyticsSource="email_view_selection_toolbar"+ />+ </Show>+ </Surface>+ </MaybeSoupEntityActionDrawerManager>+ );+}diff --git a/apps/web/src/features/email-view/components/EmailSidebar.tsx b/apps/web/src/features/email-view/components/EmailSidebar.tsxnew file mode 100644index 0000000000..f054423938--- /dev/null+++ b/apps/web/src/features/email-view/components/EmailSidebar.tsx@@ -0,0 +1,103 @@+import { useViewTabHotkeys, ViewSidebar } from '@app/components/view-shell';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { SplitPanel } from '@components/app/split-panel';+import { AnimatedNoiseIcon } from '@icon/wide-noise';+import { AnimatedSignalIcon } from '@icon/wide-signal';+import CalendarBlankIcon from '@phosphor/calendar-blank.svg';+import EnvelopeIcon from '@phosphor/envelope.svg';+import FileIcon from '@phosphor/file.svg';+import PaperPlaneTiltIcon from '@phosphor/paper-plane-tilt.svg';+import PlusIcon from '@phosphor/plus.svg';+import UsersThreeIcon from '@phosphor/users-three.svg';+import { Button } from '@ui';+import { type Component, For } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import { composeEmail } from '../compose-email';+import { EMAIL_TAB_IDS, EMAIL_TABS, type EmailTabItem } from '../constants';+import { useEmailView } from '../email-view-context';+import type { EmailTab } from '../types';+import { EmailInboxSelector } from './EmailInboxSelector';++const TAB_ICONS: Record<EmailTab, Component<{ class?: string }>> = {+ important: AnimatedSignalIcon,+ noise: AnimatedNoiseIcon,+ sent: PaperPlaneTiltIcon,+ calendar: CalendarBlankIcon,+ drafts: FileIcon,+ shared: UsersThreeIcon,+ all: EnvelopeIcon,+};++function Tab(props: { item: EmailTabItem; onNavigate?: () => void }) {+ const { state, setTab } = useEmailView();++ return (+ <ViewSidebar.Item+ active={state.tab === props.item.id}+ onClick={() => {+ setTab(props.item.id);+ props.onNavigate?.();+ }}+ >+ <span aria-hidden="true" class="flex size-4 shrink-0 items-center">+ <Dynamic component={TAB_ICONS[props.item.id]} class="size-4" />+ </span>+ <span class="truncate">{props.item.label}</span>+ </ViewSidebar.Item>+ );+}++export function EmailNavigation(props: { onNavigate?: () => void }) {+ return (+ <ViewSidebar.Nav aria-label="Email tabs">+ <For each={EMAIL_TABS}>+ {(item) => <Tab item={item} onNavigate={props.onNavigate} />}+ </For>+ </ViewSidebar.Nav>+ );+}++export function EmailSidebar() {+ const panel = useSplitPanelOrThrow();+ const { state, setTab } = useEmailView();++ useViewTabHotkeys({+ scopeId: panel.splitHotkeyScope,+ enabled: panel.isPanelActive,+ ids: () => EMAIL_TAB_IDS,+ activeId: () => state.tab,+ setActiveId: setTab,+ });++ return (+ <ViewSidebar.Root+ aria-label="Email navigation"+ class="gap-4 border-r-0 pt-2"+ >+ <SplitPanel.ControlGroup>+ <SplitPanel.CloseButton />+ <SplitPanel.BackButton />+ <SplitPanel.ForwardButton />+ </SplitPanel.ControlGroup>++ <ViewSidebar.Header>+ <ViewSidebar.Title>Email</ViewSidebar.Title>+ <Button+ type="button"+ variant="cta"+ size="md"+ class="rounded-lg px-3"+ onClick={composeEmail}+ >+ <PlusIcon class="size-4 shrink-0" />+ New+ </Button>+ </ViewSidebar.Header>++ <ViewSidebar.Content class="flex flex-col gap-3 pt-1">+ <EmailInboxSelector variant="sidebar" />+ <EmailNavigation />+ </ViewSidebar.Content>+ </ViewSidebar.Root>+ );+}diff --git a/apps/web/src/features/email-view/compose-email.ts b/apps/web/src/features/email-view/compose-email.tsnew file mode 100644index 0000000000..006ca19d1d--- /dev/null+++ b/apps/web/src/features/email-view/compose-email.ts@@ -0,0 +1,9 @@+import { runCreateAction } from '@app/features/command/Launcher';++/**+ * Opens a new email compose from the Email view, the same way the legacy+ * mail toolbar's create button does (in the split, focusing the To field).+ */+export function composeEmail() {+ runCreateAction('email', { source: 'email_view' });+}diff --git a/apps/web/src/features/email-view/constants.ts b/apps/web/src/features/email-view/constants.tsnew file mode 100644index 0000000000..ceafb351a1--- /dev/null+++ b/apps/web/src/features/email-view/constants.ts@@ -0,0 +1,20 @@+import type { EmailTab } from './types';++export type EmailTabItem = {+ id: EmailTab;+ label: string;+};++export const EMAIL_TABS: EmailTabItem[] = [+ { id: 'important', label: 'Signal' },+ { id: 'noise', label: 'Noise' },+ { id: 'sent', label: 'Sent' },+ { id: 'calendar', label: 'Calendar' },+ { id: 'drafts', label: 'Drafts' },+ { id: 'shared', label: 'Shared' },+ { id: 'all', label: 'All' },+];++export const EMAIL_TAB_IDS: EmailTab[] = EMAIL_TABS.map((tab) => tab.id);++export const DEFAULT_EMAIL_TAB: EmailTab = 'important';diff --git a/apps/web/src/features/email-view/email-view-context.tsx b/apps/web/src/features/email-view/email-view-context.tsxnew file mode 100644index 0000000000..5442f321d0--- /dev/null+++ b/apps/web/src/features/email-view/email-view-context.tsx@@ -0,0 +1,113 @@+import { registerInboxFilterSplit } from '@app/features/next-soup/soup-view/inbox-filter-controllers';+import { normalizeFacetSelection } from '@app/features/soup';+import { makePersistedState } from '@app/lib/persistence';+import { usePreference } from '@app/lib/preferences/use-preference';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { createAssertedContextProvider } from '@core/context/createContext';+import { useUserId } from '@core/context/user';+import type { ContextProviderProps } from '@solid-primitives/context';+import { type Accessor, onCleanup, type Setter } from 'solid-js';+import {+ createStore,+ produce,+ reconcile,+ type SetStoreFunction,+ type Store,+} from 'solid-js/store';+import { DEFAULT_EMAIL_TAB } from './constants';+import { createEmailViewPersistence } from './persistence';+import type { EmailTab, EmailViewState, EmailViewStateOptions } from './types';++type EmailViewProviderProps = ContextProviderProps & {+ initialState?: EmailViewStateOptions;+};++export type EmailViewContext = {+ state: Store<EmailViewState>;+ setState: SetStoreFunction<EmailViewState>;+ setTab: (tab: EmailTab) => void;+ setInboxIds: (ids: string[] | undefined) => void;+ setFacets: (facets: EmailViewState['facets']) => void;+ setOpenThreadId: (threadId: string | undefined) => void;+ /**+ * Whether the view may open its preview pane on its own. Written by the+ * Preview toggle so an explicit close stays closed across visits; shares+ * the legacy mail view's key so the choice carries over.+ */+ previewOpen: Accessor<boolean>;+ setPreviewOpen: Setter<boolean>;+};++export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<+ EmailViewContext,+ EmailViewProviderProps+>('EmailView', (props) => {+ const panel = useSplitPanelOrThrow();+ const userId = useUserId();+ const initial = props.initialState ?? {};+ const [previewOpen, setPreviewOpen] = usePreference<boolean>(+ 'macro:pref:soup:mail:preview-open',+ { default: true }+ );++ const [state, setState] = makePersistedState(+ createStore<EmailViewState>({+ tab: initial.tab ?? DEFAULT_EMAIL_TAB,+ search: initial.search ?? '',+ inboxIds:+ initial.inboxIds === undefined ? undefined : [...initial.inboxIds],+ facets: normalizeFacetSelection(initial.facets),+ openThreadId: initial.openThreadId,+ }),+ createEmailViewPersistence({+ handle: panel.handle,+ userId,+ restoreEntryState: props.initialState === undefined,+ restoreLocalState: props.initialState === undefined,+ })+ );++ // A tab is a fresh slice of the mailbox: filters chosen for one tab (Done+ // on Signal, say) would silently narrow the next, so they reset with it.+ const setTab = (tab: EmailTab) => {+ if (state.tab === tab) return;++ setState(+ produce((draft) => {+ draft.tab = tab;+ draft.facets = {};+ })+ );+ };++ const setInboxIds = (ids: string[] | undefined) =>+ setState('inboxIds', ids === undefined ? undefined : [...ids]);++ const setFacets = (facets: EmailViewState['facets']) => {+ setState('facets', reconcile(normalizeFacetSelection(facets)));+ };++ const setOpenThreadId = (threadId: string | undefined) =>+ setState('openThreadId', threadId);++ // The classic sidebar's nested account rows scope the mail list by split id+ // (see `SidebarMailLink`); registering keeps them driving this view too, and+ // flushes a selection queued while navigating here.+ onCleanup(+ registerInboxFilterSplit(panel.handle.id, {+ inboxFilter: () => state.inboxIds,+ setInboxFilter: setInboxIds,+ })+ );++ return {+ state,+ setState,+ setTab,+ setInboxIds,+ setFacets,+ setOpenThreadId,+ previewOpen,+ setPreviewOpen,+ };+});diff --git a/apps/web/src/features/email-view/email-view.tsx b/apps/web/src/features/email-view/email-view.tsxnew file mode 100644index 0000000000..72f6a98ac1--- /dev/null+++ b/apps/web/src/features/email-view/email-view.tsx@@ -0,0 +1,149 @@+import { ViewShell } from '@app/components/view-shell';+import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';+import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { SplitPanel } from '@components/app/split-panel';+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { ListEntityMetadataQueryProvider } from '@entity';+import SpinnerIcon from '@phosphor/spinner.svg';+import { cn, Surface } from '@ui';+import {+ createSignal,+ onMount,+ type ParentProps,+ Show,+ Suspense,+} from 'solid-js';+import { EmailFilterDrawer } from './components/EmailFilterDrawer';+import { EmailHeader } from './components/EmailHeader';+import { EmailList } from './components/EmailList';+import { EmailSidebar } from './components/EmailSidebar';+import { EMAIL_TABS } from './constants';+import { EmailViewProvider, useEmailView } from './email-view-context';+import type { EmailTab, EmailViewStateOptions } from './types';++export type EmailViewProps = {+ /** Explicit navigation state. When present, it wins over entry restoration. */+ initialState?: EmailViewStateOptions;+};++function EmailListFallback() {+ return (+ <Surface+ depth={isTouchDevice() ? 0 : 2}+ hideBorder={isTouchDevice()}+ class={cn(+ 'grid size-full min-h-0 min-w-0 place-items-center text-ink-muted',+ isTouchDevice()+ ? 'rounded-none bg-transparent pt-(--mobile-content-inset-top) pb-(--mobile-content-inset-bottom)'+ : 'rounded-2xl'+ )}+ >+ <SpinnerIcon aria-label="Loading email" class="size-5 animate-spin" />+ </Surface>+ );+}++function EmailDesktopLayout(+ props: ParentProps<{ onSearchEscape: () => void }>+) {+ return (+ <ViewShell.Root+ resizable+ aside={{ preserveDuringResize: false }}+ main={{ preferredWidth: 640 }}+ >+ <ViewShell.Aside>+ <EmailSidebar />+ </ViewShell.Aside>+ <ViewShell.Main>+ <ViewShell.Header>+ <EmailHeader onSearchEscape={props.onSearchEscape} />+ </ViewShell.Header>+ <ViewShell.Content>{props.children}</ViewShell.Content>+ </ViewShell.Main>+ </ViewShell.Root>+ );+}++const MOBILE_EMAIL_TABS: PillTabItem<EmailTab>[] = EMAIL_TABS.map((tab) => ({+ value: tab.id,+ label: tab.label,+}));++function EmailMobileLayout(props: ParentProps) {+ const { state, setTab } = useEmailView();++ return (+ <>+ <SplitHeaderLeft>+ <div class="flex h-full w-full min-w-0 flex-1 items-center">+ <PillTabs+ scrollable+ class="-ml-(--mobile-chrome-gutter) w-[100cqw] max-w-none flex-none"+ contentClass="px-(--mobile-chrome-gutter)"+ leading={<EmailFilterDrawer />}+ items={MOBILE_EMAIL_TABS}+ value={state.tab}+ onChange={setTab}+ />+ </div>+ </SplitHeaderLeft>+ <main+ class="size-full min-h-0 min-w-0"+ style={{+ // Match Inbox: 0.5rem above the 2.5rem pills, then a 0.75rem gap.+ '--mobile-content-inset-top': 'calc(var(--safe-top, 0px) + 3.75rem)',+ }}+ >+ {props.children}+ </main>+ </>+ );+}++function EmailViewRoot() {+ const panel = useSplitPanelOrThrow();+ const [listElement, setListElement] = createSignal<HTMLDivElement>();++ onMount(() => panel.handle.setDisplayName('Email'));++ const list = () => (+ <Suspense fallback={<EmailListFallback />}>+ <EmailList ref={setListElement} />+ </Suspense>+ );++ return (+ <ListEntityMetadataQueryProvider>+ <StaticMarkdownContext>+ <SplitPanel.Root>+ <SplitPanel.Body>+ <Show+ when={isTouchDevice()}+ fallback={+ <EmailDesktopLayout+ onSearchEscape={() => listElement()?.focus()}+ >+ {list()}+ </EmailDesktopLayout>+ }+ >+ <EmailMobileLayout>{list()}</EmailMobileLayout>+ </Show>+ </SplitPanel.Body>+ </SplitPanel.Root>+ </StaticMarkdownContext>+ </ListEntityMetadataQueryProvider>+ );+}++/** Email shares one list across desktop sidebar and mobile pill layouts. */+export function EmailView(props: EmailViewProps) {+ return (+ <EmailViewProvider initialState={props.initialState}>+ <EmailViewRoot />+ </EmailViewProvider>+ );+}diff --git a/apps/web/src/features/email-view/filters/email-facets.ts b/apps/web/src/features/email-view/filters/email-facets.tsnew file mode 100644index 0000000000..395fc34412--- /dev/null+++ b/apps/web/src/features/email-view/filters/email-facets.ts@@ -0,0 +1,144 @@+import {+ hasCalendarInviteFilter,+ hasDocumentAttachmentFilter,+ hasImageAttachmentFilter,+ hasPdfAttachmentFilter,+} from '@app/features/next-soup/filters/predicates';+import { clause, type Facet, type FacetOption } from '@app/features/soup';+import type { EntityIconSelector } from '@core/component/EntityIcon';+import type { EmailEntity, EntityData } from '@entity';+import type { EmailFilterGroupId, EmailFilterOptionId } from '../types';++type EmailFilterOption = {+ id: EmailFilterOptionId;+ label: string;+ iconType?: EntityIconSelector;+};++type EmailFacetOption = FacetOption<EmailEntity, undefined> & EmailFilterOption;++function readOption(+ id: EmailFilterOptionId,+ label: string,+ seen: boolean+): EmailFacetOption {+ return {+ id,+ label,+ clause: { ef: clause.eq('emailSeen', seen) },+ predicate: (email) => email.isRead === seen,+ };+}++function doneOption(+ id: EmailFilterOptionId,+ label: string,+ done: boolean+): EmailFacetOption {+ return {+ id,+ label,+ clause: { ef: clause.eq('emailDone', done) },+ predicate: (email) => email.done === done,+ };+}++// Attachments have no server filter: the page is refined client-side from+// each thread's attachment mime types, as the legacy mail view did.+function attachmentOption(+ id: EmailFilterOptionId,+ label: string,+ iconType: EntityIconSelector,+ predicate: (entity: EntityData) => boolean+): EmailFacetOption {+ return { id, label, iconType, predicate };+}++const EMAIL_READ_OPTIONS: EmailFacetOption[] = [+ readOption('unread', 'Unread', false),+ readOption('read', 'Read', true),+];++const EMAIL_DONE_OPTIONS: EmailFacetOption[] = [+ doneOption('not-done', 'Not done', false),+ doneOption('done', 'Done', true),+];++const EMAIL_ATTACHMENT_OPTIONS: EmailFacetOption[] = [+ attachmentOption('attachment-pdf', 'PDFs', 'pdf', hasPdfAttachmentFilter),+ attachmentOption(+ 'attachment-image',+ 'Images',+ 'image',+ hasImageAttachmentFilter+ ),+ attachmentOption(+ 'attachment-document',+ 'Documents',+ 'files',+ hasDocumentAttachmentFilter+ ),+];++const EMAIL_CALENDAR_OPTIONS: EmailFacetOption[] = [+ {+ id: 'has-calendar-invite',+ label: 'Has calendar invite',+ iconType: 'calendar',+ clause: { ef: clause.eq('emailCalendarOnly', true) },+ predicate: hasCalendarInviteFilter,+ },+];++export const EMAIL_FACETS: Facet<EmailEntity, undefined, EmailFacetOption>[] = [+ { id: 'read', mode: 'or', options: EMAIL_READ_OPTIONS },+ { id: 'done', mode: 'or', options: EMAIL_DONE_OPTIONS },+ { id: 'attachments', mode: 'or', options: EMAIL_ATTACHMENT_OPTIONS },+ { id: 'calendar', mode: 'or', options: EMAIL_CALENDAR_OPTIONS },+];++type EmailFilterGroup = {+ id: EmailFilterGroupId;+ label: string;+ selectionMode?: 'single' | 'multiple';+ /** The option that stands for "no selection" in a single-select group. */+ defaultOptionId?: EmailFilterOptionId;+ options: EmailFilterOption[];+};++const toGroupOptions = (options: EmailFacetOption[]) =>+ options.map(({ id, label, iconType }) => ({ id, label, iconType }));++/** Filter menu layout: the legacy mail filters, split into single-select status groups. */+export const EMAIL_FILTER_GROUPS: EmailFilterGroup[] = [+ {+ id: 'read',+ label: 'Status',+ selectionMode: 'single',+ defaultOptionId: 'all',+ options: [+ ...toGroupOptions(EMAIL_READ_OPTIONS),+ { id: 'all', label: 'All' },+ ],+ },+ {+ id: 'done',+ label: 'Done',+ selectionMode: 'single',+ defaultOptionId: 'all',+ options: [+ ...toGroupOptions(EMAIL_DONE_OPTIONS),+ { id: 'all', label: 'All' },+ ],+ },+ {+ id: 'attachments',+ label: 'Attachments',+ options: toGroupOptions(EMAIL_ATTACHMENT_OPTIONS),+ },+ {+ id: 'calendar',+ label: 'Calendar',+ options: toGroupOptions(EMAIL_CALENDAR_OPTIONS),+ },+];diff --git a/apps/web/src/features/email-view/filters/use-email-filters.tsx b/apps/web/src/features/email-view/filters/use-email-filters.tsxnew file mode 100644index 0000000000..112558d621--- /dev/null+++ b/apps/web/src/features/email-view/filters/use-email-filters.tsx@@ -0,0 +1,85 @@+import type { ListFilterGroup } from '@app/components/view-shell';+import { addUnique, removeValue } from '@app/lib/signals/store-array-updaters';+import { EntityIcon } from '@core/component/EntityIcon';+import { createMemo } from 'solid-js';+import { useEmailView } from '../email-view-context';+import type { EmailFilterGroupId, EmailFilterOptionId } from '../types';+import { EMAIL_FILTER_GROUPS } from './email-facets';++const FILTER_GROUPS: ListFilterGroup<+ EmailFilterGroupId,+ EmailFilterOptionId+>[] = EMAIL_FILTER_GROUPS.map((group) => ({+ ...group,+ options: group.options.map((option) => ({+ ...option,+ icon: option.iconType+ ? () => <EntityIcon targetType={option.iconType} size="xs" />+ : undefined,+ })),+}));++const groupFor = (groupId: EmailFilterGroupId) =>+ FILTER_GROUPS.find((group) => group.id === groupId);++/** Shared selection semantics for the desktop menu and mobile drawer. */+export function useEmailFilters() {+ const { state, setFacets } = useEmailView();+ const activeFilterCount = createMemo(() =>+ Object.values(state.facets).reduce(+ (count, optionIds) => count + optionIds.length,+ 0+ )+ );++ // Single-select groups carry an "All" option that stands for no selection.+ const isSelected = (+ groupId: EmailFilterGroupId,+ optionId: EmailFilterOptionId+ ) => {+ const selected = state.facets[groupId] ?? [];+ const group = groupFor(groupId);+ if (+ group?.selectionMode === 'single' &&+ optionId === group.defaultOptionId+ ) {+ return selected.length === 0;+ }++ return selected.includes(optionId);+ };++ const setSelected = (+ groupId: EmailFilterGroupId,+ optionId: EmailFilterOptionId,+ selected: boolean+ ) => {+ const group = groupFor(groupId);+ if (group?.selectionMode === 'single') {+ if (!selected) return;++ setFacets({+ ...state.facets,+ [groupId]: optionId === group.defaultOptionId ? [] : [optionId],+ });+ return;+ }++ // Persisted facets preserve unknown IDs; menu actions only accept known IDs.+ const update = selected+ ? addUnique<string>(optionId)+ : removeValue<string>(optionId);+ setFacets({+ ...state.facets,+ [groupId]: update(state.facets[groupId]),+ });+ };++ return {+ groups: FILTER_GROUPS,+ activeCount: activeFilterCount,+ isSelected,+ setSelected,+ clear: () => setFacets({}),+ };+}diff --git a/apps/web/src/features/email-view/persistence.ts b/apps/web/src/features/email-view/persistence.tsnew file mode 100644index 0000000000..808a17655f--- /dev/null+++ b/apps/web/src/features/email-view/persistence.ts@@ -0,0 +1,255 @@+import { INBOX_FILTER_ENTRY_KEY } from '@app/features/next-soup/soup-view/inbox-filter-controllers';+import { normalizeFacetSelection } from '@app/features/soup';+import type {+ MakePersistedStateOptions,+ PersistenceStorage,+} from '@app/lib/persistence';+import {+ createEntryPersistenceStorage,+ type EntryPersistenceHandle,+} from '@components/app/split-layout/entry-persistence';+import { createUserScopedStorage } from '@core/util/userScopedStorage';+import type { Accessor } from 'solid-js';+import { z } from 'zod';+import type { EmailViewState } from './types';++const EMAIL_ENTRY_STATE_KEY = 'email.view';+const EMAIL_LIST_ENTRY_STATE_KEY = 'email.listState';+const emailLocalStateStorage = createUserScopedStorage(+ 'macro:email:view-state:v1'+);++const emailTabSchema = z+ .enum(['important', 'noise', 'sent', 'calendar', 'drafts', 'shared', 'all'])+ .catch('important');++const emailFacetsSchema = z.record(z.string(), z.array(z.string()));++const emailEntryStateSchemaWithDefaults = z.object({+ version: z.literal(1).default(1),+ tab: emailTabSchema.default('important'),+ search: z.string().default(''),+ facets: emailFacetsSchema.default({}),+ openThreadId: z.string().optional(),+});++type EmailEntryState = z.infer<typeof emailEntryStateSchemaWithDefaults>;++const DEFAULT_EMAIL_ENTRY_STATE: EmailEntryState =+ emailEntryStateSchemaWithDefaults.parse({});+const emailEntryStateSchema = emailEntryStateSchemaWithDefaults.catch(+ DEFAULT_EMAIL_ENTRY_STATE+);++// The legacy mail view stores the raw `string[] | undefined` under its key;+// anything else restores as "every inbox".+const inboxIdsEntrySchema = z.array(z.string()).optional().catch(undefined);++const emailListStateSchemaWithDefaults = z.object({+ version: z.literal(1).default(1),+ focusKey: z.string().optional(),+ scrollOffset: z.number().finite().default(0),+});++type EmailListEntryState = z.infer<typeof emailListStateSchemaWithDefaults>;++const DEFAULT_EMAIL_LIST_ENTRY_STATE: EmailListEntryState =+ emailListStateSchemaWithDefaults.parse({});+const emailListStateSchema = emailListStateSchemaWithDefaults.catch(+ DEFAULT_EMAIL_LIST_ENTRY_STATE+);++export type EmailListStateSnapshot = {+ focusKey: EmailListEntryState['focusKey'];+ scrollOffset: EmailListEntryState['scrollOffset'];+};++export const DEFAULT_EMAIL_LIST_STATE: EmailListStateSnapshot = {+ focusKey: DEFAULT_EMAIL_LIST_ENTRY_STATE.focusKey,+ scrollOffset: DEFAULT_EMAIL_LIST_ENTRY_STATE.scrollOffset,+};++function createEmailEntryStorage(options: {+ handle: EntryPersistenceHandle;+ restore: boolean;+}): PersistenceStorage<EmailViewState> {+ return createEntryPersistenceStorage({+ handle: options.handle,+ key: EMAIL_ENTRY_STATE_KEY,+ restore: (current, stored) => {+ if (!options.restore) return undefined;++ const restored = emailEntryStateSchema.parse(stored);+ return {+ ...current,+ tab: restored.tab,+ search: restored.search,+ facets: normalizeFacetSelection(restored.facets),+ openThreadId: restored.openThreadId,+ };+ },+ select: (state): EmailEntryState => ({+ version: 1,+ tab: state.tab,+ search: state.search,+ facets: normalizeFacetSelection(state.facets),+ ...(state.openThreadId === undefined+ ? {}+ : { openThreadId: state.openThreadId }),+ }),+ });+}++// Split entry state is gone after a reload, so the parts of the view worth+// coming back to — tab, inbox scope, filters, and the open thread — are also+// kept per user, the way the Channels view keeps its selected channel. The+// search text is deliberately per visit.+const emailLocalStateSchemaWithDefaults = z.object({+ version: z.literal(1).default(1),+ tab: emailTabSchema.default('important'),+ inboxIds: inboxIdsEntrySchema,+ facets: emailFacetsSchema.default({}),+ openThreadId: z.string().optional(),+});++type EmailLocalState = z.infer<typeof emailLocalStateSchemaWithDefaults>;++const DEFAULT_EMAIL_LOCAL_STATE: EmailLocalState =+ emailLocalStateSchemaWithDefaults.parse({});+const emailLocalStateSchema = emailLocalStateSchemaWithDefaults.catch(+ DEFAULT_EMAIL_LOCAL_STATE+);++function selectLocalState(state: EmailViewState): EmailLocalState {+ return {+ version: 1,+ tab: state.tab,+ ...(state.inboxIds === undefined ? {} : { inboxIds: [...state.inboxIds] }),+ facets: normalizeFacetSelection(state.facets),+ ...(state.openThreadId === undefined+ ? {}+ : { openThreadId: state.openThreadId }),+ };+}++function createEmailLocalStateStorage(options: {+ userId: Accessor<string | undefined>;+ restore: boolean;+}): PersistenceStorage<EmailViewState> {+ let previous: string | undefined;+ const serialize = (state: EmailViewState) =>+ JSON.stringify(selectLocalState(state));++ return {+ restore: (current) => {+ if (!options.restore) return undefined;++ const userId = options.userId();+ if (!userId) return undefined;++ const raw = emailLocalStateStorage.read(userId);+ if (raw === null) return undefined;++ try {+ const restored = emailLocalStateSchema.parse(JSON.parse(raw));+ return {+ ...current,+ tab: restored.tab,+ inboxIds: restored.inboxIds,+ facets: normalizeFacetSelection(restored.facets),+ openThreadId: restored.openThreadId,+ };+ } catch {+ return undefined;+ }+ },+ initialize: (current) => {+ previous = serialize(current);+ },+ write: (current) => {+ const userId = options.userId();+ if (!userId) return;++ const serialized = serialize(current);+ if (serialized === previous) return;++ previous = serialized;+ emailLocalStateStorage.write(userId, serialized);+ },+ };+}++/**+ * The inbox selection lives under the legacy mail view's entry key rather+ * than in `email.view`: the classic sidebar's nested account rows read that+ * key off a mail history entry while another view is on top, and a selection+ * made in either implementation survives flipping the new-views flag.+ */+function createInboxIdsEntryStorage(options: {+ handle: EntryPersistenceHandle;+ restore: boolean;+}): PersistenceStorage<EmailViewState> {+ return createEntryPersistenceStorage({+ handle: options.handle,+ key: INBOX_FILTER_ENTRY_KEY,+ restore: (current, stored) => {+ if (!options.restore) return undefined;++ return { ...current, inboxIds: inboxIdsEntrySchema.parse(stored) };+ },+ select: (state): string[] | undefined =>+ state.inboxIds === undefined ? undefined : [...state.inboxIds],+ });+}++export function createEmailListEntryStorage(+ handle: EntryPersistenceHandle+): PersistenceStorage<EmailListStateSnapshot> {+ return createEntryPersistenceStorage({+ handle,+ key: EMAIL_LIST_ENTRY_STATE_KEY,+ restore: (current, stored) => {+ const restored = emailListStateSchema.parse(stored);++ return {+ ...current,+ focusKey: restored.focusKey,+ scrollOffset: restored.scrollOffset,+ };+ },+ select: (state): EmailListEntryState => ({+ version: 1,+ ...(state.focusKey === undefined ? {} : { focusKey: state.focusKey }),+ scrollOffset: state.scrollOffset,+ }),+ });+}++export type CreateEmailViewPersistenceOptions = {+ handle: EntryPersistenceHandle;+ userId: Accessor<string | undefined>;+ restoreEntryState?: boolean;+ restoreLocalState?: boolean;+};++/**+ * Persists Email navigation state with the owning split entry, and the parts+ * worth restoring after a reload per user. Later storages take precedence on+ * restore, so a live entry wins over the user-level copy.+ */+export function createEmailViewPersistence(+ options: CreateEmailViewPersistenceOptions+): MakePersistedStateOptions<EmailViewState> {+ const restore = options.restoreEntryState ?? true;++ return {+ storages: [+ createEmailLocalStateStorage({+ userId: options.userId,+ restore: options.restoreLocalState ?? true,+ }),+ createEmailEntryStorage({ handle: options.handle, restore }),+ createInboxIdsEntryStorage({ handle: options.handle, restore }),+ ],+ };+}diff --git a/apps/web/src/features/email-view/queries/email-query.test.ts b/apps/web/src/features/email-view/queries/email-query.test.tsnew file mode 100644index 0000000000..b5b3cf5c83--- /dev/null+++ b/apps/web/src/features/email-view/queries/email-query.test.ts@@ -0,0 +1,285 @@+import type { EntityData, WithNotification } from '@entity';+import { describe, expect, it, vi } from 'vitest';+import type { EmailTab } from '../types';+import {+ buildEmailQuery,+ type EmailQueryContext,+ emailViewForTab,+} from './email-query';+import { groupEmailEntitiesByDate } from './email-results';+import { buildEmailSearchRequest } from './email-search';++// The soup barrel these pull in transitively imports the websocket client+// modules, which open real sockets at module scope and reject under jsdom.+vi.mock('@service-storage/websocket', () => ({+ storageWS: { reconnectIfDisconnected: vi.fn() },+ createWebSocketJob: vi.fn(),+}));+vi.mock('@service-connection/websocket', () => ({+ ws: { addEventListener: vi.fn(), send: vi.fn() },+ state: () => 'closed',+ createConnectionBlockWebsocketEffect: vi.fn(),+ createConnectionWebsocketEffect: vi.fn(),+}));++const NIL = '00000000-0000-0000-0000-000000000000';+const TABS: EmailTab[] = [+ 'important',+ 'noise',+ 'sent',+ 'calendar',+ 'drafts',+ 'shared',+ 'all',+];++const serialize = (value: unknown) => JSON.stringify(value);++const contextFor = (+ overrides: Partial<EmailQueryContext> = {}+): EmailQueryContext => ({+ tab: 'all',+ inboxIds: undefined,+ facets: {},+ ...overrides,+});++describe('buildEmailQuery', () => {+ it('lists the server view each tab reads from', () => {+ expect(TABS.map((tab) => [tab, emailViewForTab(tab)])).toEqual([+ ['important', 'inbox'],+ ['noise', 'inbox'],+ ['sent', 'sent'],+ ['calendar', 'all'],+ ['drafts', 'drafts'],+ ['shared', 'all'],+ ['all', 'all'],+ ]);++ for (const tab of TABS) {+ expect(buildEmailQuery(contextFor({ tab })).body.emailView).toBe(+ emailViewForTab(tab)+ );+ }+ });++ it('confines every non-email target to nothing', () => {+ const { body } = buildEmailQuery(contextFor());++ expect(body.df).toEqual({ l: { id: NIL } });+ expect(body.chanf).toEqual({ l: { ChannelId: NIL } });+ expect(body.cthf).toEqual({ l: { ChannelId: NIL } });+ expect(body.cf).toEqual({ l: { cid: NIL } });+ expect(body.pf).toEqual({ l: { pid: NIL } });+ expect(body.calf).toEqual({ l: { id: NIL } });+ expect(body.callf).toEqual({ l: { CallId: NIL } });+ expect(body.fef).toEqual({ l: { id: NIL } });+ expect(body.ccf).toEqual({ l: { id: NIL } });+ expect(body.remf).toEqual({ l: { id: NIL } });+ expect(body.ef).toEqual({ '!': { l: { ThreadId: NIL } } });+ });++ it('scopes Signal and Noise by importance and excludes shared threads', () => {+ const signal = serialize(+ buildEmailQuery(contextFor({ tab: 'important' })).body.ef+ );+ const noise = serialize(+ buildEmailQuery(contextFor({ tab: 'noise' })).body.ef+ );++ expect(signal).toContain(serialize({ l: { Importance: true } }));+ expect(signal).toContain(serialize({ l: { Shared: 'exclude' } }));+ expect(noise).toContain(serialize({ l: { Importance: false } }));+ expect(noise).toContain(serialize({ l: { Shared: 'exclude' } }));+ });++ it('scopes Calendar to invite threads and Shared to shared threads', () => {+ const calendar = serialize(+ buildEmailQuery(contextFor({ tab: 'calendar' })).body.ef+ );+ const shared = buildEmailQuery(contextFor({ tab: 'shared' })).body.ef;++ expect(calendar).toContain(serialize({ l: { CalendarOnly: true } }));+ expect(calendar).toContain(serialize({ l: { Shared: 'exclude' } }));+ expect(shared).toEqual({ l: { Shared: 'only' } });+ });++ it('leaves the inbox unscoped when every inbox is selected', () => {+ const { body } = buildEmailQuery(contextFor());++ expect(serialize(body.ef)).not.toContain('Owner');+ });++ it('ORs the selected inbox owners', () => {+ const { body } = buildEmailQuery(+ contextFor({ inboxIds: ['link-a', 'link-b'] })+ );++ expect(body.ef).toEqual({+ '&': [+ { '!': { l: { ThreadId: NIL } } },+ { '|': [{ l: { Owner: 'link-a' } }, { l: { Owner: 'link-b' } }] },+ ],+ });+ });++ it('matches nothing when no inbox is selected', () => {+ const { body } = buildEmailQuery(contextFor({ inboxIds: [] }));++ expect(serialize(body.ef)).toContain(serialize({ l: { Owner: NIL } }));+ });++ it('refines by the read, done, and calendar facets on the server', () => {+ const ef = (facets: EmailQueryContext['facets']) =>+ serialize(buildEmailQuery(contextFor({ facets })).body.ef);++ expect(ef({ read: ['unread'] })).toContain(+ serialize({ l: { NotificationSeen: false } })+ );+ expect(ef({ read: ['read'] })).toContain(+ serialize({ l: { NotificationSeen: true } })+ );+ expect(ef({ done: ['done'] })).toContain(+ serialize({ l: { NotificationDone: true } })+ );+ expect(ef({ calendar: ['has-calendar-invite'] })).toContain(+ serialize({ l: { CalendarOnly: true } })+ );+ });++ it('leaves attachment facets to the client', () => {+ const plain = buildEmailQuery(contextFor()).body;+ const withAttachments = buildEmailQuery(+ contextFor({ facets: { attachments: ['attachment-pdf'] } })+ ).body;++ expect(withAttachments).toEqual(plain);+ });++ it('pages by latest thread activity, newest first', () => {+ expect(buildEmailQuery(contextFor()).params).toEqual({+ expand: true,+ limit: 100,+ sort_method: 'updated_at',+ sort_direction: 'desc',+ });+ });+});++describe('buildEmailSearchRequest', () => {+ const search = { query: 'invoice', matchType: 'partial' as const };++ const requestFor = (overrides: Partial<EmailQueryContext> = {}) => {+ const { body } = buildEmailSearchRequest(contextFor(overrides), search);+ if (!body.filters) throw new Error('search request has no filters');++ return { ...body, filters: body.filters };+ };++ it('searches only email threads', () => {+ const body = requestFor();++ expect(body.query).toBe('invoice');+ expect(body.search_on).toBe('name_content');+ expect(body.filters.document_filters).toEqual({ document_ids: [NIL] });+ expect(body.filters.channel_filters).toEqual({ channel_ids: [NIL] });+ expect(body.filters.email_filters).toEqual({});+ });++ it('mirrors the tab scoping the list applies', () => {+ const filtersFor = (tab: EmailTab) =>+ requestFor({ tab }).filters.email_filters;++ expect(filtersFor('important')).toEqual({+ importance: true,+ shared: 'exclude',+ });+ expect(filtersFor('noise')).toEqual({+ importance: false,+ shared: 'exclude',+ });+ expect(filtersFor('calendar')).toEqual({+ calendar_only: true,+ shared: 'exclude',+ });+ expect(filtersFor('shared')).toEqual({ shared: 'only' });+ expect(filtersFor('all')).toEqual({});+ });++ it('leaves Drafts and Sent search unscoped', () => {+ const filtersFor = (tab: EmailTab) =>+ requestFor({ tab }).filters.email_filters;++ // Macro-composed drafts are unindexed and unlabeled; the client trims+ // both tabs' results instead (see tabFilters).+ expect(filtersFor('drafts')).toEqual({});+ expect(filtersFor('sent')).toEqual({});+ });++ it('restricts to the selected inboxes', () => {+ const selected = requestFor({ inboxIds: ['link-a'] }).filters.email_filters;+ const none = requestFor({ inboxIds: [] }).filters.email_filters;++ expect(selected).toEqual({ link_ids: ['link-a'] });+ expect(none).toEqual({ link_ids: [NIL] });+ });++ it('maps the read and done facets to notification filters', () => {+ const filters = requestFor({+ facets: { read: ['unread'], done: ['not-done'] },+ }).filters.email_filters;++ expect(filters).toEqual({+ notification_filters: { seen: false, done: false },+ });+ });++ it('maps the calendar facet and ignores attachment facets', () => {+ const filters = requestFor({+ facets: {+ calendar: ['has-calendar-invite'],+ attachments: ['attachment-pdf'],+ },+ }).filters.email_filters;++ expect(filters).toEqual({ calendar_only: true });+ });+});++describe('groupEmailEntitiesByDate', () => {+ const now = new Date('2026-09-03T18:00:00Z');++ const email = (+ id: string,+ stamps: Partial<Pick<EntityData, 'sortTs' | 'updatedAt' | 'createdAt'>>+ ) =>+ ({+ id,+ type: 'email',+ name: id,+ ownerId: 'macro|[email protected]',+ ...stamps,+ }) as unknown as WithNotification<EntityData>;++ it('buckets on the server sort stamp, then thread recency', () => {+ const groups = groupEmailEntitiesByDate(+ [+ // Served by the page: the sort stamp wins over the stale updatedAt.+ email('paged', {+ sortTs: '2026-09-03T17:00:00Z',+ updatedAt: '2026-08-20T09:00:00Z',+ }),+ // A websocket insert without a stamp falls back to updatedAt.+ email('inserted', { updatedAt: '2026-09-03T16:00:00Z' }),+ // Nothing but a creation time still lands in a bucket.+ email('bare', { createdAt: '2026-08-20T09:00:00Z' }),+ ],+ now+ );++ expect(groups.map((group) => group.entities.map((e) => e.id))).toEqual([+ ['paged', 'inserted'],+ ['bare'],+ ]);+ });+});diff --git a/apps/web/src/features/email-view/queries/email-query.ts b/apps/web/src/features/email-view/queries/email-query.tsnew file mode 100644index 0000000000..71dc3d7bbc--- /dev/null+++ b/apps/web/src/features/email-view/queries/email-query.ts@@ -0,0 +1,105 @@+import {+ clause,+ compileClause,+ compileFacets,+ confine,+ type FacetSelection,+ mergeAst,+ NIL_UUID,+ type TargetExpr,+} from '@app/features/soup';+import type { SoupAstBody, SoupAstItemsQueryArgs } from '@queries/soup/items';+import { match } from 'ts-pattern';+import { EMAIL_FACETS } from '../filters/email-facets';+import type { EmailTab } from '../types';++export type EmailQueryContext = {+ tab: EmailTab;+ /** `undefined` = every linked inbox; `[]` = none; otherwise email link ids. */+ inboxIds: string[] | undefined;+ facets: FacetSelection;+};++/**+ * The mailbox slice the server lists for each tab. Mirrors the legacy+ * `VIEW_TAB_PRESETS.mail` presets.+ */+export const emailViewForTab = (tab: EmailTab): string =>+ match(tab)+ .with('important', 'noise', () => 'inbox')+ .with('drafts', () => 'drafts')+ .with('sent', () => 'sent')+ .with('calendar', 'shared', 'all', () => 'all')+ .exhaustive();++const anyThread = (): TargetExpr => clause.not(clause.eq('threadId', NIL_UUID));++// Deliberately no `!isDraft` exclusion here: `isDraft` is thread-level, so+// excluding it hid whole conversations the moment a reply draft saved (#5940).+function tabClause(tab: EmailTab): TargetExpr {+ return (+ match(tab)+ .with('important', () =>+ clause.and(+ clause.eq('emailImportance', true),+ clause.eq('emailShared', 'exclude')+ )+ )+ .with('noise', () =>+ clause.and(+ clause.eq('emailImportance', false),+ clause.eq('emailShared', 'exclude')+ )+ )+ .with('calendar', () =>+ clause.and(+ clause.eq('emailShared', 'exclude'),+ clause.eq('emailCalendarOnly', true)+ )+ )+ .with('shared', () => clause.eq('emailShared', 'only'))+ // Sent and Drafts are scoped entirely by `emailView`; the server's sent+ // view already covers every linked inbox, so no sender filter is needed.+ .with('drafts', 'sent', 'all', anyThread)+ .exhaustive()+ );+}++/**+ * Scopes the list to the selected inboxes. No selection means every inbox+ * (no clause); an explicit empty selection matches nothing, like the legacy+ * view's `emailLinkId: [NIL_UUID]`.+ */+function inboxClause(inboxIds: string[] | undefined): TargetExpr | undefined {+ if (inboxIds === undefined) return undefined;+ if (inboxIds.length === 0) return clause.eq('emailLinkId', NIL_UUID);++ return clause.or(...inboxIds.map((id) => clause.eq('emailLinkId', id)));+}++/** Builds the email-only Soup AST for the composable Email view. */+export function buildEmailQuery(+ context: EmailQueryContext+): SoupAstItemsQueryArgs {+ const expressions = [tabClause(context.tab)];+ const inbox = inboxClause(context.inboxIds);+ if (inbox) expressions.push(inbox);++ const base = compileClause(confine({ ef: clause.and(...expressions) }));+ const refinements = compileFacets(context.facets, EMAIL_FACETS, undefined);+ const body: SoupAstBody = {+ ...mergeAst(base, refinements),+ emailView: emailViewForTab(context.tab),+ };++ // Newest activity first: `updated_at` is the thread's latest message time.+ return {+ params: {+ expand: true,+ limit: 100,+ sort_method: 'updated_at',+ sort_direction: 'desc',+ },+ body,+ };+}diff --git a/apps/web/src/features/email-view/queries/email-results.ts b/apps/web/src/features/email-view/queries/email-results.tsnew file mode 100644index 0000000000..b5addeaabc--- /dev/null+++ b/apps/web/src/features/email-view/queries/email-results.ts@@ -0,0 +1,23 @@+import {+ dateBucket,+ groupSoupEntities,+ type SoupGroup,+} from '@app/features/soup/collection';+import type { EntityData, WithNotification } from '@entity';++// Threads are listed by latest activity: `sortTs` is the server's stamp for+// that order, and rows that arrived outside the page (websocket inserts,+// search hits) fall back to the thread's own recency.+const emailSortTimestamp = (entity: EntityData) =>+ entity.sortTs ?? entity.updatedAt ?? entity.createdAt;++export function groupEmailEntitiesByDate(+ entities: WithNotification<EntityData>[],+ now = new Date()+): SoupGroup<WithNotification<EntityData>>[] {+ return groupSoupEntities(entities, {+ getGroupId: (entity) => dateBucket(emailSortTimestamp(entity), now).key,+ getGroupLabel: (_groupId, firstEntity) =>+ dateBucket(emailSortTimestamp(firstEntity), now).label,+ });+}diff --git a/apps/web/src/features/email-view/queries/email-search.ts b/apps/web/src/features/email-view/queries/email-search.tsnew file mode 100644index 0000000000..30aca10bf3--- /dev/null+++ b/apps/web/src/features/email-view/queries/email-search.ts@@ -0,0 +1,101 @@+import {+ type FacetSelection,+ NIL_UUID,+ type SoupSearchRequest,+} from '@app/features/soup';+import type { SearchSoupQueryArgs } from '@queries/soup/search';+import type {+ EmailFilters,+ EntityFilters,+ NotificationFilters,+} from '@service-search/generated/models';+import { match } from 'ts-pattern';+import type { EmailTab } from '../types';+import type { EmailQueryContext } from './email-query';++const nonEmailFilters: EntityFilters = {+ calendar_event_filters: { calendar_event_ids: [NIL_UUID] },+ call_filters: { call_ids: [NIL_UUID] },+ channel_filters: { channel_ids: [NIL_UUID] },+ channel_thread_filters: { thread_ids: [NIL_UUID] },+ chat_filters: { chat_ids: [NIL_UUID] },+ crm_company_filters: { company_ids: [NIL_UUID] },+ document_filters: { document_ids: [NIL_UUID] },+ foreign_entity_filters: { ids: [NIL_UUID] },+ project_filters: { project_ids: [NIL_UUID] },+ reminder_filters: { ids: [NIL_UUID] },+};++// Search has no draft/sent scoping, so those tabs (like All) search the+// user's own threads — the same reach the legacy mail search had.+function tabFilters(tab: EmailTab): EmailFilters {+ return match(tab)+ .with('important', () => ({ importance: true, shared: 'exclude' as const }))+ .with('noise', () => ({ importance: false, shared: 'exclude' as const }))+ .with('calendar', () => ({+ calendar_only: true,+ shared: 'exclude' as const,+ }))+ .with('shared', () => ({ shared: 'only' as const }))+ .with('drafts', 'sent', 'all', () => ({}))+ .exhaustive();+}++const soleSelection = (selection: string[] | undefined) =>+ selection?.length === 1 ? selection[0] : undefined;++/**+ * The read and done facets are single-select, so at most one option of each+ * reaches the service. Attachment facets have no service counterpart; those+ * refine the results client-side like the list page.+ */+function facetFilters(facets: FacetSelection): Partial<EmailFilters> {+ const filters: Partial<EmailFilters> = {};+ const notification: NotificationFilters = {};++ const read = soleSelection(facets.read);+ if (read === 'unread') notification.seen = false;+ if (read === 'read') notification.seen = true;++ const done = soleSelection(facets.done);+ if (done === 'not-done') notification.done = false;+ if (done === 'done') notification.done = true;++ if (Object.keys(notification).length > 0) {+ filters.notification_filters = notification;+ }++ if ((facets.calendar ?? []).includes('has-calendar-invite')) {+ filters.calendar_only = true;+ }++ return filters;+}++/** Mirrors the Email view's tab, inbox, and facet scoping for service-backed search. */+export function buildEmailSearchRequest(+ context: EmailQueryContext,+ search: SoupSearchRequest+): SearchSoupQueryArgs {+ const emailFilters: EmailFilters = {+ ...tabFilters(context.tab),+ ...facetFilters(context.facets),+ };++ if (context.inboxIds !== undefined) {+ // Empty `link_ids` means "any inbox" to the service, so an explicit+ // empty selection is expressed as an inbox that cannot exist.+ emailFilters.link_ids =+ context.inboxIds.length > 0 ? [...context.inboxIds] : [NIL_UUID];+ }++ return {+ params: { cursor: null, page_size: 100 },+ body: {+ query: search.query,+ match_type: search.matchType,+ search_on: 'name_content',+ filters: { ...nonEmailFilters, email_filters: emailFilters },+ },+ };+}diff --git a/apps/web/src/features/email-view/queries/use-email-query.ts b/apps/web/src/features/email-view/queries/use-email-query.tsnew file mode 100644index 0000000000..fa6318e68e--- /dev/null+++ b/apps/web/src/features/email-view/queries/use-email-query.ts@@ -0,0 +1,239 @@+import type { ListDataSource } from '@app/components/list';+import {+ buildFlatSoupRows,+ buildGroupedSoupRows,+ createSearchState,+ createSoupLoadMoreRow,+ type SoupRow,+ testFacets,+} from '@app/features/soup';+import { withEntityNotifications } from '@app/features/soup/entity-notifications';+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';+import { useUserId } from '@core/context/user';+import {+ type EmailEntity,+ type EntityData,+ isEmailEntity,+ type WithNotification,+} from '@entity';+import { useSoupAstItemsQuery } from '@queries/soup/items';+import { createMemo } from 'solid-js';+import { match } from 'ts-pattern';+import { EMAIL_FACETS } from '../filters/email-facets';+import type { EmailTab, EmailViewState } from '../types';+import { buildEmailQuery, type EmailQueryContext } from './email-query';+import { groupEmailEntitiesByDate } from './email-results';+import { buildEmailSearchRequest } from './email-search';++export type EmailDataSourceItem = SoupRow<WithNotification<EntityData>>;++export type EmailDataSource = ListDataSource<EmailDataSourceItem>;++export type EmailDataSourceInput = Pick<+ EmailViewState,+ 'tab' | 'search' | 'inboxIds' | 'facets'+>;++/**+ * The server owns importance, calendar, sent and inbox scoping, so — as with+ * the legacy presets' client filters — only the shapes a cached entity can+ * contradict are re-checked here.+ */+function emailMatchesTab(+ entity: EmailEntity,+ tab: EmailTab,+ userId: string | undefined+): boolean {+ return match(tab)+ .with('drafts', () => entity.isDraft)+ .with('shared', () => userId !== undefined && entity.ownerId !== userId)+ .with('important', 'noise', 'sent', 'calendar', 'all', () => true)+ .exhaustive();+}++type AdmittedEmails = {+ scope: string;+ admittedIds: Set<string>;+ items: EmailEntity[];+};++/** Query, service search, and row assembly owned by the Email view. */+export function useEmailDataSource(+ state: EmailDataSourceInput+): EmailDataSource {+ const notificationSource = useGlobalNotificationSource();+ const userId = useUserId();++ const queryContext = createMemo(+ (): EmailQueryContext => ({+ tab: state.tab,+ inboxIds: state.inboxIds === undefined ? undefined : [...state.inboxIds],+ facets: state.facets,+ })+ );++ const queryArgs = createMemo(() => buildEmailQuery(queryContext()));+ const query = useSoupAstItemsQuery(queryArgs);++ const selectEmails = (entities: EntityData[]): EmailEntity[] => {+ const context = queryContext();+ const selected: EmailEntity[] = [];+ for (const entity of entities) {+ if (!isEmailEntity(entity)) continue;+ if (!emailMatchesTab(entity, context.tab, userId())) continue;++ selected.push(entity);+ }+ return selected;+ };++ // The quick-access pool behind local search holds no email threads, so+ // every search result comes from the search service.+ const search = createSearchState({+ text: () => state.search,+ disableLocalSearch: () => true,+ buildRequest: (request) => buildEmailSearchRequest(queryContext(), request),+ });++ const rawEntities = createMemo<EntityData[]>((previous) => {+ if (!search.isSearching()) {+ if (query.isLoading) return previous;++ return query.data?.entities ?? [];+ }++ const results = search.data();+ if (+ results.length === 0 &&+ previous.length > 0 &&+ search.isLocalSearchSettling()+ ) {+ return previous;+ }+ return results;+ }, []);++ // Keep rows admitted after they transition from unread to read: opening a+ // thread marks it read, and with the Unread filter on the row would+ // otherwise vanish from under the preview. Changing the tab, inbox scope,+ // or read filter starts a new admission scope.+ const entities = createMemo<AdmittedEmails>(+ (previous) => {+ const context = queryContext();+ const emails = selectEmails(rawEntities());+ const activeRead = context.facets.read ?? [];+ const scope = [+ context.tab,+ context.inboxIds?.join(',') ?? '*',+ activeRead.join(','),+ ].join('|');+ const selection = { ...context.facets, read: [] };+ const matchesOtherFacets = (email: EmailEntity) =>+ testFacets(selection, EMAIL_FACETS, email, undefined);++ // Without a read filter there is nothing to admit, so no ids are kept.+ if (activeRead.length === 0) {+ return {+ scope,+ admittedIds: new Set<string>(),+ items: emails.filter(matchesOtherFacets),+ };+ }++ const admittedIds =+ previous.scope === scope+ ? new Set(previous.admittedIds)+ : new Set<string>();+ const readSelection = { read: activeRead };+ for (const email of emails) {+ if (testFacets(readSelection, EMAIL_FACETS, email, undefined)) {+ admittedIds.add(email.id);+ }+ }++ return {+ scope,+ admittedIds,+ items: emails.filter(+ (email) => admittedIds.has(email.id) && matchesOtherFacets(email)+ ),+ };+ },+ { scope: '', admittedIds: new Set<string>(), items: [] }+ );++ const listEntities = createMemo((): WithNotification<EntityData>[] =>+ entities().items.map((email) =>+ withEntityNotifications(email, notificationSource)+ )+ );++ const usesServiceSearch = search.usesServiceSearch;++ const hasMore = () => {+ if (usesServiceSearch()) return search.hasNextPage();+ return query.hasNextPage;+ };++ const isLoadingMore = () => {+ if (usesServiceSearch()) return search.isFetchingNextPage();+ return query.isFetchingNextPage;+ };++ const items = createMemo<EmailDataSourceItem[]>(() => {+ // Search results keep their relevance order, so only the list page is+ // bucketed by date.+ const result: EmailDataSourceItem[] = search.isSearching()+ ? buildFlatSoupRows(listEntities())+ : buildGroupedSoupRows(groupEmailEntitiesByDate(listEntities()));++ if (hasMore()) {+ result.push(+ createSoupLoadMoreRow({+ scopeId: `email:${state.tab}`,+ isLoading: isLoadingMore(),+ })+ );+ }++ return result;+ });++ const isLoading = () => {+ if (!search.isSearching()) {+ return query.isLoading && rawEntities().length === 0;+ }+ if (entities().items.length > 0) return false;+ if (usesServiceSearch()) return search.isLoading();+ return query.isLoading;+ };++ return {+ items,+ isLoading,+ isFetching: () => {+ if (search.isSettling()) return true;+ return usesServiceSearch() ? search.isFetching() : query.isFetching;+ },+ error: () => {+ if (!usesServiceSearch()) return query.error ?? undefined;+ return search.error();+ },+ hasMore,+ isLoadingMore,+ loadMore: async () => {+ if (usesServiceSearch()) {+ await search.fetchNextPage();+ return;+ }+ await query.fetchNextPage();+ },+ refresh: async () => {+ if (usesServiceSearch()) {+ await search.refetch();+ return;+ }+ await query.refresh();+ },+ } satisfies EmailDataSource;+}diff --git a/apps/web/src/features/email-view/types.ts b/apps/web/src/features/email-view/types.tsnew file mode 100644index 0000000000..e2ea4efc7c--- /dev/null+++ b/apps/web/src/features/email-view/types.ts@@ -0,0 +1,47 @@+import type { FacetSelection } from '@app/features/soup';++/**+ * Tab ids match the legacy mail view's `VIEW_TAB_LISTS.mail` values (`important`+ * is the Signal tab) so entity actions keyed on `${view}-${tab}` — mark done,+ * the sender-policy bucket — keep working unchanged.+ */+export type EmailTab =+ | 'important'+ | 'noise'+ | 'sent'+ | 'calendar'+ | 'drafts'+ | 'shared'+ | 'all';++export type EmailFilterGroupId = 'read' | 'done' | 'attachments' | 'calendar';++export type EmailFilterOptionId =+ | 'all'+ | 'unread'+ | 'read'+ | 'not-done'+ | 'done'+ | 'attachment-pdf'+ | 'attachment-image'+ | 'attachment-document'+ | 'has-calendar-invite';++export type EmailViewState = {+ tab: EmailTab;+ search: string;+ /**+ * Linked inboxes the list is scoped to. Tri-state, like the legacy mail+ * view's `inboxFilter`: `undefined` = every inbox (the default), `[]` =+ * explicitly none, otherwise the selected email link ids.+ */+ inboxIds: string[] | undefined;+ facets: FacetSelection;+ /**+ * The thread last opened from this view. Restored into the preview on the+ * next visit, the way the Channels view reopens its selected channel.+ */+ openThreadId?: string;+};++export type EmailViewStateOptions = Partial<EmailViewState>;diff --git a/apps/web/src/features/email-view/use-email-list-hotkeys.ts b/apps/web/src/features/email-view/use-email-list-hotkeys.tsnew file mode 100644index 0000000000..c5f625d154--- /dev/null+++ b/apps/web/src/features/email-view/use-email-list-hotkeys.ts@@ -0,0 +1,66 @@+import { CommandState } from '@app/features/command/state';+import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';+import { TOKENS } from '@core/hotkey/tokens';+import type { EntityData } from '@entity';+import { onCleanup } from 'solid-js';++export type UseEmailListHotkeysOptions = {+ scopeId: string;+ enabled: () => boolean;+ selectedEntities: () => EntityData[];+ clearSelection: () => void;+};++/**+ * The list-level shortcuts the legacy mail list had beyond navigation and+ * entity actions: `cmd+k` opens the command menu in entity-action mode for+ * the multi-selection (or toggles it when nothing is selected), and Escape+ * clears the selection.+ */+export function useEmailListHotkeys(options: UseEmailListHotkeysOptions) {+ const analytics = useAnalytics();+ const group = createHotkeyGroup();++ registerHotkey({+ scopeId: options.scopeId,+ hotkey: 'cmd+k',+ hotkeyToken: TOKENS.global.commandMenu,+ description: () =>+ CommandState.isOpen() ? 'Close command menu' : 'Open command menu',+ condition: () => options.enabled() && !CommandState.isOpen(),+ keyDownHandler: (event) => {+ event?.preventDefault();+ const selected = options.selectedEntities();++ if (selected.length > 0) {+ analytics.track('command_menu_open', {+ from: 'email_view_entity_action',+ });+ CommandState.openForEntityAction([...selected]);+ } else {+ analytics.track('command_menu_open', { from: 'email_view' });+ CommandState.toggle();+ }++ return true;+ },+ displayPriority: 10,+ hide: CommandState.isOpen,+ runWithInputFocused: true,+ }).withGroup(group);++ registerHotkey({+ scopeId: options.scopeId,+ hotkey: 'escape',+ hotkeyToken: TOKENS.soup.dismiss,+ description: 'Clear selection',+ condition: () => options.enabled() && options.selectedEntities().length > 0,+ keyDownHandler: () => {+ options.clearSelection();+ return true;+ },+ }).withGroup(group);++ onCleanup(() => group.dispose());+}diff --git a/apps/web/src/features/entity/composed/list-entity/list-entity-metadata-provider.test.tsx b/apps/web/src/features/entity/composed/list-entity/list-entity-metadata-provider.test.tsxindex b69f516035..53b03537c4 100644--- a/apps/web/src/features/entity/composed/list-entity/list-entity-metadata-provider.test.tsx+++ b/apps/web/src/features/entity/composed/list-entity/list-entity-metadata-provider.test.tsx@@ -3,7 +3,14 @@*/import { useTagSets } from '@property/tags/tag-sets-context';-import { render, screen } from '@solidjs/testing-library';+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import { render, screen, waitFor } from '@solidjs/testing-library';+import {+ QueryClient,+ QueryClientProvider,+ useQuery,+} from '@tanstack/solid-query';+import { Suspense } from 'solid-js';import { beforeEach, describe, expect, it, vi } from 'vitest';import {ListEntityMetadataQueryProvider,@@ -30,11 +37,96 @@ function MetadataConsumer(props: { label: string }) {beforeEach(() => {mocks.useTagsQuery.mockReset();mocks.useTagsQuery.mockReturnValue({+ isPending: false,data: [{ scope: 'user', options: [] }],});});describe('ListEntityMetadataProvider', () => {+ it.each([false, true])(+ 'keeps rendering after a tag query error (cached metadata: %s)',+ async (hasCachedTags) => {+ const queryKey = ['failed-tags'];+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ if (hasCachedTags) {+ client.setQueryData<TagSetResponse[]>(queryKey, [+ { scope: 'user', options: [] },+ ]);+ }+ let refetch!: () => Promise<unknown>;+ mocks.useTagsQuery.mockImplementation(() => {+ const query = useQuery(() => ({+ queryKey,+ enabled: false,+ queryFn: async (): Promise<TagSetResponse[]> => {+ throw new Error('Tag service unavailable');+ },+ }));+ refetch = query.refetch;+ return query;+ });++ const view = render(() => (+ <QueryClientProvider client={client}>+ <Suspense fallback={<span>Loading view</span>}>+ <ListEntityMetadataQueryProvider>+ <MetadataConsumer label="rows" />+ </ListEntityMetadataQueryProvider>+ </Suspense>+ </QueryClientProvider>+ ));++ try {+ const expected = hasCachedTags ? 'rows:1' : 'rows:0';+ expect(screen.getByText(expected)).toBeTruthy();+ await refetch();+ await waitFor(() =>+ expect(client.getQueryState(queryKey)?.status).toBe('error')+ );+ expect(screen.queryByText('Loading view')).toBeNull();+ expect(screen.getByText(expected)).toBeTruthy();+ } finally {+ view.unmount();+ client.clear();+ }+ }+ );++ it('renders the collection while tag metadata is pending, then adds the metadata', async () => {+ let resolveTags!: (tags: TagSetResponse[]) => void;+ const response = new Promise<TagSetResponse[]>((resolve) => {+ resolveTags = resolve;+ });+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ mocks.useTagsQuery.mockImplementation(() =>+ useQuery(() => ({ queryKey: ['pending-tags'], queryFn: () => response }))+ );++ const view = render(() => (+ <QueryClientProvider client={client}>+ <Suspense fallback={<span>Loading view</span>}>+ <ListEntityMetadataQueryProvider>+ <MetadataConsumer label="rows" />+ </ListEntityMetadataQueryProvider>+ </Suspense>+ </QueryClientProvider>+ ));++ try {+ expect(screen.queryByText('Loading view')).toBeNull();+ expect(screen.getByText('rows:0')).toBeTruthy();+ resolveTags([{ scope: 'user', options: [] }]);+ await waitFor(() => expect(screen.getByText('rows:1')).toBeTruthy());+ } finally {+ view.unmount();+ client.clear();+ }+ });+it('shares one tag query across a collection', () => {render(() => (<ListEntityMetadataQueryProvider>diff --git a/apps/web/src/features/inbox-view/components/InboxFilters.tsx b/apps/web/src/features/inbox-view/components/InboxFilters.tsxindex c0baf06cf5..e07296f719 100644--- a/apps/web/src/features/inbox-view/components/InboxFilters.tsx+++ b/apps/web/src/features/inbox-view/components/InboxFilters.tsx@@ -1,17 +1,13 @@-import { ListFilterDropdown } from '@app/components/view-shell';+import {+ ListFilterDropdown,+ MobileFilterDrawer,+} from '@app/components/view-shell';import { addUnique, removeValue } from '@app/lib/signals/store-array-updaters';import { MobileDrawer } from '@components/app/mobile/MobileDrawer';-import { pressPulse } from '@components/app/mobile/pressPulse';import { EntityIcon } from '@core/component/EntityIcon';-import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';import { Accordion } from '@kobalte/core/accordion';import BellSimpleIcon from '@phosphor/bell-simple.svg';-import ChevronDownIcon from '@phosphor/caret-down.svg';-import CheckIcon from '@phosphor/check.svg';-import XIcon from '@phosphor/x.svg';-import SlidersHorizontalIcon from '@phosphor-icons/core/regular/sliders-horizontal.svg?component-solid';-import { Button, cn } from '@ui';-import { createMemo, createSignal, For, type JSX, Show } from 'solid-js';+import { createMemo, For, type JSX, Show } from 'solid-js';import { INBOX_FILTER_GROUPS } from '../inbox-facets';import { useInboxView } from '../inbox-view-context';@@ -83,29 +79,6 @@ function useInboxFilters() {};}-function scrollAccordionItemToTop(- event: MouseEvent,- scrollElement: HTMLElement | undefined-) {- if (!scrollElement) return;-- const item = (event.currentTarget as HTMLElement).closest(- '[data-closed],[data-expanded]'- );- if (!(item instanceof HTMLElement)) return;-- requestAnimationFrame(() => {- if (!item.hasAttribute('data-expanded')) return;-- const containerRect = scrollElement.getBoundingClientRect();- const itemRect = item.getBoundingClientRect();- scrollElement.scrollTo({- top: scrollElement.scrollTop + (itemRect.top - containerRect.top),- behavior: 'smooth',- });- });-}-function FilterCountBadge(props: { count: number }) {return (<Show when={props.count > 0}>@@ -136,160 +109,67 @@ export function InboxFilterDropdown() {export function InboxFilterDrawer() {const filters = useInboxFilters();- const [scrollRef, setScrollRef] = createSignal<HTMLElement>();return (- <MobileDrawer- side="bottom"- preventScroll={false}- preventScrollbarShift={false}- breakPoints={[0.85]}+ <MobileFilterDrawer+ triggerLabel="Open Inbox filters"+ label="Inbox filters"+ activeCount={filters.activeCount()}+ onClear={filters.clear}>- <MobileDrawer.Trigger- as={Button}- aria-label="Open Inbox filters"- variant="ghost"- size="sm"- depth={3}- class="island pointer-events-auto relative size-10 shrink-0 rounded-full bg-chrome [&_svg]:size-6"- ref={pressPulse}- >- <SlidersHorizontalIcon />- <FilterCountBadge count={filters.activeCount()} />- </MobileDrawer.Trigger>+ <MobileDrawer.Label class="pt-4">Filters</MobileDrawer.Label>- <MobileDrawer.Portal>- <MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />- <MobileDrawer.Content aria-label="Inbox filters" class="h-[80vh]">- <MobileDrawer.Handle class="pb-1" />-- <div class="relative min-h-0 flex-1">- <ScrollIndicators scrollRef={scrollRef} noBorderStart noBorderEnd />- <div- ref={setScrollRef}- class="h-full overflow-y-auto pb-1 scrollbar-hidden"- >- <MobileDrawer.Label class="pt-4">Filters</MobileDrawer.Label>-- <Accordion- multiple- collapsible- defaultValue={[FILTER_GROUPS[0]?.id ?? 'type']}- >- <div class="flex flex-col">- <For each={FILTER_GROUPS}>- {(group) => {- const activeCount = createMemo(- () =>- group.options.filter(- (option) =>- option.id !== group.defaultOptionId &&- filters.isSelected(group.id, option.id)- ).length- );-- return (- <MobileDrawer.Section- as={Accordion.Item}- value={group.id}- class="mb-3"+ <Accordion+ multiple+ collapsible+ defaultValue={[FILTER_GROUPS[0]?.id ?? 'type']}+ >+ <div class="flex flex-col">+ <For each={FILTER_GROUPS}>+ {(group) => {+ const activeCount = createMemo(+ () =>+ group.options.filter(+ (option) =>+ option.id !== group.defaultOptionId &&+ filters.isSelected(group.id, option.id)+ ).length+ );++ return (+ <MobileFilterDrawer.Section+ value={group.id}+ label={group.label}+ activeCount={activeCount()}+ class="mb-3"+ >+ <div+ role={+ group.selectionMode === 'single' ? 'radiogroup' : 'group'+ }+ aria-label={group.label}+ >+ <For each={group.options}>+ {(option) => (+ <MobileFilterDrawer.Option+ selectionMode={group.selectionMode}+ checked={filters.isSelected(group.id, option.id)}+ onChange={(checked) =>+ filters.setSelected(group.id, option.id, checked)+ }+ icon={option.icon?.()}>- <Accordion.Header>- <Accordion.Trigger- class="group mb-px flex w-full items-center justify-between bg-surface p-3 text-sm text-ink outline-none transition-colors hover:bg-hover"- onClick={(event) =>- scrollAccordionItemToTop(event, scrollRef())- }- >- <span class="font-medium">{group.label}</span>- <div class="flex items-center gap-2">- <Show when={activeCount() > 0}>- <span class="group-data-expanded:hidden flex size-4 items-center justify-center rounded-full bg-accent text-xxs font-medium leading-none text-surface">- {activeCount()}- </span>- </Show>- <ChevronDownIcon class="size-3.5 text-ink-muted transition-transform duration-200 group-data-expanded:rotate-180" />- </div>- </Accordion.Trigger>- </Accordion.Header>-- <Accordion.Content>- <For each={group.options}>- {(option) => {- const selected = () =>- filters.isSelected(group.id, option.id);-- return (- <button- type="button"- role={- group.selectionMode === 'single'- ? 'radio'- : 'checkbox'- }- aria-checked={selected()}- class="not-last:mb-px flex w-full items-center gap-3 bg-surface px-3 py-2.5 text-left text-sm transition-colors hover:bg-hover"- onClick={() =>- filters.setSelected(- group.id,- option.id,- group.selectionMode === 'single'- ? true- : !selected()- )- }- >- <span- class={cn(- 'flex size-4 shrink-0 items-center justify-center border transition-colors',- selected()- ? 'border-accent bg-accent'- : 'border-edge'- )}- >- <Show when={selected()}>- <CheckIcon class="size-2.5 text-surface" />- </Show>- </span>- <Show when={option.icon}>- {(icon) => (- <span class="flex size-4 shrink-0 items-center justify-center">- {icon()()}- </span>- )}- </Show>- <span class="min-w-0 flex-1 truncate">- {option.label}- </span>- </button>- );- }}- </For>- </Accordion.Content>- </MobileDrawer.Section>- );- }}- </For>- </div>- </Accordion>- </div>- </div>-- <Show when={filters.activeCount() > 0}>- <div class="shrink-0 border-edge-muted border-t p-2">- <Button- variant="outline"- size="sm"- class="min-h-10 rounded-lg bg-active!"- onClick={filters.clear}- >- <XIcon class="size-3!" />- Clear all- </Button>- </div>- </Show>- </MobileDrawer.Content>- </MobileDrawer.Portal>- </MobileDrawer>+ {option.label}+ </MobileFilterDrawer.Option>+ )}+ </For>+ </div>+ </MobileFilterDrawer.Section>+ );+ }}+ </For>+ </div>+ </Accordion>+ </MobileFilterDrawer>);}diff --git a/apps/web/src/features/inbox-view/components/InboxList.tsx b/apps/web/src/features/inbox-view/components/InboxList.tsxindex 4207623a56..fd3ddf5bed 100644--- a/apps/web/src/features/inbox-view/components/InboxList.tsx+++ b/apps/web/src/features/inbox-view/components/InboxList.tsx@@ -258,9 +258,28 @@ export function InboxList() {};let listRoot: HTMLDivElement | undefined;+ const [collapseRow, setCollapseRow] =+ createSignal<(rowId: string) => Promise<void>>();+const actionState = toEntityActionListState({controller: list,getEntity: (row) => (row.kind === 'entity' ? row.entity : undefined),+ collapse: {+ enabled: isTouchDevice,+ run: async (entityId) => {+ const collapse = collapseRow();+ if (!collapse) return;++ // Actions target entities; swipe rows are keyed by notification occurrence.+ await Promise.all(+ rows().flatMap((row) =>+ row.kind === 'entity' && row.entity.id === entityId+ ? [collapse(row.id)]+ : []+ )+ );+ },+ },onFocus: (target) => {if (target) {virtualizer()?.scrollToIndex(target.index, { align: 'nearest' });@@ -428,6 +447,7 @@ export function InboxList() {<SwipableRowProvidercontainer={viewport}+ setCollapseEntity={setCollapseRow}canSwipeLeft={(rowId) => {const row = swipeRowsById().get(rowId);return row ? markDoneActionFor(row) !== undefined : false;diff --git a/apps/web/src/features/inbox-view/components/InboxTabs.tsx b/apps/web/src/features/inbox-view/components/InboxTabs.tsxindex 226ee29b42..949ef1c9eb 100644--- a/apps/web/src/features/inbox-view/components/InboxTabs.tsx+++ b/apps/web/src/features/inbox-view/components/InboxTabs.tsx@@ -53,6 +53,8 @@ export function InboxTabs() {<div class="h-10 min-w-0 flex-1"><PillTabsscrollable+ class="-ml-(--mobile-chrome-gutter) w-[calc(100%+2*var(--mobile-chrome-gutter))] max-w-none flex-none"+ contentClass="px-(--mobile-chrome-gutter)"leading={<InboxFilterDrawer />}items={INBOX_TABS}value={state.tab}diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsxindex b4e463abb8..8da183ea97 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx@@ -1,3 +1,4 @@+import { MobileFilterDrawer as FilterDrawer } from '@app/components/view-shell/MobileFilterDrawer';import type { ListView } from '@app/constants/list-views';import { isListViewID } from '@app/constants/list-views';import {@@ -21,27 +22,19 @@ import {} from '@app/features/next-soup/soup-view/sort-options';import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';import { useFeatureFlag } from '@app/lib/analytics/posthog';-import {- MobileDrawer,- scrollToFocusedInput,-} from '@components/app/mobile/MobileDrawer';-import { pressPulse } from '@components/app/mobile/pressPulse';+import { MobileDrawer } from '@components/app/mobile/MobileDrawer';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { UserIcon } from '@core/component/UserIcon';-import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';import { enableMultiInbox } from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import { useAddInboxFlow } from '@core/email-link';import { Accordion } from '@kobalte/core/accordion';-import ChevronDownIcon from '@phosphor/caret-down.svg';import CheckIcon from '@phosphor/check.svg';import CircleDashedIcon from '@phosphor/circle-dashed.svg';import SearchIcon from '@phosphor/magnifying-glass.svg';import PlusIcon from '@phosphor/plus.svg';-import XIcon from '@phosphor/x.svg';-import SlidersHorizontalIcon from '@phosphor-icons/core/regular/sliders-horizontal.svg?component-solid';import { useContacts } from '@queries/contacts/contacts';-import { Button, cn } from '@ui';+import { cn } from '@ui';import { createMemo, createSignal, For, Show } from 'solid-js';import { ConsolidatedFilterChip } from './consolidated-filter-chip';import { useInboxPicker } from './inbox-picker';@@ -52,26 +45,6 @@ import {} from './unified-filter-dropdown';import { useFilterRefinements } from './use-filter-refinements';-function scrollAccordionItemToTop(- e: MouseEvent,- scrollEl: HTMLElement | undefined-) {- if (!scrollEl) return;- const item = (e.currentTarget as HTMLElement).closest(- '[data-closed],[data-expanded]'- ) as HTMLElement | null;- if (!item) return;- requestAnimationFrame(() => {- if (!item.hasAttribute('data-expanded')) return;- const containerRect = scrollEl.getBoundingClientRect();- const itemRect = item.getBoundingClientRect();- scrollEl.scrollTo({- top: scrollEl.scrollTop + (itemRect.top - containerRect.top),- behavior: 'smooth',- });- });-}-export const MobileFilterDrawer = (props: {/** Extra classes on the trigger button (rendered only when filters exist). */class?: string;@@ -319,502 +292,322 @@ export const MobileFilterDrawer = (props: {const activeCount = () => consolidatedFiltersList().length;- const [scrollRef, setScrollRef] = createSignal<HTMLElement>();-return (<Show when={hasFiltersOrCategories()}>- <MobileDrawer- side="bottom"- preventScroll={false}- preventScrollbarShift={false}- breakPoints={[0.85]}+ <FilterDrawer+ class={props.class}+ activeCount={activeCount()}+ onClear={resetToTabDefaults}+ footer={+ <For each={consolidatedFiltersList()}>+ {(filter) => (+ <ConsolidatedFilterChip+ filter={filter}+ hideCategoryLabel+ mobile+ />+ )}+ </For>+ }>- <MobileDrawer.Trigger- as={Button}- aria-label="Open filters"- variant="ghost"- size="sm"- depth={3}- class={cn(- 'island bg-chrome pointer-events-auto relative size-10 shrink-0 rounded-full [&_svg]:size-6',- props.class- )}- ref={pressPulse}+ {/* Sort section */}+ <Show when={sortOptions().length > 0}>+ <MobileDrawer.Label id="sort-section-label">Sort</MobileDrawer.Label>+ <MobileDrawer.Section+ role="radiogroup"+ aria-labelledby="sort-section-label"+ >+ <For each={sortOptions()}>+ {(option) => {+ const active = () => activeSort() === option.value;+ return (+ <button+ type="button"+ role="radio"+ aria-checked={active()}+ class="w-full bg-surface flex items-center gap-3 px-3 py-2.5 text-sm hover:bg-hover transition-colors text-left not-last:mb-px"+ onClick={() => setSort(option.value)}+ >+ <Show when={option.icon}>+ {(icon) => (+ <span class="size-4 flex items-center justify-center shrink-0 text-ink-muted">+ {icon()()}+ </span>+ )}+ </Show>+ <span class="flex-1 truncate">{option.label}</span>+ <Show when={active()}>+ <CheckIcon class="size-3.5 text-accent shrink-0" />+ </Show>+ </button>+ );+ }}+ </For>+ </MobileDrawer.Section>+ </Show>++ <Accordion+ multiple+ collapsible+ defaultValue={[categories()[0]?.id ?? 'assignee']}>- <SlidersHorizontalIcon />- <Show when={activeCount() > 0}>- <span class="absolute -top-0.5 right-0 translate-x-1/2 size-4 flex items-center justify-center rounded-full bg-accent text-surface text-xxs font-medium leading-none">- {activeCount()}- </span>+ {/* Filter section */}+ <Show+ when={+ categories().length > 0 || isTasksView() || showInboxSection()+ }+ >+ <MobileDrawer.Label class="pt-4">Filters</MobileDrawer.Label></Show>- </MobileDrawer.Trigger>-- <MobileDrawer.Portal>- <MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />- <MobileDrawer.Content aria-label="Filters" class="h-[80vh]">- <MobileDrawer.Handle class="pb-1" />-- {/* Scrollable filter list */}- <div class="relative flex-1 min-h-0">- <ScrollIndicators- scrollRef={scrollRef}- noBorderStart- noBorderEnd- />- <div- ref={setScrollRef}- onFocusIn={(e) => scrollToFocusedInput(e)}- class="overflow-y-auto scrollbar-hidden h-full pb-1"- >- {/* Sort section */}- <Show when={sortOptions().length > 0}>- <MobileDrawer.Label id="sort-section-label">- Sort- </MobileDrawer.Label>- <MobileDrawer.Section- role="radiogroup"- aria-labelledby="sort-section-label"- >- <For each={sortOptions()}>- {(option) => {- const active = () => activeSort() === option.value;- return (- <button- type="button"- role="radio"- aria-checked={active()}- class="w-full bg-surface flex items-center gap-3 px-3 py-2.5 text-sm hover:bg-hover transition-colors text-left not-last:mb-px"- onClick={() => setSort(option.value)}- >- <Show when={option.icon}>- {(icon) => (- <span class="size-4 flex items-center justify-center shrink-0 text-ink-muted">- {icon()()}- </span>- )}- </Show>- <span class="flex-1 truncate">{option.label}</span>- <Show when={active()}>- <CheckIcon class="size-3.5 text-accent shrink-0" />- </Show>- </button>- );- }}- </For>- </MobileDrawer.Section>- </Show>- <Accordion- multiple- collapsible- defaultValue={[categories()[0]?.id ?? 'assignee']}- >- {/* Filter section */}- <Show- when={- categories().length > 0 ||- isTasksView() ||- showInboxSection()- }- >- <MobileDrawer.Label class="pt-4">- Filters- </MobileDrawer.Label>- </Show>-- <Show when={showInboxSection()}>- <MobileDrawer.Section- as={Accordion.Item}- value="inboxes"- class="mb-3"- >- <Accordion.Header>- <Accordion.Trigger- class="w-full flex bg-surface items-center justify-between p-3 text-sm text-ink hover:bg-hover transition-colors outline-none group mb-px"- onClick={(e) =>- scrollAccordionItemToTop(e, scrollRef())- }+ <Show when={showInboxSection()}>+ <FilterDrawer.Section+ value="inboxes"+ label="Inboxes"+ activeCount={+ inboxFilter() !== undefined ? picker.activeIds().length : 0+ }+ class="mb-3"+ >+ <For each={picker.options()}>+ {(option) => {+ const active = () => picker.activeIds().includes(option.id);+ const isSole = () => {+ const ids = picker.activeIds();+ return ids.length === 1 && ids[0] === option.id;+ };+ return (+ <div class="w-full flex items-stretch bg-surface not-last:mb-px">+ <button+ type="button"+ role="checkbox"+ aria-checked={active()}+ class="flex-1 min-w-0 flex items-center gap-3 px-3 py-2.5 text-sm hover:bg-hover transition-colors text-left"+ onClick={() => toggleInbox(option.id)}+ >+ <span+ class={cn(+ 'size-4 flex items-center justify-center shrink-0 rounded border transition-colors',+ active() ? 'bg-accent border-accent' : 'border-edge'+ )}>- <span class="font-medium">Inboxes</span>- <div class="flex items-center gap-2">- <Show when={inboxFilter() !== undefined}>- <span class="group-data-expanded:hidden size-4 flex items-center justify-center rounded-full bg-accent text-surface text-xxs font-medium leading-none">- {picker.activeIds().length}- </span>- </Show>- <ChevronDownIcon class="size-3.5 text-ink-muted transition-transform duration-200 group-data-expanded:rotate-180" />- </div>- </Accordion.Trigger>- </Accordion.Header>- <Accordion.Content>- <For each={picker.options()}>- {(option) => {- const active = () =>- picker.activeIds().includes(option.id);- const isSole = () => {- const ids = picker.activeIds();- return ids.length === 1 && ids[0] === option.id;- };- return (- <div class="w-full flex items-stretch bg-surface not-last:mb-px">- <button- type="button"- role="checkbox"- aria-checked={active()}- class="flex-1 min-w-0 flex items-center gap-3 px-3 py-2.5 text-sm hover:bg-hover transition-colors text-left"- onClick={() => toggleInbox(option.id)}- >- <span- class={cn(- 'size-4 flex items-center justify-center shrink-0 rounded border transition-colors',- active()- ? 'bg-accent border-accent'- : 'border-edge'- )}- >- <Show when={active()}>- <CheckIcon class="size-2.5 text-surface" />- </Show>- </span>- <Show when={option.icon}>- {(icon) => (- <span class="size-4 flex items-center justify-center shrink-0">- {icon()()}- </span>- )}- </Show>- <span- class={cn(- 'flex-1 truncate',- active() ? 'text-ink' : 'text-ink-muted'- )}- >- {option.label}- </span>- </button>- <Show when={picker.hasMultiple()}>- <button- type="button"- class="shrink-0 px-3 text-xs text-ink-muted hover:text-ink hover:bg-hover transition-colors"- aria-label={- isSole()- ? 'Show all inboxes'- : `Show only ${option.label}`- }- onClick={() => picker.selectOnly(option.id)}- >- {isSole() ? 'All' : 'Only'}- </button>- </Show>- </div>- );- }}- </For>- <Show when={multiInboxFlag().enabled}>- <button- type="button"- class="w-full flex items-center gap-3 px-3 py-2.5 text-sm hover:bg-hover transition-colors text-left bg-surface not-last:mb-px"- onClick={() => void addInbox()}- >+ <Show when={active()}>+ <CheckIcon class="size-2.5 text-surface" />+ </Show>+ </span>+ <Show when={option.icon}>+ {(icon) => (<span class="size-4 flex items-center justify-center shrink-0">- <PlusIcon class="size-4 text-ink-muted" />+ {icon()()}</span>- <span class="flex-1 truncate">- Connect another account- </span>- </button>+ )}</Show>- </Accordion.Content>- </MobileDrawer.Section>- </Show>-- <div class="flex flex-col">- <For each={categories()}>- {(category) => {- const activeCount = createMemo(- () =>- category.options.filter((o) =>- soup.predicates.isActive(o.id)- ).length- );+ <span+ class={cn(+ 'flex-1 truncate',+ active() ? 'text-ink' : 'text-ink-muted'+ )}+ >+ {option.label}+ </span>+ </button>+ <Show when={picker.hasMultiple()}>+ <button+ type="button"+ class="shrink-0 px-3 text-xs text-ink-muted hover:text-ink hover:bg-hover transition-colors"+ aria-label={+ isSole()+ ? 'Show all inboxes'+ : `Show only ${option.label}`+ }+ onClick={() => picker.selectOnly(option.id)}+ >+ {isSole() ? 'All' : 'Only'}+ </button>+ </Show>+ </div>+ );+ }}+ </For>+ <Show when={multiInboxFlag().enabled}>+ <button+ type="button"+ class="w-full flex items-center gap-3 px-3 py-2.5 text-sm hover:bg-hover transition-colors text-left bg-surface not-last:mb-px"+ onClick={() => void addInbox()}+ >+ <span class="size-4 flex items-center justify-center shrink-0">+ <PlusIcon class="size-4 text-ink-muted" />+ </span>+ <span class="flex-1 truncate">Connect another account</span>+ </button>+ </Show>+ </FilterDrawer.Section>+ </Show>++ <div class="flex flex-col">+ <For each={categories()}>+ {(category) => {+ const activeCount = createMemo(+ () =>+ category.options.filter((o) =>+ soup.predicates.isActive(o.id)+ ).length+ );+ return (+ <FilterDrawer.Section+ value={category.id}+ label={category.label}+ activeCount={activeCount()}+ class="mb-3"+ >+ <For each={category.options}>+ {(option) => {+ const active = () =>+ soup.predicates.isActive(option.id);return (- <MobileDrawer.Section- as={Accordion.Item}- value={category.id}- class="mb-3"+ <FilterDrawer.Option+ checked={active()}+ onChange={() => toggleFilter(option.id)}+ icon={option.icon?.()}>- <Accordion.Header>- <Accordion.Trigger- class="w-full flex bg-surface items-center justify-between p-3 text-sm text-ink hover:bg-hover transition-colors outline-none group mb-px"- onClick={(e) =>- scrollAccordionItemToTop(e, scrollRef())- }- >- <span class="font-medium">- {category.label}- </span>- <div class="flex items-center gap-2">- <Show when={activeCount() > 0}>- <span class="group-data-expanded:hidden size-4 flex items-center justify-center rounded-full bg-accent text-surface text-xxs font-medium leading-none">- {activeCount()}- </span>- </Show>- <ChevronDownIcon class="size-3.5 text-ink-muted transition-transform duration-200 group-data-expanded:rotate-180" />- </div>- </Accordion.Trigger>- </Accordion.Header>- <Accordion.Content>- <For each={category.options}>- {(option) => {- const active = () =>- soup.predicates.isActive(option.id);- return (- <button- type="button"- role="checkbox"- aria-checked={active()}- class="w-full flex items-center gap-3 px-3 py-2.5 text-sm hover:bg-hover transition-colors text-left bg-surface not-last:mb-px"- onClick={() => toggleFilter(option.id)}- >- <span- class={cn(- 'size-4 flex items-center justify-center shrink-0 border transition-colors',- active()- ? 'bg-accent border-accent'- : 'border-edge'- )}- >- <Show when={active()}>- <CheckIcon class="size-2.5 text-surface" />- </Show>- </span>- <Show when={option.icon}>- {(icon) => (- <span class="size-4 flex items-center justify-center shrink-0">- {icon()()}- </span>- )}- </Show>- <span class={cn('flex-1 truncate')}>- {option.label}- </span>- </button>- );- }}- </For>- </Accordion.Content>- </MobileDrawer.Section>+ {option.label}+ </FilterDrawer.Option>);}}</For>- </div>-- {/* Assignee section for tasks view */}- <Show when={isTasksView()}>- <MobileDrawer.Section as={Accordion.Item} value="assignee">- <Accordion.Header>- <Accordion.Trigger- class="w-full flex items-center justify-between p-3 text-sm text-ink hover:bg-hover transition-colors outline-none group bg-surface mb-px"- onClick={(e) =>- scrollAccordionItemToTop(e, scrollRef())- }+ </FilterDrawer.Section>+ );+ }}+ </For>+ </div>++ {/* Assignee section for tasks view */}+ <Show when={isTasksView()}>+ <FilterDrawer.Section+ value="assignee"+ label="Assignee"+ activeCount={assigneeFilter().length}+ >+ {/* Search */}+ <div class="flex items-center gap-2 px-3 py-2 muted bg-surface mb-px">+ <SearchIcon class="size-3.5 text-ink-muted shrink-0" />+ <input+ type="text"+ aria-label="Search assignees"+ value={assigneeSearch()}+ onInput={(e) => setAssigneeSearch(e.currentTarget.value)}+ placeholder="Search assignees..."+ class="flex-1 bg-transparent text-sm outline-none placeholder:text-ink-placeholder"+ />+ </div>+ <div class="max-h-[calc(50*var(--dvh))] overflow-y-auto scrollbar-hidden">+ <For each={filteredAssigneeOptions()}>+ {(option) => {+ const active = () => assigneeFilter().includes(option.id);+ return (+ <button+ type="button"+ role="checkbox"+ aria-checked={active()}+ class="w-full flex items-center gap-3 px-4 py-2.5 text-sm hover:bg-hover transition-colors text-left bg-surface not-last:mb-px"+ onClick={() => toggleAssignee(option.id)}+ >+ <span+ class={cn(+ 'size-4 flex items-center justify-center shrink-0 rounded border transition-colors',+ active() ? 'bg-accent border-accent' : 'border-edge'+ )}>- <span class="font-medium">Assignee</span>- <div class="flex items-center gap-2">- <Show when={assigneeFilter().length > 0}>- <span class="group-data-expanded:hidden size-4 flex items-center justify-center rounded-full bg-accent text-surface text-xxs font-medium leading-none">- {assigneeFilter().length}- </span>- </Show>- <ChevronDownIcon class="size-3.5 text-ink-muted transition-transform duration-200 group-data-expanded:rotate-180" />- </div>- </Accordion.Trigger>- </Accordion.Header>- <Accordion.Content>- {/* Search */}- <div class="flex items-center gap-2 px-3 py-2 muted bg-surface mb-px">- <SearchIcon class="size-3.5 text-ink-muted shrink-0" />- <input- type="text"- aria-label="Search assignees"- value={assigneeSearch()}- onInput={(e) =>- setAssigneeSearch(e.currentTarget.value)- }- placeholder="Search assignees..."- class="flex-1 bg-transparent text-sm outline-none placeholder:text-ink-placeholder"- />- </div>- <div class="max-h-[calc(50*var(--dvh))] overflow-y-auto scrollbar-hidden">- <For each={filteredAssigneeOptions()}>- {(option) => {- const active = () =>- assigneeFilter().includes(option.id);- return (- <button- type="button"- role="checkbox"- aria-checked={active()}- class="w-full flex items-center gap-3 px-4 py-2.5 text-sm hover:bg-hover transition-colors text-left bg-surface not-last:mb-px"- onClick={() => toggleAssignee(option.id)}- >- <span- class={cn(- 'size-4 flex items-center justify-center shrink-0 rounded border transition-colors',- active()- ? 'bg-accent border-accent'- : 'border-edge'- )}- >- <Show when={active()}>- <CheckIcon class="size-2.5 text-surface" />- </Show>- </span>- <span class="size-4 flex items-center justify-center shrink-0">- {option.icon()}- </span>- <span- class={cn(- 'flex-1 truncate',- active() ? 'text-ink' : 'text-ink-muted'- )}- >- {option.label}- </span>- </button>- );- }}- </For>- </div>-- <Show when={filteredAssigneeOptions().length === 0}>- <div class="px-4 py-2 text-sm text-ink-muted">- No results- </div>- </Show>- </Accordion.Content>- </MobileDrawer.Section>- </Show>-- {/* Created by section for Tasks and Files */}- <Show when={showCreatedByFilter()}>- <MobileDrawer.Section- as={Accordion.Item}- value="created-by"- >- <Accordion.Header>- <Accordion.Trigger- class="w-full flex items-center justify-between p-3 text-sm text-ink hover:bg-hover transition-colors outline-none group bg-surface mb-px"- onClick={(e) =>- scrollAccordionItemToTop(e, scrollRef())- }+ <Show when={active()}>+ <CheckIcon class="size-2.5 text-surface" />+ </Show>+ </span>+ <span class="size-4 flex items-center justify-center shrink-0">+ {option.icon()}+ </span>+ <span+ class={cn(+ 'flex-1 truncate',+ active() ? 'text-ink' : 'text-ink-muted'+ )}>- <span class="font-medium">Created by</span>- <div class="flex items-center gap-2">- <Show when={createdByIds().length > 0}>- <span class="group-data-expanded:hidden size-4 flex items-center justify-center rounded-full bg-accent text-surface text-xxs font-medium leading-none">- {createdByIds().length}- </span>- </Show>- <ChevronDownIcon class="size-3.5 text-ink-muted transition-transform duration-200 group-data-expanded:rotate-180" />- </div>- </Accordion.Trigger>- </Accordion.Header>- <Accordion.Content>- <div class="flex items-center gap-2 px-3 py-2 muted bg-surface mb-px">- <SearchIcon class="size-3.5 text-ink-muted shrink-0" />- <input- type="text"- aria-label="Search creators"- value={createdBySearch()}- onInput={(e) =>- setCreatedBySearch(e.currentTarget.value)- }- placeholder="Search creators..."- class="flex-1 bg-transparent text-sm outline-none placeholder:text-ink-placeholder"- />- </div>- <div class="max-h-[calc(50*var(--dvh))] overflow-y-auto scrollbar-hidden">- <For each={filteredCreatedByOptions()}>- {(option) => {- const active = () =>- createdByIds().includes(option.id);- return (- <button- type="button"- role="checkbox"- aria-checked={active()}- class="w-full flex items-center gap-3 px-4 py-2.5 text-sm hover:bg-hover transition-colors text-left bg-surface not-last:mb-px"- onClick={() => toggleCreatedBy(option.id)}- >- <span- class={cn(- 'size-4 flex items-center justify-center shrink-0 rounded border transition-colors',- active()- ? 'bg-accent border-accent'- : 'border-edge'- )}- >- <Show when={active()}>- <CheckIcon class="size-2.5 text-surface" />- </Show>- </span>- <span class="size-4 flex items-center justify-center shrink-0">- {option.icon()}- </span>- <span- class={cn(- 'flex-1 truncate',- active() ? 'text-ink' : 'text-ink-muted'- )}- >- {option.label}- </span>- </button>- );- }}- </For>- </div>- <Show when={filteredCreatedByOptions().length === 0}>- <div class="px-4 py-2 text-sm text-ink-muted">- No results- </div>- </Show>- </Accordion.Content>- </MobileDrawer.Section>- </Show>- </Accordion>+ {option.label}+ </span>+ </button>+ );+ }}+ </For></div>- </div>-- {/* Active filter chips footer */}- <Show when={activeCount() > 0}>- <div class="shrink-0 border-t border-edge-muted p-2">- <div class="flex items-center gap-2 flex-wrap">- <For each={consolidatedFiltersList()}>- {(filter) => (- <ConsolidatedFilterChip- filter={filter}- hideCategoryLabel- mobile- />- )}- </For>- <Button- onClick={() => resetToTabDefaults()}- variant="outline"- size="sm"- class="min-h-10 rounded-lg bg-active!"- >- <XIcon class="size-3!" />- Clear all- </Button>- </div>++ <Show when={filteredAssigneeOptions().length === 0}>+ <div class="px-4 py-2 text-sm text-ink-muted">No results</div>+ </Show>+ </FilterDrawer.Section>+ </Show>++ {/* Created by section for Tasks and Files */}+ <Show when={showCreatedByFilter()}>+ <FilterDrawer.Section+ value="created-by"+ label="Created by"+ activeCount={createdByIds().length}+ >+ <div class="flex items-center gap-2 px-3 py-2 muted bg-surface mb-px">+ <SearchIcon class="size-3.5 text-ink-muted shrink-0" />+ <input+ type="text"+ aria-label="Search creators"+ value={createdBySearch()}+ onInput={(e) => setCreatedBySearch(e.currentTarget.value)}+ placeholder="Search creators..."+ class="flex-1 bg-transparent text-sm outline-none placeholder:text-ink-placeholder"+ /></div>- </Show>- </MobileDrawer.Content>- </MobileDrawer.Portal>- </MobileDrawer>+ <div class="max-h-[calc(50*var(--dvh))] overflow-y-auto scrollbar-hidden">+ <For each={filteredCreatedByOptions()}>+ {(option) => {+ const active = () => createdByIds().includes(option.id);+ return (+ <button+ type="button"+ role="checkbox"+ aria-checked={active()}+ class="w-full flex items-center gap-3 px-4 py-2.5 text-sm hover:bg-hover transition-colors text-left bg-surface not-last:mb-px"+ onClick={() => toggleCreatedBy(option.id)}+ >+ <span+ class={cn(+ 'size-4 flex items-center justify-center shrink-0 rounded border transition-colors',+ active() ? 'bg-accent border-accent' : 'border-edge'+ )}+ >+ <Show when={active()}>+ <CheckIcon class="size-2.5 text-surface" />+ </Show>+ </span>+ <span class="size-4 flex items-center justify-center shrink-0">+ {option.icon()}+ </span>+ <span+ class={cn(+ 'flex-1 truncate',+ active() ? 'text-ink' : 'text-ink-muted'+ )}+ >+ {option.label}+ </span>+ </button>+ );+ }}+ </For>+ </div>+ <Show when={filteredCreatedByOptions().length === 0}>+ <div class="px-4 py-2 text-sm text-ink-muted">No results</div>+ </Show>+ </FilterDrawer.Section>+ </Show>+ </Accordion>+ </FilterDrawer></Show>);};diff --git a/apps/web/src/features/property/tags/tag-sets-context.tsx b/apps/web/src/features/property/tags/tag-sets-context.tsxindex ed002ddc39..68117315b6 100644--- a/apps/web/src/features/property/tags/tag-sets-context.tsx+++ b/apps/web/src/features/property/tags/tag-sets-context.tsx@@ -41,7 +41,9 @@ export const TagSetsProvider: FlowComponent<{ tagSets: TagSets }> = (props) => {/** Explicit query-owning adapter for standalone tag-aware lists. */export const TagSetsQueryProvider: FlowComponent = (props) => {const tagsQuery = useTagsQuery();- const tagSets = (): TagSetResponse[] => tagsQuery.data ?? [];+ // Avoid suspending on a cold query, but retain cached tags after refetch errors.+ const tagSets = (): TagSetResponse[] =>+ tagsQuery.isPending ? [] : (tagsQuery.data ?? []);return <TagSetsProvider tagSets={tagSets}>{props.children}</TagSetsProvider>;};diff --git a/apps/web/src/features/tasks-view/components/TasksFilterDrawer.tsx b/apps/web/src/features/tasks-view/components/TasksFilterDrawer.tsxindex 42ed9f375f..10588b4525 100644--- a/apps/web/src/features/tasks-view/components/TasksFilterDrawer.tsx+++ b/apps/web/src/features/tasks-view/components/TasksFilterDrawer.tsx@@ -1,13 +1,8 @@+import { MobileFilterDrawer } from '@app/components/view-shell/MobileFilterDrawer';import { MobileDrawer } from '@components/app/mobile/MobileDrawer';-import { pressPulse } from '@components/app/mobile/pressPulse';-import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';import { Accordion } from '@kobalte/core/accordion';-import CaretDownIcon from '@phosphor/caret-down.svg';import CheckIcon from '@phosphor/check.svg';-import XIcon from '@phosphor/x.svg';-import SlidersHorizontalIcon from '@phosphor-icons/core/regular/sliders-horizontal.svg?component-solid';-import { Button, cn } from '@ui';-import { createMemo, createSignal, For, Show } from 'solid-js';+import { createMemo, For, Show } from 'solid-js';import { TASK_GROUP_OPTIONS, TASK_SORT_OPTIONS } from '../constants';import { useTaskFilters } from '../filters/use-task-filters';import { useTasksView } from '../tasks-view-context';@@ -15,212 +10,111 @@ import { useTasksView } from '../tasks-view-context';export function TasksFilterDrawer() {const { state, setPrimarySort, setState } = useTasksView();const filters = useTaskFilters();- const [scrollRef, setScrollRef] = createSignal<HTMLElement>();const primarySort = () => state.sort[0]?.id ?? 'updated_at';return (- <MobileDrawer- side="bottom"- preventScroll={false}- preventScrollbarShift={false}- breakPoints={[0.85]}+ <MobileFilterDrawer+ triggerLabel="Open task filters"+ label="Task list controls"+ activeCount={filters.activeCount()}+ onClear={filters.clear}>- <MobileDrawer.Trigger- as={Button}- aria-label="Open task filters"- variant="ghost"- size="sm"- depth={3}- class="island pointer-events-auto relative size-10 shrink-0 rounded-full bg-chrome"- ref={pressPulse}- >- <SlidersHorizontalIcon class="size-6" />- <Show when={filters.activeCount() > 0}>- <span class="pointer-events-none absolute -top-0.5 right-0 z-10 flex size-4 translate-x-1/2 items-center justify-center rounded-full bg-accent text-xxs font-medium leading-none text-surface">- {filters.activeCount()}- </span>- </Show>- </MobileDrawer.Trigger>-- <MobileDrawer.Portal>- <MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />- <MobileDrawer.Content aria-label="Task list controls" class="h-[80vh]">- <MobileDrawer.Handle class="pb-1" />+ <MobileDrawer.Label id="task-sort-label" class="pt-4">+ Sort+ </MobileDrawer.Label>+ <MobileDrawer.Section role="radiogroup" aria-labelledby="task-sort-label">+ <For each={TASK_SORT_OPTIONS}>+ {(option) => {+ const selected = () => primarySort() === option.id;- <div class="relative min-h-0 flex-1">- <ScrollIndicators scrollRef={scrollRef} noBorderStart noBorderEnd />- <div- ref={setScrollRef}- class="h-full overflow-y-auto pb-1 scrollbar-hidden"- >- <MobileDrawer.Label id="task-sort-label" class="pt-4">- Sort- </MobileDrawer.Label>- <MobileDrawer.Section- role="radiogroup"- aria-labelledby="task-sort-label"+ return (+ <button+ type="button"+ role="radio"+ aria-checked={selected()}+ class="flex w-full items-center gap-3 bg-surface px-3 py-2.5 text-left text-sm transition-colors not-last:border-edge-muted not-last:border-b hover:bg-hover"+ onClick={() => setPrimarySort(option.id)}>- <For each={TASK_SORT_OPTIONS}>- {(option) => {- const selected = () => primarySort() === option.id;-- return (- <button- type="button"- role="radio"- aria-checked={selected()}- class="flex w-full items-center gap-3 bg-surface px-3 py-2.5 text-left text-sm transition-colors not-last:border-edge-muted not-last:border-b hover:bg-hover"- onClick={() => setPrimarySort(option.id)}- >- <span class="min-w-0 flex-1 truncate">- {option.label}- </span>- <Show when={selected()}>- <CheckIcon class="size-3.5 shrink-0 text-accent" />- </Show>- </button>- );- }}- </For>- </MobileDrawer.Section>+ <span class="min-w-0 flex-1 truncate">{option.label}</span>+ <Show when={selected()}>+ <CheckIcon class="size-3.5 shrink-0 text-accent" />+ </Show>+ </button>+ );+ }}+ </For>+ </MobileDrawer.Section>- <MobileDrawer.Label id="task-group-label" class="pt-4">- Group- </MobileDrawer.Label>- <MobileDrawer.Section- role="radiogroup"- aria-labelledby="task-group-label"- >- <For each={TASK_GROUP_OPTIONS}>- {(option) => {- const selected = () => state.groupBy === option.id;-- return (- <button- type="button"- role="radio"- aria-checked={selected()}- class="flex w-full items-center gap-3 bg-surface px-3 py-2.5 text-left text-sm transition-colors not-last:border-edge-muted not-last:border-b hover:bg-hover"- onClick={() => setState('groupBy', option.id)}- >- <span class="min-w-0 flex-1 truncate">- {option.label}- </span>- <Show when={selected()}>- <CheckIcon class="size-3.5 shrink-0 text-accent" />- </Show>- </button>- );- }}- </For>- </MobileDrawer.Section>+ <MobileDrawer.Label id="task-group-label" class="pt-4">+ Group+ </MobileDrawer.Label>+ <MobileDrawer.Section+ role="radiogroup"+ aria-labelledby="task-group-label"+ >+ <For each={TASK_GROUP_OPTIONS}>+ {(option) => {+ const selected = () => state.groupBy === option.id;- <MobileDrawer.Label class="pt-4">Filters</MobileDrawer.Label>- <Accordion- multiple- collapsible- defaultValue={[filters.groups()[0]?.id ?? 'status']}+ return (+ <button+ type="button"+ role="radio"+ aria-checked={selected()}+ class="flex w-full items-center gap-3 bg-surface px-3 py-2.5 text-left text-sm transition-colors not-last:border-edge-muted not-last:border-b hover:bg-hover"+ onClick={() => setState('groupBy', option.id)}>- <div class="flex flex-col gap-3">- <For each={filters.groups()}>- {(group) => {- const activeCount = createMemo(- () =>- group.options.filter((option) =>- filters.isSelected(group.id, option.id)- ).length- );-- return (- <MobileDrawer.Section- as={Accordion.Item}- value={group.id}- >- <Accordion.Header>- <Accordion.Trigger class="group flex w-full items-center justify-between border-edge-muted border-b bg-surface p-3 text-sm text-ink outline-none transition-colors hover:bg-hover">- <span class="font-medium">{group.label}</span>- <div class="flex items-center gap-2">- <Show when={activeCount() > 0}>- <span class="group-data-expanded:hidden flex size-4 items-center justify-center rounded-full bg-accent text-xxs font-medium leading-none text-surface">- {activeCount()}- </span>- </Show>- <CaretDownIcon class="size-3.5 text-ink-muted transition-transform duration-200 group-data-expanded:rotate-180" />- </div>- </Accordion.Trigger>- </Accordion.Header>+ <span class="min-w-0 flex-1 truncate">{option.label}</span>+ <Show when={selected()}>+ <CheckIcon class="size-3.5 shrink-0 text-accent" />+ </Show>+ </button>+ );+ }}+ </For>+ </MobileDrawer.Section>- <Accordion.Content>- <For each={group.options}>- {(option) => {- const selected = () =>- filters.isSelected(group.id, option.id);+ <MobileDrawer.Label class="pt-4">Filters</MobileDrawer.Label>+ <Accordion+ multiple+ collapsible+ defaultValue={[filters.groups()[0]?.id ?? 'status']}+ >+ <div class="flex flex-col gap-3">+ <For each={filters.groups()}>+ {(group) => {+ const activeCount = createMemo(+ () =>+ group.options.filter((option) =>+ filters.isSelected(group.id, option.id)+ ).length+ );- return (- <button- type="button"- role="checkbox"- aria-checked={selected()}- class="flex w-full items-center gap-3 bg-surface px-3 py-2.5 text-left text-sm transition-colors not-last:border-edge-muted not-last:border-b hover:bg-hover"- onClick={() =>- filters.setSelected(- group.id,- option.id,- !selected()- )- }- >- <span- class={cn(- 'flex size-4 shrink-0 items-center justify-center border transition-colors',- selected()- ? 'border-accent bg-accent'- : 'border-edge'- )}- >- <Show when={selected()}>- <CheckIcon class="size-2.5 text-surface" />- </Show>- </span>- <Show when={option.icon}>- {(icon) => (- <span class="flex size-4 shrink-0 items-center justify-center">- {icon()()}- </span>- )}- </Show>- <span class="min-w-0 flex-1 truncate">- {option.label}- </span>- </button>- );- }}- </For>- </Accordion.Content>- </MobileDrawer.Section>- );- }}+ return (+ <MobileFilterDrawer.Section+ value={group.id}+ label={group.label}+ activeCount={activeCount()}+ >+ <For each={group.options}>+ {(option) => (+ <MobileFilterDrawer.Option+ checked={filters.isSelected(group.id, option.id)}+ onChange={(checked) =>+ filters.setSelected(group.id, option.id, checked)+ }+ icon={option.icon?.()}+ >+ {option.label}+ </MobileFilterDrawer.Option>+ )}</For>- </div>- </Accordion>- </div>- </div>-- <Show when={filters.activeCount() > 0}>- <div class="shrink-0 border-edge-muted border-t p-2">- <Button- variant="outline"- size="sm"- class="min-h-10 rounded-lg bg-active"- onClick={filters.clear}- >- <XIcon class="size-3" />- Clear all- </Button>- </div>- </Show>- </MobileDrawer.Content>- </MobileDrawer.Portal>- </MobileDrawer>+ </MobileFilterDrawer.Section>+ );+ }}+ </For>+ </div>+ </Accordion>+ </MobileFilterDrawer>);}diff --git a/apps/web/src/features/tasks-view/components/TasksHeader.tsx b/apps/web/src/features/tasks-view/components/TasksHeader.tsxindex bb4ed62eec..1089f994b9 100644--- a/apps/web/src/features/tasks-view/components/TasksHeader.tsx+++ b/apps/web/src/features/tasks-view/components/TasksHeader.tsx@@ -13,7 +13,12 @@ import { TasksControls } from './TasksControls';import { TasksMobileTabs } from './TasksMobileTabs';import { TasksNavigation } from './TasksSidebar';-export function TasksHeader() {+export type TasksHeaderProps = {+ /** Restores list focus when Escape leaves the search field. */+ onSearchEscape?: () => void;+};++export function TasksHeader(props: TasksHeaderProps) {const panel = useSplitPanelOrThrow();const layout = useSplitLayout();const { state, setState } = useTasksView();@@ -98,6 +103,7 @@ export function TasksHeader() {value={state.search}hotkey="cmd+f"onValueChange={(search) => setState('search', search)}+ onEscape={props.onSearchEscape}placeholder="Search tasks"class="max-w-md flex-1"/>diff --git a/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx b/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsxindex 9e4a8eda28..42237975a0 100644--- a/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx+++ b/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx@@ -17,6 +17,8 @@ export function TasksMobileTabs() {<div class="h-10 min-w-0 flex-1"><PillTabsscrollable+ class="-ml-(--mobile-chrome-gutter) w-[calc(100%+2*var(--mobile-chrome-gutter))] max-w-none flex-none"+ contentClass="px-(--mobile-chrome-gutter)"leading={<TasksFilterDrawer />}items={items()}value={state.tab}diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsxindex d1865d5bbc..97055f1a2f 100644--- a/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx+++ b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx@@ -42,8 +42,8 @@ import CaretDownIcon from '@phosphor/caret-down.svg';import CheckIcon from '@phosphor/check.svg';import SpinnerIcon from '@phosphor/spinner.svg';import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property';+import { useTagSets } from '@property/tags/tag-sets-context';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';-import { useTagsQuery } from '@queries/properties/tags';import { EntityType } from '@service-properties/generated/schemas/entityType';import { Button, cn, Surface } from '@ui';import {@@ -99,7 +99,12 @@ type TasksListActivationMetadata = {newSplit?: boolean;};-export function TaskList() {+export type TaskListProps = {+ /** The focusable list root, for callers that hand keyboard focus back. */+ ref?: (element: HTMLDivElement) => void;+};++export function TaskList(props: TaskListProps) {const panel = useSplitPanelOrThrow();const { state, setState } = useTasksView();const userId = useUserId();@@ -116,15 +121,14 @@ export function TaskList() {const toggleGroup = (groupId: string) =>setState('collapsedGroupIds', toggleValue(groupId));- const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () => {- const tagsQuery = useTagsQuery();-- return useTasksDataSource(state, {+ const tagSets = useTagSets();+ const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () =>+ useTasksDataSource(state, {userId,- tagSets: () => tagsQuery.data ?? [],+ tagSets,isGroupExpanded,- });- });+ })+ );function openEntity(entity: EntityData,@@ -426,7 +430,10 @@ export function TaskList() {<Surfacedepth={isTouchDevice() ? 0 : 2}hideBorder={isTouchDevice()}- ref={setGrid}+ ref={(element: HTMLDivElement) => {+ setGrid(element);+ props.ref?.(element);+ }}role="grid"aria-label="Tasks"aria-multiselectable="true"diff --git a/apps/web/src/features/tasks-view/tasks-view.tsx b/apps/web/src/features/tasks-view/tasks-view.tsxindex 8cccce7b1c..828f5571a6 100644--- a/apps/web/src/features/tasks-view/tasks-view.tsx+++ b/apps/web/src/features/tasks-view/tasks-view.tsx@@ -5,7 +5,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import { ListEntityMetadataQueryProvider } from '@entity';import SpinnerIcon from '@phosphor/spinner.svg';import { cn, Surface } from '@ui';-import { onMount, Suspense } from 'solid-js';+import { createSignal, onMount, Suspense } from 'solid-js';import { TasksHeader } from './components/TasksHeader';import { TasksSidebar } from './components/TasksSidebar';import { TaskList } from './components/task-list/TaskList';@@ -34,6 +34,7 @@ function TasksListFallback() {function TasksViewRoot() {const panel = useSplitPanelOrThrow();+ const [listElement, setListElement] = createSignal<HTMLDivElement>();onMount(() => panel.handle.setDisplayName('Tasks'));@@ -51,11 +52,11 @@ function TasksViewRoot() {</ViewShell.Aside><ViewShell.Main><ViewShell.Header>- <TasksHeader />+ <TasksHeader onSearchEscape={() => listElement()?.focus()} /></ViewShell.Header><ViewShell.Content><Suspense fallback={<TasksListFallback />}>- <TaskList />+ <TaskList ref={setListElement} /></Suspense></ViewShell.Content></ViewShell.Main>diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex 9e9ac63d0e..722880ff4b 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -70,6 +70,8 @@ category, Esc closes.- `c` then `d`/`t`/`e`/`m`/`a` — create doc / task / email / channel / AI chat.Single-letter shortcuts only work when no editor has focus; press `Escape` first.- `/` — search everything. `j`/`k` — move in lists. `e` — mark done. `g` then `i` — inbox.+- In Email and Tasks search, `Escape` returns focus to the list and keeps the query.+ Use the search field's clear button to clear it.- Splits: `` ` `` split, `Shift+H`/`Shift+L` move focus, `Shift+Esc` maximize.- In any text surface: `@` mentions (bidirectional links), `#` tags, `/` block commands,`:` emoji. Clicking a rendered tag opens a Search split filtered to that tag.diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 5c927948b5..e88d67f650 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -45,6 +45,15 @@ Full email client. Tabs: `Signal` / `Noise` / `Sent` / `Calendar` / `Drafts` / `shows `Connect your email` (Gmail/Google Workspace OAuth) — most functionality needs aconnected account. Search is `Ctrl+F` within the surface.+With the new app views enabled, mobile and tablet Email use a floating, horizontally+scrolling row of those tabs, with `Open email filters` at the left. The rest of the+view is the email list, which scrolls beneath the header and supports pull to refresh+and swiping left to mark emails done in Signal and Noise. The filter button opens a+bottom drawer for status, done, attachment and calendar filters, plus the inbox+selector when available. `Clear all`+resets those filters and the inbox selection. Desktop keeps its sidebar, search field,+filter menu and preview control.+## SearchSidebar `Search` button → `/app/.../component/search` with a focused query box. Results