Skip to content

Build your personal knowledge base with Trilium Notes

fix(toc): keep the outline off the editor's previous note while unlocking

Elian Doran1646c33a3346
diff --git a/apps/client/src/widgets/react/NoteStore.ts b/apps/client/src/widgets/react/NoteStore.ts
index 6f34c6d23f..ceb86b55e2 100644
--- a/apps/client/src/widgets/react/NoteStore.ts
+++ b/apps/client/src/widgets/react/NoteStore.ts
@@ -31,3 +31,18 @@ class NoteSavedDataStore {
}
export const noteSavedDataStore = new NoteSavedDataStore();
+
+/**
+ * The note whose content each live text editor holds. A CKEditor instance is reused across note
+ * switches and across the read-only ↔ editable switch, so a consumer that reads its model (the
+ * sidebar table of contents) has to tell whether what is in it belongs to the note it shows.
+ */
+const editorNoteIds = new WeakMap<object, string>();
+
+export function setEditorNoteId(editor: object, noteId: string) {
+ editorNoteIds.set(editor, noteId);
+}
+
+export function getEditorNoteId(editor: object) {
+ return editorNoteIds.get(editor);
+}
diff --git a/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx b/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx
index b7be45e000..c5da1cb262 100644
--- a/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx
+++ b/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx
@@ -1,9 +1,17 @@
+import type { CKTextEditor } from "@triliumnext/ckeditor5";
import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import appContext from "../../components/app_context";
+import Component from "../../components/component";
+import NoteContext from "../../components/note_context";
+import options from "../../services/options";
+import { buildNote } from "../../test/easy-froca";
import { renderInto } from "../../test/render";
-import { useActiveHeading } from "./TableOfContents";
+import { setEditorNoteId } from "../react/NoteStore";
+import { ParentComponent } from "../react/react_utils";
+import TableOfContents, { useActiveHeading } from "./TableOfContents";
const HEADINGS = [
{ id: "first", level: 1, text: "First" },
@@ -97,3 +105,176 @@ 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;
}
+
+/**
+ * Regression tests for the table of contents while an auto-read-only note is temporarily made
+ * editable ("Edit this note").
+ *
+ * The sidebar swaps its source the instant `readOnlyTemporarilyDisabled` flips: the read-only
+ * extractor (which reads the rendered content element) gives way to the editor one. The note
+ * detail, meanwhile, keeps the CKEditor instance mounted behind the read-only view with the
+ * previously edited note still in it, and hands it this note's content only once the blob
+ * arrives — a wait the auto-read-only threshold guarantees is a long one. Extracting from the
+ * editor in between put the other note's headings in the sidebar, so unlocking a note appeared
+ * to shift its table of contents back to a previous version.
+ */
+describe("TableOfContents while an auto-read-only note is temporarily editable", () => {
+ it("leaves out the headings of the note the reused editor still holds, until it has this note's", async () => {
+ const toc = await setupUnlockScenario();
+
+ // Read-only: the headings come from the rendered content, and are the note's own.
+ expect(toc.headings()).toEqual([ "Current" ]);
+
+ await toc.unlock();
+ expect(toc.headings()).not.toContain("Previously edited note");
+ expect(toc.headings()).toEqual([]);
+
+ // The blob arrives and the note detail loads it into the editor.
+ await toc.editor.loadNote(toc.noteId, [ [ 2, "Current" ], [ 3, "Nested" ] ]);
+ expect(toc.headings()).toEqual([ "Current", "Nested" ]);
+ });
+
+ it("shows the editor's headings straight away when it already holds the note", async () => {
+ const toc = await setupUnlockScenario();
+ await toc.editor.loadNote(toc.noteId, [ [ 2, "Current" ] ]);
+
+ await toc.unlock();
+
+ expect(toc.headings()).toEqual([ "Current" ]);
+ });
+
+ it("picks up a heading typed into the editor before the CKEditor helper import resolves", async () => {
+ // The attribute-change check is loaded lazily, but the change listener itself is attached
+ // synchronously: a `setData()` in between must not go unseen.
+ const toc = await setupUnlockScenario();
+ await toc.unlock({ settleImports: false });
+
+ await toc.editor.loadNote(toc.noteId, [ [ 2, "Typed while loading" ] ]);
+
+ expect(toc.headings()).toEqual([ "Typed while loading" ]);
+ });
+});
+
+async function setupUnlockScenario() {
+ options.load({ rightPaneCollapsedItems: "[]" } as Parameters<typeof options.load>[0]);
+
+ const note = buildNote({ id: "bignote", title: "Big note", type: "text", content: "<h2>Current</h2>" });
+ const noteContext = new NoteContext("toc-ntx");
+ noteContext.noteId = note.noteId;
+ noteContext.notePath = note.noteId;
+ noteContext.viewScope = { viewMode: "default", isReadOnly: true };
+ Object.defineProperty(noteContext, "note", { get: () => note });
+ appContext.tabManager = { getActiveContext: () => noteContext } as typeof appContext.tabManager;
+
+ // What the read-only view has on screen.
+ const contentEl = document.createElement("div");
+ contentEl.innerHTML = "<h2>Current</h2>";
+ document.body.appendChild(contentEl);
+ vi.spyOn(noteContext, "getContentElement").mockResolvedValue($(contentEl));
+
+ // The editor the note detail keeps mounted behind the read-only view, still holding the note
+ // the user edited before navigating here.
+ const editor = fakeTextEditor();
+ await editor.loadNote("othernote", [ [ 2, "Previously edited note" ] ]);
+ vi.spyOn(noteContext, "getTextEditor").mockImplementation(async (callback) => {
+ callback?.(editor.editor);
+ return editor.editor;
+ });
+
+ const parent = new Component();
+ appContext.child(parent);
+ let container!: HTMLElement;
+ await act(async () => {
+ container = renderInto(
+ <ParentComponent.Provider value={parent}>
+ <TableOfContents />
+ </ParentComponent.Provider>
+ );
+ });
+ await settle();
+
+ return {
+ noteId: note.noteId,
+ editor,
+ headings: () => [ ...container.querySelectorAll(".toc .item-content") ].map((el) => el.textContent),
+ async unlock({ settleImports = true } = {}) {
+ await act(async () => {
+ if (noteContext.viewScope) noteContext.viewScope.readOnlyTemporarilyDisabled = true;
+ await appContext.triggerEvent("readOnlyTemporarilyDisabled", { noteContext });
+ });
+ await settle({ settleImports });
+ }
+ };
+}
+
+/** Lets the effects, the lazy `import()` behind them and the extraction's animation frame run. */
+async function settle({ settleImports = true } = {}) {
+ const rounds = settleImports ? 5 : 1;
+ for (let i = 0; i < rounds; i++) {
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+ }
+}
+
+/**
+ * The parts of a CKEditor instance {@link TableOfContents} reads: a model whose walker yields the
+ * headings it was last loaded with, and a `change:data` event for when they are replaced.
+ */
+function fakeTextEditor() {
+ const listeners = new Set<() => void>();
+ let items: FakeHeadingItem[] = [];
+
+ const editor = {
+ model: {
+ document: {
+ getRoot: () => ({}),
+ differ: { getChanges: () => [ { type: "insert" } ] },
+ on: (_event: string, callback: () => void) => listeners.add(callback),
+ off: (_event: string, callback: () => void) => listeners.delete(callback)
+ },
+ change: (callback: (writer: { setAttribute(name: string, value: string, item: FakeHeadingItem): void }) => void) =>
+ callback({ setAttribute: (name, value, item) => item.attrs.set(name, value) }),
+ createRangeIn: () => ({ getWalker: () => items.map((item) => ({ type: "elementStart", item })) })
+ },
+ editing: {
+ mapper: { toViewElement: (item: FakeHeadingItem) => item },
+ view: { domConverter: { mapViewToDom: (viewElement: FakeHeadingItem) => viewElement.el } }
+ }
+ } as unknown as CKTextEditor;
+
+ return {
+ editor,
+ /** Stands in for the note detail feeding the editor a note's content once its blob arrives. */
+ async loadNote(noteId: string, headings: [ number, string ][]) {
+ items = headings.map(([ level, text ]) => fakeHeadingItem(level, text));
+ setEditorNoteId(editor, noteId);
+ await act(async () => {
+ for (const listener of [ ...listeners ]) listener();
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ });
+ }
+ };
+}
+
+interface FakeHeadingItem {
+ name: string;
+ el: HTMLElement;
+ attrs: Map<string, string>;
+ is(type: string, name?: string): boolean;
+ getAttribute(key: string): string | undefined;
+ getChildren(): never[];
+}
+
+function fakeHeadingItem(level: number, text: string): FakeHeadingItem {
+ const el = document.createElement(`h${level}`);
+ el.textContent = text;
+ const attrs = new Map<string, string>();
+
+ return {
+ name: `heading${level}`,
+ el,
+ attrs,
+ is: (type, name) => type === "element" && (!name || name === `heading${level}`),
+ getAttribute: (key) => attrs.get(key),
+ getChildren: () => []
+ };
+}
diff --git a/apps/client/src/widgets/sidebar/TableOfContents.tsx b/apps/client/src/widgets/sidebar/TableOfContents.tsx
index 33eb59cf2f..7e5ebfd14d 100644
--- a/apps/client/src/widgets/sidebar/TableOfContents.tsx
+++ b/apps/client/src/widgets/sidebar/TableOfContents.tsx
@@ -8,6 +8,7 @@ import { t } from "../../services/i18n";
import { randomString } from "../../services/utils";
import { useActiveNoteContext, useContentElement, useGetContextData, useIsNoteReadOnly, useMathRendering, useNoteProperty, useTextEditor } from "../react/hooks";
import Icon from "../react/Icon";
+import { getEditorNoteId } from "../react/NoteStore";
import RawHtml from "../react/RawHtml";
import RightPanelWidget from "./RightPanelWidget";
@@ -213,58 +214,55 @@ interface CKHeading extends RawHeading {
}
function EditableTextTableOfContents() {
- const { noteContext } = useActiveNoteContext();
+ const { note, noteContext } = useActiveNoteContext();
const textEditor = useTextEditor(noteContext);
const [ headings, setHeadings ] = useState<CKHeading[]>([]);
const [ scrollingContainer, setScrollingContainer ] = useState<HTMLElement | null>(null);
- // Subscribe to editor changes once per editor instance — crucially NOT keyed on the
- // active note. The CKEditor instance is reused across note switches within a tab (the
- // content is swapped in via `editor.setData()`, which emits `change:data`), so keying
- // this on the note would tear the listener down and re-attach it on every navigation.
- // Because re-attaching is deferred behind an async `import()`, the `setData()` for the
- // freshly-navigated note — and the `change:data` it emits — can fire during that gap
- // with no listener attached, leaving the sidebar stuck on the previous note's headings
- // (especially for large notes, whose content lands well after the switch). A stable
- // per-editor subscription closes that window: the initial extract handles the first
- // note, and every subsequent note's `setData()` re-extracts through the same listener.
+ // The CKEditor instance is reused across note switches within a tab and across the
+ // read-only ↔ editable switch: the note detail keeps it mounted behind the read-only view
+ // and swaps content in with `editor.setData()`, which emits `change:data`. So the editor
+ // this runs against can still hold the note the user edited before, and does until this
+ // note's blob arrives — a wait the auto-readonly threshold makes a long one.
useEffect(() => {
if (!textEditor) return;
- setHeadings(extractTocFromTextEditor(textEditor));
- // The helper lives in the CKEditor bundle, which is statically heavy but guaranteed
- // to be loaded by now (a text editor instance exists), so resolving it via a dynamic
- // import keeps it out of this component's startup graph.
- let disposed = false;
- let removeListener: (() => void) | undefined;
- void import("@triliumnext/ckeditor5").then(({ attributeChangeAffectsHeading }) => {
- if (disposed) return;
+ // `getEditorNoteId()` says whose content is in the editor. Extracting from another note's
+ // would put its headings in the sidebar; the listener below picks this note's up as soon
+ // as `setData()` lands.
+ if (getEditorNoteId(textEditor) === note?.noteId) {
+ setHeadings(extractTocFromTextEditor(textEditor));
+ }
- const changeCallback = () => {
- const changes = textEditor.model.document.differ.getChanges();
+ // Attached synchronously so no `setData()` can slip past it. Only the attribute check
+ // waits on the CKEditor bundle, which is statically heavy but guaranteed to be loaded by
+ // now (a text editor instance exists); until it resolves, inserts and removals — which is
+ // what `setData()` produces — still come through.
+ let affectsHeading: typeof import("@triliumnext/ckeditor5").attributeChangeAffectsHeading | undefined;
+ void import("@triliumnext/ckeditor5").then(({ attributeChangeAffectsHeading }) => {
+ affectsHeading = attributeChangeAffectsHeading;
+ });
- const affectsHeadings = changes.some( change => {
- return (
- change.type === 'insert' || change.type === 'remove' ||
- (change.type === 'attribute' && attributeChangeAffectsHeading(change, textEditor))
- );
+ const changeCallback = () => {
+ const changes = textEditor.model.document.differ.getChanges();
+
+ const affectsHeadings = changes.some( change => {
+ return (
+ change.type === 'insert' || change.type === 'remove' ||
+ (change.type === 'attribute' && (affectsHeading?.(change, textEditor) ?? false))
+ );
+ });
+ if (affectsHeadings) {
+ requestAnimationFrame(() => {
+ setHeadings(extractTocFromTextEditor(textEditor));
});
- if (affectsHeadings) {
- requestAnimationFrame(() => {
- setHeadings(extractTocFromTextEditor(textEditor));
- });
- }
- };
+ }
+ };
- textEditor.model.document.on("change:data", changeCallback);
- removeListener = () => textEditor.model.document.off("change:data", changeCallback);
- });
+ textEditor.model.document.on("change:data", changeCallback);
- return () => {
- disposed = true;
- removeListener?.();
- };
- }, [ textEditor ]);
+ return () => textEditor.model.document.off("change:data", changeCallback);
+ }, [ textEditor, note?.noteId ]);
useEffect(() => {
if (!textEditor) {
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index a41923b551..c1940cfcec 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -17,6 +17,7 @@ import { consumeSearchTerms } from "../../../services/search_jump";
import toast from "../../../services/toast";
import utils, { isMobile } from "../../../services/utils";
import { useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useSearchTermsConsumer, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import { setEditorNoteId } from "../../react/NoteStore";
import { TypeWidgetProps } from "../type_widget";
import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditorWithWatchdog";
import getTemplates, { updateTemplateCache } from "./snippets.js";
@@ -33,6 +34,8 @@ import { loadIncludedNote, refreshIncludedNote, setupImageOpening } from "./util
export default function EditableText({ note, parentComponent, ntxId, noteContext }: TypeWidgetProps) {
const containerRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<string>("");
+ /** The note `contentRef` holds the content of, so a restarted editor can be marked as holding it. */
+ const contentNoteIdRef = useRef<string>();
const watchdogRef = useRef<EditorWatchdog>(null);
const editorApiRef = useRef<CKEditorApi>(null);
const [ language ] = useNoteLabel(note, "language");
@@ -66,7 +69,12 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
},
onContentChange(newContent) {
contentRef.current = newContent;
- watchdogRef.current?.editor?.setData(newContent);
+ contentNoteIdRef.current = note?.noteId;
+ const editor = watchdogRef.current?.editor;
+ if (editor && note) {
+ setEditorNoteId(editor, note.noteId);
+ }
+ editor?.setData(newContent);
// Jump to the first search match when navigated from search results.
consumeSearchTerms(noteContext, ntxId);
@@ -82,6 +90,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
dataSaved(savedData) {
// Store back the saved data in order to retrieve it in case the CKEditor crashes.
contentRef.current = savedData.content;
+ contentNoteIdRef.current = note?.noteId;
}
});
const templates = useTemplates();
@@ -469,6 +478,9 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
initialized.current.resolve();
// Restore the data, either on the first render or if the editor crashes.
// We are not using CKEditor's built-in watch dog content, instead we are using the data we store regularly in the spaced update (see `dataSaved`).
+ if (contentNoteIdRef.current) {
+ setEditorNoteId(editor, contentNoteIdRef.current);
+ }
editor.setData(contentRef.current);
parentComponent?.triggerEvent("textEditorRefreshed", { ntxId, editor });