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(text): save a Mermaid diagram's last edits when the note saves
Elian Dorana76fd6d340f4
diff --git a/.claude/skills/developing-content-embeds/SKILL.md b/.claude/skills/developing-content-embeds/SKILL.mdindex a90b6cad17..6579470dd4 100644--- a/.claude/skills/developing-content-embeds/SKILL.md+++ b/.claude/skills/developing-content-embeds/SKILL.md@@ -162,6 +162,20 @@ in-place drawings replaced the code blocks the boxes need.## Traps already hit+- **A write held back is part of the note.** `InlineSourceEmbed` writes the source 500 ms after the+ last change. Until then the text note's model does not have it, so a note switch saved the old+ source and `setData()` then dropped the embed, whose later write went to the graveyard. The+ editor hands each held write to `InlineSourceSaves` (`text/attachment_saves.ts`), which marks the+ note changed, and `getData()` in `EditableText` flushes it first — as `AttachmentSaves` does for+ attachments.+- **Non-interactive rendering must be finished when it returns.** A presentation slide snapshots+ `getRenderedContent()` and disposes it at once, so a mounted component that draws in an effect+ leaves it blank. Without `options.interactive`, draw a picture before returning+ (`SourceEmbedType.renderPreview()`, `renderCanvasDrawingPicture()`).+- **Keep the block ID.** A read-only view that swaps the saved element for a box copies+ `data-trilium-block-id` onto it (on the `<pre>`, or the `<code>` of older diagrams), or links to+ the block stop resolving.+- **Content renders detached.** `loadInlineEmbed()` renders into a detached `div` before the boxmounts it, so a hook that looks up `.closest(".include-note")` once finds nothing. Use thehelpers (`useEmbedState()` / `whenInPage()` inside `content_embed_tools.ts`) that wait for thediff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex ab12867a69..8a6055166c 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -40,7 +40,7 @@ import IconPicker from "../../react/IconPicker";import { setEditorNoteId } from "../../react/NoteStore";import { convertImageToDrawing } from "../canvas/image_to_drawing";import { TypeWidgetProps } from "../type_widget";-import AttachmentSaves, { useNoteEditor } from "./attachment_saves";+import AttachmentSaves, { InlineSourceSaves, useNoteEditor } from "./attachment_saves";import CKEditor, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditor";import { getContentEmbedTools } from "./content_embed_tools";import { useEmbedEditors } from "./editable_embed";@@ -101,6 +101,8 @@ export default function EditableText({: undefined));const [ attachmentSaves ] = useState(() =>new AttachmentSaves(() => spacedUpdate.scheduleUpdate()));+ const [ inlineSourceSaves ] = useState(() =>+ new InlineSourceSaves(() => spacedUpdate.scheduleUpdate()));const noteEditor = useNoteEditor(noteContext);const { noteEditor: embedNoteEditor, attachmentEditor: embedAttachmentEditor } =useEmbedEditors({ noteEditor, attachmentEditor: attachmentSaves });@@ -116,6 +118,7 @@ export default function EditableText({return;}+ inlineSourceSaves.flush();const attachments = attachmentSaves.collect();const savedAttachments = attachments.length ? { attachments } : {};if (block !== undefined) {@@ -303,7 +306,7 @@ export default function EditableText({boxSize: string | undefined,options: { isFocused: boolean }) {- return loadInlineEmbed(source, $el, boxSize, options);+ return loadInlineEmbed(source, $el, boxSize, { ...options, saves: inlineSourceSaves });},focusContentEmbed(attachmentId: string) {focusedAttachmentIdRef.current = attachmentId;diff --git a/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsxindex e46de1e637..e15e5a1427 100644--- a/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx@@ -4,6 +4,7 @@ import { act } from "preact/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";import type { SourceEmbedProps } from "../../../services/source_embeds";+import { InlineSourceSaves } from "./attachment_saves";import { createInlineSourceEditor, InlineSourceEmbed } from "./SourceEmbed";/** An inline source as the text editor hands it over, which notifies its listeners on writes. */@@ -66,6 +67,32 @@ describe("createInlineSourceEditor", () => {expect(source.setSource).toHaveBeenCalledOnce();});+ it("marks the note changed while a write waits, and writes it when the note saves", () => {+ vi.useFakeTimers();+ const source = createSource("a");+ const onChange = vi.fn();+ const saves = new InlineSourceSaves(onChange);+ const editor = createInlineSourceEditor(source, saves);++ saves.flush();+ expect(source.setSource).not.toHaveBeenCalled();++ editor.scheduleSave(() => "b");+ expect(onChange).toHaveBeenCalledOnce();+ saves.flush();+ expect(source.setSource).toHaveBeenCalledExactlyOnceWith("b");+ expect(editor.getUnsavedContent()).toBeUndefined();++ vi.advanceTimersByTime(500);+ saves.flush();+ expect(source.setSource).toHaveBeenCalledOnce();++ editor.scheduleSave(() => "c");+ vi.advanceTimersByTime(500);+ saves.flush();+ expect(source.setSource).toHaveBeenCalledTimes(2);+ });+it("cannot edit the source of a read-only text editor", () => {expect(createInlineSourceEditor(createSource("a", true)).canEdit()).toBe(false);});diff --git a/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx b/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsxindex 21e05a7d6a..2d6b8ab7d5 100644--- a/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx@@ -6,6 +6,7 @@ import { useEffect, useMemo, useState } from "preact/hooks";import type FAttachment from "../../../entities/fattachment";import type FNote from "../../../entities/fnote";import type { ContentEditor } from "../../../services/content_renderer";+import type { InlineSourceSaves } from "./attachment_saves";import type { SourceEmbedProps } from "../../../services/source_embeds";import { useSavedContent } from "../code/CodeEmbed";@@ -30,12 +31,14 @@ export default function AttachmentSourceEmbed({interface InlineSourceEmbedProps {source: InlineEmbedSource;component: ComponentType<SourceEmbedProps>;+ /** The writes that the text note saves first. */+ saves?: InlineSourceSaves;}/** The component of a source embed type, over a source kept inline in the text note. */-export function InlineSourceEmbed({ source, component: Component }: InlineSourceEmbedProps) {+export function InlineSourceEmbed({ source, component: Component, saves }: InlineSourceEmbedProps) {const content = useSyncExternalStore(source.subscribe, source.getSource);- const editor = useMemo(() => createInlineSourceEditor(source), [ source ]);+ const editor = useMemo(() => createInlineSourceEditor(source, saves), [ source, saves ]);useEffect(() => () => editor.release(), [ editor ]);return <Component content={content} editor={editor} />;@@ -43,15 +46,20 @@ export function InlineSourceEmbed({ source, component: Component }: InlineSource/*** The editor of a source kept inline, which writes the source into the text note a moment after- * it stops changing, each write one step of the text editor's undo.+ * it stops changing, each write one step of the text editor's undo. Until then `saves` holds the+ * write, so that the text note makes it before it saves.*/-export function createInlineSourceEditor(source: InlineEmbedSource): ContentEditor {+export function createInlineSourceEditor(+ source: InlineEmbedSource,+ saves?: InlineSourceSaves+): ContentEditor {let getPending: (() => string) | undefined;let timeout: ReturnType<typeof setTimeout> | undefined;const flush = () => {clearTimeout(timeout);timeout = undefined;+ saves?.delete(flush);const getContent = getPending;getPending = undefined;if (getContent) {@@ -64,6 +72,7 @@ export function createInlineSourceEditor(source: InlineEmbedSource): ContentEditgetUnsavedContent: () => getPending?.(),scheduleSave(getContent, onSaved) {getPending = getContent;+ saves?.add(flush);clearTimeout(timeout);timeout = setTimeout(() => {flush();diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.tsindex 9e893da157..00b5c70722 100644--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts@@ -224,6 +224,34 @@ export class NoteSaves extends PendingSaves<FNote, SavedNote> implements NoteEdi}}+/**+ * The writes that inline sources, such as Mermaid diagrams, hold back until their source stops+ * changing. The text note saves them into its model first, since they are part of its content.+ */+export class InlineSourceSaves {+ private readonly pending = new Set<() => void>();++ /** @param scheduleUpdate schedules a save of the text note. */+ constructor(private readonly scheduleUpdate: () => void) {}++ /** Holds `write` until {@link flush}, or until the source writes it itself. */+ add(write: () => void) {+ this.pending.add(write);+ this.scheduleUpdate();+ }++ delete(write: () => void) {+ this.pending.delete(write);+ }++ /** Makes the held writes now. */+ flush() {+ for (const write of [ ...this.pending ]) {+ write();+ }+ }+}+/*** Saves the changes that content shown outside a text note, such as a canvas drawing in the full* detail of its attachment, makes to the attachments of `note`.diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex b9ae90b812..1ce58c1ca9 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -12,6 +12,7 @@ import froca from "../../../services/froca";import link, { ViewScope } from "../../../services/link";import { getSourceEmbedTypeByLanguage } from "../../../services/source_embeds";import utils from "../../../services/utils";+import type { InlineSourceSaves } from "./attachment_saves";import { watchContentEmbedTools } from "./content_embed_tools";import ContentEmbed, { getNoteActions, TinyContentEmbed } from "./ContentEmbed";@@ -158,7 +159,7 @@ export async function loadInlineEmbed(source: InlineEmbedSource,$el: JQuery<HTMLElement>,boxSize: string | undefined,- { isFocused }: { isFocused: boolean }+ { isFocused, saves }: { isFocused: boolean; saves?: InlineSourceSaves }) {const type = getSourceEmbedTypeByLanguage(source.language);if (!type) return;@@ -170,7 +171,7 @@ export async function loadInlineEmbed(]);const $renderedContent = $('<div class="rendered-content">');const container = $('<div class="source-embed">').appendTo($renderedContent)[0];- await content_renderer.mountInteractiveWidget(h(InlineSourceEmbed, { source, component }), container);+ await content_renderer.mountInteractiveWidget(h(InlineSourceEmbed, { source, component, saves }), container);const box = h(ContentEmbed, {boxSize: boxSize ?? getEmbedBoxSize(el),