Skip to content

Build your personal knowledge base with Trilium Notes

fix(widgets): unmount a React widget's Preact tree on cleanup

Elian Doran5db8eb84c4bb
diff --git a/apps/client/src/services/debug_perf.ts b/apps/client/src/services/debug_perf.ts
index ee66cc08a1..97b096a729 100644
--- a/apps/client/src/services/debug_perf.ts
+++ b/apps/client/src/services/debug_perf.ts
@@ -6,10 +6,11 @@
* normal use. Drive it from the devtools console:
*
* ```js
- * triliumPerf.enable(); // start recording; also logs every long task as it happens
- * triliumPerf.report(); // print what has been gathered so far
- * triliumPerf.reset(); // clear the counters, keep recording
+ * triliumPerf.enable(); // start recording; also logs every long task as it happens
+ * triliumPerf.report(); // print what has been gathered so far
+ * triliumPerf.reset(); // clear the counters, keep recording
* triliumPerf.disable();
+ * triliumPerf.components(); // census the widget tree, for hunting leaked widgets
* ```
*
* Spans additionally land on the User Timing track via `performance.measure()`, so a DevTools
@@ -226,7 +227,71 @@ function report() {
console.table(rows);
}
-const triliumPerf = { enable, disable, reset, report };
+/** The parts of a `Component` the census reads, so that this module doesn't have to import one. */
+interface CensusComponent {
+ children: CensusComponent[];
+ /** Handlers registered by `useTriliumEvent`. Private on the component, hence the local shape. */
+ listeners: Record<string, unknown[]> | null;
+}
+
+let previousCensus = new Map<string, number>();
+
+/**
+ * Prints how many components are reachable from the root of the widget tree, and how many React
+ * event handlers they hold, broken down by class and by event.
+ *
+ * For hunting leaks of the "the tab was closed but its widgets kept handling events" kind: take a
+ * reading, open and close a few tabs, take another. The `since last` column is what matters --
+ * anything that doesn't come back down stayed in the tree. `NoteWrapperWidget` should always equal
+ * the number of open splits.
+ *
+ * Independent of `enable()`: it walks live state rather than anything that had to be recorded.
+ */
+function components() {
+ const root = window.glob?.appContext as unknown as CensusComponent | undefined;
+ if (!root) {
+ console.log("[perf] no appContext to walk (is the app still starting up?).");
+ return;
+ }
+
+ const counts = new Map<string, number>();
+ let total = 0;
+ let handlers = 0;
+
+ function count(key: string, by: number) {
+ counts.set(key, (counts.get(key) ?? 0) + by);
+ }
+
+ (function walk(component: CensusComponent) {
+ total++;
+ count(`class ${component.constructor.name}`, 1);
+
+ for (const [ eventName, listeners ] of Object.entries(component.listeners ?? {})) {
+ handlers += listeners.length;
+ count(`event ${eventName}`, listeners.length);
+ }
+
+ component.children.forEach(walk);
+ })(root);
+
+ const rows = [ ...counts.entries() ]
+ .map(([ what, count ]) => ({ what, count, "since last": count - (previousCensus.get(what) ?? 0) }))
+ .sort((a, b) => b["since last"] - a["since last"] || b.count - a.count);
+
+ // Anything gone since the last reading has no row of its own, so surface it as a negative one.
+ for (const [ what, count ] of previousCensus) {
+ if (!counts.has(what)) {
+ rows.push({ what, count: 0, "since last": -count });
+ }
+ }
+
+ previousCensus = counts;
+
+ console.log(`[perf] ${total} components, ${handlers} React handlers reachable from the root`);
+ console.table(rows);
+}
+
+const triliumPerf = { enable, disable, reset, report, components };
export default triliumPerf;
window.triliumPerf = triliumPerf;
diff --git a/apps/client/src/widgets/basic_widget.ts b/apps/client/src/widgets/basic_widget.ts
index 0d515b38a3..d86cb884cf 100644
--- a/apps/client/src/widgets/basic_widget.ts
+++ b/apps/client/src/widgets/basic_widget.ts
@@ -5,7 +5,7 @@ import froca from "../services/froca.js";
import { t } from "../services/i18n.js";
import toastService, { showErrorForScriptNote } from "../services/toast.js";
import { randomString } from "../services/utils.js";
-import { renderReactWidget } from "./react/react_utils.jsx";
+import { disposeReactWidget, renderReactWidgetAtElement } from "./react/react_utils.jsx";
export class TypedBasicWidget<T extends TypedComponent<any>> extends TypedComponent<T> {
protected attrs: Record<string, string>;
@@ -275,6 +275,11 @@ export function wrapReactWidgets<T extends TypedComponent<any>>(components: (T |
export class ReactWrappedWidget extends BasicWidget {
private el: VNode;
+ /**
+ * The Preact root. Kept because `$widget` is only the rendered children, which have since been
+ * moved into the widget tree -- unmounting needs the container they were rendered into.
+ */
+ private container?: DocumentFragment;
constructor(el: VNode) {
super();
@@ -282,7 +287,20 @@ export class ReactWrappedWidget extends BasicWidget {
}
doRender() {
- this.$widget = renderReactWidget(this, this.el);
+ this.container = new DocumentFragment();
+ this.$widget = renderReactWidgetAtElement(this, this.el, this.container).children();
+ }
+
+ /**
+ * Called when the widget is taken out of the tree (a closed split, an unmounted `useWidget`).
+ * Without this the Preact tree stays mounted for the lifetime of the page: no effect cleanup
+ * runs, and it keeps holding the DOM it rendered.
+ */
+ cleanup() {
+ if (this.container) {
+ disposeReactWidget(this.container);
+ this.container = undefined;
+ }
}
}
diff --git a/apps/client/src/widgets/containers/split_note_container.spec.ts b/apps/client/src/widgets/containers/split_note_container.spec.tsx
similarity index 64%
rename from apps/client/src/widgets/containers/split_note_container.spec.ts
rename to apps/client/src/widgets/containers/split_note_container.spec.tsx
index bbc3f089cf..7beb7f51d0 100644
--- a/apps/client/src/widgets/containers/split_note_container.spec.ts
+++ b/apps/client/src/widgets/containers/split_note_container.spec.tsx
@@ -1,3 +1,4 @@
+import { useLayoutEffect } from "preact/hooks";
import { beforeEach, describe, expect, it, vi } from "vitest";
import appContext from "../../components/app_context";
@@ -22,8 +23,8 @@ describe("SplitNoteContainer", () => {
} as unknown as TabManager;
});
- async function openSplits(ntxIds: string[]) {
- const container = new SplitNoteContainer(() => new NoteWrapperWidget());
+ async function openSplits(ntxIds: string[], widgetFactory = () => new NoteWrapperWidget()) {
+ const container = new SplitNoteContainer(widgetFactory);
container.render();
for (const ntxId of ntxIds) {
@@ -53,4 +54,30 @@ describe("SplitNoteContainer", () => {
expect(closedHandler).not.toHaveBeenCalled();
expect(container.children).toHaveLength(1);
});
+
+ it("unmounts the React widgets of a split once its tab is closed", async () => {
+ let isMounted = false;
+
+ function Probe() {
+ // A layout effect rather than useEffect: it runs during the commit, so the probe is
+ // mounted by the time render() returns, with no scheduled work to flush first.
+ useLayoutEffect(() => {
+ isMounted = true;
+ return () => { isMounted = false; };
+ }, []);
+
+ return <div className="probe" />;
+ }
+
+ const container = await openSplits(
+ [ "split-a" ],
+ () => new NoteWrapperWidget().child(<Probe />));
+ expect(isMounted).toBe(true);
+
+ container.noteContextRemovedEvent({ ntxIds: [ "split-a" ] });
+
+ // Detaching the widget stops the events; only unmounting releases the Preact tree and the
+ // DOM it still points at.
+ expect(isMounted).toBe(false);
+ });
});
diff --git a/apps/client/src/widgets/react/react_utils.tsx b/apps/client/src/widgets/react/react_utils.tsx
index 5c2c56122f..11a90e4cb7 100644
--- a/apps/client/src/widgets/react/react_utils.tsx
+++ b/apps/client/src/widgets/react/react_utils.tsx
@@ -47,7 +47,12 @@ export function renderReactWidgetAtElement(parentComponent: Component | null, el
return $(container) as JQuery<HTMLElement>;
}
-export function disposeReactWidget(container: Element) {
+/**
+ * Unmounts the tree rendered into `container`, running every effect cleanup and releasing the DOM
+ * the vnodes still point at. `container` has to be the element the tree was rendered *into* -- for a
+ * widget built by `renderReactWidget()` that is the fragment, not the `$widget` it returned.
+ */
+export function disposeReactWidget(container: Element | DocumentFragment) {
render(null, container);
}