Pointer follower
primitive · T1 · v1.0.0 · readyAbout
Feeds custom cursors and trailing elements without React re-renders: one or more viewport positions in px, eased by half-life through the smoothing primitive. Active only for fine, hovering pointers.
Layers
- JS
- CSS cannot read pointer coordinates.
- Static
- No following; properties stay unset.
Accessibility
Callers do not mount it on the static layer, which reduced motion selects.
Pointer-only by nature: whatever follows the pointer must be decoration, never the only feedback (D3.8).
Sources
- original
Code
Self-contained: copy every file, keeping the folder structure.
follower.ts// web-effects pointer-follower 1.0.0 · MIT-0
// Pointer follower: follows the pointer over an area and writes one or more smoothed viewport
// positions (px) into custom properties (D2.7). Each output has its own half-life, so a fast
// output and a slow one make a dot with a trail. Events only set smoother targets; values are
// written in the shared scheduler's write phase (D3.9). Activate it only for fine pointers
// (D3.7): see `finePointerQuery` in the pointer tracker.
import { createSmoother } from "./primitives/smoothing/smoother";
export type FollowerOutput = {
/** Custom properties receiving the position in px from the viewport's left and top edges. */
x: string;
y: string;
/** Lag of this output, in ms (0: attached to the pointer). */
halfLife: number;
};
export type FollowerOptions = {
/** Positions to write; at least one. */
outputs: readonly FollowerOutput[];
/** Element whose pointer moves are followed (default: the element written to). */
area?: HTMLElement;
};
/** Sub-pixel precision is invisible; stopping at 0.1 px lets the loop rest sooner. */
const precision = 0.1;
export function trackPointerFollower(
element: HTMLElement,
{ outputs, area = element }: FollowerOptions,
): () => void {
const smoothers = outputs.map(({ x, y, halfLife }) =>
createSmoother([0, 0], {
halfLife,
precision,
onChange: ([left, top]) => {
element.style.setProperty(x, String(left));
element.style.setProperty(y, String(top));
},
}),
);
// After entering the area, outputs start at the pointer instead of gliding in from where they
// were left.
let inside = false;
const onMove = (event: PointerEvent) => {
const position = [event.clientX, event.clientY];
for (const smoother of smoothers)
if (inside) smoother.set(position);
else smoother.jump(position);
inside = true;
};
const onLeave = () => {
inside = false;
};
area.addEventListener("pointermove", onMove, { passive: true });
area.addEventListener("pointerleave", onLeave, { passive: true });
return () => {
area.removeEventListener("pointermove", onMove);
area.removeEventListener("pointerleave", onLeave);
for (const smoother of smoothers) smoother.stop();
for (const { x, y } of outputs) {
element.style.removeProperty(x);
element.style.removeProperty(y);
}
};
}
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();
primitives/smoothing/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/smoothing/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 "../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,
};
}
use-pointer-follower.ts// web-effects pointer-follower 1.0.0 · MIT-0
import { useEffect, type RefObject } from "react";
import { trackPointerFollower, type FollowerOutput } from "./follower";
/**
* Runs the follower on `ref` while `enabled` (typically a "js" layer and a fine pointer).
* `outputs` must keep its identity between renders (a module constant or a memoised array).
*/
export function usePointerFollower(
ref: RefObject<HTMLElement | null>,
{
enabled,
outputs,
area,
}: {
enabled: boolean;
outputs: readonly FollowerOutput[];
area?: RefObject<HTMLElement | null>;
},
) {
useEffect(() => {
const element = ref.current;
if (!enabled || !element) return;
return trackPointerFollower(element, {
outputs,
area: area?.current ?? undefined,
});
}, [ref, enabled, outputs, area]);
}