phase 0.0.1-alpha.1 → 0.0.1

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.
package/dist/react.js ADDED
@@ -0,0 +1,1079 @@
1
+ "use client";
2
+ import { clamp01, easeOutCubic } from "./ease.js";
3
+ import { _ as missingContextError, a as subscribeDpr, c as createLoop, d as subscribeMediaQuery, f as createSight, h as invalidDurationError, i as readDpr, l as createLifecycle, n as prefersReducedMotion, o as createRenderState, r as whenIdle, s as createScrollProgress, t as REDUCED_MOTION_QUERY, u as readMediaQuery } from "./reduced-motion-CEJtegNG.js";
4
+ import { createContext, use, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
5
+ import { jsx } from "react/jsx-runtime";
6
+ //#region src/react/use-synced-ref/index.ts
7
+ /**
8
+ * Ref whose `.current` is always the latest value, updated synchronously on
9
+ * every render. Readable from any callback or effect without triggering re-render.
10
+ *
11
+ * @example
12
+ * const propsRef = useSyncedRef(props);
13
+ * useEffect(() => {
14
+ * // propsRef.current is always fresh
15
+ * }, []);
16
+ */
17
+ function useSyncedRef(value) {
18
+ "use no memo";
19
+ const ref = useRef(value);
20
+ ref.current = value;
21
+ return ref;
22
+ }
23
+ //#endregion
24
+ //#region src/react/use-stable-callback/index.ts
25
+ /**
26
+ * Returns a function with **stable identity** that always calls the latest
27
+ * version of `callback`. Safe in deps arrays and as a prop to `memo()`'d children.
28
+ *
29
+ * @example
30
+ * const handleClick = useStableCallback((e: MouseEvent) => {
31
+ * console.log(latestValue); // always fresh
32
+ * });
33
+ */
34
+ function useStableCallback(callback) {
35
+ "use no memo";
36
+ const callbackRef = useRef(callback);
37
+ callbackRef.current = callback;
38
+ return useCallback((...args) => callbackRef.current(...args), []);
39
+ }
40
+ //#endregion
41
+ //#region src/react/_internal/degraded-config/index.ts
42
+ /**
43
+ * Map flat `degraded` / `degradedFps` hook options onto the loop's discriminated
44
+ * union. `degradedFps` is only meaningful in `'throttle'` mode.
45
+ */
46
+ function degradedConfig(degraded, degradedFps) {
47
+ if (degraded === "pause") return { degraded: "pause" };
48
+ if (degraded === "ignore") return { degraded: "ignore" };
49
+ return {
50
+ degraded: "throttle",
51
+ degradedFps
52
+ };
53
+ }
54
+ //#endregion
55
+ //#region src/react/use-loop/index.ts
56
+ const INITIAL_STATE$3 = {
57
+ phase: "idle",
58
+ phaseReason: "initial",
59
+ quality: "full",
60
+ qualityReason: void 0
61
+ };
62
+ /**
63
+ * Ref-based animation loop that never triggers re-renders from the frame loop.
64
+ *
65
+ * @example
66
+ * const { ref, phase } = useLoop({
67
+ * onTick: (frame) => {
68
+ * ref.current.style.transform = `translateX(${frame.elapsed * 0.1}px)`;
69
+ * },
70
+ * });
71
+ * return <div ref={ref} />;
72
+ */
73
+ function useLoop(options) {
74
+ const { fps, enabled = true, reducedMotion, degraded, degradedFps, intersectionOptions } = options;
75
+ const onTickRef = useSyncedRef(options.onTick);
76
+ const internalRef = useRef(null);
77
+ const ref = options.ref ?? internalRef;
78
+ const [state, setState] = useState(INITIAL_STATE$3);
79
+ const loopRef = useRef(null);
80
+ useEffect(() => {
81
+ const element = ref.current;
82
+ if (!element || !enabled) {
83
+ setState(INITIAL_STATE$3);
84
+ return;
85
+ }
86
+ const loop = createLoop({
87
+ element,
88
+ onTick: (frame) => onTickRef.current(frame),
89
+ fps,
90
+ reducedMotion,
91
+ intersectionOptions,
92
+ ...degradedConfig(degraded, degradedFps),
93
+ onPhaseChange: (phase, reason) => {
94
+ const current = loopRef.current;
95
+ setState({
96
+ phase,
97
+ phaseReason: reason,
98
+ quality: current?.quality ?? "full",
99
+ qualityReason: current?.qualityReason
100
+ });
101
+ }
102
+ });
103
+ loopRef.current = loop;
104
+ return () => {
105
+ loop.stop();
106
+ loopRef.current = null;
107
+ };
108
+ }, [
109
+ enabled,
110
+ fps,
111
+ reducedMotion,
112
+ degraded,
113
+ degradedFps
114
+ ]);
115
+ return {
116
+ ref,
117
+ ...state
118
+ };
119
+ }
120
+ //#endregion
121
+ //#region src/react/use-lifecycle/index.ts
122
+ const INITIAL_STATE$2 = {
123
+ phase: "idle",
124
+ phaseReason: "initial"
125
+ };
126
+ /**
127
+ * React binding for `createLifecycle`. The activation signal for loops you own.
128
+ *
129
+ * Returns `active` / `paused` so a consumer-owned render loop (WebGL, three.js, a
130
+ * Web Worker) can pause when off-screen or under reduced motion. When `phase`
131
+ * should drive the loop for you, use `useLoop` or `useCanvas` instead.
132
+ *
133
+ * @example
134
+ * const { ref, isActive } = useLifecycle();
135
+ * useEffect(() => {
136
+ * if (!isActive) return;
137
+ * const id = requestAnimationFrame(function render() {
138
+ * renderer.render();
139
+ * requestAnimationFrame(render);
140
+ * });
141
+ * return () => cancelAnimationFrame(id);
142
+ * }, [isActive]);
143
+ * return <canvas ref={ref} />;
144
+ */
145
+ function useLifecycle(options) {
146
+ const { reducedMotion, intersectionOptions, enabled = true } = options ?? {};
147
+ const paused = options?.paused ?? false;
148
+ const onPhaseChangeRef = useSyncedRef(options?.onPhaseChange);
149
+ const internalRef = useRef(null);
150
+ const ref = options?.ref ?? internalRef;
151
+ const [state, setState] = useState(INITIAL_STATE$2);
152
+ const lifecycleRef = useRef(null);
153
+ useEffect(() => {
154
+ const element = ref.current;
155
+ if (!element || !enabled) {
156
+ setState(INITIAL_STATE$2);
157
+ return;
158
+ }
159
+ const lifecycle = createLifecycle({
160
+ element,
161
+ reducedMotion,
162
+ intersectionOptions,
163
+ onPhaseChange: (phase, phaseReason) => {
164
+ onPhaseChangeRef.current?.(phase, phaseReason);
165
+ setState({
166
+ phase,
167
+ phaseReason
168
+ });
169
+ }
170
+ });
171
+ lifecycleRef.current = lifecycle;
172
+ if (paused) lifecycle.pause();
173
+ return () => {
174
+ lifecycle.stop();
175
+ lifecycleRef.current = null;
176
+ };
177
+ }, [enabled, reducedMotion]);
178
+ useEffect(() => {
179
+ const lifecycle = lifecycleRef.current;
180
+ if (!lifecycle) return;
181
+ if (paused) lifecycle.pause();
182
+ else lifecycle.resume();
183
+ }, [paused]);
184
+ return {
185
+ ref,
186
+ ...state,
187
+ isActive: state.phase === "active"
188
+ };
189
+ }
190
+ //#endregion
191
+ //#region src/react/use-device-pixel-ratio/index.ts
192
+ /**
193
+ * Reactive devicePixelRatio that updates when the user moves the window
194
+ * between monitors with different DPR values.
195
+ *
196
+ * Returns `1` during SSR and initial hydration, then the live value.
197
+ */
198
+ function useDevicePixelRatio() {
199
+ const [dpr, setDpr] = useState(1);
200
+ useEffect(() => {
201
+ setDpr(readDpr());
202
+ return subscribeDpr(setDpr);
203
+ }, []);
204
+ return dpr;
205
+ }
206
+ //#endregion
207
+ //#region src/react/use-media/index.ts
208
+ /**
209
+ * Subscribe to a media query via the shared MQL pool.
210
+ *
211
+ * Returns `false` during SSR and initial hydration render,
212
+ * then the live value from the first `useEffect`.
213
+ *
214
+ * @example
215
+ * const isNarrow = useMediaQuery('(max-width: 600px)');
216
+ */
217
+ function useMediaQuery(query) {
218
+ const [matches, setMatches] = useState(false);
219
+ useEffect(() => {
220
+ setMatches(readMediaQuery(query));
221
+ return subscribeMediaQuery(query, setMatches);
222
+ }, [query]);
223
+ return matches;
224
+ }
225
+ //#endregion
226
+ //#region src/react/use-reduced-motion/index.ts
227
+ /**
228
+ * Reactive boolean that tracks the user's `prefers-reduced-motion` OS setting.
229
+ *
230
+ * Returns `false` during SSR and initial hydration, then the live value.
231
+ * Re-renders only when the preference changes.
232
+ */
233
+ function usePrefersReducedMotion() {
234
+ return useMediaQuery(REDUCED_MOTION_QUERY);
235
+ }
236
+ //#endregion
237
+ //#region src/react/use-sight/index.ts
238
+ const INITIAL_STATE$1 = {
239
+ phase: "unknown",
240
+ phaseReason: "initial"
241
+ };
242
+ /**
243
+ * Intersection + document visibility as a phase.
244
+ *
245
+ * Returns `'unknown'` during SSR and before first observation.
246
+ * `observe: 'once'` freezes at `'visible'` after first intersection and unobserves.
247
+ *
248
+ * @example
249
+ * const { ref, phase } = useSight();
250
+ * if (phase === 'visible') startAnimation();
251
+ * return <div ref={ref} />;
252
+ */
253
+ function useSight(options) {
254
+ const [state, setState] = useState(INITIAL_STATE$1);
255
+ const observe = options?.observe ?? "continuous";
256
+ const internalRef = useRef(null);
257
+ const ref = options?.ref ?? internalRef;
258
+ useEffect(() => {
259
+ const element = ref.current;
260
+ if (!element) return;
261
+ let frozen = false;
262
+ const sight = createSight({
263
+ element,
264
+ intersectionOptions: {
265
+ root: options?.root,
266
+ rootMargin: options?.rootMargin,
267
+ threshold: options?.threshold
268
+ },
269
+ onPhaseChange: (phase, reason) => {
270
+ if (frozen) return;
271
+ setState({
272
+ phase,
273
+ phaseReason: reason
274
+ });
275
+ if (observe === "once" && phase === "visible") {
276
+ frozen = true;
277
+ sight.stop();
278
+ }
279
+ }
280
+ });
281
+ return () => sight.stop();
282
+ }, [observe]);
283
+ return {
284
+ ref,
285
+ ...state
286
+ };
287
+ }
288
+ //#endregion
289
+ //#region src/core/_internal/pool/ro-pool.ts
290
+ let observer = null;
291
+ const callbacks = /* @__PURE__ */ new Map();
292
+ /**
293
+ * Observe an element via a singleton ResizeObserver.
294
+ * One RO instance for the entire page. RO takes zero constructor options.
295
+ *
296
+ * @returns Cleanup function that unobserves the element.
297
+ */
298
+ function observeResize(element, callback) {
299
+ callbacks.set(element, callback);
300
+ getObserver().observe(element);
301
+ let disposed = false;
302
+ return () => {
303
+ if (disposed) return;
304
+ disposed = true;
305
+ if (callbacks.get(element) === callback) {
306
+ callbacks.delete(element);
307
+ observer?.unobserve(element);
308
+ }
309
+ };
310
+ }
311
+ /** Lazy-created singleton. RO takes zero constructor options, so one instance can observe everything. */
312
+ function getObserver() {
313
+ if (!observer) observer = new ResizeObserver((entries) => {
314
+ for (const entry of entries) {
315
+ const cb = callbacks.get(entry.target);
316
+ if (cb) cb(entry);
317
+ }
318
+ });
319
+ return observer;
320
+ }
321
+ //#endregion
322
+ //#region src/react/use-size/index.ts
323
+ /**
324
+ * Element dimensions via the shared ResizeObserver singleton.
325
+ *
326
+ * `size` is `null` until the first observation. Never calls `getBoundingClientRect()`.
327
+ * RO callbacks are compositor-aligned (once per frame), so no rAF coalescing needed.
328
+ *
329
+ * @example
330
+ * const { ref, size } = useSize();
331
+ * return <div ref={ref}>{size?.width}</div>;
332
+ */
333
+ function useSize(options) {
334
+ const [size, setSize] = useState(null);
335
+ const prevWidth = useRef(null);
336
+ const prevHeight = useRef(null);
337
+ const internalRef = useRef(null);
338
+ const ref = options?.ref ?? internalRef;
339
+ useEffect(() => {
340
+ const element = ref.current;
341
+ if (!element) return;
342
+ return observeResize(element, (entry) => {
343
+ const box = entry.contentBoxSize[0];
344
+ if (!box) return;
345
+ const width = box.inlineSize;
346
+ const height = box.blockSize;
347
+ if (width === prevWidth.current && height === prevHeight.current) return;
348
+ prevWidth.current = width;
349
+ prevHeight.current = height;
350
+ setSize({
351
+ width,
352
+ height
353
+ });
354
+ });
355
+ }, []);
356
+ return {
357
+ ref,
358
+ size
359
+ };
360
+ }
361
+ //#endregion
362
+ //#region src/react/use-container-query/index.ts
363
+ /**
364
+ * Returns whether an element matches a size-based container breakpoint.
365
+ *
366
+ * Unlike `useSize` (which re-renders on every pixel of resize), this hook only
367
+ * re-renders when the match result changes, i.e. when the element crosses a
368
+ * breakpoint boundary. Uses the shared ResizeObserver singleton.
369
+ *
370
+ * @example
371
+ * const { ref, matches } = useContainerQuery({ minWidth: 600 });
372
+ * return <div ref={ref}>{matches ? 'wide' : 'narrow'}</div>;
373
+ */
374
+ function useContainerQuery(breakpoint, options) {
375
+ const [matches, setMatches] = useState(false);
376
+ const matchesRef = useRef(false);
377
+ const internalRef = useRef(null);
378
+ const ref = options?.ref ?? internalRef;
379
+ const { minWidth, maxWidth, minHeight, maxHeight } = breakpoint;
380
+ useEffect(() => {
381
+ const element = ref.current;
382
+ if (!element) return;
383
+ return observeResize(element, (entry) => {
384
+ const box = entry.contentBoxSize[0];
385
+ if (!box) return;
386
+ const width = box.inlineSize;
387
+ const height = box.blockSize;
388
+ const nowMatches = evaluateBreakpoint(width, height, minWidth, maxWidth, minHeight, maxHeight);
389
+ if (nowMatches !== matchesRef.current) {
390
+ matchesRef.current = nowMatches;
391
+ setMatches(nowMatches);
392
+ }
393
+ });
394
+ }, [
395
+ minWidth,
396
+ maxWidth,
397
+ minHeight,
398
+ maxHeight
399
+ ]);
400
+ return {
401
+ ref,
402
+ matches
403
+ };
404
+ }
405
+ function evaluateBreakpoint(width, height, minWidth, maxWidth, minHeight, maxHeight) {
406
+ if (minWidth !== void 0 && width < minWidth) return false;
407
+ if (maxWidth !== void 0 && width > maxWidth) return false;
408
+ if (minHeight !== void 0 && height < minHeight) return false;
409
+ if (maxHeight !== void 0 && height > maxHeight) return false;
410
+ return true;
411
+ }
412
+ //#endregion
413
+ //#region src/react/use-scroll-progress/index.ts
414
+ /**
415
+ * Element visibility ratio (0–1) via the shared IntersectionObserver pool.
416
+ *
417
+ * Reports the fraction of the element currently visible. Ideal for reveal/opacity
418
+ * effects. Not a scroll-scrubbing engine: event-driven and quantized to `steps`.
419
+ *
420
+ * Re-renders only at threshold crossings (~20 per full viewport traversal).
421
+ * `progress` is `0` before first observation and during SSR.
422
+ *
423
+ * @example
424
+ * const { ref, progress } = useScrollProgress();
425
+ * return <div ref={ref} style={{ opacity: progress }} />;
426
+ */
427
+ function useScrollProgress(options) {
428
+ const [progress, setProgress] = useState(0);
429
+ const steps = options?.steps;
430
+ const rootMargin = options?.rootMargin;
431
+ const internalRef = useRef(null);
432
+ const ref = options?.ref ?? internalRef;
433
+ useEffect(() => {
434
+ const element = ref.current;
435
+ if (!element) return;
436
+ const scrollProgress = createScrollProgress({
437
+ element,
438
+ onProgress: setProgress,
439
+ steps,
440
+ root: options?.root,
441
+ rootMargin
442
+ });
443
+ return () => scrollProgress.stop();
444
+ }, [steps, rootMargin]);
445
+ return {
446
+ ref,
447
+ progress
448
+ };
449
+ }
450
+ //#endregion
451
+ //#region src/react/use-render-state/index.ts
452
+ /**
453
+ * Track whether the browser is rendering an element or skipping it under
454
+ * `content-visibility` (e.g. a `Defer` subtree). Returns `'rendered'` until the
455
+ * browser reports otherwise.
456
+ *
457
+ * Use it to pause raw, non-phase work (a hand-written rAF loop, `setInterval`)
458
+ * when the subtree stops painting. phase loops self-pause off-screen already.
459
+ * Has no layout effect. Safe for CLS.
460
+ *
461
+ * @example
462
+ * const ref = useRef<HTMLDivElement>(null);
463
+ * const phase = useRenderState(ref);
464
+ * useEffect(() => {
465
+ * if (phase === 'skipped') clock.pause();
466
+ * else clock.resume();
467
+ * }, [phase]);
468
+ * return <Defer ref={ref}><Heavy /></Defer>;
469
+ */
470
+ function useRenderState(ref) {
471
+ const [phase, setPhase] = useState("rendered");
472
+ useEffect(() => {
473
+ const element = ref.current;
474
+ if (!element) return;
475
+ const render = createRenderState({
476
+ element,
477
+ onPhaseChange: setPhase
478
+ });
479
+ return () => render.stop();
480
+ }, []);
481
+ return phase;
482
+ }
483
+ //#endregion
484
+ //#region src/react/use-idle/index.ts
485
+ /**
486
+ * Returns `false`, then `true` once the browser is idle after mount. Use it to
487
+ * defer non-critical work or mounting until the main thread is free.
488
+ *
489
+ * SSR-safe: returns `false` on the server and during the first client render.
490
+ *
491
+ * @example
492
+ * const idle = useIdle();
493
+ * return idle ? <Analytics /> : null;
494
+ */
495
+ function useIdle(options) {
496
+ const [idle, setIdle] = useState(false);
497
+ const timeout = options?.timeout;
498
+ useEffect(() => {
499
+ return whenIdle(() => setIdle(true), { timeout });
500
+ }, [timeout]);
501
+ return idle;
502
+ }
503
+ //#endregion
504
+ //#region src/react/use-when-idle/index.ts
505
+ /**
506
+ * Run a callback once, when the browser is idle after mount. The effect-shaped
507
+ * counterpart to `useIdle`. Use it for side effects (prefetching a chunk,
508
+ * warming a cache, `import()`) rather than rendering.
509
+ *
510
+ * Cancels automatically on unmount, and always calls the latest `callback`
511
+ * without re-subscribing. SSR-safe: nothing runs on the server.
512
+ *
513
+ * @example
514
+ * // Prefetch a heavy panel during idle time so it opens instantly later.
515
+ * useWhenIdle(() => void import('./chat-panel'));
516
+ */
517
+ function useWhenIdle(callback, options) {
518
+ const callbackRef = useSyncedRef(callback);
519
+ const timeout = options?.timeout;
520
+ useEffect(() => {
521
+ return whenIdle(() => callbackRef.current(), { timeout });
522
+ }, [timeout]);
523
+ }
524
+ //#endregion
525
+ //#region src/react/use-canvas/index.ts
526
+ const INITIAL_STATE = {
527
+ phase: "idle",
528
+ phaseReason: "initial",
529
+ quality: "full",
530
+ qualityReason: void 0
531
+ };
532
+ /**
533
+ * Canvas-specific animation with DPR-aware sizing, ResizeObserver coalescing,
534
+ * context management, and GPU context loss recovery.
535
+ *
536
+ * @example
537
+ * useCanvas({
538
+ * containerRef,
539
+ * canvasRef,
540
+ * draw: (ctx, frame, size) => {
541
+ * ctx.clearRect(0, 0, size.width, size.height);
542
+ * // render...
543
+ * },
544
+ * });
545
+ */
546
+ function useCanvas(options) {
547
+ const { containerRef, canvasRef, fps, enabled = true, reducedMotion, degraded, degradedFps } = options;
548
+ const drawRef = useSyncedRef(options.draw);
549
+ const [state, setState] = useState(INITIAL_STATE);
550
+ const [restartNonce, setRestartNonce] = useState(0);
551
+ const ctxRef = useRef(null);
552
+ const sizeRef = useRef({
553
+ width: 0,
554
+ height: 0
555
+ });
556
+ const qualityRef = useSyncedRef(state.quality);
557
+ useEffect(() => {
558
+ const container = containerRef.current;
559
+ const canvasEl = canvasRef.current;
560
+ if (!container || !canvasEl || !enabled) return;
561
+ const canvas = canvasEl;
562
+ const initialCtx = canvas.getContext("2d");
563
+ if (!initialCtx) return;
564
+ ctxRef.current = initialCtx;
565
+ let dpr = readDpr();
566
+ let contextLost = false;
567
+ function applySize(width, height, physicalBox) {
568
+ sizeRef.current = {
569
+ width,
570
+ height
571
+ };
572
+ const isDegraded = qualityRef.current === "degraded";
573
+ let bufferWidth;
574
+ let bufferHeight;
575
+ if (isDegraded) {
576
+ bufferWidth = width;
577
+ bufferHeight = height;
578
+ } else if (physicalBox) {
579
+ bufferWidth = physicalBox.inlineSize;
580
+ bufferHeight = physicalBox.blockSize;
581
+ } else {
582
+ bufferWidth = width * dpr;
583
+ bufferHeight = height * dpr;
584
+ }
585
+ canvas.width = bufferWidth;
586
+ canvas.height = bufferHeight;
587
+ canvas.style.width = width + "px";
588
+ canvas.style.height = height + "px";
589
+ const effectiveDpr = isDegraded ? 1 : dpr;
590
+ ctxRef.current?.setTransform(effectiveDpr, 0, 0, effectiveDpr, 0, 0);
591
+ }
592
+ const unsubDpr = subscribeDpr((newDpr) => {
593
+ dpr = newDpr;
594
+ applySize(sizeRef.current.width, sizeRef.current.height);
595
+ });
596
+ const unobserve = observeResize(container, (entry) => {
597
+ const box = entry.contentBoxSize[0];
598
+ if (!box) return;
599
+ const physicalBox = entry.devicePixelContentBoxSize?.[0];
600
+ applySize(box.inlineSize, box.blockSize, physicalBox);
601
+ });
602
+ function onContextLost(event) {
603
+ event.preventDefault();
604
+ contextLost = true;
605
+ }
606
+ function onContextRestored() {
607
+ const restoredCtx = canvas.getContext("2d");
608
+ if (!restoredCtx) return;
609
+ ctxRef.current = restoredCtx;
610
+ contextLost = false;
611
+ applySize(sizeRef.current.width, sizeRef.current.height);
612
+ }
613
+ canvas.addEventListener("contextlost", onContextLost);
614
+ canvas.addEventListener("contextrestored", onContextRestored);
615
+ let loopInstance = null;
616
+ const loop = createLoop({
617
+ element: container,
618
+ fps,
619
+ reducedMotion,
620
+ ...degradedConfig(degraded, degradedFps),
621
+ onTick: (frame) => {
622
+ if (contextLost || !ctxRef.current) return;
623
+ drawRef.current(ctxRef.current, frame, sizeRef.current);
624
+ },
625
+ onPhaseChange: (phase, reason) => {
626
+ setState({
627
+ phase,
628
+ phaseReason: reason,
629
+ quality: loopInstance?.quality ?? "full",
630
+ qualityReason: loopInstance?.qualityReason
631
+ });
632
+ }
633
+ });
634
+ loopInstance = loop;
635
+ function teardown() {
636
+ loop.stop();
637
+ loopInstance = null;
638
+ unobserve();
639
+ unsubDpr();
640
+ canvas.removeEventListener("contextlost", onContextLost);
641
+ canvas.removeEventListener("contextrestored", onContextRestored);
642
+ }
643
+ return teardown;
644
+ }, [
645
+ enabled,
646
+ fps,
647
+ reducedMotion,
648
+ degraded,
649
+ degradedFps,
650
+ restartNonce
651
+ ]);
652
+ return {
653
+ restart: useCallback(() => {
654
+ setRestartNonce((n) => n + 1);
655
+ }, []),
656
+ ...state
657
+ };
658
+ }
659
+ //#endregion
660
+ //#region src/react/use-tween/index.ts
661
+ /**
662
+ * Animate a value from its current position to `target` over `duration`.
663
+ *
664
+ * Uses `useState` per frame. Appropriate for cheap renders (counters, opacity,
665
+ * progress bars). For batch animations, use `useLoop` with ref-based DOM writes.
666
+ *
667
+ * @remarks
668
+ * Unlike `createTicker`/`createLoop`, `useTween` drives its own rAF rather than
669
+ * the shared frame-locked clock. It's a finite, self-completing tween whose value
670
+ * must land in React state, so it doesn't need cross-loop visual sync, strong
671
+ * pause, or delta clamping. Routing it through the shared clock would add bundle
672
+ * weight for no benefit.
673
+ *
674
+ * @example
675
+ * const value = useTween({ target: 100, duration: 500 });
676
+ */
677
+ function useTween(options) {
678
+ const { target, duration = 300, delay = 0, easing = easeOutCubic, enabled = true, reducedMotion = "complete" } = options;
679
+ const [value, setValue] = useState(target);
680
+ const fromRef = useRef(target);
681
+ const currentRef = useRef(target);
682
+ const isFirstRender = useRef(true);
683
+ useEffect(() => {
684
+ if (!Number.isFinite(duration) || duration <= 0) invalidDurationError("useTween", duration);
685
+ if (isFirstRender.current) {
686
+ isFirstRender.current = false;
687
+ jumpToTarget({
688
+ target,
689
+ fromRef,
690
+ currentRef,
691
+ setValue
692
+ });
693
+ return;
694
+ }
695
+ if (!enabled || reducedMotion !== "ignore" && prefersReducedMotion()) {
696
+ jumpToTarget({
697
+ target,
698
+ fromRef,
699
+ currentRef,
700
+ setValue
701
+ });
702
+ return;
703
+ }
704
+ const from = currentRef.current;
705
+ if (from === target) return;
706
+ let rafId;
707
+ let startTime = null;
708
+ function tick(now) {
709
+ if (startTime === null) startTime = now;
710
+ const elapsed = now - startTime - delay;
711
+ if (elapsed < 0) {
712
+ rafId = requestAnimationFrame(tick);
713
+ return;
714
+ }
715
+ const progress = clamp01(elapsed / duration);
716
+ const current = from + (target - from) * easing(progress);
717
+ currentRef.current = current;
718
+ setValue(current);
719
+ if (progress < 1) rafId = requestAnimationFrame(tick);
720
+ else fromRef.current = target;
721
+ }
722
+ rafId = requestAnimationFrame(tick);
723
+ return () => {
724
+ cancelAnimationFrame(rafId);
725
+ fromRef.current = currentRef.current;
726
+ };
727
+ }, [
728
+ target,
729
+ duration,
730
+ delay,
731
+ enabled,
732
+ reducedMotion
733
+ ]);
734
+ return value;
735
+ }
736
+ function jumpToTarget(options) {
737
+ const { target, fromRef, currentRef, setValue } = options;
738
+ fromRef.current = target;
739
+ currentRef.current = target;
740
+ setValue(target);
741
+ }
742
+ //#endregion
743
+ //#region src/react/_internal/use-update-effect/index.ts
744
+ /**
745
+ * Like `useEffect` but skips the first invocation on mount.
746
+ * Used by Presence to distinguish initial render from subsequent `show` changes.
747
+ */
748
+ function useUpdateEffect(effect, deps) {
749
+ const isMounted = useRef(false);
750
+ useEffect(() => {
751
+ if (!isMounted.current) {
752
+ isMounted.current = true;
753
+ return;
754
+ }
755
+ return effect();
756
+ }, deps);
757
+ }
758
+ //#endregion
759
+ //#region src/react/use-presence/index.ts
760
+ /**
761
+ * Composable presence primitive for mount/unmount lifecycle with CSS transitions.
762
+ *
763
+ * Enter animations use CSS `@starting-style`, gated by `data-enter="animate"`.
764
+ * Exit animations are JS-coordinated: waits for `transitionend`/`animationend`
765
+ * before unmounting.
766
+ *
767
+ * @example
768
+ * const { phase, ref, mounted, enter } = usePresence({ show: isOpen });
769
+ * if (!mounted) return null;
770
+ * return (
771
+ * <div ref={ref} data-phase={phase} data-enter={enter === 'animate' ? 'animate' : undefined}
772
+ * className="transition-opacity data-[enter=animate]:starting:opacity-0 data-[phase=exiting]:opacity-0" />
773
+ * );
774
+ */
775
+ function usePresence(options) {
776
+ const { show, mode = "mount", enter: enterOption = "animate", exitDuration = 5e3, reducedMotion = "respect" } = options;
777
+ const ref = useRef(null);
778
+ const [phase, setPhase] = useState(show ? "entered" : "idle");
779
+ const [reason, setReason] = useState("initial");
780
+ const exitTimerRef = useRef(null);
781
+ const exitCleanupRef = useRef(null);
782
+ const clearTimers = useCallback(() => {
783
+ if (exitTimerRef.current !== null) {
784
+ clearTimeout(exitTimerRef.current);
785
+ exitTimerRef.current = null;
786
+ }
787
+ if (exitCleanupRef.current) {
788
+ exitCleanupRef.current();
789
+ exitCleanupRef.current = null;
790
+ }
791
+ }, []);
792
+ useEffect(() => () => clearTimers(), [clearTimers]);
793
+ useUpdateEffect(() => {
794
+ clearTimers();
795
+ if (show) setPhase((prev) => {
796
+ setReason(prev === "exiting" ? "interrupted" : "show");
797
+ return "entered";
798
+ });
799
+ else if (reducedMotion === "respect" && prefersReducedMotion()) {
800
+ setPhase(mode === "reveal" ? "idle" : "exited");
801
+ setReason("animation-end");
802
+ } else handleExit(ref, mode, exitDuration, setPhase, setReason, clearTimers, exitTimerRef, exitCleanupRef);
803
+ }, [show]);
804
+ const mounted = phase !== "idle" && phase !== "exited";
805
+ const wantsAnimation = !(reason === "initial" && enterOption === "instant");
806
+ const motionAllowed = reducedMotion === "ignore" || !prefersReducedMotion();
807
+ return {
808
+ phase,
809
+ phaseReason: reason,
810
+ mounted,
811
+ ref,
812
+ enter: wantsAnimation && motionAllowed ? "animate" : "instant"
813
+ };
814
+ }
815
+ function handleExit(ref, mode, exitDuration, setPhase, setReason, clearTimers, exitTimerRef, exitCleanupRef) {
816
+ setPhase("exiting");
817
+ setReason("hide");
818
+ const exitTarget = mode === "reveal" ? "idle" : "exited";
819
+ const element = ref.current;
820
+ function completeExit() {
821
+ clearTimers();
822
+ setPhase((current) => {
823
+ if (current !== "exiting") return current;
824
+ setReason("animation-end");
825
+ return exitTarget;
826
+ });
827
+ }
828
+ function cleanup() {
829
+ if (element) {
830
+ element.removeEventListener("transitionend", completeExit);
831
+ element.removeEventListener("animationend", completeExit);
832
+ }
833
+ if (exitTimerRef.current !== null) {
834
+ clearTimeout(exitTimerRef.current);
835
+ exitTimerRef.current = null;
836
+ }
837
+ exitCleanupRef.current = null;
838
+ }
839
+ exitCleanupRef.current = cleanup;
840
+ if (element) {
841
+ element.addEventListener("transitionend", completeExit, { once: true });
842
+ element.addEventListener("animationend", completeExit, { once: true });
843
+ }
844
+ exitTimerRef.current = setTimeout(completeExit, exitDuration);
845
+ }
846
+ //#endregion
847
+ //#region src/react/presence/index.tsx
848
+ /**
849
+ * Renders a `div` that manages its own mounting lifecycle.
850
+ *
851
+ * Stamps `data-phase` for exit animations and `data-enter="animate"` to gate
852
+ * CSS `@starting-style` enter animations. Reduced motion is handled automatically.
853
+ *
854
+ * @example
855
+ * <Presence
856
+ * show={isOpen}
857
+ * className="transition-opacity data-[enter=animate]:starting:opacity-0 data-[phase=exiting]:opacity-0"
858
+ * >
859
+ * Modal content
860
+ * </Presence>
861
+ */
862
+ function Presence({ show, mode, enter: enterOption, exitDuration, reducedMotion, ref: forwardedRef, children, ...divProps }) {
863
+ const { phase, ref, mounted, enter } = usePresence({
864
+ show,
865
+ mode,
866
+ enter: enterOption,
867
+ exitDuration,
868
+ reducedMotion
869
+ });
870
+ useImperativeHandle(forwardedRef, () => ref.current);
871
+ if (!mounted && mode !== "reveal") return null;
872
+ return /* @__PURE__ */ jsx("div", {
873
+ ...divProps,
874
+ ref,
875
+ "data-phase": phase,
876
+ "data-enter": enter === "animate" ? "animate" : void 0,
877
+ children
878
+ });
879
+ }
880
+ //#endregion
881
+ //#region src/react/when-visible/index.tsx
882
+ /**
883
+ * Mounts children when the element enters the viewport. One-shot (once
884
+ * triggered, stays mounted).
885
+ *
886
+ * Enter animation uses CSS `@starting-style`, gated by `data-enter="animate"`.
887
+ * Reduced motion is automatic: the attribute is not stamped when the user
888
+ * prefers reduced motion.
889
+ *
890
+ * @example
891
+ * <WhenVisible rootMargin="200px" className="transition-opacity data-[enter=animate]:starting:opacity-0">
892
+ * <HeavyChart />
893
+ * </WhenVisible>
894
+ */
895
+ function WhenVisible({ rootMargin = "200px", threshold, root, fallback, children, ref: forwardedRef, ...divProps }) {
896
+ const sentinelRef = useRef(null);
897
+ const { phase } = useSight({
898
+ ref: sentinelRef,
899
+ observe: "once",
900
+ rootMargin,
901
+ threshold,
902
+ root
903
+ });
904
+ const setRef = (node) => {
905
+ sentinelRef.current = node;
906
+ assignRef(forwardedRef, node);
907
+ };
908
+ if (phase !== "visible") return /* @__PURE__ */ jsx("div", {
909
+ ref: setRef,
910
+ ...divProps,
911
+ children: fallback
912
+ });
913
+ const motionAllowed = !prefersReducedMotion();
914
+ return /* @__PURE__ */ jsx("div", {
915
+ ...divProps,
916
+ ref: setRef,
917
+ "data-phase": "entered",
918
+ "data-enter": motionAllowed ? "animate" : void 0,
919
+ children
920
+ });
921
+ }
922
+ function assignRef(ref, node) {
923
+ if (typeof ref === "function") ref(node);
924
+ else if (ref) ref.current = node;
925
+ }
926
+ //#endregion
927
+ //#region src/react/when-idle/index.tsx
928
+ /**
929
+ * Mounts children once the browser is idle after first paint. One-shot (once
930
+ * mounted, stays mounted). Use it to defer non-critical UI off the critical path.
931
+ *
932
+ * Children are not server-rendered (idle never fires during SSR), so reserve
933
+ * this for non-critical content. For viewport-gated mounting use `WhenVisible`;
934
+ * to keep content in the DOM but skip painting use `Defer`.
935
+ *
936
+ * Enter animation uses CSS `@starting-style`, gated by `data-enter="animate"`.
937
+ * Reduced motion is automatic: the attribute is not stamped when the user
938
+ * prefers reduced motion.
939
+ *
940
+ * @example
941
+ * <WhenIdle fallback={<Skeleton />}>
942
+ * <SecondaryPanel />
943
+ * </WhenIdle>
944
+ */
945
+ function WhenIdle({ timeout, fallback, children, ref: forwardedRef, ...divProps }) {
946
+ if (!useIdle({ timeout })) return /* @__PURE__ */ jsx("div", {
947
+ ...divProps,
948
+ children: fallback
949
+ });
950
+ const motionAllowed = !prefersReducedMotion();
951
+ return /* @__PURE__ */ jsx("div", {
952
+ ...divProps,
953
+ ref: forwardedRef,
954
+ "data-phase": "entered",
955
+ "data-enter": motionAllowed ? "animate" : void 0,
956
+ children
957
+ });
958
+ }
959
+ //#endregion
960
+ //#region src/react/defer/index.tsx
961
+ /**
962
+ * Skip the browser's rendering work (style, layout, paint) for off-screen
963
+ * content via `content-visibility: auto`. Pure CSS, no JS, no observer.
964
+ *
965
+ * Children stay in the DOM and are server-rendered (SEO- and CLS-safe).
966
+ * `contain-intrinsic-size: auto <estimatedHeight>` reserves space so the
967
+ * scrollbar does not jump. Defers rendering only, not hydration or mounting.
968
+ *
969
+ * The render-skip styles are encapsulated and cannot be overridden. There is
970
+ * no `style` prop. Style the wrapper with `className`; this keeps the
971
+ * no-layout-shift guarantee intact.
972
+ *
973
+ * @example
974
+ * <Defer estimatedHeight="600px" className="my-section">
975
+ * <ArticleSection />
976
+ * </Defer>
977
+ *
978
+ * @remarks
979
+ * Animations inside a `Defer` keep running while paint is skipped. phase loops
980
+ * self-pause off-screen on their own; for raw rAF/interval work, gate it with
981
+ * `useRenderState`.
982
+ */
983
+ function Defer({ estimatedHeight = "1000px", children, ref, ...divProps }) {
984
+ const deferStyle = {
985
+ contentVisibility: "auto",
986
+ containIntrinsicSize: `auto ${estimatedHeight}`
987
+ };
988
+ return /* @__PURE__ */ jsx("div", {
989
+ ...divProps,
990
+ ref,
991
+ style: deferStyle,
992
+ children
993
+ });
994
+ }
995
+ //#endregion
996
+ //#region src/react/swap/index.tsx
997
+ const SwapCtx = createContext(null);
998
+ /**
999
+ * Coordinated exit-then-enter transitions for N states.
1000
+ * Only one state is entering or exiting at a time (no overlap).
1001
+ *
1002
+ * The current state fully exits before the new state enters. Rapid changes
1003
+ * (A->B->C during A's exit) skip intermediate states and jump to the latest.
1004
+ *
1005
+ * @example
1006
+ * <Swap active={success ? 'success' : 'form'}>
1007
+ * <Swap.State id="form" className="transition-all data-[phase=exiting]:opacity-0">
1008
+ * <Form />
1009
+ * </Swap.State>
1010
+ * <Swap.State id="success" className="transition-all data-[enter=animate]:starting:opacity-0">
1011
+ * <SuccessMessage />
1012
+ * </Swap.State>
1013
+ * </Swap>
1014
+ */
1015
+ function SwapRoot({ active, exitDuration = 5e3, children, ...divProps }) {
1016
+ const [current, setCurrent] = useState(active);
1017
+ const [hasSwapped, setHasSwapped] = useState(false);
1018
+ const activeRef = useSyncedRef(active);
1019
+ const onExited = useCallback((id) => {
1020
+ setHasSwapped(true);
1021
+ setCurrent((cur) => cur === id ? activeRef.current : cur);
1022
+ }, [activeRef]);
1023
+ const enter = hasSwapped ? "animate" : "instant";
1024
+ const ctx = useMemo(() => ({
1025
+ current,
1026
+ active,
1027
+ exitDuration,
1028
+ enter,
1029
+ onExited
1030
+ }), [
1031
+ current,
1032
+ active,
1033
+ exitDuration,
1034
+ enter,
1035
+ onExited
1036
+ ]);
1037
+ return /* @__PURE__ */ jsx(SwapCtx.Provider, {
1038
+ value: ctx,
1039
+ children: /* @__PURE__ */ jsx("div", {
1040
+ ...divProps,
1041
+ children
1042
+ })
1043
+ });
1044
+ }
1045
+ function SwapState({ id, ref: forwardedRef, children, ...divProps }) {
1046
+ const ctx = use(SwapCtx);
1047
+ if (!ctx) missingContextError("Swap.State", "Swap");
1048
+ const isCurrent = ctx.current === id;
1049
+ const show = isCurrent && ctx.active === id;
1050
+ const { phase, ref, mounted, enter } = usePresence({
1051
+ show,
1052
+ mode: "mount",
1053
+ enter: ctx.enter,
1054
+ exitDuration: ctx.exitDuration
1055
+ });
1056
+ useImperativeHandle(forwardedRef, () => ref.current);
1057
+ useEffect(() => {
1058
+ if (isCurrent && !show && phase === "exited") ctx.onExited(id);
1059
+ }, [
1060
+ isCurrent,
1061
+ show,
1062
+ phase,
1063
+ id,
1064
+ ctx
1065
+ ]);
1066
+ if (!isCurrent || !mounted) return null;
1067
+ return /* @__PURE__ */ jsx("div", {
1068
+ ...divProps,
1069
+ ref,
1070
+ "data-phase": phase,
1071
+ "data-enter": enter === "animate" ? "animate" : void 0,
1072
+ children
1073
+ });
1074
+ }
1075
+ const Swap = Object.assign(SwapRoot, { State: SwapState });
1076
+ //#endregion
1077
+ export { Defer, Presence, Swap, WhenIdle, WhenVisible, useCanvas, useContainerQuery, useDevicePixelRatio, useIdle, useLifecycle, useLoop, useMediaQuery, usePrefersReducedMotion, usePresence, useRenderState, useScrollProgress, useSight, useSize, useStableCallback, useSyncedRef, useTween, useWhenIdle };
1078
+
1079
+ //# sourceMappingURL=react.js.map