Spec Sweep
A one-line spec slides in word by word while a highlight runs along it and an icon charges up
Source
components/kuchi/spec-sweep/index.tsx
1"use client";23import { loadFont } from "@remotion/google-fonts/Inter";4import { useEffect, useId, useMemo, useState } from "react";5import {6 AbsoluteFill,7 continueRender,8 delayRender,9 Easing,10 getRemotionEnvironment,11 interpolate,12 useCurrentFrame,13 useVideoConfig,14} from "remotion";15import {16 mixOklch,17 resolveFont,18 type KuchiTheme,19 useKuchiTheme,20} from "@/lib/kuchi-ui";21import { BOLT, ENTRY, ICON_BOX, SWEEP } from "./data";2223/**24 * Spec Sweep — one centred line that arrives word by word and then gets read25 * out by a highlight. Every word slides in on its own clock, a soft band of26 * brightness travels along the line, and an icon charges up from the bottom.27 *28 * The defaults are measured off a 1920x1080 reference: it is a single curve29 * through time (`SWEEP`), reached at each point of the line by its distance from30 * the start plus that word's entry delay, so copy of any length rides the same31 * band.32 */3334const { fontFamily: INTER } = loadFont("normal", {35 weights: ["500"],36 subsets: ["latin"],37});3839export type SpecSegmentRole = "lead" | "icon" | "accent" | "muted";4041export interface SpecSegment {42 /** The words. Split on spaces; each word enters on its own. Unused by `icon`. */43 text?: string;44 /**45 * `lead` rides the highlight and falls back to grey behind it. `accent` stays46 * lit once the highlight has reached it. `muted` never rises past `mutedLevel`.47 * `icon` draws the `icon` path, charged with `accentColor`.48 */49 role?: SpecSegmentRole;50}5152export interface SpecSweepProps {53 segments?: SpecSegment[];54 /** SVG path data of the icon, drawn in an `iconBox` viewBox. */55 icon?: string;56 /** viewBox width and height of `icon`. */57 iconBox?: [number, number];58 /** Icon height, in em. */59 iconSize?: number;60 /** Icon colour once charged. Defaults to `theme.primary`. */61 accentColor?: string;62 /** Opacity of the icon before the charge reaches it. */63 iconDim?: number;64 /** Lighter inner edge of the icon, px on a 1920 stage. 0 turns it off. */65 iconRim?: number;66 /** Colour of that edge. Defaults to `accentColor` towards white. */67 iconRimColor?: string;68 /** Frames from the icon's entry to the start of its charge, and the charge's length. */69 chargeDelay?: number;70 chargeFrames?: number;71 /** A family from `fonts.ts`, or a CSS family you have loaded yourself. */72 fontFamily?: string;73 /** Type size, px on a 1920 stage. Long copy shrinks from here to fit. */74 fontSize?: number;75 fontWeight?: number;76 /** How far a word slides in, em. */77 travel?: number;78 /** Frames between one word's entry and the next. Compressed on long copy. */79 stagger?: number;80 /** Frames the highlight takes to cross the line. */81 sweepFrames?: number;82 /** Level `muted` words are capped at. */83 mutedLevel?: number;84 theme?: Partial<KuchiTheme>;85 mode?: "light" | "dark";86 speed?: number;87}8889/** Widest the line may get, as a fraction of the stage: a word still sliding in stays on it. */90const MAX_LINE = 0.85;91/** The last word has landed by this frame, however long the copy. */92const LAST_ENTRY = 14;93/** Frame the highlight's centre leaves the start of the line. */94const SWEEP_START = 1.476;95/** Frames a word is ahead of the highlight at the very start of its slide. */96const SWEEP_LEAD = 6.093;97/** The text baseline sits this far below the stage centre, em. */98const BASELINE = 0.258;99/** Spacing of the sampled gradient stops, px on a 1920 stage. */100const STOP_EVERY = 8;101102const chargeEase = Easing.bezier(0.166, 0.092, 0.279, 1);103104const held = { extrapolateLeft: "clamp", extrapolateRight: "clamp" } as const;105const ENTRY_AT = ENTRY.map((_, i) => i);106const SWEEP_AT = SWEEP.map(([at]) => at);107const SWEEP_LEVEL = SWEEP.map(([, level]) => level);108109/** The fraction of `travel` a word has left, `age` frames after it entered. */110export const entryOffset = (age: number) =>111 interpolate(age, ENTRY_AT, [...ENTRY], held);112113/** Level of a word at `t` frames past the highlight's centre. */114export const sweepLevel = (115 role: SpecSegmentRole,116 t: number,117 mutedLevel = 0.6,118) => {119 if (role === "accent" && t > 0) return 1;120 const level = interpolate(t, SWEEP_AT, SWEEP_LEVEL, held);121 return role === "muted" ? Math.min(level, mutedLevel) : level;122};123124export interface LineItem {125 role: SpecSegmentRole;126 text: string;127 /** Left edge from the start of the line, and advance. px. */128 x: number;129 w: number;130}131132/** Splits segments into words and lays them on one line. */133export const layoutLine = (134 segments: SpecSegment[],135 measure: (text: string) => number,136 iconWidth: number,137) => {138 const space = measure(" ");139 const items: LineItem[] = [];140 let x = 0;141 const push = (role: SpecSegmentRole, text: string, w: number) => {142 items.push({ role, text, x, w });143 x += w + space;144 };145 for (const s of segments) {146 if (s.role === "icon") push("icon", "", iconWidth);147 else148 for (const word of (s.text ?? "").split(/\s+/).filter(Boolean))149 push(s.role ?? "lead", word, measure(word));150 }151 return { items, width: Math.max(0, x - space) };152};153154const makeMeasure = (font: string, size: number) => {155 const ctx =156 typeof document === "undefined"157 ? null158 : document.createElement("canvas").getContext("2d");159 if (!ctx) return (text: string) => text.length * 0.55 * size;160 ctx.font = font;161 return (text: string) => ctx.measureText(text).width;162};163164const DEFAULT_SEGMENTS: SpecSegment[] = [165 { text: "Ship", role: "lead" },166 { role: "icon" },167 { text: "a launch film", role: "accent" },168 { text: "in", role: "muted" },169 { text: "20 minutes", role: "accent" },170];171172export const SpecSweep = ({173 segments = DEFAULT_SEGMENTS,174 icon = BOLT,175 iconBox = ICON_BOX,176 iconSize = 1.452,177 accentColor,178 iconDim = 0.39,179 iconRim = 1.47,180 iconRimColor,181 chargeDelay = 11.47,182 chargeFrames = 30,183 fontFamily,184 fontSize = 85.15,185 fontWeight = 500,186 travel = 1.466,187 stagger = 2,188 sweepFrames = 54,189 mutedLevel = 0.6,190 theme,191 mode = "dark",192 speed = 1,193}: SpecSweepProps) => {194 const f = useCurrentFrame() * speed;195 const { width, height } = useVideoConfig();196 const t = useKuchiTheme(theme, mode);197 const id = useId().replace(/:/g, "");198 const family = resolveFont(fontFamily ?? t.fontFamily) ?? INTER;199 const stage = Math.min(width / 1920, height / 1080);200201 // A width measured before the face lands is a width for the fallback, so the202 // layout waits on it; a render holds its first frame until that has re-rendered.203 const [fontTick, setFontTick] = useState(0);204 const [handle] = useState(() =>205 getRemotionEnvironment().isRendering206 ? delayRender("spec-sweep: loading the face")207 : null,208 );209 const fontSpec = `${fontWeight} 100px ${family}`;210 useEffect(() => {211 let alive = true;212 document.fonts213 .load(fontSpec)214 .catch(() => [])215 .then(() => {216 if (alive) setFontTick((n) => n + 1);217 });218 return () => {219 alive = false;220 };221 }, [fontSpec]);222 useEffect(() => {223 if (fontTick > 0 && handle != null) continueRender(handle);224 }, [fontTick, handle]);225226 const line = useMemo(() => {227 void fontTick;228 const place = (size: number) =>229 layoutLine(230 segments,231 makeMeasure(`${fontWeight} ${size}px ${family}`, size),232 (size * iconSize * iconBox[0]) / iconBox[1],233 );234 const size = fontSize * stage;235 const first = place(size);236 const fit = Math.min(1, (MAX_LINE * width) / Math.max(1, first.width));237 const fitted = fit < 1 ? place(size * fit) : first;238 return { ...fitted, size: size * fit, left: (width - fitted.width) / 2 };239 }, [240 fontTick,241 segments,242 fontWeight,243 family,244 iconSize,245 iconBox,246 fontSize,247 stage,248 width,249 ]);250251 const { items, size, left } = line;252 const step = Math.min(stagger, LAST_ENTRY / Math.max(1, items.length - 1));253 const rate = line.width / sweepFrames; // px per frame254 const baseline = height / 2 + BASELINE * size;255 const accent = accentColor ?? t.primary;256 const rimColor = iconRimColor ?? mixOklch(accent, "#ffffff", 0.3);257 const ink = t.foreground;258259 const iconH = size * iconSize;260 const iconScale = iconH / iconBox[1];261262 return (263 <AbsoluteFill style={{ background: t.background }}>264 <svg265 width={width}266 height={height}267 style={{ position: "absolute", inset: 0, overflow: "hidden" }}268 >269 {items.map((item, i) => {270 const age = f - step * i;271 if (age < 0) return null;272 const off = entryOffset(age);273 const x = left + item.x + off * travel * size;274275 if (item.role === "icon") {276 const charge = chargeEase(277 Math.min(1, Math.max(0, (age - chargeDelay) / chargeFrames)),278 );279 const level = iconBox[1] * (1.006 - 1.018 * charge);280 const clip = `${id}c${i}`;281 const shape = (fill: string, rim: string) => (282 <>283 <path d={icon} fill={fill} />284 {iconRim > 0 && (285 <path286 d={icon}287 fill="none"288 stroke={rim}289 strokeWidth={(2 * iconRim * stage) / iconScale}290 clipPath={`url(#${clip})`}291 />292 )}293 </>294 );295 return (296 <g297 key={`${item.x}`}298 transform={`translate(${x} ${height / 2 - iconH / 2}) scale(${iconScale})`}299 >300 <clipPath id={clip}>301 <path d={icon} />302 </clipPath>303 <clipPath id={`${clip}a`}>304 <rect x={-9e3} y={-9e3} width={18e3} height={9e3 + level} />305 </clipPath>306 <clipPath id={`${clip}b`}>307 <rect x={-9e3} y={level} width={18e3} height={9e3} />308 </clipPath>309 <g clipPath={`url(#${clip}a)`} opacity={iconDim}>310 {shape(accent, rimColor)}311 </g>312 <g clipPath={`url(#${clip}b)`}>{shape(accent, rimColor)}</g>313 </g>314 );315 }316317 // The highlight reaches each point of the word at its own moment, so the318 // word is painted with a gradient sampled from that one curve.319 const grad = `${id}g${i}`;320 const from = age + SWEEP_LEAD * off - SWEEP_START - item.x / rate;321 const n = Math.max(2, Math.ceil(item.w / (STOP_EVERY * stage)));322 const stops = Array.from({ length: n + 1 }, (_, k) => {323 const u = k / n;324 return (325 <stop326 key={u}327 offset={u}328 stopColor={ink}329 stopOpacity={sweepLevel(330 item.role,331 from - (u * item.w) / rate,332 mutedLevel,333 )}334 />335 );336 });337 return (338 <g key={`${item.x}`}>339 <linearGradient340 id={grad}341 gradientUnits="userSpaceOnUse"342 x1={x}343 x2={x + item.w}344 y1={0}345 y2={0}346 >347 {stops}348 </linearGradient>349 <text350 x={x}351 y={baseline}352 fill={`url(#${grad})`}353 style={{354 fontFamily: family,355 fontWeight,356 fontSize: size,357 textRendering: "geometricPrecision",358 }}359 >360 {item.text}361 </text>362 </g>363 );364 })}365 </svg>366 </AbsoluteFill>367 );368};369370export default SpecSweep;
components/kuchi/spec-sweep/data.ts
1/**2 * Everything below is measured frame by frame off a 1920x1080, 30fps reference.3 * Times are frames, lengths are em unless a comment says otherwise.4 */56/** A word's slide in, as a fraction of `travel`, one entry per frame of its own clock. */7export const ENTRY = [8 1, 0.64, 0.484, 0.374, 0.29, 0.224, 0.172, 0.128, 0.094, 0.066, 0.044, 0.028,9 0.016, 0.008, 0.002, 0,10] as const;1112/**13 * Brightness against time, relative to the moment the highlight's centre reaches14 * a point of the line: [frames, level], where 1 is full ink. One curve explains15 * every word of the reference to 0.8% of full scale.16 */17export const SWEEP: readonly (readonly [number, number])[] = [18 [-50, 0.255],19 [-49, 0.271],20 [-45, 0.377],21 [-42, 0.437],22 [-39, 0.467],23 [-31, 0.525],24 [-25, 0.587],25 [-12, 0.806],26 [-5, 0.966],27 [-3, 0.99],28 [0, 1],29 [4, 0.995],30 [6, 0.974],31 [13, 0.81],32 [26, 0.588],33 [33, 0.517],34 [43, 0.462],35 [51, 0.365],36];3738/** Default mark: a rounded bolt in a `ICON_BOX` viewBox. */39export const BOLT =40 "M54.13 2.15A5.78 5.78 0 0 1 64.00 7.96L47.41 48.65A1.03 1.03 0 0 0 48.36 50.07L78.20 50.31A4.41 4.41 0 0 1 81.63 57.46L30.83 121.75A5.39 5.39 0 0 1 21.55 116.54L37.50 73.40L6.96 72.69A4.58 4.58 0 0 1 3.50 65.25Z";41export const ICON_BOX: [number, number] = [83.07, 123.79];









