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(soup): refactor soup and unified list implementation [stack/01] (#1248)

dev-rb4315828ce279
diff --git a/js/app/packages/app/component/EntityActionsMenuItems.tsx b/js/app/packages/app/component/EntityActionsMenuItems.tsx
deleted file mode 100644
index 4cf5307318..0000000000
--- a/js/app/packages/app/component/EntityActionsMenuItems.tsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import { globalSplitManager } from '@app/signal/splitLayout';
-import { MenuItem } from '@core/component/Menu';
-import { fileTypeToBlockName } from '@core/constant/allBlocks';
-import { intersection } from '@core/util/list';
-import type { EntityData } from '@macro-entity';
-import { type Setter, Show } from 'solid-js';
-import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
-import type { EntityActionType } from './UnifiedEntityActions';
-
-interface EntityActionsMenuItemsProps {
- entity: EntityData;
- onSelectAction: (action: EntityActionType) => void;
-}
-
-export const EntityActionsMenuItems = (props: EntityActionsMenuItemsProps) => {
- const { soupContext } = useSplitPanelOrThrow();
-
- const { actionRegistry, viewsDataStore, selectedView } = soupContext;
-
- const entities = () => {
- const { multiSelectEntities } = viewsDataStore[selectedView()];
- if (multiSelectEntities.length > 0) {
- if (multiSelectEntities.some((e) => e.id === props.entity.id)) {
- return multiSelectEntities;
- }
- }
- return [props.entity];
- };
-
- const canOpenEntityInSplit = () => {
- const splits = globalSplitManager()?.splits;
- if (!splits) return false;
- for (const split of splits()) {
- if (split.content.id === props.entity.id) {
- return false;
- }
- }
- return true;
- };
-
- const setSelection: Setter<EntityData[]> = (entities) => {
- return soupContext.setViewDataStore(
- selectedView(),
- 'multiSelectEntities',
- entities
- );
- };
- const Divider = () => (
- <div class="border-b border-edge-muted w-full my-1"></div>
- );
-
- const MenuItemInner = (props: {
- action: EntityActionType;
- label: string;
- }) => {
- return (
- <Show when={actionRegistry.has(props.action)}>
- <MenuItem
- text={props.label}
- disabled={!actionRegistry.isActionEnabled(props.action, entities())}
- onClick={async () => {
- const { success, failedEntities } = await actionRegistry.execute(
- props.action,
- entities()
- );
- if (success) {
- setSelection([]);
- } else if (failedEntities) {
- setSelection((prev) =>
- intersection(prev, failedEntities, (a, b) => a.id === b.id)
- );
- }
- }}
- />
- </Show>
- );
- };
-
- return (
- <>
- <MenuItemInner action="mark_as_done" label="Mark Done" />
- <MenuItem
- text="Open in new split"
- disabled={entities().length > 1 || !canOpenEntityInSplit()}
- onClick={() => {
- const splitManager = globalSplitManager();
- if (!splitManager) {
- console.error('No split manager available');
- return;
- }
- if (props.entity.type === 'document') {
- const { fileType, id, subType } = props.entity;
- splitManager.createNewSplit({
- content: {
- type: fileTypeToBlockName(subType?.type ?? fileType),
- id,
- },
- referredFrom: 'entity-actions-menu',
- });
- } else {
- const { id, type } = props.entity;
- splitManager.createNewSplit({
- content: {
- type,
- id,
- },
- referredFrom: 'entity-actions-menu',
- });
- }
- }}
- />
- <Divider />
- <MenuItemInner action="rename" label="Rename" />
- <MenuItemInner action="move_to_project" label="Move to folder" />
- <MenuItemInner action="copy" label="Copy" />
- <Divider />
- <div class="text-failure-ink w-full">
- <MenuItemInner action="delete" label="Delete" />
- </div>
- </>
- );
-};
diff --git a/js/app/packages/app/component/EntityModal/RenameView.tsx b/js/app/packages/app/component/EntityModal/RenameView.tsx
index 49ce24567e..b65f1ad1f2 100644
--- a/js/app/packages/app/component/EntityModal/RenameView.tsx
+++ b/js/app/packages/app/component/EntityModal/RenameView.tsx
@@ -1,8 +1,4 @@
-import { useUpsertSavedViewMutation } from '@app/component/Soup';
-import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
-import type { ViewConfigBase } from '@app/component/ViewConfig';
-import { unwrapSignals } from '@core/util/unwrapSignals';
-import { createMemo, createSignal, onMount } from 'solid-js';
+import { createSignal, onMount } from 'solid-js';
import { createRenameDssEntityMutation } from '../../../macro-entity/src/queries/rename';
import type { EntityData } from '../../../macro-entity/src/types/entity';
import { EntityModalActionFooter, EntityModalTitle } from './EntityModal';
@@ -15,31 +11,8 @@ export const RenameView = (props: {
}) => {
const renameMutation = createRenameDssEntityMutation();
let inputRef: HTMLInputElement | undefined;
- const saveViewMutation = useUpsertSavedViewMutation();
- const {
- soupContext: { viewsDataStore: viewsData },
- } = useSplitPanelOrThrow();
- const view = createMemo(() => {
- if (props.viewId) {
- return viewsData[props.viewId];
- }
- return null;
- });
-
- const [editValue, setEditValue] = createSignal(
- props.entity?.name || view()?.view || ''
- );
-
- const currentViewConfigBase = createMemo(() => {
- const foundView = view();
- if (!foundView) return null;
- return unwrapSignals<ViewConfigBase>({
- display: foundView.display,
- filters: foundView.filters,
- sort: foundView.sort,
- });
- });
+ const [editValue, setEditValue] = createSignal(props.entity?.name || '');
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter') {
@@ -54,18 +27,6 @@ export const RenameView = (props: {
const finishEditing = async () => {
const newValue = editValue().trim();
- // Handle view renaming
- if (props.viewId && newValue) {
- const viewConfig = currentViewConfigBase();
- if (viewConfig) {
- saveViewMutation.mutate({
- id: props.viewId,
- name: newValue,
- config: viewConfig,
- });
- }
- }
-
// Handle entity renaming
if (newValue && props.entity) {
await renameMutation.mutateAsync({
diff --git a/js/app/packages/app/component/EntityNavigationIndicator.tsx b/js/app/packages/app/component/EntityNavigationIndicator.tsx
index bbcd127f0e..77aa12965e 100644
--- a/js/app/packages/app/component/EntityNavigationIndicator.tsx
+++ b/js/app/packages/app/component/EntityNavigationIndicator.tsx
@@ -1,3 +1,4 @@
+import { useSoup } from '@app/component/next-soup/soup-context';
import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import { TOKENS } from '@core/hotkey/tokens';
@@ -7,35 +8,26 @@ import CaretUp from '@icon/regular/caret-up.svg';
import { Show } from 'solid-js';
const EntityNavigationIndicator = () => {
- const {
- soupContext: {
- entitiesSignal: [entities],
- selectedView,
- viewsDataStore,
- },
- handle,
- } = useSplitPanelOrThrow();
- const selectedViewData = () => viewsDataStore[selectedView()];
- const selectedEntity = () => selectedViewData().selectedEntity;
- const selectedEntityIndex = () =>
- entities()?.findIndex((item) => item.id === selectedEntity()?.id) ?? -1;
+ const soup = useSoup();
+ const panel = useSplitPanelOrThrow();
+ const selectedEntity = () => soup.focus.item();
+ const selectedEntityIndex = () => soup.focus.index();
return (
<Show
when={
- handle.referredFrom() === 'unified-list' &&
- entities()?.length &&
+ panel.handle.referredFrom() === 'unified-list' &&
+ soup.data()?.length &&
selectedEntity() &&
- handle.content().type !== 'component' &&
- handle.content().type !== 'project'
+ panel.handle.content().type !== 'component' &&
+ panel.handle.content().type !== 'project'
}
>
<div class="flex gap-1 items-center font-mono text-xs text-ink/50 pl-2 pr-4">
<div>
[<span class="text-ink">{selectedEntityIndex() + 1}</span>/
- {entities()?.length}]
+ {soup.data()?.length}]
</div>
- <div>{selectedViewData().view}</div>
<div class="flex text-ink">
<DeprecatedIconButton
size="sm"
@@ -44,7 +36,7 @@ const EntityNavigationIndicator = () => {
label: 'Navigate Down',
hotkeyToken: TOKENS.entity.step.end,
}}
- disabled={selectedEntityIndex() >= entities()!.length - 1}
+ disabled={selectedEntityIndex() >= soup.data()!.length - 1}
theme="current"
onDeepClick={() => {
const command = getActiveCommandByToken(TOKENS.entity.step.end);
diff --git a/js/app/packages/app/component/PreviewPanel.tsx b/js/app/packages/app/component/PreviewPanel.tsx
index 9e5f105bdd..91786a0c85 100644
--- a/js/app/packages/app/component/PreviewPanel.tsx
+++ b/js/app/packages/app/component/PreviewPanel.tsx
@@ -1,41 +1,44 @@
import type { BlockAliasContext } from '@core/block';
import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';
-import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import type { BlockOrchestrator } from '@core/orchestrator';
import type { NonNullableFields } from '@core/util/withRequired';
import { type EntityData, isTaskEntity } from '@macro-entity';
import {
type Component,
- createMemo,
createRenderEffect,
createSignal,
- onMount,
Show,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
-import {
- createNavigationEntityListShortcut,
- createSoupContext,
-} from './SoupContext';
import {
SplitPanelContext,
type SplitPanelContextType,
} from './split-layout/context';
-import { useSplitLayout } from './split-layout/layout';
import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
+import { Suspense } from 'solid-js';
+import { createContextProvider } from '@solid-primitives/context';
+
+export const [PreviewPanelContext, useMaybePreviewPanel] =
+ createContextProvider(
+ (props: { previewEntity: EntityData; onFocusOut?: VoidFunction }) => {
+ return {
+ previewEntity: () => props.previewEntity,
+ onFocusOut: () => props.onFocusOut?.(),
+ };
+ }
+ );
type PreviewPanel = {
selectedEntity: EntityData | undefined;
orchestrator: BlockOrchestrator;
splitPanelContext: SplitPanelContextType;
+ onFocusOut?: VoidFunction;
+ ref?: (el: HTMLElement) => void;
};
const PreviewPanelContent: Component<NonNullableFields<PreviewPanel>> = (
props
) => {
- const [containerRef, setContainerRef] = createSignal<HTMLDivElement | null>(
- null
- );
let scopedSplitPanelContextType: SplitPanelContextType = {} as any;
const splitPanelContext = useSplitPanelOrThrow();
const scopedLayoutRefs: SplitPanelContextType['layoutRefs'] = {
@@ -47,39 +50,8 @@ const PreviewPanelContent: Component<NonNullableFields<PreviewPanel>> = (
scopedLayoutRefs.headerRight = undefined;
if (props.selectedEntity.type === 'project') {
- const { getSplitCount } = useSplitLayout();
- const soupContext = createSoupContext({
- isRenderedFromPreview: true,
- parentContext: splitPanelContext.soupContext,
- domRef: containerRef,
- });
-
- const [attachHotKeys, splitHotkeyScope] = useHotkeyDOMScope(
- `split=${splitPanelContext.splitHotkeyScope}`
- );
-
const [previewState, setPreviewState] = createSignal(true);
- const splitName = createMemo(() => {
- const { type, id } = splitPanelContext.handle.content();
- if (type === 'component') return id;
-
- return type;
- });
-
- createNavigationEntityListShortcut({
- splitName,
- splitHandle: splitPanelContext.handle,
- splitHotkeyScope,
- soupContext,
- previewState: [previewState, setPreviewState],
- getSplitCount: getSplitCount,
- });
- scopedSplitPanelContextType.soupContext = soupContext;
scopedSplitPanelContextType.previewState = [previewState, setPreviewState];
-
- onMount(() => {
- attachHotKeys(containerRef()!);
- });
}
const blockInstance = () => {
@@ -116,6 +88,7 @@ const PreviewPanelContent: Component<NonNullableFields<PreviewPanel>> = (
return (
<div
+ ref={props.ref}
class="flex flex-col size-full"
onFocusIn={(event) => {
if (interactedWith()) return;
@@ -138,7 +111,6 @@ const PreviewPanelContent: Component<NonNullableFields<PreviewPanel>> = (
setInteractedWith(true);
}}
tabIndex={-1}
- ref={setContainerRef}
>
{/* Preview-specific toolbar slots so blocks can render the "share" bar (via SplitToolbarLeft/Right) */}
<div
@@ -178,7 +150,14 @@ const PreviewPanelContent: Component<NonNullableFields<PreviewPanel>> = (
halfSplitState: undefined,
}}
>
- <Dynamic component={blockInstance().element} />
+ <PreviewPanelContext
+ previewEntity={props.selectedEntity}
+ onFocusOut={props.onFocusOut}
+ >
+ <Suspense>
+ <Dynamic component={blockInstance().element} />
+ </Suspense>
+ </PreviewPanelContext>
</SplitPanelContext.Provider>
</div>
</div>
@@ -191,9 +170,11 @@ export const PreviewPanel: Component<PreviewPanel> = (props) => {
<Show when={props.selectedEntity}>
{(selectedEntity) => (
<PreviewPanelContent
+ ref={props.ref}
selectedEntity={selectedEntity()}
orchestrator={props.orchestrator}
splitPanelContext={props.splitPanelContext}
+ onFocusOut={props.onFocusOut}
/>
)}
</Show>
diff --git a/js/app/packages/app/component/PropertyDisplayControl.tsx b/js/app/packages/app/component/PropertyDisplayControl.tsx
index 92c72bc183..8d09baebe5 100644
--- a/js/app/packages/app/component/PropertyDisplayControl.tsx
+++ b/js/app/packages/app/component/PropertyDisplayControl.tsx
@@ -19,7 +19,14 @@ import {
onMount,
Show,
} from 'solid-js';
-import type { DisplayOptions } from './ViewConfig';
+
+export type DisplayOptions = {
+ layout: 'compact' | 'expanded' | 'visual';
+ unrollNotifications: boolean;
+ showUnreadIndicator: boolean;
+ displayProperties: string[];
+ limit?: number;
+};
const MAX_DISPLAY_PROPERTIES = 4;
diff --git a/js/app/packages/app/component/Soup.tsx b/js/app/packages/app/component/Soup.tsx
deleted file mode 100644
index 5aec7aaa49..0000000000
--- a/js/app/packages/app/component/Soup.tsx
+++ /dev/null
@@ -1,883 +0,0 @@
-import {
- useGlobalBlockOrchestrator,
- useGlobalNotificationSource,
-} from '@app/component/GlobalAppState';
-import { useHandleFileUpload } from '@app/util/handleFileUpload';
-import { useIsAuthenticated } from '@core/context/user';
-import { getIconConfig } from '@core/component/EntityIcon';
-import { FileDropOverlay } from '@core/component/FileDropOverlay';
-import { SegmentedControl } from '@core/component/FormControls/SegmentControls';
-import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';
-import { ENABLE_UNIFIED_LIST_AI_INPUT } from '@core/constant/featureFlags';
-import { IS_MAC } from '@core/constant/isMac';
-import { useSettingsState } from '@core/constant/SettingsState';
-import { fileFolderDrop } from '@core/directive/fileFolderDrop';
-import { TOKENS } from '@core/hotkey/tokens';
-import type { RegisterHotkeyReturn, ValidHotkey } from '@core/hotkey/types';
-import {
- DEFAULT_VIEWS,
- type DefaultView,
- type ViewId,
- type ViewLabel,
-} from '@core/types/view';
-import { throttledDependent } from '@core/util/debounce';
-import { handleFileFolderDrop } from '@core/util/upload';
-import { Tabs } from '@kobalte/core/tabs';
-import {
- queryKeys,
- useQueryClient as useEntityQueryClient,
-} from '@macro-entity';
-import IconGear from '@macro-icons/macro-gear.svg';
-import SearchIcon from '@macro-icons/macro-magnifying-glass.svg';
-import PreviewIcon from '@macro-icons/wide/preview.svg';
-import NoiseIcon from '@macro-icons/wide/noise.svg';
-import SignalIcon from '@macro-icons/wide/signal.svg';
-import XIcon from '@icon/regular/x.svg?component-solid';
-import { createEffectOnEntityTypeNotification } from '@notifications';
-import { invalidateEntityNotifications } from '@queries/notification/user-notifications';
-import { storageServiceClient } from '@service-storage/client';
-import { createElementSize } from '@solid-primitives/resize-observer';
-import { Navigate } from '@solidjs/router';
-import { globalSplitManager } from '@app/signal/splitLayout';
-import { useMutation, useQueryClient } from '@tanstack/solid-query';
-import { registerHotkey } from 'core/hotkey/hotkeys';
-import {
- batch,
- type Component,
- createEffect,
- createMemo,
- createSignal,
- For,
- Match,
- on,
- onCleanup,
- onMount,
- type ParentComponent,
- Show,
- Switch,
-} from 'solid-js';
-import { PreviewPanel } from './PreviewPanel';
-import { SoupChatInput } from './SoupChatInput';
-import { SuspenseContextComp } from './SuspenseContext';
-import {
- SplitHeaderLeft,
- SplitHeaderRight,
-} from './split-layout/components/SplitHeader';
-import { SplitToolbarRight } from './split-layout/components/SplitToolbar';
-import { SplitPanelContext } from './split-layout/context';
-import { useSplitLayout } from './split-layout/layout';
-import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
-import { UnifiedListView } from './UnifiedListView';
-import type { SystemSortOption } from './ViewConfig';
-import {
- VIEWCONFIG_BASE,
- VIEWCONFIG_DEFAULTS_IDS,
- type ViewConfigBase,
-} from './ViewConfig';
-import { ENTITY_TYPE_FILTERS } from './Soup/utils/filterConfigs';
-import { useFilterActions } from './Soup/hooks/useFilterActions';
-import {
- FilterButton,
- FilterDivider,
- ShortcutLabel,
-} from './Soup/components/FilterButton';
-import { SortDropdown } from './Soup/components/SortDropdown';
-import { isMobile } from '@core/mobile/isMobile';
-
-false && fileFolderDrop;
-
-function EntityTypeIconFilter() {
- const splitContext = useSplitPanelOrThrow();
- const {
- splitHotkeyScope,
- previewState,
- soupContext: {
- viewsDataStore,
- setViewDataStore,
- selectedView,
- setSelectedView,
- },
- } = splitContext;
- const [preview, setPreview] = previewState;
-
- const view = createMemo(() => viewsDataStore[selectedView()]);
-
- // Search state (must be after view is defined)
- let searchInputRef: HTMLInputElement | undefined;
- const [searchFocused, setSearchFocused] = createSignal(false);
- const searchText = createMemo(() => view()?.searchText ?? '');
- const setSearchText = (text: string) => {
- setViewDataStore(selectedView(), 'searchText', text);
- };
-
- // Memoized filter accessors
- const entityTypeFilter = createMemo(
- () => view()?.filters?.typeFilter ?? VIEWCONFIG_BASE.filters.typeFilter
- );
- const channelCategoryFilter = createMemo(
- () =>
- view()?.filters?.channelCategoryFilter ??
- VIEWCONFIG_BASE.filters.channelCategoryFilter
- );
- const focusFilters = createMemo(
- () => view()?.filters?.focusFilters ?? VIEWCONFIG_BASE.filters.focusFilters
- );
- const notificationFilter = createMemo(
- () =>
- view()?.filters?.notificationFilter ??
- VIEWCONFIG_BASE.filters.notificationFilter
- );
- const unrollNotifications = createMemo(
- () =>
- view()?.display?.unrollNotifications ??
- VIEWCONFIG_BASE.display.unrollNotifications
- );
- const documentTypeFilter = createMemo(
- () =>
- view()?.filters?.documentTypeFilter ??
- VIEWCONFIG_BASE.filters.documentTypeFilter
- );
-
- // Use the extracted filter actions hook
- const filterActions = useFilterActions({
- selectedView,
- setViewDataStore,
- entityTypeFilter,
- documentTypeFilter,
- channelCategoryFilter,
- focusFilters,
- });
-
- // Ensure state consistency when switching views (not continuous watching)
- createEffect(
- on(selectedView, (viewId) => {
- const focus = focusFilters() ?? [];
- if (!focus.includes('signal') && !focus.includes('noise')) return;
-
- batch(() => {
- if (notificationFilter() !== 'notDone') {
- setViewDataStore(viewId, 'filters', 'notificationFilter', 'notDone');
- }
- if (!unrollNotifications()) {
- setViewDataStore(viewId, 'display', 'unrollNotifications', true);
- }
- });
- })
- );
-
- const isUnreadFilterActive = () => view()?.filters?.unreadOnly === true;
-
- const toggleUnreadFilter = () => {
- const current = view()?.filters?.unreadOnly ?? false;
- setViewDataStore(selectedView(), 'filters', 'unreadOnly', !current);
- };
-
- const clearAllFilters = () => {
- batch(() => {
- setSelectedView('all');
- setViewDataStore('all', 'filters', 'typeFilter', []);
- setViewDataStore('all', 'filters', 'documentTypeFilter', []);
- setViewDataStore('all', 'filters', 'focusFilters', []);
- setViewDataStore('all', 'filters', 'notificationFilter', 'all');
- setViewDataStore('all', 'filters', 'unreadOnly', false);
- setViewDataStore('all', 'filters', 'channelCategoryFilter', []);
- });
- };
-
- const sortType = createMemo(() => {
- const sort = view()?.sort;
- if (sort?.type === 'systemSortOption') {
- return sort.sortBy;
- }
- return 'updated_at';
- });
-
- const setSortType = (sortBy: SystemSortOption) => {
- const currentSort = view()?.sort;
- setViewDataStore(selectedView(), 'sort', {
- type: 'systemSortOption',
- sortBy,
- sortOrder: currentSort?.sortOrder ?? 'ascending',
- });
- };
-
- const [sortDropdownOpen, setSortDropdownOpen] = createSignal(false);
-
- // Register all hotkeys
- const hotkeyConfigs: {
- hotkey: ValidHotkey;
- description: string;
- handler: () => void;
- }[] = [
- {
- hotkey: 'i',
- description: 'Toggle Inbox',
- handler: () => filterActions.toggleFocusFilter('signal'),
- },
- {
- hotkey: 'o',
- description: 'Toggle Other',
- handler: () => filterActions.toggleFocusFilter('noise'),
- },
- ...ENTITY_TYPE_FILTERS.filter((f) => f.enabled).map((f) => ({
- hotkey: f.shortcut as ValidHotkey,
- description: `Filter by ${f.label}`,
- handler: filterActions.getFilterHandler(f),
- })),
- {
- hotkey: 'u',
- description: 'Filter by Unread',
- handler: () => toggleUnreadFilter(),
- },
- {
- hotkey: 's',
- description: 'Open sort menu',
- handler: () => setSortDropdownOpen((prev) => !prev),
- },
- {
- hotkey: '/',
- description: 'Clear filters',
- handler: () => {
- clearAllFilters();
- setViewDataStore('all', 'searchText', '');
- },
- },
- {
- hotkey: 'cmd+f',
- description: 'Search',
- handler: () => {
- searchInputRef?.focus();
- if (searchInputRef?.value) searchInputRef.select();
- },
- },
- ];
-
- const hotkeyDisposers = hotkeyConfigs.map((config) =>
- registerHotkey({
- hotkey: [config.hotkey],
- scopeId: splitHotkeyScope,
- description: config.description,
- keyDownHandler: () => {
- config.handler();
- return true;
- },
- registrationType: 'add',
- })
- );
-
- onCleanup(() => {
- hotkeyDisposers.forEach((d) => d.dispose());
- });
-
- // Scroll shadow indicators
- const [scrollRef, setScrollRef] = createSignal<HTMLDivElement | null>(null);
- const [leftOpacity, setLeftOpacity] = createSignal(0);
- const [rightOpacity, setRightOpacity] = createSignal(0);
- const SCROLL_THRESHOLD = 10;
-
- // Track size changes to update indicators
- const size = createElementSize(scrollRef);
- const containerWidth = () => size.width ?? 0;
-
- const updateClipIndicators = () => {
- const ref = scrollRef();
- if (!ref) return;
- const { scrollLeft, scrollWidth, clientWidth } = ref;
-
- const leftAmount = Math.min(scrollLeft, SCROLL_THRESHOLD);
- setLeftOpacity(leftAmount / SCROLL_THRESHOLD);
-
- const maxScroll = scrollWidth - clientWidth;
- const remainingScroll = maxScroll - scrollLeft;
- const rightAmount = Math.min(remainingScroll, SCROLL_THRESHOLD);
- setRightOpacity(rightAmount / SCROLL_THRESHOLD);
- };
-
- // Update indicators when size changes
- createEffect(() => {
- containerWidth(); // Track size changes
- updateClipIndicators();
- });
-
- onMount(() => {
- const ref = scrollRef();
- if (!ref) return;
- ref.addEventListener('scroll', updateClipIndicators);
- onCleanup(() => ref?.removeEventListener('scroll', updateClipIndicators));
- });
-
- return (
- <div class="relative h-full">
- {/* Left clip boundary indicator */}
- <div
- class="absolute pointer-events-none left-0 top-px bottom-px w-3 z-2 pattern-diagonal-4 pattern-edge mask-r-from-0% border-l border-edge-muted"
- style={{ opacity: leftOpacity() }}
- />
- {/* Right clip boundary indicator */}
- <div
- class="absolute pointer-events-none right-0 top-px bottom-px w-3 z-2 pattern-diagonal-4 pattern-edge mask-l-from-0% border-r border-edge-muted"
- style={{ opacity: rightOpacity() }}
- />
- <div
- class="flex items-center h-full overflow-x-auto scrollbar-hidden overscroll-none text-xs touch:mobile-width:text-sm"
- ref={setScrollRef}
- >
- {/* Inbox toggle */}
- <FilterButton
- icon={SignalIcon}
- label="Inbox"
- shortcut="i"
- isActive={filterActions.isInboxActive}
- onClick={() => filterActions.toggleFocusFilter('signal')}
- />
- {/* Other toggle */}
- <FilterButton
- icon={NoiseIcon}
- label="Other"
- shortcut="o"
- isActive={filterActions.isOtherActive}
- onClick={() => filterActions.toggleFocusFilter('noise')}
- />
- <FilterDivider />
- {/* Unread filter */}
- <div class="flex items-center mr-0.5 shrink-0">
- <Tooltip
- tooltip={<LabelAndHotKey label="Unread Only" shortcut="u" />}
- >
- <button
- type="button"
- class="flex items-center gap-1 h-[22px] touch:mobile-width:h-9 pr-2.5 pl-1 active:bg-accent active:text-panel rounded-full"
- classList={{
- 'bg-accent text-panel': isUnreadFilterActive(),
- 'text-ink-muted hover:text-accent hover:bg-accent/20':
- !isUnreadFilterActive(),
- }}
- onClick={() => toggleUnreadFilter()}
- >
- <svg
- class="size-4"
- viewBox="0 0 24 24"
- fill="currentColor"
- stroke="none"
- xmlns="http://www.w3.org/2000/svg"
- >
- <circle cx="12" cy="12" r="4" />
- </svg>
- <span class="leading-none">
- <ShortcutLabel label="Unread" shortcut="u" />
- </span>
- </button>
- </Tooltip>
- </div>
- <div class="mx-0.5 w-px h-5 bg-edge-muted/50 shrink-0" />
- {/* Entity type icons */}
- <div class="flex items-center shrink-0">
- <For each={ENTITY_TYPE_FILTERS.filter((f) => f.enabled)}>
- {(filter) => {
- const iconConfig = () => getIconConfig(filter.iconType);
- return (
- <FilterButton
- icon={iconConfig().icon}
- label={filter.label}
- shortcut={filter.shortcut}
- isActive={() => filterActions.isFilterConfigActive(filter)}
- onClick={filterActions.getFilterHandler(filter)}
- paddingClass="px-2.5"
- />
- );
- }}
- </For>
- </div>
- <div class="mx-0.5 w-px h-5 bg-edge-muted/50 shrink-0" />
- {/* Preview toggle */}
- <Tooltip
- tooltip={<LabelAndHotKey label="Toggle Preview" shortcut="space" />}
- >
- <button
- type="button"
- class="flex items-center gap-1.5 h-[22px] touch:mobile-width:h-9 px-2.5 active:bg-accent active:text-panel rounded-full"
- classList={{
- 'bg-accent text-panel': preview(),
- 'text-ink-muted hover:text-accent hover:bg-accent/20': !preview(),
- }}
- onClick={() => {
- setPreview((prev) => !prev);
- }}
- >
- <PreviewIcon class="size-4.5" />
- <span class="leading-none">
- <ShortcutLabel label="Preview" shortcut="space" />
- </span>
- </button>
- </Tooltip>
- <FilterDivider />
- {/* Sort dropdown */}
- <SortDropdown
- value={sortType}
- onChange={setSortType}
- open={sortDropdownOpen}
- onOpenChange={setSortDropdownOpen}
- />
- <div class="touch:mobile-width:-order-1">
- <FilterDivider />
- </div>
- {/* Filter search bar */}
- <div class="flex items-center shrink-0 touch:mobile-width:-order-2">
- <Tooltip tooltip={<LabelAndHotKey label="Filter" shortcut="⌘F" />}>
- <div
- class="relative flex items-center gap-1.5 h-[22px] touch:mobile-width:h-9 px-2.5 rounded-full touch:mobile-width:min-w-35"
- classList={{
- 'bg-accent text-panel': !!searchText() && !searchFocused(),
- 'text-ink-muted hover:text-accent hover:bg-accent/20':
- !searchText() || searchFocused(),
- }}
- onClick={() => searchInputRef?.focus()}
- >
- <SearchIcon class="size-4.5 shrink-0" />
- <Show when={!searchText() && !searchFocused()}>
- <span class="leading-none pointer-events-none">
- <span class="underline underline-offset-2 decoration-current/60">
- {IS_MAC ? '⌘' : '^'}F
- </span>
- <span>ilter</span>
- </span>
- </Show>
- <input
- ref={(el) => {
- searchInputRef = el;
- }}
- type="text"
- value={searchText()}
- onInput={(e) => setSearchText(e.currentTarget.value)}
- onFocus={() => setSearchFocused(true)}
- onBlur={() => setSearchFocused(false)}
- onKeyDown={(e) => {
- if (
- e.key === 'Escape' ||
- e.key === 'Enter' ||
- e.key === 'ArrowDown'
- ) {
- e.preventDefault();
- e.currentTarget.blur();
- }
- }}
- class="p-0 bg-transparent border-none outline-none ring-0 focus:outline-none focus:ring-0 cursor-default"
- style={{
- width:
- !searchText() && !searchFocused()
- ? '0'
- : `${Math.max(5, searchText().length + 1)}ch`,
- }}
- />
- </div>
- </Tooltip>
- </div>
- </div>
- </div>
- );
-}
-
-function ClearFiltersButton() {
- const splitContext = useSplitPanelOrThrow();
- const {
- soupContext: { setViewDataStore, setSelectedView },
- } = splitContext;
-
- const clearAllFilters = () => {
- batch(() => {
- setSelectedView('all');
- setViewDataStore('all', 'filters', 'typeFilter', []);
- setViewDataStore('all', 'filters', 'documentTypeFilter', []);
- setViewDataStore('all', 'filters', 'focusFilters', []);
- setViewDataStore('all', 'filters', 'notificationFilter', 'all');
- setViewDataStore('all', 'filters', 'unreadOnly', false);
- setViewDataStore('all', 'filters', 'channelCategoryFilter', []);
- setViewDataStore('all', 'searchText', '');
- });
- };
-
- return (
- <Tooltip tooltip={<LabelAndHotKey label="Clear filters" shortcut="/" />}>
- <button
- type="button"
- class="flex items-center gap-1.5 px-2.5 rounded-full text-ink-muted hover:text-accent hover:bg-accent/20 active:bg-accent active:text-panel"
- onClick={clearAllFilters}
- >
- <XIcon class="size-4.5" />
- <span class="text-xs touch:mobile-width:text-sm leading-none">
- Clear
- <span class="ml-1 font-mono opacity-70">/</span>
- </span>
- </button>
- </Tooltip>
- );
-}
-
-function SettingsButton() {
- const { settingsOpen, toggleSettings } = useSettingsState();
- const { getSplitCount } = useSplitLayout();
-
- // Hide settings button when there are multiple splits
- const isSingleSplit = () => getSplitCount() <= 1;
-
- return (
- <Show when={isSingleSplit()}>
- <Tooltip
- tooltip={
- <LabelAndHotKey
- label={settingsOpen() ? 'Close Settings' : 'Open Settings'}
- hotkeyToken={TOKENS.global.toggleSettings}
- />
- }
- >
- <button
- type="button"
- class="relative flex items-center justify-center size-[22px] rounded-full active:bg-accent active:text-panel"
- classList={{
- 'bg-hover text-ink': settingsOpen(),
- 'text-ink-muted hover:text-accent hover:bg-accent/20':
- !settingsOpen(),
- }}
- onClick={() => toggleSettings()}
- >
- <IconGear class="size-4.5" />
- </button>
- </Tooltip>
- </Show>
- );
-}
-
-const ViewTab: ParentComponent<{
- viewId: ViewId;
-}> = (props) => {
- return (
- <Tabs.Content class="flex flex-col size-full" value={props.viewId}>
- {/* If Kobalte TabContent recieves Suspense as direct child, Suspense owner doesn't cleanup and causes memory leak */}
- {/* Make sure Suspense isn't root child by by wrapping children with DOM node */}
- <div class="contents">{props.children}</div>
- </Tabs.Content>
- );
-};
-
-let runSuspenseWarningLog = false;
-const SuspenseUnifiedListFallback = () => {
- const runWarningLog = () => {
- if (!runSuspenseWarningLog) {
- setTimeout(() => {
- runSuspenseWarningLog = true;
- });
- return;
- }
-
- console.warn('UnifiedList Suspsense Triggered');
- };
-
- runWarningLog();
-
- // Return a skeleton that maintains layout instead of null to avoid black flash
- return (
- <div class="size-full flex flex-col gap-1 p-2 animate-pulse">
- <div class="h-12 bg-surface-2 rounded" />
- <div class="h-12 bg-surface-2 rounded" />
- <div class="h-12 bg-surface-2 rounded" />
- <div class="h-12 bg-surface-2 rounded" />
- <div class="h-12 bg-surface-2 rounded" />
- </div>
- );
-};
-
-const ViewWithSearch: Component<{
- viewId: ViewId;
-}> = (props) => {
- return (
- <ViewTab viewId={props.viewId}>
- <Switch>
- <Match
- when={props.viewId === 'email' && DEFAULT_VIEWS.includes('email')}
- >
- <SuspenseContextComp fallback={<SuspenseUnifiedListFallback />}>
- <EmailView />
- </SuspenseContextComp>
- </Match>
- <Match when={props.viewId === 'all' && DEFAULT_VIEWS.includes('all')}>
- <SuspenseContextComp fallback={<SuspenseUnifiedListFallback />}>
- <AllView />
- </SuspenseContextComp>
- </Match>
- <Match when={true}>
- <SuspenseContextComp fallback={<SuspenseUnifiedListFallback />}>
- <UnifiedListView hideToolbar />
- </SuspenseContextComp>
- </Match>
- </Switch>
- </ViewTab>
- );
-};
-
-export function Soup() {
- const isAuthenticated = useIsAuthenticated();
-
- // NOTE: if trying to access a split in which we are looking at a document, we shouldn't redirect away.
- const hasDocumentSplit = createMemo(() => {
- const manager = globalSplitManager();
- if (!manager) return false;
- return manager.splits().some((split) => split.content.type !== 'component');
- });
-
- const splitPanelContext = useSplitPanelOrThrow();
- const {
- handle,
- splitHotkeyScope,
- soupContext: {
- viewsDataStore: viewsData,
- selectedView,
- setSelectedView,
- entityListRefSignal: [, setEntityListRef],
- },
- } = splitPanelContext;
- const view = createMemo(() => viewsData[selectedView()]);
- const previewState = () => splitPanelContext.previewState;
- const [preview, setPreview] = previewState();
- const selectedEntity = () => view().selectedEntity;
- const throttledSelectedEntity = throttledDependent(selectedEntity, 100);
-
- createEffect(() => {
- handle.setDisplayName('');
- });
-
- // Sync selected view to split metadata
- createEffect(() => {
- handle.updateMeta?.({ viewId: selectedView() });
- });
-
- const orchestrator = useGlobalBlockOrchestrator();
-
- const entityQueryClient = useEntityQueryClient();
-
- const hotkeyDisposers: RegisterHotkeyReturn[] = [];
-
- hotkeyDisposers.push(
- registerHotkey({
- hotkey: ['space'],
- scopeId: splitHotkeyScope,
- description: 'Toggle Preview',
- hotkeyToken: TOKENS.unifiedList.togglePreview,
- keyDownHandler: () => {
- setPreview((prev) => !prev);
- return true;
- },
- // displayPriority: 10,
- })
- );
-
- const [isDragging, setIsDragging] = createSignal(false);
- const [isValidDrag, setIsValidDrag] = createSignal(true);
-
- const handleFileUpload = useHandleFileUpload();
-
- const notificationSource = useGlobalNotificationSource();
- createEffectOnEntityTypeNotification(
- notificationSource,
- 'channel',
- (notification) => {
- entityQueryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
- });
- invalidateEntityNotifications(notification.entity_id);
- }
- );
-
- createEffectOnEntityTypeNotification(notificationSource, 'email', () => {
- entityQueryClient.invalidateQueries({
- // HACK: this needs to be improved, since we use a single query, per entity invalidations
- // become a little more complicated.
- queryKey: queryKeys.all.entity,
- });
- });
-
- createEffectOnEntityTypeNotification(
- notificationSource,
- 'document',
- (notification) => {
- if (notification.notificationEventType === 'task_assigned') {
- entityQueryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
- });
- invalidateEntityNotifications(notification.entity_id);
- }
- }
- );
-
- let tabsRef: HTMLDivElement | undefined;
-
- onCleanup(() => {
- setEntityListRef(undefined);
- hotkeyDisposers.forEach((disposer) => disposer.dispose());
- });
-
- return (
- <Show
- when={isAuthenticated() !== false || hasDocumentSplit()}
- fallback={<Navigate href="/" />}
- >
- <div
- class="relative flex flex-col bg-panel size-full"
- use:fileFolderDrop={{
- onDrop: (fileEntries, folderEntries) => {
- handleFileFolderDrop(fileEntries, folderEntries, handleFileUpload);
- },
- onDragStart: () => {
- setIsValidDrag(true);
- setIsDragging(true);
- },
- onDragEnd: () => setIsDragging(false),
- }}
- >
- <Show when={isDragging()}>
- <FileDropOverlay valid={isValidDrag()}>
- <Show when={!isValidDrag()}>
- <div class="text-failure">[!] Invalid file type</div>
- </Show>
- <div>Drop any file here to add it to your workspace</div>
- </FileDropOverlay>
- </Show>
-
- <div class="relative flex-grow min-h-0 flex max-sm:flex-col flex-row size-full">
- <SplitPanelContext.Provider
- value={{
- ...splitPanelContext,
- halfSplitState: () =>
- preview() ? { side: 'left', percentage: 30 } : undefined,
- }}
- >
- <Tabs
- ref={tabsRef}
- class="@container/soup [container-type:inline-size] flex flex-col gap-1 size-full overflow-x-clip"
- classList={{
- 'border-r border-edge-muted': preview(),
- }}
- value={selectedView()}
- onChange={setSelectedView}
- >
- <SplitHeaderLeft>
- <EntityTypeIconFilter />
- </SplitHeaderLeft>
- <SplitHeaderRight>
- <div class="flex items-center h-full gap-0.5">
- <ClearFiltersButton />
- <div class="mx-0.5 w-px h-5 bg-edge-muted/50 shrink-0" />
- <SettingsButton />
- </div>
- </SplitHeaderRight>
- <For each={Object.keys(viewsData)}>
- {(viewId) => <ViewWithSearch viewId={viewId} />}
- </For>
- </Tabs>
- </SplitPanelContext.Provider>
- <Show when={preview()}>
- <PreviewPanel
- selectedEntity={throttledSelectedEntity()}
- orchestrator={orchestrator}
- splitPanelContext={splitPanelContext}
- />
- </Show>
- </div>
- <Show when={ENABLE_UNIFIED_LIST_AI_INPUT && !isMobile()}>
- <SoupChatInput />
- </Show>
- </div>
- </Show>
- );
-}
-
-function AllView() {
- return <UnifiedListView hideToolbar />;
-}
-
-function EmailView() {
- const {
- emailViewSignal: [emailView, setEmailView],
- viewsDataStore,
- selectedView,
- } = useSplitPanelOrThrow().soupContext;
- const viewData = createMemo(() => viewsDataStore[selectedView()]);
-
- return (
- <>
- <UnifiedListView hideToolbar />
- <SplitToolbarRight>
- <div class="flex flex-row items-center pr-2">
- <SegmentedControl
- disabled={!!viewData().searchText}
- size="SM"
- label="View"
- list={['inbox', 'sent', 'drafts']}
- value={emailView()}
- onChange={setEmailView}
- />
- </div>
- </SplitToolbarRight>
- </>
- );
-}
-
-export const useUpsertSavedViewMutation = () => {
- const queryClient = useQueryClient();
- return useMutation(() => ({
- mutationFn: async (
- viewData:
- | {
- config: ViewConfigBase;
- id?: ViewId;
- name: ViewLabel;
- }
- | {
- id: ViewId;
- }
- ) => {
- const isDefaultView = VIEWCONFIG_DEFAULTS_IDS.includes(
- viewData.id as DefaultView
- );
- if ('config' in viewData) {
- // if data id is in defaults, exclude default, set up args to create new view
- if (isDefaultView) {
- // don't exclude default view on editing default view config
- // await storageServiceClient.views.excludeDefaultView({
- // defaultViewId: viewData.id!,
- // });
- viewData.id = undefined;
- viewData.name = `My ${viewData.name}`;
- }
- // create new view
- if (!viewData.id) {
- return await storageServiceClient.views.createSavedView({
- name: viewData.name,
- config: viewData.config,
- });
- } // patch existing view
- else {
- return await storageServiceClient.views.patchView({
- saved_view_id: viewData.id,
- name: viewData.name,
- config: viewData.config,
- });
- }
- } else {
- // delete or exclude view
- if (isDefaultView) {
- // for now don't exclude default view
- // return await storageServiceClient.views.excludeDefaultView({
- // defaultViewId: viewData.id,
- // });
- } else {
- return await storageServiceClient.views.deleteView({
- savedViewId: viewData.id,
- });
- }
- }
- },
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['savedViews'] });
- },
- }));
-};
diff --git a/js/app/packages/app/component/Soup/components/FilterButton.tsx b/js/app/packages/app/component/Soup/components/FilterButton.tsx
deleted file mode 100644
index 5839f7e1bc..0000000000
--- a/js/app/packages/app/component/Soup/components/FilterButton.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import type { Component } from 'solid-js';
-import { Dynamic } from 'solid-js/web';
-import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';
-
-const SHORTCUT_SUFFIXES: Record<string, string> = { space: '␣', '/': '/' };
-
-export const ShortcutLabel: Component<{ label: string; shortcut: string }> = (
- props
-) => {
- const s = props.shortcut.trim();
- if (!s) return <>{props.label}</>;
-
- const suffix = SHORTCUT_SUFFIXES[s.toLowerCase()] ?? SHORTCUT_SUFFIXES[s];
- if (suffix) {
- return (
- <>
- {props.label}
- <span class="ml-1 font-mono opacity-70">{suffix}</span>
- </>
- );
- }
-
- const idx = props.label.toLowerCase().indexOf(s.toLowerCase());
- if (idx === -1) return <>{props.label}</>;
-
- return (
- <>
- {props.label.slice(0, idx)}
- <span class="underline underline-offset-2 decoration-current/60">
- {props.label.slice(idx, idx + s.length)}
- </span>
- {props.label.slice(idx + s.length)}
- </>
- );
-};
-
-export interface FilterButtonProps {
- icon: Component<{ class?: string }>;
- label: string;
- shortcut: string;
- isActive: () => boolean;
- onClick: () => void;
- paddingClass?: string;
-}
-
-export const FilterButton: Component<FilterButtonProps> = (props) => (
- <div class="flex items-center mr-0.5 shrink-0">
- <Tooltip
- tooltip={<LabelAndHotKey label={props.label} shortcut={props.shortcut} />}
- >
- <button
- type="button"
- class={`flex items-center gap-1 h-[22px] touch:mobile-width:h-9 ${props.paddingClass ?? 'pl-2 pr-2.5'} active:bg-accent active:text-panel rounded-full`}
- classList={{
- 'bg-accent text-panel': props.isActive(),
- 'text-ink-muted hover:text-accent hover:bg-accent/20':
- !props.isActive(),
- }}
- onClick={props.onClick}
- >
- <Dynamic component={props.icon} class="size-3.5" />
- <span class="leading-none">
- <ShortcutLabel label={props.label} shortcut={props.shortcut} />
- </span>
- </button>
- </Tooltip>
- </div>
-);
-
-export const FilterDivider: Component = () => (
- <div class="mx-0.5 w-px h-5 bg-edge-muted/50 shrink-0" />
-);
diff --git a/js/app/packages/app/component/Soup/hooks/useFilterActions.ts b/js/app/packages/app/component/Soup/hooks/useFilterActions.ts
deleted file mode 100644
index b033e54717..0000000000
--- a/js/app/packages/app/component/Soup/hooks/useFilterActions.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-import { produce } from 'solid-js/store';
-import type { SetStoreFunction } from 'solid-js/store';
-import type { Accessor } from 'solid-js';
-import type { ViewId } from '@core/types/view';
-import type { ExpandedEntityType } from '@macro-entity';
-import { match } from 'ts-pattern';
-import type { DocumentTypeFilter, ViewDataMap } from '../../ViewConfig';
-import {
- type EntityTypeFilterConfig,
- FOCUS_FILTER_CONFIGS,
- type FocusFilterTarget,
-} from '../utils/filterConfigs';
-import {
- isChannelCategoryActive,
- isDocumentPresetActive,
- isEntityTypeFilterActive,
- isFocusFilterActive,
-} from '../utils/filterHelpers';
-
-export interface UseFilterActionsParams {
- selectedView: Accessor<ViewId>;
- setViewDataStore: SetStoreFunction<ViewDataMap>;
- entityTypeFilter: Accessor<ExpandedEntityType[]>;
- documentTypeFilter: Accessor<DocumentTypeFilter[]>;
- channelCategoryFilter: Accessor<('people' | 'groups')[] | undefined>;
- focusFilters: Accessor<('signal' | 'noise')[] | undefined>;
-}
-
-export function useFilterActions(params: UseFilterActionsParams) {
- const {
- selectedView,
- setViewDataStore,
- entityTypeFilter,
- documentTypeFilter,
- channelCategoryFilter,
- focusFilters,
- } = params;
-
- const isInboxActive = () => isFocusFilterActive(focusFilters(), 'signal');
- const isOtherActive = () => isFocusFilterActive(focusFilters(), 'noise');
- const isEntityTypeActive = (type: ExpandedEntityType) =>
- isEntityTypeFilterActive(entityTypeFilter(), type);
- const isDocPresetActive = (types: DocumentTypeFilter[]) =>
- isDocumentPresetActive(entityTypeFilter(), documentTypeFilter(), types);
- const isChannelCatActive = (category: 'people' | 'groups') =>
- isChannelCategoryActive(
- entityTypeFilter(),
- channelCategoryFilter() ?? [],
- category
- );
-
- const clearTopbarTypeFilters = () => {
- setViewDataStore(
- selectedView(),
- 'filters',
- produce((filters) => {
- filters.typeFilter = [];
- filters.documentTypeFilter = [];
- filters.channelCategoryFilter = [];
- })
- );
- };
-
- const toggleFocusFilter = (target: FocusFilterTarget) => {
- const isActive = target === 'signal' ? isInboxActive() : isOtherActive();
- const config = isActive
- ? FOCUS_FILTER_CONFIGS.none
- : FOCUS_FILTER_CONFIGS[target];
- const viewId = selectedView();
-
- setViewDataStore(viewId, 'filters', 'focusFilters', [
- ...config.focusFilters,
- ]);
- setViewDataStore(
- viewId,
- 'filters',
- 'notificationFilter',
- config.notificationFilter
- );
- setViewDataStore(
- viewId,
- 'display',
- 'unrollNotifications',
- config.unrollNotifications
- );
- };
-
- const setExclusiveEntityTypeFilter = (type: ExpandedEntityType) => {
- if (isEntityTypeActive(type)) {
- clearTopbarTypeFilters();
- return;
- }
- setViewDataStore(
- selectedView(),
- 'filters',
- produce((filters) => {
- filters.typeFilter = [type];
- filters.documentTypeFilter = [];
- filters.channelCategoryFilter = [];
- })
- );
- };
-
- const toggleDocumentPreset = (preset: DocumentTypeFilter[]) => {
- if (entityTypeFilter().length === 1 && isDocPresetActive(preset)) {
- clearTopbarTypeFilters();
- return;
- }
- setViewDataStore(
- selectedView(),
- 'filters',
- produce((filters) => {
- filters.typeFilter = ['document'];
- filters.documentTypeFilter = preset;
- filters.channelCategoryFilter = [];
- })
- );
- };
-
- const toggleChannelCategoryFilter = (category: 'people' | 'groups') => {
- const isActive =
- entityTypeFilter().length === 1 &&
- entityTypeFilter()[0] === 'channel' &&
- isChannelCatActive(category);
-
- if (isActive) {
- clearTopbarTypeFilters();
- return;
- }
- setViewDataStore(
- selectedView(),
- 'filters',
- produce((filters) => {
- filters.typeFilter = ['channel'];
- filters.channelCategoryFilter = [category];
- filters.documentTypeFilter = [];
- })
- );
- };
-
- const getFilterHandler = (filter: EntityTypeFilterConfig): (() => void) => {
- return match(filter)
- .with(
- { kind: 'documentPreset' },
- (f) => () => toggleDocumentPreset(f.documentTypes)
- )
- .with(
- { kind: 'channelCategory' },
- (f) => () => toggleChannelCategoryFilter(f.channelCategory)
- )
- .with(
- { kind: 'entityType' },
- (f) => () => setExclusiveEntityTypeFilter(f.type)
- )
- .exhaustive();
- };
-
- const isFilterConfigActive = (filter: EntityTypeFilterConfig): boolean => {
- return match(filter)
- .with(
- { kind: 'documentPreset' },
- (f) =>
- entityTypeFilter().length === 1 && isDocPresetActive(f.documentTypes)
- )
- .with(
- { kind: 'channelCategory' },
- (f) =>
- entityTypeFilter().length === 1 &&
- isChannelCatActive(f.channelCategory)
- )
- .with({ kind: 'entityType' }, (f) => isEntityTypeActive(f.type))
- .exhaustive();
- };
-
- return {
- isInboxActive,
- isOtherActive,
- isEntityTypeActive,
- isDocPresetActive,
- isChannelCatActive,
- isFilterConfigActive,
- clearTopbarTypeFilters,
- toggleFocusFilter,
- setExclusiveEntityTypeFilter,
- toggleDocumentPreset,
- toggleChannelCategoryFilter,
- getFilterHandler,
- };
-}
diff --git a/js/app/packages/app/component/Soup/utils/filterConfigs.ts b/js/app/packages/app/component/Soup/utils/filterConfigs.ts
deleted file mode 100644
index c2dfb89ab9..0000000000
--- a/js/app/packages/app/component/Soup/utils/filterConfigs.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import type { ExpandedEntityType } from '@macro-entity';
-import type { DocumentTypeFilter, FilterOptions } from '../../ViewConfig';
-import { ENABLE_TASKS_TABS } from '@core/constant/featureFlags';
-
-/**
- * Discriminated union for entity type filter configurations.
- * Each kind determines which fields are valid, making illegal states unrepresentable.
- */
-export type EntityTypeFilterConfig =
- | {
- kind: 'entityType';
- type: ExpandedEntityType;
- label: string;
- iconType: string;
- enabled: boolean;
- shortcut: string;
- }
- | {
- kind: 'channelCategory';
- channelCategory: 'people' | 'groups';
- label: string;
- iconType: string;
- enabled: boolean;
- shortcut: string;
- }
- | {
- kind: 'documentPreset';
- type: 'document';
- documentTypes: DocumentTypeFilter[];
- label: string;
- iconType: string;
- enabled: boolean;
- shortcut: string;
- };
-
-/**
- * Entity type filter button configurations for the topbar.
- * Only one filter can be active at a time (exclusive selection).
- */
-export const ENTITY_TYPE_FILTERS: EntityTypeFilterConfig[] = [
- {
- kind: 'documentPreset',
- type: 'document',
- documentTypes: ['md', 'canvas'],
- label: 'Docs',
- iconType: 'md',
- enabled: true,
- shortcut: 'd',
- },
- {
- kind: 'entityType',
- type: 'chat',
- label: 'Agents',
- iconType: 'chat',
- enabled: true,
- shortcut: 'a',
- },
- {
- kind: 'channelCategory',
- channelCategory: 'people',
- label: 'People',
- iconType: 'channel',
- enabled: true,
- shortcut: 'p',
- },
- {
- kind: 'channelCategory',
- channelCategory: 'groups',
- label: 'Teams',
- iconType: 'direct_message',
- enabled: true,
- shortcut: 'm',
- },
- {
- kind: 'entityType',
- type: 'task',
- label: 'Tasks',
- iconType: 'task',
- enabled: ENABLE_TASKS_TABS,
- shortcut: 't',
- },
- {
- kind: 'entityType',
- type: 'email',
- label: 'Mail',
- iconType: 'email',
- enabled: true,
- shortcut: 'l',
- },
- {
- kind: 'documentPreset',
- type: 'document',
- documentTypes: ['code', 'image', 'pdf', 'unknown'],
- label: 'Files',
- iconType: 'project',
- enabled: true,
- shortcut: 'f',
- },
-];
-
-/**
- * Focus filter coupling configuration.
- * Defines the coupled state that must be set together when toggling inbox/other filters.
- * This makes the coupling explicit and centralized rather than scattered across toggle functions.
- */
-export const FOCUS_FILTER_CONFIGS = {
- signal: {
- focusFilters: ['signal'] as const,
- notificationFilter: 'notDone' as FilterOptions['notificationFilter'],
- unrollNotifications: true,
- },
- noise: {
- focusFilters: ['noise'] as const,
- notificationFilter: 'notDone' as FilterOptions['notificationFilter'],
- unrollNotifications: true,
- },
- none: {
- focusFilters: [] as ('signal' | 'noise')[],
- notificationFilter: 'all' as FilterOptions['notificationFilter'],
- unrollNotifications: false,
- },
-} as const;
-
-export type FocusFilterTarget = 'signal' | 'noise';
diff --git a/js/app/packages/app/component/Soup/utils/filterHelpers.ts b/js/app/packages/app/component/Soup/utils/filterHelpers.ts
deleted file mode 100644
index b32e9a6e15..0000000000
--- a/js/app/packages/app/component/Soup/utils/filterHelpers.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import {
- PROPERTY_OPTION_IDS,
- SYSTEM_PROPERTY_IDS,
-} from '@core/component/Properties/constants';
-import type { TaskEntityWithProperties } from '@macro-entity';
-import type { ExpandedEntityType } from '@macro-entity';
-import type { DocumentTypeFilter } from '../../ViewConfig';
-
-/**
- * Pure helper for set equality comparison.
- */
-export const sameSet = <T>(a: readonly T[], b: readonly T[]): boolean => {
- if (a.length !== b.length) return false;
- const setA = new Set(a);
- return b.every((x) => setA.has(x));
-};
-
-/**
- * Pure predicate: is a specific document preset filter active?
- * Checks if typeFilter is exactly ['document'] and documentTypeFilter matches targetTypes.
- */
-export const isDocumentPresetActive = (
- typeFilter: readonly ExpandedEntityType[],
- documentTypeFilter: readonly DocumentTypeFilter[],
- targetTypes: readonly DocumentTypeFilter[]
-): boolean => {
- if (typeFilter.length !== 1 || typeFilter[0] !== 'document') return false;
- return sameSet(documentTypeFilter, targetTypes);
-};
-
-/**
- * Pure predicate: is a specific channel category filter active?
- * Checks if typeFilter includes 'channel' and categoryFilter is exactly [targetCategory].
- */
-export const isChannelCategoryActive = (
- typeFilter: readonly ExpandedEntityType[],
- categoryFilter: readonly ('people' | 'groups')[],
- targetCategory: 'people' | 'groups'
-): boolean => {
- if (typeFilter.length !== 1 || typeFilter[0] !== 'channel') return false;
- return categoryFilter.length === 1 && categoryFilter[0] === targetCategory;
-};
-
-/**
- * Pure predicate: is a specific entity type filter active (exclusive)?
- * Checks if typeFilter is exactly [type].
- */
-export const isEntityTypeFilterActive = (
- typeFilter: readonly ExpandedEntityType[],
- type: ExpandedEntityType
-): boolean => {
- return typeFilter.length === 1 && typeFilter[0] === type;
-};
-
-/**
- * Pure predicate: is a focus filter (signal/noise) active?
- * Signal = Inbox, Noise = Other.
- */
-export const isFocusFilterActive = (
- focusFilters: readonly ('signal' | 'noise')[] | undefined,
- target: 'signal' | 'noise'
-): boolean => {
- if (!focusFilters || focusFilters.length === 0) return false;
- // Inbox active means signal is in list and noise is not
- // Other active means noise is in list and signal is not
- const hasTarget = focusFilters.includes(target);
- const opposite = target === 'signal' ? 'noise' : 'signal';
- const hasOpposite = focusFilters.includes(opposite);
- return hasTarget && !hasOpposite;
-};
-
-/**
- * extracts assignee user ids from task properties.
- */
-export const getTaskAssigneeIds = (
- entity: TaskEntityWithProperties
-): string[] => {
- const properties = entity.properties;
- if (!properties) return [];
- const assigneesProperty = properties.find(
- (p) => p.definition.id === SYSTEM_PROPERTY_IDS.ASSIGNEES
- );
- if (!assigneesProperty?.value) return [];
-
- const value = assigneesProperty.value;
- if (value.type === 'EntityReference' && Array.isArray(value.value)) {
- return value.value
- .filter((ref) => ref.entity_type === 'USER')
- .map((ref) => ref.entity_id);
- }
-
- return [];
-};
-
-/**
- * gets the status option id from task properties.
- */
-export const getTaskStatusOptionId = (
- entity: TaskEntityWithProperties
-): string | undefined => {
- const properties = entity.properties;
- if (!properties) return undefined;
-
- const statusProperty = properties.find(
- (p) => p.definition.id === SYSTEM_PROPERTY_IDS.STATUS
- );
- if (!statusProperty?.value) return undefined;
-
- const value = statusProperty.value;
- if (
- value.type === 'SelectOption' &&
- 'value' in value &&
- Array.isArray(value.value)
- ) {
- return value.value[0];
- }
-
- return undefined;
-};
-
-/**
- * checks if a task is in a "closed" state (completed or canceled).
- */
-export const isTaskClosed = (entity: TaskEntityWithProperties): boolean => {
- if (entity.subType?.is_completed === true) {
- return true;
- }
- const statusOptionId = getTaskStatusOptionId(entity);
- if (
- statusOptionId === PROPERTY_OPTION_IDS.STATUS.COMPLETED ||
- statusOptionId === PROPERTY_OPTION_IDS.STATUS.CANCELED
- ) {
- return true;
- }
- return false;
-};
-
-/**
- * checks if the current user is assigned to the task.
- */
-export const isCurrentUserAssigned = (
- entity: TaskEntityWithProperties,
- currentUserId: string | undefined
-): boolean => {
- if (!currentUserId) return false;
- const assigneeIds = getTaskAssigneeIds(entity);
- if (assigneeIds.length === 0) return true;
- return assigneeIds.includes(currentUserId);
-};
-
-/**
- * determines if a task should appear in the signal tab.
- * tasks appear in signal if:
- * - they are not completed or canceled
- * - the current user is an assignee (or the task has no assignees)
- */
-export const isSignalTask = (
- entity: TaskEntityWithProperties,
- currentUserId: string | undefined
-): boolean => {
- if (isTaskClosed(entity)) {
- return false;
- }
- return isCurrentUserAssigned(entity, currentUserId);
-};
diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsx
index 3e32353236..cc67b12073 100644
--- a/js/app/packages/app/component/SoupChatInput.tsx
+++ b/js/app/packages/app/component/SoupChatInput.tsx
@@ -6,11 +6,12 @@ import { cognitionApiServiceClient } from '@service-cognition/client';
import { useHotkeyDOMScope } from 'core/hotkey/hotkeys';
import { onMount, Show } from 'solid-js';
import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
+import { useSoup } from '@app/component/next-soup/soup-context';
export function SoupChatInput() {
let containerRef!: HTMLDivElement;
const splitPanelContext = useSplitPanelOrThrow();
- const [preview] = splitPanelContext.previewState;
+ const soup = useSoup();
const { ChatInput } = useChatInput({ autoAttach: false });
const [attachHotkeys] = useHotkeyDOMScope('soup.chatInput');
@@ -46,7 +47,7 @@ export function SoupChatInput() {
};
return (
- <Show when={!preview()}>
+ <Show when={!soup.previewEntity()}>
<div
ref={containerRef}
class="absolute z-10 bottom-0 pb-2 px-2 flex justify-center w-full pointer-events-none"
diff --git a/js/app/packages/app/component/SoupContext.tsx b/js/app/packages/app/component/SoupContext.tsx
deleted file mode 100644
index a3d8ae8148..0000000000
--- a/js/app/packages/app/component/SoupContext.tsx
+++ /dev/null
@@ -1,1757 +0,0 @@
-import { globalSplitManager } from '@app/signal/splitLayout';
-import { useChannelsContext } from '@core/context/channels';
-import { toast } from '@core/component/Toast/Toast';
-import { HotkeyTags } from '@core/hotkey/constants';
-import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';
-import { TOKENS } from '@core/hotkey/tokens';
-import { HOTKEY_PRIORITY_LOW } from '@core/hotkey/types';
-import {
- getHotkeyCommand,
- getScopeElement,
- runCommand,
-} from '@core/hotkey/utils';
-import { isModality } from '@core/mobile/inputModality';
-import type { DefaultView, ViewId } from '@core/types/view';
-import { getActualTarget } from '@core/util/getActualTarget';
-import { isInteractiveElement } from '@core/util/isInteractiveElement';
-import { filterMap } from '@core/util/list';
-import { isErr } from '@core/util/maybeResult';
-import { getScrollParent } from '@core/util/scrollParent';
-import { scrollToKeepGap } from '@core/util/scrollToKeepGap';
-import { waitForFrames } from '@core/util/sleep';
-import {
- type EntityData,
- isSearchEntity,
- isTaskEntity,
- type TaskEntityWithProperties,
-} from '@macro-entity';
-import { entityHasUnreadNotifications } from '@notifications';
-import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';
-import type { PropertiesEntityType } from '@service-properties/client';
-import { ChannelTypeEnum } from '@service-comms/client';
-import { useSetPropertyStatusCompleteMutation } from '@queries/properties/entity';
-import { storageServiceClient } from '@service-storage/client';
-import { createLazyMemo } from '@solid-primitives/memo';
-import { useQuery } from '@tanstack/solid-query';
-import type { Virtualizer } from '@tanstack/solid-virtual';
-import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
-import {
- type Accessor,
- batch,
- createEffect,
- createMemo,
- createSignal,
- on,
- onCleanup,
- type Setter,
- type Signal,
-} from 'solid-js';
-import {
- createStore,
- produce,
- reconcile,
- type SetStoreFunction,
- type Store,
-} from 'solid-js/store';
-import { ENTITY_HEIGHT } from '../../macro-entity/src/components/EntityWithEverything';
-import { useUserId } from '../../macro-entity/src/queries/auth';
-import { createBulkCopyDssEntityMutation } from '../../macro-entity/src/queries/dss';
-import { openBulkEditModal } from './bulk-edit-entity/BulkEditEntityModal';
-import {
- resetCommandCategoryIndex,
- searchCategories,
- setCommandCategoryIndex,
- setKonsoleContextInformation,
-} from './command/KonsoleItem';
-import {
- konsoleOpen,
- resetKonsoleMode,
- setKonsoleMode,
- toggleKonsoleVisibility,
-} from './command/state';
-import { useGlobalNotificationSource } from './GlobalAppState';
-import { openEntityInSplitFromUnifiedList } from './soupContextHelpers';
-import {
- isCurrentUserAssigned,
- isTaskClosed,
-} from './Soup/utils/filterHelpers';
-import type { SplitHandle } from './split-layout/layoutManager';
-import { globalRemoveFromSplitHistory } from './split-layout/layoutUtils';
-import {
- createEntityActionRegistry,
- type EntityActionRegistry,
-} from './UnifiedEntityActions';
-import {
- VIEWCONFIG_BASE,
- VIEWCONFIG_DEFAULTS,
- VIEWCONFIG_DEFAULTS_IDS,
- type ViewConfigBase,
- type ViewConfigEnhanced,
- type ViewData,
- type ViewDataMap,
-} from './ViewConfig';
-
-type NavigateListFn = (input: NavigationInput) => Promise<NavigationResult>;
-
-type CollapseEntityFn = (entityId: string) => Promise<void>;
-
-export type SoupContext = {
- viewsDataStore: Store<ViewDataMap>;
- setViewDataStore: SetStoreFunction<Partial<ViewDataMap>>;
- selectedView: Accessor<ViewId>;
- setSelectedView: Setter<ViewId>;
- virtualizerHandleSignal: Signal<Virtualizer<Element, Element> | undefined>;
- entityListRefSignal: Signal<HTMLDivElement | undefined>;
- entitiesSignal: Signal<EntityData[] | undefined>;
- emailViewSignal: Signal<PreviewViewStandardLabel>;
- actionRegistry: EntityActionRegistry;
- isRenderedFromPreview: boolean;
- navigateThroughList: NavigateListFn;
- // this is a private method that should be registered once by createNavigationEntityListShortcut
- _setNavigateThroughList: (fn: NavigateListFn) => void;
- /**
- * Optional hook to animate an entity row collapsing before the entity disappears from the list. This gets set by the EntityRowProvider.
- */
- collapseEntitySignal: Signal<CollapseEntityFn | undefined>;
- parentContextSignal: Signal<SoupContext | undefined>;
- childContextSignal: Signal<SoupContext | undefined>;
- activeContextSignal: Signal<SoupContext | undefined>;
- domRef: Accessor<HTMLDivElement | null>;
-};
-
-export function createStubSoupContext(): SoupContext {
- return {
- viewsDataStore: createStore({})[0],
- setViewDataStore: () => {},
- selectedView: () => '',
- setSelectedView: () => {},
- virtualizerHandleSignal: createSignal(),
- entityListRefSignal: createSignal(),
- entitiesSignal: createSignal(),
- emailViewSignal: createSignal<PreviewViewStandardLabel>('all'),
- actionRegistry: createEntityActionRegistry(),
- navigateThroughList: async () => ({
- success: false,
- type: '',
- entity: undefined,
- }),
- _setNavigateThroughList: () => {},
- collapseEntitySignal: createSignal<CollapseEntityFn | undefined>(undefined),
-
- isRenderedFromPreview: false,
- parentContextSignal: createSignal<SoupContext | undefined>(undefined),
- childContextSignal: createSignal<SoupContext | undefined>(undefined),
- activeContextSignal: createSignal<SoupContext | undefined>(undefined),
- domRef: () => null,
- };
-}
-
-const DEFAULT_VIEW_ID: DefaultView = 'all';
-
-const DEFAULT_VIEW_IDS_SET = new Set(VIEWCONFIG_DEFAULTS_IDS);
-
-type CreateSoupContextProps = {
- splitId?: string;
- domRef: Accessor<HTMLDivElement | null>;
- isRenderedFromPreview?: boolean;
- parentContext?: SoupContext;
-};
-
-const splitIdSoupContextMapper = new Map<string, SoupContext>();
-
-export function createSoupContext(props: CreateSoupContextProps): SoupContext {
- const [selectedView, setSelectedView] = createSignal<ViewId>(DEFAULT_VIEW_ID);
- const [viewsDataStore, setViewDataStore] = useAllViews({
- selectedViewSignal: [selectedView, setSelectedView],
- });
- const virtualizerHandleSignal = createSignal<Virtualizer<Element, Element>>();
- const entityListRefSignal = createSignal<HTMLDivElement>();
- const entitiesSignal = createSignal<EntityData[]>();
- const emailViewSignal = createSignal<PreviewViewStandardLabel>('inbox');
- const collapseEntitySignal = createSignal<CollapseEntityFn | undefined>(
- undefined
- );
- let navigateThroughListFn: NavigateListFn | undefined;
-
- const parentContextSignal = createSignal<SoupContext | undefined>(
- props?.parentContext
- );
- const childContextSignal = createSignal<SoupContext | undefined>(undefined);
- const activeContextSignal =
- props?.parentContext?.activeContextSignal ??
- createSignal<SoupContext | undefined>(undefined);
-
- const context: SoupContext = {
- viewsDataStore,
- setViewDataStore,
- selectedView,
- setSelectedView,
- virtualizerHandleSignal,
- entityListRefSignal,
- entitiesSignal,
- emailViewSignal,
- collapseEntitySignal,
- actionRegistry: createEntityActionRegistry(),
- isRenderedFromPreview: props?.isRenderedFromPreview ?? false,
- parentContextSignal,
- childContextSignal,
- activeContextSignal,
- navigateThroughList: (input) => {
- if (!navigateThroughListFn) {
- throw new Error('navigateThroughList not initialized');
- }
- return navigateThroughListFn(input);
- },
- _setNavigateThroughList: (fn) => {
- if (navigateThroughListFn) {
- console.warn('navigateThroughList already initialized');
- }
- navigateThroughListFn = fn;
- },
- domRef: props?.domRef!,
- };
-
- if (props.splitId) {
- splitIdSoupContextMapper.set(props.splitId, context);
- }
-
- onCleanup(() => {
- const [parentContext] = parentContextSignal;
- parentContext()?.childContextSignal[1](undefined);
- if (activeContextSignal[0]() === context) {
- activeContextSignal[1](parentContext);
- }
- if (props.splitId) {
- splitIdSoupContextMapper.delete(props.splitId);
- }
- });
-
- if (!activeContextSignal[0]()) {
- activeContextSignal[1](context);
- }
-
- if (props?.parentContext) {
- props.parentContext.childContextSignal[1](context);
- }
-
- return context;
-}
-
-function createViewData(
- view: DefaultView,
- viewProps?: Omit<ViewConfigEnhanced, 'id'> &
- Partial<Pick<ViewConfigEnhanced, 'id'>>
-): ViewData {
- return {
- id: (viewProps?.id || view) ?? '',
- view: viewProps?.view ?? view,
- filters: {
- notificationFilter:
- viewProps?.filters?.notificationFilter ??
- VIEWCONFIG_BASE.filters.notificationFilter,
- importantFilter:
- viewProps?.filters?.importantFilter ??
- VIEWCONFIG_BASE.filters.importantFilter,
- documentTypeFilter:
- viewProps?.filters?.documentTypeFilter ??
- VIEWCONFIG_BASE.filters.documentTypeFilter,
- typeFilter:
- viewProps?.filters?.typeFilter ?? VIEWCONFIG_BASE.filters.typeFilter,
- projectFilter:
- viewProps?.filters?.projectFilter ??
- VIEWCONFIG_BASE.filters.projectFilter,
- fromFilter:
- viewProps?.filters?.fromFilter ??
- VIEWCONFIG_BASE.filters.fromFilter ??
- [],
- focusFilters:
- viewProps?.filters?.focusFilters ??
- VIEWCONFIG_BASE.filters.focusFilters ??
- [],
- propertyFilters:
- viewProps?.filters?.propertyFilters ??
- VIEWCONFIG_BASE.filters.propertyFilters ??
- [],
- },
- display: {
- layout: viewProps?.display?.layout ?? VIEWCONFIG_BASE.display.layout,
- showUnreadIndicator:
- viewProps?.display?.showUnreadIndicator ??
- VIEWCONFIG_BASE.display.showUnreadIndicator,
- unrollNotifications:
- viewProps?.display?.unrollNotifications ??
- VIEWCONFIG_BASE.display.unrollNotifications,
- displayProperties:
- viewProps?.display?.displayProperties ??
- VIEWCONFIG_BASE.display.displayProperties,
- limit: viewProps?.display?.limit,
- },
- sort: viewProps?.sort ?? VIEWCONFIG_BASE.sort,
- selectedEntity: undefined,
- scrollOffset: undefined,
- initialConfig: undefined,
- multiSelectEntities: [],
- hasUserInteractedEntity: false,
- searchText: viewProps?.searchText,
- };
-}
-
-export type NavigationInput = {
- axis: 'start' | 'end'; // movement direction
- mode: 'step' | 'jump'; // how far: one step or to the end
-};
-
-export type NavigationResult = {
- success: boolean;
- entity: EntityData | undefined;
-};
-
-export function createNavigationEntityListShortcut({
- splitHandle,
- splitHotkeyScope,
- soupContext,
- previewState,
- getSplitCount,
-}: {
- splitName: Accessor<string>;
- splitHandle: SplitHandle;
- splitHotkeyScope: string;
- soupContext: SoupContext;
- previewState: Signal<boolean>;
- getSplitCount: () => number;
-}) {
- const {
- viewsDataStore: viewsData,
- setViewDataStore,
- entityListRefSignal: [entityListRef],
- virtualizerHandleSignal: [virtualizerHandle],
- selectedView,
- entitiesSignal: [entities],
- actionRegistry,
- parentContextSignal: [getParentContext],
- childContextSignal: [getChildContext],
- activeContextSignal: [activeContext, setActiveContext],
- } = soupContext;
- const viewData = createMemo(() => viewsData[selectedView()]);
-
- const [attachEntityHotkeys, _entityHotkeyScope] = useHotkeyDOMScope('entity');
- const selectedEntity = () => viewData().selectedEntity;
-
- const setSelectedEntity = (entity: EntityData | undefined) => {
- setViewDataStore(
- selectedView(),
- produce((state) => {
- if (!state) return;
- state.selectedEntity = entity;
- })
- );
- };
-
- const notificationSource = useGlobalNotificationSource();
- const userId = useUserId();
-
- const isViewingList = createMemo(() => {
- return (
- splitHandle.content().id === 'unified-list' ||
- splitHandle.content().type === 'project'
- );
- });
- const canAccessEntityList = () => {
- if (isViewingList()) return true;
- const result =
- !isViewingList() && splitHandle.referredFrom() === 'unified-list';
- return result;
- };
-
- let lastMultiNavigationInput: NavigationInput;
-
- /**
- * From the current selection, get the entity to try to select after a modal
- * edit operation.
- */
- const getNextEntity = (
- entitiesForAction: EntityData[]
- ): EntityData | null => {
- const entityList = entities();
- if (!entityList) return null;
- const idToIndexMap = new Map(entityList.map(({ id }, i) => [id, i]));
- let maxIndex = 0;
- for (const entity of entitiesForAction) {
- const ndx = idToIndexMap.get(entity.id);
- if (ndx && ndx > maxIndex) {
- maxIndex = ndx;
- }
- }
- return maxIndex < entityList.length - 1 ? entityList[maxIndex + 1] : null;
- };
-
- /**
- * Return to list after entity modal edit action.
- */
- const afterEntityAction = (
- entity: EntityData | null | undefined,
- clearSelection?: boolean
- ) => {
- const virtualizer = virtualizerHandle();
- const virtualItems = virtualizer?.getVirtualItems() || [];
- if (clearSelection) {
- setViewDataStore(selectedView(), 'multiSelectEntities', []);
- }
- if (entity) {
- setSelectedEntity(entity);
- const nextIndex = entities()?.findIndex(({ id }) => id === entity.id);
- if (nextIndex !== undefined && nextIndex > -1) {
- const start = virtualItems[0]?.index;
- const end = virtualItems.at(-1)?.index ?? 0;
-
- if (nextIndex < start) {
- virtualizer?.scrollToIndex(nextIndex, { align: 'start' });
- } else if (nextIndex > end) {
- virtualizer?.scrollToIndex(nextIndex, { align: 'end' });
- }
- waitForFrames(2).then(() => {
- const elem = getEntityElAtIndex(nextIndex);
- if (elem instanceof HTMLElement) {
- elem.focus();
- return;
- // TODO: cooked state (no focus returned - have not yet seen tho)
- }
- });
- } else {
- const firstIndex = virtualItems.at(0)?.index;
- if (!firstIndex) return;
- const elem = getEntityElAtIndex(firstIndex);
- if (elem instanceof HTMLElement) elem.focus();
- // TODO: cooked state (no focus returned - have not yet seen tho)
- }
- }
- };
-
- // ---------------------------------------------------------------------------
- // MARK AS DONE
- // ---------------------------------------------------------------------------
-
- // Helper to get the correct properties entity type for an entity
- // Tasks have type 'document' but subType 'task', so we need special handling
- const getPropertiesEntityType = (
- entity: EntityData
- ): PropertiesEntityType | undefined => {
- if (isTaskEntity(entity)) return 'TASK';
- if (entity.type === 'email') return 'THREAD';
- if (entity.type === 'document') return 'DOCUMENT';
- if (entity.type === 'project') return 'PROJECT';
- return undefined;
- };
-
- const setPropertyStatusCompleteMutation =
- useSetPropertyStatusCompleteMutation();
-
- actionRegistry.register(
- 'mark_as_done',
- async (multiSelectEntities) => {
- const handler =
- VIEWCONFIG_DEFAULTS[selectedView() as DefaultView]?.hotkeyOptions?.e;
-
- const hasSupportedEntity = multiSelectEntities.some(
- (entity) => getPropertiesEntityType(entity) !== undefined
- );
-
- if (handler || hasSupportedEntity) {
- // focus the correct entity first, so that the animation is not blcoking
- if (multiSelectEntities.length > 1) {
- const selectedEntityData = getSelectedEntity();
- const selectedEntityIncludedInMultiSelectedEntities =
- multiSelectEntities.find(
- (entity) => selectedEntityData?.entity.id === entity.id
- );
-
- // update selected entity to current selected entity's neighbor, before/after neighbor is based on last navigation direction.
- // if selected entity is not from multi selected list, don't update selected entity
- // we don't want to update the selected entity when user is using touch modality because it will cause the list to scroll in unexpected ways when swiping to mark done
- if (
- selectedEntityIncludedInMultiSelectedEntities &&
- !isModality('touch')
- ) {
- const index = selectedEntityData?.index ?? 0;
-
- const newSelectedEntity = entities()?.at(index);
- setSelectedEntity(newSelectedEntity);
-
- navigateThroughList({
- axis: lastMultiNavigationInput.axis,
- mode: 'step',
- });
- }
- } else if (!isModality('touch')) {
- if (isEntityLastItem()) {
- navigateThroughList({ axis: 'start', mode: 'step' });
- } else {
- navigateThroughList({ axis: 'end', mode: 'step' });
- }
- }
-
- // Check if current view filters out completed items in order to know whether to run collapse animation. More robustly we would have the list of entitites itself trigger entity removal animation when the list changes, but this is complicated by our usage of queries and virtualized lists.
- // NOTE: collapse animation is currently only enabled for touch modality, i.e. phone.
- const currentViewConfig = soupContext.viewsDataStore[selectedView()];
- const [collapseEntity] = soupContext.collapseEntitySignal;
- const shouldCollapse =
- currentViewConfig?.filters?.notificationFilter === 'notDone' &&
- collapseEntity() !== undefined &&
- isModality('touch');
-
- if (shouldCollapse) {
- // If the view hides completed items, collapse the entities first
- const collapse = collapseEntity();
- if (collapse) {
- await Promise.all(
- multiSelectEntities.map((entity) => collapse(entity.id))
- );
- }
- }
-
- for (const entity of multiSelectEntities) {
- if (handler) {
- handler(entity, {
- soupContext,
- notificationSource,
- });
- }
- const entityType = getPropertiesEntityType(entity);
- if (entityType) {
- setPropertyStatusCompleteMutation.mutate({
- entityType,
- entityId: entity.id,
- });
- }
- }
-
- setViewDataStore(selectedView(), 'multiSelectEntities', []);
-
- toast.success('Marked as done');
- }
-
- return { success: true };
- },
- {
- canExecute: (entity) => {
- // notifications
- if (entity.type === 'email' || entity.type === 'channel') return true;
-
- // property status complete (tasks have type 'document' with subType 'task')
- if (isTaskEntity(entity)) {
- // Check if current user is assigned to the task
- const currentUserId = userId();
- if (
- !isCurrentUserAssigned(
- entity as TaskEntityWithProperties,
- currentUserId
- )
- ) {
- return false;
- }
- // Check if task is not already closed
- if (isTaskClosed(entity as TaskEntityWithProperties)) {
- return false;
- }
- return true;
- }
- if (['document', 'project'].includes(entity.type)) return true;
-
- if (entityHasUnreadNotifications(notificationSource, entity)) {
- return true;
- }
- return false;
- },
- }
- );
-
- registerEntityHotkey({
- hotkey: ['e'],
- hotkeyToken: TOKENS.entity.action.markDone,
- scopeId: splitHotkeyScope,
- description: 'Mark done',
- keyDownHandler: () => {
- const entitiesForAction = getEntitiesForAction();
- if (entitiesForAction.entities.length === 0) {
- return false;
- }
-
- actionRegistry.execute(
- 'mark_as_done',
- entitiesForAction.entities.map(({ entity }) => entity)
- );
-
- return true;
- },
- canExecuteKeyDownHandler: () => {
- if (!canAccessEntityList()) return false;
- return actionRegistry.isActionEnabled(
- 'mark_as_done',
- plainSelectedEntities()
- );
- },
- displayPriority: 10,
- tags: [HotkeyTags.SelectionModification],
- });
-
- // ---------------------------------------------------------------------------
- // DELETE
- // ---------------------------------------------------------------------------
- actionRegistry.register(
- 'delete',
- async (entitiesToDelete) => {
- const prev = selectedEntity();
- const next = getNextEntity(entitiesToDelete);
- try {
- openBulkEditModal({
- view: 'delete',
- entities: entitiesToDelete,
- onFinish: () => {
- afterEntityAction(next, true);
- const splitManager = globalSplitManager();
- if (splitManager) {
- const entityIdSet = new Set(entitiesToDelete.map(({ id }) => id));
- globalRemoveFromSplitHistory(splitManager, (entry) =>
- entityIdSet.has(entry.id)
- );
- }
- },
- onCancel: () => {
- afterEntityAction(prev);
- },
- });
- } catch (err) {
- console.error('Failed to open bulk delete modal', err);
- }
- return { success: true };
- },
- {
- canExecute: (entity) => {
- // can't delete these bad boys yet.
- if (entity.type === 'channel' || entity.type === 'email') return false;
- // only delete what you own.
- return entity.ownerId === userId();
- },
- // TODO (seamus): fix the handler from the modal so that we can delete
- // some of the items. Then switch this to some.
- mode: 'every',
- }
- );
-
- registerEntityHotkey({
- hotkey: ['delete', 'backspace'],
- hotkeyToken: TOKENS.entity.action.delete,
- scopeId: splitHotkeyScope,
- description: () =>
- viewData().multiSelectEntities.length > 1
- ? 'Delete items'
- : 'Delete item',
- keyDownHandler: () => {
- const entitiesForAction = getEntitiesForAction();
- if (entitiesForAction.entities.length === 0) {
- return false;
- }
- actionRegistry.execute(
- 'delete',
- entitiesForAction.entities.map(({ entity }) => entity)
- );
- return true;
- },
- canExecuteKeyDownHandler: () =>
- isViewingList() &&
- actionRegistry.isActionEnabled('delete', plainSelectedEntities()),
-
- tags: [HotkeyTags.SelectionModification],
- displayPriority: 10,
- });
-
- createEffect(() => {
- const ref = entityListRef();
- if (!ref) return;
-
- attachEntityHotkeys(ref);
- });
-
- // ---------------------------------------------------------------------------
- // RENAME
- // ---------------------------------------------------------------------------
- actionRegistry.register(
- 'rename',
- async (entitiesToRename) => {
- const prev = selectedEntity();
- const next = getNextEntity(entitiesToRename);
- try {
- openBulkEditModal({
- view: 'rename',
- entities: entitiesToRename,
- onFinish: () => {
- afterEntityAction(next);
- },
- onCancel: () => {
- afterEntityAction(prev);
- },
- });
- } catch (err) {
- console.error('Failed to open bulk rename modal', err);
- }
- return { success: true };
- },
- {
- canExecute: (entity) => {
- if (entity.type === 'channel') {
- if (entity.channelType === ChannelTypeEnum.DirectMessage)
- return false;
-
- const currentUserId = userId();
- if (!currentUserId) return false;
-
- // Check if user is the owner
- if (entity.ownerId === currentUserId) {
- return true;
- }
-
- // Check if user is an admin by looking up channel participant data
- try {
- const channelsContext = useChannelsContext();
- const channel = channelsContext
- .channels()
- .find((c) => c.id === entity.id);
- if (channel) {
- const participant = channel.participants.find(
- (p) => p.user_id === currentUserId
- );
- if (
- participant &&
- ['admin', 'owner'].includes(participant.role)
- ) {
- return true;
- }
- }
- } catch (_err) {
- return false;
- }
-
- return false;
- }
- if (entity.type === 'email') return false;
-
- // only rename what you own.
- return entity.ownerId === userId();
- },
- }
- );
-
- registerHotkey({
- scopeId: splitHotkeyScope,
- hotkeyToken: TOKENS.entity.action.rename,
- description: () =>
- viewData().multiSelectEntities.length > 1
- ? 'Rename items'
- : 'Rename item',
- condition: () =>
- isViewingList() &&
- actionRegistry.isActionEnabled('rename', plainSelectedEntities()),
- keyDownHandler: () => {
- const entitiesForAction = getEntitiesForAction();
- if (entitiesForAction.entities.length === 0) {
- return false;
- }
- actionRegistry.execute(
- 'rename',
- entitiesForAction.entities.map(({ entity }) => entity)
- );
- return true;
- },
- tags: [HotkeyTags.SelectionModification],
- displayPriority: 10,
- });
-
- // ---------------------------------------------------------------------------
- // COPY
- // ---------------------------------------------------------------------------
- const bulkCopyMutation = createBulkCopyDssEntityMutation();
- actionRegistry.register(
- 'copy',
- async (entitiesToCopy) => {
- try {
- await bulkCopyMutation.mutateAsync({
- entities: entitiesToCopy,
- name: (name) => name,
- });
- } catch (_) {}
- return { success: true };
- },
- {
- canExecute: (entity) => {
- if (entity.type === 'channel' || entity.type === 'email') return false;
- return true;
- },
- }
- );
-
- registerHotkey({
- scopeId: splitHotkeyScope,
-
- hotkeyToken: TOKENS.entity.action.copy,
- description: () =>
- viewData().multiSelectEntities.length > 1 ? 'Copy items' : 'Copy item',
- condition: () =>
- isViewingList() &&
- actionRegistry.isActionEnabled('copy', plainSelectedEntities()),
- keyDownHandler: () => {
- const entitiesForAction = getEntitiesForAction();
- if (entitiesForAction.entities.length === 0) {
- return false;
- }
- actionRegistry.execute(
- 'copy',
- entitiesForAction.entities.map(({ entity }) => entity)
- );
- return true;
- },
- tags: [HotkeyTags.SelectionModification],
- displayPriority: 10,
- });
-
- // ---------------------------------------------------------------------------
- // MOVE TO FOLDER
- // ---------------------------------------------------------------------------
- actionRegistry.register(
- 'move_to_project',
- async (entitiesToMove) => {
- const prev = selectedEntity();
- const next = getNextEntity(entitiesToMove);
- try {
- openBulkEditModal({
- view: 'moveToProject',
- entities: entitiesToMove,
- onFinish: () => {
- afterEntityAction(next, true);
- },
- onCancel: () => {
- afterEntityAction(prev);
- },
- });
- } catch (err) {
- console.error('Failed to open bulk move modal', err);
- }
- return { success: true };
- },
- {
- canExecute: (entity) => {
- if (entity.type === 'channel' || entity.type === 'email') return false;
- return true;
- },
- }
- );
-
- registerHotkey({
- scopeId: splitHotkeyScope,
- hotkeyToken: TOKENS.entity.action.moveToFolder,
- description: () =>
- viewData().multiSelectEntities.length > 1
- ? 'Move items to folder'
- : 'Move item to folder',
- condition: () =>
- isViewingList() &&
- actionRegistry.isActionEnabled(
- 'move_to_project',
- plainSelectedEntities()
- ),
- keyDownHandler: () => {
- const entitiesForAction = getEntitiesForAction();
- if (entitiesForAction.entities.length === 0) {
- return false;
- }
- actionRegistry.execute(
- 'move_to_project',
- entitiesForAction.entities.map(({ entity }) => entity)
- );
- return true;
- },
- tags: [HotkeyTags.SelectionModification],
- displayPriority: 10,
- });
-
- const getEntityElAtIndex = (index: number) => {
- const entity = entities()?.at(index);
- if (!entity) return;
-
- return entityListRef()?.querySelector(`[data-entity-id="${entity.id}"]`);
- };
-
- const getSelectedEntity = createLazyMemo(() => {
- const index =
- entities()?.findIndex(
- ({ id }) => id === viewData()?.selectedEntity?.id
- ) ?? -1;
- if (index < 0) return;
-
- const entity = entities()?.at(index);
- if (!entity) return;
-
- return {
- index,
- entity,
- };
- });
-
- const getEntitiesForAction = createLazyMemo<{
- entities: Array<{ entity: EntityData; index: number }>;
- beforeEntity: EntityData | null;
- afterEntity: EntityData | null;
- }>(() => {
- const entityList = entities();
- if (!entityList)
- return { entities: [], beforeEntity: null, afterEntity: null };
-
- const idToIndexMap = new Map(entityList.map(({ id }, i) => [id, i]));
- let selectedEntityIndices: Array<{ entity: EntityData; index: number }> =
- [];
-
- if (viewData().multiSelectEntities.length > 0) {
- selectedEntityIndices = filterMap(
- viewData().multiSelectEntities,
- (entity) => {
- const index = idToIndexMap.get(entity.id);
- if (index === undefined) {
- return undefined;
- }
- return {
- index,
- entity,
- };
- }
- );
- } else {
- const entity = getSelectedEntity();
- if (entity) selectedEntityIndices = [entity];
- }
-
- if (selectedEntityIndices.length === 0) {
- return { entities: [], beforeEntity: null, afterEntity: null };
- }
-
- selectedEntityIndices.sort((a, b) => a.index - b.index);
-
- const firstIndex = selectedEntityIndices[0].index;
- const lastIndex =
- selectedEntityIndices[selectedEntityIndices.length - 1].index;
-
- let before = null;
- if (firstIndex === 0) {
- // If first item is at index 0, use the item after the selection as beforeId
- const afterSelectionIndex = lastIndex + 1;
- if (afterSelectionIndex < entityList.length) {
- before = entityList[afterSelectionIndex];
- }
- } else {
- before = entityList[firstIndex - 1];
- }
-
- // Calculate afterId
- let after = null;
- const afterSelectionIndex = lastIndex + 1;
- if (afterSelectionIndex < entityList.length) {
- after = entityList[afterSelectionIndex];
- }
-
- return {
- entities: selectedEntityIndices,
- beforeEntity: before,
- afterEntity: after,
- };
- });
-
- // the full info with indices and neighbors is great but we also need to
- // flatten back to the plain entities a lot - so just memoize.
- const plainSelectedEntities = createLazyMemo(() => {
- return getEntitiesForAction().entities.map(({ entity }) => entity);
- });
-
- const isEntityLastItem = createLazyMemo(() => {
- const entityList = entities();
- if (!entityList) return false;
-
- const selectedEntity = getSelectedEntity();
- if (!selectedEntity) return false;
-
- return selectedEntity.index >= entityList.length - 1;
- });
-
- const calculateEntityIndex = (
- startIndex: number,
- { axis, mode }: NavigationInput
- ) => {
- let index = startIndex;
-
- const maxLength = (entities()?.length || 1) - 1;
- if (mode === 'jump') {
- if (axis === 'start') {
- // setIndex(0);
- index = 0;
- } else {
- // setIndex(maxLength);
- index = maxLength;
- }
- } else {
- if (axis === 'start') {
- // setIndex(Math.max(index() - 1, 0));
- index = Math.max(index - 1, 0);
- } else {
- // setIndex(Math.min(index() + 1, maxLength));
- index = Math.min(index + 1, maxLength);
- }
- }
-
- return index;
- };
-
- const navigateThroughList = async ({
- axis,
- mode,
- }: NavigationInput): Promise<NavigationResult> => {
- let index = calculateEntityIndex(getSelectedEntity()?.index ?? -1, {
- axis,
- mode,
- });
-
- setViewDataStore(selectedView(), 'hasUserInteractedEntity', true);
-
- const entityEl = entityListRef()?.querySelector('[data-entity]');
- const scrollParent = getScrollParent(entityEl);
- const getAdjecentEl = async () => {
- const virtualizer = virtualizerHandle();
- const virtualItems = virtualizer?.getVirtualItems() || [];
- const start = virtualItems[0]?.index;
- const end = virtualItems.at(-1)?.index ?? 0;
-
- if (index < start) {
- virtualizer?.scrollToIndex(index, { align: 'start' });
- } else if (index > end) {
- virtualizer?.scrollToIndex(index, { align: 'end' });
- }
-
- if (mode === 'jump') {
- await new Promise<true>((resolve) =>
- requestAnimationFrame(() => {
- requestAnimationFrame(() => {
- resolve(true);
- });
- })
- );
- }
-
- // Logic fails Entity el dismounts due to EntityList fetching new page
- // *ReSelectEntity effect logic covers this failure
- // should refactor
- const newSelectedEntityEl = getEntityElAtIndex(index);
-
- const selectedEntity = entities()?.at(index);
- if (selectedEntity) {
- if (
- splitHandle.content().type !== 'component' &&
- splitHandle.content().type !== 'project'
- ) {
- openEntityInSplitFromUnifiedList(selectedEntity, {
- splitHandle,
- });
- }
- batch(() => {
- setSelectedEntity(selectedEntity);
- });
- }
-
- if (
- scrollParent instanceof Element &&
- newSelectedEntityEl &&
- mode === 'step'
- ) {
- scrollToKeepGap({
- container: scrollParent,
- target: newSelectedEntityEl.parentElement!,
- align: axis === 'start' ? 'top' : 'bottom',
- gap: ENTITY_HEIGHT,
- });
- }
-
- return {
- element: newSelectedEntityEl,
- entity: selectedEntity,
- };
- };
-
- const { element: adjacentEl, entity } = await getAdjecentEl();
-
- // Logic fails to focus entity element due to EntityList shuffling items after fetching new page
- // *ReSelectEntity effect logic covers this failure
- // should refactor
- if (adjacentEl instanceof HTMLElement) {
- adjacentEl.focus();
- setTimeout(() => adjacentEl.focus());
- return {
- success: true,
- entity,
- };
- }
- return {
- success: false,
- entity,
- };
- };
-
- soupContext._setNavigateThroughList(navigateThroughList);
-
- const isEntitySelected = (entityID: string) => {
- return (
- viewData()?.multiSelectEntities.find((e) => e.id === entityID) !==
- undefined
- );
- };
-
- const toggleEntity = (entity: EntityData) => {
- setViewDataStore(selectedView(), 'multiSelectEntities', (s) => {
- if (isEntitySelected(entity.id)) {
- return s.filter((e) => e.id !== entity.id);
- }
- return s.concat(entity);
- });
- };
-
- const navigateAndSelectEntity = async (input: NavigationInput) => {
- const { success, entity } = await navigateThroughList(input);
-
- if (!success || !entity) return;
-
- toggleEntity(entity);
- };
-
- const handleNavigationSelection = (input: NavigationInput) => {
- const selectedEntity = getSelectedEntity();
- const currentIndex = selectedEntity?.index ?? -1;
- const nextIndex = calculateEntityIndex(currentIndex, input);
-
- const nextEntity = entities()?.at(nextIndex);
- if (!nextEntity) return true;
-
- if (!selectedEntity) {
- navigateAndSelectEntity(input);
- return true;
- }
-
- // If multiSelectEntities is empty, select current item first without moving
- const multiSelectEntities = viewData()?.multiSelectEntities || [];
- if (multiSelectEntities.length === 0) {
- toggleEntity(selectedEntity.entity);
- return true;
- }
-
- if (
- !isEntitySelected(selectedEntity.entity.id) &&
- !isEntitySelected(nextEntity.id)
- ) {
- toggleEntity(selectedEntity.entity);
- navigateAndSelectEntity(input);
-
- return true;
- }
-
- if (isEntitySelected(nextEntity.id)) {
- toggleEntity(selectedEntity.entity);
- navigateThroughList(input);
- return true;
- }
-
- navigateAndSelectEntity(input);
-
- return true;
- };
-
- registerHotkey({
- scopeId: splitHotkeyScope,
- description: () => {
- return konsoleOpen() ? 'Close command menu' : 'Open command menu';
- },
- hotkey: 'cmd+k',
- condition: () => !konsoleOpen() && isViewingList(),
- keyDownHandler: (e) => {
- e?.preventDefault();
- const multiSelectEntities = viewData().multiSelectEntities;
-
- const hasSelection = multiSelectEntities.length > 0;
-
- if (hasSelection) {
- setKonsoleMode('SELECTION_MODIFICATION');
- const selectionIndex = searchCategories.getCategoryIndex('Selection');
-
- if (selectionIndex === undefined) return false;
-
- setCommandCategoryIndex(selectionIndex);
-
- searchCategories.showCategory('Selection');
-
- setKonsoleContextInformation({
- multiSelectEntities: multiSelectEntities.slice(),
- });
-
- toggleKonsoleVisibility();
- return true;
- }
- searchCategories.hideCategory('Selection');
- resetCommandCategoryIndex();
- resetKonsoleMode();
- return false;
- },
- displayPriority: 10,
- hide: konsoleOpen,
- runWithInputFocused: true,
- });
-
- function stepDown() {
- navigateThroughList({ axis: 'end', mode: 'step' });
- return true;
- }
-
- registerEntityHotkey({
- hotkey: ['j'],
- scopeId: splitHotkeyScope,
- description: 'Down',
- hotkeyToken: TOKENS.entity.step.end,
- keyDownHandler: stepDown,
- canExecuteKeyDownHandler: () => canAccessEntityList(),
- hide: true,
- });
-
- registerEntityHotkey({
- hotkey: ['arrowdown'],
- scopeId: splitHotkeyScope,
- description: 'Down',
- hotkeyToken: TOKENS.entity.step.end,
- keyDownHandler: stepDown,
- canExecuteKeyDownHandler: () => isViewingList(),
- hide: true,
- });
-
- registerEntityHotkey({
- hotkey: ['shift+arrowdown', 'shift+j'],
- scopeId: splitHotkeyScope,
- description: 'Select down',
- hotkeyToken: TOKENS.entity.select.end,
- keyDownHandler: () => {
- const navigationInput: NavigationInput = { axis: 'end', mode: 'step' };
- lastMultiNavigationInput = navigationInput;
- return handleNavigationSelection(navigationInput);
- },
- canExecuteKeyDownHandler: () => canAccessEntityList(),
- hide: true,
- });
-
- function stepUp() {
- navigateThroughList({ axis: 'start', mode: 'step' });
- return true;
- }
-
- registerEntityHotkey({
- hotkey: ['k'],
- scopeId: splitHotkeyScope,
- hotkeyToken: TOKENS.entity.step.start,
- description: 'Up',
- keyDownHandler: stepUp,
- canExecuteKeyDownHandler: () => canAccessEntityList(),
- hide: true,
- });
-
- registerEntityHotkey({
- hotkey: ['arrowup'],
- scopeId: splitHotkeyScope,
- hotkeyToken: TOKENS.entity.step.start,
- description: 'Up',
- keyDownHandler: stepUp,
- canExecuteKeyDownHandler: () => isViewingList(),
- hide: true,
- });
-
- registerEntityHotkey({
- hotkey: ['shift+arrowup', 'shift+k'],
- scopeId: splitHotkeyScope,
- hotkeyToken: TOKENS.entity.select.start,
- description: 'Select up',
- keyDownHandler: () => {
- const navigationInput: NavigationInput = { axis: 'start', mode: 'step' };
- lastMultiNavigationInput = navigationInput;
- return handleNavigationSelection(navigationInput);
- },
- canExecuteKeyDownHandler: () => canAccessEntityList(),
- hide: true,
- });
- registerEntityHotkey({
- hotkey: ['home'],
- scopeId: splitHotkeyScope,
- hotkeyToken: TOKENS.entity.jump.home,
- description: 'Go to top of list',
- keyDownHandler: () => {
- navigateThroughList({ axis: 'start', mode: 'jump' });
- return true;
- },
- canExecuteKeyDownHandler: () => canAccessEntityList(),
- hide: true,
- });
- const {
- registerHotkeyReturn: topGScope,
- globalRegisterHotkeyReturn: topGScopeGlobal,
- } = registerEntityHotkey({
- hotkey: ['g'],
- scopeId: splitHotkeyScope,
- description: 'Go to top of list',
- keyDownHandler: () => true,
- activateCommandScope: true,
- canExecuteKeyDownHandler: () => canAccessEntityList(),
- hide: true,
- });
- registerEntityHotkey({
- hotkey: ['g'],
- scopeId: topGScope.commandScopeId,
- globalCommandScope: topGScopeGlobal.commandScopeId,
- description: 'Go to top of list',
- keyDownHandler: () => {
- navigateThroughList({ axis: 'start', mode: 'jump' });
- return true;
- },
- canExecuteKeyDownHandler: () => canAccessEntityList(),
- });
- registerEntityHotkey({
- hotkey: ['shift+g', 'end'],
- scopeId: splitHotkeyScope,
- hotkeyToken: TOKENS.entity.jump.end,
- description: 'Go to bottom of list',
- keyDownHandler: () => {
- navigateThroughList({ axis: 'end', mode: 'jump' });
- return true;
- },
- canExecuteKeyDownHandler: () => canAccessEntityList(),
- hide: true,
- });
-
- registerEntityHotkey({
- hotkey: ['h', 'arrowleft'],
- scopeId: splitHotkeyScope,
- description: 'Navigate to parent context',
- hotkeyToken: TOKENS.unifiedList.navigation.parent,
- keyDownHandler: () => {
- const parentContext = getParentContext();
-
- if (!parentContext) {
- return false;
- }
-
- const parentDomRef = parentContext.domRef();
- if (parentContext === activeContext()) {
- return true;
- }
-
- if (parentDomRef) {
- setActiveContext(parentContext);
- parentDomRef.focus();
- return true;
- }
-
- return false;
- },
- canExecuteKeyDownHandler: () => {
- return isViewingList();
- },
- registrationType: 'add',
- handlerPriority: HOTKEY_PRIORITY_LOW,
- hide: true,
- });
-
- registerEntityHotkey({
- hotkey: ['l', 'arrowright'],
- scopeId: splitHotkeyScope,
- description: 'Navigate to child context',
- hotkeyToken: TOKENS.unifiedList.navigation.child,
- keyDownHandler: () => {
- const childContext = getChildContext();
- if (!childContext) return false;
-
- const childDomRef = childContext.domRef();
-
- if (!childDomRef) {
- return false;
- }
-
- if (childContext === activeContext()) {
- return false;
- }
-
- if (childDomRef) {
- setActiveContext(childContext);
- childDomRef.setAttribute('data-allow-focus-in-preview', '');
- childDomRef.focus();
- return true;
- }
- return false;
- },
- canExecuteKeyDownHandler: () => {
- return isViewingList() && getChildContext() !== undefined;
- },
- registrationType: 'add',
- handlerPriority: HOTKEY_PRIORITY_LOW,
- hide: true,
- });
-
- const splitIsUnifiedList = createMemo(
- () => splitHandle.content().id === 'unified-list'
- );
-
- registerEntityHotkey({
- hotkey: ['enter'],
- hotkeyToken: TOKENS.entity.open,
- scopeId: splitHotkeyScope,
- description: 'Open',
- hide: true,
- keyDownHandler: () => {
- const entity = getSelectedEntity()?.entity;
- if (!entity) return false;
-
- const contentHitData = isSearchEntity(entity)
- ? entity.search.contentHitData
- : undefined;
- // Only navigate to specific location if there's exactly one hit
- const location =
- contentHitData?.length === 1 ? contentHitData[0]?.location : undefined;
-
- openEntityInSplitFromUnifiedList(entity, {
- splitHandle,
- location,
- });
- return true;
- },
- canExecuteKeyDownHandler: ({ keyboardEvent }) => {
- if (!isViewingList()) return false;
-
- if (keyboardEvent) {
- const target = getActualTarget(keyboardEvent);
-
- if (entityListRef()?.contains(target)) {
- return true;
- }
-
- if (isInteractiveElement(target)) {
- return false;
- }
- }
- return true;
- },
- displayPriority: 4,
- registrationType: 'add',
- });
-
- registerEntityHotkey({
- hotkey: ['cmd+enter'],
- scopeId: splitHotkeyScope,
- description: 'Focus Preview',
- keyDownHandler: () => {
- const [preview] = previewState;
-
- const entity = getSelectedEntity()?.entity;
- if (!entity) return false;
-
- if (preview()) {
- // focus inside preview block
- const blockEl = document.getElementById(`block-${entity.id}`);
- if (blockEl) {
- // TODO: use state instead to determine when preview block can recieve focus
- blockEl.setAttribute('data-allow-focus-in-preview', '');
-
- blockEl.focus();
- const getEnterCommand = () => {
- const currentActiveScope = activeScope();
- if (!currentActiveScope) return undefined;
- const activeScopeNode = hotkeyScopeTree.get(currentActiveScope);
- if (!activeScopeNode) return undefined;
- if (activeScopeNode?.type !== 'dom') return;
- const dom = getScopeElement(currentActiveScope);
- if (!dom) return undefined;
- const closestBlockScope = dom.closest(`[id="block-${entity.id}"]`);
- if (
- !closestBlockScope ||
- !(closestBlockScope instanceof HTMLElement)
- )
- return;
- const scopeId = closestBlockScope.dataset.hotkeyScope;
- if (!scopeId) return undefined;
-
- return getHotkeyCommand(scopeId, 'enter');
- };
- const command = getEnterCommand();
- if (command) {
- runCommand(command);
- }
- }
- return true;
- }
-
- openEntityInSplitFromUnifiedList(entity, {
- splitHandle,
- });
- return true;
- },
- canExecuteKeyDownHandler: () => isViewingList(),
- displayPriority: 4,
- });
- registerEntityHotkey({
- hotkey: ['x'],
- scopeId: splitHotkeyScope,
- description: 'Toggle select item',
- keyDownHandler: () => {
- const entity = getSelectedEntity();
- if (!entity) return false;
- toggleEntity(entity.entity);
- return true;
- },
- canExecuteKeyDownHandler: () => isViewingList(),
- displayPriority: 10,
- });
-
- const clearMultiCondition: () => boolean = () =>
- isViewingList() && viewData().multiSelectEntities.length > 0;
- const closeSpotlightCondition = () => splitHandle.isSpotLight();
- const goHomeCondition = () => !splitIsUnifiedList();
- const closeSplitCondition = () => splitIsUnifiedList() && getSplitCount() > 1;
- const escapeDescription = () => {
- if (clearMultiCondition()) {
- return 'Clear multi selection';
- }
- if (closeSpotlightCondition()) {
- return 'Close spotlight';
- }
- if (closeSplitCondition()) {
- return 'Close split';
- }
- if (goHomeCondition()) {
- return 'Go home';
- }
- return '';
- };
- registerHotkey({
- hotkey: ['escape'],
- scopeId: splitHotkeyScope,
- description: escapeDescription,
- condition: () =>
- clearMultiCondition() ||
- closeSpotlightCondition() ||
- closeSplitCondition() ||
- goHomeCondition(),
- keyDownHandler: () => {
- if (clearMultiCondition()) {
- const length = viewData().multiSelectEntities.length;
- setViewDataStore(selectedView(), 'multiSelectEntities', []);
- return length > 1;
- }
- if (closeSpotlightCondition()) {
- splitHandle.toggleSpotlight();
- return true;
- }
- if (closeSplitCondition()) {
- splitHandle.close();
- return true;
- }
- if (goHomeCondition()) {
- splitHandle.replace({
- next: { type: 'component', id: 'unified-list' },
- referredFrom: 'unified-list',
- });
- return true;
- }
- return false;
- },
- });
-}
-
-const useAllViews = ({
- selectedViewSignal,
-}: {
- selectedViewSignal: Signal<string>;
-}): ReturnType<typeof createStore<ViewDataMap>> => {
- const [selectedView, setSelectedView] = selectedViewSignal;
- const initialState: ViewDataMap = {};
- for (const [view, viewProps] of Object.entries(VIEWCONFIG_DEFAULTS)) {
- initialState[view] = createViewData(view as DefaultView, viewProps);
- }
-
- const [viewsData, setViewsData] = createStore(initialState);
-
- // add all default views
- const savedViews = useQuery(() => ({
- queryKey: ['savedViews'],
- queryFn: async () => {
- const resp = await storageServiceClient.views.getSavedViews();
-
- if (isErr(resp)) {
- throw Error(resp[0][0].message);
- }
- return resp[1];
- },
- }));
-
- createEffect(
- on(
- () => savedViews.data,
- (data) => {
- if (!data) return;
-
- const savedViewConfigs = data.views.map((view) => {
- const config = view.config as ViewConfigBase;
-
- return createViewData(view.name as DefaultView, {
- id: view.id,
- view: view.name as DefaultView,
- display: { ...VIEWCONFIG_BASE.display, ...config.display },
- filters: { ...VIEWCONFIG_BASE.filters, ...config.filters },
- sort: {
- ...VIEWCONFIG_BASE.sort,
- ...config.sort,
- },
- });
- });
- const savedViewsData: ViewDataMap = Object.fromEntries(
- savedViewConfigs.map((view) => [view.id, view])
- );
-
- // Filter viewsData to exclude items that are not in savedViewConfigs, except for default views
- const savedViewIds = new Set(savedViewConfigs.map((view) => view.id));
- const filteredViewsData = Object.fromEntries(
- Object.entries(viewsData).filter(
- ([viewId, viewData]) =>
- savedViewIds.has(viewId) ||
- DEFAULT_VIEW_IDS_SET.has(viewId as DefaultView) ||
- viewData.viewType !== undefined
- )
- );
-
- // Deduplicate items with same id, prioritizing savedViewConfigs over filteredDefaultViews
- const uniqueViews: ViewDataMap = {
- ...filteredViewsData,
- ...savedViewsData,
- };
- if (!uniqueViews[selectedView()]) {
- setSelectedView(DEFAULT_VIEW_ID);
- }
-
- setViewsData(reconcile(uniqueViews));
- }
- )
- );
-
- return [viewsData, setViewsData] as const;
-};
-
-let globalKeyboardEvent: KeyboardEvent | undefined;
-
-type ExecuteKeyDownHandlerCallback = (props: {
- keyboardEvent?: KeyboardEvent;
-}) => boolean;
-
-/**
- *
- * Registers entity hotkeys to global scope and split panel scope. When global hotkey is fired, runs hotkey command from active split panel scope.
- *
- */
-function registerEntityHotkey(
- opts: Omit<Parameters<typeof registerHotkey>[0], 'condition'> & {
- canExecuteKeyDownHandler?: ExecuteKeyDownHandlerCallback;
- globalCommandScope?: string;
- }
-): {
- registerHotkeyReturn: {
- commandScopeId: string;
- };
- globalRegisterHotkeyReturn: {
- commandScopeId: string;
- };
-} {
- onCleanup(() => {
- globalKeyboardEvent = undefined;
- });
-
- // scoped hotkey
- const registerHotkeyReturn = registerHotkey({
- ...opts,
- keyDownHandler: (e) => {
- const canExecuteKeyDownHandler = () => {
- if (!opts.canExecuteKeyDownHandler) return true;
- return opts.canExecuteKeyDownHandler({
- keyboardEvent: e ?? globalKeyboardEvent,
- });
- };
-
- if (canExecuteKeyDownHandler()) {
- return opts.keyDownHandler(e);
- }
-
- return false;
- },
- condition: undefined,
- });
- // global hotkey to run active split scope command
- const globalRegisterHotkeyReturn = registerHotkey({
- ...opts,
- scopeId: opts.globalCommandScope ? opts.globalCommandScope : 'global',
- hotkeyToken: undefined,
- tags: undefined,
- condition: undefined,
- registrationType: undefined,
- handlerPriority: undefined,
- keyDownHandler: (event) => {
- globalKeyboardEvent = event;
- queueMicrotask(() => {
- globalKeyboardEvent = undefined;
- });
-
- if (event) {
- const target = event.target as HTMLElement;
- if (
- target.closest(
- `
- [role="dialog"],
- [role="alertdialog"],
- [data-modal="true"],
- .z-modal,
- .z-modal-overlay
- `
- )
- ) {
- return false;
- }
- }
-
- const currentActiveSplitId = globalSplitManager()?.activeSplitId();
-
- const getCommand = () => {
- const soupContext = splitIdSoupContextMapper.get(currentActiveSplitId!);
- const activeSoupContext = soupContext?.activeContextSignal[0]?.();
- const splitScope = activeSoupContext?.domRef();
- if (!splitScope || !(splitScope instanceof HTMLElement)) return;
- const scopeId = splitScope.dataset.hotkeyScope;
- if (!scopeId || !opts.hotkey) return undefined;
-
- return getHotkeyCommand(
- scopeId,
- // @ts-expect-error
- opts.hotkey[0]
- );
- };
- const command = getCommand();
- if (!command) return false;
-
- runCommand(command);
- return false;
- },
- });
-
- return {
- registerHotkeyReturn,
- globalRegisterHotkeyReturn,
- } as any;
-}
diff --git a/js/app/packages/app/component/UnifiedEntityActions.tsx b/js/app/packages/app/component/UnifiedEntityActions.tsx
deleted file mode 100644
index ea85903bea..0000000000
--- a/js/app/packages/app/component/UnifiedEntityActions.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { type EntityData, isEntityData } from '@macro-entity';
-import type { Component } from 'solid-js';
-
-export type EntityActionType =
- | 'mark_as_done'
- | 'delete'
- | 'rename'
- | 'move_to_project'
- | 'copy';
-
-export type EntityActionResult = {
- success: boolean;
- failedEntities?: EntityData[];
- message?: string;
-};
-
-export type EntityActionHandler = (
- entities: EntityData[]
-) => Promise<EntityActionResult>;
-
-export type EntityActionConfig = {
- /** Optional label for the action */
- label?: string;
- /** Optional icon component */
- icon?: Component;
- /**
- * Optional condition to run over an entity to see if the action can be performed
- * on that entity.
- */
- canExecute?: (entity: EntityData) => boolean;
- /**
- * Mode for bulk version of action. If 'every' then all entities must pass
- * for the action to register as enabled. If 'some' then the action can be
- * enabled if a single entity passes the test. Only meaningful if canExecute
- * is also provided. Default is 'every'
- */
- mode?: 'some' | 'every';
-};
-
-export type EntityActionRegistry = {
- register: (
- type: EntityActionType,
- handler: EntityActionHandler,
- config?: EntityActionConfig
- ) => void;
- getHandler: (type: EntityActionType) => EntityActionHandler | undefined;
- getConfig: (type: EntityActionType) => EntityActionConfig | undefined;
- execute: (
- type: EntityActionType,
- entities: EntityData | EntityData[]
- ) => Promise<EntityActionResult>;
- isActionEnabled: (
- type: EntityActionType,
- entities: EntityData | EntityData[]
- ) => boolean;
- getAvailableActions: () => EntityActionType[];
- has: (action: EntityActionType) => boolean;
-};
-
-export function createEntityActionRegistry(): EntityActionRegistry {
- const actions = new Map<EntityActionType, EntityActionHandler>();
- const configs = new Map<EntityActionType, EntityActionConfig>();
-
- const register = (
- type: EntityActionType,
- handler: EntityActionHandler,
- config?: EntityActionConfig
- ): void => {
- actions.set(type, handler);
- if (config) {
- configs.set(type, config);
- }
- };
-
- const getHandler = (
- type: EntityActionType
- ): EntityActionHandler | undefined => {
- return actions.get(type);
- };
-
- const getConfig = (
- type: EntityActionType
- ): EntityActionConfig | undefined => {
- return configs.get(type);
- };
-
- const execute = async (
- type: EntityActionType,
- entities: EntityData | EntityData[]
- ): Promise<EntityActionResult> => {
- const handler = actions.get(type);
- if (!handler) {
- return { success: false, message: `Unknown action: ${type}` };
- }
-
- const result = await handler(
- Array.isArray(entities) ? entities : [entities]
- );
-
- if (typeof result === 'boolean') {
- return { success: result };
- } else if (result && typeof result === 'object') {
- return result;
- }
- return { success: true };
- };
-
- const isActionEnabled = (
- type: EntityActionType,
- entities: EntityData | EntityData[]
- ): boolean => {
- const { canExecute, mode } = configs.get(type) ?? {};
- if (!canExecute) return true;
- if (Array.isArray(entities)) {
- if (mode === 'some') {
- return entities.some(canExecute);
- } else {
- return entities.every(canExecute);
- }
- } else if (isEntityData(entities)) {
- return canExecute(entities);
- }
- return false;
- };
-
- const getAvailableActions = (): EntityActionType[] => {
- return Array.from(actions.keys());
- };
-
- return {
- register,
- getHandler,
- getConfig,
- execute,
- isActionEnabled: isActionEnabled,
- getAvailableActions,
- has: (action) => actions.has(action),
- };
-}
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
deleted file mode 100644
index 7292394778..0000000000
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ /dev/null
@@ -1,2321 +0,0 @@
-import {
- useGlobalBlockOrchestrator,
- useGlobalNotificationSource,
-} from '@app/component/GlobalAppState';
-import {
- explicitNoiseFilter,
- noiseFilter,
- signalFilter,
-} from '@app/component/soupFilters';
-import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
-import { codeFileExtensions } from '@block-code/util/languageSupport';
-import { ChannelTypeEnum } from '@service-comms/client';
-import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
-import { DeprecatedButton } from '@core/component/FormControls/DeprecatedButton';
-import DropdownMenu from '@core/component/FormControls/DropdownMenu';
-import { SegmentedControl } from '@core/component/FormControls/SegmentControls';
-import { ToggleButton } from '@core/component/FormControls/ToggleButton';
-import { ToggleSwitch } from '@core/component/FormControls/ToggleSwitch';
-import { ContextMenuContent, MenuSeparator } from '@core/component/Menu';
-import { useTaskProperties } from '@core/component/Properties/hooks';
-import { getSuggestedProperties } from '@core/component/Properties/utils';
-import { RecipientSelector } from '@core/component/RecipientSelector';
-import { toast } from '@core/component/Toast/Toast';
-import {
- blockAcceptsFileExtension,
- fileTypeToBlockName,
-} from '@core/constant/allBlocks';
-import {
- ENABLE_PROPERTY_DISPLAY,
- ENABLE_PROPERTY_FILTER,
- ENABLE_SOUP_FROM_FILTER,
- ENABLE_TASKS_TABS,
-} from '@core/constant/featureFlags';
-import { useEmailLinksStatus } from '@core/email-link';
-import { registerHotkey } from '@core/hotkey/hotkeys';
-import { TOKENS } from '@core/hotkey/tokens';
-import { isMobile } from '@core/mobile/isMobile';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
-import { arrayEquals } from '@core/util/compareUtils';
-import { debouncedDependent } from '@core/util/debounce';
-import { fuzzyMatch } from '@core/util/fuzzy';
-import CheckIcon from '@icon/bold/check-bold.svg';
-import SearchIcon from '@icon/regular/magnifying-glass.svg?component-solid';
-import LoadingSpinner from '@icon/regular/spinner.svg?component-solid';
-import XIcon from '@icon/regular/x.svg?component-solid';
-import { ContextMenu } from '@kobalte/core/context-menu';
-import {
- createDssInfiniteQuery,
- createFilterComposer,
- createProjectFilterFn,
- createSort,
- createUnifiedInfiniteList,
- createUnifiedSearchInfiniteQuery,
- Entity,
- type EntityData,
- type EntityFilter,
- type ExpandedEntityType,
- importantFilterFn,
- isTaskEntity,
- notDoneFilterFn,
- type SearchLocation,
- type SortOption,
- sortByCreatedAt,
- sortByUpdatedAt,
- sortByViewedAt,
- unreadFilterFn,
- type WithNotification,
- type WithSearch,
-} from '@macro-entity';
-import { usePropertyEditorHotkeys } from '../component/property-edit-modal/hooks/usePropertyEditorHotkeys';
-import {
- getMetadata,
- isChannelMention,
- isChannelMessageReply,
- isChannelMessageSend,
- tryToTypedNotification,
- type UnifiedNotification,
- useNotificationsForEntity,
-} from '@notifications';
-import type { SearchArgs } from '@service-search/client';
-import type {
- ChannelFilters,
- ChatFilters,
- DocumentFilters,
- EmailFilters,
- ProjectFilters,
- UnifiedSearchIndex,
- UnifiedSearchRequestFilters,
-} from '@service-search/generated/models';
-import type {
- GetItemsSoupParams,
- PostSoupRequest,
-} from '@service-storage/generated/schemas';
-import stringify from 'json-stable-stringify';
-import {
- type Accessor,
- batch,
- createEffect,
- createMemo,
- createRenderEffect,
- createRoot,
- createSelector,
- createSignal,
- For,
- mergeProps,
- on,
- onCleanup,
- onMount,
- type ParentProps,
- type Setter,
- Show,
- type Signal,
- Suspense,
-} from 'solid-js';
-import {
- createStore,
- produce,
- type SetStoreFunction,
- unwrap,
-} from 'solid-js/store';
-import {
- ENTITY_HEIGHT,
- type EntityClickHandler,
- type EntityPointerDownHandler,
- EntityWithEverything,
-} from '../../macro-entity/src/components/EntityWithEverything';
-import {
- resetCommandCategoryIndex,
- searchCategories,
- setCommandCategoryIndex,
- setKonsoleContextInformation,
-} from './command/KonsoleItem';
-import {
- resetKonsoleMode,
- setKonsoleMode,
- toggleKonsoleVisibility,
-} from './command/state';
-import { EntityActionsMenuItems } from './EntityActionsMenuItems';
-import { EntityModal } from './EntityModal/EntityModal';
-import { EntitySelectionToolbarModal } from './EntitySelectionToolbarModal';
-import { EntityRow, EntityRowProvider } from './mobile/EntityRow';
-import { PropertyDisplayControl } from './PropertyDisplayControl';
-import { PropertyFilterControl } from './PropertyFilterControl';
-import type { PropertyFilter } from './PropertyFilterTypes';
-import { useUpsertSavedViewMutation } from './Soup';
-import { openEntityInSplitFromUnifiedList } from './soupContextHelpers';
-import {
- SplitToolbarLeft,
- SplitToolbarRight,
-} from './split-layout/components/SplitToolbar';
-import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
-import {
- type DisplayOptions,
- type DocumentTypeFilter,
- type FilterOptions,
- isConfigEqual,
- KNOWN_FILE_TYPES,
- type SortOptions,
- type SystemSortOption,
- VIEWCONFIG_BASE,
- VIEWCONFIG_DEFAULTS_IDS_ENUM,
- VIEWCONFIG_FILTER_DOCUMENT_TYPE_FILTER,
- type ViewConfigBase,
- type ViewData,
-} from './ViewConfig';
-import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
-
-const SEARCH_SERVICE_DEBOUNCE_MS = 300;
-const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 20;
-
-const NIL_UUID = '00000000-0000-0000-0000-000000000000';
-
-const FILE_TYPE_DISPLAY_LABELS: Record<DocumentTypeFilter, string> = {
- md: 'NOTE',
- pdf: 'PDF',
- canvas: 'CANVAS',
- code: 'CODE',
- image: 'IMAGE',
- unknown: 'OTHER',
-};
-
-const sortOptions = [
- {
- value: 'viewed_at',
- label: 'Viewed',
- sortFn: sortByViewedAt,
- },
- {
- value: 'updated_at',
- label: 'Updated',
- sortFn: sortByUpdatedAt,
- },
- {
- value: 'created_at',
- label: 'Created',
- sortFn: sortByCreatedAt,
- },
-] satisfies SortOption<EntityData, SystemSortOption>[];
-
-export type UnifiedListViewProps = {
- defaultFilterOptions?: Partial<FilterOptions>;
- defaultSortOptions?: Partial<SortOptions>;
- defaultDisplayOptions?: Partial<DisplayOptions>;
- hideToolbar?: boolean;
-};
-export function UnifiedListView(props: UnifiedListViewProps) {
- const [contextAndModalState, setContextAndModalState] = createStore<{
- modalOpen: boolean;
- modalView: 'rename' | 'moveToProject';
- contextMenuOpen: boolean;
- selectedEntity: WithNotification<EntityData> | undefined;
- prevSelectedEntity: WithNotification<EntityData> | undefined;
- }>({
- modalOpen: false,
- modalView: 'rename',
- contextMenuOpen: false,
- selectedEntity: undefined,
- prevSelectedEntity: undefined,
- });
-
- const [localEntityListRef, setLocalEntityListRef] = createSignal<
- HTMLDivElement | undefined
- >();
-
- const defaultFilterOptions = mergeProps(
- VIEWCONFIG_BASE.filters,
- props.defaultFilterOptions
- );
- const defaultSortOptions = mergeProps(
- VIEWCONFIG_BASE.sort,
- props.defaultSortOptions
- );
- const defaultDisplayOptions = mergeProps(
- VIEWCONFIG_BASE.display,
- props.defaultDisplayOptions,
- // When the toolbar is hidden (e.g. `Soup`'s topbar is used instead), users
- // have no in-view way to toggle this on. Default it to on so unread dots
- // are visible in the list.
- props.hideToolbar ? { showUnreadIndicator: true } : {}
- );
-
- const splitContext = useSplitPanelOrThrow();
- const { isPanelActive, soupContext, previewState } = splitContext;
- const [preview] = previewState;
- const {
- viewsDataStore: viewsData,
- setViewDataStore,
- selectedView,
- virtualizerHandleSignal: [virtualizerHandle, setVirtualizerHandle],
- entityListRefSignal: [, setEntityListRef],
- entitiesSignal: [entities_, setEntities],
- emailViewSignal: [emailView],
- activeContextSignal: [activeSoupContext, setActiveSoupContext],
- } = soupContext;
-
- // Properties for task entities
- const taskPropertiesStore = useTaskProperties(entities_);
-
- const view = createMemo(() => viewsData[selectedView()]);
- const selectedEntity = createMemo(() => view()?.selectedEntity);
-
- const entityById = createMemo(() => {
- const list = entities_() ?? [];
- const map = new Map<string, EntityData>();
- for (const entity of list as any[]) {
- if (entity?.id) map.set(entity.id, entity);
- }
- return map;
- });
-
- const { isKeypressActive } = useIsKeyPressActive();
-
- const setSelectedEntity = (entity: EntityData | undefined) => {
- setViewDataStore(
- selectedView(),
- produce((state) => {
- if (!state) return;
- state.selectedEntity = entity;
- })
- );
- };
- const setSelectedEntityFromMouse = (entity: EntityData | undefined) => {
- if (isKeypressActive()) return;
-
- setViewDataStore(
- selectedView(),
- produce((state) => {
- if (!state) return;
- state.selectedEntity = entity;
- })
- );
- };
-
- const entityListResetScroll = () => {
- setSelectedEntity(entities_()?.at(0));
- virtualizerHandle()?.scrollToOffset(0);
- };
-
- const rawSearchText = createMemo<string>(() => view()?.searchText ?? '');
- const searchText = createMemo(() => rawSearchText()?.trim() ?? '');
-
- // Track entity list ref changes
- createEffect(
- on(
- [localEntityListRef, () => entities_()?.at(0), searchText],
- ([localEntityListRef, firstEntity]) => {
- if (!localEntityListRef) return;
- setEntityListRef(localEntityListRef);
-
- if (view()?.hasUserInteractedEntity) return;
- if (isTouchDevice()) return;
- if (!firstEntity) return;
-
- setSelectedEntity(firstEntity);
- }
- )
- );
-
- // Stable key for filter state - changes trigger selection reset
- const filterKey = createMemo(() =>
- stringify({ viewId: selectedView(), filters: view()?.filters })
- );
-
- // Reset selection and scroll when filters change
- createEffect(
- on(
- filterKey,
- () => {
- if (isTouchDevice()) return;
-
- batch(() => {
- setViewDataStore(selectedView(), 'selectedEntity', undefined);
- setViewDataStore(selectedView(), 'hasUserInteractedEntity', false);
- });
- virtualizerHandle()?.scrollToIndex(0);
- },
- { defer: true }
- )
- );
-
- // Auto-select first entity when no selection exists
- createEffect(
- on(entities_, () => {
- if (isTouchDevice()) return;
- const list = entities_() ?? [];
- const first = list.at(0);
- if (!first) return;
-
- const current = selectedEntity();
- if (!current || !entityById().has(current.id)) {
- setSelectedEntity(first);
- }
- })
- );
-
- const notificationFilter = createMemo(
- () =>
- view()?.filters?.notificationFilter ??
- defaultFilterOptions.notificationFilter
- );
- const setNotificationFilter = (
- notificationFilter: FilterOptions['notificationFilter']
- ) => {
- setViewDataStore(
- selectedView(),
- 'filters',
- 'notificationFilter',
- notificationFilter
- );
- };
-
- const focusFilters = createMemo(
- () => view()?.filters?.focusFilters ?? defaultFilterOptions.focusFilters
- );
-
- const toggleFocusFilter = (
- filter: NonNullable<FilterOptions['focusFilters']>[number]
- ) => {
- setViewDataStore(selectedView(), 'filters', 'focusFilters', (prev) => {
- if (!prev) return [filter];
-
- if (prev.includes(filter)) {
- return prev.filter((value) => value !== filter);
- }
-
- return [...prev, filter];
- });
- };
-
- const importantFilter = createMemo(
- () =>
- view()?.filters?.importantFilter ?? defaultFilterOptions.importantFilter
- );
- const setImportantFilter = (importantFilter: boolean) => {
- setViewDataStore(
- selectedView(),
- 'filters',
- 'importantFilter',
- importantFilter
- );
- };
-
- const unreadOnly = createMemo(
- () => view()?.filters?.unreadOnly ?? defaultFilterOptions.unreadOnly
- );
-
- const entityTypeFilter = createMemo(
- () => view()?.filters?.typeFilter ?? defaultFilterOptions.typeFilter
- );
- const setEntityTypeFilter: SetStoreFunction<
- ViewData['filters']['typeFilter']
- > = (...args: any[]) => {
- // @ts-ignore narrowing set store function is annoying due to function overloading
- setViewDataStore(selectedView(), 'filters', 'typeFilter', ...args);
- entityListResetScroll();
- };
-
- const fileTypeFilter = createMemo(
- () =>
- view()?.filters?.documentTypeFilter ??
- defaultFilterOptions.documentTypeFilter
- );
-
- const setFileTypeFilter: SetStoreFunction<
- ViewData['filters']['documentTypeFilter']
- > = (...args: any[]) => {
- setViewDataStore(
- selectedView(),
- 'filters',
- 'documentTypeFilter',
- // @ts-ignore narrowing set store function is annoying due to function overloading
- ...args
- );
- };
-
- const projectFilter = createMemo(
- () => view()?.filters?.projectFilter ?? defaultFilterOptions.projectFilter
- );
-
- const channelCategoryFilter = () =>
- view()?.filters?.channelCategoryFilter ??
- defaultFilterOptions.channelCategoryFilter;
-
- const { all: emailRecipientOptions } = useCombinedRecipients(['user']);
- const fromFilter = createMemo(() => view()?.filters.fromFilter);
- const hasFromFilter = createMemo(() => fromFilter() !== undefined);
- const shouldFilterEmails = createMemo(() => {
- if (!hasFromFilter()) return false;
- const types = entityTypeFilter();
- return types.length === 0 || types.includes('email');
- });
- const shouldFilterOwnedEntities = createMemo(() => {
- if (!hasFromFilter()) return false;
- const types = entityTypeFilter();
- return types.length === 0 || types.some((t) => t !== 'email');
- });
- const showFromFilter = createMemo(
- () => shouldFilterEmails() || shouldFilterOwnedEntities()
- );
- const fromFilterUsers = createMemo(() => fromFilter() ?? []);
- const setFromFilterUsers: SetStoreFunction<
- ViewData['filters']['fromFilter']
- > = (...args: any[]) => {
- // @ts-ignore narrowing set store function is annoying due to function overloading
- setViewDataStore(selectedView(), 'filters', 'fromFilter', ...args);
- };
-
- // Property filters
- const propertyFilters = createMemo(
- () => view()?.filters.propertyFilters ?? []
- );
- const setPropertyFilters = (filters: PropertyFilter[]) => {
- setViewDataStore(selectedView(), 'filters', 'propertyFilters', filters);
- };
- // Track incomplete property filters for toast warning on save
- const [hasIncompletePropertyFilters, setHasIncompletePropertyFilters] =
- createSignal(false);
- // Store clear handler from PropertyFilterControl
- let clearPropertyFilters: (() => void) | undefined;
-
- const getSystemSortOption = (
- sort: SortOptions | undefined
- ): SystemSortOption => {
- if (sort?.type === 'systemSortOption') {
- return sort.sortBy;
- }
- // Default fallback - use defaultSortOptions if it's a system sort
- if (
- defaultSortOptions.type === 'systemSortOption' &&
- defaultSortOptions.sortBy
- ) {
- return defaultSortOptions.sortBy;
- }
- return 'updated_at';
- };
-
- const sortType = createMemo(() => getSystemSortOption(view()?.sort));
- const setSortType = (sortBy: SystemSortOption) => {
- (setViewDataStore as any)(selectedView(), 'sort', 'sortBy', sortBy);
- };
-
- const propertyId = createMemo(() => {
- const sort = view()?.sort;
- return sort?.type === 'property' ? sort.propertyId : null;
- });
- const setPropertyId = (id: string | null) => {
- if (id === null) {
- // Clear property sort, revert to system
- batch(() => {
- (setViewDataStore as any)(
- selectedView(),
- 'sort',
- 'type',
- 'systemSortOption'
- );
- (setViewDataStore as any)(selectedView(), 'sort', 'propertyId', null);
- });
- } else {
- // Set property sort
- batch(() => {
- (setViewDataStore as any)(selectedView(), 'sort', 'type', 'property');
- (setViewDataStore as any)(selectedView(), 'sort', 'propertyId', id);
- // Clear sortBy if switching to property
- (setViewDataStore as any)(selectedView(), 'sort', 'sortBy', null);
- });
- }
- };
-
- const sortOrder = createMemo(
- () => view()?.sort?.sortOrder ?? defaultSortOptions.sortOrder
- );
- const setSortOrder = (order: 'ascending' | 'descending') => {
- setViewDataStore(selectedView(), 'sort', 'sortOrder', order);
- };
-
- // Inbox + notification unrolling are coupled:
- // - inbox=true => unroll=true
- // - inbox=false => unroll=false
- const showUnrollNotifications = createMemo(() => {
- const focusFilters = view()?.filters?.focusFilters ?? [];
- return focusFilters.includes('signal') && !focusFilters.includes('noise');
- });
-
- const showUnreadIndicator = createMemo(() => {
- // When the toolbar is hidden, the user has no in-view way to toggle this.
- // Keep unread indicators visible by default in these contexts.
- if (props.hideToolbar) return true;
- return (
- view()?.display?.showUnreadIndicator ??
- defaultDisplayOptions.showUnreadIndicator
- );
- });
- const setShowUnreadIndicator = (
- showUnreadIndicator: DisplayOptions['showUnreadIndicator']
- ) => {
- setViewDataStore(
- selectedView(),
- 'display',
- 'showUnreadIndicator',
- showUnreadIndicator
- );
- };
-
- const displayProperties = createMemo(
- () =>
- view()?.display?.displayProperties ??
- defaultDisplayOptions.displayProperties
- );
- const setDisplayProperties = (
- properties: DisplayOptions['displayProperties']
- ) => {
- setViewDataStore(
- selectedView(),
- 'display',
- 'displayProperties',
- properties
- );
- };
-
- // Suggested properties reactive to filter type
- const suggestedProperties = createMemo(() => {
- const types = entityTypeFilter();
- return getSuggestedProperties(types);
- });
-
- const debouncedSearchForLocal = debouncedDependent(
- searchText,
- LOCAL_FUZZY_SEARCH_DEBOUNCE_MS
- );
- const debouncedSearchForService = debouncedDependent(
- searchText,
- SEARCH_SERVICE_DEBOUNCE_MS
- );
-
- const [, setIsSearchLoading] = createSignal(false);
-
- const currentViewConfigBase = createMemo(() => {
- const viewKey = selectedView();
- const viewData = viewsData[viewKey];
- if (!viewData) return null;
-
- // Access store properties directly (not through view() memo) for reactivity
- const sort = viewsData[viewKey]?.sort as any;
- const sortType = sort?.type ?? null;
- const sortBy = sort?.sortBy ?? null;
- const propertyId = sort?.propertyId ?? null;
- const sortOrder = sort?.sortOrder ?? null;
-
- // Spread filters with propertyFilters explicitly accessed to ensure reactivity tracking
- const filters = viewsData[viewKey]?.filters;
-
- return {
- display: viewsData[viewKey]?.display,
- filters: { ...filters, propertyFilters: filters.propertyFilters },
- sort: {
- type: sortType,
- sortBy,
- propertyId,
- sortOrder,
- },
- };
- });
- const stringifiedCurrentViewConfigBase = createMemo(() => {
- if (!view()) return null;
- return stringify(currentViewConfigBase());
- });
-
- const { setFilters: setOptionalFilters, filterFn: optionalFilter } =
- createFilterComposer([signalFilter.predicate]);
- // Initialize with default inbox filter since focusFilters defaults to ['signal']
- const { setFilters: setRequiredFilters, filterFn: requiredFilter } =
- createFilterComposer([signalFilter.predicate]);
-
- const toggleFileTypeFilter = (fileType: DocumentTypeFilter) => {
- batch(() => {
- if (!entityTypeFilter().includes('document'))
- setEntityTypeFilter((prev) => [...prev, 'document']);
-
- setFileTypeFilter((prev) =>
- prev.includes(fileType)
- ? prev.filter((t) => t !== fileType)
- : [...prev, fileType]
- );
- });
- entityListResetScroll();
- };
-
- const nameFuzzySearchFilter = createMemo(() =>
- rawSearchText()
- ? (items: WithNotification<EntityData>[]) => {
- const query = debouncedSearchForLocal();
- if (!query || query.length === 0) return items;
-
- const matchResults = fuzzyMatch(query, items, (item) => item.name);
-
- return matchResults.map((result) => {
- return {
- ...result.item,
- search: {
- nameHighlight: result.nameHighlight,
- contentHitData: null,
- source: 'local',
- },
- } as WithNotification<WithSearch<EntityData>>;
- });
- }
- : undefined
- );
-
- const fileTypeCompatibilityFilter = createMemo(() => {
- const filterByFileType = fileTypeFilter();
-
- let filterFn: EntityFilter<EntityData> | undefined;
- if (filterByFileType.length === 1 && filterByFileType[0] === 'unknown') {
- filterFn = (entity) => {
- if (entity.type !== 'document') return true;
-
- const entityFileType = entity.fileType;
- if (!entityFileType) return true;
-
- return KNOWN_FILE_TYPES.every(
- (fileType) => !blockAcceptsFileExtension(fileType, entityFileType)
- );
- };
- } else if (filterByFileType.length > 0) {
- filterFn = (entity) => {
- if (entity.type !== 'document') return true;
-
- const entityFileType = entity.fileType;
- if (
- filterByFileType.includes('unknown') &&
- (!entityFileType ||
- KNOWN_FILE_TYPES.every(
- (fileType) => !blockAcceptsFileExtension(fileType, entityFileType)
- ))
- )
- return true;
-
- return (
- !!entityFileType &&
- filterByFileType.some((fileType) =>
- blockAcceptsFileExtension(fileType, entityFileType)
- )
- );
- };
- }
- return filterFn;
- });
-
- const ownerFilter = createMemo<EntityFilter<EntityData> | undefined>(() => {
- if (!shouldFilterOwnedEntities()) return undefined;
- const selectedFromUsers = fromFilterUsers();
- if (selectedFromUsers.length === 0) return undefined;
-
- return (entity) => {
- if (entity.type === 'email') return true;
-
- const ownerId = entity.ownerId;
- if (!ownerId) return false;
-
- const match = selectedFromUsers.some((user) => {
- return user.id === ownerId;
- });
- return match;
- };
- });
-
- // NOTE: these filters are required because the backend doesn't support these filters yet
- createEffect(() => {
- const filterFns: EntityFilter<EntityData>[] = [];
-
- if (importantFilter()) filterFns.push(importantFilterFn);
-
- const shouldFilterUnread =
- unreadOnly() === true || notificationFilter() === 'unread';
- if (shouldFilterUnread) filterFns.push(unreadFilterFn);
-
- if (notificationFilter() === 'notDone') filterFns.push(notDoneFilterFn);
-
- const focusFilters_ = focusFilters();
- const hasSignalFilter = focusFilters_?.includes('signal') === true;
- const hasNoiseFilter = focusFilters_?.includes('noise') === true;
-
- if (hasSignalFilter && !hasNoiseFilter) {
- filterFns.push(signalFilter.predicate);
- } else if (hasNoiseFilter && !hasSignalFilter) {
- filterFns.push(noiseFilter.predicate);
- } else if (!hasSignalFilter && !hasNoiseFilter) {
- filterFns.push(
- (entity) => !explicitNoiseFilter.predicate(entity, undefined)
- );
- }
-
- setRequiredFilters(filterFns);
- });
-
- createEffect(() => {
- const filterFns: EntityFilter<EntityData>[] = [];
-
- const projectFilter_ = projectFilter();
- if (projectFilter_) {
- filterFns.push(createProjectFilterFn(projectFilter_));
- }
-
- if (entityTypeFilter().length > 0) {
- filterFns.push((entity) => {
- // special case the tasks, entity type will still be document
- if (isTaskEntity(entity)) {
- return entityTypeFilter().includes('task');
- }
- return entityTypeFilter().includes(entity.type);
- });
- }
-
- const channelCategoryFilter_ = channelCategoryFilter() ?? [];
- if (channelCategoryFilter_.length > 0) {
- filterFns.push((entity) => {
- if (entity.type !== 'channel') return true;
- const isDm = entity.channelType === ChannelTypeEnum.DirectMessage;
- const includePeople = channelCategoryFilter_.includes('people');
- const includeGroups = channelCategoryFilter_.includes('groups');
- // Defensive: if both are selected, behave like "no refinement".
- if (includePeople && includeGroups) return true;
- if (includePeople) return isDm;
- if (includeGroups) return !isDm;
- return true;
- });
- }
-
- const fileTypeCompatibilityFilter_ = fileTypeCompatibilityFilter();
- if (fileTypeCompatibilityFilter_)
- filterFns.push(fileTypeCompatibilityFilter_);
-
- // NOTE: email from filters handled directly in search service
- const ownerFilter_ = ownerFilter();
- if (ownerFilter_) filterFns.push(ownerFilter_);
-
- setOptionalFilters(filterFns);
- });
-
- const unifiedSearchIncludeArray = createMemo<UnifiedSearchIndex[]>(
- () => {
- let types = entityTypeFilter();
- // NOTE: empty array means search all
- if (types.length === 0) types = [];
- const includeArray: UnifiedSearchIndex[] = [];
- for (const type of types) {
- switch (type) {
- case 'document':
- case 'task':
- includeArray.push('documents');
- break;
- case 'chat':
- includeArray.push('chats');
- break;
- case 'channel':
- includeArray.push('channels');
- break;
- case 'email':
- includeArray.push('emails');
- break;
- case 'project':
- includeArray.push('projects');
- break;
- }
- }
- return Array.from(new Set(includeArray));
- },
- [],
- { equals: arrayEquals }
- );
-
- const createFileTypeFilterMemo = (type: 'soup' | 'search') =>
- createMemo<string[]>(
- () => {
- let fileTypes = [];
- if (entityTypeFilter().includes('task')) {
- fileTypes.push('md');
- }
-
- if (entityTypeFilter().includes('document')) {
- if (
- fileTypeFilter().length > 0 &&
- fileTypeFilter().length <
- VIEWCONFIG_FILTER_DOCUMENT_TYPE_FILTER.length
- ) {
- const documentFileTypes = fileTypeFilter().flatMap((fileType) => {
- if (fileType === 'code')
- return type === 'soup' ? ['assoc:code'] : codeFileExtensions;
- if (fileType === 'image')
- return type === 'soup' ? ['assoc:image'] : [NIL_UUID];
- if (fileType === 'unknown')
- return type === 'soup' ? ['assoc:other'] : [NIL_UUID];
- return [fileType];
- });
- fileTypes.push(...documentFileTypes);
- } else {
- // if we have task + document and no file type filter, we want to include all file types
- fileTypes = [];
- }
- }
-
- return Array.from(new Set(fileTypes));
- },
- [],
- {
- equals: arrayEquals,
- }
- );
-
- const joinedSoupFileTypeFilter = createFileTypeFilterMemo('soup');
- const joinedSearchFileTypeFilter = createFileTypeFilterMemo('search');
-
- const unifiedSearchFilters = createMemo<UnifiedSearchRequestFilters>(() => {
- let documentFilters: DocumentFilters | null = null;
- documentFilters = {
- file_types: joinedSearchFileTypeFilter(),
- };
-
- let emailFilters: EmailFilters | null = null;
- if (shouldFilterEmails()) {
- const users = fromFilterUsers();
- if (users.length > 0) {
- const senderEmails = users.map((user) => user.data.email);
- emailFilters = {
- senders: senderEmails,
- };
- }
- }
-
- let channelFilters: ChannelFilters | null = null;
- let chatFilters: ChatFilters | null = null;
- let projectFilters: ProjectFilters | null = null;
- if (shouldFilterOwnedEntities()) {
- const users = fromFilterUsers();
- if (users.length > 0) {
- const ownerIds = users.map((user) => user.id);
- channelFilters = {
- sender_ids: ownerIds,
- };
- chatFilters = {
- owners: ownerIds,
- };
- projectFilters = {
- owners: ownerIds,
- };
- }
- }
-
- const projectId = projectFilter();
- if (projectId) {
- documentFilters = {
- ...(documentFilters ?? {}),
- project_ids: [projectId],
- };
- chatFilters = {
- ...(chatFilters ?? {}),
- project_ids: [projectId],
- };
- projectFilters = {
- ...(projectFilters ?? {}),
- project_ids: [projectId],
- };
- }
-
- const filters = {
- document: documentFilters,
- chat: chatFilters,
- channel: channelFilters,
- email: emailFilters,
- project: projectFilters,
- };
-
- return filters;
- });
-
- const emailActive = useEmailLinksStatus();
-
- const validSearchTerms = createMemo(
- () => debouncedSearchForService().length >= 3
- );
- const hasSignalOrNoiseFilter = createMemo(() => {
- const focusFilters_ = focusFilters();
- return (
- focusFilters_?.includes('signal') === true ||
- focusFilters_?.includes('noise') === true
- );
- });
- const isSearchActive = createMemo(
- () => validSearchTerms() && !hasSignalOrNoiseFilter()
- );
-
- const dssQueryParams = createMemo(
- (): GetItemsSoupParams => ({
- limit: props.defaultDisplayOptions?.limit ?? 100,
- sort_method: sortType(),
- })
- );
-
- const dssQueryRequestBody = createMemo(
- (): PostSoupRequest => ({
- channel_filters: {
- channel_ids:
- entityTypeFilter().includes('channel') ||
- entityTypeFilter().length === 0
- ? []
- : [NIL_UUID],
- },
- document_filters: {
- document_ids:
- entityTypeFilter().includes('document') ||
- entityTypeFilter().includes('task') ||
- entityTypeFilter().length === 0
- ? []
- : [NIL_UUID],
- project_ids: view().viewType === 'project' ? [view().id] : [],
- file_types: joinedSoupFileTypeFilter(),
- },
- chat_filters: {
- chat_ids:
- entityTypeFilter().includes('chat') || entityTypeFilter().length === 0
- ? []
- : [NIL_UUID],
- project_ids: view().viewType === 'project' ? [view().id] : [],
- },
- email_filters: {
- recipients:
- emailActive() &&
- !isSearchActive() &&
- view().viewType !== 'project' &&
- (entityTypeFilter().includes('email') ||
- entityTypeFilter().length === 0)
- ? []
- : [NIL_UUID],
- },
- project_filters: {
- project_ids:
- view().viewType === 'project'
- ? [view().id]
- : entityTypeFilter().includes('project') ||
- entityTypeFilter().length === 0
- ? []
- : [NIL_UUID],
- },
- limit: props.defaultDisplayOptions?.limit ?? 100,
- emailView: importantFilter()
- ? 'important'
- : view().id === VIEWCONFIG_DEFAULTS_IDS_ENUM.email
- ? emailView()
- : 'all',
-
- sort_method: sortType(),
- })
- );
- const searchUnifiedNameContentQueryParams = createMemo(
- (): SearchArgs => ({
- params: {
- cursor: null,
- page_size: 100,
- },
- request: {
- search_on: 'name_content',
- match_type: 'partial',
- terms:
- debouncedSearchForService().length > 0
- ? [debouncedSearchForService()]
- : undefined,
- filters: unifiedSearchFilters(),
- include: unifiedSearchIncludeArray(),
- },
- })
- );
-
- const disableSearchService = createMemo(() => {
- return !isSearchActive();
- });
-
- const disableDssInfiniteQuery = createMemo(() => {
- const typeFilter = entityTypeFilter();
- if (typeFilter.length === 0) return false;
-
- function onlyHas<T>(arr: readonly T[], value: T): boolean {
- return arr.length === 1 && arr[0] === value;
- }
-
- if (isSearchActive() && onlyHas(typeFilter, 'email')) return true;
- return false;
- });
-
- // TODO: fix email source
- // const emailSource = useGlobalEmailSource();
- // createEffect(() => emailSource.setQueryParams(emailQueryParams()));
-
- const notificationSource = useGlobalNotificationSource();
- const markEntityAsDone = (entity: EntityData) => {
- const actions = soupContext.actionRegistry;
- if (actions.isActionEnabled('mark_as_done', entity)) {
- actions.execute('mark_as_done', entity);
- return true;
- }
- return false;
- };
-
- const blockOrchestrator = useGlobalBlockOrchestrator();
- const gotoChannelNotification = async (notification: UnifiedNotification) => {
- let message_id: string | undefined;
- let thread_id: string | undefined;
-
- if (isChannelMention(notification)) {
- const metadata = getMetadata(notification);
- message_id = metadata.messageId;
- } else if (isChannelMessageReply(notification)) {
- const metadata = getMetadata(notification);
- message_id = metadata.messageId;
- thread_id = metadata.threadId;
- } else if (isChannelMessageSend(notification)) {
- const metadata = getMetadata(notification);
- message_id = metadata.messageId;
- } else {
- return;
- }
-
- const blockHandle = await blockOrchestrator.getBlockHandle(
- notification.entity_id,
- 'channel'
- );
- if (!blockHandle) return;
-
- notificationSource.markAsRead(notification);
-
- return blockHandle?.goToLocationFromParams({
- [CHANNEL_PARAMS.message]: message_id,
- [CHANNEL_PARAMS.thread]: thread_id,
- });
- };
-
- const { SortComponent, sortFn: entitySort } = createSort({
- sortOptions,
- defaultSortOption: getSystemSortOption(defaultSortOptions as SortOptions),
- sortTypeSignal: [sortType, setSortType] as Signal<SystemSortOption>,
- propertyIdSignal: [propertyId, setPropertyId] as Signal<string | null>,
- sortOrderSignal: [sortOrder, setSortOrder] as Signal<
- 'ascending' | 'descending'
- >,
- disabled: isSearchActive,
- });
-
- const {
- dispose: disposeUnifiedListQueries,
- UnifiedListComponent,
- isLoading,
- } = createRoot((dispose) => {
- const dssInfiniteQuery = createDssInfiniteQuery(
- dssQueryParams,
- dssQueryRequestBody,
- {
- disabled: disableDssInfiniteQuery,
- }
- );
- const searchNameContentInfiniteQuery = createUnifiedSearchInfiniteQuery(
- searchUnifiedNameContentQueryParams,
- { disabled: disableSearchService }
- );
- const notificationSource = useGlobalNotificationSource();
-
- const entityMapper = (entity: EntityData) => {
- return {
- ...unwrap(entity),
- notifications: useNotificationsForEntity(notificationSource, entity),
- };
- };
-
- // We want to be to be able to search over locally cached emails without actually
- // fetching more data when we have a invalid search term (i.e. one or two chars).
- // If we're using search service for a valid term, we can safely fetch more data
- // from dss for fuzzy name search since we won't be searching over emails (too big).
- const disableFetchMore = createMemo(() => {
- const searchAllEmails =
- (dssQueryRequestBody().email_filters?.recipients ?? []).length === 0;
- return searchText().length > 0 && searchAllEmails;
- });
-
- const { UnifiedListComponent, entities, isLoading } =
- createUnifiedInfiniteList<
- WithNotification<WithSearch<EntityData> | EntityData>
- >({
- id: `${selectedView()}-${splitContext.handle.id}`,
- entityInfiniteQueries: [
- {
- query: dssInfiniteQuery,
- operations: { filter: true, search: true },
- },
- {
- query: searchNameContentInfiniteQuery,
- operations: { filter: true, search: false },
- },
- ],
- entityMapper,
- requiredFilter,
- optionalFilter,
- entitySort,
- searchFilter: nameFuzzySearchFilter,
- isSearchActive,
- disableFetchMore,
- });
-
- createEffect(() => {
- setEntities(entities());
- });
-
- return { dispose, isLoading, UnifiedListComponent };
- });
-
- createEffect(() => {
- const loading = isLoading();
- setIsSearchLoading(loading);
- });
-
- onCleanup(() => {
- createRoot((dispose) => {
- createEffect(() => {
- // don't dispose on blocks, such as email block when marking as done, in order to update entity navigation indicator
- if (
- splitContext.panelRef()?.isConnected &&
- splitContext.handle.content().id !== 'unified-list'
- ) {
- return;
- }
-
- disposeUnifiedListQueries();
- dispose();
- });
- });
- });
-
- const openEntityInNewTab = ({
- entity,
- location,
- }: {
- entity: EntityData;
- location?: SearchLocation;
- }) => {
- // Build URL for the entity
- let entityPath: string;
- if (entity.type === 'document') {
- const { fileType, subType } = entity;
- const blockName = fileTypeToBlockName(subType?.type ?? fileType);
- entityPath = `/app/${blockName}/${entity.id}`;
- } else {
- entityPath = `/app/${entity.type}/${entity.id}`;
- }
-
- // Add location params if present
- const entityUrl = new URL(entityPath, window.location.origin);
- if (location) {
- switch (location.type) {
- case 'channel':
- if (location.messageId) {
- entityUrl.searchParams.set(
- 'channel_message_id',
- location.messageId
- );
- }
- if (location.threadId) {
- entityUrl.searchParams.set('thread', location.threadId);
- }
- break;
- case 'email':
- if (location.messageId) {
- entityUrl.searchParams.set('email_message_id', location.messageId);
- }
-
- break;
- case 'md':
- if (location.nodeId) {
- entityUrl.searchParams.set('node_id', location.nodeId);
- }
- break;
- case 'pdf':
- if (location.searchPage !== undefined) {
- entityUrl.searchParams.set(
- 'search_page',
- location.searchPage.toString()
- );
- }
- if (location.searchRawQuery) {
- entityUrl.searchParams.set(
- 'search_raw_query',
- location.searchRawQuery
- );
- }
- if (location.highlightTerms) {
- entityUrl.searchParams.set(
- 'search_highlight_terms',
- JSON.stringify(location.highlightTerms)
- );
- }
- if (location.searchSnippet) {
- entityUrl.searchParams.set(
- 'search_snippet',
- location.searchSnippet
- );
- }
- break;
- }
- }
-
- window.open(entityUrl.toString(), '_blank', 'noopener');
- };
-
- const entityClickHandler: EntityClickHandler<EntityData> = async (args) => {
- const { type, event, location } = args;
-
- const entity = (
- type === 'entity' ? args.entity : args.projectEntity
- ) as EntityData;
-
- if (event.metaKey || event.ctrlKey) {
- openEntityInNewTab({ entity, location });
- return;
- }
-
- if (preview() && type === 'entity') {
- setSelectedEntity(entity);
-
- // Move browser focus to the row
- const target = event.target;
- if (target instanceof HTMLElement) {
- const row = target.closest('[data-entity]');
- if (row instanceof HTMLElement) {
- row.focus();
- }
- }
-
- return;
- }
-
- await openEntityInSplitFromUnifiedList(entity, {
- openInNewSplit: event.altKey,
- location,
- splitHandle: splitContext.handle,
- });
- };
-
- const entityDblClickHandler: EntityClickHandler<EntityData> = async ({
- entity,
- location,
- event,
- }) => {
- if (!preview()) {
- return;
- }
-
- await openEntityInSplitFromUnifiedList(entity, {
- openInNewSplit: event.altKey,
- location,
- splitHandle: splitContext.handle,
- });
- };
-
- const entityPointerDownHandler: EntityPointerDownHandler<EntityData> = async (
- args
- ) => {
- const { type, location, event } = args;
- const entity = (
- type === 'entity' ? args.entity : args.projectEntity
- ) as EntityData;
-
- // middle mouse button pressed
- if (event.button === 1 && event.pointerType === 'mouse') {
- // TODO: current page should remain focused after opening new tab
- openEntityInNewTab({ entity, location });
- }
- };
-
- const StyledTriggerLabel = (props: ParentProps) => {
- return <span class="text-[0.625rem]">{props.children}</span>;
- };
-
- const focusedSelector = createSelector(() => selectedEntity()?.id);
- const multiSelectSelector = createSelector(
- () => view()?.multiSelectEntities,
- (a: string, b: EntityData[]) => b.find((e) => e.id === a) !== undefined
- );
-
- // Add property editor hotkeys
- usePropertyEditorHotkeys({
- scopeId: splitContext.splitHotkeyScope,
- getSelectedEntities: () => {
- const multi = view().multiSelectEntities;
- if (multi.length > 0) return multi;
- return selectedEntity() ? [selectedEntity()!] : [];
- },
- });
-
- const saveViewMutation = useUpsertSavedViewMutation();
-
- const isViewConfigChanged = createMemo(() => {
- const view_ = view();
- if (!view_) return false;
-
- const initialConfigStr = view_.initialConfig;
- if (initialConfigStr == null || initialConfigStr === '') return false;
-
- try {
- const initialConfigObj = JSON.parse(initialConfigStr);
- const currentConfigObj = currentViewConfigBase();
-
- if (!currentConfigObj) return false;
-
- const isEqual = isConfigEqual(initialConfigObj, currentConfigObj);
-
- return !isEqual;
- } catch (e) {
- console.warn(e);
- return false;
- }
- });
-
- const onClickSaveViewConfigChanges = async () => {
- const view_ = view();
- const config = currentViewConfigBase();
- if (!view_ || !config) return;
-
- // Warn if there are incomplete property filters (they won't be saved)
- if (hasIncompletePropertyFilters()) {
- toast.alert('Incomplete property filters were not saved');
- }
-
- // Wait for mutation to complete (including query refetch) before updating initialConfig
- await saveViewMutation.mutateAsync({
- id: view_.id,
- name: view_.view,
- config,
- });
-
- // Reset initialConfig after save + refetch so isViewConfigChanged returns false
- const currentConfig = stringifiedCurrentViewConfigBase();
- if (currentConfig !== null && currentConfig !== undefined) {
- setViewDataStore(selectedView(), 'initialConfig', currentConfig);
- }
- };
-
- const onClickResetViewConfigChanges = () => {
- const view_ = view();
- if (!view_) return;
-
- const initialConfigStr = view_.initialConfig;
- if (initialConfigStr == null || initialConfigStr === '') return;
-
- const initialConfigObj = JSON.parse(initialConfigStr) as ViewConfigBase;
-
- batch(() => {
- setViewDataStore(selectedView(), 'filters', initialConfigObj.filters);
- setViewDataStore(selectedView(), 'sort', initialConfigObj.sort);
- setViewDataStore(selectedView(), 'display', initialConfigObj.display);
- });
- // Clear property filter UI state
- clearPropertyFilters?.();
- };
-
- // Set initialConfig when it's not present (on load or after save/refetch)
- createEffect(() => {
- const view_ = view();
- if (!view_) return;
-
- const initialConfig = view_.initialConfig;
- if (initialConfig) return;
-
- const stringifiedConfig = stringifiedCurrentViewConfigBase();
- if (stringifiedConfig) {
- setViewDataStore(selectedView(), 'initialConfig', stringifiedConfig);
- }
- });
-
- let lastClickedEntityId = -1;
-
- const toggleSingleMultiSelection = (params: {
- entity: EntityData;
- next: boolean;
- }) => {
- soupContext.setViewDataStore(
- selectedView(),
- 'multiSelectEntities',
- (prev) => {
- if (!params.next) {
- return prev.filter((e) => e.id !== params.entity.id);
- }
- return prev.concat(params.entity);
- }
- );
- };
-
- const getSelectionAnchorIndex = (params: {
- entityList: EntityData[];
- selectedEntitySet: Set<EntityData>;
- lastClickedIndex: number;
- }) => {
- // Try to grab the last clicked item and fall back on the highest currently
- // selected index.
- let anchorIndex = params.lastClickedIndex;
- if (anchorIndex === -1) {
- for (let i = 0; i < params.entityList.length; i++) {
- if (params.selectedEntitySet.has(params.entityList[i])) {
- anchorIndex = i;
- }
- }
- }
- return anchorIndex;
- };
-
- const getNewEntitiesForShiftSelection = (params: {
- entityList: EntityData[];
- selectedEntitySet: Set<EntityData>;
- anchorIndex: number;
- targetIndex: number;
- }) => {
- const newEntitiesForSelection: EntityData[] = [];
- const sign = Math.sign(params.targetIndex - params.anchorIndex);
- if (params.anchorIndex === params.targetIndex)
- return newEntitiesForSelection;
-
- for (
- let i = params.anchorIndex;
- sign > 0 ? i <= params.targetIndex : i >= params.targetIndex;
- i += sign
- ) {
- const entity = params.entityList[i];
- if (!params.selectedEntitySet.has(entity)) {
- newEntitiesForSelection.push(entity);
- }
- }
-
- return newEntitiesForSelection;
- };
-
- const handleMultiSelectChecked = (params: {
- entity: EntityData;
- entityIndex: number;
- next: boolean;
- shiftKey: boolean;
- }) => {
- if (!params.shiftKey) {
- toggleSingleMultiSelection({ entity: params.entity, next: params.next });
- lastClickedEntityId = params.entityIndex;
- return;
- }
-
- const entityList = soupContext.entitiesSignal[0]();
- if (!entityList) return;
-
- const selectedEntitySet = new Set(
- soupContext.viewsDataStore[soupContext.selectedView()].multiSelectEntities
- );
-
- const anchorIndex = getSelectionAnchorIndex({
- entityList,
- selectedEntitySet,
- lastClickedIndex: lastClickedEntityId,
- });
-
- if (anchorIndex === -1) {
- toggleSingleMultiSelection({ entity: params.entity, next: params.next });
- lastClickedEntityId = params.entityIndex;
- return;
- }
-
- const newEntitiesForSelection = getNewEntitiesForShiftSelection({
- entityList,
- selectedEntitySet,
- anchorIndex,
- targetIndex: params.entityIndex,
- });
-
- soupContext.setViewDataStore(
- selectedView(),
- 'multiSelectEntities',
- (prev) => prev.concat(newEntitiesForSelection)
- );
-
- lastClickedEntityId = params.entityIndex;
- };
-
- // reset last clicked on view change.
- createEffect(
- on(view, () => {
- lastClickedEntityId = -1;
- })
- );
-
- // reset last clicked on reset multi-selection.
- createEffect(() => {
- if (
- soupContext.viewsDataStore[selectedView()].multiSelectEntities.length ===
- 0
- ) {
- lastClickedEntityId = -1;
- }
- });
-
- createEffect(
- on(splitContext.isPanelActive, () => {
- if (splitContext.isPanelActive()) {
- if (activeSoupContext() !== soupContext) return;
- const domEl = activeSoupContext()?.domRef();
- setTimeout(() => {
- domEl?.focus();
- });
- }
- })
- );
-
- return (
- <>
- <Show when={!props.hideToolbar}>
- <SplitToolbarRight order={5}>
- <div class="flex flex-row items-center gap-1 p-1 h-full select-none">
- <Show when={isViewConfigChanged()}>
- <Show when={preview()}>
- <DropdownMenu
- size="SM"
- theme="secondary"
- triggerLabel={<span class="font-extrabold">⋮</span>}
- >
- <div class="flex flex-col gap-2 p-2">
- <DeprecatedButton
- size="SM"
- classList={{
- '!border-ink/25 !text-ink !bg-panel hover:!text-ink font-normal': true,
- }}
- onClick={onClickResetViewConfigChanges}
- >
- CLEAR
- </DeprecatedButton>
- <DeprecatedButton
- size="SM"
- classList={{
- '!border-ink/25 !text-ink !bg-panel hover:!text-ink font-normal': true,
- }}
- onClick={onClickSaveViewConfigChanges}
- >
- SAVE CHANGES
- </DeprecatedButton>
- </div>
- </DropdownMenu>
- </Show>
- <Show when={!preview()}>
- <DeprecatedButton
- size="SM"
- classList={{
- '!border-ink/25 !text-ink !bg-panel hover:!text-ink ml-1.5 font-normal': true,
- }}
- onClick={onClickResetViewConfigChanges}
- >
- CLEAR
- </DeprecatedButton>
- <DeprecatedButton
- size="SM"
- classList={{
- '!border-ink/25 !text-ink !bg-panel hover:!text-ink mx-1.5 font-normal': true,
- }}
- onClick={onClickSaveViewConfigChanges}
- >
- SAVE CHANGES
- </DeprecatedButton>
- </Show>
- </Show>
- <DropdownMenu
- size="SM"
- theme="primary"
- triggerLabel={<StyledTriggerLabel>Filter</StyledTriggerLabel>}
- >
- <div class="min-w-[10vw] max-w-md">
- <div class="grid divide-y divide-edge">
- <section class="gap-1 grid p-2">
- <ToggleSwitch
- onChange={setImportantFilter}
- checked={importantFilter()}
- label="Important"
- size="SM"
- />
- <SegmentedControl
- size="SM"
- label="Show"
- list={[
- { value: 'all', label: 'All' },
- { value: 'unread', label: 'Unread' },
- { value: 'notDone', label: 'Not Done' },
- ]}
- value={notificationFilter()}
- onChange={setNotificationFilter}
- />
-
- <div class="flex items-center justify-between">
- <span class="font-medium text-xs">Focus</span>
- <div class="flex items-center gap-1">
- <ToggleButton
- size="SM"
- pressed={focusFilters()?.includes('signal')}
- onChange={() => toggleFocusFilter('signal')}
- >
- <span class="uppercase">Signal</span>
- </ToggleButton>
- <ToggleButton
- size="SM"
- pressed={focusFilters()?.includes('noise')}
- onChange={() => toggleFocusFilter('noise')}
- >
- <span class="uppercase">Noise</span>
- </ToggleButton>
- </div>
- </div>
- </section>
- <section class="gap-1 p-2">
- <span class="font-medium text-xs">Type</span>
- <div class="flex flex-row flex-wrap items-center gap-1">
- <EntityTypeToggle
- filter={entityTypeFilter}
- setFilter={setEntityTypeFilter}
- setFileTypeFilter={setFileTypeFilter}
- type="document"
- />
- <EntityTypeToggle
- filter={entityTypeFilter}
- setFilter={setEntityTypeFilter}
- type="chat"
- />
- <EntityTypeToggle
- filter={entityTypeFilter}
- setFilter={setEntityTypeFilter}
- type="channel"
- />
- <Show when={ENABLE_TASKS_TABS}>
- <EntityTypeToggle
- filter={entityTypeFilter}
- setFilter={setEntityTypeFilter}
- type="task"
- />
- </Show>
- <EntityTypeToggle
- filter={entityTypeFilter}
- setFilter={setEntityTypeFilter}
- type="email"
- />
- <EntityTypeToggle
- filter={entityTypeFilter}
- setFilter={setEntityTypeFilter}
- type="project"
- />
- </div>
- </section>
- <section class="gap-1 p-2">
- <span class="font-medium text-xs">Filetype</span>
- <div class="flex flex-row flex-wrap items-center gap-1">
- <For each={[...VIEWCONFIG_FILTER_DOCUMENT_TYPE_FILTER]}>
- {(fileType) => (
- <ToggleButton
- size="SM"
- pressed={fileTypeFilter().includes(fileType)}
- onChange={() => toggleFileTypeFilter(fileType)}
- >
- {FILE_TYPE_DISPLAY_LABELS[fileType]}
- </ToggleButton>
- )}
- </For>
- </div>
- </section>
- <Show when={ENABLE_SOUP_FROM_FILTER && showFromFilter()}>
- <section class="gap-1 p-2">
- <span class="font-medium text-xs">From</span>
- <RecipientSelector<'user' | 'contact'>
- options={emailRecipientOptions}
- selectedOptions={fromFilterUsers()}
- setSelectedOptions={setFromFilterUsers}
- placeholder="Filter by user..."
- includeSelf
- />
- </section>
- </Show>
- <Show when={ENABLE_PROPERTY_FILTER}>
- <Suspense>
- <section class="gap-1 grid p-2">
- <span class="font-medium text-xs">Property</span>
- <PropertyFilterControl
- propertyFilters={propertyFilters}
- setPropertyFilters={setPropertyFilters}
- onIncompleteFiltersChange={
- setHasIncompletePropertyFilters
- }
- registerClearHandler={(fn) => {
- clearPropertyFilters = fn;
- }}
- />
- </section>
- </Suspense>
- </Show>
- </div>
- </div>
- </DropdownMenu>
- <DropdownMenu
- size="SM"
- triggerLabel={<StyledTriggerLabel>Display</StyledTriggerLabel>}
- >
- <div class="min-w-[10vw] max-w-md">
- <div class="grid divide-y divide-edge">
- <section class="p-2">
- <SegmentedControl
- size="SM"
- label="Layout"
- // value={selectItemFromList()}
- list={['Compact', 'Relaxed', 'Visual']}
- // onChange={(newValue) => setSelectItemFromList(newValue)}
- disabled
- />
- </section>
- <section class="gap-1 grid p-2">
- <ToggleSwitch
- size="SM"
- label="Indicate Unread"
- checked={showUnreadIndicator()}
- onChange={setShowUnreadIndicator}
- />
- </section>
- <section class="p-2">
- <SortComponent
- size="SM"
- onSelectSystemSort={() => {
- entityListResetScroll();
- }}
- />
- </section>
- <Show when={ENABLE_PROPERTY_DISPLAY}>
- <section class="p-2">
- <PropertyDisplayControl
- selectedPropertyIds={displayProperties}
- setSelectedPropertyIds={setDisplayProperties}
- suggestedProperties={suggestedProperties()}
- />
- </section>
- </Show>
- </div>
- </div>
- </DropdownMenu>
- </div>
- </SplitToolbarRight>
- </Show>
- <ContextMenu
- forceMount={contextAndModalState.contextMenuOpen}
- onOpenChange={(open) => {
- setContextAndModalState((prev) => {
- if (open) {
- return {
- ...prev,
- contextMenuOpen: open,
- prevSelectedEntity: prev.selectedEntity,
- };
- }
- return {
- ...prev,
- contextMenuOpen: open,
- selectedEntity: undefined,
- };
- });
- }}
- >
- <ContextMenu.Trigger
- class="@container/uList size-full unified-list-root"
- onPointerDown={() => {
- setActiveSoupContext(soupContext);
- }}
- onKeyUp={() => {
- setActiveSoupContext(soupContext);
- }}
- >
- <EntityRowProvider
- container={localEntityListRef}
- canSwipeLeft={(entityId) => {
- const entity = entityById().get(entityId);
- if (!entity) return false;
- return soupContext.actionRegistry.isActionEnabled(
- 'mark_as_done',
- entity
- );
- }}
- onSwipeLeft={(entityId) => {
- const entity = entityById().get(entityId);
- if (!entity) return false;
-
- soupContext.actionRegistry.execute('mark_as_done', entity);
- }}
- setCollapseEntity={soupContext.collapseEntitySignal[1]}
- >
- <UnifiedListComponent
- entityListRef={setLocalEntityListRef}
- virtualizerHandle={setVirtualizerHandle}
- viewId={view()?.id}
- searchText={searchText()}
- hasRefinementsFromBase={isViewConfigChanged()}
- entityMinHeight={ENTITY_HEIGHT}
- viewType={view()?.viewType}
- name={view()?.view}
- splitId={splitContext.handle.id}
- >
- {(innerProps) => {
- const displayDoneButton = () => {
- if (innerProps.entity.type === 'email') {
- return !innerProps.entity.done;
- }
-
- return (innerProps.entity.notifications?.().length ?? 0) > 0;
- };
- const timestamp = () => {
- switch (sortType()) {
- case 'viewed_at':
- return innerProps.entity.viewedAt;
- case 'created_at':
- return innerProps.entity.createdAt;
- case 'updated_at':
- return innerProps.entity.updatedAt;
- }
- };
-
- const properties = () => {
- if (isTaskEntity(innerProps.entity)) {
- return taskPropertiesStore()[innerProps.entity.id] ?? [];
- }
- return undefined;
- };
-
- return (
- <EntityRow
- entityId={innerProps.entity.id}
- swipeLeftColor="bg-success"
- swipeLeftRevealedComponent={
- <CheckIcon class="size-8 text-panel" />
- }
- >
- <EntityWithEverything
- onContextMenu={() => {
- if (isPanelActive() && !preview()) {
- setSelectedEntity(innerProps.entity);
- }
- setContextAndModalState((prev) => {
- return {
- ...prev,
- contextMenuOpen: true,
- selectedEntity: innerProps.entity,
- };
- });
- }}
- entity={innerProps.entity}
- properties={properties()}
- splitId={splitContext.handle.id}
- timestamp={timestamp()}
- onClick={entityClickHandler}
- onDblClick={entityDblClickHandler}
- onPointerDown={entityPointerDownHandler}
- onClickRowAction={
- soupContext.actionRegistry.isActionEnabled(
- 'mark_as_done',
- innerProps.entity
- )
- ? (entity, type) => {
- if (type === 'done') {
- markEntityAsDone?.(entity);
- }
- }
- : undefined
- }
- onClickNotification={({ entity: notifiedEntity }) => {
- const notification = tryToTypedNotification(
- notifiedEntity.notification
- );
- if (!notification) return;
- if (notifiedEntity.type === 'channel')
- gotoChannelNotification(notification);
- }}
- onMouseOver={() => {
- if (preview()) return;
- setViewDataStore(
- selectedView(),
- 'hasUserInteractedEntity',
- true
- );
- setSelectedEntityFromMouse(innerProps.entity);
- }}
- onMouseLeave={() => {}}
- onFocusIn={() => {
- if (preview()) return;
- setSelectedEntity(innerProps.entity);
- }}
- showLeftColumnIndicator={
- showUnreadIndicator() || importantFilter()
- }
- fadeIfRead={showUnreadIndicator()}
- showUnrollNotifications={showUnrollNotifications()}
- importantIndicatorActive={importantFilterFn(
- innerProps.entity
- )}
- unreadIndicatorActive={unreadFilterFn(innerProps.entity)}
- showDoneButton={displayDoneButton()}
- highlighted={
- isPanelActive() && focusedSelector(innerProps.entity.id)
- }
- selected={{
- active:
- focusedSelector(innerProps.entity.id) ||
- contextAndModalState.selectedEntity?.id ===
- innerProps.entity.id,
- muted:
- focusedSelector(innerProps.entity.id) &&
- activeSoupContext() !== soupContext,
- }}
- checked={multiSelectSelector(innerProps.entity.id)}
- onChecked={(next, shiftKey) =>
- handleMultiSelectChecked({
- entity: innerProps.entity,
- entityIndex: innerProps.index,
- next,
- shiftKey: shiftKey ?? false,
- })
- }
- searchActive={!!searchText()}
- />
- </EntityRow>
- );
- }}
- </UnifiedListComponent>
- </EntityRowProvider>
-
- <EntityModal
- isOpen={() =>
- !!(
- contextAndModalState.modalOpen &&
- contextAndModalState.selectedEntity?.id
- )
- }
- setIsOpen={() =>
- setContextAndModalState((prev) => ({
- ...prev,
- modalOpen: !prev.modalOpen,
- }))
- }
- view={() => contextAndModalState.modalView}
- entity={contextAndModalState.selectedEntity}
- />
- <ContextMenu.Portal>
- <Show when={contextAndModalState.selectedEntity}>
- {(selectedEntity) => (
- <ContextMenuContent mobileFullScreen>
- <Show when={isMobile()}>
- <Entity
- entity={selectedEntity()}
- timestamp={
- sortType() === 'viewed_at'
- ? selectedEntity().viewedAt
- : sortType() === 'created_at'
- ? selectedEntity().createdAt
- : undefined
- }
- />
- <MenuSeparator />
- </Show>
- <EntityActionsMenuItems
- entity={selectedEntity()}
- onSelectAction={() => {}}
- />
- </ContextMenuContent>
- )}
- </Show>
- </ContextMenu.Portal>
- </ContextMenu.Trigger>
- <Show when={view()?.multiSelectEntities.length}>
- <EntitySelectionToolbarModal
- multiSelectEntities={view()?.multiSelectEntities ?? []}
- onClose={() =>
- soupContext.setViewDataStore(
- selectedView(),
- 'multiSelectEntities',
- []
- )
- }
- onAction={() => {
- const multiSelectEntities =
- viewsData[selectedView()].multiSelectEntities;
- const hasSelection = multiSelectEntities.length > 0;
- if (hasSelection) {
- setKonsoleMode('SELECTION_MODIFICATION');
- const selectionIndex =
- searchCategories.getCategoryIndex('Selection');
-
- if (selectionIndex === undefined) return false;
-
- setCommandCategoryIndex(selectionIndex);
-
- searchCategories.showCategory('Selection');
-
- setKonsoleContextInformation({
- selectedEntities: multiSelectEntities.slice(),
- clearSelection: () => {
- soupContext.setViewDataStore(
- selectedView(),
- 'multiSelectEntities',
- []
- );
- },
- });
-
- toggleKonsoleVisibility();
- return true;
- }
- searchCategories.hideCategory('Selection');
- resetCommandCategoryIndex();
- resetKonsoleMode();
- return false;
- }}
- />
- </Show>{' '}
- </ContextMenu>
- </>
- );
-}
-
-const EntityTypeToggle = (props: {
- type: ExpandedEntityType;
- filter: Accessor<typeof VIEWCONFIG_BASE.filters.typeFilter>;
- setFilter: Setter<typeof VIEWCONFIG_BASE.filters.typeFilter>;
- setFileTypeFilter?: Setter<typeof VIEWCONFIG_BASE.filters.documentTypeFilter>;
-}) => {
- const toggleEntityTypeFilter = (type: ExpandedEntityType) => {
- props.setFilter((prev) =>
- prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type]
- );
- };
- return (
- <ToggleButton
- size="SM"
- pressed={props.filter().includes(props.type)}
- onChange={(pressed) =>
- batch(() => {
- if (props.setFileTypeFilter && !pressed) props.setFileTypeFilter([]);
-
- toggleEntityTypeFilter(props.type);
- })
- }
- >
- <span class="uppercase">
- {props.type === 'project' ? 'folder' : props.type}
- </span>
- </ToggleButton>
- );
-};
-
-function _SearchBar(props: {
- isLoading: Accessor<boolean>;
- setIsLoading: Setter<boolean>;
-}) {
- const getInputId = (selectedView: string) =>
- `search-input-${splitContext.handle.id}-${selectedView}`;
- const splitContext = useSplitPanelOrThrow();
- const {
- viewsDataStore,
- selectedView,
- setSelectedView,
- setViewDataStore,
- virtualizerHandleSignal: [virtualizerHandle],
- entityListRefSignal: [entityListRef],
- navigateThroughList,
- } = splitContext.soupContext;
- const viewData = createMemo(() => viewsDataStore[selectedView()]);
- const viewName = createMemo(() => viewData().view);
-
- let inputRef: HTMLInputElement | undefined;
-
- const searchText = createMemo<string>(() => viewData().searchText ?? '');
- const setSearchText = (text: string) => {
- setViewDataStore(selectedView(), 'searchText', text);
- };
-
- const selectionClick = () => {
- const id = viewsDataStore[selectedView()].selectedEntity?.id;
- if (!id) return;
- const el = entityListRef()?.querySelector(`[data-entity-id="${id}"]`);
- if (!(el instanceof HTMLElement)) return;
- el.click();
- };
-
- const focusNextEntity = () => {
- navigateThroughList({
- axis: 'end',
- mode: 'step',
- });
- };
-
- const [waitForLoadingEnd, setWaitForLoadingEnd] = createSignal(false);
-
- // When search text changes, mark that we're waiting for loading to end
- createRenderEffect((prevText: string) => {
- const text = searchText().trim();
- if (text !== prevText) {
- setViewDataStore(selectedView(), 'selectedEntity', undefined);
- setViewDataStore(selectedView(), 'hasUserInteractedEntity', false);
- virtualizerHandle()?.scrollToIndex(0);
- setWaitForLoadingEnd(true);
- }
- return text;
- }, searchText());
-
- // When we're no longer loading but still waiting, reset the list
- createRenderEffect((prevLoading: boolean) => {
- const loading = props.isLoading();
-
- if (prevLoading && !loading && waitForLoadingEnd()) {
- // Loading just ended and we were waiting for it
- setWaitForLoadingEnd(false);
- virtualizerHandle()?.scrollToIndex(0);
- }
-
- return loading;
- }, props.isLoading());
-
- // waits for input element to be mounted before focusing it
- const focusSearch = () => {
- const inputId = getInputId(selectedView());
- const existingInput = document.getElementById(inputId) as HTMLInputElement;
- if (existingInput) {
- existingInput.focus();
- return;
- }
-
- const mutationObserver = new MutationObserver(() => {
- const input = document.getElementById(inputId) as HTMLInputElement;
- if (input) {
- mutationObserver.disconnect();
- input.focus();
- }
- });
-
- const toolbarLeft = splitContext.layoutRefs.toolbarLeft;
- if (toolbarLeft) {
- mutationObserver.observe(toolbarLeft, {
- childList: true,
- subtree: true,
- });
- }
-
- setTimeout(() => {
- mutationObserver.disconnect();
- }, 1000);
- };
-
- onMount(() => {
- const { dispose: disposeSlash } = registerHotkey({
- hotkey: ['/'],
- scopeId: splitContext.splitHotkeyScope,
- description: 'Search all',
- hotkeyToken: TOKENS.soup.openSearch,
- keyDownHandler: () => {
- setSelectedView(VIEWCONFIG_DEFAULTS_IDS_ENUM.all);
- setTimeout(() => {
- focusSearch();
- }, 0);
- return true;
- },
- displayPriority: 5,
- });
-
- const { dispose: disposeCmd } = registerHotkey({
- hotkey: ['cmd+f'],
- scopeId: splitContext.splitHotkeyScope,
- description: 'Search in current view',
- keyDownHandler: () => {
- focusSearch();
- return true;
- },
- displayPriority: 5,
- });
-
- onCleanup(() => {
- disposeSlash();
- disposeCmd();
- });
- });
-
- return (
- <SplitToolbarLeft class="min-w-0">
- <div class="flex ml-2 h-full items-center gap-1">
- <Show
- when={props.isLoading() && searchText()}
- fallback={
- <Show
- when={searchText()}
- fallback={
- <DeprecatedIconButton
- size="sm"
- icon={SearchIcon}
- theme="clear"
- tooltip={{ label: 'Search' }}
- tabIndex={-1}
- onClick={() => {
- inputRef?.focus();
- }}
- />
- }
- >
- <DeprecatedIconButton
- size="sm"
- icon={XIcon}
- theme="clear"
- tooltip={{ label: 'Clear search' }}
- tabIndex={-1}
- onClick={() => {
- setSearchText('');
- inputRef?.focus();
- }}
- />
- </Show>
- }
- >
- <DeprecatedIconButton
- size="sm"
- icon={LoadingSpinner}
- theme="clear"
- tooltip={{ label: 'Cancel search' }}
- class="[&_svg]:animate-spin"
- tabIndex={-1}
- onClick={() => {
- setSearchText('');
- inputRef?.focus();
- }}
- />
- </Show>
- <input
- ref={inputRef}
- id={getInputId(selectedView())}
- placeholder={`Search in ${viewName()}`}
- value={searchText()}
- onInput={(e) => {
- setSearchText(e.target.value);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Escape') {
- e.preventDefault();
- e.currentTarget.blur();
- } else if (e.key === 'Enter') {
- e.preventDefault();
- e.currentTarget.blur();
- selectionClick();
- } else if (e.key === 'ArrowDown') {
- e.preventDefault();
- e.currentTarget.blur();
- focusNextEntity();
- }
- }}
- class="p-1 pr-0 border-0 outline-none! focus:outline-none ring-0! focus:ring-0 flex-1 text-ink text-sm truncate min-w-0"
- />
- </div>
- </SplitToolbarLeft>
- );
-}
diff --git a/js/app/packages/app/component/ViewConfig.tsx b/js/app/packages/app/component/ViewConfig.tsx
deleted file mode 100644
index 7cf1d849bc..0000000000
--- a/js/app/packages/app/component/ViewConfig.tsx
+++ /dev/null
@@ -1,538 +0,0 @@
-import { ENABLE_TASKS_TABS } from '@core/constant/featureFlags';
-import {
- DEFAULT_VIEWS,
- type DefaultView,
- type ViewId,
- type ViewLabel,
-} from '@core/types/view';
-import type { WithCustomUserInput } from '@core/user';
-import type { DeepPartial } from '@core/util/withRequired';
-import {
- type EntityData,
- type ExpandedEntityType,
- isTaskEntity,
- queryKeys,
- type WithNotification,
-} from '@macro-entity';
-import {
- markNotificationsForEntityAsDone,
- type NotificationSource,
-} from '@notifications';
-import { emailClient } from '@service-email/client';
-import stringify from 'json-stable-stringify';
-import { queryClient } from '../../macro-entity/src/queries/client';
-import type { PropertyFilter } from './PropertyFilterTypes';
-import type { SoupContext } from './SoupContext';
-
-// for custom views that extend the unified list view
-export type ViewType = 'project';
-
-export type ViewData = {
- id: ViewId;
- view: ViewLabel;
- viewType?: ViewType;
- selectedEntity: EntityData | undefined;
- scrollOffset: number | undefined;
- initialConfig: string | undefined;
- hasUserInteractedEntity: boolean;
- searchText: string | undefined;
- multiSelectEntities: EntityData[];
-} & ViewConfigBase;
-
-/** maps view id to view data */
-export type ViewDataMap = Record<ViewId, ViewData>;
-
-export const KNOWN_FILE_TYPES = [
- 'md',
- 'code',
- 'image',
- 'canvas',
- 'pdf',
-] as const;
-
-export type DocumentTypeFilter =
- | 'md'
- | 'code'
- | 'image'
- | 'canvas'
- | 'pdf'
- | 'unknown';
-
-export type FilterOptions = {
- notificationFilter: 'all' | 'unread' | 'notDone';
- importantFilter: boolean;
- typeFilter: ExpandedEntityType[];
- documentTypeFilter: DocumentTypeFilter[];
- projectFilter?: string;
- fromFilter?: WithCustomUserInput<'user' | 'contact'>[];
- focusFilters?: ('signal' | 'noise')[];
- unreadOnly?: boolean;
- /**
- * Further refines `channel` entities:
- * - `people`: direct messages
- * - `groups`: non-DM channels (private / organization / public)
- *
- * Empty array means "no refinement" (i.e. include all channels).
- */
- channelCategoryFilter?: Array<'people' | 'groups'>;
- propertyFilters?: PropertyFilter[];
-};
-
-export type SystemSortOption =
- | 'updated_at'
- | 'created_at'
- | 'viewed_at'
- | 'frecency';
-
-export type SortOptions = {
- sortOrder: 'ascending' | 'descending';
-} & (
- | { type: 'systemSortOption'; sortBy: SystemSortOption }
- | { type: 'property'; propertyId: string }
-);
-
-export type DisplayOptions = {
- layout: 'compact' | 'expanded' | 'visual';
- unrollNotifications: boolean;
- showUnreadIndicator: boolean;
- displayProperties: string[];
- limit?: number;
-};
-
-export type HotkeyOptions = {
- e: (
- entity: WithNotification<EntityData>,
- extra?: {
- notificationSource?: NotificationSource;
- soupContext?: SoupContext;
- }
- ) => boolean;
-};
-
-export type ViewConfigBase = {
- viewType?: ViewType;
- filters: FilterOptions;
- sort: SortOptions;
- display: DisplayOptions;
-};
-
-export type ViewConfigEnhanced = {
- id: ViewId;
- view: ViewLabel;
- searchText?: string;
- hideToolbar?: true;
- onLoadingChange?: (isLoading: boolean) => void;
- hotkeyOptions?: Partial<HotkeyOptions>;
-} & ViewConfigBase;
-
-export type ClientFilterContext = {
- soupContext?: SoupContext;
-};
-
-export type ClientFilter = {
- id: string;
- predicate: (
- entity: WithNotification<EntityData>,
- ctx?: ClientFilterContext
- ) => boolean;
-};
-
-export const VIEWCONFIG_BASE: ViewConfigBase = {
- sort: {
- type: 'systemSortOption',
- sortBy: 'updated_at',
- sortOrder: 'ascending',
- },
- filters: {
- notificationFilter: 'all',
- importantFilter: false,
- typeFilter: [],
- documentTypeFilter: [],
- projectFilter: undefined,
- fromFilter: [],
- focusFilters: [],
- unreadOnly: false,
- channelCategoryFilter: [],
- propertyFilters: [],
- },
- display: {
- layout: 'compact',
- unrollNotifications: false,
- showUnreadIndicator: false,
- displayProperties: [],
- limit: 100,
- },
-};
-
-export const PROJECT_VIEWCONFIG_BASE: ViewConfigBase = {
- viewType: 'project',
- sort: {
- type: 'systemSortOption',
- sortBy: 'viewed_at',
- sortOrder: 'descending',
- },
- filters: {
- notificationFilter: 'all',
- importantFilter: false,
- typeFilter: ['document', 'task', 'chat', 'project'],
- documentTypeFilter: [],
- projectFilter: undefined,
- fromFilter: [],
- },
- display: {
- layout: 'compact',
- unrollNotifications: false,
- showUnreadIndicator: true,
- displayProperties: [],
- limit: 100,
- },
-};
-
-const ALL_VIEWCONFIG_DEFAULTS = {
- signal: {
- view: 'Signal',
- filters: {
- notificationFilter: 'notDone',
- focusFilters: ['signal'],
- },
- sort: {
- sortBy: 'updated_at',
- },
- display: {
- unrollNotifications: true,
- showUnreadIndicator: true,
- },
- hotkeyOptions: {
- e: (entity, extra) => {
- if (entity.type === 'email') {
- archiveEmail(entity.id, {
- isDone: entity.done,
- optimisticallyExclude: true,
- });
- }
- if (isTaskEntity(entity)) {
- optimisticallyRemoveTaskFromSignal(entity.id);
- }
- if (extra?.notificationSource) {
- console.log('marking notification as done');
- markNotificationsForEntityAsDone(extra.notificationSource, entity);
- }
- return true;
- },
- },
- },
- noise: {
- view: 'Noise',
- filters: {
- notificationFilter: 'notDone',
- focusFilters: ['noise'],
- },
- sort: {
- sortBy: 'updated_at',
- },
- display: {
- unrollNotifications: true,
- showUnreadIndicator: true,
- },
- hotkeyOptions: {
- e: (entity, extra) => {
- if (entity.type === 'email') {
- archiveEmail(entity.id, {
- isDone: entity.done,
- optimisticallyExclude: true,
- });
- }
- if (extra?.notificationSource) {
- markNotificationsForEntityAsDone(extra.notificationSource, entity);
- }
- return true;
- },
- },
- },
- files: {
- view: 'Files',
- filters: {
- typeFilter: ['document'],
- },
- },
- people: {
- view: 'People',
- filters: {
- typeFilter: ['channel'],
- },
- display: {
- showUnreadIndicator: true,
- },
- },
- email: {
- view: 'Email',
- filters: {
- typeFilter: ['email'],
- },
- sort: {
- sortBy: 'updated_at',
- },
- display: {
- showUnreadIndicator: true,
- },
- hotkeyOptions: {
- e: (entity, extra) => {
- if (extra?.soupContext) {
- const {
- emailViewSignal: [emailView],
- } = extra.soupContext;
- if (emailView() === 'inbox') {
- if (entity.type === 'email') {
- archiveEmail(entity.id, {
- isDone: entity.done,
- optimisticallyExclude: true,
- });
- }
- return true;
- }
- }
- if (entity.type === 'email') {
- archiveEmail(entity.id, { isDone: entity.done });
- }
- return true;
- },
- },
- },
- tasks: {
- view: 'Tasks',
- filters: {
- typeFilter: ['task'],
- },
- },
- folders: {
- view: 'Folders',
- filters: {
- typeFilter: ['project'],
- },
- },
- all: {
- view: 'All',
- sort: {
- sortBy: 'viewed_at',
- },
- hotkeyOptions: {
- e: (entity, extra) => {
- if (entity.type === 'email') {
- archiveEmail(entity.id, {
- isDone: entity.done,
- optimisticallyExclude: true,
- });
- }
- if (extra?.notificationSource) {
- markNotificationsForEntityAsDone(extra.notificationSource, entity);
- }
- return true;
- },
- },
- },
-} satisfies Record<DefaultView, Omit<DeepPartial<ViewConfigEnhanced>, 'id'>>;
-
-export const VIEWCONFIG_DEFAULTS = Object.fromEntries(
- Object.entries(ALL_VIEWCONFIG_DEFAULTS).filter(([key]) => {
- if (key === 'tasks') return ENABLE_TASKS_TABS;
- return DEFAULT_VIEWS.includes(key as DefaultView);
- })
-) as Record<DefaultView, Omit<ViewConfigEnhanced, 'id'>>;
-
-export const VIEWCONFIG_DEFAULTS_IDS = Object.keys(
- VIEWCONFIG_DEFAULTS
-) as DefaultView[];
-export const VIEWCONFIG_DEFAULTS_IDS_ENUM = Object.fromEntries(
- Object.entries(VIEWCONFIG_DEFAULTS).map(([key]) => {
- return [key, key];
- })
-) as Record<DefaultView, string>;
-
-export const VIEWCONFIG_FILTER_SHOW_OPTIONS: readonly FilterOptions['notificationFilter'][] =
- ['all', 'unread', 'notDone'] as const;
-export const VIEWCONFIG_FILTER_FILETYPE_OPTIONS: readonly FilterOptions['documentTypeFilter'][number][] =
- ['md', 'code', 'image', 'canvas', 'pdf', 'unknown'] as const;
-export const VIEWCONFIG_DISPLAY_LAYOUT_OPTIONS: readonly DisplayOptions['layout'][] =
- ['compact', 'expanded', 'visual'] as const;
-export const VIEWCONFIG_SORT_BY: readonly SystemSortOption[] = [
- 'updated_at',
- 'created_at',
- 'viewed_at',
-] as const;
-export const VIEWCONFIG_SORT_ORDER: readonly SortOptions['sortOrder'][] = [
- 'ascending',
- 'descending',
-] as const;
-export const VIEWCONFIG_FILTER_DOCUMENT_TYPE_FILTER: readonly FilterOptions['documentTypeFilter'][number][] =
- ['md', 'pdf', 'canvas', 'code', 'image', 'unknown'] as const;
-export const VIEWCONFIG_FILTER_ENTITY_TYPE: readonly FilterOptions['typeFilter'][number][] =
- ['channel', 'chat', 'document', 'email', 'project', 'task'] as const;
-
-export async function archiveEmail(
- id: string,
- options: { isDone: boolean; optimisticallyExclude?: boolean }
-) {
- await Promise.all([
- queryClient.cancelQueries({ queryKey: queryKeys.all.email }),
- queryClient.cancelQueries({ queryKey: queryKeys.all.dss }),
- ]);
-
- const previousEmail = queryClient.getQueriesData<{
- pages: { items: EntityData[] }[];
- }>({
- queryKey: queryKeys.all.email,
- });
- const previousEmailThreadItemFromDss = queryClient.getQueriesData<{
- pages: { items: EntityData[] }[];
- }>({
- queryKey: queryKeys.all.dss,
- });
-
- const applyOptimistic = (data?: {
- pages: { items: (EntityData | { data: EntityData })[] }[];
- }) => {
- if (!data) return data;
-
- return {
- ...data,
- pages: data.pages.map((page) => ({
- ...page,
- items: options.optimisticallyExclude
- ? page.items.filter((item) => {
- if ('data' in item) {
- return item.data.id !== id;
- }
- return item.id !== id;
- })
- : page.items.map((item) => {
- if ('data' in item) {
- return item.data.id === id
- ? {
- ...item,
- data: {
- ...item.data,
- inboxVisible: false,
- },
- }
- : item;
- }
- return item.id === id
- ? {
- ...item,
- inboxVisible: false,
- }
- : item;
- }),
- })),
- };
- };
-
- for (const [key, data] of [
- ...previousEmailThreadItemFromDss,
- ...previousEmail,
- ]) {
- queryClient.setQueryData(key, applyOptimistic(data));
- }
-
- try {
- // server mutation
- await emailClient.flagArchived({ value: !options.isDone, id });
- } catch (_err) {
- // rollback on error
- for (const [key, data] of previousEmail) {
- queryClient.setQueryData(key, data);
- }
- for (const [key, data] of previousEmailThreadItemFromDss) {
- queryClient.setQueryData(key, data);
- }
- } finally {
- // revalidate
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
- queryClient.invalidateQueries({ queryKey: queryKeys.all.dss }),
- ]);
- }
-}
-
-/**
- * Optimistically removes a task from the DSS queries (signal view).
- * This is used when marking a task as done in the signal view to immediately
- * remove it from the list before the query refetches.
- */
-export async function optimisticallyRemoveTaskFromSignal(id: string) {
- await queryClient.cancelQueries({ queryKey: queryKeys.all.dss });
-
- const previousDss = queryClient.getQueriesData<{
- pages: { items: (EntityData | { data: EntityData })[] }[];
- }>({
- queryKey: queryKeys.all.dss,
- });
-
- // Filter out the task with the given ID
- for (const [key, data] of previousDss) {
- if (!data) continue;
-
- const updatedData = {
- ...data,
- pages: data.pages.map((page) => ({
- ...page,
- items: page.items.filter((item) => {
- if ('data' in item) {
- return item.data.id !== id;
- }
- return item.id !== id;
- }),
- })),
- };
-
- queryClient.setQueryData(key, updatedData);
- }
-
- // Note: We don't rollback on error since the mutation happens separately
- // via setPropertyStatusCompleteMutation. The query invalidation will
- // sync the state after the mutation completes.
-}
-
-/**
- * Normalizes an object by treating [], undefined, null, or missing properties as equivalent.
- * Removes properties that are empty arrays, undefined, or null, and recursively processes nested objects.
- */
-const normalizeConfig = (obj: any): any => {
- if (obj === null || obj === undefined) {
- return undefined;
- }
-
- if (Array.isArray(obj)) {
- // Empty arrays are treated as undefined (missing property)
- if (obj.length === 0) {
- return undefined;
- }
- // For arrays with items, normalize each item recursively but keep the array structure
- return obj.map((item) => normalizeConfig(item));
- }
-
- if (typeof obj === 'object') {
- const normalized: any = {};
- for (const [key, value] of Object.entries(obj)) {
- const normalizedValue = normalizeConfig(value);
- // Only include the property if it's not undefined after normalization
- if (normalizedValue !== undefined) {
- normalized[key] = normalizedValue;
- }
- }
- return normalized;
- }
-
- return obj;
-};
-
-/**
- * Deep comparison that treats [], undefined, null, or missing properties as equivalent.
- */
-export const isConfigEqual = (a: any, b: any): boolean => {
- const normalizedA = normalizeConfig(a);
- const normalizedB = normalizeConfig(b);
-
- // Use stringify for comparison after normalization
- return stringify(normalizedA) === stringify(normalizedB);
-};
diff --git a/js/app/packages/app/component/import-linear/ImportLinear.tsx b/js/app/packages/app/component/import-linear/ImportLinear.tsx
index 1e8e3e5cf8..6a08156f7f 100644
--- a/js/app/packages/app/component/import-linear/ImportLinear.tsx
+++ b/js/app/packages/app/component/import-linear/ImportLinear.tsx
@@ -4,10 +4,8 @@ import { parseCsv } from '@core/util/csv';
import { createTask } from '@core/util/create';
import { linearCsvRecordToMacroTaskDraft } from '@core/util/linearImport';
import { buildSimpleEntityUrl } from '@core/util/url';
-import {
- queryKeys,
- useQueryClient as useEntityQueryClient,
-} from '@macro-entity';
+import { useQueryClient } from '@queries/client';
+import { soupKeys } from '@queries/soup/keys';
import { useUpsertToHistoryMutation } from '@queries/history/history';
import { useContacts } from '@core/user';
import { Button } from '@ui/components/Button';
@@ -30,7 +28,7 @@ function lower(s: string): string {
export default function ImportLinear() {
const contacts = useContacts();
const upsertToHistory = useUpsertToHistoryMutation();
- const entityQueryClient = useEntityQueryClient();
+ const queryClient = useQueryClient();
const [fileName, setFileName] = createSignal<string>('');
const [parseError, setParseError] = createSignal<string>('');
@@ -187,8 +185,8 @@ export default function ImportLinear() {
setProgress({ type: 'running', done: i + 1, total: rows.length });
}
- // Refresh DSS-backed lists so the new tasks appear.
- entityQueryClient.invalidateQueries({ queryKey: queryKeys.all.dss });
+ // Refresh soup items so the new tasks appear.
+ queryClient.invalidateQueries({ queryKey: soupKeys.items._def });
setCreatedIds(createdList);
setProgress({ type: 'done', created, skipped, failed });
diff --git a/js/app/packages/app/component/mobile/MobileDock.tsx b/js/app/packages/app/component/mobile/MobileDock.tsx
index 36b6830293..904006e95d 100644
--- a/js/app/packages/app/component/mobile/MobileDock.tsx
+++ b/js/app/packages/app/component/mobile/MobileDock.tsx
@@ -7,13 +7,8 @@ import { impactFeedback } from '@tauri-apps/plugin-haptics';
import { batch, type Component, type JSX } from 'solid-js';
import { setCreateMenuOpen } from '../Launcher';
import { useSplitPanelOrThrow } from '../split-layout/layoutUtils';
-import { VIEWCONFIG_BASE } from '../ViewConfig';
-import { FOCUS_FILTER_CONFIGS } from '../Soup/utils/filterConfigs';
-import {
- isEntityTypeFilterActive,
- isFocusFilterActive,
- sameSet,
-} from '../Soup/utils/filterHelpers';
+import { useSoup } from '@app/component/next-soup/soup-context';
+import type { FilterID } from '@app/component/next-soup/filters/filters';
type MobileDockButtonProps = {
icon: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
@@ -25,6 +20,7 @@ type MobileDockButtonProps = {
function MobileDockButton(props: MobileDockButtonProps) {
return (
<button
+ type="button"
onClick={() => {
impactFeedback('light');
props.onClick();
@@ -43,18 +39,16 @@ function MobileDockButton(props: MobileDockButtonProps) {
export function MobileDock() {
const splitContext = useSplitPanelOrThrow();
- const { selectedView, setViewDataStore, viewsDataStore } =
- splitContext.soupContext;
+ const soup = useSoup();
const splitContent = () => splitContext.handle.content();
- const view = () => viewsDataStore[selectedView()];
- const filters = () => view()?.filters ?? VIEWCONFIG_BASE.filters;
- const typeFilter = () => filters().typeFilter ?? [];
- const channelCategoryFilter = () => filters().channelCategoryFilter ?? [];
- const focusFilters = () => filters().focusFilters ?? [];
- const splitIsUnifiedList = () =>
- splitContent().type === 'component' && splitContent().id === 'unified-list';
+ const splitIsUnifiedList = () => {
+ const id = splitContent().id;
+ const type = splitContent().type;
+
+ return type === 'component' && id === 'unified-list';
+ };
const ensureUnifiedList = () => {
if (splitIsUnifiedList()) return;
@@ -64,64 +58,35 @@ export function MobileDock() {
};
const isInboxActive = () =>
- isFocusFilterActive(focusFilters(), 'signal') && splitIsUnifiedList();
+ soup.filters.isActive('signal') && splitIsUnifiedList();
const isPeopleTeamsActive = () =>
- isEntityTypeFilterActive(typeFilter(), 'channel') &&
- sameSet(channelCategoryFilter(), ['people', 'groups']) &&
- splitIsUnifiedList();
+ soup.filters.isActive('teams-and-people') && splitIsUnifiedList();
const isTasksActive = () =>
- isEntityTypeFilterActive(typeFilter(), 'task') && splitIsUnifiedList();
+ soup.filters.isActive('task') && splitIsUnifiedList();
const isAllActive = () =>
!isInboxActive() &&
!isPeopleTeamsActive() &&
!isTasksActive() &&
splitIsUnifiedList();
- const setFocusFilter = (target: 'signal' | 'noise' | 'none') => {
- const config =
- target === 'none'
- ? FOCUS_FILTER_CONFIGS.none
- : FOCUS_FILTER_CONFIGS[target];
- const viewId = selectedView();
- setViewDataStore(viewId, 'filters', 'focusFilters', [
- ...config.focusFilters,
- ]);
- setViewDataStore(
- viewId,
- 'filters',
- 'notificationFilter',
- config.notificationFilter
- );
- setViewDataStore(
- viewId,
- 'display',
- 'unrollNotifications',
- config.unrollNotifications
- );
+ const activateFilter = (filter: FilterID) => {
+ soup.filters.activate(filter);
};
- const setTypeFilters = ({
- type,
- channelCategories = [],
- }: {
- type: Array<'channel' | 'chat' | 'document' | 'email' | 'project' | 'task'>;
- channelCategories?: Array<'people' | 'groups'>;
- }) => {
- const viewId = selectedView();
- setViewDataStore(viewId, 'filters', 'typeFilter', type);
- setViewDataStore(viewId, 'filters', 'documentTypeFilter', []);
- setViewDataStore(viewId, 'filters', 'channelCategoryFilter', [
- ...channelCategories,
- ]);
+ const toggleSignalFilter = (value: boolean) => {
+ // If we're going to be removing the signal filter,
+ // we should replace it with the explicit-noise filter
+ if (!value) {
+ activateFilter('explicit-noise');
+ soup.filters.deactivate('not-done');
+ } else {
+ activateFilter('signal');
+ activateFilter('not-done');
+ }
};
const clearSearchFilters = () => {
- const viewId = selectedView();
- batch(() => {
- setTypeFilters({ type: [], channelCategories: [] });
- setFocusFilter('none');
- setViewDataStore(viewId, 'filters', 'unreadOnly', false);
- });
+ soup.filters.clear();
};
return (
@@ -142,8 +107,8 @@ export function MobileDock() {
onClick={() => {
ensureUnifiedList();
batch(() => {
- setFocusFilter('signal');
- setTypeFilters({ type: [] });
+ clearSearchFilters();
+ toggleSignalFilter(true);
});
}}
/>
@@ -154,11 +119,8 @@ export function MobileDock() {
onClick={() => {
ensureUnifiedList();
batch(() => {
- setFocusFilter('none');
- setTypeFilters({
- type: ['channel'],
- channelCategories: ['people', 'groups'],
- });
+ toggleSignalFilter(false);
+ activateFilter('teams-and-people');
});
}}
/>
@@ -169,8 +131,8 @@ export function MobileDock() {
onClick={() => {
ensureUnifiedList();
batch(() => {
- setFocusFilter('none');
- setTypeFilters({ type: ['task'] });
+ toggleSignalFilter(false);
+ activateFilter('task');
});
}}
/>
diff --git a/js/app/packages/app/component/next-soup/actions/index.ts b/js/app/packages/app/component/next-soup/actions/index.ts
new file mode 100644
index 0000000000..a34aaa43f1
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/index.ts
@@ -0,0 +1,7 @@
+export { makeMarkDoneAction } from './make-mark-done-action';
+export { makeDeleteAction } from './make-delete-action';
+export { makeRenameAction } from './make-rename-action';
+export { makeCopyAction } from './make-copy-action';
+export { makeMoveToProjectAction } from './make-move-to-project-action';
+
+export { useEntityActionHotkeys } from './use-entity-action-hotkeys';
diff --git a/js/app/packages/app/component/next-soup/actions/make-copy-action.ts b/js/app/packages/app/component/next-soup/actions/make-copy-action.ts
new file mode 100644
index 0000000000..bc74675c94
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/make-copy-action.ts
@@ -0,0 +1,29 @@
+import { toast } from '@core/component/Toast/Toast';
+import type { EntityData } from '@macro-entity';
+import type { SoupState } from '../create-soup-state';
+import { createBulkCopyDssEntityMutation } from '../../../../macro-entity/src/queries/dss';
+
+export const makeCopyAction = () => {
+ const bulkCopyMutation = createBulkCopyDssEntityMutation();
+
+ const canExecute = (entity: EntityData): boolean => {
+ return entity.type !== 'channel' && entity.type !== 'email';
+ };
+
+ const execute = async (entities: EntityData[]) => {
+ await bulkCopyMutation.mutateAsync({
+ entities,
+ name: (name) => name,
+ });
+ toast.success(
+ entities.length > 1 ? `Copied ${entities.length} items` : 'Copied'
+ );
+ };
+
+ const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ await execute(entities);
+ soup.selection.clear();
+ };
+
+ return { canExecute, execute, executeWithSoup };
+};
diff --git a/js/app/packages/app/component/next-soup/actions/make-delete-action.ts b/js/app/packages/app/component/next-soup/actions/make-delete-action.ts
new file mode 100644
index 0000000000..f4aa4b209c
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/make-delete-action.ts
@@ -0,0 +1,86 @@
+import { toast } from '@core/component/Toast/Toast';
+import type { EntityData } from '@macro-entity';
+import { openBulkEditModal } from '@app/component/bulk-edit-entity/BulkEditEntityModal';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import { globalRemoveFromSplitHistory } from '@app/component/split-layout/layoutUtils';
+import type { SoupState } from '../create-soup-state';
+import { restoreSoupFocus } from '../utils';
+import { useMaybePreviewPanel } from '@app/component/PreviewPanel';
+
+type MakeDeleteOptions = {
+ userId: () => string | undefined;
+};
+
+export const makeDeleteAction = (options: MakeDeleteOptions) => {
+ const { userId } = options;
+
+ const canExecute = (entity: EntityData): boolean => {
+ if (entity.type === 'channel' || entity.type === 'email') {
+ return false;
+ }
+ return entity.ownerId === userId();
+ };
+
+ const execute = async (entities: EntityData[]) => {
+ openBulkEditModal({
+ view: 'delete',
+ entities,
+ onFinish: () => {
+ const splitManager = globalSplitManager();
+ if (splitManager) {
+ const entityIdSet = new Set(entities.map(({ id }) => id));
+ globalRemoveFromSplitHistory(splitManager, (entry) =>
+ entityIdSet.has(entry.id)
+ );
+ }
+ toast.success(
+ entities.length > 1 ? `Deleted ${entities.length} items` : 'Deleted'
+ );
+ },
+ });
+ };
+
+ const previewPanel = useMaybePreviewPanel();
+
+ const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const currentIndex = soup.focus.index();
+ const nextEntity =
+ soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
+
+ const inPreview = previewPanel !== undefined;
+
+ openBulkEditModal({
+ view: 'delete',
+ entities,
+ onFinish: () => {
+ const splitManager = globalSplitManager();
+ if (splitManager) {
+ const entityIdSet = new Set(entities.map(({ id }) => id));
+ globalRemoveFromSplitHistory(splitManager, (entry) =>
+ entityIdSet.has(entry.id)
+ );
+ }
+
+ soup.selection.clear();
+ if (nextEntity) {
+ soup.focus.set(nextEntity.id);
+ }
+
+ toast.success(
+ entities.length > 1 ? `Deleted ${entities.length} items` : 'Deleted'
+ );
+
+ restoreSoupFocus(nextEntity?.id, inPreview);
+ },
+ onCancel: () => {
+ const firstEntity = entities[0];
+ if (firstEntity) {
+ soup.focus.set(firstEntity.id);
+ }
+ restoreSoupFocus(firstEntity?.id, inPreview);
+ },
+ });
+ };
+
+ return { canExecute, execute, executeWithSoup };
+};
diff --git a/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
new file mode 100644
index 0000000000..b6a66e8039
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
@@ -0,0 +1,120 @@
+import { toast } from '@core/component/Toast/Toast';
+import {
+ type EntityData,
+ isTaskEntity,
+ type TaskEntityWithProperties,
+} from '@macro-entity';
+import {
+ markNotificationsForEntityAsDone,
+ type NotificationSource,
+} from '@notifications';
+import { useSetPropertyStatusCompleteMutation } from '@queries/properties/entity';
+import type { PropertiesEntityType } from '@service-properties/client';
+import type { SoupState } from '../create-soup-state';
+import {
+ archiveEmail,
+ isCurrentUserAssigned,
+ isTaskClosed,
+} from '@app/component/next-soup/utils';
+
+type MakeMarkDoneOptions = {
+ userId: () => string | undefined;
+ notificationSource: () => NotificationSource;
+};
+
+const getPropertiesEntityType = (
+ entity: EntityData
+): PropertiesEntityType | undefined => {
+ if (isTaskEntity(entity)) return 'TASK';
+ if (entity.type === 'email') return 'THREAD';
+ if (entity.type === 'document') return 'DOCUMENT';
+ if (entity.type === 'project') return 'PROJECT';
+ return undefined;
+};
+
+export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
+ const { userId, notificationSource } = options;
+
+ const setPropertyStatusCompleteMutation =
+ useSetPropertyStatusCompleteMutation();
+
+ const canExecute = (entity: EntityData): boolean => {
+ if (entity.type === 'email' || entity.type === 'channel') {
+ return true;
+ }
+
+ if (isTaskEntity(entity)) {
+ const currentUserId = userId();
+ if (
+ !isCurrentUserAssigned(
+ entity as TaskEntityWithProperties,
+ currentUserId
+ )
+ ) {
+ return false;
+ }
+ if (isTaskClosed(entity as TaskEntityWithProperties)) {
+ return false;
+ }
+ return true;
+ }
+
+ if (entity.type === 'document' || entity.type === 'project') {
+ return true;
+ }
+
+ return false;
+ };
+
+ const execute = async (entities: EntityData[]) => {
+ const source = notificationSource();
+
+ for (const entity of entities) {
+ if (entity.type === 'email') {
+ archiveEmail(entity.id, {
+ isDone: entity.done,
+ optimisticallyExclude: true,
+ });
+ }
+
+ markNotificationsForEntityAsDone(source, entity);
+
+ const entityType = getPropertiesEntityType(entity);
+ if (entityType) {
+ setPropertyStatusCompleteMutation.mutate({
+ entityType,
+ entityId: entity.id,
+ });
+ }
+ }
+
+ toast.success(
+ entities.length > 1
+ ? `Marked ${entities.length} items as done`
+ : 'Marked as done'
+ );
+ };
+
+ const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const currentIndex = soup.focus.index();
+ const nextEntity =
+ soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
+
+ // Run collapse animation if conditions are met (touch modality + not-done filter active)
+ if (soup.collapseEntity.shouldCollapse()) {
+ const collapse = soup.collapseEntity.callback();
+ if (collapse) {
+ await Promise.all(entities.map((entity) => collapse(entity.id)));
+ }
+ }
+
+ await execute(entities);
+
+ soup.selection.clear();
+ if (nextEntity) {
+ soup.focus.set(nextEntity.id);
+ }
+ };
+
+ return { canExecute, execute, executeWithSoup };
+};
diff --git a/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.ts b/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.ts
new file mode 100644
index 0000000000..96354bd3cc
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.ts
@@ -0,0 +1,62 @@
+import { toast } from '@core/component/Toast/Toast';
+import type { EntityData } from '@macro-entity';
+import { openBulkEditModal } from '@app/component/bulk-edit-entity/BulkEditEntityModal';
+import type { SoupState } from '../create-soup-state';
+import { restoreSoupFocus } from '../utils';
+import { useMaybePreviewPanel } from '@app/component/PreviewPanel';
+
+export const makeMoveToProjectAction = () => {
+ const canExecute = (entity: EntityData): boolean => {
+ return entity.type !== 'channel' && entity.type !== 'email';
+ };
+
+ const execute = async (entities: EntityData[]) => {
+ openBulkEditModal({
+ view: 'moveToProject',
+ entities,
+ onFinish: () => {
+ toast.success(
+ entities.length > 1
+ ? `Moved ${entities.length} items`
+ : 'Moved to folder'
+ );
+ },
+ });
+ };
+
+ const previewPanel = useMaybePreviewPanel();
+
+ const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const currentIndex = soup.focus.index();
+ const nextEntity =
+ soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
+
+ const inPreview = previewPanel !== undefined;
+
+ openBulkEditModal({
+ view: 'moveToProject',
+ entities,
+ onFinish: () => {
+ soup.selection.clear();
+ if (nextEntity) {
+ soup.focus.set(nextEntity.id);
+ }
+ toast.success(
+ entities.length > 1
+ ? `Moved ${entities.length} items`
+ : 'Moved to folder'
+ );
+ restoreSoupFocus(nextEntity?.id, inPreview);
+ },
+ onCancel: () => {
+ const firstEntity = entities[0];
+ if (firstEntity) {
+ soup.focus.set(firstEntity.id);
+ }
+ restoreSoupFocus(firstEntity?.id, inPreview);
+ },
+ });
+ };
+
+ return { canExecute, execute, executeWithSoup };
+};
diff --git a/js/app/packages/app/component/next-soup/actions/make-rename-action.ts b/js/app/packages/app/component/next-soup/actions/make-rename-action.ts
new file mode 100644
index 0000000000..53cc6103d0
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/make-rename-action.ts
@@ -0,0 +1,67 @@
+import { toast } from '@core/component/Toast/Toast';
+import type { EntityData } from '@macro-entity';
+import { openBulkEditModal } from '@app/component/bulk-edit-entity/BulkEditEntityModal';
+import type { SoupState } from '../create-soup-state';
+import { restoreSoupFocus } from '../utils';
+import { useMaybePreviewPanel } from '@app/component/PreviewPanel';
+
+type MakeRenameOptions = {
+ userId: () => string | undefined;
+};
+
+export const makeRenameAction = (options: MakeRenameOptions) => {
+ const { userId } = options;
+
+ const canExecute = (entity: EntityData): boolean => {
+ if (entity.type === 'email') return false;
+
+ if (entity.type === 'channel') {
+ if (entity.channelType === 'direct_message') return false;
+ return entity.ownerId === userId();
+ }
+
+ return entity.ownerId === userId();
+ };
+
+ const execute = async (entities: EntityData[]) => {
+ openBulkEditModal({
+ view: 'rename',
+ entities,
+ onFinish: () => {
+ toast.success(
+ entities.length > 1 ? `Renamed ${entities.length} items` : 'Renamed'
+ );
+ },
+ });
+ };
+
+ const previewPanel = useMaybePreviewPanel();
+
+ const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {
+ const firstEntity = entities[0];
+
+ const inPreview = previewPanel !== undefined;
+
+ openBulkEditModal({
+ view: 'rename',
+ entities,
+ onFinish: () => {
+ toast.success(
+ entities.length > 1 ? `Renamed ${entities.length} items` : 'Renamed'
+ );
+ if (firstEntity) {
+ soup.focus.set(firstEntity.id);
+ }
+ restoreSoupFocus(firstEntity?.id, inPreview);
+ },
+ onCancel: () => {
+ if (firstEntity) {
+ soup.focus.set(firstEntity.id);
+ }
+ restoreSoupFocus(firstEntity?.id, inPreview);
+ },
+ });
+ };
+
+ return { canExecute, execute, executeWithSoup };
+};
diff --git a/js/app/packages/app/component/next-soup/actions/use-entity-action-hotkeys.ts b/js/app/packages/app/component/next-soup/actions/use-entity-action-hotkeys.ts
new file mode 100644
index 0000000000..00d1e30968
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/use-entity-action-hotkeys.ts
@@ -0,0 +1,181 @@
+import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
+import { HotkeyTags } from '@core/hotkey/constants';
+import { TOKENS } from '@core/hotkey/tokens';
+import type { EntityData } from '@macro-entity';
+import type { SoupState } from '../create-soup-state';
+import {
+ makeCopyAction,
+ makeDeleteAction,
+ makeMarkDoneAction,
+ makeMoveToProjectAction,
+ makeRenameAction,
+} from './index';
+import { useUserId } from '@core/context/user';
+import { registerHotkey } from '@core/hotkey/hotkeys';
+
+type UseEntityActionHotkeysOptions = {
+ scopeId: string;
+ soup: SoupState;
+ condition?: () => boolean;
+};
+
+export const useEntityActionHotkeys = (
+ options: UseEntityActionHotkeysOptions
+) => {
+ const { scopeId, soup, condition } = options;
+
+ const userId = useUserId();
+ const notificationSource = useGlobalNotificationSource();
+
+ const markDone = makeMarkDoneAction({
+ userId: () => userId(),
+ notificationSource: () => notificationSource,
+ });
+
+ const deleteAction = makeDeleteAction({
+ userId: () => userId(),
+ });
+
+ const renameAction = makeRenameAction({
+ userId: () => userId(),
+ });
+
+ const copyAction = makeCopyAction();
+
+ const moveToProjectAction = makeMoveToProjectAction();
+
+ const getEntitiesForAction = (): EntityData[] => {
+ const selected = soup.selection.selected();
+ if (selected.length > 0) return selected;
+
+ const focused = soup.focus.item();
+ return focused ? [focused] : [];
+ };
+
+ // Mark Done - 'e'
+ registerHotkey({
+ hotkey: ['e'],
+ hotkeyToken: TOKENS.entity.action.markDone,
+ scopeId,
+ description: 'Mark done',
+ keyDownHandler: () => {
+ const entities = getEntitiesForAction();
+ if (entities.length === 0) return false;
+ if (!entities.some(markDone.canExecute)) return false;
+
+ markDone.executeWithSoup(entities, soup);
+ return true;
+ },
+ condition: () => {
+ if (condition && !condition()) return false;
+ const entities = getEntitiesForAction();
+ return entities.some(markDone.canExecute);
+ },
+ displayPriority: 10,
+ tags: [HotkeyTags.SelectionModification],
+ });
+
+ // Delete - 'delete', 'backspace'
+ registerHotkey({
+ hotkey: ['delete', 'backspace'],
+ hotkeyToken: TOKENS.entity.action.delete,
+ scopeId,
+ description: () => {
+ const count = getEntitiesForAction().length;
+ return count > 1 ? 'Delete items' : 'Delete item';
+ },
+ keyDownHandler: () => {
+ const entities = getEntitiesForAction();
+ if (entities.length === 0) return false;
+ if (!entities.every(deleteAction.canExecute)) return false;
+
+ deleteAction.executeWithSoup(entities, soup);
+ return true;
+ },
+ condition: () => {
+ if (condition && !condition()) return false;
+ const entities = getEntitiesForAction();
+ return entities.length > 0 && entities.every(deleteAction.canExecute);
+ },
+ displayPriority: 10,
+ tags: [HotkeyTags.SelectionModification],
+ });
+
+ // Rename - 'r'
+ registerHotkey({
+ hotkey: ['r'],
+ hotkeyToken: TOKENS.entity.action.rename,
+ scopeId,
+ description: () => {
+ const count = getEntitiesForAction().length;
+ return count > 1 ? 'Rename items' : 'Rename item';
+ },
+ keyDownHandler: () => {
+ const entities = getEntitiesForAction();
+ if (entities.length === 0) return false;
+ if (!entities.every(renameAction.canExecute)) return false;
+
+ renameAction.executeWithSoup(entities, soup);
+ return true;
+ },
+ condition: () => {
+ if (condition && !condition()) return false;
+ const entities = getEntitiesForAction();
+ return entities.length > 0 && entities.every(renameAction.canExecute);
+ },
+ displayPriority: 10,
+ tags: [HotkeyTags.SelectionModification],
+ });
+
+ // Copy - 'cmd+d'
+ registerHotkey({
+ hotkey: ['cmd+d'],
+ hotkeyToken: TOKENS.entity.action.copy,
+ scopeId,
+ description: () => {
+ const count = getEntitiesForAction().length;
+ return count > 1 ? 'Duplicate items' : 'Duplicate item';
+ },
+ keyDownHandler: () => {
+ const entities = getEntitiesForAction();
+ if (entities.length === 0) return false;
+ if (!entities.some(copyAction.canExecute)) return false;
+
+ copyAction.executeWithSoup(entities, soup);
+ return true;
+ },
+ condition: () => {
+ if (condition && !condition()) return false;
+ const entities = getEntitiesForAction();
+ return entities.some(copyAction.canExecute);
+ },
+ displayPriority: 10,
+ tags: [HotkeyTags.SelectionModification],
+ });
+
+ // Move to folder - 'm'
+ registerHotkey({
+ hotkey: ['m'],
+ hotkeyToken: TOKENS.entity.action.moveToFolder,
+ scopeId,
+ description: () => {
+ const count = getEntitiesForAction().length;
+ return count > 1 ? 'Move items to folder' : 'Move to folder';
+ },
+ keyDownHandler: () => {
+ const entities = getEntitiesForAction();
+ if (entities.length === 0) return false;
+ if (!entities.some(moveToProjectAction.canExecute)) return false;
+
+ moveToProjectAction.executeWithSoup(entities, soup);
+ return true;
+ },
+ condition: () => {
+ if (condition && !condition()) return false;
+ const entities = getEntitiesForAction();
+ return entities.some(moveToProjectAction.canExecute);
+ },
+ displayPriority: 10,
+ tags: [HotkeyTags.SelectionModification],
+ });
+};
diff --git a/js/app/packages/app/component/next-soup/create-sort-state.test.ts b/js/app/packages/app/component/next-soup/create-sort-state.test.ts
new file mode 100644
index 0000000000..8240c24531
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/create-sort-state.test.ts
@@ -0,0 +1,278 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+import { createSortState, type SortConfig } from './create-sort-state';
+
+type Item = { name: string; date: number; priority: number };
+
+const sortConfigs = {
+ name: {
+ id: 'name',
+ fn: (a: Item, b: Item) => a.name.localeCompare(b.name),
+ },
+ date: {
+ id: 'date',
+ fn: (a: Item, b: Item) => a.date - b.date,
+ desc: true,
+ },
+ priority: {
+ id: 'priority',
+ fn: (a: Item, b: Item) => a.priority - b.priority,
+ },
+} satisfies Record<string, SortConfig<Item>>;
+
+describe('createSortState', () => {
+ describe('initial state', () => {
+ it('should start with no active sorts by default', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs);
+
+ expect(sort.active()).toEqual([]);
+
+ dispose();
+ });
+ });
+
+ it('should accept initial sort ids', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['name', 'date']);
+
+ expect(sort.active()).toEqual([sortConfigs.name, sortConfigs.date]);
+
+ dispose();
+ });
+ });
+
+ it('should ignore invalid initial sort ids', () => {
+ createRoot((dispose) => {
+ // @ts-expect-error - testing invalid id
+ const sort = createSortState(sortConfigs, ['name', 'invalid']);
+
+ expect(sort.active()).toEqual([sortConfigs.name]);
+
+ dispose();
+ });
+ });
+
+ it('should expose available configs', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs);
+
+ expect(sort.available).toBe(sortConfigs);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('isActive', () => {
+ it('should return true for active sorts', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['name']);
+
+ expect(sort.isActive('name')).toBe(true);
+ expect(sort.isActive('date')).toBe(false);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('toggle', () => {
+ it('should add sort when not active', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs);
+
+ sort.toggle('name');
+
+ expect(sort.active()).toEqual([sortConfigs.name]);
+ expect(sort.isActive('name')).toBe(true);
+
+ dispose();
+ });
+ });
+
+ it('should remove sort when active', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['name']);
+
+ sort.toggle('name');
+
+ expect(sort.active()).toEqual([]);
+ expect(sort.isActive('name')).toBe(false);
+
+ dispose();
+ });
+ });
+
+ it('should force add with value=true', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs);
+
+ sort.toggle('name', true);
+
+ expect(sort.isActive('name')).toBe(true);
+
+ // Toggling again with true should keep it active
+ sort.toggle('name', true);
+
+ expect(sort.isActive('name')).toBe(true);
+
+ dispose();
+ });
+ });
+
+ it('should force remove with value=false', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['name']);
+
+ sort.toggle('name', false);
+
+ expect(sort.isActive('name')).toBe(false);
+
+ // Toggling again with false should keep it inactive
+ sort.toggle('name', false);
+
+ expect(sort.isActive('name')).toBe(false);
+
+ dispose();
+ });
+ });
+
+ it('should not add invalid sort id', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs);
+
+ // @ts-expect-error - testing invalid id
+ sort.toggle('invalid');
+
+ expect(sort.active()).toEqual([]);
+
+ dispose();
+ });
+ });
+
+ it('should append to existing sorts', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['name']);
+
+ sort.toggle('date');
+
+ expect(sort.active()).toEqual([sortConfigs.name, sortConfigs.date]);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('setAll', () => {
+ it('should replace all active sorts', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['name']);
+
+ sort.setAll(['date', 'priority']);
+
+ expect(sort.active()).toEqual([sortConfigs.date, sortConfigs.priority]);
+
+ dispose();
+ });
+ });
+
+ it('should clear sorts when given empty array', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['name', 'date']);
+
+ sort.setAll([]);
+
+ expect(sort.active()).toEqual([]);
+
+ dispose();
+ });
+ });
+
+ it('should filter out invalid ids', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs);
+
+ // @ts-expect-error - testing invalid id
+ sort.setAll(['name', 'invalid', 'date']);
+
+ expect(sort.active()).toEqual([sortConfigs.name, sortConfigs.date]);
+
+ dispose();
+ });
+ });
+
+ it('should preserve order of ids', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs);
+
+ sort.setAll(['priority', 'name', 'date']);
+
+ expect(sort.active().map((s) => s.id)).toEqual([
+ 'priority',
+ 'name',
+ 'date',
+ ]);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('clear', () => {
+ it('should remove all active sorts', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['name', 'date', 'priority']);
+
+ sort.clear();
+
+ expect(sort.active()).toEqual([]);
+
+ dispose();
+ });
+ });
+
+ it('should be a no-op when already empty', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs);
+
+ sort.clear();
+
+ expect(sort.active()).toEqual([]);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('sort function integration', () => {
+ it('should provide working sort functions', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['name']);
+
+ const items: Item[] = [
+ { name: 'Charlie', date: 3, priority: 1 },
+ { name: 'Alice', date: 1, priority: 3 },
+ { name: 'Bob', date: 2, priority: 2 },
+ ];
+
+ const sortFn = sort.active()[0].fn;
+ const sorted = [...items].sort(sortFn);
+
+ expect(sorted.map((i) => i.name)).toEqual(['Alice', 'Bob', 'Charlie']);
+
+ dispose();
+ });
+ });
+
+ it('should support descending sort via desc flag', () => {
+ createRoot((dispose) => {
+ const sort = createSortState(sortConfigs, ['date']);
+
+ expect(sort.active()[0].desc).toBe(true);
+
+ dispose();
+ });
+ });
+ });
+});
diff --git a/js/app/packages/app/component/next-soup/create-sort-state.ts b/js/app/packages/app/component/next-soup/create-sort-state.ts
new file mode 100644
index 0000000000..4db5983459
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/create-sort-state.ts
@@ -0,0 +1,83 @@
+import { type Accessor, createSignal } from 'solid-js';
+
+export type SortConfig<T> = {
+ id: string;
+ fn: (a: T, b: T) => number;
+ desc?: boolean;
+};
+
+/** Sort state return type with strongly typed IDs */
+export type SortState<T, TId extends string = string> = {
+ /** Currently active sort configs (ordered by priority) */
+ active: Accessor<SortConfig<T>[]>;
+ isActive: (id: TId) => boolean;
+ /** Toggle a sort on/off */
+ toggle: (id: TId, value?: boolean) => void;
+ /** Set multiple sorts by IDs (in priority order) */
+ setAll: (ids: TId[]) => void;
+ clear: () => void;
+ /** Available sort configs */
+ available: Record<TId, SortConfig<T>>;
+};
+
+export const createSortState = <
+ T,
+ TConfigs extends Record<string, SortConfig<T>>,
+>(
+ configs: TConfigs,
+ initialSortIds?: (keyof TConfigs & string)[]
+): SortState<T, keyof TConfigs & string> => {
+ type TId = keyof TConfigs & string;
+
+ const initialSorts = (initialSortIds ?? [])
+ .map((id) => configs[id])
+ .filter((c) => c !== undefined);
+
+ const [activeSorts, setActiveSorts] =
+ createSignal<SortConfig<T>[]>(initialSorts);
+
+ const isActive = (id: TId): boolean =>
+ activeSorts().some((s) => s.id === configs[id]?.id);
+
+ const add = (id: TId) => {
+ const config = configs[id];
+ if (!config || isActive(id)) return;
+ setActiveSorts((prev) => [...prev, config]);
+ };
+
+ const remove = (id: TId) => {
+ const config = configs[id];
+ if (!config || !isActive(id)) return;
+ setActiveSorts((prev) => prev.filter((s) => s.id !== config.id));
+ };
+
+ const toggle = (id: TId, value?: boolean) => {
+ if (value === true) {
+ add(id);
+ } else if (value === false) {
+ remove(id);
+ } else if (isActive(id)) {
+ remove(id);
+ } else {
+ add(id);
+ }
+ };
+
+ const setAll = (ids: TId[]) => {
+ const newSorts = ids
+ .map((id) => configs[id])
+ .filter((c) => c !== undefined);
+ setActiveSorts(newSorts);
+ };
+
+ const clear = () => setActiveSorts([]);
+
+ return {
+ active: activeSorts,
+ isActive,
+ toggle,
+ setAll,
+ clear,
+ available: configs as Record<TId, SortConfig<T>>,
+ };
+};
diff --git a/js/app/packages/app/component/next-soup/create-soup-state.test.ts b/js/app/packages/app/component/next-soup/create-soup-state.test.ts
new file mode 100644
index 0000000000..b18aa9c052
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/create-soup-state.test.ts
@@ -0,0 +1,449 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+
+// Mock external dependencies
+vi.mock('@app/component/next-soup/filters/filters', () => ({
+ SOUP_FILTERS: {},
+ FILTER_GROUPS: [],
+}));
+
+vi.mock('@app/component/next-soup/filters', () => ({
+ createFilterState: vi.fn(() => ({
+ active: () => [],
+ isActive: () => false,
+ toggle: vi.fn(),
+ setAll: vi.fn(),
+ clear: vi.fn(),
+ available: {},
+ })),
+}));
+
+vi.mock('@app/component/next-soup/soup-view/sort-options', () => ({
+ SORT_CONFIGS: {
+ updated_at: {
+ id: 'updated_at',
+ fn: (a: { updatedAt?: number }, b: { updatedAt?: number }) =>
+ (b.updatedAt ?? 0) - (a.updatedAt ?? 0),
+ },
+ },
+}));
+
+vi.mock('@core/mobile/inputModality', () => ({
+ isModality: vi.fn(() => false),
+}));
+
+vi.mock('@core/component/EntityIcon', () => ({
+ getIconConfig: vi.fn(),
+}));
+
+import { createSoupState } from './create-soup-state';
+import type { EntityData } from '@macro-entity';
+
+const createTestEntity = (id: string, name?: string): EntityData => ({
+ id,
+ type: 'document',
+ name: name ?? `Entity ${id}`,
+ ownerId: 'test-owner',
+ updatedAt: Date.now(),
+});
+
+describe('createSoupState', () => {
+ describe('initial state', () => {
+ it('should start with empty data', () => {
+ createRoot((dispose) => {
+ const state = createSoupState();
+
+ expect(state.data()).toEqual([]);
+ expect(state.items.count()).toBe(0);
+
+ dispose();
+ });
+ });
+
+ it('should accept initial data', () => {
+ createRoot((dispose) => {
+ const entities = [createTestEntity('1'), createTestEntity('2')];
+ const state = createSoupState({ initialData: entities });
+
+ expect(state.data()).toEqual(entities);
+ expect(state.items.count()).toBe(2);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('setData', () => {
+ it('should update data', () => {
+ createRoot((dispose) => {
+ const state = createSoupState();
+ const entities = [createTestEntity('1'), createTestEntity('2')];
+
+ state.setData(entities);
+
+ expect(state.data()).toEqual(entities);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('items', () => {
+ it('should get item by id', () => {
+ createRoot((dispose) => {
+ const entity1 = createTestEntity('1');
+ const entity2 = createTestEntity('2');
+ const state = createSoupState({ initialData: [entity1, entity2] });
+
+ expect(state.items.get('1')).toBe(entity1);
+ expect(state.items.get('2')).toBe(entity2);
+ expect(state.items.get('nonexistent')).toBeUndefined();
+
+ dispose();
+ });
+ });
+
+ it('should get item at index', () => {
+ createRoot((dispose) => {
+ const entity1 = createTestEntity('1');
+ const entity2 = createTestEntity('2');
+ const state = createSoupState({ initialData: [entity1, entity2] });
+
+ expect(state.items.at(0)).toBe(entity1);
+ expect(state.items.at(1)).toBe(entity2);
+ expect(state.items.at(99)).toBeUndefined();
+
+ dispose();
+ });
+ });
+
+ it('should get index of item by id', () => {
+ createRoot((dispose) => {
+ const state = createSoupState({
+ initialData: [createTestEntity('1'), createTestEntity('2')],
+ });
+
+ expect(state.items.indexOf('1')).toBe(0);
+ expect(state.items.indexOf('2')).toBe(1);
+ expect(state.items.indexOf('nonexistent')).toBe(-1);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('focus', () => {
+ it('should start with no focus', () => {
+ createRoot((dispose) => {
+ const state = createSoupState({
+ initialData: [createTestEntity('1')],
+ });
+
+ expect(state.focus.id()).toBeUndefined();
+ expect(state.focus.item()).toBeUndefined();
+ expect(state.focus.index()).toBe(-1);
+
+ dispose();
+ });
+ });
+
+ it('should set focus by id', () => {
+ createRoot((dispose) => {
+ const entity = createTestEntity('1');
+ const state = createSoupState({ initialData: [entity] });
+
+ state.focus.set('1');
+
+ expect(state.focus.id()).toBe('1');
+ expect(state.focus.item()).toBe(entity);
+ expect(state.focus.index()).toBe(0);
+
+ dispose();
+ });
+ });
+
+ it('should clear focus', () => {
+ createRoot((dispose) => {
+ const state = createSoupState({
+ initialData: [createTestEntity('1')],
+ });
+
+ state.focus.set('1');
+ state.focus.clear();
+
+ expect(state.focus.id()).toBeUndefined();
+ expect(state.focus.item()).toBeUndefined();
+
+ dispose();
+ });
+ });
+ });
+
+ describe('navigate', () => {
+ it('should navigate down', () => {
+ createRoot((dispose) => {
+ const entities = [
+ createTestEntity('1'),
+ createTestEntity('2'),
+ createTestEntity('3'),
+ ];
+ const state = createSoupState({ initialData: entities });
+
+ const result1 = state.navigate.down();
+ expect(result1?.item).toBe(entities[0]);
+ expect(result1?.index).toBe(0);
+
+ const result2 = state.navigate.down();
+ expect(result2?.item).toBe(entities[1]);
+ expect(result2?.index).toBe(1);
+
+ dispose();
+ });
+ });
+
+ it('should navigate up', () => {
+ createRoot((dispose) => {
+ const entities = [
+ createTestEntity('1'),
+ createTestEntity('2'),
+ createTestEntity('3'),
+ ];
+ const state = createSoupState({ initialData: entities });
+
+ // When no focus, up goes to last
+ const result1 = state.navigate.up();
+ expect(result1?.item).toBe(entities[2]);
+ expect(result1?.index).toBe(2);
+
+ const result2 = state.navigate.up();
+ expect(result2?.item).toBe(entities[1]);
+ expect(result2?.index).toBe(1);
+
+ dispose();
+ });
+ });
+
+ it('should navigate to first', () => {
+ createRoot((dispose) => {
+ const entities = [createTestEntity('1'), createTestEntity('2')];
+ const state = createSoupState({ initialData: entities });
+
+ state.focus.set('2');
+ const result = state.navigate.toFirst();
+
+ expect(result?.item).toBe(entities[0]);
+ expect(state.focus.id()).toBe('1');
+
+ dispose();
+ });
+ });
+
+ it('should navigate to last', () => {
+ createRoot((dispose) => {
+ const entities = [createTestEntity('1'), createTestEntity('2')];
+ const state = createSoupState({ initialData: entities });
+
+ state.focus.set('1');
+ const result = state.navigate.toLast();
+
+ expect(result?.item).toBe(entities[1]);
+ expect(state.focus.id()).toBe('2');
+
+ dispose();
+ });
+ });
+
+ it('should navigate to specific index', () => {
+ createRoot((dispose) => {
+ const entities = [
+ createTestEntity('1'),
+ createTestEntity('2'),
+ createTestEntity('3'),
+ ];
+ const state = createSoupState({ initialData: entities });
+
+ const result = state.navigate.toIndex(1);
+
+ expect(result?.item).toBe(entities[1]);
+ expect(state.focus.id()).toBe('2');
+
+ dispose();
+ });
+ });
+
+ it('should navigate to specific id', () => {
+ createRoot((dispose) => {
+ const entities = [createTestEntity('1'), createTestEntity('2')];
+ const state = createSoupState({ initialData: entities });
+
+ const result = state.navigate.toId('2');
+
+ expect(result?.item).toBe(entities[1]);
+ expect(state.focus.id()).toBe('2');
+
+ dispose();
+ });
+ });
+
+ it('should return undefined for invalid id', () => {
+ createRoot((dispose) => {
+ const state = createSoupState({
+ initialData: [createTestEntity('1')],
+ });
+
+ const result = state.navigate.toId('nonexistent');
+
+ expect(result).toBeUndefined();
+
+ dispose();
+ });
+ });
+
+ it('should clamp to bounds without wrapping', () => {
+ createRoot((dispose) => {
+ const entities = [createTestEntity('1'), createTestEntity('2')];
+ const state = createSoupState({
+ initialData: entities,
+ wrapNavigation: false,
+ });
+
+ // Navigate past end
+ state.navigate.toIndex(99);
+ expect(state.focus.id()).toBe('2');
+
+ // Navigate before start
+ state.navigate.toIndex(-99);
+ expect(state.focus.id()).toBe('1');
+
+ dispose();
+ });
+ });
+
+ it('should wrap around with wrapNavigation enabled', () => {
+ createRoot((dispose) => {
+ const entities = [createTestEntity('1'), createTestEntity('2')];
+ const state = createSoupState({
+ initialData: entities,
+ wrapNavigation: true,
+ });
+
+ // Start at last item
+ state.navigate.toLast();
+ expect(state.focus.id()).toBe('2');
+
+ // Navigate down should wrap to first
+ state.navigate.down();
+ expect(state.focus.id()).toBe('1');
+
+ // Navigate up should wrap to last
+ state.navigate.up();
+ expect(state.focus.id()).toBe('2');
+
+ dispose();
+ });
+ });
+
+ it('should peek offset without changing focus', () => {
+ createRoot((dispose) => {
+ const entities = [
+ createTestEntity('1'),
+ createTestEntity('2'),
+ createTestEntity('3'),
+ ];
+ const state = createSoupState({ initialData: entities });
+
+ state.navigate.toIndex(1);
+ expect(state.focus.id()).toBe('2');
+
+ const peeked = state.navigate.peekOffset(1);
+ expect(peeked?.item).toBe(entities[2]);
+
+ // Focus should remain unchanged
+ expect(state.focus.id()).toBe('2');
+
+ dispose();
+ });
+ });
+
+ it('should return undefined when navigating empty data', () => {
+ createRoot((dispose) => {
+ const state = createSoupState({ initialData: [] });
+
+ expect(state.navigate.down()).toBeUndefined();
+ expect(state.navigate.up()).toBeUndefined();
+ expect(state.navigate.toFirst()).toBeUndefined();
+
+ dispose();
+ });
+ });
+ });
+
+ describe('previewEntity', () => {
+ it('should manage preview entity state', () => {
+ createRoot((dispose) => {
+ const state = createSoupState();
+
+ expect(state.previewEntity()).toBeUndefined();
+
+ state.setPreviewEntity('entity-1');
+ expect(state.previewEntity()).toBe('entity-1');
+
+ state.setPreviewEntity(undefined);
+ expect(state.previewEntity()).toBeUndefined();
+
+ dispose();
+ });
+ });
+ });
+
+ describe('selection', () => {
+ it('should expose selection state', () => {
+ createRoot((dispose) => {
+ const entity = createTestEntity('1');
+ const state = createSoupState({ initialData: [entity] });
+
+ expect(state.selection.count()).toBe(0);
+
+ state.selection.select(entity);
+ expect(state.selection.count()).toBe(1);
+ expect(state.selection.isSelected('1')).toBe(true);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('sort', () => {
+ it('should expose sort state', () => {
+ createRoot((dispose) => {
+ const state = createSoupState();
+
+ // Initial sort should be updated_at
+ expect(state.sort.active().length).toBe(1);
+ expect(state.sort.active()[0].id).toBe('updated_at');
+
+ dispose();
+ });
+ });
+ });
+
+ describe('groups', () => {
+ it('should manage group configs', () => {
+ createRoot((dispose) => {
+ const state = createSoupState();
+
+ expect(state.groups()).toEqual([]);
+
+ const groupConfig = {
+ id: 'type',
+ getValue: (_item: unknown) => 'test',
+ };
+ state.setGroups([groupConfig]);
+
+ expect(state.groups()).toEqual([groupConfig]);
+
+ dispose();
+ });
+ });
+ });
+});
diff --git a/js/app/packages/app/component/next-soup/create-soup-state.ts b/js/app/packages/app/component/next-soup/create-soup-state.ts
new file mode 100644
index 0000000000..4435780b73
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/create-soup-state.ts
@@ -0,0 +1,195 @@
+import { createSortState } from '@app/component/next-soup/create-sort-state';
+import {
+ createFilterState,
+ type FilterConfig,
+} from '@app/component/next-soup/filters';
+import {
+ FILTER_GROUPS,
+ type FilterGroup,
+ SOUP_FILTERS,
+} from '@app/component/next-soup/filters/filters';
+import { createSelectionState } from '@app/component/next-soup/selection-state';
+import { SORT_CONFIGS } from '@app/component/next-soup/soup-view/sort-options';
+import { isModality } from '@core/mobile/inputModality';
+import type { EntityData, WithSearch } from '@macro-entity';
+import { createMemo, createSignal } from 'solid-js';
+
+type SoupEntity = EntityData | WithSearch<EntityData>;
+
+export type NavigationResult<T> = { item: T; index: number } | undefined;
+
+export type GroupConfig<T> = {
+ id: string;
+ getValue: (item: T) => unknown;
+};
+
+export type SortConfig<T> = {
+ id: string;
+ fn: (a: T, b: T) => number;
+ desc?: boolean;
+};
+
+interface SoupContextOptions<
+ TFilter extends Readonly<FilterConfig<SoupEntity>>,
+> {
+ initialData?: SoupEntity[];
+ initialFilters?: TFilter['id'][];
+ filterConfigs?: TFilter[];
+ filterGroups?: FilterGroup[];
+ wrapNavigation?: boolean;
+}
+
+export const createSoupState = <
+ TFilter extends Readonly<FilterConfig<SoupEntity>>,
+>(
+ {
+ wrapNavigation,
+ initialData,
+ initialFilters,
+ filterConfigs,
+ filterGroups,
+ }: SoupContextOptions<TFilter> = {
+ wrapNavigation: false,
+ }
+) => {
+ const selection = createSelectionState<SoupEntity>({
+ getItemId: (i) => i.id,
+ });
+
+ const filters = createFilterState<SoupEntity, FilterConfig<SoupEntity>>({
+ filters: filterConfigs ?? SOUP_FILTERS,
+ groups: filterGroups ?? FILTER_GROUPS,
+ initialFilters,
+ });
+
+ const sort = createSortState(SORT_CONFIGS, ['updated_at']);
+
+ const [groups, setGroups] = createSignal<GroupConfig<SoupEntity>[]>([]);
+
+ const [data, setDataInternal] = createSignal<SoupEntity[]>(initialData ?? []);
+
+ const setData = (newData: SoupEntity[]) => {
+ setDataInternal(newData);
+ };
+
+ const [previewEntity, setPreviewEntity] = createSignal<string | undefined>();
+
+ const [collapseEntityCallback, setCollapseEntityCallback] = createSignal<
+ ((entityId: string) => Promise<void>) | undefined
+ >(undefined);
+
+ const [focusedId, setFocusedId] = createSignal<string | undefined>();
+
+ const indexOf = (id: string): number => data().findIndex((r) => r.id === id);
+
+ const focusedIndex = createMemo(() => {
+ const id = focusedId();
+ if (!id) return -1;
+ return indexOf(id);
+ });
+
+ const focused = createMemo(() => {
+ const index = focusedIndex();
+ if (index === -1) return undefined;
+ return data()[index];
+ });
+
+ const getItem = (id: string): SoupEntity | undefined =>
+ data().find((e) => e.id === id);
+
+ const getItemAt = (index: number): SoupEntity | undefined => data()[index];
+
+ // Navigation implementation
+ const setFocus = (index: number): NavigationResult<SoupEntity> => {
+ const visibleRows = data();
+ if (visibleRows.length === 0) return undefined;
+
+ let targetIndex = index;
+ if (targetIndex < 0) {
+ targetIndex = wrapNavigation ? visibleRows.length - 1 : 0;
+ } else if (targetIndex >= visibleRows.length) {
+ targetIndex = wrapNavigation ? 0 : visibleRows.length - 1;
+ }
+
+ const row = visibleRows[targetIndex];
+ if (!row) return undefined;
+
+ setFocusedId(row.id);
+ return { item: row, index: targetIndex };
+ };
+
+ const navigateBy = (offset: number): NavigationResult<SoupEntity> => {
+ const current = focusedIndex();
+ if (current === -1) {
+ return setFocus(offset > 0 ? 0 : data().length - 1);
+ }
+ return setFocus(current + offset);
+ };
+
+ const clearFocus = () => {
+ setFocusedId(undefined);
+ };
+
+ return {
+ data,
+ setData,
+ filters,
+ selection,
+ sort,
+ groups,
+ setGroups,
+
+ focus: {
+ item: focused,
+ id: focusedId,
+ index: focusedIndex,
+ clear: clearFocus,
+ set: (id: string | undefined) => setFocusedId(id),
+ },
+
+ navigate: {
+ down: () => navigateBy(1),
+ up: () => navigateBy(-1),
+ by: navigateBy,
+ toIndex: setFocus,
+ toId: (id: string) => {
+ const index = indexOf(id);
+ if (index === -1) return undefined;
+ return setFocus(index);
+ },
+ toFirst: () => setFocus(0),
+ toLast: () => setFocus(data().length - 1),
+ peekOffset: (offset: number) => {
+ const current = focusedIndex();
+ const next = navigateBy(offset);
+ setFocus(current);
+ return next;
+ },
+ },
+
+ items: {
+ data,
+ count: () => data().length,
+ get: getItem,
+ at: getItemAt,
+ indexOf,
+ },
+
+ previewEntity,
+ setPreviewEntity,
+
+ collapseEntity: {
+ callback: collapseEntityCallback,
+ set: setCollapseEntityCallback,
+ shouldCollapse: () => {
+ return (
+ filters.isActive('not-done') &&
+ collapseEntityCallback() !== undefined &&
+ isModality('touch')
+ );
+ },
+ },
+ };
+};
+
+export type SoupState = ReturnType<typeof createSoupState>;
diff --git a/js/app/packages/app/component/next-soup/filters/create-filter-state.ts b/js/app/packages/app/component/next-soup/filters/create-filter-state.ts
new file mode 100644
index 0000000000..8cec885e21
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/filters/create-filter-state.ts
@@ -0,0 +1,186 @@
+import { createMemo, createSignal, type Accessor } from 'solid-js';
+
+export type FilterPredicate<T> = (entity: T, ...args: any[]) => boolean;
+
+export type FilterConfig<T> = {
+ readonly id: string;
+ readonly predicate: FilterPredicate<T>;
+ readonly group?: string;
+};
+
+export type FilterGroupConfig = {
+ readonly id: string;
+ readonly allowMultiple?: boolean;
+};
+
+export type CreateFilterStateOptions<T, TFilter extends FilterConfig<T>> = {
+ /** All available filter configurations */
+ readonly filters: readonly TFilter[];
+ /** Filter group configurations */
+ readonly groups?: readonly FilterGroupConfig[];
+ /** Initial active filter IDs */
+ readonly initialFilters?: readonly string[];
+ /** Callback when filters change */
+ readonly onChange?: (filters: TFilter[]) => void;
+};
+
+/** Filter state return type */
+export type FilterState<T, TFilter extends FilterConfig<T>> = {
+ /** Currently active filter configs */
+ readonly active: Accessor<TFilter[]>;
+ /** IDs of currently active filters */
+ readonly activeIds: Accessor<string[]>;
+ /** Check if a filter is active by ID */
+ readonly isActive: (id: string) => boolean;
+ /** Toggle a filter on/off */
+ readonly toggle: (id: string) => void;
+ /** Set a filter as active (respecting group exclusivity) */
+ readonly activate: (id: string) => void;
+ /** Remove a filter from active filters */
+ readonly deactivate: (id: string) => void;
+ /** Clear all active filters */
+ readonly clear: () => void;
+ /** Set filters directly */
+ readonly set: (filters: TFilter[]) => void;
+ /** Get a filter config by ID */
+ readonly getFilter: (id: string) => TFilter | undefined;
+ /** All available filter configs */
+ readonly available: readonly TFilter[];
+};
+
+/**
+ * Creates reactive filter state.
+ *
+ * Handles filter toggling with group-based mutual exclusivity:
+ * - Filters without a group can be combined freely
+ * - Filters with a group replace other filters in the same group
+ *
+ * @example
+ * ```ts
+ * const filters = createFilterState({
+ * filters: SOUP_FILTERS,
+ * initialFilters: ['signal'],
+ * onChange: (filters) => console.log('Filters changed:', filters),
+ * });
+ *
+ * // Toggle a filter
+ * filters.toggle('email');
+ *
+ * // Check active state
+ * const isEmailActive = filters.isActive('email');
+ *
+ * // Get active filter configs for predicates
+ * const activeFilters = filters.active();
+ * ```
+ */
+export function createFilterState<T, TFilter extends FilterConfig<T>>(
+ options: CreateFilterStateOptions<T, TFilter>
+): FilterState<T, TFilter> {
+ const {
+ filters: availableFilters,
+ groups = [],
+ initialFilters = [],
+ onChange,
+ } = options;
+
+ const filterMap = new Map<string, TFilter>(
+ availableFilters.map((f) => [f.id, f])
+ );
+ const groupMap = new Map<string, FilterGroupConfig>(
+ groups.map((g) => [g.id, g])
+ );
+
+ // Initialize with initial filters
+ const initialActiveFilters = initialFilters
+ .map((id) => filterMap.get(id))
+ .filter((f): f is TFilter => f !== undefined);
+
+ const [activeFilters, setActiveFilters] =
+ createSignal<TFilter[]>(initialActiveFilters);
+
+ // Computed: active filter IDs
+ const activeIds = createMemo(() => activeFilters().map((f) => f.id));
+
+ // Helper: get filter by ID
+ const getFilter = (id: string): TFilter | undefined => filterMap.get(id);
+
+ // Helper: check if filter is active
+ const isActive = (id: string): boolean => activeIds().includes(id);
+
+ // Helper: update filters with onChange callback
+ const updateFilters = (next: TFilter[]) => {
+ setActiveFilters(next);
+ onChange?.(next);
+ };
+
+ // Activate a filter (respecting group exclusivity based on allowMultiple)
+ const activate = (id: string) => {
+ const config = getFilter(id);
+ if (!config) {
+ console.warn(`Filter not found: ${id}`);
+ return;
+ }
+
+ // Already active, nothing to do
+ if (isActive(id)) return;
+
+ const current = activeFilters();
+
+ if (config.group) {
+ const groupConfig = groupMap.get(config.group);
+ const allowMultiple = groupConfig?.allowMultiple ?? false;
+
+ if (allowMultiple) {
+ // Allow multiple selections in this group
+ updateFilters([...current, config]);
+ } else {
+ // Mutual exclusivity: remove other filters in same group
+ const withoutSameGroup = current.filter(
+ (f) => f.group !== config.group
+ );
+ updateFilters([...withoutSameGroup, config]);
+ }
+ } else {
+ // No group, just add
+ updateFilters([...current, config]);
+ }
+ };
+
+ // Deactivate a filter
+ const deactivate = (id: string) => {
+ if (!isActive(id)) return;
+ updateFilters(activeFilters().filter((f) => f.id !== id));
+ };
+
+ // Toggle a filter on/off
+ const toggle = (id: string) => {
+ if (isActive(id)) {
+ deactivate(id);
+ } else {
+ activate(id);
+ }
+ };
+
+ // Clear all filters
+ const clear = () => {
+ updateFilters([]);
+ };
+
+ // Set filters directly
+ const set = (filters: TFilter[]) => {
+ updateFilters(filters);
+ };
+
+ return {
+ active: activeFilters,
+ activeIds,
+ isActive,
+ toggle,
+ activate,
+ deactivate,
+ clear,
+ set,
+ getFilter,
+ available: availableFilters,
+ };
+}
diff --git a/js/app/packages/app/component/next-soup/filters/filters.ts b/js/app/packages/app/component/next-soup/filters/filters.ts
new file mode 100644
index 0000000000..737ba634ae
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/filters/filters.ts
@@ -0,0 +1,354 @@
+import {
+ isTaskEntity,
+ type EntityData,
+ type WithNotification,
+} from '@macro-entity';
+import {
+ signalFilter,
+ noiseFilter,
+ explicitNoiseFilter,
+} from './signal-filters';
+import {
+ type EntityWithValidIcon,
+ getIconConfig,
+} from '@core/component/EntityIcon';
+import type {
+ SoupItemsQueryArgs,
+ SoupItemsQueryFilters,
+} from '@queries/soup/items';
+import { codeFileExtensions } from '@block-code/util/languageSupport';
+
+/**
+ * Unread filter - entity has unread content.
+ *
+ * Entity-specific logic:
+ * - Emails: Uses `isRead` boolean field
+ * - Everything else: Has at least one notification with viewedAt === null
+ */
+export function unreadFilter(entity: EnhancedEntity): boolean {
+ if (entity.type === 'email') {
+ return !entity.isRead;
+ }
+ return entity.notifications?.()?.some((n) => !n.viewedAt) ?? false;
+}
+
+/**
+ * NotDone filter - entity has outstanding items.
+ *
+ * Entity-specific logic:
+ * - Emails: Uses `done` field (derived from !inboxVisible - email is "not done" when in inbox)
+ * - Everything else: Has at least one notification with done === false
+ */
+export function notDoneFilter(entity: WithNotification<EntityData>) {
+ if (entity.type === 'email') return !entity.done;
+ // Tasks are handled by signalFilter based on assignee/status, not notifications
+ if (isTaskEntity(entity)) return true;
+
+ return (
+ !!entity.notifications && entity.notifications().some(({ done }) => !done)
+ );
+}
+
+/** Filter predicate function */
+export type FilterPredicate<T> = (entity: T) => boolean;
+
+/** Filter configuration */
+export type FilterConfig<T> = {
+ readonly id: string;
+ readonly label: string;
+ readonly predicate: FilterPredicate<T>;
+ readonly group?: string;
+};
+
+/** Filter group configuration */
+export type FilterGroup = {
+ readonly id: string;
+ readonly allowMultiple?: boolean;
+};
+
+/** Filter group configurations */
+export const FILTER_GROUPS: readonly FilterGroup[] = [
+ { id: 'focus', allowMultiple: false },
+ { id: 'type', allowMultiple: false },
+];
+
+type EnhancedEntity = WithNotification<EntityData>;
+
+/** Document filter (markdown, canvas) - excludes tasks */
+export function documentFilter(entity: EntityData): boolean {
+ if (entity.type !== 'document') return false;
+ if (entity.subType?.type === 'task') return false;
+ const fileType = entity.fileType ?? '';
+ return fileType === 'md' || fileType === 'canvas';
+}
+
+/** Task filter */
+export function taskFilter(entity: EntityData): boolean {
+ return entity.type === 'document' && entity.subType?.type === 'task';
+}
+
+/** Email filter */
+export function emailFilter(entity: EntityData): boolean {
+ return entity.type === 'email';
+}
+
+/** People filter (direct messages) */
+export function peopleFilter(entity: EntityData): boolean {
+ return entity.type === 'channel' && entity.channelType === 'direct_message';
+}
+
+/** Teams filter (group channels) */
+export function teamsFilter(entity: EntityData): boolean {
+ return entity.type === 'channel' && entity.channelType !== 'direct_message';
+}
+
+/** Chat/agent filter */
+export function agentFilter(entity: EntityData): boolean {
+ return entity.type === 'chat';
+}
+
+/** Project/folder filter */
+export function projectFilter(entity: EntityData): boolean {
+ return entity.type === 'project';
+}
+
+/** File filter (non-markdown documents) */
+export function fileFilter(entity: EntityData): boolean {
+ if (entity.type !== 'document') return false;
+ const fileType = entity.fileType ?? '';
+ return !['md', 'canvas'].includes(fileType);
+}
+
+export function teamsAndPeopleFilter(entity: EntityData): boolean {
+ if (entity.type !== 'channel') return false;
+
+ return true;
+}
+
+export const SOUP_FILTERS = [
+ // Focus filters (mutually exclusive)
+ {
+ id: 'signal',
+ label: 'Inbox',
+ predicate: signalFilter,
+ group: 'focus',
+ },
+ {
+ id: 'noise',
+ label: 'Other',
+ predicate: noiseFilter,
+ group: 'focus',
+ },
+ {
+ id: 'explicit-noise',
+ label: 'Explicit Noise',
+ predicate: (entity: EntityData) => !explicitNoiseFilter(entity),
+ group: 'focus',
+ },
+
+ // Notification filters
+ {
+ id: 'unread',
+ label: 'Unread',
+ predicate: unreadFilter,
+ },
+ {
+ id: 'not-done',
+ label: 'Not done',
+ predicate: notDoneFilter,
+ },
+
+ // Entity type filters (mutually exclusive)
+ {
+ id: 'document',
+ label: 'Docs',
+ predicate: documentFilter,
+ group: 'type',
+ },
+ {
+ id: 'agent',
+ label: 'Agents',
+ predicate: agentFilter,
+ group: 'type',
+ },
+ {
+ id: 'people',
+ label: 'People',
+ predicate: peopleFilter,
+ group: 'type',
+ },
+ {
+ id: 'teams',
+ label: 'Teams',
+ predicate: teamsFilter,
+ group: 'type',
+ },
+ {
+ id: 'task',
+ label: 'Tasks',
+ predicate: taskFilter,
+ group: 'type',
+ },
+ {
+ id: 'email',
+ label: 'Mail',
+ predicate: emailFilter,
+ group: 'type',
+ },
+ {
+ id: 'file',
+ label: 'Files',
+ predicate: fileFilter,
+ group: 'type',
+ },
+ {
+ id: 'teams-and-people',
+ label: 'Groups',
+ predicate: teamsAndPeopleFilter,
+ group: 'type',
+ },
+] as const;
+
+export type FilterID = (typeof SOUP_FILTERS)[number]['id'];
+
+const ENTITY_TYPE_FILTERS = [
+ 'document',
+ 'task',
+ 'email',
+ 'people',
+ 'teams',
+ 'agent',
+ 'file',
+] as const;
+
+type EntityTypeFilters = (typeof ENTITY_TYPE_FILTERS)[number];
+
+export const isEntityTypeFilter = (
+ filter: FilterConfig<EntityData>
+): filter is Extract<
+ (typeof SOUP_FILTERS)[number],
+ { readonly id: EntityTypeFilters }
+> => {
+ return ENTITY_TYPE_FILTERS.includes(filter.id as EntityTypeFilters);
+};
+
+export const ENTITY_TYPE_FILTER_CONFIGS = SOUP_FILTERS.filter((f) =>
+ isEntityTypeFilter(f)
+);
+
+const ENTITY_TYPE_TO_ICON_TYPE: Record<EntityTypeFilters, EntityWithValidIcon> =
+ {
+ document: 'md',
+ email: 'email',
+ task: 'task',
+ people: 'channel',
+ teams: 'direct_message',
+ agent: 'chat',
+ file: 'project',
+ };
+
+export const getEntityTypeFilterIcon = (filter: EntityTypeFilters) => {
+ return getIconConfig(ENTITY_TYPE_TO_ICON_TYPE[filter]);
+};
+
+export const getFilterWithID = (filterID: FilterID) => {
+ const found = SOUP_FILTERS.find((f) => f.id === filterID);
+
+ if (!found) return;
+
+ return found;
+};
+
+export const FOLDER_DOCUMENT_TYPES = [
+ 'code',
+ 'image',
+ 'pdf',
+ 'unknown',
+] as const;
+
+export const getFolderFileTypes = (type: 'soup' | 'search') => {
+ return FOLDER_DOCUMENT_TYPES.flatMap((fileType) => {
+ if (fileType === 'code')
+ return type === 'soup' ? ['assoc:code'] : codeFileExtensions;
+ if (fileType === 'image')
+ return type === 'soup' ? ['assoc:image'] : [NIL_UUID];
+ if (fileType === 'unknown')
+ return type === 'soup' ? ['assoc:other'] : [NIL_UUID];
+ return [fileType];
+ });
+};
+
+const NIL_UUID = '00000000-0000-0000-0000-000000000000';
+
+const buildDefaultValue = (entityTypes: string[], required: string[]) => {
+ const hasNoEntityTypes = entityTypes.length === 0;
+
+ const hasSomeRequiredType = required.some((t) => entityTypes.includes(t));
+
+ if (hasSomeRequiredType || hasNoEntityTypes) {
+ return [];
+ }
+
+ return [NIL_UUID];
+};
+
+export const buildDssFiltersRequest = (
+ filters: FilterConfig<EntityData>[],
+ context?: {
+ extra?: SoupItemsQueryFilters;
+ isSearchActive?: boolean;
+ emailActive?: boolean;
+ }
+): SoupItemsQueryArgs['body'] => {
+ const entityTypes = filters
+ .filter((f) => ENTITY_TYPE_FILTERS.includes(f.id as EntityTypeFilters))
+ .map((f) => f.id);
+
+ const {
+ channel_filters,
+ document_filters,
+ chat_filters,
+ email_filters,
+ project_filters,
+ } = context?.extra ?? {};
+
+ return {
+ channel_filters: {
+ ...channel_filters,
+ channel_ids:
+ channel_filters?.channel_ids ??
+ buildDefaultValue(entityTypes, ['teams', 'people']),
+ },
+ document_filters: {
+ ...document_filters,
+ document_ids:
+ document_filters?.document_ids ??
+ buildDefaultValue(entityTypes, ['file', 'document', 'task']),
+ project_ids: document_filters?.project_ids ?? [],
+ file_types: document_filters?.file_types ?? [],
+ },
+ chat_filters: {
+ ...chat_filters,
+ chat_ids:
+ chat_filters?.chat_ids ?? buildDefaultValue(entityTypes, ['agent']),
+ project_ids: chat_filters?.project_ids ?? [],
+ },
+ email_filters: {
+ ...email_filters,
+ recipients:
+ email_filters?.recipients ??
+ (context?.emailActive &&
+ !context.isSearchActive &&
+ (entityTypes.includes('email') || entityTypes.length === 0)
+ ? []
+ : [NIL_UUID]),
+ },
+ project_filters: {
+ ...project_filters,
+ project_ids:
+ project_filters?.project_ids ??
+ buildDefaultValue(entityTypes, ['file']),
+ },
+ emailView: 'all',
+ };
+};
diff --git a/js/app/packages/app/component/next-soup/filters/index.ts b/js/app/packages/app/component/next-soup/filters/index.ts
new file mode 100644
index 0000000000..c002766876
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/filters/index.ts
@@ -0,0 +1,24 @@
+export {
+ agentFilter,
+ documentFilter,
+ emailFilter,
+ fileFilter,
+ FILTER_GROUPS,
+ type FilterConfig,
+ type FilterGroup,
+ type FilterPredicate,
+ notDoneFilter,
+ peopleFilter,
+ projectFilter,
+ taskFilter,
+ teamsFilter,
+ unreadFilter,
+} from './filters';
+
+export {
+ noiseFilter,
+ signalFilter,
+ explicitNoiseFilter,
+} from './signal-filters';
+
+export { createFilterState } from './create-filter-state';
diff --git a/js/app/packages/app/component/next-soup/filters/signal-configs.ts b/js/app/packages/app/component/next-soup/filters/signal-configs.ts
new file mode 100644
index 0000000000..a7334c4f94
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/filters/signal-configs.ts
@@ -0,0 +1,81 @@
+import { makePersisted } from '@solid-primitives/storage';
+import { createSignal } from 'solid-js';
+
+type SignalConfig<T extends string> = {
+ key: T;
+ label: string;
+ defaultValue: boolean;
+};
+
+type SignalToggle<T extends string> = SignalConfig<T> & {
+ enabled: () => boolean;
+ setEnabled: (value: boolean) => void;
+};
+
+const makeToggle = (storageKey: string, defaultValue: boolean) =>
+ makePersisted(createSignal(defaultValue), { name: storageKey });
+
+const toStorageKey = (scope: string, key: string) =>
+ `signalFilter_${scope}_${key.toLowerCase().replace(/[^a-z0-9]+/g, '_')}`;
+
+const createSignalToggles = <T extends string>(
+ scope: string,
+ configs: SignalConfig<T>[]
+): SignalToggle<T>[] =>
+ configs.map((config) => {
+ const [enabled, setEnabled] = makeToggle(
+ toStorageKey(scope, config.key),
+ config.defaultValue
+ );
+ return { ...config, enabled, setEnabled };
+ });
+
+const PRIORITY_LABEL_SIGNAL_CONFIGS: SignalConfig<string>[] = [
+ {
+ key: 'CATEGORY_PERSONAL',
+ label: 'Personal',
+ defaultValue: true,
+ },
+ {
+ key: 'SENT',
+ label: 'Sent',
+ defaultValue: true,
+ },
+ {
+ key: 'IMPORTANT',
+ label: 'Important',
+ defaultValue: false,
+ },
+];
+
+const DEPRIORITY_LABEL_SIGNAL_CONFIGS: SignalConfig<string>[] = [
+ {
+ key: 'CATEGORY_UPDATES',
+ label: 'Updates',
+ defaultValue: true,
+ },
+ {
+ key: 'CATEGORY_PROMOTIONS',
+ label: 'Promotions',
+ defaultValue: true,
+ },
+ {
+ key: 'CATEGORY_SOCIAL',
+ label: 'Social',
+ defaultValue: true,
+ },
+ {
+ key: 'CATEGORY_FORUMS',
+ label: 'Forums',
+ defaultValue: true,
+ },
+];
+
+export const PRIORITY_LABEL_SIGNAL_TOGGLES = createSignalToggles(
+ 'priority_label',
+ PRIORITY_LABEL_SIGNAL_CONFIGS
+);
+export const DEPRIORITY_LABEL_SIGNAL_TOGGLES = createSignalToggles(
+ 'depriority_label',
+ DEPRIORITY_LABEL_SIGNAL_CONFIGS
+);
diff --git a/js/app/packages/app/component/next-soup/filters/signal-filters.ts b/js/app/packages/app/component/next-soup/filters/signal-filters.ts
new file mode 100644
index 0000000000..2320130b23
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/filters/signal-filters.ts
@@ -0,0 +1,183 @@
+import {
+ isTaskEntity,
+ type TaskEntityWithProperties,
+ type EntityData,
+} from '@macro-entity';
+import { useUserId } from '@core/context/user';
+import { createMemo } from 'solid-js';
+import {
+ DEPRIORITY_LABEL_SIGNAL_TOGGLES,
+ PRIORITY_LABEL_SIGNAL_TOGGLES,
+} from '@app/component/next-soup/filters/signal-configs';
+import {
+ isCurrentUserAssigned,
+ isTaskClosed,
+} from '@app/component/next-soup/utils';
+
+/** Labels that indicate priority emails (signal) */
+const PRIORITY_LABELS = createMemo(
+ () =>
+ new Set(
+ PRIORITY_LABEL_SIGNAL_TOGGLES.filter(({ enabled }) => enabled()).map(
+ ({ key }) => key
+ )
+ )
+);
+
+/** Labels that indicate depriority emails (noise) */
+const DEPRIORITY_LABELS = createMemo(
+ () =>
+ new Set(
+ DEPRIORITY_LABEL_SIGNAL_TOGGLES.filter(({ enabled }) => enabled()).map(
+ ({ key }) => key
+ )
+ )
+);
+
+// ============================================================================
+// Signal/Noise Configuration
+// ============================================================================
+
+/** Extract label tokens from email labels for matching */
+const getLabelTokens = (
+ labels?: Array<{ id?: string; providerLabelId?: string; name?: string }>
+): string[] => {
+ if (!labels?.length) return [];
+
+ const tokens: string[] = [];
+ for (const label of labels) {
+ if (label.id) tokens.push(label.id);
+ if (label.providerLabelId) tokens.push(label.providerLabelId);
+ if (label.name) tokens.push(label.name);
+ }
+
+ return tokens.map((token) => token.toUpperCase());
+};
+
+/** Check if entity was recently viewed (within last 24 hours) */
+const hasRecentlyViewed = (entity: EntityData): boolean => {
+ if (!entity.viewedAt) return false;
+
+ const now = Date.now();
+ const viewedAt = new Date(entity.viewedAt).getTime();
+ const oneDayMs = 24 * 60 * 60 * 1000;
+
+ return now - viewedAt < oneDayMs;
+};
+
+type EmailEntity = Extract<EntityData, { type: 'email' }>;
+
+/** Analyze email for priority/depriority indicators */
+function getEmailSignalInfo(entity: EmailEntity): {
+ hasPriority: boolean;
+ hasDepriority: boolean;
+} {
+ const labelTokens = getLabelTokens(entity.labels);
+ const priorityLabels = PRIORITY_LABELS();
+ const depriorityLabels = DEPRIORITY_LABELS();
+
+ const hasPriorityLabel = labelTokens.some((label) =>
+ priorityLabels.has(label)
+ );
+ const hasDeprioritizingLabel = labelTokens.some((label) =>
+ depriorityLabels.has(label)
+ );
+
+ return {
+ hasPriority: hasPriorityLabel,
+ hasDepriority: hasDeprioritizingLabel,
+ };
+}
+
+/** Check if email is signal (important) */
+function isSignalEmail(entity: EmailEntity): boolean {
+ const { hasPriority, hasDepriority } = getEmailSignalInfo(entity);
+ // Signal = has priority indicators OR no depriority indicators
+ return hasPriority || !hasDepriority;
+}
+
+/** Check if email is noise (less important) */
+function isNoiseEmail(entity: EmailEntity): boolean {
+ const { hasPriority, hasDepriority } = getEmailSignalInfo(entity);
+ // Noise = has depriority indicators AND no priority indicators
+ return hasDepriority && !hasPriority;
+}
+
+/**
+ * determines if a task should appear in the signal tab.
+ * tasks appear in signal if:
+ * - they are not completed or canceled
+ * - the current user is an assignee (or the task has no assignees)
+ */
+export const isSignalTask = (
+ entity: TaskEntityWithProperties,
+ currentUserId: string | undefined
+): boolean => {
+ if (isTaskClosed(entity)) {
+ return false;
+ }
+ return isCurrentUserAssigned(entity, currentUserId);
+};
+
+const getCurrentUserId = () => {
+ try {
+ return useUserId()();
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Signal filter - important/prioritized items.
+ *
+ * Classification:
+ * - Channels: Always signal (explicit membership)
+ * - Chats: Signal if recently viewed
+ * - Documents: Tasks always signal, others if recently viewed
+ * - Emails: Based on priority/depriority labels and metadata
+ * - Projects: Signal if recently viewed
+ */
+export function signalFilter(entity: EntityData): boolean {
+ switch (entity.type) {
+ case 'channel':
+ return true;
+ case 'chat':
+ return hasRecentlyViewed(entity);
+ case 'document': {
+ if (isTaskEntity(entity)) {
+ const currentUserId = getCurrentUserId();
+ return isSignalTask(entity as TaskEntityWithProperties, currentUserId);
+ }
+
+ return hasRecentlyViewed(entity);
+ }
+ case 'email':
+ return isSignalEmail(entity) || entity.isDraft;
+ case 'project':
+ return hasRecentlyViewed(entity);
+ }
+}
+
+/**
+ * Noise filter - less important items.
+ * Returns the opposite of signal filter.
+ */
+export function noiseFilter(entity: EntityData): boolean {
+ return !signalFilter(entity);
+}
+
+/**
+ * Explicit noise filter - only true for items with explicit noise indicators.
+ *
+ * Currently only emails can be "explicit noise" (those with depriority labels/metadata).
+ * Non-email items are never considered explicit noise (they're neutral).
+ *
+ * This is used when NO focus filter is selected to hide explicitly noisy items.
+ */
+export function explicitNoiseFilter(entity: EntityData): boolean {
+ if (entity.type === 'email') {
+ return isNoiseEmail(entity);
+ }
+ // Non-email items are never explicit noise
+ return false;
+}
diff --git a/js/app/packages/app/component/next-soup/selection-state.test.ts b/js/app/packages/app/component/next-soup/selection-state.test.ts
new file mode 100644
index 0000000000..2ec1759f93
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/selection-state.test.ts
@@ -0,0 +1,322 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import { createSelectionState } from './selection-state';
+
+type Item = { id: string; name: string };
+
+const getItemId = (item: Item) => item.id;
+
+const item1: Item = { id: '1', name: 'Item 1' };
+const item2: Item = { id: '2', name: 'Item 2' };
+const item3: Item = { id: '3', name: 'Item 3' };
+
+describe('createSelectionState', () => {
+ describe('initial state', () => {
+ it('should start with empty selection', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({ getItemId });
+
+ expect(selection.selected()).toEqual([]);
+ expect(selection.selectedIds()).toEqual(new Set());
+ expect(selection.count()).toBe(0);
+
+ dispose();
+ });
+ });
+
+ it('should accept initial items', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1, item2],
+ });
+
+ expect(selection.selected()).toEqual([item1, item2]);
+ expect(selection.selectedIds()).toEqual(new Set(['1', '2']));
+ expect(selection.count()).toBe(2);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('select', () => {
+ it('should add item to selection', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({ getItemId });
+
+ selection.select(item1);
+
+ expect(selection.selected()).toEqual([item1]);
+ expect(selection.isSelected('1')).toBe(true);
+ expect(selection.count()).toBe(1);
+
+ dispose();
+ });
+ });
+
+ it('should not duplicate already selected item', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({ getItemId });
+
+ selection.select(item1);
+ selection.select(item1);
+
+ expect(selection.count()).toBe(1);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('deselect', () => {
+ it('should remove item from selection', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1, item2],
+ });
+
+ selection.deselect('1');
+
+ expect(selection.selected()).toEqual([item2]);
+ expect(selection.isSelected('1')).toBe(false);
+ expect(selection.count()).toBe(1);
+
+ dispose();
+ });
+ });
+
+ it('should do nothing if item not selected', () => {
+ createRoot((dispose) => {
+ const onChange = vi.fn();
+ const selection = createSelectionState({ getItemId, onChange });
+
+ selection.deselect('nonexistent');
+
+ expect(onChange).not.toHaveBeenCalled();
+
+ dispose();
+ });
+ });
+ });
+
+ describe('toggle', () => {
+ it('should select unselected item', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({ getItemId });
+
+ selection.toggle(item1);
+
+ expect(selection.isSelected('1')).toBe(true);
+
+ dispose();
+ });
+ });
+
+ it('should deselect selected item', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1],
+ });
+
+ selection.toggle(item1);
+
+ expect(selection.isSelected('1')).toBe(false);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('selectRange', () => {
+ it('should add multiple items to selection', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1],
+ });
+
+ selection.selectRange([item2, item3]);
+
+ expect(selection.selected()).toEqual([item1, item2, item3]);
+ expect(selection.count()).toBe(3);
+
+ dispose();
+ });
+ });
+
+ it('should not duplicate existing items', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1],
+ });
+
+ selection.selectRange([item1, item2]);
+
+ expect(selection.count()).toBe(2);
+
+ dispose();
+ });
+ });
+
+ it('should not trigger onChange if no new items added', () => {
+ createRoot((dispose) => {
+ const onChange = vi.fn();
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1, item2],
+ onChange,
+ });
+
+ onChange.mockClear();
+ selection.selectRange([item1, item2]);
+
+ expect(onChange).not.toHaveBeenCalled();
+
+ dispose();
+ });
+ });
+ });
+
+ describe('set', () => {
+ it('should replace entire selection', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1, item2],
+ });
+
+ selection.set([item3]);
+
+ expect(selection.selected()).toEqual([item3]);
+ expect(selection.count()).toBe(1);
+
+ dispose();
+ });
+ });
+ });
+
+ describe('clear', () => {
+ it('should remove all items', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1, item2],
+ });
+
+ selection.clear();
+
+ expect(selection.selected()).toEqual([]);
+ expect(selection.count()).toBe(0);
+
+ dispose();
+ });
+ });
+
+ it('should not trigger onChange if already empty', () => {
+ createRoot((dispose) => {
+ const onChange = vi.fn();
+ const selection = createSelectionState({ getItemId, onChange });
+
+ selection.clear();
+
+ expect(onChange).not.toHaveBeenCalled();
+
+ dispose();
+ });
+ });
+ });
+
+ describe('get', () => {
+ it('should return item by id', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1, item2],
+ });
+
+ expect(selection.get('1')).toBe(item1);
+ expect(selection.get('2')).toBe(item2);
+
+ dispose();
+ });
+ });
+
+ it('should return undefined for non-selected id', () => {
+ createRoot((dispose) => {
+ const selection = createSelectionState({ getItemId });
+
+ expect(selection.get('nonexistent')).toBeUndefined();
+
+ dispose();
+ });
+ });
+ });
+
+ describe('onChange callback', () => {
+ it('should be called on select', () => {
+ createRoot((dispose) => {
+ const onChange = vi.fn();
+ const selection = createSelectionState({ getItemId, onChange });
+
+ selection.select(item1);
+
+ expect(onChange).toHaveBeenCalledWith([item1]);
+
+ dispose();
+ });
+ });
+
+ it('should be called on deselect', () => {
+ createRoot((dispose) => {
+ const onChange = vi.fn();
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1, item2],
+ onChange,
+ });
+
+ onChange.mockClear();
+ selection.deselect('1');
+
+ expect(onChange).toHaveBeenCalledWith([item2]);
+
+ dispose();
+ });
+ });
+
+ it('should be called on set', () => {
+ createRoot((dispose) => {
+ const onChange = vi.fn();
+ const selection = createSelectionState({ getItemId, onChange });
+
+ selection.set([item1, item2]);
+
+ expect(onChange).toHaveBeenCalledWith([item1, item2]);
+
+ dispose();
+ });
+ });
+
+ it('should be called on clear', () => {
+ createRoot((dispose) => {
+ const onChange = vi.fn();
+ const selection = createSelectionState({
+ getItemId,
+ initial: [item1],
+ onChange,
+ });
+
+ onChange.mockClear();
+ selection.clear();
+
+ expect(onChange).toHaveBeenCalledWith([]);
+
+ dispose();
+ });
+ });
+ });
+});
diff --git a/js/app/packages/app/component/next-soup/selection-state.ts b/js/app/packages/app/component/next-soup/selection-state.ts
new file mode 100644
index 0000000000..bb32feecd9
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/selection-state.ts
@@ -0,0 +1,150 @@
+import { createSignal, createMemo, type Accessor } from 'solid-js';
+
+export type CreateSelectionOptions<T> = {
+ /** Function to extract ID from item */
+ getItemId: (item: T) => string;
+ /** Initial selected items */
+ initial?: T[];
+ onChange?: (selected: T[]) => void;
+};
+
+export type SelectionState<T> = {
+ readonly selected: Accessor<T[]>;
+ readonly selectedIds: Accessor<Set<string>>;
+ /** Number of selected items */
+ readonly count: Accessor<number>;
+ readonly isSelected: (id: string) => boolean;
+ readonly get: (id: string) => T | undefined;
+ readonly toggle: (item: T) => void;
+ readonly select: (item: T) => void;
+ readonly deselect: (id: string) => void;
+ readonly selectRange: (items: T[]) => void;
+ readonly set: (items: T[]) => void;
+ readonly clear: () => void;
+};
+
+/**
+ * Creates reactive selection state.
+ *
+ * @example
+ * ```ts
+ * const selection = createSelectionState({
+ * getItemId: (item) => item.id,
+ * onChange: (selected) => console.log('Selected:', selected.length),
+ * });
+ *
+ * selection.select(item1);
+ * selection.toggle(item2);
+ * selection.isSelected(item1.id); // true
+ * selection.selected(); // [item1, item2]
+ * ```
+ */
+export function createSelectionState<T>(
+ options: CreateSelectionOptions<T>
+): SelectionState<T> {
+ const { getItemId, initial = [], onChange } = options;
+
+ // Mutable map + version signal for efficient O(1) mutations
+ const items = new Map<string, T>(
+ initial.map((item) => [getItemId(item), item])
+ );
+ const [version, setVersion] = createSignal(0);
+
+ const touch = () => setVersion((v) => v + 1);
+ const notify = () => onChange?.(Array.from(items.values()));
+
+ // Derived state reads version to subscribe to mutations
+ const selected = createMemo(() => {
+ version();
+ return Array.from(items.values());
+ });
+
+ const selectedIds = createMemo(() => {
+ version();
+ return new Set(items.keys());
+ });
+
+ const count = createMemo(() => {
+ version();
+ return items.size;
+ });
+
+ const isSelected = (id: string): boolean => {
+ version();
+ return items.has(id);
+ };
+
+ const get = (id: string): T | undefined => {
+ version();
+ return items.get(id);
+ };
+
+ const select = (item: T) => {
+ const id = getItemId(item);
+ if (items.has(id)) return;
+ items.set(id, item);
+ touch();
+ notify();
+ };
+
+ const deselect = (id: string) => {
+ if (!items.has(id)) return;
+ items.delete(id);
+ touch();
+ notify();
+ };
+
+ const toggle = (item: T) => {
+ const id = getItemId(item);
+ if (items.has(id)) {
+ deselect(id);
+ } else {
+ select(item);
+ }
+ };
+
+ const selectRange = (newItems: T[]) => {
+ let changed = false;
+ for (const item of newItems) {
+ const id = getItemId(item);
+ if (!items.has(id)) {
+ items.set(id, item);
+ changed = true;
+ }
+ }
+ if (changed) {
+ touch();
+ notify();
+ }
+ };
+
+ const set = (newItems: T[]) => {
+ items.clear();
+ for (const item of newItems) {
+ items.set(getItemId(item), item);
+ }
+ touch();
+ notify();
+ };
+
+ const clear = () => {
+ if (items.size === 0) return;
+ items.clear();
+ touch();
+ notify();
+ };
+
+ return {
+ selected,
+ selectedIds,
+ count,
+ isSelected,
+ get,
+ toggle,
+ select,
+ deselect,
+ selectRange,
+ set,
+ clear,
+ };
+}
diff --git a/js/app/packages/app/component/next-soup/soup-context.tsx b/js/app/packages/app/component/next-soup/soup-context.tsx
new file mode 100644
index 0000000000..884843fcef
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-context.tsx
@@ -0,0 +1,29 @@
+import { createSoupState, type SoupState } from './create-soup-state';
+import { createContext, type FlowComponent, useContext } from 'solid-js';
+
+const SoupContext = createContext<SoupState>();
+
+export const useSoup = () => {
+ const context = useContext(SoupContext);
+
+ if (!context) {
+ throw new Error('useSoup can only be used under a SoupContext.Provider');
+ }
+ return context;
+};
+
+export const useMaybeSoup = () => useContext(SoupContext);
+
+interface SoupContextProviderProps {
+ soup?: SoupState;
+}
+
+export const SoupContextProvider: FlowComponent<SoupContextProviderProps> = (
+ props
+) => {
+ return (
+ <SoupContext.Provider value={props.soup ?? createSoupState()}>
+ {props.children}
+ </SoupContext.Provider>
+ );
+};
diff --git a/js/app/packages/app/component/UnifiedListEmptyState.tsx b/js/app/packages/app/component/next-soup/soup-view/empty-states.tsx
similarity index 100%
rename from js/app/packages/app/component/UnifiedListEmptyState.tsx
rename to js/app/packages/app/component/next-soup/soup-view/empty-states.tsx
diff --git a/js/app/packages/app/component/Soup/components/SortDropdown.tsx b/js/app/packages/app/component/next-soup/soup-view/sort-dropdown.tsx
similarity index 96%
rename from js/app/packages/app/component/Soup/components/SortDropdown.tsx
rename to js/app/packages/app/component/next-soup/soup-view/sort-dropdown.tsx
index f563238ffe..4aa531630e 100644
--- a/js/app/packages/app/component/Soup/components/SortDropdown.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/sort-dropdown.tsx
@@ -2,8 +2,8 @@ import { type Component, createSignal, For, Show } from 'solid-js';
import { Popover } from '@kobalte/core/popover';
import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';
import SortIcon from '@macro-icons/wide/sort.svg';
-import type { SystemSortOption } from '../../ViewConfig';
-import { ShortcutLabel } from './FilterButton';
+import type { SystemSortOption } from '@app/component/next-soup/soup-view/sort-options';
+import { ShortcutLabel } from '@app/component/next-soup/soup-view/soup-toolbar';
export interface SortOption {
value: SystemSortOption;
diff --git a/js/app/packages/app/component/next-soup/soup-view/sort-options.ts b/js/app/packages/app/component/next-soup/soup-view/sort-options.ts
new file mode 100644
index 0000000000..befa85a8c1
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/sort-options.ts
@@ -0,0 +1,101 @@
+import type { SortConfig } from '@app/component/next-soup/create-soup-state';
+import type { SoupEntity } from '@app/component/next-soup/soup-view/soup-view-context';
+import {
+ isSearchEntity,
+ type WithSearch,
+ type EntityData,
+ type WithNotification,
+} from '@macro-entity';
+
+export type SystemSortOption =
+ | 'updated_at'
+ | 'created_at'
+ | 'viewed_at'
+ | 'frecency';
+
+export function sortByNotifiedAt<T extends WithNotification<EntityData>>(
+ a: T,
+ b: T
+) {
+ const aNotification = a.notifications?.()[0];
+ const bNotification = b.notifications?.()[0];
+
+ if (aNotification && bNotification) {
+ return bNotification.createdAt - aNotification.createdAt;
+ } else if (aNotification) {
+ return -1;
+ } else if (bNotification) {
+ return 1;
+ }
+
+ return sortByUpdatedAt(a, b);
+}
+
+export function sortByCreatedAt<T extends EntityData>(a: T, b: T): number {
+ return (b.createdAt ?? 0) - (a.createdAt ?? 0);
+}
+
+export function sortByUpdatedAt<T extends EntityData>(a: T, b: T) {
+ return (b.updatedAt ?? 0) - (a.updatedAt ?? 0);
+}
+
+export function sortByViewedAt<T extends EntityData>(a: T, b: T) {
+ return (b.viewedAt ?? 0) - (a.viewedAt ?? 0);
+}
+
+export function sortByFrecencyScore<T extends EntityData>(a: T, b: T): number {
+ return (b.frecencyScore ?? 0) - (a.frecencyScore ?? 0);
+}
+
+export const SORT_CONFIGS = {
+ updated_at: {
+ id: 'updated_at',
+ fn: sortByUpdatedAt,
+ },
+ created_at: {
+ id: 'created_at',
+ fn: sortByCreatedAt,
+ },
+ viewed_at: {
+ id: 'viewed_at',
+ fn: sortByViewedAt,
+ },
+ frecency: {
+ id: 'frecency',
+ fn: sortByFrecencyScore,
+ },
+ notified_at: {
+ id: 'notified_at',
+ fn: sortByNotifiedAt,
+ },
+} satisfies Record<string, SortConfig<SoupEntity>>;
+
+export const sortEntitiesForSearch = <T extends EntityData>(
+ a: T,
+ b: T
+): number => {
+ if (!isSearchEntity(a) || !isSearchEntity(b)) {
+ if (isSearchEntity(a)) return -1;
+ if (isSearchEntity(b)) return 1;
+ return 0;
+ }
+
+ const channelsWithNameMatchesFirst = (a: WithSearch<T>, b: WithSearch<T>) => {
+ if (a.type === 'channel' && b.type !== 'channel' && a.search.nameHighlight)
+ return -1;
+ if (a.type !== 'channel' && b.type === 'channel' && b.search.nameHighlight)
+ return 1;
+ return 0;
+ };
+
+ // NOTE: backend returns items in descending order of updatedAt so we match that here
+ const updatedAtFirst = (a: WithSearch<T>, b: WithSearch<T>) => {
+ if (a.updatedAt && b.updatedAt) return b.updatedAt - a.updatedAt;
+ if (a.updatedAt) return -1;
+ if (b.updatedAt) return 1;
+ return 0;
+ };
+
+ // TODO: we may want to sort exact name matches first for other items too
+ return channelsWithNameMatchesFirst(a, b) || updatedAtFirst(a, b);
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
new file mode 100644
index 0000000000..c289732abc
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
@@ -0,0 +1,138 @@
+import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import { MenuItem } from '@core/component/Menu';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import type { EntityData } from '@macro-entity';
+import {
+ makeCopyAction,
+ makeDeleteAction,
+ makeMarkDoneAction,
+ makeMoveToProjectAction,
+ makeRenameAction,
+} from '../actions';
+import type { SoupState } from '../create-soup-state';
+import { useUserId } from '@core/context/user';
+
+interface SoupEntityActionsMenuProps {
+ entities: EntityData[];
+ soup: SoupState;
+ onActionComplete?: () => void;
+}
+
+export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {
+ const userId = useUserId();
+ const notificationSource = useGlobalNotificationSource();
+
+ const markDone = makeMarkDoneAction({
+ userId: () => userId(),
+ notificationSource: () => notificationSource,
+ });
+
+ const deleteAction = makeDeleteAction({
+ userId: () => userId(),
+ });
+
+ const renameAction = makeRenameAction({
+ userId: () => userId(),
+ });
+
+ const copyAction = makeCopyAction();
+
+ const moveToProjectAction = makeMoveToProjectAction();
+
+ const canExecuteAny = (canExecute: (e: EntityData) => boolean) =>
+ props.entities.some(canExecute);
+
+ const canExecuteAll = (canExecute: (e: EntityData) => boolean) =>
+ props.entities.length > 0 && props.entities.every(canExecute);
+
+ const handleAction = async (
+ execute: (entities: EntityData[], soup: SoupState) => Promise<void>
+ ) => {
+ await execute(props.entities, props.soup);
+ props.onActionComplete?.();
+ };
+
+ const canOpenInSplit = () => {
+ if (props.entities.length !== 1) return false;
+ const entity = props.entities[0];
+ const splits = globalSplitManager()?.splits;
+ if (!splits) return false;
+ return !splits().some((split) => split.content.id === entity.id);
+ };
+
+ const openInNewSplit = () => {
+ const entity = props.entities[0];
+ if (!entity) return;
+
+ const splitManager = globalSplitManager();
+ if (!splitManager) return;
+
+ if (entity.type === 'document') {
+ const { fileType, id, subType } = entity;
+ splitManager.createNewSplit({
+ content: {
+ type: fileTypeToBlockName(subType?.type ?? fileType),
+ id,
+ },
+ referredFrom: 'entity-actions-menu',
+ });
+ } else {
+ splitManager.createNewSplit({
+ content: {
+ type: entity.type,
+ id: entity.id,
+ },
+ referredFrom: 'entity-actions-menu',
+ });
+ }
+ };
+
+ return (
+ <>
+ <MenuItem
+ text="Mark Done"
+ disabled={!canExecuteAny(markDone.canExecute)}
+ onClick={() => handleAction(markDone.executeWithSoup)}
+ />
+
+ <MenuItem
+ text="Open in new split"
+ disabled={!canOpenInSplit()}
+ onClick={openInNewSplit}
+ />
+
+ <Divider />
+
+ <MenuItem
+ text="Rename"
+ disabled={!canExecuteAll(renameAction.canExecute)}
+ onClick={() => handleAction(renameAction.executeWithSoup)}
+ />
+
+ <MenuItem
+ text="Move to folder"
+ disabled={!canExecuteAny(moveToProjectAction.canExecute)}
+ onClick={() => handleAction(moveToProjectAction.executeWithSoup)}
+ />
+
+ <MenuItem
+ text="Copy"
+ disabled={!canExecuteAny(copyAction.canExecute)}
+ onClick={() => handleAction(copyAction.executeWithSoup)}
+ />
+
+ <Divider />
+
+ <div class="text-failure-ink w-full">
+ <MenuItem
+ text="Delete"
+ disabled={!canExecuteAll(deleteAction.canExecute)}
+ onClick={() => handleAction(deleteAction.executeWithSoup)}
+ />
+ </div>
+ </>
+ );
+};
+
+const Divider = () => <div class="border-b border-edge-muted w-full my-1" />;
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-entity-context-menu.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-entity-context-menu.tsx
new file mode 100644
index 0000000000..6a7af3c618
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-entity-context-menu.tsx
@@ -0,0 +1,46 @@
+import { ContextMenuContent, MenuSeparator } from '@core/component/Menu';
+import { isMobile } from '@core/mobile/isMobile';
+import { ContextMenu } from '@kobalte/core/context-menu';
+import { Entity, type EntityData } from '@macro-entity';
+import { type FlowComponent, Show } from 'solid-js';
+import { useSoupView } from './soup-view-context';
+import { SoupEntityActionsMenu } from './soup-entity-actions-menu';
+
+interface SoupEntityContextMenuProps {
+ entity: EntityData;
+ entityTimestamp?: number;
+ onOpenChange?: (open: boolean) => void;
+}
+
+export const SoupEntityContextMenu: FlowComponent<
+ SoupEntityContextMenuProps
+> = (props) => {
+ const { soup } = useSoupView();
+
+ return (
+ <ContextMenu onOpenChange={props.onOpenChange}>
+ <ContextMenu.Trigger class="size-full">
+ {props.children}
+ </ContextMenu.Trigger>
+ <ContextMenu.Portal>
+ <Show when={props.entity}>
+ {(selectedEntity) => (
+ <ContextMenuContent mobileFullScreen>
+ <Show when={isMobile()}>
+ <Entity
+ entity={selectedEntity()}
+ timestamp={props.entityTimestamp}
+ />
+ <MenuSeparator />
+ </Show>
+ <SoupEntityActionsMenu
+ entities={[selectedEntity()]}
+ soup={soup}
+ />
+ </ContextMenuContent>
+ )}
+ </Show>
+ </ContextMenu.Portal>
+ </ContextMenu>
+ );
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx
new file mode 100644
index 0000000000..e5af9051bc
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx
@@ -0,0 +1,56 @@
+import {
+ resetCommandCategoryIndex,
+ searchCategories,
+ setCommandCategoryIndex,
+ setKonsoleContextInformation,
+} from '@app/component/command/KonsoleItem';
+import {
+ resetKonsoleMode,
+ setKonsoleMode,
+ toggleKonsoleVisibility,
+} from '@app/component/command/state';
+import { EntitySelectionToolbarModal } from '@app/component/EntitySelectionToolbarModal';
+import type { EntityData } from '@macro-entity';
+
+interface SoupEntitySelectionToolbarProps {
+ selected: EntityData[];
+ onClose: VoidFunction;
+ onClear: VoidFunction;
+}
+
+export const SoupEntitySelectionToolbar = (
+ props: SoupEntitySelectionToolbarProps
+) => {
+ return (
+ <EntitySelectionToolbarModal
+ multiSelectEntities={props.selected}
+ onClose={props.onClose}
+ onAction={() => {
+ const selected = props.selected;
+ const hasSelection = selected.length > 0;
+ if (!hasSelection) {
+ searchCategories.hideCategory('Selection');
+ resetCommandCategoryIndex();
+ resetKonsoleMode();
+ return;
+ }
+
+ setKonsoleMode('SELECTION_MODIFICATION');
+ const selectionIndex = searchCategories.getCategoryIndex('Selection');
+
+ if (selectionIndex === undefined) return false;
+
+ setCommandCategoryIndex(selectionIndex);
+
+ searchCategories.showCategory('Selection');
+
+ setKonsoleContextInformation({
+ selectedEntities: selected.slice(),
+ clearSelection: props.onClear,
+ });
+
+ toggleKonsoleVisibility();
+ }}
+ />
+ );
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx
new file mode 100644
index 0000000000..d6eb2a8b4d
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx
@@ -0,0 +1,585 @@
+import SearchIcon from '@macro-icons/macro-magnifying-glass.svg';
+import IconGear from '@macro-icons/macro-gear.svg';
+import XIcon from '@icon/regular/x.svg?component-solid';
+import PreviewIcon from '@macro-icons/wide/preview.svg';
+import NoiseIcon from '@macro-icons/wide/noise.svg';
+import SignalIcon from '@macro-icons/wide/signal.svg';
+import {
+ SplitHeaderLeft,
+ SplitHeaderRight,
+} from '@app/component/split-layout/components/SplitHeader';
+import { useSplitLayout } from '@app/component/split-layout/layout';
+import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';
+import { useSettingsState } from '@core/constant/SettingsState';
+import { TOKENS } from '@core/hotkey/tokens';
+import {
+ For,
+ Show,
+ onCleanup,
+ createSignal,
+ onMount,
+ createEffect,
+ type Component,
+} from 'solid-js';
+import {
+ ENTITY_TYPE_FILTER_CONFIGS,
+ type FilterID,
+ getEntityTypeFilterIcon,
+} from '@app/component/next-soup/filters/filters';
+import { registerHotkey } from '@core/hotkey/hotkeys';
+import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';
+import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
+import type { ValidHotkey } from '@core/hotkey/types';
+import { createElementSize } from '@solid-primitives/resize-observer';
+import { IS_MAC } from '@core/constant/isMac';
+import type { SystemSortOption } from '@app/component/next-soup/soup-view/sort-options';
+import { Dynamic } from 'solid-js/web';
+import { SortDropdown } from '@app/component/next-soup/soup-view/sort-dropdown';
+
+/**
+ * Keyboard shortcuts for entity type filters.
+ * This object is the single source of truth for filter shortcuts,
+ * used by both the filter buttons and hotkey registrations.
+ */
+const ENTITY_TYPE_SHORTCUTS: Record<
+ (typeof ENTITY_TYPE_FILTER_CONFIGS)[number]['id'],
+ ValidHotkey
+> = {
+ document: 'd',
+ task: 't',
+ email: 'l',
+ people: 'p',
+ teams: 'm',
+ agent: 'a',
+ file: 'f',
+};
+
+export const SoupToolbar = () => {
+ const { soup } = useSoupView();
+
+ const [scrollContainerRef, setScrollContainerRef] = createSignal<
+ HTMLDivElement | undefined
+ >(undefined);
+
+ return (
+ <>
+ <SplitHeaderLeft>
+ <div class="relative h-full">
+ <ScrollIndicators scrollRef={scrollContainerRef()} />
+
+ <div
+ ref={setScrollContainerRef}
+ class="flex items-center h-full overflow-x-auto scrollbar-hidden overscroll-none text-xs touch:mobile-width:text-sm"
+ >
+ <SoupFilters />
+ <SearchBar />
+ </div>
+ </div>
+ </SplitHeaderLeft>
+
+ <SplitHeaderRight>
+ <div class="flex items-center h-full gap-0.5">
+ <Tooltip
+ tooltip={<LabelAndHotKey label="Clear filters" shortcut="/" />}
+ >
+ <button
+ type="button"
+ class="flex items-center gap-1.5 px-2.5 rounded-full text-ink-muted hover:text-accent hover:bg-accent/20 active:bg-accent active:text-panel"
+ onClick={soup.filters.clear}
+ >
+ <XIcon class="size-4.5" />
+ <span class="text-xs touch:mobile-width:text-sm leading-none">
+ Clear
+ <span class="ml-1 font-mono opacity-70">/</span>
+ </span>
+ </button>
+ </Tooltip>
+ <div class="mx-0.5 w-px h-5 bg-edge-muted/50 shrink-0" />
+ <SettingsButton />
+ </div>
+ </SplitHeaderRight>
+ </>
+ );
+};
+
+const SoupFilters = () => {
+ const { soup, setSearchText } = useSoupView();
+ const panel = useSplitPanelOrThrow();
+
+ const [sortDropdownOpen, setSortDropdownOpen] = createSignal(false);
+
+ const toggleFilter = (filter: FilterID) => {
+ soup.filters.toggle(filter);
+ };
+
+ const toggleSignalFilter = () => {
+ // If we're going to be removing the signal filter,
+ // we should replace it with the explicit-noise filter
+ if (soup.filters.isActive('signal')) {
+ toggleFilter('explicit-noise');
+ } else {
+ toggleFilter('signal');
+ }
+
+ toggleFilter('not-done');
+ };
+
+ const toggleNoiseFilter = () => {
+ // If we're going to be removing the noise filter,
+ // we should replace it with the explicit-noise filter
+ if (soup.filters.isActive('noise')) {
+ toggleFilter('explicit-noise');
+ } else {
+ toggleFilter('noise');
+ }
+
+ toggleFilter('not-done');
+ };
+
+ const togglePreview = () => {
+ const currentPreview = soup.previewEntity();
+ if (currentPreview) {
+ soup.setPreviewEntity(undefined);
+ return;
+ }
+
+ const focused = soup.focus.id();
+
+ if (!focused) return;
+
+ soup.setPreviewEntity(focused);
+ };
+
+ const hotkeyConfigs: {
+ hotkey: ValidHotkey;
+ description: string;
+ handler: () => void;
+ }[] = [
+ {
+ hotkey: 'i',
+ description: 'Toggle Inbox',
+ handler: toggleSignalFilter,
+ },
+ {
+ hotkey: 'o',
+ description: 'Toggle Other',
+ handler: toggleNoiseFilter,
+ },
+ // Entity type filter hotkeys
+ {
+ hotkey: ENTITY_TYPE_SHORTCUTS.document,
+ description: 'Filter by Docs',
+ handler: () => toggleFilter('document'),
+ },
+ {
+ hotkey: ENTITY_TYPE_SHORTCUTS.task,
+ description: 'Filter by Tasks',
+ handler: () => toggleFilter('task'),
+ },
+ {
+ hotkey: ENTITY_TYPE_SHORTCUTS.email,
+ description: 'Filter by Mail',
+ handler: () => toggleFilter('email'),
+ },
+ {
+ hotkey: ENTITY_TYPE_SHORTCUTS.people,
+ description: 'Filter by People',
+ handler: () => toggleFilter('people'),
+ },
+ {
+ hotkey: ENTITY_TYPE_SHORTCUTS.teams,
+ description: 'Filter by Teams',
+ handler: () => toggleFilter('teams'),
+ },
+ {
+ hotkey: ENTITY_TYPE_SHORTCUTS.agent,
+ description: 'Filter by Agents',
+ handler: () => toggleFilter('agent'),
+ },
+ {
+ hotkey: ENTITY_TYPE_SHORTCUTS.file,
+ description: 'Filter by Files',
+ handler: () => toggleFilter('file'),
+ },
+ {
+ hotkey: 'u',
+ description: 'Filter by Unread',
+ handler: () => toggleFilter('unread'),
+ },
+ {
+ hotkey: 's',
+ description: 'Open sort menu',
+ handler: () => setSortDropdownOpen((prev) => !prev),
+ },
+ {
+ hotkey: '/',
+ description: 'Clear filters',
+ handler: () => {
+ soup.filters.clear();
+ setSearchText('');
+ },
+ },
+ {
+ hotkey: 'space',
+ description: 'Toggle preview',
+ handler: () => {
+ togglePreview();
+ },
+ },
+ ];
+
+ const hotkeyDisposers = hotkeyConfigs.map((config) =>
+ registerHotkey({
+ hotkey: [config.hotkey],
+ scopeId: panel.splitHotkeyScope,
+ description: config.description,
+ keyDownHandler: () => {
+ config.handler();
+ return true;
+ },
+ })
+ );
+
+ onCleanup(() => {
+ hotkeyDisposers.forEach((d) => d.dispose());
+ });
+
+ return (
+ <>
+ {/* Inbox toggle */}
+ <FilterButton
+ icon={SignalIcon}
+ label="Inbox"
+ shortcut="i"
+ isActive={soup.filters.isActive('signal')}
+ onClick={toggleSignalFilter}
+ />
+ {/* Other toggle */}
+ <FilterButton
+ icon={NoiseIcon}
+ label="Other"
+ shortcut="o"
+ isActive={soup.filters.isActive('noise')}
+ onClick={toggleNoiseFilter}
+ />
+ <FilterDivider />
+ {/* Unread filter */}
+ <div class="flex items-center mr-0.5 shrink-0">
+ <Tooltip tooltip={<LabelAndHotKey label="Unread Only" shortcut="u" />}>
+ <button
+ type="button"
+ class="flex items-center gap-1 h-[22px] touch:mobile-width:h-9 pr-2.5 pl-1 active:bg-accent active:text-panel rounded-full"
+ classList={{
+ 'bg-accent text-panel': soup.filters.isActive('unread'),
+ 'text-ink-muted hover:text-accent hover:bg-accent/20':
+ !soup.filters.isActive('unread'),
+ }}
+ onClick={() => soup.filters.toggle('unread')}
+ >
+ <svg
+ class="size-4"
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ stroke="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <circle cx="12" cy="12" r="4" />
+ </svg>
+ <span class="leading-none">
+ <ShortcutLabel label="Unread" shortcut="u" />
+ </span>
+ </button>
+ </Tooltip>
+ </div>
+ <div class="mx-0.5 w-px h-5 bg-edge-muted/50 shrink-0" />
+ {/* Entity type icons */}
+ <div class="flex items-center shrink-0">
+ <For each={ENTITY_TYPE_FILTER_CONFIGS}>
+ {(filter) => {
+ const iconConfig = () => getEntityTypeFilterIcon(filter.id);
+ const shortcut = ENTITY_TYPE_SHORTCUTS[filter.id];
+
+ return (
+ <FilterButton
+ icon={iconConfig().icon}
+ label={filter.label ?? ''}
+ shortcut={shortcut}
+ isActive={() => soup.filters.isActive(filter.id)}
+ onClick={() => toggleFilter(filter.id)}
+ paddingClass="px-2.5"
+ />
+ );
+ }}
+ </For>
+ </div>
+ <div class="mx-0.5 w-px h-5 bg-edge-muted/50 shrink-0" />
+ {/* Preview toggle */}
+ <Tooltip
+ tooltip={<LabelAndHotKey label="Toggle Preview" shortcut="space" />}
+ >
+ <button
+ type="button"
+ class="flex items-center gap-1.5 h-[22px] touch:mobile-width:h-9 px-2.5 active:bg-accent active:text-panel rounded-full"
+ classList={{
+ 'bg-accent text-panel': !!soup.previewEntity(),
+ 'text-ink-muted hover:text-accent hover:bg-accent/20':
+ !soup.previewEntity(),
+ }}
+ disabled={!soup.focus.id()}
+ onClick={togglePreview}
+ >
+ <PreviewIcon class="size-4.5" />
+ <span class="leading-none">
+ <ShortcutLabel label="Preview" shortcut="space" />
+ </span>
+ </button>
+ </Tooltip>
+ <FilterDivider />
+ {/* Sort dropdown */}
+ <SortDropdown
+ open={sortDropdownOpen}
+ onOpenChange={setSortDropdownOpen}
+ value={() => soup.sort.active()[0].id as SystemSortOption}
+ onChange={(value) => {
+ soup.sort.setAll([value]);
+ }}
+ />
+ <div class="touch:mobile-width:-order-1">
+ <FilterDivider />
+ </div>
+ {/* Filter search bar */}
+ </>
+ );
+};
+
+function SettingsButton() {
+ const { settingsOpen, toggleSettings } = useSettingsState();
+ const { getSplitCount } = useSplitLayout();
+
+ // Hide settings button when there are multiple splits
+ const isSingleSplit = () => getSplitCount() <= 1;
+
+ return (
+ <Show when={isSingleSplit()}>
+ <Tooltip
+ tooltip={
+ <LabelAndHotKey
+ label={settingsOpen() ? 'Close Settings' : 'Open Settings'}
+ hotkeyToken={TOKENS.global.toggleSettings}
+ />
+ }
+ >
+ <button
+ type="button"
+ class="relative flex items-center justify-center size-[22px] rounded-full active:bg-accent active:text-panel"
+ classList={{
+ 'bg-hover text-ink': settingsOpen(),
+ 'text-ink-muted hover:text-accent hover:bg-accent/20':
+ !settingsOpen(),
+ }}
+ onClick={() => toggleSettings()}
+ >
+ <IconGear class="size-4.5" />
+ </button>
+ </Tooltip>
+ </Show>
+ );
+}
+
+const ScrollIndicators = (props: { scrollRef: HTMLElement | undefined }) => {
+ const [leftOpacity, setLeftOpacity] = createSignal(0);
+ const [rightOpacity, setRightOpacity] = createSignal(0);
+ const SCROLL_THRESHOLD = 10;
+
+ // Track size changes to update indicators
+ const size = createElementSize(() => props.scrollRef);
+ const containerWidth = () => size.width ?? 0;
+
+ const updateClipIndicators = () => {
+ const ref = props.scrollRef;
+ if (!ref) return;
+ const { scrollLeft, scrollWidth, clientWidth } = ref;
+
+ const leftAmount = Math.min(scrollLeft, SCROLL_THRESHOLD);
+ setLeftOpacity(leftAmount / SCROLL_THRESHOLD);
+
+ const maxScroll = scrollWidth - clientWidth;
+ const remainingScroll = maxScroll - scrollLeft;
+ const rightAmount = Math.min(remainingScroll, SCROLL_THRESHOLD);
+ setRightOpacity(rightAmount / SCROLL_THRESHOLD);
+ };
+
+ // Update indicators when size changes
+ createEffect(() => {
+ containerWidth(); // Track size changes
+ updateClipIndicators();
+ });
+
+ onMount(() => {
+ const ref = props.scrollRef;
+ if (!ref) return;
+ ref.addEventListener('scroll', updateClipIndicators);
+ onCleanup(() => ref?.removeEventListener('scroll', updateClipIndicators));
+ });
+ return (
+ <>
+ {/* Left clip boundary indicator */}
+ <div
+ class="absolute pointer-events-none left-0 top-px bottom-px w-3 z-2 pattern-diagonal-4 pattern-edge mask-r-from-0% border-l border-edge-muted"
+ style={{ opacity: leftOpacity() }}
+ />
+ {/* Right clip boundary indicator */}
+ <div
+ class="absolute pointer-events-none right-0 top-px bottom-px w-3 z-2 pattern-diagonal-4 pattern-edge mask-l-from-0% border-r border-edge-muted"
+ style={{ opacity: rightOpacity() }}
+ />
+ </>
+ );
+};
+
+const SearchBar = () => {
+ const { searchText, setSearchText } = useSoupView();
+ const panel = useSplitPanelOrThrow();
+
+ const [ref, setRef] = createSignal<HTMLInputElement | undefined>();
+
+ const [searchFocused, setSearchFocused] = createSignal(false);
+
+ const searchHotkey = registerHotkey({
+ hotkey: ['cmd+f'],
+ scopeId: panel.splitHotkeyScope,
+ description: 'Search',
+ keyDownHandler: () => {
+ ref()?.focus();
+ if (ref()?.value) ref()?.select();
+ return true;
+ },
+ });
+
+ onCleanup(searchHotkey.dispose);
+
+ return (
+ <div class="flex items-center shrink-0 touch:mobile-width:-order-2">
+ <Tooltip tooltip={<LabelAndHotKey label="Filter" shortcut="⌘F" />}>
+ <div
+ class="relative flex items-center gap-1.5 h-[22px] touch:mobile-width:h-9 px-2.5 rounded-full touch:mobile-width:min-w-35"
+ classList={{
+ 'bg-accent text-panel': !!searchText() && !searchFocused(),
+ 'text-ink-muted hover:text-accent hover:bg-accent/20':
+ !searchText() || searchFocused(),
+ }}
+ onClick={() => ref()?.focus()}
+ >
+ <SearchIcon class="size-4.5 shrink-0" />
+ <Show when={!searchText() && !searchFocused()}>
+ <span class="leading-none pointer-events-none">
+ <span class="underline underline-offset-2 decoration-current/60">
+ {IS_MAC ? '⌘' : '^'}F
+ </span>
+ <span>ilter</span>
+ </span>
+ </Show>
+ <input
+ ref={setRef}
+ type="text"
+ value={searchText()}
+ onInput={(e) => setSearchText(e.currentTarget.value)}
+ onFocus={() => setSearchFocused(true)}
+ onBlur={() => setSearchFocused(false)}
+ onKeyDown={(e) => {
+ if (
+ e.key === 'Escape' ||
+ e.key === 'Enter' ||
+ e.key === 'ArrowDown'
+ ) {
+ e.preventDefault();
+ e.currentTarget.blur();
+ }
+ }}
+ class="p-0 bg-transparent border-none outline-none ring-0 focus:outline-none focus:ring-0 cursor-default"
+ style={{
+ width:
+ !searchText() && !searchFocused()
+ ? '0'
+ : `${Math.max(5, searchText().length + 1)}ch`,
+ }}
+ />
+ </div>
+ </Tooltip>
+ </div>
+ );
+};
+
+const SHORTCUT_SUFFIXES: Record<string, string> = { space: '␣', '/': '/' };
+
+export const ShortcutLabel: Component<{ label: string; shortcut: string }> = (
+ props
+) => {
+ const s = props.shortcut.trim();
+ if (!s) return <>{props.label}</>;
+
+ const suffix = SHORTCUT_SUFFIXES[s.toLowerCase()] ?? SHORTCUT_SUFFIXES[s];
+ if (suffix) {
+ return (
+ <>
+ {props.label}
+ <span class="ml-1 font-mono opacity-70">{suffix}</span>
+ </>
+ );
+ }
+
+ const idx = props.label.toLowerCase().indexOf(s.toLowerCase());
+ if (idx === -1) return <>{props.label}</>;
+
+ return (
+ <>
+ {props.label.slice(0, idx)}
+ <span class="underline underline-offset-2 decoration-current/60">
+ {props.label.slice(idx, idx + s.length)}
+ </span>
+ {props.label.slice(idx + s.length)}
+ </>
+ );
+};
+
+export interface FilterButtonProps {
+ icon: Component<{ class?: string }>;
+ label: string;
+ shortcut: string;
+ isActive: (() => boolean) | boolean;
+ onClick: () => void;
+ paddingClass?: string;
+}
+
+export const FilterButton: Component<FilterButtonProps> = (props) => (
+ <div class="flex items-center mr-0.5 shrink-0">
+ <Tooltip
+ tooltip={<LabelAndHotKey label={props.label} shortcut={props.shortcut} />}
+ >
+ <button
+ type="button"
+ class={`flex items-center gap-1 h-[22px] touch:mobile-width:h-9 ${props.paddingClass ?? 'pl-2 pr-2.5'} active:bg-accent active:text-panel rounded-full`}
+ classList={{
+ 'bg-accent text-panel':
+ typeof props.isActive === 'function'
+ ? props.isActive()
+ : props.isActive,
+ 'text-ink-muted hover:text-accent hover:bg-accent/20':
+ !(typeof props.isActive === 'function'
+ ? props.isActive()
+ : props.isActive),
+ }}
+ onClick={props.onClick}
+ >
+ <Dynamic component={props.icon} class="size-3.5" />
+ <span class="leading-none">
+ <ShortcutLabel label={props.label} shortcut={props.shortcut} />
+ </span>
+ </button>
+ </Tooltip>
+ </div>
+);
+
+export const FilterDivider: Component = () => (
+ <div class="mx-0.5 w-px h-5 bg-edge-muted/50 shrink-0" />
+);
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
new file mode 100644
index 0000000000..ef22a48f63
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
@@ -0,0 +1,409 @@
+import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
+import {
+ createSoupState,
+ type SoupState,
+} from '@app/component/next-soup/create-soup-state';
+import {
+ buildDssFiltersRequest,
+ getFolderFileTypes,
+} from '@app/component/next-soup/filters/filters';
+import { sortEntitiesForSearch } from '@app/component/next-soup/soup-view/sort-options';
+import { deduplicateEntities } from '@app/component/next-soup/utils';
+import { useEmailLinksStatus } from '@core/email-link';
+import { arrayEquals } from '@core/util/compareUtils';
+import { debouncedDependent } from '@core/util/debounce';
+import { fuzzyMatch } from '@core/util/fuzzy';
+import type { EntityData, WithNotification, WithSearch } from '@macro-entity';
+import { useNotificationsForEntity } from '@notifications';
+import {
+ type SoupItemsQueryFilters,
+ useSoupItemsQuery,
+} from '@queries/soup/items';
+import { useSearchSoupQuery } from '@queries/soup/search';
+import type { SearchArgs } from '@service-search/client';
+import type { UnifiedSearchIndex } from '@service-search/generated/models';
+import {
+ type Accessor,
+ createContext,
+ createMemo,
+ createRenderEffect,
+ createSignal,
+ type FlowComponent,
+ on,
+ Suspense,
+ useContext,
+} from 'solid-js';
+import { match } from 'ts-pattern';
+
+const SEARCH_SERVICE_DEBOUNCE_MS = 300;
+const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 20;
+
+type Row<T> = {
+ original: T;
+ depth: number;
+ isSelected: () => boolean;
+ isExpanded: () => boolean;
+ isGrouped: () => boolean;
+ isFocused: () => boolean;
+ toggleExpanded: (expanded?: boolean) => void;
+};
+
+export type SoupRow = Row<SoupEntity>;
+
+export type SoupEntity = WithNotification<EntityData | WithSearch<EntityData>>;
+
+type DataSource<T> = {
+ data: Accessor<T[]>;
+ isLoading: Accessor<boolean>;
+ isFetching: Accessor<boolean>;
+ isFetchingNextPage: Accessor<boolean>;
+ hasNextPage: Accessor<boolean>;
+ fetchNextPage: VoidFunction;
+};
+
+interface SoupViewContextValues {
+ soup: SoupState;
+ source: DataSource<EntityData>;
+ searchText: Accessor<string>;
+ setSearchText: (value: string) => void;
+ isSearchDisabled: Accessor<boolean>;
+ rows: Accessor<SoupRow[]>;
+}
+
+export const SoupViewContext = createContext<SoupViewContextValues>();
+
+export const useSoupView = () => {
+ const context = useContext(SoupViewContext);
+
+ if (!context) {
+ throw new Error(
+ 'useSoupView can only be used under a SoupViewContext.Provider'
+ );
+ }
+
+ return context;
+};
+
+export const useMaybeSoupView = () => useContext(SoupViewContext);
+
+interface SoupViewContextProviderProps {
+ soup?: SoupState;
+ queryFilters?: SoupItemsQueryFilters;
+}
+
+export const SoupViewContextProvider: FlowComponent<
+ SoupViewContextProviderProps
+> = (props) => {
+ const soup = props.soup ?? createSoupState();
+
+ const emailActive = useEmailLinksStatus();
+
+ const [searchText, setSearchText] = createSignal('');
+
+ const debouncedSearchForLocal = debouncedDependent(
+ searchText,
+ LOCAL_FUZZY_SEARCH_DEBOUNCE_MS
+ );
+
+ const debouncedSearchForService = debouncedDependent(
+ searchText,
+ SEARCH_SERVICE_DEBOUNCE_MS
+ );
+
+ const unifiedSearchIncludeArray = createMemo<UnifiedSearchIndex[]>(
+ () => {
+ let types = soup.filters.activeIds();
+ // NOTE: empty array means search all
+ if (types.length === 0) types = [];
+ const includeArray: UnifiedSearchIndex[] = [];
+ for (const type of types) {
+ match(type)
+ .with('document', () => {
+ includeArray.push('documents');
+ })
+ .with('agent', () => {
+ includeArray.push('chats');
+ })
+ .with('people', 'teams', () => {
+ includeArray.push('channels');
+ })
+ .with('email', () => {
+ includeArray.push('emails');
+ })
+ .with('project', () => {
+ includeArray.push('projects');
+ });
+ }
+ return Array.from(new Set(includeArray));
+ },
+ [],
+ { equals: arrayEquals }
+ );
+
+ const validSearchTerms = createMemo(
+ () => debouncedSearchForService().length >= 3
+ );
+ const isSearchDisabled = createMemo(() => !validSearchTerms());
+
+ const searchUnifiedNameContentQueryParams = createMemo(
+ (prev: SearchArgs | undefined): SearchArgs => {
+ if (prev && prev.request.terms?.[0] === debouncedSearchForService()) {
+ return prev;
+ }
+
+ return {
+ params: {
+ cursor: null,
+ page_size: 100,
+ },
+ request: {
+ search_on: 'name_content',
+ match_type: 'partial',
+ terms:
+ debouncedSearchForService().length > 0
+ ? [debouncedSearchForService()]
+ : undefined,
+ // filters: unifiedSearchFilters(),
+ include: unifiedSearchIncludeArray(),
+ },
+ };
+ }
+ );
+
+ const queryFilters = createMemo(() => {
+ const base = buildDssFiltersRequest(soup.filters.active(), {
+ extra: props.queryFilters,
+ isSearchActive: !isSearchDisabled(),
+ emailActive: emailActive(),
+ });
+
+ if (soup.filters.isActive('file')) {
+ if (base.document_filters?.file_types) {
+ base.document_filters.file_types = getFolderFileTypes('soup');
+ }
+ }
+
+ if (soup.filters.isActive('task')) {
+ if (base.document_filters?.file_types) {
+ base.document_filters.file_types = ['md'];
+ }
+ }
+
+ return base;
+ });
+
+ const searchFilters = createMemo(() => {
+ const {
+ channel_filters,
+ chat_filters,
+ document_filters,
+ email_filters,
+ project_filters,
+ } = queryFilters();
+
+ let fileTypes = document_filters?.file_types;
+
+ if (soup.filters.isActive('file')) {
+ fileTypes = getFolderFileTypes('search');
+ }
+
+ return {
+ channel: channel_filters?.channel_ids?.length ? channel_filters : null,
+ chat:
+ chat_filters?.chat_ids?.length || chat_filters?.project_ids?.length
+ ? chat_filters
+ : null,
+ document:
+ document_filters?.document_ids?.length ||
+ document_filters?.project_ids?.length ||
+ document_filters?.file_types?.length
+ ? { ...document_filters, file_types: fileTypes }
+ : null,
+ email: email_filters?.recipients?.length ? email_filters : null,
+ project: project_filters?.project_ids?.length ? project_filters : null,
+ };
+ });
+
+ const itemsQuery = useSoupItemsQuery(
+ () => ({
+ params: {
+ limit: 100,
+ sort_method:
+ (soup.sort.active()[0]?.id as 'updated_at') ?? 'updated_at',
+ },
+ body: queryFilters(),
+ }),
+ () => ({
+ enabled: isSearchDisabled(),
+ })
+ );
+
+ const searchQuery = useSearchSoupQuery(
+ () => ({
+ params: {
+ page_size: 100,
+ },
+ body: {
+ ...searchFilters(),
+ ...searchUnifiedNameContentQueryParams().request,
+ },
+ }),
+ () => ({
+ enabled: !isSearchDisabled(),
+ })
+ );
+
+ const nameFuzzySearchFilter = (items: EntityData[]) => {
+ const query = debouncedSearchForLocal();
+ if (!query || query.length === 0) return items;
+
+ const matchResults = fuzzyMatch(query, items, (item) => item.name);
+
+ return matchResults.map((result) => {
+ return {
+ ...result.item,
+ search: {
+ nameHighlight: result.nameHighlight,
+ contentHitData: null,
+ source: 'local',
+ },
+ } as WithSearch<EntityData>;
+ });
+ };
+
+ const notificationSource = useGlobalNotificationSource();
+
+ const attachNotifications = (entity: EntityData) => {
+ return {
+ ...entity,
+ notifications: useNotificationsForEntity(notificationSource, entity),
+ };
+ };
+
+ const attachMethods = (
+ entity: WithNotification<EntityData>,
+ depth = 0
+ ): SoupRow => {
+ return {
+ original: entity,
+ depth,
+ isFocused() {
+ return soup.focus.id() === entity.id;
+ },
+ isSelected() {
+ return soup.selection.isSelected(entity.id);
+ },
+ isGrouped() {
+ return false;
+ },
+ isExpanded() {
+ return soup.selection.isSelected(entity.id);
+ },
+ toggleExpanded() {
+ return soup.selection.isSelected(entity.id);
+ },
+ };
+ };
+
+ const entities = () => {
+ const itemsData = itemsQuery.data;
+ const searchData = searchQuery.data;
+
+ if (!itemsData && !searchData) return [];
+
+ const filters = soup.filters.active();
+
+ const isSearching = searchText().length > 0;
+
+ const items = itemsData ?? [];
+ const searchItems = isSearching ? (searchData ?? []) : [];
+
+ let transformed: SoupEntity[] = [...searchItems];
+
+ if (isSearching) {
+ transformed.push(...nameFuzzySearchFilter(items));
+ } else {
+ transformed.push(...items);
+ }
+
+ transformed = transformed.map(attachNotifications);
+
+ for (const filter of filters) {
+ transformed = transformed.filter(filter.predicate);
+ }
+
+ transformed = deduplicateEntities(transformed);
+
+ if (isSearching) {
+ transformed = transformed.toSorted(sortEntitiesForSearch);
+ }
+
+ const sorts = soup.sort.active();
+
+ if (sorts.length > 0) {
+ transformed = transformed.toSorted((a, b) => {
+ for (const sort of sorts) {
+ const result = sort.fn(a, b);
+ if (result !== 0) return result;
+ }
+ return 0;
+ });
+ }
+
+ return transformed;
+ };
+
+ const rows = () => {
+ return entities().map((e) => attachMethods(e));
+ };
+
+ const context = {
+ soup,
+ source: {
+ data: entities,
+ isLoading: () => searchQuery.isLoading || itemsQuery.isLoading,
+ isFetching: () => searchQuery.isFetching || itemsQuery.isFetching,
+ isFetchingNextPage: () =>
+ searchQuery.isFetchingNextPage || itemsQuery.isFetchingNextPage,
+ hasNextPage: () => {
+ return (
+ (searchQuery.isEnabled && searchQuery.hasNextPage) ||
+ (itemsQuery.isEnabled && itemsQuery.hasNextPage)
+ );
+ },
+ fetchNextPage: () => {
+ if (searchQuery.isEnabled) {
+ searchQuery.fetchNextPage();
+ }
+
+ if (itemsQuery.isEnabled) {
+ itemsQuery.fetchNextPage();
+ }
+ },
+ },
+ rows,
+ searchText,
+ setSearchText,
+ isSearchDisabled,
+ };
+
+ return (
+ <SoupViewContext.Provider value={context}>
+ {props.children}
+ <Suspense>
+ <SyncWithSoup soup={soup} entities={entities()} />
+ </Suspense>
+ </SoupViewContext.Provider>
+ );
+};
+
+interface SyncWithSoupProps {
+ soup: SoupState;
+ entities: SoupEntity[];
+}
+
+const SyncWithSoup = (props: SyncWithSoupProps) => {
+ createRenderEffect(on(() => props.entities, props.soup.setData));
+
+ return null;
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-file-dropzone.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-file-dropzone.tsx
new file mode 100644
index 0000000000..dec395f9e6
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-file-dropzone.tsx
@@ -0,0 +1,40 @@
+import { useHandleFileUpload } from '@app/util/handleFileUpload';
+import { FileDropOverlay } from '@core/component/FileDropOverlay';
+import { handleFileFolderDrop } from '@core/util/upload';
+import { createSignal, Show, type FlowComponent } from 'solid-js';
+import { fileFolderDrop } from '@core/directive/fileFolderDrop';
+
+false && fileFolderDrop;
+
+export const SoupViewFileDropzone: FlowComponent = (props) => {
+ const [isDragging, setIsDragging] = createSignal(false);
+ const [isValidDrag, setIsValidDrag] = createSignal(true);
+
+ const handleFileUpload = useHandleFileUpload();
+
+ return (
+ <div
+ class="relative flex flex-col bg-panel size-full"
+ use:fileFolderDrop={{
+ onDrop: (fileEntries, folderEntries) => {
+ handleFileFolderDrop(fileEntries, folderEntries, handleFileUpload);
+ },
+ onDragStart: () => {
+ setIsValidDrag(true);
+ setIsDragging(true);
+ },
+ onDragEnd: () => setIsDragging(false),
+ }}
+ >
+ <Show when={isDragging()}>
+ <FileDropOverlay valid={isValidDrag()}>
+ <Show when={!isValidDrag()}>
+ <div class="text-failure">[!] Invalid file type</div>
+ </Show>
+ <div>Drop any file here to add it to your workspace</div>
+ </FileDropOverlay>
+ </Show>
+ {props.children}
+ </div>
+ );
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
new file mode 100644
index 0000000000..ba75cd5bde
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
@@ -0,0 +1,812 @@
+import CheckIcon from '@icon/bold/check-bold.svg';
+import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
+import {
+ useGlobalBlockOrchestrator,
+ useGlobalNotificationSource,
+} from '@app/component/GlobalAppState';
+import { EntityRow, EntityRowProvider } from '@app/component/mobile/EntityRow';
+import {
+ makeMarkDoneAction,
+ useEntityActionHotkeys,
+} from '@app/component/next-soup/actions';
+import { useSoup } from '@app/component/next-soup/soup-context';
+import { SoupEntityContextMenu } from '@app/component/next-soup/soup-view/soup-entity-context-menu';
+import {
+ type SoupEntity,
+ type SoupRow,
+ SoupViewContextProvider,
+ useSoupView,
+} from '@app/component/next-soup/soup-view/soup-view-context';
+import { useSoupNavigationHotkeys } from './use-soup-navigation-hotkeys';
+import { useSoupViewHotkeys } from './use-soup-view-hotkeys';
+import { useElementItemCount } from '@app/component/next-soup/use-element-item-count';
+import { useSplitLayout } from '@app/component/split-layout/layout';
+import {
+ openEntityInNewTab,
+ openEntityInSplitFromUnifiedList,
+} from '@app/component/next-soup/utils';
+import {
+ PreviewPanel,
+ useMaybePreviewPanel,
+} from '@app/component/PreviewPanel';
+import { SplitPanelContext } from '@app/component/split-layout/context';
+import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
+import { LoadingBlock } from '@core/component/LoadingBlock';
+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { useTaskProperties } from '@core/component/Properties/hooks';
+import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
+import {
+ type EntityData,
+ isTaskEntity,
+ type Notification,
+ queryKeys,
+ unreadFilterFn,
+ useQueryClient,
+} from '@macro-entity';
+import {
+ createEffectOnEntityTypeNotification,
+ getMetadata,
+ isChannelMention,
+ isChannelMessageReply,
+ isChannelMessageSend,
+ tryToTypedNotification,
+ type UnifiedNotification,
+} from '@notifications';
+import { debounce } from '@solid-primitives/scheduled';
+import { cn } from '@ui/utils/classname';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ type JSX,
+ Match,
+ on,
+ onCleanup,
+ Show,
+ Switch,
+} from 'solid-js';
+import { type VirtualizerHandle, VList } from 'virtua/solid';
+import { SoupEntitySelectionToolbar } from './soup-entity-selection-toolbar';
+import { SoupToolbar } from './soup-toolbar';
+import { useUserId } from '@core/context/user';
+import {
+ type EntityClickHandler,
+ type EntityPointerDownHandler,
+ EntityWithEverything,
+} from '../../../../macro-entity/src/components/EntityWithEverything';
+import { CustomScrollbar } from '@core/component/CustomScrollbar';
+import { SoupViewFileDropzone } from '@app/component/next-soup/soup-view/soup-view-file-dropzone';
+import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';
+import { invalidateEntityNotifications } from '@queries/notification/user-notifications';
+import { soupKeys } from '@queries/soup/keys';
+import type { CacheSnapshot } from 'virtua/unstable_core';
+import { EmptyState } from '@app/component/next-soup/soup-view/empty-states';
+import { SoupChatInput } from '@app/component/SoupChatInput';
+import { ENABLE_UNIFIED_LIST_AI_INPUT } from '@core/constant/featureFlags';
+import { isMobile } from '@core/mobile/isMobile';
+
+const DEFAULT_ENTITY_HEIGHT = 40;
+
+const useSoupNotificationInvalidators = () => {
+ const notificationSource = useGlobalNotificationSource();
+ const entityQueryClient = useQueryClient();
+
+ createEffectOnEntityTypeNotification(
+ notificationSource,
+ 'channel',
+ (notification) => {
+ entityQueryClient.invalidateQueries({
+ queryKey: soupKeys._def,
+ });
+ invalidateEntityNotifications(notification.entity_id);
+ }
+ );
+
+ createEffectOnEntityTypeNotification(notificationSource, 'email', () => {
+ entityQueryClient.invalidateQueries({
+ // HACK: this needs to be improved, since we use a single query, per entity invalidations
+ // become a little more complicated.
+ queryKey: queryKeys.all.entity,
+ });
+ });
+
+ createEffectOnEntityTypeNotification(
+ notificationSource,
+ 'document',
+ (notification) => {
+ if (notification.notificationEventType === 'task_assigned') {
+ entityQueryClient.invalidateQueries({
+ queryKey: soupKeys._def,
+ });
+ invalidateEntityNotifications(notification.entity_id);
+ }
+ }
+ );
+};
+
+const cacheMap = new Map<
+ string,
+ {
+ virtualCache: CacheSnapshot;
+ scrollOffset: number;
+ }
+>();
+
+export const SoupView = () => {
+ const soup = useSoup();
+ const panel = useSplitPanelOrThrow();
+
+ useSoupNotificationInvalidators();
+
+ return (
+ <SplitPanelContext.Provider
+ value={{
+ ...panel,
+ halfSplitState: () =>
+ soup.previewEntity() ? { side: 'left', percentage: 30 } : undefined,
+ }}
+ >
+ <SoupViewContextProvider soup={soup}>
+ <div class="relative flex-grow min-h-0 flex max-sm:flex-col flex-row size-full">
+ <SoupToolbar />
+ <SoupViewFileDropzone>
+ <SoupViewList />
+ </SoupViewFileDropzone>
+ </div>
+ <Show when={ENABLE_UNIFIED_LIST_AI_INPUT && !isMobile()}>
+ <SoupChatInput />
+ </Show>
+ </SoupViewContextProvider>
+ </SplitPanelContext.Provider>
+ );
+};
+
+interface SoupViewListProps {
+ customScrollbarHidden?: boolean;
+}
+
+export const SoupViewList = (props: SoupViewListProps) => {
+ const panel = useSplitPanelOrThrow();
+ const { soup, source, rows: _rows, searchText } = useSoupView();
+ const { getSplitCount } = useSplitLayout();
+
+ const rows = createMemo(() => _rows());
+
+ const { isKeypressActive } = useIsKeyPressActive();
+
+ const [virtualizerHandle, setVirtualizerHandle] =
+ createSignal<VirtualizerHandle>();
+
+ const [soupViewRef, setSoupViewRef] = createSignal<HTMLElement | undefined>();
+
+ const [previewPanelRef, setPreviewPanelRef] = createSignal<
+ HTMLElement | undefined
+ >();
+
+ const focusFirstEntity = () => {
+ const next = soup.navigate.toFirst();
+
+ if (next) {
+ virtualizerHandle()?.scrollToIndex(next.index, { align: 'nearest' });
+ }
+ };
+
+ let initialLoad = true;
+
+ createEffect(
+ on(rows, () => {
+ if (!initialLoad || source.isLoading()) return;
+ focusFirstEntity();
+ initialLoad = false;
+ })
+ );
+
+ createEffect(
+ on(
+ () => [soup.filters.activeIds(), searchText()] as const,
+ () => {
+ focusFirstEntity();
+ }
+ )
+ );
+
+ const previewPanel = useMaybePreviewPanel();
+
+ // Auto focus the soup on mount except when it's in a preview panel
+ createEffect(() => {
+ if (previewPanel) return;
+
+ soupViewRef()?.focus();
+ });
+
+ const [attachHotkeys, soupViewScope] = useHotkeyDOMScope('soup-view');
+
+ const scopeId = createMemo(() => {
+ return previewPanel ? soupViewScope : panel.splitHotkeyScope;
+ });
+
+ // Register navigation hotkeys
+ useSoupNavigationHotkeys({
+ scopeId: scopeId(),
+ soup,
+ virtualizerHandle,
+ previewPanelRef,
+ });
+
+ // Register entity action hotkeys
+ useEntityActionHotkeys({
+ scopeId: scopeId(),
+ soup,
+ });
+
+ // Register soup view hotkeys (jump navigation, enter, escape, cmd+k, etc.)
+ useSoupViewHotkeys({
+ splitId: panel.handle.id,
+ scopeId: scopeId(),
+ domRef: soupViewRef,
+ soup,
+ splitHandle: panel.handle,
+ virtualizerHandle,
+ previewState: () => !!soup.previewEntity(),
+ getSplitCount,
+ });
+
+ // Create markDone action for swipe/click handlers
+ const userId = useUserId();
+ const notificationSource = useGlobalNotificationSource();
+
+ const markDoneAction = makeMarkDoneAction({
+ userId,
+ notificationSource: () => notificationSource,
+ });
+
+ const debouncedFetchMore = debounce(() => {
+ if (source.isFetchingNextPage() || !source.hasNextPage()) return;
+
+ source.fetchNextPage();
+ });
+
+ const orchestrator = useGlobalBlockOrchestrator();
+
+ const taskPropertiesStore = useTaskProperties(soup.data);
+
+ const onEntityClick: EntityClickHandler<EntityData> = async (args) => {
+ const { type, event, location } = args;
+
+ const entity = (
+ type === 'entity' ? args.entity : args.projectEntity
+ ) as EntityData;
+
+ if (event.metaKey || event.ctrlKey) {
+ openEntityInNewTab({ entity, location });
+ return;
+ }
+
+ if (soup.previewEntity() && type === 'entity') {
+ soup.focus.set(entity.id);
+ return;
+ }
+
+ await openEntityInSplitFromUnifiedList(entity, {
+ openInNewSplit: event.altKey,
+ location,
+ splitHandle: panel.handle,
+ });
+ };
+
+ const onEntityDoubleClick: EntityClickHandler<EntityData> = async (args) => {
+ const { entity, event, location } = args;
+
+ if (!soup.previewEntity()) {
+ return;
+ }
+
+ await openEntityInSplitFromUnifiedList(entity, {
+ openInNewSplit: event.altKey,
+ location,
+ splitHandle: panel.handle,
+ });
+ };
+
+ const onEntityPointerDown: EntityPointerDownHandler<EntityData> = async (
+ args
+ ) => {
+ const { type, location, event } = args;
+
+ const entity = (
+ type === 'entity' ? args.entity : args.projectEntity
+ ) as EntityData;
+
+ // middle mouse button pressed
+ if (event.button === 1 && event.pointerType === 'mouse') {
+ // TODO: current page should remain focused after opening new tab
+ openEntityInNewTab({ entity, location });
+ }
+ };
+
+ const onClickEntityAction = (entity: EntityData) => {
+ if (markDoneAction.canExecute(entity)) {
+ markDoneAction.executeWithSoup([entity], soup);
+ }
+ };
+
+ const blockOrchestrator = useGlobalBlockOrchestrator();
+ const gotoChannelNotification = async (notification: UnifiedNotification) => {
+ let message_id: string | undefined;
+ let thread_id: string | undefined;
+
+ if (isChannelMention(notification)) {
+ const metadata = getMetadata(notification);
+ message_id = metadata.messageId;
+ } else if (isChannelMessageReply(notification)) {
+ const metadata = getMetadata(notification);
+ message_id = metadata.messageId;
+ thread_id = metadata.threadId;
+ } else if (isChannelMessageSend(notification)) {
+ const metadata = getMetadata(notification);
+ message_id = metadata.messageId;
+ } else {
+ return;
+ }
+
+ const blockHandle = await blockOrchestrator.getBlockHandle(
+ notification.entity_id,
+ 'channel'
+ );
+ if (!blockHandle) return;
+
+ notificationSource.markAsRead(notification);
+
+ return blockHandle?.goToLocationFromParams({
+ [CHANNEL_PARAMS.message]: message_id,
+ [CHANNEL_PARAMS.thread]: thread_id,
+ });
+ };
+
+ const onClickNotification = ({
+ entity,
+ }: {
+ entity: SoupEntity & { notification: Notification };
+ }) => {
+ const notification = tryToTypedNotification(entity.notification);
+ if (!notification || entity.type !== 'channel') return;
+
+ gotoChannelNotification(notification);
+ };
+
+ let lastClickedEntityId = -1;
+
+ const getSelectionAnchorIndex = (params: {
+ entities: SoupRow[];
+ lastClickedIndex: number;
+ }) => {
+ // Try to grab the last clicked item and fall back on the highest currently
+ // selected index.
+ let anchorIndex = params.lastClickedIndex;
+ if (anchorIndex === -1) {
+ for (let i = 0; i < params.entities.length; i++) {
+ if (params.entities[i].isSelected()) {
+ anchorIndex = i;
+ }
+ }
+ }
+ return anchorIndex;
+ };
+
+ const handleMultiSelectChecked = (params: {
+ entity: EntityData;
+ entityIndex: number;
+ next: boolean;
+ shiftKey: boolean;
+ }) => {
+ if (!params.shiftKey) {
+ soup.selection.toggle(params.entity);
+ lastClickedEntityId = params.entityIndex;
+ return;
+ }
+
+ const entityList = rows();
+
+ const anchorIndex = getSelectionAnchorIndex({
+ entities: entityList,
+ lastClickedIndex: lastClickedEntityId,
+ });
+
+ if (anchorIndex === -1) {
+ soup.selection.toggle(params.entity);
+ lastClickedEntityId = params.entityIndex;
+ return;
+ }
+
+ const newEntitiesForSelection = [];
+ const sign = Math.sign(params.entityIndex - anchorIndex);
+
+ for (
+ let i = anchorIndex;
+ sign > 0 ? i <= params.entityIndex : i >= params.entityIndex;
+ i += sign
+ ) {
+ const entity = entityList[i];
+ if (!entity.isSelected()) {
+ newEntitiesForSelection.push(entity.original);
+ }
+ }
+
+ soup.selection.selectRange(newEntitiesForSelection);
+
+ lastClickedEntityId = params.entityIndex;
+ };
+
+ // reset last clicked on reset multi-selection.
+ createEffect(() => {
+ if (soup.selection.count() === 0) {
+ lastClickedEntityId = -1;
+ }
+ });
+
+ const [listRef, setListRef] = createSignal<HTMLDivElement>();
+
+ const viewportItemCount = useElementItemCount({
+ element: listRef,
+ itemHeight: DEFAULT_ENTITY_HEIGHT,
+ });
+
+ // Fetch more data if we filter out more items than the viewport can display
+ // because it's possible that the match exists on the server
+ createEffect(
+ on([rows, viewportItemCount], ([rows, viewportItemCount]) => {
+ if (rows.length >= viewportItemCount || source.isFetching()) return;
+ debouncedFetchMore();
+ })
+ );
+
+ onCleanup(() => debouncedFetchMore.clear());
+
+ const [entityContextMenuOpen, setEntityContextMenuOpen] = createSignal<
+ string | undefined
+ >(undefined);
+
+ const [localEntityListRef, setLocalEntityListRef] = createSignal<
+ HTMLDivElement | undefined
+ >();
+
+ const entityById = createMemo(
+ () => {
+ const list = rows() ?? [];
+ const map = new Map<string, SoupRow>();
+ for (const entity of list) {
+ map.set(entity.original.id, entity);
+ }
+ return map;
+ },
+ new Map<string, SoupRow>(),
+ {
+ equals(prev, next) {
+ return prev.size === next.size;
+ },
+ }
+ );
+
+ const getCacheKey = () => {
+ let key = `soup-view-${panel.handle.id}`;
+
+ if (previewPanel) {
+ key += '-preview';
+ }
+
+ return key;
+ };
+
+ onCleanup(() => {
+ const virtualHandle = virtualizerHandle();
+
+ if (!virtualHandle) return;
+
+ cacheMap.set(getCacheKey(), {
+ virtualCache: virtualHandle.cache,
+ scrollOffset: virtualHandle.scrollOffset,
+ });
+ });
+
+ const registerVirtualizerHandler = (
+ handle: VirtualizerHandle | undefined
+ ) => {
+ setVirtualizerHandle(handle);
+
+ const cached = cacheMap.get(getCacheKey());
+
+ if (!cached) return;
+
+ handle?.scrollTo(cached.scrollOffset);
+ };
+
+ return (
+ <div
+ class="size-full flex bracket-never"
+ ref={(el) => {
+ setSoupViewRef(el);
+ attachHotkeys(el);
+ }}
+ tabIndex={-1}
+ onFocusIn={(e) => {
+ e.stopPropagation();
+ }}
+ data-hotkey-scope={soupViewScope}
+ data-soup-view
+ data-soup-view-id={panel.handle.id + (previewPanel ? '-preview' : '')}
+ >
+ <div
+ ref={setListRef}
+ class="@container/uList size-full unified-list-root flex flex-col"
+ classList={{
+ 'border-r border-edge-muted': soup.previewEntity() !== undefined,
+ }}
+ >
+ <StaticMarkdownContext>
+ <Switch>
+ <Match when={source.isLoading()}>
+ <LoadingBlock />
+ </Match>
+ <Match when={!rows().length}>
+ <EmptyState search={!!searchText()} />
+ </Match>
+ <Match when={!source.isLoading() && rows().length}>
+ <EntityRowProvider
+ container={localEntityListRef}
+ canSwipeLeft={(entityId) => {
+ const entity = entityById().get(entityId);
+ if (!entity) return false;
+ return markDoneAction.canExecute(entity.original);
+ }}
+ onSwipeLeft={(entityId) => {
+ const entity = entityById().get(entityId);
+ if (!entity) return;
+ markDoneAction.executeWithSoup([entity.original], soup);
+ }}
+ setCollapseEntity={soup.collapseEntity.set}
+ >
+ <SoupList
+ cache={cacheMap.get(getCacheKey())?.virtualCache}
+ ref={setLocalEntityListRef}
+ virtualizerClass="scrollbar-hidden"
+ class="overflow-hidden flex min-w-0"
+ virtualizerRef={registerVirtualizerHandler}
+ onScrollBottom={debouncedFetchMore}
+ rows={rows()}
+ >
+ {(row, i) => {
+ const timestamp = () => {
+ const sort_ = soup.sort.active();
+ if (!sort_.length) return;
+
+ switch (sort_[0].id) {
+ case 'viewed_at':
+ return row.original.viewedAt;
+ case 'created_at':
+ return row.original.createdAt;
+ case 'updated_at':
+ return row.original.updatedAt;
+ }
+ };
+
+ const properties = () => {
+ if (isTaskEntity(row.original)) {
+ return taskPropertiesStore()[row.original.id] ?? [];
+ }
+ return undefined;
+ };
+
+ const shouldDisplayDoneButton = () => {
+ if (row.original.type === 'email') {
+ return !row.original.done;
+ }
+
+ return (row.original.notifications?.().length ?? 0) > 0;
+ };
+
+ return (
+ <EntityRow
+ entityId={row.original.id}
+ swipeLeftColor="bg-success"
+ swipeLeftRevealedComponent={
+ <CheckIcon class="size-8 text-panel" />
+ }
+ >
+ <SoupEntityContextMenu
+ entity={row.original}
+ entityTimestamp={timestamp()}
+ onOpenChange={(open) => {
+ setEntityContextMenuOpen(
+ open ? row.original.id : undefined
+ );
+ }}
+ >
+ <div
+ class="flex flex-col w-full min-w-0"
+ style={{
+ 'padding-left': `${row.depth * 8}px`,
+ }}
+ >
+ <Show
+ when={!row.isGrouped()}
+ fallback={
+ <div class="bg-accent flex gap-2 items-center px-2 py-1 text-input font-medium">
+ <button
+ type="button"
+ onClick={() => row.toggleExpanded()}
+ >
+ {row.isExpanded() ? 'Close' : 'Open'}
+ </button>
+ <span>{row.original.name}</span>
+ </div>
+ }
+ >
+ <EntityWithEverything
+ splitId={panel.handle.id}
+ entity={row.original}
+ timestamp={timestamp()}
+ properties={properties()}
+ searchActive={!!searchText()}
+ selected={{
+ active:
+ row.isFocused() ||
+ entityContextMenuOpen() === row.original.id,
+ // TODO: Update this to take into account when this is used within a nested
+ // view like the preview panel
+ muted:
+ row.isFocused() && !panel.isPanelActive(),
+ }}
+ highlighted={
+ panel.isPanelActive() && row.isFocused()
+ }
+ onMouseOver={() => {
+ if (
+ soup.previewEntity() ||
+ isKeypressActive()
+ )
+ return;
+ soup.focus.set(row.original.id);
+ }}
+ onFocusIn={() => {
+ if (soup.previewEntity()) return;
+ soup.focus.set(row.original.id);
+ }}
+ showUnrollNotifications={
+ soup.filters.isActive('signal') &&
+ !soup.filters.isActive('noise')
+ }
+ unreadIndicatorActive={unreadFilterFn(
+ row.original
+ )}
+ showDoneButton={shouldDisplayDoneButton()}
+ checked={row.isSelected()}
+ onChecked={(next, shiftKey) =>
+ handleMultiSelectChecked({
+ entity: row.original,
+ entityIndex: i(),
+ next,
+ shiftKey: shiftKey ?? false,
+ })
+ }
+ onClick={onEntityClick}
+ onDblClick={onEntityDoubleClick}
+ onPointerDown={onEntityPointerDown}
+ onClickRowAction={onClickEntityAction}
+ onClickNotification={onClickNotification}
+ />
+ </Show>
+ </div>
+ </SoupEntityContextMenu>
+ </EntityRow>
+ );
+ }}
+ </SoupList>
+ </EntityRowProvider>
+
+ <Show when={!props.customScrollbarHidden}>
+ <CustomScrollbar
+ scrollContainer={() => {
+ // Find the actual scroll container (VList creates its own scroll container)
+ const listEl = localEntityListRef();
+ if (!listEl) return undefined;
+ const scrollContainer = listEl.querySelector(
+ '[data-soup-list-container]'
+ ) as HTMLElement;
+ return scrollContainer || undefined;
+ }}
+ />
+ </Show>
+ </Match>
+ </Switch>
+ </StaticMarkdownContext>
+ </div>
+ <Show when={soup.selection.count() > 0}>
+ <SoupEntitySelectionToolbar
+ selected={soup.selection.selected()}
+ onClose={soup.selection.clear}
+ onClear={soup.selection.clear}
+ />
+ </Show>
+ <Show when={soup.previewEntity()}>
+ <PreviewPanel
+ ref={setPreviewPanelRef}
+ selectedEntity={soup.focus.item()}
+ orchestrator={orchestrator}
+ splitPanelContext={panel}
+ onFocusOut={() => {
+ soupViewRef()?.focus();
+ }}
+ />
+ </Show>
+ </div>
+ );
+};
+
+const DEFAULT_ITEM_SIZE = 10;
+const DEFAULT_OVERSCAN = 5;
+
+interface SoupListProps {
+ ref?: (el: HTMLElement) => void;
+ virtualizerRef?: (handle: VirtualizerHandle) => void;
+ class?: string;
+ virtualizerClass?: string;
+ itemSize?: number;
+ overscan?: number;
+ children: (row: SoupRow, index: Accessor<number>) => JSX.Element;
+ onScrollBottom?: VoidFunction;
+ scrollBottomOffset?: number;
+ rows: SoupRow[];
+ cache?: CacheSnapshot;
+}
+
+const SoupList = (props: SoupListProps) => {
+ const [virtualizerHandle, setVirtualizerHandle] =
+ createSignal<VirtualizerHandle>();
+
+ const itemSize = createMemo(() => props.itemSize ?? DEFAULT_ITEM_SIZE);
+ const overscan = createMemo(() => props.overscan ?? DEFAULT_OVERSCAN);
+
+ const handleScroll = (offset: number) => {
+ const handle = virtualizerHandle();
+
+ if (!handle) return;
+
+ if (
+ handle.scrollSize - handle.viewportSize - offset <=
+ (props.scrollBottomOffset ?? 100)
+ ) {
+ props.onScrollBottom?.();
+ }
+ };
+
+ const registerVirtualizerHandler = (
+ handle: VirtualizerHandle | undefined
+ ) => {
+ setVirtualizerHandle(handle);
+
+ if (handle) {
+ props.virtualizerRef?.(handle);
+ }
+ };
+
+ return (
+ <div
+ ref={props.ref}
+ class={cn('unified-table-body size-full relative', props.class)}
+ >
+ <VList
+ cache={props.cache}
+ ref={registerVirtualizerHandler}
+ class={props.virtualizerClass}
+ data={props.rows}
+ itemSize={itemSize()}
+ bufferSize={overscan() * itemSize()}
+ onScroll={handleScroll}
+ data-soup-list-container
+ >
+ {(row, i) => props.children(row, i)}
+ </VList>
+ </div>
+ );
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/use-soup-navigation-hotkeys.ts b/js/app/packages/app/component/next-soup/soup-view/use-soup-navigation-hotkeys.ts
new file mode 100644
index 0000000000..e674278a0a
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/use-soup-navigation-hotkeys.ts
@@ -0,0 +1,175 @@
+import { TOKENS } from '@core/hotkey/tokens';
+import type { VirtualizerHandle } from 'virtua/solid';
+import type { Accessor } from 'solid-js';
+import type { SoupState } from '../create-soup-state';
+import { useMaybePreviewPanel } from '@app/component/PreviewPanel';
+import { registerHotkey } from '@core/hotkey/hotkeys';
+
+type UseSoupNavigationHotkeysOptions = {
+ scopeId: string;
+ soup: SoupState;
+ virtualizerHandle: Accessor<VirtualizerHandle | undefined>;
+ previewPanelRef: Accessor<HTMLElement | undefined>;
+};
+
+export const useSoupNavigationHotkeys = (
+ options: UseSoupNavigationHotkeysOptions
+) => {
+ const { scopeId, soup, virtualizerHandle } = options;
+
+ const navigateAndSelectEntity = (offset: number) => {
+ const nextRow = soup.navigate.by(offset);
+ if (!nextRow) return true;
+ soup.selection.select(nextRow.item);
+ virtualizerHandle()?.scrollToIndex(nextRow.index, { align: 'nearest' });
+ return true;
+ };
+
+ const handleNavigationSelection = (offset: number) => {
+ const focusedEntity = soup.focus.item();
+ const nextIndex = soup.navigate.peekOffset(offset);
+
+ const selection = soup.selection;
+
+ const nextRow = nextIndex?.item;
+ if (!nextRow) return true;
+
+ if (!focusedEntity) {
+ navigateAndSelectEntity(offset);
+ return true;
+ }
+
+ if (selection.count() === 0) {
+ selection.toggle(focusedEntity);
+ return true;
+ }
+
+ if (
+ !selection.isSelected(focusedEntity.id) &&
+ !selection.isSelected(nextRow.id)
+ ) {
+ selection.toggle(focusedEntity);
+ navigateAndSelectEntity(offset);
+ return true;
+ }
+
+ if (selection.isSelected(nextRow.id)) {
+ selection.toggle(focusedEntity);
+ soup.navigate.by(offset);
+ return true;
+ }
+
+ navigateAndSelectEntity(offset);
+
+ return true;
+ };
+
+ // Navigate down - 'j', 'arrowdown'
+ registerHotkey({
+ hotkey: ['j', 'arrowdown'],
+ scopeId,
+ description: 'Down',
+ hotkeyToken: TOKENS.entity.step.end,
+ keyDownHandler: () => {
+ const next = soup.navigate.down();
+
+ if (!next) return true;
+
+ virtualizerHandle()?.scrollToIndex(next.index, { align: 'nearest' });
+
+ return true;
+ },
+ hide: true,
+ });
+
+ // Navigate up - 'k', 'arrowup'
+ registerHotkey({
+ hotkey: ['k', 'arrowup'],
+ scopeId,
+ hotkeyToken: TOKENS.entity.step.start,
+ description: 'Up',
+ keyDownHandler: () => {
+ const next = soup.navigate.up();
+
+ if (!next) return true;
+
+ virtualizerHandle()?.scrollToIndex(next.index, { align: 'nearest' });
+
+ return true;
+ },
+ hide: true,
+ });
+
+ // Select up - 'shift+arrowup', 'shift+k'
+ registerHotkey({
+ hotkey: ['shift+arrowup', 'shift+k'],
+ scopeId,
+ description: 'Select up',
+ hotkeyToken: TOKENS.entity.select.start,
+ keyDownHandler: () => {
+ return handleNavigationSelection(-1);
+ },
+ hide: true,
+ });
+
+ // Select down - 'shift+arrowdown', 'shift+j'
+ registerHotkey({
+ hotkey: ['shift+arrowdown', 'shift+j'],
+ scopeId,
+ description: 'Select down',
+ hotkeyToken: TOKENS.entity.select.end,
+ keyDownHandler: () => {
+ return handleNavigationSelection(1);
+ },
+ hide: true,
+ });
+
+ const previewPanel = useMaybePreviewPanel();
+
+ registerHotkey({
+ hotkey: ['h', 'arrowleft'],
+ scopeId,
+ description: 'Navigate to parent context',
+ hotkeyToken: TOKENS.unifiedList.navigation.parent,
+ keyDownHandler: () => {
+ if (!previewPanel) return false;
+
+ previewPanel.onFocusOut();
+
+ return true;
+ },
+ registrationType: 'add',
+ handlerPriority: 4,
+ hide: true,
+ });
+
+ registerHotkey({
+ hotkey: ['l', 'arrowright'],
+ scopeId,
+ description: 'Navigate to child context',
+ hotkeyToken: TOKENS.unifiedList.navigation.child,
+ keyDownHandler: () => {
+ const previewPanelContent = options.previewPanelRef();
+ // If there is no preview or the preview already contains focus, skip
+ if (
+ !previewPanelContent ||
+ previewPanelContent.contains(document.activeElement)
+ )
+ return false;
+
+ const previewPanelSoup = previewPanelContent?.querySelector(
+ 'div[data-soup-view]'
+ );
+
+ // If it doesn't contain soup, skip
+ if (!previewPanelSoup || !(previewPanelSoup instanceof HTMLElement))
+ return false;
+
+ previewPanelSoup.focus();
+ return true;
+ },
+ registrationType: 'add',
+ handlerPriority: 4,
+ hide: true,
+ });
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts b/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts
new file mode 100644
index 0000000000..8af74f290f
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts
@@ -0,0 +1,296 @@
+import {
+ konsoleOpen,
+ resetKonsoleMode,
+ setKonsoleMode,
+ toggleKonsoleVisibility,
+} from '@app/component/command/state';
+import {
+ resetCommandCategoryIndex,
+ searchCategories,
+ setCommandCategoryIndex,
+ setKonsoleContextInformation,
+} from '@app/component/command/KonsoleItem';
+import type { SplitHandle } from '@app/component/split-layout/layoutManager';
+import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';
+import { registerHotkey } from '@core/hotkey/hotkeys';
+import { TOKENS } from '@core/hotkey/tokens';
+import {
+ getHotkeyCommand,
+ getScopeElement,
+ runCommand,
+} from '@core/hotkey/utils';
+import { isSearchEntity } from '@macro-entity';
+import type { Accessor } from 'solid-js';
+import type { VirtualizerHandle } from 'virtua/solid';
+import type { SoupState } from '../create-soup-state';
+import { openEntityInSplitFromUnifiedList } from '@app/component/next-soup/utils';
+
+type UseSoupViewHotkeysOptions = {
+ splitId: string;
+ scopeId: string;
+ domRef: Accessor<HTMLElement | undefined>;
+ soup: SoupState;
+ splitHandle: SplitHandle;
+ virtualizerHandle: Accessor<VirtualizerHandle | undefined>;
+ previewState: Accessor<boolean>;
+ getSplitCount: () => number;
+};
+
+export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {
+ const {
+ scopeId,
+ soup,
+ splitHandle,
+ virtualizerHandle,
+ previewState,
+ getSplitCount,
+ } = options;
+
+ const splitIsUnifiedList = () => splitHandle.content().id === 'unified-list';
+
+ // home - Jump to top of list
+ registerHotkey({
+ hotkey: ['home'],
+ scopeId,
+ hotkeyToken: TOKENS.entity.jump.home,
+ description: 'Go to top of list',
+ keyDownHandler: () => {
+ const next = soup.navigate.toFirst();
+ if (next) {
+ virtualizerHandle()?.scrollToIndex(next.index, { align: 'nearest' });
+ }
+ return true;
+ },
+ hide: true,
+ });
+
+ // g g - Jump to top of list (vim-style command scope)
+ const { commandScopeId } = registerHotkey({
+ hotkey: ['g'],
+ scopeId,
+ description: 'Go to top of list',
+ keyDownHandler: () => true,
+ activateCommandScope: true,
+ hide: true,
+ });
+
+ registerHotkey({
+ hotkey: ['g'],
+ scopeId: commandScopeId,
+ description: 'Go to top of list',
+ keyDownHandler: () => {
+ const next = soup.navigate.toFirst();
+ if (next) {
+ virtualizerHandle()?.scrollToIndex(next.index, { align: 'nearest' });
+ }
+ return true;
+ },
+ });
+
+ // shift+g, end - Jump to bottom of list
+ registerHotkey({
+ hotkey: ['shift+g', 'end'],
+ scopeId,
+ hotkeyToken: TOKENS.entity.jump.end,
+ description: 'Go to bottom of list',
+ keyDownHandler: () => {
+ const next = soup.navigate.toLast();
+ if (next) {
+ virtualizerHandle()?.scrollToIndex(next.index, { align: 'nearest' });
+ }
+ return true;
+ },
+ hide: true,
+ });
+
+ // enter - Open entity in split
+ registerHotkey({
+ hotkey: ['enter'],
+ hotkeyToken: TOKENS.entity.open,
+ scopeId,
+ description: 'Open',
+ hide: true,
+ keyDownHandler: () => {
+ const entity = soup.focus.item();
+ if (!entity) return false;
+
+ const contentHitData = isSearchEntity(entity)
+ ? entity.search.contentHitData
+ : undefined;
+ // Only navigate to specific location if there's exactly one hit
+ const location =
+ contentHitData?.length === 1 ? contentHitData[0]?.location : undefined;
+
+ openEntityInSplitFromUnifiedList(entity, {
+ splitHandle,
+ location,
+ });
+ return true;
+ },
+ displayPriority: 4,
+ });
+
+ // cmd+enter - Focus preview block
+ registerHotkey({
+ hotkey: ['cmd+enter'],
+ scopeId,
+ description: 'Focus Preview',
+ keyDownHandler: () => {
+ const preview = previewState();
+ const entity = soup.focus.item();
+ if (!entity) return false;
+
+ if (preview) {
+ // focus inside preview block
+ const blockEl = document.getElementById(`block-${entity.id}`);
+ if (blockEl) {
+ // TODO: use state instead to determine when preview block can receive focus
+ blockEl.setAttribute('data-allow-focus-in-preview', '');
+
+ blockEl.focus();
+ const getEnterCommand = () => {
+ const currentActiveScope = activeScope();
+ if (!currentActiveScope) return undefined;
+ const activeScopeNode = hotkeyScopeTree.get(currentActiveScope);
+ if (!activeScopeNode) return undefined;
+ if (activeScopeNode?.type !== 'dom') return;
+ const dom = getScopeElement(currentActiveScope);
+ if (!dom) return undefined;
+ const closestBlockScope = dom.closest(`[id="block-${entity.id}"]`);
+ if (
+ !closestBlockScope ||
+ !(closestBlockScope instanceof HTMLElement)
+ )
+ return;
+ const scopeId = closestBlockScope.dataset.hotkeyScope;
+ if (!scopeId) return undefined;
+
+ return getHotkeyCommand(scopeId, 'enter');
+ };
+ const command = getEnterCommand();
+ if (command) {
+ runCommand(command);
+ }
+ }
+ return true;
+ }
+
+ openEntityInSplitFromUnifiedList(entity, {
+ splitHandle,
+ });
+ return true;
+ },
+ displayPriority: 4,
+ });
+
+ // x - Toggle select item
+ registerHotkey({
+ hotkey: ['x'],
+ scopeId,
+ description: 'Toggle select item',
+ keyDownHandler: () => {
+ const entity = soup.focus.item();
+ if (!entity) return false;
+ soup.selection.toggle(entity);
+ return true;
+ },
+ displayPriority: 10,
+ });
+
+ // cmd+k - Open command menu with selection context
+ registerHotkey({
+ scopeId,
+ description: () => {
+ return konsoleOpen() ? 'Close command menu' : 'Open command menu';
+ },
+ hotkey: 'cmd+k',
+ condition: () => !konsoleOpen(),
+ keyDownHandler: (e) => {
+ e?.preventDefault();
+ const multiSelectEntities = soup.selection.selected();
+
+ const hasSelection = multiSelectEntities.length > 0;
+
+ if (hasSelection) {
+ setKonsoleMode('SELECTION_MODIFICATION');
+ const selectionIndex = searchCategories.getCategoryIndex('Selection');
+
+ if (selectionIndex === undefined) return false;
+
+ setCommandCategoryIndex(selectionIndex);
+
+ searchCategories.showCategory('Selection');
+
+ setKonsoleContextInformation({
+ multiSelectEntities: multiSelectEntities.slice(),
+ });
+
+ toggleKonsoleVisibility();
+ return true;
+ }
+ searchCategories.hideCategory('Selection');
+ resetCommandCategoryIndex();
+ resetKonsoleMode();
+ return false;
+ },
+ displayPriority: 10,
+ hide: konsoleOpen,
+ runWithInputFocused: true,
+ });
+
+ // escape - Multi-purpose: Clear selection / Close spotlight / Close split / Go home
+ const clearMultiCondition = () => soup.selection.count() > 0;
+ const closeSpotlightCondition = () => splitHandle.isSpotLight();
+ const goHomeCondition = () => !splitIsUnifiedList();
+ const closeSplitCondition = () => splitIsUnifiedList() && getSplitCount() > 1;
+
+ const escapeDescription = () => {
+ if (clearMultiCondition()) {
+ return 'Clear multi selection';
+ }
+ if (closeSpotlightCondition()) {
+ return 'Close spotlight';
+ }
+ if (closeSplitCondition()) {
+ return 'Close split';
+ }
+ if (goHomeCondition()) {
+ return 'Go home';
+ }
+ return '';
+ };
+
+ registerHotkey({
+ hotkey: ['escape'],
+ scopeId,
+ description: escapeDescription,
+ condition: () =>
+ clearMultiCondition() ||
+ closeSpotlightCondition() ||
+ closeSplitCondition() ||
+ goHomeCondition(),
+ keyDownHandler: () => {
+ if (clearMultiCondition()) {
+ const length = soup.selection.count();
+ soup.selection.clear();
+ return length > 1;
+ }
+ if (closeSpotlightCondition()) {
+ splitHandle.toggleSpotlight();
+ return true;
+ }
+ if (closeSplitCondition()) {
+ splitHandle.close();
+ return true;
+ }
+ if (goHomeCondition()) {
+ splitHandle.replace({
+ next: { type: 'component', id: 'unified-list' },
+ referredFrom: 'unified-list',
+ });
+ return true;
+ }
+ return false;
+ },
+ });
+};
diff --git a/js/app/packages/app/component/next-soup/use-element-item-count.ts b/js/app/packages/app/component/next-soup/use-element-item-count.ts
new file mode 100644
index 0000000000..2615a2daf1
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/use-element-item-count.ts
@@ -0,0 +1,46 @@
+import {
+ createSignal,
+ createEffect,
+ onCleanup,
+ type Accessor,
+ createMemo,
+} from 'solid-js';
+
+const DEFAULT_HEIGHT = 600;
+
+interface Options {
+ element: Accessor<HTMLElement | undefined>;
+ itemHeight: number;
+}
+
+export const useElementItemCount = (options: Options) => {
+ let containerSizeObserver: ResizeObserver | null = null;
+
+ const [containerHeight, setContainerHeight] = createSignal(DEFAULT_HEIGHT);
+
+ createEffect(() => {
+ containerSizeObserver?.disconnect();
+ const ref = options.element();
+ if (!ref) return;
+
+ // Initialize with current size of the container using this component
+ const initial =
+ ref.clientHeight || ref.getBoundingClientRect().height || DEFAULT_HEIGHT;
+ setContainerHeight((prevHeight) => Math.max(prevHeight, initial));
+
+ containerSizeObserver = new ResizeObserver((entries) => {
+ const last = entries.pop();
+ const nextHeight = last?.contentRect?.height ?? ref.clientHeight;
+ if (Number.isFinite(nextHeight) && nextHeight > 0)
+ setContainerHeight((prevHeight) => Math.max(prevHeight, nextHeight));
+ });
+ containerSizeObserver.observe(ref);
+ onCleanup(() => containerSizeObserver?.disconnect());
+ });
+
+ const viewportItemCount = createMemo(() =>
+ Math.max(1, Math.ceil(containerHeight() / options.itemHeight))
+ );
+
+ return viewportItemCount;
+};
diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.ts
new file mode 100644
index 0000000000..e85b1e0ae8
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/utils.ts
@@ -0,0 +1,585 @@
+import type { BlockOrchestrator } from '@core/orchestrator';
+import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
+import { URL_PARAMS as EMAIL_PARAMS } from '@block-email/constants';
+import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';
+import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';
+import type {
+ SplitContent,
+ SplitHandle,
+} from '@app/component/split-layout/layoutManager';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import { waitForFrames } from '@core/util/sleep';
+import {
+ type DocumentEntity,
+ type EntityData,
+ isSearchEntity,
+ queryKeys,
+ type SearchLocation,
+ type TaskEntityWithProperties,
+ type WithSearch,
+} from '@macro-entity';
+import { queryClient } from '@queries/client';
+import { emailClient } from '@service-email/client';
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@core/component/Properties/constants';
+
+const mergeSearchEntities = <T extends EntityData>(
+ first: WithSearch<T>,
+ second: WithSearch<T>
+): WithSearch<T> => {
+ const serviceEntity = first.search.source === 'service' ? first : second;
+ const localEntity = first.search.source === 'local' ? first : second;
+ const hasLocal =
+ first.search.source === 'local' || second.search.source === 'local';
+
+ // NOTE: we that the longer name highlight is more relevant since it will contain a macro highlight tag
+ let nameHighlight;
+ if (serviceEntity.search.nameHighlight && localEntity.search.nameHighlight) {
+ nameHighlight =
+ serviceEntity.search.nameHighlight.length >=
+ localEntity.search.nameHighlight.length
+ ? serviceEntity.search.nameHighlight
+ : localEntity.search.nameHighlight;
+ } else {
+ nameHighlight =
+ serviceEntity.search.nameHighlight || localEntity.search.nameHighlight;
+ }
+
+ return {
+ ...serviceEntity,
+ search: {
+ ...serviceEntity.search,
+ source: hasLocal ? 'local' : 'service',
+ nameHighlight,
+ contentHitData: serviceEntity.search.contentHitData?.length
+ ? serviceEntity.search.contentHitData
+ : localEntity.search.contentHitData,
+ },
+ };
+};
+
+/**
+ * Deduplicates entities by id, preferring entities with search data from 'service' source
+ * over 'local' source, and using latest timestamp as a tiebreaker.
+ * When preferring service results, merges local nameHighlight if service doesn't have one.
+ */
+export const deduplicateEntities = <T extends EntityData>(
+ entities: T[]
+): T[] => {
+ const entityMap = new Map<string, T>();
+
+ for (const entity of entities) {
+ const existing = entityMap.get(entity.id);
+
+ if (!existing) {
+ entityMap.set(entity.id, entity);
+ continue;
+ }
+
+ const existingHasSearch = isSearchEntity(existing);
+ const newHasSearch = isSearchEntity(entity);
+
+ // Prefer entities with search data
+ if (newHasSearch && !existingHasSearch) {
+ entityMap.set(entity.id, entity);
+ continue;
+ }
+
+ // If both have search data, prefer 'service' over 'local'
+ if (existingHasSearch && newHasSearch) {
+ const existingSource = existing.search.source;
+ const newSource = entity.search.source;
+
+ if (
+ (newSource === 'service' && existingSource === 'local') ||
+ (existingSource === 'service' && newSource === 'local')
+ ) {
+ // Merge service and local search data
+ entityMap.set(entity.id, mergeSearchEntities(entity, existing));
+ continue;
+ }
+
+ // If both are the same source, keep the one with latest timestamp
+ if (isNewerEntity(entity, existing)) {
+ entityMap.set(entity.id, entity);
+ }
+ continue;
+ }
+
+ // If neither has search, keep the one with latest timestamp
+ if (!existingHasSearch && !newHasSearch) {
+ if (isNewerEntity(entity, existing)) {
+ entityMap.set(entity.id, entity);
+ }
+ }
+ // Otherwise keep existing (it has search and new doesn't)
+ }
+
+ return Array.from(entityMap.values());
+};
+
+/**
+ * Gets the timestamp of an entity (updatedAt or createdAt)
+ */
+const getEntityTimestamp = (entity: EntityData): number => {
+ return entity.updatedAt ?? entity.createdAt ?? 0;
+};
+
+/**
+ * Returns true if the new entity should replace the existing one based on timestamp. If the timestamp is the same, prefer to use the newer entity to handle optimistic updates
+ */
+export const isNewerEntity = (
+ newEntity: EntityData,
+ existing: EntityData
+): boolean => {
+ return getEntityTimestamp(newEntity) >= getEntityTimestamp(existing);
+};
+
+export const openEntityInNewTab = ({
+ entity,
+ location,
+}: {
+ entity: EntityData;
+ location?: SearchLocation;
+}) => {
+ // Build URL for the entity
+ let entityPath: string;
+ if (entity.type === 'document') {
+ const { fileType, subType } = entity;
+ const blockName = fileTypeToBlockName(subType?.type ?? fileType);
+ entityPath = `/app/${blockName}/${entity.id}`;
+ } else {
+ entityPath = `/app/${entity.type}/${entity.id}`;
+ }
+
+ // Add location params if present
+ const entityUrl = new URL(entityPath, window.location.origin);
+ if (location) {
+ switch (location.type) {
+ case 'channel':
+ if (location.messageId) {
+ entityUrl.searchParams.set('channel_message_id', location.messageId);
+ }
+ if (location.threadId) {
+ entityUrl.searchParams.set('thread', location.threadId);
+ }
+ break;
+ case 'email':
+ if (location.messageId) {
+ entityUrl.searchParams.set('email_message_id', location.messageId);
+ }
+
+ break;
+ case 'md':
+ if (location.nodeId) {
+ entityUrl.searchParams.set('node_id', location.nodeId);
+ }
+ break;
+ case 'pdf':
+ if (location.searchPage !== undefined) {
+ entityUrl.searchParams.set(
+ 'search_page',
+ location.searchPage.toString()
+ );
+ }
+ if (location.searchRawQuery) {
+ entityUrl.searchParams.set(
+ 'search_raw_query',
+ location.searchRawQuery
+ );
+ }
+ if (location.highlightTerms) {
+ entityUrl.searchParams.set(
+ 'search_highlight_terms',
+ JSON.stringify(location.highlightTerms)
+ );
+ }
+ if (location.searchSnippet) {
+ entityUrl.searchParams.set('search_snippet', location.searchSnippet);
+ }
+ break;
+ }
+ }
+
+ window.open(entityUrl.toString(), '_blank', 'noopener');
+};
+
+/**
+ * Restores DOM focus to an entity row in the soup view after a modal action completes.
+ * This is necessary because the hotkey system is focus-based, and modals steal
+ * focus away from the soup view. Without restoring DOM focus, scoped hotkeys
+ * like 'escape' won't work.
+ *
+ * @param entityId - Optional entity ID to focus on. If not provided, focuses the first entity in the list.
+ * @param inPreview - Whether to check for the soup view in a preview panel
+ */
+export const restoreSoupFocus = async (
+ entityId?: string,
+ inPreview = false
+): Promise<void> => {
+ // Get the active split's soup view DOM reference
+ const activeSplitId = globalSplitManager()?.activeSplitId();
+ if (!activeSplitId) return;
+
+ let domRef = document.querySelector(`[data-soup-view-id="${activeSplitId}"]`);
+
+ if (inPreview) {
+ domRef = document.querySelector(
+ `[data-soup-view-id="${activeSplitId}-preview"]`
+ );
+ }
+
+ if (!domRef) return;
+
+ // Wait for DOM to update after modal closes
+ await waitForFrames(2);
+
+ // Find and focus the entity element
+ if (entityId) {
+ const entityEl = domRef.querySelector(`[data-entity-id="${entityId}"]`);
+ if (entityEl instanceof HTMLElement) {
+ entityEl.focus();
+ return;
+ }
+ }
+
+ // Fallback: focus the first entity in the list if no specific entity to focus
+ const firstEntityEl = domRef.querySelector('[data-entity-id]');
+ if (firstEntityEl instanceof HTMLElement) {
+ firstEntityEl.focus();
+ }
+};
+
+export interface OpenEntityOptions {
+ openInNewSplit?: boolean;
+ location?: SearchLocation;
+ splitHandle: SplitHandle;
+}
+
+/**
+ * Opens an entity in a split, handling navigation to specific locations within the entity.
+ * Supports both regular entities (channel, email, etc.) and document entities.
+ *
+ * @param entity - The entity to open
+ * @param options - Configuration options including whether to open in new split, location, and split handle
+ */
+export const openEntityInSplitFromUnifiedList = async (
+ entity: EntityData,
+ options: OpenEntityOptions
+): Promise<void> => {
+ const { openInNewSplit, location, splitHandle } = options;
+
+ // Get dependencies internally
+ const splitManager = globalSplitManager();
+ if (!splitManager) {
+ console.error('No split manager found');
+ return;
+ }
+
+ const blockOrchestrator = splitManager.getOrchestrator();
+
+ // Create split functions
+ const insertSplit = (content: SplitContent) => {
+ return splitManager.createNewSplit({
+ content,
+ activate: true,
+ referredFrom: 'unified-list',
+ });
+ };
+
+ const replaceOrInsertSplit = (content: SplitContent) => {
+ const existingSplit = splitManager.getSplitByContent(
+ content.type,
+ content.id
+ );
+ if (existingSplit) {
+ return existingSplit;
+ }
+
+ splitHandle.replace({ next: content, referredFrom: 'unified-list' });
+ return splitHandle;
+ };
+
+ // Handle document entities separately
+ if (entity.type === 'document') {
+ return openDocument(entity as DocumentEntity, {
+ openInNewSplit,
+ blockOrchestrator,
+ location,
+ insertSplit,
+ replaceOrInsertSplit,
+ });
+ }
+
+ // Build params for channel entities with location
+ const params =
+ entity.type === 'channel' && location?.type === 'channel'
+ ? {
+ [CHANNEL_PARAMS.message]: location.messageId,
+ [CHANNEL_PARAMS.thread]: location.threadId,
+ }
+ : undefined;
+
+ // Create or replace split based on openInNewSplit option
+ const handle = openInNewSplit
+ ? insertSplit({ type: entity.type, id: entity.id, params })
+ : replaceOrInsertSplit({ type: entity.type, id: entity.id, params });
+
+ handle?.activate();
+
+ // Navigate to specific location if provided
+ if (!location) return;
+
+ await navigateToLocation(entity.id, location, blockOrchestrator);
+};
+
+/**
+ * Opens a document entity in a split.
+ */
+async function openDocument(
+ entity: DocumentEntity,
+ options: {
+ openInNewSplit?: boolean;
+ blockOrchestrator: BlockOrchestrator;
+ location?: SearchLocation;
+ insertSplit: (content: SplitContent) => SplitHandle | undefined;
+ replaceOrInsertSplit: (content: SplitContent) => SplitHandle | undefined;
+ }
+): Promise<void> {
+ const {
+ openInNewSplit,
+ blockOrchestrator,
+ location,
+ insertSplit,
+ replaceOrInsertSplit,
+ } = options;
+
+ const { id, fileType, subType } = entity;
+ const blockName = fileTypeToBlockName(subType?.type ?? fileType);
+
+ // Create or replace split based on openInNewSplit option
+ const handle = openInNewSplit
+ ? insertSplit({ type: blockName, id })
+ : replaceOrInsertSplit({ type: blockName, id });
+
+ handle?.activate();
+
+ // Navigate to specific location if provided
+ if (!location) return;
+
+ await navigateToLocation(id, location, blockOrchestrator);
+}
+
+/**
+ * Navigates to a specific location within a block.
+ */
+async function navigateToLocation(
+ entityId: string,
+ location: SearchLocation,
+ blockOrchestrator: BlockOrchestrator
+): Promise<void> {
+ const blockHandle = await blockOrchestrator.getBlockHandle(entityId);
+ if (!blockHandle) return;
+
+ switch (location.type) {
+ case 'channel': {
+ // NOTE: this is handled by the channel block params but this can be used to re-flash an open channel
+ await blockHandle.goToLocationFromParams({
+ [CHANNEL_PARAMS.thread]: location.threadId,
+ [CHANNEL_PARAMS.message]: location.messageId,
+ });
+ break;
+ }
+ case 'email': {
+ await blockHandle.goToLocationFromParams({
+ [EMAIL_PARAMS.messageId]: location.messageId,
+ });
+ break;
+ }
+ case 'md': {
+ await blockHandle.goToLocationFromParams({
+ [MD_PARAMS.nodeId]: location.nodeId,
+ });
+ break;
+ }
+ case 'pdf': {
+ await blockHandle.goToLocationFromParams({
+ [PDF_PARAMS.searchPage]: location.searchPage.toString(),
+ [PDF_PARAMS.searchRawQuery]: location.searchRawQuery,
+ [PDF_PARAMS.searchHighlightTerms]: JSON.stringify(
+ location.highlightTerms
+ ),
+ [PDF_PARAMS.searchSnippet]: location.searchSnippet,
+ });
+ break;
+ }
+ }
+}
+
+export async function archiveEmail(
+ id: string,
+ options: { isDone: boolean; optimisticallyExclude?: boolean }
+) {
+ await Promise.all([
+ queryClient.cancelQueries({ queryKey: queryKeys.all.email }),
+ queryClient.cancelQueries({ queryKey: queryKeys.all.dss }),
+ ]);
+
+ const previousEmail = queryClient.getQueriesData<{
+ pages: { items: EntityData[] }[];
+ }>({
+ queryKey: queryKeys.all.email,
+ });
+ const previousEmailThreadItemFromDss = queryClient.getQueriesData<{
+ pages: { items: EntityData[] }[];
+ }>({
+ queryKey: queryKeys.all.dss,
+ });
+
+ const applyOptimistic = (data?: {
+ pages: { items: (EntityData | { data: EntityData })[] }[];
+ }) => {
+ if (!data) return data;
+
+ return {
+ ...data,
+ pages: data.pages.map((page) => ({
+ ...page,
+ items: options.optimisticallyExclude
+ ? page.items.filter((item) => {
+ if ('data' in item) {
+ return item.data.id !== id;
+ }
+ return item.id !== id;
+ })
+ : page.items.map((item) => {
+ if ('data' in item) {
+ return item.data.id === id
+ ? {
+ ...item,
+ data: {
+ ...item.data,
+ inboxVisible: false,
+ },
+ }
+ : item;
+ }
+ return item.id === id
+ ? {
+ ...item,
+ inboxVisible: false,
+ }
+ : item;
+ }),
+ })),
+ };
+ };
+
+ for (const [key, data] of [
+ ...previousEmailThreadItemFromDss,
+ ...previousEmail,
+ ]) {
+ queryClient.setQueryData(key, applyOptimistic(data));
+ }
+
+ try {
+ // server mutation
+ await emailClient.flagArchived({ value: !options.isDone, id });
+ } catch (_err) {
+ // rollback on error
+ for (const [key, data] of previousEmail) {
+ queryClient.setQueryData(key, data);
+ }
+ for (const [key, data] of previousEmailThreadItemFromDss) {
+ queryClient.setQueryData(key, data);
+ }
+ } finally {
+ // revalidate
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.all.dss }),
+ ]);
+ }
+}
+
+/**
+ * extracts assignee user ids from task properties.
+ */
+export const getTaskAssigneeIds = (
+ entity: TaskEntityWithProperties
+): string[] => {
+ const properties = entity.properties;
+ if (!properties) return [];
+ const assigneesProperty = properties.find(
+ (p) => p.definition.id === SYSTEM_PROPERTY_IDS.ASSIGNEES
+ );
+ if (!assigneesProperty?.value) return [];
+
+ const value = assigneesProperty.value;
+ if (value.type === 'EntityReference' && Array.isArray(value.value)) {
+ return value.value
+ .filter((ref) => ref.entity_type === 'USER')
+ .map((ref) => ref.entity_id);
+ }
+
+ return [];
+};
+
+/**
+ * gets the status option id from task properties.
+ */
+export const getTaskStatusOptionId = (
+ entity: TaskEntityWithProperties
+): string | undefined => {
+ const properties = entity.properties;
+ if (!properties) return undefined;
+
+ const statusProperty = properties.find(
+ (p) => p.definition.id === SYSTEM_PROPERTY_IDS.STATUS
+ );
+ if (!statusProperty?.value) return undefined;
+
+ const value = statusProperty.value;
+ if (
+ value.type === 'SelectOption' &&
+ 'value' in value &&
+ Array.isArray(value.value)
+ ) {
+ return value.value[0];
+ }
+
+ return undefined;
+};
+
+/**
+ * checks if a task is in a "closed" state (completed or canceled).
+ */
+export const isTaskClosed = (entity: TaskEntityWithProperties): boolean => {
+ if (entity.subType?.is_completed === true) {
+ return true;
+ }
+ const statusOptionId = getTaskStatusOptionId(entity);
+ if (
+ statusOptionId === PROPERTY_OPTION_IDS.STATUS.COMPLETED ||
+ statusOptionId === PROPERTY_OPTION_IDS.STATUS.CANCELED
+ ) {
+ return true;
+ }
+ return false;
+};
+
+/**
+ * checks if the current user is assigned to the task.
+ */
+export const isCurrentUserAssigned = (
+ entity: TaskEntityWithProperties,
+ currentUserId: string | undefined
+): boolean => {
+ if (!currentUserId) return false;
+ const assigneeIds = getTaskAssigneeIds(entity);
+ if (assigneeIds.length === 0) return true;
+ return assigneeIds.includes(currentUserId);
+};
diff --git a/js/app/packages/app/component/settings/Inbox.tsx b/js/app/packages/app/component/settings/Inbox.tsx
index 685a5b5459..f47418c7d2 100644
--- a/js/app/packages/app/component/settings/Inbox.tsx
+++ b/js/app/packages/app/component/settings/Inbox.tsx
@@ -1,13 +1,10 @@
+import { DEPRIORITY_LABEL_SIGNAL_TOGGLES, PRIORITY_LABEL_SIGNAL_TOGGLES } from '@app/component/next-soup/filters/signal-configs';
import { ToggleSwitch } from '@core/component/FormControls/ToggleSwitch';
import { For } from 'solid-js';
-import {
- DEPRIORITY_LABEL_SIGNAL_TOGGLES,
- PRIORITY_LABEL_SIGNAL_TOGGLES,
-} from '../soupFilters';
export function Inbox() {
- const prioritySignals = [...PRIORITY_LABEL_SIGNAL_TOGGLES];
- const deprioritySignals = [...DEPRIORITY_LABEL_SIGNAL_TOGGLES];
+ const prioritySignals = PRIORITY_LABEL_SIGNAL_TOGGLES;
+ const deprioritySignals = DEPRIORITY_LABEL_SIGNAL_TOGGLES;
return (
<div class="font-mono flex flex-col gap-3 text-sm p-2">
diff --git a/js/app/packages/app/component/soupContextHelpers.ts b/js/app/packages/app/component/soupContextHelpers.ts
deleted file mode 100644
index 2c93a08df0..0000000000
--- a/js/app/packages/app/component/soupContextHelpers.ts
+++ /dev/null
@@ -1,175 +0,0 @@
-import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
-import { URL_PARAMS as EMAIL_PARAMS } from '@block-email/constants';
-import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';
-import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';
-import { fileTypeToBlockName } from '@core/constant/allBlocks';
-import type { BlockOrchestrator } from '@core/orchestrator';
-import type { DocumentEntity, EntityData, SearchLocation } from '@macro-entity';
-import { globalSplitManager } from '../signal/splitLayout';
-import type { SplitContent, SplitHandle } from './split-layout/layoutManager';
-
-export interface OpenEntityOptions {
- openInNewSplit?: boolean;
- location?: SearchLocation;
- splitHandle: SplitHandle;
-}
-
-/**
- * Opens an entity in a split, handling navigation to specific locations within the entity.
- * Supports both regular entities (channel, email, etc.) and document entities.
- *
- * @param entity - The entity to open
- * @param options - Configuration options including whether to open in new split, location, and split handle
- */
-export const openEntityInSplitFromUnifiedList = async (
- entity: EntityData,
- options: OpenEntityOptions
-): Promise<void> => {
- const { openInNewSplit, location, splitHandle } = options;
-
- // Get dependencies internally
- const splitManager = globalSplitManager();
- if (!splitManager) {
- console.error('No split manager found');
- return;
- }
-
- const blockOrchestrator = splitManager.getOrchestrator();
-
- // Create split functions
- const insertSplit = (content: SplitContent) => {
- return splitManager.createNewSplit({
- content,
- activate: true,
- referredFrom: 'unified-list',
- });
- };
-
- const replaceOrInsertSplit = (content: SplitContent) => {
- const existingSplit = splitManager.getSplitByContent(
- content.type,
- content.id
- );
- if (existingSplit) {
- return existingSplit;
- }
-
- splitHandle.replace({ next: content, referredFrom: 'unified-list' });
- return splitHandle;
- };
-
- // Handle document entities separately
- if (entity.type === 'document') {
- return openDocument(entity as DocumentEntity, {
- openInNewSplit,
- blockOrchestrator,
- location,
- insertSplit,
- replaceOrInsertSplit,
- });
- }
-
- // Build params for channel entities with location
- const params =
- entity.type === 'channel' && location?.type === 'channel'
- ? {
- [CHANNEL_PARAMS.message]: location.messageId,
- [CHANNEL_PARAMS.thread]: location.threadId,
- }
- : undefined;
-
- // Create or replace split based on openInNewSplit option
- const handle = openInNewSplit
- ? insertSplit({ type: entity.type, id: entity.id, params })
- : replaceOrInsertSplit({ type: entity.type, id: entity.id, params });
-
- handle?.activate();
-
- // Navigate to specific location if provided
- if (!location) return;
-
- await navigateToLocation(entity.id, location, blockOrchestrator);
-};
-
-/**
- * Opens a document entity in a split.
- */
-async function openDocument(
- entity: DocumentEntity,
- options: {
- openInNewSplit?: boolean;
- blockOrchestrator: BlockOrchestrator;
- location?: SearchLocation;
- insertSplit: (content: SplitContent) => SplitHandle | undefined;
- replaceOrInsertSplit: (content: SplitContent) => SplitHandle | undefined;
- }
-): Promise<void> {
- const {
- openInNewSplit,
- blockOrchestrator,
- location,
- insertSplit,
- replaceOrInsertSplit,
- } = options;
-
- const { id, fileType, subType } = entity;
- const blockName = fileTypeToBlockName(subType?.type ?? fileType);
-
- // Create or replace split based on openInNewSplit option
- const handle = openInNewSplit
- ? insertSplit({ type: blockName, id })
- : replaceOrInsertSplit({ type: blockName, id });
-
- handle?.activate();
-
- // Navigate to specific location if provided
- if (!location) return;
-
- await navigateToLocation(id, location, blockOrchestrator);
-}
-
-/**
- * Navigates to a specific location within a block.
- */
-async function navigateToLocation(
- entityId: string,
- location: SearchLocation,
- blockOrchestrator: BlockOrchestrator
-): Promise<void> {
- const blockHandle = await blockOrchestrator.getBlockHandle(entityId);
- if (!blockHandle) return;
-
- switch (location.type) {
- case 'channel': {
- // NOTE: this is handled by the channel block params but this can be used to re-flash an open channel
- await blockHandle.goToLocationFromParams({
- [CHANNEL_PARAMS.thread]: location.threadId,
- [CHANNEL_PARAMS.message]: location.messageId,
- });
- break;
- }
- case 'email': {
- await blockHandle.goToLocationFromParams({
- [EMAIL_PARAMS.messageId]: location.messageId,
- });
- break;
- }
- case 'md': {
- await blockHandle.goToLocationFromParams({
- [MD_PARAMS.nodeId]: location.nodeId,
- });
- break;
- }
- case 'pdf': {
- await blockHandle.goToLocationFromParams({
- [PDF_PARAMS.searchPage]: location.searchPage.toString(),
- [PDF_PARAMS.searchRawQuery]: location.searchRawQuery,
- [PDF_PARAMS.searchHighlightTerms]: JSON.stringify(
- location.highlightTerms
- ),
- [PDF_PARAMS.searchSnippet]: location.searchSnippet,
- });
- break;
- }
- }
-}
diff --git a/js/app/packages/app/component/soupFilters.ts b/js/app/packages/app/component/soupFilters.ts
deleted file mode 100644
index 3e38e59203..0000000000
--- a/js/app/packages/app/component/soupFilters.ts
+++ /dev/null
@@ -1,229 +0,0 @@
-import { useUserId } from '@core/context/user';
-import {
- type EntityData,
- isTaskEntity,
- type TaskEntityWithProperties,
-} from '@macro-entity';
-import { makePersisted } from '@solid-primitives/storage';
-import { createMemo, createSignal } from 'solid-js';
-import { isSignalTask } from './Soup/utils/filterHelpers';
-import type { ClientFilter } from './ViewConfig';
-
-type SignalConfig<T extends string> = {
- key: T;
- label: string;
- defaultValue: boolean;
-};
-
-type SignalToggle<T extends string> = SignalConfig<T> & {
- enabled: () => boolean;
- setEnabled: (value: boolean) => void;
-};
-
-const makeToggle = (storageKey: string, defaultValue: boolean) =>
- makePersisted(createSignal(defaultValue), { name: storageKey });
-
-const toStorageKey = (scope: string, key: string) =>
- `signalFilter_${scope}_${key.toLowerCase().replace(/[^a-z0-9]+/g, '_')}`;
-
-const createSignalToggles = <T extends string>(
- scope: string,
- configs: SignalConfig<T>[]
-): SignalToggle<T>[] =>
- configs.map((config) => {
- const [enabled, setEnabled] = makeToggle(
- toStorageKey(scope, config.key),
- config.defaultValue
- );
- return { ...config, enabled, setEnabled };
- });
-
-const PRIORITY_LABEL_SIGNAL_CONFIGS: SignalConfig<string>[] = [
- {
- key: 'CATEGORY_PERSONAL',
- label: 'Personal',
- defaultValue: true,
- },
- {
- key: 'SENT',
- label: 'Sent',
- defaultValue: true,
- },
- {
- key: 'IMPORTANT',
- label: 'Important',
- defaultValue: false,
- },
-];
-
-const DEPRIORITY_LABEL_SIGNAL_CONFIGS: SignalConfig<string>[] = [
- {
- key: 'CATEGORY_UPDATES',
- label: 'Updates',
- defaultValue: true,
- },
- {
- key: 'CATEGORY_PROMOTIONS',
- label: 'Promotions',
- defaultValue: true,
- },
- {
- key: 'CATEGORY_SOCIAL',
- label: 'Social',
- defaultValue: true,
- },
- {
- key: 'CATEGORY_FORUMS',
- label: 'Forums',
- defaultValue: true,
- },
-];
-
-export const PRIORITY_LABEL_SIGNAL_TOGGLES = createSignalToggles(
- 'priority_label',
- PRIORITY_LABEL_SIGNAL_CONFIGS
-);
-export const DEPRIORITY_LABEL_SIGNAL_TOGGLES = createSignalToggles(
- 'depriority_label',
- DEPRIORITY_LABEL_SIGNAL_CONFIGS
-);
-
-// Computed Sets based on persisted settings
-const SIGNAL_PRIORITY_LABELS = createMemo(
- () =>
- new Set(
- PRIORITY_LABEL_SIGNAL_TOGGLES.filter(({ enabled }) => enabled()).map(
- ({ key }) => key
- )
- )
-);
-
-const SIGNAL_DEPRIORITY_LABELS = createMemo(
- () =>
- new Set(
- DEPRIORITY_LABEL_SIGNAL_TOGGLES.filter(({ enabled }) => enabled()).map(
- ({ key }) => key
- )
- )
-);
-
-const getLabelTokens = (
- labels?: Array<{ id?: string; providerLabelId?: string; name?: string }>
-): string[] => {
- if (!labels?.length) return [];
-
- const tokens: string[] = [];
- for (const label of labels) {
- if (label.id) tokens.push(label.id);
- if (label.providerLabelId) tokens.push(label.providerLabelId);
- if (label.name) tokens.push(label.name);
- }
-
- return tokens.map((token) => token.toUpperCase());
-};
-
-const getEmailSignalInfo = (entity: Extract<EntityData, { type: 'email' }>) => {
- const labelTokens = getLabelTokens(entity.labels);
- const priorityLabels = SIGNAL_PRIORITY_LABELS();
- const depriorityLabels = SIGNAL_DEPRIORITY_LABELS();
-
- const hasPriorityLabel = labelTokens.some((label) =>
- priorityLabels.has(label)
- );
- const hasDeprioritizingLabel = labelTokens.some((label) =>
- depriorityLabels.has(label)
- );
-
- return {
- hasPriority: hasPriorityLabel,
- hasDepriority: hasDeprioritizingLabel,
- };
-};
-
-const isSignalEmail = (entity: Extract<EntityData, { type: 'email' }>) => {
- const { hasPriority, hasDepriority } = getEmailSignalInfo(entity);
- // Signal = has priority indicators OR has no depriority indicators
- return hasPriority || !hasDepriority;
-};
-
-const isNoiseEmail = (entity: Extract<EntityData, { type: 'email' }>) => {
- const { hasPriority, hasDepriority } = getEmailSignalInfo(entity);
- // Noise = has depriority indicators AND no priority indicators
- return hasDepriority && !hasPriority;
-};
-
-const hasRecentlyViewed = (entity: EntityData) => {
- if (!entity.viewedAt) return false;
-
- const now = Date.now();
- const viewedAt = new Date(entity.viewedAt);
-
- const diff = now - viewedAt.getTime();
-
- const seconds = diff / 1000;
-
- const oneDayOfSeconds = 3600 * 24;
-
- return seconds < oneDayOfSeconds;
-};
-
-const getCurrentUserId = () => {
- try {
- return useUserId()();
- } catch {
- return undefined;
- }
-};
-
-export const signalFilter: ClientFilter = {
- id: 'signal',
- predicate: (entity, _ctx) => {
- switch (entity.type) {
- case 'channel': {
- return true;
- }
- case 'chat': {
- return hasRecentlyViewed(entity);
- }
- case 'document': {
- if (isTaskEntity(entity)) {
- const currentUserId = getCurrentUserId();
- return isSignalTask(
- entity as TaskEntityWithProperties,
- currentUserId
- );
- }
- return hasRecentlyViewed(entity);
- }
- case 'email': {
- return isSignalEmail(entity) || entity.isDraft;
- }
- case 'project': {
- return hasRecentlyViewed(entity);
- }
- }
- },
-};
-
-export const noiseFilter: ClientFilter = {
- id: 'noise',
- predicate: (entity, ctx) => {
- return !signalFilter.predicate(entity, ctx);
- },
-};
-
-/**
- * Explicit noise filter - only returns true for items with explicit noise indicators.
- * Currently only emails can be "explicit noise" (those with depriority labels/metadata).
- * Non-email items are never considered explicit noise (they're neutral).
- */
-export const explicitNoiseFilter: ClientFilter = {
- id: 'explicitNoise',
- predicate: (entity, _ctx) => {
- if (entity.type === 'email') {
- return isNoiseEmail(entity);
- }
- // Non-email items are never explicit noise
- return false;
- },
-};
diff --git a/js/app/packages/app/component/split-layout/SplitLayout.tsx b/js/app/packages/app/component/split-layout/SplitLayout.tsx
index 4357269683..c91046df86 100644
--- a/js/app/packages/app/component/split-layout/SplitLayout.tsx
+++ b/js/app/packages/app/component/split-layout/SplitLayout.tsx
@@ -19,10 +19,6 @@ import {
Suspense,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
-import {
- createNavigationEntityListShortcut,
- createSoupContext,
-} from '../SoupContext';
import { PopoverSplitRenderer } from './components/PopoverSplitRenderer';
import { SplitContainer } from './components/SplitContainer';
import { SplitLayoutContext, SplitPanelContext } from './context';
@@ -39,6 +35,8 @@ import {
} from './layoutManager';
import { decodePairs } from './layoutUtils';
import { registerSplitHotkeys } from './registerSplitHotkeys';
+import { SoupContextProvider } from '@app/component/next-soup/soup-context';
+import { createSoupState } from '@app/component/next-soup/create-soup-state';
type SplitLayoutContainerProps = {
pairs: string[];
@@ -356,11 +354,6 @@ function SplitPanel(props: SplitPanelProps) {
const panelSize = createElementSize(panelRef);
const [contentOffsetTop, setContentOffsetTop] = createSignal(0);
- const soupContext = createSoupContext({
- splitId: props.split.id,
- domRef: panelRef,
- });
-
const [previewState, setPreviewState] = createSignal(false);
const splitLayoutHelpers = useSplitLayout();
@@ -373,7 +366,6 @@ function SplitPanel(props: SplitPanelProps) {
goBack: () => props.handle.goBack(),
canGoForward: () => props.handle.canGoForward(),
goForward: () => props.handle.goForward(),
- setSelectedView: (view) => soupContext.setSelectedView(view),
replaceSplit: splitLayoutHelpers.replaceSplit,
splitName: () => props.handle.displayName(),
getSplitCount: () => splitLayoutHelpers.getSplitCount(),
@@ -383,49 +375,38 @@ function SplitPanel(props: SplitPanelProps) {
},
});
- const splitName = createMemo(() => {
- const { type, id } = props.split.content;
- if (type === 'component') return id;
-
- return type;
- });
-
- createNavigationEntityListShortcut({
- splitName,
- splitHandle: props.handle,
- splitHotkeyScope,
- soupContext,
- previewState: [previewState, setPreviewState],
- getSplitCount: () => splitLayoutHelpers.getSplitCount(),
+ const nextSoup = createSoupState({
+ initialFilters: ['explicit-noise'],
});
return (
- <SplitPanelContext.Provider
- value={{
- handle: props.handle,
- splitHotkeyScope,
- soupContext,
- isPanelActive: () => props.active,
- panelRef,
- panelSize,
- layoutRefs: {},
- contentOffsetTop,
- setContentOffsetTop,
- previewState: [previewState, setPreviewState],
- }}
- >
- <SplitContainer
- id={props.split.id}
- ref={(ref) => {
- setPanelRef(ref);
- props.setPanelRef(ref);
- attachHotKeys(ref);
+ <SoupContextProvider soup={nextSoup}>
+ <SplitPanelContext.Provider
+ value={{
+ handle: props.handle,
+ splitHotkeyScope,
+ isPanelActive: () => props.active,
+ panelRef,
+ panelSize,
+ layoutRefs: {},
+ contentOffsetTop,
+ setContentOffsetTop,
+ previewState: [previewState, setPreviewState],
}}
>
- <Suspense>
- <Dynamic component={props.split.mount.element} />
- </Suspense>
- </SplitContainer>
- </SplitPanelContext.Provider>
+ <SplitContainer
+ id={props.split.id}
+ ref={(ref) => {
+ setPanelRef(ref);
+ props.setPanelRef(ref);
+ attachHotKeys(ref);
+ }}
+ >
+ <Suspense>
+ <Dynamic component={props.split.mount.element} />
+ </Suspense>
+ </SplitContainer>
+ </SplitPanelContext.Provider>
+ </SoupContextProvider>
);
}
diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsx
index 293bc26f4f..9a4173a636 100644
--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx
+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx
@@ -5,9 +5,9 @@ import { DEV_MODE_ENV, LOCAL_ONLY } from '@core/constant/featureFlags';
import type { ViewId } from '@core/types/view';
import { type JSXElement, lazy } from 'solid-js';
import { EmailCompose } from '../../../block-email/component/Compose';
-import { Soup } from '../Soup';
import { SettingsPanel } from '../settings/Settings';
import NotificationRoute from '@notifications/components/NotificationRoute';
+import { SoupView } from '@app/component/next-soup/soup-view/soup-view';
export type ComponentFactory = (params?: Record<string, any>) => JSXElement;
@@ -55,7 +55,7 @@ export function resolveComponent(
};
}
-registerComponent('unified-list', () => <Soup />, { viewId: 'signal' });
+registerComponent('unified-list', () => <SoupView />);
registerComponent('loading', () => <LoadingBlock />);
registerComponent('channel-compose', () => <ChannelCompose />);
registerComponent('email-compose', () => <EmailCompose />);
diff --git a/js/app/packages/app/component/split-layout/components/PopoverSplitRenderer.tsx b/js/app/packages/app/component/split-layout/components/PopoverSplitRenderer.tsx
index 01a352f066..dff6617c1f 100644
--- a/js/app/packages/app/component/split-layout/components/PopoverSplitRenderer.tsx
+++ b/js/app/packages/app/component/split-layout/components/PopoverSplitRenderer.tsx
@@ -5,7 +5,6 @@ import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { Dialog } from '@kobalte/core/dialog';
import { createMemo, createSignal, For, Show } from 'solid-js';
import { Dynamic } from 'solid-js/web';
-import { createStubSoupContext } from '../../SoupContext';
import { SplitPanelContext, type SplitPanelContextType } from '../context';
import type {
PopoverSplitOptions,
@@ -14,6 +13,7 @@ import type {
SplitId,
SplitMount,
} from '../layoutManager';
+import { SoupContextProvider } from '@app/component/next-soup/soup-context';
false && clickOutside;
@@ -91,7 +91,6 @@ function PopoverSplitModal(props: {
handle: stubHandle,
splitHotkeyScope: `popover-${props.popover.id}`,
isPanelActive: () => true,
- soupContext: createStubSoupContext(),
panelRef,
panelSize: { width: null, height: null },
contentOffsetTop,
@@ -139,9 +138,11 @@ function PopoverSplitModal(props: {
<Dialog.Content class="portal-scope">
<ClippedPanel active tl ref={setPanelRef}>
<SplitPanelContext.Provider value={stubPanelContext}>
- <Show when={props.popover.mount}>
- <Dynamic component={props.popover.mount.element} />
- </Show>
+ <SoupContextProvider>
+ <Show when={props.popover.mount}>
+ <Dynamic component={props.popover.mount.element} />
+ </Show>
+ </SoupContextProvider>
</SplitPanelContext.Provider>
</ClippedPanel>
</Dialog.Content>
diff --git a/js/app/packages/app/component/split-layout/context.ts b/js/app/packages/app/component/split-layout/context.ts
index aae728d358..628a020ffa 100644
--- a/js/app/packages/app/component/split-layout/context.ts
+++ b/js/app/packages/app/component/split-layout/context.ts
@@ -5,7 +5,6 @@ import {
type Setter,
type Signal,
} from 'solid-js';
-import type { SoupContext } from '../SoupContext';
import type { SplitHandle, SplitManager } from './layoutManager';
export const SplitLayoutContext = createContext<{
@@ -20,7 +19,6 @@ export type HalfSplitState = {
export type SplitPanelContextType = {
handle: SplitHandle;
splitHotkeyScope: string;
- soupContext: SoupContext;
isPanelActive: Accessor<boolean>;
panelRef: Accessor<HTMLElement | null>;
panelSize: NullableSize;
diff --git a/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts b/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts
index daf12e35dd..e589671844 100644
--- a/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts
+++ b/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts
@@ -4,7 +4,6 @@ import {
useBigChat,
useToggleRightPanel,
} from '@core/signal/layout';
-import type { ViewId } from '@core/types/view';
import { registerHotkey } from 'core/hotkey/hotkeys';
import { globalSplitManager } from '../../signal/splitLayout';
import { fireMacroJump } from '../MacroJump';
@@ -21,7 +20,6 @@ export function registerSplitHotkeys(args: {
goBack: () => void;
canGoForward: () => boolean;
goForward: () => void;
- setSelectedView: (view: ViewId) => void;
replaceSplit: (options: {
content: SplitContent;
referredFrom?: ReferredFrom;
@@ -38,10 +36,10 @@ export function registerSplitHotkeys(args: {
goBack,
canGoForward,
goForward,
- replaceSplit,
splitName,
getSplitCount,
isNotUnifiedList,
+ replaceSplit,
} = args;
const splitManager = globalSplitManager();
registerHotkey({
@@ -81,23 +79,6 @@ export function registerSplitHotkeys(args: {
runWithInputFocused: true,
});
- registerHotkey({
- scopeId: splitHotkeyScope,
- hotkey: 'h',
- description: 'Go home',
- condition: isNotUnifiedList,
- keyDownHandler: () => {
- replaceSplit({
- content: { type: 'component', id: 'unified-list' },
- referredFrom: 'hotkey',
- });
- return true;
- },
- registrationType: 'add',
- hotkeyToken: TOKENS.split.goHome,
- displayPriority: 8,
- });
-
// History back/forward - legacy bindings.
registerHotkey({
scopeId: splitHotkeyScope,
@@ -159,7 +140,7 @@ export function registerSplitHotkeys(args: {
registerHotkey({
hotkeyToken: TOKENS.window.focusSplitRight,
- hotkey: ['arrowright'],
+ hotkey: ['l', 'arrowright'],
scopeId: splitHotkeyScope,
description: 'Focus split right',
condition: () => getSplitCount() > 1,
@@ -172,7 +153,7 @@ export function registerSplitHotkeys(args: {
registerHotkey({
hotkeyToken: TOKENS.window.focusSplitLeft,
- hotkey: ['arrowleft'],
+ hotkey: ['h', 'arrowleft'],
scopeId: splitHotkeyScope,
description: 'Focus split left',
condition: () => getSplitCount() > 1,
diff --git a/js/app/packages/app/component/useNavigatedFromJK.ts b/js/app/packages/app/component/useNavigatedFromJK.ts
index bb1be711e3..883157280f 100644
--- a/js/app/packages/app/component/useNavigatedFromJK.ts
+++ b/js/app/packages/app/component/useNavigatedFromJK.ts
@@ -1,16 +1,12 @@
import { lastExecutedCommand } from '@core/hotkey/state';
import { TOKENS } from '@core/hotkey/tokens';
import { createMemo } from 'solid-js';
-import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
+import { useSoup } from '@app/component/next-soup/soup-context';
export function useNavigatedFromJK() {
- const {
- soupContext: {
- entitiesSignal: [_entities],
- },
- } = useSplitPanelOrThrow();
+ const soup = useSoup();
const navigatedFromJK = createMemo(() => {
- const entities = _entities();
+ const entities = soup.data();
if (!entities) return false;
return (
entities.length > 0 &&
diff --git a/js/app/packages/app/util/handleFileUpload.ts b/js/app/packages/app/util/handleFileUpload.ts
index 7a68294665..ed91dd948c 100644
--- a/js/app/packages/app/util/handleFileUpload.ts
+++ b/js/app/packages/app/util/handleFileUpload.ts
@@ -1,10 +1,8 @@
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { type UploadInput, uploadFiles } from '@core/util/upload';
-import {
- queryKeys,
- useQueryClient as useEntityQueryClient,
-} from '@macro-entity';
+import { useQueryClient as useEntityQueryClient } from '@macro-entity';
import { useSplitLayout } from '../component/split-layout/layout';
+import { soupKeys } from '@queries/soup/keys';
export function useHandleFileUpload({
projectId,
@@ -38,7 +36,7 @@ export function useHandleFileUpload({
);
if (uploaded.length > 0) {
entityQueryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryKey: soupKeys.items._def,
});
}
}
@@ -51,7 +49,7 @@ export function useHandleFileUpload({
// this refreshes the uploaded data into the soup list
entityQueryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryKey: soupKeys.items._def,
});
const upload = successfulUploads[0];
diff --git a/js/app/packages/app/vitest.config.ts b/js/app/packages/app/vitest.config.ts
index ee531c19ed..28bf532346 100644
--- a/js/app/packages/app/vitest.config.ts
+++ b/js/app/packages/app/vitest.config.ts
@@ -1,3 +1,4 @@
+import solidPlugin from 'vite-plugin-solid';
import tsconfigPaths from 'vite-tsconfig-paths';
import { defineConfig } from 'vitest/config';
@@ -6,6 +7,7 @@ export default defineConfig({
tsconfigPaths({
root: '../',
}),
+ solidPlugin(),
],
test: {
environment: 'jsdom',
diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsx
index b33e25641e..52f2ed78a1 100644
--- a/js/app/packages/block-email/component/EmailContext.tsx
+++ b/js/app/packages/block-email/component/EmailContext.tsx
@@ -1,5 +1,6 @@
import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
-import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
+import { makeMarkDoneAction } from '@app/component/next-soup/actions';
+import { useMaybeSoup } from '@app/component/next-soup/soup-context';
import { URL_PARAMS } from '@block-email/constants';
import { convertContactInfoToEmailRecipient } from '@block-email/util/recipientConversion';
import {
@@ -8,6 +9,7 @@ import {
Permissions,
} from '@core/component/SharePermissions';
import { toast } from '@core/component/Toast/Toast';
+import { useUserId } from '@core/context/user';
import { createMethodRegistration } from '@core/orchestrator';
import { blockHandleSignal } from '@core/signal/load';
import {
@@ -312,12 +314,14 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
return Array.from(optionsMap.values());
};
- const {
- soupContext: {
- entitiesSignal: [entities],
- actionRegistry,
- },
- } = useSplitPanelOrThrow();
+ const soup = useMaybeSoup();
+
+ const userId = useUserId();
+
+ const markAsDoneAction = makeMarkDoneAction({
+ notificationSource: () => notificationSource,
+ userId,
+ });
const archiveMutation = useArchiveThreadMutation({
onError: () => {
@@ -337,12 +341,14 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
if (!props) return false;
- const selectedEntity = entities()?.find(
- (entity) => entity.id === thread.db_id
- );
+ const selectedEntity = soup?.items.get(thread.db_id);
if (selectedEntity) {
- actionRegistry.execute('mark_as_done', selectedEntity);
+ if (soup) {
+ markAsDoneAction.executeWithSoup([selectedEntity], soup);
+ } else {
+ markAsDoneAction.execute([selectedEntity]);
+ }
} else {
archiveMutation.mutate({
threadId: thread.db_id,
diff --git a/js/app/packages/block-email/component/MessageContainer.tsx b/js/app/packages/block-email/component/MessageContainer.tsx
index 5c6134511b..e8b9eb3b98 100644
--- a/js/app/packages/block-email/component/MessageContainer.tsx
+++ b/js/app/packages/block-email/component/MessageContainer.tsx
@@ -13,7 +13,8 @@ import { VideoPreview } from '@core/component/VideoPreview';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { tryMacroId, useDisplayName } from '@core/user';
import { isErr } from '@core/util/maybeResult';
-import { queryKeys, useQueryClient } from '@macro-entity';
+import { useQueryClient } from '@queries/client';
+import { soupKeys } from '@queries/soup/keys';
import { logger } from '@observability';
import { emailClient } from '@service-email/client';
import type {
@@ -139,7 +140,7 @@ export function MessageContainer(props: MessageContainerProps) {
});
const { replaceOrInsertSplit } = useSplitLayout();
- const entityQueryClient = useQueryClient();
+ const queryClient = useQueryClient();
const onClickAttachment = async (
attachment: Attachment,
@@ -177,8 +178,8 @@ export function MessageContainer(props: MessageContainerProps) {
);
}
- entityQueryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryClient.invalidateQueries({
+ queryKey: soupKeys.items._def,
});
const blockName = fileType ? fileTypeToBlockName(fileType) : 'unknown';
diff --git a/js/app/packages/block-email/signal/threadNavigation.ts b/js/app/packages/block-email/signal/threadNavigation.ts
deleted file mode 100644
index dc867e7242..0000000000
--- a/js/app/packages/block-email/signal/threadNavigation.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
-import { useBlockId } from '@core/block';
-import { createMemo } from 'solid-js';
-import { useSplitLayout } from '../../app/component/split-layout/layout';
-
-export function useThreadNavigation() {
- const {
- soupContext: {
- entitiesSignal: [entities],
- selectedView,
- setViewDataStore,
- },
- } = useSplitPanelOrThrow();
- const { replaceOrInsertSplit } = useSplitLayout();
- const blockId = useBlockId();
-
- const emailsEntities = createMemo(
- () => entities()?.filter(({ type }) => type === 'email') ?? []
- );
-
- const currentIndex = createMemo(() =>
- emailsEntities().findIndex((m) => m.id === blockId)
- );
-
- const navigateThread = (direction: 'up' | 'down'): boolean => {
- const currIndex = currentIndex();
- if (currIndex < 0) return false;
-
- if (
- (currIndex === 0 && direction === 'up') ||
- (currIndex === emailsEntities().length - 1 && direction === 'down')
- ) {
- return false;
- }
-
- const newIndex = currIndex + (direction === 'down' ? 1 : -1);
- const email = emailsEntities().at(newIndex);
-
- if (!email) return false;
-
- setViewDataStore(selectedView(), 'selectedEntity', email);
- replaceOrInsertSplit({ type: 'email', id: email.id });
-
- return true;
- };
-
- return {
- currentIndex,
- emailsEntities,
- navigateThread,
- };
-}
diff --git a/js/app/packages/block-md/component/ComposeTask.tsx b/js/app/packages/block-md/component/ComposeTask.tsx
index 98ef785d9f..83f90ab043 100644
--- a/js/app/packages/block-md/component/ComposeTask.tsx
+++ b/js/app/packages/block-md/component/ComposeTask.tsx
@@ -37,10 +37,8 @@ import { buildSimpleEntityUrl } from '@core/util/url';
import LinkIcon from '@icon/regular/link-simple.svg';
import TrashIcon from '@icon/regular/trash.svg';
import XIcon from '@icon/regular/x.svg';
-import {
- queryKeys,
- useQueryClient as useEntityQueryClient,
-} from '@macro-entity';
+import { useQueryClient } from '@queries/client';
+import { soupKeys } from '@queries/soup/keys';
import { useUpsertToHistoryMutation } from '@queries/history/history';
import { useUserId } from '@core/context/user';
import { propertiesServiceClient } from '@service-properties/client';
@@ -110,10 +108,10 @@ async function createTaskWithProperties(
}
);
- // Invalidate queries to refresh DSS and add to history
- const entityQueryClient = useEntityQueryClient();
- entityQueryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ // Invalidate queries to refresh soup items and add to history
+ const queryClient = useQueryClient();
+ queryClient.invalidateQueries({
+ queryKey: soupKeys.items._def,
});
// Upsert the new task to history
diff --git a/js/app/packages/block-project/component/Block.tsx b/js/app/packages/block-project/component/Block.tsx
index f4ab2b52fd..4d1e9745cc 100644
--- a/js/app/packages/block-project/component/Block.tsx
+++ b/js/app/packages/block-project/component/Block.tsx
@@ -1,9 +1,10 @@
import { useGlobalBlockOrchestrator } from '@app/component/GlobalAppState';
-import { PreviewPanel } from '@app/component/PreviewPanel';
+import {
+ PreviewPanel,
+ useMaybePreviewPanel,
+} from '@app/component/PreviewPanel';
import { SplitPanelContext } from '@app/component/split-layout/context';
import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
-import { UnifiedListView } from '@app/component/UnifiedListView';
-import { PROJECT_VIEWCONFIG_BASE } from '@app/component/ViewConfig';
import { getIsSpecialProject } from '@block-project/isSpecial';
import { useBlockId } from '@core/block';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
@@ -18,35 +19,35 @@ import {
type UploadInput,
uploadFiles,
} from '@core/util/upload';
+import { useQueryClient } from '@queries/client';
+import { soupKeys } from '@queries/soup/keys';
import { throttledDependent } from '@core/util/debounce';
-import {
- queryKeys,
- useQueryClient as useEntityQueryClient,
-} from '@macro-entity';
import { refetchResources } from '@service-storage/util/refetchResources';
import { toast } from 'core/component/Toast/Toast';
-import {
- type Component,
- createMemo,
- createRenderEffect,
- createSignal,
- onCleanup,
- Show,
- untrack,
-} from 'solid-js';
-import { projectBlockDataSignal } from '../signal/projectBlockData';
+import { type Component, createSignal, Show } from 'solid-js';
import { TopBar } from './TopBar';
+import {
+ SoupContextProvider,
+ useSoup,
+} from '@app/component/next-soup/soup-context';
+import {
+ createSoupState,
+ type SoupState,
+} from '@app/component/next-soup/create-soup-state';
+import { SoupViewContextProvider } from '@app/component/next-soup/soup-view/soup-view-context';
+import { SoupViewList } from '@app/component/next-soup/soup-view/soup-view';
// HACK: prevent lint error on custom directive
false && fileFolderDrop;
false && fileSelector;
+const PROJECT_ENTITY_TYPES = ['document', 'agent', 'file', 'task'];
+
const Block: Component = () => {
const [isDragging, setIsDragging] = createSignal(false);
const projectId = useBlockId();
const isSpecialProject = getIsSpecialProject(projectId);
- const name = () => projectBlockDataSignal()?.projectMetadata.name;
- const entityQueryClient = useEntityQueryClient();
+ const queryClient = useQueryClient();
const handleFileUpload = async (files: UploadInput[]) => {
if (files.length === 0) return;
@@ -67,8 +68,8 @@ const Block: Component = () => {
// show documents that were immediately uploaded
const successfulUploads = uploads.filter((result) => !result.pending);
if (successfulUploads.length > 0) {
- entityQueryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryClient.invalidateQueries({
+ queryKey: soupKeys.items._def,
});
refetchResources();
}
@@ -80,8 +81,8 @@ const Block: Component = () => {
.map((result) => result.projectId);
if (pendingFolderUploads.length > 0) {
await Promise.all(pendingFolderUploads);
- entityQueryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryClient.invalidateQueries({
+ queryKey: soupKeys.items._def,
});
refetchResources();
}
@@ -92,20 +93,18 @@ const Block: Component = () => {
};
const orchestrator = useGlobalBlockOrchestrator();
+
+ const soup = useSoup();
+
+ const previewPanel = useMaybePreviewPanel();
+
const splitPanelContext = useSplitPanelOrThrow();
- const {
- selectedView,
- setSelectedView,
- setViewDataStore,
- isRenderedFromPreview,
- viewsDataStore: viewsData,
- } = splitPanelContext.soupContext;
+
const [preview, setPreview] = splitPanelContext.previewState;
- const view = createMemo(() => viewsData[selectedView()]);
- const selectedEntity = () => view().selectedEntity;
+ const selectedEntity = () => soup.focus.item();
const throttledSelectedEntity = throttledDependent(selectedEntity, 150);
- if (!isRenderedFromPreview) {
+ if (!previewPanel) {
registerHotkey({
hotkey: ['space'],
scopeId: splitPanelContext.splitHotkeyScope,
@@ -119,26 +118,16 @@ const Block: Component = () => {
});
}
- createRenderEffect(() => {
- const previousView = untrack(selectedView);
-
- setSelectedView(projectId);
-
- setViewDataStore(projectId, {
- ...PROJECT_VIEWCONFIG_BASE,
- id: projectId,
- view: name() ?? 'folder',
- multiSelectEntities: [],
- filters: {
- ...PROJECT_VIEWCONFIG_BASE.filters,
- projectFilter: projectId,
+ const projectSoup = createSoupState({
+ initialFilters: ['project-content'],
+ filterConfigs: [
+ {
+ id: 'project-content',
+ label: 'Project content',
+ predicate: (entity) => PROJECT_ENTITY_TYPES.includes(entity.type),
},
- });
-
- onCleanup(() => {
- setSelectedView(previousView);
- setViewDataStore(projectId, undefined);
- });
+ ],
+ filterGroups: [],
});
return (
@@ -158,7 +147,12 @@ const Block: Component = () => {
<FileDropOverlay>Upload to this folder</FileDropOverlay>
</Show>
<TopBar />
- <Show when={ENABLE_PROJECT_VIEW_PREVIEW} fallback={<UnifiedListView />}>
+ <Show
+ when={ENABLE_PROJECT_VIEW_PREVIEW}
+ fallback={
+ <ProjectEntityList projectId={projectId} soup={projectSoup} />
+ }
+ >
<div class="flex size-full">
<SplitPanelContext.Provider
value={{
@@ -167,7 +161,7 @@ const Block: Component = () => {
preview() ? { side: 'left', percentage: 30 } : undefined,
}}
>
- <UnifiedListView hideToolbar={isRenderedFromPreview} />
+ <ProjectEntityList projectId={projectId} soup={projectSoup} />
</SplitPanelContext.Provider>
<Show when={preview()}>
<PreviewPanel
@@ -183,4 +177,27 @@ const Block: Component = () => {
);
};
+const ProjectEntityList = (props: { projectId: string; soup: SoupState }) => {
+ return (
+ <SoupContextProvider soup={props.soup}>
+ <SoupViewContextProvider
+ soup={props.soup}
+ queryFilters={{
+ chat_filters: {
+ project_ids: [props.projectId],
+ },
+ project_filters: {
+ project_ids: [props.projectId],
+ },
+ document_filters: {
+ project_ids: [props.projectId],
+ },
+ }}
+ >
+ <SoupViewList customScrollbarHidden={true} />
+ </SoupViewContextProvider>
+ </SoupContextProvider>
+ );
+};
+
export default Block;
diff --git a/js/app/packages/core/component/EntityIcon.tsx b/js/app/packages/core/component/EntityIcon.tsx
index 2ae24c2856..d8c977b453 100644
--- a/js/app/packages/core/component/EntityIcon.tsx
+++ b/js/app/packages/core/component/EntityIcon.tsx
@@ -394,7 +394,7 @@ export function CustomEntityIcon(
}
export function getIconConfig(
- targetType: EntityWithValidIcon | FileType | string
+ targetType: EntityWithValidIcon | FileType | (string & {})
) {
const key = validateEntity(targetType);
const config = { ...ENTITY_ICON_CONFIGS[key] };
diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
index 1ec3a82f53..5a3f820a9c 100644
--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
@@ -1196,7 +1196,7 @@ export function EntityWithEverything(
<div
use:draggable
data-checked={props.checked}
- class="everything-entity w-full relative group/entity hover:bg-hover/30 text-sm touch:mobile-width:text-base mx-[1px]"
+ class="everything-entity w-full relative group/entity hover:bg-hover/30 text-sm touch:mobile-width:text-base"
style={{
'min-height': `${ENTITY_HEIGHT}px`,
}}
diff --git a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx b/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
deleted file mode 100644
index 48929f80cc..0000000000
--- a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
+++ /dev/null
@@ -1,760 +0,0 @@
-import { useSuspenseContext } from '@app/component/SuspenseContext';
-import { EmptyState } from '@app/component/UnifiedListEmptyState';
-import { CustomScrollbar } from '@core/component/CustomScrollbar';
-import { toast } from '@core/component/Toast/Toast';
-import '@core/directive/dnd';
-import type { ViewId } from '@core/types/view';
-import { onElementConnect } from '@solid-primitives/lifecycle';
-import { debounce } from '@solid-primitives/scheduled';
-import { createVirtualizer, type Virtualizer } from '@tanstack/solid-virtual';
-import { StaticMarkdownContext } from 'core/component/LexicalMarkdown/component/core/StaticMarkdown';
-import {
- type Accessor,
- createComputed,
- createEffect,
- createMemo,
- createRenderEffect,
- createSignal,
- For,
- Match,
- on,
- onCleanup,
- type Setter,
- Show,
- Switch,
- untrack,
-} from 'solid-js';
-import { createStore, reconcile } from 'solid-js/store';
-import type {
- EntityInfiniteQuery,
- EntityList,
- EntityQuery,
- EntityQueryOperations,
- EntityQueryWithOperations,
-} from '../queries/entity';
-import { isSearchEntity } from '../queries/search';
-import type {
- EntitiesFilter,
- EntityComparator,
- EntityData,
- EntityFilter,
- EntityMapper,
- EntityRenderer,
-} from '../types/entity';
-import type { WithSearch } from '../types/search';
-import { Entity } from './Entity';
-import { ProjectDropOverlay } from './ProjectDrop';
-
-const DEBOUNCE_FETCH_MORE_MS = 50;
-
-// note that this must be greater than DEBOUNCE_FETCH_MORE_MS
-const DEBOUNCE_LOADING_STATE_MS = 100;
-
-const cacheMap = new Map<
- string,
- {
- offset: number;
- cache?: any; // TBD
- }
->();
-
-/**
- * Merges search data from two entities, preferring service source with local as fallback.
- * - Uses service entity as base
- * - Falls back to local nameHighlight if service doesn't have one
- * - Falls back to local contentHighlights if service doesn't have any
- * - Preserves 'local' source if either entity is local (for stable ordering)
- */
-const mergeSearchEntities = <T extends EntityData>(
- first: WithSearch<T>,
- second: WithSearch<T>
-): WithSearch<T> => {
- const serviceEntity = first.search.source === 'service' ? first : second;
- const localEntity = first.search.source === 'local' ? first : second;
- const hasLocal =
- first.search.source === 'local' || second.search.source === 'local';
-
- // NOTE: we that the longer name highlight is more relevant since it will contain a macro highlight tag
- let nameHighlight;
- if (serviceEntity.search.nameHighlight && localEntity.search.nameHighlight) {
- nameHighlight =
- serviceEntity.search.nameHighlight.length >=
- localEntity.search.nameHighlight.length
- ? serviceEntity.search.nameHighlight
- : localEntity.search.nameHighlight;
- } else {
- nameHighlight =
- serviceEntity.search.nameHighlight || localEntity.search.nameHighlight;
- }
-
- return {
- ...serviceEntity,
- search: {
- ...serviceEntity.search,
- source: hasLocal ? 'local' : 'service',
- nameHighlight,
- contentHitData: serviceEntity.search.contentHitData?.length
- ? serviceEntity.search.contentHitData
- : localEntity.search.contentHitData,
- },
- };
-};
-
-/**
- * Gets the timestamp of an entity (updatedAt or createdAt)
- */
-const getEntityTimestamp = (entity: EntityData): number => {
- return entity.updatedAt ?? entity.createdAt ?? 0;
-};
-
-/**
- * Returns true if the new entity should replace the existing one based on timestamp. If the timestamp is the same, prefer to use the newer entity to handle optimistic updates
- */
-const isNewerEntity = (
- newEntity: EntityData,
- existing: EntityData
-): boolean => {
- return getEntityTimestamp(newEntity) >= getEntityTimestamp(existing);
-};
-
-/**
- * Deduplicates entities by id, preferring entities with search data from 'service' source
- * over 'local' source, and using latest timestamp as a tiebreaker.
- * When preferring service results, merges local nameHighlight if service doesn't have one.
- */
-const deduplicateEntities = <T extends EntityData>(entities: T[]): T[] => {
- const entityMap = new Map<string, T>();
-
- for (const entity of entities) {
- const existing = entityMap.get(entity.id);
-
- if (!existing) {
- entityMap.set(entity.id, entity);
- continue;
- }
-
- const existingHasSearch = isSearchEntity(existing);
- const newHasSearch = isSearchEntity(entity);
-
- // Prefer entities with search data
- if (newHasSearch && !existingHasSearch) {
- entityMap.set(entity.id, entity);
- continue;
- }
-
- // If both have search data, prefer 'service' over 'local'
- if (existingHasSearch && newHasSearch) {
- const existingSource = existing.search.source;
- const newSource = entity.search.source;
-
- if (
- (newSource === 'service' && existingSource === 'local') ||
- (existingSource === 'service' && newSource === 'local')
- ) {
- // Merge service and local search data
- entityMap.set(entity.id, mergeSearchEntities(entity, existing));
- continue;
- }
-
- // If both are the same source, keep the one with latest timestamp
- if (isNewerEntity(entity, existing)) {
- entityMap.set(entity.id, entity);
- }
- continue;
- }
-
- // If neither has search, keep the one with latest timestamp
- if (!existingHasSearch && !newHasSearch) {
- if (isNewerEntity(entity, existing)) {
- entityMap.set(entity.id, entity);
- }
- }
- // Otherwise keep existing (it has search and new doesn't)
- }
-
- return Array.from(entityMap.values());
-};
-
-/**
- * Sorts entities for search mode
- */
-const sortEntitiesForSearch = <T extends EntityData>(a: T, b: T): number => {
- if (!isSearchEntity(a) || !isSearchEntity(b)) {
- if (isSearchEntity(a)) return -1;
- if (isSearchEntity(b)) return 1;
- return 0;
- }
-
- const channelsWithNameMatchesFirst = (a: WithSearch<T>, b: WithSearch<T>) => {
- if (a.type === 'channel' && b.type !== 'channel' && a.search.nameHighlight)
- return -1;
- if (a.type !== 'channel' && b.type === 'channel' && b.search.nameHighlight)
- return 1;
- return 0;
- };
-
- // NOTE: backend returns items in descending order of updatedAt so we match that here
- const updatedAtFirst = (a: WithSearch<T>, b: WithSearch<T>) => {
- if (a.updatedAt && b.updatedAt) return b.updatedAt - a.updatedAt;
- if (a.updatedAt) return -1;
- if (b.updatedAt) return 1;
- return 0;
- };
-
- // TODO: we may want to sort exact name matches first for other items too
- return channelsWithNameMatchesFirst(a, b) || updatedAtFirst(a, b);
-};
-
-const getGroupKey = (operations?: EntityQueryOperations): PropertyKey => {
- if (!operations) return 0;
- let key = 0;
- // we don't need to group by sort because we will do a global sort at the end
- // this gives us bitwise unique keys for each pairwise combination
- if (operations.filter) key |= 1;
- if (operations.search) key |= 2;
- return key;
-};
-
-const getOperations = <T extends Partial<EntityQueryOperations>>(
- query?: T
-): EntityQueryOperations => {
- if (!query) return { filter: false, search: false };
- return {
- filter: !!query.filter,
- search: !!query.search,
- };
-};
-
-interface UnifiedInfiniteListContext<T extends EntityData> {
- id: string;
- entityInfiniteQueries: Array<
- EntityQueryWithOperations<
- EntityData | WithSearch<EntityData>,
- EntityInfiniteQuery
- >
- >;
- entityQueries?: Array<EntityQueryWithOperations<EntityData, EntityQuery>>;
- entityMapper?: EntityMapper<T>;
- requiredFilter?: Accessor<EntityFilter<T>>;
- optionalFilter?: Accessor<EntityFilter<T>>;
- entitySort?: Accessor<EntityComparator<T>>;
- searchFilter?: Accessor<EntitiesFilter<T> | undefined>;
- isSearchActive?: Accessor<boolean>;
- disableFetchMore?: Accessor<boolean>;
-}
-
-export function createUnifiedInfiniteList<T extends EntityData>({
- id,
- entityInfiniteQueries,
- entityQueries,
- entityMapper = (entity: EntityData) => entity as T,
- requiredFilter,
- optionalFilter,
- entitySort,
- searchFilter,
- isSearchActive,
- disableFetchMore,
-}: UnifiedInfiniteListContext<T>) {
- const [sortedEntitiesStore, setSortedEntitiesStore] = createStore<T[]>([]);
- const allEntities = createMemo(() => {
- const entities =
- entityQueries?.map((query) => {
- const operations = getOperations(query.operations);
- const data =
- query.query.isEnabled && query.query.data ? query.query.data : [];
- return {
- data,
- operations,
- };
- }) ?? [];
- const groups = Object.groupBy(entities, (entityList) =>
- getGroupKey(entityList.operations)
- );
-
- const infiniteEntities = entityInfiniteQueries.map((query) => {
- const operations = getOperations(query.operations);
- // NOTE: we don't use the isSuccess check because fetch next page can fail
- const data = query.query.isEnabled ? (query.query.data ?? []) : [];
- return {
- data,
- operations,
- };
- });
- const infiniteGroups = Object.groupBy(infiniteEntities, (entityList) =>
- getGroupKey(entityList.operations)
- );
-
- // merge the entity and infinite entity groups
- const entityMapList = new Map<PropertyKey, Array<EntityList>>();
- for (const group of [groups, infiniteGroups]) {
- for (const [key, entityList] of Object.entries(group)) {
- if (!entityList || entityList.length === 0) continue;
- const existing = entityMapList.get(key) ?? [];
- if (existing.length === 0) {
- entityMapList.set(key, existing);
- }
- existing.push(...entityList);
- }
- }
-
- // flatten the groups
- // each group has a "unique" operation set for the purposes of providing the unified list
- const entityMap = new Map<PropertyKey, EntityList<T>>();
- for (const [key, entityLists] of entityMapList.entries()) {
- if (!entityLists || entityLists.length === 0) continue;
- const entityList: EntityList<T> = {
- data: entityLists
- .flatMap((entityList) => entityList.data)
- .map(entityMapper),
-
- operations: entityLists[0].operations,
- };
- entityMap.set(key, entityList);
- }
-
- return entityMap;
- });
-
- const filteredEntities = createMemo(() => {
- const requiredFilterFn = requiredFilter?.();
- const optionalFilterFn = optionalFilter?.();
- const searchFn = searchFilter?.();
- const entityGroupMap = allEntities();
-
- // apply filters + search filter to entities that haven't been operated on
- const entities: T[] = [];
- for (const entityList of entityGroupMap.values()) {
- const operations = getOperations(entityList.operations);
- let data = entityList.data;
- if (requiredFilterFn) data = data.filter(requiredFilterFn);
- if (optionalFilterFn && operations.filter)
- data = data.filter(optionalFilterFn);
- if (searchFn && operations.search) data = searchFn(data);
- entities.push(...data);
- }
-
- return entities;
- });
-
- const deduplicatedEntities = createMemo(() =>
- deduplicateEntities(filteredEntities())
- );
-
- const sortedEntities = createMemo<T[]>(() => {
- const entities = deduplicatedEntities();
- const sortFn = entitySort?.();
- const searching = isSearchActive?.();
-
- if (searching) {
- // NOTE: the default sort will be channels, then local fuzzy name, then search service
- // avoiding doing an extra sort as a speed optimization
- return entities.toSorted(sortEntitiesForSearch);
- }
-
- if (!sortFn) return entities;
-
- return entities.toSorted(sortFn);
- });
-
- const isLoading = createMemo(() => {
- const fetching =
- entityInfiniteQueries.some((query) => query.query.isFetching) ||
- entityQueries?.some((query) => query.query.isFetching);
- return !!fetching;
- });
-
- const hasFinishedInitialLoad = createMemo(() => {
- const enabledInfinite = entityInfiniteQueries.filter(
- (q) => q.query.isEnabled
- );
- const enabledSingles =
- entityQueries?.filter((q) => q.query.isEnabled) ?? [];
- if (enabledInfinite.length + enabledSingles.length === 0) return true;
-
- return (
- enabledInfinite.every((q) => !q.query.isLoading) &&
- enabledSingles.every((q) => !q.query.isLoading)
- );
- });
-
- // debounce loading state to prevent flickering during a series of paginated fetches
- const [debouncedIsLoading, setDebouncedIsLoading] = createSignal(false);
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
- createEffect(() => {
- const loading = isLoading();
-
- if (timeoutId) clearTimeout(timeoutId);
-
- if (loading) {
- setDebouncedIsLoading(true);
- } else {
- timeoutId = setTimeout(() => {
- setDebouncedIsLoading(false);
- }, DEBOUNCE_LOADING_STATE_MS);
- }
-
- onCleanup(() => {
- if (timeoutId) clearTimeout(timeoutId);
- });
- });
-
- let isFetchingMore = false;
- const fetchMoreData = async () => {
- if (disableFetchMore?.() || isFetchingMore) return;
-
- isFetchingMore = true;
- const results = entityInfiniteQueries.map((query) => {
- if (
- query.query.isEnabled &&
- query.query.hasNextPage &&
- !query.query.isFetching
- ) {
- return query.query.fetchNextPage();
- }
- });
-
- await Promise.allSettled(results);
- isFetchingMore = false;
- };
-
- createEffect(() => {
- const enabledQueries = entityInfiniteQueries.filter(
- (q) => q.query.isEnabled
- );
- const errorQueries = enabledQueries.filter((q) => q.query.isError);
-
- // Only show error if all enabled queries failed
- if (
- errorQueries.length === 0 ||
- errorQueries.length < enabledQueries.length
- )
- return;
-
- errorQueries.forEach((query) => {
- if (query.query.isFetchNextPageError) {
- console.error('failed to fetch next page', query.query.failureReason);
- toast.failure('Failed to fetch more data');
- } else {
- console.error('failed to fetch', query.query.failureReason);
- toast.failure('Failed to fetch data');
- }
- });
- });
-
- const debouncedFetchMore = debounce(fetchMoreData, DEBOUNCE_FETCH_MORE_MS);
-
- const DEFAULT_HEIGHT = 600;
- const [containerHeight, setContainerHeight] = createSignal(DEFAULT_HEIGHT);
-
- const UnifiedInfiniteList = (props: {
- children?: EntityRenderer<T>;
- entityListRef?: (ref: HTMLDivElement | undefined) => void;
- virtualizerHandle?: Setter<Virtualizer<Element, Element> | undefined>;
- hasRefinementsFromBase?: boolean;
- viewId?: ViewId;
- searchText?: string;
- entityMinHeight?: number;
- viewType?: string;
- name?: string;
- splitId?: string;
- }) => {
- const [scrollParentRef, setScrollParentRef] =
- createSignal<HTMLDivElement>();
-
- // Estimate items per viewport and derive overscan and page size
- // Keep a conservative default item size for estimation;
- const entityHeight = props.entityMinHeight ?? 40;
- const viewportItemCount = createMemo(() =>
- Math.max(1, Math.ceil(containerHeight() / entityHeight))
- );
- const computedOverscan = createMemo(() =>
- Math.max(6, Math.ceil(viewportItemCount() * 0.5))
- );
- const rowVirtualizer = createVirtualizer({
- get count() {
- return sortedEntitiesStore.length;
- },
- estimateSize: () => entityHeight,
- getScrollElement: () => scrollParentRef() as Element,
- overscan: computedOverscan(),
- });
-
- props.virtualizerHandle?.(rowVirtualizer);
-
- const [listRef, setListRef] = createSignal<HTMLDivElement>();
- let containerSizeObserver: ResizeObserver | null = null;
-
- createEffect(() => {
- containerSizeObserver?.disconnect();
- const ref = listRef();
- if (!ref) return;
-
- // Initialize with current size of the container using this component
- const initial =
- ref.clientHeight ||
- ref.getBoundingClientRect().height ||
- DEFAULT_HEIGHT;
- setContainerHeight((prevHeight) => Math.max(prevHeight, initial));
-
- containerSizeObserver = new ResizeObserver((entries) => {
- const last = entries.pop();
- const nextHeight = last?.contentRect?.height ?? ref.clientHeight;
- if (Number.isFinite(nextHeight) && nextHeight > 0)
- setContainerHeight((prevHeight) => Math.max(prevHeight, nextHeight));
- });
- containerSizeObserver.observe(ref);
- onCleanup(() => containerSizeObserver?.disconnect());
- });
-
- const loadingCount = () =>
- entityQueries?.filter((query) => query.query.isLoading).length ??
- 0 + entityInfiniteQueries.filter((query) => query.query.isLoading).length;
-
- const EntityRenderer = props.children ?? Entity;
-
- // Fetch more data if we filter out more items than the viewport can display
- // because it's possible that the match exists on the server
- createEffect(
- on(
- [sortedEntities, viewportItemCount, loadingCount],
- ([sortedEntities, viewportItemCount, loadingCount]) => {
- if (sortedEntities.length >= viewportItemCount) return;
- if (loadingCount > 0) return;
- debouncedFetchMore();
- }
- )
- );
-
- onCleanup(() => debouncedFetchMore.clear());
-
- const cacheKey = `list-cache-${id}`;
-
- // compose method to cache scroll position when called
- const scrollToIndex = rowVirtualizer.scrollToIndex;
- rowVirtualizer.scrollToIndex = (
- index: number,
- options?: ScrollToOptions | undefined
- ) => {
- // @ts-expect-error
- scrollToIndex(index, options);
- requestAnimationFrame(() => {
- cacheVirtualizerHandle();
- });
- };
-
- // Restore scroll position on mount
- const restoreScrollPosition = () => {
- const { offset: cachedOffset } = cacheMap.get(cacheKey) || { offset: 0 };
- if (rowVirtualizer && cachedOffset != null) {
- rowVirtualizer.scrollToOffset(cachedOffset);
- }
- };
-
- const cacheVirtualizerHandle = () => {
- const key = cacheKey;
-
- const scrollOffset = rowVirtualizer.scrollOffset;
- if (rowVirtualizer && key) {
- cacheMap.set(key, { offset: scrollOffset ?? 0 });
- }
- };
-
- let scrollMounted = false;
- createEffect(
- on(scrollParentRef, (scrollParentRef, prev) => {
- if (scrollParentRef && prev == null) {
- scrollMounted = true;
- restoreScrollPosition();
- }
- })
- );
-
- const { isPending } = useSuspenseContext();
-
- // Save scroll position and cache on cleanup
- onCleanup(() => {
- cacheVirtualizerHandle();
- });
-
- // Restore scroll after Suspense
- createComputed(
- on(
- isPending,
- (isPending, prevIsPending) => {
- if (isPending) {
- if (scrollMounted) {
- cacheVirtualizerHandle();
- }
- }
- if (isPending === false && prevIsPending === true) {
- queueMicrotask(() => {
- restoreScrollPosition();
- });
- }
- },
- { defer: true }
- )
- );
-
- // stable empty state
- const entityCount = createMemo(() => sortedEntities().length);
- const [showEmptyState, setShowEmptyState] = createSignal<boolean>(false);
- const [loadFinished, setLoadFinished] = createSignal<boolean>(false);
- createEffect(() => {
- if (entityCount() === 0) {
- setLoadFinished(false);
- let count = 0;
- const timeoutId = setInterval(() => {
- const countExceeded = ++count > 10;
- if (countExceeded) {
- console.warn('Too many interval iterations');
- }
-
- if (loadFinished() || countExceeded) clearInterval(timeoutId);
- if (entityCount() === 0 && !debouncedIsLoading()) {
- setLoadFinished(true);
- }
- }, 500);
- }
- });
- createEffect(() => {
- if (hasFinishedInitialLoad() && !debouncedIsLoading()) {
- setLoadFinished(true);
- }
- });
- createEffect(() => {
- if (entityCount() > 0) {
- setShowEmptyState(false);
- return;
- }
- setShowEmptyState(loadFinished());
- });
-
- return (
- <>
- <Show when={props.viewType === 'project' && props.viewId}>
- {(id) => (
- <ProjectDropOverlay
- projectId={id()}
- name={props.name}
- splitId={props.splitId}
- />
- )}
- </Show>
- <Switch>
- <Match when={showEmptyState()}>
- <EmptyState
- viewId={props.viewId}
- search={!!props.searchText}
- hasRefinementsFromBase={props.hasRefinementsFromBase}
- />
- </Match>
- <Match when={true}>
- <div class="flex size-full relative" ref={setListRef}>
- <StaticMarkdownContext>
- <div
- class="size-full relative scrollbar-hidden"
- data-unified-entity-list
- ref={(el) => {
- onElementConnect(el, () => {
- setScrollParentRef(el as HTMLDivElement);
- });
- }}
- style={{
- overflow: 'auto',
- }}
- >
- <div
- ref={(el) => {
- onElementConnect(el, () => {
- props.entityListRef?.(el as HTMLDivElement);
- });
- }}
- style={{
- height: `${rowVirtualizer.getTotalSize()}px`,
- width: '100%',
- position: 'relative',
- }}
- >
- <div
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- width: '100%',
- transform: `translateY(${rowVirtualizer.getVirtualItems()?.[0]?.start}px)`,
- }}
- >
- <For each={rowVirtualizer.getVirtualItems()}>
- {(virtualItem) => {
- if (
- untrack(() => virtualItem.index) >=
- Math.floor(untrack(sortedEntities).length * 0.9)
- ) {
- debouncedFetchMore();
- }
-
- return (
- <Show
- when={sortedEntitiesStore[virtualItem.index]?.id}
- keyed
- >
- {(_) => {
- const entity =
- sortedEntitiesStore[virtualItem.index];
- return (
- <Show when={entity}>
- <div
- data-index={virtualItem.index}
- ref={(el) =>
- queueMicrotask(() =>
- rowVirtualizer.measureElement(el)
- )
- }
- >
- <EntityRenderer
- entity={entity}
- index={virtualItem.index}
- />
- </div>
- </Show>
- );
- }}
- </Show>
- );
- }}
- </For>
- </div>
- </div>
- </div>
- </StaticMarkdownContext>
- <CustomScrollbar
- scrollContainer={() => {
- // Find the actual scroll container (VList creates its own scroll container)
- const listEl = listRef();
- if (!listEl) return undefined;
- const scrollContainer = listEl.querySelector(
- '[data-unified-entity-list]'
- ) as HTMLElement;
- return scrollContainer || undefined;
- }}
- />
- </div>
- </Match>
- </Switch>
- </>
- );
- };
-
- // need derived store to keep entities references stable, otherwise entities rerenders components
- createRenderEffect(() => {
- setSortedEntitiesStore(reconcile(sortedEntities(), { key: 'id' }));
- });
-
- return {
- UnifiedInfiniteList,
- UnifiedListComponent: UnifiedInfiniteList,
- entities: () => sortedEntitiesStore,
- isLoading: debouncedIsLoading,
- };
-}
diff --git a/js/app/packages/macro-entity/src/components/UnifiedList.tsx b/js/app/packages/macro-entity/src/components/UnifiedList.tsx
deleted file mode 100644
index aee0a909bc..0000000000
--- a/js/app/packages/macro-entity/src/components/UnifiedList.tsx
+++ /dev/null
@@ -1,228 +0,0 @@
-import { StaticMarkdownContext } from 'core/component/LexicalMarkdown/component/core/StaticMarkdown';
-import { unifiedListMarkdownTheme } from 'core/component/LexicalMarkdown/theme';
-import { useHotkeyDOMScope } from 'core/hotkey/hotkeys';
-import type { Accessor, JSX, Setter } from 'solid-js';
-import {
- createMemo,
- createSignal,
- mapArray,
- onCleanup,
- onMount,
- splitProps,
- untrack,
-} from 'solid-js';
-import { type VirtualizerHandle, VList, type VListProps } from 'virtua/solid';
-import { LIST_WRAPPER } from '../constants/classStrings';
-import type { EntityInfiniteQuery, EntityQuery } from '../queries/entity';
-import type {
- EntityComparator,
- EntityData,
- EntityEnhancer,
- EntityFilter,
- EntityRenderer,
-} from '../types/entity';
-import { Entity } from './Entity';
-
-type ChildlessVListProps<T extends EntityData> = Omit<
- VListProps<T>,
- 'children' | 'data'
->;
-
-interface UnifiedListProps<T extends EntityData>
- extends ChildlessVListProps<T> {
- entitiesData: T[];
- children?: EntityRenderer<T>;
-}
-
-export function UnifiedList<T extends EntityData>(props: UnifiedListProps<T>) {
- const [unifiedListProps, vListProps] = splitProps(props, [
- 'entitiesData',
- 'children',
- ]);
-
- return (
- <StaticMarkdownContext theme={unifiedListMarkdownTheme}>
- <VList
- data={unifiedListProps.entitiesData}
- class={LIST_WRAPPER}
- {...vListProps}
- >
- {(entity, index) =>
- unifiedListProps.children?.({ entity, index: index() }) ?? (
- <Entity entity={entity} />
- )
- }
- </VList>
- </StaticMarkdownContext>
- );
-}
-
-type EnhancedEntity<E> = E extends EntityEnhancer<infer T> ? T : never;
-type FilteredEntity<F> = F extends EntityFilter<infer T> ? T : never;
-type SortedEntity<S> = S extends EntityComparator<infer T> ? T : never;
-type RequiredEntity<F, S> = FilteredEntity<F> & SortedEntity<S>;
-
-interface UnifiedListContext {
- entityQueries: EntityQuery[];
- entityInfiniteQueries: EntityInfiniteQuery[];
-}
-export type UnifiedListComponent<T extends EntityData> = (props: {
- children: EntityRenderer<T>;
- ref?: Setter<VirtualizerHandle | undefined>;
-}) => JSX.Element;
-type UnifiedListReturn<T extends EntityData> = {
- UnifiedList: UnifiedListComponent<T>;
- entities: Accessor<T[]>;
- containerRef: Accessor<HTMLDivElement | undefined>;
- virtualizerHandle: Accessor<VirtualizerHandle | undefined>;
- hotkeyScope: string;
-};
-
-/**
- * Creates a unified list component for rendering a list of entities.
- * @param context - Non-reactive options for creating the list.
- * @param context.entityQueries - An array of entity queries for the list.
- * @param context.entityInfiniteQueries - An array of entity infinite queries for the list.
- * @param context.entityEnhancer - A function that will be called to enhance the entity data.
- * @param context.entityFilter - A function that will be called to filter the entity data.
- * @param context.entitySort - A function that will be called to sort the entity data.
- * @param context.entityClickHandler - An optional function that will be called with the entity data and event when an entity is clicked.
- * @returns A component that will render a list of entities. Props passed to this component are reactive.
- *
- * TODO: also returns functions for manipulating the list and/or component.
- */
-export function createUnifiedList(
- context: UnifiedListContext
-): UnifiedListReturn<EntityData>;
-
-export function createUnifiedList<T extends EntityData>(
- context: UnifiedListContext,
- entityEnhancer: EntityEnhancer<T>
-): UnifiedListReturn<T>;
-
-export function createUnifiedList<
- T extends EntityData,
- F extends EntityFilter<T>,
- S extends EntityComparator<T>,
- E extends EntityEnhancer<RequiredEntity<F, S>>,
->(
- context: UnifiedListContext &
- (
- | {
- entityFilter: Accessor<F>;
- }
- | {
- entitySort: Accessor<S>;
- }
- | {
- entityFilter: Accessor<F>;
- entitySort: Accessor<S>;
- }
- ),
- entityEnhancer?: E
-): UnifiedListReturn<EnhancedEntity<E>>;
-
-export function createUnifiedList<
- T extends EntityData,
- F extends EntityFilter<T>,
- S extends EntityComparator<T>,
- E extends EntityEnhancer<RequiredEntity<F, S>>,
->(
- {
- entityQueries,
- entityInfiniteQueries,
- entityFilter,
- entitySort,
- }: UnifiedListContext & {
- entityFilter?: Accessor<F>;
- entitySort?: Accessor<S>;
- },
- entityEnhancer?: E
-): UnifiedListReturn<T> {
- let isFetchingMore = false;
- const fetchMorePages = async () => {
- if (isFetchingMore) return;
-
- isFetchingMore = true;
- const results = entityInfiniteQueries.map((query) => {
- if (query.hasNextPage && !query.isFetching) return query.fetchNextPage();
- });
-
- await Promise.allSettled(results);
- isFetchingMore = false;
- };
-
- const entities = createMemo<EntityData[]>(() => [
- ...entityQueries.flatMap((query) => (query.isSuccess ? query.data : [])),
- ...entityInfiniteQueries.flatMap((query) =>
- query.isSuccess ? query.data : []
- ),
- ]);
-
- const enhancedEntities = entityEnhancer
- ? mapArray(entities, (entity, index) =>
- entityEnhancer(entity, index(), entities())
- )
- : (entities as Accessor<T[]>);
-
- const filteredEntities = createMemo<T[]>(() => {
- const entityFilterFn = entityFilter?.();
- if (entityFilterFn) return enhancedEntities().filter(entityFilterFn);
-
- return enhancedEntities();
- });
-
- const sortedEntities = createMemo<T[]>(() => {
- const entitySortFn = entitySort?.();
- if (entitySortFn) return filteredEntities().toSorted(entitySortFn);
-
- return filteredEntities();
- });
-
- const [containerRef, setContainerRef] = createSignal<HTMLDivElement>();
- const [virtualizerHandle, setVirtualizerHandle] =
- createSignal<VirtualizerHandle>();
- const [attachHotkeys, hotkeyScope] = useHotkeyDOMScope('unified-list');
- const UnifiedListComponent: UnifiedListComponent<T> = (props) => {
- onMount(() => {
- const ref = containerRef();
- if (!ref) return;
-
- attachHotkeys(ref);
- });
-
- onCleanup(() => {
- setContainerRef(undefined);
- setVirtualizerHandle(undefined);
- });
-
- return (
- <div ref={setContainerRef} class="contents">
- <UnifiedList
- entitiesData={sortedEntities()}
- ref={(handle) => {
- if (!handle) return;
-
- setVirtualizerHandle(handle);
- props.ref?.(handle);
- }}
- >
- {(data) => {
- if (data.index === Math.floor(untrack(sortedEntities).length * 0.9))
- fetchMorePages();
-
- return props.children(data);
- }}
- </UnifiedList>
- </div>
- );
- };
-
- return {
- UnifiedList: UnifiedListComponent,
- entities: sortedEntities,
- containerRef,
- virtualizerHandle,
- hotkeyScope,
- };
-}
diff --git a/js/app/packages/macro-entity/src/contexts/soup.ts b/js/app/packages/macro-entity/src/contexts/soup.ts
deleted file mode 100644
index 9366eab73c..0000000000
--- a/js/app/packages/macro-entity/src/contexts/soup.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { DefaultView } from '@core/types/view';
-import {
- type Accessor,
- createContext,
- type Setter,
- useContext,
-} from 'solid-js';
-
-export const SoupContext = createContext<{
- splitHotkeyScope: string;
- setSelectedView: Setter<DefaultView>;
- tabButtonsRef: Accessor<HTMLDivElement | null>;
-}>();
-
-export function useSoupContext() {
- const context = useContext(SoupContext);
- if (!context)
- throw new Error('useSoupContext must be used within a SoupContext');
-
- return context;
-}
diff --git a/js/app/packages/macro-entity/src/index.tsx b/js/app/packages/macro-entity/src/index.tsx
index 67917c2c33..3b3c172c41 100644
--- a/js/app/packages/macro-entity/src/index.tsx
+++ b/js/app/packages/macro-entity/src/index.tsx
@@ -3,14 +3,7 @@ export { EntityWrapper } from './components/EntityWrapper';
export { createFilter } from './components/Filter';
export { Provider } from './components/Provider';
export * from './components/Sort';
-export { createUnifiedInfiniteList } from './components/UnifiedInfiniteList';
-export {
- createUnifiedList,
- UnifiedList,
- type UnifiedListComponent,
-} from './components/UnifiedList';
export { UnreadIndicator } from './components/Unread';
-export * from './contexts/soup';
export { useQueryClient } from './queries/client';
export {
createChatsInfiniteQuery,
diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.ts
index 6ae145e5f4..9d4dca8140 100644
--- a/js/app/packages/macro-entity/src/queries/dss.ts
+++ b/js/app/packages/macro-entity/src/queries/dss.ts
@@ -41,6 +41,7 @@ import {
} from './auth';
import { queryClient } from './client';
import { type DssQueryKey, dssQueryKeyHashFn, queryKeys } from './key';
+import { soupKeys } from '@queries/soup/keys';
const getSoupItemId = (item: SoupApiItem): string => {
switch (item.tag) {
@@ -424,7 +425,7 @@ export function createDeleteDssItemMutation() {
}
queryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryKey: soupKeys.items._def,
});
},
}));
@@ -451,7 +452,7 @@ export function createBulkDeleteDssItemsMutation() {
const deletedIDs = entities.map((e) => e.id);
queryClient.cancelQueries({
- queryKey: queryKeys.all.dss,
+ queryKey: soupKeys.items._def,
});
queryClient.cancelQueries({
queryKey: queryKeys.all.search,
@@ -510,7 +511,7 @@ export function createBulkDeleteDssItemsMutation() {
};
}
- queryClient.setQueriesData({ queryKey: queryKeys.all.dss }, (prev) =>
+ queryClient.setQueriesData({ queryKey: soupKeys.items._def }, (prev) =>
removeEntitiesFromQueryData(
prev as InfiniteData<SoupPage, unknown> | undefined
)
@@ -529,7 +530,7 @@ export function createBulkDeleteDssItemsMutation() {
toast.failure('Failed to delete items');
// Rollback on error - restore the deleted items
queryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryKey: soupKeys.items._def,
});
queryClient.invalidateQueries({
queryKey: queryKeys.all.search,
@@ -562,7 +563,7 @@ function invalidateAfterMove(hasProjects: boolean, failed?: boolean) {
}
queryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryKey: soupKeys.items._def,
});
queryClient.invalidateQueries({ queryKey: ['entity'] });
// If moving a project, invalidate all project queries since nested projects' breadcrumbs change too
@@ -605,7 +606,7 @@ export function createMoveToProjectDssEntityMutation() {
// Projects have complex path data that we can't compute client-side
if (type !== 'project') {
queryClient.setQueriesData(
- { queryKey: queryKeys.all.dss },
+ { queryKey: soupKeys.items._def },
createMoveOptimisticUpdate([id], projectId)
);
}
@@ -653,7 +654,7 @@ export function createCopyDssEntityMutation() {
toast.failure('Failed to copy item');
}
queryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryKey: soupKeys.items._def,
});
queryClient.invalidateQueries({ queryKey: ['entity'] });
},
@@ -711,7 +712,7 @@ export function createBulkCopyDssEntityMutation() {
// Trigger refetch so new items appear
queryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
+ queryKey: soupKeys.items._def,
});
queryClient.invalidateQueries({ queryKey: ['entity'] });
},
diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.ts
index 1c9c866d02..b80df75e83 100644
--- a/js/app/packages/queries/email/thread.ts
+++ b/js/app/packages/queries/email/thread.ts
@@ -1,6 +1,6 @@
import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';
import { catchToResult, isErr, ok, throwOnErr } from '@core/util/maybeResult';
-import { queryKeys } from '@macro-entity';
+import { soupKeys } from '../soup/keys';
import { emailClient } from '@service-email/client';
import type {
MessageToSend,
@@ -158,7 +158,7 @@ type MarkThreadAsSeenParams = { threadId: string };
*/
function threadSeenOnMutate(params: MarkThreadAsSeenParams): void {
queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(
- { queryKey: queryKeys.all.dss },
+ { queryKey: soupKeys.items._def },
(old) => {
if (!old) return old;
return {
diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.ts
index 3c652a1db7..ef4d1da3a7 100644
--- a/js/app/packages/queries/properties/entity.ts
+++ b/js/app/packages/queries/properties/entity.ts
@@ -29,7 +29,7 @@ import type { SoupProperty } from '../../service-clients/service-storage/generat
import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { propertiesKeys } from './keys';
-import { queryKeys } from '../../macro-entity/src/queries/key';
+import { soupKeys } from '../soup/keys';
import type { BulkEntityPropertiesData } from './bulk';
export function useEntityPropertiesQuery(
@@ -136,7 +136,7 @@ export function useSaveEntityPropertyMutation(
variables.property.propertyDefinitionId ===
SYSTEM_PROPERTY_IDS.STATUS
) {
- queryClient.invalidateQueries({ queryKey: queryKeys.all.dss });
+ queryClient.invalidateQueries({ queryKey: soupKeys.items._def });
}
},
},
@@ -343,7 +343,7 @@ export function useSetPropertyStatusCompleteMutation(
predicate: ({ queryKey }) =>
bulkIncludesEntityPredicate(queryKey, vars.entityId),
}),
- queryClient.cancelQueries({ queryKey: queryKeys.all.dss }),
+ queryClient.cancelQueries({ queryKey: soupKeys.items._def }),
]);
// Snapshot previous data for rollback
@@ -363,7 +363,7 @@ export function useSetPropertyStatusCompleteMutation(
const previousDss = queryClient.getQueriesData<
InfiniteData<SoupPage, unknown>
>({
- queryKey: queryKeys.all.dss,
+ queryKey: soupKeys.items._def,
});
// Optimistically update entity properties query
@@ -394,9 +394,9 @@ export function useSetPropertyStatusCompleteMutation(
}
);
- // Optimistically update DSS queries (embedded properties on entities)
+ // Optimistically update soup queries (embedded properties on entities)
queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(
- { queryKey: queryKeys.all.dss },
+ { queryKey: soupKeys.items._def },
(old) => updateDssStatusToCompleted(old, vars.entityId)
);
@@ -428,8 +428,8 @@ export function useSetPropertyStatusCompleteMutation(
},
onSettled: (_data, _error, variables) => {
invalidatePropertiesForEntity(variables.entityType, variables.entityId);
- // Also invalidate DSS to ensure consistency
- queryClient.invalidateQueries({ queryKey: queryKeys.all.dss });
+ // Also invalidate soup items to ensure consistency
+ queryClient.invalidateQueries({ queryKey: soupKeys.items._def });
},
...(callbacks
? withCallbacks<
diff --git a/js/app/packages/queries/soup/items.ts b/js/app/packages/queries/soup/items.ts
new file mode 100644
index 0000000000..7bb5704900
--- /dev/null
+++ b/js/app/packages/queries/soup/items.ts
@@ -0,0 +1,84 @@
+import { throwOnErr } from '@core/util/maybeResult';
+import type { EntityData } from '@macro-entity';
+import { soupKeys } from '@queries/soup/keys';
+import { mapSoupPageToEntityList } from '@queries/soup/transform-utils';
+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
+import { storageServiceClient } from '@service-storage/client';
+import type {
+ ChannelFilters,
+ ChatFilters,
+ DocumentFilters,
+ EmailFilters,
+ ParamsSortMethod,
+ ProjectFilters,
+} from '@service-storage/generated/schemas';
+import {
+ useInfiniteQuery,
+ type UseInfiniteQueryResult,
+} from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+
+export type SoupItemsQueryFilters = {
+ /** the bundled [ChannelFilters] */
+ channel_filters?: ChannelFilters;
+ /** the bundled [ChatFilters] */
+ chat_filters?: ChatFilters;
+ /** the bundled [DocumentFilters] */
+ document_filters?: DocumentFilters;
+ /** the bundled [EmailFilters] */
+ email_filters?: EmailFilters;
+ /** the bundled [ProjectFilters] */
+ project_filters?: ProjectFilters;
+};
+
+export type SoupItemsQueryArgs = {
+ params: {
+ limit?: number;
+ sort_method?: ParamsSortMethod;
+ };
+ body: SoupItemsQueryFilters & {
+ emailView?: string;
+ };
+};
+
+export type UseSoupQueyResult = UseInfiniteQueryResult<EntityData[], Error>;
+
+interface SoupItemsQueryOptions {
+ enabled: boolean;
+}
+
+export const useSoupItemsQuery = (
+ args: Accessor<SoupItemsQueryArgs>,
+ options?: Accessor<SoupItemsQueryOptions>
+) => {
+ const instructionsIdQuery = useInstructionsMdIdQuery();
+
+ return useInfiniteQuery(() => ({
+ queryKey: soupKeys.items(args()).queryKey,
+ queryFn: async (ctx) => {
+ const { params, body } = args();
+
+ return throwOnErr(
+ async () =>
+ await storageServiceClient.getSoupItems({
+ params: { cursor: ctx.pageParam },
+ body: {
+ ...body,
+ ...params,
+ },
+ })
+ );
+ },
+ initialPageParam: null as string | null,
+ getNextPageParam: (lastPage) => {
+ return lastPage.next_cursor;
+ },
+ select: (data) => {
+ return data.pages.flatMap((page) => {
+ return mapSoupPageToEntityList(page, { instructionsIdQuery });
+ });
+ },
+ enabled: options?.().enabled,
+ placeholderData: (p) => p,
+ }));
+};
diff --git a/js/app/packages/queries/soup/keys.ts b/js/app/packages/queries/soup/keys.ts
new file mode 100644
index 0000000000..b3324797c5
--- /dev/null
+++ b/js/app/packages/queries/soup/keys.ts
@@ -0,0 +1,12 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+import type { SoupItemsQueryArgs } from './items';
+import type { SearchSoupQueryArgs } from './search';
+
+export const soupKeys = createQueryKeys('soup', {
+ items: (args: SoupItemsQueryArgs) => ({
+ queryKey: [args.params, args.body],
+ }),
+ search: (args: SearchSoupQueryArgs) => ({
+ queryKey: [args.params, args.body],
+ }),
+});
diff --git a/js/app/packages/queries/soup/search.ts b/js/app/packages/queries/soup/search.ts
new file mode 100644
index 0000000000..9f532080b4
--- /dev/null
+++ b/js/app/packages/queries/soup/search.ts
@@ -0,0 +1,96 @@
+import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';
+import { throwOnErr } from '@core/util/maybeResult';
+import type { WithSearch, EntityData } from '@macro-entity';
+import { soupKeys } from '@queries/soup/keys';
+import { useSearchResponseItemMapper } from '@queries/soup/transform-utils';
+import { searchClient } from '@service-search/client';
+import type { UnifiedSearchRequest } from '@service-search/generated/models';
+import { useInfiniteQuery } from '@tanstack/solid-query';
+import { type Accessor, createMemo } from 'solid-js';
+
+export type SearchSoupQueryArgs = {
+ params: {
+ cursor?: string | null;
+ page_size?: number;
+ };
+ body: UnifiedSearchRequest;
+};
+
+interface SearchQueryOptions {
+ enabled: boolean;
+}
+
+export const useSearchSoupQuery = (
+ args: Accessor<SearchSoupQueryArgs>,
+ options?: Accessor<SearchQueryOptions>
+) => {
+ const pageSize = createMemo(() => args().params.page_size);
+
+ const request = createMemo(() => args().body);
+
+ const terms = createMemo(() => {
+ const query = request().query;
+ const hasQuery = query && query.length > 0;
+ const terms = request().terms;
+ const hasTerms = terms && terms.length > 0;
+ if (hasTerms && hasQuery) {
+ console.error('Cannot have both query and terms');
+ return [];
+ }
+ if (hasTerms) {
+ return terms;
+ }
+ if (hasQuery) {
+ return [query];
+ }
+ return [];
+ });
+
+ const validSearchTerms = createMemo(() => {
+ return terms().length > 0 && terms().every((term) => term.length >= 3);
+ });
+
+ const enabled = createMemo(() => {
+ if (options?.().enabled === false) return false;
+
+ if (!terms().length) return true;
+
+ return ENABLE_SEARCH_SERVICE && validSearchTerms();
+ });
+
+ const mapSearchResponseItem = useSearchResponseItemMapper();
+
+ return useInfiniteQuery(() => ({
+ queryKey: soupKeys.search(args()).queryKey,
+ queryFn: async (ctx) => {
+ return throwOnErr(
+ async () =>
+ await searchClient.search({
+ params: ctx.pageParam,
+ request: { ...request() },
+ })
+ );
+ },
+ initialPageParam: {
+ cursor: null as string | null,
+ page_size: pageSize(),
+ },
+ getNextPageParam: (lastPage) => {
+ if (!lastPage.next_cursor) return;
+ return {
+ cursor: lastPage.next_cursor,
+ page_size: pageSize(),
+ };
+ },
+ select: (data) => {
+ const searchQuery = terms()[0];
+ return data.pages.flatMap((page) => {
+ return page.results
+ .map((result) => mapSearchResponseItem(result, searchQuery))
+ .filter((entity): entity is WithSearch<EntityData> => !!entity);
+ });
+ },
+ enabled: enabled(),
+ placeholderData: (p) => p,
+ }));
+};
diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.ts
new file mode 100644
index 0000000000..53dc10c90d
--- /dev/null
+++ b/js/app/packages/queries/soup/transform-utils.ts
@@ -0,0 +1,477 @@
+import {
+ blockNameToDefaultFile,
+ itemToSafeName,
+} from '@core/constant/allBlocks';
+import { useChannelsContext } from '@core/context/channels';
+import { emailToId } from '@core/user';
+import {
+ truncateSearchMatch,
+ mergeAdjacentMacroEmTags,
+ extractSearchSnippet,
+ extractSearchTerms,
+} from '@core/util/searchHighlight';
+import type {
+ SearchData,
+ ContentHitData,
+ WithSearch,
+ EntityData,
+ DocumentEntity,
+ ChatEntity,
+ ProjectEntity,
+ EmailEntity,
+ ChannelEntity,
+} from '@macro-entity';
+import { useHistoryQuery } from '@queries/history/history';
+import type { ChannelType } from '@service-comms/generated/models';
+import type {
+ DocumentSearchResult,
+ EmailSearchResult,
+ ChatMessageSearchResult,
+ ChannelSearchResult,
+ ProjectSearchResult,
+ UnifiedSearchResponseItem,
+} from '@service-search/generated/models';
+import type {
+ SoupDocument,
+ SoupPage,
+} from '@service-storage/generated/schemas';
+import type { UseQueryResult } from '@tanstack/solid-query';
+
+const SEARCH_MATCH_LENGTH = 60;
+
+type InnerSearchResult =
+ | DocumentSearchResult
+ | EmailSearchResult
+ | ChatMessageSearchResult
+ | ChannelSearchResult
+ | ProjectSearchResult;
+
+type TypedInnerSearchResult =
+ | { results: InnerSearchResult[]; type?: undefined }
+ | { results: DocumentSearchResult[]; type: 'pdf'; searchQuery: string }
+ | { results: DocumentSearchResult[]; type: 'md' }
+ | { results: ChannelSearchResult[]; type: 'channel' }
+ | { results: EmailSearchResult[]; type: 'email' };
+
+const getSearchData = (data: TypedInnerSearchResult): SearchData => {
+ let contentHitData: ContentHitData[] = [];
+
+ switch (data.type) {
+ case 'channel': {
+ contentHitData = data.results.flatMap((r) => {
+ const isContentHit = !!r.message_id;
+ if (!isContentHit) return [];
+
+ const contents = r.highlight.content ?? [];
+ return contents.map((content) => ({
+ type: 'channel' as const,
+ id: r.message_id!,
+ content: truncateSearchMatch(
+ mergeAdjacentMacroEmTags(content),
+ SEARCH_MATCH_LENGTH
+ ),
+ senderId: r.sender_id!,
+ sentAt: r.created_at!,
+ location: {
+ type: 'channel' as const,
+ threadId: r.thread_id ?? undefined,
+ messageId: r.message_id!,
+ },
+ }));
+ });
+ break;
+ }
+ case 'pdf': {
+ contentHitData = data.results.flatMap((r) => {
+ const contents = r.highlight.content ?? [];
+ return contents.map((content) => {
+ const mergedContent = mergeAdjacentMacroEmTags(content);
+ return {
+ type: 'pdf' as const,
+ content: truncateSearchMatch(
+ mergeAdjacentMacroEmTags(content),
+ SEARCH_MATCH_LENGTH
+ ),
+ location: {
+ type: 'pdf' as const,
+ searchPage: Number(r.node_id),
+ searchSnippet: extractSearchSnippet(mergedContent),
+ searchRawQuery: data.searchQuery,
+ highlightTerms: extractSearchTerms(mergedContent),
+ },
+ };
+ });
+ });
+ break;
+ }
+ case 'md': {
+ contentHitData = data.results.flatMap((r) => {
+ const isContentHit = !!r.node_id;
+ if (!isContentHit) return [];
+
+ const contents = r.highlight.content ?? [];
+ return contents.map((content) => ({
+ type: 'md' as const,
+ content: truncateSearchMatch(
+ mergeAdjacentMacroEmTags(content),
+ SEARCH_MATCH_LENGTH
+ ),
+ location: { type: 'md' as const, nodeId: r.node_id! },
+ }));
+ });
+ break;
+ }
+ case 'email': {
+ contentHitData = data.results.flatMap((r) => {
+ const contents = r.highlight.content ?? [];
+ return contents.map((content) => ({
+ type: 'email' as const,
+ content: truncateSearchMatch(
+ mergeAdjacentMacroEmTags(content),
+ SEARCH_MATCH_LENGTH
+ ),
+ sender: r.pretty_sender!,
+ senderId: emailToId(r.sender),
+ sentAt: r.sent_at!,
+ location: {
+ type: 'email' as const,
+ messageId: r.message_id!,
+ },
+ }));
+ });
+ break;
+ }
+ default: {
+ contentHitData = data.results.flatMap((r) => {
+ const contents = r.highlight.content ?? [];
+ return contents.map((content) => ({
+ content: truncateSearchMatch(
+ mergeAdjacentMacroEmTags(content),
+ SEARCH_MATCH_LENGTH
+ ),
+ location: undefined,
+ }));
+ });
+ }
+ }
+
+ const nameHighlight = data.results.at(0)?.highlight.name ?? null;
+
+ return {
+ nameHighlight: nameHighlight
+ ? mergeAdjacentMacroEmTags(nameHighlight)
+ : null,
+ contentHitData: contentHitData.length > 0 ? contentHitData : null,
+ source: 'service' as const,
+ };
+};
+
+export const useSearchResponseItemMapper = () => {
+ const channelsContext = useChannelsContext();
+ const channels = channelsContext.channels;
+
+ const historyQuery = useHistoryQuery();
+
+ return (
+ result: UnifiedSearchResponseItem,
+ searchQuery: string
+ ): WithSearch<EntityData> | undefined => {
+ switch (result.type) {
+ case 'document': {
+ if (!result.metadata || result.metadata.deleted_at) return;
+ const searchFileType =
+ result.file_type === 'docx' ? 'pdf' : result.file_type;
+ let search: SearchData;
+ if (searchFileType === 'md') {
+ search = getSearchData({
+ results: result.document_search_results,
+ type: 'md',
+ });
+ } else if (searchFileType === 'pdf') {
+ search = getSearchData({
+ results: result.document_search_results,
+ type: 'pdf',
+ searchQuery,
+ });
+ } else {
+ search = getSearchData({
+ results: result.document_search_results,
+ });
+ }
+ return {
+ type: 'document',
+ subType: result.sub_type === 'task' ? { type: 'task' } : null,
+ id: result.document_id,
+ name: result.name || blockNameToDefaultFile(result.file_type),
+ ownerId: result.owner_id,
+ createdAt: result.metadata?.created_at,
+ updatedAt: result.metadata?.updated_at,
+ fileType: result.file_type || undefined,
+ projectId: result.metadata?.project_id ?? undefined,
+ search,
+ };
+ }
+ case 'email': {
+ const messageHits = result.email_message_search_results.filter(
+ (m) => m.message_id
+ );
+ // NOTE: guaranteed to be empty or singleton array
+ const threadHits = result.email_message_search_results.filter(
+ (m) => !m.message_id
+ );
+
+ const singleMessage = messageHits.length === 1;
+
+ const search = getSearchData({
+ results: result.email_message_search_results,
+ type: 'email',
+ });
+
+ const name = result.name ?? blockNameToDefaultFile('email');
+
+ // TODO: display sender for each message in the content hit list
+ const combinedSenders =
+ [...new Set(messageHits.map((m) => m.pretty_sender))].join(', ') ||
+ threadHits.at(0)?.pretty_sender;
+
+ // TODO: we probably want to get the actual latest message info on the full thread
+ const messagesSentAt = messageHits
+ .map((m) => m.sent_at)
+ .filter((m) => m != null);
+ const latestMessageSentAt =
+ messagesSentAt.length > 0 ? Math.max(...messagesSentAt) : null;
+
+ return {
+ type: 'email',
+ id: result.thread_id,
+ name,
+ ownerId: result.owner_id,
+ createdAt: latestMessageSentAt ?? result.created_at,
+ updatedAt: latestMessageSentAt ?? result.updated_at,
+ viewedAt: result.viewed_at ?? undefined,
+ isRead: singleMessage
+ ? !messageHits[0].labels.includes('UNREAD')
+ : false,
+ isImportant: singleMessage
+ ? messageHits[0].labels.includes('IMPORTANT')
+ : false,
+ isDraft: singleMessage
+ ? messageHits[0].labels.includes('DRAFT')
+ : false,
+ done: singleMessage
+ ? !messageHits[0].labels.includes('INBOX')
+ : false,
+ senderName: combinedSenders,
+ search,
+ };
+ }
+ case 'chat': {
+ if (!result.metadata || result.metadata.deleted_at) return;
+ const search = getSearchData({
+ results: result.chat_search_results,
+ });
+ let name = result.name;
+ if (!name || name === blockNameToDefaultFile('chat')) {
+ const chat = (historyQuery.data ?? []).find(
+ (item) => item.id === result.chat_id
+ );
+ if (chat) {
+ name = chat.name;
+ }
+ }
+ return {
+ type: 'chat',
+ id: result.chat_id,
+ name,
+ ownerId: result.user_id,
+ createdAt: result.metadata?.created_at,
+ updatedAt: result.metadata?.updated_at,
+ projectId: result.metadata?.project_id ?? undefined,
+ search,
+ };
+ }
+ case 'channel': {
+ const channelWithLatest = channels().find(
+ (c) => c.id === result.channel_id
+ );
+
+ const search = getSearchData({
+ type: 'channel',
+ results: result.channel_message_search_results,
+ });
+
+ return {
+ type: 'channel',
+ id: result.channel_id,
+ name: channelWithLatest?.name ?? blockNameToDefaultFile('channel'),
+ ownerId: result.owner_id ?? '',
+ createdAt: result.metadata?.created_at,
+ updatedAt: result.metadata?.updated_at,
+ channelType: result.channel_type as ChannelType,
+ interactedAt: result.metadata?.interacted_at ?? undefined,
+ participantIds: channelWithLatest?.participants?.map(
+ (p) => p.user_id
+ ),
+ search,
+ };
+ }
+
+ case 'project': {
+ if (!result.metadata || result.metadata.deleted_at) return;
+ const search = getSearchData({
+ results: result.project_search_results,
+ });
+
+ return {
+ type: 'project',
+ id: result.id,
+ name: result.name,
+ ownerId: result.owner_id,
+ createdAt: result.created_at,
+ updatedAt: result.updated_at,
+ projectId: result.metadata?.parent_project_id ?? undefined,
+ search,
+ };
+ }
+ }
+ };
+};
+
+const resolveDocumentEntityName = (
+ entity: DocumentEntity | SoupDocument
+): string => {
+ return itemToSafeName({
+ type: 'document',
+ name: entity.name,
+ fileType: entity.fileType,
+ subType:
+ entity.subType === null || entity.subType === undefined
+ ? null
+ : {
+ type: entity.subType.type as 'task',
+ is_completed: entity.subType.is_completed,
+ },
+ });
+};
+
+export const mapSoupPageToEntityList: (
+ data: SoupPage,
+ options: {
+ instructionsIdQuery: UseQueryResult<string | null | undefined, Error>;
+ }
+) => (
+ | DocumentEntity
+ | ChatEntity
+ | ProjectEntity
+ | EmailEntity
+ | ChannelEntity
+)[] = (data, options) => {
+ return data.items
+ .filter(
+ (item) =>
+ item.tag !== 'document' ||
+ !options.instructionsIdQuery.isSuccess ||
+ item.data.id !== options.instructionsIdQuery.data
+ )
+ .map(
+ (
+ item
+ ):
+ | DocumentEntity
+ | ChatEntity
+ | ProjectEntity
+ | EmailEntity
+ | ChannelEntity => {
+ if (item.tag === 'chat') {
+ return {
+ ...item.data,
+ type: item.tag,
+ name: item.data.name || 'New Chat',
+ frecencyScore: item.frecency_score,
+ viewedAt: item.data.viewedAt ?? undefined,
+ projectId: item.data.projectId ?? undefined,
+ };
+ }
+
+ if (item.tag === 'project') {
+ return {
+ createdAt: item.data.createdAt,
+ updatedAt: item.data.updatedAt,
+ id: item.data.id,
+ ownerId: item.data.ownerId,
+ frecencyScore: item.frecency_score,
+ viewedAt: item.data.viewedAt ?? undefined,
+ projectId: item.data.parentId ?? undefined,
+ type: item.tag,
+ name: item.data.name || 'New Project',
+ };
+ }
+
+ if (item.tag === 'emailThread') {
+ const participants = item.data.participants?.map((p) => ({
+ email: p.emailAddress ?? '',
+ name: p.name ?? '',
+ }));
+
+ return {
+ ...item.data,
+ senderEmail: item.data.senderEmail ?? undefined,
+ senderName: item.data.senderName ?? undefined,
+ snippet: item.data.snippet ?? undefined,
+ done: !item.data.inboxVisible,
+ type: 'email',
+ name: item.data.name || 'Email Thread',
+ frecencyScore: item.frecency_score,
+ viewedAt: item.data.viewedAt ?? undefined,
+ participants,
+ };
+ }
+
+ if (item.tag === 'channel') {
+ const out: ChannelEntity = {
+ type: 'channel',
+ id: item.data.channel.id,
+ name: item.data.channel.name || 'Unknown Channel',
+ channelType: item.data.channel.channel_type,
+ ownerId: item.data.channel.owner_id,
+ frecencyScore: item.frecency_score ?? 0,
+ updatedAt: Date.parse(item.data.channel.updated_at),
+ createdAt: Date.parse(item.data.channel.created_at),
+ participantIds: item.data.participants.map((p) => p.user_id),
+ viewedAt: item.data.viewed_at
+ ? Date.parse(item.data.viewed_at)
+ : item.data.interacted_at
+ ? Date.parse(item.data.interacted_at)
+ : undefined,
+ latestMessage: item.data.latest_non_thread_message
+ ? {
+ content: item.data.latest_non_thread_message.content,
+ senderId: item.data.latest_non_thread_message.sender_id,
+ createdAt: Date.parse(
+ item.data.latest_non_thread_message.created_at
+ ),
+ }
+ : undefined,
+ };
+ return out;
+ }
+
+ return {
+ ...item.data,
+ type: item.tag,
+ frecencyScore: item.frecency_score,
+ viewedAt: item.data.viewedAt ?? undefined,
+ fileType: item.data.fileType ?? undefined,
+ projectId: item.data.projectId ?? undefined,
+ subType:
+ item.data.subType === null || item.data.subType === undefined
+ ? undefined
+ : {
+ type: item.data.subType.type as 'task',
+ is_completed: item.data.subType.is_completed,
+ },
+ name: resolveDocumentEntityName(item.data),
+ };
+ }
+ );
+};
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index 1a634fd105..3c2344ffc8 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -29,7 +29,13 @@ import { registerClient } from '@core/util/mockClient';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { IDocumentStorageServiceFile } from '@filesystem/file';
import { platformFetch } from 'core/util/platformFetch';
-import type { AccessLevel, View, ViewsResponse } from './generated/schemas';
+import type {
+ AccessLevel,
+ PostSoupRequest,
+ SoupPage,
+ View,
+ ViewsResponse,
+} from './generated/schemas';
import type { AddPinRequest } from './generated/schemas/addPinRequest';
import type { AnchorResponse } from './generated/schemas/anchorResponse';
import {
@@ -236,6 +242,21 @@ export const storageServiceClient = {
);
},
+ async getSoupItems(args: {
+ params: { cursor?: string | null };
+ body: PostSoupRequest;
+ }) {
+ // Could use URLSearchParams?
+ const searchParams = args.params.cursor
+ ? `?cursor=${args.params.cursor}`
+ : '';
+
+ return await dssFetch<SoupPage>(`/items/soup${searchParams}`, {
+ method: 'POST',
+ body: JSON.stringify(args.body),
+ });
+ },
+
permissionsTokens: {
async createPermissionToken(args) {
return await dssFetch<GetDocumentPermissionsTokenResponse>(
diff --git a/js/app/patches/[email protected] b/js/app/patches/[email protected]
index 1fcf8f4483..7e99d3cc8e 100644
--- a/js/app/patches/[email protected]
+++ b/js/app/patches/[email protected]
@@ -1,15 +1,36 @@
+diff --git a/node_modules/virtua/.bun-tag-15612e2a041760f2 b/.bun-tag-15612e2a041760f2
+new file mode 100644
+index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/node_modules/virtua/.bun-tag-172fdc1cd9f249d3 b/.bun-tag-172fdc1cd9f249d3
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
+diff --git a/node_modules/virtua/.bun-tag-24dd483730732e6d b/.bun-tag-24dd483730732e6d
+new file mode 100644
+index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
+diff --git a/node_modules/virtua/.bun-tag-2824fc852a5fa84f b/.bun-tag-2824fc852a5fa84f
+new file mode 100644
+index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/node_modules/virtua/.bun-tag-3f7fdc11113d6518 b/.bun-tag-3f7fdc11113d6518
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
+diff --git a/node_modules/virtua/.bun-tag-642a2a583764625e b/.bun-tag-642a2a583764625e
+new file mode 100644
+index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/node_modules/virtua/.bun-tag-69ffcae45e968edb b/.bun-tag-69ffcae45e968edb
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
+diff --git a/node_modules/virtua/.bun-tag-943ab1ac08ad6c4 b/.bun-tag-943ab1ac08ad6c4
+new file mode 100644
+index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
+diff --git a/node_modules/virtua/.bun-tag-a52dba5b35f86f0d b/.bun-tag-a52dba5b35f86f0d
+new file mode 100644
+index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/node_modules/virtua/.bun-tag-b5e5cc1416c6ecd6 b/.bun-tag-b5e5cc1416c6ecd6
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
+diff --git a/node_modules/virtua/.bun-tag-c5121815fed5cc5b b/.bun-tag-c5121815fed5cc5b
+new file mode 100644
+index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/node_modules/virtua/.bun-tag-dc314e50881f3a5e b/.bun-tag-dc314e50881f3a5e
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
@@ -17,7 +38,7 @@ diff --git a/node_modules/virtua/.bun-tag-eeedd702ea82f0a5 b/.bun-tag-eeedd702ea
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/lib/solid/index.jsx b/lib/solid/index.jsx
-index 84788e713100b0e5a746bae3411a789002b42b8d..032896f69f7806c829bbbcf2e0c762b9868a5449 100644
+index 84788e713100b0e5a746bae3411a789002b42b8d..48b8b9c36ee3b7d97fa356f26d0d1e29098610b2 100644
--- a/lib/solid/index.jsx
+++ b/lib/solid/index.jsx
@@ -819,9 +819,9 @@ const createScroller = (store, isHorizontal) => {
@@ -41,3 +62,50 @@ index 84788e713100b0e5a746bae3411a789002b42b8d..032896f69f7806c829bbbcf2e0c762b9
},
_unobserve(e) {
ro.unobserve(e);
+@@ -1084,7 +1084,9 @@ const createResizeObserver = (cb) => {
+ */
+ const createResizer = (store, isHorizontal) => {
+ let viewportElement;
++ let containerElement;
+ const sizeKey = isHorizontal ? "width" : "height";
++ const scrollOffsetKey = isHorizontal ? "scrollLeft" : "scrollTop";
+ const mountedIndexes = new WeakMap();
+ const resizeObserver = createResizeObserver((entries) => {
+ const resizes = [];
+@@ -1092,10 +1094,14 @@ const createResizer = (store, isHorizontal) => {
+ // Skip zero-sized rects that may be observed under `display: none` style
+ if (!target.offsetParent)
+ continue;
++
++ const scrollOffset = viewportElement[scrollOffsetKey]
++
+ if (target === viewportElement) {
+ store.$update(ACTION_VIEWPORT_RESIZE, contentRect[sizeKey]);
+- }
+- else {
++ } else if (target === containerElement && normalizeScrollOffset(scrollOffset, scrollOffset < 0) !== store.$getScrollOffset()) {
++ store.$update(ACTION_SCROLL, normalizeScrollOffset(scrollOffset, scrollOffset < 0));
++ } else {
+ const index = mountedIndexes.get(target);
+ if (index != NULL) {
+ resizes.push([index, contentRect[sizeKey]]);
+@@ -1107,8 +1113,9 @@ const createResizer = (store, isHorizontal) => {
+ }
+ });
+ return {
+- $observeRoot(viewport) {
++ $observeRoot(container, viewport) {
+ resizeObserver._observe((viewportElement = viewport));
++ resizeObserver._observe((containerElement = container));
+ },
+ $observeItem: (el, i) => {
+ mountedIndexes.set(el, i);
+@@ -1389,7 +1396,7 @@ const Virtualizer = (props) => {
+ });
+ }
+ const scrollable = props.scrollRef || containerRef.parentElement;
+- resizer.$observeRoot(scrollable);
++ resizer.$observeRoot(containerRef, scrollable);
+ scroller.$observe(scrollable);
+ onCleanup(() => {
+ if (props.ref) {