Claude Skill

ai-elements

Build AI chat interfaces using ai-elements components — conversations, messages, tool displays, prompt inputs, and more. Use when the user wants to build a chatbot, AI assistant UI, or any AI-powered chat interface.

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download mxyhi-ok-skills-ai-elements-7933c15.zip · 356 KB
mxyhi/ok-skills 490 46 forks Apache-2.0 Updated 5d ago
Part of mxyhi/ok-skills — 37 skills

Install

skills CLI npx skills add https://github.com/mxyhi/ok-skills/tree/main/ai-elements
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install mxyhi-ok-skills@llmmart
Git git clone https://github.com/mxyhi/ok-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole mxyhi/ok-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

AI Elements

AI Elements is a component library and custom registry built on top of shadcn/ui to help you build AI-native applications faster. It provides pre-built components like conversations, messages and more.

Installing AI Elements is straightforward and can be done in a couple of ways. You can use the dedicated CLI command for the fastest setup, or integrate via the standard shadcn/ui CLI if you've already adopted shadcn's workflow.

IMPORTANT: Run all CLI commands using the project's package runner: npx ai-elements@latest, pnpm dlx ai-elements@latest, or bunx --bun ai-elements@latest — based on the project's packageManager. Examples below use npx ai-elements@latest but substitute the correct runner for the project.

Prerequisites

Before installing AI Elements, make sure your environment meets the following requirements:

  • Node.js, version 18 or later
  • A Next.js project with the AI SDK installed.
  • shadcn/ui installed in your project. If you don't have it installed, running any install command will automatically install it for you.
  • We also highly recommend using the AI Gateway and adding AI_GATEWAY_API_KEY to your env.local so you don't have to use an API key from every provider. AI Gateway also gives $5 in usage per month so you can experiment with models. You can obtain an API key here.

Installing Components

You can install AI Elements components using either the AI Elements CLI or the shadcn/ui CLI. Both achieve the same result: adding the selected component’s code and any needed dependencies to your project.

The CLI will download the component’s code and integrate it into your project’s directory (usually under your components folder). By default, AI Elements components are added to the @/components/ai-elements/ directory (or whatever folder you’ve configured in your shadcn components settings).

After running the command, you should see a confirmation in your terminal that the files were added. You can then proceed to use the component in your code.

Usage

Once an AI Elements component is installed, you can import it and use it in your application like any other React component. The components are added as part of your codebase (not hidden in a library), so the usage feels very natural.

Example

After installing AI Elements components, you can use them in your application like any other React component. For example:

"use client";

import {
  Message,
  MessageContent,
  MessageResponse,
} from "@/components/ai-elements/message";
import { useChat } from "@ai-sdk/react";

const Example = () => {
  const { messages } = useChat();

  return (
    <>
      {messages.map(({ role, parts }, index) => (
        <Message from={role} key={index}>
          <MessageContent>
            {parts.map((part, i) => {
              switch (part.type) {
                case "text":
                  return (
                    <MessageResponse key={`${role}-${i}`}>
                      {part.text}
                    </MessageResponse>
                  );
              }
            })}
          </MessageContent>
        </Message>
      ))}
    </>
  );
};

export default Example;

In the example above, we import the Message component from our AI Elements directory and include it in our JSX. Then, we compose the component with the MessageContent and MessageResponse subcomponents. You can style or configure the component just as you would if you wrote it yourself – since the code lives in your project, you can even open the component file to see how it works or make custom modifications.

Extensibility

All AI Elements components take as many primitive attributes as possible. For example, the Message component extends HTMLAttributes<HTMLDivElement>, so you can pass any props that a div supports. This makes it easy to extend the component with your own styles or functionality.

Customization

After installation, no additional setup is needed. The component’s styles (Tailwind CSS classes) and scripts are already integrated. You can start interacting with the component in your app immediately.

For example, if you'd like to remove the rounding on Message, you can go to components/ai-elements/message.tsx and remove rounded-lg as follows:

export const MessageContent = ({
  children,
  className,
  ...props
}: MessageContentProps) => (
  <div
    className={cn(
      "flex flex-col gap-2 text-sm text-foreground",
      "group-[.is-user]:bg-primary group-[.is-user]:text-primary-foreground group-[.is-user]:px-4 group-[.is-user]:py-3",
      className
    )}
    {...props}
  >
    <div className="is-user:dark">{children}</div>
  </div>
);

Troubleshooting

Why are my components not styled?

Make sure your project is configured correctly for shadcn/ui in Tailwind 4 - this means having a globals.css file that imports Tailwind and includes the shadcn/ui base styles.

I ran the AI Elements CLI but nothing was added to my project

Double-check that:

  • Your current working directory is the root of your project (where package.json lives).
  • Your components.json file (if using shadcn-style config) is set up correctly.
  • You’re using the latest version of the AI Elements CLI:
npx ai-elements@latest

If all else fails, feel free to open an issue on GitHub.

Theme switching doesn’t work — my app stays in light mode

Ensure your app is using the same data-theme system that shadcn/ui and AI Elements expect. The default implementation toggles a data-theme attribute on the <html> element. Make sure your tailwind.config.js is using class or data- selectors accordingly.

The component imports fail with “module not found”

Check the file exists. If it does, make sure your tsconfig.json has a proper paths alias for @/ i.e.

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./*"]
    }
  }
}

My AI coding assistant can't access AI Elements components

  1. Verify your config file syntax is valid JSON.
  2. Check that the file path is correct for your AI tool.
  3. Restart your coding assistant after making changes.
  4. Ensure you have a stable internet connection.

Still stuck?

If none of these answers help, open an issue on GitHub and someone will be happy to assist.

Available Components

See the references/ folder for detailed documentation on each component.

Files (ok-skills)
  • references
    • agent.md 4.1 KB
      # Agent
      
      A composable component for displaying AI agent configuration with model, instructions, tools, and output schema.
      
      The `Agent` component displays an interface for showing AI agent configuration details. It's designed to represent a configured agent from the AI SDK, showing the agent's model, system instructions, available tools (with expandable input schemas), and output schema.
      
      See `scripts/agent.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add agent
      ```
      
      ## Usage with AI SDK
      
      Display an agent's configuration alongside your chat interface. Tools are displayed in an accordion where clicking the description expands to show the input schema.
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { tool } from "ai";
      import { z } from "zod";
      import {
        Agent,
        AgentContent,
        AgentHeader,
        AgentInstructions,
        AgentOutput,
        AgentTool,
        AgentTools,
      } from "@/components/ai-elements/agent";
      
      const webSearch = tool({
        description: "Search the web for information",
        inputSchema: z.object({
          query: z.string().describe("The search query"),
        }),
      });
      
      const readUrl = tool({
        description: "Read and parse content from a URL",
        inputSchema: z.object({
          url: z.string().url().describe("The URL to read"),
        }),
      });
      
      const outputSchema = `z.object({
        sentiment: z.enum(['positive', 'negative', 'neutral']),
        score: z.number(),
        summary: z.string(),
      })`;
      
      export default function Page() {
        return (
          <Agent>
            <AgentHeader
              name="Sentiment Analyzer"
              model="anthropic/claude-sonnet-4-5"
            />
            <AgentContent>
              <AgentInstructions>
                Analyze the sentiment of the provided text and return a structured
                analysis with sentiment classification, confidence score, and summary.
              </AgentInstructions>
              <AgentTools>
                <AgentTool tool={webSearch} value="web_search" />
                <AgentTool tool={readUrl} value="read_url" />
              </AgentTools>
              <AgentOutput schema={outputSchema} />
            </AgentContent>
          </Agent>
        );
      }
      ```
      
      ## Features
      
      - Model badge in header
      - Instructions rendered as markdown
      - Tools displayed as accordion items with expandable input schemas
      - Output schema display with syntax highlighting
      - Composable structure for flexible layouts
      - Works with AI SDK `Tool` type
      
      ## Props
      
      ### `<Agent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any props are spread to the root div. |
      
      ### `<AgentHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `name` | `string` | Required | The name of the agent. |
      | `model` | `string` | - | The model identifier (e.g.  |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the container div. |
      
      ### `<AgentContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the container div. |
      
      ### `<AgentInstructions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `string` | Required | The instruction text. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the container div. |
      
      ### `<AgentTools />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Accordion>` | - | Any other props are spread to the Accordion component. |
      
      ### `<AgentTool />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `tool` | `Tool` | Required | The tool object from the AI SDK containing description and inputSchema. |
      | `value` | `string` | Required | Unique identifier for the accordion item. |
      | `...props` | `React.ComponentProps<typeof AccordionItem>` | - | Any other props are spread to the AccordionItem component. |
      
      ### `<AgentOutput />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `schema` | `string` | Required | The output schema as a string (displayed with syntax highlighting). |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the container div. |
      
    • artifact.md 2.9 KB
      # Artifact
      
      A container component for displaying generated content like code, documents, or other outputs with built-in actions.
      
      The `Artifact` component provides a structured container for displaying generated content like code, documents, or other outputs with built-in header actions.
      
      See `scripts/artifact.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add artifact
      ```
      
      ## Features
      
      - Structured container with header and content areas
      - Built-in header with title and description support
      - Flexible action buttons with tooltips
      - Customizable styling for all subcomponents
      - Support for close buttons and action groups
      - Clean, modern design with border and shadow
      - Responsive layout that adapts to content
      - TypeScript support with proper type definitions
      - Composable architecture for maximum flexibility
      
      ## Examples
      
      ### With Code Display
      
      See `scripts/artifact.tsx` for this example.
      
      ## Props
      
      ### `<Artifact />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the underlying div element. |
      
      ### `<ArtifactHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the underlying div element. |
      
      ### `<ArtifactTitle />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLParagraphElement>` | - | Any other props are spread to the underlying paragraph element. |
      
      ### `<ArtifactDescription />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLParagraphElement>` | - | Any other props are spread to the underlying paragraph element. |
      
      ### `<ArtifactActions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the underlying div element. |
      
      ### `<ArtifactAction />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `tooltip` | `string` | - | Tooltip text to display on hover. |
      | `label` | `string` | - | Screen reader label for the action button. |
      | `icon` | `LucideIcon` | - | Lucide icon component to display in the button. |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `<ArtifactClose />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `<ArtifactContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the underlying div element. |
      
    • attachments.md 5.6 KB
      # Attachments
      
      A flexible, composable attachment component for displaying files, images, videos, audio, and source documents.
      
      The `Attachment` component provides a unified way to display file attachments and source documents with multiple layout variants.
      
      See `scripts/attachments.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add attachments
      ```
      
      ## Usage with AI SDK
      
      Display user-uploaded files in chat messages or input areas.
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import {
        Attachments,
        Attachment,
        AttachmentPreview,
        AttachmentInfo,
        AttachmentRemove,
      } from "@/components/ai-elements/attachments";
      import type { FileUIPart } from "ai";
      
      interface MessageProps {
        attachments: (FileUIPart & { id: string })[];
        onRemove?: (id: string) => void;
      }
      
      const MessageAttachments = ({ attachments, onRemove }: MessageProps) => (
        <Attachments variant="grid">
          {attachments.map((file) => (
            <Attachment
              key={file.id}
              data={file}
              onRemove={onRemove ? () => onRemove(file.id) : undefined}
            >
              <AttachmentPreview />
              <AttachmentRemove />
            </Attachment>
          ))}
        </Attachments>
      );
      
      export default MessageAttachments;
      ```
      
      ## Features
      
      - Three display variants: grid (thumbnails), inline (badges), and list (rows)
      - Supports both FileUIPart and SourceDocumentUIPart from the AI SDK
      - Automatic media type detection (image, video, audio, document, source)
      - Hover card support for inline previews
      - Remove button with customizable callback
      - Composable architecture for maximum flexibility
      - Accessible with proper ARIA labels
      - TypeScript support with exported utility functions
      
      ## Examples
      
      ### Grid Variant
      
      Best for displaying attachments in messages with visual thumbnails.
      
      See `scripts/attachments.tsx` for this example.
      
      ### Inline Variant
      
      Best for compact badge-style display in input areas with hover previews.
      
      See `scripts/attachments-inline.tsx` for this example.
      
      ### List Variant
      
      Best for file lists with full metadata display.
      
      See `scripts/attachments-list.tsx` for this example.
      
      ## Props
      
      ### `<Attachments />`
      
      Container component that sets the layout variant.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `variant` | `unknown` | - | The display layout variant. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the underlying div element. |
      
      ### `<Attachment />`
      
      Individual attachment item wrapper.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `data` | `unknown` | - | The attachment data (FileUIPart or SourceDocumentUIPart with id). |
      | `onRemove` | `() => void` | - | Callback fired when the remove button is clicked. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the underlying div element. |
      
      ### `<AttachmentPreview />`
      
      Displays the media preview (image, video, or icon).
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `fallbackIcon` | `React.ReactNode` | - | Custom icon to display when no preview is available. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the underlying div element. |
      
      ### `<AttachmentInfo />`
      
      Displays the filename and optional media type.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `showMediaType` | `boolean` | `false` | Whether to show the media type below the filename. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the underlying div element. |
      
      ### `<AttachmentRemove />`
      
      Remove button that appears on hover.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `label` | `string` | - | Screen reader label for the button. |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Spread to the underlying Button component. |
      
      ### `<AttachmentHoverCard />`
      
      Wrapper for hover preview functionality.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `openDelay` | `number` | `0` | Delay in ms before opening the hover card. |
      | `closeDelay` | `number` | `0` | Delay in ms before closing the hover card. |
      | `...props` | `React.ComponentProps<typeof HoverCard>` | - | Spread to the underlying HoverCard component. |
      
      ### `<AttachmentHoverCardTrigger />`
      
      Trigger element for the hover card.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof HoverCardTrigger>` | - | Spread to the underlying HoverCardTrigger component. |
      
      ### `<AttachmentHoverCardContent />`
      
      Content displayed in the hover card.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `align` | `unknown` | - | Alignment of the hover card content. |
      | `...props` | `React.ComponentProps<typeof HoverCardContent>` | - | Spread to the underlying HoverCardContent component. |
      
      ### `<AttachmentEmpty />`
      
      Empty state component when no attachments are present.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the underlying div element. |
      
      ## Utility Functions
      
      ### `getMediaCategory(data)`
      
      Returns the media category for an attachment.
      
      ```tsx
      import { getMediaCategory } from "@/components/ai-elements/attachments";
      
      const category = getMediaCategory(attachment);
      // Returns: "image" | "video" | "audio" | "document" | "source" | "unknown"
      ```
      
      ### `getAttachmentLabel(data)`
      
      Returns the display label for an attachment.
      
      ```tsx
      import { getAttachmentLabel } from "@/components/ai-elements/attachments";
      
      const label = getAttachmentLabel(attachment);
      // Returns filename or fallback like "Image" or "Attachment"
      ```
      
    • audio-player.md 5.2 KB
      # Audio Player
      
      A composable audio player component built on media-chrome, with shadcn styling and flexible controls.
      
      The `AudioPlayer` component provides a flexible and customizable audio playback interface built on top of media-chrome. It features a composable architecture that allows you to build audio experiences with custom controls, metadata display, and seamless integration with AI-generated audio content.
      
      See `scripts/audio-player.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add audio-player
      ```
      
      ## Features
      
      - Built on media-chrome for reliable audio playback
      - Fully composable architecture with granular control components
      - ButtonGroup integration for cohesive control layout
      - Individual control components (play, seek, volume, etc.)
      - Flexible layout with customizable control bars
      - CSS custom properties for deep theming
      - Shadcn/ui Button component styling
      - Responsive design that works across devices
      - Full TypeScript support with proper types for all components
      
      ## Variants
      
      ### AI SDK Speech Result
      
      The `AudioPlayer` component can be used to play audio from an AI SDK Speech Result.
      
      See `scripts/audio-player.tsx` for this example.
      
      ### Remote Audio
      
      The `AudioPlayer` component can be used to play remote audio files.
      
      See `scripts/audio-player-remote.tsx` for this example.
      
      ## Props
      
      ### `<AudioPlayer />`
      
      Root MediaController component. Accepts all MediaController props except `audio` (which is set to `true` by default).
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `style` | `CSSProperties` | - | Custom CSS properties can be passed to override media-chrome theming variables. |
      | `...props` | `Omit<React.ComponentProps<typeof MediaController>, ` | - | Any other props are spread to the MediaController component. |
      
      ### `<AudioPlayerElement />`
      
      The audio element that contains the media source. Accepts either a remote URL or AI SDK Speech Result data.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `src` | `string` | - | The URL of the audio file to play (for remote audio). |
      | `data` | `SpeechResult[` | - | AI SDK Speech Result audio data with base64 encoding (for AI-generated audio). |
      | `...props` | `Omit<React.ComponentProps<` | - | Any other props are spread to the audio element (excluding src when using data). |
      
      ### `<AudioPlayerControlBar />`
      
      Container for control buttons, wraps children in a ButtonGroup.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof MediaControlBar>` | - | Any other props are spread to the MediaControlBar component. |
      
      ### `<AudioPlayerPlayButton />`
      
      Play/pause button wrapped in a shadcn Button component.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof MediaPlayButton>` | - | Any other props are spread to the MediaPlayButton component. |
      
      ### `<AudioPlayerSeekBackwardButton />`
      
      Seek backward button wrapped in a shadcn Button component.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `seekOffset` | `number` | `10` | The number of seconds to seek backward. |
      | `...props` | `React.ComponentProps<typeof MediaSeekBackwardButton>` | - | Any other props are spread to the MediaSeekBackwardButton component. |
      
      ### `<AudioPlayerSeekForwardButton />`
      
      Seek forward button wrapped in a shadcn Button component.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `seekOffset` | `number` | `10` | The number of seconds to seek forward. |
      | `...props` | `React.ComponentProps<typeof MediaSeekForwardButton>` | - | Any other props are spread to the MediaSeekForwardButton component. |
      
      ### `<AudioPlayerTimeDisplay />`
      
      Displays the current playback time, wrapped in ButtonGroupText.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof MediaTimeDisplay>` | - | Any other props are spread to the MediaTimeDisplay component. |
      
      ### `<AudioPlayerTimeRange />`
      
      Seek slider for controlling playback position, wrapped in ButtonGroupText.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof MediaTimeRange>` | - | Any other props are spread to the MediaTimeRange component. |
      
      ### `<AudioPlayerDurationDisplay />`
      
      Displays the total duration of the audio, wrapped in ButtonGroupText.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof MediaDurationDisplay>` | - | Any other props are spread to the MediaDurationDisplay component. |
      
      ### `<AudioPlayerMuteButton />`
      
      Mute/unmute button, wrapped in ButtonGroupText.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof MediaMuteButton>` | - | Any other props are spread to the MediaMuteButton component. |
      
      ### `<AudioPlayerVolumeRange />`
      
      Volume slider control, wrapped in ButtonGroupText.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof MediaVolumeRange>` | - | Any other props are spread to the MediaVolumeRange component. |
      
    • canvas.md 1.1 KB
      # Canvas
      
      A React Flow-based canvas component for building interactive node-based interfaces.
      
      The `Canvas` component provides a React Flow-based canvas for building interactive node-based interfaces. It comes pre-configured with sensible defaults for AI applications, including panning, zooming, and selection behaviors.
      
      
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add canvas
      ```
      
      ## Features
      
      - Pre-configured React Flow canvas with AI-optimized defaults
      - Pan on scroll enabled for intuitive navigation
      - Selection on drag for multi-node operations
      - Customizable background color using CSS variables
      - Delete key support (Backspace and Delete keys)
      - Auto-fit view to show all nodes
      - Disabled double-click zoom for better UX
      - Disabled pan on drag to prevent accidental canvas movement
      - Fully compatible with React Flow props and API
      
      ## Props
      
      ### `<Canvas />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `ReactNode` | - | Child components like Background, Controls, or MiniMap. |
      | `...props` | `ReactFlowProps` | - | Any other React Flow props like nodes, edges, nodeTypes, edgeTypes, onNodesChange, etc. |
      
    • chain-of-thought.md 3.3 KB
      # Chain of Thought
      
      A collapsible component that visualizes AI reasoning steps with support for search results, images, and step-by-step progress indicators.
      
      The `ChainOfThought` component provides a visual representation of an AI's reasoning process, showing step-by-step thinking with support for search results, images, and progress indicators. It helps users understand how AI arrives at conclusions.
      
      See `scripts/chain-of-thought.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add chain-of-thought
      ```
      
      ## Features
      
      - Collapsible interface with smooth animations powered by Radix UI
      - Step-by-step visualization of AI reasoning process
      - Support for different step statuses (complete, active, pending)
      - Built-in search results display with badge styling
      - Image support with captions for visual content
      - Custom icons for different step types
      - Context-aware components using React Context API
      - Fully typed with TypeScript
      - Accessible with keyboard navigation support
      - Responsive design that adapts to different screen sizes
      - Smooth fade and slide animations for content transitions
      - Composable architecture for flexible customization
      
      ## Props
      
      ### `<ChainOfThought />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `open` | `boolean` | - | Controlled open state of the collapsible. |
      | `defaultOpen` | `boolean` | `false` | Default open state when uncontrolled. |
      | `onOpenChange` | `(open: boolean) => void` | - | Callback when the open state changes. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the root div element. |
      
      ### `<ChainOfThoughtHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom header text. |
      | `...props` | `React.ComponentProps<typeof CollapsibleTrigger>` | - | Any other props are spread to the CollapsibleTrigger component. |
      
      ### `<ChainOfThoughtStep />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `icon` | `LucideIcon` | `DotIcon` | Icon to display for the step. |
      | `label` | `string` | - | The main text label for the step. |
      | `description` | `string` | - | Optional description text shown below the label. |
      | `status` | `unknown` | - | Visual status of the step. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the root div element. |
      
      ### `<ChainOfThoughtSearchResults />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any props are spread to the container div element. |
      
      ### `<ChainOfThoughtSearchResult />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Badge>` | - | Any props are spread to the Badge component. |
      
      ### `<ChainOfThoughtContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleContent>` | - | Any props are spread to the CollapsibleContent component. |
      
      ### `<ChainOfThoughtImage />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `caption` | `string` | - | Optional caption text displayed below the image. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the container div element. |
      
    • checkpoint.md 5.5 KB
      # Checkpoint
      
      A simple component for marking conversation history points and restoring the chat to a previous state.
      
      The `Checkpoint` component provides a way to mark specific points in a conversation history and restore the chat to that state. Inspired by VSCode's Copilot checkpoint feature, it allows users to revert to an earlier conversation state while maintaining a clear visual separation between different conversation segments.
      
      See `scripts/checkpoint.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add checkpoint
      ```
      
      ## Features
      
      - Simple flex layout with icon, trigger, and separator
      - Visual separator line for clear conversation breaks
      - Clickable restore button for reverting to checkpoint
      - Customizable icon (defaults to BookmarkIcon)
      - Keyboard accessible with proper ARIA labels
      - Responsive design that adapts to different screen sizes
      - Seamless light/dark theme integration
      
      ## Usage with AI SDK
      
      Build a chat interface with conversation checkpoints that allow users to restore to previous states.
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { useState, Fragment } from "react";
      import { useChat } from "@ai-sdk/react";
      import {
        Checkpoint,
        CheckpointIcon,
        CheckpointTrigger,
      } from "@/components/ai-elements/checkpoint";
      import {
        Message,
        MessageContent,
        MessageResponse,
      } from "@/components/ai-elements/message";
      import {
        Conversation,
        ConversationContent,
      } from "@/components/ai-elements/conversation";
      
      type CheckpointType = {
        id: string;
        messageIndex: number;
        timestamp: Date;
        messageCount: number;
      };
      
      const CheckpointDemo = () => {
        const { messages, setMessages } = useChat();
        const [checkpoints, setCheckpoints] = useState<CheckpointType[]>([]);
      
        const createCheckpoint = (messageIndex: number) => {
          const checkpoint: CheckpointType = {
            id: nanoid(),
            messageIndex,
            timestamp: new Date(),
            messageCount: messageIndex + 1,
          };
          setCheckpoints([...checkpoints, checkpoint]);
        };
      
        const restoreToCheckpoint = (messageIndex: number) => {
          // Restore messages to checkpoint state
          setMessages(messages.slice(0, messageIndex + 1));
          // Remove checkpoints after this point
          setCheckpoints(checkpoints.filter((cp) => cp.messageIndex <= messageIndex));
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <Conversation>
              <ConversationContent>
                {messages.map((message, index) => {
                  const checkpoint = checkpoints.find(
                    (cp) => cp.messageIndex === index
                  );
      
                  return (
                    <Fragment key={message.id}>
                      <Message from={message.role}>
                        <MessageContent>
                          <MessageResponse>{message.content}</MessageResponse>
                        </MessageContent>
                      </Message>
                      {checkpoint && (
                        <Checkpoint>
                          <CheckpointIcon />
                          <CheckpointTrigger
                            onClick={() =>
                              restoreToCheckpoint(checkpoint.messageIndex)
                            }
                          >
                            Restore checkpoint
                          </CheckpointTrigger>
                        </Checkpoint>
                      )}
                    </Fragment>
                  );
                })}
              </ConversationContent>
            </Conversation>
          </div>
        );
      };
      
      export default CheckpointDemo;
      ```
      
      ## Use Cases
      
      ### Manual Checkpoints
      
      Allow users to manually create checkpoints at important conversation points:
      
      ```tsx
      <Button onClick={() => createCheckpoint(messages.length - 1)}>
        Create Checkpoint
      </Button>
      ```
      
      ### Automatic Checkpoints
      
      Create checkpoints automatically after significant conversation milestones:
      
      ```tsx
      useEffect(() => {
        // Create checkpoint every 5 messages
        if (messages.length > 0 && messages.length % 5 === 0) {
          createCheckpoint(messages.length - 1);
        }
      }, [messages.length]);
      ```
      
      ### Branching Conversations
      
      Use checkpoints to enable conversation branching where users can explore different conversation paths:
      
      ```tsx
      const restoreAndBranch = (messageIndex: number) => {
        // Save current branch
        const currentBranch = messages.slice(messageIndex + 1);
        saveBranch(currentBranch);
      
        // Restore to checkpoint
        restoreToCheckpoint(messageIndex);
      };
      ```
      
      ## Props
      
      ### `<Checkpoint />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | The checkpoint icon and trigger components. Automatically includes a Separator at the end. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the root div. |
      
      ### `<CheckpointIcon />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom icon content. If not provided, defaults to a BookmarkIcon from lucide-react. |
      | `...props` | `LucideProps` | - | Any other props are spread to the BookmarkIcon component. |
      
      ### `<CheckpointTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | The text or content to display in the trigger button. |
      | `tooltip` | `string` | - | Optional tooltip text shown on hover. |
      | `variant` | `string` | - | The button variant style. |
      | `size` | `string` | - | The button size. |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
    • code-block.md 5.4 KB
      # Code Block
      
      Provides syntax highlighting, line numbers, and copy to clipboard functionality for code blocks.
      
      The `CodeBlock` component provides syntax highlighting, line numbers, and copy to clipboard functionality for code blocks. It's fully composable, allowing you to customize the header, actions, and content.
      
      See `scripts/code-block.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add code-block
      ```
      
      ## Usage
      
      The CodeBlock is fully composable. Here's a basic example:
      
      ```tsx
      import {
        CodeBlock,
        CodeBlockActions,
        CodeBlockCopyButton,
        CodeBlockFilename,
        CodeBlockHeader,
        CodeBlockTitle,
      } from "@/components/ai-elements/code-block";
      import { FileIcon } from "lucide-react";
      
      export const Example = () => (
        <CodeBlock code={code} language="typescript">
          <CodeBlockHeader>
            <CodeBlockTitle>
              <FileIcon size={14} />
              <CodeBlockFilename>example.ts</CodeBlockFilename>
            </CodeBlockTitle>
            <CodeBlockActions>
              <CodeBlockCopyButton />
            </CodeBlockActions>
          </CodeBlockHeader>
        </CodeBlock>
      );
      ```
      
      ## Features
      
      - Syntax highlighting with Shiki
      - Line numbers (optional)
      - Copy to clipboard functionality
      - Automatic light/dark theme switching via CSS variables
      - Language selector for multi-language examples
      - Fully composable architecture
      - Accessible design
      
      ## Examples
      
      ### Dark Mode
      
      To use the `CodeBlock` component in dark mode, wrap it in a `div` with the `dark` class.
      
      See `scripts/code-block-dark.tsx` for this example.
      
      ### Language Selector
      
      Add a language selector to switch between different code implementations:
      
      See `scripts/code-block.tsx` for this example.
      
      ## Props
      
      ### `<CodeBlock />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `code` | `string` | - | The code content to display. |
      | `language` | `BundledLanguage` | - | The programming language for syntax highlighting. |
      | `showLineNumbers` | `boolean` | `false` | Whether to show line numbers. |
      | `children` | `React.ReactNode` | - | Child elements like CodeBlockHeader. |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<CodeBlockHeader />`
      
      Container for the header row. Uses flexbox with `justify-between`.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Header content (CodeBlockTitle, CodeBlockActions, etc.). |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<CodeBlockTitle />`
      
      Left-aligned container for icon and filename. Uses flexbox with `gap-2`.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Title content (icon, CodeBlockFilename, etc.). |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<CodeBlockFilename />`
      
      Displays the filename in monospace font.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | The filename to display. |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<CodeBlockActions />`
      
      Right-aligned container for action buttons. Uses flexbox with `gap-2`.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Action buttons (CodeBlockCopyButton, CodeBlockLanguageSelector, etc.). |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<CodeBlockCopyButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `onCopy` | `() => void` | - | Callback fired after a successful copy. |
      | `onError` | `(error: Error) => void` | - | Callback fired if copying fails. |
      | `timeout` | `number` | `2000` | How long to show the copied state (ms). |
      | `children` | `React.ReactNode` | - | Custom content for the button. Defaults to copy/check icons. |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<CodeBlockLanguageSelector />`
      
      Wrapper for the language selector. Extends shadcn/ui Select.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `value` | `string` | - | The currently selected language. |
      | `onValueChange` | `(value: string) => void` | - | Callback when the language changes. |
      | `children` | `React.ReactNode` | - | Selector components (Trigger, Content, Items). |
      
      ### `<CodeBlockLanguageSelectorTrigger />`
      
      Trigger button for the language selector dropdown. Pre-styled for code block header.
      
      ### `<CodeBlockLanguageSelectorValue />`
      
      Displays the selected language value.
      
      ### `<CodeBlockLanguageSelectorContent />`
      
      Dropdown content container. Defaults to `align="end"`.
      
      ### `<CodeBlockLanguageSelectorItem />`
      
      Individual language option in the dropdown.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `value` | `string` | - | The language value. |
      | `children` | `React.ReactNode` | - | The display label. |
      
      ### `<CodeBlockContainer />`
      
      Low-level container component with performance optimizations (`contentVisibility`). Used internally by CodeBlock.
      
      ### `<CodeBlockContent />`
      
      Low-level component that handles syntax highlighting. Used internally by CodeBlock, but can be used directly for custom layouts.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `code` | `string` | - | The code content to display. |
      | `language` | `BundledLanguage` | - | The programming language for syntax highlighting. |
      | `showLineNumbers` | `boolean` | `false` | Whether to show line numbers. |
      
    • commit.md 5.8 KB
      # Commit
      
      Display commit information with hash, message, author, and file changes.
      
      The `Commit` component displays commit details including hash, message, author, timestamp, and changed files.
      
      See `scripts/commit.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add commit
      ```
      
      ## Features
      
      - Commit hash display with copy button
      - Author avatar with initials
      - Relative timestamp formatting
      - Collapsible file changes list
      - Color-coded file status (added/modified/deleted/renamed)
      - Line additions/deletions count
      
      ## File Status
      
      | Status     | Label | Color  |
      | ---------- | ----- | ------ |
      | `added`    | A     | Green  |
      | `modified` | M     | Yellow |
      | `deleted`  | D     | Red    |
      | `renamed`  | R     | Blue   |
      
      ## Props
      
      ### `<Commit />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Collapsible>` | - | Spread to the Collapsible component. |
      
      ### `<CommitHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleTrigger>` | - | Spread to the CollapsibleTrigger component. |
      
      ### `<CommitAuthor />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<CommitAuthorAvatar />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `initials` | `string` | Required | Author initials to display. |
      | `...props` | `React.ComponentProps<typeof Avatar>` | - | Spread to the Avatar component. |
      
      ### `<CommitInfo />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<CommitMessage />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Spread to the span element. |
      
      ### `<CommitMetadata />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<CommitHash />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Spread to the span element. |
      
      ### `<CommitSeparator />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom separator content. |
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Spread to the span element. |
      
      ### `<CommitTimestamp />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `date` | `Date` | Required | Commit date. |
      | `children` | `React.ReactNode` | - | Custom timestamp content. Defaults to relative time. |
      | `...props` | `React.HTMLAttributes<HTMLTimeElement>` | - | Spread to the time element. |
      
      ### `<CommitActions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<CommitCopyButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `hash` | `string` | Required | Commit hash to copy. |
      | `onCopy` | `() => void` | - | Callback after successful copy. |
      | `onError` | `(error: Error) => void` | - | Callback if copying fails. |
      | `timeout` | `number` | `2000` | Duration to show copied state (ms). |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Spread to the Button component. |
      
      ### `<CommitContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleContent>` | - | Spread to the CollapsibleContent component. |
      
      ### `<CommitFiles />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<CommitFile />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the row div. |
      
      ### `<CommitFileInfo />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<CommitFileStatus />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `status` | `unknown` | Required | File change status. |
      | `children` | `React.ReactNode` | - | Custom status label. |
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Spread to the span element. |
      
      ### `<CommitFileIcon />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof FileIcon>` | - | Spread to the FileIcon component. |
      
      ### `<CommitFilePath />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Spread to the span element. |
      
      ### `<CommitFileChanges />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<CommitFileAdditions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `count` | `number` | Required | Number of lines added. |
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Spread to the span element. |
      
      ### `<CommitFileDeletions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `count` | `number` | Required | Number of lines deleted. |
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Spread to the span element. |
      
    • confirmation.md 8.6 KB
      # Confirmation
      
      An alert-based component for managing tool execution approval workflows with request, accept, and reject states.
      
      The `Confirmation` component provides a flexible system for displaying tool approval requests and their outcomes. Perfect for showing users when AI tools require approval before execution, and displaying the approval status afterward.
      
      See `scripts/confirmation.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add confirmation
      ```
      
      ## Usage with AI SDK
      
      Build a chat UI with tool approval workflow where dangerous tools require user confirmation before execution.
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { useChat } from "@ai-sdk/react";
      import { DefaultChatTransport, type ToolUIPart } from "ai";
      import { useState } from "react";
      import { CheckIcon, XIcon } from "lucide-react";
      import { Button } from "@/components/ui/button";
      import {
        Confirmation,
        ConfirmationTitle,
        ConfirmationRequest,
        ConfirmationAccepted,
        ConfirmationRejected,
        ConfirmationActions,
        ConfirmationAction,
      } from "@/components/ai-elements/confirmation";
      import { MessageResponse } from "@/components/ai-elements/message";
      
      type DeleteFileInput = {
        filePath: string;
        confirm: boolean;
      };
      
      type DeleteFileToolUIPart = ToolUIPart<{
        delete_file: {
          input: DeleteFileInput;
          output: { success: boolean; message: string };
        };
      }>;
      
      const Example = () => {
        const { messages, sendMessage, status, addToolApprovalResponse } = useChat({
          transport: new DefaultChatTransport({
            api: "/api/chat",
          }),
        });
      
        const handleDeleteFile = () => {
          sendMessage({ text: "Delete the file at /tmp/example.txt" });
        };
      
        const latestMessage = messages[messages.length - 1];
        const deleteTool = latestMessage?.parts?.find(
          (part) => part.type === "tool-delete_file"
        ) as DeleteFileToolUIPart | undefined;
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full space-y-4">
              <Button onClick={handleDeleteFile} disabled={status !== "ready"}>
                Delete Example File
              </Button>
      
              {deleteTool?.approval && (
                <Confirmation approval={deleteTool.approval} state={deleteTool.state}>
                  <ConfirmationRequest>
                    This tool wants to delete:{" "}
                    <code>{deleteTool.input?.filePath}</code>
                    <br />
                    Do you approve this action?
                  </ConfirmationRequest>
                  <ConfirmationAccepted>
                    <CheckIcon className="size-4" />
                    <span>You approved this tool execution</span>
                  </ConfirmationAccepted>
                  <ConfirmationRejected>
                    <XIcon className="size-4" />
                    <span>You rejected this tool execution</span>
                  </ConfirmationRejected>
                  <ConfirmationActions>
                    <ConfirmationAction
                      variant="outline"
                      onClick={() =>
                        addToolApprovalResponse({
                          id: deleteTool.approval!.id,
                          approved: false,
                        })
                      }
                    >
                      Reject
                    </ConfirmationAction>
                    <ConfirmationAction
                      variant="default"
                      onClick={() =>
                        addToolApprovalResponse({
                          id: deleteTool.approval!.id,
                          approved: true,
                        })
                      }
                    >
                      Approve
                    </ConfirmationAction>
                  </ConfirmationActions>
                </Confirmation>
              )}
      
              {deleteTool?.output && (
                <MessageResponse>
                  {deleteTool.output.success
                    ? deleteTool.output.message
                    : `Error: ${deleteTool.output.message}`}
                </MessageResponse>
              )}
            </div>
          </div>
        );
      };
      
      export default Example;
      ```
      
      Add the following route to your backend:
      
      ```ts title="app/api/chat/route.tsx"
      import { streamText, UIMessage, convertToModelMessages } from "ai";
      import { z } from "zod";
      
      // Allow streaming responses up to 30 seconds
      export const maxDuration = 30;
      
      export async function POST(req: Request) {
        const { messages }: { messages: UIMessage[] } = await req.json();
      
        const result = streamText({
          model: "openai/gpt-4o",
          messages: await convertToModelMessages(messages),
          tools: {
            delete_file: {
              description: "Delete a file from the file system",
              parameters: z.object({
                filePath: z.string().describe("The path to the file to delete"),
                confirm: z
                  .boolean()
                  .default(false)
                  .describe("Confirmation that the user wants to delete the file"),
              }),
              requireApproval: true, // Enable approval workflow
              execute: async ({ filePath, confirm }) => {
                if (!confirm) {
                  return {
                    success: false,
                    message: "Deletion not confirmed",
                  };
                }
      
                // Simulate file deletion
                await new Promise((resolve) => setTimeout(resolve, 500));
      
                return {
                  success: true,
                  message: `Successfully deleted ${filePath}`,
                };
              },
            },
          },
        });
      
        return result.toUIMessageStreamResponse();
      }
      ```
      
      ## Features
      
      - Context-based state management for approval workflow
      - Conditional rendering based on approval state
      - Support for approval-requested, approval-responded, output-denied, and output-available states
      - Built on shadcn/ui Alert and Button components
      - TypeScript support with comprehensive type definitions
      - Customizable styling with Tailwind CSS
      - Keyboard navigation and accessibility support
      - Theme-aware with automatic dark mode support
      
      ## Examples
      
      ### Approval Request State
      
      Shows the approval request with action buttons when state is `approval-requested`.
      
      See `scripts/confirmation-request.tsx` for this example.
      
      ### Approved State
      
      Shows the accepted status when user approves and state is `approval-responded` or `output-available`.
      
      See `scripts/confirmation-accepted.tsx` for this example.
      
      ### Rejected State
      
      Shows the rejected status when user rejects and state is `output-denied`.
      
      See `scripts/confirmation-rejected.tsx` for this example.
      
      ## Props
      
      ### `<Confirmation />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `approval` | `ToolUIPart[` | - | The approval object containing the approval ID and status. If not provided or undefined, the component will not render. |
      | `state` | `ToolUIPart[` | - | The current state of the tool (input-streaming, input-available, approval-requested, approval-responded, output-denied, or output-available). Will not render for input-streaming or input-available states. |
      | `className` | `string` | - | Additional CSS classes to apply to the Alert component. |
      | `...props` | `React.ComponentProps<typeof Alert>` | - | Any other props are spread to the Alert component. |
      
      ### `<ConfirmationTitle />`
      
      A styled description element for displaying a title or label within the confirmation alert.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof AlertDescription>` | - | Any other props are spread to the underlying AlertDescription component. |
      
      ### `<ConfirmationRequest />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | The content to display when approval is requested. Only renders when state is  |
      
      ### `<ConfirmationAccepted />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | The content to display when approval is accepted. Only renders when approval.approved is true and state is  |
      
      ### `<ConfirmationRejected />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | The content to display when approval is rejected. Only renders when approval.approved is false and state is  |
      
      ### `<ConfirmationActions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply to the actions container. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the div element. Only renders when state is  |
      
      ### `<ConfirmationAction />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the Button component. Styled with h-8 px-3 text-sm classes by default. |
      
    • connection.md 1.1 KB
      # Connection
      
      A custom connection line component for React Flow-based canvases with animated bezier curve styling.
      
      The `Connection` component provides a styled connection line for React Flow canvases. It renders an animated bezier curve with a circle indicator at the target end, using consistent theming through CSS variables.
      
      
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add connection
      ```
      
      ## Features
      
      - Smooth bezier curve animation for connection lines
      - Visual indicator circle at the target position
      - Theme-aware styling using CSS variables
      - Cubic bezier curve calculation for natural flow
      - Lightweight implementation with minimal props
      - Full TypeScript support with React Flow types
      - Compatible with React Flow's connection system
      
      ## Props
      
      ### `<Connection />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `fromX` | `number` | - | The x-coordinate of the connection start point. |
      | `fromY` | `number` | - | The y-coordinate of the connection start point. |
      | `toX` | `number` | - | The x-coordinate of the connection end point. |
      | `toY` | `number` | - | The y-coordinate of the connection end point. |
      
    • context.md 5.6 KB
      # Context
      
      A compound component system for displaying AI model context window usage, token consumption, and cost estimation.
      
      The `Context` component provides a comprehensive view of AI model usage through a compound component system. It displays context window utilization, token consumption breakdown (input, output, reasoning, cache), and cost estimation in an interactive hover card interface.
      
      See `scripts/context.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add context
      ```
      
      ## Features
      
      - **Compound Component Architecture**: Flexible composition of context display elements
      - **Visual Progress Indicator**: Circular SVG progress ring showing context usage percentage
      - **Token Breakdown**: Detailed view of input, output, reasoning, and cached tokens
      - **Cost Estimation**: Real-time cost calculation using the `tokenlens` library
      - **Intelligent Formatting**: Automatic token count formatting (K, M, B suffixes)
      - **Interactive Hover Card**: Detailed information revealed on hover
      - **Context Provider Pattern**: Clean data flow through React Context API
      - **TypeScript Support**: Full type definitions for all components
      - **Accessible Design**: Proper ARIA labels and semantic HTML
      - **Theme Integration**: Uses currentColor for automatic theme adaptation
      
      ## Props
      
      ### `<Context />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `maxTokens` | `number` | - | The total context window size in tokens. |
      | `usedTokens` | `number` | - | The number of tokens currently used. |
      | `usage` | `LanguageModelUsage` | - | Detailed token usage breakdown from the AI SDK (input, output, reasoning, cached tokens). |
      | `modelId` | `ModelId` | - | Model identifier for cost calculation (e.g.,  |
      | `...props` | `ComponentProps<HoverCard>` | - | Any other props are spread to the HoverCard component. |
      
      ### `<ContextTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom trigger element. If not provided, renders a default button with percentage and icon. |
      | `...props` | `ComponentProps<Button>` | - | Props spread to the default button element. |
      
      ### `<ContextContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes for the hover card content. |
      | `...props` | `ComponentProps<HoverCardContent>` | - | Props spread to the HoverCardContent component. |
      
      ### `<ContextContentHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom header content. If not provided, renders percentage and token count with progress bar. |
      | `...props` | `ComponentProps<div>` | - | Props spread to the header div element. |
      
      ### `<ContextContentBody />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Body content, typically containing usage breakdown components. |
      | `...props` | `ComponentProps<div>` | - | Props spread to the body div element. |
      
      ### `<ContextContentFooter />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom footer content. If not provided, renders total cost when modelId is provided. |
      | `...props` | `ComponentProps<div>` | - | Props spread to the footer div element. |
      
      ### Usage Components
      
      All usage components (`ContextInputUsage`, `ContextOutputUsage`, `ContextReasoningUsage`, `ContextCacheUsage`) share the same props:
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom content. If not provided, renders token count and cost for the respective usage type. |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `ComponentProps<div>` | - | Props spread to the div element. |
      
      ## Component Architecture
      
      The Context component uses a compound component pattern with React Context for data sharing:
      
      1. **`<Context>`** - Root provider component that holds all context data
      2. **`<ContextTrigger>`** - Interactive trigger element (default: button with percentage)
      3. **`<ContextContent>`** - Hover card content container
      4. **`<ContextContentHeader>`** - Header section with progress visualization
      5. **`<ContextContentBody>`** - Body section for usage breakdowns
      6. **`<ContextContentFooter>`** - Footer section for total cost
      7. **Usage Components** - Individual token usage displays (Input, Output, Reasoning, Cache)
      
      ## Token Formatting
      
      The component uses `Intl.NumberFormat` with compact notation for automatic formatting:
      
      - Under 1,000: Shows exact count (e.g., "842")
      - 1,000+: Shows with K suffix (e.g., "32K")
      - 1,000,000+: Shows with M suffix (e.g., "1.5M")
      - 1,000,000,000+: Shows with B suffix (e.g., "2.1B")
      
      ## Cost Calculation
      
      When a `modelId` is provided, the component automatically calculates costs using the `tokenlens` library:
      
      - **Input tokens**: Cost based on model's input pricing
      - **Output tokens**: Cost based on model's output pricing
      - **Reasoning tokens**: Special pricing for reasoning-capable models
      - **Cached tokens**: Reduced pricing for cached input tokens
      - **Total cost**: Sum of all token type costs
      
      Costs are formatted using `Intl.NumberFormat` with USD currency.
      
      ## Styling
      
      The component uses Tailwind CSS classes and follows your design system:
      
      - Progress indicator uses `currentColor` for theme adaptation
      - Hover card has customizable width and padding
      - Footer has a secondary background for visual separation
      - All text sizes use the `text-xs` class for consistency
      - Muted foreground colors for secondary information
      
    • controls.md 971 B
      # Controls
      
      A styled controls component for React Flow-based canvases with zoom and fit view functionality.
      
      The `Controls` component provides interactive zoom and fit view controls for React Flow canvases. It includes a modern, themed design with backdrop blur and card styling.
      
      
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add controls
      ```
      
      ## Features
      
      - Zoom in/out controls
      - Fit view button to center and scale content
      - Rounded pill design with backdrop blur
      - Theme-aware card background
      - Subtle drop shadow for depth
      - Full TypeScript support
      - Compatible with all React Flow control features
      
      ## Props
      
      ### `<Controls />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply to the controls. |
      | `...props` | `ComponentProps<typeof Controls>` | - | Any other props from @xyflow/react Controls component (showZoom, showFitView, showInteractive, position, etc.). |
      
    • conversation.md 7.4 KB
      # Conversation
      
      Wraps messages and automatically scrolls to the bottom. Also includes a scroll button that appears when not at the bottom.
      
      The `Conversation` component wraps messages and automatically scrolls to the bottom. Also includes a scroll button that appears when not at the bottom.
      
      <Preview path="conversation" className="p-0" />
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add conversation
      ```
      
      ## Usage with AI SDK
      
      Build a simple conversational UI with `Conversation` and [`PromptInput`](/components/prompt-input):
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import {
        Conversation,
        ConversationContent,
        ConversationDownload,
        ConversationEmptyState,
        ConversationScrollButton,
      } from "@/components/ai-elements/conversation";
      import {
        Message,
        MessageContent,
        MessageResponse,
      } from "@/components/ai-elements/message";
      import {
        PromptInput,
        type PromptInputMessage,
        PromptInputTextarea,
        PromptInputSubmit,
      } from "@/components/ai-elements/prompt-input";
      import { MessageSquare } from "lucide-react";
      import { useState } from "react";
      import { useChat } from "@ai-sdk/react";
      
      const ConversationDemo = () => {
        const [input, setInput] = useState("");
        const { messages, sendMessage, status } = useChat();
      
        const handleSubmit = (message: PromptInputMessage) => {
          if (message.text.trim()) {
            sendMessage({ text: message.text });
            setInput("");
          }
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <Conversation>
                <ConversationContent>
                  {messages.length === 0 ? (
                    <ConversationEmptyState
                      icon={<MessageSquare className="size-12" />}
                      title="Start a conversation"
                      description="Type a message below to begin chatting"
                    />
                  ) : (
                    messages.map((message) => (
                      <Message from={message.role} key={message.id}>
                        <MessageContent>
                          {message.parts.map((part, i) => {
                            switch (part.type) {
                              case "text": // we don't use any reasoning or tool calls in this example
                                return (
                                  <MessageResponse key={`${message.id}-${i}`}>
                                    {part.text}
                                  </MessageResponse>
                                );
                              default:
                                return null;
                            }
                          })}
                        </MessageContent>
                      </Message>
                    ))
                  )}
                </ConversationContent>
                <ConversationDownload messages={messages} />
                <ConversationScrollButton />
              </Conversation>
      
              <PromptInput
                onSubmit={handleSubmit}
                className="mt-4 w-full max-w-2xl mx-auto relative"
              >
                <PromptInputTextarea
                  value={input}
                  placeholder="Say something..."
                  onChange={(e) => setInput(e.currentTarget.value)}
                  className="pr-12"
                />
                <PromptInputSubmit
                  status={status === "streaming" ? "streaming" : "ready"}
                  disabled={!input.trim()}
                  className="absolute bottom-1 right-1"
                />
              </PromptInput>
            </div>
          </div>
        );
      };
      
      export default ConversationDemo;
      ```
      
      Add the following route to your backend:
      
      ```tsx title="api/chat/route.ts"
      import { streamText, UIMessage, convertToModelMessages } from "ai";
      
      // Allow streaming responses up to 30 seconds
      export const maxDuration = 30;
      
      export async function POST(req: Request) {
        const { messages }: { messages: UIMessage[] } = await req.json();
      
        const result = streamText({
          model: "openai/gpt-4o",
          messages: await convertToModelMessages(messages),
        });
      
        return result.toUIMessageStreamResponse();
      }
      ```
      
      ## Features
      
      - Automatic scrolling to the bottom when new messages are added
      - Smooth scrolling behavior with configurable animation
      - Scroll button that appears when not at the bottom
      - Download conversation as Markdown
      - Responsive design with customizable padding and spacing
      - Flexible content layout with consistent message spacing
      - Accessible with proper ARIA roles for screen readers
      - Customizable styling through className prop
      - Support for any number of child message components
      
      ## Props
      
      ### `<Conversation />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `contextRef` | `React.Ref<StickToBottomContext>` | - | Optional ref to access the StickToBottom context object. |
      | `instance` | `StickToBottomInstance` | - | Optional instance for controlling the StickToBottom component. |
      | `children` | `((context: StickToBottomContext) => ReactNode) | ReactNode` | - | Render prop or ReactNode for custom rendering with context. |
      | `...props` | `Omit<React.HTMLAttributes<HTMLDivElement>, ` | - | Any other props are spread to the root div. |
      
      ### `<ConversationContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `((context: StickToBottomContext) => ReactNode) | ReactNode` | - | Render prop or ReactNode for custom rendering with context. |
      | `...props` | `Omit<React.HTMLAttributes<HTMLDivElement>, ` | - | Any other props are spread to the root div. |
      
      ### `<ConversationEmptyState />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `title` | `string` | - | The title text to display. |
      | `description` | `string` | - | The description text to display. |
      | `icon` | `React.ReactNode` | - | Optional icon to display above the text. |
      | `children` | `React.ReactNode` | - | Optional additional content to render below the text. |
      | `...props` | `ComponentProps<` | - | Any other props are spread to the root div. |
      
      ### `<ConversationScrollButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `<ConversationDownload />`
      
      A button that downloads the conversation as a Markdown file.
      
      ```tsx
      import { ConversationDownload } from "@/components/ai-elements/conversation";
      
      <Conversation>
        <ConversationContent>
          {messages.map(...)}
        </ConversationContent>
        <ConversationDownload messages={messages} />
        <ConversationScrollButton />
      </Conversation>
      ```
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `messages` | `UIMessage[]` | Required | Array of messages to include in the download. |
      | `filename` | `string` | - | The filename for the downloaded file. |
      | `formatMessage` | `(message: UIMessage, index: number) => string` | - | Custom function to format each message in the output. |
      | `...props` | `Omit<ComponentProps<typeof Button>, ` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `messagesToMarkdown`
      
      A utility function to convert messages to Markdown format. Useful for custom download implementations.
      
      ```tsx
      import { messagesToMarkdown } from "@/components/ai-elements/conversation";
      
      const markdown = messagesToMarkdown(messages);
      
      // With custom formatter
      const customMarkdown = messagesToMarkdown(
        messages,
        (msg, i) =>
          `[${msg.role}]: ${msg.parts
            .filter((p) => p.type === "text")
            .map((p) => p.text)
            .join("")}`
      );
      ```
      
    • edge.md 2.1 KB
      # Edge
      
      Customizable edge components for React Flow canvases with animated and temporary states.
      
      The `Edge` component provides two pre-styled edge types for React Flow canvases: `Temporary` for dashed temporary connections and `Animated` for connections with animated indicators.
      
      
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add edge
      ```
      
      ## Features
      
      - Two distinct edge types: Temporary and Animated
      - Temporary edges use dashed lines with ring color
      - Animated edges include a moving circle indicator
      - Automatic handle position calculation
      - Smart offset calculation based on handle type and position
      - Uses Bezier curves for smooth, natural-looking connections
      - Fully compatible with React Flow's edge system
      - Type-safe implementation with TypeScript
      
      ## Edge Types
      
      ### `Edge.Temporary`
      
      A dashed edge style for temporary or preview connections. Uses a simple Bezier path with a dashed stroke pattern.
      
      ### `Edge.Animated`
      
      A solid edge with an animated circle that moves along the path. The animation repeats indefinitely with a 2-second duration, providing visual feedback for active connections.
      
      ## Props
      
      Both edge types accept standard React Flow `EdgeProps`:
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `id` | `string` | - | Unique identifier for the edge. |
      | `source` | `string` | - | ID of the source node. |
      | `target` | `string` | - | ID of the target node. |
      | `sourceX` | `number` | - | X coordinate of the source handle (Temporary only). |
      | `sourceY` | `number` | - | Y coordinate of the source handle (Temporary only). |
      | `targetX` | `number` | - | X coordinate of the target handle (Temporary only). |
      | `targetY` | `number` | - | Y coordinate of the target handle (Temporary only). |
      | `sourcePosition` | `Position` | - | Position of the source handle (Left, Right, Top, Bottom). |
      | `targetPosition` | `Position` | - | Position of the target handle (Left, Right, Top, Bottom). |
      | `markerEnd` | `string` | - | SVG marker ID for the edge end (Animated only). |
      | `style` | `React.CSSProperties` | - | Custom styles for the edge (Animated only). |
      
    • environment-variables.md 3.7 KB
      # Environment Variables
      
      Display environment variables with masking and copy functionality.
      
      The `EnvironmentVariables` component displays environment variables with value masking, visibility toggle, and copy functionality.
      
      See `scripts/environment-variables.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add environment-variables
      ```
      
      ## Features
      
      - Value masking by default
      - Toggle visibility switch
      - Copy individual values
      - Export format support (`export KEY="value"`)
      - Required badge indicator
      
      ## Props
      
      ### `<EnvironmentVariables />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `showValues` | `boolean` | - | Controlled visibility state. |
      | `defaultShowValues` | `boolean` | `false` | Default visibility state. |
      | `onShowValuesChange` | `(show: boolean) => void` | - | Callback when visibility changes. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<EnvironmentVariablesHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the header div. |
      
      ### `<EnvironmentVariablesTitle />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom title text. |
      | `...props` | `React.HTMLAttributes<HTMLHeadingElement>` | - | Spread to the h3 element. |
      
      ### `<EnvironmentVariablesToggle />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Switch>` | - | Spread to the Switch component. |
      
      ### `<EnvironmentVariablesContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the content div. |
      
      ### `<EnvironmentVariable />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `name` | `string` | Required | Variable name. |
      | `value` | `string` | Required | Variable value. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the row div. |
      
      ### `<EnvironmentVariableGroup />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the group div. |
      
      ### `<EnvironmentVariableName />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom name content. Defaults to the name from context. |
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Spread to the span element. |
      
      ### `<EnvironmentVariableValue />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom value content. Defaults to the masked/unmasked value from context. |
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Spread to the span element. |
      
      ### `<EnvironmentVariableCopyButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `copyFormat` | `unknown` | - | Format to copy. |
      | `onCopy` | `() => void` | - | Callback after successful copy. |
      | `onError` | `(error: Error) => void` | - | Callback if copying fails. |
      | `timeout` | `number` | `2000` | Duration to show copied state (ms). |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Spread to the Button component. |
      
      ### `<EnvironmentVariableRequired />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom badge text. |
      | `...props` | `React.ComponentProps<typeof Badge>` | - | Spread to the Badge component. |
      
    • file-tree.md 2 KB
      # File Tree
      
      Display hierarchical file and folder structure with expand/collapse functionality.
      
      The `FileTree` component displays a hierarchical file system structure with expandable folders and file selection.
      
      See `scripts/file-tree.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add file-tree
      ```
      
      ## Features
      
      - Hierarchical folder structure
      - Expand/collapse folders
      - File selection with callback
      - Keyboard accessible
      - Customizable icons
      - Controlled and uncontrolled modes
      
      ## Examples
      
      ### Basic Usage
      
      See `scripts/file-tree-basic.tsx` for this example.
      
      ### With Selection
      
      See `scripts/file-tree-selection.tsx` for this example.
      
      ### Default Expanded
      
      See `scripts/file-tree-expanded.tsx` for this example.
      
      ## Props
      
      ### `<FileTree />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `expanded` | `Set<string>` | - | Controlled expanded paths. |
      | `defaultExpanded` | `Set<string>` | `new Set()` | Default expanded paths. |
      | `selectedPath` | `string` | - | Currently selected file/folder path. |
      | `onSelect` | `(path: string) => void` | - | Callback when a file/folder is selected. |
      | `onExpandedChange` | `(expanded: Set<string>) => void` | - | Callback when expanded paths change. |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<FileTreeFolder />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `path` | `string` | - | Unique folder path. |
      | `name` | `string` | - | Display name. |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<FileTreeFile />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `path` | `string` | - | Unique file path. |
      | `name` | `string` | - | Display name. |
      | `icon` | `ReactNode` | - | Custom file icon. |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### Subcomponents
      
      - `FileTreeIcon` - Icon wrapper
      - `FileTreeName` - Name text
      - `FileTreeActions` - Action buttons container (stops click propagation)
      
    • image.md 4 KB
      # Image
      
      Displays AI-generated images from the AI SDK.
      
      The `Image` component displays AI-generated images from the AI SDK. It accepts a [`Experimental_GeneratedImage`](/docs/reference/ai-sdk-core/generate-image) object from the AI SDK's `generateImage` function and automatically renders it as an image.
      
      See `scripts/image.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add image
      ```
      
      ## Usage with AI SDK
      
      Build a simple app allowing a user to generate an image given a prompt.
      
      Install the `@ai-sdk/openai` package:
      
      ```package-install
      npm i @ai-sdk/openai
      ```
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { Image } from "@/components/ai-elements/image";
      import {
        PromptInput,
        type PromptInputMessage,
        PromptInputTextarea,
        PromptInputSubmit,
      } from "@/components/ai-elements/prompt-input";
      import { useState } from "react";
      import { Spinner } from "@/components/ui/spinner";
      
      const ImageDemo = () => {
        const [prompt, setPrompt] = useState("A futuristic cityscape at sunset");
        const [imageData, setImageData] = useState<any>(null);
        const [isLoading, setIsLoading] = useState(false);
      
        const handleSubmit = async (message: PromptInputMessage) => {
          if (!message.text.trim()) return;
          setPrompt("");
      
          setIsLoading(true);
          try {
            const response = await fetch("/api/image", {
              method: "POST",
              body: JSON.stringify({ prompt: message.text.trim() }),
            });
      
            const data = await response.json();
      
            setImageData(data);
          } catch (error) {
            console.error("Error generating image:", error);
          } finally {
            setIsLoading(false);
          }
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <div className="flex-1 overflow-y-auto p-4">
                {imageData && (
                  <div className="flex justify-center">
                    <Image
                      {...imageData}
                      alt="Generated image"
                      className="h-[300px] aspect-square border rounded-lg"
                    />
                  </div>
                )}
                {isLoading && <Spinner />}
              </div>
      
              <PromptInput
                onSubmit={handleSubmit}
                className="mt-4 w-full max-w-2xl mx-auto relative"
              >
                <PromptInputTextarea
                  value={prompt}
                  placeholder="Describe the image you want to generate..."
                  onChange={(e) => setPrompt(e.currentTarget.value)}
                  className="pr-12"
                />
                <PromptInputSubmit
                  status={isLoading ? "submitted" : "ready"}
                  disabled={!prompt.trim()}
                  className="absolute bottom-1 right-1"
                />
              </PromptInput>
            </div>
          </div>
        );
      };
      
      export default ImageDemo;
      ```
      
      Add the following route to your backend:
      
      ```ts title="app/api/image/route.ts"
      import { openai } from "@ai-sdk/openai";
      import { experimental_generateImage } from "ai";
      
      export async function POST(req: Request) {
        const { prompt }: { prompt: string } = await req.json();
      
        const { image } = await experimental_generateImage({
          model: openai.image("dall-e-3"),
          prompt: prompt,
          size: "1024x1024",
        });
      
        return Response.json({
          base64: image.base64,
          uint8Array: image.uint8Array,
          mediaType: image.mediaType,
        });
      }
      ```
      
      ## Features
      
      - Accepts `Experimental_GeneratedImage` objects directly from the AI SDK
      - Automatically creates proper data URLs from base64-encoded image data
      - Supports all standard HTML image attributes
      - Responsive by default with `max-w-full h-auto` styling
      - Customizable with additional CSS classes
      - Includes proper TypeScript types for AI SDK compatibility
      
      ## Props
      
      ### `<Image />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `alt` | `string` | - | Alternative text for the image. |
      | `className` | `string` | - | Additional CSS classes to apply to the image. |
      | `...props` | `Experimental_GeneratedImage` | - | The image data to display, as returned by the AI SDK. |
      
    • inline-citation.md 10.8 KB
      # Inline Citation
      
      A hoverable citation component that displays source information and quotes inline with text, perfect for AI-generated content with references.
      
      The `InlineCitation` component provides a way to display citations inline with text content, similar to academic papers or research documents. It consists of a citation pill that shows detailed source information on hover, making it perfect for AI-generated content that needs to reference sources.
      
      See `scripts/inline-citation.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add inline-citation
      ```
      
      ## Usage with AI SDK
      
      Build citations for AI-generated content using [`experimental_generateObject`](/docs/reference/ai-sdk-ui/use-object).
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { experimental_useObject as useObject } from "@ai-sdk/react";
      import {
        InlineCitation,
        InlineCitationText,
        InlineCitationCard,
        InlineCitationCardTrigger,
        InlineCitationCardBody,
        InlineCitationCarousel,
        InlineCitationCarouselContent,
        InlineCitationCarouselItem,
        InlineCitationCarouselHeader,
        InlineCitationCarouselIndex,
        InlineCitationCarouselPrev,
        InlineCitationCarouselNext,
        InlineCitationSource,
        InlineCitationQuote,
      } from "@/components/ai-elements/inline-citation";
      import { Button } from "@/components/ui/button";
      import { citationSchema } from "@/app/api/citation/route";
      
      const CitationDemo = () => {
        const { object, submit, isLoading } = useObject({
          api: "/api/citation",
          schema: citationSchema,
        });
      
        const handleSubmit = (topic: string) => {
          submit({ prompt: topic });
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 space-y-6">
            <div className="flex gap-2 mb-6">
              <Button
                onClick={() => handleSubmit("artificial intelligence")}
                disabled={isLoading}
                variant="outline"
              >
                Generate AI Content
              </Button>
              <Button
                onClick={() => handleSubmit("climate change")}
                disabled={isLoading}
                variant="outline"
              >
                Generate Climate Content
              </Button>
            </div>
      
            {isLoading && !object && (
              <div className="text-muted-foreground">
                Generating content with citations...
              </div>
            )}
      
            {object?.content && (
              <div className="prose prose-sm max-w-none">
                <p className="leading-relaxed">
                  {object.content.split(/(\[\d+\])/).map((part, index) => {
                    const citationMatch = part.match(/\[(\d+)\]/);
                    if (citationMatch) {
                      const citationNumber = citationMatch[1];
                      const citation = object.citations?.find(
                        (c: any) => c.number === citationNumber
                      );
      
                      if (citation) {
                        return (
                          <InlineCitation key={index}>
                            <InlineCitationCard>
                              <InlineCitationCardTrigger sources={[citation.url]} />
                              <InlineCitationCardBody>
                                <InlineCitationCarousel>
                                  <InlineCitationCarouselHeader>
                                    <InlineCitationCarouselPrev />
                                    <InlineCitationCarouselNext />
                                    <InlineCitationCarouselIndex />
                                  </InlineCitationCarouselHeader>
                                  <InlineCitationCarouselContent>
                                    <InlineCitationCarouselItem>
                                      <InlineCitationSource
                                        title={citation.title}
                                        url={citation.url}
                                        description={citation.description}
                                      />
                                      {citation.quote && (
                                        <InlineCitationQuote>
                                          {citation.quote}
                                        </InlineCitationQuote>
                                      )}
                                    </InlineCitationCarouselItem>
                                  </InlineCitationCarouselContent>
                                </InlineCitationCarousel>
                              </InlineCitationCardBody>
                            </InlineCitationCard>
                          </InlineCitation>
                        );
                      }
                    }
                    return part;
                  })}
                </p>
              </div>
            )}
          </div>
        );
      };
      
      export default CitationDemo;
      ```
      
      Add the following route to your backend:
      
      ```ts title="app/api/citation/route.ts"
      import { streamObject } from "ai";
      import { z } from "zod";
      
      export const citationSchema = z.object({
        content: z.string(),
        citations: z.array(
          z.object({
            number: z.string(),
            title: z.string(),
            url: z.string(),
            description: z.string().optional(),
            quote: z.string().optional(),
          })
        ),
      });
      
      // Allow streaming responses up to 30 seconds
      export const maxDuration = 30;
      
      export async function POST(req: Request) {
        const { prompt } = await req.json();
      
        const result = streamObject({
          model: "openai/gpt-4o",
          schema: citationSchema,
          prompt: `Generate a well-researched paragraph about ${prompt} with proper citations. 
          
          Include:
          - A comprehensive paragraph with inline citations marked as [1], [2], etc.
          - 2-3 citations with realistic source information
          - Each citation should have a title, URL, and optional description/quote
          - Make the content informative and the sources credible
          
          Format citations as numbered references within the text.`,
        });
      
        return result.toTextStreamResponse();
      }
      ```
      
      ## Features
      
      - Hover interaction to reveal detailed citation information
      - **Carousel navigation** for multiple citations with prev/next controls
      - **Live index tracking** showing current slide position (e.g., "1/5")
      - Support for source titles, URLs, and descriptions
      - Optional quote blocks for relevant excerpts
      - Composable architecture for flexible citation formats
      - Accessible design with proper keyboard navigation
      - Seamless integration with AI-generated content
      - Clean visual design that doesn't disrupt reading flow
      - Smart badge display showing source hostname and count
      
      ## Usage with AI SDK
      
      Currently, there is no official support for inline citations with Streamdown or the Response component. This is because:
      
      - There isn't any good markdown syntax for inline citations
      - Language models don't naturally respond with inline citation syntax
      - The AI SDK doesn't have built-in support for inline citations
      
      ### Potential Approaches
      
      While these methods are hypothetical and not officially supported, there are two conceptual ways inline citations could work with Streamdown:
      
      1. **Footnote conversion**: GitHub Flavored Markdown (GFM) handles footnotes using `[^1]` syntax. You could hypothetically remove the default footnote rendering and convert footnotes to inline citations instead.
      
      2. **Custom HTML syntax**: You could add a system prompt instructing the model to use a special HTML syntax like `<citation />` and pass that as a custom component to Streamdown.
      
      These approaches require custom implementation and are not currently supported out of the box. We will investigate official support for this use case in the future.
      
      For now, the recommended approach is to use `experimental_useObject` (as shown in the usage example above) to generate structured citation data, then manually parse and render inline citations.
      
      ## Props
      
      ### `<InlineCitation />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the root span element. |
      
      ### `<InlineCitationText />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying span element. |
      
      ### `<InlineCitationCard />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the HoverCard component. |
      
      ### `<InlineCitationCardTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `sources` | `string[]` | - | Array of source URLs. The length determines the number displayed in the badge. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying button element. |
      
      ### `<InlineCitationCardBody />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div. |
      
      ### `<InlineCitationCarousel />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Carousel>` | - | Any other props are spread to the underlying Carousel component. |
      
      ### `<InlineCitationCarouselContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying CarouselContent component. |
      
      ### `<InlineCitationCarouselItem />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div. |
      
      ### `<InlineCitationCarouselHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div. |
      
      ### `<InlineCitationCarouselIndex />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div. Children will override the default index display. |
      
      ### `<InlineCitationCarouselPrev />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CarouselPrevious>` | - | Any other props are spread to the underlying CarouselPrevious component. |
      
      ### `<InlineCitationCarouselNext />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CarouselNext>` | - | Any other props are spread to the underlying CarouselNext component. |
      
      ### `<InlineCitationSource />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `title` | `string` | - | The title of the source. |
      | `url` | `string` | - | The URL of the source. |
      | `description` | `string` | - | A brief description of the source. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div. |
      
      ### `<InlineCitationQuote />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying blockquote element. |
      
    • jsx-preview.md 3.2 KB
      # JSX Preview
      
      A component that dynamically renders JSX strings with streaming support for AI-generated UI.
      
      The `JSXPreview` component renders JSX strings dynamically, supporting streaming scenarios where JSX may be incomplete. It automatically closes unclosed tags during streaming, making it ideal for displaying AI-generated UI components in real-time.
      
      See `scripts/jsx-preview.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add jsx-preview
      ```
      
      ## Features
      
      - Renders JSX strings dynamically using `react-jsx-parser`
      - Streaming support with automatic tag completion
      - Custom component injection for rendering your own components
      - Error handling with customizable error display
      - Context-based architecture for flexible composition
      
      ## Usage with AI SDK
      
      The JSXPreview component integrates with the AI SDK to render generated UI in real-time:
      
      ```tsx title="components/generated-ui.tsx"
      "use client";
      
      import {
        JSXPreview,
        JSXPreviewContent,
        JSXPreviewError,
      } from "@/components/ai-elements/jsx-preview";
      
      type GeneratedUIProps = {
        jsx: string;
        isStreaming: boolean;
      };
      
      export const GeneratedUI = ({ jsx, isStreaming }: GeneratedUIProps) => (
        <JSXPreview
          jsx={jsx}
          isStreaming={isStreaming}
          onError={(error) => console.error("JSX Parse Error:", error)}
        >
          <JSXPreviewContent />
          <JSXPreviewError />
        </JSXPreview>
      );
      ```
      
      ### With Custom Components
      
      You can inject custom components to be used within the rendered JSX:
      
      ```tsx title="components/generated-ui-with-components.tsx"
      "use client";
      
      import {
        JSXPreview,
        JSXPreviewContent,
      } from "@/components/ai-elements/jsx-preview";
      import { Button } from "@/components/ui/button";
      import { Card } from "@/components/ui/card";
      
      const customComponents = {
        Button,
        Card,
      };
      
      export const GeneratedUIWithComponents = ({ jsx }: { jsx: string }) => (
        <JSXPreview jsx={jsx} components={customComponents}>
          <JSXPreviewContent />
        </JSXPreview>
      );
      ```
      
      ## Props
      
      ### `<JSXPreview />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `jsx` | `string` | Required | The JSX string to render. |
      | `isStreaming` | `boolean` | `false` | When true, automatically completes unclosed tags. |
      | `components` | `Record<string, React.ComponentType>` | - | Custom components available within the rendered JSX. |
      | `bindings` | `Record<string, unknown>` | - | Variables and functions available within the JSX scope. |
      | `onError` | `(error: Error) => void` | - | Callback fired when a parsing or rendering error occurs. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div element. |
      
      ### `<JSXPreviewContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `renderError` | `JsxParserProps[` | - | Custom error renderer passed to react-jsx-parser. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div element. |
      
      ### `<JSXPreviewError />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `ReactNode | ((error: Error) => ReactNode)` | - | Custom error content or render function receiving the error. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div element. |
      
    • message.md 9.4 KB
      # Message
      
      A comprehensive suite of components for displaying chat messages, including message rendering, branching, actions, and markdown responses.
      
      The `Message` component suite provides a complete set of tools for building chat interfaces. It includes components for displaying messages from users and AI assistants, managing multiple response branches, adding action buttons, and rendering markdown content.
      
      See `scripts/message.tsx` for this example.
      
      
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add message
      ```
      
      ## Features
      
      - Displays messages from both user and AI assistant with distinct styling and automatic alignment
      - Minimalist flat design with user messages in secondary background and assistant messages full-width
      - **Response branching** with navigation controls to switch between multiple AI response versions
      - **Markdown rendering** with GFM support (tables, task lists, strikethrough), math equations, and smart streaming
      - **Action buttons** for common operations (retry, like, dislike, copy, share) with tooltips and state management
      - **File attachments** display with support for images and generic files with preview and remove functionality
      - Code blocks with syntax highlighting and copy-to-clipboard functionality
      - Keyboard accessible with proper ARIA labels
      - Responsive design that adapts to different screen sizes
      - Seamless light/dark theme integration
      
      
      
      ## Usage with AI SDK
      
      Build a simple chat UI where the user can copy or regenerate the most recent message.
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { useState } from "react";
      import {
        MessageActions,
        MessageAction,
      } from "@/components/ai-elements/message";
      import { Message, MessageContent } from "@/components/ai-elements/message";
      import {
        Conversation,
        ConversationContent,
        ConversationScrollButton,
      } from "@/components/ai-elements/conversation";
      import {
        PromptInput,
        type PromptInputMessage,
        PromptInputTextarea,
        PromptInputSubmit,
      } from "@/components/ai-elements/prompt-input";
      import { MessageResponse } from "@/components/ai-elements/message";
      import { RefreshCcwIcon, CopyIcon } from "lucide-react";
      import { useChat } from "@ai-sdk/react";
      import { Fragment } from "react";
      
      const ActionsDemo = () => {
        const [input, setInput] = useState("");
        const { messages, sendMessage, status, regenerate } = useChat();
      
        const handleSubmit = (message: PromptInputMessage) => {
          if (message.text.trim()) {
            sendMessage({ text: message.text });
            setInput("");
          }
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <Conversation>
                <ConversationContent>
                  {messages.map((message, messageIndex) => (
                    <Fragment key={message.id}>
                      {message.parts.map((part, i) => {
                        switch (part.type) {
                          case "text":
                            const isLastMessage =
                              messageIndex === messages.length - 1;
      
                            return (
                              <Fragment key={`${message.id}-${i}`}>
                                <Message from={message.role}>
                                  <MessageContent>
                                    <MessageResponse>{part.text}</MessageResponse>
                                  </MessageContent>
                                </Message>
                                {message.role === "assistant" && isLastMessage && (
                                  <MessageActions>
                                    <MessageAction
                                      onClick={() => regenerate()}
                                      label="Retry"
                                    >
                                      <RefreshCcwIcon className="size-3" />
                                    </MessageAction>
                                    <MessageAction
                                      onClick={() =>
                                        navigator.clipboard.writeText(part.text)
                                      }
                                      label="Copy"
                                    >
                                      <CopyIcon className="size-3" />
                                    </MessageAction>
                                  </MessageActions>
                                )}
                              </Fragment>
                            );
                          default:
                            return null;
                        }
                      })}
                    </Fragment>
                  ))}
                </ConversationContent>
                <ConversationScrollButton />
              </Conversation>
      
              <PromptInput
                onSubmit={handleSubmit}
                className="mt-4 w-full max-w-2xl mx-auto relative"
              >
                <PromptInputTextarea
                  value={input}
                  placeholder="Say something..."
                  onChange={(e) => setInput(e.currentTarget.value)}
                  className="pr-12"
                />
                <PromptInputSubmit
                  status={status === "streaming" ? "streaming" : "ready"}
                  disabled={!input.trim()}
                  className="absolute bottom-1 right-1"
                />
              </PromptInput>
            </div>
          </div>
        );
      };
      
      export default ActionsDemo;
      ```
      
      ## Props
      
      ### `<Message />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `from` | `UIMessage[` | - | The role of the message sender ( |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the root div. |
      
      ### `<MessageContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the content div. |
      
      ### `<MessageResponse />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `string` | - | The markdown content to render. |
      | `parseIncompleteMarkdown` | `boolean` | `true` | Whether to parse and fix incomplete markdown syntax (e.g., unclosed code blocks or lists). |
      | `className` | `string` | - | CSS class names to apply to the wrapper div element. |
      | `components` | `object` | - | Custom React components to use for rendering markdown elements (e.g., custom heading, paragraph, code block components). |
      | `allowedImagePrefixes` | `string[]` | `[` | Array of allowed URL prefixes for images. Use [ |
      | `allowedLinkPrefixes` | `string[]` | `[` | Array of allowed URL prefixes for links. Use [ |
      | `defaultOrigin` | `string` | - | Default origin to use for relative URLs in links and images. |
      | `rehypePlugins` | `array` | `[rehypeKatex]` | Array of rehype plugins to use for processing HTML. Includes KaTeX for math rendering by default. |
      | `remarkPlugins` | `array` | `[remarkGfm, remarkMath]` | Array of remark plugins to use for processing markdown. Includes GitHub Flavored Markdown and math support by default. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the root div. |
      
      ### `<MessageActions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | HTML attributes to spread to the root div. |
      
      ### `<MessageAction />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `tooltip` | `string` | - | Optional tooltip text shown on hover. |
      | `label` | `string` | - | Accessible label for screen readers. Also used as fallback if tooltip is not provided. |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `<MessageBranch />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `defaultBranch` | `number` | `0` | The index of the branch to show by default. |
      | `onBranchChange` | `(branchIndex: number) => void` | - | Callback fired when the branch changes. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the root div. |
      
      ### `<MessageBranchContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the root div. |
      
      ### `<MessageBranchSelector />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof ButtonGroup>` | - | Any other props are spread to the underlying ButtonGroup component. |
      
      ### `<MessageBranchPrevious />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `<MessageBranchNext />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `<MessageBranchPage />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Any other props are spread to the underlying span element. |
      
      ### `<MessageToolbar />`
      
      A container for placing actions and branch selectors below a message. Lays out children in a horizontal row with space-between alignment.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the root div. |
      ```
      
    • mic-selector.md 7.7 KB
      # Mic Selector
      
      A composable dropdown component for selecting audio input devices with permission handling and device change detection.
      
      The `MicSelector` component provides a flexible and composable interface for selecting microphone input devices. Built on shadcn/ui's Command and Popover components, it features automatic device detection, permission handling, dynamic device list updates, and intelligent device name parsing.
      
      See `scripts/mic-selector.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add mic-selector
      ```
      
      ## Features
      
      - Fully composable architecture with granular control components
      - Automatic audio input device enumeration
      - Permission-based device name display
      - Real-time device change detection via devicechange events
      - Intelligent device label parsing with ID extraction
      - Controlled and uncontrolled component patterns
      - Responsive width matching between trigger and content
      - Built on shadcn/ui Command and Popover components
      - Full TypeScript support with proper types for all components
      
      ## Props
      
      ### `<MicSelector />`
      
      Root Popover component that provides context for all child components.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `defaultValue` | `string` | - | The default selected device ID (uncontrolled). |
      | `value` | `string` | - | The selected device ID (controlled). |
      | `onValueChange` | `(deviceId: string) => void` | - | Callback fired when the selected device changes. |
      | `defaultOpen` | `boolean` | `false` | The default open state (uncontrolled). |
      | `open` | `boolean` | - | The open state (controlled). |
      | `onOpenChange` | `(open: boolean) => void` | - | Callback fired when the open state changes. Automatically requests microphone permission when opened without permission. |
      | `...props` | `React.ComponentProps<typeof Popover>` | - | Any other props are spread to the Popover component. |
      
      ### `<MicSelectorTrigger />`
      
      Button that opens the microphone selector popover. Automatically tracks its width to match the popover content.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the Button component. |
      
      ### `<MicSelectorValue />`
      
      Displays the currently selected microphone name or a placeholder.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<MicSelectorContent />`
      
      Container for the Command component, rendered inside the popover.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `popoverOptions` | `React.ComponentProps<typeof PopoverContent>` | - | Props to pass to the underlying PopoverContent component. |
      | `...props` | `React.ComponentProps<typeof Command>` | - | Any other props are spread to the Command component. |
      
      ### `<MicSelectorInput />`
      
      Search input for filtering microphones.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandInput>` | - | Any other props are spread to the CommandInput component. |
      
      ### `<MicSelectorList />`
      
      Wrapper for the list of microphone items. Uses render props pattern to provide access to device data.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `(devices: MediaDeviceInfo[]) => ReactNode` | - | Render function that receives the array of available devices. |
      | `...props` | `Omit<React.ComponentProps<typeof CommandList>, ` | - | Any other props are spread to the CommandList component. |
      
      ### `<MicSelectorEmpty />`
      
      Message shown when no microphones match the search.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `ReactNode` | - | The message to display. |
      | `...props` | `React.ComponentProps<typeof CommandEmpty>` | - | Any other props are spread to the CommandEmpty component. |
      
      ### `<MicSelectorItem />`
      
      Selectable item representing a microphone.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `value` | `string` | - | The device ID for this item. |
      | `...props` | `React.ComponentProps<typeof CommandItem>` | - | Any other props are spread to the CommandItem component. |
      
      ### `<MicSelectorLabel />`
      
      Displays a formatted microphone label with intelligent device ID parsing. Automatically extracts and styles device IDs in the format (XXXX:XXXX).
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `device` | `MediaDeviceInfo` | - | The MediaDeviceInfo object for the device. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ## Hooks
      
      ### `useAudioDevices()`
      
      A custom hook for managing audio input devices. This hook is used internally by the `MicSelector` component but can also be used independently.
      
      ```tsx
      import { useAudioDevices } from "@repo/elements/mic-selector";
      
      export default function Example() {
        const { devices, loading, error, hasPermission, loadDevices } =
          useAudioDevices();
      
        return (
          <div>
            {loading && <p>Loading devices...</p>}
            {error && <p>Error: {error}</p>}
            {devices.map((device) => (
              <div key={device.deviceId}>{device.label}</div>
            ))}
            {!hasPermission && (
              <button onClick={loadDevices}>Grant Permission</button>
            )}
          </div>
        );
      }
      ```
      
      #### Return Value
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `devices` | `MediaDeviceInfo[]` | - | Array of available audio input devices. |
      | `loading` | `boolean` | - | Whether devices are currently being loaded. |
      | `error` | `string | null` | - | Error message if device loading failed. |
      | `hasPermission` | `boolean` | - | Whether microphone permission has been granted. |
      | `loadDevices` | `() => Promise<void>` | - | Function to request microphone permission and load device names. |
      
      ## Behavior
      
      ### Permission Handling
      
      The component implements a two-stage permission approach:
      
      1. **Without Permission**: Initially loads devices without requesting permission. Device labels may show as generic names (e.g., "Microphone 1").
      2. **With Permission**: When the popover is opened and permission hasn't been granted, automatically requests microphone access and displays actual device names.
      
      ### Device Label Parsing
      
      The `MicSelectorLabel` component intelligently parses device names that include hardware IDs in the format `(XXXX:XXXX)`. It splits the label into the device name and ID, styling the ID with muted text for better readability.
      
      For example: `"MacBook Pro Microphone (1a2b:3c4d)"` becomes:
      
      - Device name: `"MacBook Pro Microphone"`
      - Device ID: `"(1a2b:3c4d)"` (styled with muted color)
      
      ### Width Synchronization
      
      The `MicSelectorTrigger` uses a ResizeObserver to track its width and automatically synchronizes it with the `MicSelectorContent` popover width for a cohesive appearance.
      
      ### Device Change Detection
      
      The component listens for `devicechange` events (e.g., plugging/unplugging microphones) and automatically updates the device list in real-time.
      
      ## Accessibility
      
      - Uses semantic HTML with proper ARIA attributes via shadcn/ui components
      - Full keyboard navigation support through Command component
      - Screen reader friendly with proper labels and roles
      - Searchable device list for quick selection
      
      ## Notes
      
      - Requires a secure context (HTTPS or localhost) for microphone access
      - Browser may prompt user for microphone permission on first open
      - Device labels are only fully descriptive after permission is granted
      - Component handles cleanup of temporary media streams during permission requests
      - Uses Radix UI's `useControllableState` for flexible controlled/uncontrolled patterns
      
    • model-selector.md 4.3 KB
      # Model Selector
      
      A searchable command palette for selecting AI models in your chat interface.
      
      The `ModelSelector` component provides a searchable command palette interface for selecting AI models. It's built on top of the cmdk library and provides a keyboard-navigable interface with search functionality.
      
      See `scripts/model-selector.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add model-selector
      ```
      
      ## Features
      
      - Searchable interface with keyboard navigation
      - Fuzzy search filtering across model names
      - Grouped model organization by provider
      - Keyboard shortcuts support
      - Empty state handling
      - Customizable styling with Tailwind CSS
      - Built on cmdk for excellent accessibility
      - TypeScript support with proper type definitions
      
      ## Props
      
      ### `<ModelSelector />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Dialog>` | - | Any other props are spread to the underlying Dialog component. |
      
      ### `<ModelSelectorTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof DialogTrigger>` | - | Any other props are spread to the underlying DialogTrigger component. |
      
      ### `<ModelSelectorContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `title` | `ReactNode` | - | Accessible title for the dialog (rendered in sr-only). |
      | `...props` | `React.ComponentProps<typeof DialogContent>` | - | Any other props are spread to the underlying DialogContent component. |
      
      ### `<ModelSelectorDialog />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandDialog>` | - | Any other props are spread to the underlying CommandDialog component. |
      
      ### `<ModelSelectorInput />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandInput>` | - | Any other props are spread to the underlying CommandInput component. |
      
      ### `<ModelSelectorList />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandList>` | - | Any other props are spread to the underlying CommandList component. |
      
      ### `<ModelSelectorEmpty />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandEmpty>` | - | Any other props are spread to the underlying CommandEmpty component. |
      
      ### `<ModelSelectorGroup />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandGroup>` | - | Any other props are spread to the underlying CommandGroup component. |
      
      ### `<ModelSelectorItem />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandItem>` | - | Any other props are spread to the underlying CommandItem component. |
      
      ### `<ModelSelectorShortcut />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandShortcut>` | - | Any other props are spread to the underlying CommandShortcut component. |
      
      ### `<ModelSelectorSeparator />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandSeparator>` | - | Any other props are spread to the underlying CommandSeparator component. |
      
      ### `<ModelSelectorLogo />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `provider` | `string` | Required | The AI provider name. Supports major providers like  |
      | `...props` | `Omit<React.ComponentProps<` | - | Any other props are spread to the underlying img element (except src and alt which are generated). |
      
      ### `<ModelSelectorLogoGroup />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div element. |
      
      ### `<ModelSelectorName />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying span element. |
      
    • node.md 2.8 KB
      # Node
      
      A composable node component for React Flow-based canvases with Card-based styling.
      
      The `Node` component provides a composable, Card-based node for React Flow canvases. It includes support for connection handles, structured layouts, and consistent styling using shadcn/ui components.
      
      
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add node
      ```
      
      ## Features
      
      - Built on shadcn/ui Card components for consistent styling
      - Automatic handle placement (left for target, right for source)
      - Composable sub-components (Header, Title, Description, Action, Content, Footer)
      - Semantic structure for organizing node information
      - Pre-styled sections with borders and backgrounds
      - Responsive sizing with fixed small width
      - Full TypeScript support with proper type definitions
      - Compatible with React Flow's node system
      
      ## Props
      
      ### `<Node />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `handles` | `unknown` | - | Configuration for connection handles. Target renders on the left, source on the right. |
      | `className` | `string` | - | Additional CSS classes to apply to the node. |
      | `...props` | `ComponentProps<typeof Card>` | - | Any other props are spread to the underlying Card component. |
      
      ### `<NodeHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply to the header. |
      | `...props` | `ComponentProps<typeof CardHeader>` | - | Any other props are spread to the underlying CardHeader component. |
      
      ### `<NodeTitle />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `ComponentProps<typeof CardTitle>` | - | Any other props are spread to the underlying CardTitle component. |
      
      ### `<NodeDescription />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `ComponentProps<typeof CardDescription>` | - | Any other props are spread to the underlying CardDescription component. |
      
      ### `<NodeAction />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `ComponentProps<typeof CardAction>` | - | Any other props are spread to the underlying CardAction component. |
      
      ### `<NodeContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply to the content. |
      | `...props` | `ComponentProps<typeof CardContent>` | - | Any other props are spread to the underlying CardContent component. |
      
      ### `<NodeFooter />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply to the footer. |
      | `...props` | `ComponentProps<typeof CardFooter>` | - | Any other props are spread to the underlying CardFooter component. |
      
    • open-in-chat.md 2.7 KB
      # Open In Chat
      
      A dropdown menu for opening queries in various AI chat platforms including ChatGPT, Claude, T3, Scira, and v0.
      
      The `OpenIn` component provides a dropdown menu that allows users to open queries in different AI chat platforms with a single click.
      
      See `scripts/open-in-chat.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add open-in-chat
      ```
      
      ## Features
      
      - Pre-configured links to popular AI chat platforms
      - Context-based query passing for cleaner API
      - Customizable dropdown trigger button
      - Automatic URL parameter encoding for queries
      - Support for ChatGPT, Claude, T3 Chat, Scira AI, v0, and Cursor
      - Branded icons for each platform
      - TypeScript support with proper type definitions
      - Accessible dropdown menu with keyboard navigation
      - External link indicators for clarity
      
      ## Supported Platforms
      
      - **ChatGPT** - Opens query in OpenAI's ChatGPT with search hints
      - **Claude** - Opens query in Anthropic's Claude AI
      - **T3 Chat** - Opens query in T3 Chat platform
      - **Scira AI** - Opens query in Scira's AI assistant
      - **v0** - Opens query in Vercel's v0 platform
      - **Cursor** - Opens query in Cursor AI editor
      
      ## Props
      
      ### `<OpenIn />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `query` | `string` | - | The query text to be sent to all AI platforms. |
      | `...props` | `React.ComponentProps<typeof DropdownMenu>` | - | Props to spread to the underlying radix-ui DropdownMenu component. |
      
      ### `<OpenInTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom trigger button. |
      | `...props` | `React.ComponentProps<typeof DropdownMenuTrigger>` | - | Props to spread to the underlying DropdownMenuTrigger component. |
      
      ### `<OpenInContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply to the dropdown content. |
      | `...props` | `React.ComponentProps<typeof DropdownMenuContent>` | - | Props to spread to the underlying DropdownMenuContent component. |
      
      ### `<OpenInChatGPT />`, `<OpenInClaude />`, `<OpenInT3 />`, `<OpenInScira />`, `<OpenInv0 />`, `<OpenInCursor />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof DropdownMenuItem>` | - | Props to spread to the underlying DropdownMenuItem component. The query is automatically provided via context from the parent OpenIn component. |
      
      ### `<OpenInItem />`, `<OpenInLabel />`, `<OpenInSeparator />`
      
      Additional composable components for custom dropdown menu items, labels, and separators that follow the same props pattern as their underlying radix-ui counterparts.
      
    • package-info.md 3.2 KB
      # Package Info
      
      Display dependency information and version changes.
      
      The `PackageInfo` component displays package dependency information including version changes and change type badges.
      
      See `scripts/package-info.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add package-info
      ```
      
      ## Features
      
      - Version change display (current → new)
      - Color-coded change type badges
      - Dependencies list
      - Description support
      
      ## Change Types
      
      | Type      | Color  | Use Case           |
      | --------- | ------ | ------------------ |
      | `major`   | Red    | Breaking changes   |
      | `minor`   | Yellow | New features       |
      | `patch`   | Green  | Bug fixes          |
      | `added`   | Blue   | New dependency     |
      | `removed` | Gray   | Removed dependency |
      
      ## Props
      
      ### `<PackageInfo />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `name` | `string` | Required | Package name. |
      | `currentVersion` | `string` | - | Current installed version. |
      | `newVersion` | `string` | - | New version being installed. |
      | `changeType` | `unknown` | - | Type of version change. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<PackageInfoHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the header div. |
      
      ### `<PackageInfoName />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom name content. Defaults to the name from context. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<PackageInfoChangeType />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom change type label. Defaults to the changeType from context. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the Badge component. |
      
      ### `<PackageInfoVersion />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom version content. Defaults to version transition display. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<PackageInfoDescription />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLParagraphElement>` | - | Spread to the p element. |
      
      ### `<PackageInfoContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<PackageInfoDependencies />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the container div. |
      
      ### `<PackageInfoDependency />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `name` | `string` | Required | Dependency name. |
      | `version` | `string` | - | Dependency version. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Spread to the row div. |
      
    • panel.md 1 KB
      # Panel
      
      A styled panel component for React Flow-based canvases to position custom UI elements.
      
      The `Panel` component provides a positioned container for custom UI elements on React Flow canvases. It includes modern card styling with backdrop blur and flexible positioning options.
      
      
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add panel
      ```
      
      ## Features
      
      - Flexible positioning (top-left, top-right, bottom-left, bottom-right, top-center, bottom-center)
      - Rounded pill design with backdrop blur
      - Theme-aware card background
      - Flexbox layout for easy content alignment
      - Subtle drop shadow for depth
      - Full TypeScript support
      - Compatible with React Flow's panel system
      
      ## Props
      
      ### `<Panel />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `position` | `unknown` | - | Position of the panel on the canvas. |
      | `className` | `string` | - | Additional CSS classes to apply to the panel. |
      | `...props` | `ComponentProps<typeof Panel>` | - | Any other props from @xyflow/react Panel component. |
      
    • persona.md 5.4 KB
      # Persona
      
      An animated AI visual component powered by Rive that responds to different states like listening, thinking, and speaking.
      
      The `Persona` component displays an animated AI visual that responds to different conversational states. Built with Rive WebGL2, it provides smooth, high-performance animations for various AI interaction states including idle, listening, thinking, speaking, and asleep. The component supports multiple visual variants to match different design aesthetics.
      
      See `scripts/persona-obsidian.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add persona
      ```
      
      ## Features
      
      - Smooth state-based animations powered by Rive
      - Multiple visual variants (obsidian, mana, opal, halo, glint, command)
      - Responsive to five distinct states: idle, listening, thinking, speaking, and asleep
      - WebGL2-accelerated rendering for optimal performance
      - Customizable size and styling
      - Lifecycle callbacks for load, ready, pause, play, and stop events
      - TypeScript support with full type definitions
      
      ## Variants
      
      The Persona component comes with 6 distinct visual variants, each with its own unique aesthetic:
      
      ### Obsidian (Default)
      
      See `scripts/persona-obsidian.tsx` for this example.
      
      ### Mana
      
      See `scripts/persona-mana.tsx` for this example.
      
      ### Opal
      
      See `scripts/persona-opal.tsx` for this example.
      
      ### Halo
      
      See `scripts/persona-halo.tsx` for this example.
      
      ### Glint
      
      See `scripts/persona-glint.tsx` for this example.
      
      ### Command
      
      See `scripts/persona-command.tsx` for this example.
      
      ## Props
      
      ### `<Persona />`
      
      The root component that renders the animated AI visual.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `state` | `unknown` | - | The current state of the AI persona. Controls which animation is displayed. |
      | `variant` | `unknown` | - | The visual style variant to display. |
      | `className` | `string` | - | Additional CSS classes to apply to the component. |
      | `onLoad` | `RiveParameters[` | - | Callback fired when the Rive file starts loading. |
      | `onLoadError` | `RiveParameters[` | - | Callback fired if the Rive file fails to load. |
      | `onReady` | `() => void` | - | Callback fired when the Rive animation is ready to play. |
      | `onPause` | `RiveParameters[` | - | Callback fired when the animation is paused. |
      | `onPlay` | `RiveParameters[` | - | Callback fired when the animation starts playing. |
      | `onStop` | `RiveParameters[` | - | Callback fired when the animation is stopped. |
      
      ## States
      
      The Persona component responds to five distinct states, each triggering different animations:
      
      - **idle**: The default resting state when the AI is not active
      - **listening**: Displayed when the AI is actively listening to user input (e.g., during voice recording)
      - **thinking**: Shown when the AI is processing or generating a response
      - **speaking**: Active when the AI is delivering a response (e.g., text-to-speech output)
      - **asleep**: A dormant state for when the AI is inactive or in low-power mode
      
      ## React Strict Mode (Vite)
      
      The Persona component uses WebGL2 for rendering. Browsers limit the number of active WebGL2 contexts (~8–16), and React Strict Mode (enabled by default in Vite dev) double-mounts components, which can exhaust that limit and crash the page.
      
      The component includes a built-in guard that defers WebGL2 initialization by one frame, preventing context creation during Strict Mode's throw-away mount. This means the component works in Vite dev mode out of the box — no configuration needed.
      
      If you still experience crashes (for example, when rendering many Persona instances simultaneously), reduce the number of concurrent Persona components on screen.
      
      ## Usage Examples
      
      ### Basic Usage
      
      ```tsx
      import { Persona } from "@repo/elements/persona";
      
      export default function App() {
        return <Persona state="listening" variant="opal" />;
      }
      ```
      
      ### With State Management
      
      ```tsx
      import { Persona } from "@repo/elements/persona";
      import { useState } from "react";
      
      export default function App() {
        const [state, setState] = useState<
          "idle" | "listening" | "thinking" | "speaking" | "asleep"
        >("idle");
      
        const startListening = () => setState("listening");
        const startThinking = () => setState("thinking");
        const startSpeaking = () => setState("speaking");
        const reset = () => setState("idle");
      
        return (
          <div>
            <Persona state={state} variant="opal" className="size-32" />
            <div>
              <button onClick={startListening}>Listen</button>
              <button onClick={startThinking}>Think</button>
              <button onClick={startSpeaking}>Speak</button>
              <button onClick={reset}>Reset</button>
            </div>
          </div>
        );
      }
      ```
      
      ### With Custom Styling
      
      ```tsx
      import { Persona } from "@repo/elements/persona";
      
      export default function App() {
        return (
          <Persona
            state="thinking"
            variant="halo"
            className="size-64 rounded-full border border-border"
          />
        );
      }
      ```
      
      ### With Lifecycle Callbacks
      
      ```tsx
      import { Persona } from "@repo/elements/persona";
      
      export default function App() {
        return (
          <Persona
            state="listening"
            variant="glint"
            onReady={() => console.log("Animation ready")}
            onLoad={() => console.log("Starting to load")}
            onLoadError={(error) => console.error("Failed to load:", error)}
            onPlay={() => console.log("Animation playing")}
            onPause={() => console.log("Animation paused")}
            onStop={() => console.log("Animation stopped")}
          />
        );
      }
      ```
      
    • plan.md 3.2 KB
      # Plan
      
      A collapsible plan component for displaying AI-generated execution plans with streaming support and shimmer animations.
      
      The `Plan` component provides a flexible system for displaying AI-generated execution plans with collapsible content. Perfect for showing multi-step workflows, task breakdowns, and implementation strategies with support for streaming content and loading states.
      
      See `scripts/plan.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add plan
      ```
      
      ## Features
      
      - Collapsible content with smooth animations
      - Streaming support with shimmer loading states
      - Built on shadcn/ui Card and Collapsible components
      - TypeScript support with comprehensive type definitions
      - Customizable styling with Tailwind CSS
      - Responsive design with mobile-friendly interactions
      - Keyboard navigation and accessibility support
      - Theme-aware with automatic dark mode support
      - Context-based state management for streaming
      
      ## Props
      
      ### `<Plan />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `isStreaming` | `boolean` | `false` | Whether content is currently streaming. Enables shimmer animations on title and description. |
      | `defaultOpen` | `boolean` | - | Whether the plan is expanded by default. |
      | `...props` | `React.ComponentProps<typeof Collapsible>` | - | Any other props are spread to the Collapsible component. |
      
      ### `<PlanHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CardHeader>` | - | Any other props are spread to the CardHeader component. |
      
      ### `<PlanTitle />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `string` | - | The title text. Displays with shimmer animation when isStreaming is true. |
      | `...props` | `Omit<React.ComponentProps<typeof CardTitle>, ` | - | Any other props (except children) are spread to the CardTitle component. |
      
      ### `<PlanDescription />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `string` | - | The description text. Displays with shimmer animation when isStreaming is true. |
      | `...props` | `Omit<React.ComponentProps<typeof CardDescription>, ` | - | Any other props (except children) are spread to the CardDescription component. |
      
      ### `<PlanTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleTrigger>` | - | Any other props are spread to the CollapsibleTrigger component. Renders as a Button with chevron icon. |
      
      ### `<PlanContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CardContent>` | - | Any other props are spread to the CardContent component. |
      
      ### `<PlanFooter />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the div element. |
      
      ### `<PlanAction />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CardAction>` | - | Any other props are spread to the CardAction component. |
      
    • prompt-input.md 19.8 KB
      # Prompt Input
      
      Allows a user to send a message with file attachments to a large language model. It includes a textarea, file upload capabilities, a submit button, and a dropdown for selecting the model.
      
      The `PromptInput` component allows a user to send a message with file attachments to a large language model. It includes a textarea, file upload capabilities, a submit button, and a dropdown for selecting the model.
      
      See `scripts/prompt-input.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add prompt-input
      ```
      
      ## Usage with AI SDK
      
      Build a fully functional chat app using `PromptInput`, [`Conversation`](/components/conversation) with a model picker:
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import {
        Attachment,
        AttachmentPreview,
        AttachmentRemove,
        Attachments,
      } from "@/components/ai-elements/attachments";
      import {
        PromptInput,
        PromptInputActionAddAttachments,
        PromptInputActionAddScreenshot,
        PromptInputActionMenu,
        PromptInputActionMenuContent,
        PromptInputActionMenuTrigger,
        PromptInputBody,
        PromptInputButton,
        PromptInputHeader,
        type PromptInputMessage,
        PromptInputSelect,
        PromptInputSelectContent,
        PromptInputSelectItem,
        PromptInputSelectTrigger,
        PromptInputSelectValue,
        PromptInputSubmit,
        PromptInputTextarea,
        PromptInputFooter,
        PromptInputTools,
        usePromptInputAttachments,
      } from "@/components/ai-elements/prompt-input";
      import { GlobeIcon } from "lucide-react";
      import { useState } from "react";
      import { useChat } from "@ai-sdk/react";
      import {
        Conversation,
        ConversationContent,
        ConversationScrollButton,
      } from "@/components/ai-elements/conversation";
      import {
        Message,
        MessageContent,
        MessageResponse,
      } from "@/components/ai-elements/message";
      
      const PromptInputAttachmentsDisplay = () => {
        const attachments = usePromptInputAttachments();
      
        if (attachments.files.length === 0) {
          return null;
        }
      
        return (
          <Attachments variant="inline">
            {attachments.files.map((attachment) => (
              <Attachment
                data={attachment}
                key={attachment.id}
                onRemove={() => attachments.remove(attachment.id)}
              >
                <AttachmentPreview />
                <AttachmentRemove />
              </Attachment>
            ))}
          </Attachments>
        );
      };
      
      const models = [
        { id: "gpt-4o", name: "GPT-4o" },
        { id: "claude-opus-4-20250514", name: "Claude 4 Opus" },
      ];
      
      const InputDemo = () => {
        const [text, setText] = useState<string>("");
        const [model, setModel] = useState<string>(models[0].id);
        const [useWebSearch, setUseWebSearch] = useState<boolean>(false);
      
        const { messages, status, sendMessage } = useChat();
      
        const handleSubmit = (message: PromptInputMessage) => {
          const hasText = Boolean(message.text);
          const hasAttachments = Boolean(message.files?.length);
      
          if (!(hasText || hasAttachments)) {
            return;
          }
      
          sendMessage(
            {
              text: message.text || "Sent with attachments",
              files: message.files,
            },
            {
              body: {
                model: model,
                webSearch: useWebSearch,
              },
            }
          );
          setText("");
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <Conversation>
                <ConversationContent>
                  {messages.map((message) => (
                    <Message from={message.role} key={message.id}>
                      <MessageContent>
                        {message.parts.map((part, i) => {
                          switch (part.type) {
                            case "text":
                              return (
                                <MessageResponse key={`${message.id}-${i}`}>
                                  {part.text}
                                </MessageResponse>
                              );
                            default:
                              return null;
                          }
                        })}
                      </MessageContent>
                    </Message>
                  ))}
                </ConversationContent>
                <ConversationScrollButton />
              </Conversation>
      
              <PromptInput
                onSubmit={handleSubmit}
                className="mt-4"
                globalDrop
                multiple
              >
                <PromptInputHeader>
                  <PromptInputAttachmentsDisplay />
                </PromptInputHeader>
                <PromptInputBody>
                  <PromptInputTextarea
                    onChange={(e) => setText(e.target.value)}
                    value={text}
                  />
                </PromptInputBody>
                <PromptInputFooter>
                  <PromptInputTools>
                    <PromptInputActionMenu>
                      <PromptInputActionMenuTrigger />
                      <PromptInputActionMenuContent>
                        <PromptInputActionAddAttachments />
                        <PromptInputActionAddScreenshot />
                      </PromptInputActionMenuContent>
                    </PromptInputActionMenu>
                    <PromptInputButton
                      onClick={() => setUseWebSearch(!useWebSearch)}
                      tooltip={{ content: "Search the web", shortcut: "⌘K" }}
                      variant={useWebSearch ? "default" : "ghost"}
                    >
                      <GlobeIcon size={16} />
                      <span>Search</span>
                    </PromptInputButton>
                    <PromptInputSelect
                      onValueChange={(value) => {
                        setModel(value);
                      }}
                      value={model}
                    >
                      <PromptInputSelectTrigger>
                        <PromptInputSelectValue />
                      </PromptInputSelectTrigger>
                      <PromptInputSelectContent>
                        {models.map((model) => (
                          <PromptInputSelectItem key={model.id} value={model.id}>
                            {model.name}
                          </PromptInputSelectItem>
                        ))}
                      </PromptInputSelectContent>
                    </PromptInputSelect>
                  </PromptInputTools>
                  <PromptInputSubmit disabled={!text && !status} status={status} />
                </PromptInputFooter>
              </PromptInput>
            </div>
          </div>
        );
      };
      
      export default InputDemo;
      ```
      
      Add the following route to your backend:
      
      ```ts title="app/api/chat/route.ts"
      import { streamText, UIMessage, convertToModelMessages } from "ai";
      
      // Allow streaming responses up to 30 seconds
      export const maxDuration = 30;
      
      export async function POST(req: Request) {
        const {
          model,
          messages,
          webSearch,
        }: {
          messages: UIMessage[];
          model: string;
          webSearch?: boolean;
        } = await req.json();
      
        const result = streamText({
          model: webSearch ? "perplexity/sonar" : model,
          messages: await convertToModelMessages(messages),
        });
      
        return result.toUIMessageStreamResponse();
      }
      ```
      
      ## Features
      
      - Auto-resizing textarea that adjusts height based on content
      - File attachment support with drag-and-drop
      - Built-in screenshot capture action
      - Image preview for image attachments
      - Configurable file constraints (max files, max size, accepted types)
      - Automatic submit button icons based on status
      - Support for keyboard shortcuts (Enter to submit, Shift+Enter for new line)
      - Customizable min/max height for the textarea
      - Flexible toolbar with support for custom actions and tools
      - Built-in model selection dropdown
      - Built-in native speech recognition button (Web Speech API)
      - Optional provider for lifted state management
      - Form automatically resets on submit
      - Responsive design with mobile-friendly controls
      - Clean, modern styling with customizable themes
      - Form-based submission handling
      - Hidden file input sync for native form posts
      - Global document drop support (opt-in)
      
      ## Examples
      
      ### Cursor style
      
      See `scripts/prompt-input-cursor.tsx` for this example.
      
      ### Button tooltips
      
      Buttons can display tooltips with optional keyboard shortcut hints. Hover over the buttons below to see the tooltips.
      
      See `scripts/prompt-input-tooltip.tsx` for this example.
      
      ## Props
      
      ### `<PromptInput />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `onSubmit` | `(message: PromptInputMessage, event: FormEvent) => void` | - | Handler called when the form is submitted with message text and files. |
      | `accept` | `string` | - | File types to accept (e.g.,  |
      | `multiple` | `boolean` | - | Whether to allow multiple file selection. |
      | `globalDrop` | `boolean` | - | When true, accepts file drops anywhere on the document. |
      | `syncHiddenInput` | `boolean` | - | Render a hidden input with given name for native form posts. |
      | `maxFiles` | `number` | - | Maximum number of files allowed. |
      | `maxFileSize` | `number` | - | Maximum file size in bytes. |
      | `onError` | `(err: { code: ` | - | Handler for file validation errors. |
      | `...props` | `React.HTMLAttributes<HTMLFormElement>` | - | Any other props are spread to the root form element. |
      
      ### `<PromptInputTextarea />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Textarea>` | - | Any other props are spread to the underlying Textarea component. |
      
      ### `<PromptInputFooter />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the toolbar div. |
      
      ### `<PromptInputTools />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the tools div. |
      
      ### `<PromptInputButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `tooltip` | `string | { content: ReactNode; shortcut?: string; side?: ` | - | Optional tooltip to display on hover. Can be a string or an object with content, shortcut, and side properties. |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      #### Tooltip Examples
      
      ```tsx
      // Simple string tooltip
      <PromptInputButton tooltip="Search the web">
        <GlobeIcon size={16} />
      </PromptInputButton>
      
      // Tooltip with keyboard shortcut hint
      <PromptInputButton tooltip={{ content: "Search", shortcut: "⌘K" }}>
        <GlobeIcon size={16} />
      </PromptInputButton>
      
      // Tooltip with custom position
      <PromptInputButton tooltip={{ content: "Search", side: "bottom" }}>
        <GlobeIcon size={16} />
      </PromptInputButton>
      ```
      
      ### `<PromptInputSubmit />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `status` | `ChatStatus` | - | Current chat status to determine button icon (submitted, streaming, error). |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `<PromptInputSelect />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Select>` | - | Any other props are spread to the underlying Select component. |
      
      ### `<PromptInputSelectTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof SelectTrigger>` | - | Any other props are spread to the underlying SelectTrigger component. |
      
      ### `<PromptInputSelectContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof SelectContent>` | - | Any other props are spread to the underlying SelectContent component. |
      
      ### `<PromptInputSelectItem />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof SelectItem>` | - | Any other props are spread to the underlying SelectItem component. |
      
      ### `<PromptInputSelectValue />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof SelectValue>` | - | Any other props are spread to the underlying SelectValue component. |
      
      ### `<PromptInputBody />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the body div. |
      
      ### Attachments
      
      Attachment components have been moved to a separate module. See the [Attachment](/components/attachment) component documentation for details on `<Attachments />`, `<Attachment />`, `<AttachmentPreview />`, `<AttachmentInfo />`, and `<AttachmentRemove />`.
      
      ### `<PromptInputActionMenu />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof DropdownMenu>` | - | Any other props are spread to the underlying DropdownMenu component. |
      
      ### `<PromptInputActionMenuTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying Button component. |
      
      ### `<PromptInputActionMenuContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof DropdownMenuContent>` | - | Any other props are spread to the underlying DropdownMenuContent component. |
      
      ### `<PromptInputActionMenuItem />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof DropdownMenuItem>` | - | Any other props are spread to the underlying DropdownMenuItem component. |
      
      ### `<PromptInputActionAddAttachments />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `label` | `string` | - | Label for the menu item. |
      | `...props` | `React.ComponentProps<typeof DropdownMenuItem>` | - | Any other props are spread to the underlying DropdownMenuItem component. |
      
      ### `<PromptInputActionAddScreenshot />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `label` | `string` | - | Label for the menu item. |
      | `...props` | `React.ComponentProps<typeof DropdownMenuItem>` | - | Any other props are spread to the underlying DropdownMenuItem component. |
      
      ### `<PromptInputProvider />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `initialInput` | `string` | - | Initial text input value. |
      | `children` | `React.ReactNode` | - | Child components that will have access to the provider context. |
      
      Optional global provider that lifts PromptInput state outside of PromptInput. When used, it allows you to access and control the input state from anywhere within the provider tree. If not used, PromptInput stays fully self-managed.
      
      ### `<PromptInputHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `Omit<React.ComponentProps<typeof InputGroupAddon>, ` | - | Any other props (except align) are spread to the InputGroupAddon component. |
      
      ### `<PromptInputHoverCard />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `openDelay` | `number` | `0` | Delay in milliseconds before opening. |
      | `closeDelay` | `number` | `0` | Delay in milliseconds before closing. |
      | `...props` | `React.ComponentProps<typeof HoverCard>` | - | Any other props are spread to the HoverCard component. |
      
      ### `<PromptInputHoverCardTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof HoverCardTrigger>` | - | Any other props are spread to the HoverCardTrigger component. |
      
      ### `<PromptInputHoverCardContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `align` | `unknown` | - | Alignment of the hover card content. |
      | `...props` | `React.ComponentProps<typeof HoverCardContent>` | - | Any other props are spread to the HoverCardContent component. |
      
      ### `<PromptInputTabsList />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<PromptInputTab />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<PromptInputTabLabel />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLHeadingElement>` | - | Any other props are spread to the h3 element. |
      
      ### `<PromptInputTabBody />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<PromptInputTabItem />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<PromptInputCommand />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Command>` | - | Any other props are spread to the Command component. |
      
      ### `<PromptInputCommandInput />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandInput>` | - | Any other props are spread to the CommandInput component. |
      
      ### `<PromptInputCommandList />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandList>` | - | Any other props are spread to the CommandList component. |
      
      ### `<PromptInputCommandEmpty />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandEmpty>` | - | Any other props are spread to the CommandEmpty component. |
      
      ### `<PromptInputCommandGroup />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandGroup>` | - | Any other props are spread to the CommandGroup component. |
      
      ### `<PromptInputCommandItem />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandItem>` | - | Any other props are spread to the CommandItem component. |
      
      ### `<PromptInputCommandSeparator />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandSeparator>` | - | Any other props are spread to the CommandSeparator component. |
      
      ## Hooks
      
      ### `usePromptInputAttachments`
      
      Access and manage file attachments within a PromptInput context.
      
      ```tsx
      const attachments = usePromptInputAttachments();
      
      // Available methods:
      attachments.files; // Array of current attachments
      attachments.add(files); // Add new files
      attachments.remove(id); // Remove an attachment by ID
      attachments.clear(); // Clear all attachments
      attachments.openFileDialog(); // Open file selection dialog
      ```
      
      ### `usePromptInputController`
      
      Access the full PromptInput controller from a PromptInputProvider. Only available when using the provider.
      
      ```tsx
      const controller = usePromptInputController();
      
      // Available methods:
      controller.textInput.value; // Current text input value
      controller.textInput.setInput(value); // Set text input value
      controller.textInput.clear(); // Clear text input
      controller.attachments; // Same as usePromptInputAttachments
      ```
      
      ### `useProviderAttachments`
      
      Access attachments context from a PromptInputProvider. Only available when using the provider.
      
      ```tsx
      const attachments = useProviderAttachments();
      
      // Same interface as usePromptInputAttachments
      ```
      
      ### `usePromptInputReferencedSources`
      
      Access referenced sources context within a PromptInput.
      
      ```tsx
      const sources = usePromptInputReferencedSources();
      
      // Available methods:
      sources.sources; // Array of current referenced sources
      sources.add(sources); // Add new source(s)
      sources.remove(id); // Remove a source by ID
      sources.clear(); // Clear all sources
      ```
      
    • queue.md 5.4 KB
      # Queue
      
      A comprehensive queue component system for displaying message lists, todos, and collapsible task sections in AI applications.
      
      The `Queue` component provides a flexible system for displaying lists of messages, todos, attachments, and collapsible sections. Perfect for showing AI workflow progress, pending tasks, message history, or any structured list of items in your application.
      
      See `scripts/queue.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add queue
      ```
      
      ## Features
      
      - Flexible component system with composable parts
      - Collapsible sections with smooth animations
      - Support for completed/pending state indicators
      - Built-in scroll area for long lists
      - Attachment display with images and file indicators
      - Hover-revealed action buttons for queue items
      - TypeScript support with comprehensive type definitions
      - Customizable styling with Tailwind CSS
      - Responsive design with mobile-friendly interactions
      - Keyboard navigation and accessibility support
      - Theme-aware with automatic dark mode support
      
      ## Examples
      
      ### With PromptInput
      
      See `scripts/queue-prompt-input.tsx` for this example.
      
      ## Props
      
      ### `<Queue />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the root div. |
      
      ### `<QueueSection />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `defaultOpen` | `boolean` | `true` | Whether the section is open by default. |
      | `...props` | `React.ComponentProps<typeof Collapsible>` | - | Any other props are spread to the Collapsible component. |
      
      ### `<QueueSectionTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the button element. |
      
      ### `<QueueSectionLabel />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `label` | `string` | - | The label text to display. |
      | `count` | `number` | - | The count to display before the label. |
      | `icon` | `React.ReactNode` | - | An optional icon to display before the count. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<QueueSectionContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleContent>` | - | Any other props are spread to the CollapsibleContent component. |
      
      ### `<QueueList />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof ScrollArea>` | - | Any other props are spread to the ScrollArea component. |
      
      ### `<QueueItem />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the li element. |
      
      ### `<QueueItemIndicator />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `completed` | `boolean` | `false` | Whether the item is completed. Affects the indicator styling. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<QueueItemContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `completed` | `boolean` | `false` | Whether the item is completed. Affects text styling with strikethrough and opacity. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<QueueItemDescription />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `completed` | `boolean` | `false` | Whether the item is completed. Affects text styling. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the div element. |
      
      ### `<QueueItemActions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the div element. |
      
      ### `<QueueItemAction />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `Omit<React.ComponentProps<typeof Button>, ` | - | Any other props (except variant and size) are spread to the Button component. |
      
      ### `<QueueItemAttachment />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the div element. |
      
      ### `<QueueItemImage />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the img element. |
      
      ### `<QueueItemFile />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ## Type Exports
      
      ### `QueueMessagePart`
      
      Interface for message parts within queue messages.
      
      ```tsx
      interface QueueMessagePart {
        type: string;
        text?: string;
        url?: string;
        filename?: string;
        mediaType?: string;
      }
      ```
      
      ### `QueueMessage`
      
      Interface for queue message items.
      
      ```tsx
      interface QueueMessage {
        id: string;
        parts: QueueMessagePart[];
      }
      ```
      
      ### `QueueTodo`
      
      Interface for todo items in the queue.
      
      ```tsx
      interface QueueTodo {
        id: string;
        title: string;
        description?: string;
        status?: "pending" | "completed";
      }
      ```
      
    • reasoning.md 7.8 KB
      # Reasoning
      
      A collapsible component that displays AI reasoning content, automatically opening during streaming and closing when finished.
      
      The `Reasoning` component displays AI reasoning content, automatically opening during streaming and closing when finished.
      
      See `scripts/reasoning.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add reasoning
      ```
      
      ## Usage with AI SDK
      
      Build a chatbot with reasoning using Deepseek R1 or other reasoning models.
      
      Some models (like GPT with high reasoning effort) return multiple reasoning parts instead of a single streaming block. The example below consolidates all reasoning parts into a single component to avoid displaying multiple "Thinking..." indicators.
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import {
        Reasoning,
        ReasoningContent,
        ReasoningTrigger,
      } from "@/components/ai-elements/reasoning";
      import {
        Conversation,
        ConversationContent,
        ConversationScrollButton,
      } from "@/components/ai-elements/conversation";
      import {
        PromptInput,
        type PromptInputMessage,
        PromptInputTextarea,
        PromptInputSubmit,
      } from "@/components/ai-elements/prompt-input";
      import { Spinner } from "@/components/ui/spinner";
      import {
        Message,
        MessageContent,
        MessageResponse,
      } from "@/components/ai-elements/message";
      import { useState } from "react";
      import { useChat } from "@ai-sdk/react";
      import type { UIMessage } from "ai";
      
      const MessageParts = ({
        message,
        isLastMessage,
        isStreaming,
      }: {
        message: UIMessage;
        isLastMessage: boolean;
        isStreaming: boolean;
      }) => {
        // Consolidate all reasoning parts into one block
        const reasoningParts = message.parts.filter(
          (part) => part.type === "reasoning"
        );
        const reasoningText = reasoningParts.map((part) => part.text).join("\n\n");
        const hasReasoning = reasoningParts.length > 0;
      
        // Check if reasoning is still streaming (last part is reasoning on last message)
        const lastPart = message.parts.at(-1);
        const isReasoningStreaming =
          isLastMessage && isStreaming && lastPart?.type === "reasoning";
      
        return (
          <>
            {hasReasoning && (
              <Reasoning className="w-full" isStreaming={isReasoningStreaming}>
                <ReasoningTrigger />
                <ReasoningContent>{reasoningText}</ReasoningContent>
              </Reasoning>
            )}
            {message.parts.map((part, i) => {
              if (part.type === "text") {
                return (
                  <MessageResponse key={`${message.id}-${i}`}>
                    {part.text}
                  </MessageResponse>
                );
              }
              return null;
            })}
          </>
        );
      };
      
      const ReasoningDemo = () => {
        const [input, setInput] = useState("");
      
        const { messages, sendMessage, status } = useChat();
      
        const handleSubmit = (message: PromptInputMessage) => {
          sendMessage({ text: message.text });
          setInput("");
        };
      
        const isStreaming = status === "streaming";
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <Conversation>
                <ConversationContent>
                  {messages.map((message, index) => (
                    <Message from={message.role} key={message.id}>
                      <MessageContent>
                        <MessageParts
                          message={message}
                          isLastMessage={index === messages.length - 1}
                          isStreaming={isStreaming}
                        />
                      </MessageContent>
                    </Message>
                  ))}
                  {status === "submitted" && <Spinner />}
                </ConversationContent>
                <ConversationScrollButton />
              </Conversation>
      
              <PromptInput
                onSubmit={handleSubmit}
                className="mt-4 w-full max-w-2xl mx-auto relative"
              >
                <PromptInputTextarea
                  value={input}
                  placeholder="Say something..."
                  onChange={(e) => setInput(e.currentTarget.value)}
                  className="pr-12"
                />
                <PromptInputSubmit
                  status={isStreaming ? "streaming" : "ready"}
                  disabled={!input.trim()}
                  className="absolute bottom-1 right-1"
                />
              </PromptInput>
            </div>
          </div>
        );
      };
      
      export default ReasoningDemo;
      ```
      
      Add the following route to your backend:
      
      ```ts title="app/api/chat/route.ts"
      import { streamText, UIMessage, convertToModelMessages } from "ai";
      
      // Allow streaming responses up to 30 seconds
      export const maxDuration = 30;
      
      export async function POST(req: Request) {
        const { model, messages }: { messages: UIMessage[]; model: string } =
          await req.json();
      
        const result = streamText({
          model: "deepseek/deepseek-r1",
          messages: await convertToModelMessages(messages),
        });
      
        return result.toUIMessageStreamResponse({
          sendReasoning: true,
        });
      }
      ```
      
      ## Reasoning vs Chain of Thought
      
      Use the `Reasoning` component when your model outputs thinking content as a single block or continuous stream (Deepseek R1, Claude with extended thinking, etc.).
      
      If your model outputs discrete, labeled steps (search queries, tool calls, distinct thought stages), consider using the [Chain of Thought](/components/chain-of-thought) component instead for a more structured visual representation.
      
      ## Features
      
      - Automatically opens when streaming content and closes when finished
      - Manual toggle control for user interaction
      - Smooth animations and transitions powered by Radix UI
      - Visual streaming indicator with pulsing animation
      - Composable architecture with separate trigger and content components
      - Built with accessibility in mind including keyboard navigation
      - Responsive design that works across different screen sizes
      - Seamlessly integrates with both light and dark themes
      - Built on top of shadcn/ui Collapsible primitives
      - TypeScript support with proper type definitions
      
      ## Props
      
      ### `<Reasoning />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `isStreaming` | `boolean` | `false` | Whether the reasoning is currently streaming (auto-opens and closes the panel). |
      | `open` | `boolean` | - | Controlled open state. |
      | `defaultOpen` | `boolean` | `true` | Default open state when uncontrolled. |
      | `onOpenChange` | `(open: boolean) => void` | - | Callback when open state changes. |
      | `duration` | `number` | - | Duration in seconds to display (can be controlled externally). |
      | `...props` | `React.ComponentProps<typeof Collapsible>` | - | Any other props are spread to the underlying Collapsible component. |
      
      ### `<ReasoningTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `getThinkingMessage` | `(isStreaming: boolean, duration?: number) => ReactNode` | - | Optional function to customize the thinking message. Receives isStreaming and duration parameters. |
      | `...props` | `React.ComponentProps<typeof CollapsibleTrigger>` | - | Any other props are spread to the underlying CollapsibleTrigger component. |
      
      ### `<ReasoningContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `string` | Required | The reasoning text to display (rendered via Streamdown). |
      | `...props` | `React.ComponentProps<typeof CollapsibleContent>` | - | Any other props are spread to the underlying CollapsibleContent component. |
      
      ## Hooks
      
      ### `useReasoning`
      
      Access the reasoning context from child components.
      
      ```tsx
      const { isStreaming, isOpen, setIsOpen, duration } = useReasoning();
      ```
      
      Returns:
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `isStreaming` | `boolean` | - | Whether reasoning is currently streaming. |
      | `isOpen` | `boolean` | - | Whether the reasoning panel is open. |
      | `setIsOpen` | `(open: boolean) => void` | - | Function to set the open state. |
      | `duration` | `number | undefined` | - | Duration in seconds (undefined while streaming). |
      
    • sandbox.md 4.3 KB
      # Sandbox
      
      A collapsible container for displaying AI-generated code and output in chat interfaces.
      
      The `Sandbox` component provides a structured way to display AI-generated code alongside its execution output in chat conversations. It features a collapsible container with status indicators and tabbed navigation between code and output views. It's designed to be used with `CodeBlock` for displaying code and `StackTrace` for displaying errors.
      
      See `scripts/sandbox.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add sandbox
      ```
      
      ## Features
      
      - Collapsible container with smooth animations
      - Status badges showing execution state (Pending, Running, Completed, Error)
      - Tabs for Code and Output views
      - Syntax-highlighted code display
      - Copy button for easy code sharing
      - Works with AI SDK tool state patterns
      
      ## Usage with AI SDK
      
      The Sandbox component integrates with the AI SDK's tool state to show code generation progress:
      
      ```tsx title="components/code-sandbox.tsx"
      "use client";
      
      import type { ToolUIPart } from "ai";
      import {
        Sandbox,
        SandboxContent,
        SandboxHeader,
        SandboxTabContent,
        SandboxTabs,
        SandboxTabsBar,
        SandboxTabsList,
        SandboxTabsTrigger,
      } from "@/components/ai-elements/sandbox";
      import { CodeBlock } from "@/components/ai-elements/code-block";
      
      type CodeSandboxProps = {
        toolPart: ToolUIPart;
      };
      
      export const CodeSandbox = ({ toolPart }: CodeSandboxProps) => {
        const code = toolPart.input?.code ?? "";
        const output = toolPart.output?.logs ?? "";
      
        return (
          <Sandbox>
            <SandboxHeader
              state={toolPart.state}
              title={toolPart.input?.filename ?? "code.tsx"}
            />
            <SandboxContent>
              <SandboxTabs defaultValue="code">
                <SandboxTabsBar>
                  <SandboxTabsList>
                    <SandboxTabsTrigger value="code">Code</SandboxTabsTrigger>
                    <SandboxTabsTrigger value="output">Output</SandboxTabsTrigger>
                  </SandboxTabsList>
                </SandboxTabsBar>
                <SandboxTabContent value="code">
                  <CodeBlock code={code} language="tsx" />
                </SandboxTabContent>
                <SandboxTabContent value="output">
                  <CodeBlock code={output} language="log" />
                </SandboxTabContent>
              </SandboxTabs>
            </SandboxContent>
          </Sandbox>
        );
      };
      ```
      
      ## Props
      
      ### `<Sandbox />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Collapsible>` | - | Any other props are spread to the underlying Collapsible component. |
      
      ### `<SandboxHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `title` | `string` | `undefined` | The title displayed in the header (e.g., filename). |
      | `state` | `ToolUIPart[` | Required | The current execution state, used to display the appropriate status badge. |
      | `className` | `string` | - | Additional CSS classes for the header. |
      
      ### `<SandboxContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleContent>` | - | Any other props are spread to the CollapsibleContent. |
      
      ### `<SandboxTabs />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Tabs>` | - | Any other props are spread to the underlying Tabs component. |
      
      ### `<SandboxTabsBar />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the container div. |
      
      ### `<SandboxTabsList />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof TabsList>` | - | Any other props are spread to the underlying TabsList component. |
      
      ### `<SandboxTabsTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof TabsTrigger>` | - | Any other props are spread to the underlying TabsTrigger component. |
      
      ### `<SandboxTabContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof TabsContent>` | - | Any other props are spread to the underlying TabsContent component. |
      
    • schema-display.md 2.5 KB
      # Schema Display
      
      Display REST API endpoint documentation with parameters, request/response bodies.
      
      The `SchemaDisplay` component visualizes REST API endpoints with HTTP methods, paths, parameters, and request/response schemas.
      
      See `scripts/schema-display.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add schema-display
      ```
      
      ## Features
      
      - Color-coded HTTP methods
      - Path parameter highlighting
      - Collapsible parameters section
      - Request/response body schemas
      - Nested object property display
      - Required field indicators
      
      ## Method Colors
      
      | Method   | Color  |
      | -------- | ------ |
      | `GET`    | Green  |
      | `POST`   | Blue   |
      | `PUT`    | Orange |
      | `PATCH`  | Yellow |
      | `DELETE` | Red    |
      
      ## Examples
      
      ### Basic Usage
      
      See `scripts/schema-display-basic.tsx` for this example.
      
      ### With Parameters
      
      See `scripts/schema-display-params.tsx` for this example.
      
      ### With Request/Response Bodies
      
      See `scripts/schema-display-body.tsx` for this example.
      
      ### Nested Properties
      
      See `scripts/schema-display-nested.tsx` for this example.
      
      ## Props
      
      ### `<SchemaDisplay />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `method` | `unknown` | - | HTTP method. |
      | `path` | `string` | - | API endpoint path. |
      | `description` | `string` | - | Endpoint description. |
      | `parameters` | `SchemaParameter[]` | - | URL/query parameters. |
      | `requestBody` | `SchemaProperty[]` | - | Request body properties. |
      | `responseBody` | `SchemaProperty[]` | - | Response body properties. |
      
      ### `SchemaParameter`
      
      ```tsx
      interface SchemaParameter {
        name: string;
        type: string;
        required?: boolean;
        description?: string;
        location?: "path" | "query" | "header";
      }
      ```
      
      ### `SchemaProperty`
      
      ```tsx
      interface SchemaProperty {
        name: string;
        type: string;
        required?: boolean;
        description?: string;
        properties?: SchemaProperty[]; // For objects
        items?: SchemaProperty; // For arrays
      }
      ```
      
      ### Subcomponents
      
      - `SchemaDisplayHeader` - Header container
      - `SchemaDisplayMethod` - Color-coded method badge
      - `SchemaDisplayPath` - Path with highlighted parameters
      - `SchemaDisplayDescription` - Description text
      - `SchemaDisplayContent` - Content container
      - `SchemaDisplayParameters` - Collapsible parameters section
      - `SchemaDisplayParameter` - Individual parameter
      - `SchemaDisplayRequest` - Collapsible request body
      - `SchemaDisplayResponse` - Collapsible response body
      - `SchemaDisplayProperty` - Schema property (recursive)
      - `SchemaDisplayExample` - Code example block
      
    • shimmer.md 1.6 KB
      # Shimmer
      
      An animated text shimmer component for creating eye-catching loading states and progressive reveal effects.
      
      The `Shimmer` component provides an animated shimmer effect that sweeps across text, perfect for indicating loading states, progressive reveals, or drawing attention to dynamic content in AI applications.
      
      See `scripts/shimmer.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add shimmer
      ```
      
      ## Features
      
      - Smooth animated shimmer effect using CSS gradients and Framer Motion
      - Customizable animation duration and spread
      - Polymorphic component - render as any HTML element via the `as` prop
      - Automatic spread calculation based on text length
      - Theme-aware styling using CSS custom properties
      - Infinite looping animation with linear easing
      - TypeScript support with proper type definitions
      - Memoized for optimal performance
      - Responsive and accessible design
      - Uses `text-transparent` with background-clip for crisp text rendering
      
      ## Examples
      
      ### Different Durations
      
      See `scripts/shimmer-duration.tsx` for this example.
      
      ### Custom Elements
      
      See `scripts/shimmer-elements.tsx` for this example.
      
      ## Props
      
      ### `<Shimmer />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `string` | - | The text content to apply the shimmer effect to. |
      | `as` | `ElementType` | - | The HTML element or React component to render. |
      | `className` | `string` | - | Additional CSS classes to apply to the component. |
      | `duration` | `number` | `2` | The duration of the shimmer animation in seconds. |
      | `spread` | `number` | `2` | The spread multiplier for the shimmer gradient, multiplied by text length. |
      
    • snippet.md 2.2 KB
      # Snippet
      
      Lightweight inline code display for terminal commands and short code references.
      
      The `Snippet` component provides a lightweight way to display terminal commands and short code snippets with copy functionality. Built on top of InputGroup, it's designed for brief code references in text.
      
      See `scripts/snippet.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add snippet
      ```
      
      ## Features
      
      - Composable architecture with InputGroup
      - Optional prefix text (e.g., `$` for terminal commands)
      - Built-in copy button
      - Compact design for chat/markdown
      
      ## Examples
      
      ### Without Prefix
      
      See `scripts/snippet-plain.tsx` for this example.
      
      ## Props
      
      ### `<Snippet />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `code` | `string` | Required | The code content to display. |
      | `children` | `React.ReactNode` | - | Child elements like SnippetAddon, SnippetInput, etc. |
      | `...props` | `React.ComponentProps<typeof InputGroup>` | - | Spread to the InputGroup component. |
      
      ### `<SnippetAddon />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof InputGroupAddon>` | - | Spread to the InputGroupAddon component. |
      
      ### `<SnippetText />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof InputGroupText>` | - | Spread to the InputGroupText component. |
      
      ### `<SnippetInput />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `Omit<React.ComponentProps<typeof InputGroupInput>, ` | - | Spread to the InputGroupInput component. Value and readOnly are set automatically. |
      
      ### `<SnippetCopyButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `onCopy` | `() => void` | - | Callback fired after a successful copy. |
      | `onError` | `(error: Error) => void` | - | Callback fired if copying fails. |
      | `timeout` | `number` | `2000` | How long to show the copied state (ms). |
      | `children` | `React.ReactNode` | - | Custom button content. |
      | `...props` | `React.ComponentProps<typeof InputGroupButton>` | - | Spread to the InputGroupButton component. |
      
    • sources.md 6.2 KB
      # Sources
      
      A component that allows a user to view the sources or citations used to generate a response.
      
      The `Sources` component allows a user to view the sources or citations used to generate a response.
      
      See `scripts/sources.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add sources
      ```
      
      ## Usage with AI SDK
      
      Build a simple web search agent with Perplexity Sonar.
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { useChat } from "@ai-sdk/react";
      import {
        Source,
        Sources,
        SourcesContent,
        SourcesTrigger,
      } from "@/components/ai-elements/sources";
      import {
        PromptInput,
        type PromptInputMessage,
        PromptInputTextarea,
        PromptInputSubmit,
      } from "@/components/ai-elements/prompt-input";
      import {
        Conversation,
        ConversationContent,
        ConversationScrollButton,
      } from "@/components/ai-elements/conversation";
      import {
        Message,
        MessageContent,
        MessageResponse,
      } from "@/components/ai-elements/message";
      import { useState } from "react";
      import { DefaultChatTransport } from "ai";
      
      const SourceDemo = () => {
        const [input, setInput] = useState("");
        const { messages, sendMessage, status } = useChat({
          transport: new DefaultChatTransport({
            api: "/api/sources",
          }),
        });
      
        const handleSubmit = (message: PromptInputMessage) => {
          if (message.text.trim()) {
            sendMessage({ text: message.text });
            setInput("");
          }
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <div className="flex-1 overflow-auto mb-4">
                <Conversation>
                  <ConversationContent>
                    {messages.map((message) => (
                      <div key={message.id}>
                        {message.role === "assistant" && (
                          <Sources>
                            <SourcesTrigger
                              count={
                                message.parts.filter(
                                  (part) => part.type === "source-url"
                                ).length
                              }
                            />
                            {message.parts.map((part, i) => {
                              switch (part.type) {
                                case "source-url":
                                  return (
                                    <SourcesContent key={`${message.id}-${i}`}>
                                      <Source
                                        key={`${message.id}-${i}`}
                                        href={part.url}
                                        title={part.url}
                                      />
                                    </SourcesContent>
                                  );
                              }
                            })}
                          </Sources>
                        )}
                        <Message from={message.role} key={message.id}>
                          <MessageContent>
                            {message.parts.map((part, i) => {
                              switch (part.type) {
                                case "text":
                                  return (
                                    <MessageResponse key={`${message.id}-${i}`}>
                                      {part.text}
                                    </MessageResponse>
                                  );
                                default:
                                  return null;
                              }
                            })}
                          </MessageContent>
                        </Message>
                      </div>
                    ))}
                  </ConversationContent>
                  <ConversationScrollButton />
                </Conversation>
              </div>
      
              <PromptInput
                onSubmit={handleSubmit}
                className="mt-4 w-full max-w-2xl mx-auto relative"
              >
                <PromptInputTextarea
                  value={input}
                  placeholder="Ask a question and search the..."
                  onChange={(e) => setInput(e.currentTarget.value)}
                  className="pr-12"
                />
                <PromptInputSubmit
                  status={status === "streaming" ? "streaming" : "ready"}
                  disabled={!input.trim()}
                  className="absolute bottom-1 right-1"
                />
              </PromptInput>
            </div>
          </div>
        );
      };
      
      export default SourceDemo;
      ```
      
      Add the following route to your backend:
      
      ```tsx title="api/chat/route.ts"
      import { convertToModelMessages, streamText, UIMessage } from "ai";
      import { perplexity } from "@ai-sdk/perplexity";
      
      // Allow streaming responses up to 30 seconds
      export const maxDuration = 30;
      
      export async function POST(req: Request) {
        const { messages }: { messages: UIMessage[] } = await req.json();
      
        const result = streamText({
          model: "perplexity/sonar",
          system:
            "You are a helpful assistant. Keep your responses short (< 100 words) unless you are asked for more details. ALWAYS USE SEARCH.",
          messages: await convertToModelMessages(messages),
        });
      
        return result.toUIMessageStreamResponse({
          sendSources: true,
        });
      }
      ```
      
      ## Features
      
      - Collapsible component that allows a user to view the sources or citations used to generate a response
      - Customizable trigger and content components
      - Support for custom sources or citations
      - Responsive design with mobile-friendly controls
      - Clean, modern styling with customizable themes
      
      ## Examples
      
      ### Custom rendering
      
      See `scripts/sources-custom.tsx` for this example.
      
      ## Props
      
      ### `<Sources />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the root div. |
      
      ### `<SourcesTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `count` | `number` | Required | The number of sources to display in the trigger. |
      | `...props` | `React.ComponentProps<typeof CollapsibleTrigger>` | - | Any other props are spread to the CollapsibleTrigger component. |
      
      ### `<SourcesContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the content container. |
      
      ### `<Source />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.AnchorHTMLAttributes<HTMLAnchorElement>` | - | Any other props are spread to the anchor element. |
      
    • speech-input.md 6.5 KB
      # Speech Input
      
      A button component that captures voice input and converts it to text, with cross-browser support.
      
      The `SpeechInput` component provides an easy-to-use interface for capturing voice input in your application. It uses the Web Speech API for real-time transcription in supported browsers (Chrome, Edge), and falls back to MediaRecorder with an external transcription service for browsers that don't support Web Speech API (Firefox, Safari).
      
      See `scripts/speech-input.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add speech-input
      ```
      
      ## Features
      
      - Built on Web Speech API (SpeechRecognition) with MediaRecorder fallback
      - Cross-browser support (Chrome, Edge, Firefox, Safari)
      - Continuous speech recognition with interim results
      - Visual feedback with pulse animation when listening
      - Loading state during transcription processing
      - Automatic browser compatibility detection
      - Final transcript extraction and callbacks
      - Error handling and automatic state management
      - Extends shadcn/ui Button component
      - Full TypeScript support
      
      ## Props
      
      ### `<SpeechInput />`
      
      The component extends the shadcn/ui Button component, so all Button props are available.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `onTranscriptionChange` | `(text: string) => void` | - | Callback fired when final transcription text is available. Only fires for completed phrases, not interim results. |
      | `onAudioRecorded` | `(audioBlob: Blob) => Promise<string>` | - | Callback for MediaRecorder fallback. Required for Firefox/Safari support. Receives recorded audio blob and should return transcribed text from an external service (e.g., OpenAI Whisper). |
      | `lang` | `string` | - | Language for speech recognition. |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the Button component, including variant, size, disabled, etc. |
      
      ## Behavior
      
      ### Speech Recognition Modes
      
      The component automatically detects browser capabilities and uses the best available method:
      
      | Browser         | Mode           | Behavior                                               |
      | --------------- | -------------- | ------------------------------------------------------ |
      | Chrome, Edge    | Web Speech API | Real-time transcription, no server required            |
      | Firefox, Safari | MediaRecorder  | Records audio, sends to external transcription service |
      | Unsupported     | Disabled       | Button is disabled                                     |
      
      ### Web Speech API Mode (Chrome, Edge)
      
      Uses the Web Speech API with the following configuration:
      
      - **Continuous**: Set to `true` to keep recognition active until manually stopped
      - **Interim Results**: Set to `true` to receive partial results during speech
      - **Language**: Configurable via `lang` prop, defaults to `"en-US"`
      
      ### MediaRecorder Mode (Firefox, Safari)
      
      When the Web Speech API is unavailable, the component falls back to recording audio:
      
      1. Records audio using `MediaRecorder` API
      2. On stop, creates an audio blob (`audio/webm`)
      3. Calls `onAudioRecorded` with the blob
      4. Waits for transcription result
      5. Passes result to `onTranscriptionChange`
      
      **Note**: The `onAudioRecorded` prop is required for this mode to work. Without it, the button will be disabled in Firefox/Safari.
      
      ### Transcription Processing
      
      The component only calls `onTranscriptionChange` with **final transcripts**. Interim results (Web Speech API) are ignored to prevent incomplete text from being processed.
      
      ### Visual States
      
      - **Default State**: Standard button appearance with microphone icon
      - **Listening State**: Pulsing animation with accent colors to indicate active listening
      - **Processing State**: Loading spinner while waiting for transcription (MediaRecorder mode)
      - **Disabled State**: Button is disabled when no API is available or required props are missing
      
      ### Lifecycle
      
      1. **Mount**: Detects available APIs and initializes appropriate mode
      2. **Click**: Toggles between listening/recording and stopped states
      3. **Stop (MediaRecorder)**: Processes audio and waits for transcription
      4. **Unmount**: Stops recognition/recording and releases microphone
      
      ## Browser Support
      
      The component provides cross-browser support through a two-tier system:
      
      | Browser | API Used       | Requirements           |
      | ------- | -------------- | ---------------------- |
      | Chrome  | Web Speech API | None                   |
      | Edge    | Web Speech API | None                   |
      | Firefox | MediaRecorder  | `onAudioRecorded` prop |
      | Safari  | MediaRecorder  | `onAudioRecorded` prop |
      
      For full cross-browser support, provide the `onAudioRecorded` callback that sends audio to a transcription service like OpenAI Whisper, Google Cloud Speech-to-Text, or AssemblyAI.
      
      ## Accessibility
      
      - Uses semantic button element via shadcn/ui Button
      - Visual feedback for listening state
      - Keyboard accessible (can be triggered with Space/Enter)
      - Screen reader friendly with proper button semantics
      
      ## Usage with MediaRecorder Fallback
      
      To support Firefox and Safari, provide an `onAudioRecorded` callback that sends audio to a transcription service:
      
      ```tsx
      const handleAudioRecorded = async (audioBlob: Blob): Promise<string> => {
        const formData = new FormData();
        formData.append("file", audioBlob, "audio.webm");
        formData.append("model", "whisper-1");
      
        const response = await fetch(
          "https://api.openai.com/v1/audio/transcriptions",
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
            },
            body: formData,
          }
        );
      
        const data = await response.json();
        return data.text;
      };
      
      <SpeechInput
        onTranscriptionChange={(text) => console.log(text)}
        onAudioRecorded={handleAudioRecorded}
      />;
      ```
      
      ## Notes
      
      - Requires a secure context (HTTPS or localhost)
      - Browser may prompt user for microphone permission
      - Only final transcripts trigger the `onTranscriptionChange` callback
      - Language is configurable via the `lang` prop
      - Continuous recognition continues until button is clicked again
      - Errors are logged to console and automatically stop recognition/recording
      - MediaRecorder fallback requires the `onAudioRecorded` prop to be provided
      - Audio is recorded in `audio/webm` format for the MediaRecorder fallback
      
      ## TypeScript
      
      The component includes full TypeScript definitions for the Web Speech API:
      
      - `SpeechRecognition`
      - `SpeechRecognitionEvent`
      - `SpeechRecognitionResult`
      - `SpeechRecognitionAlternative`
      - `SpeechRecognitionErrorEvent`
      
      These types are properly declared for both standard and webkit-prefixed implementations.
      
    • stack-trace.md 7.9 KB
      # Stack Trace
      
      Displays formatted JavaScript/Node.js error stack traces with syntax highlighting and collapsible frames.
      
      The `StackTrace` component displays formatted JavaScript/Node.js error stack traces with clickable file paths, internal frame dimming, and collapsible content.
      
      See `scripts/stack-trace.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add stack-trace
      ```
      
      ## Usage with AI SDK
      
      Build an error display tool that shows stack traces from AI-generated code using the [`useChat`](https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat) hook.
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { useChat } from "@ai-sdk/react";
      import {
        StackTrace,
        StackTraceHeader,
        StackTraceError,
        StackTraceErrorType,
        StackTraceErrorMessage,
        StackTraceActions,
        StackTraceCopyButton,
        StackTraceExpandButton,
        StackTraceContent,
        StackTraceFrames,
      } from "@/components/ai-elements/stack-trace";
      
      export default function Page() {
        const { messages } = useChat({
          api: "/api/run-code",
        });
      
        return (
          <div className="max-w-4xl mx-auto p-6">
            {messages.map((message) => {
              const toolInvocations = message.parts?.filter(
                (part) => part.type === "tool-invocation"
              );
      
              return toolInvocations?.map((tool) => {
                if (tool.toolName === "runCode" && tool.result?.error) {
                  return (
                    <StackTrace
                      key={tool.toolCallId}
                      trace={tool.result.error}
                      defaultOpen
                    >
                      <StackTraceHeader>
                        <StackTraceError>
                          <StackTraceErrorType />
                          <StackTraceErrorMessage />
                        </StackTraceError>
                        <StackTraceActions>
                          <StackTraceCopyButton />
                          <StackTraceExpandButton />
                        </StackTraceActions>
                      </StackTraceHeader>
                      <StackTraceContent>
                        <StackTraceFrames />
                      </StackTraceContent>
                    </StackTrace>
                  );
                }
                return null;
              });
            })}
          </div>
        );
      }
      ```
      
      Add the following route to your backend:
      
      ```tsx title="api/run-code/route.ts"
      import { streamText, tool } from "ai";
      import { z } from "zod";
      
      export async function POST(req: Request) {
        const { messages } = await req.json();
      
        const result = streamText({
          model: "openai/gpt-4o",
          messages,
          tools: {
            runCode: tool({
              description: "Execute JavaScript code and return any errors",
              parameters: z.object({
                code: z.string(),
              }),
              execute: async ({ code }) => {
                try {
                  // Execute code in sandbox
                  eval(code);
                  return { success: true };
                } catch (error) {
                  return { error: (error as Error).stack };
                }
              },
            }),
          },
        });
      
        return result.toDataStreamResponse();
      }
      ```
      
      ## Features
      
      - Parses standard JavaScript/Node.js stack trace format
      - Highlights error type in red
      - Dims internal frames (node_modules, node: paths)
      - Collapsible content with smooth animation
      - Copy full stack trace to clipboard
      - Clickable file paths with line/column numbers
      
      ## Examples
      
      ### Collapsed by Default
      
      See `scripts/stack-trace-collapsed.tsx` for this example.
      
      ### Hide Internal Frames
      
      See `scripts/stack-trace-no-internal.tsx` for this example.
      
      ## Props
      
      ### `<StackTrace />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `trace` | `string` | - | The raw stack trace string to parse and display. |
      | `open` | `boolean` | - | Controlled open state. |
      | `defaultOpen` | `boolean` | `false` | Whether the content is expanded by default. |
      | `onOpenChange` | `(open: boolean) => void` | - | Callback when open state changes. |
      | `onFilePathClick` | `(path: string, line?: number, column?: number) => void` | - | Callback when a file path is clicked. Receives the file path, line number, and column number. |
      | `children` | `React.ReactNode` | - | Child elements (StackTraceHeader, StackTraceContent, etc.). |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the root div. |
      
      ### `<StackTraceHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Header content (typically StackTraceError and StackTraceActions). |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.ComponentProps<typeof CollapsibleTrigger>` | - | Any other props are spread to the CollapsibleTrigger. |
      
      ### `<StackTraceError />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Error content (typically StackTraceErrorType and StackTraceErrorMessage). |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the container div. |
      
      ### `<StackTraceErrorType />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom content. Defaults to the parsed error type (e.g.,  |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Any other props are spread to the span element. |
      
      ### `<StackTraceErrorMessage />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Custom content. Defaults to the parsed error message. |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Any other props are spread to the span element. |
      
      ### `<StackTraceActions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `React.ReactNode` | - | Action buttons (typically StackTraceCopyButton and StackTraceExpandButton). |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the container div. |
      
      ### `<StackTraceCopyButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `onCopy` | `() => void` | - | Callback fired after a successful copy. |
      | `onError` | `(error: Error) => void` | - | Callback fired if copying fails. |
      | `timeout` | `number` | `2000` | How long to show the copied state (ms). |
      | `children` | `React.ReactNode` | - | Custom content for the button. Defaults to copy/check icons. |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `<StackTraceExpandButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the container div. |
      
      ### `<StackTraceContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `maxHeight` | `number` | `400` | Maximum height of the content area. Enables scrolling when content exceeds this height. |
      | `children` | `React.ReactNode` | - | Content to display (typically StackTraceFrames). |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.ComponentProps<typeof CollapsibleContent>` | - | Any other props are spread to the CollapsibleContent. |
      
      ### `<StackTraceFrames />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `showInternalFrames` | `boolean` | `true` | Whether to show internal frames (node_modules, node: paths). |
      | `className` | `string` | - | Additional CSS classes. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the container div. |
      
    • suggestion.md 3.6 KB
      # Suggestion
      
      A suggestion component that displays a horizontal row of clickable suggestions for user interaction.
      
      The `Suggestion` component displays a horizontal row of clickable suggestions for user interaction.
      
      See `scripts/suggestion.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add suggestion
      ```
      
      ## Usage with AI SDK
      
      Build a simple input with suggestions users can click to send a message to the LLM.
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import {
        PromptInput,
        type PromptInputMessage,
        PromptInputTextarea,
        PromptInputSubmit,
      } from "@/components/ai-elements/prompt-input";
      import { Suggestion, Suggestions } from "@/components/ai-elements/suggestion";
      import { useState } from "react";
      import { useChat } from "@ai-sdk/react";
      
      const suggestions = [
        "Can you explain how to play tennis?",
        "What is the weather in Tokyo?",
        "How do I make a really good fish taco?",
      ];
      
      const SuggestionDemo = () => {
        const [input, setInput] = useState("");
        const { sendMessage, status } = useChat();
      
        const handleSubmit = (message: PromptInputMessage) => {
          if (message.text.trim()) {
            sendMessage({ text: message.text });
            setInput("");
          }
        };
      
        const handleSuggestionClick = (suggestion: string) => {
          sendMessage({ text: suggestion });
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <div className="flex flex-col gap-4">
                <Suggestions>
                  {suggestions.map((suggestion) => (
                    <Suggestion
                      key={suggestion}
                      onClick={handleSuggestionClick}
                      suggestion={suggestion}
                    />
                  ))}
                </Suggestions>
                <PromptInput
                  onSubmit={handleSubmit}
                  className="mt-4 w-full max-w-2xl mx-auto relative"
                >
                  <PromptInputTextarea
                    value={input}
                    placeholder="Say something..."
                    onChange={(e) => setInput(e.currentTarget.value)}
                    className="pr-12"
                  />
                  <PromptInputSubmit
                    status={status === "streaming" ? "streaming" : "ready"}
                    disabled={!input.trim()}
                    className="absolute bottom-1 right-1"
                  />
                </PromptInput>
              </div>
            </div>
          </div>
        );
      };
      
      export default SuggestionDemo;
      ```
      
      ## Features
      
      - Horizontal row of clickable suggestion buttons
      - Customizable styling with variant and size options
      - Flexible layout that wraps suggestions on smaller screens
      - onClick callback that emits the selected suggestion string
      - Support for both individual suggestions and suggestion lists
      - Clean, modern styling with hover effects
      - Responsive design with mobile-friendly touch targets
      - TypeScript support with proper type definitions
      
      ## Examples
      
      ### Usage with AI Input
      
      See `scripts/suggestion-input.tsx` for this example.
      
      ## Props
      
      ### `<Suggestions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof ScrollArea>` | - | Any other props are spread to the underlying ScrollArea component. |
      
      ### `<Suggestion />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `suggestion` | `string` | Required | The suggestion string to display and emit on click. |
      | `onClick` | `(suggestion: string) => void` | - | Callback fired when the suggestion is clicked. |
      | `...props` | `Omit<React.ComponentProps<typeof Button>, ` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
    • task.md 6.7 KB
      # Task
      
      A collapsible task list component for displaying AI workflow progress, with status indicators and optional descriptions.
      
      The `Task` component provides a structured way to display task lists or workflow progress with collapsible details, status indicators, and progress tracking. It consists of a main `Task` container with `TaskTrigger` for the clickable header and `TaskContent` for the collapsible content area.
      
      See `scripts/task.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add task
      ```
      
      ## Usage with AI SDK
      
      Build a mock async programming agent using [`experimental_generateObject`](/docs/reference/ai-sdk-ui/use-object).
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { experimental_useObject as useObject } from "@ai-sdk/react";
      import {
        Task,
        TaskItem,
        TaskItemFile,
        TaskTrigger,
        TaskContent,
      } from "@/components/ai-elements/task";
      import { Button } from "@/components/ui/button";
      import { tasksSchema } from "@/app/api/task/route";
      import {
        SiReact,
        SiTypescript,
        SiJavascript,
        SiCss,
        SiHtml5,
        SiJson,
        SiMarkdown,
      } from "@icons-pack/react-simple-icons";
      
      const iconMap = {
        react: { component: SiReact, color: "#149ECA" },
        typescript: { component: SiTypescript, color: "#3178C6" },
        javascript: { component: SiJavascript, color: "#F7DF1E" },
        css: { component: SiCss, color: "#1572B6" },
        html: { component: SiHtml5, color: "#E34F26" },
        json: { component: SiJson, color: "#000000" },
        markdown: { component: SiMarkdown, color: "#000000" },
      };
      
      const TaskDemo = () => {
        const { object, submit, isLoading } = useObject({
          api: "/api/agent",
          schema: tasksSchema,
        });
      
        const handleSubmit = (taskType: string) => {
          submit({ prompt: taskType });
        };
      
        const renderTaskItem = (item: any, index: number) => {
          if (item?.type === "file" && item.file) {
            const iconInfo = iconMap[item.file.icon as keyof typeof iconMap];
            if (iconInfo) {
              const IconComponent = iconInfo.component;
              return (
                <span className="inline-flex items-center gap-1" key={index}>
                  {item.text}
                  <TaskItemFile>
                    <IconComponent
                      color={item.file.color || iconInfo.color}
                      className="size-4"
                    />
                    <span>{item.file.name}</span>
                  </TaskItemFile>
                </span>
              );
            }
          }
          return item?.text || "";
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <div className="flex gap-2 mb-6 flex-wrap">
                <Button
                  onClick={() => handleSubmit("React component development")}
                  disabled={isLoading}
                  variant="outline"
                >
                  React Development
                </Button>
              </div>
      
              <div className="flex-1 overflow-auto space-y-4">
                {isLoading && !object && (
                  <div className="text-muted-foreground">Generating tasks...</div>
                )}
      
                {object?.tasks?.map((task: any, taskIndex: number) => (
                  <Task key={taskIndex} defaultOpen={taskIndex === 0}>
                    <TaskTrigger title={task.title || "Loading..."} />
                    <TaskContent>
                      {task.items?.map((item: any, itemIndex: number) => (
                        <TaskItem key={itemIndex}>
                          {renderTaskItem(item, itemIndex)}
                        </TaskItem>
                      ))}
                    </TaskContent>
                  </Task>
                ))}
              </div>
            </div>
          </div>
        );
      };
      
      export default TaskDemo;
      ```
      
      Add the following route to your backend:
      
      ```ts title="app/api/agent.ts"
      import { streamObject } from "ai";
      import { z } from "zod";
      
      export const taskItemSchema = z.object({
        type: z.enum(["text", "file"]),
        text: z.string(),
        file: z
          .object({
            name: z.string(),
            icon: z.string(),
            color: z.string().optional(),
          })
          .optional(),
      });
      
      export const taskSchema = z.object({
        title: z.string(),
        items: z.array(taskItemSchema),
        status: z.enum(["pending", "in_progress", "completed"]),
      });
      
      export const tasksSchema = z.object({
        tasks: z.array(taskSchema),
      });
      
      // Allow streaming responses up to 30 seconds
      export const maxDuration = 30;
      
      export async function POST(req: Request) {
        const { prompt } = await req.json();
      
        const result = streamObject({
          model: "openai/gpt-4o",
          schema: tasksSchema,
          prompt: `You are an AI assistant that generates realistic development task workflows. Generate a set of tasks that would occur during ${prompt}.
      
          Each task should have:
          - A descriptive title
          - Multiple task items showing the progression
          - Some items should be plain text, others should reference files
          - Use realistic file names and appropriate file types
          - Status should progress from pending to in_progress to completed
      
          For file items, use these icon types: 'react', 'typescript', 'javascript', 'css', 'html', 'json', 'markdown'
      
          Generate 3-4 tasks total, with 4-6 items each.`,
        });
      
        return result.toTextStreamResponse();
      }
      ```
      
      ## Features
      
      - Visual icons for pending, in-progress, completed, and error states
      - Expandable content for task descriptions and additional information
      - Built-in progress counter showing completed vs total tasks
      - Optional progressive reveal of tasks with customizable timing
      - Support for custom content within task items
      - Full type safety with proper TypeScript definitions
      - Keyboard navigation and screen reader support
      
      ## Props
      
      ### `<Task />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `defaultOpen` | `boolean` | `true` | Whether the task is open by default. |
      | `...props` | `React.ComponentProps<typeof Collapsible>` | - | Any other props are spread to the root Collapsible component. |
      
      ### `<TaskTrigger />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `title` | `string` | Required | The title of the task that will be displayed in the trigger. |
      | `...props` | `React.ComponentProps<typeof CollapsibleTrigger>` | - | Any other props are spread to the CollapsibleTrigger component. |
      
      ### `<TaskContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleContent>` | - | Any other props are spread to the CollapsibleContent component. |
      
      ### `<TaskItem />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div. |
      
      ### `<TaskItemFile />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div. |
      
    • terminal.md 3.1 KB
      # Terminal
      
      Display streaming console output with full ANSI color support.
      
      The `Terminal` component displays console output with ANSI color support, streaming indicators, and auto-scroll functionality.
      
      See `scripts/terminal.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add terminal
      ```
      
      ## Features
      
      - Full ANSI color support (256 colors, bold, italic, underline)
      - Streaming mode with cursor animation
      - Auto-scroll to latest output
      - Copy output to clipboard
      - Clear button support
      - Dark terminal theme
      
      ## ANSI Support
      
      The Terminal uses `ansi-to-react` to parse ANSI escape codes:
      
      ```bash
      \x1b[32m✓\x1b[0m Success    # Green checkmark
      \x1b[31m✗\x1b[0m Error      # Red X
      \x1b[33mwarn\x1b[0m Warning   # Yellow text
      \x1b[1mBold\x1b[0m           # Bold text
      ```
      
      ## Examples
      
      ### Basic Usage
      
      See `scripts/terminal-basic.tsx` for this example.
      
      ### Streaming Mode
      
      See `scripts/terminal-streaming.tsx` for this example.
      
      ### With Clear Button
      
      See `scripts/terminal-clear.tsx` for this example.
      
      ## Props
      
      ### `<Terminal />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `output` | `string` | - | Terminal output text (supports ANSI codes). |
      | `isStreaming` | `boolean` | `false` | Show streaming indicator. |
      | `autoScroll` | `boolean` | `true` | Auto-scroll to bottom on new output. |
      | `onClear` | `() => void` | - | Callback to clear output (enables clear button). |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<TerminalCopyButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `onCopy` | `() => void` | - | Callback after successful copy. |
      | `onError` | `(error: Error) => void` | - | Callback if copying fails. |
      | `timeout` | `number` | `2000` | Duration to show copied state (ms). |
      
      ### `<TerminalHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TerminalTitle />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TerminalStatus />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TerminalActions />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TerminalClearButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the Button component. |
      
      ### `<TerminalContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
    • test-results.md 5 KB
      # Test Results
      
      Display test suite results with pass/fail/skip status and error details.
      
      The `TestResults` component displays test suite results including summary statistics, progress, individual tests, and error details.
      
      See `scripts/test-results.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add test-results
      ```
      
      ## Features
      
      - Summary statistics (passed/failed/skipped)
      - Progress bar visualization
      - Collapsible test suites
      - Individual test status and duration
      - Error messages with stack traces
      - Color-coded status indicators
      
      ## Status Colors
      
      | Status    | Color           | Use Case         |
      | --------- | --------------- | ---------------- |
      | `passed`  | Green           | Test succeeded   |
      | `failed`  | Red             | Test failed      |
      | `skipped` | Yellow          | Test skipped     |
      | `running` | Blue (animated) | Test in progress |
      
      ## Examples
      
      ### Basic Usage
      
      See `scripts/test-results-basic.tsx` for this example.
      
      ### With Test Suites
      
      See `scripts/test-results-suites.tsx` for this example.
      
      ### With Error Details
      
      See `scripts/test-results-errors.tsx` for this example.
      
      ## Props
      
      ### `<TestResults />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `summary` | `unknown` | - | Test results summary. |
      | `className` | `string` | - | Additional CSS classes. |
      
      ### `<TestSuite />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `name` | `string` | - | Suite name. |
      | `status` | `unknown` | - | Overall suite status. |
      | `defaultOpen` | `boolean` | - | Initially expanded. |
      
      ### `<Test />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `name` | `string` | - | Test name. |
      | `status` | `unknown` | - | Test status. |
      | `duration` | `number` | - | Test duration in ms. |
      
      ### `<TestResultsHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TestResultsSummary />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TestResultsDuration />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Any other props are spread to the span element. |
      
      ### `<TestResultsProgress />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TestResultsContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TestSuiteName />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleTrigger>` | - | Any other props are spread to the CollapsibleTrigger component. |
      
      ### `<TestSuiteStats />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `passed` | `number` | `0` | Number of passed tests. |
      | `failed` | `number` | `0` | Number of failed tests. |
      | `skipped` | `number` | `0` | Number of skipped tests. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TestSuiteContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleContent>` | - | Any other props are spread to the CollapsibleContent component. |
      
      ### `<TestStatus />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Any other props are spread to the span element. |
      
      ### `<TestName />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Any other props are spread to the span element. |
      
      ### `<TestDuration />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLSpanElement>` | - | Any other props are spread to the span element. |
      
      ### `<TestError />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the div element. |
      
      ### `<TestErrorMessage />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLParagraphElement>` | - | Any other props are spread to the p element. |
      
      ### `<TestErrorStack />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLPreElement>` | - | Any other props are spread to the pre element. |
      
    • tool.md 8.5 KB
      # Tool
      
      A collapsible component for displaying tool invocation details in AI chatbot interfaces.
      
      The `Tool` component displays a collapsible interface for showing/hiding tool details. It is designed to take the `ToolUIPart` type from the AI SDK and display it in a collapsible interface.
      
      See `scripts/tool.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add tool
      ```
      
      ## Usage in AI SDK
      
      Build a simple stateful weather app that renders the last message in a tool using [`useChat`](/docs/reference/ai-sdk-ui/use-chat).
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import { useChat } from "@ai-sdk/react";
      import { DefaultChatTransport, type ToolUIPart } from "ai";
      import { Button } from "@/components/ui/button";
      import { MessageResponse } from "@/components/ai-elements/message";
      import {
        Tool,
        ToolContent,
        ToolHeader,
        ToolInput,
        ToolOutput,
      } from "@/components/ai-elements/tool";
      
      type WeatherToolInput = {
        location: string;
        units: "celsius" | "fahrenheit";
      };
      
      type WeatherToolOutput = {
        location: string;
        temperature: string;
        conditions: string;
        humidity: string;
        windSpeed: string;
        lastUpdated: string;
      };
      
      type WeatherToolUIPart = ToolUIPart<{
        fetch_weather_data: {
          input: WeatherToolInput;
          output: WeatherToolOutput;
        };
      }>;
      
      const Example = () => {
        const { messages, sendMessage, status } = useChat({
          transport: new DefaultChatTransport({
            api: "/api/weather",
          }),
        });
      
        const handleWeatherClick = () => {
          sendMessage({ text: "Get weather data for San Francisco in fahrenheit" });
        };
      
        const latestMessage = messages[messages.length - 1];
        const weatherTool = latestMessage?.parts?.find(
          (part) => part.type === "tool-fetch_weather_data"
        ) as WeatherToolUIPart | undefined;
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <div className="space-y-4">
                <Button onClick={handleWeatherClick} disabled={status !== "ready"}>
                  Get Weather for San Francisco
                </Button>
      
                {weatherTool && (
                  <Tool defaultOpen={true}>
                    <ToolHeader
                      type="tool-fetch_weather_data"
                      state={weatherTool.state}
                    />
                    <ToolContent>
                      <ToolInput input={weatherTool.input} />
                      <ToolOutput
                        output={
                          <MessageResponse>
                            {formatWeatherResult(weatherTool.output)}
                          </MessageResponse>
                        }
                        errorText={weatherTool.errorText}
                      />
                    </ToolContent>
                  </Tool>
                )}
              </div>
            </div>
          </div>
        );
      };
      
      function formatWeatherResult(result: WeatherToolOutput): string {
        return `**Weather for ${result.location}**
      
      **Temperature:** ${result.temperature}  
      **Conditions:** ${result.conditions}  
      **Humidity:** ${result.humidity}  
      **Wind Speed:** ${result.windSpeed}  
      
      *Last updated: ${result.lastUpdated}*`;
      }
      
      export default Example;
      ```
      
      Add the following route to your backend:
      
      ```ts title="app/api/weather/route.tsx"
      import { streamText, UIMessage, convertToModelMessages } from "ai";
      import { z } from "zod";
      
      // Allow streaming responses up to 30 seconds
      export const maxDuration = 30;
      
      export async function POST(req: Request) {
        const { messages }: { messages: UIMessage[] } = await req.json();
      
        const result = streamText({
          model: "openai/gpt-4o",
          messages: await convertToModelMessages(messages),
          tools: {
            fetch_weather_data: {
              description: "Fetch weather information for a specific location",
              parameters: z.object({
                location: z
                  .string()
                  .describe("The city or location to get weather for"),
                units: z
                  .enum(["celsius", "fahrenheit"])
                  .default("celsius")
                  .describe("Temperature units"),
              }),
              inputSchema: z.object({
                location: z.string(),
                units: z.enum(["celsius", "fahrenheit"]).default("celsius"),
              }),
              execute: async ({ location, units }) => {
                await new Promise((resolve) => setTimeout(resolve, 1500));
      
                const temp =
                  units === "celsius"
                    ? Math.floor(Math.random() * 35) + 5
                    : Math.floor(Math.random() * 63) + 41;
      
                return {
                  location,
                  temperature: `${temp}°${units === "celsius" ? "C" : "F"}`,
                  conditions: "Sunny",
                  humidity: `12%`,
                  windSpeed: `35 ${units === "celsius" ? "km/h" : "mph"}`,
                  lastUpdated: new Date().toLocaleString(),
                };
              },
            },
          },
        });
      
        return result.toUIMessageStreamResponse();
      }
      ```
      
      ## Features
      
      - Collapsible interface for showing/hiding tool details
      - Visual status indicators with icons and badges
      - Support for multiple tool execution states (pending, running, completed, error)
      - Formatted parameter display with JSON syntax highlighting
      - Result and error handling with appropriate styling
      - Composable structure for flexible layouts
      - Accessible keyboard navigation and screen reader support
      - Consistent styling that matches your design system
      - Auto-opens completed tools by default for better UX
      
      ## Examples
      
      ### Input Streaming (Pending)
      
      Shows a tool in its initial state while parameters are being processed.
      
      See `scripts/tool-input-streaming.tsx` for this example.
      
      ### Input Available (Running)
      
      Shows a tool that's actively executing with its parameters.
      
      See `scripts/tool-input-available.tsx` for this example.
      
      ### Output Available (Completed)
      
      Shows a completed tool with successful results. Opens by default to show the results. In this instance, the output is a JSON object, so we can use the `CodeBlock` component to display it.
      
      See `scripts/tool-output-available.tsx` for this example.
      
      ### Output Error
      
      Shows a tool that encountered an error during execution. Opens by default to display the error.
      
      See `scripts/tool-output-error.tsx` for this example.
      
      ## Props
      
      ### `<Tool />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Collapsible>` | - | Any other props are spread to the root Collapsible component. |
      
      ### `<ToolHeader />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `title` | `string` | - | Custom title to display instead of the derived tool name. |
      | `type` | `ToolUIPart[` | Required | The type/name of the tool. |
      | `state` | `ToolUIPart[` | Required | The current state of the tool (input-streaming, input-available, output-available, or output-error). |
      | `toolName` | `string` | - | Required when type is  |
      | `className` | `string` | - | Additional CSS classes to apply to the header. |
      | `...props` | `React.ComponentProps<typeof CollapsibleTrigger>` | - | Any other props are spread to the CollapsibleTrigger. |
      
      ### `<ToolContent />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CollapsibleContent>` | - | Any other props are spread to the CollapsibleContent. |
      
      ### `<ToolInput />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `input` | `ToolUIPart[` | - | The input parameters passed to the tool, displayed as formatted JSON. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div. |
      
      ### `<ToolOutput />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `output` | `React.ReactNode` | - | The output/result of the tool execution. |
      | `errorText` | `ToolUIPart[` | - | An error message if the tool execution failed. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the underlying div. |
      
      ## Type Exports
      
      ### `ToolPart`
      
      Union type representing both static and dynamic tool UI parts.
      
      ```tsx
      type ToolPart = ToolUIPart | DynamicToolUIPart;
      ```
      
      ## Utilities
      
      ### `getStatusBadge`
      
      Returns a Badge component with icon and label based on tool state.
      
      ```tsx
      import { getStatusBadge } from "@/components/ai-elements/tool";
      
      // Returns a Badge with appropriate icon and label
      const badge = getStatusBadge("output-available");
      ```
      
      Supported states:
      
      - `input-streaming` - "Pending"
      - `input-available` - "Running"
      - `approval-requested` - "Awaiting Approval"
      - `approval-responded` - "Responded"
      - `output-available` - "Completed"
      - `output-error` - "Error"
      - `output-denied` - "Denied"
      
    • toolbar.md 983 B
      # Toolbar
      
      A styled toolbar component for React Flow nodes with flexible positioning and custom actions.
      
      The `Toolbar` component provides a positioned toolbar that attaches to nodes in React Flow canvases. It features modern card styling with backdrop blur and flexbox layout for action buttons and controls.
      
      
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add toolbar
      ```
      
      ## Features
      
      - Attaches to any React Flow node
      - Bottom positioning by default
      - Rounded card design with border
      - Theme-aware background styling
      - Flexbox layout with gap spacing
      - Full TypeScript support
      - Compatible with all React Flow NodeToolbar features
      
      ## Props
      
      ### `<Toolbar />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply to the toolbar. |
      | `...props` | `ComponentProps<typeof NodeToolbar>` | - | Any other props from @xyflow/react NodeToolbar component (position, offset, isVisible, etc.). |
      
    • transcription.md 4.9 KB
      # Transcription
      
      A composable component for displaying interactive, synchronized transcripts from AI SDK transcribe() results with click-to-seek functionality.
      
      The `Transcription` component provides a flexible render props interface for displaying audio transcripts with synchronized playback. It automatically highlights the current segment based on playback time and supports click-to-seek functionality for interactive navigation.
      
      See `scripts/transcription.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add transcription
      ```
      
      ## Features
      
      - Render props pattern for maximum flexibility
      - Automatic segment highlighting based on current time
      - Click-to-seek functionality for interactive navigation
      - Controlled and uncontrolled component patterns
      - Automatic filtering of empty segments
      - Visual state indicators (active, past, future)
      - Built on Radix UI's `useControllableState` for flexible state management
      - Full TypeScript support with AI SDK transcription types
      
      ## Props
      
      ### `<Transcription />`
      
      Root component that provides context and manages transcript state. Uses render props pattern for rendering segments.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `segments` | `TranscriptionSegment[]` | - | Array of transcription segments from AI SDK transcribe() function. |
      | `currentTime` | `number` | `0` | Current playback time in seconds (controlled). |
      | `onSeek` | `(time: number) => void` | - | Callback fired when a segment is clicked or when currentTime changes. |
      | `children` | `(segment: TranscriptionSegment, index: number) => ReactNode` | - | Render function that receives each segment and its index. |
      | `...props` | `Omit<React.ComponentProps<` | - | Any other props are spread to the root div element. |
      
      ### `<TranscriptionSegment />`
      
      Individual segment button with automatic state styling and click-to-seek functionality.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `segment` | `TranscriptionSegment` | - | The transcription segment data. |
      | `index` | `number` | - | The segment index. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the button element. |
      
      ## Behavior
      
      ### Render Props Pattern
      
      The component uses a render props pattern where the `children` prop is a function that receives each segment and its index. This provides maximum flexibility for custom rendering while still benefiting from automatic state management and context.
      
      ### Segment Highlighting
      
      Segments are automatically styled based on their relationship to the current playback time:
      
      - **Active** (`isActive`): When `currentTime` is within the segment's time range. Styled with primary color.
      - **Past** (`isPast`): When `currentTime` is after the segment's end time. Styled with muted foreground.
      - **Future**: When `currentTime` is before the segment's start time. Styled with dimmed muted foreground.
      
      ### Click-to-Seek
      
      When `onSeek` is provided, segments become interactive buttons. Clicking a segment calls `onSeek` with the segment's start time, allowing your audio/video player to seek to that position.
      
      ### Empty Segment Filtering
      
      The component automatically filters out segments with empty or whitespace-only text to avoid rendering unnecessary elements.
      
      ### State Management
      
      Uses Radix UI's `useControllableState` hook to support both controlled and uncontrolled patterns. When `currentTime` is provided, the component operates in controlled mode. Otherwise, it maintains its own internal state.
      
      ## Data Format
      
      The component expects segments from the AI SDK `transcribe()` function:
      
      ```ts
      type TranscriptionSegment = {
        text: string;
        startSecond: number;
        endSecond: number;
      };
      ```
      
      ## Styling
      
      The component uses data attributes for custom styling:
      
      - `data-slot="transcription"`: Root container
      - `data-slot="transcription-segment"`: Individual segment button
      - `data-active`: Present on the currently playing segment
      - `data-index`: The segment's index in the array
      
      Default segment appearance:
      
      - Active segment: `text-primary` (primary brand color)
      - Past segments: `text-muted-foreground`
      - Future segments: `text-muted-foreground/60` (dimmed)
      - Interactive segments: `cursor-pointer hover:text-foreground`
      - Non-interactive segments: `cursor-default`
      
      ## Accessibility
      
      - Uses semantic `<button>` elements for interactive segments
      - Full keyboard navigation support
      - Proper button semantics for screen readers
      - `data-active` attribute for assistive technology
      - Hover and focus states for keyboard users
      
      ## Notes
      
      - Empty or whitespace-only segments are automatically filtered out
      - The component uses `flex-wrap` for responsive text flow
      - Segments maintain inline layout with `gap-1` spacing
      - `text-sm` and `leading-relaxed` provide comfortable reading
      - Click events on segments still fire the `onClick` handler if provided
      - The `onSeek` callback is called both when segments are clicked and when controlled `currentTime` changes
      
    • voice-selector.md 10.3 KB
      # Voice Selector
      
      A composable dialog component for selecting AI voices with metadata display and search functionality.
      
      The `VoiceSelector` component provides a flexible and composable interface for selecting AI voices. Built on shadcn/ui's Dialog and Command components, it features a searchable voice list with support for metadata display (gender, accent, age), grouping, and customizable layouts. The component includes a context provider for accessing voice selection state from any nested component.
      
      See `scripts/voice-selector.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add voice-selector
      ```
      
      ## Features
      
      - Fully composable architecture with granular control components
      - Built on shadcn/ui Dialog and Command components
      - React Context API for accessing state in nested components
      - Searchable voice list with real-time filtering
      - Support for voice metadata with icons and emojis (gender icons, accent flags, age)
      - Voice preview button with play/pause/loading states
      - Voice grouping with separators and bullet dividers
      - Keyboard navigation support
      - Controlled and uncontrolled component patterns
      - Full TypeScript support with proper types for all components
      
      ## Props
      
      ### `<VoiceSelector />`
      
      Root Dialog component that provides context for all child components. Manages both voice selection and dialog open states.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `value` | `string` | - | The selected voice ID (controlled). |
      | `defaultValue` | `string` | - | The default selected voice ID (uncontrolled). |
      | `onValueChange` | `(value: string | undefined) => void` | - | Callback fired when the selected voice changes. |
      | `defaultOpen` | `boolean` | `false` | The default open state (uncontrolled). |
      | `open` | `boolean` | - | The open state (controlled). |
      | `onOpenChange` | `(open: boolean) => void` | - | Callback fired when the open state changes. |
      | `modal` | `boolean` | `true` | Whether the dialog is modal (blocks interaction with the rest of the page). |
      | `...props` | `React.ComponentProps<typeof Dialog>` | - | Any other props are spread to the Dialog component. |
      
      ### `<VoiceSelectorTrigger />`
      
      Button or element that opens the voice selector dialog.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `asChild` | `boolean` | `false` | Change the default rendered element for the one passed as a child, merging their props and behavior. |
      | `...props` | `React.ComponentProps<typeof DialogTrigger>` | - | Any other props are spread to the DialogTrigger component. |
      
      ### `<VoiceSelectorContent />`
      
      Container for the Command component and voice list, rendered inside the dialog.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `title` | `ReactNode` | - | The title for screen readers. Hidden visually but accessible to assistive technologies. |
      | `className` | `string` | - | Additional CSS classes to apply to the dialog content. |
      | `...props` | `React.ComponentProps<typeof DialogContent>` | - | Any other props are spread to the DialogContent component. |
      
      ### `<VoiceSelectorDialog />`
      
      Alternative dialog implementation using CommandDialog for a full-screen command palette style.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandDialog>` | - | Any other props are spread to the CommandDialog component. |
      
      ### `<VoiceSelectorInput />`
      
      Search input for filtering voices.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `placeholder` | `string` | - | Placeholder text for the search input. |
      | `className` | `string` | - | Additional CSS classes to apply. |
      | `...props` | `React.ComponentProps<typeof CommandInput>` | - | Any other props are spread to the CommandInput component. |
      
      ### `<VoiceSelectorList />`
      
      Scrollable container for voice items and groups.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandList>` | - | Any other props are spread to the CommandList component. |
      
      ### `<VoiceSelectorEmpty />`
      
      Message shown when no voices match the search query.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `children` | `ReactNode` | - | The message to display. |
      | `...props` | `React.ComponentProps<typeof CommandEmpty>` | - | Any other props are spread to the CommandEmpty component. |
      
      ### `<VoiceSelectorGroup />`
      
      Groups related voices together with an optional heading.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `heading` | `string` | - | The heading text for the group. |
      | `...props` | `React.ComponentProps<typeof CommandGroup>` | - | Any other props are spread to the CommandGroup component. |
      
      ### `<VoiceSelectorItem />`
      
      Selectable item representing a voice.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `value` | `string` | - | The unique identifier for this voice. Used for search filtering. |
      | `onSelect` | `(value: string) => void` | - | Callback fired when the voice is selected. |
      | `...props` | `React.ComponentProps<typeof CommandItem>` | - | Any other props are spread to the CommandItem component. |
      
      ### `<VoiceSelectorSeparator />`
      
      Visual separator between voice groups.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandSeparator>` | - | Any other props are spread to the CommandSeparator component. |
      
      ### `<VoiceSelectorName />`
      
      Displays the voice name with proper styling.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<VoiceSelectorGender />`
      
      Displays the voice gender metadata with icons from Lucide. Supports multiple gender identities with corresponding icons.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `value` | `unknown` | - | The gender value that determines which icon to display. Supported values:  |
      | `className` | `string` | - | Additional CSS classes to apply. |
      | `children` | `ReactNode` | - | Override the icon with custom content. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<VoiceSelectorAccent />`
      
      Displays the voice accent metadata with emoji flags representing different countries/regions.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `value` | `unknown` | - | The accent value that determines which flag emoji to display. Supports 27 different accents including:  |
      | `className` | `string` | - | Additional CSS classes to apply. |
      | `children` | `ReactNode` | - | Override the flag emoji with custom content. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<VoiceSelectorAge />`
      
      Displays the voice age metadata with muted styling and tabular numbers for consistent alignment.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<VoiceSelectorDescription />`
      
      Displays a description for the voice with muted styling.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<VoiceSelectorAttributes />`
      
      Container for grouping voice attributes (gender, accent, age) together. Use with `VoiceSelectorBullet` for separation.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the div element. |
      
      ### `<VoiceSelectorBullet />`
      
      Displays a bullet separator (•) between voice attributes. Hidden from screen readers via `aria-hidden`.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `className` | `string` | - | Additional CSS classes to apply. |
      | `...props` | `React.ComponentProps<` | - | Any other props are spread to the span element. |
      
      ### `<VoiceSelectorShortcut />`
      
      Displays keyboard shortcuts for voice items.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof CommandShortcut>` | - | Any other props are spread to the CommandShortcut component. |
      
      ### `<VoiceSelectorPreview />`
      
      A button that allows users to preview/play a voice sample before selecting it. Shows play, pause, or loading icons based on state.
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `playing` | `boolean` | - | Whether the voice is currently playing. Shows pause icon when true. |
      | `loading` | `boolean` | - | Whether the voice preview is loading. Shows loading spinner and disables the button. |
      | `onPlay` | `() => void` | - | Callback fired when the preview button is clicked. |
      | `className` | `string` | - | Additional CSS classes to apply. |
      | `...props` | `Omit<React.ComponentProps<` | - | Any other props are spread to the button element. |
      
      ## Hooks
      
      ### `useVoiceSelector()`
      
      A custom hook for accessing the voice selector context. This hook allows you to access and control the voice selection state from any component nested within `VoiceSelector`.
      
      ```tsx
      import { useVoiceSelector } from "@repo/elements/voice-selector";
      
      export default function CustomVoiceDisplay() {
        const { value, setValue, open, setOpen } = useVoiceSelector();
      
        return (
          <div>
            <p>Selected voice: {value ?? "None"}</p>
            <button onClick={() => setOpen(!open)}>Toggle Dialog</button>
          </div>
        );
      }
      ```
      
      #### Return Value
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `value` | `string | undefined` | - | The currently selected voice ID. |
      | `setValue` | `(value: string | undefined) => void` | - | Function to update the selected voice ID. |
      | `open` | `boolean` | - | Whether the dialog is currently open. |
      | `setOpen` | `(open: boolean) => void` | - | Function to control the dialog open state. |
      
    • web-preview.md 6.1 KB
      # Web Preview
      
      A composable component for previewing the result of a generated UI, with support for live examples and code display.
      
      The `WebPreview` component provides a flexible way to showcase the result of a generated UI component, along with its source code. It is designed for documentation and demo purposes, allowing users to interact with live examples and view the underlying implementation.
      
      See `scripts/web-preview.tsx` for this example.
      
      ## Installation
      
      ```bash
      npx ai-elements@latest add web-preview
      ```
      
      ## Usage with AI SDK
      
      Build a simple v0 clone using the [v0 Platform API](https://v0.dev/docs/api/platform).
      
      Install the `v0-sdk` package:
      
      ```package-install
      npm i v0-sdk
      ```
      
      Add the following component to your frontend:
      
      ```tsx title="app/page.tsx"
      "use client";
      
      import {
        WebPreview,
        WebPreviewBody,
        WebPreviewNavigation,
        WebPreviewUrl,
      } from "@/components/ai-elements/web-preview";
      import { useState } from "react";
      import {
        PromptInput,
        type PromptInputMessage,
        PromptInputTextarea,
        PromptInputSubmit,
      } from "@/components/ai-elements/prompt-input";
      import { Spinner } from "@/components/ui/spinner";
      
      const WebPreviewDemo = () => {
        const [previewUrl, setPreviewUrl] = useState("");
        const [prompt, setPrompt] = useState("");
        const [isGenerating, setIsGenerating] = useState(false);
      
        const handleSubmit = async (message: PromptInputMessage) => {
          if (!message.text.trim()) return;
          setPrompt("");
      
          setIsGenerating(true);
          try {
            const response = await fetch("/api/v0", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ prompt: message.text }),
            });
      
            const data = await response.json();
            setPreviewUrl(data.demo || "/");
            console.log("Generation finished:", data);
          } catch (error) {
            console.error("Generation failed:", error);
          } finally {
            setIsGenerating(false);
          }
        };
      
        return (
          <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
            <div className="flex flex-col h-full">
              <div className="flex-1 mb-4">
                {isGenerating ? (
                  <div className="flex flex-col items-center justify-center h-full">
                    <Spinner />
                    <p className="mt-4 text-muted-foreground">
                      Generating app, this may take a few seconds...
                    </p>
                  </div>
                ) : previewUrl ? (
                  <WebPreview defaultUrl={previewUrl}>
                    <WebPreviewNavigation>
                      <WebPreviewUrl />
                    </WebPreviewNavigation>
                    <WebPreviewBody src={previewUrl} />
                  </WebPreview>
                ) : (
                  <div className="flex items-center justify-center h-full text-muted-foreground">
                    Your generated app will appear here
                  </div>
                )}
              </div>
      
              <PromptInput
                onSubmit={handleSubmit}
                className="w-full max-w-2xl mx-auto relative"
              >
                <PromptInputTextarea
                  value={prompt}
                  placeholder="Describe the app you want to build..."
                  onChange={(e) => setPrompt(e.currentTarget.value)}
                  className="pr-12 min-h-[60px]"
                />
                <PromptInputSubmit
                  status={isGenerating ? "streaming" : "ready"}
                  disabled={!prompt.trim()}
                  className="absolute bottom-1 right-1"
                />
              </PromptInput>
            </div>
          </div>
        );
      };
      
      export default WebPreviewDemo;
      ```
      
      Add the following route to your backend:
      
      ```ts title="app/api/v0/route.ts"
      import { v0 } from "v0-sdk";
      
      export async function POST(req: Request) {
        const { prompt }: { prompt: string } = await req.json();
      
        const result = await v0.chats.create({
          system: "You are an expert coder",
          message: prompt,
          modelConfiguration: {
            modelId: "v0-1.5-sm",
            imageGenerations: false,
            thinking: false,
          },
        });
      
        return Response.json({
          demo: result.demo,
          webUrl: result.webUrl,
        });
      }
      ```
      
      ## Features
      
      - Live preview of UI components
      - Composable architecture with dedicated sub-components
      - Responsive design modes (Desktop, Tablet, Mobile)
      - Navigation controls with back/forward functionality
      - URL input and example selector
      - Full screen mode support
      - Console logging with timestamps
      - Context-based state management
      - Consistent styling with the design system
      - Easy integration into documentation pages
      
      ## Props
      
      ### `<WebPreview />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `defaultUrl` | `string` | - | The initial URL to load in the preview. |
      | `onUrlChange` | `(url: string) => void` | - | Callback fired when the URL changes. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the root div. |
      
      ### `<WebPreviewNavigation />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the navigation container. |
      
      ### `<WebPreviewNavigationButton />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `tooltip` | `string` | - | Tooltip text to display on hover. |
      | `...props` | `React.ComponentProps<typeof Button>` | - | Any other props are spread to the underlying shadcn/ui Button component. |
      
      ### `<WebPreviewUrl />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `...props` | `React.ComponentProps<typeof Input>` | - | Any other props are spread to the underlying shadcn/ui Input component. |
      
      ### `<WebPreviewBody />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `loading` | `React.ReactNode` | - | Optional loading indicator to display over the preview. |
      | `...props` | `React.IframeHTMLAttributes<HTMLIFrameElement>` | - | Any other props are spread to the underlying iframe. |
      
      ### `<WebPreviewConsole />`
      
      | Prop | Type | Default | Description |
      |------|------|---------|-------------|
      | `logs` | `Array<{ level: ` | - | Console log entries to display in the console panel. |
      | `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | Any other props are spread to the root div. |
      
  • scripts
    • agent.tsx 1.6 KB · in bundle
    • artifact.tsx 2.9 KB · in bundle
    • attachments-inline.tsx 3.5 KB · in bundle
    • attachments-list.tsx 2.2 KB · in bundle
    • attachments.tsx 2 KB · in bundle
    • audio-player-remote.tsx 1 KB · in bundle
    • audio-player.tsx 1.8 KB · in bundle
    • chain-of-thought.tsx 138.6 KB · in bundle
    • checkpoint.tsx 2.8 KB · in bundle
    • code-block-dark.tsx 1 KB · in bundle
    • code-block.tsx 2.9 KB · in bundle
    • commit.tsx 2.1 KB · in bundle
    • confirmation-accepted.tsx 1.2 KB · in bundle
    • confirmation-rejected.tsx 1.1 KB · in bundle
    • confirmation-request.tsx 1.7 KB · in bundle
    • confirmation.tsx 1.7 KB · in bundle
    • context.tsx 1005 B · in bundle
    • conversation.tsx 4.1 KB · in bundle
    • environment-variables.tsx 1.7 KB · in bundle
    • file-tree-basic.tsx 380 B · in bundle
    • file-tree-expanded.tsx 609 B · in bundle
    • file-tree-selection.tsx 619 B · in bundle
    • file-tree.tsx 1.5 KB · in bundle
    • image.tsx 136.5 KB · in bundle
    • inline-citation.tsx 3.2 KB · in bundle
    • jsx-preview.tsx 3.2 KB · in bundle
    • message.tsx 10.1 KB · in bundle
    • mic-selector.tsx 1.2 KB · in bundle
    • model-selector.tsx 8.5 KB · in bundle
    • open-in-chat.tsx 704 B · in bundle
    • package-info.tsx 1.3 KB · in bundle
    • persona-command.tsx 2.5 KB · in bundle
    • persona-glint.tsx 2.5 KB · in bundle
    • persona-halo.tsx 2.5 KB · in bundle
    • persona-mana.tsx 2.5 KB · in bundle
    • persona-obsidian.tsx 2.5 KB · in bundle
    • persona-opal.tsx 2.5 KB · in bundle
    • plan.tsx 1.9 KB · in bundle
    • prompt-input-cursor.tsx 15.1 KB · in bundle
    • prompt-input-tooltip.tsx 1.1 KB · in bundle
    • prompt-input.tsx 7.4 KB · in bundle
    • queue-prompt-input.tsx 10.5 KB · in bundle
    • queue.tsx 8 KB · in bundle
    • reasoning.tsx 2.2 KB · in bundle
    • sandbox.tsx 5.4 KB · in bundle
    • schema-display-basic.tsx 221 B · in bundle
    • schema-display-body.tsx 487 B · in bundle
    • schema-display-nested.tsx 470 B · in bundle
    • schema-display-params.tsx 374 B · in bundle
    • schema-display.tsx 2.7 KB · in bundle
    • shimmer-duration.tsx 934 B · in bundle
    • shimmer-elements.tsx 1.1 KB · in bundle
    • shimmer.tsx 443 B · in bundle
    • snippet-plain.tsx 362 B · in bundle
    • snippet.tsx 589 B · in bundle
    • sources-custom.tsx 1 KB · in bundle
    • sources.tsx 752 B · in bundle
    • speech-input.tsx 2.3 KB · in bundle
    • stack-trace-collapsed.tsx 1.1 KB · in bundle
    • stack-trace-no-internal.tsx 1.2 KB · in bundle
    • stack-trace.tsx 1.9 KB · in bundle
    • suggestion-input.tsx 4.4 KB · in bundle
    • suggestion.tsx 802 B · in bundle
    • task.tsx 1.5 KB · in bundle
    • terminal-basic.tsx 169 B · in bundle
    • terminal-clear.tsx 523 B · in bundle
    • terminal-streaming.tsx 1007 B · in bundle
    • terminal.tsx 2.3 KB · in bundle
    • test-results-basic.tsx 464 B · in bundle
    • test-results-errors.tsx 1.3 KB · in bundle
    • test-results-suites.tsx 901 B · in bundle
    • test-results.tsx 2.7 KB · in bundle
    • tool-input-available.tsx 738 B · in bundle
    • tool-input-streaming.tsx 683 B · in bundle
    • tool-output-available.tsx 1.7 KB · in bundle
    • tool-output-error.tsx 1.1 KB · in bundle
    • tool.tsx 6.7 KB · in bundle
    • transcription.tsx 4.9 KB · in bundle
    • voice-selector.tsx 7.1 KB · in bundle
    • web-preview.tsx 2.8 KB · in bundle
  • SKILL.md 7.1 KB
    ---
    name: ai-elements
    description: Build AI chat interfaces using ai-elements components — conversations, messages, tool displays, prompt inputs, and more. Use when the user wants to build a chatbot, AI assistant UI, or any AI-powered chat interface.
    ---
    
    # AI Elements
    
    [AI Elements](https://www.npmjs.com/package/ai-elements) is a component library and custom registry built on top of [shadcn/ui](https://ui.shadcn.com/) to help you build AI-native applications faster. It provides pre-built components like conversations, messages and more.
    
    Installing AI Elements is straightforward and can be done in a couple of ways. You can use the dedicated CLI command for the fastest setup, or integrate via the standard shadcn/ui CLI if you've already adopted shadcn's workflow.
    
    > **IMPORTANT:** Run all CLI commands using the project's package runner: `npx ai-elements@latest`, `pnpm dlx ai-elements@latest`, or `bunx --bun ai-elements@latest` — based on the project's `packageManager`. Examples below use `npx ai-elements@latest` but substitute the correct runner for the project.
    
    ## Prerequisites
    
    Before installing AI Elements, make sure your environment meets the following requirements:
    
    - [Node.js](https://nodejs.org/en/download/), version 18 or later
    - A [Next.js](https://nextjs.org/) project with the [AI SDK](https://ai-sdk.dev/) installed.
    - [shadcn/ui](https://ui.shadcn.com/) installed in your project. If you don't have it installed, running any install command will automatically install it for you.
    - We also highly recommend using the [AI Gateway](https://vercel.com/docs/ai-gateway) and adding `AI_GATEWAY_API_KEY` to your `env.local` so you don't have to use an API key from every provider. AI Gateway also gives $5 in usage per month so you can experiment with models. You can obtain an API key [here](https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys&title=Get%20your%20AI%20Gateway%20key).
    
    ## Installing Components
    
    You can install AI Elements components using either the AI Elements CLI or the shadcn/ui CLI. Both achieve the same result: adding the selected component’s code and any needed dependencies to your project.
    
    The CLI will download the component’s code and integrate it into your project’s directory (usually under your components folder). By default, AI Elements components are added to the `@/components/ai-elements/` directory (or whatever folder you’ve configured in your shadcn components settings).
    
    After running the command, you should see a confirmation in your terminal that the files were added. You can then proceed to use the component in your code.
    
    ## Usage
    
    Once an AI Elements component is installed, you can import it and use it in your application like any other React component. The components are added as part of your codebase (not hidden in a library), so the usage feels very natural.
    
    ## Example
    
    After installing AI Elements components, you can use them in your application like any other React component. For example:
    
    ```tsx title="conversation.tsx"
    "use client";
    
    import {
      Message,
      MessageContent,
      MessageResponse,
    } from "@/components/ai-elements/message";
    import { useChat } from "@ai-sdk/react";
    
    const Example = () => {
      const { messages } = useChat();
    
      return (
        <>
          {messages.map(({ role, parts }, index) => (
            <Message from={role} key={index}>
              <MessageContent>
                {parts.map((part, i) => {
                  switch (part.type) {
                    case "text":
                      return (
                        <MessageResponse key={`${role}-${i}`}>
                          {part.text}
                        </MessageResponse>
                      );
                  }
                })}
              </MessageContent>
            </Message>
          ))}
        </>
      );
    };
    
    export default Example;
    ```
    
    In the example above, we import the `Message` component from our AI Elements directory and include it in our JSX. Then, we compose the component with the `MessageContent` and `MessageResponse` subcomponents. You can style or configure the component just as you would if you wrote it yourself – since the code lives in your project, you can even open the component file to see how it works or make custom modifications.
    
    ## Extensibility
    
    All AI Elements components take as many primitive attributes as possible. For example, the `Message` component extends `HTMLAttributes<HTMLDivElement>`, so you can pass any props that a `div` supports. This makes it easy to extend the component with your own styles or functionality.
    
    ## Customization
    
    After installation, no additional setup is needed. The component’s styles (Tailwind CSS classes) and scripts are already integrated. You can start interacting with the component in your app immediately.
    
    For example, if you'd like to remove the rounding on `Message`, you can go to `components/ai-elements/message.tsx` and remove `rounded-lg` as follows:
    
    ```tsx title="components/ai-elements/message.tsx" highlight="8"
    export const MessageContent = ({
      children,
      className,
      ...props
    }: MessageContentProps) => (
      <div
        className={cn(
          "flex flex-col gap-2 text-sm text-foreground",
          "group-[.is-user]:bg-primary group-[.is-user]:text-primary-foreground group-[.is-user]:px-4 group-[.is-user]:py-3",
          className
        )}
        {...props}
      >
        <div className="is-user:dark">{children}</div>
      </div>
    );
    ```
    
    ## Troubleshooting
    
    ### Why are my components not styled?
    
    Make sure your project is configured correctly for shadcn/ui in Tailwind 4 - this means having a `globals.css` file that imports Tailwind and includes the shadcn/ui base styles.
    
    ### I ran the AI Elements CLI but nothing was added to my project
    
    Double-check that:
    
    - Your current working directory is the root of your project (where `package.json` lives).
    - Your components.json file (if using shadcn-style config) is set up correctly.
    - You’re using the latest version of the AI Elements CLI:
    
    ```bash title="Terminal"
    npx ai-elements@latest
    ```
    
    If all else fails, feel free to open an [issue on GitHub](https://github.com/vercel/ai-elements/issues).
    
    ### Theme switching doesn’t work — my app stays in light mode
    
    Ensure your app is using the same data-theme system that shadcn/ui and AI Elements expect. The default implementation toggles a data-theme attribute on the `<html>` element. Make sure your tailwind.config.js is using class or data- selectors accordingly.
    
    ### The component imports fail with “module not found”
    
    Check the file exists. If it does, make sure your `tsconfig.json` has a proper paths alias for `@/` i.e.
    
    ```json title="tsconfig.json"
    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["./*"]
        }
      }
    }
    ```
    
    ### My AI coding assistant can't access AI Elements components
    
    1. Verify your config file syntax is valid JSON.
    2. Check that the file path is correct for your AI tool.
    3. Restart your coding assistant after making changes.
    4. Ensure you have a stable internet connection.
    
    ### Still stuck?
    
    If none of these answers help, open an [issue on GitHub](https://github.com/vercel/ai-elements/issues) and someone will be happy to assist.
    
    ## Available Components
    
    See the `references/` folder for detailed documentation on each component.
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related