For the complete documentation index, see llms.txt. Markdown variants are available by appending .md to any URL or sending an Accept: text/markdown header. An agent skill is available at /.well-known/agent-skills/site-skill.md.
18

Prompt Input

A composable message composer with auto-growing input, file attachments, mentions, model selection, and streaming controls.

raven.jpg
34%

brand-assets.zip

"use client";

import { useEffect, useRef, useState } from "react";

Installation

$ pnpm dlx shadcn@latest add https://motif.sweetretry.com/r/prompt-input.json

Pulls in attachment and dropdown-menu; PromptInputEditor and PromptInputTrigger also include Tiptap.

Usage

import { useState } from "react";
 
import {
  ModelPicker,
  PromptInput,
  PromptInputAttach,
  PromptInputAttachment,
  PromptInputFooter,
  PromptInputHeader,
  PromptInputSubmit,
  PromptInputTextarea,
  type PromptAttachment,
  type PromptModel,
} from "@/components/ui/motif/prompt-input";
 
const MODELS: PromptModel[] = [
  { id: "gpt-5.2", name: "GPT-5.2", provider: "openai" },
  { id: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", provider: "anthropic" },
  { id: "gemini-3-pro", name: "Gemini 3 Pro", provider: "gemini" },
];
 
export function Composer() {
  const [model, setModel] = useState(MODELS[0].id);
  const [attachments, setAttachments] = useState<PromptAttachment[]>([]);
 
  return (
    <PromptInput onSubmit={(message) => send({ message, model })}>
      <PromptInputHeader>
        {attachments.map(({ id, ...chip }) => (
          <PromptInputAttachment
            key={id}
            {...chip}
            onRemove={() =>
              setAttachments((current) =>
                current.filter((file) => file.id !== id)
              )
            }
          />
        ))}
      </PromptInputHeader>
 
      <PromptInputTextarea placeholder="Review the current implementation and suggest the next improvement." />
 
      <PromptInputFooter>
        <PromptInputAttach onFiles={(files) => upload(files, setAttachments)} />
        <ModelPicker models={MODELS} onValueChange={setModel} value={model} />
        <PromptInputSubmit />
      </PromptInputFooter>
    </PromptInput>
  );
}

Uncontrolled drafts clear on submit; pass value and onValueChange to control the draft yourself (onSubmit receives trimmed text).

Parts

PartRole
PromptInputRoot card, draft state, and submit contract
PromptInputHeaderFlex row above the field; renders nothing when empty
PromptInputTextareaAuto-growing textarea with two-line floor and Enter binding
PromptInputEditorRich-text document field for mentions and slash commands
PromptInputTriggerTrigger character and menu config inside PromptInputEditor
PromptInputFooterFlex row below the field
PromptInputAttachmentAnimated attachment chip
PromptInputButtonPlatform button at size-10 rounded-full
PromptInputAttachFile picker button; renders nothing without onFiles
PromptInputSubmitSubmit or stop button; disabled when the draft is empty
ModelPickerStandalone model selector
  • PromptInputTextarea, PromptInputEditor, PromptInputAttach, and PromptInputSubmit read root context and must sit inside PromptInput.
  • The field starts at two lines, grows up to maxHeight (200px default), and then scrolls.
  • Enter submits, Shift+Enter inserts a newline, and IME composition Enter is ignored.

Mentions and commands

"use client";

import { useEffect, useRef, useState } from "react";
<PromptInput onSubmit={(text, segments) => send(segments)}>
  <PromptInputEditor placeholder="Type @ to point at a file, / to run a command.">
    <PromptInputTrigger char="@" items={files} />
    <PromptInputTrigger
      char="/"
      items={commands}
      lineStart
      onSelect={(item) => (item.id === "clear" ? false : undefined)}
    />
  </PromptInputEditor>
  <PromptInputFooter>
    <PromptInputSubmit />
  </PromptInputFooter>
</PromptInput>
  • PromptInputTrigger configures a trigger character (lineStart restricts it to line start; items accepts an array or search function).
  • Arrow keys navigate, Enter or Tab selects, Escape closes, and returning false from onSelect runs the command without inserting text.
  • onSubmit receives (text, segments) where mentions keep their id; setting value externally resets the document to plain text.
type PromptSegment =
  | { type: "text"; text: string }
  | { type: "mention"; trigger: string; id: string; label: string };

Models

ModelPicker accepts { id, name, provider }[] (controlled via value/onValueChange or uncontrolled via defaultValue) and opens upward. ProviderLogo (from Provider Logo) and PROVIDER_NAMES are re-exported; monochrome marks inherit text-* color classes while colored marks ignore them.

import { ProviderLogo } from "@/components/ui/motif/provider-logo";
 
<ProviderLogo className="size-5 text-foreground" provider="anthropic" />;

Streaming

  • Passing streaming swaps PromptInputSubmit to a stop button (onStop) and blocks Enter submission.
  • Pass onQueue to queue drafts on Enter while streaming (e.g. for Queue).
"use client";

import { useEffect, useRef, useState } from "react";

Props

PromptInput

PropDefaultMeaning
value—Controlled draft, never cleared by a send
defaultValue""Draft the composer starts with
onValueChange—Called with the draft on every change
onSubmit—Called with the trimmed draft and its segments; Enter or submit
streamingfalseSwaps the submit part's arrow for stop, and blocks Enter
onStop—Called when the stop face is pressed
onQueue—Under streaming, called with the draft on Enter in place of onSubmit
disabledfalseDisables the field and the submit button
className—Extra classes for the card

Extra props pass through to the underlying form.

Parts

PartProps
PromptInputTextareamaxHeight, plus textarea props; onKeyDown runs before the binding
PromptInputEditormaxHeight, placeholder, plus div props; PromptInputTrigger children
PromptInputTriggerchar, items, lineStart, onSelect
PromptInputAttachmentAttachmentProps — name, src, progress, status, icon, onRemove
PromptInputAttachonFiles, accept, plus ButtonProps
PromptInputSubmitButtonProps; className lands on the button
PromptInputButtonButtonProps — variant, size, sound, haptic; geometry fixed
PromptInputHeader / PromptInputFooterdiv props
ModelPickermodels, value, defaultValue, onValueChange, className

Component source

prompt-input/index.tsx
"use client";

import type { FormEvent } from "react";
import { useCallback, useMemo, useRef, useState } from "react";

import { cn } from "@/lib/utils";

import { PromptInputContext } from "./context";
import type { PromptInputState } from "./context";
import type { PromptInputProps, PromptSegment } from "./types";

export { PromptInputEditor } from "./editor";
export { PromptInputTrigger } from "./trigger";
export {
  PromptInputAttach,
  PromptInputAttachment,
  PromptInputButton,
  PromptInputFooter,
  PromptInputHeader,
  PromptInputSubmit,
  PromptInputTextarea,
} from "./parts";
export { ModelPicker } from "./model-picker";
// Re-exported so a composer that hands its own model list over does not have to reach
// for a second import path to draw the marks on it.
export {
  PROVIDER_NAMES,
  ProviderLogo,
} from "@/components/ui/motif/provider-logo";
export type {
  ModelPickerProps,
  PromptAttachment,
  PromptInputAttachProps,
  PromptInputButtonProps,
  PromptInputEditorProps,
  PromptInputProps,
  PromptInputTextareaProps,
  PromptInputTriggerProps,
  PromptModel,
  PromptSegment,
  PromptTriggerItem,
} from "./types";
export type {
  ProviderId,
  ProviderLogoProps,
} from "@/components/ui/motif/provider-logo";

/* -- The composer --------------------------------------------------------------
 * Everything an agent surface asks for passes through one box, so the box is mostly the
 * sentence: the field owns the middle, and the row under it holds only the things a
 * message can carry besides its text — what rides with it, and who answers it — plus the
 * one action that ends the turn.
 *
 * The root owns the state and draws nothing but the card. What goes in it is assembled
 * from parts: `PromptInputHeader`, `PromptInputTextarea`, `PromptInputFooter`, and
 * whatever is dropped into them. A composer is where a surface grows its own
 * conventions — a tools menu, a microphone, a quoted reply, no attach button at all —
 * and every one of those is an arrangement of these pieces rather than a prop this
 * component has to learn about first.
 *
 * Four decisions the parts inherit:
 *
 *  - Enter sends, Shift+Enter breaks the line. A composer is typed into and then sent
 *    far more often than it is made to hold a second line; the reverse is right for a
 *    form, not for this. The composition guard matters as much as the binding: an IME's
 *    Enter commits the candidate under it, and sending on that key would eat the word
 *    the user was still assembling.
 *
 *  - The field grows to its content and then scrolls, instead of pushing the card
 *    taller, and it never shrinks below two lines.
 *
 *  - Nothing is drawn that cannot do anything: no attach button without `onFiles`, no
 *    header without chips. A dead control is worse than a missing one — it costs a click
 *    to find out, and it teaches the user that this surface has parts that lie.
 *
 *  - The draft is the composer's own until `value` is passed, and a send clears it. A
 *    controlled draft belongs to the caller, who knows where the sentence goes next.
 * --------------------------------------------------------------------------- */

export const PromptInput = ({
  children,
  className,
  defaultValue,
  disabled = false,
  onQueue,
  onStop,
  onSubmit,
  onValueChange,
  streaming = false,
  value,
  ...props
}: PromptInputProps) => {
  const [draft, setDraft] = useState(defaultValue ?? "");
  const field = useRef<HTMLElement>(null);
  const segments = useRef<(() => PromptSegment[]) | null>(null);

  // Controlled when the caller passes `value`; otherwise the root keeps the draft and
  // clears it after a send.
  const controlled = value !== undefined;
  const text = controlled ? value : draft;

  const setValue = useCallback(
    (next: string) => {
      if (!controlled) {
        setDraft(next);
      }
      onValueChange?.(next);
    },
    [controlled, onValueChange]
  );

  const submit = useCallback(() => {
    const message = text.trim();
    if (message.length === 0 || disabled || (streaming && !onQueue)) {
      return;
    }
    (streaming ? onQueue : onSubmit)?.(
      message,
      segments.current?.() ?? [{ text: message, type: "text" }]
    );
    if (!controlled) {
      setValue("");
    }
    field.current?.focus();
  }, [controlled, disabled, onQueue, onSubmit, setValue, streaming, text]);

  const state = useMemo<PromptInputState>(
    () => ({
      canSend: text.trim().length > 0 && !disabled,
      disabled,
      field,
      segments,
      setValue,
      stop: onStop,
      streaming,
      submit,
      value: text,
    }),
    [disabled, field, onStop, segments, setValue, streaming, submit, text]
  );

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    submit();
  };

  return (
    <PromptInputContext.Provider value={state}>
      <form
        className={cn(
          "flex w-full max-w-2xl flex-col rounded-3xl border border-border bg-card p-2.5 transition-colors duration-150 ease-out focus-within:border-ring/50",
          disabled && "opacity-60",
          className
        )}
        onSubmit={handleSubmit}
        {...props}
      >
        {children}
      </form>
    </PromptInputContext.Provider>
  );
};
parts.tsx
"use client";

import { ArrowUp, Plus, Square } from "lucide-react";
import type { ChangeEvent, ComponentProps, KeyboardEvent } from "react";
import { Children, useLayoutEffect, useRef } from "react";

import type { ButtonProps } from "@/components/ui/button";
import { Button } from "@/components/ui/button";
import type { AttachmentProps } from "@/components/ui/motif/attachment";
import { Attachment } from "@/components/ui/motif/attachment";
import { cn } from "@/lib/utils";

import { usePromptInput } from "./context";
import type {
  PromptInputAttachProps,
  PromptInputButtonProps,
  PromptInputTextareaProps,
} from "./types";

/* -- The parts -----------------------------------------------------------------
 * A composer is four decisions stacked — what rides with the message, what it says,
 * what it can be sent with, and how it ends — and each one is a part, so a caller can
 * take the stack apart. A tools menu, a microphone, a quote of the message being
 * answered, a composer with no attach button: all of them are a different arrangement
 * of the same pieces rather than a prop this file has to know about.
 *
 * The parts that need the root's state read it from context and the rest take no
 * context at all, so `PromptInputHeader` and `PromptInputFooter` are ordinary flex rows
 * that happen to be named after where they sit.
 * --------------------------------------------------------------------------- */

/** How tall the field may grow before it scrolls: four lines of `text-base` and a wrap.
 *  Enough for a paragraph, short of half the window. */
const MAX_FIELD_HEIGHT = 200;

/** The field holds at least two lines even when it is empty. One line of text in a box
 *  this wide reads as a single-line input, which is not what this is — the second line is
 *  the room the draft is visibly allowed to grow into. */
const MIN_ROWS = 2;

/** The footer's round controls are the platform button at one size, so the row reads as
 *  one row rather than three buttons that happen to be next to each other. Everything
 *  else — hover, focus ring, the disabled treatment — is the button's own. */
const ROUND_CONTROL = "size-10 shrink-0 rounded-full";

/**
 * The row above the field: what rides with the message. For attachments, quotes of the
 * message being answered, a warning about the draft — anything that is *about* the text
 * rather than part of it.
 *
 * It draws nothing when it holds nothing, so a composer that always renders its header
 * does not pay for one when there is nothing to put in it.
 */
export const PromptInputHeader = ({
  children,
  className,
  ...props
}: ComponentProps<"div">) =>
  Children.toArray(children).length === 0 ? null : (
    <div className={cn("flex flex-wrap gap-2.5 p-1.5", className)} {...props}>
      {children}
    </div>
  );

/**
 * A chip in the header: the attachment card plus the one thing the header adds — it
 * fades in. Chips land one at a time and the row reflows around them, so a chip that
 * appears whole is a tear in the row; the fade is the difference, and it is short enough
 * that a picked file still feels like it landed instantly.
 *
 * The fade is a CSS animation, not a motion one, and that is the point: chips already in
 * the draft when the page loads are in the markup at full opacity, so reopening a thread
 * with five attachments does not replay their arrival, and no inline `opacity: 0` is left
 * waiting on hydration for a script that never runs. It is skipped outright under
 * `prefers-reduced-motion`.
 *
 * Props are the chip's own, so `onRemove` is what makes it removable and `progress`
 * under 100 is what draws the upload ring.
 */
export const PromptInputAttachment = ({
  className,
  ...props
}: AttachmentProps) => (
  <Attachment
    className={cn(
      "animate-in fade-in zoom-in-95 duration-150 motion-reduce:animate-none",
      className
    )}
    {...props}
  />
);

/**
 * The field. It grows to its content and then scrolls instead of pushing the card
 * taller — a composer is anchored to the bottom of the window in every app that has one,
 * and a draft long enough to fill the viewport would otherwise be a draft you cannot see
 * the end of.
 *
 * Enter sends, Shift+Enter breaks the line, and a composition in progress is left alone:
 * an IME's Enter commits the candidate under it, and sending on that key would eat the
 * word the user was still assembling.
 */
export const PromptInputTextarea = ({
  className,
  maxHeight = MAX_FIELD_HEIGHT,
  onKeyDown,
  rows,
  style,
  ...props
}: PromptInputTextareaProps) => {
  const { disabled, field, setValue, submit, value } = usePromptInput();
  // Two empty lines in px, measured once off the field itself so it stays true if the
  // type scale changes.
  const floor = useRef(0);

  useLayoutEffect(() => {
    const node = field.current;
    if (!node) {
      return;
    }
    if (floor.current === 0) {
      const styles = window.getComputedStyle(node);
      const frame =
        Number.parseFloat(styles.paddingTop) +
        Number.parseFloat(styles.paddingBottom);
      floor.current = Number.parseFloat(styles.lineHeight) * MIN_ROWS + frame;
    }
    // `auto` first: a field sitting at its old height cannot report a shorter
    // `scrollHeight`, because its own padding box counts as overflow.
    node.style.height = "auto";
    const wanted = Math.max(node.scrollHeight, floor.current);
    node.style.height = `${Math.min(wanted, maxHeight)}px`;
    node.style.overflowY = node.scrollHeight > maxHeight ? "auto" : "hidden";
  }, [field, maxHeight, value]);

  const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
    onKeyDown?.(event);
    if (
      event.defaultPrevented ||
      event.key !== "Enter" ||
      event.shiftKey ||
      event.nativeEvent.isComposing
    ) {
      return;
    }
    event.preventDefault();
    submit();
  };

  return (
    <textarea
      {...props}
      className={cn(
        "w-full resize-none bg-transparent px-2 py-2.5 text-base leading-relaxed outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed",
        className
      )}
      disabled={disabled}
      onChange={(event) => setValue(event.target.value)}
      onKeyDown={handleKeyDown}
      ref={(node) => {
        field.current = node;
      }}
      rows={rows ?? MIN_ROWS}
      style={{ maxHeight, ...style }}
      value={value}
    />
  );
};

/** The row under the field: what the message can be sent with, and the button that sends
 *  it. */
export const PromptInputFooter = ({
  className,
  ...props
}: ComponentProps<"div">) => (
  <div className={cn("flex items-center gap-1", className)} {...props} />
);

/** A round control in the footer: the platform `Button` at 40px round, with every
 *  variant, size and feedback prop it already has left intact. */
export const PromptInputButton = ({
  className,
  size = "icon",
  variant = "ghost",
  ...props
}: PromptInputButtonProps) => (
  <Button
    className={cn(ROUND_CONTROL, className)}
    size={size}
    variant={variant}
    {...props}
  />
);

/**
 * The plus: the composer's own file input, opened by a button rather than drawn. It
 * resets the input after a pick, so choosing the same file twice in a row counts twice,
 * and hands focus back to the field, because the next thing the user does is type.
 */
export const PromptInputAttach = ({
  accept,
  onFiles,
  ...props
}: PromptInputAttachProps) => {
  const { field } = usePromptInput();
  const input = useRef<HTMLInputElement>(null);

  if (!onFiles) {
    return null;
  }

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    const chosen = [...(event.target.files ?? [])];
    if (chosen.length > 0) {
      onFiles(chosen);
    }
    event.target.value = "";
    field.current?.focus();
  };

  return (
    <>
      <PromptInputButton
        aria-label="Attach files"
        onClick={() => input.current?.click()}
        type="button"
        {...props}
      >
        <Plus className="size-5" strokeWidth={1.75} />
      </PromptInputButton>
      <input
        accept={accept}
        className="hidden"
        multiple
        onChange={handleChange}
        ref={input}
        type="file"
      />
    </>
  );
};

/**
 * The one button that ends the turn, taking the trailing edge of the row. While an
 * answer is arriving it becomes stop: the only thing worth doing to the composer then is
 * stopping it, and a second button beside send would make the reader choose between two
 * live actions on every frame.
 *
 * Under `streaming` there is nothing to send, so the arrow is disabled until there is.
 */
export const PromptInputSubmit = ({ className, ...props }: ButtonProps) => {
  const { canSend, stop, streaming } = usePromptInput();

  if (streaming) {
    return (
      <PromptInputButton
        aria-label="Stop"
        className={cn("ml-auto", className)}
        onClick={stop}
        type="button"
        variant="default"
        {...props}
      >
        <Square className="size-3.5 fill-current" strokeWidth={0} />
      </PromptInputButton>
    );
  }

  return (
    <PromptInputButton
      aria-label="Send message"
      className={cn("ml-auto", className)}
      disabled={!canSend}
      type="submit"
      variant="default"
      {...props}
    >
      <ArrowUp className="size-5" strokeWidth={2.25} />
    </PromptInputButton>
  );
};
editor.tsx
"use client";

import { Extension, Node, mergeAttributes } from "@tiptap/core";
import { Document } from "@tiptap/extension-document";
import { Paragraph } from "@tiptap/extension-paragraph";
import { Text } from "@tiptap/extension-text";
import { Placeholder, UndoRedo } from "@tiptap/extensions";
import { EditorContent, EditorContext, useEditor } from "@tiptap/react";
import { useEffect, useMemo, useRef } from "react";

import { cn } from "@/lib/utils";

import { usePromptInput } from "./context";
import {
  docToSegments,
  segmentsToText,
  textToDoc,
  trimSegments,
} from "./segments";
import type { PromptInputEditorProps } from "./types";

/** Same ceiling as the textarea: four lines of `text-base` and a wrap. */
const MAX_FIELD_HEIGHT = 200;

/* -- A mention is one thing ----------------------------------------------------
 * An atom: the caret cannot stop inside it, Backspace takes it whole, and a selection
 * either holds all of it or none. That is the whole reason this field is not a textarea.
 * The attributes ride in `data-*` so a copy and paste inside the editor keeps the `id`.
 * --------------------------------------------------------------------------- */

const attribute = (name: string) => ({
  default: "",
  parseHTML: (element: HTMLElement) =>
    element.getAttribute(`data-${name}`) ?? "",
  renderHTML: (attributes: Record<string, string>) => ({
    [`data-${name}`]: attributes[name],
  }),
});

const Mention = Node.create({
  addAttributes: () => ({
    id: attribute("id"),
    label: attribute("label"),
    trigger: attribute("trigger"),
  }),
  atom: true,
  group: "inline",
  inline: true,
  name: "mention",
  parseHTML: () => [{ tag: "span[data-mention]" }],
  renderHTML: ({ HTMLAttributes, node }) => [
    "span",
    mergeAttributes(HTMLAttributes, {
      class: "rounded-md bg-muted px-1.5 py-0.5 font-medium text-foreground",
      "data-mention": "",
    }),
    `${node.attrs.trigger}${node.attrs.label}`,
  ],
  renderText: ({ node }) => `${node.attrs.trigger}${node.attrs.label}`,
  selectable: true,
});

/** Enter sends and Shift+Enter breaks the line, as in the textarea. A menu that is open
 *  has already taken the key by the time this runs. */
const Keys = Extension.create<{ submit: () => void }>({
  addKeyboardShortcuts() {
    return {
      Enter: () => {
        this.options.submit();
        return true;
      },
      "Shift-Enter": ({ editor }) => editor.commands.splitBlock(),
    };
  },
  name: "promptKeys",
});

/** The empty paragraph carries the placeholder as a `before` pseudo-element, which keeps
 *  it out of the document and out of the caret's way. */
const PLACEHOLDER = [
  "[&_p.is-editor-empty:first-child]:before:pointer-events-none",
  "[&_p.is-editor-empty:first-child]:before:float-left",
  "[&_p.is-editor-empty:first-child]:before:h-0",
  "[&_p.is-editor-empty:first-child]:before:text-muted-foreground",
  "[&_p.is-editor-empty:first-child]:before:content-[attr(data-placeholder)]",
].join(" ");

/**
 * The field, when the draft holds more than text. It is `PromptInputTextarea` with a
 * document under it: the same growth cap, two-line floor and Enter binding, and a draft
 * that can hold mentions — chips the user picked from a menu, which the message carries
 * as objects instead of as the characters that spelled them.
 *
 * `PromptInputTrigger` parts go inside it. The root's `value` stays a plain string (a
 * mention written as its trigger and label), so everything that reads the draft as text
 * keeps working; `onSubmit`'s second argument is where the mentions arrive with their ids.
 * What the root hands back as `value` is text, so a mention does not survive being set
 * from outside.
 */
export const PromptInputEditor = ({
  children,
  className,
  maxHeight = MAX_FIELD_HEIGHT,
  placeholder,
  style,
  ...props
}: PromptInputEditorProps) => {
  const { disabled, field, segments, setValue, submit, value } =
    usePromptInput();

  // The editor is built once, so what it calls back into is read through here.
  const latest = useRef({ placeholder, setValue, submit });
  useEffect(() => {
    latest.current = { placeholder, setValue, submit };
  });

  const editor = useEditor(
    {
      content: textToDoc(value),
      editable: !disabled,
      editorProps: {
        attributes: {
          "aria-multiline": "true",
          class:
            "min-h-18 whitespace-pre-wrap break-words px-2 py-2.5 text-base leading-relaxed outline-none",
          role: "textbox",
        },
      },
      extensions: [
        Document,
        Paragraph,
        Text,
        UndoRedo,
        Mention,
        Placeholder.configure({
          placeholder: () => latest.current.placeholder ?? "",
        }),
        Keys.configure({ submit: () => latest.current.submit() }),
      ],
      // The server has no document to measure, and the first paint has no draft yet.
      immediatelyRender: false,
      onUpdate: ({ editor: current }) =>
        latest.current.setValue(
          segmentsToText(docToSegments(current.getJSON()))
        ),
    },
    []
  );

  // The root reaches the field through these two, the way it reaches a textarea.
  useEffect(() => {
    if (!editor) {
      return;
    }
    field.current = editor.view.dom;
    segments.current = () => trimSegments(docToSegments(editor.getJSON()));
    return () => {
      field.current = null;
      segments.current = null;
    };
  }, [editor, field, segments]);

  useEffect(() => {
    editor?.setEditable(!disabled);
  }, [disabled, editor]);

  // The draft changed from outside: a send cleared it, or a prompt card filled it.
  // Anything the editor itself typed already matches and is left alone.
  useEffect(() => {
    if (!editor || segmentsToText(docToSegments(editor.getJSON())) === value) {
      return;
    }
    editor.commands.setContent(textToDoc(value), { emitUpdate: false });
    if (editor.isFocused) {
      editor.commands.focus("end");
    }
  }, [editor, value]);

  const context = useMemo(() => ({ editor }), [editor]);

  return (
    <EditorContext.Provider value={context}>
      <div
        {...props}
        className={cn(
          "w-full overflow-y-auto [&_.ProseMirror-selectednode]:bg-accent [&_.ProseMirror-selectednode]:text-accent-foreground",
          PLACEHOLDER,
          disabled && "cursor-not-allowed",
          className
        )}
        style={{ maxHeight, ...style }}
      >
        <EditorContent editor={editor} />
        {children}
      </div>
    </EditorContext.Provider>
  );
};
trigger.tsx
"use client";

import { PluginKey } from "@tiptap/pm/state";
import { useCurrentEditor } from "@tiptap/react";
import { Suggestion } from "@tiptap/suggestion";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";

import { cn } from "@/lib/utils";

import type { PromptInputTriggerProps, PromptTriggerItem } from "./types";

interface Menu {
  command: (item: PromptTriggerItem) => void;
  index: number;
  items: PromptTriggerItem[];
}

/**
 * A character that opens a menu inside `PromptInputEditor`, and what picking a row does.
 * `@` offers things to point at and `/` offers things to run; they are the same part with
 * a different character, rows, and `lineStart`.
 *
 * The menu belongs to the caret, not to the card: it opens above the character that
 * summoned it and follows the line as it wraps. Focus never leaves the field — the
 * arrows, Enter, Tab and Escape are taken from the editor while a menu is open — so the
 * user keeps typing to narrow it. With nothing matching, nothing is drawn and the keys
 * go back to the field, so Enter still sends.
 *
 * Picking a row replaces the trigger and what followed it with a mention, plus a space to
 * keep typing in. Without `items` the part is not registered at all.
 */
export const PromptInputTrigger = ({
  char,
  items,
  lineStart = false,
  onSelect,
}: PromptInputTriggerProps) => {
  const { editor } = useCurrentEditor();
  const [menu, setMenu] = useState<Menu | null>(null);
  const [host, setHost] = useState<HTMLElement | null>(null);
  const live = useRef<Menu | null>(null);
  const latest = useRef({ items, onSelect });
  useEffect(() => {
    latest.current = { items, onSelect };
  });
  const active = useRef<HTMLLIElement>(null);

  const enabled = items !== undefined;

  useEffect(() => {
    if (!editor || !enabled) {
      return;
    }
    const element = document.createElement("div");
    const key = new PluginKey(`prompt-trigger-${char}`);
    let unmount: (() => void) | undefined;

    const show = (next: Menu | null) => {
      live.current = next;
      setMenu(next);
    };

    const plugin = Suggestion<PromptTriggerItem>({
      // A line start is the start of a paragraph, not of the text node after a mention.
      allow: ({ range, state }) =>
        !lineStart || state.doc.resolve(range.from).parentOffset === 0,
      char,
      command: ({ editor: current, range, props: item }) => {
        const keep = latest.current.onSelect?.(item) !== false;
        const { nodeAfter } = current.state.doc.resolve(range.to);
        const to = nodeAfter?.text?.startsWith(" ") ? range.to + 1 : range.to;
        const chain = current.chain().focus();
        if (keep) {
          chain
            .insertContentAt({ from: range.from, to }, [
              {
                attrs: { id: item.id, label: item.label, trigger: char },
                type: "mention",
              },
              { text: " ", type: "text" },
            ])
            .run();
        } else {
          chain.deleteRange({ from: range.from, to }).run();
        }
      },
      editor,
      items: ({ query }) => {
        const source = latest.current.items;
        if (typeof source === "function") {
          return source(query);
        }
        const needle = query.toLowerCase();
        return (source ?? []).filter((item) =>
          item.label.toLowerCase().includes(needle)
        );
      },
      offset: { crossAxis: 0, mainAxis: 8 },
      placement: "top-start",
      pluginKey: key,
      render: () => ({
        onExit: () => {
          unmount?.();
          unmount = undefined;
          show(null);
        },
        onKeyDown: ({ event }) => {
          const { current } = live;
          if (!current || current.items.length === 0) {
            return false;
          }
          const { length } = current.items;
          if (event.key === "ArrowDown" || event.key === "ArrowUp") {
            const step = event.key === "ArrowDown" ? 1 : -1;
            show({
              ...current,
              index: (current.index + step + length) % length,
            });
            return true;
          }
          if (event.key === "Enter" || event.key === "Tab") {
            current.command(current.items[current.index]);
            return true;
          }
          return false;
        },
        onStart: (props) => {
          unmount = props.mount(element);
          show({ command: props.command, index: 0, items: props.items });
        },
        onUpdate: (props) =>
          show({ command: props.command, index: 0, items: props.items }),
      }),
      startOfLine: lineStart,
    });

    // First in line, so an open menu sees Enter before the field's own binding does.
    editor.registerPlugin(plugin, (added, current) => [added, ...current]);
    setHost(element);
    return () => {
      unmount?.();
      editor.unregisterPlugin(key);
      setHost(null);
      show(null);
    };
  }, [char, editor, enabled, lineStart]);

  // A hover moves the highlight through state, and the keys read it from the ref.
  useEffect(() => {
    live.current = menu;
  }, [menu]);

  useEffect(() => {
    active.current?.scrollIntoView({ block: "nearest" });
  }, [menu?.index]);

  if (!menu || !host || menu.items.length === 0) {
    return null;
  }

  return createPortal(
    <ul
      aria-label={`${char} menu`}
      className="max-h-64 w-72 origin-bottom-left animate-in overflow-y-auto rounded-xl border border-border bg-popover p-1 text-popover-foreground shadow-md duration-100 fade-in-0 zoom-in-95 motion-reduce:animate-none"
      role="listbox"
    >
      {menu.items.map((item, index) => (
        <li
          aria-selected={index === menu.index}
          className={cn(
            "flex cursor-default items-center gap-2 rounded-lg px-2.5 py-2 text-sm",
            index === menu.index && "bg-accent text-accent-foreground"
          )}
          key={item.id}
          // Down on a row would move focus out of the field, and the menu with it.
          onMouseDown={(event) => {
            event.preventDefault();
            menu.command(item);
          }}
          onMouseMove={() =>
            index !== menu.index && setMenu({ ...menu, index })
          }
          ref={index === menu.index ? active : undefined}
          role="option"
        >
          {item.icon}
          <span className="truncate font-medium">{item.label}</span>
          {item.description ? (
            <span className="truncate text-muted-foreground">
              {item.description}
            </span>
          ) : null}
        </li>
      ))}
    </ul>,
    host
  );
};
segments.ts
import type { JSONContent } from "@tiptap/core";

import type { PromptSegment } from "./types";

/* -- The draft, three ways -------------------------------------------------------
 * The editor holds a document, the root holds a string, and the caller wants parts. This
 * file is the only place the three meet, and it works on plain JSON so it can be run
 * without an editor: the document is paragraphs, a paragraph is text and mentions, and
 * a break between paragraphs is a newline everywhere else.
 * --------------------------------------------------------------------------- */

/** The document as segments, adjacent text merged across paragraph breaks. */
export const docToSegments = (doc: JSONContent): PromptSegment[] => {
  const segments: PromptSegment[] = [];
  const pushText = (text: string) => {
    if (text.length === 0) {
      return;
    }
    const last = segments.at(-1);
    if (last?.type === "text") {
      last.text += text;
    } else {
      segments.push({ text, type: "text" });
    }
  };

  for (const [index, paragraph] of (doc.content ?? []).entries()) {
    if (index > 0) {
      pushText("\n");
    }
    for (const node of paragraph.content ?? []) {
      if (node.type === "mention") {
        segments.push({
          id: String(node.attrs?.id),
          label: String(node.attrs?.label),
          trigger: String(node.attrs?.trigger),
          type: "mention",
        });
      } else {
        pushText(node.text ?? "");
      }
    }
  }
  return segments;
};

/** What the root keeps as `value`: a mention is written as its trigger and label. */
export const segmentsToText = (segments: PromptSegment[]) =>
  segments
    .map((segment) =>
      segment.type === "text"
        ? segment.text
        : `${segment.trigger}${segment.label}`
    )
    .join("");

/** The same trim `submit` gives the string, applied to the ends of the segments. */
export const trimSegments = (segments: PromptSegment[]): PromptSegment[] => {
  const trimmed = [...segments];
  const [first] = trimmed;
  if (first?.type === "text") {
    trimmed[0] = { ...first, text: first.text.trimStart() };
  }
  const last = trimmed.at(-1);
  if (last?.type === "text") {
    trimmed[trimmed.length - 1] = { ...last, text: last.text.trimEnd() };
  }
  return trimmed.filter(
    (segment) => segment.type === "mention" || segment.text.length > 0
  );
};

/** A string as a document, one paragraph per line. Mentions do not survive the trip. */
export const textToDoc = (text: string): JSONContent => ({
  content: text.split("\n").map((line) =>
    line.length > 0
      ? {
          content: [{ text: line, type: "text" }],
          type: "paragraph",
        }
      : { type: "paragraph" }
  ),
  type: "doc",
});
model-picker.tsx
"use client";

import { ChevronDown } from "lucide-react";
import { useState } from "react";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  PROVIDER_NAMES,
  ProviderLogo,
} from "@/components/ui/motif/provider-logo";
import { cn } from "@/lib/utils";

import type { ModelPickerProps } from "./types";

/* -- Which model answers -------------------------------------------------------
 * One mark, one name, one chevron. The mark is the loud part because it is the part read
 * at a glance; the name sits in the muted tone the rest of the composer's row uses, so
 * the row has one subject instead of two.
 *
 * The menu opens upward: a composer lives at the bottom of the window, and a menu that
 * unfolds over the message you are about to send is a menu covering the thing you are
 * deciding about. Radix flips it on its own if there is no room above.
 *
 * The pick is the picker's own until `value` is passed, like every other
 * value/defaultValue pair here: a composer that only needs to know which model to call
 * should not have to hold the answer in the page that renders it.
 * --------------------------------------------------------------------------- */

export const ModelPicker = ({
  className,
  defaultValue,
  models,
  onValueChange,
  value,
}: ModelPickerProps) => {
  const [picked, setPicked] = useState(defaultValue ?? models[0]?.id);
  const controlled = value !== undefined;
  const activeId = controlled ? value : picked;

  const active = models.find((model) => model.id === activeId) ?? models[0];

  if (!active) {
    return null;
  }

  const pick = (id: string) => {
    if (!controlled) {
      setPicked(id);
    }
    onValueChange?.(id);
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          aria-label={`Model: ${active.name}`}
          className={cn(
            "flex h-10 max-w-52 shrink-0 cursor-pointer items-center gap-2 rounded-full pr-2 pl-2.5 outline-none transition-colors duration-150 ease-out hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:bg-accent",
            className
          )}
          type="button"
        >
          <ProviderLogo
            className="size-5 text-foreground"
            provider={active.provider}
          />
          {/* The name is the part that changes, so it is the part that truncates. */}
          <span className="truncate text-sm text-muted-foreground">
            {active.name}
          </span>
          <ChevronDown className="size-4 shrink-0 text-muted-foreground/60" />
        </button>
      </DropdownMenuTrigger>

      <DropdownMenuContent align="start" className="min-w-56" side="top">
        <DropdownMenuRadioGroup onValueChange={pick} value={active.id}>
          {models.map((model) => (
            <DropdownMenuRadioItem
              className="gap-2.5 py-2"
              key={model.id}
              value={model.id}
            >
              <ProviderLogo
                className="size-4.5 text-foreground"
                provider={model.provider}
              />
              <span className="truncate">{model.name}</span>
              {/* The maker, on the far side, where it answers a question the name
                  alone leaves open: two vendors ship a model called `Pro`. */}
              <span className="ml-auto pl-4 text-muted-foreground text-xs">
                {PROVIDER_NAMES[model.provider]}
              </span>
            </DropdownMenuRadioItem>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
context.ts
"use client";

import type { RefObject } from "react";
import { createContext, useContext } from "react";

import type { PromptSegment } from "./types";

/**
 * What a part needs from the root to do its job: the draft, the door out of it, and the
 * field — so a part that takes a click can hand focus back to the place the user was
 * typing. The parts that only lay out (the header, the footer, a plain button chip) take
 * no context and can be used anywhere.
 */
export interface PromptInputState {
  /** There is something to send and the composer is not disabled. */
  canSend: boolean;
  disabled: boolean;
  /** Whichever field is mounted: the textarea, or the editor's contenteditable. */
  field: RefObject<HTMLElement | null>;
  /** Set by the editor, which is the only field that holds more than text. */
  segments: RefObject<(() => PromptSegment[]) | null>;
  setValue: (value: string) => void;
  /** The composer's `onStop`, for the submit part's stop face. */
  stop?: () => void;
  streaming: boolean;
  submit: () => void;
  value: string;
}

export const PromptInputContext = createContext<PromptInputState | null>(null);

export const usePromptInput = () => {
  const context = useContext(PromptInputContext);
  if (!context) {
    throw new Error("PromptInput parts must be used within a PromptInput.");
  }

  return context;
};
types.ts
import type { ComponentProps, ReactNode } from "react";

import type { ButtonProps } from "@/components/ui/button";
import type { AttachmentProps } from "@/components/ui/motif/attachment";
import type { ProviderId } from "@/components/ui/motif/provider-logo";

/**
 * A file riding along with the draft, the way a composer usually holds them: the chip's
 * own props plus an `id` for the key. Convenience only — `PromptInputAttachment` takes
 * `AttachmentProps`, so a caller with their own shape can spread it in instead.
 */
export type PromptAttachment = { id: string } & Omit<
  AttachmentProps,
  "className" | "icon" | "onRemove"
>;

/** One model the composer can be pointed at. */
export interface PromptModel {
  /** What `value` and `onValueChange` trade in. */
  id: string;
  name: string;
  provider: ProviderId;
}

export interface ModelPickerProps {
  className?: string;
  /** Model the picker opens on when it holds the choice itself. */
  defaultValue?: string;
  models: PromptModel[];
  onValueChange?: (id: string) => void;
  value?: string;
}

/** The root: the state of the message, and the door out of it. */
export interface PromptInputProps extends Omit<
  ComponentProps<"form">,
  "onSubmit"
> {
  /** Draft the composer starts with. Ignored under a controlled `value`. */
  defaultValue?: string;
  disabled?: boolean;
  onQueue?: (value: string, segments: PromptSegment[]) => void;
  /** Pairs with `streaming`: what the submit part's stop face calls. */
  onStop?: () => void;
  /**
   * Called with the trimmed draft — Enter or the submit part. The second argument is the
   * same draft as parts, with every mention still an object: a composer with a plain
   * `PromptInputTextarea` always hands over one text segment.
   */
  onSubmit?: (value: string, segments: PromptSegment[]) => void;
  onValueChange?: (value: string) => void;
  /** Swaps the submit part's arrow for a stop square, and blocks Enter. */
  streaming?: boolean;
  /** Controlled draft. A controlled draft is never cleared by a send. */
  value?: string;
}

export interface PromptInputTextareaProps extends Omit<
  ComponentProps<"textarea">,
  "onChange" | "value"
> {
  /**
   * The field's own props, plus the cap. It is the composer's own primitive: no textarea
   * base exists to build on, and the growth cap, the two-line floor and the Enter binding
   * are the composer's, not the platform's.
   */
  maxHeight?: number;
}

/**
 * The platform button's own props — `variant`, `size`, `sound`, `haptic` — with the row's
 * geometry already applied on top.
 */
export type PromptInputButtonProps = ButtonProps;

export interface PromptInputAttachProps extends Omit<ButtonProps, "onClick"> {
  /** Offered to the file picker, e.g. `"image/*,.pdf"`. */
  accept?: string;
  /**
   * Makes the part real: the composer opens the file dialog and hands the files over.
   * Omit it and nothing is drawn — a composer with nowhere to attach should not offer
   * to attach.
   */
  onFiles?: (files: File[]) => void;
}

/**
 * The draft as the model of the message wants it: runs of text, and the objects the user
 * picked out of a menu. `value` is these joined into one string, with a mention written
 * as its trigger and label; the segments keep the `id` the string cannot.
 */
export type PromptSegment =
  | { type: "text"; text: string }
  | { type: "mention"; trigger: string; id: string; label: string };

/** One row of a trigger menu, and what becomes of it once picked. */
export interface PromptTriggerItem {
  description?: string;
  icon?: ReactNode;
  /** What the picked mention carries into `segments`. */
  id: string;
  /** Written after the trigger, and what the query is matched against. */
  label: string;
}

export interface PromptInputEditorProps extends Omit<
  ComponentProps<"div">,
  "defaultValue" | "onChange" | "onKeyDown" | "onSubmit"
> {
  /**
   * The editor's own props, plus the cap. It replaces `PromptInputTextarea` when the
   * draft needs to hold more than text, and keeps the textarea's rules: it grows then
   * scrolls, never shrinks below two lines, Enter sends and Shift+Enter breaks the line.
   */
  maxHeight?: number;
  placeholder?: string;
}

export interface PromptInputTriggerProps {
  /** The character that opens the menu, e.g. `"@"` or `"/"`. */
  char: string;
  /**
   * The rows to offer. An array is filtered by what follows the trigger; a function gets
   * that query and returns the rows itself, for a list that lives behind a search. Omit it
   * and nothing is drawn — a trigger with nothing to offer should not swallow the key.
   */
  items?:
    | PromptTriggerItem[]
    | ((query: string) => PromptTriggerItem[] | Promise<PromptTriggerItem[]>);
  /** Only opens at the start of a line, the way a command does. */
  lineStart?: boolean;
  /**
   * Called with the picked row. Return `false` to run it without leaving a mention in the
   * draft, for a command that acts on the spot instead of becoming part of the message.
   */
  onSelect?: (item: PromptTriggerItem) => boolean | undefined;
}