Text Cursor

Trail of text glyphs that follows the pointer (or a simulated one) and fades out when it stops.

pnpm dlx shadcn@latest add @leo/text-cursor

Props

NameTypeDefaultDescription
autoPlayboolean | undefinedfalseSimulates a pointer travelling an ellipse; pauses while a real pointer is inside the container and resumes when it leaves. Off by default.
autoPlaySpeednumber | undefined5Angular speed of the simulated pointer, in radians per second.
classNamestring | undefined-
exitDurationnumber | undefined0.5
followMouseDirectionboolean | undefinedtrue
maxPointsnumber | undefined5
randomFloatboolean | undefinedtrue
removalIntervalnumber | undefined30
spacingnumber | undefined100
textstring | undefined⚛️

Dependencies

  • motion@^12.23.12

Source

"use client";

import { AnimatePresence, motion } from "motion/react";
import type React from "react";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";

export interface TextCursorProps {
  text?: string;
  spacing?: number;
  followMouseDirection?: boolean;
  randomFloat?: boolean;
  exitDuration?: number;
  removalInterval?: number;
  maxPoints?: number;
  /** Simulates a pointer travelling an ellipse; pauses while a real pointer is inside the container and resumes when it leaves. Off by default. */
  autoPlay?: boolean;
  /** Angular speed of the simulated pointer, in radians per second. */
  autoPlaySpeed?: number;
  className?: string;
}

// Trail items are dropped one by one once the pointer has been still for this long.
const IDLE_REMOVAL_DELAY_MS = 100;

// Time between simulated pointer samples while autoplaying. Deliberately not a divisor-friendly value: a
// step that is a multiple of the 16 ms frame makes a sample land exactly on a frame, and a one-frame timing
// jitter then adds or drops the newest point.
const AUTO_PLAY_STEP_MS = 109;

interface TrailItem {
  id: number;
  x: number;
  y: number;
  angle: number;
  randomX?: number;
  randomY?: number;
  randomRotate?: number;
}

const TextCursor: React.FC<TextCursorProps> = ({
  text = "⚛️",
  spacing = 100,
  followMouseDirection = true,
  randomFloat = true,
  exitDuration = 0.5,
  removalInterval = 30,
  maxPoints = 5,
  autoPlay = false,
  autoPlaySpeed = 5,
  className,
}) => {
  const [trail, setTrail] = useState<TrailItem[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);
  const lastMoveTimeRef = useRef<number>(Date.now());
  const idCounter = useRef<number>(0);
  const pointerInsideRef = useRef(false);

  const createItem = (x: number, y: number, angle: number): TrailItem => ({
    id: idCounter.current++,
    x,
    y,
    angle,
    ...(randomFloat && {
      randomX: Math.random() * 10 - 5,
      randomY: Math.random() * 10 - 5,
      randomRotate: Math.random() * 10 - 5,
    }),
  });

  // Autoplay drops a point at an exact path position instead of walking `spacing` steps from the previous
  // point, so the visible trail depends only on the clock, not on when the effect started.
  const pushPoint = (x: number, y: number, angle: number) => {
    setTrail((prev) =>
      [...prev, createItem(x, y, followMouseDirection ? angle : 0)].slice(-maxPoints),
    );
    lastMoveTimeRef.current = Date.now();
  };

  const addPoint = (mouseX: number, mouseY: number) => {
    setTrail((prev) => {
      let newTrail = [...prev];
      if (newTrail.length === 0) {
        newTrail.push(createItem(mouseX, mouseY, 0));
      } else {
        const last = newTrail[newTrail.length - 1];
        const dx = mouseX - last.x;
        const dy = mouseY - last.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        if (distance >= spacing) {
          let rawAngle = (Math.atan2(dy, dx) * 180) / Math.PI;

          rawAngle = ((rawAngle + 180) % 360) - 180;

          const computedAngle = followMouseDirection ? rawAngle : 0;
          const steps = Math.floor(distance / spacing);
          for (let i = 1; i <= steps; i++) {
            const t = (spacing * i) / distance;
            const newX = last.x + dx * t;
            const newY = last.y + dy * t;
            newTrail.push(createItem(newX, newY, computedAngle));
          }
        }
      }
      if (newTrail.length > maxPoints) {
        newTrail = newTrail.slice(newTrail.length - maxPoints);
      }
      return newTrail;
    });
    lastMoveTimeRef.current = Date.now();
  };

  // The listeners are attached once; they call through this ref so they always see the latest props.
  const addPointRef = useRef(addPoint);
  addPointRef.current = addPoint;
  const pushPointRef = useRef(pushPoint);
  pushPointRef.current = pushPoint;

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleMouseMove = (e: MouseEvent) => {
      const rect = container.getBoundingClientRect();
      addPointRef.current(e.clientX - rect.left, e.clientY - rect.top);
    };
    const handleMouseEnter = () => {
      pointerInsideRef.current = true;
    };
    const handleMouseLeave = () => {
      pointerInsideRef.current = false;
    };

    container.addEventListener("mousemove", handleMouseMove);
    container.addEventListener("mouseenter", handleMouseEnter);
    container.addEventListener("mouseleave", handleMouseLeave);
    return () => {
      container.removeEventListener("mousemove", handleMouseMove);
      container.removeEventListener("mouseenter", handleMouseEnter);
      container.removeEventListener("mouseleave", handleMouseLeave);
    };
  }, []);

  useEffect(() => {
    if (!autoPlay) return;
    let frame = 0;
    let lastSlot = Number.NaN;

    // Points sit on a fixed time grid and their position is a pure function of the grid time, so a frozen
    // clock yields the same trail whenever the effect happened to start.
    const tick = (now: number) => {
      const container = containerRef.current;
      if (container && !pointerInsideRef.current) {
        const slot = Math.floor(now / AUTO_PLAY_STEP_MS);
        if (slot !== lastSlot) {
          lastSlot = slot;
          const angle = ((slot * AUTO_PLAY_STEP_MS) / 1000) * autoPlaySpeed;
          const { width, height } = container.getBoundingClientRect();
          const rx = width * 0.3;
          const ry = height * 0.3;
          pushPointRef.current(
            width / 2 + Math.cos(angle) * rx,
            height / 2 + Math.sin(angle) * ry,
            (Math.atan2(Math.cos(angle) * ry, -Math.sin(angle) * rx) * 180) / Math.PI,
          );
        }
        lastMoveTimeRef.current = Date.now();
      }
      frame = requestAnimationFrame(tick);
    };
    frame = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(frame);
  }, [autoPlay, autoPlaySpeed]);

  useEffect(() => {
    const interval = setInterval(() => {
      if (Date.now() - lastMoveTimeRef.current > IDLE_REMOVAL_DELAY_MS) {
        setTrail((prev) => (prev.length > 0 ? prev.slice(1) : prev));
      }
    }, removalInterval);
    return () => clearInterval(interval);
  }, [removalInterval]);

  return (
    <div ref={containerRef} className={cn("relative h-full w-full", className)}>
      <div className="absolute inset-0 pointer-events-none">
        <AnimatePresence>
          {trail.map((item) => (
            <motion.div
              key={item.id}
              initial={{ opacity: 0, scale: 1, rotate: item.angle }}
              animate={{
                opacity: 1,
                scale: 1,
                x: randomFloat ? [0, item.randomX || 0, 0] : 0,
                y: randomFloat ? [0, item.randomY || 0, 0] : 0,
                rotate: randomFloat
                  ? [item.angle, item.angle + (item.randomRotate || 0), item.angle]
                  : item.angle,
              }}
              exit={{ opacity: 0, scale: 0 }}
              transition={{
                opacity: { duration: exitDuration, ease: "easeOut" },

                ...(randomFloat && {
                  x: {
                    duration: 2,
                    ease: "easeInOut",
                    repeat: Infinity,
                    repeatType: "mirror",
                  },
                  y: {
                    duration: 2,
                    ease: "easeInOut",
                    repeat: Infinity,
                    repeatType: "mirror",
                  },
                  rotate: {
                    duration: 2,
                    ease: "easeInOut",
                    repeat: Infinity,
                    repeatType: "mirror",
                  },
                }),
              }}
              className="absolute select-none whitespace-nowrap text-3xl"
              style={{ left: item.x, top: item.y }}
            >
              {text}
            </motion.div>
          ))}
        </AnimatePresence>
      </div>
    </div>
  );
};

export { TextCursor };
export default TextCursor;