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
fix(ckeditor): gate slash entries on `isEnabled`, and correlate feed requests
Elian Dorana0532825e278
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.tsindex 568f37ecd9..d3f340ff70 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts@@ -129,6 +129,14 @@ describe("TriliumSlashCommands", () => {expect(slashFeed().minimumCharacters).toBe(0);});+ it("shows the palette unbounded by default, since the query only ever narrows it", async () => {+ // Premium defaulted to `Infinity`; a cap would hide entries no query could then reach.+ expect(slashFeed().dropdownLimit).toBe(Infinity);++ await createEditor({ dropdownLimit: 3 });+ expect(slashFeed().dropdownLimit).toBe(3);+ });+describe("catalog", () => {it("derives heading entries from heading.options, so the palette matches the configured levels", () => {const defaults = buildDefaultSlashCommands(editor).map((definition) => definition.id);@@ -179,6 +187,37 @@ describe("TriliumSlashCommands", () => {expect(ids).toContain("/heading2");});+ it("hides an entry whose command is registered but disabled for the current selection", async () => {+ const blockQuote = editor.commands.get("blockQuote");++ if (!blockQuote) {+ throw new Error("the editor should register the blockQuote command");+ }++ expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toContain("/blockQuote");++ // Committing an entry first deletes the `/query`, so an entry whose command would no-op+ // costs the user their input and returns nothing.+ blockQuote.forceDisabled("spec");+ expect((await queryPalette("")).map((item) => (item as { id: string }).id)).not.toContain("/blockQuote");++ blockQuote.clearForceDisabled("spec");+ expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toContain("/blockQuote");+ });++ it("honours an entry's own isEnabled predicate, which is the only gate an execute-only entry has", async () => {+ const isEnabled = vi.fn(() => false);+ await createEditor({+ extraCommands: [ { id: "custom", title: "Custom thing", icon: "<svg/>", execute: () => {}, isEnabled } ]+ });++ expect((await queryPalette("")).map((item) => (item as { id: string }).id)).not.toContain("/custom");+ expect(isEnabled).toHaveBeenCalledWith(editor);++ isEnabled.mockReturnValue(true);+ expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toContain("/custom");+ });+it("appends extraCommands after the defaults, without gating them on a command", async () => {await createEditor({extraCommands: [ { id: "custom", title: "Custom thing", icon: "<svg/>", execute: () => {} } ]diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.tsindex 2745f75042..579713283c 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts@@ -21,8 +21,6 @@ import { registerMentionFeed } from "./register_feed.js";export const SLASH_MARKER = "/";-const DROPDOWN_LIMIT = 10;-/*** One entry of the `/` palette. Structurally the same shape premium `SlashCommand` accepted, so the* definitions in `extra_slash_commands.ts` carry over unchanged.@@ -40,11 +38,19 @@ export interface SlashCommandDefinition {commandName?: string;/** Runs instead of `commandName`, for entries that need arguments or open a UI. */execute?: (editor: Editor) => void;+ /**+ * Whether the entry applies to the current selection. Defaults to the `isEnabled` of+ * {@link commandName}; entries that only provide {@link execute} are always offered unless they+ * define this. Mirrors premium's `_proxyIsEnabled`.+ */+ isEnabled?: (editor: Editor) => boolean;}export interface SlashCommandConfig {extraCommands?: SlashCommandDefinition[];removeCommands?: string[];+ /** How many entries the palette shows at once. Unlimited by default, as premium's was. */+ dropdownLimit?: number;}/**@@ -74,7 +80,9 @@ export default class TriliumSlashCommands extends Plugin {marker: SLASH_MARKER,// A bare `/` opens the full palette, as the premium plugin did.minimumCharacters: 0,- dropdownLimit: DROPDOWN_LIMIT,+ // Premium defaulted this to `Infinity` and let the panel scroll. Capping it would hide+ // entries the user cannot then reach, since the query only narrows the list.+ dropdownLimit: (editor.config.get("slashCommand.dropdownLimit") as number | undefined) ?? Infinity,feed: (query: string) => matchSlashCommands(this._catalog(), query).map(toFeedItem),itemRenderer: (item) => renderRow(item as SlashCommandItem),commit: (editorInstance, item) => runSlashCommand(editorInstance, (item as SlashCommandItem).definition)@@ -82,8 +90,9 @@ export default class TriliumSlashCommands extends Plugin {}/**- * The definitions available in *this* editor: the built-in palette plus the configured extras,- * minus anything `removeCommands` names and anything whose command is not loaded.+ * The definitions available in *this* editor right now: the built-in palette plus the configured+ * extras, minus anything `removeCommands` names and anything that does not apply to the current+ * selection.*/private _catalog(): SlashCommandDefinition[] {const editor = this.editor;@@ -92,11 +101,29 @@ export default class TriliumSlashCommands extends Plugin {return [ ...buildDefaultSlashCommands(editor), ...(config.extraCommands ?? []) ].filter((definition) => !removed.has(definition.id))- // An entry naming a command no plugin registered would throw on execute. Entries with- // their own `execute` are the caller's responsibility, exactly as upstream treated- // `extraCommands`.- .filter((definition) => !definition.commandName || !!editor.commands.get(definition.commandName));+ .filter((definition) => isSlashCommandEnabled(editor, definition));+ }+}++/**+ * Whether an entry should be offered for the caret's current position.+ *+ * Existence of the command is not enough: a registered but disabled command (`indent` in a plain+ * paragraph, say) makes `editor.execute()` a no-op, and since committing an entry first deletes the+ * `/query` the user would lose what they typed and get nothing back. Premium evaluated the same+ * predicate on every keystroke in `getMatchingCommands()`, so entries appear and disappear as the+ * selection moves.+ */+function isSlashCommandEnabled(editor: Editor, definition: SlashCommandDefinition): boolean {+ if (definition.isEnabled) {+ return definition.isEnabled(editor);}++ if (!definition.commandName) {+ return true;+ }++ return editor.commands.get(definition.commandName)?.isEnabled ?? false;}type SlashCommandItem = MentionFeedObjectItem & { definition: SlashCommandDefinition };diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.tsindex 062a652ee4..0e32186981 100644--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts@@ -423,6 +423,55 @@ describe("TriliumMentionUI", () => {pressKey(keyCodes.enter);expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alpha");});++ it("discards a stale response even when the newer request has the same query text", async () => {+ const resolvers: Array<(items: MentionFeedObjectItem[]) => void> = [];+ await createEditor({+ feed: (() => new Promise((resolve) => resolvers.push(resolve))) as unknown as TriliumMentionFeed["feed"]+ });+ setModelData(editor.model, "<paragraph>[]</paragraph>");++ // Same query typed twice, so correlating on the text alone cannot tell them apart.+ type("#al");+ await settle();+ editor.model.change((writer) => writer.remove(editor.model.createRangeIn(editor.model.document.getRoot()?.getChild(0) as never)));+ type("#al");+ await settle();++ resolvers[1]?.([ { id: "#fresh", text: "#fresh" } ]);+ resolvers[0]?.([ { id: "#stale", text: "#stale" } ]);+ await settle();++ pressKey(keyCodes.enter);+ const data = getModelData(editor.model, { withoutSelection: true });+ expect(data).toContain("#fresh");+ expect(data).not.toContain("#stale");+ });++ it("does not let an earlier request's rejection close the panel a later one opened", async () => {+ let rejectFirst: (reason: Error) => void = () => {};+ let call = 0;+ await createEditor({+ feed: (() => {+ if (call++ === 0) {+ return new Promise((_resolve, reject) => { rejectFirst = reject; });+ }+ return Promise.resolve([ { id: "#alpha", text: "#alpha" } ]);+ }) as unknown as TriliumMentionFeed["feed"]+ });+ setModelData(editor.model, "<paragraph>[]</paragraph>");++ type("#a");+ await settle();+ type("l");+ await settle();+ expect(isPanelVisible()).toBe(true);++ rejectFirst(new Error("boom"));+ await settle();++ expect(isPanelVisible()).toBe(true);+ });});it("does not re-trigger inside an existing mention", async () => {diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.tsindex 893db56238..667276bfc0 100644--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts@@ -57,9 +57,11 @@ export default class TriliumMentionUI extends Plugin {private _patterns: Pattern[] = [];private _balloon?: ContextualBalloon;- private _lastRequestedQuery?: string;private _feedTimer?: ReturnType<typeof setTimeout>;+ /** Monotonic id of the most recently *started* feed request; see {@link _requestFeed}. */+ private _requestId = 0;+/*** Where the marker of the panel the user dismissed with Escape sits, or `null` when nothing is* dismissed. Live, so it follows edits and lands in the graveyard if the marker is deleted.@@ -121,6 +123,10 @@ export default class TriliumMentionUI extends Plugin {return this._balloon?.visibleView === this._view;}+ private _isCurrentRequest(requestId: number) {+ return this._requestId === requestId;+ }+/*** Returns whether the key was consumed. Commit keys are deliberately *not* consumed when nothing* is selected, so that in the attribute editor — where `preselectFirstItem` is off — Enter still@@ -250,12 +256,12 @@ export default class TriliumMentionUI extends Plugin {}});- this._lastRequestedQuery = query;+ const requestId = ++this._requestId;clearTimeout(this._feedTimer);- this._feedTimer = setTimeout(() => void this._requestFeed(feed, query), FEED_DEBOUNCE_MS);+ this._feedTimer = setTimeout(() => void this._requestFeed(feed, query, requestId), FEED_DEBOUNCE_MS);}- private async _requestFeed(feed: TriliumMentionFeed, query: string) {+ private async _requestFeed(feed: TriliumMentionFeed, query: string, requestId: number) {let items: Array<MentionFeedObjectItem | string>;try {@@ -263,13 +269,21 @@ export default class TriliumMentionUI extends Plugin {? await feed.feed.call(this.editor, query): feed.feed.filter((item) => String(typeof item === "object" ? item.id : item).toLowerCase().includes(query.toLowerCase()));} catch {- this._hide();+ // Only the request still in flight may act on a failure. Debouncing bounds how many+ // requests are *started*, not how many are outstanding, so an earlier one rejecting+ // must not tear down the panel a later one has since populated.+ if (this._isCurrentRequest(requestId)) {+ this._hide();+ }return;}// Drop out-of-order responses, and responses that arrived after the panel was dismissed or- // the marker went away.- if (this._lastRequestedQuery !== query || !this.editor.model.markers.has(MARKER_NAME)) {+ // the marker went away. Correlating on the request rather than the query text matters when+ // the same text is retyped, or typed under a different marker: `#al` and `~al` produce equal+ // queries but different feeds, and the stale one would otherwise fill the panel with the+ // wrong suggestions.+ if (!this._isCurrentRequest(requestId) || !this.editor.model.markers.has(MARKER_NAME)) {return;}