0

Component

Scramble text

Text that decodes itself from random glyphs, left to right.

Hover me to decodeCosverse AIship it, then tell the truth

Usage

<ScrambleText text="Cosverse AI" trigger="hover" />

Source

Copy both files into your project. The component has no dependencies beyond React.

"use client";

import { useEffect, useRef, useState } from "react";
import styles from "./scramble-text.module.css";

const GLYPHS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#%&*+=/<>";

type ScrambleTextProps = {
  text: string;
  /** When to decode: on hover and focus, or once when it mounts. */
  trigger?: "hover" | "mount";
  /** Milliseconds from first glyph to fully resolved. */
  duration?: number;
  className?: string;
};

export function ScrambleText({ text, trigger = "hover", duration = 700, className }: ScrambleTextProps) {
  const [shown, setShown] = useState(text);
  const frame = useRef(0);

  function run() {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    cancelAnimationFrame(frame.current);
    const start = performance.now();

    const step = (now: number) => {
      const t = Math.min(1, (now - start) / duration);
      const settled = Math.floor(t * text.length);
      setShown(
        text
          .split("")
          .map((char, index) =>
            index < settled || char === " " ? char : GLYPHS[Math.floor(Math.random() * GLYPHS.length)],
          )
          .join(""),
      );
      if (t < 1) frame.current = requestAnimationFrame(step);
    };
    frame.current = requestAnimationFrame(step);
  }

  useEffect(() => {
    setShown(text);
    if (trigger === "mount") run();
    return () => cancelAnimationFrame(frame.current);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [text, trigger]);

  return (
    <span
      className={[styles.scramble, className].filter(Boolean).join(" ")}
      onPointerEnter={trigger === "hover" ? run : undefined}
      onFocus={trigger === "hover" ? run : undefined}
    >
      {/* The real text sets the width and is what screen readers hear; the scramble sits on top. */}
      <span className={styles.ghost}>{text}</span>
      <span className={styles.live} aria-hidden="true">
        {shown}
      </span>
    </span>
  );
}