{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"karaoke-captions","type":"registry:component","title":"Karaoke Captions","description":"Karaoke captions: word-by-word highlighted subtitles synced to speech. A caption line that fills word by word as it is spoken — heavy outlined type that reads on any footage.","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>.","registryDependencies":["https://kuchi.kalarislabs.com/r/kuchi-ui.json"],"files":[{"path":"components/kuchi/karaoke-captions.tsx","type":"registry:component","target":"components/kuchi/karaoke-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  Easing,\r\n  getRemotionEnvironment,\r\n  interpolate,\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// The face the look is made of. Inter at 600 is a subtitle; a caption is a heavy\r\n// geometric grotesque carrying an outline.\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 auto-caption, which is set in Roboto — a\r\n// neutral grotesque, not a geometric one.\r\nconst { fontFamily: ROBOTO } = loadRoboto(\"normal\", {\r\n  weights: [\"500\", \"700\"],\r\n  subsets: [\"latin\"],\r\n});\r\n\r\nexport type CaptionTheme = \"light\" | \"dark\";\r\nexport type SafeAreaPreset = \"landscape\" | \"portrait\" | \"square\";\r\n\r\nexport interface CaptionLine {\r\n  text: string;\r\n  /** First frame the line is on screen and the fill sweep begins. */\r\n  startFrame: number;\r\n  /** Frame the sweep completes; the line fades out shortly after. */\r\n  endFrame: number;\r\n  /**\r\n   * Absolute frame each word starts filling (one entry per word).\r\n   * Omitted → words are spread evenly across [startFrame, endFrame].\r\n   */\r\n  wordTimings?: number[];\r\n  /** Word indices rendered in the accent color with a subtle scale-up. */\r\n  emphasize?: number[];\r\n}\r\n\r\nexport interface KaraokeCaptionsProps {\r\n  /**\r\n   * Word-level captions in MILLISECONDS — the shape Whisper, CapCut and Remotion's\r\n   * own `@remotion/captions` all speak. This is the input you will actually have.\r\n   */\r\n  captions?: Caption[];\r\n  /** An .srt, pasted straight in. */\r\n  srt?: string;\r\n  /** The look. See {@link KaraokePreset}. */\r\n  preset?: KaraokePreset;\r\n  /** Outline width as a fraction of the font size. 0 turns it off. */\r\n  strokeRatio?: number;\r\n  strokeColor?: string;\r\n  uppercase?: boolean;\r\n  /** Timed caption lines. Omit to build a single line from `text`. */\r\n  lines?: CaptionLine[];\r\n  /** Convenience single line used when `lines` is not provided. */\r\n  text?: string;\r\n  /** Comma-separated words of `text` to emphasize (case-insensitive). */\r\n  emphasize?: string;\r\n  /** Design-system token overrides. */\r\n  theme?: Partial<KuchiTheme>;\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  /** Light or dark pill chrome. */\r\n  mode?: CaptionTheme;\r\n  /** Color of emphasized words. */\r\n  accentColor?: string;\r\n  fontSize?: number;\r\n  fontWeight?: number;\r\n  /** Safe-area preset positioning the caption block per aspect ratio. */\r\n  aspect?: SafeAreaPreset;\r\n  /** Rounded surface behind the line. */\r\n  pill?: boolean;\r\n  /** Scale emphasized words grow to as their fill completes. */\r\n  emphasisScale?: number;\r\n  /** Unfilled (not-yet-spoken) word color override. Defaults per theme. */\r\n  baseColor?: string;\r\n  /** Filled (spoken) word color override. Defaults per theme. */\r\n  fillColor?: string;\r\n  speed?: number;\r\n  className?: string;\r\n}\r\n\r\n/**\r\n * The looks.\r\n *\r\n * - `karaoke`   — a heavy outlined line; each word snaps from dimmed to full white\r\n *                 as it is spoken. The read-along look.\r\n * - `highlight` — the spoken word rides a rounded accent bar that sweeps along the\r\n *                 line, like a marker running under the voice.\r\n * - `clean`     — the quiet pill. No outline. (The old default.)\r\n */\r\nexport type KaraokePreset = \"boxed\" | \"karaoke\" | \"highlight\" | \"clean\";\r\n\r\nexport interface KaraokeLook {\r\n  weight: number;\r\n  uppercase: boolean;\r\n  /** Font size as a fraction of the frame's SHORT side. */\r\n  sizeRatio: number;\r\n  strokeRatio: number;\r\n  bar: boolean;\r\n  pill: boolean;\r\n  shadow: boolean;\r\n  /** Per-line solid box behind the line (YouTube auto-caption look). */\r\n  box?: boolean;\r\n}\r\n\r\nexport const KARAOKE_LOOKS: Record<KaraokePreset, KaraokeLook> = {\r\n  /**\r\n   * The default: the YouTube auto-caption — white Roboto on a solid black box\r\n   * that wraps each line tight (`box-decoration-break: clone`). No outline, no\r\n   * sweep; the box carries the contrast.\r\n   */\r\n  boxed: {\r\n    weight: 700,\r\n    uppercase: false,\r\n    sizeRatio: 0.062,\r\n    strokeRatio: 0,\r\n    bar: false,\r\n    pill: false,\r\n    shadow: false,\r\n    box: true,\r\n  },\r\n  karaoke: {\r\n    weight: 900,\r\n    uppercase: true,\r\n    sizeRatio: 0.085,\r\n    strokeRatio: 0.09,\r\n    bar: false,\r\n    pill: false,\r\n    shadow: true,\r\n  },\r\n  highlight: {\r\n    weight: 800,\r\n    uppercase: false,\r\n    sizeRatio: 0.08,\r\n    strokeRatio: 0.07,\r\n    bar: true,\r\n    pill: false,\r\n    shadow: true,\r\n  },\r\n  clean: {\r\n    weight: 600,\r\n    uppercase: false,\r\n    sizeRatio: 0.067,\r\n    strokeRatio: 0,\r\n    bar: false,\r\n    pill: true,\r\n    shadow: false,\r\n  },\r\n};\r\n\r\n/** Frames the line takes to rise/fade in and to fade out past `endFrame`. */\r\nexport const LINE_FADE_FRAMES = 8;\r\n\r\n/**\r\n * The pill's chrome, taken from the design system.\r\n *\r\n * A caption pill IS app chrome — a card floating over footage — so it follows\r\n * the tokens. The burned-in type it carries does not: its accent, its outline\r\n * and its white fill are the caption's look, and stay props.\r\n */\r\nexport function karaokePalette(t: KuchiTheme): {\r\n  base: string;\r\n  fill: string;\r\n  pillBg: string;\r\n  pillBorder: string;\r\n  pillShadow: string;\r\n} {\r\n  return {\r\n    base: t.mutedForeground,\r\n    fill: t.foreground,\r\n    pillBg: withAlpha(t.card, 0.92),\r\n    pillBorder: t.border,\r\n    pillShadow: `0 8px 24px ${withAlpha(t.foreground, 0.1)}`,\r\n  };\r\n}\r\n\r\n/**\r\n * Aspect-ratio safe areas for social placements. Shared caption-block\r\n * positioning (portrait keeps clear of TikTok/Reels UI chrome).\r\n */\r\nexport const CAPTION_SAFE_AREAS: Record<\r\n  SafeAreaPreset,\r\n  { bottom: string; horizontal: string }\r\n> = {\r\n  landscape: { bottom: \"8%\", horizontal: \"10%\" },\r\n  portrait: { bottom: \"18%\", horizontal: \"7%\" },\r\n  square: { bottom: \"10%\", horizontal: \"8%\" },\r\n};\r\n\r\n/** Whitespace-split words, empties dropped. */\r\nexport function splitWords(text: string): string[] {\r\n  return text.split(/\\s+/).filter((w) => w.length > 0);\r\n}\r\n\r\nexport interface WordWindow {\r\n  start: number;\r\n  end: number;\r\n}\r\n\r\n/**\r\n * Per-word fill windows for a line. Uses `wordTimings` (absolute start\r\n * frames; a word ends when the next begins, the last at `endFrame`) when\r\n * provided, otherwise splits [startFrame, endFrame] evenly.\r\n */\r\nexport function wordWindows(line: CaptionLine): WordWindow[] {\r\n  const words = splitWords(line.text);\r\n  const n = words.length;\r\n  if (n === 0) return [];\r\n  const { startFrame, endFrame, wordTimings } = line;\r\n  if (wordTimings && wordTimings.length > 0) {\r\n    return words.map((_, i) => {\r\n      const start = wordTimings[i] ?? wordTimings[wordTimings.length - 1];\r\n      const end = wordTimings[i + 1] ?? endFrame;\r\n      return { start, end: Math.max(end, start + 1) };\r\n    });\r\n  }\r\n  const step = (endFrame - startFrame) / n;\r\n  return words.map((_, i) => ({\r\n    start: startFrame + step * i,\r\n    end: startFrame + step * (i + 1),\r\n  }));\r\n}\r\n\r\n/** 0..1 sweep progress of one word at `frame`. */\r\nexport function fillProgress(frame: number, window: WordWindow): number {\r\n  if (window.end <= window.start) return frame >= window.end ? 1 : 0;\r\n  return Math.min(\r\n    1,\r\n    Math.max(0, (frame - window.start) / (window.end - window.start)),\r\n  );\r\n}\r\n\r\n/**\r\n * Word indices of `text` matching the comma-separated `emphasize` list.\r\n * Comparison is case-insensitive and ignores surrounding punctuation.\r\n */\r\nexport function emphasisIndices(text: string, emphasize: string): number[] {\r\n  const targets = emphasize\r\n    .split(\",\")\r\n    .map((w) => w.trim().toLowerCase())\r\n    .filter((w) => w.length > 0);\r\n  if (targets.length === 0) return [];\r\n  const strip = (w: string) =>\r\n    w.toLowerCase().replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\");\r\n  return splitWords(text)\r\n    .map((word, i) => (targets.indexOf(strip(word)) !== -1 ? i : -1))\r\n    .filter((i) => i >= 0);\r\n}\r\n\r\n/** Single demo line built from the convenience `text` prop. */\r\nexport function linesFromText(\r\n  text: string,\r\n  emphasize: string,\r\n  startFrame: number,\r\n  endFrame: number,\r\n): CaptionLine[] {\r\n  return [\r\n    {\r\n      text,\r\n      startFrame,\r\n      endFrame: Math.max(endFrame, startFrame + 1),\r\n      emphasize: emphasisIndices(text, emphasize),\r\n    },\r\n  ];\r\n}\r\n\r\n/* ---------------------------------------------------------------------------\r\n * Real transcripts.\r\n *\r\n * Nobody has frame numbers. A caption comes out of Whisper, whisper.cpp, CapCut or\r\n * Descript in MILLISECONDS, or as an .srt. Remotion's own `@remotion/captions` type\r\n * is `{ text, startMs, endMs }` — so that is what this takes.\r\n *\r\n * (Deliberately duplicated from word-captions rather than imported: this is a\r\n * copy-paste registry, and installing a caption line should not drag a second\r\n * component in with it.)\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/** `00:00:01,234` (or `.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/** Cues from an .srt. Handles `,` and `.` separators and multi-line cues. */\r\nexport function parseSrt(srt: string): Caption[] {\r\n  const out: Caption[] = [];\r\n  for (const raw of srt\r\n    .replace(/\\r/g, \"\")\r\n    .trim()\r\n    .split(/\\n\\s*\\n/)) {\r\n    const lines = raw.split(\"\\n\").filter((l) => l.trim().length > 0);\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) out.push({ text, startMs, endMs });\r\n  }\r\n  return out;\r\n}\r\n\r\n/**\r\n * Captions (ms) → the line model this component draws. One cue is one line; its\r\n * words are spread across the cue so the fill has something to track. Word-level\r\n * Whisper output collapses naturally: consecutive words inside `groupWithinMs` of\r\n * each other become one line, which is how a caption tool builds a line too.\r\n */\r\nexport function linesFromCaptions(\r\n  captions: Caption[],\r\n  fps: number,\r\n  groupWithinMs = 1200,\r\n): CaptionLine[] {\r\n  if (captions.length === 0) return [];\r\n  const toFrame = (ms: number) => (ms / 1000) * fps;\r\n\r\n  const groups: Caption[][] = [];\r\n  let current: Caption[] = [];\r\n  for (const c of captions) {\r\n    const prev = current[current.length - 1];\r\n    if (prev && c.startMs - prev.endMs > groupWithinMs) {\r\n      groups.push(current);\r\n      current = [];\r\n    }\r\n    current.push(c);\r\n  }\r\n  if (current.length) groups.push(current);\r\n\r\n  return groups.map((group) => {\r\n    const words = ([] as string[]).concat(\r\n      ...group.map((c) => c.text.split(/\\s+/).filter(Boolean)),\r\n    );\r\n    const startMs = group[0].startMs;\r\n    const endMs = group[group.length - 1].endMs;\r\n    // One timing per word: a multi-word cue is spread across its own span.\r\n    const timings: number[] = [];\r\n    for (const c of group) {\r\n      const parts = c.text.split(/\\s+/).filter(Boolean);\r\n      const per = Math.max(1, c.endMs - c.startMs) / Math.max(1, parts.length);\r\n      for (let i = 0; i < parts.length; i++) {\r\n        timings.push(toFrame(c.startMs + i * per));\r\n      }\r\n    }\r\n    return {\r\n      text: words.join(\" \"),\r\n      startFrame: toFrame(startMs),\r\n      endFrame: Math.max(toFrame(endMs), toFrame(startMs) + 1),\r\n      wordTimings: timings,\r\n    };\r\n  });\r\n}\r\n\r\n/**\r\n * Index of the line on screen at `frame` (the last one whose window contains it,\r\n * including its fade-out tail), or -1 when nothing is showing.\r\n */\r\nexport function activeLineIndex(\r\n  lines: CaptionLine[],\r\n  frame: number,\r\n  fadeOut = LINE_FADE_FRAMES,\r\n): number {\r\n  let active = -1;\r\n  for (let i = 0; i < lines.length; i++) {\r\n    if (frame >= lines[i].startFrame && frame < lines[i].endFrame + fadeOut) {\r\n      active = i;\r\n    }\r\n  }\r\n  return active;\r\n}\r\n\r\n/**\r\n * A caption line that fills word by word as it is spoken — the read-along look.\r\n *\r\n * Same three things that separate a caption from a subtitle:\r\n *\r\n * 1. **An OUTSIDE outline.** `-webkit-text-stroke` centres the stroke on the glyph\r\n *    and eats it from the inside (measured: a 14px stroke takes a 38px stem down to\r\n *    22px). `paint-order: stroke fill` puts the fill back over it. Without this a\r\n *    caption is unreadable the moment the footage behind it is bright.\r\n * 2. **Weight and size.** Montserrat 800–900 at ~8.5% of the frame's short side.\r\n * 3. **The spoken word actually lands** — it snaps to full white (or rides an accent\r\n *    bar), rather than easing politely.\r\n *\r\n * The emphasis scale pivots on the MEASURED baseline: a browser gives glyph origins\r\n * no vertical sub-pixel precision, so a scale that moves the baseline makes the word\r\n * climb the pixel grid in whole-pixel jumps.\r\n */\r\nexport function KaraokeCaptions({\r\n  captions,\r\n  srt,\r\n  lines,\r\n  text = \"Acme reconciles every transaction automatically\",\r\n  emphasize = \"automatically\",\r\n  preset = \"boxed\",\r\n  theme,\r\n  fontFamily,\r\n  mode = \"dark\",\r\n  accentColor = \"#FFE81F\",\r\n  fontSize,\r\n  fontWeight,\r\n  aspect = \"landscape\",\r\n  pill,\r\n  emphasisScale = 1.08,\r\n  baseColor,\r\n  fillColor,\r\n  strokeColor = \"#000000\",\r\n  strokeRatio,\r\n  uppercase,\r\n  speed = 1,\r\n  className,\r\n}: KaraokeCaptionsProps) {\r\n  const frame = useCurrentFrame() * speed;\r\n  const { durationInFrames, fps, width, height } = useVideoConfig();\r\n\r\n  const look = KARAOKE_LOOKS[preset] ?? KARAOKE_LOOKS.karaoke;\r\n  const t = useKuchiTheme(theme, mode);\r\n  const face = resolveFont(fontFamily ?? t.fontFamily) ?? MONTSERRAT;\r\n  const palette = karaokePalette(t);\r\n  const safeArea = CAPTION_SAFE_AREAS[aspect] ?? CAPTION_SAFE_AREAS.landscape;\r\n\r\n  const shortSide = Math.min(width, height);\r\n  // 0 (or omitted) means \"the preset decides\" — the preset IS the design.\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 showPill = pill ?? look.pill;\r\n\r\n  // An outlined caption is white-on-black by definition; the muted grey of the old\r\n  // \"unspoken\" colour disappears the moment there is footage behind it. Unspoken\r\n  // words are DIMMED WHITE, which still reads.\r\n  const unfilled =\r\n    baseColor ?? (look.pill ? palette.base : \"rgba(255,255,255,0.45)\");\r\n  const filled = fillColor ?? (look.pill ? palette.fill : \"#FFFFFF\");\r\n\r\n  // Real captions first; the evenly-paced string is only a demo.\r\n  const resolvedLines = captions?.length\r\n    ? linesFromCaptions(captions, fps)\r\n    : srt && srt.trim().length > 0\r\n      ? linesFromCaptions(parseSrt(srt), fps)\r\n      : lines && lines.length > 0\r\n        ? lines\r\n        : linesFromText(\r\n            text,\r\n            emphasize,\r\n            10,\r\n            Math.max(11, durationInFrames - 24),\r\n          );\r\n\r\n  const lineIndex = activeLineIndex(resolvedLines, frame);\r\n\r\n  // The baseline inside a word span, measured once — the pivot for the emphasis\r\n  // scale. Guessing it from a line-height ratio is what makes an emphasised word\r\n  // judder.\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(\r\n          \"karaoke-captions: measuring the baseline for the emphasis pivot\",\r\n        )\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 lineHeight = Math.round(size * 1.2);\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: caps ? \"-0.005em\" : \"-0.015em\",\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          // Stroke first, fill over it — an OUTSIDE outline, not one eating the glyph.\r\n          paintOrder: \"stroke fill\" as const,\r\n        }\r\n      : {};\r\n\r\n  const shadow = look.shadow\r\n    ? { textShadow: `0 ${size * 0.05}px ${size * 0.045}px rgba(0,0,0,0.42)` }\r\n    : {};\r\n\r\n  const probe = (\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\r\n  if (lineIndex === -1) {\r\n    // The probe still has to mount, or delayRender never resolves and the render hangs.\r\n    return (\r\n      <div style={{ position: \"absolute\", inset: 0, pointerEvents: \"none\" }}>\r\n        {probe}\r\n      </div>\r\n    );\r\n  }\r\n\r\n  const line = resolvedLines[lineIndex];\r\n  const words = splitWords(line.text);\r\n  const windows = wordWindows(line);\r\n  const emphasized = new Set(line.emphasize ?? []);\r\n\r\n  const enter = interpolate(\r\n    frame - line.startFrame,\r\n    [0, LINE_FADE_FRAMES],\r\n    [0, 1],\r\n    { extrapolateLeft: \"clamp\", extrapolateRight: \"clamp\" },\r\n  );\r\n  const exit = interpolate(\r\n    frame - line.endFrame,\r\n    [0, LINE_FADE_FRAMES],\r\n    [1, 0],\r\n    { extrapolateLeft: \"clamp\", extrapolateRight: \"clamp\" },\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: safeArea.bottom,\r\n        paddingLeft: safeArea.horizontal,\r\n        paddingRight: safeArea.horizontal,\r\n        pointerEvents: \"none\",\r\n      }}\r\n    >\r\n      {probe}\r\n      {look.box ? (\r\n        <div\r\n          style={{\r\n            maxWidth: Math.round(width * 0.82),\r\n            textAlign: \"center\",\r\n            opacity: Math.min(enter, exit),\r\n          }}\r\n        >\r\n          {/* White Roboto on a solid black box that clones per line — the\r\n              YouTube auto-caption look. Inline text so the box wraps each line. */}\r\n          <span\r\n            style={{\r\n              ...typeStyle,\r\n              fontFamily: ROBOTO,\r\n              display: \"inline\",\r\n              color: \"#FFFFFF\",\r\n              backgroundColor: \"rgba(0,0,0,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            {caps ? line.text.toUpperCase() : line.text}\r\n          </span>\r\n        </div>\r\n      ) : (\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            columnGap: size * 0.28,\r\n            rowGap: size * 0.06,\r\n            textAlign: \"center\",\r\n            opacity: Math.min(enter, exit),\r\n            ...(showPill\r\n              ? {\r\n                  padding: `${size * 0.3}px ${size * 0.55}px`,\r\n                  borderRadius: size * 0.24,\r\n                  background: palette.pillBg,\r\n                  border: `1px solid ${palette.pillBorder}`,\r\n                  boxShadow: palette.pillShadow,\r\n                }\r\n              : {}),\r\n          }}\r\n        >\r\n          {words.map((word, i) => {\r\n            const progress = fillProgress(frame, windows[i]);\r\n            const spoken = progress >= 0.999;\r\n            const isEmphasized = emphasized.has(i);\r\n            const scale = isEmphasized\r\n              ? interpolate(progress, [0, 1], [1, emphasisScale], {\r\n                  easing: Easing.out(Easing.cubic),\r\n                  extrapolateLeft: \"clamp\",\r\n                  extrapolateRight: \"clamp\",\r\n                })\r\n              : 1;\r\n\r\n            // The bar preset: the spoken word rides a rounded accent block.\r\n            const onBar =\r\n              look.bar && progress > 0 && !spoken ? false : look.bar && spoken;\r\n            const color = look.bar\r\n              ? spoken\r\n                ? \"#0B0B0C\"\r\n                : unfilled\r\n              : isEmphasized && spoken\r\n                ? accentColor\r\n                : spoken\r\n                  ? filled\r\n                  : unfilled;\r\n\r\n            return (\r\n              <span\r\n                // biome-ignore lint/suspicious/noArrayIndexKey: words in a line repeat, so the index is what makes each key unique\r\n                key={`${word}-${i}`}\r\n                style={{\r\n                  ...typeStyle,\r\n                  ...outline,\r\n                  ...shadow,\r\n                  display: \"inline-block\",\r\n                  color,\r\n                  transform: `scale(${scale})`,\r\n                  // Pivot on the BASELINE. `50% 80%` is a guess, and a guess drags the\r\n                  // word down the pixel grid as it scales.\r\n                  transformOrigin:\r\n                    baselineY === null ? \"50% 82%\" : `50% ${baselineY}px`,\r\n                  willChange,\r\n                  ...(onBar\r\n                    ? {\r\n                        background: accentColor,\r\n                        borderRadius: size * 0.14,\r\n                        padding: `0 ${size * 0.11}px`,\r\n                        WebkitTextStrokeWidth: 0,\r\n                      }\r\n                    : {}),\r\n                }}\r\n              >\r\n                {caps ? word.toUpperCase() : word}\r\n              </span>\r\n            );\r\n          })}\r\n        </div>\r\n      )}\r\n    </div>\r\n  );\r\n}\r\n"}]}