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(web): refactor drive view to use new patterns and not depend on old soup (#6662)

dev-rbba539073e134
diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsx
index 8946f5dbb4..c22f48519e 100644
--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx
+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx
@@ -230,6 +230,7 @@ const SIDEBAR_LINKS = [
label: 'Documents',
href: LIST_VIEW_PATHS.documents,
params: {
+ initialFacets: { type: ['doc-markdown'] },
initialFilters: markdownDocumentsQuery ?? {},
initialClientFilters: {
and: ['document-or-file'],
@@ -295,10 +296,13 @@ type OpenWithSplitFn = ReturnType<typeof useSplitLayout>['openWithSplit'];
const isMarkdownDocumentsParams = (
params: SidebarItem['params'] | undefined
): boolean => {
+ const facets = params?.initialFacets as
+ | { type?: readonly unknown[] }
+ | undefined;
+ if (facets?.type?.includes('doc-markdown')) return true;
const initialClientFilters = params?.initialClientFilters as
| { or?: readonly unknown[] }
| undefined;
-
return initialClientFilters?.or?.includes('doc-markdown') ?? false;
};
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index eb48026d44..05a2d57abc 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -6,7 +6,10 @@ import { useSpreadsheetAccess } from '@app/features/block-spreadsheet/primitives
import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
import type { CalendarEvent } from '@app/features/calendar/types';
import { ChannelsView } from '@app/features/channels-view/channels-view';
-import { DriveView } from '@app/features/drive-view/drive-view';
+import {
+ DriveView,
+ type DriveViewProps,
+} from '@app/features/drive-view/drive-view';
import { EmailCompose } from '@app/features/email-compose/email-compose';
import { EmailView } from '@app/features/email-view/email-view';
import { GettingStarted } from '@app/features/getting-started';
@@ -122,7 +125,7 @@ type ComponentParams = Record<string, unknown>;
type ComponentFactory = (params: ComponentParams) => JSXElement;
-type DocumentsComponentParams = {
+type DocumentsComponentParams = DriveViewProps & {
initialFilters?: Query;
initialClientFilters?: SetPredicatesInput<string>;
};
@@ -512,10 +515,7 @@ registerComponent(
/>
}
>
- <DriveView
- initialFilters={params.initialFilters}
- initialClientFilters={params.initialClientFilters}
- />
+ <DriveView initialFacets={params.initialFacets} />
</Show>
</Show>
);
diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
index fb0f5a24f7..5f47fa9f0d 100644
--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
@@ -249,7 +249,7 @@ function SplitDriveReturnButton() {
const state = sourceList()?.state;
const label = state?.['drive.returnLabel'];
if (typeof label === 'string') return label;
- const driveState = state?.['drive.view'] as DriveState | undefined;
+ const driveState = state?.['drive.view.v2'] as DriveState | undefined;
return driveState ? driveLocationLabel(driveState.location) : 'My Files';
};
const returnToDrive = () => {
diff --git a/apps/web/src/features/drive-view/components/drive-file-dropzone.tsx b/apps/web/src/features/drive-view/components/drive-file-dropzone.tsx
new file mode 100644
index 0000000000..033b4ba562
--- /dev/null
+++ b/apps/web/src/features/drive-view/components/drive-file-dropzone.tsx
@@ -0,0 +1,36 @@
+import { FileDropOverlay } from '@core/component/FileDropOverlay';
+import { fileFolderDrop } from '@core/directive/fileFolderDrop';
+import { createSignal, type ParentProps, Show } from 'solid-js';
+
+false && fileFolderDrop;
+
+export function DriveFileDropzone(
+ props: ParentProps<{
+ onDrop: (
+ files: FileSystemFileEntry[],
+ folders: FileSystemDirectoryEntry[]
+ ) => void;
+ }>
+) {
+ const [dragging, setDragging] = createSignal(false);
+
+ return (
+ <div
+ class="relative flex size-full min-h-0 flex-col"
+ use:fileFolderDrop={{
+ onDrop: props.onDrop,
+
+ onDragStart: (valid) => setDragging(valid),
+
+ onDragEnd: () => setDragging(false),
+ }}
+ >
+ <Show when={dragging()}>
+ <FileDropOverlay>
+ Drop files here to add them to this location
+ </FileDropOverlay>
+ </Show>
+ {props.children}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/drive-view/context/drive-context.tsx b/apps/web/src/features/drive-view/context/drive-context.tsx
new file mode 100644
index 0000000000..c7db2affa0
--- /dev/null
+++ b/apps/web/src/features/drive-view/context/drive-context.tsx
@@ -0,0 +1,46 @@
+import type { EntityData, ProjectEntity, SearchLocation } from '@entity';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import { type Accessor, createContext, useContext } from 'solid-js';
+import type { DriveListState } from '../primitives/drive-list';
+import type { createDriveState } from '../primitives/drive-state';
+import type { DriveListSource, DriveSidebarSource } from './drive-source';
+
+export type DriveHostActions = {
+ userId: Accessor<string | undefined>;
+ canOpenNewSplit: Accessor<boolean>;
+ openEntity: (
+ entity: EntityData,
+ event?: MouseEvent,
+ location?: SearchLocation,
+ newSplit?: boolean
+ ) => void;
+ openFavorite: (favorite: Favorite, name: string, event: MouseEvent) => void;
+ openFolderInNewSplit: (folder: ProjectEntity) => void;
+ shareFolder: (folder: ProjectEntity) => void;
+ uploadFiles: () => void;
+ uploadFolder: () => void;
+ dropFiles: (
+ files: FileSystemFileEntry[],
+ folders: FileSystemDirectoryEntry[]
+ ) => void;
+};
+
+export type DriveContext = {
+ state: ReturnType<typeof createDriveState>;
+ source: DriveListSource;
+ list: DriveListState;
+ sidebar: DriveSidebarSource;
+ actions: DriveHostActions;
+};
+
+const Context = createContext<DriveContext>();
+
+export const DriveProvider = Context.Provider;
+
+export function useDriveView(): DriveContext {
+ const context = useContext(Context);
+
+ if (!context) throw new Error('DriveProvider is required');
+
+ return context;
+}
diff --git a/apps/web/src/features/drive-view/context/drive-source.ts b/apps/web/src/features/drive-view/context/drive-source.ts
index 9747e562b3..cd2b8eed89 100644
--- a/apps/web/src/features/drive-view/context/drive-source.ts
+++ b/apps/web/src/features/drive-view/context/drive-source.ts
@@ -1,7 +1,30 @@
-import type { DriveState } from '../core/types';
+import type { ListDataSource } from '@app/components/list';
+import type { SoupEntityRow } from '@app/features/soup/collection/types';
+import type { EntityData } from '@entity';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import type { Accessor } from 'solid-js';
+import type { DriveFolder, DriveState } from '../core/types';
-export type DriveSelection = Pick<DriveState, 'location' | 'scope' | 'sort'>;
+export type DriveListItem = SoupEntityRow<EntityData>;
-export type DriveResults = {
- apply: (selection: DriveSelection, clearSearch: boolean) => void;
+/** Query results consumed by Drive's list controller and renderer. */
+export type DriveListSource = ListDataSource<DriveListItem> & {
+ hasData: Accessor<boolean>;
+ featuredIds: Accessor<readonly string[]>;
+ deferInteractions: Accessor<boolean>;
+};
+
+export type DriveSelection = Pick<
+ DriveState,
+ 'location' | 'scope' | 'sort' | 'search' | 'facets'
+>;
+
+export type DriveFolderMetadata = DriveFolder & { userId: string };
+
+export type DriveSidebarSource = {
+ folders: Accessor<DriveFolderMetadata[]>;
+ favorites: Accessor<Favorite[]>;
+ foldersLoading: Accessor<boolean>;
+ foldersError: Accessor<boolean>;
+ retryFolders: () => Promise<void>;
};
diff --git a/apps/web/src/features/drive-view/core/types.ts b/apps/web/src/features/drive-view/core/types.ts
index bf4cf68a44..66ea808363 100644
--- a/apps/web/src/features/drive-view/core/types.ts
+++ b/apps/web/src/features/drive-view/core/types.ts
@@ -1,3 +1,5 @@
+import type { FacetSelection } from '@app/features/soup/filters/facets/types';
+
export type DriveTab = 'owned' | 'recent' | 'shared';
export type DriveScope = 'default' | 'all' | 'attachments';
export type DriveSort = 'updated_at' | 'created_at' | 'viewed_at';
@@ -18,6 +20,8 @@ export type DriveState = {
location: DriveLocation;
scope: DriveScope;
sort: DriveSort;
+ search: string;
+ facets: FacetSelection;
expandedFolderIds: string[];
favoritesOpen: boolean;
rootOpen: boolean;
diff --git a/apps/web/src/features/drive-view/drive-create-menu.tsx b/apps/web/src/features/drive-view/drive-create-menu.tsx
new file mode 100644
index 0000000000..46e364dba1
--- /dev/null
+++ b/apps/web/src/features/drive-view/drive-create-menu.tsx
@@ -0,0 +1,77 @@
+import { ViewSidebar } from '@app/components/view-shell';
+import {
+ CREATABLE_BLOCKS,
+ runCreateAction,
+ useCreatableEnabled,
+} from '@app/features/command/Launcher';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import FolderIcon from '@phosphor/folder.svg';
+import PlusIcon from '@phosphor/plus.svg';
+import UploadIcon from '@phosphor/upload-simple.svg';
+import { Dropdown } from '@ui';
+import { For } from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+import { useDriveView } from './context/drive-context';
+
+/** Launcher integration for the current Drive folder. */
+export function DriveCreateMenu() {
+ const { state, actions } = useDriveView();
+
+ const isEnabled = useCreatableEnabled();
+
+ const options = () =>
+ CREATABLE_BLOCKS.filter(
+ (block) =>
+ ['md', 'snippet', 'spreadsheet', 'canvas', 'code', 'project'].includes(
+ block.blockName
+ ) && isEnabled(block.blockName)
+ );
+
+ return (
+ <Dropdown placement="bottom-start">
+ <Dropdown.Trigger as={ViewSidebar.Action} aria-label="New file or folder">
+ <ViewSidebar.Icon>
+ <PlusIcon class="size-4" />
+ </ViewSidebar.Icon>
+ <span class="truncate">New</span>
+ <ViewSidebar.Trailing>
+ <CaretDownIcon class="size-3 shrink-0" />
+ </ViewSidebar.Trailing>
+ </Dropdown.Trigger>
+ <Dropdown.Content class="min-w-48">
+ <Dropdown.Group>
+ <For each={options()}>
+ {(option) => (
+ <Dropdown.Item
+ onSelect={() =>
+ runCreateAction(option.blockName, {
+ projectId: state.projectId(),
+ source: 'drive',
+ })
+ }
+ >
+ <span
+ aria-hidden="true"
+ class="flex size-4 shrink-0 items-center justify-center [&_svg]:size-4"
+ >
+ <Dynamic component={option.icon} />
+ </span>
+ <span>{option.label}</span>
+ </Dropdown.Item>
+ )}
+ </For>
+ </Dropdown.Group>
+ <Dropdown.Group>
+ <Dropdown.Item onSelect={actions.uploadFiles}>
+ <UploadIcon aria-hidden="true" class="size-4 shrink-0" />
+ <span>Upload files</span>
+ </Dropdown.Item>
+ <Dropdown.Item onSelect={actions.uploadFolder}>
+ <FolderIcon aria-hidden="true" class="size-4 shrink-0" />
+ <span>Upload folder</span>
+ </Dropdown.Item>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ );
+}
diff --git a/apps/web/src/features/drive-view/drive-folder-actions.tsx b/apps/web/src/features/drive-view/drive-folder-actions.tsx
index abf5a52363..577aed525b 100644
--- a/apps/web/src/features/drive-view/drive-folder-actions.tsx
+++ b/apps/web/src/features/drive-view/drive-folder-actions.tsx
@@ -9,12 +9,13 @@ import { toast } from '@core/component/Toast/Toast';
import { useUserId } from '@core/context/user';
import type { ProjectEntity } from '@entity';
import { invalidateProjects } from '@queries/storage/projects';
-import type { Project } from '@service-storage/generated/schemas/project';
import { Show } from 'solid-js';
+import type { DriveFolderMetadata } from './context/drive-source';
/** App wiring for sidebar folder actions using the shared list dialogs and mutations. */
-export function DriveFolderActions(props: { folder: Project }) {
+export function DriveFolderActions(props: { folder: DriveFolderMetadata }) {
const userId = useUserId();
+
const entity = (): ProjectEntity => ({
type: 'project',
id: props.folder.id,
@@ -22,10 +23,14 @@ export function DriveFolderActions(props: { folder: Project }) {
ownerId: props.folder.userId,
projectId: props.folder.parentId ?? undefined,
});
+
const favorite = makeFavoriteAction();
+
const copyLink = makeCopyLinkAction();
+
const deleteFolder = makeDeleteAction({
userId,
+
onDeleted: () => void invalidateProjects(),
});
@@ -33,10 +38,12 @@ export function DriveFolderActions(props: { folder: Project }) {
openBulkEditModal({
view,
entities: [entity()],
+
onFinish: () => {
void invalidateProjects();
toast.success(view === 'rename' ? 'Renamed' : 'Moved to folder');
},
+
onError: () => toast.failure('Failed to update folder'),
});
};
diff --git a/apps/web/src/features/drive-view/drive-host-actions.ts b/apps/web/src/features/drive-view/drive-host-actions.ts
new file mode 100644
index 0000000000..8b3063db7b
--- /dev/null
+++ b/apps/web/src/features/drive-view/drive-host-actions.ts
@@ -0,0 +1,170 @@
+import { entityDetailBlockType } from '@app/components/entity-detail/EntityDetail';
+import {
+ entityDetailTarget,
+ useEntityDetailNavigationStack,
+} from '@app/components/entity-detail/EntityDetailNavigationStack';
+import { makeShareAction } from '@app/features/next-soup/actions';
+import {
+ markReminderSeenOnOpen,
+ openEntityInNewTab,
+ openEntityInSplitFromUnifiedList,
+} from '@app/features/next-soup/utils';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import { favoriteBlockName, favoriteSplitContent } from '@app/util/favorites';
+import { useHandleFileUpload } from '@app/util/handleFileUpload';
+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { useUserId } from '@core/context/user';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import {
+ handleFileFolderDrop,
+ handleFolderSelect,
+ openFilePicker,
+ openFolderPicker,
+} from '@core/util/upload';
+import type { Accessor } from 'solid-js';
+import type { DriveHostActions } from './context/drive-context';
+
+/** App-specific navigation, upload and sharing adapters for the Drive workspace. */
+export function createDriveHostActions(options: {
+ projectId: Accessor<string | undefined>;
+ selectFolder: (id: string | null) => void;
+}): DriveHostActions {
+ const panel = useSplitPanelOrThrow();
+
+ const layout = useSplitLayout();
+
+ const navigation = useEntityDetailNavigationStack();
+
+ const notificationSource = useGlobalNotificationSource();
+
+ const share = makeShareAction();
+
+ const upload = useHandleFileUpload({
+ get projectId() {
+ return options.projectId();
+ },
+ });
+
+ return {
+ userId: useUserId(),
+
+ canOpenNewSplit: () =>
+ !isTouchDevice() && !!globalSplitManager()?.canAppendSplit(),
+
+ openEntity(entity, event, location, newSplit = false) {
+ const openInNewSplit = newSplit || event?.shiftKey === true;
+
+ // Nested project/content targets reach this adapter. The main row
+ // consumes Cmd/Ctrl itself for selection.
+ if (event?.metaKey || event?.ctrlKey) {
+ markReminderSeenOnOpen(entity, notificationSource);
+ openEntityInNewTab({ entity, location });
+
+ return;
+ }
+
+ if (entity.type === 'project' && !openInNewSplit && !event?.altKey) {
+ options.selectFolder(entity.id);
+
+ return;
+ }
+
+ markReminderSeenOnOpen(entity, notificationSource);
+
+ if (entity.type === 'document' && !openInNewSplit && !location) {
+ const target = entityDetailTarget.document({
+ id: entity.id,
+ fileType: entity.fileType,
+ subType: entity.subType,
+ fallbackName: entity.name,
+ });
+
+ if (
+ entityDetailBlockType(target) &&
+ navigation.shouldNavigate(target, { event })
+ ) {
+ navigation.reset(target);
+
+ return;
+ }
+ }
+
+ void openEntityInSplitFromUnifiedList(entity, {
+ splitHandle: panel.handle,
+ referredFrom: 'documents',
+ openInNewSplit,
+ replacePreview: event?.altKey && !openInNewSplit,
+ location,
+ notificationSource,
+ });
+ },
+
+ openFavorite(favorite, name, event) {
+ if (favorite.entityType === 'project' && !event.shiftKey) {
+ options.selectFolder(favorite.entityId);
+
+ return;
+ }
+
+ if (favorite.entityType === 'document') {
+ const block = favoriteBlockName(favorite);
+
+ const target = entityDetailTarget.document({
+ id: favorite.entityId,
+ fileType: favorite.fileType ?? undefined,
+ subType:
+ block === 'snippet' || block === 'skill'
+ ? { type: block }
+ : undefined,
+ fallbackName: name,
+ });
+
+ if (
+ entityDetailBlockType(target) &&
+ navigation.shouldNavigate(target, { event })
+ ) {
+ navigation.reset(target);
+
+ return;
+ }
+ }
+
+ layout.openWithSplit(favoriteSplitContent(favorite), {
+ referredFrom: 'sidebar',
+ preferNewSplit: event.shiftKey,
+ });
+ },
+
+ openFolderInNewSplit: (folder) => {
+ layout.openWithSplit(
+ { type: 'project', id: folder.id },
+ {
+ preferNewSplit: true,
+ referredFrom: 'entity-actions-menu',
+ }
+ );
+ },
+
+ shareFolder: (folder) => {
+ void share.execute(folder);
+ },
+
+ uploadFiles: () =>
+ openFilePicker({ multiple: true }, async (files) => {
+ await upload(files, false);
+ }),
+
+ uploadFolder: () =>
+ openFolderPicker({}, async (files) => {
+ await handleFolderSelect(files, async (entries) => {
+ await upload(entries, false);
+ });
+ }),
+
+ dropFiles: (files, folders) => {
+ void handleFileFolderDrop(files, folders, upload);
+ },
+ };
+}
diff --git a/apps/web/src/features/drive-view/drive-location-menu.tsx b/apps/web/src/features/drive-view/drive-location-menu.tsx
new file mode 100644
index 0000000000..01cc615498
--- /dev/null
+++ b/apps/web/src/features/drive-view/drive-location-menu.tsx
@@ -0,0 +1,72 @@
+import { globalSplitManager } from '@app/signal/splitLayout';
+import { SidebarOpenInSplitMenu } from '@components/app/app-sidebar/sidebar';
+import type { SplitContent } from '@components/app/split-layout/layoutManager';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { batch, type ParentProps, Show } from 'solid-js';
+import { useDriveView } from './context/drive-context';
+import type { DriveLocation, DriveState } from './core/types';
+import { DriveFolderActions } from './drive-folder-actions';
+
+/** App-specific split/menu wiring shared by Drive's sidebar locations. */
+export function DriveLocationMenu(
+ props: ParentProps<{ location: DriveLocation }>
+) {
+ const { state, sidebar } = useDriveView();
+
+ const panel = useSplitPanelOrThrow();
+
+ const folder = () => {
+ const location = props.location;
+
+ return location.kind === 'folder'
+ ? sidebar.folders().find((folder) => folder.id === location.id)
+ : undefined;
+ };
+
+ const content = (): SplitContent => ({
+ type: 'component',
+ id: 'documents',
+ state: {
+ 'drive.view.v2': {
+ ...state.value(),
+ location: props.location,
+ scope: 'default',
+ search: '',
+ facets: {},
+ } satisfies DriveState,
+ },
+ });
+
+ const openFullscreen = () => {
+ const manager = globalSplitManager();
+
+ if (!manager) return;
+
+ batch(() => {
+ state.navigate(props.location);
+
+ for (const split of manager.splits()) {
+ if (split.id !== panel.handle.id) manager.removeSplit(split.id);
+ }
+
+ manager.unSpotlightSplit();
+ panel.handle.activate();
+ });
+ };
+
+ return (
+ <SidebarOpenInSplitMenu
+ content={content}
+ triggerClass="block h-auto"
+ onOpenCurrentSplit={() => state.navigate(props.location)}
+ onOpenFullscreen={openFullscreen}
+ additionalActions={
+ <Show when={folder()}>
+ {(folder) => <DriveFolderActions folder={folder()} />}
+ </Show>
+ }
+ >
+ {props.children}
+ </SidebarOpenInSplitMenu>
+ );
+}
diff --git a/apps/web/src/features/drive-view/drive-view.tsx b/apps/web/src/features/drive-view/drive-view.tsx
index c4ed6c35f4..c20b510fc3 100644
--- a/apps/web/src/features/drive-view/drive-view.tsx
+++ b/apps/web/src/features/drive-view/drive-view.tsx
@@ -1,620 +1,157 @@
-import { entityDetailBlockType } from '@app/components/entity-detail/EntityDetail';
import {
EntityDetailNavigationStack,
- type EntityDetailTarget,
- entityDetailTarget,
useEntityDetailNavigationStack,
} from '@app/components/entity-detail/EntityDetailNavigationStack';
+import { listOwnedSlotName } from '@app/components/list';
+import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';
import {
- ListFilterDropdown,
- useViewControlHotkeys,
- useViewTabHotkeys,
- ViewBreadcrumbs,
- ViewSidebar,
-} from '@app/components/view-shell';
-import {
- CREATABLE_BLOCKS,
- runCreateAction,
- useCreatableEnabled,
-} from '@app/features/command/Launcher';
-import { FavoriteContextMenu } from '@app/features/favorites/FavoriteContextMenu';
-import { FavoriteIcon } from '@app/features/favorites/FavoriteIcon';
-import { makeShareAction } from '@app/features/next-soup/actions';
-import type { Query } from '@app/features/next-soup/filters/filter-store';
-import { queryStateFrom } from '@app/features/next-soup/filters/filter-store';
-import type { SetPredicatesInput } from '@app/features/next-soup/filters/filter-store/predicates-store';
-import { mergeQuery } from '@app/features/next-soup/filters/filter-store/query-store';
-import { soupItemMatchesProjectMembership } from '@app/features/next-soup/filters/query-filters';
-import { FilterSubmenu } from '@app/features/next-soup/soup-view/filters-bar/filter-menu';
-import { UnifiedFilterDropdown } from '@app/features/next-soup/soup-view/filters-bar/unified-filter-dropdown';
-import { SoupViewList } from '@app/features/next-soup/soup-view/soup-view';
-import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';
-import { globalSplitManager } from '@app/signal/splitLayout';
-import {
- favoriteBlockName,
- favoriteSplitContent,
- useFavoriteDisplayName,
-} from '@app/util/favorites';
-import { useHandleFileUpload } from '@app/util/handleFileUpload';
-import { SidebarOpenInSplitMenu } from '@components/app/app-sidebar/sidebar';
+ type FacetSelection,
+ useSoupListNavigationHotkeys,
+} from '@app/features/soup';
+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { useEntryState } from '@components/app/split-layout/entry-state';
-import { useSplitLayout } from '@components/app/split-layout/layout';
-import type { SplitContent } from '@components/app/split-layout/layoutManager';
-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
-import { useUserId } from '@core/context/user';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
import {
- handleFolderSelect,
- openFilePicker,
- openFolderPicker,
-} from '@core/util/upload';
-import EmptyStateFolderGraphic from '@design/empty-state-folder.svg';
-import ArrowLeftIcon from '@phosphor/arrow-left.svg';
-import CaretDownIcon from '@phosphor/caret-down.svg';
-import FolderIcon from '@phosphor/folder.svg';
-import FilterIcon from '@phosphor/funnel-simple.svg';
-import PlusIcon from '@phosphor/plus.svg';
-import SpinnerIcon from '@phosphor/spinner.svg';
-import UploadIcon from '@phosphor/upload-simple.svg';
-import { TagSetsProvider } from '@property/tags/tag-sets-context';
-import { useFavoritesData } from '@queries/favorites/favorites';
-import { useProjectsQuery } from '@queries/storage/projects';
-import type { Favorite } from '@service-storage/generated/schemas/favorite';
-import { Dropdown, EmptyStatePanel } from '@ui';
-import { batch, createMemo, For, onCleanup, Show, Suspense } from 'solid-js';
-import { Dynamic } from 'solid-js/web';
-import { DriveLocationBreadcrumbItems } from './components/DriveBreadcrumbs';
-import { DriveDetailView } from './components/DriveDetailView';
-import type { DriveLocationMenu } from './components/drive-navigation';
-import { driveLocationBreadcrumbs } from './core/breadcrumbs';
+ useSplitPanelOrThrow,
+ withSplitPanelOwner,
+} from '@components/app/split-layout/layoutUtils';
+import { useUserId } from '@core/context/user';
+import { ListEntityMetadataQueryProvider } from '@entity';
+import { useTagSets, useTagSetsReady } from '@property/tags/tag-sets-context';
+import { onCleanup, onMount, Suspense } from 'solid-js';
+import { DriveProvider } from './context/drive-context';
import { driveLocationLabel } from './core/location-label';
+import type { DriveState } from './core/types';
+import { createDriveHostActions } from './drive-host-actions';
import {
- DRIVE_TABS,
- type DriveScope,
- type DriveState,
- type DriveTab,
-} from './core/types';
-import { DriveFolderActions } from './drive-folder-actions';
-import { createDriveNavigation } from './primitives/drive-navigation';
-import { driveFilterTab, driveQuery } from './queries/drive-query';
-import { createDriveResults } from './queries/drive-results';
-import { DriveLayout } from './views/drive-layout';
+ createDriveList,
+ parseDriveListSnapshot,
+} from './primitives/drive-list';
+import { createDriveState } from './primitives/drive-state';
+import { createDriveDataSource } from './queries/drive-data-source';
+import { createDriveSidebarSource } from './queries/drive-sidebar-source';
+import { DriveLoading, DriveWorkspace } from './views/drive-workspace';
+
+export type DriveViewProps = { initialFacets?: FacetSelection };
+
+/** The only place that constructs production sources and app capabilities. */
+function DriveComposition(props: DriveViewProps) {
+ const panel = useSplitPanelOrThrow();
-export type DriveViewProps = {
- initialFilters?: Query;
- initialClientFilters?: SetPredicatesInput<string>;
-};
+ const navigation = useEntityDetailNavigationStack();
-function favoriteDetailTarget(
- favorite: Favorite,
- fallbackName: string
-): EntityDetailTarget | undefined {
- if (favorite.entityType !== 'document') return;
+ const userId = useUserId();
- const blockName = favoriteBlockName(favorite);
- const target = entityDetailTarget.document({
- id: favorite.entityId,
- fileType: favorite.fileType ?? undefined,
- subType:
- blockName === 'snippet' || blockName === 'skill'
- ? { type: blockName }
- : undefined,
- fallbackName,
- });
- return entityDetailBlockType(target) ? target : undefined;
-}
+ const notificationSource = useGlobalNotificationSource();
-function DriveFavorite(props: {
- favorite: Favorite;
- onOpen: (favorite: Favorite, name: string, event: MouseEvent) => void;
-}) {
- const name = useFavoriteDisplayName(props.favorite);
- return (
- <FavoriteContextMenu favorite={props.favorite} triggerClass="block">
- <ViewSidebar.Item
- title={name()}
- onClick={(event) => props.onOpen(props.favorite, name(), event)}
- >
- <ViewSidebar.Icon>
- <FavoriteIcon favorite={props.favorite} class="size-4" />
- </ViewSidebar.Icon>
- <span class="truncate">{name()}</span>
- </ViewSidebar.Item>
- </FavoriteContextMenu>
- );
-}
+ const tagSets = useTagSets();
-function DriveViewContent(props: DriveViewProps) {
- const panel = useSplitPanelOrThrow();
- const layout = useSplitLayout();
- const navigationStack = useEntityDetailNavigationStack();
- const shareAction = makeShareAction();
- const userId = useUserId();
- const view = useSoupView();
- const projects = useProjectsQuery();
- const folders = () =>
- projects.isSuccess
- ? projects.data.filter((folder) => !folder.deletedAt)
- : [];
- const favoritesData = useFavoritesData();
- const favorites = createMemo(() =>
- (favoritesData()?.favorites ?? [])
- .filter(
- (favorite) =>
- favorite.entityType === 'project' ||
- (favorite.entityType === 'document' &&
- favorite.documentSubType !== 'task')
- )
- .sort((a, b) => a.sortOrder - b.sortOrder)
- );
- const [state, setState] = useEntryState<DriveState>('drive.view', {
+ const tagSetsReady = useTagSetsReady();
+
+ const [value, setValue] = useEntryState<DriveState>('drive.view.v2', {
default: {
location: { kind: 'tab', tab: 'owned' },
scope: 'default',
sort: 'updated_at',
+ search: '',
+ facets: props.initialFacets ?? {},
expandedFolderIds: [],
favoritesOpen: true,
rootOpen: true,
tagsOpen: true,
},
});
- onCleanup(
- panel.handle.registerEntryStateCaptor('drive.returnLabel', () =>
- driveLocationLabel(state().location, folders())
- )
+
+ const sidebar = createDriveSidebarSource();
+
+ const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () =>
+ createDriveDataSource({
+ selection: value,
+ userId,
+ tagSets,
+ tagSetsReady,
+ notificationSource,
+ })
);
- const projectId = () => {
- const location = state().location;
- return location.kind === 'folder' ? (location.id ?? undefined) : undefined;
- };
- const isRecent = () => {
- const location = state().location;
- return location.kind === 'tab' && location.tab === 'recent';
- };
- const upload = useHandleFileUpload({
- get projectId() {
- return projectId();
- },
- });
- const isCreatableEnabled = useCreatableEnabled();
- const createOptions = () =>
- CREATABLE_BLOCKS.filter(
- (block) =>
- ['md', 'snippet', 'spreadsheet', 'canvas', 'code', 'project'].includes(
- block.blockName
- ) && isCreatableEnabled(block.blockName)
- );
- /** Exit any inline detail so the list reflects the chosen location or tags. */
- const showList = () => {
- navigationStack.clear();
- panel.handle.resetPreview();
- };
- const { navigate, setScope } = createDriveNavigation({
- state,
- setState,
- folders,
- results: createDriveResults(view, userId),
- onNavigate: showList,
+ const actions = createDriveHostActions({
+ projectId: () => state.projectId(),
+
+ selectFolder: (id) => state.selectFolder(id),
});
- const selectTab = (tab: DriveTab) => navigate({ kind: 'tab', tab });
- const selectFolder = (id: string | null) => navigate({ kind: 'folder', id });
- const locationBreadcrumbs = createMemo(() =>
- driveLocationBreadcrumbs(state().location, folders())
+
+ const list = withSplitPanelOwner(listOwnedSlotName('controller'), () =>
+ createDriveList({
+ source,
+ initial: parseDriveListSnapshot(
+ panel.handle.content().state?.['drive.listState']
+ ),
+
+ onActivate: (row, metadata) =>
+ actions.openEntity(
+ row.entity,
+ metadata?.event,
+ undefined,
+ metadata?.newSplit
+ ),
+ })
);
- const initial = driveQuery(state(), userId());
- view.initialize({
- initialQuery: props.initialFilters
- ? mergeQuery(queryStateFrom(initial.filters), props.initialFilters)
- : initial.filters,
- initialClientFilters: props.initialClientFilters ?? initial.clientFilters,
- initialSearchText: projectId() ? '' : view.searchText(),
- preferInitialFilters: true,
- sortMethod: () => (isRecent() ? 'touched_by_me' : undefined),
- persistFilters: false,
- itemMembershipFilter: (item) => {
- const id = projectId();
- return !id || soupItemMatchesProjectMembership(item, id);
- },
- });
- view.setActiveTab(driveFilterTab(state()));
- view.soup.grouping.setActiveGroupId(undefined);
- view.soup.sort.setAll([state().sort]);
- panel.handle.setDisplayName('Drive');
- let searchInput: HTMLInputElement | undefined;
- useViewControlHotkeys({
- scopeId: panel.splitHotkeyScope,
- enabled: panel.isPanelActive,
- search: {
- description: 'Search Drive',
- condition: () => !projectId() && !navigationStack.active(),
- run: () => {
- searchInput?.focus();
- searchInput?.select();
- return true;
- },
- },
- });
- useViewTabHotkeys({
- scopeId: panel.splitHotkeyScope,
- enabled: panel.isPanelActive,
- ids: () => DRIVE_TABS.map((tab) => tab.id),
- activeId: () => {
- const location = state().location;
- return location.kind === 'tab' ? location.tab : 'owned';
+ const state = createDriveState({
+ state: value,
+ setState: setValue,
+ folders: sidebar.folders,
+ list,
+
+ showList: () => {
+ navigation.clear();
+ panel.handle.resetPreview();
},
- setActiveId: selectTab,
});
- const scopeOptions: { id: DriveScope; label: string }[] = [
- { id: 'default', label: 'Default' },
- { id: 'all', label: 'All files' },
- { id: 'attachments', label: 'Email attachments' },
- ];
- const FilterMenu = () => (
- <Show when={state().location.kind === 'tab'}>
- <Show
- when={!isRecent()}
- fallback={
- <ListFilterDropdown
- label="Filter files"
- groups={[
- {
- id: 'scope',
- label: 'Files',
- selectionMode: 'single',
- defaultOptionId: 'default',
- options: scopeOptions,
- },
- ]}
- isSelected={(_, id) => state().scope === id}
- onSelectionChange={(_, id) => setScope(id)}
- />
- }
- >
- <Suspense>
- <UnifiedFilterDropdown
- customTrigger={
- <Dropdown.Trigger
- variant="outline"
- size="md"
- square
- depth={2}
- class="rounded-lg bg-surface"
- label="Filter files"
- >
- <FilterIcon />
- </Dropdown.Trigger>
- }
- >
- <FilterSubmenu
- label="Files"
- active={state().scope !== 'default'}
- options={scopeOptions}
- isSelected={(id) => state().scope === id}
- onSelect={setScope}
- closeOnSelect
- />
- </UnifiedFilterDropdown>
- </Suspense>
- </Show>
- </Show>
- );
-
- const CreateMenu = () => (
- <Dropdown placement="bottom-start">
- <Dropdown.Trigger as={ViewSidebar.Action} aria-label="New file or folder">
- <ViewSidebar.Icon>
- <PlusIcon class="size-4" />
- </ViewSidebar.Icon>
- <span class="truncate">New</span>
- <ViewSidebar.Trailing>
- <CaretDownIcon class="size-3 shrink-0" />
- </ViewSidebar.Trailing>
- </Dropdown.Trigger>
- <Dropdown.Content class="min-w-48">
- <Dropdown.Group>
- <For each={createOptions()}>
- {(option) => (
- <Dropdown.Item
- onSelect={() =>
- runCreateAction(option.blockName, {
- projectId: projectId(),
- source: 'drive',
- })
- }
- >
- <span
- aria-hidden="true"
- class="flex size-4 shrink-0 items-center justify-center [&_svg]:size-4"
- >
- <Dynamic component={option.icon} />
- </span>
- <span>{option.label}</span>
- </Dropdown.Item>
- )}
- </For>
- </Dropdown.Group>
- <Dropdown.Group>
- <Dropdown.Item
- onSelect={() =>
- openFilePicker({ multiple: true }, async (files) => {
- await upload(files, false);
- })
- }
- >
- <UploadIcon aria-hidden="true" class="size-4 shrink-0" />
- <span>Upload files</span>
- </Dropdown.Item>
- <Dropdown.Item
- onSelect={() =>
- openFolderPicker({}, async (files) => {
- await handleFolderSelect(files, async (entries) => {
- await upload(entries, false);
- });
- })
- }
- >
- <FolderIcon aria-hidden="true" class="size-4 shrink-0" />
- <span>Upload folder</span>
- </Dropdown.Item>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
+ onCleanup(
+ panel.handle.registerEntryStateCaptor('drive.returnLabel', () =>
+ driveLocationLabel(value().location, sidebar.folders())
+ )
);
- const Favorites = () => (
- <ViewSidebar.Nav aria-label="Favorite files and folders">
- <For each={favorites()}>
- {(favorite) => (
- <DriveFavorite
- favorite={favorite}
- onOpen={(item, name, event) => {
- const target = favoriteDetailTarget(item, name);
- if (item.entityType === 'project' && !event.shiftKey)
- selectFolder(item.entityId);
- else if (
- target &&
- navigationStack.shouldNavigate(target, { event })
- ) {
- navigationStack.reset(target);
- return;
- } else
- layout.openWithSplit(favoriteSplitContent(item), {
- referredFrom: 'sidebar',
- preferNewSplit: event.shiftKey,
- });
- }}
- />
- )}
- </For>
- </ViewSidebar.Nav>
+ onCleanup(
+ panel.handle.registerEntryStateCaptor('drive.listState', list.snapshot)
);
- const LocationMenu: DriveLocationMenu = (menuProps) => {
- const folder = () => {
- const location = menuProps.location;
- return location.kind === 'folder'
- ? folders().find((folder) => folder.id === location.id)
- : undefined;
- };
- const content = (): SplitContent => ({
- type: 'component',
- id: 'documents',
- state: {
- 'drive.view': {
- ...state(),
- location: menuProps.location,
- scope: 'default',
- } satisfies DriveState,
+ withSplitPanelOwner(listOwnedSlotName('navigation-hotkeys'), () => {
+ useSoupListNavigationHotkeys({
+ splitHotkeyScope: panel.splitHotkeyScope,
+ viewId: 'documents',
+ dataSource: source,
+ controller: list.controller,
+ handle: panel.handle,
+
+ openEntityInSplit: (entity, options) => {
+ void openEntityInSplitFromUnifiedList(entity, {
+ splitHandle: panel.handle,
+ ...options,
+ });
},
});
- const openFullscreen = () => {
- const manager = globalSplitManager();
- if (!manager) return;
-
- // Keep this Drive instance so the chosen location is applied to its navigation.
- batch(() => {
- navigate(menuProps.location);
- for (const split of manager.splits()) {
- if (split.id !== panel.handle.id) manager.removeSplit(split.id);
- }
- manager.unSpotlightSplit();
- panel.handle.activate();
- });
- };
+ });
- return (
- <SidebarOpenInSplitMenu
- content={content}
- triggerClass="block h-auto"
- onOpenCurrentSplit={() => navigate(menuProps.location)}
- onOpenFullscreen={openFullscreen}
- additionalActions={
- <Show when={folder()}>
- {(folder) => <DriveFolderActions folder={folder()} />}
- </Show>
- }
- >
- {menuProps.children}
- </SidebarOpenInSplitMenu>
- );
- };
+ onMount(() => panel.handle.setDisplayName('Drive'));
return (
- <ViewBreadcrumbs.Root
- value={
- navigationStack.active()?.value ?? locationBreadcrumbs().at(-1)!.value
- }
- onChange={(value) => {
- const breadcrumb = locationBreadcrumbs().find(
- (entry) => entry.value === value
- );
- if (!breadcrumb) {
- navigationStack.popTo(value);
- return;
- }
-
- const current = state().location;
- const location = breadcrumb.location;
- const isCurrent =
- (current.kind === 'tab' &&
- location.kind === 'tab' &&
- current.tab === location.tab) ||
- (current.kind === 'folder' &&
- location.kind === 'folder' &&
- current.id === location.id);
- if (isCurrent) {
- navigationStack.clear();
- return;
- }
- navigate(location);
- }}
- >
- <DriveLocationBreadcrumbItems
- entries={locationBreadcrumbs()}
- folders={folders()}
- userId={userId()}
- onOpenFolderInNewSplit={
- !isTouchDevice() && globalSplitManager()?.canAppendSplit()
- ? (folder) =>
- layout.openWithSplit(
- { type: 'project', id: folder.id },
- {
- preferNewSplit: true,
- referredFrom: 'entity-actions-menu',
- }
- )
- : undefined
- }
- onShareFolder={(folder) => void shareAction.execute(folder)}
- onDeleteFolder={(folder) => {
- const parentId = folders().some(({ id }) => id === folder.parentId)
- ? folder.parentId
- : null;
- selectFolder(parentId ?? null);
- }}
- />
- <TagSetsProvider tagSets={view.tagFilter.tagSets}>
- <DriveLayout
- locationMenu={LocationMenu}
- state={state()}
- folders={folders()}
- foldersLoading={projects.isPending}
- foldersError={projects.isError}
- onRetryFolders={() => void projects.refetch()}
- search={view.searchText()}
- onSearch={view.setSearchText}
- searchRef={(element) => {
- searchInput = element;
- }}
- onTab={selectTab}
- onFolder={selectFolder}
- filterMenu={FilterMenu}
- onSort={(sort) => {
- setState((current) => ({ ...current, sort }));
- view.soup.sort.setAll([sort]);
- }}
- onToggleFolder={(id) =>
- setState((current) => ({
- ...current,
- expandedFolderIds: current.expandedFolderIds.includes(id)
- ? current.expandedFolderIds.filter((value) => value !== id)
- : [...current.expandedFolderIds, id],
- }))
- }
- onFavoritesOpen={(favoritesOpen) =>
- setState((current) => ({ ...current, favoritesOpen }))
- }
- onRootOpen={(rootOpen) =>
- setState((current) => ({ ...current, rootOpen }))
- }
- activeTagIds={view.tagFilter.activeIds()}
- onTags={(ids) =>
- batch(() => {
- view.tagFilter.onChange(ids);
- showList();
- })
- }
- onTagsOpen={(tagsOpen) =>
- setState((current) => ({ ...current, tagsOpen }))
- }
- createMenu={CreateMenu}
- favorites={Favorites}
- hasFavorites={favorites().length > 0}
- detail={
- navigationStack.active() ? (
- <DriveDetailView
- breadcrumbOrderOffset={locationBreadcrumbs().length}
- />
- ) : undefined
- }
- >
- <Suspense
- fallback={
- <div class="grid size-full place-items-center text-ink-muted">
- <SpinnerIcon
- aria-label="Loading files"
- class="size-5 animate-spin"
- />
- </div>
- }
- >
- <SoupViewList
- emptyState={
- // A folder emptied by a tag filter is a filter miss, not a vacant folder.
- projectId() &&
- state().scope === 'default' &&
- view.tagFilter.activeIds().length === 0
- ? () => (
- <EmptyStatePanel
- centered
- graphic={EmptyStateFolderGraphic}
- title="This folder is empty"
- description="Create something new or drop files here to add them to this folder."
- primaryAction={{
- label: 'Back to Drive',
- icon: ArrowLeftIcon,
- onClick: () => selectFolder(null),
- }}
- />
- )
- : undefined
- }
- onOpenProject={selectFolder}
- onOpenEntity={(entity, event) => {
- if (entity.type !== 'document') return false;
-
- const target = entityDetailTarget.document({
- id: entity.id,
- fileType: entity.fileType,
- subType: entity.subType,
- fallbackName: entity.name,
- });
- if (!entityDetailBlockType(target)) return false;
- if (!navigationStack.shouldNavigate(target, { event }))
- return false;
- navigationStack.reset(target);
- return true;
- }}
- uploadProjectId={projectId()}
- disableTabHotkeys
- navigationKey={JSON.stringify([state().location, state().scope])}
- timestamp={isRecent() ? (entity) => entity.touchedAt : undefined}
- />
- </Suspense>
- </DriveLayout>
- </TagSetsProvider>
- </ViewBreadcrumbs.Root>
+ <DriveProvider value={{ state, source, list, sidebar, actions }}>
+ <DriveWorkspace />
+ </DriveProvider>
);
}
-/** App composition: shared queries, inline details, and upload/create capabilities. */
export function DriveView(props: DriveViewProps) {
return (
<EntityDetailNavigationStack.Root>
- <DriveViewContent {...props} />
+ <ListEntityMetadataQueryProvider>
+ <Suspense fallback={<DriveLoading />}>
+ <DriveComposition {...props} />
+ </Suspense>
+ </ListEntityMetadataQueryProvider>
</EntityDetailNavigationStack.Root>
);
}
diff --git a/apps/web/src/features/drive-view/filters/drive-facets.ts b/apps/web/src/features/drive-view/filters/drive-facets.ts
new file mode 100644
index 0000000000..a6fe1eb7d4
--- /dev/null
+++ b/apps/web/src/features/drive-view/filters/drive-facets.ts
@@ -0,0 +1,210 @@
+import {
+ clause,
+ type Facet,
+ type FacetClause,
+ type FacetOption,
+ TAG_FACET_ID,
+ type TagFacetContext,
+ tagFacetOption,
+} from '@app/features/soup/filters';
+import { codeFileExtensions } from '@block-code/util/languageSupport';
+import type { EntityData, EntityWithProperties } from '@entity';
+
+const IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'] as const;
+const VIDEO_EXTENSIONS = [
+ 'mp4',
+ 'mkv',
+ 'webm',
+ 'avi',
+ 'mov',
+ 'wmv',
+ 'mpg',
+ 'mpeg',
+ 'm4v',
+ 'flv',
+ 'f4v',
+ 'threegp',
+] as const;
+
+export type DriveFacetContext = TagFacetContext;
+export type DriveFacetEntity = EntityWithProperties<EntityData>;
+
+type DriveFacetOption = FacetOption<DriveFacetEntity, DriveFacetContext>;
+
+type DocumentTypeOptionId =
+ | 'doc-markdown'
+ | 'doc-canvas'
+ | 'doc-spreadsheet'
+ | 'file-code'
+ | 'file-image'
+ | 'file-pdf'
+ | 'file-docx'
+ | 'file-video'
+ | 'doc-snippet'
+ | 'doc-skill'
+ | 'file-other';
+
+function typeOption(
+ id: DocumentTypeOptionId,
+ expression: FacetClause['df'],
+ predicate: (entity: DriveFacetEntity) => boolean
+): DriveFacetOption {
+ return { id, clause: { df: expression }, predicate };
+}
+
+const namedDocumentSubtype = clause.or(
+ clause.eq('subType', 'task'),
+ clause.eq('subType', 'snippet'),
+ clause.eq('subType', 'skill')
+);
+
+const TYPE_OPTIONS: DriveFacetOption[] = [
+ typeOption(
+ 'doc-markdown',
+ clause.and(clause.eq('fileType', 'md'), clause.not(namedDocumentSubtype)),
+ (entity) =>
+ entity.type === 'document' && entity.fileType === 'md' && !entity.subType
+ ),
+ typeOption(
+ 'doc-canvas',
+ clause.eq('fileType', 'canvas'),
+ (entity) => entity.type === 'document' && entity.fileType === 'canvas'
+ ),
+ typeOption(
+ 'doc-spreadsheet',
+ clause.eq('fileType', 'spreadsheet'),
+ (entity) => entity.type === 'document' && entity.fileType === 'spreadsheet'
+ ),
+ typeOption(
+ 'file-code',
+ clause.eq('fileAssoc', 'assoc:code'),
+ (entity) =>
+ entity.type === 'document' &&
+ (codeFileExtensions as readonly string[]).includes(entity.fileType ?? '')
+ ),
+ typeOption(
+ 'file-image',
+ clause.eq('fileAssoc', 'assoc:image'),
+ (entity) =>
+ entity.type === 'document' &&
+ (IMAGE_EXTENSIONS as readonly string[]).includes(entity.fileType ?? '')
+ ),
+ typeOption(
+ 'file-pdf',
+ clause.eq('fileType', 'pdf'),
+ (entity) => entity.type === 'document' && entity.fileType === 'pdf'
+ ),
+ typeOption(
+ 'file-docx',
+ clause.eq('fileType', 'docx'),
+ (entity) => entity.type === 'document' && entity.fileType === 'docx'
+ ),
+ typeOption(
+ 'file-video',
+ clause.eq('fileAssoc', 'assoc:video'),
+ (entity) =>
+ entity.type === 'document' &&
+ (VIDEO_EXTENSIONS as readonly string[]).includes(entity.fileType ?? '')
+ ),
+ typeOption(
+ 'doc-snippet',
+ clause.and(clause.eq('fileType', 'md'), clause.eq('subType', 'snippet')),
+ (entity) => entity.type === 'document' && entity.subType?.type === 'snippet'
+ ),
+ typeOption(
+ 'doc-skill',
+ clause.and(clause.eq('fileType', 'md'), clause.eq('subType', 'skill')),
+ (entity) => entity.type === 'document' && entity.subType?.type === 'skill'
+ ),
+ typeOption(
+ 'file-other',
+ clause.and(
+ clause.eq('fileAssoc', 'assoc:other'),
+ clause.not(
+ clause.or(
+ clause.eq('fileAssoc', 'assoc:document'),
+ clause.eq('fileAssoc', 'assoc:image'),
+ clause.eq('fileAssoc', 'assoc:video')
+ )
+ )
+ ),
+ (entity) => {
+ if (entity.type !== 'document') return false;
+
+ const fileType = entity.fileType ?? '';
+
+ if (['md', 'canvas', 'spreadsheet', 'pdf', 'docx'].includes(fileType)) {
+ return false;
+ }
+ if ((codeFileExtensions as readonly string[]).includes(fileType)) {
+ return false;
+ }
+ if ((IMAGE_EXTENSIONS as readonly string[]).includes(fileType)) {
+ return false;
+ }
+ if ((VIDEO_EXTENSIONS as readonly string[]).includes(fileType)) {
+ return false;
+ }
+
+ return true;
+ }
+ ),
+];
+
+const SEARCH_FILE_TYPES: Record<string, readonly string[] | undefined> = {
+ 'doc-markdown': ['md'],
+ 'doc-canvas': ['canvas'],
+ 'doc-spreadsheet': ['spreadsheet'],
+ 'doc-snippet': ['md'],
+ 'doc-skill': ['md'],
+ 'file-code': codeFileExtensions,
+ 'file-image': IMAGE_EXTENSIONS,
+ 'file-pdf': ['pdf'],
+ 'file-docx': ['docx'],
+ 'file-video': VIDEO_EXTENSIONS,
+};
+
+/** A safe service-search superset; subtype exclusions still run client-side. */
+export function driveSearchFileTypes(
+ ids: readonly string[]
+): string[] | undefined {
+ if (ids.includes('file-other')) return undefined;
+
+ const fileTypes = ids.flatMap((id) => SEARCH_FILE_TYPES[id] ?? []);
+
+ if (fileTypes.length === 0) return undefined;
+
+ return [...new Set(fileTypes)];
+}
+
+function creatorOption(id: string): DriveFacetOption {
+ return {
+ id,
+ clause: {
+ df: clause.eq('documentOwnerId', id),
+ cf: clause.eq('chatOwnerId', id),
+ pf: clause.eq('folderOwnerId', id),
+ },
+ predicate: (entity) => entity.ownerId === id,
+ };
+}
+
+export const DRIVE_FACETS: Facet<
+ DriveFacetEntity,
+ DriveFacetContext,
+ DriveFacetOption
+>[] = [
+ {
+ id: 'type',
+ mode: 'or',
+ restrict: true,
+ options: TYPE_OPTIONS,
+ },
+ { id: 'created-by', mode: 'or', options: creatorOption },
+ {
+ id: TAG_FACET_ID,
+ mode: 'or',
+ options: (optionId, context) =>
+ tagFacetOption<DriveFacetEntity>(optionId, context),
+ },
+];
diff --git a/apps/web/src/features/drive-view/primitives/drive-list.ts b/apps/web/src/features/drive-view/primitives/drive-list.ts
new file mode 100644
index 0000000000..2d8a35cade
--- /dev/null
+++ b/apps/web/src/features/drive-view/primitives/drive-list.ts
@@ -0,0 +1,82 @@
+import { createListController } from '@app/components/list/create-list-controller';
+import { createSignal } from 'solid-js';
+import type { DriveListItem, DriveListSource } from '../context/drive-source';
+
+export type DriveListActivationMetadata = {
+ event?: MouseEvent;
+ newSplit?: boolean;
+};
+
+export type DriveListSnapshot = {
+ focusKey?: string;
+ scrollOffset: number;
+};
+
+/** Entry state can come from an older build or an external navigation target. */
+export function parseDriveListSnapshot(
+ value: unknown
+): DriveListSnapshot | undefined {
+ if (!value || typeof value !== 'object') return;
+
+ const focusKey =
+ 'focusKey' in value && typeof value.focusKey === 'string'
+ ? value.focusKey
+ : undefined;
+
+ const scrollOffset =
+ 'scrollOffset' in value &&
+ typeof value.scrollOffset === 'number' &&
+ Number.isFinite(value.scrollOffset)
+ ? Math.max(0, value.scrollOffset)
+ : 0;
+
+ return { focusKey, scrollOffset };
+}
+
+/** Owned by the workspace, so opening an inline detail does not reset the list. */
+export function createDriveList(options: {
+ source: DriveListSource;
+ initial?: DriveListSnapshot;
+ onActivate: (
+ item: DriveListItem,
+ metadata?: DriveListActivationMetadata
+ ) => void;
+}) {
+ const [scrollOffset, setScrollOffset] = createSignal(
+ options.initial?.scrollOffset ?? 0
+ );
+
+ const controller = createListController<
+ DriveListItem,
+ DriveListActivationMetadata
+ >({
+ items: options.source.items,
+
+ getKey: (row) => row.id,
+
+ onActivate: ({ item, metadata }) => options.onActivate(item, metadata),
+ });
+
+ if (options.initial?.focusKey) {
+ controller.focus.restore(options.initial.focusKey, { reason: 'restore' });
+ }
+
+ return {
+ controller,
+ scrollOffset,
+ setScrollOffset,
+
+ snapshot: (): DriveListSnapshot => ({
+ focusKey: controller.focus.requestedKey(),
+ scrollOffset: scrollOffset(),
+ }),
+
+ reset: () => {
+ controller.selection.clear();
+ controller.focus.clear();
+ setScrollOffset(0);
+ },
+ };
+}
+
+export type DriveListState = ReturnType<typeof createDriveList>;
diff --git a/apps/web/src/features/drive-view/primitives/drive-navigation.test.ts b/apps/web/src/features/drive-view/primitives/drive-navigation.test.ts
deleted file mode 100644
index b2c1d6a860..0000000000
--- a/apps/web/src/features/drive-view/primitives/drive-navigation.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { createRoot, createSignal } from 'solid-js';
-import { describe, expect, it, vi } from 'vitest';
-import type { DriveState } from '../core/types';
-import { createDriveNavigation } from './drive-navigation';
-
-describe('Drive navigation state', () => {
- it('opens ancestors, clears refinements on navigation, and keeps search when filtering', () =>
- createRoot((dispose) => {
- const [state, setState] = createSignal<DriveState>({
- location: { kind: 'tab', tab: 'shared' },
- scope: 'attachments',
- sort: 'created_at',
- expandedFolderIds: ['unrelated'],
- favoritesOpen: false,
- rootOpen: false,
- tagsOpen: false,
- });
- const apply = vi.fn();
- const onNavigate = vi.fn();
- const navigation = createDriveNavigation({
- state,
- setState,
- results: { apply },
- onNavigate,
- folders: () => [
- { id: 'parent', name: 'Parent' },
- { id: 'child', name: 'Child', parentId: 'parent' },
- ],
- });
- navigation.navigate({ kind: 'folder', id: 'child' });
- expect(state().expandedFolderIds).toEqual([
- 'unrelated',
- 'parent',
- 'child',
- ]);
- expect(state()).toMatchObject({
- scope: 'default',
- rootOpen: true,
- favoritesOpen: false,
- tagsOpen: false,
- sort: 'created_at',
- });
- expect(apply).toHaveBeenLastCalledWith(state(), true);
- expect(onNavigate).toHaveBeenCalledOnce();
- navigation.navigate({ kind: 'tab', tab: 'recent' });
- expect(state().location).toEqual({ kind: 'tab', tab: 'recent' });
- navigation.setScope('attachments');
- expect(apply).toHaveBeenLastCalledWith(state(), false);
- dispose();
- }));
-});
diff --git a/apps/web/src/features/drive-view/primitives/drive-navigation.ts b/apps/web/src/features/drive-view/primitives/drive-navigation.ts
deleted file mode 100644
index e7e4f069d7..0000000000
--- a/apps/web/src/features/drive-view/primitives/drive-navigation.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { type Accessor, batch, type Setter } from 'solid-js';
-import type { DriveResults } from '../context/drive-source';
-import { folderAncestors } from '../core/folder-tree';
-import type {
- DriveFolder,
- DriveLocation,
- DriveScope,
- DriveState,
-} from '../core/types';
-
-export function createDriveNavigation(options: {
- state: Accessor<DriveState>;
- setState: Setter<DriveState>;
- folders: Accessor<DriveFolder[]>;
- results: DriveResults;
- onNavigate: () => void;
-}) {
- const navigate = (location: DriveLocation) => {
- const ancestors =
- location.kind === 'folder' && location.id
- ? folderAncestors(options.folders(), location.id).map(
- (folder) => folder.id
- )
- : [];
- const current = options.state();
- const next: DriveState = {
- ...current,
- location,
- scope: 'default',
- rootOpen: true,
- expandedFolderIds: [
- ...new Set([...current.expandedFolderIds, ...ancestors]),
- ],
- };
- batch(() => {
- options.setState(next);
- options.results.apply(next, true);
- options.onNavigate();
- });
- };
- const setScope = (scope: DriveScope) =>
- batch(() => {
- const next = { ...options.state(), scope };
- options.setState(next);
- options.results.apply(next, false);
- });
- return { navigate, setScope };
-}
diff --git a/apps/web/src/features/drive-view/primitives/drive-state.ts b/apps/web/src/features/drive-view/primitives/drive-state.ts
new file mode 100644
index 0000000000..77e85f8616
--- /dev/null
+++ b/apps/web/src/features/drive-view/primitives/drive-state.ts
@@ -0,0 +1,132 @@
+import { normalizeFacetSelection } from '@app/features/soup/filters/facets/selection';
+import { type Accessor, batch, type Setter } from 'solid-js';
+import type { DriveFolderMetadata } from '../context/drive-source';
+import { folderAncestors } from '../core/folder-tree';
+import type {
+ DriveLocation,
+ DriveScope,
+ DriveSort,
+ DriveState,
+ DriveTab,
+} from '../core/types';
+import type { DriveListState } from './drive-list';
+
+/** Shared navigation and controls. Display derivations stay with their consumers. */
+export function createDriveState(options: {
+ state: Accessor<DriveState>;
+ setState: Setter<DriveState>;
+ folders: Accessor<DriveFolderMetadata[]>;
+ list: DriveListState;
+ showList: () => void;
+}) {
+ const { state, setState, list } = options;
+
+ const projectId = () => {
+ const location = state().location;
+
+ if (location.kind !== 'folder') return undefined;
+
+ return location.id ?? undefined;
+ };
+
+ const navigate = (location: DriveLocation) => {
+ const current = state();
+
+ const expandedFolderIds = new Set(current.expandedFolderIds);
+
+ if (location.kind === 'folder' && location.id) {
+ for (const folder of folderAncestors(options.folders(), location.id)) {
+ expandedFolderIds.add(folder.id);
+ }
+ }
+
+ batch(() => {
+ setState({
+ ...current,
+ location,
+ scope: 'default',
+ facets: {},
+ search: '',
+ rootOpen: true,
+ expandedFolderIds: [...expandedFolderIds],
+ });
+
+ list.reset();
+ options.showList();
+ });
+ };
+
+ const updateFilter = (update: () => void) =>
+ batch(() => {
+ list.reset();
+ update();
+ });
+
+ const setFacetSelected = (facetId: string, id: string, selected: boolean) =>
+ updateFilter(() => {
+ const facets = state().facets;
+
+ const values = (facets[facetId] ?? []).filter((value) => value !== id);
+
+ if (selected) values.push(id);
+
+ setState((current) => ({
+ ...current,
+ facets: normalizeFacetSelection({ ...facets, [facetId]: values }),
+ }));
+ });
+
+ return {
+ value: state,
+ projectId,
+ navigate,
+
+ selectTab: (tab: DriveTab) => navigate({ kind: 'tab', tab }),
+
+ selectFolder: (id: string | null) => navigate({ kind: 'folder', id }),
+
+ setScope: (scope: DriveScope) =>
+ updateFilter(() => {
+ setState((current) => ({ ...current, scope, facets: {} }));
+ }),
+
+ setSort: (sort: DriveSort) => setState((current) => ({ ...current, sort })),
+
+ setSearch: (search: string) =>
+ updateFilter(() => setState((current) => ({ ...current, search }))),
+
+ setFacetSelected,
+
+ setTags: (ids: string[]) =>
+ updateFilter(() => {
+ setState((current) => ({
+ ...current,
+ facets: normalizeFacetSelection({ ...current.facets, tags: ids }),
+ }));
+
+ options.showList();
+ }),
+
+ clearFilters: () =>
+ updateFilter(() => {
+ setState((current) => ({ ...current, scope: 'default', facets: {} }));
+ }),
+
+ toggleFolder: (id: string) =>
+ setState((current) => ({
+ ...current,
+ expandedFolderIds: current.expandedFolderIds.includes(id)
+ ? current.expandedFolderIds.filter((value) => value !== id)
+ : [...current.expandedFolderIds, id],
+ })),
+
+ setFavoritesOpen: (favoritesOpen: boolean) =>
+ setState((current) => ({ ...current, favoritesOpen })),
+
+ setRootOpen: (rootOpen: boolean) =>
+ setState((current) => ({ ...current, rootOpen })),
+
+ setTagsOpen: (tagsOpen: boolean) =>
+ setState((current) => ({ ...current, tagsOpen })),
+ };
+}
diff --git a/apps/web/src/features/drive-view/queries/drive-data-source.ts b/apps/web/src/features/drive-view/queries/drive-data-source.ts
new file mode 100644
index 0000000000..8e79feeb79
--- /dev/null
+++ b/apps/web/src/features/drive-view/queries/drive-data-source.ts
@@ -0,0 +1,240 @@
+import { buildFlatSoupRows } from '@app/features/soup/collection/rows';
+import { withEntityNotifications } from '@app/features/soup/entity-notifications';
+import {
+ createTagFacetContext,
+ tagFacetReady,
+ testFacets,
+} from '@app/features/soup/filters';
+import {
+ createSearchState,
+ useOptionalSearchContext,
+} from '@app/features/soup/search';
+import { enableSnippets, isFeatureEnabled } from '@core/constant/featureFlags';
+import type { EntityData } from '@entity';
+import type { NotificationSource } from '@notifications';
+import { useSoupAstItemsQuery } from '@queries/soup/items';
+import {
+ isDisplayableSoupItem,
+ mapApiSoupItemToEntity,
+} from '@queries/soup/transform-utils';
+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';
+import { type Accessor, createMemo } from 'solid-js';
+import type { DriveListSource, DriveSelection } from '../context/drive-source';
+import { DRIVE_FACETS } from '../filters/drive-facets';
+import { buildDriveQuery } from './drive-query';
+import {
+ driveEntityMatchesLocation,
+ orderDriveEntities,
+} from './drive-results';
+import { buildDriveSearchRequest } from './drive-search';
+
+/** Query, local/service search and row assembly owned by Drive. */
+export function createDriveDataSource(options: {
+ selection: Accessor<DriveSelection>;
+ userId: Accessor<string | undefined>;
+ tagSets: Accessor<readonly TagSetResponse[]>;
+ tagSetsReady: Accessor<boolean>;
+ notificationSource: NotificationSource;
+}): DriveListSource {
+ const { selection, userId, notificationSource } = options;
+
+ const searchContext = useOptionalSearchContext();
+
+ const facetContext = createMemo(() =>
+ createTagFacetContext(options.tagSets())
+ );
+
+ const facetsReady = () =>
+ tagFacetReady(selection().facets, options.tagSetsReady());
+
+ const query = useSoupAstItemsQuery(
+ () =>
+ buildDriveQuery({
+ selection: selection(),
+ userId: userId(),
+ facetContext: facetContext(),
+ snippetsEnabled: isFeatureEnabled(enableSnippets),
+ }),
+ () => {
+ // Bind optimistic cache membership to this query, not a later location.
+ const current = selection();
+
+ const viewer = userId();
+
+ const context = facetContext();
+
+ return {
+ enabled: Boolean(viewer) && facetsReady() && !current.search.trim(),
+ meta: {
+ // REST inserts omit attachment status. Let a scoped server refetch
+ // admit them rather than inserting an unverifiable document.
+ insertFilter: (item) =>
+ current.scope === 'all' || item.tag !== 'document',
+
+ itemFilter: (item) => {
+ if (!isDisplayableSoupItem(item)) return false;
+
+ const entity = mapApiSoupItemToEntity(item);
+
+ if (!driveEntityMatchesLocation(entity, current, viewer))
+ return false;
+
+ return testFacets(current.facets, DRIVE_FACETS, entity, context);
+ },
+ },
+ };
+ }
+ );
+
+ // Cold REST data suspends; keep the shell and its controls available.
+ const queryData = () => (query.isLoading ? undefined : query.data);
+
+ const matchesFacets = (entity: EntityData) =>
+ testFacets(selection().facets, DRIVE_FACETS, entity, facetContext());
+
+ const localPool = createMemo(() => {
+ const attachmentScoped = selection().scope !== 'all';
+
+ const admittedDocuments = new Set<string>();
+
+ if (attachmentScoped && !query.isPlaceholderData) {
+ for (const entity of queryData()?.entities ?? []) {
+ if (entity.type === 'document') admittedDocuments.add(entity.id);
+ }
+ }
+
+ return (searchContext?.entityPool() ?? []).filter(({ data: entity }) => {
+ if (!driveEntityMatchesLocation(entity, selection(), userId()))
+ return false;
+ if (!matchesFacets(entity)) return false;
+ if (entity.type !== 'document' || !attachmentScoped) return true;
+
+ // Local documents lack attachment status: trust only membership already
+ // established by this exact scoped query, never another view's cache.
+ return admittedDocuments.has(entity.id);
+ });
+ });
+
+ const search = createSearchState({
+ text: () => selection().search,
+
+ enabled: facetsReady,
+ localPool,
+
+ buildRequest: (request) =>
+ buildDriveSearchRequest({
+ ...request,
+ selection: selection(),
+ userId: userId(),
+ facetContext: facetContext(),
+ }),
+ });
+
+ const rawEntities = createMemo<EntityData[]>((previous) => {
+ if (!search.isSearching()) {
+ if (query.isPlaceholderData) return [];
+
+ return queryData()?.entities ?? [];
+ }
+
+ const results = search.data();
+
+ if (results.length === 0 && search.isLocalSearchSettling()) return previous;
+
+ return results;
+ }, []);
+
+ const entities = createMemo(() => {
+ if (!facetsReady()) return [];
+
+ const matching = rawEntities().filter((entity) => {
+ const matchesLocation = driveEntityMatchesLocation(
+ entity,
+ selection(),
+ userId(),
+ {
+ trustFolderMembership: true,
+ }
+ );
+
+ return matchesLocation && matchesFacets(entity);
+ });
+
+ return orderDriveEntities(matching, selection(), search.featuredIds()).map(
+ (entity) => withEntityNotifications(entity, notificationSource)
+ );
+ });
+
+ const items = createMemo(() => buildFlatSoupRows(entities()));
+
+ const isFetching = () => {
+ if (search.isSearching())
+ return search.isFetching() || search.isLocalSearchSettling();
+
+ return query.isFetching;
+ };
+
+ const hasMore = () =>
+ search.isSearching() ? search.hasNextPage() : query.hasNextPage;
+
+ const error = () => {
+ if (search.isSearching()) return search.error();
+
+ return query.error ?? undefined;
+ };
+
+ return {
+ items,
+
+ isLoading: () => {
+ if (items().length > 0) return false;
+ if (!facetsReady()) return true;
+ if (search.isSearching()) return isFetching();
+
+ return query.isLoading || query.isFetching;
+ },
+
+ isFetching,
+
+ error,
+
+ hasData: () => {
+ if (search.isSearching())
+ return items().length > 0 || (!isFetching() && !error());
+
+ return queryData() !== undefined && !query.isPlaceholderData;
+ },
+
+ hasMore,
+
+ isLoadingMore: () =>
+ search.isSearching()
+ ? search.isFetchingNextPage()
+ : query.isFetchingNextPage,
+
+ loadMore: async () => {
+ if (isFetching() || !hasMore()) return;
+
+ if (search.isSearching()) await search.fetchNextPage();
+ else await query.fetchNextPage();
+
+ // Both transports can resolve failed page requests instead of rejecting.
+ const failure = error();
+
+ if (failure) throw failure;
+ },
+
+ refresh: async () => {
+ if (search.isSearching()) await search.refresh();
+ else await query.refresh();
+ },
+
+ featuredIds: search.featuredIds,
+
+ deferInteractions: () => {
+ if (search.isSearching()) return search.isLocalSearchSettling();
+
+ return query.isFetching && query.isPlaceholderData;
+ },
+ };
+}
diff --git a/apps/web/src/features/drive-view/queries/drive-query.test.ts b/apps/web/src/features/drive-view/queries/drive-query.test.ts
index 4eb594b1b5..2fef49c4b3 100644
--- a/apps/web/src/features/drive-view/queries/drive-query.test.ts
+++ b/apps/web/src/features/drive-view/queries/drive-query.test.ts
@@ -1,77 +1,164 @@
-import { describe, expect, it, vi } from 'vitest';
-
-vi.mock('@core/constant/featureFlags', () => ({
- enableCalendarUi: {},
- enableReminders: {},
- enableSnippets: {},
- enableSupportedSoupForeignEntities: {},
- isCalendarSearchUiEnabled: () => false,
- isFeatureEnabled: () => false,
-}));
-
-import {
- compileToAst,
- queryStateFrom,
-} from '@app/features/next-soup/filters/filter-store';
+import { NIL_UUID, type TagFacetContext } from '@app/features/soup/filters';
+import { describe, expect, it } from 'vitest';
import type { DriveSelection } from '../context/drive-source';
-import { driveFilterTab, driveQuery } from './drive-query';
+import { buildDriveQuery } from './drive-query';
+
+const facetContext: TagFacetContext = {
+ tagPropertyDefinitionByOptionId: new Map([['urgent', 'tag-definition']]),
+};
const selection: DriveSelection = {
location: { kind: 'tab', tab: 'owned' },
scope: 'default',
sort: 'updated_at',
+ search: '',
+ facets: {},
};
-describe('Drive query scopes', () => {
- it('keeps owned/shared scopes and excludes tasks and disabled snippets', () => {
- const owned = driveQuery(selection, 'me');
- expect(driveFilterTab(selection)).toBe('owned');
- expect(owned.filters.include?.documentOwnerId).toEqual(['me']);
- expect(owned.filters.exclude?.subType).toEqual(['task', 'snippet']);
- const shared = driveQuery(
- { ...selection, location: { kind: 'tab', tab: 'shared' } },
- 'me'
- );
- expect(shared.filters.exclude?.documentOwnerId).toEqual(['me']);
- expect(shared.clientFilters.and).toContain('shared-entity');
+function request(
+ selected: DriveSelection = selection,
+ userId: string | undefined = 'me'
+) {
+ return buildDriveQuery({
+ selection: selected,
+ userId,
+ facetContext,
+ snippetsEnabled: true,
});
- it('allows all files and attachments without retaining the owned restriction', () => {
- expect(driveFilterTab({ ...selection, scope: 'all' })).toBe('all');
- expect(driveFilterTab({ ...selection, scope: 'attachments' })).toBe(
- 'attachments'
- );
- const all = driveQuery({ ...selection, scope: 'all' }, 'me');
- expect(all.filters.include?.documentOwnerId).toBeUndefined();
- const attachments = driveQuery(
- { ...selection, scope: 'attachments' },
- 'me'
- );
- expect(attachments.filters.include?.isEmailAttachment).toBe(true);
- expect(attachments.filters.include?.documentOwnerId).toBeUndefined();
+}
+
+describe('buildDriveQuery', () => {
+ it('builds the owned/default document scope and request params', () => {
+ const result = request();
+
+ expect(result.params).toEqual({
+ expand: true,
+ limit: 100,
+ sort_method: 'updated_at',
+ sort_direction: 'desc',
+ });
+ expect(result.body.df).toEqual({
+ '&': [
+ {
+ '&': [{ '!': { l: { dst: 'task' } } }, { l: { iea: false } }],
+ },
+ { l: { o: 'me' } },
+ ],
+ });
+ expect(result.body.ef).toEqual({ l: { ThreadId: NIL_UUID } });
+ expect(result.body.cf).toEqual({ l: { cid: NIL_UUID } });
+ expect(result.body.pf).toEqual({ l: { pid: NIL_UUID } });
});
- it('scopes every supported folder entity type to the selected folder', () => {
- const folder = driveQuery(
- { ...selection, location: { kind: 'folder', id: 'folder' } },
- 'me'
+
+ it('excludes disabled snippets before paginating the list', () => {
+ const result = buildDriveQuery({ selection, userId: 'me', facetContext });
+ expect(JSON.stringify(result.body.df)).toContain(
+ '"!":{"l":{"dst":"snippet"}}'
);
- expect(folder.filters.include).toMatchObject({
- projectId: ['folder'],
- chatProjectId: ['folder'],
- folderId: ['folder'],
- emailProjectId: ['folder'],
+ expect(JSON.stringify(request().body.df)).not.toContain('snippet');
+ });
+
+ it('drops owned scoping outside default and maps attachment scope', () => {
+ const all = request({ ...selection, scope: 'all' });
+ expect(all.body.df).toEqual({ '!': { l: { dst: 'task' } } });
+
+ const attachments = request({ ...selection, scope: 'attachments' });
+ expect(attachments.body.df).toEqual({
+ '&': [{ '!': { l: { dst: 'task' } } }, { l: { iea: true } }],
});
- expect(folder.filters.emailView).toBe('all');
- expect(folder.clientFilters).toEqual({});
});
- it('keeps Recent compatible with the touched feed and restricts display to files', () => {
- const recent = driveQuery(
- { ...selection, location: { kind: 'tab', tab: 'recent' } },
- 'me'
- );
- const ast = compileToAst(queryStateFrom(recent.filters));
- expect(ast.chanf).toBeUndefined();
- expect(ast.ef).toBeUndefined();
- expect(recent.clientFilters.and).toEqual(['document-or-file']);
- expect(recent.filters.exclude?.subType).toContain('task');
+
+ it('keeps shared exclusion when a creator facet is selected', () => {
+ const shared = request({
+ ...selection,
+ location: { kind: 'tab', tab: 'shared' },
+ facets: { 'created-by': ['creator-1'] },
+ });
+
+ expect(shared.body.df).toEqual({
+ '&': [
+ {
+ '&': [
+ {
+ '&': [{ '!': { l: { dst: 'task' } } }, { l: { iea: false } }],
+ },
+ { '!': { l: { o: 'me' } } },
+ ],
+ },
+ { l: { o: 'creator-1' } },
+ ],
+ });
+ });
+
+ it('matches nothing for an owner-dependent tab without a user', () => {
+ const owned = buildDriveQuery({
+ selection,
+ userId: undefined,
+ facetContext,
+ });
+ expect(owned.body.df).toEqual({ l: { id: NIL_UUID } });
+
+ const shared = buildDriveQuery({
+ selection: {
+ ...selection,
+ location: { kind: 'tab', tab: 'shared' },
+ },
+ userId: undefined,
+ facetContext,
+ });
+ expect(shared.body.df).toEqual({ l: { id: NIL_UUID } });
+ });
+
+ it('allows only projects at the Drive root', () => {
+ const root = request({
+ ...selection,
+ location: { kind: 'folder', id: null },
+ });
+
+ expect(root.body.pf).toBeUndefined();
+ expect(root.body.df).toEqual({ l: { id: NIL_UUID } });
+ expect(root.body.cf).toEqual({ l: { cid: NIL_UUID } });
+ expect(root.body.ef).toEqual({ l: { ThreadId: NIL_UUID } });
+ });
+
+ it('scopes every supported folder entity type to its parent', () => {
+ const folder = request({
+ ...selection,
+ location: { kind: 'folder', id: 'folder-1' },
+ });
+
+ expect(folder.body.df).toEqual({
+ '&': [{ l: { pid: 'folder-1' } }, { l: { iea: false } }],
+ });
+ expect(folder.body.cf).toEqual({ l: { pid: 'folder-1' } });
+ expect(folder.body.pf).toEqual({ l: { pid: 'folder-1' } });
+ expect(folder.body.ef).toEqual({ l: { ProjectId: 'folder-1' } });
+ expect(folder.body.emailView).toBe('all');
+ expect(folder.body.chanf).toEqual({ l: { ChannelId: NIL_UUID } });
+ });
+
+ it('combines type and tag facets with the base scope', () => {
+ const filtered = request({
+ ...selection,
+ facets: { type: ['file-pdf'], tags: ['urgent'] },
+ });
+
+ expect(JSON.stringify(filtered.body.df)).toContain('"ft":"pdf"');
+ expect(filtered.body.propf).toEqual({
+ l: { pd: 'tag-definition', v: { so: 'urgent' } },
+ });
+ });
+
+ it('uses touched_by_me for Recent without unsupported email/channel trees', () => {
+ const recent = request({
+ ...selection,
+ location: { kind: 'tab', tab: 'recent' },
+ facets: { type: ['file-pdf'] },
+ });
+
+ expect(recent.params.sort_method).toBe('touched_by_me');
+ expect(recent.body.ef).toBeUndefined();
+ expect(recent.body.chanf).toBeUndefined();
+ expect(JSON.stringify(recent.body.df)).toContain('"ft":"pdf"');
});
});
diff --git a/apps/web/src/features/drive-view/queries/drive-query.ts b/apps/web/src/features/drive-view/queries/drive-query.ts
index 6ba85e0f1b..f94ab8ad0c 100644
--- a/apps/web/src/features/drive-view/queries/drive-query.ts
+++ b/apps/web/src/features/drive-view/queries/drive-query.ts
@@ -1,76 +1,171 @@
import {
- defineQueryFilters,
- type Query,
-} from '@app/features/next-soup/filters/filter-store';
-import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-presets';
+ type BackendAstMap,
+ type BackendAstNode,
+ combine,
+ compileFacets,
+ literal,
+ mergeAst,
+ NIL_UUID,
+ type TagFacetContext,
+} from '@app/features/soup/filters';
+import type { SoupAstBody, SoupAstItemsQueryArgs } from '@queries/soup/items';
import type { DriveSelection } from '../context/drive-source';
+import { DRIVE_FACETS } from '../filters/drive-facets';
-/** Match the legacy filter controller's base tab to the current Drive scope. */
-export function driveFilterTab(state: DriveSelection) {
- const location = state.location;
- if (location.kind === 'folder') return location.id ? 'all' : 'folders';
- if (location.tab === 'owned' && state.scope !== 'default') return state.scope;
- return location.tab;
+export type BuildDriveQueryOptions = {
+ selection: DriveSelection;
+ userId: string | undefined;
+ facetContext: TagFacetContext;
+ snippetsEnabled?: boolean;
+};
+
+type DriveAstBody = BackendAstMap & Pick<SoupAstBody, 'emailView'>;
+
+function excludedEntityTargets(): BackendAstMap {
+ return {
+ asf: literal('id', NIL_UUID),
+ calf: literal('id', NIL_UUID),
+ callf: literal('CallId', NIL_UUID),
+ ccf: literal('id', NIL_UUID),
+ cf: literal('cid', NIL_UUID),
+ chanf: literal('ChannelId', NIL_UUID),
+ cthf: literal('ChannelId', NIL_UUID),
+ df: literal('id', NIL_UUID),
+ ef: literal('ThreadId', NIL_UUID),
+ fef: literal('id', NIL_UUID),
+ pf: literal('pid', NIL_UUID),
+ remf: literal('id', NIL_UUID),
+ };
+}
+
+function attachmentScope(
+ selection: DriveSelection
+): BackendAstNode | undefined {
+ if (selection.scope === 'default') return literal('iea', false);
+ if (selection.scope === 'attachments') return literal('iea', true);
+
+ return undefined;
}
-export function driveQuery(state: DriveSelection, userId: string | undefined) {
- const context = { userId, isTeamAdmin: false };
- const location = state.location;
- if (location.kind === 'folder') {
- if (!location.id) return getViewPreset('documents', 'folders', context)!;
- return {
- filters: defineQueryFilters({
- include: {
- projectId: [location.id],
- chatProjectId: [location.id],
- folderId: [location.id],
- emailProjectId: [location.id],
- },
- emailView: 'all',
- }),
- clientFilters: {},
- };
+function tabDocumentScope(
+ selection: DriveSelection,
+ userId: string | undefined,
+ snippetsEnabled: boolean
+): BackendAstNode {
+ const nodes: BackendAstNode[] = [{ '!': literal('dst', 'task') }];
+
+ if (!snippetsEnabled) nodes.push({ '!': literal('dst', 'snippet') });
+
+ const attachment = attachmentScope(selection);
+
+ if (attachment) nodes.push(attachment);
+
+ const location = selection.location;
+
+ if (location.kind !== 'tab') {
+ return combine('&', nodes) ?? literal('id', NIL_UUID);
}
- if (location.tab === 'recent') {
- const recent = getViewPreset('recent', undefined, context)!;
- const files = getViewPreset('documents', 'all', context)!;
- return {
- filters: {
- ...recent.filters,
- exclude: {
- ...recent.filters.exclude,
- subType: files.filters.exclude?.subType,
- },
- include: {
- ...recent.filters.include,
- isEmailAttachment:
- state.scope === 'all' ? undefined : state.scope === 'attachments',
- },
- } satisfies Query,
- clientFilters: { and: ['document-or-file'] },
- };
+
+ if (location.tab === 'owned' && selection.scope === 'default') {
+ if (!userId) return literal('id', NIL_UUID);
+
+ nodes.push(literal('o', userId));
}
- const tab = driveFilterTab(state);
- const preset =
- getViewPreset('documents', tab, context) ??
- getViewPreset('documents', 'all', context)!;
- if (state.scope === 'attachments') {
- return {
- ...preset,
- filters: {
- ...preset.filters,
- include: { ...preset.filters.include, isEmailAttachment: true },
- },
- };
+
+ if (location.tab === 'shared') {
+ if (!userId) return literal('id', NIL_UUID);
+
+ nodes.push({ '!': literal('o', userId) });
}
- if (state.scope === 'all') {
- return {
- ...preset,
- filters: {
- ...preset.filters,
- include: { ...preset.filters.include, isEmailAttachment: undefined },
- },
- };
+
+ return combine('&', nodes) ?? literal('id', NIL_UUID);
+}
+
+function selectedFolderDocumentScope(
+ selection: DriveSelection,
+ folderId: string
+): BackendAstNode {
+ const nodes = [literal('pid', folderId)];
+
+ const attachment = attachmentScope(selection);
+
+ if (attachment) nodes.push(attachment);
+
+ return combine('&', nodes) ?? literal('id', NIL_UUID);
+}
+
+function baseBody(
+ selection: DriveSelection,
+ userId: string | undefined,
+ snippetsEnabled: boolean
+): DriveAstBody {
+ const body: DriveAstBody = excludedEntityTargets();
+
+ const location = selection.location;
+
+ if (location.kind === 'tab') {
+ body.df = tabDocumentScope(selection, userId, snippetsEnabled);
+
+ return body;
+ }
+
+ if (location.id === null) {
+ delete body.pf;
+
+ return body;
}
- return preset;
+
+ body.df = selectedFolderDocumentScope(selection, location.id);
+ body.cf = literal('pid', location.id);
+ body.ef = literal('ProjectId', location.id);
+ body.pf = literal('pid', location.id);
+ body.emailView = 'all';
+
+ return body;
+}
+
+function omitUnsupportedRecentTargets(body: DriveAstBody): DriveAstBody {
+ const supported = { ...body };
+
+ delete supported.ef;
+ delete supported.chanf;
+
+ return supported;
+}
+
+/** Builds the Soup AST for Drive without relying on legacy query state. */
+export function buildDriveQuery(
+ options: BuildDriveQueryOptions
+): SoupAstItemsQueryArgs {
+ const { selection } = options;
+
+ const facets = compileFacets(
+ selection.facets,
+ DRIVE_FACETS,
+ options.facetContext
+ );
+
+ let body: DriveAstBody = mergeAst(
+ baseBody(selection, options.userId, options.snippetsEnabled ?? false),
+ facets
+ );
+
+ let sortMethod: DriveSelection['sort'] | 'touched_by_me' = selection.sort;
+
+ const location = selection.location;
+
+ if (location.kind === 'tab' && location.tab === 'recent') {
+ sortMethod = 'touched_by_me';
+ body = omitUnsupportedRecentTargets(body);
+ }
+
+ return {
+ params: {
+ expand: true,
+ limit: 100,
+ sort_method: sortMethod,
+ sort_direction: 'desc',
+ },
+ body,
+ };
}
diff --git a/apps/web/src/features/drive-view/queries/drive-results.ts b/apps/web/src/features/drive-view/queries/drive-results.ts
index 8e491c0ab5..7f1219574b 100644
--- a/apps/web/src/features/drive-view/queries/drive-results.ts
+++ b/apps/web/src/features/drive-view/queries/drive-results.ts
@@ -1,23 +1,100 @@
-import type { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';
-import type { Accessor } from 'solid-js';
-import type { DriveResults } from '../context/drive-source';
-import { driveFilterTab, driveQuery } from './drive-query';
-
-export function createDriveResults(
- view: ReturnType<typeof useSoupView>,
- userId: Accessor<string | undefined>
-): DriveResults {
- return {
- apply(selection, clearSearch) {
- const preset = driveQuery(selection, userId());
- view.setActiveTab(driveFilterTab(selection));
- view.queryFilters.replace(preset.filters);
- view.soup.predicates.set(preset.clientFilters);
- view.soup.grouping.setActiveGroupId(undefined);
- view.soup.sort.setAll([selection.sort]);
- view.soup.selection.clear();
- view.soup.focus.clear();
- if (clearSearch) view.setSearchText('');
- },
+import { enableSnippets, isFeatureEnabled } from '@core/constant/featureFlags';
+import { compareDateDesc } from '@core/util/date';
+import type { DocumentEntity, EntityData } from '@entity';
+import type { DriveSelection } from '../context/drive-source';
+import type { DriveScope, DriveTab } from '../core/types';
+
+function documentMatchesTab(
+ entity: DocumentEntity,
+ tab: DriveTab,
+ scope: DriveScope,
+ userId: string | undefined
+): boolean {
+ if (entity.subType?.type === 'task') return false;
+ if (entity.subType?.type === 'snippet' && !isFeatureEnabled(enableSnippets))
+ return false;
+ if (tab === 'shared') return Boolean(userId) && entity.ownerId !== userId;
+ if (tab === 'owned' && scope === 'default') return entity.ownerId === userId;
+
+ return true;
+}
+
+function entityMatchesFolder(
+ entity: EntityData,
+ projectId: string,
+ trustMembership: boolean
+): boolean {
+ switch (entity.type) {
+ case 'document':
+ case 'chat':
+ case 'project':
+ return entity.projectId === projectId;
+ case 'email':
+ if (entity.projectId) return entity.projectId === projectId;
+ // Only fetched, folder-scoped results may omit this metadata.
+ return trustMembership;
+ default:
+ return false;
+ }
+}
+
+/** Backstop location scoping for local search and normalized cache updates. */
+export function driveEntityMatchesLocation(
+ entity: EntityData,
+ selection: DriveSelection,
+ userId: string | undefined,
+ options: { trustFolderMembership?: boolean } = {}
+): boolean {
+ const { location } = selection;
+
+ if (location.kind === 'folder') {
+ if (!location.id) return entity.type === 'project';
+
+ return entityMatchesFolder(
+ entity,
+ location.id,
+ options.trustFolderMembership ?? false
+ );
+ }
+
+ if (entity.type !== 'document') return false;
+
+ return documentMatchesTab(entity, location.tab, selection.scope, userId);
+}
+
+/** Preserve recency sorting and the local-search featured prefix. */
+export function orderDriveEntities(
+ entities: readonly EntityData[],
+ selection: DriveSelection,
+ featuredIds: readonly string[]
+): EntityData[] {
+ const { location, sort } = selection;
+
+ if (location.kind === 'tab' && location.tab === 'recent')
+ return [...entities];
+
+ const timestamp = (entity: EntityData) => {
+ if (sort === 'created_at') return entity.sortTs ?? entity.createdAt;
+ if (sort === 'viewed_at') return entity.sortTs ?? entity.viewedAt;
+
+ return entity.sortTs ?? entity.updatedAt;
};
+
+ const ordered = [...entities].sort((a, b) =>
+ compareDateDesc(timestamp(a), timestamp(b))
+ );
+
+ if (featuredIds.length === 0) return ordered;
+
+ const featured = new Set(featuredIds);
+
+ const byId = new Map(ordered.map((entity) => [entity.id, entity]));
+
+ const prefix = featuredIds.flatMap((id) => {
+ const entity = byId.get(id);
+
+ return entity ? [entity] : [];
+ });
+
+ return [...prefix, ...ordered.filter((entity) => !featured.has(entity.id))];
}
diff --git a/apps/web/src/features/drive-view/queries/drive-search.ts b/apps/web/src/features/drive-view/queries/drive-search.ts
new file mode 100644
index 0000000000..bb6082166c
--- /dev/null
+++ b/apps/web/src/features/drive-view/queries/drive-search.ts
@@ -0,0 +1,181 @@
+import { NIL_UUID, type TagFacetContext } from '@app/features/soup/filters';
+import type { SoupSearchMatchType } from '@app/features/soup/search';
+import type { SearchSoupQueryArgs } from '@queries/soup/search';
+import type {
+ DocumentFilters,
+ EntityFilters,
+} from '@service-search/generated/models';
+import type { DriveSelection } from '../context/drive-source';
+import { driveSearchFileTypes } from '../filters/drive-facets';
+
+export type BuildDriveSearchRequestOptions = {
+ selection: DriveSelection;
+ userId: string | undefined;
+ facetContext: TagFacetContext;
+ query: string;
+ matchType: SoupSearchMatchType;
+};
+
+function excludedEntityFilters(): EntityFilters {
+ return {
+ agent_session_filters: { ids: [NIL_UUID] },
+ calendar_event_filters: { calendar_event_ids: [NIL_UUID] },
+ call_filters: { call_ids: [NIL_UUID] },
+ channel_filters: { channel_ids: [NIL_UUID] },
+ channel_thread_filters: { thread_ids: [NIL_UUID] },
+ chat_filters: { chat_ids: [NIL_UUID] },
+ crm_company_filters: { company_ids: [NIL_UUID] },
+ document_filters: { document_ids: [NIL_UUID] },
+ email_filters: { email_thread_ids: [NIL_UUID] },
+ foreign_entity_filters: { ids: [NIL_UUID] },
+ project_filters: { project_ids: [NIL_UUID] },
+ reminder_filters: { ids: [NIL_UUID] },
+ };
+}
+
+function attachmentFilter(selection: DriveSelection): boolean | undefined {
+ if (selection.scope === 'default') return false;
+ if (selection.scope === 'attachments') return true;
+
+ return undefined;
+}
+
+function selectedCreators(selection: DriveSelection): string[] | undefined {
+ const creators = [...new Set(selection.facets['created-by'] ?? [])];
+
+ if (creators.length === 0) return undefined;
+
+ return creators;
+}
+
+function documentOwners(
+ selection: DriveSelection,
+ userId: string | undefined
+): string[] | undefined {
+ const creators = selectedCreators(selection);
+
+ const location = selection.location;
+
+ if (location.kind !== 'tab') return creators;
+
+ if (location.tab === 'owned' && selection.scope === 'default') {
+ if (!userId) return [NIL_UUID];
+ if (creators && !creators.includes(userId)) return [NIL_UUID];
+
+ return [userId];
+ }
+
+ if (location.tab === 'shared') {
+ if (!userId) return [NIL_UUID];
+
+ if (creators) {
+ const others = creators.filter((id) => id !== userId);
+
+ return others.length > 0 ? others : [NIL_UUID];
+ }
+ }
+
+ return creators;
+}
+
+function documentFilters(
+ selection: DriveSelection,
+ userId: string | undefined
+): DocumentFilters {
+ const filters: DocumentFilters = {};
+
+ const attachment = attachmentFilter(selection);
+
+ if (attachment !== undefined) {
+ filters.is_email_attachment = attachment;
+ }
+
+ const owners = documentOwners(selection, userId);
+
+ if (owners) filters.owners = owners;
+
+ const fileTypes = driveSearchFileTypes(selection.facets.type ?? []);
+
+ if (fileTypes) filters.file_types = fileTypes;
+
+ return filters;
+}
+
+function applyTags(
+ filters: EntityFilters,
+ selection: DriveSelection,
+ facetContext: TagFacetContext
+): void {
+ const selected = [...new Set(selection.facets.tags ?? [])];
+
+ const resolved = selected.filter((id) =>
+ facetContext.tagPropertyDefinitionByOptionId.has(id)
+ );
+ if (resolved.length === 0) return;
+
+ filters.tag_option_ids = resolved;
+ filters.tag_filter_mode = 'any';
+}
+
+function filtersForSelection(
+ selection: DriveSelection,
+ userId: string | undefined,
+ facetContext: TagFacetContext
+): EntityFilters {
+ const filters = excludedEntityFilters();
+
+ const location = selection.location;
+
+ const creators = selectedCreators(selection);
+
+ if (location.kind === 'tab') {
+ filters.document_filters = documentFilters(selection, userId);
+ } else if (location.id === null) {
+ filters.project_filters = {};
+
+ if (creators) filters.project_filters.owners = creators;
+ } else {
+ const documents = documentFilters(selection, userId);
+
+ documents.project_ids = [location.id];
+ filters.document_filters = documents;
+
+ filters.chat_filters = { project_ids: [location.id] };
+ filters.project_filters = { project_ids: [location.id] };
+
+ if (creators) {
+ filters.chat_filters.owners = creators;
+ filters.project_filters.owners = creators;
+ }
+
+ // Email search has no owner field, so creator selection is completed by
+ // Drive's client predicate after fetching the folder-scoped candidates.
+ filters.email_filters = { project_ids: [location.id] };
+ }
+
+ // Finite file-type and creator refinements narrow service pages. Negative
+ // subtype/ownership constraints still need Drive's exact client predicates;
+ // the list continues loading short filtered pages.
+ applyTags(filters, selection, facetContext);
+
+ return filters;
+}
+
+/** Builds the positive service-backed portion of Drive text search. */
+export function buildDriveSearchRequest(
+ options: BuildDriveSearchRequestOptions
+): SearchSoupQueryArgs {
+ return {
+ params: { cursor: null, page_size: 100 },
+ body: {
+ query: options.query,
+ match_type: options.matchType,
+ search_on: 'name_content',
+ filters: filtersForSelection(
+ options.selection,
+ options.userId,
+ options.facetContext
+ ),
+ },
+ };
+}
diff --git a/apps/web/src/features/drive-view/queries/drive-sidebar-source.ts b/apps/web/src/features/drive-view/queries/drive-sidebar-source.ts
new file mode 100644
index 0000000000..cb04973fcc
--- /dev/null
+++ b/apps/web/src/features/drive-view/queries/drive-sidebar-source.ts
@@ -0,0 +1,36 @@
+import { useFavoritesData } from '@queries/favorites/favorites';
+import { useProjectsQuery } from '@queries/storage/projects';
+import { createMemo } from 'solid-js';
+import type { DriveSidebarSource } from '../context/drive-source';
+
+export function createDriveSidebarSource(): DriveSidebarSource {
+ const projects = useProjectsQuery();
+
+ const favoritesData = useFavoritesData();
+
+ return {
+ folders: () =>
+ projects.isSuccess
+ ? projects.data.filter((folder) => !folder.deletedAt)
+ : [],
+
+ foldersLoading: () => projects.isPending,
+
+ foldersError: () => projects.isError,
+
+ retryFolders: async () => {
+ await projects.refetch();
+ },
+
+ favorites: createMemo(() =>
+ (favoritesData()?.favorites ?? [])
+ .filter(
+ (favorite) =>
+ favorite.entityType === 'project' ||
+ (favorite.entityType === 'document' &&
+ favorite.documentSubType !== 'task')
+ )
+ .sort((a, b) => a.sortOrder - b.sortOrder)
+ ),
+ };
+}
diff --git a/apps/web/src/features/drive-view/views/drive-breadcrumbs.tsx b/apps/web/src/features/drive-view/views/drive-breadcrumbs.tsx
new file mode 100644
index 0000000000..00be1f11d9
--- /dev/null
+++ b/apps/web/src/features/drive-view/views/drive-breadcrumbs.tsx
@@ -0,0 +1,64 @@
+import { useEntityDetailNavigationStack } from '@app/components/entity-detail/EntityDetailNavigationStack';
+import { ViewBreadcrumbs } from '@app/components/view-shell';
+import type { ParentProps } from 'solid-js';
+import { DriveLocationBreadcrumbItems } from '../components/DriveBreadcrumbs';
+import { useDriveView } from '../context/drive-context';
+import type { DriveLocationBreadcrumb } from '../core/breadcrumbs';
+
+export function DriveBreadcrumbs(
+ props: ParentProps<{ entries: DriveLocationBreadcrumb[] }>
+) {
+ const { state, sidebar, actions } = useDriveView();
+
+ const navigation = useEntityDetailNavigationStack();
+
+ return (
+ <ViewBreadcrumbs.Root
+ value={navigation.active()?.value ?? props.entries.at(-1)!.value}
+ onChange={(value) => {
+ const breadcrumb = props.entries.find((entry) => entry.value === value);
+
+ if (!breadcrumb) {
+ navigation.popTo(value);
+
+ return;
+ }
+
+ const current = state.value().location;
+
+ const location = breadcrumb.location;
+
+ const isCurrent =
+ (current.kind === 'tab' &&
+ location.kind === 'tab' &&
+ current.tab === location.tab) ||
+ (current.kind === 'folder' &&
+ location.kind === 'folder' &&
+ current.id === location.id);
+
+ if (isCurrent) navigation.clear();
+ else state.navigate(location);
+ }}
+ >
+ <DriveLocationBreadcrumbItems
+ entries={props.entries}
+ folders={sidebar.folders()}
+ userId={actions.userId()}
+ onOpenFolderInNewSplit={
+ actions.canOpenNewSplit() ? actions.openFolderInNewSplit : undefined
+ }
+ onShareFolder={actions.shareFolder}
+ onDeleteFolder={(folder) => {
+ const parentId = sidebar
+ .folders()
+ .some(({ id }) => id === folder.parentId)
+ ? folder.parentId
+ : null;
+
+ state.selectFolder(parentId ?? null);
+ }}
+ />
+ {props.children}
+ </ViewBreadcrumbs.Root>
+ );
+}
diff --git a/apps/web/src/features/drive-view/views/drive-filter-menu.tsx b/apps/web/src/features/drive-view/views/drive-filter-menu.tsx
new file mode 100644
index 0000000000..fd55d5ab66
--- /dev/null
+++ b/apps/web/src/features/drive-view/views/drive-filter-menu.tsx
@@ -0,0 +1,181 @@
+import {
+ ListFilterDropdown,
+ type ListFilterGroup,
+ useViewControlHotkeys,
+} from '@app/components/view-shell';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { EntityIcon } from '@core/component/EntityIcon';
+import { UserIcon } from '@core/component/UserIcon';
+import { useTagFilterGroup } from '@property/tags/use-tag-filter-group';
+import { useContacts } from '@queries/contacts/contacts';
+import { createMemo, createSignal } from 'solid-js';
+import { useDriveView } from '../context/drive-context';
+
+type GroupId = 'type' | 'created-by' | 'tags' | 'scope';
+
+const typeOptions = [
+ { id: 'doc-markdown', label: 'Markdown', type: 'md' },
+ { id: 'doc-canvas', label: 'Canvas', type: 'canvas' },
+ { id: 'doc-spreadsheet', label: 'Spreadsheet', type: 'spreadsheet' },
+ { id: 'file-code', label: 'Code', type: 'code' },
+ { id: 'file-image', label: 'Images', type: 'image' },
+ { id: 'file-pdf', label: 'PDFs', type: 'pdf' },
+ { id: 'file-docx', label: 'DOCX', type: 'write' },
+ { id: 'file-video', label: 'Videos', type: 'video' },
+ { id: 'doc-snippet', label: 'Snippets', type: 'snippet' },
+ { id: 'doc-skill', label: 'Skills', type: 'skill' },
+ { id: 'file-other', label: 'Other', type: 'files' },
+] as const;
+
+export function DriveFilterMenu() {
+ const { state, actions } = useDriveView();
+
+ const panel = useSplitPanelOrThrow();
+
+ const userId = actions.userId;
+
+ const contacts = useContacts();
+
+ const tagGroup = useTagFilterGroup();
+
+ const [open, setOpen] = createSignal(false);
+
+ useViewControlHotkeys({
+ scopeId: panel.splitHotkeyScope,
+ enabled: panel.isPanelActive,
+ filter: {
+ description: 'Filter files',
+
+ run: () => {
+ setOpen(true);
+
+ return true;
+ },
+ },
+ });
+
+ const people = createMemo(() => {
+ const sorted = [...contacts()].sort(
+ (a, b) => Number(b.id === userId()) - Number(a.id === userId())
+ );
+
+ return sorted.map((person) => {
+ let label = person.name || person.id;
+
+ if (person.id === userId()) {
+ label = person.name ? `${person.name} (me)` : 'Me';
+ }
+
+ return {
+ id: person.id,
+ label,
+
+ icon: () => (
+ <UserIcon
+ id={person.id}
+ size="sm"
+ suppressClick
+ showTooltip={false}
+ />
+ ),
+ };
+ });
+ });
+
+ const showCreators = () => {
+ const { location, scope } = state.value();
+
+ if (location.kind === 'folder') return true;
+
+ return location.tab !== 'owned' || scope !== 'default';
+ };
+
+ const groups = createMemo(() => {
+ const groups: ListFilterGroup<GroupId, string>[] = [];
+
+ const location = state.value().location;
+
+ const isRecent = location.kind === 'tab' && location.tab === 'recent';
+
+ if (!isRecent) {
+ const tags = tagGroup();
+
+ if (tags.options.length > 0) groups.push(tags);
+
+ groups.push({
+ id: 'type',
+ label: 'Type',
+ options: typeOptions.map((option) => ({
+ id: option.id,
+ label: option.label,
+
+ icon: () => <EntityIcon targetType={option.type} size="xs" />,
+ })),
+ });
+
+ if (showCreators()) {
+ groups.push({
+ id: 'created-by',
+ label: 'Created by',
+ searchPlaceholder: 'Search creators...',
+ options: people(),
+ });
+ }
+ }
+
+ groups.push({
+ id: 'scope',
+ label: 'Files',
+ selectionMode: 'single',
+ defaultOptionId: 'default',
+ options: [
+ { id: 'default', label: 'Default' },
+ { id: 'all', label: 'All files' },
+ { id: 'attachments', label: 'Email attachments' },
+ ],
+ });
+
+ return groups;
+ });
+
+ const setTagSelected = (id: string, selected: boolean) => {
+ const ids = (state.value().facets.tags ?? []).filter(
+ (value) => value !== id
+ );
+
+ if (selected) ids.push(id);
+
+ state.setTags(ids);
+ };
+
+ return (
+ <ListFilterDropdown
+ label="Filter files"
+ open={open()}
+ onOpenChange={setOpen}
+ groups={groups()}
+ onClear={state.clearFilters}
+ isSelected={(group, id) => {
+ if (group === 'scope') return state.value().scope === id;
+
+ return state.value().facets[group]?.includes(id) ?? false;
+ }}
+ onSelectionChange={(group, id, selected) => {
+ if (group === 'scope') {
+ if (id === 'default' || id === 'all' || id === 'attachments')
+ state.setScope(id);
+
+ return;
+ }
+
+ if (group === 'tags') {
+ setTagSelected(id, selected);
+
+ return;
+ }
+
+ state.setFacetSelected(group, id, selected);
+ }}
+ />
+ );
+}
diff --git a/apps/web/src/features/drive-view/views/drive-header.tsx b/apps/web/src/features/drive-view/views/drive-header.tsx
new file mode 100644
index 0000000000..a2cb6676a2
--- /dev/null
+++ b/apps/web/src/features/drive-view/views/drive-header.tsx
@@ -0,0 +1,143 @@
+import {
+ ListSortDropdown,
+ SearchBar,
+ useViewControlHotkeys,
+ ViewShell,
+} from '@app/components/view-shell';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import { Dropdown } from '@ui';
+import { createSignal, Show, Suspense } from 'solid-js';
+import { DriveBreadcrumbsOutlet } from '../components/DriveBreadcrumbs';
+import { useDriveView } from '../context/drive-context';
+import { driveLocationLabel } from '../core/location-label';
+import { DriveCreateMenu } from '../drive-create-menu';
+import { DriveFilterMenu } from './drive-filter-menu';
+import { DriveSidebarContent } from './drive-sidebar';
+
+export function DriveHeader() {
+ const { state, sidebar } = useDriveView();
+
+ const title = () =>
+ driveLocationLabel(state.value().location, sidebar.folders());
+
+ const isRecent = () => {
+ const location = state.value().location;
+
+ return location.kind === 'tab' && location.tab === 'recent';
+ };
+
+ const panel = useSplitPanelOrThrow();
+
+ const [navigationOpen, setNavigationOpen] = createSignal(false);
+
+ let searchInput: HTMLInputElement | undefined;
+
+ useViewControlHotkeys({
+ scopeId: panel.splitHotkeyScope,
+ enabled: panel.isPanelActive,
+ search: {
+ description: 'Search Drive',
+
+ condition: () => !state.projectId(),
+
+ run: () => {
+ searchInput?.focus();
+ searchInput?.select();
+
+ return true;
+ },
+ },
+ });
+
+ return (
+ <>
+ <ViewShell.TopBar class="touch:flex">
+ <h1 class="hidden min-w-0 truncate text-sm font-semibold tracking-[-0.03em] text-ink @max-[720px]/view-shell:block">
+ Drive
+ </h1>
+ <DriveBreadcrumbsOutlet
+ aria-label="Drive location"
+ class="@max-[720px]/view-shell:hidden"
+ />
+ </ViewShell.TopBar>
+ <ViewShell.Header>
+ <div class="flex min-w-0 flex-col gap-3">
+ <div class="hidden min-w-0 items-center gap-2 @max-[720px]/view-shell:flex">
+ <Show
+ when={isTouchDevice()}
+ fallback={
+ <h1 class="min-w-0 truncate text-xl font-semibold tracking-[-0.03em] text-ink">
+ {title()}
+ </h1>
+ }
+ >
+ <Dropdown
+ open={navigationOpen()}
+ onOpenChange={setNavigationOpen}
+ placement="bottom-start"
+ >
+ <h1 class="min-w-0">
+ <Dropdown.Trigger
+ variant="ghost"
+ size="sm"
+ class="h-auto min-w-0 max-w-full gap-1 rounded-lg px-2 py-1 text-xl font-semibold tracking-[-0.03em] text-ink"
+ aria-label={`Select Drive view: ${title()}`}
+ >
+ <span class="truncate">{title()}</span>
+ <CaretDownIcon class="size-3.5 shrink-0 text-ink-muted" />
+ </Dropdown.Trigger>
+ </h1>
+ <Dropdown.Content class="max-h-[70vh] w-72 overflow-auto rounded-2xl">
+ <Dropdown.Group class="gap-5 p-3">
+ <DriveSidebarContent
+ onNavigate={() => setNavigationOpen(false)}
+ />
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ </Show>
+ <div class="ml-auto shrink-0">
+ <DriveCreateMenu />
+ </div>
+ </div>
+ <div class="flex min-w-0 items-center justify-between gap-3">
+ <Show when={!state.projectId()}>
+ <SearchBar
+ ref={(element) => {
+ searchInput = element;
+ }}
+ label="Search Drive"
+ placeholder="Search files"
+ value={state.value().search}
+ onValueChange={state.setSearch}
+ hotkey="cmd+f"
+ class="max-w-md flex-1"
+ />
+ </Show>
+ <div class="ml-auto flex shrink-0 items-center gap-2">
+ <Show when={!isRecent()}>
+ <ListSortDropdown
+ label="Sort files"
+ value={state.value().sort}
+ onChange={state.setSort}
+ options={[
+ { id: 'updated_at', label: 'Last modified' },
+ { id: 'created_at', label: 'Created' },
+ { id: 'viewed_at', label: 'Last viewed' },
+ ]}
+ />
+ </Show>
+ <Show when={state.value().location.kind === 'tab'}>
+ <Suspense>
+ <DriveFilterMenu />
+ </Suspense>
+ </Show>
+ </div>
+ </div>
+ </div>
+ </ViewShell.Header>
+ </>
+ );
+}
diff --git a/apps/web/src/features/drive-view/views/drive-layout.tsx b/apps/web/src/features/drive-view/views/drive-layout.tsx
deleted file mode 100644
index cd34ba8737..0000000000
--- a/apps/web/src/features/drive-view/views/drive-layout.tsx
+++ /dev/null
@@ -1,325 +0,0 @@
-import {
- CollapsibleSection,
- ListSortDropdown,
- SearchBar,
- ViewShell,
- ViewSidebar,
-} from '@app/components/view-shell';
-import { SplitPanel } from '@components/app/split-panel';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import CaretDownIcon from '@phosphor/caret-down.svg';
-import FolderIcon from '@phosphor/folder.svg';
-import SearchIcon from '@phosphor/magnifying-glass.svg';
-import { SidebarTagsSection } from '@property/tags/SidebarTagsSection';
-import { Button, Dropdown } from '@ui';
-import { createMemo, createSignal, type JSX, Show } from 'solid-js';
-import { DriveBreadcrumbsOutlet } from '../components/DriveBreadcrumbs';
-import {
- type DriveLocationMenu,
- DriveNavigation,
-} from '../components/drive-navigation';
-import { FolderTree } from '../components/folder-tree';
-import { buildFolderTree, filterFolderTree } from '../core/folder-tree';
-import { driveLocationLabel } from '../core/location-label';
-import type {
- DriveFolder,
- DriveSort,
- DriveState,
- DriveTab,
-} from '../core/types';
-
-export function DriveLayout(props: {
- state: DriveState;
- folders: DriveFolder[];
- foldersLoading: boolean;
- foldersError: boolean;
- onRetryFolders: () => void;
- search: string;
- onSearch: (value: string) => void;
- searchRef: (element: HTMLInputElement) => void;
- onTab: (tab: DriveTab) => void;
- onFolder: (id: string | null) => void;
- filterMenu: () => JSX.Element;
- onSort: (sort: DriveSort) => void;
- onToggleFolder: (id: string) => void;
- onFavoritesOpen: (open: boolean) => void;
- onRootOpen: (open: boolean) => void;
- /** Tag option ids narrowing the current location. */
- activeTagIds: readonly string[];
- onTags: (ids: string[]) => void;
- onTagsOpen: (open: boolean) => void;
- createMenu: () => JSX.Element;
- favorites: () => JSX.Element;
- /** The favorites section is hidden entirely when the user has none. */
- hasFavorites: boolean;
- locationMenu: DriveLocationMenu;
- detail?: JSX.Element;
- children: JSX.Element;
-}) {
- const [folderSearch, setFolderSearch] = createSignal('');
- const [searchingFolders, setSearchingFolders] = createSignal(false);
- const [navigationOpen, setNavigationOpen] = createSignal(false);
- const tree = createMemo(() => buildFolderTree(props.folders));
- const filteredTree = createMemo(() =>
- filterFolderTree(tree(), folderSearch())
- );
- const selectedFolder = () =>
- props.state.location.kind === 'folder'
- ? props.state.location.id
- : undefined;
- const title = () => driveLocationLabel(props.state.location, props.folders);
-
- const SidebarContent = () => (
- <>
- <DriveNavigation
- locationMenu={props.locationMenu}
- location={props.state.location}
- onNavigate={(tab) => {
- props.onTab(tab);
- setNavigationOpen(false);
- }}
- />
- <Show when={props.hasFavorites}>
- <CollapsibleSection.Root
- open={props.state.favoritesOpen}
- onOpenChange={props.onFavoritesOpen}
- >
- <CollapsibleSection.Trigger>
- <span class="min-w-0 truncate">Favorites</span>
- <CollapsibleSection.Indicator />
- </CollapsibleSection.Trigger>
- <CollapsibleSection.Content>
- <props.favorites />
- </CollapsibleSection.Content>
- </CollapsibleSection.Root>
- </Show>
- <CollapsibleSection.Root
- open={props.state.rootOpen}
- onOpenChange={props.onRootOpen}
- >
- <CollapsibleSection.Header>
- <CollapsibleSection.Trigger class="flex-1">
- <span class="min-w-0 truncate">Folders</span>
- <CollapsibleSection.Indicator />
- </CollapsibleSection.Trigger>
- <CollapsibleSection.Action
- label="Search folders"
- onClick={() => {
- const open = !searchingFolders();
- setSearchingFolders(open);
- setFolderSearch('');
- if (open) props.onRootOpen(true);
- }}
- >
- <SearchIcon class="size-3.5" />
- </CollapsibleSection.Action>
- </CollapsibleSection.Header>
- <CollapsibleSection.Content>
- <Show when={searchingFolders()}>
- <SearchBar
- label="Search folders"
- placeholder="Search folders"
- value={folderSearch()}
- onValueChange={setFolderSearch}
- class="mb-2"
- />
- </Show>
- <ViewSidebar.Nav aria-label="Folders">
- <props.locationMenu location={{ kind: 'folder', id: null }}>
- <ViewSidebar.Item
- active={selectedFolder() === null}
- onClick={() => {
- props.onFolder(null);
- setNavigationOpen(false);
- }}
- >
- <ViewSidebar.Icon>
- <FolderIcon class="size-4" />
- </ViewSidebar.Icon>
- <span>Drive</span>
- </ViewSidebar.Item>
- </props.locationMenu>
- <ViewSidebar.Branch>
- <Show
- when={!props.foldersLoading}
- fallback={
- <p
- role="status"
- class="px-3 py-2 text-sm text-ink-extra-muted"
- >
- Loading folders…
- </p>
- }
- >
- <Show
- when={!props.foldersError}
- fallback={
- <div class="p-3 text-sm text-ink-muted">
- Folders couldn’t be loaded.
- <Button variant="ghost" onClick={props.onRetryFolders}>
- Try again
- </Button>
- </div>
- }
- >
- <FolderTree
- locationMenu={props.locationMenu}
- nodes={filteredTree()}
- selectedId={selectedFolder()}
- expandedIds={props.state.expandedFolderIds}
- searching={!!folderSearch().trim()}
- onToggle={props.onToggleFolder}
- onSelect={(id) => {
- props.onFolder(id);
- setNavigationOpen(false);
- }}
- />
- <Show when={filteredTree().length === 0}>
- <p class="px-3 py-2 text-sm text-ink-extra-muted">
- {folderSearch()
- ? 'No matching folders'
- : 'No folders yet'}
- </p>
- </Show>
- </Show>
- </Show>
- </ViewSidebar.Branch>
- </ViewSidebar.Nav>
- </CollapsibleSection.Content>
- </CollapsibleSection.Root>
- <SidebarTagsSection
- activeIds={props.activeTagIds}
- onActiveIdsChange={props.onTags}
- open={props.state.tagsOpen}
- onOpenChange={props.onTagsOpen}
- onNavigate={() => setNavigationOpen(false)}
- />
- </>
- );
-
- return (
- <SplitPanel.Root>
- <SplitPanel.Body>
- <ViewShell.Root
- asidePreferenceKey="documents"
- resizable
- aside={{ preserveDuringResize: false }}
- main={{ preferredWidth: 640 }}
- >
- <ViewShell.Aside>
- <ViewSidebar.Root aria-label="Drive navigation">
- <ViewSidebar.Header>
- <div class="flex min-w-0 items-center gap-1">
- <ViewSidebar.CloseButton />
- <ViewSidebar.Title>Drive</ViewSidebar.Title>
- </div>
- </ViewSidebar.Header>
- <ViewSidebar.Primary>
- <props.createMenu />
- </ViewSidebar.Primary>
- <ViewSidebar.Content>
- <SidebarContent />
- </ViewSidebar.Content>
- </ViewSidebar.Root>
- </ViewShell.Aside>
- <ViewShell.Main>
- <Show
- when={props.detail}
- fallback={
- <>
- <ViewShell.TopBar class="touch:flex">
- <h1 class="hidden min-w-0 truncate text-sm font-semibold tracking-[-0.03em] text-ink @max-[720px]/view-shell:block">
- Drive
- </h1>
- <DriveBreadcrumbsOutlet
- aria-label="Drive location"
- class="@max-[720px]/view-shell:hidden"
- />
- </ViewShell.TopBar>
- <ViewShell.Header>
- <div class="flex min-w-0 flex-col gap-3">
- <div class="hidden min-w-0 items-center gap-2 @max-[720px]/view-shell:flex">
- <Show
- when={isTouchDevice()}
- fallback={
- <h1 class="min-w-0 truncate text-xl font-semibold tracking-[-0.03em] text-ink">
- {title()}
- </h1>
- }
- >
- <Dropdown
- open={navigationOpen()}
- onOpenChange={setNavigationOpen}
- placement="bottom-start"
- >
- <h1 class="min-w-0">
- <Dropdown.Trigger
- variant="ghost"
- size="sm"
- class="h-auto min-w-0 max-w-full gap-1 rounded-lg px-2 py-1 text-xl font-semibold tracking-[-0.03em] text-ink"
- aria-label={`Select Drive view: ${title()}`}
- >
- <span class="truncate">{title()}</span>
- <CaretDownIcon class="size-3.5 shrink-0 text-ink-muted" />
- </Dropdown.Trigger>
- </h1>
- <Dropdown.Content class="max-h-[70vh] w-72 overflow-auto rounded-2xl">
- <Dropdown.Group class="gap-5 p-3">
- <SidebarContent />
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- </Show>
- <div class="ml-auto shrink-0">
- <props.createMenu />
- </div>
- </div>
- <div class="flex min-w-0 items-center justify-between gap-3">
- <Show when={!selectedFolder()}>
- <SearchBar
- ref={props.searchRef}
- label="Search Drive"
- placeholder="Search files"
- value={props.search}
- onValueChange={props.onSearch}
- hotkey="cmd+f"
- class="max-w-md flex-1"
- />
- </Show>
- <div class="ml-auto flex shrink-0 items-center gap-2">
- <Show
- when={
- !(
- props.state.location.kind === 'tab' &&
- props.state.location.tab === 'recent'
- )
- }
- >
- <ListSortDropdown
- label="Sort files"
- value={props.state.sort}
- onChange={props.onSort}
- options={[
- { id: 'updated_at', label: 'Last modified' },
- { id: 'created_at', label: 'Created' },
- { id: 'viewed_at', label: 'Last viewed' },
- ]}
- />
- </Show>
- <props.filterMenu />
- </div>
- </div>
- </div>
- </ViewShell.Header>
- <ViewShell.Content>{props.children}</ViewShell.Content>
- </>
- }
- >
- {(detail) => detail()}
- </Show>
- </ViewShell.Main>
- </ViewShell.Root>
- </SplitPanel.Body>
- </SplitPanel.Root>
- );
-}
diff --git a/apps/web/src/features/drive-view/views/drive-list.tsx b/apps/web/src/features/drive-view/views/drive-list.tsx
new file mode 100644
index 0000000000..34826990b2
--- /dev/null
+++ b/apps/web/src/features/drive-view/views/drive-list.tsx
@@ -0,0 +1,503 @@
+import { useListInteractions } from '@app/components/list';
+import {
+ resolveEntityActionViewContext,
+ toEntityActionListState,
+ useEntityActionHotkeys,
+} from '@app/features/next-soup/actions';
+import {
+ MaybeSoupEntityActionDrawerManager,
+ SoupEntityContextMenu,
+} from '@app/features/soup';
+import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { toast } from '@core/component/Toast/Toast';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
+import EmptyStateFolderGraphic from '@design/empty-state-folder.svg';
+import {
+ type EntityData,
+ EntitySelectionToolbar,
+ ListEntity,
+ ListLayoutProvider,
+} from '@entity';
+import ArrowLeftIcon from '@phosphor/arrow-left.svg';
+import SpinnerIcon from '@phosphor/spinner.svg';
+import { createElementSize } from '@solid-primitives/resize-observer';
+import { Button, EmptyStatePanel } from '@ui';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ Match,
+ on,
+ onCleanup,
+ onMount,
+ Show,
+ Suspense,
+ Switch,
+} from 'solid-js';
+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
+import { useDriveView } from '../context/drive-context';
+
+export function DriveList() {
+ const { state, source, list: listState, actions } = useDriveView();
+
+ const panel = useSplitPanelOrThrow();
+
+ const { isKeypressActive } = useIsKeyPressActive();
+
+ const list = listState.controller;
+
+ const hasFilters = () => {
+ if (state.value().scope !== 'default') return true;
+
+ return Object.values(state.value().facets).some((ids) => ids.length > 0);
+ };
+
+ const isSearching = () => state.value().search.trim().length > 0;
+
+ const rowElementId = (key: string | undefined) => {
+ if (!key) return undefined;
+
+ return `drive-${panel.handle.id}-${key}`;
+ };
+
+ const timestamp = (entity: EntityData) => {
+ const { location, sort } = state.value();
+
+ if (location.kind === 'tab' && location.tab === 'recent')
+ return entity.touchedAt;
+ if (entity.sortTs) return entity.sortTs;
+ if (sort === 'viewed_at') return entity.viewedAt;
+ if (sort === 'created_at') return entity.createdAt;
+
+ return entity.updatedAt;
+ };
+
+ const [grid, setGrid] = createSignal<HTMLDivElement>();
+
+ const [viewport, setViewport] = createSignal<HTMLDivElement>();
+
+ const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();
+
+ const forceEmptyState = useDebugSetting(
+ DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES
+ );
+
+ const selected = createMemo(() =>
+ list.selection.items().map((row) => row.entity)
+ );
+
+ const actionContext = () =>
+ resolveEntityActionViewContext({
+ activeListView: 'documents',
+ activeTab: 'all',
+ });
+
+ const actionState = toEntityActionListState({
+ controller: list,
+
+ getEntity: (row) => row.entity,
+
+ onFocus: (target) => {
+ if (target)
+ virtualizer()?.scrollToIndex(target.index, { align: 'nearest' });
+
+ grid()?.focus();
+ },
+ });
+
+ async function loadMore() {
+ try {
+ await source.loadMore();
+ } catch {
+ // The source retains the error for the inline retry UI.
+ }
+ }
+
+ function checkNearEnd() {
+ if (forceEmptyState() || source.error()) return;
+ if (source.isLoading() || source.isFetching() || !source.hasMore()) return;
+
+ const container = viewport();
+
+ if (!container || container.clientHeight === 0) return;
+
+ const distance =
+ container.scrollHeight - container.scrollTop - container.clientHeight;
+
+ if (distance < 300) void loadMore();
+ }
+
+ const viewportSize = createElementSize(viewport);
+
+ createEffect(() => {
+ source.items();
+ source.isFetching();
+ viewportSize.height;
+
+ // A filtered page may be too short to produce a scroll event.
+ const frame = requestAnimationFrame(checkNearEnd);
+
+ onCleanup(() => cancelAnimationFrame(frame));
+ });
+
+ async function refresh() {
+ try {
+ await source.refresh();
+ } catch {
+ toast.failure('Files couldn’t be loaded. Try again.');
+ }
+ }
+
+ const interactions = useListInteractions({
+ controller: list,
+ scopeId: panel.splitHotkeyScope,
+ enabled: panel.isPanelActive,
+ scrollHandle: virtualizer,
+ navigation: {
+ onNavigate: (event) => {
+ if (event.kind !== 'move' || event.direction !== 1) return;
+ if (source.error()) return;
+
+ if (!event.result || list.items.count() - event.result.index <= 4) {
+ void loadMore();
+ }
+ },
+ },
+
+ activation: {
+ createMetadata: (intent) => ({ newSplit: intent === 'alternate' }),
+
+ alternateDescription: 'Open in new split',
+ },
+ });
+
+ useEntityActionHotkeys({
+ scopeId: panel.splitHotkeyScope,
+ list: actionState,
+ selectedEntities: selected,
+
+ focusedEntity: () => list.focus.item()?.entity,
+
+ restoreFocus: () => grid()?.focus(),
+
+ viewContext: actionContext,
+ splitHandle: panel.handle,
+ condition: panel.isPanelActive,
+ });
+
+ onMount(() => {
+ if (!panel.isPanelActive() || isTouchDevice()) return;
+
+ const active = document.activeElement;
+
+ if (
+ active instanceof HTMLElement &&
+ (active.isContentEditable || active.matches('input, textarea'))
+ )
+ return;
+
+ grid()?.focus({ preventScroll: true });
+ });
+
+ // Reconcile the imperative keyboard focus anchor after results change.
+ createEffect(() => {
+ source.items();
+
+ if (source.isLoading() || list.focus.result()) return;
+
+ if (
+ list.focus.restore(list.focus.requestedKey(), {
+ retainUnavailable: false,
+ })
+ )
+ return;
+
+ if (isTouchDevice() || panel.handle.isControllerSplit()) return;
+
+ list.focus.first({ reason: 'restore' });
+ });
+
+ createEffect(
+ on(listState.scrollOffset, (offset) => {
+ const handle = virtualizer();
+
+ if (handle && handle.scrollOffset !== offset) handle.scrollTo(offset);
+ })
+ );
+
+ const featuredCount = createMemo(() => {
+ const ids = new Set(source.featuredIds());
+
+ return source.items().filter((row) => ids.has(row.entity.id)).length;
+ });
+
+ const showError = () => !!source.error() && !source.hasData();
+
+ const folderIsEmpty = () => {
+ if (!state.projectId() || isSearching()) return false;
+ if (hasFilters() || source.hasMore()) return false;
+
+ return true;
+ };
+
+ const emptyMessage = () => {
+ if (source.error()) return 'More files couldn’t be loaded.';
+ if (source.hasMore()) return 'Looking for matching files…';
+ if (isSearching()) return 'No files match this search.';
+
+ return 'No files in this view.';
+ };
+
+ return (
+ <MaybeSoupEntityActionDrawerManager>
+ <StaticMarkdownContext>
+ <div
+ ref={setGrid}
+ role="grid"
+ aria-label="Drive files"
+ aria-multiselectable="true"
+ aria-activedescendant={rowElementId(list.focus.key())}
+ tabIndex={0}
+ class="@container/u-list relative flex size-full min-h-0 min-w-0 flex-col overflow-hidden outline-none"
+ >
+ <ListLayoutProvider ref={grid}>
+ <Switch>
+ <Match when={!forceEmptyState() && showError()}>
+ <div class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted">
+ <span>Files couldn’t be loaded.</span>
+ <Button variant="outline" onClick={() => void refresh()}>
+ Try again
+ </Button>
+ </div>
+ </Match>
+ <Match
+ when={
+ !forceEmptyState() &&
+ source.isLoading() &&
+ source.items().length === 0
+ }
+ >
+ <div
+ role="status"
+ class="grid min-h-0 flex-1 place-items-center text-ink-muted"
+ >
+ <SpinnerIcon
+ aria-label="Loading files"
+ class="size-5 animate-spin"
+ />
+ </div>
+ </Match>
+ <Match when={forceEmptyState() || source.items().length === 0}>
+ <Show
+ when={folderIsEmpty()}
+ fallback={
+ <div
+ ref={setViewport}
+ class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted"
+ >
+ <span>{emptyMessage()}</span>
+ <Show when={hasFilters()}>
+ <Button variant="outline" onClick={state.clearFilters}>
+ Clear filters
+ </Button>
+ </Show>
+ <Show when={!forceEmptyState() && source.hasMore()}>
+ <Button
+ variant="outline"
+ disabled={source.isFetching()}
+ onClick={() => void loadMore()}
+ >
+ Search more results
+ </Button>
+ </Show>
+ </div>
+ }
+ >
+ <EmptyStatePanel
+ centered
+ graphic={EmptyStateFolderGraphic}
+ title="This folder is empty"
+ description="Create something new or drop files here to add them to this folder."
+ primaryAction={{
+ label: 'Back to Drive',
+ icon: ArrowLeftIcon,
+ onClick: () => state.selectFolder(null),
+ }}
+ />
+ </Show>
+ </Match>
+ <Match when={true}>
+ <div
+ ref={setViewport}
+ class="min-h-0 flex-1 overflow-auto overscroll-none"
+ >
+ <Suspense>
+ <Virtualizer
+ ref={(handle) => {
+ setVirtualizer(handle);
+ handle?.scrollTo(listState.scrollOffset());
+ }}
+ data={source.items()}
+ scrollRef={viewport()}
+ bufferSize={240}
+ itemSize={44}
+ keepMounted={
+ list.focus.index() >= 0
+ ? [list.focus.index()]
+ : undefined
+ }
+ onScroll={(offset) => {
+ listState.setScrollOffset(offset);
+ checkNearEnd();
+ }}
+ >
+ {(row, index) => (
+ <div>
+ <Show
+ when={
+ featuredCount() > 0 &&
+ (index() === 0 || index() === featuredCount())
+ }
+ >
+ <div class="px-3 py-2 text-xs font-semibold text-ink-muted">
+ {index() === 0
+ ? 'Featured Results'
+ : 'More Results'}
+ </div>
+ </Show>
+ <div
+ id={rowElementId(row.id)}
+ role="row"
+ aria-selected={list.selection.isSelected(row.id)}
+ >
+ <div role="gridcell">
+ <SoupEntityContextMenu
+ entity={row.entity}
+ list={actionState}
+ selectedEntities={selected}
+ viewContext={actionContext()}
+ onOpenChange={(open) => {
+ if (!open) return;
+
+ list.focus.set(row.id, {
+ reason: 'pointer',
+ force: true,
+ });
+
+ list.selection.setAnchor(row.id);
+ }}
+ >
+ <ListEntity
+ entity={row.entity}
+ showCalendarAttendance
+ deferInteractions={source.deferInteractions()}
+ timestamp={timestamp(row.entity)}
+ highlighted={list.focus.key() === row.id}
+ checked={list.selection.isSelected(row.id)}
+ onMouseMove={() => {
+ if (isKeypressActive()) return;
+ if (panel.handle.isControllerSplit())
+ return;
+
+ list.focus.set(row.id, { reason: 'hover' });
+ }}
+ onFilterByTag={(id) => state.setTags([id])}
+ onChecked={(checked, shiftKey) =>
+ interactions.selection.set(
+ row.id,
+ checked,
+ { range: shiftKey }
+ )
+ }
+ onClick={(event) => {
+ if (
+ event.metaKey ||
+ event.ctrlKey ||
+ (isTouchDevice() &&
+ list.selection.count() > 0)
+ ) {
+ interactions.selection.toggle(row.id);
+
+ return;
+ }
+
+ list.activate.key(row.id, {
+ reason: 'pointer',
+ metadata: { event },
+ });
+ }}
+ onProjectClick={(project, event) =>
+ actions.openEntity(project, event)
+ }
+ onContentHitClick={(event, location) =>
+ actions.openEntity(
+ row.entity,
+ event,
+ location
+ )
+ }
+ />
+ </SoupEntityContextMenu>
+ </div>
+ </div>
+ <Show when={index() === source.items().length - 1}>
+ <Show when={source.isLoadingMore()}>
+ <div
+ role="status"
+ class="flex items-center gap-2 p-3 text-xs text-ink-muted"
+ >
+ <SpinnerIcon class="size-3 animate-spin" />
+ Loading more…
+ </div>
+ </Show>
+ <Show when={source.error()}>
+ <div
+ role="alert"
+ class="flex items-center gap-2 p-3 text-xs text-ink-muted"
+ >
+ More files couldn’t be loaded.
+ <Button
+ variant="outline"
+ onClick={() => void loadMore()}
+ >
+ Try again
+ </Button>
+ </div>
+ </Show>
+ <div class="h-15" />
+ </Show>
+ </div>
+ )}
+ </Virtualizer>
+ </Suspense>
+ </div>
+ </Match>
+ </Switch>
+ <Show
+ when={
+ isSearching() && source.isFetching() && !source.isLoadingMore()
+ }
+ >
+ <div
+ role="status"
+ class="pointer-events-none absolute bottom-3 right-3 text-xs text-ink-muted"
+ >
+ Searching…
+ </div>
+ </Show>
+ <Show when={selected().length > 0}>
+ <EntitySelectionToolbar
+ selected={selected()}
+ onClear={interactions.selection.clear}
+ analyticsSource="drive_view_selection_toolbar"
+ />
+ </Show>
+ </ListLayoutProvider>
+ </div>
+ </StaticMarkdownContext>
+ </MaybeSoupEntityActionDrawerManager>
+ );
+}
diff --git a/apps/web/src/features/drive-view/views/drive-sidebar.tsx b/apps/web/src/features/drive-view/views/drive-sidebar.tsx
new file mode 100644
index 0000000000..4c3a8b780f
--- /dev/null
+++ b/apps/web/src/features/drive-view/views/drive-sidebar.tsx
@@ -0,0 +1,224 @@
+import {
+ CollapsibleSection,
+ SearchBar,
+ ViewSidebar,
+} from '@app/components/view-shell';
+import { FavoriteContextMenu } from '@app/features/favorites/FavoriteContextMenu';
+import { FavoriteIcon } from '@app/features/favorites/FavoriteIcon';
+import { useFavoriteDisplayName } from '@app/util/favorites';
+import FolderIcon from '@phosphor/folder.svg';
+import SearchIcon from '@phosphor/magnifying-glass.svg';
+import { SidebarTagsSection } from '@property/tags/SidebarTagsSection';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import { Button } from '@ui';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+import { DriveNavigation } from '../components/drive-navigation';
+import { FolderTree } from '../components/folder-tree';
+import { useDriveView } from '../context/drive-context';
+import { buildFolderTree, filterFolderTree } from '../core/folder-tree';
+import { DriveCreateMenu } from '../drive-create-menu';
+import { DriveLocationMenu } from '../drive-location-menu';
+
+function DriveFavorite(props: { favorite: Favorite; onNavigate?: () => void }) {
+ const { actions } = useDriveView();
+
+ const name = useFavoriteDisplayName(props.favorite);
+
+ return (
+ <FavoriteContextMenu favorite={props.favorite} triggerClass="block">
+ <ViewSidebar.Item
+ title={name()}
+ onClick={(event) => {
+ actions.openFavorite(props.favorite, name(), event);
+ props.onNavigate?.();
+ }}
+ >
+ <ViewSidebar.Icon>
+ <FavoriteIcon favorite={props.favorite} class="size-4" />
+ </ViewSidebar.Icon>
+ <span class="truncate">{name()}</span>
+ </ViewSidebar.Item>
+ </FavoriteContextMenu>
+ );
+}
+
+/** Also used by the narrow-layout navigation menu. */
+export function DriveSidebarContent(props: { onNavigate?: () => void }) {
+ const { state, sidebar } = useDriveView();
+
+ const [folderSearch, setFolderSearch] = createSignal('');
+
+ const [searchingFolders, setSearchingFolders] = createSignal(false);
+
+ const tree = createMemo(() => buildFolderTree(sidebar.folders()));
+
+ const filteredTree = createMemo(() =>
+ filterFolderTree(tree(), folderSearch())
+ );
+
+ const selectedFolder = () => {
+ const location = state.value().location;
+
+ return location.kind === 'folder' ? location.id : undefined;
+ };
+
+ const selectFolder = (id: string | null) => {
+ state.selectFolder(id);
+ props.onNavigate?.();
+ };
+
+ return (
+ <>
+ <DriveNavigation
+ locationMenu={DriveLocationMenu}
+ location={state.value().location}
+ onNavigate={(tab) => {
+ state.selectTab(tab);
+ props.onNavigate?.();
+ }}
+ />
+ <Show when={sidebar.favorites().length > 0}>
+ <CollapsibleSection.Root
+ open={state.value().favoritesOpen}
+ onOpenChange={state.setFavoritesOpen}
+ >
+ <CollapsibleSection.Trigger>
+ <span class="min-w-0 truncate">Favorites</span>
+ <CollapsibleSection.Indicator />
+ </CollapsibleSection.Trigger>
+ <CollapsibleSection.Content>
+ <ViewSidebar.Nav aria-label="Favorite files and folders">
+ <For each={sidebar.favorites()}>
+ {(favorite) => (
+ <DriveFavorite
+ favorite={favorite}
+ onNavigate={props.onNavigate}
+ />
+ )}
+ </For>
+ </ViewSidebar.Nav>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ </Show>
+ <CollapsibleSection.Root
+ open={state.value().rootOpen}
+ onOpenChange={state.setRootOpen}
+ >
+ <CollapsibleSection.Header>
+ <CollapsibleSection.Trigger class="flex-1">
+ <span class="min-w-0 truncate">Folders</span>
+ <CollapsibleSection.Indicator />
+ </CollapsibleSection.Trigger>
+ <CollapsibleSection.Action
+ label="Search folders"
+ onClick={() => {
+ const open = !searchingFolders();
+
+ setSearchingFolders(open);
+ setFolderSearch('');
+
+ if (open) state.setRootOpen(true);
+ }}
+ >
+ <SearchIcon class="size-3.5" />
+ </CollapsibleSection.Action>
+ </CollapsibleSection.Header>
+ <CollapsibleSection.Content>
+ <Show when={searchingFolders()}>
+ <SearchBar
+ label="Search folders"
+ placeholder="Search folders"
+ value={folderSearch()}
+ onValueChange={setFolderSearch}
+ class="mb-2"
+ />
+ </Show>
+ <ViewSidebar.Nav aria-label="Folders">
+ <DriveLocationMenu location={{ kind: 'folder', id: null }}>
+ <ViewSidebar.Item
+ active={selectedFolder() === null}
+ onClick={() => selectFolder(null)}
+ >
+ <ViewSidebar.Icon>
+ <FolderIcon class="size-4" />
+ </ViewSidebar.Icon>
+ <span>Drive</span>
+ </ViewSidebar.Item>
+ </DriveLocationMenu>
+ <ViewSidebar.Branch>
+ <Show
+ when={!sidebar.foldersLoading()}
+ fallback={
+ <p
+ role="status"
+ class="px-3 py-2 text-sm text-ink-extra-muted"
+ >
+ Loading folders…
+ </p>
+ }
+ >
+ <Show
+ when={!sidebar.foldersError()}
+ fallback={
+ <div class="p-3 text-sm text-ink-muted">
+ Folders couldn’t be loaded.
+ <Button
+ variant="ghost"
+ onClick={() => void sidebar.retryFolders()}
+ >
+ Try again
+ </Button>
+ </div>
+ }
+ >
+ <FolderTree
+ locationMenu={DriveLocationMenu}
+ nodes={filteredTree()}
+ selectedId={selectedFolder()}
+ expandedIds={state.value().expandedFolderIds}
+ searching={!!folderSearch().trim()}
+ onToggle={state.toggleFolder}
+ onSelect={selectFolder}
+ />
+ <Show when={filteredTree().length === 0}>
+ <p class="px-3 py-2 text-sm text-ink-extra-muted">
+ {folderSearch()
+ ? 'No matching folders'
+ : 'No folders yet'}
+ </p>
+ </Show>
+ </Show>
+ </Show>
+ </ViewSidebar.Branch>
+ </ViewSidebar.Nav>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ <SidebarTagsSection
+ activeIds={state.value().facets.tags ?? []}
+ onActiveIdsChange={state.setTags}
+ open={state.value().tagsOpen}
+ onOpenChange={state.setTagsOpen}
+ onNavigate={props.onNavigate}
+ />
+ </>
+ );
+}
+
+export function DriveSidebar() {
+ return (
+ <ViewSidebar.Root aria-label="Drive navigation">
+ <ViewSidebar.Header>
+ <div class="flex min-w-0 items-center gap-1">
+ <ViewSidebar.CloseButton />
+ <ViewSidebar.Title>Drive</ViewSidebar.Title>
+ </div>
+ </ViewSidebar.Header>
+ <ViewSidebar.Primary>
+ <DriveCreateMenu />
+ </ViewSidebar.Primary>
+ <ViewSidebar.Content>
+ <DriveSidebarContent />
+ </ViewSidebar.Content>
+ </ViewSidebar.Root>
+ );
+}
diff --git a/apps/web/src/features/drive-view/views/drive-workspace.tsx b/apps/web/src/features/drive-view/views/drive-workspace.tsx
new file mode 100644
index 0000000000..283a46289f
--- /dev/null
+++ b/apps/web/src/features/drive-view/views/drive-workspace.tsx
@@ -0,0 +1,88 @@
+import { useEntityDetailNavigationStack } from '@app/components/entity-detail/EntityDetailNavigationStack';
+import { useViewTabHotkeys, ViewShell } from '@app/components/view-shell';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { SplitPanel } from '@components/app/split-panel';
+import SpinnerIcon from '@phosphor/spinner.svg';
+import { createMemo, Show, Suspense } from 'solid-js';
+import { DriveDetailView } from '../components/DriveDetailView';
+import { DriveFileDropzone } from '../components/drive-file-dropzone';
+import { useDriveView } from '../context/drive-context';
+import { driveLocationBreadcrumbs } from '../core/breadcrumbs';
+import { DRIVE_TABS } from '../core/types';
+import { DriveBreadcrumbs } from './drive-breadcrumbs';
+import { DriveHeader } from './drive-header';
+import { DriveList } from './drive-list';
+import { DriveSidebar } from './drive-sidebar';
+
+export function DriveLoading() {
+ return (
+ <div class="grid size-full place-items-center text-ink-muted">
+ <SpinnerIcon aria-label="Loading files" class="size-5 animate-spin" />
+ </div>
+ );
+}
+
+export function DriveWorkspace() {
+ const { state, sidebar, actions } = useDriveView();
+
+ const breadcrumbs = createMemo(() =>
+ driveLocationBreadcrumbs(state.value().location, sidebar.folders())
+ );
+
+ const navigation = useEntityDetailNavigationStack();
+
+ const panel = useSplitPanelOrThrow();
+
+ useViewTabHotkeys({
+ scopeId: panel.splitHotkeyScope,
+ enabled: panel.isPanelActive,
+
+ ids: () => DRIVE_TABS.map((tab) => tab.id),
+
+ activeId: () => {
+ const location = state.value().location;
+
+ return location.kind === 'tab' ? location.tab : 'owned';
+ },
+
+ setActiveId: state.selectTab,
+ });
+
+ return (
+ <DriveBreadcrumbs entries={breadcrumbs()}>
+ <SplitPanel.Root>
+ <SplitPanel.Body>
+ <ViewShell.Root
+ asidePreferenceKey="documents"
+ resizable
+ aside={{ preserveDuringResize: false }}
+ main={{ preferredWidth: 640 }}
+ >
+ <ViewShell.Aside>
+ <DriveSidebar />
+ </ViewShell.Aside>
+ <ViewShell.Main>
+ <Show
+ when={navigation.active()}
+ fallback={
+ <>
+ <DriveHeader />
+ <ViewShell.Content>
+ <Suspense fallback={<DriveLoading />}>
+ <DriveFileDropzone onDrop={actions.dropFiles}>
+ <DriveList />
+ </DriveFileDropzone>
+ </Suspense>
+ </ViewShell.Content>
+ </>
+ }
+ >
+ <DriveDetailView breadcrumbOrderOffset={breadcrumbs().length} />
+ </Show>
+ </ViewShell.Main>
+ </ViewShell.Root>
+ </SplitPanel.Body>
+ </SplitPanel.Root>
+ </DriveBreadcrumbs>
+ );
+}
diff --git a/apps/web/src/features/entity/composed/ListEntity.tsx b/apps/web/src/features/entity/composed/ListEntity.tsx
index f457400fe0..3465a89bea 100644
--- a/apps/web/src/features/entity/composed/ListEntity.tsx
+++ b/apps/web/src/features/entity/composed/ListEntity.tsx
@@ -1,4 +1,5 @@
import './ListEntity.css';
+import { useMaybeSoupView } from '@app/features/next-soup/soup-view/soup-view-context';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import {
SwipableRow,
@@ -90,6 +91,9 @@ export function MaybeEntityRow(props: {
}
export function ListEntity(props: ListEntityProps) {
+ // Legacy Soup callers do not pass row behavior explicitly yet.
+ const soupView = useMaybeSoupView();
+
const unread = () => unreadFilterFn(props.entity);
const isShared = useIsShared(props.entity);
const bulkWakeupEnabled = useFeatureFlag(BULK_DOCUMENT_WAKEUP_FEATURE_FLAG);
@@ -155,6 +159,10 @@ export function ListEntity(props: ListEntityProps) {
setSnippetContainerRef,
chars: chars(),
onProjectClick: props.onProjectClick,
+ onFilterByTag: props.onFilterByTag ?? soupView?.filterByTag,
+ showCalendarAttendance:
+ props.showCalendarAttendance ??
+ (soupView?.activeTab() ?? 'all') === 'all',
});
const draggable = createEntityDraggable({
diff --git a/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx b/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx
index cc2ba92338..df40e58054 100644
--- a/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx
@@ -1,4 +1,3 @@
-import { useMaybeSoupView } from '@app/features/next-soup/soup-view/soup-view-context';
import { cn } from '@ui';
import { Match, Show, Switch } from 'solid-js';
import { MultiSelectCheckbox } from '../../components/MultiSelectCheckbox';
@@ -27,7 +26,6 @@ import { InboxDivider, type LayoutProps } from './shared';
import { TaskNarrowBody } from './task';
export function NarrowInboxLayout(props: LayoutProps) {
- const soupView = useMaybeSoupView();
const isDirectMessage = () =>
isChannelEntity(props.entity) &&
props.entity.channelType === 'direct_message';
@@ -158,7 +156,7 @@ export function NarrowInboxLayout(props: LayoutProps) {
{(entity) => (
<CallNarrowBody
entity={entity()}
- showAttendanceBadge={(soupView?.activeTab() ?? 'all') === 'all'}
+ showAttendanceBadge={props.showCalendarAttendance !== false}
setContainerRef={props.setSnippetContainerRef}
chars={props.chars}
/>
diff --git a/apps/web/src/features/entity/composed/list-entity/shared.tsx b/apps/web/src/features/entity/composed/list-entity/shared.tsx
index 8086e00bc2..8d7717179c 100644
--- a/apps/web/src/features/entity/composed/list-entity/shared.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/shared.tsx
@@ -35,6 +35,9 @@ export interface BaseListEntityProps<E extends EntityData = EntityData> {
hideCheckbox?: boolean;
onChecked?: (checked: boolean, shiftKey: boolean) => void;
onMouseMove?: () => void;
+ showCalendarAttendance?: boolean;
+ /** Lets standalone collections own their tag-filter navigation. */
+ onFilterByTag?: (optionId: string) => void;
onProjectClick?: (
entity: ProjectEntity,
e: PointerEvent | MouseEvent
@@ -63,6 +66,8 @@ export interface LayoutProps {
streamState?: StreamEvent;
setSnippetContainerRef: (el: HTMLElement) => void;
chars: number;
+ showCalendarAttendance?: boolean;
+ onFilterByTag?: (optionId: string) => void;
onProjectClick?: (
entity: ProjectEntity,
e: PointerEvent | MouseEvent
diff --git a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
index 922c1f78be..5437c4915a 100644
--- a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
@@ -1,4 +1,3 @@
-import { useMaybeSoupView } from '@app/features/next-soup/soup-view/soup-view-context';
import { formatCallDuration } from '@block-call/utils';
import { EntityRowTags } from '@property/tags';
import { EntityType } from '@service-properties/generated/schemas/entityType';
@@ -64,7 +63,6 @@ function RowTags(props: {
}
export function WideLayout(props: LayoutProps) {
- const soupView = useMaybeSoupView();
// When a thread resolves to one of the user's inboxes the inbox chip already
// conveys ownership, so the generic "shared" badge would be redundant.
const owningInbox = useOwningInboxForEntity(() => props.entity);
@@ -180,7 +178,7 @@ export function WideLayout(props: LayoutProps) {
entityId={entity().id}
entityType={EntityType.PROJECT}
properties={entity().properties}
- onFilterByTag={soupView?.filterByTag}
+ onFilterByTag={props.onFilterByTag}
/>
)}
</Show>
@@ -197,7 +195,7 @@ export function WideLayout(props: LayoutProps) {
isTaskEntity(entity()) ? EntityType.TASK : EntityType.DOCUMENT
}
properties={properties()}
- onFilterByTag={soupView?.filterByTag}
+ onFilterByTag={props.onFilterByTag}
/>
);
}}
@@ -208,7 +206,7 @@ export function WideLayout(props: LayoutProps) {
entityId={entity().id}
entityType={EntityType.THREAD}
properties={entity().properties}
- onFilterByTag={soupView?.filterByTag}
+ onFilterByTag={props.onFilterByTag}
/>
)}
</Show>
@@ -218,7 +216,7 @@ export function WideLayout(props: LayoutProps) {
entityId={entity().id}
entityType={EntityType.CHAT}
properties={entity().properties}
- onFilterByTag={soupView?.filterByTag}
+ onFilterByTag={props.onFilterByTag}
/>
)}
</Show>
@@ -228,7 +226,7 @@ export function WideLayout(props: LayoutProps) {
entityId={entity().id}
entityType={EntityType.CALL_RECORD}
properties={entity().properties}
- onFilterByTag={soupView?.filterByTag}
+ onFilterByTag={props.onFilterByTag}
/>
)}
</Show>
@@ -245,7 +243,7 @@ export function WideLayout(props: LayoutProps) {
<Show when={isCallEntity(props.entity) && props.entity}>
{(entity) => (
<>
- <Show when={(soupView?.activeTab() ?? 'all') === 'all'}>
+ <Show when={props.showCalendarAttendance !== false}>
<CallStatusBadge status={entity().status} />
</Show>
<Show
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index f274490afe..217db8d165 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -463,14 +463,17 @@ descendants' ancestors and reveals their branches.
is temporarily hidden, including its Cmd+F shortcut. The sidebar's folder-name
search remains available. Right-click any Drive view, the Drive folder overview,
or a folder at any depth for **Open in new split**, **Open in current split**, and
-**Open fullscreen** (when multiple splits are open). Folder menus also offer
-Favorite/Unfavorite, Move to folder, Copy Link, and owner-only Rename and Delete.
+**Open fullscreen** (when multiple splits are open). Opening a location in a new
+split clears search and filters in the destination, leaving the original split
+unchanged. Folder menus also offer Favorite/Unfavorite, Move to folder, Copy Link,
+and owner-only Rename and Delete.
A folder's Share dialog, when the owner belongs to a team, has Team access
(None, View, Comment, or Edit) without a Link sharing card or Link tab.
Favorites use the same open actions and **Remove from favorites** menu as Tasks.
-The **Filter** menu reuses the
-legacy **Type**, searchable **Tags**, and **Created by** submenus alongside **Files**
-for Default, All files, and Email attachments. Created by is hidden while My Files
+The **Filter** menu uses the same controls as Tasks: **Type**, searchable **Tags**,
+and **Created by** submenus alongside **Files** for Default, All files, and Email
+attachments. Options within a group match any selected option; different groups
+combine to narrow the results. Created by is hidden while My Files
is restricted to your own files. Recent offers only file-scope filtering.
`Sort files` offers modified, created, and viewed dates.
Recent uses the viewer's own interaction order and does not offer a sort override.
@@ -480,10 +483,14 @@ while Markdown, code/CSV, image, video, PDF/DOCX, canvas, and unrecognized file
clicks and Enter replace the list with a breadcrumbed detail. Choose the current location
breadcrumb to return to the list; choosing an ancestor file drops newer detail
entries. Opening a list row or sidebar favorite starts a new detail path; only
-navigation originating inside a detail appends to that path. Modified clicks
-retain existing split navigation. On narrow layouts, use `Select Drive view` for tabs, favorites,
-folders, and tags. Navigation state and expanded folders are restored when returning
-from an opened file.
+navigation originating inside a detail appends to that path. Cmd/Ctrl-clicking a
+row toggles selection; Shift-clicking a checkbox selects a range, and Shift+Enter
+opens the focused row in a new split. Cmd/Ctrl-clicking a row's folder link or
+search hit opens a new tab. Short filtered pages load more results automatically;
+a failed page shows a retry action instead of silently stopping. On narrow layouts,
+use `Select Drive view` for tabs, favorites, folders, and tags. Location, search,
+filters, expanded folders, list focus, and scroll position are restored when
+returning from an opened file.
## Calendar — `/app/calendar/view`