Word Captions
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.
Source
components/kuchi/word-captions.tsx
1"use client";23import { loadFont } from "@remotion/google-fonts/Montserrat";4import { loadFont as loadRoboto } from "@remotion/google-fonts/Roboto";5import { useEffect, useLayoutEffect, useRef, useState } from "react";6import {7 continueRender,8 delayRender,9 getRemotionEnvironment,10 interpolate,11 spring,12 useCurrentFrame,13 useVideoConfig,14} from "remotion";15import {16 resolveFont,17 type KuchiTheme,18 useKuchiTheme,19 withAlpha,20} from "@/lib/kuchi-ui";2122// Montserrat, 700–900. This is the face the look is actually made of: the caption23// styles every big channel uses are a heavy geometric grotesque, and Inter at 70024// simply is not heavy enough to carry a stroke. Loaded through25// @remotion/google-fonts so the Player, the mp4 and a user's project all agree.26const { fontFamily: MONTSERRAT, waitUntilDone: montserratReady } = loadFont(27 "normal",28 {29 weights: ["700", "800", "900"],30 subsets: ["latin"],31 },32);3334// The `boxed` look is the YouTube/CapCut auto-caption, and that is set in Roboto35// — a neutral grotesque, not a geometric one. Montserrat would read as a logo.36const { fontFamily: ROBOTO } = loadRoboto("normal", {37 weights: ["500", "700"],38 subsets: ["latin"],39});4041export type CaptionAspect = "16:9" | "1:1" | "9:16";42export type CaptionActiveStyle = "pop" | "highlight" | "color";4344/**45 * The four looks, and they are not invented — they are the caption styles that46 * actually run on big channels:47 *48 * - `beast` — ALL CAPS, Montserrat Black, white with a heavy black outline and a49 * hard shadow; the spoken word snaps to yellow and springs. The50 * YouTube-hook look.51 * - `hormozi` — same weight class, but the spoken word lands inside a filled52 * rounded block that cycles through an accent set. Reads at a glance53 * on a phone.54 * - `pop` — sentence case, outlined, the spoken word takes the accent and pops.55 * Punchy without shouting.56 * - `clean` — a quiet pill. No outline. For product footage where captions are57 * support, not the show. (The old default.)58 */59export type CaptionPreset =60 | "boxed"61 | "youtube"62 | "beast"63 | "hormozi"64 | "pop"65 | "clean";6667export interface CaptionWord {68 text: string;69 startFrame: number;70 /** Defaults to the next word's startFrame (or startFrame + fallback for the last word). */71 endFrame?: number;72}7374/** A caption word with its endFrame resolved. */75export interface TimedWord {76 text: string;77 startFrame: number;78 endFrame: number;79}8081/** One caption beat: 1–3 words shown together in the pill. */82export interface CaptionGroup {83 words: TimedWord[];84 startFrame: number;85 endFrame: number;86}8788export interface WordCaptionsProps {89 /**90 * Word-level captions in MILLISECONDS — the shape Whisper, whisper.cpp, CapCut,91 * Submagic and Remotion's own `@remotion/captions` all speak. This is the input92 * you will actually have.93 */94 captions?: Caption[];95 /** An .srt, pasted straight in. Cues are split into words automatically. */96 srt?: string;97 /** The look. See {@link CaptionPreset}. */98 preset?: CaptionPreset;99 /** Words per page. Defaults per preset. */100 maxWords?: number;101 /** Character budget per page — what stops a page wrapping into a tower. */102 maxChars?: number;103 /** A pause longer than this (ms) starts a new page. */104 pageBreakMs?: number;105 /**106 * Outline width, as a fraction of the font size. This is what makes a caption107 * legible on ANY footage, and it is why hand-rolled captions look cheap without108 * it. 0 turns it off.109 */110 strokeRatio?: number;111 strokeColor?: string;112 /** Force upper case. Defaults per preset — the loud ones shout. */113 uppercase?: boolean;114 /** Accent set the `hormozi` block cycles through, one colour per beat. */115 accentCycle?: string[];116 /**117 * Timed transcript. Pass an array of `{ text, startFrame, endFrame? }`118 * (e.g. mapped from Whisper word timestamps), or a plain string that is119 * paced evenly at `framesPerWord`.120 */121 words?: CaptionWord[] | string;122 /** Tokens shown per caption beat (1–3). */123 groupSize?: number;124 /** How the currently-spoken word is emphasized. */125 activeStyle?: CaptionActiveStyle;126 /** Safe-area position preset for the target frame shape. */127 aspect?: CaptionAspect;128 /** Max width of the caption block in px. */129 maxWidth?: number;130 fontSize?: number;131 /** Overrides the design system's `foreground`. */132 textColor?: string;133 /** Design-system token overrides. */134 theme?: Partial<KuchiTheme>;135 /** Defaults to `"dark"` — a caption scrim is lit for footage. */136 mode?: "light" | "dark";137 /**138 * The face this scene paints its words in — a label from `fonts.ts`139 * ("Inter", "Space Grotesk", "Instrument Serif") or a CSS family you have140 * loaded yourself. Unset, the scene keeps the face it was designed around.141 *142 * Overrides `theme.fontFamily`, which is how a brand kit re-skins a whole143 * timeline from one value.144 */145 fontFamily?: string;146 /** Backdrop pill behind the caption line. Any CSS color; empty string hides it. */147 pillColor?: string;148 /** Active-word accent used by the `highlight` and `color` styles. */149 accentColor?: string;150 /** Pacing (frames per word) used when `words` is a plain string. */151 framesPerWord?: number;152 fontWeight?: number;153 speed?: number;154 className?: string;155}156157/**158 * Bottom inset of the caption block per aspect, as a percentage of the159 * composition height — keeps captions clear of platform chrome (9:16 stays160 * above the feed UI, 16:9 sits in the lower third).161 */162export const SAFE_AREA_BOTTOM_PCT: Record<CaptionAspect, number> = {163 "16:9": 8,164 "1:1": 11,165 "9:16": 20,166};167168/** Clamps the beat size to the supported 1–3 token range. */169export function clampGroupSize(groupSize: number): number {170 if (!Number.isFinite(groupSize)) return 1;171 return Math.min(3, Math.max(1, Math.floor(groupSize)));172}173174/** Evenly paces a plain transcript string into timed words. */175export function scheduleWords(176 text: string,177 framesPerWord: number,178 startFrame = 0,179): CaptionWord[] {180 const pace = Math.max(1, framesPerWord);181 return text182 .split(/\s+/)183 .filter((token) => token.length > 0)184 .map((token, i) => ({185 text: token,186 startFrame: startFrame + i * pace,187 endFrame: startFrame + (i + 1) * pace,188 }));189}190191/**192 * Fills in missing endFrames: a word ends when the next one starts, and the193 * last word holds for `fallbackFrames`. Every word lasts at least 1 frame.194 */195export function resolveWordTimings(196 words: CaptionWord[],197 fallbackFrames: number,198): TimedWord[] {199 return words.map((word, i) => {200 const next = words[i + 1];201 const endFrame =202 word.endFrame ??203 (next ? next.startFrame : word.startFrame + Math.max(1, fallbackFrames));204 return {205 text: word.text,206 startFrame: word.startFrame,207 endFrame: Math.max(endFrame, word.startFrame + 1),208 };209 });210}211212/** Chunks timed words into caption beats of `groupSize` tokens. */213export function groupWords(214 words: TimedWord[],215 groupSize: number,216): CaptionGroup[] {217 const size = clampGroupSize(groupSize);218 const groups: CaptionGroup[] = [];219 for (let i = 0; i < words.length; i += size) {220 const chunk = words.slice(i, i + size);221 groups.push({222 words: chunk,223 startFrame: chunk[0].startFrame,224 endFrame: chunk[chunk.length - 1].endFrame,225 });226 }227 return groups;228}229230/** Index of the group on screen at `frame`, or -1 when no caption shows. */231export function activeGroupIndex(232 groups: CaptionGroup[],233 frame: number,234): number {235 for (let i = groups.length - 1; i >= 0; i--) {236 if (frame >= groups[i].startFrame && frame < groups[i].endFrame) return i;237 }238 return -1;239}240241export interface CaptionLook {242 weight: number;243 uppercase: boolean;244 /** Words per page, and the character budget that keeps a page on 1–2 lines. */245 maxWords: number;246 maxChars: number;247 /** Font size as a fraction of the composition's SHORT side, so it reads the248 * same on 9:16 and 16:9 instead of shrinking to nothing on one of them. */249 sizeRatio: number;250 strokeRatio: number;251 tracking: string;252 /** Scale the spoken word springs to. */253 pop: number;254 /** Does the spoken word sit inside a filled block? */255 block: boolean;256 pill: boolean;257 shadow: boolean;258 /** Per-line solid box behind the whole line (YouTube auto-caption look). */259 box?: boolean;260}261262/**263 * Sizes are a fraction of the frame's SHORT side. The old default was 54px on a264 * 1920-tall frame — 2.8% of its height — which is a subtitle, not a caption. These265 * run 11–13% of the short side, which is where burned-in captions actually live.266 */267export const CAPTION_LOOKS: Record<CaptionPreset, CaptionLook> = {268 /**269 * The default: the YouTube / TikTok auto-caption look — white text on a solid270 * black box that wraps each line tight (`box-decoration-break: clone`). No271 * outline, no pop; the box carries the contrast. Clean and unmistakable.272 */273 boxed: {274 weight: 700,275 uppercase: false,276 maxWords: 7,277 maxChars: 28,278 sizeRatio: 0.062,279 strokeRatio: 0,280 tracking: "-0.005em",281 pop: 1,282 block: false,283 pill: false,284 shadow: false,285 box: true,286 },287 /**288 * The default, and the one you actually see under a talking head: a phrase per289 * page, big enough to read on a phone but small enough to stay on 1–2 lines, with290 * the spoken word lit up inside it. This is what Submagic / Opus / CapCut put out291 * and what most channels burn in.292 */293 youtube: {294 weight: 800,295 uppercase: false,296 maxWords: 6,297 maxChars: 26,298 sizeRatio: 0.075,299 strokeRatio: 0.075,300 tracking: "-0.015em",301 pop: 1.07,302 block: false,303 pill: false,304 shadow: true,305 },306 beast: {307 weight: 900,308 uppercase: true,309 maxWords: 3,310 maxChars: 16,311 sizeRatio: 0.125,312 strokeRatio: 0.1,313 tracking: "-0.005em",314 pop: 1.14,315 block: false,316 pill: false,317 shadow: true,318 },319 hormozi: {320 weight: 800,321 uppercase: true,322 maxWords: 3,323 maxChars: 14,324 sizeRatio: 0.115,325 strokeRatio: 0.085,326 tracking: "-0.005em",327 pop: 1.06,328 block: true,329 pill: false,330 shadow: true,331 },332 pop: {333 weight: 800,334 uppercase: false,335 maxWords: 4,336 maxChars: 22,337 sizeRatio: 0.11,338 strokeRatio: 0.07,339 tracking: "-0.015em",340 pop: 1.12,341 block: false,342 pill: false,343 shadow: true,344 },345 clean: {346 weight: 700,347 uppercase: false,348 maxWords: 8,349 maxChars: 42,350 sizeRatio: 0.06,351 strokeRatio: 0,352 tracking: "-0.01em",353 pop: 1.06,354 block: false,355 pill: true,356 shadow: false,357 },358};359360/** The accent set the `hormozi` block cycles through, one colour per beat. */361export const DEFAULT_ACCENT_CYCLE = [362 "#27E36B",363 "#FFE81F",364 "#FF4D4D",365 "#3EA8FF",366];367368/**369 * The spoken word's scale. A spring with a little overshoot — a caption that eases370 * politely into place does not read as a caption, it reads as a lower third.371 */372export function popScale(373 frame: number,374 startFrame: number,375 fps: number,376 peak: number,377): number {378 const s = spring({379 frame: frame - startFrame,380 fps,381 config: { damping: 11, stiffness: 190, mass: 0.7 },382 durationInFrames: 14,383 });384 return 1 + (peak - 1) * s;385}386387/* ---------------------------------------------------------------------------388 * Real transcripts. This is the part that makes the component usable.389 *390 * Nobody has frame numbers. A caption comes out of Whisper, whisper.cpp, CapCut,391 * Submagic, Opus Clip or Descript, and it comes out in MILLISECONDS — or as an392 * .srt file. Remotion's own `@remotion/captions` type is `{ text, startMs, endMs }`,393 * and that is the shape the whole ecosystem speaks.394 *395 * So that is the shape this takes. Paste a Whisper JSON, or paste an .srt straight396 * in. The frame maths is ours, not yours.397 * ------------------------------------------------------------------------- */398399/** The standard caption token. Structurally identical to `@remotion/captions`. */400export interface Caption {401 text: string;402 startMs: number;403 endMs: number;404}405406/** ms → frame, at the composition's own rate. */407export function msToFrame(ms: number, fps: number): number {408 return (ms / 1000) * fps;409}410411/**412 * Word-level captions from an SRT. Handles both `,` and `.` as the millisecond413 * separator (Whisper writes commas; some tools write dots), and multi-line cues.414 */415export function parseSrt(srt: string): Caption[] {416 const out: Caption[] = [];417 const blocks = srt418 .replace(/\r/g, "")419 .trim()420 .split(/\n\s*\n/);421 for (const raw of blocks) {422 const lines = raw.split("\n").filter((l) => l.trim().length > 0);423 if (lines.length === 0) continue;424 const timeLine = lines.find((l) => l.includes("-->"));425 if (!timeLine) continue;426 const [from, to] = timeLine.split("-->").map((t) => t.trim());427 const startMs = srtTimeToMs(from);428 const endMs = srtTimeToMs(to);429 if (startMs === null || endMs === null) continue;430 const text = lines431 .filter((l) => l !== timeLine && !/^\d+$/.test(l.trim()))432 .join(" ")433 .trim();434 if (text.length > 0) out.push({ text, startMs, endMs });435 }436 return out;437}438439/** `00:00:01,234` (or `.234`, or `00:01,234`) → 1234. Null when it isn't a timestamp. */440export function srtTimeToMs(stamp: string): number | null {441 const m = stamp.trim().match(/^(?:(\d+):)?(\d+):(\d+)[,.](\d{1,3})$/);442 if (!m) return null;443 const [, h, min, sec, frac] = m;444 return (445 (h ? Number(h) : 0) * 3600000 +446 Number(min) * 60000 +447 Number(sec) * 1000 +448 // `padEnd(3, "0")` without the ES2017 lib a stock Remotion project lacks.449 Number(frac + "000".slice(frac.length))450 );451}452453/**454 * An SRT cue is usually a whole phrase, not a word. Split it into words and spread455 * them across the cue so the active-word highlight still has something to track.456 * (Word-level Whisper output needs none of this — it already IS one word per cue.)457 */458export function explodeCue(caption: Caption): Caption[] {459 const words = caption.text.split(/\s+/).filter(Boolean);460 if (words.length <= 1) return [caption];461 const span = Math.max(1, caption.endMs - caption.startMs);462 const per = span / words.length;463 return words.map((text, i) => ({464 text,465 startMs: caption.startMs + i * per,466 endMs: caption.startMs + (i + 1) * per,467 }));468}469470/** Captions (ms) → the internal frame-timed model. */471export function captionsToWords(472 captions: Caption[],473 fps: number,474 explode = true,475): TimedWord[] {476 // `concat(...map)`, not `flatMap` (ES2019): stock Remotion types ES2015.477 const tokens = explode478 ? ([] as Caption[]).concat(...captions.map((c) => explodeCue(c)))479 : captions;480 return tokens.map((c) => ({481 text: c.text,482 startFrame: msToFrame(c.startMs, fps),483 endFrame: Math.max(msToFrame(c.endMs, fps), msToFrame(c.startMs, fps) + 1),484 }));485}486487export interface PageOptions {488 /** Hard cap on words per page. */489 maxWords: number;490 /** Character budget, so a page actually FITS the frame instead of wrapping to a tower. */491 maxChars: number;492 /** A pause longer than this starts a new page — that is where a sentence breaks. */493 maxGapFrames: number;494}495496/**497 * Group words into PAGES the way real caption tools do — by the shape of the speech,498 * not by a fixed count.499 *500 * A page ends when it runs out of words, runs out of characters, or the speaker501 * pauses. The old `groupWords` chopped every 3 words regardless, which is how you502 * end up with "STOP / LOSING / HOURS" stacked in a tower: three words that never503 * belonged on their own page.504 */505export function buildPages(506 words: TimedWord[],507 opts: PageOptions,508): CaptionGroup[] {509 const pages: CaptionGroup[] = [];510 let current: TimedWord[] = [];511 let chars = 0;512513 const flush = () => {514 if (current.length === 0) return;515 pages.push({516 words: current,517 startFrame: current[0].startFrame,518 endFrame: current[current.length - 1].endFrame,519 });520 current = [];521 chars = 0;522 };523524 for (const word of words) {525 const prev = current[current.length - 1];526 const gap = prev ? word.startFrame - prev.endFrame : 0;527 const wouldOverflow =528 current.length >= Math.max(1, opts.maxWords) ||529 chars + word.text.length + 1 > Math.max(1, opts.maxChars);530531 if (prev && (wouldOverflow || gap > opts.maxGapFrames)) flush();532533 current.push(word);534 chars += word.text.length + 1;535 }536 flush();537 return pages;538}539540/**541 * Burned-in captions, in the styles big channels actually use.542 *543 * Three things separate a premium caption from a subtitle, and all three are here:544 *545 * 1. **The outline.** A caption has to be legible over footage it has never seen —546 * a face, a sky, a white desk. A heavy black outline does that, and nothing else547 * does. It has to be an OUTSIDE outline: `-webkit-text-stroke` centres the stroke548 * on the glyph, so half of it eats inwards and the letterform goes thin and549 * mushy (measured: a 14px stroke takes a 38px stem down to 22px). `paint-order:550 * stroke fill` draws the stroke first and the fill over it, and the stem comes551 * back to 38px. That one line is most of the look.552 * 2. **The weight and the size.** Montserrat 800–900, at 11–13% of the frame's553 * short side. The old default was 2.8%.554 * 3. **The spoken word pops.** A spring with overshoot, not an ease.555 *556 * That pop is a scale on text, which is where captions usually fall apart: a browser557 * gives glyph origins no vertical sub-pixel precision, so a scale that moves the558 * baseline makes the word climb the pixel grid in whole-pixel jumps. The scale559 * pivots on the **measured baseline**, so the baseline's device Y never changes.560 */561export function WordCaptions({562 captions,563 srt,564 words = "Stop losing hours to manual invoices",565 preset = "boxed",566 maxWords,567 maxChars,568 pageBreakMs = 420,569 groupSize,570 activeStyle = "pop",571 aspect = "16:9",572 maxWidth,573 fontSize,574 textColor,575 pillColor,576 theme,577 mode,578 fontFamily,579 accentColor = "#FFE81F",580 accentCycle = DEFAULT_ACCENT_CYCLE,581 strokeColor = "#000000",582 strokeRatio,583 uppercase,584 framesPerWord = 14,585 fontWeight,586 speed = 1,587 className,588}: WordCaptionsProps) {589 const frame = useCurrentFrame() * speed;590 const { fps, width, height } = useVideoConfig();591 // A caption pill is a legibility scrim over footage, so its neutrals come592 // from the dark end of the system by default. The accent, the outline and593 // the cycle are the caption's look and stay props (design-system Rule 3c).594 const t = useKuchiTheme(theme, mode ?? "dark");595 const face = resolveFont(fontFamily ?? t.fontFamily) ?? MONTSERRAT;596 const ink = textColor ?? t.foreground;597 const scrim = pillColor ?? withAlpha(t.background, 0.55);598599 const look = CAPTION_LOOKS[preset] ?? CAPTION_LOOKS.beast;600 const shortSide = Math.min(width, height);601 // 0 (or omitted) means "the preset decides" — the preset IS the design, so a602 // customizer knob that silently overrode it would make every preset identical.603 const size =604 fontSize && fontSize > 0605 ? fontSize606 : Math.round(look.sizeRatio * shortSide);607 const weight = fontWeight && fontWeight > 0 ? fontWeight : look.weight;608 const stroke =609 (strokeRatio !== undefined && strokeRatio >= 0610 ? strokeRatio611 : look.strokeRatio) * size;612 const caps = uppercase ?? look.uppercase;613 const block = maxWidth && maxWidth > 0 ? maxWidth : Math.round(width * 0.86);614615 // Real captions first, the toy string last. `captions` (ms) and `srt` are what a616 // user actually has; `words` (frames) is the legacy path; a bare string is a demo.617 const timed: TimedWord[] = captions?.length618 ? captionsToWords(captions, fps)619 : srt && srt.trim().length > 0620 ? captionsToWords(parseSrt(srt), fps)621 : resolveWordTimings(622 typeof words === "string"623 ? scheduleWords(words, framesPerWord)624 : words,625 framesPerWord,626 );627628 // Pages, not fixed-size chunks. `groupSize` still forces a hard count if you pass629 // it, so nothing that relied on it breaks.630 const groups = groupSize631 ? groupWords(timed, groupSize)632 : buildPages(timed, {633 maxWords: maxWords ?? look.maxWords,634 maxChars: maxChars ?? look.maxChars,635 maxGapFrames: (pageBreakMs / 1000) * fps,636 });637 const groupIdx = activeGroupIndex(groups, frame);638 const group = groupIdx === -1 ? null : groups[groupIdx];639640 // The baseline inside a word span, measured once. Guessing it from a line-height641 // ratio is what makes a popping word judder: the pivot has to be exact.642 const probeRef = useRef<HTMLSpanElement>(null);643 const baseRef = useRef<HTMLSpanElement>(null);644 const [baselineY, setBaselineY] = useState<number | null>(null);645 // The delayRender exists only to hold the *mp4 render* on its first frame until646 // the baseline is measured — there the font is already loaded, so that one647 // measurement is exact. In the Player we never block: `baselineY === null`648 // falls back to a line-height pivot until the mount measurement lands, which is649 // invisible on a looping preview. Blocking the Player here is what stranded650 // every caption card behind an orphaned delayRender handle that React651 // StrictMode's double-invoked initializer creates and never clears.652 const [handle] = useState(() =>653 getRemotionEnvironment().isRendering654 ? delayRender("word-captions: measuring the baseline for the pop pivot")655 : null,656 );657658 useLayoutEffect(() => {659 const probe = probeRef.current;660 const base = baseRef.current;661 if (probe && base) {662 setBaselineY(663 base.getBoundingClientRect().top - probe.getBoundingClientRect().top,664 );665 } else if (handle != null) {666 // Nothing to measure in a render — release it rather than hang the frame.667 continueRender(handle);668 }669 // Re-measure once Montserrat lands: a best-effort refinement for the Player670 // (the render already has the font). Never blocks — the pivot above is set.671 let cancelled = false;672 void montserratReady().then(() => {673 if (cancelled) return;674 const p = probeRef.current;675 const b = baseRef.current;676 if (p && b) {677 setBaselineY(678 b.getBoundingClientRect().top - p.getBoundingClientRect().top,679 );680 }681 });682 return () => {683 cancelled = true;684 };685 }, [handle]);686687 // In a render, release the held first frame the moment the baseline is known.688 useEffect(() => {689 if (baselineY != null && handle != null) continueRender(handle);690 }, [baselineY, handle]);691692 const accent =693 look.block && accentCycle.length > 0694 ? accentCycle[Math.max(0, groupIdx) % accentCycle.length]695 : accentColor;696697 const lineHeight = Math.round(size * 1.14);698 const willChange = getRemotionEnvironment().isRendering699 ? undefined700 : ("transform" as const);701702 const typeStyle = {703 fontFamily: face,704 fontWeight: weight,705 fontSize: size,706 lineHeight: `${lineHeight}px`,707 letterSpacing: look.tracking,708 // Hinting re-snaps every stem to the pixel grid as a word scales, and the709 // letterforms visibly boil. This turns it off.710 textRendering: "geometricPrecision" as const,711 fontVariantLigatures: "none" as const,712 };713714 const outline =715 stroke > 0716 ? {717 WebkitTextStrokeWidth: `${stroke}px`,718 WebkitTextStrokeColor: strokeColor,719 // Draw the stroke, THEN the fill on top of it. Without this the stroke is720 // centred on the outline and eats the letterform from the inside.721 paintOrder: "stroke fill" as const,722 }723 : {};724725 const shadow = look.shadow726 ? {727 textShadow: `0 ${size * 0.055}px ${size * 0.05}px ${withAlpha(728 t.background,729 0.42,730 )}`,731 }732 : {};733734 return (735 <div736 className={className}737 style={{738 position: "absolute",739 inset: 0,740 display: "flex",741 alignItems: "flex-end",742 justifyContent: "center",743 paddingBottom: `${SAFE_AREA_BOTTOM_PCT[aspect] ?? SAFE_AREA_BOTTOM_PCT["9:16"]}%`,744 paddingLeft: "5%",745 paddingRight: "5%",746 pointerEvents: "none",747 }}748 >749 {/* Off-screen probe: one word, same type, with a zero-sized inline-block750 sitting on its baseline. Read once, used as the pivot for every pop. */}751 <span752 ref={probeRef}753 aria-hidden754 style={{755 ...typeStyle,756 position: "absolute",757 left: -99999,758 top: 0,759 visibility: "hidden",760 display: "inline-block",761 }}762 >763 Hg764 <span765 ref={baseRef}766 style={{ display: "inline-block", width: 0, height: 0 }}767 />768 </span>769770 {/* Boxed look: white text on a solid black box that clones per line. The771 words stay inline (no flex, no per-word transform), so the background772 wraps each line tight — the YouTube auto-caption look. */}773 {group && look.box && (774 <div775 style={{776 maxWidth: block,777 textAlign: "center",778 opacity: interpolate(frame - group.startFrame, [0, 3], [0, 1], {779 extrapolateLeft: "clamp",780 extrapolateRight: "clamp",781 }),782 }}783 >784 <span785 style={{786 ...typeStyle,787 fontFamily: ROBOTO,788 display: "inline",789 color: ink,790 backgroundColor: withAlpha(t.background, 0.9),791 padding: `${size * 0.06}px ${size * 0.32}px`,792 boxDecorationBreak: "clone",793 WebkitBoxDecorationBreak: "clone",794 lineHeight: `${Math.round(size * 1.46)}px`,795 borderRadius: 2,796 }}797 >798 {group.words799 .map((w) => (caps ? w.text.toUpperCase() : w.text))800 .join(" ")}801 </span>802 </div>803 )}804805 {group && !look.box && (806 <div807 style={{808 display: "flex",809 flexWrap: "wrap",810 alignItems: "flex-end",811 justifyContent: "center",812 // px, not em: `em` here would resolve against the CONTAINER's font size,813 // which is the inherited 16px — not the caption's. That is how the words814 // ended up welded together as "STOPLOSING".815 columnGap: size * 0.26,816 rowGap: size * 0.04,817 maxWidth: block,818 textAlign: "center",819 ...(look.pill820 ? {821 padding: `${size * 0.3}px ${size * 0.5}px`,822 borderRadius: size * 0.22,823 backgroundColor: pillColor === "" ? "transparent" : scrim,824 }825 : {}),826 opacity: interpolate(frame - group.startFrame, [0, 3], [0, 1], {827 extrapolateLeft: "clamp",828 extrapolateRight: "clamp",829 }),830 }}831 >832 {group.words.map((word, i) => {833 const spoken =834 frame >= word.startFrame &&835 (frame < word.endFrame || i === group.words.length - 1);836 const isActive =837 spoken && frame >= word.startFrame && frame < word.endFrame;838839 const scale =840 isActive && activeStyle === "pop"841 ? popScale(frame, word.startFrame, fps, look.pop)842 : 1;843844 // Not yet spoken words in a beat stay white; the spoken one takes the845 // accent (or the block). That is what makes the beat readable AHEAD of846 // the voice instead of only with it.847 const useAccent = isActive && activeStyle !== "pop";848 const fill = look.block ? ink : isActive ? accent : ink;849850 return (851 <span852 key={`${word.text}-${word.startFrame}`}853 style={{854 ...typeStyle,855 ...outline,856 ...shadow,857 display: "inline-block",858 color: useAccent ? accent : fill,859 transform: `scale(${scale})`,860 // The pivot is the BASELINE, not the middle of the box. 50% 100%861 // is the bottom of the box, which sits a descent BELOW the862 // baseline — it drags the word down the pixel grid as it scales.863 transformOrigin:864 baselineY === null ? "50% 85%" : `50% ${baselineY}px`,865 willChange,866 ...(look.block && isActive867 ? {868 backgroundColor: accent,869 borderRadius: size * 0.12,870 padding: `0 ${size * 0.1}px`,871 // The block wants the fill on top of the stroke too, or the872 // stroke shows as a dark halo inside the block.873 WebkitTextStrokeWidth: `${stroke * 0.6}px`,874 }875 : {}),876 }}877 >878 {caps ? word.text.toUpperCase() : word.text}879 </span>880 );881 })}882 </div>883 )}884 </div>885 );886}


