@istmx/ui 0.1.11 → 0.1.13

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 (55) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +533 -463
  3. package/bin/istmx.mjs +481 -314
  4. package/package.json +27 -27
  5. package/registry/accordion.tsx +186 -0
  6. package/registry/ai-chat-block/ai-chat-block.tsx +456 -460
  7. package/registry/ai-chat-block/ai-chat-input.tsx +694 -694
  8. package/registry/ai-chat-block/attachment.tsx +466 -466
  9. package/registry/ai-chat-block/chat-code-block.tsx +50 -50
  10. package/registry/ai-chat-block/chat-composer.tsx +51 -51
  11. package/registry/ai-chat-block/chat-logo.tsx +18 -18
  12. package/registry/ai-chat-block/chat-message.tsx +161 -161
  13. package/registry/ai-chat-block/chat-sidebar.tsx +273 -273
  14. package/registry/ai-chat-block/chat-user-avatar.tsx +9 -9
  15. package/registry/ai-chat-block/code-highlighter.tsx +342 -357
  16. package/registry/ai-chat-block/default-attachments.tsx +42 -42
  17. package/registry/ai-chat-block/index.ts +30 -30
  18. package/registry/ai-chat-block/message-content.tsx +287 -287
  19. package/registry/ai-chat-block/message-list.tsx +93 -93
  20. package/registry/ai-chat-block/send-button.tsx +102 -102
  21. package/registry/ai-chat-block/types.ts +70 -71
  22. package/registry/ai-chat-block/utils.ts +6 -6
  23. package/registry/ai-chat-block/voice-button.tsx +66 -66
  24. package/registry/alert-dialog.tsx +229 -0
  25. package/registry/alert.tsx +188 -0
  26. package/registry/animated-text.tsx +228 -225
  27. package/registry/aspect-ratio.tsx +32 -0
  28. package/registry/avatar-group.tsx +66 -0
  29. package/registry/avatar.tsx +121 -0
  30. package/registry/badge.tsx +52 -0
  31. package/registry/bento-grid.tsx +438 -433
  32. package/registry/button.tsx +156 -237
  33. package/registry/carousel.tsx +184 -0
  34. package/registry/dock-navigation.tsx +200 -198
  35. package/registry/drift-canvas.tsx +383 -0
  36. package/registry/drift-wall.tsx +361 -0
  37. package/registry/flex-carousel.tsx +1430 -0
  38. package/registry/guided-gallery.tsx +1506 -0
  39. package/registry/image-accordion.tsx +306 -302
  40. package/registry/image-trail.tsx +126 -121
  41. package/registry/infinite-image-canvas.tsx +268 -263
  42. package/registry/input-otp.tsx +332 -0
  43. package/registry/list-card.tsx +130 -0
  44. package/registry/mobile-menu-dock.tsx +216 -211
  45. package/registry/morph-slider.tsx +756 -0
  46. package/registry/pixel-cat.tsx +972 -1020
  47. package/registry/scroll-canvas-cards.tsx +643 -0
  48. package/registry/scroll-parallax-hero.tsx +566 -565
  49. package/registry/scroll-story-cards.tsx +443 -438
  50. package/registry/slider.tsx +163 -0
  51. package/registry/spotlight-grid.tsx +226 -0
  52. package/registry/streaming-text.tsx +269 -278
  53. package/registry/text-reveal.tsx +311 -307
  54. package/registry/user-avatar.tsx +99 -0
  55. package/registry/utils.ts +6 -6
@@ -0,0 +1,1506 @@
1
+ 'use client';
2
+
3
+ import { forwardRef, useEffect, useImperativeHandle, useRef, useState, type CSSProperties } from 'react';
4
+ import { motion, useReducedMotion } from 'motion/react';
5
+ import { TextMorph } from 'torph/react';
6
+ import NextImage from 'next/image';
7
+ import { Renderer, Program, Mesh, Triangle, Plane, Texture, RenderTarget } from 'ogl';
8
+ import { cn } from '@/lib/utils';
9
+
10
+ export interface GuidedGalleryItem {
11
+ src: string;
12
+ alt: string;
13
+ aspect?: number;
14
+ focalPoint?: GuidedGalleryFocusPoint;
15
+ title?: string;
16
+ subtitle?: string;
17
+ note?: string;
18
+ }
19
+
20
+ export interface GuidedGalleryFocusPoint {
21
+ x: number;
22
+ y: number;
23
+ }
24
+
25
+ export type GuidedGalleryPreset = 'liquid' | 'ribbon' | 'vortex' | 'arch';
26
+ export type GuidedGalleryIntro = 'rise' | 'bloom' | 'spin' | 'deal' | 'fade' | 'none';
27
+ export type GuidedGalleryFit = 'natural' | 'portrait' | 'square' | 'landscape';
28
+ export type GuidedGalleryCurl = 'twist' | 'rise' | 'fall';
29
+
30
+ export interface GuidedGalleryProps {
31
+ items?: GuidedGalleryItem[];
32
+ preset?: GuidedGalleryPreset;
33
+ intro?: GuidedGalleryIntro;
34
+ cardHeight?: number;
35
+ gap?: number;
36
+ radius?: number;
37
+ fit?: GuidedGalleryFit;
38
+ lensWidth?: number;
39
+ lensHeight?: number;
40
+ tilt?: number;
41
+ roundness?: number;
42
+ bend?: number;
43
+ reach?: number;
44
+ curl?: GuidedGalleryCurl;
45
+ dispersion?: number;
46
+ liquid?: number;
47
+ followCursor?: boolean;
48
+ squeeze?: number;
49
+ focusOnClick?: boolean;
50
+ autoplay?: boolean;
51
+ interval?: number;
52
+ captions?: boolean;
53
+ captureWheel?: boolean;
54
+ onChange?: (index: number, item: GuidedGalleryItem) => void;
55
+ onSelect?: (index: number, item: GuidedGalleryItem) => void;
56
+ className?: string;
57
+ style?: CSSProperties;
58
+ 'aria-label'?: string;
59
+ }
60
+
61
+ interface BendPreset {
62
+ lensWidth: number;
63
+ lensHeight: number;
64
+ tilt: number;
65
+ roundness: number;
66
+ bend: number;
67
+ reach: number;
68
+ curl: GuidedGalleryCurl;
69
+ dispersion: number;
70
+ liquid: number;
71
+ followCursor: boolean;
72
+ }
73
+
74
+ interface CarouselMetrics {
75
+ cardH: number;
76
+ widths: number[];
77
+ centers: number[];
78
+ gap: number;
79
+ loop: number;
80
+ }
81
+
82
+ interface CarouselSettings extends BendPreset {
83
+ intro: GuidedGalleryIntro;
84
+ cardHeight: number;
85
+ gap: number;
86
+ radius: number;
87
+ fit: GuidedGalleryFit;
88
+ squeeze: number;
89
+ focusOnClick: boolean;
90
+ autoplay: boolean;
91
+ interval: number;
92
+ captureWheel: boolean;
93
+ }
94
+
95
+ interface CarouselSlot {
96
+ item: GuidedGalleryItem;
97
+ index: number;
98
+ texture: Texture;
99
+ aspect: number;
100
+ loaded: boolean;
101
+ failed: boolean;
102
+ ready: number;
103
+ color: number[];
104
+ image: number[];
105
+ dispose: () => void;
106
+ }
107
+
108
+ const photo = (id: string) => `https://images.unsplash.com/${id}?w=1200&q=80&auto=format&fit=max`;
109
+
110
+ const DEFAULT_ITEMS: GuidedGalleryItem[] = [
111
+ {
112
+ src: photo('photo-1737071371043-761e02b1ef95'),
113
+ alt: 'An iridescent chrome sculpture of a head',
114
+ title: 'Iridescence'
115
+ },
116
+ {
117
+ src: photo('photo-1693645325828-62cd35c8da8f'),
118
+ alt: 'A person in dark clothes standing in front of a white backdrop',
119
+ title: 'White Room'
120
+ },
121
+ { src: photo('photo-1739056238917-d89cd05c48d5'), alt: 'A twisted chrome form on black', title: 'Liquid Metal' },
122
+ { src: photo('photo-1747191092806-c7da11881986'), alt: 'A clay bust shown in profile', title: 'Clay Study' },
123
+ { src: photo('photo-1605034313761-73ea4a0cfbf3'), alt: 'Black and white low top sneakers', title: 'Low Tops' },
124
+ { src: photo('photo-1495462911434-be47104d70fa'), alt: 'A woman in a wide black hat', title: 'Brim' },
125
+ {
126
+ src: photo('photo-1786835568925-20cd20007ed0'),
127
+ alt: 'Three swirling shapes in white, gold and silver on grey',
128
+ title: 'Three Forms'
129
+ },
130
+ { src: photo('photo-1770249196550-ff6c641165cb'), alt: 'A chrome humanoid sculpture', title: 'Automaton' },
131
+ {
132
+ src: photo('photo-1787181875088-087d612262a7'),
133
+ alt: 'A black textured sculpture with an opening at its center',
134
+ title: 'Obsidian'
135
+ },
136
+ {
137
+ src: photo('photo-1770062422885-2dfcbe8fb65b'),
138
+ alt: 'A woman in a white shirt crouching on a dark set',
139
+ title: 'Poise'
140
+ },
141
+ { src: photo('photo-1726910133626-9b573eca70ff'), alt: 'Black curved shapes stacked like a fan', title: 'Fins' },
142
+ { src: photo('photo-1604854574958-59047362c165'), alt: 'A white plaster bust on a black table', title: 'Plaster' }
143
+ ];
144
+
145
+ const BEND_PRESETS: Record<GuidedGalleryPreset, BendPreset> = {
146
+ liquid: {
147
+ lensWidth: 0.74,
148
+ lensHeight: 1.18,
149
+ tilt: 62,
150
+ roundness: 1,
151
+ bend: 0.34,
152
+ reach: 0.38,
153
+ curl: 'twist',
154
+ dispersion: 0.45,
155
+ liquid: 0,
156
+ followCursor: false
157
+ },
158
+ ribbon: {
159
+ lensWidth: 0.8,
160
+ lensHeight: 0.8,
161
+ tilt: 0,
162
+ roundness: 1,
163
+ bend: 0.34,
164
+ reach: 0.34,
165
+ curl: 'twist',
166
+ dispersion: 0.4,
167
+ liquid: 0,
168
+ followCursor: false
169
+ },
170
+ vortex: {
171
+ lensWidth: 0.7,
172
+ lensHeight: 0.95,
173
+ tilt: 30,
174
+ roundness: 1,
175
+ bend: 0.46,
176
+ reach: 0.3,
177
+ curl: 'twist',
178
+ dispersion: 0.5,
179
+ liquid: 0,
180
+ followCursor: false
181
+ },
182
+ arch: {
183
+ lensWidth: 0.8,
184
+ lensHeight: 0.8,
185
+ tilt: 0,
186
+ roundness: 1,
187
+ bend: 0.3,
188
+ reach: 0.36,
189
+ curl: 'rise',
190
+ dispersion: 0.4,
191
+ liquid: 0,
192
+ followCursor: false
193
+ }
194
+ };
195
+
196
+ const FIT_ASPECT: Partial<Record<GuidedGalleryFit, number>> = { portrait: 0.75, square: 1, landscape: 4 / 3 };
197
+ const TAPS = 12;
198
+ const PIXEL_BUDGET = 4.5e6;
199
+ const INTRO_DURATION: Record<Exclude<GuidedGalleryIntro, 'none'>, number> = { rise: 2.1, bloom: 1.6, spin: 2.2, deal: 1.5, fade: 0.35 };
200
+ const PLAY_ICON_PATH = 'M7 5 L13 8.5 L13 15.5 L7 19 Z M13 8.5 L19 12 L13 15.5 L13 8.5 Z';
201
+ const PAUSE_ICON_PATH = 'M7 5 L11 5 L11 19 L7 19 Z M13 5 L17 5 L17 19 L13 19 Z';
202
+
203
+ const wrap = (value: number, size: number) => ((((value + size / 2) % size) + size) % size) - size / 2;
204
+ const clamp01 = (value: number) => Math.min(Math.max(value, 0), 1);
205
+ const easeOut = (value: number) => 1 - Math.pow(1 - clamp01(value), 3);
206
+ const easeOutQuint = (value: number) => 1 - Math.pow(1 - clamp01(value), 5);
207
+ const easeInOut = (value: number) => {
208
+ const t = clamp01(value);
209
+ return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
210
+ };
211
+
212
+ const cardVertex = `#version 300 es
213
+ in vec3 position;
214
+ in vec2 uv;
215
+ uniform vec4 uRect;
216
+ uniform vec2 uResolution;
217
+ out vec2 vUv;
218
+ out vec2 vLocal;
219
+ void main() {
220
+ vUv = uv;
221
+ vLocal = vec2(position.x, -position.y) * uRect.zw;
222
+ vec2 px = uRect.xy + vLocal;
223
+ gl_Position = vec4(px.x / uResolution.x * 2.0 - 1.0, 1.0 - px.y / uResolution.y * 2.0, 0.0, 1.0);
224
+ }
225
+ `;
226
+
227
+ const cardFragment = `#version 300 es
228
+ precision highp float;
229
+ uniform sampler2D tMap;
230
+ uniform vec2 uSize;
231
+ uniform vec2 uImage;
232
+ uniform float uRadius;
233
+ uniform float uAlpha;
234
+ uniform float uReady;
235
+ uniform float uShift;
236
+ uniform vec2 uFocal;
237
+ uniform float uDpr;
238
+ uniform vec3 uPlaceholder;
239
+ in vec2 vUv;
240
+ in vec2 vLocal;
241
+ out vec4 fragColor;
242
+
243
+ float roundedBox(vec2 p, vec2 b, float r) {
244
+ vec2 q = abs(p) - b + r;
245
+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
246
+ }
247
+
248
+ void main() {
249
+ float sd = roundedBox(vLocal, uSize * 0.5, min(uRadius, min(uSize.x, uSize.y) * 0.5));
250
+ float mask = clamp(0.5 - sd * uDpr, 0.0, 1.0);
251
+ vec2 local = vLocal / uSize + 0.5;
252
+ float cardAspect = uSize.x / uSize.y;
253
+ float imageAspect = uImage.x / max(uImage.y, 1.0);
254
+ vec2 scale = imageAspect > cardAspect ? vec2(cardAspect / imageAspect, 1.0) : vec2(1.0, imageAspect / cardAspect);
255
+ scale /= 1.08;
256
+ vec2 focal = vec2(uFocal.x, 1.0 - uFocal.y);
257
+ vec2 cropCenter = clamp(focal, scale * 0.5, 1.0 - scale * 0.5);
258
+ vec2 uv = (vec2(local.x, 1.0 - local.y) - 0.5) * scale + cropCenter;
259
+ uv.x += uShift * (1.0 - scale.x) * 0.5;
260
+ vec3 image = texture(tMap, uv).rgb;
261
+ vec3 color = mix(uPlaceholder, image, uReady);
262
+ float alpha = mask * uAlpha;
263
+ fragColor = vec4(color * alpha, alpha);
264
+ }
265
+ `;
266
+
267
+ const lensVertex = `#version 300 es
268
+ in vec2 position;
269
+ void main() {
270
+ gl_Position = vec4(position, 0.0, 1.0);
271
+ }
272
+ `;
273
+
274
+ const lensFragment = `#version 300 es
275
+ precision highp float;
276
+ uniform sampler2D tScene;
277
+ uniform vec2 uResolution;
278
+ uniform float uDpr;
279
+ uniform vec2 uCenter;
280
+ uniform vec2 uHalf;
281
+ uniform float uAngle;
282
+ uniform float uExponent;
283
+ uniform float uInner;
284
+ uniform float uOuter;
285
+ uniform float uFlow;
286
+ uniform float uCurl;
287
+ uniform float uDispersion;
288
+ uniform float uStrength;
289
+ uniform float uSceneAlpha;
290
+ out vec4 fragColor;
291
+
292
+ void main() {
293
+ vec2 frag = gl_FragCoord.xy / uDpr;
294
+ vec2 uv = frag / uResolution;
295
+ vec2 rel = frag - vec2(uCenter.x, uResolution.y - uCenter.y);
296
+ float ca = cos(uAngle);
297
+ float sa = sin(uAngle);
298
+ vec2 local = vec2(ca * rel.x + sa * rel.y, -sa * rel.x + ca * rel.y);
299
+ vec2 k = max(abs(local) / uHalf, vec2(1e-5));
300
+ float nd = pow(pow(k.x, uExponent) + pow(k.y, uExponent), 1.0 / uExponent);
301
+ vec2 grad = pow(k, vec2(uExponent - 1.0)) * sign(local) / uHalf * pow(nd, 1.0 - uExponent);
302
+ float glen = max(length(grad), 1e-6);
303
+ float edge = (nd - 1.0) / glen;
304
+ vec2 outward = grad / glen;
305
+ vec2 normal = vec2(ca * outward.x - sa * outward.y, sa * outward.x + ca * outward.y);
306
+ vec2 along = vec2(-normal.y, normal.x);
307
+
308
+ float t = clamp((edge + uInner) / (uInner + uOuter), 0.0, 1.0);
309
+ float ramp = t * t * t * (t * (t * 6.0 - 15.0) + 10.0);
310
+ float slope = 16.0 * t * t * (1.0 - t) * (1.0 - t);
311
+ float reachX = rel.x / (uResolution.x * 0.5);
312
+ float side = smoothstep(0.02, 0.3, abs(reachX)) * (uCurl == 0.0 ? sign(reachX) : uCurl);
313
+ float lift = ramp * side * uFlow * uStrength;
314
+ vec2 swirl = along * along.y * side * slope * uFlow * uStrength * 0.35;
315
+ vec2 drift = vec2(0.0, -lift) - swirl;
316
+ vec2 shifted = uv + drift / uResolution;
317
+
318
+ vec2 texels = uResolution * uDpr;
319
+ vec2 gx = dFdx(shifted);
320
+ vec2 gy = dFdy(shifted);
321
+ gx *= min(1.0, 3.0 / max(length(gx * texels), 1e-4));
322
+ gy *= min(1.0, 3.0 / max(length(gy * texels), 1e-4));
323
+
324
+ vec4 color = textureGrad(tScene, shifted, gx, gy);
325
+ vec2 spread = vec2(0.0, side * slope * uFlow * uStrength) / uResolution * uDispersion;
326
+ float spreadPx = length(spread * texels);
327
+ if (color.a > 0.002 && spreadPx > 0.25) {
328
+ vec3 base = color.rgb / color.a;
329
+ vec3 sumColor = vec3(0.0);
330
+ vec3 sumWeight = vec3(0.0);
331
+ for (int i = 0; i < ${TAPS}; i++) {
332
+ float s = (float(i) + 0.5) / float(${TAPS});
333
+ vec4 c = textureGrad(tScene, shifted + spread * (s - 0.5), gx, gy);
334
+ vec3 w = max(1.0 - abs(vec3(s) - vec3(0.15, 0.5, 0.85)) * 2.6, 0.0) * c.a;
335
+ sumColor += c.rgb * (w / max(c.a, 0.002));
336
+ sumWeight += w;
337
+ }
338
+ vec3 split = mix(base, sumColor / max(sumWeight, vec3(1e-4)), clamp(sumWeight * 2.0, 0.0, 1.0));
339
+ color.rgb = mix(color.rgb, clamp(split, 0.0, 1.0) * color.a, smoothstep(0.25, 1.5, spreadPx));
340
+ }
341
+
342
+ fragColor = color * uSceneAlpha;
343
+ }
344
+ `;
345
+
346
+ export const GuidedGallery = forwardRef<HTMLDivElement, GuidedGalleryProps>(function GuidedGallery({
347
+ items = DEFAULT_ITEMS,
348
+ preset = 'liquid',
349
+ intro = 'rise',
350
+ cardHeight = 0.5,
351
+ gap = 12,
352
+ radius = 0,
353
+ fit = 'natural',
354
+ lensWidth = undefined,
355
+ lensHeight = undefined,
356
+ tilt = undefined,
357
+ roundness = undefined,
358
+ bend = undefined,
359
+ reach = undefined,
360
+ curl = undefined,
361
+ dispersion = undefined,
362
+ liquid = undefined,
363
+ followCursor = undefined,
364
+ squeeze = 0.2,
365
+ focusOnClick = true,
366
+ autoplay = false,
367
+ interval = 1.5,
368
+ captions = true,
369
+ captureWheel = true,
370
+ onChange = undefined,
371
+ onSelect = undefined,
372
+ className = '',
373
+ style = undefined,
374
+ 'aria-label': ariaLabel = 'Guided image gallery'
375
+ }: GuidedGalleryProps, forwardedRef) {
376
+ const containerRef = useRef<HTMLDivElement>(null);
377
+ useImperativeHandle(forwardedRef, () => containerRef.current as HTMLDivElement, []);
378
+ const settingsRef = useRef<CarouselSettings | null>(null);
379
+ const itemsRef = useRef<GuidedGalleryItem[]>(items);
380
+ const engineRef = useRef<{
381
+ wake: () => void;
382
+ setItems: (next: GuidedGalleryItem[]) => void;
383
+ goTo: (index: number) => void;
384
+ startAutoplay: () => void;
385
+ } | null>(null);
386
+ const callbacksRef = useRef<{
387
+ onChange: GuidedGalleryProps['onChange'];
388
+ onSelect: GuidedGalleryProps['onSelect'];
389
+ pause: () => void;
390
+ }>({ onChange, onSelect, pause: () => {} });
391
+ const [active, setActive] = useState(0);
392
+ const [revealed, setRevealed] = useState(false);
393
+ const [focusOpen, setFocusOpen] = useState(false);
394
+ const [webglReady, setWebglReady] = useState(false);
395
+ const [playing, setPlaying] = useState(autoplay);
396
+ const reducedMotion = useReducedMotion();
397
+
398
+ useEffect(() => {
399
+ callbacksRef.current = {
400
+ onChange,
401
+ onSelect,
402
+ pause: () => setPlaying(false)
403
+ };
404
+ }, [onChange, onSelect]);
405
+
406
+ const base = BEND_PRESETS[preset];
407
+ const pick = <K extends keyof BendPreset>(value: BendPreset[K] | undefined, key: K): BendPreset[K] => value ?? base[key];
408
+
409
+ const list = items && items.length ? items : DEFAULT_ITEMS;
410
+ const itemsKey = list.map(item => item.src).join('|');
411
+
412
+ useEffect(() => {
413
+ itemsRef.current = list;
414
+ settingsRef.current = {
415
+ intro,
416
+ cardHeight,
417
+ gap,
418
+ radius,
419
+ fit,
420
+ lensWidth: pick(lensWidth, 'lensWidth'),
421
+ lensHeight: pick(lensHeight, 'lensHeight'),
422
+ tilt: pick(tilt, 'tilt'),
423
+ roundness: pick(roundness, 'roundness'),
424
+ bend: pick(bend, 'bend'),
425
+ reach: pick(reach, 'reach'),
426
+ curl: pick(curl, 'curl'),
427
+ dispersion: pick(dispersion, 'dispersion'),
428
+ liquid: pick(liquid, 'liquid'),
429
+ followCursor: pick(followCursor, 'followCursor'),
430
+ squeeze,
431
+ focusOnClick,
432
+ autoplay: playing,
433
+ interval,
434
+ captureWheel
435
+ };
436
+ engineRef.current?.wake();
437
+ });
438
+
439
+ useEffect(() => {
440
+ engineRef.current?.setItems(itemsRef.current);
441
+ }, [itemsKey]);
442
+
443
+ useEffect(() => {
444
+ const container = containerRef.current;
445
+ if (!container) return undefined;
446
+
447
+ const renderer = new Renderer({
448
+ dpr: Math.min(window.devicePixelRatio || 1, 2),
449
+ alpha: true,
450
+ premultipliedAlpha: true,
451
+ antialias: false,
452
+ depth: false
453
+ });
454
+ const gl = renderer.gl;
455
+ if (!renderer.isWebgl2) {
456
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
457
+ return undefined;
458
+ }
459
+ gl.clearColor(0, 0, 0, 0);
460
+ const canvas = gl.canvas;
461
+ canvas.style.display = 'block';
462
+ canvas.style.width = '100%';
463
+ canvas.style.height = '100%';
464
+ canvas.style.position = 'absolute';
465
+ canvas.style.inset = '0';
466
+ canvas.style.zIndex = '1';
467
+ canvas.setAttribute('aria-hidden', 'true');
468
+ container.prepend(canvas);
469
+
470
+ const cardProgram = new Program(gl, {
471
+ vertex: cardVertex,
472
+ fragment: cardFragment,
473
+ transparent: true,
474
+ depthTest: false,
475
+ depthWrite: false,
476
+ uniforms: {
477
+ tMap: { value: new Texture(gl) },
478
+ uRect: { value: [0, 0, 1, 1] },
479
+ uResolution: { value: [1, 1] },
480
+ uSize: { value: [1, 1] },
481
+ uImage: { value: [1, 1] },
482
+ uRadius: { value: 16 },
483
+ uAlpha: { value: 1 },
484
+ uReady: { value: 0 },
485
+ uShift: { value: 0 },
486
+ uFocal: { value: [0.5, 0.5] },
487
+ uDpr: { value: 1 },
488
+ uPlaceholder: { value: [0.5, 0.5, 0.5] }
489
+ }
490
+ });
491
+ cardProgram.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
492
+ const cardMesh = new Mesh(gl, { geometry: new Plane(gl), program: cardProgram });
493
+
494
+ const target = new RenderTarget(gl, {
495
+ width: 2,
496
+ height: 2,
497
+ depth: false,
498
+ minFilter: gl.LINEAR_MIPMAP_LINEAR,
499
+ magFilter: gl.LINEAR
500
+ });
501
+
502
+ const lensUniforms = {
503
+ tScene: { value: target.texture },
504
+ uResolution: { value: [1, 1] },
505
+ uDpr: { value: 1 },
506
+ uCenter: { value: [0, 0] },
507
+ uHalf: { value: [1, 1] },
508
+ uAngle: { value: 0 },
509
+ uExponent: { value: 2 },
510
+ uInner: { value: 60 },
511
+ uOuter: { value: 80 },
512
+ uFlow: { value: 0 },
513
+ uCurl: { value: 0 },
514
+ uDispersion: { value: 0 },
515
+ uStrength: { value: 0 },
516
+ uSceneAlpha: { value: 0 }
517
+ };
518
+ const lensMesh = new Mesh(gl, {
519
+ geometry: new Triangle(gl),
520
+ program: new Program(gl, {
521
+ vertex: lensVertex,
522
+ fragment: lensFragment,
523
+ uniforms: lensUniforms,
524
+ depthTest: false,
525
+ depthWrite: false
526
+ })
527
+ });
528
+
529
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
530
+ const anisotropy = renderer.getExtension('EXT_texture_filter_anisotropic') ? 8 : 0;
531
+
532
+ let slots: CarouselSlot[] = [];
533
+ let width = 1;
534
+ let height = 1;
535
+ let pos = 0;
536
+ let vel = 0;
537
+ let goal = 0;
538
+ let mode = 'spring';
539
+ let wheelAt = 0;
540
+ let raf = 0;
541
+ let last = performance.now();
542
+ let visible = true;
543
+ let alive = true;
544
+ let didMarkWebglReady = false;
545
+ let dirty = true;
546
+ let activeIndex = -1;
547
+ let interactedAt = -Infinity;
548
+ let hasFocus = false;
549
+ let deform = 0;
550
+ let deformVel = 0;
551
+ let layout: CarouselMetrics | null = null;
552
+ let resnap = false;
553
+ let hover = '';
554
+ let lift = 1;
555
+ let energy = 0;
556
+ let lastPos = 0;
557
+ const lens = { x: 0, y: 0, vx: 0, vy: 0, ready: false };
558
+ const pointer = {
559
+ x: 0,
560
+ y: 0,
561
+ over: false,
562
+ down: false,
563
+ id: -1,
564
+ startX: 0,
565
+ startY: 0,
566
+ startPos: 0,
567
+ dragging: false,
568
+ touch: false,
569
+ samples: [] as { x: number; t: number }[]
570
+ };
571
+ const introState = { kind: 'none', t: 0, running: false, done: false, readyAt: 0 };
572
+ const focus = { index: -1, pending: -1, t: 0, v: 0, target: 0 };
573
+ let instances: { index: number; x0: number; x1: number; y0: number; y1: number }[] = [];
574
+
575
+ const loadSlot = (item: GuidedGalleryItem, index: number): CarouselSlot => {
576
+ const texture = new Texture(gl, {
577
+ generateMipmaps: true,
578
+ minFilter: gl.LINEAR_MIPMAP_LINEAR,
579
+ magFilter: gl.LINEAR,
580
+ anisotropy
581
+ });
582
+ const slot = {
583
+ item,
584
+ index,
585
+ texture,
586
+ aspect: item.aspect ?? 0.8,
587
+ loaded: false,
588
+ failed: false,
589
+ ready: 0,
590
+ color: [0.5, 0.5, 0.5],
591
+ image: [1, 1],
592
+ dispose: () => {}
593
+ };
594
+ const image = new Image();
595
+ image.crossOrigin = 'anonymous';
596
+ image.decoding = 'async';
597
+ image.onload = () => {
598
+ if (!alive || !slots.includes(slot)) return;
599
+ texture.image = image;
600
+ texture.update();
601
+ slot.image = [image.naturalWidth || 1, image.naturalHeight || 1];
602
+ slot.aspect = item.aspect ?? slot.image[0] / slot.image[1];
603
+ try {
604
+ const probe = document.createElement('canvas');
605
+ probe.width = 8;
606
+ probe.height = 8;
607
+ const ctx = probe.getContext('2d', { willReadFrequently: true });
608
+ if (ctx) {
609
+ ctx.drawImage(image, 0, 0, 8, 8);
610
+ const data = ctx.getImageData(0, 0, 8, 8).data;
611
+ const avg = [0, 0, 0];
612
+ for (let i = 0; i < data.length; i += 4) {
613
+ avg[0] += data[i];
614
+ avg[1] += data[i + 1];
615
+ avg[2] += data[i + 2];
616
+ }
617
+ slot.color = avg.map(v => v / 64 / 255);
618
+ }
619
+ } catch {
620
+ slot.color = [0.5, 0.5, 0.5];
621
+ }
622
+ slot.loaded = true;
623
+ dirty = true;
624
+ start();
625
+ };
626
+ image.onerror = () => {
627
+ if (!alive) return;
628
+ slot.failed = true;
629
+ dirty = true;
630
+ start();
631
+ };
632
+ image.src = item.src;
633
+ slot.dispose = () => {
634
+ image.onload = null;
635
+ image.onerror = null;
636
+ gl.deleteTexture(texture.texture);
637
+ };
638
+ return slot;
639
+ };
640
+
641
+ const setItems = (next: GuidedGalleryItem[]) => {
642
+ slots.forEach(slot => slot.dispose());
643
+ slots = next.map(loadSlot);
644
+ activeIndex = -1;
645
+ layout = null;
646
+ resnap = true;
647
+ focus.target = 0;
648
+ focus.t = 0;
649
+ focus.v = 0;
650
+ focus.pending = -1;
651
+ setFocusOpen(false);
652
+ introState.readyAt = performance.now();
653
+ dirty = true;
654
+ start();
655
+ };
656
+
657
+ const metrics = (s: CarouselSettings): CarouselMetrics => {
658
+ const cardH = Math.max(24, s.cardHeight * height);
659
+ const fixed = FIT_ASPECT[s.fit as GuidedGalleryFit];
660
+ const widths = slots.map(slot => (fixed || slot.aspect) * cardH);
661
+ const centers = [];
662
+ let cursor = 0;
663
+ for (let i = 0; i < widths.length; i++) {
664
+ centers.push(cursor + widths[i] / 2);
665
+ cursor += widths[i] + s.gap;
666
+ }
667
+ return { cardH, widths, centers, gap: s.gap, loop: Math.max(cursor, 1) };
668
+ };
669
+
670
+ const nearest = (m: CarouselMetrics, at: number) => {
671
+ let best = 0;
672
+ let bestDist = Infinity;
673
+ for (let i = 0; i < m.centers.length; i++) {
674
+ const dist = Math.abs(wrap(m.centers[i] - at, m.loop));
675
+ if (dist < bestDist) {
676
+ bestDist = dist;
677
+ best = i;
678
+ }
679
+ }
680
+ return best;
681
+ };
682
+
683
+ const snapPoint = (m: CarouselMetrics, at: number) => {
684
+ const i = nearest(m, at);
685
+ return at + wrap(m.centers[i] - at, m.loop);
686
+ };
687
+
688
+ const remap = (from: CarouselMetrics, to: CarouselMetrics, at: number) => {
689
+ const i = nearest(from, at);
690
+ const offset = wrap(at - from.centers[i], from.loop);
691
+ const cycles = Math.round((at - offset - from.centers[i]) / from.loop);
692
+ return cycles * to.loop + to.centers[i] + offset * (to.widths[i] / from.widths[i]);
693
+ };
694
+
695
+ const step = (m: CarouselMetrics, delta: number) => {
696
+ let at = snapPoint(m, goal);
697
+ let index = nearest(m, at);
698
+ const n = m.centers.length;
699
+ for (let k = 0; k < Math.abs(delta); k++) {
700
+ const next = (index + (delta > 0 ? 1 : n - 1)) % n;
701
+ const distance =
702
+ delta > 0
703
+ ? m.widths[index] / 2 + m.gap + m.widths[next] / 2
704
+ : -(m.widths[next] / 2 + m.gap + m.widths[index] / 2);
705
+ at += distance;
706
+ index = next;
707
+ }
708
+ goal = at;
709
+ mode = 'spring';
710
+ dirty = true;
711
+ start();
712
+ };
713
+
714
+ const goTo = (m: CarouselMetrics, index: number) => {
715
+ interactedAt = performance.now();
716
+ const i = ((index % m.centers.length) + m.centers.length) % m.centers.length;
717
+ goal = goal + wrap(m.centers[i] - goal, m.loop);
718
+ mode = 'spring';
719
+ dirty = true;
720
+ start();
721
+ };
722
+
723
+ const openFocus = (index: number) => {
724
+ focus.index = index;
725
+ focus.pending = -1;
726
+ focus.target = 1;
727
+ setFocusOpen(true);
728
+ dirty = true;
729
+ start();
730
+ };
731
+
732
+ const closeFocus = () => {
733
+ focus.pending = -1;
734
+ if (focus.target === 0) return false;
735
+ focus.target = 0;
736
+ setFocusOpen(false);
737
+ dirty = true;
738
+ start();
739
+ return true;
740
+ };
741
+
742
+ const skipIntro = () => {
743
+ if (introState.running) introState.t = 1;
744
+ };
745
+
746
+ const introEffects = () => {
747
+ const t = introState.running ? introState.t : introState.done ? 1 : 0;
748
+ const e: {
749
+ sceneAlpha: number;
750
+ strength: number;
751
+ card: ((rel: number) => { alpha: number; x: number; y: number; scale: number }) | null;
752
+ } = { sceneAlpha: 1, strength: 1, card: null };
753
+ if (!introState.done && !introState.running) {
754
+ e.sceneAlpha = 0;
755
+ e.strength = 0;
756
+ return e;
757
+ }
758
+ if (t >= 1) return e;
759
+ const kind = introState.kind;
760
+ if (kind === 'rise') {
761
+ e.strength = easeInOut((t - 0.3) / 0.65);
762
+ e.card = rel => {
763
+ const delay = Math.min(Math.abs(rel) / (width * 0.6), 1) * 0.34;
764
+ const local = clamp01((t - delay) / 0.6);
765
+ return {
766
+ alpha: clamp01(local * 4),
767
+ x: 0,
768
+ y: (1 - easeOutQuint(local)) * height * 0.62,
769
+ scale: 0.5 + 0.5 * easeInOut((local - 0.18) / 0.82)
770
+ };
771
+ };
772
+ } else if (kind === 'bloom') {
773
+ e.strength = easeInOut((t - 0.2) / 0.8);
774
+ e.card = rel => {
775
+ const delay = Math.min(Math.abs(rel) / (width * 0.6), 1) * 0.25;
776
+ const local = easeOut((t - delay) / 0.55);
777
+ return { alpha: local, x: 0, y: 0, scale: 0.92 + 0.08 * local };
778
+ };
779
+ } else if (kind === 'spin') {
780
+ e.sceneAlpha = easeOut(t / 0.25);
781
+ e.strength = easeOut((t - 0.55) / 0.45);
782
+ } else if (kind === 'deal') {
783
+ e.strength = easeOut((t - 0.45) / 0.5);
784
+ e.card = rel => {
785
+ const spread = Math.min(Math.abs(rel) / (width * 0.6), 1) * 0.3;
786
+ const local = easeOut((t - 0.12 - spread) / 0.5);
787
+ return { alpha: easeOut((t - spread) / 0.12), x: -rel * (1 - local), y: 0, scale: 1 };
788
+ };
789
+ } else {
790
+ e.sceneAlpha = easeOut(t);
791
+ e.strength = easeOut(t);
792
+ }
793
+ return e;
794
+ };
795
+
796
+ const beginIntro = (s: CarouselSettings, m: CarouselMetrics) => {
797
+ const kind = reducedMotion && s.intro !== 'none' ? 'fade' : s.intro;
798
+ introState.kind = INTRO_DURATION[kind as keyof typeof INTRO_DURATION] ? kind : 'none';
799
+ introState.running = introState.kind !== 'none';
800
+ introState.done = !introState.running;
801
+ introState.t = 0;
802
+ if (introState.done) setRevealed(true);
803
+ if (introState.kind === 'spin') {
804
+ const distance = m.loop * 1.6 + width;
805
+ pos = goal + distance;
806
+ vel = -distance * 3;
807
+ mode = 'spring';
808
+ }
809
+ };
810
+
811
+ let resizePending = false;
812
+ const applyResize = () => {
813
+ width = Math.max(1, container.clientWidth);
814
+ height = Math.max(1, container.clientHeight);
815
+ renderer.dpr = Math.min(window.devicePixelRatio || 1, 2, Math.sqrt(PIXEL_BUDGET / (width * height)));
816
+ renderer.setSize(width, height);
817
+ target.setSize(Math.max(2, Math.round(width * renderer.dpr)), Math.max(2, Math.round(height * renderer.dpr)));
818
+ lensUniforms.tScene.value = target.texture;
819
+ dirty = true;
820
+ };
821
+
822
+ const resize = () => {
823
+ resizePending = true;
824
+ start();
825
+ };
826
+
827
+ const frame = (now: number) => {
828
+ raf = 0;
829
+ if (resizePending) {
830
+ resizePending = false;
831
+ applyResize();
832
+ }
833
+ if (!alive) return;
834
+ const s = settingsRef.current;
835
+ const dt = Math.min(0.05, Math.max(0.001, (now - last) / 1000));
836
+ last = now;
837
+ if (!s || !slots.length) {
838
+ if (visible) raf = requestAnimationFrame(frame);
839
+ return;
840
+ }
841
+
842
+ const m = metrics(s);
843
+ const n = slots.length;
844
+ let animating = false;
845
+
846
+ if (resnap) {
847
+ goal = snapPoint(m, goal);
848
+ pos = goal;
849
+ vel = 0;
850
+ resnap = false;
851
+ } else if (layout && layout.loop !== m.loop) {
852
+ pos = remap(layout, m, pos);
853
+ goal = remap(layout, m, goal);
854
+ pointer.startPos = pos + (pointer.x - pointer.startX);
855
+ animating = true;
856
+ }
857
+ layout = m;
858
+
859
+ if (!introState.running && !introState.done) {
860
+ const allSettled = slots.every(slot => slot.loaded || slot.failed);
861
+ if (allSettled || now - introState.readyAt > 3500) {
862
+ goal = snapPoint(m, goal);
863
+ pos = goal;
864
+ beginIntro(s, m);
865
+ }
866
+ }
867
+ if (introState.running) {
868
+ introState.t = Math.min(1, introState.t + dt / (INTRO_DURATION[introState.kind as keyof typeof INTRO_DURATION] || 1));
869
+ if (introState.t >= 1) {
870
+ introState.running = false;
871
+ introState.done = true;
872
+ setRevealed(true);
873
+ }
874
+ animating = true;
875
+ }
876
+
877
+ if (mode === 'wheel' && now - wheelAt > 150) {
878
+ goal = snapPoint(m, goal);
879
+ mode = 'spring';
880
+ }
881
+ const hoveringCard = pointer.over && instances.some(
882
+ instance => pointer.x >= instance.x0 && pointer.x <= instance.x1 && pointer.y >= instance.y0 && pointer.y <= instance.y1
883
+ );
884
+ const autoplaying =
885
+ s.autoplay &&
886
+ !reducedMotion &&
887
+ introState.done &&
888
+ focus.target === 0 &&
889
+ focus.t < 0.01 &&
890
+ !pointer.down &&
891
+ !hasFocus &&
892
+ !hoveringCard &&
893
+ now - interactedAt > 3000;
894
+ if (autoplaying) {
895
+ mode = 'autoplay';
896
+ const speed = (m.loop / n) / Math.max(s.interval, 0.1);
897
+ vel = speed;
898
+ pos += speed * dt;
899
+ goal = pos;
900
+ animating = true;
901
+ } else if (mode === 'autoplay') {
902
+ mode = 'spring';
903
+ goal = pos;
904
+ vel = 0;
905
+ }
906
+
907
+ if (!pointer.dragging && mode !== 'autoplay') {
908
+ const spinning = introState.running && introState.kind === 'spin';
909
+ const stiffness = spinning ? 9 : mode === 'wheel' ? 80 : 55;
910
+ const damping = 2 * Math.sqrt(stiffness);
911
+ const steps = Math.ceil(dt / (1 / 240));
912
+ const h = dt / steps;
913
+ for (let i = 0; i < steps; i++) {
914
+ const acc = stiffness * (goal - pos) - damping * vel;
915
+ vel += acc * h;
916
+ pos += vel * h;
917
+ }
918
+ if (Math.abs(goal - pos) < 0.05 && Math.abs(vel) < 0.5) {
919
+ pos = goal;
920
+ vel = 0;
921
+ } else {
922
+ animating = true;
923
+ }
924
+ } else {
925
+ animating = true;
926
+ }
927
+
928
+ if (Math.abs(pos) > m.loop * 8) {
929
+ const shift = Math.round(pos / m.loop) * m.loop;
930
+ pos -= shift;
931
+ goal -= shift;
932
+ pointer.startPos -= shift;
933
+ }
934
+
935
+ const current = nearest(m, pos);
936
+ if (current !== activeIndex) {
937
+ activeIndex = current;
938
+ setActive(current);
939
+ callbacksRef.current.onChange?.(current, itemsRef.current[current]);
940
+ }
941
+
942
+ if (focus.pending >= 0 && mode === 'spring' && Math.abs(goal - pos) < 1.5 && Math.abs(vel) < 30) {
943
+ if (current === focus.pending) openFocus(current);
944
+ else focus.pending = -1;
945
+ }
946
+
947
+ const travel = Math.abs(pos - lastPos) / dt;
948
+ lastPos = pos;
949
+ const energyTarget = reducedMotion ? 0 : Math.min(travel / 2600, 1);
950
+ energy += (energyTarget - energy) * (1 - Math.exp(-dt / (energyTarget > energy ? 0.07 : 0.35)));
951
+ if (energy > 0.001) animating = true;
952
+ const liquidAmount = reducedMotion ? 0 : s.liquid;
953
+ const push = Math.max(-1, Math.min(1, vel / 2200));
954
+ const deformStiffness = 120;
955
+ const deformDamping = 2 * Math.sqrt(deformStiffness) * 0.32;
956
+ deformVel += (deformStiffness * (push - deform) - deformDamping * deformVel) * dt;
957
+ deform += deformVel * dt;
958
+ if (Math.abs(deform) > 0.0005 || Math.abs(deformVel) > 0.005) animating = true;
959
+
960
+ const focusStiffness = 64;
961
+ focus.v += (focusStiffness * (focus.target - focus.t) - 2 * Math.sqrt(focusStiffness) * focus.v) * dt;
962
+ focus.t += focus.v * dt;
963
+ if (Math.abs(focus.target - focus.t) < 0.0005 && Math.abs(focus.v) < 0.001) {
964
+ focus.t = focus.target;
965
+ focus.v = 0;
966
+ } else {
967
+ animating = true;
968
+ }
969
+ const focusAmount = clamp01(focus.t);
970
+ const focusEase = easeInOut(focusAmount);
971
+ const focusW = focus.index >= 0 && focus.index < n ? m.widths[focus.index] : m.cardH;
972
+ const focusScale = Math.max(1, Math.min(1.3, (height * 0.84) / m.cardH, (width * 0.92) / focusW));
973
+ const nextLift = 1 + (focusScale - 1) * focusEase;
974
+ if (Math.abs(nextLift - lift) > 0.0005) {
975
+ lift = nextLift;
976
+ container.style.setProperty('--guided-gallery-lift', lift.toFixed(4));
977
+ }
978
+
979
+ const effects = introEffects();
980
+
981
+ const homeX = width / 2;
982
+ const homeY = height / 2;
983
+ const follow = s.followCursor && pointer.over && !pointer.dragging && !pointer.touch && focus.target === 0;
984
+ const aimX = follow ? pointer.x : homeX;
985
+ const aimY = follow ? pointer.y : homeY;
986
+ if (!lens.ready) {
987
+ lens.x = homeX;
988
+ lens.y = homeY;
989
+ lens.ready = true;
990
+ }
991
+ const lensK = 110;
992
+ const lensC = 2 * Math.sqrt(lensK) * 0.8;
993
+ lens.vx += (lensK * (aimX - lens.x) - lensC * lens.vx) * dt;
994
+ lens.vy += (lensK * (aimY - lens.y) - lensC * lens.vy) * dt;
995
+ lens.x += lens.vx * dt;
996
+ lens.y += lens.vy * dt;
997
+ if (Math.abs(aimX - lens.x) + Math.abs(aimY - lens.y) > 0.2 || Math.abs(lens.vx) + Math.abs(lens.vy) > 0.5)
998
+ animating = true;
999
+
1000
+ const cardH = m.cardH;
1001
+ let halfW = (s.lensWidth * width) / 2;
1002
+ let halfH = (s.lensHeight * width) / 2;
1003
+ const squash = Math.abs(deform) * liquidAmount;
1004
+ halfW *= 1 + squash * 0.16;
1005
+ halfH *= 1 - squash * 0.08;
1006
+ const lensX = lens.x - deform * 14 * liquidAmount;
1007
+
1008
+ for (let i = 0; i < n; i++) {
1009
+ const slot = slots[i];
1010
+ if (slot.loaded && slot.ready < 1) {
1011
+ slot.ready = Math.min(1, slot.ready + dt / 0.45);
1012
+ animating = true;
1013
+ }
1014
+ }
1015
+
1016
+ const waiting = !introState.done;
1017
+ if (dirty || animating || pointer.dragging) {
1018
+ dirty = false;
1019
+ instances = [];
1020
+ const dpr = renderer.dpr;
1021
+ cardProgram.uniforms.uResolution.value = [width, height];
1022
+ cardProgram.uniforms.uDpr.value = dpr;
1023
+ cardProgram.uniforms.uRadius.value = s.radius;
1024
+ const shrink = 1 - clamp01(s.squeeze) * energy;
1025
+ const draws = [];
1026
+ for (let i = 0; i < n; i++) {
1027
+ const w = m.widths[i];
1028
+ const baseRel = wrap(m.centers[i] - pos, m.loop);
1029
+ for (let k = -3; k <= 3; k++) {
1030
+ const rel = baseRel + k * m.loop;
1031
+ if (Math.abs(rel) - w / 2 > width + 40) continue;
1032
+ const fx = effects.card ? effects.card(rel) : null;
1033
+ let x = homeX + rel + (fx ? fx.x : 0);
1034
+ let scale = shrink * (fx ? fx.scale : 1);
1035
+ let alpha = fx ? fx.alpha : 1;
1036
+ if (focusAmount > 0) {
1037
+ if (i === focus.index && Math.abs(rel) < w) {
1038
+ scale *= 1 + (focusScale - 1) * focusEase;
1039
+ } else {
1040
+ const order = Math.min(Math.abs(rel) / width, 1) * 0.25;
1041
+ const part = easeInOut(focusAmount * 1.25 - order);
1042
+ x += Math.sign(rel) * part * width * 0.7;
1043
+ alpha *= 1 - part;
1044
+ }
1045
+ }
1046
+ const cw = w * scale;
1047
+ if (alpha <= 0.001 || x + cw / 2 < -40 || x - cw / 2 > width + 40) continue;
1048
+ draws.push({ i, rel, x, y: homeY + (fx ? fx.y : 0), cw, ch: cardH * scale, alpha });
1049
+ }
1050
+ }
1051
+ draws.sort((a, b) => Math.abs(b.rel) - Math.abs(a.rel));
1052
+ let first = true;
1053
+ for (const draw of draws) {
1054
+ const slot = slots[draw.i];
1055
+ cardProgram.uniforms.tMap.value = slot.texture;
1056
+ cardProgram.uniforms.uRect.value = [draw.x, draw.y, draw.cw + 2, draw.ch + 2];
1057
+ cardProgram.uniforms.uSize.value = [draw.cw, draw.ch];
1058
+ cardProgram.uniforms.uImage.value = slot.image;
1059
+ cardProgram.uniforms.uAlpha.value = draw.alpha;
1060
+ cardProgram.uniforms.uReady.value = slot.ready;
1061
+ const focalPoint = slot.item.focalPoint;
1062
+ cardProgram.uniforms.uFocal.value = [
1063
+ clamp01(focalPoint?.x ?? 0.5),
1064
+ clamp01(focalPoint?.y ?? 0.5)
1065
+ ];
1066
+ cardProgram.uniforms.uShift.value = reducedMotion || focalPoint ? 0 : Math.max(-1, Math.min(1, draw.rel / (width * 0.75)));
1067
+ cardProgram.uniforms.uPlaceholder.value = slot.color;
1068
+ renderer.render({ scene: cardMesh, target, clear: first });
1069
+ first = false;
1070
+ instances.push({
1071
+ index: draw.i,
1072
+ x0: draw.x - draw.cw / 2,
1073
+ x1: draw.x + draw.cw / 2,
1074
+ y0: draw.y - draw.ch / 2,
1075
+ y1: draw.y + draw.ch / 2
1076
+ });
1077
+ }
1078
+ if (first) {
1079
+ renderer.bindFramebuffer(target);
1080
+ gl.viewport(0, 0, target.width, target.height);
1081
+ gl.clear(gl.COLOR_BUFFER_BIT);
1082
+ }
1083
+ renderer.bindFramebuffer();
1084
+ target.texture.bind();
1085
+ gl.generateMipmap(gl.TEXTURE_2D);
1086
+
1087
+ lensUniforms.uResolution.value = [width, height];
1088
+ lensUniforms.uDpr.value = dpr;
1089
+ lensUniforms.uCenter.value = [lensX, lens.y];
1090
+ lensUniforms.uHalf.value = [Math.max(halfW, 1), Math.max(halfH, 1)];
1091
+ lensUniforms.uAngle.value = (s.tilt * Math.PI) / 180;
1092
+ lensUniforms.uExponent.value = 2 + Math.pow(1 - clamp01(s.roundness), 1.5) * 10;
1093
+ const spanW = Math.max(halfW, 1);
1094
+ const spanH = Math.max(halfH, 1);
1095
+ const inner = Math.max(4, s.reach * (spanW + spanH) * 0.5);
1096
+ lensUniforms.uInner.value = inner;
1097
+ lensUniforms.uOuter.value = inner * 1.6;
1098
+ lensUniforms.uFlow.value = s.bend * (spanW + spanH) * 0.45;
1099
+ lensUniforms.uCurl.value = s.curl === 'rise' ? 1 : s.curl === 'fall' ? -1 : 0;
1100
+ lensUniforms.uDispersion.value = s.dispersion * 0.12 * (1 + Math.abs(deform) * liquidAmount * 1.2);
1101
+ lensUniforms.uStrength.value = effects.strength * (1 - focusEase);
1102
+ lensUniforms.uSceneAlpha.value = effects.sceneAlpha;
1103
+ renderer.render({ scene: lensMesh });
1104
+ if (
1105
+ !didMarkWebglReady &&
1106
+ slots.length > 0 &&
1107
+ slots.every(slot => slot.loaded || slot.failed) &&
1108
+ gl.getError() === gl.NO_ERROR
1109
+ ) {
1110
+ didMarkWebglReady = true;
1111
+ setWebglReady(true);
1112
+ }
1113
+ }
1114
+
1115
+ let nextHover = '';
1116
+ if (pointer.over && !pointer.dragging && introState.done && s.focusOnClick) {
1117
+ const hit = instances.find(
1118
+ inst => pointer.x >= inst.x0 && pointer.x <= inst.x1 && pointer.y >= inst.y0 && pointer.y <= inst.y1
1119
+ );
1120
+ if (focus.target > 0) nextHover = 'close';
1121
+ else if (hit) nextHover = 'open';
1122
+ }
1123
+ if (nextHover !== hover) {
1124
+ hover = nextHover;
1125
+ if (hover) container.setAttribute('data-hover', hover);
1126
+ else container.removeAttribute('data-hover');
1127
+ }
1128
+
1129
+ if (visible && (animating || waiting || dirty || pointer.down)) raf = requestAnimationFrame(frame);
1130
+ };
1131
+
1132
+ const start = () => {
1133
+ if (raf || !visible || !alive) return;
1134
+ last = performance.now();
1135
+ raf = requestAnimationFrame(frame);
1136
+ };
1137
+
1138
+ const localPoint = (e: PointerEvent) => {
1139
+ const rect = container.getBoundingClientRect();
1140
+ return [e.clientX - rect.left, e.clientY - rect.top];
1141
+ };
1142
+
1143
+ const onPointerDown = (e: PointerEvent) => {
1144
+ if (e.button !== undefined && e.button > 0) return;
1145
+ skipIntro();
1146
+ const [x, y] = localPoint(e);
1147
+ pointer.down = true;
1148
+ pointer.id = e.pointerId;
1149
+ pointer.touch = e.pointerType === 'touch';
1150
+ pointer.startX = x;
1151
+ pointer.startY = y;
1152
+ pointer.x = x;
1153
+ pointer.y = y;
1154
+ pointer.startPos = pos;
1155
+ pointer.dragging = false;
1156
+ pointer.samples = [{ x, t: performance.now() }];
1157
+ interactedAt = performance.now();
1158
+ if (Math.abs(vel) > 40) {
1159
+ goal = pos;
1160
+ vel = 0;
1161
+ }
1162
+ dirty = true;
1163
+ start();
1164
+ };
1165
+
1166
+ const onPointerMove = (e: PointerEvent) => {
1167
+ const [x, y] = localPoint(e);
1168
+ pointer.x = x;
1169
+ pointer.y = y;
1170
+ pointer.over = true;
1171
+ if (pointer.down && e.pointerId === pointer.id) {
1172
+ const dx = x - pointer.startX;
1173
+ const dy = y - pointer.startY;
1174
+ const slop = pointer.touch ? 10 : 5;
1175
+ if (!pointer.dragging) {
1176
+ if (pointer.touch && Math.abs(dy) > slop && Math.abs(dy) > Math.abs(dx)) {
1177
+ pointer.down = false;
1178
+ return;
1179
+ }
1180
+ if (Math.abs(dx) > slop) {
1181
+ pointer.dragging = true;
1182
+ pointer.startX = x;
1183
+ pointer.startPos = pos;
1184
+ closeFocus();
1185
+ try {
1186
+ container.setPointerCapture(e.pointerId);
1187
+ } catch {
1188
+ pointer.dragging = true;
1189
+ }
1190
+ container.setAttribute('data-dragging', '');
1191
+ }
1192
+ }
1193
+ if (pointer.dragging) {
1194
+ pos = pointer.startPos - (x - pointer.startX);
1195
+ goal = pos;
1196
+ vel = 0;
1197
+ const now = performance.now();
1198
+ pointer.samples.push({ x, t: now });
1199
+ while (pointer.samples.length > 2 && now - pointer.samples[0].t > 100) pointer.samples.shift();
1200
+ }
1201
+ }
1202
+ dirty = true;
1203
+ start();
1204
+ };
1205
+
1206
+ const onPointerUp = (e: PointerEvent) => {
1207
+ if (!pointer.down || e.pointerId !== pointer.id) return;
1208
+ pointer.down = false;
1209
+ container.removeAttribute('data-dragging');
1210
+ const s = settingsRef.current;
1211
+ if (!s) return;
1212
+ const m = metrics(s);
1213
+ interactedAt = performance.now();
1214
+ if (pointer.dragging) {
1215
+ pointer.dragging = false;
1216
+ const now = performance.now();
1217
+ const first = pointer.samples[0];
1218
+ const lastSample = pointer.samples[pointer.samples.length - 1];
1219
+ let velocity = 0;
1220
+ if (first && lastSample && lastSample.t > first.t && now - lastSample.t < 70) {
1221
+ velocity = -((lastSample.x - first.x) / (lastSample.t - first.t)) * 1000;
1222
+ }
1223
+ vel = velocity;
1224
+ const landing = snapPoint(m, pos + velocity * 0.32);
1225
+ goal = landing;
1226
+ if (Math.abs(velocity) > 400 && Math.abs(landing - pos) < 1) step(m, velocity > 0 ? 1 : -1);
1227
+ mode = 'spring';
1228
+ start();
1229
+ return;
1230
+ }
1231
+ if (closeFocus()) return;
1232
+ const [x, y] = localPoint(e);
1233
+ const hit = instances.find(inst => x >= inst.x0 && x <= inst.x1 && y >= inst.y0 && y <= inst.y1);
1234
+ if (!hit) return;
1235
+ callbacksRef.current.pause();
1236
+ if (hit.index === activeIndex && Math.abs(goal - pos) < 2) {
1237
+ callbacksRef.current.onSelect?.(hit.index, itemsRef.current[hit.index]);
1238
+ if (s.focusOnClick) openFocus(hit.index);
1239
+ } else {
1240
+ const rel = (hit.x0 + hit.x1) / 2 - width / 2;
1241
+ goal = snapPoint(m, pos + rel);
1242
+ mode = 'spring';
1243
+ if (s.focusOnClick) focus.pending = hit.index;
1244
+ start();
1245
+ }
1246
+ };
1247
+
1248
+ const onPointerLeave = () => {
1249
+ pointer.over = false;
1250
+ dirty = true;
1251
+ start();
1252
+ };
1253
+
1254
+ const onPointerCancel = () => {
1255
+ pointer.down = false;
1256
+ pointer.dragging = false;
1257
+ container.removeAttribute('data-dragging');
1258
+ const s = settingsRef.current;
1259
+ if (!s) return;
1260
+ goal = snapPoint(metrics(s), pos);
1261
+ mode = 'spring';
1262
+ start();
1263
+ };
1264
+
1265
+ const onWheel = (e: WheelEvent) => {
1266
+ const s = settingsRef.current;
1267
+ if (!s || e.ctrlKey) return;
1268
+ let dx = e.deltaX;
1269
+ let dy = e.deltaY;
1270
+ if (e.shiftKey && Math.abs(dx) < Math.abs(dy)) {
1271
+ dx = dy;
1272
+ dy = 0;
1273
+ }
1274
+ const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? height : 1;
1275
+ const horizontal = Math.abs(dx) > Math.abs(dy);
1276
+ if (!horizontal && !s.captureWheel) return;
1277
+ e.preventDefault();
1278
+ skipIntro();
1279
+ interactedAt = performance.now();
1280
+ if (closeFocus()) return;
1281
+ const delta = Math.max(-120, Math.min(120, (horizontal ? dx : dy) * unit));
1282
+ goal += delta * 1.25;
1283
+ mode = 'wheel';
1284
+ wheelAt = performance.now();
1285
+ start();
1286
+ };
1287
+
1288
+ const onKeyDown = (e: KeyboardEvent) => {
1289
+ const s = settingsRef.current;
1290
+ if (!s) return;
1291
+ const m = metrics(s);
1292
+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
1293
+ e.preventDefault();
1294
+ skipIntro();
1295
+ closeFocus();
1296
+ interactedAt = performance.now();
1297
+ step(m, 1);
1298
+ } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
1299
+ e.preventDefault();
1300
+ skipIntro();
1301
+ closeFocus();
1302
+ interactedAt = performance.now();
1303
+ step(m, -1);
1304
+ } else if (e.key === 'Home') {
1305
+ e.preventDefault();
1306
+ closeFocus();
1307
+ goTo(m, 0);
1308
+ } else if (e.key === 'End') {
1309
+ e.preventDefault();
1310
+ closeFocus();
1311
+ goTo(m, slots.length - 1);
1312
+ } else if (e.key === 'Escape') {
1313
+ if (closeFocus()) e.preventDefault();
1314
+ } else if (e.key === 'Enter' || e.key === ' ') {
1315
+ e.preventDefault();
1316
+ if (closeFocus() || activeIndex < 0) return;
1317
+ callbacksRef.current.onSelect?.(activeIndex, itemsRef.current[activeIndex]);
1318
+ if (s.focusOnClick) openFocus(activeIndex);
1319
+ }
1320
+ };
1321
+
1322
+ const onFocus = () => {
1323
+ hasFocus = true;
1324
+ };
1325
+ const onBlur = () => {
1326
+ hasFocus = false;
1327
+ };
1328
+ const onVisibility = () => {
1329
+ if (!document.hidden) start();
1330
+ };
1331
+
1332
+ container.addEventListener('pointerdown', onPointerDown);
1333
+ container.addEventListener('pointermove', onPointerMove);
1334
+ container.addEventListener('pointerup', onPointerUp);
1335
+ container.addEventListener('pointerleave', onPointerLeave);
1336
+ container.addEventListener('pointercancel', onPointerCancel);
1337
+ container.addEventListener('wheel', onWheel, { passive: false });
1338
+ container.addEventListener('keydown', onKeyDown);
1339
+ container.addEventListener('focus', onFocus);
1340
+ container.addEventListener('blur', onBlur);
1341
+ document.addEventListener('visibilitychange', onVisibility);
1342
+
1343
+ const resizeObserver = new ResizeObserver(resize);
1344
+ resizeObserver.observe(container);
1345
+ const intersectionObserver = new IntersectionObserver(([entry]) => {
1346
+ visible = entry.isIntersecting;
1347
+ start();
1348
+ });
1349
+ intersectionObserver.observe(container);
1350
+
1351
+ engineRef.current = {
1352
+ wake: () => {
1353
+ dirty = true;
1354
+ start();
1355
+ },
1356
+ setItems,
1357
+ goTo: index => {
1358
+ const settings = settingsRef.current;
1359
+ if (!settings) return;
1360
+ goTo(metrics(settings), index);
1361
+ },
1362
+ startAutoplay: () => {
1363
+ interactedAt = -Infinity;
1364
+ dirty = true;
1365
+ start();
1366
+ }
1367
+ };
1368
+
1369
+ resize();
1370
+ setItems(itemsRef.current);
1371
+
1372
+ return () => {
1373
+ alive = false;
1374
+ visible = false;
1375
+ engineRef.current = null;
1376
+ cancelAnimationFrame(raf);
1377
+ resizeObserver.disconnect();
1378
+ intersectionObserver.disconnect();
1379
+ container.removeEventListener('pointerdown', onPointerDown);
1380
+ container.removeEventListener('pointermove', onPointerMove);
1381
+ container.removeEventListener('pointerup', onPointerUp);
1382
+ container.removeEventListener('pointerleave', onPointerLeave);
1383
+ container.removeEventListener('pointercancel', onPointerCancel);
1384
+ container.removeEventListener('wheel', onWheel);
1385
+ container.removeEventListener('keydown', onKeyDown);
1386
+ container.removeEventListener('focus', onFocus);
1387
+ container.removeEventListener('blur', onBlur);
1388
+ document.removeEventListener('visibilitychange', onVisibility);
1389
+ slots.forEach(slot => slot.dispose());
1390
+ slots = [];
1391
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
1392
+ if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
1393
+ };
1394
+ }, []);
1395
+
1396
+ const current = list[active] || list[0];
1397
+ const label = current ? current.title || current.alt || `Image ${active + 1}` : '';
1398
+ const togglePlayback = () => {
1399
+ const nextPlaying = !playing;
1400
+ setPlaying(nextPlaying);
1401
+ if (nextPlaying) engineRef.current?.startAutoplay();
1402
+ };
1403
+ return (
1404
+ <div
1405
+ ref={containerRef}
1406
+ className={cn(
1407
+ 'relative h-full w-full cursor-grab touch-pan-y select-none overflow-hidden overscroll-contain outline-none [-webkit-tap-highlight-color:transparent] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-muted-foreground/50 data-[hover=open]:cursor-zoom-in data-[hover=close]:cursor-zoom-out data-[dragging]:cursor-grabbing',
1408
+ className
1409
+ )}
1410
+ style={{ ...style, '--guided-gallery-half': `${Math.min(Math.max(cardHeight, 0.05), 1) * 50}%` } as CSSProperties}
1411
+ role="region"
1412
+ aria-roledescription="carousel"
1413
+ aria-label={ariaLabel}
1414
+ tabIndex={0}
1415
+ >
1416
+ <div
1417
+ className={cn(
1418
+ 'pointer-events-none absolute inset-0 z-0 flex items-center justify-center gap-3 overflow-hidden transition-opacity duration-500 motion-reduce:transition-none',
1419
+ webglReady && 'opacity-0'
1420
+ )}
1421
+ aria-hidden="true"
1422
+ >
1423
+ {list.map((item, index) => (
1424
+ <div
1425
+ key={`${item.src}-${index}`}
1426
+ className="relative max-w-none shrink-0 overflow-hidden rounded-xl border border-border/50 shadow-lg"
1427
+ style={{
1428
+ height: `${Math.min(Math.max(cardHeight, 0.05), 1) * 100}%`,
1429
+ aspectRatio: item.aspect ? String(item.aspect) : '4 / 3',
1430
+ }}
1431
+ >
1432
+ <NextImage src={item.src} alt="" fill sizes="(max-width: 768px) 55vw, 24vw" unoptimized className="object-cover" />
1433
+ </div>
1434
+ ))}
1435
+ </div>
1436
+ <button
1437
+ type="button"
1438
+ className="absolute right-4 top-4 z-20 grid size-10 cursor-pointer place-items-center rounded-full border border-border bg-surface/85 text-foreground shadow-sm backdrop-blur-sm transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground/70"
1439
+ aria-label={playing ? 'Pause gallery' : 'Play gallery'}
1440
+ aria-pressed={playing}
1441
+ onClick={event => {
1442
+ event.stopPropagation();
1443
+ togglePlayback();
1444
+ }}
1445
+ onPointerDown={event => event.stopPropagation()}
1446
+ onKeyDown={event => event.stopPropagation()}
1447
+ >
1448
+ <svg aria-hidden="true" viewBox="0 0 24 24" className="size-4 fill-current">
1449
+ <motion.path
1450
+ initial={false}
1451
+ d={playing ? PAUSE_ICON_PATH : PLAY_ICON_PATH}
1452
+ animate={{ d: playing ? PAUSE_ICON_PATH : PLAY_ICON_PATH }}
1453
+ transition={{ duration: 0.32, ease: [0.22, 1, 0.36, 1] }}
1454
+ />
1455
+ </svg>
1456
+ </button>
1457
+ {captions && current && revealed && (
1458
+ <motion.div
1459
+ className="pointer-events-none absolute inset-x-0 top-[calc(50%_+_var(--guided-gallery-half)_*_var(--guided-gallery-lift,1)_+_22px)] z-10 flex flex-col items-center gap-1.5 px-4 text-center"
1460
+ initial={reducedMotion ? false : { opacity: 0 }}
1461
+ animate={{ opacity: 1 }}
1462
+ transition={{ duration: reducedMotion ? 0 : 0.9, ease: 'easeOut' }}
1463
+ aria-hidden="true"
1464
+ >
1465
+ <motion.div
1466
+ className="flex max-w-full flex-col items-center text-[15px] leading-[1.35] font-medium"
1467
+ initial={reducedMotion ? false : { opacity: 0, y: 8 }}
1468
+ animate={{ opacity: 1, y: 0 }}
1469
+ transition={{ duration: reducedMotion ? 0 : 0.52, ease: [0.22, 1, 0.36, 1] }}
1470
+ >
1471
+ <TextMorph as="span" duration={650} ease="cubic-bezier(0.22, 1, 0.36, 1)" className="inline-block">
1472
+ {current.title || current.alt}
1473
+ </TextMorph>
1474
+ {current.subtitle && (
1475
+ <TextMorph as="span" duration={650} ease="cubic-bezier(0.22, 1, 0.36, 1)" className="inline-block font-normal opacity-60">
1476
+ {current.subtitle}
1477
+ </TextMorph>
1478
+ )}
1479
+ {current.note && (
1480
+ <TextMorph as="span" duration={650} ease="cubic-bezier(0.22, 1, 0.36, 1)" className="mt-1 inline-block max-w-md text-xs leading-5 text-muted-foreground">
1481
+ {current.note}
1482
+ </TextMorph>
1483
+ )}
1484
+ </motion.div>
1485
+ <span className={cn('inline-flex items-center gap-[3px] text-xs leading-none opacity-50 tabular-nums transition-opacity duration-400', focusOpen && 'opacity-0')}>
1486
+ <TextMorph as="span" duration={650} ease="cubic-bezier(0.22, 1, 0.36, 1)" className="inline-block">
1487
+ {String(active + 1).padStart(2, '0')}
1488
+ </TextMorph>
1489
+ <span className="opacity-60">/</span>
1490
+ <TextMorph as="span" duration={650} ease="cubic-bezier(0.22, 1, 0.36, 1)" className="inline-block">
1491
+ {String(list.length).padStart(2, '0')}
1492
+ </TextMorph>
1493
+ </span>
1494
+ </motion.div>
1495
+ )}
1496
+ <div className="absolute m-[-1px] h-px w-px overflow-hidden whitespace-nowrap [clip:rect(0,0,0,0)]" aria-live="polite" aria-atomic="true">
1497
+ {`${label}, ${active + 1} of ${list.length}`}
1498
+ </div>
1499
+ </div>
1500
+ );
1501
+ });
1502
+
1503
+ GuidedGallery.displayName = 'GuidedGallery';
1504
+
1505
+ export default GuidedGallery;
1506
+