Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/drawing canvas: remove the hamburger menu from the canvas surface, relocate its commands to the toolbar

Adorian Doran45d98ac58c10
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css
index deb14d716e..ed8f60c7d8 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css
@@ -46,7 +46,7 @@
background: none;
}
- /* The main menu offers the library and help. */
+ /* The menus offer the library and help. */
.excalidraw :is(.sidebar-trigger, .help-icon) {
display: none;
}
@@ -116,11 +116,12 @@
width: 100% !important;
}
-/* While `CanvasEmbedTools` sets `data-embed-tools`, 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. */
+/* While `CanvasEmbedTools` sets `data-embed-tools`, the tools, the main menu, 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-editor[data-embed-tools] .excalidraw {
.App-toolbar-container > .App-toolbar,
+ .main-menu-trigger,
.mobile-misc-tools-container > label:has(
[data-testid="toolbar-lock"], [data-testid="toolbar-hand"]
),
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawingMenu.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawingMenu.tsx
index 7bb2493d0b..4d265788a0 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawingMenu.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawingMenu.tsx
@@ -3,10 +3,7 @@ import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";
import type { RefObject } from "preact";
import Icon from "../../react/Icon";
-import { useExcalidrawTranslation } from "./CanvasEmbedTools";
-
-/** The name of Excalidraw's default sidebar, whose first tab is the library. */
-export const LIBRARY_SIDEBAR = "default";
+import { DEFAULT_SIDEBAR, useExcalidrawTranslation } from "./CanvasEmbedTools";
interface CanvasDrawingMenuProps {
apiRef: RefObject<ExcalidrawImperativeAPI | null>;
@@ -26,7 +23,7 @@ export default function CanvasDrawingMenu({ apiRef, isEditable }: CanvasDrawingM
{isEditable && (
<MainMenu.Item
icon={<Icon icon="bx bx-library" />}
- onSelect={() => apiRef.current?.toggleSidebar({ name: LIBRARY_SIDEBAR })}
+ onSelect={() => apiRef.current?.toggleSidebar({ name: DEFAULT_SIDEBAR })}
>
{t("toolBar.library")}
</MainMenu.Item>
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx
index 0f8dc645a6..e367eb9a2c 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx
@@ -110,11 +110,27 @@ describe("CanvasEmbedTools", () => {
icon: ICON,
isOn: false,
group: "moreTools",
- children: EXTRA_TOOL_IDS.map((id) => ({
- id,
- label: `t:toolBar.${id}`,
- isOn: id === "selection"
- }))
+ children: [
+ ...EXTRA_TOOL_IDS.map((id) => ({
+ id,
+ label: `t:toolBar.${id}`,
+ isOn: id === "selection"
+ })),
+ {
+ id: "exportImage",
+ label: "t:buttons.exportImage",
+ keystroke: "Ctrl+Shift+E",
+ group: "export"
+ },
+ {
+ id: "searchMenu",
+ label: "t:search.title",
+ keystroke: "Ctrl+F",
+ group: "canvas"
+ },
+ { id: "library", label: "t:toolBar.library", group: "canvas" },
+ { id: "help", label: "t:helpDialog.title", keystroke: "?", group: "canvas" }
+ ]
});
expect(tools.slice(count + 2)).toEqual([
{ id: "undo", label: "t:buttons.undo", icon: ICON, isEnabled: true, group: "history" },
@@ -296,6 +312,31 @@ describe("CanvasEmbedTools", () => {
expect(api.updateScene).toHaveBeenCalledTimes(3);
});
+ it("opens the export, the search, the library and the help from the menu", async () => {
+ const { provider } = await mount();
+
+ provider.execute("exportImage");
+ expect(api.updateScene).toHaveBeenLastCalledWith({
+ appState: { openDialog: { name: "imageExport" } }
+ });
+ expect(document.activeElement).toBe(container.querySelector(".excalidraw-container"));
+
+ provider.execute("searchMenu");
+ expect(api.toggleSidebar).toHaveBeenLastCalledWith({
+ name: "default", tab: "search", force: true
+ });
+
+ provider.execute("library");
+ expect(api.toggleSidebar).toHaveBeenLastCalledWith({ name: "default" });
+
+ provider.execute("help");
+ expect(api.updateScene).toHaveBeenLastCalledWith({
+ appState: { openDialog: { name: "help" } }
+ });
+ expect(api.updateScene).toHaveBeenCalledTimes(2);
+ expect(api.toggleSidebar).toHaveBeenCalledTimes(2);
+ });
+
it("keeps a zoom of a drawing over a locked image inside the image", async () => {
const { provider } = await mount();
api.setElements([ { type: "image", locked: true, x: 0, y: 0, width: 800, height: 400 } ]);
@@ -314,11 +355,12 @@ describe("CanvasEmbedTools", () => {
expect(getIds()).toEqual([ "zoomOut", "resetZoom", "zoomIn" ]);
expect(provider.hasEditableFlag).toBe(true);
- for (const id of [ "rectangle", "frame", "lock", "undo" ]) {
+ for (const id of [ "rectangle", "frame", "lock", "undo", "help", "library" ]) {
provider.execute(id);
}
expect(api.setActiveTool).not.toHaveBeenCalled();
expect(api.updateScene).not.toHaveBeenCalled();
+ expect(api.toggleSidebar).not.toHaveBeenCalled();
expect(undo).not.toHaveBeenCalled();
provider.execute("zoomIn");
@@ -368,6 +410,7 @@ function createApi() {
const unsubscribe = vi.fn();
const setActiveTool = vi.fn();
const updateScene = vi.fn();
+ const toggleSidebar = vi.fn();
const getAppState = () => appState as unknown as AppState;
const api = {
@@ -375,6 +418,7 @@ function createApi() {
getSceneElements: () => elements,
setActiveTool,
updateScene,
+ toggleSidebar,
onChange: (callback: typeof onChange) => {
onChange = callback;
return unsubscribe;
@@ -386,6 +430,7 @@ function createApi() {
unsubscribe,
setActiveTool,
updateScene,
+ toggleSidebar,
setElements(next: FakeElement[]) {
elements = next;
},
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx
index 3f914ebc83..2c49bdef1c 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx
@@ -45,6 +45,51 @@ 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 name of Excalidraw's default sidebar, whose tabs are the library and the search. */
+export const DEFAULT_SIDEBAR = "default";
+export const SEARCH_TAB = "search";
+
+/** A command after the tools in the "More tools" menu. */
+interface MenuCommand {
+ id: string;
+ /** The key of Excalidraw's translation of the label, such as `search.title`. */
+ label: string;
+ /** The keystroke that Excalidraw binds to the command. */
+ keystroke?: string;
+ group: string;
+ run(api: ExcalidrawImperativeAPI): void;
+}
+
+/** The commands after the tools in the "More tools" menu. */
+export const MENU_COMMANDS: readonly MenuCommand[] = [
+ {
+ id: "exportImage",
+ label: "buttons.exportImage",
+ keystroke: "Ctrl+Shift+E",
+ group: "export",
+ run: (api) => api.updateScene({ appState: { openDialog: { name: "imageExport" } } })
+ },
+ {
+ id: "searchMenu",
+ label: "search.title",
+ keystroke: "Ctrl+F",
+ group: "canvas",
+ run: (api) => api.toggleSidebar({ name: DEFAULT_SIDEBAR, tab: SEARCH_TAB, force: true })
+ },
+ {
+ id: "library",
+ label: "toolBar.library",
+ group: "canvas",
+ run: (api) => api.toggleSidebar({ name: DEFAULT_SIDEBAR })
+ },
+ {
+ id: "help",
+ label: "helpDialog.title",
+ keystroke: "?",
+ group: "canvas",
+ run: (api) => api.updateScene({ appState: { openDialog: { name: "help" } } })
+ }
+];
/** Shows the embed in fullscreen, as the button of its title row does while the title is hidden. */
const FULLSCREEN = "fullscreen";
/** The commands that click Excalidraw's own `button-undo` and `button-redo`. */
@@ -247,7 +292,7 @@ export class CanvasTools implements ContentEmbedToolProvider {
return this.translate?.(key) ?? key;
}
- /** The lock, the drawing tools, undo and redo. */
+ /** The lock, the drawing tools with the menu commands, undo and redo. */
private getEditingTools(activeTool: AppState["activeTool"]): ContentEmbedTool[] {
return [
{
@@ -270,12 +315,17 @@ export class CanvasTools implements ContentEmbedToolProvider {
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}`),
- icon: ICONS[type],
- isOn: activeTool.type === type
- }))
+ children: [
+ ...EXTRA_TOOLS.map((type) => ({
+ id: type,
+ label: this.t(`toolBar.${type}`),
+ icon: ICONS[type],
+ isOn: activeTool.type === type
+ })),
+ ...MENU_COMMANDS.map(({ id, label, keystroke, group }) => ({
+ id, label: this.t(label), keystroke, group
+ }))
+ ]
},
this.getHistoryTool("undo", undoIcon),
this.getHistoryTool("redo", redoIcon)
@@ -325,9 +375,12 @@ export class CanvasTools implements ContentEmbedToolProvider {
];
}
- /** Runs the lock, a drawing tool, undo or redo. */
+ /** Runs the lock, a drawing tool, a menu command, undo or redo. */
private runEditingTool(api: ExcalidrawImperativeAPI, appState: AppState, id: string) {
- if (id === "undo" || id === "redo") {
+ const command = MENU_COMMANDS.find((menuCommand) => menuCommand.id === id);
+ if (command) {
+ command.run(api);
+ } else if (id === "undo" || id === "redo") {
this.getHistoryButton(id)?.click();
} else if (id === LOCK) {
const locked = !appState.activeTool.locked;
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.ts
index 68edcf6cb5..ef5a28aca4 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,10 +7,10 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("@excalidraw/excalidraw", () => ({ MainMenu: {}, useI18n: vi.fn() }));
const {
- EXTRA_TOOLS, HISTORY_ACTIONS, LOCK, MAIN_TOOLS, ZOOM_STEP, ZOOMS
+ DEFAULT_SIDEBAR, EXTRA_TOOLS, HISTORY_ACTIONS, LOCK, MAIN_TOOLS, MENU_COMMANDS, SEARCH_TAB,
+ ZOOM_STEP, ZOOMS
} = await import("./CanvasEmbedTools");
const { MAX_ZOOM, MIN_ZOOM } = await import("./drawing_view");
-const { LIBRARY_SIDEBAR } = await import("./CanvasDrawingMenu");
const { FITTED_MENU_STYLES } = await import("./CanvasDrawing");
const { DRAWING_DARK_FILTER, IMAGE_DARK_FILTER } = await import("./persistence");
@@ -68,7 +68,8 @@ describe("Excalidraw contract of the canvas drawing", () => {
const source = readBundle(developmentDir, [ ".js" ]);
const keys = [
...[ ...MAIN_TOOLS, ...EXTRA_TOOLS, LOCK, "extraTools" ].map((id) => `toolBar.${id}`),
- ...[ ...HISTORY_ACTIONS, ...Object.keys(ZOOMS) ].map((id) => `buttons.${id}`)
+ ...[ ...HISTORY_ACTIONS, ...Object.keys(ZOOMS) ].map((id) => `buttons.${id}`),
+ ...MENU_COMMANDS.map((command) => command.label)
];
const missing = keys.filter((key) => {
@@ -106,10 +107,26 @@ describe("Excalidraw contract of the canvas drawing", () => {
}`));
});
- it("opens the library in the sidebar that the main menu names", () => {
+ it("opens the library and the search in the sidebar that the menus name", () => {
const source = readBundle(developmentDir, [ ".js" ]).replace(/\s+/g, "");
- expect(source).toContain(`varDEFAULT_SIDEBAR={name:"${LIBRARY_SIDEBAR}"`);
+ expect(source).toContain(`varDEFAULT_SIDEBAR={name:"${DEFAULT_SIDEBAR}"`);
+ expect(source).toContain(`varCANVAS_SEARCH_TAB="${SEARCH_TAB}";`);
+ });
+
+ it("shows the keystrokes that Excalidraw binds to the commands of the menu", () => {
+ const source = readBundle(developmentDir, [ ".js" ]).replace(/\s+/g, "");
+ // Excalidraw's names of the shortcuts, which its own main menu shows.
+ const names: Record<string, string> = {
+ exportImage: "imageExport", searchMenu: "searchMenu", help: "toggleShortcuts"
+ };
+
+ const missing = MENU_COMMANDS
+ .filter((command) => command.keystroke !== undefined)
+ .map(({ id, keystroke }) =>
+ `${names[id]}:[getShortcutKey("${keystroke?.replace("Ctrl", "CtrlOrCmd")}")]`)
+ .filter((shortcut) => !source.includes(shortcut));
+ expect(missing).toEqual([]);
});
it("fits the context menu in its container with the styles that the top layer replaces", () => {
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.ts
index 9b9b7726b8..c493aea5d9 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
@@ -14,8 +14,13 @@ export interface ContentEmbedTool {
isOn?: boolean;
/** `true` when left out. */
isEnabled?: boolean;
- /** A separator goes between buttons of different groups. */
+ /** A separator goes between buttons, or items of a menu, of different groups. */
group?: string;
+ /**
+ * The keystroke shown beside the label of an item of a menu: CKEditor's notation, such as
+ * `Ctrl+F`, or a single character, such as `?`.
+ */
+ keystroke?: string;
/** The tools of the menu that the button opens. */
children?: ContentEmbedTool[];
/** A class of the button, for the content to style it. */
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
index d202996ca1..5ebb813b36 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
@@ -227,6 +227,9 @@
over the text. To zoom, use the zoom buttons of the canvas toolbar; to
move around the drawing, use the <span class="tn-icon bx bxs-hand"></span> <em>Hand</em> tool.
In fullscreen, the mouse wheel moves and zooms the drawing instead.</li>
+ <li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are
+ at the end of its <span class="tn-icon bx bx-category"></span> <em>More tools</em> menu.
+ In fullscreen, the Excalidraw menu shows again.</li>
<li>A new drawing has the background color of the note. A background chosen
from the Excalidraw menu replaces it.</li>
<li>To protect a finished drawing from accidental changes, select it and turn
diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
index 50abf1fa48..a72572b91e 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
@@ -124,6 +124,7 @@ A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-
* An Excalidraw file (`.excalidraw`) attached with the <span class="tn-icon cke cke-paper-clip"></span>_Attach file_ button becomes a drawing canvas too, in a _Medium_ box titled with the file name. It starts with _Editable_ off, so the drawing shows but cannot be changed until _Editable_ is turned on (see below).
* To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.
* The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class="tn-icon bx bxs-hand"></span> _Hand_ tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.
+* The canvas toolbar replaces the Excalidraw menu: _Export image_, _Find on canvas_, _Library_ and _Help_ are at the end of its <span class="tn-icon bx bx-category"></span> _More tools_ menu. In fullscreen, the Excalidraw menu shows again.
* A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.
* To protect a finished drawing from accidental changes, select it and turn off the <span class="tn-icon bx bx-edit-alt"></span> _Editable_ button at the start of its toolbar, or uncheck _Editable_ in its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn _Editable_ back on.
* The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, _Show title_ and _Convert to link_ to its _More actions_ menu.
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index f4cb477f06..c0c26524bb 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -43,8 +43,13 @@ declare global {
isOn?: boolean;
/** `true` when left out. */
isEnabled?: boolean;
- /** A separator goes between buttons of different groups. */
+ /** A separator goes between buttons, or items of a menu, of different groups. */
group?: string;
+ /**
+ * The keystroke shown beside the label of an item of a menu: CKEditor's notation, such as
+ * `Ctrl+F`, or a single character, such as `?`.
+ */
+ keystroke?: string;
/** The tools of the menu that the button opens. */
children?: ContentEmbedTool[];
/** A class of the button, for the content to style it. */
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.ts
index 8c8918f5ed..e411494e15 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
@@ -30,6 +30,7 @@ interface Tool {
isOn?: boolean;
isEnabled?: boolean;
group?: string;
+ keystroke?: string;
children?: Tool[];
class?: string;
}
@@ -191,6 +192,49 @@ describe("ContentEmbedTools", () => {
expect(provider.execute).toHaveBeenCalledWith("eraser");
});
+ it("separates the groups of a menu, and shows the keystrokes of its commands", () => {
+ const tools = createView();
+ selectEmbed();
+ const children: Tool[] = [
+ { id: "frame", label: "Frame", isOn: false },
+ { id: "export", label: "Export", group: "export", keystroke: "Ctrl+Shift+E" },
+ { id: "find", label: "Find", group: "canvas", keystroke: "Ctrl+F" },
+ { id: "library", label: "Library", group: "canvas" },
+ { id: "help", label: "Help", group: "canvas", keystroke: "?" }
+ ];
+ provider.change([ { ...MORE_TOOLS, children } ]);
+ const menu = tools.views[0];
+ if (!(menu instanceof DropdownView)) {
+ throw new Error("Expected a menu.");
+ }
+
+ menu.isOpen = true;
+ const items = [ ...menu.listView?.element?.children ?? [] ].map((item) => {
+ const button = item.querySelector(".ck-button");
+ if (!button) {
+ return "|";
+ }
+ const label = button.querySelector(".ck-button__label")?.textContent;
+ const keystroke = button.querySelector(".ck-button__keystroke")?.textContent;
+ return [ label, keystroke, button.getAttribute("role") ].filter(Boolean).join(" ");
+ });
+ expect(items).toEqual([
+ "Frame menuitemradio",
+ "|",
+ "Export Ctrl+Shift+E menuitem",
+ "|",
+ "Find Ctrl+F menuitem",
+ "Library menuitem",
+ "Help ? menuitem"
+ ]);
+
+ menu.isOpen = false;
+ menu.isOpen = true;
+ expect(menu.listView?.element?.querySelectorAll(".ck-button__keystroke")).toHaveLength(3);
+ menu.listView?.element?.querySelectorAll<HTMLElement>(".ck-button")[4]?.click();
+ expect(provider.execute).toHaveBeenCalledWith("help");
+ });
+
it("shows no tools for content without any, or for a host that offers none", () => {
const tools = createView();
getContentEmbedTools.mockReturnValue(null);
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts
index c8c7672566..b01fb0f818 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts
@@ -2,8 +2,8 @@ import "../../theme/content_embed_tools.css";
import {
addListToDropdown, ButtonView, Collection, createDropdown, DropdownView,
- type ListDropdownButtonDefinition, type Locale, Plugin, ToolbarSeparatorView, View,
- type ViewCollection, ViewModel
+ getEnvKeystrokeText, type ListDropdownItemDefinition, ListItemView, type Locale, Plugin,
+ ToolbarSeparatorView, View, type ViewCollection, ViewModel
} from "ckeditor5";
import ContentEmbed from "./content_embed.js";
@@ -68,7 +68,7 @@ export class ContentEmbedToolsView extends View {
private updaters: Array<ToolView["update"]> = [];
private provider: ContentEmbedToolProvider | null = null;
private unsubscribe: (() => void) | undefined;
- /** The group and the ids of each tool, to create the views again only for another set. */
+ /** What identifies each tool and its children, to create the views again for another set. */
private toolKeys: string[] = [];
constructor(locale?: Locale) {
@@ -116,9 +116,11 @@ export class ContentEmbedToolsView extends View {
/** 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, ...tool.children?.map(child => child.id) ?? []
- ].join("/"));
+ const keys = tools.map(tool => JSON.stringify([
+ tool.group,
+ tool.id,
+ tool.children?.map(child => [ child.group, child.id, child.keystroke ])
+ ]));
const isNewSet = keys.length !== this.toolKeys.length
|| keys.some((key, index) => key !== this.toolKeys[index]);
@@ -174,7 +176,10 @@ export class ContentEmbedToolsView extends View {
};
}
- /** A dropdown that lists `children`, each run as a tool of its own. */
+ /**
+ * A dropdown that lists `children`, each run as a tool of its own, with a separator between
+ * groups.
+ */
private createMenu(children: ContentEmbedTool[]): ToolView {
const dropdown = createDropdown(this.locale);
keepFocus(dropdown.buttonView);
@@ -183,13 +188,21 @@ export class ContentEmbedToolsView extends View {
const models = children.map(child => new ViewModel({
toolId: child.id,
withText: true,
- role: "menuitemradio"
+ withKeystroke: child.keystroke !== undefined,
+ role: child.isOn === undefined ? "menuitem" : "menuitemradio"
}));
- const definitions = new Collection<ListDropdownButtonDefinition>();
- for (const model of models) {
+ const definitions = new Collection<ListDropdownItemDefinition>();
+ for (const [ index, model ] of models.entries()) {
+ if (index && children[index]?.group !== children[index - 1]?.group) {
+ definitions.add({ type: "separator" });
+ }
definitions.add({ type: "button", model });
}
addListToDropdown(dropdown, definitions);
+ // Runs after `addListToDropdown()` creates the list, as the dropdown first opens.
+ dropdown.once("change:isOpen", () => addKeystrokes(dropdown, children), {
+ priority: "high"
+ });
this.listenTo(dropdown, "execute", (evt) => {
this.provider?.execute((evt.source as { toolId: string }).toolId);
});
@@ -229,6 +242,33 @@ function getButtonFace(tool: ContentEmbedTool) {
};
}
+/**
+ * Shows the keystrokes of `children` beside their labels in the list of `dropdown`. The own
+ * keystroke of `ButtonView` throws on a key that CKEditor cannot parse, such as `?`.
+ */
+function addKeystrokes(dropdown: DropdownView, children: ContentEmbedTool[]) {
+ const buttons = [ ...dropdown.listView?.items ?? [] ]
+ .filter(item => item instanceof ListItemView)
+ .map(item => item.children.first);
+ for (const [ index, button ] of buttons.entries()) {
+ const keystroke = children[index]?.keystroke;
+ if (button instanceof ButtonView && keystroke !== undefined) {
+ button.children.add(createKeystrokeView(button.locale, keystroke));
+ }
+ }
+}
+
+/** A keystroke as `ButtonView` shows it, or a single character as it is. */
+function createKeystrokeView(locale: Locale | undefined, keystroke: string) {
+ const view = new View(locale);
+ view.setTemplate({
+ tag: "span",
+ attributes: { class: [ "ck", "ck-button__keystroke" ] },
+ children: [ keystroke.length === 1 ? keystroke : getEnvKeystrokeText(keystroke) ]
+ });
+ return view;
+}
+
/** Keeps the focus in the content that the tools act on. */
function keepFocus(view: View) {
view.extendTemplate({