Cursor with context
composition · cursor · text · overlay · T1 · v1.0.0 · readyAbout
A marquee band of phrases scrolls endlessly. Inside the section a small cursor with a trailing dot follows a mouse or trackpad pointer: over the band it becomes a round lens that blurs the text, over the button it shows a short label. The button opens a side drawer over the dimmed page, where the system cursor is back.
Move the pointer over the band and the button; click the button.
Built from
- Effects
- Context cursor, Marquee, Side drawer
- Primitives
- Frame scheduler, Layer select, Pointer follower, Pointer tracker, Smoothing
Layers
- Native
- No gated feature: supported everywhere.
- JS
- From its effects: context-cursor.
- Static
- The band's first copy at rest, the system cursor, a drawer that opens and closes at once (each effect's static layer).
Skin
| Variable | Default | Meaning |
|---|---|---|
--cursor-with-context-accent | #e7000b | Colour of the band's separators and of the cursor. |
Accessibility
Each effect's static layer: the band stands still, no custom cursor, the drawer opens without sliding.
The band's text is read once; the cursor is hidden from assistive technology.
Sources
- reel · thedesignshop.tds · "Cursor with Context" reel; technique only (P6).
Code
Self-contained: copy every file, keeping the folder structure.
effects/context-cursor/cursor.tsx// web-effects context-cursor 1.0.0 · MIT-0
import type { ReactNode } from "react";
import mechanism from "./mechanism.module.css";
// The cursor layers, shared by both styling variants (P8). Decoration only: hidden from
// assistive technology and transparent to the pointer.
export type CursorTarget = {
/** `data-cursor` of the hovered target, or null over the rest of the region. */
state: string | null;
/** Last label shown, kept while the label layer animates out. */
label: string;
};
/** Which layer a target state shows: the built-in lens and label, a host shape, or the dot. */
function layerOf(state: string | null, shapes: Record<string, ReactNode>) {
if (state === "lens" || state === "label") return state;
if (state !== null && Object.hasOwn(shapes, state)) return "shape";
return "default";
}
export function Cursor({
visible,
target,
shapes,
labelClassName,
}: {
visible: boolean;
target: CursorTarget;
shapes: Record<string, ReactNode>;
labelClassName: string;
}) {
return (
<div
aria-hidden="true"
className={mechanism.cursor}
data-visible={visible || undefined}
data-state={layerOf(target.state, shapes)}
>
<span className={mechanism.trail} />
<span className={mechanism.point}>
<span className={mechanism.dot} />
<span className={mechanism.lens} />
<span className={`${mechanism.label} ${labelClassName}`}>
{target.label}
</span>
{Object.entries(shapes).map(([name, shape]) => (
<span
key={name}
className={mechanism.shape}
data-active={name === target.state || undefined}
>
{shape}
</span>
))}
</span>
</div>
);
}
effects/context-cursor/mechanism.module.css/* web-effects context-cursor 1.0.0 · MIT-0 */
/* Mechanism of the context cursor (D2.8, D3.11), shared by both styling variants.
Driver / renderer split (D2.7): the pointer follower (L2, data-layer="js") writes two smoothed
viewport positions on .root, in px: --_context-cursor-x/y (the cursor) and
--_context-cursor-trail-x/y (the trailing dot). The cursor layers are fixed and sit at those
positions; the hovered target's state picks which layer shows, by scale and opacity.
L3: no cursor is rendered at all (static layer, touch screens, reduced motion). */
.root {
--_context-cursor-color: var(--context-cursor-color, #171717);
--_context-cursor-label-color: var(--context-cursor-label-color, #fff);
--_context-cursor-size: var(--context-cursor-size, 0.75rem);
--_context-cursor-trail-size: var(--context-cursor-trail-size, 0.375rem);
--_context-cursor-lens-size: var(--context-cursor-lens-size, 5rem);
--_context-cursor-lens-blur: var(--context-cursor-lens-blur, 6px);
--_context-cursor-duration: var(--context-cursor-duration, 200ms);
--_context-cursor-easing: var(--context-cursor-easing, ease-out);
--_context-cursor-z-index: var(--context-cursor-z-index, 1000);
}
/* D3.7: the system cursor is hidden only inside the region, and only while the custom cursor
runs (the attribute is set on the JS layer only, which needs a fine pointer). */
.root[data-hide-native],
.root[data-hide-native] * {
cursor: none;
}
.cursor {
position: fixed;
top: 0;
left: 0;
z-index: var(--_context-cursor-z-index);
pointer-events: none;
opacity: 0;
transition: opacity var(--_context-cursor-duration)
var(--_context-cursor-easing);
}
.cursor[data-visible] {
opacity: 1;
}
/* Zero-size anchor at the cursor position; the layers inside centre on it. */
.point {
position: absolute;
top: 0;
left: 0;
translate: calc(var(--_context-cursor-x, 0) * 1px)
calc(var(--_context-cursor-y, 0) * 1px);
}
.trail,
.dot,
.lens,
.label,
.shape {
position: absolute;
top: 0;
left: 0;
transition-property: scale, opacity;
transition-duration: var(--_context-cursor-duration);
transition-timing-function: var(--_context-cursor-easing);
}
.trail {
width: var(--_context-cursor-trail-size);
height: var(--_context-cursor-trail-size);
border-radius: 50%;
background: var(--_context-cursor-color);
translate: calc(var(--_context-cursor-trail-x, 0) * 1px - 50%)
calc(var(--_context-cursor-trail-y, 0) * 1px - 50%);
}
.dot,
.lens,
.label,
.shape {
translate: -50% -50%;
scale: 0;
opacity: 0;
}
.dot {
width: var(--_context-cursor-size);
height: var(--_context-cursor-size);
border-radius: 50%;
background: var(--_context-cursor-color);
}
/* backdrop-filter repaints the area under the lens as it moves (D3.4 exception, see notes).
Safari 17 needs the prefix. */
.lens {
width: var(--_context-cursor-lens-size);
height: var(--_context-cursor-lens-size);
border-radius: 50%;
-webkit-backdrop-filter: blur(var(--_context-cursor-lens-blur));
backdrop-filter: blur(var(--_context-cursor-lens-blur));
}
.label {
border-radius: 9999px;
background: var(--_context-cursor-color);
color: var(--_context-cursor-label-color);
white-space: nowrap;
}
/* Host-supplied shapes take the cursor colour through currentColor. */
.shape {
display: grid;
color: var(--_context-cursor-color);
}
/* One layer at a time: the state of the hovered target picks it. */
.cursor[data-state="default"] .dot,
.cursor[data-state="lens"] .lens,
.cursor[data-state="label"] .label,
.shape[data-active] {
scale: 1;
opacity: 1;
}
/* The trailing dot belongs to the plain cursor only. */
.cursor:not([data-state="default"]) .trail {
scale: 0;
opacity: 0;
}
effects/context-cursor/tailwind/ContextCursor.tsx// web-effects context-cursor 1.0.0 · MIT-0
"use client";
import type { ReactNode } from "react";
import { Cursor } from "../cursor";
import mechanism from "../mechanism.module.css";
import { useContextCursor } from "../use-context-cursor";
/**
* Shows a custom cursor over its children (the region), which changes with the hovered target:
* `data-cursor="lens"` blurs what is under it, `data-cursor="label"` shows `data-cursor-label`,
* any key of `shapes` shows that shape. `lag` and `trailLag`: half-lives in ms of the cursor and
* of its trailing dot. `hideNative` hides the system cursor inside the region.
*/
export function ContextCursor({
children,
shapes = {},
hideNative = false,
lag = 20,
trailLag = 120,
className = "",
}: {
children: ReactNode;
shapes?: Record<string, ReactNode>;
hideNative?: boolean;
lag?: number;
trailLag?: number;
className?: string;
}) {
const { driven, rootProps, cursorProps } = useContextCursor({
lag,
trailLag,
hideNative,
});
return (
<div {...rootProps} className={`${mechanism.root} ${className}`}>
{children}
{driven && (
<Cursor
{...cursorProps}
shapes={shapes}
labelClassName="px-3 py-1.5 text-xs font-semibold"
/>
)}
</div>
);
}
effects/context-cursor/use-context-cursor.ts// web-effects context-cursor 1.0.0 · MIT-0
import { useEffect, useMemo, useRef, useState } from "react";
import { useLayer } from "../../primitives/layer-select/use-layer";
import { usePointerFollower } from "../../primitives/pointer-follower/use-pointer-follower";
import { useFinePointer } from "../../primitives/pointer-tracker/use-pointer";
import type { CursorTarget } from "./cursor";
// Behaviour shared by both styling variants (P8): layer decision, the L2 follower, and which
// target the pointer is over. Positions go to custom properties every frame; the hovered target
// is React state, which changes only when the pointer crosses a target's edge.
const resting: CursorTarget = { state: null, label: "" };
/** The target state under `element`, read from the nearest `[data-cursor]` inside `root`. */
function targetUnder(
element: EventTarget | null,
root: HTMLElement,
previous: CursorTarget,
): CursorTarget {
const target =
element instanceof Element ? element.closest("[data-cursor]") : null;
if (!target || !root.contains(target))
return previous.state === null ? previous : { ...previous, state: null };
const state = target.getAttribute("data-cursor");
const label = target.getAttribute("data-cursor-label") || previous.label;
return state === previous.state && label === previous.label
? previous
: { state, label };
}
export function useContextCursor({
lag,
trailLag,
hideNative,
}: {
lag: number;
trailLag: number;
hideNative: boolean;
}) {
const ref = useRef<HTMLDivElement>(null);
// No native layer (CSS cannot read pointer coordinates); a fine pointer is a prerequisite (D3.7).
const driven = useLayer(null, useFinePointer()) === "js";
const outputs = useMemo(
() => [
{ x: "--_context-cursor-x", y: "--_context-cursor-y", halfLife: lag },
{
x: "--_context-cursor-trail-x",
y: "--_context-cursor-trail-y",
halfLife: trailLag,
},
],
[lag, trailLag],
);
usePointerFollower(ref, { enabled: driven, outputs });
const [visible, setVisible] = useState(false);
const [target, setTarget] = useState(resting);
useEffect(() => {
const root = ref.current;
if (!driven || !root) return;
const onOver = (event: PointerEvent) => {
setVisible(true);
setTarget((previous) => targetUnder(event.target, root, previous));
};
const onLeave = () => {
setVisible(false);
setTarget((previous) => ({ ...previous, state: null }));
};
root.addEventListener("pointerover", onOver, { passive: true });
root.addEventListener("pointerleave", onLeave, { passive: true });
return () => {
root.removeEventListener("pointerover", onOver);
root.removeEventListener("pointerleave", onLeave);
onLeave();
};
}, [driven]);
return {
driven,
rootProps: {
ref,
"data-layer": driven ? "js" : undefined,
"data-hide-native": (driven && hideNative) || undefined,
},
cursorProps: { visible, target },
};
}
effects/marquee/mechanism.module.css/* web-effects marquee 1.0.0 · MIT-0 */
/* Mechanism of the marquee (D2.8, D3.11), shared by both styling variants.
.track holds `copies` identical .group elements side by side (copies count set inline as
--_marquee-copies). Moving the track by one group, -100% / copies of its own width, lands on
an identical picture, so the loop is seamless. L1: a CSS animation, which every supported
browser runs, so the native layer has no feature gate and there is no L2. L3 (base rules):
the track stands still. */
.root {
--_marquee-duration: var(--marquee-duration, 20s);
--_marquee-gap: var(--marquee-gap, 2rem);
overflow: hidden;
/* Width comes from the container, never from the (much wider) track: without this, a grid or
flex track sized to its content would grow to the track's width. */
contain: inline-size;
}
.track {
display: flex;
width: max-content;
}
/* The gap also trails each group, so the seam between copies matches the gap inside them. */
.group {
display: flex;
flex-shrink: 0;
align-items: center;
gap: var(--_marquee-gap);
padding-inline-end: var(--_marquee-gap);
}
@keyframes slide {
to {
transform: translateX(calc(-100% / var(--_marquee-copies)));
}
}
/* L1 native (gated on the override attribute, D3.6a). */
:root:not([data-fx-layer]) .track,
:root[data-fx-layer="native"] .track {
animation: slide var(--_marquee-duration) linear infinite;
}
.root[data-reverse] .track {
animation-direction: reverse;
}
/* Hover or focus inside pauses the row (WCAG 2.2.2, partly). */
.root:hover .track,
.root:focus-within .track {
animation-play-state: paused;
}
/* L3 under reduced motion (unless forced). */
@media (prefers-reduced-motion: reduce) {
:root:not([data-fx-layer]) .track {
animation: none;
}
}
effects/marquee/tailwind/Marquee.tsx// web-effects marquee 1.0.0 · MIT-0
import type { ReactNode } from "react";
import mechanism from "../mechanism.module.css";
import { Track } from "../track";
/**
* Slides `children` sideways without end. `copies`: how many times the content is repeated; one
* copy must be at least as wide as the marquee, or a gap shows before the loop restarts.
*/
export function Marquee({
children,
copies = 2,
reverse = false,
className = "",
}: {
children: ReactNode;
copies?: number;
reverse?: boolean;
className?: string;
}) {
return (
<div
data-reverse={reverse || undefined}
className={`${mechanism.root} w-full ${className}`}
>
<Track copies={copies}>{children}</Track>
</div>
);
}
effects/marquee/track.tsx// web-effects marquee 1.0.0 · MIT-0
import type { CSSProperties, ReactNode } from "react";
import mechanism from "./mechanism.module.css";
// The moving track, shared by both styling variants (P8): `copies` groups of the same content.
// Only the first is exposed; the others are aria-hidden and inert (no focus, no clicks).
export function Track({
children,
copies,
}: {
children: ReactNode;
copies: number;
}) {
return (
<div
className={mechanism.track}
style={{ "--_marquee-copies": copies } as CSSProperties}
>
{Array.from({ length: copies }, (_, index) => (
<div
key={index}
className={mechanism.group}
aria-hidden={index > 0 || undefined}
inert={index > 0 || undefined}
>
{children}
</div>
))}
</div>
);
}
effects/side-drawer/mechanism.module.css/* web-effects side-drawer 1.0.0 · MIT-0 */
/* Mechanism of the side drawer (D2.8, D3.11), shared by both styling variants.
.drawer is a modal <dialog> (showModal: top layer, focus trap, Escape, inert page, ::backdrop)
positioned as a floating panel along one side; .body fills it and scrolls. Opening: the panel
slides in from its side while the backdrop fades in, then the content fades in. Closing: the
hook sets data-closing, waits for the drawer's animations, then closes the dialog.
L1: CSS animations, run by every supported browser: no feature gate, no JS layer. JS only
opens, closes and waits (D3.6c). L3 (base rules): opens and closes at once. */
.drawer {
--_side-drawer-width: var(--side-drawer-width, 24rem);
--_side-drawer-inset: var(--side-drawer-inset, 0.75rem);
--_side-drawer-radius: var(--side-drawer-radius, 1rem);
--_side-drawer-surface: var(--side-drawer-surface, #fff);
--_side-drawer-backdrop: var(--side-drawer-backdrop, rgb(0 0 0 / 0.4));
--_side-drawer-duration: var(--side-drawer-duration, 400ms);
--_side-drawer-easing: var(
--side-drawer-easing,
cubic-bezier(0.32, 0.72, 0, 1)
);
--_side-drawer-content-delay: var(--side-drawer-content-delay, 150ms);
/* Off-screen offset the panel slides from: its own width plus the inset. */
--_side-drawer-from: calc(100% + var(--_side-drawer-inset));
/* Replaces the UA's centred modal box. */
position: fixed;
inset: var(--_side-drawer-inset) var(--_side-drawer-inset)
var(--_side-drawer-inset) auto;
box-sizing: border-box;
width: min(var(--_side-drawer-width), 100% - 2 * var(--_side-drawer-inset));
height: auto;
max-width: none;
max-height: none;
margin: 0;
padding: 0;
border: 0;
border-radius: var(--_side-drawer-radius);
background: var(--_side-drawer-surface);
color: inherit;
overflow: hidden;
}
.drawer[data-side="left"] {
--_side-drawer-from: calc(-100% - var(--_side-drawer-inset));
inset: var(--_side-drawer-inset) auto var(--_side-drawer-inset)
var(--_side-drawer-inset);
}
/* ::backdrop inherits the alias from the dialog (Chrome 122, Firefox 120, Safari 17.4). */
.drawer::backdrop {
background: var(--_side-drawer-backdrop);
}
/* Fills the panel, so a click whose target is the dialog itself landed on the backdrop. */
.body {
box-sizing: border-box;
height: 100%;
overflow: auto;
overscroll-behavior: contain;
}
@keyframes slide-in {
from {
translate: var(--_side-drawer-from) 0;
opacity: 0;
}
}
@keyframes slide-out {
to {
translate: var(--_side-drawer-from) 0;
opacity: 0;
}
}
@keyframes fade-in {
from {
opacity: 0;
}
}
@keyframes fade-out {
to {
opacity: 0;
}
}
@keyframes content-in {
from {
translate: 0 0.5rem;
opacity: 0;
}
}
/* L1 native (gated on the override attribute, D3.6a). */
:root:not([data-fx-layer]) .drawer[open],
:root[data-fx-layer="native"] .drawer[open] {
animation: slide-in var(--_side-drawer-duration) var(--_side-drawer-easing);
}
:root:not([data-fx-layer]) .drawer[open]::backdrop,
:root[data-fx-layer="native"] .drawer[open]::backdrop {
animation: fade-in var(--_side-drawer-duration) ease-out;
}
:root:not([data-fx-layer]) .drawer[open] .body,
:root[data-fx-layer="native"] .drawer[open] .body {
animation: content-in var(--_side-drawer-duration) var(--_side-drawer-easing)
var(--_side-drawer-content-delay) both;
}
/* Closing: the hook waits for the drawer's own animation (the slide) before closing. */
:root:not([data-fx-layer]) .drawer[data-closing],
:root[data-fx-layer="native"] .drawer[data-closing] {
animation: slide-out var(--_side-drawer-duration) var(--_side-drawer-easing)
forwards;
}
:root:not([data-fx-layer]) .drawer[data-closing]::backdrop,
:root[data-fx-layer="native"] .drawer[data-closing]::backdrop {
animation: fade-out var(--_side-drawer-duration) ease-in forwards;
}
:root:not([data-fx-layer]) .drawer[data-closing] .body,
:root[data-fx-layer="native"] .drawer[data-closing] .body {
animation: none;
}
/* L3 under reduced motion (unless forced): open and close at once. Same specificity as the
native rules above ([open] also matches while closing), so these win by order. */
@media (prefers-reduced-motion: reduce) {
:root:not([data-fx-layer]) .drawer[open],
:root:not([data-fx-layer]) .drawer[open]::backdrop,
:root:not([data-fx-layer]) .drawer[open] .body {
animation: none;
}
}
effects/side-drawer/tailwind/SideDrawer.tsx// web-effects side-drawer 1.0.0 · MIT-0
"use client";
import type { ReactNode } from "react";
import mechanism from "../mechanism.module.css";
import { useSideDrawer } from "../use-side-drawer";
/**
* A modal panel that slides in from one side over a dimmed page. Controlled: `open` and
* `onOpenChange` (called with false on Escape, on a backdrop click, or when the dialog closes).
* Name it with `label` or `labelledBy`. `lockScroll` stops the page scrolling while open.
*/
export function SideDrawer({
open,
onOpenChange,
children,
side = "right",
label,
labelledBy,
lockScroll = true,
className = "",
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
children: ReactNode;
side?: "left" | "right";
label?: string;
labelledBy?: string;
lockScroll?: boolean;
className?: string;
}) {
const { dialogProps } = useSideDrawer({ open, onOpenChange, lockScroll });
return (
<dialog
{...dialogProps}
data-side={side}
aria-label={label}
aria-labelledby={labelledBy}
className={`${mechanism.drawer} shadow-2xl ${className}`}
>
<div className={`${mechanism.body} p-6`}>{children}</div>
</dialog>
);
}
effects/side-drawer/use-side-drawer.ts// web-effects side-drawer 1.0.0 · MIT-0
import {
useEffect,
useLayoutEffect,
useRef,
useState,
type MouseEvent,
type PointerEvent,
type SyntheticEvent,
} from "react";
// Behaviour shared by both styling variants (P8): syncing `open` with the modal dialog, the
// animated close, light dismiss, and the scroll lock. CSS owns every animation; closing waits
// for whatever animations the drawer runs (none on the static layer, so it closes at once).
export function useSideDrawer({
open,
onOpenChange,
lockScroll,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
lockScroll: boolean;
}) {
const ref = useRef<HTMLDialogElement>(null);
const latest = useRef({ open, onOpenChange });
useLayoutEffect(() => {
latest.current = { open, onOpenChange };
});
// Whether the dialog is showing, closing animation included: drives the scroll lock.
const [shown, setShown] = useState(false);
useEffect(() => {
const dialog = ref.current;
if (!dialog) return;
if (open) {
delete dialog.dataset.closing;
if (!dialog.open) {
dialog.showModal();
setShown(true);
}
return;
}
if (!dialog.open) return;
let cancelled = false;
dialog.dataset.closing = "";
// getAnimations() applies the pending style change first, so the slide-out is included.
Promise.allSettled(dialog.getAnimations().map((a) => a.finished)).then(
() => {
if (cancelled) return;
dialog.close();
delete dialog.dataset.closing;
},
);
return () => {
cancelled = true;
};
}, [open]);
useEffect(() => {
if (!shown || !lockScroll) return;
const root = document.documentElement;
const previous = root.style.overflow;
root.style.overflow = "hidden";
return () => {
root.style.overflow = previous;
};
}, [shown, lockScroll]);
// Light dismiss: press and release both on the backdrop (the dialog itself, since .body fills
// the panel), so a text selection dragged out of the panel does not close it.
const pressedOnBackdrop = useRef(false);
const requestClose = () => {
if (latest.current.open) latest.current.onOpenChange(false);
};
return {
dialogProps: {
ref,
onCancel: (event: SyntheticEvent<HTMLDialogElement>) => {
// Escape: animate instead of closing at once. Browsers may refuse the cancellation
// (repeated Escape without user activation); onClose then keeps `open` in sync.
event.preventDefault();
requestClose();
},
onClose: () => {
setShown(false);
requestClose();
},
onPointerDown: (event: PointerEvent<HTMLDialogElement>) => {
pressedOnBackdrop.current = event.target === event.currentTarget;
},
onClick: (event: MouseEvent<HTMLDialogElement>) => {
if (pressedOnBackdrop.current && event.target === event.currentTarget)
requestClose();
pressedOnBackdrop.current = false;
},
},
};
}
mechanism.module.css/* web-effects cursor-with-context 1.0.0 · MIT-0 */
/* Mechanism of the cursor with context composition, shared by both styling variants. One accent
colours the marquee's separators and the cursor: the composition sets the cursor's skin
variable from its own. */
.root {
--_cursor-with-context-accent: var(--cursor-with-context-accent, #e7000b);
--context-cursor-color: var(--_cursor-with-context-accent);
}
.separator {
background: var(--_cursor-with-context-accent);
}
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/layer-select/layer.ts// web-effects layer-select 1.0.0 · MIT-0
// Browser side of layer selection: reads the current inputs and notifies on change.
// Framework-free, for plain-browser hosts; use-layer.ts wraps it for React.
import {
layerAttribute,
parseLayer,
selectLayer,
type Layer,
} from "./select-layer";
const reducedMotionQuery = "(prefers-reduced-motion: reduce)";
/**
* The layer for an item whose native layer needs `supports` (an `@supports` condition, the same
* text as in the item's CSS), or null when the item has no native layer.
*/
export function currentLayer(
supports: string | null,
prerequisitesMet = true,
): Layer {
return selectLayer({
nativeSupported: supports !== null && CSS.supports(supports),
reducedMotion: matchMedia(reducedMotionQuery).matches,
prerequisitesMet,
override: parseLayer(document.documentElement.getAttribute(layerAttribute)),
});
}
/** Calls `onChange` when reduced motion or the forced override changes. Returns a stop function. */
export function watchLayerInputs(onChange: () => void): () => void {
const media = matchMedia(reducedMotionQuery);
media.addEventListener("change", onChange);
const observer = new MutationObserver(onChange);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: [layerAttribute],
});
return () => {
media.removeEventListener("change", onChange);
observer.disconnect();
};
}
primitives/layer-select/select-layer.ts// web-effects layer-select 1.0.0 · MIT-0
// Layer selection (D2.4, D3.6). CSS decides on its own: `@supports` enables L1, and the base
// rules are the L3 static state, so server-rendered HTML works without JS. JavaScript only
// decides whether to mount an L2 driver; this is that decision, as a pure function.
//
// Forced override (R6.1): an attribute on <html>. Item CSS honours it by writing native-layer
// and reduced-motion rules as `:root:not([data-fx-layer]) .x, :root[data-fx-layer="native"] .x`.
// The showcase sets the attribute from `?driver=`; items never read the host's URL.
export const layers = ["native", "js", "static"] as const;
export type Layer = (typeof layers)[number];
export const layerAttribute = "data-fx-layer";
export function parseLayer(value: string | null | undefined): Layer | null {
return layers.find((layer) => layer === value) ?? null;
}
export type LayerInputs = {
/** The item's `@supports` condition holds; false for items without a native layer. */
nativeSupported: boolean;
reducedMotion: boolean;
/** Inputs the effect cannot work without (e.g. a fine pointer) are present. */
prerequisitesMet: boolean;
/** Forced layer from the `data-fx-layer` attribute; wins over everything else. */
override: Layer | null;
};
export function selectLayer({
nativeSupported,
reducedMotion,
prerequisitesMet,
override,
}: LayerInputs): Layer {
if (override) return override;
if (reducedMotion || !prerequisitesMet) return "static";
return nativeSupported ? "native" : "js";
}
primitives/layer-select/use-layer.ts// web-effects layer-select 1.0.0 · MIT-0
import { useCallback, useSyncExternalStore } from "react";
import { currentLayer, watchLayerInputs } from "./layer";
import type { Layer } from "./select-layer";
/**
* The active layer, or null during server rendering and hydration (CSS alone decides until then).
* Mount the L2 driver when this returns "js".
*/
export function useLayer(
supports: string | null,
prerequisitesMet = true,
): Layer | null {
const getSnapshot = useCallback(
() => currentLayer(supports, prerequisitesMet),
[supports, prerequisitesMet],
);
return useSyncExternalStore(watchLayerInputs, getSnapshot, () => null);
}
primitives/pointer-follower/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 "../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/pointer-follower/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]);
}
primitives/pointer-tracker/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
);
}
primitives/pointer-tracker/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 "../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/pointer-tracker/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]);
}
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,
};
}
tailwind/CursorWithContext.tsx// web-effects cursor-with-context 1.0.0 · MIT-0
"use client";
import type { ReactNode } from "react";
import { ContextCursor } from "../effects/context-cursor/tailwind/ContextCursor";
import { Marquee } from "../effects/marquee/tailwind/Marquee";
import { SideDrawer } from "../effects/side-drawer/tailwind/SideDrawer";
import mechanism from "../mechanism.module.css";
import { useCursorWithContext } from "../use-cursor-with-context";
/**
* A marquee band of `phrases` under a contextual cursor: over the band the cursor becomes a blur
* lens, over the `cta` button it shows `cursorLabel`. The button opens a side drawer titled
* `heading` with `children`. The drawer lies outside the cursor's region, so the system cursor
* always works inside it.
*/
export function CursorWithContext({
phrases,
cta,
cursorLabel = "Open",
heading,
closeLabel = "Close",
hideNative = false,
children,
className = "",
}: {
phrases: readonly string[];
cta: string;
cursorLabel?: string;
heading: string;
closeLabel?: string;
hideNative?: boolean;
children: ReactNode;
className?: string;
}) {
const { headingId, triggerProps, closeProps, drawerProps } =
useCursorWithContext();
return (
<div className={`${mechanism.root} ${className}`}>
<ContextCursor hideNative={hideNative}>
<div data-cursor="lens">
<Marquee className="py-4">
{phrases.map((phrase) => [
<span
key={phrase}
className="text-4xl font-black tracking-tight uppercase"
>
{phrase}
</span>,
<span
key={`${phrase}-separator`}
className={`${mechanism.separator} h-1 w-8`}
/>,
])}
</Marquee>
</div>
<div className="flex justify-center py-6">
<button
type="button"
{...triggerProps}
data-cursor="label"
data-cursor-label={cursorLabel}
className="rounded-full bg-neutral-900 px-6 py-3 text-sm font-semibold text-white"
>
{cta}
</button>
</div>
</ContextCursor>
<SideDrawer {...drawerProps}>
<div className="flex flex-col gap-5">
<div className="flex items-start justify-between gap-4">
<h2 id={headingId} className="text-xl font-semibold">
{heading}
</h2>
<button
type="button"
{...closeProps}
className="rounded-md border border-neutral-300 px-3 py-1 text-sm"
>
{closeLabel}
</button>
</div>
{children}
</div>
</SideDrawer>
</div>
);
}
use-cursor-with-context.ts// web-effects cursor-with-context 1.0.0 · MIT-0
import { useId, useState } from "react";
/** Drawer state and the id naming it, shared by both styling variants. */
export function useCursorWithContext() {
const [open, setOpen] = useState(false);
const headingId = useId();
return {
headingId,
triggerProps: { onClick: () => setOpen(true) },
closeProps: { onClick: () => setOpen(false) },
drawerProps: { open, onOpenChange: setOpen, labelledBy: headingId },
};
}