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: fix some issues
Adorian Dorancf47b2adbae1
diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.tsindex 6d2fa1dd87..75fe3a165e 100644--- a/apps/client/src/widgets/collections/board/data.spec.ts+++ b/apps/client/src/widgets/collections/board/data.spec.ts@@ -3,7 +3,9 @@ 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, filterColumnMap, getBoardData } from "./data";+import {+ applyCardMove, type ColumnMap, filterColumnMap, getBoardData, unfilteredCardIndex+} from "./data";describe("applyCardMove", () => {/** Cards named by their note id, which is all this reads them for. */@@ -83,6 +85,41 @@ describe("applyCardMove", () => {expect(filterColumnMap(start, null)).toBe(start);});});++ describe("unfilteredCardIndex", () => {+ const items = (ids: string[]) => board({ A: ids }).get("A") ?? [];++ it("puts the card where the card it was dropped before stands", () => {+ const all = items([ "hidden1", "hidden2", "a1", "hidden3", "a2" ]);+ const shown = items([ "a1", "a2" ]);++ // Before the first card on screen, which stands after two hidden ones.+ expect(unfilteredCardIndex(shown, all, 0)).toBe(2);+ // Between the two on screen, which is where `a2` stands rather than where `hidden3` does.+ expect(unfilteredCardIndex(shown, all, 1)).toBe(4);+ });++ it("puts a card dropped past the last one on screen right after it", () => {+ const all = items([ "a1", "hidden1", "hidden2" ]);+ const shown = items([ "a1" ]);++ expect(unfilteredCardIndex(shown, all, 1)).toBe(1);+ });++ it("counts against the column itself when nothing is filtered out", () => {+ const all = items([ "a1", "a2", "a3" ]);++ for (const index of [ 0, 1, 2 ]) {+ expect(unfilteredCardIndex(all, all, index)).toBe(index);+ }+ expect(unfilteredCardIndex(all, all, 3)).toBe(3);+ });++ it("puts the card at the end of a column showing none of its own", () => {+ expect(unfilteredCardIndex([], items([ "hidden1" ]), 0)).toBe(1);+ expect(unfilteredCardIndex([], [], 0)).toBe(0);+ });+ });});describe("Board data", () => {diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex 652dcbebf3..6b3a071ff9 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -3,10 +3,12 @@ import FNote from "../../../entities/fnote";import { INBOX_COLUMN, resolveBoardColumns } from "./columns";import { BoardColumnData, BoardViewData } from "./index";-export type ColumnMap = Map<string, {+export interface ColumnItem {branch: FBranch;note: FNote;-}[]>;+}++export type ColumnMap = Map<string, ColumnItem[]>;/*** The columns as they stand once a card has moved, for drawing the outcome before the writes land.@@ -61,6 +63,33 @@ export function filterColumnMap(return filtered;}+/**+ * Where a card dropped among the cards on screen goes in the full column.+ *+ * A drop is measured against the cards a filter leaves showing, and the move is written against the+ * visible card it was dropped before. That card decides the place in the full column too, so the+ * cards a filter hides keep their order around it.+ *+ * @param shown the target column as it is drawn, counting the moved card where it stays in place.+ * @param all the same column with every card it holds.+ * @param index where the card goes among the ones drawn.+ */+export function unfilteredCardIndex(shown: ColumnItem[], all: ColumnItem[], index: number) {+ const placeOf = (item: ColumnItem | undefined) => (item+ ? all.findIndex(other => other.branch.branchId === item.branch.branchId)+ : -1);++ const before = placeOf(shown[index]);+ if (before >= 0) {+ return before;+ }++ // Dropped past the last card on screen, which is what the move is written against; a hidden+ // card below it stays below.+ const after = placeOf(shown.at(-1));+ return after >= 0 ? after + 1 : all.length;+}+/*** @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.cssindex 7c89b93edc..64083bfa6f 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -391,6 +391,14 @@ body.mobile .board-view-container .board-add-column {.board-view-container .board-note > .title {display: flex;align-items: flex-start;++ /* The spans mark.js wraps a filter's matched tokens in. Matches the search result cards. */+ .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 > .title > .icon {@@ -405,14 +413,6 @@ body.mobile .board-view-container .board-add-column {var(--card-title-inset) - var(--card-icon-inset) - var(--card-icon-size));}-/* 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);- 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.tsxindex 1c6b15d3d5..10023c9161 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -3306,8 +3306,10 @@ describe("the promoted attributes a card shows", () => {describe("Board filtering", () => {let container: HTMLElement;+ let host: Component;afterEach(() => {+ vi.useRealTimers();saved.length = 0;render(null, container);container.remove();@@ -3338,10 +3340,11 @@ describe("Board filtering", () => {]});+ host = new Component();container = document.body.appendChild(document.createElement("div"));await act(async () => {render(- <ParentComponent.Provider value={new Component()}>+ <ParentComponent.Provider value={host}><Harnessnote={note}noteIds={[ ...note.getChildNoteIds() ]}@@ -3367,6 +3370,17 @@ describe("Board filtering", () => {.map(el => el.textContent);}+ /** A branch change under the board, which is what re-runs an active filter. */+ function branchChange(parentNoteId: string, noteId: string) {+ const results = new LoadResults([ {+ entityName: "branches",+ entityId: "branch1",+ entity: { branchId: "branch1", parentNoteId, noteId }+ } as never ]);+ results.addBranch("branch1", "other");+ return results;+ }+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: [ "filtered3", "filtered1" ] });@@ -3386,6 +3400,32 @@ describe("Board filtering", () => {expect(column?.classList.contains("over-limit")).toBe(true);});+ /**+ * The cards drawn are derived from what the filter matches rather than held beside it, so a+ * re-run's answer cannot be left unapplied by whatever else the board is doing at the time.+ */+ it("draws what a re-run matches", async () => {+ const note = await setup({ matched: [ "filtered1" ] });+ expect(cardTitles(0)).toEqual([ "First" ]);++ searchInSubtree.mockResolvedValue({+ searchResultNoteIds: [ "filtered2", "filtered3" ],+ highlightedTokens: [],+ error: null+ });++ // A change under the board re-runs the filter, after the wait that collects a run of them.+ vi.useFakeTimers();+ await act(async () => {+ await host.handleEvent("entitiesReloaded", {+ loadResults: branchChange(note.noteId, "filtered2")+ });+ await vi.advanceTimersByTimeAsync(400);+ });++ expect(cardTitles(0)).toEqual([ "Second", "Third" ]);+ });+it("marks the matched tokens in the card titles", async () => {await setup({matched: [ "filtered1" ],diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex feb470755b..2b89faec92 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -48,7 +48,9 @@ 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, filterColumnMap, getBoardData } from "./data";+import {+ applyCardMove, ColumnMap, filterColumnMap, getBoardData, unfilteredCardIndex+} from "./data";import { useBoardKeyboard } from "./keyboard";/**@@ -267,8 +269,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCconst [ statusAttributeWithPrefix ] = useNoteLabelWithDefault(parentNote, "board:groupBy", DEFAULT_GROUP_BY);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. */+ /** Every card the board holds, which an active filter narrows before the cards are drawn. */const [ allByColumn, setAllByColumn ] = useState<ColumnMap>();const [ columns, setColumns ] = useState<string[]>();const [ isInRelationMode, setIsRelationMode ] = useState(false);@@ -342,6 +343,19 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// them for a move that touched one. Another board takes a new one, since this instance is// reused across boards and the api holds that board's record of the writes in flight.const apiRef = useRef<{ board: string, api: Api }>();+ const persistFilterQuery = useCallback(+ (query: string) => apiRef.current?.api.setFilterQuery(query), []);+ const filter = useCollectionFilter(parentNote, {+ persistedQuery: viewConfig?.filterQuery,+ onQueryChanged: persistFilterQuery,+ collectionNoteIds: noteIds+ });+ // The cards as drawn. Derived rather than held, so that what is shown cannot fall behind what+ // the filter matches: a card move and a search resolving in the same moment both land here.+ const byColumn = useMemo(+ () => allByColumn && filterColumnMap(allByColumn, filter.matchedNoteIds),+ [ allByColumn, filter.matchedNoteIds ]);+if (!apiRef.current || apiRef.current.board !== boardIdentity) {apiRef.current = {board: boardIdentity,@@ -356,17 +370,6 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCsaveConfig, 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) => {@@ -487,7 +490,9 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCgetBoardData(parentNote, statusAttributeWithPrefix, viewConfig ?? {}, includeArchived,statusDefinition?.options ?? [], pendingRenamesRef.current.writes.renames, inboxEnabled)- .then(({ byColumn, columns, newPersistedData, isInRelationMode, settledRenames }) => {+ .then(({+ byColumn: allCards, columns, newPersistedData, isInRelationMode, settledRenames+ }) => {if (refreshId !== refreshSeqRef.current) {return;}@@ -496,8 +501,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCsettleColumn(pendingRenamesRef.current.writes, settled);}- setAllByColumn(byColumn);- setByColumn(filterColumnMap(byColumn, matchedNoteIdsRef.current));+ setAllByColumn(allCards);setIsRelationMode(isInRelationMode);setColumns(columns);@@ -564,11 +568,17 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC},onCardEnd: (card, position) => {const branchId = byColumn?.get(card.fromColumn)?.[card.index]?.branch.branchId;- if (position && branchId && byColumn) {+ if (position && branchId && byColumn && allByColumn) {// Drawn where it landed at once, and held there until both writes are in: each of// them lands a redraw, and the first would show the card at the top of the column.- setByColumn(applyCardMove(- byColumn, card.noteId, card.fromColumn, position.column, position.index));+ // Written into the full column, which is what the cards are drawn from, at the+ // place the move is written against rather than the one it was dropped at.+ setAllByColumn(applyCardMove(+ allByColumn, card.noteId, card.fromColumn, position.column,+ unfilteredCardIndex(+ byColumn.get(position.column) ?? [],+ allByColumn.get(position.column) ?? [],+ position.index)));movesInFlight.current++;// Any refresh already on its way is about the board as it stood before the drop,// and would put the card back where it came from as it resolves.@@ -684,15 +694,6 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCparentNote, 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.