Type Morph
Typewriter effect: a headline types with a blinking caret, then morphs letter by letter. A headline that types itself under a glowing caret, sheds its lead, morphs letter by letter, and ends under a colour flood.
Source
components/kuchi/type-morph.tsx
1"use client";23import { loadFont as loadInter } from "@remotion/google-fonts/Inter";4import { type CSSProperties, useLayoutEffect, useRef, useState } from "react";5import {6 AbsoluteFill,7 continueRender,8 delayRender,9 Easing,10 getRemotionEnvironment,11 interpolate,12 useCurrentFrame,13 useVideoConfig,14} from "remotion";15import { TextReveal } from "@/components/kuchi/text-reveal";16import {17 mixOklch,18 resolveFont,19 type KuchiTheme,20 useKuchiTheme,21} from "@/lib/kuchi-ui";22import {23 CUT_AT,24 CUT2_AT,25 EXIT_COEFF,26 EXIT_FROM,27 EXIT_RATIO,28 FLOOD_STAGE_FRAMES,29 MORPH_FROM,30 MORPH_TO,31 SLIDE_BEZIER,32 SLIDE_FROM,33 SLIDE_TO,34} from "./type-morph-timeline";3536const { fontFamily: SANS } = loadInter("normal", {37 weights: ["400", "700"],38 subsets: ["latin"],39});4041export interface TypeMorphProps {42 /**43 * The line as it is typed. Everything up to and including `lead` is cut away44 * once typing finishes, which is what leaves the emphasis alone on screen.45 */46 lead?: string;47 /** The emphasised tail of the typed line — this is what survives the cut. */48 emphasis?: string;49 /** What the emphasis morphs into, letter by letter. */50 morphTo?: string;51 /**52 * What is left after the second cut. Empty ends the beat on the bare flood.53 */54 finally_?: string;55 /**56 * Whether the final phrase survives into the flood.57 *58 * The reference carries it across; off is the cleaner ending, and it is the59 * default because a word sitting on a full-bleed colour for four frames reads60 * as a leftover rather than as a beat.61 */62 wordOnFlood?: boolean;63 /** Accepted, not drawn: the caret and fresh glyphs take the ink colour. */64 accent?: string;65 /**66 * Two flat colours to flood the frame with at the end, or `false` to end on67 * paper — the default.68 *69 * The reference floods; off is the quieter ending and the one that composes,70 * because a beat that hands the next scene a full-bleed colour has decided71 * what that scene opens on.72 *73 * Two flat colours rather than a ramp: the reference arrives at 99% frame74 * coverage inside a single frame and then steps once. A crossfade between them75 * would put a half-transparent wash over the type for several frames, and76 * there is no reading of that except the screen dimming.77 */78 flood?: [string, string] | false;79 /**80 * The page.81 *82 * Defaults to the theme's background so the component belongs in whatever83 * project installs it. The reference's paper is a plain near-white (#f7f7f7 to84 * #fafafa across the beat), not the warm off-white the token carries, so the85 * preview passes its own.86 */87 background?: string;88 /** The type. Defaults to the theme's foreground. */89 ink?: string;90 /**91 * The opening line is rendered by `text-reveal` itself.92 *93 * Not a reimplementation of it, and not its helper functions rebuilt into a94 * second animator — the component, mounted. Everything in `reveal` is passed95 * to it untouched, so its lead-word push, its recede and its assemble are96 * exactly what that component does anywhere else, and there is nothing here97 * that can drift away from it.98 */99 reveal?: Omit<100 React.ComponentProps<typeof TextReveal>,101 "text" | "theme" | "mode" | "color" | "fontSize"102 >;103 /**104 * Cap-to-descender height as a fraction of the frame height.105 *106 * 0.1256, not the 0.139 the reference's raw ink height suggests: measured back107 * from the rendered line width against the reference's at the same frame, mine108 * came out 12.7% wide at 0.139 and 4% narrow at 0.1233, because ink height109 * includes the descender and the face's110 * own metrics differ from the reference's.111 */112 size?: number;113 theme?: Partial<KuchiTheme>;114 mode?: "light" | "dark";115 /**116 * The face this scene paints its words in — a label from `fonts.ts`117 * ("Inter", "Space Grotesk", "Instrument Serif") or a CSS family you have118 * loaded yourself. Unset, the scene keeps the face it was designed around.119 *120 * Overrides `theme.fontFamily`, which is how a brand kit re-skins a whole121 * timeline from one value.122 */123 fontFamily?: string;124}125126/**127 * `will-change` is right for the Player and wrong for the render — a render128 * draws each frame in a different tab, and a promoted layer hands that tab a129 * stale raster from whatever scale it last drew.130 */131const promoted = getRemotionEnvironment().isRendering132 ? null133 : ({ willChange: "transform" } as const);134135/**136 * Hinting bends each glyph so its stems land on whole pixels, so as anything137 * moves the letterforms re-snap and boil. This also forces sub-pixel glyph138 * positioning, which Blink otherwise only enables above a device scale factor of139 * 1 — and a render is exactly 1, so without it every glyph in the morph would140 * land on a whole pixel and the travel would stutter.141 */142const CRISP: CSSProperties = {143 textRendering: "geometricPrecision",144 WebkitFontSmoothing: "antialiased",145};146147/** Moderate decelerate. Quint/expo spend frames below half a pixel, which rasterise identically. */148const EASE = Easing.bezier(0.2, 0.6, 0.35, 1);149150/**151 * Pair each glyph of `to` with a glyph of `from` that can travel to it.152 *153 * Greedy nearest-unused match on the character itself. It is not the optimal154 * assignment and does not need to be — what the eye reads is *continuity*, that155 * some letters persisted rather than the whole line being replaced, and a156 * nearest match delivers that while an optimal one costs a matrix and looks the157 * same. Unmatched targets fade up in place; unmatched sources fade out in place.158 */159function pairGlyphs(from: string, to: string): (number | null)[] {160 const used = new Set<number>();161 return [...to].map((ch, ti) => {162 let best: number | null = null;163 let bestDist = Infinity;164 for (let fi = 0; fi < from.length; fi += 1) {165 if (used.has(fi) || from[fi] !== ch) continue;166 const dist = Math.abs(fi - ti);167 if (dist < bestDist) {168 bestDist = dist;169 best = fi;170 }171 }172 if (best !== null) used.add(best);173 return best;174 });175}176177/** Per-glyph x offsets of a string, measured in the real face at the real size. */178function useGlyphOffsets(strings: string[], fontSize: number, face: string) {179 const ref = useRef<HTMLDivElement>(null);180 const [offsets, setOffsets] = useState<number[][] | null>(null);181 // Every frame of a render is a fresh mount, so a plain effect + state lets the182 // frame be captured *before* the measurement has re-rendered — the glyphs are183 // then placed with no offsets at all and the frame comes out blank or short.184 // `delayRender` holds the capture until the second render has happened.185 const [handle] = useState(() => delayRender("type-morph: measuring glyphs"));186187 useLayoutEffect(() => {188 const root = ref.current;189 if (!root) return;190 // `offsetLeft` is layout px and unaffected by transforms — which is exactly191 // why it is the right tool for measuring a line that is about to be192 // transformed, which is exactly why it is the right tool for measuring a193 // line that is about to be transformed.194 setOffsets(195 [...root.children].map((line) =>196 [...(line as HTMLElement).children].map(197 (g) => (g as HTMLElement).offsetLeft,198 ),199 ),200 );201 }, []);202203 // Only once the measured offsets are actually in the tree.204 useLayoutEffect(() => {205 if (offsets) continueRender(handle);206 }, [offsets, handle]);207208 const probe = (209 <div210 ref={ref}211 aria-hidden212 style={{213 position: "absolute",214 visibility: "hidden",215 pointerEvents: "none",216 whiteSpace: "pre",217 fontFamily: face,218 fontSize,219 letterSpacing: "-0.035em",220 ...CRISP,221 }}222 >223 {strings.map((s) => (224 <div key={s} style={{ whiteSpace: "pre" }}>225 {[...s].map((ch, i) => (226 // biome-ignore lint/suspicious/noArrayIndexKey: glyph position is the identity here227 <span key={i} style={{ display: "inline-block" }}>228 {ch === " " ? " " : ch}229 </span>230 ))}231 </div>232 ))}233 </div>234 );235236 return { probe, offsets };237}238239/**240 * A headline that types itself, sheds its lead, morphs letter by letter, and241 * ends under a colour flood.242 *243 * Four mechanics on one timeline, each measured off a reference frame by frame244 * (see `timeline.ts` for the signals and the numbers they produced):245 *246 * 1. **Typing.** The line is centre-anchored, so it grows in both directions247 * rather than running to the right. Freshly landed glyphs arrive in the248 * accent colour and cool to ink over four frames, which is what gives the249 * typing a moving warm edge instead of a hard cursor.250 * 2. **The cut.** The lead is removed in a single frame, not animated out. What251 * *is* animated is the slide back to centre that follows it.252 * 3. **The morph.** Glyphs shared between the two phrases travel from where they253 * were to where they belong; the rest cross-fade in place.254 * 4. **The flood.** Two flat colours, four frames each.255 *256 * Every glyph position is measured in the real face at the real size behind a257 * hidden probe, because a morph built on estimated advance widths lands each258 * letter a pixel or two off and reads as a wobble.259 */260export function TypeMorph({261 lead = "Not just ",262 emphasis = "communicator.",263 morphTo = "something more.",264 finally_ = "more.",265 wordOnFlood = false,266 background,267 ink,268 reveal,269 flood = false,270 size = 0.1256,271 theme,272 mode,273 fontFamily,274}: TypeMorphProps) {275 const frame = useCurrentFrame();276 const { height, width } = useVideoConfig();277 const t = useKuchiTheme(theme, mode);278 const face = resolveFont(fontFamily ?? t.fontFamily) ?? SANS;279 const paper = background ?? t.background;280 const type = ink ?? t.foreground;281 const fontSize = height * size;282283 const typed = lead + emphasis;284 const { probe, offsets } = useGlyphOffsets(285 [typed, emphasis, morphTo, finally_],286 fontSize,287 face,288 );289290 // ── the timeline ──────────────────────────────────────────────────────────291 //292 // Absolute frame numbers, measured, not derived from each other. Deriving them293 // meant one wrong constant early shifted everything after it.294295 const floodAt = CUT2_AT + 1;296 const floodBAt = floodAt + FLOOD_STAGE_FRAMES;297298 const phase =299 flood && frame >= floodAt300 ? "flood"301 : frame >= CUT2_AT302 ? "final"303 : frame >= MORPH_FROM304 ? "morph"305 : frame >= CUT_AT306 ? "slide"307 : "type";308309 const floodColor =310 flood && frame >= floodAt311 ? frame >= floodBAt312 ? flood[1]313 : flood[0]314 : null;315316 const centre = width / 2;317318 /**319 * The line's horizontal offset — ONE continuous function of frame.320 *321 * The reference does not cut and then move; it moves continuously and the cut322 * only changes what is drawn. A single 16-frame cubic-bezier fits all 17323 * frames of the re-centring, straight through the cut, to 0.067px. Modelling324 * it as "drift, cut, slide" fits the same curve twice and puts a seam where325 * the reference has none.326 *327 * The travel is not a fixed distance — it is however far off-centre the328 * emphasis happens to sit inside the typed line, which the measured probe329 * already knows. On the reference that works out to 184.4px right of centre on330 * a 1400px frame; on any other phrase it is whatever that phrase needs.331 */332 const slideProgress = interpolate(frame, [SLIDE_FROM, SLIDE_TO], [0, 1], {333 easing: Easing.bezier(...SLIDE_BEZIER),334 extrapolateLeft: "clamp",335 extrapolateRight: "clamp",336 });337338 /** The exit: geometric per-frame velocity. Persists past the cut it precedes. */339 //340 // It stops at the cut. The reference carries the drifted position into what341 // the cut leaves behind, but the final phrase here is centred by choice, and a342 // drift still applied to it would drag a centred phrase off to the left — 300px343 // by the last frame.344 const exitDrift =345 frame <= EXIT_FROM || frame >= CUT2_AT346 ? 0347 : (-EXIT_COEFF * (EXIT_RATIO ** (frame - EXIT_FROM) - 1) * width) / 1400;348349 /** One glyph, absolutely placed, so nothing reflows as the line changes. */350 const glyph = (351 key: string,352 ch: string,353 x: number,354 lineWidth: number,355 style: CSSProperties,356 ) => (357 <span358 key={key}359 style={{360 position: "absolute",361 left: centre - lineWidth / 2 + x,362 top: 0,363 whiteSpace: "pre",364 ...style,365 }}366 >367 {ch === " " ? " " : ch}368 </span>369 );370371 let content: React.ReactNode = null;372373 if (offsets) {374 const [typedX, emphX, morphX, finalX] = offsets;375 const widthOf = (xs: number[], str: string) =>376 (xs[str.length - 1] ?? 0) + fontSize * 0.34;377378 const wTyped = widthOf(typedX, typed);379 const wEmph = widthOf(emphX, emphasis);380 const wMorph = widthOf(morphX, morphTo);381382 // Where the emphasis sits inside the typed line. The slide carries the whole383 // line, so both the typed phase and the post-cut phase read the same offset.384 const emphInTyped = typedX[lead.length] - wTyped / 2 + wEmph / 2;385386 if (phase === "type") {387 // `text-reveal` owns these frames entirely — see the render below.388 content = null;389 } else if (phase === "slide") {390 // From the cut to the end of the slide, this component draws the line —391 // `text-reveal` has already delivered it, centred, and the emphasis now392 // slides on the measured bezier.393 const w = widthOf(emphX, emphasis);394 const dx = -emphInTyped * (1 - slideProgress);395 content = [...emphasis].map((ch, i) =>396 glyph(`e${i}`, ch, emphX[i] + dx, w, {397 color: type,398 fontWeight: 700,399 }),400 );401 } else if (phase === "morph") {402 const p = interpolate(frame, [MORPH_FROM, MORPH_TO], [0, 1], {403 easing: EASE,404 extrapolateLeft: "clamp",405 extrapolateRight: "clamp",406 });407 const w = interpolate(p, [0, 1], [wEmph, wMorph]);408 const pairs = pairGlyphs(emphasis, morphTo);409 const matched = new Set(pairs.filter((x): x is number => x !== null));410 content = [411 ...[...emphasis].map((ch, i) =>412 matched.has(i)413 ? null414 : glyph(`x${i}`, ch, emphX[i] + (wEmph - w) / 2, w, {415 color: type,416 fontWeight: 700,417 opacity: interpolate(p, [0, 0.45], [1, 0], {418 extrapolateRight: "clamp",419 }),420 }),421 ),422 ...[...morphTo].map((ch, i) => {423 const src = pairs[i];424 const to = morphX[i] + (wMorph - w) / 2;425 if (src === null) {426 return glyph(`n${i}`, ch, to, w, {427 color: type,428 fontWeight: 700,429 opacity: interpolate(p, [0.55, 1], [0, 1], {430 extrapolateLeft: "clamp",431 extrapolateRight: "clamp",432 }),433 });434 }435 const fromX = emphX[src] + (wEmph - w) / 2;436 return glyph(`m${i}`, ch, interpolate(p, [0, 1], [fromX, to]), w, {437 color: type,438 fontWeight: 700,439 });440 }),441 ].filter(Boolean);442 } else {443 // The final phrase, CENTRED — it does not inherit the drifted position.444 const w = widthOf(finalX, finally_);445 const hidden = phase === "flood" && !wordOnFlood;446 content = hidden447 ? []448 : [...finally_].map((ch, i) =>449 glyph(`f${i}`, ch, finalX[i], w, {450 fontWeight: 700,451 color: floodColor452 ? mixOklch(floodColor, t.background, 0.92)453 : type,454 opacity: 1,455 }),456 );457 }458 }459460 return (461 <AbsoluteFill462 style={{463 background: floodColor ?? paper,464 fontFamily: face,465 ...CRISP,466 }}467 >468 {probe}469 {frame < CUT_AT ? (470 <TextReveal471 text={typed}472 fontSize={fontSize}473 color={type}474 theme={theme}475 mode={mode}476 {...reveal}477 />478 ) : null}479 <div480 style={{481 position: "absolute",482 top: "50%",483 left: 0,484 right: 0,485 height: 0,486 fontSize,487 lineHeight: 1,488 letterSpacing: "-0.035em",489 transform: `translate(${exitDrift.toFixed(2)}px, ${-fontSize * 0.36}px)`,490 ...promoted,491 }}492 >493 {content}494 </div>495 </AbsoluteFill>496 );497}498499export default TypeMorph;
components/kuchi/type-morph-timeline.ts
1/**2 * Every number here was measured off the reference recording, frame by frame.3 *4 * Source: a 30fps screen recording, 89 frames, 1400x762. Frames were cut at5 * 30fps and each reduced to signals — the bounding box of ink (a green-channel6 * threshold isolates glyph cores and rejects the violet bloom, which a mean-RGB7 * threshold does not), the centroid and count of chromatic pixels, and mean8 * luminance. Curves were then fitted against exponential, polynomial and9 * cubic-bezier families and the residuals compared, rather than a shape being10 * assumed.11 *12 * Frame numbers below are 0-based composition frames. The source's `g001.png` is13 * frame 0.14 */1516export const FPS = 30;1718// ── The opening ──────────────────────────────────────────────────────────────1920/**21 * Frames 0 to `CUT_AT` belong to `text-reveal`, which this component mounts22 * rather than reimplements — so its schedule lives there, not here.23 *24 * What the reference does in those frames is a *typewriter*: a constant25 * 1.5467 frames per character with the final full stop held back five frames,26 * each glyph landing at 1.178x and settling over five, arriving near-black with27 * a violet cast (#292541) rather than at the caret's own light violet. That is28 * documented because it was measured and is worth keeping, not because anything29 * below consumes it — `text-reveal` assembles word by word instead, which is a30 * different animation and a deliberate choice.31 */3233// ── The slide ────────────────────────────────────────────────────────────────3435/**36 * The re-centring move is ONE continuous curve, and it starts before the cut.37 *38 * This is the correction that mattered most. The obvious reading is "the lead is39 * cut, then what is left slides back to centre", which makes the motion start at40 * the cut. It does not. The line is already moving five frames earlier, and one41 * 16-frame cubic-bezier fits all 17 frames of it — through the cut — to a mean42 * error of 0.067px, max 0.23px.43 *44 * Alternatives on the same data: exponential decay 8.76px, a Remotion spring45 * with five free parameters 2.07px, degree-6 polynomial 1.60px, cubic 6.94px.46 * The bezier is better by two orders of magnitude, so this is not a close call.47 *48 * The consequence for the implementation: **the cut is a visibility change, not49 * a position change.** Residuals across it are +0.080 (before) and -0.10850 * (after) — nothing jumps. Earlier versions modelled a "pre-cut drift" and a51 * separate slide, which is the same curve described as two and fitted twice.52 */53export const SLIDE_FROM = 39;54export const SLIDE_TO = 55;55export const SLIDE_BEZIER = [0.3438, 0.0294, 0.032, 0.9269] as const;5657/** The lead stops being drawn here. Position is unaffected — see `SLIDE_BEZIER`. */58export const CUT_AT = 44;5960// ── The morph ────────────────────────────────────────────────────────────────6162export const MORPH_FROM = 56;63export const MORPH_TO = 67;6465// ── The exit ─────────────────────────────────────────────────────────────────6667/**68 * The exit drift: geometric per-frame velocity, i.e. an exponential ease-in.69 *70 * Starts at frame 72 — the frames before it are static to within 0.005px, and71 * frame 73 is the first displaced one at 0.73px. Sub-pixel displacements are72 * 0.73, 1.99, 3.70, 6.05, 9.76, 16.28, 30.03, 54.2; the integer bounding box73 * reads those as 1,2,3,7,9,16,29,54 because motion blur erodes a thresholded74 * edge, which is why an earlier hand-fit had both the start frame and the first75 * step wrong.76 *77 * Fit: 0.36px mean error. Quadratic is 8.60px, cubic 3.42px, easeInQuart 1.72px.78 */79export const EXIT_FROM = 72;80export const EXIT_RATIO = 1.76456;81export const EXIT_COEFF = 1.3194;8283/** The cut to the final phrase. */84export const CUT2_AT = 81;8586// ── The ending ───────────────────────────────────────────────────────────────8788/** Frames the final phrase is held when there is no flood. */89export const FINAL_HOLD = 12;90/** Each flood stage. Both are single-frame cuts to a flat colour, not ramps. */91export const FLOOD_STAGE_FRAMES = 4;9293/**94 * The reference's own palette. Component defaults come from the design system;95 * these are here so the doc and the preview can quote what was measured.96 *97 * The page is #f7f7f7 for the whole non-flood run and never changes — the98 * per-channel median is exactly 247 on 79 of 82 frames, reading 249 only where99 * a grain overlay peaks.100 */101export const REFERENCE = {102 page: "#f7f7f7",103 ink: "#1f1f1f",104 caret: "#b3a9f9",105 floodA: "#8575fa",106 floodB: "#4931f2",107} as const;108109/** Total frames, end to end. */110export function totalFrames(hasFlood = false): number {111 return CUT2_AT + 1 + (hasFlood ? FLOOD_STAGE_FRAMES * 2 : FINAL_HOLD);112}









