@jsb188/gfx 1.1.11 → 1.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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +248 -54
  3. package/elements/Shapes.helpers.ts +204 -0
  4. package/elements/Shapes.hooks.ts +171 -0
  5. package/elements/Shapes.tsx +505 -0
  6. package/elements/Shapes.types.ts +81 -0
  7. package/elements/Stack.helpers.ts +42 -0
  8. package/elements/Stack.tsx +143 -0
  9. package/elements/Text.helpers.ts +45 -0
  10. package/elements/Text.hooks.ts +197 -0
  11. package/elements/Text.tsx +98 -0
  12. package/libs/dotGrid.helpers.ts +53 -0
  13. package/libs/dotGrid.ts +480 -77
  14. package/libs/effects/dotEffects.ts +136 -0
  15. package/libs/effects/effectQuad.ts +8 -2
  16. package/libs/pointer.ts +6 -0
  17. package/libs/runtime.ts +6 -4
  18. package/libs/types.ts +8 -1
  19. package/main.ts +2 -0
  20. package/modules/Carousel.helpers.ts +234 -0
  21. package/modules/Carousel.hooks.ts +520 -0
  22. package/modules/Carousel.tsx +135 -29
  23. package/modules/Dots.tsx +269 -0
  24. package/modules/DotsBoard.helpers.ts +388 -0
  25. package/modules/DotsBoard.hooks.ts +144 -0
  26. package/modules/DotsBoard.strings.ts +649 -0
  27. package/modules/DotsBoard.types.ts +240 -0
  28. package/modules/DotsBoardCanvas.hooks.ts +49 -0
  29. package/modules/DotsBoardCanvas.tsx +190 -0
  30. package/modules/DotsBoardElements.tsx +330 -0
  31. package/modules/Gallery.helpers.ts +32 -0
  32. package/modules/Gallery.hooks.ts +149 -0
  33. package/modules/Gallery.tsx +194 -0
  34. package/modules/GfxCanvas.tsx +10 -2
  35. package/modules/KineticHeader.helpers.ts +44 -0
  36. package/modules/KineticHeader.hooks.ts +206 -0
  37. package/modules/KineticHeader.tsx +305 -0
  38. package/modules/KineticHeader.types.ts +56 -0
  39. package/modules/ScrollSteps.hooks.ts +138 -0
  40. package/modules/ScrollSteps.tsx +7 -52
  41. package/package.json +30 -7
  42. package/scenes/Carousel.ts +99 -18
  43. package/scenes/DotsBoard.helpers.ts +12 -0
  44. package/scenes/DotsBoard.ts +245 -0
  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 +316 -47
  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
  57. package/tsconfig.json +0 -13
@@ -0,0 +1,388 @@
1
+ import type { CSSProperties } from 'react';
2
+ import type { AlignX, AlignY } from '../utils/align.ts';
3
+ import { getNearestDotGridCenter } from '../utils/dotGridSpecs.ts';
4
+ import type { DotStyle } from '../utils/dotGridSpecs.ts';
5
+ import type { Point } from '../utils/strings.ts';
6
+ import type {
7
+ DotsBoardBottomFade,
8
+ DotsBoardConnections,
9
+ DotsBoardCoordinate,
10
+ DotsBoardHole,
11
+ DotsBoardLength,
12
+ DotsBoardOutline,
13
+ DotsBoardSectionSpec,
14
+ DotsBoardStringOptions,
15
+ DotsBoardStringSpec,
16
+ DotsBoardStrings,
17
+ DotsStageContextValue,
18
+ ElementSize,
19
+ Offset,
20
+ Rect,
21
+ } from './DotsBoard.types.ts';
22
+
23
+ /**
24
+ * Constants
25
+ */
26
+
27
+ export const DOTS_STRING_DEFAULTS = {
28
+ color: 'rgba(0, 0, 0, 0.25)',
29
+ width: 1.5,
30
+ slack: 0.1,
31
+ maxSag: Number.POSITIVE_INFINITY,
32
+ spring: { stiffness: 150, damping: 30 },
33
+ fadeMs: 350,
34
+ tug: 4,
35
+ pull: 40,
36
+ };
37
+
38
+ /**
39
+ * Items
40
+ */
41
+
42
+ /*
43
+ * A stage coordinate in CSS pixels from the stage's start edge, for a stage `extent` long.
44
+ */
45
+ export function resolveDotsBoardCoordinate(value: DotsBoardCoordinate, extent: number) {
46
+ if (typeof value === 'number') return value;
47
+ if (value === 'center') return extent / 2;
48
+ return (Number.parseFloat(value) / 100) * extent;
49
+ }
50
+
51
+ /*
52
+ * The dot an item sits on, in board pixels: the requested point is taken from stage into board
53
+ * pixels, snapped to the nearest dot center of the board's grid, and nudged by `dx` / `dy`
54
+ * whole dots. The stage is measured, so a stage that moves as the flow content around it
55
+ * changes size keeps its items on the dots.
56
+ */
57
+ export function getDotsBoardItemDot(
58
+ item: { x: DotsBoardCoordinate; y: DotsBoardCoordinate; dx: number; dy: number },
59
+ stage: DotsStageContextValue,
60
+ grid: Required<DotStyle>,
61
+ boardWidth: number,
62
+ boardHeight: number,
63
+ ): Point {
64
+ const { size, spacing, alignX, alignY } = grid;
65
+ const x = stage.left + resolveDotsBoardCoordinate(item.x, stage.width);
66
+ const y = stage.top + resolveDotsBoardCoordinate(item.y, stage.height);
67
+ return {
68
+ x: getNearestDotGridCenter(x, alignX, size, spacing, boardWidth) + item.dx * spacing,
69
+ y: getNearestDotGridCenter(y, alignY, size, spacing, boardHeight) + item.dy * spacing,
70
+ };
71
+ }
72
+
73
+ /*
74
+ * The transform that hangs an item's content off its dot: the content's `anchorX` / `anchorY`
75
+ * edge (or its middle) sits on the dot, then it is shifted by `offsetX` / `offsetY` pixels
76
+ * (right / down positive).
77
+ */
78
+ export function getDotsBoardItemTransform(anchorX: AlignX, anchorY: AlignY, offsetX: number, offsetY: number) {
79
+ const axis = (align: AlignX | AlignY, offset: number) => {
80
+ if (align === 'left' || align === 'top') return `${offset}px`;
81
+ if (align === 'right' || align === 'bottom') return `calc(-100% + ${offset}px)`;
82
+ return `calc(-50% + ${offset}px)`;
83
+ };
84
+ return `translate(${axis(anchorX, offsetX)}, ${axis(anchorY, offsetY)})`;
85
+ }
86
+
87
+ /**
88
+ * Strings
89
+ */
90
+
91
+ /*
92
+ * Fill in the board's string settings.
93
+ */
94
+ export function resolveDotsBoardStrings(strings: DotsBoardStrings = {}) {
95
+ return {
96
+ color: strings.color ?? DOTS_STRING_DEFAULTS.color,
97
+ width: Math.max(0, strings.width ?? DOTS_STRING_DEFAULTS.width),
98
+ slack: Math.max(0, strings.slack ?? DOTS_STRING_DEFAULTS.slack),
99
+ maxSag: Math.max(0, strings.maxSag ?? DOTS_STRING_DEFAULTS.maxSag),
100
+ spring: strings.spring === false ? null : { ...DOTS_STRING_DEFAULTS.spring, ...strings.spring },
101
+ fadeMs: Math.max(0, strings.fadeMs ?? DOTS_STRING_DEFAULTS.fadeMs),
102
+ tug: strings.tug === false ? 0 : Math.max(0, strings.tug ?? DOTS_STRING_DEFAULTS.tug),
103
+ pull: strings.pull === false ? 0 : Math.max(0, strings.pull ?? DOTS_STRING_DEFAULTS.pull),
104
+ };
105
+ }
106
+
107
+ /*
108
+ * The connections as string specs, each keyed by the connection's key (its index unless given)
109
+ * so that a connection whose items change keeps its string: the engine re-pins the same string
110
+ * rather than drawing another.
111
+ */
112
+ export function getDotsBoardStringSpecs(
113
+ connections: DotsBoardConnections,
114
+ defaults: Omit<ReturnType<typeof resolveDotsBoardStrings>, keyof DotsBoardStringOptions>,
115
+ ): DotsBoardStringSpec[] {
116
+ return connections.map((entry, index) => {
117
+ const connection = Array.isArray(entry) ? { items: entry } : entry;
118
+ return {
119
+ key: connection.key ?? String(index),
120
+ items: connection.items,
121
+ color: connection.color ?? defaults.color,
122
+ width: Math.max(0, connection.width ?? defaults.width),
123
+ slack: Math.max(0, connection.slack ?? defaults.slack),
124
+ maxSag: Math.max(0, connection.maxSag ?? defaults.maxSag),
125
+ dashed: !!connection.dashed,
126
+ };
127
+ });
128
+ }
129
+
130
+ /**
131
+ * Sections
132
+ */
133
+
134
+ /*
135
+ * CSS for a stage coordinate or length (pixels, a percentage of the stage, or its middle), to
136
+ * place something against the stage before it has been measured.
137
+ */
138
+ function getDotsBoardCoordinateCss(value: DotsBoardCoordinate) {
139
+ if (typeof value === 'number') return `${value}px`;
140
+ return value === 'center' ? '50%' : value;
141
+ }
142
+
143
+ /*
144
+ * The fraction of a box's extent that lies before its anchor: none for the start edge, half
145
+ * for the middle, all of it for the end edge.
146
+ */
147
+ function getAnchorFraction(align: AlignX | AlignY) {
148
+ if (align === 'left' || align === 'top') return 0;
149
+ if (align === 'right' || align === 'bottom') return 1;
150
+ return 0.5;
151
+ }
152
+
153
+ /*
154
+ * How many dot spacings a section spans along one axis for `pixels` of room: rounded to the
155
+ * nearest spacing for a size that was asked for, or up for one that must hold content (`fit`),
156
+ * allowing half a pixel into the padding so a measurement a hair over a whole spacing does not
157
+ * add another; at least one.
158
+ */
159
+ function getDotsBoardSectionSpan(pixels: number, spacing: number, fit: boolean) {
160
+ return Math.max(1, fit ? Math.ceil((pixels - 0.5) / spacing) : Math.round(pixels / spacing));
161
+ }
162
+
163
+ /*
164
+ * A section's rectangle in board pixels, its corners on the board's dots. Each side spans
165
+ * whole dot spacings: the `width` / `height` asked for, rounded to the nearest spacing, or,
166
+ * without one, the content's size plus the padding on both sides, rounded up. The rectangle
167
+ * is then set with its `anchorX` / `anchorY` edge (or middle) on the section's point in the
168
+ * stage, its top-left corner snapped to the nearest dot and moved `dx` / `dy` whole dots, so
169
+ * the anchor lands within half a spacing of where it was asked for.
170
+ */
171
+ export function getDotsBoardSectionRect(
172
+ section: DotsBoardSectionSpec,
173
+ content: ElementSize,
174
+ stage: DotsStageContextValue,
175
+ grid: Required<DotStyle>,
176
+ boardWidth: number,
177
+ boardHeight: number,
178
+ ): Rect {
179
+ const { spacing } = grid;
180
+ const span = (length: DotsBoardLength | undefined, extent: number, measured: number) => {
181
+ const pixels = length == null ? measured + 2 * section.padding : resolveDotsBoardCoordinate(length, extent);
182
+ return getDotsBoardSectionSpan(pixels, spacing, length == null) * spacing;
183
+ };
184
+ const width = span(section.width, stage.width, content.width);
185
+ const height = span(section.height, stage.height, content.height);
186
+ const corner = getDotsBoardItemDot(
187
+ {
188
+ x: resolveDotsBoardCoordinate(section.x, stage.width) - getAnchorFraction(section.anchorX) * width,
189
+ y: resolveDotsBoardCoordinate(section.y, stage.height) - getAnchorFraction(section.anchorY) * height,
190
+ dx: section.dx,
191
+ dy: section.dy,
192
+ },
193
+ stage,
194
+ grid,
195
+ boardWidth,
196
+ boardHeight,
197
+ );
198
+ return { left: corner.x, top: corner.y, width, height };
199
+ }
200
+
201
+ /*
202
+ * Where a section's content goes in its stage, and how large. Without the section's
203
+ * rectangle (before the board has been measured, and on the server) it is placed by CSS alone
204
+ * from the point, size and dot moves asked for, so it shows about where it belongs from the
205
+ * first paint; with it, it lays out like a regular block from the rectangle's top-left
206
+ * corner, `padding` pixels in, so its own spacing always shows: only the outline snaps to the
207
+ * dots, never the content. Along an axis with a size the content fills the room inside the
208
+ * padding; along one without it keeps its own size, and the rounding up to whole dots is left
209
+ * as extra room at the far (right or bottom) edge.
210
+ */
211
+ export function getDotsBoardSectionContentStyle(
212
+ section: DotsBoardSectionSpec,
213
+ rect: Rect | null,
214
+ stage: Offset,
215
+ spacing: number,
216
+ ): CSSProperties {
217
+ const { width, height, padding } = section;
218
+ if (!rect) {
219
+ // In from the anchor edge by the padding; a middle anchor needs no inset.
220
+ const inset = (align: AlignX | AlignY) => (1 - 2 * getAnchorFraction(align)) * padding;
221
+ return {
222
+ left: getDotsBoardCoordinateCss(section.x),
223
+ top: getDotsBoardCoordinateCss(section.y),
224
+ width: width == null ? 'max-content' : `calc(${getDotsBoardCoordinateCss(width)} - ${2 * padding}px)`,
225
+ height: height == null ? undefined : `calc(${getDotsBoardCoordinateCss(height)} - ${2 * padding}px)`,
226
+ transform: getDotsBoardItemTransform(
227
+ section.anchorX,
228
+ section.anchorY,
229
+ inset(section.anchorX) + section.dx * spacing,
230
+ inset(section.anchorY) + section.dy * spacing,
231
+ ),
232
+ };
233
+ }
234
+ return {
235
+ left: rect.left - stage.left + padding,
236
+ top: rect.top - stage.top + padding,
237
+ width: width == null ? 'max-content' : rect.width - 2 * padding,
238
+ height: height == null ? undefined : rect.height - 2 * padding,
239
+ };
240
+ }
241
+
242
+ /*
243
+ * The dots at a rounded corner that the outline curves away from, for a section `rect` whose
244
+ * corners (dots) are rounded `radius` pixels: every dot of the grid in a corner's
245
+ * `radius` × `radius` square, where the rounding differs from the rectangle, that sits outside
246
+ * the curve by more than `clearance` pixels, so the stroke does not touch it. Those dots belong
247
+ * to the board around the section, not to its outline, and stay drawn.
248
+ */
249
+ function getDotsBoardCornerDots(rect: Rect, spacing: number, radius: number, clearance: number): Point[] {
250
+ const { left, top, width, height } = rect;
251
+ const steps = Math.floor(radius / spacing);
252
+ const dots: Point[] = [];
253
+ // Each corner, and the directions into the rectangle from it.
254
+ for (const [x, y, inX, inY] of [
255
+ [left, top, 1, 1],
256
+ [left + width, top, -1, 1],
257
+ [left, top + height, 1, -1],
258
+ [left + width, top + height, -1, -1],
259
+ ]) {
260
+ const centerX = x + inX * radius;
261
+ const centerY = y + inY * radius;
262
+ for (let column = 0; column <= steps; column++) {
263
+ for (let row = 0; row <= steps; row++) {
264
+ const dot = { x: x + inX * column * spacing, y: y + inY * row * spacing };
265
+ if (Math.hypot(dot.x - centerX, dot.y - centerY) - radius > clearance) dots.push(dot);
266
+ }
267
+ }
268
+ }
269
+ return dots;
270
+ }
271
+
272
+ /*
273
+ * The hole a section leaves in its layer's dots, in the layer's pixels (the layer rests
274
+ * `origin` pixels into the board). With an outline `lineWidth` pixels wide it is the rectangle
275
+ * grown by half a dot spacing, which takes in the dots on the outline too, so the stroke is
276
+ * drawn where they were rather than over them; where corners rounded `radius` pixels curve the
277
+ * stroke away from dots, those are kept (`keep`, see `getDotsBoardCornerDots`). Without an
278
+ * outline it is the rectangle shrunk by half a spacing, rounded concentrically, which takes in
279
+ * only the dots inside, so the dots on the edge still mark it out. Either way it stops halfway
280
+ * to the next row of dots. Null for a section one spacing across without an outline, which has
281
+ * no dots inside.
282
+ */
283
+ export function getDotsBoardHole(
284
+ rect: Rect,
285
+ origin: Offset,
286
+ grid: Required<DotStyle>,
287
+ radius: number,
288
+ lineWidth: number | null,
289
+ ): DotsBoardHole | null {
290
+ const { spacing, size } = grid;
291
+ const inLayer = { left: rect.left - origin.left, top: rect.top - origin.top, width: rect.width, height: rect.height };
292
+ const corner = Math.max(0, Math.min(radius, rect.width / 2, rect.height / 2));
293
+ const inset = lineWidth === null ? spacing / 2 : -spacing / 2;
294
+ const width = rect.width - 2 * inset;
295
+ const height = rect.height - 2 * inset;
296
+ if (width <= 0 || height <= 0) return null;
297
+ return {
298
+ left: inLayer.left + inset,
299
+ top: inLayer.top + inset,
300
+ width,
301
+ height,
302
+ radius: lineWidth === null ? Math.max(0, corner - inset) : 0,
303
+ keep: lineWidth === null || corner <= 0 ? [] : getDotsBoardCornerDots(inLayer, spacing, corner, size / 2 + lineWidth / 2),
304
+ // A kept dot's spot stays short of its neighbours and of the hole's edge.
305
+ keepRadius: spacing / 2 - 0.5,
306
+ };
307
+ }
308
+
309
+ /*
310
+ * SVG path data for a hole: a rectangle with corners rounded `radius` pixels (at most half its
311
+ * shorter side), to a hundredth of a pixel.
312
+ */
313
+ function getDotsBoardHolePath({ left, top, width, height, radius, keep, keepRadius }: DotsBoardHole) {
314
+ const n = (value: number) => Math.round(value * 100) / 100;
315
+ const r = Math.min(radius, width / 2, height / 2);
316
+ const arc = (dx: number, dy: number) => `a${n(r)} ${n(r)} 0 0 1 ${n(dx)} ${n(dy)}`;
317
+ const w = n(width - 2 * r);
318
+ const h = n(height - 2 * r);
319
+ let d =
320
+ r <= 0
321
+ ? `M${n(left)} ${n(top)}h${n(width)}v${n(height)}h${n(-width)}Z`
322
+ : `M${n(left + r)} ${n(top)}h${w}${arc(r, r)}v${h}${arc(-r, r)}h${-w}${arc(-r, -r)}v${-h}${arc(r, -r)}Z`;
323
+ // A circle around each kept dot, inside the hole: under the even-odd rule it cuts the dot back in.
324
+ const k = n(keepRadius);
325
+ for (const dot of keep)
326
+ d += `M${n(dot.x - keepRadius)} ${n(dot.y)}a${k} ${k} 0 1 0 ${n(2 * keepRadius)} 0a${k} ${k} 0 1 0 ${n(-2 * keepRadius)} 0Z`;
327
+ return d;
328
+ }
329
+
330
+ /*
331
+ * CSS `clip-path` that leaves a layer's holes out of its dots (and its hover glow): a
332
+ * rectangle reaching far past any layer's edges with every hole cut from it by the even-odd
333
+ * rule, so holes must not overlap (where two do, the dots show again); undefined with none.
334
+ */
335
+ export function getDotsBoardHolesClipPath(holes: Iterable<DotsBoardHole>) {
336
+ let d = '';
337
+ for (const hole of holes) d += getDotsBoardHolePath(hole);
338
+ return d ? `path(evenodd, 'M-100000 -100000H100000V100000H-100000Z${d}')` : undefined;
339
+ }
340
+
341
+ /*
342
+ * Fill in a section's outline from the strings' default color and width; null for none.
343
+ */
344
+ export function resolveDotsBoardOutline(outline: DotsBoardOutline | false | undefined) {
345
+ if (outline === false) return null;
346
+ return {
347
+ color: outline?.color ?? DOTS_STRING_DEFAULTS.color,
348
+ width: Math.max(0, outline?.width ?? DOTS_STRING_DEFAULTS.width),
349
+ dashed: !!outline?.dashed,
350
+ };
351
+ }
352
+
353
+ /*
354
+ * Keep fade stops nonnegative and ordered; an inverted or zero-width band becomes a hard stop.
355
+ */
356
+ export function resolveDotsBoardBottomFade(fade?: DotsBoardBottomFade): DotsBoardBottomFade | undefined {
357
+ if (!fade) return undefined;
358
+ const start = Math.max(0, fade.start);
359
+ const end = Math.min(start, Math.max(0, fade.end));
360
+ const fadeOutStart = Math.max(0, fade.fadeOut?.start ?? 0);
361
+ const fadeOut = fade.fadeOut ? { start: fadeOutStart, end: Math.min(fadeOutStart, Math.max(0, fade.fadeOut.end)) } : undefined;
362
+ return fade.mode && fade.mode !== 'color'
363
+ ? { mode: fade.mode, start, end, fadeOut, opacity: Math.min(1, Math.max(0, fade.opacity ?? 1)) }
364
+ : { ...fade, start, end, fadeOut };
365
+ }
366
+
367
+ /*
368
+ * Match the shader's linear blend with CSS stops measured upward from the full board bottom.
369
+ */
370
+ export function getDotsBoardFadeGradient(fade: { start: number; end: number }, from: string, to: string): string {
371
+ return `linear-gradient(to bottom, ${from} calc(100% - ${fade.start}px), ${to} calc(100% - ${fade.end}px))`;
372
+ }
373
+
374
+ /*
375
+ * Select CSS backdrop compositing; color mode stays inside the ordinary dot shader.
376
+ */
377
+ export function getDotsBoardBlendMode(fade?: DotsBoardBottomFade): 'difference' | 'soft-light' | 'overlay' | 'color-burn' | undefined {
378
+ if (!fade?.mode || fade.mode === 'color') return undefined;
379
+ return fade.mode === 'invert' ? 'difference' : fade.mode;
380
+ }
381
+
382
+ /*
383
+ * Share the blend source between WebGL and its CSS fallback. Burn needs gray because white is neutral.
384
+ */
385
+ export function getDotsBoardBlendColor(fade?: DotsBoardBottomFade): [number, number, number, number] {
386
+ const channel = fade?.mode === 'color-burn' ? 0.5 : 1;
387
+ return [channel, channel, channel, Math.min(1, Math.max(0, fade?.opacity ?? 1))];
388
+ }
@@ -0,0 +1,144 @@
1
+ import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useState } from 'react';
2
+ import type { RefObject } from 'react';
3
+ import { getDotsBoardHolesClipPath } from './DotsBoard.helpers.ts';
4
+ import type {
5
+ DotsBoardContextValue,
6
+ DotsBoardHole,
7
+ DotsLayerContextValue,
8
+ DotsStageContextValue,
9
+ ElementSize,
10
+ Offset,
11
+ } from './DotsBoard.types.ts';
12
+
13
+ /**
14
+ * Contexts
15
+ */
16
+
17
+ export const DotsBoardContext = createContext<DotsBoardContextValue | null>(null);
18
+ export const DotsLayerContext = createContext<DotsLayerContextValue | null>(null);
19
+ export const DotsStageContext = createContext<DotsStageContextValue | null>(null);
20
+
21
+ /*
22
+ * The enclosing board's grid, size and strings; throws outside a `<DotsBoard>`.
23
+ */
24
+ export function useDotsBoard() {
25
+ const board = useContext(DotsBoardContext);
26
+ if (!board) throw new Error('useDotsBoard must be used inside <DotsBoard>');
27
+ return board;
28
+ }
29
+
30
+ /*
31
+ * The enclosing layer (the board itself, or a `<DotsBoard.Sticky>`); throws outside a `<DotsBoard>`.
32
+ */
33
+ export function useDotsLayer() {
34
+ const layer = useContext(DotsLayerContext);
35
+ if (!layer) throw new Error('useDotsLayer must be used inside <DotsBoard>');
36
+ return layer;
37
+ }
38
+
39
+ /*
40
+ * The enclosing stage's rectangle; throws outside a `<DotsBoard.Stage>`.
41
+ */
42
+ export function useDotsStage() {
43
+ const stage = useContext(DotsStageContext);
44
+ if (!stage) throw new Error('useDotsStage must be used inside <DotsBoard.Stage>');
45
+ return stage;
46
+ }
47
+
48
+ /**
49
+ * Measuring
50
+ */
51
+
52
+ /*
53
+ * Track an element's size: measured synchronously on mount (so the first paint is already
54
+ * laid out) and again whenever a `ResizeObserver` sees it change. `version` is 0 until the
55
+ * first measurement and ticks on every observed change after. Select one axis to avoid updates
56
+ * from unrelated layout changes; the unobserved dimension stays zero.
57
+ */
58
+ export function useElementSize(ref: RefObject<HTMLElement | null>, axis: 'both' | 'width' | 'height' = 'both'): ElementSize {
59
+ const [size, setSize] = useState<ElementSize>({ width: 0, height: 0, version: 0 });
60
+ useLayoutEffect(() => {
61
+ const element = ref.current;
62
+ if (!element) return;
63
+ const measure = () => {
64
+ const rect = element.getBoundingClientRect();
65
+ const width = axis === 'height' ? 0 : rect.width;
66
+ const height = axis === 'width' ? 0 : rect.height;
67
+ setSize((prev) =>
68
+ prev.version > 0 && prev.width === width && prev.height === height ? prev : { width, height, version: prev.version + 1 },
69
+ );
70
+ };
71
+ measure();
72
+ // The border box, to match `getBoundingClientRect` and so a padding change counts too.
73
+ const observer = new ResizeObserver(measure);
74
+ observer.observe(element, { box: 'border-box' });
75
+ return () => observer.disconnect();
76
+ }, [ref, axis]);
77
+ return size;
78
+ }
79
+
80
+ /*
81
+ * The viewport's height in CSS pixels, following window resizes; 0 on the server and until the
82
+ * first measurement, so a layout sized to it can fall back to a default until then.
83
+ */
84
+ export function useViewportHeight() {
85
+ const [height, setHeight] = useState(0);
86
+ useLayoutEffect(() => {
87
+ const measure = () => setHeight(window.innerHeight);
88
+ measure();
89
+ window.addEventListener('resize', measure);
90
+ return () => window.removeEventListener('resize', measure);
91
+ }, []);
92
+ return height;
93
+ }
94
+
95
+ /*
96
+ * Where an element's top-left corner sits inside another, in CSS pixels, re-measured whenever
97
+ * `deps` change (the sizes of either, typically). Both rectangles are read in one layout pass,
98
+ * and the offset is scroll-independent, so it holds for an element pinned by `position: sticky`
99
+ * as long as `within` moves with it.
100
+ */
101
+ export function useElementOffset(
102
+ ref: RefObject<HTMLElement | null>,
103
+ within: RefObject<HTMLElement | null>,
104
+ deps: readonly unknown[],
105
+ ): Offset {
106
+ const [offset, setOffset] = useState<Offset>({ left: 0, top: 0 });
107
+ useLayoutEffect(() => {
108
+ const element = ref.current;
109
+ const container = within.current;
110
+ if (!element || !container) return;
111
+ const containerRect = container.getBoundingClientRect();
112
+ const rect = element.getBoundingClientRect();
113
+ const left = rect.left - containerRect.left;
114
+ const top = rect.top - containerRect.top;
115
+ setOffset((prev) => (prev.left === left && prev.top === top ? prev : { left, top }));
116
+ }, deps);
117
+ return offset;
118
+ }
119
+
120
+ /**
121
+ * Holes
122
+ */
123
+
124
+ /*
125
+ * The holes a layer's sections leave in its dots: `setHole` (stable, for the layer's context)
126
+ * adds, replaces or takes away a section's hole by key, and `clipPath` is the CSS that leaves
127
+ * them all out of the layer's dots and hover glow, undefined without any. Sections set their
128
+ * holes in layout effects, so the layer re-renders with them before the paint; nothing inside
129
+ * it re-renders, since its children and context values stay the same.
130
+ */
131
+ export function useDotsHoles() {
132
+ const [holes, setHoles] = useState<ReadonlyMap<string, DotsBoardHole>>(() => new Map());
133
+ const setHole = useCallback((key: string, hole: DotsBoardHole | null) => {
134
+ setHoles((prev) => {
135
+ if ((prev.get(key) ?? null) === hole) return prev;
136
+ const next = new Map(prev);
137
+ if (hole) next.set(key, hole);
138
+ else next.delete(key);
139
+ return next;
140
+ });
141
+ }, []);
142
+ const clipPath = useMemo(() => getDotsBoardHolesClipPath(holes.values()), [holes]);
143
+ return { clipPath, setHole };
144
+ }