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.

fix(soup): add nested doctype and subtype support to front end soup AST utils (#4196)

Seamusf13872bc1d92
diff --git a/js/app/packages/app/component/app-sidebar/sidebar.tsx b/js/app/packages/app/component/app-sidebar/sidebar.tsx
index 1f76035d16..4b4f3d5c8e 100644
--- a/js/app/packages/app/component/app-sidebar/sidebar.tsx
+++ b/js/app/packages/app/component/app-sidebar/sidebar.tsx
@@ -12,6 +12,7 @@ import {
import { CommandState } from '@app/component/command';
import { InteractiveOnboardingModal } from '@app/component/interactive-onboarding/InteractiveOnboardingModal';
import { createMenuOpen, setCreateMenuOpen } from '@app/component/Launcher';
+import { buildDocumentTypeQuery } from '@app/component/next-soup/filters/configs/document-type-query';
import { getDocumentsFilterSplit } from '@app/component/next-soup/soup-view/documents-filter-controllers';
import {
getInboxFilterSplit,
@@ -113,6 +114,8 @@ interface SidebarItem {
hiddenFromSidebar?: boolean;
}
+const markdownDocumentsQuery = buildDocumentTypeQuery(['doc-markdown']);
+
const SIDEBAR_LINKS = [
{
id: 'inbox',
@@ -160,7 +163,7 @@ const SIDEBAR_LINKS = [
label: 'Documents',
href: LIST_VIEW_PATHS.documents,
params: {
- initialFilters: { include: { fileAssoc: ['assoc:md'] } },
+ initialFilters: markdownDocumentsQuery ?? {},
initialClientFilters: {
and: ['document-or-file'],
or: ['doc-markdown'],
diff --git a/js/app/packages/app/component/next-soup/debug/DocumentWherePlayground.tsx b/js/app/packages/app/component/next-soup/debug/DocumentWherePlayground.tsx
new file mode 100644
index 0000000000..117d2f1fb6
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/debug/DocumentWherePlayground.tsx
@@ -0,0 +1,684 @@
+import {
+ compileToAst,
+ type DocumentFieldFilters,
+ type DocumentFilterExpression,
+ type Query,
+ queryStateFrom,
+} from '@app/component/next-soup/filters/filter-store';
+import { throwOnErr } from '@core/util/result';
+import { ListEntity, ListLayoutProvider } from '@entity';
+import {
+ isDisplayableSoupItem,
+ mapApiSoupItemToEntity,
+} from '@queries/soup/transform-utils';
+import { storageServiceClient } from '@service-storage/client';
+import type {
+ PostSoupRequest,
+ SoupApiItem,
+ SoupPage,
+} from '@service-storage/generated/schemas';
+import { Button, InlineCheckbox, SegmentedControl } from '@ui';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+
+type FilterTokenId =
+ | 'pdf'
+ | 'docx'
+ | 'canvas'
+ | 'image-assoc'
+ | 'code-assoc'
+ | 'md'
+ | 'snippet'
+ | 'task'
+ | 'plain-md'
+ | 'email-attachment'
+ | 'not-email-attachment'
+ | 'unseen'
+ | 'seen'
+ | 'not-done'
+ | 'done'
+ | 'updated-this-year';
+type ExpressionMode = 'or' | 'and' | 'nested-md' | 'not-selected';
+type EndpointMode = 'ast' | 'simple';
+
+const NIL_UUID = '00000000-0000-0000-0000-000000000000';
+
+const FILTER_TOKENS: {
+ id: FilterTokenId;
+ label: string;
+ detail: string;
+ expression: DocumentFilterExpression;
+}[] = [
+ {
+ id: 'pdf',
+ label: 'PDF',
+ detail: 'fileType = pdf',
+ expression: { include: { fileType: ['pdf'] } },
+ },
+ {
+ id: 'docx',
+ label: 'DOCX',
+ detail: 'fileType = docx',
+ expression: { include: { fileType: ['docx'] } },
+ },
+ {
+ id: 'canvas',
+ label: 'Canvas',
+ detail: 'fileType = canvas',
+ expression: { include: { fileType: ['canvas'] } },
+ },
+ {
+ id: 'image-assoc',
+ label: 'Images',
+ detail: 'fileAssoc = assoc:image',
+ expression: { include: { fileAssoc: ['assoc:image'] } },
+ },
+ {
+ id: 'code-assoc',
+ label: 'Code',
+ detail: 'fileAssoc = assoc:code',
+ expression: { include: { fileAssoc: ['assoc:code'] } },
+ },
+ {
+ id: 'md',
+ label: 'Any markdown',
+ detail: 'fileType = md',
+ expression: { include: { fileType: ['md'] } },
+ },
+ {
+ id: 'snippet',
+ label: 'Snippet',
+ detail: 'fileType = md AND subType = snippet',
+ expression: {
+ op: 'and',
+ clauses: [
+ { include: { fileType: ['md'] } },
+ { include: { subType: ['snippet'] } },
+ ],
+ },
+ },
+ {
+ id: 'task',
+ label: 'Task',
+ detail: 'fileType = md AND subType = task',
+ expression: {
+ op: 'and',
+ clauses: [
+ { include: { fileType: ['md'] } },
+ { include: { subType: ['task'] } },
+ ],
+ },
+ },
+ {
+ id: 'plain-md',
+ label: 'Plain markdown',
+ detail: 'fileType = md AND NOT subType in snippet/task',
+ expression: {
+ op: 'and',
+ clauses: [
+ { include: { fileType: ['md'] } },
+ { exclude: { subType: ['snippet', 'task'] } },
+ ],
+ },
+ },
+ {
+ id: 'email-attachment',
+ label: 'Email attachments',
+ detail: 'isEmailAttachment = true',
+ expression: { include: { isEmailAttachment: true } },
+ },
+ {
+ id: 'not-email-attachment',
+ label: 'Not email attachments',
+ detail: 'isEmailAttachment = false',
+ expression: { include: { isEmailAttachment: false } },
+ },
+ {
+ id: 'unseen',
+ label: 'Unseen',
+ detail: 'documentSeen = false',
+ expression: { include: { documentSeen: false } },
+ },
+ {
+ id: 'seen',
+ label: 'Seen',
+ detail: 'documentSeen = true',
+ expression: { include: { documentSeen: true } },
+ },
+ {
+ id: 'not-done',
+ label: 'Not done',
+ detail: 'documentDone = false',
+ expression: { include: { documentDone: false } },
+ },
+ {
+ id: 'done',
+ label: 'Done',
+ detail: 'documentDone = true',
+ expression: { include: { documentDone: true } },
+ },
+ {
+ id: 'updated-this-year',
+ label: 'Updated this year',
+ detail: 'documentUpdatedAt >= Jan 1 of the current year',
+ expression: {
+ include: {
+ documentUpdatedAt: {
+ gte: `${new Date().getFullYear()}-01-01T00:00:00.000Z`,
+ },
+ },
+ },
+ },
+];
+
+const EXAMPLES: {
+ label: string;
+ mode: ExpressionMode;
+ tokens: FilterTokenId[];
+}[] = [
+ {
+ label: 'PDF OR markdown snippets/tasks',
+ mode: 'nested-md',
+ tokens: ['pdf', 'snippet', 'task'],
+ },
+ {
+ label: 'Documents: md/canvas but not tasks',
+ mode: 'and',
+ tokens: ['md', 'plain-md'],
+ },
+ {
+ label: 'Unread PDF attachments',
+ mode: 'and',
+ tokens: ['pdf', 'email-attachment', 'unseen'],
+ },
+ {
+ label: 'Everything except selected types',
+ mode: 'not-selected',
+ tokens: ['task', 'snippet'],
+ },
+];
+
+const SIMPLE_SOUP_NON_DOCUMENT_FILTERS: Pick<
+ PostSoupRequest,
+ | 'call_filters'
+ | 'channel_filters'
+ | 'chat_filters'
+ | 'crm_company_filters'
+ | 'email_filters'
+ | 'foreign_entity_filters'
+ | 'project_filters'
+> = {
+ call_filters: { call_ids: [NIL_UUID] },
+ channel_filters: { channel_ids: [NIL_UUID] },
+ chat_filters: { chat_ids: [NIL_UUID] },
+ crm_company_filters: { company_ids: [NIL_UUID] },
+ email_filters: { email_thread_ids: [NIL_UUID] },
+ foreign_entity_filters: { ids: [NIL_UUID] },
+ project_filters: { project_ids: [NIL_UUID] },
+};
+
+const AST_SOUP_DOCUMENT_ONLY_FILTERS: Query['include'] = {
+ callId: [NIL_UUID],
+ channelId: [NIL_UUID],
+ chatId: [NIL_UUID],
+ crmCompanyId: [NIL_UUID],
+ foreignEntityRecordId: [NIL_UUID],
+ folderId: [NIL_UUID],
+ threadId: [NIL_UUID],
+};
+
+function tokenExpression(id: FilterTokenId): DocumentFilterExpression {
+ return FILTER_TOKENS.find((token) => token.id === id)?.expression ?? {};
+}
+
+function expressionFromTokens(
+ selected: Set<FilterTokenId>,
+ mode: ExpressionMode,
+ customClause: DocumentFilterExpression | undefined
+): DocumentFilterExpression {
+ const clauses = [...selected].map(tokenExpression);
+ if (customClause) clauses.push(customClause);
+
+ if (clauses.length === 0) return { include: { documentId: [NIL_UUID] } };
+ if (clauses.length === 1 && mode !== 'not-selected') return clauses[0];
+
+ if (mode === 'and') return { op: 'and', clauses };
+ if (mode === 'not-selected')
+ return { op: 'not', clause: { op: 'or', clauses } };
+ if (mode === 'nested-md') {
+ const markdownClauses = [...selected]
+ .filter((id) => ['md', 'snippet', 'task', 'plain-md'].includes(id))
+ .map(tokenExpression);
+ const nonMarkdownClauses = [...selected]
+ .filter((id) => !['md', 'snippet', 'task', 'plain-md'].includes(id))
+ .map(tokenExpression);
+ const groupedClauses = [
+ ...nonMarkdownClauses,
+ ...(markdownClauses.length
+ ? [{ op: 'or', clauses: markdownClauses } as DocumentFilterExpression]
+ : []),
+ ...(customClause ? [customClause] : []),
+ ];
+
+ if (groupedClauses.length === 1) return groupedClauses[0];
+ return { op: 'or', clauses: groupedClauses };
+ }
+
+ return { op: 'or', clauses };
+}
+
+function simpleRequestFromClauses(
+ selected: Set<FilterTokenId>,
+ limit: number
+): PostSoupRequest {
+ const fileTypes = new Set<string>();
+ const subTypes = new Set<string>();
+
+ if (selected.has('pdf')) fileTypes.add('pdf');
+ if (selected.has('docx')) fileTypes.add('docx');
+ if (selected.has('canvas')) fileTypes.add('canvas');
+
+ if (
+ selected.has('md') ||
+ selected.has('snippet') ||
+ selected.has('task') ||
+ selected.has('plain-md')
+ ) {
+ fileTypes.add('md');
+ }
+
+ if (selected.has('snippet')) subTypes.add('snippet');
+ if (selected.has('task')) subTypes.add('task');
+
+ return {
+ ...SIMPLE_SOUP_NON_DOCUMENT_FILTERS,
+ document_filters: {
+ document_ids: selected.size === 0 ? [NIL_UUID] : undefined,
+ file_types: fileTypes.size ? [...fileTypes] : undefined,
+ sub_types: subTypes.size ? [...subTypes] : undefined,
+ },
+ limit,
+ sort_method: 'viewed_updated',
+ };
+}
+
+export default function DocumentWherePlayground() {
+ const [resultsRef, setResultsRef] = createSignal<HTMLElement>();
+ const [mode, setMode] = createSignal<EndpointMode>('ast');
+ const [expressionMode, setExpressionMode] =
+ createSignal<ExpressionMode>('nested-md');
+ const [selected, setSelected] = createSignal<Set<FilterTokenId>>(
+ new Set(['pdf', 'snippet', 'task'])
+ );
+ const [limit, setLimit] = createSignal(20);
+ const [jsonText, setJsonText] = createSignal('');
+ const [useJson, setUseJson] = createSignal(false);
+ const [documentIds, setDocumentIds] = createSignal('');
+ const [ownerIds, setOwnerIds] = createSignal('');
+ const [projectIds, setProjectIds] = createSignal('');
+ const [updatedAfter, setUpdatedAfter] = createSignal('');
+ const [updatedBefore, setUpdatedBefore] = createSignal('');
+ const [items, setItems] = createSignal<SoupApiItem[]>([]);
+ const [nextCursor, setNextCursor] = createSignal<string | null>(null);
+ const [loading, setLoading] = createSignal(false);
+ const [error, setError] = createSignal<string | undefined>();
+
+ const splitValues = (value: string) =>
+ value
+ .split(',')
+ .map((part) => part.trim())
+ .filter(Boolean);
+
+ const customClause = createMemo<DocumentFilterExpression | undefined>(() => {
+ const include: DocumentFieldFilters = {};
+ const documentIdValues = splitValues(documentIds());
+ const ownerValues = splitValues(ownerIds());
+ const projectValues = splitValues(projectIds());
+ const updatedAfterValue = updatedAfter().trim();
+ const updatedBeforeValue = updatedBefore().trim();
+
+ if (documentIdValues.length) include.documentId = documentIdValues;
+ if (ownerValues.length) include.documentOwnerId = ownerValues;
+ if (projectValues.length) include.projectId = projectValues;
+ if (updatedAfterValue || updatedBeforeValue) {
+ include.documentUpdatedAt = {
+ ...(updatedAfterValue && { gte: updatedAfterValue }),
+ ...(updatedBeforeValue && { lte: updatedBeforeValue }),
+ };
+ }
+
+ return Object.keys(include).length ? { include } : undefined;
+ });
+
+ const selectedExpression = createMemo(() =>
+ expressionFromTokens(selected(), expressionMode(), customClause())
+ );
+
+ const parsedExpression = createMemo<DocumentFilterExpression | undefined>(
+ () => {
+ if (!useJson()) return selectedExpression();
+ try {
+ return JSON.parse(jsonText()) as DocumentFilterExpression;
+ } catch {
+ return undefined;
+ }
+ }
+ );
+
+ const query = createMemo<Query>(() => ({
+ include: AST_SOUP_DOCUMENT_ONLY_FILTERS,
+ documentWhere: parsedExpression(),
+ }));
+
+ const compiled = createMemo(() => compileToAst(queryStateFrom(query())));
+ const requestBody = createMemo(() => ({
+ ...compiled(),
+ limit: limit(),
+ sort_method: 'viewed_updated' as const,
+ }));
+ const simpleRequestBody = createMemo(() =>
+ simpleRequestFromClauses(selected(), limit())
+ );
+ const activeRequestBody = createMemo(() =>
+ mode() === 'ast' ? requestBody() : simpleRequestBody()
+ );
+ const entities = createMemo(() =>
+ items()
+ .filter(isDisplayableSoupItem)
+ .map((item) => mapApiSoupItemToEntity(item))
+ );
+
+ const run = async (cursor: string | null = null) => {
+ setLoading(true);
+ setError(undefined);
+
+ try {
+ if (!parsedExpression()) {
+ throw new Error('Expression JSON is not valid');
+ }
+
+ const page = await throwOnErr(async () => {
+ if (mode() === 'simple') {
+ return await storageServiceClient.getSoupItems({
+ params: { cursor },
+ body: simpleRequestBody(),
+ });
+ }
+
+ return await storageServiceClient.getSoupAstItems({
+ params: { cursor },
+ body: requestBody(),
+ });
+ });
+
+ const soupPage = page as SoupPage;
+ setItems((prev) =>
+ cursor ? [...prev, ...soupPage.items] : soupPage.items
+ );
+ setNextCursor(soupPage.next_cursor ?? null);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const toggleToken = (id: FilterTokenId) => {
+ setUseJson(false);
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) {
+ next.delete(id);
+ } else {
+ next.add(id);
+ }
+ return next;
+ });
+ };
+
+ const loadJsonFromControls = () => {
+ setJsonText(JSON.stringify(selectedExpression(), null, 2));
+ setUseJson(true);
+ };
+
+ const applyExample = (example: (typeof EXAMPLES)[number]) => {
+ setUseJson(false);
+ setExpressionMode(example.mode);
+ setSelected(new Set(example.tokens));
+ };
+
+ return (
+ <div class="flex h-full flex-col bg-bg text-ink">
+ <header class="flex h-10 shrink-0 items-center border-edge-muted border-b px-4">
+ <div class="text-sm font-medium">Document AST Playground</div>
+ </header>
+ <div class="grid min-h-0 flex-1 grid-cols-[420px_1fr] overflow-hidden">
+ <aside class="flex min-h-0 flex-col gap-4 border-edge-muted border-r p-4">
+ <section class="space-y-2">
+ <div class="text-sm font-medium">Endpoint</div>
+ <SegmentedControl
+ class="w-full"
+ size="sm"
+ value={mode()}
+ options={[
+ { value: 'ast', label: 'AST soup' },
+ { value: 'simple', label: 'Simple soup' },
+ ]}
+ onChange={(value) => setMode(value)}
+ />
+ </section>
+
+ <section class="space-y-3">
+ <div class="text-sm font-medium">Expression shape</div>
+ <select
+ class="w-full rounded-sm border border-edge-muted bg-surface p-1.5 text-sm outline-none focus:border-accent"
+ value={expressionMode()}
+ onChange={(event) =>
+ setExpressionMode(event.currentTarget.value as ExpressionMode)
+ }
+ >
+ <option value="or">OR selected clauses</option>
+ <option value="and">AND selected clauses</option>
+ <option value="nested-md">
+ OR selected, grouping markdown subtypes
+ </option>
+ <option value="not-selected">NOT selected clauses</option>
+ </select>
+ </section>
+
+ <section class="space-y-2">
+ <div class="text-sm font-medium">Examples</div>
+ <div class="grid grid-cols-1 gap-1">
+ <For each={EXAMPLES}>
+ {(example) => (
+ <Button
+ variant="base"
+ size="sm"
+ class="h-auto justify-start py-1.5"
+ onClick={() => applyExample(example)}
+ >
+ {example.label}
+ </Button>
+ )}
+ </For>
+ </div>
+ </section>
+
+ <section class="min-h-0 space-y-3 overflow-auto">
+ <div class="text-sm font-medium">Document clauses</div>
+ <div class="grid grid-cols-2 gap-2">
+ <For each={FILTER_TOKENS}>
+ {(token) => (
+ <button
+ type="button"
+ class="flex min-h-14 items-start gap-2 rounded-sm border border-edge-muted bg-surface p-2 text-left text-sm hover:bg-hover"
+ classList={{
+ 'border-accent/50 bg-accent-bg/30': selected().has(
+ token.id
+ ),
+ }}
+ onClick={() => toggleToken(token.id)}
+ >
+ <InlineCheckbox checked={selected().has(token.id)} />
+ <span class="min-w-0">
+ <span class="block">{token.label}</span>
+ <span class="block text-ink-secondary text-xs">
+ {token.detail}
+ </span>
+ </span>
+ </button>
+ )}
+ </For>
+ </div>
+ </section>
+
+ <section class="space-y-2">
+ <div class="text-sm font-medium">Custom include fields</div>
+ <input
+ class="w-full rounded-sm border border-edge-muted bg-surface p-1.5 text-sm outline-none focus:border-accent"
+ placeholder="document ids, comma separated"
+ value={documentIds()}
+ onInput={(event) => setDocumentIds(event.currentTarget.value)}
+ />
+ <input
+ class="w-full rounded-sm border border-edge-muted bg-surface p-1.5 text-sm outline-none focus:border-accent"
+ placeholder="owner ids, comma separated"
+ value={ownerIds()}
+ onInput={(event) => setOwnerIds(event.currentTarget.value)}
+ />
+ <input
+ class="w-full rounded-sm border border-edge-muted bg-surface p-1.5 text-sm outline-none focus:border-accent"
+ placeholder="project ids, comma separated"
+ value={projectIds()}
+ onInput={(event) => setProjectIds(event.currentTarget.value)}
+ />
+ <div class="grid grid-cols-2 gap-2">
+ <input
+ class="rounded-sm border border-edge-muted bg-surface p-1.5 text-sm outline-none focus:border-accent"
+ placeholder="updated >= ISO"
+ value={updatedAfter()}
+ onInput={(event) => setUpdatedAfter(event.currentTarget.value)}
+ />
+ <input
+ class="rounded-sm border border-edge-muted bg-surface p-1.5 text-sm outline-none focus:border-accent"
+ placeholder="updated <= ISO"
+ value={updatedBefore()}
+ onInput={(event) => setUpdatedBefore(event.currentTarget.value)}
+ />
+ </div>
+ </section>
+
+ <section class="space-y-2">
+ <div class="text-sm font-medium">Limit</div>
+ <input
+ class="w-24 rounded-sm border border-edge-muted bg-surface p-1 text-sm outline-none focus:border-accent"
+ type="number"
+ min="1"
+ max="100"
+ value={limit()}
+ onInput={(event) =>
+ setLimit(Number(event.currentTarget.value) || 20)
+ }
+ />
+ </section>
+
+ <section class="flex gap-2">
+ <Button variant="base" size="sm" onClick={loadJsonFromControls}>
+ Edit JSON
+ </Button>
+ <Button
+ variant="cta"
+ size="sm"
+ disabled={loading()}
+ onClick={() => run()}
+ >
+ Run
+ </Button>
+ </section>
+
+ <Show when={useJson()}>
+ <section class="min-h-0 flex-1 space-y-2">
+ <div class="text-sm font-medium">documentWhere JSON</div>
+ <textarea
+ class="h-full min-h-48 w-full resize-none rounded-sm border border-edge-muted bg-surface p-2 font-mono text-xs outline-none focus:border-accent"
+ value={jsonText()}
+ onInput={(event) => setJsonText(event.currentTarget.value)}
+ />
+ </section>
+ </Show>
+ </aside>
+
+ <main class="grid min-h-0 grid-cols-2 overflow-hidden">
+ <section class="min-h-0 overflow-auto border-edge-muted border-r p-4">
+ <div class="mb-2 text-sm font-medium">documentWhere expression</div>
+ <pre class="mb-4 whitespace-pre-wrap rounded-sm border border-edge-muted bg-surface p-3 font-mono text-xs">
+ {JSON.stringify(parsedExpression(), null, 2)}
+ </pre>
+ <div class="mb-2 text-sm font-medium">
+ {mode() === 'ast'
+ ? 'Compiled AST request body'
+ : 'Simple soup request body'}
+ </div>
+ <pre class="whitespace-pre-wrap rounded-sm border border-edge-muted bg-surface p-3 font-mono text-xs">
+ {JSON.stringify(activeRequestBody(), null, 2)}
+ </pre>
+ <Show when={mode() === 'simple' && selected().has('plain-md')}>
+ <div class="mt-3 rounded-sm border border-edge-muted bg-surface p-2 text-ink-secondary text-sm">
+ Simple soup cannot express the plain-markdown exclusion for
+ snippet/task. It requests markdown documents and shows the old
+ flat-filter behavior.
+ </div>
+ </Show>
+ <Show when={error()}>
+ <div class="mt-3 rounded-sm border border-failure/50 bg-failure/10 p-2 text-failure text-sm">
+ {error()}
+ </div>
+ </Show>
+ </section>
+
+ <section ref={setResultsRef} class="min-h-0 overflow-auto p-4">
+ <div class="mb-3 flex items-center justify-between">
+ <div class="text-sm font-medium">
+ Soup entities ({entities().length})
+ </div>
+ <Show when={nextCursor()}>
+ <Button
+ variant="base"
+ size="sm"
+ disabled={loading()}
+ onClick={() => run(nextCursor())}
+ >
+ Load more
+ </Button>
+ </Show>
+ </div>
+
+ <Show when={loading()}>
+ <div class="mb-3 text-ink-secondary text-sm">Loading...</div>
+ </Show>
+
+ <Show when={items().length !== entities().length}>
+ <div class="mb-3 rounded-sm border border-edge-muted bg-surface p-2 text-ink-secondary text-sm">
+ {items().length - entities().length} returned soup items were
+ not displayable entity rows.
+ </div>
+ </Show>
+
+ <ListLayoutProvider ref={resultsRef}>
+ <div class="space-y-1">
+ <For each={entities()}>
+ {(entity) => (
+ <ListEntity
+ entity={entity}
+ hideCheckbox
+ onClick={() => console.log('Soup entity:', entity)}
+ />
+ )}
+ </For>
+ </div>
+ </ListLayoutProvider>
+ </section>
+ </main>
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/app/component/next-soup/filters/configs/document-type-query.test.ts b/js/app/packages/app/component/next-soup/filters/configs/document-type-query.test.ts
new file mode 100644
index 0000000000..3e88834c70
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/filters/configs/document-type-query.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildDocumentTypeQuery,
+ getActiveDocumentTypeFilterIds,
+ isDocumentTypeFilterId,
+} from './document-type-query';
+
+describe('document type query helpers', () => {
+ it('groups selected document type chips into one OR documentWhere query', () => {
+ expect(buildDocumentTypeQuery(['file-pdf', 'doc-snippet'])).toEqual({
+ documentWhere: {
+ op: 'or',
+ clauses: [
+ { include: { fileType: ['pdf'] } },
+ {
+ op: 'and',
+ clauses: [
+ { include: { fileType: ['md'] } },
+ { include: { subType: ['snippet'] } },
+ ],
+ },
+ ],
+ },
+ });
+ });
+
+ it('filters active ids to supported document type chips in stable order', () => {
+ const active = new Set(['doc-snippet', 'file-pdf', 'email-attachments']);
+
+ expect(getActiveDocumentTypeFilterIds((id) => active.has(id))).toEqual([
+ 'file-pdf',
+ 'doc-snippet',
+ ]);
+ });
+
+ it('identifies document type chip ids', () => {
+ expect(isDocumentTypeFilterId('file-pdf')).toBe(true);
+ expect(isDocumentTypeFilterId('email-attachments')).toBe(false);
+ });
+});
diff --git a/js/app/packages/app/component/next-soup/filters/configs/document-type-query.ts b/js/app/packages/app/component/next-soup/filters/configs/document-type-query.ts
new file mode 100644
index 0000000000..ee62d89cc6
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/filters/configs/document-type-query.ts
@@ -0,0 +1,73 @@
+import type { FilterID } from '@app/component/next-soup/filters';
+import type {
+ DocumentFilterExpression,
+ Query,
+} from '@app/component/next-soup/filters/filter-store';
+
+const DOCUMENT_TYPE_FILTER_IDS = [
+ 'doc-markdown',
+ 'doc-canvas',
+ 'file-code',
+ 'file-image',
+ 'file-pdf',
+ 'file-docx',
+ 'file-video',
+ 'doc-snippet',
+ 'file-other',
+] as const satisfies readonly FilterID[];
+
+type DocumentTypeFilterId = (typeof DOCUMENT_TYPE_FILTER_IDS)[number];
+
+export const documentTypeFilterIds = new Set<string>(DOCUMENT_TYPE_FILTER_IDS);
+
+export const isDocumentTypeFilterId = (
+ id: string
+): id is DocumentTypeFilterId => documentTypeFilterIds.has(id);
+
+const documentTypeExpressions: Record<
+ DocumentTypeFilterId,
+ DocumentFilterExpression
+> = {
+ 'doc-markdown': {
+ op: 'and',
+ clauses: [
+ { include: { fileType: ['md'] } },
+ { exclude: { subType: ['snippet', 'task'] } },
+ ],
+ },
+ 'doc-canvas': { include: { fileType: ['canvas'] } },
+ 'file-code': { include: { fileAssoc: ['assoc:code'] } },
+ 'file-image': { include: { fileAssoc: ['assoc:image'] } },
+ 'file-pdf': { include: { fileType: ['pdf'] } },
+ 'file-docx': { include: { fileType: ['docx'] } },
+ 'file-video': { include: { fileAssoc: ['assoc:video'] } },
+ 'doc-snippet': {
+ op: 'and',
+ clauses: [
+ { include: { fileType: ['md'] } },
+ { include: { subType: ['snippet'] } },
+ ],
+ },
+ 'file-other': {
+ include: { fileAssoc: ['assoc:other'] },
+ exclude: { fileAssoc: ['assoc:document', 'assoc:image', 'assoc:video'] },
+ },
+};
+
+export const getActiveDocumentTypeFilterIds = (
+ isActive: (id: string) => boolean
+) => DOCUMENT_TYPE_FILTER_IDS.filter((id) => isActive(id));
+
+export const buildDocumentTypeQuery = (
+ ids: readonly string[]
+): Query | undefined => {
+ const clauses = ids
+ .filter(isDocumentTypeFilterId)
+ .map((id) => documentTypeExpressions[id]);
+
+ if (clauses.length === 0) return undefined;
+
+ return {
+ documentWhere: clauses.length === 1 ? clauses[0] : { op: 'or', clauses },
+ };
+};
diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/compile.test.ts b/js/app/packages/app/component/next-soup/filters/filter-store/compile.test.ts
index 16d6bd124e..5dffd3b689 100644
--- a/js/app/packages/app/component/next-soup/filters/filter-store/compile.test.ts
+++ b/js/app/packages/app/component/next-soup/filters/filter-store/compile.test.ts
@@ -1,7 +1,111 @@
import { describe, expect, it } from 'vitest';
import { compileToAst, queryStateFrom } from './compile';
+import type { DocumentFilterExpression, QueryState } from './types';
describe('compileToAst', () => {
+ it('keeps existing flat include and exclude document filters unchanged', () => {
+ const state: QueryState = {
+ include: {
+ fileType: ['pdf', 'md'],
+ subType: ['snippet', 'task'],
+ },
+ exclude: {
+ documentOwnerId: ['user-1'],
+ },
+ };
+
+ expect(compileToAst(state).df).toEqual({
+ '&': [
+ {
+ '|': [{ l: { ft: 'pdf' } }, { l: { ft: 'md' } }],
+ },
+ {
+ '&': [
+ {
+ '|': [{ l: { dst: 'snippet' } }, { l: { dst: 'task' } }],
+ },
+ {
+ '!': { l: { o: 'user-1' } },
+ },
+ ],
+ },
+ ],
+ });
+ });
+
+ it('compiles nested documentWhere OR across file type and subtype groups', () => {
+ const expression: DocumentFilterExpression = {
+ op: 'or',
+ clauses: [
+ { include: { fileType: ['pdf'] } },
+ {
+ op: 'and',
+ clauses: [
+ { include: { fileType: ['md'] } },
+ { include: { subType: ['snippet', 'task'] } },
+ ],
+ },
+ ],
+ };
+
+ expect(
+ compileToAst({
+ include: {},
+ exclude: {},
+ documentWhere: [expression],
+ }).df
+ ).toEqual({
+ '|': [
+ { l: { ft: 'pdf' } },
+ {
+ '&': [
+ { l: { ft: 'md' } },
+ {
+ '|': [{ l: { dst: 'snippet' } }, { l: { dst: 'task' } }],
+ },
+ ],
+ },
+ ],
+ });
+ });
+
+ it('ANDs documentWhere with top-level document filters', () => {
+ expect(
+ compileToAst({
+ include: { projectId: ['project-1'] },
+ exclude: {},
+ documentWhere: [{ include: { fileType: ['pdf'] } }],
+ }).df
+ ).toEqual({
+ '&': [{ l: { pid: 'project-1' } }, { l: { ft: 'pdf' } }],
+ });
+ });
+
+ it('supports NOT groups in documentWhere', () => {
+ expect(
+ compileToAst({
+ include: {},
+ exclude: {},
+ documentWhere: [
+ {
+ op: 'not',
+ clause: { include: { subType: ['task'] } },
+ },
+ ],
+ }).df
+ ).toEqual({
+ '!': { l: { dst: 'task' } },
+ });
+ });
+
+ it('normalizes query documentWhere into QueryState', () => {
+ expect(
+ queryStateFrom({
+ documentWhere: { include: { fileType: ['pdf'] } },
+ }).documentWhere
+ ).toEqual([{ include: { fileType: ['pdf'] } }]);
+ });
+
it('compiles foreign entity source filters to the backend AST source literal', () => {
const ast = compileToAst(
queryStateFrom({
diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts b/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts
index 43e1e008b2..547754acd0 100644
--- a/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts
+++ b/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts
@@ -1,5 +1,7 @@
import type {
DateRangeFilter,
+ DocumentFieldFilters,
+ DocumentFilterExpression,
EmailView,
FieldFilters,
FieldName,
@@ -157,29 +159,44 @@ const propertyToAst = (p: PropertyFilter): BackendAst =>
const propertyEquals = (a: PropertyFilter, b: PropertyFilter): boolean =>
a.propertyId === b.propertyId && a.type === b.type && a.value === b.value;
+export const normalizeDocumentWhere = (
+ documentWhere: Query['documentWhere']
+): DocumentFilterExpression[] | undefined => {
+ if (!documentWhere) return undefined;
+ return Array.isArray(documentWhere) ? documentWhere : [documentWhere];
+};
+
export const queryStateFrom = (query: Query): QueryState => ({
include: { ...(query.include ?? {}) },
exclude: { ...(query.exclude ?? {}) },
+ documentWhere: normalizeDocumentWhere(query.documentWhere),
emailView: query.emailView,
});
-export function compileToAst(state: QueryState): TargetAstMap {
- const byTarget: Record<QueryTarget, BackendAst[]> = {
- df: [],
- ef: [],
- chanf: [],
- cf: [],
- pf: [],
- callf: [],
- fef: [],
- ccf: [],
- propf: [],
- };
+const emptyTargetAstLists = (): Record<QueryTarget, BackendAst[]> => ({
+ df: [],
+ ef: [],
+ chanf: [],
+ cf: [],
+ pf: [],
+ callf: [],
+ fef: [],
+ ccf: [],
+ propf: [],
+});
+function pushFieldFiltersToTargets(
+ byTarget: Record<QueryTarget, BackendAst[]>,
+ include: FieldFilters,
+ exclude: FieldFilters,
+ options: { onlyTarget?: QueryTarget } = {}
+) {
for (const fieldName of Object.keys(FIELD_CONFIG) as CompiledFieldName[]) {
const config = FIELD_CONFIG[fieldName];
- const includeVal = state.include[fieldName];
- const excludeVal = state.exclude[fieldName];
+ if (options.onlyTarget && config.target !== options.onlyTarget) continue;
+
+ const includeVal = include[fieldName];
+ const excludeVal = exclude[fieldName];
if (config.unit) {
if (includeVal === true) {
@@ -227,6 +244,83 @@ export function compileToAst(state: QueryState): TargetAstMap {
}
}
}
+}
+
+function pushDateRangeFiltersToTargets(
+ byTarget: Record<QueryTarget, BackendAst[]>,
+ include: FieldFilters,
+ exclude: FieldFilters,
+ options: { onlyTarget?: QueryTarget } = {}
+) {
+ for (const [fieldName, config] of Object.entries(DATE_RANGE_FIELDS)) {
+ if (options.onlyTarget && config.target !== options.onlyTarget) continue;
+
+ const includeVal = include[fieldName as FieldName] as
+ | DateRangeFilter
+ | undefined;
+ const excludeVal = exclude[fieldName as FieldName] as
+ | DateRangeFilter
+ | undefined;
+
+ if (includeVal) {
+ byTarget[config.target].push(
+ ...expandDateRange(config.field, includeVal)
+ );
+ }
+ if (excludeVal) {
+ const expanded = expandDateRange(config.field, excludeVal);
+ if (expanded.length) {
+ byTarget[config.target].push(AST.not(AST.and(expanded)));
+ }
+ }
+ }
+}
+
+function compileDocumentClauseToAst(clause: {
+ include?: DocumentFieldFilters;
+ exclude?: DocumentFieldFilters;
+}): BackendAst | undefined {
+ const byTarget = emptyTargetAstLists();
+ pushFieldFiltersToTargets(
+ byTarget,
+ clause.include ?? {},
+ clause.exclude ?? {},
+ { onlyTarget: 'df' }
+ );
+ pushDateRangeFiltersToTargets(
+ byTarget,
+ clause.include ?? {},
+ clause.exclude ?? {},
+ { onlyTarget: 'df' }
+ );
+
+ return byTarget.df.length ? AST.and(byTarget.df) : undefined;
+}
+
+export function compileDocumentExpressionToAst(
+ expression: DocumentFilterExpression
+): BackendAst | undefined {
+ if ('op' in expression) {
+ if (expression.op === 'not') {
+ const child = compileDocumentExpressionToAst(expression.clause);
+ return child ? AST.not(child) : undefined;
+ }
+
+ const clauses = expression.clauses
+ .map(compileDocumentExpressionToAst)
+ .filter((ast): ast is BackendAst => ast !== undefined);
+
+ if (clauses.length === 0) return undefined;
+ return expression.op === 'and' ? AST.and(clauses) : AST.or(clauses);
+ }
+
+ return compileDocumentClauseToAst(expression);
+}
+
+export function compileToAst(state: QueryState): TargetAstMap {
+ const byTarget = emptyTargetAstLists();
+
+ pushFieldFiltersToTargets(byTarget, state.include, state.exclude);
const includeProps = state.include.properties ?? [];
const excludeProps = state.exclude.properties ?? [];
@@ -273,25 +367,11 @@ export function compileToAst(state: QueryState): TargetAstMap {
}
}
- for (const [fieldName, config] of Object.entries(DATE_RANGE_FIELDS)) {
- const includeVal = state.include[fieldName as FieldName] as
- | DateRangeFilter
- | undefined;
- const excludeVal = state.exclude[fieldName as FieldName] as
- | DateRangeFilter
- | undefined;
+ pushDateRangeFiltersToTargets(byTarget, state.include, state.exclude);
- if (includeVal) {
- byTarget[config.target].push(
- ...expandDateRange(config.field, includeVal)
- );
- }
- if (excludeVal) {
- const expanded = expandDateRange(config.field, excludeVal);
- if (expanded.length) {
- byTarget[config.target].push(AST.not(AST.and(expanded)));
- }
- }
+ for (const expression of state.documentWhere ?? []) {
+ const ast = compileDocumentExpressionToAst(expression);
+ if (ast) byTarget.df.push(ast);
}
const result: TargetAstMap = {};
@@ -327,6 +407,10 @@ type DefineQueryFiltersOptions = {
const extractQueryTargets = (query: Query): QueryTarget[] => {
const targets = new Set<QueryTarget>();
+ if (query.documentWhere) {
+ targets.add('df');
+ }
+
for (const field of Object.keys(query.include ?? {})) {
if (field in FIELD_CONFIG) {
targets.add(FIELD_CONFIG[field as CompiledFieldName].target);
diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/index.ts b/js/app/packages/app/component/next-soup/filters/filter-store/index.ts
index 847423067d..a6938b913c 100644
--- a/js/app/packages/app/component/next-soup/filters/filter-store/index.ts
+++ b/js/app/packages/app/component/next-soup/filters/filter-store/index.ts
@@ -4,6 +4,9 @@ export {
queryStateFrom,
} from './compile';
export type {
+ DocumentFieldFilters,
+ DocumentFilterClause,
+ DocumentFilterExpression,
PropertyFilter,
Query,
QueryState,
diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/query-store.ts b/js/app/packages/app/component/next-soup/filters/filter-store/query-store.ts
index 0a92412e0f..c45a741daf 100644
--- a/js/app/packages/app/component/next-soup/filters/filter-store/query-store.ts
+++ b/js/app/packages/app/component/next-soup/filters/filter-store/query-store.ts
@@ -1,8 +1,18 @@
+import { deepEqual } from '@core/util/compareUtils';
import { batch } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
-import { compileToAst, type TargetAstMap } from './compile';
+import {
+ compileToAst,
+ normalizeDocumentWhere,
+ type TargetAstMap,
+} from './compile';
import { addFieldValues, removeFieldValues } from './field-values';
-import type { FieldFilters, Query, QueryState } from './types';
+import type {
+ DocumentFilterExpression,
+ FieldFilters,
+ Query,
+ QueryState,
+} from './types';
export type { Query } from './types';
@@ -13,6 +23,7 @@ type QueryStoreOptions = {
const emptyQueryState = (): QueryState => ({
include: {},
exclude: {},
+ documentWhere: undefined,
emailView: undefined,
});
@@ -53,9 +64,30 @@ const partialFieldUpdate = (updates: FieldFilters): Record<string, unknown> => {
export const mergeQuery = (base: QueryState, query: Query): QueryState => ({
include: addFieldValues(base.include, query.include),
exclude: addFieldValues(base.exclude, query.exclude),
+ documentWhere: query.documentWhere
+ ? [
+ ...(base.documentWhere ?? []),
+ ...normalizeDocumentWhere(query.documentWhere)!,
+ ]
+ : base.documentWhere,
emailView: query.emailView ?? base.emailView,
});
+const removeDocumentWhere = (
+ existing: DocumentFilterExpression[] | undefined,
+ remove: Query['documentWhere']
+): DocumentFilterExpression[] | undefined => {
+ if (!existing || !remove) return existing;
+
+ const next = [...existing];
+ for (const expression of normalizeDocumentWhere(remove) ?? []) {
+ const index = next.findIndex((expr) => deepEqual(expr, expression));
+ if (index !== -1) next.splice(index, 1);
+ }
+
+ return next.length ? next : undefined;
+};
+
export function createQueryStore(options: QueryStoreOptions = {}) {
const { initial } = options;
@@ -73,6 +105,10 @@ export function createQueryStore(options: QueryStoreOptions = {}) {
setState((prev) => ({
include: removeFieldValues(prev.include, query.include),
exclude: removeFieldValues(prev.exclude, query.exclude),
+ documentWhere: removeDocumentWhere(
+ prev.documentWhere,
+ query.documentWhere
+ ),
emailView:
query.emailView && prev.emailView === query.emailView
? undefined
@@ -89,6 +125,7 @@ export function createQueryStore(options: QueryStoreOptions = {}) {
reconcile({
include: compactedFields({}, query.include),
exclude: compactedFields({}, query.exclude),
+ documentWhere: normalizeDocumentWhere(query.documentWhere),
emailView: query.emailView,
})
);
@@ -102,6 +139,12 @@ export function createQueryStore(options: QueryStoreOptions = {}) {
if (query.exclude) {
setState('exclude', partialFieldUpdate(query.exclude));
}
+ if (query.documentWhere) {
+ setState('documentWhere', [
+ ...(state.documentWhere ?? []),
+ ...normalizeDocumentWhere(query.documentWhere)!,
+ ]);
+ }
if (query.emailView !== undefined) {
setState('emailView', query.emailView);
}
diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/types.ts b/js/app/packages/app/component/next-soup/filters/filter-store/types.ts
index 5fa739bde2..b125037f08 100644
--- a/js/app/packages/app/component/next-soup/filters/filter-store/types.ts
+++ b/js/app/packages/app/component/next-soup/filters/filter-store/types.ts
@@ -86,14 +86,42 @@ export type FieldFilters = ArrayFieldFilters & ScalarFieldFilters;
export type FieldName = keyof FieldFilters;
+export type DocumentFieldName =
+ | 'documentId'
+ | 'fileType'
+ | 'fileAssoc'
+ | 'subType'
+ | 'projectId'
+ | 'documentOwnerId'
+ | 'documentSeen'
+ | 'documentDone'
+ | 'isEmailAttachment'
+ | 'documentCreatedAt'
+ | 'documentUpdatedAt';
+
+export type DocumentFieldFilters = Pick<FieldFilters, DocumentFieldName>;
+
+export type DocumentFilterClause = {
+ include?: DocumentFieldFilters;
+ exclude?: DocumentFieldFilters;
+};
+
+export type DocumentFilterExpression =
+ | DocumentFilterClause
+ | { op: 'and'; clauses: DocumentFilterExpression[] }
+ | { op: 'or'; clauses: DocumentFilterExpression[] }
+ | { op: 'not'; clause: DocumentFilterExpression };
+
export type QueryState = {
include: FieldFilters;
exclude: FieldFilters;
+ documentWhere?: DocumentFilterExpression[];
emailView?: EmailView;
};
export type Query = {
include?: FieldFilters;
exclude?: FieldFilters;
+ documentWhere?: DocumentFilterExpression | DocumentFilterExpression[];
emailView?: EmailView;
};
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx
index bd528ec979..ebd9896eca 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx
@@ -7,6 +7,11 @@ import {
type FilterContext,
NO_ASSIGNEE,
} from '@app/component/next-soup/filters';
+import {
+ buildDocumentTypeQuery,
+ getActiveDocumentTypeFilterIds,
+ isDocumentTypeFilterId,
+} from '@app/component/next-soup/filters/configs/document-type-query';
import {
CHANNEL_SORT_OPTIONS,
DEFAULT_SORT_OPTIONS,
@@ -156,8 +161,23 @@ export const MobileFilterDrawer = () => {
const toggleFilter = (optionId: FilterOption['id']) => {
const wasActive = soup.predicates.isActive(optionId);
+ const previousDocumentTypeIds =
+ currentView() === 'documents' && isDocumentTypeFilterId(optionId)
+ ? getActiveDocumentTypeFilterIds(soup.predicates.isActive)
+ : undefined;
+
soup.predicates.toggle({ or: [optionId] });
+ if (previousDocumentTypeIds) {
+ const previousQuery = buildDocumentTypeQuery(previousDocumentTypeIds);
+ const nextQuery = buildDocumentTypeQuery(
+ getActiveDocumentTypeFilterIds(soup.predicates.isActive)
+ );
+ if (previousQuery) queryFilters.remove(previousQuery);
+ if (nextQuery) queryFilters.add(nextQuery);
+ return;
+ }
+
const filter = soup.predicates.getConfig(optionId);
if (!filter?.query) return;
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx
index 8271bcfa9c..c5e3e94f1e 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx
@@ -3,6 +3,11 @@ import {
type FilterContext,
NO_ASSIGNEE,
} from '@app/component/next-soup/filters/configs/';
+import {
+ buildDocumentTypeQuery,
+ getActiveDocumentTypeFilterIds,
+ isDocumentTypeFilterId,
+} from '@app/component/next-soup/filters/configs/document-type-query';
import {
defineQueryFilters,
type PropertyFilter,
@@ -505,8 +510,23 @@ export const UnifiedFilterDropdown = (
const toggleFilter = (optionId: string) => {
const wasActive = soup.predicates.isActive(optionId);
+ const previousDocumentTypeIds =
+ currentView() === 'documents' && isDocumentTypeFilterId(optionId)
+ ? getActiveDocumentTypeFilterIds(soup.predicates.isActive)
+ : undefined;
+
soup.predicates.toggle({ or: [optionId] });
+ if (previousDocumentTypeIds) {
+ const previousQuery = buildDocumentTypeQuery(previousDocumentTypeIds);
+ const nextQuery = buildDocumentTypeQuery(
+ getActiveDocumentTypeFilterIds(soup.predicates.isActive)
+ );
+ if (previousQuery) queryFilters.remove(previousQuery);
+ if (nextQuery) queryFilters.add(nextQuery);
+ return;
+ }
+
const filter = soup.predicates.getConfig(optionId);
if (!filter?.query) return;
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx
index 4193778c85..ca1d279f10 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx
@@ -8,6 +8,10 @@ import {
type FilterID,
NO_ASSIGNEE,
} from '@app/component/next-soup/filters';
+import {
+ buildDocumentTypeQuery,
+ getActiveDocumentTypeFilterIds,
+} from '@app/component/next-soup/filters/configs/document-type-query';
import {
defineQueryFilters,
type Query,
@@ -116,10 +120,14 @@ export function useFilterRefinements() {
// Check if there are any external filters set (normalize undefined vs {} for comparison)
const currentFilterData = filterData();
- const presetFilters = preset.filters;
+ const presetFilters = queryStateFrom(preset.filters);
const hasQueryFilterDiff =
- !deepEqual(currentFilterData.include, presetFilters.include ?? {}) ||
- !deepEqual(currentFilterData.exclude, presetFilters.exclude ?? {}) ||
+ !deepEqual(currentFilterData.include, presetFilters.include) ||
+ !deepEqual(currentFilterData.exclude, presetFilters.exclude) ||
+ !deepEqual(
+ currentFilterData.documentWhere,
+ presetFilters.documentWhere
+ ) ||
currentFilterData.emailView !== presetFilters.emailView;
const hasSubFilters = assigneeFilter().length > 0;
@@ -368,6 +376,12 @@ export function useFilterRefinements() {
onToggleValue: (id) => {
const isInboxTypeFilter =
currentView() === 'inbox' && categoryId === 'type';
+ const isDocumentTypeFilter =
+ currentView() === 'documents' && categoryId === 'type';
+ const previousDocumentTypeIds = isDocumentTypeFilter
+ ? getActiveDocumentTypeFilterIds(soup.predicates.isActive)
+ : undefined;
+
batch(() => {
soup.predicates.toggle({ or: [id as FilterID] });
@@ -379,6 +393,18 @@ export function useFilterRefinements() {
return;
}
+ if (previousDocumentTypeIds) {
+ const previousQuery = buildDocumentTypeQuery(
+ previousDocumentTypeIds
+ );
+ const nextQuery = buildDocumentTypeQuery(
+ getActiveDocumentTypeFilterIds(soup.predicates.isActive)
+ );
+ if (previousQuery) queryFilters.remove(previousQuery);
+ if (nextQuery) queryFilters.add(nextQuery);
+ return;
+ }
+
const query = getFilterQuery(id);
if (!query) return;
@@ -394,6 +420,12 @@ export function useFilterRefinements() {
const currentValues = getActiveValues();
const isInboxTypeFilter =
currentView() === 'inbox' && categoryId === 'type';
+ const isDocumentTypeFilter =
+ currentView() === 'documents' && categoryId === 'type';
+ const previousDocumentTypeIds = isDocumentTypeFilter
+ ? getActiveDocumentTypeFilterIds(soup.predicates.isActive)
+ : undefined;
+
batch(() => {
for (const value of currentValues) {
soup.predicates.toggle({ or: [value.id as FilterID] });
@@ -404,6 +436,18 @@ export function useFilterRefinements() {
return;
}
+ if (previousDocumentTypeIds) {
+ const previousQuery = buildDocumentTypeQuery(
+ previousDocumentTypeIds
+ );
+ const nextQuery = buildDocumentTypeQuery(
+ getActiveDocumentTypeFilterIds(soup.predicates.isActive)
+ );
+ if (previousQuery) queryFilters.remove(previousQuery);
+ if (nextQuery) queryFilters.add(nextQuery);
+ return;
+ }
+
for (const value of currentValues) {
const query = getFilterQuery(value.id);
if (query) queryFilters.remove(query);
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
index f7b3af6145..7b52a4a425 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
@@ -13,10 +13,8 @@ import type {
GroupHeaderProps,
SoupRow,
} from '@app/component/next-soup/create-soup-state';
-import type {
- Query,
- QueryState,
-} from '@app/component/next-soup/filters/filter-store';
+import { buildDocumentTypeQuery } from '@app/component/next-soup/filters/configs/document-type-query';
+import type { Query } from '@app/component/next-soup/filters/filter-store';
import type { SetPredicatesInput } from '@app/component/next-soup/filters/filter-store/predicates-store';
import { useSoup } from '@app/component/next-soup/soup-context';
import { registerDocumentsFilterSplit } from '@app/component/next-soup/soup-view/documents-filter-controllers';
@@ -367,7 +365,7 @@ const listStateCache = new Map<
interface SoupViewProps {
viewName: string;
initialClientFilters?: SetPredicatesInput<string>;
- initialFilters?: Partial<QueryState>;
+ initialFilters?: Query;
initialSearchText?: string;
/**
* Initial group-by id (same format as `soup.grouping.setActiveGroupId`,
@@ -466,7 +464,9 @@ export const SoupView = (props: SoupViewProps) => {
onMount(() => {
if (contentId !== 'documents') return;
- const markdownQuery: Query = { include: { fileAssoc: ['assoc:md'] } };
+ const markdownQuery = buildDocumentTypeQuery(['doc-markdown']);
+ if (!markdownQuery) return;
+
const dispose = registerDocumentsFilterSplit(panel.handle.id, {
toggleMarkdownFilter: () => {
if (soup.predicates.isActive('doc-markdown')) {
diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsx
index 16b7484f36..8766a6f03a 100644
--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx
+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx
@@ -444,6 +444,15 @@ if (LOCAL_ONLY) {
}
if (DEV_MODE_ENV) {
+ registerComponent(
+ 'document-where-playground',
+ withAuth(
+ lazy(
+ () => import('@app/component/next-soup/debug/DocumentWherePlayground')
+ )
+ )
+ );
+
// NOTE (seamus) : putting pixel icons on dev/staging for aidan
registerComponent(
'pixel-icon',