Plate
PlateEditorsCreateTemplates
GitHub16kGitHub
DiscordDiscord
    • Stream
    • Copilot
    • Prompt Editor
  • Comments
  • Discussion
  • Suggestions
    • Basic Blocks
      • Blockquote
      • Heading
      • Horizontal Rule
    • Board
    • Callout
    • Code Block
    • Column
    • Date
    • Equation
    • FieldExperimental
    • Link
    • Media
    • MentionElement
    • Table
    • Table of Contents
    • Footnote
    • Details
  • Marks
    • Bold
    • Italic
    • Underline
    • Code
    • Highlight
    • Keyboard Input
    • Strikethrough
    • Subscript
    • Superscript
      • Font
      • Line Height
      • Text Align
      • Clear Formatting
      • Format Painter
    • Indent
    • List
      • Exit Break
      • Single Block
      • Trailing Block
    • Autoformat
    • Block Menu
    • Block Placeholder
    • Combobox
      • Emoji
      • MentionElement
      • Slash Command
    • Drag & Drop
    • Navigation Feedback
    • Linting
    • Tabbable
    • Toolbar
    • Yjs
    • Multi SelectEditor
    • DOCX
    • HTML
    • Markdown

Prompt Editor

PreviousNext

A chat message field that holds @ chips and sends on Enter.

Prompt EditorMention
Loading…
CopilotComments

On This Page

InstallationUsageExamplesAI SDK chatAI ElementsAI Elements with its providerMessageBehaviorLimitsAPI ReferencePromptEditor
Build your editor
Production-ready AI template and reusable components.
Get all-access

PromptEditor is the message field of a chat form, in place of a text area. Typing @ opens a menu of the app's items, and a picked item becomes a chip. Enter presses the form's Send button. The message is a string, the typed text with each chip written as a <mention> tag.

Installation

npx shadcn@latest add @plate/prompt-editor

The registry item adds prompt-editor.tsx and the mention and inline-combobox items it imports.

Usage

'use client';
 
import * as React from 'react';
 
import { ArrowUpIcon } from 'lucide-react';
 
import { PromptEditor } from '@/components/editor/prompt-editor';
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
} from '@/components/ui/input-group';
 
const items = [
  { label: 'Spec', ref: 'docs/spec.md' },
  { label: 'Changelog', ref: 'docs/changelog.md' },
];
 
export function ChatForm({ onSend }: { onSend: (message: string) => void }) {
  const [message, setMessage] = React.useState('');
 
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        onSend(message);
        setMessage('');
      }}
    >
      <InputGroup>
        <PromptEditor
          items={items}
          placeholder="Ask anything..."
          value={message}
          onChange={setMessage}
        />
        <InputGroupAddon align="block-end">
          <InputGroupButton
            aria-label="Send"
            className="ml-auto rounded-full"
            disabled={!message.trim()}
            size="icon-sm"
            type="submit"
            variant="default"
          >
            <ArrowUpIcon />
          </InputGroupButton>
        </InputGroupAddon>
      </InputGroup>
    </form>
  );
}
'use client';
 
import * as React from 'react';
 
import { ArrowUpIcon } from 'lucide-react';
 
import { PromptEditor } from '@/components/editor/prompt-editor';
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
} from '@/components/ui/input-group';
 
const items = [
  { label: 'Spec', ref: 'docs/spec.md' },
  { label: 'Changelog', ref: 'docs/changelog.md' },
];
 
export function ChatForm({ onSend }
































Enter presses the form's first submit button, so the form sends from onSubmit as it does for a text area. Enter does nothing while that button is disabled, so disable it while the message is empty or a reply streams.

InputGroup keeps the height of one line until it holds a block addon. Without one, give it className="h-auto" so it grows with the field.

Examples

AI SDK chat

The demo sends the message and its attached files through the AI SDK's useChat, with a local transport that streams a fixed reply instead of calling a model. Pasted and dropped files go to onFiles, and removing one moves focus back to the field through its ref.

'use client';
 
import { Chat, useChat } from '@ai-sdk/react';
import {
  type ChatTransport,
  convertFileListToFileUIParts,
  convertToModelMessages,
  simulateReadableStream,
  type UIMessage,
  type UIMessageChunk,
  type UserContent,
} from 'ai';
import { ArrowUpIcon, FileTextIcon, PlusIcon, XIcon } from 'lucide-react';
import * as React from 'react';
 
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
} from '@/components/ui/input-group';
import { PromptEditor } from '@/components/editor/prompt-editor';
 
const mentionItems = [
  { label: 'Spec', ref: 'docs/spec.md' },
  { label: 'Changelog', ref: 'docs/changelog.md' },
];
 
const reply: UIMessageChunk[] = [
  { type: 'start' },
  { id: 'reply', type: 'text-start' },
  { delta: 'Message ', id: 'reply', type: 'text-delta' },
  { delta: 'received. ', id: 'reply', type: 'text-delta' },
  { delta: 'This ', id: 'reply', type: 'text-delta' },
  { delta: 'reply ', id: 'reply', type: 'text-delta' },
  { delta: 'streams ', id: 'reply', type: 'text-delta' },
  { delta: 'locally.', id: 'reply', type: 'text-delta' },
  { id: 'reply', type: 'text-end' },
  { type: 'finish' },
];
 
type ModelParts = Exclude<UserContent, string>;
 
const createLocalTransport = (
  onModelParts: (id: string, parts: ModelParts) => void
): ChatTransport<UIMessage> => ({
  reconnectToStream: () => Promise.resolve(null),
  sendMessages: async ({ messages }) => {
    const sent = messages.at(-1);
    const modelMessages = await convertToModelMessages(messages);
    const model = modelMessages.at(-1);
 
    if (sent && model?.role === 'user' && Array.isArray(model.content)) {
      onModelParts(sent.id, model.content);
    }
 
    return simulateReadableStream({ chunkDelayInMs: 250, chunks: reply });
  },
});
 
export default function PromptEditorDemo() {
  const [text, setText] = React.useState('');
  const [files, setFiles] = React.useState<Array<{ file: File; id: string }>>(
    []
  );
  const [modelParts, setModelParts] = React.useState<
    Record<string, ModelParts>
  >({});
  const [chat] = React.useState(
    () =>
      new Chat({
        transport: createLocalTransport((id, parts) =>
          setModelParts((current) => ({ ...current, [id]: parts }))
        ),
      })
  );
  const { messages, sendMessage, status } = useChat({ chat });
  const inputRef = React.useRef<HTMLInputElement>(null);
  const editorRef = React.useRef<{ focus: () => void }>(null);
  const [sending, setSending] = React.useState(false);
  const canSend = text.trim().length > 0 && !sending;
 
  const addFiles = (added: File[]) => {
    setFiles((current) => [
      ...current,
      ...added.map((file) => ({ file, id: crypto.randomUUID() })),
    ]);
  };
 
  return (
    <div className="mx-auto flex w-full max-w-lg flex-col gap-4 px-4 py-6">
      <ol className="flex flex-col gap-3 text-sm" data-slot="chat-messages">
        {messages.map((message) => (
          <li
            key={message.id}
            className="flex flex-col gap-1.5 rounded-md border p-3"
            data-role={message.role}
            data-slot="chat-message"
          >
            {message.role === 'user' ? (
              modelParts[message.id]?.map((part, index) => {
                if (part.type === 'text') {
                  return (
                    <p
                      // oxlint-disable-next-line react-doctor/no-array-index-as-key -- A sent message's parts never change.
                      key={index}
                      className="whitespace-pre-wrap"
                      data-slot="model-part"
                      data-type="text"
                    >
                      {part.text}
                    </p>
                  );
                }
                if (part.type !== 'file') return null;
 
                return (
                  <div
                    // oxlint-disable-next-line react-doctor/no-array-index-as-key -- A sent message's parts never change.
                    key={index}
                    className="flex min-w-0 items-center gap-2 font-mono text-xs text-muted-foreground"
                    data-filename={part.filename}
                    data-media-type={part.mediaType}
                    data-slot="model-part"
                    data-type="file"
                  >
                    <FileTextIcon className="size-4 shrink-0" />
                    <span className="shrink-0">{part.filename}</span>
                    <span className="truncate" data-slot="model-part-data">
                      {typeof part.data === 'string' ? part.data : null}
                    </span>
                  </div>
                );
              })
            ) : (
              <p className="whitespace-pre-wrap">
                {message.parts.map((part) =>
                  part.type === 'text' ? part.text : null
                )}
              </p>
            )}
          </li>
        ))}
      </ol>
      <form
        data-status={status}
        onSubmit={(event) => {
          event.preventDefault();
          if (!canSend) return;
 
          const attached = new DataTransfer();
 
          for (const { file } of files) attached.items.add(file);
          setText('');
          setFiles([]);
          setSending(true);
          void convertFileListToFileUIParts(attached.files)
            .then((parts) => sendMessage({ files: parts, text }))
            .finally(() => setSending(false));
        }}
      >
        <input
          ref={inputRef}
          className="sr-only"
          multiple
          tabIndex={-1}
          type="file"
          onChange={(event) => {
            addFiles(Array.from(event.target.files ?? []));
            event.target.value = '';
          }}
        />
        <InputGroup>
          {files.length > 0 && (
            <InputGroupAddon align="block-start" className="flex-wrap">
              {files.map(({ file, id }) => (
                <span
                  key={id}
                  className="flex items-center gap-1.5 rounded-md border py-0.5 pr-0.5 pl-2 text-xs text-foreground"
                  data-filename={file.name}
                  data-slot="attachment"
                >
                  <FileTextIcon />
                  {file.name}
                  <InputGroupButton
                    aria-label={`Remove ${file.name}`}
                    size="icon-xs"
                    onClick={() => {
                      setFiles((current) =>
                        current.filter((item) => item.id !== id)
                      );
                      editorRef.current?.focus();
                    }}
                  >
                    <XIcon />
                  </InputGroupButton>
                </span>
              ))}
            </InputGroupAddon>
          )}
          <PromptEditor
            ref={editorRef}
            value={text}
            onChange={setText}
            items={mentionItems}
            placeholder="Ask the agent to change your code..."
            onFiles={addFiles}
            className="p-3"
          />
          <InputGroupAddon align="block-end">
            <InputGroupButton
              aria-label="Attach files"
              className="rounded-full"
              size="icon-sm"
              variant="outline"
              onClick={() => inputRef.current?.click()}
            >
              <PlusIcon />
            </InputGroupButton>
            <InputGroupButton
              aria-label="Send"
              className="ml-auto rounded-full"
              disabled={!canSend}
              size="icon-sm"
              type="submit"
              variant="default"
            >
              <ArrowUpIcon />
            </InputGroupButton>
          </InputGroupAddon>
        </InputGroup>
      </form>
    </div>
  );
}
'use client';
 
import { Chat, useChat } from '@ai-sdk/react';
import {
  type ChatTransport,
  convertFileListToFileUIParts,
  convertToModelMessages,
  simulateReadableStream,
  type UIMessage,
  type UIMessageChunk,
  type UserContent,
} from 'ai';
import { ArrowUpIcon, FileTextIcon, PlusIcon, XIcon } from 'lucide-react';
import * as React from 'react';
 
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
} from '@/components/ui/input-group';





















































































































































































































AI Elements

AI Elements' PromptInput reads the message from the form's data under message, the name its own text area uses. Give the field that name and put it where PromptInputTextarea goes:

import {
  PromptInput,
  PromptInputBody,
  PromptInputFooter,
  PromptInputSubmit,
  PromptInputTools,
} from '@/components/ai-elements/prompt-input';
import { PromptEditor } from '@/components/editor/prompt-editor';
 
<PromptInput onSubmit={({ text }) => sendMessage({ text })}>
  <PromptInputBody>
    <PromptEditor items={items} name="message" placeholder="Ask anything..." />
  </PromptInputBody>
  <PromptInputFooter>
    <PromptInputTools />
    <PromptInputSubmit status={status} />
  </PromptInputFooter>
</PromptInput>;
import {
  PromptInput,
  PromptInputBody,
  PromptInputFooter,
  PromptInputSubmit,
  PromptInputTools,
} from '@/components/ai-elements/prompt-input';
import { PromptEditor } from '@/components/editor/prompt-editor';
 
<PromptInput onSubmit={({ text }) => sendMessage({ text })}>
  <PromptInputBody>
    <PromptEditor items={items} name="message" placeholder="Ask anything..." />
  </PromptInputBody>
  <PromptInputFooter>
    <PromptInputTools />
    <

PromptInput attaches the files dropped on its form itself. For pasted files, pass add from usePromptInputAttachments() as onFiles, in a component inside PromptInput.

AI Elements with its provider

Under PromptInputProvider, PromptInput reads the message from the provider instead of the form's data. Connect the field through value and onChange:

import {
  PromptInput,
  PromptInputBody,
  PromptInputProvider,
  usePromptInputController,
} from '@/components/ai-elements/prompt-input';
import { PromptEditor } from '@/components/editor/prompt-editor';
 
function MessageField() {
  const { textInput } = usePromptInputController();
 
  return (
    <PromptEditor
      items={items}
      value={textInput.value}
      onChange={textInput.setInput}
    />
  );
}
 
<PromptInputProvider>
  <PromptInput onSubmit={({ text }) => sendMessage({ text })}>
    <PromptInputBody>
      <MessageField />
    </PromptInputBody>
  </PromptInput>
</PromptInputProvider>;
import {
  PromptInput,
  PromptInputBody,
  PromptInputProvider,
  usePromptInputController,
} from '@/components/ai-elements/prompt-input';
import { PromptEditor } from '@/components/editor/prompt-editor';
 
function MessageField() {
  const { textInput } = usePromptInputController();
 
  return (
    <PromptEditor
      items={items}
      value={textInput.value}
      onChange={textInput.setInput}
    />
  );
}
 
<PromptInputProvider>
  <




Message

The message holds one line per paragraph, joined with \n. A chip is <mention ref="docs/spec.md">Spec</mention>. Its ref and label escape &, < and >, and its ref also escapes ". The rest of the text is what the user typed. The app's server reads each ref and gives the model what the chip points to.

A value sets the same shape back: each tag becomes a chip, and each \n starts a paragraph.

Behavior

  • Enter, and Ctrl, Cmd or Alt with Enter, press the form's first submit button. Enter outside a form or while that button is disabled sends nothing and keeps the draft.
  • Shift+Enter breaks the line.
  • Enter while an input method composes sends nothing.
  • With the @ menu showing a match, Enter and Tab pick it. When the menu finds nothing, Enter sends the typed text.
  • Without items, a typed @ stays text.
  • A pasted or dropped file goes to onFiles and never into the text. A disabled field passes no file on.
  • A paste keeps plain lines and chips only. A pasted chip stays a chip when items holds its ref and label, and becomes its label as text otherwise.
  • A form reset that no listener cancels clears the field.
  • A value other than the last message the field reported replaces the text and puts the caret at the end. A change the app turns down, such as one past a length limit, puts the app's value back, as a controlled text area does.

Edit PromptEditorPlugin in the copied prompt-editor.tsx to change these rules.

Limits

  • The field fires no input event while the user types, so a form onInput listener never runs for it. Read changes through onChange.
  • A class that changes the field's minimum height needs !, such as min-h-24!, because the editable sets an inline minimum height while the placeholder shows.
  • AI Elements clears the field whenever it clears its own text area. That includes a send the app refuses without the provider and a failed send with it.

API Reference

PromptEditor

Props

    What the @ menu offers. The menu matches the start of any word in a label, or the start of a ref.

    The key the message takes in the form's FormData.

    The message of a controlled field.

    Called with the message after each change, and before Enter sends.

    Called with the files of a paste or a drop.

    The text shown while the field is empty.

    Turns off editing and file handling.

    Classes for the editable.

    Gives the app focus().

:
{
onSend
:
(
message
:
string
)
=>
void
}) {
const [message, setMessage] = React.useState('');
return (
<form
onSubmit={(event) => {
event.preventDefault();
onSend(message);
setMessage('');
}}
>
<InputGroup>
<PromptEditor
items={items}
placeholder="Ask anything..."
value={message}
onChange={setMessage}
/>
<InputGroupAddon align="block-end">
<InputGroupButton
aria-label="Send"
className="ml-auto rounded-full"
disabled={!message.trim()}
size="icon-sm"
type="submit"
variant="default"
>
<ArrowUpIcon />
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
</form>
);
}
import
{ PromptEditor }
from
'@/components/editor/prompt-editor'
;
const mentionItems = [
{ label: 'Spec', ref: 'docs/spec.md' },
{ label: 'Changelog', ref: 'docs/changelog.md' },
];
const reply: UIMessageChunk[] = [
{ type: 'start' },
{ id: 'reply', type: 'text-start' },
{ delta: 'Message ', id: 'reply', type: 'text-delta' },
{ delta: 'received. ', id: 'reply', type: 'text-delta' },
{ delta: 'This ', id: 'reply', type: 'text-delta' },
{ delta: 'reply ', id: 'reply', type: 'text-delta' },
{ delta: 'streams ', id: 'reply', type: 'text-delta' },
{ delta: 'locally.', id: 'reply', type: 'text-delta' },
{ id: 'reply', type: 'text-end' },
{ type: 'finish' },
];
type ModelParts = Exclude<UserContent, string>;
const createLocalTransport = (
onModelParts: (id: string, parts: ModelParts) => void
): ChatTransport<UIMessage> => ({
reconnectToStream: () => Promise.resolve(null),
sendMessages: async ({ messages }) => {
const sent = messages.at(-1);
const modelMessages = await convertToModelMessages(messages);
const model = modelMessages.at(-1);
if (sent && model?.role === 'user' && Array.isArray(model.content)) {
onModelParts(sent.id, model.content);
}
return simulateReadableStream({ chunkDelayInMs: 250, chunks: reply });
},
});
export default function PromptEditorDemo() {
const [text, setText] = React.useState('');
const [files, setFiles] = React.useState<Array<{ file: File; id: string }>>(
[]
);
const [modelParts, setModelParts] = React.useState<
Record<string, ModelParts>
>({});
const [chat] = React.useState(
() =>
new Chat({
transport: createLocalTransport((id, parts) =>
setModelParts((current) => ({ ...current, [id]: parts }))
),
})
);
const { messages, sendMessage, status } = useChat({ chat });
const inputRef = React.useRef<HTMLInputElement>(null);
const editorRef = React.useRef<{ focus: () => void }>(null);
const [sending, setSending] = React.useState(false);
const canSend = text.trim().length > 0 && !sending;
const addFiles = (added: File[]) => {
setFiles((current) => [
...current,
...added.map((file) => ({ file, id: crypto.randomUUID() })),
]);
};
return (
<div className="mx-auto flex w-full max-w-lg flex-col gap-4 px-4 py-6">
<ol className="flex flex-col gap-3 text-sm" data-slot="chat-messages">
{messages.map((message) => (
<li
key={message.id}
className="flex flex-col gap-1.5 rounded-md border p-3"
data-role={message.role}
data-slot="chat-message"
>
{message.role === 'user' ? (
modelParts[message.id]?.map((part, index) => {
if (part.type === 'text') {
return (
<p
// oxlint-disable-next-line react-doctor/no-array-index-as-key -- A sent message's parts never change.
key={index}
className="whitespace-pre-wrap"
data-slot="model-part"
data-type="text"
>
{part.text}
</p>
);
}
if (part.type !== 'file') return null;
return (
<div
// oxlint-disable-next-line react-doctor/no-array-index-as-key -- A sent message's parts never change.
key={index}
className="flex min-w-0 items-center gap-2 font-mono text-xs text-muted-foreground"
data-filename={part.filename}
data-media-type={part.mediaType}
data-slot="model-part"
data-type="file"
>
<FileTextIcon className="size-4 shrink-0" />
<span className="shrink-0">{part.filename}</span>
<span className="truncate" data-slot="model-part-data">
{typeof part.data === 'string' ? part.data : null}
</span>
</div>
);
})
) : (
<p className="whitespace-pre-wrap">
{message.parts.map((part) =>
part.type === 'text' ? part.text : null
)}
</p>
)}
</li>
))}
</ol>
<form
data-status={status}
onSubmit={(event) => {
event.preventDefault();
if (!canSend) return;
const attached = new DataTransfer();
for (const { file } of files) attached.items.add(file);
setText('');
setFiles([]);
setSending(true);
void convertFileListToFileUIParts(attached.files)
.then((parts) => sendMessage({ files: parts, text }))
.finally(() => setSending(false));
}}
>
<input
ref={inputRef}
className="sr-only"
multiple
tabIndex={-1}
type="file"
onChange={(event) => {
addFiles(Array.from(event.target.files ?? []));
event.target.value = '';
}}
/>
<InputGroup>
{files.length > 0 && (
<InputGroupAddon align="block-start" className="flex-wrap">
{files.map(({ file, id }) => (
<span
key={id}
className="flex items-center gap-1.5 rounded-md border py-0.5 pr-0.5 pl-2 text-xs text-foreground"
data-filename={file.name}
data-slot="attachment"
>
<FileTextIcon />
{file.name}
<InputGroupButton
aria-label={`Remove ${file.name}`}
size="icon-xs"
onClick={() => {
setFiles((current) =>
current.filter((item) => item.id !== id)
);
editorRef.current?.focus();
}}
>
<XIcon />
</InputGroupButton>
</span>
))}
</InputGroupAddon>
)}
<PromptEditor
ref={editorRef}
value={text}
onChange={setText}
items={mentionItems}
placeholder="Ask the agent to change your code..."
onFiles={addFiles}
className="p-3"
/>
<InputGroupAddon align="block-end">
<InputGroupButton
aria-label="Attach files"
className="rounded-full"
size="icon-sm"
variant="outline"
onClick={() => inputRef.current?.click()}
>
<PlusIcon />
</InputGroupButton>
<InputGroupButton
aria-label="Send"
className="ml-auto rounded-full"
disabled={!canSend}
size="icon-sm"
type="submit"
variant="default"
>
<ArrowUpIcon />
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
</form>
</div>
);
}
PromptInputSubmit
status
=
{status} />
</PromptInputFooter>
</PromptInput>;
PromptInput
onSubmit
=
{({
text
})
=>
sendMessage
({ text })}>
<PromptInputBody>
<MessageField />
</PromptInputBody>
</PromptInput>
</PromptInputProvider>;