Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(demo): added the deep search system for demo mode (#782)

Corentin Thomasset33881f33359e
diff --git a/apps/papra-client/package.json b/apps/papra-client/package.json
index 99398709..dbe51bea 100644
--- a/apps/papra-client/package.json
+++ b/apps/papra-client/package.json
@@ -33,6 +33,7 @@
"@kobalte/core": "^0.13.10",
"@kobalte/utils": "^0.9.1",
"@modular-forms/solid": "^0.25.1",
+ "@papra/search-parser": "workspace:*",
"@pdfslick/solid": "^2.3.0",
"@solid-primitives/storage": "^4.3.2",
"@solidjs/router": "^0.14.10",
diff --git a/apps/papra-client/src/modules/demo/demo-api-mock.ts b/apps/papra-client/src/modules/demo/demo-api-mock.ts
index 386c20d4..043c1b67 100644
--- a/apps/papra-client/src/modules/demo/demo-api-mock.ts
+++ b/apps/papra-client/src/modules/demo/demo-api-mock.ts
@@ -20,6 +20,7 @@ import {
webhooksStorage,
} from './demo.storage';
import { findMany, getValues } from './demo.storage.models';
+import { searchDemoDocuments } from './search/demo.search.services';
import { demoUser } from './seed/users.fixtures';
function assert(condition: unknown, { message = 'Error', status }: { message?: string; status?: number } = {}): asserts condition {
@@ -201,30 +202,31 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
const organization = await organizationStorage.getItem(organizationId);
assert(organization, { status: 403 });
- const documents = await findMany(documentStorage, document => document?.organizationId === organizationId);
+ const searchQuery = rawSearchQuery.trim();
+ const [organizationDocuments, allTags, tagDocuments] = await Promise.all([
+ findMany(documentStorage, document => document?.organizationId === organizationId && !document?.deletedAt),
+ getValues(tagStorage),
+ getValues(tagDocumentStorage),
+ ]);
- const searchQuery = rawSearchQuery.trim().toLowerCase();
+ const documentsWithTags = organizationDocuments.map((document) => {
+ const documentTagDocuments = tagDocuments.filter(tagDocument => tagDocument?.documentId === document?.id);
+ const tags = allTags.filter(tag => documentTagDocuments.some(tagDocument => tagDocument?.tagId === tag?.id));
- const matchQuery = (document: Document) =>
- !document?.deletedAt
- && [document?.name, document?.content].filter(Boolean).some(content => content.toLowerCase().includes(searchQuery));
+ return {
+ ...document,
+ tags,
+ };
+ });
- const filteredDocuments = documents.filter(matchQuery);
- const pagedDocuments = filteredDocuments.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize);
- const documentsWithTags = await Promise.all(
- pagedDocuments.map(async (document) => {
- const tagDocuments = await findMany(tagDocumentStorage, tagDocument => tagDocument?.documentId === document?.id);
- const allTags = await getValues(tagStorage);
- const tags = allTags.filter(tag => tagDocuments.some(tagDocument => tagDocument?.tagId === tag?.id));
- return {
- ...document,
- tags,
- };
- }),
- );
+ const filteredDocuments = searchDemoDocuments({ query: searchQuery, documents: documentsWithTags as Document[] });
+
+ const paginatedDocuments = filteredDocuments
+ .toSorted((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
+ .slice(pageIndex * pageSize, (pageIndex + 1) * pageSize);
return {
- documents: documentsWithTags,
+ documents: paginatedDocuments,
totalCount: filteredDocuments.length,
};
},
diff --git a/apps/papra-client/src/modules/demo/search/demo.search.services.test.ts b/apps/papra-client/src/modules/demo/search/demo.search.services.test.ts
new file mode 100644
index 00000000..5e0809b0
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/search/demo.search.services.test.ts
@@ -0,0 +1,41 @@
+import type { Document } from '@/modules/documents/documents.types';
+import type { Tag } from '@/modules/tags/tags.types';
+import { describe, expect, test } from 'vitest';
+import { searchDemoDocuments } from './demo.search.services';
+
+describe('demo search services', () => {
+ describe('searchDemoDocuments', () => {
+ const tags = {
+ cooking: { id: '1', name: 'cooking' },
+ work: { id: '2', name: 'work' },
+ personal: { id: '3', name: 'personal' },
+ } as unknown as Record<string, Tag>;
+
+ const documents = [
+ { id: 'doc_1', name: 'Recipe for Pancakes', content: 'Mix flour, eggs, and milk to make pancakes.', tags: [tags.cooking], createdAt: new Date('2023-01-01') },
+ { id: 'doc_2', name: 'Work Meeting Notes', content: 'Discuss project timeline and deliverables.', tags: [tags.work], createdAt: new Date('2023-02-15') },
+ { id: 'doc_3', name: 'Personal Journal', content: 'Today I went for a walk in the park.', tags: [tags.personal], createdAt: new Date('2023-03-10') },
+ { id: 'doc_4', name: 'Grocery List', content: 'Eggs, milk, bread, and butter.', tags: [tags.cooking, tags.personal], createdAt: new Date('2023-04-05') },
+ { id: 'doc_5', name: 'Project Plan', content: 'Outline project goals and milestones.', tags: [tags.work], createdAt: new Date('2023-05-20') },
+ { id: 'doc_6', name: 'Vacation Ideas', content: 'Consider visiting the beach or mountains.', tags: [], createdAt: new Date('2023-06-15') },
+ ] as unknown as Document[];
+
+ const queries = [
+ { query: 'pancakes', expectedIds: ['doc_1'] },
+ { query: 'tag:cooking', expectedIds: ['doc_1', 'doc_4'] },
+ { query: 'tag:cooking butter', expectedIds: ['doc_4'] },
+ { query: 'tag:work created:>2023-03-01', expectedIds: ['doc_5'] },
+ { query: '-tag:work', expectedIds: ['doc_1', 'doc_3', 'doc_4', 'doc_6'] },
+ ];
+
+ for (const { query, expectedIds } of queries) {
+ test(`search query "${query}"`, () => {
+ expect(
+ searchDemoDocuments({ query, documents }).map(doc => doc.id),
+ ).toEqual(
+ expectedIds,
+ );
+ });
+ }
+ });
+});
diff --git a/apps/papra-client/src/modules/demo/search/demo.search.services.ts b/apps/papra-client/src/modules/demo/search/demo.search.services.ts
new file mode 100644
index 00000000..69b2caa9
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/search/demo.search.services.ts
@@ -0,0 +1,114 @@
+import type { AndExpression, Expression, FilterExpression, NotExpression, OrExpression, TextExpression } from '@papra/search-parser';
+import type { Document } from '../../documents/documents.types';
+import { parseSearchQuery } from '@papra/search-parser';
+
+type DocumentCondition = (params: { document: Document }) => boolean;
+
+const falseCondition: DocumentCondition = () => false;
+
+function buildTextCondition({ expression }: { expression: TextExpression }): DocumentCondition {
+ const searchText = expression.value.trim().toLowerCase();
+
+ return ({ document }) => [document.name, document.content].join(' ').toLowerCase().includes(searchText);
+}
+
+function buildAndCondition({ expression }: { expression: AndExpression }): DocumentCondition {
+ const conditions = expression.operands.map(operand => buildExpressionCondition({ expression: operand }));
+
+ return ({ document }) => conditions.every(condition => condition({ document }));
+}
+
+function buildOrCondition({ expression }: { expression: OrExpression }): DocumentCondition {
+ const conditions = expression.operands.map(operand => buildExpressionCondition({ expression: operand }));
+
+ return ({ document }) => conditions.some(condition => condition({ document }));
+}
+
+function buildNotCondition({ expression }: { expression: NotExpression }): DocumentCondition {
+ const condition = buildExpressionCondition({ expression: expression.operand });
+
+ return ({ document }) => !condition({ document });
+}
+
+function buildTagFilterCondition({ expression }: { expression: FilterExpression }): DocumentCondition {
+ const { value, operator } = expression;
+
+ if (operator !== '=') {
+ return falseCondition;
+ }
+
+ return ({ document }) => document.tags.find(tag => tag.name === value || tag.id === value) !== undefined;
+}
+
+function buildNameFilterCondition({ expression }: { expression: FilterExpression }): DocumentCondition {
+ const { value, operator } = expression;
+
+ if (operator !== '=') {
+ return falseCondition;
+ }
+
+ return ({ document }) => document.name.toLowerCase().includes(value.toLowerCase());
+}
+
+function buildContentFilterCondition({ expression }: { expression: FilterExpression }): DocumentCondition {
+ const { value, operator } = expression;
+
+ if (operator !== '=') {
+ return falseCondition;
+ }
+
+ return ({ document }) => document.content.toLowerCase().includes(value.toLowerCase());
+}
+
+function buildCreatedFilterCondition({ expression }: { expression: FilterExpression }): DocumentCondition {
+ const { value, operator } = expression;
+ const dateValue = new Date(value);
+
+ if (Number.isNaN(dateValue.getTime())) {
+ return () => false;
+ }
+
+ return ({ document }) => {
+ const documentDate = new Date(document.createdAt);
+
+ switch (operator) {
+ case '=': return documentDate.toDateString() === dateValue.toDateString();
+ case '<': return documentDate < dateValue;
+ case '<=': return documentDate <= dateValue;
+ case '>': return documentDate > dateValue;
+ case '>=': return documentDate >= dateValue;
+ default: return false;
+ }
+ };
+}
+
+function buildExpressionCondition({ expression }: { expression: Expression }): DocumentCondition {
+ switch (expression.type) {
+ case 'text': return buildTextCondition({ expression });
+ case 'and': return buildAndCondition({ expression });
+ case 'or': return buildOrCondition({ expression });
+ case 'not': return buildNotCondition({ expression });
+ case 'filter':
+ switch (expression.field) {
+ case 'tag': return buildTagFilterCondition({ expression });
+ case 'name': return buildNameFilterCondition({ expression });
+ case 'content': return buildContentFilterCondition({ expression });
+ case 'created': return buildCreatedFilterCondition({ expression });
+ default: return () => false;
+ }
+ case 'empty': return () => false;
+ default: return () => false;
+ }
+}
+
+export function searchDemoDocuments({ query, documents }: { query: string; documents: Document[] }) {
+ if (query.trim() === '') {
+ return documents;
+ }
+
+ const { expression } = parseSearchQuery({ query });
+
+ const condition = buildExpressionCondition({ expression });
+
+ return documents.filter(document => condition({ document }));
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c9a8e359..68719057 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -301,6 +301,9 @@ importers:
'@modular-forms/solid':
specifier: ^0.25.1
+ '@papra/search-parser':
+ specifier: workspace:*
+ version: link:../../packages/search-parser
'@pdfslick/solid':
specifier: ^2.3.0
@@ -20025,7 +20028,7 @@ snapshots:
'@typescript-eslint/parser': 8.46.2([email protected]([email protected]))([email protected])
eslint: 9.39.1([email protected])
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
@@ -20054,7 +20057,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3([email protected])
@@ -20079,14 +20082,14 @@ snapshots:
dependencies:
eslint: 9.39.1([email protected])
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 8.46.2([email protected]([email protected]))([email protected])
eslint: 9.39.1([email protected])
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
@@ -20149,7 +20152,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.1([email protected])
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.16.1
is-glob: 4.0.3