{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "letter-reveal",
  "type": "registry:ui",
  "title": "Letter Reveal",
  "description": "Headline type that writes itself in on scroll, one letter at a time, with a synthesised tick as each lands. Letters take no space until they arrive, so a centred line opens outward from the middle. Arrival order, raggedness, spacing behaviour and the tick are all tunable, plus an onReveal hook per letter.",
  "dependencies": [
    "motion"
  ],
  "files": [
    {
      "path": "registry/crafterui/ui/letter-reveal.tsx",
      "type": "registry:ui",
      "content": "\"use client\"\n\n// Headline type that writes itself in as you scroll, one letter at a time, with\n// a tick as each one lands.\n//\n// Layout: a letter that has not arrived yet takes up no room, so a centred line\n// opens outward from the middle instead of fading up in place. Getting width to\n// animate from zero to \"however wide this glyph happens to be\" normally means\n// measuring every character and re-measuring on resize. It does not have to - an\n// inline-grid whose one column runs 0fr -> 1fr collapses and restores its\n// child's natural width by itself, so the type stays sized in container units\n// and nothing needs measuring. Set `space=\"reserve\"` for the other behaviour,\n// where letters hold their final position and only fade.\n//\n// Timing: each letter owns one slice of scroll and nothing overlaps into the\n// next, so only ever one letter is arriving. By default `snap` is 0, which makes\n// that arrival a hard step - the glyph and the space it needs appear together in\n// a single frame, with no interpolation between them at all.\n//\n// That is deliberately mechanical. A centred line has to shift sideways by half\n// a letter every time one lands, and easing the width in hides that shift; a\n// hard step lets you feel it, which is what makes the thing read as typing on a\n// machine rather than text dissolving up. Raise `snap` to ease each letter in\n// over that fraction of its slice instead - at 1 the slices touch and it becomes\n// a continuous crossfade.\n//\n// Sound is synthesised, not a file: a registry component that shipped an .mp3\n// would make the consumer copy the asset too, and this is smaller and tunable.\n//\n// It is a filtered noise burst, deliberately not a tone. A pitched oscillator\n// per letter turns thirty-odd letters into a melody, and a melody you did not\n// ask for and cannot skip is a ringtone. Real interface ticks are broadband and\n// almost over before you place them: white noise through a bandpass, ~35ms, with\n// the centre frequency knocked about a little each hit so a run of them does not\n// sound looped.\n//\n// It starts muted behind a toggle for two reasons - nothing should make noise at\n// someone unasked, and browsers refuse to start an AudioContext until a real\n// gesture. Scrolling is not one in Chrome, so the toggle press doubles as the\n// unlock.\nimport * as React from \"react\"\nimport { Volume2, VolumeX } from \"lucide-react\"\nimport {\n  motion,\n  useMotionValueEvent,\n  useScroll,\n  useTransform,\n  type MotionValue,\n} from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport type LetterRevealOrder = \"forward\" | \"backward\" | \"center\" | \"random\"\n\nexport interface LetterRevealSound {\n  /** Peak gain of a single tick, 0-1. @default 0.11 */\n  volume?: number\n  /** Centre of the bandpass, in Hz. Lower is duller and woodier. @default 1900 */\n  tone?: number\n  /** How far the centre wanders per hit, 0-1, so repeats do not sound looped. @default 0.22 */\n  spread?: number\n  /** Tick length in seconds. @default 0.045 */\n  decay?: number\n  /** Weight under the click, 0-1. 0 is a dry tap. @default 0.35 */\n  body?: number\n  /** Shortest gap between two ticks in ms - a fast flick must not machine-gun. @default 45 */\n  throttle?: number\n}\n\nexport interface LetterRevealProps {\n  /** Lines of the headline. Each fills across the same stretch of scroll. */\n  lines: string[]\n  /** Element to render the headline as. @default \"h2\" */\n  as?: \"h1\" | \"h2\" | \"h3\" | \"p\" | \"div\"\n  /** Whether a letter waits its turn taking no space, or holds its place and fades. @default \"grow\" */\n  space?: \"grow\" | \"reserve\"\n  /** Which end letters arrive from. @default \"forward\" */\n  order?: LetterRevealOrder\n  /** How far through the scroll the last letter lands. @default 0.8 */\n  finish?: number\n  /** Fraction of a letter's slice spent arriving. 0 is a hard step, 1 a crossfade. @default 0 */\n  snap?: number\n  /** How ragged the arriving edge is, as a fraction of the scroll. 0 keeps strict order. @default 0 */\n  jitter?: number\n  /** Height of the scroll track, in multiples of the panel. @default 300 */\n  track?: number\n  /** Tick config, or false for a silent component with no toggle. @default true */\n  sound?: boolean | LetterRevealSound\n  /** Called as each letter lands - hook up your own audio, haptics or analytics. @default undefined */\n  onReveal?: (letter: { char: string; line: number; index: number }) => void\n  /** Caption pinned under the type; pass `null` to hide it. @default \"Scroll\" */\n  label?: string | null\n  /** Extra classes on the root surface. @default undefined */\n  className?: string\n  /** Extra classes on the headline. @default undefined */\n  textClassName?: string\n}\n\n// Deterministic stand-in for Math.random: the same value on the server and the\n// client, so the arrival order never differs between the two renders.\nfunction noise(i: number) {\n  const x = Math.sin((i + 1) * 12.9898) * 43758.5453\n  return x - Math.floor(x)\n}\n\nconst clamp = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v)\n\n// Recovers the amplitude the bandpass costs, so `volume` means peak amplitude.\nconst BANDPASS_MAKEUP = 2.1\n\n// Most ticks one scroll event may fire. Past this it stops reading as typing.\nconst MAX_BURST = 6\n\n/** Position in the queue for each letter of a line, by arrival order. */\nfunction ranks(n: number, order: LetterRevealOrder, seed: number): number[] {\n  const idx = Array.from({ length: n }, (_, i) => i)\n  if (order === \"forward\") return idx\n  if (order === \"backward\") return idx.map((i) => n - 1 - i)\n\n  const by =\n    order === \"center\"\n      ? (i: number) => Math.abs(i - (n - 1) / 2)\n      : (i: number) => noise(i + seed)\n\n  const queue = [...idx].sort((a, b) => by(a) - by(b))\n  const out = new Array<number>(n)\n  queue.forEach((letter, place) => {\n    out[letter] = place\n  })\n  return out\n}\n\ntype Planned = {\n  char: string\n  line: number\n  index: number\n  from: number\n  to: number\n  audible: boolean\n}\n\nfunction Letter({\n  char,\n  from,\n  to,\n  snap,\n  space,\n  progress,\n}: {\n  char: string\n  from: number\n  to: number\n  snap: number\n  space: \"grow\" | \"reserve\"\n  progress: MotionValue<number>\n}) {\n  const p = useTransform(progress, (v) => clamp((v - from) / (to - from)))\n\n  // One value drives the glyph and the room it takes, so they land together. At\n  // snap 0 it is a step function - there is no in-between frame to catch.\n  const enter = 1 - clamp(snap)\n  const landed = useTransform(p, (v) =>\n    snap <= 0 ? (v >= 1 ? 1 : 0) : clamp((v - enter) / (1 - enter))\n  )\n\n  const column = useTransform(landed, (v) =>\n    space === \"grow\" ? `${v}fr` : \"1fr\"\n  )\n\n  return (\n    <motion.span\n      aria-hidden=\"true\"\n      style={{ gridTemplateColumns: column }}\n      className=\"inline-grid align-baseline\"\n    >\n      <motion.span style={{ opacity: landed }} className=\"min-w-0 overflow-hidden\">\n        {char}\n      </motion.span>\n    </motion.span>\n  )\n}\n\nexport function LetterReveal({\n  lines,\n  as: Tag = \"h2\",\n  space = \"grow\",\n  order = \"forward\",\n  finish = 0.8,\n  snap = 0,\n  jitter = 0,\n  track = 300,\n  sound = true,\n  onReveal,\n  label = \"Scroll\",\n  className,\n  textClassName,\n}: LetterRevealProps) {\n  const scrollRef = React.useRef<HTMLDivElement>(null)\n  const { scrollYProgress } = useScroll({ container: scrollRef })\n\n  const tone: Required<LetterRevealSound> = {\n    volume: 0.11,\n    tone: 1900,\n    spread: 0.22,\n    decay: 0.045,\n    body: 0.35,\n    throttle: 45,\n    ...(typeof sound === \"object\" ? sound : {}),\n  }\n\n  const [muted, setMuted] = React.useState(true)\n  const audio = React.useRef<{\n    ctx: AudioContext\n    noise: AudioBuffer\n    out: GainNode\n  } | null>(null)\n  const lastTick = React.useRef(0)\n\n  // One flat plan drives both the render and the tick, so a letter can never\n  // sound at a different moment than it appears.\n  const plan = React.useMemo<Planned[]>(() => {\n    const out: Planned[] = []\n    lines.forEach((line, l) => {\n      const chars = [...line]\n      const n = Math.max(chars.length, 1)\n      const place = ranks(n, order, l * 97)\n      // One slice each, butted end to end. Any overlap here and two letters are\n      // always mid-flight, which is what turns typing into a dissolve.\n      const slice = finish / n\n      chars.forEach((char, i) => {\n        const from = clamp(place[i] * slice + (noise(i + l * 97) - 0.5) * jitter)\n        out.push({\n          char,\n          line: l,\n          index: i,\n          from,\n          to: from + slice,\n          audible: char.trim().length > 0,\n        })\n      })\n    })\n    return out\n  }, [lines, order, finish, jitter])\n\n  React.useEffect(() => {\n    return () => {\n      void audio.current?.ctx.close()\n      audio.current = null\n    }\n  }, [])\n\n  function tick(delay = 0) {\n    const rig = audio.current\n    if (!rig || rig.ctx.state !== \"running\") return\n\n    const { ctx, noise: buffer, out } = rig\n    const now = ctx.currentTime + delay\n\n    const src = ctx.createBufferSource()\n    src.buffer = buffer\n\n    const band = ctx.createBiquadFilter()\n    band.type = \"bandpass\"\n    band.frequency.value = tone.tone * (1 + (Math.random() - 0.5) * tone.spread)\n    band.Q.value = 0.9\n\n    // Takes the fizz off the top of the noise; without it the tick reads as a\n    // hiss rather than as a tap.\n    const soften = ctx.createBiquadFilter()\n    soften.type = \"lowpass\"\n    soften.frequency.value = 7000\n\n    // A bandpass throws away most of the noise's energy, so without makeup a\n    // `volume` of 0.11 actually peaks around 0.05 and the knob lies about what\n    // it does. This puts peak amplitude back in step with the number asked for.\n    const gain = ctx.createGain()\n    gain.gain.setValueAtTime(tone.volume * BANDPASS_MAKEUP, now)\n    gain.gain.exponentialRampToValueAtTime(0.0001, now + tone.decay)\n\n    src.connect(band)\n    band.connect(soften)\n    soften.connect(gain)\n    gain.connect(out)\n    src.start(now)\n    src.stop(now + tone.decay + 0.02)\n\n    if (tone.body <= 0) return\n    // A little low weight under the click so it lands rather than just hisses.\n    const thud = ctx.createOscillator()\n    const thudGain = ctx.createGain()\n    thud.type = \"sine\"\n    thud.frequency.setValueAtTime(190, now)\n    thud.frequency.exponentialRampToValueAtTime(120, now + tone.decay * 1.6)\n    thudGain.gain.setValueAtTime(tone.volume * tone.body, now)\n    thudGain.gain.exponentialRampToValueAtTime(0.0001, now + tone.decay * 1.6)\n    thud.connect(thudGain)\n    thudGain.connect(out)\n    thud.start(now)\n    thud.stop(now + tone.decay * 1.6 + 0.02)\n  }\n\n  // Letters already landed. Scrubbing back up rewinds it without sounding, so\n  // dragging the scrollbar to and fro cannot retrigger the same letter.\n  const landed = React.useRef(0)\n\n  useMotionValueEvent(scrollYProgress, \"change\", (v) => {\n    let count = 0\n    for (const letter of plan) if (v >= letter.to) count++\n    if (count === landed.current) return\n\n    if (count < landed.current) {\n      landed.current = count\n      return\n    }\n\n    const fresh = plan.slice(landed.current, count)\n    landed.current = count\n\n    for (const letter of fresh) onReveal?.(letter)\n\n    const audible = fresh.reduce((n, l) => n + (l.audible ? 1 : 0), 0)\n    if (muted || audible === 0) return\n\n    const now = performance.now()\n    if (now - lastTick.current < tone.throttle) return\n\n    // One scroll event can land several letters. Fire them as a short run of\n    // separate ticks rather than a single click, so a quick flick still sounds\n    // like typing - capped, because a whole line at once would machine-gun.\n    const burst = Math.min(audible, MAX_BURST)\n    for (let i = 0; i < burst; i++) tick((i * tone.throttle) / 1000)\n    lastTick.current = now + (burst - 1) * tone.throttle\n  })\n\n  async function toggleSound() {\n    if (!muted) {\n      setMuted(true)\n      return\n    }\n    // The click is the gesture the AudioContext needs; a scroll is not one.\n    try {\n      if (!audio.current) {\n        const ctx = new AudioContext()\n        // One short buffer of white noise, reused by every tick.\n        const frames = Math.floor(ctx.sampleRate * 0.08)\n        const noise = ctx.createBuffer(1, frames, ctx.sampleRate)\n        const channel = noise.getChannelData(0)\n        for (let i = 0; i < frames; i++) channel[i] = Math.random() * 2 - 1\n        const out = ctx.createGain()\n        out.gain.value = 0.9\n        out.connect(ctx.destination)\n        audio.current = { ctx, noise, out }\n      }\n      if (audio.current.ctx.state === \"suspended\") {\n        await audio.current.ctx.resume()\n      }\n      setMuted(false)\n    } catch {\n      // No audio available - stay muted rather than break the reveal.\n    }\n  }\n\n  return (\n    <div\n      className={cn(\n        \"bg-background text-foreground [container-type:size] relative h-full min-h-[24rem] w-full overflow-hidden\",\n        className\n      )}\n    >\n      <div\n        ref={scrollRef}\n        className=\"relative h-full w-full overflow-x-hidden overflow-y-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden\"\n      >\n        {/* Tall track for the pinned panel to travel across. */}\n        <div className=\"relative w-full\" style={{ height: `${track}cqh` }}>\n          <div className=\"sticky top-0 flex h-[100cqh] flex-col items-center justify-center px-[4cqw]\">\n            <Tag\n              aria-label={lines.join(\" \")}\n              className={cn(\n                \"text-center text-[9cqw] leading-[0.98] font-medium tracking-[-0.035em]\",\n                textClassName\n              )}\n            >\n              {lines.map((line, l) => (\n                <span key={l} className=\"block whitespace-pre\">\n                  {plan\n                    .filter((letter) => letter.line === l)\n                    .map((letter) => (\n                      <Letter\n                        key={`${l}-${letter.index}`}\n                        char={letter.char}\n                        from={letter.from}\n                        to={letter.to}\n                        snap={snap}\n                        space={space}\n                        progress={scrollYProgress}\n                      />\n                    ))}\n                </span>\n              ))}\n            </Tag>\n          </div>\n        </div>\n      </div>\n\n      {sound !== false ? (\n        <button\n          type=\"button\"\n          onClick={toggleSound}\n          aria-pressed={!muted}\n          aria-label={muted ? \"Turn tick sound on\" : \"Turn tick sound off\"}\n          className={cn(\n            \"text-muted-foreground hover:text-foreground hover:bg-foreground/10\",\n            \"absolute top-[4cqh] right-[4cqw] z-10 grid size-8 place-items-center rounded-full\",\n            \"transition-colors duration-150 ease-smooth-out\",\n            \"focus-visible:ring-ring/50 outline-none focus-visible:ring-[3px]\"\n          )}\n        >\n          {muted ? (\n            <VolumeX className=\"size-4\" />\n          ) : (\n            <Volume2 className=\"size-4\" />\n          )}\n        </button>\n      ) : null}\n\n      {label !== null ? (\n        <div className=\"pointer-events-none absolute inset-x-0 bottom-[7%] z-10 flex flex-col items-center\">\n          <span className=\"bg-foreground/20 mb-3 h-10 w-px\" />\n          <span className=\"text-muted-foreground text-xs leading-tight tracking-[0.22em] uppercase\">\n            {label}\n          </span>\n        </div>\n      ) : null}\n    </div>\n  )\n}\n"
    }
  ]
}
