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): swap a slide and its editor without a blank frame
Elian Doran02b91979fd9a
diff --git a/apps/client/src/widgets/collections/presentation/index.tsx b/apps/client/src/widgets/collections/presentation/index.tsxindex ada7336838..8b5d8b93c4 100644--- a/apps/client/src/widgets/collections/presentation/index.tsx+++ b/apps/client/src/widgets/collections/presentation/index.tsx@@ -40,7 +40,16 @@ export default function PresentationView({ note, noteIds, media, onReady, onProgconst [ editedNoteId, setEditedNoteId ] = useState<string>();const [ editorHost, setEditorHost ] = useState<HTMLElement | null>(null);const editedNote = editedNoteId ? froca.getNoteFromCache(editedNoteId) : undefined;- const finishEditing = () => setEditedNoteId(undefined);+ const [ readyEditorNoteId, setReadyEditorNoteId ] = useState<string>();+ // Each edit waits for its own editor, so editing the same slide again starts out not ready.+ const startEditing = (noteId: string) => {+ setReadyEditorNoteId(undefined);+ setEditedNoteId(noteId);+ };+ const finishEditing = () => {+ setEditedNoteId(undefined);+ setReadyEditorNoteId(undefined);+ };const shadowHost = useElementOf(containerRef);useEffect(() => {@@ -86,7 +95,8 @@ export default function PresentationView({ note, noteIds, media, onReady, onProgsetApi={setApi}ntxId={noteContext?.ntxId}editedNoteId={editedNoteId}- onEditSlide={media === "screen" && !isReadOnly ? setEditedNoteId : undefined}+ isEditorReady={!!editedNoteId && readyEditorNoteId === editedNoteId}+ onEditSlide={media === "screen" && !isReadOnly ? startEditing : undefined}onEditorHost={setEditorHost}/></>@@ -121,7 +131,11 @@ export default function PresentationView({ note, noteIds, media, onReady, onProg{editedNote && editorHost && createPortal(// Its own boundary, so that loading the editor does not suspend the presentation.<Suspense fallback={null}>- <SlideEditor note={editedNote} onFinish={finishEditing} />+ <SlideEditor+ note={editedNote}+ onReady={() => setReadyEditorNoteId(editedNote.noteId)}+ onFinish={finishEditing}+ /></Suspense>,editorHost)}@@ -281,13 +295,15 @@ interface PresentationProps {ntxId: string | null | undefined;/** The note of the slide being edited in place. */editedNoteId: string | undefined;+ /** Whether the editor of the edited slide holds its content. */+ isEditorReady: boolean;/** Starts editing a text 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, onEditSlide, onEditorHost }: PresentationProps) {+function Presentation({ presentation, setApi, ntxId, editedNoteId, isEditorReady, onEditSlide, onEditorHost }: PresentationProps) {const containerRef = useRef<HTMLDivElement>(null);const [revealApi, setRevealApi] = useState<RevealApi>();const fitObserverRef = useRef<ResizeObserver>(null);@@ -362,6 +378,7 @@ function Presentation({ presentation, setApi, ntxId, editedNoteId, onEditSlide,slide={slide}ntxId={ntxId}editorHostRef={slide.noteId === editedNoteId ? onEditorHost : undefined}+ isEditorReady={isEditorReady}onEdit={canEdit ? () => {if (!revealApi?.isOverview() && !document.fullscreenElement) onEditSlide(slide.noteId);} : undefined}@@ -395,11 +412,13 @@ interface SlideProps {ntxId: string | null | undefined;/** Set while the slide is edited in place, to receive the element that the editor goes into. */editorHostRef?: (element: HTMLElement | null) => void;+ /** Whether the editor of the slide holds its content, so that it replaces the rendered content. */+ isEditorReady?: boolean;/** Starts editing the slide in place, on a double-click. */onEdit?: () => void;}-export function Slide({ slide, ntxId, editorHostRef, onEdit }: SlideProps) {+export function Slide({ slide, ntxId, editorHostRef, isEditorReady, onEdit }: SlideProps) {// On desktop a web view goes in an Electron `<webview>`, whose own session keeps the page away// from the app; elsewhere Reveal.js frames it in the slide's background.const desktopWebViewSrc = isElectron ? slide.webViewSrc : undefined;@@ -408,9 +427,17 @@ export function Slide({ slide, ntxId, editorHostRef, onEdit }: SlideProps) {function renderContent() {if (desktopWebViewSrc) return <DesktopWebView src={desktopWebViewSrc} ntxId={ntxId} />;if (slide.isCollection) return <slot name={getCollectionSlotName(slide.noteId)} />;- // The keys keep Preact from reusing the rendered content's element, and its zoom, for the editor.- if (editorHostRef) return <div key="editor" className="slide-content slide-editor" ref={editorHostRef} />;- return <div key="content" className="slide-content" dangerouslySetInnerHTML={slide.content} />;+ // The rendered content stays, with its zoom, until the editor that loads hidden beside it+ // holds the slide; then one render swaps them. The keys keep the two elements apart.+ return [+ (!editorHostRef || !isEditorReady) &&+ <div key="content" className="slide-content" dangerouslySetInnerHTML={slide.content} />,+ editorHostRef && <div+ key="editor"+ className={`slide-content slide-editor ${isEditorReady ? "" : "slide-editor-pending"}`}+ ref={editorHostRef}+ />+ ];}return (diff --git a/apps/client/src/widgets/collections/presentation/slide_editor.spec.ts b/apps/client/src/widgets/collections/presentation/slide_editor.spec.tsindex 9c24307c8f..8a77a07e34 100644--- a/apps/client/src/widgets/collections/presentation/slide_editor.spec.ts+++ b/apps/client/src/widgets/collections/presentation/slide_editor.spec.ts@@ -1,6 +1,81 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";-import { adoptEditorStyleSheet, collectEditorStylesheet } from "./slide_editor";+import type FNote from "../../../entities/fnote";+import { adoptEditorStyleSheet, collectEditorStylesheet, whenEditorHoldsContent } from "./slide_editor";++describe("whenEditorHoldsContent", () => {+ function setUp(noteContent: string) {+ const root = document.createElement("div");+ const note = { getContent: async () => noteContent } as unknown as FNote;+ const onReady = vi.fn();+ const focus = vi.fn();+ const stop = whenEditorHoldsContent(root, note, onReady);++ /** Mounts an editor root as CKEditor does, holding `data`. */+ function mountEditor(data: string, { hidden = false } = {}) {+ const editable = document.createElement("div");+ editable.className = "ck-editor__editable";+ editable.style.visibility = hidden ? "hidden" : "";+ Object.assign(editable, {+ ckeditorInstance: {+ getData: () => data,+ editing: { view: { focus, getDomRoot: () => editable } }+ }+ });+ root.replaceChildren(editable);+ document.body.append(root);+ return editable;+ }+ return { onReady, focus, stop, mountEditor };+ }++ it("focuses the editor only once it is shown", async () => {+ const { onReady, focus, mountEditor } = setUp("<p>Slide</p>");+ const editable = mountEditor("<p>Slide</p>", { hidden: true });+ await vi.waitFor(() => expect(onReady).toHaveBeenCalledOnce());+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(focus).not.toHaveBeenCalled();++ editable.style.visibility = "";+ await vi.waitFor(() => expect(focus).toHaveBeenCalledOnce());+ });++ it("waits for the note's content before reporting the editor ready, then focuses it", async () => {+ const { onReady, focus, mountEditor } = setUp("<p>Slide</p>");+ mountEditor("");+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(onReady).not.toHaveBeenCalled();++ mountEditor("<p>Slide</p>");+ await vi.waitFor(() => expect(onReady).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(focus).toHaveBeenCalledOnce());+ });++ it("reports an empty note ready once its editor exists, and nothing after stopping", async () => {+ const empty = setUp("");+ empty.mountEditor("");+ await vi.waitFor(() => expect(empty.onReady).toHaveBeenCalledOnce());++ const stopped = setUp("<p>Slide</p>");+ stopped.stop();+ stopped.mountEditor("<p>Slide</p>");+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(stopped.onReady).not.toHaveBeenCalled();+ });++ it("shows the editor anyway when it takes too long to load", async () => {+ vi.useFakeTimers();+ try {+ const { onReady } = setUp("<p>Slide</p>");+ await vi.advanceTimersByTimeAsync(2999);+ expect(onReady).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(onReady).toHaveBeenCalledOnce();+ } finally {+ vi.useRealTimers();+ }+ });+});describe("adoptEditorStyleSheet", () => {it("shares one stylesheet between edits and removes only its own", () => {diff --git a/apps/client/src/widgets/collections/presentation/slide_editor.tsx b/apps/client/src/widgets/collections/presentation/slide_editor.tsxindex 9c4d2c84e8..1c58bb6444 100644--- a/apps/client/src/widgets/collections/presentation/slide_editor.tsx+++ b/apps/client/src/widgets/collections/presentation/slide_editor.tsx@@ -1,18 +1,34 @@import { Suspense } from "preact/compat";-import { useLayoutEffect, useRef } from "preact/hooks";+import { useEffect, useLayoutEffect, useRef } from "preact/hooks";import FNote from "../../../entities/fnote";+import { isHtmlEmpty } from "../../../services/utils";+import { findTextEditorIn } from "../../type_widgets/text/editable_embed";import TextEmbedEditor from "../../type_widgets/text/TextEmbedEditor";+/** How long the editor can take to load before it is shown anyway. */+const READY_TIMEOUT = 3000;+/** How long the editor can take to be shown after it is ready, after which it is not focused. */+const FOCUS_TIMEOUT = 1000;+let editorStyleSheet: CSSStyleSheet | undefined;+interface SlideEditorProps {+ note: FNote;+ /** Called once the editor holds the slide's content and can replace the rendered slide. */+ onReady(): void;+ onFinish(): void;+}+/*** Edits a text slide in place, inside the slide's frame in the shadow root, so that the slide's* theme styles the text being edited. Escape finishes editing, unless the editor already handled* it.*/-export default function SlideEditor({ note, onFinish }: { note: FNote; onFinish(): void }) {+export default function SlideEditor({ note, onReady, onFinish }: SlideEditorProps) {const rootRef = useRef<HTMLDivElement>(null);+ const onReadyRef = useRef(onReady);+ onReadyRef.current = onReady;// A layout effect, so the editor's styles are in the shadow root before the editor paints.useLayoutEffect(() => {@@ -20,6 +36,12 @@ export default function SlideEditor({ note, onFinish }: { note: FNote; onFinish(if (root instanceof ShadowRoot) return adoptEditorStyleSheet(root);}, []);+ useEffect(() => {+ const root = rootRef.current;+ if (!root) return;+ return whenEditorHoldsContent(root, note, () => onReadyRef.current());+ }, [ note ]);+return (<divref={rootRef}@@ -38,15 +60,76 @@ export default function SlideEditor({ note, onFinish }: { note: FNote; onFinish();}+/**+ * Calls `onReady` once the text editor inside `root` holds the content of `note`, then focuses the+ * editor, which could not take the focus while hidden. An editor with no content is ready once+ * it exists, if the note is empty too. Returns the function that stops waiting.+ */+export function whenEditorHoldsContent(root: HTMLElement, note: FNote, onReady: () => void) {+ let isNoteEmpty: boolean | undefined;+ let isReady = false;+ let isStopped = false;+ let focusFrame: number | undefined;++ const check = () => {+ if (isReady || !findTextEditorIn(root) || isNoteEmpty === undefined) return;+ if (!isNoteEmpty && isHtmlEmpty(findTextEditorIn(root)?.getData() ?? "")) return;+ finish();+ };+ const finish = () => {+ isReady = true;+ observer.disconnect();+ clearTimeout(timeout);+ onReady();+ focusWhenShown(performance.now() + FOCUS_TIMEOUT);+ };+ // The slides render in an effect after `onReady`, and a hidden editor cannot take the focus.+ const focusWhenShown = (deadline: number) => {+ const editor = findTextEditorIn(root);+ const editable = editor?.editing.view.getDomRoot();+ if (isStopped || !editor || !editable) return;+ if (getComputedStyle(editable).visibility !== "hidden") {+ editor.editing.view.focus();+ } else if (performance.now() < deadline) {+ focusFrame = requestAnimationFrame(() => focusWhenShown(deadline));+ }+ };++ const observer = new MutationObserver(check);+ observer.observe(root, { childList: true, subtree: true, characterData: true });+ const timeout = setTimeout(finish, READY_TIMEOUT);+ void note.getContent().then((content) => {+ isNoteEmpty = isHtmlEmpty(content ?? "");+ check();+ });++ return () => {+ isStopped = true;+ isReady = true;+ observer.disconnect();+ clearTimeout(timeout);+ if (focusFrame !== undefined) cancelAnimationFrame(focusFrame);+ };+}+/*** Adds the editor's styles to `root` and returns the function that removes them. The stylesheet* is built on the first edit and shared by every later one, so only the first edit collects and* parses it. This module imports the editor, so its stylesheets are in the document by then.+ *+ * The rules go in a cascade layer, which the theme's unlayered rules outrank whatever their+ * specificity, so the slide keeps the theme's spacing where both set it. The margins CKEditor+ * gives the first and last block of an inline editor are reverted, so the edited slide is as tall+ * as the rendered one.*/export function adoptEditorStyleSheet(root: ShadowRoot) {if (!editorStyleSheet) {editorStyleSheet = new CSSStyleSheet();- editorStyleSheet.replaceSync(collectEditorStylesheet());+ editorStyleSheet.replaceSync(`@layer slide-editor {+${collectEditorStylesheet()}+.ck.ck-editor__editable_inline > :first-child { margin-top: revert-layer; }+.ck.ck-editor__editable_inline > :last-child { margin-bottom: revert-layer; }+}`);}const sheet = editorStyleSheet;root.adoptedStyleSheets = [ ...root.adoptedStyleSheets, sheet ];diff --git a/apps/client/src/widgets/collections/presentation/slidejs.css b/apps/client/src/widgets/collections/presentation/slidejs.cssindex 56faf493aa..0eee75cec8 100644--- a/apps/client/src/widgets/collections/presentation/slidejs.css+++ b/apps/client/src/widgets/collections/presentation/slidejs.css@@ -58,6 +58,15 @@outline-offset: 8px;}+.slide-editor-pending {+ position: absolute;+ top: 0;+ inset-inline: 0;+ height: 0;+ overflow: hidden;+ visibility: hidden;+}+.reveal .slides section.has-dark-background {color-scheme: dark;}diff --git a/apps/client/src/widgets/react/ShadowDom.tsx b/apps/client/src/widgets/react/ShadowDom.tsxindex 564d689edb..faf3330608 100644--- a/apps/client/src/widgets/react/ShadowDom.tsx+++ b/apps/client/src/widgets/react/ShadowDom.tsx@@ -1,5 +1,5 @@import { ComponentChildren, HTMLAttributes, JSX, RefObject, render } from "preact";-import { useEffect, useState } from "preact/hooks";+import { useLayoutEffect, useState } from "preact/hooks";import { useSyncedRef } from "./hooks";interface ShadowDomProps extends Omit<HTMLAttributes<HTMLDivElement>, "ref"> {@@ -12,14 +12,15 @@ export default function ShadowDom({ children, containerRef: externalContainerRefconst [ shadowRoot, setShadowRoot ] = useState<ShadowRoot | null>(null);// Create the shadow root.- useEffect(() => {+ useLayoutEffect(() => {if (!containerRef.current) return;const shadow = containerRef.current.attachShadow({ mode: "open" });setShadowRoot(shadow);}, []);- // Render the child elements.- useEffect(() => {+ // Render the child elements. A layout effect, so the shadow tree commits before the paint+ // together with the tree around it, as a portal from that tree into the shadow tree expects.+ useLayoutEffect(() => {if (!shadowRoot) return;render(<>{children}</>, shadowRoot);}, [ shadowRoot, children ]);