Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: prevent the note to be sent to the server when the outline panel is opened

Adorian Doran4fe3550c1306
diff --git a/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx b/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx
index 8a1dec2030..450f590671 100644
--- a/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx
+++ b/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx
@@ -172,6 +172,22 @@ describe("TableOfContents while an auto-read-only note is temporarily editable",
expect(createRangeIn).toHaveBeenCalledTimes(1);
expect(toc.headings()).toEqual([ "Current" ]);
});
+
+ it("reads the headings without changing the model, and keeps each heading's id", async () => {
+ const toc = await setupUnlockScenario();
+ await toc.unlock();
+ const change = vi.spyOn(toc.editor.editor.model, "change");
+
+ await toc.editor.loadNote(toc.noteId, [ [ 2, "Current" ], [ 2, "Current" ] ]);
+ const [ first, second ] = toc.rows();
+ expect(toc.rows()).toHaveLength(2);
+ await toc.editor.notify();
+
+ expect(change).not.toHaveBeenCalled();
+ expect(toc.rows()).toHaveLength(2);
+ expect(toc.rows()[0]).toBe(first);
+ expect(toc.rows()[1]).toBe(second);
+ });
});
async function setupUnlockScenario() {
@@ -216,6 +232,7 @@ async function setupUnlockScenario() {
noteId: note.noteId,
editor,
headings: () => [ ...container.querySelectorAll(".toc .item-content") ].map((el) => el.textContent),
+ rows: () => [ ...container.querySelectorAll(".toc li") ],
async unlock({ rounds }: { rounds?: number } = {}) {
await act(async () => {
if (noteContext.viewScope) noteContext.viewScope.readOnlyTemporarilyDisabled = true;
@@ -249,8 +266,7 @@ function fakeTextEditor() {
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) }),
+ change: () => {},
createRangeIn: () => ({ getWalker: () => items.map((item) => ({ type: "elementStart", item })) })
},
editing: {
@@ -268,36 +284,37 @@ function fakeTextEditor() {
async loadNote(noteId: string, headings: [ number, string ][], { changes = 1 } = {}) {
items = headings.map(([ level, text ]) => fakeHeadingItem(level, text));
setEditorNoteId(editor, noteId);
- await act(async () => {
- for (let i = 0; i < changes; i++) {
- for (const listener of [ ...listeners ]) listener();
- }
- await new Promise((resolve) => requestAnimationFrame(resolve));
- });
- }
+ await notify(changes);
+ },
+ /** Reports a change that leaves the headings as they are. */
+ notify
};
+
+ async function notify(changes = 1) {
+ await act(async () => {
+ for (let i = 0; i < changes; i++) {
+ 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 937f201916..b7c84b6d29 100644
--- a/apps/client/src/widgets/sidebar/TableOfContents.tsx
+++ b/apps/client/src/widgets/sidebar/TableOfContents.tsx
@@ -208,7 +208,8 @@ export function useActiveHeading<T extends RawHeading>({ headings, scrollingCont
//#endregion
//#region Editable text (CKEditor)
-const TOC_ID = 'tocId';
+/** The id of each heading element, outside the model: reading the headings must not edit the note. */
+const headingIds = new WeakMap<ModelElement, string>();
interface CKHeading extends RawHeading {
element: ModelElement;
@@ -321,59 +322,53 @@ function extractTocFromTextEditor(editor: CKTextEditor) {
const root = editor.model.document.getRoot();
if (!root) return [];
- editor.model.change(writer => {
- for (const { type, item } of editor.model.createRangeIn(root).getWalker()) {
- if (type !== "elementStart" || !item.is('element') || !item.name.startsWith('heading')) continue;
-
- const level = Number(item.name.replace( 'heading', '' ));
-
- // Convert model element to view, then to DOM to get HTML.
- // Math UIElements render their KaTeX content asynchronously, so
- // ck-math-tex spans may be empty at read time. Replace them with
- // math-tex spans (the data format) using the equation from the model,
- // so useMathRendering can render them synchronously in the sidebar.
- const viewEl = editor.editing.mapper.toViewElement(item);
- let text = '';
- if (viewEl) {
- const domEl = editor.editing.view.domConverter.mapViewToDom(viewEl);
- if (domEl instanceof HTMLElement) {
- const clone = domEl.cloneNode(true) as HTMLElement;
- const ckMathSpans = clone.querySelectorAll('.ck-math-tex');
- let mathIdx = 0;
- for (const child of item.getChildren()) {
- if (!child.is('element', 'mathtex-inline')) continue;
- if (mathIdx >= ckMathSpans.length) break;
- const equation = String(child.getAttribute('equation') ?? '');
- const span = document.createElement('span');
- span.className = 'math-tex';
- span.textContent = `\\(${equation}\\)`;
- ckMathSpans[mathIdx].replaceWith(span);
- mathIdx++;
- }
- text = clone.innerHTML;
+ for (const { type, item } of editor.model.createRangeIn(root).getWalker()) {
+ if (type !== "elementStart" || !item.is('element') || !item.name.startsWith('heading')) continue;
+
+ const level = Number(item.name.replace( 'heading', '' ));
+
+ // Convert model element to view, then to DOM to get HTML.
+ // Math UIElements render their KaTeX content asynchronously, so
+ // ck-math-tex spans may be empty at read time. Replace them with
+ // math-tex spans (the data format) using the equation from the model,
+ // so useMathRendering can render them synchronously in the sidebar.
+ const viewEl = editor.editing.mapper.toViewElement(item);
+ let text = '';
+ if (viewEl) {
+ const domEl = editor.editing.view.domConverter.mapViewToDom(viewEl);
+ if (domEl instanceof HTMLElement) {
+ const clone = domEl.cloneNode(true) as HTMLElement;
+ const ckMathSpans = clone.querySelectorAll('.ck-math-tex');
+ let mathIdx = 0;
+ for (const child of item.getChildren()) {
+ if (!child.is('element', 'mathtex-inline')) continue;
+ if (mathIdx >= ckMathSpans.length) break;
+ const equation = String(child.getAttribute('equation') ?? '');
+ const span = document.createElement('span');
+ span.className = 'math-tex';
+ span.textContent = `\\(${equation}\\)`;
+ ckMathSpans[mathIdx].replaceWith(span);
+ mathIdx++;
}
+ text = clone.innerHTML;
}
+ }
- // Fallback to plain text if DOM conversion fails
- if (!text) {
- text = Array.from( item.getChildren() )
- .map( (c: ModelNode) => c.is( '$text' ) ? c.data : '' )
- .join( '' );
- }
-
- // Assign a unique ID
- let tocId = item.getAttribute(TOC_ID) as string | undefined;
- // 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();
- writer.setAttribute(TOC_ID, tocId, item);
- }
+ // Fallback to plain text if DOM conversion fails
+ if (!text) {
+ text = Array.from( item.getChildren() )
+ .map( (c: ModelNode) => c.is( '$text' ) ? c.data : '' )
+ .join( '' );
+ }
- headings.push({ level, text, element: item, id: tocId });
+ let id = headingIds.get(item);
+ if (!id) {
+ id = randomString();
+ headingIds.set(item, id);
}
- });
+
+ headings.push({ level, text, element: item, id });
+ }
return headings;
}