Word Flip
Word flip text rotator: a typewriter headline with a 3D rotating word. A headline types itself out, then one word cycles on a 3D flip — it sinks into an anticipation dip, throws up and away about its baseline under motion blur, and the next word unfurls from below.
Source
components/kuchi/word-flip.tsx
1"use client";23import { useEffect, useRef, useState } from "react";4import {5 AbsoluteFill,6 continueRender,7 delayRender,8 Easing,9 getRemotionEnvironment,10 interpolate,11 useCurrentFrame,12 useVideoConfig,13} from "remotion";14import {15 mixOklch,16 resolveFont,17 type KuchiTheme,18 useKuchiTheme,19} from "@/lib/kuchi-ui";2021/**22 * Pure animation math for WordFlip. Everything above the component is23 * frame-deterministic and side-effect free so it can be unit tested.24 */2526const CLAMP = {27 extrapolateLeft: "clamp",28 extrapolateRight: "clamp",29} as const;3031/** Frames each character takes, from a characters-per-second rate. */32export function framesPerChar(cps: number, fps: number): number {33 return fps / Math.max(0.001, cps);34}3536/**37 * A deterministic, seedless wobble on the keystroke clock so the typing does not38 * land on a metronome. Real typing is uneven; a perfectly regular cadence is the39 * single thing that gives a "typewriter" away. Bounded to ±`jitter` of one40 * keystroke and summed into an *offset*, never a per-key delay, so the sentence41 * still finishes exactly when the timeline says it does.42 */43export function keystrokeOffset(index: number, jitter: number): number {44 if (jitter <= 0) return 0;45 // Two incommensurable sines: no repeat over any realistic sentence, and no RNG,46 // so a render and the Player agree frame for frame.47 const w = Math.sin(index * 12.9898) * 0.6 + Math.sin(index * 4.1414) * 0.4;48 return w * jitter;49}5051/** Frame at which character `index` starts to appear. */52export function charStartFrame(53 index: number,54 opts: { typeStart: number; cps: number; fps: number; jitter: number },55): number {56 const per = framesPerChar(opts.cps, opts.fps);57 return (58 opts.typeStart + index * per + keystrokeOffset(index, opts.jitter) * per59 );60}6162/** Frame the last character has finished fading in. */63export function typingEndFrame(opts: {64 charCount: number;65 typeStart: number;66 cps: number;67 fps: number;68 jitter: number;69 charFade: number;70}): number {71 const last = charStartFrame(Math.max(0, opts.charCount - 1), opts);72 return last + opts.charFade;73}7475/** Frame at which flip `i` (0-based) begins. */76export function flipStartFrame(77 i: number,78 opts: { typingEnd: number; pause: number; cycle: number },79): number {80 return opts.typingEnd + opts.pause + i * opts.cycle;81}8283/**84 * Which word is showing at `frame`, and how far into its flip we are.85 *86 * `index` is the word entering (or resting); `local` is frames since that87 * flip began, and is negative while the previous word is still holding.88 */89export function wordAt(90 frame: number,91 opts: {92 typingEnd: number;93 pause: number;94 cycle: number;95 wordCount: number;96 loop: boolean;97 },98): { index: number; local: number } {99 const first = flipStartFrame(0, opts);100 if (frame < first) return { index: 0, local: frame - first };101 const n = Math.floor((frame - first) / opts.cycle);102 const local = frame - first - n * opts.cycle;103 // Flip n takes word n -> word n+1. Before the first flip the slot is empty, so104 // flip 0 brings in word 0 and flip k brings in word k.105 const raw = n;106 const index = opts.loop107 ? ((raw % opts.wordCount) + opts.wordCount) % opts.wordCount108 : Math.min(raw, opts.wordCount - 1);109 return { index, local };110}111112/**113 * The anticipation curve — `easeInBack`.114 *115 * The reference does not simply throw the word upward: it sinks it first. That116 * backswing is the whole reason the flip reads as weight rather than as a cut,117 * and it is not a separate keyframe — one `easeInBack` progress drives the118 * translate and the rotation together, so the dip and the throw are the same119 * gesture.120 *121 * Its minimum is `p = -0.100` at `t = 2s/(3(s+1)) = 0.42`. Measured off the122 * reference: the dip bottoms out at t = 0.44 of the exit and is worth 0.100 of123 * the exit travel. That is the curve, not an approximation of it.124 */125export function easeInBack(t: number, s = 1.70158): number {126 return t * t * ((s + 1) * t - s);127}128129/**130 * Speed of {@link easeInBack}, normalised so the fastest instant is 1.131 *132 * The blur is a shutter, not a ramp: it has to be proportional to how fast the133 * word is actually travelling. That is not a stylistic preference, it is what134 * the reference does — at the bottom of the dip the word has *stopped* to turn135 * around, and it is sharp there; three frames later it is flying and it is136 * smeared. A blur keyed to progress instead of speed blurs the word while it is137 * standing still, which reads as a focus pull.138 *139 * `easeInBack` is a cubic, so this is exact rather than sampled — and its140 * derivative is zero precisely at the turnaround, which is the frame that has141 * to be sharp.142 */143export function easeInBackSpeed(t: number, s = 1.70158): number {144 const d = 3 * (s + 1) * t * t - 2 * s * t;145 const peak = 3 * (s + 1) - 2 * s; // the derivative at t = 1, its maximum146 return Math.abs(d) / peak;147}148149/**150 * Uniform scale that makes every word fill the same slot.151 *152 * The reference pins *both* edges of the slot: all three words measure the same153 * width to within 1%, while their heights differ by up to 6% — exactly inversely154 * with their aspect ratios. That identity only closes if each word is scaled to155 * a common width, and it is what makes the layout incapable of reflowing: the156 * widest word sits at scale 1 and the rest are scaled up to meet it.157 */158export function fitScales(widths: number[]): number[] {159 const max = Math.max(...widths, 1);160 return widths.map((w) => (w > 0 ? max / w : 1));161}162163export interface WordFlipMotion {164 /** How far the outgoing word is thrown, in em. Negative is up. */165 exitY: number;166 /** How far below rest the incoming word starts, in em. */167 enterY: number;168 /** Degrees the word rotates about the baseline. */169 rotate: number;170 /** Scale the outgoing word shrinks to (and the incoming grows from). */171 scale: number;172 /** Peak blur, in em. */173 blur: number;174}175176/** Measured off the reference. See the doc page for the derivation. */177export const DEFAULT_MOTION: WordFlipMotion = {178 // 0.100 x 1.29em = 0.13em of backswing, which is the ~10px dip the reference179 // shows at a 72px font.180 exitY: -1.29,181 enterY: 0.135,182 rotate: 90,183 scale: 0.98,184 blur: 0.085,185};186187export interface WordFlipProps {188 /** Text before the flipping word. */189 prefix?: string;190 /** The words that cycle through the slot. */191 words?: string[];192 /** Text after the flipping word. */193 suffix?: string;194 /**195 * Gradient painted on the flipping word, left to right. Defaults to the196 * design system's accent walked toward `destructive` — a two-stop ramp that197 * follows a user's theme instead of a fixed blue-to-pink.198 */199 gradient?: string[];200 /** Typing speed, characters per second. */201 cps?: number;202 /** Frames before the first keystroke. */203 typeStart?: number;204 /** Frames each character takes to fade in. */205 charFade?: number;206 /** Keystroke unevenness, as a fraction of one keystroke. 0 is a metronome. */207 jitter?: number;208 /** Frames held after the sentence completes, before the first flip. */209 pause?: number;210 /** Frames from one flip to the next. */211 cycle?: number;212 /** Frames the outgoing word takes to leave. */213 exitDuration?: number;214 /** Frames the incoming word takes to settle. */215 enterDuration?: number;216 /** Frames the incoming word starts before the outgoing one is gone. */217 overlap?: number;218 /** Show a blinking caret while typing. The reference has none. */219 caret?: boolean;220 /** Keep cycling the words forever. */221 loop?: boolean;222 motion?: Partial<WordFlipMotion>;223 /** 3D depth, in em. Smaller is a stronger perspective. */224 perspective?: number;225 /**226 * The typeface. Defaults to the shadcn app's sans stack. A headline is set in227 * *your* type, and the inline style would otherwise beat anything a className228 * could say — so this is the prop that lets it.229 */230 fontFamily?: string;231 fontSize?: number;232 /** Overrides the design system's `foreground`. */233 color?: string;234 fontWeight?: number;235 speed?: number;236 className?: string;237 /** Design-system token overrides. */238 theme?: Partial<KuchiTheme>;239 mode?: "light" | "dark";240}241242const FONT_FAMILY = "-apple-system, BlinkMacSystemFont, sans-serif";243244export function WordFlip({245 prefix = "Looking For A",246 words = ["Modern", "Stunning", "Minimal"],247 suffix = "Portfolio",248 gradient,249 cps = 9,250 typeStart = 4,251 charFade = 6,252 jitter = 0.18,253 pause = 6,254 cycle = 35,255 exitDuration = 9,256 enterDuration = 9,257 overlap = 3,258 caret = true,259 loop = true,260 motion,261 perspective = 6.5,262 fontFamily,263 fontSize = 72,264 color,265 fontWeight = 600,266 speed = 1,267 className,268 theme,269 mode,270}: WordFlipProps) {271 const frame = useCurrentFrame() * speed;272 const { fps } = useVideoConfig();273 const t = useKuchiTheme(theme, mode);274 const face = resolveFont(fontFamily ?? t.fontFamily) ?? FONT_FAMILY;275 const fill = color ?? t.foreground;276 const stops = gradient ?? [277 t.primary,278 mixOklch(t.primary, t.destructive, 0.45),279 ];280281 const m = { ...DEFAULT_MOTION, ...motion };282283 // ---------------------------------------------------------------------------284 // Measure. offsetWidth/offsetTop are *layout* px — untouched by the transforms285 // we are about to apply, which is exactly why they are the right tool here. We286 // measure in a hidden, untransformed copy so frame 0 can never be captured287 // against the wrong geometry.288 // ---------------------------------------------------------------------------289 const [metrics, setMetrics] = useState<{290 widths: number[];291 baseline: number;292 } | null>(null);293 const [handle] = useState(() => delayRender("word-flip: measuring the slot"));294 const wordRefs = useRef<(HTMLSpanElement | null)[]>([]);295 const baselineRef = useRef<HTMLSpanElement | null>(null);296297 useEffect(() => {298 if (metrics) {299 // Only now has the measured geometry actually rendered.300 continueRender(handle);301 return;302 }303 const widths = words.map((_, i) => wordRefs.current[i]?.offsetWidth ?? 0);304 const baseline = baselineRef.current?.offsetTop ?? 0;305 if (widths.length > 0 && widths.every((w) => w > 0)) {306 setMetrics({ widths, baseline });307 }308 }, [metrics, handle, words]);309310 const scales = metrics ? fitScales(metrics.widths) : words.map(() => 1);311 const slotWidth = metrics ? Math.max(...metrics.widths) : 0;312 const baseline = metrics?.baseline ?? 0;313314 // ---------------------------------------------------------------------------315 // Timeline316 // ---------------------------------------------------------------------------317 const chars = [...prefix, ...suffix];318 const clock = { typeStart, cps, fps, jitter };319 const typingEnd = typingEndFrame({320 charCount: chars.length,321 charFade,322 ...clock,323 });324 const schedule = { typingEnd, pause, cycle, wordCount: words.length, loop };325 const { index: entering, local } = wordAt(frame, schedule);326327 const em = fontSize;328 const outgoing = entering - 1;329 const enterStart = Math.max(0, exitDuration - overlap);330331 /** The word that is leaving: one `easeInBack` progress drives everything. */332 const exitAt = (localFrame: number) => {333 const t = interpolate(localFrame, [0, exitDuration], [0, 1], CLAMP);334 const p = easeInBack(t);335 return {336 y: p * m.exitY * em,337 rotate: p * m.rotate,338 scale: 1 + p * (m.scale - 1),339 blur: easeInBackSpeed(t) * m.blur * em,340 // Solid until it is genuinely on its way out. A word that starts dimming on341 // the backswing reads as a crossfade; the reference holds it almost fully342 // opaque through the throw and then it is simply gone.343 opacity: interpolate(t, [0.65, 1], [1, 0], CLAMP),344 };345 };346347 /** The word that is arriving. A moderate decelerate — see motion-quality. */348 const enterAt = (localFrame: number) => {349 const p = interpolate(350 localFrame,351 [enterStart, enterStart + enterDuration],352 [0, 1],353 { ...CLAMP, easing: Easing.bezier(0.2, 0.6, 0.35, 1) },354 );355 return {356 y: (1 - p) * m.enterY * em,357 rotate: -(1 - p) * m.rotate,358 scale: m.scale + p * (1 - m.scale),359 blur: (1 - p) * m.blur * em,360 opacity: interpolate(p, [0, 0.45], [0, 1], CLAMP),361 };362 };363364 const stateFor = (i: number) => {365 if (i === entering && local >= enterStart) return enterAt(local);366 if (i === outgoing && local >= 0 && local <= exitDuration)367 return exitAt(local);368 if (i === entering && local > exitDuration) return enterAt(local);369 // Resting: the word that is showing between flips.370 if (i === entering && local < 0)371 return { y: 0, rotate: 0, scale: 1, blur: 0, opacity: 0 };372 return null;373 };374375 // The Player is one continuous tab and hands the transform to the compositor;376 // a render is spread across tabs that each inherit a stale raster, so the same377 // hint there makes the type shimmer while standing still.378 const gpu = getRemotionEnvironment().isRendering379 ? null380 : ({ willChange: "transform, opacity, filter" } as const);381382 const lineStyle: React.CSSProperties = {383 fontSize,384 fontWeight,385 color: fill,386 letterSpacing: "-0.02em",387 fontFamily: face,388 lineHeight: 1.25,389 whiteSpace: "pre",390 // Hinting re-snaps every stem to the pixel grid as the size slides, so the391 // letterforms change shape frame to frame. Off, the type reads a shade392 // softer — that is the absence of a lie, not blur.393 textRendering: "geometricPrecision",394 };395396 const wordPaint: React.CSSProperties = {397 backgroundImage: `linear-gradient(90deg, ${stops.join(", ")})`,398 WebkitBackgroundClip: "text",399 backgroundClip: "text",400 color: "transparent",401 WebkitTextFillColor: "transparent",402 };403404 const typedChar = (ch: string, i: number) => {405 const start = charStartFrame(i, clock);406 return (407 <span408 key={i}409 style={{410 opacity: interpolate(frame, [start, start + charFade], [0, 1], CLAMP),411 }}412 >413 {ch}414 </span>415 );416 };417418 // The caret rides the typing head. It is a zero-width inline-block with an419 // absolutely-positioned bar inside, so it cannot push a single glyph sideways420 // — the sentence's geometry has to be identical with it and without it.421 const caretIndex = Math.max(422 0,423 Math.min(424 chars.length,425 Math.floor((frame - typeStart) / framesPerChar(cps, fps)) + 1,426 ),427 );428 const caretDone = frame > typingEnd + pause;429 const showCaret = caret && !caretDone && frame >= typeStart;430 const blink = Math.floor((frame / fps) * 2) % 2 === 0 ? 1 : 0.15;431432 const Caret = () => (433 <span434 style={{435 position: "relative",436 display: "inline-block",437 width: 0,438 verticalAlign: "baseline",439 }}440 >441 <span442 style={{443 position: "absolute",444 left: 0.06 * em,445 bottom: 0,446 width: Math.max(2, 0.055 * em),447 height: 0.78 * em,448 background: fill,449 opacity: blink,450 borderRadius: 1,451 }}452 />453 </span>454 );455456 const prefixChars = chars.slice(0, prefix.length);457 const suffixChars = chars.slice(prefix.length);458 const caretInPrefix = caretIndex <= prefix.length;459460 return (461 <AbsoluteFill462 className={className}463 style={{464 alignItems: "center",465 justifyContent: "center",466 background: "transparent",467 }}468 >469 {/*470 The measuring copy. Hidden, never transformed, laid out exactly like the471 real line so the widths and the baseline it reports are the ones the real472 line will use.473 */}474 {!metrics && (475 <span476 aria-hidden477 style={{478 ...lineStyle,479 position: "absolute",480 visibility: "hidden",481 pointerEvents: "none",482 left: 0,483 top: 0,484 }}485 >486 {words.map((w, i) => (487 <span488 // biome-ignore lint/suspicious/noArrayIndexKey: words are positional489 key={i}490 ref={(el) => {491 wordRefs.current[i] = el;492 }}493 style={{ display: "inline-block" }}494 >495 {w}496 {i === 0 && (497 // A zero-sized inline-block sits ON the baseline, so its498 // offsetTop *is* the baseline. Never derive it from line-height.499 <span500 ref={baselineRef}501 style={{ display: "inline-block", width: 0, height: 0 }}502 />503 )}504 </span>505 ))}506 </span>507 )}508509 <span style={lineStyle}>510 {prefixChars.map((ch, i) => typedChar(ch, i))}511 {showCaret && caretInPrefix && <Caret />}{" "}512 {/*513 The slot. Fixed width from the widest word, so it is reserved before the514 first word ever arrives — during typing it is the gap the reference515 shows between "A" and "Portfolio" — and nothing downstream of it can516 ever move.517 */}518 <span519 style={{520 display: "inline-block",521 position: "relative",522 width: slotWidth || undefined,523 perspective: perspective * em,524 verticalAlign: "baseline",525 }}526 >527 {/* In-flow strut: gives the inline-block its height and its baseline. */}528 <span aria-hidden style={{ visibility: "hidden" }}>529 {words[0] ?? ""}530 </span>531532 {words.map((w, i) => {533 const s = stateFor(i);534 if (!s || s.opacity <= 0) return null;535 return (536 <span537 // biome-ignore lint/suspicious/noArrayIndexKey: words are positional538 key={i}539 style={{540 ...wordPaint,541 ...gpu,542 position: "absolute",543 left: 0,544 top: 0,545 display: "inline-block",546 width: "max-content",547 // Everything pivots on the baseline. Anywhere else and the548 // glyph origins climb the pixel grid in whole-pixel jumps as549 // the scale moves the baseline, and the word sits still, jumps,550 // sits still.551 transformOrigin: `0px ${baseline}px`,552 transform: `translateY(${s.y}px) rotateX(${s.rotate}deg) scale(${553 scales[i] * s.scale554 })`,555 opacity: s.opacity,556 filter: s.blur > 0.01 ? `blur(${s.blur}px)` : undefined,557 }}558 >559 {w}560 </span>561 );562 })}563 </span>{" "}564 {suffixChars.map((ch, i) => typedChar(ch, prefix.length + i))}565 {showCaret && !caretInPrefix && <Caret />}566 </span>567 </AbsoluteFill>568 );569}









