← All items

Context cursor

effect · cursor · delight · T1 · v1.0.0 · ready

About

Wraps a region of the page. Inside it, a small dot follows a mouse or trackpad pointer, eased, with a second dot trailing behind. Over elements marked with `data-cursor`, the dot changes: a round lens that blurs what is under it, a pill showing the element's label, or any shape the host supplies. Outside the region, and on touch screens, the system cursor works as usual.

Move the pointer over the heading, the badge and the card.

Layers

JS
CSS cannot read pointer coordinates (pointer-follower and smoothing primitives).
Static
No custom cursor: the system cursor only.

Skin

VariableDefaultMeaning
--context-cursor-color#171717Fill of the dot, the trailing dot and the label pill; colour of host shapes (currentColor).
--context-cursor-label-color#fffText colour inside the label pill.
--context-cursor-size0.75remDiameter of the dot.
--context-cursor-trail-size0.375remDiameter of the trailing dot.
--context-cursor-lens-size5remDiameter of the blur lens; larger lenses cost more to repaint.
--context-cursor-lens-blur6pxBlur radius inside the lens.
--context-cursor-duration200msLength of the change between states, and of showing or hiding the cursor.
--context-cursor-easingease-outEasing of the change between states.
--context-cursor-z-index1000Stacking level of the cursor; above everything it passes over.

Accessibility

Static layer: no custom cursor.

Hidden from assistive technology. hideNative removes the system cursor inside the region only; keep it off where precise pointing matters (forms, dense controls).

Sources

  • reel · thedesignshop.tds · "Magnetic Buttons" (cursor turning into a shape) and "Cursor with Context" (dot with a trail, blur lens) reels; technique only (P6).

Code

Download zip

Self-contained: copy every file, keeping the folder structure.

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>
  );
}
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;
}
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/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>
  );
}
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 },
  };
}