Word Gather
Word-by-word sentence animation: words fly in out of order and settle into the line. A sentence that arrives one word at a time, out of order, and gathers.
Source
components/kuchi/word-gather.tsx
1"use client";23import { loadFont as loadSans } from "@remotion/google-fonts/Figtree";4import { useEffect, useMemo, useState } from "react";5import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "remotion";6import {7 resolveFont,8 type KuchiTheme,9 useKuchiTheme,10} from "@/lib/kuchi-ui";1112/**13 * A sentence that arrives one word at a time, out of order, and gathers.14 *15 * The first word holds the middle of the frame on its own. Then the rest of the16 * sentence drops in around it — not in reading order, and not where it belongs17 * — each word landing somewhere near its slot in the accent colour and sliding18 * the last of the way home, turning to ink as it settles. The line makes room19 * for them as they come, and when the last one is down the whole block eases20 * back to its real size.21 *22 * ## Two layouts, and one word that moves between them23 *24 * The scene is only ever in one of two arrangements: the lead word alone,25 * centred on the card, or the whole sentence wrapped and centred. Every other26 * word appears in the second one and never sees the first. The lead word is the27 * only thing that has to travel between them — and it does so on two separate28 * clocks, which is measured, not invented: it drops onto its line in seven29 * frames and slides left across the line over twenty-one, because one of those30 * is a line changing and the other is a line reflowing.31 *32 * ## The layout is arithmetic, not the browser's33 *34 * Word advances come from `measureText` and the wrap, the centring and every35 * slot are computed here. That is not a preference either: a word has to be36 * transformed from somewhere else to its slot, and to know where its slot *is*37 * you have to have laid the line out yourself. It also means the line break38 * cannot move on you frame to frame — the layout is solved once, at scale 1,39 * and the block's own scale is a transform over the top of it.40 */4142const { fontFamily: SANS } = loadSans("normal", {43 weights: ["400", "500", "600"],44 subsets: ["latin"],45});4647/* ─────────────────────────────────────────────────────────────────────────48 The card, in the reference's own 710 × 388 pixels49 ───────────────────────────────────────────────────────────────────────── */5051export const REF_W = 710;52export const REF_H = 388;53export const CENTRE_X = REF_W / 2;54/**55 * Where the lines are centred, which is not quite the middle of the card.56 *57 * A line is centred on its advance box and read back as its ink, and the two58 * differ by half the difference of the first character's left bearing and the59 * last one's right — a face-dependent three and a half pixels here.60 */61export const LINE_CX = REF_W / 2 - 3.53;62export const CENTRE_Y = REF_H / 2;63/** The card's corner, measured off the coverage of its own antialiasing. */64export const RADIUS = 5.5;65/** The recording runs out here. */66export const END = 49;6768/**69 * The recording's own clock, as the beat a composition frame falls on.70 *71 * It was captured at about 24 frames a second with a screen recorder's jitter72 * and this plays at 30, so the two only line up every fifth frame. Every table73 * below is in *beats* rather than frames for that reason: it is the only way a74 * number measured off frame 23 of the recording can be the number this scene is75 * on when frame 23 of the recording is what it is being compared to.76 */77export const BEATS = 39;78export const BEAT: readonly Pt[] = [79 [0, 0],80 [1, 1],81 [2, 2],82 [3, 3],83 [4, 4],84 [6, 5],85 [7, 6],86 [8, 7],87 [9, 8],88 [10, 9],89 [12, 10],90 [13, 11],91 [14, 12],92 [15, 13],93 [17, 14],94 [18, 15],95 [19, 16],96 [20, 17],97 [22, 18],98 [23, 19],99 [24, 20],100 [26, 21],101 [27, 22],102 [28, 23],103 [29, 24],104 [31, 25],105 [32, 26],106 [33, 27],107 [34, 28],108 [35, 29],109 [37, 30],110 [38, 31],111 [39, 32],112 [41, 33],113 [42, 34],114 [43, 35],115 [44, 36],116 [45, 37],117 [47, 38],118 [48, 39],119];120121export type Pt = readonly [number, number];122123/** Linear read of a `[key, value]` table, clamped at both ends. */124export function track(table: readonly Pt[], at: number): number {125 const first = table[0];126 const last = table[table.length - 1];127 if (!first || !last) return 0;128 if (at <= first[0]) return first[1];129 if (at >= last[0]) return last[1];130 for (let i = 0; i < table.length - 1; i++) {131 const a = table[i];132 const b = table[i + 1];133 if (!a || !b) break;134 if (at <= b[0]) {135 const t = (at - a[0]) / (b[0] - a[0]);136 return a[1] + (b[1] - a[1]) * t;137 }138 }139 return last[1];140}141142/* ─────────────────────────────────────────────────────────────────────────143 Type144 ───────────────────────────────────────────────────────────────────────── */145146/** Cap height and line spacing of the settled block, at scale 1. */147export const CAP = 35.82;148export const LINE_H = 48.18;149/**150 * How far the sentence block sits below where the lead word sat alone.151 *152 * Measured, and not a rounding error: the lead word's cap box is centred on the153 * card to within a tenth of a pixel, and the two-line block that replaces it154 * sits nearly six pixels lower than the same rule would put it. Left out, every155 * baseline in the scene is six pixels high.156 */157export const DROP = 5.77;158/** The face's cap height, which is what `CAP` is turned into a font size with. */159export const CAP_RATIO = 0.74909;160/** The face's own hhea metrics: at `lineHeight: LEADING` the baseline is here. */161export const ASC = 0.9527;162export const LEADING = 1.2103;163export const TRACKING = -0.055;164/**165 * And an extra trim on the space, on top of the tracking.166 *167 * The reference sets its words 0.15 of a cap height apart. The face's own space168 * is more than twice that, and tracking tight enough to close it would take the169 * letters with it — so the two are separate numbers, which is what a typesetter170 * would call word-spacing and letter-spacing and is exactly the distinction.171 */172export const SPACE_TRIM = -0.0549;173174/* ─────────────────────────────────────────────────────────────────────────175 The clock176 ───────────────────────────────────────────────────────────────────────── */177178/** The beat the second word drops in on, and the gap between the ones after. */179export const FIRST_AT = 20;180export const STAGGER = 1;181/** How many beats a word stays in the accent colour after it drops in. */182export const SETTLE = 4;183/** The lead word starts this far above its own resting place. */184export const LEAD_RISE = 20.6;185186/**187 * How far a word has travelled from where it dropped in to its slot, against188 * beats since it dropped.189 *190 * It is an exponential settle — about 0.7 of the remaining distance left every191 * beat — and the five words that do it are within 0.07 of each other on the192 * first beat and 0.02 by the fourth, which is the capture's sub-frame jitter193 * and not five different curves.194 */195export const TRAVEL: readonly Pt[] = [196 [0, 0],197 [1, 0.391],198 [2, 0.563],199 [3, 0.686],200 [4, 0.77],201 [5, 0.836],202 [6, 0.887],203 [7, 0.928],204 [8, 0.96],205 [9, 0.982],206 [10, 0.991],207 [12, 0.996],208 [14, 1],209];210211/**212 * The lead word sliding across the line, and dropping onto it.213 *214 * Two tables because the reference has two moves. `LEAD_X` is the line215 * reflowing — an ease *in* and out, twenty-one beats long, which is what a line216 * that has just been told it is about to get five more words does. `LEAD_Y` is217 * the block going from one line to two, and it is over in six.218 */219export const LEAD_X: readonly Pt[] = [220 [10, 0],221 [11, 0.004],222 [12, 0.007],223 [13, 0.02],224 [14, 0.036],225 [15, 0.063],226 [16, 0.107],227 [17, 0.18],228 [18, 0.317],229 [19, 0.547],230 [20, 0.701],231 [21, 0.793],232 [22, 0.852],233 [23, 0.892],234 [24, 0.921],235 [25, 0.946],236 [26, 0.959],237 [27, 0.97],238 [28, 0.98],239 [29, 0.99],240 [30, 0.992],241 [31, 1],242];243244export const LEAD_Y: readonly Pt[] = [245 [0, 0],246 [1, 0.131],247 [2, 0.211],248 [3, 0.27],249 [4, 0.329],250 [5, 0.35],251 [6, 0.391],252 [7, 0.411],253 [8, 0.4341],254 [9, 0.47],255 [10, 0.514],256 [11, 0.612],257 [12, 0.817],258 [13, 0.905],259 [14, 0.949],260 [15, 0.985],261 [16, 1],262];263264/**265 * The block's own scale.266 *267 * It holds at 1.289 while the words are still coming and then falls to 1 over268 * ten beats, with the whole middle of that fall inside two of them. The first269 * eighteen are flat because they are measured off one word's ink width and270 * wobble a third of a percent; the fall is every word at once and does not.271 */272export const SCALE: readonly Pt[] = [273 [0, 1.289],274 [18, 1.289],275 [19, 1.2798],276 [20, 1.2782],277 [21, 1.2727],278 [22, 1.264],279 [23, 1.2546],280 [24, 1.2414],281 [25, 1.2184],282 [26, 1.159],283 [27, 1.0689],284 [28, 1.0417],285 [29, 1.0275],286 [30, 1.0193],287 [31, 1.0132],288 [32, 1.0081],289 [33, 1.0064],290 [34, 1],291 [BEATS, 1],292];293294/**295 * Where each word drops in, relative to its own slot, in card pixels.296 *297 * Measured off the frame each word first appears on, and indexed by the word's298 * place in the sentence rather than by the order it drops in. There is no299 * pattern in them and there is not meant to be — three of the five come in flat300 * from the side and two fall past their line — so they are a table and not a301 * formula, and a sentence longer than the reference's simply reuses them.302 */303export const SCATTER: readonly Pt[] = [304 [44.4, -59.2],305 [73.8, -1],306 [-31.7, -1.7],307 [12.4, 41],308 [96.2, -1.7],309];310311/**312 * The order the words drop in, as offsets into the sentence.313 *314 * The last word first, then the third, the first, the fourth, the second — so315 * the sentence is never briefly readable and never briefly wrong, it is just316 * scattered until it is not.317 */318export const ORDER: readonly number[] = [5, 3, 1, 4, 2];319320/**321 * The order `n` words after the lead drop in.322 *323 * The reference's own order where it fits, folded into range where it does not,324 * and then whatever is left in reading order. It has to be a permutation — one325 * repeated index is a word that never drops and a hole in the sentence — which326 * is why it is built as a list and not as arithmetic.327 */328export function dropOrder(n: number): number[] {329 const out: number[] = [];330 const seen = new Set<number>();331 const take = (i: number) => {332 if (i >= 1 && i <= n && !seen.has(i)) {333 seen.add(i);334 out.push(i);335 }336 };337 for (const seed of ORDER) take(seed <= n ? seed : ((seed - 1) % n) + 1);338 for (let i = 1; i <= n; i++) take(i);339 return out;340}341342/** Which word drops in `k`th. */343export function orderAt(k: number, n: number): number {344 return dropOrder(n)[k] ?? k + 1;345}346347/* ─────────────────────────────────────────────────────────────────────────348 Layout349 ───────────────────────────────────────────────────────────────────────── */350351const MEASURE_FALLBACK = 0.52;352353/** Advance width of each word, from canvas, with an SSR-safe estimate. */354export function measureWords(355 words: string[],356 fontSize: number,357 weight: number,358 face: string,359): { widths: number[]; space: number } {360 const guess = {361 widths: words.map((w) => w.length * fontSize * MEASURE_FALLBACK),362 space: fontSize * 0.26,363 };364 if (typeof document === "undefined") return guess;365 const ctx = document.createElement("canvas").getContext("2d");366 if (!ctx) return guess;367 ctx.font = `${weight} ${fontSize}px ${face}`;368 return {369 widths: words.map((w) => ctx.measureText(w).width),370 space: ctx.measureText(" ").width,371 };372}373374export type Slot = { x: number; baseline: number };375376/**377 * The sentence, wrapped greedily and centred line by line.378 *379 * `maxWidth` is in card pixels at scale 1, so it is the same number whatever380 * the block's scale is doing — which is the only reason the line break holds381 * still while the block shrinks by a third.382 */383export function solve(384 widths: number[],385 space: number,386 maxWidth: number,387): Slot[] {388 const lines: number[][] = [[]];389 let run = 0;390 for (let i = 0; i < widths.length; i++) {391 const w = widths[i] ?? 0;392 const line = lines[lines.length - 1] as number[];393 const add = (line.length ? space : 0) + w;394 if (line.length > 0 && run + add > maxWidth) {395 lines.push([i]);396 run = w;397 } else {398 line.push(i);399 run += add;400 }401 }402 const top = CENTRE_Y + CAP / 2 + DROP - ((lines.length - 1) * LINE_H) / 2;403 const out: Slot[] = [];404 lines.forEach((line, k) => {405 let total = 0;406 for (const i of line) total += widths[i] ?? 0;407 total += space * (line.length - 1);408 let x = LINE_CX - total / 2;409 for (const i of line) {410 out[i] = { x, baseline: top + k * LINE_H };411 x += (widths[i] ?? 0) + space;412 }413 });414 return out;415}416417/* ─────────────────────────────────────────────────────────────────────────418 The component419 ───────────────────────────────────────────────────────────────────────── */420421export interface WordGatherProps {422 /** The sentence. The first word is the one that holds the frame alone. */423 text?: string;424 /**425 * Where the line breaks, in card pixels at scale 1. Wider is fewer lines;426 * the reference breaks a six-word sentence into two.427 */428 maxWidth?: number;429 /** The colour a word wears while it is still travelling. */430 accent?: string;431 fontWeight?: number;432 fontFamily?: string;433 theme?: Partial<KuchiTheme>;434 mode?: "light" | "dark";435 speed?: number;436 className?: string;437}438439export function WordGather({440 text = "Every scene is yours to own.",441 maxWidth = 330,442 accent,443 fontWeight = 500,444 fontFamily,445 theme,446 mode = "light",447 speed = 1,448 className,449}: WordGatherProps) {450 const frame = useCurrentFrame() * speed;451 const { width, height } = useVideoConfig();452 const t = useKuchiTheme(theme, mode);453 const face = resolveFont(fontFamily ?? t.fontFamily) ?? SANS;454 const ink = t.foreground;455 // The customiser hands an unset colour control through as "", not undefined.456 const lit = accent || t.primary;457458 // Carrying each word's place in the sentence as its own id, because a459 // sentence can say the same word twice and the pair is what identifies it.460 const items = useMemo(461 () =>462 text463 .split(/\s+/)464 .filter(Boolean)465 .map((word, at) => ({ word, at, id: `${at}:${word}` })),466 [text],467 );468 const words = useMemo(() => items.map((w) => w.word), [items]);469 const size = CAP / CAP_RATIO;470471 // Canvas measurement is not available during SSR, so the first client render472 // has to use the same estimate the server used or React logs a hydration473 // mismatch; the precise widths land on the next tick.474 const [ready, setReady] = useState(false);475 useEffect(() => setReady(true), []);476 const { widths, space } = useMemo(() => {477 const raw = ready478 ? measureWords(words, size, fontWeight, face)479 : {480 widths: words.map((w) => w.length * size * MEASURE_FALLBACK),481 space: size * 0.26,482 };483 // `letter-spacing` lands after every character, the last one included, so a484 // word's advance grows by its whole length and the space by one.485 return {486 widths: raw.widths.map(487 (w, i) => w + (words[i]?.length ?? 0) * TRACKING * size,488 ),489 space: raw.space + (TRACKING + SPACE_TRIM) * size,490 };491 }, [ready, words, size, fontWeight, face]);492 const slots = useMemo(493 () => solve(widths, space, maxWidth),494 [widths, space, maxWidth],495 );496497 // Everything below is on the recording's clock, not the composition's.498 const b = track(BEAT, frame);499 const s = track(SCALE, b);500 const lead = slots[0];501 const aloneX = LINE_CX - (widths[0] ?? 0) / 2;502 const aloneBase = CENTRE_Y + CAP / 2;503 const lx = track(LEAD_X, b);504 const ly = track(LEAD_Y, b);505506 // `cover`, so a 16:9 composition crops the card rather than letterboxing it.507 const k = Math.max(width / REF_W, height / REF_H);508509 return (510 <AbsoluteFill511 className={className}512 style={{ background: t.background, overflow: "hidden" }}513 >514 <AbsoluteFill515 style={{516 width: REF_W,517 height: REF_H,518 left: (width - REF_W * k) / 2,519 top: (height - REF_H * k) / 2,520 transform: `scale(${k})`,521 transformOrigin: "top left",522 background: t.background,523 borderRadius: RADIUS,524 overflow: "hidden",525 fontFamily: face,526 textRendering: "geometricPrecision",527 }}528 >529 {items.map(({ word, at: i, id }) => {530 const slot = slots[i];531 if (!slot) return null;532 let x = slot.x;533 let base = slot.baseline;534 let colour = ink;535 if (i === 0 && lead) {536 x = slot.x + (aloneX - slot.x) * (1 - lx);537 base =538 slot.baseline +539 (aloneBase - slot.baseline + LEAD_RISE) * (1 - ly);540 } else {541 const k2 = dropSlot(i, words.length - 1);542 const at = FIRST_AT + STAGGER * k2;543 if (b < at) return null;544 const p = track(TRAVEL, b - at);545 const d = SCATTER[(i - 1) % SCATTER.length] ?? [0, 0];546 x = slot.x + d[0] * (1 - p);547 base = slot.baseline + d[1] * (1 - p);548 if (b < at + SETTLE) colour = lit;549 }550 return (551 <Word552 key={id}553 text={word}554 x={CENTRE_X + (x - CENTRE_X) * s}555 baseline={CENTRE_Y + (base - CENTRE_Y) * s}556 size={size}557 scale={s}558 weight={fontWeight}559 colour={colour}560 />561 );562 })}563 </AbsoluteFill>564 </AbsoluteFill>565 );566}567568/** Which drop-in slot word `i` of `n` is on. */569function dropSlot(i: number, n: number): number {570 const k = dropOrder(n).indexOf(i);571 return k < 0 ? i - 1 : k;572}573574/* ─────────────────────────────────────────────────────────────────────────575 One word, scaled about its own baseline576 ───────────────────────────────────────────────────────────────────────── */577578function Word({579 text,580 x,581 baseline,582 size,583 scale,584 weight,585 colour,586}: {587 text: string;588 x: number;589 baseline: number;590 size: number;591 scale: number;592 weight: number;593 colour: string;594}) {595 const rise = ASC * size;596 return (597 <div598 style={{599 position: "absolute",600 left: x,601 top: baseline - rise,602 width: "max-content",603 }}604 >605 <div606 style={{607 transform: `scale(${scale})`,608 transformOrigin: `0 ${rise}px`,609 fontSize: size,610 lineHeight: LEADING,611 fontWeight: weight,612 letterSpacing: `${TRACKING}em`,613 color: colour,614 whiteSpace: "pre",615 }}616 >617 {text}618 </div>619 </div>620 );621}









