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/text editor/code embed: stop re-creating the CodeMirror instance when switching between read-only/editing states
Adorian Doran3f3a79d974b9
diff --git a/.claude/skills/developing-content-embeds/SKILL.md b/.claude/skills/developing-content-embeds/SKILL.mdindex 54cacd0d3a..6a66ef9b7d 100644--- a/.claude/skills/developing-content-embeds/SKILL.md+++ b/.claude/skills/developing-content-embeds/SKILL.md@@ -217,15 +217,21 @@ in-place drawings replaced the code blocks the boxes need.element to join the page. `registerContentEmbedTools()` likewise notifies the toolbar only oncethe content is in the page — otherwise an embed auto-selected on load shows the toolbar of anincluded note.-- **CodeMirror's `readOnly` is fixed at creation.** Remount the editor when editability changes- (`key={isEditing ? "editing" : "read-only"}` on `CodeEmbedEditor`). Test with- `EditorView.state.readOnly`, not `contenteditable`, which CodeMirror leaves `true`. A read-only- `CodeEmbedEditor` carries the `read-only` class, which hides the active-line highlight.+- **Switch editability in place, never by remounting.** `CodeMirror.tsx` follows its `readOnly`+ prop through `setReadOnly()`, which keeps the view, its scroll and selection, and starts a new+ undo history. A `key` that remounted `CodeEmbedEditor` on the toggle painted an empty `<pre>` (a+ Full box collapsed) and then CodeMirror's light default until `setTheme()` loaded the theme. An+ embed renders read-only before it finds its figure, so this runs on every editable load too.+ `CodeMirror` keeps the `onContentChanged` it was created with, so `CodeEmbedEditor` reads the+ current `editor` through a ref, and releases it in a layout cleanup as `editor` goes away. Test+ with `EditorView.state.readOnly`, not `contenteditable`, which CodeMirror leaves `true`, and+ assert the view is the same one after the toggle. A read-only `CodeEmbedEditor` carries the+ `read-only` class, which hides the active-line highlight.- **A parent render can run effects ahead of CodeMirror's.** Preact runs a component's pending- effects when it renders again before they flush, so the `setContent` that `onClose` causes as- Editable goes off ran the new `CodeEmbedEditor`'s effects before `CodeMirror` created the view:- no find target, no `onReady`. Its effects wait for the `view` state that `onInitialized` sets;- the content loads in a layout effect, so it paints with the editor.+ effects when it renders again before they flush, which once ran `CodeEmbedEditor`'s effects+ before `CodeMirror` created the view: no find target, no `onReady`. Its effects wait for the+ `view` state that `onInitialized` sets; the content loads in a layout effect, so it paints with+ the editor.- **Box sizes need a title row.** Tiny and Expandable show only the title, so an untitled inlineembed was invisible at Tiny. `INLINE_BOX_SIZES` (Small, Medium, Full) limits the dropdown, thecommand and the ⋮ menu (`getBoxSizes(domElement)`), and other sizes load as Medium. Give eachdiff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsxindex f2da170327..904f046bb1 100644--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx@@ -121,7 +121,7 @@ describe("CodeEmbed", () => {await vi.waitFor(() => expect(view.state.doc.toString()).toBe("print('hi')"));});- it("lets the find search both editors and replace only in the editable one", async () => {+ it("lets the find search the editor, and replace only while it edits", async () => {const { figure } = await mount(buildCodeNote("print(1)\nprint(2)"), buildEditor(), {isEditable: true});@@ -154,37 +154,37 @@ describe("CodeEmbed", () => {delete figure.dataset.editable;await Promise.resolve();});- const readOnlyView = await findView(figure, true);- const readOnlyTarget = getEmbedFindTarget(figure);- if (!(readOnlyTarget instanceof CodeMirrorFindTarget)) {- throw new Error("Expected a code target.");- }- expect(readOnlyTarget).not.toBe(target);- expect(await readOnlyTarget.find("print", { matchCase: false, wholeWord: false })).toBe(1);- expect(await target.find("print", { matchCase: false, wholeWord: false })).toBe(0);- expect(readOnlyTarget.canReplace()).toBe(false);- expect(await readOnlyTarget.replace(0, "log")).toBe(1);- expect(await readOnlyTarget.replaceAll("log")).toBe(1);- expect(readOnlyView.state.doc.toString()).toBe("#print(1)\nlog(2)");+ expect(await findView(figure, true)).toBe(view);+ expect(getEmbedFindTarget(figure)).toBe(target);+ expect(await target.find("print", { matchCase: false, wholeWord: false })).toBe(1);+ expect(target.canReplace()).toBe(false);+ expect(await target.replace(0, "log")).toBe(1);+ expect(await target.replaceAll("log")).toBe(1);+ expect(view.state.doc.toString()).toBe("#print(1)\nlog(2)");});- it("releases the edited content and shows it read-only once the toggle goes off", async () => {+ it("switches the same CodeMirror to editing and back, and releases the edits", async () => {const note = buildCodeNote("a");const editor = buildSavingEditor(note);- const { figure } = await mount(note, editor, { isEditable: true });- const view = await findView(figure);+ const { figure } = await mount(note, editor);+ const view = await findView(figure, true);++ await act(async () => {+ figure.dataset.editable = "true";+ await Promise.resolve();+ });+ expect(await findView(figure)).toBe(view);+ expect(view.state.readOnly).toBe(false);act(() => view.dispatch({ changes: { from: 1, insert: "b" } }));+ expect(editor.getUnsavedContent()).toBe("ab");await act(async () => {delete figure.dataset.editable;await Promise.resolve();});-expect(editor.getUnsavedContent()).toBe("ab");- const readOnlyView = await findView(figure, true);- expect(readOnlyView).not.toBe(view);- expect([ readOnlyView.state.doc.toString(), readOnlyView.state.readOnly ])- .toEqual([ "ab", true ]);+ expect(await findView(figure, true)).toBe(view);+ expect([ view.state.doc.toString(), view.state.readOnly ]).toEqual([ "ab", true ]);expect(figure.querySelectorAll(".cm-editor")).toHaveLength(1);});diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsxindex acc27f7749..c4f253aca7 100644--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx@@ -84,7 +84,6 @@ export default function CodeEmbed({<CaretNavigationContext.Provider value={isEditing ? rootRef : null}><Suspense fallback={null}><CodeEmbedEditor- key={isEditing ? "editing" : "read-only"}note={note}ownerNote={entity instanceof FNote ? entity : entity.getNote()}editor={isEditing ? editor : undefined}diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsxindex af446920ed..6cd35f3e48 100644--- a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx@@ -87,16 +87,33 @@ export default function CodeEmbedEditor({view.clearHistory();}, [ view, content ]);- // A layout cleanup runs during the unmount, before CodeMirror is destroyed.+ // Layout cleanups run as `editor` goes away and during the unmount, before CodeMirror is+ // destroyed, in the order of these hooks.+ useLayoutEffect(() => {+ if (!editor) return;++ return () => {+ const text = viewRef.current?.getText();+ // `release()` reads the pending content through `viewRef`, so the ref clears after it.+ editor.release();+ if (text !== undefined) {+ onClose(text);+ }+ };+ }, [ editor, onClose ]);+useLayoutEffect(() => () => {- const text = viewRef.current?.getText();- // `release()` reads the pending content through `viewRef`, so the ref clears after it.- editor?.release();viewRef.current = null;- if (editor && text !== undefined) {- onClose(text);+ }, []);++ // `CodeMirror` keeps the `onContentChanged` it is created with, which calls the latest one.+ const handleChangeRef = useRef<() => void>(() => {});+ handleChangeRef.current = () => {+ if (editor && !isLoadingRef.current) {+ editor.scheduleSave(() => viewRef.current?.getText() ?? "");+ onChange?.(viewRef.current?.getText() ?? "");}- }, [ editor, onClose ]);+ };return (<CodeEditor@@ -109,12 +126,7 @@ export default function CodeEmbedEditor({readOnly={!editor}lineNumbers={hasLineNumbers}onInitialized={() => setView(viewRef.current)}- onContentChanged={() => {- if (editor && !isLoadingRef.current) {- editor.scheduleSave(() => viewRef.current?.getText() ?? "");- onChange?.(viewRef.current?.getText() ?? "");- }- }}+ onContentChanged={() => handleChangeRef.current()}{...(tabWidth !== undefined && { indentSize: tabWidth })}{...(useTabs !== undefined && { useTabs })}{...(lineWrapping != null && { lineWrapping })}@@ -150,7 +162,6 @@ export function EmbedSourcePane({value={isEditing && isSourceShown ? rootRef : null}><CodeEmbedEditor- key={isEditing ? "editing" : "read-only"}editor={isEditing ? editor : undefined}isShown={isSourceShown}onClose={onContentChange}diff --git a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsxindex d60a98d44f..2da2af8213 100644--- a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx@@ -1,6 +1,6 @@import { EditorConfig, default as VanillaCodeMirror } from "@triliumnext/codemirror";import { Ref } from "preact";-import { useEffect, useRef } from "preact/hooks";+import { useEffect, useLayoutEffect, useRef } from "preact/hooks";import { useSyncedRef } from "../../react/hooks";import { codeCompletions } from "./code_completions";@@ -74,6 +74,11 @@ export default function CodeMirror({ className, content, mime, editorRef: extern// on-screen keyboard is allowed to suggest words.useEffect(() => codeEditorRef.current?.setAllowKeyboardSuggestions(!!allowKeyboardSuggestions), [ allowKeyboardSuggestions ]);+ // React to editability, in the same commit as the change.+ useLayoutEffect(() => {+ codeEditorRef.current?.setReadOnly(!!extraOpts.readOnly);+ }, [ extraOpts.readOnly ]);+// React to line wrapping.useEffect(() => codeEditorRef.current?.setLineWrapping(!!lineWrapping), [ lineWrapping ]);diff --git a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsxindex ca499ac727..f97becc5bd 100644--- a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx+++ b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx@@ -185,8 +185,10 @@ describe("MermaidDiagram", () => {expect(split.figure.querySelector(".mermaid-diagram-controls")).toBeNull();});- it("makes the source editable once Editable turns on", async () => {- const { figure } = await mount({ editor: buildEditor(), displayMode: "split" });+ it("makes the same source editor editable while Editable is on", async () => {+ const editor = buildEditor();+ const { figure } = await mount({ editor, displayMode: "split" });+ const view = await findSourceView(figure);expect(await isSourceEditable(figure)).toBe(false);await act(async () => {@@ -194,6 +196,16 @@ describe("MermaidDiagram", () => {await Promise.resolve();});await vi.waitFor(async () => expect(await isSourceEditable(figure)).toBe(true));+ expect(await findSourceView(figure)).toBe(view);+ act(() => view.dispatch({ changes: { from: 0, insert: "%% " } }));+ expect(editor.scheduleSave).toHaveBeenCalledOnce();++ await act(async () => {+ delete figure.dataset.editable;+ await Promise.resolve();+ });+ expect(await isSourceEditable(figure)).toBe(false);+ expect(await findSourceView(figure)).toBe(view);});it("wraps and numbers the lines of the source as the menu of its embed sets", async () => {diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.tsindex f4af34bacb..be5ac46fe5 100644--- a/packages/codemirror/src/index.spec.ts+++ b/packages/codemirror/src/index.spec.ts@@ -1,4 +1,5 @@import { closeCompletion, completionStatus, startCompletion } from "@codemirror/autocomplete";+import { undo } from "@codemirror/commands";import { indentUnit } from "@codemirror/language";import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";import { EditorView, showTooltip, type ViewUpdate } from "@codemirror/view";@@ -267,6 +268,42 @@ describe("CodeMirror", () => {expect(editor.getText()).toBe("");});+ it("applies a theme it has loaded before without waiting", async () => {+ const theme = getThemeById("github-light");+ expect(theme).not.toBeNull();+ if (!theme) return;+ editor = build();+ await editor.setTheme(theme);+ editor.destroy();++ editor = build();+ void editor.setTheme(theme);+ expect(getGutterRules(editor).join("\n")).toContain("background-color: #f6f8fa;");+ });++ it("switches between read-only and editable in place, with a new history", () => {+ editor = build({ readOnly: true, placeholder: "Type here" });+ const hasPlaceholder = () => !!editor?.dom.querySelector(".cm-placeholder");+ expect(hasPlaceholder()).toBe(false);++ editor.setReadOnly(false);+ expect([ editor.state.readOnly, hasPlaceholder() ]).toEqual([ false, true ]);+ editor.dispatch({ changes: { from: 0, insert: "a" } });+ expect(undo(editor)).toBe(true);+ expect(editor.getText()).toBe("");+ editor.dispatch({ changes: { from: 0, insert: "b" } });++ editor.setReadOnly(true);+ editor.setReadOnly(true);+ expect(editor.state.readOnly).toBe(true);+ editor.insertBlankLineAtTop();+ expect(editor.getText()).toBe("b");++ editor.setReadOnly(false);+ expect(undo(editor)).toBe(false);+ expect(editor.getText()).toBe("b");+ });+it("toggles line wrapping both ways", () => {editor = build();editor.setLineWrapping(true);@@ -369,7 +406,7 @@ describe("CodeMirror", () => {});it("does nothing for a read-only editor", () => {- // A read-only editor has no history compartment to reconfigure.+ // A read-only editor keeps no history.editor = build({ readOnly: true });expect(() => editor?.clearHistory()).not.toThrow();});diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.tsindex 1606de4871..7781dcbc47 100644--- a/packages/codemirror/src/index.ts+++ b/packages/codemirror/src/index.ts@@ -102,6 +102,7 @@ export default class CodeMirror extends EditorView {private config: EditorConfig;private languageCompartment: Compartment;private historyCompartment: Compartment;+ private editabilityCompartment: Compartment;private themeCompartment: Compartment;private lineWrappingCompartment: Compartment;private lineNumbersCompartment: Compartment;@@ -129,6 +130,7 @@ export default class CodeMirror extends EditorView {constructor(config: EditorConfig) {const languageCompartment = new Compartment();const historyCompartment = new Compartment();+ const editabilityCompartment = new Compartment();const themeCompartment = new Compartment();const lineWrappingCompartment = new Compartment();const lineNumbersCompartment = new Compartment();@@ -185,19 +187,11 @@ export default class CodeMirror extends EditorView {];}- extensions.push(EditorView.updateListener.of((v) => this.#onDocumentUpdated(v)));-- if (!config.readOnly) {- // Logic specific to editable notes- if (config.placeholder) {- extensions.push(placeholder(config.placeholder));- }-- extensions.push(historyCompartment.of(history()));- } else {- // Logic specific to read-only notes- extensions.push(EditorState.readOnly.of(true));- }+ extensions.push(+ EditorView.updateListener.of((v) => this.#onDocumentUpdated(v)),+ editabilityCompartment.of(buildEditability(!!config.readOnly, config.placeholder)),+ historyCompartment.of(config.readOnly ? [] : history())+ );super({parent: config.parent,@@ -211,6 +205,7 @@ export default class CodeMirror extends EditorView {this.config = config;this.languageCompartment = languageCompartment;this.historyCompartment = historyCompartment;+ this.editabilityCompartment = editabilityCompartment;this.themeCompartment = themeCompartment;this.lineWrappingCompartment = lineWrappingCompartment;this.lineNumbersCompartment = lineNumbersCompartment;@@ -280,13 +275,35 @@ export default class CodeMirror extends EditorView {}}+ /** Applies `theme`, at once if an editor has loaded it before. */async setTheme(theme: ThemeDefinition) {- const extension = await theme.load();+ let extension = loadedThemes.get(theme);+ if (!extension) {+ extension = await theme.load();+ loadedThemes.set(theme, extension);+ }this.dispatch({effects: [ this.themeCompartment.reconfigure([ extension ]) ]});}+ /**+ * Makes the editor read-only or editable without replacing its view. An editable editor starts+ * a new undo history.+ */+ setReadOnly(isReadOnly: boolean) {+ if (isReadOnly === this.state.readOnly) return;++ this.dispatch({+ effects: [+ this.editabilityCompartment.reconfigure(+ buildEditability(isReadOnly, this.config.placeholder)+ ),+ this.historyCompartment.reconfigure(isReadOnly ? [] : history())+ ]+ });+ }+setLineWrapping(wrapping: boolean) {this.dispatch({effects: [ this.lineWrappingCompartment.reconfigure(wrapping ? EditorView.lineWrapping : []) ]@@ -337,7 +354,7 @@ export default class CodeMirror extends EditorView {* Clears the history of undo/redo. Generally useful when changing to a new document.*/clearHistory() {- if (this.config.readOnly) {+ if (this.state.readOnly) {return;}@@ -414,7 +431,7 @@ export default class CodeMirror extends EditorView {* CodeMirror's `readOnly` facet does not block programmatic transactions.*/insertBlankLineAtTop() {- if (this.config.readOnly) {+ if (this.state.readOnly) {return;}const firstLineEmpty = this.state.doc.line(1).length === 0;@@ -635,6 +652,15 @@ function getTooltipHost() {return host;}+/** The read-only facet, or the placeholder of an editable editor. */+function buildEditability(isReadOnly: boolean, placeholderText: string | undefined): Extension {+ if (isReadOnly) return EditorState.readOnly.of(true);+ return placeholderText ? placeholder(placeholderText) : [];+}++/** The extension of each theme that an editor has loaded. */+const loadedThemes = new WeakMap<ThemeDefinition, Extension>();+/*** Merges the gutter, which still holds the fold markers, into the code area while the line* numbers are off. `Prec.highest` outranks the `.cm-gutters` rule of the color theme.