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
chore(presentation): split the presentation view into modules
Elian Doran9d3ad7d45ffc
diff --git a/apps/client/src/widgets/collections/presentation/closing_slides.ts b/apps/client/src/widgets/collections/presentation/closing_slides.tsnew file mode 100644index 0000000000..7f57a10874--- /dev/null+++ b/apps/client/src/widgets/collections/presentation/closing_slides.ts@@ -0,0 +1,58 @@+import { useRef, useState } from "preact/hooks";++import FNote from "../../../entities/fnote";+import { PresentationSlideBaseModel, renderSlideContent } from "./model";++export 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.+ */+export 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 };+}diff --git a/apps/client/src/widgets/collections/presentation/fit.spec.ts b/apps/client/src/widgets/collections/presentation/fit.spec.tsnew file mode 100644index 0000000000..463c5cfd23--- /dev/null+++ b/apps/client/src/widgets/collections/presentation/fit.spec.ts@@ -0,0 +1,102 @@+import { describe, expect, it, vi } from "vitest";++import { createFitObserver, fitSlideContent } from "./fit";++describe("fitSlideContent", () => {+ it("zooms out only the content that is larger than the slide", () => {+ const tall = buildContent({ height: zoom => 2 * zoom });+ fitSlideContent(tall);+ expect(Number(tall.style.zoom)).toBeCloseTo(0.5);++ // A second fit measures the content without the zoom it already has.+ fitSlideContent(tall);+ expect(Number(tall.style.zoom)).toBeCloseTo(0.5);++ const wide = buildContent({ width: zoom => 2 * zoom });+ fitSlideContent(wide);+ expect(Number(wide.style.zoom)).toBeCloseTo(0.5);++ const fitting = buildContent({ height: () => 1 });+ fitting.style.zoom = "0.5";+ fitSlideContent(fitting);+ expect(fitting.style.zoom).toBe("");++ const hidden = buildContent({ height: () => 0, hidden: true });+ fitSlideContent(hidden);+ expect(hidden.style.zoom).toBe("");+ });++ it("fits content with parts that do not scale with the zoom", () => {+ // Text as tall as the slide plus an image half as tall, which keeps its height.+ const content = buildContent({ height: zoom => zoom + 0.5 });+ fitSlideContent(content);+ expect(Number(content.style.zoom)).toBeCloseTo(0.5);+ expect(Number(content.style.zoom) + 0.5).toBeLessThanOrEqual(1);+ });++ it("stops zooming out when the zoom barely shrinks the overflow", () => {+ // A table editor's column resizer, 3px past a full-width table, overflows by the same share at+ // any zoom; the secant step would place the fit at a zoom of almost nothing.+ const content = buildContent({ width: zoom => 1 + 0.00234 * zoom });+ fitSlideContent(content);+ expect(Number(content.style.zoom)).toBeGreaterThan(0.99);+ });+});++describe("createFitObserver", () => {+ it("fits again when the size changes, but not for the size its own fit leaves", () => {+ let notify: ResizeObserverCallback = () => {};+ vi.stubGlobal("ResizeObserver", class {+ constructor(callback: ResizeObserverCallback) { notify = callback; }+ disconnect() {}+ });++ let naturalHeight = 2;+ const content = buildContent({ height: zoom => naturalHeight * zoom });+ const onFitted = vi.fn();+ const observer = createFitObserver(onFitted);+ const resize = () => notify([ { target: content } as unknown as ResizeObserverEntry ], observer);++ resize();+ expect(Number(content.style.zoom)).toBeCloseTo(0.5);+ expect(onFitted).toHaveBeenCalledTimes(1);++ // The notification for the zoom the fit applied.+ resize();+ expect(onFitted).toHaveBeenCalledTimes(1);++ // A stylesheet makes the content taller.+ naturalHeight = 4;+ resize();+ expect(Number(content.style.zoom)).toBeCloseTo(0.25);+ expect(onFitted).toHaveBeenCalledTimes(2);++ vi.unstubAllGlobals();+ });+});++interface ContentSize {+ /** The height relative to the slide's, for a given zoom. */+ height?: (zoom: number) => number;+ /** The scrolled width relative to the slide's, for a given zoom. */+ width?: (zoom: number) => number;+ hidden?: boolean;+}++/** Builds slide content whose measured size follows its zoom, as it does in a browser. */+function buildContent({ height = () => 1, width = () => 1, hidden }: ContentSize) {+ const slides = document.createElement("div");+ slides.className = "slides";+ const content = document.createElement("div");+ slides.appendChild(content);++ const zoom = () => Number(content.style.zoom || 1);+ const clientWidth = hidden ? 0 : 1280;+ slides.getBoundingClientRect = () => DOMRect.fromRect({ width: 640, height: 360 });+ content.getBoundingClientRect = () => DOMRect.fromRect({ width: 640, height: 360 * height(zoom()) });+ Object.defineProperty(content, "clientWidth", { get: () => clientWidth });+ Object.defineProperty(content, "scrollWidth", { get: () => clientWidth * width(zoom()) });+ Object.defineProperty(content, "offsetWidth", { get: () => clientWidth });+ Object.defineProperty(content, "offsetHeight", { get: () => 720 * height(zoom()) });+ return content;+}diff --git a/apps/client/src/widgets/collections/presentation/index.tsx b/apps/client/src/widgets/collections/presentation/index.tsxindex 36b1fa8664..eb13b40052 100644--- a/apps/client/src/widgets/collections/presentation/index.tsx+++ b/apps/client/src/widgets/collections/presentation/index.tsx@@ -4,7 +4,7 @@ import multicolumnStylesheet from "@triliumnext/ckeditor5/src/theme/multicolumn.import { createPortal, RefObject } from "preact";import { lazy, Suspense } from "preact/compat";import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";-import Reveal, { RevealApi } from "reveal.js";+import type { RevealApi } from "reveal.js";import slideBaseStylesheet from "reveal.js/reveal.css?raw";import { openInCurrentNoteContext } from "../../../components/note_context";@@ -13,29 +13,25 @@ import froca from "../../../services/froca";import { t } from "../../../services/i18n";import katexStylesheet from "../../../services/katex.scss?inline";import options from "../../../services/options";-import utils from "../../../services/utils";import CollectionProperties from "../../note_bars/CollectionProperties";import ActionButton from "../../react/ActionButton";import {useEffectiveReadOnly, useNoteContext, useNoteLabelWithDefault, useTriliumEvent, useTriliumOptionBool} from "../../react/hooks";import ShadowDom from "../../react/ShadowDom";-import { DesktopWebView } from "../../type_widgets/WebView";import { ViewModeMedia, ViewModeProps } from "../interface";-import { createFitObserver } from "./fit";+import { useClosingSlides } from "./closing_slides";import {applySlideMove, buildPresentationModel, createSlide, getSlideMove, isSlideRebuilt, moveSlideNote,- PresentationModel, PresentationSlideBaseModel, renderSlideContent, SlideMove+ PresentationModel, SlideMove} from "./model";+import { getNoteIdFromSlide, goToSlide, useActiveSlideNoteId } from "./reveal";import SlideSidebar from "./sidebar";import slideCustomStylesheet from "./slidejs.css?raw";+import { CollectionSlides, Presentation } from "./slides";import { DEFAULT_THEME, loadPresentationTheme } from "./themes";-const SLIDE_WIDTH = 1280;-const SLIDE_HEIGHT = 720;-const isElectron = utils.isElectron();const SlideEditor = lazy(() => import("./slide_editor"));-const EmbeddedNoteList = lazy(() => import("../NoteList").then(({ EmbeddedNoteList }) => ({ default: EmbeddedNoteList })));export default function PresentationView({ note, noteIds, media, onReady, onProgressChanged, onOpenNote }: ViewModeProps<{}>) {const [ presentation, setPresentation ] = useState<PresentationModel>();@@ -246,124 +242,6 @@ function useElementOf<T extends HTMLElement>(ref: RefObject<T | null>) {return element;}-/** Returns the note ID of the slide that Reveal.js shows. */-export function useActiveSlideNoteId(api: RevealApi | undefined) {- const [ activeNoteId, setActiveNoteId ] = useState<string>();- useEffect(() => {- if (!api) return;- const update = () => setActiveNoteId(getNoteIdFromSlide(api.getCurrentSlide()));- update();- api.on("slidechanged", update);- return () => api.off("slidechanged", update);- }, [ api ]);- return activeNoteId;-}--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;- /** The note of the slide being edited, whose collection alone can be changed and open its notes. */- editedNoteId: string | undefined;- onOpenNote: ((noteId: string) => void) | undefined;-}--/**- * Renders the collection of each collection slide with the app's own note list, as children of the shadow- * host that its slide's `<slot>` shows. Outside the shadow root, the document's stylesheets style the- * collection and the slide's theme does not; the collection is still drawn, scaled and moved with its slide.- */-export function CollectionSlides({ presentation, ntxId, editedNoteId, onOpenNote }: CollectionSlidesProps) {- const slides = presentation.slides.flatMap(slide => [ slide, ...slide.verticalSlides ?? [] ]);- return (- <>- {slides.filter(slide => slide.isCollection).map(slide => {- const note = froca.getNoteFromCache(slide.noteId);- if (!note) return null;- const isEdited = slide.noteId === editedNoteId;- return (- <div- key={slide.noteId}- slot={getCollectionSlotName(slide.noteId)}- className={`presentation-collection-slide ${isEdited ? "is-edited" : ""}`}- >- <Suspense fallback={null}>- <EmbeddedNoteList- note={note}- notePath={note.getBestNotePathString()}- ntxId={ntxId}- media="screen"- isReadOnly={!isEdited}- // Opening a note leaves the presentation, or opens a popup that full-screen hides.- onOpenNote={isEdited ? onOpenNote : ignoreOpenNote}- />- </Suspense>- </div>- );- })}- </>- );-}--function ignoreOpenNote() {}--function getCollectionSlotName(noteId: string) {- return `collection-${noteId}`;-}-function usePresentationStylesheets(note: FNote, media: ViewModeMedia) {const [ themeName ] = useNoteLabelWithDefault(note, "presentation:theme", DEFAULT_THEME);const [ stylesheets, setStylesheets ] = useState<string[]>();@@ -462,299 +340,3 @@ function ButtonOverlay({ containerRef, api, isReadOnly, isEditing, onFinishEditi);}-interface PresentationProps {- presentation: PresentationModel;- setApi: (api: RevealApi | undefined) => void;- 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;- /** 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;- /** The note of a slide just added, to go to once Reveal.js has it. */- newSlideNoteId: string | undefined;- /** Called once the presentation shows the slide of `newSlideNoteId`. */- onNewSlideShown: (noteId: string) => void;-}--function Presentation({- presentation, setApi, ntxId, editedNoteId, isEditorReady, closingContents, onEditSlide,- onEditorHost, newSlideNoteId, onNewSlideShown-}: PresentationProps) {- const containerRef = useRef<HTMLDivElement>(null);- const [revealApi, setRevealApi] = useState<RevealApi>();- const fitObserverRef = useRef<ResizeObserver>(null);-- useEffect(() => {- if (!containerRef.current) return;-- const api = new Reveal(containerRef.current, {- transition: "slide",- embedded: true,- // Must match the aspect ratio of `.reveal` in slidejs.css.- width: SLIDE_WIDTH,- height: SLIDE_HEIGHT,- minScale: 0,- maxScale: Infinity,- pdfMaxPagesPerSlide: 1,- keyboardCondition(event) {- // Full-screen requests sometimes fail, we rely on the UI button instead.- if (event.key === "f") {- return false;- }-- return !isTypingIn(event) && !isPressingButton(event);- },- });- const container = containerRef.current;- const fitObserver = createFitObserver(() => {- if (api.isReady()) api.layout();- });- fitObserverRef.current = fitObserver;-- api.initialize().then(() => {- setRevealApi(api);- setApi(api);- });-- // Reveal.js listens only to window resizes, not to the note pane changing size.- const resizeObserver = new ResizeObserver(() => {- if (api.isReady()) api.layout();- });- resizeObserver.observe(container);- const releaseKeyboard = keepKeyboardInPresentation(container);- const stopFollowingLinks = followSlideLinks(container, api);-- return () => {- stopFollowingLinks();- releaseKeyboard();- fitObserver.disconnect();- fitObserverRef.current = null;- resizeObserver.disconnect();- api.destroy();- setRevealApi(undefined);- setApi(undefined);- };- }, []);-- useEffect(() => {- const fitObserver = fitObserverRef.current;- if (!revealApi || !containerRef.current || !fitObserver) return;- const currentNoteId = getNoteIdFromSlide(revealApi.getCurrentSlide());- revealApi.sync();- if (currentNoteId) keepSlideShown(revealApi, currentNoteId);-- fitObserver.disconnect();- for (const content of containerRef.current.querySelectorAll(".slide-content")) {- fitObserver.observe(content);- }- }, [ presentation, revealApi, editedNoteId ]);-- // After the effect above, so that Reveal.js has synced the new slide.- useEffect(() => {- if (!revealApi || !newSlideNoteId) return;- if (!containerRef.current?.querySelector(`#slide-${newSlideNoteId}`)) return;- goToSlide(revealApi, newSlideNoteId);- onNewSlideShown(newSlideNoteId);- }, [ presentation, revealApi, newSlideNoteId ]);-- function renderSlide(slide: PresentationSlideBaseModel) {- const isEdited = slide.noteId === editedNoteId;- const canEdit = onEditSlide && !isEdited && !slide.isReadOnly- && (slide.type === "text" || slide.isCollection);- const closingContent = closingContents[slide.noteId];- return (- <Slide- key={slide.noteId}- 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}- isEditorReady={isEditorReady}- onEdit={canEdit ? () => {- if (!revealApi?.isOverview() && !document.fullscreenElement) onEditSlide(slide.noteId);- } : undefined}- />- );- }-- return (- <div ref={containerRef} className="reveal">- <div className="slides">- {presentation.slides?.map(slide => {- if (!slide.verticalSlides) {- return renderSlide(slide);- }- return (- <section key={`stack-${slide.noteId}`}>- {renderSlide(slide)}- {slide.verticalSlides.map(renderSlide)}- </section>- );-- })}- </div>- </div>- );--}--interface SlideProps {- slide: PresentationSlideBaseModel;- 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, 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;- const backgroundIframe = isElectron ? undefined : slide.webViewSrc;-- function renderContent() {- if (desktopWebViewSrc) return <DesktopWebView src={desktopWebViewSrc} ntxId={ntxId} />;- if (slide.isCollection) return <slot name={getCollectionSlotName(slide.noteId)} />;- // 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 (- <section- id={`slide-${slide.noteId}`}- data-note-id={slide.noteId}- className={desktopWebViewSrc ? "web-view-slide" : slide.isCollection ? "collection-slide" : undefined}- data-background-color={slide.backgroundColor}- data-background-gradient={slide.backgroundGradient}- data-background-iframe={backgroundIframe}- data-background-interactive={backgroundIframe ? "" : undefined}- onDblClick={editorHostRef ? undefined : onEdit}- >- {renderContent()}- </section>- );-}--/**- * Whether a key press goes to a field being typed in: the slide editor, or an input of a collection slide.- * Reveal.js checks `document.activeElement` for that, which is the shadow host rather than the field.- */-export function isTypingIn(event: Event) {- const target = event.composedPath()[0];- return target instanceof HTMLElement && (target.isContentEditable || target.matches("input, textarea, select"));-}--/**- * Whether a key press activates a focused button, such as a thumbnail in the sidebar. Reveal.js listens- * to the whole document, so it would otherwise also move to the next slide on the same Space.- */-export function isPressingButton(event: KeyboardEvent) {- const target = event.composedPath()[0];- return (event.key === " " || event.key === "Enter")- && target instanceof Element && target.closest("button") !== null;-}--function getNoteIdFromSlide(slide: HTMLElement | undefined) {- if (!slide) return;- return slide.dataset.noteId;-}--const FRAME_SELECTOR = "iframe, webview";--/**- * Takes the keyboard back whenever an iframe or `<webview>` in the slides gets focus, from a click or from- * the page focusing itself, so that Space and the arrow keys keep moving between slides. Clicks, links and- * wheel scrolling still reach the page. Chromium reports focus entering a frame as `focusin` on its- * element; Firefox only blurs the window, so the frame is then found as the active element.- */-export function keepKeyboardInPresentation(container: HTMLElement) {- const returnFocus = (frame: HTMLElement) => {- frame.blur();- window.focus();- };- const onFocusIn = (e: Event) => {- if (e.target instanceof HTMLElement && e.target.matches(FRAME_SELECTOR)) returnFocus(e.target);- };- const onWindowBlur = () => {- // The frame becomes the active element only after the window's `blur` is dispatched.- setTimeout(() => {- const active = (container.getRootNode() as Document | ShadowRoot).activeElement;- if (active instanceof HTMLElement && active.matches(FRAME_SELECTOR) && container.contains(active)) {- returnFocus(active);- }- });- };-- container.addEventListener("focusin", onFocusIn);- window.addEventListener("blur", onWindowBlur);- return () => {- container.removeEventListener("focusin", onFocusIn);- window.removeEventListener("blur", onWindowBlur);- };-}--/**- * Moves to the slide that a clicked link in `container` points at, including the links of content- * rendered after this starts. Returns the function that stops it.- *- * Reveal.js navigates by slide ID on its own, but looks the slide up with- * `document.getElementById()`, which does not find it inside the shadow root.- */-export function followSlideLinks(container: HTMLElement, api: RevealApi) {- const onClick = (e: MouseEvent) => {- const link = e.target instanceof Element- ? e.target.closest<HTMLAnchorElement>("a.reference-link")- : null;- if (!link) return;- const url = new URL(link.href);- if (!url.hash.startsWith("#/slide-")) return;- goToSlide(api, url.hash.substring(8));- };-- container.addEventListener("click", onClick);- return () => container.removeEventListener("click", onClick);-}--/**- * Shows the slide of the note `noteId` again after the slides were reordered, as Reveal.js keeps the- * position of the slide it showed rather than the slide, and points Reveal.js at the slide's section- * when a change of level built it anew.- */-export function keepSlideShown(api: RevealApi, noteId: string) {- const slide = api.getRevealElement()?.querySelector<HTMLElement>(`#slide-${noteId}`);- if (!slide) return;- const { h, v } = api.getIndices(slide);- const current = api.getIndices();- // `sync()` does not update the current slide that `getCurrentSlide()` returns, but `slide()` does.- if (h !== current.h || v !== current.v || api.getCurrentSlide() !== slide) api.slide(h, v);-}--/**- * Moves to the slide of the note `noteId`, if it is a slide. The slide is looked up in the- * `.reveal` element, as `document.getElementById()` does not reach into the shadow root.- */-export function goToSlide(api: RevealApi, noteId: string) {- const slide = api.getRevealElement()?.querySelector<HTMLElement>(`#slide-${noteId}`);- if (!slide) return;-- const { h, v, f } = api.getIndices(slide);- api.slide(h, v, f);-}diff --git a/apps/client/src/widgets/collections/presentation/index.spec.ts b/apps/client/src/widgets/collections/presentation/reveal.spec.tssimilarity index 61%rename from apps/client/src/widgets/collections/presentation/index.spec.tsrename to apps/client/src/widgets/collections/presentation/reveal.spec.tsindex 4e5ed68f7f..3054f8254f 100644--- a/apps/client/src/widgets/collections/presentation/index.spec.ts+++ b/apps/client/src/widgets/collections/presentation/reveal.spec.ts@@ -1,109 +1,9 @@import type { RevealApi } from "reveal.js";import { afterEach, describe, expect, it, vi } from "vitest";-import { createFitObserver, fitSlideContent } from "./fit";import {followSlideLinks, goToSlide, isPressingButton, keepKeyboardInPresentation, keepSlideShown-} from "./index";--describe("fitSlideContent", () => {- it("zooms out only the content that is larger than the slide", () => {- const tall = buildContent({ height: zoom => 2 * zoom });- fitSlideContent(tall);- expect(Number(tall.style.zoom)).toBeCloseTo(0.5);-- // A second fit measures the content without the zoom it already has.- fitSlideContent(tall);- expect(Number(tall.style.zoom)).toBeCloseTo(0.5);-- const wide = buildContent({ width: zoom => 2 * zoom });- fitSlideContent(wide);- expect(Number(wide.style.zoom)).toBeCloseTo(0.5);-- const fitting = buildContent({ height: () => 1 });- fitting.style.zoom = "0.5";- fitSlideContent(fitting);- expect(fitting.style.zoom).toBe("");-- const hidden = buildContent({ height: () => 0, hidden: true });- fitSlideContent(hidden);- expect(hidden.style.zoom).toBe("");- });-- it("fits content with parts that do not scale with the zoom", () => {- // Text as tall as the slide plus an image half as tall, which keeps its height.- const content = buildContent({ height: zoom => zoom + 0.5 });- fitSlideContent(content);- expect(Number(content.style.zoom)).toBeCloseTo(0.5);- expect(Number(content.style.zoom) + 0.5).toBeLessThanOrEqual(1);- });-- it("stops zooming out when the zoom barely shrinks the overflow", () => {- // A table editor's column resizer, 3px past a full-width table, overflows by the same share at- // any zoom; the secant step would place the fit at a zoom of almost nothing.- const content = buildContent({ width: zoom => 1 + 0.00234 * zoom });- fitSlideContent(content);- expect(Number(content.style.zoom)).toBeGreaterThan(0.99);- });-});--describe("createFitObserver", () => {- it("fits again when the size changes, but not for the size its own fit leaves", () => {- let notify: ResizeObserverCallback = () => {};- vi.stubGlobal("ResizeObserver", class {- constructor(callback: ResizeObserverCallback) { notify = callback; }- disconnect() {}- });-- let naturalHeight = 2;- const content = buildContent({ height: zoom => naturalHeight * zoom });- const onFitted = vi.fn();- const observer = createFitObserver(onFitted);- const resize = () => notify([ { target: content } as unknown as ResizeObserverEntry ], observer);-- resize();- expect(Number(content.style.zoom)).toBeCloseTo(0.5);- expect(onFitted).toHaveBeenCalledTimes(1);-- // The notification for the zoom the fit applied.- resize();- expect(onFitted).toHaveBeenCalledTimes(1);-- // A stylesheet makes the content taller.- naturalHeight = 4;- resize();- expect(Number(content.style.zoom)).toBeCloseTo(0.25);- expect(onFitted).toHaveBeenCalledTimes(2);-- vi.unstubAllGlobals();- });-});--interface ContentSize {- /** The height relative to the slide's, for a given zoom. */- height?: (zoom: number) => number;- /** The scrolled width relative to the slide's, for a given zoom. */- width?: (zoom: number) => number;- hidden?: boolean;-}--/** Builds slide content whose measured size follows its zoom, as it does in a browser. */-function buildContent({ height = () => 1, width = () => 1, hidden }: ContentSize) {- const slides = document.createElement("div");- slides.className = "slides";- const content = document.createElement("div");- slides.appendChild(content);-- const zoom = () => Number(content.style.zoom || 1);- const clientWidth = hidden ? 0 : 1280;- slides.getBoundingClientRect = () => DOMRect.fromRect({ width: 640, height: 360 });- content.getBoundingClientRect = () => DOMRect.fromRect({ width: 640, height: 360 * height(zoom()) });- Object.defineProperty(content, "clientWidth", { get: () => clientWidth });- Object.defineProperty(content, "scrollWidth", { get: () => clientWidth * width(zoom()) });- Object.defineProperty(content, "offsetWidth", { get: () => clientWidth });- Object.defineProperty(content, "offsetHeight", { get: () => 720 * height(zoom()) });- return content;-}+} from "./reveal";describe("keepKeyboardInPresentation", () => {afterEach(() => {diff --git a/apps/client/src/widgets/collections/presentation/reveal.ts b/apps/client/src/widgets/collections/presentation/reveal.tsnew file mode 100644index 0000000000..04ccc291af--- /dev/null+++ b/apps/client/src/widgets/collections/presentation/reveal.ts@@ -0,0 +1,121 @@+import { useEffect, useState } from "preact/hooks";+import type { RevealApi } from "reveal.js";++/** Returns the note ID of the slide that Reveal.js shows. */+export function useActiveSlideNoteId(api: RevealApi | undefined) {+ const [ activeNoteId, setActiveNoteId ] = useState<string>();+ useEffect(() => {+ if (!api) return;+ const update = () => setActiveNoteId(getNoteIdFromSlide(api.getCurrentSlide()));+ update();+ api.on("slidechanged", update);+ return () => api.off("slidechanged", update);+ }, [ api ]);+ return activeNoteId;+}++/**+ * Whether a key press goes to a field being typed in: the slide editor, or an input of a collection slide.+ * Reveal.js checks `document.activeElement` for that, which is the shadow host rather than the field.+ */+export function isTypingIn(event: Event) {+ const target = event.composedPath()[0];+ return target instanceof HTMLElement && (target.isContentEditable || target.matches("input, textarea, select"));+}++/**+ * Whether a key press activates a focused button, such as a thumbnail in the sidebar. Reveal.js listens+ * to the whole document, so it would otherwise also move to the next slide on the same Space.+ */+export function isPressingButton(event: KeyboardEvent) {+ const target = event.composedPath()[0];+ return (event.key === " " || event.key === "Enter")+ && target instanceof Element && target.closest("button") !== null;+}++export function getNoteIdFromSlide(slide: HTMLElement | undefined) {+ if (!slide) return;+ return slide.dataset.noteId;+}++const FRAME_SELECTOR = "iframe, webview";++/**+ * Takes the keyboard back whenever an iframe or `<webview>` in the slides gets focus, from a click or from+ * the page focusing itself, so that Space and the arrow keys keep moving between slides. Clicks, links and+ * wheel scrolling still reach the page. Chromium reports focus entering a frame as `focusin` on its+ * element; Firefox only blurs the window, so the frame is then found as the active element.+ */+export function keepKeyboardInPresentation(container: HTMLElement) {+ const returnFocus = (frame: HTMLElement) => {+ frame.blur();+ window.focus();+ };+ const onFocusIn = (e: Event) => {+ if (e.target instanceof HTMLElement && e.target.matches(FRAME_SELECTOR)) returnFocus(e.target);+ };+ const onWindowBlur = () => {+ // The frame becomes the active element only after the window's `blur` is dispatched.+ setTimeout(() => {+ const active = (container.getRootNode() as Document | ShadowRoot).activeElement;+ if (active instanceof HTMLElement && active.matches(FRAME_SELECTOR) && container.contains(active)) {+ returnFocus(active);+ }+ });+ };++ container.addEventListener("focusin", onFocusIn);+ window.addEventListener("blur", onWindowBlur);+ return () => {+ container.removeEventListener("focusin", onFocusIn);+ window.removeEventListener("blur", onWindowBlur);+ };+}++/**+ * Moves to the slide that a clicked link in `container` points at, including the links of content+ * rendered after this starts. Returns the function that stops it.+ *+ * Reveal.js navigates by slide ID on its own, but looks the slide up with+ * `document.getElementById()`, which does not find it inside the shadow root.+ */+export function followSlideLinks(container: HTMLElement, api: RevealApi) {+ const onClick = (e: MouseEvent) => {+ const link = e.target instanceof Element+ ? e.target.closest<HTMLAnchorElement>("a.reference-link")+ : null;+ if (!link) return;+ const url = new URL(link.href);+ if (!url.hash.startsWith("#/slide-")) return;+ goToSlide(api, url.hash.substring(8));+ };++ container.addEventListener("click", onClick);+ return () => container.removeEventListener("click", onClick);+}++/**+ * Shows the slide of the note `noteId` again after the slides were reordered, as Reveal.js keeps the+ * position of the slide it showed rather than the slide, and points Reveal.js at the slide's section+ * when a change of level built it anew.+ */+export function keepSlideShown(api: RevealApi, noteId: string) {+ const slide = api.getRevealElement()?.querySelector<HTMLElement>(`#slide-${noteId}`);+ if (!slide) return;+ const { h, v } = api.getIndices(slide);+ const current = api.getIndices();+ // `sync()` does not update the current slide that `getCurrentSlide()` returns, but `slide()` does.+ if (h !== current.h || v !== current.v || api.getCurrentSlide() !== slide) api.slide(h, v);+}++/**+ * Moves to the slide of the note `noteId`, if it is a slide. The slide is looked up in the+ * `.reveal` element, as `document.getElementById()` does not reach into the shadow root.+ */+export function goToSlide(api: RevealApi, noteId: string) {+ const slide = api.getRevealElement()?.querySelector<HTMLElement>(`#slide-${noteId}`);+ if (!slide) return;++ const { h, v, f } = api.getIndices(slide);+ api.slide(h, v, f);+}diff --git a/apps/client/src/widgets/collections/presentation/sidebar.spec.tsx b/apps/client/src/widgets/collections/presentation/sidebar.spec.tsxindex 62cea1b5ff..89c8f8f1ab 100644--- a/apps/client/src/widgets/collections/presentation/sidebar.spec.tsx+++ b/apps/client/src/widgets/collections/presentation/sidebar.spec.tsx@@ -387,7 +387,7 @@ function getButton(sidebar: HTMLElement, noteId: string) {describe("useActiveSlideNoteId", () => {it("follows the slide that Reveal.js shows", async () => {- const { useActiveSlideNoteId } = await import("./index");+ const { useActiveSlideNoteId } = await import("./reveal");const listeners: (() => void)[] = [];let current = buildSection("intro");const api = {diff --git a/apps/client/src/widgets/collections/presentation/slide.spec.tsx b/apps/client/src/widgets/collections/presentation/slide.spec.tsxindex 5b0c3a0590..87fb3ea96d 100644--- a/apps/client/src/widgets/collections/presentation/slide.spec.tsx+++ b/apps/client/src/widgets/collections/presentation/slide.spec.tsx@@ -42,7 +42,7 @@ async function renderSlide({ isElectron }: { isElectron: boolean }) {const actual = await importOriginal<typeof import("../../../services/utils")>();return { ...actual, default: { ...actual.default, isElectron: () => isElectron }, isElectron: () => isElectron };});- const { Slide } = await import("./index");+ const { Slide } = await import("./slides");const container = document.createElement("div");render(<Slide slide={webViewSlide} ntxId={undefined} />, container);@@ -67,7 +67,7 @@ describe("collection slides", () => {}}));const { buildNote } = await import("../../../test/easy-froca");- const { CollectionSlides, Slide } = await import("./index");+ const { CollectionSlides, Slide } = await import("./slides");buildNote({ id: "board", title: "Board", type: "book", "#viewType": "board" });buildNote({ id: "table", title: "Table", type: "book", "#viewType": "table" });const boardSlide: PresentationSlideBaseModel = { noteId: "board", type: "book", content: { __html: "" }, isCollection: true };@@ -112,7 +112,7 @@ describe("collection slides", () => {});it("leaves the keys of a field being typed in to the field", async () => {- const { isTypingIn } = await import("./index");+ const { isTypingIn } = await import("./reveal");const keyFrom = (element: HTMLElement) => {let typing: boolean | undefined;element.addEventListener("keydown", (e) => { typing = isTypingIn(e); });diff --git a/apps/client/src/widgets/collections/presentation/slides.tsx b/apps/client/src/widgets/collections/presentation/slides.tsxnew file mode 100644index 0000000000..5f529ce78f--- /dev/null+++ b/apps/client/src/widgets/collections/presentation/slides.tsx@@ -0,0 +1,261 @@+import { lazy, Suspense } from "preact/compat";+import { useEffect, useRef, useState } from "preact/hooks";+import Reveal, { RevealApi } from "reveal.js";++import froca from "../../../services/froca";+import utils from "../../../services/utils";+import { DesktopWebView } from "../../type_widgets/WebView";+import { SlideContent } from "./closing_slides";+import { createFitObserver } from "./fit";+import { PresentationModel, PresentationSlideBaseModel } from "./model";+import {+ followSlideLinks, getNoteIdFromSlide, goToSlide, isPressingButton, isTypingIn, keepKeyboardInPresentation,+ keepSlideShown+} from "./reveal";++const SLIDE_WIDTH = 1280;+const SLIDE_HEIGHT = 720;+const isElectron = utils.isElectron();+const EmbeddedNoteList = lazy(() => import("../NoteList").then(({ EmbeddedNoteList }) => ({ default: EmbeddedNoteList })));++interface PresentationProps {+ presentation: PresentationModel;+ setApi: (api: RevealApi | undefined) => void;+ 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;+ /** 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;+ /** The note of a slide just added, to go to once Reveal.js has it. */+ newSlideNoteId: string | undefined;+ /** Called once the presentation shows the slide of `newSlideNoteId`. */+ onNewSlideShown: (noteId: string) => void;+}++export function Presentation({+ presentation, setApi, ntxId, editedNoteId, isEditorReady, closingContents, onEditSlide,+ onEditorHost, newSlideNoteId, onNewSlideShown+}: PresentationProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const [revealApi, setRevealApi] = useState<RevealApi>();+ const fitObserverRef = useRef<ResizeObserver>(null);++ useEffect(() => {+ if (!containerRef.current) return;++ const api = new Reveal(containerRef.current, {+ transition: "slide",+ embedded: true,+ // Must match the aspect ratio of `.reveal` in slidejs.css.+ width: SLIDE_WIDTH,+ height: SLIDE_HEIGHT,+ minScale: 0,+ maxScale: Infinity,+ pdfMaxPagesPerSlide: 1,+ keyboardCondition(event) {+ // Full-screen requests sometimes fail, we rely on the UI button instead.+ if (event.key === "f") {+ return false;+ }++ return !isTypingIn(event) && !isPressingButton(event);+ },+ });+ const container = containerRef.current;+ const fitObserver = createFitObserver(() => {+ if (api.isReady()) api.layout();+ });+ fitObserverRef.current = fitObserver;++ api.initialize().then(() => {+ setRevealApi(api);+ setApi(api);+ });++ // Reveal.js listens only to window resizes, not to the note pane changing size.+ const resizeObserver = new ResizeObserver(() => {+ if (api.isReady()) api.layout();+ });+ resizeObserver.observe(container);+ const releaseKeyboard = keepKeyboardInPresentation(container);+ const stopFollowingLinks = followSlideLinks(container, api);++ return () => {+ stopFollowingLinks();+ releaseKeyboard();+ fitObserver.disconnect();+ fitObserverRef.current = null;+ resizeObserver.disconnect();+ api.destroy();+ setRevealApi(undefined);+ setApi(undefined);+ };+ }, []);++ useEffect(() => {+ const fitObserver = fitObserverRef.current;+ if (!revealApi || !containerRef.current || !fitObserver) return;+ const currentNoteId = getNoteIdFromSlide(revealApi.getCurrentSlide());+ revealApi.sync();+ if (currentNoteId) keepSlideShown(revealApi, currentNoteId);++ fitObserver.disconnect();+ for (const content of containerRef.current.querySelectorAll(".slide-content")) {+ fitObserver.observe(content);+ }+ }, [ presentation, revealApi, editedNoteId ]);++ // After the effect above, so that Reveal.js has synced the new slide.+ useEffect(() => {+ if (!revealApi || !newSlideNoteId) return;+ if (!containerRef.current?.querySelector(`#slide-${newSlideNoteId}`)) return;+ goToSlide(revealApi, newSlideNoteId);+ onNewSlideShown(newSlideNoteId);+ }, [ presentation, revealApi, newSlideNoteId ]);++ function renderSlide(slide: PresentationSlideBaseModel) {+ const isEdited = slide.noteId === editedNoteId;+ const canEdit = onEditSlide && !isEdited && !slide.isReadOnly+ && (slide.type === "text" || slide.isCollection);+ const closingContent = closingContents[slide.noteId];+ return (+ <Slide+ key={slide.noteId}+ 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}+ isEditorReady={isEditorReady}+ onEdit={canEdit ? () => {+ if (!revealApi?.isOverview() && !document.fullscreenElement) onEditSlide(slide.noteId);+ } : undefined}+ />+ );+ }++ return (+ <div ref={containerRef} className="reveal">+ <div className="slides">+ {presentation.slides?.map(slide => {+ if (!slide.verticalSlides) {+ return renderSlide(slide);+ }+ return (+ <section key={`stack-${slide.noteId}`}>+ {renderSlide(slide)}+ {slide.verticalSlides.map(renderSlide)}+ </section>+ );++ })}+ </div>+ </div>+ );++}++interface SlideProps {+ slide: PresentationSlideBaseModel;+ 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, 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;+ const backgroundIframe = isElectron ? undefined : slide.webViewSrc;++ function renderContent() {+ if (desktopWebViewSrc) return <DesktopWebView src={desktopWebViewSrc} ntxId={ntxId} />;+ if (slide.isCollection) return <slot name={getCollectionSlotName(slide.noteId)} />;+ // 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 (+ <section+ id={`slide-${slide.noteId}`}+ data-note-id={slide.noteId}+ className={desktopWebViewSrc ? "web-view-slide" : slide.isCollection ? "collection-slide" : undefined}+ data-background-color={slide.backgroundColor}+ data-background-gradient={slide.backgroundGradient}+ data-background-iframe={backgroundIframe}+ data-background-interactive={backgroundIframe ? "" : undefined}+ onDblClick={editorHostRef ? undefined : onEdit}+ >+ {renderContent()}+ </section>+ );+}++interface CollectionSlidesProps {+ presentation: PresentationModel;+ ntxId: string | null | undefined;+ /** The note of the slide being edited, whose collection alone can be changed and open its notes. */+ editedNoteId: string | undefined;+ onOpenNote: ((noteId: string) => void) | undefined;+}++/**+ * Renders the collection of each collection slide with the app's own note list, as children of the shadow+ * host that its slide's `<slot>` shows. Outside the shadow root, the document's stylesheets style the+ * collection and the slide's theme does not; the collection is still drawn, scaled and moved with its slide.+ */+export function CollectionSlides({ presentation, ntxId, editedNoteId, onOpenNote }: CollectionSlidesProps) {+ const slides = presentation.slides.flatMap(slide => [ slide, ...slide.verticalSlides ?? [] ]);+ return (+ <>+ {slides.filter(slide => slide.isCollection).map(slide => {+ const note = froca.getNoteFromCache(slide.noteId);+ if (!note) return null;+ const isEdited = slide.noteId === editedNoteId;+ return (+ <div+ key={slide.noteId}+ slot={getCollectionSlotName(slide.noteId)}+ className={`presentation-collection-slide ${isEdited ? "is-edited" : ""}`}+ >+ <Suspense fallback={null}>+ <EmbeddedNoteList+ note={note}+ notePath={note.getBestNotePathString()}+ ntxId={ntxId}+ media="screen"+ isReadOnly={!isEdited}+ // Opening a note leaves the presentation, or opens a popup that full-screen hides.+ onOpenNote={isEdited ? onOpenNote : ignoreOpenNote}+ />+ </Suspense>+ </div>+ );+ })}+ </>+ );+}++function ignoreOpenNote() {}++function getCollectionSlotName(noteId: string) {+ return `collection-${noteId}`;+}