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/transclusion: fix some issues
Adorian Doran5a866789320a
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsxindex e5a4e7ba20..1f0abb7b90 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx@@ -149,14 +149,46 @@ describe("TextEmbed", () => {// A save made before the editor closed lands while its last save runs.note.getBlob = async () => buildBlob("<p>Typed</p>");- const earlierSave = new LoadResults([]);- earlierSave.addNoteContent(note.noteId, "other-component");await act(async () => {- await appContext.handleEvent("entitiesReloaded", { loadResults: earlierSave });+ await reloadNoteContent(note);await new Promise((resolve) => setTimeout(resolve, 50));});expect(shownPreview()).toBe("<div><p>Typed just now</p></div>");expect(renderPreview).toHaveBeenCalledExactlyOnceWith("<p>Typed just now</p>");++ // Once the last save lands, the preview follows what the note holds.+ note.getBlob = async () => buildBlob("<p>Saved</p>");+ await act(async () => {+ finishSave();+ });+ await vi.waitFor(() => expect(shownPreview()).toBe("<div><p>Saved</p></div>"));+ });++ it("lets another include of the note follow its saves while an editor closes", async () => {+ const note = buildTextNote("shared");+ let finishSave = () => {};+ editorAskedToSave.mockImplementationOnce(() => new Promise<void>((resolve) => {+ finishSave = resolve;+ }));+ const { figure: edited } = await mount(note, buildEditor(), { isEditable: true });+ const { figure: other } = await mount(note, buildEditor());+ await vi.waitFor(() => {+ expect(edited.querySelector(".editable-text-stub")).not.toBeNull();+ }, { timeout: 5000 });++ editorData = "<p>Final</p>";+ await act(async () => {+ delete edited.dataset.editable;+ await Promise.resolve();+ });+ note.getBlob = async () => buildBlob("<p>Final</p>");+ await act(async () => {+ await reloadNoteContent(note);+ });+ await vi.waitFor(() => {+ expect(other.querySelector(".editable-embed-preview")?.innerHTML)+ .toBe("<div><p>Final</p></div>");+ });await act(async () => {finishSave();});@@ -266,6 +298,13 @@ function buildEditor(): ContentEditor {};}+/** Announces a save of the content of `note`, as the server does. */+async function reloadNoteContent(note: FNote) {+ const loadResults = new LoadResults([]);+ loadResults.addNoteContent(note.noteId, "other-component");+ await appContext.handleEvent("entitiesReloaded", { loadResults });+}+function buildBlob(content: string) {return new FBlob({blobId: `blob-${content}`,diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsxindex a2b417e1fd..64ff4adec4 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx@@ -1,5 +1,5 @@import { lazy } from "preact/compat";-import { useEffect, useRef, useState } from "preact/hooks";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";import type FNote from "../../../entities/fnote";import type { ContentEditor } from "../../../services/content_renderer";@@ -36,15 +36,7 @@ export default function TextEmbed({note,focusTarget: ".ck-editor__editable"});- const [ content, setContent ] = useState(initialContent);- const blob = useNoteBlob(note);- // While the last save of the editor runs, the preview shows what the editor held, rather than- // what an earlier save stored.- useEffect(() => {- if (blob && !getClosingSave(note.noteId)) {- setContent(blob.content);- }- }, [ blob ]);+ const [ content, onEditorClose ] = useShownContent(note, initialContent);const shownPreview =useEmbedPreview(preview, content, () => renderPreview(content), isEditing);@@ -58,12 +50,46 @@ export default function TextEmbed({<TextEmbedEditornote={note}hasFixedToolbar={isEditing && hasFixedToolbarAround(rootRef.current)}- onClose={setContent}+ onClose={onEditorClose}/></EditableEmbedContent>);}+/**+ * The content of `note` to preview: the content of the editor of the embed as it closed, until its+ * last save lands, and otherwise the content that each save of the note stores. Returns that+ * content, and the callback that takes the content of the closing editor and its save.+ */+function useShownContent(note: FNote, initialContent: string) {+ const [ content, setContent ] = useState(initialContent);+ const closingSaveRef = useRef<Promise<void> | undefined>(undefined);+ const blob = useNoteBlob(note);++ // An earlier save that lands while the last save runs stores older content.+ useEffect(() => {+ if (blob && !closingSaveRef.current) {+ setContent(blob.content);+ }+ }, [ blob ]);++ const onEditorClose = useCallback((editorContent: string, save: Promise<void>) => {+ setContent(editorContent);+ closingSaveRef.current = save;+ void save+ .then(() => (closingSaveRef.current === save ? note.getBlob() : undefined))+ .then((saved) => {+ if (closingSaveRef.current !== save) return;+ closingSaveRef.current = undefined;+ if (saved) {+ setContent(saved.content);+ }+ });+ }, [ note ]);++ return [ content, onEditorClose ] as const;+}+/** The last saves of the editors of included notes that went away, by note ID, until they land. */const closingSaves = new Map<string, Promise<void>>();@@ -83,6 +109,7 @@ export function trackClosingSave(noteId: string, save: Promise<unknown> | null)}});closingSaves.set(noteId, tracked);+ return tracked;}/** The last save of an editor of `noteId` that went away, while it runs. */diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsxindex aa60d4d028..a36a672b8f 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx@@ -18,8 +18,11 @@ interface TextEmbedEditorProps {note: FNote;/** Whether the editor around the embed has a fixed toolbar, rather than a floating one. */hasFixedToolbar: boolean;- /** Receives the content of the editor as it goes away, which can be unsaved yet. */- onClose(content: string): void;+ /**+ * Receives the content of the editor as it goes away, which can be unsaved yet, and the save+ * of what is left.+ */+ onClose(content: string, save: Promise<void>): void;}/**@@ -44,10 +47,10 @@ export default function TextEmbedEditor({ note, hasFixedToolbar, onClose }: Text// A layout cleanup runs while the editor is still mounted, so it saves what is left.useLayoutEffect(() => () => {- trackClosingSave(note.noteId, announceEmbeddedNoteClosing(component, ntxId));+ const save = trackClosingSave(note.noteId, announceEmbeddedNoteClosing(component, ntxId));const content = findTextEditorIn(rootRef.current)?.getData();if (content !== undefined) {- onCloseRef.current(content);+ onCloseRef.current(content, save);}}, [ component, ntxId ]);diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.tsindex 5f328eba57..ba4e8a8f31 100644--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts@@ -192,6 +192,19 @@ describe("NoteSaves", () => {expect(saves.getUnsavedContent("code2")).toBeUndefined();});+ it("keeps a change made while a retry of an earlier save runs", () => {+ const saves = new NoteSaves(vi.fn(), "host");+ const note = buildCodeNote("code1");+ saves.scheduleSave(note, () => "first");+ const sent = saves.collect();+ saves.markSaved(sent);++ // The batch is retried, as after another note of it failed, while the note changes.+ saves.scheduleSave(note, () => "typed during the retry");+ saves.markSaved(sent);+ expect(saves.getUnsavedContent("code1")).toBe("typed during the retry");+ });+it("tracks the save state of each note, and tells its listeners", async () => {const saves = new NoteSaves(vi.fn(), "host");const listener = vi.fn();diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.tsindex 83ba4dee31..bf2ccf9d39 100644--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts@@ -23,7 +23,10 @@ interface PendingSave<T> {getContent?: () => string;/** The content read when the editor went away. */content?: string;- /** Counts the changes, so that a save keeps the changes made while it ran. */+ /**+ * Numbers the change, uniquely among all changes, so that a save drops only the change it+ * sent, also when it is retried.+ */revision: number;}@@ -33,6 +36,7 @@ interface PendingSave<T> {*/abstract class PendingSaves<T, I extends object> {protected pending = new Map<string, PendingSave<T>>();+ private lastRevision = 0;private sentRevisions = new WeakMap<I, { id: string; revision: number }>();getUnsavedContent(id: string) {@@ -59,8 +63,7 @@ abstract class PendingSaves<T, I extends object> {}protected schedule(id: string, entity: T, getContent: () => string) {- const revision = (this.pending.get(id)?.revision ?? 0) + 1;- this.pending.set(id, { entity, getContent, revision });+ this.pending.set(id, { entity, getContent, revision: ++this.lastRevision });}/** One item for each change, with the content read at the time of the call. */