Story Text
Story-style text types in word by word on rounded gradient highlight bubbles.
Source
components/kuchi/story-text.tsx
1"use client";23import { loadFont } from "@remotion/google-fonts/Figtree";4import type React from "react";5import { useEffect, useId, useMemo, useRef, useState } from "react";6import {7 AbsoluteFill,8 continueRender,9 delayRender,10 Easing,11 interpolate,12 interpolateColors,13 spring,14 useCurrentFrame,15 useVideoConfig,16} from "remotion";17import type { GradientParams } from "@/lib/kuchi/gsh/gradient-engine";18import { GshGround } from "@/lib/kuchi/gsh/gsh-ground";19import type { GshPresetId } from "@/lib/kuchi/gsh/presets";2021const figtree = loadFont("normal", {22 weights: ["400"],23 subsets: ["latin"],24});25const sans = figtree.fontFamily;2627export interface StoryTextProps {28 text?: string;29 measure?: number;30 accent?: string;31 /** Text and sticker color; overrides the theme ink. */32 ink?: string;33 /** Solid fill in place of the gradient ground; "transparent" drops it. */34 background?: string;35 /** Typeface for the text. Load it yourself; Figtree by default. */36 fontFamily?: string;37 /** Frames between words as they type in. */38 stagger?: number;39 /** Frames the typed text holds before the sticker styles cycle. */40 hold?: number;41 /** Size of the sticker, around the frame's center. */42 scale?: number;43 /** Frames to hold the first frame before anything moves. */44 delay?: number;45 theme?: "dark" | "light";46 ground?: GshPresetId;47 groundParams?: Partial<GradientParams>;48 speed?: number;49}5051const FONT_PX = 100;52const TRACK = -0.012;5354const ENTER = Easing.bezier(0.22, 1, 0.36, 1);55const MOVE = Easing.bezier(0.65, 0, 0.35, 1);56const EXIT = Easing.bezier(0.55, 0, 1, 0.45);57const CARD = { mass: 0.8, damping: 18, stiffness: 160 };58const CLAMP = {59 extrapolateLeft: "clamp",60 extrapolateRight: "clamp",61} as const;6263const LIGHT_GROUND: Partial<GradientParams> = {64 kind: "mist",65 background: "#F2EDE6",66 colors: ["#F58C3D", "#F7C79B", "#E889B5", "#FFF6EC"],67};6869const THEMES = {70 dark: {71 ground: "static-sunset" as GshPresetId,72 base: "#0A0510",73 fg: "#FBF7F1",74 sticker: "#FBF7F1",75 onFill: "#17120E",76 scrim: "10,5,16",77 scrimA: 0.34,78 lift: "rgba(20,6,12,0.38)",79 shadow: "0 2px 22px rgba(10,5,16,0.45)",80 },81 light: {82 ground: undefined,83 base: "#F2EDE6",84 fg: "#17140F",85 sticker: "#17140F",86 onFill: "#FBF7F1",87 scrim: "242,237,230",88 scrimA: 0.3,89 lift: "rgba(80,40,20,0.22)",90 shadow: "0 1px 16px rgba(242,237,230,0.6)",91 },92} as const;9394const FIRST_WORD = -2;95const WORD_GAP = 5;96const WORD_IN = 8;9798function measureWith(_version: number, family: string) {99 const ctx = document.createElement("canvas").getContext("2d");100 const cache: Record<string, number> = {};101 return (s: string) => {102 if (cache[s] === undefined) {103 if (!ctx) return s.length * 0.52;104 ctx.font = `400 ${FONT_PX}px "${family}"`;105 cache[s] = ctx.measureText(s).width / FONT_PX + TRACK * [...s].length;106 }107 return cache[s];108 };109}110111function useMeasure(family: string) {112 const [version, setVersion] = useState(0);113 const [handle] = useState(() => delayRender("story-text: measuring"));114 const released = useRef(false);115 useEffect(() => {116 let live = true;117 const bump = () => {118 if (live) setVersion((v) => v + 1);119 };120 document.fonts.addEventListener("loadingdone", bump);121 Promise.all([122 figtree.waitUntilDone(),123 document.fonts.load(`400 ${FONT_PX}px "${family}"`),124 ])125 .catch(() => undefined)126 .then(() => {127 bump();128 if (!released.current) {129 released.current = true;130 continueRender(handle);131 }132 });133 return () => {134 live = false;135 document.fonts.removeEventListener("loadingdone", bump);136 };137 }, [handle, family]);138 return useMemo(() => measureWith(version, family), [version, family]);139}140141function wrap(widths: number[], space: number, max: number) {142 const lineOf: number[] = [];143 let line = 0;144 let run = 0;145 widths.forEach((w, i) => {146 const next = run === 0 ? w : run + space + w;147 if (run > 0 && next > max) {148 line += 1;149 run = w;150 } else {151 run = next;152 }153 lineOf[i] = line;154 });155 return lineOf;156}157158type Pt = [number, number];159160function roundedPath(raw: Pt[], R: number) {161 const pts: Pt[] = [];162 for (const p of raw) {163 const q = pts[pts.length - 1];164 if (!q || Math.hypot(p[0] - q[0], p[1] - q[1]) > 0.25) pts.push(p);165 }166 if (pts.length > 1) {167 const a = pts[0];168 const b = pts[pts.length - 1];169 if (Math.hypot(a[0] - b[0], a[1] - b[1]) <= 0.25) pts.pop();170 }171 const clean = pts.filter((v, i) => {172 const p = pts[(i - 1 + pts.length) % pts.length];173 const n = pts[(i + 1) % pts.length];174 const cross = (v[0] - p[0]) * (n[1] - v[1]) - (v[1] - p[1]) * (n[0] - v[0]);175 return Math.abs(cross) > 0.01;176 });177 const N = clean.length;178 if (N < 3) return "";179 let d = "";180 clean.forEach((v, i) => {181 const p = clean[(i - 1 + N) % N];182 const n = clean[(i + 1) % N];183 const lin = Math.hypot(v[0] - p[0], v[1] - p[1]);184 const lout = Math.hypot(n[0] - v[0], n[1] - v[1]);185 const r = Math.min(R, lin / 2, lout / 2);186 const a: Pt = [187 v[0] + ((p[0] - v[0]) / lin) * r,188 v[1] + ((p[1] - v[1]) / lin) * r,189 ];190 const b: Pt = [191 v[0] + ((n[0] - v[0]) / lout) * r,192 v[1] + ((n[1] - v[1]) / lout) * r,193 ];194 const cross = (v[0] - p[0]) * (n[1] - v[1]) - (v[1] - p[1]) * (n[0] - v[0]);195 const sweep = cross > 0 ? 1 : 0;196 d += `${i === 0 ? "M" : "L"}${a[0].toFixed(2)} ${a[1].toFixed(2)}`;197 d += `A${r.toFixed(2)} ${r.toFixed(2)} 0 0 ${sweep} ${b[0].toFixed(2)} ${b[1].toFixed(2)}`;198 });199 return `${d}Z`;200}201202/** The foreground at `scale`, around the frame's center; nothing extra at 1. */203function ScaleLayer({204 scale,205 children,206}: {207 scale: number;208 children: React.ReactNode;209}) {210 if (scale === 1) return children;211 return (212 <AbsoluteFill style={{ transform: `scale(${scale})` }}>213 {children}214 </AbsoluteFill>215 );216}217218export function StoryText({219 text = "okay, it’s live — the update you kept asking for is finally here",220 measure,221 accent = "#3B5BFD",222 ink: inkColor,223 background,224 fontFamily = sans,225 stagger = WORD_GAP,226 hold = 14,227 scale = 1,228 delay = 0,229 theme = "dark",230 ground,231 groundParams,232 speed = 1,233}: StoryTextProps) {234 const frame = Math.max(0, useCurrentFrame() - delay) * speed;235 const { width: W, height: H, fps } = useVideoConfig();236 const t = THEMES[theme];237 const fg = inkColor ?? t.fg;238 const uid = useId().replace(/[^a-zA-Z0-9_-]/g, "");239 const width = useMeasure(fontFamily);240 const tall = H > W;241242 const words = text.split(/\s+/).filter(Boolean);243 const F = tall ? W * 0.115 : H * 0.125;244 const space = width(" ");245 const widths = words.map((w) => width(w));246 const lineOf = wrap(247 widths,248 space,249 (W * (measure ?? (tall ? 0.8 : 0.76))) / F,250 );251 const lineCount = (lineOf[lineOf.length - 1] ?? 0) + 1;252253 const lh = F * 1.34;254 const padX = F * 0.36;255 const R = lh * 0.3;256257 const appear = words.map((_, i) =>258 Math.max(259 0,260 spring({261 frame: frame - (FIRST_WORD + i * stagger),262 fps,263 config: CARD,264 }),265 ),266 );267 const ink = words.map((_, i) =>268 interpolate(269 frame,270 [FIRST_WORD + i * stagger + 2, FIRST_WORD + i * stagger + WORD_IN + 1],271 [0, 1],272 { ...CLAMP, easing: ENTER },273 ),274 );275 const typedEnd = FIRST_WORD + (words.length - 1) * stagger + WORD_IN;276277 const C1 = typedEnd + hold;278 const C2 = C1 + 22;279 const C3 = C2 + 22;280 const step = (a: number) =>281 interpolate(frame, [a, a + 9], [0, 1], { ...CLAMP, easing: MOVE });282 const toOutline = step(C1);283 const toNone = step(C2);284 const toFill = step(C3);285 const fillAmt = 1 - toOutline + toFill;286 const strokeAmt = toOutline * (1 - toNone);287 const textColor = interpolateColors(fillAmt, [0, 1], [fg, t.onFill]);288 const pop = spring({ frame: frame - C3, fps, config: CARD });289 const settle =290 frame >= C3 ? 1 + 0.035 * Math.sin(Math.min(1, pop) * Math.PI) : 1;291292 const lines = Array.from({ length: lineCount }, (_, l) => {293 const idx = words.map((_, i) => i).filter((i) => lineOf[i] === l);294 let w = 0;295 const xs: number[] = [];296 idx.forEach((i, k) => {297 const a = appear[i];298 if (k > 0) w += space * F * Math.min(1, a * 3);299 xs.push(w);300 w += widths[i] * F * a;301 });302 const grow = appear[idx[0]] ?? 0;303 return { idx, xs, w, grow };304 });305 const lineH = (g: number) => lh * MOVE(Math.min(1, g * 1.6));306 const totalH = lines.reduce((acc, l) => acc + lineH(l.grow), 0);307 let y = H / 2 - totalH / 2;308 const geo = lines.map((l) => {309 const h = lineH(l.grow);310 const top = y;311 y += h;312 const half = l.w / 2 + padX * Math.min(1, l.grow * 2);313 return { ...l, top, h, x0: W / 2 - half, x1: W / 2 + half };314 });315 const shown = geo.filter((g) => g.h > 0.5 && g.x1 - g.x0 > 1);316317 let path = "";318 if (shown.length) {319 const pts: Pt[] = [];320 const first = shown[0];321 pts.push([first.x0, first.top], [first.x1, first.top]);322 shown.forEach((g, i) => {323 pts.push([g.x1, g.top + g.h]);324 const next = shown[i + 1];325 if (next) pts.push([next.x1, g.top + g.h]);326 });327 const last = shown[shown.length - 1];328 pts.push([last.x0, last.top + last.h]);329 for (let i = shown.length - 1; i > 0; i--) {330 pts.push([shown[i].x0, shown[i].top], [shown[i - 1].x0, shown[i].top]);331 }332 path = roundedPath(pts, R);333 }334335 const caretOpacity = interpolate(336 frame,337 [typedEnd - 2, typedEnd + 6],338 [1, 0],339 { ...CLAMP, easing: EXIT },340 );341 let caret: { x: number; top: number } | null = null;342 for (let i = words.length - 1; i >= 0; i--) {343 if (appear[i] > 0 || i === 0) {344 const g = geo[lineOf[i]];345 const k = g.idx.indexOf(i);346 caret = {347 x: W / 2 - g.w / 2 + g.xs[k] + widths[i] * F * appear[i] + F * 0.06,348 top: g.top + (lh - F * 1.08) / 2,349 };350 break;351 }352 }353354 const push = interpolate(frame, [0, 200], [1, 1.04], CLAMP);355356 return (357 <AbsoluteFill358 style={{359 background: background === undefined ? t.base : undefined,360 overflow: "hidden",361 }}362 >363 {background === undefined ? (364 <>365 <AbsoluteFill style={{ transform: `scale(${push})` }}>366 <GshGround367 preset={groundParams ? undefined : (ground ?? t.ground)}368 params={369 groundParams ??370 (theme === "light" && !ground ? LIGHT_GROUND : undefined)371 }372 timeOffset={theme === "dark" ? 3 : 5}373 timeScale={0.4}374 />375 </AbsoluteFill>376 <AbsoluteFill377 style={{378 background: `radial-gradient(${tall ? "90% 40%" : "60% 55%"} at 50% 50%, rgba(${t.scrim},${t.scrimA}) 0%, rgba(${t.scrim},0) 100%)`,379 }}380 />381 </>382 ) : (383 <AbsoluteFill384 style={{385 background: background === "transparent" ? undefined : background,386 }}387 />388 )}389 <ScaleLayer scale={scale}>390 <AbsoluteFill391 style={{ transform: `scale(${settle})`, transformOrigin: "50% 50%" }}392 >393 <svg394 width={W}395 height={H}396 style={{ position: "absolute", inset: 0, overflow: "visible" }}397 aria-hidden398 >399 {path ? (400 <>401 <defs>402 <filter403 id={`${uid}-lift`}404 x="-20%"405 y="-40%"406 width="140%"407 height="180%"408 >409 <feDropShadow410 dx="0"411 dy={F * 0.12}412 stdDeviation={F * 0.22}413 floodColor={t.lift}414 />415 </filter>416 </defs>417 <path418 d={path}419 fill={inkColor ?? t.sticker}420 opacity={Math.min(1, fillAmt)}421 filter={`url(#${uid}-lift)`}422 />423 <path424 d={path}425 fill="none"426 stroke={fg}427 strokeWidth={Math.max(2, F * 0.045)}428 opacity={strokeAmt}429 />430 </>431 ) : null}432 </svg>433 <div434 style={{435 position: "absolute",436 inset: 0,437 fontFamily,438 fontWeight: 400,439 clipPath: path ? `path("${path}")` : undefined,440 }}441 >442 {geo.map((g) =>443 g.idx.map((i, k) => {444 const a = ink[i];445 if (a <= 0) return null;446 return (447 <span448 key={`w-${i}`}449 style={{450 position: "absolute",451 left: W / 2 - g.w / 2 + g.xs[k],452 top: g.top + (lh - F) / 2,453 fontSize: F,454 lineHeight: 1,455 letterSpacing: `${TRACK}em`,456 whiteSpace: "pre",457 color: textColor,458 textShadow: fillAmt < 0.5 ? t.shadow : undefined,459 opacity: a,460 transformOrigin: "0% 80%",461 transform: `translateY(${(1 - a) * F * 0.22}px) scale(${0.9 + 0.1 * a})`,462 }}463 >464 {words[i]}465 </span>466 );467 }),468 )}469 {caret ? (470 <div471 style={{472 position: "absolute",473 left: caret.x,474 top: caret.top,475 width: Math.max(2, F * 0.045),476 height: F * 1.08,477 borderRadius: F,478 background: accent,479 opacity: caretOpacity,480 }}481 />482 ) : null}483 </div>484 </AbsoluteFill>485 </ScaleLayer>486 </AbsoluteFill>487 );488}









