Skip to content

Build your personal knowledge base with Trilium Notes

perf(collections/table): build the rows and columns once on open

Elian Doranaae029a3d210
diff --git a/apps/client/src/widgets/collections/NoteList.tsx b/apps/client/src/widgets/collections/NoteList.tsx
index 77a9cfd679..6819cd76bc 100644
--- a/apps/client/src/widgets/collections/NoteList.tsx
+++ b/apps/client/src/widgets/collections/NoteList.tsx
@@ -273,7 +273,7 @@ export function useNoteIds(note: FNote | null | undefined, viewType: ViewTypeOpt
}
/** Order-sensitive equality for note-id lists, used to skip no-op `noteIds` updates. */
-function sameNoteIds(a: string[], b: string[]) {
+export function sameNoteIds(a: string[], b: string[]) {
return a.length === b.length && a.every((id, index) => id === b[index]);
}
diff --git a/apps/client/src/widgets/collections/table/data.spec.tsx b/apps/client/src/widgets/collections/table/data.spec.tsx
index 7d1017af76..7b7325306b 100644
--- a/apps/client/src/widgets/collections/table/data.spec.tsx
+++ b/apps/client/src/widgets/collections/table/data.spec.tsx
@@ -14,12 +14,15 @@ describe("useData", () => {
let container: HTMLElement;
let handlers: Map<string, (data: unknown) => void>;
let captured: ReturnType<typeof useData> | undefined;
+ /** Every distinct row set and column set the hook has handed out, in order. */
+ let builds: { rows: Set<unknown>; columns: Set<unknown> };
let resetNewAttributePosition: ReturnType<typeof vi.fn<() => void>>;
beforeEach(() => {
vi.clearAllMocks();
handlers = new Map();
captured = undefined;
+ builds = { rows: new Set(), columns: new Set() };
resetNewAttributePosition = vi.fn();
container = document.createElement("div");
document.body.appendChild(container);
@@ -34,6 +37,8 @@ describe("useData", () => {
/** Runs the hook as the table does, under a parent that can hand it a reload. */
function Probe({ note, noteIds, isReadOnly }: { note: FNote; noteIds: string[]; isReadOnly?: boolean }) {
captured = useData(note, noteIds, undefined, { current: undefined }, resetNewAttributePosition, isReadOnly);
+ if (captured.rowData) builds.rows.add(captured.rowData);
+ if (captured.columnDefs) builds.columns.add(captured.columnDefs);
return null;
}
@@ -152,6 +157,34 @@ describe("useData", () => {
expect(captured?.rowData?.map((row) => row.title)).toEqual([ "Task 1", "Task 2" ]);
});
+ it("builds a nested table once, though its note list and its subtree are known only later", async () => {
+ const note = buildNote({
+ title: "Collection",
+ children: [ { title: "Task", children: [ { title: "Subtask" } ] }, { title: "Other" } ]
+ });
+
+ // `useNoteIds()` starts out empty and hands over the list once its search returns.
+ await mount(note, []);
+ await mount(note, [ ...note.children ]);
+
+ expect(builds.rows.size).toBe(1);
+ expect(builds.columns.size).toBe(1);
+ // The subtree keeps the rows from being dragged, and the one column set built knows it.
+ expect(captured?.movableRows).toBe(false);
+ expect(captured?.columnDefs?.[0]).toMatchObject({ title: "#", rowHandle: false });
+ });
+
+ it("rebuilds the rows for a note list that differs from the one it walked", async () => {
+ const { note, noteIds } = collection();
+ await mount(note, noteIds);
+
+ // A search collection's results change without a branch reload; only the list tells.
+ note.children.reverse();
+ await mount(note, [ ...note.children ]);
+
+ expect(captured?.rowData?.map((row) => row.title)).toEqual([ "Task 2", "Task 1" ]);
+ });
+
it("refreshes only the rows for a row change, leaving the columns be", async () => {
const { note, noteIds } = collection();
await mount(note, noteIds);
diff --git a/apps/client/src/widgets/collections/table/data.tsx b/apps/client/src/widgets/collections/table/data.tsx
index 9fcef23413..0c610b58df 100644
--- a/apps/client/src/widgets/collections/table/data.tsx
+++ b/apps/client/src/widgets/collections/table/data.tsx
@@ -8,6 +8,7 @@ import froca from "../../../services/froca";
import { buildColumnDefinitions } from "./columns";
import attributes from "../../../services/attributes";
import { RefObject } from "preact";
+import { sameNoteIds } from "../NoteList";
export interface TableConfig {
tableData: {
@@ -27,10 +28,17 @@ export default function useData(note: FNote, noteIds: string[], viewConfig: Tabl
const [ rowData, setRowData ] = useState<TableData[]>();
const [ hasChildren, setHasChildren ] = useState<boolean>();
const [ isSorted ] = useNoteLabelBoolean(note, "sorted");
- // Derived during render, so that the refresh started on mount already builds the row handle.
- const movableRows = !isReadOnly && !isSorted && note.type !== "search" && !hasChildren;
+ const canMoveRows = !isReadOnly && !isSorted && note.type !== "search";
+ const movableRows = canMoveRows && !hasChildren;
const latestRefreshId = useRef(0);
const columnsPending = useRef(false);
+ // Whether the current columns carry the row handle, which a refresh compares against the
+ // subtree it finds rather than waiting for `hasChildren` to trigger another refresh.
+ const columnsMovable = useRef<boolean | undefined>(undefined);
+ // The children the latest refresh walked, so that the note list arriving after the mount
+ // refresh does not walk the same tree again.
+ const walkedChildren = useRef<string[]>([]);
+ const lastNoteIds = useRef(noteIds);
// Rows change far more often than the columns do, and rebuilding the columns is not free: they
// are replaced wholesale in Tabulator, which resets the scroll — so a refresh only rebuilds
@@ -41,15 +49,15 @@ export default function useData(note: FNote, noteIds: string[], viewConfig: Tabl
async function refresh(rebuildColumns = true) {
const refreshId = ++latestRefreshId.current;
columnsPending.current ||= rebuildColumns;
+ walkedChildren.current = [ ...note.children ];
const info = getAttributeDefinitionInformation(note);
- // Ensure all note IDs are loaded.
- await froca.getNotes(noteIds);
-
const { definitions: rowData, hasSubtree: hasChildren, rowNumber } = await buildRowDefinitions(note, info, includeArchived, maxDepth);
if (refreshId !== latestRefreshId.current) return;
- if (columnsPending.current) {
+ const movableRows = canMoveRows && !hasChildren;
+ if (columnsPending.current || movableRows !== columnsMovable.current) {
columnsPending.current = false;
+ columnsMovable.current = movableRows;
const columnDefs = buildColumnDefinitions({
info,
movableRows,
@@ -70,7 +78,19 @@ export default function useData(note: FNote, noteIds: string[], viewConfig: Tabl
setHasChildren(hasChildren);
}
- useEffect(() => { refresh() }, [ note, noteIds, maxDepth, movableRows, isReadOnly ]);
+ useEffect(() => { refresh() }, [ note, includeArchived, maxDepth, canMoveRows, isReadOnly ]);
+
+ // The rows come from the note's branches, so a new note list only needs a refresh when it
+ // differs from the children the latest refresh walked, such as a search collection run again.
+ useEffect(() => {
+ if (noteIds === lastNoteIds.current) return;
+ lastNoteIds.current = noteIds;
+ const expected = walkedChildren.current.filter((noteId) => noteId !== "_hidden"
+ && (includeArchived || note.type === "search" || !froca.getNoteFromCache(noteId)?.isArchived));
+ if (!sameNoteIds(noteIds, expected)) {
+ refresh(false);
+ }
+ }, [ noteIds ]);
useTriliumEvent("entitiesReloaded", ({ loadResults}) => {
if (glob.device === "print") return;