@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,12 @@
1
+ import { useMemo } from 'react';
2
+
3
+ /*
4
+ * `useMemo` keyed on the content of its dependencies instead of their identity, for scene
5
+ * params built from inline arrays and objects (effect specs, option groups) that a caller
6
+ * re-creates on every render. Dependencies must be JSON-serializable; keep stable references
7
+ * such as refs and maps out of the list and read them inside the factory.
8
+ */
9
+ export function useContentMemo<T>(factory: () => T, deps: unknown[]): T {
10
+ const key = JSON.stringify(deps);
11
+ return useMemo(factory, [key]);
12
+ }
@@ -0,0 +1,189 @@
1
+ import { cn } from '@jsb188/app/utils/string.ts';
2
+ import { useEffect, useRef, useState } from 'react';
3
+ import type { CSSProperties, ReactNode, Ref } from 'react';
4
+ import type { SceneLoader, GfxRuntime } from '../libs/types.ts';
5
+
6
+ /*
7
+ * Cover-fit photo for a canvas's placeholder: fetched in the same CORS mode as the
8
+ * WebGL texture so the browser downloads the file once, decoded off the main thread, and
9
+ * never draggable. Use it for any placeholder that shows the photo a scene will present.
10
+ */
11
+ export const PlaceholderImage = (p: { src: string; className?: string; style?: CSSProperties; ref?: Ref<HTMLImageElement> }) => (
12
+ <img
13
+ ref={p.ref}
14
+ src={p.src}
15
+ alt=""
16
+ crossOrigin="anonymous"
17
+ decoding="async"
18
+ fetchPriority="high"
19
+ draggable={false}
20
+ className={cn('img_auto', p.className)}
21
+ style={p.style}
22
+ />
23
+ );
24
+
25
+ /*
26
+ * Reserve canvas space and load both the renderer and scene only when needed.
27
+ */
28
+ export const GfxCanvas = <P = void>({
29
+ load,
30
+ params,
31
+ placeholder,
32
+ errorFallback,
33
+ label,
34
+ className,
35
+ style,
36
+ fill = false,
37
+ lazy = true,
38
+ maxPixelRatio = 1.5,
39
+ transparent = false,
40
+ fadeIn = 600,
41
+ onReady,
42
+ onError,
43
+ }: {
44
+ /** Declare at module scope or memoize: a different loader recreates the scene. */
45
+ load: SceneLoader<P>;
46
+ /** Passed to the factory; later identities go to the scene's setParams without a remount. */
47
+ params?: P;
48
+ placeholder?: ReactNode;
49
+ errorFallback?: ReactNode;
50
+ /** Omit for a decorative canvas; pass translated text for meaningful artwork. */
51
+ label?: string;
52
+ className?: string;
53
+ /** Block mode defaults to a full-width square; override aspectRatio or provide an explicit height. */
54
+ style?: CSSProperties;
55
+ /** Stretch over the nearest positioned ancestor (an overlay or a background) instead of the block sizing. */
56
+ fill?: boolean;
57
+ lazy?: boolean;
58
+ maxPixelRatio?: number;
59
+ /** Overlay mode: the canvas keeps its alpha channel and the scene clears to transparent itself. */
60
+ transparent?: boolean;
61
+ /** Milliseconds the canvas fades in over the placeholder; 0 swaps instantly (for a first frame that matches the placeholder). */
62
+ fadeIn?: number;
63
+ /** Called once the scene has drawn its first ready frame and the canvas starts fading in. */
64
+ onReady?: () => void;
65
+ onError?: (error: unknown) => void;
66
+ }) => {
67
+ const canvasRef = useRef<HTMLCanvasElement>(null);
68
+ const runtimeRef = useRef<GfxRuntime<P> | null>(null);
69
+ const paramsRef = useRef(params);
70
+ const onErrorRef = useRef(onError);
71
+ const onReadyRef = useRef(onReady);
72
+ // ready: first frame drawn, fading in over the placeholder; shown: fade done, placeholder gone.
73
+ const [status, setStatus] = useState<'loading' | 'ready' | 'shown' | 'error'>('loading');
74
+ // A disposed runtime loses its WebGL context for good, and a canvas never gets another, so a
75
+ // runtime replaced while the canvas stays mounted (new props, Fast Refresh) gets a new element.
76
+ const [canvasKey, setCanvasKey] = useState(0);
77
+
78
+ useEffect(() => {
79
+ onErrorRef.current = onError;
80
+ onReadyRef.current = onReady;
81
+ }, [onError, onReady]);
82
+
83
+ useEffect(() => {
84
+ if (status !== 'ready') return;
85
+ const timer = window.setTimeout(() => setStatus('shown'), fadeIn + 50);
86
+ return () => clearTimeout(timer);
87
+ }, [status]);
88
+
89
+ useEffect(() => {
90
+ // Skip the initial identity; the factory already received it.
91
+ if (paramsRef.current === params) return;
92
+ paramsRef.current = params;
93
+ runtimeRef.current?.setParams(params as P);
94
+ }, [params]);
95
+
96
+ useEffect(() => {
97
+ const canvas = canvasRef.current;
98
+ if (!canvas) return;
99
+ let cancelled = false;
100
+ let started = false;
101
+ let visible = !lazy;
102
+ let runtime: GfxRuntime<P> | undefined;
103
+ setStatus('loading');
104
+
105
+ /*
106
+ * Show a caller-owned fallback for import, initialization, or rendering failures.
107
+ */
108
+ const fail = (error: unknown) => {
109
+ if (cancelled) return;
110
+ setStatus('error');
111
+ onErrorRef.current?.(error);
112
+ };
113
+
114
+ /*
115
+ * Cross the asynchronous boundary without allowing stale loads to mount a scene.
116
+ */
117
+ const start = async () => {
118
+ if (started || cancelled) return;
119
+ started = true;
120
+ try {
121
+ const [{ createGfxRuntime }, { default: createScene }] = await Promise.all([import('../libs/runtime.ts'), load()]);
122
+ if (cancelled) return;
123
+ runtime = createGfxRuntime<P>({
124
+ canvas,
125
+ createScene,
126
+ params: paramsRef.current as P,
127
+ visible,
128
+ maxPixelRatio,
129
+ transparent,
130
+ onError: fail,
131
+ onReady: () => {
132
+ if (cancelled) return;
133
+ setStatus('ready');
134
+ onReadyRef.current?.();
135
+ },
136
+ });
137
+ runtimeRef.current = runtime;
138
+ } catch (error) {
139
+ fail(error);
140
+ }
141
+ };
142
+
143
+ const observer =
144
+ typeof IntersectionObserver === 'undefined'
145
+ ? undefined
146
+ : new IntersectionObserver(([entry]) => {
147
+ visible = entry.isIntersecting;
148
+ runtime?.setVisible(visible);
149
+ if (visible) void start();
150
+ });
151
+ observer?.observe(canvas);
152
+ if (!lazy || !observer) {
153
+ visible = true;
154
+ void start();
155
+ }
156
+
157
+ return () => {
158
+ cancelled = true;
159
+ observer?.disconnect();
160
+ runtime?.dispose();
161
+ if (runtimeRef.current === runtime) runtimeRef.current = null;
162
+ if (runtime && canvas.isConnected) setCanvasKey((key) => key + 1);
163
+ };
164
+ }, [load, lazy, maxPixelRatio, transparent, canvasKey]);
165
+
166
+ const shown = status === 'ready' || status === 'shown';
167
+ // The placeholder stays under the canvas while it fades in. With no fade the swap is one
168
+ // commit, so a translucent placeholder never stacks under the same translucent first frame.
169
+ const placeholderShown = status === 'loading' || status === 'error' || (status === 'ready' && fadeIn > 0);
170
+
171
+ return (
172
+ <div
173
+ className={cn(fill ? 'abs_full' : 'rel w_f ap_1', className)}
174
+ style={style}
175
+ >
176
+ {/* Rendered first so the canvas fades in on top of it. */}
177
+ {placeholderShown && <div className="abs_full">{status === 'error' ? (errorFallback ?? placeholder) : placeholder}</div>}
178
+ <canvas
179
+ key={canvasKey}
180
+ ref={canvasRef}
181
+ role={label ? 'img' : undefined}
182
+ aria-label={label}
183
+ aria-hidden={!label}
184
+ className={cn('abs_full bl w_f h_f', shown ? 'op_100' : 'op_0')}
185
+ style={fadeIn > 0 ? { transition: `opacity ${fadeIn}ms ease` } : undefined}
186
+ />
187
+ </div>
188
+ );
189
+ };
@@ -0,0 +1,90 @@
1
+ import { cn } from '@jsb188/app/utils/string.ts';
2
+ import type { EffectRegion } from '../libs/effects/effectRegion.ts';
3
+ import { normalizeImageEffectSpecs } from '../utils/imageEffectSpecs.ts';
4
+ import type { ImageEffectName, ImageEffectSpec } from '../utils/imageEffectSpecs.ts';
5
+ import { GfxCanvas, PlaceholderImage } from './GfxCanvas.tsx';
6
+ import { useContentMemo } from './GfxCanvas.hooks.ts';
7
+ import { memo } from 'react';
8
+ import type { CSSProperties, ReactNode } from 'react';
9
+ import type { HeroSceneParams } from '../scenes/Hero.ts';
10
+
11
+ /**
12
+ * Types
13
+ */
14
+
15
+ /** An effect name with its defaults, or a spec with options: `{ name: 'lens', zoom: 2 }`. */
16
+ export type HeroImageEffect = ImageEffectName | ImageEffectSpec;
17
+ export type HeroHoverEffect = HeroImageEffect;
18
+ export type HeroImageEffectRegion = EffectRegion;
19
+
20
+ /*
21
+ * Load OGL and the shader passes only when the hero mounts, never with the route bundle.
22
+ */
23
+ const loadHeroScene = () => import('../scenes/Hero.ts');
24
+
25
+ /*
26
+ * Full-bleed hero: the photo is the background, a cursor-following spotlight with rippling,
27
+ * shattered bokeh edges plays over it, and children render on top. A plain <img> of the photo
28
+ * shows until the canvas is ready (and if WebGL is unavailable), so the hero never looks empty.
29
+ * While the pointer is over the hero, `hoverEffect` alters the photo itself (eased in and out).
30
+ * `imageEffect` alters the photo permanently, over the whole image or only inside
31
+ * `imageEffectRegion`, whose shapes can be fixed or anchored to the pointer.
32
+ */
33
+ export const Hero = memo(
34
+ (p: {
35
+ backgroundImageUrl: string;
36
+ children?: ReactNode;
37
+ /** Hex brand color: pre-load fill, photo tint, and the seed for the light and shade colors. */
38
+ baseColor?: string;
39
+ className?: string;
40
+ style?: CSSProperties;
41
+ /** 0..1 how strongly the light field darkens and warms the photo. */
42
+ intensity?: number;
43
+ /** Photo effect(s) while hovering; several are applied in order (at most one of chromatic/zoomBlur/bokeh). */
44
+ hoverEffect?: HeroHoverEffect | HeroHoverEffect[];
45
+ /** Photo effect(s) that are always on, applied to the whole image unless `imageEffectRegion` limits them. */
46
+ imageEffect?: HeroImageEffect | HeroImageEffect[];
47
+ /** Where `imageEffect` applies: a shape anchored to fixed coordinates or to `'pointer'`. */
48
+ imageEffectRegion?: HeroImageEffectRegion;
49
+ }) => {
50
+ const {
51
+ backgroundImageUrl,
52
+ children,
53
+ baseColor = '#ffaaa5',
54
+ className,
55
+ style,
56
+ intensity = 0.45,
57
+ hoverEffect,
58
+ imageEffect,
59
+ imageEffectRegion,
60
+ } = p;
61
+ const params = useContentMemo<HeroSceneParams>(
62
+ () => ({
63
+ imageUrl: backgroundImageUrl,
64
+ baseColor,
65
+ intensity,
66
+ hoverEffects: normalizeImageEffectSpecs(hoverEffect),
67
+ imageEffects: normalizeImageEffectSpecs(imageEffect),
68
+ imageEffectRegion: imageEffectRegion ?? null,
69
+ }),
70
+ [backgroundImageUrl, baseColor, intensity, hoverEffect, imageEffect, imageEffectRegion],
71
+ );
72
+
73
+ return (
74
+ <div
75
+ className={cn('rel of', className)}
76
+ style={{ backgroundColor: baseColor, ...style }}
77
+ >
78
+ {/* The photo stands in until the canvas has faded in, and again if WebGL fails; it is then unmounted so its decoded bitmap is released. */}
79
+ <GfxCanvas
80
+ load={loadHeroScene}
81
+ params={params}
82
+ fill
83
+ lazy={false}
84
+ placeholder={<PlaceholderImage src={backgroundImageUrl} />}
85
+ />
86
+ <div className="rel">{children}</div>
87
+ </div>
88
+ );
89
+ },
90
+ );
@@ -0,0 +1,44 @@
1
+ import type { CSSProperties } from 'react';
2
+ import type { KineticHeaderImage } from './KineticHeader.types.ts';
3
+
4
+ /*
5
+ * Anchor captions outside the image with 8px top/bottom gaps and 10px left/right gaps.
6
+ */
7
+ export function getKineticImageAltStyle({ altPosition = 'top', altWidth }: KineticHeaderImage): CSSProperties {
8
+ const width = altWidth ?? '100%';
9
+ switch (altPosition) {
10
+ case 'left':
11
+ return { width, top: 0, right: 'calc(100% + 10px)' };
12
+ case 'right':
13
+ return { width, top: 0, left: 'calc(100% + 10px)' };
14
+ case 'bottom':
15
+ return { width, left: 0, top: 'calc(100% + 8px)' };
16
+ default:
17
+ return { width, left: 0, bottom: 'calc(100% + 8px)' };
18
+ }
19
+ }
20
+
21
+ /*
22
+ * Animate entrance and exit around the full display duration. The first slide skips entrance.
23
+ */
24
+ export function createKineticImageAnimation(
25
+ element: HTMLElement | null,
26
+ { duration, enterDuration, exitDuration }: { duration: number; enterDuration: number; exitDuration: number },
27
+ ) {
28
+ if (!element?.animate || (enterDuration <= 0 && exitDuration <= 0)) return;
29
+ const totalDuration = enterDuration + duration + exitDuration;
30
+ return element.animate(
31
+ [
32
+ {
33
+ opacity: enterDuration > 0 ? 0 : 1,
34
+ transform: enterDuration > 0 ? 'translateY(32px)' : 'translateY(0)',
35
+ offset: 0,
36
+ easing: 'ease-in-out',
37
+ },
38
+ { opacity: 1, transform: 'translateY(0)', offset: enterDuration / totalDuration },
39
+ { opacity: 1, transform: 'translateY(0)', offset: (enterDuration + duration) / totalDuration, easing: 'ease-in-out' },
40
+ { opacity: 0, transform: 'translateY(32px)', offset: 1 },
41
+ ],
42
+ { duration: totalDuration, fill: 'both' },
43
+ );
44
+ }
@@ -0,0 +1,206 @@
1
+ import { useLayoutEffect, useRef, useState } from 'react';
2
+ import { createKineticImageAnimation } from './KineticHeader.helpers.ts';
3
+ import type { KineticHeaderProps } from './KineticHeader.types.ts';
4
+
5
+ /*
6
+ * Schedule entrance, display, and exit boundaries while native animations draw images and progress.
7
+ * Hover pauses display time or uses its configured duration; keyboard focus pauses display time.
8
+ * Offscreen slides, hidden tabs, and reduced motion pause all phases.
9
+ * The enclosing component remounts this sequence when the slide contents or fixed selection change.
10
+ * Fixed slides stay fully visible without starting timers or animations.
11
+ */
12
+ export function useKineticHeader({
13
+ slides,
14
+ fixedSlide,
15
+ slideDuration = 5000,
16
+ mouseOverSlideDuration,
17
+ slideTransitionMs = 350,
18
+ }: KineticHeaderProps) {
19
+ const [index, setIndex] = useState(fixedSlide ?? 0);
20
+ const [isPaused, setIsPaused] = useState(fixedSlide !== undefined);
21
+ const [reducedMotion, setReducedMotion] = useState(false);
22
+ const [showControls, setShowControls] = useState(false);
23
+ const imageAreaRef = useRef<HTMLDivElement>(null);
24
+ const hoverAreaRef = useRef<HTMLDivElement>(null);
25
+ const progressRef = useRef<HTMLDivElement>(null);
26
+ const previousIndex = useRef(index);
27
+ const hovered = useRef<boolean | null>(null);
28
+ const navigateRef = useRef<((direction: -1 | 1) => void) | null>(null);
29
+
30
+ /*
31
+ * Request navigation through the active timeline, which ignores input during transitions or fixed slides.
32
+ */
33
+ const navigate = (direction: -1 | 1) => {
34
+ navigateRef.current?.(direction);
35
+ };
36
+
37
+ useLayoutEffect(() => {
38
+ const changed = previousIndex.current !== index;
39
+ previousIndex.current = index;
40
+ if (fixedSlide !== undefined || slides.length < 2) return;
41
+
42
+ const duration = Number.isFinite(slideDuration) ? Math.max(1, slideDuration) : 5000;
43
+ const hoverDuration =
44
+ typeof mouseOverSlideDuration === 'number' && Number.isInteger(mouseOverSlideDuration) && mouseOverSlideDuration > 0
45
+ ? mouseOverSlideDuration
46
+ : undefined;
47
+ const transition = Number.isFinite(slideTransitionMs) ? Math.max(0, slideTransitionMs) : 350;
48
+ const enterDuration = changed ? transition : 0;
49
+ const exitDuration = transition > 0 ? 350 : 0;
50
+ const exitStart = enterDuration + duration;
51
+ const totalDuration = exitStart + exitDuration;
52
+ const hoverArea = hoverAreaRef.current;
53
+ const progress = progressRef.current;
54
+ const motion = window.matchMedia?.('(prefers-reduced-motion: reduce)');
55
+ const imageAnimation = createKineticImageAnimation(imageAreaRef.current, { duration, enterDuration, exitDuration });
56
+ const progressAnimation = progress?.animate?.([{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }], {
57
+ duration,
58
+ fill: 'both',
59
+ });
60
+ let elapsed = 0;
61
+ let startedAt: number | null = null;
62
+ let playbackRate = 1;
63
+ let timer: number | undefined;
64
+ let nextIndex = (index + 1) % slides.length;
65
+ // Keep pointer presence across slide effects, including entry during the outgoing fade.
66
+ hovered.current ??= hoverArea?.matches(':hover') ?? false;
67
+ let focused = !!hoverArea?.contains(document.activeElement);
68
+ let visible = true;
69
+
70
+ /*
71
+ * Preserve elapsed progress at the previous speed before applying hover speed or pause changes.
72
+ */
73
+ const syncPlayback = () => {
74
+ const now = performance.now();
75
+ if (startedAt !== null) {
76
+ // Stop at each boundary so a delayed timer cannot consume display time before checking hover.
77
+ const phaseEnd = elapsed < enterDuration ? enterDuration : elapsed < exitStart ? exitStart : totalDuration;
78
+ elapsed = Math.min(phaseEnd, elapsed + (now - startedAt) * playbackRate);
79
+ }
80
+ startedAt = null;
81
+ window.clearTimeout(timer);
82
+ timer = undefined;
83
+
84
+ const reduced = motion?.matches ?? false;
85
+ const displaying = elapsed >= enterDuration && elapsed < exitStart;
86
+ const displayElapsed = Math.max(0, Math.min(duration, elapsed - enterDuration));
87
+ const interacting = !!hovered.current || focused;
88
+ const paused =
89
+ ((focused || (hovered.current && hoverDuration === undefined)) && displaying) || !visible || document.hidden || reduced;
90
+ playbackRate = displaying && hovered.current && hoverDuration !== undefined ? duration / hoverDuration : 1;
91
+ setIsPaused(paused);
92
+ setReducedMotion(reduced);
93
+ setShowControls(interacting && (displaying || reduced) && visible && !document.hidden);
94
+
95
+ if (imageAnimation) {
96
+ // Cancelling restores the complete image if reduced motion interrupts an entrance or exit.
97
+ if (reduced) imageAnimation.cancel();
98
+ else {
99
+ imageAnimation.pause();
100
+ imageAnimation.playbackRate = playbackRate;
101
+ imageAnimation.currentTime = elapsed;
102
+ }
103
+ }
104
+ if (progressAnimation) {
105
+ progressAnimation.pause();
106
+ progressAnimation.playbackRate = playbackRate;
107
+ progressAnimation.currentTime = displayElapsed;
108
+ }
109
+ if (progress && !progressAnimation) {
110
+ progress.style.transition = 'none';
111
+ progress.style.transform = `scaleX(${displayElapsed / duration})`;
112
+ if (!paused && displaying) {
113
+ // Browsers without Web Animations can still interpolate progress natively.
114
+ progress.getBoundingClientRect();
115
+ progress.style.transition = `transform ${(duration - displayElapsed) / playbackRate}ms linear`;
116
+ progress.style.transform = 'scaleX(1)';
117
+ }
118
+ }
119
+ if (paused) return;
120
+ if (elapsed >= totalDuration) {
121
+ setIndex(nextIndex);
122
+ return;
123
+ }
124
+
125
+ startedAt = now;
126
+ imageAnimation?.play();
127
+ if (displaying) progressAnimation?.play();
128
+ const nextBoundary = elapsed < enterDuration ? enterDuration : displaying ? exitStart : totalDuration;
129
+ timer = window.setTimeout(syncPlayback, (nextBoundary - elapsed) / playbackRate);
130
+ };
131
+
132
+ /*
133
+ * Exit the current slide before entering its neighbor; reduced motion switches immediately.
134
+ */
135
+ navigateRef.current = (direction) => {
136
+ const reduced = motion?.matches ?? false;
137
+ if (!reduced && (elapsed < enterDuration || elapsed >= exitStart)) return;
138
+ nextIndex = (index + direction + slides.length) % slides.length;
139
+ if (reduced) {
140
+ setIndex(nextIndex);
141
+ return;
142
+ }
143
+ elapsed = exitStart;
144
+ startedAt = null;
145
+ syncPlayback();
146
+ };
147
+
148
+ /*
149
+ * Remember pointer entry; only display time uses the hover duration or pauses.
150
+ */
151
+ const onMouseEnter = () => {
152
+ hovered.current = true;
153
+ syncPlayback();
154
+ };
155
+
156
+ /*
157
+ * Restore the normal display speed after pointer exit unless another pause reason remains active.
158
+ */
159
+ const onMouseLeave = () => {
160
+ hovered.current = false;
161
+ syncPlayback();
162
+ };
163
+
164
+ /*
165
+ * Track focus across descendants using the destination, before activeElement updates.
166
+ */
167
+ const syncFocus = (event: FocusEvent) => {
168
+ focused = event.type === 'focusin' || (event.relatedTarget instanceof Node && !!hoverArea?.contains(event.relatedTarget));
169
+ syncPlayback();
170
+ };
171
+
172
+ /*
173
+ * Stop advancing and fetching subsequent slide images while the image area is offscreen.
174
+ */
175
+ const syncVisibility = (entries: IntersectionObserverEntry[]) => {
176
+ visible = entries.at(-1)?.isIntersecting ?? visible;
177
+ syncPlayback();
178
+ };
179
+
180
+ const observer = hoverArea && typeof IntersectionObserver !== 'undefined' ? new IntersectionObserver(syncVisibility) : null;
181
+ if (hoverArea) observer?.observe(hoverArea);
182
+ syncPlayback();
183
+ hoverArea?.addEventListener('mouseenter', onMouseEnter);
184
+ hoverArea?.addEventListener('mouseleave', onMouseLeave);
185
+ hoverArea?.addEventListener('focusin', syncFocus);
186
+ hoverArea?.addEventListener('focusout', syncFocus);
187
+ document.addEventListener('visibilitychange', syncPlayback);
188
+ motion?.addEventListener('change', syncPlayback);
189
+ return () => {
190
+ navigateRef.current = null;
191
+ observer?.disconnect();
192
+ window.clearTimeout(timer);
193
+ imageAnimation?.cancel();
194
+ progressAnimation?.cancel();
195
+ if (progress && !progressAnimation) progress.style.transition = 'none';
196
+ hoverArea?.removeEventListener('mouseenter', onMouseEnter);
197
+ hoverArea?.removeEventListener('mouseleave', onMouseLeave);
198
+ hoverArea?.removeEventListener('focusin', syncFocus);
199
+ hoverArea?.removeEventListener('focusout', syncFocus);
200
+ document.removeEventListener('visibilitychange', syncPlayback);
201
+ motion?.removeEventListener('change', syncPlayback);
202
+ };
203
+ }, [index, slides.length, slideDuration, mouseOverSlideDuration, slideTransitionMs, fixedSlide]);
204
+
205
+ return { index, isPaused, reducedMotion, showControls, navigate, imageAreaRef, hoverAreaRef, progressRef };
206
+ }