Text Swap
Text swap animation, rotating headline that replaces one line with another. Replaces one line of text with another using exit-then-enter scheduling, with five transition presets: fade-through, crossfade, shared-axis-y, shared-axis-z, and cut.
Source
components/kuchi/text-swap.tsx
1"use client";23import { Easing, interpolate, useCurrentFrame } from "remotion";4import {5 resolveFont,6 type KuchiTheme,7 useKuchiTheme,8} from "@/lib/kuchi-ui";910export type TextSwapTransition =11 | "fly-through"12 | "fade-through"13 | "crossfade"14 | "shared-axis-y"15 | "shared-axis-z"16 | "cut";1718export type TextSwapUnit = "word" | "block";1920export interface TextSwapTransitionDefaults {21 unit: TextSwapUnit;22 exitDuration: number;23 enterDuration: number;24}2526/**27 * Per-transition timing defaults. `unit` picks whether the line animates as a28 * whole block or word-by-word when the `unit` prop is omitted.29 */30export const TRANSITION_DEFAULTS: Record<31 TextSwapTransition,32 TextSwapTransitionDefaults33> = {34 // Always a block: the line has to rush the camera as one object. Per-word it35 // would be five objects each blowing up about its own centre, which is not a36 // camera move, it is a collision.37 "fly-through": { unit: "block", exitDuration: 20, enterDuration: 16 },38 "fade-through": { unit: "block", exitDuration: 8, enterDuration: 13 },39 crossfade: { unit: "word", exitDuration: 15, enterDuration: 21 },40 "shared-axis-y": { unit: "block", exitDuration: 10, enterDuration: 14 },41 "shared-axis-z": { unit: "block", exitDuration: 11, enterDuration: 16 },42 cut: { unit: "word", exitDuration: 8, enterDuration: 8 },43};4445export interface TextSwapMotion {46 /** Y offset (px) the outgoing text drifts to. */47 exitY: number;48 /** Scale the outgoing text ends at. */49 exitScale: number;50 /** Blur (px) the outgoing text ends at. */51 exitBlur: number;52 /** Y offset (px) the incoming text starts from. */53 enterY: number;54 /** Scale the incoming text starts from. */55 enterScale: number;56 /** Blur (px) the incoming text starts from. */57 enterBlur: number;5859 /**60 * Shape the exit's scale as a **perspective rush** instead of a plain ramp —61 * see `perspectiveScale`. Only worth it when the line is meant to pass the62 * camera rather than merely grow.63 */64 exitPerspective?: boolean;65 /**66 * Fraction of the exit that passes before the outgoing line starts to fade.67 * 0 (the default) fades across the whole exit. A line flying at your face does68 * not dim on the way in — it stays solid until it is on top of you and then it69 * is gone, so this holds the fade back until the very end.70 */71 exitFadeStart?: number;72 /**73 * Motion-blur samples for the exit. See `SHUTTER` below.74 *75 * Not decoration. At the end of a perspective rush the line more than doubles76 * in size between one frame and the next; drawn sharp, that does not read as77 * speed, it reads as strobing. Sampling the exit several times across the78 * frame and averaging is what a shutter does, and because the motion is a79 * scale, the samples fan out radially — which is exactly the smear in the80 * reference, sharp at the centre of the rush and streaked at the edges.81 */82 exitTrail?: number;83}8485/** Motion targets per transition — exit drifts away from rest, enter settles into rest. */86export const TRANSITION_MOTION: Record<TextSwapTransition, TextSwapMotion> = {87 // The line does not fade out and it does not slide away: it comes at you and88 // goes past. Measured off the reference — apparent size reached ~12x before it89 // was gone, and it stayed solid almost the whole way there.90 "fly-through": {91 exitY: 0,92 exitScale: 12,93 // The shutter does the smearing; this only closes the gaps between its94 // discrete samples at the very end of the rush, where the line grows so fast95 // that consecutive samples land a visible distance apart. It is applied in96 // the line's own space and the scale multiplies it, so it is nothing at the97 // start — when it must not soften the type — and enough by the end.98 exitBlur: 0.5,99 exitPerspective: true,100 exitFadeStart: 0.72,101 exitTrail: 18,102 // The replacement is revealed *behind* the line that just flew past, so it103 // arrives from depth: small, out of focus, resolving into place.104 enterY: 0,105 enterScale: 0.82,106 enterBlur: 9,107 },108 "fade-through": {109 exitY: -4,110 exitScale: 1,111 exitBlur: 0,112 enterY: 6,113 enterScale: 0.99,114 enterBlur: 2,115 },116 crossfade: {117 exitY: -6,118 exitScale: 1,119 exitBlur: 0,120 enterY: 8,121 enterScale: 1,122 enterBlur: 0,123 },124 "shared-axis-y": {125 exitY: -24,126 exitScale: 1,127 exitBlur: 0,128 enterY: 24,129 enterScale: 1,130 enterBlur: 0,131 },132 "shared-axis-z": {133 exitY: 0,134 exitScale: 1.06,135 exitBlur: 1,136 enterY: 0,137 enterScale: 0.9,138 enterBlur: 2,139 },140 cut: {141 exitY: 0,142 exitScale: 1,143 exitBlur: 0,144 enterY: 0,145 enterScale: 1,146 enterBlur: 0,147 },148};149150const TRANSITION_EASINGS: Record<151 TextSwapTransition,152 { exit: (t: number) => number; enter: (t: number) => number }153> = {154 "fly-through": {155 // This is the *travel*, not the scale — how far the line has moved toward156 // the eye. Fitted to the reference: near-constant speed with a little157 // acceleration off the mark. All the drama is the perspective, not the158 // curve; a bezier cannot make something blow up eightfold in three frames,159 // and it should not have to.160 exit: Easing.bezier(1, 0.65, 0.85, 1),161 // A moderate decelerate. Not an expo/quint-out: over a 16-frame settle those162 // spend most of their frames moving less than a pixel, which renders as163 // identical frames — the text visibly stops dead and waits.164 enter: Easing.bezier(0.2, 0.6, 0.35, 1),165 },166 "fade-through": {167 exit: Easing.bezier(0.4, 0, 1, 1),168 enter: Easing.bezier(0.2, 0, 0, 1),169 },170 crossfade: {171 exit: Easing.bezier(0.7, 0, 0.84, 0),172 enter: Easing.bezier(0.16, 1, 0.3, 1),173 },174 "shared-axis-y": {175 exit: Easing.bezier(0.4, 0, 1, 1),176 enter: Easing.bezier(0.2, 0, 0, 1),177 },178 "shared-axis-z": {179 exit: Easing.bezier(0.4, 0, 1, 1),180 enter: Easing.bezier(0.2, 0, 0, 1),181 },182 cut: { exit: Easing.step1, enter: Easing.step1 },183};184185/**186 * Apparent size of something travelling toward the camera.187 *188 * `travel` is 0 at rest and 1 at the moment it reaches the eye; `maxScale` is189 * how big it gets before it is gone. Size goes as `1 / (1 - travel)`, so it190 * creeps for most of the trip and then blows up right at the end — the whole191 * character of a thing rushing past you.192 *193 * This is why the exit is not a plain `interpolate(…, [1, exitScale])`. Fitted194 * against the reference, that shape is off by rmse 0.31 and *cannot* reach the195 * blowup at all; this one lands at 10.09 where the reference measured 10.28.196 * The easing then describes the travel, which is nearly linear — the drama is197 * perspective, not easing, and asking a bezier to fake it never works.198 */199export function perspectiveScale(travel: number, maxScale: number): number {200 if (maxScale <= 1) return 1;201 const p = 1 - 1 / maxScale;202 // Clamp short of 1: at travel = 1 / p the denominator is 0 and the line is203 // already long gone.204 return 1 / (1 - p * Math.min(Math.max(travel, 0), 0.9999));205}206207/**208 * How long the shutter is open, in frames, when `exitTrail` is on. One whole209 * frame — a 360° shutter. Anything shorter leaves gaps between the samples at210 * the speeds this transition reaches.211 */212const SHUTTER = 1;213214/** Split a line into animatable segments for the given unit. */215export function splitSegments(text: string, unit: TextSwapUnit): string[] {216 return unit === "word" ? text.split(" ") : [text];217}218219/**220 * Exit-then-enter scheduling: the incoming text starts once the outgoing text221 * (including its stagger tail) is almost gone, minus `overlap`, plus a222 * `microDelay` beat so the swap reads as two distinct moments.223 */224export function getEnterStart(opts: {225 exitDuration: number;226 segmentCount: number;227 exitStagger: number;228 overlap: number;229 microDelay: number;230}): number {231 const exitTotal =232 opts.exitDuration + Math.max(0, opts.segmentCount - 1) * opts.exitStagger;233 return Math.max(0, exitTotal - opts.overlap + opts.microDelay);234}235236const CLAMP = {237 extrapolateLeft: "clamp",238 extrapolateRight: "clamp",239} as const;240241export interface TextSwapProps {242 fromText: string;243 toText: string;244 /** Animate word-by-word or as one block. Defaults per transition. */245 unit?: TextSwapUnit;246 transition?: TextSwapTransition;247 /** Frames each outgoing segment takes to exit. Defaults per transition. */248 exitDuration?: number;249 /** Frames each incoming segment takes to enter. Defaults per transition. */250 enterDuration?: number;251 exitStagger?: number;252 enterStagger?: number;253 overlap?: number;254 microDelay?: number;255 fontSize?: number;256 /** Overrides the design system's `foreground`. */257 color?: string;258 fontWeight?: number;259 speed?: number;260 className?: string;261 /** Design-system token overrides. */262 theme?: Partial<KuchiTheme>;263 mode?: "light" | "dark";264 /**265 * The face this scene paints its words in — a label from `fonts.ts`266 * ("Inter", "Space Grotesk", "Instrument Serif") or a CSS family you have267 * loaded yourself. Unset, the scene keeps the face it was designed around.268 *269 * Overrides `theme.fontFamily`, which is how a brand kit re-skins a whole270 * timeline from one value.271 */272 fontFamily?: string;273}274275export function TextSwap({276 fromText,277 toText,278 unit,279 transition = "fly-through",280 exitDuration,281 enterDuration,282 exitStagger = 1,283 enterStagger = 2,284 overlap = 1,285 microDelay = 2,286 fontSize = 72,287 color,288 fontWeight = 600,289 speed = 1,290 className,291 theme,292 mode,293 fontFamily,294}: TextSwapProps) {295 const frame = useCurrentFrame() * speed;296 const t = useKuchiTheme(theme, mode);297 const fill = color ?? t.foreground;298299 const defaults = TRANSITION_DEFAULTS[transition];300 const motion = TRANSITION_MOTION[transition];301 const easing = TRANSITION_EASINGS[transition];302303 const resolvedUnit = unit ?? defaults.unit;304 const exitDur = exitDuration ?? defaults.exitDuration;305 const enterDur = enterDuration ?? defaults.enterDuration;306307 const fromSegments = splitSegments(fromText, resolvedUnit);308 const toSegments = splitSegments(toText, resolvedUnit);309310 const enterStart = getEnterStart({311 exitDuration: exitDur,312 segmentCount: fromSegments.length,313 exitStagger,314 overlap,315 microDelay,316 });317318 const isWord = resolvedUnit === "word";319 const exitFadeStart = motion.exitFadeStart ?? 0;320321 // The frames the shutter sees. One sample (the default) is just the exit drawn322 // sharp, and costs nothing — the copies only exist for transitions that move323 // fast enough to strobe without them.324 const trail = Math.max(1, Math.round(motion.exitTrail ?? 1));325 const exitSamples = Array.from(326 { length: trail },327 (_, sample) => frame - (sample / trail) * SHUTTER,328 );329330 const fontStack =331 resolveFont(fontFamily ?? t.fontFamily) ??332 "-apple-system, BlinkMacSystemFont, sans-serif";333 const lineStyle: React.CSSProperties = {334 fontSize,335 fontWeight,336 color: fill,337 letterSpacing: "-0.02em",338 fontFamily: fontStack,339 // Hinting bends each glyph's outline so its stems land on whole pixels. As340 // the size slides, every stem re-snaps to a different grid and the341 // letterforms change shape from frame to frame — they boil. Off, the type342 // reads a shade softer, which is not blur, it is the absence of a lie.343 textRendering: "geometricPrecision",344 };345 const layerStyle: React.CSSProperties = {346 position: "absolute",347 inset: 0,348 display: "flex",349 alignItems: "center",350 justifyContent: "center",351 };352353 return (354 <div355 className={className}356 style={{ position: "absolute", inset: 0, background: "transparent" }}357 >358 {/*359 The shutter. Every sample gets an equal 1/n slice of it and they are360 blended with `plus-lighter`, which *adds* premultiplied colour and alpha361 rather than painting one over the next. A pixel the line covered for half362 the shutter therefore ends up half opaque, which is precisely what a363 shutter does and precisely what makes it read as speed.364365 Ordinary `source-over` cannot do this, and getting it wrong is worth366 spelling out because the result is so plausible: stacking the samples at367 1/1, 1/2, 1/3 … averages *opaque* layers correctly, but these layers are368 type on transparent, so the first sample stays fully solid wherever the369 others miss it, and every overlap drives alpha toward 1. What you get is a370 sharp, over-dark line with ghosts hung around it and visibly fattened371 stems — not a smear. `isolation` keeps the additive blending inside this372 group instead of leaking onto whatever the scene is sitting on.373 */}374 <div style={{ ...layerStyle, isolation: "isolate" }}>375 {exitSamples.map((sampleFrame, sample) => (376 <div377 // biome-ignore lint/suspicious/noArrayIndexKey: shutter samples are positional378 key={sample}379 style={{380 ...layerStyle,381 opacity: 1 / exitSamples.length,382 mixBlendMode: "plus-lighter",383 }}384 >385 <span style={lineStyle}>386 {fromSegments.map((segment, i) => {387 const local = sampleFrame - i * exitStagger;388 // 0 at rest, 1 at the eye. The easing shapes the *travel*; the389 // perspective (or the plain ramp) turns that into apparent size.390 const travel = interpolate(local, [0, exitDur], [0, 1], {391 ...CLAMP,392 easing: easing.exit,393 });394 return (395 <span396 // biome-ignore lint/suspicious/noArrayIndexKey: segments are positional and never reorder397 key={`${segment}-${i}`}398 style={{399 display: "inline-block",400 marginRight: isWord ? "0.25em" : undefined,401 transformOrigin: "50% 50%",402 opacity: interpolate(403 local,404 [exitFadeStart * exitDur, exitDur],405 [1, 0],406 { ...CLAMP, easing: easing.exit },407 ),408 translate: `0 ${motion.exitY * travel}px`,409 scale: `${410 motion.exitPerspective411 ? perspectiveScale(travel, motion.exitScale)412 : 1 + (motion.exitScale - 1) * travel413 }`,414 filter: `blur(${motion.exitBlur * travel}px)`,415 }}416 >417 {segment}418 </span>419 );420 })}421 </span>422 </div>423 ))}424 </div>425426 <div style={layerStyle}>427 <span style={lineStyle}>428 {toSegments.map((segment, j) => {429 const local = frame - enterStart - j * enterStagger;430 return (431 <span432 // biome-ignore lint/suspicious/noArrayIndexKey: segments are positional and never reorder433 key={`${segment}-${j}`}434 style={{435 display: "inline-block",436 marginRight: isWord ? "0.25em" : undefined,437 transformOrigin: "50% 50%",438 opacity: interpolate(local, [0, enterDur], [0, 1], {439 ...CLAMP,440 easing: easing.enter,441 }),442 translate: `0 ${interpolate(443 local,444 [0, enterDur],445 [motion.enterY, 0],446 { ...CLAMP, easing: easing.enter },447 )}px`,448 scale: `${interpolate(449 local,450 [0, enterDur],451 [motion.enterScale, 1],452 { ...CLAMP, easing: easing.enter },453 )}`,454 filter: `blur(${interpolate(455 local,456 [0, enterDur],457 [motion.enterBlur, 0],458 { ...CLAMP, easing: easing.enter },459 )}px)`,460 }}461 >462 {segment}463 </span>464 );465 })}466 </span>467 </div>468 </div>469 );470}









