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(presentation): show the edited text after finishing an edit
Elian Dorancc713e812a08
diff --git a/apps/client/src/widgets/collections/presentation/index.tsx b/apps/client/src/widgets/collections/presentation/index.tsxindex 1878904a01..3a23ada022 100644--- a/apps/client/src/widgets/collections/presentation/index.tsx+++ b/apps/client/src/widgets/collections/presentation/index.tsx@@ -20,7 +20,9 @@ import { useEffectiveReadOnly, useNoteContext, useNoteLabelWithDefault, useTriliimport ShadowDom from "../../react/ShadowDom";import { DesktopWebView } from "../../type_widgets/WebView";import { ViewModeMedia, ViewModeProps } from "../interface";-import { buildPresentationModel, PresentationModel, PresentationSlideBaseModel } from "./model";+import {+ buildPresentationModel, PresentationModel, PresentationSlideBaseModel, renderSlideContent+} from "./model";import slideCustomStylesheet from "./slidejs.css?raw";import { DEFAULT_THEME, loadPresentationTheme } from "./themes";@@ -53,6 +55,8 @@ export default function PresentationView({ note, noteIds, media, onReady, onProg};const shadowHost = useElementOf(containerRef);const canEditSlides = media === "screen" && !isReadOnly && !options.is("databaseReadonly");+ const closingSlides = useClosingSlides(refresh);+ const refreshIdRef = useRef(0);useEffect(() => {if (!api) return;@@ -67,8 +71,15 @@ export default function PresentationView({ note, noteIds, media, onReady, onProg};}, [ api ]);+ // Only the latest model applies, as an earlier one can land later.function refresh() {- buildPresentationModel(note, onProgressChanged).then(setPresentation);+ const refreshId = ++refreshIdRef.current;+ const savedSlides = closingSlides.getSaved();+ buildPresentationModel(note, onProgressChanged).then((model) => {+ if (refreshId !== refreshIdRef.current) return;+ setPresentation(model);+ closingSlides.release(savedSlides);+ });}useTriliumEvent("entitiesReloaded", ({ loadResults }) => {@@ -99,6 +110,7 @@ export default function PresentationView({ note, noteIds, media, onReady, onProgntxId={noteContext?.ntxId}editedNoteId={editedNoteId}isEditorReady={!!editedNoteId && readyEditorNoteId === editedNoteId}+ closingContents={closingSlides.contents}onEditSlide={canEditSlides ? startEditing : undefined}onEditorHost={setEditorHost}/>@@ -139,6 +151,9 @@ export default function PresentationView({ note, noteIds, media, onReady, onPrognote={editedNote}onReady={() => setReadyEditorNoteId(editedNote.noteId)}onFinish={finishEditing}+ onClose={(content, save) => (+ closingSlides.onEditorClose(editedNote, content, save)+ )}/></Suspense>,editorHost@@ -165,6 +180,60 @@ function useElementOf<T extends HTMLElement>(ref: RefObject<T | null>) {return element;}+type SlideContent = PresentationSlideBaseModel["content"];++/** An editor of a text slide that went away, while its last save runs. */+interface ClosingSlide {+ isSaving: boolean;+}++/**+ * Keeps the content of each text slide as its editor held it when it closed, rendered, until a+ * model built after the last save of the editor holds what the save stored. After a failed save,+ * the content stays until the next model. `refresh` builds the model again once a save succeeds.+ */+function useClosingSlides(refresh: () => void) {+ const [ contents, setContents ] = useState<Record<string, SlideContent>>({});+ const closingRef = useRef(new Map<string, ClosingSlide>());++ function onEditorClose(slideNote: FNote, content: string, save: Promise<boolean>) {+ const { noteId } = slideNote;+ const closing: ClosingSlide = { isSaving: true };+ closingRef.current.set(noteId, closing);+ void renderSlideContent(slideNote, content).then((rendered) => {+ if (closingRef.current.get(noteId) === closing) {+ setContents((current) => ({ ...current, [noteId]: rendered }));+ }+ });+ void save.then((isSaved) => {+ if (closingRef.current.get(noteId) !== closing) return;+ closing.isSaving = false;+ if (isSaved) refresh();+ });+ }++ /** Returns the closed editors whose save has landed, which a model built from now reflects. */+ function getSaved() {+ return [ ...closingRef.current ].filter(([ , closing ]) => !closing.isSaving);+ }++ /** Drops the content of the editors that `getSaved()` returned, once a later model applies. */+ function release(saved: [string, ClosingSlide][]) {+ const released = saved.filter(([ noteId, closing ]) => (+ closingRef.current.get(noteId) === closing+ ));+ if (!released.length) return;+ for (const [ noteId ] of released) closingRef.current.delete(noteId);+ setContents((current) => {+ const next = { ...current };+ for (const [ noteId ] of released) delete next[noteId];+ return next;+ });+ }++ return { contents, onEditorClose, getSaved, release };+}+interface CollectionSlidesProps {presentation: PresentationModel;ntxId: string | null | undefined;@@ -312,13 +381,18 @@ interface PresentationProps {editedNoteId: string | undefined;/** Whether the editor of the edited slide holds its content. */isEditorReady: boolean;+ /** The content of each text slide whose editor closed, by note ID, shown over the model's. */+ closingContents: Record<string, SlideContent>;/** Starts editing a text or collection slide in place; left out when the presentation cannot be edited. */onEditSlide: ((noteId: string) => void) | undefined;/** Receives the element that the editor of the edited slide goes into. */onEditorHost: (element: HTMLElement | null) => void;}-function Presentation({ presentation, setApi, ntxId, editedNoteId, isEditorReady, onEditSlide, onEditorHost }: PresentationProps) {+function Presentation({+ presentation, setApi, ntxId, editedNoteId, isEditorReady, closingContents, onEditSlide,+ onEditorHost+}: PresentationProps) {const containerRef = useRef<HTMLDivElement>(null);const [revealApi, setRevealApi] = useState<RevealApi>();const fitObserverRef = useRef<ResizeObserver>(null);@@ -390,10 +464,11 @@ function Presentation({ presentation, setApi, ntxId, editedNoteId, isEditorReadyconst isEdited = slide.noteId === editedNoteId;const canEdit = onEditSlide && !isEdited && !slide.isReadOnly&& (slide.type === "text" || slide.isCollection);+ const closingContent = closingContents[slide.noteId];return (<Slidekey={slide.noteId}- slide={slide}+ slide={closingContent ? { ...slide, content: closingContent } : slide}ntxId={ntxId}// A collection slide is edited in its own view, so it takes no editor.editorHostRef={isEdited && !slide.isCollection ? onEditorHost : undefined}diff --git a/apps/client/src/widgets/collections/presentation/model.spec.ts b/apps/client/src/widgets/collections/presentation/model.spec.tsindex 6fa26f25f9..aa0c4e36bf 100644--- a/apps/client/src/widgets/collections/presentation/model.spec.ts+++ b/apps/client/src/widgets/collections/presentation/model.spec.ts@@ -7,7 +7,7 @@ import { beforeAll, describe, expect, it, vi } from "vitest";import FNote from "../../../entities/fnote";import { buildNote } from "../../../test/easy-froca";-import { buildPresentationModel, PresentationModel } from "./model";+import { buildPresentationModel, PresentationModel, renderSlideContent } from "./model";vi.mock("../../type_widgets/llm_chat/ChatPreview", () => ({default: ({ messages }: { messages: { content: string }[] }) =>@@ -189,3 +189,16 @@ describe("Presentation model with read-only slides", () => {]);});});++describe("renderSlideContent", () => {+ it("renders the content an editor held, with its links pointing at slides", async () => {+ const note = buildNote({ id: "editedSlide", title: "Edited", content: "<p>Saved</p>" });++ const link = `<a class="reference-link" href="#root/presentation/slide1">Link</a>`;+ const content = await renderSlideContent(note, `<p>Typed ${link}</p>`);++ expect(content.__html).toContain("Typed");+ expect(content.__html).not.toContain("Saved");+ expect(content.__html).toContain(`href="#/slide-slide1"`);+ });+});diff --git a/apps/client/src/widgets/collections/presentation/model.ts b/apps/client/src/widgets/collections/presentation/model.tsindex a43cbdeff2..0964bed408 100644--- a/apps/client/src/widgets/collections/presentation/model.ts+++ b/apps/client/src/widgets/collections/presentation/model.ts@@ -1,6 +1,7 @@import { NoteType } from "@triliumnext/commons";import FNote from "../../../entities/fnote";import contentRenderer, { snapshotAndDispose } from "../../../services/content_renderer";+import { renderTextContent } from "../../../services/content_renderer_text";import { sanitizeNoteContentHtml } from "../../../services/sanitize_content";import { ProgressChangedFn } from "../interface";@@ -116,19 +117,41 @@ function getWebViewSrc(note: FNote) {}async function processContent(note: FNote): Promise<DangerouslySetInnerHTML> {- const { $renderedContent } = await contentRenderer.getRenderedContent(note, {- noChildrenList: true,- mediaEnvironment: "native"- });+ const { $renderedContent } =+ await contentRenderer.getRenderedContent(note, SLIDE_RENDER_OPTIONS);return { __html: sanitizeNoteContentHtml(snapshotAndDispose($renderedContent)) };}+const SLIDE_RENDER_OPTIONS = {+ noChildrenList: true,+ mediaEnvironment: "native"+} as const;++/**+ * Renders `content`, the HTML of the text slide `note`, which can differ from the saved content,+ * as the editor of the slide holds it when it closes.+ */+export async function renderSlideContent(+ note: FNote,+ content: string+): Promise<DangerouslySetInnerHTML> {+ const $renderedContent = $("<div>");+ await renderTextContent(note, content, $renderedContent, SLIDE_RENDER_OPTIONS);+ const html = sanitizeNoteContentHtml(snapshotAndDispose($renderedContent));+ return { __html: rewriteSlideLinks(html) };+}+async function postProcessSlides(slides: (PresentationSlideModel | PresentationSlideBaseModel)[]) {for (const slide of slides) {if (slide.type !== "text") continue;- slide.content.__html = slide.content.__html.replaceAll(/href="[^"]*#root[a-zA-Z0-9_\/]*\/([a-zA-Z0-9_]+)[^"]*"/g, `href="#/slide-$1"`);+ slide.content.__html = rewriteSlideLinks(slide.content.__html);if ("verticalSlides" in slide && slide.verticalSlides) {postProcessSlides(slide.verticalSlides);}}}++/** Points the links in `html` at the slides of the notes they link to. */+function rewriteSlideLinks(html: string) {+ return html.replaceAll(/href="[^"]*#root[a-zA-Z0-9_\/]*\/([a-zA-Z0-9_]+)[^"]*"/g, `href="#/slide-$1"`);+}diff --git a/apps/client/src/widgets/collections/presentation/slide_editor.tsx b/apps/client/src/widgets/collections/presentation/slide_editor.tsxindex 1c58bb6444..88e0af2694 100644--- a/apps/client/src/widgets/collections/presentation/slide_editor.tsx+++ b/apps/client/src/widgets/collections/presentation/slide_editor.tsx@@ -18,6 +18,8 @@ interface SlideEditorProps {/** Called once the editor holds the slide's content and can replace the rendered slide. */onReady(): void;onFinish(): void;+ /** Receives the content of the editor as it goes away, and the save of what is left. */+ onClose(content: string, save: Promise<boolean>): void;}/**@@ -25,7 +27,7 @@ interface SlideEditorProps {* theme styles the text being edited. Escape finishes editing, unless the editor already handled* it.*/-export default function SlideEditor({ note, onReady, onFinish }: SlideEditorProps) {+export default function SlideEditor({ note, onReady, onFinish, onClose }: SlideEditorProps) {const rootRef = useRef<HTMLDivElement>(null);const onReadyRef = useRef(onReady);onReadyRef.current = onReady;@@ -54,7 +56,7 @@ export default function SlideEditor({ note, onReady, onFinish }: SlideEditorProp}}><Suspense fallback={null}>- <TextEmbedEditor note={note} hasFixedToolbar={false} onClose={() => {}} />+ <TextEmbedEditor note={note} hasFixedToolbar={false} onClose={onClose} /></Suspense></div>);