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(ai-assistant): redraw the quick actions menu on a live editor
Elian Doran2b24ee8f037a
diff --git a/apps/client/src/menus/text_editor_context_menu.spec.ts b/apps/client/src/menus/text_editor_context_menu.spec.tsindex 2a99ab6256..138571c6ca 100644--- a/apps/client/src/menus/text_editor_context_menu.spec.ts+++ b/apps/client/src/menus/text_editor_context_menu.spec.ts@@ -62,12 +62,12 @@ function fakeEditor({isEnabled?: boolean;hasPlugin?: boolean;}) {- const ui = { hasContext, isStreaming, runQuickAction: vi.fn() };+ // The live list is the plugin's, which the editor config only seeded.+ const ui = { hasContext, isStreaming, quickActions: groups, runQuickAction: vi.fn() };const editor = {editing: { view: { getDomRoot: () => domRoot } },plugins: { has: () => hasPlugin, get: () => ui },commands: { get: () => ({ isEnabled }) },- config: { get: () => ({ quickActions: groups }) },execute: vi.fn()};tabManager.activeNote = { type: "text" };diff --git a/apps/client/src/menus/text_editor_context_menu.ts b/apps/client/src/menus/text_editor_context_menu.tsindex 39556d318f..4054015892 100644--- a/apps/client/src/menus/text_editor_context_menu.ts+++ b/apps/client/src/menus/text_editor_context_menu.ts@@ -31,8 +31,10 @@ export async function buildAiActionsMenuItem(): Promise<MenuItem<CommandNames> |return null;}+ // The plugin's list rather than the config's: the config only seeded it, and the content+ // languages behind Translate can be changed from inside the editor.const quickActions = buildQuickActionItems(- editor.config.get("aiAssistant")?.quickActions ?? [],+ ui.quickActions,ui.hasContext,(action) => ui.runQuickAction(action));@@ -73,7 +75,7 @@ export async function buildAiActionsMenuItem(): Promise<MenuItem<CommandNames> |* submenu whose actions all do.*/function buildQuickActionItems(- groups: AiQuickActionGroup[],+ groups: ReadonlyArray<AiQuickActionGroup>,hasContext: boolean,run: (action: AiQuickAction) => void): MenuItem<CommandNames>[] {diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxindex c6c654dfeb..18e6ae1457 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx@@ -6,6 +6,7 @@ import froca from "../../../services/froca";import link from "../../../services/link";import linkEmbedService, { type EmbedMetadata } from "../../../services/link_embed";import { useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteContext, useSyncedRef, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import { buildAiAssistantQuickActions } from "./ai_assistant_stream";import { buildConfig, BuildEditorOptions } from "./config";export type BoxSize = "small" | "medium" | "full" | "expandable";@@ -93,6 +94,12 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe// the tag list, for the same by-value reason as `customReplacements` above.const [ htmlSupportEnabled ] = useTriliumOptionBool("textNoteHtmlSupportEnabled");const [ allowedHtmlTags ] = useTriliumOption("allowedHtmlTags");+ // Deliberately *not* a rebuild trigger: the enabled content languages fill the AI assistant's+ // Translate submenu, which now offers the row that edits them — so the change is made from+ // inside the editor, several times over while the modal is open, and a rebuild each time would+ // cost the caret and the undo history of the note being written. Pushed into the live editor by+ // the effect below instead. The raw JSON, for the by-value reason above.+ const [ contentLanguages ] = useTriliumOption("languages");const [ editor, setEditor ] = useState<CKTextEditor>();const { parentComponent, ntxId, note } = useNoteContext();@@ -334,6 +341,16 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe}}, [ editor, templates ]);+ // Likewise for the AI quick actions, whose Translate group lists the enabled content languages:+ // rebuilt from the current options and pushed into the live editor, so enabling a language shows+ // it in the menu without the note losing its undo history.+ useEffect(() => {+ if (!editor) return;+ if (editor.plugins.has("AiAssistantUI")) {+ editor.plugins.get("AiAssistantUI").updateQuickActions(buildAiAssistantQuickActions());+ }+ }, [ editor, contentLanguages ]);+// React to notification warning callback.useEffect(() => {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 341d5b4e8f..2fda537119 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@@ -31,6 +31,8 @@ interface QuickActionsDropdown {isEnabled: boolean;class?: string;buttonView: SplitButtonView;+ /** Holds the menu once it is open; a redraw has to leave exactly one behind. */+ panelView: { children: { length: number } };menuView: {/** A separator is a plain view: no `childView`, which is how the walker tells it apart. */items: Array<{ childView?: MenuButtonView | NestedMenuView }>;@@ -126,9 +128,12 @@ function menuEntries(dropdown: QuickActionsDropdown): Array<string | { menu: str});}-/** Every action button, submenus included, in definition order. */+/**+ * Every action button, submenus included, in definition order — without the row that heads the+ * menu, which opens the assistant rather than running anything.+ */function quickActionButtons(dropdown: QuickActionsDropdown): MenuButtonView[] {- return openMenu(dropdown).buttons;+ return openMenu(dropdown).buttons.filter((button) => button.id !== "__ask");}/** What the dialog's header currently reads. */@@ -190,6 +195,10 @@ describe("AiAssistantUI toolbar entry", () => {// 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([+ // The way in the button half offers, for the menu — a prompt rather than an+ // instruction, so it heads the menu behind a rule of its own.+ "Ask AI…",+ "---","Fix typos","Make shorter","---",@@ -202,9 +211,26 @@ describe("AiAssistantUI toolbar entry", () => {// A rule between blocks, and none between two openers: without the headings the menu// definition cannot carry, the separator is what marks where a set of actions ends.+ it("heads the menu with the way in the button half offers", () => {+ const showSpy = vi.spyOn(editor.plugins.get(AiAssistantUI), "show");+ const [ask] = openMenu(dropdown).buttons;++ expect(ask.id).toBe("__ask");+ expect(ask.label).toBe("Ask AI…");++ // A prompt is typed against whatever is there, so unlike an instruction about content+ // this row does not go inert when there is none.+ setModelData(editor.model, "<paragraph>[]</paragraph>");+ expect(ask.isEnabled).toBe(true);++ ask.fire("execute");+ expect(showSpy).toHaveBeenCalled();+ });+it("rules off each block but not between adjacent submenus", () => {const entries = menuEntries(dropdown);- expect(entries.filter((entry) => entry === "---")).toHaveLength(2);+ // One under the prompt row, then one per group boundary that is not between submenus.+ expect(entries.filter((entry) => entry === "---")).toHaveLength(3);expect(entries.at(-1)).toEqual({ menu: "Translate", actions: ["Romanian"] });});@@ -307,6 +333,43 @@ describe("AiAssistantUI toolbar entry", () => {expect(editorWithFooter.plugins.get(Dialog).id).toBeNull();});+ // The Translate group lists the enabled content languages, which the footer above lets the+ // user change from inside the editor — so the menu has to be able to say something new+ // without the editor being torn down and rebuilt, which would cost the caret and the undo+ // history of the note being written.+ it("redraws the menu when the quick actions are replaced on a live editor", async () => {+ expect(menuEntries(dropdown)).toContainEqual({ menu: "Translate", actions: ["Romanian"] });++ editor.plugins.get(AiAssistantUI).updateQuickActions([{+ id: "translate",+ label: "Translate",+ submenu: true,+ actions: [+ { id: "german", label: "German", prompt: "Translate to German." },+ { id: "japanese", label: "Japanese", prompt: "Translate to Japanese." }+ ]+ }]);++ // Redrawn on the way open, so it is still the old menu until the dropdown is reopened.+ dropdown.isOpen = false;+ dropdown.isOpen = true;+ expect(menuEntries(dropdown)).toEqual([+ "Ask AI…",+ "---",+ { menu: "Translate", actions: ["German", "Japanese"] }+ ]);++ // The menu the redraw replaced is gone rather than left beside its successor.+ expect(dropdown.panelView.children.length).toBe(1);++ // A button from the new draw still reaches the assistant, so the execute lookup was+ // refilled along with the views.+ setModelData(editor.model, "<paragraph>[foo]</paragraph>");+ quickActionButtons(dropdown).find((button) => button.id === "japanese")?.fire("execute");+ await vi.waitFor(() => expect(requests).toHaveLength(1));+ expect(requests[0]).toEqual({ query: "Translate to Japanese.", context: "foo" });+ });+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.diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsindex 2359ae4a78..a81b224015 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -32,6 +32,12 @@ const RENDER_THROTTLE_MS = 80;/** Identifies our dialog in the editor-wide `Dialog` plugin, which shows one dialog at a time. */const DIALOG_ID = "aiAssistant";+/**+ * Identifies the menu row that opens the assistant for a typed prompt. Prefixed out of the way of+ * the host's action ids, which share the same id space.+ */+const ASK_ID = "__ask";+/*** How much of a response has to be a replacement rather than an edit (see* `AiDiffResult.rewriteRatio`) before the review opens on the plain result instead of the diff.@@ -93,11 +99,28 @@ export default class AiAssistantUI extends Plugin {*/private _reviewView: AiReviewView | null = null;+ /**+ * The quick actions as they stand, which the config only seeds — see {@link updateQuickActions}.+ * Every surface offering them reads this rather than the config, so they cannot disagree about+ * what is on offer.+ */+ private _quickActions: AiQuickActionGroup[] = [];+ /**+ * Marks each menu built from {@link _quickActions} as owing a redraw, one closure per toolbar+ * showing us.+ */+ private readonly _invalidateMenu: Array<() => void> = [];++ public get quickActions(): ReadonlyArray<AiQuickActionGroup> {+ return this._quickActions;+ }+public init(): void {const editor = this.editor;this.set("isStreaming", false);this.set("hasContext", false);+ this._quickActions = editor.config.get("aiAssistant")?.quickActions ?? [];editor.ui.componentFactory.add("aiAssistant", (locale) => this._createToolbarComponent(locale));@@ -115,12 +138,30 @@ export default class AiAssistantUI extends Plugin {* degrades to a plain button.*/private _createToolbarComponent(locale: Locale): ButtonView | DropdownView {- const groups = this.editor.config.get("aiAssistant")?.quickActions ?? [];- return groups.length- ? this._createQuickActionsDropdown(locale, groups)+ // Which of the two the entry is, is settled here and for good: a toolbar item cannot change+ // its own kind. A host that configures actions at all keeps configuring some.+ return this._quickActions.length+ ? this._createQuickActionsDropdown(locale): this._createAssistantButton(locale);}+ /**+ * Replaces the quick actions on a live editor, redrawing every menu built from them — the same+ * contract `TriliumSnippets.updateDefinitions` has, and for the same reason: a list the user+ * edits from inside the editor cannot wait for the editor to be rebuilt to say what it now+ * holds, and rebuilding one costs the caret and the undo history.+ *+ * A menu is redrawn the next time it opens rather than on the spot. CKEditor builds its views+ * in `render()`, which `addMenuToDropdown` defers to the first open, so a menu that has never+ * been opened has nothing to redraw yet — and one that has is not on screen to see it happen.+ */+ public updateQuickActions(groups: AiQuickActionGroup[]): void {+ this._quickActions = groups;+ for (const invalidate of this._invalidateMenu) {+ invalidate();+ }+ }+private _createAssistantButton(locale: Locale): ButtonView {const command = this.editor.commands.get("aiAssistant");const buttonView = new ButtonView(locale);@@ -144,7 +185,7 @@ export default class AiAssistantUI extends Plugin {* marked `requiresContent` stay disabled until there is something to work on — a selection, or* a response to chain on.*/- private _createQuickActionsDropdown(locale: Locale, groups: AiQuickActionGroup[]): DropdownView {+ private _createQuickActionsDropdown(locale: Locale): DropdownView {const command = this.editor.commands.get("aiAssistant");const dropdownView = createDropdown(locale, SplitButtonView);const splitButtonView = dropdownView.buttonView;@@ -163,49 +204,99 @@ export default class AiAssistantUI extends Plugin {this.listenTo(splitButtonView, "execute", () => this.editor.execute("aiAssistant"));// 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.+ // on execute rather than carried by the view. Refilled by every draw: which actions there+ // are is the very thing a redraw changes.const actionsById = new Map<string, AiQuickAction>();const footersById = new Map<string, AiQuickActionFooter>();const groupsById = new Map<string, AiQuickActionGroup>();- const definition: DropdownMenuDefinition = [];// Where the menu wants a rule drawn, as indices into the finished item list. An inlined// group lost its heading to the menu definition, so a separator is what is left to say// where one set of actions ends and the next begins. Consecutive submenus need none: they// read as one block of "openers" already.- const separatorAt: number[] = [];- for (const [index, group] of groups.entries()) {- groupsById.set(group.id, group);- const children = group.actions.map((action) => {- actionsById.set(action.id, action);- return { id: action.id, label: action.label };- });- if (group.submenu) {- if (group.footer) {- const id = `${group.id}:footer`;- footersById.set(id, group.footer);- children.push({ id, label: group.footer.label });- }- definition.push({ id: group.id, menu: group.label, children });- } else {- definition.push(...children);+ let separatorAt: number[] = [];++ /**+ * Lets go of the menu a previous draw left behind. `addMenuToDropdown` only ever assigns+ * `menuView`, so without this the old one stays in the panel and in the focus tracker and+ * the new one is added beside it.+ */+ const discardMenu = () => {+ const previous = dropdownView.menuView;+ /* v8 ignore next 3 -- only the first draw finds no menu, and it is not a redraw */+ if (!previous) {+ return;}+ for (const menu of previous.menus) {+ dropdownView.focusTracker.remove(menu);+ }+ dropdownView.focusTracker.remove(previous);+ if (dropdownView.panelView.children.has(previous)) {+ dropdownView.panelView.children.remove(previous);+ }+ previous.destroy();+ };++ const buildMenu = () => {+ actionsById.clear();+ footersById.clear();+ groupsById.clear();+ separatorAt = [];- const next = groups[index + 1];- if (next && !(group.submenu && next.submenu)) {+ const groups = this._quickActions;+ const definition: DropdownMenuDefinition = [];++ // Heads the menu: the typed prompt every row below it is a shortcut past, and what the+ // button half of the split does. Ruled off from them, since it is a way in rather than an+ // instruction.+ definition.push({ id: ASK_ID, label: locale.t("Ask AI…") });+ if (groups.length) {separatorAt.push(definition.length);}- }- addMenuToDropdown(dropdownView, this.editor.ui.view.body, definition, {- ariaLabel: locale.t("AI assistant")- });++ for (const [index, group] of groups.entries()) {+ groupsById.set(group.id, group);+ const children = group.actions.map((action) => {+ actionsById.set(action.id, action);+ return { id: action.id, label: action.label };+ });+ if (group.submenu) {+ if (group.footer) {+ const id = `${group.id}:footer`;+ footersById.set(id, group.footer);+ children.push({ id, label: group.footer.label });+ }+ definition.push({ id: group.id, menu: group.label, children });+ } else {+ definition.push(...children);+ }++ const next = groups[index + 1];+ if (next && !(group.submenu && next.submenu)) {+ separatorAt.push(definition.length);+ }+ }++ discardMenu();+ addMenuToDropdown(dropdownView, this.editor.ui.view.body, definition, {+ ariaLabel: locale.t("AI assistant")+ });+ };++ buildMenu();dropdownView.class = "ck-ai-assistant-quick-actions";// 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.+ // has already run by the time this one does). There are no buttons to bind before that.const decorateMenu = () => {for (const button of dropdownView.menuView?.buttons ?? []) {+ if (button.id === ASK_ID) {+ // A prompt is typed against whatever is there, selection or not, so this row+ // is never gated the way an instruction about content is.+ addIcon(button, this.editor.config.get("aiAssistant")?.askIconClass);+ continue;+ }+const footer = footersById.get(button.id);if (footer) {// A footer configures the group rather than running against the document, so it@@ -241,9 +332,33 @@ export default class AiAssistantUI extends Plugin {for (const index of [...separatorAt].reverse()) {dropdownView.menuView?.items.add(new ListSeparatorView(locale), index);}- this.stopListening(dropdownView, "change:isOpen", decorateMenu);};- this.listenTo(dropdownView, "change:isOpen", decorateMenu);++ // Everything the menu needs doing happens on the way open: the views to decorate do not+ // exist until then, and a redraw asked for meanwhile is invisible until then anyway. Both+ // are one-shot per menu — hence the flags rather than an unsubscribe, since a redraw makes+ // the work due again.+ let needsDraw = false;+ let needsDecoration = true;+ this._invalidateMenu.push(() => {+ needsDraw = true;+ });+ this.listenTo(dropdownView, "change:isOpen", () => {+ if (!dropdownView.isOpen) {+ return;+ }+ if (needsDraw) {+ // Open, so `addMenuToDropdown` attaches and renders on the spot rather than+ // deferring to an opening that has already happened.+ buildMenu();+ needsDraw = false;+ needsDecoration = true;+ }+ if (needsDecoration) {+ decorateMenu();+ needsDecoration = false;+ }+ });// 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@@ -251,6 +366,12 @@ export default class AiAssistantUI extends Plugin {// source, so the button (and its id) is the same either way.dropdownView.on("execute", (evt) => {const id = (evt.source as DropdownMenuListItemButtonView).id;+ if (id === ASK_ID) {+ // Through the command, so this row and the button half arrive by the same road.+ this.editor.execute("aiAssistant");+ return;+ }+const footer = footersById.get(id);if (footer) {footer.run();@@ -366,7 +487,9 @@ export default class AiAssistantUI extends Plugin {}const editor = this.editor;- const form = new AiAssistantFormView(editor.locale);+ const form = new AiAssistantFormView(editor.locale, {+ onResultRendered: (preview) => this._renderPreviewDiagrams(preview)+ });this._formView = form;form.on("submit", () => {@@ -525,6 +648,33 @@ export default class AiAssistantUI extends Plugin {return sanitize(html);}+ /**+ * Turns the `language-mermaid` code blocks of a finished response into rendered diagrams, so+ * the review shows what committing it will show. The response is Markdown rendered to note+ * HTML, in which a diagram is a code block — the editor only makes one a diagram when the+ * content is upcast into the model, which the assistant deliberately postpones until commit.+ *+ * Soft-coupled to the Mermaid feature by name: a build without it renders the source, which is+ * also all a commit could produce there.+ */+ private _renderPreviewDiagrams(preview: HTMLElement): void {+ const editor = this.editor;+ if (!editor.plugins.has("MermaidEditing")) {+ return;+ }++ const mermaid = editor.plugins.get("MermaidEditing");+ for (const code of preview.querySelectorAll("pre > code.language-mermaid")) {+ const source = code.textContent ?? "";+ const diagram = preview.ownerDocument.createElement("div");+ diagram.className = "ck-ai-assistant-form__diagram";+ // The `<pre>` goes with it: what is left has to be a plain block, or the code-block+ // styling frames the diagram in the preview and nowhere else.+ code.parentElement?.replaceWith(diagram);+ void mermaid.renderMermaid(diagram, source);+ }+ }+/*** The "Changes" view of the review: the finished response diffed against the context the run* saw (`_previousContext` — so a follow-up query diffs against the response it refined, notdiff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.tsindex d2946e2771..eff6fda7a5 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts@@ -427,7 +427,9 @@ function buildAiQuickActionSlashCommands(editor: Editor): SlashCommandDefinitionconst t = editor.locale.t;- return (editor.config.get("aiAssistant")?.quickActions ?? []).flatMap((group) =>+ // The plugin's list rather than the config's: the config only seeded it, and the content+ // languages behind Translate can be changed from inside the editor.+ return editor.plugins.get("AiAssistantUI").quickActions.flatMap((group) =>group.actions.map((action) => ({id: `ai-${action.id}`,title: t("AI: %0", action.commandLabel ?? action.label),