{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pulsing-border-prompt",
  "title": "Pulsing Border Prompt",
  "description": "An AI prompt input with modes and file drops, whose glow shows what it is doing: listening, thinking, streaming or failing.",
  "dependencies": [
    "@paper-design/shaders-react",
    "lucide-react"
  ],
  "registryDependencies": [
    "button"
  ],
  "files": [
    {
      "path": "registry/shaders/pulsing-border-prompt/pulsing-border-prompt.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport {\n  getShaderColorFromString,\n  PulsingBorder,\n  pulsingBorderMeta,\n  type PaperShaderElement,\n} from \"@paper-design/shaders-react\"\nimport {\n  ArrowUpIcon,\n  FileIcon,\n  PaperclipIcon,\n  SquareIcon,\n  XIcon,\n} from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\n\n// How far (in px) the glow is allowed to bleed outside the input.\nconst GLOW = 40\n\n/** Matches the `status` returned by the AI SDK's `useChat`. */\ntype PromptStatus = \"ready\" | \"submitted\" | \"streaming\" | \"error\"\n\ntype PromptMode = {\n  value: string\n  label: string\n  /** Glow colors while this mode is selected. */\n  colors: string[]\n}\n\ntype PromptMessage = {\n  text: string\n  files: File[]\n  mode?: string\n}\n\ntype PulsingBorderPromptProps = Omit<\n  React.ComponentProps<\"form\">,\n  \"onSubmit\"\n> & {\n  /** Called with the trimmed text and attached files. The input clears itself afterwards. */\n  onSubmit?: (message: PromptMessage) => void\n  /** Called when the stop button is pressed while a response is on its way. */\n  onStop?: () => void\n  /** Drives the glow, and swaps the send button for a stop button while busy. */\n  status?: PromptStatus\n  placeholder?: string\n  /** Glow colors when there are no modes. */\n  colors?: string[]\n  /** A mode picker shown in the toolbar. Each mode tints the glow. */\n  modes?: PromptMode[]\n  defaultMode?: string\n  onModeChange?: (mode: string) => void\n  /** Allow attaching files by picking, dropping or pasting them. */\n  attachments?: boolean\n  /** Which files can be attached, like the `accept` attribute of a file input. */\n  accept?: string\n  speed?: number\n}\n\ntype Attachment = { id: number; file: File; preview?: string }\n\nlet nextAttachmentId = 0\n\nfunction PulsingBorderPrompt({\n  onSubmit,\n  onStop,\n  status = \"ready\",\n  placeholder = \"Ask anything…\",\n  colors = [\"#0dc1fd\", \"#d915ef\", \"#ff3f2ecc\"],\n  modes,\n  defaultMode,\n  onModeChange,\n  attachments = true,\n  accept,\n  speed = 1,\n  className,\n  children,\n  ...props\n}: PulsingBorderPromptProps) {\n  const [value, setValue] = React.useState(\"\")\n  const [files, setFiles] = React.useState<Attachment[]>([])\n  const [focused, setFocused] = React.useState(false)\n  const [dragging, setDragging] = React.useState(false)\n  const [mode, setMode] = React.useState(defaultMode ?? modes?.[0]?.value)\n  const fileInput = React.useRef<HTMLInputElement>(null)\n  const glow = React.useRef<GlowState>({\n    status,\n    focused,\n    dragging,\n    colors,\n    speed,\n    energy: 0,\n    flash: null,\n  })\n\n  const busy = status === \"submitted\" || status === \"streaming\"\n  const text = value.trim()\n  const activeColors =\n    modes?.find((option) => option.value === mode)?.colors ?? colors\n\n  // Hand the latest state to the glow, which animates outside of React.\n  React.useEffect(() => {\n    Object.assign(glow.current, {\n      status,\n      focused,\n      dragging,\n      colors: activeColors,\n      speed,\n    })\n  })\n\n  // Flash once when a response finishes, or fails.\n  const previousStatus = React.useRef(status)\n  React.useEffect(() => {\n    const previous = previousStatus.current\n    previousStatus.current = status\n    if (status === \"error\") {\n      glow.current.flash = { kind: \"error\", start: performance.now() }\n    } else if (\n      status === \"ready\" &&\n      (previous === \"submitted\" || previous === \"streaming\")\n    ) {\n      glow.current.flash = { kind: \"done\", start: performance.now() }\n    }\n  }, [status])\n\n  // Free image previews when the input goes away.\n  const filesRef = React.useRef(files)\n  React.useEffect(() => {\n    filesRef.current = files\n  }, [files])\n  React.useEffect(() => () => filesRef.current.forEach(revokePreview), [])\n\n  function addFiles(list: FileList | null) {\n    const added = Array.from(list ?? [])\n      .filter((file) => matchesAccept(file, accept))\n      .map((file) => ({\n        id: nextAttachmentId++,\n        file,\n        preview: file.type.startsWith(\"image/\")\n          ? URL.createObjectURL(file)\n          : undefined,\n      }))\n    if (added.length) setFiles((current) => [...current, ...added])\n  }\n\n  function removeFile(attachment: Attachment) {\n    revokePreview(attachment)\n    setFiles((current) => current.filter((item) => item !== attachment))\n  }\n\n  return (\n    <form\n      data-slot=\"pulsing-border-prompt\"\n      aria-busy={busy}\n      className={cn(\"relative isolate w-full max-w-xl\", className)}\n      onSubmit={(event) => {\n        event.preventDefault()\n        if ((!text && !files.length) || busy) return\n        onSubmit?.({ text, files: files.map((item) => item.file), mode })\n        files.forEach(revokePreview)\n        setFiles([])\n        setValue(\"\")\n      }}\n      onDragEnter={(event) => {\n        if (!attachments || !hasFiles(event)) return\n        event.preventDefault()\n        setDragging(true)\n      }}\n      onDragOver={(event) => {\n        if (!attachments || !hasFiles(event)) return\n        event.preventDefault()\n      }}\n      onDragLeave={(event) => {\n        if (!event.currentTarget.contains(event.relatedTarget as Node)) {\n          setDragging(false)\n        }\n      }}\n      onDrop={(event) => {\n        if (!attachments || !hasFiles(event)) return\n        event.preventDefault()\n        setDragging(false)\n        addFiles(event.dataTransfer.files)\n      }}\n      {...props}\n    >\n      <Glow state={glow} />\n      <div className=\"relative flex flex-col gap-2 border bg-card p-3 text-card-foreground\">\n        {files.length > 0 && (\n          <ul className=\"flex flex-wrap gap-2\">\n            {files.map((attachment) => (\n              <li\n                key={attachment.id}\n                className=\"flex h-10 max-w-52 items-center gap-2 border bg-background pr-1 text-xs\"\n              >\n                {attachment.preview ? (\n                  <span\n                    aria-hidden\n                    className=\"size-10 shrink-0 bg-cover bg-center\"\n                    style={{ backgroundImage: `url(${attachment.preview})` }}\n                  />\n                ) : (\n                  <span\n                    aria-hidden\n                    className=\"flex size-10 shrink-0 items-center justify-center bg-muted\"\n                  >\n                    <FileIcon className=\"size-4 text-muted-foreground\" />\n                  </span>\n                )}\n                <span className=\"flex min-w-0 flex-col\">\n                  <span className=\"truncate font-medium\">\n                    {attachment.file.name}\n                  </span>\n                  <span className=\"text-muted-foreground\">\n                    {formatSize(attachment.file.size)}\n                  </span>\n                </span>\n                <Button\n                  type=\"button\"\n                  variant=\"ghost\"\n                  size=\"icon-xs\"\n                  aria-label={`Remove ${attachment.file.name}`}\n                  onClick={() => removeFile(attachment)}\n                >\n                  <XIcon />\n                </Button>\n              </li>\n            ))}\n          </ul>\n        )}\n        <textarea\n          aria-label={placeholder}\n          value={value}\n          placeholder={placeholder}\n          rows={2}\n          className=\"field-sizing-content max-h-48 min-h-12 w-full resize-none bg-transparent px-1 text-sm outline-none placeholder:text-muted-foreground\"\n          onChange={(event) => {\n            setValue(event.target.value)\n            // Every keystroke brightens the glow a little, then it fades.\n            glow.current.energy = Math.min(1, glow.current.energy + 0.25)\n          }}\n          onFocus={() => setFocused(true)}\n          onBlur={() => setFocused(false)}\n          onPaste={(event) => {\n            if (!attachments || !event.clipboardData.files.length) return\n            event.preventDefault()\n            addFiles(event.clipboardData.files)\n          }}\n          onKeyDown={(event) => {\n            // Enter sends, Shift+Enter adds a new line. Skip while an IME is\n            // composing so picking a suggestion doesn't send the prompt.\n            if (\n              event.key === \"Enter\" &&\n              !event.shiftKey &&\n              !event.nativeEvent.isComposing\n            ) {\n              event.preventDefault()\n              event.currentTarget.form?.requestSubmit()\n            }\n          }}\n        />\n        <div className=\"flex items-center justify-between gap-2\">\n          <div className=\"flex min-w-0 items-center gap-1\">\n            {attachments && (\n              <>\n                <input\n                  ref={fileInput}\n                  type=\"file\"\n                  accept={accept}\n                  multiple\n                  hidden\n                  onChange={(event) => {\n                    addFiles(event.target.files)\n                    event.target.value = \"\"\n                  }}\n                />\n                <Button\n                  type=\"button\"\n                  variant=\"ghost\"\n                  size=\"icon-sm\"\n                  aria-label=\"Attach files\"\n                  onClick={() => fileInput.current?.click()}\n                >\n                  <PaperclipIcon />\n                </Button>\n              </>\n            )}\n            {modes && modes.length > 0 && (\n              <div role=\"group\" aria-label=\"Mode\" className=\"flex items-center\">\n                {modes.map((option) => (\n                  <button\n                    key={option.value}\n                    type=\"button\"\n                    aria-pressed={mode === option.value}\n                    onClick={() => {\n                      setMode(option.value)\n                      onModeChange?.(option.value)\n                    }}\n                    className=\"flex h-7 items-center gap-1.5 px-2 text-xs text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring aria-pressed:bg-muted aria-pressed:text-foreground\"\n                  >\n                    <span\n                      aria-hidden\n                      className=\"size-2 rounded-full\"\n                      style={{\n                        background: `linear-gradient(135deg, ${option.colors.join(\", \")})`,\n                      }}\n                    />\n                    {option.label}\n                  </button>\n                ))}\n              </div>\n            )}\n            {children}\n          </div>\n          {busy ? (\n            <Button\n              type=\"button\"\n              size=\"icon\"\n              aria-label=\"Stop\"\n              disabled={!onStop}\n              onClick={onStop}\n            >\n              <SquareIcon className=\"size-3 fill-current\" />\n            </Button>\n          ) : (\n            <Button\n              type=\"submit\"\n              size=\"icon\"\n              aria-label=\"Send\"\n              disabled={!text && !files.length}\n            >\n              <ArrowUpIcon />\n            </Button>\n          )}\n        </div>\n        {dragging && (\n          <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center bg-card/90 text-sm font-medium\">\n            Drop files to attach\n          </div>\n        )}\n      </div>\n    </form>\n  )\n}\n\ntype GlowState = {\n  status: PromptStatus\n  focused: boolean\n  dragging: boolean\n  colors: string[]\n  speed: number\n  /** Rises with each keystroke and decays back to 0. */\n  energy: number\n  flash: { kind: \"done\" | \"error\"; start: number } | null\n}\n\ntype Look = {\n  opacity: number\n  intensity: number\n  bloom: number\n  pulse: number\n  spotSize: number\n  speed: number\n  spots: number\n}\n\n// What the glow looks like in each state. The glow eases between them.\nconst LOOKS = {\n  // Barely there, so it doesn't compete with the page.\n  idle: {\n    opacity: 0.35,\n    intensity: 0.2,\n    bloom: 0.2,\n    pulse: 0,\n    spotSize: 0.5,\n    speed: 0.5,\n    spots: 3,\n  },\n  focused: {\n    opacity: 0.7,\n    intensity: 0.3,\n    bloom: 0.3,\n    pulse: 0.1,\n    spotSize: 0.5,\n    speed: 1,\n    spots: 3,\n  },\n  // Gathers into a few bright spots racing around the border.\n  submitted: {\n    opacity: 1,\n    intensity: 0.5,\n    bloom: 0.5,\n    pulse: 0.2,\n    spotSize: 0.3,\n    speed: 4,\n    spots: 1,\n  },\n  // A steady pulse while the answer arrives.\n  streaming: {\n    opacity: 1,\n    intensity: 0.4,\n    bloom: 0.45,\n    pulse: 0.6,\n    spotSize: 0.45,\n    speed: 2,\n    spots: 3,\n  },\n  dragging: {\n    opacity: 1,\n    intensity: 0.6,\n    bloom: 0.6,\n    pulse: 0.3,\n    spotSize: 0.6,\n    speed: 3,\n    spots: 3,\n  },\n} satisfies Record<string, Look>\n\nconst EASED_KEYS = [\n  \"opacity\",\n  \"intensity\",\n  \"bloom\",\n  \"pulse\",\n  \"spotSize\",\n  \"speed\",\n] as const\n\nconst FLASH_MS = 900\nconst ERROR_COLOR = getShaderColorFromString(\"#ff3b30\")\n\ntype ShaderMount = NonNullable<PaperShaderElement[\"paperShaderMount\"]>\n\n/**\n * The glow mounts once and never re-renders. A single animation loop reads\n * the prompt's state and eases the shader towards the matching look, without\n * going through React on every frame.\n */\nconst Glow = React.memo(function Glow({\n  state,\n}: {\n  state: React.RefObject<GlowState>\n}) {\n  const ref = React.useRef<PaperShaderElement>(null)\n\n  React.useEffect(() => {\n    const element = ref.current\n    if (!element) return\n    const reducedMotion = window.matchMedia(\n      \"(prefers-reduced-motion: reduce)\"\n    ).matches\n\n    let size = { width: 0, height: 0 }\n    const observer = new ResizeObserver(([entry]) => {\n      const box = entry.borderBoxSize[0]\n      size = { width: box.inlineSize, height: box.blockSize }\n    })\n    observer.observe(element)\n\n    const current: Omit<Look, \"spots\"> = { ...LOOKS.idle }\n    let currentColors: number[][] = []\n    let palette = { key: \"\", colors: [] as number[][] }\n    let mount: PaperShaderElement[\"paperShaderMount\"]\n    let setUniforms: ShaderMount[\"setUniforms\"] = () => {}\n    let setSpeed: ShaderMount[\"setSpeed\"] = () => {}\n    let sent: Record<string, number | number[][]> = {}\n    let sentSpeed = -1\n    let last = performance.now()\n\n    let frame = requestAnimationFrame(function tick(now) {\n      frame = requestAnimationFrame(tick)\n      const dt = Math.min(now - last, 100)\n      last = now\n\n      const glow = state.current\n      const look =\n        LOOKS[\n          glow.dragging\n            ? \"dragging\"\n            : glow.status === \"submitted\" || glow.status === \"streaming\"\n              ? glow.status\n              : glow.focused\n                ? \"focused\"\n                : \"idle\"\n        ]\n      const ease = 1 - Math.exp(-dt / 180)\n      for (const key of EASED_KEYS) {\n        current[key] += (look[key] - current[key]) * ease\n      }\n      glow.energy *= Math.exp(-dt / 300)\n\n      let flash = 0\n      if (glow.flash) {\n        const t = (now - glow.flash.start) / FLASH_MS\n        if (t >= 1) glow.flash = null\n        else flash = (1 - t) ** 2\n      }\n\n      // Cross-fade between palettes, e.g. when the mode changes. Palettes are\n      // padded to the same length so every color has one to fade into.\n      const key = glow.colors.join()\n      if (key !== palette.key) {\n        palette = { key, colors: toPalette(glow.colors) }\n      }\n      if (!currentColors.length) currentColors = palette.colors\n      currentColors = currentColors.map((color, i) =>\n        color.map((v, j) => v + (palette.colors[i][j] - v) * ease)\n      )\n      const error = glow.flash?.kind === \"error\" ? flash : 0\n      const colors = currentColors.map((color) =>\n        color.map((v, j) => v + (ERROR_COLOR[j] - v) * error)\n      )\n\n      const shader = element.paperShaderMount\n      if (!shader || !size.width || !size.height) return\n      if (shader !== mount) {\n        mount = shader\n        setUniforms = shader.setUniforms\n        setSpeed = shader.setSpeed\n        // The React wrapper re-applies its own props once, some time after\n        // mounting. Catch any write that isn't ours and send everything\n        // again on the next frame.\n        shader.setUniforms = (uniforms) => {\n          setUniforms(uniforms)\n          sent = {}\n        }\n        shader.setSpeed = (speed) => {\n          setSpeed(speed)\n          sentSpeed = -1\n        }\n        sent = {}\n        sentSpeed = -1\n      }\n\n      const uniforms: Record<string, number | number[][]> = {\n        u_colors: colors,\n        u_colorsCount: colors.length,\n        u_intensity: current.intensity + glow.energy * 0.15 + flash * 0.3,\n        u_bloom: current.bloom + glow.energy * 0.25 + flash * 0.4,\n        u_pulse: current.pulse,\n        u_spots: look.spots,\n        u_spotSize: current.spotSize,\n        u_marginLeft: GLOW / size.width,\n        u_marginRight: GLOW / size.width,\n        u_marginTop: GLOW / size.height,\n        u_marginBottom: GLOW / size.height,\n      }\n      const changed = Object.fromEntries(\n        Object.entries(uniforms).filter(\n          ([name, value]) => !isClose(sent[name], value)\n        )\n      )\n      // setUniforms redraws straight away, so only call it when something\n      // actually moved. A settled glow costs nothing extra.\n      if (Object.keys(changed).length) {\n        setUniforms(changed)\n        Object.assign(sent, changed)\n      }\n\n      const speed = reducedMotion ? 0 : current.speed * glow.speed\n      if (Math.abs(speed - sentSpeed) > 0.01) {\n        setSpeed(speed)\n        sentSpeed = speed\n      }\n\n      element.style.opacity = String(\n        Math.min(1, current.opacity + glow.energy * 0.3 + flash * 0.5)\n      )\n    })\n\n    return () => {\n      cancelAnimationFrame(frame)\n      observer.disconnect()\n    }\n  }, [state])\n\n  return (\n    <PulsingBorder\n      ref={ref}\n      aria-hidden\n      className=\"pointer-events-none absolute -z-10\"\n      // Hidden until the loop has sized the border to the input.\n      style={{ inset: -GLOW, opacity: 0 }}\n      colorBack=\"#00000000\"\n      roundness={0}\n      thickness={0.05}\n      softness={0.75}\n      smoke={0.3}\n      smokeSize={0.5}\n      scale={1}\n    />\n  )\n})\n\nfunction toPalette(colors: string[]) {\n  const count = pulsingBorderMeta.maxColorCount\n  return Array.from({ length: count }, (_, i) =>\n    getShaderColorFromString(colors[i % colors.length])\n  )\n}\n\nfunction isClose(\n  a: number | number[][] | undefined,\n  b: number | number[][]\n): boolean {\n  if (a === undefined) return false\n  if (typeof a === \"number\" || typeof b === \"number\") {\n    return typeof a === \"number\" && typeof b === \"number\"\n      ? Math.abs(a - b) < 0.001\n      : false\n  }\n  return a.every((row, i) => row.every((v, j) => Math.abs(v - b[i][j]) < 0.001))\n}\n\nfunction hasFiles(event: React.DragEvent) {\n  return event.dataTransfer.types.includes(\"Files\")\n}\n\nfunction matchesAccept(file: File, accept?: string) {\n  if (!accept) return true\n  return accept.split(\",\").some((rule) => {\n    const type = rule.trim().toLowerCase()\n    if (type.startsWith(\".\")) return file.name.toLowerCase().endsWith(type)\n    if (type.endsWith(\"/*\")) return file.type.startsWith(type.slice(0, -1))\n    return file.type === type\n  })\n}\n\nfunction revokePreview(attachment: Attachment) {\n  if (attachment.preview) URL.revokeObjectURL(attachment.preview)\n}\n\nfunction formatSize(bytes: number) {\n  if (bytes < 1024) return `${bytes} B`\n  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`\n  return `${(bytes / 1024 / 1024).toFixed(1)} MB`\n}\n\nexport {\n  PulsingBorderPrompt,\n  type PromptMessage,\n  type PromptMode,\n  type PromptStatus,\n}\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "components",
    "inputs"
  ],
  "type": "registry:component"
}