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
client/collections/board: add the initial implementation search / filtering support
Adorian Doranc179f808378f
diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex 6e2e0e796a..652dcbebf3 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -47,7 +47,9 @@ export function applyCardMove(* discovery, the config write-back and bulk operations keep reading, so filtering cannot rewrite* the board's columns or reach fewer cards than an operation means to.*/-export function filterColumnMap(byColumn: ColumnMap, matchedNoteIds: Set<string> | null): ColumnMap {+export function filterColumnMap(+ byColumn: ColumnMap, matchedNoteIds: Set<string> | null+): ColumnMap {if (!matchedNoteIds) {return byColumn;}diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex 6d46ae7076..7c89b93edc 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -405,8 +405,7 @@ body.mobile .board-view-container .board-add-column {var(--card-title-inset) - var(--card-icon-inset) - var(--card-icon-size));}-/* The mark.js spans the filter's matched tokens are wrapped in, styled as the search cards- style theirs. */+/* The spans mark.js wraps a filter's matched tokens in. Matches the search result cards. */.board-view-container .board-note > .title .ck-find-result {background: var(--note-list-view-search-result-highlight-background);color: var(--note-list-view-search-result-highlight-color);diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 9f9498bf74..1c6b15d3d5 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -3331,10 +3331,10 @@ describe("Board filtering", () => {"#collection": "","#viewType": "board",children: [- { id: "card1", title: "First", "#status": "To Do" },- { id: "card2", title: "Second", "#status": "To Do" },- { id: "card3", title: "Third", "#status": "To Do" },- { id: "card4", title: "Fourth", "#status": "Done" }+ { id: "filtered1", title: "First", "#status": "To Do" },+ { id: "filtered2", title: "Second", "#status": "To Do" },+ { id: "filtered3", title: "Third", "#status": "To Do" },+ { id: "filtered4", title: "Fourth", "#status": "Done" }]});@@ -3369,11 +3369,8 @@ describe("Board filtering", () => {it("shows only the matched cards, in their own order, keeping every column", async () => {// The matches arrive in score order; the board must keep branch order regardless.- const note = await setup({ matched: [ "card3", "card1" ] });+ const note = await setup({ matched: [ "filtered3", "filtered1" ] });- console.log("CALLS", searchInSubtree.mock.calls.length,- JSON.stringify(searchInSubtree.mock.calls));- console.log("COL0", [ ...container.querySelectorAll(".board-column") ][0]?.innerHTML);expect(searchInSubtree).toHaveBeenCalledWith("#urgent", note.noteId);expect(cardTitles(0)).toEqual([ "First", "Third" ]);expect(cardTitles(1)).toEqual([]);@@ -3381,7 +3378,7 @@ describe("Board filtering", () => {});it("counts the visible cards in the badge while the limit reads the real column", async () => {- await setup({ matched: [ "card1" ], limit: 2 });+ await setup({ matched: [ "filtered1" ], limit: 2 });const column = container.querySelector(".board-column");// One of three cards is shown, and three stand against the limit of two.@@ -3391,7 +3388,7 @@ describe("Board filtering", () => {it("marks the matched tokens in the card titles", async () => {await setup({- matched: [ "card1" ],+ matched: [ "filtered1" ],tokens: [ { token: "First", type: "plain" } ]});diff --git a/apps/client/src/widgets/collections/collection_filter.tsx b/apps/client/src/widgets/collections/collection_filter.tsxindex 16c6ddee89..79e68706c5 100644--- a/apps/client/src/widgets/collections/collection_filter.tsx+++ b/apps/client/src/widgets/collections/collection_filter.tsx@@ -12,7 +12,7 @@ import ActionButton from "../react/ActionButton";import FormTextBox from "../react/FormTextBox";import { useTriliumEvent } from "../react/hooks";-/** How long changes are left to settle before the active filter is re-run over them. */+/** How long to wait after a change before re-running the active filter. */const RERUN_DEBOUNCE_MS = 300;export interface CollectionFilter {@@ -37,10 +37,9 @@ const NO_MATCHES: FilterMatches = { matchedNoteIds: null, highlightedTokens: nul/*** Narrows a collection to the notes matching a search query, using the full search syntax.*- * The query runs server-side, scoped to the collection's subtree, and the result is a membership- * set: the view keeps its own enumeration and order and only leaves out the notes not in the set.- * Search results are a snapshot, so while a filter is active it is re-run (debounced) whenever an- * entity change touches the collection.+ * The result is a membership set, not an order: a view keeps its own enumeration and leaves out+ * the notes the set does not name. A search result is a snapshot, so an active filter re-runs+ * when an entity change touches the collection.*/export function useCollectionFilter(note: FNote, {persistedQuery, onQueryChanged, collectionNoteIds@@ -55,8 +54,8 @@ export function useCollectionFilter(note: FNote, {const [ query, setQuery ] = useState(persistedQuery ?? "");const [ matches, setMatches ] = useState<FilterMatches>(NO_MATCHES);const [ error, setError ] = useState<string | null>(null);- // Runs resolve on the server, so an older one can land after a newer one; only the latest run- // is allowed to set the result.+ // A run resolves on the server, so an older one can land after a newer one. Only the latest+ // run sets the result.const runSeqRef = useRef(0);const rerunTimerRef = useRef<number>();const collectionSet = useMemo(() => new Set(collectionNoteIds), [ collectionNoteIds ]);@@ -111,7 +110,8 @@ export function useCollectionFilter(note: FNote, {}, [ note.noteId, query ]);useTriliumEvent("entitiesReloaded", ({ loadResults }) => {- if (!query.trim() || !touchesCollection(loadResults, collectionSetRef.current, note.noteId)) {+ const collection = collectionSetRef.current;+ if (!query.trim() || !touchesCollection(loadResults, collection, note.noteId)) {return;}window.clearTimeout(rerunTimerRef.current);@@ -133,9 +133,10 @@ export function useCollectionFilter(note: FNote, {}/**- * The filter box a collection header shows: Enter submits what is typed, the button or an emptied- * box clears the filter, and a query error is shown under the box. What is typed but not submitted- * is local to the box, so an unrelated redraw does not apply a half-typed query.+ * The filter box for a collection header. Enter submits what is typed and the button clears it.+ *+ * What is typed is held here until it is submitted, so an unrelated redraw cannot apply a+ * half-typed query.*/export function CollectionFilterInput({ filter }: { filter: CollectionFilter }) {const [ typed, setTyped ] = useState(filter.query);@@ -159,8 +160,8 @@ export function CollectionFilterInput({ filter }: { filter: CollectionFilter })e.preventDefault();filter.setQuery(typed);} else if (e.key === "Escape" && typed !== filter.query) {- // Give up what was typed, keeping the submitted query; a second Escape is- // left for whatever the view does with it.+ // Drops what was typed and keeps the submitted query. A second Escape+ // reaches the view, which handles it as usual.e.stopPropagation();setTyped(filter.query);}diff --git a/packages/trilium-core/src/routes/api/search.ts b/packages/trilium-core/src/routes/api/search.tsindex f41adf0dc6..b8b45f3a96 100644--- a/packages/trilium-core/src/routes/api/search.ts+++ b/packages/trilium-core/src/routes/api/search.ts@@ -1,4 +1,7 @@-import { dayjs, type SearchResultDetails, type SearchResultDetailsRequest, type SearchResultDetailsResponse, type SearchWithTokensResponse, type TemplatesResponse } from "@triliumnext/commons";+import {+ dayjs, type SearchResultDetails, type SearchResultDetailsRequest,+ type SearchResultDetailsResponse, type SearchWithTokensResponse, type TemplatesResponse+} from "@triliumnext/commons";import type { Request } from "express";import becca from "../../becca/becca.js";@@ -146,12 +149,13 @@ function search(includeArchivedNotes: true,fuzzyAttributeSearch: false,ignoreHoistedNote: true,- // Restricts the results to one subtree, for callers that filter a collection rather than- // search the whole tree.- ancestorNoteId: typeof ancestorNoteId === "string" && ancestorNoteId ? ancestorNoteId : undefined+ // Restricts the results to one subtree, for callers that filter a collection rather+ // than search the whole tree.+ ancestorNoteId: ancestorNoteId || undefined});- const noteIds = searchService.findResultsWithQuery(searchString, searchContext).map((sr) => sr.noteId);+ const noteIds = searchService.findResultsWithQuery(searchString, searchContext)+ .map((sr) => sr.noteId);if (includeTokens !== "true") {return noteIds;