Inline Word Roll
Roll through words beside a fixed prefix with accelerating timing and smoothly centered width.
Source
components/kuchi/inline-word-roll.tsx
1"use client";23import { useLayoutEffect, useRef, useState } from "react";4import {5 Easing,6 useCurrentFrame,7 useDelayRender,8 useVideoConfig,9} from "remotion";1011export interface InlineWordRollProps {12 prefix?: string;13 /** Separate words or phrases with | or newlines. */14 text?: string;15 suffix?: string;16 fontSize?: number;17 fontFamily?: string;18 fontWeight?: number;19 color?: string;20 /** Initial interval between switches, in frames. */21 interval?: number;22 /** Each following interval is multiplied by this number; 1 keeps a steady pace. */23 acceleration?: number;24 transitionFrames?: number;25}2627export const inlineWordRollDefaultText =28 "leads | customers | subscribers | appointments | demos | quotes | registrants | trials | conversions";2930export const parseInlineWords = (text: string) =>31 text32 .split(/[|\n\r]+/)33 .map((word) => word.trim())34 .filter(Boolean);3536const finite = (value: number, fallback: number) =>37 Number.isFinite(value) ? value : fallback;38const clamp = (n: number) => Math.max(0, Math.min(1, n));39const ease = Easing.bezier(0.22, 0.75, 0.25, 1);4041export function getInlineWordRollState(42 frame: number,43 count: number,44 interval = 12,45 acceleration = 0.9,46 transitionFrames = 6,47) {48 const transition = Math.max(1, finite(transitionFrames, 6));49 const gap = Math.max(transition, finite(interval, 12));50 const rate = Math.min(1, Math.max(0.5, finite(acceleration, 0.9)));51 const f = Math.max(0, finite(frame, 0));52 let start = 0;53 for (let index = 1; index < count; index++) {54 start += Math.max(transition, gap * rate ** (index - 1));55 if (f < start) return { from: index - 1, to: index - 1, progress: 1 };56 if (f < start + transition)57 return {58 from: index - 1,59 to: index,60 progress: clamp((f - start) / transition),61 };62 }63 const last = Math.max(0, count - 1);64 return { from: last, to: last, progress: 1 };65}6667export function getInlineWordRollDuration({68 text = inlineWordRollDefaultText,69 interval = 12,70 acceleration = 0.9,71 transitionFrames = 6,72}: Pick<73 InlineWordRollProps,74 "text" | "interval" | "acceleration" | "transitionFrames"75> = {}) {76 const count = parseInlineWords(text).length;77 const transition = Math.max(1, finite(transitionFrames, 6));78 const gap = Math.max(transition, finite(interval, 12));79 const rate = Math.min(1, Math.max(0.5, finite(acceleration, 0.9)));80 let total = 0;81 for (let index = 0; index < count - 1; index++)82 total += Math.max(transition, gap * rate ** index);83 return count < 2 ? 0 : Math.ceil(total + transition);84}8586export function InlineWordRoll({87 prefix = "Looking for",88 text = inlineWordRollDefaultText,89 suffix = "?",90 fontSize = 60,91 fontFamily = "Arial, Helvetica, sans-serif",92 fontWeight = 400,93 color = "#f5f5f5",94 interval = 12,95 acceleration = 0.9,96 transitionFrames = 6,97}: InlineWordRollProps) {98 const frame = useCurrentFrame();99 const { width, height } = useVideoConfig();100 const { delayRender, continueRender, cancelRender } = useDelayRender();101 const words = parseInlineWords(text);102 const measurement = useRef<HTMLDivElement>(null);103 const pending = useRef<number | null>(null);104 const [metrics, setMetrics] = useState<{105 prefix: number;106 words: number[];107 } | null>(null);108 const size = Math.max(1, finite(fontSize, 60));109 const typography = {110 fontFamily,111 fontSize: size,112 fontWeight,113 letterSpacing: "-0.035em",114 lineHeight: 1.2,115 whiteSpace: "pre" as const,116 };117118 useLayoutEffect(() => {119 let cancelled = false;120 const handle = delayRender("Measure Inline Word Roll font");121 pending.current = handle;122 void document.fonts123 .load(124 `${fontWeight} ${size}px ${fontFamily}`,125 `${prefix} ${text}${suffix}`,126 )127 .then(() => {128 if (cancelled || !measurement.current) return;129 const children = Array.from(measurement.current.children);130 // Computed widths are in composition pixels. Bounding rectangles include131 // the Player's preview scale and would shrink our layout a second time.132 const measure = (node: Element) =>133 Number.parseFloat(getComputedStyle(node).width);134 setMetrics({135 prefix: measure(children[0]),136 words: children.slice(1).map(measure),137 });138 })139 .catch((error: unknown) => {140 if (!cancelled)141 cancelRender(142 error instanceof Error ? error : new Error(String(error)),143 );144 });145 return () => {146 cancelled = true;147 continueRender(handle);148 if (pending.current === handle) pending.current = null;149 };150 }, [151 prefix,152 text,153 suffix,154 size,155 fontFamily,156 fontWeight,157 delayRender,158 continueRender,159 cancelRender,160 ]);161162 useLayoutEffect(() => {163 if (metrics && pending.current !== null) {164 continueRender(pending.current);165 pending.current = null;166 }167 }, [metrics, continueRender]);168169 const state = getInlineWordRollState(170 frame,171 words.length,172 interval,173 acceleration,174 transitionFrames,175 );176 const moving = state.from !== state.to;177 const p = ease(state.progress);178 const gap = prefix ? size * 0.23 : 0;179 const prefixWidth = metrics?.prefix ?? 0;180 const fromWidth = metrics?.words[state.from] ?? 0;181 const toWidth = metrics?.words[state.to] ?? 0;182 const slotWidth = fromWidth + (toWidth - fromWidth) * p;183 const totalWidth = prefixWidth + gap + slotWidth;184 const widest = prefixWidth + gap + Math.max(0, ...(metrics?.words ?? []));185 const fit = Math.min(186 1,187 (width * 0.84) / Math.max(1, widest),188 (height * 0.5) / (size * 1.2),189 );190 const rowHeight = size * 1.2;191192 return (193 <div194 role="img"195 aria-label={[prefix, words[state.to] ? `${words[state.to]}${suffix}` : ""]196 .filter(Boolean)197 .join(" ")}198 style={{ position: "absolute", inset: 0, overflow: "hidden", color }}199 >200 <div201 ref={measurement}202 aria-hidden="true"203 style={{204 ...typography,205 position: "absolute",206 visibility: "hidden",207 pointerEvents: "none",208 }}209 >210 <span style={{ display: "inline-block" }}>{prefix}</span>211 {words.map((word, index) => (212 <span key={`${index}:${word}`} style={{ display: "inline-block" }}>213 {word}214 {suffix}215 </span>216 ))}217 </div>218 <div219 aria-hidden="true"220 style={{221 position: "absolute",222 left: "50%",223 top: "50%",224 scale: fit,225 visibility: metrics && words.length ? "visible" : "hidden",226 }}227 >228 <div229 style={{230 ...typography,231 position: "absolute",232 left: -totalWidth / 2,233 top: -rowHeight / 2,234 height: rowHeight,235 }}236 >237 <span style={{ position: "absolute", left: 0 }}>{prefix}</span>238 <div239 style={{240 position: "absolute",241 left: prefixWidth + gap,242 top: 0,243 width: Math.max(fromWidth, toWidth) + size * 0.12,244 height: rowHeight,245 overflow: "hidden",246 maskImage:247 "linear-gradient(to bottom, transparent, black 12%, black 88%, transparent)",248 }}249 >250 <span251 style={{252 position: "absolute",253 left: 0,254 top: 0,255 translate: `0 ${moving ? -p * rowHeight : 0}px`,256 opacity: moving ? 1 - clamp(p * 1.2) : 1,257 }}258 >259 {words[state.from]}260 {words.length ? suffix : ""}261 </span>262 {moving ? (263 <span264 style={{265 position: "absolute",266 left: 0,267 top: 0,268 translate: `0 ${(1 - p) * rowHeight}px`,269 opacity: clamp(p * 1.6),270 }}271 >272 {words[state.to]}273 {suffix}274 </span>275 ) : null}276 </div>277 </div>278 </div>279 </div>280 );281}









