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(mermaid): save the diagram's picture for every content it shows
Elian Doran68c4babb3718
diff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsxindex 0c0fd6109d..b7f58ac631 100644--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx@@ -3,6 +3,7 @@ import { useEffect } from "preact/hooks";import { act } from "preact/test-utils";import { beforeEach, describe, expect, it, vi } from "vitest";+import server from "../../../services/server";import type { SplitEditorProps } from "./SplitEditor";import SvgSplitEditor from "./SvgSplitEditor";@@ -51,8 +52,11 @@ vi.mock("react-zoom-pan-pinch", async () => {// SplitEditor pulls in CodeMirror, Split.js and a Bootstrap ribbon that have nothing to do with// the pan/zoom behavior under test; stub it down to just the preview pane and the controls over it,// and fire the same `onContentChanged` callback the real editor would once content arrives.+// `loadContent` stands for the editor loading content, as it does when the note is saved elsewhere.+const editor = vi.hoisted(() => ({ loadContent: undefined as ((content: string) => void) | undefined }));vi.mock("./SplitEditor", () => ({default: ({ previewContent, previewButtons, onContentChanged }: SplitEditorProps) => {+ editor.loadContent = onContentChanged;useEffect(() => {onContentChanged?.("gantt\nsection Test\nTask: 2024-01-01, 1d");}, []);@@ -151,6 +155,46 @@ describe("SvgSplitEditor", () => {unmount();container.remove();});++ it("saves the picture of content that the note gets from elsewhere, and of no content at all", async () => {+ const post = vi.spyOn(server, "post").mockResolvedValue(undefined);+ const container = document.createElement("div");+ document.body.appendChild(container);+ const props = {+ ...svgSplitEditorProps(SVG_MARKUP),+ renderSvg: async (content: string) => (+ content.trim() ? `<svg data-source="${content.split("\n")[0]}"/>` : ""+ )+ };+ props.note.getAttachments = async () => [ { title: "gantt-export.svg" } ] as never;++ await act(async () => {+ render(<SvgSplitEditor {...props} />, container);+ });+ await vi.waitFor(() => expect(container.querySelector("svg[data-source='gantt']")).not.toBeNull());+ // The picture of the content that the note opened with is the one it already has.+ await new Promise((resolve) => setTimeout(resolve, 700));+ expect(post).not.toHaveBeenCalled();++ // A sample diagram is written to the note without the editor, which loads it.+ await act(async () => editor.loadContent?.("flowchart LR\nA --> B"));+ await vi.waitFor(() => expect(post).toHaveBeenLastCalledWith(+ "notes/note1/attachments?matchBy=title",+ expect.objectContaining({ title: "gantt-export.svg", content: `<svg data-source="flowchart LR"/>` })+ ));++ // Without content, the picture is empty rather than the last diagram.+ await act(async () => editor.loadContent?.(""));+ await vi.waitFor(() => expect(post).toHaveBeenLastCalledWith(+ "notes/note1/attachments?matchBy=title",+ expect.objectContaining({ content: expect.stringMatching(/^<svg [^>]*><\/svg>$/) })+ ));+ expect(post).toHaveBeenCalledTimes(2);++ act(() => render(null, container));+ container.remove();+ post.mockRestore();+ });});/**diff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsxindex f30194b50c..801205d24e 100644--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx@@ -15,6 +15,11 @@ import { ShortcutHintOverlayButton } from "../../shortcut_hints/shortcut_hint_buimport SplitEditor, { SplitEditorProps } from "./SplitEditor";import { resolveDisplayMode } from "./split_editor_mode";+/** How long the rendered SVG stays the same before it is saved, in ms. */+const SVG_SAVE_DELAY = 500;+/** The picture of a note without content. */+const EMPTY_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>`;+interface SvgSplitEditorProps extends Omit<SplitEditorProps, "previewContent"> {/*** The title of the note attachment used for storing the preview, extension included. Take it from@@ -56,35 +61,53 @@ export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvguseZoomPanWheel(zoom.ref, previewEl);useContextualShortcutHints(mode !== "source" ? ZOOM_PAN_HINTS : []);+ // The SVG that the attachment holds, as far as the editor knows: the first one rendered for the+ // note, which the attachment was saved from, then each one saved.+ const savedSvgRef = useRef<string | undefined>(undefined);+// Reset the render state when switching notes so a previous note's render (and the// "showing last valid render" badge) can't briefly carry over to a different note.- useEffect(reset, [ note.noteId ]);-- // Save as attachment.- const onSave = useCallback(() => {- if (!svg) return; // Don't save if SVG hasn't been rendered yet+ useEffect(() => {+ reset();+ savedSvgRef.current = undefined;+ }, [ note.noteId ]);- const payload = {+ const saveSvg = useCallback((toSave: string) => {+ if (toSave === savedSvgRef.current) return;+ savedSvgRef.current = toSave;+ server.post(`notes/${note.noteId}/attachments?matchBy=title`, {role: "image",title: attachmentTitle,mime: "image/svg+xml",- content: svg,+ content: toSave || EMPTY_SVG,position: 0- };+ });+ }, [ attachmentTitle, note.noteId ]);- server.post(`notes/${note.noteId}/attachments?matchBy=title`, payload);- }, [ svg, attachmentTitle, note.noteId ]);+ // A save of the note saves the SVG at once, which also covers a save as the editor closes.+ const onSave = useCallback(() => {+ if (svg !== undefined) saveSvg(svg);+ }, [ svg, saveSvg ]);- // Save the SVG when entering a note only when it does not have an attachment.+ // The SVG also changes with content that the editor does not save, such as a sample diagram+ // written to the note, so each SVG that differs from the attachment's is saved once it settles.useEffect(() => {- if (!svg) return; // Wait until SVG is rendered-- note?.getAttachments().then((attachments) => {- if (!attachments.find((a) => a.title === attachmentTitle)) {- onSave();- }- }).catch(e => console.error("Failed to get attachments for SVGSplitEditor", e));- }, [ note, svg, attachmentTitle, onSave ]);+ if (svg === undefined) return;+ if (savedSvgRef.current === undefined) {+ savedSvgRef.current = svg;+ // A note made before its pictures were saved has no attachment yet.+ note.getAttachments().then((attachments) => {+ if (!attachments.some((a) => a.title === attachmentTitle)) {+ savedSvgRef.current = undefined;+ saveSvg(svg);+ }+ }).catch(e => console.error("Failed to get attachments for SVGSplitEditor", e));+ return;+ }+ if (readOnly || svg === savedSvgRef.current) return;+ const timer = setTimeout(() => saveSvg(svg), SVG_SAVE_DELAY);+ return () => clearTimeout(timer);+ }, [ svg ]);// Import/export. Exports the `svg` string from `renderSvg()` rather than the on-screen element,// which CSS has sized to the preview pane.