@jsb188/gfx 1.1.11 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +248 -54
  2. package/elements/Shapes.helpers.ts +204 -0
  3. package/elements/Shapes.hooks.ts +171 -0
  4. package/elements/Shapes.tsx +505 -0
  5. package/elements/Shapes.types.ts +81 -0
  6. package/elements/Stack.helpers.ts +42 -0
  7. package/elements/Stack.tsx +143 -0
  8. package/elements/Text.helpers.ts +45 -0
  9. package/elements/Text.hooks.ts +197 -0
  10. package/elements/Text.tsx +98 -0
  11. package/libs/dotGrid.helpers.ts +53 -0
  12. package/libs/dotGrid.ts +480 -77
  13. package/libs/effects/dotEffects.ts +136 -0
  14. package/libs/effects/effectQuad.ts +8 -2
  15. package/libs/pointer.ts +6 -0
  16. package/libs/runtime.ts +6 -4
  17. package/libs/types.ts +8 -1
  18. package/main.ts +2 -0
  19. package/modules/Carousel.helpers.ts +234 -0
  20. package/modules/Carousel.hooks.ts +520 -0
  21. package/modules/Carousel.tsx +135 -29
  22. package/modules/Dots.tsx +269 -0
  23. package/modules/DotsBoard.helpers.ts +388 -0
  24. package/modules/DotsBoard.hooks.ts +144 -0
  25. package/modules/DotsBoard.strings.ts +649 -0
  26. package/modules/DotsBoard.types.ts +240 -0
  27. package/modules/DotsBoardCanvas.hooks.ts +49 -0
  28. package/modules/DotsBoardCanvas.tsx +190 -0
  29. package/modules/DotsBoardElements.tsx +330 -0
  30. package/modules/Gallery.helpers.ts +32 -0
  31. package/modules/Gallery.hooks.ts +149 -0
  32. package/modules/Gallery.tsx +194 -0
  33. package/modules/GfxCanvas.tsx +10 -2
  34. package/modules/KineticHeader.helpers.ts +44 -0
  35. package/modules/KineticHeader.hooks.ts +206 -0
  36. package/modules/KineticHeader.tsx +305 -0
  37. package/modules/KineticHeader.types.ts +56 -0
  38. package/modules/ScrollSteps.hooks.ts +138 -0
  39. package/modules/ScrollSteps.tsx +7 -52
  40. package/package.json +15 -5
  41. package/scenes/Carousel.ts +99 -18
  42. package/scenes/DotsBoard.helpers.ts +12 -0
  43. package/scenes/DotsBoard.ts +245 -0
  44. package/tsconfig.json +1 -1
  45. package/utils/align.ts +18 -0
  46. package/utils/color.ts +64 -2
  47. package/utils/dotEffectSpecs.ts +79 -0
  48. package/utils/dotGridSpecs.ts +304 -46
  49. package/utils/motion.ts +88 -0
  50. package/utils/random.ts +22 -0
  51. package/utils/strings.ts +116 -0
  52. package/modules/DotsArea.tsx +0 -120
  53. package/modules/VisionBoard.helpers.ts +0 -561
  54. package/modules/VisionBoard.tsx +0 -358
  55. package/modules/VisionBoard.types.ts +0 -88
  56. package/scenes/DotsArea.ts +0 -208
@@ -1,11 +1,13 @@
1
1
  import { cn } from '@jsb188/app/utils/string.ts';
2
2
  import { Icon } from '@jsb188/react-web/svgs/Icon';
3
- import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
- import type { CSSProperties, KeyboardEvent } from 'react';
3
+ import { Children, isValidElement, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
+ import type { CSSProperties, KeyboardEvent, ReactNode } from 'react';
5
5
  import type { CarouselSceneParams } from '../scenes/Carousel.ts';
6
6
  import { normalizeImageEffectSpecs } from '../utils/imageEffectSpecs.ts';
7
7
  import type { ImageEffectName, ImageEffectSpec } from '../utils/imageEffectSpecs.ts';
8
8
  import { getItemIndex, getVirtualLeft, getVirtualPositions, playVideo, whenVideosPlaying } from './Carousel.helpers.ts';
9
+ import type { BlocksAlign } from './Carousel.helpers.ts';
10
+ import { useBlocksCarousel } from './Carousel.hooks.ts';
9
11
  import { GfxCanvas } from './GfxCanvas.tsx';
10
12
  import { useContentMemo } from './GfxCanvas.hooks.ts';
11
13
 
@@ -17,7 +19,7 @@ export interface VideoCarouselItem {
17
19
  videoUrl: string;
18
20
  /** Shown until the video has a frame, and in place of the video when it cannot play. */
19
21
  posterUrl?: string;
20
- /** Display size of the video in CSS pixels; each item may differ. */
22
+ /** Display size of the video in CSS pixels; each item may differ (the track is as tall as the tallest, and every video is top-aligned in it). */
21
23
  width: number;
22
24
  height: number;
23
25
  /** Already translated; shown above the video only while this item is focused. */
@@ -104,16 +106,16 @@ const CarouselCaption = memo(
104
106
  aria-hidden={phase === 'out'}
105
107
  >
106
108
  <div
107
- className="v_bottom a_c pb_md h_f max_w_f"
109
+ className="v_bottom a_c pb_md h_f max_w_350"
108
110
  style={{ width }}
109
111
  >
110
- {item.iconName && (
111
- <div className="h_center mb_sm">
112
- <Icon name={item.iconName} />
113
- </div>
114
- )}
115
- <div className="ft_semibold ft_lg">{item.title}</div>
116
- {item.description && <div className="op_70 mt_xs">{item.description}</div>}
112
+ <div className="ft_medium h_center ft_md">
113
+ {item.title}
114
+ </div>
115
+ {item.description && <div className="op_70 mt_4 gap_xs h_center">
116
+ {item.iconName && <span className='shift_up'><Icon name={item.iconName} /></span>}
117
+ {item.description}
118
+ </div>}
117
119
  </div>
118
120
  </div>
119
121
  );
@@ -188,10 +190,11 @@ const CarouselSlide = memo(
188
190
  : { className: 'abs_tl h_f v_top' })}
189
191
  style={{ left, width, transition: transition && `left ${transition}, width ${transition}` }}
190
192
  >
191
- <div className="h_center f w_f">
193
+ {/* Top-aligned, so videos of different heights line up along the track's top edge. */}
194
+ <div className="v_top w_f">
192
195
  {/* The video's own backdrop: a dimmed video fades toward it instead of revealing the page; the scene reads this background for the drawn copy. */}
193
196
  <div
194
- className="bg_active of max_w_f"
197
+ className="bg_fade of max_w_f"
195
198
  style={{ width: item.width, borderRadius }}
196
199
  >
197
200
  <video
@@ -221,11 +224,12 @@ const CarouselSlide = memo(
221
224
 
222
225
  /*
223
226
  * Horizontal carousel of videos laid out edge to edge across the full width of its container;
224
- * whatever falls past the left or right edge is clipped (never widening the page). The focused
225
- * slide sits centered in a box `focusedContentWidth` wide; every other slide shows its video at
226
- * its own size, dimmed to `unfocusedOpacity` over a `bg_active` backdrop (so the page never
227
- * shows through it), through `effect` (pixelated by default). Above the track a text area of
228
- * fixed height, which never moves with the videos, shows the focused item's icon, title, and
227
+ * whatever falls past the left or right edge is clipped (never widening the page). Every slide
228
+ * is its video at its own size, top-aligned on the track, with `gap` between; the focused one sits
229
+ * centered and plain, and every other one is dimmed to `unfocusedOpacity` over a `bg_active`
230
+ * backdrop (so the page never shows through it), through `effect` (pixelated by default). Above
231
+ * the track a text area of fixed size (`textAreaWidth` × `textAreaHeight`, independent of the
232
+ * videos), which never moves with them, shows the focused item's icon, title, and
229
233
  * description; when focus moves, that caption fades out sliding a little in the direction the
230
234
  * videos travel while the next one fades in sliding into place from the other side. The list is
231
235
  * endless: slides are laid out along an unbounded track and the items repeat, so focus only ever
@@ -242,8 +246,8 @@ const CarouselSlide = memo(
242
246
  export const VideoCarousel = memo(
243
247
  (p: {
244
248
  items: VideoCarouselItem[];
245
- /** Width of the focused slide's box (texts and video); it never changes with the item. */
246
- focusedContentWidth: number;
249
+ /** Width of the caption area above the videos, centered; independent of the videos' sizes. */
250
+ textAreaWidth: number;
247
251
  /** Controlled focused item; a change moves forward around the loop to that item. Omit to let clicks and autoplay move focus on their own. */
248
252
  focusedIndex?: number;
249
253
  defaultFocusedIndex?: number;
@@ -273,7 +277,7 @@ export const VideoCarousel = memo(
273
277
  }) => {
274
278
  const {
275
279
  items,
276
- focusedContentWidth,
280
+ textAreaWidth,
277
281
  focusedIndex: controlledIndex,
278
282
  defaultFocusedIndex = 0,
279
283
  onFocusedIndexChange,
@@ -441,12 +445,11 @@ export const VideoCarousel = memo(
441
445
  [slides, effect, transitionMs, borderRadius, unfocusedOpacity, backdropColor],
442
446
  );
443
447
 
444
- // Slides sit at their natural-width positions along the endless track, with everything right of
445
- // the focused slide pushed by its widening to the focused box; the track is shifted so that box
446
- // lands centered. All coordinates are absolute, so slides entering or leaving move nothing else.
448
+ // Slides sit at their natural-width positions along the endless track, and the track is shifted
449
+ // so the focused slide lands centered. All coordinates are absolute, so slides entering or
450
+ // leaving move nothing else.
447
451
  const focusedLeft = getVirtualLeft(position, widths, gap);
448
- const focusedShift = focusedContentWidth - widths[focusedItemIndex];
449
- const trackOffset = containerWidth / 2 - focusedContentWidth / 2 - focusedLeft;
452
+ const trackOffset = containerWidth / 2 - widths[focusedItemIndex] / 2 - focusedLeft;
450
453
  const trackHeight = Math.max(...items.map((item) => item.height));
451
454
  const transition = containerWidth ? `${transitionMs}ms ${CAROUSEL.easing}` : undefined;
452
455
  const videosHidden = canvasStatus === 'ready';
@@ -472,7 +475,7 @@ export const VideoCarousel = memo(
472
475
  item={items[getItemIndex(caption.position, count)]}
473
476
  phase={caption.phase}
474
477
  direction={caption.direction}
475
- width={focusedContentWidth}
478
+ width={textAreaWidth}
476
479
  durationMs={transitionMs}
477
480
  />
478
481
  ))}
@@ -496,8 +499,8 @@ export const VideoCarousel = memo(
496
499
  item={items[getItemIndex(v, count)]}
497
500
  focused={focused}
498
501
  interactive={!focused && !paused}
499
- left={getVirtualLeft(v, widths, gap) + (v > position ? focusedShift : 0)}
500
- width={focused ? focusedContentWidth : widths[getItemIndex(v, count)]}
502
+ left={getVirtualLeft(v, widths, gap)}
503
+ width={widths[getItemIndex(v, count)]}
501
504
  borderRadius={borderRadius}
502
505
  transition={transition}
503
506
  videoOpacity={videosHidden ? 0 : focused ? 1 : unfocusedOpacity}
@@ -523,3 +526,106 @@ export const VideoCarousel = memo(
523
526
  );
524
527
  },
525
528
  );
529
+
530
+ /*
531
+ * A row of blocks (its children, each any width, all stretched to the tallest) that the visitor
532
+ * drags with any pointer or scrolls sideways with a wheel or trackpad; whatever falls past the
533
+ * container's edges is clipped. When the drag or the scroll ends, the track glides to the
534
+ * nearest snap position: a block's left edge at the container's left edge (`align='start'`), or
535
+ * its middle at the container's middle. The track stops at its ends (the last blocks share the
536
+ * end position), so nothing loops, and nothing moves on its own. A drag past an end gives with
537
+ * rubber-band resistance and springs back; a flick always leaves the current block, and a wheel
538
+ * notch too short to reach the next block still advances one. A click on a block stays a click
539
+ * unless the pointer moved first, so blocks can hold buttons and links. With `selectableText` (the
540
+ * default) a mouse or pen press on text selects it the way it would anywhere on the page, and
541
+ * the drag starts from everything else (blank space, images, links, buttons); the cursor shows
542
+ * which one a press would do. On a touch screen a sideways swipe drags and a long press selects.
543
+ * Form fields inside the blocks are never dragged from. `index` / `defaultIndex`
544
+ * / `onIndexChange` name the block at the snap position; changing `index` glides there. Keyboard
545
+ * focus landing in a clipped block brings it into view. Padding on the container (through
546
+ * `className` or `style`) shows the neighbouring blocks under it. `lock={false}` turns the
547
+ * snapping off: a gesture leaves the track wherever it put it (a flick coasts a little further,
548
+ * and a drag past an end still springs back), while `index` and keyboard focus still glide to
549
+ * a block's snap position. `contentOffset` shifts where the content sits, at the start and
550
+ * throughout: -20 shows it 20px further left than the container's content box.
551
+ */
552
+ export const BlocksCarousel = memo(
553
+ (p: {
554
+ children: ReactNode;
555
+ /** Space between blocks in CSS pixels. */
556
+ gap?: number;
557
+ /** Where the current block rests: its left edge at the container's left edge, or centered in it. */
558
+ align?: BlocksAlign;
559
+ /** Controlled current block; a change glides the track to it. Omit to let gestures move it on their own. */
560
+ index?: number;
561
+ defaultIndex?: number;
562
+ /** Called with the block a gesture picked, as soon as it is picked (the glide there is still under way). */
563
+ onIndexChange?: (index: number) => void;
564
+ /** Duration of the glide to a snap position, in ms. */
565
+ transitionMs?: number;
566
+ /** Whether a finished drag or scroll locks the track onto the nearest block; `false` leaves it where the gesture ended. */
567
+ lock?: boolean;
568
+ /** Shift of the content in CSS pixels, at the start and throughout: -20 shows it 20px further left. */
569
+ contentOffset?: number;
570
+ /** Whether a mouse or pen press on text selects it instead of dragging the track; `false` drags from anywhere. */
571
+ selectableText?: boolean;
572
+ className?: string;
573
+ style?: CSSProperties;
574
+ }) => {
575
+ const {
576
+ children,
577
+ gap = 16,
578
+ align = 'start',
579
+ index,
580
+ defaultIndex = 0,
581
+ onIndexChange,
582
+ transitionMs = 600,
583
+ lock = true,
584
+ contentOffset = 0,
585
+ selectableText = true,
586
+ className,
587
+ style,
588
+ } = p;
589
+ const containerRef = useRef<HTMLDivElement>(null);
590
+ const trackRef = useRef<HTMLDivElement>(null);
591
+ const handlers = useBlocksCarousel(containerRef, trackRef, {
592
+ align,
593
+ index,
594
+ defaultIndex,
595
+ onIndexChange,
596
+ transitionMs,
597
+ lock,
598
+ contentOffset,
599
+ selectableText,
600
+ });
601
+
602
+ return (
603
+ <div
604
+ ref={containerRef}
605
+ // Vertical pans and pinches stay the browser's, so a finger can still scroll the page across the carousel; sideways ones are the drag.
606
+ // `cs_grab` is the cursor until the pointer first moves over the blocks; the hook writes it from then on.
607
+ className={cn('rel of cs_grab', className)}
608
+ style={{ ...style, touchAction: 'pan-y pinch-zoom' }}
609
+ {...handlers}
610
+ >
611
+ <div
612
+ ref={trackRef}
613
+ // As wide as its blocks (never shrunk to the container), moved by its transform alone. The first block's start
614
+ // position is rendered already, so server-rendered HTML does not jump by `contentOffset` when the hook takes over.
615
+ className="rel h_stretch"
616
+ style={{ gap, width: 'max-content', willChange: 'transform', transform: `translate3d(${contentOffset}px, 0, 0)` }}
617
+ >
618
+ {/* Each block in its own wrapper, so blocks are measured without needing refs of their own, and stretched to the row's height. */}
619
+ {Children.toArray(children).map((child, i) => (
620
+ <div
621
+ key={isValidElement(child) ? (child.key ?? i) : i}
622
+ className="no_shrink h_stretch"
623
+ >
624
+ {child}
625
+ </div>
626
+ ))}
627
+ </div>
628
+ </div>
629
+ );
630
+ },
631
+ );
@@ -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
+ });