@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
package/README.md CHANGED
@@ -9,11 +9,12 @@ modules built on them.
9
9
 
10
10
  | Folder | Contents |
11
11
  | ---------------- | ------------------------------------------------------------------------------------------ |
12
- | `modules/` | React components: the `<GfxCanvas>` wrapper (with `PlaceholderImage` and the `useContentMemo` hook beside it), the components built on it (`Hero`, `DotsArea`, `VideoCarousel`), and the DOM-only `VisionBoard` and `ScrollSteps`; component-specific pure logic lives in `*.helpers.ts` next to its component |
12
+ | `modules/` | React components: the `<GfxCanvas>` wrapper (with `PlaceholderImage` and the `useContentMemo` hook beside it), the components built on it (`Hero`, `DotsBoard`, `VideoCarousel`), and the DOM-only `BlocksCarousel` (its gestures in `Carousel.hooks.ts`), `DotsBoard` anchoring (its pure math in `DotsBoard.helpers.ts`, contexts and measuring hooks in `DotsBoard.hooks.ts`, the string engine in `DotsBoard.strings.ts`, types in `DotsBoard.types.ts`) and `ScrollSteps`; component-specific pure logic lives in `*.helpers.ts` next to its component |
13
+ | `elements/` | Static illustration pieces with no WebGL: `<Shape>` (two-layer painted SVG shape with a grain or pixelate effect and rounded, straight or sketched edges; geometry in `Shapes.helpers.ts`, the state stepping in `Shapes.hooks.ts`), `<Marker>` (a disc or check mark on a halo, the pin `<DotsBoard.Item>` uses), `<PulsingMarker>` (the disc with glowing halos pulsing out of it, as Web Animations), `<Stack>` (children piled with small seeded rotations about one pivot; angles in `Stack.helpers.ts`) and `<TypedText>` (text retyped whenever it changes; the run in `Text.hooks.ts`) |
13
14
  | `scenes/` | Scene modules (`SceneFactory` default exports) that the components `import()` lazily; this is where OGL composition lives |
14
15
  | `libs/` | The OGL engine: runtime, pointer, pass chain, GLSL chunks, passes, textures, uniform helpers, dot grid |
15
- | `libs/effects/` | Photo effects (`imageEffects`), effect regions, the effect quad, the ripple simulation, and an `index.ts` that re-exports the effects and regions for lazy `import()` |
16
- | `utils/` | OGL-free helpers safe to import from route bundles: color parsing, easing curves, effect specs, dot grid specs |
16
+ | `libs/effects/` | Photo effects (`imageEffects`), effect regions, the effect quad, the ripple simulation, shared dot effect math (`dotEffects`), and an `index.ts` that re-exports the effects and regions for lazy `import()` |
17
+ | `utils/` | OGL-free helpers safe to import from route bundles: color parsing, easing curves, effect specs, dot grid specs and their CSS, reduced motion and springs, string curves, edge alignment keywords, the seeded PRNG |
17
18
 
18
19
  ## Entry points
19
20
 
@@ -21,10 +22,14 @@ modules built on them.
21
22
  | -------------------------------------------------- | ------------------------------------------------------------------------ |
22
23
  | `@jsb188/gfx/modules/GfxCanvas` | `<GfxCanvas>` wrapper: lazy loading, placeholder, error fallback, transparent overlays; `<PlaceholderImage>` cover-fit placeholder photo |
23
24
  | `@jsb188/gfx/modules/Hero` | Full-bleed photo hero with the cursor-following light field and hover/image effects |
24
- | `@jsb188/gfx/modules/DotsArea` | Transparent dot pattern a moving cursor throws aside; the dots bounce back home |
25
- | `@jsb188/gfx/modules/Carousel` | `<VideoCarousel>`: full-width row of videos, the centered one plain, the rest through an effect (pixelated by default) |
26
- | `@jsb188/gfx/modules/VisionBoard` | `<VisionBoard>`: draggable photo/icon items joined by springy strings, driven through states by `overrides` and a tag filter (no WebGL) |
25
+ | `@jsb188/gfx/modules/KineticHeader` | `<KineticHeader title slides>`: centered title with one `{word}` placeholder and a finite list of `{ text, images }` entries. The component `slideDuration` prop (default 5000ms) sets the fully visible display time for every slide, excluding image entrance and exit. Progress advances only during this display time, staying empty during entrance and full during exit. Optional `mouseOverSlideDuration` (a positive integer in milliseconds) changes the display speed on hover instead of pausing. It preserves the completed fraction of the slide and restores the normal speed on mouse leave; transition durations are unchanged. Without a valid value, hover still pauses. Navigation remains visible on hover, but the paused caption appears only when playback is actually paused. Keyboard focus still pauses. The first slide starts fully typed and still. On subsequent changes, the images and captions rise 32px and fade in together over `slideTransitionMs` (default 350ms; 0 disables entrance and exit), with gradual easing; the title and children stay stationary. Before each change, the outgoing images fade downward over 350ms in addition to the display duration; only after this exit finishes do the next text typing and image entrance begin. Images switch when their slide starts; display-time expiry starts exit even if typing is unfinished. Each image has `{ src, alt, altPosition?, altWidth?, altClassName?, offset?: { x, y }, width?, height? }`: offsets are pixels from the image area's center (negative x is left, negative y is up), and sizes are pixels. Supplying only width or only height preserves the natural aspect ratio; supplying both uses `img_cover` to crop to the box. With neither dimension, width defaults to 650. Captions default to the top at image width with an 8px gap. `altPosition` accepts `top`, `left`, `right`, or `bottom`; top/bottom use an 8px gap, and left/right use a 10px gap. `altWidth` sets caption width in pixels; `altClassName` adds classes to its container (for example, `a_r` for right alignment). Side captions align to the image top; top/bottom captions align to its left edge. Captions never shift or resize the image. Later images overlap earlier ones; the title stays above the image area. `imageAreaWidth` and `imageAreaHeight` set the maximum area width and fixed height (defaults: 1000 × 750 pixels). An optional `imageAreaAspectRatio` derives height only when `imageAreaHeight` is omitted. Images, captions, and offsets retain their exact pixel values at every container width; images may overflow the area. A thin line at the bottom of the image area tracks elapsed slide time. Without `mouseOverSlideDuration`, hovering or focusing the image area freezes only the fully visible display time and progress line; entrance and exit continue through hover and focus. Previous/next arrows appear at the progress bar edges with the paused caption while hovered or keyboard-focused. Navigation wraps around, runs exit before entrance, and resets display time; repeated input during transitions is ignored. Reduced motion switches manually without animations; fixed slides keep navigation disabled. A pointer remaining over the slide after entrance applies the hover speed, or pauses at the start of display time if no hover duration is supplied. Scrolling the image area offscreen or hiding the tab freezes all phases; returning resumes from that point. Native Web Animations interpolate the images and progress without a JavaScript frame loop. Optional `pausedLabelText` supplies a translated caption above the progress line only while paused. Loops back to the first entry after the last slide duration; a single entry stays visible without a progress line. Supports `typeMs`, `deleteMs`, `pauseMs`, `jitter`, `slideDuration`, `slideTransitionMs`, and styling props. Reduced motion keeps the current complete entry still (the first entry on initial load); changing the list restarts the sequence. Only the current slide mounts its images, so later slides are not preloaded. No WebGL. |
26
+ | `@jsb188/gfx/modules/Dots` | `<DotsBoard>`: one animated grid, hero image region, anchored `Stage` / `Item` / `Section` content, connecting strings and interactive `Sticky` layers |
27
+ | `@jsb188/gfx/modules/Gallery` | `<GalleryThumbs items>`: fixed halftone video thumbnails with enlarged native previews on pointer hover or keyboard focus. Items contain `{ videoUrl, title? }` with translated captions; optional `count` repeats them and `thumbnailWidth` sets their width (default 200). Each source loads only when its thumbnail enters view or becomes active. Paused thumbnails render on demand, and their opacity changes only while the gallery and tab are visible. Active videos pause when the gallery or tab is hidden. Preview bounds follow viewport changes; thumbnail geometry stays fixed. |
28
+ | `@jsb188/gfx/modules/Carousel` | `<VideoCarousel>`: full-width row of videos, the centered one plain, the rest through an effect (pixelated by default); `<BlocksCarousel>`: a row of any blocks dragged or scrolled sideways, snapping to the nearest block when the gesture ends (no WebGL) |
27
29
  | `@jsb188/gfx/modules/ScrollSteps` | `<ScrollSteps>`: a sticky stage whose step advances as the page scrolls; `<ScrollStepFade>` fades content in on each step (no WebGL) |
30
+ | `@jsb188/gfx/elements/Text` | `<TypedText text caret typingClassName typeMs deleteMs pauseMs jitter>`: text retyped whenever it changes (cleared, or deleted a character at a time with `deleteMs`, then the new text typed at a human's uneven pace), a change mid-retype waiting for the running one to finish and only the latest text being typed then; `useTypedText` is the hook behind it (no WebGL) |
31
+ | `@jsb188/gfx/elements/Stack` | `<Stack spread alignX alignY originX originY seed items>`: its children piled in one spot (centered in the pile's box by default), each turned by a small seeded angle about one pivot point of that box, first at the bottom, with `items` setting any one's angle or pixel shift; sized by its biggest item |
32
+ | `@jsb188/gfx/elements/Shapes` | `<Shape state>`: a flat `baseColor` layer and a gradient `color` layer, each painted in as one brush stroke with a grain or pixelate `effect` as `state` goes `empty` → `base` → `active` (and out again the other way; a sweep always finishes before the next starts); `rounded` / `straight` / `sketch` edge; `shape` is a built-in name or a custom `{ d, viewBox }` icon silhouette, and `effect` `hatch` prints it like a woodcut; `reveal` starts it empty and paints it in on mount or on scrolling into view |
28
33
  | `@jsb188/gfx/libs/types` | Scene contract types; safe to import without loading the engine |
29
34
  | `@jsb188/gfx/libs/chain` | `PassChain`, `createPassProgram`, `disposeTexture`, `disposeRenderTarget` |
30
35
  | `@jsb188/gfx/libs/uniforms` | `UniformValues` type plus `setVec2` / `setVec3`, which write vector uniforms in place |
@@ -36,12 +41,17 @@ modules built on them.
36
41
  | `@jsb188/gfx/libs/effects/imageEffects` | Hover/photo effects spliced into an image pass, plus `createImageEffects` |
37
42
  | `@jsb188/gfx/libs/effects/effectRegion` | `createEffectRegion` — per-pixel masks (split/circle/rect/path/image) that limit an effect group |
38
43
  | `@jsb188/gfx/libs/effects/effectQuad` | `createEffectQuad` — draw a cover-fit image through effects into any rectangle of a transparent canvas |
44
+ | `@jsb188/gfx/libs/effects/dotEffects` | Shared GLSL evaluator and uniform helpers for click, pulse, and resting dot effects |
39
45
  | `@jsb188/gfx/libs/effects/ripple` | `RippleSimulation` — cursor-driven wave equation on a ping-pong buffer |
40
46
  | `@jsb188/gfx/libs/runtime` | `createGfxRuntime`; the wrapper imports this for you |
41
47
  | `@jsb188/gfx/utils/color` | `hexToRgb`, `mixRgb`, `scaleRgb`, `cssColorToRgb` for color uniforms |
42
48
  | `@jsb188/gfx/utils/easing` | `easeOutCubic`, `easeInOutCubic` for JavaScript-driven reveals and fades (no OGL) |
49
+ | `@jsb188/gfx/utils/motion` | `prefersReducedMotion`, and the damped spring integrator (`springBodyAt`, `stepSpring`, `snapSpring`) behind the board's strings (no OGL) |
50
+ | `@jsb188/gfx/utils/strings` | The curve of a string hung between two points: `getStringRestControl`, `getQuadraticPoint`, `buildStringPath` (no OGL) |
51
+ | `@jsb188/gfx/utils/align` | `AlignX` / `AlignY` edge keywords shared by the dot grid, `<Stack>` and `<DotsBoard.Item>` |
43
52
  | `@jsb188/gfx/utils/imageEffectSpecs` | Effect names, option types, `normalizeImageEffectSpecs` (no OGL) |
44
- | `@jsb188/gfx/utils/dotGridSpecs` | Dot grid options, defaults, and a matching SVG tile for a CSS fallback (no OGL) |
53
+ | `@jsb188/gfx/utils/dotEffectSpecs` | `DOT_EFFECTS`, `DOT_SHAPES`, shared effect types/defaults, and `resolveDotEffectOptions` (no OGL) |
54
+ | `@jsb188/gfx/utils/dotGridSpecs` | Dot grid options, defaults, a matching SVG tile and the CSS mask style that draws the grid at rest (no OGL) |
45
55
 
46
56
  Only `modules/*`, `libs/types`, and `utils/*` are safe to import from route bundles (plus
47
57
  `import type` from anywhere). Everything else pulls in OGL and must stay behind the scene
@@ -76,7 +86,7 @@ export const MyHero = () => {
76
86
  - `style` / `className`: size the outer container. Block mode (the default) is `rel w_f ap_1`,
77
87
  a full-width square; override `aspectRatio` or give an explicit height through `style`.
78
88
  - `fill`: stretch over the nearest positioned ancestor (`abs_full`) instead, for a background or
79
- an overlay; the hero, dots area, and carousel use this inside their own `rel of` container.
89
+ an overlay; hero and carousel clip their containers, while a dots board clips only its background layers.
80
90
  - Params built from inline arrays or objects (effect specs, option groups) should be memoized
81
91
  by content with `useContentMemo` from `modules/GfxCanvas.hooks.ts`, so a caller re-creating
82
92
  them each render does not call `setParams` each render.
@@ -214,13 +224,13 @@ rectangle, so several images with the same effects share one program. Effects wi
214
224
  state (`ripple`, `bokeh`) are not supported in a quad; stateless ones (`pixelate`, the color
215
225
  effects, the barrel family, ...) are.
216
226
 
217
- `<VideoCarousel items focusedContentWidth>` lays its videos out edge to edge across the full
218
- width of its container and clips whatever falls outside (the page never scrolls sideways). The
219
- focused slide sits centered in a box `focusedContentWidth` wide holding its `iconName`, `title`,
220
- and `description` in a text area `textAreaHeight` tall (default 120) above the plain video; every
221
- other slide shows only its video at its own `width × height`, through `effect` (`'pixelate'` by
222
- default; any `ImageEffectSpec` list), under an empty text area of the same height, so videos keep
223
- their vertical position when focus moves. Clicking a slide, or changing `focusedIndex` /
227
+ `<VideoCarousel items textAreaWidth>` lays its videos out edge to edge across the full
228
+ width of its container and clips whatever falls outside (the page never scrolls sideways). Every
229
+ slide is its video at its own `width × height`, `gap` apart and top-aligned on a track as tall as
230
+ the tallest; the focused one sits centered and plain, and every other one shows through `effect`
231
+ (`'pixelate'` by default; any `ImageEffectSpec` list). Above the track, a fixed text area
232
+ `textAreaWidth` wide and `textAreaHeight` tall (default 120), independent of the videos' sizes,
233
+ shows the focused item's `iconName`, `title`, and `description`. Clicking a slide, or changing `focusedIndex` /
224
234
  `onFocusedIndexChange`, moves focus: the slides glide over `transitionMs` while the effect eases
225
235
  in on the slide that lost focus and out on the one that gained it. One transparent canvas covers
226
236
  the carousel; each frame the scene reads every `<video>`'s `getBoundingClientRect()` and redraws
@@ -229,36 +239,45 @@ clipped away entirely are skipped. The `<video>` elements (muted, looping, inlin
229
239
  stay in the DOM underneath — they decode the frames and are what shows without WebGL. Each slide
230
240
  is its own memoized `CarouselSlide`, so a carousel re-render (hover, autoplay) neither re-renders
231
241
  untouched slides nor re-registers their videos. The endless-track arithmetic lives in
232
- `modules/Carousel.helpers.ts`. Choose `focusedContentWidth` responsively at the call site; it is
233
- not clamped to the container.
234
-
235
- ## Vision board
236
-
237
- `<VisionBoard items connections width height>` is plain DOM: absolutely positioned items over one
238
- SVG of strings, no canvas. `width` × `height` is the design space the item coordinates live in;
239
- the board keeps that aspect ratio at any CSS width, so positions scale while node sizes and texts
240
- stay in pixels. Each item needs only `x` / `y`; `image` or `icon` fills the node, and `title`,
241
- `text`, and `tags` sit on the `textPlacement` side, always or on hover (`textVisibility`). Ids
242
- default to the index. A connection is a chain of item ids: each stretch is a quadratic curve that
243
- sags by `slack` (0 draws it straight), takes the color of the item it leaves, and may be `dashed`.
244
-
245
- Items drag: free up to `dragLimit` board units from home, rubber-banding beyond it, and spring back
246
- with a bounce on release (a fast release throws them). Strings have their own spring on the bend
247
- (`physics.string`), so they lag and wobble behind moving items; `physics.item` tunes the item spring.
248
-
249
- The board is driven by `overrides` (item id → any item fields): switching to another overrides
250
- object springs items to their new places, fades hidden ones out, and transitions colors, so
251
- buttons or a scroll position can step the board through states. `visibleTags` hides tagged items
252
- carrying none of the tags; untagged items (a hub) always show. All motion runs in one
253
- requestAnimationFrame loop outside React (`modules/VisionBoard.helpers.ts`) that stops when nothing
254
- moves, writing transforms and path data straight to the DOM; the markup carries the rest state, so
255
- server output shows the finished board, and reduced motion snaps instead of springing.
256
-
257
- `<ScrollSteps count stepHeight stageHeight top>{(step) => …}</ScrollSteps>` is the scroll side: a
258
- track `count × stepHeight` taller than its sticky stage, whose render prop re-renders only when
259
- the step changes (`onProgress` gets the continuous 0..1 for parallax). The scroll listener attaches
260
- only while the track is near the viewport. `<ScrollStepFade step>` fades its content in on each
261
- change. See `HomeWorkflowStory` in marketday's `home-test.tsx` for the two together.
242
+ `modules/Carousel.helpers.ts`. Choose `textAreaWidth` responsively at the call site; it is
243
+ clamped to the container's width.
244
+
245
+ ## Blocks carousel
246
+
247
+ `<BlocksCarousel gap align index defaultIndex onIndexChange transitionMs lock contentOffset selectableText>` is a plain DOM row
248
+ of its children: each block keeps its own width, every one is stretched to the tallest, and
249
+ whatever falls past the container's edges is clipped. The visitor drags the track with any
250
+ pointer (mouse, pen, or a sideways finger; vertical pans still scroll the page) or scrolls it
251
+ sideways with a wheel or trackpad (vertical wheels pass through to the page). When the drag or
252
+ the scroll ends, the track glides over `transitionMs` (default 600) to the nearest snap position:
253
+ a block's left edge at the container's left edge (`align='start'`, the default), or its middle at
254
+ the container's middle (`'center'`). The track stops at its ends, so the last blocks share the
255
+ end position and nothing loops or moves on its own. A drag past an end gives with rubber-band
256
+ resistance and springs back; a flick always leaves the current block; a wheel notch too short
257
+ to reach the next block still advances one, so a mouse wheel is never stuck. A press that
258
+ moves less than a few pixels is a click on the block, so blocks can hold buttons and links; once
259
+ it becomes a drag, the click the browser fires at release is swallowed. With `selectableText`
260
+ (the default) a mouse or pen press on text selects it as anywhere else on the page, and the drag
261
+ starts from everything else (blank space, images, links, buttons); the cursor is an I-beam over
262
+ text and an open hand elsewhere. On touch a sideways swipe drags and a long press selects; form
263
+ fields are never dragged from, and a sideways wheel over a block's own scroller scrolls that
264
+ scroller. Keyboard focus landing
265
+ in a clipped block brings that block into view. Padding on the container shows the neighbouring
266
+ blocks under it. The track and the cursor are written to the DOM directly, never through React
267
+ state, so no gesture re-renders anything; the gestures are `useBlocksCarousel` in `modules/Carousel.hooks.ts`,
268
+ and the snap arithmetic (`getBlockSnapOffsets`, `getSettleIndex`, the rubber band, the wheel
269
+ units) is in `modules/Carousel.helpers.ts`.
270
+
271
+ ## Scroll steps
272
+
273
+ `<ScrollSteps count stepHeight stageHeight top>{(step) => …}</ScrollSteps>` is a scroll-driven
274
+ stage: a track `count × stepHeight` taller than its sticky stage, whose render prop re-renders
275
+ only when the step changes (`onProgress` gets the continuous 0..1 for parallax). The scroll
276
+ listener attaches only while the track is near the viewport. `<ScrollStepFade step>` fades its
277
+ content in on each change. `useScrollStep(ref, { count, stepHeight, stepHeights, top,
278
+ onProgress })` is the hook behind it, which `<DotsBoard.Sticky>` uses too. `useInView(ref, { once,
279
+ rootMargin, threshold })` says whether an element is in the viewport (latching after the first
280
+ sighting with `once`), which `<Shape reveal="view">` uses to paint itself in on scroll.
262
281
 
263
282
  ## Effect regions
264
283
 
@@ -279,6 +298,124 @@ round. Every position accepts `[x, y]` or `'pointer'`, and every shape takes `so
279
298
  | `path` | `d` (SVG path data), `viewBox` (default 100×100), `position`, `size` (omit to cover the canvas); rasterized to a mask texture, feathered by `softness` |
280
299
  | `image` | `url` (grayscale mask), `position`, `size` (omit to cover the canvas) |
281
300
 
301
+ ## Dots board
302
+
303
+ `<DotsBoard>` is the single public container for the homepage's background and anchored
304
+ content. `DotsBackground` and the separate CSS `hover` lens have been retired. Import
305
+ `DotsBoard`, `useDotsBoard`, `useDotsStage`, `useElementSize`, and `useViewportHeight` from
306
+ `@jsb188/gfx/modules/Dots`.
307
+
308
+ ```tsx
309
+ <DotsBoard
310
+ dots={{ shape: 'rounded_square', size: 2, spacing: 20, color: '#E0E0E0', alignY: 1 }}
311
+ image={{ src: '/hero.jpg', height: 1200, fade: 250 }}
312
+ footerImageUrl='/footer.jpg'
313
+ effects={{
314
+ kick: { radius: 225, strength: 0.2 },
315
+ thrown: { opacity: 0, scale: 15 },
316
+ click: { effect: 'ripple', radius: 300, width: 100, duration: 1500, scale: 3 },
317
+ pulse: { count: 75, interval: 6000, duration: 3000, scale: 3 },
318
+ }}
319
+ intro={{ initialSize: 2, peakSize: 4, delay: 250, duration: 1000 }}
320
+ fadeDotsBottom={{ start: 500, end: 400, color: 'rgba(0,0,0,.025)' }}
321
+ connections={connections}
322
+ strings={{ color: '#F0F0F0', width: 4, pull: 30 }}
323
+ >
324
+ <HomeHero />
325
+ <DotsBoard.Sticky top={40} lock={[400, 900]}>
326
+ <DotsBoard.Stage height={800}>
327
+ <DotsBoard.Item id='first' x='center' y={20}>Content</DotsBoard.Item>
328
+ </DotsBoard.Stage>
329
+ </DotsBoard.Sticky>
330
+ <DotsBoard.Stage height={400}>
331
+ <DotsBoard.Section x='center' y={20} width={600}>Content without dots behind it</DotsBoard.Section>
332
+ </DotsBoard.Stage>
333
+ <DotsBoard.Footer>
334
+ <MarketdayFooter disableBackground />
335
+ </DotsBoard.Footer>
336
+ </DotsBoard>
337
+ ```
338
+
339
+ - `footerImageUrl` paints a full background image inside `DotsBoard.Footer`, underneath the
340
+ interactive dots. The footer content sets its height through normal flow, including on the
341
+ server. Page CSS styles `[data-dots-footer-background]` for responsive image sizing and the
342
+ backing color. Keep `Footer` directly in the board's flow, outside sticky layers or wrappers
343
+ that create a stacking context. The root isolates its layers; content wrappers must not add
344
+ a stacking context between the footer artwork and the root. Disable the nested footer's own
345
+ background so the dots remain visible, and omit `fadeDotsBottom` to keep the normal dot colors to the bottom.
346
+ - `dots` defines one shared grid: shape, size, spacing, color, opacity and alignment. Use a
347
+ top pixel anchor such as `alignY: 1` to keep its rows stable as page height changes.
348
+ - `image: { src, height, fade }` cover-fits a photo to the board's top `height` CSS pixels.
349
+ Its final `fade` pixels blend into `dots.color`. This changes only the base color, never
350
+ interaction strength or dot opacity. Layers below the region do not load its texture.
351
+ - `effects: { hover, kick, thrown, click, pulse, rest }` configures the shared GPU effects described
352
+ below. Omitted effects are disabled, including cursor kicks. There is no second CSS hover
353
+ renderer underneath the animated dots. `hover: { color, radius, fade }` tints dots even under a
354
+ stationary pointer; `color` supports CSS variables, `radius` defaults to 175px, and `fade: false`
355
+ keeps the tint solid within that radius. Image-colored dots
356
+ blend into the active hover tint through the image fade; full-strength image pixels retain
357
+ their image colors. Pulse count is per layer.
358
+ - `intro: { delay, duration, initialSize, peakSize }` grows dots once on the board's clock.
359
+ Defaults are 0ms delay, 1000ms duration, zero initial size and the resting size as peak.
360
+ A late-loading or newly visible layer joins the current time instead of replaying the intro.
361
+ - `fadeDotsBottom: { start, end, color }` blends the final dot color (after image and hover
362
+ tints) over a band measured upward from the board's bottom in CSS pixels. For example,
363
+ `start: 500, end: 400` leaves dots unchanged above 500px, blends over the next 100px, and
364
+ holds `color` from 400px through the bottom. CSS colors, alpha and theme variables work;
365
+ use `transparent` to fade out. Equal stops produce a hard transition. Stops are clamped
366
+ to nonnegative values, with `end` at most `start`. Motion and scale effects continue;
367
+ sticky layers do not inherit this page-bottom color blend. The footer artwork is unaffected.
368
+ - Background blend modes use `fadeDotsBottom: { start: 900, end: 800, mode: 'soft-light', opacity: 0.4 }`.
369
+ Choose `'soft-light'` for gentle brightening, `'overlay'` for stronger contrast, or `'invert'`
370
+ for CSS difference inversion. These three blend white dots with the actual backdrop.
371
+ Use `'color-burn'` to darken the backdrop colors with neutral gray dots (50% RGB); white
372
+ would have no effect in this mode. All four modes choose their source internally; omit
373
+ `color`. `opacity` defaults to 1 and is clamped to 0..1. Omit `mode` (or use `'color'`) with
374
+ `color` to retain the color blend. These CSS modes share one additional canvas bounded to
375
+ the bottom band and lazy-loaded near it; normal colors fade out while blended dots fade in.
376
+ Both surfaces retain motion, scale, clicks and the shared animation clock. The board inherits
377
+ its parent's background color to provide an opaque blending backdrop; footer artwork stays
378
+ beneath the dots, and text/buttons stay above them.
379
+ - Add `fadeOut: { start: 500, end: 350 }` inside `fadeDotsBottom` to independently fade dots
380
+ to transparent from 500px to 350px above the board bottom, keeping the final 350px dot-free.
381
+ This works with every mode, including `color-burn`, and masks animated dots and the static
382
+ fallback equally. The image and footer content remain visible. Stops are clamped just like
383
+ the color blend range; omitting `fadeOut` keeps dots visible through the bottom.
384
+ - `Stage` reserves its `height` in normal flow and measures its position in its owning layer.
385
+ `useDotsStage()` exposes board coordinates and `ready` after measurement.
386
+ - `Item` snaps `x` / `y` (CSS pixels, percentages or `'center'`) to the nearest board dot,
387
+ then shifts by `dx` / `dy` whole dots. `anchorX` / `anchorY` and `offsetX` / `offsetY`
388
+ place its content relative to that dot. Its optional `id` connects it to strings; `marker`
389
+ defaults to a `Marker`, or accepts `null`. Unmeasured items stay hidden.
390
+ - `Section` snaps a rectangle to the grid and cuts it out of the layer's background, including
391
+ moving dots and the static fallback. `width` / `height` accept pixels or percentages;
392
+ omitted dimensions fit measured content plus `padding` (one spacing by default). `radius`
393
+ rounds the corners. `outline` accepts `{ color, width, dashed }`, or `false` to retain edge
394
+ dots. The outline is static; section cutouts must not overlap.
395
+ - `connections` lists item IDs per string, or `{ key, items, color, width, slack, maxSag, dashed }`.
396
+ `strings` supplies defaults plus `spring`, `fadeMs`, `tug`, and `pull`. Strings are still
397
+ SVG paths with spring motion and pointer hit paths; background rendering does not own them.
398
+ - `Sticky` pins a layer at `top` for `lock` CSS pixels (or an array of phase distances).
399
+ `onStep` and `onProgress` report scrolling; `pin={false}` keeps the section in normal flow.
400
+ The layer inherits the board's effects and grid, and carries dots, items and strings together.
401
+ Its opaque `bg` hides scrolling dots underneath. Keep a connection's items within one layer;
402
+ the homepage uses one sticky layer per board.
403
+
404
+ Internally, `Dots.tsx` composes the board and sticky layers. Anchoring components live in
405
+ `DotsBoardElements.tsx`; measurement and context in `DotsBoard.hooks.ts`; pure layout math in
406
+ `DotsBoard.helpers.ts`; string animation in `DotsBoard.strings.ts`. `DotsBoardCanvas.tsx`
407
+ provides the shared renderer and CSS fallback, using `useDotsBoardView` to move a canvas
408
+ window through the layer without React scroll updates. Only the background is clipped, so
409
+ sticky content retains the document's scroll context.
410
+
411
+ Each layer's framebuffer is at most the viewport height plus 512px of overscan, capped by
412
+ its own height. The logical grid's small spring texture persists across scrolls; scrolling
413
+ changes projection, not grid layout. Canvas dimensions never scale with the full page height.
414
+ The scene (`scenes/DotsBoard.ts`) shares wall-clock timing across layers and maps board clicks
415
+ into each layer, including nearby clicks outside its edges. Reduced motion disables the intro,
416
+ kicks, pulses and clicks. Before hydration or without WebGL, CSS draws the same image region,
417
+ base dots, fade and section cutouts. The fallback shows resting dots rather than animating.
418
+
282
419
  ## Dot grid
283
420
 
284
421
  `createDotGrid(gl, options)` draws evenly spaced dots as GPU points, laid out from
@@ -287,27 +424,84 @@ with `mask-position: center`. A moving cursor throws the dots near it aside and
287
424
  back home with a damped bounce; a still cursor does nothing. Each dot's offset and velocity
288
425
  live in one texel of a half-float ping-pong texture (`cols × rows`) that a fullscreen pass
289
426
  advances per frame, and the point shader reads its texel back. Without half-float render
290
- targets the grid is static.
427
+ targets physical kicks are disabled; visual click, pulse, and resting effects still work.
428
+
429
+ Ripple clicks can apply a radial impulse using `click.kickRadius` (default 80) and
430
+ `click.kickStrength` (default 0, disabled). These are independent of cursor kicks and work
431
+ with `kick: false`. Negative click strength pulls inward. The return uses `kick.bounceDuration`
432
+ and `kick.bounciness` when cursor kicks are configured, or their defaults otherwise. The
433
+ existing `thrown` styling applies to displaced dots. The visual ripple still uses `click.radius`.
291
434
 
292
435
  Options come in groups (`dotGridSpecs` holds the types, `DOT_GRID_DEFAULTS`,
293
- `resolveDotGridOptions`, `isDotGridInteractive`, `getDotGridCoverSize`, and
294
- `makeDotGridTileUrl`, which returns one tile of the grid as an SVG data URL for a
295
- `mask-image` placeholder that lines up with the canvas):
436
+ `resolveDotGridOptions`, `isDotGridInteractive`, `getDotGridCoverSize`, `getDotGridAnchor`,
437
+ `makeDotGridTileUrl` + `getDotGridMaskPosition`, which return one tile of the grid as an
438
+ SVG data URL and the `mask-position` that lays it on the same dots as the canvas, and
439
+ `getDotGridMaskStyle`, the CSS that draws the resting grid from them, with
440
+ `getDotGridLayerMaskStyle` for a layer that rests at an offset inside a measured area):
296
441
 
297
442
  | Group | Fields | Meaning |
298
443
  | -------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
299
- | `dots` | `size` 2.25, `shape` `circle`, `spacing` 7, `color` `#ffffff`, `opacity` 1 | The grid at rest (defaults match marketday's `.pattern_speckle` tile). `shape` is `circle` or `rounded_square` (`size` is the bounding size either way); thrown dots keep it |
300
- | `kick` | `radius` 80, `strength` 1, `bounceDuration` 1200, `bounciness` 0.5 | How a moving cursor throws dots within `radius` (a fast swipe throws the dots at its centre about `radius × strength` px; negative pulls them toward the path) and how they return (`bounceDuration` ms to settle, `bounciness` 0 = glide back, 1 = ring). `false` for a static grid |
444
+ | `dots` | `size` 2.25, `shape` `circle`, `spacing` 7, `color` `#ffffff`, `opacity` 1, `alignX` `center`, `alignY` `center` | The grid at rest (defaults match marketday's `.pattern_speckle` tile). `shape` is `circle`, `rounded_square`, `ring`, or `ring_rectangle` (`size` is the bounding size either way); thrown dots keep it. `alignX` (`left` / `center` / `right`) and `alignY` (`top` / `center` / `bottom`) anchor the grid: `center` puts a dot on the middle of the area; `left` / `top` hide the first dot just past that edge (its center one `size` out, so the first visible one is about a spacing in); `right` / `bottom` set the last dot flush against that edge; a number (or `{ left }` / `{ top }`) puts a dot's center that many px from the left / top edge, `{ right }` / `{ bottom }` that many from the right / bottom edge |
445
+ | `kick` | `radius` 80, `strength` 1, `bounceDuration` 1200, `bounciness` 0.5 | How a moving cursor throws dots within `radius` (a fast swipe throws the dots at its centre about `radius × strength` px; negative pulls them toward the path) and how they return (`bounceDuration` ms to settle, `bounciness` 0 = glide back, 1 = ring). `false` disables cursor kicks |
301
446
  | `thrown` | `color`, `opacity`, `scale` | The look of a dot while thrown, blended by its swing amplitude (full at a quarter of `radius × strength`, the biggest throw a swipe gives) so it fades smoothly instead of flickering at each pass through home. Omit to keep the resting look |
302
- | `pulse` | `count` 20, `interval` 3000, `duration` 1500, `scale` 3, `opacity`, `shape` | Ambient twinkle: each cycle about `count` random dots swell to `scale`× (and to `opacity`, if given) and back over `duration` ms, each starting at a random moment in the cycle, and morphing into `shape` (default `dots.shape`) at the peak. Picked by hashing the cell with the cycle number, so it costs no per-dot state; needs continuous frames. Starts only once any reveal has finished. `true` for the defaults |
303
- | `reveal` | `delay` 1000, `duration` 800, `zoomOnMount` 1, `zoomDuration` 1000 | Intro: dots start at the cover size (√2 × spacing + 1 for circles, less for rounded squares, so no pixel is uncovered), hold for `delay`, then shrink to `dots.size` over `duration`; kicks are ignored meanwhile. With an image, `zoomOnMount` (e.g. 1.25) eases it from that scale to the plain cover fit over `zoomDuration`, starting at mount and independent of `delay`: the shrink begins when the delay is up whether or not the zoom has finished (but never before the canvas has started rendering, since only it can draw dots). `true` for the defaults |
447
+ | `pulse` | `effect` `swell`, `count` 20, `interval` 3000, `duration` 1500, `scale` 3, shared effect settings | A random handful of dots animate each cycle. Motion effects use a small local orbit around each selected dot; default radius is 3 × dot spacing. Starts after the reveal, with a stable effect choice per dot/cycle. Existing pulse configurations keep their simple swell. `true` enables defaults |
448
+ | `click` | `effect` `ripple`, `radius` 420, `width` 80, `duration` 1400, `scale` 4, shared effect settings | A click or tap runs the effect from that point. Up to eight clicks overlap; another replaces the oldest, and each dot follows the strongest active click. Works with `kick={false}`. Clicks during the reveal or reduced motion are ignored. `true` enables defaults; omitted or `false` disables it |
449
+ | `rest` | `effect` `ripple`, `interval` 6000, `duration` 1800, `scale` 2, `origin` `center`, shared effect settings | An ambient animation across the resting grid, independent of clicks and pulses. `origin: 'random'` chooses a point inside the area each cycle. Begins after the reveal; duration is capped at the interval. `true` enables defaults; omitted or `false` disables it |
304
450
 
305
451
  Resolved options are themselves valid options, so a scene can pass them straight through.
306
452
 
453
+ ```tsx
454
+ <DotsBoard
455
+ dots={{ shape: 'rounded_square', size: 2, spacing: 20 }}
456
+ intro={{ initialSize: 1, peakSize: 10, duration: 800 }}
457
+ effects={{
458
+ click: { effect: 'random', shape: 'ring_rectangle', radius: 480, width: 90, duration: 1500, scale: 6 },
459
+ pulse: { effect: 'sparkle', count: 50, color: '#70C9D4', shape: 'ring', scale: 3 },
460
+ rest: { effect: 'vortex', interval: 8000, duration: 2500, strength: 0.15, scale: 1 },
461
+ }}
462
+ >
463
+ {children}
464
+ </DotsBoard>
465
+ ```
466
+
467
+ All three triggers use `DotEffectOptions`: `effect`, `shape`, `radius`, `width`, `duration`,
468
+ `strength`, `scale`, `opacity`, and `color`. Shapes and opacity default to the resting dots.
469
+ `strength` (0..1, default 0.35) controls movement; `width` is the half-width of a ripple/color
470
+ wave. `color` is an optional hex tint, including over images. Color wave and sparkle choose
471
+ a stable accent color when it is omitted. Set `scale: 1` for movement, tint, or shape changes
472
+ without swelling. Pulse and resting durations cannot exceed their intervals.
473
+
474
+ | Effect | Behavior |
475
+ | --- | --- |
476
+ | `swell` | Smoothly grow and return; the original pulse behavior |
477
+ | `ripple` | A wave grows dots as it expands outward |
478
+ | `vortex` | Swirl around the origin, then unwind |
479
+ | `magnet` | Pull toward the origin and release |
480
+ | `color_wave` | Spread a temporary tint in an expanding wave |
481
+ | `sparkle` | Stagger brief flashes and shape changes between dots |
482
+ | `random` | Choose one of the six effects per click, per selected pulse dot/cycle, or per resting cycle |
483
+
484
+ Random choices are held for the animation's lifetime, including across parameter-preserving
485
+ React rerenders. Pulse and resting choices are seeded in the shader; clicks choose once when
486
+ recorded. New effects belong in `libs/effects/dotEffects.ts` and their names/defaults in
487
+ `utils/dotEffectSpecs.ts`; triggers supply only origins, timing, and style. All effects use
488
+ the same point draw pass, no new textures or render passes. Click work is bounded to eight
489
+ events; pulsing/resting need continuous frames while visible. Reduced motion disables the
490
+ animations and returns every dot to its resting appearance. The static CSS fallback keeps
491
+ the resting pattern when WebGL is unavailable.
492
+
493
+ The click listener belongs to the background area, including its overlaid children, and
494
+ preserves their normal button/link actions and touch scrolling. Coordinates follow the canvas
495
+ after scrolling or CSS scaling. `ring` (a circular outline) and `ring_rectangle` (the outline of a rounded square) also work
496
+ as resting or pulse shapes, with matching SVG fallbacks. Their holes open during a reveal
497
+ so the intro starts filled; all shapes use `size` as their bounding diameter or side length.
498
+
307
499
  Drive the grid from a scene: `resize(size)` from `resize`; `setOptions` from `setParams`;
308
500
  `setOverlay(imageTexture | null)` to show an image through the dots instead of `dots.color`
309
501
  (each fragment samples the cover-fit image at its own screen position, so a dot is a window
310
- onto it and a bigger dot shows more); `setReveal(0..1)` with an already eased amount and `setOverlayZoom(scale)` for the image; `setTime(seconds)` each frame while `isPulsing()`, with `setPulseStart(seconds | null)` to begin (or hold) the pulsing on that clock;
502
+ onto it and a bigger dot shows more); `setReveal(0..1, diameter?)` with an already eased amount (an optional CSS-pixel diameter supports growing dots from zero) and `setOverlayZoom(scale)` for the image; `setTime(seconds, reducedMotion)` every update, with `setPulseStart(seconds | null)` to begin (or hold) both ambient timelines. `isAnimating()` reports whether pulse or resting effects need continuous frames; `isPulsing()` reports pulses alone;
503
+ `clickAt(x, y, seconds)` on a click in canvas CSS pixels, and `stepClicks(seconds, reducedMotion)`
504
+ each frame to expire click effects (returns whether to `invalidate()` again);
311
505
  `step(pointerPx, velocityPxPerSecond, active, dt, now)` from `update` with the raw pointer in
312
506
  CSS pixels (y down), which returns whether the dots are still settling so the scene can
313
507
  `invalidate()`; and `draw(clear)` from `render` (`draw(true)` clears to transparent first).
@@ -0,0 +1,204 @@
1
+ import { jitter } from '../utils/random.ts';
2
+ import type { PixelCell, ShapeBox, ShapeIcon, ShapeKind, ShapeLineStyle, ShapeOutline, ShapePoints } from './Shapes.types.ts';
3
+
4
+ /**
5
+ * Outline
6
+ */
7
+
8
+ /*
9
+ * A coordinate to a thousandth of a pixel: `Math.sin` / `Math.cos` differ in their last digits
10
+ * between the server's and the browser's V8, so full-precision path data fails hydration.
11
+ */
12
+ function fix(value: number): number {
13
+ return Math.round(value * 1000) / 1000;
14
+ }
15
+
16
+ /*
17
+ * Outline points for a built-in shape filling `box`, each point displaced by up to `wobble` pixels.
18
+ */
19
+ export function shapePoints(kind: Exclude<ShapeKind, ShapeIcon>, box: ShapeBox, wobble: number, random: () => number): ShapePoints {
20
+ const { cx, cy, rx, ry } = box;
21
+ const wobbled = (points: [number, number][]): ShapePoints =>
22
+ points.map(([x, y]) => [fix(x + jitter(random, wobble)), fix(y + jitter(random, wobble))]);
23
+ // Points around an ellipse in the box, `scaleAt` stretching its radius per angle.
24
+ const around = (count: number, scaleAt: (angle: number) => number): ShapePoints =>
25
+ wobbled(
26
+ Array.from({ length: count }, (_, i) => {
27
+ const angle = (i / count) * Math.PI * 2;
28
+ const scale = scaleAt(angle);
29
+ return [cx + Math.cos(angle) * rx * scale, cy + Math.sin(angle) * ry * scale];
30
+ }),
31
+ );
32
+ switch (kind) {
33
+ case 'square':
34
+ return wobbled([
35
+ [cx - rx, cy - ry],
36
+ [cx + rx, cy - ry],
37
+ [cx + rx, cy + ry],
38
+ [cx - rx, cy + ry],
39
+ ]);
40
+ case 'triangle': {
41
+ // Sitting on its base and vertically centered on the box, a little wider than it.
42
+ const h = ry * 1.9;
43
+ const top = cy - h / 2;
44
+ return wobbled([
45
+ [cx, top],
46
+ [cx + rx * 1.08, top + h],
47
+ [cx - rx * 1.08, top + h],
48
+ ]);
49
+ }
50
+ case 'circle':
51
+ return around(24, () => 1);
52
+ case 'blob':
53
+ return around(20, (a) => 1 + Math.sin(a * 3) * 0.14 + Math.cos(a * 2) * 0.1);
54
+ }
55
+ }
56
+
57
+ /*
58
+ * Closed path through the points with straight segments.
59
+ */
60
+ function straightPath(points: ShapePoints): string {
61
+ return `M${points.map((p) => p.join(' ')).join('L')}Z`;
62
+ }
63
+
64
+ /*
65
+ * Closed path through the points as a smooth curve (quadratics through segment midpoints).
66
+ */
67
+ function smoothPath(points: ShapePoints): string {
68
+ const first = points[0];
69
+ const last = points[points.length - 1];
70
+ let d = `M${fix((first[0] + last[0]) / 2)} ${fix((first[1] + last[1]) / 2)}`;
71
+ for (let i = 0; i < points.length; i++) {
72
+ const a = points[i];
73
+ const b = points[(i + 1) % points.length];
74
+ d += `Q${a.join(' ')} ${fix((a[0] + b[0]) / 2)} ${fix((a[1] + b[1]) / 2)}`;
75
+ }
76
+ return `${d}Z`;
77
+ }
78
+
79
+ /*
80
+ * Closed polygon whose corners are cut with a quadratic of `cornerRadius` pixels.
81
+ */
82
+ function roundedPolygonPath(points: ShapePoints, cornerRadius: number): string {
83
+ const n = points.length;
84
+ let d = '';
85
+ for (let i = 0; i < n; i++) {
86
+ const prev = points[(i - 1 + n) % n];
87
+ const v = points[i];
88
+ const next = points[(i + 1) % n];
89
+ const toward = (target: [number, number]): [number, number] => {
90
+ const dx = target[0] - v[0];
91
+ const dy = target[1] - v[1];
92
+ const len = Math.hypot(dx, dy) || 1;
93
+ const t = Math.min(cornerRadius, len / 2) / len;
94
+ return [fix(v[0] + dx * t), fix(v[1] + dy * t)];
95
+ };
96
+ const a = toward(prev);
97
+ const b = toward(next);
98
+ d += `${i === 0 ? 'M' : 'L'}${a.join(' ')}Q${v.join(' ')} ${b.join(' ')}`;
99
+ }
100
+ return `${d}Z`;
101
+ }
102
+
103
+ /*
104
+ * The outline for a shape filling `box` in the given line style: a custom icon's own path,
105
+ * scaled by a transform (never by rewriting its data, which would break arc flags) into the
106
+ * largest square centered in the box; an exact ellipse for a clean circle; a smooth curve
107
+ * through the points of a curved shape; and a polygon with rounded or sharp corners
108
+ * otherwise. `sketch` wobbles every point of a built-in shape first (an icon keeps its path;
109
+ * the sketch filter roughens its edge).
110
+ */
111
+ export function shapeOutline(kind: ShapeKind, line: ShapeLineStyle, box: ShapeBox, random: () => number): ShapeOutline {
112
+ const { cx, cy, rx, ry } = box;
113
+ const r = Math.min(rx, ry);
114
+ if (typeof kind === 'object') {
115
+ const scale = (r * 2) / (kind.viewBox ?? 24);
116
+ return { d: kind.d, transform: `translate(${fix(cx - r)} ${fix(cy - r)}) scale(${fix(scale)})` };
117
+ }
118
+ if (kind === 'circle' && line !== 'sketch') {
119
+ return { d: `M${cx - rx} ${cy}a${rx} ${ry} 0 1 0 ${rx * 2} 0a${rx} ${ry} 0 1 0 ${-rx * 2} 0Z` };
120
+ }
121
+ const points = shapePoints(kind, box, line === 'sketch' ? r * 0.045 : 0, random);
122
+ if (kind === 'circle' || kind === 'blob') return { d: smoothPath(points) };
123
+ if (line === 'rounded') return { d: roundedPolygonPath(points, r * 0.16) };
124
+ return { d: straightPath(points) };
125
+ }
126
+
127
+ /**
128
+ * Brush
129
+ */
130
+
131
+ /*
132
+ * How many brush passes a box takes: `rows` for a square, more for a taller box so the
133
+ * passes stay about as thick.
134
+ */
135
+ export function brushRows(box: ShapeBox, rows: number): number {
136
+ return Math.max(3, Math.round((rows * box.ry) / box.rx));
137
+ }
138
+
139
+ /*
140
+ * Stroke width that makes `rows` brush passes over a box `ry` tall overlap into solid cover.
141
+ */
142
+ export function brushWidth(box: ShapeBox, rows: number): number {
143
+ return ((box.ry * 1.12 * 2) / rows) * 1.5;
144
+ }
145
+
146
+ /*
147
+ * A single brush stroke that sweeps down the shape box in wobbly horizontal passes, wide enough
148
+ * (see `brushWidth`) to leave no gaps. Clipped to the shape by the caller.
149
+ */
150
+ export function brushPath(box: ShapeBox, rows: number, random: () => number): string {
151
+ const { cx, cy, rx, ry } = box;
152
+ const reachX = rx * 1.12;
153
+ const reachY = ry * 1.12;
154
+ const step = (reachY * 2) / rows;
155
+ let d = '';
156
+ for (let i = 0; i <= rows; i++) {
157
+ const y = fix(cy - reachY + i * step + jitter(random, step * 0.12));
158
+ const from = fix((i % 2 ? cx + reachX : cx - reachX) + jitter(random, rx * 0.08));
159
+ const to = fix((i % 2 ? cx - reachX : cx + reachX) + jitter(random, rx * 0.08));
160
+ d += `${i ? 'L' : 'M'}${from} ${y}Q${fix((from + to) / 2)} ${fix(y + jitter(random, step * 0.22))} ${to} ${y}`;
161
+ }
162
+ return d;
163
+ }
164
+
165
+ /**
166
+ * Pixelate
167
+ */
168
+
169
+ /*
170
+ * How many mosaic cells span the shape's width for a pixelate `intensity`: two at 0, many at
171
+ * 1. The cell size follows from the shape's size, so the look scales with it.
172
+ */
173
+ export function pixelateCells(intensity: number): number {
174
+ return Math.round(2 + 30 * Math.min(1, Math.max(0, intensity)));
175
+ }
176
+
177
+ /*
178
+ * The cells of one repeating mosaic tile, `columns × rows` of them, each shaded by a seeded
179
+ * random amount either way of the paint; the tile repeats over the shape, so a modest tile
180
+ * keeps the markup small.
181
+ */
182
+ export function pixelateTile(columns: number, rows: number, random: () => number): PixelCell[] {
183
+ const cells: PixelCell[] = [];
184
+ for (let row = 0; row < rows; row++) {
185
+ for (let col = 0; col < columns; col++) cells.push({ col, row, shade: jitter(random, 1) });
186
+ }
187
+ return cells;
188
+ }
189
+
190
+ /**
191
+ * Pulse
192
+ */
193
+
194
+ /*
195
+ * One pulse of a `<PulsingMarker>` halo: from the dot's `size` to `pulseSize` across, lit while
196
+ * it grows and fading out in the second half, as the next halo comes up.
197
+ */
198
+ export function pulseHaloKeyframes(size: number, pulseSize: number): Keyframe[] {
199
+ return [
200
+ { transform: `scale(${size / pulseSize})`, opacity: 1 },
201
+ { opacity: 0.7, offset: 0.5 },
202
+ { transform: 'scale(1)', opacity: 0 },
203
+ ];
204
+ }