Magnetic pull
effect · button · delight · T1 · v1.0.0 · readyAbout
Wraps any interactive element. While a mouse or trackpad pointer is over it or within a small radius around it, the element shifts towards the pointer by a few pixels, eased; when the pointer leaves, it eases back to rest. On touch screens it scales down slightly while pressed instead.
Move the pointer near and over the buttons.
Layers
- JS
- CSS cannot read pointer coordinates (pointer-tracker primitive).
- Static
- The element stays in place; on touch screens it scales down while pressed.
Skin
| Variable | Default | Meaning |
|---|---|---|
--magnetic-pull-distance | 0.5rem | Largest shift towards the pointer, reached at the edge of the tracking area. |
--magnetic-pull-duration | 250ms | How long the element takes to catch up with the pointer. |
--magnetic-pull-easing | ease-out | Easing of the catch-up and of the return to rest. |
--magnetic-pull-press-scale | 0.96 | Scale while pressed on touch screens. |
Accessibility
Static layer: no pull and no press scale.
Sources
- reel · thedesignshop.tds · "Magnetic Buttons" reel; technique only (P6).
Code
Self-contained: copy every file, keeping the folder structure.
mechanism.module.css/* web-effects magnetic-pull 1.0.0 · MIT-0 */
/* Mechanism of the magnetic pull (D2.8, D3.11), shared by both styling variants.
Driver / renderer split (D2.7): the pointer tracker (L2, data-layer="js") writes the pointer
position over .root's tracking area, -1..1 per axis, into --_magnetic-pull-x/y; .pull
translates by that share of the distance. .root never moves: it is the box the tracker
measures, so the movement cannot feed back into the measurement. L3: no translate. */
.root {
--_magnetic-pull-distance: var(--magnetic-pull-distance, 0.5rem);
--_magnetic-pull-duration: var(--magnetic-pull-duration, 250ms);
--_magnetic-pull-easing: var(--magnetic-pull-easing, ease-out);
--_magnetic-pull-press-scale: var(--magnetic-pull-press-scale, 0.96);
}
/* Flex, not block: no line box (and no strut gap) around the host element. translate and
scale need a non-inline box. */
.pull {
display: flex;
transition-property: translate, scale;
transition-duration: var(--_magnetic-pull-duration);
transition-timing-function: var(--_magnetic-pull-easing);
}
/* L2 JS driver. Each write restarts the transition: the element chases the pointer, eased. */
.root[data-layer="js"] .pull {
translate: calc(var(--_magnetic-pull-x, 0) * var(--_magnetic-pull-distance))
calc(var(--_magnetic-pull-y, 0) * var(--_magnetic-pull-distance));
}
/* Touch adaptation (D3.7): wherever the fine-pointer query fails, press feedback instead. */
@media not all and (hover: hover) and (pointer: fine) {
.pull:active {
scale: var(--_magnetic-pull-press-scale);
}
}
/* L3 under reduced motion (unless forced): no pull, no press scale. */
@media (prefers-reduced-motion: reduce) {
:root:not([data-fx-layer]) .pull {
translate: none;
scale: none;
transition: none;
}
}
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-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]);
}
tailwind/MagneticPull.tsx// web-effects magnetic-pull 1.0.0 · MIT-0
"use client";
import type { ReactNode } from "react";
import mechanism from "../mechanism.module.css";
import { useMagneticPull } from "../use-magnetic-pull";
/**
* Pulls its child (a button, a link) towards a nearby fine pointer. `radius`: px around the child
* where the pull starts.
*/
export function MagneticPull({
children,
radius = 24,
className = "",
}: {
children: ReactNode;
radius?: number;
className?: string;
}) {
const { rootProps } = useMagneticPull(radius);
return (
<span
{...rootProps}
className={`${mechanism.root} inline-block ${className}`}
>
<span className={mechanism.pull}>{children}</span>
</span>
);
}
use-magnetic-pull.ts// web-effects magnetic-pull 1.0.0 · MIT-0
import { useRef } from "react";
import { useLayer } from "./primitives/layer-select/use-layer";
import {
useFinePointer,
usePointer,
} from "./primitives/pointer-tracker/use-pointer";
// Behaviour shared by both styling variants (P8): layer decision and the L2 driver. The variants
// add presentation classes only.
export function useMagneticPull(radius: number) {
const ref = useRef<HTMLSpanElement>(null);
// No native layer (CSS cannot read pointer coordinates); a fine pointer is a prerequisite (D3.7).
const driven = useLayer(null, useFinePointer()) === "js";
usePointer(ref, {
enabled: driven,
x: "--_magnetic-pull-x",
y: "--_magnetic-pull-y",
margin: radius,
});
return { rootProps: { ref, "data-layer": driven ? "js" : undefined } };
}