Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: add the initial implementation search / filtering support

Adorian Doranefaa4898079f
diff --git a/apps/client/src/services/search.spec.ts b/apps/client/src/services/search.spec.ts
index 214c10978e..5031154f75 100644
--- a/apps/client/src/services/search.spec.ts
+++ b/apps/client/src/services/search.spec.ts
@@ -32,6 +32,18 @@ describe("search service", () => {
expect(notes.map((n) => n.noteId)).toEqual([noteA.noteId, noteB.noteId]);
});
+ it("searchInSubtree scopes the query to the ancestor and asks for tokens", async () => {
+ const response = { searchResultNoteIds: ["id1"], highlightedTokens: [], error: null };
+ const get = vi.fn(async () => response);
+ server.get = get as typeof server.get;
+
+ const result = await searchService.searchInSubtree("#done & task", "board1");
+
+ expect(get).toHaveBeenCalledWith(
+ `search/${encodeURIComponent("#done & task")}?ancestorNoteId=board1&includeTokens=true`);
+ expect(result).toBe(response);
+ });
+
it("searchForNotes returns an empty array when no ids match", async () => {
server.get = vi.fn(async () => []) as typeof server.get;
diff --git a/apps/client/src/services/search.ts b/apps/client/src/services/search.ts
index bc516ecb47..b4cbf1c0e4 100644
--- a/apps/client/src/services/search.ts
+++ b/apps/client/src/services/search.ts
@@ -1,3 +1,5 @@
+import type { SearchWithTokensResponse } from "@triliumnext/commons";
+
import server from "./server.js";
import froca from "./froca.js";
@@ -11,7 +13,18 @@ async function searchForNotes(searchString: string) {
return await froca.getNotes(noteIds);
}
+/**
+ * Runs a search restricted to one subtree and returns the matching note ids together with the
+ * 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/${encodeURIComponent(searchString)}`
+ + `?ancestorNoteId=${encodeURIComponent(ancestorNoteId)}&includeTokens=true`);
+}
+
export default {
searchForNoteIds,
- searchForNotes
+ searchForNotes,
+ searchInSubtree
};
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 0e4bce7c62..b56b5d6bd0 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4192,5 +4192,11 @@
"invalid-symbol": "the markdown symbol should be one character, excepting \"[\", \" \", \"X\", and \"]\"",
"duplicate-symbol": "duplicate markdown symbol"
}
+ },
+ "collection_filter": {
+ "placeholder": "Filter...",
+ "tooltip": "Narrows the collection to the notes matching a search query. Press Enter to apply; clear the box to show everything again.",
+ "clear": "Clear the filter",
+ "fetch-error": "The filter could not be run."
}
}
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index 375ba3c882..2f80cf6d31 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -68,7 +68,8 @@ function createApi(
columns: string[],
parentNote?: FNote,
statusAttribute = "status",
- byColumn: ColumnMap = new Map()
+ byColumn: ColumnMap = new Map(),
+ allByColumn?: ColumnMap
) {
const board = parentNote ?? buildNote({ title: "Board" });
const saved: BoardViewData[] = [];
@@ -84,11 +85,62 @@ function createApi(
(newConfig) => saved.push(newConfig),
(branchId) => editing.push(branchId),
pending,
- getStatusDefinition(board, statusAttribute)
+ getStatusDefinition(board, statusAttribute),
+ allByColumn
);
return { api, board, saved, editing, pendingRenames: pending.renames };
}
+describe("BoardApi filtering", () => {
+ /** Cards named by their note id, which is all the operations under test read them for. */
+ function cards(columns: Record<string, string[]>): ColumnMap {
+ return new Map(Object.entries(columns).map(([ column, ids ]) => [
+ column,
+ ids.map((noteId) => ({ note: { noteId }, branch: { branchId: `b_${noteId}` } }))
+ ])) as unknown as ColumnMap;
+ }
+
+ it("stores a submitted filter query and clears it for an empty one", () => {
+ const { api, saved } = createApi({ filterQuery: undefined }, []);
+
+ api.setFilterQuery("#done");
+ expect(saved.at(-1)?.filterQuery).toBe("#done");
+
+ api.setFilterQuery("#done");
+ expect(saved).toHaveLength(1);
+
+ api.setFilterQuery("");
+ expect(saved).toHaveLength(2);
+ expect(saved.at(-1)?.filterQuery).toBeUndefined();
+ });
+
+ it("does not save for a cleared filter that was never set", () => {
+ const { api, saved } = createApi({}, []);
+
+ api.setFilterQuery("");
+ expect(saved).toHaveLength(0);
+ });
+
+ it("removes a column's value from the cards the filter is not showing too", async () => {
+ const { api } = createApi(
+ { columns: [ { value: "To Do" } ] },
+ [ "To Do" ],
+ undefined,
+ "status",
+ cards({ "To Do": [ "visible" ] }),
+ cards({ "To Do": [ "visible", "hidden" ] })
+ );
+
+ await api.removeColumn("To Do");
+
+ expect(executeBulkActions).toHaveBeenCalledWith(
+ [ "visible", "hidden" ],
+ [ { name: "deleteLabel", labelName: "status" } ],
+ { silent: true }
+ );
+ });
+});
+
describe("BoardApi column mutations", () => {
/**
* #10689: the view re-renders off the identity of the config object it is handed
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index aad3fe4428..8f01449bdf 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -118,7 +118,12 @@ export default class BoardApi {
private setBranchIdToEdit: (branchId: string | undefined) => void,
private pending: PendingColumnWrites =
{ renames: new Map(), claims: new Map(), inFlight: 0 },
- private statusDefinition?: BoardStatusDefinition
+ private statusDefinition?: BoardStatusDefinition,
+ /**
+ * Every card, when `byColumn` is narrowed by a filter. Bulk operations read this one, so a
+ * column operation reaches the cards the filter leaves out too.
+ */
+ private allByColumn?: ColumnMap
) {
this.viewConfigSource = viewConfig;
this.viewConfig = viewConfig ?? {};
@@ -144,7 +149,8 @@ export default class BoardApi {
viewConfig: BoardViewData | undefined,
saveConfig: (newConfig: BoardViewData) => void,
setBranchIdToEdit: (branchId: string | undefined) => void,
- statusDefinition?: BoardStatusDefinition
+ statusDefinition?: BoardStatusDefinition,
+ allByColumn?: ColumnMap
) {
// What was sent to the end of a column stands in for what the map does not show yet, so it
// is given up with the map it stands in for. Kept across a refresh, it would name a branch
@@ -154,6 +160,7 @@ export default class BoardApi {
}
this.byColumn = byColumn;
+ this.allByColumn = allByColumn;
this.columns = columns;
this.parentNote = parentNote;
// Only a config the board has actually replaced, since `storeColumns` moves this one ahead
@@ -448,8 +455,10 @@ export default class BoardApi {
}
async removeColumn(column: string) {
- // Remove the value from the notes.
- const noteIds = this.byColumn?.get(column)?.map(item => item.note.noteId) || [];
+ // Remove the value from the notes. Read off the unfiltered map where there is one, so the
+ // value also comes off the cards an active filter is not showing.
+ const items = (this.allByColumn ?? this.byColumn)?.get(column);
+ const noteIds = items?.map(item => item.note.noteId) || [];
const action: BulkAction = this.isRelationMode
? { name: "deleteRelation", relationName: this.statusAttribute }
@@ -676,6 +685,15 @@ export default class BoardApi {
this.storeConfig({ templates });
}
+ /** Stores the query the board is narrowed to, or clears it when given an empty one. */
+ setFilterQuery(query: string) {
+ if ((query || undefined) === this.viewConfig?.filterQuery) {
+ return;
+ }
+
+ this.storeConfig({ filterQuery: query || undefined });
+ }
+
/** Remembers what the last card was made from, so the next one is made from it too. */
async setLastCardTemplateId(template: string) {
if (template === this.viewConfig?.template) {
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index cb481aee2c..cf120c8142 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -5,7 +5,9 @@ import {
import FBranch from "../../../entities/fbranch";
import FNote from "../../../entities/fnote";
import BoardApi from "./api";
-import { BoardActionsContext, BoardPromotedAttributesContext, TitleEditor } from ".";
+import {
+ BoardActionsContext, BoardHighlightTokensContext, BoardPromotedAttributesContext, TitleEditor
+} from ".";
import { ContextMenuEvent } from "../../../menus/context_menu";
import { openNoteContextMenu } from "./context_menu";
import { t } from "../../../services/i18n";
@@ -15,6 +17,7 @@ import { FLIP_SETTLE_MS } from "../../react/flip";
import {
useNoteColorClass, useNoteIcon, useNoteLabel, useNoteLabelBoolean, useTriliumEvent
} from "../../react/hooks";
+import { HighlightedText } from "../../react/RawHtml";
function Card({
api,
@@ -60,6 +63,7 @@ function Card({
}) {
const { setBranchIdToEdit } = useContext(BoardActionsContext);
const shownAttributes = useContext(BoardPromotedAttributesContext);
+ const highlightedTokens = useContext(BoardHighlightTokensContext);
// Tracks the `color` label, which the board does not redraw a card for.
const colorClass = useNoteColorClass(note) || "";
const editorRef = useRef<HTMLInputElement>(null);
@@ -192,7 +196,7 @@ function Card({
<>
<span className="title">
<span class={`icon ${icon}`} />
- {title}
+ <HighlightedText text={title} highlightedTokens={highlightedTokens} />
</span>
<span
className="edit-icon icon bx bx-edit"
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index a2d03ac0b0..ba3738820c 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -61,6 +61,7 @@ export default function Column({
nested,
limit,
columnItems,
+ totalCount,
isNew,
cardTemplates,
api,
@@ -88,6 +89,11 @@ export default function Column({
nested?: boolean,
/** The note limit, absent if disabled. */
limit?: number,
+ /**
+ * How many cards the column really holds, when an active filter leaves `columnItems` with
+ * fewer. The badge counts what is shown; the limit is about the real column.
+ */
+ totalCount?: number,
api: BoardApi,
parentNote: FNote,
isInRelationMode: boolean,
@@ -160,7 +166,7 @@ export default function Column({
: undefined;
// Read here rather than in the badge: the column body shows an outline as well.
- const isOverLimit = limit !== undefined && (columnItems?.length ?? 0) > limit;
+ const isOverLimit = limit !== undefined && (totalCount ?? columnItems?.length ?? 0) > limit;
const isCollapsed = !!collapsed && !isActive && !isPeeked;
// A column opened to take a dragged card takes its width at once, and its cards with it.
const opensAtOnce = !!draggedCard || dropTarget === column;
diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.ts
index 659165e66e..6d2fa1dd87 100644
--- a/apps/client/src/widgets/collections/board/data.spec.ts
+++ b/apps/client/src/widgets/collections/board/data.spec.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import FBranch from "../../../entities/fbranch";
import froca from "../../../services/froca";
import { buildNote } from "../../../test/easy-froca";
-import { applyCardMove, type ColumnMap, getBoardData } from "./data";
+import { applyCardMove, type ColumnMap, filterColumnMap, getBoardData } from "./data";
describe("applyCardMove", () => {
/** Cards named by their note id, which is all this reads them for. */
@@ -58,6 +58,31 @@ describe("applyCardMove", () => {
expect(applyCardMove(start, "nope", "A", "B", 0)).toBe(start);
});
+
+ describe("filterColumnMap", () => {
+ it("keeps only the matched cards, in the order the column holds them", () => {
+ // The set is built in reversed order to prove it carries membership, not order.
+ const matched = new Set([ "a4", "a2", "a1" ]);
+ const filtered = filterColumnMap(
+ board({ A: [ "a1", "a2", "a3", "a4" ], B: [ "b1" ] }), matched);
+
+ expect(names(filtered, "A")).toEqual([ "a1", "a2", "a4" ]);
+ expect(names(filtered, "B")).toEqual([]);
+ });
+
+ it("keeps every column, emptied ones included", () => {
+ const filtered = filterColumnMap(board({ A: [ "a1" ], B: [] }), new Set([ "nothing" ]));
+
+ expect([ ...filtered.keys() ]).toEqual([ "A", "B" ]);
+ expect(names(filtered, "A")).toEqual([]);
+ });
+
+ it("hands the map back untouched while no filter is active", () => {
+ const start = board({ A: [ "a1" ] });
+
+ expect(filterColumnMap(start, null)).toBe(start);
+ });
+ });
});
describe("Board data", () => {
diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.ts
index 633305324a..6e2e0e796a 100644
--- a/apps/client/src/widgets/collections/board/data.ts
+++ b/apps/client/src/widgets/collections/board/data.ts
@@ -40,6 +40,25 @@ export function applyCardMove(
return next;
}
+/**
+ * The columns with only the cards in `matchedNoteIds`, keeping their order relative to each other.
+ *
+ * A filter narrows what is drawn, nothing else: every column stays, and the full map is what column
+ * 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 {
+ if (!matchedNoteIds) {
+ return byColumn;
+ }
+
+ const filtered: ColumnMap = new Map();
+ for (const [ column, items ] of byColumn) {
+ filtered.set(column, items.filter(item => matchedNoteIds.has(item.note.noteId)));
+ }
+ return filtered;
+}
+
/**
* @param definitionOptions the choices the board's group-by definition offers, empty when it has no
* select definition of its own to lead the column order.
diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.css
index 470f84d5af..6d46ae7076 100644
--- a/apps/client/src/widgets/collections/board/index.css
+++ b/apps/client/src/widgets/collections/board/index.css
@@ -405,6 +405,15 @@ 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. */
+.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);
+ font-weight: 600;
+ text-decoration: underline;
+}
+
.board-view-container .board-note > .edit-icon {
position: absolute;
top: 8px;
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index 0c6a14798a..9f9498bf74 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -20,6 +20,7 @@ import froca from "../../../services/froca";
import attributes from "../../../services/attributes";
import { executeBulkActions } from "../../../services/bulk_action";
import LoadResults from "../../../services/load_results";
+import searchService from "../../../services/search";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
import BoardView, { BoardViewData } from ".";
@@ -107,6 +108,16 @@ vi.mock("../../../services/bulk_action", () => ({
})
}));
+vi.mock("../../../services/search", () => ({
+ default: {
+ searchInSubtree: vi.fn(),
+ searchForNoteIds: vi.fn(async () => []),
+ searchForNotes: vi.fn(async () => [])
+ }
+}));
+
+const searchInSubtree = vi.mocked(searchService.searchInSubtree);
+
/** What a card is made from until another template is picked: the first the board offers. */
function textTemplate() {
return expect.objectContaining({ id: "type:text:text/html" });
@@ -3292,3 +3303,99 @@ describe("the promoted attributes a card shows", () => {
.map(element => element.textContent);
}
});
+
+describe("Board filtering", () => {
+ let container: HTMLElement;
+
+ afterEach(() => {
+ saved.length = 0;
+ render(null, container);
+ container.remove();
+ });
+
+ /** A board of four cards over two columns, opened with a stored filter query. */
+ async function setup({ matched, tokens = [], limit }: {
+ matched: string[];
+ tokens?: { token: string; type: "plain" }[];
+ limit?: number;
+ }) {
+ searchInSubtree.mockReset();
+ searchInSubtree.mockResolvedValue({
+ searchResultNoteIds: matched,
+ highlightedTokens: tokens,
+ error: null
+ });
+
+ const note = buildNote({
+ title: "Board",
+ "#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" }
+ ]
+ });
+
+ container = document.body.appendChild(document.createElement("div"));
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={new Component()}>
+ <Harness
+ note={note}
+ noteIds={[ ...note.getChildNoteIds() ]}
+ initialConfig={{
+ columns: [ { value: "To Do", ...(limit ? { limit } : {}) },
+ { value: "Done" } ],
+ filterQuery: "#urgent"
+ }}
+ />
+ </ParentComponent.Provider>,
+ container
+ );
+ });
+ await act(async () => { await flush(); });
+ await act(async () => { await flush(); });
+
+ return note;
+ }
+
+ function cardTitles(column: number) {
+ const columns = [ ...container.querySelectorAll(".board-column") ];
+ return [ ...columns[column].querySelectorAll(".board-note .title") ]
+ .map(el => el.textContent);
+ }
+
+ 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" ] });
+
+ 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([]);
+ expect(container.querySelectorAll(".board-column")).toHaveLength(2);
+ });
+
+ it("counts the visible cards in the badge while the limit reads the real column", async () => {
+ await setup({ matched: [ "card1" ], limit: 2 });
+
+ const column = container.querySelector(".board-column");
+ // One of three cards is shown, and three stand against the limit of two.
+ expect(column?.querySelector(".counter-badge")?.textContent).toBe("1/2");
+ expect(column?.classList.contains("over-limit")).toBe(true);
+ });
+
+ it("marks the matched tokens in the card titles", async () => {
+ await setup({
+ matched: [ "card1" ],
+ tokens: [ { token: "First", type: "plain" } ]
+ });
+
+ const marks = [ ...container.querySelectorAll(".board-note .title .ck-find-result") ];
+ expect(marks.map(el => el.textContent)).toEqual([ "First" ]);
+ });
+});
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 56a68ada08..feb470755b 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -9,6 +9,8 @@ import {
Dispatch, StateUpdater, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState
} from "preact/hooks";
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
+
import FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
import type LoadResults from "../../../services/load_results";
@@ -34,6 +36,7 @@ import ActionButton from "../../react/ActionButton";
import { IconPickerButton } from "../../react/IconPicker";
import { useDragPan } from "../../react/drag_pan";
import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";
+import { CollectionFilterInput, useCollectionFilter } from "../collection_filter";
import { ViewModeProps } from "../interface";
import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api";
import { useBoardDrag } from "./board_drag";
@@ -45,7 +48,7 @@ import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";
import ColumnLimitDialog from "./column_limit";
import BoardProperties from "./properties";
import { openBoardContextMenu, openCreateColumnMenu } from "./context_menu";
-import { applyCardMove, ColumnMap, getBoardData } from "./data";
+import { applyCardMove, ColumnMap, filterColumnMap, getBoardData } from "./data";
import { useBoardKeyboard } from "./keyboard";
/**
@@ -73,6 +76,8 @@ export interface BoardViewData {
* name is shown after the ones it does; see {@link resolvePromotedAttributes}.
*/
promotedAttributes?: PromotedAttributeSetting[];
+ /** The search query the board is narrowed to, absent while no filter is active. */
+ filterQuery?: string;
}
export interface BoardColumnData {
@@ -193,6 +198,13 @@ export const BoardDragStateContext = createContext<BoardDragState>({
dropTarget: null
});
+/**
+ * The tokens the active filter matched by, which the cards highlight in their titles. Null while
+ * no filter is active. A context for the same reason the promoted attributes use one: a card is
+ * memoized, and the tokens change only when a query is submitted.
+ */
+export const BoardHighlightTokensContext = createContext<HighlightedTokenInfo[] | null>(null);
+
/**
* What the board answers with when asked for contextual keyboard help. Every entry is a key the
* board handles itself (see `keyboard.ts` and the card and column handlers), none of them
@@ -256,6 +268,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
const [ includeArchived ] = useNoteLabelBoolean(parentNote, "includeArchived");
const [ inboxEnabled ] = useNoteLabelBoolean(parentNote, "enableInboxColumn");
const [ byColumn, setByColumn ] = useState<ColumnMap>();
+ /** Every card, while `byColumn` holds only what the active filter matches. */
+ const [ allByColumn, setAllByColumn ] = useState<ColumnMap>();
const [ columns, setColumns ] = useState<string[]>();
const [ isInRelationMode, setIsRelationMode ] = useState(false);
const [ draggedCard, setDraggedCard ] = useState<CardDrag | null>(null);
@@ -333,14 +347,26 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
board: boardIdentity,
api: new Api(
byColumn, usableColumns, parentNote, statusAttributeWithPrefix, viewConfig,
- saveConfig, setBranchIdToEdit, pendingRenamesRef.current.writes, statusDefinition)
+ saveConfig, setBranchIdToEdit, pendingRenamesRef.current.writes, statusDefinition,
+ allByColumn)
};
} else {
apiRef.current.api.update(
byColumn, usableColumns, parentNote, statusAttributeWithPrefix, viewConfig,
- saveConfig, setBranchIdToEdit, statusDefinition);
+ saveConfig, setBranchIdToEdit, statusDefinition, allByColumn);
}
const api = apiRef.current.api;
+
+ const persistFilterQuery = useCallback(
+ (query: string) => apiRef.current?.api.setFilterQuery(query), []);
+ const filter = useCollectionFilter(parentNote, {
+ persistedQuery: viewConfig?.filterQuery,
+ onQueryChanged: persistFilterQuery,
+ collectionNoteIds: noteIds
+ });
+ // Read through a ref by `refresh`, whose result can land after the filter has moved on.
+ const matchedNoteIdsRef = useRef(filter.matchedNoteIds);
+ matchedNoteIdsRef.current = filter.matchedNoteIds;
// Every member is one of useState's own setters, so this value is built once and never changes
// identity -- a drag cannot reach anything that reads only this.
const openBoardMenu = useCallback((event: ContextMenuEvent) => {
@@ -470,7 +496,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
settleColumn(pendingRenamesRef.current.writes, settled);
}
- setByColumn(byColumn);
+ setAllByColumn(byColumn);
+ setByColumn(filterColumnMap(byColumn, matchedNoteIdsRef.current));
setIsRelationMode(isInRelationMode);
setColumns(columns);
@@ -657,6 +684,15 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
parentNote, noteIds, viewConfig, statusAttributeWithPrefix, statusDefinition, inboxEnabled
]);
+ // Redraws for a change in what the filter matches; a change in the cards themselves goes
+ // through `refresh`. Skipped while a move is being written, exactly as a refresh would be:
+ // the board has already been drawn as the move will leave it, and the maps are older.
+ useEffect(() => {
+ if (allByColumn && !movesInFlight.current) {
+ setByColumn(filterColumnMap(allByColumn, filter.matchedNoteIds));
+ }
+ }, [ filter.matchedNoteIds ]);
+
// The drag reports where the column landed among the ones on screen, which is not where it
// landed among them all once some are archived and hidden. Translated here so a reorder leaves
// every hidden column where it was rather than herding them to the end.
@@ -710,9 +746,13 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
return (
<div className="board-view">
- <CollectionProperties note={parentNote} />
+ <CollectionProperties
+ note={parentNote}
+ centerChildren={<CollectionFilterInput filter={filter} />}
+ />
<BoardActionsContext.Provider value={boardActions}>
<BoardPromotedAttributesContext.Provider value={shownAttributes}>
+ <BoardHighlightTokensContext.Provider value={filter.highlightedTokens}>
<BoardDragStateContext.Provider value={boardDragState}>
{byColumn && columns && <div
ref={containerRef}
@@ -764,6 +804,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
onFocusColumn={focusColumn}
onFocusCard={focusCard}
columnItems={byColumn.get(column)}
+ totalCount={allByColumn?.get(column)?.length}
isNew={column === createdColumn}
/>
</Fragment>
@@ -811,6 +852,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
)}
</div>}
</BoardDragStateContext.Provider>
+ </BoardHighlightTokensContext.Provider>
</BoardPromotedAttributesContext.Provider>
</BoardActionsContext.Provider>
</div>
diff --git a/apps/client/src/widgets/collections/collection_filter.css b/apps/client/src/widgets/collections/collection_filter.css
new file mode 100644
index 0000000000..ecc4153910
--- /dev/null
+++ b/apps/client/src/widgets/collections/collection_filter.css
@@ -0,0 +1,41 @@
+:where(:root) {
+ --collection-filter-active-border-color: var(--main-text-color);
+ --collection-filter-error-color: #c73a35;
+ --collection-filter-error-background: var(--main-background-color);
+ --collection-filter-error-border-color: var(--main-border-color);
+}
+
+.collection-filter {
+ display: inline-flex;
+ position: relative;
+ align-items: center;
+ gap: 0.25em;
+
+ > input.form-control {
+ width: clamp(120px, 30vw, 260px);
+ padding: 2px 8px;
+ font-size: inherit;
+ }
+
+ &.active > input.form-control {
+ border-color: var(--collection-filter-active-border-color);
+ }
+
+ .collection-filter-error {
+ display: block;
+ position: absolute;
+ top: calc(100% + 4px);
+ left: 0;
+ z-index: 100;
+ max-width: 60vw;
+ border: 1px solid var(--collection-filter-error-border-color);
+ border-radius: 4px;
+ padding: 2px 8px;
+ background: var(--collection-filter-error-background);
+ color: var(--collection-filter-error-color);
+ font-size: 0.9em;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+}
diff --git a/apps/client/src/widgets/collections/collection_filter.spec.tsx b/apps/client/src/widgets/collections/collection_filter.spec.tsx
new file mode 100644
index 0000000000..7dbf1e0004
--- /dev/null
+++ b/apps/client/src/widgets/collections/collection_filter.spec.tsx
@@ -0,0 +1,347 @@
+import { deferred } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import Component from "../../components/component";
+import type FNote from "../../entities/fnote";
+import type { EntityChange } from "../../server_types";
+import LoadResults from "../../services/load_results";
+import searchService from "../../services/search";
+import { buildNote } from "../../test/easy-froca";
+import { ParentComponent } from "../react/react_utils";
+import {
+ type CollectionFilter, CollectionFilterInput, useCollectionFilter
+} from "./collection_filter";
+
+vi.mock("../../services/i18n", () => ({
+ t: (key: string) => key
+}));
+
+vi.mock("../../services/search", () => ({
+ default: { searchInSubtree: vi.fn() }
+}));
+
+const searchInSubtree = vi.mocked(searchService.searchInSubtree);
+
+let currentFilter: CollectionFilter | undefined;
+
+function Harness({ note, persistedQuery, onQueryChanged, collectionNoteIds }: {
+ note: FNote;
+ persistedQuery?: string;
+ onQueryChanged?: (query: string) => void;
+ collectionNoteIds?: string[];
+}) {
+ currentFilter = useCollectionFilter(note, {
+ persistedQuery,
+ onQueryChanged: onQueryChanged ?? (() => {}),
+ collectionNoteIds: collectionNoteIds ?? []
+ });
+ return null;
+}
+
+function matchResponse(noteIds: string[], error: string | null = null) {
+ return {
+ searchResultNoteIds: noteIds,
+ highlightedTokens: [ { token: "match", type: "plain" as const } ],
+ error
+ };
+}
+
+function branchEntitiesReloaded(parentNoteId: string, childNoteId: string) {
+ const branchId = `br-${childNoteId}`;
+ const loadResults = new LoadResults([
+ {
+ entityName: "branches",
+ entityId: branchId,
+ entity: { branchId, parentNoteId, noteId: childNoteId },
+ componentId: "comp-1"
+ } as unknown as EntityChange
+ ]);
+ loadResults.addBranch(branchId, "comp-1");
+ return loadResults;
+}
+
+async function flushMicrotasks() {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+/**
+ * Flushes the work a mutation leaves behind: the effect run at the end of the previous `act` starts
+ * the search, whose resolution then has to land inside an `act` of its own to be drawn.
+ */
+async function settle() {
+ await act(async () => {
+ await flushMicrotasks();
+ });
+}
+
+describe("useCollectionFilter", () => {
+ let container: HTMLElement | undefined;
+ let parent: Component;
+
+ beforeEach(() => {
+ currentFilter = undefined;
+ searchInSubtree.mockReset();
+ parent = new Component();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ async function mount(props: Omit<Parameters<typeof Harness>[0], "note"> & { note?: FNote }) {
+ const note = props.note ?? buildNote({ title: "Board" });
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={parent}>
+ <Harness {...props} note={note} />
+ </ParentComponent.Provider>,
+ container ?? document.body
+ );
+ await flushMicrotasks();
+ });
+ return note;
+ }
+
+ it("stays inactive without a query and resolves matches on submit", async () => {
+ searchInSubtree.mockResolvedValue(matchResponse([ "n1", "n2" ]));
+ const note = await mount({});
+
+ expect(currentFilter?.matchedNoteIds).toBeNull();
+ expect(searchInSubtree).not.toHaveBeenCalled();
+
+ await act(async () => {
+ currentFilter?.setQuery("#done");
+ await flushMicrotasks();
+ });
+ await settle();
+
+ expect(searchInSubtree).toHaveBeenCalledWith("#done", note.noteId);
+ expect([ ...(currentFilter?.matchedNoteIds ?? []) ]).toEqual([ "n1", "n2" ]);
+ expect(currentFilter?.highlightedTokens).toEqual([ { token: "match", type: "plain" } ]);
+
+ await act(async () => {
+ currentFilter?.setQuery("");
+ await flushMicrotasks();
+ });
+
+ expect(currentFilter?.matchedNoteIds).toBeNull();
+ expect(currentFilter?.highlightedTokens).toBeNull();
+ });
+
+ it("reports a submitted query for persistence, trimmed", async () => {
+ searchInSubtree.mockResolvedValue(matchResponse([]));
+ const onQueryChanged = vi.fn();
+ await mount({ onQueryChanged });
+
+ await act(async () => {
+ currentFilter?.setQuery(" #done ");
+ await flushMicrotasks();
+ });
+
+ expect(onQueryChanged).toHaveBeenCalledWith("#done");
+ expect(currentFilter?.query).toBe("#done");
+ });
+
+ it("resolves a persisted query on mount", async () => {
+ searchInSubtree.mockResolvedValue(matchResponse([ "n1" ]));
+ const note = await mount({ persistedQuery: "#done" });
+
+ expect(searchInSubtree).toHaveBeenCalledWith("#done", note.noteId);
+ expect(currentFilter?.matchedNoteIds?.has("n1")).toBe(true);
+ });
+
+ it("keeps the previous matches when a query comes back with an error", async () => {
+ searchInSubtree.mockResolvedValueOnce(matchResponse([ "n1" ]));
+ await mount({});
+
+ await act(async () => {
+ currentFilter?.setQuery("#done");
+ await flushMicrotasks();
+ });
+ await settle();
+
+ searchInSubtree.mockResolvedValueOnce(matchResponse([ "other" ], "broken query"));
+ await act(async () => {
+ currentFilter?.setQuery("#done ==");
+ await flushMicrotasks();
+ });
+ await settle();
+
+ expect(currentFilter?.error).toBe("broken query");
+ expect([ ...(currentFilter?.matchedNoteIds ?? []) ]).toEqual([ "n1" ]);
+
+ // A good query clears the error and takes over.
+ searchInSubtree.mockResolvedValueOnce(matchResponse([ "n2" ]));
+ await act(async () => {
+ currentFilter?.setQuery("#other");
+ await flushMicrotasks();
+ });
+ await settle();
+
+ expect(currentFilter?.error).toBeNull();
+ expect([ ...(currentFilter?.matchedNoteIds ?? []) ]).toEqual([ "n2" ]);
+ });
+
+ it("lets only the newest run set the result when runs resolve out of order", async () => {
+ const first = deferred<ReturnType<typeof matchResponse>>();
+ const second = deferred<ReturnType<typeof matchResponse>>();
+ searchInSubtree.mockReturnValueOnce(first).mockReturnValueOnce(second);
+ await mount({});
+
+ await act(async () => { currentFilter?.setQuery("#first"); });
+ await act(async () => { currentFilter?.setQuery("#second"); });
+
+ await act(async () => {
+ second.resolve(matchResponse([ "newer" ]));
+ await flushMicrotasks();
+ });
+ await act(async () => {
+ first.resolve(matchResponse([ "older" ]));
+ await flushMicrotasks();
+ });
+
+ expect([ ...(currentFilter?.matchedNoteIds ?? []) ]).toEqual([ "newer" ]);
+ });
+
+ it("re-runs an active filter, debounced, when a change touches the collection", async () => {
+ vi.useFakeTimers();
+ searchInSubtree.mockResolvedValue(matchResponse([ "n1" ]));
+ const note = await mount({ collectionNoteIds: [ "n1", "n2" ] });
+
+ await act(async () => {
+ currentFilter?.setQuery("#done");
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(searchInSubtree).toHaveBeenCalledTimes(1);
+
+ // Two changes inside the debounce window collapse into one re-run.
+ await act(async () => {
+ await parent.handleEvent("entitiesReloaded", {
+ loadResults: branchEntitiesReloaded(note.noteId, "added")
+ });
+ await parent.handleEvent("entitiesReloaded", {
+ loadResults: branchEntitiesReloaded("n2", "nested")
+ });
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ expect(searchInSubtree).toHaveBeenCalledTimes(2);
+
+ // A change elsewhere re-runs nothing.
+ await act(async () => {
+ await parent.handleEvent("entitiesReloaded", {
+ loadResults: branchEntitiesReloaded("unrelated", "elsewhere")
+ });
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ expect(searchInSubtree).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not re-run while no filter is active", async () => {
+ const note = await mount({ collectionNoteIds: [ "n1" ] });
+ vi.useFakeTimers();
+
+ await act(async () => {
+ await parent.handleEvent("entitiesReloaded", {
+ loadResults: branchEntitiesReloaded(note.noteId, "added")
+ });
+ await vi.advanceTimersByTimeAsync(400);
+ });
+
+ expect(searchInSubtree).not.toHaveBeenCalled();
+ });
+});
+
+describe("CollectionFilterInput", () => {
+ let container: HTMLElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ function mountInput(overrides: Partial<CollectionFilter> = {}) {
+ const filter: CollectionFilter = {
+ query: "",
+ matchedNoteIds: null,
+ highlightedTokens: null,
+ error: null,
+ setQuery: vi.fn(),
+ ...overrides
+ };
+ // Rendered inside act so the mount effects run now, not queued into the next act where
+ // they would clobber what a test has typed in the meantime.
+ act(() => render(<CollectionFilterInput filter={filter} />, container));
+ const input = container.querySelector("input");
+ expect(input).not.toBeNull();
+ return { filter, input: input as HTMLInputElement };
+ }
+
+ function type(input: HTMLInputElement, value: string) {
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+
+ it("submits what is typed on Enter", async () => {
+ const { filter, input } = mountInput();
+
+ // Typed first and submitted in a pass of its own, so the keydown runs against the
+ // re-rendered handler that has seen the typing.
+ await act(async () => type(input, "#done"));
+ await act(async () => {
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ });
+
+ expect(filter.setQuery).toHaveBeenCalledWith("#done");
+ });
+
+ it("clears the filter through the button and refocuses the box", async () => {
+ const { filter } = mountInput({ query: "#done" });
+
+ const clear = container.querySelector<HTMLElement>(".collection-filter-clear");
+ expect(clear).not.toBeNull();
+ await act(async () => clear?.click());
+
+ expect(filter.setQuery).toHaveBeenCalledWith("");
+ });
+
+ it("shows the box as active and offers no clear button while empty and inactive", () => {
+ mountInput();
+ expect(container.querySelector(".collection-filter")?.classList.contains("active")).toBe(false);
+ expect(container.querySelector(".collection-filter-clear")).toBeNull();
+
+ mountInput({ query: "#done" });
+ expect(container.querySelector(".collection-filter")?.classList.contains("active")).toBe(true);
+ });
+
+ it("shows the query error under the box", () => {
+ mountInput({ error: "broken" });
+ expect(container.querySelector(".collection-filter-error")?.textContent).toBe("broken");
+ });
+
+ it("gives up unsubmitted typing on Escape without touching the filter", async () => {
+ const { filter, input } = mountInput({ query: "#kept" });
+
+ await act(async () => type(input, "#typed"));
+ await act(async () => {
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+ });
+
+ expect(input.value).toBe("#kept");
+ expect(filter.setQuery).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/widgets/collections/collection_filter.tsx b/apps/client/src/widgets/collections/collection_filter.tsx
new file mode 100644
index 0000000000..16c6ddee89
--- /dev/null
+++ b/apps/client/src/widgets/collections/collection_filter.tsx
@@ -0,0 +1,197 @@
+import "./collection_filter.css";
+
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
+import clsx from "clsx";
+import { useEffect, useMemo, useRef, useState } from "preact/hooks";
+
+import FNote from "../../entities/fnote";
+import { t } from "../../services/i18n";
+import type LoadResults from "../../services/load_results";
+import searchService from "../../services/search";
+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. */
+const RERUN_DEBOUNCE_MS = 300;
+
+export interface CollectionFilter {
+ /** The submitted query, empty while no filter is active. */
+ query: string;
+ /** The notes the query matches, or null while no filter is active. */
+ matchedNoteIds: Set<string> | null;
+ /** The tokens the matches were found by, for highlighting them where the notes are drawn. */
+ highlightedTokens: HighlightedTokenInfo[] | null;
+ /** What is wrong with the query, or null. An erroneous query keeps the previous matches. */
+ error: string | null;
+ setQuery: (query: string) => void;
+}
+
+interface FilterMatches {
+ matchedNoteIds: Set<string> | null;
+ highlightedTokens: HighlightedTokenInfo[] | null;
+}
+
+const NO_MATCHES: FilterMatches = { matchedNoteIds: null, highlightedTokens: null };
+
+/**
+ * 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.
+ */
+export function useCollectionFilter(note: FNote, {
+ persistedQuery, onQueryChanged, collectionNoteIds
+}: {
+ /** The stored query the filter starts from, so it survives reopening the collection. */
+ persistedQuery: string | undefined;
+ /** Reports a submitted query, for the view to persist. Called with "" when cleared. */
+ onQueryChanged: (query: string) => void;
+ /** The notes the collection shows, deciding which entity changes re-run the filter. */
+ collectionNoteIds: string[];
+}): CollectionFilter {
+ 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.
+ const runSeqRef = useRef(0);
+ const rerunTimerRef = useRef<number>();
+ const collectionSet = useMemo(() => new Set(collectionNoteIds), [ collectionNoteIds ]);
+ const collectionSetRef = useRef(collectionSet);
+ collectionSetRef.current = collectionSet;
+
+ async function run(activeQuery: string) {
+ const seq = ++runSeqRef.current;
+ let response;
+ try {
+ response = await searchService.searchInSubtree(activeQuery, note.noteId);
+ } catch (e) {
+ console.error("Failed to run the collection filter:", e);
+ if (seq === runSeqRef.current) {
+ setError(t("collection_filter.fetch-error"));
+ }
+ return;
+ }
+
+ if (seq !== runSeqRef.current) {
+ return;
+ }
+
+ if (response.error) {
+ // The previous matches stay shown: a broken query must not blank the collection.
+ setError(response.error);
+ return;
+ }
+
+ setError(null);
+ setMatches({
+ matchedNoteIds: new Set(response.searchResultNoteIds),
+ highlightedTokens: response.highlightedTokens
+ });
+ }
+
+ // Adopt a query stored elsewhere: the persisted one on mount, or one another view submitted.
+ useEffect(() => {
+ setQuery(persistedQuery ?? "");
+ }, [ note.noteId, persistedQuery ]);
+
+ // Resolve the submitted query, or drop the filter when it is cleared.
+ useEffect(() => {
+ window.clearTimeout(rerunTimerRef.current);
+ if (!query.trim()) {
+ runSeqRef.current++;
+ setError(null);
+ setMatches(NO_MATCHES);
+ return;
+ }
+ run(query);
+ }, [ note.noteId, query ]);
+
+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
+ if (!query.trim() || !touchesCollection(loadResults, collectionSetRef.current, note.noteId)) {
+ return;
+ }
+ window.clearTimeout(rerunTimerRef.current);
+ rerunTimerRef.current = window.setTimeout(() => run(query), RERUN_DEBOUNCE_MS);
+ });
+
+ useEffect(() => () => window.clearTimeout(rerunTimerRef.current), []);
+
+ return {
+ query,
+ ...matches,
+ error,
+ setQuery: (newQuery: string) => {
+ const trimmed = newQuery.trim();
+ setQuery(trimmed);
+ onQueryChanged(trimmed);
+ }
+ };
+}
+
+/**
+ * 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.
+ */
+export function CollectionFilterInput({ filter }: { filter: CollectionFilter }) {
+ const [ typed, setTyped ] = useState(filter.query);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ // Adopt a query submitted elsewhere, or the stored one arriving on mount.
+ useEffect(() => setTyped(filter.query), [ filter.query ]);
+
+ const isActive = !!filter.query;
+
+ return (
+ <div className={clsx("collection-filter", { active: isActive })}>
+ <FormTextBox
+ inputRef={inputRef}
+ currentValue={typed}
+ placeholder={t("collection_filter.placeholder")}
+ title={t("collection_filter.tooltip")}
+ onChange={setTyped}
+ onKeyDown={(e: KeyboardEvent) => {
+ if (e.key === "Enter") {
+ 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.
+ e.stopPropagation();
+ setTyped(filter.query);
+ }
+ }}
+ />
+ {(!!typed || isActive) && (
+ <ActionButton
+ className="collection-filter-clear"
+ icon="bx bx-x"
+ text={t("collection_filter.clear")}
+ onClick={() => {
+ setTyped("");
+ filter.setQuery("");
+ inputRef.current?.focus();
+ }}
+ />
+ )}
+ {filter.error && <span className="collection-filter-error">{filter.error}</span>}
+ </div>
+ );
+}
+
+/** Whether any changed note, attribute or branch belongs to the collection's subtree. */
+function touchesCollection(
+ loadResults: LoadResults, collectionNoteIds: Set<string>, collectionNoteId: string
+) {
+ const inCollection = (noteId: string | null | undefined) =>
+ !!noteId && (noteId === collectionNoteId || collectionNoteIds.has(noteId));
+
+ return loadResults.getNoteIds().some(inCollection)
+ || loadResults.getAttributeRows().some(attr => inCollection(attr.noteId))
+ || loadResults.getBranchRows().some(branch =>
+ inCollection(branch.noteId) || inCollection(branch.parentNoteId));
+}
diff --git a/apps/client/src/widgets/collections/search/SearchResultCard.tsx b/apps/client/src/widgets/collections/search/SearchResultCard.tsx
index 3a1d2ca7b2..9bdb8db972 100644
--- a/apps/client/src/widgets/collections/search/SearchResultCard.tsx
+++ b/apps/client/src/widgets/collections/search/SearchResultCard.tsx
@@ -1,12 +1,11 @@
import type { HighlightedTokenInfo, SearchResultDetails } from "@triliumnext/commons";
-import { useEffect, useRef } from "preact/hooks";
import { t } from "../../../services/i18n";
import { calculateHash, type ViewScope } from "../../../services/link";
import { Badge } from "../../react/Badge";
-import { useImperativeSearchHighlighlighting, useNote, useNoteTitle } from "../../react/hooks";
+import { useNote, useNoteTitle } from "../../react/hooks";
import Icon from "../../react/Icon";
-import RawHtml, { RawHtmlBlock } from "../../react/RawHtml";
+import RawHtml, { HighlightedText, RawHtmlBlock } from "../../react/RawHtml";
interface SearchResultCardProps {
noteId: string;
@@ -33,26 +32,15 @@ export default function SearchResultCard({ noteId, details, loading, highlighted
const viewScope: ViewScope = { searchTerms };
const href = calculateHash({ notePath: noteId, viewScope });
- // Set the title text imperatively so mark.js, which injects `.ck-find-result` spans into the
- // DOM, does not fight Preact's reconciliation of a controlled text child. NoteLink renders its
- // title imperatively for the same reason.
- const titleRef = useRef<HTMLSpanElement>(null);
- const highlightTitle = useImperativeSearchHighlighlighting(highlightedTokens);
- useEffect(() => {
- if (titleRef.current) {
- titleRef.current.textContent = title;
- highlightTitle(titleRef.current);
- }
- // highlightTitle is a fresh closure each render; keying on the token list (as the legacy
- // cards do) avoids re-running on every render.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [ title, highlightedTokens ]);
-
return (
<a className="search-result-card" href={href}>
<div className="search-result-card-header">
<Icon className="search-result-card-icon" icon={icon} />
- <span className="search-result-card-title" ref={titleRef} />
+ <HighlightedText
+ className="search-result-card-title"
+ text={title}
+ highlightedTokens={highlightedTokens}
+ />
{breadcrumb && <span className="search-result-card-path">{breadcrumb}</span>}
</div>
<SearchResultSnippet details={details} loading={loading} />
diff --git a/apps/client/src/widgets/react/RawHtml.spec.tsx b/apps/client/src/widgets/react/RawHtml.spec.tsx
index 9ad3b4d145..0e905c9e5d 100644
--- a/apps/client/src/widgets/react/RawHtml.spec.tsx
+++ b/apps/client/src/widgets/react/RawHtml.spec.tsx
@@ -1,7 +1,8 @@
import { render } from "preact";
+import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import RawHtml, { RawHtmlBlock } from "./RawHtml";
+import RawHtml, { HighlightedText, RawHtmlBlock } from "./RawHtml";
let container: HTMLDivElement;
@@ -47,3 +48,47 @@ describe("RawHtml", () => {
expect(el?.hasAttribute("tabindex")).toBe(false);
});
});
+
+describe("HighlightedText", () => {
+ it("renders the text as text, never as markup", () => {
+ act(() => render(
+ <HighlightedText className="title" text="a <b>literal</b> title" highlightedTokens={null} />,
+ container
+ ));
+
+ const el = container.querySelector("span.title");
+ expect(el?.textContent).toBe("a <b>literal</b> title");
+ expect(el?.querySelector("b")).toBeNull();
+ });
+
+ it("marks the matched tokens and clears them when the tokens go away", () => {
+ act(() => render(
+ <HighlightedText text="the matched word" highlightedTokens={[ "matched" ]} />,
+ container
+ ));
+
+ const marks = () => [ ...container.querySelectorAll(".ck-find-result") ];
+ expect(marks().map((mark) => mark.textContent)).toEqual([ "matched" ]);
+
+ act(() => render(
+ <HighlightedText text="the matched word" highlightedTokens={null} />,
+ container
+ ));
+ expect(marks()).toEqual([]);
+ expect(container.textContent).toBe("the matched word");
+ });
+
+ it("re-applies the marks when the text changes under the same tokens", () => {
+ act(() => render(
+ <HighlightedText text="one match" highlightedTokens={[ "match" ]} />,
+ container
+ ));
+ act(() => render(
+ <HighlightedText text="another match here" highlightedTokens={[ "match" ]} />,
+ container
+ ));
+
+ expect(container.textContent).toBe("another match here");
+ expect(container.querySelectorAll(".ck-find-result")).toHaveLength(1);
+ });
+});
diff --git a/apps/client/src/widgets/react/RawHtml.tsx b/apps/client/src/widgets/react/RawHtml.tsx
index a6e251425b..2bf0a3c18f 100644
--- a/apps/client/src/widgets/react/RawHtml.tsx
+++ b/apps/client/src/widgets/react/RawHtml.tsx
@@ -1,5 +1,9 @@
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
import DOMPurify from "dompurify";
import type { CSSProperties, HTMLProps, RefObject } from "preact/compat";
+import { useEffect, useRef } from "preact/hooks";
+
+import { useImperativeSearchHighlighlighting } from "./hooks";
type HTMLElementLike = string | HTMLElement | JQuery<HTMLElement>;
@@ -43,6 +47,30 @@ export function getHtml(html: string | HTMLElement | JQuery<HTMLElement>) {
};
}
+/**
+ * Renders plain text with search-match highlighting. The text is set imperatively so mark.js,
+ * which injects `.ck-find-result` spans around matches, does not fight Preact's reconciliation
+ * of a controlled text child.
+ */
+export function HighlightedText({ className, text, highlightedTokens }: {
+ className?: string;
+ text: string;
+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined;
+}) {
+ const ref = useRef<HTMLSpanElement>(null);
+ const highlight = useImperativeSearchHighlighlighting(highlightedTokens);
+
+ // `highlight` is a fresh closure each render, so the effect keys on the token list instead.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useEffect(() => {
+ if (!ref.current) return;
+ ref.current.textContent = text;
+ highlight(ref.current);
+ }, [ text, highlightedTokens ]);
+
+ return <span className={className} ref={ref} />;
+}
+
/**
* Renders HTML content sanitized via DOMPurify to prevent XSS.
* Use this instead of {@link RawHtml} when the HTML originates from
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index b6a9345003..1fcf00731f 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -349,6 +349,13 @@ export interface HighlightedTokenInfo {
type: "plain" | "regex" | "fuzzy";
}
+/** Response for `GET /api/search/:searchString?includeTokens=true`. */
+export interface SearchWithTokensResponse {
+ searchResultNoteIds: string[];
+ highlightedTokens: HighlightedTokenInfo[];
+ error: string | null;
+}
+
/** Request body for `POST /api/search-note/:noteId/result-details` (max 100 noteIds). */
export interface SearchResultDetailsRequest {
noteIds: string[];
diff --git a/packages/trilium-core/src/routes/api/search.spec.ts b/packages/trilium-core/src/routes/api/search.spec.ts
index 539bff71cb..4a1822b3ba 100644
--- a/packages/trilium-core/src/routes/api/search.spec.ts
+++ b/packages/trilium-core/src/routes/api/search.spec.ts
@@ -1,4 +1,4 @@
-import { dayjs, type SearchResultDetailsResponse, type TemplatesResponse } from "@triliumnext/commons";
+import { dayjs, type SearchResultDetailsResponse, type SearchWithTokensResponse, type TemplatesResponse } from "@triliumnext/commons";
import { beforeAll, describe, expect, it } from "vitest";
import { createTextNote } from "../../test/api_fixtures";
@@ -30,6 +30,46 @@ describe("Search API (core)", () => {
expect(res.body).toContain(createdNoteId);
});
+ it("restricts a full search to the given ancestor's subtree", async () => {
+ const token = "ZzScopedSearchQwerty";
+ const board = await createTextNote(api, { title: "Board" });
+ const inside = await createTextNote(api, { parentNoteId: board.noteId, title: `${token} inside` });
+ const outside = await createTextNote(api, { title: `${token} outside` });
+
+ const scoped = await api.get<string[]>(`/api/search/${token}`, {
+ query: { ancestorNoteId: board.noteId }
+ });
+ expect(scoped.status).toBe(200);
+ expect(scoped.body).toContain(inside.noteId);
+ expect(scoped.body).not.toContain(outside.noteId);
+
+ const unscoped = await api.get<string[]>(`/api/search/${token}`);
+ expect(unscoped.body).toContain(inside.noteId);
+ expect(unscoped.body).toContain(outside.noteId);
+ });
+
+ it("returns note ids with token infos and the error when includeTokens is set", async () => {
+ const withTokens = await api.get<SearchWithTokensResponse>(`/api/search/${UNIQUE_TOKEN}`, {
+ query: { includeTokens: "true" }
+ });
+ expect(withTokens.status).toBe(200);
+ expect(withTokens.body.searchResultNoteIds).toContain(createdNoteId);
+ expect(withTokens.body.highlightedTokens).toContainEqual({
+ token: UNIQUE_TOKEN.toLowerCase(),
+ type: "plain"
+ });
+ expect(withTokens.body.error).toBeNull();
+
+ // A query the parser rejects still answers 200, with the parse error in the body for the
+ // client to show inline.
+ const broken = await api.get<SearchWithTokensResponse>(
+ `/api/search/${encodeURIComponent("#label = ")}`,
+ { query: { includeTokens: "true" } }
+ );
+ expect(broken.status).toBe(200);
+ expect(broken.body.error).toBeTruthy();
+ });
+
it("returns structured quick-search results with snippets", async () => {
const res = await api.get<{ searchResultNoteIds: string[]; searchResults: unknown[]; highlightedTokens: string[] }>(
`/api/quick-search/${UNIQUE_TOKEN}`
diff --git a/packages/trilium-core/src/routes/api/search.ts b/packages/trilium-core/src/routes/api/search.ts
index 457552358f..f41adf0dc6 100644
--- a/packages/trilium-core/src/routes/api/search.ts
+++ b/packages/trilium-core/src/routes/api/search.ts
@@ -1,4 +1,4 @@
-import { dayjs, type SearchResultDetails, type SearchResultDetailsRequest, type SearchResultDetailsResponse, 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";
@@ -134,17 +134,34 @@ function quickSearch(req: Request<{ searchString: string }>) {
};
}
-function search(req: Request<{ searchString: string }>) {
+function search(
+ req: Request<{ searchString: string }, unknown, unknown,
+ { ancestorNoteId?: string, includeTokens?: string }>
+): string[] | SearchWithTokensResponse {
const { searchString } = req.params;
+ const { ancestorNoteId, includeTokens } = req.query;
const searchContext = new SearchContext({
fastSearch: false,
includeArchivedNotes: true,
fuzzyAttributeSearch: false,
- ignoreHoistedNote: true
+ 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
});
- return searchService.findResultsWithQuery(searchString, searchContext).map((sr) => sr.noteId);
+ const noteIds = searchService.findResultsWithQuery(searchString, searchContext).map((sr) => sr.noteId);
+
+ if (includeTokens !== "true") {
+ return noteIds;
+ }
+
+ return {
+ searchResultNoteIds: noteIds,
+ highlightedTokens: searchContext.getHighlightedTokenInfos(),
+ error: searchContext.getError()
+ };
}
function getRelatedNotes(req: Request) {