@jsb188/gfx 1.1.2

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 (65) hide show
  1. package/README.md +522 -0
  2. package/elements/Shapes.helpers.ts +204 -0
  3. package/elements/Shapes.hooks.ts +171 -0
  4. package/elements/Shapes.tsx +505 -0
  5. package/elements/Shapes.types.ts +81 -0
  6. package/elements/Stack.helpers.ts +42 -0
  7. package/elements/Stack.tsx +143 -0
  8. package/elements/Text.helpers.ts +45 -0
  9. package/elements/Text.hooks.ts +197 -0
  10. package/elements/Text.tsx +98 -0
  11. package/libs/chain.ts +174 -0
  12. package/libs/dotGrid.helpers.ts +53 -0
  13. package/libs/dotGrid.ts +954 -0
  14. package/libs/effects/dotEffects.ts +136 -0
  15. package/libs/effects/effectQuad.ts +146 -0
  16. package/libs/effects/effectRegion.ts +299 -0
  17. package/libs/effects/imageEffects.ts +599 -0
  18. package/libs/effects/index.ts +8 -0
  19. package/libs/effects/ripple.ts +160 -0
  20. package/libs/glsl.ts +134 -0
  21. package/libs/passes.ts +374 -0
  22. package/libs/pointer.ts +151 -0
  23. package/libs/runtime.ts +329 -0
  24. package/libs/texture.ts +160 -0
  25. package/libs/types.ts +94 -0
  26. package/libs/uniforms.ts +32 -0
  27. package/main.ts +4 -0
  28. package/modules/Carousel.helpers.ts +316 -0
  29. package/modules/Carousel.hooks.ts +520 -0
  30. package/modules/Carousel.tsx +631 -0
  31. package/modules/Dots.tsx +269 -0
  32. package/modules/DotsBoard.helpers.ts +388 -0
  33. package/modules/DotsBoard.hooks.ts +144 -0
  34. package/modules/DotsBoard.strings.ts +649 -0
  35. package/modules/DotsBoard.types.ts +240 -0
  36. package/modules/DotsBoardCanvas.hooks.ts +49 -0
  37. package/modules/DotsBoardCanvas.tsx +190 -0
  38. package/modules/DotsBoardElements.tsx +330 -0
  39. package/modules/Gallery.helpers.ts +32 -0
  40. package/modules/Gallery.hooks.ts +149 -0
  41. package/modules/Gallery.tsx +194 -0
  42. package/modules/GfxCanvas.hooks.ts +12 -0
  43. package/modules/GfxCanvas.tsx +189 -0
  44. package/modules/Hero.tsx +90 -0
  45. package/modules/KineticHeader.helpers.ts +44 -0
  46. package/modules/KineticHeader.hooks.ts +206 -0
  47. package/modules/KineticHeader.tsx +305 -0
  48. package/modules/KineticHeader.types.ts +56 -0
  49. package/modules/ScrollSteps.hooks.ts +138 -0
  50. package/modules/ScrollSteps.tsx +98 -0
  51. package/package.json +52 -0
  52. package/scenes/Carousel.ts +277 -0
  53. package/scenes/DotsBoard.helpers.ts +12 -0
  54. package/scenes/DotsBoard.ts +245 -0
  55. package/scenes/Hero.ts +280 -0
  56. package/tsconfig.json +13 -0
  57. package/utils/align.ts +18 -0
  58. package/utils/color.ts +112 -0
  59. package/utils/dotEffectSpecs.ts +79 -0
  60. package/utils/dotGridSpecs.ts +469 -0
  61. package/utils/easing.ts +18 -0
  62. package/utils/imageEffectSpecs.ts +89 -0
  63. package/utils/motion.ts +88 -0
  64. package/utils/random.ts +22 -0
  65. package/utils/strings.ts +116 -0
@@ -0,0 +1,631 @@
1
+ import { cn } from '@jsb188/app/utils/string.ts';
2
+ import { Icon } from '@jsb188/react-web/svgs/Icon';
3
+ import { Children, isValidElement, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
+ import type { CSSProperties, KeyboardEvent, ReactNode } from 'react';
5
+ import type { CarouselSceneParams } from '../scenes/Carousel.ts';
6
+ import { normalizeImageEffectSpecs } from '../utils/imageEffectSpecs.ts';
7
+ import type { ImageEffectName, ImageEffectSpec } from '../utils/imageEffectSpecs.ts';
8
+ import { getItemIndex, getVirtualLeft, getVirtualPositions, playVideo, whenVideosPlaying } from './Carousel.helpers.ts';
9
+ import type { BlocksAlign } from './Carousel.helpers.ts';
10
+ import { useBlocksCarousel } from './Carousel.hooks.ts';
11
+ import { GfxCanvas } from './GfxCanvas.tsx';
12
+ import { useContentMemo } from './GfxCanvas.hooks.ts';
13
+
14
+ /**
15
+ * Types
16
+ */
17
+
18
+ export interface VideoCarouselItem {
19
+ videoUrl: string;
20
+ /** Shown until the video has a frame, and in place of the video when it cannot play. */
21
+ posterUrl?: string;
22
+ /** Display size of the video in CSS pixels; each item may differ (the track is as tall as the tallest, and every video is top-aligned in it). */
23
+ width: number;
24
+ height: number;
25
+ /** Already translated; shown above the video only while this item is focused. */
26
+ title: string;
27
+ description?: string;
28
+ iconName?: string;
29
+ }
30
+
31
+ /** An effect name with its defaults, or a spec with options: `{ name: 'pixelate', size: 0.05 }`. */
32
+ export type VideoCarouselEffect = ImageEffectName | ImageEffectSpec;
33
+
34
+ /** Registers a slide's <video> for the scene; returns the cleanup React runs when the element goes away. */
35
+ type RegisterVideo = (key: string, video: HTMLVideoElement | null) => (() => void) | undefined;
36
+
37
+ /** A caption on screen: the one entering for the focused slide, or one leaving after focus moved on. */
38
+ interface CarouselCaptionState {
39
+ /** Virtual slide position the caption belongs to; also its React key. */
40
+ position: number;
41
+ phase: 'in' | 'out';
42
+ /** 1 when the track moved forward (slides travelling left), -1 when it moved back. */
43
+ direction: 1 | -1;
44
+ }
45
+
46
+ /**
47
+ * Constants
48
+ */
49
+
50
+ const CAROUSEL = {
51
+ easing: 'cubic-bezier(0.22, 1, 0.36, 1)',
52
+ // Matches the wrapper's canvas fade-in, so the plain videos cross-fade into the drawn ones.
53
+ crossFadeMs: 600,
54
+ // Fade-in of the whole carousel once `delayMs` has passed and its videos are playing.
55
+ revealMs: 1000,
56
+ // Longest the reveal waits for the videos to start before showing them regardless.
57
+ revealTimeoutMs: 3000,
58
+ // How far the caption slides while fading out and in, in CSS pixels, along the track's direction.
59
+ captionShiftPx: 100,
60
+ };
61
+
62
+ /*
63
+ * Load OGL and the scene only when the carousel mounts, never with the route bundle.
64
+ */
65
+ const loadCarouselScene = () => import('../scenes/Carousel.ts');
66
+
67
+ /*
68
+ * The icon, title, and description of one slide, laid over the fixed text area above the track.
69
+ * It never moves with the videos: on mount it fades in while sliding into place from the side
70
+ * the track is coming from, and once `phase` turns to `out` it fades away while sliding on in
71
+ * the track's direction. The motion is a Web Animation, so no stylesheet is needed; where the
72
+ * API is missing (server, old browsers) the caption simply appears and disappears.
73
+ */
74
+ const CarouselCaption = memo(
75
+ (p: { item: VideoCarouselItem; phase: 'in' | 'out'; direction: 1 | -1; width: number; durationMs: number }) => {
76
+ const { item, phase, direction, width, durationMs } = p;
77
+ const ref = useRef<HTMLDivElement>(null);
78
+
79
+ useEffect(() => {
80
+ const el = ref.current;
81
+ if (!el || typeof el.animate !== 'function') return;
82
+ // Forward motion (direction 1) carries everything leftwards: the leaving caption exits to the left and the next one enters from the right.
83
+ const shift = CAROUSEL.captionShiftPx * direction;
84
+ const frames =
85
+ phase === 'in'
86
+ ? [
87
+ { opacity: 0, transform: `translateX(${shift}px)` },
88
+ { opacity: 1, transform: 'translateX(0)' },
89
+ ]
90
+ : // A single keyframe starts from wherever the entrance left the caption, so an interrupted entrance never jumps.
91
+ [{ opacity: 0, transform: `translateX(${-shift}px)` }];
92
+ const animation = el.animate(frames, { duration: durationMs, easing: CAROUSEL.easing, fill: 'both' });
93
+ return () => {
94
+ // Keep the current opacity and offset as inline style, so the next animation continues from them.
95
+ try {
96
+ animation.commitStyles();
97
+ } catch {}
98
+ animation.cancel();
99
+ };
100
+ }, [phase, direction, durationMs]);
101
+
102
+ return (
103
+ <div
104
+ ref={ref}
105
+ className="abs_tl w_f h_f h_center"
106
+ aria-hidden={phase === 'out'}
107
+ >
108
+ <div
109
+ className="v_bottom a_c pb_md h_f max_w_350"
110
+ style={{ width }}
111
+ >
112
+ <div className="ft_medium h_center ft_md">
113
+ {item.title}
114
+ </div>
115
+ {item.description && <div className="op_70 mt_4 gap_xs h_center">
116
+ {item.iconName && <span className='shift_up'><Icon name={item.iconName} /></span>}
117
+ {item.description}
118
+ </div>}
119
+ </div>
120
+ </div>
121
+ );
122
+ },
123
+ );
124
+
125
+ /*
126
+ * One slide on the track: just the video, in its own backdrop. Memoized so the <video> ref
127
+ * callback keeps its identity and the element is registered once, instead of being
128
+ * unregistered and re-registered on every carousel render.
129
+ */
130
+ const CarouselSlide = memo(
131
+ (p: {
132
+ slideKey: string;
133
+ /** Virtual position on the endless track; what `onSelect` receives. */
134
+ position: number;
135
+ item: VideoCarouselItem;
136
+ focused: boolean;
137
+ /** Whether a click or Enter/Space brings this slide to the center (unfocused, and the carousel not held). */
138
+ interactive: boolean;
139
+ left: number;
140
+ width: number;
141
+ borderRadius: number;
142
+ /** CSS transition timing for the slide's movement; undefined until the layout has been measured. */
143
+ transition?: string;
144
+ /** Opacity of the plain <video>: 0 once the canvas draws it, else full or `unfocusedOpacity`. */
145
+ videoOpacity: number;
146
+ videoTransition: string;
147
+ autoPlay: boolean;
148
+ onSelect: (position: number) => void;
149
+ registerVideo: RegisterVideo;
150
+ }) => {
151
+ const {
152
+ slideKey,
153
+ position,
154
+ item,
155
+ focused,
156
+ interactive,
157
+ left,
158
+ width,
159
+ borderRadius,
160
+ transition,
161
+ videoOpacity,
162
+ videoTransition,
163
+ autoPlay,
164
+ onSelect,
165
+ registerVideo,
166
+ } = p;
167
+ const videoRef = useCallback((video: HTMLVideoElement | null) => registerVideo(slideKey, video), [registerVideo, slideKey]);
168
+
169
+ /*
170
+ * Focus the slide from the keyboard the way a button would.
171
+ */
172
+ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
173
+ if (e.key !== 'Enter' && e.key !== ' ') return;
174
+ e.preventDefault();
175
+ onSelect(position);
176
+ };
177
+
178
+ return (
179
+ <div
180
+ // Only an unfocused slide of a running carousel is a control; the focused slide and a held carousel are inert.
181
+ {...(interactive
182
+ ? {
183
+ className: 'abs_tl h_f v_top pointer',
184
+ role: 'button',
185
+ tabIndex: 0,
186
+ 'aria-label': item.title,
187
+ onClick: () => onSelect(position),
188
+ onKeyDown,
189
+ }
190
+ : { className: 'abs_tl h_f v_top' })}
191
+ style={{ left, width, transition: transition && `left ${transition}, width ${transition}` }}
192
+ >
193
+ {/* Top-aligned, so videos of different heights line up along the track's top edge. */}
194
+ <div className="v_top w_f">
195
+ {/* The video's own backdrop: a dimmed video fades toward it instead of revealing the page; the scene reads this background for the drawn copy. */}
196
+ <div
197
+ className="bg_fade of max_w_f"
198
+ style={{ width: item.width, borderRadius }}
199
+ >
200
+ <video
201
+ ref={videoRef}
202
+ src={item.videoUrl}
203
+ poster={item.posterUrl}
204
+ className="bl w_f img_cover noclick unsel"
205
+ autoPlay={autoPlay}
206
+ muted
207
+ loop
208
+ playsInline
209
+ disablePictureInPicture
210
+ controlsList="nodownload"
211
+ preload="auto"
212
+ // Same CORS mode the texture upload needs; harmless for same-origin files.
213
+ crossOrigin="anonymous"
214
+ aria-hidden={!focused}
215
+ // Plain fallback look until the canvas takes over (and again if WebGL fails).
216
+ style={{ aspectRatio: `${item.width} / ${item.height}`, opacity: videoOpacity, transition: videoTransition }}
217
+ />
218
+ </div>
219
+ </div>
220
+ </div>
221
+ );
222
+ },
223
+ );
224
+
225
+ /*
226
+ * Horizontal carousel of videos laid out edge to edge across the full width of its container;
227
+ * whatever falls past the left or right edge is clipped (never widening the page). Every slide
228
+ * is its video at its own size, top-aligned on the track, with `gap` between; the focused one sits
229
+ * centered and plain, and every other one is dimmed to `unfocusedOpacity` over a `bg_active`
230
+ * backdrop (so the page never shows through it), through `effect` (pixelated by default). Above
231
+ * the track a text area of fixed size (`textAreaWidth` × `textAreaHeight`, independent of the
232
+ * videos), which never moves with them, shows the focused item's icon, title, and
233
+ * description; when focus moves, that caption fades out sliding a little in the direction the
234
+ * videos travel while the next one fades in sliding into place from the other side. The list is
235
+ * endless: slides are laid out along an unbounded track and the items repeat, so focus only ever
236
+ * moves forward from the last item to the first (never rewinding), and `autoplayMs` advances it
237
+ * on its own (paused while the pointer is over the carousel or the page is hidden). `delayMs` holds everything
238
+ * (videos, autoplay, clicks) for a moment after mount, invisibly unless `hideWhilePaused` is off;
239
+ * the hidden carousel fades in only once its videos are actually playing, so it never reveals
240
+ * still frames.
241
+ * Clicking a slide or changing `focusedIndex` moves focus too; the slides glide to their new
242
+ * places while the effect and the dimming fade in on the slide that lost focus and out on the
243
+ * one that gained it. The effects are drawn on one transparent WebGL canvas over the whole
244
+ * carousel, redrawing each video where its element sits; without WebGL the plain videos show.
245
+ */
246
+ export const VideoCarousel = memo(
247
+ (p: {
248
+ items: VideoCarouselItem[];
249
+ /** Width of the caption area above the videos, centered; independent of the videos' sizes. */
250
+ textAreaWidth: number;
251
+ /** Controlled focused item; a change moves forward around the loop to that item. Omit to let clicks and autoplay move focus on their own. */
252
+ focusedIndex?: number;
253
+ defaultFocusedIndex?: number;
254
+ onFocusedIndexChange?: (index: number) => void;
255
+ /** Advance to the next slide every this many ms; omit or 0 for no autoplay. */
256
+ autoplayMs?: number;
257
+ /** Hold the whole carousel (videos, autoplay, clicks) for this many ms after mount before it starts. */
258
+ delayMs?: number;
259
+ /** While held by `delayMs`, also make the carousel invisible until its videos play (it is never clickable while held). */
260
+ hideWhilePaused?: boolean;
261
+ /** Space between slides in CSS pixels. */
262
+ gap?: number;
263
+ /** Effect(s) applied to the unfocused videos, in order. */
264
+ effect?: VideoCarouselEffect | VideoCarouselEffect[];
265
+ /** 0..1 opacity of the unfocused videos, over `backdropColor`. */
266
+ unfocusedOpacity?: number;
267
+ /** Fallback hex color behind a video for the drawn copy, used only when the wrapper's `bg_active` background cannot be read. */
268
+ backdropColor?: string;
269
+ /** Duration of the slide movement, the effect fade, and the caption change, in ms. */
270
+ transitionMs?: number;
271
+ /** Corner radius of every video in CSS pixels. */
272
+ borderRadius?: number;
273
+ /** Fixed height of the text area above the videos, in CSS pixels; captions are bottom-aligned inside it. */
274
+ textAreaHeight?: number;
275
+ className?: string;
276
+ style?: CSSProperties;
277
+ }) => {
278
+ const {
279
+ items,
280
+ textAreaWidth,
281
+ focusedIndex: controlledIndex,
282
+ defaultFocusedIndex = 0,
283
+ onFocusedIndexChange,
284
+ autoplayMs = 0,
285
+ delayMs = 0,
286
+ hideWhilePaused = true,
287
+ gap = 24,
288
+ effect = 'pixelate',
289
+ unfocusedOpacity = 1,
290
+ backdropColor = '#ffffff',
291
+ transitionMs = 600,
292
+ borderRadius = 0,
293
+ textAreaHeight = 120,
294
+ className,
295
+ style,
296
+ } = p;
297
+ const count = items.length;
298
+ const containerRef = useRef<HTMLDivElement>(null);
299
+ // Filled by the <video> ref callbacks and read live by the scene, so it never needs to re-render.
300
+ const videosRef = useRef(new Map<string, HTMLVideoElement>());
301
+ // The virtual slide a click asked for, so a controlled parent confirming it lands there instead of a forward hop.
302
+ const requestedRef = useRef<number | null>(null);
303
+ // Unbounded slide position along the endless track; the item shown is position mod count.
304
+ const [position, setPosition] = useState(defaultFocusedIndex);
305
+ // 0 until measured on the client; the layout is not animated until then.
306
+ const [containerWidth, setContainerWidth] = useState(0);
307
+ const [hovering, setHovering] = useState(false);
308
+ // Held until `delayMs` has passed; the ref lets the video callbacks read it without re-registering.
309
+ const [paused, setPaused] = useState(delayMs > 0);
310
+ const pausedRef = useRef(paused);
311
+ pausedRef.current = paused;
312
+ // With `hideWhilePaused`, stays false until the hold is released and the mounted videos are playing.
313
+ const [revealed, setRevealed] = useState(!hideWhilePaused);
314
+ // Once the canvas draws the videos the plain ones fade out under it; they come back if WebGL fails.
315
+ const [canvasStatus, setCanvasStatus] = useState<'loading' | 'ready' | 'error'>('loading');
316
+ const focusedItemIndex = getItemIndex(position, count);
317
+ // The caption entering for the focused slide, preceded by the one leaving until its exit has played out.
318
+ const [captions, setCaptions] = useState<CarouselCaptionState[]>(() => [{ position, phase: 'in', direction: 1 }]);
319
+
320
+ // When focus moves, the current caption starts leaving in the track's direction and the new one enters behind it.
321
+ useEffect(() => {
322
+ setCaptions((current) => {
323
+ const entering = current.find((caption) => caption.phase === 'in');
324
+ if (!entering || entering.position === position) return current;
325
+ const direction = position > entering.position ? 1 : -1;
326
+ return [
327
+ { ...entering, phase: 'out', direction },
328
+ { position, phase: 'in', direction },
329
+ ];
330
+ });
331
+ const timer = window.setTimeout(
332
+ () => setCaptions((current) => current.filter((caption) => caption.phase === 'in')),
333
+ transitionMs,
334
+ );
335
+ return () => clearTimeout(timer);
336
+ }, [position, transitionMs]);
337
+
338
+ useEffect(() => {
339
+ const container = containerRef.current;
340
+ if (!container) return;
341
+ const observer = new ResizeObserver(([entry]) => setContainerWidth(entry.contentRect.width));
342
+ observer.observe(container);
343
+ setContainerWidth(container.clientWidth);
344
+ return () => observer.disconnect();
345
+ }, []);
346
+
347
+ // A controlled parent picks the item; the track moves forward to its next occurrence unless a click already chose one.
348
+ useEffect(() => {
349
+ if (controlledIndex === undefined) return;
350
+ setPosition((current) => {
351
+ const target = getItemIndex(controlledIndex, count);
352
+ if (getItemIndex(current, count) === target) return current;
353
+ const requested = requestedRef.current;
354
+ requestedRef.current = null;
355
+ if (requested !== null && getItemIndex(requested, count) === target) return requested;
356
+ return current + getItemIndex(target - current, count);
357
+ });
358
+ }, [controlledIndex, count]);
359
+
360
+ const focusSlide = useCallback(
361
+ (next: number) => {
362
+ if (controlledIndex === undefined) setPosition(next);
363
+ else requestedRef.current = next;
364
+ onFocusedIndexChange?.(getItemIndex(next, count));
365
+ },
366
+ [controlledIndex, count, onFocusedIndexChange],
367
+ );
368
+
369
+ // Release the hold once the delay has passed, and start every video that was waiting.
370
+ useEffect(() => {
371
+ if (!delayMs) {
372
+ setPaused(false);
373
+ return;
374
+ }
375
+ const timer = window.setTimeout(() => setPaused(false), delayMs);
376
+ return () => clearTimeout(timer);
377
+ }, [delayMs]);
378
+
379
+ // Start every video that was waiting, then reveal the carousel only once they are actually playing.
380
+ useEffect(() => {
381
+ if (paused) return;
382
+ const videos = [...videosRef.current.values()];
383
+ for (const video of videos) playVideo(video);
384
+ return whenVideosPlaying(videos, CAROUSEL.revealTimeoutMs, () => setRevealed(true));
385
+ }, [paused]);
386
+
387
+ // Autoplay: one step forward per interval, restarted whenever focus moves; idle while held, hovered, or hidden.
388
+ useEffect(() => {
389
+ if (!autoplayMs || paused || hovering || count < 2) return;
390
+ const timer = window.setInterval(() => {
391
+ if (!document.hidden) focusSlide(position + 1);
392
+ }, autoplayMs);
393
+ return () => clearInterval(timer);
394
+ }, [autoplayMs, paused, hovering, count, position, focusSlide]);
395
+
396
+ // Videos never start while the page is hidden; resume any that were left paused once it shows.
397
+ useEffect(() => {
398
+ const onVisible = () => {
399
+ if (document.visibilityState !== 'visible' || pausedRef.current) return;
400
+ for (const video of videosRef.current.values()) playVideo(video);
401
+ };
402
+ document.addEventListener('visibilitychange', onVisible);
403
+ return () => document.removeEventListener('visibilitychange', onVisible);
404
+ }, []);
405
+
406
+ /*
407
+ * Register a slide's <video> for the scene and make sure it plays; React 19 calls the cleanup
408
+ * when the element goes away. The `autoplay` attribute alone is unreliable (React sets `muted`
409
+ * as a property only, and a page loaded in the background may never start), so play() is
410
+ * asked for explicitly once the video can play, unless the carousel is still held by `delayMs`.
411
+ * Stable for the component's lifetime, so slides register exactly once.
412
+ */
413
+ const registerVideo = useCallback<RegisterVideo>((key, video) => {
414
+ if (!video) return;
415
+ video.muted = true;
416
+ videosRef.current.set(key, video);
417
+ const onCanPlay = () => {
418
+ if (!pausedRef.current) playVideo(video);
419
+ };
420
+ video.addEventListener('canplay', onCanPlay);
421
+ onCanPlay();
422
+ return () => {
423
+ video.removeEventListener('canplay', onCanPlay);
424
+ videosRef.current.delete(key);
425
+ };
426
+ }, []);
427
+
428
+ const widths = items.map((item) => item.width);
429
+ const minSlideWidth = Math.min(...widths) + gap;
430
+ const positions = useMemo(
431
+ () => getVirtualPositions(position, containerWidth, minSlideWidth),
432
+ [position, containerWidth, minSlideWidth],
433
+ );
434
+ const slides = useMemo(() => positions.map((v) => ({ key: String(v), focused: v === position })), [positions, position]);
435
+ const params = useContentMemo<CarouselSceneParams>(
436
+ () => ({
437
+ slides,
438
+ videos: videosRef.current,
439
+ effects: normalizeImageEffectSpecs(effect),
440
+ transitionMs,
441
+ borderRadius,
442
+ unfocusedOpacity,
443
+ backdropColor,
444
+ }),
445
+ [slides, effect, transitionMs, borderRadius, unfocusedOpacity, backdropColor],
446
+ );
447
+
448
+ // Slides sit at their natural-width positions along the endless track, and the track is shifted
449
+ // so the focused slide lands centered. All coordinates are absolute, so slides entering or
450
+ // leaving move nothing else.
451
+ const focusedLeft = getVirtualLeft(position, widths, gap);
452
+ const trackOffset = containerWidth / 2 - widths[focusedItemIndex] / 2 - focusedLeft;
453
+ const trackHeight = Math.max(...items.map((item) => item.height));
454
+ const transition = containerWidth ? `${transitionMs}ms ${CAROUSEL.easing}` : undefined;
455
+ const videosHidden = canvasStatus === 'ready';
456
+ const videoTransition = `opacity ${videosHidden ? CAROUSEL.crossFadeMs : transitionMs}ms ease`;
457
+
458
+ return (
459
+ <div
460
+ ref={containerRef}
461
+ // While held nothing is clickable or hoverable; with `hideWhilePaused` it stays invisible until released and playing, then fades in.
462
+ className={cn('rel of', paused && 'noclick', !revealed && 'invis op_0', className)}
463
+ style={hideWhilePaused ? { ...style, transition: `opacity ${CAROUSEL.revealMs}ms ease` } : style}
464
+ onPointerEnter={() => setHovering(true)}
465
+ onPointerLeave={() => setHovering(false)}
466
+ >
467
+ {/* Captions live here, above the track and outside it, so they never move with the videos. */}
468
+ <div
469
+ className="rel of w_f"
470
+ style={{ height: textAreaHeight }}
471
+ >
472
+ {captions.map((caption) => (
473
+ <CarouselCaption
474
+ key={caption.position}
475
+ item={items[getItemIndex(caption.position, count)]}
476
+ phase={caption.phase}
477
+ direction={caption.direction}
478
+ width={textAreaWidth}
479
+ durationMs={transitionMs}
480
+ />
481
+ ))}
482
+ </div>
483
+ <div
484
+ className="rel"
485
+ style={{
486
+ height: trackHeight,
487
+ transform: `translateX(${trackOffset}px)`,
488
+ transition: transition && `transform ${transition}`,
489
+ willChange: 'transform',
490
+ }}
491
+ >
492
+ {positions.map((v) => {
493
+ const focused = v === position;
494
+ return (
495
+ <CarouselSlide
496
+ key={v}
497
+ slideKey={String(v)}
498
+ position={v}
499
+ item={items[getItemIndex(v, count)]}
500
+ focused={focused}
501
+ interactive={!focused && !paused}
502
+ left={getVirtualLeft(v, widths, gap)}
503
+ width={widths[getItemIndex(v, count)]}
504
+ borderRadius={borderRadius}
505
+ transition={transition}
506
+ videoOpacity={videosHidden ? 0 : focused ? 1 : unfocusedOpacity}
507
+ videoTransition={videoTransition}
508
+ autoPlay={!paused}
509
+ onSelect={focusSlide}
510
+ registerVideo={registerVideo}
511
+ />
512
+ );
513
+ })}
514
+ </div>
515
+ {/* Draws every video with its effect exactly over its element; clicks pass through to the slides. */}
516
+ <GfxCanvas
517
+ load={loadCarouselScene}
518
+ params={params}
519
+ fill
520
+ transparent
521
+ className="noclick"
522
+ onReady={() => setCanvasStatus('ready')}
523
+ onError={() => setCanvasStatus('error')}
524
+ />
525
+ </div>
526
+ );
527
+ },
528
+ );
529
+
530
+ /*
531
+ * A row of blocks (its children, each any width, all stretched to the tallest) that the visitor
532
+ * drags with any pointer or scrolls sideways with a wheel or trackpad; whatever falls past the
533
+ * container's edges is clipped. When the drag or the scroll ends, the track glides to the
534
+ * nearest snap position: a block's left edge at the container's left edge (`align='start'`), or
535
+ * its middle at the container's middle. The track stops at its ends (the last blocks share the
536
+ * end position), so nothing loops, and nothing moves on its own. A drag past an end gives with
537
+ * rubber-band resistance and springs back; a flick always leaves the current block, and a wheel
538
+ * notch too short to reach the next block still advances one. A click on a block stays a click
539
+ * unless the pointer moved first, so blocks can hold buttons and links. With `selectableText` (the
540
+ * default) a mouse or pen press on text selects it the way it would anywhere on the page, and
541
+ * the drag starts from everything else (blank space, images, links, buttons); the cursor shows
542
+ * which one a press would do. On a touch screen a sideways swipe drags and a long press selects.
543
+ * Form fields inside the blocks are never dragged from. `index` / `defaultIndex`
544
+ * / `onIndexChange` name the block at the snap position; changing `index` glides there. Keyboard
545
+ * focus landing in a clipped block brings it into view. Padding on the container (through
546
+ * `className` or `style`) shows the neighbouring blocks under it. `lock={false}` turns the
547
+ * snapping off: a gesture leaves the track wherever it put it (a flick coasts a little further,
548
+ * and a drag past an end still springs back), while `index` and keyboard focus still glide to
549
+ * a block's snap position. `contentOffset` shifts where the content sits, at the start and
550
+ * throughout: -20 shows it 20px further left than the container's content box.
551
+ */
552
+ export const BlocksCarousel = memo(
553
+ (p: {
554
+ children: ReactNode;
555
+ /** Space between blocks in CSS pixels. */
556
+ gap?: number;
557
+ /** Where the current block rests: its left edge at the container's left edge, or centered in it. */
558
+ align?: BlocksAlign;
559
+ /** Controlled current block; a change glides the track to it. Omit to let gestures move it on their own. */
560
+ index?: number;
561
+ defaultIndex?: number;
562
+ /** Called with the block a gesture picked, as soon as it is picked (the glide there is still under way). */
563
+ onIndexChange?: (index: number) => void;
564
+ /** Duration of the glide to a snap position, in ms. */
565
+ transitionMs?: number;
566
+ /** Whether a finished drag or scroll locks the track onto the nearest block; `false` leaves it where the gesture ended. */
567
+ lock?: boolean;
568
+ /** Shift of the content in CSS pixels, at the start and throughout: -20 shows it 20px further left. */
569
+ contentOffset?: number;
570
+ /** Whether a mouse or pen press on text selects it instead of dragging the track; `false` drags from anywhere. */
571
+ selectableText?: boolean;
572
+ className?: string;
573
+ style?: CSSProperties;
574
+ }) => {
575
+ const {
576
+ children,
577
+ gap = 16,
578
+ align = 'start',
579
+ index,
580
+ defaultIndex = 0,
581
+ onIndexChange,
582
+ transitionMs = 600,
583
+ lock = true,
584
+ contentOffset = 0,
585
+ selectableText = true,
586
+ className,
587
+ style,
588
+ } = p;
589
+ const containerRef = useRef<HTMLDivElement>(null);
590
+ const trackRef = useRef<HTMLDivElement>(null);
591
+ const handlers = useBlocksCarousel(containerRef, trackRef, {
592
+ align,
593
+ index,
594
+ defaultIndex,
595
+ onIndexChange,
596
+ transitionMs,
597
+ lock,
598
+ contentOffset,
599
+ selectableText,
600
+ });
601
+
602
+ return (
603
+ <div
604
+ ref={containerRef}
605
+ // Vertical pans and pinches stay the browser's, so a finger can still scroll the page across the carousel; sideways ones are the drag.
606
+ // `cs_grab` is the cursor until the pointer first moves over the blocks; the hook writes it from then on.
607
+ className={cn('rel of cs_grab', className)}
608
+ style={{ ...style, touchAction: 'pan-y pinch-zoom' }}
609
+ {...handlers}
610
+ >
611
+ <div
612
+ ref={trackRef}
613
+ // As wide as its blocks (never shrunk to the container), moved by its transform alone. The first block's start
614
+ // position is rendered already, so server-rendered HTML does not jump by `contentOffset` when the hook takes over.
615
+ className="rel h_stretch"
616
+ style={{ gap, width: 'max-content', willChange: 'transform', transform: `translate3d(${contentOffset}px, 0, 0)` }}
617
+ >
618
+ {/* Each block in its own wrapper, so blocks are measured without needing refs of their own, and stretched to the row's height. */}
619
+ {Children.toArray(children).map((child, i) => (
620
+ <div
621
+ key={isValidElement(child) ? (child.key ?? i) : i}
622
+ className="no_shrink h_stretch"
623
+ >
624
+ {child}
625
+ </div>
626
+ ))}
627
+ </div>
628
+ </div>
629
+ );
630
+ },
631
+ );