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.

refactor: view and soup primitives (#6076)

dev-rbfea437bdfc1f
diff --git a/apps/web/src/components/app/PreviewPanel.tsx b/apps/web/src/components/app/PreviewPanel.tsx
index c63ed01ce7..81b75401e2 100644
--- a/apps/web/src/components/app/PreviewPanel.tsx
+++ b/apps/web/src/components/app/PreviewPanel.tsx
@@ -1,11 +1,17 @@
import {
+ calendarBlockParamsForEntity,
getChannelEntityTarget,
+ navigateCalendarEntityToTarget,
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 type {
+ BlockAliasContext,
+ BlockComponentProps,
+ 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';
@@ -52,13 +58,13 @@ type PreviewBlockTarget = {
blockType: BlockName;
blockId: string;
aliasContext: BlockAliasContext | undefined;
+ params?: BlockComponentProps[BlockName];
};
function PreviewPanelContent(
props: PreviewPanelProps & { selectedEntity: EntityData }
) {
const scopedLayoutRefs: SplitPanelContextType['layoutRefs'] = {};
- const selectedEntityId = createMemo(() => props.selectedEntity.id);
const [interactedWith, setInteractedWith] = createSignal(false);
const blockInstance = createMemo(() => {
@@ -89,11 +95,21 @@ function PreviewPanelContent(
}))
.with(
{ type: P.union('channel_message', 'channel_thread') },
- (message) => ({
- blockType: 'channel',
- blockId: message.channelId,
- aliasContext: undefined,
- })
+ (message) => {
+ const channelTarget = untrack(() => getChannelEntityTarget(message));
+ return {
+ blockType: 'channel',
+ blockId: message.channelId,
+ aliasContext: undefined,
+ params:
+ channelTarget?.kind === 'message'
+ ? getChannelParams(
+ channelTarget.messageId,
+ channelTarget.threadId
+ )
+ : undefined,
+ };
+ }
)
.with({ type: 'foreign' }, (foreignEntity) => ({
blockType:
@@ -113,10 +129,11 @@ function PreviewPanelContent(
blockId: contact.id,
aliasContext: undefined,
}))
- .with({ type: 'calendar_event' }, () => ({
+ .with({ type: 'calendar_event' }, (calendarEvent) => ({
blockType: 'calendar',
blockId: CALENDAR_BLOCK_ID,
aliasContext: undefined,
+ params: untrack(() => calendarBlockParamsForEntity(calendarEvent)),
}))
.with({ type: 'reminder' }, (reminder) => {
const reminderTarget = reminderSplitTarget(reminder);
@@ -132,32 +149,25 @@ function PreviewPanelContent(
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,
+ params: target.params,
}
);
});
createRenderEffect(
- on(selectedEntityId, () => {
- setInteractedWith(false);
- void navigateChannelEntityToTarget(
- props.selectedEntity,
- props.orchestrator
- );
- })
+ on(
+ () => props.selectedEntity,
+ (entity) => {
+ setInteractedWith(false);
+ void navigateChannelEntityToTarget(entity, props.orchestrator);
+ void navigateCalendarEntityToTarget(entity, props.orchestrator);
+ }
+ )
);
return (
diff --git a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx
index 30f7bc4dde..642713457e 100644
--- a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx
+++ b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx
@@ -134,6 +134,14 @@ function PopoverSplitModal(props: {
setTitleFileMenuTrigger,
titleFileMenuActions,
setTitleFileMenuActions,
+ list: () => undefined,
+ setList: (factory) => {
+ if (import.meta.env.DEV) {
+ console.warn('Popover splits do not register lists');
+ }
+
+ return factory();
+ },
headerCollapser: { register: () => () => {} },
toolbarCollapser: { register: () => () => {} },
};
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 24d82109d0..e99cc6b77a 100644
--- a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
@@ -2,6 +2,7 @@ import { isListViewID, LIST_VIEW_ID } from '@app/constants/list-views';
import { createSoupState } from '@app/features/next-soup/create-soup-state';
import { SoupContextProvider } from '@app/features/next-soup/soup-context';
import { SoupViewContextProvider } from '@app/features/next-soup/soup-view/soup-view-context';
+import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';
import { globalSplitManager } from '@app/signal/splitLayout';
import { MobileTopEdgeFade } from '@components/app/mobile/MobileEdgeFade';
import { SplitPanelControllerProvider } from '@components/app/split-panel';
@@ -36,6 +37,8 @@ import { useSplitLayout } from '../layout';
import type { SplitHandle, SplitState } from '../layoutManager';
import { shouldShowSplitCloseButton } from '../layoutUtils';
import { registerSplitHotkeys } from '../registerSplitHotkeys';
+import { useSplitList } from '../useSplitList';
+import { useSplitListNavigationHotkeys } from '../useSplitListNavigationHotkeys';
import { createPriorityCollapseController } from './PriorityCollapseOverflowSensor';
import { SplitDrawerGroup } from './SplitDrawerContext';
import { SplitHeader } from './SplitHeader';
@@ -76,6 +79,10 @@ export function SplitPanel(props: SplitPanelProps) {
const toolbarCollapseController = createPriorityCollapseController();
const splitLayoutHelpers = useSplitLayout();
+ const isNotUnifiedList = () => {
+ const content = props.handle.content();
+ return content.type !== 'component' || !isListViewID(content.id);
+ };
registerSplitHotkeys({
// Leaving a piece of content should return you to the list you reached it
@@ -91,10 +98,7 @@ export function SplitPanel(props: SplitPanelProps) {
referredFrom: 'hotkey',
});
},
- isNotUnifiedList: () => {
- const content = props.handle.content();
- return !isListViewID(content.id);
- },
+ isNotUnifiedList,
isViewerSplit: () => props.handle.isViewerSplit(),
getSplitCount: () => splitLayoutHelpers.getSplitCount(),
toggleSpotlight: () => props.handle.toggleSpotlight(),
@@ -108,6 +112,20 @@ export function SplitPanel(props: SplitPanelProps) {
splitHotkeyScope,
});
+ const splitList = useSplitList();
+
+ useSplitListNavigationHotkeys({
+ splitHotkeyScope,
+ list: splitList.list,
+ handle: props.handle,
+ openEntityInSplit: (entity, options) => {
+ void openEntityInSplitFromUnifiedList(entity, {
+ splitHandle: props.handle,
+ ...options,
+ });
+ },
+ });
+
const nextSoup = createSoupState({
initialPredicates: { and: ['explicit-noise'] },
});
@@ -288,6 +306,8 @@ export function SplitPanel(props: SplitPanelProps) {
setTitleFileMenuTrigger,
titleFileMenuActions,
setTitleFileMenuActions,
+ list: splitList.list,
+ setList: splitList.setList,
panelSize,
panelRef,
}}
diff --git a/apps/web/src/components/app/split-layout/context.ts b/apps/web/src/components/app/split-layout/context.ts
index b4c52e09f8..9632455b2e 100644
--- a/apps/web/src/components/app/split-layout/context.ts
+++ b/apps/web/src/components/app/split-layout/context.ts
@@ -1,4 +1,8 @@
+import type { ListController, ListDataSource } from '@app/components/list';
+import type { ListView } from '@app/constants/list-views';
+import type { SoupRow } from '@app/features/soup';
import type { HotkeyToken } from '@core/hotkey/tokens';
+import type { EntityData } from '@entity';
import type { NullableSize } from '@solid-primitives/resize-observer';
import {
type Accessor,
@@ -61,6 +65,37 @@ export type SplitFileMenuActionSection = {
actions: SplitFileMenuAction[];
};
+export type SplitListRow = SoupRow<EntityData>;
+
+export type SplitListActivationMetadata = {
+ event?: MouseEvent;
+ newSplit?: boolean;
+};
+
+export type SplitListController = ListController<
+ SplitListRow,
+ SplitListActivationMetadata
+>;
+
+export type SplitListRegistration<
+ TDataSource extends
+ ListDataSource<SplitListRow> = ListDataSource<SplitListRow>,
+> = {
+ viewId: ListView;
+ dataSource: TDataSource;
+ controller: SplitListController;
+};
+
+export type SetSplitList = <TDataSource extends ListDataSource<SplitListRow>>(
+ factory: () => SplitListRegistration<TDataSource>
+) => SplitListRegistration<TDataSource>;
+
+export type SplitListBinding = {
+ viewId: ListView | undefined;
+ dataSource: ListDataSource<SplitListRow>;
+ controller: SplitListController;
+};
+
export function getSplitFileMenuActionSections(
groups: SplitFileMenuActionGroups
): SplitFileMenuActionSection[] {
@@ -98,6 +133,8 @@ export type SplitPanelContextType = {
setTitleFileMenuTrigger: Setter<(() => void) | undefined>;
titleFileMenuActions: Accessor<SplitFileMenuActionGroups | undefined>;
setTitleFileMenuActions: Setter<SplitFileMenuActionGroups | undefined>;
+ list: Accessor<SplitListBinding | undefined>;
+ setList: SetSplitList;
headerCollapser: PriorityCollapser;
toolbarCollapser: PriorityCollapser;
};
diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.ts
index 3ab9fb86d9..6f9d86f89f 100644
--- a/apps/web/src/components/app/split-layout/layoutManager.ts
+++ b/apps/web/src/components/app/split-layout/layoutManager.ts
@@ -1263,14 +1263,14 @@ export function createSplitLayout(
}
}
},
- meta: () =>
- currentSplit.mount.kind === 'component'
- ? currentSplit.mount.meta
- : undefined,
- updateMeta:
- currentSplit.mount.kind === 'component'
- ? currentSplit.mount.updateMeta
- : undefined,
+ meta: () => {
+ const mount = findSplitById(currentSplit.id)?.mount;
+ return mount?.kind === 'component' ? mount.meta : undefined;
+ },
+ get updateMeta() {
+ const mount = findSplitById(currentSplit.id)?.mount;
+ return mount?.kind === 'component' ? mount.updateMeta : undefined;
+ },
referredFrom: () => s()?.referredFrom ?? null,
lastNavigationCause: () => s()?.lastNavigationCause ?? 'fresh',
registerEntryStateCaptor: (key: string, getter: () => unknown) => {
diff --git a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts b/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts
index b55c605019..c2c11e8331 100644
--- a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts
+++ b/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts
@@ -355,6 +355,36 @@ describe('layoutManager', () => {
});
});
+ describe('component metadata', () => {
+ it('updates the current mount through a retained split handle', () => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'component', id: 'inbox' },
+ ]);
+ const handle = manager.getSplit(manager.splits()[0].id)!;
+ const inboxMeta = handle.meta()!;
+
+ handle.updateMeta?.({ splitPanelLayout: 'legacy' });
+ handle.replace({ next: { type: 'component', id: 'tasks' } });
+
+ const tasksMeta = handle.meta()!;
+ expect(tasksMeta).not.toBe(inboxMeta);
+
+ handle.updateMeta?.({ splitPanelLayout: 'composable' });
+
+ expect(tasksMeta.splitPanelLayout).toBe('composable');
+ expect(inboxMeta.splitPanelLayout).toBe('legacy');
+
+ handle.replace({ next: { type: 'md', id: 'document-1' } });
+
+ expect(handle.meta()).toBeUndefined();
+ expect(handle.updateMeta).toBeUndefined();
+
+ dispose();
+ });
+ });
+ });
+
describe('navigation params', () => {
const channelWithTarget = {
type: 'channel',
diff --git a/apps/web/src/components/app/split-layout/useSplitList.ts b/apps/web/src/components/app/split-layout/useSplitList.ts
new file mode 100644
index 0000000000..4466775839
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/useSplitList.ts
@@ -0,0 +1,81 @@
+import {
+ createListController,
+ createStaticListDataSource,
+ type ListDataSource,
+} from '@app/components/list';
+import {
+ type Accessor,
+ createRoot,
+ createSignal,
+ getOwner,
+ onCleanup,
+} from 'solid-js';
+import type {
+ SetSplitList,
+ SplitListActivationMetadata,
+ SplitListBinding,
+ SplitListRegistration,
+ SplitListRow,
+} from './context';
+
+export type UseSplitListResult = {
+ list: Accessor<SplitListBinding>;
+ setList: SetSplitList;
+};
+
+export function useSplitList(): UseSplitListResult {
+ const splitOwner = getOwner();
+ if (!splitOwner) {
+ throw new Error('useSplitList requires a Solid owner');
+ }
+
+ const emptyDataSource = createStaticListDataSource<SplitListRow>(() => []);
+ const emptyController = createListController<
+ SplitListRow,
+ SplitListActivationMetadata
+ >({
+ items: emptyDataSource.items,
+ getKey: (row) => row.id,
+ });
+ const [list, setListBinding] = createSignal<SplitListBinding>({
+ viewId: undefined,
+ dataSource: emptyDataSource,
+ controller: emptyController,
+ });
+
+ let disposeListRoot: (() => void) | undefined;
+
+ function setList<TDataSource extends ListDataSource<SplitListRow>>(
+ factory: () => SplitListRegistration<TDataSource>
+ ): SplitListRegistration<TDataSource> {
+ let disposeNextRoot: (() => void) | undefined;
+ let nextRegistration: SplitListRegistration<TDataSource>;
+
+ try {
+ nextRegistration = createRoot((dispose) => {
+ disposeNextRoot = dispose;
+ return factory();
+ }, splitOwner);
+ } catch (error) {
+ disposeNextRoot?.();
+ throw error;
+ }
+
+ if (!disposeNextRoot) {
+ throw new Error('Split list root did not provide a disposer');
+ }
+
+ const disposePreviousRoot = disposeListRoot;
+
+ disposeListRoot = disposeNextRoot;
+ setListBinding(nextRegistration);
+
+ disposePreviousRoot?.();
+
+ return nextRegistration;
+ }
+
+ onCleanup(() => disposeListRoot?.());
+
+ return { list, setList };
+}
diff --git a/apps/web/src/components/app/split-layout/useSplitListNavigationHotkeys.ts b/apps/web/src/components/app/split-layout/useSplitListNavigationHotkeys.ts
new file mode 100644
index 0000000000..442bd8f46e
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/useSplitListNavigationHotkeys.ts
@@ -0,0 +1,90 @@
+import { isListViewID, type ListView } from '@app/constants/list-views';
+import { registerHotkey } from '@core/hotkey/hotkeys';
+import type { EntityData } from '@entity';
+import type { SplitListBinding } from './context';
+import type { SplitHandle } from './layoutManager';
+
+const LOAD_MORE_DISTANCE_FROM_END = 3;
+
+export type SplitListOpenEntityOptions = {
+ mergeHistory: true;
+ referredFrom: ListView;
+};
+
+export type UseSplitListNavigationHotkeysOptions = {
+ splitHotkeyScope: string;
+ list: () => SplitListBinding | undefined;
+ handle: SplitHandle;
+ openEntityInSplit: (
+ entity: EntityData,
+ options: SplitListOpenEntityOptions
+ ) => void;
+};
+
+type ConfiguredSplitListBinding = SplitListBinding & {
+ viewId: ListView;
+};
+
+export function useSplitListNavigationHotkeys(
+ options: UseSplitListNavigationHotkeysOptions
+) {
+ const canNavigate = (
+ list: SplitListBinding | undefined
+ ): list is ConfiguredSplitListBinding => {
+ const content = options.handle.content();
+ return (
+ list?.viewId !== undefined &&
+ (content.type !== 'component' || !isListViewID(content.id)) &&
+ options.handle.referredFrom() === list.viewId
+ );
+ };
+
+ const step = (direction: -1 | 1) => {
+ const list = options.list();
+ if (!canNavigate(list)) return false;
+
+ const rows = list.dataSource.items();
+ const next = list.controller.navigate.by(direction, {
+ isNavigable: (row) => row.kind === 'entity',
+ });
+
+ if (next?.item.kind === 'entity') {
+ list.controller.selection.setAnchor(next.key);
+ options.openEntityInSplit(next.item.entity, {
+ mergeHistory: true,
+ referredFrom: list.viewId,
+ });
+ }
+
+ if (
+ direction === 1 &&
+ (!next || rows.length - next.index - 1 <= LOAD_MORE_DISTANCE_FROM_END) &&
+ list.dataSource.hasMore() &&
+ !list.dataSource.isLoadingMore()
+ ) {
+ void list.dataSource.loadMore();
+ }
+
+ return true;
+ };
+
+ registerHotkey({
+ scopeId: options.splitHotkeyScope,
+ hotkey: 'j',
+ description: 'Move down',
+ condition: () => canNavigate(options.list()),
+ keyDownHandler: () => step(1),
+ registrationType: 'add',
+ hide: true,
+ });
+
+ registerHotkey({
+ scopeId: options.splitHotkeyScope,
+ hotkey: 'k',
+ description: 'Move up',
+ condition: () => canNavigate(options.list()),
+ keyDownHandler: () => step(-1),
+ registrationType: 'add',
+ hide: true,
+ });
+}
diff --git a/apps/web/src/components/list/create-list-controller.test.ts b/apps/web/src/components/list/create-list-controller.test.ts
index a773316067..fa5350e4ac 100644
--- a/apps/web/src/components/list/create-list-controller.test.ts
+++ b/apps/web/src/components/list/create-list-controller.test.ts
@@ -100,6 +100,33 @@ describe('createListController', () => {
});
});
+ it('owns range anchors and resets the range session with selection', () => {
+ withRoot(() => {
+ const values = [item('a'), item('b'), item('c')];
+ const list = createListController({
+ items: () => values,
+ getKey: (value: Item) => value.id,
+ });
+
+ list.selection.set('a', true);
+ expect(list.selection.anchor()).toBe('a');
+
+ list.selection.set('c', true, { range: true });
+ expect([...list.selection.keys()]).toEqual(['a', 'b', 'c']);
+
+ list.selection.set('b', true, { range: true });
+ expect([...list.selection.keys()]).toEqual(['a', 'b']);
+
+ list.selection.clear();
+ expect(list.selection.count()).toBe(0);
+ expect(list.selection.anchor()).toBeUndefined();
+
+ list.selection.set('c', true);
+ list.selection.set('b', true, { range: true });
+ expect([...list.selection.keys()]).toEqual(['c', 'b']);
+ });
+ });
+
it('selects logical items independently from rendered occurrences', () => {
withRoot(() => {
const [items, setItems] = createSignal<readonly Item[]>([
diff --git a/apps/web/src/components/list/create-list-controller.ts b/apps/web/src/components/list/create-list-controller.ts
index 273ec88410..f9e1b3d6f1 100644
--- a/apps/web/src/components/list/create-list-controller.ts
+++ b/apps/web/src/components/list/create-list-controller.ts
@@ -24,6 +24,15 @@ export type CreateListSelectionOptions<TItem> = {
getKey: (item: TItem, index: number) => ListKey;
};
+export type ListSelectionSetOptions = {
+ range?: boolean;
+};
+
+type ListSelectionRangeSession = {
+ baseline: ReadonlySet<ListKey>;
+ selected: boolean;
+};
+
export type CreateListControllerOptions<TItem, TMetadata = unknown> = {
items: () => readonly TItem[];
/** Unique rendered occurrence identity used by focus and activation. */
@@ -331,6 +340,10 @@ export function createListController<TItem, TMetadata = unknown>(
initialKeys: options.initialSelectedKeys,
onChange: options.onSelectionChange,
});
+ const [selectionAnchor, setSelectionAnchor] = createSignal<
+ ListKey | undefined
+ >();
+ let selectionRangeSession: ListSelectionRangeSession | undefined;
const effectiveSelectionKeys = createMemo<ReadonlySet<ListKey>>(
() =>
@@ -386,6 +399,62 @@ export function createListController<TItem, TMetadata = unknown>(
keySelection.replace(next);
};
+ const setSelectionRangeAnchor = (key: ListKey | undefined) => {
+ setSelectionAnchor(key);
+ selectionRangeSession = undefined;
+ };
+
+ const extendSelectionRange = (targetKey: ListKey, selected: boolean) => {
+ const anchorKey = selectionAnchor();
+ if (
+ anchorKey === undefined ||
+ !selectableResult(anchorKey) ||
+ !selectableResult(targetKey)
+ ) {
+ return false;
+ }
+
+ selectionRangeSession ??= {
+ baseline: new Set(keySelection.keys()),
+ selected,
+ };
+ selectRange(
+ anchorKey,
+ targetKey,
+ selectionRangeSession.selected,
+ selectionRangeSession.baseline
+ );
+ return true;
+ };
+
+ const setSelected = (
+ rowKey: ListKey,
+ selected: boolean,
+ selectionOptions: ListSelectionSetOptions = {}
+ ) => {
+ const selectionKey = selectionKeyForRow(rowKey);
+ if (selectionKey === undefined) return false;
+
+ if (selectionOptions.range && selectionAnchor() !== undefined) {
+ return extendSelectionRange(rowKey, selected);
+ }
+
+ if (selected) keySelection.select(selectionKey);
+ else keySelection.deselect(selectionKey);
+ setSelectionRangeAnchor(rowKey);
+ return true;
+ };
+
+ const toggleSelected = (
+ rowKey: ListKey,
+ selectionOptions?: ListSelectionSetOptions
+ ) => setSelected(rowKey, !isRowSelected(rowKey), selectionOptions);
+
+ const clearSelection = () => {
+ keySelection.clear();
+ setSelectionRangeAnchor(undefined);
+ };
+
const visibleSelectionKeys = createMemo(
() => new Set(selectableBySelectionKey().keys())
);
@@ -403,9 +472,11 @@ export function createListController<TItem, TMetadata = unknown>(
keySelection.replace(
[...keySelection.keys()].filter((key) => !visible.has(key))
);
- return;
+ } else {
+ selectAllVisible();
}
- selectAllVisible();
+
+ setSelectionRangeAnchor(undefined);
};
const focusOptionsForActivation = (
@@ -524,6 +595,8 @@ export function createListController<TItem, TMetadata = unknown>(
) => activateResult(itemResultAt(index), activateOptions, true),
},
selection: {
+ /** Rendered occurrence used as the origin for range selection. */
+ anchor: selectionAnchor,
/** Requested logical keys, including identities awaiting item payloads. */
requestedKeys: keySelection.keys,
/** Currently resolved logical selection identities. */
@@ -544,11 +617,8 @@ export function createListController<TItem, TMetadata = unknown>(
const selectionKey = selectionKeyForRow(rowKey);
if (selectionKey !== undefined) keySelection.deselect(selectionKey);
},
- toggle: (rowKey: ListKey) => {
- const selectionKey = selectionKeyForRow(rowKey);
- if (selectionKey === undefined) return;
- keySelection.toggle(selectionKey);
- },
+ set: setSelected,
+ toggle: toggleSelected,
selectKey: (selectionKey: ListKey) => {
if (selectableBySelectionKey().has(selectionKey)) {
keySelection.select(selectionKey);
@@ -569,11 +639,14 @@ export function createListController<TItem, TMetadata = unknown>(
/** Restore logical keys before their item payloads are available. */
restore: keySelection.replace,
selectRange,
+ extendRange: extendSelectionRange,
+ setAnchor: setSelectionRangeAnchor,
+ clearAnchor: () => setSelectionRangeAnchor(undefined),
visibleKeys: visibleSelectionKeys,
allVisibleSelected,
selectAllVisible,
toggleAllVisible,
- clear: keySelection.clear,
+ clear: clearSelection,
prune: keySelection.prune,
},
};
diff --git a/apps/web/src/components/list/index.ts b/apps/web/src/components/list/index.ts
index 4206e3b5b2..78457e19c1 100644
--- a/apps/web/src/components/list/index.ts
+++ b/apps/web/src/components/list/index.ts
@@ -8,12 +8,17 @@ export {
type CreateListSelectionOptions,
createListController,
type ListController,
+ type ListSelectionSetOptions,
} from './create-list-controller';
export {
type CreateSelectionStateOptions,
createSelectionState,
type SelectionState,
} from './create-selection-state';
+export {
+ createStaticListDataSource,
+ type ListDataSource,
+} from './list-data-source';
export type {
ListActivateOptions,
ListActivation,
@@ -31,7 +36,9 @@ export type {
export {
type ListInteractionActivation,
type ListInteractionActivationIntent,
+ type ListInteractionDisclosure,
type ListInteractionNavigation,
+ type ListInteractionNavigationEvent,
type ListScrollHandle,
type UseListInteractionsOptions,
useListInteractions,
diff --git a/apps/web/src/components/list/list-data-source.ts b/apps/web/src/components/list/list-data-source.ts
new file mode 100644
index 0000000000..6d0474e493
--- /dev/null
+++ b/apps/web/src/components/list/list-data-source.ts
@@ -0,0 +1,36 @@
+import type { Accessor } from 'solid-js';
+
+/**
+ * Reactive data and loading controls consumed by a list independently of its
+ * query implementation.
+ */
+export type ListDataSource<TItem> = {
+ items: Accessor<readonly TItem[]>;
+ isLoading: Accessor<boolean>;
+ isFetching: Accessor<boolean>;
+ error: Accessor<unknown | undefined>;
+ hasMore: Accessor<boolean>;
+ isLoadingMore: Accessor<boolean>;
+ loadMore: () => Promise<void>;
+ refresh: () => Promise<void>;
+};
+
+/** Wraps local reactive items in the same contract as query-backed lists. */
+export function createStaticListDataSource<TItem>(
+ items: Accessor<readonly TItem[]>
+): ListDataSource<TItem> {
+ const falseAccessor = () => false;
+ const noError = () => undefined;
+ const noOp = () => Promise.resolve();
+
+ return {
+ items,
+ isLoading: falseAccessor,
+ isFetching: falseAccessor,
+ error: noError,
+ hasMore: falseAccessor,
+ isLoadingMore: falseAccessor,
+ loadMore: noOp,
+ refresh: noOp,
+ };
+}
diff --git a/apps/web/src/components/list/use-list-interactions.ts b/apps/web/src/components/list/use-list-interactions.ts
index 0f014a9257..09ebae18ad 100644
--- a/apps/web/src/components/list/use-list-interactions.ts
+++ b/apps/web/src/components/list/use-list-interactions.ts
@@ -1,8 +1,10 @@
+import { GO_TO_COMMAND_SCOPE, GO_TO_LEADER_KEY } from '@app/constants/hotkeys';
import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
-import { type Accessor, createSignal, onCleanup } from 'solid-js';
+import { isScopeInActiveBranch } from '@core/hotkey/utils';
+import { type Accessor, onCleanup } from 'solid-js';
import type { ListController } from './create-list-controller';
-import type { ListKey, ListNavigationOptions } from './types';
+import type { ListItemResult, ListNavigationOptions } from './types';
/** Minimal scrolling contract implemented by virtualized list handles. */
export type ListScrollHandle = {
@@ -16,12 +18,11 @@ type ListInteractionConditions = Partial<
Record<
| 'move'
| 'extendSelection'
- | 'first'
- | 'last'
| 'open'
| 'toggleSelection'
| 'toggleAllVisible'
- | 'clearSelection',
+ | 'clearSelection'
+ | 'disclosure',
() => boolean
>
>;
@@ -31,8 +32,20 @@ export type ListInteractionNavigation<TItem> = {
first?: ListNavigationOptions<TItem>;
last?: ListNavigationOptions<TItem>;
extendSelection?: ListNavigationOptions<TItem>;
+ onNavigate?: (event: ListInteractionNavigationEvent<TItem>) => void;
};
+export type ListInteractionNavigationEvent<TItem> =
+ | {
+ kind: 'move';
+ direction: 1 | -1;
+ result: ListItemResult<TItem> | undefined;
+ }
+ | {
+ kind: 'first' | 'last';
+ result: ListItemResult<TItem> | undefined;
+ };
+
export type ListInteractionActivationIntent = 'primary' | 'alternate';
export type ListInteractionActivation<TMetadata> = {
@@ -40,6 +53,13 @@ export type ListInteractionActivation<TMetadata> = {
alternateDescription?: string;
};
+export type ListInteractionDisclosure<TItem> = {
+ getKey: (item: TItem) => string | undefined;
+ isExpanded: (key: string) => boolean;
+ setExpanded: (key: string, expanded: boolean) => void;
+ getFocusKey?: (key: string, item: TItem) => string | undefined;
+};
+
export type UseListInteractionsOptions<TItem, TMetadata> = {
controller: ListController<TItem, TMetadata>;
scopeId: string;
@@ -49,6 +69,7 @@ export type UseListInteractionsOptions<TItem, TMetadata> = {
conditions?: ListInteractionConditions;
navigation?: ListInteractionNavigation<TItem>;
activation?: ListInteractionActivation<TMetadata>;
+ disclosure?: ListInteractionDisclosure<TItem>;
};
/**
@@ -60,16 +81,6 @@ 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);
@@ -81,86 +92,42 @@ export function useListInteractions<TItem, TMetadata = unknown>(
}
};
- const finishNavigation = (key: ListKey) => {
- setSelectionAnchor(key);
- setRangeSession(undefined);
+ const finishNavigation = (result: ListItemResult<TItem>) => {
+ list.selection.setAnchor(result.key);
scrollFocusedIntoView();
};
const move = (offset: 1 | -1) => {
const result = list.navigate.by(offset, options.navigation?.move);
+ options.navigation?.onNavigate?.({
+ kind: 'move',
+ direction: offset,
+ result,
+ });
if (!result) return false;
- finishNavigation(result.key);
+
+ finishNavigation(result);
return true;
};
const first = () => {
const result = list.navigate.toFirst(options.navigation?.first);
+ options.navigation?.onNavigate?.({ kind: 'first', result });
if (!result) return false;
- finishNavigation(result.key);
+
+ finishNavigation(result);
return true;
};
const last = () => {
const result = list.navigate.toLast(options.navigation?.last);
+ options.navigation?.onNavigate?.({ kind: 'last', result });
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
- );
+ finishNavigation(result);
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 {
@@ -185,42 +152,77 @@ export function useListInteractions<TItem, TMetadata = unknown>(
selectionNavigationOptions()
);
if (!firstSelectable) return false;
- setSelectionAnchor(firstSelectable.key);
- setRangeSession({
- baseline: new Set(list.selection.requestedKeys()),
- selected: true,
- });
- list.selection.select(firstSelectable.key);
+
+ list.selection.set(firstSelectable.key, true);
scrollFocusedIntoView();
return true;
}
- const anchor = selectionAnchor();
+ const anchor = list.selection.anchor();
if (anchor === undefined || !list.selection.isSelectable(anchor)) {
- setSelectionAnchor(currentKey);
+ list.selection.setAnchor(currentKey);
}
- beginRange(true);
const result = list.navigate.by(offset, selectionNavigationOptions());
- if (!result || !applyRange(result.key, true)) return false;
+ if (!result || !list.selection.extendRange(result.key, true)) return false;
+
scrollFocusedIntoView();
return true;
};
- const toggleAllVisible = () => {
- list.selection.toggleAllVisible();
- setSelectionAnchor(undefined);
- setRangeSession(undefined);
- };
+ const toggleAllVisible = () => list.selection.toggleAllVisible();
- const clearSelection = () => {
- list.selection.clear();
- setSelectionAnchor(undefined);
- setRangeSession(undefined);
- };
+ const clearSelection = () => list.selection.clear();
const group = createHotkeyGroup();
+ if (options.disclosure) {
+ const disclosure = options.disclosure;
+ const setExpanded = (expanded: boolean) => {
+ const item = list.focus.item();
+ if (item === undefined) return false;
+
+ const key = disclosure.getKey(item);
+ if (key === undefined || disclosure.isExpanded(key) === expanded) {
+ return false;
+ }
+
+ disclosure.setExpanded(key, expanded);
+ if (expanded) return true;
+
+ const focusKey = disclosure.getFocusKey?.(key, item);
+ if (focusKey === undefined) return true;
+
+ list.focus.set(focusKey, { reason: 'keyboard' });
+ scrollFocusedIntoView();
+ return true;
+ };
+
+ registerHotkey({
+ hotkey: ['h', 'arrowleft'],
+ hotkeyToken: TOKENS.unifiedList.navigation.parent,
+ scopeId: options.scopeId,
+ description: 'Collapse item',
+ condition: () => canHandle(options.conditions?.disclosure),
+ keyDownHandler: () => setExpanded(false),
+ registrationType: 'add',
+ handlerPriority: 4,
+ hide: true,
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: ['l', 'arrowright'],
+ hotkeyToken: TOKENS.unifiedList.navigation.child,
+ scopeId: options.scopeId,
+ description: 'Expand item',
+ condition: () => canHandle(options.conditions?.disclosure),
+ keyDownHandler: () => setExpanded(true),
+ registrationType: 'add',
+ handlerPriority: 4,
+ hide: true,
+ }).withGroup(group);
+ }
+
registerHotkey({
hotkey: ['arrowdown', 'j'],
hotkeyToken: TOKENS.entity.step.end,
@@ -248,51 +250,56 @@ export function useListInteractions<TItem, TMetadata = unknown>(
}).withGroup(group);
registerHotkey({
- hotkey: ['shift+arrowdown', 'shift+j'],
+ hotkey: 'home',
+ hotkeyToken: TOKENS.entity.jump.home,
scopeId: options.scopeId,
- description: 'Extend selection down',
- condition: () => canHandle(options.conditions?.extendSelection),
+ description: 'Go to first item',
+ condition: () => canHandle(options.conditions?.move),
hide: true,
- keyDownHandler: () => {
- extendSelection(1);
- return true;
- },
+ keyDownHandler: first,
}).withGroup(group);
registerHotkey({
- hotkey: ['shift+arrowup', 'shift+k'],
+ hotkey: GO_TO_LEADER_KEY,
+ scopeId: GO_TO_COMMAND_SCOPE,
+ description: 'Go to first item',
+ condition: () =>
+ canHandle(options.conditions?.move) &&
+ isScopeInActiveBranch(options.scopeId),
+ keyDownHandler: first,
+ registrationType: 'add',
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: ['end', 'shift+g'],
+ hotkeyToken: TOKENS.entity.jump.end,
scopeId: options.scopeId,
- description: 'Extend selection up',
- condition: () => canHandle(options.conditions?.extendSelection),
+ description: 'Go to last item',
+ condition: () => canHandle(options.conditions?.move),
hide: true,
- keyDownHandler: () => {
- extendSelection(-1);
- return true;
- },
+ keyDownHandler: last,
}).withGroup(group);
registerHotkey({
- hotkey: 'home',
- hotkeyToken: TOKENS.entity.jump.home,
+ hotkey: ['shift+arrowdown', 'shift+j'],
scopeId: options.scopeId,
- description: 'Go to first item',
- condition: () => canHandle(options.conditions?.first),
+ description: 'Extend selection down',
+ condition: () => canHandle(options.conditions?.extendSelection),
hide: true,
keyDownHandler: () => {
- first();
+ extendSelection(1);
return true;
},
}).withGroup(group);
registerHotkey({
- hotkey: ['end', 'shift+g'],
- hotkeyToken: TOKENS.entity.jump.end,
+ hotkey: ['shift+arrowup', 'shift+k'],
scopeId: options.scopeId,
- description: 'Go to last item',
- condition: () => canHandle(options.conditions?.last),
+ description: 'Extend selection up',
+ condition: () => canHandle(options.conditions?.extendSelection),
hide: true,
keyDownHandler: () => {
- last();
+ extendSelection(-1);
return true;
},
}).withGroup(group);
@@ -340,7 +347,7 @@ export function useListInteractions<TItem, TMetadata = unknown>(
condition: canToggleSelection,
keyDownHandler: () => {
const key = list.focus.key();
- return key === undefined ? false : toggleSelected(key);
+ return key === undefined ? false : list.selection.toggle(key);
},
}).withGroup(group);
@@ -369,6 +376,7 @@ export function useListInteractions<TItem, TMetadata = unknown>(
clearSelection();
return true;
},
+ registrationType: 'add',
}).withGroup(group);
onCleanup(() => group.dispose());
@@ -381,16 +389,13 @@ export function useListInteractions<TItem, TMetadata = unknown>(
scrollFocusedIntoView,
},
selection: {
- anchor: selectionAnchor,
- set: setSelected,
- toggle: toggleSelected,
+ anchor: list.selection.anchor,
+ set: list.selection.set,
+ toggle: list.selection.toggle,
extend: extendSelection,
toggleAllVisible,
clear: clearSelection,
- clearAnchor: () => {
- setSelectionAnchor(undefined);
- setRangeSession(undefined);
- },
+ clearAnchor: list.selection.clearAnchor,
},
};
}
diff --git a/apps/web/src/components/view-shell/ViewShell.tsx b/apps/web/src/components/view-shell/ViewShell.tsx
index 7a9eb8f5d8..8499a7c150 100644
--- a/apps/web/src/components/view-shell/ViewShell.tsx
+++ b/apps/web/src/components/view-shell/ViewShell.tsx
@@ -363,6 +363,14 @@ function Detail(props: JSX.HTMLAttributes<HTMLDivElement>) {
const [local, rest] = splitProps(props, ['children', 'class']);
const ws = useViewShellInternal();
const layout = ws.detail.layout;
+ const target = () => {
+ const initialWidth = layout().initialWidth;
+ if (initialWidth === 'auto') return undefined;
+ return {
+ kind: 'px' as const,
+ px: initialWidth ?? layout().width,
+ };
+ };
return (
<Switch>
@@ -372,7 +380,7 @@ function Detail(props: JSX.HTMLAttributes<HTMLDivElement>) {
index={2}
minSize={layout().min}
maxSize={layout().max}
- target={{ kind: 'px', px: layout().width }}
+ target={target()}
>
<div
{...rest}
diff --git a/apps/web/src/components/view-shell/index.ts b/apps/web/src/components/view-shell/index.ts
index 33f420327a..dcd468b412 100644
--- a/apps/web/src/components/view-shell/index.ts
+++ b/apps/web/src/components/view-shell/index.ts
@@ -13,6 +13,15 @@ export {
type ListSortDropdownProps,
} from './ListDropdowns';
export { SearchBar, type SearchBarProps } from './SearchBar';
+export {
+ type UseViewControlHotkeysOptions,
+ useViewControlHotkeys,
+ type ViewControlHotkeyAction,
+} from './use-view-control-hotkeys';
+export {
+ type UseViewTabHotkeysOptions,
+ useViewTabHotkeys,
+} from './use-view-tab-hotkeys';
export {
useViewShell,
ViewShell,
diff --git a/apps/web/src/components/view-shell/use-view-control-hotkeys.ts b/apps/web/src/components/view-shell/use-view-control-hotkeys.ts
new file mode 100644
index 0000000000..0cb6dc394b
--- /dev/null
+++ b/apps/web/src/components/view-shell/use-view-control-hotkeys.ts
@@ -0,0 +1,51 @@
+import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
+import type { HotkeyToken } from '@core/hotkey/tokens';
+import { TOKENS } from '@core/hotkey/tokens';
+import type { ValidHotkey } from '@core/hotkey/types';
+import { onCleanup } from 'solid-js';
+
+export type ViewControlHotkeyAction = {
+ description: string;
+ run: () => boolean | void;
+ condition?: () => boolean;
+};
+
+export type UseViewControlHotkeysOptions = {
+ scopeId: string;
+ enabled?: () => boolean;
+ search?: ViewControlHotkeyAction;
+ filter?: ViewControlHotkeyAction;
+ sort?: ViewControlHotkeyAction;
+};
+
+/** Registers shortcuts that open a view's search, filter, and sort controls. */
+export function useViewControlHotkeys(options: UseViewControlHotkeysOptions) {
+ const group = createHotkeyGroup();
+ const isEnabled = () => options.enabled?.() ?? true;
+
+ const registerAction = (
+ hotkey: ValidHotkey,
+ hotkeyToken: HotkeyToken,
+ action: ViewControlHotkeyAction | undefined,
+ registrationType: 'add' | 'override' = 'override'
+ ) => {
+ if (!action) return;
+
+ registerHotkey({
+ hotkey,
+ hotkeyToken,
+ scopeId: options.scopeId,
+ description: action.description,
+ condition: () => isEnabled() && (action.condition?.() ?? true),
+ keyDownHandler: () => action.run() !== false,
+ registrationType,
+ runWithInputFocused: hotkey === 'cmd+f',
+ }).withGroup(group);
+ };
+
+ registerAction('cmd+f', TOKENS.soup.openSearch, options.search, 'add');
+ registerAction('f', TOKENS.soup.filter, options.filter);
+ registerAction('s', TOKENS.soup.sort, options.sort);
+
+ onCleanup(() => group.dispose());
+}
diff --git a/apps/web/src/components/view-shell/use-view-tab-hotkeys.ts b/apps/web/src/components/view-shell/use-view-tab-hotkeys.ts
new file mode 100644
index 0000000000..af9dc40992
--- /dev/null
+++ b/apps/web/src/components/view-shell/use-view-tab-hotkeys.ts
@@ -0,0 +1,76 @@
+import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
+import { TOKENS } from '@core/hotkey/tokens';
+import { onCleanup } from 'solid-js';
+
+export type UseViewTabHotkeysOptions<TTab extends string> = {
+ scopeId: string;
+ ids: () => readonly TTab[];
+ activeId: () => TTab;
+ setActiveId: (id: TTab) => void;
+ enabled?: () => boolean;
+};
+
+/** Registers numeric and sequential navigation for a view's tabs. */
+export function useViewTabHotkeys<TTab extends string>(
+ options: UseViewTabHotkeysOptions<TTab>
+) {
+ const group = createHotkeyGroup();
+ const isEnabled = () => options.enabled?.() ?? true;
+ const numberKeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] as const;
+
+ numberKeys.forEach((key, index) => {
+ registerHotkey({
+ hotkey: key,
+ hotkeyToken: TOKENS.soup.tabs[key],
+ scopeId: options.scopeId,
+ description: `Switch to tab ${key}`,
+ condition: () => isEnabled() && options.ids().length > index,
+ keyDownHandler: () => {
+ const id = options.ids()[index];
+ if (!id) return false;
+
+ options.setActiveId(id);
+ return true;
+ },
+ hide: true,
+ }).withGroup(group);
+ });
+
+ const move = (offset: 1 | -1) => {
+ const ids = options.ids();
+ if (ids.length < 2) return false;
+
+ const currentIndex = ids.indexOf(options.activeId());
+ let origin = currentIndex;
+ if (origin === -1) {
+ origin = offset === 1 ? -1 : 0;
+ }
+
+ const nextIndex = (origin + offset + ids.length) % ids.length;
+ const next = ids[nextIndex];
+ if (!next) return false;
+
+ options.setActiveId(next);
+ return true;
+ };
+
+ registerHotkey({
+ hotkey: 'tab',
+ hotkeyToken: TOKENS.soup.tabs.next,
+ scopeId: options.scopeId,
+ description: 'Next tab',
+ condition: () => isEnabled() && options.ids().length > 1,
+ keyDownHandler: () => move(1),
+ }).withGroup(group);
+
+ registerHotkey({
+ hotkey: 'shift+tab',
+ hotkeyToken: TOKENS.soup.tabs.prev,
+ scopeId: options.scopeId,
+ description: 'Previous tab',
+ condition: () => isEnabled() && options.ids().length > 1,
+ keyDownHandler: () => move(-1),
+ }).withGroup(group);
+
+ onCleanup(() => group.dispose());
+}
diff --git a/apps/web/src/components/view-shell/view-shell-layout.ts b/apps/web/src/components/view-shell/view-shell-layout.ts
index b6581e7f7b..5c556d0c6a 100644
--- a/apps/web/src/components/view-shell/view-shell-layout.ts
+++ b/apps/web/src/components/view-shell/view-shell-layout.ts
@@ -30,6 +30,8 @@ export type DetailNarrowBehavior = 'overlay' | 'replace' | 'hide';
export type DetailLayout = {
width: number;
+ /** Initial inline panel width. Use `auto` to fill the space left by siblings. */
+ initialWidth?: number | 'auto';
min: number;
max: number;
whenNarrow: DetailNarrowBehavior;
diff --git a/apps/web/src/features/next-soup/actions/entity-action-context.ts b/apps/web/src/features/next-soup/actions/entity-action-context.ts
new file mode 100644
index 0000000000..e592633a55
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/entity-action-context.ts
@@ -0,0 +1,244 @@
+import type { ListController } from '@app/components/list';
+import { isListViewID } from '@app/constants/list-views';
+import type { EntityData } from '@entity';
+import type { SoupRow, SoupState } from '../create-soup-state';
+import { canExecuteMarkDoneOnView } from './make-mark-done-action';
+
+type MaybePromise<T> = T | Promise<T>;
+
+export type EntityActionSenderBucket = 'signal' | 'noise';
+
+export type EntityActionViewContext = {
+ supportsMarkDone: boolean;
+ senderBucket: EntityActionSenderBucket | undefined;
+};
+
+/** Soup list capabilities used by entity actions. */
+export type EntityActionListState = {
+ focus: Pick<SoupState['focus'], 'id' | 'index' | 'set'>;
+ navigate: Pick<SoupState['navigate'], 'peekOffset'>;
+ items: Pick<SoupState['items'], 'count' | 'get' | 'at'>;
+ selection: Pick<SoupState['selection'], 'clear'>;
+ collapseEntity: Pick<
+ SoupState['collapseEntity'],
+ 'callback' | 'shouldCollapse'
+ >;
+};
+
+export type EntityActionListFocusTarget = {
+ key: string;
+ index: number;
+ entity: EntityData;
+};
+
+export type ToEntityActionListStateOptions<TItem, TMetadata> = {
+ controller: ListController<TItem, TMetadata>;
+ getEntity: (item: TItem) => EntityData | undefined;
+ onFocus?: (
+ target: EntityActionListFocusTarget | undefined
+ ) => MaybePromise<void>;
+ collapse?: {
+ enabled: () => boolean;
+ run: (entityId: string) => Promise<void>;
+ };
+};
+
+type AdaptedRow = {
+ row: SoupRow;
+ controllerIndex: number;
+ entity: EntityData;
+};
+
+function resolveSenderBucket(
+ activeTab: string | undefined
+): EntityActionSenderBucket | undefined {
+ if (activeTab === 'noise') return 'noise';
+
+ if (
+ activeTab === undefined ||
+ activeTab === 'signal' ||
+ activeTab === 'important'
+ ) {
+ return 'signal';
+ }
+
+ return undefined;
+}
+
+export function resolveEntityActionViewContext(options: {
+ activeListView: string;
+ activeTab: string | undefined;
+}): EntityActionViewContext {
+ const { activeListView, activeTab } = options;
+
+ return {
+ supportsMarkDone:
+ activeTab !== undefined &&
+ isListViewID(activeListView) &&
+ canExecuteMarkDoneOnView(activeListView, activeTab),
+ senderBucket: resolveSenderBucket(activeTab),
+ };
+}
+
+/**
+ * Adapts a generic list controller to the narrow Soup-shaped state consumed by
+ * entity actions.
+ */
+export function toEntityActionListState<TItem, TMetadata>(
+ options: ToEntityActionListStateOptions<TItem, TMetadata>
+): EntityActionListState {
+ const { controller } = options;
+
+ const rows = (): AdaptedRow[] => {
+ const result: AdaptedRow[] = [];
+
+ controller.items.all().forEach((item, controllerIndex) => {
+ const entity = options.getEntity(item);
+ if (!entity) return;
+
+ const key = controller.items.keyOf(item);
+ const row: SoupRow = {
+ identityKey: key,
+ id: key,
+ index: result.length,
+ original: entity,
+ group: undefined,
+ getIsGrouped: () => false,
+ getIsLoadMore: () => false,
+ isFocused: () => controller.focus.key() === key,
+ isSelected: () => controller.selection.isSelected(key),
+ };
+ result.push({ row, controllerIndex, entity });
+ });
+
+ return result;
+ };
+
+ const focusedRow = () => {
+ const key = controller.focus.key();
+ if (key === undefined) return undefined;
+
+ return rows().find(({ row }) => row.id === key);
+ };
+
+ const getRow = (id: string) => {
+ const allRows = rows();
+ return (
+ allRows.find(({ row }) => row.id === id) ??
+ allRows.find(({ entity }) => entity.id === id)
+ );
+ };
+
+ const setFocus = (id: string | undefined) => {
+ if (id === undefined) {
+ controller.focus.clear({ reason: 'programmatic' });
+ void options.onFocus?.(undefined);
+ return;
+ }
+
+ const target = getRow(id);
+ if (!target) return;
+
+ const focused = controller.focus.set(target.row.id, {
+ reason: 'programmatic',
+ force: true,
+ });
+ if (!focused) return;
+
+ void options.onFocus?.({
+ key: focused.key,
+ index: target.controllerIndex,
+ entity: target.entity,
+ });
+ };
+
+ const peekOffset: EntityActionListState['navigate']['peekOffset'] = (
+ offset,
+ navigationOptions
+ ) => {
+ if (!Number.isSafeInteger(offset)) {
+ throw new RangeError('List navigation offset must be a finite integer');
+ }
+
+ const allRows = rows();
+ if (allRows.length === 0) return undefined;
+
+ const shouldSkip = (row: SoupRow) =>
+ navigationOptions?.skip?.(row) ?? false;
+ const currentIndex = focusedRow()?.row.index ?? -1;
+
+ if (offset === 0) {
+ const current = allRows[currentIndex];
+ return current && !shouldSkip(current.row)
+ ? { row: current.row, index: currentIndex }
+ : undefined;
+ }
+
+ const direction = offset > 0 ? 1 : -1;
+ if (currentIndex === -1) {
+ let index = direction > 0 ? 0 : allRows.length - 1;
+ while (index >= 0 && index < allRows.length) {
+ const candidate = allRows[index];
+ if (candidate && !shouldSkip(candidate.row)) {
+ return { row: candidate.row, index };
+ }
+ index += direction;
+ }
+ return undefined;
+ }
+
+ let remaining = Math.abs(offset);
+ let cursor = currentIndex;
+ let lastValid = shouldSkip(allRows[currentIndex]?.row) ? -1 : currentIndex;
+ let iterations = 0;
+ const iterationLimit = allRows.length * remaining;
+ const shouldWrap = navigationOptions?.wrapNavigation ?? false;
+
+ while (remaining > 0 && iterations < iterationLimit) {
+ iterations += 1;
+ cursor += direction;
+
+ if (cursor < 0 || cursor >= allRows.length) {
+ if (!shouldWrap) break;
+ cursor = (cursor + allRows.length) % allRows.length;
+ }
+
+ const candidate = allRows[cursor];
+ if (!candidate || shouldSkip(candidate.row)) continue;
+
+ lastValid = cursor;
+ remaining -= 1;
+ }
+
+ const result = allRows[lastValid];
+ return result ? { row: result.row, index: lastValid } : undefined;
+ };
+
+ const collapseCallback = () => {
+ const collapse = options.collapse;
+ return collapse ? (entityId: string) => collapse.run(entityId) : undefined;
+ };
+
+ return {
+ focus: {
+ id: () => focusedRow()?.row.id,
+ index: () => focusedRow()?.row.index ?? -1,
+ set: setFocus,
+ },
+ navigate: {
+ peekOffset,
+ },
+ items: {
+ count: () => rows().length,
+ get: (id) => getRow(id)?.row,
+ at: (index) => rows()[index]?.row,
+ },
+ selection: {
+ clear: controller.selection.clear,
+ },
+ collapseEntity: {
+ callback: collapseCallback,
+ shouldCollapse: () => options.collapse?.enabled() ?? false,
+ },
+ };
+}
diff --git a/apps/web/src/features/next-soup/actions/index.ts b/apps/web/src/features/next-soup/actions/index.ts
index b87f00701e..c4c31dc74e 100644
--- a/apps/web/src/features/next-soup/actions/index.ts
+++ b/apps/web/src/features/next-soup/actions/index.ts
@@ -1,3 +1,12 @@
+export {
+ type EntityActionListFocusTarget,
+ type EntityActionListState,
+ type EntityActionSenderBucket,
+ type EntityActionViewContext,
+ resolveEntityActionViewContext,
+ type ToEntityActionListStateOptions,
+ toEntityActionListState,
+} from './entity-action-context';
export { makeAddTagAction } from './make-add-tag-action';
export { makeBlockSenderAction } from './make-block-sender-action';
export { makeCopyAction } from './make-copy-action';
diff --git a/apps/web/src/features/next-soup/actions/make-block-sender-action.ts b/apps/web/src/features/next-soup/actions/make-block-sender-action.ts
index f47d5441c9..675eea946b 100644
--- a/apps/web/src/features/next-soup/actions/make-block-sender-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-block-sender-action.ts
@@ -1,7 +1,7 @@
import type { EntityData } from '@entity';
import { useNonPrimaryEmailLinkIdHeader } from '@queries/email/link';
import { blockSenderWithToast } from '@queries/email/thread';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
export const makeBlockSenderAction = () => {
const toHeaderLinkId = useNonPrimaryEmailLinkIdHeader();
@@ -22,7 +22,10 @@ export const makeBlockSenderAction = () => {
}
};
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
await execute(entities);
};
diff --git a/apps/web/src/features/next-soup/actions/make-copy-action.ts b/apps/web/src/features/next-soup/actions/make-copy-action.ts
index c169fcc342..89f8cd29b6 100644
--- a/apps/web/src/features/next-soup/actions/make-copy-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-copy-action.ts
@@ -1,7 +1,7 @@
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
import { createBulkCopyDssEntityMutation } from '@entity';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
export const makeCopyAction = () => {
const bulkCopyMutation = createBulkCopyDssEntityMutation();
@@ -30,7 +30,10 @@ export const makeCopyAction = () => {
);
};
- const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ soup: EntityActionListState
+ ) => {
await execute(entities);
soup.selection.clear();
};
diff --git a/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.ts b/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.ts
index cb9c3150b7..cd6b205b86 100644
--- a/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.ts
@@ -1,6 +1,6 @@
import { copyBranchNameToClipboard } from '@core/util/branchName';
import { type EntityData, isTaskEntity } from '@entity';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
export const makeCopyBranchNameAction = () => {
const canExecute = (entity: EntityData): boolean => {
@@ -13,7 +13,10 @@ export const makeCopyBranchNameAction = () => {
await copyBranchNameToClipboard(entity.id);
};
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
await execute(entities);
};
diff --git a/apps/web/src/features/next-soup/actions/make-copy-entity-id-action.ts b/apps/web/src/features/next-soup/actions/make-copy-entity-id-action.ts
index 6be47e0a17..509064a484 100644
--- a/apps/web/src/features/next-soup/actions/make-copy-entity-id-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-copy-entity-id-action.ts
@@ -1,6 +1,6 @@
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
export const makeCopyEntityIdAction = () => {
const canExecute = (_entity: EntityData): boolean => {
@@ -22,7 +22,10 @@ export const makeCopyEntityIdAction = () => {
await executeById(entity.id);
};
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
await execute(entities);
};
diff --git a/apps/web/src/features/next-soup/actions/make-copy-link-action.ts b/apps/web/src/features/next-soup/actions/make-copy-link-action.ts
index ddca6548f5..46aa775ee7 100644
--- a/apps/web/src/features/next-soup/actions/make-copy-link-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-copy-link-action.ts
@@ -4,8 +4,8 @@ import { toast } from '@core/component/Toast/Toast';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { buildSimpleEntityUrl } from '@core/util/url';
import { type EntityData, isGithubPrEntity } from '@entity';
-import type { SoupState } from '../create-soup-state';
import { calendarEventLinkTarget } from '../utils';
+import type { EntityActionListState } from './entity-action-context';
/**
* Get the URL type/path segment for an entity
@@ -89,7 +89,10 @@ export const makeCopyLinkAction = () => {
toast.success('Link copied to clipboard');
};
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
await execute(entities);
// Don't clear selection or change focus for copy link
};
diff --git a/apps/web/src/features/next-soup/actions/make-create-reminder-action.ts b/apps/web/src/features/next-soup/actions/make-create-reminder-action.ts
index 1046f4c420..74a517143b 100644
--- a/apps/web/src/features/next-soup/actions/make-create-reminder-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-create-reminder-action.ts
@@ -2,7 +2,7 @@ import { openReminderComposer } from '@app/features/reminders/reminder-composer'
import { ENABLE_REMINDERS } from '@core/constant/featureFlags';
import type { EntityData } from '@entity';
import { reminderTarget } from '@queries/reminders/reminders';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
import type { makeMarkDoneAction } from './make-mark-done-action';
/**
@@ -15,7 +15,7 @@ import type { makeMarkDoneAction } from './make-mark-done-action';
* done is a thing this list does.
*/
export type ReminderCreatedList = {
- soup: SoupState;
+ soup: EntityActionListState;
advances: boolean;
};
@@ -61,7 +61,7 @@ export const makeCreateReminderAction = (
const executeWithSoup = async (
entities: EntityData[],
- soup: SoupState,
+ soup: EntityActionListState,
/** Whether the list moves on once the row is marked done. */
opts: { advances: boolean }
) => {
diff --git a/apps/web/src/features/next-soup/actions/make-delete-action.ts b/apps/web/src/features/next-soup/actions/make-delete-action.ts
index 98acc74817..aa8ad2b360 100644
--- a/apps/web/src/features/next-soup/actions/make-delete-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-delete-action.ts
@@ -4,8 +4,8 @@ import { globalRemoveFromSplitHistory } from '@components/app/split-layout/layou
import { toast } from '@core/component/Toast/Toast';
import { createBulkDeleteDssItemsMutation, type EntityData } from '@entity';
import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
-import type { SoupState } from '../create-soup-state';
import { restoreSoupFocus, trashEmails } from '../utils';
+import type { EntityActionListState } from './entity-action-context';
type MakeDeleteOptions = {
userId: () => string | undefined;
@@ -93,7 +93,10 @@ export const makeDeleteAction = (options: MakeDeleteOptions) => {
});
};
- const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ soup: EntityActionListState
+ ) => {
const currentIndex = soup.focus.index();
const nextRow =
soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
diff --git a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts
index 432158ede4..b16e11c02c 100644
--- a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts
@@ -9,7 +9,7 @@ import {
getCachedItemPreview,
isAccessiblePreviewItem,
} from '@queries/preview';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
/**
* The description this reminder would get if it were being created now, for a
@@ -57,7 +57,10 @@ export const makeEditReminderAction = () => {
});
};
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
// Opening the composer doesn't change the list, so selection and focus are
// left where they are.
execute(entities);
diff --git a/apps/web/src/features/next-soup/actions/make-favorite-action.ts b/apps/web/src/features/next-soup/actions/make-favorite-action.ts
index d41618f8a4..84917c09f0 100644
--- a/apps/web/src/features/next-soup/actions/make-favorite-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-favorite-action.ts
@@ -6,7 +6,7 @@ import {
useFavoritesData,
useRemoveFavoriteMutation,
} from '@queries/favorites/favorites';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
/**
* Toggle an entity in the user's favorites.
@@ -82,7 +82,10 @@ export const makeFavoriteAction = () => {
}
};
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
// Favoriting doesn't change the list contents; keep selection/focus.
await execute(entities);
};
diff --git a/apps/web/src/features/next-soup/actions/make-hide-company-action.ts b/apps/web/src/features/next-soup/actions/make-hide-company-action.ts
index 7536c4d4ef..9143047dbe 100644
--- a/apps/web/src/features/next-soup/actions/make-hide-company-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-hide-company-action.ts
@@ -1,7 +1,7 @@
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
-import type { SoupState } from '../create-soup-state';
import { restoreSoupFocus } from '../utils';
+import type { EntityActionListState } from './entity-action-context';
type MakeHideCompanyOptions = {
// Available to all team members; the backend enforces
@@ -15,7 +15,10 @@ export const makeHideCompanyAction = (options: MakeHideCompanyOptions) => {
const canExecute = (entity: EntityData): boolean =>
entity.type === 'crm_company';
- const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ soup: EntityActionListState
+ ) => {
const entity = entities[0];
if (entity?.type !== 'crm_company') return;
diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-done-action.ts
index bede448d46..967c75ab7d 100644
--- a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.ts
@@ -20,7 +20,7 @@ import {
toNotificationEntityRef,
} from '@queries/notification/entity-mutations';
import { type UndoHandle, useUndoableMutation } from '@queries/undo';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
// Valid list views where the mark done should be allowed to run
const VALID_MARK_DONE_LIST_VIEWS: `${ListView}-${string}`[] = [
@@ -87,6 +87,7 @@ type MarkDoneExecuteOpts = Pick<
>;
type MarkDoneExecuteWithSoupOpts = MarkDoneExecuteOpts & {
+ anchorKey?: string;
nextEntityId?: string;
};
@@ -300,7 +301,7 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
const executeWithSoup = async (
entities: EntityData[],
- soup: SoupState,
+ soup: EntityActionListState,
onNavigate?: (entity: EntityData) => void,
opts?: MarkDoneExecuteWithSoupOpts
) => {
@@ -310,7 +311,7 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
const targets = entities.filter(isMarkDoneTarget);
if (targets.length === 0) return;
- const focusedIdBeforeMarkDone = soup.focus.id();
+ const focusedIdBeforeMarkDone = opts?.anchorKey ?? soup.focus.id();
const markedEntityIds = new Set(targets.map((entity) => entity.id));
const adjacentRow = (direction: 1 | -1) => {
let previousCandidateIndex: number | undefined;
diff --git a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts
index d6f1756957..60aff44917 100644
--- a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts
@@ -9,7 +9,7 @@ import type { NotificationSource } from '@notifications';
import { threadCanBeMarkedNotDone } from '@queries/email/thread';
import { fetchDoneNotificationIdsByEventItemIds } from '@queries/notification/user-notifications';
import { invalidateAllSoup, refetchSoupEntity } from '@queries/soup/cache';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
type MakeMarkNotDoneOptions = {
notificationSource: () => NotificationSource;
@@ -139,7 +139,10 @@ export const makeMarkNotDoneAction = (options: MakeMarkNotDoneOptions) => {
/** Signature parity with makeMarkDoneAction's executeWithSoup — no
* navigation or collapse: the rows stay in place. */
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
await execute(entities);
};
diff --git a/apps/web/src/features/next-soup/actions/make-mark-notifications-read-action.ts b/apps/web/src/features/next-soup/actions/make-mark-notifications-read-action.ts
index f443f164c7..f98f7a34f1 100644
--- a/apps/web/src/features/next-soup/actions/make-mark-notifications-read-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-mark-notifications-read-action.ts
@@ -13,7 +13,7 @@ import {
toNotificationEntityRef,
updateNotificationsForEntities,
} from '@queries/notification/entity-mutations';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
type MakeMarkNotificationsReadOptions = {
notificationSource: () => NotificationSource;
@@ -106,7 +106,10 @@ export const makeMarkNotificationsReadAction = (
};
/** Rows remain in place; this only updates their notification read state. */
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
await execute(entities);
};
diff --git a/apps/web/src/features/next-soup/actions/make-mark-unread-action.ts b/apps/web/src/features/next-soup/actions/make-mark-unread-action.ts
index 19e7c797d1..4b2387201f 100644
--- a/apps/web/src/features/next-soup/actions/make-mark-unread-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-mark-unread-action.ts
@@ -6,7 +6,7 @@ import {
useMarkThreadAsUnreadMutation,
} from '@queries/email/thread';
import { refetchSoupEntity } from '@queries/soup/cache';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
/**
* Marks read email threads as unread. Rows stay in place — only the soup
@@ -49,7 +49,10 @@ export const makeMarkUnreadAction = () => {
/** Signature parity with the mark-done actions — no navigation or
* collapse: the rows stay in place. */
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
await execute(entities);
};
@@ -99,7 +102,10 @@ export const makeMarkReadAction = () => {
/** Signature parity with the mark-done actions — no navigation or
* collapse: the rows stay in place. */
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
await execute(entities);
};
diff --git a/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts b/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts
index 1eee9f689a..42a5c58533 100644
--- a/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts
@@ -1,8 +1,8 @@
import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
-import type { SoupState } from '../create-soup-state';
import { restoreSoupFocus } from '../utils';
+import type { EntityActionListState } from './entity-action-context';
export const makeMoveToProjectAction = () => {
const canExecute = (entity: EntityData): boolean => {
@@ -31,7 +31,10 @@ export const makeMoveToProjectAction = () => {
});
};
- const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ soup: EntityActionListState
+ ) => {
const currentIndex = soup.focus.index();
const nextRow =
soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
diff --git a/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts b/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts
index 078549975c..38ff88ab8f 100644
--- a/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts
@@ -1,8 +1,8 @@
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
import { createBulkRemoveFromProjectDssEntityMutation } from '@entity';
-import type { SoupState } from '../create-soup-state';
import { restoreSoupFocus } from '../utils';
+import type { EntityActionListState } from './entity-action-context';
/** Clear the entities' folder (set their project to none). */
export const makeRemoveFromProjectAction = () => {
@@ -28,7 +28,10 @@ export const makeRemoveFromProjectAction = () => {
return true;
};
- const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ soup: EntityActionListState
+ ) => {
// Entities leave the viewed folder's list; move focus to a neighbor
const currentIndex = soup.focus.index();
const nextRow =
diff --git a/apps/web/src/features/next-soup/actions/make-rename-action.ts b/apps/web/src/features/next-soup/actions/make-rename-action.ts
index f248842317..b467f0e957 100644
--- a/apps/web/src/features/next-soup/actions/make-rename-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-rename-action.ts
@@ -1,8 +1,8 @@
import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
-import type { SoupState } from '../create-soup-state';
import { restoreSoupFocus } from '../utils';
+import type { EntityActionListState } from './entity-action-context';
type MakeRenameOptions = {
userId: () => string | undefined;
@@ -38,7 +38,10 @@ export const makeRenameAction = (options: MakeRenameOptions) => {
});
};
- const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ soup: EntityActionListState
+ ) => {
const firstEntity = entities[0];
openBulkEditModal({
diff --git a/apps/web/src/features/next-soup/actions/make-sender-filter-action.ts b/apps/web/src/features/next-soup/actions/make-sender-filter-action.ts
index 674ac4075a..0cf099dc38 100644
--- a/apps/web/src/features/next-soup/actions/make-sender-filter-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-sender-filter-action.ts
@@ -1,6 +1,6 @@
import type { EntityData } from '@entity';
import { useNonPrimaryEmailLinkIdHeader } from '@queries/email/link';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
export const makeSenderFilterAction = (
action: (email: string, linkId?: string) => Promise<void>
@@ -26,7 +26,10 @@ export const makeSenderFilterAction = (
}
};
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
await execute(entities);
};
diff --git a/apps/web/src/features/next-soup/actions/make-share-action.ts b/apps/web/src/features/next-soup/actions/make-share-action.ts
index 24b032074c..52a4461eaa 100644
--- a/apps/web/src/features/next-soup/actions/make-share-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-share-action.ts
@@ -4,7 +4,7 @@ import {
type ShareableEntityData,
} from '@app/features/sharing/global-share-modal/shareable-entity';
import type { EntityData } from '@entity';
-import type { SoupState } from '../create-soup-state';
+import type { EntityActionListState } from './entity-action-context';
export const makeShareAction = () => {
/**
@@ -26,7 +26,10 @@ export const makeShareAction = () => {
});
};
- const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ const executeWithSoup = async (
+ entities: EntityData[],
+ _soup: EntityActionListState
+ ) => {
const entity = entities[0];
if (!entity) return;
diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts
index f3cffa249f..31a213bf4d 100644
--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts
+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts
@@ -1,9 +1,4 @@
-import { isListViewID } from '@app/constants/list-views';
-import { canExecuteMarkDoneOnView } from '@app/features/next-soup/actions/make-mark-done-action';
-import {
- openEntityInSplitFromUnifiedList,
- restoreSoupFocus,
-} from '@app/features/next-soup/utils';
+import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';
import { useAllProperties } from '@app/features/property/editor/hooks/useAllProperties';
import { openPropertyEditor } from '@app/features/property/editor/state/propertyEditor';
import { isShareableEntityType } from '@app/features/sharing/global-share-modal/shareable-entity';
@@ -16,8 +11,11 @@ import { TOKENS } from '@core/hotkey/tokens';
import { type EntityData, isTaskEntity } from '@entity';
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import type { Property, PropertyDefinitionDomain } from '@property/types';
-import { onCleanup } from 'solid-js';
-import type { SoupState } from '../create-soup-state';
+import { type Accessor, onCleanup } from 'solid-js';
+import type {
+ EntityActionListState,
+ EntityActionViewContext,
+} from './entity-action-context';
import {
makeAddTagAction,
makeCopyAction,
@@ -41,18 +39,27 @@ import {
type UseEntityActionHotkeysOptions = {
scopeId: string;
- soup: SoupState;
- activeSoupViewTab?: () => string | undefined;
+ list: EntityActionListState;
+ selectedEntities: Accessor<EntityData[]>;
+ focusedEntity: Accessor<EntityData | undefined>;
+ restoreFocus: (entityId?: string) => void | Promise<void>;
+ viewContext: Accessor<EntityActionViewContext>;
splitHandle?: SplitHandle;
condition?: () => boolean;
- /** Fallback entity getter used when soup has no selection/focus (e.g., block views) */
- getEntityFallback?: () => EntityData | undefined;
};
export const useEntityActionHotkeys = (
options: UseEntityActionHotkeysOptions
) => {
- const { scopeId, soup, splitHandle, condition, getEntityFallback } = options;
+ const {
+ scopeId,
+ list,
+ selectedEntities,
+ focusedEntity,
+ restoreFocus,
+ splitHandle,
+ condition,
+ } = options;
const userId = useUserId();
const notificationSource = useGlobalNotificationSource();
@@ -99,23 +106,12 @@ export const useEntityActionHotkeys = (
const addTagAction = makeAddTagAction();
const getEntitiesForAction = (): EntityData[] => {
- if (
- splitHandle?.content().type === 'component' &&
- isListViewID(splitHandle?.content().id)
- ) {
- const selected = soup.selection.selected();
- if (selected.length > 0) return selected;
- }
+ const selected = selectedEntities();
+ if (selected.length > 0) return selected;
- const focused = soup.focus.item();
+ const focused = focusedEntity();
if (focused) return [focused];
- // Fallback: use provided entity getter (e.g., for block views)
- if (getEntityFallback) {
- const entity = getEntityFallback();
- if (entity) return [entity];
- }
-
return [];
};
@@ -140,10 +136,7 @@ export const useEntityActionHotkeys = (
* that follows setting a reminder advances on the same answer.
*/
const marksDoneOnThisView = (): boolean => {
- const contentId = splitHandle?.content().id;
- if (!isListViewID(contentId)) return false;
- const soupViewTab = options.activeSoupViewTab?.();
- return !soupViewTab || canExecuteMarkDoneOnView(contentId, soupViewTab);
+ return options.viewContext().supportsMarkDone;
};
// Declared here rather than with the other actions above because its
@@ -169,7 +162,7 @@ export const useEntityActionHotkeys = (
const entities = getEntitiesForAction();
if (entities.length > 0) {
openPropertyEditor(entities, mode, property, {
- restoreFocus: () => restoreSoupFocus(entities[0]?.id),
+ restoreFocus: () => restoreFocus(entities[0]?.id),
});
}
};
@@ -184,7 +177,7 @@ export const useEntityActionHotkeys = (
if (entities.length === 0) return false;
if (!entities.every(markDone.canExecute)) return false;
- markDone.executeWithSoup(entities, soup, openNextEntity);
+ markDone.executeWithSoup(entities, list, openNextEntity);
return true;
},
condition: () => {
@@ -209,21 +202,12 @@ export const useEntityActionHotkeys = (
if (entities.length === 0) return false;
if (!entities.every(markNotDone.canExecute)) return false;
- markNotDone.executeWithSoup(entities, soup);
+ markNotDone.executeWithSoup(entities, list);
return true;
},
condition: () => {
if (condition && !condition()) return false;
-
- const contentId = splitHandle?.content().id;
-
- const soupViewTab = options.activeSoupViewTab?.();
-
- if (
- !isListViewID(contentId) ||
- (soupViewTab && !canExecuteMarkDoneOnView(contentId, soupViewTab))
- )
- return false;
+ if (!marksDoneOnThisView()) return false;
const entities = getEntitiesForAction();
return entities.length > 0 && entities.every(markNotDone.canExecute);
@@ -243,7 +227,7 @@ export const useEntityActionHotkeys = (
if (entities.length === 0) return false;
if (!entities.every(markUnread.canExecute)) return false;
- markUnread.executeWithSoup(entities, soup);
+ markUnread.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -266,7 +250,7 @@ export const useEntityActionHotkeys = (
if (entities.length === 0) return false;
if (!entities.some(markRead.canExecute)) return false;
- markRead.executeWithSoup(entities, soup);
+ markRead.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -296,7 +280,7 @@ export const useEntityActionHotkeys = (
if (entities.length === 0) return false;
if (!entities.every(deleteAction.canExecute)) return false;
- deleteAction.executeWithSoup(entities, soup);
+ deleteAction.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -338,13 +322,13 @@ export const useEntityActionHotkeys = (
if (entities.length === 0) return false;
if (editsReminder()) {
- editReminderAction.executeWithSoup(entities, soup);
+ editReminderAction.executeWithSoup(entities, list);
return true;
}
if (!entities.every(renameAction.canExecute)) return false;
- renameAction.executeWithSoup(entities, soup);
+ renameAction.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -374,7 +358,7 @@ export const useEntityActionHotkeys = (
if (entities.length === 0) return false;
if (!entities.every(favoriteAction.canExecute)) return false;
- favoriteAction.executeWithSoup(entities, soup);
+ favoriteAction.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -400,7 +384,7 @@ export const useEntityActionHotkeys = (
if (entities.length === 0) return false;
if (!entities.every(copyAction.canExecute)) return false;
- copyAction.executeWithSoup(entities, soup);
+ copyAction.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -426,7 +410,7 @@ export const useEntityActionHotkeys = (
if (entities.length === 0) return false;
if (!entities.every(moveToProjectAction.canExecute)) return false;
- moveToProjectAction.executeWithSoup(entities, soup);
+ moveToProjectAction.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -450,7 +434,7 @@ export const useEntityActionHotkeys = (
const entities = getEntitiesForAction();
if (entities.length === 0) return false;
if (!copyLinkAction.canExecute(entities[0])) return false;
- copyLinkAction.executeWithSoup(entities, soup);
+ copyLinkAction.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -472,7 +456,7 @@ export const useEntityActionHotkeys = (
const entities = getEntitiesForAction();
if (entities.length === 0) return false;
if (!copyBranchNameAction.canExecute(entities[0])) return false;
- copyBranchNameAction.executeWithSoup(entities, soup);
+ copyBranchNameAction.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -495,7 +479,7 @@ export const useEntityActionHotkeys = (
const entities = getEntitiesForAction();
if (entities.length === 0) return false;
if (!copyEntityIdAction.canExecute(entities[0])) return false;
- copyEntityIdAction.executeWithSoup(entities, soup);
+ copyEntityIdAction.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -522,7 +506,7 @@ export const useEntityActionHotkeys = (
const entities = getEntitiesForAction();
if (entities.length !== 1) return false;
if (!createReminderAction.canExecute(entities[0])) return false;
- createReminderAction.executeWithSoup(entities, soup, {
+ createReminderAction.executeWithSoup(entities, list, {
advances: marksDoneOnThisView(),
});
return true;
@@ -548,7 +532,7 @@ export const useEntityActionHotkeys = (
const entities = getEntitiesForAction();
if (entities.length === 0) return false;
if (!shareAction.canExecute(entities[0])) return false;
- shareAction.executeWithSoup(entities, soup);
+ shareAction.executeWithSoup(entities, list);
return true;
},
condition: () => {
@@ -593,7 +577,7 @@ export const useEntityActionHotkeys = (
const entities = getEntitiesForAction();
if (entities.length === 0) return false;
addTagAction.execute(entities, {
- restoreFocus: () => restoreSoupFocus(entities[0]?.id),
+ restoreFocus: () => restoreFocus(entities[0]?.id),
});
return true;
},
diff --git a/apps/web/src/features/next-soup/search-context.tsx b/apps/web/src/features/next-soup/search-context.tsx
index a28544ae42..e69b68b13a 100644
--- a/apps/web/src/features/next-soup/search-context.tsx
+++ b/apps/web/src/features/next-soup/search-context.tsx
@@ -1,44 +1,5 @@
-import { type EntityTypeItemMap, useQuickAccessEntities } from '@property';
-import { EntityType } from '@service-properties/generated/schemas/entityType';
-import {
- type Accessor,
- createContext,
- type FlowComponent,
- useContext,
-} from 'solid-js';
-
-const SEARCH_ENTITY_TYPES = [
- EntityType.CHANNEL,
- EntityType.CHAT,
- EntityType.DOCUMENT,
- EntityType.PROJECT,
- EntityType.TASK,
-] as const;
-
-type SearchEntityType = (typeof SEARCH_ENTITY_TYPES)[number];
-
-export type SearchPoolItem = EntityTypeItemMap[SearchEntityType];
-
-interface SearchContextValue {
- entityPool: Accessor<SearchPoolItem[]>;
-}
-
-const SearchContext = createContext<SearchContextValue>();
-
-export const useSearchContext = () => {
- const context = useContext(SearchContext);
- if (!context) {
- throw new Error('useSearchContext can only be used under a SearchProvider');
- }
- return context;
-};
-
-export const SearchProvider: FlowComponent = (props) => {
- const { items } = useQuickAccessEntities(() => [...SEARCH_ENTITY_TYPES]);
-
- return (
- <SearchContext.Provider value={{ entityPool: items }}>
- {props.children}
- </SearchContext.Provider>
- );
-};
+export {
+ SearchProvider,
+ type SoupSearchPoolItem as SearchPoolItem,
+ useSearchContext,
+} from '@app/features/soup/search/context';
diff --git a/apps/web/src/features/next-soup/search-utils.ts b/apps/web/src/features/next-soup/search-utils.ts
index df5e615e75..2bcd58bbbe 100644
--- a/apps/web/src/features/next-soup/search-utils.ts
+++ b/apps/web/src/features/next-soup/search-utils.ts
@@ -1,96 +1,5 @@
-import { createFreshSearch } from '@core/util/freshSort';
-import { fuzzyMatch } from '@core/util/fuzzy';
-import { mergeAdjacentMacroEmTags } from '@core/util/searchHighlight';
-import type { EntityData, WithSearch } from '@entity';
-import type { PredicateConfig } from './filters/filter-store/predicates-store';
-import type { SearchPoolItem } from './search-context';
-
-const _getValidSearchFilters = <T>(filters: readonly PredicateConfig<T>[]) => {
- return filters.filter((f) => f.id !== 'explicit-noise');
-};
-
-/** Takes a list of entity pools and returns a list of unique entities that are present in all pools, deduplicating by id */
-export function intersectEntityPools(
- pools: readonly EntityData[][]
-): EntityData[] {
- if (pools.length === 0) return [];
- if (pools.length === 1) return pools[0];
-
- const idCounts = new Map<string, number>();
- const entityById = new Map<string, EntityData>();
-
- for (const pool of pools) {
- const seen = new Set<string>();
- for (const entity of pool) {
- if (!seen.has(entity.id)) {
- seen.add(entity.id);
- idCounts.set(entity.id, (idCounts.get(entity.id) ?? 0) + 1);
- if (!entityById.has(entity.id)) {
- entityById.set(entity.id, entity);
- }
- }
- }
- }
-
- const result: EntityData[] = [];
- for (const [id, count] of idCounts) {
- if (count === pools.length) {
- result.push(entityById.get(id)!);
- }
- }
-
- return result;
-}
-
-/** Adds name highlight to item list based on fuzzy match */
-export const nameFuzzySearchFilter = (
- items: EntityData[],
- query: string
-): EntityData[] | WithSearch<EntityData>[] => {
- if (!query || query.length === 0) return items;
-
- const matchResults = fuzzyMatch(query, items, (item) => item.name, {
- noSort: true,
- });
-
- const resultMap = new Map(
- matchResults.map((r) => [
- r.item.id,
- { nameHighlight: r.nameHighlight, score: r.score },
- ])
- );
- return items
- .filter((item) => resultMap.has(item.id))
- .map((item) => {
- const matchResult = resultMap.get(item.id)!;
- return {
- ...item,
- search: {
- nameHighlight: mergeAdjacentMacroEmTags(matchResult.nameHighlight),
- senderHighlightTerms: null,
- contentHitData: null,
- source: 'local',
- },
- } as WithSearch<EntityData>;
- });
-};
-
-export const createSoupFreshSearch = () =>
- createFreshSearch<SearchPoolItem>({
- config: {
- useViewedAt: true,
- channelBoost: 3,
- dmBoost: 1.5,
- fuzzyWeight: 0.7,
- timeWeight: 0.3,
- minFuzzyThreshold: 0.1,
- commaSeparatedChannelMatch: true,
- },
- getName: (item) => item.data.name,
- isChannelItem: (item) => item.data.type === 'channel',
- isDmItem: (item) => item.bucket === 'dm',
- getTimestamp: (item) => ({
- viewedAt: item.data.viewedAt,
- updatedAt: item.data.updatedAt,
- }),
- });
+export {
+ createSoupFreshSearch,
+ intersectEntityPools,
+ nameFuzzySearchFilter,
+} from '@app/features/soup/search/utils';
diff --git a/apps/web/src/features/next-soup/soup-view/SoupEntityActionDrawerManager.tsx b/apps/web/src/features/next-soup/soup-view/SoupEntityActionDrawerManager.tsx
deleted file mode 100644
index 4e9608cf3b..0000000000
--- a/apps/web/src/features/next-soup/soup-view/SoupEntityActionDrawerManager.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { isMobile } from '@core/mobile/isMobile';
-import type { EntityData } from '@entity';
-import { createEffect, createSignal, type JSX, onCleanup } from 'solid-js';
-import type { SoupState } from '../create-soup-state';
-import { SoupEntityActionDrawer } from './SoupEntityActionDrawer';
-import {
- SoupEntityActionDrawerContextProvider,
- type SoupEntityActionDrawerState,
-} from './soup-entity-action-drawer-context';
-
-/**
- * On mobile: provides drawer context and renders the SoupEntityActionDrawer
- * (opened via long-press on soup entity rows).
- * On desktop: renders children as-is with no context, signals, or drawer.
- */
-export function MaybeSoupEntityActionDrawerManager(props: {
- children: JSX.Element;
-}) {
- if (!isMobile()) return props.children;
-
- const [isOpen, setIsOpen] = createSignal(false);
- const [entity, setEntity] = createSignal<EntityData | undefined>();
- const [soup, setSoup] = createSignal<SoupState | undefined>();
-
- const ctx: SoupEntityActionDrawerState = {
- isOpen,
- entity,
- soup,
- open: (e: EntityData, s: SoupState) => {
- setEntity(() => e);
- setSoup(() => s);
- setIsOpen(true);
- },
- close: () => setIsOpen(false),
- };
-
- let wrapperEl!: HTMLDivElement;
-
- // Block in-progress touch sequences (scroll, swipe) the moment the drawer opens.
- createEffect(() => {
- if (!isOpen()) return;
- const block = (e: TouchEvent) => {
- e.preventDefault();
- e.stopPropagation();
- };
- wrapperEl.addEventListener('touchmove', block, {
- capture: true,
- passive: false,
- });
- onCleanup(() =>
- wrapperEl.removeEventListener('touchmove', block, { capture: true })
- );
- });
-
- return (
- <SoupEntityActionDrawerContextProvider value={ctx}>
- <div class="size-full" ref={wrapperEl}>
- {props.children}
- </div>
- <SoupEntityActionDrawer />
- </SoupEntityActionDrawerContextProvider>
- );
-}
diff --git a/apps/web/src/features/next-soup/soup-view/create-search-state.ts b/apps/web/src/features/next-soup/soup-view/create-search-state.ts
index 322b75a39a..60338ea71e 100644
--- a/apps/web/src/features/next-soup/soup-view/create-search-state.ts
+++ b/apps/web/src/features/next-soup/soup-view/create-search-state.ts
@@ -4,39 +4,20 @@ import {
NIL_UUID,
type QueryState,
} from '@app/features/next-soup/filters/filter-store';
-import { useSearchContext } from '@app/features/next-soup/search-context';
import {
- createSoupFreshSearch,
+ createSearchState as createSharedSearchState,
intersectEntityPools,
- nameFuzzySearchFilter,
-} from '@app/features/next-soup/search-utils';
+ type SoupSearchRequest,
+ useSearchContext,
+} from '@app/features/soup/search';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { useUserId } from '@core/context/user';
-import { arrayEquals } from '@core/util/compareUtils';
-import { debouncedDependent } from '@core/util/debounce';
-import { type EntityData, isChannelEntity } from '@entity';
-import {
- useSearchSoupQuery,
- validateSearchServiceText,
-} from '@queries/soup/search';
import type {
EntityFilters,
PropertyFilter,
UnifiedSearchRequest,
} from '@service-search/generated/models';
-import { type Accessor, createMemo, on, type Setter } from 'solid-js';
-
-// A fully-quoted term searches exactly, not as a prefix. Quotes stay in the
-// query so the backend tokenizer still groups a quoted phrase.
-function isSingleQuotedTerm(query: string): boolean {
- const trimmed = query.trim();
- return (
- trimmed.length >= 2 &&
- trimmed.startsWith('"') &&
- trimmed.endsWith('"') &&
- trimmed.indexOf('"', 1) === trimmed.length - 1
- );
-}
+import { type Accessor, createMemo, type Setter } from 'solid-js';
// Map the tasks-view property filters (status/priority/assignee/custom) into the
// search request shape, mirroring the soup path so search and soup agree. Values
@@ -209,14 +190,6 @@ function filterDataToQueryFilters(data: QueryState): EntityFilters {
return filters;
}
-const SEARCH_SERVICE_DEBOUNCE_MS = 300;
-const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 20;
-// Max number of non-channel local results to feature. Channels bypass this
-// limit since they are only searched locally, not via the backend search service.
-const FEATURED_COUNT = 3;
-
-const freshSearch = createSoupFreshSearch();
-
interface CreateSearchStateArgs {
soup: SoupState;
filters: Accessor<QueryState>;
@@ -249,180 +222,95 @@ export const createSearchState = ({
assignees: assignees(),
});
- const trimmedSearchText = createMemo(() => searchText().trim());
-
- const debouncedSearchForLocal = debouncedDependent(
- trimmedSearchText,
- LOCAL_FUZZY_SEARCH_DEBOUNCE_MS
- );
-
- const debouncedSearchForService = debouncedDependent(
- trimmedSearchText,
- SEARCH_SERVICE_DEBOUNCE_MS
- );
-
- const isSearching = createMemo(() => trimmedSearchText().length > 0);
-
- const isSearchServiceDebounceSettled = createMemo(
- () => trimmedSearchText() === debouncedSearchForService()
- );
-
- const isSearchServiceDisabled = createMemo(
- () => !validateSearchServiceText(debouncedSearchForService())
- );
-
- const searchUnifiedNameContentRequest = createMemo(
- (): UnifiedSearchRequest => {
- const state = filters();
- const query = debouncedSearchForService();
- const baseFilters = filterDataToQueryFilters(state);
- const matchType = isSingleQuotedTerm(query) ? 'exact' : 'partial';
+ const { entityPool } = useSearchContext();
+ const localPool = createMemo(() => {
+ const pool = entityPool();
+ const activeIds = soup.predicates
+ .activeIds()
+ .filter((id) => id !== 'explicit-noise');
+ if (activeIds.length === 0) return pool;
+
+ const context = getFilterContext();
+ const entities = pool.map((item) => item.data);
+ const matches = intersectEntityPools(
+ activeIds.map((id) => {
+ const predicate = soup.predicates.available.find(
+ (candidate) => candidate.id === id
+ );
+ if (!predicate) return [];
+ return entities.filter((entity) =>
+ predicate.predicate(entity, context)
+ );
+ })
+ );
+ const matchingIds = new Set(matches.map((entity) => entity.id));
+ return pool.filter((item) => matchingIds.has(item.data.id));
+ });
- // CRM is opt-in on the backend. A view includes CRM in search unless it
- // NIL-excludes the CRM target (the same sentinel pattern other entity
- // types use) — so the Companies view (CRM-scoped) searches CRM, while
- // every other view (including the global Search view) excludes it.
- const includeCrm = !(state.include.crmCompanyId ?? []).includes(NIL_UUID);
+ // We hide local results for channel-filtered searches because those views
+ // should show message hits from the search service rather than channel rows.
+ const hideLocalResults = () => {
+ const include = filters().include;
+ return (
+ (include.channelId?.length ?? 0) > 0 ||
+ (include.channelSenderId?.length ?? 0) > 0
+ );
+ };
- if (!includeCrm) {
- return {
+ const buildRequest = ({
+ query,
+ matchType,
+ }: SoupSearchRequest): {
+ params: { page_size: number };
+ body: UnifiedSearchRequest;
+ } => {
+ const state = filters();
+ const baseFilters = filterDataToQueryFilters(state);
+
+ // CRM is opt-in on the backend. A view includes CRM in search unless it
+ // NIL-excludes the CRM target (the same sentinel pattern other entity
+ // types use) — so the Companies view (CRM-scoped) searches CRM, while
+ // every other view (including the global Search view) excludes it.
+ const includeCrm = !(state.include.crmCompanyId ?? []).includes(NIL_UUID);
+ const body: UnifiedSearchRequest = includeCrm
+ ? {
+ search_on: 'name_content',
+ match_type: matchType,
+ query,
+ include_crm: true,
+ filters: {
+ ...baseFilters,
+ crm_company_filters: { hidden: state.include.crmCompanyHidden },
+ },
+ }
+ : {
search_on: 'name_content',
match_type: matchType,
query,
filters: baseFilters,
};
- }
-
- // CRM is opt-in on the backend. Search surfaces visible companies
- // everywhere except the admin Companies → Hidden tab, which sets
- // `crmCompanyHidden: true` to search the hidden set. Elsewhere
- // (Companies → Active) `crmCompanyHidden` is false/undefined →
- // visible only. Non-CRM targets are already NIL-excluded by the
- // Companies preset.
- return {
- search_on: 'name_content',
- match_type: matchType,
- query,
- include_crm: true,
- filters: {
- ...baseFilters,
- crm_company_filters: { hidden: state.include.crmCompanyHidden },
- },
- };
- }
- );
-
- const searchQuery = useSearchSoupQuery(
- () => ({
- params: {
- page_size: 100,
- },
- body: {
- ...searchUnifiedNameContentRequest(),
- },
- }),
- () => ({
- enabled:
- !isSearchServiceDisabled() &&
- isSearchServiceDebounceSettled() &&
- !searchPaused?.(),
- })
- );
-
- const { entityPool } = useSearchContext();
-
- const localFuzzyResults = createMemo(
- on(debouncedSearchForLocal, (query) => {
- if (disableLocalSearch?.()) return [];
- if (!query || query.length === 0) return [];
- const pool = entityPool();
- // TODO: we can optimize fresh search for small feature counts since we
- // don't need to sort everything, we just need the featured results
- const freshSearchResults = freshSearch(pool, query);
- // NOTE: this is a temporary hack because the fresh search fuzzy library
- // does not give us the highlighted matches
- const results = nameFuzzySearchFilter(
- freshSearchResults.map((r) => r.item.data),
- query
- );
- return results;
- })
- );
-
- const allFiltersResults = createMemo((): Map<string, EntityData[]> => {
- if (!localFuzzyResults()) return new Map();
- const filterToResultMap = new Map<string, EntityData[]>();
- const ctx = getFilterContext();
- for (const filter of soup.predicates.available) {
- filterToResultMap.set(
- filter.id,
- localFuzzyResults().filter((e) => filter.predicate(e, ctx))
- );
- }
- return filterToResultMap;
- });
- // we will hide local results if there are channel filters because we only want message results
- const hasChannelQueryFilters = () => {
- const filters_ = filters().include;
- const channelIds = filters_.channelId ?? [];
- const senderIds = filters_.channelSenderId ?? [];
- return channelIds.length > 0 || senderIds.length > 0;
+ return { params: { page_size: 100 }, body };
};
- const filteredLocalFuzzyResults = createMemo(() => {
- if (!localFuzzyResults()) return [];
- if (hasChannelQueryFilters()) return [];
- const activeIds = soup.predicates
- .activeIds()
- .filter((id) => id !== 'explicit-noise');
- const results =
- activeIds.length === 0
- ? localFuzzyResults()
- : intersectEntityPools(
- activeIds.map((id) => allFiltersResults().get(id) ?? [])
- );
- const channels = results.filter((e) => isChannelEntity(e));
- const nonChannels = results
- .filter((e) => !isChannelEntity(e))
- .slice(0, FEATURED_COUNT);
- return [...channels, ...nonChannels];
- });
-
- const serviceSearchResults = createMemo<EntityData[]>(() => {
- if (isSearchServiceDisabled()) return [];
- if (!isSearchServiceDebounceSettled()) return [];
- if (searchQuery.isFetching && !searchQuery.isFetchingNextPage) return [];
- return searchQuery.data ?? [];
- });
-
- const featuredIds = createMemo<string[]>(
- () => filteredLocalFuzzyResults().map((r) => r.id),
- [],
- { equals: arrayEquals }
- );
-
- const isLocalSearchSettling = createMemo(
- () => isSearching() && trimmedSearchText() !== debouncedSearchForLocal()
- );
-
- const isSearchServiceLoading = createMemo(() => {
- if (!isSearching()) return false;
- if (!validateSearchServiceText(trimmedSearchText())) return false;
- if (!isSearchServiceDebounceSettled()) return true;
- if (searchQuery.isFetching && !searchQuery.isFetchingNextPage) return true;
- return false;
+ const search = createSharedSearchState({
+ text: searchText,
+ buildRequest,
+ localPool,
+ disableLocalSearch,
+ hideLocalResults,
+ searchPaused,
});
return {
searchText,
setSearchText,
- isSearching,
- localFuzzyResults: filteredLocalFuzzyResults,
- serviceSearchResults,
- featuredIds,
- searchQuery,
- isSearchServiceLoading,
- isLocalSearchSettling,
+ isSearching: search.isSearching,
+ localFuzzyResults: search.localFuzzyResults,
+ serviceSearchResults: search.serviceSearchResults,
+ featuredIds: search.featuredIds,
+ searchQuery: search.searchQuery,
+ isSearchServiceLoading: search.isSearchServiceLoading,
+ isLocalSearchSettling: search.isLocalSearchSettling,
};
};
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsx
index 1c0f578c55..9d0fd06596 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx
@@ -3,9 +3,9 @@ import { isListViewID, type ListView } from '@app/constants/list-views';
import { SoupChatInput } from '@app/features/chat/SoupChatInput';
import {
makeMarkDoneAction,
+ resolveEntityActionViewContext,
useEntityActionHotkeys,
} from '@app/features/next-soup/actions';
-import { canExecuteMarkDoneOnView } from '@app/features/next-soup/actions/make-mark-done-action';
import type {
GroupHeaderProps,
SoupRow,
@@ -25,9 +25,7 @@ import { InboxSelector } from '@app/features/next-soup/soup-view/filters-bar/inb
import { SoupFiltersBar } from '@app/features/next-soup/soup-view/filters-bar/soup-filters-bar';
import { SoupSearchbar } from '@app/features/next-soup/soup-view/filters-bar/soup-view-search-bar';
import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';
-import { MaybeSoupEntityActionDrawerManager } from '@app/features/next-soup/soup-view/SoupEntityActionDrawerManager';
import { SoupSectionHeader } from '@app/features/next-soup/soup-view/section-header';
-import { SoupEntityContextMenu } from '@app/features/next-soup/soup-view/soup-entity-context-menu';
import {
persistSoupNavigationTouchHighlight,
soupNavigationTouchHighlight,
@@ -57,7 +55,12 @@ import {
openEntityInNewTab,
openEntityInSplitFromUnifiedList,
preventDuplicatePreviewEntityOpen,
+ restoreSoupFocus,
} from '@app/features/next-soup/utils';
+import {
+ MaybeSoupEntityActionDrawerManager,
+ SoupEntityContextMenu,
+} from '@app/features/soup';
import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';
import { usePreference } from '@app/preferences/use-preference';
import { useDealStages } from '@companies/crm/deal-stages';
@@ -742,7 +745,14 @@ export const SoupView = (props: SoupViewProps) => {
</Show>
<div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full">
<Suspense>
- <Show when={!isBoardMode()} fallback={<CompanyKanban />}>
+ <Show
+ when={!isBoardMode()}
+ fallback={
+ <MaybeSoupEntityActionDrawerManager>
+ <CompanyKanban />
+ </MaybeSoupEntityActionDrawerManager>
+ }
+ >
<SoupViewList />
</Show>
</Suspense>
@@ -907,6 +917,11 @@ const SoupViewListContent = (props: SoupViewListProps) => {
const [attachHotkeys, soupViewScope] = useHotkeyDOMScope('soup-view');
const scopeId = createMemo(() => props.scopeId ?? panel.splitHotkeyScope);
+ const entityActionViewContext = () =>
+ resolveEntityActionViewContext({
+ activeListView: panel.handle.content().id,
+ activeTab: activeTab(),
+ });
// Register navigation hotkeys on the active list scope (usually the split
// scope). Most handlers are disposed with SoupViewList, but j/k intentionally
@@ -926,8 +941,11 @@ const SoupViewListContent = (props: SoupViewListProps) => {
// Register entity action hotkeys
useEntityActionHotkeys({
scopeId: scopeId(),
- soup,
- activeSoupViewTab: activeTab,
+ list: soup,
+ selectedEntities: soup.selection.selected,
+ focusedEntity: soup.focus.item,
+ restoreFocus: restoreSoupFocus,
+ viewContext: entityActionViewContext,
splitHandle: panel.handle,
});
@@ -1198,7 +1216,6 @@ const SoupViewListContent = (props: SoupViewListProps) => {
);
const isProjectList = panel.handle.content().type === 'project';
- const contentId = panel.handle.content().id;
const readListEntryState = () =>
panel.handle.currentEntryState()?.[SOUP_LIST_STATE_ENTRY_KEY] as
@@ -1374,13 +1391,9 @@ const SoupViewListContent = (props: SoupViewListProps) => {
const entity = entityById().get(entityId);
if (!entity) return false;
- const tab = activeTab();
-
- if (
- !isListViewID(contentId) ||
- (tab && !canExecuteMarkDoneOnView(contentId, tab))
- )
+ if (!entityActionViewContext().supportsMarkDone) {
return false;
+ }
return markDoneAction.canExecute(entity.original);
}}
@@ -1524,7 +1537,12 @@ const SoupViewListContent = (props: SoupViewListProps) => {
<Match
when={!row.group || row.group?.isExpanded()}
>
- <SoupEntityContextMenu entity={row.original}>
+ <SoupEntityContextMenu
+ entity={row.original}
+ list={soup}
+ selectedEntities={soup.selection.selected}
+ viewContext={entityActionViewContext()}
+ >
<Dynamic
component={rowEntry().component}
entity={row.original}
diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx
index ad8505e2af..5c8ae0131d 100644
--- a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx
+++ b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx
@@ -1,12 +1,13 @@
+import { resolveEntityActionViewContext } from '@app/features/next-soup/actions';
import { NO_STAGE } from '@app/features/next-soup/filters/configs/';
import { EmptyState } from '@app/features/next-soup/soup-view/empty-states';
import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';
-import { SoupEntityContextMenu } from '@app/features/next-soup/soup-view/soup-entity-context-menu';
import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';
import {
openEntityInSplitFromUnifiedList,
preventDuplicatePreviewEntityOpen,
} from '@app/features/next-soup/utils';
+import { SoupEntityContextMenu } from '@app/features/soup';
import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';
import { useDealStages } from '@companies/crm/deal-stages';
import { CrmStageIcon } from '@companies/crm/StageIcon';
@@ -59,8 +60,13 @@ type StageColumn = {
*
*/
export function CompanyKanban() {
- const { source, soup, stageFilter, searchText } = useSoupView();
+ const { source, soup, stageFilter, searchText, activeTab } = useSoupView();
const panel = useSplitPanelOrThrow();
+ const entityActionViewContext = () =>
+ resolveEntityActionViewContext({
+ activeListView: panel.handle.content().id,
+ activeTab: activeTab(),
+ });
// Stage moves made while the board is fed by search results. Search rows
// bypass the normalized soup cache, so the mutation's optimistic update
@@ -353,7 +359,12 @@ export function CompanyKanban() {
// rows); an auto-height wrapper resolves that to the
// card's content height instead of the column's.
<div class="shrink-0">
- <SoupEntityContextMenu entity={entity}>
+ <SoupEntityContextMenu
+ entity={entity}
+ list={soup}
+ selectedEntities={soup.selection.selected}
+ viewContext={entityActionViewContext()}
+ >
<CompanyKanbanCard
entity={entity}
draggable={canDragFrom(column.key)}
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index 23f9aad606..eaa775da15 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -532,6 +532,22 @@ export async function navigateChannelEntityToTarget(
);
}
+/** Retargets the singleton Calendar block to a calendar event row. */
+export async function navigateCalendarEntityToTarget(
+ entity: EntityData,
+ blockOrchestrator: BlockOrchestrator
+): Promise<void> {
+ if (entity.type !== 'calendar_event') return;
+
+ const calendarHandle = await blockOrchestrator.getBlockHandle(
+ CALENDAR_BLOCK_ID,
+ 'calendar'
+ );
+ await calendarHandle?.goToLocationFromParams(
+ calendarBlockParamsForEntity(entity)
+ );
+}
+
/**
* Location a plain row click falls back to when no explicit location is given.
* Email rows open like plain soup rows — at the latest message, expanded —
@@ -649,11 +665,7 @@ export const openEntityInSplitFromUnifiedList = async (
}
);
}
- const calendarHandle = await blockOrchestrator.getBlockHandle(
- CALENDAR_BLOCK_ID,
- 'calendar'
- );
- await calendarHandle?.goToLocationFromParams(params);
+ await navigateCalendarEntityToTarget(entity, blockOrchestrator);
return;
}
@@ -800,7 +812,6 @@ export function markReminderSeenOnOpen(
});
}
-/** Build the singleton block params for an event row's target occurrence. */
/**
* The event and instance a calendar row points at, resolved exactly as the
* open path resolves it so a copied link lands where a click would.
@@ -812,7 +823,8 @@ export function calendarEventLinkTarget(
return { eventId: eventId ?? entity.id, occurrenceKey };
}
-function calendarBlockParamsForEntity(
+/** Build singleton calendar block parameters for an event row's occurrence. */
+export function calendarBlockParamsForEntity(
entity: Extract<EntityData, { type: 'calendar_event' }>
): CalendarBlockProps {
const notifications = isWithNotification(entity)
diff --git a/apps/web/src/features/next-soup/soup-view/SoupEntityActionDrawer.tsx b/apps/web/src/features/soup/SoupEntityActionDrawer.tsx
similarity index 52%
rename from apps/web/src/features/next-soup/soup-view/SoupEntityActionDrawer.tsx
rename to apps/web/src/features/soup/SoupEntityActionDrawer.tsx
index d218eeaf0e..4999ef6fe6 100644
--- a/apps/web/src/features/next-soup/soup-view/SoupEntityActionDrawer.tsx
+++ b/apps/web/src/features/soup/SoupEntityActionDrawer.tsx
@@ -1,49 +1,39 @@
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
-import { getShareDrawerRecipientInput } from '@core/component/TopBar/ShareButton';
-import { triggerFocusInput } from '@core/directive/focusInput';
-import { InlineEntity } from '@entity';
+import { type EntityData, InlineEntity } from '@entity';
import { cn } from '@ui';
import { For, Show } from 'solid-js';
-import {
- createSoupEntityActions,
- viewedProjectIdFromContent,
-} from './create-soup-entity-actions';
-import { useSoupEntityActionDrawer } from './soup-entity-action-drawer-context';
-import { useSoupView } from './soup-view-context';
-export function SoupEntityActionDrawer() {
- const panel = useSplitPanelOrThrow();
- const drawerState = useSoupEntityActionDrawer();
- const { activeTab } = useSoupView();
- const { buildActionGroups } = createSoupEntityActions();
+export type SoupEntityDrawerAction = {
+ id: string;
+ label: string;
+ destructive?: boolean;
+ disabled?: boolean;
+ onClick: () => void | Promise<void>;
+};
- if (!drawerState) {
- console.warn('SoupEntityActionDrawer: no drawer state');
- return null;
- }
+export type SoupEntityDrawerActionGroup = {
+ items: readonly SoupEntityDrawerAction[];
+};
- const groups = () => {
- const e = drawerState.entity();
- const s = drawerState.soup();
- if (!e || !s) return [];
- const content = panel.handle.content();
- return buildActionGroups(s, [e], {
- activeTab: activeTab(),
- activeListView: content.id,
- viewedProjectId: viewedProjectIdFromContent(content),
- splitHandle: panel.handle,
- });
- };
+type SoupEntityActionDrawerProps = {
+ entity: EntityData | undefined;
+ groups: readonly SoupEntityDrawerActionGroup[];
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ beforeAction?: (
+ action: SoupEntityDrawerAction,
+ trigger: HTMLButtonElement
+ ) => void;
+};
+/** Mobile drawer presentation shared by Soup-backed entity lists. */
+export function SoupEntityActionDrawer(props: SoupEntityActionDrawerProps) {
return (
<MobileDrawer
side="bottom"
- open={drawerState.isOpen()}
+ open={props.open}
closeOnOutsidePointerStrategy="pointerdown"
- onOpenChange={(v) => {
- if (!v) drawerState.close();
- }}
+ onOpenChange={props.onOpenChange}
preventScroll={false}
preventScrollbarShift={false}
restoreFocus={false}
@@ -54,18 +44,16 @@ export function SoupEntityActionDrawer() {
<MobileDrawer.Content aria-label="Entity actions">
<MobileDrawer.Handle />
- {/* Entity preview */}
- <Show when={drawerState.entity()}>
- {(e) => (
+ <Show when={props.entity}>
+ {(entity) => (
<div class="px-4 pb-4 shrink-0 text-sm font-medium text-ink-muted">
- <InlineEntity entity={e()} />
+ <InlineEntity entity={entity()} />
</div>
)}
</Show>
- {/* Action groups */}
<MobileDrawer.ScrollBody>
- <For each={groups()}>
+ <For each={props.groups}>
{(group, groupIndex) => (
<>
<Show when={groupIndex() > 0}>
@@ -84,15 +72,10 @@ export function SoupEntityActionDrawer() {
: 'text-ink',
action.disabled && 'opacity-50'
)}
- onClick={async (e: MouseEvent) => {
- if (action.id === 'share') {
- triggerFocusInput(
- getShareDrawerRecipientInput,
- e.currentTarget as HTMLElement
- );
- }
+ onClick={async (event) => {
+ props.beforeAction?.(action, event.currentTarget);
await action.onClick();
- drawerState.close();
+ props.onOpenChange(false);
}}
>
{action.label}
diff --git a/apps/web/src/features/next-soup/soup-view/soup-entity-action-drawer-context.ts b/apps/web/src/features/soup/SoupEntityActionDrawerContext.ts
similarity index 60%
rename from apps/web/src/features/next-soup/soup-view/soup-entity-action-drawer-context.ts
rename to apps/web/src/features/soup/SoupEntityActionDrawerContext.ts
index d8d8f08e18..802e6a338d 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-entity-action-drawer-context.ts
+++ b/apps/web/src/features/soup/SoupEntityActionDrawerContext.ts
@@ -1,12 +1,20 @@
+import type {
+ EntityActionListState,
+ EntityActionViewContext,
+} from '@app/features/next-soup/actions';
import type { EntityData } from '@entity';
import { type Accessor, createContext, useContext } from 'solid-js';
-import type { SoupState } from '../create-soup-state';
+
+export type EntityActionDrawerEntry = {
+ entity: EntityData;
+ list: EntityActionListState;
+ viewContext: EntityActionViewContext;
+};
export type SoupEntityActionDrawerState = {
isOpen: Accessor<boolean>;
- entity: Accessor<EntityData | undefined>;
- soup: Accessor<SoupState | undefined>;
- open: (entity: EntityData, soup: SoupState) => void;
+ entry: Accessor<EntityActionDrawerEntry | undefined>;
+ open: (entry: EntityActionDrawerEntry) => void;
close: () => void;
};
diff --git a/apps/web/src/features/soup/SoupEntityActionDrawerManager.tsx b/apps/web/src/features/soup/SoupEntityActionDrawerManager.tsx
new file mode 100644
index 0000000000..c9dbf8988e
--- /dev/null
+++ b/apps/web/src/features/soup/SoupEntityActionDrawerManager.tsx
@@ -0,0 +1,103 @@
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { getShareDrawerRecipientInput } from '@core/component/TopBar/ShareButton';
+import { triggerFocusInput } from '@core/directive/focusInput';
+import { isMobile } from '@core/mobile/isMobile';
+import { createEffect, createSignal, type JSX, onCleanup } from 'solid-js';
+import {
+ createSoupEntityActions,
+ viewedProjectIdFromContent,
+} from './createSoupEntityActions';
+import { SoupEntityActionDrawer } from './SoupEntityActionDrawer';
+import {
+ type EntityActionDrawerEntry,
+ SoupEntityActionDrawerContextProvider,
+ type SoupEntityActionDrawerState,
+ useSoupEntityActionDrawer,
+} from './SoupEntityActionDrawerContext';
+
+function ConfiguredSoupEntityActionDrawer() {
+ const panel = useSplitPanelOrThrow();
+ const drawerState = useSoupEntityActionDrawer();
+ const { buildActionGroups } = createSoupEntityActions();
+
+ if (!drawerState) {
+ console.warn('SoupEntityActionDrawer: no drawer state');
+ return null;
+ }
+
+ const groups = () => {
+ const entry = drawerState.entry();
+ if (!entry) return [];
+
+ const content = panel.handle.content();
+ return buildActionGroups(entry.list, [entry.entity], {
+ viewContext: entry.viewContext,
+ viewedProjectId: viewedProjectIdFromContent(content),
+ splitHandle: panel.handle,
+ });
+ };
+
+ return (
+ <SoupEntityActionDrawer
+ entity={drawerState.entry()?.entity}
+ groups={groups()}
+ open={drawerState.isOpen()}
+ onOpenChange={(open) => {
+ if (!open) drawerState.close();
+ }}
+ beforeAction={(action, trigger) => {
+ if (action.id !== 'share') return;
+
+ triggerFocusInput(getShareDrawerRecipientInput, trigger);
+ }}
+ />
+ );
+}
+
+export function MaybeSoupEntityActionDrawerManager(props: {
+ children: JSX.Element;
+}) {
+ if (!isMobile()) return props.children;
+
+ const [isOpen, setIsOpen] = createSignal(false);
+ const [entry, setEntry] = createSignal<EntityActionDrawerEntry>();
+
+ const ctx: SoupEntityActionDrawerState = {
+ isOpen,
+ entry,
+ open: (nextEntry) => {
+ setEntry(() => nextEntry);
+ setIsOpen(true);
+ },
+ close: () => setIsOpen(false),
+ };
+
+ let wrapperEl!: HTMLDivElement;
+
+ createEffect(() => {
+ if (!isOpen()) return;
+ const block = (e: TouchEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ };
+ wrapperEl.addEventListener('touchmove', block, {
+ capture: true,
+ passive: false,
+ });
+ onCleanup(() =>
+ wrapperEl.removeEventListener('touchmove', block, { capture: true })
+ );
+ });
+
+ return (
+ <SoupEntityActionDrawerContextProvider value={ctx}>
+ <div
+ class="flex size-full min-h-0 min-w-0 flex-1 flex-col"
+ ref={wrapperEl}
+ >
+ {props.children}
+ </div>
+ <ConfiguredSoupEntityActionDrawer />
+ </SoupEntityActionDrawerContextProvider>
+ );
+}
diff --git a/apps/web/src/features/next-soup/soup-view/soup-entity-actions-menu.tsx b/apps/web/src/features/soup/SoupEntityActionsMenu.tsx
similarity index 83%
rename from apps/web/src/features/next-soup/soup-view/soup-entity-actions-menu.tsx
rename to apps/web/src/features/soup/SoupEntityActionsMenu.tsx
index 834f560739..48fb0445b2 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-entity-actions-menu.tsx
+++ b/apps/web/src/features/soup/SoupEntityActionsMenu.tsx
@@ -1,31 +1,32 @@
+import type {
+ EntityActionListState,
+ EntityActionViewContext,
+} from '@app/features/next-soup/actions';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { MenuItem, MenuSeparator } from '@core/component/ContextMenu';
import type { EntityData } from '@entity';
import { For, Show } from 'solid-js';
-import type { SoupState } from '../create-soup-state';
import {
createSoupEntityActions,
viewedProjectIdFromContent,
-} from './create-soup-entity-actions';
-import { useSoupView } from './soup-view-context';
+} from './createSoupEntityActions';
interface SoupEntityActionsMenuProps {
entities: EntityData[];
- soup: SoupState;
+ list: EntityActionListState;
+ viewContext: EntityActionViewContext;
onActionComplete?: () => void;
onEditTags?: () => void;
}
export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {
const panel = useSplitPanelOrThrow();
- const { activeTab } = useSoupView();
const { buildActionGroups } = createSoupEntityActions();
const groups = () => {
const content = panel.handle.content();
- return buildActionGroups(props.soup, props.entities, {
- activeTab: activeTab(),
- activeListView: content.id,
+ return buildActionGroups(props.list, props.entities, {
+ viewContext: props.viewContext,
viewedProjectId: viewedProjectIdFromContent(content),
openTagPicker: props.onEditTags,
splitHandle: panel.handle,
diff --git a/apps/web/src/features/next-soup/soup-view/soup-entity-context-menu.tsx b/apps/web/src/features/soup/SoupEntityContextMenu.tsx
similarity index 75%
rename from apps/web/src/features/next-soup/soup-view/soup-entity-context-menu.tsx
rename to apps/web/src/features/soup/SoupEntityContextMenu.tsx
index ec452d5bdb..25abd47182 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-entity-context-menu.tsx
+++ b/apps/web/src/features/soup/SoupEntityContextMenu.tsx
@@ -1,3 +1,8 @@
+import {
+ type EntityActionListState,
+ type EntityActionViewContext,
+ makeAddTagAction,
+} from '@app/features/next-soup/actions';
import { ContextMenuContent } from '@core/component/ContextMenu';
import { touchHandler } from '@core/directive/touchHandler';
import { isMobile } from '@core/mobile/isMobile';
@@ -18,18 +23,17 @@ import {
Show,
Switch,
} from 'solid-js';
-import { makeAddTagAction } from '../actions';
-import { useSoupEntityActionDrawer } from './soup-entity-action-drawer-context';
-import { SoupEntityActionsMenu } from './soup-entity-actions-menu';
-import { useSoupView } from './soup-view-context';
+import { useSoupEntityActionDrawer } from './SoupEntityActionDrawerContext';
+import { SoupEntityActionsMenu } from './SoupEntityActionsMenu';
interface SoupEntityContextMenuProps {
entity: EntityData;
+ list: EntityActionListState;
+ selectedEntities: Accessor<EntityData[]>;
+ viewContext: EntityActionViewContext;
onOpenChange?: (open: boolean) => void;
}
-// Detached tag picker anchored at the position the context menu opened from.
-// Mounted only while open, so picker state resets on every invocation.
function RowTagPicker(props: {
entityId: string;
entityType: EntityType;
@@ -58,7 +62,6 @@ function RowTagPicker(props: {
export const SoupEntityContextMenu: FlowComponent<
SoupEntityContextMenuProps
> = (props) => {
- const { soup } = useSoupView();
const drawerManager = useSoupEntityActionDrawer();
const addTagAction = makeAddTagAction();
@@ -68,11 +71,12 @@ export const SoupEntityContextMenu: FlowComponent<
y: number;
}>();
- // If the right-clicked row is part of a multi-selection, act on the whole
- // selection; otherwise act on just that row.
const menuEntities = () => {
- const selected = soup.selection.selected();
- if (selected.length > 1 && soup.selection.isSelected(props.entity.id)) {
+ const selected = props.selectedEntities();
+ if (
+ selected.length > 1 &&
+ selected.some((entity) => entity.id === props.entity.id)
+ ) {
return selected;
}
return [props.entity];
@@ -88,7 +92,14 @@ export const SoupEntityContextMenu: FlowComponent<
data-soup-entity
ref={(el) => {
touchHandler(el, () => ({
- onLongPress: () => drawerManager?.open(props.entity, soup),
+ onLongPress: () => {
+ props.onOpenChange?.(true);
+ drawerManager?.open({
+ entity: props.entity,
+ list: props.list,
+ viewContext: props.viewContext,
+ });
+ },
}));
}}
>
@@ -99,8 +110,6 @@ export const SoupEntityContextMenu: FlowComponent<
<ContextMenu onOpenChange={props.onOpenChange}>
<ContextMenu.Trigger
class="size-full group/cm-trigger"
- // Kobalte's trigger consumes the onContextMenu prop without
- // calling it, so capture the pointer position natively.
on:contextmenu={(event: MouseEvent) =>
setMenuPosition({ x: event.clientX, y: event.clientY })
}
@@ -112,10 +121,8 @@ export const SoupEntityContextMenu: FlowComponent<
<ContextMenuContent class="w-64 text-xs text-ink-muted">
<SoupEntityActionsMenu
entities={menuEntities()}
- soup={soup}
- // Deferred so the menu finishes closing (and its focus
- // handoff settles) before the picker popover mounts, else
- // the popover dismisses itself on focus-outside.
+ list={props.list}
+ viewContext={props.viewContext}
onEditTags={
canEditTags()
? () => setTimeout(() => setTagPickerOpen(true), 0)
diff --git a/apps/web/src/features/next-soup/soup-view/create-soup-entity-actions.ts b/apps/web/src/features/soup/createSoupEntityActions.ts
similarity index 95%
rename from apps/web/src/features/next-soup/soup-view/create-soup-entity-actions.ts
rename to apps/web/src/features/soup/createSoupEntityActions.ts
index f1fd9dce6a..2dcad9d9a0 100644
--- a/apps/web/src/features/next-soup/soup-view/create-soup-entity-actions.ts
+++ b/apps/web/src/features/soup/createSoupEntityActions.ts
@@ -1,17 +1,6 @@
-import { isListViewID } from '@app/constants/list-views';
-import { canExecuteMarkDoneOnView } from '@app/features/next-soup/actions/make-mark-done-action';
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { globalSplitManager } from '@app/signal/splitLayout';
-import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
-import type { SplitHandle } from '@components/app/split-layout/layoutManager';
-import { itemToBlockName } from '@core/constant/allBlocks';
-import { useUserId } from '@core/context/user';
-import { type HotkeyToken, TOKENS } from '@core/hotkey/tokens';
-import { isMobile } from '@core/mobile/isMobile';
-import type { EntityData } from '@entity';
-import { useSetCompanyHiddenMutation } from '@queries/crm/companies';
-import type { Component, JSX } from 'solid-js';
import {
+ type EntityActionListState,
+ type EntityActionViewContext,
makeBlockSenderAction,
makeCopyAction,
makeCopyBranchNameAction,
@@ -35,20 +24,23 @@ import {
makeSetCompanyPropertyAction,
makeShareAction,
markReminderTargetDone,
-} from '../actions';
-import type { SoupState } from '../create-soup-state';
+} from '@app/features/next-soup/actions';
import {
markReminderSeenOnOpen,
openEntityInSplitFromUnifiedList,
reminderSplitTarget,
-} from '../utils';
-
-const SIGNAL_TABS = new Set<string | undefined>([
- undefined,
- 'signal',
- 'important',
-]);
-const NOISE_TABS = new Set(['noise']);
+} from '@app/features/next-soup/utils';
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
+import type { SplitHandle } from '@components/app/split-layout/layoutManager';
+import { itemToBlockName } from '@core/constant/allBlocks';
+import { useUserId } from '@core/context/user';
+import { type HotkeyToken, TOKENS } from '@core/hotkey/tokens';
+import { isMobile } from '@core/mobile/isMobile';
+import type { EntityData } from '@entity';
+import { useSetCompanyHiddenMutation } from '@queries/crm/companies';
+import type { Component, JSX } from 'solid-js';
type SoupEntityActionItem = {
id: string;
@@ -66,11 +58,10 @@ type SoupEntityActionGroup = {
};
type BuildActionGroups = (
- soup: SoupState,
+ soup: EntityActionListState,
entities: EntityData[],
context: {
- activeListView: string;
- activeTab: string | undefined;
+ viewContext: EntityActionViewContext;
/** Set when the list is a folder's contents (project block view) */
viewedProjectId?: string;
// Provided only where the menu host can anchor a tag picker for the
@@ -150,13 +141,18 @@ export function createSoupEntityActions(): {
const buildActionGroups: BuildActionGroups = (
soup,
entities,
- { activeTab, activeListView, viewedProjectId, openTagPicker, splitHandle }
+ { viewContext, viewedProjectId, openTagPicker, splitHandle }
) => {
const canExecuteAll = (canExecute: (e: EntityData) => boolean) =>
entities.length > 0 && entities.every(canExecute);
const handle =
- (execute: (entities: EntityData[], soup: SoupState) => Promise<void>) =>
+ (
+ execute: (
+ entities: EntityData[],
+ soup: EntityActionListState
+ ) => Promise<void>
+ ) =>
() =>
execute(entities, soup);
@@ -164,10 +160,7 @@ export function createSoupEntityActions(): {
const topItems: SoupEntityActionItem[] = [];
// Also what the reminder's own mark-done advances on, further down.
- const marksDoneOnThisView =
- !!activeTab &&
- isListViewID(activeListView) &&
- canExecuteMarkDoneOnView(activeListView, activeTab);
+ const marksDoneOnThisView = viewContext.supportsMarkDone;
if (marksDoneOnThisView) {
// A fully-done selection (e.g. archived threads in mail "All") gets the
@@ -428,7 +421,7 @@ export function createSoupEntityActions(): {
const senderItems: SoupEntityActionItem[] = [];
if (
- NOISE_TABS.has(activeTab ?? '') &&
+ viewContext.senderBucket === 'noise' &&
canExecuteAll(markSenderSignalAction.canExecute)
) {
senderItems.push({
@@ -439,7 +432,7 @@ export function createSoupEntityActions(): {
}
if (
- SIGNAL_TABS.has(activeTab) &&
+ viewContext.senderBucket === 'signal' &&
canExecuteAll(markSenderNoiseAction.canExecute)
) {
senderItems.push({
diff --git a/apps/web/src/features/soup/index.ts b/apps/web/src/features/soup/index.ts
index e627136837..6b27590c2f 100644
--- a/apps/web/src/features/soup/index.ts
+++ b/apps/web/src/features/soup/index.ts
@@ -1,2 +1,7 @@
export * from './collection';
+export * from './createSoupEntityActions';
export * from './filters';
+export * from './SoupEntityActionDrawer';
+export * from './SoupEntityActionDrawerManager';
+export * from './SoupEntityContextMenu';
+export * from './search';
diff --git a/apps/web/src/features/soup/search/context.tsx b/apps/web/src/features/soup/search/context.tsx
new file mode 100644
index 0000000000..c4484b79c9
--- /dev/null
+++ b/apps/web/src/features/soup/search/context.tsx
@@ -0,0 +1,52 @@
+import type { EntityData } from '@entity';
+import { type EntityTypeItemMap, useQuickAccessEntities } from '@property';
+import { EntityType } from '@service-properties/generated/schemas/entityType';
+import {
+ type Accessor,
+ createContext,
+ type FlowComponent,
+ useContext,
+} from 'solid-js';
+
+const SEARCH_ENTITY_TYPES = [
+ EntityType.CHANNEL,
+ EntityType.CHAT,
+ EntityType.DOCUMENT,
+ EntityType.PROJECT,
+ EntityType.TASK,
+] as const;
+
+type SearchEntityType = (typeof SEARCH_ENTITY_TYPES)[number];
+
+export type SoupSearchPoolItem = EntityTypeItemMap[SearchEntityType];
+
+export type SoupSearchPoolEntry = {
+ data: EntityData;
+ bucket?: string;
+};
+
+interface SearchContextValue {
+ entityPool: Accessor<SoupSearchPoolEntry[]>;
+}
+
+const SearchContext = createContext<SearchContextValue>();
+
+export const useSearchContext = () => {
+ const context = useContext(SearchContext);
+ if (!context) {
+ throw new Error('useSearchContext can only be used under a SearchProvider');
+ }
+ return context;
+};
+
+export const useOptionalSearchContext = () => useContext(SearchContext);
+
+export const SearchProvider: FlowComponent = (props) => {
+ const { items } = useQuickAccessEntities(() => [...SEARCH_ENTITY_TYPES]);
+
+ return (
+ <SearchContext.Provider value={{ entityPool: items }}>
+ {props.children}
+ </SearchContext.Provider>
+ );
+};
diff --git a/apps/web/src/features/soup/search/create-search-state.ts b/apps/web/src/features/soup/search/create-search-state.ts
new file mode 100644
index 0000000000..4371767dcb
--- /dev/null
+++ b/apps/web/src/features/soup/search/create-search-state.ts
@@ -0,0 +1,184 @@
+import { arrayEquals } from '@core/util/compareUtils';
+import { debouncedDependent } from '@core/util/debounce';
+import { type EntityData, isChannelEntity } from '@entity/types/entity';
+import type { WithSearch } from '@entity/types/search';
+import {
+ type SearchSoupQueryArgs,
+ useSearchSoupQuery,
+ validateSearchServiceText,
+} from '@queries/soup/search';
+import { type Accessor, createMemo } from 'solid-js';
+import { type SoupSearchPoolEntry, useOptionalSearchContext } from './context';
+import { createSoupFreshSearch, nameFuzzySearchFilter } from './utils';
+
+const LOCAL_SEARCH_DEBOUNCE_MS = 20;
+const SERVICE_SEARCH_DEBOUNCE_MS = 300;
+const FEATURED_RESULT_COUNT = 3;
+
+export type SoupSearchMatchType = 'exact' | 'partial';
+
+export type SoupSearchRequest = {
+ query: string;
+ matchType: SoupSearchMatchType;
+};
+
+export type CreateSearchStateOptions = {
+ text: Accessor<string>;
+ buildRequest: (search: SoupSearchRequest) => SearchSoupQueryArgs;
+ enabled?: Accessor<boolean>;
+ localPool?: Accessor<SoupSearchPoolEntry[]>;
+ disableLocalSearch?: Accessor<boolean>;
+ hideLocalResults?: Accessor<boolean>;
+ searchPaused?: Accessor<boolean>;
+};
+
+export function soupSearchMatchType(query: string): SoupSearchMatchType {
+ const trimmed = query.trim();
+ const quoted =
+ trimmed.length >= 2 &&
+ trimmed.startsWith('"') &&
+ trimmed.endsWith('"') &&
+ trimmed.indexOf('"', 1) === trimmed.length - 1;
+
+ return quoted ? 'exact' : 'partial';
+}
+
+const freshSearch = createSoupFreshSearch();
+
+/**
+ * Combines local quick-access search with service-backed results while
+ * retaining the established Soup search behavior.
+ */
+export function createSearchState(options: CreateSearchStateOptions) {
+ const context = useOptionalSearchContext();
+
+ const text = createMemo(() => options.text().trim());
+ const localText = debouncedDependent(text, LOCAL_SEARCH_DEBOUNCE_MS);
+ const serviceText = debouncedDependent(text, SERVICE_SEARCH_DEBOUNCE_MS);
+
+ const isSearching = () => text().length > 0;
+ const isServiceDebounceSettled = () => text() === serviceText();
+ const isServiceDisabled = () => !validateSearchServiceText(serviceText());
+
+ const queryEnabled = () =>
+ !isServiceDisabled() &&
+ isServiceDebounceSettled() &&
+ !options.searchPaused?.() &&
+ (options.enabled?.() ?? true);
+
+ const searchQuery = useSearchSoupQuery(
+ () =>
+ options.buildRequest({
+ query: serviceText(),
+ matchType: soupSearchMatchType(serviceText()),
+ }),
+ () => ({ enabled: queryEnabled() })
+ );
+
+ const localPool = () => {
+ if (options.localPool) return options.localPool();
+ if (context) return context.entityPool();
+ return [];
+ };
+
+ const localFuzzyPoolResults = createMemo((): WithSearch<EntityData>[] => {
+ const query = localText();
+ if (options.disableLocalSearch?.() || !query) return [];
+ const ranked = freshSearch(localPool(), query);
+ return nameFuzzySearchFilter(
+ ranked.map((result) => result.item.data),
+ query
+ ) as WithSearch<EntityData>[];
+ });
+
+ const localFuzzyResults = createMemo(() => {
+ if (options.hideLocalResults?.()) return [];
+
+ const entities = localFuzzyPoolResults();
+ const channels = entities.filter((entity) => isChannelEntity(entity));
+
+ const nonChannels = entities
+ .filter((entity) => !isChannelEntity(entity))
+ .slice(0, FEATURED_RESULT_COUNT);
+
+ return [...channels, ...nonChannels];
+ });
+
+ const serviceSearchResults = createMemo<EntityData[]>(() => {
+ if (isServiceDisabled() || !isServiceDebounceSettled()) return [];
+
+ if (searchQuery.isFetching && !searchQuery.isFetchingNextPage) return [];
+
+ return searchQuery.data ?? [];
+ });
+
+ const featuredIds = createMemo<string[]>(
+ () => localFuzzyResults().map((entity) => entity.id),
+ [],
+ { equals: arrayEquals }
+ );
+
+ const data = createMemo<EntityData[]>((previous) => {
+ if (!isSearching()) return [];
+
+ const local = localFuzzyResults();
+ const service = serviceSearchResults();
+ const merged = [...service, ...local];
+
+ if (merged.length === 0 && previous.length > 0 && text() !== localText()) {
+ return previous;
+ }
+
+ const byId = new Map<string, EntityData>();
+
+ for (const entity of merged) {
+ if (!byId.has(entity.id)) byId.set(entity.id, entity);
+ }
+
+ const featured = new Set(featuredIds());
+
+ return [
+ ...featuredIds().flatMap((id) => {
+ const entity = byId.get(id);
+ return entity ? [entity] : [];
+ }),
+ ...[...byId.values()].filter((entity) => !featured.has(entity.id)),
+ ];
+ }, []);
+
+ const isLocalSearchSettling = () => isSearching() && text() !== localText();
+
+ const isSearchServiceLoading = () => {
+ if (!isSearching() || !validateSearchServiceText(text())) return false;
+
+ if (!(options.enabled?.() ?? true) || options.searchPaused?.())
+ return false;
+
+ if (!isServiceDebounceSettled()) return true;
+
+ return searchQuery.isFetching && !searchQuery.isFetchingNextPage;
+ };
+
+ return {
+ data,
+ isSearching,
+ localFuzzyResults,
+ serviceSearchResults,
+ featuredIds,
+ searchQuery,
+ isSearchServiceLoading,
+ isLocalSearchSettling,
+ isSettling: () => isLocalSearchSettling() || isSearchServiceLoading(),
+ usesServiceSearch: queryEnabled,
+ isLoading: () => isSearchServiceLoading() && data().length === 0,
+ isFetching: () => isSearchServiceLoading() || searchQuery.isFetching,
+ error: () =>
+ searchQuery.error instanceof Error ? searchQuery.error : undefined,
+ hasNextPage: () => queryEnabled() && (searchQuery.hasNextPage ?? false),
+ isFetchingNextPage: () => searchQuery.isFetchingNextPage,
+ fetchNextPage: () => searchQuery.fetchNextPage(),
+ refetch: () => searchQuery.refetch(),
+ };
+}
+
+export type SearchState = ReturnType<typeof createSearchState>;
diff --git a/apps/web/src/features/soup/search/index.ts b/apps/web/src/features/soup/search/index.ts
new file mode 100644
index 0000000000..8b8b755af0
--- /dev/null
+++ b/apps/web/src/features/soup/search/index.ts
@@ -0,0 +1,20 @@
+export {
+ SearchProvider,
+ type SoupSearchPoolEntry,
+ type SoupSearchPoolItem,
+ useOptionalSearchContext,
+ useSearchContext,
+} from './context';
+export {
+ type CreateSearchStateOptions,
+ createSearchState,
+ type SearchState,
+ type SoupSearchMatchType,
+ type SoupSearchRequest,
+ soupSearchMatchType,
+} from './create-search-state';
+export {
+ createSoupFreshSearch,
+ intersectEntityPools,
+ nameFuzzySearchFilter,
+} from './utils';
diff --git a/apps/web/src/features/soup/search/utils.ts b/apps/web/src/features/soup/search/utils.ts
new file mode 100644
index 0000000000..3e7d57b976
--- /dev/null
+++ b/apps/web/src/features/soup/search/utils.ts
@@ -0,0 +1,82 @@
+import { createFreshSearch } from '@core/util/freshSort';
+import { fuzzyMatch } from '@core/util/fuzzy';
+import { mergeAdjacentMacroEmTags } from '@core/util/searchHighlight';
+import type { EntityData, WithSearch } from '@entity';
+import type { SoupSearchPoolEntry } from './context';
+
+/** Takes a list of entity pools and returns unique entities present in every pool. */
+export function intersectEntityPools(
+ pools: readonly EntityData[][]
+): EntityData[] {
+ if (pools.length === 0) return [];
+ if (pools.length === 1) return pools[0];
+
+ const idCounts = new Map<string, number>();
+ const entityById = new Map<string, EntityData>();
+
+ for (const pool of pools) {
+ const seen = new Set<string>();
+ for (const entity of pool) {
+ if (seen.has(entity.id)) continue;
+ seen.add(entity.id);
+ idCounts.set(entity.id, (idCounts.get(entity.id) ?? 0) + 1);
+ if (!entityById.has(entity.id)) entityById.set(entity.id, entity);
+ }
+ }
+
+ const result: EntityData[] = [];
+ for (const [id, count] of idCounts) {
+ if (count === pools.length) result.push(entityById.get(id)!);
+ }
+ return result;
+}
+
+/** Fuzzy-matches entity names and attaches local search highlights. */
+export function nameFuzzySearchFilter<TEntity extends EntityData>(
+ items: TEntity[],
+ query: string
+): WithSearch<TEntity>[] {
+ if (!query) {
+ return items.map((item) => ({
+ ...item,
+ search: {
+ nameHighlight: null,
+ senderHighlightTerms: null,
+ contentHitData: null,
+ source: 'local',
+ },
+ }));
+ }
+
+ return fuzzyMatch(query, items, (item) => item.name, { noSort: true }).map(
+ ({ item, nameHighlight }) => ({
+ ...item,
+ search: {
+ nameHighlight: mergeAdjacentMacroEmTags(nameHighlight),
+ senderHighlightTerms: null,
+ contentHitData: null,
+ source: 'local',
+ },
+ })
+ );
+}
+
+export const createSoupFreshSearch = () =>
+ createFreshSearch<SoupSearchPoolEntry>({
+ config: {
+ useViewedAt: true,
+ channelBoost: 3,
+ dmBoost: 1.5,
+ fuzzyWeight: 0.7,
+ timeWeight: 0.3,
+ minFuzzyThreshold: 0.1,
+ commaSeparatedChannelMatch: true,
+ },
+ getName: (item) => item.data.name,
+ isChannelItem: (item) => item.data.type === 'channel',
+ isDmItem: (item) => item.bucket === 'dm',
+ getTimestamp: (item) => ({
+ viewedAt: item.data.viewedAt,
+ updatedAt: item.data.updatedAt,
+ }),
+ });
diff --git a/apps/web/src/lib/core/component/TabsInset.tsx b/apps/web/src/lib/core/component/TabsInset.tsx
index a113e2ab3d..3578f3c305 100644
--- a/apps/web/src/lib/core/component/TabsInset.tsx
+++ b/apps/web/src/lib/core/component/TabsInset.tsx
@@ -17,6 +17,7 @@ type TabsInsetProps = {
defaultValue?: string;
class?: string;
depth?: 0 | 1 | 2 | 3 | 4;
+ fullWidth?: boolean;
} & Omit<SegmentedControlRootProps, 'defaultValue'>;
export const TabsInset = (props: TabsInsetProps) => {
@@ -27,6 +28,7 @@ export const TabsInset = (props: TabsInsetProps) => {
'disabled',
'class',
'depth',
+ 'fullWidth',
]);
// The track sits at the control's depth (matching the panel it's on); the
@@ -41,20 +43,33 @@ export const TabsInset = (props: TabsInsetProps) => {
defaultValue={local.defaultValue ?? local.list[0]?.value}
disabled={local.disabled}
{...rootProps}
- class={cn('h-full flex items-center', local.class)}
+ class={cn(
+ 'h-full flex items-center',
+ local.fullWidth && 'w-full',
+ local.class
+ )}
>
<Layer depth={trackDepth()}>
- <div class="relative flex items-center border border-edge-muted bg-surface rounded-lg p-0.5 has-focus-visible:ring-2 has-focus-visible:ring-accent/20">
+ <div
+ class={cn(
+ 'relative flex items-center border border-edge-muted bg-surface rounded-lg p-0.5 has-focus-visible:ring-2 has-focus-visible:ring-accent/20',
+ local.fullWidth && 'w-full'
+ )}
+ >
<For each={local.list}>
{(item) => (
<Layer depth={itemDepth()}>
<KSegmentedControl.Item
value={item.value}
disabled={local.disabled}
+ class={cn(local.fullWidth && 'flex-1')}
>
<KSegmentedControl.ItemInput class="absolute inset-0 pointer-events-none" />
<KSegmentedControl.ItemLabel
- class="flex items-center px-2.5 py-1 text-xs font-medium data-checked:ring data-checked:ring-edge-muted ring-inset rounded-md text-ink-extra-muted hover:text-ink data-checked:bg-surface data-checked:text-ink data-checked:shadow-[0_1px_2px_rgba(0,0,0,0.06)]"
+ class={cn(
+ 'flex items-center px-2.5 py-1 text-xs font-medium data-checked:ring data-checked:ring-edge-muted ring-inset rounded-md text-ink-extra-muted hover:text-ink data-checked:bg-surface data-checked:text-ink data-checked:shadow-[0_1px_2px_rgba(0,0,0,0.06)]',
+ local.fullWidth && 'w-full justify-center'
+ )}
onPointerDown={(e) => {
if (isTouchDevice()) e.preventDefault();
}}
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 88aa43caa6..4a4847b14b 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -7,12 +7,12 @@ import { MobileOnboarding } from '@app/features/auth/mobile-onboarding/MobileOnb
import { setCookie } from '@app/features/auth/Shared';
import { ChannelInviteAcceptance } from '@app/features/channel-invitations/ChannelInviteAcceptance';
import { GlobalShareInboxConflictDialog } from '@app/features/inbox/ShareInboxConflictDialog';
-import { SearchProvider } from '@app/features/next-soup/search-context';
import { usePendingNotificationNavigationEffect } from '@app/features/notifications/PendingNotificationNavigationEffect';
import { InteractiveOnboardingModal } from '@app/features/onboarding/InteractiveOnboardingModal';
import MobileWebSignup from '@app/features/onboarding/MobileWebSignup';
import { OnboardingFlow } from '@app/features/setup/flow/OnboardingFlow';
import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';
+import { SearchProvider } from '@app/features/soup/search/context';
import { TeamInviteAcceptance } from '@app/features/team-invitations/TeamInviteAcceptance';
import {
AnalyticsContextProvider,