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: performance improvements
Adorian Doran45c9da8b26b3
diff --git a/apps/client/src/components/component.spec.ts b/apps/client/src/components/component.spec.tsnew file mode 100644index 0000000000..13a0b4d27b--- /dev/null+++ b/apps/client/src/components/component.spec.ts@@ -0,0 +1,59 @@+import { describe, expect, it, vi } from "vitest";++import Component from "./component.js";++type Handler = (data: unknown) => unknown;++/** Registers `handler` for the `entitiesReloaded` event, which every froca hook subscribes to. */+function register(component: Component, handler: Handler) {+ component.registerHandler("entitiesReloaded" as never, handler);+}++describe("Component handlers", () => {+ it("holds each handler once, drops the one removed, and keeps the rest", () => {+ const component = new Component();+ const first = vi.fn();+ const second = vi.fn();++ register(component, first);+ register(component, first);+ register(component, second);+ component.handleEvent("entitiesReloaded" as never, {} as never);+ expect(first).toHaveBeenCalledTimes(1);+ expect(second).toHaveBeenCalledTimes(1);++ component.removeHandler("entitiesReloaded" as never, first);+ component.handleEvent("entitiesReloaded" as never, {} as never);+ expect(first).toHaveBeenCalledTimes(1);+ expect(second).toHaveBeenCalledTimes(2);++ // Removing what was never registered, and removing the last one twice over, are both+ // no-ops rather than errors: a hook tears down whether or not it ever subscribed.+ expect(() => component.removeHandler("entitiesReloaded" as never, first)).not.toThrow();+ component.removeHandler("entitiesReloaded" as never, second);+ component.handleEvent("entitiesReloaded" as never, {} as never);+ expect(second).toHaveBeenCalledTimes(2);+ });++ it("distributes to the handlers standing when the event went out", () => {+ const component = new Component();+ const late = vi.fn();+ const removed = vi.fn();+ // Subscribing and unsubscribing from inside a handler is what a hook does when an event+ // makes it re-render, so neither may disturb the round it arrived in.+ const first = vi.fn(() => {+ register(component, late);+ component.removeHandler("entitiesReloaded" as never, removed);+ });++ register(component, first);+ register(component, removed);+ component.handleEvent("entitiesReloaded" as never, {} as never);+ expect(removed).toHaveBeenCalledTimes(1);+ expect(late).not.toHaveBeenCalled();++ component.handleEvent("entitiesReloaded" as never, {} as never);+ expect(removed).toHaveBeenCalledTimes(1);+ expect(late).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/client/src/components/component.ts b/apps/client/src/components/component.tsindex 2b9cbc3066..3b3e11cc38 100644--- a/apps/client/src/components/component.ts+++ b/apps/client/src/components/component.ts@@ -21,7 +21,10 @@ export class TypedComponent<ChildT extends TypedComponent<ChildT>> {initialized: Promise<void> | null;parent?: TypedComponent<any>;_position!: number;- private listeners: Record<string, EventHandler[]> | null = {};+ // A set rather than an array: every froca hook re-subscribes whenever its handler changes+ // identity, so a view with thousands of components registers and removes against a list+ // thousands of entries long. Scanning it each time made that quadratic.+ private listeners: Record<string, Set<EventHandler>> | null = {};constructor() {this.componentId = `${this.sanitizedClassName}-${utils.randomString(8)}`;@@ -160,26 +163,22 @@ export class TypedComponent<ChildT extends TypedComponent<ChildT>> {}if (!this.listeners[name]) {- this.listeners[name] = [];+ this.listeners[name] = new Set();}- if (this.listeners[name].includes(handler)) {- return;- }-- this.listeners[name].push(handler);+ this.listeners[name].add(handler);}removeHandler<T extends EventNames>(name: T, handler: EventHandler) {- if (!this.listeners?.[name]?.includes(handler)) {+ const listeners = this.listeners?.[name];+ if (!listeners) {return;}- this.listeners[name] = this.listeners[name]- .filter(listener => listener !== handler);+ listeners.delete(handler);- if (!this.listeners[name].length) {- delete this.listeners[name];+ if (!listeners.size) {+ delete this.listeners?.[name];}}}diff --git a/apps/client/src/services/debug_perf.ts b/apps/client/src/services/debug_perf.tsindex e525f193f5..03dc43f270 100644--- a/apps/client/src/services/debug_perf.ts+++ b/apps/client/src/services/debug_perf.ts@@ -237,7 +237,7 @@ function report() {interface CensusComponent {children: CensusComponent[];/** Handlers registered by `useTriliumEvent`. Private on the component, hence the local shape. */- listeners: Record<string, unknown[]> | null;+ listeners: Record<string, Set<unknown>> | null;}let previousCensus = new Map<string, number>();@@ -273,8 +273,8 @@ function components() {count(`class ${component.constructor.name}`, 1);for (const [ eventName, listeners ] of Object.entries(component.listeners ?? {})) {- handlers += listeners.length;- count(`event ${eventName}`, listeners.length);+ handlers += listeners.size;+ count(`event ${eventName}`, listeners.size);}component.children.forEach(walk);diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex ba3738820c..c0cb1de37c 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -153,7 +153,18 @@ export default function Column({// Cards slide to follow the drop gap opening and closing. No card opens out of nothing: one// made in the footer is shown by the scroll to the end and by its fade, and one made among the// others takes the place its field was standing in.- useFlip(contentRef, { selector: ".board-note" });+ //+ // While a card is carried, only the column it came from and the ones the gap can reach next+ // measure their cards: every column redraws on every step of the gesture, and measuring one+ // forces a layout of the whole board. The neighbours are included because the gap crosses to+ // an adjacent column, and a column measured only once the gap is already in it has no earlier+ // places to slide its cards from.+ const dropColumnIndex = dropPosition ? columns.indexOf(dropPosition.column) : -1;+ useFlip(contentRef, {+ selector: ".board-note",+ disabled: !!draggedCard && column !== draggedCard.fromColumn+ && !(dropColumnIndex >= 0 && Math.abs(columnIndex - dropColumnIndex) <= 1)+ });const { handleDragOver, handleDragLeave, handleDrop } = useDragging({column, columnIndex, columnItems, isEditing, api, parentNote});diff --git a/apps/client/src/widgets/react/flip.spec.tsx b/apps/client/src/widgets/react/flip.spec.tsxindex 58abc072ca..7f5379c740 100644--- a/apps/client/src/widgets/react/flip.spec.tsx+++ b/apps/client/src/widgets/react/flip.spec.tsx@@ -110,13 +110,32 @@ describe("useFlip", () => {expect(second.style.transform).toBe("translateY(-45px)");});- it("says nothing while it is switched off", async () => {- const items = await draw([ "a", "b" ], { disabled: true });+ it("says nothing while it is switched off, and reads no places either", async () => {+ let reads = 0;+ Object.defineProperty(HTMLElement.prototype, "offsetParent", {+ configurable: true,+ get(this: HTMLElement) { reads++; return this.parentElement; }+ });++ const options = { disabled: true };+ const items = await draw([ "a", "b" ], options);+ reads = 0;place(items(), [ 0, 90 ]);await settle();+ expect(reads).toBe(0);+ expect(items()[1].style.transform).toBe("");+ // Switched back on, the first commit only records: where the children stood while nobody+ // was watching is not where they came from.+ options.disabled = false;+ await settle();+ expect(reads).toBeGreaterThan(0);expect(items()[1].style.transform).toBe("");++ place(items(), [ 0, 140 ]);+ await settle();+ expect(items()[1].style.transform).toBe("translateY(-50px)");});describe("opening out what was not there", () => {diff --git a/apps/client/src/widgets/react/flip.ts b/apps/client/src/widgets/react/flip.tsindex 12af7ccef7..a9e38026b8 100644--- a/apps/client/src/widgets/react/flip.ts+++ b/apps/client/src/widgets/react/flip.ts@@ -25,7 +25,7 @@ export interface FlipOptions {* full size. A predicate decides per child, for arrivals already shown some other way.*/grow?: boolean | ((child: HTMLElement) => boolean);- /** Whether to leave the children where the browser puts them. */+ /** Whether to leave the children where the browser puts them, and stop measuring them. */disabled?: boolean;}@@ -76,6 +76,16 @@ export function useFlip(return;}+ // Measured only when a slide can come of it: reading one position forces a layout of the+ // whole document, which on a list of thousands is what this hook costs. The remembered+ // places are dropped with it, since the children can move while they are not being+ // followed and a stale place slides a child that never went anywhere.+ if (disabled) {+ seen.current.clear();+ drawn.current = false;+ return;+ }+const before = seen.current;const now = read();const moved: { child: HTMLElement, by: number }[] = [];@@ -87,7 +97,7 @@ export function useFlip(const child = element as HTMLElement;const previous = before.get(child);- if (disabled || place.at === null) {+ if (place.at === null) {continue;}