{ "$schema": "https://ui.shadcn.com/schema/registry-item.json", "name": "prompt-editor", "title": "Prompt Editor", "description": "A message field for a chat form: a text area that holds mention chips, sends on Enter through the Send button of its form and gives the message as text with each chip as a tag.", "dependencies": [ "platejs", "cn", "diff-match-patch-ts@^0.6.0" ], "registryDependencies": [ "https://platejs.org/r/inline-combobox.json", "https://platejs.org/r/mention.json" ], "files": [ { "path": "src/registry/components/editor/prompt-editor.tsx", "content": "'use client';\n\nimport { cn } from 'cn';\nimport {\n ContentSlice,\n type Descendant,\n editorCommands,\n ElementApi,\n NodeApi,\n txLocate,\n} from 'platejs';\nimport { MentionPlugin } from 'platejs/mention/react';\nimport {\n definePlugin,\n type EditableSiblingProps,\n EditorContent,\n EditorRoot,\n useCreateEditor,\n usePluginStore,\n} from 'platejs/react';\nimport * as React from 'react';\n// oxlint-disable-next-line react-doctor/no-flush-sync -- Enter presses Send in the same keydown, so a form that reads its own state must have rendered the text first.\nimport { flushSync } from 'react-dom';\n\nimport {\n InlineCombobox,\n InlineComboboxContent,\n InlineComboboxEmpty,\n InlineComboboxItem,\n rankOptions,\n useInlineComboboxQuery,\n} from './inline-combobox';\nimport { MentionElement } from './mention';\n\ntype PromptEditorItem = { label: string; ref: string };\n\nconst RECEIVE = 'prompt-editor-receive';\n\nconst MENTION_TAG =\n /]*[^\"<>\\s][^\"<>]*)\">([^<>]*)<\\/mention>/g;\n\nconst escapeText = (text: string) =>\n text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');\n\nconst unescapeText = (text: string) =>\n text\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('"', '\"')\n .replaceAll('&', '&');\n\nconst isMention = (\n node: Descendant,\n mentionType: string\n): node is Descendant & { ref: string; label?: string } =>\n ElementApi.isElementType(node, mentionType) && typeof node.ref === 'string';\n\nconst toMessage = (children: readonly Descendant[], mentionType: string) =>\n children\n .map((block) =>\n ElementApi.isElement(block)\n ? block.children\n .map((node) =>\n isMention(node, mentionType)\n ? `${escapeText(node.label ?? node.ref)}`\n : NodeApi.string(node)\n )\n .join('')\n : ''\n )\n .join('\\n');\n\nconst toValue = (message: string, mentionType: string) =>\n message.split('\\n').map((line) => {\n const children: Descendant[] = [];\n let end = 0;\n\n for (const tag of line.matchAll(MENTION_TAG)) {\n children.push(\n { text: line.slice(end, tag.index) },\n {\n children: [{ text: '' }],\n label: unescapeText(tag[2]),\n ref: unescapeText(tag[1]),\n type: mentionType,\n }\n );\n end = tag.index + tag[0].length;\n }\n\n children.push({ text: line.slice(end) });\n\n return { children, type: 'paragraph' };\n });\n\nconst menuShowsMatch = (root: HTMLElement) => {\n const listbox = root.getAttribute('aria-controls');\n\n return (\n !!listbox &&\n !!root.ownerDocument\n .getElementById(listbox)\n ?.querySelector('[role=\"option\"]')\n );\n};\n\nconst PromptEditorPlugin = definePlugin('promptEditor', {\n initialState: (): {\n items: readonly PromptEditorItem[];\n report: () => void;\n } => ({ items: [], report: () => {} }),\n}).extend(({ editor, store }) => ({\n commands: ({ around }) => [\n // A chip pasted from another document keeps its id only when this field\n // offers the same item, because the id may name something else here.\n around(editorCommands.replaceSlice, ({ input, next }) => {\n const { items } = store.get();\n const mentionType = editor.plugin(MentionPlugin).schema.type;\n const keepKnownChips = (nodes: readonly Descendant[]): Descendant[] =>\n nodes.map((node) => {\n if (!ElementApi.isElement(node)) return node;\n if (!isMention(node, mentionType)) {\n return { ...node, children: keepKnownChips(node.children) };\n }\n\n const label = node.label ?? node.ref;\n\n return items.some(\n (item) => item.ref === node.ref && item.label === label\n )\n ? node\n : { text: label };\n });\n\n return next({\n ...input,\n slice: ContentSlice.withContent(\n input.slice,\n keepKnownChips(input.slice.content),\n { open: 'preserve' }\n ),\n });\n }),\n ],\n shortcuts: {\n send: {\n keys: 'alt?+ctrl?+meta?+enter',\n handler: () => {\n const root = editor.api.dom.root();\n const form = root?.closest('form');\n\n if (!root || menuShowsMatch(root) || !form) return;\n\n flushSync(store.get().report);\n\n const send = Array.from(form.elements).find(\n (control): control is HTMLButtonElement | HTMLInputElement =>\n (control instanceof HTMLButtonElement ||\n control instanceof HTMLInputElement) &&\n control.type === 'submit'\n );\n\n if (send && !send.disabled) send.click();\n },\n },\n },\n update: ({ tx }) => ({\n setMessage: txLocate(false, (message: string) => {\n const hadSelection = tx.selection() !== null;\n\n tx.value.replace({\n children: toValue(message, editor.plugin(MentionPlugin).schema.type),\n });\n\n const end = tx.points.end([]);\n\n if (hadSelection && end) tx.selection.set(end);\n }),\n }),\n}));\n\nfunction PromptEditorCombobox({ editableRef }: EditableSiblingProps) {\n return (\n \n \n \n );\n}\n\nfunction PromptEditorOptions() {\n const items = usePluginStore(PromptEditorPlugin, 'items');\n const query = useInlineComboboxQuery();\n const options = React.useMemo(\n () =>\n rankOptions(\n items.map((item) => ({ ...item, keywords: [item.ref] })),\n query\n ).slice(0, 50),\n [items, query]\n );\n\n return (\n \n No results\n\n {options.map((item) => (\n {\n tx.plugin(MentionPlugin).insert({\n label: item.label,\n ref: item.ref,\n });\n }}\n >\n {item.label}\n {item.ref}\n \n ))}\n \n );\n}\n\n/**\n * A message field for a chat form: a text area that also holds chips. Enter\n * presses the form's Send button, and the message is the typed text with each\n * chip as `label`.\n */\nexport function PromptEditor({\n className,\n disabled,\n items,\n name,\n placeholder,\n ref,\n value,\n onChange,\n onFiles,\n}: {\n className?: string;\n disabled?: boolean;\n /** What the @ menu offers. Without items, a typed @ stays text. */\n items?: readonly PromptEditorItem[];\n /** The key the message takes in the form's `FormData`. */\n name?: string;\n placeholder?: string;\n ref?: React.Ref<{ focus: () => void }>;\n /** The message. A value other than the last one reported replaces the text. */\n value?: string;\n /** Called with the message after each change, and before Enter sends. */\n onChange?: (message: string) => void;\n /** Called with the files of a paste or a drop, which never enter the text. */\n onFiles?: (files: File[]) => void;\n}) {\n const editor = useCreateEditor(\n {\n plugins: [\n MentionPlugin.configure({\n component: MentionElement,\n initialState: {\n insertSpaceAfterMention: true,\n triggerPreviousCharPattern: /^$|^[\\s\"']$/,\n triggerQuery: (current) =>\n current.plugin(PromptEditorPlugin).store.get().items.length > 0,\n },\n slots: { afterEditable: PromptEditorCombobox },\n }),\n PromptEditorPlugin,\n ],\n initialValue: ({ editor: created }) =>\n toValue(value ?? '', created.plugin(MentionPlugin).schema.type),\n },\n []\n );\n const prompt = editor.plugin(PromptEditorPlugin);\n const mentionType = editor.plugin(MentionPlugin).schema.type;\n const reported = React.useRef(value ?? '');\n // A parent that turns a change down keeps the same `value`, so React would\n // not render the field again to put that value back.\n const [, renderAgain] = React.useReducer((count: number) => count + 1, 0);\n const report = () => {\n const message = toMessage(editor.read.children(), mentionType);\n\n reported.current = message;\n onChange?.(message);\n if (value !== undefined) renderAgain();\n };\n\n React.useImperativeHandle(\n ref,\n () => ({ focus: () => editor.api.dom.focus() }),\n [editor]\n );\n\n React.useLayoutEffect(() => {\n prompt.store.set({ items: items ?? [], report });\n\n if (value === undefined || value === reported.current) return;\n\n reported.current = value;\n prompt.update({ history: 'skip', tags: RECEIVE }).setMessage(value);\n });\n\n React.useEffect(() => {\n const form = editor.api.dom.root()?.closest('form');\n\n if (!form) return undefined;\n\n const view = form.ownerDocument.defaultView;\n const onFormData = (event: FormDataEvent) => {\n if (name) {\n event.formData.set(\n name,\n toMessage(editor.read.children(), mentionType)\n );\n }\n };\n // The window hears a reset after every listener that can cancel it,\n // React's `onReset` included.\n const onReset = (event: Event) => {\n if (event.target !== form || event.defaultPrevented) return;\n\n prompt.update({ history: 'skip' }).setMessage('');\n };\n const onSubmit = () => {\n editor.api.react.settleInput();\n flushSync(prompt.store.get().report);\n };\n\n form.addEventListener('formdata', onFormData);\n form.addEventListener('submit', onSubmit, true);\n view?.addEventListener('reset', onReset);\n\n return () => {\n form.removeEventListener('formdata', onFormData);\n form.removeEventListener('submit', onSubmit, true);\n view?.removeEventListener('reset', onReset);\n };\n }, [editor, mentionType, name, prompt]);\n\n return (\n {\n if (!commit.tags.includes(RECEIVE)) report();\n }}\n >\n {\n if (disabled || !event.dataTransfer.types.includes('Files')) {\n return undefined;\n }\n\n event.preventDefault();\n\n return true;\n }}\n onDrop={(event) => {\n const files = Array.from(event.dataTransfer.files);\n\n if (files.length === 0) return undefined;\n if (!disabled && !event.defaultPrevented) {\n event.preventDefault();\n // A host's document drop listener would add the files again.\n event.stopPropagation();\n onFiles?.(files);\n }\n\n return true;\n }}\n onPaste={(event) => {\n const files = Array.from(event.clipboardData.files);\n\n if (files.length === 0) return undefined;\n\n event.preventDefault();\n if (!disabled) onFiles?.(files);\n\n return true;\n }}\n />\n \n );\n}\n", "type": "registry:component", "target": "@components/editor/prompt-editor.tsx" } ], "meta": { "docs": [ { "route": "/docs/prompt-editor" } ], "examples": [ "prompt-editor-demo" ] }, "type": "registry:component" }