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 Doran17a2bb895971
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsxindex 1f0abb7b90..2b1f239d86 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx@@ -164,6 +164,72 @@ describe("TextEmbed", () => {await vi.waitFor(() => expect(shownPreview()).toBe("<div><p>Saved</p></div>"));});+ it("keeps what the editor held when its last save fails", async () => {+ const note = buildTextNote("failing");+ const { figure } = await mount(note, buildEditor(), { isEditable: true });+ await vi.waitFor(() => expect(editorProps).toHaveBeenCalled(), { timeout: 5000 });+ const { noteContext } = editorProps.mock.calls[0][0] as TypeWidgetProps;+ editorAskedToSave.mockImplementationOnce(async () => {+ noteContext?.setContextData("saveState", { state: "error" });+ });++ editorData = "<p>Not saved yet</p>";+ note.getBlob = async () => buildBlob("<p>Saved before</p>");+ await act(async () => {+ delete figure.dataset.editable;+ await Promise.resolve();+ });+ await settle();+ expect(figure.querySelector(".editable-embed-preview")?.innerHTML)+ .toBe("<div><p>Not saved yet</p></div>");+ });++ it("shows the newest content when reads of the note land out of order", async () => {+ const note = buildTextNote("racing");+ const { figure } = await mount(note, buildEditor(), { isEditable: true });+ await vi.waitFor(() => {+ expect(figure.querySelector(".editable-text-stub")).not.toBeNull();+ }, { timeout: 5000 });++ let finishSave = () => {};+ editorAskedToSave.mockImplementationOnce(() => new Promise<void>((resolve) => {+ finishSave = resolve;+ }));+ editorData = "<p>Closed</p>";+ await act(async () => {+ delete figure.dataset.editable;+ await Promise.resolve();+ });++ // The read that follows the last save of the editor is slow.+ let slowRead = () => {};+ const isRead = vi.fn();+ note.getBlob = () => new Promise((resolve) => {+ isRead();+ slowRead = () => resolve(buildBlob("<p>Older</p>"));+ });+ await act(async () => {+ finishSave();+ });+ await settle();+ expect(isRead).toHaveBeenCalledOnce();++ // Another editor saves the note meanwhile.+ note.getBlob = async () => buildBlob("<p>Newer</p>");+ await act(async () => {+ await reloadNoteContent(note);+ });+ await settle();+ expect(figure.querySelector(".editable-embed-preview")?.innerHTML)+ .toBe("<div><p>Newer</p></div>");+ await act(async () => {+ slowRead();+ });+ await settle();+ expect(figure.querySelector(".editable-embed-preview")?.innerHTML)+ .toBe("<div><p>Newer</p></div>");+ });+it("lets another include of the note follow its saves while an editor closes", async () => {const note = buildTextNote("shared");let finishSave = () => {};@@ -298,6 +364,15 @@ function buildEditor(): ContentEditor {};}+/** Lets the reads, renders and effects that are under way finish. */+async function settle() {+ for (let i = 0; i < 3; i++) {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 50));+ });+ }+}+/** Announces a save of the content of `note`, as the server does. */async function reloadNoteContent(note: FNote) {const loadResults = new LoadResults([]);diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsxindex 64ff4adec4..1533795c4c 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx@@ -4,7 +4,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";import type FNote from "../../../entities/fnote";import type { ContentEditor } from "../../../services/content_renderer";import froca from "../../../services/froca";-import { useNoteBlob } from "../../react/hooks";+import { useTriliumEvent } from "../../react/hooks";import {EditableEmbedContent, hasFixedToolbarAround, useEditableEmbed, useEmbedPreview} from "./editable_embed";@@ -58,55 +58,63 @@ export default function TextEmbed({/*** 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.+ * last save lands, and otherwise the latest content that a save of the note stores. After a failed+ * save, the content of the editor stays until the next save of the note. 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);+ const requestIdRef = useRef(0);+ const closingSaveRef = useRef<Promise<boolean> | undefined>(undefined);- // An earlier save that lands while the last save runs stores older content.- useEffect(() => {- if (blob && !closingSaveRef.current) {+ // Only the latest read applies, and none while the last save of the editor runs: an earlier+ // save that lands meanwhile stores older content.+ const refresh = useCallback(async () => {+ const requestId = ++requestIdRef.current;+ const blob = await note.getBlob();+ if (blob && requestId === requestIdRef.current && !closingSaveRef.current) {setContent(blob.content);}- }, [ blob ]);+ }, [ note ]);++ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {+ if (loadResults.isNoteContentReloaded(note.noteId)) {+ void refresh();+ }+ });- const onEditorClose = useCallback((editorContent: string, save: Promise<void>) => {+ const onEditorClose = useCallback((editorContent: string, save: Promise<boolean>) => {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 ]);+ void save.then((isSaved) => {+ if (closingSaveRef.current !== save) return;+ closingSaveRef.current = undefined;+ if (isSaved) {+ void refresh();+ }+ });+ }, [ refresh ]);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>>();+const closingSaves = new Map<string, Promise<boolean>>();/**- * Tracks `save`, the last save of an editor of `noteId` that went away, until it lands. Then drops- * the content that `froca` fetched before, so that the next editor loads what the save stored.+ * Tracks `save`, the last save of an editor of `noteId` that went away, which resolves to whether+ * it succeeded, until it lands. Then drops the content that `froca` fetched before, so that the+ * next editor loads what the save stored.*/-export function trackClosingSave(noteId: string, save: Promise<unknown> | null) {- const tracked: Promise<void> = Promise.resolve(save)- .catch(() => {- // Failures are logged by `SpacedUpdate` and retried.- })- .then(() => {+export function trackClosingSave(noteId: string, save: Promise<boolean>) {+ const tracked: Promise<boolean> = save+ .catch(() => false)+ .then((isSaved) => {delete froca.blobPromises[`notes-${noteId}`];if (closingSaves.get(noteId) === tracked) {closingSaves.delete(noteId);}+ return isSaved;});closingSaves.set(noteId, tracked);return tracked;diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsxindex a36a672b8f..5a2fcc5b2d 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx@@ -3,6 +3,8 @@ import "./TextEmbedEditor.css";import { createPortal, type RefObject } from "preact";import { useLayoutEffect, useRef, useState } from "preact/hooks";+import type Component from "../../../components/component";+import type NoteContext from "../../../components/note_context";import type FNote from "../../../entities/fnote";import { randomString } from "../../../services/utils";import {@@ -22,7 +24,7 @@ interface TextEmbedEditorProps {* 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;+ onClose(content: string, save: Promise<boolean>): void;}/**@@ -47,12 +49,12 @@ 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(() => () => {- const save = trackClosingSave(note.noteId, announceEmbeddedNoteClosing(component, ntxId));+ const save = trackClosingSave(note.noteId, saveWhatIsLeft(component, noteContext, ntxId));const content = findTextEditorIn(rootRef.current)?.getData();if (content !== undefined) {onCloseRef.current(content, save);}- }, [ component, ntxId ]);+ }, [ component, noteContext, ntxId ]);return (<EmbeddedNoteScope component={component} noteContext={noteContext}>@@ -90,3 +92,12 @@ function ScopedEditor({ rootRef, note }: ScopedEditorProps) {</div>);}++/**+ * Saves what is left in the editor of `ntxId`, and resolves to whether the save succeeded. The+ * editor reports a failed save in the save state of its note context.+ */+async function saveWhatIsLeft(component: Component, noteContext: NoteContext, ntxId: string) {+ await announceEmbeddedNoteClosing(component, ntxId);+ return noteContext.getContextData("saveState")?.state !== "error";+}