Skip to content

Build your personal knowledge base with Trilium Notes

chore(presentation): cover editing slides from the view

Elian Doran0d3814ef2355
diff --git a/apps/client/src/widgets/collections/presentation/closing_slides.spec.ts b/apps/client/src/widgets/collections/presentation/closing_slides.spec.ts
new file mode 100644
index 0000000000..6f52f02a8c
--- /dev/null
+++ b/apps/client/src/widgets/collections/presentation/closing_slides.spec.ts
@@ -0,0 +1,96 @@
+import { h, render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import FNote from "../../../entities/fnote";
+import { buildNote } from "../../../test/easy-froca";
+import { useClosingSlides } from "./closing_slides";
+import { renderSlideContent } from "./model";
+
+vi.mock("./model", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./model")>(),
+ renderSlideContent: vi.fn(async (_note: FNote, content: string) => ({ __html: `<p>${content}</p>` }))
+}));
+
+describe("useClosingSlides", () => {
+ afterEach(() => {
+ document.body.replaceChildren();
+ });
+
+ function renderHook() {
+ const refresh = vi.fn();
+ let closing: ReturnType<typeof useClosingSlides> | undefined;
+ const Probe = () => {
+ closing = useClosingSlides(refresh);
+ return null;
+ };
+ act(() => render(h(Probe, {}), document.createElement("div")));
+ const current = () => {
+ if (!closing) throw new Error("The hook did not render.");
+ return closing;
+ };
+ return { refresh, current };
+ }
+
+ function deferred() {
+ let resolve: (isSaved: boolean) => void = () => {};
+ const promise = new Promise<boolean>((r) => { resolve = r; });
+ return { promise, resolve };
+ }
+
+ it("shows the closed editor's content until a model built after the save applies", async () => {
+ const note = buildNote({ title: "Slide" });
+ const { refresh, current } = renderHook();
+ const save = deferred();
+
+ await act(async () => current().onEditorClose(note, "typed", save.promise));
+ expect(renderSlideContent).toHaveBeenCalledWith(note, "typed");
+ expect(current().contents).toStrictEqual({ [note.noteId]: { __html: "<p>typed</p>" } });
+ // A model built while the save runs does not hold it yet.
+ expect(current().getSaved()).toStrictEqual([]);
+
+ await act(async () => save.resolve(true));
+ expect(refresh).toHaveBeenCalledOnce();
+ const saved = current().getSaved();
+ expect(saved.map(([ noteId ]) => noteId)).toStrictEqual([ note.noteId ]);
+
+ act(() => current().release(saved));
+ expect(current().contents).toStrictEqual({});
+ expect(current().getSaved()).toStrictEqual([]);
+ });
+
+ it("keeps the content after a failed save until the next model, without building one", async () => {
+ const note = buildNote({ title: "Slide" });
+ const { refresh, current } = renderHook();
+
+ await act(async () => current().onEditorClose(note, "typed", Promise.resolve(false)));
+ expect(refresh).not.toHaveBeenCalled();
+ expect(current().contents[note.noteId]).toStrictEqual({ __html: "<p>typed</p>" });
+
+ act(() => current().release(current().getSaved()));
+ expect(current().contents).toStrictEqual({});
+ });
+
+ it("follows only the last editor of a slide closed twice", async () => {
+ const note = buildNote({ title: "Slide" });
+ const { refresh, current } = renderHook();
+ const first = deferred();
+ let renderFirst: (html: { __html: string }) => void = () => {};
+ vi.mocked(renderSlideContent).mockImplementationOnce(() => new Promise((r) => { renderFirst = r; }));
+
+ await act(async () => current().onEditorClose(note, "first", first.promise));
+ await act(async () => current().onEditorClose(note, "second", new Promise(() => {})));
+
+ // The first editor's render and save land after the second closed, and change nothing.
+ await act(async () => {
+ renderFirst({ __html: "<p>first</p>" });
+ first.resolve(true);
+ });
+ expect(current().contents[note.noteId]).toStrictEqual({ __html: "<p>second</p>" });
+ expect(refresh).not.toHaveBeenCalled();
+
+ // A release of an editor that is no longer the slide's keeps its content.
+ act(() => current().release([ [ note.noteId, { isSaving: false } ] ]));
+ expect(current().contents[note.noteId]).toStrictEqual({ __html: "<p>second</p>" });
+ });
+});
diff --git a/apps/client/src/widgets/collections/presentation/index.spec.tsx b/apps/client/src/widgets/collections/presentation/index.spec.tsx
index 577c7a7bec..e7e7468381 100644
--- a/apps/client/src/widgets/collections/presentation/index.spec.tsx
+++ b/apps/client/src/widgets/collections/presentation/index.spec.tsx
@@ -1,6 +1,8 @@
import { act } from "preact/test-utils";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import type { RevealApi } from "reveal.js";
+import { afterEach, describe, expect, it, type Mock, vi } from "vitest";
+import appContext from "../../../components/app_context";
import Component from "../../../components/component";
import NoteContext from "../../../components/note_context";
import FNote from "../../../entities/fnote";
@@ -10,8 +12,19 @@ import options from "../../../services/options";
import { buildNote } from "../../../test/easy-froca";
import { renderInto } from "../../../test/render";
import { NoteContextContext, ParentComponent } from "../../react/react_utils";
+import type { ViewModeMedia } from "../interface";
import PresentationView from "./index";
-import { buildPresentationModel } from "./model";
+import {
+ buildPresentationModel, createSlide, deleteSlide, duplicateSlide, getNewSlideTypes, moveSlideNote,
+ type PresentationModel, type SlideMove
+} from "./model";
+import type SlideSidebar from "./sidebar";
+import type SlideEditor from "./slide_editor";
+import type { Presentation } from "./slides";
+
+type PresentationProps = Parameters<typeof Presentation>[0];
+type SlideSidebarProps = Parameters<typeof SlideSidebar>[0];
+type SlideEditorProps = Parameters<typeof SlideEditor>[0];
// i18next is never initialized under test, so `t()` looks keys up in the English catalog itself.
vi.mock("../../../services/i18n", async (importOriginal) => {
@@ -26,9 +39,45 @@ vi.mock("../../../services/i18n", async (importOriginal) => {
vi.mock("./model", async (importOriginal) => {
const actual = await importOriginal<typeof import("./model")>();
- return { ...actual, buildPresentationModel: vi.fn(actual.buildPresentationModel) };
+ return {
+ ...actual,
+ buildPresentationModel: vi.fn(actual.buildPresentationModel),
+ createSlide: vi.fn(actual.createSlide),
+ duplicateSlide: vi.fn(actual.duplicateSlide),
+ deleteSlide: vi.fn(actual.deleteSlide),
+ moveSlideNote: vi.fn(actual.moveSlideNote)
+ };
});
+/** The props of the stubbed slides, sidebar and slide editor, as they last rendered. */
+const rendered = vi.hoisted(() => ({
+ slides: undefined as PresentationProps | undefined,
+ sidebar: undefined as SlideSidebarProps | undefined,
+ editor: undefined as SlideEditorProps | undefined
+}));
+
+vi.mock("./slides", () => ({
+ Presentation: (props: PresentationProps) => {
+ rendered.slides = props;
+ return null;
+ },
+ CollectionSlides: () => null
+}));
+
+vi.mock("./sidebar", () => ({
+ default: (props: SlideSidebarProps) => {
+ rendered.sidebar = props;
+ return null;
+ }
+}));
+
+vi.mock("./slide_editor", () => ({
+ default: (props: SlideEditorProps) => {
+ rendered.editor = props;
+ return null;
+ }
+}));
+
vi.mock("./themes", async (importOriginal) => ({
...await importOriginal<typeof import("./themes")>(),
loadPresentationTheme: async () => ""
@@ -123,9 +172,236 @@ describe("reloading the presentation", () => {
});
});
+describe("changing slides from the view", () => {
+ const actualBuild = vi.mocked(buildPresentationModel).getMockImplementation();
+
+ afterEach(() => {
+ vi.mocked(buildPresentationModel).mockImplementation(actualBuild ?? (async () => ({ slides: [] })));
+ vi.restoreAllMocks();
+ rendered.slides = undefined;
+ rendered.sidebar = undefined;
+ rendered.editor = undefined;
+ });
+
+ /** Renders a deck of a slide with a vertical slide below it and a second slide, on a stubbed Reveal.js. */
+ async function renderDeck() {
+ options.set("presentationSidebarVisible", "true");
+ for (const id of [ "first", "below", "second", "added" ]) buildNote({ id, title: id, type: "text" });
+ const note = buildNote({ title: "Deck", type: "book", "#viewType": "presentation" });
+ const model: PresentationModel = { slides: [
+ { noteId: "first", type: "text", content: { __html: "" }, verticalSlides: [
+ { noteId: "below", type: "text", content: { __html: "" } }
+ ] },
+ { noteId: "second", type: "text", content: { __html: "" }, verticalSlides: undefined }
+ ] };
+ vi.mocked(buildPresentationModel).mockImplementation(async () => model);
+ const onReady = vi.fn();
+ renderPresentation(note, onReady);
+ const slides = await vi.waitFor(() => {
+ expect(rendered.slides?.presentation).toBe(model);
+ return rendered.slides as PresentationProps;
+ });
+
+ const reveal = createReveal([ "first", "below", "second", "added" ]);
+ act(() => slides.setApi(reveal.api));
+ await vi.waitFor(() => expect(onReady).toHaveBeenCalled());
+ return { note, model, reveal, props: () => rendered.slides as PresentationProps, sidebar: () => rendered.sidebar as SlideSidebarProps };
+ }
+
+ it("edits a slide from its menu, and finishes when another slide, the overview or full-screen shows", async () => {
+ const { reveal, props, sidebar } = await renderDeck();
+ const edit = (noteId: string) => act(() => sidebar().slideMenuActions?.onEdit?.(noteId));
+
+ reveal.isOverview = true;
+ edit("second");
+ expect(reveal.api.toggleOverview).toHaveBeenCalledWith(false);
+ expect(reveal.api.slide).toHaveBeenLastCalledWith(2, 0, undefined);
+ expect(props().editedNoteId).toBe("second");
+ expect(props().isEditorReady).toBe(false);
+
+ // The editor mounts in the host that the slide gives it.
+ const host = document.createElement("div");
+ act(() => props().onEditorHost(host));
+ const editor = await vi.waitFor(() => {
+ expect(rendered.editor?.note.noteId).toBe("second");
+ return rendered.editor as SlideEditorProps;
+ });
+ act(() => editor.onReady());
+ expect(props().isEditorReady).toBe(true);
+ act(() => editor.onClose("<p>typed</p>", new Promise(() => {})));
+
+ // Moving within the edited slide keeps the edit, and another slide ends it.
+ act(() => reveal.emit("slidechanged", "second"));
+ expect(props().editedNoteId).toBe("second");
+ act(() => reveal.emit("slidechanged", "first"));
+ expect(props().editedNoteId).toBeUndefined();
+
+ edit("first");
+ act(() => reveal.emit("overviewshown"));
+ expect(props().editedNoteId).toBeUndefined();
+ edit("first");
+ act(() => { document.dispatchEvent(new Event("fullscreenchange")); });
+ expect(props().editedNoteId).toBeUndefined();
+ });
+
+ it("goes to an added or duplicated slide, and starts editing it as its type asks", async () => {
+ const { note, props, sidebar } = await renderDeck();
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockImplementation(async () => {});
+ const changes = () => {
+ const found = sidebar().slideMenuActions?.changes;
+ expect(found).toBeDefined();
+ return found as NonNullable<NonNullable<SlideSidebarProps["slideMenuActions"]>["changes"]>;
+ };
+ const types = getNewSlideTypes().flat();
+ const text = types.find(type => type.type === "text");
+ const mermaid = types.find(type => type.type === "mermaid");
+ if (!text || !mermaid) throw new Error("The text and Mermaid slide types are missing.");
+
+ vi.mocked(createSlide).mockResolvedValueOnce("added").mockResolvedValueOnce("added");
+ await act(async () => changes().addSlideAfter("first", text));
+ expect(createSlide).toHaveBeenLastCalledWith({ parentNoteId: note.noteId, afterNoteId: "first" }, "text", undefined);
+ expect(props().pendingNoteId).toBe("added");
+ act(() => props().onPendingSlideShown("added"));
+ expect(props().pendingNoteId).toBeUndefined();
+ expect(props().editedNoteId).toBe("added");
+
+ await act(async () => changes().addVerticalSlide("first", mermaid));
+ expect(createSlide).toHaveBeenLastCalledWith({ parentNoteId: "first", afterNoteId: "below" }, mermaid.type, mermaid.mime);
+ act(() => props().onPendingSlideShown("added"));
+ expect(triggerCommand).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: "added" });
+
+ vi.mocked(duplicateSlide).mockResolvedValueOnce("added");
+ await act(async () => changes().duplicate("second"));
+ expect(props().pendingNoteId).toBe("added");
+ act(() => props().onPendingSlideShown("added"));
+ expect(props().pendingNoteId).toBeUndefined();
+ expect(triggerCommand).toHaveBeenCalledOnce();
+
+ // A slide that was not created leaves nothing to go to.
+ vi.mocked(createSlide).mockResolvedValueOnce(undefined);
+ vi.mocked(duplicateSlide).mockResolvedValueOnce(undefined);
+ await act(async () => changes().addSlideAfter("first", text));
+ await act(async () => changes().duplicate("second"));
+ expect(props().pendingNoteId).toBeUndefined();
+ });
+
+ it("finishes editing a deleted slide, or one below it", async () => {
+ const { props, sidebar } = await renderDeck();
+ const remove = (noteId: string) => act(async () => sidebar().slideMenuActions?.changes?.delete(noteId));
+ const edit = (noteId: string) => act(() => sidebar().slideMenuActions?.onEdit?.(noteId));
+
+ vi.mocked(deleteSlide).mockResolvedValueOnce(true).mockResolvedValueOnce(true).mockResolvedValueOnce(true);
+ edit("second");
+ await remove("first");
+ expect(props().editedNoteId).toBe("second");
+ await remove("second");
+ expect(props().editedNoteId).toBeUndefined();
+
+ edit("below");
+ await remove("first");
+ expect(props().editedNoteId).toBeUndefined();
+
+ // A slide that was not deleted keeps its edit.
+ vi.mocked(deleteSlide).mockResolvedValueOnce(false);
+ edit("second");
+ await remove("second");
+ expect(props().editedNoteId).toBe("second");
+ });
+
+ it("moves a slide at once, and builds the slides again when the server does not follow", async () => {
+ const { props, sidebar, model } = await renderDeck();
+ const move: SlideMove = { noteId: "second", targetNoteId: "first", position: "before" };
+ const order = () => props().presentation.slides.map(slide => slide.noteId);
+ expect(sidebar().planSlideMove?.("second", 0, 0)).toBeDefined();
+
+ let confirm: (isMoved: boolean) => void = () => {};
+ vi.mocked(moveSlideNote).mockImplementationOnce(() => new Promise((resolve) => { confirm = resolve; }));
+ const builds = vi.mocked(buildPresentationModel).mock.calls.length;
+ act(() => sidebar().onMoveSlide?.(move));
+ expect(order()).toStrictEqual([ "second", "first" ]);
+ await act(async () => confirm(true));
+ expect(buildPresentationModel).toHaveBeenCalledTimes(builds);
+
+ // A rejected move puts back the model that the server holds.
+ vi.mocked(moveSlideNote).mockResolvedValueOnce(false);
+ await act(async () => sidebar().onMoveSlide?.(move));
+ expect(buildPresentationModel).toHaveBeenCalledTimes(builds + 1);
+ await vi.waitFor(() => expect(order()).toStrictEqual(model.slides.map(slide => slide.noteId)));
+
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ vi.mocked(moveSlideNote).mockRejectedValueOnce(new Error("offline"));
+ await act(async () => sidebar().onMoveSlide?.(move));
+ expect(buildPresentationModel).toHaveBeenCalledTimes(builds + 2);
+
+ // A vertical slide made top-level is built anew, which drops its editor.
+ vi.mocked(moveSlideNote).mockResolvedValueOnce(true);
+ act(() => sidebar().slideMenuActions?.onEdit?.("below"));
+ await act(async () => sidebar().onMoveSlide?.({ noteId: "below", targetNoteId: "second", position: "after" }));
+ expect(props().editedNoteId).toBeUndefined();
+ });
+
+ it("prints the slides without the stage, asking Reveal.js for its print layout", async () => {
+ const location = window.location.href;
+ const model: PresentationModel = { slides: [
+ { noteId: "first", type: "text", content: { __html: "" }, verticalSlides: undefined }
+ ] };
+ vi.mocked(buildPresentationModel).mockImplementation(async () => model);
+ const note = buildNote({ title: "Deck", type: "book", "#viewType": "presentation" });
+ const container = renderPresentation(note, vi.fn(), { media: "print" });
+
+ await vi.waitFor(() => expect(rendered.slides?.presentation).toBe(model));
+ expect(new URL(window.location.href).searchParams.has("print-pdf")).toBe(true);
+ expect(container.querySelector(".presentation-view, .presentation-container")).toBeNull();
+ window.history.replaceState({}, "", location);
+ });
+
+ it("goes to a slide picked in the sidebar", async () => {
+ const { reveal, sidebar } = await renderDeck();
+ act(() => sidebar().onSelectSlide("second"));
+ expect(reveal.api.slide).toHaveBeenLastCalledWith(2, 0, undefined);
+ });
+});
+
+/** A stand-in for Reveal.js over sections of the given notes, at their index as the horizontal position. */
+function createReveal(noteIds: string[]) {
+ const element = document.createElement("div");
+ for (const noteId of noteIds) {
+ const section = document.createElement("section");
+ section.id = `slide-${noteId}`;
+ section.dataset.noteId = noteId;
+ element.append(section);
+ }
+ const listeners = new Map<string, Set<(e: Event) => void>>();
+ let currentNoteId = noteIds[0];
+ const reveal = {
+ isOverview: false,
+ api: {
+ on: (name: string, listener: (e: Event) => void) => {
+ listeners.set(name, (listeners.get(name) ?? new Set()).add(listener));
+ },
+ off: (name: string, listener: (e: Event) => void) => listeners.get(name)?.delete(listener),
+ isOverview: () => reveal.isOverview,
+ toggleOverview: vi.fn((isShown?: boolean) => { reveal.isOverview = isShown ?? !reveal.isOverview; }),
+ getRevealElement: () => element,
+ getCurrentSlide: () => element.querySelector(`#slide-${currentNoteId}`),
+ getIndices: (slide?: HTMLElement) => ({ h: slide ? noteIds.indexOf(slide.dataset.noteId ?? "") : 0, v: 0 }),
+ getScale: () => 1,
+ slide: vi.fn()
+ } as unknown as RevealApi & { toggleOverview: Mock; slide: Mock },
+ emit(name: string, noteId?: string) {
+ if (noteId) currentNoteId = noteId;
+ const event = Object.assign(new Event(name), { currentSlide: element.querySelector(`#slide-${currentNoteId}`) });
+ for (const listener of listeners.get(name) ?? []) listener(event);
+ }
+ };
+ return reveal;
+}
+
function renderPresentation(
note: FNote, onReady: () => void,
- { parent = new Component(), noteIds = [] }: { parent?: Component; noteIds?: string[] } = {}
+ { parent = new Component(), noteIds = [], media = "screen" }: {
+ parent?: Component; noteIds?: string[]; media?: ViewModeMedia
+ } = {}
) {
const noteContext = new NoteContext("ntx-presentation");
noteContext.noteId = note.noteId;
@@ -139,7 +415,7 @@ function renderPresentation(
highlightedTokens={undefined}
viewConfig={undefined}
saveConfig={() => {}}
- media="screen"
+ media={media}
onReady={onReady}
/>
</NoteContextContext.Provider>
diff --git a/apps/client/src/widgets/collections/presentation/slide.spec.tsx b/apps/client/src/widgets/collections/presentation/slide.spec.tsx
index fabd8d8559..d4464aa10d 100644
--- a/apps/client/src/widgets/collections/presentation/slide.spec.tsx
+++ b/apps/client/src/widgets/collections/presentation/slide.spec.tsx
@@ -3,7 +3,7 @@ import { useContext } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
-import type { PresentationSlideBaseModel } from "./model";
+import type { PresentationModel, PresentationSlideBaseModel } from "./model";
const webViewSlide: PresentationSlideBaseModel = {
noteId: "web",
@@ -290,4 +290,64 @@ describe("Presentation double-click", () => {
dblclick(container.querySelector(".reveal"));
expect(onEditSlide).toHaveBeenCalledTimes(2);
});
+
+ it("goes to a pending slide once it is rendered, and lets Reveal.js go when it unmounts", async () => {
+ const slide = vi.fn();
+ const destroy = vi.fn();
+ vi.doMock("reveal.js", () => ({
+ default: class {
+ element: HTMLElement;
+ constructor(element: HTMLElement) { this.element = element; }
+ initialize() { return Promise.resolve(); }
+ destroy = destroy;
+ isReady() { return true; }
+ layout() {}
+ sync() {}
+ slide = slide;
+ on() {}
+ off() {}
+ getIndices(section?: HTMLElement) { return { h: section?.id === "slide-added" ? 1 : 0, v: 0 }; }
+ getRevealElement() { return this.element; }
+ getCurrentSlide() { return this.element.querySelector("#slide-first"); }
+ }
+ }));
+ const { Presentation } = await import("./slides");
+ const setApi = vi.fn();
+ const onPendingSlideShown = vi.fn();
+ const container = document.createElement("div");
+ document.body.append(container);
+ const first: PresentationModel["slides"][number] = {
+ noteId: "first", type: "text", content: { __html: "" },
+ verticalSlides: [ { noteId: "below", type: "text", content: { __html: "" } } ]
+ };
+ const show = (slides: PresentationModel["slides"]) => act(async () => render(
+ <Presentation
+ presentation={{ slides }}
+ setApi={setApi}
+ ntxId={undefined}
+ editedNoteId={undefined}
+ isEditorReady={false}
+ closingContents={{}}
+ onEditSlide={undefined}
+ onEditorHost={() => {}}
+ pendingNoteId="added"
+ onPendingSlideShown={onPendingSlideShown}
+ onStartPresentation={undefined}
+ />,
+ container
+ ));
+
+ await show([ first ]);
+ await vi.waitFor(() => expect(setApi).toHaveBeenCalledWith(expect.anything()));
+ expect(container.querySelector(":scope .slides > section > #slide-below")).not.toBeNull();
+ expect(onPendingSlideShown).not.toHaveBeenCalled();
+
+ await show([ first, { noteId: "added", type: "text", content: { __html: "" }, verticalSlides: undefined } ]);
+ expect(slide).toHaveBeenLastCalledWith(1, 0, undefined);
+ expect(onPendingSlideShown).toHaveBeenCalledExactlyOnceWith("added");
+
+ await act(async () => render(null, container));
+ expect(destroy).toHaveBeenCalledOnce();
+ expect(setApi).toHaveBeenLastCalledWith(undefined);
+ });
});
diff --git a/apps/client/src/widgets/collections/presentation/slide_editor.spec.ts b/apps/client/src/widgets/collections/presentation/slide_editor.spec.ts
index 8a77a07e34..a019eee55c 100644
--- a/apps/client/src/widgets/collections/presentation/slide_editor.spec.ts
+++ b/apps/client/src/widgets/collections/presentation/slide_editor.spec.ts
@@ -1,7 +1,13 @@
+import { h, render } from "preact";
+import { act } from "preact/test-utils";
import { describe, expect, it, vi } from "vitest";
import type FNote from "../../../entities/fnote";
-import { adoptEditorStyleSheet, collectEditorStylesheet, whenEditorHoldsContent } from "./slide_editor";
+import SlideEditor, { adoptEditorStyleSheet, collectEditorStylesheet, whenEditorHoldsContent } from "./slide_editor";
+
+vi.mock("../../type_widgets/text/TextEmbedEditor", () => ({
+ default: () => h("div", { className: "text-embed-editor" })
+}));
describe("whenEditorHoldsContent", () => {
function setUp(noteContent: string) {
@@ -144,3 +150,36 @@ describe("collectEditorStylesheet", () => {
expect(collectEditorStylesheet([ crossOrigin, sheet ])).toContain(".ck-toolbar");
});
});
+
+describe("SlideEditor", () => {
+ it("styles the editor in the slide's shadow root, and finishes on an Escape the editor left alone", async () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const shadowRoot = host.attachShadow({ mode: "open" });
+ const note = { noteId: "slide", getContent: async () => "" } as unknown as FNote;
+ const onFinish = vi.fn();
+ await act(async () => render(
+ h(SlideEditor, { note, onReady: vi.fn(), onFinish, onClose: vi.fn() }),
+ shadowRoot
+ ));
+ expect(shadowRoot.adoptedStyleSheets).toHaveLength(1);
+ const root = shadowRoot.querySelector(".slide-editor-root");
+ expect(root?.querySelector(".text-embed-editor")).not.toBeNull();
+
+ const press = (key: string, isHandled = false) => {
+ const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });
+ if (isHandled) event.preventDefault();
+ root?.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+ expect(press("Escape", true)).toBe(true);
+ expect(press("a")).toBe(false);
+ expect(onFinish).not.toHaveBeenCalled();
+ expect(press("Escape")).toBe(true);
+ expect(onFinish).toHaveBeenCalledOnce();
+
+ await act(async () => render(null, shadowRoot));
+ expect(shadowRoot.adoptedStyleSheets).toHaveLength(0);
+ host.remove();
+ });
+});
diff --git a/apps/client/src/widgets/collections/presentation/slide_menu.spec.ts b/apps/client/src/widgets/collections/presentation/slide_menu.spec.ts
index b636f79358..4a0c689648 100644
--- a/apps/client/src/widgets/collections/presentation/slide_menu.spec.ts
+++ b/apps/client/src/widgets/collections/presentation/slide_menu.spec.ts
@@ -1,9 +1,10 @@
import { describe, expect, it, vi } from "vitest";
import appContext, { type CommandNames } from "../../../components/app_context";
-import type { MenuCommandItem, MenuItem } from "../../../menus/context_menu";
+import contextMenu, { type ContextMenuEvent, type MenuCommandItem, type MenuItem } from "../../../menus/context_menu";
+import link_context_menu from "../../../menus/link_context_menu";
import type { PresentationSlideBaseModel, SlideMove } from "./model";
-import { buildSlideMenuItems, type SlideMenuActions, type SlideMenuTarget } from "./slide_menu";
+import { buildSlideMenuItems, openSlideMenu, type SlideMenuActions, type SlideMenuTarget } from "./slide_menu";
// i18next is never initialized under test, so `t()` looks keys up in the English catalog itself.
// The code languages enabled in the code note options, in their order.
@@ -141,3 +142,36 @@ describe("buildSlideMenuItems", () => {
expect(onMove).toHaveBeenCalledWith(move("b"));
});
});
+
+describe("openSlideMenu", () => {
+ it("opens beside the pointer for a right-click, and below the thumbnail from the keyboard", () => {
+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
+ const handleItem = vi.spyOn(link_context_menu, "handleLinkContextMenuItem").mockReturnValue(true);
+ vi.spyOn(link_context_menu, "getOpenNoteItem").mockReturnValue(openNoteItem);
+ const thumbnail = document.createElement("button");
+ vi.spyOn(thumbnail, "getBoundingClientRect").mockReturnValue(new DOMRect(10, 20, 100, 50));
+ const target: SlideMenuTarget = { slide: textSlide, isVertical: false, moves: undefined, isRtl: false };
+ const onHide = vi.fn();
+ const open = (e: Partial<ContextMenuEvent>) => {
+ show.mockClear();
+ openSlideMenu(e as ContextMenuEvent, thumbnail, target, {}, vi.fn(), onHide);
+ const options = show.mock.calls[0]?.[0];
+ expect(options).toBeDefined();
+ return options;
+ };
+
+ const onPointer = open({ clientX: 30, clientY: 40, pageX: 130, pageY: 140 });
+ expect(onPointer).toMatchObject({ x: 130, y: 140, onHide });
+ expect(onPointer).not.toHaveProperty("anchor");
+ expect(onPointer?.items.length).toBeGreaterThan(0);
+
+ // Shift+F10 and the Menu key report no place, or one off the thumbnail.
+ expect(open({ clientX: 0, clientY: 0 })).toMatchObject({ anchor: thumbnail });
+ expect(open({})).toMatchObject({ anchor: thumbnail });
+ expect(open({ clientX: 500, clientY: 40, pageX: 500, pageY: 40 })).toMatchObject({ anchor: thumbnail });
+
+ onPointer?.selectMenuItemHandler({ command: "openNoteInNewTab" } as MenuCommandItem<unknown>, {} as MouseEvent);
+ expect(handleItem).toHaveBeenCalledWith("openNoteInNewTab", { target: thumbnail }, "s");
+ vi.restoreAllMocks();
+ });
+});