@leitware/composables 0.1.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 (209) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +387 -0
  3. package/dist/presets/brutalist.css +298 -0
  4. package/dist/presets/default.css +298 -0
  5. package/dist/presets/signal-pop.css +369 -0
  6. package/dist/styles.css +2 -0
  7. package/package.json +216 -0
  8. package/rules/composables.md +244 -0
  9. package/src/_internal/accordion.tsx +93 -0
  10. package/src/_internal/ai-elements/attachments.tsx +385 -0
  11. package/src/_internal/ai-elements/chain-of-thought.tsx +197 -0
  12. package/src/_internal/ai-elements/code-block.tsx +516 -0
  13. package/src/_internal/ai-elements/confirmation.tsx +150 -0
  14. package/src/_internal/ai-elements/conversation.tsx +148 -0
  15. package/src/_internal/ai-elements/inline-citation.tsx +248 -0
  16. package/src/_internal/ai-elements/message.tsx +292 -0
  17. package/src/_internal/ai-elements/plan.tsx +126 -0
  18. package/src/_internal/ai-elements/prompt-input.tsx +1285 -0
  19. package/src/_internal/ai-elements/reasoning.tsx +208 -0
  20. package/src/_internal/ai-elements/shimmer.tsx +72 -0
  21. package/src/_internal/ai-elements/sources.tsx +53 -0
  22. package/src/_internal/ai-elements/suggestion.tsx +48 -0
  23. package/src/_internal/ai-elements/task.tsx +64 -0
  24. package/src/_internal/ai-elements/tool.tsx +156 -0
  25. package/src/_internal/alert-dialog.tsx +159 -0
  26. package/src/_internal/alert.tsx +88 -0
  27. package/src/_internal/aspect-ratio.tsx +23 -0
  28. package/src/_internal/avatar.tsx +58 -0
  29. package/src/_internal/badge.tsx +60 -0
  30. package/src/_internal/breadcrumb.tsx +104 -0
  31. package/src/_internal/bubble.tsx +125 -0
  32. package/src/_internal/button-group.tsx +78 -0
  33. package/src/_internal/button.tsx +62 -0
  34. package/src/_internal/calendar.tsx +179 -0
  35. package/src/_internal/card.tsx +83 -0
  36. package/src/_internal/carousel.tsx +215 -0
  37. package/src/_internal/checkbox.tsx +26 -0
  38. package/src/_internal/code-block.tsx +53 -0
  39. package/src/_internal/collapsible.tsx +15 -0
  40. package/src/_internal/combobox.tsx +264 -0
  41. package/src/_internal/command.tsx +155 -0
  42. package/src/_internal/container.tsx +35 -0
  43. package/src/_internal/dialog.tsx +132 -0
  44. package/src/_internal/direction.tsx +12 -0
  45. package/src/_internal/divider.tsx +162 -0
  46. package/src/_internal/dropdown-menu.tsx +247 -0
  47. package/src/_internal/dropzone.tsx +481 -0
  48. package/src/_internal/empty.tsx +94 -0
  49. package/src/_internal/field.tsx +221 -0
  50. package/src/_internal/grid-overlay.tsx +48 -0
  51. package/src/_internal/grid.tsx +109 -0
  52. package/src/_internal/hover-card.tsx +47 -0
  53. package/src/_internal/icon.tsx +45 -0
  54. package/src/_internal/input-group.tsx +146 -0
  55. package/src/_internal/input.tsx +24 -0
  56. package/src/_internal/item.tsx +187 -0
  57. package/src/_internal/kbd.tsx +28 -0
  58. package/src/_internal/label.tsx +18 -0
  59. package/src/_internal/layout-bento.tsx +386 -0
  60. package/src/_internal/layout.tsx +174 -0
  61. package/src/_internal/marker.tsx +66 -0
  62. package/src/_internal/message.tsx +85 -0
  63. package/src/_internal/native-select.tsx +50 -0
  64. package/src/_internal/pagination.tsx +108 -0
  65. package/src/_internal/popover.tsx +83 -0
  66. package/src/_internal/progress.tsx +59 -0
  67. package/src/_internal/radio-group.tsx +36 -0
  68. package/src/_internal/resizable.tsx +44 -0
  69. package/src/_internal/scroll-area.tsx +48 -0
  70. package/src/_internal/select.tsx +187 -0
  71. package/src/_internal/separator.tsx +19 -0
  72. package/src/_internal/sheet.tsx +122 -0
  73. package/src/_internal/sidebar.tsx +687 -0
  74. package/src/_internal/skeleton.tsx +13 -0
  75. package/src/_internal/slider.tsx +60 -0
  76. package/src/_internal/sonner.tsx +51 -0
  77. package/src/_internal/spacer.tsx +42 -0
  78. package/src/_internal/spinner.tsx +16 -0
  79. package/src/_internal/stack.tsx +78 -0
  80. package/src/_internal/switch.tsx +31 -0
  81. package/src/_internal/table.tsx +84 -0
  82. package/src/_internal/tabs.tsx +74 -0
  83. package/src/_internal/textarea.tsx +19 -0
  84. package/src/_internal/toggle-group.tsx +99 -0
  85. package/src/_internal/toggle.tsx +42 -0
  86. package/src/_internal/tooltip.tsx +55 -0
  87. package/src/_internal/typography.tsx +129 -0
  88. package/src/hooks/use-mobile.ts +19 -0
  89. package/src/hooks/use-numeric-input.ts +119 -0
  90. package/src/index.ts +443 -0
  91. package/src/lib/numeric-input.ts +88 -0
  92. package/src/lib/utils.ts +39 -0
  93. package/src/opinionated/accordion.tsx +92 -0
  94. package/src/opinionated/ai/attachments.tsx +27 -0
  95. package/src/opinionated/ai/chain-of-thought.tsx +16 -0
  96. package/src/opinionated/ai/code-block.tsx +22 -0
  97. package/src/opinionated/ai/confirmation.tsx +16 -0
  98. package/src/opinionated/ai/conversation.tsx +13 -0
  99. package/src/opinionated/ai/index.ts +15 -0
  100. package/src/opinionated/ai/inline-citation.tsx +30 -0
  101. package/src/opinionated/ai/message.tsx +26 -0
  102. package/src/opinionated/ai/plan.tsx +18 -0
  103. package/src/opinionated/ai/prompt-input.tsx +29 -0
  104. package/src/opinionated/ai/reasoning.tsx +9 -0
  105. package/src/opinionated/ai/shimmer.tsx +4 -0
  106. package/src/opinionated/ai/sources.tsx +10 -0
  107. package/src/opinionated/ai/suggestion.tsx +6 -0
  108. package/src/opinionated/ai/task.tsx +12 -0
  109. package/src/opinionated/ai/tool.tsx +14 -0
  110. package/src/opinionated/alert-dialog.tsx +143 -0
  111. package/src/opinionated/alert.tsx +99 -0
  112. package/src/opinionated/aspect-ratio.tsx +12 -0
  113. package/src/opinionated/avatar.tsx +59 -0
  114. package/src/opinionated/badge.tsx +33 -0
  115. package/src/opinionated/breadcrumb.tsx +99 -0
  116. package/src/opinionated/bubble.tsx +9 -0
  117. package/src/opinionated/button.tsx +59 -0
  118. package/src/opinionated/calendar.tsx +20 -0
  119. package/src/opinionated/card.tsx +83 -0
  120. package/src/opinionated/carousel.tsx +99 -0
  121. package/src/opinionated/checkbox.tsx +11 -0
  122. package/src/opinionated/code-block.tsx +12 -0
  123. package/src/opinionated/collapsible.tsx +123 -0
  124. package/src/opinionated/combobox.tsx +123 -0
  125. package/src/opinionated/container.tsx +12 -0
  126. package/src/opinionated/dialog.tsx +124 -0
  127. package/src/opinionated/direction.tsx +6 -0
  128. package/src/opinionated/divider.tsx +13 -0
  129. package/src/opinionated/dropdown-menu.tsx +131 -0
  130. package/src/opinionated/dropzone.tsx +39 -0
  131. package/src/opinionated/empty.tsx +191 -0
  132. package/src/opinionated/field.tsx +26 -0
  133. package/src/opinionated/form-calendar-popover.tsx +138 -0
  134. package/src/opinionated/form-checkbox.tsx +107 -0
  135. package/src/opinionated/form-combobox.tsx +181 -0
  136. package/src/opinionated/form-date-of-birth.tsx +193 -0
  137. package/src/opinionated/form-dropzone.tsx +126 -0
  138. package/src/opinionated/form-input-group.tsx +184 -0
  139. package/src/opinionated/form-input.tsx +118 -0
  140. package/src/opinionated/form-multi-combobox.tsx +213 -0
  141. package/src/opinionated/form-multi-dropzone.tsx +141 -0
  142. package/src/opinionated/form-radiogroup.tsx +116 -0
  143. package/src/opinionated/form-select.tsx +176 -0
  144. package/src/opinionated/form-slider.tsx +100 -0
  145. package/src/opinionated/form-switch.tsx +117 -0
  146. package/src/opinionated/form-textarea.tsx +79 -0
  147. package/src/opinionated/grid-overlay.tsx +11 -0
  148. package/src/opinionated/grid.tsx +14 -0
  149. package/src/opinionated/hover-card.tsx +59 -0
  150. package/src/opinionated/icon.tsx +14 -0
  151. package/src/opinionated/input-group.tsx +20 -0
  152. package/src/opinionated/input.tsx +11 -0
  153. package/src/opinionated/item.tsx +182 -0
  154. package/src/opinionated/kbd.tsx +16 -0
  155. package/src/opinionated/label.tsx +11 -0
  156. package/src/opinionated/layout-bento.tsx +29 -0
  157. package/src/opinionated/layout.tsx +26 -0
  158. package/src/opinionated/list.tsx +94 -0
  159. package/src/opinionated/marker.tsx +7 -0
  160. package/src/opinionated/message.tsx +8 -0
  161. package/src/opinionated/native-select.tsx +51 -0
  162. package/src/opinionated/pagination.tsx +204 -0
  163. package/src/opinionated/popover.tsx +68 -0
  164. package/src/opinionated/progress.tsx +48 -0
  165. package/src/opinionated/radio-group.tsx +13 -0
  166. package/src/opinionated/resizable.tsx +2 -0
  167. package/src/opinionated/scroll-area.tsx +82 -0
  168. package/src/opinionated/select.tsx +101 -0
  169. package/src/opinionated/separator.tsx +11 -0
  170. package/src/opinionated/sheet.tsx +120 -0
  171. package/src/opinionated/sidebar.tsx +68 -0
  172. package/src/opinionated/skeleton.tsx +246 -0
  173. package/src/opinionated/slider.tsx +11 -0
  174. package/src/opinionated/sonner.tsx +15 -0
  175. package/src/opinionated/spacer.tsx +11 -0
  176. package/src/opinionated/stack.tsx +18 -0
  177. package/src/opinionated/switch.tsx +11 -0
  178. package/src/opinionated/table.tsx +11 -0
  179. package/src/opinionated/tabs.tsx +68 -0
  180. package/src/opinionated/textarea.tsx +11 -0
  181. package/src/opinionated/theme-injector.tsx +31 -0
  182. package/src/opinionated/toggle-group.tsx +63 -0
  183. package/src/opinionated/toggle.tsx +75 -0
  184. package/src/opinionated/token-config-panel/color-editor.tsx +85 -0
  185. package/src/opinionated/token-config-panel/helpers.ts +31 -0
  186. package/src/opinionated/token-config-panel/index.tsx +398 -0
  187. package/src/opinionated/token-config-panel/json-import-export.tsx +89 -0
  188. package/src/opinionated/token-config-panel/preset-manager.ts +31 -0
  189. package/src/opinionated/token-config-panel/presets-data.ts +23 -0
  190. package/src/opinionated/token-config-panel/spacing-editor.tsx +325 -0
  191. package/src/opinionated/token-config-panel/types.ts +39 -0
  192. package/src/opinionated/token-config-panel/typography-editor.tsx +145 -0
  193. package/src/opinionated/tooltip.tsx +62 -0
  194. package/src/opinionated/typography.tsx +7 -0
  195. package/src/scripts/lint-no-arbitrary.ts +155 -0
  196. package/src/styles/composable.css +68 -0
  197. package/src/styles/presets/brutalist.css +298 -0
  198. package/src/styles/presets/default.css +298 -0
  199. package/src/styles/presets/signal-pop.css +369 -0
  200. package/src/styles/presets-data/brutalist.ts +325 -0
  201. package/src/styles/presets-data/default.ts +315 -0
  202. package/src/styles/presets-data/index.ts +45 -0
  203. package/src/styles/presets-data/signal-pop.ts +393 -0
  204. package/src/styles/tokens/base.css +71 -0
  205. package/src/styles/tokens/components.css +150 -0
  206. package/src/styles/tokens/palette.css +795 -0
  207. package/src/styles/tokens/registry.ts +324 -0
  208. package/src/styles/tokens/semantic.css +266 -0
  209. package/src/styles/tokens/tailwind-theme.css +247 -0
@@ -0,0 +1,516 @@
1
+ 'use client'
2
+
3
+ import { Button } from '../button'
4
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../select'
5
+ import { cn } from '../../lib/utils'
6
+ import { CheckIcon, CopyIcon } from 'lucide-react'
7
+ import type { ComponentProps, CSSProperties, HTMLAttributes } from 'react'
8
+ import {
9
+ createContext,
10
+ memo,
11
+ useCallback,
12
+ useContext,
13
+ useEffect,
14
+ useMemo,
15
+ useRef,
16
+ useState,
17
+ } from 'react'
18
+ import type { BundledLanguage, BundledTheme, HighlighterGeneric, ThemedToken } from 'shiki'
19
+ import { createHighlighter } from 'shiki'
20
+
21
+ // Shiki uses bitflags for font styles: 1=italic, 2=bold, 4=underline
22
+ // oxlint-disable-next-line eslint(no-bitwise)
23
+ const isItalic = (fontStyle: number | undefined) => fontStyle && fontStyle & 1
24
+ // oxlint-disable-next-line eslint(no-bitwise)
25
+ const isBold = (fontStyle: number | undefined) => fontStyle && fontStyle & 2
26
+ const isUnderline = (fontStyle: number | undefined) =>
27
+ // oxlint-disable-next-line eslint(no-bitwise)
28
+ fontStyle && fontStyle & 4
29
+
30
+ // Transform tokens to include pre-computed keys to avoid noArrayIndexKey lint
31
+ interface KeyedToken {
32
+ token: ThemedToken
33
+ key: string
34
+ }
35
+ interface KeyedLine {
36
+ tokens: KeyedToken[]
37
+ key: string
38
+ }
39
+
40
+ const addKeysToTokens = (lines: ThemedToken[][]): KeyedLine[] =>
41
+ lines.map((line, lineIdx) => ({
42
+ key: `line-${lineIdx}`,
43
+ tokens: line.map((token, tokenIdx) => ({
44
+ key: `line-${lineIdx}-${tokenIdx}`,
45
+ token,
46
+ })),
47
+ }))
48
+
49
+ // Token rendering component
50
+ const TokenSpan = ({ token }: { token: ThemedToken }) => (
51
+ <span
52
+ className="dark:!bg-[var(--shiki-dark-bg)] dark:!text-[var(--shiki-dark)]"
53
+ style={
54
+ {
55
+ backgroundColor: token.bgColor,
56
+ color: token.color,
57
+ fontStyle: isItalic(token.fontStyle) ? 'italic' : undefined,
58
+ fontWeight: isBold(token.fontStyle) ? 'bold' : undefined,
59
+ textDecoration: isUnderline(token.fontStyle) ? 'underline' : undefined,
60
+ ...token.htmlStyle,
61
+ } as CSSProperties
62
+ }
63
+ >
64
+ {token.content}
65
+ </span>
66
+ )
67
+
68
+ // Line number styles using CSS counters
69
+ const LINE_NUMBER_CLASSES = cn(
70
+ 'block',
71
+ 'before:content-[counter(line)]',
72
+ 'before:inline-block',
73
+ 'before:[counter-increment:line]',
74
+ 'before:w-8',
75
+ 'before:mr-4',
76
+ 'before:text-right',
77
+ 'before:text-muted-foreground/50',
78
+ 'before:font-mono',
79
+ 'before:select-none',
80
+ )
81
+
82
+ // Line rendering component
83
+ const LineSpan = ({
84
+ keyedLine,
85
+ showLineNumbers,
86
+ }: {
87
+ keyedLine: KeyedLine
88
+ showLineNumbers: boolean
89
+ }) => (
90
+ <span className={showLineNumbers ? LINE_NUMBER_CLASSES : 'block'}>
91
+ {keyedLine.tokens.length === 0
92
+ ? '\n'
93
+ : keyedLine.tokens.map(({ token, key }) => <TokenSpan key={key} token={token} />)}
94
+ </span>
95
+ )
96
+
97
+ // Types
98
+ type CodeBlockProps = HTMLAttributes<HTMLDivElement> & {
99
+ code: string
100
+ language: BundledLanguage
101
+ showLineNumbers?: boolean
102
+ }
103
+
104
+ interface TokenizedCode {
105
+ tokens: ThemedToken[][]
106
+ fg: string
107
+ bg: string
108
+ }
109
+
110
+ interface CodeBlockContextType {
111
+ code: string
112
+ }
113
+
114
+ // Context
115
+ const CodeBlockContext = createContext<CodeBlockContextType>({
116
+ code: '',
117
+ })
118
+
119
+ // Highlighter cache (singleton per language)
120
+ const highlighterCache = new Map<
121
+ string,
122
+ Promise<HighlighterGeneric<BundledLanguage, BundledTheme>>
123
+ >()
124
+
125
+ // Token cache
126
+ const tokensCache = new Map<string, TokenizedCode>()
127
+
128
+ // Subscribers for async token updates
129
+ const subscribers = new Map<string, Set<(result: TokenizedCode) => void>>()
130
+
131
+ const getTokensCacheKey = (code: string, language: BundledLanguage) => {
132
+ const start = code.slice(0, 100)
133
+ const end = code.length > 100 ? code.slice(-100) : ''
134
+ return `${language}:${code.length}:${start}:${end}`
135
+ }
136
+
137
+ const getHighlighter = (
138
+ language: BundledLanguage,
139
+ ): Promise<HighlighterGeneric<BundledLanguage, BundledTheme>> => {
140
+ const cached = highlighterCache.get(language)
141
+ if (cached) {
142
+ return cached
143
+ }
144
+
145
+ const highlighterPromise = createHighlighter({
146
+ langs: [language],
147
+ themes: ['github-light', 'github-dark'],
148
+ })
149
+
150
+ highlighterCache.set(language, highlighterPromise)
151
+ return highlighterPromise
152
+ }
153
+
154
+ // Create raw tokens for immediate display while highlighting loads
155
+ const createRawTokens = (code: string): TokenizedCode => ({
156
+ bg: 'transparent',
157
+ fg: 'inherit',
158
+ tokens: code.split('\n').map((line) =>
159
+ line === ''
160
+ ? []
161
+ : [
162
+ {
163
+ color: 'inherit',
164
+ content: line,
165
+ } as ThemedToken,
166
+ ],
167
+ ),
168
+ })
169
+
170
+ // Synchronous highlight with callback for async results
171
+ export const highlightCode = (
172
+ code: string,
173
+ language: BundledLanguage,
174
+ // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-callbacks)
175
+ callback?: (result: TokenizedCode) => void,
176
+ ): TokenizedCode | null => {
177
+ const tokensCacheKey = getTokensCacheKey(code, language)
178
+
179
+ // Return cached result if available
180
+ const cached = tokensCache.get(tokensCacheKey)
181
+ if (cached) {
182
+ return cached
183
+ }
184
+
185
+ // Subscribe callback if provided
186
+ if (callback) {
187
+ if (!subscribers.has(tokensCacheKey)) {
188
+ subscribers.set(tokensCacheKey, new Set())
189
+ }
190
+ subscribers.get(tokensCacheKey)?.add(callback)
191
+ }
192
+
193
+ // Start highlighting in background - fire-and-forget async pattern
194
+ getHighlighter(language)
195
+ // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-then)
196
+ .then((highlighter) => {
197
+ const availableLangs = highlighter.getLoadedLanguages()
198
+ const langToUse = availableLangs.includes(language) ? language : 'text'
199
+
200
+ const result = highlighter.codeToTokens(code, {
201
+ lang: langToUse,
202
+ themes: {
203
+ dark: 'github-dark',
204
+ light: 'github-light',
205
+ },
206
+ })
207
+
208
+ const tokenized: TokenizedCode = {
209
+ bg: result.bg ?? 'transparent',
210
+ fg: result.fg ?? 'inherit',
211
+ tokens: result.tokens,
212
+ }
213
+
214
+ // Cache the result
215
+ tokensCache.set(tokensCacheKey, tokenized)
216
+
217
+ // Notify all subscribers
218
+ const subs = subscribers.get(tokensCacheKey)
219
+ if (subs) {
220
+ for (const sub of subs) {
221
+ sub(tokenized)
222
+ }
223
+ subscribers.delete(tokensCacheKey)
224
+ }
225
+ })
226
+ // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-then), eslint-plugin-promise(prefer-await-to-callbacks)
227
+ .catch((error) => {
228
+ console.error('Failed to highlight code:', error)
229
+ subscribers.delete(tokensCacheKey)
230
+ })
231
+
232
+ return null
233
+ }
234
+
235
+ const CodeBlockBody = memo(
236
+ ({
237
+ tokenized,
238
+ showLineNumbers,
239
+ className,
240
+ }: {
241
+ tokenized: TokenizedCode
242
+ showLineNumbers: boolean
243
+ className?: string
244
+ }) => {
245
+ const preStyle = useMemo(
246
+ () => ({
247
+ backgroundColor: tokenized.bg,
248
+ color: tokenized.fg,
249
+ }),
250
+ [tokenized.bg, tokenized.fg],
251
+ )
252
+
253
+ const keyedLines = useMemo(() => addKeysToTokens(tokenized.tokens), [tokenized.tokens])
254
+
255
+ return (
256
+ <pre
257
+ className={cn(
258
+ 'dark:!bg-[var(--shiki-dark-bg)] dark:!text-[var(--shiki-dark)] m-0 p-4 text-sm',
259
+ className,
260
+ )}
261
+ style={preStyle}
262
+ >
263
+ <code
264
+ className={cn(
265
+ 'font-mono text-sm',
266
+ showLineNumbers && '[counter-increment:line_0] [counter-reset:line]',
267
+ )}
268
+ >
269
+ {keyedLines.map((keyedLine) => (
270
+ <LineSpan key={keyedLine.key} keyedLine={keyedLine} showLineNumbers={showLineNumbers} />
271
+ ))}
272
+ </code>
273
+ </pre>
274
+ )
275
+ },
276
+ (prevProps, nextProps) =>
277
+ prevProps.tokenized === nextProps.tokenized &&
278
+ prevProps.showLineNumbers === nextProps.showLineNumbers &&
279
+ prevProps.className === nextProps.className,
280
+ )
281
+
282
+ CodeBlockBody.displayName = 'CodeBlockBody'
283
+
284
+ export const CodeBlockContainer = ({
285
+ className,
286
+ language,
287
+ style,
288
+ ...props
289
+ }: HTMLAttributes<HTMLDivElement> & { language: string }) => (
290
+ <div
291
+ className={cn(
292
+ 'group relative w-full overflow-hidden rounded-md border bg-page text-foreground',
293
+ className,
294
+ )}
295
+ data-language={language}
296
+ style={{
297
+ containIntrinsicSize: 'auto 200px',
298
+ contentVisibility: 'auto',
299
+ ...style,
300
+ }}
301
+ {...props}
302
+ />
303
+ )
304
+
305
+ export const CodeBlockHeader = ({
306
+ children,
307
+ className,
308
+ ...props
309
+ }: HTMLAttributes<HTMLDivElement>) => (
310
+ <div
311
+ className={cn(
312
+ 'flex items-center justify-between border-b bg-muted/80 px-3 py-2 text-muted-foreground text-xs',
313
+ className,
314
+ )}
315
+ {...props}
316
+ >
317
+ {children}
318
+ </div>
319
+ )
320
+
321
+ export const CodeBlockTitle = ({
322
+ children,
323
+ className,
324
+ ...props
325
+ }: HTMLAttributes<HTMLDivElement>) => (
326
+ <div className={cn('flex items-center gap-2', className)} {...props}>
327
+ {children}
328
+ </div>
329
+ )
330
+
331
+ export const CodeBlockFilename = ({
332
+ children,
333
+ className,
334
+ ...props
335
+ }: HTMLAttributes<HTMLSpanElement>) => (
336
+ <span className={cn('font-mono', className)} {...props}>
337
+ {children}
338
+ </span>
339
+ )
340
+
341
+ export const CodeBlockActions = ({
342
+ children,
343
+ className,
344
+ ...props
345
+ }: HTMLAttributes<HTMLDivElement>) => (
346
+ <div className={cn('-my-1 -mr-1 flex items-center gap-2', className)} {...props}>
347
+ {children}
348
+ </div>
349
+ )
350
+
351
+ export const CodeBlockContent = ({
352
+ code,
353
+ language,
354
+ showLineNumbers = false,
355
+ }: {
356
+ code: string
357
+ language: BundledLanguage
358
+ showLineNumbers?: boolean
359
+ }) => {
360
+ // Memoized raw tokens for immediate display
361
+ const rawTokens = useMemo(() => createRawTokens(code), [code])
362
+
363
+ // Synchronous cache lookup — avoids setState in effect for cached results
364
+ const syncTokens = useMemo(
365
+ () => highlightCode(code, language) ?? rawTokens,
366
+ [code, language, rawTokens],
367
+ )
368
+
369
+ // Async highlighting result (populated after shiki loads)
370
+ const [asyncTokens, setAsyncTokens] = useState<TokenizedCode | null>(null)
371
+ const asyncKeyRef = useRef({ code, language })
372
+
373
+ // Invalidate stale async tokens synchronously during render
374
+ if (asyncKeyRef.current.code !== code || asyncKeyRef.current.language !== language) {
375
+ asyncKeyRef.current = { code, language }
376
+ setAsyncTokens(null)
377
+ }
378
+
379
+ useEffect(() => {
380
+ let cancelled = false
381
+
382
+ highlightCode(code, language, (result) => {
383
+ if (!cancelled) {
384
+ setAsyncTokens(result)
385
+ }
386
+ })
387
+
388
+ return () => {
389
+ cancelled = true
390
+ }
391
+ }, [code, language])
392
+
393
+ const tokenized = asyncTokens ?? syncTokens
394
+
395
+ return (
396
+ <div className="relative overflow-auto">
397
+ <CodeBlockBody showLineNumbers={showLineNumbers} tokenized={tokenized} />
398
+ </div>
399
+ )
400
+ }
401
+
402
+ export const CodeBlock = ({
403
+ code,
404
+ language,
405
+ showLineNumbers = false,
406
+ className,
407
+ children,
408
+ ...props
409
+ }: CodeBlockProps) => {
410
+ const contextValue = useMemo(() => ({ code }), [code])
411
+
412
+ return (
413
+ <CodeBlockContext.Provider value={contextValue}>
414
+ <CodeBlockContainer className={className} language={language} {...props}>
415
+ {children}
416
+ <CodeBlockContent code={code} language={language} showLineNumbers={showLineNumbers} />
417
+ </CodeBlockContainer>
418
+ </CodeBlockContext.Provider>
419
+ )
420
+ }
421
+
422
+ export type CodeBlockCopyButtonProps = ComponentProps<typeof Button> & {
423
+ onCopy?: () => void
424
+ onError?: (error: Error) => void
425
+ timeout?: number
426
+ }
427
+
428
+ export const CodeBlockCopyButton = ({
429
+ onCopy,
430
+ onError,
431
+ timeout = 2000,
432
+ children,
433
+ className,
434
+ ...props
435
+ }: CodeBlockCopyButtonProps) => {
436
+ const [isCopied, setIsCopied] = useState(false)
437
+ const timeoutRef = useRef<number>(0)
438
+ const { code } = useContext(CodeBlockContext)
439
+
440
+ const copyToClipboard = useCallback(async () => {
441
+ if (typeof window === 'undefined' || !navigator?.clipboard?.writeText) {
442
+ onError?.(new Error('Clipboard API not available'))
443
+ return
444
+ }
445
+
446
+ try {
447
+ if (!isCopied) {
448
+ await navigator.clipboard.writeText(code)
449
+ setIsCopied(true)
450
+ onCopy?.()
451
+ timeoutRef.current = window.setTimeout(() => setIsCopied(false), timeout)
452
+ }
453
+ } catch (error) {
454
+ onError?.(error as Error)
455
+ }
456
+ }, [code, onCopy, onError, timeout, isCopied])
457
+
458
+ useEffect(
459
+ () => () => {
460
+ window.clearTimeout(timeoutRef.current)
461
+ },
462
+ [],
463
+ )
464
+
465
+ const Icon = isCopied ? CheckIcon : CopyIcon
466
+
467
+ return (
468
+ <Button
469
+ className={cn('shrink-0', className)}
470
+ onClick={copyToClipboard}
471
+ size="icon"
472
+ variant="ghost"
473
+ {...props}
474
+ >
475
+ {children ?? <Icon size={14} />}
476
+ </Button>
477
+ )
478
+ }
479
+
480
+ export type CodeBlockLanguageSelectorProps = ComponentProps<typeof Select>
481
+
482
+ export const CodeBlockLanguageSelector = (props: CodeBlockLanguageSelectorProps) => (
483
+ <Select {...props} />
484
+ )
485
+
486
+ export type CodeBlockLanguageSelectorTriggerProps = ComponentProps<typeof SelectTrigger>
487
+
488
+ export const CodeBlockLanguageSelectorTrigger = ({
489
+ className,
490
+ ...props
491
+ }: CodeBlockLanguageSelectorTriggerProps) => (
492
+ <SelectTrigger
493
+ className={cn('h-7 border-none bg-transparent px-2 text-xs shadow-none', className)}
494
+ size="sm"
495
+ {...props}
496
+ />
497
+ )
498
+
499
+ export type CodeBlockLanguageSelectorValueProps = ComponentProps<typeof SelectValue>
500
+
501
+ export const CodeBlockLanguageSelectorValue = (props: CodeBlockLanguageSelectorValueProps) => (
502
+ <SelectValue {...props} />
503
+ )
504
+
505
+ export type CodeBlockLanguageSelectorContentProps = ComponentProps<typeof SelectContent>
506
+
507
+ export const CodeBlockLanguageSelectorContent = ({
508
+ align = 'end',
509
+ ...props
510
+ }: CodeBlockLanguageSelectorContentProps) => <SelectContent align={align} {...props} />
511
+
512
+ export type CodeBlockLanguageSelectorItemProps = ComponentProps<typeof SelectItem>
513
+
514
+ export const CodeBlockLanguageSelectorItem = (props: CodeBlockLanguageSelectorItemProps) => (
515
+ <SelectItem {...props} />
516
+ )
@@ -0,0 +1,150 @@
1
+ 'use client'
2
+
3
+ import { Alert, AlertDescription } from '../alert'
4
+ import { Button } from '../button'
5
+ import { cn } from '../../lib/utils'
6
+ import type { ToolUIPart } from 'ai'
7
+ import type { ComponentProps, ReactNode } from 'react'
8
+ import { createContext, useContext, useMemo } from 'react'
9
+
10
+ type ToolUIPartApproval =
11
+ | {
12
+ id: string
13
+ approved?: never
14
+ reason?: never
15
+ }
16
+ | {
17
+ id: string
18
+ approved: boolean
19
+ reason?: string
20
+ }
21
+ | {
22
+ id: string
23
+ approved: true
24
+ reason?: string
25
+ }
26
+ | {
27
+ id: string
28
+ approved: true
29
+ reason?: string
30
+ }
31
+ | {
32
+ id: string
33
+ approved: false
34
+ reason?: string
35
+ }
36
+ | undefined
37
+
38
+ interface ConfirmationContextValue {
39
+ approval: ToolUIPartApproval
40
+ state: ToolUIPart['state']
41
+ }
42
+
43
+ const ConfirmationContext = createContext<ConfirmationContextValue | null>(null)
44
+
45
+ const useConfirmation = () => {
46
+ const context = useContext(ConfirmationContext)
47
+
48
+ if (!context) {
49
+ throw new Error('Confirmation components must be used within Confirmation')
50
+ }
51
+
52
+ return context
53
+ }
54
+
55
+ export type ConfirmationProps = ComponentProps<typeof Alert> & {
56
+ approval?: ToolUIPartApproval
57
+ state: ToolUIPart['state']
58
+ }
59
+
60
+ export const Confirmation = ({ className, approval, state, ...props }: ConfirmationProps) => {
61
+ const contextValue = useMemo(() => ({ approval, state }), [approval, state])
62
+
63
+ if (!approval || state === 'input-streaming' || state === 'input-available') {
64
+ return null
65
+ }
66
+
67
+ return (
68
+ <ConfirmationContext.Provider value={contextValue}>
69
+ <Alert className={cn('flex flex-col gap-2', className)} {...props} />
70
+ </ConfirmationContext.Provider>
71
+ )
72
+ }
73
+
74
+ export type ConfirmationTitleProps = ComponentProps<typeof AlertDescription>
75
+
76
+ export const ConfirmationTitle = ({ className, ...props }: ConfirmationTitleProps) => (
77
+ <AlertDescription className={cn('inline', className)} {...props} />
78
+ )
79
+
80
+ export interface ConfirmationRequestProps {
81
+ children?: ReactNode
82
+ }
83
+
84
+ export const ConfirmationRequest = ({ children }: ConfirmationRequestProps) => {
85
+ const { state } = useConfirmation()
86
+
87
+ // Only show when approval is requested
88
+ if (state !== 'approval-requested') {
89
+ return null
90
+ }
91
+
92
+ return children
93
+ }
94
+
95
+ export interface ConfirmationAcceptedProps {
96
+ children?: ReactNode
97
+ }
98
+
99
+ export const ConfirmationAccepted = ({ children }: ConfirmationAcceptedProps) => {
100
+ const { approval, state } = useConfirmation()
101
+
102
+ // Only show when approved and in response states
103
+ if (
104
+ !approval?.approved ||
105
+ (state !== 'approval-responded' && state !== 'output-denied' && state !== 'output-available')
106
+ ) {
107
+ return null
108
+ }
109
+
110
+ return children
111
+ }
112
+
113
+ export interface ConfirmationRejectedProps {
114
+ children?: ReactNode
115
+ }
116
+
117
+ export const ConfirmationRejected = ({ children }: ConfirmationRejectedProps) => {
118
+ const { approval, state } = useConfirmation()
119
+
120
+ // Only show when rejected and in response states
121
+ if (
122
+ approval?.approved !== false ||
123
+ (state !== 'approval-responded' && state !== 'output-denied' && state !== 'output-available')
124
+ ) {
125
+ return null
126
+ }
127
+
128
+ return children
129
+ }
130
+
131
+ export type ConfirmationActionsProps = ComponentProps<'div'>
132
+
133
+ export const ConfirmationActions = ({ className, ...props }: ConfirmationActionsProps) => {
134
+ const { state } = useConfirmation()
135
+
136
+ // Only show when approval is requested
137
+ if (state !== 'approval-requested') {
138
+ return null
139
+ }
140
+
141
+ return (
142
+ <div className={cn('flex items-center justify-end gap-2 self-end', className)} {...props} />
143
+ )
144
+ }
145
+
146
+ export type ConfirmationActionProps = ComponentProps<typeof Button>
147
+
148
+ export const ConfirmationAction = (props: ConfirmationActionProps) => (
149
+ <Button className="h-8 px-3 text-sm" type="button" {...props} />
150
+ )