Decode text
Text that resolves out of random glyphs into the real string. Each character cycles through a glyph set (letters, hex, binary, symbols or your own) and locks left to right, from the centre out or in random order, at a fixed tick so the pace is the same on any screen. Give it a list of strings and it cycles through them, decoding only the characters that change, with an optional block caret riding the resolve front. It can start on mount, on scroll into view or on hover and focus, keeps its width steady by reserving the longest string, gives screen readers the plain text without live announcements, and shows the final text at once when reduced motion is on.
Source
"use client";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
const CHARSETS = {
alpha: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
hex: "0123456789abcdef",
binary: "01",
symbols: "!<>-_\\/[]{}=+*^?#%&$@~",
} as const;
export type DecodeTextProps = {
/** One string to resolve. Use `texts` instead to cycle through several. */
text?: string;
/** Several strings: each one decodes from the last, changing only the characters that differ. */
texts?: string[];
/** Time each string stays resolved before the next one starts, in milliseconds. */
interval?: number;
/** Which characters lock first. */
order?: "ltr" | "center" | "random";
/** Glyphs used while scrambling: a preset name or your own string. */
charset?: keyof typeof CHARSETS | (string & {});
/** Milliseconds per tick. Lower is faster; the pace is the same at any frame rate. */
speed?: number;
/** Ticks between neighbouring characters locking. */
spread?: number;
/** "hover" waits for pointer or keyboard focus and shows a scrambled placeholder until then. */
trigger?: "mount" | "inView" | "hover";
/** A solid block that rides the resolve front. */
caret?: boolean;
/** Use a monospaced face so the line never shifts while glyphs change. */
mono?: boolean;
/** Called each time a string finishes resolving. */
onDone?: (text: string) => void;
className?: string;
};
type Cell = { ch: string; locked: boolean; front?: boolean };
function seeded(seed: number) {
let s = seed >>> 0 || 1;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 4294967296;
};
}
function hash(value: string) {
let h = 2166136261;
for (let i = 0; i < value.length; i++) h = Math.imul(h ^ value.charCodeAt(i), 16777619);
return h >>> 0;
}
function prefersReducedMotion() {
return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
}
const settled = (value: string): Cell[] => Array.from(value).map((ch) => ({ ch, locked: true }));
function scrambled(value: string, glyphs: string): Cell[] {
const rand = seeded(hash(value));
return Array.from(value).map((ch) => (ch === " " ? { ch, locked: true } : { ch: glyphs[Math.floor(rand() * glyphs.length)] ?? ch, locked: false }));
}
export function DecodeText({
text,
texts,
interval = 2600,
order = "ltr",
charset = "alpha",
speed = 34,
spread = 1,
trigger = "mount",
caret = false,
mono = true,
onDone,
className,
}: DecodeTextProps) {
const list = texts?.length ? texts : [text ?? ""];
const listKey = list.join("\u0000");
const glyphs = charset in CHARSETS ? CHARSETS[charset as keyof typeof CHARSETS] : charset || CHARSETS.alpha;
const ref = useRef<HTMLSpanElement>(null);
const [index, setIndex] = useState(0);
const [started, setStarted] = useState(trigger === "mount");
const [cells, setCells] = useState<Cell[]>(() => scrambled(list[0]!, glyphs));
const [done, setDone] = useState(false);
const shown = useRef(trigger === "mount" ? "" : "\u0001");
const doneRef = useRef(onDone);
doneRef.current = onDone;
const target = list[index % list.length] ?? "";
// Waiting for a trigger.
useEffect(() => {
if (started) return;
const node = ref.current;
if (!node) return;
const go = () => setStarted(true);
if (trigger === "hover") {
node.addEventListener("pointerenter", go);
node.addEventListener("focus", go);
return () => {
node.removeEventListener("pointerenter", go);
node.removeEventListener("focus", go);
};
}
if (typeof IntersectionObserver === "undefined") return go();
const observer = new IntersectionObserver(([entry]) => entry?.isIntersecting && go(), { threshold: 0.5 });
observer.observe(node);
return () => observer.disconnect();
}, [started, trigger]);
// Resolve from whatever is on screen to the current target.
useEffect(() => {
if (!started) return;
const from = shown.current;
const to = target;
if (prefersReducedMotion()) {
setCells(settled(to));
shown.current = to;
setDone(true);
doneRef.current?.(to);
return;
}
const length = Math.max(from.length, to.length);
const goal = to.padEnd(length, " ");
const start = from === "\u0001" ? "" : from.padEnd(length, " ");
const positions = Array.from({ length }, (_, i) => i).filter((i) => start[i] !== goal[i]);
// Rank each changing position by the chosen order; rank decides when it locks.
const ranked = [...positions];
if (order === "center") {
const mid = (to.length - 1) / 2;
ranked.sort((a, b) => Math.abs(a - mid) - Math.abs(b - mid));
} else if (order === "random") {
const rand = seeded(hash(to + from));
for (let i = ranked.length - 1; i > 0; i--) {
const j = Math.floor(rand() * (i + 1));
[ranked[i], ranked[j]] = [ranked[j]!, ranked[i]!];
}
}
const lockAt = new Map<number, number>();
ranked.forEach((pos, rank) => lockAt.set(pos, 3 + Math.round(rank * spread)));
setDone(false);
let tick = 0;
let carry = 0;
let last = performance.now();
let frame = 0;
let fallback: ReturnType<typeof setTimeout> | undefined;
let finished = false;
const paint = () => {
let front = Infinity;
for (const pos of ranked) if ((lockAt.get(pos) ?? 0) > tick) front = Math.min(front, lockAt.get(pos)!);
const next: Cell[] = Array.from(goal, (ch, i) => {
const at = lockAt.get(i);
if (at === undefined || at <= tick) return { ch, locked: true };
if (ch === " " && (start[i] ?? " ") === " " && tick < at - 2) return { ch: " ", locked: false };
return { ch: glyphs[Math.floor(Math.random() * glyphs.length)] ?? ch, locked: false, front: at === front };
});
setCells(next);
return front === Infinity;
};
const step = () => {
cancelAnimationFrame(frame);
clearTimeout(fallback);
const now = performance.now();
carry += Math.min(now - last, 250);
last = now;
let changed = false;
while (carry >= speed) {
carry -= speed;
tick++;
changed = true;
}
if (changed && paint()) {
finished = true;
shown.current = to;
setCells(settled(to));
setDone(true);
doneRef.current?.(to);
return;
}
frame = requestAnimationFrame(step);
// Keeps the decode moving where frames are throttled, such as background tabs.
fallback = setTimeout(step, 120);
};
paint();
frame = requestAnimationFrame(step);
fallback = setTimeout(step, 120);
return () => {
cancelAnimationFrame(frame);
clearTimeout(fallback);
if (!finished) shown.current = to;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [started, target, order, speed, spread, glyphs]);
// Cycle to the next string after a pause.
useEffect(() => {
if (!done || list.length < 2) return;
const id = window.setTimeout(() => setIndex((value) => value + 1), interval);
return () => window.clearTimeout(id);
}, [done, interval, list.length]);
useEffect(() => {
setIndex(0);
}, [listKey]);
return (
<span
ref={ref}
tabIndex={trigger === "hover" && !started ? 0 : undefined}
className={cn(
"relative inline-grid align-baseline",
mono && "font-mono tabular-nums",
trigger === "hover" && "rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
className,
)}
>
<span className="sr-only">{started ? target : list[0]}</span>
{/* Reserves the widest string so the layout never moves. */}
{list.map((value, i) => (
<span key={i} aria-hidden="true" className="invisible col-start-1 row-start-1 whitespace-pre">
{value}
{caret ? " " : ""}
</span>
))}
<span aria-hidden="true" className="col-start-1 row-start-1 whitespace-pre">
{cells.map((cell, i) => (
<span
key={i}
className={cn(
cell.locked ? "text-current" : "text-muted-foreground",
caret && cell.front && "bg-foreground text-background",
)}
>
{cell.ch}
</span>
))}
{caret && done && (
<span className="ml-[0.08em] inline-block h-[0.95em] w-[0.5em] translate-y-[0.12em] bg-current align-baseline motion-safe:animate-pulse" />
)}
</span>
</span>
);
}
