{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"word-gather","type":"registry:component","title":"Word Gather","description":"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.","dependencies":["remotion","@remotion/google-fonts"],"docs":"Needs a Remotion project. If a frame renders black, the component is drawing on a transparent layer: put a background behind it, e.g. <AbsoluteFill style={{ background: \"#faf9f6\" }}><Component /></AbsoluteFill>. Pass mode=\"dark\" for dark frames.","registryDependencies":["https://kuchi.kalarislabs.com/r/kuchi-ui.json"],"files":[{"path":"components/kuchi/word-gather.tsx","type":"registry:component","target":"components/kuchi/word-gather.tsx","content":"/*! Portions Copyright (c) 2026 Sri Nath (snap-cn). MIT License. See THIRD_PARTY_LICENSES. */\n\"use client\";\r\n\r\nimport { loadFont as loadSans } from \"@remotion/google-fonts/Figtree\";\r\nimport { useEffect, useMemo, useState } from \"react\";\r\nimport { AbsoluteFill, useCurrentFrame, useVideoConfig } from \"remotion\";\r\nimport {\r\n  resolveFont,\r\n  type KuchiTheme,\r\n  useKuchiTheme,\r\n} from \"@/lib/kuchi-ui\";\r\n\r\n/**\r\n * A sentence that arrives one word at a time, out of order, and gathers.\r\n *\r\n * The first word holds the middle of the frame on its own. Then the rest of the\r\n * sentence drops in around it — not in reading order, and not where it belongs\r\n * — each word landing somewhere near its slot in the accent colour and sliding\r\n * the last of the way home, turning to ink as it settles. The line makes room\r\n * for them as they come, and when the last one is down the whole block eases\r\n * back to its real size.\r\n *\r\n * ## Two layouts, and one word that moves between them\r\n *\r\n * The scene is only ever in one of two arrangements: the lead word alone,\r\n * centred on the card, or the whole sentence wrapped and centred. Every other\r\n * word appears in the second one and never sees the first. The lead word is the\r\n * only thing that has to travel between them — and it does so on two separate\r\n * clocks, which is measured, not invented: it drops onto its line in seven\r\n * frames and slides left across the line over twenty-one, because one of those\r\n * is a line changing and the other is a line reflowing.\r\n *\r\n * ## The layout is arithmetic, not the browser's\r\n *\r\n * Word advances come from `measureText` and the wrap, the centring and every\r\n * slot are computed here. That is not a preference either: a word has to be\r\n * transformed from somewhere else to its slot, and to know where its slot *is*\r\n * you have to have laid the line out yourself. It also means the line break\r\n * cannot move on you frame to frame — the layout is solved once, at scale 1,\r\n * and the block's own scale is a transform over the top of it.\r\n */\r\n\r\nconst { fontFamily: SANS } = loadSans(\"normal\", {\r\n  weights: [\"400\", \"500\", \"600\"],\r\n  subsets: [\"latin\"],\r\n});\r\n\r\n/* ─────────────────────────────────────────────────────────────────────────\r\n   The card, in the reference's own 710 × 388 pixels\r\n   ───────────────────────────────────────────────────────────────────────── */\r\n\r\nexport const REF_W = 710;\r\nexport const REF_H = 388;\r\nexport const CENTRE_X = REF_W / 2;\r\n/**\r\n * Where the lines are centred, which is not quite the middle of the card.\r\n *\r\n * A line is centred on its advance box and read back as its ink, and the two\r\n * differ by half the difference of the first character's left bearing and the\r\n * last one's right — a face-dependent three and a half pixels here.\r\n */\r\nexport const LINE_CX = REF_W / 2 - 3.53;\r\nexport const CENTRE_Y = REF_H / 2;\r\n/** The card's corner, measured off the coverage of its own antialiasing. */\r\nexport const RADIUS = 5.5;\r\n/** The recording runs out here. */\r\nexport const END = 49;\r\n\r\n/**\r\n * The recording's own clock, as the beat a composition frame falls on.\r\n *\r\n * It was captured at about 24 frames a second with a screen recorder's jitter\r\n * and this plays at 30, so the two only line up every fifth frame. Every table\r\n * below is in *beats* rather than frames for that reason: it is the only way a\r\n * number measured off frame 23 of the recording can be the number this scene is\r\n * on when frame 23 of the recording is what it is being compared to.\r\n */\r\nexport const BEATS = 39;\r\nexport const BEAT: readonly Pt[] = [\r\n  [0, 0],\r\n  [1, 1],\r\n  [2, 2],\r\n  [3, 3],\r\n  [4, 4],\r\n  [6, 5],\r\n  [7, 6],\r\n  [8, 7],\r\n  [9, 8],\r\n  [10, 9],\r\n  [12, 10],\r\n  [13, 11],\r\n  [14, 12],\r\n  [15, 13],\r\n  [17, 14],\r\n  [18, 15],\r\n  [19, 16],\r\n  [20, 17],\r\n  [22, 18],\r\n  [23, 19],\r\n  [24, 20],\r\n  [26, 21],\r\n  [27, 22],\r\n  [28, 23],\r\n  [29, 24],\r\n  [31, 25],\r\n  [32, 26],\r\n  [33, 27],\r\n  [34, 28],\r\n  [35, 29],\r\n  [37, 30],\r\n  [38, 31],\r\n  [39, 32],\r\n  [41, 33],\r\n  [42, 34],\r\n  [43, 35],\r\n  [44, 36],\r\n  [45, 37],\r\n  [47, 38],\r\n  [48, 39],\r\n];\r\n\r\nexport type Pt = readonly [number, number];\r\n\r\n/** Linear read of a `[key, value]` table, clamped at both ends. */\r\nexport function track(table: readonly Pt[], at: number): number {\r\n  const first = table[0];\r\n  const last = table[table.length - 1];\r\n  if (!first || !last) return 0;\r\n  if (at <= first[0]) return first[1];\r\n  if (at >= last[0]) return last[1];\r\n  for (let i = 0; i < table.length - 1; i++) {\r\n    const a = table[i];\r\n    const b = table[i + 1];\r\n    if (!a || !b) break;\r\n    if (at <= b[0]) {\r\n      const t = (at - a[0]) / (b[0] - a[0]);\r\n      return a[1] + (b[1] - a[1]) * t;\r\n    }\r\n  }\r\n  return last[1];\r\n}\r\n\r\n/* ─────────────────────────────────────────────────────────────────────────\r\n   Type\r\n   ───────────────────────────────────────────────────────────────────────── */\r\n\r\n/** Cap height and line spacing of the settled block, at scale 1. */\r\nexport const CAP = 35.82;\r\nexport const LINE_H = 48.18;\r\n/**\r\n * How far the sentence block sits below where the lead word sat alone.\r\n *\r\n * Measured, and not a rounding error: the lead word's cap box is centred on the\r\n * card to within a tenth of a pixel, and the two-line block that replaces it\r\n * sits nearly six pixels lower than the same rule would put it. Left out, every\r\n * baseline in the scene is six pixels high.\r\n */\r\nexport const DROP = 5.77;\r\n/** The face's cap height, which is what `CAP` is turned into a font size with. */\r\nexport const CAP_RATIO = 0.74909;\r\n/** The face's own hhea metrics: at `lineHeight: LEADING` the baseline is here. */\r\nexport const ASC = 0.9527;\r\nexport const LEADING = 1.2103;\r\nexport const TRACKING = -0.055;\r\n/**\r\n * And an extra trim on the space, on top of the tracking.\r\n *\r\n * The reference sets its words 0.15 of a cap height apart. The face's own space\r\n * is more than twice that, and tracking tight enough to close it would take the\r\n * letters with it — so the two are separate numbers, which is what a typesetter\r\n * would call word-spacing and letter-spacing and is exactly the distinction.\r\n */\r\nexport const SPACE_TRIM = -0.0549;\r\n\r\n/* ─────────────────────────────────────────────────────────────────────────\r\n   The clock\r\n   ───────────────────────────────────────────────────────────────────────── */\r\n\r\n/** The beat the second word drops in on, and the gap between the ones after. */\r\nexport const FIRST_AT = 20;\r\nexport const STAGGER = 1;\r\n/** How many beats a word stays in the accent colour after it drops in. */\r\nexport const SETTLE = 4;\r\n/** The lead word starts this far above its own resting place. */\r\nexport const LEAD_RISE = 20.6;\r\n\r\n/**\r\n * How far a word has travelled from where it dropped in to its slot, against\r\n * beats since it dropped.\r\n *\r\n * It is an exponential settle — about 0.7 of the remaining distance left every\r\n * beat — and the five words that do it are within 0.07 of each other on the\r\n * first beat and 0.02 by the fourth, which is the capture's sub-frame jitter\r\n * and not five different curves.\r\n */\r\nexport const TRAVEL: readonly Pt[] = [\r\n  [0, 0],\r\n  [1, 0.391],\r\n  [2, 0.563],\r\n  [3, 0.686],\r\n  [4, 0.77],\r\n  [5, 0.836],\r\n  [6, 0.887],\r\n  [7, 0.928],\r\n  [8, 0.96],\r\n  [9, 0.982],\r\n  [10, 0.991],\r\n  [12, 0.996],\r\n  [14, 1],\r\n];\r\n\r\n/**\r\n * The lead word sliding across the line, and dropping onto it.\r\n *\r\n * Two tables because the reference has two moves. `LEAD_X` is the line\r\n * reflowing — an ease *in* and out, twenty-one beats long, which is what a line\r\n * that has just been told it is about to get five more words does. `LEAD_Y` is\r\n * the block going from one line to two, and it is over in six.\r\n */\r\nexport const LEAD_X: readonly Pt[] = [\r\n  [10, 0],\r\n  [11, 0.004],\r\n  [12, 0.007],\r\n  [13, 0.02],\r\n  [14, 0.036],\r\n  [15, 0.063],\r\n  [16, 0.107],\r\n  [17, 0.18],\r\n  [18, 0.317],\r\n  [19, 0.547],\r\n  [20, 0.701],\r\n  [21, 0.793],\r\n  [22, 0.852],\r\n  [23, 0.892],\r\n  [24, 0.921],\r\n  [25, 0.946],\r\n  [26, 0.959],\r\n  [27, 0.97],\r\n  [28, 0.98],\r\n  [29, 0.99],\r\n  [30, 0.992],\r\n  [31, 1],\r\n];\r\n\r\nexport const LEAD_Y: readonly Pt[] = [\r\n  [0, 0],\r\n  [1, 0.131],\r\n  [2, 0.211],\r\n  [3, 0.27],\r\n  [4, 0.329],\r\n  [5, 0.35],\r\n  [6, 0.391],\r\n  [7, 0.411],\r\n  [8, 0.4341],\r\n  [9, 0.47],\r\n  [10, 0.514],\r\n  [11, 0.612],\r\n  [12, 0.817],\r\n  [13, 0.905],\r\n  [14, 0.949],\r\n  [15, 0.985],\r\n  [16, 1],\r\n];\r\n\r\n/**\r\n * The block's own scale.\r\n *\r\n * It holds at 1.289 while the words are still coming and then falls to 1 over\r\n * ten beats, with the whole middle of that fall inside two of them. The first\r\n * eighteen are flat because they are measured off one word's ink width and\r\n * wobble a third of a percent; the fall is every word at once and does not.\r\n */\r\nexport const SCALE: readonly Pt[] = [\r\n  [0, 1.289],\r\n  [18, 1.289],\r\n  [19, 1.2798],\r\n  [20, 1.2782],\r\n  [21, 1.2727],\r\n  [22, 1.264],\r\n  [23, 1.2546],\r\n  [24, 1.2414],\r\n  [25, 1.2184],\r\n  [26, 1.159],\r\n  [27, 1.0689],\r\n  [28, 1.0417],\r\n  [29, 1.0275],\r\n  [30, 1.0193],\r\n  [31, 1.0132],\r\n  [32, 1.0081],\r\n  [33, 1.0064],\r\n  [34, 1],\r\n  [BEATS, 1],\r\n];\r\n\r\n/**\r\n * Where each word drops in, relative to its own slot, in card pixels.\r\n *\r\n * Measured off the frame each word first appears on, and indexed by the word's\r\n * place in the sentence rather than by the order it drops in. There is no\r\n * pattern in them and there is not meant to be — three of the five come in flat\r\n * from the side and two fall past their line — so they are a table and not a\r\n * formula, and a sentence longer than the reference's simply reuses them.\r\n */\r\nexport const SCATTER: readonly Pt[] = [\r\n  [44.4, -59.2],\r\n  [73.8, -1],\r\n  [-31.7, -1.7],\r\n  [12.4, 41],\r\n  [96.2, -1.7],\r\n];\r\n\r\n/**\r\n * The order the words drop in, as offsets into the sentence.\r\n *\r\n * The last word first, then the third, the first, the fourth, the second — so\r\n * the sentence is never briefly readable and never briefly wrong, it is just\r\n * scattered until it is not.\r\n */\r\nexport const ORDER: readonly number[] = [5, 3, 1, 4, 2];\r\n\r\n/**\r\n * The order `n` words after the lead drop in.\r\n *\r\n * The reference's own order where it fits, folded into range where it does not,\r\n * and then whatever is left in reading order. It has to be a permutation — one\r\n * repeated index is a word that never drops and a hole in the sentence — which\r\n * is why it is built as a list and not as arithmetic.\r\n */\r\nexport function dropOrder(n: number): number[] {\r\n  const out: number[] = [];\r\n  const seen = new Set<number>();\r\n  const take = (i: number) => {\r\n    if (i >= 1 && i <= n && !seen.has(i)) {\r\n      seen.add(i);\r\n      out.push(i);\r\n    }\r\n  };\r\n  for (const seed of ORDER) take(seed <= n ? seed : ((seed - 1) % n) + 1);\r\n  for (let i = 1; i <= n; i++) take(i);\r\n  return out;\r\n}\r\n\r\n/** Which word drops in `k`th. */\r\nexport function orderAt(k: number, n: number): number {\r\n  return dropOrder(n)[k] ?? k + 1;\r\n}\r\n\r\n/* ─────────────────────────────────────────────────────────────────────────\r\n   Layout\r\n   ───────────────────────────────────────────────────────────────────────── */\r\n\r\nconst MEASURE_FALLBACK = 0.52;\r\n\r\n/** Advance width of each word, from canvas, with an SSR-safe estimate. */\r\nexport function measureWords(\r\n  words: string[],\r\n  fontSize: number,\r\n  weight: number,\r\n  face: string,\r\n): { widths: number[]; space: number } {\r\n  const guess = {\r\n    widths: words.map((w) => w.length * fontSize * MEASURE_FALLBACK),\r\n    space: fontSize * 0.26,\r\n  };\r\n  if (typeof document === \"undefined\") return guess;\r\n  const ctx = document.createElement(\"canvas\").getContext(\"2d\");\r\n  if (!ctx) return guess;\r\n  ctx.font = `${weight} ${fontSize}px ${face}`;\r\n  return {\r\n    widths: words.map((w) => ctx.measureText(w).width),\r\n    space: ctx.measureText(\" \").width,\r\n  };\r\n}\r\n\r\nexport type Slot = { x: number; baseline: number };\r\n\r\n/**\r\n * The sentence, wrapped greedily and centred line by line.\r\n *\r\n * `maxWidth` is in card pixels at scale 1, so it is the same number whatever\r\n * the block's scale is doing — which is the only reason the line break holds\r\n * still while the block shrinks by a third.\r\n */\r\nexport function solve(\r\n  widths: number[],\r\n  space: number,\r\n  maxWidth: number,\r\n): Slot[] {\r\n  const lines: number[][] = [[]];\r\n  let run = 0;\r\n  for (let i = 0; i < widths.length; i++) {\r\n    const w = widths[i] ?? 0;\r\n    const line = lines[lines.length - 1] as number[];\r\n    const add = (line.length ? space : 0) + w;\r\n    if (line.length > 0 && run + add > maxWidth) {\r\n      lines.push([i]);\r\n      run = w;\r\n    } else {\r\n      line.push(i);\r\n      run += add;\r\n    }\r\n  }\r\n  const top = CENTRE_Y + CAP / 2 + DROP - ((lines.length - 1) * LINE_H) / 2;\r\n  const out: Slot[] = [];\r\n  lines.forEach((line, k) => {\r\n    let total = 0;\r\n    for (const i of line) total += widths[i] ?? 0;\r\n    total += space * (line.length - 1);\r\n    let x = LINE_CX - total / 2;\r\n    for (const i of line) {\r\n      out[i] = { x, baseline: top + k * LINE_H };\r\n      x += (widths[i] ?? 0) + space;\r\n    }\r\n  });\r\n  return out;\r\n}\r\n\r\n/* ─────────────────────────────────────────────────────────────────────────\r\n   The component\r\n   ───────────────────────────────────────────────────────────────────────── */\r\n\r\nexport interface WordGatherProps {\r\n  /** The sentence. The first word is the one that holds the frame alone. */\r\n  text?: string;\r\n  /**\r\n   * Where the line breaks, in card pixels at scale 1. Wider is fewer lines;\r\n   * the reference breaks a six-word sentence into two.\r\n   */\r\n  maxWidth?: number;\r\n  /** The colour a word wears while it is still travelling. */\r\n  accent?: string;\r\n  fontWeight?: number;\r\n  fontFamily?: string;\r\n  theme?: Partial<KuchiTheme>;\r\n  mode?: \"light\" | \"dark\";\r\n  speed?: number;\r\n  className?: string;\r\n}\r\n\r\nexport function WordGather({\r\n  text = \"Every scene is yours to own.\",\r\n  maxWidth = 330,\r\n  accent,\r\n  fontWeight = 500,\r\n  fontFamily,\r\n  theme,\r\n  mode = \"light\",\r\n  speed = 1,\r\n  className,\r\n}: WordGatherProps) {\r\n  const frame = useCurrentFrame() * speed;\r\n  const { width, height } = useVideoConfig();\r\n  const t = useKuchiTheme(theme, mode);\r\n  const face = resolveFont(fontFamily ?? t.fontFamily) ?? SANS;\r\n  const ink = t.foreground;\r\n  // The customiser hands an unset colour control through as \"\", not undefined.\r\n  const lit = accent || t.primary;\r\n\r\n  // Carrying each word's place in the sentence as its own id, because a\r\n  // sentence can say the same word twice and the pair is what identifies it.\r\n  const items = useMemo(\r\n    () =>\r\n      text\r\n        .split(/\\s+/)\r\n        .filter(Boolean)\r\n        .map((word, at) => ({ word, at, id: `${at}:${word}` })),\r\n    [text],\r\n  );\r\n  const words = useMemo(() => items.map((w) => w.word), [items]);\r\n  const size = CAP / CAP_RATIO;\r\n\r\n  // Canvas measurement is not available during SSR, so the first client render\r\n  // has to use the same estimate the server used or React logs a hydration\r\n  // mismatch; the precise widths land on the next tick.\r\n  const [ready, setReady] = useState(false);\r\n  useEffect(() => setReady(true), []);\r\n  const { widths, space } = useMemo(() => {\r\n    const raw = ready\r\n      ? measureWords(words, size, fontWeight, face)\r\n      : {\r\n          widths: words.map((w) => w.length * size * MEASURE_FALLBACK),\r\n          space: size * 0.26,\r\n        };\r\n    // `letter-spacing` lands after every character, the last one included, so a\r\n    // word's advance grows by its whole length and the space by one.\r\n    return {\r\n      widths: raw.widths.map(\r\n        (w, i) => w + (words[i]?.length ?? 0) * TRACKING * size,\r\n      ),\r\n      space: raw.space + (TRACKING + SPACE_TRIM) * size,\r\n    };\r\n  }, [ready, words, size, fontWeight, face]);\r\n  const slots = useMemo(\r\n    () => solve(widths, space, maxWidth),\r\n    [widths, space, maxWidth],\r\n  );\r\n\r\n  // Everything below is on the recording's clock, not the composition's.\r\n  const b = track(BEAT, frame);\r\n  const s = track(SCALE, b);\r\n  const lead = slots[0];\r\n  const aloneX = LINE_CX - (widths[0] ?? 0) / 2;\r\n  const aloneBase = CENTRE_Y + CAP / 2;\r\n  const lx = track(LEAD_X, b);\r\n  const ly = track(LEAD_Y, b);\r\n\r\n  // `cover`, so a 16:9 composition crops the card rather than letterboxing it.\r\n  const k = Math.max(width / REF_W, height / REF_H);\r\n\r\n  return (\r\n    <AbsoluteFill\r\n      className={className}\r\n      style={{ background: t.background, overflow: \"hidden\" }}\r\n    >\r\n      <AbsoluteFill\r\n        style={{\r\n          width: REF_W,\r\n          height: REF_H,\r\n          left: (width - REF_W * k) / 2,\r\n          top: (height - REF_H * k) / 2,\r\n          transform: `scale(${k})`,\r\n          transformOrigin: \"top left\",\r\n          background: t.background,\r\n          borderRadius: RADIUS,\r\n          overflow: \"hidden\",\r\n          fontFamily: face,\r\n          textRendering: \"geometricPrecision\",\r\n        }}\r\n      >\r\n        {items.map(({ word, at: i, id }) => {\r\n          const slot = slots[i];\r\n          if (!slot) return null;\r\n          let x = slot.x;\r\n          let base = slot.baseline;\r\n          let colour = ink;\r\n          if (i === 0 && lead) {\r\n            x = slot.x + (aloneX - slot.x) * (1 - lx);\r\n            base =\r\n              slot.baseline +\r\n              (aloneBase - slot.baseline + LEAD_RISE) * (1 - ly);\r\n          } else {\r\n            const k2 = dropSlot(i, words.length - 1);\r\n            const at = FIRST_AT + STAGGER * k2;\r\n            if (b < at) return null;\r\n            const p = track(TRAVEL, b - at);\r\n            const d = SCATTER[(i - 1) % SCATTER.length] ?? [0, 0];\r\n            x = slot.x + d[0] * (1 - p);\r\n            base = slot.baseline + d[1] * (1 - p);\r\n            if (b < at + SETTLE) colour = lit;\r\n          }\r\n          return (\r\n            <Word\r\n              key={id}\r\n              text={word}\r\n              x={CENTRE_X + (x - CENTRE_X) * s}\r\n              baseline={CENTRE_Y + (base - CENTRE_Y) * s}\r\n              size={size}\r\n              scale={s}\r\n              weight={fontWeight}\r\n              colour={colour}\r\n            />\r\n          );\r\n        })}\r\n      </AbsoluteFill>\r\n    </AbsoluteFill>\r\n  );\r\n}\r\n\r\n/** Which drop-in slot word `i` of `n` is on. */\r\nfunction dropSlot(i: number, n: number): number {\r\n  const k = dropOrder(n).indexOf(i);\r\n  return k < 0 ? i - 1 : k;\r\n}\r\n\r\n/* ─────────────────────────────────────────────────────────────────────────\r\n   One word, scaled about its own baseline\r\n   ───────────────────────────────────────────────────────────────────────── */\r\n\r\nfunction Word({\r\n  text,\r\n  x,\r\n  baseline,\r\n  size,\r\n  scale,\r\n  weight,\r\n  colour,\r\n}: {\r\n  text: string;\r\n  x: number;\r\n  baseline: number;\r\n  size: number;\r\n  scale: number;\r\n  weight: number;\r\n  colour: string;\r\n}) {\r\n  const rise = ASC * size;\r\n  return (\r\n    <div\r\n      style={{\r\n        position: \"absolute\",\r\n        left: x,\r\n        top: baseline - rise,\r\n        width: \"max-content\",\r\n      }}\r\n    >\r\n      <div\r\n        style={{\r\n          transform: `scale(${scale})`,\r\n          transformOrigin: `0 ${rise}px`,\r\n          fontSize: size,\r\n          lineHeight: LEADING,\r\n          fontWeight: weight,\r\n          letterSpacing: `${TRACKING}em`,\r\n          color: colour,\r\n          whiteSpace: \"pre\",\r\n        }}\r\n      >\r\n        {text}\r\n      </div>\r\n    </div>\r\n  );\r\n}\r\n"}]}