Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: new app view primitives and components (#6003)

dev-rb9f771d153a80
diff --git a/apps/web/src/components/app/PreviewPanel.tsx b/apps/web/src/components/app/PreviewPanel.tsx
new file mode 100644
index 0000000000..c63ed01ce7
--- /dev/null
+++ b/apps/web/src/components/app/PreviewPanel.tsx
@@ -0,0 +1,246 @@
+import {
+ getChannelEntityTarget,
+ navigateChannelEntityToTarget,
+ reminderSplitTarget,
+} from '@app/features/next-soup/utils';
+import { CALENDAR_BLOCK_ID } from '@block-calendar/types';
+import { getChannelParams } from '@block-channel/utils/link';
+import type { BlockAliasContext, BlockName } from '@core/block';
+import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';
+import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';
+import type { BlockOrchestrator } from '@core/orchestrator';
+import {
+ type EntityData,
+ isGithubPrEntity,
+ isSnippetEntity,
+ isTaskEntity,
+} from '@entity';
+import { createContextProvider } from '@solid-primitives/context';
+import {
+ createMemo,
+ createRenderEffect,
+ createSignal,
+ on,
+ Show,
+ Suspense,
+ untrack,
+} from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+import { match, P } from 'ts-pattern';
+import {
+ SplitPanelContext,
+ type SplitPanelContextType,
+} from './split-layout/context';
+
+export const [PreviewPanelContext, useMaybePreviewPanel] =
+ createContextProvider(
+ (props: { previewEntity: EntityData; onFocusOut?: VoidFunction }) => ({
+ previewEntity: () => props.previewEntity,
+ onFocusOut: () => props.onFocusOut?.(),
+ })
+ );
+
+export type PreviewPanelProps = {
+ selectedEntity: EntityData | undefined;
+ orchestrator: BlockOrchestrator;
+ splitPanelContext: SplitPanelContextType;
+ onFocusOut?: VoidFunction;
+ ref?: (el: HTMLElement) => void;
+};
+
+type PreviewBlockTarget = {
+ blockType: BlockName;
+ blockId: string;
+ aliasContext: BlockAliasContext | undefined;
+};
+
+function PreviewPanelContent(
+ props: PreviewPanelProps & { selectedEntity: EntityData }
+) {
+ const scopedLayoutRefs: SplitPanelContextType['layoutRefs'] = {};
+ const selectedEntityId = createMemo(() => props.selectedEntity.id);
+ const [interactedWith, setInteractedWith] = createSignal(false);
+
+ const blockInstance = createMemo(() => {
+ const entity = props.selectedEntity;
+
+ const target = match(entity)
+ .returnType<PreviewBlockTarget>()
+ .when(isTaskEntity, (task) => ({
+ blockType: fileTypeToResolvedBlockName(task.fileType),
+ blockId: task.id,
+ aliasContext: {
+ alias: 'task',
+ baseType: 'md',
+ } satisfies BlockAliasContext,
+ }))
+ .when(isSnippetEntity, (snippet) => ({
+ blockType: fileTypeToResolvedBlockName(snippet.fileType),
+ blockId: snippet.id,
+ aliasContext: {
+ alias: 'snippet',
+ baseType: 'md',
+ } satisfies BlockAliasContext,
+ }))
+ .with({ type: 'document' }, (document) => ({
+ blockType: fileTypeToResolvedBlockName(document.fileType),
+ blockId: document.id,
+ aliasContext: undefined,
+ }))
+ .with(
+ { type: P.union('channel_message', 'channel_thread') },
+ (message) => ({
+ blockType: 'channel',
+ blockId: message.channelId,
+ aliasContext: undefined,
+ })
+ )
+ .with({ type: 'foreign' }, (foreignEntity) => ({
+ blockType:
+ USE_MACRO_PR_SUMMARY_BLOCK && isGithubPrEntity(foreignEntity)
+ ? 'pr'
+ : 'unknown',
+ blockId: foreignEntity.id,
+ aliasContext: undefined,
+ }))
+ .with({ type: 'crm_company' }, (company) => ({
+ blockType: 'company',
+ blockId: company.id,
+ aliasContext: undefined,
+ }))
+ .with({ type: 'crm_contact' }, (contact) => ({
+ blockType: 'contact',
+ blockId: contact.id,
+ aliasContext: undefined,
+ }))
+ .with({ type: 'calendar_event' }, () => ({
+ blockType: 'calendar',
+ blockId: CALENDAR_BLOCK_ID,
+ aliasContext: undefined,
+ }))
+ .with({ type: 'reminder' }, (reminder) => {
+ const reminderTarget = reminderSplitTarget(reminder);
+ return {
+ blockType: fileTypeToResolvedBlockName(reminderTarget?.type),
+ blockId: reminderTarget?.id ?? reminder.id,
+ aliasContext: undefined,
+ };
+ })
+ .otherwise((fallbackEntity) => ({
+ blockType: fileTypeToResolvedBlockName(fallbackEntity.type),
+ blockId: fallbackEntity.id,
+ aliasContext: undefined,
+ }));
+
+ const channelTarget =
+ target.blockType === 'channel'
+ ? untrack(() => getChannelEntityTarget(entity))
+ : undefined;
+
+ return props.orchestrator.createBlockInstance(
+ target.blockType,
+ target.blockId,
+ {
+ aliasContext: target.aliasContext,
+ params:
+ channelTarget?.kind === 'message'
+ ? getChannelParams(channelTarget.messageId, channelTarget.threadId)
+ : undefined,
+ }
+ );
+ });
+
+ createRenderEffect(
+ on(selectedEntityId, () => {
+ setInteractedWith(false);
+ void navigateChannelEntityToTarget(
+ props.selectedEntity,
+ props.orchestrator
+ );
+ })
+ );
+
+ return (
+ <div
+ ref={props.ref}
+ class="flex size-full min-h-0 flex-col"
+ onFocusIn={(event) => {
+ if (interactedWith()) return;
+ if (event.target.hasAttribute('data-allow-focus-in-preview')) {
+ setInteractedWith(true);
+ return;
+ }
+ const relatedTarget = event.relatedTarget;
+ if (
+ relatedTarget instanceof HTMLElement &&
+ !event.currentTarget.contains(relatedTarget)
+ ) {
+ relatedTarget.focus();
+ } else {
+ (event.target as HTMLElement).blur?.();
+ }
+ }}
+ onPointerDown={() => setInteractedWith(true)}
+ tabIndex={-1}
+ >
+ <div class="relative flex min-h-10 w-full shrink-0 items-center justify-between bg-surface px-2">
+ <div
+ class="flex h-full items-center gap-1"
+ ref={(ref) => {
+ scopedLayoutRefs.headerLeft = ref;
+ }}
+ />
+ <div
+ class="flex h-full items-center gap-1"
+ ref={(ref) => {
+ scopedLayoutRefs.headerRight = ref;
+ }}
+ />
+ </div>
+ <div class="relative flex min-h-0 w-full shrink-0 items-center justify-between bg-surface px-2">
+ <div
+ class="flex h-full items-center gap-1"
+ ref={(ref) => {
+ scopedLayoutRefs.toolbarLeft = ref;
+ }}
+ />
+ <div
+ class="flex h-full items-center gap-1"
+ ref={(ref) => {
+ scopedLayoutRefs.toolbarRight = ref;
+ }}
+ />
+ </div>
+ <div class="min-h-0 flex-1">
+ <SplitPanelContext.Provider
+ value={{
+ ...props.splitPanelContext,
+ layoutRefs: scopedLayoutRefs,
+ }}
+ >
+ <PreviewPanelContext
+ previewEntity={props.selectedEntity}
+ onFocusOut={props.onFocusOut}
+ >
+ <Suspense>
+ <Dynamic component={blockInstance().element} />
+ </Suspense>
+ </PreviewPanelContext>
+ </SplitPanelContext.Provider>
+ </div>
+ </div>
+ );
+}
+
+/** Renders a selected entity's actual block inside an inline preview surface. */
+export function PreviewPanel(props: PreviewPanelProps) {
+ return (
+ <div class="flex size-full min-h-0">
+ <Show when={props.selectedEntity}>
+ {(selectedEntity) => (
+ <PreviewPanelContent {...props} selectedEntity={selectedEntity()} />
+ )}
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 5ae966fef2..d025080fb9 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -88,13 +88,16 @@ function mergeClientFilters(
};
}
-export type UnifiedListMeta = {
+export type ComponentMeta = {
+ kind?: string;
+ splitPanelLayout?: 'legacy' | 'composable';
+};
+
+export type UnifiedListMeta = ComponentMeta & {
kind: 'unified-list';
viewId: ViewId;
};
-export type ComponentMeta = UnifiedListMeta | { kind?: undefined };
-
export type ComponentMetaMap = {
'unified-list': UnifiedListMeta;
};
@@ -106,13 +109,16 @@ type ComponentRegistration = {
const REGISTRY = new Map<string, ComponentRegistration>();
-function registerComponent<T extends Omit<ComponentMeta, 'kind'>>(
+function registerComponent<TMeta extends Record<string, unknown>>(
name: string,
factory: ComponentFactory,
- initialMeta?: T
+ initialMeta?: TMeta
) {
const metaWithKind = initialMeta ? { kind: name, ...initialMeta } : undefined;
- REGISTRY.set(name, { factory, initialMeta: metaWithKind as ComponentMeta });
+ REGISTRY.set(name, {
+ factory,
+ initialMeta: metaWithKind as ComponentMeta,
+ });
}
type ResolvedComponent = {
diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
index bd29c6a67d..e0edd3ce93 100644
--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
@@ -45,6 +45,7 @@ import { Portal } from 'solid-js/web';
import { splitBackInterceptor } from '../back-interceptor';
import { SplitLayoutContext, SplitPanelContext } from '../context';
import type { SplitContent } from '../layoutManager';
+import { shouldShowSplitCloseButton } from '../layoutUtils';
import { canSpotlight } from '../utils/canSpotlight';
import { HeaderIsland } from './HeaderIsland';
import {
@@ -204,22 +205,8 @@ function SplitCloseButton() {
return isOnlySplit && isNotUnifiedList ? 'Return to list' : 'Close';
});
- // A Viewer has no close affordance or close hotkey: it closes with its
- // Controller, when its Preview Pair dissolves (external navigation or the
- // Controller leaving its list view), or via the preview toggle.
- const isPreviewViewer = () => context.handle.isViewerSplit();
-
- // A Preview Pair occupies two split slots but is a single logical split: its
- // Viewer isn't independently closable. Subtract one slot per pair so that
- // when the only splits open are a single Preview Pair, the Controller hides
- // its close button — just like a lone split does.
- const hasMultipleSplits = createMemo(
- () =>
- layout.manager.splits().length - layout.manager.previewPairs().length > 1
- );
-
return (
- <Show when={hasMultipleSplits() && !isPreviewViewer()}>
+ <Show when={shouldShowSplitCloseButton(layout.manager, context.handle)}>
<Button
square
size="sm"
diff --git a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
index 54b99d5c92..57d8a7187c 100644
--- a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
@@ -4,6 +4,7 @@ import { SoupContextProvider } from '@app/features/next-soup/soup-context';
import { SoupViewContextProvider } from '@app/features/next-soup/soup-view/soup-view-context';
import { globalSplitManager } from '@app/signal/splitLayout';
import { MobileTopEdgeFade } from '@components/app/mobile/MobileEdgeFade';
+import { SplitPanelControllerProvider } from '@components/app/split-panel';
import { isSoloSettings } from '@core/constant/SettingsState';
import { BlockOpenTrackingDelayContext } from '@core/context/blockOpenTracking';
import { splitContainerAttribute } from '@core/dom-selectors';
@@ -24,6 +25,7 @@ import {
Suspense,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
+import { splitBackInterceptor } from '../back-interceptor';
import {
type SplitBottomPanelRegistration,
type SplitFileMenuActionGroups,
@@ -32,6 +34,7 @@ import {
} from '../context';
import { useSplitLayout } from '../layout';
import type { SplitHandle, SplitState } from '../layoutManager';
+import { shouldShowSplitCloseButton } from '../layoutUtils';
import { registerSplitHotkeys } from '../registerSplitHotkeys';
import { createPriorityCollapseController } from './PriorityCollapseOverflowSensor';
import { SplitDrawerGroup } from './SplitDrawerContext';
@@ -218,6 +221,46 @@ export function SplitPanel(props: SplitPanelProps) {
const activeId = manager.activeSplitId();
return activeId === props.split.id || activeId === peerId;
});
+
+ const usesComposableLayout = () =>
+ props.split.mount.kind === 'component' &&
+ props.split.mount.meta.splitPanelLayout === 'composable';
+
+ const MountedContent = () => (
+ <SplitPanelControllerProvider
+ controller={{
+ canGoBack: props.handle.canGoBack,
+ goBack: () => {
+ if (splitBackInterceptor()?.()) return;
+ props.handle.goBack();
+ },
+ canGoForward: props.handle.canGoForward,
+ goForward: props.handle.goForward,
+ canClose: () => {
+ const manager = globalSplitManager();
+ return manager
+ ? shouldShowSplitCloseButton(manager, props.handle)
+ : false;
+ },
+ close: props.handle.close,
+ }}
+ >
+ <Suspense>
+ <SoupViewContextProvider soup={nextSoup}>
+ <BlockOpenTrackingDelayContext.Provider
+ value={
+ props.handle.isViewerSplit()
+ ? PREVIEW_VIEWER_OPEN_TRACK_DELAY_MS
+ : 0
+ }
+ >
+ <Dynamic component={props.split.mount.element} />
+ </BlockOpenTrackingDelayContext.Provider>
+ </SoupViewContextProvider>
+ </Suspense>
+ </SplitPanelControllerProvider>
+ );
+
return (
<SoupContextProvider soup={nextSoup}>
<SplitPanelContext.Provider
@@ -316,83 +359,85 @@ export function SplitPanel(props: SplitPanelProps) {
)}
depth={isTouchDevice() ? 0 : 1}
>
- <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>
+ <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>
+ <Panel.Toolbar
+ class={cn(
+ 'items-start overflow-visible',
+ !hasToolbarContent() && 'hidden',
+ isTouchDevice() && 'hidden',
+ 'border-b-0'
+ )}
+ >
+ <SplitToolbar
+ ref={setToolbarRef}
+ collapseController={toolbarCollapseController}
+ />
+ </Panel.Toolbar>
- <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'
- )}
- >
- <Suspense>
- <SoupViewContextProvider soup={nextSoup}>
- <BlockOpenTrackingDelayContext.Provider
- value={
- props.handle.isViewerSplit()
- ? PREVIEW_VIEWER_OPEN_TRACK_DELAY_MS
- : 0
- }
+ <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'
+ )}
>
- <Dynamic component={props.split.mount.element} />
- </BlockOpenTrackingDelayContext.Provider>
- </SoupViewContextProvider>
- </Suspense>
- </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-content-secondary">
- {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()}
+ <MountedContent />
</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-content-secondary">
+ {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>
- )}
- </Show>
+ <MobileTopEdgeFade />
+ </Panel.Body>
+ </>
+ }
+ >
+ <div
+ class="size-full min-h-0 min-w-0 overflow-hidden"
+ style={{ 'grid-area': '1 / 1 / -1 / -1' }}
+ >
+ <MountedContent />
</div>
- <MobileTopEdgeFade />
- </Panel.Body>
+ </Show>
</Panel>
</div>
</SplitDrawerGroup>
diff --git a/apps/web/src/components/app/split-layout/entry-persistence.ts b/apps/web/src/components/app/split-layout/entry-persistence.ts
new file mode 100644
index 0000000000..824bc60f43
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/entry-persistence.ts
@@ -0,0 +1,48 @@
+import type { PersistenceStorage } from '@app/lib/persistence';
+import type { SplitHandle } from './layoutManager';
+
+export type EntryPersistenceHandle = Pick<
+ SplitHandle,
+ 'currentEntryState' | 'registerEntryStateCaptor'
+>;
+
+export type CreateEntryPersistenceStorageOptions<TState, TStored> = {
+ handle: EntryPersistenceHandle;
+ key: string;
+ restore: (current: TState, stored: unknown) => TState | undefined;
+ select: (state: TState) => TStored;
+};
+
+/**
+ * Adapts a split history entry to persistence storage.
+ *
+ * TODO: Replace the split layout's captor pattern with direct entry-state
+ * persistence.
+ *
+ * Writes update a deferred capture value. The split manager commits that
+ * value to the current history entry immediately before navigation.
+ */
+export function createEntryPersistenceStorage<TState, TStored>(
+ options: CreateEntryPersistenceStorageOptions<TState, TStored>
+): PersistenceStorage<TState> {
+ let captured: TStored | undefined;
+ const dispose = options.handle.registerEntryStateCaptor(
+ options.key,
+ () => captured
+ );
+ const update = (state: TState) => {
+ captured = options.select(state);
+ };
+
+ return {
+ restore: (current) => {
+ const stored = options.handle.currentEntryState()?.[options.key];
+ return stored === undefined
+ ? undefined
+ : options.restore(current, stored);
+ },
+ initialize: update,
+ write: update,
+ dispose,
+ };
+}
diff --git a/apps/web/src/components/app/split-layout/layoutUtils.ts b/apps/web/src/components/app/split-layout/layoutUtils.ts
index d898437a52..5bc9c397fb 100644
--- a/apps/web/src/components/app/split-layout/layoutUtils.ts
+++ b/apps/web/src/components/app/split-layout/layoutUtils.ts
@@ -104,6 +104,19 @@ export function useSplitPanel() {
return useContext(SplitPanelContext);
}
+/**
+ * A Preview Pair occupies two slots but behaves as one logical split, and its
+ * Viewer is never independently closable.
+ */
+export function shouldShowSplitCloseButton(
+ manager: SplitManager,
+ handle: SplitHandle
+) {
+ const logicalSplitCount =
+ manager.splits().length - manager.previewPairs().length;
+ return logicalSplitCount > 1 && !handle.isViewerSplit();
+}
+
/**
* Whether content may claim focus automatically when it mounts in the current
* split. Preview Pair Viewers stay passive until the user focuses them.
diff --git a/apps/web/src/components/app/split-panel/SplitPanel.tsx b/apps/web/src/components/app/split-panel/SplitPanel.tsx
new file mode 100644
index 0000000000..9812d8cffe
--- /dev/null
+++ b/apps/web/src/components/app/split-panel/SplitPanel.tsx
@@ -0,0 +1,285 @@
+import { TOKENS } from '@core/hotkey/tokens';
+import CaretLeftIcon from '@phosphor/caret-left.svg';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import CloseIcon from '@phosphor/x.svg';
+import { Button, type ButtonProps, cn } from '@ui';
+import {
+ createContext,
+ type JSX,
+ type ParentProps,
+ Show,
+ splitProps,
+ useContext,
+} from 'solid-js';
+
+export type SplitPanelController = {
+ canGoBack: () => boolean;
+ goBack: () => void;
+ canGoForward: () => boolean;
+ goForward: () => void;
+ canClose: () => boolean;
+ close: () => void;
+};
+
+const SplitPanelControllerContext = createContext<
+ SplitPanelController | undefined
+>();
+
+export function SplitPanelControllerProvider(
+ props: ParentProps<{ controller: SplitPanelController }>
+) {
+ return (
+ <SplitPanelControllerContext.Provider value={props.controller}>
+ {props.children}
+ </SplitPanelControllerContext.Provider>
+ );
+}
+
+export function useSplitPanelController(): SplitPanelController {
+ const controller = useContext(SplitPanelControllerContext);
+ if (!controller) {
+ throw new Error(
+ 'Split panel controls require <SplitPanel.Root controller={...}>'
+ );
+ }
+ return controller;
+}
+
+type SplitPanelRootProps = JSX.HTMLAttributes<HTMLElement> & {
+ controller?: SplitPanelController;
+};
+
+/**
+ * Presentation-only frame for one split.
+ *
+ * Children stay in the consumer's DOM order. The root provides only the
+ * vertical panel boundary; consumers decide which chrome exists and how each
+ * header or toolbar lays out its contents.
+ */
+function Root(props: SplitPanelRootProps) {
+ const [local, rest] = splitProps(props, ['children', 'class', 'controller']);
+ const inheritedController = useContext(SplitPanelControllerContext);
+
+ return (
+ <SplitPanelControllerContext.Provider
+ value={local.controller ?? inheritedController}
+ >
+ <section
+ {...rest}
+ class={cn(
+ 'relative flex size-full min-h-0 min-w-0 flex-col overflow-hidden bg-panel text-ink',
+ local.class
+ )}
+ data-split-panel=""
+ >
+ {local.children}
+ </section>
+ </SplitPanelControllerContext.Provider>
+ );
+}
+
+function Header(props: JSX.HTMLAttributes<HTMLElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <header
+ {...rest}
+ class={cn(
+ 'flex min-h-10 min-w-0 shrink-0 items-center border-b border-edge-muted px-2',
+ local.class
+ )}
+ data-split-panel-header=""
+ >
+ {local.children}
+ </header>
+ );
+}
+
+function Toolbar(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class', 'role']);
+ return (
+ <div
+ {...rest}
+ role={local.role ?? 'toolbar'}
+ class={cn(
+ 'flex min-w-0 shrink-0 items-center border-b border-edge-muted p-2',
+ local.class
+ )}
+ data-split-panel-toolbar=""
+ >
+ {local.children}
+ </div>
+ );
+}
+
+function Body(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <div
+ {...rest}
+ class={cn('relative min-h-0 min-w-0 flex-1 overflow-hidden', local.class)}
+ data-split-panel-body=""
+ >
+ {local.children}
+ </div>
+ );
+}
+
+function Footer(props: JSX.HTMLAttributes<HTMLElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <footer
+ {...rest}
+ class={cn(
+ 'flex min-h-10 min-w-0 shrink-0 items-center border-t border-edge-muted px-2',
+ local.class
+ )}
+ data-split-panel-footer=""
+ >
+ {local.children}
+ </footer>
+ );
+}
+
+function ControlGroup(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <div
+ {...rest}
+ class={cn('flex min-w-0 shrink-0 items-center gap-0', local.class)}
+ data-split-panel-control-group=""
+ >
+ {local.children}
+ </div>
+ );
+}
+
+type SplitControlButtonProps = Omit<ButtonProps, 'children' | 'onClick'> & {
+ children?: JSX.Element;
+};
+
+function BackButton(props: SplitControlButtonProps) {
+ const controller = useSplitPanelController();
+ const [local, rest] = splitProps(props, [
+ 'aria-label',
+ 'children',
+ 'class',
+ 'disabled',
+ 'hotkey',
+ 'label',
+ 'size',
+ 'square',
+ 'type',
+ 'variant',
+ ]);
+ const label = () => local.label ?? 'Go back';
+
+ return (
+ <Button
+ {...rest}
+ type={local.type ?? 'button'}
+ variant={local.variant}
+ size={local.size ?? 'sm'}
+ square={local.square ?? true}
+ class={cn(
+ !local.size && 'p-1',
+ 'rounded-lg touch:active:bg-transparent',
+ local.class
+ )}
+ aria-label={local['aria-label']}
+ label={label()}
+ hotkey={local.hotkey ?? TOKENS.split.go.back}
+ disabled={Boolean(local.disabled) || !controller.canGoBack()}
+ onClick={() => controller.goBack()}
+ >
+ {local.children ?? <CaretLeftIcon />}
+ </Button>
+ );
+}
+
+function ForwardButton(props: SplitControlButtonProps) {
+ const controller = useSplitPanelController();
+ const [local, rest] = splitProps(props, [
+ 'aria-label',
+ 'children',
+ 'class',
+ 'disabled',
+ 'hotkey',
+ 'label',
+ 'size',
+ 'square',
+ 'type',
+ 'variant',
+ ]);
+ const label = () => local.label ?? 'Go forward';
+
+ return (
+ <Button
+ {...rest}
+ type={local.type ?? 'button'}
+ variant={local.variant}
+ size={local.size ?? 'sm'}
+ square={local.square ?? true}
+ class={cn(
+ !local.size && 'p-1',
+ 'rounded-lg touch:active:bg-transparent',
+ local.class
+ )}
+ aria-label={local['aria-label']}
+ label={label()}
+ hotkey={local.hotkey ?? TOKENS.split.go.forward}
+ disabled={Boolean(local.disabled) || !controller.canGoForward()}
+ onClick={() => controller.goForward()}
+ >
+ {local.children ?? <CaretRightIcon />}
+ </Button>
+ );
+}
+
+function CloseButton(props: SplitControlButtonProps) {
+ const controller = useSplitPanelController();
+ const [local, rest] = splitProps(props, [
+ 'aria-label',
+ 'children',
+ 'class',
+ 'disabled',
+ 'hotkey',
+ 'label',
+ 'size',
+ 'square',
+ 'type',
+ 'variant',
+ ]);
+ const label = () => local.label ?? 'Close';
+
+ return (
+ <Show when={controller.canClose()}>
+ <Button
+ {...rest}
+ type={local.type ?? 'button'}
+ variant={local.variant}
+ size={local.size ?? 'sm'}
+ square={local.square ?? true}
+ class={cn('rounded-lg', local.class)}
+ aria-label={local['aria-label']}
+ label={label()}
+ hotkey={local.hotkey ?? TOKENS.split.close}
+ disabled={Boolean(local.disabled)}
+ onClick={() => controller.close()}
+ >
+ {local.children ?? <CloseIcon />}
+ </Button>
+ </Show>
+ );
+}
+
+export const SplitPanel = Object.assign(Root, {
+ Root,
+ Header,
+ Toolbar,
+ Body,
+ Footer,
+ ControlGroup,
+ BackButton,
+ ForwardButton,
+ CloseButton,
+});
diff --git a/apps/web/src/components/app/split-panel/index.ts b/apps/web/src/components/app/split-panel/index.ts
new file mode 100644
index 0000000000..cb351b6dfa
--- /dev/null
+++ b/apps/web/src/components/app/split-panel/index.ts
@@ -0,0 +1,6 @@
+export {
+ SplitPanel,
+ type SplitPanelController,
+ SplitPanelControllerProvider,
+ useSplitPanelController,
+} from './SplitPanel';
diff --git a/apps/web/src/components/list/create-disclosure-state.ts b/apps/web/src/components/list/create-disclosure-state.ts
new file mode 100644
index 0000000000..7a1e9d0c4d
--- /dev/null
+++ b/apps/web/src/components/list/create-disclosure-state.ts
@@ -0,0 +1,89 @@
+import { type Accessor, createMemo, createSignal } from 'solid-js';
+import type { ListKey } from './types';
+
+export type CreateDisclosureStateOptions = {
+ /** Whether unknown keys are expanded. Defaults to false. */
+ defaultExpanded?: boolean;
+ /** Keys initially differing from `defaultExpanded`. */
+ initialToggledKeys?: Iterable<ListKey>;
+ onChange?: (toggledKeys: ReadonlySet<ListKey>) => void;
+};
+
+/** Generic expanded/collapsed state keyed independently from rendered items. */
+export type DisclosureState = {
+ defaultExpanded: boolean;
+ toggledKeys: Accessor<ReadonlySet<ListKey>>;
+ isExpanded: (key: ListKey) => boolean;
+ setExpanded: (key: ListKey, expanded: boolean) => void;
+ expand: (key: ListKey) => void;
+ collapse: (key: ListKey) => void;
+ toggle: (key: ListKey) => void;
+ replaceToggled: (keys: Iterable<ListKey>) => void;
+ /** Return every key to its default state. */
+ reset: () => void;
+};
+
+/**
+ * Tracks only keys whose disclosure state differs from the default.
+ *
+ * This works for paginated collections because the complete key universe is
+ * not required to represent "all expanded" or "all collapsed".
+ */
+export function createDisclosureState(
+ options: CreateDisclosureStateOptions = {}
+): DisclosureState {
+ const defaultExpanded = options.defaultExpanded ?? false;
+ const toggled = new Set(options.initialToggledKeys ?? []);
+ const [version, invalidate] = createSignal(undefined, { equals: false });
+
+ const toggledKeys = createMemo<ReadonlySet<ListKey>>(() => {
+ version();
+ return new Set(toggled);
+ });
+
+ const expandedWithoutTracking = (key: ListKey) =>
+ toggled.has(key) ? !defaultExpanded : defaultExpanded;
+
+ const notify = () => {
+ invalidate();
+ options.onChange?.(new Set(toggled));
+ };
+
+ const setExpanded = (key: ListKey, expanded: boolean) => {
+ const shouldToggle = expanded !== defaultExpanded;
+ if (shouldToggle === toggled.has(key)) return;
+
+ if (shouldToggle) toggled.add(key);
+ else toggled.delete(key);
+ notify();
+ };
+
+ const replaceToggled = (keys: Iterable<ListKey>) => {
+ const next = new Set(keys);
+ if (
+ next.size === toggled.size &&
+ [...next].every((key) => toggled.has(key))
+ ) {
+ return;
+ }
+
+ toggled.clear();
+ for (const key of next) toggled.add(key);
+ notify();
+ };
+
+ return {
+ defaultExpanded,
+ toggledKeys,
+ isExpanded: (key) => {
+ version();
+ return expandedWithoutTracking(key);
+ },
+ setExpanded,
+ expand: (key) => setExpanded(key, true),
+ collapse: (key) => setExpanded(key, false),
+ toggle: (key) => setExpanded(key, !expandedWithoutTracking(key)),
+ replaceToggled,
+ reset: () => replaceToggled([]),
+ };
+}
diff --git a/apps/web/src/components/list/create-list-controller.test.ts b/apps/web/src/components/list/create-list-controller.test.ts
new file mode 100644
index 0000000000..a773316067
--- /dev/null
+++ b/apps/web/src/components/list/create-list-controller.test.ts
@@ -0,0 +1,252 @@
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import { createListController } from './create-list-controller';
+
+type Item = { id: string; label: string; structural?: boolean };
+
+const item = (id: string, label = id, structural = false): Item => ({
+ id,
+ label,
+ structural,
+});
+
+const withRoot = (run: () => void) =>
+ createRoot((dispose) => {
+ try {
+ run();
+ } finally {
+ dispose();
+ }
+ });
+
+describe('createListController', () => {
+ it('derives focused and selected payloads from replacement items', () => {
+ withRoot(() => {
+ const [items, setItems] = createSignal<readonly Item[]>([
+ item('a', 'old'),
+ item('b'),
+ ]);
+ const list = createListController({
+ items,
+ getKey: (value: Item) => value.id,
+ });
+
+ list.focus.set('a');
+ list.selection.select('a');
+ setItems([item('a', 'new'), item('b')]);
+
+ expect(list.focus.item()?.label).toBe('new');
+ expect(list.selection.items().map((value) => value.label)).toEqual([
+ 'new',
+ ]);
+ });
+ });
+
+ it('retains unavailable anchors until explicit pruning', () => {
+ withRoot(() => {
+ const [items, setItems] = createSignal<readonly Item[]>([item('a')]);
+ const list = createListController({
+ items,
+ getKey: (value: Item) => value.id,
+ });
+
+ list.focus.set('a');
+ list.selection.select('a');
+ setItems([]);
+
+ expect(list.focus.requestedKey()).toBe('a');
+ expect(list.focus.key()).toBeUndefined();
+ expect([...list.selection.requestedKeys()]).toEqual(['a']);
+ expect([...list.selection.keys()]).toEqual([]);
+ expect([...list.selection.missingKeys()]).toEqual(['a']);
+
+ list.focus.prune();
+ list.selection.prune();
+ expect(list.focus.requestedKey()).toBeUndefined();
+ expect(list.selection.count()).toBe(0);
+ });
+ });
+
+ it('skips structural rows and wraps only when requested', () => {
+ withRoot(() => {
+ const values = [item('header', 'Header', true), item('a'), item('b')];
+ const list = createListController({
+ items: () => values,
+ getKey: (value: Item) => value.id,
+ isNavigable: (value) => !value.structural,
+ wrapNavigation: true,
+ });
+
+ expect(list.navigate.down()?.key).toBe('a');
+ expect(list.navigate.down()?.key).toBe('b');
+ expect(list.navigate.down()?.key).toBe('a');
+ expect(list.navigate.up()?.key).toBe('b');
+ });
+ });
+
+ it('selects ranges using only selectable items', () => {
+ withRoot(() => {
+ const values = [item('a'), item('header', 'Header', true), item('b')];
+ const list = createListController({
+ items: () => values,
+ getKey: (value: Item) => value.id,
+ isSelectable: (value) => !value.structural,
+ });
+
+ list.selection.selectRange('a', 'b');
+ expect([...list.selection.keys()].sort()).toEqual(['a', 'b']);
+ list.selection.selectRange('a', 'b', false);
+ expect(list.selection.count()).toBe(0);
+ });
+ });
+
+ it('selects logical items independently from rendered occurrences', () => {
+ withRoot(() => {
+ const [items, setItems] = createSignal<readonly Item[]>([
+ item('first', 'shared'),
+ item('second', 'shared'),
+ item('other'),
+ ]);
+ const list = createListController({
+ items,
+ getKey: (value) => value.id,
+ selection: { getKey: (value) => value.label },
+ });
+
+ list.selection.select('first');
+ expect([...list.selection.keys()]).toEqual(['shared']);
+ expect(list.selection.isSelected('first')).toBe(true);
+ expect(list.selection.isSelected('second')).toBe(true);
+ expect(list.selection.items().map((value) => value.id)).toEqual([
+ 'first',
+ ]);
+
+ setItems([item('second', 'shared'), item('other')]);
+ expect([...list.selection.keys()]).toEqual(['shared']);
+ expect(list.selection.items().map((value) => value.id)).toEqual([
+ 'second',
+ ]);
+ });
+ });
+
+ it('supports command-specific navigation predicates and wrapping', () => {
+ withRoot(() => {
+ const values = [item('a'), item('b'), item('c')];
+ const list = createListController({
+ items: () => values,
+ getKey: (value) => value.id,
+ wrapNavigation: true,
+ });
+
+ list.focus.set('a');
+ expect(
+ list.navigate.by(1, {
+ isNavigable: (value) => value.id !== 'b',
+ })?.key
+ ).toBe('c');
+ expect(list.navigate.by(1, { wrap: false })).toBeUndefined();
+ expect(list.navigate.by(1, { wrap: true })?.key).toBe('a');
+ });
+ });
+
+ it('toggles all currently visible logical selections', () => {
+ withRoot(() => {
+ const values = [
+ item('first', 'shared'),
+ item('second', 'shared'),
+ item('header', 'Header', true),
+ item('other'),
+ ];
+ const list = createListController({
+ items: () => values,
+ getKey: (value) => value.id,
+ selection: { getKey: (value) => value.label },
+ isSelectable: (value) => !value.structural,
+ });
+
+ list.selection.toggleAllVisible();
+ expect([...list.selection.keys()]).toEqual(['shared', 'other']);
+ expect(list.selection.allVisibleSelected()).toBe(true);
+
+ list.selection.toggleAllVisible();
+ expect(list.selection.count()).toBe(0);
+ });
+ });
+
+ it('emits typed activation metadata and focuses keyed activation', () => {
+ withRoot(() => {
+ const onActivate = vi.fn();
+ const list = createListController<Item, { source: string }>({
+ items: () => [item('a')],
+ getKey: (value) => value.id,
+ onActivate,
+ });
+
+ const activation = list.activate.key('a', {
+ reason: 'pointer',
+ metadata: { source: 'row' },
+ });
+
+ expect(activation).toMatchObject({
+ key: 'a',
+ reason: 'pointer',
+ metadata: { source: 'row' },
+ });
+ expect(list.focus.key()).toBe('a');
+ expect(onActivate).toHaveBeenCalledOnce();
+ });
+ });
+
+ it('keeps restored anchors ineffective until eligible payloads arrive', () => {
+ withRoot(() => {
+ const [items, setItems] = createSignal<readonly Item[]>([]);
+ const list = createListController({
+ items,
+ getKey: (value: Item) => value.id,
+ isNavigable: (value) => !value.structural,
+ isSelectable: (value) => !value.structural,
+ initialSelectedKeys: ['restored'],
+ });
+ list.focus.restore('restored');
+
+ setItems([item('restored', 'Header', true)]);
+ expect(list.focus.requestedKey()).toBe('restored');
+ expect(list.focus.key()).toBeUndefined();
+ expect([...list.selection.requestedKeys()]).toEqual(['restored']);
+ expect(list.selection.keys().size).toBe(0);
+ expect(list.selection.items()).toEqual([]);
+
+ setItems([item('restored')]);
+ expect(list.focus.key()).toBe('restored');
+ expect([...list.selection.keys()]).toEqual(['restored']);
+ });
+ });
+
+ it('supports falsy generic items and rejects invalid navigation offsets', () => {
+ withRoot(() => {
+ const list = createListController({
+ items: () => [0, 1],
+ getKey: (value: number) => String(value),
+ });
+
+ expect(list.items.result('0')).toEqual({ item: 0, index: 0, key: '0' });
+ expect(() => list.navigate.by(Number.POSITIVE_INFINITY)).toThrow(
+ 'List navigation offset must be a finite integer'
+ );
+ expect(() => list.navigate.by(1.5)).toThrow(
+ 'List navigation offset must be a finite integer'
+ );
+ });
+ });
+
+ it('rejects duplicate collection keys', () => {
+ withRoot(() => {
+ expect(() =>
+ createListController({
+ items: () => [item('duplicate'), item('duplicate')],
+ getKey: (value: Item) => value.id,
+ })
+ ).toThrow('List items must have unique keys; received: duplicate');
+ });
+ });
+});
diff --git a/apps/web/src/components/list/create-list-controller.ts b/apps/web/src/components/list/create-list-controller.ts
new file mode 100644
index 0000000000..273ec88410
--- /dev/null
+++ b/apps/web/src/components/list/create-list-controller.ts
@@ -0,0 +1,585 @@
+import { createMemo, createSignal } from 'solid-js';
+import {
+ createSelectionState,
+ type SelectionState,
+} from './create-selection-state';
+import type {
+ ListActivateOptions,
+ ListActivation,
+ ListActivationReason,
+ ListFocusChange,
+ ListFocusOptions,
+ ListItemResult,
+ ListItems,
+ ListKey,
+ ListNavigationOptions,
+ ListRestoreFocusOptions,
+} from './types';
+
+export type CreateListSelectionOptions<TItem> = {
+ /**
+ * Logical identity used for selection and bulk actions. Defaults to the
+ * rendered item key. Multiple rendered occurrences may share this key.
+ */
+ getKey: (item: TItem, index: number) => ListKey;
+};
+
+export type CreateListControllerOptions<TItem, TMetadata = unknown> = {
+ items: () => readonly TItem[];
+ /** Unique rendered occurrence identity used by focus and activation. */
+ getKey: (item: TItem) => ListKey;
+ selection?: CreateListSelectionOptions<TItem>;
+ /** Whether keyboard focus may land on an item. */
+ isNavigable?: (item: TItem, index: number) => boolean;
+ /** Whether an item may participate in batch selection. */
+ isSelectable?: (item: TItem, index: number) => boolean;
+ wrapNavigation?: boolean;
+ initialFocusKey?: ListKey;
+ initialSelectedKeys?: Iterable<ListKey>;
+ onFocusChange?: (change: ListFocusChange<TItem>) => void;
+ onSelectionChange?: (keys: ReadonlySet<ListKey>) => void;
+ onActivate?: (activation: ListActivation<TItem, TMetadata>) => void;
+};
+
+const activationFocusReason = (
+ reason: ListActivationReason
+): ListFocusOptions['reason'] => {
+ switch (reason) {
+ case 'keyboard':
+ return 'keyboard';
+ case 'pointer':
+ return 'pointer';
+ case 'programmatic':
+ return 'programmatic';
+ }
+};
+
+/**
+ * Creates a stable, headless controller over a reactive item accessor.
+ *
+ * Interaction state stores keys only. Replacing item objects updates every
+ * derived payload without synchronization effects, while temporarily missing
+ * focus and selection anchors survive until their explicit `prune` commands.
+ */
+export function createListController<TItem, TMetadata = unknown>(
+ options: CreateListControllerOptions<TItem, TMetadata>
+) {
+ const isNavigable = options.isNavigable ?? (() => true);
+ const isSelectable = options.isSelectable ?? (() => true);
+
+ const snapshot = createMemo(() => {
+ const all = options.items();
+ const byKey = new Map<ListKey, TItem>();
+ const indexByKey = new Map<ListKey, number>();
+
+ all.forEach((item, index) => {
+ const key = options.getKey(item);
+ if (byKey.has(key)) {
+ throw new Error(`List items must have unique keys; received: ${key}`);
+ }
+ byKey.set(key, item);
+ indexByKey.set(key, index);
+ });
+
+ return { all, byKey, indexByKey };
+ });
+
+ const itemResultAt = (index: number): ListItemResult<TItem> | undefined => {
+ const all = snapshot().all;
+ if (index < 0 || index >= all.length) return undefined;
+ const item = all[index];
+ return { item, index, key: options.getKey(item) };
+ };
+
+ const itemResultFor = (key: ListKey): ListItemResult<TItem> | undefined => {
+ const index = snapshot().indexByKey.get(key);
+ return index === undefined ? undefined : itemResultAt(index);
+ };
+
+ const items: ListItems<TItem> = {
+ all: () => snapshot().all,
+ count: () => snapshot().all.length,
+ keyOf: options.getKey,
+ get: (key) => snapshot().byKey.get(key),
+ at: (index) => snapshot().all[index],
+ indexOf: (key) => snapshot().indexByKey.get(key) ?? -1,
+ result: itemResultFor,
+ };
+
+ const canNavigateTo = (result: ListItemResult<TItem>, force = false) =>
+ force || isNavigable(result.item, result.index);
+
+ const matchesNavigation = (
+ result: ListItemResult<TItem>,
+ navigationOptions: ListNavigationOptions<TItem> = {}
+ ) =>
+ canNavigateTo(result, navigationOptions.force) &&
+ (navigationOptions.isNavigable?.(result.item, result.index) ?? true);
+
+ const [requestedFocusKey, setRequestedFocusKey] = createSignal<
+ ListKey | undefined
+ >(options.initialFocusKey);
+ const [forcedFocus, setForcedFocus] = createSignal(false);
+ const focusedResult = createMemo(() => {
+ const key = requestedFocusKey();
+ if (key === undefined) return undefined;
+ const result = itemResultFor(key);
+ return result && canNavigateTo(result, forcedFocus()) ? result : undefined;
+ });
+
+ const commitFocus = (
+ nextKey: ListKey | undefined,
+ reason: NonNullable<ListFocusOptions['reason']>,
+ force = false
+ ) => {
+ const previousKey = requestedFocusKey();
+ const previousForced = forcedFocus();
+ const previous = focusedResult();
+ if (previousKey === nextKey && previousForced === force) return previous;
+
+ setForcedFocus(force);
+ setRequestedFocusKey(nextKey);
+ const current = focusedResult();
+ options.onFocusChange?.({
+ current,
+ previous,
+ requestedKey: nextKey,
+ reason,
+ });
+ return current;
+ };
+
+ const focusResult = (
+ result: ListItemResult<TItem> | undefined,
+ focusOptions: ListFocusOptions = {}
+ ) => {
+ if (!result || !canNavigateTo(result, focusOptions.force)) return undefined;
+ commitFocus(
+ result.key,
+ focusOptions.reason ?? 'programmatic',
+ focusOptions.force === true
+ );
+ return result;
+ };
+
+ const findNavigable = (
+ start: number,
+ direction: 1 | -1,
+ navigationOptions: ListNavigationOptions<TItem> = {}
+ ) => {
+ const all = snapshot().all;
+ for (
+ let index = start;
+ index >= 0 && index < all.length;
+ index += direction
+ ) {
+ const result = itemResultAt(index);
+ if (result && matchesNavigation(result, navigationOptions)) return result;
+ }
+ return undefined;
+ };
+
+ const focusFirst = (navigationOptions: ListNavigationOptions<TItem> = {}) =>
+ focusResult(findNavigable(0, 1, navigationOptions), navigationOptions);
+
+ const focusLast = (navigationOptions: ListNavigationOptions<TItem> = {}) =>
+ focusResult(
+ findNavigable(snapshot().all.length - 1, -1, navigationOptions),
+ navigationOptions
+ );
+
+ const findNearest = (
+ targetIndex: number,
+ navigationOptions: ListNavigationOptions<TItem> = {}
+ ) => {
+ const all = snapshot().all;
+ if (all.length === 0) return undefined;
+
+ const center = Math.min(Math.max(targetIndex, 0), all.length - 1);
+ const centered = itemResultAt(center);
+ if (centered && matchesNavigation(centered, navigationOptions)) {
+ return centered;
+ }
+
+ for (let distance = 1; distance < all.length; distance++) {
+ const after = itemResultAt(center + distance);
+ if (after && matchesNavigation(after, navigationOptions)) return after;
+
+ const before = itemResultAt(center - distance);
+ if (before && matchesNavigation(before, navigationOptions)) return before;
+ }
+ return undefined;
+ };
+
+ const focusNearest = (
+ index: number,
+ navigationOptions: ListNavigationOptions<TItem> = {}
+ ) => focusResult(findNearest(index, navigationOptions), navigationOptions);
+
+ const peekBy = (
+ offset: number,
+ navigationOptions: ListNavigationOptions<TItem> = {}
+ ): ListItemResult<TItem> | undefined => {
+ if (offset === 0) {
+ const current = focusedResult();
+ return current && matchesNavigation(current, navigationOptions)
+ ? current
+ : undefined;
+ }
+
+ const all = snapshot().all;
+ if (all.length === 0) return undefined;
+
+ if (!Number.isSafeInteger(offset)) {
+ throw new RangeError('List navigation offset must be a finite integer');
+ }
+
+ const direction: 1 | -1 = offset > 0 ? 1 : -1;
+ let remaining = Math.abs(offset);
+ let cursor = focusedResult()?.index ?? (direction > 0 ? -1 : all.length);
+ let candidate: ListItemResult<TItem> | undefined;
+ let visited = 0;
+ const visitLimit = all.length * remaining;
+
+ while (remaining > 0 && visited < visitLimit) {
+ cursor += direction;
+ if (cursor < 0 || cursor >= all.length) {
+ if (!(navigationOptions.wrap ?? options.wrapNavigation)) break;
+ cursor = (cursor + all.length) % all.length;
+ }
+
+ visited += 1;
+ const result = itemResultAt(cursor);
+ if (!result || !matchesNavigation(result, navigationOptions)) continue;
+ candidate = result;
+ remaining -= 1;
+ }
+
+ return candidate;
+ };
+
+ const navigateBy = (
+ offset: number,
+ navigationOptions: ListNavigationOptions<TItem> = {}
+ ) => {
+ const target = peekBy(offset, navigationOptions);
+ return focusResult(target, {
+ ...navigationOptions,
+ reason: navigationOptions.reason ?? 'keyboard',
+ });
+ };
+
+ const restoreFocus = (
+ key: ListKey | undefined,
+ restoreOptions: ListRestoreFocusOptions = {}
+ ) => {
+ const reason = restoreOptions.reason ?? 'restore';
+ if (key !== undefined) {
+ const restored = focusResult(itemResultFor(key), {
+ ...restoreOptions,
+ reason,
+ });
+ if (restored) return restored;
+ }
+
+ switch (restoreOptions.fallback ?? 'none') {
+ case 'first':
+ return focusFirst({ ...restoreOptions, reason });
+ case 'last':
+ return focusLast({ ...restoreOptions, reason });
+ case 'nearest':
+ return focusNearest(
+ restoreOptions.nearestIndex ?? focusedResult()?.index ?? 0,
+ { ...restoreOptions, reason }
+ );
+ case 'none':
+ commitFocus(
+ restoreOptions.retainUnavailable !== false &&
+ key !== undefined &&
+ itemResultFor(key) === undefined
+ ? key
+ : undefined,
+ reason,
+ false
+ );
+ return undefined;
+ }
+ };
+
+ const selectableResult = (rowKey: ListKey) => {
+ const result = itemResultFor(rowKey);
+ return result && isSelectable(result.item, result.index)
+ ? result
+ : undefined;
+ };
+ const selectionKeyForResult = (result: ListItemResult<TItem>) =>
+ options.selection?.getKey(result.item, result.index) ?? result.key;
+ const selectableBySelectionKey = createMemo(() => {
+ const results = new Map<ListKey, ListItemResult<TItem>>();
+ snapshot().all.forEach((_item, index) => {
+ const result = itemResultAt(index);
+ if (!result || !isSelectable(result.item, result.index)) return;
+ const selectionKey = selectionKeyForResult(result);
+ if (!results.has(selectionKey)) results.set(selectionKey, result);
+ });
+ return results;
+ });
+ const keySelection: SelectionState<ListItemResult<TItem>> =
+ createSelectionState({
+ items: () => [...selectableBySelectionKey().values()],
+ getKey: selectionKeyForResult,
+ initialKeys: options.initialSelectedKeys,
+ onChange: options.onSelectionChange,
+ });
+
+ const effectiveSelectionKeys = createMemo<ReadonlySet<ListKey>>(
+ () =>
+ new Set(
+ [...keySelection.keys()].filter((key) =>
+ selectableBySelectionKey().has(key)
+ )
+ )
+ );
+ const effectiveSelectionItems = createMemo(() =>
+ [...effectiveSelectionKeys()].flatMap((key) => {
+ const result = selectableBySelectionKey().get(key);
+ return result ? [result.item] : [];
+ })
+ );
+ const selectionKeyForRow = (rowKey: ListKey) => {
+ const result = selectableResult(rowKey);
+ return result ? selectionKeyForResult(result) : undefined;
+ };
+ const isSelectionKeySelected = (selectionKey: ListKey) =>
+ effectiveSelectionKeys().has(selectionKey);
+ const isRowSelected = (rowKey: ListKey) => {
+ const selectionKey = selectionKeyForRow(rowKey);
+ return selectionKey !== undefined && isSelectionKeySelected(selectionKey);
+ };
+
+ const replaceSelected = (keys: Iterable<ListKey>) => {
+ keySelection.replace(
+ [...keys].filter((key) => selectableBySelectionKey().has(key))
+ );
+ };
+
+ const selectRange = (
+ fromKey: ListKey,
+ toKey: ListKey,
+ selected = true,
+ baseline: Iterable<ListKey> = keySelection.keys()
+ ) => {
+ const from = items.indexOf(fromKey);
+ const to = items.indexOf(toKey);
+ if (from < 0 || to < 0) return;
+
+ const start = Math.min(from, to);
+ const end = Math.max(from, to);
+ const next = new Set(baseline);
+ for (let index = start; index <= end; index++) {
+ const result = itemResultAt(index);
+ if (!result || !isSelectable(result.item, result.index)) continue;
+ const selectionKey = selectionKeyForResult(result);
+ if (selected) next.add(selectionKey);
+ else next.delete(selectionKey);
+ }
+ keySelection.replace(next);
+ };
+
+ const visibleSelectionKeys = createMemo(
+ () => new Set(selectableBySelectionKey().keys())
+ );
+ const allVisibleSelected = () => {
+ const visible = visibleSelectionKeys();
+ return (
+ visible.size > 0 &&
+ [...visible].every((key) => effectiveSelectionKeys().has(key))
+ );
+ };
+ const selectAllVisible = () => keySelection.add(visibleSelectionKeys());
+ const toggleAllVisible = () => {
+ if (allVisibleSelected()) {
+ const visible = visibleSelectionKeys();
+ keySelection.replace(
+ [...keySelection.keys()].filter((key) => !visible.has(key))
+ );
+ return;
+ }
+ selectAllVisible();
+ };
+
+ const focusOptionsForActivation = (
+ activateOptions: ListActivateOptions<TMetadata>,
+ defaultFocus: boolean
+ ): ListFocusOptions | undefined => {
+ const requested = activateOptions.focus;
+ if (requested === false || (requested === undefined && !defaultFocus)) {
+ return undefined;
+ }
+
+ const reason = activationFocusReason(
+ activateOptions.reason ?? 'programmatic'
+ );
+ if (requested === undefined || requested === true) return { reason };
+ return { ...requested, reason: requested.reason ?? reason };
+ };
+
+ const activateResult = (
+ result: ListItemResult<TItem> | undefined,
+ activateOptions: ListActivateOptions<TMetadata> = {},
+ defaultFocus = true
+ ) => {
+ if (!result) return undefined;
+
+ const focusOptions = focusOptionsForActivation(
+ activateOptions,
+ defaultFocus
+ );
+ if (focusOptions) focusResult(result, focusOptions);
+
+ const activation: ListActivation<TItem, TMetadata> = {
+ ...result,
+ reason: activateOptions.reason ?? 'programmatic',
+ ...(activateOptions.metadata === undefined
+ ? {}
+ : { metadata: activateOptions.metadata }),
+ };
+ options.onActivate?.(activation);
+ return activation;
+ };
+
+ return {
+ items,
+ focus: {
+ requestedKey: requestedFocusKey,
+ key: () => focusedResult()?.key,
+ item: () => focusedResult()?.item,
+ index: () => focusedResult()?.index ?? -1,
+ result: focusedResult,
+ isNavigable: (key: ListKey) => {
+ const result = itemResultFor(key);
+ return result !== undefined && canNavigateTo(result);
+ },
+ set: (key: ListKey, focusOptions?: ListFocusOptions) =>
+ focusResult(itemResultFor(key), focusOptions),
+ setIndex: (index: number, focusOptions?: ListFocusOptions) =>
+ focusResult(itemResultAt(index), focusOptions),
+ request: (
+ key: ListKey | undefined,
+ focusOptions: ListFocusOptions = {}
+ ) =>
+ commitFocus(
+ key,
+ focusOptions.reason ?? 'programmatic',
+ focusOptions.force === true
+ ),
+ restore: restoreFocus,
+ first: focusFirst,
+ last: focusLast,
+ nearest: focusNearest,
+ clear: (focusOptions: ListFocusOptions = {}) =>
+ commitFocus(undefined, focusOptions.reason ?? 'programmatic'),
+ prune: (focusOptions: ListFocusOptions = {}) => {
+ const key = requestedFocusKey();
+ if (key === undefined || focusedResult()) return;
+ commitFocus(undefined, focusOptions.reason ?? 'programmatic');
+ },
+ },
+ navigate: {
+ down: (navigationOptions?: ListNavigationOptions<TItem>) =>
+ navigateBy(1, navigationOptions),
+ up: (navigationOptions?: ListNavigationOptions<TItem>) =>
+ navigateBy(-1, navigationOptions),
+ by: navigateBy,
+ toKey: (key: ListKey, focusOptions: ListFocusOptions = {}) =>
+ focusResult(itemResultFor(key), {
+ ...focusOptions,
+ reason: focusOptions.reason ?? 'keyboard',
+ }),
+ toIndex: (index: number, focusOptions: ListFocusOptions = {}) =>
+ focusResult(itemResultAt(index), {
+ ...focusOptions,
+ reason: focusOptions.reason ?? 'keyboard',
+ }),
+ toFirst: (navigationOptions: ListNavigationOptions<TItem> = {}) =>
+ focusFirst({
+ ...navigationOptions,
+ reason: navigationOptions.reason ?? 'keyboard',
+ }),
+ toLast: (navigationOptions: ListNavigationOptions<TItem> = {}) =>
+ focusLast({
+ ...navigationOptions,
+ reason: navigationOptions.reason ?? 'keyboard',
+ }),
+ peekBy,
+ },
+ activate: {
+ current: (activateOptions?: ListActivateOptions<TMetadata>) =>
+ activateResult(focusedResult(), activateOptions, false),
+ key: (key: ListKey, activateOptions?: ListActivateOptions<TMetadata>) =>
+ activateResult(itemResultFor(key), activateOptions, true),
+ index: (
+ index: number,
+ activateOptions?: ListActivateOptions<TMetadata>
+ ) => activateResult(itemResultAt(index), activateOptions, true),
+ },
+ selection: {
+ /** Requested logical keys, including identities awaiting item payloads. */
+ requestedKeys: keySelection.keys,
+ /** Currently resolved logical selection identities. */
+ keys: effectiveSelectionKeys,
+ /** One current selectable payload per logical selection identity. */
+ items: effectiveSelectionItems,
+ missingKeys: keySelection.missingKeys,
+ count: () => effectiveSelectionKeys().size,
+ keyForRow: selectionKeyForRow,
+ isSelectable: (rowKey: ListKey) => selectableResult(rowKey) !== undefined,
+ isSelected: isRowSelected,
+ isKeySelected: isSelectionKeySelected,
+ select: (rowKey: ListKey) => {
+ const selectionKey = selectionKeyForRow(rowKey);
+ if (selectionKey !== undefined) keySelection.select(selectionKey);
+ },
+ deselect: (rowKey: ListKey) => {
+ const selectionKey = selectionKeyForRow(rowKey);
+ if (selectionKey !== undefined) keySelection.deselect(selectionKey);
+ },
+ toggle: (rowKey: ListKey) => {
+ const selectionKey = selectionKeyForRow(rowKey);
+ if (selectionKey === undefined) return;
+ keySelection.toggle(selectionKey);
+ },
+ selectKey: (selectionKey: ListKey) => {
+ if (selectableBySelectionKey().has(selectionKey)) {
+ keySelection.select(selectionKey);
+ }
+ },
+ deselectKey: keySelection.deselect,
+ toggleKey: (selectionKey: ListKey) => {
+ if (selectableBySelectionKey().has(selectionKey)) {
+ keySelection.toggle(selectionKey);
+ }
+ },
+ /** Add currently resolved logical selection identities. */
+ add: (keys: Iterable<ListKey>) =>
+ keySelection.add(
+ [...keys].filter((key) => selectableBySelectionKey().has(key))
+ ),
+ replace: replaceSelected,
+ /** Restore logical keys before their item payloads are available. */
+ restore: keySelection.replace,
+ selectRange,
+ visibleKeys: visibleSelectionKeys,
+ allVisibleSelected,
+ selectAllVisible,
+ toggleAllVisible,
+ clear: keySelection.clear,
+ prune: keySelection.prune,
+ },
+ };
+}
+
+/** Headless list controller returned by `createListController`. */
+export type ListController<TItem, TMetadata = unknown> = ReturnType<
+ typeof createListController<TItem, TMetadata>
+>;
diff --git a/apps/web/src/components/list/create-selection-state.ts b/apps/web/src/components/list/create-selection-state.ts
new file mode 100644
index 0000000000..0393edfb65
--- /dev/null
+++ b/apps/web/src/components/list/create-selection-state.ts
@@ -0,0 +1,128 @@
+import { type Accessor, createMemo, createSignal } from 'solid-js';
+import type { ListKey } from './types';
+
+export type CreateSelectionStateOptions<TItem> = {
+ items: Accessor<readonly TItem[]>;
+ getKey: (item: TItem) => ListKey;
+ initialKeys?: Iterable<ListKey>;
+ onChange?: (keys: ReadonlySet<ListKey>) => void;
+};
+
+/** ID-only selection state. Item payloads are always derived from current data. */
+export type SelectionState<TItem> = {
+ keys: Accessor<ReadonlySet<ListKey>>;
+ items: Accessor<readonly TItem[]>;
+ missingKeys: Accessor<ReadonlySet<ListKey>>;
+ count: Accessor<number>;
+ isSelected: (key: ListKey) => boolean;
+ select: (key: ListKey) => void;
+ deselect: (key: ListKey) => void;
+ toggle: (key: ListKey) => void;
+ add: (keys: Iterable<ListKey>) => void;
+ replace: (keys: Iterable<ListKey>) => void;
+ clear: () => void;
+ /** Explicitly remove keys that are not present in the current collection. */
+ prune: () => void;
+};
+
+/**
+ * Creates selection state without retaining item objects.
+ *
+ * Missing keys intentionally survive collection replacement until `prune` is
+ * called. This lets a view preserve selection while data is temporarily absent
+ * during refetching without an effect synchronizing two sources of truth.
+ */
+export function createSelectionState<TItem>(
+ options: CreateSelectionStateOptions<TItem>
+): SelectionState<TItem> {
+ const selected = new Set<ListKey>(options.initialKeys ?? []);
+ const [version, invalidate] = createSignal(undefined, { equals: false });
+
+ const keys = createMemo<ReadonlySet<ListKey>>(() => {
+ version();
+ return new Set(selected);
+ });
+
+ const currentItems = createMemo(() => {
+ version();
+ return options.items().filter((item) => selected.has(options.getKey(item)));
+ });
+
+ const missingKeys = createMemo<ReadonlySet<ListKey>>(() => {
+ version();
+ const available = new Set(options.items().map(options.getKey));
+ return new Set([...selected].filter((key) => !available.has(key)));
+ });
+
+ const notify = () => {
+ invalidate();
+ options.onChange?.(new Set(selected));
+ };
+
+ const select = (key: ListKey) => {
+ if (selected.has(key)) return;
+ selected.add(key);
+ notify();
+ };
+
+ const deselect = (key: ListKey) => {
+ if (!selected.delete(key)) return;
+ notify();
+ };
+
+ const add = (nextKeys: Iterable<ListKey>) => {
+ let changed = false;
+ for (const key of nextKeys) {
+ if (selected.has(key)) continue;
+ selected.add(key);
+ changed = true;
+ }
+ if (changed) notify();
+ };
+
+ const replace = (nextKeys: Iterable<ListKey>) => {
+ const next = new Set(nextKeys);
+ if (
+ next.size === selected.size &&
+ [...next].every((key) => selected.has(key))
+ ) {
+ return;
+ }
+
+ selected.clear();
+ for (const key of next) selected.add(key);
+ notify();
+ };
+
+ const clear = () => {
+ if (selected.size === 0) return;
+ selected.clear();
+ notify();
+ };
+
+ const prune = () => {
+ const available = new Set(options.items().map(options.getKey));
+ let changed = false;
+ for (const key of selected) {
+ if (available.has(key)) continue;
+ selected.delete(key);
+ changed = true;
+ }
+ if (changed) notify();
+ };
+
+ return {
+ keys,
+ items: currentItems,
+ missingKeys,
+ count: () => keys().size,
+ isSelected: (key) => keys().has(key),
+ select,
+ deselect,
+ toggle: (key) => (selected.has(key) ? deselect(key) : select(key)),
+ add,
+ replace,
+ clear,
+ prune,
+ };
+}
diff --git a/apps/web/src/components/list/index.ts b/apps/web/src/components/list/index.ts
new file mode 100644
index 0000000000..4206e3b5b2
--- /dev/null
+++ b/apps/web/src/components/list/index.ts
@@ -0,0 +1,38 @@
+export {
+ type CreateDisclosureStateOptions,
+ createDisclosureState,
+ type DisclosureState,
+} from './create-disclosure-state';
+export {
+ type CreateListControllerOptions,
+ type CreateListSelectionOptions,
+ createListController,
+ type ListController,
+} from './create-list-controller';
+export {
+ type CreateSelectionStateOptions,
+ createSelectionState,
+ type SelectionState,
+} from './create-selection-state';
+export type {
+ ListActivateOptions,
+ ListActivation,
+ ListActivationReason,
+ ListFocusChange,
+ ListFocusFallback,
+ ListFocusOptions,
+ ListFocusReason,
+ ListItemResult,
+ ListItems,
+ ListKey,
+ ListNavigationOptions,
+ ListRestoreFocusOptions,
+} from './types';
+export {
+ type ListInteractionActivation,
+ type ListInteractionActivationIntent,
+ type ListInteractionNavigation,
+ type ListScrollHandle,
+ type UseListInteractionsOptions,
+ useListInteractions,
+} from './use-list-interactions';
diff --git a/apps/web/src/components/list/types.ts b/apps/web/src/components/list/types.ts
new file mode 100644
index 0000000000..9d7f999928
--- /dev/null
+++ b/apps/web/src/components/list/types.ts
@@ -0,0 +1,85 @@
+import type { Accessor } from 'solid-js';
+
+/** Stable identity used by the headless list primitives. */
+export type ListKey = string;
+
+/** One resolved item and its current position in the collection. */
+export type ListItemResult<TItem> = {
+ item: TItem;
+ index: number;
+ key: ListKey;
+};
+
+/** Why focus moved. Consumers can use this to decide whether to scroll. */
+export type ListFocusReason =
+ | 'keyboard'
+ | 'hover'
+ | 'pointer'
+ | 'restore'
+ | 'programmatic';
+
+/** Options shared by direct focus commands. */
+export type ListFocusOptions = {
+ reason?: ListFocusReason;
+ /** Allow direct focus to bypass the list's navigability predicate. */
+ force?: boolean;
+};
+
+/** Command-specific constraints layered on top of base list navigability. */
+export type ListNavigationOptions<TItem> = ListFocusOptions & {
+ /** Additional eligibility required by this navigation command. */
+ isNavigable?: (item: TItem, index: number) => boolean;
+ /** Override the controller's default wrapping policy for this command. */
+ wrap?: boolean;
+};
+
+/** Fallback used when a requested restoration key is not currently present. */
+export type ListFocusFallback = 'none' | 'first' | 'last' | 'nearest';
+
+/** Options for restoring focus from persisted view state. */
+export type ListRestoreFocusOptions = ListFocusOptions & {
+ fallback?: ListFocusFallback;
+ /** Center point for a nearest fallback. */
+ nearestIndex?: number;
+ /** Keep an unavailable key as the restoration anchor. Defaults to true. */
+ retainUnavailable?: boolean;
+};
+
+/** Information emitted after an explicit focus command changes the anchor. */
+export type ListFocusChange<TItem> = {
+ current: ListItemResult<TItem> | undefined;
+ previous: ListItemResult<TItem> | undefined;
+ requestedKey: ListKey | undefined;
+ reason: ListFocusReason;
+};
+
+/** Why an item was activated. */
+export type ListActivationReason = 'keyboard' | 'pointer' | 'programmatic';
+
+/** Item activation emitted by a list controller. */
+export type ListActivation<
+ TItem,
+ TMetadata = unknown,
+> = ListItemResult<TItem> & {
+ reason: ListActivationReason;
+ metadata?: TMetadata;
+};
+
+/** Options for activating an item. */
+export type ListActivateOptions<TMetadata = unknown> = {
+ reason?: ListActivationReason;
+ /** Focus before activation. Defaults to true for keyed/index activation. */
+ focus?: boolean | ListFocusOptions;
+ metadata?: TMetadata;
+};
+
+/** Reactive item collection exposed by a list controller. */
+export type ListItems<TItem> = {
+ all: Accessor<readonly TItem[]>;
+ count: Accessor<number>;
+ keyOf: (item: TItem) => ListKey;
+ get: (key: ListKey) => TItem | undefined;
+ at: (index: number) => TItem | undefined;
+ indexOf: (key: ListKey) => number;
+ result: (key: ListKey) => ListItemResult<TItem> | undefined;
+};
diff --git a/apps/web/src/components/list/use-list-interactions.ts b/apps/web/src/components/list/use-list-interactions.ts
new file mode 100644
index 0000000000..0f014a9257
--- /dev/null
+++ b/apps/web/src/components/list/use-list-interactions.ts
@@ -0,0 +1,396 @@
+import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
+import { TOKENS } from '@core/hotkey/tokens';
+import { type Accessor, createSignal, onCleanup } from 'solid-js';
+import type { ListController } from './create-list-controller';
+import type { ListKey, ListNavigationOptions } from './types';
+
+/** Minimal scrolling contract implemented by virtualized list handles. */
+export type ListScrollHandle = {
+ scrollToIndex: (
+ index: number,
+ options?: { align?: 'start' | 'center' | 'end' | 'nearest' }
+ ) => void;
+};
+
+type ListInteractionConditions = Partial<
+ Record<
+ | 'move'
+ | 'extendSelection'
+ | 'first'
+ | 'last'
+ | 'open'
+ | 'toggleSelection'
+ | 'toggleAllVisible'
+ | 'clearSelection',
+ () => boolean
+ >
+>;
+
+export type ListInteractionNavigation<TItem> = {
+ move?: ListNavigationOptions<TItem>;
+ first?: ListNavigationOptions<TItem>;
+ last?: ListNavigationOptions<TItem>;
+ extendSelection?: ListNavigationOptions<TItem>;
+};
+
+export type ListInteractionActivationIntent = 'primary' | 'alternate';
+
+export type ListInteractionActivation<TMetadata> = {
+ createMetadata?: (intent: ListInteractionActivationIntent) => TMetadata;
+ alternateDescription?: string;
+};
+
+export type UseListInteractionsOptions<TItem, TMetadata> = {
+ controller: ListController<TItem, TMetadata>;
+ scopeId: string;
+ scrollHandle: Accessor<ListScrollHandle | undefined>;
+ /** Optional view-level gate in addition to hotkey-scope ownership. */
+ enabled?: () => boolean;
+ conditions?: ListInteractionConditions;
+ navigation?: ListInteractionNavigation<TItem>;
+ activation?: ListInteractionActivation<TMetadata>;
+};
+
+/**
+ * Connects a headless list controller to standard navigation, range selection,
+ * scrolling, activation, and hotkeys. Domain-specific row activation remains
+ * on the controller supplied by the consuming view.
+ */
+export function useListInteractions<TItem, TMetadata = unknown>(
+ options: UseListInteractionsOptions<TItem, TMetadata>
+) {
+ const list = options.controller;
+ const [selectionAnchor, setSelectionAnchor] = createSignal<
+ ListKey | undefined
+ >();
+ const [rangeSession, setRangeSession] = createSignal<
+ | {
+ baseline: ReadonlySet<ListKey>;
+ selected: boolean;
+ }
+ | undefined
+ >();
+
+ const canHandle = (condition?: () => boolean) =>
+ (options.enabled?.() ?? true) && (condition?.() ?? true);
+
+ const scrollFocusedIntoView = () => {
+ const index = list.focus.index();
+ if (index >= 0) {
+ options.scrollHandle()?.scrollToIndex(index, { align: 'nearest' });
+ }
+ };
+
+ const finishNavigation = (key: ListKey) => {
+ setSelectionAnchor(key);
+ setRangeSession(undefined);
+ scrollFocusedIntoView();
+ };
+
+ const move = (offset: 1 | -1) => {
+ const result = list.navigate.by(offset, options.navigation?.move);
+ if (!result) return false;
+ finishNavigation(result.key);
+ return true;
+ };
+
+ const first = () => {
+ const result = list.navigate.toFirst(options.navigation?.first);
+ if (!result) return false;
+ finishNavigation(result.key);
+ return true;
+ };
+
+ const last = () => {
+ const result = list.navigate.toLast(options.navigation?.last);
+ if (!result) return false;
+ finishNavigation(result.key);
+ return true;
+ };
+
+ const beginRange = (selected: boolean) => {
+ const existing = rangeSession();
+ if (existing) return existing;
+ const session = {
+ baseline: new Set(list.selection.requestedKeys()),
+ selected,
+ };
+ setRangeSession(session);
+ return session;
+ };
+
+ const applyRange = (targetKey: ListKey, selected: boolean) => {
+ const anchor = selectionAnchor();
+ if (
+ anchor === undefined ||
+ !list.selection.isSelectable(anchor) ||
+ !list.selection.isSelectable(targetKey)
+ ) {
+ return false;
+ }
+
+ const session = beginRange(selected);
+ list.selection.selectRange(
+ anchor,
+ targetKey,
+ session.selected,
+ session.baseline
+ );
+ return true;
+ };
+
+ const setSelected = (
+ key: ListKey,
+ selected: boolean,
+ selectionOptions: { range?: boolean } = {}
+ ) => {
+ if (!list.selection.isSelectable(key)) return false;
+ if (selectionOptions.range && selectionAnchor() !== undefined) {
+ return applyRange(key, selected);
+ }
+
+ if (selected) list.selection.select(key);
+ else list.selection.deselect(key);
+ setSelectionAnchor(key);
+ setRangeSession(undefined);
+ return true;
+ };
+
+ const toggleSelected = (
+ key: ListKey,
+ selectionOptions: { range?: boolean } = {}
+ ) => setSelected(key, !list.selection.isSelected(key), selectionOptions);
+
+ const selectionNavigationOptions = (): ListNavigationOptions<TItem> => {
+ const configured = options.navigation?.extendSelection;
+ return {
+ ...configured,
+ isNavigable: (item, index) => {
+ const rowKey = list.items.keyOf(item);
+ return (
+ list.selection.isSelectable(rowKey) &&
+ (configured?.isNavigable?.(item, index) ?? true)
+ );
+ },
+ };
+ };
+
+ const extendSelection = (offset: 1 | -1) => {
+ const currentKey = list.focus.key();
+ if (currentKey === undefined) return false;
+
+ if (!list.selection.isSelectable(currentKey)) {
+ const firstSelectable = list.navigate.by(
+ offset,
+ selectionNavigationOptions()
+ );
+ if (!firstSelectable) return false;
+ setSelectionAnchor(firstSelectable.key);
+ setRangeSession({
+ baseline: new Set(list.selection.requestedKeys()),
+ selected: true,
+ });
+ list.selection.select(firstSelectable.key);
+ scrollFocusedIntoView();
+ return true;
+ }
+
+ const anchor = selectionAnchor();
+ if (anchor === undefined || !list.selection.isSelectable(anchor)) {
+ setSelectionAnchor(currentKey);
+ }
+ beginRange(true);
+
+ const result = list.navigate.by(offset, selectionNavigationOptions());
+ if (!result || !applyRange(result.key, true)) return false;
+ scrollFocusedIntoView();
+ return true;
+ };
+
+ const toggleAllVisible = () => {
+ list.selection.toggleAllVisible();
+ setSelectionAnchor(undefined);
+ setRangeSession(undefined);
+ };
+
+ const clearSelection = () => {
+ list.selection.clear();
+ setSelectionAnchor(undefined);
+ setRangeSession(undefined);
+ };
+
+ const group = createHotkeyGroup();
+
+ registerHotkey({
+ hotkey: ['arrowdown', 'j'],
+ hotkeyToken: TOKENS.entity.step.end,
+ scopeId: options.scopeId,
+ description: 'Move down',
+ condition: () => canHandle(options.conditions?.move),
+ hide: true,
+ keyDownHandler: () => {
+ move(1);
+ return true;
+ },
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: ['arrowup', 'k'],
+ hotkeyToken: TOKENS.entity.step.start,
+ scopeId: options.scopeId,
+ description: 'Move up',
+ condition: () => canHandle(options.conditions?.move),
+ hide: true,
+ keyDownHandler: () => {
+ move(-1);
+ return true;
+ },
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: ['shift+arrowdown', 'shift+j'],
+ scopeId: options.scopeId,
+ description: 'Extend selection down',
+ condition: () => canHandle(options.conditions?.extendSelection),
+ hide: true,
+ keyDownHandler: () => {
+ extendSelection(1);
+ return true;
+ },
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: ['shift+arrowup', 'shift+k'],
+ scopeId: options.scopeId,
+ description: 'Extend selection up',
+ condition: () => canHandle(options.conditions?.extendSelection),
+ hide: true,
+ keyDownHandler: () => {
+ extendSelection(-1);
+ return true;
+ },
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: 'home',
+ hotkeyToken: TOKENS.entity.jump.home,
+ scopeId: options.scopeId,
+ description: 'Go to first item',
+ condition: () => canHandle(options.conditions?.first),
+ hide: true,
+ keyDownHandler: () => {
+ first();
+ return true;
+ },
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: ['end', 'shift+g'],
+ hotkeyToken: TOKENS.entity.jump.end,
+ scopeId: options.scopeId,
+ description: 'Go to last item',
+ condition: () => canHandle(options.conditions?.last),
+ hide: true,
+ keyDownHandler: () => {
+ last();
+ return true;
+ },
+ }).withGroup(group);
+
+ const canOpen = () =>
+ canHandle(options.conditions?.open) && list.focus.key() !== undefined;
+ const open = (intent: ListInteractionActivationIntent) => {
+ const metadata = options.activation?.createMetadata?.(intent);
+ const activation = list.activate.current({
+ reason: 'keyboard',
+ ...(metadata === undefined ? {} : { metadata }),
+ });
+ return activation !== undefined;
+ };
+
+ registerHotkey({
+ hotkey: 'enter',
+ hotkeyToken: TOKENS.entity.open,
+ scopeId: options.scopeId,
+ description: 'Open item',
+ condition: canOpen,
+ keyDownHandler: () => open('primary'),
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: 'shift+enter',
+ scopeId: options.scopeId,
+ description:
+ options.activation?.alternateDescription ?? 'Open item alternatively',
+ condition: canOpen,
+ hide: true,
+ keyDownHandler: () => open('alternate'),
+ }).withGroup(group);
+
+ const canToggleSelection = () => {
+ if (!canHandle(options.conditions?.toggleSelection)) return false;
+ const key = list.focus.key();
+ return key !== undefined && list.selection.isSelectable(key);
+ };
+
+ registerHotkey({
+ hotkey: 'x',
+ scopeId: options.scopeId,
+ description: 'Toggle item selection',
+ condition: canToggleSelection,
+ keyDownHandler: () => {
+ const key = list.focus.key();
+ return key === undefined ? false : toggleSelected(key);
+ },
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: 'cmd+a',
+ scopeId: options.scopeId,
+ description: 'Toggle all visible items',
+ condition: () =>
+ canHandle(options.conditions?.toggleAllVisible) &&
+ list.selection.visibleKeys().size > 0,
+ keyDownHandler: () => {
+ toggleAllVisible();
+ return true;
+ },
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: 'escape',
+ hotkeyToken: TOKENS.soup.dismiss,
+ scopeId: options.scopeId,
+ description: 'Clear selection',
+ condition: () =>
+ canHandle(options.conditions?.clearSelection) &&
+ list.selection.count() > 0,
+ keyDownHandler: () => {
+ clearSelection();
+ return true;
+ },
+ }).withGroup(group);
+
+ onCleanup(() => group.dispose());
+
+ return {
+ navigation: {
+ move,
+ first,
+ last,
+ scrollFocusedIntoView,
+ },
+ selection: {
+ anchor: selectionAnchor,
+ set: setSelected,
+ toggle: toggleSelected,
+ extend: extendSelection,
+ toggleAllVisible,
+ clear: clearSelection,
+ clearAnchor: () => {
+ setSelectionAnchor(undefined);
+ setRangeSession(undefined);
+ },
+ },
+ };
+}
diff --git a/apps/web/src/components/view-shell/CollapsibleSection.tsx b/apps/web/src/components/view-shell/CollapsibleSection.tsx
new file mode 100644
index 0000000000..cd5b0810f7
--- /dev/null
+++ b/apps/web/src/components/view-shell/CollapsibleSection.tsx
@@ -0,0 +1,71 @@
+import { Collapsible } from '@kobalte/core/collapsible';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import { cn } from '@ui';
+import { type ComponentProps, type JSX, Show, splitProps } from 'solid-js';
+
+export type CollapsibleSectionRootProps = Omit<
+ ComponentProps<typeof Collapsible>,
+ 'defaultOpen' | 'onOpenChange' | 'open'
+> & {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+function Root(props: CollapsibleSectionRootProps) {
+ return <Collapsible {...props} />;
+}
+
+function Trigger(props: ComponentProps<typeof Collapsible.Trigger>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <Collapsible.Trigger
+ {...rest}
+ class={cn(
+ 'group flex h-9 w-full min-w-0 items-center gap-2.5 rounded-xl px-3 py-2 text-left text-sm font-medium text-ink-muted outline-none hover:bg-hover hover:text-ink focus-visible:ring-2 focus-visible:ring-accent/30',
+ local.class
+ )}
+ >
+ {local.children}
+ </Collapsible.Trigger>
+ );
+}
+
+function Indicator(props: JSX.HTMLAttributes<HTMLSpanElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <span
+ {...rest}
+ aria-hidden="true"
+ class={cn(
+ 'ml-auto flex size-4 shrink-0 items-center justify-center text-ink-extra-muted transition-transform group-data-expanded:rotate-90',
+ local.class
+ )}
+ >
+ <Show
+ when={local.children}
+ fallback={<CaretDownIcon class="size-3 -rotate-90" />}
+ >
+ {local.children}
+ </Show>
+ </span>
+ );
+}
+
+function Content(props: ComponentProps<typeof Collapsible.Content>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <Collapsible.Content
+ {...rest}
+ class={cn('min-w-0 data-closed:hidden', local.class)}
+ >
+ {local.children}
+ </Collapsible.Content>
+ );
+}
+
+export const CollapsibleSection = Object.assign(Root, {
+ Root,
+ Trigger,
+ Indicator,
+ Content,
+});
diff --git a/apps/web/src/components/view-shell/ListDropdowns.tsx b/apps/web/src/components/view-shell/ListDropdowns.tsx
new file mode 100644
index 0000000000..a8d367476a
--- /dev/null
+++ b/apps/web/src/components/view-shell/ListDropdowns.tsx
@@ -0,0 +1,244 @@
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import CheckIcon from '@phosphor/check.svg';
+import FilterIcon from '@phosphor/funnel-simple.svg';
+import SortIcon from '@phosphor/sort-ascending.svg';
+import GroupIcon from '@phosphor/stack.svg';
+import { buttonClasses, cn, Dropdown } from '@ui';
+import { For, type JSX, Show } from 'solid-js';
+
+export type ListControlOption<TId extends string> = {
+ id: TId;
+ label: string;
+ icon?: () => JSX.Element;
+ disabled?: boolean;
+};
+
+type SingleSelectDropdownProps<TId extends string> = {
+ label: string;
+ icon: JSX.Element;
+ value: TId;
+ options: ListControlOption<TId>[];
+ onChange: (value: TId) => void;
+ class?: string;
+ contentClass?: string;
+};
+
+function SingleSelectDropdown<TId extends string>(
+ props: SingleSelectDropdownProps<TId>
+) {
+ return (
+ <Dropdown placement="bottom-end">
+ <Dropdown.Trigger
+ variant="outline"
+ size="md"
+ square
+ depth={2}
+ class={cn('rounded-lg bg-surface', props.class)}
+ label={props.label}
+ >
+ {props.icon}
+ </Dropdown.Trigger>
+ <Dropdown.Content class={cn('min-w-40', props.contentClass)}>
+ <Dropdown.Group>
+ <Dropdown.RadioGroup
+ value={props.value}
+ onChange={(value) => props.onChange(value as TId)}
+ >
+ <For each={props.options}>
+ {(option) => (
+ <Dropdown.RadioItem
+ closeOnSelect
+ value={option.id}
+ disabled={option.disabled}
+ >
+ <Show when={option.icon}>
+ <span
+ aria-hidden="true"
+ class="flex size-3.5 shrink-0 items-center justify-center [&_svg]:size-3.5"
+ >
+ {option.icon?.()}
+ </span>
+ </Show>
+ <span class="flex-1">{option.label}</span>
+ <Dropdown.ItemIndicator>
+ <CheckIcon class="size-3.5 text-accent" />
+ </Dropdown.ItemIndicator>
+ </Dropdown.RadioItem>
+ )}
+ </For>
+ </Dropdown.RadioGroup>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ );
+}
+
+export type ListSortDropdownProps<TId extends string> = Omit<
+ SingleSelectDropdownProps<TId>,
+ 'icon' | 'label'
+> & {
+ label?: string;
+};
+
+export function ListSortDropdown<TId extends string>(
+ props: ListSortDropdownProps<TId>
+) {
+ return (
+ <SingleSelectDropdown
+ {...props}
+ label={props.label ?? 'Sort list'}
+ icon={<SortIcon />}
+ />
+ );
+}
+
+export type ListGroupDropdownProps<TId extends string> = Omit<
+ SingleSelectDropdownProps<TId>,
+ 'icon' | 'label'
+> & {
+ label?: string;
+};
+
+export function ListGroupDropdown<TId extends string>(
+ props: ListGroupDropdownProps<TId>
+) {
+ return (
+ <SingleSelectDropdown
+ {...props}
+ label={props.label ?? 'Group list'}
+ icon={<GroupIcon />}
+ />
+ );
+}
+
+export type ListFilterGroup<
+ TGroupId extends string,
+ TOptionId extends string,
+> = {
+ id: TGroupId;
+ label: string;
+ options: ListControlOption<TOptionId>[];
+ contentClass?: string;
+};
+
+export type ListFilterDropdownProps<
+ TGroupId extends string,
+ TOptionId extends string,
+> = {
+ groups: ListFilterGroup<TGroupId, TOptionId>[];
+ isSelected: (groupId: TGroupId, optionId: TOptionId) => boolean;
+ onSelectionChange: (
+ groupId: TGroupId,
+ optionId: TOptionId,
+ selected: boolean
+ ) => void;
+ onClear?: () => void;
+ label?: string;
+ clearLabel?: string;
+ class?: string;
+ contentClass?: string;
+};
+
+export function ListFilterDropdown<
+ TGroupId extends string,
+ TOptionId extends string,
+>(props: ListFilterDropdownProps<TGroupId, TOptionId>) {
+ return (
+ <Dropdown placement="bottom-end">
+ <Dropdown.Trigger
+ variant="outline"
+ size="md"
+ square
+ depth={2}
+ class={cn('rounded-lg bg-surface', props.class)}
+ label={props.label ?? 'Filter list'}
+ >
+ <FilterIcon />
+ </Dropdown.Trigger>
+ <Dropdown.Content class={cn('min-w-40', props.contentClass)}>
+ <Dropdown.Group>
+ <For each={props.groups}>
+ {(group) => {
+ const hasSelection = () =>
+ group.options.some((option) =>
+ props.isSelected(group.id, option.id)
+ );
+
+ return (
+ <Dropdown.Sub>
+ <Dropdown.SubTrigger>
+ <span class="flex-1 text-ink">{group.label}</span>
+ <Show when={hasSelection()}>
+ <span
+ aria-hidden="true"
+ class="size-1.5 shrink-0 rounded-full bg-accent"
+ />
+ </Show>
+ <CaretRightIcon class="size-3 shrink-0 text-ink-muted" />
+ </Dropdown.SubTrigger>
+ <Dropdown.SubContent
+ class={cn(
+ 'max-h-72 w-65 max-w-[90vw] overflow-y-auto',
+ group.contentClass
+ )}
+ >
+ <Dropdown.Group>
+ <For each={group.options}>
+ {(option) => (
+ <Dropdown.CheckboxItem
+ checked={props.isSelected(group.id, option.id)}
+ closeOnSelect={false}
+ disabled={option.disabled}
+ onChange={(selected) =>
+ props.onSelectionChange(
+ group.id,
+ option.id,
+ selected
+ )
+ }
+ >
+ <span class="ml-1 flex min-w-0 flex-1 items-center gap-1.5">
+ <Show when={option.icon}>
+ <span
+ aria-hidden="true"
+ class="flex size-3.5 shrink-0 items-center justify-center [&_svg]:size-3.5"
+ >
+ {option.icon?.()}
+ </span>
+ </Show>
+ <span class="flex-1 truncate">
+ {option.label}
+ </span>
+ </span>
+ </Dropdown.CheckboxItem>
+ )}
+ </For>
+ </Dropdown.Group>
+ </Dropdown.SubContent>
+ </Dropdown.Sub>
+ );
+ }}
+ </For>
+ </Dropdown.Group>
+ <Show when={props.onClear}>
+ {(onClear) => (
+ <Dropdown.Group>
+ <Dropdown.Item
+ class={buttonClasses({
+ variant: 'strong',
+ size: 'sm',
+ fullWidth: true,
+ class:
+ 'rounded-lg text-xs data-highlighted:bg-ink data-highlighted:text-surface-4 data-highlighted:overlay-[color-mix(in_oklch,var(--color-surface-4)_12%,transparent)]',
+ })}
+ onSelect={onClear()}
+ >
+ {props.clearLabel ?? 'Clear filters'}
+ </Dropdown.Item>
+ </Dropdown.Group>
+ )}
+ </Show>
+ </Dropdown.Content>
+ </Dropdown>
+ );
+}
diff --git a/apps/web/src/components/view-shell/SearchBar.tsx b/apps/web/src/components/view-shell/SearchBar.tsx
new file mode 100644
index 0000000000..49133835a2
--- /dev/null
+++ b/apps/web/src/components/view-shell/SearchBar.tsx
@@ -0,0 +1,98 @@
+import { TextField } from '@kobalte/core/text-field';
+import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';
+import XIcon from '@phosphor/x.svg';
+import { mergeRefs } from '@solid-primitives/refs';
+import { Button, cn, Hotkey, Surface } from '@ui';
+import type { JSX } from 'solid-js';
+import { Show, splitProps } from 'solid-js';
+
+export type SearchBarProps = Omit<
+ JSX.InputHTMLAttributes<HTMLInputElement>,
+ 'children' | 'class' | 'onInput' | 'type' | 'value'
+> & {
+ label: string;
+ value: string;
+ onValueChange: (value: string) => void;
+ hotkey?: string;
+ class?: string;
+ inputClass?: string;
+};
+
+export function SearchBar(props: SearchBarProps) {
+ const [local, inputProps] = splitProps(props, [
+ 'label',
+ 'value',
+ 'onValueChange',
+ 'hotkey',
+ 'class',
+ 'inputClass',
+ 'disabled',
+ 'id',
+ 'name',
+ 'readOnly',
+ 'ref',
+ 'required',
+ ]);
+
+ let input: HTMLInputElement | undefined;
+ const clear = () => {
+ local.onValueChange('');
+ queueMicrotask(() => input?.focus());
+ };
+
+ return (
+ <Surface
+ depth={2}
+ class={cn('h-10 w-full min-w-0 rounded-2xl text-ink', local.class)}
+ data-search-bar=""
+ >
+ <TextField
+ id={local.id}
+ name={local.name}
+ value={local.value}
+ onChange={local.onValueChange}
+ disabled={local.disabled}
+ readOnly={local.readOnly}
+ required={local.required}
+ class="group flex size-full min-w-0 items-center gap-2 px-3"
+ >
+ <TextField.Label class="sr-only">{local.label}</TextField.Label>
+ <MagnifyingGlassIcon
+ aria-hidden="true"
+ class="size-4 shrink-0 text-ink-extra-muted"
+ />
+ <TextField.Input
+ {...inputProps}
+ ref={mergeRefs((element) => (input = element), local.ref)}
+ type="search"
+ class={cn(
+ 'min-w-0 flex-1 border-0 bg-transparent text-sm text-ink outline-none placeholder:text-ink-placeholder focus:outline-none focus:ring-0 [&::-webkit-search-cancel-button]:hidden',
+ local.inputClass
+ )}
+ />
+ <Show when={!local.value && local.hotkey}>
+ {(hotkey) => (
+ <Hotkey
+ shortcut={hotkey()}
+ theme="subtle"
+ class="shrink-0 group-focus-within:hidden"
+ />
+ )}
+ </Show>
+ <Show when={local.value && !local.disabled && !local.readOnly}>
+ <Button
+ type="button"
+ size="sm"
+ square
+ label="Clear search"
+ class="rounded-lg"
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={clear}
+ >
+ <XIcon />
+ </Button>
+ </Show>
+ </TextField>
+ </Surface>
+ );
+}
diff --git a/apps/web/src/components/view-shell/ViewShell.tsx b/apps/web/src/components/view-shell/ViewShell.tsx
new file mode 100644
index 0000000000..7a9eb8f5d8
--- /dev/null
+++ b/apps/web/src/components/view-shell/ViewShell.tsx
@@ -0,0 +1,422 @@
+import {
+ type BreakpointAccessors,
+ type BreakpointThresholds,
+ createSizeBreakpoints,
+} from '@app/util/create-size-breakpoints';
+import { Resize } from '@core/component/Resize';
+import { createElementSize } from '@solid-primitives/resize-observer';
+import { cn } from '@ui';
+import {
+ type Accessor,
+ createContext,
+ createSignal,
+ createUniqueId,
+ type JSX,
+ Match,
+ Show,
+ Switch,
+ splitProps,
+ useContext,
+} from 'solid-js';
+import {
+ type AsideLayout,
+ type AsideMode,
+ DEFAULT_ASIDE_LAYOUT,
+ DEFAULT_DETAIL_LAYOUT,
+ DEFAULT_LAYOUT_BREAKPOINT,
+ DEFAULT_MAIN_LAYOUT,
+ DEFAULT_VIEW_SHELL_BREAKPOINT_THRESHOLDS,
+ type DetailLayout,
+ type DetailPlacement,
+ type MainLayout,
+} from './view-shell-layout';
+
+export type ViewShellLayout = {
+ width: Accessor<number | undefined>;
+ /**
+ * Keyed reactive breakpoints from {@link createSizeBreakpoints}.
+ * Read as `breakpoints.narrow?.()`, `breakpoints.dense?.()`, …
+ */
+ breakpoints: BreakpointAccessors;
+ aside: {
+ layout: Accessor<AsideLayout>;
+ mode: Accessor<AsideMode>;
+ isCollapsed: Accessor<boolean>;
+ };
+ main: {
+ layout: Accessor<MainLayout>;
+ };
+ detail: {
+ layout: Accessor<DetailLayout>;
+ isOpen: Accessor<boolean>;
+ placement: Accessor<DetailPlacement>;
+ open: () => void;
+ close: () => void;
+ toggle: () => void;
+ };
+};
+
+type ViewShellInternal = ViewShellLayout & { id: string };
+
+const RESIZE_GUTTER = 8;
+
+const ViewShellContext = createContext<ViewShellInternal>();
+
+function useViewShellInternal(): ViewShellInternal {
+ const ctx = useContext(ViewShellContext);
+ if (!ctx) {
+ throw new Error('ViewShell slots require <ViewShell.Root>');
+ }
+ return ctx;
+}
+
+export function useViewShell(): ViewShellLayout {
+ const ctx = useViewShellInternal();
+ return {
+ width: ctx.width,
+ breakpoints: ctx.breakpoints,
+ aside: ctx.aside,
+ main: ctx.main,
+ detail: ctx.detail,
+ };
+}
+
+export type ViewShellRootProps = Omit<
+ JSX.HTMLAttributes<HTMLDivElement>,
+ 'children'
+> & {
+ children: JSX.Element;
+ /**
+ * Breakpoint thresholds passed to {@link createSizeBreakpoints}.
+ * Each value is a max-width number or `{ min?, max? }`.
+ * Defaults to {@link DEFAULT_VIEW_SHELL_BREAKPOINT_THRESHOLDS} (`narrow: 720`).
+ */
+ breakpoints?: BreakpointThresholds;
+ /**
+ * Breakpoint key that drives aside collapse and detail narrow behavior.
+ * Must exist on `breakpoints`. Defaults to `"narrow"`.
+ */
+ layoutBreakpoint?: string;
+ /**
+ * When true, Aside/Main/Detail panels expose drag gutters via Resize.
+ * Defaults to false — panels still size via the Resize solver, without handles.
+ */
+ resizable?: boolean;
+ /** Set to false when the workspace has no navigation region. */
+ aside?: false | Partial<AsideLayout>;
+ main?: Partial<MainLayout>;
+ detail?: Partial<DetailLayout>;
+ /** Controlled detail open state. Omit for uncontrolled. */
+ detailOpen?: boolean;
+ /** Uncontrolled initial open state when `detailOpen` is omitted. */
+ defaultDetailOpen?: boolean;
+ onDetailOpenChange?: (open: boolean) => void;
+};
+
+/**
+ * Root of one workspace. Owns measurement, panel track, detail open-state,
+ * and layout context. Renders a plain div. Landmark elements come from
+ * ViewSidebar and Main.
+ */
+function Root(props: ViewShellRootProps) {
+ const [local, rest] = splitProps(props, [
+ 'children',
+ 'class',
+ 'breakpoints',
+ 'layoutBreakpoint',
+ 'resizable',
+ 'aside',
+ 'main',
+ 'detail',
+ 'detailOpen',
+ 'defaultDetailOpen',
+ 'onDetailOpenChange',
+ ]);
+
+ const id = createUniqueId();
+ const [root, setRoot] = createSignal<HTMLDivElement>();
+ const size = createElementSize(root);
+
+ const thresholds = (): BreakpointThresholds =>
+ local.breakpoints ?? DEFAULT_VIEW_SHELL_BREAKPOINT_THRESHOLDS;
+ const layoutKey = () => {
+ const key = local.layoutBreakpoint ?? DEFAULT_LAYOUT_BREAKPOINT;
+ if (!(key in thresholds())) {
+ throw new Error(
+ `ViewShell layoutBreakpoint "${key}" is not defined in breakpoints`
+ );
+ }
+ return key;
+ };
+
+ const asideLayout = (): AsideLayout => ({
+ ...DEFAULT_ASIDE_LAYOUT,
+ ...(local.aside || {}),
+ });
+
+ const mainLayout = (): MainLayout => ({
+ ...DEFAULT_MAIN_LAYOUT,
+ ...local.main,
+ });
+
+ const detailLayout = (): DetailLayout => ({
+ ...DEFAULT_DETAIL_LAYOUT,
+ ...local.detail,
+ });
+
+ const controlled = () => local.detailOpen !== undefined;
+ const [uncontrolledOpen, setUncontrolledOpen] = createSignal(
+ local.defaultDetailOpen ?? false
+ );
+
+ const isOpen = () =>
+ controlled() ? (local.detailOpen ?? false) : uncontrolledOpen();
+
+ const setOpen = (next: boolean) => {
+ if (isOpen() === next) return;
+ if (!controlled()) setUncontrolledOpen(next);
+ local.onDetailOpenChange?.(next);
+ };
+
+ const resizable = () => local.resizable ?? false;
+ const width = () => size.width ?? undefined;
+ const breakpoints = createSizeBreakpoints(width, thresholds);
+
+ const atLayoutBreakpoint = () => {
+ const match = breakpoints[layoutKey()];
+ return match ? match() : false;
+ };
+
+ const asideMode = (): AsideMode =>
+ local.aside === false || atLayoutBreakpoint() ? 'collapsed' : 'docked';
+
+ const canFitInlineDetail = () => {
+ const currentWidth = width();
+ if (currentWidth === undefined) return false;
+
+ const asideMin = asideMode() === 'docked' ? asideLayout().min : 0;
+ const panelCount = asideMode() === 'docked' ? 3 : 2;
+ const minimumWidth =
+ asideMin +
+ mainLayout().min +
+ detailLayout().min +
+ (panelCount - 1) * RESIZE_GUTTER;
+ return currentWidth >= minimumWidth;
+ };
+
+ const placement = (): DetailPlacement => {
+ if (!isOpen()) return 'hidden';
+ if (!atLayoutBreakpoint() && canFitInlineDetail()) return 'inline';
+
+ const whenNarrow = detailLayout().whenNarrow;
+ return whenNarrow === 'hide' ? 'hidden' : whenNarrow;
+ };
+
+ const value: ViewShellInternal = {
+ id,
+ width,
+ breakpoints,
+ aside: {
+ layout: asideLayout,
+ mode: asideMode,
+ isCollapsed: () => asideMode() === 'collapsed',
+ },
+ main: {
+ layout: mainLayout,
+ },
+ detail: {
+ layout: detailLayout,
+ isOpen,
+ placement,
+ open: () => {
+ setOpen(true);
+ },
+ close: () => {
+ setOpen(false);
+ },
+ toggle: () => {
+ setOpen(!isOpen());
+ },
+ },
+ };
+
+ return (
+ <ViewShellContext.Provider value={value}>
+ <div
+ {...rest}
+ ref={setRoot}
+ class={cn(
+ '@container/view-shell relative size-full min-h-0 min-w-0',
+ local.class
+ )}
+ data-view-shell=""
+ data-view-shell-layout={atLayoutBreakpoint() ? layoutKey() : undefined}
+ >
+ <Resize.Zone
+ direction="horizontal"
+ gutter={RESIZE_GUTTER}
+ resizable={resizable()}
+ >
+ {local.children}
+ </Resize.Zone>
+ </div>
+ </ViewShellContext.Provider>
+ );
+}
+
+/**
+ * Sizing region for navigation. Renders a div, not aside.
+ * ViewSidebar.Root inside keeps the landmark.
+ */
+function Aside(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ const ws = useViewShellInternal();
+
+ return (
+ <Resize.Panel
+ id={`${ws.id}-aside`}
+ index={0}
+ minSize={ws.aside.layout().min}
+ maxSize={ws.aside.layout().max}
+ target={{ kind: 'px', px: ws.aside.layout().width }}
+ collapsed={() => ws.aside.isCollapsed()}
+ >
+ <div
+ {...rest}
+ class={cn('size-full min-h-0 min-w-0', local.class)}
+ data-view-shell-aside=""
+ >
+ {local.children}
+ </div>
+ </Resize.Panel>
+ );
+}
+
+function Main(props: JSX.HTMLAttributes<HTMLElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ const ws = useViewShellInternal();
+ const layout = ws.main.layout;
+ const target = () => {
+ const width = layout().width;
+ if (ws.detail.placement() !== 'inline' || width === undefined) {
+ return undefined;
+ }
+ return { kind: 'px' as const, px: width };
+ };
+
+ return (
+ <Resize.Panel
+ id={`${ws.id}-main`}
+ index={1}
+ minSize={layout().min}
+ maxSize={ws.detail.placement() === 'inline' ? layout().max : undefined}
+ target={target()}
+ >
+ <main
+ {...rest}
+ class={cn('flex size-full min-h-0 min-w-0 flex-col', local.class)}
+ data-view-shell-main=""
+ >
+ {local.children}
+ </main>
+ </Resize.Panel>
+ );
+}
+
+function Header(props: JSX.HTMLAttributes<HTMLElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <header
+ {...rest}
+ class={cn(
+ 'shrink-0 px-4 pb-5 pt-4 @max-[760px]/view-shell:px-3 @max-[480px]/view-shell:px-2',
+ local.class
+ )}
+ data-view-shell-header=""
+ >
+ {local.children}
+ </header>
+ );
+}
+
+function Content(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ const ws = useViewShellInternal();
+
+ return (
+ <Show when={ws.detail.placement() !== 'replace'}>
+ <div
+ {...rest}
+ class={cn(
+ 'min-h-0 min-w-0 flex-1 px-4 pb-4 @max-[760px]/view-shell:px-3 @max-[480px]/view-shell:px-2',
+ local.class
+ )}
+ data-view-shell-content=""
+ >
+ {local.children}
+ </div>
+ </Show>
+ );
+}
+
+function Detail(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ const ws = useViewShellInternal();
+ const layout = ws.detail.layout;
+
+ return (
+ <Switch>
+ <Match when={ws.detail.placement() === 'inline'}>
+ <Resize.Panel
+ id={`${ws.id}-detail`}
+ index={2}
+ minSize={layout().min}
+ maxSize={layout().max}
+ target={{ kind: 'px', px: layout().width }}
+ >
+ <div
+ {...rest}
+ class={cn('size-full min-h-0 min-w-0', local.class)}
+ data-view-shell-detail=""
+ data-view-shell-detail-placement="inline"
+ >
+ {local.children}
+ </div>
+ </Resize.Panel>
+ </Match>
+ <Match when={ws.detail.placement() === 'overlay'}>
+ <div
+ {...rest}
+ class={cn(
+ 'absolute inset-y-0 right-0 z-10 min-h-0 border-l border-edge bg-panel shadow-menu',
+ local.class
+ )}
+ style={{ width: `${layout().width}px`, 'max-width': '100%' }}
+ data-view-shell-detail=""
+ data-view-shell-detail-placement="overlay"
+ >
+ {local.children}
+ </div>
+ </Match>
+ <Match when={ws.detail.placement() === 'replace'}>
+ <div
+ {...rest}
+ class={cn('absolute inset-0 z-10 min-h-0 min-w-0', local.class)}
+ data-view-shell-detail=""
+ data-view-shell-detail-placement="replace"
+ >
+ {local.children}
+ </div>
+ </Match>
+ </Switch>
+ );
+}
+
+export const ViewShell = Object.assign(Root, {
+ Root,
+ Aside,
+ Main,
+ Header,
+ Content,
+ Detail,
+});
diff --git a/apps/web/src/components/view-shell/ViewSidebar.tsx b/apps/web/src/components/view-shell/ViewSidebar.tsx
new file mode 100644
index 0000000000..0bf9f0a304
--- /dev/null
+++ b/apps/web/src/components/view-shell/ViewSidebar.tsx
@@ -0,0 +1,108 @@
+import { cn, NavRow, type NavRowProps } from '@ui';
+import type { JSX } from 'solid-js';
+import { splitProps } from 'solid-js';
+
+function Root(props: JSX.HTMLAttributes<HTMLElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <aside
+ {...rest}
+ class={cn(
+ 'flex size-full min-h-0 min-w-0 flex-col border-r border-edge px-4 pb-5 pt-4',
+ local.class
+ )}
+ data-view-sidebar=""
+ >
+ {local.children}
+ </aside>
+ );
+}
+
+function Header(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <div
+ {...rest}
+ class={cn(
+ 'flex min-w-0 shrink-0 items-center justify-between gap-3',
+ local.class
+ )}
+ data-view-sidebar-header=""
+ >
+ {local.children}
+ </div>
+ );
+}
+
+function Title(props: JSX.HTMLAttributes<HTMLHeadingElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <h1
+ {...rest}
+ class={cn(
+ 'min-w-0 truncate text-2xl font-semibold tracking-[-0.03em] text-ink',
+ local.class
+ )}
+ >
+ {local.children}
+ </h1>
+ );
+}
+
+function Content(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <div
+ {...rest}
+ class={cn('min-h-0 min-w-0 flex-1 overflow-auto', local.class)}
+ data-view-sidebar-content=""
+ >
+ {local.children}
+ </div>
+ );
+}
+
+function Nav(props: JSX.HTMLAttributes<HTMLElement>) {
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <nav {...rest} class={cn('flex min-w-0 flex-col gap-0.5', local.class)}>
+ {local.children}
+ </nav>
+ );
+}
+
+function Item(props: NavRowProps) {
+ const [local, rest] = splitProps(props, [
+ 'active',
+ 'aria-current',
+ 'class',
+ 'type',
+ ]);
+ const ariaCurrent = () => {
+ if (local['aria-current'] !== undefined) return local['aria-current'];
+ if (local.active) return 'page';
+ return undefined;
+ };
+ return (
+ <NavRow
+ {...rest}
+ type={local.type ?? 'button'}
+ active={local.active}
+ aria-current={ariaCurrent()}
+ class={cn(
+ 'h-9 gap-2.5 rounded-xl px-3 py-2 text-sm font-medium text-ink-muted not-disabled:hover:bg-hover not-disabled:hover:text-ink',
+ local.active && 'bg-active text-ink not-disabled:hover:bg-active',
+ local.class
+ )}
+ />
+ );
+}
+
+export const ViewSidebar = Object.assign(Root, {
+ Root,
+ Header,
+ Title,
+ Content,
+ Nav,
+ Item,
+});
diff --git a/apps/web/src/components/view-shell/index.ts b/apps/web/src/components/view-shell/index.ts
new file mode 100644
index 0000000000..33f420327a
--- /dev/null
+++ b/apps/web/src/components/view-shell/index.ts
@@ -0,0 +1,35 @@
+export {
+ CollapsibleSection,
+ type CollapsibleSectionRootProps,
+} from './CollapsibleSection';
+export {
+ type ListControlOption,
+ ListFilterDropdown,
+ type ListFilterDropdownProps,
+ type ListFilterGroup,
+ ListGroupDropdown,
+ type ListGroupDropdownProps,
+ ListSortDropdown,
+ type ListSortDropdownProps,
+} from './ListDropdowns';
+export { SearchBar, type SearchBarProps } from './SearchBar';
+export {
+ useViewShell,
+ ViewShell,
+ type ViewShellLayout,
+ type ViewShellRootProps,
+} from './ViewShell';
+export { ViewSidebar } from './ViewSidebar';
+export {
+ type AsideLayout,
+ type AsideMode,
+ DEFAULT_ASIDE_LAYOUT,
+ DEFAULT_DETAIL_LAYOUT,
+ DEFAULT_LAYOUT_BREAKPOINT,
+ DEFAULT_MAIN_LAYOUT,
+ DEFAULT_VIEW_SHELL_BREAKPOINT_THRESHOLDS,
+ type DetailLayout,
+ type DetailNarrowBehavior,
+ type DetailPlacement,
+ type MainLayout,
+} from './view-shell-layout';
diff --git a/apps/web/src/components/view-shell/view-shell-layout.ts b/apps/web/src/components/view-shell/view-shell-layout.ts
new file mode 100644
index 0000000000..b6581e7f7b
--- /dev/null
+++ b/apps/web/src/components/view-shell/view-shell-layout.ts
@@ -0,0 +1,57 @@
+import type { BreakpointThresholds } from '@app/util/create-size-breakpoints';
+
+export const DEFAULT_VIEW_SHELL_BREAKPOINT_THRESHOLDS = {
+ narrow: 720,
+} as const satisfies BreakpointThresholds;
+
+export type AsideLayout = {
+ width: number;
+ min: number;
+ max: number;
+};
+
+export const DEFAULT_ASIDE_LAYOUT: AsideLayout = {
+ width: 288,
+ min: 224,
+ max: 360,
+};
+
+export type MainLayout = {
+ width?: number;
+ min: number;
+ max?: number;
+};
+
+export const DEFAULT_MAIN_LAYOUT: MainLayout = {
+ min: 320,
+};
+
+export type DetailNarrowBehavior = 'overlay' | 'replace' | 'hide';
+
+export type DetailLayout = {
+ width: number;
+ min: number;
+ max: number;
+ whenNarrow: DetailNarrowBehavior;
+};
+
+export const DEFAULT_DETAIL_LAYOUT: DetailLayout = {
+ width: 420,
+ min: 320,
+ max: 640,
+ whenNarrow: 'overlay',
+};
+
+/**
+ * Where the shell puts the detail region right now.
+ *
+ * - `inline` — docked beside Content, reserving width in the resize solver.
+ * - `overlay` — floats above Content.
+ * - `replace` — takes over the Content area.
+ * - `hidden` — closed, or suppressed at the layout breakpoint.
+ */
+export type DetailPlacement = 'inline' | 'overlay' | 'replace' | 'hidden';
+
+export type AsideMode = 'docked' | 'collapsed';
+
+export const DEFAULT_LAYOUT_BREAKPOINT = 'narrow';
diff --git a/apps/web/src/features/entity/EntitySelectionToolbar.tsx b/apps/web/src/features/entity/EntitySelectionToolbar.tsx
new file mode 100644
index 0000000000..7bb644c9b6
--- /dev/null
+++ b/apps/web/src/features/entity/EntitySelectionToolbar.tsx
@@ -0,0 +1,28 @@
+import { CommandState } from '@app/features/command/state';
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { EntitySelectionToolbarModal } from './EntitySelectionToolbarModal';
+import type { EntityData } from './types/entity';
+
+export type EntitySelectionToolbarProps = {
+ selected: EntityData[];
+ onClear: VoidFunction;
+ analyticsSource?: string;
+};
+
+export function EntitySelectionToolbar(props: EntitySelectionToolbarProps) {
+ const analytics = useAnalytics();
+
+ return (
+ <EntitySelectionToolbarModal
+ multiSelectEntities={props.selected}
+ onClose={props.onClear}
+ onAction={() => {
+ if (props.selected.length === 0) return;
+ analytics.track('command_menu_open', {
+ from: props.analyticsSource ?? 'entity_list_selection_toolbar',
+ });
+ CommandState.openForEntityAction(props.selected);
+ }}
+ />
+ );
+}
diff --git a/apps/web/src/features/entity/index.ts b/apps/web/src/features/entity/index.ts
index c7a1eb0432..331abb6c0e 100644
--- a/apps/web/src/features/entity/index.ts
+++ b/apps/web/src/features/entity/index.ts
@@ -14,6 +14,10 @@ export {
ListEntityMetadataQueryProvider,
ListEntityNoopMetadataProvider,
} from './composed/list-entity/list-entity-metadata-provider';
+export {
+ EntitySelectionToolbar,
+ type EntitySelectionToolbarProps,
+} from './EntitySelectionToolbar';
export { Entity } from './entity';
export { EntityIcon as EntityRowIcon } from './extractors/entity-icon';
export { EntityTitle as EntityRowTitle } from './extractors/entity-title';
diff --git a/apps/web/src/features/next-soup/soup-view/group-by-date.ts b/apps/web/src/features/next-soup/soup-view/group-by-date.ts
index ee29ac8d22..123eef04f5 100644
--- a/apps/web/src/features/next-soup/soup-view/group-by-date.ts
+++ b/apps/web/src/features/next-soup/soup-view/group-by-date.ts
@@ -1,38 +1 @@
-import {
- differenceInCalendarDays,
- isSameMonth,
- isToday,
- isYesterday,
- subMonths,
-} from 'date-fns';
-
-export type DateBucket = { key: string; label: string };
-
-/**
- * Bucket a timestamp into a relative section: Today, Yesterday, Last 7 days,
- * Earlier this month, Last month, then Older. The `key` is stable/collapsible;
- * the `label` is the section header text.
- *
- * Generic and client-side — used to group soup rows by date without relying on
- * backend grouping.
- */
-export function dateBucket(value: unknown, now = new Date()): DateBucket {
- const date =
- value == null ? undefined : new Date(value as string | number | Date);
-
- if (!date || Number.isNaN(date.getTime())) {
- return { key: 'older', label: 'Older' };
- }
- if (isToday(date)) return { key: 'today', label: 'Today' };
- if (isYesterday(date)) return { key: 'yesterday', label: 'Yesterday' };
- if (differenceInCalendarDays(now, date) < 7) {
- return { key: 'last-7-days', label: 'Last 7 days' };
- }
- if (isSameMonth(date, now)) {
- return { key: 'earlier-this-month', label: 'Earlier this month' };
- }
- if (isSameMonth(date, subMonths(now, 1))) {
- return { key: 'last-month', label: 'Last month' };
- }
- return { key: 'older', label: 'Older' };
-}
+export { type DateBucket, dateBucket } from '@app/features/soup';
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
index 582fb9cfaa..2a8409e5f2 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
@@ -29,7 +29,6 @@ import {
getViewPreset,
VIEW_TAB_PRESETS,
} from '@app/features/next-soup/sidebar/soup-filter-presets';
-import { createGroupedSoupQueries } from '@app/features/next-soup/soup-view/create-grouped-soup-queries';
import { createSearchState } from '@app/features/next-soup/soup-view/create-search-state';
import {
createTagFilter,
@@ -41,10 +40,8 @@ import {
registerInboxFilterSplit,
} from '@app/features/next-soup/soup-view/inbox-filter-controllers';
import { useSoupFilterPersistence } from '@app/features/next-soup/use-soup-filter-persistence';
-import {
- deduplicateEntities,
- scopeChannelNotificationsForEntity,
-} from '@app/features/next-soup/utils';
+import { deduplicateEntities } from '@app/features/next-soup/utils';
+import { withEntityNotifications } from '@app/features/soup/entity-notifications';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { makeFlaggedPersisted } from '@app/preferences/make-flagged-persisted';
import { useDealStages } from '@companies/crm/deal-stages';
@@ -69,14 +66,12 @@ import {
type EntityData,
getPropertyOptionLabel,
isWithNotification,
- type Notification,
- toNotificationEntity,
unreadFilterFn,
} from '@entity';
-import { useNotificationsForEntity } from '@notifications';
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import { useQueryClient } from '@queries/client';
import { invalidateUserNotifications } from '@queries/notification/user-notifications';
+import { createGroupedSoupQueries } from '@queries/soup/grouped/create-grouped-soup-queries';
import type {
GroupMeta as ApiGroupMeta,
GroupByField,
@@ -286,10 +281,6 @@ const VALID_API_SORT_METHODS: ApiSortMethod[] = [
'viewed_updated',
];
-type EntityWithRawNotifications = EntityData & {
- notifications?: Notification[];
-};
-
const NATIVE_OFFLINE_LOAD_ERROR = new Error(NATIVE_OFFLINE_ERROR_MESSAGE);
/** Retryable load error for a data-less view once iOS reports no network path. */
@@ -299,13 +290,6 @@ function nativeOfflineLoadError(hasData: () => boolean): Error | null {
: null;
}
-function rawEntityNotifications(
- entity: EntityData
-): Notification[] | undefined {
- const notifications = (entity as EntityWithRawNotifications).notifications;
- return Array.isArray(notifications) ? notifications : undefined;
-}
-
export const SoupViewContextProvider: FlowComponent<
SoupViewContextProviderProps
> = (props) => {
@@ -923,37 +907,10 @@ export const SoupViewContextProvider: FlowComponent<
// the migration to graphql. We should not need this since
// the items themselves have the notifications on them. Remove
// when completely migrated
- const attachNotifications = (entity: EntityData) => {
- const rawNotifications = rawEntityNotifications(entity);
- if (rawNotifications) {
- const {
- notifications: _notifications,
- ...entityWithoutRawNotifications
- } = entity as EntityWithRawNotifications;
- return {
- ...entityWithoutRawNotifications,
- notifications: () =>
- isInboxView()
- ? scopeChannelNotificationsForEntity(
- entityWithoutRawNotifications,
- rawNotifications
- )
- : rawNotifications,
- };
- }
-
- const notifications = useNotificationsForEntity(
- notificationSource,
- toNotificationEntity(entity)
- );
- return {
- ...entity,
- notifications: () =>
- isInboxView()
- ? scopeChannelNotificationsForEntity(entity, notifications())
- : notifications(),
- };
- };
+ const attachNotifications = (entity: EntityData) =>
+ withEntityNotifications(entity, notificationSource, {
+ scopeChannelThreads: isInboxView(),
+ });
// Active tag option ids and combine mode, used to gate optimistic websocket
// inserts so an active tag filter is honored even on the grouped render path.
@@ -1185,8 +1142,7 @@ export const SoupViewContextProvider: FlowComponent<
groupByField: serverGroupByField,
soupParams,
soupBody,
- graphqlReactive: () =>
- itemsQuery.transport === 'graphql' && serverGroupByField() !== undefined,
+ transport: () => itemsQuery.transport,
queryOptions: () => {
const view = activeListView();
return {
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index 583f956d48..425acee6da 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -1,4 +1,5 @@
import { isListViewID } from '@app/constants/list-views';
+import { scopeChannelNotificationsForEntity } from '@app/features/soup/entity-notifications';
import { globalSplitManager } from '@app/signal/splitLayout';
import { createCalendarBlockRange } from '@block-calendar/calendar-range';
import {
@@ -55,13 +56,11 @@ import {
} from '@entity';
import {
compositeEntity,
- getAllNotificationsFromGroup,
getChannelNotificationParams,
markNotificationsForEntityAsRead,
type NotificationSource,
notificationIsRead,
setDoneOverride,
- stackNotifications,
type UnifiedNotification,
} from '@notifications';
import { queryClient } from '@queries/client';
@@ -93,6 +92,8 @@ import { isAfter } from 'date-fns';
import { match } from 'ts-pattern';
import { withPreviewSourceEntityId } from './preview-history';
+export { scopeChannelNotificationsForEntity };
+
const mergeSearchEntities = <T extends EntityData>(
first: WithSearch<T>,
second: WithSearch<T>
@@ -1130,81 +1131,6 @@ export type MarkEntitiesDoneContext = {
applyUndone: () => void;
};
-function channelThreadNotificationIds(
- notifications: UnifiedNotification[],
- threadId?: string
-): Set<string> {
- const ids = new Set<string>();
-
- if (threadId !== undefined) {
- for (const notification of notifications) {
- const metadata = notification.notification_metadata;
-
- const belongsToThread = match(metadata)
- .with(
- { tag: 'channel_message_send' },
- (m) => m.content.messageId === threadId
- )
- .with(
- { tag: 'channel_mention' },
- (m) => (m.content.threadId ?? m.content.messageId) === threadId
- )
- .with(
- { tag: 'channel_message_reply' },
- (m) => m.content.threadId === threadId
- )
- .otherwise(() => false);
-
- if (!belongsToThread) {
- continue;
- }
- ids.add(notification.id);
- }
-
- return ids;
- }
-
- for (const stack of stackNotifications(notifications)) {
- // New inbox renders thread replies and mentions separately from channels.
- if (
- stack.type !== 'channel_message_reply' &&
- stack.type !== 'channel_mention'
- ) {
- continue;
- }
-
- for (const notification of getAllNotificationsFromGroup(stack)) {
- ids.add(notification.id);
- }
- }
-
- return ids;
-}
-
-export function scopeChannelNotificationsForEntity(
- entity: EntityData,
- notifications: UnifiedNotification[]
-): UnifiedNotification[] {
- if (entity.type === 'channel') {
- const threadNotificationIds = channelThreadNotificationIds(notifications);
- return notifications.filter(
- (notification) => !threadNotificationIds.has(notification.id)
- );
- }
-
- if (entity.type === 'channel_thread') {
- const threadNotificationIds = channelThreadNotificationIds(
- notifications,
- entity.messageId
- );
- return notifications.filter((notification) =>
- threadNotificationIds.has(notification.id)
- );
- }
-
- return notifications;
-}
-
function notificationsForMarkDone(
entity: EntityData,
notifications: UnifiedNotification[],
diff --git a/apps/web/src/features/soup/collection/date-buckets.ts b/apps/web/src/features/soup/collection/date-buckets.ts
new file mode 100644
index 0000000000..96a7e0b1d1
--- /dev/null
+++ b/apps/web/src/features/soup/collection/date-buckets.ts
@@ -0,0 +1,32 @@
+import { differenceInCalendarDays, isSameMonth, subMonths } from 'date-fns';
+
+export type DateBucket = { key: string; label: string };
+
+/**
+ * Buckets a timestamp into stable relative-date sections for client-side lists.
+ */
+export function dateBucket(value: unknown, now = new Date()): DateBucket {
+ const date =
+ value instanceof Date
+ ? value
+ : typeof value === 'string' || typeof value === 'number'
+ ? new Date(value)
+ : undefined;
+
+ if (!date || Number.isNaN(date.getTime())) {
+ return { key: 'older', label: 'Older' };
+ }
+ const daysAgo = differenceInCalendarDays(now, date);
+ if (daysAgo === 0) return { key: 'today', label: 'Today' };
+ if (daysAgo === 1) return { key: 'yesterday', label: 'Yesterday' };
+ if (daysAgo > 1 && daysAgo < 7) {
+ return { key: 'last-7-days', label: 'Last 7 days' };
+ }
+ if (isSameMonth(date, now)) {
+ return { key: 'earlier-this-month', label: 'Earlier this month' };
+ }
+ if (isSameMonth(date, subMonths(now, 1))) {
+ return { key: 'last-month', label: 'Last month' };
+ }
+ return { key: 'older', label: 'Older' };
+}
diff --git a/apps/web/src/features/soup/collection/index.ts b/apps/web/src/features/soup/collection/index.ts
new file mode 100644
index 0000000000..10b279398c
--- /dev/null
+++ b/apps/web/src/features/soup/collection/index.ts
@@ -0,0 +1,36 @@
+export { type DateBucket, dateBucket } from './date-buckets';
+export {
+ assertUniqueSoupRowIds,
+ type BuildFlatSoupRowsOptions,
+ type BuildGroupedSoupRowsOptions,
+ buildFlatSoupRows,
+ buildGroupedSoupRows,
+ type CreateSoupEntityRowOptions,
+ createSoupEntityRow,
+ createSoupGroupHeaderRow,
+ createSoupLoadMoreRow,
+ createSoupSectionHeaderRow,
+ getSoupRowEntities,
+ getUniqueSoupRowEntities,
+ isSoupRowVisible,
+} from './rows';
+export {
+ type DeduplicateItemsOptions,
+ deduplicateItems,
+ deduplicateSoupEntities,
+ type GroupSoupEntitiesOptions,
+ groupSoupEntities,
+ prioritizeItems,
+ type SortDefinition,
+ type SortSelection,
+ sortItems,
+} from './transforms';
+export type {
+ SoupEntityIdentity,
+ SoupEntityRow,
+ SoupGroup,
+ SoupGroupHeaderRow,
+ SoupLoadMoreRow,
+ SoupRow,
+ SoupSectionHeaderRow,
+} from './types';
diff --git a/apps/web/src/features/soup/collection/rows.ts b/apps/web/src/features/soup/collection/rows.ts
new file mode 100644
index 0000000000..8a83a264e0
--- /dev/null
+++ b/apps/web/src/features/soup/collection/rows.ts
@@ -0,0 +1,191 @@
+import { deduplicateSoupEntities } from './transforms';
+import type {
+ SoupEntityIdentity,
+ SoupEntityRow,
+ SoupGroup,
+ SoupGroupHeaderRow,
+ SoupLoadMoreRow,
+ SoupRow,
+ SoupSectionHeaderRow,
+} from './types';
+
+const encodeRowIdSegment = (value: string | undefined) =>
+ value === undefined ? 'u' : `s${value.length}:${value}`;
+
+const createSoupRowId = (
+ kind: SoupRow['kind'],
+ ...segments: (string | undefined)[]
+): string =>
+ ['soup-row', kind, ...segments]
+ .map((segment) => encodeRowIdSegment(segment))
+ .join('|');
+
+export type CreateSoupEntityRowOptions = {
+ groupId?: string;
+ occurrenceId?: string;
+};
+
+export function createSoupEntityRow<TEntity extends SoupEntityIdentity>(
+ entity: TEntity,
+ options: CreateSoupEntityRowOptions = {}
+): SoupEntityRow<TEntity> {
+ return {
+ kind: 'entity',
+ id: createSoupRowId(
+ 'entity',
+ entity.type,
+ entity.id,
+ options.groupId,
+ options.occurrenceId
+ ),
+ entity,
+ ...(options.groupId === undefined ? {} : { groupId: options.groupId }),
+ ...(options.occurrenceId === undefined
+ ? {}
+ : { occurrenceId: options.occurrenceId }),
+ };
+}
+
+export const createSoupGroupHeaderRow = (
+ group: Pick<SoupGroup<SoupEntityIdentity>, 'id' | 'label' | 'count'>
+): SoupGroupHeaderRow => ({
+ kind: 'group-header',
+ id: createSoupRowId('group-header', group.id),
+ groupId: group.id,
+ label: group.label,
+ ...(group.count === undefined ? {} : { count: group.count }),
+});
+
+export const createSoupSectionHeaderRow = (
+ sectionId: string,
+ label: string
+): SoupSectionHeaderRow => ({
+ kind: 'section-header',
+ id: createSoupRowId('section-header', sectionId),
+ sectionId,
+ label,
+});
+
+export const createSoupLoadMoreRow = (options: {
+ scopeId: string;
+ groupId?: string;
+ label?: string;
+ isLoading?: boolean;
+}): SoupLoadMoreRow => ({
+ kind: 'load-more',
+ id: createSoupRowId('load-more', options.scopeId, options.groupId),
+ scopeId: options.scopeId,
+ ...(options.groupId === undefined ? {} : { groupId: options.groupId }),
+ ...(options.label === undefined ? {} : { label: options.label }),
+ ...(options.isLoading === undefined ? {} : { isLoading: options.isLoading }),
+});
+
+export type BuildFlatSoupRowsOptions<TEntity extends SoupEntityIdentity> = {
+ getOccurrenceId?: (entity: TEntity, index: number) => string | undefined;
+};
+
+const nextDuplicateOccurrence = (
+ entity: SoupEntityIdentity,
+ occurrences: Map<string, number>
+) => {
+ const key = entity.id;
+ const occurrence = occurrences.get(key) ?? 0;
+ occurrences.set(key, occurrence + 1);
+ return occurrence === 0 ? undefined : `duplicate-${occurrence}`;
+};
+
+export function assertUniqueSoupRowIds<TEntity extends SoupEntityIdentity>(
+ rows: SoupRow<TEntity>[]
+): void {
+ const ids = new Set<string>();
+ for (const row of rows) {
+ if (ids.has(row.id)) {
+ throw new Error(
+ `Soup rows must have unique occurrence IDs; received: ${row.id}`
+ );
+ }
+ ids.add(row.id);
+ }
+}
+
+export function buildFlatSoupRows<TEntity extends SoupEntityIdentity>(
+ entities: TEntity[],
+ options: BuildFlatSoupRowsOptions<TEntity> = {}
+): SoupEntityRow<TEntity>[] {
+ const occurrences = new Map<string, number>();
+ const rows = entities.map((entity, index) =>
+ createSoupEntityRow(entity, {
+ occurrenceId:
+ options.getOccurrenceId?.(entity, index) ??
+ nextDuplicateOccurrence(entity, occurrences),
+ })
+ );
+ assertUniqueSoupRowIds(rows);
+ return rows;
+}
+
+export type BuildGroupedSoupRowsOptions<TEntity extends SoupEntityIdentity> = {
+ getOccurrenceId?: (
+ entity: TEntity,
+ index: number,
+ group: SoupGroup<TEntity>
+ ) => string | undefined;
+};
+
+export function buildGroupedSoupRows<TEntity extends SoupEntityIdentity>(
+ groups: SoupGroup<TEntity>[],
+ options: BuildGroupedSoupRowsOptions<TEntity> = {}
+): SoupRow<TEntity>[] {
+ const groupIds = new Set<string>();
+ const rows = groups.flatMap((group) => {
+ if (groupIds.has(group.id)) {
+ throw new Error(
+ `Soup groups must have unique IDs; received: ${group.id}`
+ );
+ }
+ groupIds.add(group.id);
+
+ const groupRows: SoupRow<TEntity>[] = [createSoupGroupHeaderRow(group)];
+ const occurrences = new Map<string, number>();
+ group.entities.forEach((entity, index) => {
+ groupRows.push(
+ createSoupEntityRow(entity, {
+ groupId: group.id,
+ occurrenceId:
+ options.getOccurrenceId?.(entity, index, group) ??
+ nextDuplicateOccurrence(entity, occurrences),
+ })
+ );
+ });
+ if (group.loadMore) {
+ groupRows.push(
+ createSoupLoadMoreRow({
+ ...group.loadMore,
+ groupId: group.id,
+ })
+ );
+ }
+ return groupRows;
+ });
+ assertUniqueSoupRowIds(rows);
+ return rows;
+}
+
+export const getSoupRowEntities = <TEntity extends SoupEntityIdentity>(
+ rows: SoupRow<TEntity>[]
+): TEntity[] =>
+ rows.flatMap((row) => (row.kind === 'entity' ? [row.entity] : []));
+
+export function getUniqueSoupRowEntities<TEntity extends SoupEntityIdentity>(
+ rows: SoupRow<TEntity>[]
+): TEntity[] {
+ return deduplicateSoupEntities(getSoupRowEntities(rows));
+}
+
+export const isSoupRowVisible = <TEntity extends SoupEntityIdentity>(
+ row: SoupRow<TEntity>,
+ isGroupExpanded: (groupId: string) => boolean
+): boolean =>
+ row.kind === 'entity' || row.kind === 'load-more'
+ ? row.groupId === undefined || isGroupExpanded(row.groupId)
+ : true;
diff --git a/apps/web/src/features/soup/collection/transforms.ts b/apps/web/src/features/soup/collection/transforms.ts
new file mode 100644
index 0000000000..b1541b25cf
--- /dev/null
+++ b/apps/web/src/features/soup/collection/transforms.ts
@@ -0,0 +1,159 @@
+import type { SoupEntityIdentity, SoupGroup } from './types';
+
+export type DeduplicateItemsOptions<TItem> = {
+ getKey: (item: TItem) => string;
+ resolveConflict?: (existing: TItem, incoming: TItem) => TItem;
+};
+
+export function deduplicateItems<TItem>(
+ items: TItem[],
+ options: DeduplicateItemsOptions<TItem>
+): TItem[] {
+ const result: TItem[] = [];
+ const indexByKey = new Map<string, number>();
+
+ for (const item of items) {
+ const key = options.getKey(item);
+ const existingIndex = indexByKey.get(key);
+ if (existingIndex === undefined) {
+ indexByKey.set(key, result.length);
+ result.push(item);
+ continue;
+ }
+
+ if (options.resolveConflict) {
+ result[existingIndex] = options.resolveConflict(
+ result[existingIndex],
+ item
+ );
+ }
+ }
+
+ return result;
+}
+
+export const deduplicateSoupEntities = <TEntity extends SoupEntityIdentity>(
+ entities: TEntity[],
+ resolveConflict?: (existing: TEntity, incoming: TEntity) => TEntity
+): TEntity[] =>
+ deduplicateItems(entities, {
+ getKey: (entity) => entity.id,
+ resolveConflict,
+ });
+
+/**
+ * Moves caller-prioritized keys to the front while preserving all relative
+ * order not explicitly controlled by the priority sequence.
+ */
+export function prioritizeItems<TItem>(
+ items: TItem[],
+ priorityKeys: string[],
+ getKey: (item: TItem) => string
+): TItem[] {
+ const priority = new Map<string, number>();
+ priorityKeys.forEach((key, index) => {
+ if (!priority.has(key)) priority.set(key, index);
+ });
+ return items
+ .map((item, index) => ({ item, index }))
+ .sort((left, right) => {
+ const leftPriority = priority.get(getKey(left.item));
+ const rightPriority = priority.get(getKey(right.item));
+ if (leftPriority === undefined && rightPriority === undefined) {
+ return left.index - right.index;
+ }
+ if (leftPriority === undefined) return 1;
+ if (rightPriority === undefined) return -1;
+ return leftPriority - rightPriority || left.index - right.index;
+ })
+ .map(({ item }) => item);
+}
+
+export type SortDefinition<TItem, TId extends string = string> = {
+ id: TId;
+ compare: (left: TItem, right: TItem) => number;
+};
+
+export type SortSelection<TId extends string = string> = {
+ id: TId;
+ reversed?: boolean;
+};
+
+export function sortItems<TItem, TId extends string>(
+ items: TItem[],
+ selections: SortSelection<TId>[],
+ definitions: SortDefinition<TItem, TId>[]
+): TItem[] {
+ const byId = new Map<TId, SortDefinition<TItem, TId>>();
+ for (const definition of definitions) {
+ if (byId.has(definition.id)) {
+ throw new Error(
+ `Sort definitions must have unique IDs; received: ${definition.id}`
+ );
+ }
+ byId.set(definition.id, definition);
+ }
+ const comparators = selections.flatMap((selection) => {
+ const definition = byId.get(selection.id);
+ if (!definition) return [];
+ const direction = selection.reversed ? -1 : 1;
+ return [
+ (left: TItem, right: TItem) =>
+ direction * definition.compare(left, right),
+ ];
+ });
+
+ return items
+ .map((item, index) => ({ item, index }))
+ .sort((left, right) => {
+ for (const compare of comparators) {
+ const result = compare(left.item, right.item);
+ if (result !== 0) return result;
+ }
+ return left.index - right.index;
+ })
+ .map(({ item }) => item);
+}
+
+export type GroupSoupEntitiesOptions<TEntity extends SoupEntityIdentity> = {
+ getGroupId: (entity: TEntity) => string;
+ getGroupLabel: (
+ groupId: string,
+ firstEntity: TEntity,
+ entities: TEntity[]
+ ) => string;
+ compareGroups?: (
+ left: SoupGroup<TEntity>,
+ right: SoupGroup<TEntity>
+ ) => number;
+};
+
+export function groupSoupEntities<TEntity extends SoupEntityIdentity>(
+ entities: TEntity[],
+ options: GroupSoupEntitiesOptions<TEntity>
+): SoupGroup<TEntity>[] {
+ const grouped = new Map<string, TEntity[]>();
+ for (const entity of entities) {
+ const groupId = options.getGroupId(entity);
+ const group = grouped.get(groupId);
+ if (group) group.push(entity);
+ else grouped.set(groupId, [entity]);
+ }
+
+ const groups = [...grouped].map(([id, groupEntities]) => ({
+ id,
+ label: options.getGroupLabel(id, groupEntities[0], groupEntities),
+ entities: groupEntities,
+ count: groupEntities.length,
+ }));
+
+ if (!options.compareGroups) return groups;
+ return groups
+ .map((group, index) => ({ group, index }))
+ .sort(
+ (left, right) =>
+ options.compareGroups?.(left.group, right.group) ||
+ left.index - right.index
+ )
+ .map(({ group }) => group);
+}
diff --git a/apps/web/src/features/soup/collection/types.ts b/apps/web/src/features/soup/collection/types.ts
new file mode 100644
index 0000000000..0425e755df
--- /dev/null
+++ b/apps/web/src/features/soup/collection/types.ts
@@ -0,0 +1,55 @@
+import type { EntityData } from '@entity';
+
+export type SoupEntityIdentity = Pick<EntityData, 'id' | 'type'>;
+
+export type SoupEntityRow<TEntity extends SoupEntityIdentity = EntityData> = {
+ kind: 'entity';
+ /** Rendered occurrence identity; intentionally distinct from `entity.id`. */
+ id: string;
+ entity: TEntity;
+ groupId?: string;
+ occurrenceId?: string;
+};
+
+export type SoupGroupHeaderRow = {
+ kind: 'group-header';
+ id: string;
+ groupId: string;
+ label: string;
+ count?: number;
+};
+
+export type SoupSectionHeaderRow = {
+ kind: 'section-header';
+ id: string;
+ sectionId: string;
+ label: string;
+};
+
+export type SoupLoadMoreRow = {
+ kind: 'load-more';
+ id: string;
+ scopeId: string;
+ groupId?: string;
+ label?: string;
+ isLoading?: boolean;
+};
+
+export type SoupRow<TEntity extends SoupEntityIdentity = EntityData> =
+ | SoupEntityRow<TEntity>
+ | SoupGroupHeaderRow
+ | SoupSectionHeaderRow
+ | SoupLoadMoreRow;
+
+export type SoupGroup<TEntity extends SoupEntityIdentity = EntityData> = {
+ id: string;
+ label: string;
+ entities: TEntity[];
+ /** Total server count when it differs from the currently loaded entities. */
+ count?: number;
+ loadMore?: {
+ scopeId: string;
+ label?: string;
+ isLoading?: boolean;
+ };
+};
diff --git a/apps/web/src/features/soup/entity-notifications.ts b/apps/web/src/features/soup/entity-notifications.ts
new file mode 100644
index 0000000000..8bb996b88d
--- /dev/null
+++ b/apps/web/src/features/soup/entity-notifications.ts
@@ -0,0 +1,117 @@
+import type { EntityData } from '@entity/types/entity';
+import type { WithNotification } from '@entity/types/notification';
+import { toNotificationEntity } from '@entity/utils/notification';
+import type { NotificationSource } from '@notifications/notification-source';
+import {
+ getAllNotificationsFromGroup,
+ stackNotifications,
+} from '@notifications/notification-stacking';
+import {
+ compositeEntity,
+ type UnifiedNotification,
+} from '@notifications/types';
+import type { Accessor } from 'solid-js';
+import { match } from 'ts-pattern';
+
+function channelThreadNotificationIds(
+ notifications: UnifiedNotification[],
+ threadId?: string
+): Set<string> {
+ const ids = new Set<string>();
+
+ if (threadId !== undefined) {
+ for (const notification of notifications) {
+ const belongsToThread = match(notification.notification_metadata)
+ .with(
+ { tag: 'channel_message_send' },
+ (metadata) => metadata.content.messageId === threadId
+ )
+ .with(
+ { tag: 'channel_mention' },
+ (metadata) =>
+ (metadata.content.threadId ?? metadata.content.messageId) ===
+ threadId
+ )
+ .with(
+ { tag: 'channel_message_reply' },
+ (metadata) => metadata.content.threadId === threadId
+ )
+ .otherwise(() => false);
+ if (belongsToThread) ids.add(notification.id);
+ }
+ return ids;
+ }
+
+ for (const stack of stackNotifications(notifications)) {
+ if (
+ stack.type !== 'channel_message_reply' &&
+ stack.type !== 'channel_mention'
+ ) {
+ continue;
+ }
+ for (const notification of getAllNotificationsFromGroup(stack)) {
+ ids.add(notification.id);
+ }
+ }
+ return ids;
+}
+
+/**
+ * Splits notifications shared by channel and channel-thread entities into the
+ * stack rendered by each Inbox row.
+ */
+export function scopeChannelNotificationsForEntity(
+ entity: EntityData,
+ notifications: UnifiedNotification[]
+): UnifiedNotification[] {
+ if (entity.type === 'channel') {
+ const threadIds = channelThreadNotificationIds(notifications);
+ return notifications.filter(
+ (notification) => !threadIds.has(notification.id)
+ );
+ }
+ if (entity.type === 'channel_thread') {
+ const threadIds = channelThreadNotificationIds(
+ notifications,
+ entity.messageId
+ );
+ return notifications.filter((notification) =>
+ threadIds.has(notification.id)
+ );
+ }
+ return notifications;
+}
+
+type EntityWithRawNotifications = EntityData & {
+ notifications?: UnifiedNotification[] | Accessor<UnifiedNotification[]>;
+};
+
+/**
+ * Normalizes GraphQL notification arrays and the global notification source
+ * into the accessor shape expected by reusable list-entity components.
+ */
+export function withEntityNotifications(
+ entity: EntityWithRawNotifications,
+ source: NotificationSource,
+ options: { scopeChannelThreads?: boolean } = {}
+): WithNotification<EntityData> {
+ const attached = entity.notifications;
+ const read = (): UnifiedNotification[] => {
+ if (typeof attached === 'function') return attached();
+ if (Array.isArray(attached)) return attached;
+ return (
+ source.notificationsByEntity()[
+ compositeEntity(toNotificationEntity(entity))
+ ] ?? []
+ );
+ };
+ return {
+ ...entity,
+ notifications: () => {
+ const notifications = read();
+ return options.scopeChannelThreads
+ ? scopeChannelNotificationsForEntity(entity, notifications)
+ : notifications;
+ },
+ };
+}
diff --git a/apps/web/src/features/soup/filters/facets/clause.ts b/apps/web/src/features/soup/filters/facets/clause.ts
new file mode 100644
index 0000000000..1115ae1efb
--- /dev/null
+++ b/apps/web/src/features/soup/filters/facets/clause.ts
@@ -0,0 +1,137 @@
+import {
+ type DateRangeFilter,
+ FILTER_TARGETS,
+ type FilterFieldMeta,
+ type PropertyFilter,
+ type Target,
+} from './constants';
+
+// a clause is a boolean over ONE target's fields; facets combine them
+export type Leaf = { field: string; value: unknown };
+
+export type TargetExpr =
+ | Leaf
+ | { not: TargetExpr }
+ | { and: TargetExpr[] }
+ | { or: TargetExpr[] };
+
+export const eq = (field: string, value: unknown): Leaf => ({ field, value });
+export const not = (expr: TargetExpr): TargetExpr => ({ not: expr });
+export const and = (...exprs: TargetExpr[]): TargetExpr => ({ and: exprs });
+export const or = (...exprs: TargetExpr[]): TargetExpr => ({ or: exprs });
+
+export const clause = { eq, not, and, or };
+
+export type BackendAstNode =
+ | { '&': [BackendAstNode, BackendAstNode] }
+ | { '|': [BackendAstNode, BackendAstNode] }
+ | { '!': BackendAstNode }
+ | { l: unknown };
+
+export type BackendAstMap = Partial<Record<Target, BackendAstNode>>;
+
+export const isBackendAstNode = (
+ node: BackendAstNode | undefined
+): node is BackendAstNode => node !== undefined;
+
+export const AST = {
+ or(asts: BackendAstNode[]): BackendAstNode | undefined {
+ if (asts.length === 0) return undefined;
+ if (asts.length === 1) return asts[0];
+ return asts.reduceRight((acc, ast) => ({ '|': [ast, acc] }));
+ },
+ and(asts: BackendAstNode[]): BackendAstNode | undefined {
+ if (asts.length === 0) return undefined;
+ if (asts.length === 1) return asts[0];
+ return asts.reduceRight((acc, ast) => ({ '&': [ast, acc] }));
+ },
+ not(ast: BackendAstNode): BackendAstNode {
+ return { '!': ast };
+ },
+ literal(field: string, value?: unknown): BackendAstNode {
+ return value === undefined ? { l: field } : { l: { [field]: value } };
+ },
+};
+
+export const literal = AST.literal;
+
+export const combine = (
+ operator: '&' | '|',
+ values: BackendAstNode[]
+): BackendAstNode | undefined => {
+ const [first, ...rest] = values;
+ if (!first) return undefined;
+ return rest.reduce<BackendAstNode>(
+ (left, right) =>
+ operator === '&' ? { '&': [left, right] } : { '|': [left, right] },
+ first
+ );
+};
+
+const expandDateRange = (field: string, range: DateRangeFilter) => {
+ const asts: BackendAstNode[] = [];
+
+ if (range.gt) asts.push(AST.literal(field, { gt: range.gt }));
+ if (range.gte) asts.push(AST.literal(field, { gte: range.gte }));
+ if (range.lt) asts.push(AST.literal(field, { lt: range.lt }));
+ if (range.lte) asts.push(AST.literal(field, { lte: range.lte }));
+
+ return asts;
+};
+
+const propertyToAst = (property: PropertyFilter): BackendAstNode =>
+ property.type === 'select'
+ ? { l: { pd: property.propertyId, v: { so: property.value } } }
+ : { l: { pd: property.propertyId, v: { er: property.value } } };
+
+const fieldMeta = (target: Target, field: string): FilterFieldMeta => {
+ const targetFields = FILTER_TARGETS[target];
+ return targetFields[field as keyof typeof targetFields];
+};
+
+const compileLeaf = (
+ target: Target,
+ { field, value }: Leaf
+): BackendAstNode | undefined => {
+ if (field === 'properties') return propertyToAst(value as PropertyFilter);
+
+ const config = fieldMeta(target, field);
+
+ if (!config) return undefined;
+
+ if (config.compile === 'unit') {
+ return value === true ? AST.literal(config.backend) : undefined;
+ }
+
+ if (config.compile === 'dateRange') {
+ return AST.and(expandDateRange(config.backend, value as DateRangeFilter));
+ }
+
+ const format = config.formatValue ?? ((input: unknown) => input);
+
+ return AST.literal(config.backend, format(value));
+};
+
+export const compileExpr = (
+ target: Target,
+ expr: TargetExpr
+): BackendAstNode | undefined => {
+ if ('and' in expr) {
+ return AST.and(
+ expr.and.map((e) => compileExpr(target, e)).filter(isBackendAstNode)
+ );
+ }
+
+ if ('or' in expr) {
+ return AST.or(
+ expr.or.map((e) => compileExpr(target, e)).filter(isBackendAstNode)
+ );
+ }
+
+ if ('not' in expr) {
+ const child = compileExpr(target, expr.not);
+ return child ? AST.not(child) : undefined;
+ }
+
+ return compileLeaf(target, expr);
+};
diff --git a/apps/web/src/features/soup/filters/facets/compile.test.ts b/apps/web/src/features/soup/filters/facets/compile.test.ts
new file mode 100644
index 0000000000..40b9481588
--- /dev/null
+++ b/apps/web/src/features/soup/filters/facets/compile.test.ts
@@ -0,0 +1,152 @@
+import { describe, expect, it } from 'vitest';
+import {
+ clause,
+ combine,
+ compileFacets,
+ confine,
+ type Facet,
+ type FacetClause,
+ type FacetOption,
+ literal,
+ mergeAst,
+ NIL_UUID,
+} from '.';
+
+type Item = { status: string };
+type Context = { propertyId: string };
+type Option = FacetOption<Item, Context>;
+
+const selectClause = (propertyId: string, optionId: string): FacetClause => ({
+ propf: clause.eq('properties', {
+ propertyId,
+ type: 'select',
+ value: optionId,
+ }),
+});
+
+const facets: Facet<Item, Context, Option>[] = [
+ {
+ id: 'status',
+ mode: 'or',
+ options: [
+ { id: 'open', clause: selectClause('status-property', 'open-option') },
+ {
+ id: 'closed',
+ clause: selectClause('status-property', 'closed-option'),
+ },
+ ],
+ },
+ {
+ id: 'priority',
+ mode: 'or',
+ options: (optionId, context) => ({
+ id: optionId,
+ clause: selectClause(context.propertyId, optionId),
+ }),
+ },
+];
+
+const confinedFacet: Facet<Item, undefined> = {
+ id: 'type',
+ mode: 'or',
+ options: [
+ {
+ id: 'documents',
+ clause: confine({ df: clause.eq('subType', ['task']) }),
+ },
+ {
+ id: 'email',
+ clause: confine({ ef: clause.eq('emailSeen', false) }),
+ },
+ ],
+};
+
+const propertyLiteral = (propertyId: string, optionId: string) => ({
+ l: { pd: propertyId, v: { so: optionId } },
+});
+
+describe('facet compiler', () => {
+ it('combines options with the facet mode and facets with AND', () => {
+ expect(
+ compileFacets(
+ { status: ['open', 'closed'], priority: ['high'] },
+ facets,
+ { propertyId: 'priority-property' }
+ ).propf
+ ).toEqual({
+ '&': [
+ {
+ '|': [
+ propertyLiteral('status-property', 'closed-option'),
+ propertyLiteral('status-property', 'open-option'),
+ ],
+ },
+ propertyLiteral('priority-property', 'high'),
+ ],
+ });
+ });
+
+ it('leaves unknown facets and unresolved options inert', () => {
+ expect(
+ compileFacets({ unknown: ['value'], status: ['missing'] }, facets, {
+ propertyId: 'priority-property',
+ })
+ ).toEqual({});
+ });
+
+ it('leaves unresolved restricting options inert', () => {
+ expect(
+ compileFacets(
+ { type: ['missing'] },
+ [
+ {
+ id: 'type',
+ mode: 'or',
+ restrict: true,
+ options: [
+ {
+ id: 'documents',
+ clause: { df: clause.eq('documentId', ['document-id']) },
+ },
+ ],
+ },
+ ],
+ undefined
+ )
+ ).toEqual({});
+ });
+
+ it('keeps each target admitted by confined OR options', () => {
+ const result = compileFacets(
+ { type: ['documents', 'email'] },
+ [confinedFacet],
+ undefined
+ );
+
+ expect(result.df).toEqual({
+ '|': [{ l: { dst: ['task'] } }, { l: { id: NIL_UUID } }],
+ });
+ expect(result.ef).toEqual({
+ '|': [{ l: { ThreadId: NIL_UUID } }, { l: { NotificationSeen: false } }],
+ });
+ });
+
+ it('builds and combines transport-neutral AST nodes', () => {
+ expect(
+ combine('&', [literal('dst', 'task'), literal('o', 'user-id')])
+ ).toEqual({
+ '&': [{ l: { dst: 'task' } }, { l: { o: 'user-id' } }],
+ });
+ expect(combine('|', [])).toBeUndefined();
+ });
+
+ it('merges compiled maps without owning request transport', () => {
+ expect(
+ mergeAst({ df: { l: { dst: 'task' } } }, { df: { l: { o: 'user-id' } } })
+ ).toEqual({
+ df: {
+ '&': [{ l: { dst: 'task' } }, { l: { o: 'user-id' } }],
+ },
+ });
+ });
+});
diff --git a/apps/web/src/features/soup/filters/facets/compile.ts b/apps/web/src/features/soup/filters/facets/compile.ts
new file mode 100644
index 0000000000..02690d9b0f
--- /dev/null
+++ b/apps/web/src/features/soup/filters/facets/compile.ts
@@ -0,0 +1,189 @@
+import {
+ AST,
+ type BackendAstMap,
+ type BackendAstNode,
+ clause,
+ compileExpr,
+ eq,
+ isBackendAstNode,
+ type TargetExpr,
+} from './clause';
+import {
+ ENTITY_ID_BACKENDS,
+ ENTITY_ID_FIELDS,
+ ENTITY_TARGETS,
+ type EntityTarget,
+ NIL_ID,
+ TARGETS,
+ type Target,
+} from './constants';
+import type {
+ Facet,
+ FacetClause,
+ FacetClauseDefinition,
+ FacetOption,
+ FacetSelection,
+} from './types';
+
+export function resolveFacetOption<
+ TItem,
+ TContext,
+ TOption extends FacetOption<TItem, TContext>,
+>(
+ facet: Facet<TItem, TContext, TOption>,
+ optionId: string,
+ context: TContext
+): TOption | undefined {
+ if (typeof facet.options === 'function') {
+ return facet.options(optionId, context);
+ }
+ return facet.options.find((candidate) => candidate.id === optionId);
+}
+
+export function resolveFacetMode<TItem, TContext>(
+ facet: Facet<TItem, TContext>,
+ context: TContext
+) {
+ if (typeof facet.mode === 'function') return facet.mode(context);
+ return facet.mode;
+}
+
+const resolveClause = <TContext>(
+ definition: FacetClauseDefinition<TContext> | undefined,
+ context: TContext
+): FacetClause => {
+ if (definition === undefined) return {};
+ if (typeof definition === 'function') return definition(clause, context);
+ return definition;
+};
+
+// Excludes unused entity targets with a NIL ID filter.
+export const confine = (facetClause: FacetClause): FacetClause => {
+ const out: FacetClause = { ...facetClause };
+ for (const target of ENTITY_TARGETS) {
+ if (!(target in out)) {
+ out[target] = eq(ENTITY_ID_FIELDS[target], NIL_ID);
+ }
+ }
+ return out;
+};
+
+const isEntityTarget = (target: Target): target is EntityTarget =>
+ ENTITY_TARGETS.includes(target as EntityTarget);
+
+// per target: combine each facet's active options by mode, then AND the facets.
+// Keep `confine`d NIL leaves inside each facet's expression so OR semantics
+// preserve targets admitted by another active option.
+export const compileFacets = <
+ TItem,
+ TContext,
+ TOption extends FacetOption<TItem, TContext>,
+>(
+ selection: FacetSelection,
+ facets: Facet<TItem, TContext, TOption>[],
+ context: TContext
+): BackendAstMap => {
+ const byTarget = new Map<Target, BackendAstNode[]>();
+ let allowed: Set<EntityTarget> | undefined;
+
+ for (const facet of facets) {
+ const activeIds = [...new Set(selection[facet.id] ?? [])].sort();
+
+ if (!activeIds.length) continue;
+
+ const activeOptions = activeIds.flatMap((id) => {
+ const option = resolveFacetOption(facet, id, context);
+ return option ? [option] : [];
+ });
+ if (!activeOptions.length) continue;
+
+ const clauses = activeOptions.map((option) =>
+ resolveClause(option.clause, context)
+ );
+
+ const exprsByTarget = new Map<Target, TargetExpr[]>();
+ const facetAllowed = new Set<EntityTarget>();
+
+ for (const clause of clauses) {
+ for (const target of Object.keys(clause) as Target[]) {
+ if (facet.restrict && isEntityTarget(target)) facetAllowed.add(target);
+
+ const expr = clause[target];
+ if (!expr) continue;
+
+ const list = exprsByTarget.get(target) ?? [];
+ list.push(expr);
+ exprsByTarget.set(target, list);
+ }
+ }
+
+ if (facet.restrict) {
+ allowed =
+ allowed === undefined
+ ? facetAllowed
+ : new Set([...allowed].filter((target) => facetAllowed.has(target)));
+ }
+
+ const mode = resolveFacetMode(facet, context);
+ for (const [target, exprs] of exprsByTarget) {
+ const combined: TargetExpr =
+ mode === 'or' ? { or: exprs } : { and: exprs };
+ const ast = compileExpr(target, combined);
+
+ if (!ast) continue;
+
+ const list = byTarget.get(target) ?? [];
+ list.push(ast);
+ byTarget.set(target, list);
+ }
+ }
+
+ const result: BackendAstMap = {};
+
+ for (const target of TARGETS) {
+ const asts = byTarget.get(target);
+ if (!asts?.length) continue;
+
+ const combined = AST.and(asts);
+ if (isBackendAstNode(combined)) result[target] = combined;
+ }
+
+ if (allowed !== undefined) {
+ for (const target of ENTITY_TARGETS) {
+ if (allowed.has(target)) continue;
+ result[target] = {
+ l: { [ENTITY_ID_BACKENDS[target]]: NIL_ID },
+ };
+ }
+ }
+
+ return result;
+};
+
+export const compileClause = (optionClause: FacetClause): BackendAstMap => {
+ const out: BackendAstMap = {};
+
+ for (const target of Object.keys(optionClause) as Target[]) {
+ const expr = optionClause[target];
+ if (!expr) continue;
+
+ const ast = compileExpr(target, expr);
+ if (ast) out[target] = ast;
+ }
+
+ return out;
+};
+
+export const mergeAst = (a: BackendAstMap, b: BackendAstMap): BackendAstMap => {
+ const out: BackendAstMap = { ...a };
+
+ for (const target of Object.keys(b) as Target[]) {
+ const incoming = b[target];
+ if (!incoming) continue;
+
+ const existing = out[target];
+ out[target] = existing ? { '&': [existing, incoming] } : incoming;
+ }
+
+ return out;
+};
diff --git a/apps/web/src/features/soup/filters/facets/constants.ts b/apps/web/src/features/soup/filters/facets/constants.ts
new file mode 100644
index 0000000000..f8bb32bacc
--- /dev/null
+++ b/apps/web/src/features/soup/filters/facets/constants.ts
@@ -0,0 +1,352 @@
+export type CallStatus = 'ATTENDED' | 'MISSED' | 'UNATTENDED';
+
+export type DateRangeFilter = {
+ gt?: string;
+ gte?: string;
+ lt?: string;
+ lte?: string;
+};
+
+export type PropertyFilter = {
+ propertyId: string;
+ type: 'select' | 'entity';
+ value: string;
+};
+
+export type PropertyValue = { type: 'select' | 'entity'; value: string };
+
+type FilterFieldCompileKind = 'value' | 'unit' | 'dateRange';
+
+export type FilterFieldMeta = {
+ backend: string;
+ compile?: FilterFieldCompileKind;
+ formatValue?: (value: unknown) => unknown;
+ domain?: unknown[];
+};
+
+/*
+ * When adding a filter, update FILTER_TARGETS and FilterTargetsMeta. New
+ * targets also require TARGETS; entity targets additionally require
+ * ENTITY_TARGETS, ENTITY_ID_BACKENDS, and ENTITY_ID_FIELDS.
+ */
+export const FILTER_TARGETS = {
+ // df — documents / files / tasks
+ df: {
+ documentId: { backend: 'id' },
+ documentProjectId: { backend: 'pid' },
+ fileType: { backend: 'ft' },
+ fileAssoc: { backend: 'fa' },
+ subType: { backend: 'dst' },
+ documentOwnerId: { backend: 'o' },
+ documentSeen: { backend: 'ns', domain: [true, false] },
+ documentDone: { backend: 'nd', domain: [true, false] },
+ documentImportance: { backend: 'imp', domain: [true, false] },
+ isEmailAttachment: { backend: 'iea', domain: [true, false] },
+ documentCreatedAt: { backend: 'ca', compile: 'dateRange' },
+ documentUpdatedAt: { backend: 'ua', compile: 'dateRange' },
+ },
+
+ // calf — calendar events
+ calf: {
+ calendarEventId: { backend: 'id' },
+ calendarEventSeen: { backend: 'ns', domain: [true, false] },
+ calendarEventDone: { backend: 'nd', domain: [true, false] },
+ },
+
+ // ef — email
+ ef: {
+ threadId: { backend: 'ThreadId' },
+ emailLinkId: { backend: 'Owner' },
+ emailProjectId: { backend: 'ProjectId' },
+ emailSender: {
+ backend: 'Sender',
+ formatValue: (value) => ({ Partial: value }),
+ },
+ emailSeen: { backend: 'NotificationSeen', domain: [true, false] },
+ emailDone: { backend: 'NotificationDone', domain: [true, false] },
+ emailImportance: { backend: 'Importance', domain: [true, false] },
+ emailShared: { backend: 'Shared' },
+ emailCalendarOnly: { backend: 'CalendarOnly', domain: [true, false] },
+ emailUpdatedAt: { backend: 'ua', compile: 'dateRange' },
+ },
+
+ // chanf — channels
+ chanf: {
+ channelId: { backend: 'ChannelId' },
+ channelType: { backend: 'ChannelType' },
+ channelSenderId: { backend: 'Sender' },
+ channelSeen: { backend: 'NotificationSeen', domain: [true, false] },
+ channelDone: { backend: 'NotificationDone', domain: [true, false] },
+ channelImportance: { backend: 'Importance', domain: [true, false] },
+ channelIsParticipant: { backend: 'IsParticipant', domain: [true, false] },
+ },
+
+ // cthf — channel threads
+ cthf: {
+ channelThreadChannelId: { backend: 'ChannelId' },
+ channelThreadId: { backend: 'ThreadId' },
+ channelThreadRootSenderId: { backend: 'RootSender' },
+ channelThreadParticipantId: { backend: 'Participant' },
+ channelThreadSeen: { backend: 'NotificationSeen', domain: [true, false] },
+ channelThreadDone: { backend: 'NotificationDone', domain: [true, false] },
+ },
+
+ // cf — chats / agents
+ cf: {
+ chatId: { backend: 'cid' },
+ chatOwnerId: { backend: 'o' },
+ chatProjectId: { backend: 'pid' },
+ chatSeen: { backend: 'ns', domain: [true, false] },
+ chatDone: { backend: 'nd', domain: [true, false] },
+ chatCreatedAt: { backend: 'ca', compile: 'dateRange' },
+ chatUpdatedAt: { backend: 'ua', compile: 'dateRange' },
+ },
+
+ // pf — folders / projects
+ pf: {
+ folderId: { backend: 'pid' },
+ folderOwnerId: { backend: 'o' },
+ folderSeen: { backend: 'ns', domain: [true, false] },
+ folderDone: { backend: 'nd', domain: [true, false] },
+ folderCreatedAt: { backend: 'ca', compile: 'dateRange' },
+ folderUpdatedAt: { backend: 'ua', compile: 'dateRange' },
+ projectId: { backend: 'pid' },
+ },
+
+ // callf — calls
+ callf: {
+ callId: { backend: 'CallId' },
+ callChannelId: { backend: 'ChannelId' },
+ callSpeakerId: { backend: 'Speaker' },
+ callStatus: { backend: 'Status' },
+ callAttended: { backend: 'Attended', domain: [true, false] },
+ },
+
+ // fef — foreign entities
+ fef: {
+ foreignEntityRecordId: { backend: 'id' },
+ foreignEntitySource: { backend: 'fes' },
+ foreignEntitySeen: { backend: 'ns', domain: [true, false] },
+ foreignEntityDone: { backend: 'nd', domain: [true, false] },
+ foreignEntityIncludesMe: { backend: 'me', compile: 'unit' },
+ },
+
+ // ccf — crm companies
+ ccf: {
+ crmCompanyId: { backend: 'id' },
+ crmCompanyHidden: { backend: 'hidden', domain: [true, false] },
+ },
+
+ // remf — reminders
+ remf: {
+ reminderId: { backend: 'id' },
+ reminderCompleted: { backend: 'comp', domain: [true, false] },
+ reminderFired: { backend: 'fired', domain: [true, false] },
+ includeReminders: { backend: 'inc', compile: 'unit' },
+ },
+
+ // propf — properties
+ propf: {
+ properties: { backend: 'properties' },
+ },
+} satisfies Record<string, Record<string, FilterFieldMeta>>;
+
+type FilterTargetsMeta = {
+ // df — documents / files / tasks
+ df: {
+ documentId: string[];
+ documentProjectId: string[];
+ fileType: string[];
+ fileAssoc: string[];
+ subType: string[];
+ documentOwnerId: string[];
+ documentSeen: boolean;
+ documentDone: boolean;
+ documentImportance: boolean;
+ isEmailAttachment: boolean;
+ documentCreatedAt: DateRangeFilter;
+ documentUpdatedAt: DateRangeFilter;
+ };
+
+ // calf — calendar events
+ calf: {
+ calendarEventId: string[];
+ calendarEventSeen: boolean;
+ calendarEventDone: boolean;
+ };
+
+ // ef — email
+ ef: {
+ threadId: string[];
+ emailLinkId: string[];
+ emailProjectId: string[];
+ emailSender: string[];
+ emailSeen: boolean;
+ emailDone: boolean;
+ emailImportance: boolean;
+ emailShared: 'exclude' | 'include' | 'only';
+ emailCalendarOnly: boolean;
+ emailUpdatedAt: DateRangeFilter;
+ };
+
+ // chanf — channels
+ chanf: {
+ channelId: string[];
+ channelType: string[];
+ channelSenderId: string[];
+ channelSeen: boolean;
+ channelDone: boolean;
+ channelImportance: boolean;
+ channelIsParticipant: boolean;
+ };
+
+ // cthf — channel threads
+ cthf: {
+ channelThreadChannelId: string[];
+ channelThreadId: string[];
+ channelThreadRootSenderId: string[];
+ channelThreadParticipantId: string[];
+ channelThreadSeen: boolean;
+ channelThreadDone: boolean;
+ };
+
+ // cf — chats / agents
+ cf: {
+ chatId: string[];
+ chatOwnerId: string[];
+ chatProjectId: string[];
+ chatSeen: boolean;
+ chatDone: boolean;
+ chatCreatedAt: DateRangeFilter;
+ chatUpdatedAt: DateRangeFilter;
+ };
+
+ // pf — folders / projects
+ pf: {
+ folderId: string[];
+ folderOwnerId: string[];
+ folderSeen: boolean;
+ folderDone: boolean;
+ folderCreatedAt: DateRangeFilter;
+ folderUpdatedAt: DateRangeFilter;
+ projectId: string[];
+ };
+
+ // callf — calls
+ callf: {
+ callId: string[];
+ callChannelId: string[];
+ callSpeakerId: string[];
+ callStatus: CallStatus;
+ callAttended: boolean;
+ };
+
+ // fef — foreign entities
+ fef: {
+ foreignEntityRecordId: string[];
+ foreignEntitySource: string[];
+ foreignEntitySeen: boolean;
+ foreignEntityDone: boolean;
+ foreignEntityIncludesMe: boolean;
+ };
+
+ // ccf — crm companies
+ ccf: {
+ crmCompanyId: string[];
+ crmCompanyHidden: boolean;
+ };
+
+ // remf — reminders
+ remf: {
+ reminderId: string[];
+ reminderCompleted: boolean;
+ reminderFired: boolean;
+ includeReminders: boolean;
+ };
+
+ // propf — properties
+ propf: {
+ properties: PropertyFilter[];
+ };
+};
+
+type FilterTargetsConfig = typeof FILTER_TARGETS;
+
+export type FilterTargets = {
+ [T in keyof FilterTargetsConfig]: {
+ [K in keyof FilterTargetsConfig[T]]: T extends keyof FilterTargetsMeta
+ ? K extends keyof FilterTargetsMeta[T]
+ ? FilterTargetsMeta[T][K]
+ : never
+ : never;
+ };
+};
+
+export type Target = keyof FilterTargets;
+
+export const TARGETS: Target[] = [
+ 'df',
+ 'calf',
+ 'ef',
+ 'chanf',
+ 'cthf',
+ 'cf',
+ 'pf',
+ 'callf',
+ 'fef',
+ 'ccf',
+ 'remf',
+ 'propf',
+];
+
+export type FieldsForTarget<T extends Target> = keyof FilterTargets[T] & string;
+
+export type FieldKey = {
+ [T in Target]: FieldsForTarget<T>;
+}[Target];
+
+export type EntityTarget = Exclude<Target, 'propf'>;
+
+export const ENTITY_TARGETS: EntityTarget[] = [
+ 'df',
+ 'calf',
+ 'ef',
+ 'chanf',
+ 'cthf',
+ 'cf',
+ 'pf',
+ 'callf',
+ 'fef',
+ 'ccf',
+ 'remf',
+];
+
+export const ENTITY_ID_BACKENDS: Record<EntityTarget, string> = {
+ df: 'id',
+ calf: 'id',
+ ef: 'ThreadId',
+ chanf: 'ChannelId',
+ cthf: 'ChannelId',
+ cf: 'cid',
+ pf: 'pid',
+ callf: 'CallId',
+ fef: 'id',
+ ccf: 'id',
+ remf: 'id',
+};
+
+export const ENTITY_ID_FIELDS: Record<EntityTarget, string> = {
+ df: 'documentId',
+ calf: 'calendarEventId',
+ ef: 'threadId',
+ chanf: 'channelId',
+ cthf: 'channelThreadChannelId',
+ cf: 'chatId',
+ pf: 'folderId',
+ callf: 'callId',
+ fef: 'foreignEntityRecordId',
+ ccf: 'crmCompanyId',
+ remf: 'reminderId',
+};
+
+export const NIL_ID = '00000000-0000-0000-0000-000000000000';
diff --git a/apps/web/src/features/soup/filters/facets/evaluate.test.ts b/apps/web/src/features/soup/filters/facets/evaluate.test.ts
new file mode 100644
index 0000000000..7c78f9ab42
--- /dev/null
+++ b/apps/web/src/features/soup/filters/facets/evaluate.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+import { testFacets } from './evaluate';
+import type { Facet } from './types';
+
+type Item = { status: 'closed' | 'open' };
+const item = (status: Item['status']): Item => ({ status });
+
+const statusFacet = (mode: 'and' | 'or'): Facet<Item, undefined> => ({
+ id: 'status',
+ mode,
+ options: [
+ {
+ id: 'open',
+ predicate: (item) => item.status === 'open',
+ },
+ ],
+});
+
+describe('testFacets', () => {
+ it('keeps an item when an OR option is unresolved', () => {
+ expect(
+ testFacets(
+ { status: ['open', 'unresolved'] },
+ [statusFacet('or')],
+ item('closed'),
+ undefined
+ )
+ ).toBe(true);
+ });
+
+ it('still rejects an item when every OR option is known to miss', () => {
+ expect(
+ testFacets(
+ { status: ['open'] },
+ [statusFacet('or')],
+ item('closed'),
+ undefined
+ )
+ ).toBe(false);
+ });
+
+ it('does not let an unresolved AND option hide a known miss', () => {
+ expect(
+ testFacets(
+ { status: ['open', 'unresolved'] },
+ [statusFacet('and')],
+ item('closed'),
+ undefined
+ )
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/soup/filters/facets/evaluate.ts b/apps/web/src/features/soup/filters/facets/evaluate.ts
new file mode 100644
index 0000000000..95b49affdc
--- /dev/null
+++ b/apps/web/src/features/soup/filters/facets/evaluate.ts
@@ -0,0 +1,38 @@
+import { resolveFacetMode, resolveFacetOption } from './compile';
+import type { Facet, FacetOption, FacetSelection } from './types';
+
+/**
+ * Tests one item against active facets.
+ *
+ * Unresolved options and options without a client predicate remain included;
+ * the server may already have validated them. Facets combine with AND while
+ * each facet combines its selected options according to its mode.
+ */
+export function testFacets<
+ TItem,
+ TContext,
+ TOption extends FacetOption<TItem, TContext>,
+>(
+ selection: FacetSelection,
+ facets: Facet<TItem, TContext, TOption>[],
+ item: TItem,
+ context: TContext
+): boolean {
+ return facets.every((facet) => {
+ const active = selection[facet.id] ?? [];
+ if (active.length === 0) return true;
+
+ const results = active.map((optionId) =>
+ resolveFacetOption(facet, optionId, context)?.predicate?.(item, context)
+ );
+ const testable = results.filter(
+ (result): result is boolean => result !== undefined
+ );
+ if (testable.length === 0) return true;
+
+ if (resolveFacetMode(facet, context) === 'and') {
+ return testable.every(Boolean);
+ }
+ return testable.some(Boolean) || results.includes(undefined);
+ });
+}
diff --git a/apps/web/src/features/soup/filters/facets/index.ts b/apps/web/src/features/soup/filters/facets/index.ts
new file mode 100644
index 0000000000..d05504c3f5
--- /dev/null
+++ b/apps/web/src/features/soup/filters/facets/index.ts
@@ -0,0 +1,39 @@
+export type {
+ BackendAstMap,
+ BackendAstNode,
+ Leaf,
+ TargetExpr,
+} from './clause';
+export { and, clause, combine, eq, literal, not, or } from './clause';
+export {
+ compileClause,
+ compileFacets,
+ confine,
+ mergeAst,
+ resolveFacetMode,
+ resolveFacetOption,
+} from './compile';
+export type {
+ DateRangeFilter,
+ FieldKey,
+ PropertyFilter,
+ Target,
+} from './constants';
+export { NIL_ID as NIL_UUID } from './constants';
+export { testFacets } from './evaluate';
+export {
+ deserializeFacetSelection,
+ normalizeFacetSelection,
+ serializeFacetSelection,
+} from './selection';
+export type {
+ Facet,
+ FacetClause,
+ FacetClauseBuilder,
+ FacetClauseDefinition,
+ FacetMode,
+ FacetOption,
+ FacetOptionResolver,
+ FacetPredicate,
+ FacetSelection,
+} from './types';
diff --git a/apps/web/src/features/soup/filters/facets/selection.ts b/apps/web/src/features/soup/filters/facets/selection.ts
new file mode 100644
index 0000000000..36d1928504
--- /dev/null
+++ b/apps/web/src/features/soup/filters/facets/selection.ts
@@ -0,0 +1,33 @@
+import type { FacetSelection } from './types';
+
+/** Sorts, deduplicates, and removes malformed or empty facet selections. */
+export function normalizeFacetSelection(raw: unknown): FacetSelection {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
+
+ const entries: Array<[string, string[]]> = [];
+ for (const [facetId, optionIds] of Object.entries(raw).sort(
+ ([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)
+ )) {
+ if (!Array.isArray(optionIds)) continue;
+ const valid = [
+ ...new Set(
+ optionIds.filter((id): id is string => typeof id === 'string')
+ ),
+ ].sort();
+ if (valid.length > 0) entries.push([facetId, valid]);
+ }
+ return Object.fromEntries(entries);
+}
+
+/** Stable JSON serialization suitable for URL, entry-state, or preferences. */
+export const serializeFacetSelection = (selection: FacetSelection): string =>
+ JSON.stringify(normalizeFacetSelection(selection));
+
+export function deserializeFacetSelection(raw: unknown): FacetSelection {
+ if (typeof raw !== 'string') return normalizeFacetSelection(raw);
+ try {
+ return normalizeFacetSelection(JSON.parse(raw));
+ } catch {
+ return {};
+ }
+}
diff --git a/apps/web/src/features/soup/filters/facets/types.ts b/apps/web/src/features/soup/filters/facets/types.ts
new file mode 100644
index 0000000000..0285b9118a
--- /dev/null
+++ b/apps/web/src/features/soup/filters/facets/types.ts
@@ -0,0 +1,53 @@
+import type { TargetExpr } from './clause';
+import type { Target } from './constants';
+
+/** Canonical persisted facet intent. Unknown string IDs are preserved. */
+export type FacetSelection = Record<string, string[]>;
+
+export type FacetMode<TContext = unknown> =
+ | 'and'
+ | 'or'
+ | ((context: TContext) => 'and' | 'or');
+
+export type FacetPredicate<TItem, TContext> = (
+ item: TItem,
+ context: TContext
+) => boolean;
+
+export type FacetClause = Partial<Record<Target, TargetExpr>>;
+
+export type FacetClauseBuilder = {
+ eq: (field: string, value: unknown) => TargetExpr;
+ not: (expression: TargetExpr) => TargetExpr;
+ and: (...expressions: TargetExpr[]) => TargetExpr;
+ or: (...expressions: TargetExpr[]) => TargetExpr;
+};
+
+export type FacetClauseDefinition<TContext> =
+ | FacetClause
+ | ((builder: FacetClauseBuilder, context: TContext) => FacetClause);
+
+export type FacetOption<TItem = unknown, TContext = unknown> = {
+ id: string;
+ clause?: FacetClauseDefinition<TContext>;
+ predicate?: FacetPredicate<TItem, TContext>;
+};
+
+export type FacetOptionResolver<
+ TItem,
+ TContext,
+ TOption extends FacetOption<TItem, TContext>,
+> = (optionId: string, context: TContext) => TOption | undefined;
+
+export type Facet<
+ TItem = unknown,
+ TContext = unknown,
+ TOption extends FacetOption<TItem, TContext> = FacetOption<TItem, TContext>,
+> = {
+ id: string;
+ mode: FacetMode<TContext>;
+ multiple?: boolean;
+ /** Constrains unrepresented entity targets with NIL filters. */
+ restrict?: boolean;
+ options: TOption[] | FacetOptionResolver<TItem, TContext, TOption>;
+};
diff --git a/apps/web/src/features/soup/filters/index.ts b/apps/web/src/features/soup/filters/index.ts
new file mode 100644
index 0000000000..0269f083cb
--- /dev/null
+++ b/apps/web/src/features/soup/filters/index.ts
@@ -0,0 +1 @@
+export * from './facets';
diff --git a/apps/web/src/features/soup/index.ts b/apps/web/src/features/soup/index.ts
new file mode 100644
index 0000000000..e627136837
--- /dev/null
+++ b/apps/web/src/features/soup/index.ts
@@ -0,0 +1,2 @@
+export * from './collection';
+export * from './filters';
diff --git a/apps/web/src/lib/persistence/index.ts b/apps/web/src/lib/persistence/index.ts
new file mode 100644
index 0000000000..3175d27243
--- /dev/null
+++ b/apps/web/src/lib/persistence/index.ts
@@ -0,0 +1,6 @@
+export {
+ type MakePersistedStateOptions,
+ makePersistedState,
+ type PersistedState,
+ type PersistenceStorage,
+} from './make-persisted-state';
diff --git a/apps/web/src/lib/persistence/make-persisted-state.test.ts b/apps/web/src/lib/persistence/make-persisted-state.test.ts
new file mode 100644
index 0000000000..21e92dffd1
--- /dev/null
+++ b/apps/web/src/lib/persistence/make-persisted-state.test.ts
@@ -0,0 +1,151 @@
+import { createRoot, createSignal } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { describe, expect, it, vi } from 'vitest';
+import {
+ makePersistedState,
+ type PersistenceStorage,
+} from './make-persisted-state';
+
+function memoryStorage<T>(initial?: T) {
+ let value = initial;
+ const storage: PersistenceStorage<T> = {
+ restore: () => value,
+ write: (next) => {
+ value = next;
+ },
+ };
+ return { storage, value: () => value };
+}
+
+describe('makePersistedState', () => {
+ it('restores sequentially and writes through the wrapped setter', () => {
+ createRoot((dispose) => {
+ const preference = memoryStorage('preference');
+ const entry = memoryStorage('entry');
+ const signal = createSignal('default');
+ const [value, setValue, restored] = makePersistedState(signal, {
+ storages: [preference.storage, entry.storage],
+ });
+
+ expect(value).toBe(signal[0]);
+ expect(setValue).not.toBe(signal[1]);
+ expect(restored).toBe('entry');
+ expect(value()).toBe('entry');
+
+ setValue('updated');
+ expect(preference.value()).toBe('updated');
+ expect(entry.value()).toBe('updated');
+ dispose();
+ });
+ });
+
+ it('lets storages merge the fields they own in precedence order', () => {
+ createRoot((dispose) => {
+ type State = { search: string; sort: string; tab: string };
+ const preference: PersistenceStorage<State> = {
+ restore: (current) => ({ ...current, sort: 'saved-sort' }),
+ write: vi.fn(),
+ };
+ const entry: PersistenceStorage<State> = {
+ restore: (current) => ({
+ ...current,
+ search: 'entry-search',
+ tab: 'entry-tab',
+ }),
+ write: vi.fn(),
+ };
+
+ const [state] = makePersistedState(
+ createStore<State>({
+ search: 'default-search',
+ sort: 'default-sort',
+ tab: 'default-tab',
+ }),
+ { storages: [preference, entry] }
+ );
+
+ expect(state).toEqual({
+ search: 'entry-search',
+ sort: 'saved-sort',
+ tab: 'entry-tab',
+ });
+ dispose();
+ });
+ });
+
+ it('persists the canonical value after functional signal updates', () => {
+ createRoot((dispose) => {
+ const persisted = memoryStorage(1);
+ const [value, setValue] = makePersistedState(createSignal(0), {
+ storages: persisted.storage,
+ });
+
+ setValue((current) => current + 1);
+ expect(value()).toBe(2);
+ expect(persisted.value()).toBe(2);
+ dispose();
+ });
+ });
+
+ it('supports Solid stores and path setters', () => {
+ createRoot((dispose) => {
+ const persisted = memoryStorage({ count: 2, label: 'restored' });
+ const source = createStore({ count: 0, label: 'default' });
+ const [state, setState, restored] = makePersistedState(source, {
+ storages: persisted.storage,
+ });
+
+ expect(state).toBe(source[0]);
+ expect(restored).toEqual({ count: 2, label: 'restored' });
+
+ setState('count', 3);
+ expect(state.count).toBe(3);
+ expect(persisted.value()).toMatchObject({
+ count: 3,
+ label: 'restored',
+ });
+ dispose();
+ });
+ });
+
+ it('initializes and disposes storage-owned capture state', () => {
+ createRoot((dispose) => {
+ const initialize = vi.fn();
+ const storageDispose = vi.fn();
+ const storage: PersistenceStorage<string> = {
+ restore: () => undefined,
+ write: vi.fn(),
+ initialize,
+ dispose: storageDispose,
+ };
+
+ makePersistedState(createSignal('default'), { storages: storage });
+ expect(initialize).toHaveBeenCalledWith('default');
+
+ dispose();
+ expect(storageDispose).toHaveBeenCalledOnce();
+ });
+ });
+
+ it('continues when one storage throws', () => {
+ createRoot((dispose) => {
+ const healthy = memoryStorage('restored');
+ const broken: PersistenceStorage<string> = {
+ restore: () => {
+ throw new Error('unavailable');
+ },
+ write: () => {
+ throw new Error('unavailable');
+ },
+ };
+ const [value, setValue] = makePersistedState(createSignal('default'), {
+ storages: [broken, healthy.storage],
+ });
+
+ expect(value()).toBe('restored');
+ setValue('updated');
+ expect(healthy.value()).toBe('updated');
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/lib/persistence/make-persisted-state.ts b/apps/web/src/lib/persistence/make-persisted-state.ts
new file mode 100644
index 0000000000..6597525f64
--- /dev/null
+++ b/apps/web/src/lib/persistence/make-persisted-state.ts
@@ -0,0 +1,136 @@
+import { type Accessor, onCleanup, type Setter, untrack } from 'solid-js';
+import { reconcile, type SetStoreFunction, type Store } from 'solid-js/store';
+
+type AccessorState<TValue> = [get: Accessor<TValue>, set: Setter<TValue>];
+
+type StoreState<TValue extends object> = [
+ get: Store<TValue>,
+ set: SetStoreFunction<TValue>,
+];
+
+type PersistableState = AccessorState<any> | StoreState<any>;
+
+type PersistedStateValue<TState extends PersistableState> =
+ TState[0] extends Accessor<infer TValue>
+ ? TValue
+ : TState[0] extends Store<infer TValue>
+ ? TValue
+ : never;
+
+export type PersistedState<TState extends PersistableState> = [
+ get: TState[0],
+ set: TState[1],
+ restored: PersistedStateValue<TState> | undefined,
+];
+
+/**
+ * One persistence projection over a canonical state value.
+ *
+ * `restore` merges this storage's owned fields onto the state restored so
+ * far. `write` receives the final canonical state and selects what to retain.
+ */
+export type PersistenceStorage<T> = {
+ restore: (current: T) => T | undefined;
+ write: (value: T) => unknown;
+ initialize?: (value: T) => void;
+ dispose?: () => void;
+};
+
+export type MakePersistedStateOptions<T> = {
+ /**
+ * Storages restore in array order, so later storages have higher
+ * precedence. Writes are offered to every storage.
+ */
+ storages: PersistenceStorage<T> | PersistenceStorage<T>[];
+};
+
+/**
+ * Setter-driven persistence for Solid signals, stores, and custom
+ * accessor/setter pairs.
+ *
+ * Restoration is synchronous and ordered. All state mutations must use the
+ * returned setter to reach storages.
+ */
+export function makePersistedState<TValue>(
+ state: AccessorState<TValue>,
+ options: MakePersistedStateOptions<TValue>
+): PersistedState<AccessorState<TValue>>;
+export function makePersistedState<TValue extends object>(
+ state: StoreState<TValue>,
+ options: MakePersistedStateOptions<TValue>
+): PersistedState<StoreState<TValue>>;
+export function makePersistedState<TState extends PersistableState>(
+ state: TState,
+ options: MakePersistedStateOptions<PersistedStateValue<TState>>
+): PersistedState<TState> {
+ type TValue = PersistedStateValue<TState>;
+
+ const storages = (
+ Array.isArray(options.storages) ? options.storages : [options.storages]
+ ) as PersistenceStorage<TValue>[];
+
+ const isAccessorState = typeof state[0] === 'function';
+ const get = (isAccessorState ? state[0] : () => state[0]) as Accessor<TValue>;
+ const set = state[1] as (...args: any[]) => any;
+
+ let restored = untrack(get);
+ let didRestore = false;
+
+ for (const storage of storages) {
+ try {
+ const next = storage.restore(restored);
+ if (next === undefined) continue;
+ restored = next;
+ didRestore = true;
+ } catch {
+ // One unavailable storage must not prevent remaining restores.
+ }
+ }
+
+ if (didRestore) {
+ if (isAccessorState) {
+ // Wrapping avoids treating function-valued state as a setter callback.
+ set(() => restored);
+ } else {
+ set(reconcile(restored));
+ }
+ }
+
+ const current = untrack(get);
+ for (const storage of storages) {
+ try {
+ storage.initialize?.(current);
+ } catch {
+ // Initialization is best effort, matching restores and writes.
+ }
+ if (storage.dispose) onCleanup(storage.dispose);
+ }
+
+ const persistCurrent = () => {
+ const value = untrack(get);
+ for (const storage of storages) {
+ try {
+ storage.write(value);
+ } catch {
+ // In-memory state remains canonical when a storage is unavailable.
+ }
+ }
+ };
+
+ const persistedSetter = isAccessorState
+ ? (...args: any[]) => {
+ const result = set(...args);
+ persistCurrent();
+ return result;
+ }
+ : (...args: any[]) => {
+ set(...args);
+ persistCurrent();
+ };
+
+ return [
+ state[0],
+ persistedSetter as TState[1],
+ didRestore ? restored : undefined,
+ ];
+}
diff --git a/apps/web/src/features/next-soup/soup-view/create-infinite-queries.ts b/apps/web/src/lib/queries/create-infinite-queries.ts
similarity index 100%
rename from apps/web/src/features/next-soup/soup-view/create-infinite-queries.ts
rename to apps/web/src/lib/queries/create-infinite-queries.ts
diff --git a/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts b/apps/web/src/lib/queries/soup/grouped/create-grouped-soup-queries.ts
similarity index 81%
rename from apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
rename to apps/web/src/lib/queries/soup/grouped/create-grouped-soup-queries.ts
index 304bc99d9f..d11191d8bf 100644
--- a/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
+++ b/apps/web/src/lib/queries/soup/grouped/create-grouped-soup-queries.ts
@@ -1,8 +1,7 @@
-import { createGraphqlGroupedSoupQueries } from '@app/features/next-soup/soup-view/create-graphql-grouped-soup-queries';
-import { createInfiniteQueries } from '@app/features/next-soup/soup-view/create-infinite-queries';
import { throwOnErr } from '@core/util/result';
import type { EntityData } from '@entity';
import { useQueryClient } from '@queries/client';
+import { createInfiniteQueries } from '@queries/create-infinite-queries';
import { groupedCacheVersion } from '@queries/soup/cache';
import {
groupedSortMethod,
@@ -14,6 +13,7 @@ import type {
SoupApiItemFilter,
SoupAstBody,
SoupAstItemsGroupedPage,
+ SoupAstItemsQueryTransport,
SoupParams,
} from '@queries/soup/items';
import { soupKeys } from '@queries/soup/keys';
@@ -35,6 +35,7 @@ import {
on,
untrack,
} from 'solid-js';
+import { createGraphqlGroupedSoupQueries } from './graphql/create-graphql-grouped-soup-queries';
type InitialGroupPage = {
items: SoupAstItemsGroupedPage['items'];
@@ -50,13 +51,12 @@ export type GroupQueryData = {
entities: EntityData[];
};
-type CreateGroupedSoupQueriesArgs = {
+export type CreateGroupedSoupQueriesArgs = {
initialPage: Accessor<InitialGroupPage | undefined>;
groupByField: Accessor<GroupByField | undefined>;
soupParams: Accessor<SoupParams>;
soupBody: Accessor<SoupAstBody>;
- /** True only when the live GraphQL grouped parent query owns the view. */
- graphqlReactive: Accessor<boolean>;
+ transport: Accessor<SoupAstItemsQueryTransport>;
queryOptions: Accessor<{
enabled?: boolean;
meta?: {
@@ -68,6 +68,7 @@ type CreateGroupedSoupQueriesArgs = {
};
export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
+ const usesGraphql = () => args.transport() === 'graphql';
const instructionsIdQuery = useInstructionsMdIdQuery();
const queryClient = useQueryClient();
@@ -123,7 +124,7 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
const field = args.groupByField();
const initialGroupedPage = args.initialPage();
- if (args.graphqlReactive() || !field || !initialGroupedPage) {
+ if (usesGraphql() || !field || !initialGroupedPage) {
return [];
}
@@ -193,15 +194,14 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
groupByField: args.groupByField,
soupParams: args.soupParams,
soupBody: args.soupBody,
- enabled: () =>
- args.graphqlReactive() && args.queryOptions().enabled === true,
+ enabled: () => usesGraphql() && args.queryOptions().enabled === true,
itemFilter: () => args.queryOptions().meta?.itemFilter,
});
const [groupDataVersion, setGroupDataVersion] = createSignal(0);
const list = createMemo(() => {
- if (args.graphqlReactive()) return graphqlQueries.list();
+ if (usesGraphql()) return graphqlQueries.list();
return queries.list().map((query) => ({
...query,
@@ -228,33 +228,38 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
return next;
});
+ const resetRestToInitialPage = (initialGroupedPage = args.initialPage()) => {
+ const field = args.groupByField();
+ if (!field || !initialGroupedPage) return;
+
+ batch(() => {
+ for (const group of initialGroupedPage.groups) {
+ const initialPage = makeInitialPage(initialGroupedPage, group);
+ const queryKey = soupKeys.groupedGroup({
+ params: args.soupParams(),
+ body: args.soupBody(),
+ groupBy: field,
+ groupKey: group.key,
+ }).queryKey;
+
+ queryClient.setQueryData<InfiniteData<GroupQueryPage, string | null>>(
+ queryKey,
+ {
+ pages: [initialPage],
+ pageParams: [null],
+ }
+ );
+ }
+
+ setGroupDataVersion((version) => version + 1);
+ });
+ };
+
createEffect(
on(
() => args.initialPage(),
(initialGroupedPage) => {
- const field = args.groupByField();
- if (args.graphqlReactive() || !field || !initialGroupedPage) return;
-
- batch(() => {
- for (const group of initialGroupedPage.groups) {
- const initialPage = makeInitialPage(initialGroupedPage, group);
- const queryKey = soupKeys.groupedGroup({
- params: args.soupParams(),
- body: args.soupBody(),
- groupBy: field,
- groupKey: group.key,
- }).queryKey;
-
- queryClient.setQueryData<
- InfiniteData<GroupQueryPage, string | null>
- >(queryKey, {
- pages: [initialPage],
- pageParams: [null],
- });
- }
-
- setGroupDataVersion((version) => version + 1);
- });
+ if (!usesGraphql()) resetRestToInitialPage(initialGroupedPage);
},
{ defer: true }
)
@@ -265,7 +270,8 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
list,
map,
resetToInitialPage: () => {
- if (args.graphqlReactive()) graphqlQueries.resetToInitialPage();
+ resetRestToInitialPage();
+ graphqlQueries.resetToInitialPage();
},
};
}
diff --git a/apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.test.ts b/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.ts
similarity index 100%
rename from apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.test.ts
rename to apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.ts
diff --git a/apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.ts b/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.ts
similarity index 100%
rename from apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.ts
rename to apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.ts
diff --git a/apps/web/src/lib/signals/store-array-updaters.ts b/apps/web/src/lib/signals/store-array-updaters.ts
new file mode 100644
index 0000000000..752b1d39c8
--- /dev/null
+++ b/apps/web/src/lib/signals/store-array-updaters.ts
@@ -0,0 +1,59 @@
+export type ArrayStoreUpdater<T> = (values: T[] | undefined) => T[];
+
+export type Equality<T> = (left: T, right: T) => boolean;
+
+/**
+ * Creates an updater that appends a value only when it is not already present.
+ * Pass it directly to a Solid signal setter or store path setter.
+ *
+ * @example
+ * setState('items', addUnique(item));
+ */
+export function addUnique<T>(
+ value: T,
+ equals: Equality<T> = Object.is
+): ArrayStoreUpdater<T> {
+ return (values) => {
+ const current = values ?? [];
+ return current.some((item) => equals(item, value))
+ ? current
+ : [...current, value];
+ };
+}
+
+/**
+ * Creates an updater that removes matching values while preserving the current
+ * array reference when there is nothing to remove.
+ *
+ * @example
+ * setState('items', removeValue(item));
+ */
+export function removeValue<T>(
+ value: T,
+ equals: Equality<T> = Object.is
+): ArrayStoreUpdater<T> {
+ return (values) => {
+ const current = values ?? [];
+ const next = current.filter((item) => !equals(item, value));
+ return next.length === current.length ? current : next;
+ };
+}
+
+/**
+ * Creates an updater that removes a present value or appends a missing value.
+ * An optional equality function supports values that need identity by key.
+ *
+ * @example
+ * setState('items', toggleValue(item));
+ */
+export function toggleValue<T>(
+ value: T,
+ equals: Equality<T> = Object.is
+): ArrayStoreUpdater<T> {
+ return (values) => {
+ const current = values ?? [];
+ return current.some((item) => equals(item, value))
+ ? removeValue(value, equals)(current)
+ : [...current, value];
+ };
+}
diff --git a/apps/web/src/lib/utils/create-size-breakpoints.test.ts b/apps/web/src/lib/utils/create-size-breakpoints.test.ts
new file mode 100644
index 0000000000..0d736e165e
--- /dev/null
+++ b/apps/web/src/lib/utils/create-size-breakpoints.test.ts
@@ -0,0 +1,131 @@
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+import {
+ type BreakpointThresholds,
+ createSizeBreakpoints,
+ matchesBreakpoint,
+} from './create-size-breakpoints';
+
+describe('matchesBreakpoint', () => {
+ it('treats unmeasured size as false', () => {
+ expect(matchesBreakpoint(undefined, 720)).toBe(false);
+ expect(matchesBreakpoint(undefined, { min: 100 })).toBe(false);
+ });
+
+ it('treats a number as max-width', () => {
+ expect(matchesBreakpoint(720, 720)).toBe(true);
+ expect(matchesBreakpoint(721, 720)).toBe(false);
+ });
+
+ it('supports max-only, min-only, and inclusive ranges', () => {
+ expect(matchesBreakpoint(720, { max: 720 })).toBe(true);
+ expect(matchesBreakpoint(721, { max: 720 })).toBe(false);
+
+ expect(matchesBreakpoint(480, { min: 480 })).toBe(true);
+ expect(matchesBreakpoint(479, { min: 480 })).toBe(false);
+
+ expect(matchesBreakpoint(500, { min: 480, max: 720 })).toBe(true);
+ expect(matchesBreakpoint(480, { min: 480, max: 720 })).toBe(true);
+ expect(matchesBreakpoint(720, { min: 480, max: 720 })).toBe(true);
+ expect(matchesBreakpoint(479, { min: 480, max: 720 })).toBe(false);
+ expect(matchesBreakpoint(721, { min: 480, max: 720 })).toBe(false);
+ });
+});
+
+describe('createSizeBreakpoints', () => {
+ it('exposes keyed reactive accessors for number thresholds', () => {
+ const dispose = createRoot((rootDispose) => {
+ const [width, setWidth] = createSignal<number | undefined>();
+ const breakpoints = createSizeBreakpoints(width, {
+ dense: 480,
+ narrow: 720,
+ });
+
+ expect(breakpoints.narrow()).toBe(false);
+ expect(breakpoints.dense()).toBe(false);
+
+ setWidth(500);
+ expect(breakpoints.narrow()).toBe(true);
+ expect(breakpoints.dense()).toBe(false);
+
+ setWidth(400);
+ expect(breakpoints.narrow()).toBe(true);
+ expect(breakpoints.dense()).toBe(true);
+
+ setWidth(800);
+ expect(breakpoints.narrow()).toBe(false);
+ expect(breakpoints.dense()).toBe(false);
+
+ return rootDispose;
+ });
+ dispose();
+ });
+
+ it('supports min/max range objects', () => {
+ const dispose = createRoot((rootDispose) => {
+ const [width, setWidth] = createSignal<number | undefined>(600);
+ const breakpoints = createSizeBreakpoints(width, {
+ dense: { max: 480 },
+ mid: { min: 481, max: 720 },
+ wide: { min: 721 },
+ });
+
+ expect(breakpoints.dense()).toBe(false);
+ expect(breakpoints.mid()).toBe(true);
+ expect(breakpoints.wide()).toBe(false);
+
+ setWidth(400);
+ expect(breakpoints.dense()).toBe(true);
+ expect(breakpoints.mid()).toBe(false);
+ expect(breakpoints.wide()).toBe(false);
+
+ setWidth(900);
+ expect(breakpoints.dense()).toBe(false);
+ expect(breakpoints.mid()).toBe(false);
+ expect(breakpoints.wide()).toBe(true);
+
+ return rootDispose;
+ });
+ dispose();
+ });
+
+ it('tracks reactive threshold definitions', () => {
+ const dispose = createRoot((rootDispose) => {
+ const [width] = createSignal(600);
+ const [thresholds, setThresholds] = createSignal<BreakpointThresholds>({
+ narrow: 720,
+ });
+ const breakpoints = createSizeBreakpoints(width, thresholds);
+
+ expect(breakpoints.narrow()).toBe(true);
+
+ setThresholds({ narrow: 480 });
+ expect(breakpoints.narrow()).toBe(false);
+
+ setThresholds({ compact: 500 });
+ expect(breakpoints.narrow()).toBe(false);
+ expect(breakpoints.compact).toBeUndefined();
+
+ return rootDispose;
+ });
+ dispose();
+ });
+
+ it('rejects invalid thresholds', () => {
+ createRoot((dispose) => {
+ expect(() =>
+ createSizeBreakpoints(() => 100, { bad: Number.NaN })
+ ).toThrow(/bad/);
+ expect(() => createSizeBreakpoints(() => 100, { bad: -1 })).toThrow(
+ /bad/
+ );
+ expect(() => createSizeBreakpoints(() => 100, { bad: {} })).toThrow(
+ /min, max/
+ );
+ expect(() =>
+ createSizeBreakpoints(() => 100, { bad: { min: 800, max: 400 } })
+ ).toThrow(/min/);
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/lib/utils/create-size-breakpoints.ts b/apps/web/src/lib/utils/create-size-breakpoints.ts
new file mode 100644
index 0000000000..6cd521db87
--- /dev/null
+++ b/apps/web/src/lib/utils/create-size-breakpoints.ts
@@ -0,0 +1,107 @@
+import { type Accessor, createMemo } from 'solid-js';
+
+/**
+ * Inclusive size range. At least one bound is required.
+ * - `max` alone — size ≤ max (same as the number shorthand)
+ * - `min` alone — size ≥ min
+ * - both — min ≤ size ≤ max
+ */
+export type BreakpointRange = {
+ min?: number;
+ max?: number;
+};
+
+/**
+ * A breakpoint threshold: max-width shorthand, or an explicit min/max range.
+ * `720` is equivalent to `{ max: 720 }`.
+ */
+export type BreakpointThreshold = number | BreakpointRange;
+
+export type BreakpointThresholds = Record<string, BreakpointThreshold>;
+
+/**
+ * Reactive breakpoint accessors.
+ *
+ * Unmeasured size matches nothing, so first paint does not flash compact UI.
+ */
+export type Breakpoints<T extends BreakpointThresholds> = {
+ [K in keyof T]-?: Accessor<boolean>;
+};
+
+export type BreakpointAccessors = Record<string, Accessor<boolean> | undefined>;
+
+export function resolveBreakpointRange(threshold: BreakpointThreshold): {
+ min?: number;
+ max?: number;
+} {
+ if (typeof threshold === 'number') return { max: threshold };
+ return threshold;
+}
+
+export function matchesBreakpoint(
+ size: number | undefined,
+ threshold: BreakpointThreshold
+): boolean {
+ if (size === undefined) return false;
+ const range = resolveBreakpointRange(threshold);
+ if (range.min !== undefined && size < range.min) return false;
+ if (range.max !== undefined && size > range.max) return false;
+ return range.min !== undefined || range.max !== undefined;
+}
+
+function assertBound(label: string, key: string, value: number): void {
+ if (!Number.isFinite(value) || value < 0) {
+ throw new Error(
+ `Breakpoint "${key}" ${label} must be a non-negative finite number`
+ );
+ }
+}
+
+export function assertBreakpointThreshold(
+ key: string,
+ threshold: BreakpointThreshold
+): void {
+ if (typeof threshold === 'number') {
+ assertBound('threshold', key, threshold);
+ return;
+ }
+
+ const { min, max } = threshold;
+ if (min === undefined && max === undefined) {
+ throw new Error(`Breakpoint "${key}" must define min, max, or both`);
+ }
+ if (min !== undefined) assertBound('min', key, min);
+ if (max !== undefined) assertBound('max', key, max);
+ if (min !== undefined && max !== undefined && min > max) {
+ throw new Error(`Breakpoint "${key}" min (${min}) must be ≤ max (${max})`);
+ }
+}
+
+/**
+ * Creates keyed reactive breakpoints for an arbitrary size accessor.
+ *
+ * Unlike media-query breakpoints, these match the supplied size rather than
+ * the browser viewport. Threshold values may change reactively; keys are fixed
+ * from the initial threshold record.
+ */
+export function createSizeBreakpoints<const T extends BreakpointThresholds>(
+ size: Accessor<number | undefined>,
+ thresholds: T | Accessor<T>
+): Breakpoints<T> {
+ const getThresholds: Accessor<T> =
+ typeof thresholds === 'function' ? thresholds : () => thresholds;
+ const result = {} as Breakpoints<T>;
+ const initialThresholds = getThresholds();
+
+ for (const key of Object.keys(initialThresholds) as Array<keyof T & string>) {
+ assertBreakpointThreshold(key, initialThresholds[key]);
+ result[key] = createMemo(() => {
+ const currentThreshold = getThresholds()[key];
+ if (currentThreshold === undefined) return false;
+ assertBreakpointThreshold(key, currentThreshold);
+ return matchesBreakpoint(size(), currentThreshold);
+ });
+ }
+
+ return result;
+}
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
index b4ed10a00e..6068f979d4 100644
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -180,6 +180,8 @@ export default defineConfig({
'src/lib/analytics/**/*.{test,spec}.{ts,tsx}',
'src/lib/constants/**/*.{test,spec}.{ts,tsx}',
'src/lib/fullcalendar-solid/**/*.{test,spec}.{ts,tsx}',
+ 'src/lib/persistence/**/*.{test,spec}.{ts,tsx}',
+ 'src/lib/utils/**/*.{test,spec}.{ts,tsx}',
'src/routes/**/*.{test,spec}.{ts,tsx}',
],
name: 'app',