Letter spin heading

Display text whose letters each turn a full circle in a left-to-right wave. Pick the axis (flip on x, turn on y, spin on z) and start it on hover, on keyboard focus, once on mount, when it scrolls into view, by bumping a play counter, or scrub it by hand from 0 to 1 for scroll-linked headings. Hover can come from any ancestor marked data-spin-group, so a whole link or card triggers it. Echo mode puts a coloured copy on each letter's back face so the wave flashes your accent mid-turn, and scatter gives each letter a small, stable offset for a looser ripple. Words never break mid-line, screen readers hear the text once rather than letter by letter, and reduced motion turns the spin off.

Animation & motionComponentTailwind v4

Source

"use client";

import { useEffect, useRef, useState, type CSSProperties, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "@/lib/utils";

type Tag = "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "span" | "a";

export type LetterSpinHeadingProps = Omit<HTMLAttributes<HTMLElement>, "children"> & {
  /** The text to show. Read once, as a whole, by screen readers. */
  text: string;
  /** The element to render. */
  as?: Tag;
  /** Link target when `as` is "a". */
  href?: string;
  /** "x" flips each letter top over bottom, "y" turns it like a page, "z" spins it flat. */
  axis?: "x" | "y" | "z";
  /** "hover" also listens on the nearest ancestor with data-spin-group, so a whole link or card can trigger it. */
  trigger?: "hover" | "mount" | "inView" | "manual";
  /** Increase this number to play the spin again, with any trigger. */
  play?: number;
  /** Delay between neighbouring letters, in milliseconds. */
  stagger?: number;
  /** Length of one letter's turn, in milliseconds. */
  duration?: number;
  /** Put a coloured copy of each letter on its back face, so letters flash the echo colour mid-turn. */
  echo?: boolean;
  /** Colour of the echo face. Any CSS colour; defaults to the first chart token. */
  echoColor?: string;
  /** Nudge each letter's start by a small stable offset, for a looser, hand-timed ripple. */
  scatter?: boolean;
  /** Scrub the wave by hand from 0 to 1, for example from scroll position. While set, triggers are ignored. */
  progress?: number;
};

const CSS = `
.chm-lsh-c{display:inline-block;position:relative;transform-style:preserve-3d;will-change:transform}
.chm-lsh-f{display:inline-block;backface-visibility:hidden}
.chm-lsh-b{position:absolute;inset:0;backface-visibility:hidden;color:var(--chm-lsh-echo)}
.chm-lsh[data-axis=x] .chm-lsh-b{transform:rotateX(180deg)}
.chm-lsh[data-axis=y] .chm-lsh-b{transform:rotateY(180deg)}
.chm-lsh[data-axis=z] .chm-lsh-b{display:none}
.chm-lsh[data-running] .chm-lsh-c{animation:var(--chm-lsh-name) var(--chm-lsh-d) cubic-bezier(.65,0,.25,1) calc(var(--i) * var(--chm-lsh-s) + var(--o, 0ms)) both}
.chm-lsh[data-running][data-axis=z][data-echo] .chm-lsh-c{animation-name:chm-lsh-z,chm-lsh-tint}
@keyframes chm-lsh-x{from{transform:rotateX(0)}to{transform:rotateX(360deg)}}
@keyframes chm-lsh-y{from{transform:rotateY(0)}to{transform:rotateY(360deg)}}
@keyframes chm-lsh-z{from{transform:rotate(0)}to{transform:rotate(360deg)}}
@keyframes chm-lsh-tint{0%,100%{color:inherit}45%,55%{color:var(--chm-lsh-echo)}}
@media (prefers-reduced-motion: reduce){.chm-lsh .chm-lsh-c{animation:none!important;transform:none!important;color:inherit!important}}
`;

const easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);

// A small, stable hash so scattered offsets are identical on the server, the client and every replay.
function jitter(seed: number) {
  let h = Math.imul(seed ^ 0x9e3779b9, 0x85ebca6b);
  h ^= h >>> 13;
  h = Math.imul(h, 0xc2b2ae35);
  h ^= h >>> 16;
  return (h >>> 0) / 4294967295 - 0.5;
}

export function LetterSpinHeading({
  text,
  as = "span",
  axis = "x",
  trigger = "hover",
  play,
  stagger = 28,
  duration = 600,
  echo = false,
  echoColor = "var(--chart-1)",
  scatter = false,
  progress,
  className,
  style,
  ...rest
}: LetterSpinHeadingProps) {
  const ref = useRef<HTMLElement>(null);
  const [run, setRun] = useState(0);
  const total = useRef(0);
  const busy = useRef(false);

  const letters = Array.from(text).filter((ch) => ch !== " ").length;
  total.current = duration + Math.max(0, letters - 1) * stagger + (scatter ? stagger : 0);

  // One spin at a time: hovering again mid-wave never restarts it from the first letter.
  const start = useRef(() => {});
  start.current = () => {
    if (busy.current) return;
    busy.current = true;
    setRun((value) => value + 1);
    window.setTimeout(() => {
      busy.current = false;
    }, total.current + 40);
  };

  useEffect(() => {
    if (play === undefined || play === 0) return;
    busy.current = false;
    start.current();
  }, [play]);

  useEffect(() => {
    const node = ref.current;
    if (!node) return;
    if (trigger === "mount") {
      start.current();
      return;
    }
    if (trigger === "inView") {
      if (typeof IntersectionObserver === "undefined") {
        start.current();
        return;
      }
      const observer = new IntersectionObserver(
        ([entry]) => {
          if (!entry?.isIntersecting) return;
          observer.disconnect();
          start.current();
        },
        { threshold: 0.5 },
      );
      observer.observe(node);
      return () => observer.disconnect();
    }
    if (trigger === "hover") {
      const host = (node.closest("[data-spin-group]") as HTMLElement | null) ?? node;
      const onEnter = () => start.current();
      const onFocus = (event: FocusEvent) => {
        const target = event.target as HTMLElement;
        if (target.matches?.(":focus-visible")) start.current();
      };
      host.addEventListener("pointerenter", onEnter);
      host.addEventListener("focusin", onFocus);
      return () => {
        host.removeEventListener("pointerenter", onEnter);
        host.removeEventListener("focusin", onFocus);
      };
    }
  }, [trigger]);

  const scrub = progress !== undefined;
  const scrubAt = scrub ? Math.max(0, Math.min(1, progress)) * total.current : 0;
  const rotate = axis === "x" ? "rotateX" : axis === "y" ? "rotateY" : "rotate";

  let index = 0;
  const words = text.split(/(\s+)/).map((part, w) => {
    if (/^\s+$/.test(part)) return " ";
    return (
      <span key={w} className="inline-block whitespace-nowrap [perspective:600px]">
        {Array.from(part).map((ch, c) => {
          const i = index++;
          const offset = scatter ? Math.round(jitter(i + 1) * stagger * 1.6) : 0;
          const style: CSSProperties & Record<string, unknown> = { "--i": i, "--o": `${offset}ms` };
          if (scrub) {
            const t = easeInOut(Math.max(0, Math.min(1, (scrubAt - i * stagger - offset) / duration)));
            style.transform = `${rotate}(${Math.round(t * 3600) / 10}deg)`;
            if (echo && axis === "z" && t > 0.3 && t < 0.7) style.color = echoColor;
          }
          return (
            <span key={`${run}-${c}`} className="chm-lsh-c" style={style}>
              <span className="chm-lsh-f">{ch}</span>
              {echo && <span className="chm-lsh-b">{ch}</span>}
            </span>
          );
        })}
      </span>
    );
  });

  const Comp = as as "span";
  const content: ReactNode = (
    <>
      <style href="chm-letter-spin" precedence="default">{CSS}</style>
      <span className="sr-only">{text}</span>
      <span aria-hidden="true">{words}</span>
    </>
  );

  return (
    <Comp
      ref={ref as React.Ref<HTMLSpanElement>}
      data-axis={axis}
      data-echo={echo ? "" : undefined}
      data-running={run > 0 && !scrub ? "" : undefined}
      className={cn("chm-lsh", className)}
      style={{
        "--chm-lsh-name": `chm-lsh-${axis}`,
        "--chm-lsh-d": `${duration}ms`,
        "--chm-lsh-s": `${stagger}ms`,
        "--chm-lsh-echo": echoColor,
        ...style,
      } as CSSProperties}
      {...rest}
    >
      {content}
    </Comp>
  );
}