{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"word-captions","type":"registry:component","title":"Word Captions","description":"TikTok-style captions: animated subtitles with word pop, Hormozi and MrBeast styles for Reels and Shorts. Burned-in captions in the styles big channels actually use — heavy Montserrat, a real outside outline so they read on any footage, and the spoken word springing to an accent.","dependencies":["remotion","@remotion/google-fonts"],"docs":"Needs a Remotion project. If a frame renders black, the component is drawing on a transparent layer: put a background behind it, e.g. <AbsoluteFill style={{ background: \"#faf9f6\" }}><Component /></AbsoluteFill>. Pass mode=\"dark\" for dark frames.","registryDependencies":["https://kuchi.kalarislabs.com/r/kuchi-ui.json"],"files":[{"path":"components/kuchi/word-captions.tsx","type":"registry:component","target":"components/kuchi/word-captions.tsx","content":"/*! Portions Copyright (c) 2026 Sri Nath (snap-cn). MIT License. See THIRD_PARTY_LICENSES. */\n\"use client\";\r\n\r\nimport { loadFont } from \"@remotion/google-fonts/Montserrat\";\r\nimport { loadFont as loadRoboto } from \"@remotion/google-fonts/Roboto\";\r\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\r\nimport {\r\n  continueRender,\r\n  delayRender,\r\n  getRemotionEnvironment,\r\n  interpolate,\r\n  spring,\r\n  useCurrentFrame,\r\n  useVideoConfig,\r\n} from \"remotion\";\r\nimport {\r\n  resolveFont,\r\n  type KuchiTheme,\r\n  useKuchiTheme,\r\n  withAlpha,\r\n} from \"@/lib/kuchi-ui\";\r\n\r\n// Montserrat, 700–900. This is the face the look is actually made of: the caption\r\n// styles every big channel uses are a heavy geometric grotesque, and Inter at 700\r\n// simply is not heavy enough to carry a stroke. Loaded through\r\n// @remotion/google-fonts so the Player, the mp4 and a user's project all agree.\r\nconst { fontFamily: MONTSERRAT, waitUntilDone: montserratReady } = loadFont(\r\n  \"normal\",\r\n  {\r\n    weights: [\"700\", \"800\", \"900\"],\r\n    subsets: [\"latin\"],\r\n  },\r\n);\r\n\r\n// The `boxed` look is the YouTube/CapCut auto-caption, and that is set in Roboto\r\n// — a neutral grotesque, not a geometric one. Montserrat would read as a logo.\r\nconst { fontFamily: ROBOTO } = loadRoboto(\"normal\", {\r\n  weights: [\"500\", \"700\"],\r\n  subsets: [\"latin\"],\r\n});\r\n\r\nexport type CaptionAspect = \"16:9\" | \"1:1\" | \"9:16\";\r\nexport type CaptionActiveStyle = \"pop\" | \"highlight\" | \"color\";\r\n\r\n/**\r\n * The four looks, and they are not invented — they are the caption styles that\r\n * actually run on big channels:\r\n *\r\n * - `beast`   — ALL CAPS, Montserrat Black, white with a heavy black outline and a\r\n *               hard shadow; the spoken word snaps to yellow and springs. The\r\n *               YouTube-hook look.\r\n * - `hormozi` — same weight class, but the spoken word lands inside a filled\r\n *               rounded block that cycles through an accent set. Reads at a glance\r\n *               on a phone.\r\n * - `pop`     — sentence case, outlined, the spoken word takes the accent and pops.\r\n *               Punchy without shouting.\r\n * - `clean`   — a quiet pill. No outline. For product footage where captions are\r\n *               support, not the show. (The old default.)\r\n */\r\nexport type CaptionPreset =\r\n  | \"boxed\"\r\n  | \"youtube\"\r\n  | \"beast\"\r\n  | \"hormozi\"\r\n  | \"pop\"\r\n  | \"clean\";\r\n\r\nexport interface CaptionWord {\r\n  text: string;\r\n  startFrame: number;\r\n  /** Defaults to the next word's startFrame (or startFrame + fallback for the last word). */\r\n  endFrame?: number;\r\n}\r\n\r\n/** A caption word with its endFrame resolved. */\r\nexport interface TimedWord {\r\n  text: string;\r\n  startFrame: number;\r\n  endFrame: number;\r\n}\r\n\r\n/** One caption beat: 1–3 words shown together in the pill. */\r\nexport interface CaptionGroup {\r\n  words: TimedWord[];\r\n  startFrame: number;\r\n  endFrame: number;\r\n}\r\n\r\nexport interface WordCaptionsProps {\r\n  /**\r\n   * Word-level captions in MILLISECONDS — the shape Whisper, whisper.cpp, CapCut,\r\n   * Submagic and Remotion's own `@remotion/captions` all speak. This is the input\r\n   * you will actually have.\r\n   */\r\n  captions?: Caption[];\r\n  /** An .srt, pasted straight in. Cues are split into words automatically. */\r\n  srt?: string;\r\n  /** The look. See {@link CaptionPreset}. */\r\n  preset?: CaptionPreset;\r\n  /** Words per page. Defaults per preset. */\r\n  maxWords?: number;\r\n  /** Character budget per page — what stops a page wrapping into a tower. */\r\n  maxChars?: number;\r\n  /** A pause longer than this (ms) starts a new page. */\r\n  pageBreakMs?: number;\r\n  /**\r\n   * Outline width, as a fraction of the font size. This is what makes a caption\r\n   * legible on ANY footage, and it is why hand-rolled captions look cheap without\r\n   * it. 0 turns it off.\r\n   */\r\n  strokeRatio?: number;\r\n  strokeColor?: string;\r\n  /** Force upper case. Defaults per preset — the loud ones shout.  */\r\n  uppercase?: boolean;\r\n  /** Accent set the `hormozi` block cycles through, one colour per beat. */\r\n  accentCycle?: string[];\r\n  /**\r\n   * Timed transcript. Pass an array of `{ text, startFrame, endFrame? }`\r\n   * (e.g. mapped from Whisper word timestamps), or a plain string that is\r\n   * paced evenly at `framesPerWord`.\r\n   */\r\n  words?: CaptionWord[] | string;\r\n  /** Tokens shown per caption beat (1–3). */\r\n  groupSize?: number;\r\n  /** How the currently-spoken word is emphasized. */\r\n  activeStyle?: CaptionActiveStyle;\r\n  /** Safe-area position preset for the target frame shape. */\r\n  aspect?: CaptionAspect;\r\n  /** Max width of the caption block in px. */\r\n  maxWidth?: number;\r\n  fontSize?: number;\r\n  /** Overrides the design system's `foreground`. */\r\n  textColor?: string;\r\n  /** Design-system token overrides. */\r\n  theme?: Partial<KuchiTheme>;\r\n  /** Defaults to `\"dark\"` — a caption scrim is lit for footage. */\r\n  mode?: \"light\" | \"dark\";\r\n  /**\r\n   * The face this scene paints its words in — a label from `fonts.ts`\r\n   * (\"Inter\", \"Space Grotesk\", \"Instrument Serif\") or a CSS family you have\r\n   * loaded yourself. Unset, the scene keeps the face it was designed around.\r\n   *\r\n   * Overrides `theme.fontFamily`, which is how a brand kit re-skins a whole\r\n   * timeline from one value.\r\n   */\r\n  fontFamily?: string;\r\n  /** Backdrop pill behind the caption line. Any CSS color; empty string hides it. */\r\n  pillColor?: string;\r\n  /** Active-word accent used by the `highlight` and `color` styles. */\r\n  accentColor?: string;\r\n  /** Pacing (frames per word) used when `words` is a plain string. */\r\n  framesPerWord?: number;\r\n  fontWeight?: number;\r\n  speed?: number;\r\n  className?: string;\r\n}\r\n\r\n/**\r\n * Bottom inset of the caption block per aspect, as a percentage of the\r\n * composition height — keeps captions clear of platform chrome (9:16 stays\r\n * above the feed UI, 16:9 sits in the lower third).\r\n */\r\nexport const SAFE_AREA_BOTTOM_PCT: Record<CaptionAspect, number> = {\r\n  \"16:9\": 8,\r\n  \"1:1\": 11,\r\n  \"9:16\": 20,\r\n};\r\n\r\n/** Clamps the beat size to the supported 1–3 token range. */\r\nexport function clampGroupSize(groupSize: number): number {\r\n  if (!Number.isFinite(groupSize)) return 1;\r\n  return Math.min(3, Math.max(1, Math.floor(groupSize)));\r\n}\r\n\r\n/** Evenly paces a plain transcript string into timed words. */\r\nexport function scheduleWords(\r\n  text: string,\r\n  framesPerWord: number,\r\n  startFrame = 0,\r\n): CaptionWord[] {\r\n  const pace = Math.max(1, framesPerWord);\r\n  return text\r\n    .split(/\\s+/)\r\n    .filter((token) => token.length > 0)\r\n    .map((token, i) => ({\r\n      text: token,\r\n      startFrame: startFrame + i * pace,\r\n      endFrame: startFrame + (i + 1) * pace,\r\n    }));\r\n}\r\n\r\n/**\r\n * Fills in missing endFrames: a word ends when the next one starts, and the\r\n * last word holds for `fallbackFrames`. Every word lasts at least 1 frame.\r\n */\r\nexport function resolveWordTimings(\r\n  words: CaptionWord[],\r\n  fallbackFrames: number,\r\n): TimedWord[] {\r\n  return words.map((word, i) => {\r\n    const next = words[i + 1];\r\n    const endFrame =\r\n      word.endFrame ??\r\n      (next ? next.startFrame : word.startFrame + Math.max(1, fallbackFrames));\r\n    return {\r\n      text: word.text,\r\n      startFrame: word.startFrame,\r\n      endFrame: Math.max(endFrame, word.startFrame + 1),\r\n    };\r\n  });\r\n}\r\n\r\n/** Chunks timed words into caption beats of `groupSize` tokens. */\r\nexport function groupWords(\r\n  words: TimedWord[],\r\n  groupSize: number,\r\n): CaptionGroup[] {\r\n  const size = clampGroupSize(groupSize);\r\n  const groups: CaptionGroup[] = [];\r\n  for (let i = 0; i < words.length; i += size) {\r\n    const chunk = words.slice(i, i + size);\r\n    groups.push({\r\n      words: chunk,\r\n      startFrame: chunk[0].startFrame,\r\n      endFrame: chunk[chunk.length - 1].endFrame,\r\n    });\r\n  }\r\n  return groups;\r\n}\r\n\r\n/** Index of the group on screen at `frame`, or -1 when no caption shows. */\r\nexport function activeGroupIndex(\r\n  groups: CaptionGroup[],\r\n  frame: number,\r\n): number {\r\n  for (let i = groups.length - 1; i >= 0; i--) {\r\n    if (frame >= groups[i].startFrame && frame < groups[i].endFrame) return i;\r\n  }\r\n  return -1;\r\n}\r\n\r\nexport interface CaptionLook {\r\n  weight: number;\r\n  uppercase: boolean;\r\n  /** Words per page, and the character budget that keeps a page on 1–2 lines. */\r\n  maxWords: number;\r\n  maxChars: number;\r\n  /** Font size as a fraction of the composition's SHORT side, so it reads the\r\n   *  same on 9:16 and 16:9 instead of shrinking to nothing on one of them. */\r\n  sizeRatio: number;\r\n  strokeRatio: number;\r\n  tracking: string;\r\n  /** Scale the spoken word springs to. */\r\n  pop: number;\r\n  /** Does the spoken word sit inside a filled block? */\r\n  block: boolean;\r\n  pill: boolean;\r\n  shadow: boolean;\r\n  /** Per-line solid box behind the whole line (YouTube auto-caption look). */\r\n  box?: boolean;\r\n}\r\n\r\n/**\r\n * Sizes are a fraction of the frame's SHORT side. The old default was 54px on a\r\n * 1920-tall frame — 2.8% of its height — which is a subtitle, not a caption. These\r\n * run 11–13% of the short side, which is where burned-in captions actually live.\r\n */\r\nexport const CAPTION_LOOKS: Record<CaptionPreset, CaptionLook> = {\r\n  /**\r\n   * The default: the YouTube / TikTok auto-caption look — white text on a solid\r\n   * black box that wraps each line tight (`box-decoration-break: clone`). No\r\n   * outline, no pop; the box carries the contrast. Clean and unmistakable.\r\n   */\r\n  boxed: {\r\n    weight: 700,\r\n    uppercase: false,\r\n    maxWords: 7,\r\n    maxChars: 28,\r\n    sizeRatio: 0.062,\r\n    strokeRatio: 0,\r\n    tracking: \"-0.005em\",\r\n    pop: 1,\r\n    block: false,\r\n    pill: false,\r\n    shadow: false,\r\n    box: true,\r\n  },\r\n  /**\r\n   * The default, and the one you actually see under a talking head: a phrase per\r\n   * page, big enough to read on a phone but small enough to stay on 1–2 lines, with\r\n   * the spoken word lit up inside it. This is what Submagic / Opus / CapCut put out\r\n   * and what most channels burn in.\r\n   */\r\n  youtube: {\r\n    weight: 800,\r\n    uppercase: false,\r\n    maxWords: 6,\r\n    maxChars: 26,\r\n    sizeRatio: 0.075,\r\n    strokeRatio: 0.075,\r\n    tracking: \"-0.015em\",\r\n    pop: 1.07,\r\n    block: false,\r\n    pill: false,\r\n    shadow: true,\r\n  },\r\n  beast: {\r\n    weight: 900,\r\n    uppercase: true,\r\n    maxWords: 3,\r\n    maxChars: 16,\r\n    sizeRatio: 0.125,\r\n    strokeRatio: 0.1,\r\n    tracking: \"-0.005em\",\r\n    pop: 1.14,\r\n    block: false,\r\n    pill: false,\r\n    shadow: true,\r\n  },\r\n  hormozi: {\r\n    weight: 800,\r\n    uppercase: true,\r\n    maxWords: 3,\r\n    maxChars: 14,\r\n    sizeRatio: 0.115,\r\n    strokeRatio: 0.085,\r\n    tracking: \"-0.005em\",\r\n    pop: 1.06,\r\n    block: true,\r\n    pill: false,\r\n    shadow: true,\r\n  },\r\n  pop: {\r\n    weight: 800,\r\n    uppercase: false,\r\n    maxWords: 4,\r\n    maxChars: 22,\r\n    sizeRatio: 0.11,\r\n    strokeRatio: 0.07,\r\n    tracking: \"-0.015em\",\r\n    pop: 1.12,\r\n    block: false,\r\n    pill: false,\r\n    shadow: true,\r\n  },\r\n  clean: {\r\n    weight: 700,\r\n    uppercase: false,\r\n    maxWords: 8,\r\n    maxChars: 42,\r\n    sizeRatio: 0.06,\r\n    strokeRatio: 0,\r\n    tracking: \"-0.01em\",\r\n    pop: 1.06,\r\n    block: false,\r\n    pill: true,\r\n    shadow: false,\r\n  },\r\n};\r\n\r\n/** The accent set the `hormozi` block cycles through, one colour per beat. */\r\nexport const DEFAULT_ACCENT_CYCLE = [\r\n  \"#27E36B\",\r\n  \"#FFE81F\",\r\n  \"#FF4D4D\",\r\n  \"#3EA8FF\",\r\n];\r\n\r\n/**\r\n * The spoken word's scale. A spring with a little overshoot — a caption that eases\r\n * politely into place does not read as a caption, it reads as a lower third.\r\n */\r\nexport function popScale(\r\n  frame: number,\r\n  startFrame: number,\r\n  fps: number,\r\n  peak: number,\r\n): number {\r\n  const s = spring({\r\n    frame: frame - startFrame,\r\n    fps,\r\n    config: { damping: 11, stiffness: 190, mass: 0.7 },\r\n    durationInFrames: 14,\r\n  });\r\n  return 1 + (peak - 1) * s;\r\n}\r\n\r\n/* ---------------------------------------------------------------------------\r\n * Real transcripts. This is the part that makes the component usable.\r\n *\r\n * Nobody has frame numbers. A caption comes out of Whisper, whisper.cpp, CapCut,\r\n * Submagic, Opus Clip or Descript, and it comes out in MILLISECONDS — or as an\r\n * .srt file. Remotion's own `@remotion/captions` type is `{ text, startMs, endMs }`,\r\n * and that is the shape the whole ecosystem speaks.\r\n *\r\n * So that is the shape this takes. Paste a Whisper JSON, or paste an .srt straight\r\n * in. The frame maths is ours, not yours.\r\n * ------------------------------------------------------------------------- */\r\n\r\n/** The standard caption token. Structurally identical to `@remotion/captions`. */\r\nexport interface Caption {\r\n  text: string;\r\n  startMs: number;\r\n  endMs: number;\r\n}\r\n\r\n/** ms → frame, at the composition's own rate. */\r\nexport function msToFrame(ms: number, fps: number): number {\r\n  return (ms / 1000) * fps;\r\n}\r\n\r\n/**\r\n * Word-level captions from an SRT. Handles both `,` and `.` as the millisecond\r\n * separator (Whisper writes commas; some tools write dots), and multi-line cues.\r\n */\r\nexport function parseSrt(srt: string): Caption[] {\r\n  const out: Caption[] = [];\r\n  const blocks = srt\r\n    .replace(/\\r/g, \"\")\r\n    .trim()\r\n    .split(/\\n\\s*\\n/);\r\n  for (const raw of blocks) {\r\n    const lines = raw.split(\"\\n\").filter((l) => l.trim().length > 0);\r\n    if (lines.length === 0) continue;\r\n    const timeLine = lines.find((l) => l.includes(\"-->\"));\r\n    if (!timeLine) continue;\r\n    const [from, to] = timeLine.split(\"-->\").map((t) => t.trim());\r\n    const startMs = srtTimeToMs(from);\r\n    const endMs = srtTimeToMs(to);\r\n    if (startMs === null || endMs === null) continue;\r\n    const text = lines\r\n      .filter((l) => l !== timeLine && !/^\\d+$/.test(l.trim()))\r\n      .join(\" \")\r\n      .trim();\r\n    if (text.length > 0) out.push({ text, startMs, endMs });\r\n  }\r\n  return out;\r\n}\r\n\r\n/** `00:00:01,234` (or `.234`, or `00:01,234`) → 1234. Null when it isn't a timestamp. */\r\nexport function srtTimeToMs(stamp: string): number | null {\r\n  const m = stamp.trim().match(/^(?:(\\d+):)?(\\d+):(\\d+)[,.](\\d{1,3})$/);\r\n  if (!m) return null;\r\n  const [, h, min, sec, frac] = m;\r\n  return (\r\n    (h ? Number(h) : 0) * 3600000 +\r\n    Number(min) * 60000 +\r\n    Number(sec) * 1000 +\r\n    // `padEnd(3, \"0\")` without the ES2017 lib a stock Remotion project lacks.\r\n    Number(frac + \"000\".slice(frac.length))\r\n  );\r\n}\r\n\r\n/**\r\n * An SRT cue is usually a whole phrase, not a word. Split it into words and spread\r\n * them across the cue so the active-word highlight still has something to track.\r\n * (Word-level Whisper output needs none of this — it already IS one word per cue.)\r\n */\r\nexport function explodeCue(caption: Caption): Caption[] {\r\n  const words = caption.text.split(/\\s+/).filter(Boolean);\r\n  if (words.length <= 1) return [caption];\r\n  const span = Math.max(1, caption.endMs - caption.startMs);\r\n  const per = span / words.length;\r\n  return words.map((text, i) => ({\r\n    text,\r\n    startMs: caption.startMs + i * per,\r\n    endMs: caption.startMs + (i + 1) * per,\r\n  }));\r\n}\r\n\r\n/** Captions (ms) → the internal frame-timed model. */\r\nexport function captionsToWords(\r\n  captions: Caption[],\r\n  fps: number,\r\n  explode = true,\r\n): TimedWord[] {\r\n  // `concat(...map)`, not `flatMap` (ES2019): stock Remotion types ES2015.\r\n  const tokens = explode\r\n    ? ([] as Caption[]).concat(...captions.map((c) => explodeCue(c)))\r\n    : captions;\r\n  return tokens.map((c) => ({\r\n    text: c.text,\r\n    startFrame: msToFrame(c.startMs, fps),\r\n    endFrame: Math.max(msToFrame(c.endMs, fps), msToFrame(c.startMs, fps) + 1),\r\n  }));\r\n}\r\n\r\nexport interface PageOptions {\r\n  /** Hard cap on words per page. */\r\n  maxWords: number;\r\n  /** Character budget, so a page actually FITS the frame instead of wrapping to a tower. */\r\n  maxChars: number;\r\n  /** A pause longer than this starts a new page — that is where a sentence breaks. */\r\n  maxGapFrames: number;\r\n}\r\n\r\n/**\r\n * Group words into PAGES the way real caption tools do — by the shape of the speech,\r\n * not by a fixed count.\r\n *\r\n * A page ends when it runs out of words, runs out of characters, or the speaker\r\n * pauses. The old `groupWords` chopped every 3 words regardless, which is how you\r\n * end up with \"STOP / LOSING / HOURS\" stacked in a tower: three words that never\r\n * belonged on their own page.\r\n */\r\nexport function buildPages(\r\n  words: TimedWord[],\r\n  opts: PageOptions,\r\n): CaptionGroup[] {\r\n  const pages: CaptionGroup[] = [];\r\n  let current: TimedWord[] = [];\r\n  let chars = 0;\r\n\r\n  const flush = () => {\r\n    if (current.length === 0) return;\r\n    pages.push({\r\n      words: current,\r\n      startFrame: current[0].startFrame,\r\n      endFrame: current[current.length - 1].endFrame,\r\n    });\r\n    current = [];\r\n    chars = 0;\r\n  };\r\n\r\n  for (const word of words) {\r\n    const prev = current[current.length - 1];\r\n    const gap = prev ? word.startFrame - prev.endFrame : 0;\r\n    const wouldOverflow =\r\n      current.length >= Math.max(1, opts.maxWords) ||\r\n      chars + word.text.length + 1 > Math.max(1, opts.maxChars);\r\n\r\n    if (prev && (wouldOverflow || gap > opts.maxGapFrames)) flush();\r\n\r\n    current.push(word);\r\n    chars += word.text.length + 1;\r\n  }\r\n  flush();\r\n  return pages;\r\n}\r\n\r\n/**\r\n * Burned-in captions, in the styles big channels actually use.\r\n *\r\n * Three things separate a premium caption from a subtitle, and all three are here:\r\n *\r\n * 1. **The outline.** A caption has to be legible over footage it has never seen —\r\n *    a face, a sky, a white desk. A heavy black outline does that, and nothing else\r\n *    does. It has to be an OUTSIDE outline: `-webkit-text-stroke` centres the stroke\r\n *    on the glyph, so half of it eats inwards and the letterform goes thin and\r\n *    mushy (measured: a 14px stroke takes a 38px stem down to 22px). `paint-order:\r\n *    stroke fill` draws the stroke first and the fill over it, and the stem comes\r\n *    back to 38px. That one line is most of the look.\r\n * 2. **The weight and the size.** Montserrat 800–900, at 11–13% of the frame's\r\n *    short side. The old default was 2.8%.\r\n * 3. **The spoken word pops.** A spring with overshoot, not an ease.\r\n *\r\n * That pop is a scale on text, which is where captions usually fall apart: a browser\r\n * gives glyph origins no vertical sub-pixel precision, so a scale that moves the\r\n * baseline makes the word climb the pixel grid in whole-pixel jumps. The scale\r\n * pivots on the **measured baseline**, so the baseline's device Y never changes.\r\n */\r\nexport function WordCaptions({\r\n  captions,\r\n  srt,\r\n  words = \"Stop losing hours to manual invoices\",\r\n  preset = \"boxed\",\r\n  maxWords,\r\n  maxChars,\r\n  pageBreakMs = 420,\r\n  groupSize,\r\n  activeStyle = \"pop\",\r\n  aspect = \"16:9\",\r\n  maxWidth,\r\n  fontSize,\r\n  textColor,\r\n  pillColor,\r\n  theme,\r\n  mode,\r\n  fontFamily,\r\n  accentColor = \"#FFE81F\",\r\n  accentCycle = DEFAULT_ACCENT_CYCLE,\r\n  strokeColor = \"#000000\",\r\n  strokeRatio,\r\n  uppercase,\r\n  framesPerWord = 14,\r\n  fontWeight,\r\n  speed = 1,\r\n  className,\r\n}: WordCaptionsProps) {\r\n  const frame = useCurrentFrame() * speed;\r\n  const { fps, width, height } = useVideoConfig();\r\n  // A caption pill is a legibility scrim over footage, so its neutrals come\r\n  // from the dark end of the system by default. The accent, the outline and\r\n  // the cycle are the caption's look and stay props (design-system Rule 3c).\r\n  const t = useKuchiTheme(theme, mode ?? \"dark\");\r\n  const face = resolveFont(fontFamily ?? t.fontFamily) ?? MONTSERRAT;\r\n  const ink = textColor ?? t.foreground;\r\n  const scrim = pillColor ?? withAlpha(t.background, 0.55);\r\n\r\n  const look = CAPTION_LOOKS[preset] ?? CAPTION_LOOKS.beast;\r\n  const shortSide = Math.min(width, height);\r\n  // 0 (or omitted) means \"the preset decides\" — the preset IS the design, so a\r\n  // customizer knob that silently overrode it would make every preset identical.\r\n  const size =\r\n    fontSize && fontSize > 0\r\n      ? fontSize\r\n      : Math.round(look.sizeRatio * shortSide);\r\n  const weight = fontWeight && fontWeight > 0 ? fontWeight : look.weight;\r\n  const stroke =\r\n    (strokeRatio !== undefined && strokeRatio >= 0\r\n      ? strokeRatio\r\n      : look.strokeRatio) * size;\r\n  const caps = uppercase ?? look.uppercase;\r\n  const block = maxWidth && maxWidth > 0 ? maxWidth : Math.round(width * 0.86);\r\n\r\n  // Real captions first, the toy string last. `captions` (ms) and `srt` are what a\r\n  // user actually has; `words` (frames) is the legacy path; a bare string is a demo.\r\n  const timed: TimedWord[] = captions?.length\r\n    ? captionsToWords(captions, fps)\r\n    : srt && srt.trim().length > 0\r\n      ? captionsToWords(parseSrt(srt), fps)\r\n      : resolveWordTimings(\r\n          typeof words === \"string\"\r\n            ? scheduleWords(words, framesPerWord)\r\n            : words,\r\n          framesPerWord,\r\n        );\r\n\r\n  // Pages, not fixed-size chunks. `groupSize` still forces a hard count if you pass\r\n  // it, so nothing that relied on it breaks.\r\n  const groups = groupSize\r\n    ? groupWords(timed, groupSize)\r\n    : buildPages(timed, {\r\n        maxWords: maxWords ?? look.maxWords,\r\n        maxChars: maxChars ?? look.maxChars,\r\n        maxGapFrames: (pageBreakMs / 1000) * fps,\r\n      });\r\n  const groupIdx = activeGroupIndex(groups, frame);\r\n  const group = groupIdx === -1 ? null : groups[groupIdx];\r\n\r\n  // The baseline inside a word span, measured once. Guessing it from a line-height\r\n  // ratio is what makes a popping word judder: the pivot has to be exact.\r\n  const probeRef = useRef<HTMLSpanElement>(null);\r\n  const baseRef = useRef<HTMLSpanElement>(null);\r\n  const [baselineY, setBaselineY] = useState<number | null>(null);\r\n  // The delayRender exists only to hold the *mp4 render* on its first frame until\r\n  // the baseline is measured — there the font is already loaded, so that one\r\n  // measurement is exact. In the Player we never block: `baselineY === null`\r\n  // falls back to a line-height pivot until the mount measurement lands, which is\r\n  // invisible on a looping preview. Blocking the Player here is what stranded\r\n  // every caption card behind an orphaned delayRender handle that React\r\n  // StrictMode's double-invoked initializer creates and never clears.\r\n  const [handle] = useState(() =>\r\n    getRemotionEnvironment().isRendering\r\n      ? delayRender(\"word-captions: measuring the baseline for the pop pivot\")\r\n      : null,\r\n  );\r\n\r\n  useLayoutEffect(() => {\r\n    const probe = probeRef.current;\r\n    const base = baseRef.current;\r\n    if (probe && base) {\r\n      setBaselineY(\r\n        base.getBoundingClientRect().top - probe.getBoundingClientRect().top,\r\n      );\r\n    } else if (handle != null) {\r\n      // Nothing to measure in a render — release it rather than hang the frame.\r\n      continueRender(handle);\r\n    }\r\n    // Re-measure once Montserrat lands: a best-effort refinement for the Player\r\n    // (the render already has the font). Never blocks — the pivot above is set.\r\n    let cancelled = false;\r\n    void montserratReady().then(() => {\r\n      if (cancelled) return;\r\n      const p = probeRef.current;\r\n      const b = baseRef.current;\r\n      if (p && b) {\r\n        setBaselineY(\r\n          b.getBoundingClientRect().top - p.getBoundingClientRect().top,\r\n        );\r\n      }\r\n    });\r\n    return () => {\r\n      cancelled = true;\r\n    };\r\n  }, [handle]);\r\n\r\n  // In a render, release the held first frame the moment the baseline is known.\r\n  useEffect(() => {\r\n    if (baselineY != null && handle != null) continueRender(handle);\r\n  }, [baselineY, handle]);\r\n\r\n  const accent =\r\n    look.block && accentCycle.length > 0\r\n      ? accentCycle[Math.max(0, groupIdx) % accentCycle.length]\r\n      : accentColor;\r\n\r\n  const lineHeight = Math.round(size * 1.14);\r\n  const willChange = getRemotionEnvironment().isRendering\r\n    ? undefined\r\n    : (\"transform\" as const);\r\n\r\n  const typeStyle = {\r\n    fontFamily: face,\r\n    fontWeight: weight,\r\n    fontSize: size,\r\n    lineHeight: `${lineHeight}px`,\r\n    letterSpacing: look.tracking,\r\n    // Hinting re-snaps every stem to the pixel grid as a word scales, and the\r\n    // letterforms visibly boil. This turns it off.\r\n    textRendering: \"geometricPrecision\" as const,\r\n    fontVariantLigatures: \"none\" as const,\r\n  };\r\n\r\n  const outline =\r\n    stroke > 0\r\n      ? {\r\n          WebkitTextStrokeWidth: `${stroke}px`,\r\n          WebkitTextStrokeColor: strokeColor,\r\n          // Draw the stroke, THEN the fill on top of it. Without this the stroke is\r\n          // centred on the outline and eats the letterform from the inside.\r\n          paintOrder: \"stroke fill\" as const,\r\n        }\r\n      : {};\r\n\r\n  const shadow = look.shadow\r\n    ? {\r\n        textShadow: `0 ${size * 0.055}px ${size * 0.05}px ${withAlpha(\r\n          t.background,\r\n          0.42,\r\n        )}`,\r\n      }\r\n    : {};\r\n\r\n  return (\r\n    <div\r\n      className={className}\r\n      style={{\r\n        position: \"absolute\",\r\n        inset: 0,\r\n        display: \"flex\",\r\n        alignItems: \"flex-end\",\r\n        justifyContent: \"center\",\r\n        paddingBottom: `${SAFE_AREA_BOTTOM_PCT[aspect] ?? SAFE_AREA_BOTTOM_PCT[\"9:16\"]}%`,\r\n        paddingLeft: \"5%\",\r\n        paddingRight: \"5%\",\r\n        pointerEvents: \"none\",\r\n      }}\r\n    >\r\n      {/* Off-screen probe: one word, same type, with a zero-sized inline-block\r\n          sitting on its baseline. Read once, used as the pivot for every pop. */}\r\n      <span\r\n        ref={probeRef}\r\n        aria-hidden\r\n        style={{\r\n          ...typeStyle,\r\n          position: \"absolute\",\r\n          left: -99999,\r\n          top: 0,\r\n          visibility: \"hidden\",\r\n          display: \"inline-block\",\r\n        }}\r\n      >\r\n        Hg\r\n        <span\r\n          ref={baseRef}\r\n          style={{ display: \"inline-block\", width: 0, height: 0 }}\r\n        />\r\n      </span>\r\n\r\n      {/* Boxed look: white text on a solid black box that clones per line. The\r\n          words stay inline (no flex, no per-word transform), so the background\r\n          wraps each line tight — the YouTube auto-caption look. */}\r\n      {group && look.box && (\r\n        <div\r\n          style={{\r\n            maxWidth: block,\r\n            textAlign: \"center\",\r\n            opacity: interpolate(frame - group.startFrame, [0, 3], [0, 1], {\r\n              extrapolateLeft: \"clamp\",\r\n              extrapolateRight: \"clamp\",\r\n            }),\r\n          }}\r\n        >\r\n          <span\r\n            style={{\r\n              ...typeStyle,\r\n              fontFamily: ROBOTO,\r\n              display: \"inline\",\r\n              color: ink,\r\n              backgroundColor: withAlpha(t.background, 0.9),\r\n              padding: `${size * 0.06}px ${size * 0.32}px`,\r\n              boxDecorationBreak: \"clone\",\r\n              WebkitBoxDecorationBreak: \"clone\",\r\n              lineHeight: `${Math.round(size * 1.46)}px`,\r\n              borderRadius: 2,\r\n            }}\r\n          >\r\n            {group.words\r\n              .map((w) => (caps ? w.text.toUpperCase() : w.text))\r\n              .join(\" \")}\r\n          </span>\r\n        </div>\r\n      )}\r\n\r\n      {group && !look.box && (\r\n        <div\r\n          style={{\r\n            display: \"flex\",\r\n            flexWrap: \"wrap\",\r\n            alignItems: \"flex-end\",\r\n            justifyContent: \"center\",\r\n            // px, not em: `em` here would resolve against the CONTAINER's font size,\r\n            // which is the inherited 16px — not the caption's. That is how the words\r\n            // ended up welded together as \"STOPLOSING\".\r\n            columnGap: size * 0.26,\r\n            rowGap: size * 0.04,\r\n            maxWidth: block,\r\n            textAlign: \"center\",\r\n            ...(look.pill\r\n              ? {\r\n                  padding: `${size * 0.3}px ${size * 0.5}px`,\r\n                  borderRadius: size * 0.22,\r\n                  backgroundColor: pillColor === \"\" ? \"transparent\" : scrim,\r\n                }\r\n              : {}),\r\n            opacity: interpolate(frame - group.startFrame, [0, 3], [0, 1], {\r\n              extrapolateLeft: \"clamp\",\r\n              extrapolateRight: \"clamp\",\r\n            }),\r\n          }}\r\n        >\r\n          {group.words.map((word, i) => {\r\n            const spoken =\r\n              frame >= word.startFrame &&\r\n              (frame < word.endFrame || i === group.words.length - 1);\r\n            const isActive =\r\n              spoken && frame >= word.startFrame && frame < word.endFrame;\r\n\r\n            const scale =\r\n              isActive && activeStyle === \"pop\"\r\n                ? popScale(frame, word.startFrame, fps, look.pop)\r\n                : 1;\r\n\r\n            // Not yet spoken words in a beat stay white; the spoken one takes the\r\n            // accent (or the block). That is what makes the beat readable AHEAD of\r\n            // the voice instead of only with it.\r\n            const useAccent = isActive && activeStyle !== \"pop\";\r\n            const fill = look.block ? ink : isActive ? accent : ink;\r\n\r\n            return (\r\n              <span\r\n                key={`${word.text}-${word.startFrame}`}\r\n                style={{\r\n                  ...typeStyle,\r\n                  ...outline,\r\n                  ...shadow,\r\n                  display: \"inline-block\",\r\n                  color: useAccent ? accent : fill,\r\n                  transform: `scale(${scale})`,\r\n                  // The pivot is the BASELINE, not the middle of the box. 50% 100%\r\n                  // is the bottom of the box, which sits a descent BELOW the\r\n                  // baseline — it drags the word down the pixel grid as it scales.\r\n                  transformOrigin:\r\n                    baselineY === null ? \"50% 85%\" : `50% ${baselineY}px`,\r\n                  willChange,\r\n                  ...(look.block && isActive\r\n                    ? {\r\n                        backgroundColor: accent,\r\n                        borderRadius: size * 0.12,\r\n                        padding: `0 ${size * 0.1}px`,\r\n                        // The block wants the fill on top of the stroke too, or the\r\n                        // stroke shows as a dark halo inside the block.\r\n                        WebkitTextStrokeWidth: `${stroke * 0.6}px`,\r\n                      }\r\n                    : {}),\r\n                }}\r\n              >\r\n                {caps ? word.text.toUpperCase() : word.text}\r\n              </span>\r\n            );\r\n          })}\r\n        </div>\r\n      )}\r\n    </div>\r\n  );\r\n}\r\n"}]}