phase 0.0.1-alpha.1 → 0.0.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.
package/README.md ADDED
@@ -0,0 +1,917 @@
1
+ <p align="center">
2
+ <img src=".github/assets/phase-header.png" alt="phase" />
3
+ </p>
4
+
5
+ # ▲ phase
6
+
7
+ > **Status: Alpha.** APIs are evolving rapidly. Expect breaking changes.
8
+
9
+ Phase is a lightweight, lifecycle-aware UI performance layer for the web. It includes tools & guidance to optimize render performance, build performant animations, and manage layout and off-screen resources.
10
+
11
+ ## Why phase
12
+
13
+ You can't accidentally tank the main thread, leak an observer, jank on scroll, or ignore reduced motion. The hard parts are handled for you, so the slow path isn't even reachable:
14
+
15
+ - **Pauses when unseen.** Off-screen or in a background tab, work stops and CPU drops to zero.
16
+ - **Respects reduced motion by default.** Accessibility is built in, not an opt-in.
17
+ - **Never forces a reflow.** No `getBoundingClientRect`, no layout thrash, anywhere in the package.
18
+ - **Zero re-renders from the frame loop.** Per-frame work writes to refs and the DOM, never React state.
19
+ - **Frame-locked shared clock.** Every animation on the page reads one clock, so nothing drifts out of sync.
20
+ - **Renders only what matters.** Skip painting off-screen content, mount non-critical UI when idle.
21
+
22
+ Each guarantee is a [tested invariant](#guarantees), not an aspiration. Every export stays [sub-kilobyte to a few kilobytes](#bundle-size).
23
+
24
+ ## Table of contents
25
+
26
+ - [Install](#install)
27
+ - [Getting started](#getting-started)
28
+ - [Philosophy](#philosophy)
29
+ - [Scope](#scope)
30
+ - [Entry points](#entry-points)
31
+ - [Core API](#core-api)
32
+ - [createLoop](#createloop)
33
+ - [createTicker](#createticker)
34
+ - [createSight](#createsight)
35
+ - [createLifecycle](#createlifecycle)
36
+ - [createScrollProgress](#createscrollprogress)
37
+ - [prefersReducedMotion](#prefersreducedmotion)
38
+ - [Easing and math](#easing-and-math)
39
+ - [Choosing a primitive](#choosing-a-primitive)
40
+ - [React hooks](#react-hooks)
41
+ - [useLoop](#useloop)
42
+ - [useLifecycle](#uselifecycle)
43
+ - [useCanvas](#usecanvas)
44
+ - [useTween](#usetween)
45
+ - [usePresence](#usepresence)
46
+ - [useScrollProgress](#usescrollprogress)
47
+ - [Utility hooks](#utility-hooks)
48
+ - [React components](#react-components)
49
+ - [How animations work](#how-animations-work)
50
+ - [Presence](#presence)
51
+ - [WhenVisible](#whenvisible)
52
+ - [Swap](#swap)
53
+ - [Rendering](#rendering)
54
+ - [Defer](#defer)
55
+ - [WhenIdle](#whenidle)
56
+ - [useWhenIdle](#usewhenidle)
57
+ - [useRenderState](#userenderstate)
58
+ - [Guarantees](#guarantees)
59
+ - [Errors](#errors)
60
+ - [Relationship to View Transitions](#relationship-to-view-transitions)
61
+ - [Bundle size](#bundle-size)
62
+ - [Agent skill](#agent-skill)
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ pnpm add phase
68
+ ```
69
+
70
+ ## Getting started
71
+
72
+ ```tsx
73
+ import { useLoop } from 'phase/react';
74
+
75
+ function Orbit({ radius }) {
76
+ const speed = 1; // radians per second
77
+ const { ref } = useLoop({
78
+ onTick: (frame) => {
79
+ const angle = (frame.elapsed / 1000) * speed;
80
+ ref.current.style.transform = `translate(${Math.cos(angle) * radius}px, ${Math.sin(angle) * radius}px)`;
81
+ },
82
+ });
83
+
84
+ return <div ref={ref} className="dot" />;
85
+ }
86
+ ```
87
+
88
+ Four lines of animation code. Behind them, performance-critical plumbing:
89
+
90
+ - **Pauses when invisible.** Scrolled off-screen or background tab? Zero CPU consumed.
91
+ - **Respects reduced motion.** Accessibility is the default, not an opt-in.
92
+ - **Resumes without teleporting.** Elapsed time freezes during pause, picks up where it left off.
93
+ - **Clean teardown.** Unmount the component and walk away. Nothing leaks.
94
+
95
+ ## Philosophy
96
+
97
+ Every primitive in `phase` exposes its state as a **phase** (a single string: `idle`, `running`, `paused`, `active`, `exiting`...) paired with a **reason** explaining _why_ that transition happened.
98
+
99
+ ```ts
100
+ const { phase, phaseReason } = useLoop({ onTick: draw });
101
+
102
+ // phase: 'paused' phaseReason: 'sight' → off-screen
103
+ // phase: 'paused' phaseReason: 'reduced-motion' → user disabled motion
104
+ // phase: 'running' phaseReason: 'resumed' → came back into view
105
+ ```
106
+
107
+ One string replaces `if (running && visible && !paused && !prefersReducedMotion && mounted)`.
108
+
109
+ Each of those signals is also a CPU and battery decision. Animating while off-screen, ignoring reduced motion, or running after unmount is what burns cycles and causes jank. `phase` composes them once, correctly, instead of leaving each call site to get the conjunction right.
110
+
111
+ Safe behavior is automatic. Visibility awareness, reduced motion, observer cleanup, and delta clamping are defaults, not opt-ins. Bypassing reduced motion requires an explicit `reducedMotion: 'ignore'` in the diff.
112
+
113
+ ## Scope
114
+
115
+ `phase` composes signals (visibility, focus, reduced motion, frame budget) into a coherent lifecycle with a reason for every state transition.
116
+
117
+ **Handles:** lifecycle state, timing, visibility, scroll visibility-ratio, reduced motion, observer pooling, quality signals, frame loops.
118
+
119
+ **Does not handle:** spring physics, gesture systems, declarative keyframe orchestration. Reach for a dedicated library (e.g. `motion`) when you need those.
120
+
121
+ This narrow scope is deliberate. Shipping only the performance-critical plumbing (and nothing else) is what keeps every export [sub-kilobyte to a few kilobytes](#bundle-size).
122
+
123
+ ## Entry points
124
+
125
+ | Import | Contents |
126
+ | ------------- | ----------------------------------------------------------------------------------------------------- |
127
+ | `phase` | Core primitives: createLoop, createTicker, createSight, createLifecycle, createScrollProgress, errors |
128
+ | `phase/ease` | Easing functions and math utilities only |
129
+ | `phase/react` | React hooks and components |
130
+
131
+ Each entry point is independently tree-shakeable. Importing `phase/ease` in a server component pulls zero browser APIs.
132
+
133
+ ## Core API
134
+
135
+ ### createLoop
136
+
137
+ The main primitive. Composes a ticker, visibility observer, and reduced-motion listener into a lifecycle-aware animation loop.
138
+
139
+ ```ts
140
+ import { createLoop } from 'phase';
141
+
142
+ const loop = createLoop({
143
+ element: el,
144
+ onTick: (frame) => {
145
+ // frame.time — performance.now()
146
+ // frame.delta — ms since last tick (clamped to 40ms)
147
+ // frame.elapsed — ms since start (paused time excluded)
148
+ // frame.frame — frame count
149
+ },
150
+ });
151
+
152
+ loop.start();
153
+ // loop.phase === 'running'
154
+ // loop.phaseReason === 'started'
155
+ ```
156
+
157
+ #### Loop phases
158
+
159
+ | Phase | Meaning | Possible reasons |
160
+ | --------- | -------------------------------- | ------------------------------------- |
161
+ | `idle` | Created but not started | `initial` |
162
+ | `running` | Actively ticking | `started`, `resumed` |
163
+ | `paused` | Temporarily stopped, will resume | `sight`, `reduced-motion`, `degraded` |
164
+ | `stopped` | Permanently disposed | `manual`, `disposed` |
165
+
166
+ #### Quality signals
167
+
168
+ `phase` and `quality` are orthogonal. A loop can be `running` + `degraded` (still animating, but at reduced fidelity to preserve resources).
169
+
170
+ | Quality | Meaning | What changes |
171
+ | ---------- | --------------------- | --------------------------------- |
172
+ | `full` | Normal operation | Configured FPS, full DPR |
173
+ | `degraded` | Resources constrained | FPS capped to 30, DPR drops to 1x |
174
+
175
+ Two signals trigger degradation:
176
+
177
+ | Trigger | `qualityReason` | When | Recovery |
178
+ | ------------ | ---------------- | ---------------------------------------------- | ------------------------ |
179
+ | Window blur | `'unfocused'` | User switches to another window | Recovers on window focus |
180
+ | Frame budget | `'frame-budget'` | 3+ consecutive frames exceed the 16.6ms budget | Does not auto-recover |
181
+
182
+ Read `loop.quality` and `loop.qualityReason` to adapt rendering (fewer particles, lower-fidelity shaders, skip non-essential visual passes).
183
+
184
+ #### The `degraded` option
185
+
186
+ Controls the loop's response when quality degrades. Same three-value pattern as `reducedMotion`.
187
+
188
+ | Value | Behavior | Use case |
189
+ | ------------ | ---------------------------------------------------- | --------------------------------------------------- |
190
+ | `'throttle'` | Cap FPS (default 30, configurable via `degradedFps`) | Most animations. Still runs, only slower |
191
+ | `'pause'` | Pause the loop entirely | Heavy canvas/WebGL. If it can't run well, don't run |
192
+ | `'ignore'` | Keep running at full quality | Critical UI that must never degrade |
193
+
194
+ ```ts
195
+ createLoop({
196
+ element: el,
197
+ onTick: draw,
198
+ degraded: 'throttle', // default
199
+ degradedFps: 20, // only accepted when degraded is 'throttle'
200
+ });
201
+ ```
202
+
203
+ #### Loop options
204
+
205
+ | Option | Type | Default | Description |
206
+ | --------------- | ----------------------------------- | ------------ | ----------------------------------------- |
207
+ | `element` | `Element` | required | Element to observe for visibility |
208
+ | `onTick` | `(frame: FrameState) => void` | required | Called each frame while running |
209
+ | `fps` | `number` | — | Cap frames per second |
210
+ | `reducedMotion` | `'pause' \| 'complete' \| 'ignore'` | `'pause'` | Behavior when user prefers reduced motion |
211
+ | `degraded` | `'throttle' \| 'pause' \| 'ignore'` | `'throttle'` | Behavior when quality degrades |
212
+ | `degradedFps` | `number` | `30` | FPS cap in degraded throttle mode |
213
+ | `onPhaseChange` | `(phase, reason) => void` | — | Called on every phase transition |
214
+
215
+ ### createTicker
216
+
217
+ The low-level rAF clock underneath `createLoop`. Use it when you need a frame loop without visibility management (background processing, audio sync, non-visual timing).
218
+
219
+ ```ts
220
+ import { createTicker } from 'phase';
221
+
222
+ const ticker = createTicker({
223
+ onTick: (frame) => {
224
+ /* runs every frame */
225
+ },
226
+ fps: 30,
227
+ });
228
+ ticker.start();
229
+ ```
230
+
231
+ All tickers share a single `requestAnimationFrame` loop. Every subscriber reads the same `performance.now()` value each frame, so independent animations stay in visual sync.
232
+
233
+ #### Ticker phases
234
+
235
+ | Phase | Meaning | Transitions |
236
+ | --------- | ------------------------ | --------------------------- |
237
+ | `idle` | Created, not started | → `running` via `start()` |
238
+ | `running` | Actively ticking | → `paused` via `pause()` |
239
+ | `paused` | Suspended, resumable | → `running` via `resume()` |
240
+ | `stopped` | Terminal, cannot restart | via `stop()` from any state |
241
+
242
+ ### createSight
243
+
244
+ Answers one question: is this element visible right now? Combines `document.visibilitychange`, `pageshow` (bfcache restore), and `IntersectionObserver` into a single phase.
245
+
246
+ ```ts
247
+ import { createSight } from 'phase';
248
+
249
+ const sight = createSight({
250
+ element: el,
251
+ onPhaseChange: (phase, reason) => {
252
+ // phase: 'visible' | 'hidden' | 'unknown'
253
+ // reason: 'initial' | 'viewport' | 'document' | 'bfcache' | 'all-hidden'
254
+ },
255
+ });
256
+ ```
257
+
258
+ `phase` is `'visible'` only when the document is visible AND the element is in the viewport. Uses a pooled `IntersectionObserver` (20 elements with the same options share one observer instance).
259
+
260
+ ### createLifecycle
261
+
262
+ The activation decision for an animation, decoupled from who drives the frames. Composes visibility (`createSight`), reduced motion, and a manual pause into a single `active` / `paused` phase.
263
+
264
+ Use `createLifecycle` when you own your render loop (a three.js/WebGL renderer, a Web Worker, or any non-rAF work that should pause when off-screen or under reduced motion). When you want `phase` to drive the loop for you, use [`createLoop`](#createloop) instead.
265
+
266
+ ```ts
267
+ import { createLifecycle } from 'phase';
268
+
269
+ const lifecycle = createLifecycle({
270
+ element: canvas,
271
+ onPhaseChange: (phase, reason) => {
272
+ // phase: 'idle' | 'active' | 'paused' | 'stopped'
273
+ // reason: 'started' | 'resumed' | 'sight' | 'reduced-motion' | 'manual' | 'disposed' | 'initial'
274
+ if (phase === 'active') renderer.start();
275
+ else renderer.stop(); // your loop, your teardown
276
+ },
277
+ });
278
+
279
+ // Manual pause (e.g. a panel opened over the hero):
280
+ lifecycle.pause();
281
+ lifecycle.resume();
282
+
283
+ // cleanup:
284
+ lifecycle.stop();
285
+ ```
286
+
287
+ `createLoop` is built on `createLifecycle` (it adds a ticker and quality signals on top). Loop-level optimizations (shared clock, zero-allocation `FrameState`, delta clamping, FPS cap, strong pause) only apply when `phase` drives the loop. Lifecycle-level optimizations (pooled observers, composed document-visibility + bfcache + viewport, reduced motion) carry over to consumer-owned loops.
288
+
289
+ #### Lifecycle phases
290
+
291
+ | Phase | Meaning | Possible reasons |
292
+ | --------- | -------------------------------- | ----------------------------------- |
293
+ | `idle` | Created but not started | `initial` |
294
+ | `active` | Should be animating | `started`, `resumed` |
295
+ | `paused` | Off-screen, reduced motion, etc. | `sight`, `reduced-motion`, `manual` |
296
+ | `stopped` | Permanently disposed | `disposed` |
297
+
298
+ Pause priority is `reduced-motion` > `sight` > `manual`.
299
+
300
+ ### createScrollProgress
301
+
302
+ Reports what fraction of an element is currently visible in the viewport (0–1), via the shared IntersectionObserver pool. Zero forced reflows, zero extra observers. Ideal for reveal/opacity effects.
303
+
304
+ > **Not a scroll-scrubbing engine.** This reports `intersectionRatio`, which plateaus for tall elements once they fill the viewport. For continuous scroll-driven animation, use `motion`'s `useScroll` or the native `ScrollTimeline` API.
305
+
306
+ ```ts
307
+ import { createScrollProgress } from 'phase';
308
+
309
+ const progress = createScrollProgress({
310
+ element: el,
311
+ onProgress: (ratio) => {
312
+ el.style.opacity = String(ratio);
313
+ },
314
+ });
315
+
316
+ // progress.ratio === 0.65 (synchronous read)
317
+
318
+ // cleanup:
319
+ progress.stop();
320
+ ```
321
+
322
+ The `steps` option controls threshold granularity. Default `20` generates 21 evenly-spaced thresholds (0%, 5%, 10%, …, 100%). Multiple instances with the same `steps` share a single IO, adding zero extra observers.
323
+
324
+ #### ScrollProgress options
325
+
326
+ | Option | Type | Default | Description |
327
+ | ------------ | ----------------------------- | -------- | ---------------------------------- |
328
+ | `element` | `Element` | required | Element to observe |
329
+ | `onProgress` | `(ratio: number) => void` | required | Called at each threshold crossing |
330
+ | `steps` | `number` | `20` | Number of evenly-spaced thresholds |
331
+ | `root` | `Element \| Document \| null` | — | IO root element |
332
+ | `rootMargin` | `string` | — | IO root margin |
333
+
334
+ ### prefersReducedMotion
335
+
336
+ Returns `true` when reduced motion is enabled at the OS level. Use it to gate expensive setup or dynamic imports.
337
+
338
+ ```ts
339
+ import { prefersReducedMotion } from 'phase';
340
+
341
+ if (!prefersReducedMotion()) {
342
+ const { startParticleSystem } = await import('./particles');
343
+ startParticleSystem(canvas);
344
+ }
345
+ ```
346
+
347
+ All hooks and primitives consult this signal automatically. You only need it directly for conditional imports or setup logic.
348
+
349
+ ## Easing and math
350
+
351
+ Pure functions with no browser APIs, side effects, or React. Safe in server components, build scripts, and tests.
352
+
353
+ ```ts
354
+ import { lerp, clamp01, easeOutCubic, remap } from 'phase/ease';
355
+ ```
356
+
357
+ ### Easing functions
358
+
359
+ | Function | Character |
360
+ | ---------------- | ------------------------------- |
361
+ | `easeOutCubic` | Fast start, smooth deceleration |
362
+ | `easeOutQuart` | Sharper deceleration |
363
+ | `easeOutBack` | Overshoots target, snaps back |
364
+ | `easeInOutCubic` | Symmetric S-curve |
365
+ | `linear` | No easing (identity) |
366
+
367
+ All easing functions take a progress value (0–1) and return a curved progress value (0–1). They don't know about time, pixels, or anything else. They reshape a number.
368
+
369
+ ### Math utilities
370
+
371
+ | Function | Description | Example |
372
+ | -------------------------------- | ------------------------------ | ---------------------------------- |
373
+ | `clamp(value, min, max)` | Constrain to range | `clamp(150, 0, 100)` → `100` |
374
+ | `clamp01(value)` | Constrain to 0–1 | `clamp01(-0.5)` → `0` |
375
+ | `lerp(start, end, t)` | Linear interpolation | `lerp(0, 100, 0.5)` → `50` |
376
+ | `inverseLerp(start, end, value)` | Where is value in range? (0–1) | `inverseLerp(0, 100, 75)` → `0.75` |
377
+ | `remap(options)` | Map from one range to another | Input range → output range |
378
+
379
+ ### The pattern
380
+
381
+ ```ts
382
+ const progress = clamp01(elapsed / duration); // normalize time to 0–1
383
+ const eased = easeOutCubic(progress); // reshape the curve
384
+ const value = lerp(startPos, endPos, eased); // map to your range
385
+ ```
386
+
387
+ Easing, interpolation, and your value range are three separate concerns. `phase` keeps them separate so you can mix and match.
388
+
389
+ ## Choosing a primitive
390
+
391
+ | Need | Use |
392
+ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
393
+ | Check on-screen visibility | `useSight` (visibility only) |
394
+ | Run a frame loop via `phase` | `useLoop` (DOM) / `useCanvas` (canvas) |
395
+ | Pause/resume your own loop (WebGL, three.js, Web Worker) | `useLifecycle` (active/paused signal) |
396
+ | Animate a single value in render output | `useTween` |
397
+ | Animate mount/unmount transitions | `Presence` / `Swap` / `WhenVisible` |
398
+ | Skip painting off-screen content (keep in DOM) | `Defer` |
399
+ | Defer non-critical UI until the browser is idle | `WhenIdle` / `useIdle` |
400
+ | Run a side effect or prefetch when idle | `useWhenIdle` |
401
+ | Pause non-`phase` work inside a `Defer` subtree | `useRenderState` |
402
+ | Subscribe to scroll, size, or media values reactively | `useScrollProgress` / `useSize` / `useContainerQuery` / `useMediaQuery` |
403
+ | Scroll/size/visibility without re-renders? | Same hooks with a callback (`onProgress` / `onResize` / `onVisibilityChange`), read via ref |
404
+
405
+ **`useSight` vs `useLifecycle`:** `useSight` reports pure visibility (for lazy-mounting, analytics, `WhenVisible`). `useLifecycle` folds in reduced motion and a manual pause, so you can't accidentally animate for users who asked not to. If you're gating an animation, use `useLifecycle`. If you're gating content, use `useSight`.
406
+
407
+ ## React hooks
408
+
409
+ ### useLoop
410
+
411
+ The primary React hook. Wraps `createLoop` with React lifecycle management.
412
+
413
+ ```tsx
414
+ import { useLoop } from 'phase/react';
415
+
416
+ const { ref, phase, phaseReason } = useLoop({
417
+ onTick: (frame) => {
418
+ ref.current.style.transform = `translateX(${frame.elapsed * 0.1}px)`;
419
+ },
420
+ });
421
+ return <div ref={ref} />;
422
+ ```
423
+
424
+ Attach the returned `ref` to the element you want to animate. To bring your own, pass `ref` in the options.
425
+
426
+ Your `onTick` callback always sees the latest props, state, and refs without restarting the loop (stored internally via `useSyncedRef`).
427
+
428
+ **Never call `setState` inside `onTick`.** It runs 60 times per second. Write to refs or the DOM directly. The only re-render trigger is `phase` changing (an infrequent lifecycle event).
429
+
430
+ ### useLifecycle
431
+
432
+ The activation signal for a loop you own. Wraps [`createLifecycle`](#createlifecycle), returning `active` / `paused` so a consumer-owned render loop (WebGL, three.js, a Web Worker) can pause when off-screen or under reduced motion.
433
+
434
+ ```tsx
435
+ import { useLifecycle } from 'phase/react';
436
+
437
+ function Hero() {
438
+ const { ref, isActive } = useLifecycle();
439
+
440
+ useEffect(() => {
441
+ if (!isActive) return; // off-screen / reduced motion / paused
442
+ let raf = requestAnimationFrame(function render() {
443
+ renderer.render();
444
+ raf = requestAnimationFrame(render);
445
+ });
446
+ return () => cancelAnimationFrame(raf);
447
+ }, [isActive]);
448
+
449
+ return <canvas ref={ref} />;
450
+ }
451
+ ```
452
+
453
+ | Option | Type | Default | Description |
454
+ | --------------------- | -------------------------- | --------- | ----------------------------------------------------- |
455
+ | `ref` | `RefObject` | returned | Bring your own, or attach the returned `ref` |
456
+ | `reducedMotion` | `'pause' \| 'ignore'` | `'pause'` | Whether reduced motion pauses the lifecycle |
457
+ | `paused` | `boolean` | `false` | Manual pause (e.g. a panel opened over the animation) |
458
+ | `enabled` | `boolean` | `true` | When `false`, tears down and reports `idle` |
459
+ | `intersectionOptions` | `IntersectionObserverInit` | — | Forwarded to the underlying observer |
460
+
461
+ Returns `{ ref, phase, phaseReason, isActive }`. See [Choosing a primitive](#choosing-a-primitive) for `useSight` vs `useLifecycle`.
462
+
463
+ ### useCanvas
464
+
465
+ Everything `useLoop` provides, plus DPR-aware buffer sizing, ResizeObserver coalescing, and GPU context loss recovery.
466
+
467
+ ```tsx
468
+ import { useRef } from 'react';
469
+ import { useCanvas } from 'phase/react';
470
+
471
+ const containerRef = useRef(null);
472
+ const canvasRef = useRef(null);
473
+
474
+ const { phase } = useCanvas({
475
+ containerRef,
476
+ canvasRef,
477
+ draw: (ctx, frame, size) => {
478
+ ctx.clearRect(0, 0, size.width, size.height);
479
+ // ctx is already scaled for devicePixelRatio — draw in CSS pixels
480
+ },
481
+ });
482
+
483
+ return (
484
+ <div ref={containerRef}>
485
+ <canvas ref={canvasRef} />
486
+ </div>
487
+ );
488
+ ```
489
+
490
+ `useCanvas` coordinates two elements (a sizing container and the canvas), so you pass both refs in.
491
+
492
+ | Concern | How useCanvas handles it |
493
+ | ------------ | -------------------------------------------------------------------------------------------------------------------------------- |
494
+ | DPR (retina) | Uses `devicePixelContentBoxSize` for exact physical pixels when available, falls back to `width * dpr`. Listens for DPR changes. |
495
+ | Resize | Shared ResizeObserver. Canvas resized on container change. No `getBoundingClientRect`. |
496
+ | Context loss | Listens for `contextlost`/`contextrestored`. Pauses on loss, recovers on restore. |
497
+ | Quality | When degraded, DPR drops to 1x automatically (halves GPU pixel count). |
498
+
499
+ Both hooks accept the same quality controls as `createLoop`: `degraded` and `degradedFps`. For heavy GPU work, consider `degraded: 'pause'`.
500
+
501
+ ### useTween
502
+
503
+ Animates a number from A to B over a duration. Calls `setState` per frame (appropriate when the animated value is used in render output).
504
+
505
+ ```tsx
506
+ import { useTween } from 'phase/react';
507
+
508
+ const opacity = useTween({ target: isVisible ? 1 : 0, duration: 300 });
509
+ ```
510
+
511
+ Use `useTween` for single values where the render is cheap (counters, progress bars, opacity). Use `useLoop` when animating many elements or doing canvas work, since per-frame `setState` doesn't scale.
512
+
513
+ Reduced motion default: `'complete'` (jumps to target instantly). The value still reaches its destination; it skips the animation.
514
+
515
+ ### usePresence
516
+
517
+ The hook behind `<Presence>`. Use directly when you need full control over mount/unmount lifecycle.
518
+
519
+ ```tsx
520
+ import { usePresence } from 'phase/react';
521
+
522
+ const { phase, ref, mounted, enter } = usePresence({ show: isOpen });
523
+ if (!mounted) return null;
524
+ return (
525
+ <div
526
+ ref={ref}
527
+ data-phase={phase}
528
+ data-enter={enter === 'animate' ? 'animate' : undefined}
529
+ className="transition-opacity data-[enter=animate]:starting:opacity-0 data-[phase=exiting]:opacity-0"
530
+ />
531
+ );
532
+ ```
533
+
534
+ #### Presence phases
535
+
536
+ `idle` → `entered` → `exiting` → `exited`
537
+
538
+ | Phase | Meaning | `mounted` |
539
+ | --------- | ---------------------------------------- | --------- |
540
+ | `idle` | Not shown (initial or after reveal exit) | `false` |
541
+ | `entered` | Visible and active | `true` |
542
+ | `exiting` | Exit animation in progress | `true` |
543
+ | `exited` | Exit complete, ready for unmount | `false` |
544
+
545
+ #### Options
546
+
547
+ | Option | Type | Default | Description |
548
+ | --------------- | ------------------------ | ----------- | ---------------------------------- |
549
+ | `show` | `boolean` | required | Visibility toggle |
550
+ | `mode` | `'mount' \| 'reveal'` | `'mount'` | Unmount after exit or stay in DOM |
551
+ | `enter` | `'animate' \| 'instant'` | `'animate'` | First-mount behavior |
552
+ | `exitDuration` | `number` | `5000` | Safety timeout for exit (ms) |
553
+ | `reducedMotion` | `'respect' \| 'ignore'` | `'respect'` | Reduced motion preference handling |
554
+
555
+ ### useScrollProgress
556
+
557
+ Element visibility ratio as a 0–1 value. Wraps `createScrollProgress` with React lifecycle management (see its [note on scope](#createscrollprogress) for the distinction between visibility ratio and scroll-scrubbing).
558
+
559
+ ```tsx
560
+ import { useScrollProgress } from 'phase/react';
561
+
562
+ function FadeIn({ children }) {
563
+ const { ref, progress } = useScrollProgress();
564
+ return (
565
+ <div ref={ref} style={{ opacity: progress }}>
566
+ {children}
567
+ </div>
568
+ );
569
+ }
570
+ ```
571
+
572
+ Re-renders only at threshold crossings (~20 per full viewport traversal at default steps). `progress` is `0` before first observation.
573
+
574
+ ### Utility hooks
575
+
576
+ | Hook | Purpose |
577
+ | ------------------- | ------------------------------------------------------------------------------------- |
578
+ | `useSight` | Element visibility as a phase. Pass `onVisibilityChange` for zero-re-render mode |
579
+ | `useSize` | Element dimensions via shared ResizeObserver. Pass `onResize` for zero-re-render mode |
580
+ | `useContainerQuery` | Breakpoint matching against element width |
581
+ | `useScrollProgress` | Element visibility ratio (0–1). Pass `onProgress` for zero-re-render mode |
582
+ | `useMediaQuery` | CSS media query subscription (shared MQL pool) |
583
+ | `useSyncedRef` | Ref always in sync with latest value |
584
+ | `useStableCallback` | Stable-identity function that calls latest closure |
585
+
586
+ `useSight`, `useSize`, and `useScrollProgress` each support a transient mode: pass a callback (`onVisibilityChange`, `onResize`, `onProgress`) and the hook delivers updates via callback with zero re-renders. The reactive state field is omitted from the return type so accessing it is a compile-time error. An always-current ref (`phaseRef`, `sizeRef`, `progressRef`) is available in both modes.
587
+
588
+ ## React components
589
+
590
+ ### How animations work
591
+
592
+ One CSS pattern covers enter and exit across `Presence`, `WhenVisible`, and `Swap`:
593
+
594
+ ```tsx
595
+ className =
596
+ 'transition-opacity data-[enter=animate]:starting:opacity-0 data-[phase=exiting]:opacity-0';
597
+ ```
598
+
599
+ No `motion-reduce:` class needed because reduced motion is handled automatically.
600
+
601
+ **Enter:** CSS `@starting-style` animates the element natively when `data-enter="animate"` is present. Zero JS during the animation.
602
+
603
+ **Exit:** `phase` stamps `data-phase="exiting"`, waits for `transitionend`/`animationend` (or a safety timeout), then unmounts. JS coordination is required because CSS has no "animate then remove from DOM" primitive.
604
+
605
+ **Reduced motion:** `phase` suppresses `data-enter="animate"` and skips the exit animation (instant unmount). No consumer effort.
606
+
607
+ ### Presence
608
+
609
+ Renders a `div` that manages its own mount/unmount lifecycle, stamping `data-phase` for exit and `data-enter="animate"` for enter.
610
+
611
+ ```tsx
612
+ import { Presence } from 'phase/react';
613
+
614
+ <Presence
615
+ show={isOpen}
616
+ className="transition-opacity data-[enter=animate]:starting:opacity-0 data-[phase=exiting]:opacity-0"
617
+ >
618
+ Modal content
619
+ </Presence>;
620
+ ```
621
+
622
+ | Prop | Type | Default | Description |
623
+ | --------------- | ------------------------ | ----------- | --------------------------------- |
624
+ | `show` | `boolean` | required | Visibility toggle |
625
+ | `mode` | `'mount' \| 'reveal'` | `'mount'` | Unmount after exit or stay in DOM |
626
+ | `enter` | `'animate' \| 'instant'` | `'animate'` | First-mount animation behavior |
627
+ | `exitDuration` | `number` | `5000` | Safety timeout for exit (ms) |
628
+ | `reducedMotion` | `'respect' \| 'ignore'` | `'respect'` | Reduced motion handling |
629
+
630
+ Two modes:
631
+
632
+ | Mode | Behavior | Use case |
633
+ | ---------- | -------------------------------------------------- | ---------------------------------------- |
634
+ | `'mount'` | Added to DOM on show, removed after exit completes | Modals, toasts, menus |
635
+ | `'reveal'` | Always in DOM, visibility toggled via phase | Scroll reveals, SEO content, IO re-entry |
636
+
637
+ ### WhenVisible
638
+
639
+ Mounts children when the element enters the viewport. One-shot (once triggered, stays mounted). Uses the pooled IntersectionObserver via `useSight`.
640
+
641
+ ```tsx
642
+ import { WhenVisible } from 'phase/react';
643
+
644
+ <WhenVisible
645
+ rootMargin="200px"
646
+ className="transition-opacity data-[enter=animate]:starting:opacity-0"
647
+ >
648
+ <HeavyInteractiveChart />
649
+ </WhenVisible>;
650
+ ```
651
+
652
+ Common pattern for viewport-gated lazy loading:
653
+
654
+ ```tsx
655
+ const HeavyChart = lazy(() => import('./heavy-chart'));
656
+
657
+ <WhenVisible
658
+ rootMargin="200px"
659
+ className="transition-opacity data-[enter=animate]:starting:opacity-0"
660
+ >
661
+ <Suspense fallback={<Skeleton />}>
662
+ <HeavyChart />
663
+ </Suspense>
664
+ </WhenVisible>;
665
+ ```
666
+
667
+ | Prop | Type | Default | Description |
668
+ | ------------ | -------------------- | --------- | --------------------------------- |
669
+ | `rootMargin` | `string` | `'200px'` | IO rootMargin (preload headroom) |
670
+ | `threshold` | `number \| number[]` | — | IO threshold |
671
+ | `root` | `Element \| null` | — | IO root element |
672
+ | `fallback` | `ReactNode` | — | Shown while awaiting intersection |
673
+
674
+ Reduced motion is automatic: `data-enter="animate"` is not stamped when reduced motion is preferred.
675
+
676
+ ### Swap
677
+
678
+ Coordinated exit-then-enter transitions. The old state fully exits before the new state enters (no overlap, no z-index issues).
679
+
680
+ ```tsx
681
+ import { Swap } from 'phase/react';
682
+
683
+ <Swap active={success ? 'success' : 'form'}>
684
+ <Swap.State
685
+ id="form"
686
+ className="transition-all data-[phase=exiting]:opacity-0"
687
+ >
688
+ <Form />
689
+ </Swap.State>
690
+ <Swap.State
691
+ id="success"
692
+ className="transition-all data-[enter=animate]:starting:opacity-0 data-[phase=exiting]:opacity-0"
693
+ >
694
+ <SuccessMessage />
695
+ </Swap.State>
696
+ </Swap>;
697
+ ```
698
+
699
+ Rapid changes (A → B → C during A's exit) skip intermediate states and advance directly to the latest `active`. First state appears instantly (CLS prevention); subsequent states animate via `@starting-style`.
700
+
701
+ ## Rendering
702
+
703
+ `phase` is the _when_ layer (when to animate, when to render, when to pause), built from one set of signals. Alongside `WhenVisible`, two helpers skip rendering work for off-screen content. They differ in how aggressively they skip and whether the content survives server rendering:
704
+
705
+ | Helper | Defers | In DOM? | In SSR HTML? | Reach for it when |
706
+ | ------------- | ----------------------------------- | ------- | ------------ | -------------------------------------------------- |
707
+ | `Defer` | browser render (style/layout/paint) | yes | yes | content must stay crawlable but need not paint yet |
708
+ | `WhenIdle` | React mount until idle | no | no | non-critical UI that shouldn't block first paint |
709
+ | `WhenVisible` | React mount until near viewport | no | no | viewport-gated lazy loading / reveals |
710
+
711
+ ### Defer
712
+
713
+ Skips the browser's rendering work (style, layout, paint) for off-screen content via `content-visibility: auto`, using pure CSS with no JS or observers. Children stay in the DOM and are server-rendered.
714
+
715
+ ```tsx
716
+ import { Defer } from 'phase/react';
717
+
718
+ <Defer estimatedHeight="600px" className="my-section">
719
+ <ArticleSection />
720
+ </Defer>;
721
+ ```
722
+
723
+ | Prop | Type | Default | Description |
724
+ | ----------------- | -------------------------------------- | ---------- | --------------------------------------------------- |
725
+ | `estimatedHeight` | `string` | `'1000px'` | Reserved size before first paint (any CSS length) |
726
+ | ...rest | `Omit<ComponentProps<'div'>, 'style'>` | — | Standard div props except `style` (use `className`) |
727
+
728
+ `contain-intrinsic-size: auto <estimatedHeight>` reserves space, so there is no layout shift. The browser remembers the real size after first paint. `Defer` defers rendering only, not hydration or mounting. There is no `style` prop: the render-skip styles are encapsulated so they can't be overridden. Style the wrapper with `className`.
729
+
730
+ **Animations inside a `Defer` keep running.** `content-visibility` skips paint, not JavaScript. `phase`'s own loops (`useLoop`, `useCanvas`, `useLifecycle`) already self-pause off-screen via their own visibility observer. For raw work (a hand-written `requestAnimationFrame` loop, `setInterval`), gate it with `useRenderState`.
731
+
732
+ ### WhenIdle
733
+
734
+ Mounts children once the browser is idle after first paint. One-shot. Use it for non-critical UI that should not compete with the critical path. Backed by the `whenIdle` core utility (`requestIdleCallback`).
735
+
736
+ ```tsx
737
+ import { WhenIdle } from 'phase/react';
738
+
739
+ <WhenIdle
740
+ fallback={<Skeleton />}
741
+ className="transition-opacity data-[enter=animate]:starting:opacity-0"
742
+ >
743
+ <SecondaryPanel />
744
+ </WhenIdle>;
745
+ ```
746
+
747
+ | Prop | Type | Default | Description |
748
+ | ---------- | ----------- | ------- | ------------------------------------- |
749
+ | `timeout` | `number` | — | Max ms to wait before mounting anyway |
750
+ | `fallback` | `ReactNode` | — | Shown until the browser is idle |
751
+
752
+ Idle never fires during SSR, so `WhenIdle` children are absent from server HTML. Reserve it for non-critical content. For content that must be crawlable, use `Defer`. Reduced motion is automatic: `data-enter="animate"` is not stamped when reduced motion is preferred.
753
+
754
+ ### useWhenIdle
755
+
756
+ Runs a callback once when the browser is idle after mount (the effect-shaped counterpart to `useIdle`). Use it for side effects (prefetching a chunk, warming a cache) rather than rendering. Cancels on unmount and always calls the latest callback.
757
+
758
+ ```tsx
759
+ import { lazy, Suspense, useState } from 'react';
760
+ import { useWhenIdle } from 'phase/react';
761
+
762
+ const openPanel = () => import('./chat-panel');
763
+ const ChatPanel = lazy(openPanel);
764
+
765
+ function Chat() {
766
+ const [open, setOpen] = useState(false);
767
+ useWhenIdle(() => void openPanel()); // prefetch the chunk during idle
768
+
769
+ return open ? (
770
+ <Suspense fallback={<Skeleton />}>
771
+ <ChatPanel />
772
+ </Suspense>
773
+ ) : (
774
+ <button onClick={() => setOpen(true)}>Open</button>
775
+ );
776
+ }
777
+ ```
778
+
779
+ It replaces the common (and leak-prone) hand-rolled `useEffect(() => { const id = requestIdleCallback(...); return () => cancelIdleCallback(id); }, [])`. `useWhenIdle` handles cancellation and the SSR guard. Reach for `useIdle` instead when you need to render from the idle signal.
780
+
781
+ ### useRenderState
782
+
783
+ Reads whether the browser is rendering an element or skipping it under `content-visibility`. Pass it the `ref` from a `Defer` to pause **raw, non-phase** work when the subtree stops painting.
784
+
785
+ ```tsx
786
+ import { useRef, useEffect } from 'react';
787
+ import { Defer, useRenderState } from 'phase/react';
788
+
789
+ function Chart() {
790
+ const ref = useRef<HTMLDivElement>(null);
791
+ const phase = useRenderState(ref); // 'rendered' | 'skipped'
792
+
793
+ useEffect(() => {
794
+ if (phase === 'skipped') clock.pause();
795
+ else clock.resume();
796
+ }, [phase]);
797
+
798
+ return (
799
+ <Defer ref={ref}>
800
+ <RawCanvasThing />
801
+ </Defer>
802
+ );
803
+ }
804
+ ```
805
+
806
+ `useRenderState` only listens and reports. It has no layout effect, so it never breaks `Defer`'s no-layout-shift guarantee. You rarely need it for `phase` loops, which already self-pause off-screen.
807
+
808
+ ## Guarantees
809
+
810
+ These are the performance invariants behind [Why phase](#why-phase). They are tested in CI, not aspirations.
811
+
812
+ ### Zero per-frame allocations
813
+
814
+ `FrameState` is created once and mutated in place every frame. No objects, arrays, closures, template literals, or spread operators in the tick path, and no GC pressure at 60 fps.
815
+
816
+ ### Strong pause
817
+
818
+ When paused, the ticker calls `cancelAnimationFrame` and stops scheduling entirely. Zero callbacks fire, zero CPU consumed. This is not the "weak pause" pattern of scheduling rAF and returning early.
819
+
820
+ ### Zero forced reflows
821
+
822
+ No `getBoundingClientRect()`, `offsetWidth`, `scrollWidth`, or `getComputedStyle()` anywhere in the package. All dimensions come from ResizeObserver (async, compositor-aligned) and all visibility from IntersectionObserver.
823
+
824
+ ### Zero React re-renders from the frame loop
825
+
826
+ The rAF loop never triggers a React re-render. All per-frame state lives in refs; `onTick` writes to refs or the DOM directly. Only `phase` changes trigger re-renders (infrequent lifecycle transitions).
827
+
828
+ ### Frame-locked shared clock
829
+
830
+ All tickers share one `requestAnimationFrame` loop with a single `performance.now()` read per frame, keeping multiple animations on the same page in visual sync.
831
+
832
+ ### Delta clamping
833
+
834
+ When a loop resumes after a pause, `frame.delta` is clamped to 40 ms. Animations resume from where they left off with no teleporting.
835
+
836
+ ## Errors
837
+
838
+ Every error includes a machine-readable `code` and an actionable message.
839
+
840
+ ```ts
841
+ import { PhaseError, isPhaseError } from 'phase';
842
+ ```
843
+
844
+ | Code | Trigger |
845
+ | ------------------ | ---------------------------------------------------- |
846
+ | `server_context` | Calling a browser-only primitive during SSR |
847
+ | `no_element` | Passing a null or undefined `element` to a primitive |
848
+ | `invalid_duration` | `useTween` duration is zero, negative, or NaN |
849
+ | `ticker_stopped` | Calling `start`/`resume` on a stopped ticker |
850
+ | `missing_context` | `<Swap.State>` used outside `<Swap>` |
851
+
852
+ ## Relationship to View Transitions
853
+
854
+ `phase` doesn't wrap React's View Transition API, and it doesn't need to. The two compose cleanly. Reach for `<ViewTransition>` when you animate between committed UI states like route changes and shared-element morphs, and reach for `Presence`, `Swap`, and the frame loops for component-local lifecycle on stable React. A `phase` loop keeps ticking inside a view-transitioned subtree without conflict.
855
+
856
+ ## Bundle size
857
+
858
+ Minimal footprint is a core promise (see [Why phase](#why-phase)). Every export is individually measured with [Size Limit](https://github.com/ai/size-limit) and budgeted in CI. Sizes reflect minified + brotli-compressed bytes.
859
+
860
+ > Regenerate with `pnpm size:readme`.
861
+
862
+ <!-- SIZE-TABLE:START -->
863
+
864
+ | Export | Size (min+brotli) |
865
+ | ------------------------- | ----------------: |
866
+ | **Core** | |
867
+ | `createTicker` | 834 B |
868
+ | `createSight` | 963 B |
869
+ | `createLifecycle` | 1.47 kB |
870
+ | `createLoop` | 2.6 kB |
871
+ | `createScrollProgress` | 868 B |
872
+ | `createRenderState` | 495 B |
873
+ | `createDevicePixelRatio` | 544 B |
874
+ | `whenIdle` | 409 B |
875
+ | `prefersReducedMotion` | 101 B |
876
+ | **Ease** | |
877
+ | `ease (all)` | 210 B |
878
+ | **React** | |
879
+ | `useLoop` | 2.81 kB |
880
+ | `useLifecycle` | 1.68 kB |
881
+ | `useSight` | 1.19 kB |
882
+ | `useCanvas` | 3.43 kB |
883
+ | `useTween` | 614 B |
884
+ | `usePresence` | 592 B |
885
+ | `useScrollProgress` | 996 B |
886
+ | `useSize` | 337 B |
887
+ | `useContainerQuery` | 334 B |
888
+ | `useMediaQuery` | 245 B |
889
+ | `usePrefersReducedMotion` | 272 B |
890
+ | `useDevicePixelRatio` | 231 B |
891
+ | `useSyncedRef` | 22 B |
892
+ | `useStableCallback` | 39 B |
893
+ | `Presence` | 745 B |
894
+ | `WhenVisible` | 1.44 kB |
895
+ | `WhenIdle` | 592 B |
896
+ | `Defer` | 104 B |
897
+ | `useIdle` | 435 B |
898
+ | `useWhenIdle` | 448 B |
899
+ | `useRenderState` | 527 B |
900
+ | `Swap` | 1.12 kB |
901
+
902
+ <!-- SIZE-TABLE:END -->
903
+
904
+ ## Agent skill
905
+
906
+ `phase` ships with an [agent skill](skills/phase) that teaches AI coding agents to implement the API correctly, follow performant-animation best practices, and audit existing code to recommend the cheapest sufficient approach (CSS-only, minimal JS, `phase`, or a heavier library).
907
+
908
+ Install it three ways:
909
+
910
+ ```bash
911
+ # skills.sh
912
+ npx skills add vercel-labs/phase --skill phase
913
+ ```
914
+
915
+ Or copy `skills/phase/` into your project's `.agents/skills/phase/` and reference its `SKILL.md` from your `AGENTS.md`, or download [`skills/phase/dist/phase-skill.zip`](skills/phase/dist/phase-skill.zip) and unzip it into your skills directory.
916
+
917
+ The audit scanner ships with the skill (no separate install needed). Ask your agent to audit your animation code and it runs `scripts/scan.mjs` for you, or run it standalone with `node <skill-dir>/scripts/scan.mjs <target-dir>`. See the [skill README](skills/phase/README.md#running-an-audit) for details.