mirror of
https://github.com/temetro/temetro.git
synced 2026-07-26 20:08:14 +00:00
Compare commits
117 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7838dd68a5 | |||
| 06810f861e | |||
| 2bb03633ff | |||
| dc5f55f87d | |||
| a4970df334 | |||
| 6c074b54f3 | |||
| f1c9f8af55 | |||
| 1c65f72ccf | |||
| f12285b8c6 | |||
| 75910f7fb0 | |||
| 3767c1689b | |||
| edf42e9741 | |||
| 31adbab87b | |||
| 15bf5653b4 | |||
| 8ba7256105 | |||
| 6237cc29d0 | |||
| 8cabd17cdd | |||
| 3ee00fcf06 | |||
| 869038477a | |||
| 8309e1e82e | |||
| b2ac27dda7 | |||
| c82ba4b33e | |||
| 130f90bf6a | |||
| 403e0e38e9 | |||
| 2454bb4c2b | |||
| 6bd81bd7dd | |||
| a68b7f2573 | |||
| 014b4ddf8f | |||
| f10d01546b | |||
| 4e60361f77 | |||
| 7a359d4911 | |||
| 2d47abcc42 | |||
| b74d5d2d05 | |||
| 90e6ec4cc0 | |||
| 516de6ad60 | |||
| e656eae362 | |||
| bbc6869745 | |||
| 1d9b1b1d22 | |||
| 913a217e1d | |||
| e841cb56e1 | |||
| c88b674196 | |||
| 0fa2802723 | |||
| 2f36875d37 | |||
| eb94c1549a | |||
| dfab71492c | |||
| 1c52dcaf84 | |||
| 5cbc7411c0 | |||
| 7bb1ee39ab | |||
| f9615fa74e | |||
| 064aa22099 | |||
| 2c9cec0112 | |||
| 43eaccb97e | |||
| b1abb29108 | |||
| 67cafdac3d | |||
| 9a913147fb | |||
| a06c8c739b | |||
| 5975e9e21a | |||
| e43409ac14 | |||
| be3968ce64 | |||
| f38f75617a | |||
| d30c310336 | |||
| 651c197f94 | |||
| d37a4e9425 | |||
| 96bda1b902 | |||
| 9503716eb3 | |||
| 29347488fa | |||
| 3b4e1c7f61 | |||
| 705d4b5719 | |||
| 700b461618 | |||
| cea781493f | |||
| 307cc3cc64 | |||
| f0fe501d62 | |||
| 559667e380 | |||
| 15fc7fdf26 | |||
| addddc8972 | |||
| 6fdb7bdb46 | |||
| 6e5598262e | |||
| ed4106ed14 | |||
| 3aa699aefe | |||
| b946dc9226 | |||
| 8c1f520047 | |||
| 9086867782 | |||
| d096c4fe9d | |||
| 9eb6353e00 | |||
| db20359b25 | |||
| 91fbe4129f | |||
| 929bec8f31 | |||
| 67249be67b | |||
| da7752272e | |||
| fa2e499440 | |||
| ddf4b49d82 | |||
| a80086ef72 | |||
| a3f4cf8633 | |||
| af956a2779 | |||
| 56b09c269b | |||
| 31d86bb5dd | |||
| ff37b555b0 | |||
| 3a7378e00d | |||
| c6a1b98427 | |||
| 9545fdd360 | |||
| 321a6298a4 | |||
| e2bcb2cfbc | |||
| 67fdf15de4 | |||
| 91e4f4ed30 | |||
| f550f4cbd7 | |||
| 09745b8fdd | |||
| 3bafe38889 | |||
| ce2a54cc43 | |||
| 84c71de2d4 | |||
| a4f692d59d | |||
| e37d131800 | |||
| e88638ca48 | |||
| a07966ca4d | |||
| 5312f914ac | |||
| 470230591c | |||
| 50fbb6cd40 | |||
| da245b8758 |
@@ -0,0 +1,160 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,134 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,84 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,190 @@
|
||||
# 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"
|
||||
```
|
||||
@@ -0,0 +1,134 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,34 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,81 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,183 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,170 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,177 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,262 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,34 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,126 @@
|
||||
# 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
|
||||
@@ -0,0 +1,32 @@
|
||||
# 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.). |
|
||||
@@ -0,0 +1,224 @@
|
||||
# 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("")}`
|
||||
);
|
||||
```
|
||||
@@ -0,0 +1,52 @@
|
||||
# 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). |
|
||||
@@ -0,0 +1,102 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,72 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,146 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,299 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,104 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,237 @@
|
||||
# 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. |
|
||||
```
|
||||
@@ -0,0 +1,189 @@
|
||||
# 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
|
||||
@@ -0,0 +1,112 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,73 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,67 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,95 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,33 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,166 @@
|
||||
# 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")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,79 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,579 @@
|
||||
# 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
|
||||
```
|
||||
@@ -0,0 +1,172 @@
|
||||
# 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";
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,238 @@
|
||||
# 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). |
|
||||
@@ -0,0 +1,129 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,102 @@
|
||||
# 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
|
||||
@@ -0,0 +1,48 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,64 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,209 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,163 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,224 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,124 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,222 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,103 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,157 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,285 @@
|
||||
# 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"
|
||||
@@ -0,0 +1,32 @@
|
||||
# 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.). |
|
||||
@@ -0,0 +1,120 @@
|
||||
# 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
|
||||
@@ -0,0 +1,241 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,200 @@
|
||||
# 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. |
|
||||
@@ -0,0 +1,61 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Agent,
|
||||
AgentContent,
|
||||
AgentHeader,
|
||||
AgentInstructions,
|
||||
AgentOutput,
|
||||
AgentTool,
|
||||
AgentTools,
|
||||
} from "@/components/ai-elements/agent";
|
||||
import { z } from "zod";
|
||||
|
||||
const webSearchTool = {
|
||||
description: "Search the web for information",
|
||||
inputSchema: z.object({
|
||||
query: z.string().describe("The search query"),
|
||||
}),
|
||||
};
|
||||
|
||||
const readUrlTool = {
|
||||
description: "Read and parse a URL",
|
||||
inputSchema: z.object({
|
||||
url: z.string().url().describe("The URL to read"),
|
||||
}),
|
||||
};
|
||||
|
||||
const summarizeTool = {
|
||||
description: "Summarize text into key points",
|
||||
inputSchema: z.object({
|
||||
maxPoints: z.number().optional().describe("Maximum number of key points"),
|
||||
text: z.string().describe("The text to summarize"),
|
||||
}),
|
||||
};
|
||||
|
||||
const outputSchema = `z.object({
|
||||
sentiment: z.enum(['positive', 'negative', 'neutral']),
|
||||
score: z.number(),
|
||||
summary: z.string(),
|
||||
})`;
|
||||
|
||||
const Example = () => (
|
||||
<Agent>
|
||||
<AgentHeader model="openai/gpt-5.2-pro" name="Research Assistant" />
|
||||
<AgentContent>
|
||||
<AgentInstructions>
|
||||
You are a helpful research assistant. Your job is to search the web for
|
||||
information and summarize findings for the user. Always cite your
|
||||
sources and provide accurate, up-to-date information.
|
||||
</AgentInstructions>
|
||||
<AgentTools type="multiple">
|
||||
<AgentTool tool={webSearchTool} value="web_search" />
|
||||
<AgentTool tool={readUrlTool} value="read_url" />
|
||||
<AgentTool tool={summarizeTool} value="summarize" />
|
||||
</AgentTools>
|
||||
<AgentOutput schema={outputSchema} />
|
||||
</AgentContent>
|
||||
</Agent>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,127 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Artifact,
|
||||
ArtifactAction,
|
||||
ArtifactActions,
|
||||
ArtifactContent,
|
||||
ArtifactDescription,
|
||||
ArtifactHeader,
|
||||
ArtifactTitle,
|
||||
} from "@/components/ai-elements/artifact";
|
||||
import { CodeBlock } from "@/components/ai-elements/code-block";
|
||||
import {
|
||||
CopyIcon,
|
||||
DownloadIcon,
|
||||
PlayIcon,
|
||||
RefreshCwIcon,
|
||||
ShareIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
const handleRun = () => {
|
||||
console.log("Run");
|
||||
};
|
||||
|
||||
const handleCopy = () => {
|
||||
console.log("Copy");
|
||||
};
|
||||
|
||||
const handleRegenerate = () => {
|
||||
console.log("Regenerate");
|
||||
};
|
||||
|
||||
const handleDownload = () => {
|
||||
console.log("Download");
|
||||
};
|
||||
|
||||
const handleShare = () => {
|
||||
console.log("Share");
|
||||
};
|
||||
|
||||
const code = `# Dijkstra's Algorithm implementation
|
||||
import heapq
|
||||
|
||||
def dijkstra(graph, start):
|
||||
distances = {node: float('inf') for node in graph}
|
||||
distances[start] = 0
|
||||
heap = [(0, start)]
|
||||
visited = set()
|
||||
|
||||
while heap:
|
||||
current_distance, current_node = heapq.heappop(heap)
|
||||
if current_node in visited:
|
||||
continue
|
||||
visited.add(current_node)
|
||||
|
||||
for neighbor, weight in graph[current_node].items():
|
||||
distance = current_distance + weight
|
||||
if distance < distances[neighbor]:
|
||||
distances[neighbor] = distance
|
||||
heapq.heappush(heap, (distance, neighbor))
|
||||
|
||||
return distances
|
||||
|
||||
# Example graph
|
||||
graph = {
|
||||
'A': {'B': 1, 'C': 4},
|
||||
'B': {'A': 1, 'C': 2, 'D': 5},
|
||||
'C': {'A': 4, 'B': 2, 'D': 1},
|
||||
'D': {'B': 5, 'C': 1}
|
||||
}
|
||||
|
||||
print(dijkstra(graph, 'A'))`;
|
||||
|
||||
const Example = () => (
|
||||
<Artifact>
|
||||
<ArtifactHeader>
|
||||
<div>
|
||||
<ArtifactTitle>Dijkstra's Algorithm Implementation</ArtifactTitle>
|
||||
<ArtifactDescription>Updated 1 minute ago</ArtifactDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<ArtifactActions>
|
||||
<ArtifactAction
|
||||
icon={PlayIcon}
|
||||
label="Run"
|
||||
onClick={handleRun}
|
||||
tooltip="Run code"
|
||||
/>
|
||||
<ArtifactAction
|
||||
icon={CopyIcon}
|
||||
label="Copy"
|
||||
onClick={handleCopy}
|
||||
tooltip="Copy to clipboard"
|
||||
/>
|
||||
<ArtifactAction
|
||||
icon={RefreshCwIcon}
|
||||
label="Regenerate"
|
||||
onClick={handleRegenerate}
|
||||
tooltip="Regenerate content"
|
||||
/>
|
||||
<ArtifactAction
|
||||
icon={DownloadIcon}
|
||||
label="Download"
|
||||
onClick={handleDownload}
|
||||
tooltip="Download file"
|
||||
/>
|
||||
<ArtifactAction
|
||||
icon={ShareIcon}
|
||||
label="Share"
|
||||
onClick={handleShare}
|
||||
tooltip="Share artifact"
|
||||
/>
|
||||
</ArtifactActions>
|
||||
</div>
|
||||
</ArtifactHeader>
|
||||
<ArtifactContent className="p-0">
|
||||
<CodeBlock
|
||||
className="border-none"
|
||||
code={code}
|
||||
language="python"
|
||||
showLineNumbers
|
||||
/>
|
||||
</ArtifactContent>
|
||||
</Artifact>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,128 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentHoverCard,
|
||||
AttachmentHoverCardContent,
|
||||
AttachmentHoverCardTrigger,
|
||||
AttachmentInfo,
|
||||
AttachmentPreview,
|
||||
AttachmentRemove,
|
||||
Attachments,
|
||||
getAttachmentLabel,
|
||||
getMediaCategory,
|
||||
} from "@/components/ai-elements/attachments";
|
||||
import { nanoid } from "nanoid";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const initialAttachments = [
|
||||
{
|
||||
filename: "mountain-landscape.jpg",
|
||||
id: nanoid(),
|
||||
mediaType: "image/jpeg",
|
||||
type: "file" as const,
|
||||
url: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=400&fit=crop",
|
||||
},
|
||||
{
|
||||
filename: "quarterly-report.pdf",
|
||||
id: nanoid(),
|
||||
mediaType: "application/pdf",
|
||||
type: "file" as const,
|
||||
url: "",
|
||||
},
|
||||
{
|
||||
id: nanoid(),
|
||||
mediaType: "text/html",
|
||||
title: "React Documentation",
|
||||
type: "source-document" as const,
|
||||
url: "https://react.dev",
|
||||
},
|
||||
{
|
||||
filename: "podcast-episode.mp3",
|
||||
id: nanoid(),
|
||||
mediaType: "audio/mp3",
|
||||
type: "file" as const,
|
||||
url: "",
|
||||
},
|
||||
];
|
||||
|
||||
interface AttachmentItemProps {
|
||||
attachment: (typeof initialAttachments)[0];
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const AttachmentItem = memo(({ attachment, onRemove }: AttachmentItemProps) => {
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(attachment.id),
|
||||
[onRemove, attachment.id]
|
||||
);
|
||||
const mediaCategory = getMediaCategory(attachment);
|
||||
const label = getAttachmentLabel(attachment);
|
||||
|
||||
return (
|
||||
<AttachmentHoverCard key={attachment.id}>
|
||||
<AttachmentHoverCardTrigger asChild>
|
||||
<Attachment data={attachment} onRemove={handleRemove}>
|
||||
<div className="relative size-5 shrink-0">
|
||||
<div className="absolute inset-0 transition-opacity group-hover:opacity-0">
|
||||
<AttachmentPreview />
|
||||
</div>
|
||||
<AttachmentRemove className="absolute inset-0" />
|
||||
</div>
|
||||
<AttachmentInfo />
|
||||
</Attachment>
|
||||
</AttachmentHoverCardTrigger>
|
||||
<AttachmentHoverCardContent>
|
||||
<div className="space-y-3">
|
||||
{mediaCategory === "image" &&
|
||||
attachment.type === "file" &&
|
||||
attachment.url && (
|
||||
<div className="flex max-h-96 w-80 items-center justify-center overflow-hidden rounded-md border">
|
||||
<img
|
||||
alt={label}
|
||||
className="max-h-full max-w-full object-contain"
|
||||
height={384}
|
||||
src={attachment.url}
|
||||
width={320}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-1 px-0.5">
|
||||
<h4 className="font-semibold text-sm leading-none">{label}</h4>
|
||||
{attachment.mediaType && (
|
||||
<p className="font-mono text-muted-foreground text-xs">
|
||||
{attachment.mediaType}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</AttachmentHoverCardContent>
|
||||
</AttachmentHoverCard>
|
||||
);
|
||||
});
|
||||
|
||||
AttachmentItem.displayName = "AttachmentItem";
|
||||
|
||||
const Example = () => {
|
||||
const [attachments, setAttachments] = useState(initialAttachments);
|
||||
|
||||
const handleRemove = useCallback((id: string) => {
|
||||
setAttachments((prev) => prev.filter((a) => a.id !== id));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Attachments variant="inline">
|
||||
{attachments.map((attachment) => (
|
||||
<AttachmentItem
|
||||
attachment={attachment}
|
||||
key={attachment.id}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
))}
|
||||
</Attachments>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentInfo,
|
||||
AttachmentPreview,
|
||||
AttachmentRemove,
|
||||
Attachments,
|
||||
} from "@/components/ai-elements/attachments";
|
||||
import { nanoid } from "nanoid";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const initialAttachments = [
|
||||
{
|
||||
filename: "mountain-landscape.jpg",
|
||||
id: nanoid(),
|
||||
mediaType: "image/jpeg",
|
||||
type: "file" as const,
|
||||
url: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=400&fit=crop",
|
||||
},
|
||||
{
|
||||
filename: "quarterly-report-2024.pdf",
|
||||
id: nanoid(),
|
||||
mediaType: "application/pdf",
|
||||
type: "file" as const,
|
||||
url: "",
|
||||
},
|
||||
{
|
||||
filename: "product-demo.mp4",
|
||||
id: nanoid(),
|
||||
mediaType: "video/mp4",
|
||||
type: "file" as const,
|
||||
url: "",
|
||||
},
|
||||
{
|
||||
filename: "api-reference",
|
||||
id: nanoid(),
|
||||
mediaType: "text/html",
|
||||
title: "API Documentation",
|
||||
type: "source-document" as const,
|
||||
url: "https://docs.example.com/api",
|
||||
},
|
||||
{
|
||||
filename: "meeting-recording.mp3",
|
||||
id: nanoid(),
|
||||
mediaType: "audio/mpeg",
|
||||
type: "file" as const,
|
||||
url: "",
|
||||
},
|
||||
];
|
||||
|
||||
interface AttachmentItemProps {
|
||||
attachment: (typeof initialAttachments)[0];
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const AttachmentItem = memo(({ attachment, onRemove }: AttachmentItemProps) => {
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(attachment.id),
|
||||
[onRemove, attachment.id]
|
||||
);
|
||||
return (
|
||||
<Attachment data={attachment} key={attachment.id} onRemove={handleRemove}>
|
||||
<AttachmentPreview />
|
||||
<AttachmentInfo showMediaType />
|
||||
<AttachmentRemove />
|
||||
</Attachment>
|
||||
);
|
||||
});
|
||||
|
||||
AttachmentItem.displayName = "AttachmentItem";
|
||||
|
||||
const Example = () => {
|
||||
const [attachments, setAttachments] = useState(initialAttachments);
|
||||
|
||||
const handleRemove = useCallback((id: string) => {
|
||||
setAttachments((prev) => prev.filter((a) => a.id !== id));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Attachments className="w-full max-w-md" variant="list">
|
||||
{attachments.map((attachment) => (
|
||||
<AttachmentItem
|
||||
attachment={attachment}
|
||||
key={attachment.id}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
))}
|
||||
</Attachments>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,85 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentPreview,
|
||||
AttachmentRemove,
|
||||
Attachments,
|
||||
} from "@/components/ai-elements/attachments";
|
||||
import { nanoid } from "nanoid";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const initialAttachments = [
|
||||
{
|
||||
filename: "mountain-landscape.jpg",
|
||||
id: nanoid(),
|
||||
mediaType: "image/jpeg",
|
||||
type: "file" as const,
|
||||
url: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=400&fit=crop",
|
||||
},
|
||||
{
|
||||
filename: "ocean-sunset.jpg",
|
||||
id: nanoid(),
|
||||
mediaType: "image/jpeg",
|
||||
type: "file" as const,
|
||||
url: "https://images.unsplash.com/photo-1682687220742-aba13b6e50ba?w=400&h=400&fit=crop",
|
||||
},
|
||||
{
|
||||
filename: "document.pdf",
|
||||
id: nanoid(),
|
||||
mediaType: "application/pdf",
|
||||
type: "file" as const,
|
||||
url: "",
|
||||
},
|
||||
{
|
||||
filename: "video.mp4",
|
||||
id: nanoid(),
|
||||
mediaType: "video/mp4",
|
||||
type: "file" as const,
|
||||
url: "",
|
||||
},
|
||||
];
|
||||
|
||||
interface AttachmentItemProps {
|
||||
attachment: (typeof initialAttachments)[0];
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const AttachmentItem = memo(({ attachment, onRemove }: AttachmentItemProps) => {
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(attachment.id),
|
||||
[onRemove, attachment.id]
|
||||
);
|
||||
return (
|
||||
<Attachment data={attachment} onRemove={handleRemove}>
|
||||
<AttachmentPreview />
|
||||
<AttachmentRemove />
|
||||
</Attachment>
|
||||
);
|
||||
});
|
||||
|
||||
AttachmentItem.displayName = "AttachmentItem";
|
||||
|
||||
const Example = () => {
|
||||
const [attachments, setAttachments] = useState(initialAttachments);
|
||||
|
||||
const handleRemove = useCallback((id: string) => {
|
||||
setAttachments((prev) => prev.filter((a) => a.id !== id));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Attachments variant="grid">
|
||||
{attachments.map((attachment) => (
|
||||
<AttachmentItem
|
||||
attachment={attachment}
|
||||
key={attachment.id}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
))}
|
||||
</Attachments>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
AudioPlayer,
|
||||
AudioPlayerControlBar,
|
||||
AudioPlayerDurationDisplay,
|
||||
AudioPlayerElement,
|
||||
AudioPlayerMuteButton,
|
||||
AudioPlayerPlayButton,
|
||||
AudioPlayerSeekBackwardButton,
|
||||
AudioPlayerSeekForwardButton,
|
||||
AudioPlayerTimeDisplay,
|
||||
AudioPlayerTimeRange,
|
||||
AudioPlayerVolumeRange,
|
||||
} from "@/components/ai-elements/audio-player";
|
||||
|
||||
const Example = () => (
|
||||
<div className="flex size-full items-center justify-center">
|
||||
<AudioPlayer>
|
||||
<AudioPlayerElement src="https://ejiidnob33g9ap1r.public.blob.vercel-storage.com/ElevenLabs_2025-11-10T22_07_46_Hayden_pvc_sp108_s50_sb75_se0_b_m2.mp3" />
|
||||
<AudioPlayerControlBar>
|
||||
<AudioPlayerPlayButton />
|
||||
<AudioPlayerSeekBackwardButton seekOffset={10} />
|
||||
<AudioPlayerSeekForwardButton seekOffset={10} />
|
||||
<AudioPlayerTimeDisplay />
|
||||
<AudioPlayerTimeRange />
|
||||
<AudioPlayerDurationDisplay />
|
||||
<AudioPlayerMuteButton />
|
||||
<AudioPlayerVolumeRange />
|
||||
</AudioPlayerControlBar>
|
||||
</AudioPlayer>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
AudioPlayer,
|
||||
AudioPlayerControlBar,
|
||||
AudioPlayerDurationDisplay,
|
||||
AudioPlayerElement,
|
||||
AudioPlayerMuteButton,
|
||||
AudioPlayerPlayButton,
|
||||
AudioPlayerSeekBackwardButton,
|
||||
AudioPlayerSeekForwardButton,
|
||||
AudioPlayerTimeDisplay,
|
||||
AudioPlayerTimeRange,
|
||||
AudioPlayerVolumeRange,
|
||||
} from "@/components/ai-elements/audio-player";
|
||||
import type { Experimental_SpeechResult as SpeechResult } from "ai";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
const Example = () => {
|
||||
const [data, setData] = useState<SpeechResult["audio"] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
const response = await fetch(
|
||||
"https://ejiidnob33g9ap1r.public.blob.vercel-storage.com/ElevenLabs_2025-11-10T22_07_46_Hayden_pvc_sp108_s50_sb75_se0_b_m2.mp3"
|
||||
);
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
const base64 = Buffer.from(arrayBuffer).toString("base64");
|
||||
|
||||
const newData: SpeechResult["audio"] = {
|
||||
base64,
|
||||
format: "mp3",
|
||||
mediaType: "audio/mpeg",
|
||||
uint8Array: new Uint8Array(arrayBuffer),
|
||||
};
|
||||
|
||||
setData(newData);
|
||||
};
|
||||
|
||||
if (!data) {
|
||||
fetchData();
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
if (!data) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex size-full items-center justify-center">
|
||||
<AudioPlayer>
|
||||
<AudioPlayerElement data={data} />
|
||||
<AudioPlayerControlBar>
|
||||
<AudioPlayerPlayButton />
|
||||
<AudioPlayerSeekBackwardButton seekOffset={10} />
|
||||
<AudioPlayerSeekForwardButton seekOffset={10} />
|
||||
<AudioPlayerTimeDisplay />
|
||||
<AudioPlayerTimeRange />
|
||||
<AudioPlayerDurationDisplay />
|
||||
<AudioPlayerMuteButton />
|
||||
<AudioPlayerVolumeRange />
|
||||
</AudioPlayerControlBar>
|
||||
</AudioPlayer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Checkpoint,
|
||||
CheckpointIcon,
|
||||
CheckpointTrigger,
|
||||
} from "@/components/ai-elements/checkpoint";
|
||||
import { Conversation, ConversationContent } from "@/components/ai-elements/conversation";
|
||||
import {
|
||||
Message,
|
||||
MessageContent,
|
||||
MessageResponse,
|
||||
} from "@/components/ai-elements/message";
|
||||
import { nanoid } from "nanoid";
|
||||
import { Fragment, memo, useCallback, useState } from "react";
|
||||
|
||||
interface MessageType {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
}
|
||||
|
||||
const initialMessages: MessageType[] = [
|
||||
{
|
||||
content: "What is React?",
|
||||
id: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content:
|
||||
"React is a JavaScript library for building user interfaces. It was developed by Facebook and is now maintained by Meta and a community of developers.",
|
||||
id: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "How does component state work?",
|
||||
id: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
];
|
||||
|
||||
interface CheckpointItemProps {
|
||||
checkpoint: { messageCount: number; timestamp: Date };
|
||||
onRestore: (messageCount: number) => void;
|
||||
}
|
||||
|
||||
const CheckpointItem = memo(
|
||||
({ checkpoint, onRestore }: CheckpointItemProps) => {
|
||||
const handleClick = useCallback(
|
||||
() => onRestore(checkpoint.messageCount),
|
||||
[onRestore, checkpoint.messageCount]
|
||||
);
|
||||
return (
|
||||
<Checkpoint>
|
||||
<CheckpointIcon />
|
||||
<CheckpointTrigger
|
||||
onClick={handleClick}
|
||||
tooltip="Restores workspace and chat to this point"
|
||||
>
|
||||
Restore checkpoint
|
||||
</CheckpointTrigger>
|
||||
</Checkpoint>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
CheckpointItem.displayName = "CheckpointItem";
|
||||
|
||||
const Example = () => {
|
||||
const [messages, setMessages] = useState<MessageType[]>(initialMessages);
|
||||
const [checkpoints] = useState([
|
||||
{ messageCount: 2, timestamp: new Date(Date.now() - 3_600_000) },
|
||||
]);
|
||||
|
||||
const handleRestore = useCallback((messageCount: number) => {
|
||||
setMessages(initialMessages.slice(0, messageCount));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col rounded-lg border p-6">
|
||||
<Conversation>
|
||||
<ConversationContent>
|
||||
{messages.map((message, index) => {
|
||||
const checkpoint = checkpoints.find(
|
||||
(cp) => cp.messageCount === index + 1
|
||||
);
|
||||
|
||||
return (
|
||||
<Fragment key={message.id}>
|
||||
<Message from={message.role}>
|
||||
<MessageContent>
|
||||
<MessageResponse>{message.content}</MessageResponse>
|
||||
</MessageContent>
|
||||
</Message>
|
||||
{checkpoint && (
|
||||
<CheckpointItem
|
||||
checkpoint={checkpoint}
|
||||
onRestore={handleRestore}
|
||||
/>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</ConversationContent>
|
||||
</Conversation>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
CodeBlock,
|
||||
CodeBlockActions,
|
||||
CodeBlockCopyButton,
|
||||
CodeBlockFilename,
|
||||
CodeBlockHeader,
|
||||
CodeBlockTitle,
|
||||
} from "@/components/ai-elements/code-block";
|
||||
import { FileIcon } from "lucide-react";
|
||||
|
||||
const handleCopy = () => {
|
||||
console.log("Copied code to clipboard");
|
||||
};
|
||||
|
||||
const handleCopyError = () => {
|
||||
console.error("Failed to copy code to clipboard");
|
||||
};
|
||||
|
||||
const code = `function MyComponent(props) {
|
||||
return (
|
||||
<div>
|
||||
<h1>Hello, {props.name}!</h1>
|
||||
<p>This is an example React component.</p>
|
||||
</div>
|
||||
);
|
||||
}`;
|
||||
|
||||
const Example = () => (
|
||||
<div className="dark">
|
||||
<CodeBlock code={code} language="jsx">
|
||||
<CodeBlockHeader>
|
||||
<CodeBlockTitle>
|
||||
<FileIcon size={14} />
|
||||
<CodeBlockFilename>MyComponent.jsx</CodeBlockFilename>
|
||||
</CodeBlockTitle>
|
||||
<CodeBlockActions>
|
||||
<CodeBlockCopyButton onCopy={handleCopy} onError={handleCopyError} />
|
||||
</CodeBlockActions>
|
||||
</CodeBlockHeader>
|
||||
</CodeBlock>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,120 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
CodeBlock,
|
||||
CodeBlockActions,
|
||||
CodeBlockCopyButton,
|
||||
CodeBlockFilename,
|
||||
CodeBlockHeader,
|
||||
CodeBlockLanguageSelector,
|
||||
CodeBlockLanguageSelectorContent,
|
||||
CodeBlockLanguageSelectorItem,
|
||||
CodeBlockLanguageSelectorTrigger,
|
||||
CodeBlockLanguageSelectorValue,
|
||||
CodeBlockTitle,
|
||||
} from "@/components/ai-elements/code-block";
|
||||
import { FileIcon } from "lucide-react";
|
||||
import { useCallback, useState } from "react";
|
||||
import type { BundledLanguage } from "shiki";
|
||||
|
||||
const codeExamples = {
|
||||
go: {
|
||||
code: `package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func greet(name string) string {
|
||||
return fmt.Sprintf("Hello, %s!", name)
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(greet("World"))
|
||||
}`,
|
||||
filename: "greet.go",
|
||||
},
|
||||
python: {
|
||||
code: `def greet(name: str) -> str:
|
||||
return f"Hello, {name}!"
|
||||
|
||||
print(greet("World"))`,
|
||||
filename: "greet.py",
|
||||
},
|
||||
rust: {
|
||||
code: `fn greet(name: &str) -> String {
|
||||
format!("Hello, {}!", name)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", greet("World"));
|
||||
}`,
|
||||
filename: "greet.rs",
|
||||
},
|
||||
typescript: {
|
||||
code: `function greet(name: string): string {
|
||||
return \`Hello, \${name}!\`;
|
||||
}
|
||||
|
||||
console.log(greet("World"));`,
|
||||
filename: "greet.ts",
|
||||
},
|
||||
} as const;
|
||||
|
||||
type Language = keyof typeof codeExamples;
|
||||
|
||||
const languages: { value: Language; label: string }[] = [
|
||||
{ label: "TypeScript", value: "typescript" },
|
||||
{ label: "Python", value: "python" },
|
||||
{ label: "Rust", value: "rust" },
|
||||
{ label: "Go", value: "go" },
|
||||
];
|
||||
|
||||
const handleCopy = () => {
|
||||
console.log("Copied code to clipboard");
|
||||
};
|
||||
|
||||
const handleCopyError = () => {
|
||||
console.error("Failed to copy code to clipboard");
|
||||
};
|
||||
|
||||
const Example = () => {
|
||||
const [language, setLanguage] = useState<Language>("typescript");
|
||||
const { code, filename } = codeExamples[language];
|
||||
|
||||
const handleLanguageChange = useCallback((value: string) => {
|
||||
setLanguage(value as Language);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<CodeBlock code={code} language={language as BundledLanguage}>
|
||||
<CodeBlockHeader>
|
||||
<CodeBlockTitle>
|
||||
<FileIcon size={14} />
|
||||
<CodeBlockFilename>{filename}</CodeBlockFilename>
|
||||
</CodeBlockTitle>
|
||||
<CodeBlockActions>
|
||||
<CodeBlockLanguageSelector
|
||||
onValueChange={handleLanguageChange}
|
||||
value={language}
|
||||
>
|
||||
<CodeBlockLanguageSelectorTrigger>
|
||||
<CodeBlockLanguageSelectorValue />
|
||||
</CodeBlockLanguageSelectorTrigger>
|
||||
<CodeBlockLanguageSelectorContent>
|
||||
{languages.map((lang) => (
|
||||
<CodeBlockLanguageSelectorItem
|
||||
key={lang.value}
|
||||
value={lang.value}
|
||||
>
|
||||
{lang.label}
|
||||
</CodeBlockLanguageSelectorItem>
|
||||
))}
|
||||
</CodeBlockLanguageSelectorContent>
|
||||
</CodeBlockLanguageSelector>
|
||||
<CodeBlockCopyButton onCopy={handleCopy} onError={handleCopyError} />
|
||||
</CodeBlockActions>
|
||||
</CodeBlockHeader>
|
||||
</CodeBlock>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,94 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Commit,
|
||||
CommitActions,
|
||||
CommitAuthor,
|
||||
CommitAuthorAvatar,
|
||||
CommitContent,
|
||||
CommitCopyButton,
|
||||
CommitFile,
|
||||
CommitFileAdditions,
|
||||
CommitFileChanges,
|
||||
CommitFileDeletions,
|
||||
CommitFileIcon,
|
||||
CommitFileInfo,
|
||||
CommitFilePath,
|
||||
CommitFileStatus,
|
||||
CommitFiles,
|
||||
CommitHash,
|
||||
CommitHeader,
|
||||
CommitInfo,
|
||||
CommitMessage,
|
||||
CommitMetadata,
|
||||
CommitSeparator,
|
||||
CommitTimestamp,
|
||||
} from "@/components/ai-elements/commit";
|
||||
|
||||
const handleCopy = () => {
|
||||
console.log("Copied hash!");
|
||||
};
|
||||
|
||||
const hash = "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0";
|
||||
const timestamp = new Date(Date.now() - 1000 * 60 * 60 * 2);
|
||||
|
||||
const files = [
|
||||
{
|
||||
additions: 150,
|
||||
deletions: 0,
|
||||
path: "src/auth/login.tsx",
|
||||
status: "added" as const,
|
||||
},
|
||||
{
|
||||
additions: 45,
|
||||
deletions: 0,
|
||||
path: "src/auth/logout.tsx",
|
||||
status: "added" as const,
|
||||
},
|
||||
{
|
||||
additions: 23,
|
||||
deletions: 8,
|
||||
path: "src/lib/session.ts",
|
||||
status: "modified" as const,
|
||||
},
|
||||
];
|
||||
|
||||
const Example = () => (
|
||||
<Commit>
|
||||
<CommitHeader>
|
||||
<CommitAuthor>
|
||||
<CommitAuthorAvatar initials="HB" />
|
||||
</CommitAuthor>
|
||||
<CommitInfo>
|
||||
<CommitMessage>feat: Add user authentication flow</CommitMessage>
|
||||
<CommitMetadata>
|
||||
<CommitHash>{hash.slice(0, 7)}</CommitHash>
|
||||
<CommitSeparator />
|
||||
<CommitTimestamp date={timestamp} />
|
||||
</CommitMetadata>
|
||||
</CommitInfo>
|
||||
<CommitActions>
|
||||
<CommitCopyButton hash={hash} onCopy={handleCopy} />
|
||||
</CommitActions>
|
||||
</CommitHeader>
|
||||
<CommitContent>
|
||||
<CommitFiles>
|
||||
{files.map((file) => (
|
||||
<CommitFile key={file.path}>
|
||||
<CommitFileInfo>
|
||||
<CommitFileStatus status={file.status} />
|
||||
<CommitFileIcon />
|
||||
<CommitFilePath>{file.path}</CommitFilePath>
|
||||
</CommitFileInfo>
|
||||
<CommitFileChanges>
|
||||
<CommitFileAdditions count={file.additions} />
|
||||
<CommitFileDeletions count={file.deletions} />
|
||||
</CommitFileChanges>
|
||||
</CommitFile>
|
||||
))}
|
||||
</CommitFiles>
|
||||
</CommitContent>
|
||||
</Commit>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Confirmation,
|
||||
ConfirmationAccepted,
|
||||
ConfirmationRejected,
|
||||
ConfirmationRequest,
|
||||
ConfirmationTitle,
|
||||
} from "@/components/ai-elements/confirmation";
|
||||
import { CheckIcon, XIcon } from "lucide-react";
|
||||
import { nanoid } from "nanoid";
|
||||
|
||||
const Example = () => (
|
||||
<div className="w-full max-w-2xl">
|
||||
<Confirmation
|
||||
approval={{ approved: true, id: nanoid() }}
|
||||
state="approval-responded"
|
||||
>
|
||||
<ConfirmationTitle>
|
||||
<ConfirmationRequest>
|
||||
This tool wants to delete the file{" "}
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 text-sm">
|
||||
/tmp/example.txt
|
||||
</code>
|
||||
. Do you approve this action?
|
||||
</ConfirmationRequest>
|
||||
<ConfirmationAccepted>
|
||||
<CheckIcon className="size-4 text-green-600 dark:text-green-400" />
|
||||
<span>You approved this tool execution</span>
|
||||
</ConfirmationAccepted>
|
||||
<ConfirmationRejected>
|
||||
<XIcon className="size-4 text-destructive" />
|
||||
<span>You rejected this tool execution</span>
|
||||
</ConfirmationRejected>
|
||||
</ConfirmationTitle>
|
||||
</Confirmation>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Confirmation,
|
||||
ConfirmationAccepted,
|
||||
ConfirmationRejected,
|
||||
ConfirmationRequest,
|
||||
ConfirmationTitle,
|
||||
} from "@/components/ai-elements/confirmation";
|
||||
import { CheckIcon, XIcon } from "lucide-react";
|
||||
import { nanoid } from "nanoid";
|
||||
|
||||
const Example = () => (
|
||||
<div className="w-full max-w-2xl">
|
||||
<Confirmation
|
||||
approval={{ approved: false, id: nanoid() }}
|
||||
state="output-denied"
|
||||
>
|
||||
<ConfirmationTitle>
|
||||
<ConfirmationRequest>
|
||||
This tool wants to delete the file{" "}
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 text-sm">
|
||||
/tmp/example.txt
|
||||
</code>
|
||||
. Do you approve this action?
|
||||
</ConfirmationRequest>
|
||||
<ConfirmationAccepted>
|
||||
<CheckIcon className="size-4 text-green-600 dark:text-green-400" />
|
||||
<span>You approved this tool execution</span>
|
||||
</ConfirmationAccepted>
|
||||
<ConfirmationRejected>
|
||||
<XIcon className="size-4 text-destructive" />
|
||||
<span>You rejected this tool execution</span>
|
||||
</ConfirmationRejected>
|
||||
</ConfirmationTitle>
|
||||
</Confirmation>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Confirmation,
|
||||
ConfirmationAccepted,
|
||||
ConfirmationAction,
|
||||
ConfirmationActions,
|
||||
ConfirmationRejected,
|
||||
ConfirmationRequest,
|
||||
ConfirmationTitle,
|
||||
} from "@/components/ai-elements/confirmation";
|
||||
import { CheckIcon, XIcon } from "lucide-react";
|
||||
import { nanoid } from "nanoid";
|
||||
|
||||
const handleReject = () => {
|
||||
// In production, call respondToConfirmationRequest with approved: false
|
||||
};
|
||||
|
||||
const handleApprove = () => {
|
||||
// In production, call respondToConfirmationRequest with approved: true
|
||||
};
|
||||
|
||||
const Example = () => (
|
||||
<div className="w-full max-w-2xl">
|
||||
<Confirmation approval={{ id: nanoid() }} state="approval-requested">
|
||||
<ConfirmationTitle>
|
||||
<ConfirmationRequest>
|
||||
This tool wants to execute a query on the production database:
|
||||
<code className="mt-2 block rounded bg-muted p-2 text-sm">
|
||||
SELECT * FROM users WHERE role = 'admin'
|
||||
</code>
|
||||
</ConfirmationRequest>
|
||||
<ConfirmationAccepted>
|
||||
<CheckIcon className="size-4 text-green-600 dark:text-green-400" />
|
||||
<span>You approved this tool execution</span>
|
||||
</ConfirmationAccepted>
|
||||
<ConfirmationRejected>
|
||||
<XIcon className="size-4 text-destructive" />
|
||||
<span>You rejected this tool execution</span>
|
||||
</ConfirmationRejected>
|
||||
</ConfirmationTitle>
|
||||
<ConfirmationActions>
|
||||
<ConfirmationAction onClick={handleReject} variant="outline">
|
||||
Reject
|
||||
</ConfirmationAction>
|
||||
<ConfirmationAction onClick={handleApprove} variant="default">
|
||||
Approve
|
||||
</ConfirmationAction>
|
||||
</ConfirmationActions>
|
||||
</Confirmation>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Confirmation,
|
||||
ConfirmationAccepted,
|
||||
ConfirmationAction,
|
||||
ConfirmationActions,
|
||||
ConfirmationRejected,
|
||||
ConfirmationRequest,
|
||||
ConfirmationTitle,
|
||||
} from "@/components/ai-elements/confirmation";
|
||||
import { CheckIcon, XIcon } from "lucide-react";
|
||||
import { nanoid } from "nanoid";
|
||||
|
||||
const handleReject = () => {
|
||||
// In production, call respondToConfirmationRequest with approved: false
|
||||
};
|
||||
|
||||
const handleApprove = () => {
|
||||
// In production, call respondToConfirmationRequest with approved: true
|
||||
};
|
||||
|
||||
const Example = () => (
|
||||
<div className="w-full max-w-2xl">
|
||||
<Confirmation approval={{ id: nanoid() }} state="approval-requested">
|
||||
<ConfirmationTitle>
|
||||
<ConfirmationRequest>
|
||||
This tool wants to delete the file{" "}
|
||||
<code className="inline rounded bg-muted px-1.5 py-0.5 text-sm">
|
||||
/tmp/example.txt
|
||||
</code>
|
||||
. Do you approve this action?
|
||||
</ConfirmationRequest>
|
||||
<ConfirmationAccepted>
|
||||
<CheckIcon className="size-4 text-green-600 dark:text-green-400" />
|
||||
<span>You approved this tool execution</span>
|
||||
</ConfirmationAccepted>
|
||||
<ConfirmationRejected>
|
||||
<XIcon className="size-4 text-destructive" />
|
||||
<span>You rejected this tool execution</span>
|
||||
</ConfirmationRejected>
|
||||
</ConfirmationTitle>
|
||||
<ConfirmationActions>
|
||||
<ConfirmationAction onClick={handleReject} variant="outline">
|
||||
Reject
|
||||
</ConfirmationAction>
|
||||
<ConfirmationAction onClick={handleApprove} variant="default">
|
||||
Approve
|
||||
</ConfirmationAction>
|
||||
</ConfirmationActions>
|
||||
</Confirmation>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Context,
|
||||
ContextCacheUsage,
|
||||
ContextContent,
|
||||
ContextContentBody,
|
||||
ContextContentFooter,
|
||||
ContextContentHeader,
|
||||
ContextInputUsage,
|
||||
ContextOutputUsage,
|
||||
ContextReasoningUsage,
|
||||
ContextTrigger,
|
||||
} from "@/components/ai-elements/context";
|
||||
|
||||
const Example = () => (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Context
|
||||
maxTokens={128_000}
|
||||
modelId="openai:gpt-5"
|
||||
usage={{
|
||||
cachedInputTokens: 0,
|
||||
inputTokens: 32_000,
|
||||
outputTokens: 8000,
|
||||
reasoningTokens: 0,
|
||||
totalTokens: 40_000,
|
||||
}}
|
||||
usedTokens={40_000}
|
||||
>
|
||||
<ContextTrigger />
|
||||
<ContextContent>
|
||||
<ContextContentHeader />
|
||||
<ContextContentBody>
|
||||
<ContextInputUsage />
|
||||
<ContextOutputUsage />
|
||||
<ContextReasoningUsage />
|
||||
<ContextCacheUsage />
|
||||
</ContextContentBody>
|
||||
<ContextContentFooter />
|
||||
</ContextContent>
|
||||
</Context>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Conversation,
|
||||
ConversationContent,
|
||||
ConversationDownload,
|
||||
ConversationEmptyState,
|
||||
ConversationScrollButton,
|
||||
} from "@/components/ai-elements/conversation";
|
||||
import { Message, MessageContent } from "@/components/ai-elements/message";
|
||||
import { MessageSquareIcon } from "lucide-react";
|
||||
import { nanoid } from "nanoid";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
const messages: {
|
||||
key: string;
|
||||
content: string;
|
||||
role: "user" | "assistant";
|
||||
}[] = [
|
||||
{
|
||||
content: "Hello, how are you?",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content: "I'm good, thank you! How can I assist you today?",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "I'm looking for information about your services.",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content:
|
||||
"Sure! We offer a variety of AI solutions. What are you interested in?",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "I'm interested in natural language processing tools.",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content: "Great choice! We have several NLP APIs. Would you like a demo?",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "Yes, a demo would be helpful.",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content: "Alright, I can show you a sentiment analysis example. Ready?",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "Yes, please proceed.",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content: "Here is a sample: 'I love this product!' → Positive sentiment.",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "Impressive! Can it handle multiple languages?",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content: "Absolutely, our models support over 20 languages.",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "How do I get started with the API?",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content: "You can sign up on our website and get an API key instantly.",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "Is there a free trial available?",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content: "Yes, we offer a 14-day free trial with full access.",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "What kind of support do you provide?",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content: "We provide 24/7 chat and email support for all users.",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
{
|
||||
content: "Thank you for the information!",
|
||||
key: nanoid(),
|
||||
role: "user",
|
||||
},
|
||||
{
|
||||
content: "You're welcome! Let me know if you have any more questions.",
|
||||
key: nanoid(),
|
||||
role: "assistant",
|
||||
},
|
||||
];
|
||||
|
||||
const Example = () => {
|
||||
const [visibleMessages, setVisibleMessages] = useState<
|
||||
{
|
||||
key: string;
|
||||
content: string;
|
||||
role: "user" | "assistant";
|
||||
}[]
|
||||
>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let currentIndex = 0;
|
||||
const interval = setInterval(() => {
|
||||
if (currentIndex < messages.length && messages[currentIndex]) {
|
||||
const currentMessage = messages[currentIndex];
|
||||
setVisibleMessages((prev) => [
|
||||
...prev,
|
||||
{
|
||||
content: currentMessage.content,
|
||||
key: currentMessage.key,
|
||||
role: currentMessage.role,
|
||||
},
|
||||
]);
|
||||
currentIndex += 1;
|
||||
} else {
|
||||
clearInterval(interval);
|
||||
}
|
||||
}, 500);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Conversation className="relative size-full">
|
||||
<ConversationContent>
|
||||
{visibleMessages.length === 0 ? (
|
||||
<ConversationEmptyState
|
||||
description="Messages will appear here as the conversation progresses."
|
||||
icon={<MessageSquareIcon className="size-6" />}
|
||||
title="Start a conversation"
|
||||
/>
|
||||
) : (
|
||||
visibleMessages.map(({ key, content, role }) => (
|
||||
<Message from={role} key={key}>
|
||||
<MessageContent>{content}</MessageContent>
|
||||
</Message>
|
||||
))
|
||||
)}
|
||||
</ConversationContent>
|
||||
<ConversationDownload messages={visibleMessages} />
|
||||
<ConversationScrollButton />
|
||||
</Conversation>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
EnvironmentVariable,
|
||||
EnvironmentVariableCopyButton,
|
||||
EnvironmentVariableGroup,
|
||||
EnvironmentVariableName,
|
||||
EnvironmentVariableRequired,
|
||||
EnvironmentVariables,
|
||||
EnvironmentVariablesContent,
|
||||
EnvironmentVariablesHeader,
|
||||
EnvironmentVariablesTitle,
|
||||
EnvironmentVariablesToggle,
|
||||
EnvironmentVariableValue,
|
||||
} from "@/components/ai-elements/environment-variables";
|
||||
|
||||
const variables = [
|
||||
{
|
||||
name: "DATABASE_URL",
|
||||
required: true,
|
||||
value: "postgresql://localhost:5432/mydb",
|
||||
},
|
||||
{ name: "API_KEY", required: true, value: "sk-1234567890abcdef" },
|
||||
{ name: "NODE_ENV", required: false, value: "production" },
|
||||
{ name: "PORT", required: false, value: "3000" },
|
||||
];
|
||||
|
||||
const handleCopy = () => {
|
||||
console.log("Copied!");
|
||||
};
|
||||
|
||||
const Example = () => (
|
||||
<EnvironmentVariables defaultShowValues={false}>
|
||||
<EnvironmentVariablesHeader>
|
||||
<EnvironmentVariablesTitle />
|
||||
<EnvironmentVariablesToggle />
|
||||
</EnvironmentVariablesHeader>
|
||||
<EnvironmentVariablesContent>
|
||||
{variables.map((variable) => (
|
||||
<EnvironmentVariable
|
||||
key={variable.name}
|
||||
name={variable.name}
|
||||
value={variable.value}
|
||||
>
|
||||
<EnvironmentVariableGroup>
|
||||
<EnvironmentVariableName />
|
||||
{variable.required && <EnvironmentVariableRequired />}
|
||||
</EnvironmentVariableGroup>
|
||||
<EnvironmentVariableGroup>
|
||||
<EnvironmentVariableValue />
|
||||
<EnvironmentVariableCopyButton
|
||||
copyFormat="export"
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
</EnvironmentVariableGroup>
|
||||
</EnvironmentVariable>
|
||||
))}
|
||||
</EnvironmentVariablesContent>
|
||||
</EnvironmentVariables>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
FileTree,
|
||||
FileTreeFile,
|
||||
FileTreeFolder,
|
||||
} from "@/components/ai-elements/file-tree";
|
||||
|
||||
const Example = () => (
|
||||
<FileTree>
|
||||
<FileTreeFolder name="src" path="src">
|
||||
<FileTreeFile name="index.ts" path="src/index.ts" />
|
||||
</FileTreeFolder>
|
||||
<FileTreeFile name="package.json" path="package.json" />
|
||||
</FileTree>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
FileTree,
|
||||
FileTreeFile,
|
||||
FileTreeFolder,
|
||||
} from "@/components/ai-elements/file-tree";
|
||||
|
||||
const Example = () => (
|
||||
<FileTree defaultExpanded={new Set(["src", "src/components"])}>
|
||||
<FileTreeFolder name="src" path="src">
|
||||
<FileTreeFolder name="components" path="src/components">
|
||||
<FileTreeFile name="button.tsx" path="src/components/button.tsx" />
|
||||
<FileTreeFile name="input.tsx" path="src/components/input.tsx" />
|
||||
</FileTreeFolder>
|
||||
<FileTreeFile name="index.ts" path="src/index.ts" />
|
||||
</FileTreeFolder>
|
||||
</FileTree>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
FileTree,
|
||||
FileTreeFile,
|
||||
FileTreeFolder,
|
||||
} from "@/components/ai-elements/file-tree";
|
||||
import { useState } from "react";
|
||||
|
||||
const Example = () => {
|
||||
const [selectedPath, setSelectedPath] = useState<string>();
|
||||
|
||||
return (
|
||||
<FileTree onSelect={setSelectedPath} selectedPath={selectedPath}>
|
||||
<FileTreeFolder name="src" path="src">
|
||||
<FileTreeFile name="app.tsx" path="src/app.tsx" />
|
||||
<FileTreeFile name="index.ts" path="src/index.ts" />
|
||||
</FileTreeFolder>
|
||||
<FileTreeFile name="package.json" path="package.json" />
|
||||
</FileTree>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
FileTree,
|
||||
FileTreeFile,
|
||||
FileTreeFolder,
|
||||
} from "@/components/ai-elements/file-tree";
|
||||
import { useState } from "react";
|
||||
|
||||
const Example = () => {
|
||||
const [selectedPath, setSelectedPath] = useState<string | undefined>();
|
||||
|
||||
return (
|
||||
<FileTree
|
||||
defaultExpanded={new Set(["src", "src/components"])}
|
||||
onSelect={setSelectedPath}
|
||||
selectedPath={selectedPath}
|
||||
>
|
||||
<FileTreeFolder name="src" path="src">
|
||||
<FileTreeFolder name="components" path="src/components">
|
||||
<FileTreeFile name="button.tsx" path="src/components/button.tsx" />
|
||||
<FileTreeFile name="input.tsx" path="src/components/input.tsx" />
|
||||
<FileTreeFile name="modal.tsx" path="src/components/modal.tsx" />
|
||||
</FileTreeFolder>
|
||||
<FileTreeFolder name="hooks" path="src/hooks">
|
||||
<FileTreeFile name="use-auth.ts" path="src/hooks/use-auth.ts" />
|
||||
<FileTreeFile name="use-theme.ts" path="src/hooks/use-theme.ts" />
|
||||
</FileTreeFolder>
|
||||
<FileTreeFolder name="lib" path="src/lib">
|
||||
<FileTreeFile name="utils.ts" path="src/lib/utils.ts" />
|
||||
</FileTreeFolder>
|
||||
<FileTreeFile name="app.tsx" path="src/app.tsx" />
|
||||
<FileTreeFile name="main.tsx" path="src/main.tsx" />
|
||||
</FileTreeFolder>
|
||||
<FileTreeFile name="package.json" path="package.json" />
|
||||
<FileTreeFile name="tsconfig.json" path="tsconfig.json" />
|
||||
<FileTreeFile name="README.md" path="README.md" />
|
||||
</FileTree>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,97 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
InlineCitation,
|
||||
InlineCitationCard,
|
||||
InlineCitationCardBody,
|
||||
InlineCitationCardTrigger,
|
||||
InlineCitationCarousel,
|
||||
InlineCitationCarouselContent,
|
||||
InlineCitationCarouselHeader,
|
||||
InlineCitationCarouselIndex,
|
||||
InlineCitationCarouselItem,
|
||||
InlineCitationCarouselNext,
|
||||
InlineCitationCarouselPrev,
|
||||
InlineCitationSource,
|
||||
InlineCitationText,
|
||||
} from "@/components/ai-elements/inline-citation";
|
||||
|
||||
const citation = {
|
||||
sources: [
|
||||
{
|
||||
description:
|
||||
"A comprehensive study on the recent developments in natural language processing technologies and their applications.",
|
||||
title: "Advances in Natural Language Processing",
|
||||
url: "https://example.com/nlp-advances",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"An overview of the most significant machine learning breakthroughs in the past year.",
|
||||
title: "Breakthroughs in Machine Learning",
|
||||
url: "https://mlnews.org/breakthroughs",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"A report on how artificial intelligence is transforming healthcare and diagnostics.",
|
||||
title: "AI in Healthcare: Current Trends",
|
||||
url: "https://healthai.com/trends",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"A discussion on the ethical considerations and challenges in the development of AI.",
|
||||
title: "Ethics of Artificial Intelligence",
|
||||
url: "https://aiethics.org/overview",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Insights into the technical challenges and solutions for scaling deep learning architectures.",
|
||||
title: "Scaling Deep Learning Models",
|
||||
url: "https://deeplearninghub.com/scaling-models",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"A summary of the latest benchmarks and evaluation metrics for natural language understanding systems.",
|
||||
title: "Natural Language Understanding Benchmarks",
|
||||
url: "https://nlubenchmarks.com/latest",
|
||||
},
|
||||
],
|
||||
text: "The technology continues to evolve rapidly, with new breakthroughs being announced regularly",
|
||||
};
|
||||
|
||||
const Example = () => (
|
||||
<p className="text-sm leading-relaxed">
|
||||
According to recent studies, artificial intelligence has shown remarkable
|
||||
progress in natural language processing.{" "}
|
||||
<InlineCitation>
|
||||
<InlineCitationText>{citation.text}</InlineCitationText>
|
||||
<InlineCitationCard>
|
||||
<InlineCitationCardTrigger
|
||||
sources={citation.sources.map((source) => source.url)}
|
||||
/>
|
||||
<InlineCitationCardBody>
|
||||
<InlineCitationCarousel>
|
||||
<InlineCitationCarouselHeader>
|
||||
<InlineCitationCarouselPrev />
|
||||
<InlineCitationCarouselNext />
|
||||
<InlineCitationCarouselIndex />
|
||||
</InlineCitationCarouselHeader>
|
||||
<InlineCitationCarouselContent>
|
||||
{citation.sources.map((source) => (
|
||||
<InlineCitationCarouselItem key={source.url}>
|
||||
<InlineCitationSource
|
||||
description={source.description}
|
||||
title={source.title}
|
||||
url={source.url}
|
||||
/>
|
||||
</InlineCitationCarouselItem>
|
||||
))}
|
||||
</InlineCitationCarouselContent>
|
||||
</InlineCitationCarousel>
|
||||
</InlineCitationCardBody>
|
||||
</InlineCitationCard>
|
||||
</InlineCitation>
|
||||
.
|
||||
</p>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,104 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
JSXPreview,
|
||||
JSXPreviewContent,
|
||||
JSXPreviewError,
|
||||
} from "@/components/ai-elements/jsx-preview";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
const handleError = (error: Error) => {
|
||||
console.log("JSX Parse Error:", error);
|
||||
};
|
||||
|
||||
const fullJsx = `<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
<div className="flex items-center gap-4 mb-4">
|
||||
<div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<span className="text-primary text-xl font-bold">AI</span>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">AI-Generated Component</h2>
|
||||
<p className="text-sm text-muted-foreground">Rendered from JSX string</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm">This component was dynamically rendered from a JSX string. The JSXPreview component supports streaming mode, automatically closing unclosed tags as content arrives.</p>
|
||||
<div className="flex gap-2">
|
||||
<span className="inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800">React</span>
|
||||
<span className="inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800">Streaming</span>
|
||||
<span className="inline-flex items-center rounded-full bg-purple-100 px-2.5 py-0.5 text-xs font-medium text-purple-800">Dynamic</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 pt-4 border-t">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-xs text-muted-foreground">Generated just now</span>
|
||||
<button className="px-3 py-1.5 text-sm bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors">
|
||||
Learn more
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
const Example = () => {
|
||||
const [streamedJsx, setStreamedJsx] = useState(fullJsx);
|
||||
const [isStreaming, setIsStreaming] = useState(false);
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
const simulateStreaming = useCallback(() => {
|
||||
setIsStreaming(true);
|
||||
setStreamedJsx("");
|
||||
let index = 0;
|
||||
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
|
||||
intervalRef.current = setInterval(() => {
|
||||
if (index < fullJsx.length) {
|
||||
setStreamedJsx(fullJsx.slice(0, index + 15));
|
||||
index += 15;
|
||||
} else {
|
||||
setIsStreaming(false);
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current);
|
||||
intervalRef.current = null;
|
||||
}
|
||||
}
|
||||
}, 30);
|
||||
}, []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Button
|
||||
disabled={isStreaming}
|
||||
onClick={simulateStreaming}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
>
|
||||
{isStreaming ? "Streaming..." : "Simulate Streaming"}
|
||||
</Button>
|
||||
|
||||
<JSXPreview
|
||||
className="min-h-[200px]"
|
||||
isStreaming={isStreaming}
|
||||
jsx={streamedJsx}
|
||||
onError={handleError}
|
||||
>
|
||||
<JSXPreviewContent />
|
||||
<JSXPreviewError className="mt-2" />
|
||||
</JSXPreview>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,365 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentPreview,
|
||||
AttachmentRemove,
|
||||
Attachments,
|
||||
} from "@/components/ai-elements/attachments";
|
||||
import {
|
||||
Message,
|
||||
MessageAction,
|
||||
MessageActions,
|
||||
MessageBranch,
|
||||
MessageBranchContent,
|
||||
MessageBranchNext,
|
||||
MessageBranchPage,
|
||||
MessageBranchPrevious,
|
||||
MessageBranchSelector,
|
||||
MessageContent,
|
||||
MessageResponse,
|
||||
MessageToolbar,
|
||||
} from "@/components/ai-elements/message";
|
||||
import {
|
||||
CopyIcon,
|
||||
RefreshCcwIcon,
|
||||
ThumbsDownIcon,
|
||||
ThumbsUpIcon,
|
||||
} from "lucide-react";
|
||||
import { nanoid } from "nanoid";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const messages: {
|
||||
key: string;
|
||||
from: "user" | "assistant";
|
||||
versions?: { id: string; content: string }[];
|
||||
content?: string;
|
||||
attachments?: {
|
||||
id: string;
|
||||
type: "file";
|
||||
url: string;
|
||||
mediaType?: string;
|
||||
filename?: string;
|
||||
}[];
|
||||
}[] = [
|
||||
{
|
||||
attachments: [
|
||||
{
|
||||
filename: "palace-of-fine-arts.jpg",
|
||||
id: nanoid(),
|
||||
mediaType: "image/jpeg",
|
||||
type: "file",
|
||||
url: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=400&fit=crop",
|
||||
},
|
||||
{
|
||||
filename: "react-hooks-guide.pdf",
|
||||
id: nanoid(),
|
||||
mediaType: "application/pdf",
|
||||
type: "file",
|
||||
url: "",
|
||||
},
|
||||
],
|
||||
content: "How do React hooks work and when should I use them?",
|
||||
from: "user",
|
||||
key: nanoid(),
|
||||
},
|
||||
{
|
||||
from: "assistant",
|
||||
key: nanoid(),
|
||||
versions: [
|
||||
{
|
||||
content: `# React Hooks Guide
|
||||
|
||||
React hooks are functions that let you "hook into" React state and lifecycle features from function components. Here's what you need to know:
|
||||
|
||||
## Core Hooks
|
||||
|
||||
### useState
|
||||
Adds state to functional components:
|
||||
|
||||
\`\`\`jsx
|
||||
const [count, setCount] = useState(0);
|
||||
|
||||
return (
|
||||
<button onClick={() => setCount(count + 1)}>
|
||||
Count: {count}
|
||||
</button>
|
||||
);
|
||||
\`\`\`
|
||||
|
||||
### useEffect
|
||||
Handles side effects (data fetching, subscriptions, DOM updates):
|
||||
|
||||
\`\`\`jsx
|
||||
useEffect(() => {
|
||||
document.title = \`You clicked \${count} times\`;
|
||||
|
||||
// Cleanup function (optional)
|
||||
return () => {
|
||||
document.title = 'React App';
|
||||
};
|
||||
}, [count]); // Dependency array
|
||||
\`\`\`
|
||||
|
||||
## When to Use Hooks
|
||||
|
||||
- ✅ **Function components** - Hooks only work in function components
|
||||
- ✅ **Replacing class components** - Modern React favors hooks over classes
|
||||
- ✅ **Sharing stateful logic** - Create custom hooks to reuse logic
|
||||
- ❌ **Class components** - Use lifecycle methods instead
|
||||
|
||||
## Rules of Hooks
|
||||
|
||||
1. Only call hooks at the **top level** (not inside loops, conditions, or nested functions)
|
||||
2. Only call hooks from **React functions** (components or custom hooks)
|
||||
|
||||
Would you like to explore more advanced hooks like \`useCallback\` or \`useMemo\`?`,
|
||||
id: nanoid(),
|
||||
},
|
||||
{
|
||||
content: `React hooks are special functions that let you use React features in function components. The most common ones are:
|
||||
|
||||
- **useState** - for managing component state
|
||||
- **useEffect** - for side effects like data fetching
|
||||
- **useContext** - for consuming context values
|
||||
- **useRef** - for accessing DOM elements
|
||||
|
||||
Here's a simple example:
|
||||
|
||||
\`\`\`jsx
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0);
|
||||
|
||||
return (
|
||||
<button onClick={() => setCount(count + 1)}>
|
||||
Clicked {count} times
|
||||
</button>
|
||||
);
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
Which specific hook would you like to learn more about?`,
|
||||
id: nanoid(),
|
||||
},
|
||||
{
|
||||
content: `Absolutely! React hooks are a powerful feature introduced in React 16.8. They solve several problems:
|
||||
|
||||
## Key Benefits
|
||||
|
||||
1. **Simpler code** - No need for class components
|
||||
2. **Reusable logic** - Extract stateful logic into custom hooks
|
||||
3. **Better organization** - Group related code together
|
||||
|
||||
## Most Popular Hooks
|
||||
|
||||
| Hook | Purpose |
|
||||
|------|---------|
|
||||
| useState | Add state to components |
|
||||
| useEffect | Handle side effects |
|
||||
| useContext | Access context values |
|
||||
| useReducer | Complex state logic |
|
||||
| useCallback | Memoize functions |
|
||||
| useMemo | Memoize values |
|
||||
|
||||
The beauty of hooks is that they let you reuse stateful logic without changing your component hierarchy. Want to dive into a specific hook?`,
|
||||
id: nanoid(),
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const handleCopy = (content: string) => {
|
||||
navigator.clipboard.writeText(content);
|
||||
};
|
||||
|
||||
const handleRetry = () => {
|
||||
console.log("Retrying...");
|
||||
};
|
||||
|
||||
interface LikeActionProps {
|
||||
messageKey: string;
|
||||
isLiked: boolean;
|
||||
onToggle: (key: string) => void;
|
||||
}
|
||||
|
||||
const LikeAction = memo(
|
||||
({ messageKey, isLiked, onToggle }: LikeActionProps) => {
|
||||
const handleClick = useCallback(
|
||||
() => onToggle(messageKey),
|
||||
[messageKey, onToggle]
|
||||
);
|
||||
return (
|
||||
<MessageAction
|
||||
label="Like"
|
||||
onClick={handleClick}
|
||||
tooltip="Like this response"
|
||||
>
|
||||
<ThumbsUpIcon
|
||||
className="size-4"
|
||||
fill={isLiked ? "currentColor" : "none"}
|
||||
/>
|
||||
</MessageAction>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
LikeAction.displayName = "LikeAction";
|
||||
|
||||
interface DislikeActionProps {
|
||||
messageKey: string;
|
||||
isDisliked: boolean;
|
||||
onToggle: (key: string) => void;
|
||||
}
|
||||
|
||||
const DislikeAction = memo(
|
||||
({ messageKey, isDisliked, onToggle }: DislikeActionProps) => {
|
||||
const handleClick = useCallback(
|
||||
() => onToggle(messageKey),
|
||||
[messageKey, onToggle]
|
||||
);
|
||||
return (
|
||||
<MessageAction
|
||||
label="Dislike"
|
||||
onClick={handleClick}
|
||||
tooltip="Dislike this response"
|
||||
>
|
||||
<ThumbsDownIcon
|
||||
className="size-4"
|
||||
fill={isDisliked ? "currentColor" : "none"}
|
||||
/>
|
||||
</MessageAction>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
DislikeAction.displayName = "DislikeAction";
|
||||
|
||||
interface CopyActionProps {
|
||||
content: string;
|
||||
}
|
||||
|
||||
const CopyAction = memo(({ content }: CopyActionProps) => {
|
||||
const handleClick = useCallback(() => handleCopy(content), [content]);
|
||||
return (
|
||||
<MessageAction
|
||||
label="Copy"
|
||||
onClick={handleClick}
|
||||
tooltip="Copy to clipboard"
|
||||
>
|
||||
<CopyIcon className="size-4" />
|
||||
</MessageAction>
|
||||
);
|
||||
});
|
||||
|
||||
CopyAction.displayName = "CopyAction";
|
||||
|
||||
const Example = () => {
|
||||
const [liked, setLiked] = useState<Record<string, boolean>>({});
|
||||
const [disliked, setDisliked] = useState<Record<string, boolean>>({});
|
||||
|
||||
const handleToggleLike = useCallback((key: string) => {
|
||||
setLiked((prev) => ({ ...prev, [key]: !prev[key] }));
|
||||
}, []);
|
||||
|
||||
const handleToggleDislike = useCallback((key: string) => {
|
||||
setDisliked((prev) => ({ ...prev, [key]: !prev[key] }));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Demo component with complex rendering logic */}
|
||||
{messages.map((message) => (
|
||||
<Message from={message.from} key={message.key}>
|
||||
{message.versions?.length && message.versions.length > 1 ? (
|
||||
<MessageBranch defaultBranch={0} key={message.key}>
|
||||
<MessageBranchContent>
|
||||
{message.versions?.map((version) => (
|
||||
<MessageContent key={version.id}>
|
||||
<MessageResponse>{version.content}</MessageResponse>
|
||||
</MessageContent>
|
||||
))}
|
||||
</MessageBranchContent>
|
||||
{message.from === "assistant" && (
|
||||
<MessageToolbar>
|
||||
<MessageBranchSelector>
|
||||
<MessageBranchPrevious />
|
||||
<MessageBranchPage />
|
||||
<MessageBranchNext />
|
||||
</MessageBranchSelector>
|
||||
<MessageActions>
|
||||
<MessageAction
|
||||
label="Retry"
|
||||
onClick={handleRetry}
|
||||
tooltip="Regenerate response"
|
||||
>
|
||||
<RefreshCcwIcon className="size-4" />
|
||||
</MessageAction>
|
||||
<LikeAction
|
||||
isLiked={liked[message.key] ?? false}
|
||||
messageKey={message.key}
|
||||
onToggle={handleToggleLike}
|
||||
/>
|
||||
<DislikeAction
|
||||
isDisliked={disliked[message.key] ?? false}
|
||||
messageKey={message.key}
|
||||
onToggle={handleToggleDislike}
|
||||
/>
|
||||
<CopyAction
|
||||
content={
|
||||
message.versions?.find((v) => v.id)?.content || ""
|
||||
}
|
||||
/>
|
||||
</MessageActions>
|
||||
</MessageToolbar>
|
||||
)}
|
||||
</MessageBranch>
|
||||
) : (
|
||||
<div key={message.key}>
|
||||
{message.attachments && message.attachments.length > 0 && (
|
||||
<Attachments className="mb-2" variant="grid">
|
||||
{message.attachments.map((attachment) => (
|
||||
<Attachment data={attachment} key={attachment.id}>
|
||||
<AttachmentPreview />
|
||||
<AttachmentRemove />
|
||||
</Attachment>
|
||||
))}
|
||||
</Attachments>
|
||||
)}
|
||||
<MessageContent>
|
||||
{message.from === "assistant" ? (
|
||||
<MessageResponse>{message.content}</MessageResponse>
|
||||
) : (
|
||||
message.content
|
||||
)}
|
||||
</MessageContent>
|
||||
{message.from === "assistant" && message.versions && (
|
||||
<MessageActions>
|
||||
<MessageAction
|
||||
label="Retry"
|
||||
onClick={handleRetry}
|
||||
tooltip="Regenerate response"
|
||||
>
|
||||
<RefreshCcwIcon className="size-4" />
|
||||
</MessageAction>
|
||||
<LikeAction
|
||||
isLiked={liked[message.key] ?? false}
|
||||
messageKey={message.key}
|
||||
onToggle={handleToggleLike}
|
||||
/>
|
||||
<DislikeAction
|
||||
isDisliked={disliked[message.key] ?? false}
|
||||
messageKey={message.key}
|
||||
onToggle={handleToggleDislike}
|
||||
/>
|
||||
<CopyAction content={message.content || ""} />
|
||||
</MessageActions>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Message>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
MicSelector,
|
||||
MicSelectorContent,
|
||||
MicSelectorEmpty,
|
||||
MicSelectorInput,
|
||||
MicSelectorItem,
|
||||
MicSelectorLabel,
|
||||
MicSelectorList,
|
||||
MicSelectorTrigger,
|
||||
MicSelectorValue,
|
||||
} from "@/components/ai-elements/mic-selector";
|
||||
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
console.log("MicSelector is open?", open);
|
||||
};
|
||||
|
||||
const handleValueChange = (newValue: string) => {
|
||||
console.log("MicSelector value:", newValue);
|
||||
};
|
||||
|
||||
const Example = () => (
|
||||
<div className="flex size-full flex-col items-center justify-center gap-4">
|
||||
<MicSelector
|
||||
onOpenChange={handleOpenChange}
|
||||
onValueChange={handleValueChange}
|
||||
>
|
||||
<MicSelectorTrigger className="w-full max-w-sm">
|
||||
<MicSelectorValue />
|
||||
</MicSelectorTrigger>
|
||||
<MicSelectorContent>
|
||||
<MicSelectorInput />
|
||||
<MicSelectorEmpty />
|
||||
<MicSelectorList>
|
||||
{(devices) =>
|
||||
devices.map((device) => (
|
||||
<MicSelectorItem key={device.deviceId} value={device.deviceId}>
|
||||
<MicSelectorLabel device={device} />
|
||||
</MicSelectorItem>
|
||||
))
|
||||
}
|
||||
</MicSelectorList>
|
||||
</MicSelectorContent>
|
||||
</MicSelector>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,365 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ModelSelector,
|
||||
ModelSelectorContent,
|
||||
ModelSelectorEmpty,
|
||||
ModelSelectorGroup,
|
||||
ModelSelectorInput,
|
||||
ModelSelectorItem,
|
||||
ModelSelectorList,
|
||||
ModelSelectorLogo,
|
||||
ModelSelectorLogoGroup,
|
||||
ModelSelectorName,
|
||||
ModelSelectorTrigger,
|
||||
} from "@/components/ai-elements/model-selector";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const models = [
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "gpt-4o",
|
||||
name: "GPT-4o",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "gpt-4o-mini",
|
||||
name: "GPT-4o Mini",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "o1",
|
||||
name: "o1",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "o1-mini",
|
||||
name: "o1 Mini",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-opus-4-20250514",
|
||||
name: "Claude 4 Opus",
|
||||
providers: ["anthropic", "azure", "google-vertex", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-sonnet-4-20250514",
|
||||
name: "Claude 4 Sonnet",
|
||||
providers: ["anthropic", "azure", "google-vertex", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-3.5-sonnet",
|
||||
name: "Claude 3.5 Sonnet",
|
||||
providers: ["anthropic", "azure", "google-vertex", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-3.5-haiku",
|
||||
name: "Claude 3.5 Haiku",
|
||||
providers: ["anthropic", "azure", "google-vertex", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Google",
|
||||
chefSlug: "google",
|
||||
id: "gemini-2.0-flash-exp",
|
||||
name: "Gemini 2.0 Flash",
|
||||
providers: ["google", "google-vertex"],
|
||||
},
|
||||
{
|
||||
chef: "Google",
|
||||
chefSlug: "google",
|
||||
id: "gemini-1.5-pro",
|
||||
name: "Gemini 1.5 Pro",
|
||||
providers: ["google", "google-vertex"],
|
||||
},
|
||||
{
|
||||
chef: "Google",
|
||||
chefSlug: "google",
|
||||
id: "gemini-1.5-flash",
|
||||
name: "Gemini 1.5 Flash",
|
||||
providers: ["google", "google-vertex"],
|
||||
},
|
||||
{
|
||||
chef: "Meta",
|
||||
chefSlug: "llama",
|
||||
id: "llama-3.3-70b",
|
||||
name: "Llama 3.3 70B",
|
||||
providers: ["groq", "togetherai", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Meta",
|
||||
chefSlug: "llama",
|
||||
id: "llama-3.1-405b",
|
||||
name: "Llama 3.1 405B",
|
||||
providers: ["togetherai", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Meta",
|
||||
chefSlug: "llama",
|
||||
id: "llama-3.1-70b",
|
||||
name: "Llama 3.1 70B",
|
||||
providers: ["groq", "togetherai", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Meta",
|
||||
chefSlug: "llama",
|
||||
id: "llama-3.1-8b",
|
||||
name: "Llama 3.1 8B",
|
||||
providers: ["groq", "togetherai"],
|
||||
},
|
||||
{
|
||||
chef: "DeepSeek",
|
||||
chefSlug: "deepseek",
|
||||
id: "deepseek-r1",
|
||||
name: "DeepSeek R1",
|
||||
providers: ["deepseek", "openrouter"],
|
||||
},
|
||||
{
|
||||
chef: "DeepSeek",
|
||||
chefSlug: "deepseek",
|
||||
id: "deepseek-v3",
|
||||
name: "DeepSeek V3",
|
||||
providers: ["deepseek", "openrouter"],
|
||||
},
|
||||
{
|
||||
chef: "DeepSeek",
|
||||
chefSlug: "deepseek",
|
||||
id: "deepseek-coder-v2",
|
||||
name: "DeepSeek Coder V2",
|
||||
providers: ["deepseek", "openrouter"],
|
||||
},
|
||||
{
|
||||
chef: "Mistral AI",
|
||||
chefSlug: "mistral",
|
||||
id: "mistral-large",
|
||||
name: "Mistral Large",
|
||||
providers: ["mistral", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "Mistral AI",
|
||||
chefSlug: "mistral",
|
||||
id: "mistral-small",
|
||||
name: "Mistral Small",
|
||||
providers: ["mistral", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "Mistral AI",
|
||||
chefSlug: "mistral",
|
||||
id: "codestral",
|
||||
name: "Codestral",
|
||||
providers: ["mistral"],
|
||||
},
|
||||
{
|
||||
chef: "Alibaba",
|
||||
chefSlug: "alibaba",
|
||||
id: "qwen-2.5-72b",
|
||||
name: "Qwen 2.5 72B",
|
||||
providers: ["alibaba", "openrouter"],
|
||||
},
|
||||
{
|
||||
chef: "Alibaba",
|
||||
chefSlug: "alibaba",
|
||||
id: "qwen-2.5-coder-32b",
|
||||
name: "Qwen 2.5 Coder 32B",
|
||||
providers: ["alibaba", "openrouter"],
|
||||
},
|
||||
{
|
||||
chef: "Alibaba",
|
||||
chefSlug: "alibaba",
|
||||
id: "qwen-max",
|
||||
name: "Qwen Max",
|
||||
providers: ["alibaba"],
|
||||
},
|
||||
{
|
||||
chef: "Cohere",
|
||||
chefSlug: "cohere",
|
||||
id: "command-r-plus",
|
||||
name: "Command R+",
|
||||
providers: ["cohere", "azure", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Cohere",
|
||||
chefSlug: "cohere",
|
||||
id: "command-r",
|
||||
name: "Command R",
|
||||
providers: ["cohere", "azure", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "xAI",
|
||||
chefSlug: "xai",
|
||||
id: "grok-3",
|
||||
name: "Grok 3",
|
||||
providers: ["xai"],
|
||||
},
|
||||
{
|
||||
chef: "xAI",
|
||||
chefSlug: "xai",
|
||||
id: "grok-2-1212",
|
||||
name: "Grok 2 1212",
|
||||
providers: ["xai"],
|
||||
},
|
||||
{
|
||||
chef: "xAI",
|
||||
chefSlug: "xai",
|
||||
id: "grok-vision",
|
||||
name: "Grok Vision",
|
||||
providers: ["xai"],
|
||||
},
|
||||
{
|
||||
chef: "Moonshot AI",
|
||||
chefSlug: "moonshotai",
|
||||
id: "moonshot-v1-128k",
|
||||
name: "Moonshot v1 128K",
|
||||
providers: ["moonshotai"],
|
||||
},
|
||||
{
|
||||
chef: "Moonshot AI",
|
||||
chefSlug: "moonshotai",
|
||||
id: "moonshot-v1-32k",
|
||||
name: "Moonshot v1 32K",
|
||||
providers: ["moonshotai"],
|
||||
},
|
||||
{
|
||||
chef: "Perplexity",
|
||||
chefSlug: "perplexity",
|
||||
id: "sonar-pro",
|
||||
name: "Sonar Pro",
|
||||
providers: ["perplexity"],
|
||||
},
|
||||
{
|
||||
chef: "Perplexity",
|
||||
chefSlug: "perplexity",
|
||||
id: "sonar",
|
||||
name: "Sonar",
|
||||
providers: ["perplexity"],
|
||||
},
|
||||
{
|
||||
chef: "Vercel",
|
||||
chefSlug: "v0",
|
||||
id: "v0-chat",
|
||||
name: "v0 Chat",
|
||||
providers: ["vercel"],
|
||||
},
|
||||
{
|
||||
chef: "Amazon",
|
||||
chefSlug: "amazon-bedrock",
|
||||
id: "nova-pro",
|
||||
name: "Nova Pro",
|
||||
providers: ["amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Amazon",
|
||||
chefSlug: "amazon-bedrock",
|
||||
id: "nova-lite",
|
||||
name: "Nova Lite",
|
||||
providers: ["amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Amazon",
|
||||
chefSlug: "amazon-bedrock",
|
||||
id: "nova-micro",
|
||||
name: "Nova Micro",
|
||||
providers: ["amazon-bedrock"],
|
||||
},
|
||||
];
|
||||
|
||||
interface ModelItemProps {
|
||||
model: (typeof models)[0];
|
||||
selectedModel: string;
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
const ModelItem = memo(({ model, selectedModel, onSelect }: ModelItemProps) => {
|
||||
const handleSelect = useCallback(
|
||||
() => onSelect(model.id),
|
||||
[onSelect, model.id]
|
||||
);
|
||||
return (
|
||||
<ModelSelectorItem key={model.id} onSelect={handleSelect} value={model.id}>
|
||||
<ModelSelectorLogo provider={model.chefSlug} />
|
||||
<ModelSelectorName>{model.name}</ModelSelectorName>
|
||||
<ModelSelectorLogoGroup>
|
||||
{model.providers.map((provider) => (
|
||||
<ModelSelectorLogo key={provider} provider={provider} />
|
||||
))}
|
||||
</ModelSelectorLogoGroup>
|
||||
{selectedModel === model.id ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
);
|
||||
});
|
||||
|
||||
ModelItem.displayName = "ModelItem";
|
||||
|
||||
const Example = () => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedModel, setSelectedModel] = useState<string>("gpt-4o");
|
||||
|
||||
const handleModelSelect = useCallback((id: string) => {
|
||||
setSelectedModel(id);
|
||||
setOpen(false);
|
||||
}, []);
|
||||
|
||||
const selectedModelData = models.find((model) => model.id === selectedModel);
|
||||
|
||||
// Get unique chefs in order of appearance
|
||||
const chefs = [...new Set(models.map((model) => model.chef))];
|
||||
|
||||
return (
|
||||
<div className="flex size-full items-center justify-center p-8">
|
||||
<ModelSelector onOpenChange={setOpen} open={open}>
|
||||
<ModelSelectorTrigger asChild>
|
||||
<Button className="w-[200px] justify-between" variant="outline">
|
||||
{selectedModelData?.chefSlug && (
|
||||
<ModelSelectorLogo provider={selectedModelData.chefSlug} />
|
||||
)}
|
||||
{selectedModelData?.name && (
|
||||
<ModelSelectorName>{selectedModelData.name}</ModelSelectorName>
|
||||
)}
|
||||
</Button>
|
||||
</ModelSelectorTrigger>
|
||||
<ModelSelectorContent>
|
||||
<ModelSelectorInput placeholder="Search models..." />
|
||||
<ModelSelectorList>
|
||||
<ModelSelectorEmpty>No models found.</ModelSelectorEmpty>
|
||||
{chefs.map((chef) => (
|
||||
<ModelSelectorGroup heading={chef} key={chef}>
|
||||
{models
|
||||
.filter((model) => model.chef === chef)
|
||||
.map((model) => (
|
||||
<ModelItem
|
||||
key={model.id}
|
||||
model={model}
|
||||
onSelect={handleModelSelect}
|
||||
selectedModel={selectedModel}
|
||||
/>
|
||||
))}
|
||||
</ModelSelectorGroup>
|
||||
))}
|
||||
</ModelSelectorList>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelector>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,33 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
OpenIn,
|
||||
OpenInChatGPT,
|
||||
OpenInClaude,
|
||||
OpenInContent,
|
||||
OpenInCursor,
|
||||
OpenInScira,
|
||||
OpenInT3,
|
||||
OpenInTrigger,
|
||||
OpenInv0,
|
||||
} from "@/components/ai-elements/open-in-chat";
|
||||
|
||||
const Example = () => {
|
||||
const sampleQuery = "How can I implement authentication in Next.js?";
|
||||
|
||||
return (
|
||||
<OpenIn>
|
||||
<OpenInTrigger />
|
||||
<OpenInContent>
|
||||
<OpenInChatGPT query={sampleQuery} />
|
||||
<OpenInClaude query={sampleQuery} />
|
||||
<OpenInCursor query={sampleQuery} />
|
||||
<OpenInT3 query={sampleQuery} />
|
||||
<OpenInScira query={sampleQuery} />
|
||||
<OpenInv0 query={sampleQuery} />
|
||||
</OpenInContent>
|
||||
</OpenIn>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
PackageInfo,
|
||||
PackageInfoChangeType,
|
||||
PackageInfoContent,
|
||||
PackageInfoDependencies,
|
||||
PackageInfoDependency,
|
||||
PackageInfoDescription,
|
||||
PackageInfoHeader,
|
||||
PackageInfoName,
|
||||
PackageInfoVersion,
|
||||
} from "@/components/ai-elements/package-info";
|
||||
|
||||
const Example = () => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<PackageInfo
|
||||
changeType="major"
|
||||
currentVersion="18.2.0"
|
||||
name="react"
|
||||
newVersion="19.0.0"
|
||||
>
|
||||
<PackageInfoHeader>
|
||||
<PackageInfoName />
|
||||
<PackageInfoChangeType />
|
||||
</PackageInfoHeader>
|
||||
<PackageInfoVersion />
|
||||
<PackageInfoDescription>
|
||||
A JavaScript library for building user interfaces.
|
||||
</PackageInfoDescription>
|
||||
<PackageInfoContent>
|
||||
<PackageInfoDependencies>
|
||||
<PackageInfoDependency name="react-dom" version="^19.0.0" />
|
||||
<PackageInfoDependency name="scheduler" version="^0.24.0" />
|
||||
</PackageInfoDependencies>
|
||||
</PackageInfoContent>
|
||||
</PackageInfo>
|
||||
|
||||
<PackageInfo changeType="added" name="lodash">
|
||||
<PackageInfoHeader>
|
||||
<PackageInfoName />
|
||||
<PackageInfoChangeType />
|
||||
</PackageInfoHeader>
|
||||
<PackageInfoVersion />
|
||||
</PackageInfo>
|
||||
|
||||
<PackageInfo changeType="removed" currentVersion="2.29.4" name="moment" />
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import type { PersonaState } from "@/components/ai-elements/persona";
|
||||
import { Persona } from "@/components/ai-elements/persona";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ButtonGroup } from "@/components/ui/button-group";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
BrainIcon,
|
||||
CircleIcon,
|
||||
EyeClosedIcon,
|
||||
MegaphoneIcon,
|
||||
MicIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const states: {
|
||||
state: PersonaState;
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
}[] = [
|
||||
{
|
||||
icon: CircleIcon,
|
||||
label: "Idle",
|
||||
state: "idle",
|
||||
},
|
||||
{
|
||||
icon: MicIcon,
|
||||
label: "Listening",
|
||||
state: "listening",
|
||||
},
|
||||
{
|
||||
icon: BrainIcon,
|
||||
label: "Thinking",
|
||||
state: "thinking",
|
||||
},
|
||||
{
|
||||
icon: MegaphoneIcon,
|
||||
label: "Speaking",
|
||||
state: "speaking",
|
||||
},
|
||||
{
|
||||
icon: EyeClosedIcon,
|
||||
label: "Asleep",
|
||||
state: "asleep",
|
||||
},
|
||||
];
|
||||
|
||||
interface StateButtonProps {
|
||||
state: (typeof states)[0];
|
||||
currentState: PersonaState;
|
||||
onStateChange: (state: PersonaState) => void;
|
||||
}
|
||||
|
||||
const StateButton = memo(
|
||||
({ state, currentState, onStateChange }: StateButtonProps) => {
|
||||
const handleClick = useCallback(
|
||||
() => onStateChange(state.state),
|
||||
[onStateChange, state.state]
|
||||
);
|
||||
return (
|
||||
<Tooltip key={state.state}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
size="icon-sm"
|
||||
variant={currentState === state.state ? "default" : "outline"}
|
||||
>
|
||||
<state.icon className="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{state.label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
StateButton.displayName = "StateButton";
|
||||
|
||||
const Example = () => {
|
||||
const [currentState, setCurrentState] = useState<PersonaState>("idle");
|
||||
|
||||
const handleStateChange = useCallback((state: PersonaState) => {
|
||||
setCurrentState(state);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col items-center justify-center gap-4">
|
||||
<Persona className="size-32" state={currentState} variant="command" />
|
||||
|
||||
<ButtonGroup orientation="horizontal">
|
||||
{states.map((state) => (
|
||||
<StateButton
|
||||
currentState={currentState}
|
||||
key={state.state}
|
||||
onStateChange={handleStateChange}
|
||||
state={state}
|
||||
/>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import type { PersonaState } from "@/components/ai-elements/persona";
|
||||
import { Persona } from "@/components/ai-elements/persona";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ButtonGroup } from "@/components/ui/button-group";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
BrainIcon,
|
||||
CircleIcon,
|
||||
EyeClosedIcon,
|
||||
MegaphoneIcon,
|
||||
MicIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const states: {
|
||||
state: PersonaState;
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
}[] = [
|
||||
{
|
||||
icon: CircleIcon,
|
||||
label: "Idle",
|
||||
state: "idle",
|
||||
},
|
||||
{
|
||||
icon: MicIcon,
|
||||
label: "Listening",
|
||||
state: "listening",
|
||||
},
|
||||
{
|
||||
icon: BrainIcon,
|
||||
label: "Thinking",
|
||||
state: "thinking",
|
||||
},
|
||||
{
|
||||
icon: MegaphoneIcon,
|
||||
label: "Speaking",
|
||||
state: "speaking",
|
||||
},
|
||||
{
|
||||
icon: EyeClosedIcon,
|
||||
label: "Asleep",
|
||||
state: "asleep",
|
||||
},
|
||||
];
|
||||
|
||||
interface StateButtonProps {
|
||||
state: (typeof states)[0];
|
||||
currentState: PersonaState;
|
||||
onStateChange: (state: PersonaState) => void;
|
||||
}
|
||||
|
||||
const StateButton = memo(
|
||||
({ state, currentState, onStateChange }: StateButtonProps) => {
|
||||
const handleClick = useCallback(
|
||||
() => onStateChange(state.state),
|
||||
[onStateChange, state.state]
|
||||
);
|
||||
return (
|
||||
<Tooltip key={state.state}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
size="icon-sm"
|
||||
variant={currentState === state.state ? "default" : "outline"}
|
||||
>
|
||||
<state.icon className="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{state.label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
StateButton.displayName = "StateButton";
|
||||
|
||||
const Example = () => {
|
||||
const [currentState, setCurrentState] = useState<PersonaState>("idle");
|
||||
|
||||
const handleStateChange = useCallback((state: PersonaState) => {
|
||||
setCurrentState(state);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col items-center justify-center gap-4">
|
||||
<Persona className="size-32" state={currentState} variant="glint" />
|
||||
|
||||
<ButtonGroup orientation="horizontal">
|
||||
{states.map((state) => (
|
||||
<StateButton
|
||||
currentState={currentState}
|
||||
key={state.state}
|
||||
onStateChange={handleStateChange}
|
||||
state={state}
|
||||
/>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import type { PersonaState } from "@/components/ai-elements/persona";
|
||||
import { Persona } from "@/components/ai-elements/persona";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ButtonGroup } from "@/components/ui/button-group";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
BrainIcon,
|
||||
CircleIcon,
|
||||
EyeClosedIcon,
|
||||
MegaphoneIcon,
|
||||
MicIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const states: {
|
||||
state: PersonaState;
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
}[] = [
|
||||
{
|
||||
icon: CircleIcon,
|
||||
label: "Idle",
|
||||
state: "idle",
|
||||
},
|
||||
{
|
||||
icon: MicIcon,
|
||||
label: "Listening",
|
||||
state: "listening",
|
||||
},
|
||||
{
|
||||
icon: BrainIcon,
|
||||
label: "Thinking",
|
||||
state: "thinking",
|
||||
},
|
||||
{
|
||||
icon: MegaphoneIcon,
|
||||
label: "Speaking",
|
||||
state: "speaking",
|
||||
},
|
||||
{
|
||||
icon: EyeClosedIcon,
|
||||
label: "Asleep",
|
||||
state: "asleep",
|
||||
},
|
||||
];
|
||||
|
||||
interface StateButtonProps {
|
||||
state: (typeof states)[0];
|
||||
currentState: PersonaState;
|
||||
onStateChange: (state: PersonaState) => void;
|
||||
}
|
||||
|
||||
const StateButton = memo(
|
||||
({ state, currentState, onStateChange }: StateButtonProps) => {
|
||||
const handleClick = useCallback(
|
||||
() => onStateChange(state.state),
|
||||
[onStateChange, state.state]
|
||||
);
|
||||
return (
|
||||
<Tooltip key={state.state}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
size="icon-sm"
|
||||
variant={currentState === state.state ? "default" : "outline"}
|
||||
>
|
||||
<state.icon className="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{state.label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
StateButton.displayName = "StateButton";
|
||||
|
||||
const Example = () => {
|
||||
const [currentState, setCurrentState] = useState<PersonaState>("idle");
|
||||
|
||||
const handleStateChange = useCallback((state: PersonaState) => {
|
||||
setCurrentState(state);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col items-center justify-center gap-4">
|
||||
<Persona className="size-32" state={currentState} variant="halo" />
|
||||
|
||||
<ButtonGroup orientation="horizontal">
|
||||
{states.map((state) => (
|
||||
<StateButton
|
||||
currentState={currentState}
|
||||
key={state.state}
|
||||
onStateChange={handleStateChange}
|
||||
state={state}
|
||||
/>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import type { PersonaState } from "@/components/ai-elements/persona";
|
||||
import { Persona } from "@/components/ai-elements/persona";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ButtonGroup } from "@/components/ui/button-group";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
BrainIcon,
|
||||
CircleIcon,
|
||||
EyeClosedIcon,
|
||||
MegaphoneIcon,
|
||||
MicIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const states: {
|
||||
state: PersonaState;
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
}[] = [
|
||||
{
|
||||
icon: CircleIcon,
|
||||
label: "Idle",
|
||||
state: "idle",
|
||||
},
|
||||
{
|
||||
icon: MicIcon,
|
||||
label: "Listening",
|
||||
state: "listening",
|
||||
},
|
||||
{
|
||||
icon: BrainIcon,
|
||||
label: "Thinking",
|
||||
state: "thinking",
|
||||
},
|
||||
{
|
||||
icon: MegaphoneIcon,
|
||||
label: "Speaking",
|
||||
state: "speaking",
|
||||
},
|
||||
{
|
||||
icon: EyeClosedIcon,
|
||||
label: "Asleep",
|
||||
state: "asleep",
|
||||
},
|
||||
];
|
||||
|
||||
interface StateButtonProps {
|
||||
state: (typeof states)[0];
|
||||
currentState: PersonaState;
|
||||
onStateChange: (state: PersonaState) => void;
|
||||
}
|
||||
|
||||
const StateButton = memo(
|
||||
({ state, currentState, onStateChange }: StateButtonProps) => {
|
||||
const handleClick = useCallback(
|
||||
() => onStateChange(state.state),
|
||||
[onStateChange, state.state]
|
||||
);
|
||||
return (
|
||||
<Tooltip key={state.state}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
size="icon-sm"
|
||||
variant={currentState === state.state ? "default" : "outline"}
|
||||
>
|
||||
<state.icon className="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{state.label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
StateButton.displayName = "StateButton";
|
||||
|
||||
const Example = () => {
|
||||
const [currentState, setCurrentState] = useState<PersonaState>("idle");
|
||||
|
||||
const handleStateChange = useCallback((state: PersonaState) => {
|
||||
setCurrentState(state);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col items-center justify-center gap-4">
|
||||
<Persona className="size-32" state={currentState} variant="mana" />
|
||||
|
||||
<ButtonGroup orientation="horizontal">
|
||||
{states.map((state) => (
|
||||
<StateButton
|
||||
currentState={currentState}
|
||||
key={state.state}
|
||||
onStateChange={handleStateChange}
|
||||
state={state}
|
||||
/>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import type { PersonaState } from "@/components/ai-elements/persona";
|
||||
import { Persona } from "@/components/ai-elements/persona";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ButtonGroup } from "@/components/ui/button-group";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
BrainIcon,
|
||||
CircleIcon,
|
||||
EyeClosedIcon,
|
||||
MegaphoneIcon,
|
||||
MicIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const states: {
|
||||
state: PersonaState;
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
}[] = [
|
||||
{
|
||||
icon: CircleIcon,
|
||||
label: "Idle",
|
||||
state: "idle",
|
||||
},
|
||||
{
|
||||
icon: MicIcon,
|
||||
label: "Listening",
|
||||
state: "listening",
|
||||
},
|
||||
{
|
||||
icon: BrainIcon,
|
||||
label: "Thinking",
|
||||
state: "thinking",
|
||||
},
|
||||
{
|
||||
icon: MegaphoneIcon,
|
||||
label: "Speaking",
|
||||
state: "speaking",
|
||||
},
|
||||
{
|
||||
icon: EyeClosedIcon,
|
||||
label: "Asleep",
|
||||
state: "asleep",
|
||||
},
|
||||
];
|
||||
|
||||
interface StateButtonProps {
|
||||
state: (typeof states)[0];
|
||||
currentState: PersonaState;
|
||||
onStateChange: (state: PersonaState) => void;
|
||||
}
|
||||
|
||||
const StateButton = memo(
|
||||
({ state, currentState, onStateChange }: StateButtonProps) => {
|
||||
const handleClick = useCallback(
|
||||
() => onStateChange(state.state),
|
||||
[onStateChange, state.state]
|
||||
);
|
||||
return (
|
||||
<Tooltip key={state.state}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
size="icon-sm"
|
||||
variant={currentState === state.state ? "default" : "outline"}
|
||||
>
|
||||
<state.icon className="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{state.label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
StateButton.displayName = "StateButton";
|
||||
|
||||
const Example = () => {
|
||||
const [currentState, setCurrentState] = useState<PersonaState>("idle");
|
||||
|
||||
const handleStateChange = useCallback((state: PersonaState) => {
|
||||
setCurrentState(state);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col items-center justify-center gap-4">
|
||||
<Persona className="size-32" state={currentState} variant="obsidian" />
|
||||
|
||||
<ButtonGroup orientation="horizontal">
|
||||
{states.map((state) => (
|
||||
<StateButton
|
||||
currentState={currentState}
|
||||
key={state.state}
|
||||
onStateChange={handleStateChange}
|
||||
state={state}
|
||||
/>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import type { PersonaState } from "@/components/ai-elements/persona";
|
||||
import { Persona } from "@/components/ai-elements/persona";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ButtonGroup } from "@/components/ui/button-group";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
BrainIcon,
|
||||
CircleIcon,
|
||||
EyeClosedIcon,
|
||||
MegaphoneIcon,
|
||||
MicIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
interface StateButtonProps {
|
||||
state: { state: PersonaState; icon: LucideIcon; label: string };
|
||||
currentState: PersonaState;
|
||||
onStateChange: (state: PersonaState) => void;
|
||||
}
|
||||
|
||||
const StateButton = memo(
|
||||
({ state, currentState, onStateChange }: StateButtonProps) => {
|
||||
const handleClick = useCallback(
|
||||
() => onStateChange(state.state),
|
||||
[onStateChange, state.state]
|
||||
);
|
||||
return (
|
||||
<Tooltip key={state.state}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
size="icon-sm"
|
||||
variant={currentState === state.state ? "default" : "outline"}
|
||||
>
|
||||
<state.icon className="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{state.label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
StateButton.displayName = "StateButton";
|
||||
|
||||
const states: {
|
||||
state: PersonaState;
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
}[] = [
|
||||
{
|
||||
icon: CircleIcon,
|
||||
label: "Idle",
|
||||
state: "idle",
|
||||
},
|
||||
{
|
||||
icon: MicIcon,
|
||||
label: "Listening",
|
||||
state: "listening",
|
||||
},
|
||||
{
|
||||
icon: BrainIcon,
|
||||
label: "Thinking",
|
||||
state: "thinking",
|
||||
},
|
||||
{
|
||||
icon: MegaphoneIcon,
|
||||
label: "Speaking",
|
||||
state: "speaking",
|
||||
},
|
||||
{
|
||||
icon: EyeClosedIcon,
|
||||
label: "Asleep",
|
||||
state: "asleep",
|
||||
},
|
||||
];
|
||||
|
||||
const Example = () => {
|
||||
const [currentState, setCurrentState] = useState<PersonaState>("idle");
|
||||
|
||||
const handleStateChange = useCallback((state: PersonaState) => {
|
||||
setCurrentState(state);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col items-center justify-center gap-4">
|
||||
<Persona className="size-32" state={currentState} variant="opal" />
|
||||
|
||||
<ButtonGroup orientation="horizontal">
|
||||
{states.map((state) => (
|
||||
<StateButton
|
||||
currentState={currentState}
|
||||
key={state.state}
|
||||
onStateChange={handleStateChange}
|
||||
state={state}
|
||||
/>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,65 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Plan,
|
||||
PlanAction,
|
||||
PlanContent,
|
||||
PlanDescription,
|
||||
PlanFooter,
|
||||
PlanHeader,
|
||||
PlanTitle,
|
||||
PlanTrigger,
|
||||
} from "@/components/ai-elements/plan";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { FileText } from "lucide-react";
|
||||
|
||||
const Example = () => (
|
||||
<Plan defaultOpen={false}>
|
||||
<PlanHeader>
|
||||
<div>
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
<FileText className="size-4" />
|
||||
<PlanTitle>Rewrite AI Elements to SolidJS</PlanTitle>
|
||||
</div>
|
||||
<PlanDescription>
|
||||
Rewrite the AI Elements component library from React to SolidJS while
|
||||
maintaining compatibility with existing React-based shadcn/ui
|
||||
components using solid-js/compat, updating all 29 components and their
|
||||
test suite.
|
||||
</PlanDescription>
|
||||
</div>
|
||||
<PlanTrigger />
|
||||
</PlanHeader>
|
||||
<PlanContent>
|
||||
<div className="space-y-4 text-sm">
|
||||
<div>
|
||||
<h3 className="mb-2 font-semibold">Overview</h3>
|
||||
<p>
|
||||
This plan outlines the migration strategy for converting the AI
|
||||
Elements library from React to SolidJS, ensuring compatibility and
|
||||
maintaining existing functionality.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="mb-2 font-semibold">Key Steps</h3>
|
||||
<ul className="list-inside list-disc space-y-1">
|
||||
<li>Set up SolidJS project structure</li>
|
||||
<li>Install solid-js/compat for React compatibility</li>
|
||||
<li>Migrate components one by one</li>
|
||||
<li>Update test suite for each component</li>
|
||||
<li>Verify compatibility with shadcn/ui</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</PlanContent>
|
||||
<PlanFooter className="justify-end">
|
||||
<PlanAction>
|
||||
<Button size="sm">
|
||||
Build <kbd className="font-mono">⌘↩</kbd>
|
||||
</Button>
|
||||
</PlanAction>
|
||||
</PlanFooter>
|
||||
</Plan>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,502 @@
|
||||
"use client";
|
||||
|
||||
import type { AttachmentData } from "@/components/ai-elements/attachments";
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentInfo,
|
||||
AttachmentPreview,
|
||||
AttachmentRemove,
|
||||
Attachments,
|
||||
} from "@/components/ai-elements/attachments";
|
||||
import {
|
||||
ModelSelector,
|
||||
ModelSelectorContent,
|
||||
ModelSelectorEmpty,
|
||||
ModelSelectorGroup,
|
||||
ModelSelectorInput,
|
||||
ModelSelectorItem,
|
||||
ModelSelectorList,
|
||||
ModelSelectorLogo,
|
||||
ModelSelectorLogoGroup,
|
||||
ModelSelectorName,
|
||||
ModelSelectorTrigger,
|
||||
} from "@/components/ai-elements/model-selector";
|
||||
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
||||
import {
|
||||
PromptInput,
|
||||
PromptInputBody,
|
||||
PromptInputButton,
|
||||
PromptInputCommand,
|
||||
PromptInputCommandEmpty,
|
||||
PromptInputCommandGroup,
|
||||
PromptInputCommandInput,
|
||||
PromptInputCommandItem,
|
||||
PromptInputCommandList,
|
||||
PromptInputCommandSeparator,
|
||||
PromptInputFooter,
|
||||
PromptInputHeader,
|
||||
PromptInputHoverCard,
|
||||
PromptInputHoverCardContent,
|
||||
PromptInputHoverCardTrigger,
|
||||
PromptInputProvider,
|
||||
PromptInputSubmit,
|
||||
PromptInputTab,
|
||||
PromptInputTabBody,
|
||||
PromptInputTabItem,
|
||||
PromptInputTabLabel,
|
||||
PromptInputTextarea,
|
||||
PromptInputTools,
|
||||
usePromptInputAttachments,
|
||||
usePromptInputReferencedSources,
|
||||
} from "@/components/ai-elements/prompt-input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { SourceDocumentUIPart } from "ai";
|
||||
import {
|
||||
AtSignIcon,
|
||||
CheckIcon,
|
||||
FilesIcon,
|
||||
GlobeIcon,
|
||||
ImageIcon,
|
||||
RulerIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const models = [
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "gpt-4o",
|
||||
name: "GPT-4o",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "gpt-4o-mini",
|
||||
name: "GPT-4o Mini",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-opus-4-20250514",
|
||||
name: "Claude 4 Opus",
|
||||
providers: ["anthropic", "azure", "google", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-sonnet-4-20250514",
|
||||
name: "Claude 4 Sonnet",
|
||||
providers: ["anthropic", "azure", "google", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Google",
|
||||
chefSlug: "google",
|
||||
id: "gemini-2.0-flash-exp",
|
||||
name: "Gemini 2.0 Flash",
|
||||
providers: ["google"],
|
||||
},
|
||||
];
|
||||
|
||||
const SUBMITTING_TIMEOUT = 200;
|
||||
const STREAMING_TIMEOUT = 2000;
|
||||
|
||||
interface AttachmentItemProps {
|
||||
attachment: AttachmentData;
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const AttachmentItem = memo(({ attachment, onRemove }: AttachmentItemProps) => {
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(attachment.id),
|
||||
[onRemove, attachment.id]
|
||||
);
|
||||
return (
|
||||
<Attachment data={attachment} key={attachment.id} onRemove={handleRemove}>
|
||||
<AttachmentPreview />
|
||||
<AttachmentRemove />
|
||||
</Attachment>
|
||||
);
|
||||
});
|
||||
|
||||
AttachmentItem.displayName = "AttachmentItem";
|
||||
|
||||
interface SourceItemProps {
|
||||
source: AttachmentData;
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const SourceItem = memo(({ source, onRemove }: SourceItemProps) => {
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(source.id),
|
||||
[onRemove, source.id]
|
||||
);
|
||||
return (
|
||||
<Attachment data={source} key={source.id} onRemove={handleRemove}>
|
||||
<AttachmentPreview />
|
||||
<AttachmentInfo />
|
||||
<AttachmentRemove />
|
||||
</Attachment>
|
||||
);
|
||||
});
|
||||
|
||||
SourceItem.displayName = "SourceItem";
|
||||
|
||||
interface ModelItemProps {
|
||||
m: (typeof models)[0];
|
||||
selectedModel: string;
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
const ModelItem = memo(({ m, selectedModel, onSelect }: ModelItemProps) => {
|
||||
const handleSelect = useCallback(() => onSelect(m.id), [onSelect, m.id]);
|
||||
return (
|
||||
<ModelSelectorItem key={m.id} onSelect={handleSelect} value={m.id}>
|
||||
<ModelSelectorLogo provider={m.chefSlug} />
|
||||
<ModelSelectorName>{m.name}</ModelSelectorName>
|
||||
<ModelSelectorLogoGroup>
|
||||
{m.providers.map((provider) => (
|
||||
<ModelSelectorLogo key={provider} provider={provider} />
|
||||
))}
|
||||
</ModelSelectorLogoGroup>
|
||||
{selectedModel === m.id ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
);
|
||||
});
|
||||
|
||||
ModelItem.displayName = "ModelItem";
|
||||
|
||||
interface SourceCommandItemProps {
|
||||
source: SourceDocumentUIPart;
|
||||
onAdd: (source: SourceDocumentUIPart) => void;
|
||||
}
|
||||
|
||||
const SourceCommandItem = memo(({ source, onAdd }: SourceCommandItemProps) => {
|
||||
const handleSelect = useCallback(() => onAdd(source), [onAdd, source]);
|
||||
return (
|
||||
<PromptInputCommandItem
|
||||
key={`${source.filename}-${source.title}`}
|
||||
onSelect={handleSelect}
|
||||
>
|
||||
<GlobeIcon className="text-primary" />
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium text-sm">{source.title}</span>
|
||||
<span className="text-muted-foreground text-xs">{source.filename}</span>
|
||||
</div>
|
||||
</PromptInputCommandItem>
|
||||
);
|
||||
});
|
||||
|
||||
SourceCommandItem.displayName = "SourceCommandItem";
|
||||
|
||||
const sampleSources: SourceDocumentUIPart[] = [
|
||||
{
|
||||
filename: "packages/elements/src",
|
||||
mediaType: "text/plain",
|
||||
sourceId: "1",
|
||||
title: "prompt-input.tsx",
|
||||
type: "source-document",
|
||||
},
|
||||
{
|
||||
filename: "apps/test/app/examples",
|
||||
mediaType: "text/plain",
|
||||
sourceId: "2",
|
||||
title: "queue.tsx",
|
||||
type: "source-document",
|
||||
},
|
||||
{
|
||||
filename: "packages/elements/src",
|
||||
mediaType: "text/plain",
|
||||
sourceId: "3",
|
||||
title: "queue.tsx",
|
||||
type: "source-document",
|
||||
},
|
||||
];
|
||||
|
||||
const sampleTabs = {
|
||||
active: [{ path: "packages/elements/src/task-queue-panel.tsx" }],
|
||||
recents: [
|
||||
{ path: "apps/test/app/examples/task-queue-panel.tsx" },
|
||||
{ path: "apps/test/app/page.tsx" },
|
||||
{ path: "packages/elements/src/task.tsx" },
|
||||
{ path: "apps/test/app/examples/prompt-input.tsx" },
|
||||
{ path: "packages/elements/src/queue.tsx" },
|
||||
{ path: "apps/test/app/examples/queue.tsx" },
|
||||
],
|
||||
};
|
||||
|
||||
const PromptInputAttachmentsDisplay = () => {
|
||||
const attachments = usePromptInputAttachments();
|
||||
|
||||
const handleRemove = useCallback(
|
||||
(id: string) => attachments.remove(id),
|
||||
[attachments]
|
||||
);
|
||||
|
||||
if (attachments.files.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Attachments variant="inline">
|
||||
{attachments.files.map((attachment) => (
|
||||
<AttachmentItem
|
||||
attachment={attachment}
|
||||
key={attachment.id}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
))}
|
||||
</Attachments>
|
||||
);
|
||||
};
|
||||
|
||||
const PromptInputReferencedSourcesDisplay = () => {
|
||||
const refs = usePromptInputReferencedSources();
|
||||
|
||||
const handleRemove = useCallback((id: string) => refs.remove(id), [refs]);
|
||||
|
||||
if (refs.sources.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Attachments variant="inline">
|
||||
{refs.sources.map((source) => (
|
||||
<SourceItem
|
||||
key={source.id}
|
||||
onRemove={handleRemove}
|
||||
source={source as AttachmentData}
|
||||
/>
|
||||
))}
|
||||
</Attachments>
|
||||
);
|
||||
};
|
||||
|
||||
const SampleFilesMenu = () => {
|
||||
const refs = usePromptInputReferencedSources();
|
||||
|
||||
const handleAdd = useCallback(
|
||||
(source: SourceDocumentUIPart) => refs.add(source),
|
||||
[refs]
|
||||
);
|
||||
|
||||
return (
|
||||
<PromptInputCommand>
|
||||
<PromptInputCommandInput
|
||||
className="border-none focus-visible:ring-0"
|
||||
placeholder="Add files, folders, docs..."
|
||||
/>
|
||||
<PromptInputCommandList>
|
||||
<PromptInputCommandEmpty className="p-3 text-muted-foreground text-sm">
|
||||
No results found.
|
||||
</PromptInputCommandEmpty>
|
||||
<PromptInputCommandGroup heading="Added">
|
||||
<PromptInputCommandItem>
|
||||
<GlobeIcon />
|
||||
<span>Active Tabs</span>
|
||||
<span className="ml-auto text-muted-foreground">✓</span>
|
||||
</PromptInputCommandItem>
|
||||
</PromptInputCommandGroup>
|
||||
<PromptInputCommandSeparator />
|
||||
<PromptInputCommandGroup heading="Other Files">
|
||||
{sampleSources
|
||||
.filter(
|
||||
(source) =>
|
||||
!refs.sources.some(
|
||||
(s) =>
|
||||
s.title === source.title && s.filename === source.filename
|
||||
)
|
||||
)
|
||||
.map((source) => (
|
||||
<SourceCommandItem
|
||||
key={`${source.filename}-${source.title}`}
|
||||
onAdd={handleAdd}
|
||||
source={source}
|
||||
/>
|
||||
))}
|
||||
</PromptInputCommandGroup>
|
||||
</PromptInputCommandList>
|
||||
</PromptInputCommand>
|
||||
);
|
||||
};
|
||||
|
||||
const Example = () => {
|
||||
const [model, setModel] = useState<string>(models[0].id);
|
||||
const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
|
||||
const [status, setStatus] = useState<
|
||||
"submitted" | "streaming" | "ready" | "error"
|
||||
>("ready");
|
||||
|
||||
const selectedModelData = models.find((m) => m.id === model);
|
||||
|
||||
const handleModelSelect = useCallback((id: string) => {
|
||||
setModel(id);
|
||||
setModelSelectorOpen(false);
|
||||
}, []);
|
||||
|
||||
const handleSubmit = useCallback((message: PromptInputMessage) => {
|
||||
const hasText = Boolean(message.text);
|
||||
const hasAttachments = Boolean(message.files?.length);
|
||||
|
||||
if (!(hasText || hasAttachments)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus("submitted");
|
||||
|
||||
setTimeout(() => {
|
||||
setStatus("streaming");
|
||||
}, SUBMITTING_TIMEOUT);
|
||||
|
||||
setTimeout(() => {
|
||||
setStatus("ready");
|
||||
}, STREAMING_TIMEOUT);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col justify-end">
|
||||
<PromptInputProvider>
|
||||
<PromptInput globalDrop multiple onSubmit={handleSubmit}>
|
||||
<PromptInputHeader>
|
||||
<PromptInputHoverCard>
|
||||
<PromptInputHoverCardTrigger>
|
||||
<PromptInputButton
|
||||
className="h-8!"
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
>
|
||||
<AtSignIcon className="text-muted-foreground" size={12} />
|
||||
</PromptInputButton>
|
||||
</PromptInputHoverCardTrigger>
|
||||
<PromptInputHoverCardContent className="w-[400px] p-0">
|
||||
<SampleFilesMenu />
|
||||
</PromptInputHoverCardContent>
|
||||
</PromptInputHoverCard>
|
||||
<PromptInputHoverCard>
|
||||
<PromptInputHoverCardTrigger>
|
||||
<PromptInputButton size="sm" variant="outline">
|
||||
<RulerIcon className="text-muted-foreground" size={12} />
|
||||
<span>1</span>
|
||||
</PromptInputButton>
|
||||
</PromptInputHoverCardTrigger>
|
||||
<PromptInputHoverCardContent className="divide-y overflow-hidden p-0">
|
||||
<div className="space-y-2 p-3">
|
||||
<p className="font-medium text-muted-foreground text-sm">
|
||||
Attached Project Rules
|
||||
</p>
|
||||
<p className="ml-4 text-muted-foreground text-sm">
|
||||
Always Apply:
|
||||
</p>
|
||||
<p className="ml-8 text-sm">ultracite.mdc</p>
|
||||
</div>
|
||||
<p className="bg-sidebar px-4 py-3 text-muted-foreground text-sm">
|
||||
Click to manage
|
||||
</p>
|
||||
</PromptInputHoverCardContent>
|
||||
</PromptInputHoverCard>
|
||||
<PromptInputHoverCard>
|
||||
<PromptInputHoverCardTrigger>
|
||||
<PromptInputButton size="sm" variant="outline">
|
||||
<FilesIcon className="text-muted-foreground" size={12} />
|
||||
<span>1 Tab</span>
|
||||
</PromptInputButton>
|
||||
</PromptInputHoverCardTrigger>
|
||||
<PromptInputHoverCardContent className="w-[300px] space-y-4 px-0 py-3">
|
||||
<PromptInputTab>
|
||||
<PromptInputTabLabel>Active Tabs</PromptInputTabLabel>
|
||||
<PromptInputTabBody>
|
||||
{sampleTabs.active.map((tab) => (
|
||||
<PromptInputTabItem key={tab.path}>
|
||||
<GlobeIcon className="text-primary" size={16} />
|
||||
<span className="truncate" dir="rtl">
|
||||
{tab.path}
|
||||
</span>
|
||||
</PromptInputTabItem>
|
||||
))}
|
||||
</PromptInputTabBody>
|
||||
</PromptInputTab>
|
||||
<PromptInputTab>
|
||||
<PromptInputTabLabel>Recents</PromptInputTabLabel>
|
||||
<PromptInputTabBody>
|
||||
{sampleTabs.recents.map((tab) => (
|
||||
<PromptInputTabItem key={tab.path}>
|
||||
<GlobeIcon className="text-primary" size={16} />
|
||||
<span className="truncate" dir="rtl">
|
||||
{tab.path}
|
||||
</span>
|
||||
</PromptInputTabItem>
|
||||
))}
|
||||
</PromptInputTabBody>
|
||||
</PromptInputTab>
|
||||
<div className="border-t px-3 pt-2 text-muted-foreground text-xs">
|
||||
Only file paths are included
|
||||
</div>
|
||||
</PromptInputHoverCardContent>
|
||||
</PromptInputHoverCard>
|
||||
<PromptInputAttachmentsDisplay />
|
||||
<PromptInputReferencedSourcesDisplay />
|
||||
</PromptInputHeader>
|
||||
<PromptInputBody>
|
||||
<PromptInputTextarea placeholder="Plan, search, build anything" />
|
||||
</PromptInputBody>
|
||||
<PromptInputFooter>
|
||||
<PromptInputTools>
|
||||
<ModelSelector
|
||||
onOpenChange={setModelSelectorOpen}
|
||||
open={modelSelectorOpen}
|
||||
>
|
||||
<ModelSelectorTrigger asChild>
|
||||
<PromptInputButton>
|
||||
{selectedModelData?.chefSlug && (
|
||||
<ModelSelectorLogo
|
||||
provider={selectedModelData.chefSlug}
|
||||
/>
|
||||
)}
|
||||
{selectedModelData?.name && (
|
||||
<ModelSelectorName>
|
||||
{selectedModelData.name}
|
||||
</ModelSelectorName>
|
||||
)}
|
||||
</PromptInputButton>
|
||||
</ModelSelectorTrigger>
|
||||
<ModelSelectorContent>
|
||||
<ModelSelectorInput placeholder="Search models..." />
|
||||
<ModelSelectorList>
|
||||
<ModelSelectorEmpty>No models found.</ModelSelectorEmpty>
|
||||
{["OpenAI", "Anthropic", "Google"].map((chef) => (
|
||||
<ModelSelectorGroup heading={chef} key={chef}>
|
||||
{models
|
||||
.filter((m) => m.chef === chef)
|
||||
.map((m) => (
|
||||
<ModelItem
|
||||
key={m.id}
|
||||
m={m}
|
||||
onSelect={handleModelSelect}
|
||||
selectedModel={model}
|
||||
/>
|
||||
))}
|
||||
</ModelSelectorGroup>
|
||||
))}
|
||||
</ModelSelectorList>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelector>
|
||||
</PromptInputTools>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button size="icon-sm" variant="ghost">
|
||||
<ImageIcon className="text-muted-foreground" size={16} />
|
||||
</Button>
|
||||
<PromptInputSubmit className="!h-8" status={status} />
|
||||
</div>
|
||||
</PromptInputFooter>
|
||||
</PromptInput>
|
||||
</PromptInputProvider>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
PromptInput,
|
||||
PromptInputBody,
|
||||
PromptInputButton,
|
||||
PromptInputFooter,
|
||||
PromptInputSubmit,
|
||||
PromptInputTextarea,
|
||||
PromptInputTools,
|
||||
} from "@/components/ai-elements/prompt-input";
|
||||
import { GlobeIcon, MicIcon, PaperclipIcon } from "lucide-react";
|
||||
|
||||
const handleSubmit = () => {
|
||||
// Handle submit
|
||||
};
|
||||
|
||||
const Example = () => (
|
||||
<PromptInput onSubmit={handleSubmit}>
|
||||
<PromptInputBody>
|
||||
<PromptInputTextarea />
|
||||
</PromptInputBody>
|
||||
<PromptInputFooter>
|
||||
<PromptInputTools>
|
||||
<PromptInputButton tooltip="Attach files">
|
||||
<PaperclipIcon size={16} />
|
||||
</PromptInputButton>
|
||||
<PromptInputButton
|
||||
tooltip={{ content: "Search the web", shortcut: "⌘K" }}
|
||||
>
|
||||
<GlobeIcon size={16} />
|
||||
</PromptInputButton>
|
||||
<PromptInputButton
|
||||
tooltip={{ content: "Voice input", shortcut: "⌘M", side: "bottom" }}
|
||||
>
|
||||
<MicIcon size={16} />
|
||||
</PromptInputButton>
|
||||
</PromptInputTools>
|
||||
<PromptInputSubmit />
|
||||
</PromptInputFooter>
|
||||
</PromptInput>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,267 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentPreview,
|
||||
AttachmentRemove,
|
||||
Attachments,
|
||||
} from "@/components/ai-elements/attachments";
|
||||
import {
|
||||
ModelSelector,
|
||||
ModelSelectorContent,
|
||||
ModelSelectorEmpty,
|
||||
ModelSelectorGroup,
|
||||
ModelSelectorInput,
|
||||
ModelSelectorItem,
|
||||
ModelSelectorList,
|
||||
ModelSelectorLogo,
|
||||
ModelSelectorLogoGroup,
|
||||
ModelSelectorName,
|
||||
ModelSelectorTrigger,
|
||||
} from "@/components/ai-elements/model-selector";
|
||||
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
||||
import {
|
||||
PromptInput,
|
||||
PromptInputActionAddAttachments,
|
||||
PromptInputActionAddScreenshot,
|
||||
PromptInputActionMenu,
|
||||
PromptInputActionMenuContent,
|
||||
PromptInputActionMenuTrigger,
|
||||
PromptInputBody,
|
||||
PromptInputButton,
|
||||
PromptInputFooter,
|
||||
PromptInputProvider,
|
||||
PromptInputSubmit,
|
||||
PromptInputTextarea,
|
||||
PromptInputTools,
|
||||
usePromptInputAttachments,
|
||||
} from "@/components/ai-elements/prompt-input";
|
||||
import { CheckIcon, GlobeIcon } from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const models = [
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "gpt-4o",
|
||||
name: "GPT-4o",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "gpt-4o-mini",
|
||||
name: "GPT-4o Mini",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-opus-4-20250514",
|
||||
name: "Claude 4 Opus",
|
||||
providers: ["anthropic", "azure", "google", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-sonnet-4-20250514",
|
||||
name: "Claude 4 Sonnet",
|
||||
providers: ["anthropic", "azure", "google", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Google",
|
||||
chefSlug: "google",
|
||||
id: "gemini-2.0-flash-exp",
|
||||
name: "Gemini 2.0 Flash",
|
||||
providers: ["google"],
|
||||
},
|
||||
];
|
||||
|
||||
const SUBMITTING_TIMEOUT = 200;
|
||||
const STREAMING_TIMEOUT = 2000;
|
||||
|
||||
interface AttachmentItemProps {
|
||||
attachment: {
|
||||
id: string;
|
||||
type: "file";
|
||||
filename?: string;
|
||||
mediaType?: string;
|
||||
url: string;
|
||||
};
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const AttachmentItem = memo(({ attachment, onRemove }: AttachmentItemProps) => {
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(attachment.id),
|
||||
[onRemove, attachment.id]
|
||||
);
|
||||
return (
|
||||
<Attachment data={attachment} key={attachment.id} onRemove={handleRemove}>
|
||||
<AttachmentPreview />
|
||||
<AttachmentRemove />
|
||||
</Attachment>
|
||||
);
|
||||
});
|
||||
|
||||
AttachmentItem.displayName = "AttachmentItem";
|
||||
|
||||
interface ModelItemProps {
|
||||
m: (typeof models)[0];
|
||||
selectedModel: string;
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
const ModelItem = memo(({ m, selectedModel, onSelect }: ModelItemProps) => {
|
||||
const handleSelect = useCallback(() => onSelect(m.id), [onSelect, m.id]);
|
||||
return (
|
||||
<ModelSelectorItem key={m.id} onSelect={handleSelect} value={m.id}>
|
||||
<ModelSelectorLogo provider={m.chefSlug} />
|
||||
<ModelSelectorName>{m.name}</ModelSelectorName>
|
||||
<ModelSelectorLogoGroup>
|
||||
{m.providers.map((provider) => (
|
||||
<ModelSelectorLogo key={provider} provider={provider} />
|
||||
))}
|
||||
</ModelSelectorLogoGroup>
|
||||
{selectedModel === m.id ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
);
|
||||
});
|
||||
|
||||
ModelItem.displayName = "ModelItem";
|
||||
|
||||
const PromptInputAttachmentsDisplay = () => {
|
||||
const attachments = usePromptInputAttachments();
|
||||
|
||||
const handleRemove = useCallback(
|
||||
(id: string) => attachments.remove(id),
|
||||
[attachments]
|
||||
);
|
||||
|
||||
if (attachments.files.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Attachments variant="inline">
|
||||
{attachments.files.map((attachment) => (
|
||||
<AttachmentItem
|
||||
attachment={attachment}
|
||||
key={attachment.id}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
))}
|
||||
</Attachments>
|
||||
);
|
||||
};
|
||||
|
||||
const Example = () => {
|
||||
const [model, setModel] = useState<string>(models[0].id);
|
||||
const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
|
||||
const [status, setStatus] = useState<
|
||||
"submitted" | "streaming" | "ready" | "error"
|
||||
>("ready");
|
||||
|
||||
const selectedModelData = models.find((m) => m.id === model);
|
||||
|
||||
const handleModelSelect = useCallback((id: string) => {
|
||||
setModel(id);
|
||||
setModelSelectorOpen(false);
|
||||
}, []);
|
||||
|
||||
const handleSubmit = useCallback((message: PromptInputMessage) => {
|
||||
const hasText = Boolean(message.text);
|
||||
const hasAttachments = Boolean(message.files?.length);
|
||||
|
||||
if (!(hasText || hasAttachments)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus("submitted");
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("Submitting message:", message);
|
||||
|
||||
setTimeout(() => {
|
||||
setStatus("streaming");
|
||||
}, SUBMITTING_TIMEOUT);
|
||||
|
||||
setTimeout(() => {
|
||||
setStatus("ready");
|
||||
}, STREAMING_TIMEOUT);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="size-full">
|
||||
<PromptInputProvider>
|
||||
<PromptInput globalDrop multiple onSubmit={handleSubmit}>
|
||||
<PromptInputAttachmentsDisplay />
|
||||
<PromptInputBody>
|
||||
<PromptInputTextarea />
|
||||
</PromptInputBody>
|
||||
<PromptInputFooter>
|
||||
<PromptInputTools>
|
||||
<PromptInputActionMenu>
|
||||
<PromptInputActionMenuTrigger />
|
||||
<PromptInputActionMenuContent>
|
||||
<PromptInputActionAddAttachments />
|
||||
<PromptInputActionAddScreenshot />
|
||||
</PromptInputActionMenuContent>
|
||||
</PromptInputActionMenu>
|
||||
<PromptInputButton>
|
||||
<GlobeIcon size={16} />
|
||||
<span>Search</span>
|
||||
</PromptInputButton>
|
||||
<ModelSelector
|
||||
onOpenChange={setModelSelectorOpen}
|
||||
open={modelSelectorOpen}
|
||||
>
|
||||
<ModelSelectorTrigger asChild>
|
||||
<PromptInputButton>
|
||||
{selectedModelData?.chefSlug && (
|
||||
<ModelSelectorLogo
|
||||
provider={selectedModelData.chefSlug}
|
||||
/>
|
||||
)}
|
||||
{selectedModelData?.name && (
|
||||
<ModelSelectorName>
|
||||
{selectedModelData.name}
|
||||
</ModelSelectorName>
|
||||
)}
|
||||
</PromptInputButton>
|
||||
</ModelSelectorTrigger>
|
||||
<ModelSelectorContent>
|
||||
<ModelSelectorInput placeholder="Search models..." />
|
||||
<ModelSelectorList>
|
||||
<ModelSelectorEmpty>No models found.</ModelSelectorEmpty>
|
||||
{["OpenAI", "Anthropic", "Google"].map((chef) => (
|
||||
<ModelSelectorGroup heading={chef} key={chef}>
|
||||
{models
|
||||
.filter((m) => m.chef === chef)
|
||||
.map((m) => (
|
||||
<ModelItem
|
||||
key={m.id}
|
||||
m={m}
|
||||
onSelect={handleModelSelect}
|
||||
selectedModel={model}
|
||||
/>
|
||||
))}
|
||||
</ModelSelectorGroup>
|
||||
))}
|
||||
</ModelSelectorList>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelector>
|
||||
</PromptInputTools>
|
||||
<PromptInputSubmit status={status} />
|
||||
</PromptInputFooter>
|
||||
</PromptInput>
|
||||
</PromptInputProvider>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,394 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentPreview,
|
||||
AttachmentRemove,
|
||||
Attachments,
|
||||
} from "@/components/ai-elements/attachments";
|
||||
import {
|
||||
ModelSelector,
|
||||
ModelSelectorContent,
|
||||
ModelSelectorEmpty,
|
||||
ModelSelectorGroup,
|
||||
ModelSelectorInput,
|
||||
ModelSelectorItem,
|
||||
ModelSelectorList,
|
||||
ModelSelectorLogo,
|
||||
ModelSelectorLogoGroup,
|
||||
ModelSelectorName,
|
||||
ModelSelectorTrigger,
|
||||
} from "@/components/ai-elements/model-selector";
|
||||
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
||||
import {
|
||||
PromptInput,
|
||||
PromptInputActionAddAttachments,
|
||||
PromptInputActionMenu,
|
||||
PromptInputActionMenuContent,
|
||||
PromptInputActionMenuTrigger,
|
||||
PromptInputBody,
|
||||
PromptInputButton,
|
||||
PromptInputFooter,
|
||||
PromptInputHeader,
|
||||
PromptInputSubmit,
|
||||
PromptInputTextarea,
|
||||
PromptInputTools,
|
||||
usePromptInputAttachments,
|
||||
} from "@/components/ai-elements/prompt-input";
|
||||
import type { QueueTodo } from "@/components/ai-elements/queue";
|
||||
import {
|
||||
Queue,
|
||||
QueueItem,
|
||||
QueueItemAction,
|
||||
QueueItemActions,
|
||||
QueueItemContent,
|
||||
QueueItemDescription,
|
||||
QueueItemIndicator,
|
||||
QueueSection,
|
||||
QueueSectionContent,
|
||||
} from "@/components/ai-elements/queue";
|
||||
import { CheckIcon, GlobeIcon, Trash2 } from "lucide-react";
|
||||
import { memo, useCallback, useRef, useState } from "react";
|
||||
|
||||
const models = [
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "gpt-4o",
|
||||
name: "GPT-4o",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "OpenAI",
|
||||
chefSlug: "openai",
|
||||
id: "gpt-4o-mini",
|
||||
name: "GPT-4o Mini",
|
||||
providers: ["openai", "azure"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-opus-4-20250514",
|
||||
name: "Claude 4 Opus",
|
||||
providers: ["anthropic", "azure", "google", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Anthropic",
|
||||
chefSlug: "anthropic",
|
||||
id: "claude-sonnet-4-20250514",
|
||||
name: "Claude 4 Sonnet",
|
||||
providers: ["anthropic", "azure", "google", "amazon-bedrock"],
|
||||
},
|
||||
{
|
||||
chef: "Google",
|
||||
chefSlug: "google",
|
||||
id: "gemini-2.0-flash-exp",
|
||||
name: "Gemini 2.0 Flash",
|
||||
providers: ["google"],
|
||||
},
|
||||
];
|
||||
|
||||
const SUBMITTING_TIMEOUT = 200;
|
||||
const STREAMING_TIMEOUT = 2000;
|
||||
|
||||
interface AttachmentItemProps {
|
||||
attachment: {
|
||||
id: string;
|
||||
type: "file";
|
||||
filename?: string;
|
||||
mediaType?: string;
|
||||
url: string;
|
||||
};
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const AttachmentItem = memo(({ attachment, onRemove }: AttachmentItemProps) => {
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(attachment.id),
|
||||
[onRemove, attachment.id]
|
||||
);
|
||||
return (
|
||||
<Attachment data={attachment} key={attachment.id} onRemove={handleRemove}>
|
||||
<AttachmentPreview />
|
||||
<AttachmentRemove />
|
||||
</Attachment>
|
||||
);
|
||||
});
|
||||
|
||||
AttachmentItem.displayName = "AttachmentItem";
|
||||
|
||||
interface TodoItemProps {
|
||||
todo: QueueTodo;
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const TodoItem = memo(({ todo, onRemove }: TodoItemProps) => {
|
||||
const isCompleted = todo.status === "completed";
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(todo.id),
|
||||
[onRemove, todo.id]
|
||||
);
|
||||
|
||||
return (
|
||||
<QueueItem key={todo.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<QueueItemIndicator completed={isCompleted} />
|
||||
<QueueItemContent completed={isCompleted}>
|
||||
{todo.title}
|
||||
</QueueItemContent>
|
||||
<QueueItemActions>
|
||||
<QueueItemAction aria-label="Remove todo" onClick={handleRemove}>
|
||||
<Trash2 size={12} />
|
||||
</QueueItemAction>
|
||||
</QueueItemActions>
|
||||
</div>
|
||||
{todo.description && (
|
||||
<QueueItemDescription completed={isCompleted}>
|
||||
{todo.description}
|
||||
</QueueItemDescription>
|
||||
)}
|
||||
</QueueItem>
|
||||
);
|
||||
});
|
||||
|
||||
TodoItem.displayName = "TodoItem";
|
||||
|
||||
interface ModelItemProps {
|
||||
m: (typeof models)[0];
|
||||
selectedModel: string;
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
const ModelItem = memo(({ m, selectedModel, onSelect }: ModelItemProps) => {
|
||||
const handleSelect = useCallback(() => onSelect(m.id), [onSelect, m.id]);
|
||||
return (
|
||||
<ModelSelectorItem key={m.id} onSelect={handleSelect} value={m.id}>
|
||||
<ModelSelectorLogo provider={m.chefSlug} />
|
||||
<ModelSelectorName>{m.name}</ModelSelectorName>
|
||||
<ModelSelectorLogoGroup>
|
||||
{m.providers.map((provider) => (
|
||||
<ModelSelectorLogo key={provider} provider={provider} />
|
||||
))}
|
||||
</ModelSelectorLogoGroup>
|
||||
{selectedModel === m.id ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
);
|
||||
});
|
||||
|
||||
ModelItem.displayName = "ModelItem";
|
||||
|
||||
const sampleTodos: QueueTodo[] = [
|
||||
{
|
||||
description: "Complete the README and API docs",
|
||||
id: "todo-1",
|
||||
status: "completed",
|
||||
title: "Write project documentation",
|
||||
},
|
||||
{
|
||||
id: "todo-2",
|
||||
status: "pending",
|
||||
title: "Implement authentication",
|
||||
},
|
||||
{
|
||||
description: "Resolve crash on settings page",
|
||||
id: "todo-3",
|
||||
status: "pending",
|
||||
title: "Fix bug #42",
|
||||
},
|
||||
{
|
||||
description: "Unify queue and todo state management",
|
||||
id: "todo-4",
|
||||
status: "pending",
|
||||
title: "Refactor queue logic",
|
||||
},
|
||||
{
|
||||
description: "Increase test coverage for hooks",
|
||||
id: "todo-5",
|
||||
status: "pending",
|
||||
title: "Add unit tests",
|
||||
},
|
||||
];
|
||||
|
||||
const PromptInputAttachmentsDisplay = () => {
|
||||
const attachments = usePromptInputAttachments();
|
||||
|
||||
const handleRemove = useCallback(
|
||||
(id: string) => attachments.remove(id),
|
||||
[attachments]
|
||||
);
|
||||
|
||||
if (attachments.files.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Attachments variant="inline">
|
||||
{attachments.files.map((attachment) => (
|
||||
<AttachmentItem
|
||||
attachment={attachment}
|
||||
key={attachment.id}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
))}
|
||||
</Attachments>
|
||||
);
|
||||
};
|
||||
|
||||
const Example = () => {
|
||||
const [todos, setTodos] = useState(sampleTodos);
|
||||
|
||||
const handleRemoveTodo = useCallback((id: string) => {
|
||||
setTodos((prev) => prev.filter((todo) => todo.id !== id));
|
||||
}, []);
|
||||
|
||||
const [text, setText] = useState<string>("");
|
||||
const [model, setModel] = useState<string>(models[0].id);
|
||||
const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
|
||||
const [status, setStatus] = useState<
|
||||
"submitted" | "streaming" | "ready" | "error"
|
||||
>("ready");
|
||||
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
const handleTextChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLTextAreaElement>) => setText(e.target.value),
|
||||
[]
|
||||
);
|
||||
|
||||
const handleModelSelect = useCallback((id: string) => {
|
||||
setModel(id);
|
||||
setModelSelectorOpen(false);
|
||||
}, []);
|
||||
|
||||
const selectedModelData = models.find((m) => m.id === model);
|
||||
|
||||
const stop = () => {
|
||||
console.log("Stopping request...");
|
||||
|
||||
// Clear any pending timeouts
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
timeoutRef.current = null;
|
||||
}
|
||||
|
||||
setStatus("ready");
|
||||
};
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(message: PromptInputMessage) => {
|
||||
// If currently streaming or submitted, stop instead of submitting
|
||||
if (status === "streaming" || status === "submitted") {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
|
||||
const hasText = Boolean(message.text);
|
||||
const hasAttachments = Boolean(message.files?.length);
|
||||
|
||||
if (!(hasText || hasAttachments)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus("submitted");
|
||||
|
||||
console.log("Submitting message:", message);
|
||||
|
||||
setTimeout(() => {
|
||||
setStatus("streaming");
|
||||
}, SUBMITTING_TIMEOUT);
|
||||
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
setStatus("ready");
|
||||
timeoutRef.current = null;
|
||||
}, STREAMING_TIMEOUT);
|
||||
},
|
||||
[status]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col justify-end">
|
||||
<Queue className="mx-auto max-h-[150px] w-[95%] overflow-y-auto rounded-b-none border-input border-b-0">
|
||||
{todos.length > 0 && (
|
||||
<QueueSection>
|
||||
<QueueSectionContent>
|
||||
<div>
|
||||
{todos.map((todo) => (
|
||||
<TodoItem
|
||||
key={todo.id}
|
||||
onRemove={handleRemoveTodo}
|
||||
todo={todo}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</QueueSectionContent>
|
||||
</QueueSection>
|
||||
)}
|
||||
</Queue>
|
||||
<PromptInput globalDrop multiple onSubmit={handleSubmit}>
|
||||
<PromptInputHeader>
|
||||
<PromptInputAttachmentsDisplay />
|
||||
</PromptInputHeader>
|
||||
<PromptInputBody>
|
||||
<PromptInputTextarea onChange={handleTextChange} value={text} />
|
||||
</PromptInputBody>
|
||||
<PromptInputFooter>
|
||||
<PromptInputTools>
|
||||
<PromptInputActionMenu>
|
||||
<PromptInputActionMenuTrigger />
|
||||
<PromptInputActionMenuContent>
|
||||
<PromptInputActionAddAttachments />
|
||||
</PromptInputActionMenuContent>
|
||||
</PromptInputActionMenu>
|
||||
<PromptInputButton>
|
||||
<GlobeIcon size={16} />
|
||||
<span>Search</span>
|
||||
</PromptInputButton>
|
||||
<ModelSelector
|
||||
onOpenChange={setModelSelectorOpen}
|
||||
open={modelSelectorOpen}
|
||||
>
|
||||
<ModelSelectorTrigger asChild>
|
||||
<PromptInputButton>
|
||||
{selectedModelData?.chefSlug && (
|
||||
<ModelSelectorLogo provider={selectedModelData.chefSlug} />
|
||||
)}
|
||||
{selectedModelData?.name && (
|
||||
<ModelSelectorName>
|
||||
{selectedModelData.name}
|
||||
</ModelSelectorName>
|
||||
)}
|
||||
</PromptInputButton>
|
||||
</ModelSelectorTrigger>
|
||||
<ModelSelectorContent>
|
||||
<ModelSelectorInput placeholder="Search models..." />
|
||||
<ModelSelectorList>
|
||||
<ModelSelectorEmpty>No models found.</ModelSelectorEmpty>
|
||||
{["OpenAI", "Anthropic", "Google"].map((chef) => (
|
||||
<ModelSelectorGroup heading={chef} key={chef}>
|
||||
{models
|
||||
.filter((m) => m.chef === chef)
|
||||
.map((m) => (
|
||||
<ModelItem
|
||||
key={m.id}
|
||||
m={m}
|
||||
onSelect={handleModelSelect}
|
||||
selectedModel={model}
|
||||
/>
|
||||
))}
|
||||
</ModelSelectorGroup>
|
||||
))}
|
||||
</ModelSelectorList>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelector>
|
||||
</PromptInputTools>
|
||||
<PromptInputSubmit status={status} />
|
||||
</PromptInputFooter>
|
||||
</PromptInput>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,295 @@
|
||||
"use client";
|
||||
|
||||
import type { QueueMessage, QueueTodo } from "@/components/ai-elements/queue";
|
||||
import {
|
||||
Queue,
|
||||
QueueItem,
|
||||
QueueItemAction,
|
||||
QueueItemActions,
|
||||
QueueItemAttachment,
|
||||
QueueItemContent,
|
||||
QueueItemDescription,
|
||||
QueueItemFile,
|
||||
QueueItemImage,
|
||||
QueueItemIndicator,
|
||||
QueueList,
|
||||
QueueSection,
|
||||
QueueSectionContent,
|
||||
QueueSectionLabel,
|
||||
QueueSectionTrigger,
|
||||
} from "@/components/ai-elements/queue";
|
||||
import { ArrowUp, Trash2 } from "lucide-react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const sampleMessages: QueueMessage[] = [
|
||||
{
|
||||
id: "msg-1",
|
||||
parts: [{ text: "How do I set up the project?", type: "text" }],
|
||||
},
|
||||
{
|
||||
id: "msg-2",
|
||||
parts: [{ text: "What is the roadmap for Q4?", type: "text" }],
|
||||
},
|
||||
{
|
||||
id: "msg-3",
|
||||
parts: [
|
||||
{ text: "Update the default logo to this png.", type: "text" },
|
||||
{
|
||||
filename: "setup-guide.png",
|
||||
mediaType: "image/png",
|
||||
type: "file",
|
||||
url: "https://github.com/haydenbleasel.png",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "msg-4",
|
||||
parts: [{ text: "Please generate a changelog.", type: "text" }],
|
||||
},
|
||||
{
|
||||
id: "msg-5",
|
||||
parts: [{ text: "Add dark mode support.", type: "text" }],
|
||||
},
|
||||
{
|
||||
id: "msg-6",
|
||||
parts: [{ text: "Optimize database queries.", type: "text" }],
|
||||
},
|
||||
{
|
||||
id: "msg-7",
|
||||
parts: [{ text: "Set up CI/CD pipeline.", type: "text" }],
|
||||
},
|
||||
];
|
||||
|
||||
const sampleTodos: QueueTodo[] = [
|
||||
{
|
||||
description: "Complete the README and API docs",
|
||||
id: "todo-1",
|
||||
status: "completed",
|
||||
title: "Write project documentation",
|
||||
},
|
||||
{
|
||||
id: "todo-2",
|
||||
status: "pending",
|
||||
title: "Implement authentication",
|
||||
},
|
||||
{
|
||||
description: "Resolve crash on settings page",
|
||||
id: "todo-3",
|
||||
status: "pending",
|
||||
title: "Fix bug #42",
|
||||
},
|
||||
{
|
||||
description: "Unify queue and todo state management",
|
||||
id: "todo-4",
|
||||
status: "pending",
|
||||
title: "Refactor queue logic",
|
||||
},
|
||||
{
|
||||
description: "Increase test coverage for hooks",
|
||||
id: "todo-5",
|
||||
status: "pending",
|
||||
title: "Add unit tests",
|
||||
},
|
||||
];
|
||||
|
||||
interface MessageActionsProps {
|
||||
messageId: string;
|
||||
onRemove: (e: React.MouseEvent, id: string) => void;
|
||||
onSend: (e: React.MouseEvent, id: string) => void;
|
||||
}
|
||||
|
||||
const MessageActions = memo(
|
||||
({ messageId, onRemove, onSend }: MessageActionsProps) => {
|
||||
const handleRemove = useCallback(
|
||||
(e: React.MouseEvent) => onRemove(e, messageId),
|
||||
[onRemove, messageId]
|
||||
);
|
||||
const handleSend = useCallback(
|
||||
(e: React.MouseEvent) => onSend(e, messageId),
|
||||
[onSend, messageId]
|
||||
);
|
||||
return (
|
||||
<QueueItemActions>
|
||||
<QueueItemAction
|
||||
aria-label="Remove from queue"
|
||||
onClick={handleRemove}
|
||||
title="Remove from queue"
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
</QueueItemAction>
|
||||
<QueueItemAction aria-label="Send now" onClick={handleSend}>
|
||||
<ArrowUp size={14} />
|
||||
</QueueItemAction>
|
||||
</QueueItemActions>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
MessageActions.displayName = "MessageActions";
|
||||
|
||||
interface TodoItemProps {
|
||||
todo: QueueTodo;
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const TodoItem = memo(({ todo, onRemove }: TodoItemProps) => {
|
||||
const isCompleted = todo.status === "completed";
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(todo.id),
|
||||
[onRemove, todo.id]
|
||||
);
|
||||
|
||||
return (
|
||||
<QueueItem key={todo.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<QueueItemIndicator completed={isCompleted} />
|
||||
<QueueItemContent completed={isCompleted}>
|
||||
{todo.title}
|
||||
</QueueItemContent>
|
||||
<QueueItemActions>
|
||||
<QueueItemAction aria-label="Remove todo" onClick={handleRemove}>
|
||||
<Trash2 size={12} />
|
||||
</QueueItemAction>
|
||||
</QueueItemActions>
|
||||
</div>
|
||||
{todo.description && (
|
||||
<QueueItemDescription completed={isCompleted}>
|
||||
{todo.description}
|
||||
</QueueItemDescription>
|
||||
)}
|
||||
</QueueItem>
|
||||
);
|
||||
});
|
||||
|
||||
TodoItem.displayName = "TodoItem";
|
||||
|
||||
const Example = () => {
|
||||
const [messages, setMessages] = useState(sampleMessages);
|
||||
const [todos, setTodos] = useState(sampleTodos);
|
||||
|
||||
const handleRemoveMessage = useCallback((id: string) => {
|
||||
setMessages((prev) => prev.filter((msg) => msg.id !== id));
|
||||
}, []);
|
||||
|
||||
const handleRemoveTodo = useCallback((id: string) => {
|
||||
setTodos((prev) => prev.filter((todo) => todo.id !== id));
|
||||
}, []);
|
||||
|
||||
const handleSendNow = useCallback((id: string) => {
|
||||
console.log("Send now:", id);
|
||||
setMessages((prev) => prev.filter((msg) => msg.id !== id));
|
||||
}, []);
|
||||
|
||||
const handleMessageRemove = useCallback(
|
||||
(e: React.MouseEvent, id: string) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleRemoveMessage(id);
|
||||
},
|
||||
[handleRemoveMessage]
|
||||
);
|
||||
|
||||
const handleMessageSend = useCallback(
|
||||
(e: React.MouseEvent, id: string) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleSendNow(id);
|
||||
},
|
||||
[handleSendNow]
|
||||
);
|
||||
|
||||
if (messages.length === 0 && todos.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Queue>
|
||||
{messages.length > 0 && (
|
||||
<QueueSection>
|
||||
<QueueSectionTrigger>
|
||||
<QueueSectionLabel count={messages.length} label="Queued" />
|
||||
</QueueSectionTrigger>
|
||||
<QueueSectionContent>
|
||||
<QueueList>
|
||||
{messages.map((message) => {
|
||||
const summary = (() => {
|
||||
const textParts = message.parts.filter(
|
||||
(p) => p.type === "text"
|
||||
);
|
||||
const text = textParts
|
||||
.map((p) => p.text)
|
||||
.join(" ")
|
||||
.trim();
|
||||
return text || "(queued message)";
|
||||
})();
|
||||
|
||||
const hasFiles = message.parts.some(
|
||||
(p) => p.type === "file" && p.url
|
||||
);
|
||||
|
||||
return (
|
||||
<QueueItem key={message.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<QueueItemIndicator />
|
||||
<QueueItemContent>{summary}</QueueItemContent>
|
||||
<MessageActions
|
||||
messageId={message.id}
|
||||
onRemove={handleMessageRemove}
|
||||
onSend={handleMessageSend}
|
||||
/>
|
||||
</div>
|
||||
{hasFiles && (
|
||||
<QueueItemAttachment>
|
||||
{message.parts
|
||||
.filter((p) => p.type === "file" && p.url)
|
||||
.map((file) => {
|
||||
if (
|
||||
file.mediaType?.startsWith("image/") &&
|
||||
file.url
|
||||
) {
|
||||
return (
|
||||
<QueueItemImage
|
||||
alt={file.filename || "attachment"}
|
||||
key={file.url}
|
||||
src={file.url}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<QueueItemFile key={file.url}>
|
||||
{file.filename || "file"}
|
||||
</QueueItemFile>
|
||||
);
|
||||
})}
|
||||
</QueueItemAttachment>
|
||||
)}
|
||||
</QueueItem>
|
||||
);
|
||||
})}
|
||||
</QueueList>
|
||||
</QueueSectionContent>
|
||||
</QueueSection>
|
||||
)}
|
||||
{todos.length > 0 && (
|
||||
<QueueSection>
|
||||
<QueueSectionTrigger>
|
||||
<QueueSectionLabel count={todos.length} label="Todo" />
|
||||
</QueueSectionTrigger>
|
||||
<QueueSectionContent>
|
||||
<QueueList>
|
||||
{todos.map((todo) => (
|
||||
<TodoItem
|
||||
key={todo.id}
|
||||
onRemove={handleRemoveTodo}
|
||||
todo={todo}
|
||||
/>
|
||||
))}
|
||||
</QueueList>
|
||||
</QueueSectionContent>
|
||||
</QueueSection>
|
||||
)}
|
||||
</Queue>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,71 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Reasoning,
|
||||
ReasoningContent,
|
||||
ReasoningTrigger,
|
||||
} from "@/components/ai-elements/reasoning";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
const reasoningSteps = [
|
||||
"Let me think about this problem step by step.",
|
||||
"\n\nFirst, I need to understand what the user is asking for.",
|
||||
"\n\nThey want a reasoning component that opens automatically when streaming begins and closes when streaming finishes. The component should be composable and follow existing patterns in the codebase.",
|
||||
"\n\nThis seems like a collapsible component with state management would be the right approach.",
|
||||
].join("");
|
||||
|
||||
const Example = () => {
|
||||
const [content, setContent] = useState("");
|
||||
const [isStreaming, setIsStreaming] = useState(false);
|
||||
const [currentTokenIndex, setCurrentTokenIndex] = useState(0);
|
||||
const [tokens, setTokens] = useState<string[]>([]);
|
||||
|
||||
// Function to chunk text into fake tokens of 3-4 characters
|
||||
const chunkIntoTokens = useCallback((text: string): string[] => {
|
||||
const chunks: string[] = [];
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
// Random size between 3-4
|
||||
const chunkSize = Math.floor(Math.random() * 2) + 3;
|
||||
chunks.push(text.slice(i, i + chunkSize));
|
||||
i += chunkSize;
|
||||
}
|
||||
return chunks;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const tokenizedSteps = chunkIntoTokens(reasoningSteps);
|
||||
setTokens(tokenizedSteps);
|
||||
setContent("");
|
||||
setCurrentTokenIndex(0);
|
||||
setIsStreaming(true);
|
||||
}, [chunkIntoTokens]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming || currentTokenIndex >= tokens.length) {
|
||||
if (isStreaming) {
|
||||
setIsStreaming(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Faster interval since we're streaming smaller chunks
|
||||
const timer = setTimeout(() => {
|
||||
setContent((prev) => prev + tokens[currentTokenIndex]);
|
||||
setCurrentTokenIndex((prev) => prev + 1);
|
||||
}, 25);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [isStreaming, currentTokenIndex, tokens]);
|
||||
|
||||
return (
|
||||
<div className="w-full p-4" style={{ height: "300px" }}>
|
||||
<Reasoning className="w-full" isStreaming={isStreaming}>
|
||||
<ReasoningTrigger />
|
||||
<ReasoningContent>{content}</ReasoningContent>
|
||||
</Reasoning>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,178 @@
|
||||
"use client";
|
||||
|
||||
import { CodeBlock, CodeBlockCopyButton } from "@/components/ai-elements/code-block";
|
||||
import {
|
||||
Sandbox,
|
||||
SandboxContent,
|
||||
SandboxHeader,
|
||||
SandboxTabContent,
|
||||
SandboxTabs,
|
||||
SandboxTabsBar,
|
||||
SandboxTabsList,
|
||||
SandboxTabsTrigger,
|
||||
} from "@/components/ai-elements/sandbox";
|
||||
import {
|
||||
StackTrace,
|
||||
StackTraceActions,
|
||||
StackTraceContent,
|
||||
StackTraceCopyButton,
|
||||
StackTraceError,
|
||||
StackTraceErrorMessage,
|
||||
StackTraceErrorType,
|
||||
StackTraceExpandButton,
|
||||
StackTraceFrames,
|
||||
StackTraceHeader,
|
||||
} from "@/components/ai-elements/stack-trace";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { ToolUIPart } from "ai";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
|
||||
const code = `import math
|
||||
|
||||
def calculate_primes(limit):
|
||||
"""Find all prime numbers up to a given limit using Sieve of Eratosthenes."""
|
||||
sieve = [True] * (limit + 1)
|
||||
sieve[0] = sieve[1] = False
|
||||
|
||||
for i in range(2, int(math.sqrt(limit)) + 1):
|
||||
if sieve[i]:
|
||||
for j in range(i * i, limit + 1, i):
|
||||
sieve[j] = False
|
||||
|
||||
return [i for i, is_prime in enumerate(sieve) if is_prime]
|
||||
|
||||
if __name__ == "__main__":
|
||||
primes = calculate_primes(50)
|
||||
print(f"Found {len(primes)} prime numbers up to 50:")
|
||||
print(primes)`;
|
||||
|
||||
const outputs: Record<ToolUIPart["state"], string | undefined> = {
|
||||
"input-available": undefined,
|
||||
"input-streaming": undefined,
|
||||
"output-available": `Found 15 prime numbers up to 50:
|
||||
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]`,
|
||||
"output-error": `TypeError: Cannot read properties of undefined (reading 'map')
|
||||
at calculatePrimes (/src/utils/primes.ts:15:23)
|
||||
at runCalculation (/src/components/Calculator.tsx:42:12)
|
||||
at onClick (/src/components/Button.tsx:18:5)
|
||||
at HTMLButtonElement.dispatch (node_modules/react-dom/cjs/react-dom.development.js:3456:9)
|
||||
at node_modules/react-dom/cjs/react-dom.development.js:4245:12`,
|
||||
};
|
||||
|
||||
const states: ToolUIPart["state"][] = [
|
||||
"input-streaming",
|
||||
"input-available",
|
||||
"output-available",
|
||||
"output-error",
|
||||
];
|
||||
|
||||
interface StateButtonProps {
|
||||
s: ToolUIPart["state"];
|
||||
currentState: ToolUIPart["state"];
|
||||
onStateChange: (state: ToolUIPart["state"]) => void;
|
||||
}
|
||||
|
||||
const StateButton = memo(
|
||||
({ s, currentState, onStateChange }: StateButtonProps) => {
|
||||
const handleClick = useCallback(() => onStateChange(s), [onStateChange, s]);
|
||||
return (
|
||||
<Button
|
||||
key={s}
|
||||
onClick={handleClick}
|
||||
size="sm"
|
||||
variant={currentState === s ? "default" : "outline"}
|
||||
>
|
||||
{s}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
StateButton.displayName = "StateButton";
|
||||
|
||||
const Example = () => {
|
||||
const [state, setState] = useState<ToolUIPart["state"]>("output-available");
|
||||
|
||||
const handleStateChange = useCallback((s: ToolUIPart["state"]) => {
|
||||
setState(s);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{states.map((s) => (
|
||||
<StateButton
|
||||
currentState={state}
|
||||
key={s}
|
||||
onStateChange={handleStateChange}
|
||||
s={s}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Sandbox>
|
||||
<SandboxHeader state={state} title="primes.py" />
|
||||
<SandboxContent>
|
||||
<SandboxTabs defaultValue="code">
|
||||
<SandboxTabsBar>
|
||||
<SandboxTabsList>
|
||||
<SandboxTabsTrigger value="code">Code</SandboxTabsTrigger>
|
||||
<SandboxTabsTrigger value="output">Output</SandboxTabsTrigger>
|
||||
</SandboxTabsList>
|
||||
</SandboxTabsBar>
|
||||
<SandboxTabContent value="code">
|
||||
<CodeBlock
|
||||
className="border-0"
|
||||
code={
|
||||
state === "input-streaming" ? "# Generating code..." : code
|
||||
}
|
||||
language="python"
|
||||
>
|
||||
<CodeBlockCopyButton
|
||||
className="absolute top-2 right-2 opacity-0 transition-opacity duration-200 group-hover:opacity-100"
|
||||
size="sm"
|
||||
/>
|
||||
</CodeBlock>
|
||||
</SandboxTabContent>
|
||||
<SandboxTabContent value="output">
|
||||
{state === "output-error" ? (
|
||||
<StackTrace
|
||||
className="rounded-none border-0"
|
||||
defaultOpen
|
||||
trace={outputs[state] ?? ""}
|
||||
>
|
||||
<StackTraceHeader>
|
||||
<StackTraceError>
|
||||
<StackTraceErrorType />
|
||||
<StackTraceErrorMessage />
|
||||
</StackTraceError>
|
||||
<StackTraceActions>
|
||||
<StackTraceCopyButton />
|
||||
<StackTraceExpandButton />
|
||||
</StackTraceActions>
|
||||
</StackTraceHeader>
|
||||
<StackTraceContent>
|
||||
<StackTraceFrames />
|
||||
</StackTraceContent>
|
||||
</StackTrace>
|
||||
) : (
|
||||
<CodeBlock
|
||||
className="border-0"
|
||||
code={outputs[state] ?? ""}
|
||||
language="log"
|
||||
>
|
||||
<CodeBlockCopyButton
|
||||
className="absolute top-2 right-2 opacity-0 transition-opacity duration-200 group-hover:opacity-100"
|
||||
size="sm"
|
||||
/>
|
||||
</CodeBlock>
|
||||
)}
|
||||
</SandboxTabContent>
|
||||
</SandboxTabs>
|
||||
</SandboxContent>
|
||||
</Sandbox>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { SchemaDisplay } from "@/components/ai-elements/schema-display";
|
||||
|
||||
const Example = () => (
|
||||
<SchemaDisplay description="List all users" method="GET" path="/api/users" />
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import { SchemaDisplay } from "@/components/ai-elements/schema-display";
|
||||
|
||||
const Example = () => (
|
||||
<SchemaDisplay
|
||||
method="POST"
|
||||
path="/api/posts"
|
||||
requestBody={[
|
||||
{ name: "title", required: true, type: "string" },
|
||||
{ name: "content", required: true, type: "string" },
|
||||
]}
|
||||
responseBody={[
|
||||
{ name: "id", required: true, type: "string" },
|
||||
{ name: "createdAt", required: true, type: "string" },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { SchemaDisplay } from "@/components/ai-elements/schema-display";
|
||||
|
||||
const Example = () => (
|
||||
<SchemaDisplay
|
||||
method="POST"
|
||||
path="/api/posts"
|
||||
requestBody={[
|
||||
{
|
||||
name: "author",
|
||||
properties: [
|
||||
{ name: "id", type: "string" },
|
||||
{ name: "name", type: "string" },
|
||||
],
|
||||
type: "object",
|
||||
},
|
||||
{ name: "title", required: true, type: "string" },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { SchemaDisplay } from "@/components/ai-elements/schema-display";
|
||||
|
||||
const Example = () => (
|
||||
<SchemaDisplay
|
||||
method="GET"
|
||||
parameters={[
|
||||
{ location: "path", name: "userId", required: true, type: "string" },
|
||||
{ location: "query", name: "include", type: "string" },
|
||||
]}
|
||||
path="/api/users/{userId}"
|
||||
/>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
SchemaDisplay,
|
||||
SchemaDisplayContent,
|
||||
SchemaDisplayDescription,
|
||||
SchemaDisplayHeader,
|
||||
SchemaDisplayMethod,
|
||||
SchemaDisplayParameters,
|
||||
SchemaDisplayPath,
|
||||
SchemaDisplayRequest,
|
||||
SchemaDisplayResponse,
|
||||
} from "@/components/ai-elements/schema-display";
|
||||
|
||||
const Example = () => (
|
||||
<SchemaDisplay
|
||||
description="Create a new post for a specific user. Requires authentication."
|
||||
method="POST"
|
||||
parameters={[
|
||||
{
|
||||
description: "The unique identifier of the user",
|
||||
location: "path",
|
||||
name: "userId",
|
||||
required: true,
|
||||
type: "string",
|
||||
},
|
||||
{
|
||||
description: "Save as draft instead of publishing",
|
||||
location: "query",
|
||||
name: "draft",
|
||||
required: false,
|
||||
type: "boolean",
|
||||
},
|
||||
]}
|
||||
path="/api/users/{userId}/posts"
|
||||
requestBody={[
|
||||
{
|
||||
description: "The post title",
|
||||
name: "title",
|
||||
required: true,
|
||||
type: "string",
|
||||
},
|
||||
{
|
||||
description: "The post content in markdown format",
|
||||
name: "content",
|
||||
required: true,
|
||||
type: "string",
|
||||
},
|
||||
{
|
||||
description: "Tags for categorization",
|
||||
items: { name: "tag", type: "string" },
|
||||
name: "tags",
|
||||
type: "array",
|
||||
},
|
||||
{
|
||||
description: "Additional metadata",
|
||||
name: "metadata",
|
||||
properties: [
|
||||
{
|
||||
description: "SEO optimized title",
|
||||
name: "seoTitle",
|
||||
type: "string",
|
||||
},
|
||||
{
|
||||
description: "Meta description",
|
||||
name: "seoDescription",
|
||||
type: "string",
|
||||
},
|
||||
],
|
||||
type: "object",
|
||||
},
|
||||
]}
|
||||
responseBody={[
|
||||
{ description: "Post ID", name: "id", required: true, type: "string" },
|
||||
{ name: "title", required: true, type: "string" },
|
||||
{ name: "content", required: true, type: "string" },
|
||||
{
|
||||
description: "ISO 8601 timestamp",
|
||||
name: "createdAt",
|
||||
required: true,
|
||||
type: "string",
|
||||
},
|
||||
{
|
||||
name: "author",
|
||||
properties: [
|
||||
{ name: "id", required: true, type: "string" },
|
||||
{ name: "name", required: true, type: "string" },
|
||||
{ name: "avatar", type: "string" },
|
||||
],
|
||||
required: true,
|
||||
type: "object",
|
||||
},
|
||||
]}
|
||||
>
|
||||
<SchemaDisplayHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<SchemaDisplayMethod />
|
||||
<SchemaDisplayPath />
|
||||
</div>
|
||||
</SchemaDisplayHeader>
|
||||
<SchemaDisplayDescription />
|
||||
<SchemaDisplayContent>
|
||||
<SchemaDisplayParameters />
|
||||
<SchemaDisplayRequest />
|
||||
<SchemaDisplayResponse />
|
||||
</SchemaDisplayContent>
|
||||
</SchemaDisplay>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { Shimmer } from "@/components/ai-elements/shimmer";
|
||||
|
||||
const Example = () => (
|
||||
<div className="flex flex-col gap-6 p-8">
|
||||
<div className="text-center">
|
||||
<p className="mb-3 text-muted-foreground text-sm">Fast (1 second)</p>
|
||||
<Shimmer duration={1}>Loading quickly...</Shimmer>
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<p className="mb-3 text-muted-foreground text-sm">Default (2 seconds)</p>
|
||||
<Shimmer duration={2}>Loading at normal speed...</Shimmer>
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<p className="mb-3 text-muted-foreground text-sm">Slow (4 seconds)</p>
|
||||
<Shimmer duration={4}>Loading slowly...</Shimmer>
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<p className="mb-3 text-muted-foreground text-sm">
|
||||
Very Slow (6 seconds)
|
||||
</p>
|
||||
<Shimmer duration={6}>Loading very slowly...</Shimmer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Example;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user