Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(share): filter a shared collection through the share
Elian Dorana687524a12c7
diff --git a/apps/client/src/services/froca-interface.ts b/apps/client/src/services/froca-interface.tsindex 58631115cb..edb4c10e0e 100644--- a/apps/client/src/services/froca-interface.ts+++ b/apps/client/src/services/froca-interface.ts@@ -1,4 +1,6 @@-import type { NoteMapPostResponse, RelationMapPostResponse } from "@triliumnext/commons";+import type {+ NoteMapPostResponse, RelationMapPostResponse, SearchLintResponse, SearchWithTokensResponse+} from "@triliumnext/commons";import type FAttachment from "../entities/fattachment.js";import type { FAttachmentRow } from "../entities/fattachment.js";@@ -47,6 +49,10 @@ export interface FrocaSource {getBlob(entityType: string, entityId: string): Promise<FBlobRow>;/** The ids of the notes below `ancestorNoteId` that match the search `query`. */searchNoteIds(query: string, ancestorNoteId: string): Promise<string[]>;+ /** The notes below `ancestorNoteId` that match `query`, with the tokens to highlight and its error. */+ searchInSubtree(query: string, ancestorNoteId: string): Promise<SearchWithTokensResponse>;+ /** What is wrong with the search string, read without running it. */+ lintSearch(searchString: string): Promise<SearchLintResponse>;/** The notes and the links of the note map of `mapRootNoteId`, as a tree or as its relations. */getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters): Promise<NoteMapPostResponse>;/** The relations the relation map note `relationMapNoteId` draws between the notes `noteIds`. */@@ -76,6 +82,8 @@ export interface Froca {getAttachmentsForNote(noteId: string): Promise<FAttachment[]>;searchNoteIds(query: string, ancestorNoteId: string): Promise<string[]>;+ searchInSubtree(query: string, ancestorNoteId: string): Promise<SearchWithTokensResponse>;+ lintSearch(searchString: string): Promise<SearchLintResponse>;getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters): Promise<NoteMapPostResponse>;getRelationMap(relationMapNoteId: string, noteIds: string[]): Promise<RelationMapPostResponse>;getScriptBundle(noteId: string): Promise<Bundle | undefined>;diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.tsindex 1b9ab69060..0303e1b122 100644--- a/apps/client/src/services/froca.ts+++ b/apps/client/src/services/froca.ts@@ -1,4 +1,7 @@-import type { HighlightedTokenInfo, NoteMapPostResponse, RelationMapPostResponse } from "@triliumnext/commons";+import type {+ HighlightedTokenInfo, NoteMapPostResponse, RelationMapPostResponse, SearchLintResponse,+ SearchWithTokensResponse+} from "@triliumnext/commons";import FAttachment, { type FAttachmentRow } from "../entities/fattachment.js";import FAttribute, { type FAttributeRow } from "../entities/fattribute.js";@@ -404,6 +407,14 @@ class FrocaImpl implements Froca {return this.source.searchNoteIds(query, ancestorNoteId);}+ searchInSubtree(query: string, ancestorNoteId: string) {+ return this.source.searchInSubtree(query, ancestorNoteId);+ }++ lintSearch(searchString: string) {+ return this.source.lintSearch(searchString);+ }+getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters) {return this.source.getNoteMap(mapRootNoteId, mapType, filters);}@@ -461,6 +472,10 @@ const SERVER_SOURCE: FrocaSource = {const { default: search } = await import("./search.js");return await search.searchForNoteIds(query);},+ searchInSubtree: (query, ancestorNoteId) => server.get<SearchWithTokensResponse>(+ `search?searchString=${encodeURIComponent(query)}`+ + `&ancestorNoteId=${encodeURIComponent(ancestorNoteId)}&includeTokens=true`),+ lintSearch: (searchString) => server.post<SearchLintResponse>("search/lint", { searchString }),getNoteMap: (mapRootNoteId, mapType, filters) =>server.post<NoteMapPostResponse>(`note-map/${mapRootNoteId}/${mapType}`, filters),getRelationMap: (relationMapNoteId, noteIds) =>diff --git a/apps/client/src/services/search.ts b/apps/client/src/services/search.tsindex 4c9190f54b..4c010b708e 100644--- a/apps/client/src/services/search.ts+++ b/apps/client/src/services/search.ts@@ -1,5 +1,3 @@-import type { SearchWithTokensResponse } from "@triliumnext/commons";-import type Component from "../components/component.js";import froca from "./froca.js";import server from "./server.js";@@ -21,9 +19,7 @@ async function searchForNotes(searchString: string) {* tokens to highlight and any parse error, for filtering a collection down to the matches.*/async function searchInSubtree(searchString: string, ancestorNoteId: string) {- return await server.get<SearchWithTokensResponse>(- `search?searchString=${encodeURIComponent(searchString)}`- + `&ancestorNoteId=${encodeURIComponent(ancestorNoteId)}&includeTokens=true`);+ return await froca.searchInSubtree(searchString, ancestorNoteId);}/**diff --git a/apps/client/src/widgets/search_field_editor.tsx b/apps/client/src/widgets/search_field_editor.tsxindex 1bce9ce575..680ecc7597 100644--- a/apps/client/src/widgets/search_field_editor.tsx+++ b/apps/client/src/widgets/search_field_editor.tsx@@ -5,11 +5,9 @@ import { type NoteChip, triliumNoteChips } from "@triliumnext/codemirror/src/extimport { triliumSearchHighlighter } from "@triliumnext/codemirror/src/extensions/trilium_search_highlighter";import { type SearchLintMessages, triliumSearchLinter } from "@triliumnext/codemirror/src/extensions/trilium_search_lint";import { createFieldEditor, type FieldEditor, type FieldEditorConfig } from "@triliumnext/codemirror/src/field_editor";-import type { SearchLintResponse } from "@triliumnext/commons";import froca from "../services/froca";import { t } from "../services/i18n";-import server from "../services/server";import { AttributeNameSuggestion, fetchAttributeNames } from "./attribute_widgets/attribute_detail";import { AutocompleteList } from "./react/FormAutocomplete";import { CommandMentionList, createHostedList, filterCommandEntries, NoteMentionList } from "./react/NoteAutocomplete";@@ -139,7 +137,7 @@ export function resolveNoteChip(noteId: string): NoteChip | Promise<NoteChip | n* no request.*/async function validateOnServer(searchString: string) {- const { error } = await server.post<SearchLintResponse>("search/lint", { searchString });+ const { error } = await froca.lintSearch(searchString);return error;}diff --git a/packages/share-theme/src/content/share_froca_source.ts b/packages/share-theme/src/content/share_froca_source.tsindex 5feb1a6ad9..3809df8edb 100644--- a/packages/share-theme/src/content/share_froca_source.ts+++ b/packages/share-theme/src/content/share_froca_source.ts@@ -30,6 +30,11 @@ export function createShareFrocaSource(links: Record<string, string>): FrocaSour// A visitor cannot change notes, so what a view saves holds only while the page is open.saveAttachment: async () => {},removeAttachment: async () => {},+ searchInSubtree: (query, ancestorNoteId) => {+ const params = new URLSearchParams({ searchString: query, ancestorNoteId });+ return getJson(`api/search?${params}`);+ },+ lintSearch: (searchString) => getJson(`api/search/lint?${new URLSearchParams({ searchString })}`),getNoteMap: (mapRootNoteId, mapType, { excludeRelations, includeRelations }) => {const params = new URLSearchParams([...excludeRelations.map((name) => [ "excludeRelation", name ]),diff --git a/packages/trilium-core/src/share/handlers.spec.ts b/packages/trilium-core/src/share/handlers.spec.tsindex 221876bd5e..9484074a6b 100644--- a/packages/trilium-core/src/share/handlers.spec.ts+++ b/packages/trilium-core/src/share/handlers.spec.ts@@ -479,6 +479,51 @@ describe("share handlers", () => {expect(search({ search: " " }).status).toBe(400);expect(search({ search: [ "a", "b" ] }).status).toBe(400);});++ it("filters a shared collection to the matches the caller can see, with the tokens to highlight", () => {+ buildShareTree([ {+ id: "board",+ title: "Board",+ content: "",+ children: [+ { id: "seen", title: "Seen", content: "" },+ { "id": "guarded", "title": "Guarded", "content": "", "#shareCredentials": "root:hunter2" },+ { id: "secret", title: "Secret", content: "", isProtected: true }+ ]+ } ]);+ vi.spyOn(searchService, "findResultsWithQuery").mockImplementation((_query, context) => {+ context.highlightedTokens.push("seen");+ return [ "seen", "guarded", "secret", "unshared" ]+ .map((noteId) => new SearchResult([ "root", "_share", "board", noteId ]));+ });+ const filter = (query: ShareRequest["query"], authorization?: string) => request(+ "/share/api/search", { query, headers: authorization ? { authorization } : {} });++ const reply = filter({ searchString: "seen", ancestorNoteId: "board" });+ expect(reply.status).toBe(200);+ expect(JSON.parse(String(reply.body))).toMatchObject({+ searchResultNoteIds: [ "seen" ],+ highlightedTokens: [ expect.objectContaining({ token: "seen" }) ],+ error: null+ });+ const authorized = filter({ searchString: "seen", ancestorNoteId: "board" },+ `Basic ${encodeBase64("root:hunter2")}`);+ expect(JSON.parse(String(authorized.body)).searchResultNoteIds).toEqual([ "seen", "guarded" ]);++ expect(filter({ ancestorNoteId: "board" }).status).toBe(400);+ expect(filter({ searchString: "seen" }).status).toBe(400);+ expect(filter({ searchString: "seen", ancestorNoteId: "missing" }).status).toBe(404);+ });++ it("reads a search string without running it, answering its error", () => {+ const lint = (query: ShareRequest["query"]) => request("/share/api/search/lint", { query });+ vi.spyOn(searchService, "validateSearchQuery").mockImplementation((query) =>+ (query === "#" ? "Misplaced or incomplete expression" : null));++ expect(JSON.parse(String(lint({ searchString: "#" }).body))).toEqual({ error: "Misplaced or incomplete expression" });+ expect(JSON.parse(String(lint({ searchString: "title" }).body))).toEqual({ error: null });+ expect(lint({}).status).toBe(400);+ });});function stubAttachmentContent(attachmentId: string, content: string | Uint8Array | undefined) {diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.tsindex 4f8a752ab5..080cd94b6f 100644--- a/packages/trilium-core/src/share/handlers.ts+++ b/packages/trilium-core/src/share/handlers.ts@@ -95,6 +95,8 @@ const HANDLERS: Record<ShareRoutePath, (req: ShareRequest) => ShareReply> = {"/share/api/attachments/:attachmentId/all": getSiblingAttachments,"/share/api/attachments/:attachmentId/blob": getAttachmentBlob,"/share/api/tree": loadTree,+ "/share/api/search/lint": lintSearch,+ "/share/api/search": searchInSubtree,"/share/api/note-map/:noteId/:mapType": getNoteMap,"/share/api/relation-map/:noteId": getRelationMap,"/share/api/script/bundle/:noteId": getScriptBundle,@@ -377,6 +379,48 @@ function downloadAttachment(req: ShareRequest): ShareReply {}/** Used for searching; requires a noteId so the subtree root is known. */+/**+ * Runs a search below a shared note the way the app filters a collection, answering the matches a+ * visitor can read with the tokens to highlight and the query's error.+ */+function searchInSubtree(req: ShareRequest): ShareReply {+ const { searchString, ancestorNoteId } = req.query;+ if (typeof searchString !== "string" || !searchString || typeof ancestorNoteId !== "string") {+ return jsonReply(400, { message: "'searchString' and 'ancestorNoteId' parameters are mandatory." });+ }+ checkNoteAccess(ancestorNoteId, req);++ const searchContext = new SearchContext({+ fastSearch: false,+ includeArchivedNotes: true,+ fuzzyAttributeSearch: false,+ ignoreHoistedNote: true,+ ancestorNoteId+ });+ const noteIds = searchService.findResultsWithQuery(searchString, searchContext)+ .filter((result) => {+ const note = shaca.notes[result.noteId];+ return note && !note.isProtected && hasCredentialAccess(note, req)+ && isVisibleInShareTree(ancestorNoteId, result.notePathArray);+ })+ .map((result) => result.noteId);++ return jsonReply(200, {+ searchResultNoteIds: noteIds,+ highlightedTokens: searchContext.getHighlightedTokenInfos(),+ error: searchContext.getError()+ });+}++/** Reads a search string without running it, for the search editor's own checks. */+function lintSearch(req: ShareRequest): ShareReply {+ const { searchString } = req.query;+ if (typeof searchString !== "string") {+ return jsonReply(400, { message: "'searchString' parameter is mandatory." });+ }+ return jsonReply(200, { error: searchService.validateSearchQuery(searchString) });+}+function searchNotes(req: ShareRequest): ShareReply {const ancestorNoteId = req.query.ancestorNoteId ?? "_share";diff --git a/packages/trilium-core/src/share/route_paths.ts b/packages/trilium-core/src/share/route_paths.tsindex be27d4ec28..8ca1b4c9ef 100644--- a/packages/trilium-core/src/share/route_paths.ts+++ b/packages/trilium-core/src/share/route_paths.ts@@ -20,6 +20,8 @@ export const SHARE_ROUTE_PATHS = ["/share/api/attachments/:attachmentId/all","/share/api/attachments/:attachmentId/blob","/share/api/tree",+ "/share/api/search/lint",+ "/share/api/search","/share/api/note-map/:noteId/:mapType","/share/api/relation-map/:noteId","/share/api/script/bundle/:noteId",