Skip to content

Open source CapCut alternative.

TypeScript

feat(site): text carries a word-by-word emphasis [rebuild]

David Lec7d26382af9c
diff --git a/site/packages/effects-kit/src/anim.ts b/site/packages/effects-kit/src/anim.ts
index 159ac972..b6c3f716 100644
--- a/site/packages/effects-kit/src/anim.ts
+++ b/site/packages/effects-kit/src/anim.ts
@@ -24,6 +24,7 @@ import {
} from "./motion/catalog";
import { evalPreset, evalWhole, presetExtent, sampleProperties } from "./motion/evaluate";
import type { MotionPose, MotionPreset } from "./motion/types";
+import type { OverlayWords } from "./words";
export type OverlayAnimStyle =
| "fade"
@@ -123,6 +124,9 @@ export interface OverlayAnim {
out?: OverlayEdge;
loop?: OverlayLoop;
move?: OverlayMove;
+ /** Word-by-word emphasis (see words.ts). Text only: every other kind
+ * ignores it, the way typewriter is offered on titles alone. */
+ words?: OverlayWords;
}
/** The motion a slot plays: the one it carries, or the catalog entry it
@@ -453,7 +457,7 @@ export function loopPeriod(anim: OverlayAnim | undefined): number | null {
/** Whether any slot is set (an element with an empty anim object is static). */
export function hasOverlayAnim(anim: OverlayAnim | undefined): boolean {
- return !!anim && (!!anim.in || !!anim.out || !!anim.loop || !!anim.move);
+ return !!anim && (!!anim.in || !!anim.out || !!anim.loop || !!anim.move || !!anim.words);
}
/**
diff --git a/site/packages/effects-kit/src/index.ts b/site/packages/effects-kit/src/index.ts
index de848238..57b486b4 100644
--- a/site/packages/effects-kit/src/index.ts
+++ b/site/packages/effects-kit/src/index.ts
@@ -1,5 +1,6 @@
export * from "./types";
export * from "./anim";
+export * from "./words";
export * from "./motion/types";
export * from "./motion/evaluate";
export * from "./motion/catalog";
diff --git a/site/packages/effects-kit/src/render.ts b/site/packages/effects-kit/src/render.ts
index 527fb518..17b746de 100644
--- a/site/packages/effects-kit/src/render.ts
+++ b/site/packages/effects-kit/src/render.ts
@@ -33,6 +33,15 @@ import {
type TextOverlay,
type TextShadowSpec,
} from "./types";
+import {
+ applyWordAccent,
+ highlightSwell,
+ overlayWords,
+ WORD_ACCENT_DEFAULT,
+ wordAccentIndex,
+ wordSwell,
+ wordWindows,
+} from "./words";
// Text metrics shared by DOM preview and canvas burn-in.
export const LINE_HEIGHT = 1.25;
@@ -372,7 +381,45 @@ async function paintText(
const totalH = lines.length * lineH;
const cx = overlay.x * width;
const cy = overlay.y * frame.height;
- const widthsOf = lines.map((l) => ctx.measureText(l).width);
+
+ // Karaoke lays its words out first. The emphasized word may be swollen, and
+ // it takes that width in the line — its neighbours move out of its way — so
+ // the plate, the alignment and the draw all have to read one layout.
+ const swell = overlay.highlightWord === undefined ? 1 : highlightSwell(overlay);
+ const bigFont = swell !== 1 ? textCssFont(overlay, fpx * swell, env) : cssFont;
+ if (swell !== 1) await ensureFontLoaded(bigFont, overlay.text);
+ /** Draw and measure at the swollen word's size, or back at the line's.
+ * Tracking is em of the size in play, so a swollen word is spaced like the
+ * words beside it. */
+ const setSize = (big: boolean) => {
+ ctx.font = big ? bigFont : cssFont;
+ if ("letterSpacing" in ctx)
+ ctx.letterSpacing = `${(overlay.letterSpacing ?? 0) * (big ? fpx * swell : fpx)}px`;
+ };
+ const runs =
+ overlay.highlightWord === undefined
+ ? null
+ : (() => {
+ const spaceW = ctx.measureText(" ").width;
+ let k = 0;
+ return lines.map((line) => {
+ const words = line.split(" ").filter(Boolean);
+ const widths = words.map((w) => {
+ const big = k++ === overlay.highlightWord && swell !== 1;
+ if (big) setSize(true);
+ const ww = ctx.measureText(w).width;
+ if (big) setSize(false);
+ return ww;
+ });
+ return {
+ words,
+ widths,
+ spaceW,
+ lineW: widths.reduce((a, b) => a + b, 0) + spaceW * Math.max(0, words.length - 1),
+ };
+ });
+ })();
+ const widthsOf = runs ? runs.map((r) => r.lineW) : lines.map((l) => ctx.measureText(l).width);
const maxW = Math.max(...widthsOf, 1);
if (overlay.plate) {
@@ -400,7 +447,10 @@ async function paintText(
const drawText = (text: string, x: number, y: number, fill: string = overlay.color) => {
if (overlay.stroke && strokeW > 0) {
ctx.lineJoin = "round";
- ctx.lineWidth = strokeW * 2; // half of a centered stroke shows behind the fill
+ // In em of whatever size is set, so a swollen word wears the same
+ // outline weight as the words beside it.
+ const em = parseFloat(ctx.font) || fpx;
+ ctx.lineWidth = (strokeW / fpx) * em * 2; // half of a centered stroke shows behind the fill
ctx.strokeStyle = overlay.stroke.color;
ctx.strokeText(text, x, y);
}
@@ -453,48 +503,69 @@ async function paintText(
return;
}
- // Karaoke: draw word by word so the spoken word gets the accent color and an
- // underline; the word index counts across all lines.
+ // Karaoke: draw word by word so the spoken word takes its accent treatment —
+ // color, underline, a box, or a swell; the word index counts across all
+ // lines. The words sit in the layout measured above, so a swollen one has
+ // already pushed its neighbours aside and they close back up as the
+ // emphasis moves on.
+ if (!runs) {
+ lines.forEach((line, i) => drawText(line, lineX(i), cy - totalH / 2 + lineH * (i + 0.5)));
+ return;
+ }
+ // A word drawn at another size shares the baseline with the words beside
+ // it, so where that baseline sits has to be read off the face: the middle
+ // this painter draws from is half the type's own height above it.
+ const fm = ctx.measureText("Hg");
+ const asc = fm.fontBoundingBoxAscent ?? fpx * 0.8;
+ const desc = fm.fontBoundingBoxDescent ?? fpx * 0.2;
+ const midOf = (size: number) => ((asc - desc) / 2) * (size / fpx);
let k = 0;
- lines.forEach((line, i) => {
+ ctx.textAlign = "left";
+ runs.forEach((run, i) => {
const y = cy - totalH / 2 + lineH * (i + 0.5);
- if (overlay.highlightWord === undefined) {
- drawText(line, lineX(i), y);
- return;
- }
- const words = line.split(" ").filter(Boolean);
- const spaceW = ctx.measureText(" ").width;
- const widths = words.map((w) => ctx.measureText(w).width);
- const lineW = widths.reduce((a, b) => a + b, 0) + spaceW * (words.length - 1);
- let x = cx - lineW / 2;
- ctx.textAlign = "left";
- words.forEach((w, wi) => {
+ let x = cx - run.lineW / 2;
+ run.words.forEach((w, wi) => {
const active = k === overlay.highlightWord;
+ const big = active && swell !== 1;
+ // A word at the line's own size draws from the middle, exactly as it
+ // always has; a swollen one hangs off the shared baseline instead, and
+ // its own middle follows from there.
+ const size = big ? fpx * swell : fpx;
+ const drawY = big ? y + midOf(fpx) : y;
+ const mid = big ? y + midOf(fpx) - midOf(size) : y;
+ if (big) {
+ setSize(true);
+ ctx.textBaseline = "alphabetic";
+ }
if (active && overlay.highlightMode === "box") {
// Accent box behind the word, contrast text on top — drawn with the
// shadow off so the box and its word stay crisp.
- const pad = 0.12 * fpx;
+ const pad = 0.12 * size;
const prevShadow = ctx.shadowColor;
ctx.shadowColor = "transparent";
- ctx.fillStyle = overlay.highlightColor ?? "#FFE94A";
+ ctx.fillStyle = overlay.highlightColor ?? WORD_ACCENT_DEFAULT;
ctx.beginPath();
- ctx.roundRect(x - pad, y - fpx * 0.5 - pad, widths[wi] + pad * 2, fpx + pad * 2, 0.18 * fpx);
+ ctx.roundRect(x - pad, mid - size * 0.5 - pad, run.widths[wi] + pad * 2, size + pad * 2, 0.18 * size);
ctx.fill();
- drawText(w, x, y, overlay.highlightText ?? "#111114");
+ drawText(w, x, drawY, overlay.highlightText ?? "#111114");
ctx.shadowColor = prevShadow;
} else if (active) {
- drawText(w, x, y, overlay.highlightColor ?? "#FFE94A");
- if (overlay.highlightMode !== "color") {
- ctx.fillRect(x, y + fpx * 0.42, widths[wi], Math.max(2 * scale, fpx * 0.07));
+ drawText(w, x, drawY, overlay.highlightColor ?? WORD_ACCENT_DEFAULT);
+ if (overlay.highlightMode === "underline") {
+ ctx.fillRect(x, mid + size * 0.42, run.widths[wi], Math.max(2 * scale, size * 0.07));
}
} else {
- drawText(w, x, y);
+ drawText(w, x, drawY);
}
- x += widths[wi] + spaceW;
+ if (big) {
+ setSize(false);
+ ctx.textBaseline = "middle";
+ }
+ x += run.widths[wi] + run.spaceW;
k++;
});
- ctx.textAlign = "center";
});
+ ctx.textAlign = "center";
}
/** Paint one element in frame coordinates with no element-level transform —
@@ -702,6 +773,11 @@ export function planAnimatedLayers(o: Overlay, end: number): AnimatedLayer[] {
const inS = anim.in ? Math.min(anim.in.seconds, dur) : 0;
const outS = anim.out ? Math.min(anim.out.seconds, Math.max(0, dur - inS)) : 0;
const out: AnimatedLayer[] = [];
+ // Word emphasis walks the line on the element's own clock, so every window
+ // below is cut at the word boundaries inside it and each piece stamped with
+ // the word it emphasizes — the same one-picture-per-word the caption
+ // burn-in has always used.
+ const words = overlayWords(o);
const push = (
overlay: Overlay,
from: number,
@@ -712,13 +788,23 @@ export function planAnimatedLayers(o: Overlay, end: number): AnimatedLayer[] {
const start = Math.max(o.start, from);
const stop = Math.min(end, to);
if (stop - start < 1e-3) return;
- out.push({
- overlay: { ...overlay, rotation: undefined, opacity: undefined } as Overlay,
- start,
- end: stop,
- anim: animPart,
- phase,
- });
+ const add = (el: Overlay, a: number, b: number) =>
+ out.push({
+ overlay: { ...el, rotation: undefined, opacity: undefined } as Overlay,
+ start: a,
+ end: b,
+ anim: animPart,
+ phase,
+ });
+ if (words) {
+ wordWindows((o as TextOverlay).text, dur, words.times).forEach((w, i) => {
+ const a = Math.max(start, o.start + w.start);
+ const b = Math.min(stop, o.start + w.end);
+ if (b - a >= 1e-3) add(applyWordAccent(overlay, i), a, b);
+ });
+ return;
+ }
+ add(overlay, start, stop);
};
/** One window per slice, each drawn at the ramp's position mid-window. The
* slot leaves the window's anim: its motion is in the picture already. */
@@ -825,7 +911,10 @@ export async function renderOverlayFrames(
// spans every pose the track visits, at the largest scale it reaches.
const keyed = hasOverlayKeys(overlay);
const extent = poseExtent(overlay);
- const maxScale = 1.15 * extent.scale * move.scale;
+ // A swollen word grows the line past the resting box, so the region carries
+ // it — width from the swell, and the type's own extra height with it.
+ const accent = overlayWords(overlay);
+ const maxScale = 1.15 * extent.scale * move.scale * wordSwell(accent);
const rotates =
!!overlay.rotation ||
loop.rotates ||
@@ -863,7 +952,10 @@ export async function renderOverlayFrames(
// Back to the origin the painters draw around, so they stay unaware of
// any of this.
ctx.translate(-overlay.x * width, -overlay.y * height);
- let el: Overlay = { ...overlay, rotation: undefined, opacity: undefined };
+ let el: Overlay = applyWordAccent(
+ { ...overlay, rotation: undefined, opacity: undefined },
+ wordAccentIndex(overlay, tLocal, dur)
+ );
if (ev.textProgress !== undefined && (overlay.kind ?? "text") === "text") {
const text = (overlay as TextOverlay).text;
const chars = Math.max(0, Math.min(text.length, Math.ceil(ev.textProgress * text.length)));
@@ -908,7 +1000,7 @@ export async function renderOverlayFrames(
// A keyframed pose, a move, or a keyframed mask changes on its own schedule
// across the whole element, so there is no still middle and no cycle to
// repeat: sample the element frame by frame.
- if (keyed || anim?.move || isMaskAnimated(overlay.mask)) {
+ if (keyed || anim?.move || isMaskAnimated(overlay.mask) || (accent && anim?.loop)) {
const n = Math.max(1, Math.round(dur * fps));
for (let i = 0; i < n; i++) {
await push(i * step, i === n - 1 ? dur - (n - 1) * step : step);
@@ -928,7 +1020,17 @@ export async function renderOverlayFrames(
const middle = dur - inS - outS;
if (middle > 1e-3) {
const period = loopPeriod(anim) ?? lottieDur;
- if (period) {
+ if (accent) {
+ // The picture changes as the emphasis moves on, and nowhere else: one
+ // frame per word covers the middle however long it runs. The last one
+ // absorbs the rounding, so the pieces sum to the middle exactly.
+ const spans = wordWindows((overlay as TextOverlay).text, dur, accent.times)
+ .map((w) => ({ a: Math.max(inS, w.start), b: Math.min(dur - outS, w.end) }))
+ .filter((w) => w.b - w.a > 1e-3);
+ if (spans.length > 0) spans[spans.length - 1].b = dur - outS;
+ for (const w of spans) await push((w.a + w.b) / 2, w.b - w.a);
+ if (spans.length === 0) await push(inS + middle / 2, middle);
+ } else if (period) {
// One cycle of pictures, repeated by reference to cover the middle.
const n = Math.max(2, Math.min(Math.round(period * fps), 180));
const cycleStep = period / n;
diff --git a/site/packages/effects-kit/src/types.ts b/site/packages/effects-kit/src/types.ts
index 33e1909e..1a1d08aa 100644
--- a/site/packages/effects-kit/src/types.ts
+++ b/site/packages/effects-kit/src/types.ts
@@ -40,8 +40,11 @@ export interface OverlayBase {
}
/** How a highlighted word lights up in karaoke text: accent color only,
- * accent color plus underline, or an accent box behind the word. */
-export type WordAccentMode = "color" | "underline" | "box";
+ * accent color plus underline, an accent box behind the word, or the word
+ * swelling at the accent color. A swollen word takes its new width in the
+ * line, so its neighbours move out of its way and settle back as the
+ * emphasis travels on. */
+export type WordAccentMode = "color" | "underline" | "box" | "pop";
/** A custom drop shadow. Every field is optional — absent ones take the
* legacy defaults, so `shadow: true` and `shadow: {}` render identically. */
@@ -93,6 +96,8 @@ export interface TextOverlay extends OverlayBase {
highlightColor?: string;
highlightMode?: WordAccentMode;
highlightText?: string;
+ /** How far the highlighted word swells; absent = the mode's own default. */
+ highlightScale?: number;
}
export type ShapeKind =
diff --git a/site/packages/effects-kit/src/words.test.ts b/site/packages/effects-kit/src/words.test.ts
new file mode 100644
index 00000000..04d459cf
--- /dev/null
+++ b/site/packages/effects-kit/src/words.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, test } from "bun:test";
+import { hasOverlayAnim } from "./anim";
+import type { TextOverlay } from "./types";
+import {
+ applyWordAccent,
+ displayWords,
+ wordAccent,
+ WORD_ACCENT_DEFAULT,
+ wordAccentIndex,
+ wordSwell,
+ WORD_POP_SCALE,
+ WORD_SWELL_MAX,
+ wordWindows,
+} from "./words";
+
+const title = (over: Partial<TextOverlay> = {}): TextOverlay => ({
+ id: "t1",
+ kind: "text",
+ text: "one two three",
+ start: 2,
+ end: 5,
+ x: 0.5,
+ y: 0.5,
+ size: 64,
+ font: "sf",
+ weight: 700,
+ color: "#FFFFFF",
+ shadow: true,
+ plate: false,
+ ...over,
+});
+
+describe("word windows", () => {
+ test("cover the span end to end with no gaps", () => {
+ const wins = wordWindows("one two three", 3);
+ expect(wins.length).toBe(3);
+ expect(wins[0].start).toBe(0);
+ expect(wins[2].end).toBe(3);
+ for (let i = 1; i < wins.length; i++) expect(wins[i].start).toBe(wins[i - 1].end);
+ });
+
+ test("follow measured onsets when they match the words", () => {
+ const wins = wordWindows("one two three", 3, [0, 1.2, 2.4]);
+ expect(wins.map((w) => w.start)).toEqual([0, 1.2, 2.4]);
+ expect(wins[2].end).toBe(3);
+ });
+
+ test("fall back to an even share when the text has outgrown the times", () => {
+ const wins = wordWindows("one two three four", 4, [0, 1.2, 2.4]);
+ expect(wins.length).toBe(4);
+ expect(wins[0].start).toBe(0);
+ });
+
+ test("never run backwards", () => {
+ const wins = wordWindows("one two three", 3, [0, 2.5, 1]);
+ expect(wins[2].start).toBeGreaterThanOrEqual(wins[1].start);
+ });
+
+ test("count words across lines", () => {
+ expect(displayWords("one two\nthree")).toEqual(["one", "two", "three"]);
+ });
+});
+
+describe("word emphasis", () => {
+ const words = { style: "pop" as const, color: "#FF3D00" };
+
+ test("counts as animation, so both renderers take the moving path", () => {
+ expect(hasOverlayAnim({ words })).toBe(true);
+ expect(hasOverlayAnim({})).toBe(false);
+ });
+
+ test("marks the word being said", () => {
+ const o = title({ anim: { words } });
+ expect(wordAccentIndex(o, 0, 3)).toBe(0);
+ expect(wordAccentIndex(o, 2.9, 3)).toBe(2);
+ });
+
+ test("is a title's slot; other kinds ignore it", () => {
+ const sticker = { ...title({ anim: { words } }), kind: "sticker" as const, w: 0.2 };
+ expect(wordAccentIndex(sticker as never, 0, 3)).toBe(-1);
+ });
+
+ test("paints through the same highlight fields captions ride", () => {
+ const marked = applyWordAccent(title({ anim: { words } }), 1) as TextOverlay;
+ expect(marked.highlightWord).toBe(1);
+ expect(marked.highlightMode).toBe("pop");
+ expect(marked.highlightColor).toBe("#FF3D00");
+ expect(marked.highlightText).toBe("#FFFFFF");
+ expect(marked.highlightScale).toBe(WORD_POP_SCALE);
+ });
+
+ test("a swell keeps the line's own color; the color treatments take the accent", () => {
+ const swelled = applyWordAccent(
+ title({ color: "#FFFFFF", anim: { words: { style: "pop" } } }),
+ 0
+ ) as TextOverlay;
+ expect(swelled.highlightColor).toBe("#FFFFFF");
+ const boxed = applyWordAccent(
+ title({ color: "#FFFFFF", anim: { words: { style: "box" } } }),
+ 0
+ ) as TextOverlay;
+ expect(boxed.highlightColor).toBe(WORD_ACCENT_DEFAULT);
+ expect(wordAccent({ style: "pop", color: "#0A84FF" }, "#FFFFFF")).toBe("#0A84FF");
+ });
+
+ test("swells by the treatment's default until something says otherwise", () => {
+ expect(wordSwell({ style: "pop" })).toBe(WORD_POP_SCALE);
+ expect(wordSwell({ style: "box" })).toBe(1);
+ expect(wordSwell({ style: "box", scale: 1.5 })).toBe(1.5);
+ expect(wordSwell(undefined)).toBe(1);
+ });
+
+ test("holds the swell inside its bounds", () => {
+ expect(wordSwell({ style: "pop", scale: 9 })).toBe(WORD_SWELL_MAX);
+ expect(wordSwell({ style: "pop", scale: 0.2 })).toBe(1);
+ expect(wordSwell({ style: "pop", scale: Number.NaN })).toBe(WORD_POP_SCALE);
+ });
+
+ test("an element with no emphasis rides through untouched", () => {
+ const o = title();
+ expect(applyWordAccent(o, 1)).toBe(o);
+ });
+});
diff --git a/site/packages/effects-kit/src/words.ts b/site/packages/effects-kit/src/words.ts
new file mode 100644
index 00000000..c81ab6d3
--- /dev/null
+++ b/site/packages/effects-kit/src/words.ts
@@ -0,0 +1,167 @@
+/**
+ * Word-by-word emphasis on text: the whole line stays on screen and the word
+ * being said takes the accent. Captions have had this since they carried word
+ * timings; here it is the same treatment offered as a slot on any text
+ * element, so a title placed by hand emphasizes on its own clock.
+ *
+ * The windows are the model. One per display word, covering the element's
+ * span end to end with no gaps, so the accent never blinks off between two
+ * words. `times` is the element's own clock — seconds from its start — filled
+ * in when something measured the speech; its absence means nobody did, and
+ * the words share the span by length.
+ */
+
+import type { Overlay, TextOverlay, WordAccentMode } from "./types";
+
+/** Accent for emphasis that names no color of its own. */
+export const WORD_ACCENT_DEFAULT = "#FFE94A";
+
+/** How much a popped word swells while it is said, and the bounds a caller
+ * may set instead. The swollen word takes its new width in the line, so the
+ * words beside it move out of its way and settle back as it shrinks. */
+export const WORD_POP_SCALE = 1.24;
+export const WORD_SWELL_MIN = 1;
+export const WORD_SWELL_MAX = 2;
+
+/** The treatments, in the order every picker offers them. */
+export const WORD_ACCENT_MODE_IDS: WordAccentMode[] = ["pop", "color", "underline", "box"];
+
+export const WORD_ACCENT_LABELS: Record<WordAccentMode, string> = {
+ pop: "Pop",
+ color: "Color",
+ underline: "Underline",
+ box: "Highlight",
+};
+
+export const WORD_ACCENT_NOTES: Record<WordAccentMode, string> = {
+ pop: "the word swells and the line makes room for it, in the text's own color unless an accent is set",
+ color: "the word takes the accent color",
+ underline: "accent color with a rule under the word",
+ box: "an accent box behind the word",
+};
+
+/** Word emphasis as an element carries it. */
+export interface OverlayWords {
+ style: WordAccentMode;
+ /** Accent color; absent = the treatment's own default (see `wordAccent`):
+ * a swell keeps the text's color, the color treatments take the accent. */
+ color?: string;
+ /** How far the word swells while it is said, WORD_SWELL_MIN..MAX; absent =
+ * the treatment's own default. */
+ scale?: number;
+ /** Word onsets in seconds from the element's start, one per display word.
+ * Absent, or a count the text has outgrown, = an even share by length. */
+ times?: number[];
+}
+
+/**
+ * The color an emphasized word wears: what the element set, else the
+ * treatment's own default. A swell says everything it has to say with size,
+ * so it keeps the color the rest of the line is written in; the treatments
+ * that speak in color take the accent.
+ */
+export function wordAccent(
+ w: { style?: WordAccentMode; color?: string } | undefined,
+ textColor: string
+): string {
+ if (w?.color) return w.color;
+ return w?.style === "pop" ? textColor : WORD_ACCENT_DEFAULT;
+}
+
+/** How far the emphasized word swells: the element's own setting, else the
+ * treatment's default — a pop swells, the rest hold their size. */
+export function wordSwell(w: { style?: WordAccentMode; scale?: number } | undefined): number {
+ if (!w) return 1;
+ const set = w.scale;
+ if (set !== undefined && Number.isFinite(set))
+ return Math.min(WORD_SWELL_MAX, Math.max(WORD_SWELL_MIN, set));
+ return w.style === "pop" ? WORD_POP_SCALE : 1;
+}
+
+/** The swell of the word a painted overlay has marked — the same reading as
+ * `wordSwell`, off the highlight fields the painters actually carry. */
+export function highlightSwell(o: { highlightMode?: WordAccentMode; highlightScale?: number }): number {
+ return wordSwell({ style: o.highlightMode, scale: o.highlightScale });
+}
+
+/** Black or white, whichever reads on the given hex fill. */
+export function contrastText(hex: string): string {
+ const m = /^#?([0-9a-fA-F]{6})$/.exec(hex.trim());
+ if (!m) return "#111114";
+ const n = parseInt(m[1], 16);
+ const lum = 0.299 * ((n >> 16) & 255) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255);
+ return lum > 150 ? "#111114" : "#FFFFFF";
+}
+
+/** The display words of a text block: whitespace-split across every line.
+ * Both renderers walk them in this order, which is what a word index means. */
+export function displayWords(text: string): string[] {
+ return text.trim().split(/\s+/).filter(Boolean);
+}
+
+/**
+ * One window per display word, seconds from the element's start, partitioning
+ * [0, dur] with no gaps. Measured onsets are used while they still match the
+ * text one for one; otherwise (an edited line, a rewrite) the span is split
+ * proportionally by word length.
+ */
+export function wordWindows(
+ text: string,
+ dur: number,
+ times?: number[]
+): { start: number; end: number }[] {
+ const words = displayWords(text);
+ const n = words.length;
+ if (n === 0 || dur <= 0) return [];
+ const starts: number[] = [];
+ if (times && times.length === n) {
+ for (let i = 0; i < n; i++) {
+ const t = i === 0 ? 0 : Math.min(Math.max(times[i], 0), dur);
+ starts.push(i > 0 && t < starts[i - 1] ? starts[i - 1] : t);
+ }
+ } else {
+ const weights = words.map((w) => w.length + 1);
+ const total = weights.reduce((a, b) => a + b, 0);
+ let acc = 0;
+ for (const w of weights) {
+ starts.push((dur * acc) / total);
+ acc += w;
+ }
+ }
+ return starts.map((start, i) => ({ start, end: i === n - 1 ? dur : starts[i + 1] }));
+}
+
+/** The emphasis an element carries, or nothing — the slot is text only. */
+export function overlayWords(o: Overlay): OverlayWords | undefined {
+ if ((o.kind ?? "text") !== "text") return undefined;
+ return o.anim?.words;
+}
+
+/** Which display word is emphasized at `tLocal`, or -1 before the first. */
+export function wordAccentIndex(o: Overlay, tLocal: number, dur: number): number {
+ const w = overlayWords(o);
+ if (!w) return -1;
+ return wordWindows((o as TextOverlay).text, dur, w.times).findIndex(
+ (win) => tLocal >= win.start && tLocal < win.end
+ );
+}
+
+/**
+ * The element as it paints with one word emphasized — the same
+ * `highlightWord` fields captions ride, so the painters need to know nothing
+ * about where the index came from. An element with no emphasis, or a time
+ * before its first word, rides through untouched.
+ */
+export function applyWordAccent<T extends Overlay>(o: T, index: number): T {
+ const w = overlayWords(o);
+ if (!w || index < 0) return o;
+ const color = wordAccent(w, (o as TextOverlay).color ?? WORD_ACCENT_DEFAULT);
+ return {
+ ...o,
+ highlightWord: index,
+ highlightColor: color,
+ highlightMode: w.style,
+ highlightText: contrastText(color),
+ highlightScale: wordSwell(w),
+ } as T;
+}