# Press — Animated Text Effect for React

> A variable-font pressure headline — the line behaves as a press bed under the cursor: glyph weight swells with a gaussian falloff while nearby letters rise and letter-spacing opens around the pressure point. Idle, the weight axis breathes almost imperceptibly. Pure rAF over font-variation-settings; real text in the DOM, static mid-weight under reduced motion; a ghost pressure point sweeps the line when untouched.

- Page: https://crucibleui.com/components/text/press
- Category: [text](https://crucibleui.com/components/text)
- Tier: free (full source)
- Engine: css

## Install

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

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

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

## Props (`PressProps`)

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `string` | — | The headline text. Server-renders as plain text; the effect attaches after hydration. |
| `minWeight?` | `number` | `320` | Resting font weight for untouched glyphs. |
| `maxWeight?` | `number` | `900` | Font weight a glyph reaches directly under the cursor. |
| `radius?` | `number` | `160` | Radius in px of the pressure field around the cursor. |
| `lift?` | `number` | `6` | How far, in px, glyphs near the cursor rise off the baseline. |
| `spread?` | `number` | `0.06` | How far, in em, letter-spacing opens around the pressure point. |
| `fontFamily?` | `string` | `variable system-ui stack` | Font stack. Must expose a variable `wght` axis for the swell to render; the default system stack is variable on every modern platform. |
| `paused?` | `boolean` | `false` | Freeze the pressure field (and the idle breathing). |
| `idle?` | `boolean` | `true` | Idle autoplay: when the cursor hasn't moved for 1.5s (or isn't over the page) and isn't pressing the line, a ghost pressure point sweeps slowly back and forth along the headline at reduced strength. A real pointer takes over instantly. Off under reduced motion / coarse pointers. |

Also accepts: `Omit<React.ComponentPropsWithoutRef<"span">, "children">`.

## Usage example

```tsx
import { Press } from "@/components/crucible/press";

export default function PressDemo() {
  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%)]"
      />
      <div className="relative z-10 w-full max-w-3xl px-6 text-center">
        <h2 className="whitespace-nowrap text-5xl tracking-tight text-white sm:text-6xl">
          <Press>Press into this</Press>
        </h2>
        <p className="mt-8 text-sm text-neutral-500">
          Run your cursor along the headline — letters swell, rise, and spread under the pressure.
        </p>
        <p className="mt-10 text-2xl text-neutral-400">
          <Press minWeight={100} maxWeight={700} radius={110} lift={3} spread={0.1}>
            A lighter touch works too
          </Press>
        </p>
        <p className="mt-3 text-[10px] font-medium uppercase tracking-[0.2em] text-neutral-600">
          Custom weight range
        </p>
      </div>
    </div>
  );
}
```

## Accessibility & performance

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

## Source (`press.tsx`)

```tsx
"use client";

import * as React from "react";

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

export interface PressProps extends Omit<React.ComponentPropsWithoutRef<"span">, "children"> {
  /** The headline text. Server-renders as plain text; the effect attaches after hydration. */
  children: string;
  /** Resting font weight for untouched glyphs. @default 320 */
  minWeight?: number;
  /** Font weight a glyph reaches directly under the cursor. @default 900 */
  maxWeight?: number;
  /** Radius in px of the pressure field around the cursor. @default 160 */
  radius?: number;
  /** How far, in px, glyphs near the cursor rise off the baseline. @default 6 */
  lift?: number;
  /** How far, in em, letter-spacing opens around the pressure point. @default 0.06 */
  spread?: number;
  /**
   * Font stack. Must expose a variable `wght` axis for the swell to render;
   * the default system stack is variable on every modern platform.
   * @default variable system-ui stack
   */
  fontFamily?: string;
  /** Freeze the pressure field (and the idle breathing). @default false */
  paused?: boolean;
  /**
   * Idle autoplay: when the cursor hasn't moved for 1.5s (or isn't over the
   * page) and isn't pressing the line, a ghost pressure point sweeps slowly
   * back and forth along the headline at reduced strength. A real pointer
   * takes over instantly. Off under reduced motion / coarse pointers. @default true
   */
  idle?: boolean;
}

const IDLE_MS = 1500;
/** Ghost pressure relative to a real cursor — deliberate, never full weight. */
const GHOST_GAIN = 0.7;

const DEFAULT_FONT =
  "system-ui, -apple-system, 'Segoe UI Variable Display', 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif";

/** True on touch-first devices, where cursor pressure is meaningless. SSR-safe: false on the server. */
function useCoarsePointer(): boolean {
  return React.useSyncExternalStore(
    subscribeCoarse,
    () => window.matchMedia("(pointer: coarse)").matches,
    () => false
  );
}

function subscribeCoarse(callback: () => void): () => void {
  const mql = window.matchMedia("(pointer: coarse)");
  mql.addEventListener("change", callback);
  return () => mql.removeEventListener("change", callback);
}

/**
 * Press — a variable-font pressure headline. The whole line behaves as a
 * press bed under the cursor: glyph weight swells with a gaussian proximity
 * falloff while nearby letters rise off the baseline and letter-spacing opens
 * around the pressure point, so the line visibly deforms as a field rather
 * than one glyph at a time. Idle, the weight axis breathes almost
 * imperceptibly so the headline reads as alive before first hover.
 *
 * Styles are written imperatively per frame (rAF lerp — no CSS transitions on
 * `font-variation-settings`, which are janky) and the loop pauses offscreen
 * and on hidden tabs. Server-side it renders the intact string, splitting
 * into per-glyph spans only after mount, so hydration always matches and
 * crawlers see real text. Coarse pointers and reduced motion get a static
 * mid-weight treatment. Untouched, a ghost pressure point sweeps the line
 * (`idle`) until the real cursor takes over.
 */
export function Press({
  children,
  minWeight = 320,
  maxWeight = 900,
  radius = 160,
  lift = 6,
  spread = 0.06,
  fontFamily = DEFAULT_FONT,
  paused = false,
  idle = true,
  className,
  style,
  ...props
}: PressProps) {
  const reducedMotion = useReducedMotion();
  const coarse = useCoarsePointer();
  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => setMounted(true), []);

  const isStatic = reducedMotion || coarse;
  const midWeight = (minWeight + maxWeight) / 2;

  // Split into words (trailing spaces attached) so line-wrapping matches the
  // plain server-rendered text, then into characters within each word.
  const wordData = React.useMemo(() => {
    let offset = 0;
    return children.split(/(?<=\s)/).map((word) => {
      const chars = Array.from(word);
      const start = offset;
      offset += chars.length;
      return { chars, start };
    });
  }, [children]);
  const totalChars = React.useMemo(
    () => wordData.reduce((sum, w) => sum + w.chars.length, 0),
    [wordData]
  );

  const charRefs = React.useRef<(HTMLSpanElement | null)[]>([]);
  const influences = React.useRef<number[]>([]);
  const pointer = React.useRef({ x: 0, y: 0, has: false });
  const lastMoveRef = React.useRef(0);
  const ghostRef = React.useRef({ presence: 0, t: 0, last: 0 });

  React.useEffect(() => {
    if (isStatic || !mounted) return;
    const onMove = (event: PointerEvent) => {
      if (event.pointerType === "touch") return;
      pointer.current.x = event.clientX;
      pointer.current.y = event.clientY;
      pointer.current.has = true;
      lastMoveRef.current = performance.now();
    };
    const onLeave = () => {
      pointer.current.has = false;
      lastMoveRef.current = performance.now();
    };
    lastMoveRef.current = performance.now();
    window.addEventListener("pointermove", onMove, { passive: true });
    document.documentElement.addEventListener("pointerleave", onLeave);
    return () => {
      window.removeEventListener("pointermove", onMove);
      document.documentElement.removeEventListener("pointerleave", onLeave);
    };
  }, [isStatic, mounted]);

  // Reset imperative state whenever the text or endpoints change.
  React.useEffect(() => {
    charRefs.current.length = totalChars;
    influences.current = new Array<number>(totalChars).fill(0);
    for (const el of charRefs.current) {
      if (!el) continue;
      el.style.fontVariationSettings = `'wght' ${minWeight}`;
      el.style.transform = "translateY(0px)";
      el.style.letterSpacing = "0em";
    }
  }, [totalChars, minWeight, maxWeight]);

  // The observed element, mirrored for the rAF tick (set after commit).
  const elRef = React.useRef<HTMLElement | null>(null);
  const wrapperRef = useVisibilityPause<HTMLSpanElement>(
    (elapsed) => {
      const spans = charRefs.current;
      const p = pointer.current;
      const sigma = radius / 2;
      const g = ghostRef.current;
      if (elapsed < g.last) g.last = elapsed;
      const dt = Math.min(elapsed - g.last, 0.05);
      g.last = elapsed;

      // Read pass first (rects), write pass second — one forced layout per frame.
      const targets = new Array<number>(spans.length).fill(0);
      const centers = new Array<number>(spans.length * 2).fill(0);
      let realPeak = 0;
      for (let i = 0; i < spans.length; i++) {
        const el = spans[i];
        if (!el) continue;
        const rect = el.getBoundingClientRect();
        const cx = rect.left + rect.width / 2;
        const cy = rect.top + rect.height / 2;
        centers[i * 2] = cx;
        centers[i * 2 + 1] = cy;
        if (p.has) {
          const dx = cx - p.x;
          const dy = cy - p.y;
          targets[i] = Math.exp(-(dx * dx + dy * dy) / (2 * sigma * sigma));
          if (targets[i] > realPeak) realPeak = targets[i];
        }
      }

      // Idle ghost: a pressure point sweeping the line, eased in and out. It
      // yields the moment the real cursor moves or presses on the text.
      const wantGhost =
        idle && realPeak < 0.05 && performance.now() - lastMoveRef.current > IDLE_MS;
      g.presence += ((wantGhost ? 1 : 0) - g.presence) * Math.min(1, dt * (wantGhost ? 1.2 : 6));
      if (g.presence > 0.005 && spans.length > 0) {
        g.t += dt;
        const wrap = elRef.current?.getBoundingClientRect();
        if (wrap) {
          // Eased ping-pong along the measured line width, with a gentle bob.
          const s = 0.5 - 0.5 * Math.cos(g.t * 0.55);
          const gx = wrap.left + wrap.width * (0.04 + 0.92 * s);
          const gy = wrap.top + wrap.height * (0.5 + 0.18 * Math.sin(g.t * 1.3));
          const k = g.presence * GHOST_GAIN;
          for (let i = 0; i < spans.length; i++) {
            const dx = centers[i * 2] - gx;
            const dy = centers[i * 2 + 1] - gy;
            const ghostT = Math.exp(-(dx * dx + dy * dy) / (2 * sigma * sigma)) * k;
            if (ghostT > (targets[i] ?? 0)) targets[i] = ghostT;
          }
        }
      }

      const weightSpan = maxWeight - minWeight;
      for (let i = 0; i < spans.length; i++) {
        const el = spans[i];
        if (!el) continue;
        const cur = influences.current[i] ?? 0;
        const next = cur + ((targets[i] ?? 0) - cur) * 0.16;
        influences.current[i] = next;
        // Idle breathing: a barely-perceptible traveling swell of the weight
        // axis, fading out wherever real cursor pressure takes over.
        const breath = 0.05 * (0.5 + 0.5 * Math.sin(elapsed * 0.9 + i * 0.42)) * (1 - next);
        const t = Math.min(1, next + breath);
        el.style.fontVariationSettings = `'wght' ${(minWeight + weightSpan * t).toFixed(1)}`;
        el.style.transform = `translateY(${(-lift * next).toFixed(2)}px)`;
        el.style.letterSpacing = next > 0.005 ? `${(spread * next).toFixed(4)}em` : "0em";
      }
    },
    { paused: paused || isStatic || !mounted }
  );

  React.useEffect(() => {
    elRef.current = wrapperRef.current;
  });

  const baseStyle: React.CSSProperties = {
    fontFamily,
    fontVariationSettings: `'wght' ${isStatic ? midWeight : minWeight}`,
    ...style,
  };

  // Server render + reduced motion / coarse pointer: the intact string, no
  // per-glyph spans — identical markup server and client, real text for
  // crawlers, static mid-weight when the effect can't run.
  if (!mounted || isStatic) {
    return (
      <span
        ref={wrapperRef}
        data-crucible="press"
        className={cn("inline-block", className)}
        style={baseStyle}
        {...props}
      >
        {children}
      </span>
    );
  }

  return (
    <span
      ref={wrapperRef}
      data-crucible="press"
      aria-label={children}
      className={cn("inline-block", className)}
      style={baseStyle}
      {...props}
    >
      {wordData.map((word, wi) => (
        <span key={wi} aria-hidden className="inline-block whitespace-pre">
          {word.chars.map((ch, ci) => {
            const index = word.start + ci;
            return (
              <span
                key={ci}
                ref={(el) => {
                  charRefs.current[index] = el;
                }}
                className="inline-block whitespace-pre will-change-transform"
                style={{ fontVariationSettings: `'wght' ${minWeight}` }}
              >
                {ch}
              </span>
            );
          })}
        </span>
      ))}
    </span>
  );
}
```
