Rubberband Word
A cursor grabs a word by its last letter, stretches it and snaps it into a new word.
Source
components/kuchi/rubberband-word.tsx
1"use client";23import { loadFont } from "@remotion/google-fonts/Sora";4import type React from "react";5import { useId } from "react";6import {7 AbsoluteFill,8 Easing,9 interpolate,10 spring,11 useCurrentFrame,12 useVideoConfig,13} from "remotion";1415const { fontFamily: sans } = loadFont("normal", {16 weights: ["500"],17 subsets: ["latin"],18});1920export interface RubberbandWordProps {21 /** The word the cursor grabs by its last letter. */22 word?: string;23 /** What the word becomes on the snap. Leave empty to keep the word and only accent it. */24 snapWord?: string;25 /** Close the final word with an accent period. */26 period?: boolean;27 accent?: string;28 /** Text color of the word; overrides the theme ink. */29 ink?: string;30 /** Background fill; "transparent" drops it. */31 background?: string;32 /** Frames the stretched word holds before it snaps back. */33 hold?: number;34 /** How far the cursor pulls the last letter; 1 is a fifth of the frame width. */35 stretch?: number;36 /** Size of the word and cursor, around the frame's center. */37 scale?: number;38 /** Frames to hold the first frame before anything moves. */39 delay?: number;40 theme?: "dark" | "light";41 speed?: number;42}4344// Sora 500, per 1000 em, chars 32–126 (harfbuzz, wght 500).45const ADV = [46 222, 303, 452, 702, 652, 864, 702, 264, 382, 382, 568, 592, 266, 506, 266,47 365, 750, 423, 623, 620, 652, 630, 668, 585, 647, 668, 266, 266, 592, 590,48 592, 556, 1124, 765, 684, 797, 788, 598, 560, 832, 803, 320, 641, 703, 549,49 937, 858, 865, 649, 865, 710, 682, 602, 785, 719, 1052, 705, 654, 652, 382,50 365, 382, 587, 581, 300, 581, 694, 608, 694, 616, 380, 679, 644, 317, 324,51 595, 296, 973, 644, 678, 694, 694, 414, 543, 429, 634, 572, 873, 574, 555,52 493, 382, 375, 382, 511,53];54const RSB = [55 0, 81, 81, 35, 50, 31, 25, 80, 13, 64, 45, 60, 51, 59, 65, 23, 67, 110, 53,56 55, 24, 42, 47, 31, 47, 66, 65, 48, 74, 60, 74, 43, 61, 23, 60, 33, 41, 59,57 44, 31, 98, 100, 86, -9, 26, 98, 98, 51, 32, 51, 21, 49, 24, 84, 28, 27, 15,58 15, 43, 50, 15, 102, 60, 0, 86, 77, 48, 35, 86, 40, 10, 80, 77, 88, 84, 1, 86,59 77, 77, 48, 48, 86, 18, 42, 41, 88, 30, 34, 16, 24, 34, 43, 136, 52, 20,60];61const LSB = [62 0, 82, 81, 35, 49, 31, 29, 81, 64, 13, 45, 61, 20, 59, 65, 23, 67, 39, 62, 41,63 43, 53, 66, 43, 47, 47, 65, 23, 74, 61, 74, 36, 61, 23, 98, 52, 98, 98, 98,64 52, 98, 100, 37, 98, 98, 98, 98, 52, 98, 52, 98, 48, 25, 84, 22, 27, 14, 13,65 54, 102, 15, 50, 61, 0, 0, 41, 86, 48, 48, 48, 28, 48, 86, 33, 0, 86, 21, 86,66 86, 48, 86, 48, 86, 39, 12, 74, 21, 23, 23, 14, 49, 52, 136, 43, 20,67];68// Lowercase + period kerning pairs, |k| >= 10/1000.69const KERN = new Map(70 [71 "bv-11 bw-11 bx-12 by-11 b.-13 ff-38 fl12 fv17 fw17 fy17 f.-43 kc-15",72 "kd-15 ke-15 kg-15 ko-15 kq-15 ks-10 ov-11 ow-11 ox-12 oy-11 o.-13",73 "pv-11 pw-11 px-12 py-11 p.-13 qj15 rt11 rv18 rw18 ry18 r.-61 vc-11",74 "vd-11 ve-11 vg-11 vo-11 vq-11 vt10 v.-37 wc-11 wd-11 we-11 wg-11 wo-11",75 "wq-11 wt10 w.-37 xa-10 xc-12 xd-12 xe-12 xg-12 xo-12 xq-12 xu-12 yc-11",76 "yd-11 ye-11 yg-11 yo-11 yq-11 yt10 y.-37 .c-13 .d-13 .e-13 .g-13 .o-13",77 ".q-13 .u-17 .v-37 .w-37 .y-37",78 ]79 .join(" ")80 .split(" ")81 .map((p) => [p.slice(0, 2), Number(p.slice(2)) / 1000] as const),82);83// Sora's hhea box is 0.97 + 0.29 em; with lineHeight 1 the baseline sits at 0.84.84const TRACK = -0.03;85const BASELINE = 0.84;86const XHEIGHT = 0.534;8788const EASE_OUT = Easing.bezier(0.22, 1, 0.36, 1);89const EASE_IO = Easing.bezier(0.65, 0, 0.35, 1);90const CLAMP = {91 extrapolateLeft: "clamp",92 extrapolateRight: "clamp",93} as const;9495// gradients.sh "halo" palette (#fff4ec #ffb36b #e2457a #3d4dff), warm end at96// the word, accent end at the pulled letter. The band carries it while pulled;97// the snapped word inherits it. Light swaps the pale amber for one that reads.98const THEMES = {99 dark: { bg: "#0A0A0B", fg: "#F3F2EF", halo: ["#FFB36B", "#E2457A"] },100 light: { bg: "#F5F4F0", fg: "#121214", halo: ["#E8743A", "#D83A71"] },101} as const;102103// Beats (frames at speed 1).104const GRAB = 22;105const DRAG_END = 56;106const RELEASE = 64;107108function adv(ch: string) {109 const c = ch.charCodeAt(0);110 return (c >= 32 && c < 127 ? ADV[c - 32] : 600) / 1000;111}112function lsb(ch: string) {113 const c = ch.charCodeAt(0);114 return (c >= 32 && c < 127 ? LSB[c - 32] : 50) / 1000;115}116function rsb(ch: string) {117 const c = ch.charCodeAt(0);118 return (c >= 32 && c < 127 ? RSB[c - 32] : 50) / 1000;119}120121/** Glyph left edges and widths in em, plus the total advance. */122function layout(text: string) {123 const xs: number[] = [];124 const ws: number[] = [];125 let x = 0;126 for (let i = 0; i < text.length; i++) {127 if (i > 0) x += (KERN.get(text[i - 1] + text[i]) ?? 0) + TRACK;128 xs.push(x);129 ws.push(adv(text[i]));130 x += adv(text[i]);131 }132 return { xs, ws, width: x };133}134135/**136 * The elastic. Pulled (`s > 0`): the grabbed last glyph travels with the137 * cursor, the letters before it spread a little toward it and squash. On the138 * overshoot (`s < 0`) the whole word compresses evenly, so nothing overlaps.139 */140function elastic(141 i: number,142 count: number,143 xs: number[],144 s: number,145 sMax: number,146) {147 const last = count - 1;148 const u = count > 1 ? (xs[i] - xs[0]) / Math.max(1e-3, xs[last] - xs[0]) : 1;149 if (s >= 0) {150 const k = s / sMax;151 if (i === last) return { dx: s, sx: 1 + 0.07 * k, sy: 1 - 0.07 * k };152 return {153 dx: s * 0.16 * u ** 1.3,154 sx: 1 + 0.05 * k * u,155 sy: 1 - 0.05 * k * u,156 };157 }158 const k = Math.max(-1, s / (sMax * 0.14));159 return { dx: s * 0.5 * u, sx: 1 + 0.05 * k * u, sy: 1 - 0.07 * k * u };160}161162/** Taffy band between the word and the pulled letter: thins and pinches as it grows. */163function bandPath(164 xL: number,165 xR: number,166 cy: number,167 xh: number,168 F: number,169 thinAs: number,170) {171 const L = Math.max(0, xR - xL);172 const thin = (1 / (1 + Math.max(0, thinAs) / (0.55 * F))) ** 0.85;173 const a = xh * 0.5 * Math.max(0.2, thin * 0.75);174 const b = xh * 0.5 * Math.max(0.4, 0.95 * thin ** 0.4);175 const c = a * (0.62 + 0.38 * thin);176 const h1 = xL + L * 0.38;177 const h2 = xR - L * 0.38;178 return [179 `M${xL} ${cy - a}`,180 `C${h1} ${cy - c} ${h2} ${cy - c} ${xR} ${cy - b}`,181 `L${xR} ${cy + b}`,182 `C${h2} ${cy + c} ${h1} ${cy + c} ${xL} ${cy + a}`,183 `A${a} ${a} 0 0 1 ${xL} ${cy - a}Z`,184 ].join("");185}186187function Cursor({ size, pressed }: { size: number; pressed: number }) {188 return (189 <svg190 width={size * 0.7}191 height={size}192 viewBox="0 0 17.5 25"193 style={{194 position: "absolute",195 left: 0,196 top: 0,197 overflow: "visible",198 transformOrigin: "6% 6%",199 transform: `scale(${1 - 0.1 * pressed})`,200 filter: "drop-shadow(0 1.5px 2px rgba(0,0,0,0.32))",201 }}202 aria-hidden203 >204 <path205 d="M1.5 1.5 L1.5 20.6 L6.1 16.3 L9.1 23.2 L12.6 21.7 L9.7 14.9 L15.9 14.9 Z"206 fill="#0A0A0B"207 stroke="#FFFFFF"208 strokeWidth={1.4}209 strokeLinejoin="round"210 />211 </svg>212 );213}214215/** The foreground at `scale`, around the frame's center; nothing extra at 1. */216function ScaleLayer({217 scale,218 children,219}: {220 scale: number;221 children: React.ReactNode;222}) {223 if (scale === 1) return children;224 return (225 <AbsoluteFill style={{ transform: `scale(${scale})` }}>226 {children}227 </AbsoluteFill>228 );229}230231export function RubberbandWord({232 word = "tension",233 snapWord = "release",234 period = true,235 accent = "#3B5BFD",236 ink,237 background,238 hold = RELEASE - DRAG_END,239 stretch = 1,240 scale = 1,241 delay = 0,242 theme = "dark",243 speed = 1,244}: RubberbandWordProps) {245 const frame = Math.max(0, useCurrentFrame() - delay) * speed;246 const { width: W, height: H, fps } = useVideoConfig();247 const uid = useId().replace(/[^a-zA-Z0-9_-]/g, "");248 const t = THEMES[theme];249 const fg = ink ?? t.fg;250 // interpolate() needs a rising range from DRAG_END, so the hold is at least a frame.251 const release = DRAG_END + Math.max(1, hold);252253 const from = word.trim() || "tension";254 const to = snapWord.trim() || from;255 const swaps = to !== from;256257 const A = layout(from);258 const B = layout(to);259 const dotW = period ? adv(".") + TRACK : 0;260 const longest = Math.max(A.width, B.width + dotW);261 const F = Math.min(H * 0.27, (W * 0.54) / longest);262 const xh = XHEIGHT * F;263 const baseline = H * 0.5 + xh * 0.5;264 const cy = baseline - xh * 0.5;265 const leftA = (W - A.width * F) / 2;266 const leftB = swaps ? (W - (B.width + dotW) * F) / 2 : leftA;267 const sMax = W * 0.21 * stretch;268269 // Pull: drag out, hold the tension, then let go with one damped overshoot.270 const drag = interpolate(frame, [GRAB + 4, DRAG_END], [0, 1], {271 ...CLAMP,272 easing: EASE_IO,273 });274 const creep = interpolate(frame, [DRAG_END, release], [0, 1], {275 ...CLAMP,276 easing: Easing.bezier(0.22, 1, 0.36, 1),277 });278 const held = sMax * (0.95 * drag + 0.05 * creep);279 const snap = spring({280 frame: frame - release,281 fps,282 config: { damping: 15, stiffness: 230, mass: 1 },283 });284 const s = frame < release ? held : sMax * (1 - snap);285286 // Grab point: the last glyph's right stem, at mid x-height.287 const lastA = from.length - 1;288 const grabX0 =289 leftA + (A.xs[lastA] + A.ws[lastA] - rsb(from[lastA])) * F - F * 0.05;290 const press = interpolate(291 frame,292 [GRAB, GRAB + 3, release, release + 4],293 [0, 1, 1, 0],294 CLAMP,295 );296 const approach = interpolate(frame, [0, GRAB], [0, 1], {297 ...CLAMP,298 easing: EASE_IO,299 });300 const startX = W * 0.8;301 const startY = H * 0.86;302 const arc = Math.sin(approach * Math.PI) * H * 0.05;303 const away = interpolate(frame, [release + 1, release + 26], [0, 1], {304 ...CLAMP,305 easing: EASE_OUT,306 });307 const lift = H * 0.015 * (0.95 * drag + 0.05 * creep);308 let cx = startX + (grabX0 - startX) * approach + arc * 0.5;309 let cyCursor = startY + (cy - startY) * approach + arc;310 if (frame >= GRAB) {311 cx = grabX0 + held;312 cyCursor = cy - lift;313 }314 if (frame >= release) {315 cx = grabX0 + sMax + W * 0.03 * away;316 cyCursor = cy - H * 0.015 + H * 0.06 * away;317 }318 const cursorOpacity = interpolate(319 frame,320 [release + 8, release + 22],321 [1, 0],322 CLAMP,323 );324 const cursorSize = H * 0.085;325326 // The swap rides the snap: the old word squashes flat onto its baseline,327 // the new one springs up out of that line with one overshoot.328 const SWAP = release + 4;329 const clipTop = baseline - F * 0.98;330 const clipH = F * 1.24;331 const squash = (i: number, count: number, incoming: boolean) => {332 const start = SWAP + (count - 1 - i) * 0.5 + (incoming ? 4 : 0);333 if (!incoming) {334 return interpolate(frame, [start, start + 5], [1, 0], {335 ...CLAMP,336 easing: Easing.bezier(0.55, 0, 1, 0.45),337 });338 }339 return spring({340 frame: frame - start,341 fps,342 config: { damping: 12, stiffness: 240, mass: 0.8 },343 });344 };345 const halo = [t.halo[0], t.halo[1], accent];346 const wordGradient = `linear-gradient(90deg, ${halo[0]} 0%, ${halo[1]} 52%, ${halo[2]} 100%)`;347 // The fill is a touch wider than the word and slides a few percent so the348 // last letter settles on the accent, next to the accent period.349 const gradW = B.width * F * 1.12;350 const gradShift =351 B.width *352 F *353 0.12 *354 interpolate(frame, [release, release + 60], [0, 1], {355 ...CLAMP,356 easing: Easing.bezier(0.45, 0, 0.55, 1),357 });358 const accentOn = interpolate(frame, [GRAB, GRAB + 3], [0, 1], CLAMP) > 0.5;359360 const glyphs = (361 text: string,362 L: ReturnType<typeof layout>,363 left: number,364 incoming: boolean,365 ) =>366 text.split("").map((ch, i) => {367 const g = elastic(i, text.length, L.xs, s, sMax);368 const q = swaps ? squash(i, text.length, incoming) : 1;369 if (q <= 0.01) return null;370 const isLast = i === text.length - 1;371 const color =372 !incoming && isLast && accentOn && (swaps || frame < release + 6)373 ? accent374 : fg;375 const w = L.ws[i] * F;376 // The snapped word wears the gradient; without a swap the word itself does.377 const fill: React.CSSProperties =378 incoming || (!swaps && frame >= release + 6)379 ? {380 color: "transparent",381 backgroundImage: wordGradient,382 backgroundRepeat: "no-repeat",383 backgroundSize: `${gradW}px ${F}px`,384 backgroundPosition: `${-L.xs[i] * F - gradShift}px 0px`,385 WebkitBackgroundClip: "text",386 backgroundClip: "text",387 }388 : { color };389 return (390 <span391 key={`${uid}-${incoming ? "b" : "a"}-${i}`}392 style={{393 position: "absolute",394 left: left + L.xs[i] * F + g.dx,395 top: baseline - clipTop - BASELINE * F,396 width: w,397 fontSize: F,398 lineHeight: 1,399 ...fill,400 opacity: Math.min(1, q * 6),401 transformOrigin: `50% ${BASELINE * F}px`,402 transform: `scale(${g.sx}, ${g.sy * q})`,403 whiteSpace: "pre",404 }}405 >406 {ch}407 </span>408 );409 });410411 // Band: from just inside the previous glyph to the pulled glyph's left stem.412 let band = "";413 let bandX: [number, number] = [0, 1];414 const bandOpacity =415 interpolate(s, [sMax * 0.02, sMax * 0.1], [0, 1], CLAMP) *416 interpolate(frame, [release, release + 5], [1, 0], CLAMP);417 if (from.length > 1 && bandOpacity > 0) {418 const prev = lastA - 1;419 const gp = elastic(prev, from.length, A.xs, s, sMax);420 const gl = elastic(lastA, from.length, A.xs, s, sMax);421 const wp = A.ws[prev] * F;422 const wl = A.ws[lastA] * F;423 const xL =424 leftA +425 A.xs[prev] * F +426 gp.dx +427 wp / 2 +428 (wp / 2 - rsb(from[prev]) * F) * gp.sx -429 F * 0.1;430 const xR =431 leftA +432 A.xs[lastA] * F +433 gl.dx +434 wl / 2 -435 (wl / 2 - lsb(from[lastA]) * F) * gl.sx +436 F * 0.05;437 // After the release the band stays thin while it whips back and fades.438 const thinAs = frame >= release ? Math.max(xR - xL, sMax * 0.8) : xR - xL;439 band = bandPath(xL, xR, cy, xh * gl.sy, F, thinAs);440 bandX = [xL - xh * 0.3, xR];441 }442443 const dotIn = interpolate(frame, [SWAP + 10, SWAP + 20], [0, 1], {444 ...CLAMP,445 easing: EASE_OUT,446 });447 const lastB = to.length - 1;448 const gB = elastic(lastB, to.length, B.xs, s, sMax);449 const dotLeft = leftB + (B.xs[lastB] + B.ws[lastB] + TRACK) * F + gB.dx;450451 return (452 <AbsoluteFill453 style={{454 background:455 background === "transparent" ? undefined : (background ?? t.bg),456 }}457 >458 <ScaleLayer scale={scale}>459 {band ? (460 <svg461 width={W}462 height={H}463 style={{ position: "absolute", inset: 0 }}464 aria-hidden465 >466 <defs>467 <linearGradient468 id={`${uid}-band`}469 gradientUnits="userSpaceOnUse"470 x1={bandX[0]}471 y1={0}472 x2={bandX[1]}473 y2={0}474 >475 <stop offset="0" stopColor={halo[0]} />476 <stop offset="0.55" stopColor={halo[1]} />477 <stop offset="1" stopColor={halo[2]} />478 </linearGradient>479 </defs>480 <path d={band} fill={`url(#${uid}-band)`} opacity={bandOpacity} />481 </svg>482 ) : null}483 <div484 style={{485 position: "absolute",486 left: 0,487 top: clipTop,488 width: W,489 height: clipH,490 overflow: "hidden",491 fontFamily: sans,492 fontWeight: 500,493 }}494 >495 {glyphs(from, A, leftA, false)}496 {swaps ? glyphs(to, B, leftB, true) : null}497 {period ? (498 <span499 style={{500 position: "absolute",501 left: dotLeft,502 top: baseline - clipTop - BASELINE * F,503 fontSize: F,504 lineHeight: 1,505 color: accent,506 opacity: dotIn,507 transformOrigin: `30% ${BASELINE * F}px`,508 transform: `scale(${0.6 + 0.4 * dotIn})`,509 }}510 >511 .512 </span>513 ) : null}514 </div>515 <div516 style={{517 position: "absolute",518 left: cx - cursorSize * 0.06,519 top: cyCursor - cursorSize * 0.06,520 opacity: cursorOpacity,521 }}522 >523 <Cursor size={cursorSize} pressed={press} />524 </div>525 </ScaleLayer>526 </AbsoluteFill>527 );528}









