Pointer tracker
primitive · T1 · v1.0.0 · readyAbout
Feeds pointer-driven effects (magnetic pull, tilt, followers) without React re-renders: two custom properties, updated at most once per frame. Active only for fine, hovering pointers.
Layers
- JS
- CSS cannot read pointer coordinates.
- Static
- No tracking; properties stay unset (effects fall back to their resting state).
Accessibility
Callers do not mount it on the static layer, which reduced motion selects.
Pointer-only by nature: effects using it need equivalent keyboard focus feedback (D3.8).
Sources
- original
Code
Self-contained: copy every file, keeping the folder structure.
normalize.ts// web-effects pointer-tracker 1.0.0 · MIT-0
export type Box = { left: number; top: number; width: number; height: number };
/** Pointer position relative to a box: -1 at the left/top edge, 0 at the centre, 1 at the right/bottom edge. */
export function normalizePointer(
clientX: number,
clientY: number,
box: Box,
): { x: number; y: number } {
return {
x: box.width > 0 ? ((clientX - box.left) / box.width) * 2 - 1 : 0,
y: box.height > 0 ? ((clientY - box.top) / box.height) * 2 - 1 : 0,
};
}
/** `box` grown by `margin` on every side. */
export function growBox(box: Box, margin: number): Box {
return {
left: box.left - margin,
top: box.top - margin,
width: box.width + 2 * margin,
height: box.height + 2 * margin,
};
}
/** Whether the point lies inside `box`, edges included. */
export function containsPoint(
clientX: number,
clientY: number,
box: Box,
): boolean {
return (
clientX >= box.left &&
clientX <= box.left + box.width &&
clientY >= box.top &&
clientY <= box.top + box.height
);
}
pointer.ts// web-effects pointer-tracker 1.0.0 · MIT-0
// Pointer tracker: writes the pointer position over an element, normalised to -1..1, into two
// custom properties (D2.7). Events only store coordinates; measuring and writing happen in the
// shared scheduler, once per frame at most (D3.9). Resets to 0, 0 when the pointer leaves.
// Activate it only for fine pointers (D3.7): see `finePointerQuery`.
import { frameScheduler } from "./primitives/frame-scheduler/scheduler";
import { containsPoint, growBox, normalizePointer } from "./normalize";
/** Pointer-driven behaviour applies only where this media query matches (D3.7). */
export const finePointerQuery = "(hover: hover) and (pointer: fine)";
export type PointerOptions = {
/** Custom properties to write, the item's private names (D2.19). */
x: string;
y: string;
/**
* Tracking area around the element, in px (default 0: the element's box). With a margin, the
* values are relative to the box grown by `margin` on every side, so they still span -1..1,
* and the pointer is followed from the window while that area is in the viewport.
*/
margin?: number;
};
type Listener = [
target: EventTarget,
type: string,
handler: (event: PointerEvent) => void,
];
export function trackPointer(
element: HTMLElement,
{ x, y, margin = 0 }: PointerOptions,
): () => void {
let client: { x: number; y: number } | null = null;
let value = { x: 0, y: 0 };
const task = {
read() {
const box = growBox(element.getBoundingClientRect(), margin);
// Element listeners only report moves over the element; window listeners report all.
value =
client && (margin === 0 || containsPoint(client.x, client.y, box))
? normalizePointer(client.x, client.y, box)
: { x: 0, y: 0 };
},
write() {
element.style.setProperty(x, String(value.x));
element.style.setProperty(y, String(value.y));
},
};
const onMove = (event: PointerEvent) => {
client = { x: event.clientX, y: event.clientY };
frameScheduler.once(task);
};
const onLeave = () => {
client = null;
frameScheduler.once(task);
};
const listen = (listeners: Listener[]) => {
for (const [target, type, handler] of listeners)
target.addEventListener(type, handler as EventListener, {
passive: true,
});
return () => {
for (const [target, type, handler] of listeners)
target.removeEventListener(type, handler as EventListener);
};
};
let stopListening: () => void;
if (margin === 0) {
stopListening = listen([
[element, "pointermove", onMove],
[element, "pointerleave", onLeave],
]);
} else {
// Window listeners only while the tracking area is visible: off-screen trackers cost nothing.
let stopWindow: (() => void) | null = null;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting && !stopWindow) {
stopWindow = listen([
[window, "pointermove", onMove],
[document.documentElement, "pointerleave", onLeave],
]);
} else if (!entry.isIntersecting && stopWindow) {
stopWindow();
stopWindow = null;
onLeave();
}
},
{ rootMargin: `${margin}px` },
);
observer.observe(element);
stopListening = () => {
observer.disconnect();
stopWindow?.();
};
}
const cancelPending = frameScheduler.once(task);
return () => {
cancelPending();
stopListening();
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();
use-pointer.ts// web-effects pointer-tracker 1.0.0 · MIT-0
import { useEffect, useSyncExternalStore, type RefObject } from "react";
import { finePointerQuery, trackPointer, type PointerOptions } from "./pointer";
function watchFinePointer(onChange: () => void) {
const media = matchMedia(finePointerQuery);
media.addEventListener("change", onChange);
return () => media.removeEventListener("change", onChange);
}
/** True for a fine, hovering pointer; false during server rendering and on touch (D3.7). */
export function useFinePointer(): boolean {
return useSyncExternalStore(
watchFinePointer,
() => matchMedia(finePointerQuery).matches,
() => false,
);
}
/** Runs the tracker on `ref` while `enabled` (typically a "js" layer and a fine pointer). */
export function usePointer(
ref: RefObject<HTMLElement | null>,
{ enabled, x, y, margin }: PointerOptions & { enabled: boolean },
) {
useEffect(() => {
const element = ref.current;
if (!enabled || !element) return;
return trackPointer(element, { x, y, margin });
}, [ref, enabled, x, y, margin]);
}