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