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/search & filtering: fix some issues
Adorian Doranc00532848ae8
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 4dbe5929ae..73404ea99a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3494,7 +3494,8 @@"move_column_to_edge": "Move the column to the far left / right"},"status-alias": "Status",- "filter-placeholder": "Filter board..."+ "filter-placeholder": "Filter board...",+ "card-outside-filter": "This card is outside of the current filtering scope"},"dashboard_view": {"refresh-widget": "Refresh",diff --git a/apps/client/src/widgets/attribute_widgets/UserAttributesList.spec.tsx b/apps/client/src/widgets/attribute_widgets/UserAttributesList.spec.tsxindex 91bb0d0d28..b5b9795960 100644--- a/apps/client/src/widgets/attribute_widgets/UserAttributesList.spec.tsx+++ b/apps/client/src/widgets/attribute_widgets/UserAttributesList.spec.tsx@@ -1,4 +1,4 @@-import { render } from "preact";+import { ComponentChildren, render } from "preact";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -53,6 +53,16 @@ describe("UserAttributesDisplay", () => {expect(container.querySelector(".user-attributes")).toBeNull();});+ it("draws a caller's badges before the attributes, and without them", () => {+ draw({ shownAttributes: [ "stage" ], badges: <span className="marker">!</span> });+ expect([ ...(container.querySelector(".user-attributes")?.children ?? []) ]+ .map(child => child.className)).toEqual([ "marker", "user-attribute type-label text" ]);++ // The row is what carries a badge, so it stands even where no attribute would raise it.+ draw({ shownAttributes: [], badges: <span className="marker">!</span> });+ expect(container.querySelector(".user-attributes .marker")).not.toBeNull();+ });+/** The values of one attribute belong together wherever the attribute is placed. */it("keeps the values of one attribute together", () => {const note = noteWith({ tag: [ "red", "green" ], owner: [ "Ada" ] });@@ -78,8 +88,9 @@ describe("UserAttributesDisplay", () => {expect(values()).toEqual([ "Doing", "Ada" ]);});- function draw({ note = NOTE, ignoredAttributes, shownAttributes }: {- note?: FNote, ignoredAttributes?: string[], shownAttributes?: string[]+ function draw({ note = NOTE, ignoredAttributes, shownAttributes, badges }: {+ note?: FNote, ignoredAttributes?: string[], shownAttributes?: string[],+ badges?: ComponentChildren} = {}) {act(() => {render(@@ -87,6 +98,7 @@ describe("UserAttributesDisplay", () => {note={note}ignoredAttributes={ignoredAttributes}shownAttributes={shownAttributes}+ badges={badges}/>,container);});diff --git a/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx b/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsxindex 8b6b6c9849..52f630948c 100644--- a/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx+++ b/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx@@ -20,6 +20,8 @@ interface UserAttributesListProps {* carrying a definition is drawn, in the order the definitions stand in.*/shownAttributes?: string[];+ /** Drawn before the attributes, for what a caller marks a note with in the same row. */+ badges?: ComponentChildren;}interface AttributeWithDefinitions {@@ -31,11 +33,12 @@ interface AttributeWithDefinitions {}export default function UserAttributesDisplay({- note, ignoredAttributes, shownAttributes+ note, ignoredAttributes, shownAttributes, badges}: UserAttributesListProps) {const userAttributes = useNoteAttributesWithDefinitions(note, ignoredAttributes, shownAttributes);- return userAttributes?.length > 0 && (+ return (userAttributes?.length > 0 || !!badges) && (<div className="user-attributes">+ {badges}{userAttributes?.map(attr => buildUserAttribute(attr))}</div>);diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex d4562d0604..6045a9b0cd 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -69,7 +69,8 @@ function createApi(parentNote?: FNote,statusAttribute = "status",byColumn: ColumnMap = new Map(),- allByColumn?: ColumnMap+ allByColumn?: ColumnMap,+ keepNote?: (noteId: string) => void) {const board = parentNote ?? buildNote({ title: "Board" });const saved: BoardViewData[] = [];@@ -86,7 +87,8 @@ function createApi((branchId) => editing.push(branchId),pending,getStatusDefinition(board, statusAttribute),- allByColumn+ allByColumn,+ keepNote);return { api, board, saved, editing, pendingRenames: pending.renames };}@@ -621,15 +623,51 @@ describe("BoardApi card operations", () => {.toHaveBeenCalledWith([ spare.branch.branchId ], done[0].branch.branchId);});- it("sends a card to the true end of a column a filter narrows", async () => {+ it("sends a card after the last one drawn in a column a filter narrows", async () => {const { api, done, spare } = createBoardWithSpareCard((all) => [ all[0] ]);await api.moveToColumnEnd(spare.note.noteId, spare.branch.branchId, "Done");+ expect(branches.moveAfterBranch)+ .toHaveBeenCalledWith([ spare.branch.branchId ], done[0].branch.branchId);+ });++ it("sends a card past the cards a filter hides when it draws none of them", async () => {+ const { api, done, spare } = createBoardWithSpareCard(() => []);++ await api.moveToColumnEnd(spare.note.noteId, spare.branch.branchId, "Done");+expect(branches.moveAfterBranch).toHaveBeenCalledWith([ spare.branch.branchId ], done[2].branch.branchId);});+ /**+ * A card is rarely made to match the query in force, so one made here is drawn anyway rather+ * than the board answering an addition by showing nothing at all.+ */+ it("reports every card it gains, so a filter does not swallow it", async () => {+ const kept: string[] = [];+ const { api } = createApi(+ {}, [ "Done" ], undefined, "status", new Map(), undefined,+ (noteId) => kept.push(noteId));+ vi.mocked(note_create.createNote).mockResolvedValue(+ { note: { noteId: "made" } } as never);++ await api.createNewItem("Done", "Made now");++ expect(kept).toEqual([ "made" ]);+ });++ it("makes a card at the head of a column above the first one drawn", async () => {+ const { api, done } = createBoardWithSpareCard((all) => [ all[1] ]);++ await api.createNewItem("Done", "Newest", "top");++ expect(note_create.createNote).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ target: "before", targetBranchId: done[1].branch.branchId }));+ });+it("reorders within a column, and places past the last card after it", async () => {const { api, items } = createBoardWithCards();const [ first, , third ] = items;diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 5ffa2d6e94..62d9b2c7fc 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -123,7 +123,9 @@ export default class BoardApi {* 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+ private allByColumn?: ColumnMap,+ /** Draws a card the active filter does not match. See {@link keepInView}. */+ private keepNote?: (noteId: string) => void) {this.viewConfigSource = viewConfig;this.viewConfig = viewConfig ?? {};@@ -150,7 +152,8 @@ export default class BoardApi {saveConfig: (newConfig: BoardViewData) => void,setBranchIdToEdit: (branchId: string | undefined) => void,statusDefinition?: BoardStatusDefinition,- allByColumn?: ColumnMap+ allByColumn?: ColumnMap,+ keepNote?: (noteId: string) => void) {// 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@@ -161,6 +164,7 @@ export default class BoardApi {this.byColumn = byColumn;this.allByColumn = allByColumn;+ this.keepNote = keepNote;this.columns = columns;this.parentNote = parentNote;// Only a config the board has actually replaced, since `storeColumns` moves this one ahead@@ -187,9 +191,7 @@ export default class BoardApi {column: string, title: string, placement: CardPlacement = "bottom", icon?: string,template: NoteTypeOption | undefined = this.getCurrentCardTemplate()) {- const first = placement === "top"- ? this.byColumn?.get(column)?.[0]?.branch.branchId- : undefined;+ const first = placement === "top" ? this.firstInColumn(column) : undefined;try {const { note } = await note_create.createNote(this.parentNote.noteId, {@@ -201,6 +203,7 @@ export default class BoardApi {...(first ? { target: "before", targetBranchId: first } : {})});+ this.keepInView(note?.noteId);return note?.noteId;} catch (error) {console.error("Failed to create new item:", error);@@ -226,6 +229,19 @@ export default class BoardApi {return note.noteId;}+ /**+ * Keeps a card the board has just gained on screen while the board is narrowed by a filter.+ *+ * A card is rarely made to match the query in force, so the board would otherwise answer every+ * addition by drawing nothing at all. It is marked as standing outside the filter, and the+ * next query decides on it like any other card.+ */+ private keepInView(noteId: string | undefined) {+ if (noteId) {+ this.keepNote?.(noteId);+ }+ }+/** What a new card carries besides its title: the column it lands in, and its icon. */private attributesFor(column: string, icon?: string) {return [@@ -298,6 +314,7 @@ export default class BoardApi {await this.moveIntoPlace(noteId, beforeBranchId);}+ this.keepInView(noteId);return true;}@@ -1058,6 +1075,7 @@ export default class BoardApi {throw new Error("Failed to create note");}+ this.keepInView(note.noteId);return { note, branch };}@@ -1086,9 +1104,11 @@ export default class BoardApi {* named by the server and has to be in froca before it can be placed.*/async duplicateItem(noteId: string, branchId: string) {- const { branch } = await server.post<{ branch: { branchId: string } }>(- `notes/${noteId}/duplicate/${this.parentNote.noteId}`);+ const { note, branch } = await server.post<+ { note: { noteId: string }, branch: { branchId: string } }>(+ `notes/${noteId}/duplicate/${this.parentNote.noteId}`);+ this.keepInView(note?.noteId);await ws.waitForMaxKnownEntityChangeId();await branches.moveAfterBranch([ branch.branchId ], branchId);}@@ -1134,11 +1154,9 @@ export default class BoardApi {// to redraw between two keystrokes, so the column map still shows the target as it was// before the card the last press sent. Anything sent since is remembered here instead, and// the memory lasts exactly as long as the map it stands in for, both being rebuilt by the- // refresh that catches up. Read off the unfiltered map, since the end of a column is behind- // the cards a filter is not showing.- const columnItems = (this.allByColumn ?? this.byColumn)?.get(targetColumn) ?? [];+ // refresh that catches up.const last = this.sentToColumnEnd.get(targetColumn)- ?? columnItems.at(-1)?.branch.branchId;+ ?? this.lastInColumn(targetColumn);await this.changeColumn(noteId, targetColumn);if (last && last !== branchId) {@@ -1153,6 +1171,27 @@ export default class BoardApi {return this.byColumn?.get(column)?.[0]?.branch.branchId === branchId;}+ /**+ * The card a new or arriving one is placed after: the last one drawn, or the last one the+ * column holds when a filter is drawing none of them.+ *+ * Placement is relative to the cards on screen, so the unfiltered map is read only where that+ * rule has nothing to say. Left unplaced, a card would rank among the ones it cannot see by+ * wherever it happened to sit before.+ */+ private lastInColumn(column: string) {+ const shown = this.byColumn?.get(column) ?? [];+ const items = shown.length ? shown : this.allByColumn?.get(column) ?? [];+ return items.at(-1)?.branch.branchId;+ }++ /** The counterpart of {@link lastInColumn}, for a card made at the head of a column. */+ private firstInColumn(column: string) {+ const shown = this.byColumn?.get(column) ?? [];+ const items = shown.length ? shown : this.allByColumn?.get(column) ?? [];+ return items[0]?.branch.branchId;+ }+/*** Moves a card to the head of the column it stands in, where Ctrl+Home also sends it.*@@ -1171,11 +1210,9 @@ export default class BoardApi {async moveWithinBoard(noteId: string, sourceBranchId: string, sourceIndex: number, targetIndex: number, sourceColumn: string, targetColumn: string) {const targetItems = this.byColumn?.get(targetColumn) ?? [];- // What a card dropped past the last one drawn is placed after: the last card shown, or the- // last one the column holds when a filter is showing none of them. Read before the writes- // below, since a redraw between them hands this instance the map with the card moved.- const lastInTarget = (targetItems.at(-1)- ?? this.allByColumn?.get(targetColumn)?.at(-1))?.branch.branchId;+ // Read before the writes below, since a redraw between them hands this instance the map+ // with the card already moved.+ const lastInTarget = this.lastInColumn(targetColumn);const note = froca.getNoteFromCache(noteId);if (!note) return;diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsxindex cf120c8142..48d50fedba 100644--- a/apps/client/src/widgets/collections/board/card.tsx+++ b/apps/client/src/widgets/collections/board/card.tsx@@ -1,12 +1,15 @@+import type { Tooltip } from "bootstrap";import { memo } from "preact/compat";import {useCallback, useContext, useEffect, useLayoutEffect, useRef, useState} from "preact/hooks";+import FBranch from "../../../entities/fbranch";import FNote from "../../../entities/fnote";import BoardApi from "./api";import {- BoardActionsContext, BoardHighlightTokensContext, BoardPromotedAttributesContext, TitleEditor+ BoardActionsContext, BoardHighlightTokensContext, BoardKeptCardsContext,+ BoardPromotedAttributesContext, TitleEditor} from ".";import { ContextMenuEvent } from "../../../menus/context_menu";import { openNoteContextMenu } from "./context_menu";@@ -15,7 +18,8 @@ import UserAttributesDisplay from "../../attribute_widgets/UserAttributesList";import { parseNavigationStateFromUrl } from "../../../services/link";import { FLIP_SETTLE_MS } from "../../react/flip";import {- useNoteColorClass, useNoteIcon, useNoteLabel, useNoteLabelBoolean, useTriliumEvent+ useNoteColorClass, useNoteIcon, useNoteLabel, useNoteLabelBoolean, useStaticTooltip,+ useTriliumEvent} from "../../react/hooks";import { HighlightedText } from "../../react/RawHtml";@@ -64,6 +68,7 @@ function Card({const { setBranchIdToEdit } = useContext(BoardActionsContext);const shownAttributes = useContext(BoardPromotedAttributesContext);const highlightedTokens = useContext(BoardHighlightTokensContext);+ const isOutsideFilter = useContext(BoardKeptCardsContext).has(note.noteId);// Tracks the `color` label, which the board does not redraw a card for.const colorClass = useNoteColorClass(note) || "";const editorRef = useRef<HTMLInputElement>(null);@@ -207,6 +212,7 @@ function Card({note={note}ignoredAttributes={[statusAttribute]}shownAttributes={shownAttributes}+ badges={isOutsideFilter && <OutsideFilterBadge />}/></>) : (@@ -230,6 +236,20 @@ function Card({)}+/** Marks a card drawn although the filter does not match it, which one just made here is. */+function OutsideFilterBadge() {+ const badgeRef = useRef<HTMLSpanElement>(null);+ useStaticTooltip(badgeRef, OUTSIDE_FILTER_TOOLTIP);++ return <span ref={badgeRef} className="board-note-outside-filter icon bx bx-time-five" />;+}++const OUTSIDE_FILTER_TOOLTIP: Partial<Tooltip.Options> = {+ title: t("board_view.card-outside-filter"),+ placement: "bottom",+ animation: false+};+/*** Memoized because a board holds hundreds of these and most redraws change none of them: a drag* moves one card, and the rest receive the same props they already had.diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex 73819a159c..ec809fc910 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -43,19 +43,19 @@ export function applyCardMove(}/**- * The columns with only the cards in `matchedNoteIds`, keeping their order relative to each other.+ * The columns with only the cards in `shownNoteIds`, keeping their order relative to each other.* Every column is kept, since a filter narrows what is drawn and nothing else.*/export function filterColumnMap(- byColumn: ColumnMap, matchedNoteIds: Set<string> | null+ byColumn: ColumnMap, shownNoteIds: Set<string> | null): ColumnMap {- if (!matchedNoteIds) {+ if (!shownNoteIds) {return byColumn;}const filtered: ColumnMap = new Map();for (const [ column, items ] of byColumn) {- filtered.set(column, items.filter(item => matchedNoteIds.has(item.note.noteId)));+ filtered.set(column, items.filter(item => shownNoteIds.has(item.note.noteId)));}return filtered;}diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex 64083bfa6f..6838bab0a9 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -401,6 +401,13 @@ body.mobile .board-view-container .board-add-column {}}+.board-view-container .board-note .board-note-outside-filter {+ color: var(--muted-text-color);+ font-size: 1.1em;+ line-height: 1;+ cursor: default;+}+.board-view-container .board-note > .title > .icon {flex: none;display: flex;diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex bbef1acb7f..71e2f10592 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -206,6 +206,9 @@ export const BoardDragStateContext = createContext<BoardDragState>({*/export const BoardHighlightTokensContext = createContext<HighlightedTokenInfo[] | null>(null);+/** The cards drawn although the filter does not match them, which say as much on their face. */+export const BoardKeptCardsContext = createContext<Set<string>>(new Set());+/*** 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@@ -353,9 +356,9 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// filter matches, and withheld until a query stored in `board.json` has said what it matches.const byColumn = useMemo(() => (allByColumn && !filter.isResolvingStoredQuery- ? filterColumnMap(allByColumn, filter.matchedNoteIds)+ ? filterColumnMap(allByColumn, filter.shownNoteIds): undefined),- [ allByColumn, filter.matchedNoteIds, filter.isResolvingStoredQuery ]);+ [ allByColumn, filter.shownNoteIds, filter.isResolvingStoredQuery ]);if (!apiRef.current || apiRef.current.board !== boardIdentity) {apiRef.current = {@@ -363,12 +366,12 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCapi: new Api(byColumn, usableColumns, parentNote, statusAttributeWithPrefix, viewConfig,saveConfig, setBranchIdToEdit, pendingRenamesRef.current.writes, statusDefinition,- allByColumn)+ allByColumn, filter.keepNote)};} else {apiRef.current.api.update(byColumn, usableColumns, parentNote, statusAttributeWithPrefix, viewConfig,- saveConfig, setBranchIdToEdit, statusDefinition, allByColumn);+ saveConfig, setBranchIdToEdit, statusDefinition, allByColumn, filter.keepNote);}const api = apiRef.current.api;// Every member is one of useState's own setters, so this value is built once and never changes@@ -758,6 +761,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC<BoardActionsContext.Provider value={boardActions}><BoardPromotedAttributesContext.Provider value={shownAttributes}><BoardHighlightTokensContext.Provider value={filter.highlightedTokens}>+ <BoardKeptCardsContext.Provider value={filter.keptNoteIds}><BoardDragStateContext.Provider value={boardDragState}>{byColumn && columns && <divref={containerRef}@@ -857,6 +861,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC)}</div>}</BoardDragStateContext.Provider>+ </BoardKeptCardsContext.Provider></BoardHighlightTokensContext.Provider></BoardPromotedAttributesContext.Provider></BoardActionsContext.Provider>diff --git a/apps/client/src/widgets/collections/collection_filter.spec.tsx b/apps/client/src/widgets/collections/collection_filter.spec.tsxindex 3d9045abe0..40692132bd 100644--- a/apps/client/src/widgets/collections/collection_filter.spec.tsx+++ b/apps/client/src/widgets/collections/collection_filter.spec.tsx@@ -116,7 +116,7 @@ describe("useCollectionFilter", () => {searchInSubtree.mockResolvedValue(matchResponse([ "n1", "n2" ]));const note = await mount({});- expect(currentFilter?.matchedNoteIds).toBeNull();+ expect(currentFilter?.shownNoteIds).toBeNull();expect(searchInSubtree).not.toHaveBeenCalled();await act(async () => {@@ -126,7 +126,7 @@ describe("useCollectionFilter", () => {await settle();expect(searchInSubtree).toHaveBeenCalledWith("#done", note.noteId);- expect([ ...(currentFilter?.matchedNoteIds ?? []) ]).toEqual([ "n1", "n2" ]);+ expect([ ...(currentFilter?.shownNoteIds ?? []) ]).toEqual([ "n1", "n2" ]);expect(currentFilter?.highlightedTokens).toEqual([ { token: "match", type: "plain" } ]);await act(async () => {@@ -134,7 +134,7 @@ describe("useCollectionFilter", () => {await flushMicrotasks();});- expect(currentFilter?.matchedNoteIds).toBeNull();+ expect(currentFilter?.shownNoteIds).toBeNull();expect(currentFilter?.highlightedTokens).toBeNull();});@@ -157,7 +157,7 @@ describe("useCollectionFilter", () => {const note = await mount({ persistedQuery: "#done" });expect(searchInSubtree).toHaveBeenCalledWith("#done", note.noteId);- expect(currentFilter?.matchedNoteIds?.has("n1")).toBe(true);+ expect(currentFilter?.shownNoteIds?.has("n1")).toBe(true);});it("holds while a stored query resolves, and not for one submitted afterwards", async () => {@@ -201,6 +201,77 @@ describe("useCollectionFilter", () => {expect(currentFilter?.isResolvingStoredQuery).toBe(false);});+ // Nothing stands outside a filter that is not there, so a note reported while the collection+ // is whole must not come back marked.+ it("keeps nothing while no filter is active", async () => {+ await mount({});++ await act(async () => { currentFilter?.keepNote("made"); });++ expect(currentFilter?.keptNoteIds.size).toBe(0);+ expect(currentFilter?.shownNoteIds).toBeNull();+ });++ /** A note made in a narrowed collection is drawn although the query misses it. */+ it("draws a kept note the query misses, and marks it, until the query changes", async () => {+ vi.useFakeTimers();+ searchInSubtree.mockResolvedValue(matchResponse([ "n1" ]));+ const note = await mount({ collectionNoteIds: [ "n1" ] });++ await act(async () => {+ currentFilter?.setQuery("#done");+ await vi.advanceTimersByTimeAsync(0);+ });+ await act(async () => { currentFilter?.keepNote("made"); });++ expect([ ...(currentFilter?.shownNoteIds ?? []) ]).toEqual([ "n1", "made" ]);+ expect([ ...(currentFilter?.keptNoteIds ?? []) ]).toEqual([ "made" ]);++ // A re-run that still misses it leaves it drawn: it was made here, on this query.+ await act(async () => {+ await parent.handleEvent("entitiesReloaded", {+ loadResults: branchEntitiesReloaded(note.noteId, "made")+ });+ await vi.advanceTimersByTimeAsync(400);+ });+ expect(currentFilter?.shownNoteIds?.has("made")).toBe(true);++ // Another query is asked afresh which notes belong.+ searchInSubtree.mockResolvedValue(matchResponse([ "n2" ]));+ await act(async () => {+ currentFilter?.setQuery("#other");+ await vi.advanceTimersByTimeAsync(0);+ });+ await settle();++ expect([ ...(currentFilter?.shownNoteIds ?? []) ]).toEqual([ "n2" ]);+ expect(currentFilter?.keptNoteIds.size).toBe(0);+ });++ it("stops marking a kept note once the query comes to match it", async () => {+ vi.useFakeTimers();+ searchInSubtree.mockResolvedValue(matchResponse([ "n1" ]));+ const note = await mount({ collectionNoteIds: [ "n1" ] });++ await act(async () => {+ currentFilter?.setQuery("#done");+ await vi.advanceTimersByTimeAsync(0);+ });+ await act(async () => { currentFilter?.keepNote("made"); });+ expect(currentFilter?.keptNoteIds.has("made")).toBe(true);++ searchInSubtree.mockResolvedValue(matchResponse([ "n1", "made" ]));+ await act(async () => {+ await parent.handleEvent("entitiesReloaded", {+ loadResults: branchEntitiesReloaded(note.noteId, "made")+ });+ await vi.advanceTimersByTimeAsync(400);+ });++ expect(currentFilter?.shownNoteIds?.has("made")).toBe(true);+ expect(currentFilter?.keptNoteIds.has("made")).toBe(false);+ });+it("keeps the previous matches when a query comes back with an error", async () => {searchInSubtree.mockResolvedValueOnce(matchResponse([ "n1" ]));await mount({});@@ -219,7 +290,7 @@ describe("useCollectionFilter", () => {await settle();expect(currentFilter?.error).toBe("broken query");- expect([ ...(currentFilter?.matchedNoteIds ?? []) ]).toEqual([ "n1" ]);+ expect([ ...(currentFilter?.shownNoteIds ?? []) ]).toEqual([ "n1" ]);// A good query clears the error and takes over.searchInSubtree.mockResolvedValueOnce(matchResponse([ "n2" ]));@@ -230,7 +301,7 @@ describe("useCollectionFilter", () => {await settle();expect(currentFilter?.error).toBeNull();- expect([ ...(currentFilter?.matchedNoteIds ?? []) ]).toEqual([ "n2" ]);+ expect([ ...(currentFilter?.shownNoteIds ?? []) ]).toEqual([ "n2" ]);});it("lets only the newest run set the result when runs resolve out of order", async () => {@@ -251,7 +322,7 @@ describe("useCollectionFilter", () => {await flushMicrotasks();});- expect([ ...(currentFilter?.matchedNoteIds ?? []) ]).toEqual([ "newer" ]);+ expect([ ...(currentFilter?.shownNoteIds ?? []) ]).toEqual([ "newer" ]);});it("re-runs an active filter, debounced, when a change touches the collection", async () => {@@ -318,10 +389,12 @@ describe("CollectionFilterInput", () => {function mountInput(overrides: Partial<CollectionFilter> = {}) {const filter: CollectionFilter = {query: "",- matchedNoteIds: null,+ shownNoteIds: null,+ keptNoteIds: new Set<string>(),highlightedTokens: null,error: null,isResolvingStoredQuery: false,+ keepNote: vi.fn(),setQuery: vi.fn(),...overrides};diff --git a/apps/client/src/widgets/collections/collection_filter.tsx b/apps/client/src/widgets/collections/collection_filter.tsxindex 8e53e9bb09..7cd12453d9 100644--- a/apps/client/src/widgets/collections/collection_filter.tsx+++ b/apps/client/src/widgets/collections/collection_filter.tsx@@ -28,8 +28,10 @@ const TOOLTIP_CONFIG: Partial<Tooltip.Options> = {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 notes to draw, or null while no filter is active. Matches plus {@link keptNoteIds}. */+ shownNoteIds: Set<string> | null;+ /** Of those, the ones the query does not match, drawn because they were just made here. */+ keptNoteIds: Set<string>;/** 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. */@@ -39,6 +41,8 @@ export interface CollectionFilter {* a stored one: a query submitted later narrows a collection that is already on screen.*/isResolvingStoredQuery: boolean;+ /** Draws a note the query does not match, until the query is changed. */+ keepNote: (noteId: string) => void;setQuery: (query: string) => void;}@@ -48,6 +52,7 @@ interface FilterMatches {}const NO_MATCHES: FilterMatches = { matchedNoteIds: null, highlightedTokens: null };+const NOTHING_KEPT: Set<string> = new Set();/*** Narrows a collection to the notes matching a search query, using the full search syntax.@@ -70,6 +75,9 @@ export function useCollectionFilter(note: FNote, {// matches instead of drawing every note and then taking most of them away.const [ isResolvingStoredQuery, setIsResolvingStoredQuery ] =useState(() => !!persistedQuery?.trim());+ // Notes made in the collection while it is narrowed, drawn until the query changes. A re-run+ // does not take them away: a note made here and not shown would look like nothing happened.+ const [ keptNoteIds, setKeptNoteIds ] = useState(NOTHING_KEPT);// 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);@@ -126,9 +134,11 @@ export function useCollectionFilter(note: FNote, {}}, [ note.noteId, persistedQuery ]);- // Resolve the submitted query, or drop the filter when it is cleared.+ // Resolve the submitted query, or drop the filter when it is cleared. What was kept goes with+ // the query it was kept against: a new one is asked afresh which notes belong.useEffect(() => {window.clearTimeout(rerunTimerRef.current);+ setKeptNoteIds(NOTHING_KEPT);if (!query.trim()) {runSeqRef.current++;setError(null);@@ -150,11 +160,30 @@ export function useCollectionFilter(note: FNote, {useEffect(() => () => window.clearTimeout(rerunTimerRef.current), []);+ // Only what the query does not match, so a note that comes to match it on a later run stops+ // being drawn on sufferance and is no longer marked as outside the filter. Nothing stands+ // outside a filter that is not there, whatever the collection has reported in the meantime.+ const stillKept = useMemo(+ () => (matches.matchedNoteIds+ ? new Set([ ...keptNoteIds ].filter(id => !matches.matchedNoteIds?.has(id)))+ : NOTHING_KEPT),+ [ keptNoteIds, matches.matchedNoteIds ]);+ const shownNoteIds = useMemo(+ () => (matches.matchedNoteIds+ ? new Set([ ...matches.matchedNoteIds, ...stillKept ])+ : null),+ [ matches.matchedNoteIds, stillKept ]);+return {query,- ...matches,+ shownNoteIds,+ keptNoteIds: stillKept,+ highlightedTokens: matches.highlightedTokens,error,isResolvingStoredQuery,+ keepNote: (noteId: string) => setKeptNoteIds(kept => (!query.trim() || kept.has(noteId)+ ? kept+ : new Set(kept).add(noteId))),setQuery: (newQuery: string) => {const trimmed = newQuery.trim();setQuery(trimmed);