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(ckeditor): open the AI tone and translate groups as submenus
Elian Doranba6463b9cf2d
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.tsindex a4672de9b1..6834638401 100644--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts@@ -96,6 +96,7 @@ export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {{id: "tone",label: t("ai_assistant.group_tone"),+ submenu: true,actions: [toneAction("professional", t("ai_assistant.tone_professional"),"Rewrite this content in a polished, formal, professional tone without changing the meaning."),@@ -110,6 +111,7 @@ export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {{id: "translate",label: t("ai_assistant.group_translate"),+ submenu: true,actions: [translateAction("translateEnglish", t("ai_assistant.lang_english"), "Translate the content to English."),translateAction("translateGerman", t("ai_assistant.lang_german"), "Translate the content to German."),diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.tsindex 248359f8b6..03bf2fef82 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -97,6 +97,16 @@ export interface AiQuickActionGroup {/** The group heading, already translated by the host. */label: string;actions: AiQuickAction[];+ /**+ * Whether the group opens as a submenu instead of having its actions listed directly in the+ * menu. Use it for the long groups whose actions only read as commands under their heading —+ * the same ones that need a {@link AiQuickAction.commandLabel}.+ *+ * An inlined group loses its heading: CKEditor's nested-menu definition has only buttons and+ * submenus, no group separators, so the choice is a submenu or bare top-level entries. That+ * suits actions that already read as commands on their own ("Fix typos", "Summarize").+ */+ submenu?: boolean;}export interface AiAssistantConfig {diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.tsindex 5fc725da02..6927175b6b 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts@@ -8,19 +8,19 @@ import AiAssistantUI from "./ai_assistant_ui.js";// ---- Typed views of the dropdown internals -----interface ListButtonView {+/** A leaf entry: an action the user can pick. */+interface MenuButtonView {+ id: string;label?: string;isEnabled: boolean;fire(event: string): void;}-interface ListItemView {- children: { get(idx: number): ListButtonView };-}--interface ListGroupView {- label: string;- items: { get(idx: number): ListItemView };+/** A submenu entry: a group that opens rather than listing its actions inline. */+interface NestedMenuView {+ id: string;+ buttonView: { label?: string };+ listView: { items: Array<{ childView: MenuButtonView }> };}interface QuickActionsDropdown {@@ -28,7 +28,10 @@ interface QuickActionsDropdown {isEnabled: boolean;class?: string;buttonView: SplitButtonView;- panelView: { children: { get(idx: number): { items: { get(idx: number): ListGroupView } } } };+ menuView: {+ items: Array<{ childView: MenuButtonView | NestedMenuView }>;+ buttons: MenuButtonView[];+ };}const QUICK_ACTIONS: AiQuickActionGroup[] = [@@ -46,6 +49,15 @@ const QUICK_ACTIONS: AiQuickActionGroup[] = [actions: [{ id: "write", label: "Write something", prompt: "Write a paragraph.", requiresContent: false }]+ },+ {+ id: "tone",+ label: "Change tone",+ submenu: true,+ actions: [+ { id: "direct", label: "Direct", prompt: "Make it direct." },+ { id: "friendly", label: "Friendly", prompt: "Make it friendly." }+ ]}];@@ -75,21 +87,28 @@ function createComponent(editor: ClassicEditor) {return editor.ui.componentFactory.create("aiAssistant") as unknown as QuickActionsDropdown;}-/** Opens the dropdown — `addListToDropdown` only populates the panel on the first open. */-function quickActionGroups(dropdown: QuickActionsDropdown): Array<{ label: string; buttons: ListButtonView[] }> {+/** Opens the dropdown — `addMenuToDropdown` only builds the menu on the first open. */+function openMenu(dropdown: QuickActionsDropdown): QuickActionsDropdown["menuView"] {dropdown.isOpen = true;+ return dropdown.menuView;+}- const list = dropdown.panelView.children.get(0);- return QUICK_ACTIONS.map((configured, groupIdx) => {- const group = list.items.get(groupIdx);- const buttons = configured.actions.map((_action, itemIdx) => group.items.get(itemIdx).children.get(0));- return { label: group.label, buttons };- });+/**+ * What the menu offers at its top level: an inlined action reads as its label, a submenu as its+ * label plus the labels it holds.+ */+function menuEntries(dropdown: QuickActionsDropdown): Array<string | { menu: string; actions: string[] }> {+ return openMenu(dropdown).items.map(({ childView }) => ("listView" in childView+ ? {+ menu: childView.buttonView.label ?? "",+ actions: childView.listView.items.map((item) => item.childView.label ?? "")+ }+ : childView.label ?? ""));}-/** The action buttons of every group, flattened into definition order. */-function quickActionButtons(dropdown: QuickActionsDropdown): ListButtonView[] {- return quickActionGroups(dropdown).flatMap((group) => group.buttons);+/** Every action button, submenus included, in definition order. */+function quickActionButtons(dropdown: QuickActionsDropdown): MenuButtonView[] {+ return openMenu(dropdown).buttons;}/** The form the assistant put into the dialog, once it is open. */@@ -138,24 +157,25 @@ describe("AiAssistantUI toolbar entry", () => {expect(showSpy).toHaveBeenCalled();});- it("lists every configured action under its group", () => {- const groups = quickActionGroups(dropdown);-- expect(groups.map((group) => ({- label: group.label,- actions: group.buttons.map((button) => button.label)- }))).toEqual([- { label: "Edit or review", actions: ["Fix typos", "Make shorter"] },- { label: "Generate", actions: ["Write something"] }+ it("inlines an ordinary group and gives a `submenu` one its own menu", () => {+ // An inlined group loses its heading — its actions already read as commands, and the+ // menu definition has no room for a heading. A submenu keeps its label as the entry.+ expect(menuEntries(dropdown)).toEqual([+ "Fix typos",+ "Make shorter",+ "Write something",+ { menu: "Change tone", actions: ["Direct", "Friendly"] }]);});it("gates the content-requiring actions on there being something to work on", () => {- const [fixTypos, , write] = quickActionButtons(dropdown);+ const [fixTypos, , write, direct] = quickActionButtons(dropdown);setModelData(editor.model, "<paragraph>[]</paragraph>");expect(fixTypos.isEnabled).toBe(false);expect(write.isEnabled).toBe(true);+ // Gating reaches into the submenus too, not just the inlined actions.+ expect(direct.isEnabled).toBe(false);// A collapsed caret is enough as long as its block has content: that is what the run// falls back to.@@ -166,6 +186,18 @@ describe("AiAssistantUI toolbar entry", () => {expect(fixTypos.isEnabled).toBe(true);});+ it("runs an action picked from inside a submenu", async () => {+ // A submenu button delegates its `execute` up through its menu to the root rather than+ // firing on the dropdown itself, so this is a different path from an inlined action.+ setModelData(editor.model, "<paragraph>[foo]</paragraph>");+ const direct = quickActionButtons(dropdown).find((button) => button.id === "direct");++ direct?.fire("execute");+ await vi.waitFor(() => expect(requests).toHaveLength(1));++ expect(requests[0]).toEqual({ query: "Make it direct.", context: "foo" });+ });+it("falls back to the caret's block when nothing is selected", async () => {setModelData(editor.model, "<paragraph>first</paragraph><paragraph>seco[]nd</paragraph>");const [fixTypos] = quickActionButtons(dropdown);diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsindex fc03536346..9ce7894f7f 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -1,17 +1,15 @@import {- addListToDropdown,+ addMenuToDropdown,ButtonView,CKEditorError,- Collection,createDropdown,Dialog,DialogViewPosition,Plugin,SplitButtonView,- ViewModel,+ type DropdownMenuDefinition,+ type DropdownMenuListItemButtonView,type DropdownView,- type ListDropdownButtonDefinition,- type ListDropdownItemDefinition,type Locale,type ModelNode,type ModelRange@@ -150,33 +148,50 @@ export default class AiAssistantUI extends Plugin {}this.listenTo(splitButtonView, "execute", () => this.editor.execute("aiAssistant"));- const items = new Collection<ListDropdownItemDefinition>();+ // The menu carries only ids and labels, so the action each button stands for is looked up+ // on execute rather than carried by the view.+ const actionsById = new Map<string, AiQuickAction>();+ const definition: DropdownMenuDefinition = [];for (const group of groups) {- const children = new Collection<ListDropdownButtonDefinition>();- for (const action of group.actions) {- const definition: ListDropdownButtonDefinition = {- type: "button",- model: new ViewModel({- _quickAction: action,- label: action.label,- withText: true- })- };- if (action.requiresContent !== false) {- definition.model.bind("isEnabled").to(this, "hasContext");- }- children.add(definition);+ const children = group.actions.map((action) => {+ actionsById.set(action.id, action);+ return { id: action.id, label: action.label };+ });+ if (group.submenu) {+ definition.push({ id: group.id, menu: group.label, children });+ } else {+ definition.push(...children);}- items.add({ type: "group", label: group.label, items: children });}- addListToDropdown(dropdownView, items);+ addMenuToDropdown(dropdownView, this.editor.ui.view.body, definition, {+ ariaLabel: locale.t("AI assistant")+ });dropdownView.class = "ck-ai-assistant-quick-actions";- // Only the list items reach this: a split button delegates its own `execute` to itself,- // and its arrow to the dropdown's `open`.+ // The menu builds its views in `render()`, which `addMenuToDropdown` defers to the first+ // open (through its own `change:isOpen` listener, registered at `highest` priority — so it+ // has already run by the time this one does). There are no buttons to bind before that,+ // and they are built exactly once, so this unsubscribes itself.+ const bindAvailability = () => {+ for (const button of dropdownView.menuView?.buttons ?? []) {+ if (actionsById.get(button.id)?.requiresContent !== false) {+ button.bind("isEnabled").to(this, "hasContext");+ }+ }+ this.stopListening(dropdownView, "change:isOpen", bindAvailability);+ };+ this.listenTo(dropdownView, "change:isOpen", bindAvailability);++ // Only the menu items reach this: a split button delegates its own `execute` to itself,+ // and its arrow to the dropdown's `open`. An item inside a submenu arrives here too — it+ // delegates up through its menu to the root — and delegation preserves the original+ // source, so the button (and its id) is the same either way.dropdownView.on("execute", (evt) => {- const { _quickAction } = evt.source as unknown as { _quickAction: AiQuickAction };- this.runQuickAction(_quickAction);+ const action = actionsById.get((evt.source as DropdownMenuListItemButtonView).id);+ /* v8 ignore next -- every button in the menu was built from an action in this map */+ if (action) {+ this.runQuickAction(action);+ }});return dropdownView;