{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "typewriter",
  "title": "Typewriter",
  "description": "A real, playable typewriter in SVG: each key presses down, its typebar swings up to strike the ribbon, and the carriage steps along. Click it and type.",
  "files": [
    {
      "path": "registry/typewriter/typewriter.tsx",
      "content": "\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport const DEFAULT_TEXT =\n  \"Dear reader,\\nevery key is wired to a typebar. Press one and its bar swings up out of the basket, strikes the ribbon, and the carriage steps left for the next letter.\\n\\nYours, 23rd\"\n\n/** Enamel of the body and paper rest, a vintage mint. */\nexport const DEFAULT_COLOR = \"#8EC3B5\"\n/** Characters per second. */\nexport const DEFAULT_SPEED = 12\n/** Line length on the sheet, in characters. */\nexport const DEFAULT_COLUMNS = 32\n/** Pause on the finished page before it feeds out and starts over, in ms. */\nexport const DEFAULT_HOLD = 2600\n/** Wait before the first keystroke, in ms. */\nexport const DEFAULT_START_DELAY = 600\n/** Per-letter baseline, tilt, and ink wobble (0–1). */\nexport const DEFAULT_JITTER = 0.3\n\n/** Bell rings this many characters before the right margin. */\nconst BELL_CELLS = 6\n\nexport type TypewriterOptions = {\n  /** What gets typed. `\\n` starts a new line; long lines wrap at words. */\n  text?: string\n  /** Characters per second. Default `12`. */\n  speed?: number\n  /** Uneven keystrokes, with longer rests after punctuation. Default `true`. */\n  humanize?: boolean\n  /** Pull the sheet out and type it again after `hold`. Default `true`. */\n  loop?: boolean\n  /** Pause on the finished page before looping, in ms. Default `2600`. */\n  hold?: number\n  /** Wait before the first keystroke, in ms. Default `600`. */\n  startDelay?: number\n  /** Body enamel, any CSS color. Default `#8EC3B5`. */\n  color?: string\n  /** Line length on the sheet, in characters (16–60). Default `32`. */\n  columns?: number\n  /** Per-letter baseline, tilt, and ink wobble, 0–1. Default `0.3`. */\n  jitter?: number\n  /** Synthesized key clicks, bell, and return. Default `false`. */\n  sound?: boolean\n  /**\n   * Click the machine and type on it: your keyboard, or its keys, space\n   * bar, shift lock, and return lever. Taking over stops the script.\n   * Default `true`.\n   */\n  interactive?: boolean\n  /** Text on a chrome nameplate on the front. Omit for none. */\n  label?: string\n  /** Called each time the last character lands. */\n  onDone?: () => void\n}\n\nexport type TypewriterInstance = {\n  setOptions: (options: Partial<TypewriterOptions>) => void\n  /** Feed a fresh sheet and type from the first character. */\n  restart: () => void\n  destroy: () => void\n}\n\nexport type TypewriterStroke =\n  | { kind: \"char\"; ch: string; line: number; col: number; src: number }\n  | { kind: \"return\"; line: number; from: number; src: number }\n\n/**\n * The keystrokes that type `text` into `columns`-wide lines: characters\n * with their cell, and carriage returns. Words wrap whole unless a word is\n * wider than the line. `src` orders strokes against the source text, so a\n * relayout can resume at the same point.\n */\nexport function layoutTypewriter(\n  text: string,\n  columns: number\n): TypewriterStroke[] {\n  const width = Math.max(1, Math.floor(columns))\n  const source = Array.from(text.replace(/\\r\\n?/g, \"\\n\").replace(/\\t/g, \"  \"))\n  const strokes: TypewriterStroke[] = []\n  let line = 0\n  let col = 0\n  /** Wrap returns wait for the character after them. */\n  let pendingWraps: TypewriterStroke[] = []\n\n  const feed = (src: number) => {\n    const stroke: TypewriterStroke = {\n      kind: \"return\",\n      line: line + 1,\n      from: col,\n      src,\n    }\n    strokes.push(stroke)\n    line += 1\n    col = 0\n    return stroke\n  }\n  const wrap = () => pendingWraps.push(feed(Infinity))\n  const type = (ch: string, src: number) => {\n    for (const stroke of pendingWraps) stroke.src = src - 0.5\n    pendingWraps = []\n    strokes.push({ kind: \"char\", ch, line, col, src })\n    col += 1\n  }\n\n  let i = 0\n  while (i < source.length) {\n    const ch = source[i]!\n    if (ch === \"\\n\") {\n      for (const stroke of pendingWraps) stroke.src = i - 0.5\n      pendingWraps = []\n      feed(i)\n      i += 1\n      continue\n    }\n    if (/\\s/.test(ch)) {\n      // Spaces past the margin fall off the page.\n      if (col < width) type(\" \", i)\n      i += 1\n      continue\n    }\n    let end = i\n    while (end < source.length && !/\\s/.test(source[end]!)) end += 1\n    const length = end - i\n    if (col > 0 && col + length > width) wrap()\n    for (let k = i; k < end; k++) {\n      if (col >= width) wrap()\n      type(source[k]!, k)\n    }\n    i = end\n  }\n  return strokes\n}\n\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, value))\n}\n\nfunction numberOr(value: unknown, fallback: number, min: number, max: number) {\n  if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback\n  return clamp(value, min, max)\n}\n\n/** Stable 0–1 noise per integer, so a letter keeps its wobble on relayout. */\nfunction hash(n: number) {\n  let x = Math.imul(n + 1, 0x27d4eb2d) ^ 0x165667b1\n  x = Math.imul(x ^ (x >>> 15), 0x85ebca6b)\n  x = Math.imul(x ^ (x >>> 13), 0xc2b2ae35)\n  return ((x ^ (x >>> 16)) >>> 0) / 4294967296\n}\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\"\n\ntype Sound = {\n  key: (space: boolean) => void\n  bell: () => void\n  carriage: (ms: number) => void\n  close: () => void\n}\n\n/** Key clicks, the margin bell, and the return ratchet, all synthesized. */\nfunction createSound(): Sound | null {\n  const Ctx =\n    window.AudioContext ??\n    (window as unknown as { webkitAudioContext?: typeof AudioContext })\n      .webkitAudioContext\n  if (!Ctx) return null\n  let audio: AudioContext | null = null\n  let out: GainNode | null = null\n  let noise: AudioBuffer | null = null\n  // Closing is final, so a key-up timed before close can't open a new context.\n  let closed = false\n\n  const ready = () => {\n    if (closed) return null\n    if (!audio) {\n      audio = new Ctx()\n      out = audio.createGain()\n      out.gain.value = 0.55\n      out.connect(audio.destination)\n      noise = audio.createBuffer(\n        1,\n        Math.floor(audio.sampleRate * 0.4),\n        audio.sampleRate\n      )\n      const data = noise.getChannelData(0)\n      for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1\n    }\n    if (audio.state === \"suspended\") void audio.resume().catch(() => {})\n    return audio.state === \"running\" ? audio : null\n  }\n\n  const burst = (\n    a: AudioContext,\n    at: number,\n    freq: number,\n    q: number,\n    peak: number,\n    decay: number\n  ) => {\n    const src = a.createBufferSource()\n    src.buffer = noise\n    const band = a.createBiquadFilter()\n    band.type = \"bandpass\"\n    band.frequency.value = freq\n    band.Q.value = q\n    const gain = a.createGain()\n    gain.gain.setValueAtTime(0.0001, at)\n    gain.gain.exponentialRampToValueAtTime(peak, at + 0.002)\n    gain.gain.exponentialRampToValueAtTime(0.0001, at + decay)\n    src.connect(band).connect(gain).connect(out!)\n    src.start(at, Math.random() * 0.2)\n    src.stop(at + decay + 0.02)\n  }\n\n  const thump = (a: AudioContext, at: number, freq: number, peak: number) => {\n    const osc = a.createOscillator()\n    osc.frequency.setValueAtTime(freq, at)\n    osc.frequency.exponentialRampToValueAtTime(freq * 0.5, at + 0.05)\n    const gain = a.createGain()\n    gain.gain.setValueAtTime(0.0001, at)\n    gain.gain.exponentialRampToValueAtTime(peak, at + 0.003)\n    gain.gain.exponentialRampToValueAtTime(0.0001, at + 0.06)\n    osc.connect(gain).connect(out!)\n    osc.start(at)\n    osc.stop(at + 0.08)\n  }\n\n  return {\n    key(space) {\n      const a = ready()\n      if (!a) return\n      const at = a.currentTime\n      if (space) {\n        burst(a, at, 900, 0.9, 0.22, 0.05)\n        thump(a, at, 110, 0.3)\n      } else {\n        burst(a, at, 2600 + Math.random() * 900, 1.3, 0.34, 0.035)\n        thump(a, at, 150 + Math.random() * 30, 0.2)\n      }\n    },\n    bell() {\n      const a = ready()\n      if (!a) return\n      const at = a.currentTime\n      for (const [freq, peak] of [\n        [2093, 0.16],\n        [5776, 0.05],\n      ] as const) {\n        const osc = a.createOscillator()\n        osc.frequency.value = freq\n        const gain = a.createGain()\n        gain.gain.setValueAtTime(0.0001, at)\n        gain.gain.exponentialRampToValueAtTime(peak, at + 0.004)\n        gain.gain.exponentialRampToValueAtTime(0.0001, at + 1.1)\n        osc.connect(gain).connect(out!)\n        osc.start(at)\n        osc.stop(at + 1.2)\n      }\n    },\n    carriage(ms) {\n      const a = ready()\n      if (!a) return\n      const at = a.currentTime\n      const seconds = ms / 1000\n      // Ratchet clicks as the line feeds, then the glide home.\n      for (let i = 0; i < 3; i++) burst(a, at + i * 0.028, 1800, 2, 0.16, 0.02)\n      const src = a.createBufferSource()\n      src.buffer = noise\n      src.loop = true\n      const low = a.createBiquadFilter()\n      low.type = \"bandpass\"\n      low.Q.value = 0.8\n      low.frequency.setValueAtTime(700, at)\n      low.frequency.linearRampToValueAtTime(1400, at + seconds)\n      const gain = a.createGain()\n      gain.gain.setValueAtTime(0.0001, at)\n      gain.gain.exponentialRampToValueAtTime(0.07, at + seconds * 0.3)\n      gain.gain.exponentialRampToValueAtTime(0.0001, at + seconds)\n      src.connect(low).connect(gain).connect(out!)\n      src.start(at)\n      src.stop(at + seconds + 0.02)\n      thump(a, at + seconds, 120, 0.28)\n    },\n    close() {\n      closed = true\n      void audio?.close().catch(() => {})\n      audio = null\n    },\n  }\n}\n\nconst TAU = Math.PI * 2\n\n// The machine is drawn in one SVG coordinate space, seen from the front and\n// a little above. The print point sits at the origin: the line being typed\n// has its baseline on y = 0, and the carriage slides so the next column\n// always lands at x = 0. Light comes from the upper left.\n\n/** Character pitch on the sheet. */\nconst CW = 10\n/** Line pitch on the sheet. */\nconst LH = 22\nconst FONT = 16.5\n/** Sheet margin either side of the text. */\nconst PAD = 30\n/** Sheet above the first baseline once it's fed in. */\nconst TOP_MARGIN = 38\nconst VIEW_TOP = -178\nconst VIEW_BOTTOM = 314\n/** Where a typebar's slug lands: the middle of the glyph on the print line. */\nconst STRIKE_Y = -5\n/** Centre of the typebar basket, under the print point. */\nconst BASKET_Y = 42\nconst PIVOT_R = 56\nconst REST_R = 27\n/** Half the basket's fan, in radians from straight down. */\nconst SPREAD = (74 * Math.PI) / 180\n/** Platen knob radius, for how far it turns per line. */\nconst KNOB_R = 21\nconst RIDGES = 11\nconst SPOOL_Y = 80\nconst SPOOL_X = 150\nconst KEY_ROWS = [\"1234567890\", \"qwertyuiop\", \"asdfghjkl;\", \"zxcvbnm,./\"]\nconst KEY_Y = [136, 166, 196, 226]\nconst KEY_PITCH = 35\nconst KEY_R = 12.5\n/** Key tops are circles seen from above: this squashes them. */\nconst KEY_TILT = 0.64\n/** How far a key travels when pressed. */\nconst KEY_TRAVEL = 4\n/** Paper lean per unit/s of carriage speed, in degrees, and its limit. */\nconst FLEX_GAIN = 0.0042\nconst FLEX_MAX = 5\n/** Spring the paper wobbles back on. */\nconst FLEX_K = 170\nconst FLEX_C = 9\n/** Platen line: where the sheet bends from. */\nconst FLEX_ANCHOR = 40\n/** Shifted characters, and the key that types them. */\nconst SHIFTED: Record<string, string> = {\n  \"!\": \"1\",\n  '\"': \"2\",\n  \"#\": \"3\",\n  $: \"4\",\n  \"%\": \"5\",\n  _: \"6\",\n  \"&\": \"7\",\n  \"'\": \"8\",\n  \"(\": \"9\",\n  \")\": \"0\",\n  \":\": \";\",\n  \"?\": \"/\",\n  \"<\": \",\",\n  \">\": \".\",\n}\n\nconst INK = \"#24221F\"\nconst LEGEND = \"#EFE7D1\"\nconst RIBBON_BLACK = \"#16171A\"\nconst RIBBON_RED = \"#C4342B\"\nconst CHROME = \"#D3D8DC\"\nconst CHROME_EDGE = \"#5E656C\"\nconst SHEET = \"var(--typewriter-sheet, #FBF9F3)\"\n\n/** An SVG element. A `fill` of `\"sheet\"` paints in the paper tone. */\nfunction draw<K extends keyof SVGElementTagNameMap>(\n  tag: K,\n  attrs: Record<string, string | number>,\n  parent?: Element\n) {\n  const node = document.createElementNS(SVG_NS, tag)\n  for (const [key, value] of Object.entries(attrs)) {\n    if (key === \"fill\" && value === \"sheet\") node.style.fill = SHEET\n    else node.setAttribute(key, String(value))\n  }\n  parent?.append(node)\n  return node\n}\n\ntype Rgb = [number, number, number]\n\nlet swatch: CanvasRenderingContext2D | null = null\n\n/** Any CSS color as RGB, via a one-pixel canvas. */\nfunction rgbOf(color: string, fallback: Rgb): Rgb {\n  swatch ??= document\n    .createElement(\"canvas\")\n    .getContext(\"2d\", { willReadFrequently: true })\n  if (!swatch) return fallback\n  swatch.clearRect(0, 0, 1, 1)\n  swatch.fillStyle = `rgb(${fallback.join(\" \")})`\n  swatch.fillStyle = color\n  swatch.fillRect(0, 0, 1, 1)\n  const [r = 0, g = 0, b = 0] = swatch.getImageData(0, 0, 1, 1).data\n  return [r, g, b]\n}\n\nfunction mix(a: Rgb, b: Rgb, t: number) {\n  const c = a.map((v, i) => Math.round(v + (b[i]! - v) * t))\n  return `rgb(${c.join(\" \")})`\n}\n\nconst linear = (t: number) => t\nconst easeIn = (t: number) => t * t * t\nconst easeOut = (t: number) => 1 - (1 - t) ** 3\nconst easeInOut = (t: number) =>\n  t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2\n\n/** Down fast, hold, ease back up: a key, a typebar, the ribbon. */\nfunction pulse(t: number, from: number, rise: number, hold: number) {\n  if (t < rise) return from + (1 - from) * easeOut(t / rise)\n  if (t < rise + hold) return 1\n  return 1 - easeInOut((t - rise - hold) / Math.max(0.001, 1 - rise - hold))\n}\n\n/** A point on the basket, `angle` radians from straight down. */\nfunction polar(r: number, angle: number): [number, number] {\n  return [r * Math.sin(angle), BASKET_Y + r * Math.cos(angle)]\n}\n\ntype Bar = {\n  rest: SVGGElement\n  strike: SVGGElement\n  /** Dark edge under the bar, so it reads over the paper. */\n  edge: SVGLineElement\n  core: SVGLineElement\n  slug: SVGLineElement\n  pivot: [number, number]\n  tip: [number, number]\n  v: number\n}\n\ntype Key = { cap: SVGGElement; bar: Bar | null; v: number }\n\ntype Machine = {\n  columns: number\n  /** Everything but the ground shadow; it shudders on each strike. */\n  rig: SVGGElement\n  /** Under-inked fills, for letters the ribbon didn't fully cover. */\n  inkFills: string[]\n  carriage: SVGGElement\n  paper: SVGGElement\n  sheet: SVGRectElement\n  shadow: SVGRectElement\n  ink: SVGGElement\n  lever: SVGGElement\n  leverPivot: [number, number]\n  knobs: { x: number; lines: SVGLineElement[] }[]\n  keys: Map<string, Key>\n  shifts: Key[]\n  space: Key\n  basket: SVGGElement\n  bars: Bar[]\n  ribbon: { path: SVGPathElement; dy: number }[]\n  vibrator: SVGGElement\n  spools: SVGGElement[]\n}\n\n/**\n * Draw the whole typewriter into `svg`: the carriage (rail, paper rest,\n * platen, knobs, return lever, sheet, scale) and the body (enamel shell,\n * typebar basket, ribbon spools, ribbon, keyboard). `color` is the enamel;\n * its lights and shadows are mixed from it.\n */\nfunction drawMachine(\n  svg: SVGSVGElement,\n  id: string,\n  columns: number,\n  color: string,\n  label?: string\n): Machine {\n  const span = columns * CW\n  const platenL = -PAD - 22\n  const platenR = span + PAD + 22\n  const knobW = 15\n  const leverX = platenL - knobW - 4\n  // Room for the carriage at both ends of its travel, and the body.\n  const left = leverX - 56 - (span + CW / 2)\n  const right = platenR + knobW - CW / 2\n  const half = Math.ceil(Math.max(-left, right, 262) + 14)\n  svg.replaceChildren()\n  svg.setAttribute(\n    \"viewBox\",\n    `${-half} ${VIEW_TOP} ${half * 2} ${VIEW_BOTTOM - VIEW_TOP}`\n  )\n\n  const base = rgbOf(color, [142, 195, 181])\n  const white: Rgb = [255, 255, 255]\n  const black: Rgb = [0, 0, 0]\n  const enamel = {\n    shine: mix(base, white, 0.62),\n    hi: mix(base, white, 0.34),\n    light: mix(base, white, 0.14),\n    mid: mix(base, base, 0),\n    low: mix(base, black, 0.16),\n    deep: mix(base, black, 0.34),\n    edge: mix(base, black, 0.55),\n  }\n\n  /* Gradients. */\n  const defs = draw(\"defs\", {}, svg)\n  const gradient = (\n    name: string,\n    kind: \"linearGradient\" | \"radialGradient\",\n    attrs: Record<string, string | number>,\n    stops: [number, string, number?][]\n  ) => {\n    const el = draw(kind, { id: `${id}-${name}`, ...attrs }, defs)\n    for (const [offset, stopColor, alpha = 1] of stops) {\n      draw(\n        \"stop\",\n        { offset, \"stop-color\": stopColor, \"stop-opacity\": alpha },\n        el\n      )\n    }\n    return `url(#${id}-${name})`\n  }\n  const down = { x1: 0, y1: 0, x2: 0, y2: 1 }\n  const across = { x1: 0, y1: 0, x2: 1, y2: 0 }\n  const fills = {\n    body: gradient(\"body\", \"linearGradient\", down, [\n      [0, enamel.hi],\n      [0.18, enamel.light],\n      [0.62, enamel.mid],\n      [1, enamel.low],\n    ]),\n    sides: gradient(\"sides\", \"linearGradient\", across, [\n      [0, \"#000\", 0.26],\n      [0.1, \"#000\", 0.04],\n      [0.5, \"#fff\", 0.05],\n      [0.9, \"#000\", 0.04],\n      [1, \"#000\", 0.3],\n    ]),\n    front: gradient(\"front\", \"linearGradient\", down, [\n      [0, enamel.low],\n      [1, enamel.deep],\n    ]),\n    rest: gradient(\"rest\", \"linearGradient\", down, [\n      [0, enamel.hi],\n      [0.5, enamel.light],\n      [1, enamel.low],\n    ]),\n    chrome: gradient(\"chrome\", \"linearGradient\", down, [\n      [0, \"#FDFEFE\"],\n      [0.38, \"#D2D7DB\"],\n      [0.52, \"#8B9298\"],\n      [0.7, \"#C3C8CC\"],\n      [1, \"#EEF0F2\"],\n    ]),\n    chromeV: gradient(\"chrome-v\", \"linearGradient\", across, [\n      [0, \"#8B9298\"],\n      [0.35, \"#F4F6F7\"],\n      [0.6, \"#BFC4C9\"],\n      [1, \"#737A80\"],\n    ]),\n    rubber: gradient(\"rubber\", \"linearGradient\", down, [\n      [0, \"#55595E\"],\n      [0.16, \"#2A2D31\"],\n      [0.55, \"#0D0E10\"],\n      [0.85, \"#050607\"],\n      [1, \"#1E2124\"],\n    ]),\n    bakelite: gradient(\"bakelite\", \"linearGradient\", down, [\n      [0, \"#62666C\"],\n      [0.2, \"#2C2F33\"],\n      [0.6, \"#111214\"],\n      [1, \"#2A2D31\"],\n    ]),\n    capTop: gradient(\n      \"cap-top\",\n      \"radialGradient\",\n      { cx: 0.38, cy: 0.3, r: 0.75 },\n      [\n        [0, \"#575C63\"],\n        [0.55, \"#202326\"],\n        [1, \"#0C0D0F\"],\n      ]\n    ),\n    capSide: gradient(\"cap-side\", \"linearGradient\", down, [\n      [0, \"#9AA1A7\"],\n      [0.5, \"#4B5157\"],\n      [1, \"#2A2E32\"],\n    ]),\n    well: gradient(\"well\", \"linearGradient\", down, [\n      [0, \"#08090A\"],\n      [0.18, \"#151719\"],\n      [1, \"#24272A\"],\n    ]),\n    recess: gradient(\"recess\", \"radialGradient\", { cx: 0.5, cy: 0, r: 1 }, [\n      [0, \"#030304\"],\n      [0.7, \"#141618\"],\n      [1, \"#24272A\"],\n    ]),\n    spoolRibbon: gradient(\n      \"spool-ribbon\",\n      \"radialGradient\",\n      { cx: 0.42, cy: 0.38, r: 0.7 },\n      [\n        [0, \"#3B3E43\"],\n        [0.7, \"#151618\"],\n        [1, \"#060607\"],\n      ]\n    ),\n    flange: gradient(\n      \"flange\",\n      \"radialGradient\",\n      { cx: 0.36, cy: 0.3, r: 0.85 },\n      [\n        [0, \"#FFFFFF\"],\n        [0.45, \"#CDD2D6\"],\n        [1, \"#7D848A\"],\n      ]\n    ),\n    ground: gradient(\"ground\", \"radialGradient\", { cx: 0.5, cy: 0.5, r: 0.5 }, [\n      [0, \"#000\", 0.34],\n      [0.6, \"#000\", 0.12],\n      [1, \"#000\", 0],\n    ]),\n    keyShadow: gradient(\n      \"key-shadow\",\n      \"radialGradient\",\n      { cx: 0.5, cy: 0.5, r: 0.5 },\n      [\n        [0, \"#000\", 0.7],\n        [1, \"#000\", 0],\n      ]\n    ),\n    curl: gradient(\n      \"curl\",\n      \"linearGradient\",\n      { gradientUnits: \"userSpaceOnUse\", x1: 0, y1: 12, x2: 0, y2: 41 },\n      [\n        [0, \"#3A2E1C\", 0],\n        [0.55, \"#3A2E1C\", 0.1],\n        [1, \"#3A2E1C\", 0.34],\n      ]\n    ),\n    contact: gradient(\"contact\", \"linearGradient\", down, [\n      [0, \"#000\", 0.3],\n      [1, \"#000\", 0],\n    ]),\n  }\n  const inkFills = (\n    [\n      [down, 0, 0.36],\n      [down, 1, 0.4],\n      [across, 0, 0.42],\n      [across, 1, 0.42],\n    ] as const\n  ).map(([dir, faintEnd, alpha], i) =>\n    gradient(\n      `ink-${i}`,\n      \"linearGradient\",\n      dir,\n      faintEnd === 0\n        ? [\n            [0, INK, alpha],\n            [0.55, INK, 1],\n            [1, INK, 1],\n          ]\n        : [\n            [0, INK, 1],\n            [0.45, INK, 1],\n            [1, INK, alpha],\n          ]\n    )\n  )\n\n  // The sheet fades out at the top of the frame and tucks behind the\n  // platen at the bottom.\n  const fade = gradient(\n    \"fade-g\",\n    \"linearGradient\",\n    {\n      gradientUnits: \"userSpaceOnUse\",\n      x1: 0,\n      x2: 0,\n      y1: VIEW_TOP,\n      y2: 41,\n    },\n    [\n      [0, \"#fff\", 0],\n      [84 / (41 - VIEW_TOP), \"#fff\", 1],\n      [0.998, \"#fff\", 1],\n      [1, \"#fff\", 0],\n    ]\n  )\n  const box = { x: -4000, y: VIEW_TOP - 4, width: 8000, height: 50 - VIEW_TOP }\n  const mask = draw(\n    \"mask\",\n    { id: `${id}-fade`, maskUnits: \"userSpaceOnUse\", ...box },\n    defs\n  )\n  draw(\"rect\", { ...box, fill: fade }, mask)\n\n  // Ground shadow.\n  draw(\"ellipse\", { cx: 0, cy: 302, rx: 300, ry: 15, fill: fills.ground }, svg)\n\n  /* ---------------- Carriage ---------------- */\n\n  const rig = draw(\"g\", {}, svg)\n  const carriage = draw(\"g\", {}, rig)\n  // Rail it rides on.\n  draw(\n    \"rect\",\n    {\n      x: platenL - knobW - 8,\n      y: 40,\n      width: platenR - platenL + knobW * 2 + 16,\n      height: 6,\n      rx: 3,\n      fill: fills.chrome,\n    },\n    carriage\n  )\n  // Paper rest behind the sheet.\n  const tL = -PAD - 16\n  const tR = span + PAD + 16\n  draw(\n    \"path\",\n    {\n      d: `M${tL} 10V-80Q${tL} -98 ${tL + 18} -98H${tR - 18}Q${tR} -98 ${tR} -80V10Z`,\n      fill: fills.rest,\n    },\n    carriage\n  )\n  draw(\n    \"path\",\n    {\n      d: `M${tL + 1} -80Q${tL + 1} -97 ${tL + 18} -97H${tR - 18}Q${tR - 1} -97 ${tR - 1} -80`,\n      fill: \"none\",\n      stroke: enamel.shine,\n      \"stroke-width\": 1.4,\n      \"stroke-opacity\": 0.85,\n    },\n    carriage\n  )\n  // Platen, with chrome collars at its ends.\n  draw(\n    \"rect\",\n    {\n      x: platenL,\n      y: 6,\n      width: platenR - platenL,\n      height: 34,\n      rx: 4,\n      fill: fills.rubber,\n    },\n    carriage\n  )\n  draw(\n    \"rect\",\n    {\n      x: platenL + 4,\n      y: 10.5,\n      width: platenR - platenL - 8,\n      height: 1.6,\n      rx: 0.8,\n      fill: \"#fff\",\n      \"fill-opacity\": 0.22,\n    },\n    carriage\n  )\n  for (const x of [platenL - 4, platenR]) {\n    draw(\n      \"rect\",\n      { x, y: 9, width: 4, height: 28, rx: 1, fill: fills.chrome },\n      carriage\n    )\n  }\n  // Knobs: bakelite with knurling that turns with the platen.\n  const knobs = [platenL - 4 - knobW, platenR + 4].map((x) => {\n    draw(\n      \"rect\",\n      { x, y: 1, width: knobW, height: 44, rx: 6, fill: fills.bakelite },\n      carriage\n    )\n    const lines = Array.from({ length: RIDGES }, () =>\n      draw(\n        \"line\",\n        {\n          x1: x + 2.5,\n          x2: x + knobW - 2.5,\n          stroke: \"#B8BEC4\",\n          \"stroke-width\": 1,\n          \"stroke-linecap\": \"round\",\n        },\n        carriage\n      )\n    )\n    draw(\n      \"rect\",\n      {\n        x: x + 2,\n        y: 3,\n        width: knobW - 4,\n        height: 6,\n        rx: 3,\n        fill: \"#fff\",\n        \"fill-opacity\": 0.12,\n      },\n      carriage\n    )\n    return { x, lines }\n  })\n  // Carriage return lever: chrome arm, bakelite grip.\n  const lever = draw(\"g\", { \"data-key\": \"return\" }, carriage)\n  const leverPivot: [number, number] = [leverX, 30]\n  draw(\n    \"rect\",\n    {\n      x: leverX - 5,\n      y: 20,\n      width: 10,\n      height: 22,\n      rx: 3,\n      fill: fills.chromeV,\n    },\n    lever\n  )\n  const arm = `M${leverX} 28L${leverX - 13} 4L${leverX - 36} -14`\n  for (const [stroke, width] of [\n    [CHROME_EDGE, 6.4],\n    [CHROME, 4],\n  ] as const) {\n    draw(\n      \"path\",\n      {\n        d: arm,\n        fill: \"none\",\n        stroke,\n        \"stroke-width\": width,\n        \"stroke-linecap\": \"round\",\n        \"stroke-linejoin\": \"round\",\n      },\n      lever\n    )\n  }\n  draw(\n    \"path\",\n    {\n      d: `M${leverX - 1} 26L${leverX - 13} 4.5L${leverX - 34} -12`,\n      fill: \"none\",\n      stroke: \"#fff\",\n      \"stroke-width\": 1.2,\n      \"stroke-opacity\": 0.8,\n      \"stroke-linecap\": \"round\",\n      \"stroke-linejoin\": \"round\",\n    },\n    lever\n  )\n  draw(\n    \"rect\",\n    {\n      x: leverX - 56,\n      y: -25,\n      width: 28,\n      height: 11,\n      rx: 5.5,\n      fill: fills.bakelite,\n      transform: `rotate(-24 ${leverX - 42} -19.5)`,\n    },\n    lever\n  )\n\n  // The sheet, masked so it fades at the top and wraps under the platen.\n  const wrap = draw(\"g\", { mask: `url(#${id}-fade)` }, carriage)\n  const paper = draw(\"g\", {}, wrap)\n  const shadow = draw(\n    \"rect\",\n    {\n      x: -PAD + 3,\n      y: -TOP_MARGIN + 3,\n      width: span + PAD * 2,\n      height: 600,\n      fill: \"#000\",\n      \"fill-opacity\": 0.12,\n    },\n    paper\n  )\n  const sheet = draw(\n    \"rect\",\n    {\n      x: -PAD,\n      y: -TOP_MARGIN,\n      width: span + PAD * 2,\n      height: 600,\n      fill: \"sheet\",\n      stroke: \"#000\",\n      \"stroke-opacity\": 0.07,\n      \"stroke-width\": 0.8,\n    },\n    paper\n  )\n  const ink = draw(\n    \"g\",\n    { \"text-anchor\": \"middle\", \"font-size\": FONT, fill: INK },\n    paper\n  )\n  // Where the sheet curls round the platen.\n  draw(\n    \"rect\",\n    {\n      x: -PAD,\n      y: 12,\n      width: span + PAD * 2,\n      height: 30,\n      fill: fills.curl,\n    },\n    wrap\n  )\n\n  // Paper scale under the print line.\n  draw(\n    \"rect\",\n    {\n      x: -PAD + 2,\n      y: 8.5,\n      width: span + PAD * 2 - 4,\n      height: 6,\n      rx: 3,\n      fill: fills.chrome,\n    },\n    carriage\n  )\n  let ticks = \"\"\n  for (let c = 0; c <= columns; c++) {\n    const x = c * CW\n    ticks += `M${x} 9.4V${c % 10 === 0 ? 13.6 : c % 5 === 0 ? 12.4 : 11.2}`\n  }\n  draw(\n    \"path\",\n    {\n      d: ticks,\n      stroke: \"#3E444A\",\n      \"stroke-width\": 0.7,\n      fill: \"none\",\n    },\n    carriage\n  )\n\n  /* ---------------- Body ---------------- */\n\n  const body = draw(\"g\", {}, rig)\n  const shell =\n    \"M-192 42Q-214 42 -219 62C-228 120 -240 190 -247 246Q-249 262 -232 264H232Q249 262 247 246C240 190 228 120 219 62Q214 42 192 42Z\"\n  draw(\"path\", { d: shell, fill: fills.body }, body)\n  draw(\"path\", { d: shell, fill: fills.sides }, body)\n  draw(\n    \"rect\",\n    { x: -206, y: 42.5, width: 412, height: 15, fill: fills.contact },\n    body\n  )\n  // Front face, below the top surfaces, with a chrome trim.\n  draw(\n    \"path\",\n    {\n      d: \"M-247 248Q-249 262 -232 264H232Q249 262 247 248L245 284Q243 296 227 296H-227Q-243 296 -245 284Z\",\n      fill: fills.front,\n    },\n    body\n  )\n  draw(\n    \"path\",\n    {\n      d: \"M-240 264.5H240\",\n      stroke: enamel.shine,\n      \"stroke-width\": 1.2,\n      \"stroke-opacity\": 0.7,\n    },\n    body\n  )\n  draw(\n    \"rect\",\n    {\n      x: -236,\n      y: 274,\n      width: 472,\n      height: 3,\n      rx: 1.5,\n      fill: fills.chrome,\n    },\n    body\n  )\n  if (label) {\n    const w = Math.max(36, label.length * 7.4 + 18)\n    draw(\n      \"rect\",\n      {\n        x: -w / 2,\n        y: 268.5,\n        width: w,\n        height: 14,\n        rx: 3,\n        fill: fills.chrome,\n        stroke: CHROME_EDGE,\n        \"stroke-width\": 0.8,\n      },\n      body\n    )\n    for (const [dy, fill] of [\n      [0.6, \"#fff\"],\n      [0, \"#30353A\"],\n    ] as const) {\n      const plate = draw(\n        \"text\",\n        {\n          x: 0,\n          y: 276 + dy,\n          \"text-anchor\": \"middle\",\n          \"dominant-baseline\": \"central\",\n          \"font-size\": 8.4,\n          \"font-weight\": 700,\n          \"letter-spacing\": 1.6,\n          fill,\n        },\n        body\n      )\n      plate.textContent = label\n    }\n  }\n  for (const x of [-228, 188]) {\n    draw(\n      \"rect\",\n      { x, y: 293, width: 40, height: 10, rx: 4, fill: \"#151618\" },\n      body\n    )\n  }\n  const sheen = gradient(\"sheen\", \"linearGradient\", across, [\n    [0, \"#fff\", 0.34],\n    [0.55, \"#fff\", 0.1],\n    [1, \"#fff\", 0],\n  ])\n  draw(\n    \"path\",\n    { d: \"M-210 48H-96L-150 110H-224Q-222 82 -210 48Z\", fill: sheen },\n    body\n  )\n  // Glossy rim along the top of the shell.\n  draw(\n    \"path\",\n    {\n      d: \"M-194 43.4H194\",\n      stroke: enamel.shine,\n      \"stroke-width\": 1.6,\n      \"stroke-linecap\": \"round\",\n    },\n    body\n  )\n  draw(\n    \"path\",\n    {\n      d: \"M-208 56Q-212 70 -216 96\",\n      stroke: enamel.shine,\n      \"stroke-width\": 2.4,\n      \"stroke-linecap\": \"round\",\n      \"stroke-opacity\": 0.55,\n      fill: \"none\",\n    },\n    body\n  )\n\n  // Typebar basket, sunk in the deck.\n  draw(\n    \"path\",\n    {\n      d: `M-68 ${BASKET_Y}A68 68 0 0 0 68 ${BASKET_Y}Z`,\n      fill: fills.recess,\n    },\n    body\n  )\n  draw(\n    \"path\",\n    {\n      d: `M-68 ${BASKET_Y}A68 68 0 0 0 68 ${BASKET_Y}`,\n      fill: \"none\",\n      stroke: enamel.shine,\n      \"stroke-width\": 1.3,\n      \"stroke-opacity\": 0.75,\n    },\n    body\n  )\n  const basket = draw(\"g\", {}, body)\n  const [ax, ay] = polar(62, -SPREAD - 0.12)\n  const [bx, by] = polar(62, SPREAD + 0.12)\n  const [cx, cy] = polar(53, SPREAD + 0.12)\n  const [dx, dy] = polar(53, -SPREAD - 0.12)\n  draw(\n    \"path\",\n    {\n      d: `M${ax} ${ay}A62 62 0 0 0 ${bx} ${by}L${cx} ${cy}A53 53 0 0 1 ${dx} ${dy}Z`,\n      fill: fills.chrome,\n    },\n    basket\n  )\n\n  // Ribbon spools: black ribbon wound under a turning chrome flange.\n  const spools = [-SPOOL_X, SPOOL_X].map((x) => {\n    draw(\n      \"circle\",\n      { cx: x, cy: SPOOL_Y + 2, r: 27, fill: \"#000\", \"fill-opacity\": 0.22 },\n      body\n    )\n    draw(\"circle\", { cx: x, cy: SPOOL_Y, r: 26, fill: fills.flange }, body)\n    draw(\"circle\", { cx: x, cy: SPOOL_Y, r: 22, fill: fills.spoolRibbon }, body)\n    const turn = draw(\"g\", {}, body)\n    let windows = \"\"\n    for (let i = 0; i < 3; i++) {\n      const a0 = (i / 3) * TAU + 0.25\n      const a1 = a0 + 1.35\n      const p = (r: number, a: number) =>\n        `${(x + Math.cos(a) * r).toFixed(2)} ${(SPOOL_Y + Math.sin(a) * r).toFixed(2)}`\n      windows += `M${p(19, a0)}A19 19 0 0 1 ${p(19, a1)}L${p(8.5, a1)}A8.5 8.5 0 0 0 ${p(8.5, a0)}Z`\n    }\n    draw(\n      \"path\",\n      {\n        d: `M${x - 21} ${SPOOL_Y}a21 21 0 1 0 42 0a21 21 0 1 0 -42 0Z${windows}`,\n        fill: fills.flange,\n        \"fill-rule\": \"evenodd\",\n      },\n      turn\n    )\n    draw(\"circle\", { cx: x, cy: SPOOL_Y, r: 5, fill: fills.chrome }, turn)\n    draw(\"circle\", { cx: x, cy: SPOOL_Y, r: 1.6, fill: \"#2A2D31\" }, turn)\n    return turn\n  })\n\n  // The type guide either side of the print point.\n  for (const x of [-23, 17]) {\n    draw(\n      \"rect\",\n      {\n        x,\n        y: 0,\n        width: 6,\n        height: 16,\n        rx: 1.6,\n        fill: fills.chromeV,\n        stroke: CHROME_EDGE,\n        \"stroke-width\": 0.8,\n      },\n      body\n    )\n  }\n\n  // Two-tone ribbon, black over red, through the vibrator.\n  const ribbon = [\n    {\n      path: draw(\n        \"path\",\n        {\n          fill: \"none\",\n          stroke: RIBBON_BLACK,\n          \"stroke-width\": 5.8,\n          \"stroke-linejoin\": \"round\",\n        },\n        body\n      ),\n      dy: 0,\n    },\n    {\n      path: draw(\n        \"path\",\n        {\n          fill: \"none\",\n          stroke: RIBBON_RED,\n          \"stroke-width\": 2.6,\n          \"stroke-linejoin\": \"round\",\n        },\n        body\n      ),\n      dy: 1.5,\n    },\n  ]\n  const vibrator = draw(\"g\", {}, body)\n  for (const [stroke, width] of [\n    [CHROME_EDGE, 3.8],\n    [CHROME, 2],\n  ] as const) {\n    draw(\n      \"path\",\n      {\n        d: \"M-12 2.5V11.5H12V2.5\",\n        fill: \"none\",\n        stroke,\n        \"stroke-width\": width,\n        \"stroke-linejoin\": \"round\",\n        \"stroke-linecap\": \"round\",\n      },\n      vibrator\n    )\n  }\n\n  // Keyboard well.\n  draw(\n    \"path\",\n    {\n      d: \"M-204 112H204Q217 112 219 125L233 240Q235 254 220 254H-220Q-235 254 -233 240L-219 125Q-217 112 -204 112Z\",\n      fill: fills.well,\n    },\n    body\n  )\n  draw(\n    \"path\",\n    {\n      d: \"M-219.5 126Q-217.5 111 -204 111H204Q217.5 111 219.5 126\",\n      fill: \"none\",\n      stroke: enamel.shine,\n      \"stroke-width\": 1.3,\n      \"stroke-opacity\": 0.8,\n    },\n    body\n  )\n  draw(\n    \"path\",\n    {\n      d: \"M-226 254.6H226\",\n      stroke: enamel.shine,\n      \"stroke-width\": 1.2,\n      \"stroke-opacity\": 0.6,\n    },\n    body\n  )\n\n  const ry = KEY_R * KEY_TILT\n  const height = 4.5\n  /** A round key on its stem, seen from above: rim, cap, legend, shadow. */\n  const keyAt = (x: number, y: number, label: string, ch: string) => {\n    draw(\n      \"ellipse\",\n      {\n        cx: x + 2,\n        cy: y + 21,\n        rx: 11,\n        ry: 4,\n        fill: fills.keyShadow,\n      },\n      body\n    )\n    draw(\n      \"rect\",\n      {\n        x: x - 1.5,\n        y: y + 4,\n        width: 3,\n        height: 19,\n        rx: 1,\n        fill: fills.chromeV,\n      },\n      body\n    )\n    const cap = draw(\"g\", {}, body)\n    draw(\n      \"path\",\n      {\n        d: `M${x - KEY_R} ${y}V${y + height}A${KEY_R} ${ry} 0 0 0 ${x + KEY_R} ${y + height}V${y}A${KEY_R} ${ry} 0 0 1 ${x - KEY_R} ${y}Z`,\n        fill: fills.capSide,\n      },\n      cap\n    )\n    draw(\"ellipse\", { cx: x, cy: y, rx: KEY_R, ry, fill: fills.chrome }, cap)\n    draw(\n      \"ellipse\",\n      {\n        cx: x,\n        cy: y + 0.3,\n        rx: KEY_R - 2.3,\n        ry: ry - 1.6,\n        fill: fills.capTop,\n      },\n      cap\n    )\n    draw(\n      \"ellipse\",\n      {\n        cx: x - 3.4,\n        cy: y - 2.6,\n        rx: 4.4,\n        ry: 1.6,\n        fill: \"#fff\",\n        \"fill-opacity\": 0.2,\n      },\n      cap\n    )\n    const text = draw(\n      \"text\",\n      {\n        x,\n        y: y + 0.7,\n        \"text-anchor\": \"middle\",\n        \"dominant-baseline\": \"central\",\n        \"font-size\": 9.6,\n        \"font-weight\": 600,\n        fill: LEGEND,\n        transform: `matrix(1 0 0 0.74 0 ${(y * 0.26).toFixed(2)})`,\n      },\n      cap\n    )\n    text.textContent = label\n    draw(\n      \"path\",\n      {\n        d: `M${x - KEY_R + 3.6} ${y - 0.4}A${KEY_R - 3.6} ${ry - 2.3} 0 0 1 ${x + KEY_R - 3.6} ${y - 0.4}`,\n        fill: \"none\",\n        stroke: \"#fff\",\n        \"stroke-width\": 0.9,\n        \"stroke-opacity\": 0.32,\n        \"stroke-linecap\": \"round\",\n      },\n      cap\n    )\n    cap.setAttribute(\"data-key\", ch)\n    return cap\n  }\n\n  const keys = new Map<string, Key>()\n  const placed: { x: number; key: Key }[] = []\n  KEY_ROWS.forEach((row, r) => {\n    Array.from(row).forEach((ch, i) => {\n      const x = -157.5 + (r - 1.5) * 9 + i * KEY_PITCH\n      const key: Key = {\n        cap: keyAt(x, KEY_Y[r]!, ch.toUpperCase(), ch),\n        bar: null,\n        v: 0,\n      }\n      keys.set(ch, key)\n      placed.push({ x, key })\n    })\n  })\n\n  /** A pill key (shift, space): same rim and cap, stretched. */\n  const pill = (x: number, y: number, w: number, legend?: string) => {\n    for (const sx of [x - w * 0.3, x + w * 0.3]) {\n      draw(\n        \"rect\",\n        {\n          x: sx - 1.5,\n          y: y + 4,\n          width: 3,\n          height: 17,\n          rx: 1,\n          fill: fills.chromeV,\n        },\n        body\n      )\n    }\n    draw(\n      \"ellipse\",\n      {\n        cx: x + 2,\n        cy: y + 19,\n        rx: w / 2 + 2,\n        ry: 4,\n        fill: fills.keyShadow,\n      },\n      body\n    )\n    const cap = draw(\"g\", {}, body)\n    const r = ry\n    draw(\n      \"rect\",\n      {\n        x: x - w / 2,\n        y: y - r + height,\n        width: w,\n        height: r * 2,\n        rx: r,\n        fill: fills.capSide,\n      },\n      cap\n    )\n    draw(\n      \"rect\",\n      {\n        x: x - w / 2,\n        y: y - r,\n        width: w,\n        height: r * 2,\n        rx: r,\n        fill: fills.chrome,\n      },\n      cap\n    )\n    draw(\n      \"rect\",\n      {\n        x: x - w / 2 + 2.3,\n        y: y - r + 1.6,\n        width: w - 4.6,\n        height: r * 2 - 3.2,\n        rx: r - 1.6,\n        fill: fills.capTop,\n      },\n      cap\n    )\n    if (legend) {\n      draw(\"path\", { d: legend, fill: LEGEND }, cap)\n    }\n    return cap\n  }\n  const y3 = KEY_Y[3]!\n  const shifts = [-1, 1].map((side) => {\n    const x = side * 201\n    const arrow = `M${x} ${y3 - 3.6}L${x + 4} ${y3 + 0.6}H${x + 1.6}V${y3 + 3.4}H${x - 1.6}V${y3 + 0.6}H${x - 4}Z`\n    const cap = pill(x, y3, 30, arrow)\n    cap.setAttribute(\"data-key\", \"shift\")\n    return { cap, bar: null, v: 0 } satisfies Key\n  })\n\n  // Space bar: a chrome bar on two arms.\n  for (const sx of [-80, 80]) {\n    draw(\n      \"rect\",\n      {\n        x: sx - 1.5,\n        y: 247,\n        width: 3,\n        height: 7,\n        fill: fills.chromeV,\n      },\n      body\n    )\n  }\n  const spaceCap = draw(\"g\", { \"data-key\": \" \" }, body)\n  draw(\n    \"rect\",\n    {\n      x: -112,\n      y: 242,\n      width: 224,\n      height: 9,\n      rx: 4.5,\n      fill: \"#4E555B\",\n    },\n    spaceCap\n  )\n  draw(\n    \"rect\",\n    {\n      x: -112,\n      y: 239.5,\n      width: 224,\n      height: 8,\n      rx: 4,\n      fill: fills.chrome,\n    },\n    spaceCap\n  )\n  const space: Key = { cap: spaceCap, bar: null, v: 0 }\n\n  // One typebar per key, fanned left to right in key order.\n  const overlay = draw(\"g\", {}, rig)\n  placed.sort((a, b) => a.x - b.x)\n  const bars = placed.map(({ key }, i) => {\n    const angle = -SPREAD + (2 * SPREAD * i) / (placed.length - 1)\n    const pivot = polar(PIVOT_R, angle)\n    const tip = polar(REST_R, angle)\n    const rest = draw(\"g\", {}, basket)\n    draw(\n      \"line\",\n      {\n        x1: pivot[0],\n        y1: pivot[1],\n        x2: tip[0],\n        y2: tip[1],\n        stroke: i % 2 ? \"#C4C9CE\" : \"#E6E9EC\",\n        \"stroke-width\": 1.25,\n        \"stroke-linecap\": \"round\",\n      },\n      rest\n    )\n    const [sx, sy] = polar(REST_R + 3.4, angle)\n    draw(\n      \"line\",\n      {\n        x1: sx,\n        y1: sy,\n        x2: tip[0],\n        y2: tip[1],\n        stroke: \"#7D848A\",\n        \"stroke-width\": 2.6,\n        \"stroke-linecap\": \"round\",\n      },\n      rest\n    )\n    const strike = draw(\"g\", { display: \"none\" }, overlay)\n    const line = (stroke: string, width: number) =>\n      draw(\n        \"line\",\n        { stroke, \"stroke-width\": width, \"stroke-linecap\": \"round\" },\n        strike\n      )\n    const edge = line(\"#1C1E21\", 3.9)\n    const core = line(\"#E2E5E8\", 1.8)\n    const slug = line(\"#2A2D31\", 5.6)\n    const bar: Bar = { rest, strike, edge, core, slug, pivot, tip, v: 0 }\n    key.bar = bar\n    return bar\n  })\n\n  return {\n    columns,\n    rig,\n    inkFills,\n    carriage,\n    paper,\n    sheet,\n    shadow,\n    ink,\n    lever,\n    leverPivot,\n    knobs,\n    keys,\n    shifts,\n    space,\n    basket,\n    bars,\n    ribbon,\n    vibrator,\n    spools,\n  }\n}\n\ntype Motion = {\n  key: string\n  start: number\n  ms: number\n  ease: (t: number) => number\n  run: (v: number) => void\n  begin?: () => void\n}\n\nlet machineIds = 0\n\n/**\n * A typewriter that types. Each letter presses its key, swings that key's\n * typebar up out of the basket to strike the ribbon, and the carriage\n * steps one character left. Capitals hold shift, which drops the basket. At\n * the margin the return lever kicks, the platen turns up a line, and the\n * carriage slides home. With `loop`, the finished sheet is pulled out and\n * a fresh one rolls in. `color` is the enamel; chrome, rubber, and the\n * ivory sheet are fixed. `prefers-reduced-motion` prints the whole page at\n * once.\n */\nexport function createTypewriter(\n  root: HTMLElement,\n  initial: TypewriterOptions = {}\n): TypewriterInstance {\n  let options: TypewriterOptions = { ...initial }\n  const textOf = () => options.text ?? DEFAULT_TEXT\n  const speedOf = () => numberOr(options.speed, DEFAULT_SPEED, 1, 60)\n  const holdOf = () => numberOr(options.hold, DEFAULT_HOLD, 0, 60000)\n  const startOf = () =>\n    numberOr(options.startDelay, DEFAULT_START_DELAY, 0, 60000)\n  const jitterOf = () => numberOr(options.jitter, DEFAULT_JITTER, 0, 1)\n  const columnsOf = () =>\n    Math.round(numberOr(options.columns, DEFAULT_COLUMNS, 16, 60))\n  const id = `typewriter-${++machineIds}`\n\n  // Screen readers get the whole text once; the machine is decoration.\n  const spoken = document.createElement(\"span\")\n  Object.assign(spoken.style, {\n    position: \"absolute\",\n    width: \"1px\",\n    height: \"1px\",\n    margin: \"-1px\",\n    padding: \"0\",\n    overflow: \"hidden\",\n    clip: \"rect(0 0 0 0)\",\n    whiteSpace: \"nowrap\",\n    border: \"0\",\n  })\n  const svg = draw(\"svg\", {\n    width: \"100%\",\n    height: \"100%\",\n    preserveAspectRatio: \"xMidYMid meet\",\n    \"aria-hidden\": \"true\",\n  })\n  svg.style.display = \"block\"\n  root.append(spoken, svg)\n\n  let M!: Machine\n\n  /* ---------------------------------------------------------------- */\n  /* Drawing                                                           */\n  /* ---------------------------------------------------------------- */\n\n  const build = () => {\n    M = drawMachine(\n      svg,\n      id,\n      columnsOf(),\n      options.color ?? DEFAULT_COLOR,\n      options.label\n    )\n    setInteractive()\n  }\n\n  /* ---------------------------------------------------------------- */\n  /* Poses                                                             */\n  /* ---------------------------------------------------------------- */\n\n  const pose = {\n    carriage: 0,\n    paper: 0,\n    knob: 0,\n    spool: 0,\n    lever: 0,\n    shift: 0,\n    ribbon: 0,\n  }\n\n  const carriageAt = (col: number) => -(col * CW + CW / 2)\n\n  const setCarriage = (x: number) => {\n    pose.carriage = x\n    M.carriage.setAttribute(\"transform\", `translate(${x.toFixed(2)} 0)`)\n  }\n  /** Sheet lean, a spring driven by how fast the carriage moves. */\n  const flex = { angle: 0, vel: 0, x: 0, t: 0 }\n  const placePaper = () => {\n    const y = pose.paper\n    const a = flex.angle\n    M.paper.setAttribute(\n      \"transform\",\n      Math.abs(a) < 0.01\n        ? `translate(0 ${y.toFixed(2)})`\n        : `translate(0 ${FLEX_ANCHOR}) skewX(${a.toFixed(3)}) translate(0 ${(y - FLEX_ANCHOR).toFixed(2)})`\n    )\n  }\n  const setPaper = (y: number) => {\n    pose.paper = y\n    placePaper()\n  }\n  /** Knurling on the platen knobs, scrolling as the platen turns. */\n  const setKnob = (phase: number) => {\n    pose.knob = phase\n    for (const knob of M.knobs) {\n      knob.lines.forEach((line, i) => {\n        const a = phase + (i / RIDGES) * TAU\n        const facing = Math.cos(a)\n        if (facing <= 0.05) {\n          line.setAttribute(\"stroke-opacity\", \"0\")\n          return\n        }\n        const y = (23 + Math.sin(a) * 19).toFixed(2)\n        line.setAttribute(\"y1\", y)\n        line.setAttribute(\"y2\", y)\n        line.setAttribute(\"stroke-opacity\", (0.18 + facing * 0.42).toFixed(2))\n      })\n    }\n  }\n  const setSpool = (deg: number) => {\n    pose.spool = deg\n    M.spools.forEach((spool, i) => {\n      const x = i === 0 ? -SPOOL_X : SPOOL_X\n      spool.setAttribute(\n        \"transform\",\n        `rotate(${(i === 0 ? -deg : deg).toFixed(1)} ${x} ${SPOOL_Y})`\n      )\n    })\n  }\n  const setLever = (deg: number) => {\n    pose.lever = deg\n    const [x, y] = M.leverPivot\n    M.lever.setAttribute(\"transform\", `rotate(${deg.toFixed(2)} ${x} ${y})`)\n  }\n  const setShift = (v: number) => {\n    pose.shift = v\n    M.basket.setAttribute(\"transform\", `translate(0 ${(v * 4).toFixed(2)})`)\n    for (const key of M.shifts) setKey(key, v)\n  }\n  /** The ribbon vibrator lifts the ribbon over the print point. */\n  const setRibbon = (v: number) => {\n    pose.ribbon = v\n    const lift = v * 13\n    const y = 7.5 - lift\n    const top = SPOOL_Y - 24\n    for (const { path, dy } of M.ribbon) {\n      path.setAttribute(\n        \"d\",\n        `M${-SPOOL_X} ${top + dy}L-12 ${(y + dy).toFixed(2)}H12L${SPOOL_X} ${top + dy}`\n      )\n    }\n    M.vibrator.setAttribute(\"transform\", `translate(0 ${(-lift).toFixed(2)})`)\n  }\n  const setKey = (key: Key, v: number) => {\n    key.v = v\n    key.cap.setAttribute(\n      \"transform\",\n      v > 0.001 ? `translate(0 ${(v * KEY_TRAVEL).toFixed(2)})` : \"\"\n    )\n  }\n  /** 0 rests in the basket; 1 is the slug on the paper. */\n  const setBar = (bar: Bar, v: number) => {\n    bar.v = v\n    if (v <= 0.001) {\n      bar.rest.removeAttribute(\"display\")\n      bar.strike.setAttribute(\"display\", \"none\")\n      return\n    }\n    bar.rest.setAttribute(\"display\", \"none\")\n    bar.strike.removeAttribute(\"display\")\n    const drop = pose.shift * 4\n    const [px, py0] = bar.pivot\n    const py = py0 + drop\n    const tx = bar.tip[0] + (0 - bar.tip[0]) * v\n    const ty = bar.tip[1] + drop + (STRIKE_Y - bar.tip[1] - drop) * v\n    const len = Math.hypot(tx - px, ty - py) || 1\n    const ux = (tx - px) / len\n    const uy = (ty - py) / len\n    for (const line of [bar.edge, bar.core]) {\n      line.setAttribute(\"x1\", px.toFixed(2))\n      line.setAttribute(\"y1\", py.toFixed(2))\n      line.setAttribute(\"x2\", tx.toFixed(2))\n      line.setAttribute(\"y2\", ty.toFixed(2))\n    }\n    bar.slug.setAttribute(\"x1\", (tx - ux * 6).toFixed(2))\n    bar.slug.setAttribute(\"y1\", (ty - uy * 6).toFixed(2))\n    bar.slug.setAttribute(\"x2\", tx.toFixed(2))\n    bar.slug.setAttribute(\"y2\", ty.toFixed(2))\n  }\n\n  /** Everything at rest, the carriage and sheet where the text has got to. */\n  const restPose = () => {\n    setCarriage(carriageAt(cursor.col))\n    setPaper(-cursor.line * LH)\n    setKnob(pose.knob)\n    setSpool(pose.spool)\n    setLever(0)\n    setShift(capsLock ? 1 : 0)\n    setRibbon(0)\n    flex.angle = 0\n    flex.vel = 0\n    placePaper()\n    for (const key of M.keys.values()) setKey(key, 0)\n    setKey(M.space, 0)\n    for (const bar of M.bars) setBar(bar, 0)\n  }\n\n  /* ---------------------------------------------------------------- */\n  /* Motion                                                            */\n  /* ---------------------------------------------------------------- */\n\n  const queued: Motion[] = []\n  const running = new Map<string, Motion>()\n  let raf = 0\n\n  const frame = (now: number) => {\n    raf = 0\n    queued.sort((a, b) => a.start - b.start)\n    while (queued.length && queued[0]!.start <= now) {\n      const motion = queued.shift()!\n      motion.begin?.()\n      running.set(motion.key, motion)\n    }\n    for (const [key, motion] of running) {\n      const t = clamp((now - motion.start) / motion.ms, 0, 1)\n      motion.run(motion.ease(t))\n      if (t >= 1) running.delete(key)\n    }\n    // The sheet leans against the carriage's motion, then wobbles upright.\n    const dt = flex.t ? Math.min(0.05, (now - flex.t) / 1000) : 0\n    flex.t = now\n    if (dt > 0) {\n      const speed = (pose.carriage - flex.x) / dt\n      const target = clamp(speed * FLEX_GAIN, -FLEX_MAX, FLEX_MAX)\n      flex.vel += (-FLEX_K * (flex.angle - target) - FLEX_C * flex.vel) * dt\n      flex.angle += flex.vel * dt\n      placePaper()\n    }\n    flex.x = pose.carriage\n    const settling = Math.abs(flex.angle) > 0.02 || Math.abs(flex.vel) > 0.05\n    if (queued.length || running.size || settling) {\n      raf = requestAnimationFrame(frame)\n    } else {\n      flex.t = 0\n    }\n  }\n  const wake = () => {\n    if (!raf) raf = requestAnimationFrame(frame)\n  }\n  /** Run `run(0…1)` over `ms`. A motion with the same key replaces it. */\n  const play = (\n    key: string,\n    ms: number,\n    run: (v: number) => void,\n    {\n      delay = 0,\n      ease = linear,\n      begin,\n    }: {\n      delay?: number\n      ease?: (t: number) => number\n      begin?: () => void\n    } = {}\n  ) => {\n    queued.push({\n      key,\n      start: performance.now() + delay,\n      ms: Math.max(1, ms),\n      ease,\n      run,\n      begin,\n    })\n    wake()\n  }\n  /** Ease a pose from wherever it is when the motion starts. */\n  const tween = (\n    key: string,\n    get: () => number,\n    set: (v: number) => void,\n    to: number,\n    ms: number,\n    opts: { delay?: number; ease?: (t: number) => number } = {}\n  ) => {\n    let from = 0\n    play(key, ms, (v) => set(from + (to - from) * v), {\n      ...opts,\n      begin: () => {\n        from = get()\n      },\n    })\n  }\n  const stopMotion = () => {\n    queued.length = 0\n    running.clear()\n    cancelAnimationFrame(raf)\n    raf = 0\n  }\n\n  const press = (name: string, key: Key, ms: number, delay = 0) => {\n    let from = 0\n    play(name, ms, (t) => setKey(key, pulse(t, from, 0.22, 0.28)), {\n      delay,\n      begin: () => {\n        from = key.v\n      },\n    })\n  }\n\n  /* ---------------------------------------------------------------- */\n  /* Typing                                                            */\n  /* ---------------------------------------------------------------- */\n\n  let strokes: TypewriterStroke[] = []\n  /** Strokes on the page. */\n  let pos = 0\n  let cursor = { line: 0, col: 0 }\n  let sheetH = 600\n  let phase: \"waiting\" | \"typing\" | \"done\" | \"feeding\" | \"manual\" = \"waiting\"\n  /** Shift lock, from the machine's own shift keys. */\n  let capsLock = false\n  /** Next `src` for strokes typed by hand. */\n  let nextSrc = 0\n  let rang = false\n  let destroyed = false\n  let reduce = false\n  let onScreen = true\n  let sound: Sound | null = null\n\n  // One pending step, paused while the machine can't be seen.\n  let pending: (() => void) | null = null\n  let timer = 0\n  let remaining = 0\n  let dueAt = 0\n  const active = () =>\n    !destroyed && onScreen && !reduce && document.visibilityState !== \"hidden\"\n  const arm = () => {\n    dueAt = performance.now() + remaining\n    timer = window.setTimeout(() => {\n      timer = 0\n      const run = pending\n      pending = null\n      run?.()\n    }, remaining)\n  }\n  const schedule = (run: () => void, ms: number) => {\n    window.clearTimeout(timer)\n    timer = 0\n    pending = run\n    remaining = Math.max(0, ms)\n    if (active()) arm()\n  }\n  const cancel = () => {\n    window.clearTimeout(timer)\n    timer = 0\n    pending = null\n  }\n  const sync = () => {\n    if (active()) {\n      if (pending && !timer) arm()\n    } else if (timer) {\n      window.clearTimeout(timer)\n      timer = 0\n      remaining = Math.max(0, dueAt - performance.now())\n    }\n  }\n\n  const soundOn = () => {\n    if (!options.sound) return null\n    sound ??= createSound()\n    return sound\n  }\n\n  const after = (stroke: TypewriterStroke | undefined) => {\n    if (!stroke) return { line: 0, col: 0 }\n    return stroke.kind === \"char\"\n      ? { line: stroke.line, col: stroke.col + 1 }\n      : { line: stroke.line, col: 0 }\n  }\n\n  /**\n   * A letter as it lands: a little off its cell, sometimes under-inked\n   * where the ribbon missed, now and then struck twice.\n   */\n  const letter = (stroke: Extract<TypewriterStroke, { kind: \"char\" }>) => {\n    const jitter = jitterOf()\n    const n = Math.floor(stroke.src) * 8\n    const x = stroke.col * CW + CW / 2\n    const y = stroke.line * LH\n    const group = draw(\"g\", {}, M.ink)\n    const glyph = (attrs: Record<string, string | number>) => {\n      const el = draw(\"text\", { x, y, ...attrs }, group)\n      el.textContent = stroke.ch\n      return el\n    }\n    if (jitter <= 0) {\n      glyph({})\n      return group\n    }\n    const dx = (hash(n) - 0.5) * jitter * 1.1\n    const dy = (hash(n + 1) - 0.5) * jitter * 1.6\n    const tilt = (hash(n + 2) - 0.5) * jitter * 3.2\n    group.setAttribute(\n      \"transform\",\n      `translate(${dx.toFixed(2)} ${dy.toFixed(2)}) rotate(${tilt.toFixed(2)} ${x} ${y})`\n    )\n    const ink = 1 - hash(n + 3) * jitter * 0.38\n    const worn = hash(n + 4) < jitter * 0.6\n    glyph({\n      \"fill-opacity\": ink.toFixed(3),\n      ...(worn\n        ? {\n            fill: M.inkFills[Math.floor(hash(n + 5) * M.inkFills.length)]!,\n          }\n        : {}),\n    })\n    if (hash(n + 6) < jitter * 0.14) {\n      glyph({\n        \"fill-opacity\": (ink * 0.42).toFixed(3),\n        transform: `translate(${(0.45 + hash(n + 7) * 0.3).toFixed(2)} 0.3)`,\n      })\n    }\n    return group\n  }\n\n  const sizeSheet = () => {\n    const lines = (strokes.at(-1)?.line ?? 0) + 1\n    sheetH = Math.max(\n      TOP_MARGIN + lines * LH + 60,\n      (M.columns * CW + PAD * 2) * 1.3\n    )\n    M.sheet.setAttribute(\"height\", sheetH.toFixed(0))\n    M.shadow.setAttribute(\"height\", sheetH.toFixed(0))\n  }\n\n  /** Print the first `pos` strokes and park the machine, without motion. */\n  const paint = () => {\n    M.ink.replaceChildren()\n    for (let i = 0; i < pos; i++) {\n      const stroke = strokes[i]!\n      if (stroke.kind === \"char\" && stroke.ch !== \" \") letter(stroke)\n    }\n    if (phase !== \"manual\") cursor = after(strokes[pos - 1])\n    rang = cursor.col >= M.columns - BELL_CELLS\n    restPose()\n  }\n\n  const keyFor = (ch: string) => {\n    const lower = ch.toLowerCase()\n    const own = M.keys.get(lower)\n    if (own) return { key: own, shift: ch !== lower }\n    const base = SHIFTED[ch]\n    if (base) return { key: M.keys.get(base)!, shift: true }\n    // Anything the keyboard doesn't have borrows a key.\n    const all = [...M.keys.values()]\n    return {\n      key: all[(ch.codePointAt(0) ?? 0) % all.length]!,\n      shift: false,\n    }\n  }\n\n  const pace = (ch: string) => {\n    const base = 1000 / speedOf()\n    if (!(options.humanize ?? true)) return base\n    let factor = 0.55 + Math.random() * 0.9\n    if (ch === \" \") factor *= 1.15\n    else if (/[,;:]/.test(ch)) factor *= 2.4\n    else if (/[.!?]/.test(ch)) factor *= 3.4\n    if (Math.random() < 0.04) factor *= 2.6\n    return base * factor\n  }\n\n  /** Press the key, swing its bar into the ribbon, step the carriage. */\n  const strike = (\n    stroke: Extract<TypewriterStroke, { kind: \"char\" }>,\n    fixed?: number\n  ) => {\n    const base = 1000 / speedOf()\n    const ms = fixed ?? clamp(base * 1.7, 90, 170)\n    const audio = soundOn()\n    const step = carriageAt(stroke.col + 1)\n    cursor = { line: stroke.line, col: stroke.col + 1 }\n\n    if (stroke.ch === \" \") {\n      press(\"space\", M.space, ms)\n      tween(\"carriage\", () => pose.carriage, setCarriage, step, ms * 0.4, {\n        delay: ms * 0.2,\n        ease: easeOut,\n      })\n      audio?.key(true)\n    } else {\n      const { key, shift } = keyFor(stroke.ch)\n      const lead = shift ? ms * 0.25 : 0\n      const impact = lead + ms * 0.42\n      if (shift && !capsLock) {\n        let from = 0\n        play(\"shift\", ms * 1.6, (t) => setShift(pulse(t, from, 0.16, 0.5)), {\n          begin: () => {\n            from = pose.shift\n          },\n        })\n      }\n      press(`key-${stroke.ch.toLowerCase()}`, key, ms * 1.1, lead)\n      const bar = key.bar\n      if (bar) {\n        let from = 0\n        play(\n          `bar-${M.bars.indexOf(bar)}`,\n          ms,\n          (t) => {\n            const v =\n              t < 0.42\n                ? from + (1 - from) * easeIn(t / 0.42)\n                : 1 - easeOut((t - 0.42) / 0.58)\n            setBar(bar, v)\n          },\n          {\n            delay: lead,\n            begin: () => {\n              from = bar.v\n            },\n          }\n        )\n      }\n      let lifted = 0\n      play(\"ribbon\", ms * 0.9, (t) => setRibbon(pulse(t, lifted, 0.4, 0.08)), {\n        delay: lead + ms * 0.08,\n        begin: () => {\n          lifted = pose.ribbon\n        },\n      })\n      const mark = letter(stroke)\n      mark.setAttribute(\"opacity\", \"0\")\n      play(\n        `ink-${stroke.src}`,\n        60,\n        (v) => mark.setAttribute(\"opacity\", v.toFixed(3)),\n        { delay: impact }\n      )\n      // The whole machine takes the blow.\n      play(\n        \"shudder\",\n        110,\n        (v) => {\n          const y = Math.sin(v * Math.PI) * (1 - v) * 1.6\n          M.rig.setAttribute(\n            \"transform\",\n            y > 0.01 ? `translate(0 ${y.toFixed(2)})` : \"\"\n          )\n        },\n        { delay: impact }\n      )\n      tween(\"carriage\", () => pose.carriage, setCarriage, step, ms * 0.36, {\n        delay: impact + 6,\n        ease: easeOut,\n      })\n      tween(\"spool\", () => pose.spool, setSpool, pose.spool + 5, ms * 0.3, {\n        delay: impact,\n      })\n      if (audio) window.setTimeout(() => audio.key(false), impact)\n    }\n\n    if (\n      !rang &&\n      cursor.col >= M.columns - BELL_CELLS &&\n      M.columns > BELL_CELLS * 2\n    ) {\n      rang = true\n      audio?.bell()\n    }\n  }\n\n  /** Kick the lever, turn up a line, slide the carriage home. */\n  const carriageReturn = (\n    stroke: Extract<TypewriterStroke, { kind: \"return\" }>\n  ) => {\n    const glide = clamp(220 + stroke.from * 8, 260, 640)\n    cursor = { line: stroke.line, col: 0 }\n    rang = false\n    play(\"lever\", 420, (t) => setLever(-24 * pulse(t, 0, 0.3, 0.12)))\n    tween(\"paper\", () => pose.paper, setPaper, -stroke.line * LH, 220, {\n      delay: 60,\n      ease: easeInOut,\n    })\n    tween(\"knob\", () => pose.knob, setKnob, pose.knob + LH / KNOB_R, 220, {\n      delay: 60,\n      ease: easeInOut,\n    })\n    tween(\"carriage\", () => pose.carriage, setCarriage, carriageAt(0), glide, {\n      delay: 130,\n      ease: easeInOut,\n    })\n    soundOn()?.carriage(glide)\n    return glide + 130\n  }\n\n  const setPhase = (next: typeof phase) => {\n    phase = next\n  }\n\n  const finish = () => {\n    setPhase(\"done\")\n    options.onDone?.()\n    if (options.loop ?? true) schedule(feedOut, holdOf())\n  }\n\n  const step = () => {\n    if (pos >= strokes.length) {\n      finish()\n      return\n    }\n    setPhase(\"typing\")\n    const stroke = strokes[pos++]!\n    if (stroke.kind === \"char\") {\n      strike(stroke)\n      schedule(step, pace(stroke.ch))\n    } else {\n      const ms = carriageReturn(stroke)\n      schedule(step, ms + pace(\" \") * 0.8)\n    }\n  }\n\n  /** Roll a fresh sheet up from behind the platen. */\n  const feedIn = (then: () => void) => {\n    setPaper(40 + TOP_MARGIN)\n    tween(\"paper\", () => pose.paper, setPaper, 0, 900, { ease: easeOut })\n    tween(\"knob\", () => pose.knob, setKnob, pose.knob + 5, 900, {\n      ease: easeOut,\n    })\n    schedule(then, 940)\n  }\n\n  /** Pull the finished sheet up and out, bring the carriage home, go again. */\n  const feedOut = () => {\n    setPhase(\"feeding\")\n    const ms = 950\n    tween(\"paper\", () => pose.paper, setPaper, VIEW_TOP - sheetH - 20, ms, {\n      ease: easeIn,\n    })\n    tween(\"knob\", () => pose.knob, setKnob, pose.knob + 7, ms, {\n      ease: easeIn,\n    })\n    tween(\"carriage\", () => pose.carriage, setCarriage, carriageAt(0), 720, {\n      ease: easeInOut,\n    })\n    if (cursor.col > 0) {\n      play(\"lever\", 420, (t) => setLever(-24 * pulse(t, 0, 0.3, 0.12)))\n    }\n    schedule(() => {\n      pos = 0\n      paint()\n      setPhase(\"waiting\")\n      feedIn(() => schedule(step, startOf() * 0.5))\n    }, ms + 40)\n  }\n\n  const start = () => {\n    cancel()\n    stopMotion()\n    capsLock = false\n    strokes = layoutTypewriter(textOf(), M.columns)\n    spoken.textContent = textOf()\n    sizeSheet()\n    if (reduce) {\n      pos = strokes.length\n      setPhase(\"done\")\n      paint()\n      return\n    }\n    pos = 0\n    setPhase(\"waiting\")\n    paint()\n    feedIn(() => schedule(step, startOf()))\n  }\n\n  /** Redraw for a new line length, keeping the place in the text. */\n  const rebuild = () => {\n    const at = strokes[pos - 1]?.src ?? -1\n    stopMotion()\n    build()\n    if (phase === \"manual\") {\n      sizeSheet()\n      paint()\n      return\n    }\n    strokes = layoutTypewriter(textOf(), M.columns)\n    if (phase === \"done\") pos = strokes.length\n    else {\n      pos = 0\n      while (pos < strokes.length && strokes[pos]!.src <= at) pos += 1\n    }\n    sizeSheet()\n    paint()\n    if (phase === \"typing\" || phase === \"feeding\") {\n      setPhase(\"typing\")\n      schedule(step, 200)\n    } else if (phase === \"waiting\") schedule(step, startOf())\n  }\n\n  /* ---------------------------------------------------------------- */\n  /* Typing by hand                                                    */\n  /* ---------------------------------------------------------------- */\n\n  const interactiveOf = () => options.interactive ?? true\n\n  /** The first key from a person stops the script; the page stays. */\n  const takeOver = () => {\n    if (phase === \"manual\") return\n    cancel()\n    if (phase === \"feeding\" || phase === \"waiting\") {\n      stopMotion()\n      strokes = phase === \"feeding\" ? [] : strokes.slice(0, pos)\n    } else {\n      strokes = strokes.slice(0, pos)\n    }\n    pos = strokes.length\n    cursor = after(strokes[pos - 1])\n    nextSrc = Math.floor(strokes.at(-1)?.src ?? -1) + 1\n    setPhase(\"manual\")\n    sizeSheet()\n    if (!running.size) paint()\n  }\n\n  const typeReturn = () => {\n    takeOver()\n    const stroke: TypewriterStroke = {\n      kind: \"return\",\n      line: cursor.line + 1,\n      from: cursor.col,\n      src: nextSrc++,\n    }\n    strokes.push(stroke)\n    pos = strokes.length\n    sizeSheet()\n    if (reduce) {\n      cursor = after(stroke)\n      setPaper(-cursor.line * LH)\n      setCarriage(carriageAt(0))\n      return\n    }\n    carriageReturn(stroke)\n  }\n\n  const typeKey = (ch: string) => {\n    takeOver()\n    // No margin release: at the margin the carriage returns on its own.\n    if (cursor.col >= M.columns) typeReturn()\n    const stroke: Extract<TypewriterStroke, { kind: \"char\" }> = {\n      kind: \"char\",\n      ch,\n      line: cursor.line,\n      col: cursor.col,\n      src: nextSrc++,\n    }\n    strokes.push(stroke)\n    pos = strokes.length\n    if (reduce) {\n      if (ch !== \" \") letter(stroke)\n      cursor = after(stroke)\n      setCarriage(carriageAt(cursor.col))\n      return\n    }\n    strike(stroke, 120)\n  }\n\n  /** Backspace moves the carriage back a space; the next letter overstrikes. */\n  const typeBack = () => {\n    takeOver()\n    if (cursor.col === 0) return\n    cursor = { line: cursor.line, col: cursor.col - 1 }\n    if (reduce) {\n      setCarriage(carriageAt(cursor.col))\n      return\n    }\n    tween(\n      \"carriage\",\n      () => pose.carriage,\n      setCarriage,\n      carriageAt(cursor.col),\n      90,\n      {\n        ease: easeOut,\n      }\n    )\n    soundOn()?.key(true)\n  }\n\n  const setShiftLock = (on: boolean) => {\n    capsLock = on\n    if (reduce) setShift(on ? 1 : 0)\n    else\n      tween(\"shift\", () => pose.shift, setShift, on ? 1 : 0, 130, {\n        ease: easeOut,\n      })\n  }\n\n  const onKeyDown = (event: KeyboardEvent) => {\n    if (!interactiveOf() || event.ctrlKey || event.metaKey || event.altKey) {\n      return\n    }\n    const { key } = event\n    if (key === \"Enter\") {\n      if (!event.repeat) typeReturn()\n    } else if (key === \"Backspace\") {\n      typeBack()\n    } else if (key.length === 1) {\n      // A real machine doesn't auto-repeat.\n      if (!event.repeat) typeKey(key)\n    } else {\n      return\n    }\n    event.preventDefault()\n  }\n\n  const onPointerDown = (event: PointerEvent) => {\n    if (!interactiveOf() || event.button !== 0) return\n    root.focus({ preventScroll: true })\n    const hit = (event.target as Element | null)?.closest?.(\"[data-key]\")\n    const key = hit?.getAttribute(\"data-key\")\n    if (key == null) return\n    event.preventDefault()\n    if (key === \"shift\") setShiftLock(!capsLock)\n    else if (key === \"return\") typeReturn()\n    else typeKey(capsLock ? key.toUpperCase() : key)\n  }\n\n  /** Focus, keyboard, and clickable parts follow `interactive`. */\n  function setInteractive() {\n    const on = interactiveOf()\n    if (on) {\n      root.tabIndex = 0\n      root.setAttribute(\"role\", \"group\")\n      root.setAttribute(\n        \"aria-label\",\n        \"Typewriter. Focus it and type, or click its keys.\"\n      )\n    } else {\n      root.removeAttribute(\"tabindex\")\n      root.removeAttribute(\"role\")\n      root.removeAttribute(\"aria-label\")\n    }\n    for (const el of svg.querySelectorAll<SVGElement>(\"[data-key]\")) {\n      el.style.cursor = on ? \"pointer\" : \"\"\n    }\n  }\n\n  root.addEventListener(\"keydown\", onKeyDown)\n  svg.addEventListener(\"pointerdown\", onPointerDown)\n\n  /* ---------------------------------------------------------------- */\n  /* Theme                                                             */\n  /* ---------------------------------------------------------------- */\n\n  const isDark = () => {\n    const html = document.documentElement\n    if (html.classList.contains(\"dark\")) return true\n    if (html.classList.contains(\"light\")) return false\n    const attr = html.getAttribute(\"data-theme\")\n    if (attr === \"dark\") return true\n    if (attr === \"light\") return false\n    return window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n  }\n  /** Ivory in light, a touch dimmer in dark so it doesn't glare. */\n  const applyTheme = () => {\n    root.style.setProperty(\n      \"--typewriter-sheet\",\n      isDark() ? \"#ECE7DA\" : \"#FBF9F3\"\n    )\n  }\n\n  build()\n  applyTheme()\n\n  const mqReduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n  reduce = mqReduce.matches\n  const onReduce = () => {\n    reduce = mqReduce.matches\n    start()\n  }\n  mqReduce.addEventListener(\"change\", onReduce)\n\n  start()\n\n  const theme = new MutationObserver(applyTheme)\n  theme.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: [\"class\", \"data-theme\", \"style\"],\n  })\n  const mqDark = window.matchMedia(\"(prefers-color-scheme: dark)\")\n  mqDark.addEventListener(\"change\", applyTheme)\n\n  const io = new IntersectionObserver(([entry]) => {\n    onScreen = entry?.isIntersecting ?? true\n    sync()\n  })\n  io.observe(root)\n  const onVisibility = () => sync()\n  document.addEventListener(\"visibilitychange\", onVisibility)\n\n  return {\n    setOptions(next) {\n      const prev = options\n      options = { ...options, ...next }\n      if (textOf() !== (prev.text ?? DEFAULT_TEXT)) {\n        start()\n        return\n      }\n      if (\n        columnsOf() !== M.columns ||\n        options.color !== prev.color ||\n        options.label !== prev.label\n      ) {\n        rebuild()\n      }\n      if (!options.sound && sound) {\n        // Sound switched off: release the audio context, not just mute it.\n        sound.close()\n        sound = null\n      }\n      if (options.interactive !== prev.interactive) setInteractive()\n      else if (options.jitter !== prev.jitter) {\n        for (const motion of running.values()) motion.run(1)\n        stopMotion()\n        paint()\n      }\n      const loop = options.loop ?? true\n      if (loop !== (prev.loop ?? true) && phase === \"done\") {\n        if (loop) schedule(feedOut, holdOf())\n        else cancel()\n      }\n    },\n    restart: start,\n    destroy() {\n      destroyed = true\n      cancel()\n      stopMotion()\n      theme.disconnect()\n      mqDark.removeEventListener(\"change\", applyTheme)\n      io.disconnect()\n      mqReduce.removeEventListener(\"change\", onReduce)\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n      root.removeEventListener(\"keydown\", onKeyDown)\n      svg.removeEventListener(\"pointerdown\", onPointerDown)\n      for (const name of [\"tabindex\", \"role\", \"aria-label\"]) {\n        root.removeAttribute(name)\n      }\n      sound?.close()\n      root.style.removeProperty(\"--typewriter-sheet\")\n      spoken.remove()\n      svg.remove()\n    },\n  }\n}\n\nexport type TypewriterProps = TypewriterOptions & {\n  className?: string\n}\n\n/**\n * A typewriter that types: each letter presses its key, swings that key's\n * typebar up to strike the ribbon, and steps the carriage left. At the\n * margin the lever kicks, the platen turns up a line, and the carriage\n * slides home. Ink follows `currentColor`. Honors\n * `prefers-reduced-motion`.\n */\nexport function Typewriter({\n  className,\n  text = DEFAULT_TEXT,\n  speed = DEFAULT_SPEED,\n  humanize = true,\n  loop = true,\n  hold = DEFAULT_HOLD,\n  startDelay = DEFAULT_START_DELAY,\n  color = DEFAULT_COLOR,\n  columns = DEFAULT_COLUMNS,\n  jitter = DEFAULT_JITTER,\n  sound = false,\n  interactive = true,\n  label,\n  onDone,\n}: TypewriterProps) {\n  const rootRef = useRef<HTMLDivElement>(null)\n  const instanceRef = useRef<TypewriterInstance | null>(null)\n  const onDoneRef = useRef(onDone)\n\n  useEffect(() => {\n    onDoneRef.current = onDone\n  }, [onDone])\n\n  useEffect(() => {\n    const root = rootRef.current\n    if (!root) return\n    instanceRef.current = createTypewriter(root, {\n      text,\n      speed,\n      humanize,\n      loop,\n      hold,\n      startDelay,\n      color,\n      columns,\n      jitter,\n      sound,\n      interactive,\n      label,\n      onDone: () => onDoneRef.current?.(),\n    })\n    return () => {\n      instanceRef.current?.destroy()\n      instanceRef.current = null\n    }\n    // Engine reads live options via setOptions; mount once.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [])\n\n  useEffect(() => {\n    instanceRef.current?.setOptions({\n      text,\n      speed,\n      humanize,\n      loop,\n      hold,\n      startDelay,\n      color,\n      columns,\n      jitter,\n      sound,\n      interactive,\n      label,\n    })\n  }, [\n    text,\n    speed,\n    humanize,\n    loop,\n    hold,\n    startDelay,\n    color,\n    columns,\n    jitter,\n    sound,\n    interactive,\n    label,\n  ])\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"typewriter\"\n      className={cn(\n        \"relative size-full overflow-hidden bg-background font-mono text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset\",\n        className\n      )}\n    />\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/ui/typewriter.tsx"
    }
  ],
  "type": "registry:ui"
}