@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,305 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { cn } from '@jsb188/app/utils/string.ts';
3
+ import { Icon } from '@jsb188/react-web/svgs/Icon';
4
+ import type { CSSProperties, RefObject } from 'react';
5
+ import { memo, useMemo } from 'react';
6
+ import { useTypedText } from '../elements/Text.hooks.ts';
7
+ import { getKineticImageAltStyle } from './KineticHeader.helpers.ts';
8
+ import { useKineticHeader } from './KineticHeader.hooks.ts';
9
+ import type { KineticHeaderImage, KineticHeaderProps } from './KineticHeader.types.ts';
10
+
11
+ export type { KineticHeaderImage, KineticHeaderProps, KineticHeaderSlide } from './KineticHeader.types.ts';
12
+
13
+ /*
14
+ * Position an image and its caption by the image center.
15
+ */
16
+ const KineticImage = memo((p: { image: KineticHeaderImage; style?: CSSProperties }) => {
17
+ const { image, style } = p;
18
+ const hasFixedSize = image.width !== undefined && image.height !== undefined;
19
+ const heightOnly = image.width === undefined && image.height !== undefined;
20
+ return (
21
+ <div
22
+ className='abs'
23
+ style={{
24
+ left: `calc(50% + ${image.offset?.x ?? 0}px)`,
25
+ top: `calc(50% + ${image.offset?.y ?? 0}px)`,
26
+ width: image.width ?? (heightOnly ? 'max-content' : 650),
27
+ height: image.height,
28
+ transform: 'translate(-50%, -50%)',
29
+ }}
30
+ >
31
+ {image.alt && (
32
+ <div
33
+ className={cn('abs ft_xs cl_md lh_2 a_l ofw bg_lighter_6', image.altClassName)}
34
+ style={getKineticImageAltStyle(image)}
35
+ aria-hidden
36
+ >
37
+ {image.alt}
38
+ </div>
39
+ )}
40
+ <img
41
+ src={image.src}
42
+ alt={image.alt}
43
+ width={image.width}
44
+ height={image.height}
45
+ decoding='async'
46
+ draggable={false}
47
+ className={cn('bl unsel', heightOnly ? 'no_shrink' : 'w_f', hasFixedSize && 'img_cover')}
48
+ style={{ height: image.height !== undefined ? '100%' : 'auto', ...style }}
49
+ />
50
+ </div>
51
+ );
52
+ });
53
+
54
+ /*
55
+ * Position images in exact pixels around the image area's center, allowing overflow.
56
+ */
57
+ const KineticImageArea = (p: {
58
+ images: readonly KineticHeaderImage[];
59
+ index: number;
60
+ imageAreaRef: RefObject<HTMLDivElement | null>;
61
+ hoverAreaRef: RefObject<HTMLDivElement | null>;
62
+ progressRef: RefObject<HTMLDivElement | null>;
63
+ showProgress: boolean;
64
+ isFixed: boolean;
65
+ isPaused: boolean;
66
+ showControls: boolean;
67
+ onNavigate: (direction: -1 | 1) => void;
68
+ reducedMotion: boolean;
69
+ pausedLabelText?: KineticHeaderProps['pausedLabelText'];
70
+ areaWidth: number;
71
+ areaHeight: number;
72
+ imageStyle?: CSSProperties;
73
+ }) => {
74
+ return (
75
+ <div
76
+ ref={p.hoverAreaRef}
77
+ className='rel z1 w_f mx_auto'
78
+ style={{ maxWidth: Math.max(1, p.areaWidth), height: Math.max(1, p.areaHeight), marginTop: 32 }}
79
+ >
80
+ <div
81
+ ref={p.imageAreaRef}
82
+ className='rel w_f h_f'
83
+ >
84
+ {p.images.map((image, itemIndex) => (
85
+ <KineticImage
86
+ key={`${p.index}-${itemIndex}`}
87
+ image={image}
88
+ style={p.imageStyle}
89
+ />
90
+ ))}
91
+ </div>
92
+ {p.showProgress && (
93
+ <div
94
+ className='abs z2 w_f h_f'
95
+ style={{
96
+ top: 0,
97
+ left: 0,
98
+ display: 'flex',
99
+ flexDirection: 'column',
100
+ justifyContent: 'flex-end',
101
+ pointerEvents: 'none',
102
+ }}
103
+ >
104
+ <div className='sticky_bottom w_f pb_5'>
105
+ {!p.isFixed && (
106
+ <div
107
+ className='w_f h_spread gap_xs ft_xs cl_darker_5'
108
+ style={{ opacity: p.showControls ? 1 : 0, pointerEvents: p.showControls ? 'auto' : 'none' }}
109
+ >
110
+ <button
111
+ type='button'
112
+ className='link h_center w_32 h_24 bg_lighter_5 bg_primary_hv no_shrink'
113
+ aria-label={i18n.t('c.prev')}
114
+ aria-disabled={!p.showControls}
115
+ onMouseDown={(event) => event.preventDefault()}
116
+ onClick={() => p.onNavigate(-1)}
117
+ >
118
+ <Icon name='arrow-narrow-left' />
119
+ </button>
120
+ {p.pausedLabelText && p.isPaused && (
121
+ <span
122
+ className='bg h_24 v_center px_6'
123
+ aria-hidden={!p.showControls}
124
+ >
125
+ {p.pausedLabelText}
126
+ </span>
127
+ )}
128
+ <button
129
+ type='button'
130
+ className='link h_center w_32 h_24 bg_lighter_5 bg_primary_hv no_shrink'
131
+ aria-label={i18n.t('c.next')}
132
+ aria-disabled={!p.showControls}
133
+ onMouseDown={(event) => event.preventDefault()}
134
+ onClick={() => p.onNavigate(1)}
135
+ >
136
+ <Icon name='arrow-narrow-right' />
137
+ </button>
138
+ </div>
139
+ )}
140
+ <div
141
+ className='w_f h_4 bg shadow_line_alt r of'
142
+ aria-hidden
143
+ hidden={p.reducedMotion}
144
+ >
145
+ <div
146
+ ref={p.progressRef}
147
+ className='w_f h_f bg_primary r'
148
+ style={{ transform: p.isFixed ? 'scaleX(1)' : 'scaleX(0)', transformOrigin: 'left' }}
149
+ />
150
+ </div>
151
+ </div>
152
+ </div>
153
+ )}
154
+ </div>
155
+ );
156
+ };
157
+
158
+ /*
159
+ * Confine each typing update to the visible title; image and layout trees stay untouched.
160
+ */
161
+ const KineticTitleText = (
162
+ p: Pick<KineticHeaderProps, 'wordClassName' | 'typeMs' | 'deleteMs' | 'pauseMs' | 'jitter'> & {
163
+ before: string;
164
+ after: string;
165
+ text: string;
166
+ index: number;
167
+ reducedMotion: boolean;
168
+ },
169
+ ) => {
170
+ const { before, after, text, index, reducedMotion, wordClassName, typeMs, deleteMs = 35, pauseMs, jitter } = p;
171
+ const { shown, typing } = useTypedText(text, { typeMs, deleteMs, pauseMs, jitter }, { replayKey: index, interruptOnChange: true });
172
+ return (
173
+ <span
174
+ aria-hidden
175
+ style={{ gridArea: '1 / 1' }}
176
+ >
177
+ {before}
178
+ <span className={cn('rel', wordClassName)}>
179
+ {reducedMotion ? text : shown}
180
+ {typing && !reducedMotion && (
181
+ <span
182
+ className='abs'
183
+ style={{ left: '100%', fontWeight: 200 }}
184
+ >
185
+ |
186
+ </span>
187
+ )}
188
+ </span>
189
+ {after}
190
+ </span>
191
+ );
192
+ };
193
+
194
+ /*
195
+ * Render a centered title and its synchronized images; invisible complete titles reserve
196
+ * enough space for every slide, keeping the image and following content still while typing.
197
+ */
198
+ const KineticHeaderSequence = (p: KineticHeaderProps) => {
199
+ const {
200
+ title,
201
+ children,
202
+ slides,
203
+ fixedSlide,
204
+ className,
205
+ titleClassName,
206
+ wordClassName,
207
+ pausedLabelText,
208
+ typeMs,
209
+ deleteMs,
210
+ pauseMs,
211
+ jitter,
212
+ style,
213
+ titleStyle,
214
+ imageStyle,
215
+ imageAreaAspectRatio,
216
+ imageAreaWidth = 1000,
217
+ imageAreaHeight = imageAreaAspectRatio ? imageAreaWidth / imageAreaAspectRatio : 750,
218
+ } = p;
219
+ const { index, isPaused, reducedMotion, showControls, navigate, imageAreaRef, hoverAreaRef, progressRef } = useKineticHeader(p);
220
+ const images = slides[index]?.images ?? [];
221
+ const placeholder = title.indexOf('{word}');
222
+ const before = placeholder < 0 ? title : title.slice(0, placeholder);
223
+ const after = placeholder < 0 ? '' : title.slice(placeholder + 6);
224
+
225
+ return (
226
+ <div
227
+ className={cn('w_f a_c', className)}
228
+ style={style}
229
+ >
230
+ <h1
231
+ className={cn('rel z2 grid gap_n mx_n my_n ofw', titleClassName)}
232
+ aria-label={title.replace('{word}', slides[index]?.text ?? '')}
233
+ style={{
234
+ whiteSpace: 'pre-line',
235
+ ...titleStyle,
236
+ }}
237
+ >
238
+ {slides.map((item, itemIndex) => (
239
+ <span
240
+ key={itemIndex}
241
+ aria-hidden
242
+ className='invis'
243
+ style={{ gridArea: '1 / 1' }}
244
+ >
245
+ {before}
246
+ <span className={wordClassName}>{placeholder < 0 ? '' : item.text}</span>
247
+ {after}
248
+ </span>
249
+ ))}
250
+ <KineticTitleText
251
+ before={before}
252
+ after={after}
253
+ text={placeholder < 0 ? '' : (slides[index]?.text ?? '')}
254
+ index={index}
255
+ reducedMotion={reducedMotion}
256
+ wordClassName={wordClassName}
257
+ typeMs={typeMs}
258
+ deleteMs={deleteMs}
259
+ pauseMs={pauseMs}
260
+ jitter={jitter}
261
+ />
262
+ </h1>
263
+ {children}
264
+ {(slides.some((item) => item.images.length > 0) || (fixedSlide !== undefined && slides.length > 0)) && (
265
+ <KineticImageArea
266
+ images={images}
267
+ index={index}
268
+ imageAreaRef={imageAreaRef}
269
+ hoverAreaRef={hoverAreaRef}
270
+ progressRef={progressRef}
271
+ showProgress={slides.length > 1 || fixedSlide !== undefined}
272
+ isFixed={fixedSlide !== undefined}
273
+ isPaused={isPaused}
274
+ showControls={showControls}
275
+ onNavigate={navigate}
276
+ reducedMotion={reducedMotion}
277
+ pausedLabelText={pausedLabelText}
278
+ areaWidth={imageAreaWidth}
279
+ areaHeight={imageAreaHeight}
280
+ imageStyle={imageStyle}
281
+ />
282
+ )}
283
+ </div>
284
+ );
285
+ };
286
+
287
+ /*
288
+ * Loop through a slide list, restarting only when its contents change rather than when
289
+ * a parent recreates the array. Fixed selections remount fully typed and disable playback.
290
+ * Reduced motion keeps the current complete slide still during autoplay.
291
+ */
292
+ export const KineticHeader = memo((p: KineticHeaderProps) => {
293
+ const sequenceKey = useMemo(() => JSON.stringify(p.slides), [p.slides]);
294
+ const fixedSlide =
295
+ typeof p.fixedSlide === 'number' && Number.isInteger(p.fixedSlide)
296
+ ? Math.max(0, Math.min(p.fixedSlide, p.slides.length - 1))
297
+ : undefined;
298
+ return (
299
+ <KineticHeaderSequence
300
+ key={`${sequenceKey}:${fixedSlide ?? 'auto'}`}
301
+ {...p}
302
+ fixedSlide={fixedSlide}
303
+ />
304
+ );
305
+ });
@@ -0,0 +1,56 @@
1
+ import type { CSSProperties, ReactNode } from 'react';
2
+ import type { TypedTextTiming } from '../elements/Text.hooks.ts';
3
+
4
+ export interface KineticHeaderImage {
5
+ src: string;
6
+ alt: string;
7
+ /** Caption side; defaults to top. Side captions align with the image's top edge. */
8
+ altPosition?: 'top' | 'left' | 'right' | 'bottom';
9
+ /** Caption width in pixels; defaults to the image width. Does not affect image placement. */
10
+ altWidth?: number;
11
+ /** Additional classes for the caption container, such as a_r for right-aligned text. */
12
+ altClassName?: string;
13
+ /** Pixel offset of the image's center from the image area's center. Defaults to { x: 0, y: 0 }. */
14
+ offset?: { x: number; y: number };
15
+ /** Width in pixels. Alone, preserves aspect ratio. Defaults to 650 only when neither dimension is set. */
16
+ width?: number;
17
+ /** Height in pixels. Alone, derives width from aspect ratio; with width, crops to fill the box. */
18
+ height?: number;
19
+ }
20
+
21
+ export interface KineticHeaderSlide {
22
+ text: string;
23
+ /** Positioned images shown when this slide starts; later entries appear on top. */
24
+ images: readonly KineticHeaderImage[];
25
+ }
26
+
27
+ export interface KineticHeaderProps extends TypedTextTiming {
28
+ /** Content rendered directly below the title and above the image area. */
29
+ children?: ReactNode;
30
+ /** A complete title containing one `{word}` placeholder; newlines are preserved. */
31
+ title: string;
32
+ /** Loops in order, starting with the first slide fully typed. Changing the list restarts it. */
33
+ slides: readonly KineticHeaderSlide[];
34
+ /** Zero-based slide index to hold without playback. Integers are clamped to the slide range; other values enable autoplay. Keeps a full, static progress bar visible. */
35
+ fixedSlide?: number;
36
+ /** Fully visible display time in milliseconds, excluding image entrance and exit; defaults to 5000. Short durations can interrupt typing. Hover pauses unless mouseOverSlideDuration is set; focus pauses display time. Neither affects entrance or exit. Offscreen slides, hidden tabs, and reduced motion pause all phases. */
37
+ slideDuration?: number;
38
+ /** Positive integer display duration in milliseconds while hovered, excluding entrance and exit. Changes speed without resetting progress; leaving restores slideDuration. Omitted or invalid values retain hover-to-pause. Keyboard focus still pauses. */
39
+ mouseOverSlideDuration?: number;
40
+ /** Image entrance duration; defaults to 350ms. Exit takes 350ms. Both run in addition to slideDuration. Use 0 to disable both. */
41
+ slideTransitionMs?: number;
42
+ /** Optional width / height ratio, used only when imageAreaHeight is omitted. */
43
+ imageAreaAspectRatio?: number;
44
+ /** Maximum image area width in pixels; defaults to 1000. Images retain their pixel sizes in narrower containers. */
45
+ imageAreaWidth?: number;
46
+ /** Image area height in pixels; defaults to 750 unless an aspect ratio is supplied. Does not scale. */
47
+ imageAreaHeight?: number;
48
+ /** Optional localized caption shown between navigation buttons while playback is paused and controls are visible. */
49
+ pausedLabelText?: string;
50
+ className?: string;
51
+ titleClassName?: string;
52
+ wordClassName?: string;
53
+ style?: CSSProperties;
54
+ titleStyle?: CSSProperties;
55
+ imageStyle?: CSSProperties;
56
+ }
@@ -0,0 +1,138 @@
1
+ import type { RefObject } from 'react';
2
+ import { useEffect, useRef, useState } from 'react';
3
+
4
+ /*
5
+ * Whether an element is in the viewport (any pixel of it, or `threshold` of it, within
6
+ * `rootMargin` of the edges). With `once` it stays true after the first sighting, for a
7
+ * reveal that should not undo itself when the visitor scrolls back. False until the first
8
+ * observation, so on the server and before hydration nothing counts as seen; where the
9
+ * browser has no `IntersectionObserver` everything counts as seen at once. `disabled` keeps
10
+ * the element unobserved (and the answer false), for a caller that only sometimes needs it.
11
+ */
12
+ export function useInView(
13
+ ref: RefObject<Element | null>,
14
+ {
15
+ once = false,
16
+ rootMargin,
17
+ threshold = 0,
18
+ disabled = false,
19
+ }: { once?: boolean; rootMargin?: string; threshold?: number; disabled?: boolean } = {},
20
+ ) {
21
+ const [inView, setInView] = useState(false);
22
+
23
+ useEffect(() => {
24
+ const element = ref.current;
25
+ if (!element || disabled) return;
26
+ if (typeof IntersectionObserver === 'undefined') {
27
+ setInView(true);
28
+ return;
29
+ }
30
+ const observer = new IntersectionObserver(
31
+ ([entry]) => {
32
+ // Initial observations can intersect without meeting the requested visible fraction.
33
+ if (entry.isIntersecting && entry.intersectionRatio >= threshold) {
34
+ setInView(true);
35
+ if (once) observer.disconnect();
36
+ } else if (!once) setInView(false);
37
+ },
38
+ { rootMargin, threshold },
39
+ );
40
+ observer.observe(element);
41
+ return () => observer.disconnect();
42
+ }, [ref, once, rootMargin, threshold, disabled]);
43
+
44
+ return inView;
45
+ }
46
+
47
+ /**
48
+ * Constants
49
+ */
50
+
51
+ /** Start listening to scroll a little before the track enters the viewport, and keep listening a little after. */
52
+ const SCROLL_ROOT_MARGIN = '25% 0px';
53
+
54
+ /*
55
+ * The step a scrolled element is at: how far its top has scrolled past the `top` line, as a
56
+ * share of `count × stepHeight` pixels, floored into `0..count - 1`; or, with `stepHeights`,
57
+ * each step its own number of pixels long, in order, `count` and `stepHeight` then being
58
+ * ignored. `onProgress` gets the continuous 0..1 position on every scroll frame (without a
59
+ * re-render) for anything that should move with the page. The scroll listener is only
60
+ * attached while the element is near the viewport, and reads one layout rectangle per frame.
61
+ */
62
+ export function useScrollStep(
63
+ ref: RefObject<HTMLElement | null>,
64
+ {
65
+ count,
66
+ stepHeight = 500,
67
+ stepHeights,
68
+ top = 0,
69
+ onProgress,
70
+ }: { count: number; stepHeight?: number; stepHeights?: number[]; top?: number; onProgress?: (progress: number) => void },
71
+ ) {
72
+ const onProgressRef = useRef(onProgress);
73
+ const [step, setStep] = useState(0);
74
+ // As one string, so a fresh array of the same heights does not restart the listener.
75
+ const heightsKey = stepHeights?.join(',');
76
+
77
+ useEffect(() => {
78
+ onProgressRef.current = onProgress;
79
+ }, [onProgress]);
80
+
81
+ // `stepHeights` is read through `heightsKey`, so a fresh array of the same values changes nothing.
82
+ useEffect(() => {
83
+ const element = ref.current;
84
+ if (!element) return;
85
+ // Where each step ends, in pixels from the start of the track.
86
+ const ends = getScrollStepEnds(heightsKey ? heightsKey.split(',').map(Number) : Array.from({ length: count }, () => stepHeight));
87
+ if (ends.length < 1) return;
88
+ let rafId = 0;
89
+ let listening = false;
90
+ const distance = ends[ends.length - 1];
91
+
92
+ const measure = () => {
93
+ rafId = 0;
94
+ const scrolled = top - element.getBoundingClientRect().top;
95
+ // Steps with no length yet (a layer not measured) are done as soon as the line is reached.
96
+ const progress = distance ? Math.min(1, Math.max(0, scrolled / distance)) : Number(scrolled >= 0);
97
+ // The first step not yet scrolled past; the last one once all are.
98
+ const at = ends.findIndex((end) => scrolled < end);
99
+ setStep(at === -1 ? ends.length - 1 : at);
100
+ onProgressRef.current?.(progress);
101
+ };
102
+ const schedule = () => {
103
+ if (!rafId) rafId = requestAnimationFrame(measure);
104
+ };
105
+ const listen = (on: boolean) => {
106
+ if (on === listening) return;
107
+ listening = on;
108
+ if (on) {
109
+ window.addEventListener('scroll', schedule, { passive: true });
110
+ window.addEventListener('resize', schedule);
111
+ schedule();
112
+ } else {
113
+ window.removeEventListener('scroll', schedule);
114
+ window.removeEventListener('resize', schedule);
115
+ }
116
+ };
117
+ const observer = new IntersectionObserver(([entry]) => listen(entry.isIntersecting), { rootMargin: SCROLL_ROOT_MARGIN });
118
+ observer.observe(element);
119
+ return () => {
120
+ observer.disconnect();
121
+ listen(false);
122
+ if (rafId) cancelAnimationFrame(rafId);
123
+ };
124
+ }, [ref, count, stepHeight, heightsKey, top]);
125
+
126
+ return step;
127
+ }
128
+
129
+ /*
130
+ * The running total of step heights: where each step ends along the track.
131
+ */
132
+ function getScrollStepEnds(heights: number[]) {
133
+ let total = 0;
134
+ return heights.map((height) => {
135
+ total += Math.max(0, height);
136
+ return total;
137
+ });
138
+ }
@@ -0,0 +1,98 @@
1
+ import { memo, useEffect, useRef } from 'react';
2
+ import type { CSSProperties, ReactNode } from 'react';
3
+ import { useScrollStep } from './ScrollSteps.hooks.ts';
4
+
5
+ export { useInView, useScrollStep } from './ScrollSteps.hooks.ts';
6
+
7
+ /**
8
+ * Constants
9
+ */
10
+
11
+ const SCROLL_STEPS = {
12
+ fadeMs: 450,
13
+ fadeEasing: 'cubic-bezier(0.22, 1, 0.36, 1)',
14
+ fadeShiftPx: 14,
15
+ };
16
+
17
+ /*
18
+ * A tall track with a sticky stage: while the visitor scrolls through the track the stage stays
19
+ * on screen and the active step advances every `stepHeight` pixels, from 0 to `count - 1`, then
20
+ * the stage scrolls away with the page. `children` renders the stage for the current step and
21
+ * re-renders only when the step changes; `onProgress` receives the continuous 0..1 position on
22
+ * every scroll frame for anything that should move with the page (see `useScrollStep`, which
23
+ * does the measuring and can drive any element the same way).
24
+ */
25
+ export const ScrollSteps = memo(
26
+ (p: {
27
+ /** Number of steps; the track is `count × stepHeight` taller than the stage. */
28
+ count: number;
29
+ /** Scroll distance each step holds for, in CSS pixels. */
30
+ stepHeight?: number;
31
+ /** CSS height of the sticky stage. */
32
+ stageHeight?: number | string;
33
+ /** Viewport offset the stage sticks at, in CSS pixels (room for a fixed header). */
34
+ top?: number;
35
+ className?: string;
36
+ style?: CSSProperties;
37
+ stageClassName?: string;
38
+ onProgress?: (progress: number) => void;
39
+ children: (step: number) => ReactNode;
40
+ }) => {
41
+ const { count, stepHeight = 500, stageHeight = '100vh', top = 0, className, style, stageClassName, onProgress, children } = p;
42
+ const trackRef = useRef<HTMLDivElement>(null);
43
+ const step = useScrollStep(trackRef, { count, stepHeight, top, onProgress });
44
+ const stageHeightCss = typeof stageHeight === 'number' ? `${stageHeight}px` : stageHeight;
45
+
46
+ return (
47
+ <div
48
+ ref={trackRef}
49
+ className={className}
50
+ style={{ ...style, height: `calc(${stageHeightCss} + ${count * stepHeight}px)` }}
51
+ >
52
+ <div
53
+ className={stageClassName}
54
+ style={{ position: 'sticky', top, height: stageHeightCss }}
55
+ >
56
+ {children(step)}
57
+ </div>
58
+ </div>
59
+ );
60
+ },
61
+ );
62
+
63
+ /*
64
+ * Content that fades and rises into place whenever `step` changes (not on mount), as a Web
65
+ * Animation so no stylesheet is needed; without the API, or with reduced motion, it just swaps.
66
+ */
67
+ export const ScrollStepFade = memo((p: { step: number; className?: string; style?: CSSProperties; children: ReactNode }) => {
68
+ const { step, className, style, children } = p;
69
+ const ref = useRef<HTMLDivElement>(null);
70
+ const mountedRef = useRef(false);
71
+
72
+ useEffect(() => {
73
+ const el = ref.current;
74
+ if (!mountedRef.current) {
75
+ mountedRef.current = true;
76
+ return;
77
+ }
78
+ if (!el || typeof el.animate !== 'function' || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
79
+ const animation = el.animate(
80
+ [
81
+ { opacity: 0, transform: `translateY(${SCROLL_STEPS.fadeShiftPx}px)` },
82
+ { opacity: 1, transform: 'none' },
83
+ ],
84
+ { duration: SCROLL_STEPS.fadeMs, easing: SCROLL_STEPS.fadeEasing },
85
+ );
86
+ return () => animation.cancel();
87
+ }, [step]);
88
+
89
+ return (
90
+ <div
91
+ ref={ref}
92
+ className={className}
93
+ style={style}
94
+ >
95
+ {children}
96
+ </div>
97
+ );
98
+ });
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@jsb188/gfx",
3
+ "version": "1.1.2",
4
+ "description": "Shared OGL/WebGL2 runtime, fullscreen pass chain, shader passes, and hero/section components for web graphics.",
5
+ "license": "ISC",
6
+ "author": "jsb188",
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "exports": {
10
+ ".": "./main.ts",
11
+ "./modules/GfxCanvas": "./modules/GfxCanvas.tsx",
12
+ "./modules/Hero": "./modules/Hero.tsx",
13
+ "./modules/KineticHeader": "./modules/KineticHeader.tsx",
14
+ "./modules/Dots": "./modules/Dots.tsx",
15
+ "./modules/Carousel": "./modules/Carousel.tsx",
16
+ "./modules/Gallery": "./modules/Gallery.tsx",
17
+ "./modules/ScrollSteps": "./modules/ScrollSteps.tsx",
18
+ "./elements/Shapes": "./elements/Shapes.tsx",
19
+ "./elements/Stack": "./elements/Stack.tsx",
20
+ "./elements/Text": "./elements/Text.tsx",
21
+ "./libs/runtime": "./libs/runtime.ts",
22
+ "./libs/types": "./libs/types.ts",
23
+ "./libs/uniforms": "./libs/uniforms.ts",
24
+ "./libs/chain": "./libs/chain.ts",
25
+ "./libs/glsl": "./libs/glsl.ts",
26
+ "./libs/passes": "./libs/passes.ts",
27
+ "./libs/texture": "./libs/texture.ts",
28
+ "./libs/dotGrid": "./libs/dotGrid.ts",
29
+ "./libs/effects": "./libs/effects/index.ts",
30
+ "./libs/effects/imageEffects": "./libs/effects/imageEffects.ts",
31
+ "./libs/effects/effectRegion": "./libs/effects/effectRegion.ts",
32
+ "./libs/effects/effectQuad": "./libs/effects/effectQuad.ts",
33
+ "./libs/effects/ripple": "./libs/effects/ripple.ts",
34
+ "./libs/effects/dotEffects": "./libs/effects/dotEffects.ts",
35
+ "./utils/color": "./utils/color.ts",
36
+ "./utils/easing": "./utils/easing.ts",
37
+ "./utils/motion": "./utils/motion.ts",
38
+ "./utils/align": "./utils/align.ts",
39
+ "./utils/imageEffectSpecs": "./utils/imageEffectSpecs.ts",
40
+ "./utils/dotGridSpecs": "./utils/dotGridSpecs.ts",
41
+ "./utils/dotEffectSpecs": "./utils/dotEffectSpecs.ts",
42
+ "./utils/strings": "./utils/strings.ts",
43
+ "./utils/random": "./utils/random.ts"
44
+ },
45
+ "peerDependencies": {
46
+ "ogl": "^1.0.11",
47
+ "react": "^19.3.0"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc"
51
+ }
52
+ }