{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "page-decode",
  "title": "Page Decode",
  "author": "zyx1121 (https://github.com/zyx1121)",
  "description": "The page motion: a page's text decodes in row by row as a terminal prints it, and scrambles out before a link within the app leaves it. No framework needed.",
  "registryDependencies": [
    "https://ui.zyx.tw/r/layout.json"
  ],
  "files": [
    {
      "path": "registry/zyx/components/page-decode.tsx",
      "content": "\"use client\"\n\nimport { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from \"react\"\n\n// Glyphs for characters that have not resolved, as ScrambleText draws them,\n// minus the ones a line may break at (\"-\", \"/\", \"!\", \"?\", brackets), so no\n// line rewraps mid-effect. Han characters take Han glyphs from the font's\n// subset (../fonts/cjk.txt): in the monospace face each glyph keeps its cell's\n// width, so nothing on the page moves. Punctuation and symbols stay as they\n// are.\nconst NARROW = Array.from(\"#$%&*+<=>@^~\")\nconst WIDE = Array.from(\"之乖值動化協境夠改測率環系統翔自良詠試詹調頻\")\nconst WIDE_CHAR = /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-｠￠-￦]/u\nconst LETTER = /[\\p{L}\\p{N}]/u\n\n/** Milliseconds per resolved character, as the title's ScrambleText. */\nconst STEP = 50\n/** A long line resolves within this, however many characters it has. */\nconst LONGEST = 600\n/** Milliseconds between rows, as enterRow. */\nconst ROW = 25\n/** Milliseconds to scramble the page before leaving it. */\nexport const OUT = 200\n/**\n * Dispatched on the document as the page starts to scramble out, for what\n * draws its own characters (the home's mark) to scramble with it over OUT.\n */\nexport const LEAVE_EVENT = \"page-decode:leave\"\n\nconst KEEP = 0\nconst NARROW_GLYPH = 1\nconst WIDE_GLYPH = 2\n\ntype Line = {\n  node: Text\n  text: string\n  chars: string[]\n  kinds: number[]\n  delay: number\n  step: number\n}\n\nfunction reducedMotion() {\n  return window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n}\n\n/**\n * Every text node in the page that has something to scramble, with the delay\n * of the row it sits in. Nodes of symbols alone are left to their owners (the\n * works window's frame on www.zyx.tw), and ScrambleText runs its own effect.\n */\nfunction collect(main: HTMLElement): Line[] {\n  const lines: Line[] = []\n  const walker = document.createTreeWalker(main, NodeFilter.SHOW_TEXT, {\n    acceptNode: (node) =>\n      (node as Text).data.trim() &&\n      !node.parentElement?.closest(\n        \"script, style, noscript, [data-slot=scramble-text]\"\n      )\n        ? NodeFilter.FILTER_ACCEPT\n        : NodeFilter.FILTER_REJECT,\n  })\n  for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n    const text = node as Text\n    const row = text.parentElement\n      ?.closest(\"[class*='enter-row-']\")\n      ?.className.match(/enter-row-(\\d+)/)?.[1]\n    const chars = Array.from(text.data)\n    const kinds = chars.map((char) =>\n      !LETTER.test(char)\n        ? KEEP\n        : WIDE_CHAR.test(char)\n          ? WIDE_GLYPH\n          : NARROW_GLYPH\n    )\n    if (kinds.every((kind) => kind === KEEP)) continue\n    lines.push({\n      node: text,\n      text: text.data,\n      chars,\n      kinds,\n      delay: Number(row ?? 0) * ROW,\n      step: Math.min(STEP, LONGEST / chars.length),\n    })\n  }\n  return lines\n}\n\nfunction draw(line: Line, resolved: number) {\n  let out = \"\"\n  for (let index = 0; index < line.chars.length; index++) {\n    const kind = line.kinds[index]\n    if (index < resolved || kind === KEEP) {\n      out += line.chars[index]\n    } else {\n      const pool = kind === WIDE_GLYPH ? WIDE : NARROW\n      out += pool[Math.floor(Math.random() * pool.length)]\n    }\n  }\n  return out\n}\n\n/**\n * Scrambles the lines in, each resolving left to right after its row's\n * delay, or out, every line scrambling from its end over OUT ms. Out keeps\n * the glyphs moving until the page is replaced. Returns a cancel that puts\n * the final text back.\n */\nfunction play(\n  main: HTMLElement,\n  lines: Line[],\n  direction: \"in\" | \"out\",\n  onScrambled?: () => void\n) {\n  let raf = 0\n  let start: number | undefined\n  let lastTick = -1\n  let called = false\n  const resolvedAt = lines.map(() => -1)\n  main.setAttribute(\"aria-busy\", \"true\")\n\n  const frame = (now: number) => {\n    start ??= now\n    const elapsed = now - start\n    const tick = Math.floor(elapsed / STEP)\n    const reroll = tick !== lastTick\n    lastTick = tick\n    // Out runs until the next page replaces this one, even on its first\n    // frame, where every line is still whole.\n    let running = direction === \"out\"\n    lines.forEach((line, index) => {\n      const length = line.chars.length\n      let resolved: number\n      if (direction === \"in\") {\n        const local = elapsed - line.delay\n        resolved = local < 0 ? 0 : Math.floor(local / line.step)\n      } else {\n        resolved = Math.ceil(length * Math.max(0, 1 - elapsed / OUT))\n      }\n      if (resolved >= length) {\n        if (resolvedAt[index] !== length) line.node.data = line.text\n        resolvedAt[index] = length\n        return\n      }\n      running = true\n      if (reroll || resolvedAt[index] !== resolved) {\n        line.node.data = draw(line, resolved)\n        resolvedAt[index] = resolved\n      }\n    })\n    if (direction === \"out\" && elapsed >= OUT && !called) {\n      called = true\n      onScrambled?.()\n    }\n    if (running) {\n      raf = requestAnimationFrame(frame)\n    } else {\n      main.removeAttribute(\"aria-busy\")\n    }\n  }\n\n  // The first frame is drawn now, so a new page never paints its final\n  // text before the effect starts.\n  frame(performance.now())\n\n  return () => {\n    cancelAnimationFrame(raf)\n    main.removeAttribute(\"aria-busy\")\n    for (const line of lines) line.node.data = line.text\n  }\n}\n\n/**\n * Decodes one element's text in at once, for text that changes after the\n * page has entered. Returns a cancel that puts the final text back.\n */\nexport function decodeText(element: HTMLElement) {\n  const lines = collect(element).map((line) => ({ ...line, delay: 0 }))\n  return play(element, lines, \"in\")\n}\n\nfunction subscribeToHistory(onChange: () => void) {\n  window.addEventListener(\"popstate\", onChange)\n  return () => window.removeEventListener(\"popstate\", onChange)\n}\n\n/**\n * The page motion of every zyx.tw app: text decodes as a terminal prints it.\n * A page's text starts scrambled and resolves row by row (its `enter-row-<n>`\n * class), 25ms apart, top to bottom. Following a link within the app first\n * scrambles the page being left, then the next one decodes in; what draws its\n * own characters takes part through LEAVE_EVENT. Reduced motion skips all of\n * it. Mount it once in the root layout: the marker it renders tells\n * globals.css to hold the rows until it starts, then their fades step aside.\n *\n * It needs no framework: by default it reads the path from `location` and\n * leaves with a full navigation. A router passes its own `pathname` and\n * `navigate` (page-decode-next.tsx does for Next.js), so links stay client\n * side.\n */\nexport function PageDecode({\n  pathname: routerPathname,\n  navigate,\n}: {\n  pathname?: string\n  navigate?: (href: string) => void\n} = {}) {\n  const locationPathname = useSyncExternalStore(\n    subscribeToHistory,\n    () => window.location.pathname,\n    () => \"\"\n  )\n  const pathname = routerPathname ?? locationPathname\n  const clientSide = navigate !== undefined\n  const navigateRef = useRef(\n    navigate ?? ((href: string) => window.location.assign(href))\n  )\n  useEffect(() => {\n    if (navigate) navigateRef.current = navigate\n  })\n  const cancel = useRef<() => void>(() => {})\n  const entering = useRef(false)\n\n  useLayoutEffect(() => {\n    document.documentElement.dataset.decoder = \"\"\n    const main = document.querySelector(\"main\")\n    if (!main || reducedMotion()) return\n    cancel.current()\n    cancel.current = play(main, collect(main), \"in\")\n    entering.current = true\n    // A click, a tap or a key while the page decodes shows it whole at once:\n    // the reader never waits on the effect.\n    const finish = () => {\n      if (!entering.current) return\n      entering.current = false\n      cancel.current()\n    }\n    const options = { capture: true, once: true } as const\n    document.addEventListener(\"pointerdown\", finish, options)\n    document.addEventListener(\"keydown\", finish, options)\n    return () => {\n      entering.current = false\n      document.removeEventListener(\"pointerdown\", finish, options)\n      document.removeEventListener(\"keydown\", finish, options)\n      cancel.current()\n    }\n  }, [pathname])\n\n  useEffect(() => {\n    // Capture, so this runs before Next's own link handler and can hold the\n    // navigation until the page has scrambled.\n    const onClick = (event: MouseEvent) => {\n      if (\n        event.defaultPrevented ||\n        event.button !== 0 ||\n        event.metaKey ||\n        event.ctrlKey ||\n        event.shiftKey ||\n        event.altKey\n      ) {\n        return\n      }\n      const link = (event.target as Element | null)?.closest(\"a[href]\")\n      if (\n        !(link instanceof HTMLAnchorElement) ||\n        (link.target && link.target !== \"_self\") ||\n        link.hasAttribute(\"download\")\n      ) {\n        return\n      }\n      const url = new URL(link.href)\n      if (\n        url.origin !== location.origin ||\n        url.pathname === location.pathname\n      ) {\n        return\n      }\n      const href = url.pathname + url.search + url.hash\n      const main = document.querySelector(\"main\")\n      // A link followed from the keyboard (detail 0) or under reduced motion\n      // goes at once, without the scramble out, but still through the router.\n      if (!main || reducedMotion() || event.detail === 0) {\n        if (!clientSide) return\n        event.preventDefault()\n        event.stopPropagation()\n        navigateRef.current(href)\n        return\n      }\n      event.preventDefault()\n      event.stopPropagation()\n      entering.current = false\n      cancel.current()\n      document.dispatchEvent(new Event(LEAVE_EVENT))\n      cancel.current = play(main, collect(main), \"out\", () =>\n        navigateRef.current(href)\n      )\n    }\n    document.addEventListener(\"click\", onClick, true)\n    return () => document.removeEventListener(\"click\", onClick, true)\n  }, [clientSide])\n\n  return <span hidden data-slot=\"page-decode\" />\n}\n",
      "type": "registry:component"
    }
  ],
  "css": {
    "@media (prefers-reduced-motion: no-preference)": {
      "html:has([data-slot=\"page-decode\"]):not([data-decoder]) main [class*=\"enter-row-\"]": {
        "animation": "scramble-text-hold 1.5s"
      },
      "html[data-decoder] main [class*=\"enter-row-\"]": {
        "animation": "none"
      }
    },
    "@keyframes scramble-text-hold": {
      "0%, 100%": {
        "opacity": "0"
      }
    }
  },
  "meta": {
    "useWhen": "Mounting once in the root layout so every page decodes in and scrambles out.",
    "notFor": "Animating one element after load; use scramble-text. In Next.js mount page-decode-next.",
    "related": [
      "page-decode-next",
      "scramble-text",
      "corners"
    ]
  },
  "docs": "Use when: Mounting once in the root layout so every page decodes in and scrambles out.\nNot for: Animating one element after load; use scramble-text. In Next.js mount page-decode-next.\nGuide: https://ui.zyx.tw/page-decode.md",
  "categories": [
    "layout",
    "motion"
  ],
  "type": "registry:component"
}