@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,269 @@
1
+ import { cn } from '@jsb188/app/utils/string.ts';
2
+ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
3
+ import type { CSSProperties, ReactNode, RefObject } from 'react';
4
+ import { resolveDotGridOptions } from '../utils/dotGridSpecs.ts';
5
+ import type { DotStyle } from '../utils/dotGridSpecs.ts';
6
+ import { getDotsBoardStringSpecs, resolveDotsBoardStrings } from './DotsBoard.helpers.ts';
7
+ import {
8
+ DotsBoardContext,
9
+ DotsLayerContext,
10
+ useDotsBoard,
11
+ useDotsHoles,
12
+ useElementOffset,
13
+ useElementSize,
14
+ useViewportHeight,
15
+ } from './DotsBoard.hooks.ts';
16
+ import { DotsStringEngine } from './DotsBoard.strings.ts';
17
+ import type { StringSvgs } from './DotsBoard.strings.ts';
18
+ import type {
19
+ DotsBoardBottomFade,
20
+ DotsBoardConnections,
21
+ DotsBoardEffects,
22
+ DotsBoardImage,
23
+ DotsBoardIntro,
24
+ DotsBoardContextValue,
25
+ DotsBoardStrings,
26
+ DotsLayerContextValue,
27
+ Offset,
28
+ } from './DotsBoard.types.ts';
29
+ import { DotsBoardStage, DotsBoardItem, DotsBoardSection, DotsBoardFooter } from './DotsBoardElements.tsx';
30
+ import { DotsBoardCanvas } from './DotsBoardCanvas.tsx';
31
+ import { useContentMemo } from './GfxCanvas.hooks.ts';
32
+ import { useScrollStep } from './ScrollSteps.hooks.ts';
33
+
34
+ export { useDotsBoard, useDotsStage, useElementSize, useViewportHeight } from './DotsBoard.hooks.ts';
35
+ export type {
36
+ DotsBoardHover,
37
+ DotsBoardConnection,
38
+ DotsBoardBottomFade,
39
+ DotsBoardConnections,
40
+ DotsBoardEffects,
41
+ DotsBoardImage,
42
+ DotsBoardIntro,
43
+ DotsBoardCoordinate,
44
+ DotsBoardLength,
45
+ DotsBoardOutline,
46
+ DotsBoardStrings,
47
+ } from './DotsBoard.types.ts';
48
+
49
+ /*
50
+ * Paint a board layer beneath its content, with strings above the dots and hit paths above
51
+ * the content. Keep the content wrapper free of a stacking context so footer artwork can
52
+ * sit beneath the dots within the isolated board. Clipping belongs to the background, never to the sticky content's ancestors.
53
+ */
54
+ const DotsLayerPaint = (p: {
55
+ hostRef: RefObject<HTMLDivElement | null>;
56
+ origin: Offset | null;
57
+ clipPath: string | undefined;
58
+ fadeDotsBottom?: DotsBoardBottomFade;
59
+ onStringSvgs: (svgs: StringSvgs | null) => void;
60
+ children?: ReactNode;
61
+ }) => {
62
+ const { hostRef, origin, clipPath, fadeDotsBottom, onStringSvgs, children } = p;
63
+ const svgRef = useRef<SVGSVGElement>(null);
64
+ const hitSvgRef = useRef<SVGSVGElement>(null);
65
+ useLayoutEffect(() => {
66
+ const paths = svgRef.current;
67
+ const hits = hitSvgRef.current;
68
+ onStringSvgs(paths && hits ? { paths, hits } : null);
69
+ return () => onStringSvgs(null);
70
+ }, [onStringSvgs]);
71
+ return (
72
+ <>
73
+ <DotsBoardCanvas
74
+ hostRef={hostRef}
75
+ origin={origin}
76
+ clipPath={clipPath}
77
+ fadeDotsBottom={fadeDotsBottom}
78
+ />
79
+ <svg
80
+ ref={svgRef}
81
+ className='abs_full w_f h_f noclick'
82
+ aria-hidden
83
+ />
84
+ <div className='rel'>{children}</div>
85
+ <svg
86
+ ref={hitSvgRef}
87
+ className='abs_full w_f h_f noclick'
88
+ aria-hidden
89
+ />
90
+ </>
91
+ );
92
+ };
93
+
94
+ /*
95
+ * One grid for the page's animated background, anchored content, strings and sticky layers.
96
+ * Every layer inherits the image, effects and intro clock. The board never clips its content.
97
+ */
98
+ const DotsBoardRoot = memo(
99
+ (p: {
100
+ dots?: DotStyle;
101
+ connections?: DotsBoardConnections;
102
+ strings?: DotsBoardStrings;
103
+ /** Image sampled only inside its top region, then blended into the base dot color. */
104
+ image?: DotsBoardImage;
105
+ /** Full image beneath the dots in `<DotsBoard.Footer>`; its sizing belongs to page CSS. */
106
+ footerImageUrl?: string;
107
+ /** Shared cursor, click and ambient effects for every layer. */
108
+ effects?: DotsBoardEffects;
109
+ /** One page-wide appear animation; layers entering later join its current time. */
110
+ intro?: DotsBoardIntro;
111
+ /** Blend dots to a CSS color or background blend between distances from the bottom. */
112
+ fadeDotsBottom?: DotsBoardBottomFade;
113
+ children?: ReactNode;
114
+ className?: string;
115
+ style?: CSSProperties;
116
+ }) => {
117
+ const { dots, connections, strings, image, footerImageUrl, effects, intro, fadeDotsBottom, children, className, style } = p;
118
+ const ref = useRef<HTMLDivElement>(null);
119
+ const animation = useContentMemo(() => resolveDotGridOptions({ ...effects, dots, kick: effects?.kick ?? false }), [dots, effects]);
120
+ const grid = animation.dots;
121
+ const background = useContentMemo(() => ({ image, intro, hover: effects?.hover }), [image, intro, effects?.hover]);
122
+ const [begin] = useState(() => performance.now());
123
+ const size = useElementSize(ref);
124
+ const holes = useDotsHoles();
125
+
126
+ // The strings are drawn outside React; the engine lives as long as the board.
127
+ const [engine] = useState(() => new DotsStringEngine());
128
+ useEffect(() => () => engine.dispose(), [engine]);
129
+ const setStringSvgs = useCallback((svgs: StringSvgs | null) => engine.setBoardSvg(svgs), [engine]);
130
+ const resolvedStrings = useContentMemo(() => resolveDotsBoardStrings(strings), [strings]);
131
+ const specs = useContentMemo(() => getDotsBoardStringSpecs(connections ?? [], resolvedStrings), [connections, resolvedStrings]);
132
+ useEffect(() => {
133
+ const { spring, fadeMs, tug, pull } = resolvedStrings;
134
+ engine.setOptions({ spring, fadeMs, tug, pull });
135
+ }, [engine, resolvedStrings]);
136
+ useEffect(() => {
137
+ engine.setStrings(specs);
138
+ }, [engine, specs]);
139
+
140
+ const board = useMemo<DotsBoardContextValue>(
141
+ () => ({ ...size, grid, ref, strings: engine, animation, background, footerImageUrl, begin }),
142
+ [size, grid, engine, animation, background, footerImageUrl, begin],
143
+ );
144
+ // The board is its own layer, at the origin.
145
+ const layer = useMemo<DotsLayerContextValue>(
146
+ () => ({ ref, left: 0, top: 0, width: size.width, height: size.height, setHole: holes.setHole }),
147
+ [holes.setHole, size.width, size.height],
148
+ );
149
+
150
+ return (
151
+ <DotsBoardContext.Provider value={board}>
152
+ <DotsLayerContext.Provider value={layer}>
153
+ <div
154
+ ref={ref}
155
+ className={cn('rel', className)}
156
+ style={{ backgroundColor: 'inherit', ...style, isolation: 'isolate' }}
157
+ >
158
+ <DotsLayerPaint
159
+ hostRef={ref}
160
+ origin={null}
161
+ clipPath={holes.clipPath}
162
+ fadeDotsBottom={fadeDotsBottom}
163
+ onStringSvgs={setStringSvgs}
164
+ >
165
+ {children}
166
+ </DotsLayerPaint>
167
+ </div>
168
+ </DotsLayerContext.Provider>
169
+ </DotsBoardContext.Provider>
170
+ );
171
+ },
172
+ );
173
+
174
+ /*
175
+ * A part of a `<DotsBoard>` that pins in the viewport, `top` pixels down, for `lock` pixels of
176
+ * scrolling before it scrolls away with the rest of the board: the sticky element plus the
177
+ * spacer that gives it that distance. It is a layer of its own (`DotsLayerPaint`): it paints
178
+ * its own interactive dots, aligned to the board's grid so they are one pattern while it rests, and draws the strings of the items inside it, so its items, their strings and
179
+ * the dots under them all pin as one; strings between items outside it stay on the board. It
180
+ * is opaque (the page background) so the board's own dots, which scroll on behind it, do not
181
+ * show through. `lock` may list the pixels of each of several
182
+ * steps instead of one distance: `onStep` gets the step being scrolled through (0-based) as
183
+ * each begins, and `onProgress` the continuous 0..1 position along the whole lock on every
184
+ * scroll frame. With `pin` off it stays in the flow and scrolls with the page instead (no
185
+ * spacer, `top` and the step heights unused), its steps then spread evenly over its own height:
186
+ * each begins once that share of the layer has scrolled up past the middle of the viewport.
187
+ * One sticky per board, and no string between an item inside it and one outside it: a string
188
+ * draws with its first item, and would part company with the other while it is pinned.
189
+ */
190
+ const DotsBoardSticky = memo(
191
+ (p: {
192
+ /** Pixels from the viewport's top the layer pins at, e.g. a fixed nav's height. */
193
+ top?: number;
194
+ /** Pixels of scrolling the layer stays pinned for, or the pixels of each step of it in order. */
195
+ lock: number | number[];
196
+ /** `false` leaves the layer in the flow, scrolling with the page; only the number of `lock` steps counts then. */
197
+ pin?: boolean;
198
+ onStep?: (step: number) => void;
199
+ onProgress?: (progress: number) => void;
200
+ children?: ReactNode;
201
+ /** Applied to the pinned element, over its `bg` background. */
202
+ className?: string;
203
+ style?: CSSProperties;
204
+ }) => {
205
+ const { top = 0, lock, pin = true, onStep, onProgress, children, className, style } = p;
206
+ const steps = useContentMemo(() => (Array.isArray(lock) ? lock : [lock]), [lock]);
207
+ const board = useDotsBoard();
208
+ const trackRef = useRef<HTMLDivElement>(null);
209
+ const ref = useRef<HTMLDivElement>(null);
210
+ const size = useElementSize(ref);
211
+ const viewportHeight = useViewportHeight();
212
+
213
+ // Unpinned, the steps share the layer's height, measured from the viewport's middle.
214
+ const step = useScrollStep(trackRef, {
215
+ count: steps.length,
216
+ stepHeights: pin ? steps : steps.map(() => size.height / steps.length),
217
+ top: pin ? top : viewportHeight / 2,
218
+ onProgress,
219
+ });
220
+ const onStepRef = useRef(onStep);
221
+ useEffect(() => {
222
+ onStepRef.current = onStep;
223
+ }, [onStep]);
224
+ useEffect(() => {
225
+ onStepRef.current?.(step);
226
+ }, [step]);
227
+
228
+ // The track never moves in the board, so where it sits is where the pinned element rests.
229
+ const rest = useElementOffset(trackRef, board.ref, [board.version]);
230
+ const holes = useDotsHoles();
231
+ const layer = useMemo<DotsLayerContextValue>(
232
+ () => ({ ref, left: rest.left, top: rest.top, width: size.width, height: size.height, setHole: holes.setHole }),
233
+ [rest, holes.setHole, size.width, size.height],
234
+ );
235
+ // Take the strings while mounted; they follow the items here.
236
+ const { strings } = board;
237
+ const setStringSvgs = useCallback((svgs: StringSvgs | null) => strings.setLayerSvg(svgs, rest), [strings, rest]);
238
+
239
+ return (
240
+ <DotsLayerContext.Provider value={layer}>
241
+ <div ref={trackRef}>
242
+ <div
243
+ ref={ref}
244
+ className={cn(pin && 'sticky', 'rel bg', className)}
245
+ style={pin ? { top, ...style } : style}
246
+ >
247
+ <DotsLayerPaint
248
+ hostRef={ref}
249
+ origin={rest}
250
+ clipPath={holes.clipPath}
251
+ onStringSvgs={setStringSvgs}
252
+ >
253
+ {children}
254
+ </DotsLayerPaint>
255
+ </div>
256
+ {pin && <div style={{ height: steps.reduce((sum, height) => sum + height, 0) }} />}
257
+ </div>
258
+ </DotsLayerContext.Provider>
259
+ );
260
+ },
261
+ );
262
+
263
+ export const DotsBoard = Object.assign(DotsBoardRoot, {
264
+ Sticky: DotsBoardSticky,
265
+ Stage: DotsBoardStage,
266
+ Item: DotsBoardItem,
267
+ Section: DotsBoardSection,
268
+ Footer: DotsBoardFooter,
269
+ });
@@ -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
+ }