Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(editor): open mention and slash pickers only for typed triggers (MUL-5429) (#6072)
Naiyuan Qingba17fcf46a09
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.tsindex 4f5adb4a72..7f7699209c 100644--- a/packages/views/editor/extensions/index.ts+++ b/packages/views/editor/extensions/index.ts@@ -45,6 +45,7 @@ import {} from "./issue-identifier-autolink";import { SlashCommandExtension } from "./slash-command-extension";import { createSlashCommandSuggestion, createBuiltinCommandSuggestion } from "./slash-command-suggestion";+import { SuggestionTriggerArmingExtension } from "./suggestion-trigger-arming";import { CodeBlockView } from "./code-block-view";import { PatchedListItem, PatchedTaskItem } from "./list-item";import { createMarkdownPasteExtension } from "./markdown-paste";@@ -241,6 +242,9 @@ export function createEditorExtensions(// so users can copy rich content out as the original Markdown.createMarkdownCopyExtension(),FileCardExtension,+ // Must precede the mention and slash pickers: it supplies the "the user+ // typed this trigger" signal their `shouldShow` reads (MUL-5429).+ SuggestionTriggerArmingExtension,BaseMentionExtension.configure({HTMLAttributes: { class: "mention" },...(options.disableMentionsdiff --git a/packages/views/editor/extensions/issue-identifier-autolink.test.ts b/packages/views/editor/extensions/issue-identifier-autolink.test.tsindex 3fba4ff4f6..e8f9aa916a 100644--- a/packages/views/editor/extensions/issue-identifier-autolink.test.ts+++ b/packages/views/editor/extensions/issue-identifier-autolink.test.ts@@ -3,8 +3,10 @@ import { Editor } from "@tiptap/core";import StarterKit from "@tiptap/starter-kit";import Link from "@tiptap/extension-link";import { Markdown } from "@tiptap/markdown";+import { EditorView } from "@tiptap/pm/view";import type { RefObject } from "react";import { BaseMentionExtension } from "./mention-extension";+import { createMarkdownPasteExtension } from "./markdown-paste";import {createIssueIdentifierAutolinkExtension,type IssueIdentifierResolver,@@ -48,6 +50,12 @@ function makeEditor(): Editor {TestMention,createIssueIdentifierAutolinkExtension({ resolveRef }),Markdown.configure({ indentation: { style: "space", size: 3 } }),+ // The extension the real editor pastes through. It is a catch-all+ // `handlePaste` that dispatches its own transaction, so it — not+ // ProseMirror — decides whether this extension can tell a paste from+ // typing. Leaving it out is what let the paste cases below pass against a+ // hand-stamped meta the product never produced (MUL-5429).+ createMarkdownPasteExtension(),],});}@@ -57,6 +65,19 @@ function flush(): Promise<void> {return new Promise((r) => setTimeout(r, 0));}+/** Fire a real paste event, so the whole handlePaste chain runs. */+function paste(ed: Editor, text: string): void {+ ed.commands.focus("start");+ const event = new Event("paste", { bubbles: false, cancelable: true });+ Object.defineProperty(event, "clipboardData", {+ value: {+ files: [],+ getData: (type: string) => (type === "text/plain" ? text : ""),+ },+ });+ ed.view.dom.dispatchEvent(event);+}+/** Simulate user typing `text` at position 1 (empty paragraph start). */function typeAt1(ed: Editor, text: string): void {const tr = ed.state.tr.insertText(text, 1);@@ -65,6 +86,10 @@ function typeAt1(ed: Editor, text: string): void {beforeEach(() => {resolveMock.mockReset();+ // jsdom has no layout; ProseMirror's post-dispatch scroll needs client rects.+ (EditorView.prototype as unknown as { scrollToSelection: () => void }).scrollToSelection =+ () => {};+ Element.prototype.scrollIntoView = () => {};});afterEach(() => {@@ -106,9 +131,7 @@ describe("createIssueIdentifierAutolinkExtension", () => {resolveMock.mockResolvedValue({ id: "uuid-2", identifier: "MUL-2" });editor = makeEditor();- const tr = editor.state.tr.insertText("See MUL-2 now", 1);- tr.setMeta("paste", true);- editor.view.dispatch(tr);+ paste(editor, "See MUL-2 now");await flush();expect(resolveMock).toHaveBeenCalledWith("MUL-2");@@ -208,9 +231,7 @@ describe("createIssueIdentifierAutolinkExtension", () => {await flush();// Paste two identifiers at the very start of the doc.- const tr = editor.state.tr.insertText("MUL-2 plus MUL-3 x ", 1);- tr.setMeta("paste", true);- editor.view.dispatch(tr);+ paste(editor, "MUL-2 plus MUL-3 x ");await flush();const md = editor.getMarkdown();diff --git a/packages/views/editor/extensions/markdown-paste.ts b/packages/views/editor/extensions/markdown-paste.tsindex 2b188a770b..feada75da9 100644--- a/packages/views/editor/extensions/markdown-paste.ts+++ b/packages/views/editor/extensions/markdown-paste.ts@@ -26,7 +26,8 @@* enough by themselves, because those should still paste as Markdown source.*/import { Extension } from "@tiptap/core";-import { Plugin, PluginKey } from "@tiptap/pm/state";+import { Plugin, PluginKey, type Transaction } from "@tiptap/pm/state";+import type { EditorView } from "@tiptap/pm/view";import {Fragment,Slice,@@ -407,6 +408,26 @@ function repairFragmentedOrderedLists(slice: Slice): Slice {return new Slice(content, slice.openStart, slice.openEnd);}+/**+ * Marks a transaction as the commit of a paste, the way ProseMirror marks its+ * own.+ *+ * `doPaste` stamps `paste` / `uiEvent` on the transaction it dispatches, but it+ * returns early once a `handlePaste` prop claims the event — and this extension+ * is a catch-all that claims nearly every paste. Anything downstream that asks+ * "did this text arrive by paste?" therefore sees an unmarked transaction and+ * treats a paste as typing. `issueIdentifierAutolink` reads exactly that, and+ * without the mark it only ever inspects the token before the caret, so pasting+ * `See MUL-2 now` autolinks nothing (MUL-5429).+ *+ * ProseMirror's author describes these metas as the contract third-party code+ * relies on to tell user events apart, so any custom `handlePaste` that+ * dispatches its own transaction owes them.+ */+function dispatchPaste(view: EditorView, tr: Transaction): void {+ view.dispatch(tr.setMeta("paste", true).setMeta("uiEvent", "paste"));+}+export function createMarkdownPasteExtension() {return Extension.create({name: "markdownPaste",@@ -438,12 +459,10 @@ export function createMarkdownPasteExtension() {if (html && !html.includes("data-pm-slice")) {const repaired = repairFragmentedOrderedLists(slice);if (repaired !== slice) {- const tr = view.state.tr- .replaceSelection(repaired)- .scrollIntoView()- .setMeta("paste", true)- .setMeta("uiEvent", "paste");- view.dispatch(tr);+ dispatchPaste(+ view,+ view.state.tr.replaceSelection(repaired).scrollIntoView(),+ );return true;}}@@ -451,7 +470,7 @@ export function createMarkdownPasteExtension() {}if (mode === "literal") {- view.dispatch(view.state.tr.insertText(text));+ dispatchPaste(view, view.state.tr.insertText(text));return true;}@@ -470,13 +489,12 @@ export function createMarkdownPasteExtension() {first?.type.name === "paragraph" &&first.content.size === 0);if (text.trim() && parsedEmpty) {- view.dispatch(view.state.tr.insertText(text));+ dispatchPaste(view, view.state.tr.insertText(text));return true;}const parsedSlice = Slice.maxOpen(node.content);- const tr = view.state.tr.replaceSelection(parsedSlice);- view.dispatch(tr);+ dispatchPaste(view, view.state.tr.replaceSelection(parsedSlice));return true;},},diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsxindex 4bf8d24a9d..9320ebdfca 100644--- a/packages/views/editor/extensions/mention-suggestion.tsx+++ b/packages/views/editor/extensions/mention-suggestion.tsx@@ -43,6 +43,7 @@ import {} from "./mention-recency";import { matchesPinyin } from "./pinyin-match";import { createSuggestionPopupRender, isPickerAcceptKey } from "./suggestion-popup";+import { isTriggerArmedAt } from "./suggestion-trigger-arming";// ---------------------------------------------------------------------------// Types@@ -617,6 +618,10 @@ export function createMentionSuggestion(return {pluginKey,allowSpaces: true,+ // Only open over an `@` the user actually typed. Tiptap matches on document+ // content alone, so without this a pasted, dropped, undone or server-loaded+ // `@` opens the picker just as readily (MUL-5429).+ shouldShow: ({ editor, range }) => isTriggerArmedAt(editor, range.from),items: ({ query }) => {if (options.mode === "context") {const normalizedQuery = query.trim();diff --git a/packages/views/editor/extensions/slash-command-suggestion.tsx b/packages/views/editor/extensions/slash-command-suggestion.tsxindex 6d13ed993d..4627651b40 100644--- a/packages/views/editor/extensions/slash-command-suggestion.tsx+++ b/packages/views/editor/extensions/slash-command-suggestion.tsx@@ -20,6 +20,7 @@ import { workspaceKeys } from "@multica/core/workspace/queries";import type { Agent, MemberWithUser } from "@multica/core/types";import { useT } from "../../i18n";import { createSuggestionPopupRender, isPickerAcceptKey } from "./suggestion-popup";+import { isTriggerArmedAt } from "./suggestion-trigger-arming";const MAX_ITEMS = 20;@@ -202,6 +203,9 @@ export function createSlashCommandSuggestion(qc: QueryClient): Omit<return {char: "/",pluginKey,+ // Only open over a `/` the user actually typed, so a pasted path+ // (`/usr/local/bin`) never opens the skill picker (MUL-5429).+ shouldShow: ({ editor, range }) => isTriggerArmedAt(editor, range.from),items: ({ query }) => buildItems(qc, query),command: ({ editor, range, props }) => {const nodeAfter = editor.view.state.selection.$to.nodeAfter;@@ -273,6 +277,9 @@ export function createBuiltinCommandSuggestion(): Omit<return {char: "/",pluginKey,+ // Only open over a `/` the user actually typed, so a pasted path+ // (`/usr/local/bin`) never opens the command menu (MUL-5429).+ shouldShow: ({ editor, range }) => isTriggerArmedAt(editor, range.from),items: ({ query }) => buildBuiltinCommandItems(query),command: ({ editor, range, props }) => {// Insert the plain-text prefix (e.g. "/note ") rather than a rich node,diff --git a/packages/views/editor/extensions/suggestion-popup.test.tsx b/packages/views/editor/extensions/suggestion-popup.test.tsxindex 4ceb3bac0f..a2224c8163 100644--- a/packages/views/editor/extensions/suggestion-popup.test.tsx+++ b/packages/views/editor/extensions/suggestion-popup.test.tsx@@ -4,7 +4,7 @@ import StarterKit from "@tiptap/starter-kit";import { Suggestion, type SuggestionProps } from "@tiptap/suggestion";import { PluginKey } from "@tiptap/pm/state";import { forwardRef, useImperativeHandle } from "react";-import { afterEach, beforeAll, describe, expect, it } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";import { createSuggestionPopupRender, isPickerAcceptKey } from "./suggestion-popup";import { PatchedListItem } from "./list-item";@@ -216,6 +216,61 @@ describe("createSuggestionPopupRender", () => {);});+// ---------------------------------------------------------------------------+// Escape containment (MUL-5429): Escape while a picker is open must close ONLY+// the picker. ProseMirror calls preventDefault() for a handled key but never+// stops propagation, and Base UI's dismiss layer listens for Escape on+// `document` in the BUBBLE phase without consulting defaultPrevented — so+// without an explicit stopPropagation the same keypress also closed the host+// create-issue dialog and threw the draft away. The plain document listener+// below stands in for that dismiss layer.+// ---------------------------------------------------------------------------++describe("Escape containment while a picker is open", () => {+ function watchHostEscape() {+ const hostEscape = vi.fn();+ document.addEventListener("keydown", hostEscape);+ return {+ hostEscape,+ stop: () => document.removeEventListener("keydown", hostEscape),+ };+ }++ it.each(["@", "/"] as const)(+ "closes the %s popup on Escape without letting the key reach the host dialog",+ async (char) => {+ const ed = makeEditor(char);+ await triggerSuggestion(ed, `${char}a`);+ const { hostEscape, stop } = watchHostEscape();++ await act(async () => {+ fireEvent.keyDown(ed.view.dom, { key: "Escape" });+ });+ stop();++ await expectPopupClosed();+ expect(hostEscape).not.toHaveBeenCalled();+ },+ );++ it("still lets Escape reach the host when no picker is open", async () => {+ const ed = makeEditor("@");+ await act(async () => {+ ed.commands.focus("end");+ });+ const { hostEscape, stop } = watchHostEscape();++ await act(async () => {+ fireEvent.keyDown(ed.view.dom, { key: "Escape" });+ });+ stop();++ // With no picker open Escape is the host dialog's own close shortcut and+ // must keep working — the fix must not swallow Escape unconditionally.+ expect(hostEscape).toHaveBeenCalledTimes(1);+ });+});+// ---------------------------------------------------------------------------// isPickerAcceptKey — the shared accept-key policy (MUL-3685)// ---------------------------------------------------------------------------diff --git a/packages/views/editor/extensions/suggestion-popup.tsx b/packages/views/editor/extensions/suggestion-popup.tsxindex 0559e037eb..d24d320be9 100644--- a/packages/views/editor/extensions/suggestion-popup.tsx+++ b/packages/views/editor/extensions/suggestion-popup.tsx@@ -216,7 +216,19 @@ export function createSuggestionPopupRender<},onKeyDown: (props: SuggestionKeyDownProps) => {- if (props.event.key === "Escape") {+ // `Esc` is the legacy alias the suggestion plugin also matches on.+ if (props.event.key === "Escape" || props.event.key === "Esc") {+ // Escape while a picker is open must close ONLY the picker. Returning+ // true makes ProseMirror call preventDefault(), but ProseMirror never+ // stops propagation, and Base UI's dismiss layer listens for Escape on+ // `document` in the bubble phase without consulting defaultPrevented.+ // Without stopPropagation the same keypress that closes this popup+ // also closes the host Dialog and discards the draft (MUL-5429).+ // This handler is the only layer that knows a picker is open, so+ // stopping here fixes every host at once (create-issue dialog, chat+ // input, comment composer).+ props.event.preventDefault();+ props.event.stopPropagation();cleanup();return true;}diff --git a/packages/views/editor/extensions/suggestion-trigger-arming.test.ts b/packages/views/editor/extensions/suggestion-trigger-arming.test.tsnew file mode 100644index 0000000000..16f44100f8--- /dev/null+++ b/packages/views/editor/extensions/suggestion-trigger-arming.test.ts@@ -0,0 +1,241 @@+import { describe, it, expect, beforeAll } from "vitest";+import { Editor, Extension } from "@tiptap/core";+import StarterKit from "@tiptap/starter-kit";+import { Markdown } from "@tiptap/markdown";+import { Suggestion } from "@tiptap/suggestion";+import { PluginKey, TextSelection } from "@tiptap/pm/state";+import { EditorView } from "@tiptap/pm/view";+import { createMarkdownPasteExtension } from "./markdown-paste";+import {+ SuggestionTriggerArmingExtension,+ isTriggerArmedAt,+} from "./suggestion-trigger-arming";++// ---------------------------------------------------------------------------+// MUL-5429. These drive the REAL pipeline end to end — a `paste` event on the+// editor DOM, and typing routed through `handleTextInput` exactly the way+// prosemirror-view's readDOMChange does it. That matters: the previous attempt+// at this fix passed its tests by hand-building transactions carrying a+// `uiEvent: "paste"` meta, which the real paste path never produces, because+// markdownPaste's catch-all `handlePaste` returns true and so short-circuits+// `doPaste` before ProseMirror stamps that meta. Anything that stubs the+// transaction instead of the event can be green while the product is broken.+// ---------------------------------------------------------------------------++const key = new PluginKey("test-mention-suggestion");+const slashKey = new PluginKey("test-slash-suggestion");++function suggestionProbe(name: string, char: "@" | "/", pluginKey: PluginKey) {+ return Extension.create({+ name,+ addProseMirrorPlugins() {+ return [+ Suggestion({+ editor: this.editor,+ char,+ pluginKey,+ // The mention picker's real config; `allowSpaces` is what lets a+ // single stray `@` swallow the rest of the line.+ allowSpaces: char === "@",+ shouldShow: ({ editor, range }) => isTriggerArmedAt(editor, range.from),+ items: () => [{ id: "1", label: "Alice" }],+ render: () => ({}),+ }),+ ];+ },+ });+}++function makeEditor(content?: object) {+ const element = document.createElement("div");+ document.body.appendChild(element);+ return new Editor({+ element,+ extensions: [+ StarterKit,+ Markdown,+ createMarkdownPasteExtension(),+ SuggestionTriggerArmingExtension,+ suggestionProbe("mentionProbe", "@", key),+ suggestionProbe("slashProbe", "/", slashKey),+ ],+ content: content ?? { type: "doc", content: [{ type: "paragraph" }] },+ });+}++/** Fires a real `paste` event, so the whole handlePaste chain runs. */+function paste(editor: Editor, text: string, html = ""): void {+ const event = new Event("paste", { bubbles: false, cancelable: true });+ Object.defineProperty(event, "clipboardData", {+ value: {+ files: [],+ getData: (type: string) =>+ type === "text/plain" ? text : type === "text/html" ? html : "",+ },+ });+ editor.view.dom.dispatchEvent(event);+}++/**+ * Types text the way ProseMirror does: `readDOMChange` consults+ * `handleTextInput` and, when no plugin claims the keystroke, dispatches the+ * insertion itself. Going through the prop is the point — that is the only+ * signal that separates typing from pasting.+ */+function type(editor: Editor, text: string): void {+ for (const ch of text) {+ const { from, to } = editor.state.selection;+ const handled = editor.view.someProp("handleTextInput", (fn) =>+ fn(editor.view, from, to, ch, () => editor.state.tr.insertText(ch, from, to)),+ );+ if (!handled) editor.view.dispatch(editor.state.tr.insertText(ch, from, to));+ }+}++function picker(editor: Editor, pluginKey: PluginKey = key) {+ const state = pluginKey.getState(editor.state);+ return { active: state?.active, query: state?.query };+}++beforeAll(() => {+ // jsdom has no layout, so ProseMirror's post-dispatch scroll walks+ // coordsAtPos into getClientRects() on nodes jsdom does not implement.+ // Scrolling is irrelevant here; these tests read plugin state.+ (EditorView.prototype as unknown as { scrollToSelection: () => void }).scrollToSelection =+ () => {};+ Element.prototype.scrollIntoView = () => {};+});++describe("suggestion trigger arming", () => {+ describe("text the user did not type never opens a picker", () => {+ it("pasted text containing @", () => {+ const editor = makeEditor();+ editor.commands.focus("end");++ paste(editor, "npx @aiforui/install --token=abc");++ expect(editor.getText()).toContain("@aiforui/install");+ expect(picker(editor).active).toBe(false);+ });++ it("pasted text containing a / path", () => {+ const editor = makeEditor();+ editor.commands.focus("end");++ paste(editor, "binary lives in /usr/local/bin");++ expect(picker(editor, slashKey).active).toBe(false);+ });++ it("stays shut across the transactions that follow the paste", () => {+ const editor = makeEditor();+ editor.commands.focus("end");+ paste(editor, "npx @aiforui/install");++ // A bare selection change. Under the previous fix this single extra+ // transaction was enough to re-open the picker: the paste meta was gone,+ // and `shouldShow` cannot see that the picker was closed a moment ago.+ editor.view.dispatch(+ editor.state.tr.setSelection(+ TextSelection.create(editor.state.doc, editor.state.doc.content.size - 1),+ ),+ );++ expect(picker(editor).active).toBe(false);+ });++ it("stays shut when the user keeps typing after the pasted @", () => {+ const editor = makeEditor();+ editor.commands.focus("end");+ paste(editor, "npx @aiforui");++ type(editor, "x");++ expect(picker(editor).active).toBe(false);+ });++ it("text already in the document when the editor mounts", () => {+ // No paste at all — a loaded draft, an undo, a collaborative edit. Tiptap+ // matches on document content alone, so this opened the picker too.+ const editor = makeEditor({+ type: "doc",+ content: [+ { type: "paragraph", content: [{ type: "text", text: "npx @aiforui/install" }] },+ ],+ });++ editor.commands.focus("end");++ expect(picker(editor).active).toBe(false);+ });+ });++ describe("typing still works exactly as before", () => {+ it("typing @ opens the mention picker", () => {+ const editor = makeEditor();+ editor.commands.focus("end");++ type(editor, "hi @al");++ expect(picker(editor)).toEqual({ active: true, query: "al" });+ });++ it("typing / opens the slash picker", () => {+ const editor = makeEditor();+ editor.commands.focus("end");++ type(editor, "/shi");++ expect(picker(editor, slashKey)).toEqual({ active: true, query: "shi" });+ });++ it("keeps multi-word queries alive, so allowSpaces issue search survives", () => {+ const editor = makeEditor();+ editor.commands.focus("end");++ type(editor, "@login redirect bug");++ expect(picker(editor)).toEqual({ active: true, query: "login redirect bug" });+ });++ it("pasting into a query the user opened by typing keeps it open", () => {+ // Arming is about the trigger character, not about every later edit —+ // pasting a name into a mention you deliberately started is still a+ // mention.+ const editor = makeEditor();+ editor.commands.focus("end");+ type(editor, "@");++ paste(editor, "alice");++ expect(picker(editor)).toEqual({ active: true, query: "alice" });+ });+ });++ describe("disarming", () => {+ it("deleting the typed @ disarms it", () => {+ const editor = makeEditor();+ editor.commands.focus("end");+ type(editor, "@al");++ editor.commands.deleteRange({ from: 1, to: 4 });+ type(editor, "x");++ expect(picker(editor).active).toBe(false);+ });++ it("moving the caret away and back does not re-open the picker", () => {+ // ueberdosis/tiptap#7371: after leaving a half-typed mention, arrowing+ // back onto it re-opened the menu. A deliberate caret move disarms.+ const editor = makeEditor();+ editor.commands.focus("end");+ type(editor, "@al");+ expect(picker(editor).active).toBe(true);++ editor.commands.setTextSelection(1);+ editor.commands.setTextSelection(editor.state.doc.content.size - 1);++ expect(picker(editor).active).toBe(false);+ });+ });+});diff --git a/packages/views/editor/extensions/suggestion-trigger-arming.ts b/packages/views/editor/extensions/suggestion-trigger-arming.tsnew file mode 100644index 0000000000..a14d161183--- /dev/null+++ b/packages/views/editor/extensions/suggestion-trigger-arming.ts@@ -0,0 +1,142 @@+import { Extension, type Editor } from "@tiptap/core";+import { Plugin, PluginKey } from "@tiptap/pm/state";+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";++/**+ * Records that the user *typed* a suggestion trigger character, so a picker can+ * refuse to open over a `@` or `/` that merely happens to sit in the document.+ *+ * ## Why this exists+ *+ * Tiptap's Suggestion plugin is state-derived, not event-driven: it re-runs+ * `findSuggestionMatch` on EVERY transaction and asks "does the text before the+ * cursor look like a trigger?" — never "did the user just type one?". Pasted,+ * dropped, undone and server-loaded text produce a document identical to typed+ * text, so the plugin cannot tell them apart. With `allowSpaces` the match then+ * runs from the `@` to the end of the line, so pasting `npx @scope/pkg --token=…`+ * opens an empty picker that swallows Enter (MUL-5429).+ *+ * That is upstream's known, unfixed design: ueberdosis/tiptap#4183 ("Suggestion+ * opens even if current user didn't type the trigger", open since 2023, labelled+ * `complexity: hard`) and #7371 ("Suggestion should only start when user+ * explicitly types suggestion char"). Upstream's answer was to expose+ * `shouldShow` and let applications supply the missing provenance themselves —+ * but `shouldShow` receives the transaction without `prev.active`, while `allow`+ * receives `prev.active` without the transaction, so no transaction-inspecting+ * predicate can express "only on the transaction that opened it". Provenance has+ * to come from outside the transaction stream.+ *+ * ## How it works+ *+ * `handleTextInput` is the one ProseMirror hook that fires for real keyboard and+ * IME input only — paste goes through `handlePaste`/`doPaste` and drop through+ * `handleDrop`, neither of which reaches it. This is the same signal Tiptap's own+ * InputRules run on, which is why typing `- ` makes a list but pasting it does+ * not. Suggestion is the one Tiptap feature that does not use it; this plugin+ * supplies it.+ *+ * Typing a trigger character arms its document position. The pickers' `shouldShow`+ * then opens only for a match anchored at the armed position. Anything the user+ * did not type is never armed, so it never opens a picker.+ */++/** Trigger characters any suggestion in this editor listens for. */+const TRIGGER_CHARS = new Set(["@", "/"]);++/**+ * Latest armed position per editor.+ *+ * `shouldShow` runs inside the Suggestion plugin's `apply`, where `editor.state`+ * is still the PREVIOUS state — so the armed position for the transaction being+ * applied is not yet readable through a PluginKey. This map mirrors it as the+ * arming plugin's `apply` computes it. Extension priority (below) puts that+ * `apply` ahead of every suggestion plugin, so the mirror is always current by+ * the time `shouldShow` reads it.+ */+const armedPositions = new WeakMap<Editor, number | null>();++/** True when `from` is where the user typed a trigger character. */+export function isTriggerArmedAt(editor: Editor, from: number): boolean {+ const armed = armedPositions.get(editor);+ return armed !== null && armed !== undefined && armed === from;+}++/** Offset of the last trigger character in typed text, or -1. */+function lastTriggerIndex(text: string): number {+ for (let i = text.length - 1; i >= 0; i--) {+ if (TRIGGER_CHARS.has(text[i]!)) return i;+ }+ return -1;+}++/** True when the armed position still holds its trigger character. */+function stillHoldsTrigger(doc: ProseMirrorNode, pos: number): boolean {+ if (pos < 0 || pos + 1 > doc.content.size) return false;+ return TRIGGER_CHARS.has(doc.textBetween(pos, pos + 1));+}++export const SuggestionTriggerArmingExtension = Extension.create({+ name: "suggestionTriggerArming",+ // Ahead of every suggestion plugin so both `handleTextInput` (which must see+ // the keystroke before an input rule can consume it) and `apply` (which must+ // refresh the mirror before `shouldShow` reads it) run first.+ priority: 1000,++ addProseMirrorPlugins() {+ const editor = this.editor;+ // Set by `handleTextInput` just before ProseMirror dispatches the insertion,+ // consumed by the very next `apply`. Holds a position in the NEW document:+ // text typed at `from` puts its i-th character at `from + i`.+ let pendingArm: number | null = null;++ return [+ new Plugin<number | null>({+ key: new PluginKey("suggestionTriggerArming"),++ state: {+ init() {+ armedPositions.set(editor, null);+ return null;+ },++ apply(tr, prev, _oldState, newState) {+ const next = ((): number | null => {+ // A trigger character was just typed — arm it unconditionally.+ if (pendingArm !== null) return pendingArm;+ if (prev === null) return null;++ // A deliberate caret move (click, arrow key) abandons the trigger.+ // Typing never sets the selection explicitly, so it survives.+ // IME excluded: composition dispatches selection transactions of+ // its own mid-word.+ if (tr.selectionSet && !tr.docChanged && !editor.view.composing) {+ return null;+ }++ const mapped = tr.docChanged ? tr.mapping.map(prev, -1) : prev;+ if (!stillHoldsTrigger(newState.doc, mapped)) return null;+ // Cursor no longer sits after the trigger inside the same query.+ if (!newState.selection.empty || newState.selection.from <= mapped) {+ return null;+ }+ return mapped;+ })();++ pendingArm = null;+ armedPositions.set(editor, next);+ return next;+ },+ },++ props: {+ handleTextInput(_view, from, _to, text) {+ const index = lastTriggerIndex(text);+ if (index !== -1) pendingArm = from + index;+ // Never handle the input — every other plugin must still see it.+ return false;+ },+ },+ }),+ ];+ },+});