Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor/canvas: use a custom toolbar outside of the canvas area
Adorian Dorand301fdb86d25
diff --git a/apps/client/src/widgets/type_widgets/canvas/Canvas.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/Canvas.spec.tsxindex ec0e37e492..7ee574433a 100644--- a/apps/client/src/widgets/type_widgets/canvas/Canvas.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/Canvas.spec.tsx@@ -1,5 +1,5 @@import type { ExcalidrawImperativeAPI, ExcalidrawProps } from "@excalidraw/excalidraw/types";-import { type RefObject, render } from "preact";+import { type ComponentChildren, type RefObject, render } from "preact";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -7,7 +7,7 @@ const excalidrawProps = vi.fn((_props: ExcalidrawProps) => undefined);vi.mock("@excalidraw/excalidraw", () => ({Excalidraw: (props: ExcalidrawProps) => {excalidrawProps(props);- return <div className="mock-excalidraw" />;+ return <div className="mock-excalidraw">{props.children as ComponentChildren}</div>;}}));vi.mock("../../react/hooks", async (importOriginal) => ({@@ -35,7 +35,7 @@ describe("CanvasEditor", () => {container.remove();});- async function mount(isEmbedded?: boolean) {+ async function mount(isEmbedded?: boolean, children?: ComponentChildren) {await act(async () => {render(<CanvasEditor@@ -44,7 +44,9 @@ describe("CanvasEditor", () => {colorScheme="light"persistence={{}}isEmbedded={isEmbedded}- />,+ >+ {children}+ </CanvasEditor>,container);});@@ -72,4 +74,10 @@ describe("CanvasEditor", () => {expect(refresh).not.toHaveBeenCalled();expect(excalidrawProps).toHaveBeenLastCalledWith(expect.objectContaining({ detectScroll: false }));});++ it("renders its children inside Excalidraw", async () => {+ const excalidraw = await mount(true, <span className="excalidraw-child" />);++ expect(excalidraw?.querySelector(".excalidraw-child")).not.toBeNull();+ });});diff --git a/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx b/apps/client/src/widgets/type_widgets/canvas/Canvas.tsxindex dc7f92f44c..23807dfd5d 100644--- a/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx@@ -2,7 +2,7 @@ import { Excalidraw } from "@excalidraw/excalidraw";import { TypeWidgetProps } from "../type_widget";import "@excalidraw/excalidraw/index.css";import { useColorScheme, useEffectiveReadOnly, useTriliumOption } from "../../react/hooks";-import type { RefObject } from "preact";+import type { ComponentChildren, RefObject } from "preact";import { useCallback, useRef } from "preact/hooks";import {type AppState,@@ -47,11 +47,13 @@ export interface CanvasEditorProps {persistence: Partial<ExcalidrawProps>;/** Whether the editor moves on the page, as inside a text note that scrolls. */isEmbedded?: boolean;+ /** Rendered inside Excalidraw, where its hooks such as `useI18n()` work. */+ children?: ComponentChildren;}/** The Excalidraw editor of a canvas note or drawing, loaded and saved by `persistence`. */export function CanvasEditor({- apiRef, isReadOnly, colorScheme, persistence, isEmbedded = false+ apiRef, isReadOnly, colorScheme, persistence, isEmbedded = false, children}: CanvasEditorProps) {const [ locale ] = useTriliumOption("locale");const noteDrop = useCanvasNoteDrop(apiRef, isReadOnly);@@ -122,7 +124,9 @@ export function CanvasEditor({validateEmbeddable={validateEmbeddable}renderEmbeddable={renderEmbeddable}{...persistence}- />+ >+ {children}+ </Excalidraw></div></div>)diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.cssindex b0e242c2cc..1ba4961b86 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css@@ -85,6 +85,16 @@opacity: 0;}+/* The tools are buttons of the embed's toolbar, which fullscreen hides. */+.include-note-content:not(:fullscreen) .canvas-drawing .excalidraw {+ .App-toolbar-container > .App-toolbar,+ .mobile-misc-tools-container > label:has(+ [data-testid="toolbar-lock"], [data-testid="toolbar-hand"]+ ) {+ display: none;+ }+}+.include-note {&[data-box-size="small"] .canvas-drawing {height: 10em;diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsxindex 314b473a0f..043f10f00d 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx@@ -12,6 +12,7 @@ import type { AttachmentEditor } from "../../../services/content_renderer";import options from "../../../services/options";import { useColorScheme } from "../../react/hooks";import { CanvasEditor } from "./Canvas";+import CanvasEmbedTools from "./CanvasEmbedTools";import { getInlineFiles, parseContent, useCanvasDrawingPersistence } from "./persistence";interface CanvasDrawingProps {@@ -46,7 +47,9 @@ export default function CanvasDrawing({ attachment, editor }: CanvasDrawingPropscolorScheme={colorScheme}persistence={persistence}isEmbedded- />+ >+ {isEditable && <CanvasEmbedTools rootRef={rootRef} apiRef={apiRef} />}+ </CanvasEditor></div>);}diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsxnew file mode 100644index 0000000000..a9aba2631b--- /dev/null+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx@@ -0,0 +1,146 @@+import type { AppState, ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";+import { render } from "preact";+import { useRef } from "preact/hooks";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const translate = vi.hoisted(() => (key: string) => `t:${key}`);+vi.mock("@excalidraw/excalidraw", () => ({+ useI18n: () => ({ t: translate, langCode: "en" })+}));++const { default: CanvasEmbedTools } = await import("./CanvasEmbedTools");+const { getContentEmbedTools } = await import("../text/content_embed_tools");++type ActiveTool = AppState["activeTool"];++const TOOL_IDS = [+ "selection", "rectangle", "diamond", "ellipse", "arrow", "line", "freedraw", "text", "image",+ "eraser", "hand", "frame", "embeddable", "laser", "lock"+];++describe("CanvasEmbedTools", () => {+ let container: HTMLElement;+ let api: ReturnType<typeof createApi>;++ beforeEach(() => {+ api = createApi();+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ function Drawing() {+ const rootRef = useRef<HTMLDivElement>(null);+ const apiRef = useRef<ExcalidrawImperativeAPI>(api.api);+ return (+ <figure className="include-note">+ <div ref={rootRef}>+ <div className="excalidraw-container" tabIndex={0} />+ <CanvasEmbedTools rootRef={rootRef} apiRef={apiRef} />+ </div>+ </figure>+ );+ }++ async function mount() {+ await act(async () => render(<Drawing />, container));+ const embed = container.querySelector<HTMLElement>("figure.include-note");+ const provider = embed && getContentEmbedTools(embed);+ if (!embed || !provider) {+ throw new Error("Expected the tools of the drawing.");+ }+ return { embed, provider };+ }++ it("adds the tools to the toolbar of the embed while the drawing is mounted", async () => {+ const { embed, provider } = await mount();+ const listener = vi.fn();+ provider.subscribe(listener);++ expect(getContentEmbedTools(document.createElement("figure"))).toBeNull();+ expect(provider.getTools()).toEqual(TOOL_IDS.map((id, index) => ({+ id,+ label: String(index + 1),+ tooltip: `t:toolBar.${id}`,+ isOn: id === "selection"+ })));++ await act(async () => render(null, container));+ expect(getContentEmbedTools(embed)).toBeNull();+ expect(api.unsubscribe).toHaveBeenCalledTimes(1);+ expect(listener).toHaveBeenCalledTimes(1);+ expect(provider.getTools()).toEqual([]);+ });++ it("notifies its listeners when the active tool or its lock changes", async () => {+ const { provider } = await mount();+ const listener = vi.fn();+ const unsubscribe = provider.subscribe(listener);++ api.change({ type: "selection", locked: false });+ expect(listener).not.toHaveBeenCalled();++ api.change({ type: "rectangle", locked: false });+ api.change({ type: "rectangle", locked: true });+ expect(listener).toHaveBeenCalledTimes(2);+ expect(provider.getTools().filter((tool) => tool.isOn).map((tool) => tool.id))+ .toEqual([ "rectangle", "lock" ]);++ unsubscribe();+ api.change({ type: "text", locked: true });+ expect(listener).toHaveBeenCalledTimes(2);+ });++ it("runs a tool with the focus in the drawing", async () => {+ const { provider } = await mount();++ provider.execute("rectangle");+ expect(api.setActiveTool).toHaveBeenCalledWith({ type: "rectangle" });+ expect(document.activeElement).toBe(container.querySelector(".excalidraw-container"));++ provider.execute("lock");+ expect(api.updateScene).toHaveBeenCalledWith({+ appState: { activeTool: expect.objectContaining({ type: "selection", locked: true }) }+ });++ provider.execute("magicframe");+ expect(api.setActiveTool).toHaveBeenCalledTimes(1);+ expect(api.updateScene).toHaveBeenCalledTimes(1);+ });+});++/** An Excalidraw API whose active tool the spec changes. */+function createApi() {+ let activeTool = { type: "selection", locked: false } as ActiveTool;+ let onChange: ((elements: unknown[], appState: AppState) => void) | undefined;+ const unsubscribe = vi.fn();+ const setActiveTool = vi.fn();+ const updateScene = vi.fn();+ const getAppState = () => ({ activeTool }) as AppState;++ const api = {+ getAppState,+ setActiveTool,+ updateScene,+ onChange: (callback: typeof onChange) => {+ onChange = callback;+ return unsubscribe;+ }+ } as unknown as ExcalidrawImperativeAPI;++ return {+ api,+ unsubscribe,+ setActiveTool,+ updateScene,+ change(next: Pick<ActiveTool, "type" | "locked">) {+ activeTool = { ...activeTool, ...next } as ActiveTool;+ onChange?.([], getAppState());+ }+ };+}diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsxnew file mode 100644index 0000000000..cab2fec09a--- /dev/null+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx@@ -0,0 +1,147 @@+import { useI18n } from "@excalidraw/excalidraw";+import type { AppState, ExcalidrawImperativeAPI, ToolType } from "@excalidraw/excalidraw/types";+import type { RefObject } from "preact";+import { useEffect, useState } from "preact/hooks";++import {+ type ContentEmbedTool,+ type ContentEmbedToolProvider,+ registerContentEmbedTools+} from "../text/content_embed_tools";++/** The tools in the order of their buttons. Excalidraw also selects the first nine with 1 to 9. */+const TOOLS = [+ "selection", "rectangle", "diamond", "ellipse", "arrow", "line", "freedraw", "text", "image",+ "eraser", "hand", "frame", "embeddable", "laser"+] as const satisfies readonly ToolType[];+const LOCK = "lock";++type Tool = typeof TOOLS[number];+/** Excalidraw's `t()`, for a key such as `toolBar.rectangle`. */+type Translate = (key: string) => string;++interface CanvasEmbedToolsProps {+ /** The element of the drawing, inside the embed whose toolbar shows the tools. */+ rootRef: RefObject<HTMLElement>;+ apiRef: RefObject<ExcalidrawImperativeAPI>;+}++/**+ * Adds Excalidraw's tools to the toolbar of the embed that shows the drawing. Renders inside+ * `<Excalidraw>`, for its translations.+ */+export default function CanvasEmbedTools({ rootRef, apiRef }: CanvasEmbedToolsProps) {+ // Excalidraw types the key of `t()` as a union that TypeScript cannot check a string against.+ const { t, langCode } = useI18n() as unknown as { t: Translate; langCode: string };+ const [ tools ] = useState(() => new CanvasTools(rootRef));++ useEffect(() => tools.setTranslate(t), [ tools, t, langCode ]);++ useEffect(() => {+ const root = rootRef.current;+ const api = apiRef.current;+ if (!root || !api) return;++ const disconnect = tools.connect(api);+ const unregister = registerContentEmbedTools(root, tools);+ return () => {+ unregister();+ disconnect();+ };+ }, [ tools, rootRef, apiRef ]);++ return null;+}++/** Excalidraw's tools, as buttons of the toolbar of the embed that shows the drawing. */+export class CanvasTools implements ContentEmbedToolProvider {+ private api: ExcalidrawImperativeAPI | null = null;+ private translate: Translate | null = null;+ private listeners = new Set<() => void>();+ /** The active tool and its lock, to notify the listeners only when they change. */+ private shownTool = "";++ constructor(private readonly rootRef: RefObject<HTMLElement>) {}++ /** Follows the active tool of `api`, until the returned function is called. */+ connect(api: ExcalidrawImperativeAPI) {+ this.api = api;+ const unsubscribe = api.onChange((_elements, appState) => this.update(appState));+ this.update(api.getAppState());++ return () => {+ unsubscribe();+ this.api = null;+ this.shownTool = "";+ this.notify();+ };+ }++ setTranslate(translate: Translate) {+ this.translate = translate;+ this.notify();+ }++ getTools(): ContentEmbedTool[] {+ const activeTool = this.api?.getAppState().activeTool;+ if (!activeTool) {+ return [];+ }++ const tools = [+ ...TOOLS.map((type) => ({ id: type, isOn: activeTool.type === type })),+ { id: LOCK, isOn: activeTool.locked }+ ];+ return tools.map(({ id, isOn }, index) => ({+ id,+ label: String(index + 1),+ tooltip: this.translate?.(`toolBar.${id}`) ?? id,+ isOn+ }));+ }++ execute(id: string) {+ const api = this.api;+ if (!api) return;++ // The embed covers the drawing with a backdrop until the drawing has the focus.+ const container = this.rootRef.current?.querySelector<HTMLElement>(".excalidraw-container");+ if (container && !container.contains(document.activeElement)) {+ container.focus({ preventScroll: true });+ }++ const { activeTool } = api.getAppState();+ if (id === LOCK) {+ const locked = !activeTool.locked;+ api.updateScene({ appState: { activeTool: { ...activeTool, locked } } });+ } else if (isTool(id)) {+ api.setActiveTool({ type: id });+ }+ }++ subscribe(callback: () => void) {+ this.listeners.add(callback);+ return () => {+ this.listeners.delete(callback);+ };+ }++ private update(appState: AppState) {+ const { type, locked } = appState.activeTool;+ const shownTool = `${type}:${locked}`;+ if (shownTool !== this.shownTool) {+ this.shownTool = shownTool;+ this.notify();+ }+ }++ private notify() {+ for (const listener of this.listeners) {+ listener();+ }+ }+}++function isTool(id: string): id is Tool {+ return (TOOLS as readonly string[]).includes(id);+}diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 8256090404..0b67d686c4 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -33,6 +33,7 @@ import { setEditorNoteId } from "../../react/NoteStore";import { TypeWidgetProps } from "../type_widget";import AttachmentSaves from "./attachment_saves";import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditorWithWatchdog";+import { getContentEmbedTools } from "./content_embed_tools";import getTemplates, { updateTemplateCache } from "./snippets.js";import linkEmbedService from "../../../services/link_embed";import { usesClassicToolbar } from "./toolbar";@@ -221,6 +222,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext},getEmbedBoxSize: getUploadBoxSize,openContentEmbedMenu,+ getContentEmbedTools,// Link preview functionality. The insert flow itself lives in the editor (a balloon form),// so the host only has to supply the metadata and the rendering.async fetchLinkMetadata(url: string) {diff --git a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts b/apps/client/src/widgets/type_widgets/text/content_embed_tools.tsnew file mode 100644index 0000000000..899ac0c231--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts@@ -0,0 +1,43 @@+/** A button that the content of an embed adds to the toolbar of the embed. */+export interface ContentEmbedTool {+ id: string;+ /** The text of the button. */+ label: string;+ /** The name of what the button does, shown as its tooltip. */+ tooltip: string;+ isOn: boolean;+}++/** The buttons that the content of an embed, such as a canvas drawing, adds to its toolbar. */+export interface ContentEmbedToolProvider {+ getTools(): ContentEmbedTool[];+ execute(id: string): void;+ /** Calls `callback` when `getTools()` changes, until the returned function is called. */+ subscribe(callback: () => void): () => void;+}++const providers = new Map<HTMLElement, ContentEmbedToolProvider>();++/**+ * Adds the buttons of `provider` to the toolbar of the embed that contains `element`, until the+ * returned function is called.+ */+export function registerContentEmbedTools(+ element: HTMLElement,+ provider: ContentEmbedToolProvider+) {+ providers.set(element, provider);+ return () => {+ providers.delete(element);+ };+}++/** The buttons that the content of `embed` adds to its toolbar, or `null`. */+export function getContentEmbedTools(embed: HTMLElement) {+ for (const [ element, provider ] of providers) {+ if (embed.contains(element)) {+ return provider;+ }+ }+ return null;+}diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex ad7c1601cc..5cbace69ad 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -30,6 +30,24 @@ declare global {onSelect(iconClass: string): void;}+ /** A button that the content of an embed adds to the toolbar of the embed. */+ interface ContentEmbedTool {+ id: string;+ /** The text of the button. */+ label: string;+ /** The name of what the button does, shown as its tooltip. */+ tooltip: string;+ isOn: boolean;+ }++ /** The buttons that the content of an embed, such as a canvas drawing, adds to its toolbar. */+ interface ContentEmbedToolProvider {+ getTools(): ContentEmbedTool[];+ execute(id: string): void;+ /** Calls `callback` when `getTools()` changes, until the returned function is called. */+ subscribe(callback: () => void): () => void;+ }+interface EditorComponent extends Component {/*** Paints the host's icon picker into `container`, and answers with the way to take it down@@ -64,6 +82,11 @@ declare global {* leave it out.*/openContentEmbedMenu?(embed: HTMLElement, anchor: HTMLElement): void;+ /**+ * The buttons that what `embed` shows adds to the toolbar of the embed, or `null`. Hosts+ * without embeds leave it out.+ */+ getContentEmbedTools?(embed: HTMLElement): ContentEmbedToolProvider | null;/*** Gives the focus to what the embed of the attachment shows, once it renders. Hosts* without embeds leave it out.diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex be562e20f5..b7b418a15d 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -124,6 +124,11 @@ export default class ContentEmbed extends Plugin {};}+ /** The rendered `<figure>` of the selected embed, or `null`. */+ getSelectedEmbedDom(): HTMLElement | null {+ return getSelectedContentEmbedDom( this.editor );+ }+/** Whether `domElement` is a reference link that `convertLinkToEmbed` turns into an embed. */canConvertLinkToEmbed( domElement: HTMLElement ): boolean {return !!getLinkToEmbed( this.editor, domElement );@@ -875,10 +880,8 @@ function getTitleAttributes( element: ModelElement ): Record<string, string> {/** Has the host open the context menu of the selected embed, below `anchor`. */function openContentEmbedMenu( editor: Editor, anchor: HTMLElement | null ) {- const embed = getSelectedContentEmbed( editor );- const viewElement = embed && editor.editing.mapper.toViewElement( embed );- const domElement = viewElement && editor.editing.view.domConverter.mapViewToDom( viewElement );- if ( !anchor || !( domElement instanceof HTMLElement ) ) {+ const domElement = getSelectedContentEmbedDom( editor );+ if ( !anchor || !domElement ) {return;}@@ -886,6 +889,14 @@ function openContentEmbedMenu( editor: Editor, anchor: HTMLElement | null ) {component.openContentEmbedMenu?.( domElement, anchor );}+/** The rendered `<figure>` of the selected embed, or `null`. */+function getSelectedContentEmbedDom( editor: Editor ): HTMLElement | null {+ const embed = getSelectedContentEmbed( editor );+ const viewElement = embed && editor.editing.mapper.toViewElement( embed );+ const domElement = viewElement && editor.editing.view.domConverter.mapViewToDom( viewElement );+ return domElement instanceof HTMLElement ? domElement : null;+}+/** The title of an embed whose upload is under way: a spinner and the name of the file. */function createUploadTitle( domDocument: Document, fileName: string ) {const title = domDocument.createElement( 'h4' );diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.tsindex a8df074106..1a4ac4a159 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts@@ -12,6 +12,7 @@ import ContentEmbed, {} from "./content_embed.js";import ContentEmbedBoxSizeDropdown from "./content_embed_box_size_dropdown.js";import ContentEmbedToolbar from "./content_embed_toolbar.js";+import ContentEmbedTools, { CONTENT_EMBED_TOOLS } from "./content_embed_tools.js";// ---------------------------------------------------------------------------// Minimal inline plugin that registers a widget without a class attribute.@@ -97,14 +98,16 @@ describe("ContentEmbedToolbar", () => {expect(requires).toContain(WidgetToolbarRepository);expect(requires).toContain(ContentEmbed);expect(requires).toContain(ContentEmbedBoxSizeDropdown);+ expect(requires).toContain(ContentEmbedTools);});- it("offers the box size, the title, the caption, the link conversion and the menu", () => {+ it("offers the content's tools, the box size, the title, the caption, the link conversion and the menu", () => {const repository = editor.plugins.get(WidgetToolbarRepository) as unknown as {_toolbarDefinitions: Map<string, { itemsConfig: string[] }>;};expect(repository._toolbarDefinitions.get("contentEmbed")?.itemsConfig).toEqual([+ CONTENT_EMBED_TOOLS,"contentEmbedBoxSizeDropdown",TOGGLE_TITLE_COMMAND_NAME,TOGGLE_CAPTION_COMMAND_NAME,diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.tsindex cb6f2df006..9dbe81d1a5 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts@@ -6,11 +6,14 @@ import ContentEmbed, {TOGGLE_TITLE_COMMAND_NAME} from "./content_embed.js";import ContentEmbedBoxSizeDropdown from "./content_embed_box_size_dropdown.js";+import ContentEmbedTools, { CONTENT_EMBED_TOOLS } from "./content_embed_tools.js";export default class ContentEmbedToolbar extends Plugin {static get requires() {- return [WidgetToolbarRepository, ContentEmbed, ContentEmbedBoxSizeDropdown] as const;+ return [+ WidgetToolbarRepository, ContentEmbed, ContentEmbedBoxSizeDropdown, ContentEmbedTools+ ] as const;}afterInit() {@@ -19,6 +22,7 @@ export default class ContentEmbedToolbar extends Plugin {widgetToolbarRepository.register("contentEmbed", {items: [+ CONTENT_EMBED_TOOLS,"contentEmbedBoxSizeDropdown",TOGGLE_TITLE_COMMAND_NAME,TOGGLE_CAPTION_COMMAND_NAME,diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.tsnew file mode 100644index 0000000000..9abd4dc64d--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts@@ -0,0 +1,174 @@+import {+ ClassicEditor, Essentials, Paragraph, Widget, _setModelData as setModelData+} from "ckeditor5";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../../../test/editor-kit.js";+import { installGlobMock } from "../../../test/globals-test-kit.js";+import ContentEmbed from "./content_embed.js";+import ContentEmbedTools, {+ CONTENT_EMBED_TOOLS, ContentEmbedToolsView+} from "./content_embed_tools.js";++const SELECTION = { id: "selection", label: "1", tooltip: "Selection", isOn: true };+const RECTANGLE = { id: "rectangle", label: "2", tooltip: "Rectangle", isOn: false };++type Tool = typeof SELECTION;++describe("ContentEmbedTools", () => {+ let editor: ClassicEditor;+ let provider: ReturnType<typeof createProvider>;+ let getContentEmbedTools: ReturnType<typeof vi.fn>;+ let view: ContentEmbedToolsView | undefined;++ beforeEach(async () => {+ provider = createProvider([ SELECTION, RECTANGLE ]);+ getContentEmbedTools = vi.fn(() => provider);+ installGlobMock({+ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn(), getContentEmbedTools })+ });++ editor = await createTestEditor([+ Essentials, Paragraph, Widget, ContentEmbed, ContentEmbedTools+ ]);+ });++ afterEach(() => {+ view?.element?.remove();+ view = undefined;+ });++ function createView() {+ const created = editor.ui.componentFactory.create(CONTENT_EMBED_TOOLS);+ if (!(created instanceof ContentEmbedToolsView)) {+ throw new Error("Expected the tools view.");+ }+ created.render();+ view = created;+ return created;+ }++ function selectEmbed() {+ editor.model.change((writer) => {+ const root = editor.model.document.getRoot();+ if (!root) {+ throw new Error("The editor has no root.");+ }+ const embed = writer.createElement("contentEmbed", { noteId: "n1", boxSize: "medium" });+ writer.insert(embed, root, 0);+ writer.setSelection(embed, "on");+ });+ editor.ui.update();+ }++ function getButtonStates(tools: ContentEmbedToolsView) {+ return [ ...tools.buttons ].map((button) => [+ button.label, button.tooltip, button.ariaLabel, button.isOn, button.withText+ ]);+ }++ it("shows the tools of the selected embed's content, and hides them elsewhere", () => {+ const tools = createView();+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");+ editor.ui.update();+ expect(getContentEmbedTools).not.toHaveBeenCalled();+ expect(tools.element?.classList.contains("ck-hidden")).toBe(true);++ selectEmbed();+ editor.ui.update();+ const embed = editor.editing.view.getDomRoot()?.querySelector("figure.include-note");+ expect(getContentEmbedTools).toHaveBeenLastCalledWith(embed);+ expect(provider.subscribe).toHaveBeenCalledTimes(1);+ expect(tools.element?.classList.contains("ck-hidden")).toBe(false);+ expect(getButtonStates(tools)).toEqual([+ [ "1", "Selection", "Selection", true, true ],+ [ "2", "Rectangle", "Rectangle", false, true ]+ ]);++ setModelData(editor.model, "<paragraph>foo[]</paragraph>");+ editor.ui.update();+ expect(provider.unsubscribe).toHaveBeenCalledTimes(1);+ expect(tools.isVisible).toBe(false);+ });++ it("shows no tools for content without any, or for a host that offers none", () => {+ const tools = createView();+ getContentEmbedTools.mockReturnValue(null);+ selectEmbed();+ expect(tools.isVisible).toBe(false);++ installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });+ selectEmbed();+ expect(tools.isVisible).toBe(false);++ installGlobMock({ getComponentByEl: () => undefined });+ editor.ui.update();+ expect(tools.isVisible).toBe(false);+ });++ it("runs a tool without taking the focus", () => {+ const tools = createView();+ selectEmbed();+ const rectangle = tools.buttons.get(1);+ const mousedown = new MouseEvent("mousedown", { bubbles: true, cancelable: true });+ rectangle?.element?.dispatchEvent(mousedown);+ rectangle?.fire("execute");++ expect(mousedown.defaultPrevented).toBe(true);+ expect(provider.execute).toHaveBeenCalledWith("rectangle");+ });++ it("updates the buttons in place, and places the toolbar again for a new set", () => {+ const tools = createView();+ selectEmbed();+ const update = vi.spyOn(editor.ui, "update");+ const first = tools.buttons.first;++ provider.change([ { ...SELECTION, isOn: false }, { ...RECTANGLE, isOn: true } ]);+ expect([ ...tools.buttons ].map((button) => button.isOn)).toEqual([ false, true ]);+ expect(tools.buttons.first).toBe(first);+ expect(update).not.toHaveBeenCalled();++ provider.change([ RECTANGLE ]);+ expect(getButtonStates(tools)).toEqual([ [ "2", "Rectangle", "Rectangle", false, true ] ]);+ expect(update).toHaveBeenCalledTimes(1);++ provider.change([]);+ expect(tools.isVisible).toBe(false);+ });++ it("focuses its first button, and stops following the provider once destroyed", () => {+ const tools = createView();+ selectEmbed();+ if (tools.element) {+ document.body.append(tools.element);+ }++ tools.focus();+ expect(document.activeElement).toBe(tools.buttons.first?.element);++ tools.destroy();+ expect(provider.unsubscribe).toHaveBeenCalledTimes(1);+ });+});++/** A provider whose tools the spec changes. */+function createProvider(initialTools: Tool[]) {+ let tools = initialTools;+ let listener: (() => void) | undefined;+ const unsubscribe = vi.fn();++ return {+ unsubscribe,+ getTools: () => tools,+ execute: vi.fn(),+ subscribe: vi.fn((callback: () => void) => {+ listener = callback;+ return unsubscribe;+ }),+ change(next: Tool[]) {+ tools = next;+ listener?.();+ }+ };+}diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.tsnew file mode 100644index 0000000000..c23613c580--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts@@ -0,0 +1,158 @@+import "../../theme/content_embed_tools.css";++import { ButtonView, type Locale, Plugin, View, type ViewCollection } from "ckeditor5";++import ContentEmbed from "./content_embed.js";++/** The toolbar item with the buttons that the content of the selected embed adds. */+export const CONTENT_EMBED_TOOLS = "contentEmbedTools";++/**+ * Shows the buttons that the content of the selected embed adds to the embed's toolbar, such as+ * the tools of a canvas drawing. The host supplies them through `getContentEmbedTools()`.+ */+export default class ContentEmbedTools extends Plugin {++ static get requires() {+ return [ ContentEmbed ] as const;+ }++ static get pluginName() {+ return "ContentEmbedTools" as const;+ }++ init() {+ const editor = this.editor;++ editor.ui.componentFactory.add(CONTENT_EMBED_TOOLS, locale => {+ const view = new ContentEmbedToolsView(locale);++ // Runs before `WidgetToolbarRepository` positions the toolbar from its width.+ this.listenTo(editor.ui, "update", () => view.setProvider(this.getProvider()), {+ priority: "high"+ });+ this.listenTo<ContentEmbedToolsResizeEvent>(view, "resize", () => editor.ui.update());++ return view;+ });+ }++ /** The buttons that the content of the selected embed adds, or `null`. */+ private getProvider() {+ const embed = this.editor.plugins.get(ContentEmbed).getSelectedEmbedDom();+ if (!embed) {+ return null;+ }++ const editorEl = this.editor.editing.view.getDomRoot();+ const component: EditorComponent | undefined =+ glob.getComponentByEl<EditorComponent>(editorEl);+ return component?.getContentEmbedTools?.(embed) ?? null;+ }++}++/** Fired when the buttons are created again, which changes the width of the toolbar. */+type ContentEmbedToolsResizeEvent = {+ name: "resize";+ args: [];+};++/** The buttons of a `ContentEmbedToolProvider`, updated when the provider changes. */+export class ContentEmbedToolsView extends View {++ declare public isVisible: boolean;+ public readonly buttons: ViewCollection<ButtonView>;+ private provider: ContentEmbedToolProvider | null = null;+ private unsubscribe: (() => void) | undefined;+ private toolIds: string[] = [];++ constructor(locale?: Locale) {+ super(locale);+ this.set("isVisible", false);+ this.buttons = this.createCollection();++ const bind = this.bindTemplate;+ this.setTemplate({+ tag: "div",+ attributes: {+ class: [+ "ck",+ "ck-content-embed-tools",+ bind.if("isVisible", "ck-hidden", isVisible => !isVisible)+ ]+ },+ children: this.buttons+ });+ }++ /** Shows the buttons of `provider`, and updates them when it changes. */+ setProvider(provider: ContentEmbedToolProvider | null) {+ if (provider === this.provider) {+ return;+ }++ this.unsubscribe?.();+ this.provider = provider;+ this.unsubscribe = provider?.subscribe(() => {+ if (this.showTools()) {+ this.fire<ContentEmbedToolsResizeEvent>("resize");+ }+ });+ this.showTools();+ }++ focus() {+ this.buttons.first?.focus();+ }++ override destroy() {+ this.unsubscribe?.();+ super.destroy();+ }++ /** Shows the tools of the provider. Returns whether the buttons were created again. */+ private showTools() {+ const tools = this.provider?.getTools() ?? [];+ const ids = tools.map(tool => tool.id);+ const isNewSet = ids.length !== this.toolIds.length+ || ids.some((id, index) => id !== this.toolIds[index]);++ if (isNewSet) {+ this.toolIds = ids;+ this.buttons.clear();+ this.buttons.addMany(ids.map(id => this.createButton(id)));+ }++ for (const [ index, tool ] of tools.entries()) {+ this.buttons.get(index)?.set({+ label: tool.label,+ tooltip: tool.tooltip,+ ariaLabel: tool.tooltip,+ isOn: tool.isOn+ });+ }+ this.isVisible = tools.length > 0;++ return isNewSet;+ }++ private createButton(id: string) {+ const button = new ButtonView(this.locale);+ button.set({ withText: true, isToggleable: true });+ // Keeps the focus in the content that the tool acts on.+ button.extendTemplate({+ on: { mousedown: button.bindTemplate.to(evt => evt.preventDefault()) }+ });+ this.listenTo(button, "execute", () => this.provider?.execute(id));++ return button;+ }++}++declare module "ckeditor5" {+ interface PluginsMap {+ [ ContentEmbedTools.pluginName ]: ContentEmbedTools;+ }+}diff --git a/packages/ckeditor5/src/theme/content_embed_tools.css b/packages/ckeditor5/src/theme/content_embed_tools.cssnew file mode 100644index 0000000000..f3ffdd8c91--- /dev/null+++ b/packages/ckeditor5/src/theme/content_embed_tools.css@@ -0,0 +1,10 @@+:where(:root) {+ --ck-content-embed-tools-divider-color: var(--ck-color-toolbar-border);+}++.ck.ck-content-embed-tools {+ display: flex;+ gap: var(--ck-spacing-small);+ border-inline-end: 1px solid var(--ck-content-embed-tools-divider-color);+ padding-inline-end: var(--ck-spacing-small);+}