From e43639cd9b099783c4fcfb0211bb42832e577a18 Mon Sep 17 00:00:00 2001 From: Rohan Chakraborty Date: Wed, 4 Nov 2026 10:52:34 +0530 Subject: [PATCH 1/2] refactor: [prompt-input, editor] use the editor core in prompt input Split EditorStore into a core store and RichEditorStore. The core store has the state, view, history, suggestion menus, mention chips, and placeholder. RichEditorStore adds formatting, lists, input rules, the clipboard, the actionsRef API, and the toolbar and link registries. Only Editor creates it. PromptInput.Editor creates a core store with its own schema and plugins, and renders through EditorHost and MentionsMenu. This removes the composer hook, schema, and markup code that copied the editor logic. A bundle test checks that a PromptInput-only bundle leaves out the rich editor modules. PromptInput.Editor no longer sets aria-expanded, which role="textbox" does not allow. --- .../editor/__tests__/bundle.test.ts | 21 + .../components/editor/core/composer/markup.ts | 241 -------- .../components/editor/core/composer/schema.ts | 25 - .../core/composer/use-composer-editor.ts | 399 ------------- .../editor/core/editor-core.module.css | 17 - .../react/components/editor/core/keymaps.ts | 36 +- .../editor/core/mention-registry.ts | 3 +- .../react/components/editor/core/nodes.ts | 6 +- .../editor/core/suggestion-plugin.ts | 22 +- .../editor/core/use-suggestion-menu.ts | 3 +- .../components/editor/editor-content.tsx | 34 +- .../react/components/editor/editor-context.ts | 13 +- .../components/editor/editor-mentions.tsx | 94 ++- .../components/editor/editor-rich-store.ts | 493 ++++++++++++++++ .../react/components/editor/editor-root.tsx | 6 +- .../react/components/editor/editor-store.ts | 550 ++++-------------- .../__tests__/prompt-input-markup.test.ts | 38 +- .../__tests__/prompt-input-mentions.test.tsx | 3 +- .../prompt-input/prompt-input-editor.tsx | 256 ++++---- .../prompt-input/prompt-input-markup.ts | 147 +++++ .../prompt-input/prompt-input-plugins.ts | 115 ++++ .../prompt-input/prompt-input.module.css | 19 +- .../prompt-input/use-mention-menu.ts | 81 --- 23 files changed, 1159 insertions(+), 1463 deletions(-) delete mode 100644 packages/react/components/editor/core/composer/markup.ts delete mode 100644 packages/react/components/editor/core/composer/schema.ts delete mode 100644 packages/react/components/editor/core/composer/use-composer-editor.ts create mode 100644 packages/react/components/editor/editor-rich-store.ts create mode 100644 packages/react/components/prompt-input/prompt-input-markup.ts create mode 100644 packages/react/components/prompt-input/prompt-input-plugins.ts delete mode 100644 packages/react/components/prompt-input/use-mention-menu.ts diff --git a/packages/react/components/editor/__tests__/bundle.test.ts b/packages/react/components/editor/__tests__/bundle.test.ts index 441cb0b71..fdbc9b37f 100644 --- a/packages/react/components/editor/__tests__/bundle.test.ts +++ b/packages/react/components/editor/__tests__/bundle.test.ts @@ -94,3 +94,24 @@ describe('Markdown bundle cost', () => { expect(withAdapter).toMatch(/from ['"]marked['"]/); }, 180_000); }); + +/* PromptInput runs on the core store, so it must not ship the rich editor. */ + +describe('PromptInput bundle cost', () => { + it('leaves out the rich editor features', async () => { + const promptInput = await bundle( + `import { PromptInput } from ${JSON.stringify(PACKAGE_INDEX)};\n` + + 'export const input = PromptInput;\n' + ); + expect(promptInput).toContain('PromptInput.Editor'); + for (const name of [ + 'prosemirror-schema-list', + 'prosemirror-inputrules', + 'prosemirror-dropcursor', + 'prosemirror-gapcursor' + ]) { + expect(promptInput).not.toMatch(new RegExp(`from ['"]${name}['"]`)); + } + expect(promptInput).not.toContain('class RichEditorStore'); + }, 180_000); +}); diff --git a/packages/react/components/editor/core/composer/markup.ts b/packages/react/components/editor/core/composer/markup.ts deleted file mode 100644 index 42a493240..000000000 --- a/packages/react/components/editor/core/composer/markup.ts +++ /dev/null @@ -1,241 +0,0 @@ -import { Fragment, type Node as PMNode, Slice } from 'prosemirror-model'; -import { - type EditorMention, - isTriggerCharacter, - type MentionAttrs, - mentionText, - readMention, - serializeMention -} from '../mention'; -import { - composerSchema, - hardBreakType, - mentionType, - paragraphType -} from './schema'; - -export interface EditorDocDetails { - /** Round-trippable markup, as in `"check @[DataTable](component:data-table)"`. */ - markup: string; - /** Plain text with each label inlined behind its trigger. */ - text: string; - /** Document order; duplicates preserved. */ - mentions: EditorMention[]; - /** No mentions, and text that trims to `""`. */ - empty: boolean; -} - -/** Inline content for a plain string, where newlines become hard breaks. */ -export function inlineFragmentFromText(text: string): Fragment { - const nodes: PMNode[] = []; - const lines = text.split('\n'); - lines.forEach((line, index) => { - if (index > 0) nodes.push(hardBreakType.create()); - if (line) nodes.push(composerSchema.text(line)); - }); - return Fragment.fromArray(nodes); -} - -/** - * Parses the markup dialect into a document. Called only for `value` / - * `defaultValue`, never for typed or pasted input, so ordinary prose that - * happens to contain `@[…](…)` stays literal while it is being written. - */ -export function docFromMarkup(markup: string): PMNode { - const nodes: PMNode[] = []; - let literal = ''; - let index = 0; - - const flush = () => { - if (!literal) return; - nodes.push(composerSchema.text(literal)); - literal = ''; - }; - - while (index < markup.length) { - const char = markup[index]; - - if (char === '\n') { - flush(); - nodes.push(hardBreakType.create()); - index += 1; - continue; - } - - if (markup[index + 1] === '[' && isTriggerCharacter(char)) { - const match = readMention(markup, index); - if (match) { - flush(); - nodes.push(mentionType.create(match.attrs)); - index = match.next; - continue; - } - } - - literal += char; - index += 1; - } - flush(); - - return composerSchema.topNodeType.create( - null, - paragraphType.create(null, Fragment.fromArray(nodes)) - ); -} - -/** A document holding a plain string, with no markup interpretation at all. */ -export function docFromText(text: string): PMNode { - return composerSchema.topNodeType.create( - null, - paragraphType.create(null, inlineFragmentFromText(text)) - ); -} - -/** Everything the host needs from a document, in one walk. */ -export function deriveDocDetails(doc: PMNode): EditorDocDetails { - let markup = ''; - let text = ''; - const mentions: EditorMention[] = []; - - doc.descendants(node => { - if (node.type === mentionType) { - const attrs = node.attrs as MentionAttrs; - const label = mentionText(attrs); - mentions.push({ - ...attrs, - start: text.length, - end: text.length + label.length - }); - markup += serializeMention(attrs); - text += label; - return false; - } - if (node.type === hardBreakType) { - markup += '\n'; - text += '\n'; - return false; - } - if (node.isText) { - markup += node.text ?? ''; - text += node.text ?? ''; - return false; - } - return true; - }); - - return { - markup, - text, - mentions, - empty: mentions.length === 0 && text.trim() === '' - }; -} - -/** The `text/plain` clipboard flavour for a copied range. */ -export function textFromFragment(fragment: Fragment): string { - let text = ''; - const walk = (content: Fragment) => { - content.forEach(node => { - if (node.type === mentionType) { - const attrs = node.attrs as MentionAttrs; - text += mentionText(attrs); - return; - } - if (node.type === hardBreakType) { - text += '\n'; - return; - } - if (node.isText) { - text += node.text ?? ''; - return; - } - if (node.isBlock && text) text += '\n'; - walk(node.content); - }); - }; - walk(fragment); - return text; -} - -export function serializeMarkup(doc: PMNode): string { - return deriveDocDetails(doc).markup; -} - -export function serializeText(doc: PMNode): string { - return deriveDocDetails(doc).text; -} - -/** - * The length of the derived text, without building it. Read on every - * transaction by the `maxLength` filter, which only ever wanted the number. - */ -export function textLength(doc: PMNode): number { - let length = 0; - doc.descendants(node => { - if (node.type === mentionType) { - const attrs = node.attrs as MentionAttrs; - length += attrs.trigger.length + attrs.label.length; - return false; - } - if (node.type === hardBreakType) { - length += 1; - return false; - } - if (node.isText) { - length += node.text?.length ?? 0; - return false; - } - return true; - }); - return length; -} - -/** - * The emptiness predicate, without building the markup and the mention list - * `deriveDocDetails` would. Read by the placeholder decoration on every state - * change, so it walks only as far as the first piece of content. - * - * Equivalent to `deriveDocDetails(doc).empty`: the concatenated text trims to - * `""` exactly when every text node does, and a hard break contributes only a - * newline. - */ -export function isDocEmpty(doc: PMNode): boolean { - let empty = true; - doc.descendants(node => { - if (!empty) return false; - if (node.type === mentionType) { - empty = false; - return false; - } - if (node.type === hardBreakType) return false; - if (node.isText) { - if ((node.text ?? '').trim() !== '') empty = false; - return false; - } - return true; - }); - return empty; -} - -/** - * Collapses a pasted slice to the inline content this schema allows: block - * boundaries become hard breaks, mentions survive with their ids, everything - * else arrives as text because the schema has nowhere else to put it. - */ -export function flattenToInlineSlice(slice: Slice): Slice { - const nodes: PMNode[] = []; - - const walk = (fragment: Fragment) => { - fragment.forEach(child => { - if (child.isInline) { - nodes.push(child.mark([])); - return; - } - if (nodes.length) nodes.push(hardBreakType.create()); - walk(child.content); - }); - }; - walk(slice.content); - - return new Slice(Fragment.fromArray(nodes), 0, 0); -} diff --git a/packages/react/components/editor/core/composer/schema.ts b/packages/react/components/editor/core/composer/schema.ts deleted file mode 100644 index b88be844f..000000000 --- a/packages/react/components/editor/core/composer/schema.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { Schema } from 'prosemirror-model'; -import { - hardBreakNodeSpec, - mentionNodeSpec, - paragraphNodeSpec -} from '../nodes'; - -/** - * The PromptInput composer: one paragraph of text, hard breaks, and atomic - * mentions. Nothing else, so pasted HTML sanitizes to plain text for free, - * there is no mark or block the parser could keep. - */ -export const composerSchema = new Schema({ - nodes: { - doc: { content: 'paragraph' }, - paragraph: paragraphNodeSpec, - text: { group: 'inline' }, - hardBreak: hardBreakNodeSpec, - mention: mentionNodeSpec - } -}); - -export const mentionType = composerSchema.nodes.mention; -export const hardBreakType = composerSchema.nodes.hardBreak; -export const paragraphType = composerSchema.nodes.paragraph; diff --git a/packages/react/components/editor/core/composer/use-composer-editor.ts b/packages/react/components/editor/core/composer/use-composer-editor.ts deleted file mode 100644 index ae41d1bae..000000000 --- a/packages/react/components/editor/core/composer/use-composer-editor.ts +++ /dev/null @@ -1,399 +0,0 @@ -'use client'; - -import { baseKeymap } from 'prosemirror-commands'; -import { history, redo, undo } from 'prosemirror-history'; -import { keymap } from 'prosemirror-keymap'; -import { Slice } from 'prosemirror-model'; -import { EditorState, Plugin, Selection } from 'prosemirror-state'; -import { EditorView } from 'prosemirror-view'; -import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'; -import { EXTERNAL, insertHardBreak, placeholderPlugin } from '../base'; -import { escapeText } from '../html'; -import { type MentionAttrs, mentionKey } from '../mention'; -import { deleteAdjacentMention, moveOverMention } from '../mention-commands'; -import { - MentionNodeView, - type MentionPortal, - type MentionPortalRegistry -} from '../mention-node-view'; -import { - dismissSuggestion, - insertMention as insertMentionAt, - type SuggestionState, - suggestionPlugin -} from '../suggestion-plugin'; -import { - deriveDocDetails, - docFromMarkup, - type EditorDocDetails, - flattenToInlineSlice, - inlineFragmentFromText, - isDocEmpty, - serializeText, - textFromFragment, - textLength -} from './markup'; -import { mentionType } from './schema'; - -export interface UseComposerEditorOptions { - /** Markup for the first document. Read once. */ - initialMarkup: string; - /** Placeholder shown while the document is empty. */ - placeholder?: string; - disabled?: boolean; - spellCheck?: boolean; - /** Cap on the derived plain text, where a chip counts as its label. */ - maxLength?: number; - /** Trigger characters currently registered by a `Mentions` part. */ - getTriggers?: () => string[]; - /** Fires for every document change the user made. */ - onChange?: (details: EditorDocDetails) => void; - /** Enter with no active menu. */ - onSubmit?: () => void; - onSuggestionChange?: (state: SuggestionState | null) => void; - /** Return true to consume the key while a menu is open. */ - onSuggestionKeyDown?: ( - event: KeyboardEvent, - state: SuggestionState - ) => boolean; -} - -export interface ComposerEditorActions { - focus: () => void; - /** - * Replaces the document when `markup` differs from what the document already - * serializes to. The compare is what keeps a controlled `value` from - * resetting the caret on every keystroke. - */ - setMarkup: (markup: string) => void; - getDetails: () => EditorDocDetails; - insertMention: ( - attrs: MentionAttrs, - range?: { from: number; to: number } - ) => void; - /** Applies fresh labels from `resolveMentions` without touching history. */ - refreshMentionLabels: (labels: Map) => void; - dismissSuggestion: () => void; -} - -export interface UseComposerEditorResult { - /** Attach to the element that becomes the editing host. */ - hostRef: (node: HTMLDivElement | null) => void; - /** - * Server and first-client markup for the host: the derived plain text, so a - * restored draft is readable before ProseMirror takes the subtree over. - */ - initialHtml: { __html: string }; - viewRef: React.RefObject; - mentionPortals: MentionPortal[]; - actions: ComposerEditorActions; -} - -export function useComposerEditor( - options: UseComposerEditorOptions -): UseComposerEditorResult { - const optionsRef = useRef(options); - optionsRef.current = options; - - const viewRef = useRef(null); - const hostNodeRef = useRef(null); - const [mentionPortals, setMentionPortals] = useState([]); - - // Read once: after mount the document is the source of truth and incoming - // markup arrives through `setMarkup`. - const initialMarkupRef = useRef(options.initialMarkup); - const initialHtml = useMemo( - () => ({ - __html: escapeText(serializeText(docFromMarkup(initialMarkupRef.current))) - }), - [] - ); - - const registry = useMemo( - () => ({ - add: portal => setMentionPortals(current => [...current, portal]), - update: (id, attrs) => - setMentionPortals(current => - current.map(portal => - portal.id === id ? { ...portal, attrs } : portal - ) - ), - remove: id => - setMentionPortals(current => current.filter(portal => portal.id !== id)) - }), - [] - ); - - const hostRef = useCallback((node: HTMLDivElement | null) => { - hostNodeRef.current = node; - }, []); - - useLayoutEffect(() => { - const host = hostNodeRef.current; - if (!host) return; - - // ProseMirror owns this subtree from here on; the first-paint text is - // dropped so the view starts from a clean slate. - host.replaceChildren(); - - let everFocused = false; - let pointerFocus = false; - - const keysPlugin = new Plugin({ - props: { - handleKeyDown(view, event) { - if (event.key !== 'Enter') return false; - // A composing Enter confirms the composition; it never submits and it - // never reaches the document. - if (event.isComposing || event.keyCode === 229) return true; - if (event.shiftKey) return insertHardBreak(view.state, view.dispatch); - optionsRef.current.onSubmit?.(); - return true; - } - } - }); - - const clipboardPlugin = new Plugin({ - props: { - transformPasted: slice => flattenToInlineSlice(slice), - clipboardTextParser: text => - new Slice(inlineFragmentFromText(text), 0, 0), - clipboardTextSerializer: slice => textFromFragment(slice.content) - } - }); - - // A bare `focus()` on an editing host places no caret. When focus arrives - // from the frame rather than from a press inside the editor, drop the caret - // at the end, the way clicking past the end of a textarea's text behaves. - const focusPlugin = new Plugin({ - props: { - handleDOMEvents: { - mousedown: () => { - pointerFocus = true; - window.setTimeout(() => { - pointerFocus = false; - }, 0); - return false; - }, - touchstart: () => { - pointerFocus = true; - window.setTimeout(() => { - pointerFocus = false; - }, 0); - return false; - }, - focus: view => { - const first = !everFocused; - everFocused = true; - if (!first || pointerFocus) return false; - view.dispatch( - view.state.tr - .setSelection(Selection.atEnd(view.state.doc)) - .setMeta(EXTERNAL, true) - ); - return false; - } - } - } - }); - - // The composer is its own scroller, so the caret only ever has to be - // brought into *it*. ProseMirror's own scroll-into-view walks every - // scrollable ancestor up to the document, which nudges the page under the - // composer by a pixel or two on any edit that changes the caret's position. - const scrollPlugin = new Plugin({ - props: { - handleScrollToSelection(view) { - const host = view.dom as HTMLElement; - let coords: { top: number; bottom: number }; - try { - coords = view.coordsAtPos(view.state.selection.head); - } catch { - return true; - } - const box = host.getBoundingClientRect(); - if (coords.top < box.top) { - host.scrollTop -= box.top - coords.top; - } else if (coords.bottom > box.bottom) { - host.scrollTop += coords.bottom - box.bottom; - } - return true; - } - } - }); - - // A cap on the derived text, enforced as a transaction filter so paste and - // IME are covered and not just keystrokes. - const maxLengthPlugin = new Plugin({ - filterTransaction(transaction, current) { - const max = optionsRef.current.maxLength; - if (max == null || !transaction.docChanged) return true; - if (transaction.getMeta(EXTERNAL)) return true; - const next = textLength(transaction.doc); - return next <= max || next <= textLength(current.doc); - } - }); - - const initialDoc = docFromMarkup(initialMarkupRef.current); - - const state = EditorState.create({ - doc: initialDoc, - // A restored draft opens with the caret after it, the way reopening a - // half-written message in any composer behaves. - selection: Selection.atEnd(initialDoc), - plugins: [ - // First in the list, so an open menu wins ↑ ↓ Enter Tab Escape. - suggestionPlugin({ - getTriggers: () => - (optionsRef.current.getTriggers?.() ?? []).map(char => ({ char })), - onStateChange: next => optionsRef.current.onSuggestionChange?.(next), - onKeyDown: (event, suggestion) => - optionsRef.current.onSuggestionKeyDown?.(event, suggestion) ?? false - }), - keysPlugin, - keymap({ - Backspace: deleteAdjacentMention(-1), - Delete: deleteAdjacentMention(1), - ArrowLeft: moveOverMention(-1), - ArrowRight: moveOverMention(1), - 'Mod-z': undo, - 'Mod-y': redo, - 'Shift-Mod-z': redo - }), - history(), - keymap(baseKeymap), - maxLengthPlugin, - scrollPlugin, - placeholderPlugin(() => optionsRef.current.placeholder, isDocEmpty), - clipboardPlugin, - focusPlugin - ] - }); - - let editorView: EditorView | null = null; - - const view = new EditorView( - { mount: host }, - { - state, - editable: () => !optionsRef.current.disabled, - nodeViews: { - mention: node => new MentionNodeView(node, registry) - }, - dispatchTransaction(transaction) { - if (!editorView) return; - const next = editorView.state.apply(transaction); - editorView.updateState(next); - if (!transaction.docChanged) return; - if (transaction.getMeta(EXTERNAL)) return; - optionsRef.current.onChange?.(deriveDocDetails(next.doc)); - } - } - ); - - editorView = view; - viewRef.current = view; - - return () => { - viewRef.current = null; - view.destroy(); - }; - }, [registry]); - - // `editable` is read through a prop function, so ProseMirror needs a nudge to - // re-read it when the composer is disabled or re-enabled. - useLayoutEffect(() => { - const view = viewRef.current; - if (!view) return; - view.setProps({ editable: () => !options.disabled }); - }, [options.disabled]); - - useLayoutEffect(() => { - const view = viewRef.current; - if (!view) return; - view.dom.spellcheck = options.spellCheck ?? true; - }, [options.spellCheck]); - - // The placeholder is a decoration read from the options ref, so a changed - // string needs a state update to redraw it. An empty transaction changes no - // document, so it is never reported as a value change. - // biome-ignore lint/correctness/useExhaustiveDependencies: the dependency is the trigger, not a value the body reads - useLayoutEffect(() => { - const view = viewRef.current; - if (!view) return; - view.dispatch(view.state.tr.setMeta(EXTERNAL, true)); - }, [options.placeholder]); - - const actions = useMemo( - () => ({ - focus: () => viewRef.current?.focus(), - - setMarkup: markup => { - const view = viewRef.current; - if (!view) return; - if (deriveDocDetails(view.state.doc).markup === markup) return; - const replacement = docFromMarkup(markup); - const tr = view.state.tr; - tr.replace( - 0, - view.state.doc.content.size, - new Slice(replacement.content, 0, 0) - ); - tr.setSelection(Selection.atEnd(tr.doc)); - tr.setMeta(EXTERNAL, true); - tr.setMeta('addToHistory', false); - view.dispatch(tr); - }, - - getDetails: () => { - const view = viewRef.current; - if (!view) { - return deriveDocDetails(docFromMarkup(initialMarkupRef.current)); - } - return deriveDocDetails(view.state.doc); - }, - - insertMention: (attrs, range) => { - const view = viewRef.current; - if (!view) return; - if (!range && !view.hasFocus()) { - // Not focused: the chip belongs at the end of the draft. - const end = Selection.atEnd(view.state.doc).from; - insertMentionAt(view, attrs, { from: end, to: end }); - } else { - insertMentionAt(view, attrs, range); - } - view.focus(); - }, - - refreshMentionLabels: labels => { - const view = viewRef.current; - if (!view || labels.size === 0) return; - const tr = view.state.tr; - let changed = false; - view.state.doc.descendants((node, pos) => { - if (node.type !== mentionType) return; - const attrs = node.attrs as MentionAttrs; - const fresh = labels.get( - mentionKey(attrs.trigger, attrs.type, attrs.id) - ); - if (fresh && fresh !== attrs.label) { - tr.setNodeMarkup(pos, undefined, { ...attrs, label: fresh }); - changed = true; - } - }); - if (!changed) return; - tr.setMeta('addToHistory', false); - view.dispatch(tr); - }, - - dismissSuggestion: () => { - const view = viewRef.current; - if (view) dismissSuggestion(view); - } - }), - [] - ); - - return { hostRef, initialHtml, viewRef, mentionPortals, actions }; -} diff --git a/packages/react/components/editor/core/editor-core.module.css b/packages/react/components/editor/core/editor-core.module.css index 810a4f6fa..fb202a251 100644 --- a/packages/react/components/editor/core/editor-core.module.css +++ b/packages/react/components/editor/core/editor-core.module.css @@ -16,23 +16,6 @@ line-height: var(--editor-line-height); } -/* The PromptInput composer. The small font's own 16px line box is shorter - than a chip's icon and trailing slots, so the composer pairs the small font - with the regular line height and sizes the chip to match, so the line box is - the same height whatever a line holds. */ -.composer { - width: 100%; - overflow-y: auto; - color: var(--rs-color-foreground-base-primary); - font-family: var(--rs-font-body); - font-size: var(--rs-font-size-small); - letter-spacing: var(--rs-letter-spacing-small); -} - -.composer > p { - margin: 0; -} - /* prosemirror-view ships a stylesheet the editor deliberately does not load, it brings its own type, layout and selection treatment. Two of those rules are load-bearing rather than cosmetic, so they are mirrored here. */ diff --git a/packages/react/components/editor/core/keymaps.ts b/packages/react/components/editor/core/keymaps.ts index bc80924f0..983af93a8 100644 --- a/packages/react/components/editor/core/keymaps.ts +++ b/packages/react/components/editor/core/keymaps.ts @@ -1,10 +1,4 @@ -import { - chainCommands, - exitCode, - newlineInCode, - setBlockType -} from 'prosemirror-commands'; -import { redo } from 'prosemirror-history'; +import { chainCommands, exitCode, setBlockType } from 'prosemirror-commands'; import { undoInputRule } from 'prosemirror-inputrules'; import { keymap } from 'prosemirror-keymap'; import type { Schema } from 'prosemirror-model'; @@ -14,8 +8,6 @@ import { splitListItem } from 'prosemirror-schema-list'; import type { Command, Plugin } from 'prosemirror-state'; -import { insertHardBreak } from './base'; -import { deleteAdjacentMention, moveOverMention } from './mention-commands'; const never: Command = () => false; @@ -62,14 +54,11 @@ const resetBlockAtStart: Command = (state, dispatch) => { }; /** - * Keys for lists, mentions and block edges. Sits after the shortcut keymap - * and before history and the base keymap. `Mod-y` redoes unless `redo` is - * false. + * Keys for lists and block edges. `Editor` adds it after the shortcut keymap + * and before the store's own keys, so Backspace tries an input rule undo, a + * list lift and a block reset before it deletes a chip. */ -export function buildEditingKeymap( - schema: Schema, - options: { redo: boolean } -): Plugin { +export function buildEditingKeymap(schema: Schema): Plugin { const { listItem, taskItem } = schema.nodes; const items = [listItem?.name, taskItem?.name].filter( (name): name is string => !!name @@ -87,24 +76,19 @@ export function buildEditingKeymap( taskItem ? liftListItem(taskItem) : null ); - const bindings: Record = { + return keymap({ Enter: splitItem, - 'Shift-Enter': chainCommands(newlineInCode, insertHardBreak), 'Mod-Enter': exitCode, // Tab stays in the editor inside a list, and moves focus everywhere else. Tab: (state, dispatch) => sink(state, dispatch) || inListItem(state), 'Shift-Tab': (state, dispatch) => lift(state, dispatch) || inListItem(state), + // A chip is never before the caret at the start of a block, so these + // never compete with the store's chip delete. Backspace: chainCommands( undoInputRule, - deleteAdjacentMention(-1), liftAtItemStart(items), resetBlockAtStart - ), - Delete: deleteAdjacentMention(1), - ArrowLeft: moveOverMention(-1), - ArrowRight: moveOverMention(1) - }; - if (options.redo) bindings['Mod-y'] = redo; - return keymap(bindings); + ) + }); } diff --git a/packages/react/components/editor/core/mention-registry.ts b/packages/react/components/editor/core/mention-registry.ts index 6ab1163aa..7a273b297 100644 --- a/packages/react/components/editor/core/mention-registry.ts +++ b/packages/react/components/editor/core/mention-registry.ts @@ -60,7 +60,8 @@ function sameData(a: MentionsData, b: MentionsData): boolean { /** * Shared between a `Mentions` part (which writes the config), the part that * drives the menu and decorates chips, and the root (which reads `data` back - * when assembling a message). PromptInput and Editor each own one. + * when assembling a message). An `Editor` store creates its own. The store + * behind `PromptInput.Editor` uses the one that the PromptInput root owns. * * `icon`, `trailing` and `data` cannot survive serialization, so they live here * rather than on the document, keyed by `trigger|type|id` and filled in when an diff --git a/packages/react/components/editor/core/nodes.ts b/packages/react/components/editor/core/nodes.ts index b23dd739f..17a4d720c 100644 --- a/packages/react/components/editor/core/nodes.ts +++ b/packages/react/components/editor/core/nodes.ts @@ -2,9 +2,9 @@ import type { NodeSpec } from 'prosemirror-model'; import { type MentionAttrs, mentionText } from './mention'; /** - * The node specs that the Editor schema and the PromptInput composer schema - * share. This module has no top-level calls, so a PromptInput-only app does - * not keep the rest of the Editor schema. + * The node specs that the Editor schema and the PromptInput schema share. + * This module has no top-level calls, so a PromptInput-only app does not keep + * the rest of the Editor schema. */ export const mentionNodeSpec: NodeSpec = { diff --git a/packages/react/components/editor/core/suggestion-plugin.ts b/packages/react/components/editor/core/suggestion-plugin.ts index 1486d3a21..ccea7c54a 100644 --- a/packages/react/components/editor/core/suggestion-plugin.ts +++ b/packages/react/components/editor/core/suggestion-plugin.ts @@ -5,7 +5,7 @@ import { TextSelection, type Transaction } from 'prosemirror-state'; -import { Decoration, DecorationSet, type EditorView } from 'prosemirror-view'; +import { Decoration, DecorationSet } from 'prosemirror-view'; import styles from './editor-core.module.css'; import type { MentionAttrs } from './mention'; @@ -283,13 +283,6 @@ export function suggestionPlugin(options: SuggestionPluginOptions): Plugin { }); } -/** Closes the menu and leaves the typed text literal. */ -export function dismissSuggestion(view: EditorView): void { - view.dispatch( - view.state.tr.setMeta(suggestionPluginKey, { type: 'dismiss' }) - ); -} - function isWhitespaceAt(state: EditorState, position: number): boolean { if (position >= state.doc.content.size) return false; return /\s/.test( @@ -299,18 +292,9 @@ function isWhitespaceAt(state: EditorState, position: number): boolean { /** * Replaces `range` with a chip followed by a single space, caret after it. - * With no range the chip lands at the caret. + * With no range the chip lands at the caret. Null when the schema has no + * mentions. */ -export function insertMention( - view: EditorView, - attrs: MentionAttrs, - range?: { from: number; to: number } -): void { - const tr = mentionTransaction(view.state, attrs, range); - if (tr) view.dispatch(tr); -} - -/** The transaction behind `insertMention`, or null when the schema has no mentions. */ export function mentionTransaction( state: EditorState, attrs: MentionAttrs, diff --git a/packages/react/components/editor/core/use-suggestion-menu.ts b/packages/react/components/editor/core/use-suggestion-menu.ts index c3d28db3a..ae1dcb416 100644 --- a/packages/react/components/editor/core/use-suggestion-menu.ts +++ b/packages/react/components/editor/core/use-suggestion-menu.ts @@ -435,8 +435,7 @@ export function useMentionResolution( registry: MentionRegistry, mentions: MentionAttrs[], refreshLabels: (labels: Map) => void, - getResolver: (trigger: string) => MentionsData['resolveMentions'] = trigger => - registry.get(trigger)?.resolveMentions + getResolver: (trigger: string) => MentionsData['resolveMentions'] ): void { const requestedRef = useRef(new Set()); const refreshRef = useRef(refreshLabels); diff --git a/packages/react/components/editor/editor-content.tsx b/packages/react/components/editor/editor-content.tsx index 674afa914..33f9d39e7 100644 --- a/packages/react/components/editor/editor-content.tsx +++ b/packages/react/components/editor/editor-content.tsx @@ -16,6 +16,7 @@ import { docToHTML } from './core/serializers'; import { useMentionRegistryVersion } from './core/use-suggestion-menu'; import styles from './editor.module.css'; import { useEditorStore, useStoreSelector } from './editor-context'; +import type { EditorStore } from './editor-store'; export interface EditorContentProps extends Omit< @@ -30,13 +31,35 @@ export interface EditorContentProps } /** The mount point for the editable document. */ -export function EditorContent({ +export function EditorContent({ className, ...props }: EditorContentProps) { + const store = useEditorStore('Editor.Content'); + return ( + + ); +} + +EditorContent.displayName = 'Editor.Content'; + +export interface EditorHostProps extends EditorContentProps { + store: EditorStore; +} + +/** + * Mounts the store's view and renders the chip portals. `Editor.Content` and + * `PromptInput.Editor` use it, each with its own typography. + */ +export function EditorHost({ + store, className, spellCheck = true, ref, ...props -}: EditorContentProps) { - const store = useEditorStore('Editor.Content'); +}: EditorHostProps) { const hostRef = useRef(null); const mergedRef = useMergedRefs(hostRef, ref); @@ -49,7 +72,7 @@ export function EditorContent({ // ProseMirror adds its own classes to the element, and React would drop // them when it writes a new `className`. React writes the first value only, // and ProseMirror's `attributes` prop applies the later ones. - const classes = cx(coreStyles.editor, styles.content, className); + const classes = cx(coreStyles.editor, className); const [initialClasses] = useState(classes); const classesRef = useRef(classes); classesRef.current = classes; @@ -97,7 +120,6 @@ export function EditorContent({
); } - -EditorContent.displayName = 'Editor.Content'; diff --git a/packages/react/components/editor/editor-context.ts b/packages/react/components/editor/editor-context.ts index dedca259a..3aad33355 100644 --- a/packages/react/components/editor/editor-context.ts +++ b/packages/react/components/editor/editor-context.ts @@ -2,12 +2,13 @@ import type { EditorState } from 'prosemirror-state'; import { createContext, useContext, useRef, useSyncExternalStore } from 'react'; +import type { RichEditorStore } from './editor-rich-store'; import type { EditorStore } from './editor-store'; import type { EditorApi } from './editor-types'; -export const EditorContext = createContext(null); +export const EditorContext = createContext(null); -export function useEditorStore(part: string): EditorStore { +export function useEditorStore(part: string): RichEditorStore { const store = useContext(EditorContext); if (!store) throw new Error(`${part} must be used within `); return store; @@ -18,14 +19,14 @@ export function useEditorStore(part: string): EditorStore { * selector each render is fine: `isEqual` keeps the previous value when the * result is the same. */ -export function useStoreSelector( - store: EditorStore, - selector: (store: EditorStore) => T, +export function useStoreSelector( + store: S, + selector: (store: S) => T, isEqual: (a: T, b: T) => boolean = Object.is ): T { const cache = useRef<{ revision: number; - selector: (store: EditorStore) => T; + selector: (store: S) => T; value: T; } | null>(null); diff --git a/packages/react/components/editor/editor-mentions.tsx b/packages/react/components/editor/editor-mentions.tsx index c8d1953ea..8cd1bd9a8 100644 --- a/packages/react/components/editor/editor-mentions.tsx +++ b/packages/react/components/editor/editor-mentions.tsx @@ -56,36 +56,84 @@ function sameMentions(a: MentionAttrs[], b: MentionAttrs[]): boolean { } /** A menu that inserts a mention chip. Mount one per trigger. */ -export function EditorMentions(props: EditorMentionsProps) { +export function EditorMentions({ + trigger = '@', + ...props +}: EditorMentionsProps) { const store = useEditorStore('Editor.Mentions'); // `formats` without `mention` builds a schema with no mention node. - if (!store.schema.nodes.mention) return null; - return ; + const enabled = store.schema.nodes.mention !== undefined; + + if ( + process.env.NODE_ENV !== 'production' && + enabled && + !isTriggerCharacter(trigger) + ) { + console.warn( + `[Apsara] Editor.Mentions trigger ${JSON.stringify(trigger)} is not a ` + + 'single punctuation character. Use "@", "#" or similar.' + ); + } + + useEffect( + () => (enabled ? store.mentions.register(trigger) : undefined), + [store, enabled, trigger] + ); + + if (!enabled) return null; + return ( + + ); } EditorMentions.displayName = 'Editor.Mentions'; -function MentionsMenu({ +export interface MentionsMenuProps extends EditorMentionsProps { + store: EditorStore; + trigger: string; + /** The part named in dev warnings. */ + name: string; + /** The spaces a query can hold. No limit when not set. */ + maxSpaces?: number; + /** The popup width in pixels. */ + width?: number; + /** + * Applies labels from `resolveMentions`. + * @default store.refreshMentionLabels + */ + refreshLabels?: (labels: Map) => void; + 'data-slot'?: string; +} + +/** + * The menu behind `Editor.Mentions`. It does not register its trigger with + * the mention registry, so `PromptInput.Editor` can render one for each + * trigger that `PromptInput.Mentions` registers. + */ +export function MentionsMenu({ store, - trigger = '@', + trigger, items, onSearch, resolveMentions, emptyMessage = 'No results', loadingRowCount = 3, - onOpenChange -}: EditorMentionsProps & { store: EditorStore }) { + onOpenChange, + name, + maxSpaces, + width, + refreshLabels = store.refreshMentionLabels, + 'data-slot': slot +}: MentionsMenuProps) { const registry = store.mentions; - if (process.env.NODE_ENV !== 'production' && !isTriggerCharacter(trigger)) { - console.warn( - `[Apsara] Editor.Mentions trigger ${JSON.stringify(trigger)} is not a ` + - 'single punctuation character. Use "@", "#" or similar.' - ); - } - - useEffect(() => registry.register(trigger), [registry, trigger]); - const resolveRef = useRef(resolveMentions); resolveRef.current = resolveMentions; const getResolver = useCallback( @@ -97,7 +145,7 @@ function MentionsMenu({ const { menu, listboxId } = useEditorSuggestion({ store, trigger, - maxSpaces: 3, + maxSpaces, items, onSearch, onSelect: (item, state) => { @@ -109,7 +157,7 @@ function MentionsMenu({ ); }, onOpenChange, - name: 'Editor.Mentions' + name }); const mentions = useStoreSelector( @@ -122,16 +170,11 @@ function MentionsMenu({ : NO_MENTIONS, sameMentions ); - useMentionResolution( - registry, - mentions, - store.refreshMentionLabels, - getResolver - ); + useMentionResolution(registry, mentions, refreshLabels, getResolver); return ( ); } diff --git a/packages/react/components/editor/editor-rich-store.ts b/packages/react/components/editor/editor-rich-store.ts new file mode 100644 index 000000000..214f92d1e --- /dev/null +++ b/packages/react/components/editor/editor-rich-store.ts @@ -0,0 +1,493 @@ +import { dropCursor } from 'prosemirror-dropcursor'; +import { gapCursor } from 'prosemirror-gapcursor'; +import { redo, undo } from 'prosemirror-history'; +import { + Fragment, + type Node as PMNode, + type Schema, + Slice +} from 'prosemirror-model'; +import { + type Command, + EditorState, + NodeSelection, + Plugin, + Selection, + type Transaction +} from 'prosemirror-state'; +import { + activeLink, + activeTextStyle, + editorCommands, + isBlockActive, + isMarkActive, + setLink +} from './core/commands'; +import { buildInputRules } from './core/input-rules'; +import { docFromJSON, type EditorJSON, emptyDoc } from './core/json'; +import { buildEditingKeymap } from './core/keymaps'; +import type { EditorFormat } from './core/schema'; +import { docToHTML, docToText, isEditorEmpty } from './core/serializers'; +import type { EditorAction } from './core/shortcuts'; +import { mentionTransaction } from './core/suggestion-plugin'; +import { TaskItemView } from './core/task-item-view'; +import styles from './editor.module.css'; +import { + type EditorExtension, + EditorStore, + type EditorStoreProps +} from './editor-store'; +import type { + EditorApi, + EditorChangeDetails, + EditorCommands, + EditorMarkdownChangeDetails, + MarkdownAdapter +} from './editor-types'; + +export interface RichEditorStoreProps extends EditorStoreProps { + markdown?: MarkdownAdapter; + onValueChange?: ( + value: EditorJSON, + details: EditorChangeDetails | EditorMarkdownChangeDetails + ) => void; +} + +export interface RichEditorStoreOptions { + schema: Schema; + /** The first doc. A string is Markdown. */ + value: EditorJSON | string | undefined; + shortcuts: Record; + props: RichEditorStoreProps; + autoFocus: boolean | 'start' | 'end'; +} + +interface Target { + priority: number; + run: () => boolean; +} + +const URL_PATTERN = /^(https?:\/\/|mailto:)\S+$/i; + +function run(targets: Set): boolean { + const sorted = [...targets].sort((a, b) => b.priority - a.priority); + return sorted.some(target => target.run()); +} + +function register(targets: Set, target: Target): () => void { + targets.add(target); + return () => { + targets.delete(target); + }; +} + +/** Loads a `value` or `defaultValue`. A string is Markdown. */ +function parseValue( + schema: Schema, + value: EditorJSON | string, + adapter: MarkdownAdapter | undefined +): PMNode { + if (typeof value !== 'string') return docFromJSON(schema, value); + if (adapter) return docFromJSON(schema, adapter.toEditor(value)); + if (process.env.NODE_ENV !== 'production') { + console.warn( + '[Apsara] Editor received a string value without the `markdown` ' + + 'prop. The string loads as plain text.' + ); + } + const paragraphs = value + .split(/\n{2,}/) + .map(text => + schema.nodes.paragraph.create(null, text ? schema.text(text) : null) + ); + return schema.topNodeType.create(null, paragraphs); +} + +/** + * Pasted Markdown. A single paragraph pastes as inline content and takes the + * marks at the caret, as a plain-text paste does. + */ +function pastedSlice(state: EditorState, doc: PMNode): Slice { + const first = doc.firstChild; + if (doc.childCount !== 1 || first?.type !== state.schema.nodes.paragraph) { + return Slice.maxOpen(doc.content); + } + const marks = state.storedMarks ?? state.selection.$from.marks(); + const nodes: PMNode[] = []; + first.forEach(node => { + let set = node.marks; + for (const mark of marks) { + if (!mark.type.isInSet(set)) set = mark.addToSet(set); + } + nodes.push(node.mark(set)); + }); + return new Slice(Fragment.from(nodes), 0, 0); +} + +/** Links pasted over a selection, and Markdown on paste and copy. */ +function clipboardPlugin(store: RichEditorStore): Plugin { + return new Plugin({ + props: { + handlePaste: (view, event) => { + const data = event.clipboardData; + if (!data) return false; + const text = data.getData('text/plain'); + const url = text.trim(); + + // A URL pasted over a selection links the selection. + if ( + !view.state.selection.empty && + URL_PATTERN.test(url) && + setLink(url)(view.state, view.dispatch) + ) { + return true; + } + + const adapter = store.props.markdown; + const { $from } = view.state.selection; + const marks = view.state.storedMarks ?? $from.marks(); + if ( + !adapter || + adapter.paste === false || + !text || + data.types.includes('text/html') || + $from.parent.type.spec.code || + marks.some(mark => mark.type.spec.code) + ) { + return false; + } + const doc = docFromJSON(store.schema, adapter.toEditor(text)); + view.dispatch( + view.state.tr + .replaceSelection(pastedSlice(view.state, doc)) + .scrollIntoView() + ); + return true; + }, + clipboardTextSerializer: (slice, view) => { + const adapter = store.props.markdown; + // A copied slice includes its parents up to the doc. + const doc = adapter?.copy + ? view.state.schema.topNodeType.createAndFill(null, slice.content) + : null; + if (adapter && doc) { + return adapter.fromEditor(doc.toJSON() as EditorJSON); + } + return slice.content.textBetween(0, slice.content.size, '\n\n'); + } + } + }); +} + +/** Formats, lists, input rules, cursors, task items and the clipboard. */ +function richExtension(store: RichEditorStore): EditorExtension { + const taskViews = new Set(); + const inputRules = buildInputRules(store.schema); + return { + commands: { + bold: editorCommands.toggleMark('bold'), + italic: editorCommands.toggleMark('italic'), + underline: editorCommands.toggleMark('underline'), + strike: editorCommands.toggleMark('strike'), + code: editorCommands.toggleMark('code'), + link: () => store.openLink(), + paragraph: editorCommands.setParagraph(), + heading1: editorCommands.setHeading(1), + heading2: editorCommands.setHeading(2), + heading3: editorCommands.setHeading(3), + heading4: editorCommands.setHeading(4), + bulletList: editorCommands.toggleList('bulletList'), + orderedList: editorCommands.toggleList('orderedList'), + taskList: editorCommands.toggleList('taskList'), + blockquote: editorCommands.toggleBlock('blockquote'), + codeBlock: editorCommands.toggleBlock('codeBlock'), + focusToolbar: () => store.focusToolbar() + }, + keys: [ + buildEditingKeymap(store.schema), + ...(inputRules ? [inputRules] : []) + ], + last: [ + dropCursor({ class: styles['drop-cursor'], color: false }), + gapCursor(), + clipboardPlugin(store) + ], + nodeViews: { + taskItem: (node, view, getPos) => { + const task: TaskItemView = new TaskItemView( + node, + view, + getPos, + { + item: styles['task-item'], + checkbox: styles['task-checkbox'], + content: styles['task-content'] + }, + () => { + taskViews.delete(task); + } + ); + taskViews.add(task); + return task; + } + }, + setEditable: editable => { + for (const task of taskViews) task.setEditable(editable); + } + }; +} + +/** + * The store `Editor` creates: the core store plus the rich-text features, + * the `actionsRef` API, toolbars and links, and JSON and Markdown values. + */ +export class RichEditorStore extends EditorStore { + declare props: RichEditorStoreProps; + readonly api: EditorApi; + + /** The last value this store emitted or loaded. */ + private lastValue: EditorJSON | string | undefined; + /** Markdown for docs the adapter has converted, so a controlled string that matches the doc does not reload it. */ + private readonly markdownCache = new WeakMap(); + private readonly toolbars = new Set(); + private readonly linkOpeners = new Set(); + + constructor(options: RichEditorStoreOptions) { + const { schema, value, props } = options; + super({ + schema, + doc: + value === undefined + ? emptyDoc(schema) + : parseValue(schema, value, props.markdown), + shortcuts: options.shortcuts, + props, + autoFocus: options.autoFocus, + // Runs during `super`, so it only builds closures over the store. + extend: store => richExtension(store as RichEditorStore) + }); + this.lastValue = value; + this.api = this.createApi(); + } + + protected override report(doc: PMNode): void { + const onValueChange = this.props.onValueChange; + if (!onValueChange) { + this.lastValue = undefined; + return; + } + const value = doc.toJSON() as EditorJSON; + this.lastValue = value; + onValueChange(value, this.details(doc, value)); + } + + private details( + doc: PMNode, + value: EditorJSON + ): EditorChangeDetails | EditorMarkdownChangeDetails { + const details: EditorChangeDetails = { + empty: isEditorEmpty(doc), + getMentions: () => docToText(doc).mentions, + getText: () => docToText(doc).text, + getHTML: () => docToHTML(doc) + }; + const adapter = this.props.markdown; + if (!adapter) return details; + return { + ...details, + getMarkdown: () => this.markdownOf(doc, adapter, value) + }; + } + + private markdownOf( + doc: PMNode, + adapter: MarkdownAdapter, + value?: EditorJSON + ): string { + let markdown = this.markdownCache.get(doc); + if (markdown === undefined) { + markdown = adapter.fromEditor(value ?? (doc.toJSON() as EditorJSON)); + this.markdownCache.set(doc, markdown); + } + return markdown; + } + + private parse(value: EditorJSON | string): PMNode { + return parseValue(this.schema, value, this.props.markdown); + } + + /** + * Applies a controlled `value`. Nothing happens when it is the value the + * store last emitted, when a Markdown string is what the doc converts to, or + * when it loads to the doc the editor already has. + */ + reconcile(value: EditorJSON | string): void { + if (value === this.lastValue) return; + this.lastValue = value; + const adapter = this.props.markdown; + if ( + typeof value === 'string' && + adapter && + this.markdownOf(this.state.doc, adapter) === value + ) { + return; + } + const doc = this.parse(value); + if (doc.eq(this.state.doc)) return; + this.replaceState(doc); + } + + /** Loads `doc` with a new history, so Undo cannot step back past it. */ + private replaceState(doc: PMNode): void { + const pos = Math.min(this.state.selection.from, doc.content.size); + this.state = EditorState.create({ + doc, + plugins: this.state.plugins, + selection: Selection.near(doc.resolve(pos)) + }); + this.view?.updateState(this.state); + this.emit(); + } + + private replaceDocTransaction(doc: PMNode): Transaction { + const tr = this.state.tr.replaceWith( + 0, + this.state.doc.content.size, + doc.content + ); + const pos = Math.min(this.state.selection.from, tr.doc.content.size); + tr.setSelection(Selection.near(tr.doc.resolve(pos))); + return tr; + } + + // ---- toolbars and links ---- + + registerToolbar(priority: number, focus: () => boolean): () => void { + return register(this.toolbars, { priority, run: focus }); + } + + focusToolbar(): boolean { + return run(this.toolbars); + } + + registerLinkOpener(priority: number, open: () => boolean): () => void { + return register(this.linkOpeners, { priority, run: open }); + } + + openLink(): boolean { + if (!this.isEditable() || !this.schema.marks.link) return false; + return run(this.linkOpeners); + } + + // ---- api ---- + + private commandSet( + runCommand: (command: Command) => boolean + ): EditorCommands { + return { + toggleMark: mark => runCommand(editorCommands.toggleMark(mark)), + setParagraph: () => runCommand(editorCommands.setParagraph()), + setHeading: level => runCommand(editorCommands.setHeading(level)), + toggleBlock: block => runCommand(editorCommands.toggleBlock(block)), + toggleList: list => runCommand(editorCommands.toggleList(list)), + setLink: href => runCommand(editorCommands.setLink(href)), + unsetLink: () => runCommand(editorCommands.unsetLink()), + insertHorizontalRule: () => + runCommand(editorCommands.insertHorizontalRule()), + insertText: text => runCommand(editorCommands.insertText(text)), + insertMention: (item, options) => + runCommand((state, dispatch) => { + if (!state.schema.nodes.mention) return false; + if (!dispatch) return true; + const trigger = + options?.trigger ?? this.mentions.triggers()[0] ?? '@'; + const type = item.type ?? 'mention'; + this.mentions.remember(trigger, { ...item, type }); + const tr = mentionTransaction(state, { + id: item.id, + label: item.label, + type, + trigger + }); + if (tr) dispatch(tr); + return true; + }), + clearFormatting: () => runCommand(editorCommands.clearFormatting()), + undo: () => runCommand(undo), + redo: () => runCommand(redo), + setContent: value => + runCommand((_state, dispatch) => { + if (dispatch) dispatch(this.replaceDocTransaction(this.parse(value))); + return true; + }), + clear: () => + runCommand((state, dispatch) => { + if (dispatch) { + dispatch(this.replaceDocTransaction(emptyDoc(state.schema))); + } + return true; + }) + }; + } + + private createApi(): EditorApi { + const store = this; + return { + get view() { + return store.view; + }, + getState: () => store.state, + commands: this.commandSet(store.run), + can: this.commandSet(command => command(store.state)), + isActive: (format: EditorFormat, attrs?: Record) => + isFormatActive(store.state, format, attrs), + getJSON: () => store.state.doc.toJSON() as EditorJSON, + getText: () => docToText(store.state.doc).text, + getHTML: () => docToHTML(store.state.doc), + getMarkdown: () => { + const adapter = store.props.markdown; + if (!adapter) { + if (process.env.NODE_ENV !== 'production') { + console.error( + '[Apsara] Editor getMarkdown() needs the `markdown` prop. ' + + 'Pass MarkdownAdapter.create().' + ); + } + return null; + } + return store.markdownOf(store.state.doc, adapter); + }, + focus: position => store.focus(position) + }; + } +} + +function isFormatActive( + state: EditorState, + format: EditorFormat, + attrs?: Record +): boolean { + switch (format) { + case 'bold': + case 'italic': + case 'underline': + case 'strike': + case 'code': + return isMarkActive(state, format); + case 'link': + return activeLink(state) !== null; + case 'heading': { + const style = activeTextStyle(state); + if (typeof style !== 'number') return false; + return attrs?.level === undefined || attrs.level === style; + } + case 'mention': + case 'horizontalRule': + return ( + state.selection instanceof NodeSelection && + state.selection.node.type.name === format + ); + default: + return isBlockActive(state, format); + } +} diff --git a/packages/react/components/editor/editor-root.tsx b/packages/react/components/editor/editor-root.tsx index 3f44975e3..6ffdb2308 100644 --- a/packages/react/components/editor/editor-root.tsx +++ b/packages/react/components/editor/editor-root.tsx @@ -14,7 +14,7 @@ import { isEditorEmpty } from './core/serializers'; import { type EditorShortcuts, resolveShortcuts } from './core/shortcuts'; import styles from './editor.module.css'; import { EditorContext, useStoreSelector } from './editor-context'; -import { EditorStore } from './editor-store'; +import { RichEditorStore } from './editor-rich-store'; import type { EditorApi, EditorChangeDetails, @@ -101,12 +101,12 @@ export function EditorRoot({ disabled, readOnly, markdown, - onValueChange: onValueChange as EditorStore['props']['onValueChange'] + onValueChange: onValueChange as RichEditorStore['props']['onValueChange'] }; const [store] = useState( () => - new EditorStore({ + new RichEditorStore({ schema: buildSchema(formats), value: value ?? defaultValue, shortcuts: resolveShortcuts(shortcuts), diff --git a/packages/react/components/editor/editor-store.ts b/packages/react/components/editor/editor-store.ts index 653dcccda..28b7c4f54 100644 --- a/packages/react/components/editor/editor-store.ts +++ b/packages/react/components/editor/editor-store.ts @@ -1,49 +1,28 @@ -import { baseKeymap } from 'prosemirror-commands'; -import { dropCursor } from 'prosemirror-dropcursor'; -import { gapCursor } from 'prosemirror-gapcursor'; +import { baseKeymap, chainCommands, newlineInCode } from 'prosemirror-commands'; import { closeHistory, history, redo, undo } from 'prosemirror-history'; import { keymap } from 'prosemirror-keymap'; -import { - Fragment, - type Node as PMNode, - type Schema, - Slice -} from 'prosemirror-model'; +import type { Node as PMNode, Schema } from 'prosemirror-model'; import { type Command, EditorState, - NodeSelection, Plugin, Selection, type Transaction } from 'prosemirror-state'; -import type { EditorView } from 'prosemirror-view'; -import { EXTERNAL, placeholderPlugin } from './core/base'; -import { - activeLink, - activeTextStyle, - editorCommands, - isBlockActive, - isMarkActive, - setLink -} from './core/commands'; -import { buildInputRules } from './core/input-rules'; -import { docFromJSON, type EditorJSON, emptyDoc } from './core/json'; -import { buildEditingKeymap } from './core/keymaps'; +import type { EditorView, NodeViewConstructor } from 'prosemirror-view'; +import { EXTERNAL, insertHardBreak, placeholderPlugin } from './core/base'; import { type MentionAttrs, mentionKey } from './core/mention'; +import { + deleteAdjacentMention, + moveOverMention +} from './core/mention-commands'; import { MentionNodeView, type MentionPortal, type MentionPortalRegistry } from './core/mention-node-view'; import { MentionRegistry } from './core/mention-registry'; -import type { EditorFormat } from './core/schema'; -import { - docToHTML, - docToText, - isEditorEmpty, - showsPlaceholder -} from './core/serializers'; +import { showsPlaceholder } from './core/serializers'; import type { EditorAction } from './core/shortcuts'; import { mentionTransaction, @@ -52,25 +31,51 @@ import { suggestionPlugin, suggestionPluginKey } from './core/suggestion-plugin'; -import { TaskItemView } from './core/task-item-view'; -import styles from './editor.module.css'; -import type { - EditorApi, - EditorChangeDetails, - EditorCommands, - EditorMarkdownChangeDetails, - MarkdownAdapter -} from './editor-types'; export interface EditorStoreProps { placeholder?: string; disabled: boolean; readOnly: boolean; - markdown?: MarkdownAdapter; - onValueChange?: ( - value: EditorJSON, - details: EditorChangeDetails | EditorMarkdownChangeDetails - ) => void; + /** Fires for each doc change that did not come from outside the editor. */ + onChange?: (doc: PMNode) => void; +} + +/** + * Behavior added on top of the core store. `Editor` adds the rich-text + * features through it. `PromptInput.Editor` adds its prompt keys. + */ +export interface EditorExtension { + /** Runs right after the suggestion plugin, so an open menu still gets its keys first. */ + first?: Plugin[]; + /** Commands for the shortcut actions. The core runs `undo` and `redo` itself. */ + commands?: Partial>; + /** Runs after the shortcut keymap and before the core keys. */ + keys?: Plugin[]; + /** Runs after the base keymap. */ + last?: Plugin[]; + nodeViews?: Record; + /** Called when the editor turns editable or not. */ + setEditable?: (editable: boolean) => void; + /** + * Whether the doc shows the placeholder. + * @default showsPlaceholder + */ + showsPlaceholder?: (doc: PMNode) => boolean; +} + +export interface EditorStoreOptions { + schema: Schema; + doc: PMNode; + shortcuts: Record; + props: EditorStoreProps; + /** Read by the view host when it mounts. */ + autoFocus?: boolean | 'start' | 'end'; + /** Puts the first caret at the end of the doc. */ + selectAtEnd?: boolean; + /** Chip data shared with a component outside the editor. */ + mentions?: MentionRegistry; + /** Called once, before the plugins are built. */ + extend?: (store: EditorStore) => EditorExtension; } export interface EditorTriggerEntry extends SuggestionTrigger { @@ -83,61 +88,22 @@ export interface EditorMenuAria { activeOptionId?: string; } -interface Target { - priority: number; - run: () => boolean; -} - -const URL_PATTERN = /^(https?:\/\/|mailto:)\S+$/i; - // Dragging selected text ends with `dragend`, not `mouseup`. const POINTER_END_EVENTS = ['mouseup', 'pointerup', 'pointercancel', 'dragend']; -function run(targets: Set): boolean { - const sorted = [...targets].sort((a, b) => b.priority - a.priority); - return sorted.some(target => target.run()); -} - -function register(targets: Set, target: Target): () => void { - targets.add(target); - return () => { - targets.delete(target); - }; -} - -/** - * Pasted Markdown. A single paragraph pastes as inline content and takes the - * marks at the caret, as a plain-text paste does. - */ -function pastedSlice(state: EditorState, doc: PMNode): Slice { - const first = doc.firstChild; - if (doc.childCount !== 1 || first?.type !== state.schema.nodes.paragraph) { - return Slice.maxOpen(doc.content); - } - const marks = state.storedMarks ?? state.selection.$from.marks(); - const nodes: PMNode[] = []; - first.forEach(node => { - let set = node.marks; - for (const mark of marks) { - if (!mark.type.isInSet(set)) set = mark.addToSet(set); - } - nodes.push(node.mark(set)); - }); - return new Slice(Fragment.from(nodes), 0, 0); -} - /** - * The editor's state, view and wiring. `Editor` creates one, and every part - * reads it through context. The state lives here and not in the view, so a - * remounted `Editor.Content` keeps the doc and the history. + * The editor's state, view and wiring: dispatch, history, the suggestion + * menus, mention chips and the placeholder. The parts read it through + * context. The state lives here and not in the view, so a remounted view + * keeps the doc and the history. `RichEditorStore` adds what `Editor` needs + * on top of it. */ export class EditorStore { readonly schema: Schema; readonly shortcuts: Record; - readonly mentions = new MentionRegistry(); - readonly api: EditorApi; - /** Read by `Editor.Content` when it mounts. */ + readonly mentions: MentionRegistry; readonly autoFocus: boolean | 'start' | 'end'; + readonly nodeViews: Record; state: EditorState; view: EditorView | null = null; @@ -151,15 +117,9 @@ export class EditorStore { /** Bumped by every change a part can observe. */ revision = 0; - /** The last value this store emitted or loaded. */ - private lastValue: EditorJSON | string | undefined; - /** Markdown for docs the adapter has converted, so a controlled string that matches the doc does not reload it. */ - private readonly markdownCache = new WeakMap(); + private readonly extension: EditorExtension; private triggers = new Map(); - private toolbars = new Set(); - private linkOpeners = new Set(); private listeners = new Set<() => void>(); - private taskViews = new Set(); private group: Transaction | null = null; readonly portalRegistry: MentionPortalRegistry = { @@ -181,52 +141,23 @@ export class EditorStore { } }; - readonly nodeViews = { - mention: (node: PMNode) => new MentionNodeView(node, this.portalRegistry), - taskItem: ( - node: PMNode, - view: EditorView, - getPos: () => number | undefined - ) => { - const task: TaskItemView = new TaskItemView( - node, - view, - getPos, - { - item: styles['task-item'], - checkbox: styles['task-checkbox'], - content: styles['task-content'] - }, - () => { - this.taskViews.delete(task); - } - ); - this.taskViews.add(task); - return task; - } - }; - - constructor(options: { - schema: Schema; - value: EditorJSON | string | undefined; - shortcuts: Record; - props: EditorStoreProps; - autoFocus: boolean | 'start' | 'end'; - }) { + constructor(options: EditorStoreOptions) { this.schema = options.schema; this.shortcuts = options.shortcuts; this.props = options.props; - this.autoFocus = options.autoFocus; - this.lastValue = options.value; - const doc = - options.value === undefined - ? emptyDoc(this.schema) - : this.parse(options.value); + this.autoFocus = options.autoFocus ?? false; + this.mentions = options.mentions ?? new MentionRegistry(); + this.extension = options.extend?.(this) ?? {}; + this.nodeViews = { + mention: node => new MentionNodeView(node, this.portalRegistry), + ...this.extension.nodeViews + }; + const { doc } = options; this.state = EditorState.create({ doc, + selection: options.selectAtEnd ? Selection.atEnd(doc) : undefined, plugins: this.plugins() }); - this.api = this.createApi(); } // ---- subscription ---- @@ -264,112 +195,9 @@ export class EditorStore { run = (command: Command): boolean => command(this.state, this.dispatch, this.view ?? undefined); - private report(doc: PMNode): void { - const onValueChange = this.props.onValueChange; - if (!onValueChange) { - this.lastValue = undefined; - return; - } - const value = doc.toJSON() as EditorJSON; - this.lastValue = value; - onValueChange(value, this.details(doc, value)); - } - - private details( - doc: PMNode, - value: EditorJSON - ): EditorChangeDetails | EditorMarkdownChangeDetails { - const details: EditorChangeDetails = { - empty: isEditorEmpty(doc), - getMentions: () => docToText(doc).mentions, - getText: () => docToText(doc).text, - getHTML: () => docToHTML(doc) - }; - const adapter = this.props.markdown; - if (!adapter) return details; - return { - ...details, - getMarkdown: () => this.markdownOf(doc, adapter, value) - }; - } - - private markdownOf( - doc: PMNode, - adapter: MarkdownAdapter, - value?: EditorJSON - ): string { - let markdown = this.markdownCache.get(doc); - if (markdown === undefined) { - markdown = adapter.fromEditor(value ?? (doc.toJSON() as EditorJSON)); - this.markdownCache.set(doc, markdown); - } - return markdown; - } - - /** Loads a `value` or `defaultValue`. A string is Markdown. */ - parse(value: EditorJSON | string): PMNode { - if (typeof value !== 'string') return docFromJSON(this.schema, value); - const adapter = this.props.markdown; - if (adapter) return docFromJSON(this.schema, adapter.toEditor(value)); - if (process.env.NODE_ENV !== 'production') { - console.warn( - '[Apsara] Editor received a string value without the `markdown` ' + - 'prop. The string loads as plain text.' - ); - } - const paragraphs = value - .split(/\n{2,}/) - .map(text => - this.schema.nodes.paragraph.create( - null, - text ? this.schema.text(text) : null - ) - ); - return this.schema.topNodeType.create(null, paragraphs); - } - - /** - * Applies a controlled `value`. Nothing happens when it is the value the - * store last emitted, when a Markdown string is what the doc converts to, or - * when it loads to the doc the editor already has. - */ - reconcile(value: EditorJSON | string): void { - if (value === this.lastValue) return; - this.lastValue = value; - const adapter = this.props.markdown; - if ( - typeof value === 'string' && - adapter && - this.markdownOf(this.state.doc, adapter) === value - ) { - return; - } - const doc = this.parse(value); - if (doc.eq(this.state.doc)) return; - this.replaceState(doc); - } - - /** Loads `doc` with a new history, so Undo cannot step back past it. */ - private replaceState(doc: PMNode): void { - const pos = Math.min(this.state.selection.from, doc.content.size); - this.state = EditorState.create({ - doc, - plugins: this.state.plugins, - selection: Selection.near(doc.resolve(pos)) - }); - this.view?.updateState(this.state); - this.emit(); - } - - private replaceDocTransaction(doc: PMNode): Transaction { - const tr = this.state.tr.replaceWith( - 0, - this.state.doc.content.size, - doc.content - ); - const pos = Math.min(this.state.selection.from, tr.doc.content.size); - tr.setSelection(Selection.near(tr.doc.resolve(pos))); - return tr; + /** Reports a change made in the editor. */ + protected report(doc: PMNode): void { + this.props.onChange?.(doc); } updateProps(next: EditorStoreProps): void { @@ -380,7 +208,7 @@ export class EditorStore { previous.readOnly !== next.readOnly ) { this.view?.setProps({ editable: () => this.isEditable() }); - for (const task of this.taskViews) task.setEditable(this.isEditable()); + this.extension.setEditable?.(this.isEditable()); this.emit(); } if (previous.placeholder !== next.placeholder) { @@ -450,8 +278,8 @@ export class EditorStore { // ---- plugins ---- private plugins(): Plugin[] { - const inputRules = buildInputRules(this.schema); - const plugins = [ + const { extension } = this; + return [ // First, so an open menu wins arrows, Enter, Tab and Escape. suggestionPlugin({ getTriggers: () => [...this.triggers.values()], @@ -462,50 +290,48 @@ export class EditorStore { onKeyDown: (event, state) => this.triggers.get(state.trigger)?.onKeyDown(event, state) ?? false }), + ...(extension.first ?? []), keymap(this.shortcutBindings()), - buildEditingKeymap(this.schema, { - redo: this.shortcuts.redo !== false - }), + ...(extension.keys ?? []), + keymap(this.coreBindings()), history(), keymap(baseKeymap), - dropCursor({ class: styles['drop-cursor'], color: false }), - gapCursor(), - placeholderPlugin(() => this.props.placeholder, showsPlaceholder), + ...(extension.last ?? []), + placeholderPlugin( + () => this.props.placeholder, + extension.showsPlaceholder ?? showsPlaceholder + ), this.eventsPlugin() ]; - if (inputRules) plugins.splice(3, 0, inputRules); - return plugins; } private shortcutBindings(): Record { - const commands: Record = { - bold: editorCommands.toggleMark('bold'), - italic: editorCommands.toggleMark('italic'), - underline: editorCommands.toggleMark('underline'), - strike: editorCommands.toggleMark('strike'), - code: editorCommands.toggleMark('code'), - link: () => this.openLink(), - paragraph: editorCommands.setParagraph(), - heading1: editorCommands.setHeading(1), - heading2: editorCommands.setHeading(2), - heading3: editorCommands.setHeading(3), - heading4: editorCommands.setHeading(4), - bulletList: editorCommands.toggleList('bulletList'), - orderedList: editorCommands.toggleList('orderedList'), - taskList: editorCommands.toggleList('taskList'), - blockquote: editorCommands.toggleBlock('blockquote'), - codeBlock: editorCommands.toggleBlock('codeBlock'), + const commands: Partial> = { + ...this.extension.commands, undo, - redo, - focusToolbar: () => this.focusToolbar() + redo }; const bindings: Record = {}; for (const [action, key] of Object.entries(this.shortcuts)) { - if (key) bindings[key] = commands[action as EditorAction]; + const command = commands[action as EditorAction]; + if (key && command) bindings[key] = command; } return bindings; } + /** Line breaks, chip keys and `Mod-y`, which redoes unless `redo` is off. */ + private coreBindings(): Record { + const bindings: Record = { + 'Shift-Enter': chainCommands(newlineInCode, insertHardBreak), + Backspace: deleteAdjacentMention(-1), + Delete: deleteAdjacentMention(1), + ArrowLeft: moveOverMention(-1), + ArrowRight: moveOverMention(1) + }; + if (this.shortcuts.redo !== false) bindings['Mod-y'] = redo; + return bindings; + } + private eventsPlugin(): Plugin { return new Plugin({ props: { @@ -526,59 +352,12 @@ export class EditorStore { this.emit(); return false; } - }, - handlePaste: (view, event) => { - const data = event.clipboardData; - if (!data) return false; - const text = data.getData('text/plain'); - const url = text.trim(); - - // A URL pasted over a selection links the selection. - if ( - !view.state.selection.empty && - URL_PATTERN.test(url) && - setLink(url)(view.state, view.dispatch) - ) { - return true; - } - - const adapter = this.props.markdown; - const { $from } = view.state.selection; - const marks = view.state.storedMarks ?? $from.marks(); - if ( - !adapter || - adapter.paste === false || - !text || - data.types.includes('text/html') || - $from.parent.type.spec.code || - marks.some(mark => mark.type.spec.code) - ) { - return false; - } - const doc = docFromJSON(this.schema, adapter.toEditor(text)); - view.dispatch( - view.state.tr - .replaceSelection(pastedSlice(view.state, doc)) - .scrollIntoView() - ); - return true; - }, - clipboardTextSerializer: (slice, view) => { - const adapter = this.props.markdown; - // A copied slice includes its parents up to the doc. - const doc = adapter?.copy - ? view.state.schema.topNodeType.createAndFill(null, slice.content) - : null; - if (adapter && doc) { - return adapter.fromEditor(doc.toJSON() as EditorJSON); - } - return slice.content.textBetween(0, slice.content.size, '\n\n'); } } }); } - // ---- menus, toolbars and links ---- + // ---- menus and mentions ---- registerTrigger(entry: EditorTriggerEntry): () => void { if ( @@ -682,133 +461,4 @@ export class EditorStore { tr.setMeta('addToHistory', false); this.dispatch(tr); }; - - registerToolbar(priority: number, focus: () => boolean): () => void { - return register(this.toolbars, { priority, run: focus }); - } - - focusToolbar(): boolean { - return run(this.toolbars); - } - - registerLinkOpener(priority: number, open: () => boolean): () => void { - return register(this.linkOpeners, { priority, run: open }); - } - - openLink(): boolean { - if (!this.isEditable() || !this.schema.marks.link) return false; - return run(this.linkOpeners); - } - - // ---- api ---- - - private commandSet( - runCommand: (command: Command) => boolean - ): EditorCommands { - return { - toggleMark: mark => runCommand(editorCommands.toggleMark(mark)), - setParagraph: () => runCommand(editorCommands.setParagraph()), - setHeading: level => runCommand(editorCommands.setHeading(level)), - toggleBlock: block => runCommand(editorCommands.toggleBlock(block)), - toggleList: list => runCommand(editorCommands.toggleList(list)), - setLink: href => runCommand(editorCommands.setLink(href)), - unsetLink: () => runCommand(editorCommands.unsetLink()), - insertHorizontalRule: () => - runCommand(editorCommands.insertHorizontalRule()), - insertText: text => runCommand(editorCommands.insertText(text)), - insertMention: (item, options) => - runCommand((state, dispatch) => { - if (!state.schema.nodes.mention) return false; - if (!dispatch) return true; - const trigger = - options?.trigger ?? this.mentions.triggers()[0] ?? '@'; - const type = item.type ?? 'mention'; - this.mentions.remember(trigger, { ...item, type }); - const tr = mentionTransaction(state, { - id: item.id, - label: item.label, - type, - trigger - }); - if (tr) dispatch(tr); - return true; - }), - clearFormatting: () => runCommand(editorCommands.clearFormatting()), - undo: () => runCommand(undo), - redo: () => runCommand(redo), - setContent: value => - runCommand((state, dispatch) => { - if (dispatch) dispatch(this.replaceDocTransaction(this.parse(value))); - return true; - }), - clear: () => - runCommand((state, dispatch) => { - if (dispatch) { - dispatch(this.replaceDocTransaction(emptyDoc(state.schema))); - } - return true; - }) - }; - } - - private createApi(): EditorApi { - const store = this; - return { - get view() { - return store.view; - }, - getState: () => store.state, - commands: this.commandSet(store.run), - can: this.commandSet(command => command(store.state)), - isActive: (format: EditorFormat, attrs?: Record) => - isFormatActive(store.state, format, attrs), - getJSON: () => store.state.doc.toJSON() as EditorJSON, - getText: () => docToText(store.state.doc).text, - getHTML: () => docToHTML(store.state.doc), - getMarkdown: () => { - const adapter = store.props.markdown; - if (!adapter) { - if (process.env.NODE_ENV !== 'production') { - console.error( - '[Apsara] Editor getMarkdown() needs the `markdown` prop. ' + - 'Pass MarkdownAdapter.create().' - ); - } - return null; - } - return store.markdownOf(store.state.doc, adapter); - }, - focus: position => store.focus(position) - }; - } -} - -export function isFormatActive( - state: EditorState, - format: EditorFormat, - attrs?: Record -): boolean { - switch (format) { - case 'bold': - case 'italic': - case 'underline': - case 'strike': - case 'code': - return isMarkActive(state, format); - case 'link': - return activeLink(state) !== null; - case 'heading': { - const style = activeTextStyle(state); - if (typeof style !== 'number') return false; - return attrs?.level === undefined || attrs.level === style; - } - case 'mention': - case 'horizontalRule': - return ( - state.selection instanceof NodeSelection && - state.selection.node.type.name === format - ); - default: - return isBlockActive(state, format); - } } diff --git a/packages/react/components/prompt-input/__tests__/prompt-input-markup.test.ts b/packages/react/components/prompt-input/__tests__/prompt-input-markup.test.ts index 0caeb7a9d..b33528ca1 100644 --- a/packages/react/components/prompt-input/__tests__/prompt-input-markup.test.ts +++ b/packages/react/components/prompt-input/__tests__/prompt-input-markup.test.ts @@ -1,20 +1,26 @@ import { describe, expect, it } from 'vitest'; -import { - deriveDocDetails, - docFromMarkup, - docFromText, - isDocEmpty, - serializeMarkup, - serializeText -} from '../../editor/core/composer/markup'; import { isTriggerCharacter, serializeMention, trimDetails } from '../../editor/core/mention'; +import { isEditorEmpty } from '../../editor/core/serializers'; +import { + deriveDocDetails, + docFromMarkup, + inlineFragmentFromText, + promptInputSchema +} from '../prompt-input-markup'; const derive = (markup: string) => deriveDocDetails(docFromMarkup(markup)); -const roundTrip = (markup: string) => serializeMarkup(docFromMarkup(markup)); +const roundTrip = (markup: string) => derive(markup).markup; + +/** A doc holding a plain string, the way a plain-text paste builds it. */ +const docFromText = (text: string) => + promptInputSchema.topNodeType.create( + null, + promptInputSchema.nodes.paragraph.create(null, inlineFragmentFromText(text)) + ); describe('markup dialect', () => { describe('triggers', () => { @@ -168,18 +174,18 @@ describe('markup dialect', () => { describe('emptiness', () => { it('is true for nothing and for whitespace', () => { - expect(isDocEmpty(docFromMarkup(''))).toBe(true); - expect(isDocEmpty(docFromMarkup(' '))).toBe(true); - expect(isDocEmpty(docFromMarkup('\n\n'))).toBe(true); + expect(isEditorEmpty(docFromMarkup(''))).toBe(true); + expect(isEditorEmpty(docFromMarkup(' '))).toBe(true); + expect(isEditorEmpty(docFromMarkup('\n\n'))).toBe(true); }); it('is false for a document holding nothing but a chip', () => { - expect(isDocEmpty(docFromMarkup('@[A](p:1)'))).toBe(false); - expect(isDocEmpty(docFromMarkup(' @[A](p:1) '))).toBe(false); + expect(isEditorEmpty(docFromMarkup('@[A](p:1)'))).toBe(false); + expect(isEditorEmpty(docFromMarkup(' @[A](p:1) '))).toBe(false); }); it('is false for text', () => { - expect(isDocEmpty(docFromMarkup('hi'))).toBe(false); + expect(isEditorEmpty(docFromMarkup('hi'))).toBe(false); }); }); @@ -215,7 +221,7 @@ describe('markup dialect', () => { }); it('splits newlines into hard breaks', () => { - expect(serializeText(docFromText('a\nb\nc'))).toBe('a\nb\nc'); + expect(deriveDocDetails(docFromText('a\nb\nc')).text).toBe('a\nb\nc'); }); }); }); diff --git a/packages/react/components/prompt-input/__tests__/prompt-input-mentions.test.tsx b/packages/react/components/prompt-input/__tests__/prompt-input-mentions.test.tsx index 9b48f29d1..8201d4366 100644 --- a/packages/react/components/prompt-input/__tests__/prompt-input-mentions.test.tsx +++ b/packages/react/components/prompt-input/__tests__/prompt-input-mentions.test.tsx @@ -323,7 +323,8 @@ describe('PromptInput.Mentions', () => { const active = editor.getAttribute('aria-activedescendant'); expect(active).toBeTruthy(); expect(screen.getAllByRole('option')[0]).toHaveAttribute('id', active); - expect(editor).toHaveAttribute('aria-expanded', 'true'); + // `role="textbox"` does not allow `aria-expanded`. + expect(editor).not.toHaveAttribute('aria-expanded'); expect(editor).toHaveAttribute( 'aria-controls', screen.getByRole('listbox').id diff --git a/packages/react/components/prompt-input/prompt-input-editor.tsx b/packages/react/components/prompt-input/prompt-input-editor.tsx index 42e83894b..66c136969 100644 --- a/packages/react/components/prompt-input/prompt-input-editor.tsx +++ b/packages/react/components/prompt-input/prompt-input-editor.tsx @@ -2,32 +2,35 @@ import { useMergedRefs } from '@base-ui/utils/useMergedRefs'; import { cx } from 'class-variance-authority'; +import { type Node as PMNode, Slice } from 'prosemirror-model'; +import { Selection } from 'prosemirror-state'; import { type ComponentProps, - Fragment, useCallback, useEffect, - useId, + useLayoutEffect, useMemo, useRef, useState } from 'react'; -import { createPortal } from 'react-dom'; -import { - deriveDocDetails, - docFromMarkup -} from '../editor/core/composer/markup'; -import { useComposerEditor } from '../editor/core/composer/use-composer-editor'; -import editorStyles from '../editor/core/editor-core.module.css'; -import { SuggestionMenu } from '../editor/core/suggestion-menu'; -import type { SuggestionState } from '../editor/core/suggestion-plugin'; -import { useMentionResolution } from '../editor/core/use-suggestion-menu'; +import { EXTERNAL } from '../editor/core/base'; +import { isEditorEmpty } from '../editor/core/serializers'; +import { resolveShortcuts } from '../editor/core/shortcuts'; +import { useMentionRegistryVersion } from '../editor/core/use-suggestion-menu'; +import { EditorHost } from '../editor/editor-content'; +import { MentionsMenu } from '../editor/editor-mentions'; +import { EditorStore, type EditorStoreProps } from '../editor/editor-store'; import styles from './prompt-input.module.css'; import { type PromptInputInputApi, usePromptInputContext } from './prompt-input-context'; -import { useMentionMenu } from './use-mention-menu'; +import { + deriveDocDetails, + docFromMarkup, + promptInputSchema +} from './prompt-input-markup'; +import { promptInputPlugins } from './prompt-input-plugins'; export interface PromptInputEditorProps extends Omit< @@ -54,9 +57,28 @@ export interface PromptInputEditorProps } /** - * The ProseMirror sibling to `PromptInput.Textarea`: the same outward contract, - * Enter submits, Shift+Enter breaks, placeholder, auto-grow, `disabled`, frame - * focus, on a contentEditable that can host inline mention chips. + * Replaces the doc when `markup` differs from what it serializes to, so a + * controlled `value` does not move the caret on every keystroke. The change is + * not reported and is not an undo step. + */ +function setMarkup(store: EditorStore, markup: string) { + const { doc } = store.state; + if (deriveDocDetails(doc).markup === markup) return; + const tr = store.state.tr.replace( + 0, + doc.content.size, + new Slice(docFromMarkup(markup).content, 0, 0) + ); + tr.setSelection(Selection.atEnd(tr.doc)) + .setMeta(EXTERNAL, true) + .setMeta('addToHistory', false); + store.dispatch(tr); +} + +/** + * The `Editor` engine as a sibling to `PromptInput.Textarea`: Enter submits, + * Shift+Enter breaks, with a placeholder, auto-grow, `disabled` and frame + * focus, on a contentEditable that can hold mention chips. */ export function PromptInputEditor({ className, @@ -68,99 +90,91 @@ export function PromptInputEditor({ ...props }: PromptInputEditorProps) { const context = usePromptInputContext('Editor'); - const listboxId = useId(); + const registry = context.mentions; const resolvedDisabled = disabled ?? context.disabled; - - const [suggestion, setSuggestion] = useState(null); const [frameWidth, setFrameWidth] = useState(undefined); - const setValueRef = useRef(context.setValue); - setValueRef.current = context.setValue; - const requestSubmitRef = useRef(context.requestSubmit); - requestSubmitRef.current = context.requestSubmit; - const registry = context.mentions; + const contextRef = useRef(context); + contextRef.current = context; + const maxLengthRef = useRef(maxLength); + maxLengthRef.current = maxLength; - // Broken out of the option object so the menu, which needs `actions`, can - // still supply the key handler the editor plugin calls. - const keyDownRef = useRef< - ((event: KeyboardEvent, state: SuggestionState) => boolean) | null - >(null); - - const { hostRef, initialHtml, viewRef, mentionPortals, actions } = - useComposerEditor({ - initialMarkup: context.value, - placeholder, - disabled: resolvedDisabled, - spellCheck, - maxLength, - getTriggers: () => registry.triggers(), - onChange: details => - setValueRef.current(details.markup, { - text: details.text, - mentions: details.mentions - }), - onSubmit: () => requestSubmitRef.current(), - onSuggestionChange: setSuggestion, - onSuggestionKeyDown: (event, state) => - keyDownRef.current?.(event, state) ?? false - }); - - const menu = useMentionMenu({ - viewRef, - actions, - registry, - suggestion, + const storeProps: EditorStoreProps = { + placeholder, disabled: resolvedDisabled, - listboxId + readOnly: false, + onChange: report + }; + + const [store] = useState( + () => + new EditorStore({ + schema: promptInputSchema, + doc: docFromMarkup(context.value), + // A restored draft opens with the caret after it. + selectAtEnd: true, + shortcuts: resolveShortcuts(), + props: storeProps, + mentions: registry, + extend: () => ({ + first: promptInputPlugins({ + onSubmit: () => contextRef.current.requestSubmit(), + getMaxLength: () => maxLengthRef.current + }), + // Whitespace alone keeps the placeholder, as it keeps `data-empty`. + showsPlaceholder: isEditorEmpty + }) + }) + ); + + function report(doc: PMNode) { + const { markup, text, mentions } = deriveDocDetails(doc); + contextRef.current.setValue(markup, { text, mentions }); + } + + useLayoutEffect(() => { + store.updateProps(storeProps); }); - keyDownRef.current = menu.handleKeyDown; - useMentionResolution( - registry, - context.details.mentions, - actions.refreshMentionLabels - ); + // The Editor applies labels from `resolveMentions` without reporting them. + // PromptInput reports them, so `onValueChange` carries the fresh label. + function refreshLabels(labels: Map) { + const before = store.state.doc; + store.refreshMentionLabels(labels); + if (store.state.doc !== before) report(store.state.doc); + } const api = useMemo( () => ({ - focus: () => actions.focus(), - setMarkup: markup => actions.setMarkup(markup), + focus: () => store.focus(), + setMarkup: markup => setMarkup(store, markup), deriveExternal: markup => { - const derived = deriveDocDetails(docFromMarkup(markup)); - return { text: derived.text, mentions: derived.mentions }; - }, - getMessage: () => { - const details = actions.getDetails(); - return { - markup: details.markup, - text: details.text, - mentions: details.mentions - }; + const { text, mentions } = deriveDocDetails(docFromMarkup(markup)); + return { text, mentions }; }, + getMessage: () => deriveDocDetails(store.state.doc), insertMention: (item, options) => { + const view = store.view; + if (!view) return; const trigger = options?.trigger ?? registry.triggers()[0] ?? '@'; const type = item.type ?? 'mention'; registry.remember(trigger, { ...item, type }); - actions.insertMention({ - id: item.id, - label: item.label, - type, - trigger - }); + // Not focused: the chip goes at the end of the draft. + const end = Selection.atEnd(store.state.doc).from; + store.insertMentionAt( + { id: item.id, label: item.label, type, trigger }, + view.hasFocus() ? undefined : { from: end, to: end } + ); } }), - [actions, registry] + [store, registry] ); const registerInput = context.registerInput; const register = useCallback( - (node: HTMLDivElement | null) => { - hostRef(node); - registerInput(node, api, 'editor'); - }, - [api, hostRef, registerInput] + (node: HTMLDivElement | null) => registerInput(node, api, 'editor'), + [api, registerInput] ); - const mergedRef = useMergedRefs(register, ref); // A caret is a zero-width anchor, so the menu cannot size itself from @@ -183,70 +197,32 @@ export function PromptInputEditor({ return () => observer.disconnect(); }, [frameRef]); - const hasMentions = registry.triggers().length > 0; + // `PromptInput.Mentions` only registers data, so the menus render here, + // next to the doc their query lives in. + useMentionRegistryVersion(registry); return ( <> -
- - {mentionPortals.map(portal => { - const item = registry.lookup( - portal.attrs.trigger, - portal.attrs.type, - portal.attrs.id - ); - return ( - - {item?.icon ? createPortal(item.icon, portal.iconTarget) : null} - {item?.trailing - ? createPortal(item.trailing, portal.trailingTarget) - : null} - - ); - })} - - {hasMentions ? ( - { - if (!next) menu.close(); - }} - loading={menu.loading} - loadingRowCount={menu.loadingRowCount} - emptyMessage={menu.emptyMessage} + {registry.triggers().map(trigger => ( + - ) : null} + ))} ); } diff --git a/packages/react/components/prompt-input/prompt-input-markup.ts b/packages/react/components/prompt-input/prompt-input-markup.ts new file mode 100644 index 000000000..f2fd4ce10 --- /dev/null +++ b/packages/react/components/prompt-input/prompt-input-markup.ts @@ -0,0 +1,147 @@ +import { + Fragment, + type Node as PMNode, + Schema, + Slice +} from 'prosemirror-model'; +import { + type EditorMention, + isTriggerCharacter, + type MentionAttrs, + readMention, + serializeMention +} from '../editor/core/mention'; +import { + hardBreakNodeSpec, + mentionNodeSpec, + paragraphNodeSpec +} from '../editor/core/nodes'; +import { docToText } from '../editor/core/serializers'; + +/** + * The nodes of `buildSchema(['mention'])`: no marks and no other blocks, so + * pasted HTML arrives as plain text. It is built from the shared specs, so + * the specs for the other formats are not bundled. + */ +export const promptInputSchema = new Schema({ + nodes: { + doc: { content: 'block+' }, + paragraph: paragraphNodeSpec, + text: { group: 'inline' }, + hardBreak: hardBreakNodeSpec, + mention: mentionNodeSpec + } +}); + +const { hardBreak, paragraph } = promptInputSchema.nodes; + +export interface PromptInputDocDetails { + /** Round-trippable markup, as in `"check @[DataTable](component:data-table)"`. */ + markup: string; + /** Plain text with each label inlined behind its trigger. */ + text: string; + /** Document order; duplicates preserved. */ + mentions: EditorMention[]; +} + +/** Inline content for a plain string, where newlines become hard breaks. */ +export function inlineFragmentFromText(text: string): Fragment { + const nodes: PMNode[] = []; + text.split('\n').forEach((line, index) => { + if (index > 0) nodes.push(hardBreak.create()); + if (line) nodes.push(promptInputSchema.text(line)); + }); + return Fragment.fromArray(nodes); +} + +/** + * Parses the markup dialect into a doc. Called only for `value` and + * `defaultValue`, never for typed or pasted input, so prose that happens to + * contain `@[…](…)` stays literal while it is being written. + */ +export function docFromMarkup(markup: string): PMNode { + const nodes: PMNode[] = []; + let literal = ''; + let index = 0; + + const flush = () => { + if (!literal) return; + nodes.push(promptInputSchema.text(literal)); + literal = ''; + }; + + while (index < markup.length) { + const char = markup[index]; + + if (char === '\n') { + flush(); + nodes.push(hardBreak.create()); + index += 1; + continue; + } + + if (markup[index + 1] === '[' && isTriggerCharacter(char)) { + const match = readMention(markup, index); + if (match) { + flush(); + nodes.push(promptInputSchema.nodes.mention.create(match.attrs)); + index = match.next; + continue; + } + } + + literal += char; + index += 1; + } + flush(); + + return promptInputSchema.topNodeType.create( + null, + paragraph.create(null, Fragment.fromArray(nodes)) + ); +} + +function markupLeaf(node: PMNode): string { + if (node.type.name === 'mention') { + return serializeMention(node.attrs as MentionAttrs); + } + return node.type.spec.leafText?.(node) ?? ''; +} + +/** + * Markup, text and mentions for a doc. Text blocks are separated by a blank + * line in both, as in `docToText`. + */ +export function deriveDocDetails(doc: PMNode): PromptInputDocDetails { + return { + markup: doc.textBetween(0, doc.content.size, '\n\n', markupLeaf), + ...docToText(doc) + }; +} + +/** The length of the text, where a chip counts as its trigger and label. */ +export function textLength(doc: PMNode): number { + return doc.textBetween(0, doc.content.size, '\n\n').length; +} + +/** + * Collapses a pasted slice to inline content: block boundaries become hard + * breaks, mentions keep their ids, and marks are dropped. + */ +export function flattenToInlineSlice(slice: Slice): Slice { + const nodes: PMNode[] = []; + + const walk = (fragment: Fragment) => { + fragment.forEach(child => { + if (child.isInline) { + nodes.push(child.mark([])); + return; + } + if (nodes.length) nodes.push(hardBreak.create()); + walk(child.content); + }); + }; + walk(slice.content); + + return new Slice(Fragment.fromArray(nodes), 0, 0); +} diff --git a/packages/react/components/prompt-input/prompt-input-plugins.ts b/packages/react/components/prompt-input/prompt-input-plugins.ts new file mode 100644 index 000000000..64b6c5d3a --- /dev/null +++ b/packages/react/components/prompt-input/prompt-input-plugins.ts @@ -0,0 +1,115 @@ +import { Slice } from 'prosemirror-model'; +import { Plugin, Selection } from 'prosemirror-state'; +import { EXTERNAL, insertHardBreak } from '../editor/core/base'; +import { + flattenToInlineSlice, + inlineFragmentFromText, + textLength +} from './prompt-input-markup'; + +export interface PromptInputPluginOptions { + /** Enter with no open menu. */ + onSubmit: () => void; + getMaxLength: () => number | undefined; +} + +/** + * What the Editor needs to work as a prompt box. The store runs these after + * its suggestion plugin, so an open menu still gets Enter first. + */ +export function promptInputPlugins({ + onSubmit, + getMaxLength +}: PromptInputPluginOptions): Plugin[] { + let everFocused = false; + let pointerFocus = false; + const markPointer = () => { + pointerFocus = true; + window.setTimeout(() => { + pointerFocus = false; + }, 0); + return false; + }; + + return [ + new Plugin({ + props: { + handleKeyDown(view, event) { + if (event.key !== 'Enter') return false; + // A composing Enter confirms the composition. It never submits and + // it never reaches the doc. + if (event.isComposing || event.keyCode === 229) return true; + if (event.shiftKey) return insertHardBreak(view.state, view.dispatch); + onSubmit(); + return true; + } + } + }), + + new Plugin({ + props: { + transformPasted: slice => flattenToInlineSlice(slice), + clipboardTextParser: text => + new Slice(inlineFragmentFromText(text), 0, 0) + } + }), + + // A bare `focus()` on an editing host places no caret. When focus comes + // from the frame and not from a press in the editor, the caret goes to + // the end, as a click past the end of a textarea's text does. + new Plugin({ + props: { + handleDOMEvents: { + mousedown: markPointer, + touchstart: markPointer, + focus: view => { + const first = !everFocused; + everFocused = true; + if (!first || pointerFocus) return false; + view.dispatch( + view.state.tr + .setSelection(Selection.atEnd(view.state.doc)) + .setMeta(EXTERNAL, true) + ); + return false; + } + } + } + }), + + // The editor is its own scroller, so the caret is brought into view in it + // only. ProseMirror's own scroll walks every scrollable ancestor, which + // moves the page under the composer by a pixel or two on an edit. + new Plugin({ + props: { + handleScrollToSelection(view) { + const host = view.dom as HTMLElement; + let coords: { top: number; bottom: number }; + try { + coords = view.coordsAtPos(view.state.selection.head); + } catch { + return true; + } + const box = host.getBoundingClientRect(); + if (coords.top < box.top) { + host.scrollTop -= box.top - coords.top; + } else if (coords.bottom > box.bottom) { + host.scrollTop += coords.bottom - box.bottom; + } + return true; + } + } + }), + + // A transaction filter, so paste and IME are capped too. + new Plugin({ + filterTransaction(transaction, current) { + const max = getMaxLength(); + if (max == null || !transaction.docChanged) return true; + if (transaction.getMeta(EXTERNAL)) return true; + const next = textLength(transaction.doc); + return next <= max || next <= textLength(current.doc); + } + }) + ]; +} diff --git a/packages/react/components/prompt-input/prompt-input.module.css b/packages/react/components/prompt-input/prompt-input.module.css index c325260c4..e88eaaa6e 100644 --- a/packages/react/components/prompt-input/prompt-input.module.css +++ b/packages/react/components/prompt-input/prompt-input.module.css @@ -66,7 +66,24 @@ padding: var(--rs-space-3); } -/* `PromptInput.Editor` shares the textarea's box inside the frame, with the same +/* `PromptInput.Editor`. The small font's own 16px line box is shorter than a + chip's icon and trailing slots, so the editor pairs the small font with the + regular line height from the Editor core, and the chip sizes itself to that + line, so the line box is the same height whatever a line holds. */ +.editor { + width: 100%; + overflow-y: auto; + color: var(--rs-color-foreground-base-primary); + font-family: var(--rs-font-body); + font-size: var(--rs-font-size-small); + letter-spacing: var(--rs-letter-spacing-small); +} + +.editor > p { + margin: 0; +} + +/* The editor shares the textarea's box inside the frame, with the same padding, floor and cap, minus `field-sizing`, which applies to form controls only: a contentEditable grows with its content natively. */ .root .editor { diff --git a/packages/react/components/prompt-input/use-mention-menu.ts b/packages/react/components/prompt-input/use-mention-menu.ts deleted file mode 100644 index ea2fb7b5c..000000000 --- a/packages/react/components/prompt-input/use-mention-menu.ts +++ /dev/null @@ -1,81 +0,0 @@ -'use client'; - -import type { EditorView } from 'prosemirror-view'; -import { useCallback } from 'react'; -import type { ComposerEditorActions } from '../editor/core/composer/use-composer-editor'; -import type { SuggestionState } from '../editor/core/suggestion-plugin'; -import { - type UseSuggestionMenuResult, - useMentionRegistryVersion, - useSuggestionMenu -} from '../editor/core/use-suggestion-menu'; -import type { - PromptInputMentionItem, - PromptInputMentionRegistry -} from './prompt-input-mention-registry'; - -export interface UseMentionMenuOptions { - viewRef: React.RefObject; - actions: ComposerEditorActions; - registry: PromptInputMentionRegistry; - suggestion: SuggestionState | null; - disabled: boolean; - listboxId: string; -} - -export interface UseMentionMenuResult - extends UseSuggestionMenuResult { - loadingRowCount: number; - emptyMessage: React.ReactNode; -} - -/** One menu for every registered trigger, driven by that trigger's config. */ -export function useMentionMenu({ - viewRef, - actions, - registry, - suggestion, - disabled, - listboxId -}: UseMentionMenuOptions): UseMentionMenuResult { - useMentionRegistryVersion(registry); - - const config = suggestion ? registry.get(suggestion.trigger) : undefined; - const open = !disabled && suggestion !== null && config !== undefined; - - const select = useCallback( - (item: PromptInputMentionItem, state: SuggestionState) => { - const type = item.type ?? 'mention'; - registry.remember(state.trigger, { ...item, type }); - actions.insertMention( - { - id: item.id, - label: item.label, - type, - trigger: state.trigger - }, - { from: state.from, to: state.to } - ); - }, - [actions, registry] - ); - - const menu = useSuggestionMenu({ - getView: () => viewRef.current, - suggestion, - open, - items: config?.items, - onSearch: config?.onSearch, - onSelect: select, - dismiss: actions.dismissSuggestion, - onOpenChange: config?.onOpenChange, - listboxId, - name: 'PromptInput.Mentions' - }); - - return { - ...menu, - loadingRowCount: config?.loadingRowCount ?? 3, - emptyMessage: config?.emptyMessage ?? 'No results' - }; -} From d26b448290653886da195b485e303f5856ed211f Mon Sep 17 00:00:00 2001 From: Rohan Chakraborty Date: Mon, 16 Nov 2026 11:55:51 +0530 Subject: [PATCH 2/2] fix: [prompt-input, editor] ignore mention labels that resolve after unmount A resolveMentions call that settled after PromptInput.Editor unmounted still changed the detached doc and called onValueChange. The label refresh now returns when the store has no view. EditorStore.rememberMention stores a mention item in the registry and returns its chip attrs. Editor.Mentions, the Editor insertMention command and the PromptInput insertMention use it. --- .../components/editor/editor-mentions.tsx | 10 +++----- .../components/editor/editor-rich-store.ts | 12 ++------- .../react/components/editor/editor-store.ts | 18 ++++++++++++- .../__tests__/prompt-input-mentions.test.tsx | 25 +++++++++++++++++++ .../prompt-input/prompt-input-editor.tsx | 9 +++---- 5 files changed, 52 insertions(+), 22 deletions(-) diff --git a/packages/react/components/editor/editor-mentions.tsx b/packages/react/components/editor/editor-mentions.tsx index 8cd1bd9a8..daf860f86 100644 --- a/packages/react/components/editor/editor-mentions.tsx +++ b/packages/react/components/editor/editor-mentions.tsx @@ -149,12 +149,10 @@ export function MentionsMenu({ items, onSearch, onSelect: (item, state) => { - const type = item.type ?? 'mention'; - registry.remember(state.trigger, { ...item, type }); - store.insertMentionAt( - { id: item.id, label: item.label, type, trigger: state.trigger }, - { from: state.from, to: state.to } - ); + store.insertMentionAt(store.rememberMention(item, state.trigger), { + from: state.from, + to: state.to + }); }, onOpenChange, name diff --git a/packages/react/components/editor/editor-rich-store.ts b/packages/react/components/editor/editor-rich-store.ts index 214f92d1e..734552928 100644 --- a/packages/react/components/editor/editor-rich-store.ts +++ b/packages/react/components/editor/editor-rich-store.ts @@ -399,16 +399,8 @@ export class RichEditorStore extends EditorStore { runCommand((state, dispatch) => { if (!state.schema.nodes.mention) return false; if (!dispatch) return true; - const trigger = - options?.trigger ?? this.mentions.triggers()[0] ?? '@'; - const type = item.type ?? 'mention'; - this.mentions.remember(trigger, { ...item, type }); - const tr = mentionTransaction(state, { - id: item.id, - label: item.label, - type, - trigger - }); + const attrs = this.rememberMention(item, options?.trigger); + const tr = mentionTransaction(state, attrs); if (tr) dispatch(tr); return true; }), diff --git a/packages/react/components/editor/editor-store.ts b/packages/react/components/editor/editor-store.ts index 28b7c4f54..f95c4d79a 100644 --- a/packages/react/components/editor/editor-store.ts +++ b/packages/react/components/editor/editor-store.ts @@ -21,7 +21,10 @@ import { type MentionPortal, type MentionPortalRegistry } from './core/mention-node-view'; -import { MentionRegistry } from './core/mention-registry'; +import { + type EditorMentionItem, + MentionRegistry +} from './core/mention-registry'; import { showsPlaceholder } from './core/serializers'; import type { EditorAction } from './core/shortcuts'; import { @@ -429,6 +432,19 @@ export class EditorStore { this.view?.focus(); } + /** + * Stores `item` in the mention registry and returns its chip attrs. The + * trigger defaults to the first registered one. + */ + rememberMention( + item: EditorMentionItem, + trigger = this.mentions.triggers()[0] ?? '@' + ): MentionAttrs { + const type = item.type ?? 'mention'; + this.mentions.remember(trigger, { ...item, type }); + return { id: item.id, label: item.label, type, trigger }; + } + insertMentionAt( attrs: MentionAttrs, range?: { from: number; to: number } diff --git a/packages/react/components/prompt-input/__tests__/prompt-input-mentions.test.tsx b/packages/react/components/prompt-input/__tests__/prompt-input-mentions.test.tsx index 8201d4366..21dad3484 100644 --- a/packages/react/components/prompt-input/__tests__/prompt-input-mentions.test.tsx +++ b/packages/react/components/prompt-input/__tests__/prompt-input-mentions.test.tsx @@ -799,6 +799,31 @@ describe('PromptInput.Mentions', () => { expect(resolveMentions).not.toHaveBeenCalled(); }); + + it('does not report a label that resolves after unmount', async () => { + let resolve: (items: PromptInputMentionItem[]) => void = () => undefined; + const resolveMentions = vi.fn( + () => + new Promise(done => { + resolve = done; + }) + ); + const onValueChange = vi.fn(); + const { unmount } = render( + + ); + + await waitFor(() => expect(resolveMentions).toHaveBeenCalled()); + unmount(); + resolve([{ id: 'data-table', label: 'DataTable v2', type: 'component' }]); + await flush(); + + expect(onValueChange).not.toHaveBeenCalled(); + }); }); describe('Requires an Editor', () => { diff --git a/packages/react/components/prompt-input/prompt-input-editor.tsx b/packages/react/components/prompt-input/prompt-input-editor.tsx index 66c136969..9265eecb0 100644 --- a/packages/react/components/prompt-input/prompt-input-editor.tsx +++ b/packages/react/components/prompt-input/prompt-input-editor.tsx @@ -139,6 +139,8 @@ export function PromptInputEditor({ // The Editor applies labels from `resolveMentions` without reporting them. // PromptInput reports them, so `onValueChange` carries the fresh label. function refreshLabels(labels: Map) { + // `resolveMentions` can settle after this part unmounts. + if (!store.view) return; const before = store.state.doc; store.refreshMentionLabels(labels); if (store.state.doc !== before) report(store.state.doc); @@ -156,18 +158,15 @@ export function PromptInputEditor({ insertMention: (item, options) => { const view = store.view; if (!view) return; - const trigger = options?.trigger ?? registry.triggers()[0] ?? '@'; - const type = item.type ?? 'mention'; - registry.remember(trigger, { ...item, type }); // Not focused: the chip goes at the end of the draft. const end = Selection.atEnd(store.state.doc).from; store.insertMentionAt( - { id: item.id, label: item.label, type, trigger }, + store.rememberMention(item, options?.trigger), view.hasFocus() ? undefined : { from: end, to: end } ); } }), - [store, registry] + [store] ); const registerInput = context.registerInput;