@jsb188/gfx 1.1.11 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +248 -54
  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/dotGrid.helpers.ts +53 -0
  12. package/libs/dotGrid.ts +480 -77
  13. package/libs/effects/dotEffects.ts +136 -0
  14. package/libs/effects/effectQuad.ts +8 -2
  15. package/libs/pointer.ts +6 -0
  16. package/libs/runtime.ts +6 -4
  17. package/libs/types.ts +8 -1
  18. package/main.ts +2 -0
  19. package/modules/Carousel.helpers.ts +234 -0
  20. package/modules/Carousel.hooks.ts +520 -0
  21. package/modules/Carousel.tsx +135 -29
  22. package/modules/Dots.tsx +269 -0
  23. package/modules/DotsBoard.helpers.ts +388 -0
  24. package/modules/DotsBoard.hooks.ts +144 -0
  25. package/modules/DotsBoard.strings.ts +649 -0
  26. package/modules/DotsBoard.types.ts +240 -0
  27. package/modules/DotsBoardCanvas.hooks.ts +49 -0
  28. package/modules/DotsBoardCanvas.tsx +190 -0
  29. package/modules/DotsBoardElements.tsx +330 -0
  30. package/modules/Gallery.helpers.ts +32 -0
  31. package/modules/Gallery.hooks.ts +149 -0
  32. package/modules/Gallery.tsx +194 -0
  33. package/modules/GfxCanvas.tsx +10 -2
  34. package/modules/KineticHeader.helpers.ts +44 -0
  35. package/modules/KineticHeader.hooks.ts +206 -0
  36. package/modules/KineticHeader.tsx +305 -0
  37. package/modules/KineticHeader.types.ts +56 -0
  38. package/modules/ScrollSteps.hooks.ts +138 -0
  39. package/modules/ScrollSteps.tsx +7 -52
  40. package/package.json +15 -5
  41. package/scenes/Carousel.ts +99 -18
  42. package/scenes/DotsBoard.helpers.ts +12 -0
  43. package/scenes/DotsBoard.ts +245 -0
  44. package/tsconfig.json +1 -1
  45. package/utils/align.ts +18 -0
  46. package/utils/color.ts +64 -2
  47. package/utils/dotEffectSpecs.ts +79 -0
  48. package/utils/dotGridSpecs.ts +304 -46
  49. package/utils/motion.ts +88 -0
  50. package/utils/random.ts +22 -0
  51. package/utils/strings.ts +116 -0
  52. package/modules/DotsArea.tsx +0 -120
  53. package/modules/VisionBoard.helpers.ts +0 -561
  54. package/modules/VisionBoard.tsx +0 -358
  55. package/modules/VisionBoard.types.ts +0 -88
  56. package/scenes/DotsArea.ts +0 -208
@@ -1,358 +0,0 @@
1
- import { cn } from '@jsb188/app/utils/string.ts';
2
- import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useState } from 'react';
3
- import type { CSSProperties, PointerEvent } from 'react';
4
- import {
5
- VISION_BOARD_DEFAULTS,
6
- buildRestStringPath,
7
- createVisionBoardEngine,
8
- getVisionBoardSegments,
9
- getVisionBoardTextStyle,
10
- resolveVisionBoardItems,
11
- } from './VisionBoard.helpers.ts';
12
- import type { VisionBoardEngine } from './VisionBoard.helpers.ts';
13
- import type {
14
- ResolvedVisionBoardItem,
15
- VisionBoardConnection,
16
- VisionBoardItem,
17
- VisionBoardOverrides,
18
- VisionBoardPhysicsOptions,
19
- VisionBoardSegment,
20
- VisionBoardTextPlacement,
21
- VisionBoardTextVisibility,
22
- } from './VisionBoard.types.ts';
23
-
24
- export type {
25
- VisionBoardConnection,
26
- VisionBoardItem,
27
- VisionBoardItemOverride,
28
- VisionBoardOverrides,
29
- VisionBoardPhysicsOptions,
30
- VisionBoardTextPlacement,
31
- VisionBoardTextVisibility,
32
- } from './VisionBoard.types.ts';
33
-
34
- /*
35
- * One item: a point in the board (its `left` / `top`, in percent, never change after mount so
36
- * the engine can move it by transform alone) holding the node centered on it and the texts to
37
- * one side. Hiding fades and shrinks the inner block so the point itself keeps its physics.
38
- */
39
- const VisionBoardNode = memo(
40
- (p: {
41
- item: ResolvedVisionBoardItem;
42
- boardWidth: number;
43
- boardHeight: number;
44
- size: number;
45
- color: string;
46
- textPlacement: VisionBoardTextPlacement;
47
- textWidth: number;
48
- hoverText: boolean;
49
- draggable: boolean;
50
- engine: VisionBoardEngine;
51
- }) => {
52
- const { item, boardWidth, boardHeight, size, color, textPlacement, textWidth, hoverText, draggable, engine } = p;
53
- const { id, image, icon, title, text, tags, hidden } = item;
54
- // The position the markup was rendered at; later moves are transforms from here.
55
- const [base] = useState(() => ({ x: item.x, y: item.y }));
56
- const hasText = !!(title || text || tags?.length);
57
- const placement = item.textPlacement ?? textPlacement;
58
-
59
- const setElement = useCallback((el: HTMLDivElement | null) => engine.setNode(id, el, base.x, base.y), [engine, id, base]);
60
-
61
- /*
62
- * Drag with the pointer captured, so the item follows even when the pointer leaves it; the
63
- * engine rubber-bands the distance and springs the item back on release.
64
- */
65
- const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
66
- if (!draggable || e.button !== 0) return;
67
- if (!engine.startDrag(id, e.clientX, e.clientY)) return;
68
- e.currentTarget.setPointerCapture(e.pointerId);
69
- e.preventDefault();
70
- };
71
- const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {
72
- if (e.currentTarget.hasPointerCapture(e.pointerId)) engine.moveDrag(id, e.clientX, e.clientY, e.timeStamp);
73
- };
74
- const onPointerEnd = (e: PointerEvent<HTMLDivElement>) => {
75
- if (!e.currentTarget.hasPointerCapture(e.pointerId)) return;
76
- e.currentTarget.releasePointerCapture(e.pointerId);
77
- engine.endDrag(id, e.timeStamp);
78
- };
79
-
80
- return (
81
- <div
82
- ref={setElement}
83
- className={cn('abs', hoverText && 'op_hv_area')}
84
- style={{ left: `${(base.x / boardWidth) * 100}%`, top: `${(base.y / boardHeight) * 100}%`, willChange: 'transform' }}
85
- aria-hidden={hidden}
86
- >
87
- <div
88
- style={{
89
- opacity: hidden ? 0 : 1,
90
- transform: hidden ? 'scale(0.5)' : 'none',
91
- transition: `opacity ${VISION_BOARD_DEFAULTS.hideMs}ms ease, transform ${VISION_BOARD_DEFAULTS.hideMs}ms ease`,
92
- pointerEvents: hidden ? 'none' : undefined,
93
- }}
94
- >
95
- <div
96
- className={cn('abs r bg h_center of', draggable && 'cs_grab')}
97
- style={{
98
- left: -size / 2,
99
- top: -size / 2,
100
- width: size,
101
- height: size,
102
- // Icons size themselves in em, so they scale with the node.
103
- fontSize: Math.round(size * 0.36),
104
- color,
105
- boxShadow: `0 0 0 2px ${color}, 0 4px 14px rgba(0, 0, 0, 0.1)`,
106
- transition: 'box-shadow 350ms ease, color 350ms ease',
107
- touchAction: 'none',
108
- }}
109
- role={title ? 'img' : undefined}
110
- aria-label={title}
111
- onPointerDown={onPointerDown}
112
- onPointerMove={onPointerMove}
113
- onPointerUp={onPointerEnd}
114
- onPointerCancel={onPointerEnd}
115
- >
116
- {image ? (
117
- <img
118
- src={image}
119
- alt=""
120
- draggable={false}
121
- className="w_f h_f img_cover bl"
122
- />
123
- ) : (
124
- icon
125
- )}
126
- </div>
127
- {hasText && (
128
- <div
129
- className={cn('abs lh_2', hoverText && 'op_0 op_100_hv trans_op')}
130
- style={getVisionBoardTextStyle(placement, size, VISION_BOARD_DEFAULTS.textGap, textWidth)}
131
- >
132
- {title && <div className="ft_sm ft_semibold">{title}</div>}
133
- {text && <div className="ft_xs op_70">{text}</div>}
134
- {!!tags?.length && (
135
- <div
136
- className="h_item f_wrap gap_xs mt_xs"
137
- style={{ justifyContent: placement === 'left' ? 'flex-end' : placement === 'right' ? 'flex-start' : 'center' }}
138
- >
139
- {tags.map((tag) => (
140
- <span
141
- key={tag}
142
- className="ft_xxs px_5 r bg_active no_wrap"
143
- >
144
- {tag}
145
- </span>
146
- ))}
147
- </div>
148
- )}
149
- </div>
150
- )}
151
- </div>
152
- </div>
153
- );
154
- },
155
- );
156
-
157
- /*
158
- * One stretch of string. The markup carries its rest path; from then on the engine owns `d`,
159
- * so React never resets a moving string (the path never re-renders `d`).
160
- */
161
- const VisionBoardString = memo(
162
- (p: {
163
- segment: VisionBoardSegment;
164
- from: ResolvedVisionBoardItem;
165
- to: ResolvedVisionBoardItem;
166
- color: string;
167
- width: number;
168
- engine: VisionBoardEngine;
169
- }) => {
170
- const { segment, from, to, color, width, engine } = p;
171
- const [restPath] = useState(() => buildRestStringPath(from.x, from.y, to.x, to.y, segment.slack));
172
- const setElement = useCallback((el: SVGPathElement | null) => engine.setSegmentElement(segment.key, el), [engine, segment.key]);
173
-
174
- return (
175
- <path
176
- ref={setElement}
177
- d={restPath}
178
- fill="none"
179
- strokeWidth={width}
180
- strokeLinecap="round"
181
- strokeDasharray={segment.dashed ? '4 8' : undefined}
182
- vectorEffect="non-scaling-stroke"
183
- style={{
184
- stroke: color,
185
- opacity: segment.hidden ? 0 : 1,
186
- transition: `opacity ${VISION_BOARD_DEFAULTS.hideMs}ms ease, stroke ${VISION_BOARD_DEFAULTS.hideMs}ms ease`,
187
- }}
188
- />
189
- );
190
- },
191
- );
192
-
193
- /*
194
- * A board of items (a photo or an icon in a ring, with a title, text, and tags beside it) placed
195
- * in a `width` × `height` design space, joined by strings. The board keeps that aspect ratio at
196
- * any CSS width, so positions scale while node sizes and texts stay in pixels. Items can be
197
- * dragged: they move freely up to `dragLimit` board units from home, resist beyond it, and
198
- * spring back with a bounce when released (a fast release throws them a little). Each string
199
- * is a chain through item ids, drawn as a quadratic curve per stretch that sags by `slack` and,
200
- * with string physics on, lags and wobbles behind the items it joins before settling.
201
- * `overrides` change any item property (position, `hidden`, color, texts) by id: switching to
202
- * another overrides object springs the items to their new places and fades hidden ones out, so
203
- * a set of buttons or a scroll position can drive the board as a sequence of states.
204
- * `visibleTags` hides tagged items that carry none of the given tags (untagged items always show).
205
- * Motion runs outside React on one frame loop that stops when everything is still; reduced
206
- * motion snaps instead of springing. The markup renders the rest state, so the server output
207
- * already shows the whole board.
208
- */
209
- export const VisionBoard = memo(
210
- (p: {
211
- items: VisionBoardItem[];
212
- connections?: VisionBoardConnection[];
213
- /** Design space the item coordinates live in; the board keeps this aspect ratio. */
214
- width: number;
215
- height: number;
216
- /** The current state of the board, applied over `items` by id. */
217
- overrides?: VisionBoardOverrides;
218
- /** Show only tagged items carrying at least one of these tags; `null` or omitted shows all. */
219
- visibleTags?: string[] | null;
220
- /** Whether the texts are always beside the node or appear while it is hovered. */
221
- textVisibility?: VisionBoardTextVisibility;
222
- textPlacement?: VisionBoardTextPlacement;
223
- /** Width of the text block in CSS pixels. */
224
- textWidth?: number;
225
- /** Node diameter in CSS pixels. */
226
- nodeSize?: number;
227
- /** Default accent color of the nodes. */
228
- color?: string;
229
- draggable?: boolean;
230
- /** How far, in board units, an item drags freely before the rubber band resists. */
231
- dragLimit?: number;
232
- /** Default sag of the strings as a fraction of each stretch's length; 0 for straight lines. */
233
- slack?: number;
234
- stringColor?: string;
235
- /** Default stroke width of the strings in CSS pixels. */
236
- stringWidth?: number;
237
- physics?: VisionBoardPhysicsOptions;
238
- className?: string;
239
- style?: CSSProperties;
240
- }) => {
241
- const {
242
- items,
243
- connections,
244
- width,
245
- height,
246
- overrides,
247
- visibleTags,
248
- textVisibility = 'always',
249
- textPlacement = 'right',
250
- textWidth = VISION_BOARD_DEFAULTS.textWidth,
251
- nodeSize = VISION_BOARD_DEFAULTS.nodeSize,
252
- color = 'currentColor',
253
- draggable = true,
254
- dragLimit = VISION_BOARD_DEFAULTS.dragLimit,
255
- slack = VISION_BOARD_DEFAULTS.slack,
256
- stringColor,
257
- stringWidth = VISION_BOARD_DEFAULTS.stringWidth,
258
- physics,
259
- className,
260
- style,
261
- } = p;
262
- const itemSpring = { ...VISION_BOARD_DEFAULTS.itemSpring, ...physics?.item };
263
- const stringSpring = physics?.string === false ? null : { ...VISION_BOARD_DEFAULTS.stringSpring, ...physics?.string };
264
- const [engine] = useState(() =>
265
- createVisionBoardEngine({
266
- dragLimit,
267
- dragStretch: VISION_BOARD_DEFAULTS.dragStretch,
268
- throwFactor: VISION_BOARD_DEFAULTS.throwFactor,
269
- itemSpring,
270
- stringSpring,
271
- }),
272
- );
273
- const [boardEl, setBoardEl] = useState<HTMLDivElement | null>(null);
274
-
275
- const resolvedItems = useMemo(() => resolveVisionBoardItems(items, overrides, visibleTags), [items, overrides, visibleTags]);
276
- const itemsById = useMemo(() => new Map(resolvedItems.map((item) => [item.id, item])), [resolvedItems]);
277
- const segments = useMemo(() => getVisionBoardSegments(connections ?? [], itemsById, slack), [connections, itemsById, slack]);
278
-
279
- useLayoutEffect(() => {
280
- engine.setOptions({
281
- dragLimit,
282
- dragStretch: VISION_BOARD_DEFAULTS.dragStretch,
283
- throwFactor: VISION_BOARD_DEFAULTS.throwFactor,
284
- itemSpring,
285
- stringSpring,
286
- });
287
- }, [dragLimit, itemSpring.stiffness, itemSpring.damping, stringSpring?.stiffness, stringSpring?.damping]);
288
-
289
- // Before paint, so a state change never shows the new markup with a stale transform.
290
- useLayoutEffect(() => {
291
- for (const item of resolvedItems) engine.setHome(item.id, item.x, item.y);
292
- }, [resolvedItems]);
293
-
294
- useLayoutEffect(() => {
295
- engine.setSegments(segments);
296
- }, [segments]);
297
-
298
- // CSS pixels per board unit, kept current so drags and transforms stay in step with the layout.
299
- useLayoutEffect(() => {
300
- engine.setBoard(boardEl);
301
- if (!boardEl) return;
302
- const measure = () => engine.setScale(boardEl.clientWidth / width);
303
- measure();
304
- const observer = new ResizeObserver(measure);
305
- observer.observe(boardEl);
306
- return () => observer.disconnect();
307
- }, [boardEl, width]);
308
-
309
- useEffect(() => () => engine.dispose(), []);
310
-
311
- return (
312
- <div
313
- ref={setBoardEl}
314
- className={cn('rel unsel', className)}
315
- style={{ aspectRatio: `${width} / ${height}`, ...style }}
316
- >
317
- <svg
318
- className="abs_full w_f h_f noclick"
319
- viewBox={`0 0 ${width} ${height}`}
320
- preserveAspectRatio="none"
321
- aria-hidden
322
- >
323
- {segments.map((segment) => {
324
- const from = itemsById.get(segment.from);
325
- const to = itemsById.get(segment.to);
326
- if (!from || !to) return null;
327
- return (
328
- <VisionBoardString
329
- key={segment.key}
330
- segment={segment}
331
- from={from}
332
- to={to}
333
- color={segment.color ?? stringColor ?? color}
334
- width={segment.width ?? stringWidth}
335
- engine={engine}
336
- />
337
- );
338
- })}
339
- </svg>
340
- {resolvedItems.map((item) => (
341
- <VisionBoardNode
342
- key={item.id}
343
- item={item}
344
- boardWidth={width}
345
- boardHeight={height}
346
- size={item.size ?? nodeSize}
347
- color={item.color ?? color}
348
- textPlacement={textPlacement}
349
- textWidth={textWidth}
350
- hoverText={(item.textVisibility ?? textVisibility) === 'hover'}
351
- draggable={item.draggable ?? draggable}
352
- engine={engine}
353
- />
354
- ))}
355
- </div>
356
- );
357
- },
358
- );
@@ -1,88 +0,0 @@
1
- import type { ReactNode } from 'react';
2
-
3
- /**
4
- * Types shared by the vision board component, its helpers, and callers that describe boards.
5
- */
6
-
7
- export type VisionBoardTextPlacement = 'right' | 'left' | 'top' | 'bottom';
8
-
9
- export type VisionBoardTextVisibility = 'always' | 'hover';
10
-
11
- export interface VisionBoardItem {
12
- /** Names the item for connections, overrides, and hover; defaults to its index in `items`. */
13
- id?: string;
14
- /** Center of the item in board units (the `width` × `height` design space of the board). */
15
- x: number;
16
- y: number;
17
- /** Photo filling the node. */
18
- image?: string;
19
- /** Custom node content (an SVG, an icon) centered in the node; ignored when `image` is set. */
20
- icon?: ReactNode;
21
- title?: string;
22
- text?: string;
23
- /** Shown as small pills under the texts; the board's `visibleTags` filters on them. */
24
- tags?: string[];
25
- /** Node diameter in CSS pixels; defaults to the board's `nodeSize`. */
26
- size?: number;
27
- /** Accent color of the node ring and its icon; strings leaving this item take it unless they set their own. */
28
- color?: string;
29
- /** Fade the item (and every string touching it) out; it keeps its place so it can come back. */
30
- hidden?: boolean;
31
- /** Side of the node the texts sit on; defaults to the board's `textPlacement`. */
32
- textPlacement?: VisionBoardTextPlacement;
33
- /** Overrides the board's `textVisibility` for this item. */
34
- textVisibility?: VisionBoardTextVisibility;
35
- /** Overrides the board's `draggable` for this item. */
36
- draggable?: boolean;
37
- }
38
-
39
- /** Per-item changes a board state applies on top of `items`: positions, visibility, colors, texts. */
40
- export type VisionBoardItemOverride = Partial<Omit<VisionBoardItem, 'id'>>;
41
-
42
- /** Overrides keyed by item id. */
43
- export type VisionBoardOverrides = Record<string, VisionBoardItemOverride>;
44
-
45
- /** An item with its overrides and the tag filter applied; `id` is always set. */
46
- export interface ResolvedVisionBoardItem extends Omit<VisionBoardItem, 'id' | 'hidden'> {
47
- id: string;
48
- hidden: boolean;
49
- }
50
-
51
- export interface VisionBoardConnection {
52
- /** Ids of the items the string runs through, in order; a string needs at least two. */
53
- items: string[];
54
- /** Sag of each stretch at rest as a fraction of its length; 0 draws it straight. Defaults to the board's `slack`. */
55
- slack?: number;
56
- /** Defaults to the color of the item each stretch leaves, then the board's `stringColor`. */
57
- color?: string;
58
- /** Stroke width in CSS pixels; defaults to the board's `stringWidth`. */
59
- width?: number;
60
- dashed?: boolean;
61
- hidden?: boolean;
62
- }
63
-
64
- /** One stretch of string between two neighbouring items of a connection. */
65
- export interface VisionBoardSegment {
66
- key: string;
67
- from: string;
68
- to: string;
69
- slack: number;
70
- color?: string;
71
- width?: number;
72
- dashed: boolean;
73
- hidden: boolean;
74
- }
75
-
76
- export interface VisionBoardSpring {
77
- /** Pull toward the rest position, per unit of distance. */
78
- stiffness: number;
79
- /** Resistance to velocity; below about `2 × √stiffness` the motion overshoots and bounces. */
80
- damping: number;
81
- }
82
-
83
- export interface VisionBoardPhysicsOptions {
84
- /** Spring that returns a released or relocated item to its place. */
85
- item?: Partial<VisionBoardSpring>;
86
- /** Spring on each string's bend, so the strings lag and wobble behind moving items; `false` keeps them taut. */
87
- string?: Partial<VisionBoardSpring> | false;
88
- }
@@ -1,208 +0,0 @@
1
- import { createDotGrid } from '../libs/dotGrid.ts';
2
- import { createImageTexture } from '../libs/texture.ts';
3
- import type { ImageTexture } from '../libs/texture.ts';
4
- import type { SceneContext, Scene, SceneSize } from '../libs/types.ts';
5
- import type { ResolvedDotGridOptions } from '../utils/dotGridSpecs.ts';
6
- import { easeOutCubic } from '../utils/easing.ts';
7
-
8
- /**
9
- * Types
10
- */
11
-
12
- export interface DotsAreaSceneParams extends ResolvedDotGridOptions {
13
- /** Image shown through the dots in place of their color, cover-fit to the area; null for the flat color. */
14
- imageUrl: string | null;
15
- /** `performance.now()` when the reveal timeline began (the area mounting), so a late-starting canvas joins it in step. */
16
- revealBegin: number;
17
- /** Height in CSS pixels of the fade to transparent along the bottom edge; 0 for none. Never fades the filled reveal state. */
18
- fadeBottom: number;
19
- }
20
-
21
- /*
22
- * Build the dots scene: one dot grid on a transparent canvas that a moving cursor throws
23
- * around, optionally opening with a reveal (the dots fill the area, optionally zooming the image
24
- * to 100% from mount, then shrink to size once the delay is up) or pulsing a few random dots.
25
- * Frames run on demand unless dots pulse: the scene asks for the next frame only while a reveal
26
- * or a throw is in progress, so an idle area costs nothing, and the pointer is only followed
27
- * once kicks can land. The reveal runs on the wall clock (ease-out cubic, so it moves from the
28
- * first frame and settles gently), since the runtime's clock only advances during frames.
29
- */
30
- export default function createDotsAreaScene(
31
- { gl, signal, invalidate, onDispose }: SceneContext,
32
- params: DotsAreaSceneParams,
33
- ): Scene<DotsAreaSceneParams> {
34
- const grid = createDotGrid(gl, params);
35
- let size: SceneSize = { width: 1, height: 1, pixelRatio: 1 };
36
- let overlay: ImageTexture | null = null;
37
- let overlayUrl: string | null = null;
38
- // The reveal timeline on the wall clock (ms): when it began (mount), when the zoom settles,
39
- // when the shrink starts (`delay` after mount, zoom or not), and when it ends; null when there
40
- // is no reveal.
41
- let revealWindow: [number, number, number, number] | null = null;
42
- let revealZoom = 1;
43
- // When the shrink actually began: the first frame at or after the delay, since dots only exist
44
- // once the canvas renders, so a delay shorter than the WebGL start-up waits for it.
45
- let shrinkBeganAt: number | null = null;
46
- let revealTimer: number | null = null;
47
- // The runtime clock as of the last frame, so pulsing restarted from `setParams` begins now.
48
- let pulseClock = 0;
49
- // Raw (un-eased) pointer in CSS pixels from the last frame, for its velocity.
50
- const previous: [number, number] = [0, 0];
51
- const pointerPx: [number, number] = [0, 0];
52
- const velocity: [number, number] = [0, 0];
53
- onDispose(() => {
54
- grid.dispose();
55
- overlay?.dispose();
56
- if (revealTimer !== null) clearTimeout(revealTimer);
57
- });
58
-
59
- /*
60
- * Let the dots pulse from this moment on (a continuous loop is needed for that), or hold
61
- * them still while a reveal is pending.
62
- */
63
- function startPulse(elapsed: number | null) {
64
- grid.setPulseStart(elapsed);
65
- scene.frameloop = elapsed !== null && grid.isPulsing() ? 'always' : 'demand';
66
- }
67
-
68
- /*
69
- * Whether a reveal is still holding or shrinking, so kicks must wait.
70
- */
71
- function isRevealing() {
72
- if (!revealWindow) return false;
73
- return shrinkBeganAt === null || performance.now() < shrinkBeganAt + (revealWindow[3] - revealWindow[2]);
74
- }
75
-
76
- /*
77
- * Start (or cancel) the reveal: fill the area now, zoom the image to 100% from mount if asked,
78
- * and let `update` drive the shrink once the delay is up. The zoom needs frames; otherwise the
79
- * hold is static and a timer wakes the loop for the shrink.
80
- */
81
- function scheduleReveal(reveal: ResolvedDotGridOptions['reveal'], begin: number) {
82
- if (revealTimer !== null) clearTimeout(revealTimer);
83
- revealTimer = null;
84
- if (!reveal) {
85
- revealWindow = null;
86
- grid.setReveal(1);
87
- grid.setOverlayZoom(1);
88
- return;
89
- }
90
- const zoomEnd = begin + (reveal.zoomOnMount !== 1 ? reveal.zoomDuration : 0);
91
- const start = begin + reveal.delay;
92
- revealWindow = [begin, zoomEnd, start, start + reveal.duration];
93
- revealZoom = reveal.zoomOnMount;
94
- shrinkBeganAt = null;
95
- grid.setReveal(0);
96
- grid.setOverlayZoom(revealZoom);
97
- if (revealZoom !== 1) invalidate();
98
- revealTimer = window.setTimeout(
99
- () => {
100
- revealTimer = null;
101
- invalidate();
102
- },
103
- Math.max(0, start - performance.now()),
104
- );
105
- }
106
-
107
- /*
108
- * Advance the reveal shrink for this frame; returns whether it is still running.
109
- */
110
- function updateReveal(elapsed: number) {
111
- if (!revealWindow) return false;
112
- const [begin, zoomEnd, start, end] = revealWindow;
113
- const now = performance.now();
114
- // The image zooms from `zoomOnMount` to 100% on its own clock, overlapping the hold and the
115
- // shrink however the durations fall.
116
- const zooming = now < zoomEnd;
117
- grid.setOverlayZoom(zooming ? revealZoom + (1 - revealZoom) * easeOutCubic((now - begin) / (zoomEnd - begin)) : 1);
118
- // The hold: nothing but the zoom to draw until the timer wakes the loop for the shrink.
119
- if (now < start) return zooming;
120
- // The shrink to dots, from the first frame the canvas draws at or after the delay.
121
- if (shrinkBeganAt === null) shrinkBeganAt = now;
122
- const progress = Math.min(1, (now - shrinkBeganAt) / (end - start));
123
- grid.setReveal(easeOutCubic(progress));
124
- if (progress >= 1) {
125
- revealWindow = null;
126
- grid.setOverlayZoom(1);
127
- // The image → dots intro is over; ambient pulsing may begin now.
128
- startPulse(elapsed);
129
- return false;
130
- }
131
- return true;
132
- }
133
-
134
- /*
135
- * Swap the overlay image; the dots keep their flat color until it decodes.
136
- */
137
- function loadOverlay(url: string | null) {
138
- if (url === overlayUrl) return;
139
- overlayUrl = url;
140
- overlay?.dispose();
141
- overlay = url
142
- ? createImageTexture(gl, {
143
- url,
144
- signal,
145
- onLoad: (loaded) => {
146
- if (loaded !== overlay) return;
147
- grid.setOverlay(overlay);
148
- invalidate();
149
- },
150
- })
151
- : null;
152
- grid.setOverlay(overlay);
153
- }
154
-
155
- /*
156
- * Pointer moves only matter once kicks can land.
157
- */
158
- function followsPointer() {
159
- return grid.isInteractive() && !isRevealing();
160
- }
161
-
162
- loadOverlay(params.imageUrl);
163
- grid.setFadeBottom(params.fadeBottom);
164
- scheduleReveal(params.reveal, params.revealBegin);
165
-
166
- const scene: Scene<DotsAreaSceneParams> = {
167
- // Pulsing is an ambient animation, so it needs continuous frames (the runtime still idles
168
- // to a lower rate and pauses off-screen); everything else runs on demand. It starts after
169
- // any reveal, from `startPulse`.
170
- frameloop: 'demand',
171
- followsPointer: followsPointer(),
172
- resize(nextSize) {
173
- size = nextSize;
174
- grid.resize(nextSize);
175
- },
176
- update({ pointer, delta, elapsed }) {
177
- pulseClock = elapsed;
178
- grid.setTime(elapsed);
179
- const revealing = updateReveal(elapsed);
180
- // The kick follows the actual cursor, not the eased one; y flips from UV space to CSS.
181
- pointerPx[0] = pointer.targetX * size.width;
182
- pointerPx[1] = (1 - pointer.targetY) * size.height;
183
- // The first frame after a pause has no delta, so it only records where the pointer is.
184
- velocity[0] = delta > 0 ? (pointerPx[0] - previous[0]) / delta : 0;
185
- velocity[1] = delta > 0 ? (pointerPx[1] - previous[1]) / delta : 0;
186
- previous[0] = pointerPx[0];
187
- previous[1] = pointerPx[1];
188
- const settling = grid.step(pointerPx, velocity, pointer.hover && !revealing, delta, elapsed);
189
- scene.followsPointer = followsPointer();
190
- if (revealing || settling) invalidate();
191
- },
192
- render() {
193
- grid.draw(true);
194
- },
195
- setParams(next) {
196
- grid.setOptions(next);
197
- loadOverlay(next.imageUrl);
198
- grid.setFadeBottom(next.fadeBottom);
199
- scheduleReveal(next.reveal, next.revealBegin);
200
- // A new reveal holds pulsing until it ends; otherwise pulsing may (re)start right away.
201
- startPulse(next.reveal ? null : pulseClock);
202
- scene.followsPointer = followsPointer();
203
- invalidate();
204
- },
205
- };
206
- if (!params.reveal) startPulse(0);
207
- return scene;
208
- }