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): give the AI quick actions icon-pack glyphs
Elian Doran7b753b61751a
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.tsindex 6d46e7268c..e975300d12 100644--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts@@ -295,6 +295,26 @@ describe("buildAiAssistantQuickActions", () => {.toEqual(["edit", "generate"]);});+ // A new action reaching the menu without an icon should fail here rather than ship a gap in+ // the column. Two exemptions, both pinned so they read as decisions: an inlined group has no+ // heading to put an icon on, and the languages share a panel with nothing that has one.+ it("gives every action, and every submenu, an icon from the pack", () => {+ for (const group of buildAiAssistantQuickActions()) {+ if (group.submenu) {+ expect(group.iconClass, group.id).toMatch(/^bx bx-[a-z-]+$/);+ } else {+ expect(group.iconClass, group.id).toBeUndefined();+ }+ for (const action of group.actions) {+ if (group.id === "translate") {+ expect(action.iconClass, action.id).toBeUndefined();+ } else {+ expect(action.iconClass, action.id).toMatch(/^bx bx-[a-z-]+$/);+ }+ }+ }+ });+it("leaves the labels that already read as commands alone", () => {for (const action of [ ...actions("edit"), ...actions("generate") ]) {expect(action.commandLabel).toBeUndefined();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 894b2f6f08..66788e776e 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@@ -81,7 +81,7 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {* given); prompts stay English — they are instructions to the model, not UI.*/export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {- return [+ return withIcons([{id: "edit",label: t("ai_assistant.group_edit"),@@ -176,7 +176,67 @@ export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {translateAction("translateChinese", t("ai_assistant.lang_chinese"), "Translate the content to Simplified Chinese.")]}- ];+ ]);+}++/**+ * The Boxicon each action and submenu shows in the menu — the icon pack the rest of the app draws+ * from, so no SVG is involved (the editor plugin renders the classes on a `<span>`, the same way+ * the template list renders a note's icon).+ *+ * Kept as one table keyed by id rather than threaded through the label helpers: those are about how+ * a label reads as a command, and one list is easier to keep complete than twenty-odd call sites.+ * The inlined groups are absent on purpose — without a heading there is nothing to put an icon on.+ */+const ICONS: Record<string, string> = {+ // Submenus.+ adjust: "bx bx-ruler",+ tone: "bx bx-palette",+ reformat: "bx bx-shape-square",+ translate: "bx bx-globe",++ // Edit or review.+ fixTypos: "bx bx-check-double",+ improveWriting: "bx bx-brush",++ // Generate.+ summarize: "bx bx-align-left",+ explain: "bx bx-bulb",+ continue: "bx bx-fast-forward",++ // Adjust.+ makeShorter: "bx bx-collapse-vertical",+ makeLonger: "bx bx-expand-vertical",+ simplify: "bx bx-leaf",++ // Change tone.+ professional: "bx bx-briefcase",+ casual: "bx bx-coffee",+ direct: "bx bx-target-lock",+ friendly: "bx bx-smile",+ confident: "bx bx-medal",++ // Reformat.+ bulletList: "bx bx-list-ul",+ table: "bx bx-table",+ diagram: "bx bx-network-chart",+ callout: "bx bx-info-circle",+ collapsible: "bx bx-chevrons-down",+ actionItems: "bx bx-task"++ // The languages are deliberately absent. The pack has no flags and nothing else tells German+ // from French, so the choice was one repeated glyph or none. `bx-empty` — Trilium's slot+ // reserver — is for an item sitting next to items that *do* have icons; the Translate submenu+ // is its own panel holding nothing but languages, so there is nothing to line up against.+};++/** Hangs {@link ICONS} on the definitions by id, leaving the ids that have none untouched. */+function withIcons(groups: AiQuickActionGroup[]): AiQuickActionGroup[] {+ return groups.map((group) => ({+ ...group,+ iconClass: ICONS[group.id],+ actions: group.actions.map((action) => ({ ...action, iconClass: ICONS[action.id] }))+ }));}/** Shorthand for a quick-action entry; all defaults require content to work on. */diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.tsindex 03bf2fef82..314667932a 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -74,6 +74,13 @@ export interface AiQuickAction {commandLabel?: string;/** The instruction sent to the model in place of a typed query. */prompt: string;+ /**+ * The action's icon, as a Boxicon class list (e.g. `"bx bx-check-double"`). Rendered directly+ * as a font-icon `<span>`, the same way {@link SnippetDefinition.iconClass} is: Trilium owns+ * this plugin, so there is no need to wrap the glyph in an SVG to satisfy CKEditor's generic+ * `IconView`.+ */+ iconClass?: string;/*** Whether the action needs content to work on. Actions that do (the default) are disabled* while there is nothing selected and nothing has been generated yet.@@ -97,6 +104,8 @@ export interface AiQuickActionGroup {/** The group heading, already translated by the host. */label: string;actions: AiQuickAction[];+ /** The group's icon, as a Boxicon class list. Only shown when the group is a {@link submenu}. */+ iconClass?: string;/*** 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 —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 6927175b6b..aa51ceaf32 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@@ -13,13 +13,14 @@ interface MenuButtonView {id: string;label?: string;isEnabled: boolean;+ element?: HTMLElement | null;fire(event: string): void;}/** A submenu entry: a group that opens rather than listing its actions inline. */interface NestedMenuView {id: string;- buttonView: { label?: string };+ buttonView: { label?: string; element?: HTMLElement | null };listView: { items: Array<{ childView: MenuButtonView }> };}@@ -54,8 +55,9 @@ const QUICK_ACTIONS: AiQuickActionGroup[] = [id: "tone",label: "Change tone",submenu: true,+ iconClass: "bx bx-palette",actions: [- { id: "direct", label: "Direct", prompt: "Make it direct." },+ { id: "direct", label: "Direct", commandLabel: "Make it direct", prompt: "Make it direct.", iconClass: "bx bx-target-lock" },{ id: "friendly", label: "Friendly", prompt: "Make it friendly." }]}@@ -111,6 +113,11 @@ function quickActionButtons(dropdown: QuickActionsDropdown): MenuButtonView[] {return openMenu(dropdown).buttons;}+/** What the dialog's header currently reads. */+function dialogTitle(editor: ClassicEditor) {+ return editor.plugins.get(Dialog).view?.headerView?.label;+}+/** The form the assistant put into the dialog, once it is open. */function openForm(editor: ClassicEditor) {return editor.plugins.get(Dialog).view?.contentView?.children.get(0) as unknown as {@@ -168,6 +175,25 @@ describe("AiAssistantUI toolbar entry", () => {]);});+ // The menu definition has no icon field, so the glyphs are hung on the views CKEditor+ // built — on an item inside a submenu as much as on an inlined one.+ it("renders an icon-pack glyph for the actions and submenus that have one", () => {+ const direct = quickActionButtons(dropdown).find((button) => button.id === "direct");+ expect(direct?.element?.querySelector(".ck-ai-action-icon")?.className)+ .toBe("ck-ai-action-icon bx bx-target-lock");++ const [tone] = openMenu(dropdown).items+ .map(({ childView }) => childView)+ .filter((childView): childView is NestedMenuView => "listView" in childView);+ expect(tone.buttonView.element?.querySelector(".ck-ai-action-icon")?.className)+ .toBe("ck-ai-action-icon bx bx-palette");+ });++ it("leaves an action without an icon alone", () => {+ const friendly = quickActionButtons(dropdown).find((button) => button.id === "friendly");+ expect(friendly?.element?.querySelector(".ck-ai-action-icon")).toBeNull();+ });+it("gates the content-requiring actions on there being something to work on", () => {const [fixTypos, , write, direct] = quickActionButtons(dropdown);@@ -234,6 +260,28 @@ describe("AiAssistantUI toolbar entry", () => {expect(dialog.id).toBe("aiAssistant");});+ it("titles the dialog with the action it is running, as the palette names it", async () => {+ setModelData(editor.model, "<paragraph>[foo]</paragraph>");+ const [fixTypos, , , direct] = quickActionButtons(dropdown);++ fixTypos.fire("execute");+ await vi.waitFor(() => expect(requests).toHaveLength(1));+ expect(dialogTitle(editor)).toBe("Fix typos");++ // A submenu's label can be a fragment ("Direct"), so an action may carry a standalone+ // phrasing for the places that show it away from its group.+ direct.fire("execute");+ await vi.waitFor(() => expect(requests).toHaveLength(2));+ expect(dialogTitle(editor)).toBe("Make it direct");++ // A typed follow-up is no longer that action.+ const form = openForm(editor);+ form.query = "now make it shorter";+ form.fire("submit");+ await vi.waitFor(() => expect(requests).toHaveLength(3));+ expect(dialogTitle(editor)).toBe("AI assistant");+ });+it("closes itself off while a run is in flight", async () => {let release = () => {};const editorWithSlowStream = await createTestEditor([Essentials, Paragraph, TriliumAiAssistant], {diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsindex ca6c5d77ca..c30bc55c78 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -7,6 +7,7 @@ import {DialogViewPosition,Plugin,SplitButtonView,+ View,type DropdownMenuDefinition,type DropdownMenuListItemButtonView,type DropdownView,@@ -150,8 +151,10 @@ export default class AiAssistantUI extends Plugin {// 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 groupsById = new Map<string, AiQuickActionGroup>();const definition: DropdownMenuDefinition = [];for (const group of groups) {+ groupsById.set(group.id, group);const children = group.actions.map((action) => {actionsById.set(action.id, action);return { id: action.id, label: action.label };@@ -171,15 +174,20 @@ export default class AiAssistantUI extends Plugin {// 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 = () => {+ const decorateMenu = () => {for (const button of dropdownView.menuView?.buttons ?? []) {- if (actionsById.get(button.id)?.requiresContent !== false) {+ const action = actionsById.get(button.id);+ if (action?.requiresContent !== false) {button.bind("isEnabled").to(this, "hasContext");}+ addIcon(button, action?.iconClass);}- this.stopListening(dropdownView, "change:isOpen", bindAvailability);+ for (const menu of dropdownView.menuView?.menus ?? []) {+ addIcon(menu.buttonView, groupsById.get(menu.id)?.iconClass);+ }+ this.stopListening(dropdownView, "change:isOpen", decorateMenu);};- this.listenTo(dropdownView, "change:isOpen", bindAvailability);+ this.listenTo(dropdownView, "change:isOpen", decorateMenu);// 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@@ -212,7 +220,9 @@ export default class AiAssistantUI extends Plugin {* entry points to the quick actions — the toolbar menu and the `/` palette — come in this way.*/public runQuickAction(action: AiQuickAction): void {- this._open(true);+ // Titled the way the `/` palette names the action: a bare label can be a fragment+ // ("Romanian") that only reads as an instruction beside its group heading.+ this._open(true, action.commandLabel ?? action.label);void this._run(action.prompt);}@@ -221,13 +231,17 @@ export default class AiAssistantUI extends Plugin {* instruction *about* content ("Fix typos"), so it needs something to* work on, while a free-form prompt typed at a collapsed caret* legitimately means "generate here" and must keep an empty context.+ * @param title names the run in the dialog's header, for a quick action. Defaults to the+ * feature's own name, which is all a free-form prompt can be called.*/- private _open(fallbackToBlock: boolean): void {+ private _open(fallbackToBlock: boolean, title?: string): void {const editor = this.editor;const dialog = editor.plugins.get(Dialog);const form = this._getForm();+ const heading = title ?? editor.t("AI assistant");if (dialog.id === DIALOG_ID) {+ this._setTitle(heading);form.focus();return;}@@ -255,7 +269,7 @@ export default class AiAssistantUI extends Plugin {id: DIALOG_ID,// A header is what makes the dialog draggable, so the user can move it off the text// being rewritten.- title: editor.t("AI assistant"),+ title: heading,icon: aiIcon,isModal: false,position: DialogViewPosition.EDITOR_CENTER,@@ -267,6 +281,21 @@ export default class AiAssistantUI extends Plugin {form.focus();}+ /**+ * Retitles the dialog while it stands. `show()` takes the title only once, so a quick action+ * picked over an already-open assistant has to write to the header itself — and to the aria+ * label, which the dialog otherwise derives from the same string.+ */+ private _setTitle(title: string): void {+ const view = this.editor.plugins.get(Dialog).view;+ /* v8 ignore next -- every call site has just established that the dialog is open */+ if (!view?.headerView) {+ return;+ }+ view.headerView.label = title;+ view.ariaLabel = title;+ }+private _getForm(): AiAssistantFormView {if (this._formView) {return this._formView;@@ -280,6 +309,9 @@ export default class AiAssistantUI extends Plugin {const query = form.query.trim();if (query) {form.query = "";+ // A typed follow-up is no longer the quick action that opened the assistant, so+ // the header stops claiming to be one.+ this._setTitle(editor.t("AI assistant"));void this._run(query);}});@@ -533,6 +565,34 @@ export default class AiAssistantUI extends Plugin {}}+/**+ * Puts a font icon in front of a menu button's label. The menu definition has no icon field and+ * CKEditor builds these views itself, so the glyph is added to the button's children afterwards —+ * the same after-render mutation the snippet list does, and safe because a `ViewCollection` bound+ * to a rendered element renders whatever is added to it.+ */+function addIcon(button: ButtonView, iconClass: string | undefined): void {+ if (iconClass) {+ button.children.add(new FontIconView(button.locale, iconClass), 0);+ }+}++/**+ * An icon-pack glyph as a plain `<span>`. CKEditor's `IconView` takes SVG source, which a font+ * icon has none of; Trilium owns this plugin, so the class list can be rendered directly.+ */+class FontIconView extends View {++ constructor(locale: Locale | undefined, iconClass: string) {+ super(locale);++ this.setTemplate({+ tag: "span",+ attributes: { class: ["ck-ai-action-icon", ...iconClass.split(" ")] }+ });+ }+}+/*** Whether the toolbar entry can be used: the command is enabled (an LLM provider is configured)* and no run is in flight.diff --git a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.cssindex 47c54c3f84..1355bacdf0 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css@@ -125,3 +125,11 @@.ck-content .ck-ai-assistant-target {background: rgba(148, 112, 219, 0.22);}++/* Not scoped to the dropdown: a submenu's panel is appended to the editor's body collection, so it+ is not inside the toolbar entry's element. */+.ck.ck-button > .ck-ai-action-icon {+ margin-inline-end: var(--ck-spacing-medium);+ font-size: 1.1em;+ line-height: 1;+}