@istmx/ui 0.1.10 → 0.1.12

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.
@@ -1,690 +0,0 @@
1
- 'use client'
2
-
3
- import { useEffect, useId, useRef, useState } from 'react'
4
- import type { ChangeEvent, CSSProperties, KeyboardEvent } from 'react'
5
- import {
6
- AnimatePresence,
7
- motion,
8
- useAnimationControls,
9
- useReducedMotion,
10
- } from 'motion/react'
11
- import { IconPlus, IconX } from '@tabler/icons-react'
12
- import { cn } from './utils'
13
- import AttachmentDialog, { AttachmentPreview } from './attachment'
14
- import SendButton from './send-button'
15
- import VoiceButton from './voice-button'
16
- import type { AttachmentOption, ChatAttachment } from './types'
17
-
18
- type AnimatedAccentBorderProps = {
19
- color: string
20
- duration?: number
21
- intensity?: number
22
- }
23
-
24
- function AnimatedAccentBorder({
25
- color,
26
- duration = 5,
27
- intensity = 1,
28
- }: AnimatedAccentBorderProps) {
29
- const borderRef = useRef<SVGSVGElement>(null)
30
- const glowFilterId = `${useId().replace(/:/g, '')}-organic-glow`
31
- const [size, setSize] = useState({ width: 0, height: 0 })
32
- const reduceMotion = useReducedMotion()
33
-
34
- useEffect(() => {
35
- const border = borderRef.current
36
- if (!border) return
37
-
38
- const observer = new ResizeObserver(() => {
39
- const { width, height } = border.getBoundingClientRect()
40
- setSize((current) =>
41
- Math.abs(current.width - width) < 0.5 &&
42
- Math.abs(current.height - height) < 0.5
43
- ? current
44
- : { width, height },
45
- )
46
- })
47
-
48
- observer.observe(border)
49
- return () => observer.disconnect()
50
- }, [])
51
-
52
- const measuredWidth = Math.max(1, size.width)
53
- const measuredHeight = Math.max(1, size.height)
54
- const width = Math.max(0, measuredWidth - 1)
55
- const height = Math.max(0, measuredHeight - 1)
56
- const radius = Math.min(15.5, width / 2, height / 2)
57
- const pathLength = Math.max(
58
- 0,
59
- 2 * (width + height - 4 * radius) + 2 * Math.PI * radius,
60
- )
61
- const dashLength = pathLength * 0.22
62
- const highlightColor = `color-mix(in srgb, ${color} 62%, white)`
63
- const animate = reduceMotion ? undefined : { strokeDashoffset: -pathLength }
64
- const transition = {
65
- duration: Math.max(1, duration),
66
- ease: 'linear' as const,
67
- repeat: Infinity,
68
- }
69
- const shape = {
70
- x: 0.5,
71
- y: 0.5,
72
- width,
73
- height,
74
- rx: radius,
75
- fill: 'none',
76
- }
77
- const animatedShape = {
78
- ...shape,
79
- strokeDasharray: `${dashLength} ${pathLength - dashLength}`,
80
- strokeLinecap: 'round' as const,
81
- initial: { strokeDashoffset: 0 },
82
- animate,
83
- transition,
84
- }
85
-
86
- return (
87
- <svg
88
- ref={borderRef}
89
- aria-hidden="true"
90
- viewBox={`0 0 ${measuredWidth} ${measuredHeight}`}
91
- className="pointer-events-none absolute -top-px -left-px z-20 overflow-visible"
92
- style={{
93
- width: 'calc(100% + 2px)',
94
- height: 'calc(100% + 2px)',
95
- opacity: Math.min(1, Math.max(0, intensity)),
96
- }}
97
- >
98
- <defs>
99
- <filter
100
- id={glowFilterId}
101
- x="-35%"
102
- y="-60%"
103
- width="170%"
104
- height="220%"
105
- colorInterpolationFilters="sRGB"
106
- >
107
- <feTurbulence
108
- type="fractalNoise"
109
- baseFrequency="0.01 0.08"
110
- numOctaves="2"
111
- seed="7"
112
- result="edgeNoise"
113
- />
114
- <feDisplacementMap
115
- in="SourceGraphic"
116
- in2="edgeNoise"
117
- scale="18"
118
- xChannelSelector="R"
119
- yChannelSelector="G"
120
- result="unevenEdge"
121
- />
122
- <feGaussianBlur in="unevenEdge" stdDeviation="10" />
123
- </filter>
124
- </defs>
125
- <rect {...shape} stroke={color} strokeWidth="1.5" opacity="0.38" />
126
- <rect
127
- {...shape}
128
- stroke={color}
129
- strokeWidth="8"
130
- filter={`url(#${glowFilterId})`}
131
- opacity="0.55"
132
- />
133
- <motion.rect
134
- {...animatedShape}
135
- stroke={color}
136
- strokeWidth="14"
137
- filter={`url(#${glowFilterId})`}
138
- opacity="0.7"
139
- />
140
- <motion.rect
141
- {...animatedShape}
142
- stroke={color}
143
- strokeWidth="8"
144
- filter={`url(#${glowFilterId})`}
145
- opacity="0.9"
146
- />
147
- <motion.rect
148
- {...animatedShape}
149
- stroke={highlightColor}
150
- strokeWidth="3.5"
151
- />
152
- </svg>
153
- )
154
- }
155
-
156
- export type AiChatInputAction = AttachmentOption & {
157
- hint?: string
158
- }
159
- export type AiChatInputAttachment = ChatAttachment
160
-
161
- export type AiChatInputProps = {
162
- actions?: readonly AiChatInputAction[]
163
- placeholder?: string
164
-
165
- label?: string
166
- menuLabel?: string
167
- submitLabel?: string
168
- startVoiceLabel?: string
169
- stopVoiceLabel?: string
170
- defaultValue?: string
171
- onValueChange?: (value: string) => void
172
- onAttachmentsChange?: (attachments: AiChatInputAttachment[]) => void
173
- onSubmit?: (value: string, attachments: AiChatInputAttachment[]) => void
174
- onStop?: () => void
175
- onListeningChange?: (listening: boolean) => void
176
- maxLength?: number
177
- maxRows?: number
178
- maxAttachments?: number
179
- maxFileSizeBytes?: number
180
- showVoice?: boolean
181
- busy?: boolean
182
- disabled?: boolean
183
- className?: string
184
- textareaClassName?: string
185
-
186
- glow?: false | AiChatInputGlow
187
- onAttachmentError?: (message: string) => void
188
- }
189
-
190
- export type AiChatInputGlow = {
191
- color?: string
192
-
193
- duration?: number
194
-
195
- intensity?: number
196
- }
197
-
198
- const LINE_HEIGHT = 24
199
- const PADDING_Y = 16
200
-
201
- const MEDIA_EXTENSION: Record<string, AiChatInputAttachment['kind']> = {
202
- png: 'image',
203
- jpg: 'image',
204
- jpeg: 'image',
205
- gif: 'image',
206
- webp: 'image',
207
- avif: 'image',
208
- svg: 'image',
209
- bmp: 'image',
210
- mp4: 'video',
211
- webm: 'video',
212
- mov: 'video',
213
- mkv: 'video',
214
- mp3: 'audio',
215
- wav: 'audio',
216
- ogg: 'audio',
217
- m4a: 'audio',
218
- flac: 'audio',
219
- }
220
-
221
- function attachmentKind(type: string, name: string) {
222
- if (type.startsWith('image/')) return 'image' as const
223
- if (type.startsWith('video/')) return 'video' as const
224
- if (type.startsWith('audio/')) return 'audio' as const
225
-
226
- const extension = name.split('.').pop()?.toLowerCase() ?? ''
227
- return MEDIA_EXTENSION[extension] ?? ('file' as const)
228
- }
229
-
230
- function formatBytes(size?: number) {
231
- if (typeof size !== 'number' || Number.isNaN(size)) return ''
232
- if (size < 1024) return `${size} B`
233
- if (size < 1024 * 1024) return `${Math.round(size / 1024)} KB`
234
- return `${(size / (1024 * 1024)).toFixed(1)} MB`
235
- }
236
-
237
- function Equalizer({ reduceMotion }: { reduceMotion: boolean | null }) {
238
- return (
239
- <span
240
- aria-hidden="true"
241
- className="flex h-3 shrink-0 items-center gap-[2px]"
242
- >
243
- {[0, 1, 2, 3, 4].map((index) => (
244
- <motion.span
245
- key={index}
246
- className="bg-foreground block h-3 w-[2px] rounded-full"
247
- style={{ transformOrigin: 'center' }}
248
- animate={
249
- reduceMotion
250
- ? { scaleY: 0.55 }
251
- : { scaleY: [0.22, 1, 0.4, 0.85, 0.22] }
252
- }
253
- transition={
254
- reduceMotion
255
- ? undefined
256
- : {
257
- duration: 1 + index * 0.14,
258
- repeat: Infinity,
259
- ease: 'easeInOut',
260
- delay: index * 0.07,
261
- }
262
- }
263
- />
264
- ))}
265
- </span>
266
- )
267
- }
268
-
269
- export function AiChatInput({
270
- actions,
271
- placeholder = 'Ask anything…',
272
- label = 'Message',
273
- menuLabel = 'Add to message',
274
- submitLabel = 'Send message',
275
- startVoiceLabel = 'Start voice input',
276
- stopVoiceLabel = 'Stop voice input',
277
- defaultValue = '',
278
- onValueChange,
279
- onAttachmentsChange,
280
- onSubmit,
281
- onStop,
282
- onListeningChange,
283
- maxLength = 4000,
284
- maxRows = 8,
285
- maxAttachments = 10,
286
- maxFileSizeBytes,
287
- showVoice = true,
288
- busy = false,
289
- disabled = false,
290
- className,
291
- textareaClassName,
292
- glow = {},
293
- onAttachmentError,
294
- }: AiChatInputProps) {
295
- const rootId = useId().replace(/:/g, '')
296
- const attachmentCounter = useRef(0)
297
- const attachmentsRef = useRef<AiChatInputAttachment[]>([])
298
-
299
- const [value, setValue] = useState(defaultValue)
300
- const [attachments, setAttachments] = useState<AiChatInputAttachment[]>([])
301
- const [menuOpen, setMenuOpen] = useState(false)
302
- const [listening, setListening] = useState(false)
303
- const [sent, setSent] = useState(false)
304
-
305
- const fieldRef = useRef<HTMLTextAreaElement>(null)
306
- const menuTriggerRef = useRef<HTMLButtonElement>(null)
307
- const fileInputRef = useRef<HTMLInputElement>(null)
308
- const sentTimer = useRef<number | null>(null)
309
- const shakeControls = useAnimationControls()
310
- const reduceMotion = useReducedMotion()
311
-
312
- const hasActions = Boolean(actions && actions.length > 0)
313
- const canSend =
314
- !disabled && !busy && (value.trim().length > 0 || attachments.length > 0)
315
- const sendState = busy ? 'busy' : canSend ? 'ready' : sent ? 'sent' : 'idle'
316
- const glowOptions = typeof glow === 'object' ? glow : {}
317
- const glowColor = glowOptions.color ?? '#0369a1'
318
- function updateValue(next: string) {
319
- const bounded = next.slice(0, maxLength)
320
- setValue(bounded)
321
- onValueChange?.(bounded)
322
- }
323
-
324
- function commitAttachments(next: AiChatInputAttachment[]) {
325
- setAttachments(next)
326
- onAttachmentsChange?.(next)
327
- }
328
- useEffect(() => {
329
- const field = fieldRef.current
330
- if (!field) return
331
-
332
- field.style.height = 'auto'
333
- const ceiling = maxRows * LINE_HEIGHT + PADDING_Y
334
- const next = Math.min(field.scrollHeight, ceiling)
335
- field.style.height = `${next}px`
336
- field.style.overflowY = field.scrollHeight > ceiling ? 'auto' : 'hidden'
337
- }, [value, maxRows])
338
- useEffect(() => {
339
- attachmentsRef.current = attachments
340
- }, [attachments])
341
- useEffect(() => {
342
- return () => {
343
- if (sentTimer.current) window.clearTimeout(sentTimer.current)
344
- attachmentsRef.current.forEach((item) => {
345
- if (item.url?.startsWith('blob:')) URL.revokeObjectURL(item.url)
346
- })
347
- }
348
- }, [])
349
-
350
- function closeMenu(refocusTrigger = false) {
351
- setMenuOpen(false)
352
- if (refocusTrigger)
353
- requestAnimationFrame(() => menuTriggerRef.current?.focus())
354
- }
355
-
356
- function runAction(action: AiChatInputAction) {
357
- if (action.disabled || disabled) return
358
-
359
- setMenuOpen(false)
360
-
361
- if (action.accept) {
362
- const input = fileInputRef.current
363
- if (input) {
364
- input.accept = action.accept
365
- input.multiple = Boolean(action.multiple)
366
- if (action.capture) input.setAttribute('capture', action.capture)
367
- else input.removeAttribute('capture')
368
- input.value = ''
369
- input.click()
370
- }
371
- } else {
372
- requestAnimationFrame(() => menuTriggerRef.current?.focus())
373
- }
374
-
375
- action.onSelect?.()
376
- }
377
-
378
- function handleFiles(event: ChangeEvent<HTMLInputElement>) {
379
- const files = Array.from(event.target.files ?? [])
380
- event.target.value = ''
381
- if (!files.length) return
382
-
383
- const capacity = Math.max(0, maxAttachments - attachments.length)
384
- const accepted = files.filter((file) => {
385
- if (maxFileSizeBytes && file.size > maxFileSizeBytes) {
386
- onAttachmentError?.(
387
- `${file.name} is larger than the allowed file size.`,
388
- )
389
- return false
390
- }
391
- return true
392
- })
393
- if (accepted.length > capacity) {
394
- onAttachmentError?.(`You can attach up to ${maxAttachments} files.`)
395
- }
396
-
397
- const next: AiChatInputAttachment[] = accepted
398
- .slice(0, capacity)
399
- .map((file) => ({
400
- id: `${rootId}-attachment-${attachmentCounter.current++}`,
401
- name: file.name,
402
- kind: attachmentKind(file.type, file.name),
403
- size: file.size,
404
- file,
405
- url:
406
- file.type.startsWith('image/') || file.type.startsWith('video/')
407
- ? URL.createObjectURL(file)
408
- : undefined,
409
- }))
410
-
411
- commitAttachments([...attachments, ...next])
412
- }
413
-
414
- function removeAttachment(id: string) {
415
- const target = attachments.find((item) => item.id === id)
416
- if (target?.url?.startsWith('blob:')) URL.revokeObjectURL(target.url)
417
- commitAttachments(attachments.filter((item) => item.id !== id))
418
- }
419
-
420
- function toggleListening() {
421
- if (disabled) return
422
- const next = !listening
423
- setListening(next)
424
- onListeningChange?.(next)
425
- }
426
-
427
- function submit() {
428
- if (disabled || busy) return
429
-
430
- if (!canSend) {
431
- if (!reduceMotion) {
432
- void shakeControls.start({
433
- x: [0, -5, 5, -4, 4, -2, 0],
434
- transition: { duration: 0.36, ease: 'easeOut' },
435
- })
436
- }
437
- fieldRef.current?.focus()
438
- return
439
- }
440
-
441
- onSubmit?.(value.trim(), attachments)
442
- attachments.forEach((item) => {
443
- if (item.url?.startsWith('blob:')) URL.revokeObjectURL(item.url)
444
- })
445
- updateValue('')
446
- commitAttachments([])
447
- setSent(true)
448
- fieldRef.current?.focus()
449
-
450
- if (sentTimer.current) window.clearTimeout(sentTimer.current)
451
- sentTimer.current = window.setTimeout(() => setSent(false), 1200)
452
- }
453
-
454
- function handleFieldKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
455
- if (event.key === 'Escape' && busy) {
456
- event.preventDefault()
457
- onStop?.()
458
- return
459
- }
460
- if (
461
- event.key === 'Enter' &&
462
- !event.shiftKey &&
463
- !event.nativeEvent.isComposing
464
- ) {
465
- event.preventDefault()
466
- submit()
467
- }
468
- }
469
-
470
- return (
471
- <div
472
- style={{ '--chat-accent': glowColor } as CSSProperties}
473
- className={cn(
474
- 'bg-background/85 relative rounded-2xl border border-transparent shadow-[0_20px_54px_-36px_rgba(0,0,0,0.75)] backdrop-blur-xl transition-[border-color] duration-300 focus-within:border-transparent',
475
- disabled && 'opacity-60',
476
- className,
477
- )}
478
- >
479
- {glow !== false ? (
480
- <AnimatedAccentBorder
481
- color={glowColor}
482
- duration={glowOptions.duration}
483
- intensity={glowOptions.intensity}
484
- />
485
- ) : null}
486
-
487
- <AnimatePresence initial={false}>
488
- {attachments.length > 0 ? (
489
- <motion.div
490
- key="attachments"
491
- initial={reduceMotion ? { opacity: 0 } : { opacity: 0, height: 0 }}
492
- animate={
493
- reduceMotion ? { opacity: 1 } : { opacity: 1, height: 'auto' }
494
- }
495
- exit={reduceMotion ? { opacity: 0 } : { opacity: 0, height: 0 }}
496
- transition={
497
- reduceMotion
498
- ? { duration: 0.1 }
499
- : { type: 'spring', stiffness: 340, damping: 34, mass: 0.7 }
500
- }
501
- className="overflow-hidden"
502
- >
503
- <div className="flex flex-wrap gap-2 px-2.5 pt-2.5 sm:px-3 sm:pt-3">
504
- <AnimatePresence initial={false}>
505
- {attachments.map((item) => {
506
- return (
507
- <motion.div
508
- key={item.id}
509
- layout={!reduceMotion}
510
- initial={
511
- reduceMotion
512
- ? { opacity: 0 }
513
- : { opacity: 0, scale: 0.9, y: 8 }
514
- }
515
- animate={{ opacity: 1, scale: 1, y: 0 }}
516
- exit={
517
- reduceMotion
518
- ? { opacity: 0 }
519
- : { opacity: 0, scale: 0.9, y: -6 }
520
- }
521
- transition={
522
- reduceMotion
523
- ? { duration: 0.1 }
524
- : {
525
- type: 'spring',
526
- stiffness: 440,
527
- damping: 30,
528
- mass: 0.6,
529
- }
530
- }
531
- className="border-border/70 bg-surface/40 group/chip flex max-w-full min-w-0 items-center gap-2 rounded-lg border p-1 pr-1.5"
532
- >
533
- <AttachmentPreview
534
- file={item.file}
535
- src={item.url}
536
- name={item.name}
537
- kind={item.kind}
538
- thumbnailClassName="size-7 rounded-md"
539
- />
540
-
541
- <span className="text-foreground max-w-[9rem] truncate text-xs font-medium sm:max-w-[12rem]">
542
- {item.name}
543
- </span>
544
- {item.size !== undefined ? (
545
- <span className="text-muted/70 hidden font-mono text-[9px] tracking-wide uppercase sm:block">
546
- {formatBytes(item.size)}
547
- </span>
548
- ) : null}
549
-
550
- <button
551
- type="button"
552
- aria-label={`Remove ${item.name}`}
553
- onClick={() => removeAttachment(item.id)}
554
- className="text-muted hover:text-foreground focus-visible:outline-foreground inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md transition-colors focus-visible:outline-2 focus-visible:outline-offset-2"
555
- >
556
- <IconX
557
- size={13}
558
- stroke={1.8}
559
- aria-hidden="true"
560
- className="transition-transform duration-300 group-hover/chip:rotate-90"
561
- />
562
- </button>
563
- </motion.div>
564
- )
565
- })}
566
- </AnimatePresence>
567
- </div>
568
- </motion.div>
569
- ) : null}
570
- </AnimatePresence>
571
-
572
- <div className="flex items-end gap-2 p-2.5 sm:gap-3 sm:p-3">
573
- {hasActions ? (
574
- <motion.button
575
- type="button"
576
- ref={menuTriggerRef}
577
- data-chat-input-trigger=""
578
- onClick={() => setMenuOpen((open) => !open)}
579
- aria-label={menuOpen ? 'Close attachment options' : menuLabel}
580
- aria-haspopup="dialog"
581
- aria-expanded={menuOpen}
582
- aria-controls={`${rootId}-attachment-dialog`}
583
- disabled={disabled}
584
- whileTap={reduceMotion ? undefined : { scale: 0.9 }}
585
- className="border-border/70 bg-surface/40 text-muted hover:border-foreground/40 hover:text-foreground focus-visible:outline-foreground group/plus relative flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-xl border transition-colors duration-200 focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed disabled:opacity-50 sm:size-9"
586
- >
587
- <span
588
- aria-hidden="true"
589
- className="pointer-events-none absolute inset-0 rounded-[inherit] bg-[linear-gradient(145deg,rgba(255,255,255,0.14)_0%,transparent_48%,rgba(0,0,0,0.06)_100%)] opacity-0 transition-opacity duration-200 group-hover/plus:opacity-100"
590
- />
591
- <motion.span
592
- aria-hidden="true"
593
- animate={{ rotate: menuOpen ? 45 : 0 }}
594
- transition={
595
- reduceMotion
596
- ? { duration: 0 }
597
- : { type: 'spring', stiffness: 480, damping: 22 }
598
- }
599
- className="relative flex items-center justify-center"
600
- >
601
- <IconPlus size={17} stroke={1.8} />
602
- </motion.span>
603
- </motion.button>
604
- ) : null}
605
-
606
- <div className="relative min-w-0 flex-1">
607
- <textarea
608
- ref={fieldRef}
609
- value={value}
610
- onChange={(event) => updateValue(event.target.value)}
611
- onKeyDown={handleFieldKeyDown}
612
- placeholder={listening ? '' : placeholder}
613
- aria-label={label}
614
- rows={1}
615
- maxLength={maxLength}
616
- enterKeyHint="send"
617
- spellCheck={false}
618
- disabled={disabled}
619
- className={cn(
620
- 'placeholder:text-muted/70 text-foreground block w-full resize-none bg-transparent px-1 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed motion-safe:transition-[height] motion-safe:duration-200',
621
- textareaClassName,
622
- )}
623
- />
624
-
625
- <AnimatePresence>
626
- {listening && value.length === 0 ? (
627
- <motion.div
628
- aria-hidden="true"
629
- initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 5 }}
630
- animate={{ opacity: 1, y: 0 }}
631
- exit={reduceMotion ? { opacity: 0 } : { opacity: 0, y: -5 }}
632
- transition={{ duration: reduceMotion ? 0 : 0.18 }}
633
- className="pointer-events-none absolute inset-0 flex items-center gap-2.5 px-1 py-2"
634
- >
635
- <Equalizer reduceMotion={reduceMotion} />
636
- <span className="text-muted text-sm">Listening…</span>
637
- </motion.div>
638
- ) : null}
639
- </AnimatePresence>
640
- </div>
641
-
642
- <div className="flex shrink-0 items-center gap-1 sm:gap-1.5">
643
- {showVoice ? (
644
- <VoiceButton
645
- listening={listening}
646
- disabled={disabled}
647
- onClick={toggleListening}
648
- startLabel={startVoiceLabel}
649
- stopLabel={stopVoiceLabel}
650
- />
651
- ) : null}
652
- <SendButton
653
- state={sendState === 'busy' ? 'sending' : sendState}
654
- disabled={disabled}
655
- label={submitLabel}
656
- shakeControls={shakeControls}
657
- onClick={submit}
658
- onStop={onStop}
659
- />
660
- </div>
661
- </div>
662
-
663
- <input
664
- ref={fileInputRef}
665
- type="file"
666
- tabIndex={-1}
667
- aria-hidden="true"
668
- onChange={handleFiles}
669
- className="sr-only"
670
- />
671
- <AttachmentDialog
672
- id={`${rootId}-attachment-dialog`}
673
- anchorRef={menuTriggerRef}
674
- open={menuOpen}
675
- title={menuLabel}
676
- options={
677
- actions?.map((action) => ({
678
- ...action,
679
- description: action.description ?? action.hint,
680
- })) ?? []
681
- }
682
- onSelect={runAction}
683
- onClose={() => closeMenu(true)}
684
- accentColor={typeof glow === 'object' ? glow.color : undefined}
685
- />
686
- </div>
687
- )
688
- }
689
-
690
- export default AiChatInput