Skip to content
Shaken UI
Sign in

Prompt Composer

Save

An agent-native prompt box with a soft border beam: Enter sends, Shift+Enter adds a line, a round Send turns into Stop during a run, and you opt into mentions, attachments, and mode, model, and permission selectors.

Category
Agent
Version
0.3.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Prompt Composer preview
Composer controls

Enter to send, Shift+Enter for a new line.

Enter sends, Shift+Enter adds a line.

Installation

npx @shakenui/cli add prompt-composer

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add prompt-composer --dry-run

Usage

prompt-composer-example.tsx
"use client";

import { useState } from "react";
import { type ComposerStatus, PromptComposer } from "@/components/shaken/agent/prompt-composer";

export default function PromptComposerExample() {
  const [status, setStatus] = useState<ComposerStatus>("idle");
  const [last, setLast] = useState<string | null>(null);

  async function send(prompt: string, { mode, files }: { mode?: string; files: File[] }) {
    setStatus("submitting");
    await new Promise((resolve) => setTimeout(resolve, 500)); // your API call
    setLast(`${prompt} (${mode}, ${files.length} files)`);
    setStatus("running");
  }

  return (
    <div className="grid w-full max-w-lg gap-2">
      <PromptComposer
        placeholder="Build anything…"
        onSubmit={send}
        onStop={() => setStatus("idle")}
        status={status}
        mentions={{ options: [{ value: "docs", label: "docs" }, { value: "api", label: "api" }] }}
        attachments
        mode
        model
      />
      {last ? <p className="text-xs text-zinc-500">Sent: {last}</p> : null}
    </div>
  );
}

API

PropTypeDefaultDescription
onSubmit(prompt: string, context: { files, mode?, model?, permission? }) => void | Promise<void>—Receives the trimmed prompt and the toolbar choices; the field and attachments clear when it resolves.
onStop() => void—Shown as a round Stop button while status is running.
status"idle" | "submitting" | "running""idle"Disables sending while busy. Running brightens the beam and says "Agent is working".
beambooleantrueA faint multi-hue light on the border. It rests still, travels while focused or running, and stays still with reduced motion.
mentionsboolean | { options?, onSelect? }—Adds an @ button. true inserts "@"; with options it opens a menu and inserts "@label" at the caret.
attachmentsboolean | { accept?, multiple?, maxFiles?, files?, defaultFiles?, onChange? }—Adds a file button, drag and drop, and paste, with removable chips (image thumbnails). Controlled with files and onChange.
modeboolean | { options?, value?, defaultValue?, onChange?, label? }—Adds a mode selector. true offers Agent, Ask, and Plan (defaultModes).
modelboolean | { options?, value?, defaultValue?, onChange?, label? }—Adds a model selector. true offers Auto, Fast, and Thorough (defaultModels).
permissionsboolean | { options?, value?, defaultValue?, onChange?, label? }—Adds a permission selector. true offers Ask every time, Auto-approve edits, and Full access (defaultPermissions).
placeholder / label / maxLength / defaultValuestring / string / number / string—Field text, accessible label, character limit (a counter appears near the limit), and starting text.

Accessibility

  • The field has an accessible label and a hint describing Enter and Shift+Enter; while running, a live region says the agent is working.
  • Enter does not send while an input method is composing text.
  • Icon buttons are named (Mention, Attach files, Send, Stop, Remove file name). Selectors are Base UI menus with radio items, named like "Mode: Agent", and work with arrow keys, Enter, and Escape.
  • Send shows a busy state while submitting; Stop replaces it during a run.
  • The border beam is decorative and hidden from assistive technology; with reduced motion it is a still gradient and other transitions are removed.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/prompt-composer.tsxprompt-composer
  • Also installs dropdown-menu@0.2.1registry dependency
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/prompt-composer/0.3.0.json.

agent/prompt-composer.tsxShow
agent/prompt-composer.tsx
"use client";

import { Menu as BaseMenu } from "@base-ui/react/menu";
import {
  type ClipboardEvent,
  type DragEvent,
  type FormEvent,
  type KeyboardEvent,
  type ReactNode,
  type RefObject,
  useEffect,
  useId,
  useRef,
  useState,
} from "react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "../ui/dropdown-menu";

export type ComposerStatus = "idle" | "submitting" | "running";

/** One choice in a toolbar selector or the mention menu. */
export interface ComposerOption {
  value: string;
  label: string;
  description?: string;
  /** A 16px glyph shown in the menu and, for the selected option, on the toolbar button. */
  icon?: ReactNode;
}

/** A toolbar selector. Pass `value` with `onChange` to control it, or `defaultValue` to let it hold its own state. */
export interface ComposerSelect {
  /** The choices. Defaults to the built-in list for that selector. */
  options?: ComposerOption[];
  value?: string;
  defaultValue?: string;
  onChange?: (value: string) => void;
  /** Names the selector for screen readers and heads its menu, e.g. "Mode". */
  label?: string;
}

export interface ComposerAttachments {
  /** File types the picker offers, as in `<input accept>`. */
  accept?: string;
  multiple?: boolean;
  maxFiles?: number;
  /** Selected files. Pass with `onChange` to control them. */
  files?: File[];
  defaultFiles?: File[];
  onChange?: (files: File[]) => void;
}

export interface ComposerMentions {
  /** People, files, or tools to mention. Without options the button inserts "@" and focuses the field. */
  options?: ComposerOption[];
  /** Called after a mention is inserted. */
  onSelect?: (option: ComposerOption) => void;
}

/** Everything chosen in the toolbar, passed to `onSubmit` with the prompt. */
export interface ComposerSubmitContext {
  files: File[];
  mode?: string;
  model?: string;
  permission?: string;
}

export interface PromptComposerProps {
  /** Called with the trimmed prompt and the toolbar choices. The field and attachments clear when it resolves. */
  onSubmit: (prompt: string, context: ComposerSubmitContext) => void | Promise<void>;
  /** Shown as a Stop button while the agent is running. */
  onStop?: () => void;
  status?: ComposerStatus;
  placeholder?: string;
  /** Accessible label for the field. */
  label?: string;
  maxLength?: number;
  defaultValue?: string;
  className?: string;
  /** A slow multi-hue light along the border, brighter while focused or running. Static with reduced motion. */
  beam?: boolean;
  /** Adds an "@" button. `true` inserts "@"; pass options for a mention menu. */
  mentions?: boolean | ComposerMentions;
  /** Adds a file button, drag and drop, and paste, with removable chips. */
  attachments?: boolean | ComposerAttachments;
  /** Adds a mode selector. `true` offers Agent, Ask, and Plan. */
  mode?: boolean | ComposerSelect;
  /** Adds a model selector. `true` offers Auto, Fast, and Thorough. */
  model?: boolean | ComposerSelect;
  /** Adds a permission selector. `true` offers Ask every time, Auto-approve edits, and Full access. */
  permissions?: boolean | ComposerSelect;
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
const stroke = { fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" } as const;

export const defaultModes: ComposerOption[] = [
  {
    value: "agent",
    label: "Agent",
    description: "Plans, edits files, and runs tools",
    icon: (
      <svg viewBox="0 0 16 16" {...stroke}>
        <path d="M5.25 10.75c-1.5 0-2.5-1.1-2.5-2.75s1-2.75 2.5-2.75c2.5 0 3 5.5 5.5 5.5 1.5 0 2.5-1.1 2.5-2.75s-1-2.75-2.5-2.75c-2.5 0-3 5.5-5.5 5.5Z" />
      </svg>
    ),
  },
  {
    value: "ask",
    label: "Ask",
    description: "Answers questions without changing anything",
    icon: (
      <svg viewBox="0 0 16 16" {...stroke}>
        <path d="M3 4.25c0-.83.67-1.5 1.5-1.5h7c.83 0 1.5.67 1.5 1.5v5c0 .83-.67 1.5-1.5 1.5H7.5L4.75 13v-2.25h-.25c-.83 0-1.5-.67-1.5-1.5z" />
      </svg>
    ),
  },
  {
    value: "plan",
    label: "Plan",
    description: "Writes a plan for you to review first",
    icon: (
      <svg viewBox="0 0 16 16" {...stroke}>
        <path d="M6.5 4.5h6.25M6.5 8h6.25M6.5 11.5h6.25M3.25 4.5h.5M3.25 8h.5M3.25 11.5h.5" />
      </svg>
    ),
  },
];

export const defaultModels: ComposerOption[] = [
  { value: "auto", label: "Auto", description: "Picks a model for each task" },
  { value: "fast", label: "Fast", description: "Quick answers for small edits" },
  { value: "thorough", label: "Thorough", description: "Slower, for larger changes" },
];

export const defaultPermissions: ComposerOption[] = [
  { value: "ask", label: "Ask every time", description: "Approve each edit and command" },
  { value: "auto-edits", label: "Auto-approve edits", description: "Edits apply; commands still ask" },
  { value: "full", label: "Full access", description: "Runs edits and commands without asking" },
];

/**
 * A prompt box for agents: Enter sends, Shift+Enter adds a line, and Stop replaces Send while a
 * run is active. Opt into mentions, attachments, and mode, model, and permission selectors.
 */
export function PromptComposer({
  onSubmit,
  onStop,
  status = "idle",
  placeholder = "Ask the agent to do something…",
  label = "Message the agent",
  maxLength = 4000,
  defaultValue = "",
  className,
  beam = true,
  mentions,
  attachments,
  mode,
  model,
  permissions,
}: PromptComposerProps) {
  const [value, setValue] = useState(defaultValue);
  const [dragging, setDragging] = useState(false);
  const id = useId();
  const fieldRef = useRef<HTMLTextAreaElement>(null);
  const fileRef = useRef<HTMLInputElement>(null);

  const attach = attachments ? (attachments === true ? {} : attachments) : null;
  const mention = mentions ? (mentions === true ? {} : mentions) : null;
  const modeSelect = useSelect(mode, defaultModes, "Mode");
  const modelSelect = useSelect(model, defaultModels, "Model");
  const permissionSelect = useSelect(permissions, defaultPermissions, "Permissions");
  const [files, setFiles] = useControllable(attach?.files, attach?.defaultFiles ?? [], attach?.onChange);

  const busy = status !== "idle";
  const running = status === "running";
  const canSend = value.trim().length > 0 && !busy;
  const nearLimit = value.length > maxLength * 0.9;

  async function submit(event?: FormEvent) {
    event?.preventDefault();
    if (!canSend) return;
    const prompt = value.trim();
    await onSubmit(prompt, { files, mode: modeSelect?.value, model: modelSelect?.value, permission: permissionSelect?.value });
    setValue("");
    if (attach) setFiles([]);
  }

  function onKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
    // Ignore Enter while an input method is composing text (e.g. Japanese, Chinese).
    if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
      event.preventDefault();
      void submit();
    }
  }

  function addFiles(list: FileList | File[]) {
    if (!attach) return;
    const incoming = [...list].filter((file) => accepts(attach.accept, file));
    if (incoming.length === 0) return;
    const next = attach.multiple === false ? incoming.slice(0, 1) : [...files, ...incoming];
    setFiles(attach.maxFiles ? next.slice(0, attach.maxFiles) : next);
  }

  function removeFile(index: number) {
    setFiles(files.filter((_, i) => i !== index));
    fieldRef.current?.focus();
  }

  function insertAtCaret(text: string) {
    const field = fieldRef.current;
    const start = field?.selectionStart ?? value.length;
    const end = field?.selectionEnd ?? value.length;
    const before = value.slice(0, start);
    const spacer = before && !/\s$/.test(before) ? " " : "";
    const next = `${before}${spacer}${text}${value.slice(end)}`.slice(0, maxLength);
    setValue(next);
    const caret = Math.min(start + spacer.length + text.length, next.length);
    requestAnimationFrame(() => {
      field?.focus();
      field?.setSelectionRange(caret, caret);
    });
  }

  function onPaste(event: ClipboardEvent<HTMLTextAreaElement>) {
    if (attach && event.clipboardData.files.length > 0) {
      event.preventDefault();
      addFiles(event.clipboardData.files);
    }
  }

  const dragProps = attach
    ? {
        onDragOver: (event: DragEvent) => {
          if (!event.dataTransfer.types.includes("Files")) return;
          event.preventDefault();
          setDragging(true);
        },
        onDragLeave: (event: DragEvent) => {
          if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDragging(false);
        },
        onDrop: (event: DragEvent) => {
          event.preventDefault();
          setDragging(false);
          addFiles(event.dataTransfer.files);
        },
      }
    : {};

  const showTopRow = Boolean(mention) || files.length > 0;

  return (
    <form
      onSubmit={submit}
      data-status={status}
      data-dragging={dragging || undefined}
      {...dragProps}
      className={[
        "group/composer relative isolate rounded-2xl border border-zinc-950/10 bg-white p-2 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
        "transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
        "hover:border-zinc-950/15 focus-within:border-zinc-950/20",
        "dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)] dark:hover:border-white/15 dark:focus-within:border-white/20",
        "data-[dragging]:border-sky-500/60 dark:data-[dragging]:border-sky-400/60",
        beam ? "" : "focus-within:shadow-[0_0_0_3px_rgb(14_165_233/0.16)] dark:focus-within:shadow-[0_0_0_3px_rgb(56_189_248/0.18)]",
        className,
      ]
        .filter(Boolean)
        .join(" ")}
    >
      {beam ? <BorderBeam /> : null}
      <label htmlFor={id} className="sr-only">
        {label}
      </label>

      {showTopRow ? (
        <div className="flex flex-wrap items-center gap-1.5 px-0.5 pt-0.5">
          {mention ? <MentionButton mention={mention} fieldRef={fieldRef} onInsert={insertAtCaret} disabled={busy && !running} /> : null}
          {files.length > 0 ? (
            <ul aria-label="Attachments" className="contents">
              {files.map((file, index) => (
                <FileChip key={`${file.name}-${file.size}-${file.lastModified}-${index}`} file={file} onRemove={() => removeFile(index)} />
              ))}
            </ul>
          ) : null}
        </div>
      ) : null}

      <textarea
        ref={fieldRef}
        id={id}
        value={value}
        onChange={(event) => setValue(event.target.value)}
        onKeyDown={onKeyDown}
        onPaste={onPaste}
        placeholder={placeholder}
        maxLength={maxLength}
        rows={1}
        aria-describedby={`${id}-hint`}
        className="block max-h-48 min-h-12 w-full resize-none bg-transparent px-2.5 pt-2.5 pb-1 text-sm leading-relaxed text-zinc-950 [field-sizing:content] placeholder:text-zinc-500 focus:outline-none dark:text-white dark:placeholder:text-zinc-500"
      />
      <p id={`${id}-hint`} className="sr-only">
        Enter to send, Shift+Enter for a new line.
      </p>

      <div className="flex items-end justify-between gap-2">
        <div className="flex min-w-0 flex-wrap items-center gap-1 sm:gap-1.5">
          {attach ? (
            <>
              <input
                ref={fileRef}
                type="file"
                hidden
                tabIndex={-1}
                accept={attach.accept}
                multiple={attach.multiple !== false}
                onChange={(event) => {
                  if (event.target.files) addFiles(event.target.files);
                  event.target.value = "";
                }}
              />
              <button type="button" aria-label="Attach files" onClick={() => fileRef.current?.click()} className={iconButton}>
                <svg aria-hidden="true" viewBox="0 0 16 16" {...stroke} className="size-4">
                  <path d="m13.1 7.6-4.85 4.85a3.1 3.1 0 0 1-4.4-4.4l4.95-4.95a2.05 2.05 0 0 1 2.9 2.9L6.85 10.85a1 1 0 0 1-1.42-1.42L9.9 4.96" />
                </svg>
              </button>
            </>
          ) : null}
          {modeSelect ? <SelectPill select={modeSelect} /> : null}
          {modelSelect ? <SelectPill select={modelSelect} /> : null}
          {permissionSelect ? <SelectPill select={permissionSelect} glyph={<ShieldGlyph value={permissionSelect.value} />} compact /> : null}
        </div>

        <div className="flex shrink-0 items-center gap-2">
          {nearLimit ? (
            <span className="font-mono text-xs text-amber-700 tabular-nums dark:text-amber-400">{maxLength - value.length} left</span>
          ) : null}
          <span role="status" className="sr-only text-xs text-sky-700 sm:not-sr-only dark:text-sky-400">
            {running ? (
              <span key="running" className={`transition-opacity duration-200 ${ease} starting:opacity-0 motion-reduce:transition-none`}>
                Agent is working
              </span>
            ) : null}
          </span>
          {running && onStop ? (
            <button key="stop" type="button" aria-label="Stop" onClick={onStop} className={roundButton}>
              <svg aria-hidden="true" viewBox="0 0 16 16" fill="currentColor" className={`size-3.5 ${swap}`}>
                <rect x="4" y="4" width="8" height="8" rx="1.75" />
              </svg>
            </button>
          ) : (
            <button
              key="send"
              type="submit"
              aria-label="Send"
              aria-busy={status === "submitting" || undefined}
              disabled={!canSend && status !== "submitting"}
              onClick={(event) => status === "submitting" && event.preventDefault()}
              className={roundButton}
            >
              {status === "submitting" ? (
                <svg key="busy" aria-hidden="true" viewBox="0 0 16 16" fill="none" className={`size-4 motion-safe:animate-spin ${swap}`}>
                  <circle cx="8" cy="8" r="6" stroke="currentColor" strokeOpacity="0.25" strokeWidth="1.5" />
                  <path d="M14 8a6 6 0 0 0-6-6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                </svg>
              ) : (
                <svg key="arrow" aria-hidden="true" viewBox="0 0 16 16" {...stroke} strokeWidth={1.75} className={`size-4 ${swap}`}>
                  <path d="M8 12.75v-9.5M3.75 7.5 8 3.25l4.25 4.25" />
                </svg>
              )}
            </button>
          )}
        </div>
      </div>
    </form>
  );
}

const swap = `transition-[opacity,scale] duration-200 ${ease} starting:opacity-0 motion-safe:starting:scale-75 motion-reduce:transition-none`;

const iconButton = [
  "inline-flex size-8 shrink-0 items-center justify-center rounded-full text-zinc-500",
  "transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
  "hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
  "data-[popup-open]:bg-zinc-950/[0.06] data-[popup-open]:text-zinc-950 dark:data-[popup-open]:bg-white/[0.09] dark:data-[popup-open]:text-white",
  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 disabled:pointer-events-none disabled:opacity-45",
].join(" ");

const pill = [
  "inline-flex h-8 min-w-0 items-center gap-1 rounded-full border border-zinc-950/10 pr-1.5 pl-2.5 text-[13px] font-medium text-zinc-700 select-none sm:gap-1.5 sm:pr-2 sm:pl-3",
  "has-[>[data-glyph]]:pl-2 sm:has-[>[data-glyph]]:pl-2.5 [&_svg]:size-4 [&_svg]:shrink-0",
  "transition-[background-color,border-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
  "hover:border-zinc-950/15 hover:bg-zinc-950/[0.04] hover:text-zinc-950",
  "data-[popup-open]:border-zinc-950/15 data-[popup-open]:bg-zinc-950/[0.06] data-[popup-open]:text-zinc-950",
  "dark:border-white/10 dark:text-zinc-300 dark:hover:border-white/20 dark:hover:bg-white/[0.06] dark:hover:text-white",
  "dark:data-[popup-open]:border-white/20 dark:data-[popup-open]:bg-white/[0.09] dark:data-[popup-open]:text-white",
  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
].join(" ");

const roundButton = [
  "relative inline-flex size-8 shrink-0 items-center justify-center rounded-full",
  "bg-zinc-950 text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.12),0_1px_2px_rgb(0_0_0/0.2)] hover:bg-zinc-800",
  "dark:bg-white dark:text-black dark:shadow-[inset_0_-1px_0_rgb(0_0_0/0.12)] dark:hover:bg-zinc-200",
  "transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
  "disabled:bg-zinc-950/[0.06] disabled:text-zinc-400 disabled:shadow-none dark:disabled:bg-white/[0.08] dark:disabled:text-zinc-500",
  "aria-busy:cursor-progress focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
].join(" ");

/**
 * A soft light that travels along the border. A conic gradient turns behind a mask that keeps
 * only the 1px ring, so only transform animates. It rests still and faint, and moves while the
 * field has focus or the agent works. Reduced motion leaves it as a still gradient.
 */
function BorderBeam() {
  return (
    <span
      aria-hidden="true"
      className={[
        "pointer-events-none absolute -inset-px -z-10 overflow-hidden rounded-[inherit] p-px",
        "[mask:linear-gradient(#000_0_0)_content-box_exclude,linear-gradient(#000_0_0)]",
        "opacity-45 transition-opacity duration-300 ease-out motion-reduce:transition-none dark:opacity-55",
        "group-hover/composer:opacity-70 group-focus-within/composer:opacity-100 group-data-[status=running]/composer:opacity-100",
      ].join(" ")}
    >
      <span
        className={[
          "absolute top-1/2 left-1/2 aspect-square w-[max(150%,40rem)] -translate-x-1/2 -translate-y-1/2",
          "bg-[conic-gradient(from_200deg,transparent_0deg,rgb(248_113_113/0.9)_28deg,rgb(251_191_36/0.85)_62deg,transparent_104deg,transparent_180deg,rgb(167_139_250/0.9)_208deg,rgb(45_212_191/0.85)_244deg,transparent_286deg)]",
          "animate-spin [animation-duration:9s] [animation-play-state:paused] motion-reduce:animate-none",
          "group-focus-within/composer:[animation-play-state:running] group-data-[status=running]/composer:[animation-play-state:running]",
        ].join(" ")}
      />
    </span>
  );
}

type ResolvedSelect = ComposerSelect & { options: ComposerOption[]; value: string; setValue: (value: string) => void; label: string };

function useSelect(config: boolean | ComposerSelect | undefined, defaults: ComposerOption[], fallbackLabel: string): ResolvedSelect | null {
  const resolved = config ? (config === true ? { options: defaults } : config) : null;
  const options = resolved?.options ?? defaults;
  const [value, setValue] = useControllable(resolved?.value, resolved?.defaultValue ?? options[0]?.value ?? "", resolved?.onChange);
  if (!resolved || options.length === 0) return null;
  return { ...resolved, options, value, setValue, label: resolved.label ?? fallbackLabel };
}

function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
  const [inner, setInner] = useState(defaultValue);
  const current = value === undefined ? inner : value;
  function set(next: T) {
    if (value === undefined) setInner(next);
    onChange?.(next);
  }
  return [current, set] as const;
}

/** A pill that opens a menu of radio choices. Its name reads as "Mode: Agent". */
function SelectPill({ select, glyph, compact = false }: { select: ResolvedSelect; glyph?: ReactNode; compact?: boolean }) {
  const current = select.options.find((option) => option.value === select.value) ?? select.options[0]!;
  const leading = glyph ?? current.icon;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger aria-label={`${select.label}: ${current.label}`} className={pill}>
        {leading ? (
          <span data-glyph aria-hidden="true" className="inline-flex text-zinc-500 dark:text-zinc-400">
            {leading}
          </span>
        ) : null}
        <span className={`truncate ${compact ? "hidden sm:inline" : ""} max-w-[10rem]`}>{current.label}</span>
        <svg aria-hidden="true" viewBox="0 0 16 16" {...stroke} className="size-3.5! text-zinc-400 dark:text-zinc-500">
          <path d="m5 6.5 3 3 3-3" />
        </svg>
      </DropdownMenuTrigger>
      <DropdownMenuContent side="top" align="start" sideOffset={8} className="w-64">
        <DropdownMenuGroup>
          <DropdownMenuLabel>{select.label}</DropdownMenuLabel>
          <BaseMenu.RadioGroup value={select.value} onValueChange={(next: string) => select.setValue(next)}>
            {select.options.map((option) => (
              <BaseMenu.RadioItem
                key={option.value}
                value={option.value}
                closeOnClick
                className={[
                  "flex cursor-default items-start gap-2.5 rounded-md px-2 py-1.5 text-sm outline-none select-none",
                  "text-zinc-700 data-[highlighted]:bg-zinc-950/[0.05] data-[highlighted]:text-zinc-950",
                  "dark:text-zinc-300 dark:data-[highlighted]:bg-white/[0.08] dark:data-[highlighted]:text-white",
                  "data-[disabled]:pointer-events-none data-[disabled]:opacity-45",
                ].join(" ")}
              >
                {option.icon ? (
                  <span aria-hidden="true" className="mt-0.5 inline-flex text-zinc-500 [&_svg]:size-4 [&_svg]:shrink-0">
                    {option.icon}
                  </span>
                ) : null}
                <span className="grid min-w-0 flex-1">
                  <span className="font-medium">{option.label}</span>
                  {option.description ? <span className="text-xs text-zinc-500">{option.description}</span> : null}
                </span>
                <BaseMenu.RadioItemIndicator className="mt-0.5 inline-flex text-zinc-950 dark:text-white">
                  <svg aria-hidden="true" viewBox="0 0 16 16" {...stroke} className="size-4">
                    <path d="m3.75 8.25 2.75 2.75 5.75-6" />
                  </svg>
                </BaseMenu.RadioItemIndicator>
              </BaseMenu.RadioItem>
            ))}
          </BaseMenu.RadioGroup>
        </DropdownMenuGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

/** A shield: open while every action asks, half filled for edits, filled for full access. */
function ShieldGlyph({ value }: { value: string }) {
  return (
    <svg viewBox="0 0 16 16" {...stroke}>
      <path d="M8 2.25 3.25 4v3.6c0 2.9 2 5 4.75 6.15 2.75-1.15 4.75-3.25 4.75-6.15V4z" />
      {value === "full" ? (
        <path d="M8 4.1 4.9 5.25v2.4c0 2 1.3 3.5 3.1 4.4 1.8-.9 3.1-2.4 3.1-4.4v-2.4z" fill="currentColor" stroke="none" />
      ) : value !== "ask" ? (
        <path d="M8 4.1v7.95c-1.8-.9-3.1-2.4-3.1-4.4v-2.4z" fill="currentColor" stroke="none" />
      ) : null}
    </svg>
  );
}

function MentionButton({
  mention,
  fieldRef,
  onInsert,
  disabled,
}: {
  mention: ComposerMentions;
  fieldRef: RefObject<HTMLTextAreaElement | null>;
  onInsert: (text: string) => void;
  disabled: boolean;
}) {
  const glyph = (
    <svg aria-hidden="true" viewBox="0 0 16 16" {...stroke} className="size-4">
      <circle cx="8" cy="8" r="2.5" />
      <path d="M10.5 8v.9a1.85 1.85 0 0 0 3.7 0V8A6.2 6.2 0 1 0 11.8 13" />
    </svg>
  );
  const button = `${iconButton} border border-zinc-950/10 dark:border-white/10`;

  if (!mention.options || mention.options.length === 0) {
    return (
      <button type="button" aria-label="Mention" disabled={disabled} onClick={() => onInsert("@")} className={button}>
        {glyph}
      </button>
    );
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger aria-label="Mention" disabled={disabled} className={button}>
        {glyph}
      </DropdownMenuTrigger>
      <DropdownMenuContent side="top" align="start" sideOffset={8} finalFocus={fieldRef} className="w-64">
        <DropdownMenuGroup>
          <DropdownMenuLabel>Mention</DropdownMenuLabel>
          {mention.options.map((option) => (
            <DropdownMenuItem
              key={option.value}
              onClick={() => {
                onInsert(`@${option.label} `);
                mention.onSelect?.(option);
              }}
              className="h-auto min-h-8 py-1.5"
            >
              {option.icon ?? null}
              <span className="grid min-w-0">
                <span className="truncate">{option.label}</span>
                {option.description ? <span className="truncate text-xs text-zinc-500">{option.description}</span> : null}
              </span>
            </DropdownMenuItem>
          ))}
        </DropdownMenuGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

function FileChip({ file, onRemove }: { file: File; onRemove: () => void }) {
  const [thumbnail, setThumbnail] = useState<string | null>(null);

  useEffect(() => {
    if (!file.type.startsWith("image/")) return;
    const url = URL.createObjectURL(file);
    setThumbnail(url);
    return () => URL.revokeObjectURL(url);
  }, [file]);

  const extension = file.name.match(/\.([a-z0-9]{1,5})$/i)?.[1]?.toLowerCase() ?? "";

  return (
    <li
      className={[
        "flex h-8 max-w-56 min-w-0 items-center gap-2 rounded-lg border border-zinc-950/10 pr-1 pl-1 text-xs dark:border-white/10",
        `transition-[opacity,scale] duration-200 ${ease} starting:opacity-0 motion-safe:starting:scale-95 motion-reduce:transition-none`,
      ].join(" ")}
    >
      {thumbnail ? (
        <img src={thumbnail} alt="" className="size-6 shrink-0 rounded-md object-cover" />
      ) : (
        <span aria-hidden="true" className="grid h-6 min-w-6 shrink-0 place-items-center rounded-md bg-zinc-950/[0.05] px-1 font-mono text-[9px] font-medium text-zinc-600 dark:bg-white/[0.08] dark:text-zinc-400">
          {extension || "file"}
        </span>
      )}
      <span className="min-w-0 truncate font-medium text-zinc-700 dark:text-zinc-300">{file.name}</span>
      <span className="shrink-0 font-mono text-[11px] text-zinc-500 tabular-nums">{formatSize(file.size)}</span>
      <button
        type="button"
        aria-label={`Remove ${file.name}`}
        onClick={onRemove}
        className={[
          "inline-flex size-6 shrink-0 items-center justify-center rounded-md text-zinc-500",
          "transition-colors duration-150 ease-out motion-reduce:transition-none",
          "hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
          "focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-500",
        ].join(" ")}
      >
        <svg aria-hidden="true" viewBox="0 0 16 16" {...stroke} className="size-3.5">
          <path d="M4.75 4.75l6.5 6.5M11.25 4.75l-6.5 6.5" />
        </svg>
      </button>
    </li>
  );
}

function accepts(accept: string | undefined, file: File) {
  if (!accept) return true;
  return accept.split(",").some((rule) => {
    const pattern = rule.trim().toLowerCase();
    if (!pattern) return false;
    if (pattern.startsWith(".")) return file.name.toLowerCase().endsWith(pattern);
    if (pattern.endsWith("/*")) return file.type.startsWith(pattern.slice(0, -1));
    return file.type === pattern;
  });
}

function formatSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}