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
feat(text): open the Insert toolbar group as the app's own menu
Elian Doran61065a148874
diff --git a/apps/client/src/widgets/react/FormList.css b/apps/client/src/widgets/react/FormList.cssindex 094efdba3e..2e05a367aa 100644--- a/apps/client/src/widgets/react/FormList.css+++ b/apps/client/src/widgets/react/FormList.css@@ -9,6 +9,19 @@flex-shrink: 0;}+ .tn-svg-icon {+ display: inline-flex;++ & > svg {+ width: 1em;+ height: 1em;+ }++ & > svg *:not([fill]) {+ fill: currentColor;+ }+ }+& > span > div:has(> .switch-widget) {flex-grow: 1;}diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsxindex ceaa92562a..ef09ba3892 100644--- a/apps/client/src/widgets/react/FormList.tsx+++ b/apps/client/src/widgets/react/FormList.tsx@@ -12,7 +12,7 @@ import { handleRightToLeftPlacement, isMobile, openInAppHelpFromUrl } from "../.import FormToggle from "./FormToggle";import HelpTooltipButton from "./HelpTooltipButton";import { useStaticTooltip, useSyncedRef, useUniqueName } from "./hooks";-import Icon from "./Icon";+import Icon, { SvgIcon } from "./Icon";import { isRightToLeft, MenuContext, type MenuContextValue, MenuLevelContext, type OpenSubmenu, pointerMoved, shouldDropStart, useMenu } from "./menu_context";import { placeFloating } from "./Popup";import { joinElements } from "./react_utils";@@ -134,6 +134,8 @@ export interface FormListItemOpts {children: ComponentChildren;/** Without one the row keeps a blank slot, lining it up with the rows that have one; `null` leaves no slot. */icon?: string | null;+ /** The SVG of an icon drawn in place of {@link icon}, such as a CKEditor toolbar item's. */+ iconSvg?: string;/** Extra class for the icon itself, e.g. to hang a marker off its corner. */iconClassName?: string;value?: string;@@ -183,7 +185,7 @@ const TOOLTIP_CONFIG: Partial<Tooltip.Options> = {animation: false};-export function FormListItem({ className, icon, iconClassName, value, title, active, disabled, checked, checkable, container, onClick, selected, rtl, description, itemRef: externalItemRef, keyboardShortcut, shortcut, trailingIcon, closeOnSelect, ...contentProps }: FormListItemOpts) {+export function FormListItem({ className, icon, iconSvg, iconClassName, value, title, active, disabled, checked, checkable, container, onClick, selected, rtl, description, itemRef: externalItemRef, keyboardShortcut, shortcut, trailingIcon, closeOnSelect, ...contentProps }: FormListItemOpts) {const itemRef = useSyncedRef<HTMLLIElement>(externalItemRef, null);// Inside a `Menu` the row is one of its items; elsewhere, as in a dropdown, it stands alone.const menu = useContext(MenuContext);@@ -264,7 +266,9 @@ export function FormListItem({ className, icon, iconClassName, value, title, act>{/* One classless span holds the row, as the rows of a menu are laid out. */}<span>- {icon === null ? <span /> : <Icon icon={icon} className={iconClassName} />}+ {iconSvg && !checked+ ? <SvgIcon svg={iconSvg} className={iconClassName} />+ : icon === null ? <span /> : <Icon icon={icon} className={iconClassName} />}{/* An element, not spaces: in a flex row, text merges with a plain title but istrimmed before one boxed by `menuName()`, indenting the two kinds of row apart. */}<span className="tn-menu-gap" />@@ -368,7 +372,9 @@ export function FormDropdownDivider() {}export interface FormDropdownSubmenuProps {- icon: string;+ icon?: string;+ /** The SVG of an icon drawn in place of {@link icon}, such as a CKEditor toolbar item's. */+ iconSvg?: string;title: ComponentChildren;children: ComponentChildren;/** Called when the row is clicked, or run from the keyboard, on the desktop. */@@ -390,7 +396,7 @@ export function FormDropdownSubmenu(props: FormDropdownSubmenuProps) {return <MenuSubmenu {...props} menu={menu} />;}-function MenuSubmenu({ menu, icon, title, children, onDropdownToggleClicked, columns, disabled, className }: FormDropdownSubmenuProps & { menu: MenuContextValue }) {+function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleClicked, columns, disabled, className }: FormDropdownSubmenuProps & { menu: MenuContextValue }) {const level = useContext(MenuLevelContext);const id = useUniqueName("menu-row");const openSubmenu = menu.open[level];@@ -453,7 +459,7 @@ function MenuSubmenu({ menu, icon, title, children, onDropdownToggleClicked, col}}><span className="dropdown-toggle">- <Icon icon={icon} />+ {iconSvg ? <SvgIcon svg={iconSvg} /> : <Icon icon={icon} />}<span className="tn-menu-gap" /><span id={titleId(id)}>{title}</span></span>diff --git a/apps/client/src/widgets/react/Icon.tsx b/apps/client/src/widgets/react/Icon.tsxindex 58e4437a3e..e50dda315e 100644--- a/apps/client/src/widgets/react/Icon.tsx+++ b/apps/client/src/widgets/react/Icon.tsx@@ -4,6 +4,7 @@ import { useRef } from "preact/hooks";import { isMobile } from "../../services/utils";import { useStaticTooltip } from "./hooks";+import RawHtml from "./RawHtml";interface IconProps extends Pick<HTMLAttributes<HTMLSpanElement>,"className" | "onClick" | "title" | "style" | "role" | "aria-label"> {@@ -20,6 +21,11 @@ export default function Icon({ icon, className, ...restProps }: IconProps) {);}+/** An icon drawn from its SVG source, such as a CKEditor toolbar item's, sized as an {@link Icon}. */+export function SvgIcon({ svg, className }: { svg: string; className?: string }) {+ return <RawHtml className={clsx("tn-icon tn-svg-icon", className)} html={svg} />;+}+interface TooltipIconProps extends Omit<IconProps, "title"> {/** Tooltip text, rendered as a Bootstrap tooltip rather than a native `title`. */tooltip: string;diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 05ac1b0473..1dbd6d8ef4 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -22,6 +22,7 @@ import { createEmojiList, createNoteMentionList, createSlashCommandList } from "import { buildQuoteTransformation, resolveQuoteSetting } from "./quotes.js";import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";import { buildToolbarConfig } from "./toolbar.js";+import { createToolbarGroupMenuHost } from "./toolbar_group_menu.js";/*** The only license key Trilium ever passes to CKEditor. Every premium plugin the editor used has@@ -320,6 +321,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi] : []};+ config.toolbarGroupMenu = { host: () => createToolbarGroupMenuHost() };+return {...config,...buildToolbarConfig(opts.isClassicEditor, !!aiAssistantStream)diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.tsindex 9b52b57389..a7a77b0214 100644--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts@@ -208,7 +208,7 @@ function buildInsertGroup() {label: t("text-editor.toolbar-groups.insert"),icon: "plus",// The group holds enough entries that a strip of icons reads as a puzzle; `asMenu` (see- // the `ToolbarGroupMenu` plugin) opens it as a menu of icon-and-label rows instead.+ // the `ToolbarGroupMenu` plugin) opens it as the app's menu of icon-and-label rows instead.asMenu: true};}diff --git a/apps/client/src/widgets/type_widgets/text/toolbar_group_menu.spec.tsx b/apps/client/src/widgets/type_widgets/text/toolbar_group_menu.spec.tsxnew file mode 100644index 0000000000..05d4659d37--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/toolbar_group_menu.spec.tsx@@ -0,0 +1,109 @@+import type { ToolbarGroupMenuItem, ToolbarGroupMenuRequest } from "@triliumnext/ckeditor5";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createToolbarGroupMenuHost } from "./toolbar_group_menu";++const ICON = `<svg viewBox="0 0 20 20"><path d="M0 0h20v20H0z"/></svg>`;++describe("createToolbarGroupMenuHost", () => {+ const anchor = document.createElement("button");+ anchor.setAttribute("aria-labelledby", "insert-label");+ document.body.append(anchor);+ let host = createToolbarGroupMenuHost();+ afterEach(() => {+ host.destroy();+ host = createToolbarGroupMenuHost();+ });++ function show() {+ const runs: string[] = [];+ // The plugin hides the menu before it runs an entry.+ const run = (name: string) => () => {+ host.hide();+ runs.push(name);+ };+ const items: ToolbarGroupMenuItem[] = [+ { kind: "entry", label: "Link", icon: ICON, isEnabled: true, run: run("link") },+ { kind: "separator" },+ { kind: "entry", label: "Math", isEnabled: false, run: run("math") },+ {+ kind: "entry", label: "Date/time", icon: ICON, isEnabled: true, run: run("date"),+ children: [ { kind: "entry", label: "2026-10-05", isEnabled: true, run: run("iso") } ]+ }+ ];+ const setElement = vi.fn<ToolbarGroupMenuRequest["setElement"]>();+ const onClose = vi.fn<ToolbarGroupMenuRequest["onClose"]>();+ host.show({ anchor, items, setElement, onClose });++ const menu = document.querySelector<HTMLElement>(".tn-popup.tn-menu");+ if (!menu) throw new Error("expected the menu to render");+ return { menu, runs, setElement, onClose };+ }++ function rowTitled(title: string) {+ const found = [ ...document.querySelectorAll<HTMLElement>("li.dropdown-item") ]+ .find((item) => item.textContent === title);+ if (!found) throw new Error(`expected a row titled ${title}`);+ return found;+ }++ const press = (element: HTMLElement) => {+ element.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));+ element.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 }));+ };++ it("draws the entries as the app's menu, with their SVG icons, and hands the editor its element", () => {+ const { menu, setElement } = show();++ expect(setElement).toHaveBeenCalledWith(menu);+ expect(menu.classList).toContain("tn-dropdown-menu");+ expect(menu.getAttribute("aria-labelledby")).toBe("insert-label");+ const rows = [ ...menu.querySelectorAll(":scope > .tn-menu-scroll > li") ]+ .map((item) => `${item.className} ${item.textContent}`);+ expect(rows).toEqual([+ "dropdown-item Link",+ "dropdown-divider ",+ "dropdown-item disabled Math",+ "dropdown-item dropdown-submenu Date/time"+ ]);+ expect(rowTitled("Link").querySelector(".tn-svg-icon > svg")).not.toBeNull();+ expect(rowTitled("Date/time").querySelector(".tn-svg-icon > svg")).not.toBeNull();+ });++ it("runs an entry without closing a second time, and leaves a disabled one alone", () => {+ const { menu, runs, setElement, onClose } = show();++ press(rowTitled("Math"));+ expect(runs).toEqual([]);++ press(rowTitled("Link"));+ expect(runs).toEqual([ "link" ]);+ expect(onClose).not.toHaveBeenCalled();+ expect(setElement).toHaveBeenLastCalledWith(null);+ expect(menu.isConnected).toBe(false);+ });++ it("runs a submenu's opener and its rows", async () => {+ const opened = show();+ press(rowTitled("Date/time"));+ expect(opened.runs).toEqual([ "date" ]);++ const { menu, runs } = show();+ rowTitled("Date/time").dispatchEvent(new PointerEvent("pointerenter"));+ await vi.waitFor(() => expect(menu.querySelector(".dropdown-submenu > .dropdown-menu")).not.toBeNull());+ press(rowTitled("2026-10-05"));+ expect(runs).toEqual([ "iso" ]);+ });++ it("returns focus to the group's button on Escape, and not on a press elsewhere", () => {+ const escaped = show();+ escaped.menu.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));+ expect(escaped.onClose).toHaveBeenCalledExactlyOnceWith(true);+ expect(escaped.menu.isConnected).toBe(false);++ const dismissed = show();+ document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));+ expect(dismissed.onClose).toHaveBeenCalledExactlyOnceWith(false);+ expect(dismissed.setElement).toHaveBeenLastCalledWith(null);+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/toolbar_group_menu.tsx b/apps/client/src/widgets/type_widgets/text/toolbar_group_menu.tsxnew file mode 100644index 0000000000..94e8103e47--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/toolbar_group_menu.tsx@@ -0,0 +1,92 @@+import type {+ ToolbarGroupMenuHost, ToolbarGroupMenuItem, ToolbarGroupMenuRequest+} from "@triliumnext/ckeditor5";+import { render } from "preact";++import { isMobile, isNarrowLayout } from "../../../services/utils";+import { FormDropdownDivider, FormDropdownSubmenu, FormListItem } from "../../react/FormList";+import Menu from "../../react/Menu";++/** The gap between the group's button and the menu, as a `Dropdown` leaves under its toggle. */+const ANCHOR_GAP = 2;++/**+ * Draws the menu of a toolbar group marked `asMenu` with the app's own `Menu`, for the editor+ * config's `toolbarGroupMenu.host`.+ */+export function createToolbarGroupMenuHost(): ToolbarGroupMenuHost {+ const container = document.createElement("div");+ let shown: ToolbarGroupMenuRequest | null = null;+ const unmount = () => {+ shown = null;+ render(null, container);+ };++ return {+ show(request) {+ shown = request;+ // An entry that runs hides the menu first, so a close that follows finds it gone.+ const close = (returnFocus: boolean) => {+ if (shown !== request) return;+ request.onClose(returnFocus);+ unmount();+ };+ render(<ToolbarGroupMenu request={request} onClose={close} />, container);+ },+ hide: unmount,+ destroy: unmount+ };+}++function ToolbarGroupMenu({ request, onClose }: {+ request: ToolbarGroupMenuRequest;+ onClose(returnFocus: boolean): void;+}) {+ return (+ <Menu+ anchor={request.anchor}+ offset={ANCHOR_GAP}+ portalClassName="tn-dropdown-portal"+ className="tn-dropdown-menu"+ bottomSheet={isMobile() && isNarrowLayout()}+ aria-labelledby={request.anchor.getAttribute("aria-labelledby") ?? undefined}+ elementRef={request.setElement}+ onDismiss={() => onClose(false)}+ onClose={() => onClose(true)}+ >+ <MenuRows items={request.items} />+ </Menu>+ );+}++function MenuRows({ items }: { items: ToolbarGroupMenuItem[] }) {+ return (+ <>+ {items.map((item, index) => {+ if (item.kind === "separator") {+ return <FormDropdownDivider key={index} />;+ }++ const { label, icon, isEnabled, run, children } = item;+ if (children) {+ return (+ <FormDropdownSubmenu+ key={index} iconSvg={icon} title={label} disabled={!isEnabled}+ onDropdownToggleClicked={run && (() => run())}+ >+ <MenuRows items={children} />+ </FormDropdownSubmenu>+ );+ }++ return (+ <FormListItem+ key={index} iconSvg={icon} disabled={!isEnabled} onClick={() => run?.()}+ >+ {label}+ </FormListItem>+ );+ })}+ </>+ );+}diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex fe96970cfb..7776bbd901 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -20,6 +20,7 @@ export type { AttachmentLinkChange } from "./plugins/referencelink.js";export type { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.js";export type { default as TriliumSlashCommands, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem } from "./plugins/mention/slash_commands.js";export type { MentionHostedFeed, MentionHostedList, MentionHostedListState } from "./plugins/mention/types.js";+export type { ToolbarGroupMenuEntry, ToolbarGroupMenuHost, ToolbarGroupMenuItem, ToolbarGroupMenuRequest } from "./plugins/toolbar_group_menu.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";export { default as TriliumAiAssistant } from "./plugins/ai_assistant/ai_assistant.js";diff --git a/packages/ckeditor5/src/plugins/toolbar_group_menu.spec.ts b/packages/ckeditor5/src/plugins/toolbar_group_menu.spec.tsindex 32f3f8ef33..11d7197ba3 100644--- a/packages/ckeditor5/src/plugins/toolbar_group_menu.spec.ts+++ b/packages/ckeditor5/src/plugins/toolbar_group_menu.spec.ts@@ -1,13 +1,15 @@import {addListToDropdown, Bold, ButtonView, type ClassicEditor, Collection, createDropdown,- type DropdownMenuNestedMenuView, DropdownView, Essentials, Italic,- type ListDropdownItemDefinition, ListSeparatorView, type Locale, Paragraph, Plugin,- SplitButtonView, type ToolbarView, UIModel, View+ DropdownView, type Editor, Essentials, Italic, type ListDropdownItemDefinition, type Locale,+ Paragraph, Plugin, SplitButtonView, type ToolbarView, UIModel, View} from "ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor, createTestEditorOf } from "../../test/editor-kit.js";-import ToolbarGroupMenu from "./toolbar_group_menu.js";+import ToolbarGroupMenu, {+ type ToolbarGroupMenuEntry, type ToolbarGroupMenuHost, type ToolbarGroupMenuItem,+ type ToolbarGroupMenuRequest+} from "./toolbar_group_menu.js";const insertedSamples: string[] = [];const blankInserts = vi.fn();@@ -59,8 +61,7 @@ class SampleDropdown extends Plugin {dropdown.on("change:isOpen", (evt, name, isOpen) => {if (isOpen) {items.clear();- const model = new UIModel({ label: now, withText: true });- items.add({ type: "button", model });+ items.add({ type: "button", model: new UIModel({ label: now, withText: true }) });}});@@ -76,6 +77,7 @@ class SampleDropdown extends Plugin {items.add({ type: "separator" });items.add({ type: "button", model: new UIModel({ label: "First", withText: true }) });items.add({ type: "separator" });+ items.add({ type: "separator" });items.add({ type: "button", model: new UIModel({ withText: true }) });items.add({type: "group",@@ -85,6 +87,7 @@ class SampleDropdown extends Plugin {model: new UIModel({ label: "Inside", withText: true })}])});+ items.add({ type: "separator" });addListToDropdown(dropdown, items);return dropdown;@@ -97,7 +100,7 @@ class SampleDropdown extends Plugin {return view;});- // A dropdown with no list of its own: nothing to open onto, so it stays a plain row.+ // A dropdown with no list of its own, which the menu has no rows to draw for.this.editor.ui.componentFactory.add("panelOnly", (locale: Locale) => {const dropdown = createDropdown(locale);dropdown.buttonView.set({ label: "Panel only", icon: "<svg />" });@@ -116,204 +119,273 @@ const MENU_GROUP = {const PLAIN_GROUP = { label: "Plain", icon: "text", items: ["bold", "italic"] };const PLUGINS = [Essentials, Paragraph, Bold, Italic, SampleDropdown, ToolbarGroupMenu];+/** A host that records what it is asked to show, as the client's `Menu` would draw it. */+function createHost() {+ const requests: ToolbarGroupMenuRequest[] = [];+ const host = {+ show: vi.fn((request: ToolbarGroupMenuRequest) => {+ requests.push(request);+ }),+ hide: vi.fn(),+ destroy: vi.fn()+ } satisfies ToolbarGroupMenuHost;++ return {+ host,+ config: { toolbarGroupMenu: { host: () => host } },+ /** The request of the menu shown last. */+ last() {+ const request = requests.at(-1);+ if (!request) {+ throw new Error("The host was asked to show no menu.");+ }+ return request;+ }+ };+}+describe("ToolbarGroupMenu", () => {- it("opens a group marked with asMenu as a menu of rows, ruled as the group was", async () => {+ it("hands a group marked with asMenu to the host as entries, ruled as the group was", async () => {+ const { host, config, last } = createHost();const editor = await createTestEditor(PLUGINS, {+ ...config,toolbar: { items: ["bold", MENU_GROUP, PLAIN_GROUP] }});- const menu = openGroup(getToolbar(editor), "Insert");- expect(rowLabels(menu)).toStrictEqual(["Bold", "—", "Italic", "Insert sample"]);+ const dropdown = groupDropdown(getToolbar(editor), "Insert");+ dropdown.buttonView.fire("open");++ // The dropdown never opens its own panel; the host's menu opens under its button.+ expect(dropdown.isOpen).toBe(false);+ expect(host.show).toHaveBeenCalledTimes(1);+ expect(last().anchor).toBe(dropdown.buttonView.element);+ expect(labels(last().items)).toStrictEqual(["Bold", "—", "Italic", "Insert sample"]);- // Each row carries the icon of the toolbar item it stands for, and follows its enabled- // state: `bold` is disabled while the editor is read-only, so its row is too.- const [bold] = menu.buttons;+ // Each entry carries the icon and the enabled state of the toolbar item it stands for, as+ // they are when the menu opens: `bold` is disabled while the editor is read-only.+ const bold = entry(last().items, "Bold");expect(bold.icon).toBeTruthy();expect(bold.isEnabled).toBe(true);++ last().onClose(false);editor.enableReadOnlyMode("spec");- expect(bold.isEnabled).toBe(false);+ dropdown.buttonView.fire("open");+ expect(entry(last().items, "Bold").isEnabled).toBe(false);++ // A group not marked opens its own panel, as CKEditor has it.+ const plain = groupDropdown(getToolbar(editor), "Plain");+ plain.isOpen = true;+ expect(plain.isOpen).toBe(true);+ expect(host.show).toHaveBeenCalledTimes(2);});- it("opens an entry carrying a list of its own as a submenu over that list", async () => {+ it("describes an entry carrying a list of its own as a submenu, read on each open", async () => {+ const { config, last } = createHost();const editor = await createTestEditor(PLUGINS, {- toolbar: { items: [MENU_GROUP] }+ ...config,+ toolbar: { items: [{ ...MENU_GROUP, items: ["samples", "clock"] }] }});- const dropdown = openDropdown(getToolbar(editor), "Insert");- const submenu = openSubmenu(dropdown);- expect(submenu.buttonView.label).toBe("Insert sample");- expect(submenu.buttonView.icon).toBe("<svg />");- // `toolbar_group_menu.css` sizes the icons of a panel pinned into the body by this class.- expect(submenu.panelView.class).toBe("ck-toolbar-group-menu__panel");- expect(itemLabels(submenu.listView.items)).toStrictEqual(["Flowchart", "Sequence"]);- });-- it("runs the action of a split button when its submenu's opener is pressed", async () => {- const editor = await createTestEditor(PLUGINS, {- toolbar: { items: [MENU_GROUP] }- });+ const dropdown = groupDropdown(getToolbar(editor), "Insert");+ dropdown.isOpen = true;- const dropdown = openDropdown(getToolbar(editor), "Insert");- submenuOf(dropdown).buttonView.fire("execute");+ const samples = entry(last().items, "Insert sample");+ expect(samples.icon).toBe("<svg />");+ expect(labels(samples.children ?? [])).toStrictEqual(["Flowchart", "Sequence"]);+ // A split button runs its own action from the submenu's opener; a plain dropdown only+ // opens its submenu.+ samples.run?.();expect(blankInserts).toHaveBeenCalled();- expect(dropdown.isOpen).toBe(false);+ expect(entry(last().items, "Clock").run).toBeUndefined();++ // `clock`, like `dateTime`, fills its list as it opens, so each menu reads it afresh.+ expect(labels(entry(last().items, "Clock").children ?? [])).toStrictEqual(["noon"]);+ now = "half past";+ dropdown.isOpen = true;+ expect(labels(entry(last().items, "Clock").children ?? [])).toStrictEqual(["half past"]);});- it("runs the toolbar item a row stands for, in the menu and in a submenu alike", async () => {+ it("runs the toolbar item an entry stands for, hiding the menu first", async () => {+ const { host, config, last } = createHost();const editor = await createTestEditor(PLUGINS, {+ ...config,toolbar: { items: [MENU_GROUP] }});- const dropdown = openDropdown(getToolbar(editor), "Insert");- const menuView = openGroup(getToolbar(editor), "Insert");+ const dropdown = groupDropdown(getToolbar(editor), "Insert");+ dropdown.isOpen = true;+ const order: string[] = [];+ host.hide.mockImplementation(() => order.push("hide"));+ editor.commands.get("bold")?.on("execute", () => order.push("bold"));- const bold = menuView.buttons.find((button) => button.label === "Bold");- expect(bold).toBeTruthy();- bold?.fire("execute");+ entry(last().items, "Bold").run?.();+ expect(order).toStrictEqual(["hide", "bold"]);expect(editor.commands.get("bold")?.value).toBe(true);+ expect(editor.editing.view.document.isFocused).toBe(true);- submenuRow(openSubmenu(dropdown), "Sequence").fire("execute");+ dropdown.isOpen = true;+ const sequence = entry(entry(last().items, "Insert sample").children ?? [], "Sequence");+ sequence.run?.();expect(insertedSamples).toStrictEqual(["Sequence"]);});- it("draws a submenu on each open, so an entry filling its own list stays fresh", async () => {+ it("toggles the menu from the group's button, and returns focus to it on Escape", async () => {+ const { host, config, last } = createHost();const editor = await createTestEditor(PLUGINS, {- toolbar: { items: [{ ...MENU_GROUP, items: ["clock"] }] }+ ...config,+ toolbar: { items: [MENU_GROUP] }});- const dropdown = openDropdown(getToolbar(editor), "Insert");- expect(itemLabels(openSubmenu(dropdown).listView.items)).toStrictEqual(["noon"]);+ const dropdown = groupDropdown(getToolbar(editor), "Insert");+ dropdown.buttonView.fire("open");+ dropdown.buttonView.fire("open");+ expect(host.show).toHaveBeenCalledTimes(1);+ expect(host.hide).toHaveBeenCalledTimes(1);- // Reopening the submenu alone is enough: it is what the reader waits in front of.- now = "half past";- submenuOf(dropdown).isOpen = false;- expect(itemLabels(openSubmenu(dropdown).listView.items)).toStrictEqual(["half past"]);-- now = "one";- dropdown.isOpen = false;+ // The ▼ key sets `isOpen` itself, past the button.dropdown.isOpen = true;- expect(itemLabels(openSubmenu(dropdown).listView.items)).toStrictEqual(["one"]);+ expect(host.show).toHaveBeenCalledTimes(2);++ // Closed by the host, the menu opens again on the next press rather than toggling shut.+ last().onClose(true);+ expect(document.activeElement).toBe(dropdown.buttonView.element);+ dropdown.buttonView.fire("open");+ expect(host.show).toHaveBeenCalledTimes(3);++ // A close that comes late, from a menu since replaced, leaves the shown one alone.+ const first = last();+ dropdown.buttonView.fire("open");+ dropdown.buttonView.fire("open");+ first.onClose(false);+ dropdown.buttonView.fire("open");+ expect(host.hide).toHaveBeenCalledTimes(3);});- it("only opens the submenu of an entry that has no action of its own", async () => {+ it("counts the menu's element as the editor's own while it is shown", async () => {+ const { config, last } = createHost();const editor = await createTestEditor(PLUGINS, {- toolbar: { items: [{ ...MENU_GROUP, items: ["clock"] }] }- });-- const dropdown = openDropdown(getToolbar(editor), "Insert");- const submenu = submenuOf(dropdown);- submenu.buttonView.fire("execute");-- expect(submenu.isOpen).toBe(true);- expect(dropdown.isOpen).toBe(true);- });-- it("holds a dropdown that carries a panel of its own in the row, panel and all", async () => {- const editor = await createTestEditor(PLUGINS, {- toolbar: { items: [{ ...MENU_GROUP, items: ["bold", "panelOnly"] }] }+ ...config,+ toolbar: { items: [MENU_GROUP] }});- const dropdown = openDropdown(getToolbar(editor), "Insert");- expect(openGroup(getToolbar(editor), "Insert").menus).toStrictEqual([]);+ groupDropdown(getToolbar(editor), "Insert").isOpen = true;+ const element = document.createElement("div");+ document.body.appendChild(element);+ const pressesReachingDocument = vi.fn();+ document.addEventListener("mousedown", pressesReachingDocument);- const mounted = rowChildren(dropdown).at(-1);- expect(mounted).toBeInstanceOf(DropdownView);- if (!(mounted instanceof DropdownView)) {- return;- }+ last().setElement(element);+ expect(editor.ui.focusTracker.elements).toContain(element);+ element.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ expect(pressesReachingDocument).not.toHaveBeenCalled();- // Its panel opens from inside the menu, where firing the detached dropdown could only have- // opened it on the strip the menu replaced.- expect(mounted.buttonView.withText).toBe(true);- mounted.isOpen = true;- expect(mounted.panelView.isVisible).toBe(true);+ last().setElement(null);+ expect(editor.ui.focusTracker.elements).not.toContain(element);+ element.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ expect(pressesReachingDocument).toHaveBeenCalledTimes(1);- // A redraw leaves it alive: it belongs to the group, not to the menu drawn over it.- dropdown.isOpen = false;- dropdown.isOpen = true;- expect(rowChildren(dropdown).at(-1)).toBe(mounted);+ document.removeEventListener("mousedown", pressesReachingDocument);+ element.remove();});- it("hands the keyboard to a mounted control when its row takes focus", async () => {+ it("keeps the toolbar's overflow dropdown open around the menu, and closes it on a run", async () => {+ const { config, last } = createHost();const editor = await createTestEditor(PLUGINS, {- toolbar: { items: [{ ...MENU_GROUP, items: ["panelOnly"] }] }+ ...config,+ toolbar: { items: ["bold", "italic", MENU_GROUP] }});- const dropdown = openDropdown(getToolbar(editor), "Insert");- const mounted = rowChildren(dropdown).at(-1);- expect(mounted).toBeInstanceOf(DropdownView);- if (!(mounted instanceof DropdownView)) {- return;+ // The suite loads no editor stylesheet, so the items would wrap rather than overflow.+ const style = document.createElement("style");+ style.textContent = ".ck.ck-toolbar, .ck.ck-toolbar__items { display: flex; flex-wrap: nowrap; }";+ document.head.appendChild(style);+ const toolbar = getToolbar(editor);+ if (toolbar.element) {+ toolbar.element.style.width = "60px";}-- // The row goes on naming the button that stood there as its `childView`, which only the- // hover behaviour reads, and only to recognize a submenu. Focus takes the other road:- // `ListItemView#focus()` reaches for `children.first`, which is the control itself.- const [row] = [...dropdown.menuView?.items ?? []] as Array<{ childView?: unknown }>;- expect(row?.childView).not.toBe(mounted);-- dropdown.menuView?.focus();- expect(document.activeElement).toBe(mounted.buttonView.element);- });-- it("draws a rule where the list has one, never at its head, and names every row", async () => {- const editor = await createTestEditor(PLUGINS, {- toolbar: { items: [{ ...MENU_GROUP, items: ["oddList"] }] }+ const overflow = await vi.waitFor(() => {+ const found = [...toolbar.children].find((child): child is DropdownView =>+ child instanceof DropdownView && child.class?.includes("ck-toolbar__grouped-dropdown") === true);+ if (!found) {+ throw new Error("The toolbar grouped no items yet.");+ }+ return found;});- const dropdown = openDropdown(getToolbar(editor), "Insert");+ overflow.isOpen = true;+ groupDropdown(toolbar, "Insert").isOpen = true;+ const element = document.createElement("div");+ document.body.appendChild(element);+ last().setElement(element);+ expect(overflow.focusTracker.elements).toContain(element);++ entry(last().items, "Italic").run?.();+ expect(overflow.isOpen).toBe(false);+ expect(editor.commands.get("italic")?.value).toBe(true);- // `listEntriesOf()` skips a `ListItemGroupView`, and `labelOf()` names an unlabeled- // button "", which still runs on execute.- const rows = itemLabels(openSubmenu(dropdown).listView.items);- expect(rows).toStrictEqual(["First", "—", ""]);+ last().setElement(null);+ element.remove();+ style.remove();});- // `_cleanSeparatorsAndLineBreaks()` drops a leading `|`, so `plan.definition` can only be- // empty at a separator when `planGroupMenu()` skipped the item before it.- it("passes over an item it has no row for, and the rule that follows it", async () => {+ it("passes over items it has no entry for, and rules that would lead, end or double", async () => {+ const { config, last } = createHost();const editor = await createTestEditor(PLUGINS, {+ ...config,toolbar: {- items: [{ ...MENU_GROUP, items: ["plainView", "|", "bold", "-", "italic"] }]+ items: [{+ ...MENU_GROUP,+ items: ["plainView", "|", "bold", "-", "panelOnly", "|", "italic", "oddList", "|", "plainView"]+ }]}});- const menu = openGroup(getToolbar(editor), "Insert");- expect(rowLabels(menu)).toStrictEqual(["Bold", "Italic"]);+ groupDropdown(getToolbar(editor), "Insert").isOpen = true;+ expect(labels(last().items)).toStrictEqual(["Bold", "—", "Italic", "Odd list"]);+ // A list's groups are passed over, and its unlabeled button is named "".+ expect(labels(entry(last().items, "Odd list").children ?? [])).toStrictEqual(["First", "—", ""]);});it("converts a group of the block toolbar, filled after the plugin is set up", async () => {const { BlockToolbar } = await import("ckeditor5");+ const { config, last } = createHost();const editor = await createTestEditor([BlockToolbar, ...PLUGINS], {+ ...config,toolbar: { items: ["bold"] },blockToolbar: [MENU_GROUP]});- const menu = openGroup(editor.plugins.get(BlockToolbar).toolbarView, "Insert");- expect(rowLabels(menu)).toStrictEqual(["Bold", "—", "Italic", "Insert sample"]);+ groupDropdown(editor.plugins.get(BlockToolbar).toolbarView, "Insert").isOpen = true;+ expect(labels(last().items)).toStrictEqual(["Bold", "—", "Italic", "Insert sample"]);});// A real `BalloonEditor`, whose UI view carries no fixed bar at all: the group is reached// through the plugin holding the selection toolbar, and nowhere else.- it("converts a group of the selection balloon", async () => {+ it("converts a group of the selection balloon, and destroys the host with the editor", async () => {const { BalloonEditor, BalloonToolbar } = await import("ckeditor5");- const editor = await createTestEditorOf(BalloonEditor, PLUGINS, {+ const { host, config, last } = createHost();+ const editor: Editor = await createTestEditorOf(BalloonEditor, PLUGINS, {+ ...config,toolbar: [MENU_GROUP]});expect((editor.ui.view as { toolbar?: ToolbarView }).toolbar).toBeUndefined();- const menu = openGroup(editor.plugins.get(BalloonToolbar).toolbarView, "Insert");- expect(rowLabels(menu)).toStrictEqual(["Bold", "—", "Italic", "Insert sample"]);+ groupDropdown(editor.plugins.get(BalloonToolbar).toolbarView, "Insert").isOpen = true;+ expect(labels(last().items)).toStrictEqual(["Bold", "—", "Italic", "Insert sample"]);++ await editor.destroy();+ expect(host.destroy).toHaveBeenCalled();});- it("leaves every group alone when none is marked", async () => {+ it("leaves a group marked with asMenu to CKEditor when no host is configured", async () => {const editor = await createTestEditor(PLUGINS, {- toolbar: { items: ["bold", PLAIN_GROUP] }+ toolbar: { items: [MENU_GROUP] }});- expect(editor.plugins.has(ToolbarGroupMenu)).toBe(true);- expect(openDropdown(getToolbar(editor), "Plain").menuView).toBeUndefined();+ const dropdown = groupDropdown(getToolbar(editor), "Insert");+ dropdown.isOpen = true;+ expect(dropdown.isOpen).toBe(true);});});@@ -321,85 +393,27 @@ function getToolbar(editor: ClassicEditor) {return (editor.ui.view as { toolbar: ToolbarView }).toolbar;}-function openDropdown(toolbar: ToolbarView, label: string) {+function groupDropdown(toolbar: ToolbarView, label: string) {const dropdown = [...toolbar.items].find((item): item is DropdownView =>item instanceof DropdownView && item.buttonView.label === label);if (!dropdown) {throw new Error(`No "${label}" group dropdown in the toolbar.`);}- dropdown.isOpen = true;return dropdown;}-/** Open the group dropdown carrying `label` and return the menu built in its panel. */-function openGroup(toolbar: ToolbarView, label: string) {- const menuView = openDropdown(toolbar, label).menuView;- if (!menuView) {- throw new Error(`The "${label}" group built no menu.`);- }-- return menuView;-}--function submenuOf(dropdown: DropdownView) {- const [submenu] = dropdown.menuView?.menus ?? [];- if (!submenu) {- throw new Error("The menu holds no submenu.");- }-- return submenu;-}--/** Open the menu's one submenu, which is what draws its rows. */-function openSubmenu(dropdown: DropdownView) {- const submenu = submenuOf(dropdown);- submenu.isOpen = true;- return submenu;+/** The labels of `items`, with a rule written as an em dash. */+function labels(items: ToolbarGroupMenuItem[]) {+ return items.map((item) => (item.kind === "separator" ? "—" : item.label));}-function submenuRow(submenu: DropdownMenuNestedMenuView, label: string) {- for (const item of submenu.listView.items) {- const child = (item as { children?: { first?: unknown } }).children?.first;- if (child instanceof ButtonView && child.label === label) {- return child;- }+function entry(items: ToolbarGroupMenuItem[], label: string) {+ const found = items.find((item): item is ToolbarGroupMenuEntry =>+ item.kind === "entry" && item.label === label);+ if (!found) {+ throw new Error(`No "${label}" entry in the menu.`);}- throw new Error(`No "${label}" row in the submenu.`);-}--/** What each row of the menu holds: a button, a submenu, or a control mounted into the row. */-function rowChildren(dropdown: DropdownView) {- return [...dropdown.menuView?.items ?? []]- .map((item) => (item as { children?: { first?: unknown } }).children?.first);-}--/** The labels the menu shows, top level only, with a rule written as an em dash. */-function rowLabels(menuView: { items: Iterable<unknown> }) {- return itemLabels(menuView.items);-}--function itemLabels(items: Iterable<unknown>) {- const labels: string[] = [];-- for (const item of items) {- if (item instanceof ListSeparatorView) {- labels.push("—");- continue;- }-- const child = (item as { children?: { first?: unknown } }).children?.first;- if (child instanceof ButtonView) {- labels.push(child.label ?? "");- } else if (isNestedMenu(child)) {- labels.push(child.buttonView.label ?? "");- }- }-- return labels;-}--function isNestedMenu(view: unknown): view is DropdownMenuNestedMenuView {- return !!view && typeof view === "object" && "buttonView" in view && "listView" in view;+ return found;}diff --git a/packages/ckeditor5/src/plugins/toolbar_group_menu.ts b/packages/ckeditor5/src/plugins/toolbar_group_menu.tsindex 511bbf6897..a9e88318f1 100644--- a/packages/ckeditor5/src/plugins/toolbar_group_menu.ts+++ b/packages/ckeditor5/src/plugins/toolbar_group_menu.ts@@ -1,28 +1,75 @@import {- addMenuToDropdown, BalloonToolbar, BlockToolbar, type Button, ButtonView,- type DropdownMenuDefinition, DropdownMenuListItemButtonView, DropdownMenuListItemView,- type DropdownMenuNestedMenuView, type DropdownMenuRootListView, DropdownView, ListItemView,- ListSeparatorView, Plugin,- SplitButtonView, type ToolbarConfig, type ToolbarConfigItem,- ToolbarSeparatorView, type ToolbarView, type View+ BalloonToolbar, BlockToolbar, ButtonView, DropdownView, type Editor, type FocusTracker,+ ListItemView, ListSeparatorView, Plugin, SplitButtonView, type ToolbarConfig,+ type ToolbarConfigItem, ToolbarSeparatorView, type ToolbarView, type View} from "ckeditor5";-import "../theme/toolbar_group_menu.css";++declare module "ckeditor5" {+ interface EditorConfig {+ toolbarGroupMenu?: {+ /** Creates the menu the toolbar groups marked `asMenu` open, once per editor. */+ host(editor: Editor): ToolbarGroupMenuHost;+ };+ }+}++/** Draws the menu of a toolbar group marked `asMenu`. See {@link ToolbarGroupMenu}. */+export interface ToolbarGroupMenuHost {+ show(request: ToolbarGroupMenuRequest): void;+ hide(): void;+ destroy(): void;+}++/** What a {@link ToolbarGroupMenuHost} shows a menu for. */+export interface ToolbarGroupMenuRequest {+ /** The group's button, which the menu opens under. */+ anchor: HTMLElement;+ items: ToolbarGroupMenuItem[];+ /**+ * Receives the menu's element once it is in the page, and `null` as it leaves. The editor+ * counts focus and presses inside that element as its own, so the toolbar holding the group+ * stays open.+ */+ setElement(element: HTMLElement | null): void;+ /**+ * Called as the menu closes without running an entry. `returnFocus` puts focus back on the+ * group's button, for a menu closed with Escape rather than a press elsewhere.+ */+ onClose(returnFocus: boolean): void;+}++export type ToolbarGroupMenuItem = { kind: "separator" } | ToolbarGroupMenuEntry;++export interface ToolbarGroupMenuEntry {+ kind: "entry";+ label: string;+ /** The SVG of the icon of the toolbar item. */+ icon?: string;+ isEnabled: boolean;+ /** Runs the toolbar item. An entry with `children` and no action only opens them. */+ run?(): void;+ children?: ToolbarGroupMenuItem[];+}/**- * Opens a toolbar group as a dropdown menu — a row of icon and label per entry, and a submenu- * for an entry that carries a list of its own — rather than as a strip of icons.+ * Opens a toolbar group as a menu drawn by the host application (`toolbarGroupMenu.host`), with a+ * row of icon and label per entry, and a submenu for an entry that carries a list of its own.** A group opts in with `asMenu: true` beside its `label` in the toolbar configuration.* `ToolbarView#_createNestedToolbarDropdown()` builds those dropdowns and keeps no reference to the* definition each came from, so the labels of the opted-in groups are read from the configuration- * and matched against the dropdown buttons. The views CKEditor lays out in the group are what the- * menu is built from: a row mirrors the label, icon and enabled state of one of them, and runs it.+ * and matched against the dropdown buttons. The dropdown never opens its own panel: the views+ * CKEditor lays out in it are described to the host each time it would, and a row runs its view.+ * A group holds buttons and dropdowns that list rows.*/export default class ToolbarGroupMenu extends Plugin {private watchedDropdowns = new WeakSet<DropdownView>();- private plans = new WeakMap<DropdownView, MenuPlan>();- private sourceToolbars = new Set<ToolbarView>();+ private host: ToolbarGroupMenuHost | null = null;+ /** The menu the host shows, with the dropdown it stands for, or `null`. */+ private shown: { dropdown: DropdownView; request: ToolbarGroupMenuRequest } | null = null;+ /** Set while the plugin opens a dropdown itself, to have CKEditor build its views. */+ private building = false;static get pluginName() {return "ToolbarGroupMenu" as const;@@ -35,27 +82,24 @@ export default class ToolbarGroupMenu extends Plugin {editor.config.get("balloonToolbar"),editor.config.get("blockToolbar"));- if (!labels.size) {+ if (!labels.size || !editor.config.get("toolbarGroupMenu")) {return;}for (const toolbar of this.getToolbarViews()) {for (const item of toolbar.items) {- this.watchGroupDropdown(item, labels);+ this.watchGroupDropdown(toolbar, item, labels);}this.listenTo(toolbar.items, "add", (evt, item: View) => {- this.watchGroupDropdown(item, labels);+ this.watchGroupDropdown(toolbar, item, labels);});}}destroy() {super.destroy();-- for (const toolbar of this.sourceToolbars) {- toolbar.destroy();- }+ this.host?.destroy();}/**@@ -80,7 +124,7 @@ export default class ToolbarGroupMenu extends Plugin {return toolbars;}- private watchGroupDropdown(item: View, labels: Set<string>) {+ private watchGroupDropdown(toolbar: ToolbarView, item: View, labels: Set<string>) {if (!(item instanceof DropdownView) || this.watchedDropdowns.has(item)) {return;}@@ -92,220 +136,125 @@ export default class ToolbarGroupMenu extends Plugin {this.watchedDropdowns.add(item);- // The menu is drawn afresh on every open: an entry such as `dateTime` fills its own list- // with the time it is opened at, so rows drawn once would show the time they were drawn at.- // `addToolbarToDropdown()` builds the group's views on the first open, from a listener it- // registers at `highest` priority, so `high` runs once those views are in place.- this.listenTo(item, "change:isOpen", () => {- if (item.isOpen && item.toolbarView) {- this.drawMenu(item, item.toolbarView);+ // Every way of opening the dropdown sets `isOpen`, its button and the ▼ key alike, so the+ // value is turned back here and the host's menu toggles instead.+ this.listenTo<DropdownSetIsOpenEvent>(item, "set:isOpen", (evt, name, isOpen) => {+ if (!isOpen || this.building) {+ return;}- }, { priority: "high" });- // Every row reaches this, submenu entries included: the root list delegates `menu:execute`- // to the dropdown, and delegation keeps the button that was pressed as the event's source.- this.listenTo(item, "execute", (evt) => {- const id = (evt.source as DropdownMenuListItemButtonView).id;- this.plans.get(item)?.rows.get(id)?.run();- });+ evt.return = false;+ if (this.shown?.dropdown === item) {+ this.hideMenu();+ } else {+ this.showMenu(toolbar, item);+ }+ }, { priority: "high" });}- private drawMenu(dropdown: DropdownView, toolbar: ToolbarView) {- if (this.sourceToolbars.has(toolbar)) {- discardMenu(dropdown, this.plans.get(dropdown));- } else {- // The group's views go on serving the menu, so only the strip they were laid out in- // leaves the panel. It is destroyed with the plugin, since nothing else holds it now.- dropdown.panelView.children.remove(toolbar);- dropdown.focusTracker.remove(toolbar);- this.sourceToolbars.add(toolbar);- }-- const locale = this.editor.locale;- const plan = planGroupMenu([...toolbar.items]);- addMenuToDropdown(dropdown, this.editor.ui.view.body, plan.definition, {- ariaLabel: dropdown.buttonView.label- });-- this.plans.set(dropdown, plan);-- const menuView = dropdown.menuView;- /* v8 ignore next 3 -- `addMenuToDropdown()` has just set the menu this narrows */- if (!menuView) {+ private showMenu(toolbar: ToolbarView, dropdown: DropdownView) {+ const editor = this.editor;+ const anchor = dropdown.buttonView.element;+ /* v8 ignore next 3 -- a dropdown is opened from its rendered button */+ if (!anchor) {return;}- // A submenu's panel is appended to the editor's body, outside the dropdown, so it needs the- // stylesheet's hook of its own.- menuView.menuPanelClass = "ck-toolbar-group-menu__panel";-- for (const button of menuView.buttons) {- const row = plan.rows.get(button.id);- if (row) {- button.icon = row.view.icon;- button.bind("isEnabled").to(row.view, "isEnabled");- }- }-- for (const [id, source] of plan.mounts) {- mountControl(menuView, plan, id, source);+ this.hideMenu();+ const host = this.host ??= editor.config.get("toolbarGroupMenu")?.host(editor) ?? null;+ /* v8 ignore next 3 -- `afterInit()` watches no dropdown without a host */+ if (!host) {+ return;}- for (const menu of menuView.menus) {- const opener = plan.openers.get(menu.id);- /* v8 ignore next 3 -- every submenu the menu holds was described from an opener */- if (!opener) {- continue;+ // The toolbar's "Show more items" dropdown closes as focus or a press leaves it, so it+ // counts the menu as its own too, while it holds the group.+ const enclosing = [...toolbar.children].filter((child): child is DropdownView =>+ child instanceof DropdownView && child !== dropdown+ && !!child.element?.contains(anchor));+ const trackers = [editor.ui.focusTracker, ...enclosing.map((child) => child.focusTracker)];++ const run = (view: View) => () => {+ this.hideMenu();+ for (const child of enclosing) {+ child.isOpen = false;}-- menu.buttonView.icon = opener.view.icon;- menu.bind("isEnabled").to(opener.view, "isEnabled");- bindOpenerAction(menu, opener, dropdown);-- // Filled on the way open rather than once: `dateTime` renders its list in the time it- // is opened at, so rows filled in earlier would show the time of that earlier opening.- menu.on("change:isOpen", (evt, name, isOpen) => {- if (isOpen) {- this.fillSubmenu(menu, opener, plan);+ editor.editing.view.focus();+ view.fire("execute");+ };++ let element: HTMLElement | null = null;+ const request: ToolbarGroupMenuRequest = {+ anchor,+ items: describeItems(this.sourceItems(dropdown), run),+ setElement: (next) => {+ if (element) {+ untrackElement(element, trackers);}- });- }-- for (const index of [...plan.rules].reverse()) {- menuView.items.add(new ListSeparatorView(locale), index);- }- }-- /** Draws a submenu over the rows the entry's own list holds at this moment. */- private fillSubmenu(menu: DropdownMenuNestedMenuView, opener: MenuOpener, plan: MenuPlan) {- const locale = this.editor.locale;- const items = menu.listView.items;-- for (const id of opener.rowIds) {- plan.rows.delete(id);- }- opener.rowIds = [];- for (const drawn of [...items]) {- items.remove(drawn);- drawn.destroy();- }-- for (const entry of listEntriesOf(opener.source)) {- if (entry instanceof ListSeparatorView) {- if (items.length) {- items.add(new ListSeparatorView(locale));+ element = next;+ if (element) {+ trackElement(element, trackers);+ }+ },+ onClose: (returnFocus) => {+ if (this.shown?.request !== request) {+ return;+ }+ this.shown = null;+ if (returnFocus) {+ dropdown.buttonView.focus();}- continue;}+ };- const id = `${menu.id}:${opener.rowIds.length}`;- plan.rows.set(id, { view: entry, run: () => entry.fire("execute") });- opener.rowIds.push(id);+ this.shown = { dropdown, request };+ host.show(request);+ }- const button = new DropdownMenuListItemButtonView(locale, id, labelOf(entry));- button.icon = entry.icon;- button.bind("isEnabled").to(entry, "isEnabled");- items.add(new DropdownMenuListItemView(locale, menu, button));+ private hideMenu() {+ if (this.shown) {+ this.shown = null;+ this.host?.hide();}}-}+ /** The views CKEditor lays out in the group, which it builds the first time it is opened. */+ private sourceItems(dropdown: DropdownView) {+ if (!dropdown.toolbarView) {+ this.building = true;+ dropdown.isOpen = true;+ dropdown.isOpen = false;+ this.building = false;+ }-/**- * Replaces the button in `id`'s row with `source`, so it opens its own panel from the menu.- */-function mountControl(- menuView: DropdownMenuRootListView, plan: MenuPlan, id: string, source: DropdownView-) {- const placeholder = menuView.buttons.find((button) => button.id === id);- const row = [...menuView.items].find((item): item is DropdownMenuListItemView =>- item instanceof DropdownMenuListItemView && item.childView === placeholder);- /* v8 ignore next 3 -- the row was described to the menu under this very id */- if (!placeholder || !row) {- return;+ return [...dropdown.toolbarView?.items ?? []];}- row.children.remove(placeholder);- placeholder.destroy();- source.buttonView.withText = true;- row.children.add(source);- plan.mounted.push({ row, source });}-/**- * Runs the action an opener stands for when its row is pressed, and dismisses the menu — hovering- * still opens the submenu. An opener with no action of its own only opens, as CKEditor has it.- */-function bindOpenerAction(- menu: DropdownMenuNestedMenuView, opener: MenuOpener, dropdown: DropdownView-) {- const run = opener.run;- if (!run) {- return;- }+type DropdownSetIsOpenEvent = {+ name: "set:isOpen";+ args: [name: string, value: boolean, oldValue: boolean];+ return: boolean;+};- // On the button, which the next draw destroys along with the menu holding it.- menu.buttonView.on("execute", () => {- run();- dropdown.isOpen = false;- });+/** Stops presses in the menu from reaching CKEditor's `clickOutsideHandler()` on the document. */+function stopPress(e: Event) {+ e.stopPropagation();}-/** Lets go of the menu the previous draw left behind, which nothing else takes out of the panel. */-function discardMenu(dropdown: DropdownView, plan: MenuPlan | undefined) {- const previous = dropdown.menuView;- /* v8 ignore next 3 -- a menu is drawn before this runs, and only a redraw discards one */- if (!previous) {- return;- }-- // The controls mounted into it belong to the group, so they leave before the menu holding them- // is destroyed; the next draw mounts them again.- /* v8 ignore next -- only a redraw discards a menu, and it draws from a plan */- for (const { row, source } of plan?.mounted ?? []) {- row.children.remove(source);- }-- for (const menu of previous.menus) {- dropdown.focusTracker.remove(menu);+function trackElement(element: HTMLElement, trackers: FocusTracker[]) {+ element.addEventListener("mousedown", stopPress);+ for (const tracker of trackers) {+ tracker.add(element);}- dropdown.focusTracker.remove(previous);- dropdown.panelView.children.remove(previous);- previous.destroy();}-/** The view a row stands for: a split button where the entry also runs an action of its own. */-type SourceButton = View & Button;--interface MenuRow {- /** The view the row takes its label, icon and enabled state from. */- view: SourceButton;- /** Runs what the row stands for. */- run: () => void;-}--interface MenuOpener {- /** The view the submenu's opener takes its label, icon and enabled state from. */- view: SourceButton;- /** The dropdown of the group the submenu is drawn over, read afresh each time it opens. */- source: DropdownView;- /** The ids the rows drawn from that list are registered under. */- rowIds: string[];- /** What pressing the opener runs, where the entry carries an action of its own. */- run?: () => void;-}--interface MenuPlan {- definition: DropdownMenuDefinition;- rows: Map<string, MenuRow>;- /** What a submenu's opener stands for, by the submenu's id. */- openers: Map<string, MenuOpener>;- /** Where a rule goes in the root list, as an index into the list the definition builds. */- rules: number[];- /** The controls whose row holds the control itself, by the id of the row held for it. */- mounts: Map<string, DropdownView>;- /** Where each of those controls ended up, so a redraw can take it out before destroying it. */- mounted: Array<{ row: DropdownMenuListItemView; source: DropdownView }>;+function untrackElement(element: HTMLElement, trackers: FocusTracker[]) {+ element.removeEventListener("mousedown", stopPress);+ for (const tracker of trackers) {+ tracker.remove(element);+ }}function collectMenuGroupLabels(...configs: (ToolbarConfig | undefined)[]) {@@ -332,68 +281,65 @@ function collectFromItems(items: ToolbarConfigItem[] | undefined, labels: Set<st}}-function planGroupMenu(items: View[]) {- const plan: MenuPlan = {- definition: [],- rows: new Map(),- openers: new Map(),- rules: [],- mounts: new Map(),- mounted: []- };- let nextId = 0;- const takeId = () => `row${nextId++}`;+/**+ * The entries `items` stand for, with a rule wherever the group has a separator between entries.+ * A dropdown's list is read now, as `dateTime` fills its list with the time it is opened at.+ */+function describeItems(items: View[], run: (view: View) => () => void) {+ const described: ToolbarGroupMenuItem[] = [];for (const item of items) {if (item instanceof ToolbarSeparatorView) {- if (plan.definition.length) {- plan.rules.push(plan.definition.length);- }+ addRule(described);} else if (item instanceof ButtonView) {- plan.definition.push(describeRow(plan, takeId(), item));+ described.push(describeButton(item, run(item)));} else if (item instanceof DropdownView) {- planSubmenu(plan, takeId, item);+ const children: ToolbarGroupMenuItem[] = [];+ for (const entry of listEntriesOf(item)) {+ if (entry instanceof ListSeparatorView) {+ addRule(children);+ } else {+ children.push(describeButton(entry, run(entry)));+ }+ }+ trimRule(children);+ if (!children.length) {+ continue;+ }++ const opener = item.buttonView;+ described.push({+ kind: "entry",+ label: opener.label ?? "",+ icon: opener.icon,+ isEnabled: item.isEnabled,+ run: opener instanceof SplitButtonView ? run(opener) : undefined,+ children+ });}}- return plan;+ trimRule(described);+ return described;}-/** What a row is called: the label of the view it stands for, or nothing where it sets none. */-function labelOf(view: { label?: string }) {- return view.label ?? "";-}--/** Records a row against the view it stands for, and describes it to the menu. */-function describeRow(plan: MenuPlan, id: string, view: SourceButton) {- plan.rows.set(id, { view, run: () => view.fire("execute") });- return { id, label: labelOf(view) };+/** Adds a rule after the entries `items` holds, unless it would lead or double one. */+function addRule(items: ToolbarGroupMenuItem[]) {+ if (items.length && items.at(-1)?.kind !== "separator") {+ items.push({ kind: "separator" });+ }}-/**- * Describes `dropdown` as a submenu, which `ToolbarGroupMenu#fillSubmenu()` draws on the way open.- * A `SplitButtonView` opener also runs its own action, as a note tree context menu row does.- */-function planSubmenu(plan: MenuPlan, takeId: () => string, dropdown: DropdownView) {- const opener = dropdown.buttonView;-- // A dropdown offering no rows of its own carries a panel instead, so the row holds the dropdown- // itself and it opens that panel from the menu.- if (!listEntriesOf(dropdown).length) {- const mountId = takeId();- plan.mounts.set(mountId, dropdown);- plan.definition.push({ id: mountId, label: labelOf(opener) });- return;+function trimRule(items: ToolbarGroupMenuItem[]) {+ if (items.at(-1)?.kind === "separator") {+ items.pop();}+}- const id = takeId();- plan.openers.set(id, {- view: opener,- source: dropdown,- rowIds: [],- run: opener instanceof SplitButtonView ? () => opener.fire("execute") : undefined- });- plan.definition.push({ id, menu: labelOf(opener), children: [] });+function describeButton(view: ButtonView, run: () => void): ToolbarGroupMenuEntry {+ return {+ kind: "entry", label: view.label ?? "", icon: view.icon, isEnabled: view.isEnabled, run+ };}/** The rows a dropdown's own list holds, which it builds the first time it is opened. */diff --git a/packages/ckeditor5/src/theme/toolbar_group_menu.css b/packages/ckeditor5/src/theme/toolbar_group_menu.cssdeleted file mode 100644index 564cc98313..0000000000--- a/packages/ckeditor5/src/theme/toolbar_group_menu.css+++ /dev/null@@ -1,10 +0,0 @@-/* Every row is named, so the icons are sized against the label rather than against the toolbar. */-.ck.ck-toolbar__nested-toolbar-dropdown > .ck-dropdown__panel > .ck-dropdown-menu-list,-.ck.ck-dropdown-menu__nested-menu__panel.ck-toolbar-group-menu__panel {- --ck-icon-size: 1.1em;-}--/* A control mounted into a row, panel and all, fills the row as the rows beside it do. */-.ck.ck-dropdown-menu-list__nested-menu__item > .ck.ck-dropdown > .ck-button.ck-dropdown__button {- width: 100%;-}