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
fix(toc): re-subscribe the active-heading listener when the editor changes
Elian Doran35d225e65db6
diff --git a/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx b/apps/client/src/widgets/sidebar/TableOfContents.spec.tsxnew file mode 100644index 0000000000..b7be45e000--- /dev/null+++ b/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx@@ -0,0 +1,99 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { renderInto } from "../../test/render";+import { useActiveHeading } from "./TableOfContents";++const HEADINGS = [+ { id: "first", level: 1, text: "First" },+ { id: "second", level: 2, text: "Second" }+];++describe("useActiveHeading", () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it("re-subscribes when getHeadingElement changes, even though the container element does not", () => {+ // The editor is swapped (watchdog recovery) while .scrolling-container, an ancestor of the+ // editor root, stays put — so the listener has to follow getHeadingElement, not the container.+ const container = scrollingContainer();+ const probe = mount(container, headingLookup({ first: 0, second: 500 }));+ scroll(container);+ expect(activeOf(probe)).toBe("first");++ update(probe, container, headingLookup({ first: 0, second: 0 }));+ scroll(container);+ expect(activeOf(probe)).toBe("second");+ });++ it("takes the last heading above the line, and clears once the container goes away", () => {+ const container = scrollingContainer();+ const probe = mount(container, headingLookup({ first: 0, second: 0 }));+ scroll(container);+ expect(activeOf(probe)).toBe("second");++ update(probe, null, headingLookup({ first: 0, second: 0 }));+ expect(activeOf(probe)).toBe("");+ });+});++function ActiveHeadingProbe({ container, getHeadingElement }: {+ container: HTMLElement | null;+ getHeadingElement(heading: typeof HEADINGS[number]): HTMLElement | null;+}) {+ const activeHeadingId = useActiveHeading({+ headings: HEADINGS,+ scrollingContainer: container,+ getHeadingElement+ });++ return <div data-active={activeHeadingId ?? ""} />;+}++type HeadingLookup = (heading: typeof HEADINGS[number]) => HTMLElement | null;++function mount(container: HTMLElement | null, getHeadingElement: HeadingLookup) {+ let probe: HTMLElement | undefined;+ act(() => {+ probe = renderInto(<ActiveHeadingProbe container={container} getHeadingElement={getHeadingElement} />);+ });+ if (!probe) throw new Error("probe did not render");+ return probe;+}++function update(probe: HTMLElement, container: HTMLElement | null, getHeadingElement: HeadingLookup) {+ act(() => {+ render(<ActiveHeadingProbe container={container} getHeadingElement={getHeadingElement} />, probe);+ });+}++function scroll(container: HTMLElement) {+ act(() => {+ container.dispatchEvent(new Event("scroll"));+ vi.advanceTimersByTime(100);+ });+}++function activeOf(probe: HTMLElement) {+ return probe.firstElementChild?.getAttribute("data-active");+}++/** happy-dom reports zeroes for every rect, so each element is given the top the test needs. */+function elementAt(top: number) {+ const el = document.createElement("h1");+ el.getBoundingClientRect = () => ({ top }) as DOMRect;+ return el;+}++function scrollingContainer() {+ const container = elementAt(0);+ document.body.appendChild(container);+ return container;+}++/** Stands in for one editor instance: which DOM element each heading currently maps to. */+function headingLookup(tops: Record<string, number>): HeadingLookup {+ const elements = new Map(Object.entries(tops).map(([id, top]) => [id, elementAt(top)]));+ return (heading) => elements.get(heading.id) ?? null;+}diff --git a/apps/client/src/widgets/sidebar/TableOfContents.tsx b/apps/client/src/widgets/sidebar/TableOfContents.tsxindex abc6add389..33eb59cf2f 100644--- a/apps/client/src/widgets/sidebar/TableOfContents.tsx+++ b/apps/client/src/widgets/sidebar/TableOfContents.tsx@@ -62,7 +62,7 @@ function AbstractTableOfContents<T extends RawHeading>({ headings, scrollToHeadiscrollToHeading(heading: T): void;activeHeadingId?: string | null;}) {- const tocRef = useRef<HTMLLIElement>(null);+ const tocRef = useRef<HTMLSpanElement>(null);const nestedHeadings = buildHeadingTree(headings);useEffect(() => {@@ -144,7 +144,7 @@ function buildHeadingTree(headings: RawHeading[]): HeadingsWithNesting[] {return root.children;}-function useActiveHeading<T extends RawHeading>({ headings, scrollingContainer, getHeadingElement }: {+export function useActiveHeading<T extends RawHeading>({ headings, scrollingContainer, getHeadingElement }: {headings: T[];scrollingContainer: HTMLElement | null;getHeadingElement: (heading: T) => HTMLElement | null@@ -196,7 +196,10 @@ function useActiveHeading<T extends RawHeading>({ headings, scrollingContainer,window.clearTimeout(timeoutId);scrollingContainer.removeEventListener("scroll", handleScroll);};- }, [scrollingContainer]);+ // getHeadingElement must re-subscribe the listener: when the watchdog replaces the editor,+ // .scrolling-container is an ancestor of the editor root and stays the same element, so+ // scrollingContainer alone would keep the listener mapping through the destroyed editor.+ }, [scrollingContainer, getHeadingElement]);return activeHeadingId;}@@ -350,9 +353,8 @@ function extractTocFromTextEditor(editor: CKTextEditor) {// Assign a unique IDlet tocId = item.getAttribute(TOC_ID) as string | undefined;- // When pressing Enter inside a heading, CKEditor splits the heading element- // and copies all attributes to the newly created element, which causes tocId- // to be duplicated and may lead to collisions in TOC identity.+ // Splitting a heading with Enter copies its attributes onto the new element, so two+ // headings can carry the same tocId and collide as React keys and as activeHeadingId.const tocIdExists = headings.some(h => h.id === tocId);if (!tocId || tocIdExists) {tocId = randomString();