@elabs-ai/components-ai 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -0
  3. package/dist/_audio-player-media-chrome-KA5DY54G.js +81 -0
  4. package/dist/_audio-player-media-chrome-KA5DY54G.js.map +1 -0
  5. package/dist/_flow-boundary-D63PJ65S.js +186 -0
  6. package/dist/_flow-boundary-D63PJ65S.js.map +1 -0
  7. package/dist/_interactive-terminal-xterm-ATJ5EW3G.js +11 -0
  8. package/dist/_interactive-terminal-xterm-ATJ5EW3G.js.map +1 -0
  9. package/dist/_persona-rive-RFR2EUWP.js +164 -0
  10. package/dist/_persona-rive-RFR2EUWP.js.map +1 -0
  11. package/dist/index.d.ts +4079 -0
  12. package/dist/index.js +11770 -0
  13. package/dist/index.js.map +1 -0
  14. package/package.json +87 -0
  15. package/src/_audio-player-media-chrome.tsx +146 -0
  16. package/src/_chat-shell-rail.tsx +18 -0
  17. package/src/_code-block-theme.test.ts +134 -0
  18. package/src/_code-block-theme.ts +184 -0
  19. package/src/_flow-boundary.tsx +237 -0
  20. package/src/_flow-lazy.ts +34 -0
  21. package/src/_interactive-terminal-xterm.ts +32 -0
  22. package/src/_lazy-mermaid.test.ts +101 -0
  23. package/src/_lazy-mermaid.ts +117 -0
  24. package/src/_persona-rive.tsx +252 -0
  25. package/src/_streamdown-i18n.ts +119 -0
  26. package/src/agent-timeline.stories.tsx +66 -0
  27. package/src/agent-timeline.test.tsx +74 -0
  28. package/src/agent-timeline.tsx +106 -0
  29. package/src/agent.tsx +113 -0
  30. package/src/agentic-workspace.stories.tsx +1099 -0
  31. package/src/artifact.stories.tsx +62 -0
  32. package/src/artifact.test.tsx +112 -0
  33. package/src/artifact.tsx +167 -0
  34. package/src/asset-preview.stories.tsx +100 -0
  35. package/src/asset-preview.test.tsx +126 -0
  36. package/src/asset-preview.tsx +218 -0
  37. package/src/attachments.tsx +393 -0
  38. package/src/audio-player.stories.tsx +99 -0
  39. package/src/audio-player.tsx +170 -0
  40. package/src/blocks-ai-composer.stories.tsx +83 -0
  41. package/src/canvas.stories.tsx +142 -0
  42. package/src/canvas.tsx +29 -0
  43. package/src/chain-of-thought.tsx +193 -0
  44. package/src/chat-greeting.stories.tsx +96 -0
  45. package/src/chat-greeting.test.tsx +91 -0
  46. package/src/chat-greeting.tsx +91 -0
  47. package/src/chat-shell.stories.tsx +123 -0
  48. package/src/chat-shell.test.tsx +113 -0
  49. package/src/chat-shell.tsx +97 -0
  50. package/src/chat.stories.tsx +99 -0
  51. package/src/checkpoint.tsx +54 -0
  52. package/src/code-block.stories.tsx +81 -0
  53. package/src/code-block.test.tsx +191 -0
  54. package/src/code-block.tsx +673 -0
  55. package/src/commit.tsx +343 -0
  56. package/src/composer.stories.tsx +188 -0
  57. package/src/composer.test.tsx +182 -0
  58. package/src/composer.tsx +202 -0
  59. package/src/confirmation.stories.tsx +61 -0
  60. package/src/confirmation.test.tsx +136 -0
  61. package/src/confirmation.tsx +273 -0
  62. package/src/connection.tsx +23 -0
  63. package/src/context-panel.stories.tsx +137 -0
  64. package/src/context-panel.test.tsx +198 -0
  65. package/src/context-panel.tsx +609 -0
  66. package/src/context.stories.tsx +16 -0
  67. package/src/context.tsx +363 -0
  68. package/src/controls.tsx +20 -0
  69. package/src/conversation.stories.tsx +26 -0
  70. package/src/conversation.test.tsx +123 -0
  71. package/src/conversation.tsx +143 -0
  72. package/src/dark-theme-variant.test.ts +47 -0
  73. package/src/edge.tsx +33 -0
  74. package/src/environment-variables.tsx +304 -0
  75. package/src/file-tree.stories.tsx +55 -0
  76. package/src/file-tree.test.tsx +101 -0
  77. package/src/file-tree.tsx +390 -0
  78. package/src/gallery.stories.tsx +182 -0
  79. package/src/gallery.test.tsx +150 -0
  80. package/src/gallery.tsx +737 -0
  81. package/src/grouped-parts.stories.tsx +104 -0
  82. package/src/grouped-parts.test.tsx +167 -0
  83. package/src/grouped-parts.tsx +247 -0
  84. package/src/image.stories.tsx +67 -0
  85. package/src/image.test.tsx +105 -0
  86. package/src/image.tsx +115 -0
  87. package/src/index.ts +93 -0
  88. package/src/inline-citation.stories.tsx +91 -0
  89. package/src/inline-citation.test.tsx +96 -0
  90. package/src/inline-citation.tsx +314 -0
  91. package/src/interactive-terminal.stories.tsx +165 -0
  92. package/src/interactive-terminal.test.tsx +448 -0
  93. package/src/interactive-terminal.tsx +444 -0
  94. package/src/jsx-preview.stories.tsx +265 -0
  95. package/src/jsx-preview.test.tsx +75 -0
  96. package/src/jsx-preview.tsx +409 -0
  97. package/src/markdown-view.stories.tsx +57 -0
  98. package/src/markdown-view.test.tsx +36 -0
  99. package/src/markdown-view.tsx +113 -0
  100. package/src/message-edit.stories.tsx +150 -0
  101. package/src/message-edit.test.tsx +115 -0
  102. package/src/message-edit.tsx +336 -0
  103. package/src/message-feedback.stories.tsx +53 -0
  104. package/src/message-feedback.test.tsx +62 -0
  105. package/src/message-feedback.tsx +117 -0
  106. package/src/message-form-spec.ts +349 -0
  107. package/src/message-form.stories.tsx +182 -0
  108. package/src/message-form.test.tsx +227 -0
  109. package/src/message-form.tsx +845 -0
  110. package/src/message-table-spec.ts +281 -0
  111. package/src/message-table.stories.tsx +176 -0
  112. package/src/message-table.test.tsx +144 -0
  113. package/src/message-table.tsx +366 -0
  114. package/src/message.stories.tsx +262 -0
  115. package/src/message.test.tsx +508 -0
  116. package/src/message.tsx +619 -0
  117. package/src/mic-selector.tsx +339 -0
  118. package/src/microcopy.test.tsx +123 -0
  119. package/src/model-selector.stories.tsx +73 -0
  120. package/src/model-selector.test.tsx +55 -0
  121. package/src/model-selector.tsx +225 -0
  122. package/src/motion-config.tsx +49 -0
  123. package/src/node.tsx +71 -0
  124. package/src/open-in-chat.tsx +340 -0
  125. package/src/package-info.tsx +205 -0
  126. package/src/panel.tsx +20 -0
  127. package/src/part-groups.ts +258 -0
  128. package/src/persona-sources.ts +59 -0
  129. package/src/persona.stories.tsx +111 -0
  130. package/src/persona.test.tsx +67 -0
  131. package/src/persona.tsx +148 -0
  132. package/src/plan.tsx +135 -0
  133. package/src/prompt-input.stories.tsx +261 -0
  134. package/src/prompt-input.test.tsx +392 -0
  135. package/src/prompt-input.tsx +1668 -0
  136. package/src/queue.tsx +237 -0
  137. package/src/reasoning.stories.tsx +81 -0
  138. package/src/reasoning.test.tsx +50 -0
  139. package/src/reasoning.tsx +229 -0
  140. package/src/sandbox.stories.tsx +62 -0
  141. package/src/sandbox.test.tsx +42 -0
  142. package/src/sandbox.tsx +149 -0
  143. package/src/schema-display.tsx +412 -0
  144. package/src/selection-toolbar.stories.tsx +86 -0
  145. package/src/selection-toolbar.test.tsx +89 -0
  146. package/src/selection-toolbar.tsx +192 -0
  147. package/src/shimmer.stories.tsx +10 -0
  148. package/src/shimmer.tsx +81 -0
  149. package/src/snippet.stories.tsx +19 -0
  150. package/src/snippet.test.tsx +116 -0
  151. package/src/snippet.tsx +138 -0
  152. package/src/sources.stories.tsx +34 -0
  153. package/src/sources.test.tsx +129 -0
  154. package/src/sources.tsx +93 -0
  155. package/src/speech-input.tsx +312 -0
  156. package/src/stack-trace.tsx +479 -0
  157. package/src/streamdown-i18n.test.tsx +163 -0
  158. package/src/suggestion.stories.tsx +75 -0
  159. package/src/suggestion.test.tsx +72 -0
  160. package/src/suggestion.tsx +120 -0
  161. package/src/task.stories.tsx +22 -0
  162. package/src/task.test.tsx +36 -0
  163. package/src/task.tsx +89 -0
  164. package/src/templates-ai-assistant.stories.tsx +142 -0
  165. package/src/terminal.tsx +244 -0
  166. package/src/test-results.stories.tsx +177 -0
  167. package/src/test-results.test.tsx +241 -0
  168. package/src/test-results.tsx +408 -0
  169. package/src/tool-result-card.stories.tsx +143 -0
  170. package/src/tool-result-card.test.tsx +72 -0
  171. package/src/tool-result-card.tsx +86 -0
  172. package/src/tool.stories.tsx +60 -0
  173. package/src/tool.test.tsx +63 -0
  174. package/src/tool.tsx +235 -0
  175. package/src/toolbar.tsx +44 -0
  176. package/src/transcription.tsx +118 -0
  177. package/src/voice-selector.tsx +469 -0
  178. package/src/web-preview.stories.tsx +67 -0
  179. package/src/web-preview.test.tsx +117 -0
  180. package/src/web-preview.tsx +283 -0
@@ -0,0 +1,218 @@
1
+ "use client";
2
+
3
+ /**
4
+ * AssetPreview — type-keyed preview of one produced asset (#193, research 04
5
+ * §5 ASSET-4). Reuses the `Artifact` chrome for the header/actions; the body
6
+ * switches on `ContextAsset.type`:
7
+ *
8
+ * markdown → `MarkdownView` (the branded renderer — a document, never
9
+ * Shiki source; the ASSET-2 fix)
10
+ * code/sql → `CodeBlock` (Shiki)
11
+ * csv → a small token-styled table + row-count summary
12
+ * image → an image preview
13
+ *
14
+ * A Preview / Raw toggle serves users who want the source (Raw = `CodeBlock`,
15
+ * soft-wrapped for narrow embeds). Selection state lives in the
16
+ * `ContextPanelProvider` — the tree and this preview are the two levels of the
17
+ * drill-in.
18
+ *
19
+ * Formats beyond that switch — a PDF, a spreadsheet, a video — arrive through
20
+ * `renderPreview` (prop, or injected once on `ContextPanelProvider`), because
21
+ * `@elabs-ai/components-viewer` is a layer PEER of this package and
22
+ * neither may import the other (ADR 0024 §6). A renderer that returns `null`
23
+ * declines, and everything below runs exactly as before.
24
+ */
25
+ import {
26
+ Button,
27
+ Table,
28
+ TableBody,
29
+ TableCell,
30
+ TableHead,
31
+ TableHeader,
32
+ TableRow,
33
+ } from "@elabs-ai/components-ui";
34
+ import { cn } from "@elabs-ai/components-ui/lib/cn";
35
+ import type { HTMLAttributes, ReactNode } from "react";
36
+ import { useMemo, useState } from "react";
37
+ import type { BundledLanguage } from "shiki";
38
+ import {
39
+ Artifact,
40
+ ArtifactActions,
41
+ ArtifactContent,
42
+ ArtifactHeader,
43
+ ArtifactTitle,
44
+ } from "./artifact";
45
+ import { CodeBlock } from "./code-block";
46
+ import type { AssetPreviewRenderer, ContextAsset } from "./context-panel";
47
+ import { useAssetPreviewRenderer } from "./context-panel";
48
+ import { MarkdownView } from "./markdown-view";
49
+
50
+ export type AssetPreviewMode = "preview" | "raw";
51
+
52
+ const DEFAULT_CODE_LANGUAGE: BundledLanguage = "typescript";
53
+
54
+ /** Raw-mode (and code-preview) Shiki language for an asset. */
55
+ function assetLanguage(asset: ContextAsset): BundledLanguage {
56
+ switch (asset.type) {
57
+ case "markdown":
58
+ return "markdown";
59
+ case "sql":
60
+ return "sql";
61
+ case "csv":
62
+ return "csv";
63
+ case "code":
64
+ return (asset.language as BundledLanguage) ?? DEFAULT_CODE_LANGUAGE;
65
+ default:
66
+ return DEFAULT_CODE_LANGUAGE;
67
+ }
68
+ }
69
+
70
+ interface ParsedCsv {
71
+ header: string[];
72
+ rows: string[][];
73
+ }
74
+
75
+ /** Minimal preview-grade CSV split (no quoted-comma handling — it's a glance, not a grid). */
76
+ function parseCsv(content: string): ParsedCsv {
77
+ const lines = content
78
+ .trim()
79
+ .split(/\r?\n/)
80
+ .filter((line) => line.length > 0);
81
+ const [head = "", ...rest] = lines;
82
+ const split = (line: string) => line.split(",").map((cell) => cell.trim());
83
+ return { header: split(head), rows: rest.map(split) };
84
+ }
85
+
86
+ const CsvPreview = ({ content }: { content: string }) => {
87
+ const { header, rows } = useMemo(() => parseCsv(content), [content]);
88
+ return (
89
+ <div className="flex flex-col gap-2">
90
+ <Table className="text-body tabular-nums">
91
+ <TableHeader>
92
+ <TableRow>
93
+ {header.map((cell) => (
94
+ <TableHead key={cell}>{cell}</TableHead>
95
+ ))}
96
+ </TableRow>
97
+ </TableHeader>
98
+ <TableBody>
99
+ {rows.map((row, rowIndex) => (
100
+ // Rows have no stable identity in raw CSV — index is the key.
101
+ // oxlint-disable-next-line eslint-plugin-react(no-array-index-key)
102
+ <TableRow key={`row-${rowIndex}`}>
103
+ {row.map((cell, cellIndex) => (
104
+ // oxlint-disable-next-line eslint-plugin-react(no-array-index-key)
105
+ <TableCell key={`cell-${rowIndex}-${cellIndex}`}>{cell}</TableCell>
106
+ ))}
107
+ </TableRow>
108
+ ))}
109
+ </TableBody>
110
+ </Table>
111
+ <p className="text-meta text-muted-foreground">
112
+ {rows.length} {rows.length === 1 ? "row" : "rows"}
113
+ </p>
114
+ </div>
115
+ );
116
+ };
117
+
118
+ export interface AssetPreviewProps extends HTMLAttributes<HTMLDivElement> {
119
+ asset: ContextAsset;
120
+ /** Initial mode. Default `"preview"`. */
121
+ defaultMode?: AssetPreviewMode;
122
+ /**
123
+ * Draw this asset's preview body yourself; return `null` to decline and get
124
+ * the built-in rendering. Wins over a renderer injected on
125
+ * `ContextPanelProvider`, so one rail-wide default can still be overridden
126
+ * for a single preview.
127
+ */
128
+ renderPreview?: AssetPreviewRenderer;
129
+ }
130
+
131
+ export const AssetPreview = ({
132
+ asset,
133
+ defaultMode = "preview",
134
+ renderPreview,
135
+ className,
136
+ ...props
137
+ }: AssetPreviewProps) => {
138
+ const [mode, setMode] = useState<AssetPreviewMode>(defaultMode);
139
+ const injectedRenderer = useAssetPreviewRenderer();
140
+ const content = asset.content ?? "";
141
+ // Raw source only exists for text assets with content.
142
+ const hasRaw = asset.type !== "image" && content.length > 0;
143
+ const showRaw = mode === "raw" && hasRaw;
144
+
145
+ // Raw is "show me the source", so an injection never intercepts it.
146
+ const render = renderPreview ?? injectedRenderer;
147
+ const injected = !showRaw && render ? render(asset) : null;
148
+
149
+ let body: ReactNode;
150
+ if (injected !== null) {
151
+ body = injected;
152
+ } else if (asset.type !== "image" && content.length === 0) {
153
+ body = <p className="text-body text-muted-foreground">No preview available…</p>;
154
+ } else if (showRaw) {
155
+ body = <CodeBlock code={content} language={assetLanguage(asset)} wrap />;
156
+ } else {
157
+ switch (asset.type) {
158
+ case "markdown": {
159
+ // Constrained heading rung inside the narrow rail (research 09 §G.2).
160
+ body = <MarkdownView baseHeadingLevel={2}>{content}</MarkdownView>;
161
+ break;
162
+ }
163
+ case "code":
164
+ case "sql": {
165
+ body = <CodeBlock code={content} language={assetLanguage(asset)} showLineNumbers wrap />;
166
+ break;
167
+ }
168
+ case "csv": {
169
+ body = <CsvPreview content={content} />;
170
+ break;
171
+ }
172
+ case "image": {
173
+ body = (
174
+ <img
175
+ src={content || asset.path}
176
+ alt={asset.name}
177
+ loading="lazy"
178
+ className="max-w-full rounded-md"
179
+ />
180
+ );
181
+ break;
182
+ }
183
+ }
184
+ }
185
+
186
+ return (
187
+ <Artifact data-slot="asset-preview" className={className} {...props}>
188
+ <ArtifactHeader>
189
+ <ArtifactTitle className="min-w-0 truncate">{asset.name}</ArtifactTitle>
190
+ {hasRaw ? (
191
+ <ArtifactActions>
192
+ <Button
193
+ type="button"
194
+ variant="ghost"
195
+ size="sm"
196
+ aria-pressed={!showRaw}
197
+ className={cn(!showRaw && "bg-accent text-accent-foreground")}
198
+ onClick={() => setMode("preview")}
199
+ >
200
+ Preview
201
+ </Button>
202
+ <Button
203
+ type="button"
204
+ variant="ghost"
205
+ size="sm"
206
+ aria-pressed={showRaw}
207
+ className={cn(showRaw && "bg-accent text-accent-foreground")}
208
+ onClick={() => setMode("raw")}
209
+ >
210
+ Raw
211
+ </Button>
212
+ </ArtifactActions>
213
+ ) : null}
214
+ </ArtifactHeader>
215
+ <ArtifactContent>{body}</ArtifactContent>
216
+ </Artifact>
217
+ );
218
+ };
@@ -0,0 +1,393 @@
1
+ "use client";
2
+
3
+ import { Button } from "@elabs-ai/components-ui";
4
+ import { HoverCard, HoverCardContent, HoverCardTrigger } from "@elabs-ai/components-ui";
5
+ import { cn } from "@elabs-ai/components-ui/lib/cn";
6
+ import type { FileUIPart, SourceDocumentUIPart } from "ai";
7
+ import {
8
+ FileTextIcon,
9
+ GlobeIcon,
10
+ ImageIcon,
11
+ Music2Icon,
12
+ PaperclipIcon,
13
+ VideoIcon,
14
+ XIcon,
15
+ } from "lucide-react";
16
+ import type { ComponentProps, HTMLAttributes, ReactNode } from "react";
17
+ import { createContext, useCallback, useContext, useMemo } from "react";
18
+
19
+ // ============================================================================
20
+ // Types
21
+ // ============================================================================
22
+
23
+ export type AttachmentData =
24
+ | (FileUIPart & { id: string })
25
+ | (SourceDocumentUIPart & { id: string });
26
+
27
+ export type AttachmentMediaCategory =
28
+ | "image"
29
+ | "video"
30
+ | "audio"
31
+ | "document"
32
+ | "source"
33
+ | "unknown";
34
+
35
+ export type AttachmentVariant = "grid" | "inline" | "list";
36
+
37
+ const mediaCategoryIcons: Record<AttachmentMediaCategory, typeof ImageIcon> = {
38
+ audio: Music2Icon,
39
+ document: FileTextIcon,
40
+ image: ImageIcon,
41
+ source: GlobeIcon,
42
+ unknown: PaperclipIcon,
43
+ video: VideoIcon,
44
+ };
45
+
46
+ // ============================================================================
47
+ // Utility Functions
48
+ // ============================================================================
49
+
50
+ export const getMediaCategory = (data: AttachmentData): AttachmentMediaCategory => {
51
+ if (data.type === "source-document") {
52
+ return "source";
53
+ }
54
+
55
+ const mediaType = data.mediaType ?? "";
56
+
57
+ if (mediaType.startsWith("image/")) {
58
+ return "image";
59
+ }
60
+ if (mediaType.startsWith("video/")) {
61
+ return "video";
62
+ }
63
+ if (mediaType.startsWith("audio/")) {
64
+ return "audio";
65
+ }
66
+ if (mediaType.startsWith("application/") || mediaType.startsWith("text/")) {
67
+ return "document";
68
+ }
69
+
70
+ return "unknown";
71
+ };
72
+
73
+ export const getAttachmentLabel = (data: AttachmentData): string => {
74
+ if (data.type === "source-document") {
75
+ return data.title || data.filename || "Source";
76
+ }
77
+
78
+ const category = getMediaCategory(data);
79
+ return data.filename || (category === "image" ? "Image" : "Attachment");
80
+ };
81
+
82
+ const renderAttachmentImage = (url: string, filename: string | undefined, isGrid: boolean) =>
83
+ isGrid ? (
84
+ <img
85
+ alt={filename || "Image"}
86
+ className="size-full object-cover"
87
+ height={96}
88
+ src={url}
89
+ width={96}
90
+ />
91
+ ) : (
92
+ <img
93
+ alt={filename || "Image"}
94
+ className="size-full rounded object-cover"
95
+ height={20}
96
+ src={url}
97
+ width={20}
98
+ />
99
+ );
100
+
101
+ // ============================================================================
102
+ // Contexts
103
+ // ============================================================================
104
+
105
+ interface AttachmentsContextValue {
106
+ variant: AttachmentVariant;
107
+ }
108
+
109
+ const AttachmentsContext = createContext<AttachmentsContextValue | null>(null);
110
+
111
+ interface AttachmentContextValue {
112
+ data: AttachmentData;
113
+ mediaCategory: AttachmentMediaCategory;
114
+ onRemove?: () => void;
115
+ variant: AttachmentVariant;
116
+ }
117
+
118
+ const AttachmentContext = createContext<AttachmentContextValue | null>(null);
119
+
120
+ // ============================================================================
121
+ // Hooks
122
+ // ============================================================================
123
+
124
+ export const useAttachmentsContext = () =>
125
+ useContext(AttachmentsContext) ?? { variant: "grid" as const };
126
+
127
+ export const useAttachmentContext = () => {
128
+ const ctx = useContext(AttachmentContext);
129
+ if (!ctx) {
130
+ throw new Error("Attachment components must be used within <Attachment>");
131
+ }
132
+ return ctx;
133
+ };
134
+
135
+ // ============================================================================
136
+ // Attachments - Container
137
+ // ============================================================================
138
+
139
+ export type AttachmentsProps = HTMLAttributes<HTMLDivElement> & {
140
+ variant?: AttachmentVariant;
141
+ };
142
+
143
+ export const Attachments = ({
144
+ variant = "grid",
145
+ className,
146
+ children,
147
+ ...props
148
+ }: AttachmentsProps) => {
149
+ const contextValue = useMemo(() => ({ variant }), [variant]);
150
+
151
+ return (
152
+ <AttachmentsContext.Provider value={contextValue}>
153
+ <div
154
+ className={cn(
155
+ "flex items-start",
156
+ variant === "list" ? "flex-col gap-2" : "flex-wrap gap-2",
157
+ variant === "grid" && "ms-auto w-fit",
158
+ className,
159
+ )}
160
+ {...props}
161
+ >
162
+ {children}
163
+ </div>
164
+ </AttachmentsContext.Provider>
165
+ );
166
+ };
167
+
168
+ // ============================================================================
169
+ // Attachment - Item
170
+ // ============================================================================
171
+
172
+ export type AttachmentProps = HTMLAttributes<HTMLDivElement> & {
173
+ data: AttachmentData;
174
+ onRemove?: () => void;
175
+ };
176
+
177
+ export const Attachment = ({ data, onRemove, className, children, ...props }: AttachmentProps) => {
178
+ const { variant } = useAttachmentsContext();
179
+ const mediaCategory = getMediaCategory(data);
180
+
181
+ const contextValue = useMemo<AttachmentContextValue>(
182
+ () => ({ data, mediaCategory, onRemove, variant }),
183
+ [data, mediaCategory, onRemove, variant],
184
+ );
185
+
186
+ return (
187
+ <AttachmentContext.Provider value={contextValue}>
188
+ <div
189
+ className={cn(
190
+ "group relative",
191
+ variant === "grid" && "size-24 overflow-hidden rounded-lg",
192
+ variant === "inline" && [
193
+ "flex h-8 cursor-pointer select-none items-center gap-1.5",
194
+ "rounded-md border border-border px-1.5",
195
+ "font-medium text-sm transition-colors duration-fast ease-standard motion-reduce:transition-none",
196
+ "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
197
+ ],
198
+ variant === "list" && [
199
+ "flex w-full items-center gap-3 rounded-lg border p-3",
200
+ "hover:bg-accent/50",
201
+ ],
202
+ className,
203
+ )}
204
+ {...props}
205
+ >
206
+ {children}
207
+ </div>
208
+ </AttachmentContext.Provider>
209
+ );
210
+ };
211
+
212
+ // ============================================================================
213
+ // AttachmentPreview - Media preview
214
+ // ============================================================================
215
+
216
+ export type AttachmentPreviewProps = HTMLAttributes<HTMLDivElement> & {
217
+ fallbackIcon?: ReactNode;
218
+ };
219
+
220
+ export const AttachmentPreview = ({
221
+ fallbackIcon,
222
+ className,
223
+ ...props
224
+ }: AttachmentPreviewProps) => {
225
+ const { data, mediaCategory, variant } = useAttachmentContext();
226
+
227
+ const iconSize = variant === "inline" ? "size-3" : "size-4";
228
+
229
+ const renderIcon = (Icon: typeof ImageIcon) => (
230
+ <Icon className={cn(iconSize, "text-muted-foreground")} />
231
+ );
232
+
233
+ const renderContent = () => {
234
+ if (mediaCategory === "image" && data.type === "file" && data.url) {
235
+ return renderAttachmentImage(data.url, data.filename, variant === "grid");
236
+ }
237
+
238
+ if (mediaCategory === "video" && data.type === "file" && data.url) {
239
+ return <video className="size-full object-cover" muted src={data.url} />;
240
+ }
241
+
242
+ const Icon = mediaCategoryIcons[mediaCategory];
243
+ return fallbackIcon ?? renderIcon(Icon);
244
+ };
245
+
246
+ return (
247
+ <div
248
+ className={cn(
249
+ "flex shrink-0 items-center justify-center overflow-hidden",
250
+ variant === "grid" && "size-full bg-muted",
251
+ variant === "inline" && "size-5 rounded bg-background",
252
+ variant === "list" && "size-12 rounded bg-muted",
253
+ className,
254
+ )}
255
+ {...props}
256
+ >
257
+ {renderContent()}
258
+ </div>
259
+ );
260
+ };
261
+
262
+ // ============================================================================
263
+ // AttachmentInfo - Name and type display
264
+ // ============================================================================
265
+
266
+ export type AttachmentInfoProps = HTMLAttributes<HTMLDivElement> & {
267
+ showMediaType?: boolean;
268
+ };
269
+
270
+ export const AttachmentInfo = ({
271
+ showMediaType = false,
272
+ className,
273
+ ...props
274
+ }: AttachmentInfoProps) => {
275
+ const { data, variant } = useAttachmentContext();
276
+ const label = getAttachmentLabel(data);
277
+
278
+ if (variant === "grid") {
279
+ return null;
280
+ }
281
+
282
+ return (
283
+ <div className={cn("min-w-0 flex-1", className)} {...props}>
284
+ <span className="block truncate">{label}</span>
285
+ {showMediaType && data.mediaType && (
286
+ <span className="block truncate text-muted-foreground text-xs">{data.mediaType}</span>
287
+ )}
288
+ </div>
289
+ );
290
+ };
291
+
292
+ // ============================================================================
293
+ // AttachmentRemove - Remove button
294
+ // ============================================================================
295
+
296
+ export type AttachmentRemoveProps = ComponentProps<typeof Button> & {
297
+ label?: string;
298
+ };
299
+
300
+ export const AttachmentRemove = ({
301
+ label = "Remove",
302
+ className,
303
+ children,
304
+ ...props
305
+ }: AttachmentRemoveProps) => {
306
+ const { onRemove, variant } = useAttachmentContext();
307
+
308
+ const handleClick = useCallback(
309
+ (e: React.MouseEvent) => {
310
+ e.stopPropagation();
311
+ onRemove?.();
312
+ },
313
+ [onRemove],
314
+ );
315
+
316
+ if (!onRemove) {
317
+ return null;
318
+ }
319
+
320
+ return (
321
+ <Button
322
+ aria-label={label}
323
+ className={cn(
324
+ variant === "grid" && [
325
+ "absolute top-2 end-2 size-6 rounded-full p-0",
326
+ "bg-background/80 backdrop-blur-sm",
327
+ "opacity-0 transition-opacity group-hover:opacity-100",
328
+ "hover:bg-background",
329
+ "[&>svg]:size-3",
330
+ ],
331
+ variant === "inline" && [
332
+ "size-5 rounded p-0",
333
+ "opacity-0 transition-opacity group-hover:opacity-100",
334
+ "[&>svg]:size-2.5",
335
+ ],
336
+ variant === "list" && ["size-8 shrink-0 rounded p-0", "[&>svg]:size-4"],
337
+ className,
338
+ )}
339
+ onClick={handleClick}
340
+ type="button"
341
+ variant="ghost"
342
+ {...props}
343
+ >
344
+ {children ?? <XIcon />}
345
+ <span className="sr-only">{label}</span>
346
+ </Button>
347
+ );
348
+ };
349
+
350
+ // ============================================================================
351
+ // AttachmentHoverCard - Hover preview
352
+ // ============================================================================
353
+
354
+ export type AttachmentHoverCardProps = ComponentProps<typeof HoverCard>;
355
+
356
+ export const AttachmentHoverCard = ({
357
+ openDelay = 0,
358
+ closeDelay = 0,
359
+ ...props
360
+ }: AttachmentHoverCardProps) => (
361
+ <HoverCard closeDelay={closeDelay} openDelay={openDelay} {...props} />
362
+ );
363
+
364
+ export type AttachmentHoverCardTriggerProps = ComponentProps<typeof HoverCardTrigger>;
365
+
366
+ export const AttachmentHoverCardTrigger = (props: AttachmentHoverCardTriggerProps) => (
367
+ <HoverCardTrigger {...props} />
368
+ );
369
+
370
+ export type AttachmentHoverCardContentProps = ComponentProps<typeof HoverCardContent>;
371
+
372
+ export const AttachmentHoverCardContent = ({
373
+ align = "start",
374
+ className,
375
+ ...props
376
+ }: AttachmentHoverCardContentProps) => (
377
+ <HoverCardContent align={align} className={cn("w-auto p-2", className)} {...props} />
378
+ );
379
+
380
+ // ============================================================================
381
+ // AttachmentEmpty - Empty state
382
+ // ============================================================================
383
+
384
+ export type AttachmentEmptyProps = HTMLAttributes<HTMLDivElement>;
385
+
386
+ export const AttachmentEmpty = ({ className, children, ...props }: AttachmentEmptyProps) => (
387
+ <div
388
+ className={cn("flex items-center justify-center p-4 text-muted-foreground text-sm", className)}
389
+ {...props}
390
+ >
391
+ {children ?? "No attachments"}
392
+ </div>
393
+ );
@@ -0,0 +1,99 @@
1
+ import type { Meta, StoryObj } from "@storybook/react-vite";
2
+ import { expect, waitFor } from "storybook/test";
3
+
4
+ import {
5
+ AudioPlayer,
6
+ AudioPlayerControlBar,
7
+ AudioPlayerDurationDisplay,
8
+ AudioPlayerElement,
9
+ AudioPlayerMuteButton,
10
+ AudioPlayerPlayButton,
11
+ AudioPlayerSeekBackwardButton,
12
+ AudioPlayerSeekForwardButton,
13
+ AudioPlayerTimeDisplay,
14
+ AudioPlayerTimeRange,
15
+ AudioPlayerVolumeRange,
16
+ } from "./audio-player";
17
+
18
+ const meta = {
19
+ title: "AI/AudioPlayer",
20
+ component: AudioPlayer,
21
+ tags: ["autodocs"],
22
+ parameters: {
23
+ layout: "padded",
24
+ docs: {
25
+ description: {
26
+ component:
27
+ "A token-themed **media-chrome** audio player for spoken agent replies. Every " +
28
+ "control is a media-chrome custom element re-skinned through the `--media-*` " +
29
+ "custom properties, so it tracks the active theme. The engine is loaded through " +
30
+ "a dynamic `import()` (ADR 0019) — it is not in any consumer's entry chunk — so " +
31
+ "the player renders a layout-shaped `Skeleton` for the first frame.",
32
+ },
33
+ },
34
+ },
35
+ } satisfies Meta<typeof AudioPlayer>;
36
+
37
+ export default meta;
38
+ type Story = StoryObj<typeof meta>;
39
+
40
+ /**
41
+ * A ~1.5 s silent 8-bit mono WAV, synthesized at module scope so the story needs
42
+ * no network origin (see `docs/CSP-AND-NETWORK.md`) and no binary fixture.
43
+ */
44
+ function silentWavSrc(seconds = 1.5, sampleRate = 8000): string {
45
+ const samples = Math.floor(seconds * sampleRate);
46
+ const bytes = new Uint8Array(44 + samples).fill(128); // 128 == silence, 8-bit unsigned
47
+ const view = new DataView(bytes.buffer);
48
+ const ascii = (offset: number, text: string) => {
49
+ for (let i = 0; i < text.length; i += 1) view.setUint8(offset + i, text.charCodeAt(i));
50
+ };
51
+ ascii(0, "RIFF");
52
+ view.setUint32(4, 36 + samples, true);
53
+ ascii(8, "WAVEfmt ");
54
+ view.setUint32(16, 16, true); // PCM header size
55
+ view.setUint16(20, 1, true); // format: PCM
56
+ view.setUint16(22, 1, true); // channels: mono
57
+ view.setUint32(24, sampleRate, true);
58
+ view.setUint32(28, sampleRate, true); // byte rate
59
+ view.setUint16(32, 1, true); // block align
60
+ view.setUint16(34, 8, true); // bits per sample
61
+ ascii(36, "data");
62
+ view.setUint32(40, samples, true);
63
+
64
+ let binary = "";
65
+ for (const byte of bytes) binary += String.fromCharCode(byte);
66
+ return `data:audio/wav;base64,${btoa(binary)}`;
67
+ }
68
+
69
+ const SILENT_WAV = silentWavSrc();
70
+
71
+ export const Default: Story = {
72
+ render: () => (
73
+ <AudioPlayer className="block w-full max-w-lg rounded-md border">
74
+ <AudioPlayerElement src={SILENT_WAV} />
75
+ <AudioPlayerControlBar>
76
+ <AudioPlayerSeekBackwardButton />
77
+ <AudioPlayerPlayButton />
78
+ <AudioPlayerSeekForwardButton />
79
+ <AudioPlayerTimeDisplay />
80
+ <AudioPlayerTimeRange />
81
+ <AudioPlayerDurationDisplay />
82
+ <AudioPlayerMuteButton />
83
+ <AudioPlayerVolumeRange />
84
+ </AudioPlayerControlBar>
85
+ </AudioPlayer>
86
+ ),
87
+ play: async ({ canvasElement }) => {
88
+ // media-chrome arrives in a lazy chunk (#313): the controls are absent for
89
+ // the first frame, so this also locks in that the chunk actually resolves.
90
+ await waitFor(
91
+ () => {
92
+ expect(canvasElement.querySelector("media-controller")).not.toBeNull();
93
+ expect(canvasElement.querySelector("media-play-button")).not.toBeNull();
94
+ expect(canvasElement.querySelector("media-time-range")).not.toBeNull();
95
+ },
96
+ { timeout: 10000 },
97
+ );
98
+ },
99
+ };