@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.
@@ -0,0 +1,640 @@
1
+ 'use client'
2
+
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
4
+ import type { RefObject } from 'react'
5
+ import { gsap } from 'gsap'
6
+ import { ScrollTrigger } from 'gsap/ScrollTrigger'
7
+ import { useGSAP } from '@gsap/react'
8
+ import { motion, useInView, useReducedMotion } from 'motion/react'
9
+ import { cn } from '@/lib/utils'
10
+
11
+ if (typeof window !== 'undefined') {
12
+ gsap.registerPlugin(ScrollTrigger, useGSAP)
13
+ }
14
+
15
+ export type ScrollCanvasSlide = {
16
+ image: string
17
+ imageAlt?: string
18
+ leftEyebrow?: string
19
+ leftHeading?: string
20
+ leftBody?: string
21
+ rightEyebrow?: string
22
+ rightHeading?: string
23
+ rightBody?: string
24
+ }
25
+
26
+ export type ScrollCanvasCardsProps = {
27
+ slides: ScrollCanvasSlide[]
28
+ className?: string
29
+ backgroundColor?: string
30
+ cardRadius?: number
31
+ cardMaxWidth?: number
32
+ cardHeight?: number
33
+ scrollLength?: number
34
+ cardBorderColor?: string
35
+ cardShadow?: string
36
+ headingClassName?: string
37
+ bodyClassName?: string
38
+ eyebrowClassName?: string
39
+ snap?: boolean
40
+ scrollContainerRef?: RefObject<HTMLElement | null>
41
+ onSlideChange?: (index: number) => void
42
+ }
43
+
44
+ const DEFAULT_BG = 'var(--background)'
45
+ const DEFAULT_CARD_RADIUS = 16
46
+ const DEFAULT_CARD_MAX_WIDTH = 320
47
+ const DEFAULT_CARD_HEIGHT = 220
48
+ const DEFAULT_SCROLL_LENGTH = 5
49
+ const DEFAULT_BORDER_COLOR = 'var(--border)'
50
+ const DEFAULT_SHADOW =
51
+ '0 12px 40px color-mix(in srgb, var(--foreground) 10%, transparent), 0 2px 10px color-mix(in srgb, var(--foreground) 6%, transparent)'
52
+
53
+ const HOLD = 0.06
54
+ const SPAN = 1 - HOLD * 2
55
+ const EASE_OUT = [0.22, 1, 0.36, 1] as const
56
+
57
+ type PanelContent = {
58
+ eyebrow?: string
59
+ heading?: string
60
+ body?: string
61
+ }
62
+
63
+ const easeInOut = (t: number) =>
64
+ t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2
65
+
66
+ function paintCover(
67
+ ctx: CanvasRenderingContext2D,
68
+ img: HTMLImageElement,
69
+ w: number,
70
+ h: number,
71
+ zoom: number,
72
+ shiftY: number,
73
+ alpha: number,
74
+ ) {
75
+ const imgRatio = img.naturalWidth / img.naturalHeight
76
+ const canvasRatio = w / h
77
+ let dw = imgRatio > canvasRatio ? h * imgRatio : w
78
+ let dh = imgRatio > canvasRatio ? h : w / imgRatio
79
+ dw *= zoom
80
+ dh *= zoom
81
+ ctx.save()
82
+ ctx.globalAlpha = alpha
83
+ ctx.drawImage(img, (w - dw) / 2, (h - dh) / 2 + shiftY, dw, dh)
84
+ ctx.restore()
85
+ }
86
+
87
+ function pose(slot: number, shift: number, reduce: boolean) {
88
+ if (slot === 0) {
89
+ return { opacity: 1, x: 0, y: 0, filter: 'blur(0px)' }
90
+ }
91
+ return {
92
+ opacity: 0,
93
+ x: reduce || slot < 0 ? 0 : shift,
94
+ y: reduce ? 0 : slot > 0 ? 30 : -22,
95
+ filter: reduce ? 'blur(0px)' : 'blur(8px)',
96
+ }
97
+ }
98
+
99
+ function SidePanel({
100
+ items,
101
+ active,
102
+ revealed,
103
+ side,
104
+ reduce,
105
+ eyebrowClassName,
106
+ headingClassName,
107
+ bodyClassName,
108
+ }: {
109
+ items: PanelContent[]
110
+ active: number
111
+ revealed: boolean
112
+ side: 'left' | 'right'
113
+ reduce: boolean
114
+ eyebrowClassName?: string
115
+ headingClassName?: string
116
+ bodyClassName?: string
117
+ }) {
118
+ const shift = side === 'left' ? -12 : 12
119
+ const align =
120
+ side === 'left' ? 'text-center md:text-right' : 'text-center md:text-left'
121
+
122
+ const timing = (isActive: boolean, order: number) => ({
123
+ duration: reduce ? 0.15 : isActive ? 0.75 : 0.4,
124
+ ease: EASE_OUT,
125
+ delay: reduce || !isActive ? 0 : 0.08 + order * 0.06,
126
+ })
127
+
128
+ return (
129
+ <div className="grid w-full max-w-xs md:max-w-[240px] lg:max-w-sm">
130
+ {items.map((item, i) => {
131
+ const offset = i - active
132
+ const slot = !revealed && offset === 0 ? 1 : offset
133
+ const isActive = slot === 0
134
+ const state = pose(slot, shift, reduce)
135
+
136
+ return (
137
+ <div
138
+ key={i}
139
+ aria-hidden={!isActive}
140
+ className={cn(
141
+ 'col-start-1 row-start-1 flex flex-col gap-1.5 sm:gap-2.5',
142
+ align,
143
+ !isActive && 'pointer-events-none select-none',
144
+ )}
145
+ >
146
+ {item.eyebrow && (
147
+ <motion.p
148
+ initial={false}
149
+ animate={state}
150
+ transition={timing(isActive, 0)}
151
+ className={cn(
152
+ 'text-muted font-mono text-[9px] font-medium tracking-[0.18em] uppercase sm:text-[10px] md:text-xs',
153
+ eyebrowClassName,
154
+ )}
155
+ >
156
+ {item.eyebrow}
157
+ </motion.p>
158
+ )}
159
+ {item.heading && (
160
+ <motion.h3
161
+ initial={false}
162
+ animate={state}
163
+ transition={timing(isActive, 1)}
164
+ className={cn(
165
+ 'text-foreground font-display text-base font-semibold tracking-tight leading-snug sm:text-lg md:text-xl',
166
+ headingClassName,
167
+ )}
168
+ >
169
+ {item.heading}
170
+ </motion.h3>
171
+ )}
172
+ {item.body && (
173
+ <motion.p
174
+ initial={false}
175
+ animate={state}
176
+ transition={timing(isActive, 2)}
177
+ className={cn(
178
+ 'text-muted max-w-prose text-xs leading-relaxed sm:text-sm md:text-base',
179
+ bodyClassName,
180
+ )}
181
+ >
182
+ {item.body}
183
+ </motion.p>
184
+ )}
185
+ </div>
186
+ )
187
+ })}
188
+ </div>
189
+ )
190
+ }
191
+
192
+ function ProgressDots({
193
+ total,
194
+ active,
195
+ reduce,
196
+ onSelect,
197
+ }: {
198
+ total: number
199
+ active: number
200
+ reduce: boolean
201
+ onSelect: (index: number) => void
202
+ }) {
203
+ return (
204
+ <div className="mt-4 flex items-center justify-center gap-1 sm:mt-6">
205
+ {Array.from({ length: total }).map((_, i) => (
206
+ <button
207
+ key={i}
208
+ type="button"
209
+ aria-label={`Go to slide ${i + 1}`}
210
+ aria-current={i === active}
211
+ onClick={() => onSelect(i)}
212
+ className="flex h-5 cursor-pointer items-center rounded-full px-1 outline-none focus-visible:ring-2 focus-visible:ring-foreground/40"
213
+ >
214
+ <motion.span
215
+ initial={false}
216
+ animate={{
217
+ width: i === active ? 20 : 6,
218
+ opacity: i === active ? 1 : 0.35,
219
+ }}
220
+ transition={
221
+ reduce
222
+ ? { duration: 0.15 }
223
+ : { type: 'spring', stiffness: 400, damping: 28 }
224
+ }
225
+ className={cn(
226
+ 'block h-1.5 rounded-full transition-colors',
227
+ i === active ? 'bg-foreground' : 'bg-muted',
228
+ )}
229
+ />
230
+ </button>
231
+ ))}
232
+ </div>
233
+ )
234
+ }
235
+
236
+ function useScrollCanvas({
237
+ canvasRef,
238
+ images,
239
+ positionRef,
240
+ reduce,
241
+ onIndexChange,
242
+ onFrame,
243
+ }: {
244
+ canvasRef: React.RefObject<HTMLCanvasElement | null>
245
+ images: string[]
246
+ positionRef: { current: number }
247
+ reduce: boolean
248
+ onIndexChange: (index: number) => void
249
+ onFrame?: (position: number) => void
250
+ }) {
251
+ const loaded = useRef<(HTMLImageElement | null)[]>([])
252
+ const current = useRef(0)
253
+ const lastIndex = useRef(0)
254
+ const dirty = useRef(true)
255
+ const size = useRef({ w: 0, h: 0, dpr: 1 })
256
+ const onIndexRef = useRef(onIndexChange)
257
+ const onFrameRef = useRef(onFrame)
258
+
259
+ useEffect(() => {
260
+ onIndexRef.current = onIndexChange
261
+ onFrameRef.current = onFrame
262
+ })
263
+
264
+ useEffect(() => {
265
+ let cancelled = false
266
+ loaded.current = images.map(() => null)
267
+ images.forEach((src, i) => {
268
+ const img = new Image()
269
+ img.decoding = 'async'
270
+ img.onload = () => {
271
+ if (cancelled) return
272
+ loaded.current[i] = img
273
+ dirty.current = true
274
+ }
275
+ img.src = src
276
+ })
277
+ return () => {
278
+ cancelled = true
279
+ }
280
+ }, [images])
281
+
282
+ useEffect(() => {
283
+ const canvas = canvasRef.current
284
+ if (!canvas) return
285
+ const ctx = canvas.getContext('2d')
286
+ if (!ctx) return
287
+
288
+ const resize = () => {
289
+ const w = canvas.clientWidth
290
+ const h = canvas.clientHeight
291
+ const dpr = Math.min(window.devicePixelRatio || 1, 2)
292
+ canvas.width = Math.round(w * dpr)
293
+ canvas.height = Math.round(h * dpr)
294
+ ctx.imageSmoothingQuality = 'high'
295
+ size.current = { w, h, dpr }
296
+ dirty.current = true
297
+ }
298
+
299
+ const draw = (pos: number) => {
300
+ const { w, h, dpr } = size.current
301
+ const frames = loaded.current
302
+ const last = frames.length - 1
303
+ if (!w || !h || last < 0) return
304
+
305
+ const clamped = Math.min(Math.max(pos, 0), last)
306
+ const base = Math.min(Math.floor(clamped), last)
307
+ const t = clamped - base
308
+ const e = easeInOut(t)
309
+ const from = frames[base]
310
+ const to = base < last ? frames[base + 1] : null
311
+
312
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
313
+ ctx.clearRect(0, 0, w, h)
314
+ if (from) paintCover(ctx, from, w, h, 1 + e * 0.07, -e * 12, 1)
315
+ if (to && t > 0) paintCover(ctx, to, w, h, 1.07 - e * 0.07, (1 - e) * 12, e)
316
+ onFrameRef.current?.(clamped)
317
+ }
318
+
319
+ const tick = (_time: number, deltaTime: number) => {
320
+ const target = reduce
321
+ ? Math.round(positionRef.current)
322
+ : positionRef.current
323
+ const delta = target - current.current
324
+
325
+ if (Math.abs(delta) > 0.0004) {
326
+ const k = reduce ? 1 : 1 - Math.exp(-Math.min(deltaTime, 100) / 150)
327
+ current.current += delta * k
328
+ dirty.current = true
329
+ } else if (delta !== 0) {
330
+ current.current = target
331
+ dirty.current = true
332
+ }
333
+
334
+ const index = Math.round(current.current)
335
+ if (index !== lastIndex.current) {
336
+ lastIndex.current = index
337
+ onIndexRef.current(index)
338
+ }
339
+
340
+ if (dirty.current) {
341
+ dirty.current = false
342
+ draw(current.current)
343
+ }
344
+ }
345
+
346
+ resize()
347
+ const observer = new ResizeObserver(resize)
348
+ observer.observe(canvas)
349
+ gsap.ticker.add(tick)
350
+
351
+ return () => {
352
+ observer.disconnect()
353
+ gsap.ticker.remove(tick)
354
+ }
355
+ }, [canvasRef, positionRef, reduce])
356
+ }
357
+
358
+ export function ScrollCanvasCards({
359
+ slides,
360
+ className,
361
+ backgroundColor = DEFAULT_BG,
362
+ cardRadius = DEFAULT_CARD_RADIUS,
363
+ cardMaxWidth = DEFAULT_CARD_MAX_WIDTH,
364
+ cardHeight = DEFAULT_CARD_HEIGHT,
365
+ scrollLength = DEFAULT_SCROLL_LENGTH,
366
+ cardBorderColor = DEFAULT_BORDER_COLOR,
367
+ cardShadow = DEFAULT_SHADOW,
368
+ headingClassName,
369
+ bodyClassName,
370
+ eyebrowClassName,
371
+ snap = true,
372
+ scrollContainerRef,
373
+ onSlideChange,
374
+ }: ScrollCanvasCardsProps) {
375
+ const containerRef = useRef<HTMLElement>(null)
376
+ const canvasRef = useRef<HTMLCanvasElement>(null)
377
+ const cardRef = useRef<HTMLDivElement>(null)
378
+ const triggerRef = useRef<ScrollTrigger | null>(null)
379
+ const positionRef = useRef(0)
380
+ const [activeIndex, setActiveIndex] = useState(0)
381
+ const reduce = useReducedMotion() ?? false
382
+ const inView = useInView(containerRef, { once: true, amount: 0.3 })
383
+ const revealed = reduce || inView
384
+ const count = slides.length
385
+ const currentSlide = slides[activeIndex] ?? slides[0]
386
+
387
+ const imageKey = JSON.stringify(slides.map((s) => s.image))
388
+ const imageUrls = useMemo(() => JSON.parse(imageKey) as string[], [imageKey])
389
+
390
+ const leftItems = useMemo<PanelContent[]>(
391
+ () =>
392
+ slides.map((s) => ({
393
+ eyebrow: s.leftEyebrow,
394
+ heading: s.leftHeading,
395
+ body: s.leftBody,
396
+ })),
397
+ [slides],
398
+ )
399
+ const rightItems = useMemo<PanelContent[]>(
400
+ () =>
401
+ slides.map((s) => ({
402
+ eyebrow: s.rightEyebrow,
403
+ heading: s.rightHeading,
404
+ body: s.rightBody,
405
+ })),
406
+ [slides],
407
+ )
408
+ const hasLeft = leftItems.some((i) => i.eyebrow || i.heading || i.body)
409
+ const hasRight = rightItems.some((i) => i.eyebrow || i.heading || i.body)
410
+
411
+ const handleIndex = useCallback(
412
+ (index: number) => {
413
+ setActiveIndex(index)
414
+ onSlideChange?.(index)
415
+ },
416
+ [onSlideChange],
417
+ )
418
+
419
+ const handleFrame = useCallback(
420
+ (position: number) => {
421
+ const card = cardRef.current
422
+ if (!card || reduce) return
423
+ const wave = Math.sin((position - Math.floor(position)) * Math.PI)
424
+ card.style.transform = `translateY(${(-wave * 5).toFixed(2)}px) scale(${(1 - wave * 0.025).toFixed(4)})`
425
+ },
426
+ [reduce],
427
+ )
428
+
429
+ useScrollCanvas({
430
+ canvasRef,
431
+ images: imageUrls,
432
+ positionRef,
433
+ reduce,
434
+ onIndexChange: handleIndex,
435
+ onFrame: handleFrame,
436
+ })
437
+
438
+ useGSAP(
439
+ () => {
440
+ const el = containerRef.current
441
+ if (!el || count < 2) return
442
+
443
+ const scroller = scrollContainerRef?.current || undefined
444
+ const toPosition = (progress: number) =>
445
+ Math.min(Math.max((progress - HOLD) / SPAN, 0), 1) * (count - 1)
446
+
447
+ triggerRef.current = ScrollTrigger.create({
448
+ trigger: el,
449
+ scroller: scroller,
450
+ start: 'top top',
451
+ end: () => {
452
+ const vh = scroller ? scroller.clientHeight : window.innerHeight
453
+ return `+=${Math.round(vh * scrollLength)}`
454
+ },
455
+ pin: true,
456
+ pinSpacing: true,
457
+ anticipatePin: 1,
458
+ invalidateOnRefresh: true,
459
+ snap:
460
+ snap && !reduce
461
+ ? {
462
+ snapTo: (value: number) => {
463
+ if (value <= HOLD || value >= 1 - HOLD) return value
464
+ const step = Math.round(((value - HOLD) / SPAN) * (count - 1))
465
+ return HOLD + (step / (count - 1)) * SPAN
466
+ },
467
+ duration: { min: 0.25, max: 0.7 },
468
+ delay: 0.12,
469
+ ease: 'power2.inOut',
470
+ inertia: false,
471
+ }
472
+ : undefined,
473
+ onRefresh: (self) => {
474
+ positionRef.current = toPosition(self.progress)
475
+ },
476
+ onUpdate: (self) => {
477
+ positionRef.current = toPosition(self.progress)
478
+ },
479
+ })
480
+
481
+ ScrollTrigger.refresh()
482
+ },
483
+ {
484
+ scope: containerRef,
485
+ dependencies: [count, scrollLength, reduce, snap, scrollContainerRef],
486
+ },
487
+ )
488
+
489
+ const scrollToSlide = useCallback(
490
+ (index: number) => {
491
+ const trigger = triggerRef.current
492
+ if (!trigger) return
493
+ const progress = HOLD + SPAN * (index / Math.max(count - 1, 1))
494
+ const targetTop = trigger.start + (trigger.end - trigger.start) * progress
495
+ const scroller = scrollContainerRef?.current
496
+ if (scroller) {
497
+ scroller.scrollTo({
498
+ top: targetTop,
499
+ behavior: reduce ? 'auto' : 'smooth',
500
+ })
501
+ } else {
502
+ window.scrollTo({
503
+ top: targetTop,
504
+ behavior: reduce ? 'auto' : 'smooth',
505
+ })
506
+ }
507
+ },
508
+ [count, reduce, scrollContainerRef],
509
+ )
510
+
511
+ const cardVariants = {
512
+ out: {
513
+ opacity: reduce ? 1 : 0,
514
+ scale: reduce ? 1 : 0.9,
515
+ y: reduce ? 0 : 24,
516
+ },
517
+ in: {
518
+ opacity: 1,
519
+ scale: 1,
520
+ y: 0,
521
+ transition: reduce
522
+ ? { duration: 0.15 }
523
+ : { type: 'spring' as const, stiffness: 170, damping: 24, mass: 0.9 },
524
+ },
525
+ }
526
+
527
+ return (
528
+ <section
529
+ ref={containerRef}
530
+ className={cn('relative w-full', className)}
531
+ style={{ backgroundColor, minHeight: '100svh' }}
532
+ >
533
+ <div className="sr-only" role="status" aria-live="polite">
534
+ Slide {activeIndex + 1} of {count}
535
+ {currentSlide?.imageAlt ? `: ${currentSlide.imageAlt}` : ''}
536
+ </div>
537
+
538
+ <div className="mx-auto flex min-h-svh w-full max-w-6xl items-center px-4 py-8 sm:px-6 md:px-8 md:py-16">
539
+ <div className="grid w-full grid-cols-1 items-center justify-items-center gap-5 sm:gap-6 md:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] md:gap-6 lg:gap-10">
540
+ <div
541
+ className={cn(
542
+ 'order-2 w-full justify-center md:order-1 md:flex md:justify-end',
543
+ hasLeft ? 'flex' : 'hidden',
544
+ )}
545
+ >
546
+ {hasLeft && (
547
+ <SidePanel
548
+ items={leftItems}
549
+ active={activeIndex}
550
+ revealed={revealed}
551
+ side="left"
552
+ reduce={reduce}
553
+ eyebrowClassName={eyebrowClassName}
554
+ headingClassName={headingClassName}
555
+ bodyClassName={bodyClassName}
556
+ />
557
+ )}
558
+ </div>
559
+
560
+ <motion.div
561
+ variants={cardVariants}
562
+ initial="out"
563
+ animate={revealed ? 'in' : 'out'}
564
+ className="order-1 flex w-full flex-col items-center justify-center md:order-2 md:w-auto"
565
+ >
566
+ <div
567
+ ref={cardRef}
568
+ className="relative will-change-transform"
569
+ style={{
570
+ width: '100%',
571
+ maxWidth: `min(${cardMaxWidth}px, calc(100vw - 2.5rem))`,
572
+ aspectRatio: `${cardMaxWidth} / ${cardHeight}`,
573
+ maxHeight: cardHeight,
574
+ }}
575
+ >
576
+ <div
577
+ className="pointer-events-none absolute -inset-[1px]"
578
+ style={{
579
+ border: `1px solid ${cardBorderColor}`,
580
+ borderRadius: cardRadius + 1,
581
+ }}
582
+ />
583
+ <div
584
+ className="bg-surface relative h-full w-full overflow-hidden"
585
+ style={{
586
+ borderRadius: cardRadius,
587
+ boxShadow: cardShadow,
588
+ }}
589
+ >
590
+ <canvas
591
+ ref={canvasRef}
592
+ role="img"
593
+ aria-label={currentSlide?.imageAlt}
594
+ className="absolute inset-0 h-full w-full"
595
+ />
596
+ <div
597
+ className="pointer-events-none absolute inset-0"
598
+ style={{
599
+ borderRadius: cardRadius,
600
+ boxShadow:
601
+ 'inset 0 0 50px color-mix(in srgb, var(--foreground) 8%, transparent)',
602
+ }}
603
+ />
604
+ </div>
605
+ </div>
606
+ <ProgressDots
607
+ total={count}
608
+ active={activeIndex}
609
+ reduce={reduce}
610
+ onSelect={scrollToSlide}
611
+ />
612
+ </motion.div>
613
+
614
+ <div
615
+ className={cn(
616
+ 'order-3 flex w-full justify-center border-border/40 pt-2 md:order-3 md:border-0 md:pt-0 md:justify-start',
617
+ hasRight ? 'flex' : 'hidden',
618
+ hasLeft && 'border-t md:border-t-0',
619
+ )}
620
+ >
621
+ {hasRight && (
622
+ <SidePanel
623
+ items={rightItems}
624
+ active={activeIndex}
625
+ revealed={revealed}
626
+ side="right"
627
+ reduce={reduce}
628
+ eyebrowClassName={eyebrowClassName}
629
+ headingClassName={headingClassName}
630
+ bodyClassName={bodyClassName}
631
+ />
632
+ )}
633
+ </div>
634
+ </div>
635
+ </div>
636
+ </section>
637
+ )
638
+ }
639
+
640
+ export default ScrollCanvasCards