Text Build
Word-by-word text build animation that keeps the line centred. Words enter one at a time while already-placed words physically reflow to stay centered — a growing line on the x axis or a growing stack on the y axis.
Source
components/kuchi/text-build.tsx
1"use client";23import { useEffect, useMemo, useState } from "react";4import { Easing, interpolate, useCurrentFrame } from "remotion";5import {6 resolveFont,7 type KuchiTheme,8 useKuchiTheme,9} from "@/lib/kuchi-ui";1011export type TextBuildAxis = "x" | "y";1213export interface TextBuildProps {14 text: string;15 /** Build direction: "x" pushes the line sideways, "y" stacks rows. */16 axis?: TextBuildAxis;17 /** Distance a new word travels in from (px). Defaults: 88 on x, 28 on y. */18 entryOffset?: number;19 /** Space between words (px on x) or between rows (px on y, default 12). */20 gap?: number;21 /** Frames the first word takes to settle. */22 firstDuration?: number;23 /** Frames each subsequent enter/push/reflow step takes. */24 pushDuration?: number;25 /** Scale a word enters at before settling to 1. */26 entryScale?: number;27 /** Blur (px) a word enters with. Defaults: 3.5 on x, 2.4 on y. */28 entryBlur?: number;29 /** Peak blur (px) on already-placed words while they reflow. */30 reflowBlur?: number;31 /** Cubic-bezier easing for every move. */32 easing?: [number, number, number, number];33 fontSize?: number;34 /** Overrides the design system's `foreground`. */35 color?: string;36 fontWeight?: number;37 speed?: number;38 className?: string;39 /** Design-system token overrides. */40 theme?: Partial<KuchiTheme>;41 mode?: "light" | "dark";42 /**43 * The face this scene paints its words in — a label from `fonts.ts`44 * ("Inter", "Space Grotesk", "Instrument Serif") or a CSS family you have45 * loaded yourself. Unset, the scene keeps the face it was designed around.46 *47 * Overrides `theme.fontFamily`, which is how a brand kit re-skins a whole48 * timeline from one value.49 */50 fontFamily?: string;51}5253const FONT_FAMILY = "-apple-system, BlinkMacSystemFont, sans-serif";5455const MEASURE_FONT =56 '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';5758/** Per-axis defaults harvested from the two legacy looks. */59const AXIS_DEFAULTS: Record<60 TextBuildAxis,61 {62 entryOffset: number;63 gap: number;64 entryBlur: number;65 /** Subtle drift the very first word settles from, on the cross axis (x)66 * or the primary axis (y). */67 firstDrift: number;68 }69> = {70 x: { entryOffset: 88, gap: 10, entryBlur: 3.5, firstDrift: 6 },71 y: { entryOffset: 28, gap: 12, entryBlur: 2.4, firstDrift: -14 },72};7374/**75 * Size of each word along the build axis. On "x" this is the measured text76 * width (canvas measureText, with a `length * fontSize * 0.55` SSR fallback);77 * on "y" every row is one `fontSize` tall.78 */79function fallbackWordSizes(80 words: string[],81 axis: TextBuildAxis,82 fontSize: number,83): number[] {84 if (axis === "y") return words.map(() => fontSize);85 return words.map((w) => w.length * fontSize * 0.55);86}8788export function measureWordSizes(89 words: string[],90 axis: TextBuildAxis,91 fontSize: number,92 fontWeight: number,93): number[] {94 if (axis === "y") return words.map(() => fontSize);95 if (typeof document === "undefined")96 return fallbackWordSizes(words, axis, fontSize);97 const ctx = document.createElement("canvas").getContext("2d");98 if (!ctx) return fallbackWordSizes(words, axis, fontSize);99 ctx.font = `${fontWeight} ${fontSize}px ${MEASURE_FONT}`;100 return words.map((w) => ctx.measureText(w).width);101}102103/**104 * Center coordinates for every intermediate layout. `result[k - 1][j]` is the105 * centered position of word `j` while the first `k` words are on stage, so106 * placed words can be interpolated between consecutive layouts as new words107 * land.108 */109export function centeredPositions(sizes: number[], gap: number): number[][] {110 const out: number[][] = [];111 for (let k = 1; k <= sizes.length; k++) {112 let total = gap * (k - 1);113 for (let j = 0; j < k; j++) total += sizes[j];114 let cursor = -total / 2;115 const centers: number[] = [];116 for (let j = 0; j < k; j++) {117 centers.push(cursor + sizes[j] / 2);118 cursor += sizes[j] + gap;119 }120 out.push(centers);121 }122 return out;123}124125export function TextBuild({126 text,127 axis = "x",128 entryOffset,129 gap,130 firstDuration = 10,131 pushDuration = 13,132 entryScale = 0.992,133 entryBlur,134 reflowBlur = 0.8,135 easing = [0.2, 0.8, 0.2, 1],136 fontSize = 72,137 color,138 fontWeight = 600,139 speed = 1,140 className,141 theme,142 mode,143 fontFamily,144}: TextBuildProps) {145 const frame = useCurrentFrame() * speed;146 const t = useKuchiTheme(theme, mode);147 const face = resolveFont(fontFamily ?? t.fontFamily) ?? FONT_FAMILY;148 const fill = color ?? t.foreground;149150 const defaults = AXIS_DEFAULTS[axis];151 const offset = entryOffset ?? defaults.entryOffset;152 const spacing = gap ?? defaults.gap;153 const inBlur = entryBlur ?? defaults.entryBlur;154155 const words = useMemo(() => text.split(" "), [text]);156157 // Canvas text measurement isn't available during SSR, so the first client158 // render must also use the fallback estimate (matching the server-rendered159 // markup) before upgrading to the precise canvas measurement post-mount —160 // otherwise the two renders disagree and React logs a hydration mismatch.161 const [measured, setMeasured] = useState(false);162 useEffect(() => setMeasured(true), []);163 const sizes = useMemo(164 () =>165 measured166 ? measureWordSizes(words, axis, fontSize, fontWeight)167 : fallbackWordSizes(words, axis, fontSize),168 [measured, words, axis, fontSize, fontWeight],169 );170 const positionsAt = useMemo(171 () => centeredPositions(sizes, spacing),172 [sizes, spacing],173 );174175 const n = words.length;176 const ease = Easing.bezier(easing[0], easing[1], easing[2], easing[3]);177178 return (179 <div180 style={{181 position: "absolute",182 inset: 0,183 display: "flex",184 alignItems: "center",185 justifyContent: "center",186 background: "transparent",187 }}188 >189 <div190 className={className}191 style={{192 position: "relative",193 fontSize,194 fontWeight,195 color: fill,196 letterSpacing: "-0.03em",197 fontFamily: face,198 whiteSpace: "nowrap",199 }}200 >201 {words.map((word, j) => {202 const entryStart =203 j === 0 ? 0 : firstDuration + (j - 1) * pushDuration;204 const entryEnd =205 entryStart + (j === 0 ? firstDuration : pushDuration);206 const target = positionsAt[j][j];207208 // Where the word enters from. Later words travel `offset` along the209 // build axis (from the right on x, from above on y). The first word210 // only drifts subtly: cross-axis on x, a short drop on y.211 const primaryFrom =212 j === 0213 ? axis === "y"214 ? target + defaults.firstDrift215 : target216 : axis === "y"217 ? target - offset218 : target + offset;219 const crossFrom = j === 0 && axis === "x" ? defaults.firstDrift : 0;220221 let primary = target;222 let cross = 0;223 let opacity = 1;224 let scale = 1;225 let blur = 0;226227 if (frame < entryStart) {228 opacity = 0;229 primary = primaryFrom;230 cross = crossFrom;231 scale = entryScale;232 blur = inBlur;233 } else if (frame <= entryEnd) {234 const range: [number, number] = [entryStart, entryEnd];235 const opts = {236 extrapolateLeft: "clamp" as const,237 extrapolateRight: "clamp" as const,238 easing: ease,239 };240 primary = interpolate(frame, range, [primaryFrom, target], opts);241 cross = interpolate(frame, range, [crossFrom, 0], opts);242 opacity = interpolate(frame, range, [0, 1], opts);243 scale = interpolate(frame, range, [entryScale, 1], opts);244 blur = interpolate(frame, range, [inBlur, 0], opts);245 } else {246 // Placed word: reflow between consecutive layouts as each later247 // word lands, with a soft blur pulse mid-move.248 for (let w = j + 1; w < n; w++) {249 const pushStart = firstDuration + (w - 1) * pushDuration;250 const pushEnd = pushStart + pushDuration;251 const from = positionsAt[w - 1][j];252 const to = positionsAt[w][j];253 if (frame >= pushEnd) {254 primary = to;255 } else if (frame >= pushStart) {256 primary = interpolate(frame, [pushStart, pushEnd], [from, to], {257 extrapolateLeft: "clamp",258 extrapolateRight: "clamp",259 easing: ease,260 });261 blur = interpolate(262 frame,263 [pushStart, (pushStart + pushEnd) / 2, pushEnd],264 [0, reflowBlur, 0],265 { extrapolateLeft: "clamp", extrapolateRight: "clamp" },266 );267 break;268 } else {269 primary = from;270 break;271 }272 }273 }274275 const tx = axis === "x" ? primary : 0;276 const ty = axis === "x" ? cross : primary;277278 return (279 <span280 key={`${j}-${word}`}281 style={{282 position: "absolute",283 left: "50%",284 top: "50%",285 whiteSpace: "nowrap",286 // Plain 2D transforms, deliberately. `translate3d(…, 0)` and287 // `backfaceVisibility: hidden` are the same layer-promotion288 // trick wearing two hats: they buy smoothness by handing the289 // scale to the compositor, which resamples a bitmap instead of290 // re-rasterising real type. On a word that is both scaling and291 // blurring, that is the whole deliverable.292 transform: `translate(-50%, -50%) translate(${tx}px, ${ty}px) scale(${scale})`,293 filter: `blur(${blur}px)`,294 opacity,295 }}296 >297 {word}298 </span>299 );300 })}301 </div>302 </div>303 );304}









