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: reorganize the tools in toolbar
Adorian Doran831d94432594
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsxindex 368f4e49fa..b74a0f0fb2 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx@@ -12,10 +12,10 @@ vi.mock("@excalidraw/excalidraw", () => ({const { default: CanvasEmbedTools } = await import("./CanvasEmbedTools");const { getContentEmbedTools } = await import("../text/content_embed_tools");-const DRAWING_TOOL_IDS = [- "selection", "rectangle", "diamond", "ellipse", "arrow", "line", "freedraw", "text", "image",- "eraser", "hand", "frame", "embeddable", "laser", "lock"+const MAIN_TOOL_IDS = [+ "hand", "rectangle", "diamond", "ellipse", "arrow", "line", "freedraw", "text", "image"];+const EXTRA_TOOL_IDS = [ "selection", "eraser", "frame", "embeddable", "laser" ];const ICON = expect.stringContaining("<svg");describe("CanvasEmbedTools", () => {@@ -68,15 +68,28 @@ describe("CanvasEmbedTools", () => {expect(getContentEmbedTools(document.createElement("figure"))).toBeNull();const tools = provider.getTools();- const count = DRAWING_TOOL_IDS.length;- expect(tools.slice(0, count)).toEqual(DRAWING_TOOL_IDS.map((id, index) => ({+ const count = MAIN_TOOL_IDS.length;+ expect(tools[0]).toEqual({+ id: "lock", label: "t:toolBar.lock", text: "1", isOn: false, group: "lock"+ });+ expect(tools.slice(1, count + 1)).toEqual(MAIN_TOOL_IDS.map((id, index) => ({id,label: `t:toolBar.${id}`,- text: String(index + 1),- isOn: id === "selection",+ text: String(index + 2),+ isOn: false,group: "tools"})));- expect(tools.slice(count)).toEqual([+ expect(tools[count + 1]).toEqual({+ id: "moreTools",+ label: "t:toolBar.extraTools",+ icon: ICON,+ isOn: true,+ group: "moreTools",+ children: EXTRA_TOOL_IDS.map((id) => ({+ id, label: `t:toolBar.${id}`, isOn: id === "selection"+ }))+ });+ expect(tools.slice(count + 2)).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" },{@@ -102,8 +115,12 @@ describe("CanvasEmbedTools", () => {const listener = vi.fn();const unsubscribe = provider.subscribe(listener);const getEnabled = () => provider.getTools()- .filter((tool) => tool.group !== "tools")+ .filter((tool) => tool.group === "history" || tool.group === "zoom").map((tool) => `${tool.id}:${tool.isEnabled ?? true}`);+ const getOn = () => provider.getTools()+ .flatMap((tool) => [ tool, ...tool.children ?? [] ])+ .filter((tool) => tool.isOn)+ .map((tool) => tool.id);api.change({});expect(listener).not.toHaveBeenCalled();@@ -111,11 +128,14 @@ describe("CanvasEmbedTools", () => {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" ]);+ expect(getOn()).toEqual([ "lock", "rectangle" ]);- api.change({ zoom: { value: 30 } });+ api.change({ activeTool: { type: "eraser", locked: true } });expect(listener).toHaveBeenCalledTimes(3);+ expect(getOn()).toEqual([ "lock", "moreTools", "eraser" ]);++ api.change({ zoom: { value: 30 } });+ expect(listener).toHaveBeenCalledTimes(4);expect(getEnabled()).toEqual(["undo:true", "redo:false", "zoomOut:true", "resetZoom:true", "zoomIn:false"]);@@ -123,12 +143,12 @@ describe("CanvasEmbedTools", () => {await act(async () => {container.querySelector("[data-testid=button-redo]")?.removeAttribute("disabled");});- expect(listener).toHaveBeenCalledTimes(4);+ expect(listener).toHaveBeenCalledTimes(5);expect(getEnabled()).toContain("redo:true");unsubscribe();api.change({ zoom: { value: 0.1 } });- expect(listener).toHaveBeenCalledTimes(4);+ expect(listener).toHaveBeenCalledTimes(5);expect(getEnabled()).toContain("zoomOut:false");});@@ -139,6 +159,9 @@ describe("CanvasEmbedTools", () => {expect(api.setActiveTool).toHaveBeenCalledWith({ type: "rectangle" });expect(document.activeElement).toBe(container.querySelector(".excalidraw-container"));+ provider.execute("laser");+ expect(api.setActiveTool).toHaveBeenLastCalledWith({ type: "laser" });+provider.execute("lock");expect(api.updateScene).toHaveBeenLastCalledWith({appState: { activeTool: expect.objectContaining({ type: "selection", locked: true }) }@@ -164,7 +187,8 @@ describe("CanvasEmbedTools", () => {});provider.execute("magicframe");- expect(api.setActiveTool).toHaveBeenCalledTimes(1);+ provider.execute("moreTools");+ expect(api.setActiveTool).toHaveBeenCalledTimes(2);expect(api.updateScene).toHaveBeenCalledTimes(3);});});diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsxindex 73c4294139..50a1fc7be5 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx@@ -2,6 +2,7 @@ import { useI18n } from "@excalidraw/excalidraw";import type {AppState, ExcalidrawImperativeAPI, NormalizedZoomValue, ToolType} from "@excalidraw/excalidraw/types";+import moreToolsIcon from "boxicons/svg/regular/bx-category.svg?raw";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";@@ -16,12 +17,18 @@ import {registerContentEmbedTools} from "../text/content_embed_tools";-/** The tools in the order of their buttons. Excalidraw also selects the first nine with 1 to 9. */-export const TOOLS = [- "selection", "rectangle", "diamond", "ellipse", "arrow", "line", "freedraw", "text", "image",- "eraser", "hand", "frame", "embeddable", "laser"+/** The tools with a button of their own, in the order of their buttons. */+export const MAIN_TOOLS = [+ "hand", "rectangle", "diamond", "ellipse", "arrow", "line", "freedraw", "text", "image"] as const satisfies readonly ToolType[];+/** The tools in the "More tools" menu. */+export const EXTRA_TOOLS = [+ "selection", "eraser", "frame", "embeddable", "laser"+] as const satisfies readonly ToolType[];+const TOOLS = [ ...MAIN_TOOLS, ...EXTRA_TOOLS ];export const LOCK = "lock";+/** The button that opens the "More tools" menu, named by Excalidraw's `toolBar.extraTools`. */+export const MORE_TOOLS = "moreTools";/** The commands that click Excalidraw's own `button-undo` and `button-redo`. */export const HISTORY_ACTIONS = [ "undo", "redo" ] as const;@@ -126,19 +133,34 @@ export class CanvasTools implements ContentEmbedToolProvider {}const { activeTool, zoom } = appState;- const drawingTools = [- ...TOOLS.map((type) => ({ id: type, isOn: activeTool.type === type })),- { id: LOCK, isOn: activeTool.locked }- ];const zoomPercent = Math.round(zoom.value * 100);return [- ...drawingTools.map(({ id, isOn }, index) => ({- id,- label: this.t(`toolBar.${id}`),- text: String(index + 1),- isOn,+ {+ id: LOCK,+ label: this.t("toolBar.lock"),+ text: "1",+ isOn: activeTool.locked,+ group: "lock"+ },+ ...MAIN_TOOLS.map((type, index) => ({+ id: type,+ label: this.t(`toolBar.${type}`),+ text: String(index + 2),+ isOn: activeTool.type === type,group: "tools"})),+ {+ id: MORE_TOOLS,+ label: this.t("toolBar.extraTools"),+ icon: moreToolsIcon,+ isOn: EXTRA_TOOLS.some((type) => activeTool.type === type),+ group: MORE_TOOLS,+ children: EXTRA_TOOLS.map((type) => ({+ id: type,+ label: this.t(`toolBar.${type}`),+ isOn: activeTool.type === type+ }))+ },this.getHistoryTool("undo", undoIcon),this.getHistoryTool("redo", redoIcon),{diff --git a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.tsindex 25f82c4db6..75eed1042f 100644--- a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts+++ b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts@@ -7,7 +7,7 @@ import { describe, expect, it, vi } from "vitest";vi.mock("@excalidraw/excalidraw", () => ({ MainMenu: {}, useI18n: vi.fn() }));const {- HISTORY_ACTIONS, LOCK, MAX_ZOOM, MIN_ZOOM, TOOLS, ZOOM_STEP, ZOOMS+ EXTRA_TOOLS, HISTORY_ACTIONS, LOCK, MAIN_TOOLS, MAX_ZOOM, MIN_ZOOM, ZOOM_STEP, ZOOMS} = await import("./CanvasEmbedTools");const { LIBRARY_SIDEBAR } = await import("./CanvasDrawingMenu");@@ -58,7 +58,7 @@ describe("Excalidraw contract of the canvas drawing", () => {it("names every button of the toolbar with Excalidraw's own translations", () => {const source = readBundle(developmentDir, [ ".js" ]);const keys = [- ...[ ...TOOLS, LOCK ].map((id) => `toolBar.${id}`),+ ...[ ...MAIN_TOOLS, ...EXTRA_TOOLS, LOCK, "extraTools" ].map((id) => `toolBar.${id}`),...[ ...HISTORY_ACTIONS, ...Object.keys(ZOOMS) ].map((id) => `buttons.${id}`)];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 00060e391d..38b9a2a65b 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@@ -13,6 +13,8 @@ export interface ContentEmbedTool {isEnabled?: boolean;/** A separator goes between buttons of different groups. */group?: string;+ /** The tools of the menu that the button opens. */+ children?: ContentEmbedTool[];}/** 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 17a10db4db..ba5727b560 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -45,6 +45,8 @@ declare global {isEnabled?: boolean;/** A separator goes between buttons of different groups. */group?: string;+ /** The tools of the menu that the button opens. */+ children?: ContentEmbedTool[];}/** 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 3b9eb7ded1..b2787fa8bc 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@@ -1,5 +1,5 @@import {- ClassicEditor, Essentials, Paragraph, Widget, _setModelData as setModelData+ ClassicEditor, DropdownView, Essentials, Paragraph, Widget, _setModelData as setModelData} from "ckeditor5";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -27,8 +27,21 @@ interface Tool {isOn?: boolean;isEnabled?: boolean;group?: string;+ children?: Tool[];}+const MORE_TOOLS: Tool = {+ id: "more",+ label: "More tools",+ icon: ICON,+ isOn: false,+ group: "more",+ children: [+ { id: "eraser", label: "Eraser", isOn: false },+ { id: "laser", label: "Laser pointer", isOn: true }+ ]+};+describe("ContentEmbedTools", () => {let editor: ClassicEditor;let provider: ReturnType<typeof createProvider>;@@ -76,12 +89,17 @@ describe("ContentEmbedTools", () => {}function getButtonStates(tools: ContentEmbedToolsView) {- return tools.buttons.map((button) => [+ return getButtons(tools).map((button) => [button.label, button.withText, button.icon, button.tooltip, button.ariaLabel,button.isToggleable, button.isOn, button.isEnabled]);}+ /** The button of each tool: its own, or the one that opens its menu. */+ function getButtons(tools: ContentEmbedToolsView) {+ return tools.views.map((item) => item instanceof DropdownView ? item.buttonView : item);+ }+/** The labels of the buttons, and `|` for each separator, in order. */function getItems(tools: ContentEmbedToolsView) {return [ ...tools.element?.children ?? [] ].map((item) =>@@ -122,7 +140,44 @@ describe("ContentEmbedTools", () => {expect(getItems(tools)).toEqual([ "1", "2", "|", "Undo" ]);provider.change([ SELECTION, RECTANGLE, { ...UNDO, isEnabled: true } ]);- expect(tools.buttons[2]?.isEnabled).toBe(true);+ expect(getButtons(tools)[2]?.isEnabled).toBe(true);+ });++ it("shows the children of a tool in a menu, without taking the focus", () => {+ const tools = createView();+ selectEmbed();+ provider.change([ RECTANGLE, MORE_TOOLS ]);+ const menu = tools.views[1];+ if (!(menu instanceof DropdownView)) {+ throw new Error("Expected a menu.");+ }+ expect(getItems(tools)).toEqual([ "2", "|", "More tools" ]);+ expect([ menu.buttonView.label, menu.buttonView.withText, menu.buttonView.icon ])+ .toEqual([ "More tools", false, ICON ]);++ menu.isOpen = true;+ const getMenuItems = () => [+ ...menu.panelView.element?.querySelectorAll(".ck-button") ?? []+ ].map((item) => `${item.textContent}:${item.classList.contains("ck-on")}`);+ expect(getMenuItems()).toEqual([ "Eraser:false", "Laser pointer:true" ]);+ expect(menu.buttonView.class).toBeUndefined();++ const children = [+ { id: "eraser", label: "Eraser", isOn: true },+ { id: "laser", label: "Laser pointer", isOn: false }+ ];+ provider.change([ RECTANGLE, { ...MORE_TOOLS, isOn: true, children } ]);+ expect(tools.views[1]).toBe(menu);+ expect(getMenuItems()).toEqual([ "Eraser:true", "Laser pointer:false" ]);+ expect(menu.buttonView.class).toBe("ck-on");++ for (const element of [ menu.buttonView.element, menu.panelView.element ]) {+ const mousedown = new MouseEvent("mousedown", { bubbles: true, cancelable: true });+ element?.dispatchEvent(mousedown);+ expect(mousedown.defaultPrevented).toBe(true);+ }+ menu.panelView.element?.querySelector<HTMLElement>(".ck-button")?.click();+ expect(provider.execute).toHaveBeenCalledWith("eraser");});it("shows no tools for content without any, or for a host that offers none", () => {@@ -143,7 +198,7 @@ describe("ContentEmbedTools", () => {it("runs a tool without taking the focus", () => {const tools = createView();selectEmbed();- const rectangle = tools.buttons[1];+ const rectangle = getButtons(tools)[1];const mousedown = new MouseEvent("mousedown", { bubbles: true, cancelable: true });rectangle?.element?.dispatchEvent(mousedown);rectangle?.fire("execute");@@ -156,11 +211,11 @@ describe("ContentEmbedTools", () => {const tools = createView();selectEmbed();const update = vi.spyOn(editor.ui, "update");- const first = tools.buttons[0];+ const first = getButtons(tools)[0];provider.change([ { ...SELECTION, isOn: false }, { ...RECTANGLE, isOn: true } ]);- expect(tools.buttons.map((button) => button.isOn)).toEqual([ false, true ]);- expect(tools.buttons[0]).toBe(first);+ expect(getButtons(tools).map((button) => button.isOn)).toEqual([ false, true ]);+ expect(getButtons(tools)[0]).toBe(first);expect(update).not.toHaveBeenCalled();provider.change([ RECTANGLE ]);@@ -180,7 +235,7 @@ describe("ContentEmbedTools", () => {}tools.focus();- expect(document.activeElement).toBe(tools.buttons[0]?.element);+ expect(document.activeElement).toBe(getButtons(tools)[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 1f2823acf2..d3f263ccb5 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts@@ -1,7 +1,9 @@import "../../theme/content_embed_tools.css";import {- ButtonView, type Locale, Plugin, ToolbarSeparatorView, View, type ViewCollection+ addListToDropdown, ButtonView, Collection, createDropdown, DropdownView,+ type ListDropdownButtonDefinition, type Locale, Plugin, ToolbarSeparatorView, View,+ type ViewCollection, ViewModel} from "ckeditor5";import ContentEmbed from "./content_embed.js";@@ -60,17 +62,24 @@ type ContentEmbedToolsResizeEvent = {args: [];};+/** The view of a tool, and the way it shows a new state of the tool. */+interface ToolView {+ view: ButtonView | DropdownView;+ update(tool: ContentEmbedTool): void;+}+/** The buttons of a `ContentEmbedToolProvider`, updated when the provider changes. */export class ContentEmbedToolsView extends View {declare public isVisible: boolean;- /** The buttons, in the order of the tools. */- public buttons: ButtonView[] = [];- /** The buttons and the separators between their groups. */+ /** The view of each tool: a button, or a dropdown for a tool with children. */+ public views: Array<ButtonView | DropdownView> = [];+ /** The views and the separators between their groups. */private readonly items: ViewCollection;+ private updaters: Array<(tool: ContentEmbedTool) => void> = [];private provider: ContentEmbedToolProvider | null = null;private unsubscribe: (() => void) | undefined;- /** The group and the id of each tool, to create the buttons again only for another set. */+ /** The group and the ids of each tool, to create the views again only for another set. */private toolKeys: string[] = [];constructor(locale?: Locale) {@@ -109,7 +118,7 @@ export class ContentEmbedToolsView extends View {}focus() {- this.buttons[0]?.focus();+ this.views[0]?.focus();}override destroy() {@@ -117,64 +126,127 @@ export class ContentEmbedToolsView extends View {super.destroy();}- /** Shows the tools of the provider. Returns whether the buttons were created again. */+ /** Shows the tools of the provider. Returns whether the views were created again. */private showTools() {const tools = this.provider?.getTools() ?? [];- const keys = tools.map(tool => `${tool.group ?? ""}/${tool.id}`);+ const keys = tools.map(tool => [+ tool.group ?? "", tool.id, ...tool.children?.map(child => child.id) ?? []+ ].join("/"));const isNewSet = keys.length !== this.toolKeys.length|| keys.some((key, index) => key !== this.toolKeys[index]);if (isNewSet) {this.toolKeys = keys;- this.createButtons(tools);+ this.createViews(tools);}for (const [ index, tool ] of tools.entries()) {- 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.updaters[index]?.(tool);}this.isVisible = tools.length > 0;return isNewSet;}- /** Creates a button for each tool, with a separator between groups. */- private createButtons(tools: ContentEmbedTool[]) {+ /** Creates a view for each tool, with a separator between groups. */+ private createViews(tools: ContentEmbedTool[]) {this.items.clear();- this.buttons = [];+ this.views = [];+ this.updaters = [];let group: string | undefined;for (const tool of tools) {- if (this.buttons.length && tool.group !== group) {+ if (this.views.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);+ const { view, update } = tool.children+ ? this.createMenu(tool.children)+ : this.createButton(tool.id);+ this.views.push(view);+ this.updaters.push(update);+ this.items.add(view);}}- private createButton(id: string) {+ private createButton(id: string): ToolView {const button = new ButtonView(this.locale);- // Keeps the focus in the content that the tool acts on.- button.extendTemplate({- on: { mousedown: button.bindTemplate.to(evt => evt.preventDefault()) }- });+ keepFocus(button);this.listenTo(button, "execute", () => this.provider?.execute(id));- return button;+ return {+ view: button,+ update: (tool) => button.set({+ ...getButtonFace(tool),+ isToggleable: tool.isOn !== undefined,+ isOn: tool.isOn ?? false,+ isEnabled: tool.isEnabled ?? true+ })+ };}+ /** A dropdown that lists `children`, each run as a tool of its own. */+ private createMenu(children: ContentEmbedTool[]): ToolView {+ const dropdown = createDropdown(this.locale);+ keepFocus(dropdown.buttonView);+ keepFocus(dropdown.panelView);++ const models = children.map(child => new ViewModel({+ toolId: child.id,+ withText: true,+ role: "menuitemradio"+ }));+ const definitions = new Collection<ListDropdownButtonDefinition>();+ for (const model of models) {+ definitions.add({ type: "button", model });+ }+ addListToDropdown(dropdown, definitions);+ this.listenTo(dropdown, "execute", (evt) => {+ const { toolId } = evt.source as { toolId?: string };+ if (toolId) {+ this.provider?.execute(toolId);+ }+ });++ return {+ view: dropdown,+ update: (tool) => {+ // `createDropdown()` binds `isOn` of the button to the dropdown being open.+ dropdown.buttonView.set({+ ...getButtonFace(tool),+ class: tool.isOn ? "ck-on" : undefined+ });+ dropdown.isEnabled = tool.isEnabled ?? true;+ for (const [ index, child ] of (tool.children ?? []).entries()) {+ models[index]?.set({+ label: child.label,+ isOn: child.isOn ?? false,+ isEnabled: child.isEnabled ?? true+ });+ }+ }+ };+ }++}++/** The label, icon and tooltip of the button of `tool`. */+function getButtonFace(tool: ContentEmbedTool) {+ return {+ label: tool.text ?? tool.label,+ withText: tool.text !== undefined,+ icon: tool.icon,+ tooltip: tool.label,+ ariaLabel: tool.label+ };+}++/** Keeps the focus in the content that the tools act on. */+function keepFocus(view: View) {+ view.extendTemplate({+ on: { mousedown: view.bindTemplate.to(evt => evt.preventDefault()) }+ });}declare module "ckeditor5" {