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: relocate the zoom/undo/redo buttons outside of the canvas area
Adorian Doranc9378efa2627
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.cssindex 77586ff485..1fd861f651 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css@@ -103,12 +103,15 @@}}-/* The tools are buttons of the embed's toolbar, which fullscreen hides. */+/* The tools, undo and redo, and zoom are buttons of the embed's toolbar, which fullscreen hides.+ `CanvasTools` clicks the hidden undo and redo buttons. */.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"]- ) {+ ),+ .layer-ui__wrapper__footer-left :is(.zoom-actions, .undo-redo-buttons),+ .App-toolbar-content > div:has(> [data-testid="button-undo"]) {display: none;}}diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsxindex a9aba2631b..368f4e49fa 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx@@ -2,7 +2,7 @@ import type { AppState, ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/timport { render } from "preact";import { useRef } from "preact/hooks";import { act } from "preact/test-utils";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from "vitest";const translate = vi.hoisted(() => (key: string) => `t:${key}`);vi.mock("@excalidraw/excalidraw", () => ({@@ -12,19 +12,20 @@ vi.mock("@excalidraw/excalidraw", () => ({const { default: CanvasEmbedTools } = await import("./CanvasEmbedTools");const { getContentEmbedTools } = await import("../text/content_embed_tools");-type ActiveTool = AppState["activeTool"];--const TOOL_IDS = [+const DRAWING_TOOL_IDS = ["selection", "rectangle", "diamond", "ellipse", "arrow", "line", "freedraw", "text", "image","eraser", "hand", "frame", "embeddable", "laser", "lock"];+const ICON = expect.stringContaining("<svg");describe("CanvasEmbedTools", () => {let container: HTMLElement;let api: ReturnType<typeof createApi>;+ let undo: Mock<() => void>;beforeEach(() => {api = createApi();+ undo = vi.fn();container = document.createElement("div");document.body.appendChild(container);});@@ -34,6 +35,7 @@ describe("CanvasEmbedTools", () => {container.remove();});+ /** A drawing with Excalidraw's container and its undo and redo buttons. */function Drawing() {const rootRef = useRef<HTMLDivElement>(null);const apiRef = useRef<ExcalidrawImperativeAPI>(api.api);@@ -41,6 +43,8 @@ describe("CanvasEmbedTools", () => {<figure className="include-note"><div ref={rootRef}><div className="excalidraw-container" tabIndex={0} />+ <button type="button" data-testid="button-undo" onClick={() => undo()} />+ <button type="button" data-testid="button-redo" disabled /><CanvasEmbedTools rootRef={rootRef} apiRef={apiRef} /></div></figure>@@ -63,12 +67,28 @@ describe("CanvasEmbedTools", () => {provider.subscribe(listener);expect(getContentEmbedTools(document.createElement("figure"))).toBeNull();- expect(provider.getTools()).toEqual(TOOL_IDS.map((id, index) => ({+ const tools = provider.getTools();+ const count = DRAWING_TOOL_IDS.length;+ expect(tools.slice(0, count)).toEqual(DRAWING_TOOL_IDS.map((id, index) => ({id,- label: String(index + 1),- tooltip: `t:toolBar.${id}`,- isOn: id === "selection"+ label: `t:toolBar.${id}`,+ text: String(index + 1),+ isOn: id === "selection",+ group: "tools"})));+ expect(tools.slice(count)).toEqual([+ { id: "undo", label: "t:buttons.undo", icon: ICON, isEnabled: true, group: "history" },+ { id: "redo", label: "t:buttons.redo", icon: ICON, isEnabled: false, group: "history" },+ {+ id: "zoomOut",+ label: "t:buttons.zoomOut",+ icon: ICON,+ isEnabled: true,+ group: "zoom"+ },+ { id: "resetZoom", label: "t:buttons.resetZoom (100%)", icon: ICON, group: "zoom" },+ { id: "zoomIn", label: "t:buttons.zoomIn", icon: ICON, isEnabled: true, group: "zoom" }+ ]);await act(async () => render(null, container));expect(getContentEmbedTools(embed)).toBeNull();@@ -77,23 +97,39 @@ describe("CanvasEmbedTools", () => {expect(provider.getTools()).toEqual([]);});- it("notifies its listeners when the active tool or its lock changes", async () => {+ it("notifies its listeners when a tool, the zoom or the history changes", async () => {const { provider } = await mount();const listener = vi.fn();const unsubscribe = provider.subscribe(listener);+ const getEnabled = () => provider.getTools()+ .filter((tool) => tool.group !== "tools")+ .map((tool) => `${tool.id}:${tool.isEnabled ?? true}`);- api.change({ type: "selection", locked: false });+ api.change({});expect(listener).not.toHaveBeenCalled();- api.change({ type: "rectangle", locked: false });- api.change({ type: "rectangle", locked: true });+ api.change({ activeTool: { type: "rectangle", locked: false } });+ api.change({ activeTool: { type: "rectangle", locked: true } });expect(listener).toHaveBeenCalledTimes(2);expect(provider.getTools().filter((tool) => tool.isOn).map((tool) => tool.id)).toEqual([ "rectangle", "lock" ]);+ api.change({ zoom: { value: 30 } });+ expect(listener).toHaveBeenCalledTimes(3);+ expect(getEnabled()).toEqual([+ "undo:true", "redo:false", "zoomOut:true", "resetZoom:true", "zoomIn:false"+ ]);++ await act(async () => {+ container.querySelector("[data-testid=button-redo]")?.removeAttribute("disabled");+ });+ expect(listener).toHaveBeenCalledTimes(4);+ expect(getEnabled()).toContain("redo:true");+unsubscribe();- api.change({ type: "text", locked: true });- expect(listener).toHaveBeenCalledTimes(2);+ api.change({ zoom: { value: 0.1 } });+ expect(listener).toHaveBeenCalledTimes(4);+ expect(getEnabled()).toContain("zoomOut:false");});it("runs a tool with the focus in the drawing", async () => {@@ -104,24 +140,60 @@ describe("CanvasEmbedTools", () => {expect(document.activeElement).toBe(container.querySelector(".excalidraw-container"));provider.execute("lock");- expect(api.updateScene).toHaveBeenCalledWith({+ expect(api.updateScene).toHaveBeenLastCalledWith({appState: { activeTool: expect.objectContaining({ type: "selection", locked: true }) }});+ provider.execute("undo");+ expect(undo).toHaveBeenCalledTimes(1);++ // Zooms around the center of the 800 × 400 view, as Excalidraw's zoom buttons do.+ provider.execute("zoomIn");+ expect(api.updateScene).toHaveBeenLastCalledWith({+ appState: {+ scrollX: expect.closeTo(10 + 400 / 1.1 - 400),+ scrollY: expect.closeTo(20 + 200 / 1.1 - 200),+ zoom: { value: 1.1 }+ }+ });++ api.change({ zoom: { value: 2 } });+ provider.execute("resetZoom");+ expect(api.updateScene).toHaveBeenLastCalledWith({+ appState: { scrollX: 210, scrollY: 120, zoom: { value: 1 } }+ });+provider.execute("magicframe");expect(api.setActiveTool).toHaveBeenCalledTimes(1);- expect(api.updateScene).toHaveBeenCalledTimes(1);+ expect(api.updateScene).toHaveBeenCalledTimes(3);});});-/** An Excalidraw API whose active tool the spec changes. */+/** The part of Excalidraw's app state that the tools read. */+interface FakeAppState {+ activeTool: { type: string; locked: boolean };+ zoom: { value: number };+ scrollX: number;+ scrollY: number;+ width: number;+ height: number;+}++/** An Excalidraw API whose app state the spec changes. */function createApi() {- let activeTool = { type: "selection", locked: false } as ActiveTool;+ let appState: FakeAppState = {+ activeTool: { type: "selection", locked: false },+ zoom: { value: 1 },+ scrollX: 10,+ scrollY: 20,+ width: 800,+ height: 400+ };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 getAppState = () => appState as unknown as AppState;const api = {getAppState,@@ -138,8 +210,8 @@ function createApi() {unsubscribe,setActiveTool,updateScene,- change(next: Pick<ActiveTool, "type" | "locked">) {- activeTool = { ...activeTool, ...next } as ActiveTool;+ change(next: Partial<FakeAppState>) {+ appState = { ...appState, ...next };onChange?.([], getAppState());}};diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsxindex cab2fec09a..8bda4f312e 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx@@ -1,5 +1,12 @@import { useI18n } from "@excalidraw/excalidraw";-import type { AppState, ExcalidrawImperativeAPI, ToolType } from "@excalidraw/excalidraw/types";+import type {+ AppState, ExcalidrawImperativeAPI, NormalizedZoomValue, ToolType+} from "@excalidraw/excalidraw/types";+import redoIcon from "boxicons/svg/regular/bx-redo.svg?raw";+import resetZoomIcon from "boxicons/svg/regular/bx-reset.svg?raw";+import undoIcon from "boxicons/svg/regular/bx-undo.svg?raw";+import zoomInIcon from "boxicons/svg/regular/bx-zoom-in.svg?raw";+import zoomOutIcon from "boxicons/svg/regular/bx-zoom-out.svg?raw";import type { RefObject } from "preact";import { useEffect, useState } from "preact/hooks";@@ -16,7 +23,19 @@ const TOOLS = [] as const satisfies readonly ToolType[];const LOCK = "lock";+/** Excalidraw's zoom step and limits, from its own zoom buttons. */+const ZOOM_STEP = 0.1;+const MIN_ZOOM = 0.1;+const MAX_ZOOM = 30;+/** The zoom that each zoom button sets, from the current one. */+const ZOOMS: Record<string, (zoom: number) => number> = {+ zoomOut: (zoom) => zoom - ZOOM_STEP,+ resetZoom: () => 1,+ zoomIn: (zoom) => zoom + ZOOM_STEP+};+type Tool = typeof TOOLS[number];+type HistoryAction = "undo" | "redo";/** Excalidraw's `t()`, for a key such as `toolBar.rectangle`. */type Translate = (key: string) => string;@@ -27,8 +46,8 @@ interface CanvasEmbedToolsProps {}/**- * Adds Excalidraw's tools to the toolbar of the embed that shows the drawing. Renders inside- * `<Excalidraw>`, for its translations.+ * Adds Excalidraw's tools, undo and redo, and zoom 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.@@ -53,51 +72,89 @@ export default function CanvasEmbedTools({ rootRef, apiRef }: CanvasEmbedToolsPrreturn null;}-/** Excalidraw's tools, as buttons of the toolbar of the embed that shows the drawing. */+/** Excalidraw's tools and commands, as buttons of the toolbar of the embed with 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 = "";+ /** The tools as last notified, to notify the listeners only when they change. */+ private shownTools = "";constructor(private readonly rootRef: RefObject<HTMLElement>) {}- /** Follows the active tool of `api`, until the returned function is called. */+ /** Follows `api` and its undo and redo buttons, 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());+ const unsubscribe = api.onChange(() => this.update());+ // Excalidraw enables its undo and redo buttons once it renders them again.+ const observer = new MutationObserver(() => this.update());+ const root = this.rootRef.current;+ if (root) {+ observer.observe(root, {+ subtree: true,+ childList: true,+ attributes: true,+ attributeFilter: [ "disabled" ]+ });+ }+ this.update();return () => {unsubscribe();+ observer.disconnect();this.api = null;- this.shownTool = "";- this.notify();+ this.update();};}setTranslate(translate: Translate) {this.translate = translate;- this.notify();+ this.update();}getTools(): ContentEmbedTool[] {- const activeTool = this.api?.getAppState().activeTool;- if (!activeTool) {+ const appState = this.api?.getAppState();+ if (!appState) {return [];}- const tools = [+ const { activeTool, zoom } = appState;+ const drawingTools = [...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- }));+ const zoomPercent = Math.round(zoom.value * 100);+ return [+ ...drawingTools.map(({ id, isOn }, index) => ({+ id,+ label: this.t(`toolBar.${id}`),+ text: String(index + 1),+ isOn,+ group: "tools"+ })),+ this.getHistoryTool("undo", undoIcon),+ this.getHistoryTool("redo", redoIcon),+ {+ id: "zoomOut",+ label: this.t("buttons.zoomOut"),+ icon: zoomOutIcon,+ isEnabled: zoom.value > MIN_ZOOM,+ group: "zoom"+ },+ {+ id: "resetZoom",+ label: `${this.t("buttons.resetZoom")} (${zoomPercent}%)`,+ icon: resetZoomIcon,+ group: "zoom"+ },+ {+ id: "zoomIn",+ label: this.t("buttons.zoomIn"),+ icon: zoomInIcon,+ isEnabled: zoom.value < MAX_ZOOM,+ group: "zoom"+ }+ ];}execute(id: string) {@@ -110,10 +167,15 @@ export class CanvasTools implements ContentEmbedToolProvider {container.focus({ preventScroll: true });}- const { activeTool } = api.getAppState();- if (id === LOCK) {- const locked = !activeTool.locked;- api.updateScene({ appState: { activeTool: { ...activeTool, locked } } });+ const appState = api.getAppState();+ const getZoom = ZOOMS[id];+ if (id === "undo" || id === "redo") {+ this.getHistoryButton(id)?.click();+ } else if (getZoom) {+ api.updateScene({ appState: getZoomState(appState, getZoom(appState.zoom.value)) });+ } else if (id === LOCK) {+ const locked = !appState.activeTool.locked;+ api.updateScene({ appState: { activeTool: { ...appState.activeTool, locked } } });} else if (isTool(id)) {api.setActiveTool({ type: id });}@@ -126,22 +188,54 @@ export class CanvasTools implements ContentEmbedToolProvider {};}- private update(appState: AppState) {- const { type, locked } = appState.activeTool;- const shownTool = `${type}:${locked}`;- if (shownTool !== this.shownTool) {- this.shownTool = shownTool;- this.notify();+ private update() {+ const shownTools = JSON.stringify(this.getTools());+ if (shownTools !== this.shownTools) {+ this.shownTools = shownTools;+ for (const listener of this.listeners) {+ listener();+ }}}- private notify() {- for (const listener of this.listeners) {- listener();- }+ private t(key: string) {+ return this.translate?.(key) ?? key;+ }++ /** Undo or redo, enabled while Excalidraw's own button is: Excalidraw keeps the history. */+ private getHistoryTool(id: HistoryAction, icon: string): ContentEmbedTool {+ const button = this.getHistoryButton(id);+ return {+ id,+ label: this.t(`buttons.${id}`),+ icon,+ isEnabled: !!button && !button.disabled,+ group: "history"+ };+ }++ /** Excalidraw's undo or redo button, which the canvas layout hides. */+ private getHistoryButton(id: HistoryAction) {+ return this.rootRef.current+ ?.querySelector<HTMLButtonElement>(`[data-testid="button-${id}"]`) ?? null;}}function isTool(id: string): id is Tool {return (TOOLS as readonly string[]).includes(id);}++/**+ * The scroll and the zoom that zoom the view to `zoom` around its center, as Excalidraw's own+ * zoom buttons compute them.+ */+function getZoomState(appState: AppState, zoom: number) {+ const value = Math.min(Math.max(Math.round(zoom * 1e6) / 1e6, MIN_ZOOM), MAX_ZOOM);+ const centerX = appState.width / 2;+ const centerY = appState.height / 2;+ return {+ scrollX: appState.scrollX + centerX / value - centerX / appState.zoom.value,+ scrollY: appState.scrollY + centerY / value - centerY / appState.zoom.value,+ zoom: { value: value as NormalizedZoomValue }+ };+}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.tsindex 899ac0c231..00060e391d 100644--- a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts+++ b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts@@ -1,11 +1,18 @@/** 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;+ label: string;+ /** The text of a button without an icon. */+ text?: string;+ /** The SVG of the icon of the button. */+ icon?: string;+ /** Whether a button that toggles is on. A command leaves it out. */+ isOn?: boolean;+ /** `true` when left out. */+ isEnabled?: boolean;+ /** A separator goes between buttons of different groups. */+ group?: string;}/** The buttons that the content of an embed, such as a canvas drawing, adds to its toolbar. */diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 5cbace69ad..17a10db4db 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -33,11 +33,18 @@ declare global {/** 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;+ label: string;+ /** The text of a button without an icon. */+ text?: string;+ /** The SVG of the icon of the button. */+ icon?: string;+ /** Whether a button that toggles is on. A command leaves it out. */+ isOn?: boolean;+ /** `true` when left out. */+ isEnabled?: boolean;+ /** A separator goes between buttons of different groups. */+ group?: string;}/** The buttons that the content of an embed, such as a canvas drawing, adds to its toolbar. */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.tsindex 9abd4dc64d..3b9eb7ded1 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts@@ -10,10 +10,24 @@ 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;+const ICON = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"></svg>";+const SELECTION: Tool = {+ id: "selection", label: "Selection", text: "1", isOn: true, group: "tools"+};+const RECTANGLE: Tool = {+ id: "rectangle", label: "Rectangle", text: "2", isOn: false, group: "tools"+};+const UNDO: Tool = { id: "undo", label: "Undo", icon: ICON, isEnabled: false, group: "history" };++interface Tool {+ id: string;+ label: string;+ text?: string;+ icon?: string;+ isOn?: boolean;+ isEnabled?: boolean;+ group?: string;+}describe("ContentEmbedTools", () => {let editor: ClassicEditor;@@ -62,11 +76,18 @@ describe("ContentEmbedTools", () => {}function getButtonStates(tools: ContentEmbedToolsView) {- return [ ...tools.buttons ].map((button) => [- button.label, button.tooltip, button.ariaLabel, button.isOn, button.withText+ return tools.buttons.map((button) => [+ button.label, button.withText, button.icon, button.tooltip, button.ariaLabel,+ button.isToggleable, button.isOn, button.isEnabled]);}+ /** The labels of the buttons, and `|` for each separator, in order. */+ function getItems(tools: ContentEmbedToolsView) {+ return [ ...tools.element?.children ?? [] ].map((item) =>+ item.classList.contains("ck-toolbar__separator") ? "|" : item.textContent);+ }+it("shows the tools of the selected embed's content, and hides them elsewhere", () => {const tools = createView();setModelData(editor.model, "<paragraph>foo[]</paragraph>");@@ -81,8 +102,8 @@ describe("ContentEmbedTools", () => {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 ]+ [ "1", true, undefined, "Selection", "Selection", true, true, true ],+ [ "2", true, undefined, "Rectangle", "Rectangle", true, false, true ]]);setModelData(editor.model, "<paragraph>foo[]</paragraph>");@@ -91,6 +112,19 @@ describe("ContentEmbedTools", () => {expect(tools.isVisible).toBe(false);});+ it("shows a command with an icon, and separates the groups of tools", () => {+ const tools = createView();+ selectEmbed();++ provider.change([ SELECTION, RECTANGLE, UNDO ]);+ expect(getButtonStates(tools)[2])+ .toEqual([ "Undo", false, ICON, "Undo", "Undo", false, false, false ]);+ expect(getItems(tools)).toEqual([ "1", "2", "|", "Undo" ]);++ provider.change([ SELECTION, RECTANGLE, { ...UNDO, isEnabled: true } ]);+ expect(tools.buttons[2]?.isEnabled).toBe(true);+ });+it("shows no tools for content without any, or for a host that offers none", () => {const tools = createView();getContentEmbedTools.mockReturnValue(null);@@ -109,7 +143,7 @@ describe("ContentEmbedTools", () => {it("runs a tool without taking the focus", () => {const tools = createView();selectEmbed();- const rectangle = tools.buttons.get(1);+ const rectangle = tools.buttons[1];const mousedown = new MouseEvent("mousedown", { bubbles: true, cancelable: true });rectangle?.element?.dispatchEvent(mousedown);rectangle?.fire("execute");@@ -122,15 +156,16 @@ describe("ContentEmbedTools", () => {const tools = createView();selectEmbed();const update = vi.spyOn(editor.ui, "update");- const first = tools.buttons.first;+ const first = tools.buttons[0];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(tools.buttons.map((button) => button.isOn)).toEqual([ false, true ]);+ expect(tools.buttons[0]).toBe(first);expect(update).not.toHaveBeenCalled();provider.change([ RECTANGLE ]);- expect(getButtonStates(tools)).toEqual([ [ "2", "Rectangle", "Rectangle", false, true ] ]);+ expect(getButtonStates(tools))+ .toEqual([ [ "2", true, undefined, "Rectangle", "Rectangle", true, false, true ] ]);expect(update).toHaveBeenCalledTimes(1);provider.change([]);@@ -145,7 +180,7 @@ describe("ContentEmbedTools", () => {}tools.focus();- expect(document.activeElement).toBe(tools.buttons.first?.element);+ expect(document.activeElement).toBe(tools.buttons[0]?.element);tools.destroy();expect(provider.unsubscribe).toHaveBeenCalledTimes(1);diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.tsindex c23613c580..1f2823acf2 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts@@ -1,6 +1,8 @@import "../../theme/content_embed_tools.css";-import { ButtonView, type Locale, Plugin, View, type ViewCollection } from "ckeditor5";+import {+ ButtonView, type Locale, Plugin, ToolbarSeparatorView, View, type ViewCollection+} from "ckeditor5";import ContentEmbed from "./content_embed.js";@@ -62,15 +64,19 @@ type ContentEmbedToolsResizeEvent = {export class ContentEmbedToolsView extends View {declare public isVisible: boolean;- public readonly buttons: ViewCollection<ButtonView>;+ /** The buttons, in the order of the tools. */+ public buttons: ButtonView[] = [];+ /** The buttons and the separators between their groups. */+ private readonly items: ViewCollection;private provider: ContentEmbedToolProvider | null = null;private unsubscribe: (() => void) | undefined;- private toolIds: string[] = [];+ /** The group and the id of each tool, to create the buttons again only for another set. */+ private toolKeys: string[] = [];constructor(locale?: Locale) {super(locale);this.set("isVisible", false);- this.buttons = this.createCollection();+ this.items = this.createCollection();const bind = this.bindTemplate;this.setTemplate({@@ -82,7 +88,7 @@ export class ContentEmbedToolsView extends View {bind.if("isVisible", "ck-hidden", isVisible => !isVisible)]},- children: this.buttons+ children: this.items});}@@ -103,7 +109,7 @@ export class ContentEmbedToolsView extends View {}focus() {- this.buttons.first?.focus();+ this.buttons[0]?.focus();}override destroy() {@@ -114,22 +120,25 @@ export class ContentEmbedToolsView extends View {/** 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]);+ const keys = tools.map(tool => `${tool.group ?? ""}/${tool.id}`);+ const isNewSet = keys.length !== this.toolKeys.length+ || keys.some((key, index) => key !== this.toolKeys[index]);if (isNewSet) {- this.toolIds = ids;- this.buttons.clear();- this.buttons.addMany(ids.map(id => this.createButton(id)));+ this.toolKeys = keys;+ this.createButtons(tools);}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.buttons[index]?.set({+ label: tool.text ?? tool.label,+ withText: tool.text !== undefined,+ icon: tool.icon,+ tooltip: tool.label,+ ariaLabel: tool.label,+ isToggleable: tool.isOn !== undefined,+ isOn: tool.isOn ?? false,+ isEnabled: tool.isEnabled ?? true});}this.isVisible = tools.length > 0;@@ -137,9 +146,26 @@ export class ContentEmbedToolsView extends View {return isNewSet;}+ /** Creates a button for each tool, with a separator between groups. */+ private createButtons(tools: ContentEmbedTool[]) {+ this.items.clear();+ this.buttons = [];++ let group: string | undefined;+ for (const tool of tools) {+ if (this.buttons.length && tool.group !== group) {+ this.items.add(new ToolbarSeparatorView(this.locale));+ }+ group = tool.group;++ const button = this.createButton(tool.id);+ this.buttons.push(button);+ this.items.add(button);+ }+ }+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()) }