# Slipstream — Cursor Effect for React

> A spring-smoothed cursor follower: a soft bead of light that stretches into a teardrop at speed, brightening to white in motion and settling neutral at rest. Scoped to its container by default, opt into page-wide with `global`, never follows coarse pointers, scales up over [data-cursor-target] elements, and idles on its own when untouched.

- Page: https://crucibleui.com/components/cursors/slipstream
- Category: [cursors](https://crucibleui.com/components/cursors)
- Tier: free (full source)
- Engine: motion
- npm dependencies: motion

## Install

```bash
npx shadcn@latest add @crucible/slipstream
```

Registry JSON: https://crucibleui.com/r/slipstream.json

Import from `@/components/crucible/slipstream`.

## Props (`SlipstreamProps`)

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className?` | `string` | — | — |
| `size?` | `number` | `26` | Resting diameter of the follower bead in px. |
| `targetScale?` | `number` | `2.2` | Scale multiplier while hovering an element carrying `data-cursor-target`. |
| `colors?` | `[string, string]` | — | `[rest, peak]` colors — the bead settles to `rest` and brightens toward `peak` with speed. |
| `spring?` | `{ stiffness?: number; damping?: number; mass?: number }` | — | Spring physics for the chase motion. |
| `global?` | `boolean` | — | Attach to the whole viewport instead of the nearest containing element. Off by default — Slipstream is scoped to its parent (place it inside a `relative` container, like Crucible's backgrounds) so it never hijacks the cursor page-wide unless you explicitly opt in. |
| `hideNativeCursor?` | `boolean` | `true ("replace" vs. "augment")` | Hide the native system cursor while active. |
| `idle?` | `boolean` | `true` | Idle autoplay (scoped mode only): after 1.5s with no pointer in the container, a ghost bead swoops a seeded Lissajous path — speeding up and easing off so the teardrop stretch shows — and swells over `data-cursor-target` elements it crosses. A real pointer takes over instantly. Also runs on touch-only devices so the surface never looks dead. Never under reduced motion; sleeps offscreen. |

## Usage example

```tsx
import { Slipstream } from "@/components/crucible/slipstream";

export default function SlipstreamDemo() {
  return (
    <div className="relative isolate flex h-full min-h-[360px] w-full items-center justify-center overflow-hidden rounded-xl bg-neutral-950">
      <div
        aria-hidden
        className="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.035),transparent_70%)]"
      />
      <Slipstream />
      <div className="relative z-10 flex flex-col items-center gap-5 px-6 text-center">
        <p className="text-3xl font-semibold tracking-tight text-white">Move your cursor</p>
        <p className="max-w-sm text-sm text-neutral-500">
          The follower stretches with speed, then cross the marked target — it swells over it.
        </p>
        <button
          type="button"
          data-cursor-target
          className="rounded-full border border-white/20 bg-white/5 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-white/10"
        >
          Marked target
        </button>
      </div>
    </div>
  );
}
```

## Accessibility & performance

Honors `prefers-reduced-motion` with a designed static frame or fade (never a blank box) and passes `className` through.

## Source (`slipstream.tsx`)

```tsx
"use client";

import * as React from "react";
import { motion, useMotionValue, useMotionTemplate, useSpring, useTransform, useVelocity } from "motion/react";

import { cn } from "@/lib/utils";
import { useReducedMotion } from "@/hooks/use-reduced-motion";
import { useVisibilityPause } from "@/hooks/use-visibility-pause";

export interface SlipstreamProps {
  className?: string;
  /** Resting diameter of the follower bead in px. Default 26. */
  size?: number;
  /** Scale multiplier while hovering an element carrying `data-cursor-target`. Default 2.2. */
  targetScale?: number;
  /** `[rest, peak]` colors — the bead settles to `rest` and brightens toward `peak` with speed. */
  colors?: [string, string];
  /** Spring physics for the chase motion. */
  spring?: { stiffness?: number; damping?: number; mass?: number };
  /**
   * Attach to the whole viewport instead of the nearest containing element.
   * Off by default — Slipstream is scoped to its parent (place it inside a
   * `relative` container, like Crucible's backgrounds) so it never hijacks
   * the cursor page-wide unless you explicitly opt in.
   */
  global?: boolean;
  /** Hide the native system cursor while active. Default true ("replace" vs. "augment"). */
  hideNativeCursor?: boolean;
  /**
   * Idle autoplay (scoped mode only): after 1.5s with no pointer in the
   * container, a ghost bead swoops a seeded Lissajous path — speeding up and
   * easing off so the teardrop stretch shows — and swells over
   * `data-cursor-target` elements it crosses. A real pointer takes over
   * instantly. Also runs on touch-only devices so the surface never looks
   * dead. Never under reduced motion; sleeps offscreen. Default true.
   */
  idle?: boolean;
}

const DEFAULT_SPRING = { stiffness: 380, damping: 32, mass: 0.6 };
const IDLE_MS = 1500;
const GHOST_SPEED = 360; // mean px/s; modulated so the stretch breathes

/**
 * Slipstream — a spring-smoothed cursor follower: a gradient-cored bead of
 * light (hot white center, soft haloed edge) that stretches into a teardrop
 * along the direction of travel at speed — brightening to its peak color in
 * motion, trailed by a lagging after-glow — and settles to a quiet
 * cyan-tinted neutral at rest. Scoped to its nearest containing element by
 * default (`global` opts into page-wide), never follows coarse/touch
 * pointers (`matchMedia('(pointer: fine)')`), and scales up over any element
 * carrying `data-cursor-target`. With no pointer for 1.5s (scoped mode,
 * `idle`), a ghost bead swoops a Lissajous path so the surface never looks
 * dead — on touch devices too — until a real pointer takes over. It fully
 * disables itself (restoring the native cursor) under
 * `prefers-reduced-motion`.
 */
export function Slipstream({
  className,
  size = 26,
  targetScale = 2.2,
  colors = ["#bae6fd", "#ffffff"],
  spring,
  global = false,
  hideNativeCursor = true,
  idle = true,
}: SlipstreamProps) {
  const wrapperRef = React.useRef<HTMLDivElement>(null);
  const reducedMotion = useReducedMotion();
  const [finePointer, setFinePointer] = React.useState(false);
  const [hovering, setHovering] = React.useState(false);
  const [active, setActive] = React.useState(false);

  React.useEffect(() => {
    if (typeof window === "undefined" || !window.matchMedia) return;
    const mql = window.matchMedia("(pointer: fine)");
    const sync = () => setFinePointer(mql.matches);
    sync();
    mql.addEventListener("change", sync);
    return () => mql.removeEventListener("change", sync);
  }, []);

  // Auto-disabled on coarse pointers and under reduced motion — this is the
  // one Crucible component that fully turns off rather than falling back to
  // a static frame, per the cursor category's accessibility contract.
  // The idle ghost (scoped only) also keeps it alive on touch-only devices;
  // there the real touch never replaces a cursor, it only interrupts the ghost.
  const ghostAllowed = idle && !global && !reducedMotion;
  const enabled = (finePointer || ghostAllowed) && !reducedMotion;
  const [ghosting, setGhosting] = React.useState(false);

  const springCfg = { ...DEFAULT_SPRING, ...spring };
  const mx = useMotionValue(0);
  const my = useMotionValue(0);
  const x = useSpring(mx, springCfg);
  const y = useSpring(my, springCfg);

  const vx = useVelocity(x);
  const vy = useVelocity(y);
  const speed = useTransform([vx, vy], (latest) => {
    const [lvx, lvy] = latest as number[];
    return Math.min(Math.hypot(lvx, lvy) / 900, 1);
  });
  const angle = useTransform([vx, vy], (latest) => {
    const [lvx, lvy] = latest as number[];
    return Math.hypot(lvx, lvy) > 40 ? (Math.atan2(lvy, lvx) * 180) / Math.PI : 0;
  });
  // Velocity stretch is deliberately pronounced — the teardrop elongation IS
  // the component's signature, so it must read at a glance.
  const stretch = useTransform(speed, (s) => 1 + s * 1.5);
  const squash = useTransform(speed, (s) => 1 - s * 0.45);
  const heatPercent = useTransform(speed, (s) => `${Math.round(s * 100)}%`);
  const bodyColor = useMotionTemplate`color-mix(in oklab, ${colors[1]} ${heatPercent}, ${colors[0]})`;
  // Gradient core: a hot white center falling off through the speed-mixed body
  // color — presence at rest, incandescent in motion.
  const coreBackground = useMotionTemplate`radial-gradient(circle at 50% 45%, #ffffff 0%, ${bodyColor} 38%, transparent 72%)`;
  const haloOpacity = useTransform(speed, (s) => 0.4 + s * 0.5);

  // Trailing after-glow: a second, softer bead chasing the main one on a much
  // looser spring, fading in with speed and vanishing at rest.
  const trailX = useSpring(x, {
    stiffness: springCfg.stiffness * 0.35,
    damping: springCfg.damping * 0.9,
    mass: springCfg.mass * 1.4,
  });
  const trailY = useSpring(y, {
    stiffness: springCfg.stiffness * 0.35,
    damping: springCfg.damping * 0.9,
    mass: springCfg.mass * 1.4,
  });
  const trailOpacity = useTransform(speed, (s) => Math.min(s * 0.9, 0.5));

  const hoverScale = useSpring(1, { stiffness: 300, damping: 24 });
  React.useEffect(() => {
    hoverScale.set(hovering ? targetScale : 1);
  }, [hovering, targetScale, hoverScale]);

  // Real-pointer presence for the ghost: inside the scope, and when last seen.
  const presenceRef = React.useRef({ inside: false, lastReal: 0 });
  // The ghost loop reads the overlay through its own ref (set in the effect),
  // so the hook never captures `wrapperRef` itself.
  const overlayRef = React.useRef<HTMLDivElement | null>(null);
  const ghostRef = React.useRef({ t: 0, last: 0, on: false, frame: 0 });

  const tick = React.useCallback(
    (elapsed: number) => {
      const el = overlayRef.current;
      const g = ghostRef.current;
      if (elapsed < g.last) g.last = elapsed;
      const dt = Math.min(elapsed - g.last, 0.05);
      g.last = elapsed;
      if (!el) return;
      const pr = presenceRef.current;
      if (pr.inside || performance.now() - pr.lastReal < IDLE_MS) {
        if (g.on) {
          g.on = false;
          setGhosting(false);
        }
        return;
      }
      const w = el.clientWidth;
      const h = el.clientHeight;
      if (w < 2 || h < 2) return;
      const ax = w * 0.38;
      const ay = h * 0.3;
      // Speed swells and ebbs so the bead visibly stretches, then relaxes.
      const surge = 0.55 + 0.75 * Math.pow(0.5 + 0.5 * Math.sin(elapsed * 0.9), 2);
      g.t += (dt * GHOST_SPEED * surge) / Math.max(100, (ax * 2 + ay * 3) * 0.7);
      const px = w / 2 + ax * Math.sin(2 * g.t + 1.1);
      const py = h / 2 + ay * Math.sin(3 * g.t);
      if (!g.on) {
        g.on = true;
        // Seat (no swoop from wherever the real pointer left it).
        x.jump(px);
        y.jump(py);
        trailX.jump(px);
        trailY.jump(py);
        setGhosting(true);
      }
      mx.set(px);
      my.set(py);
      // Swell over marked targets the ghost crosses (hit-test ~10x/s).
      if (++g.frame % 6 === 0) {
        const rect = el.getBoundingClientRect();
        const hit = document.elementFromPoint(rect.left + px, rect.top + py);
        const parent = el.parentElement;
        const tgt = hit?.closest("[data-cursor-target]");
        setHovering(!!tgt && !!parent && parent.contains(tgt));
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  );

  // The ghost loop rides the inner layer so it sleeps offscreen / on hidden tabs.
  const ghostLoopRef = useVisibilityPause<HTMLDivElement>(tick, { paused: !enabled || !ghostAllowed });

  React.useEffect(() => {
    if (!enabled) return;
    const target: Window | HTMLElement | null = global ? window : (wrapperRef.current?.parentElement ?? null);
    if (!target) return;
    const cursorRoot: HTMLElement = global ? document.documentElement : (target as HTMLElement);
    const pr = presenceRef.current;
    overlayRef.current = wrapperRef.current;
    pr.lastReal = performance.now();

    const onMove = (e: PointerEvent) => {
      pr.inside = true;
      pr.lastReal = performance.now();
      // Touch-only devices: a touch interrupts the ghost but draws no bead.
      if (!finePointer) {
        setActive(false);
        return;
      }
      let px = e.clientX;
      let py = e.clientY;
      if (!global) {
        const rect = (target as HTMLElement).getBoundingClientRect();
        px -= rect.left;
        py -= rect.top;
      }
      mx.set(px);
      my.set(py);
      setActive(true);
      setHovering(!!(e.target as Element | null)?.closest("[data-cursor-target]"));
    };
    const onLeave = () => {
      pr.inside = false;
      pr.lastReal = performance.now();
      setActive(false);
      setHovering(false);
    };

    target.addEventListener("pointermove", onMove as EventListener);
    if (!global) {
      target.addEventListener("pointerleave", onLeave as EventListener);
      target.addEventListener("pointercancel", onLeave as EventListener);
    }
    if (hideNativeCursor && finePointer) cursorRoot.style.cursor = "none";

    return () => {
      target.removeEventListener("pointermove", onMove as EventListener);
      if (!global) {
        target.removeEventListener("pointerleave", onLeave as EventListener);
        target.removeEventListener("pointercancel", onLeave as EventListener);
      }
      if (hideNativeCursor && finePointer) cursorRoot.style.cursor = "";
      pr.inside = false;
    };
  }, [enabled, finePointer, global, hideNativeCursor, mx, my]);

  if (!enabled) return null;

  return (
    <div
      ref={wrapperRef}
      aria-hidden
      data-crucible="slipstream"
      className={cn(
        "pointer-events-none",
        global ? "fixed inset-0 z-[999]" : "absolute inset-0 z-50 overflow-hidden",
        className
      )}
    >
      <div
        ref={ghostLoopRef}
        className="absolute inset-0"
        // The ghost reads as a deliberate stand-in: slightly quieter than a real pointer.
        style={{ opacity: active ? 1 : ghosting ? 0.8 : 0, transition: "opacity 300ms ease" }}
      >
        {/* Trailing after-glow — lags the main bead, only visible in motion. */}
        <motion.div
          className="absolute top-0 left-0 rounded-full"
          style={{
            x: trailX,
            y: trailY,
            translateX: "-50%",
            translateY: "-50%",
            width: size * 0.9,
            height: size * 0.9,
            rotate: angle,
            scaleX: stretch,
            scaleY: squash,
            opacity: trailOpacity,
            background: `radial-gradient(circle, ${colors[1]} 0%, transparent 70%)`,
            filter: "blur(5px)",
          }}
        />
        {/* Main bead: soft halo + gradient core, stretched along travel. */}
        <motion.div
          className="absolute top-0 left-0"
          style={{
            x,
            y,
            translateX: "-50%",
            translateY: "-50%",
            width: size,
            height: size,
            rotate: angle,
            scaleX: stretch,
            scaleY: squash,
            scale: hoverScale,
          }}
        >
          <motion.div
            className="absolute rounded-full"
            style={{
              inset: -size * 0.55,
              background: `radial-gradient(circle, ${colors[0]} 0%, transparent 70%)`,
              opacity: haloOpacity,
              filter: "blur(6px)",
            }}
          />
          <motion.div
            className="absolute inset-0 rounded-full"
            style={{ background: coreBackground, filter: "blur(0.4px)" }}
          />
        </motion.div>
      </div>
    </div>
  );
}
```
