@istmx/ui 0.1.9 → 0.1.11

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.
@@ -0,0 +1,466 @@
1
+ 'use client'
2
+
3
+ import { useEffect, useId, useRef, useState, useSyncExternalStore } from 'react'
4
+ import type { CSSProperties, RefObject } from 'react'
5
+ import { createPortal } from 'react-dom'
6
+ import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
7
+ import {
8
+ IconArrowRight,
9
+ IconFile,
10
+ IconHeadphones,
11
+ IconPaperclip,
12
+ IconPhoto,
13
+ IconVideo,
14
+ IconX,
15
+ IconZoomIn,
16
+ } from '@tabler/icons-react'
17
+ import { cn } from './utils'
18
+ import type { AttachmentOption, ChatAttachmentKind } from './types'
19
+
20
+ const subscribeToNothing = () => () => {}
21
+ const getClientSnapshot = () => true
22
+ const getServerSnapshot = () => false
23
+
24
+ export type AttachmentDialogProps = {
25
+ id?: string
26
+ anchorRef: RefObject<HTMLButtonElement | null>
27
+ open: boolean
28
+ title?: string
29
+ description?: string
30
+ options: readonly AttachmentOption[]
31
+ onSelect: (option: AttachmentOption) => void
32
+ onClose: () => void
33
+ accentColor?: string
34
+ }
35
+
36
+ export default function AttachmentDialog({
37
+ id,
38
+ anchorRef,
39
+ open,
40
+ title = 'Add to message',
41
+ description = 'Choose a file type to attach.',
42
+ options,
43
+ onSelect,
44
+ onClose,
45
+ accentColor,
46
+ }: AttachmentDialogProps) {
47
+ const panelRef = useRef<HTMLDivElement>(null)
48
+ const returnFocusRef = useRef<HTMLElement | null>(null)
49
+ const onCloseRef = useRef(onClose)
50
+ const generatedId = useId().replace(/:/g, '')
51
+ const titleId = `${id ?? generatedId}-title`
52
+ const descriptionId = `${id ?? generatedId}-description`
53
+ const mounted = useSyncExternalStore(
54
+ subscribeToNothing,
55
+ getClientSnapshot,
56
+ getServerSnapshot,
57
+ )
58
+ const [position, setPosition] = useState<{
59
+ left: number
60
+ top?: number
61
+ bottom?: number
62
+ } | null>(null)
63
+ const reduceMotion = useReducedMotion()
64
+
65
+ useEffect(() => {
66
+ onCloseRef.current = onClose
67
+ }, [onClose])
68
+
69
+ useEffect(() => {
70
+ if (!open) return
71
+
72
+ returnFocusRef.current = document.activeElement as HTMLElement | null
73
+ const updatePosition = () => {
74
+ const anchor = anchorRef.current
75
+ if (!anchor) return
76
+ const rect = anchor.getBoundingClientRect()
77
+ const width = Math.min(304, window.innerWidth - 24)
78
+ const panelHeight = Math.min(
79
+ panelRef.current?.offsetHeight ?? 288,
80
+ window.innerHeight * 0.5,
81
+ )
82
+ const left = Math.max(
83
+ 12,
84
+ Math.min(rect.left, window.innerWidth - width - 12),
85
+ )
86
+ if (rect.top >= panelHeight + 20) {
87
+ setPosition({ left, bottom: window.innerHeight - rect.top + 8 })
88
+ } else {
89
+ setPosition({
90
+ left,
91
+ top: Math.min(rect.bottom + 8, window.innerHeight - panelHeight - 12),
92
+ })
93
+ }
94
+ }
95
+
96
+ const frame = window.requestAnimationFrame(() => {
97
+ updatePosition()
98
+ panelRef.current
99
+ ?.querySelector<HTMLButtonElement>('button:not(:disabled)')
100
+ ?.focus()
101
+ })
102
+
103
+ window.addEventListener('resize', updatePosition)
104
+ window.addEventListener('scroll', updatePosition, true)
105
+
106
+ function onPointerDown(event: PointerEvent) {
107
+ const target = event.target
108
+ if (
109
+ target instanceof Node &&
110
+ !panelRef.current?.contains(target) &&
111
+ !anchorRef.current?.contains(target)
112
+ ) {
113
+ onCloseRef.current()
114
+ }
115
+ }
116
+
117
+ function onKeyDown(event: KeyboardEvent) {
118
+ if (event.key === 'Escape') {
119
+ event.preventDefault()
120
+ onCloseRef.current()
121
+ return
122
+ }
123
+ if (event.key !== 'Tab') return
124
+
125
+ const focusable = Array.from(
126
+ panelRef.current?.querySelectorAll<HTMLElement>(
127
+ 'button:not(:disabled), [href], input:not(:disabled), [tabindex]:not([tabindex="-1"])',
128
+ ) ?? [],
129
+ )
130
+ if (!focusable.length) return
131
+ const first = focusable[0]
132
+ const last = focusable[focusable.length - 1]
133
+ if (event.shiftKey && document.activeElement === first) {
134
+ event.preventDefault()
135
+ last.focus()
136
+ } else if (!event.shiftKey && document.activeElement === last) {
137
+ event.preventDefault()
138
+ first.focus()
139
+ }
140
+ }
141
+
142
+ document.addEventListener('keydown', onKeyDown)
143
+ document.addEventListener('pointerdown', onPointerDown)
144
+ return () => {
145
+ window.cancelAnimationFrame(frame)
146
+ document.removeEventListener('keydown', onKeyDown)
147
+ document.removeEventListener('pointerdown', onPointerDown)
148
+ window.removeEventListener('resize', updatePosition)
149
+ window.removeEventListener('scroll', updatePosition, true)
150
+ returnFocusRef.current?.focus()
151
+ }
152
+ }, [open, anchorRef])
153
+
154
+ const dialog = (
155
+ <AnimatePresence>
156
+ {open && position ? (
157
+ <motion.div
158
+ key="attachment-dialog-popover"
159
+ initial={{ opacity: 0 }}
160
+ animate={{ opacity: 1 }}
161
+ exit={{ opacity: 0 }}
162
+ transition={{ duration: reduceMotion ? 0.08 : 0.2 }}
163
+ style={{
164
+ left: position.left,
165
+ top: position.top,
166
+ bottom: position.bottom,
167
+ }}
168
+ className="fixed z-[100]"
169
+ >
170
+ <motion.div
171
+ ref={panelRef}
172
+ id={id ?? `${generatedId}-attachment-dialog`}
173
+ role="dialog"
174
+ aria-modal="true"
175
+ aria-labelledby={titleId}
176
+ aria-describedby={descriptionId}
177
+ initial={
178
+ reduceMotion ? { opacity: 0 } : { opacity: 0, x: 28, y: 8 }
179
+ }
180
+ animate={{ opacity: 1, x: 0, y: 0 }}
181
+ exit={reduceMotion ? { opacity: 0 } : { opacity: 0, x: 20 }}
182
+ transition={
183
+ reduceMotion
184
+ ? { duration: 0.08 }
185
+ : { type: 'spring', stiffness: 390, damping: 34, mass: 0.75 }
186
+ }
187
+ style={
188
+ { '--chat-accent': accentColor ?? '#0369a1' } as CSSProperties
189
+ }
190
+ className="text-foreground border-border/70 relative flex max-h-[min(50vh,18rem)] w-[min(19rem,calc(100vw-1.5rem))] flex-col rounded-2xl border shadow-sm"
191
+ >
192
+ <div className="bg-background text-foreground relative z-10 flex max-h-[min(50vh,18rem)] w-full flex-col overflow-hidden rounded-2xl">
193
+ <div className="border-border/60 flex items-start gap-2.5 border-b px-3 py-3 sm:px-4">
194
+ <span className="border-border/70 bg-surface/60 text-muted flex size-8 shrink-0 items-center justify-center rounded-lg border">
195
+ <IconPaperclip size={17} stroke={1.7} aria-hidden="true" />
196
+ </span>
197
+ <div className="min-w-0 flex-1">
198
+ <h2
199
+ id={titleId}
200
+ className="font-display text-[13px] font-semibold tracking-tight"
201
+ >
202
+ {title}
203
+ </h2>
204
+ <p
205
+ id={descriptionId}
206
+ className="text-muted mt-0.5 text-[11px] leading-4"
207
+ >
208
+ {description}
209
+ </p>
210
+ </div>
211
+ <button
212
+ type="button"
213
+ onClick={onClose}
214
+ aria-label="Close attachment options"
215
+ className="text-muted hover:text-foreground focus-visible:outline-foreground flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg transition-colors focus-visible:outline-2 focus-visible:outline-offset-2"
216
+ >
217
+ <IconX size={16} stroke={1.7} aria-hidden="true" />
218
+ </button>
219
+ </div>
220
+
221
+ <div className="min-h-0 [scrollbar-width:none] overflow-y-auto overscroll-contain p-2 [&::-webkit-scrollbar]:hidden">
222
+ {options.map((option) => (
223
+ <button
224
+ key={option.id}
225
+ type="button"
226
+ disabled={option.disabled}
227
+ onClick={() => onSelect(option)}
228
+ className="group focus-visible:outline-foreground hover:bg-surface/70 focus-visible:bg-surface/70 flex w-full cursor-pointer items-center gap-2.5 rounded-lg px-2 py-2 text-left transition-colors focus-visible:outline-2 focus-visible:outline-offset-[-2px] disabled:cursor-not-allowed disabled:opacity-45 sm:px-2.5"
229
+ >
230
+ <span className="border-border/70 bg-surface/45 text-muted flex size-8 shrink-0 items-center justify-center rounded-lg border transition-colors group-hover:border-[var(--chat-accent,var(--foreground))]/40 group-hover:text-[var(--chat-accent,var(--foreground))]">
231
+ {option.icon ?? (
232
+ <IconPaperclip
233
+ size={17}
234
+ stroke={1.7}
235
+ aria-hidden="true"
236
+ />
237
+ )}
238
+ </span>
239
+ <span className="min-w-0 flex-1">
240
+ <span className="font-display block text-xs font-medium">
241
+ {option.label}
242
+ </span>
243
+ <span className="text-muted mt-0.5 block text-[10px] leading-3.5">
244
+ {option.description ?? option.accept}
245
+ </span>
246
+ </span>
247
+ <IconArrowRight
248
+ size={15}
249
+ stroke={1.6}
250
+ aria-hidden="true"
251
+ className="text-muted/45 shrink-0 transition-transform group-hover:translate-x-0.5 group-hover:text-[var(--chat-accent,var(--foreground))]"
252
+ />
253
+ </button>
254
+ ))}
255
+ </div>
256
+ <div className="border-border/50 text-muted border-t px-3 py-2 font-mono text-[9px] tracking-[0.12em] uppercase sm:px-4">
257
+ {options.length} attachment{' '}
258
+ {options.length === 1 ? 'option' : 'options'}
259
+ </div>
260
+ </div>
261
+ </motion.div>
262
+ </motion.div>
263
+ ) : null}
264
+ </AnimatePresence>
265
+ )
266
+
267
+ return mounted ? createPortal(dialog, document.body) : null
268
+ }
269
+
270
+ type AttachmentPreviewProps = {
271
+ file: File
272
+ name: string
273
+ kind: ChatAttachmentKind
274
+ src?: string
275
+ thumbnailClassName?: string
276
+ }
277
+
278
+ function PreviewIcon({ kind }: { kind: ChatAttachmentKind }) {
279
+ const Icon =
280
+ kind === 'image'
281
+ ? IconPhoto
282
+ : kind === 'video'
283
+ ? IconVideo
284
+ : kind === 'audio'
285
+ ? IconHeadphones
286
+ : IconFile
287
+ return <Icon size={18} stroke={1.7} aria-hidden="true" />
288
+ }
289
+
290
+ export function AttachmentPreview({
291
+ file,
292
+ name,
293
+ kind,
294
+ src,
295
+ thumbnailClassName,
296
+ }: AttachmentPreviewProps) {
297
+ const [open, setOpen] = useState(false)
298
+ const [previewUrl, setPreviewUrl] = useState(src ?? '')
299
+ const fileUrlRef = useRef('')
300
+ const thumbnailRef = useRef<HTMLImageElement>(null)
301
+ const closeRef = useRef<HTMLButtonElement>(null)
302
+ const triggerRef = useRef<HTMLButtonElement>(null)
303
+ const reduceMotion = useReducedMotion()
304
+
305
+ useEffect(() => {
306
+ if (src) return
307
+ const url = URL.createObjectURL(file)
308
+ fileUrlRef.current = url
309
+ if (thumbnailRef.current) thumbnailRef.current.src = url
310
+ return () => {
311
+ fileUrlRef.current = ''
312
+ URL.revokeObjectURL(url)
313
+ }
314
+ }, [file, src])
315
+
316
+ useEffect(() => {
317
+ if (!open) return
318
+ closeRef.current?.focus()
319
+ const onKeyDown = (event: KeyboardEvent) => {
320
+ if (event.key === 'Escape') setOpen(false)
321
+ }
322
+ const trigger = triggerRef.current
323
+ document.addEventListener('keydown', onKeyDown)
324
+ return () => {
325
+ document.removeEventListener('keydown', onKeyDown)
326
+ trigger?.focus()
327
+ }
328
+ }, [open])
329
+
330
+ const dialog = (
331
+ <AnimatePresence>
332
+ {open ? (
333
+ <motion.div
334
+ className="fixed inset-0 z-[500] flex items-center justify-center p-3 sm:p-8"
335
+ initial={{ opacity: 0 }}
336
+ animate={{ opacity: 1 }}
337
+ exit={{ opacity: 0 }}
338
+ transition={{ duration: reduceMotion ? 0.08 : 0.18 }}
339
+ role="presentation"
340
+ onMouseDown={(event) => {
341
+ if (event.target === event.currentTarget) setOpen(false)
342
+ }}
343
+ >
344
+ <div
345
+ className="absolute inset-0 bg-black/80 backdrop-blur-sm"
346
+ aria-hidden="true"
347
+ />
348
+ <motion.section
349
+ role="dialog"
350
+ aria-modal="true"
351
+ aria-label={`Preview: ${name}`}
352
+ className="border-border/70 bg-background relative z-10 flex max-h-[92dvh] w-full max-w-5xl flex-col overflow-hidden rounded-2xl border shadow-2xl"
353
+ initial={reduceMotion ? { scale: 1 } : { scale: 0.96, y: 12 }}
354
+ animate={{ scale: 1, y: 0 }}
355
+ exit={reduceMotion ? { scale: 1 } : { scale: 0.98, y: 8 }}
356
+ transition={
357
+ reduceMotion
358
+ ? { duration: 0.08 }
359
+ : { type: 'spring', stiffness: 360, damping: 30 }
360
+ }
361
+ >
362
+ <div className="border-border/60 flex min-h-12 items-center gap-3 border-b px-3 py-2.5 sm:px-4">
363
+ <span className="text-muted bg-surface/70 flex size-8 shrink-0 items-center justify-center rounded-lg">
364
+ <PreviewIcon kind={kind} />
365
+ </span>
366
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">
367
+ {name}
368
+ </span>
369
+ <button
370
+ ref={closeRef}
371
+ type="button"
372
+ onClick={() => setOpen(false)}
373
+ aria-label="Close file preview"
374
+ className="text-muted hover:bg-surface hover:text-foreground flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg transition-colors"
375
+ >
376
+ <IconX size={17} stroke={1.7} aria-hidden="true" />
377
+ </button>
378
+ </div>
379
+ <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto bg-black/20 p-3 sm:p-6">
380
+ {kind === 'image' && previewUrl ? (
381
+ // eslint-disable-next-line @next/next/no-img-element
382
+ <img
383
+ src={previewUrl}
384
+ alt={name}
385
+ className="max-h-[calc(92dvh-8rem)] max-w-full rounded-lg object-contain"
386
+ />
387
+ ) : kind === 'video' && previewUrl ? (
388
+ <video
389
+ src={previewUrl}
390
+ controls
391
+ playsInline
392
+ className="max-h-[calc(92dvh-8rem)] max-w-full rounded-lg"
393
+ />
394
+ ) : kind === 'audio' && previewUrl ? (
395
+ <audio src={previewUrl} controls className="w-full max-w-xl" />
396
+ ) : file.type === 'application/pdf' && previewUrl ? (
397
+ <iframe
398
+ title={`Preview: ${name}`}
399
+ src={previewUrl}
400
+ className="h-[min(72vh,48rem)] w-full rounded-lg border-0"
401
+ />
402
+ ) : (
403
+ <div className="text-muted flex flex-col items-center gap-3 py-12 text-center">
404
+ <span className="bg-surface/70 flex size-14 items-center justify-center rounded-2xl">
405
+ <PreviewIcon kind={kind} />
406
+ </span>
407
+ <p className="max-w-sm text-sm">
408
+ A preview isn’t available for this file type.
409
+ </p>
410
+ <a
411
+ href={previewUrl}
412
+ download={name}
413
+ className="text-foreground bg-surface hover:bg-surface/80 rounded-lg px-3 py-2 text-xs font-medium"
414
+ >
415
+ Download file
416
+ </a>
417
+ </div>
418
+ )}
419
+ </div>
420
+ </motion.section>
421
+ </motion.div>
422
+ ) : null}
423
+ </AnimatePresence>
424
+ )
425
+
426
+ return (
427
+ <>
428
+ <button
429
+ ref={triggerRef}
430
+ type="button"
431
+ onClick={() => {
432
+ setPreviewUrl(src ?? fileUrlRef.current)
433
+ setOpen(true)
434
+ }}
435
+ aria-label={`Preview ${name}`}
436
+ title={`Preview ${name}`}
437
+ className={cn(
438
+ 'group/preview border-border/60 bg-background/70 text-muted relative flex shrink-0 cursor-zoom-in items-center justify-center overflow-hidden rounded-lg border',
439
+ thumbnailClassName,
440
+ )}
441
+ >
442
+ {kind === 'image' && previewUrl ? (
443
+ // eslint-disable-next-line @next/next/no-img-element
444
+ <img
445
+ ref={thumbnailRef}
446
+ src={previewUrl}
447
+ alt=""
448
+ aria-hidden="true"
449
+ className="size-full object-cover"
450
+ />
451
+ ) : (
452
+ <PreviewIcon kind={kind} />
453
+ )}
454
+ <span
455
+ aria-hidden="true"
456
+ className="absolute inset-0 flex items-center justify-center bg-black/45 text-white opacity-0 transition-opacity duration-150 group-hover/preview:opacity-100 group-focus-visible/preview:opacity-100"
457
+ >
458
+ <IconZoomIn size={16} stroke={1.8} />
459
+ </span>
460
+ </button>
461
+ {typeof document !== 'undefined'
462
+ ? createPortal(dialog, document.body)
463
+ : null}
464
+ </>
465
+ )
466
+ }
@@ -0,0 +1,50 @@
1
+ 'use client'
2
+
3
+ import { useMemo, useState } from 'react'
4
+ import { IconCheck, IconCopy, IconFileCode } from '@tabler/icons-react'
5
+ import { tokenizeCode, TokenSpan } from './code-highlighter'
6
+ import { cn } from './utils'
7
+
8
+ export default function ChatCodeBlock({
9
+ children,
10
+ label = 'code',
11
+ className,
12
+ }: {
13
+ children: string
14
+ label?: string
15
+ className?: string
16
+ }) {
17
+ const [copied, setCopied] = useState(false)
18
+ const lines = useMemo(() => tokenizeCode(children), [children])
19
+
20
+ async function copyCode() {
21
+ try {
22
+ await navigator.clipboard.writeText(children)
23
+ setCopied(true)
24
+ window.setTimeout(() => setCopied(false), 1600)
25
+ } catch {
26
+ setCopied(false)
27
+ }
28
+ }
29
+
30
+ return (
31
+ <div className={cn('border-border/70 my-3 overflow-hidden rounded-xl border bg-[#09090b] text-left', className)}>
32
+ <div className="flex items-center justify-between border-b border-neutral-800/80 bg-[#0d0d10]/95 px-3.5 py-2">
33
+ <span className="flex items-center gap-2 font-mono text-[11px] text-neutral-400">
34
+ <IconFileCode size={14} className="text-neutral-500" aria-hidden="true" />
35
+ {label}
36
+ </span>
37
+ <button type="button" onClick={copyCode} aria-label={copied ? 'Code copied' : 'Copy code'} className="flex size-7 cursor-pointer items-center justify-center rounded text-neutral-500 transition-colors hover:text-neutral-200">
38
+ {copied ? <IconCheck size={14} className="text-emerald-400" aria-hidden="true" /> : <IconCopy size={14} aria-hidden="true" />}
39
+ </button>
40
+ </div>
41
+ <pre className="max-w-full overflow-x-auto p-4 font-mono text-[13px] leading-[1.7] antialiased select-text">
42
+ <code>{lines.map((line, lineIndex) => (
43
+ <span key={`line-${lineIndex}`} className="block min-h-[1.7em] whitespace-pre">
44
+ {line.length ? line.map((token, tokenIndex) => <TokenSpan key={`${lineIndex}-${tokenIndex}`} token={token} />) : <>&nbsp;</>}
45
+ </span>
46
+ ))}</code>
47
+ </pre>
48
+ </div>
49
+ )
50
+ }
@@ -0,0 +1,51 @@
1
+ 'use client'
2
+
3
+ import AiChatInput from './ai-chat-input'
4
+ import type { AiChatInputAction, AiChatInputAttachment } from './ai-chat-input'
5
+
6
+ export type ChatComposerProps = {
7
+ actions: readonly AiChatInputAction[]
8
+ disabled?: boolean
9
+ busy?: boolean
10
+ maxAttachments?: number
11
+ maxFileSizeBytes?: number
12
+ showVoice?: boolean
13
+ placeholder?: string
14
+ accentColor?: string
15
+ onSubmit: (message: string, attachments: AiChatInputAttachment[]) => void
16
+ onStop?: () => void
17
+ onListeningChange?: (listening: boolean) => void
18
+ onAttachmentError?: (message: string) => void
19
+ }
20
+
21
+ export default function ChatComposer({
22
+ actions,
23
+ disabled,
24
+ busy,
25
+ maxAttachments,
26
+ maxFileSizeBytes,
27
+ showVoice,
28
+ placeholder,
29
+ accentColor,
30
+ onSubmit,
31
+ onStop,
32
+ onListeningChange,
33
+ onAttachmentError,
34
+ }: ChatComposerProps) {
35
+ return (
36
+ <AiChatInput
37
+ actions={actions}
38
+ disabled={disabled}
39
+ busy={busy}
40
+ maxAttachments={maxAttachments}
41
+ maxFileSizeBytes={maxFileSizeBytes}
42
+ showVoice={showVoice}
43
+ placeholder={placeholder}
44
+ accentColor={accentColor}
45
+ onSubmit={onSubmit}
46
+ onStop={onStop}
47
+ onListeningChange={onListeningChange}
48
+ onAttachmentError={onAttachmentError}
49
+ />
50
+ )
51
+ }
@@ -0,0 +1,18 @@
1
+ export default function ChatLogo({ className = '' }: { className?: string }) {
2
+ return (
3
+ <svg
4
+ xmlns="http://www.w3.org/2000/svg"
5
+ viewBox="0 0 512 512"
6
+ fill="none"
7
+ aria-label="istmX"
8
+ className={className}
9
+ >
10
+ <g fill="currentColor">
11
+ <path d="M118 132L238 132L304 211L247 269L191 205L151 247V334H118V132Z" />
12
+ <path d="M129 401L157 350L362 145L408 100L382 164L334 219L276 277L407 407H302L225 329L129 401Z" />
13
+ <path d="M273 151H320L296 198L273 151Z" />
14
+ <path d="M224 365H271L247 319L224 365Z" />
15
+ </g>
16
+ </svg>
17
+ )
18
+ }