Smoothing
primitive · T1 · v1.0.0 · readyAbout
Feeds trailing and lagging motion (cursor followers, eased readouts) without overshoot: after one half-life the value has covered half the remaining distance. Runs on the shared frame scheduler only while the value moves.
Layers
- Static
- n/a: no visual output.
Accessibility
n/a: callers decide whether to ease (effects using it run on the JS layer only).
Sources
- original
Code
Self-contained: copy every file, keeping the folder structure.
approach.ts// web-effects smoothing 1.0.0 · MIT-0
// Exponential approach set by a half-life: after `halfLife` ms the value has covered half the
// remaining distance to its target, whatever the frame rate. Pure functions, no browser globals.
/** Share of the remaining distance covered in `dt` ms (0 when dt is 0, 1 when halfLife is 0). */
export function approachFactor(dt: number, halfLife: number): number {
return halfLife > 0 ? 1 - 2 ** (-dt / halfLife) : 1;
}
/** `current` moved towards `target` over `dt` ms. */
export function approach(
current: number,
target: number,
dt: number,
halfLife: number,
): number {
return current + (target - current) * approachFactor(dt, halfLife);
}
primitives/frame-scheduler/scheduler.ts// web-effects frame-scheduler 1.0.0 · MIT-0
// Shared animation-frame scheduler (D3.9). One requestAnimationFrame loop for every caller.
// Each frame runs all `read` callbacks, then all `write` callbacks, so DOM measurements and
// DOM writes never interleave (no forced synchronous layout). Hidden tabs pause it for free,
// because browsers stop requestAnimationFrame there. Pausing off-screen work is the caller's job.
export type FrameTask = {
/** Measure the DOM. Runs before every write of the same frame. */
read?: (time: number) => void;
/** Mutate the DOM (styles, custom properties). */
write?: (time: number) => void;
};
export type FrameScheduler = {
/** Runs `task` every frame until the returned function is called. */
loop: (task: FrameTask) => () => void;
/** Runs `task` once, on the next frame. Requesting a pending task again is a no-op. */
once: (task: FrameTask) => () => void;
};
type FrameApi = {
request: (callback: (time: number) => void) => number;
cancel: (handle: number) => void;
};
// Resolved per call, not at import, so importing this module is safe during server rendering.
const browserFrames: FrameApi = {
request: (callback) => requestAnimationFrame(callback),
cancel: (handle) => cancelAnimationFrame(handle),
};
export function createScheduler(
frames: FrameApi = browserFrames,
): FrameScheduler {
const looping = new Set<FrameTask>();
const pending = new Set<FrameTask>();
let handle: number | null = null;
const tick = (time: number) => {
handle = null;
const tasks = [...looping, ...pending];
pending.clear();
for (const task of tasks) task.read?.(time);
for (const task of tasks) task.write?.(time);
if (looping.size > 0 || pending.size > 0) handle = frames.request(tick);
};
const start = () => {
if (handle === null) handle = frames.request(tick);
};
const stopIfIdle = () => {
if (handle !== null && looping.size === 0 && pending.size === 0) {
frames.cancel(handle);
handle = null;
}
};
return {
loop(task) {
looping.add(task);
start();
return () => {
looping.delete(task);
stopIfIdle();
};
},
once(task) {
pending.add(task);
start();
return () => {
pending.delete(task);
stopIfIdle();
};
},
};
}
/** The scheduler every primitive shares. */
export const frameScheduler: FrameScheduler = createScheduler();
smoother.ts// web-effects smoothing 1.0.0 · MIT-0
// Smoother: eases a vector of numbers (a position, a progress) towards a target set at any time,
// on the shared frame scheduler (D3.9). It runs only while the value is moving: once every
// component is within `precision` of its target, it snaps, reports once more and stops.
import { frameScheduler } from "./primitives/frame-scheduler/scheduler";
import { approach } from "./approach";
export type SmootherOptions = {
/** Time to cover half the remaining distance, in ms. 0 follows the target without easing. */
halfLife: number;
/** Distance at which a component counts as arrived, in the value's own units (default 0.01). */
precision?: number;
/** Receives the value in the write phase of each frame while it moves. Do not mutate it. */
onChange: (value: readonly number[]) => void;
};
export type Smoother = {
/** Moves the target; the value follows over the next frames. */
set: (target: readonly number[]) => void;
/** Sets value and target at once, without easing, and reports the value immediately. */
jump: (value: readonly number[]) => void;
/** Stops following; the value stays where it is. */
stop: () => void;
};
export function createSmoother(
initial: readonly number[],
{ halfLife, precision = 0.01, onChange }: SmootherOptions,
): Smoother {
let value = [...initial];
let target = [...initial];
let last = 0;
let cancel: (() => void) | null = null;
const stop = () => {
cancel?.();
cancel = null;
};
const task = {
write(time: number) {
// Frame timestamps and performance.now() share a clock; a frame that began before the
// target was set yields a negative interval.
const dt = Math.max(0, time - last);
last = time;
let arrived = true;
value = value.map((current, i) => {
const next = approach(current, target[i], dt, halfLife);
if (Math.abs(target[i] - next) < precision) return target[i];
arrived = false;
return next;
});
onChange(value);
if (arrived) stop();
},
};
return {
set(next) {
target = [...next];
if (cancel) return;
last = performance.now();
cancel = frameScheduler.loop(task);
},
jump(next) {
stop();
value = [...next];
target = [...next];
onChange(value);
},
stop,
};
}