Answer Highlight
AI answer highlight animation, ChatGPT-style chat response with a text selection. A question in a pill, an answer that writes itself a word at a time, and then the beat the whole shot is for: a caret lands mid-sentence and a selection band drags across one statement, wrapping the line the way a real one does — and settles onto the single word that matters.
Source
components/kuchi/answer-highlight.tsx
1"use client";23import { loadFont as loadSans } from "@remotion/google-fonts/Inter";4import {5 AbsoluteFill,6 Easing,7 interpolate,8 useCurrentFrame,9 useVideoConfig,10} from "remotion";11import {12 mixOklch,13 resolveFont,14 type KuchiTheme,15 useKuchiTheme,16 withAlpha,17} from "@/lib/kuchi-ui";1819// Loaded through @remotion/google-fonts, never a CSS variable — a Remotion20// bundle has none of the app's CSS, so a `var(--font-…)` gets you the right face21// in the Player and a fallback in the mp4 (design-system rule 4).22const { fontFamily: SANS } = loadSans("normal", {23 weights: ["400", "500"],24 subsets: ["latin"],25});2627// ---------------------------------------------------------------------------28// Proportions29//30// Fractions of the composition height, never pixels, so the scene holds its31// shape at 720p, 1080p or a vertical crop.32//33// The question pill's numbers are the same ones `agent-steps` carries, measured34// off the same 718x398 recording by the mass of the pill's fill and by35// cross-correlating its column ink under a scale sweep. They are repeated here36// rather than imported because a registry file is copied whole into somebody's37// project — a shared constants module would be a dependency they did not ask38// for. If you change one, change the other.39// ---------------------------------------------------------------------------4041/** Question pill height. 22.0px of 398. */42const PILL_H = 0.0553;43/** Corner radius as a fraction of pill height. Not a stadium — that would be 0.5. */44const PILL_R = 0.28;45/** Pill padding either side of the label, as a fraction of pill height. */46const PILL_PAD = 0.42;47/** Question type size, as a fraction of composition height. */48const QUESTION_FONT = 0.0223;49/** Answer type size. Bigger than the question: the question is a caption on the50 * thing you are here to read. */51const ANSWER_FONT = 0.0385;52/**53 * Answer line height, as a multiple of its own type size.54 *55 * Looser than a paragraph would normally want. The selection band fills its56 * line box the way a browser's does, so at 1.5 the band on one line sits57 * against the type on the next and the whole thing reads as a solid block of58 * colour instead of as two selected lines.59 */60const ANSWER_LEADING = 1.64;61/** Answer measure, as a fraction of frame width. Long enough for three or four62 * lines of a real answer, short enough that the eye does not lose the line. */63const MEASURE = 0.6;64/** Gap between the pill's bottom and the answer's first baseline box. */65const PILL_GAP = 0.075;6667/** Selection band padding above and below the type, as a fraction of the answer68 * type size — a browser's own selection sits a little proud of the leading. */69const BAND_PAD_Y = 0.18;70/** Band corner radius, as a fraction of the answer type size. */71const BAND_R = 0.1;72/** The caret at the leading edge of the drag, as a fraction of the type size. */73const CARET_W = 0.06;7475// ---------------------------------------------------------------------------76// Motion77//78// The pill's entrance is measured (see `agent-steps`). Everything below it is79// *chosen*, not fitted — there is no reference recording for this scene — so the80// numbers say what they are for rather than quoting an rms.81// ---------------------------------------------------------------------------8283/** The question's entrance: scale, blur and opacity, in seconds. */84const INTRO_S = 0.375;85const INTRO_BLUR_S = 0.2;86const INTRO_SCALE = 1.31;87/** Blur at t=0, as a fraction of composition height. */88const INTRO_BLUR = 0.0141;8990/**91 * One word of the answer's arrival, in seconds, and the gap between two of them.92 *93 * The stagger is the read: at 0.055s a 30-word answer takes 1.65s, which is fast94 * enough to feel generated and slow enough that the eye can start reading before95 * it finishes. Each word takes longer to arrive (0.22s) than the gap between two96 * — so four or five words are always mid-arrival, which is what stops it looking97 * like a ticker.98 */99const WORD_IN_S = 0.22;100const WORD_STEP_S = 0.055;101/** How far a word rises as it arrives, as a fraction of its own type size. */102const WORD_RISE = 0.34;103104/**105 * Seconds the drag spends on each word of the statement.106 *107 * A selection is not a fade. The band is painted as a gradient with a hard stop108 * inside the word the drag is currently crossing, so the leading edge moves109 * *through* a word rather than jumping over it — at 30fps a per-word step would110 * advance the edge three whole words a second and read as four chips appearing,111 * not as a hand pulling across the line.112 *113 * 0.11s is a real drag: four words in a little under half a second.114 */115const BAND_STEP_S = 0.11;116117/** The word inside the statement, once the statement is selected. */118const WORD_BAND_S = 0.2;119/** Word gap, as an em of the answer type. Padding, not margin — see the span. */120const WORD_GAP = 0.28;121122// ---------------------------------------------------------------------------123124export interface AnswerHighlightProps {125 /** The prompt, in the pill at the top. */126 question?: string;127 /** The answer. It writes itself a word at a time; line breaks are the128 * browser's, so write a paragraph and let `measure` set the rag. */129 answer?: string;130 /**131 * The run inside `answer` that gets selected — word for word, as written.132 * A run that is not found simply never highlights, which is the signal that133 * the two strings have drifted apart.134 */135 statement?: string;136 /** The one word inside `statement` that takes the second, stronger band. */137 word?: string;138 /** Seconds the question holds alone before the answer starts. */139 questionHold?: number;140 /** Seconds between the answer finishing and the drag starting. */141 beforeDrag?: number;142 /** Seconds the selected statement holds before the word is picked out. */143 beforeWord?: number;144 /** Seconds per word of the answer's arrival, and of the drag. */145 wordStep?: number;146 dragStep?: number;147 /** Page behind the scene. Defaults to `theme.background`. */148 paperColor?: string;149 /** Pill fill. Defaults to `theme.card`. */150 pillColor?: string;151 /** Question ink. Defaults to `theme.mutedForeground`. */152 questionColor?: string;153 /** Answer ink. Defaults to `theme.foreground`. */154 answerColor?: string;155 /** The selection, the caret and the picked word. Defaults to `theme.primary`. */156 accentColor?: string;157 /** Where the lockup sits, as a fraction of frame height. */158 centerY?: number;159 fontFamily?: string;160 theme?: Partial<KuchiTheme>;161 mode?: "light" | "dark";162 speed?: number;163}164165// --- Pure helpers (unit-tested) -------------------------------------------166167/**168 * The answer, as the tokens the scene actually animates.169 *170 * Split on whitespace and *keep the punctuation attached to its word*, because171 * the selection band is painted per token: a comma that is its own token gets172 * its own band and its own arrival, and the band comes apart at every clause.173 */174export function splitWords(text: string): string[] {175 return text.split(/\s+/).filter(Boolean);176}177178/**179 * A token with its outer punctuation taken off, for matching only.180 *181 * So that `statement="keep the timeline declarative"` finds the answer's182 * `declarative,` — writing the comma into the prop to make the match land is183 * the kind of thing nobody remembers and everybody debugs twice.184 */185export function bare(wordToken: string): string {186 return wordToken.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");187}188189/**190 * Where `phrase` sits in `words`, as a half-open [start, end) word range.191 *192 * Matched on the joined text rather than word by word so that a phrase written193 * with its own internal spacing still lands. Returns null when it is not there —194 * the caller draws no band, which makes a drifted prop visible instead of195 * highlighting some near-miss run of words.196 */197export function findRun(198 words: string[],199 phrase: string,200): [number, number] | null {201 const target = splitWords(phrase).map(bare);202 if (target.length === 0) return null;203 const wanted = target.join(" ");204 const haystack = words.map(bare);205 for (let i = 0; i + target.length <= words.length; i += 1) {206 if (haystack.slice(i, i + target.length).join(" ") === wanted) {207 return [i, i + target.length];208 }209 }210 return null;211}212213/**214 * The selection band on one word, as a CSS background.215 *216 * `across` is how far the drag has crossed this word: nothing at 0, a solid217 * band at 1, and in between a hard-edged gradient with the caret sitting just218 * past the stop. Returned as `undefined` when there is nothing to paint so the219 * span keeps its cheap "no background" path.220 */221export function paintBand(222 across: number,223 fill: string,224 caret: string,225 caretWidth: number,226): string | undefined {227 if (across <= 0) return undefined;228 if (across >= 1) return fill;229 const stop = `${(across * 100).toFixed(2)}%`;230 return (231 `linear-gradient(to right, ${fill} 0 ${stop}, ` +232 `${caret} ${stop}, ${caret} calc(${stop} + ${caretWidth.toFixed(2)}px), ` +233 `transparent calc(${stop} + ${caretWidth.toFixed(2)}px))`234 );235}236237/** Progress of a value that starts at `at` and takes `dur` frames. */238export function ramp(fc: number, at: number, dur: number): number {239 if (dur <= 0) return fc >= at ? 1 : 0;240 return Math.max(0, Math.min(1, (fc - at) / dur));241}242243/**244 * The frame the drag's leading edge is on, as a fractional word index.245 *246 * Fractional on purpose: the caret is drawn on `floor(edge)` and the band on247 * everything behind it, so the edge can sit between two words and the bar does248 * not jump a whole word at a time on a 30fps clock.249 */250export function dragEdge(251 fc: number,252 at: number,253 stepF: number,254 count: number,255): number {256 if (stepF <= 0) return fc >= at ? count : 0;257 return Math.max(0, Math.min(count, (fc - at) / stepF));258}259260// --- Defaults --------------------------------------------------------------261262const DEFAULT_ANSWER =263 "Build one composition per scene and keep the timeline declarative, " +264 "so the same props always render the same frames. Anything that reads " +265 "the clock at render time is a bug you will find in the export.";266267// ---------------------------------------------------------------------------268269export function AnswerHighlight({270 question = "How should we structure the demo video?",271 answer = DEFAULT_ANSWER,272 statement = "keep the timeline declarative",273 word = "declarative",274 questionHold = 0.6,275 beforeDrag = 0.45,276 beforeWord = 0.6,277 wordStep = WORD_STEP_S,278 dragStep = BAND_STEP_S,279 paperColor,280 pillColor,281 questionColor,282 answerColor,283 accentColor,284 centerY = 0.5,285 fontFamily,286 theme: themeOverride,287 mode,288 speed = 1,289}: AnswerHighlightProps) {290 const frame = useCurrentFrame();291 const { fps, height, width } = useVideoConfig();292 const t = useKuchiTheme(themeOverride, mode);293 const face = resolveFont(fontFamily ?? t.fontFamily) ?? SANS;294295 const fc = frame * speed;296 const paper = paperColor ?? t.background;297 const pill = pillColor ?? t.card;298 const askInk = questionColor ?? t.mutedForeground;299 const ink = answerColor ?? t.foreground;300 const accent = accentColor ?? t.primary;301302 // A selection is a *tint of the page*, never the accent at full strength.303 // Primary behind body type at any real opacity puts white-on-blue in the304 // middle of a paragraph and the line stops being readable — which is exactly305 // why a browser's own selection is pale until the window loses focus.306 //307 // Alpha, not `mixOklch`. Mixing a warm off-white (#faf9f6) toward a blue in308 // oklch takes the short way round the hue wheel and passes through green: the309 // first cut of this scene highlighted the answer in pale mint. A tint of a310 // colour over paper is an alpha composite, not a hue interpolation.311 const band = withAlpha(accent, 0.16);312313 const font = ANSWER_FONT * height;314 const words = splitWords(answer);315 const run = findRun(words, statement);316 const wordRun = run ? findRun(words, word) : null;317 // Only a word *inside* the selected statement is picked out. One that happens318 // to appear earlier in the answer is not the one meant.319 const picked =320 wordRun && run && wordRun[0] >= run[0] && wordRun[1] <= run[1]321 ? wordRun322 : null;323324 // --- the clock -----------------------------------------------------------325326 const answerAt = questionHold * fps;327 const stepF = wordStep * fps;328 const answerDone = answerAt + (words.length - 1) * stepF + WORD_IN_S * fps;329 const dragAt = answerDone + beforeDrag * fps;330 const dragStepF = dragStep * fps;331 const runLen = run ? run[1] - run[0] : 0;332 const dragDone = dragAt + runLen * dragStepF;333 const wordAt = dragDone + beforeWord * fps;334335 const edge = run ? dragEdge(fc, dragAt, dragStepF, runLen) : 0;336 const wordIn = Easing.out(Easing.cubic)(ramp(fc, wordAt, WORD_BAND_S * fps));337338 const intro = Easing.out(Easing.cubic)(ramp(fc, 0, INTRO_S * fps));339 const introBlur =340 INTRO_BLUR *341 height *342 (1 - Easing.out(Easing.cubic)(ramp(fc, 0, INTRO_BLUR_S * fps)));343344 return (345 <AbsoluteFill346 style={{347 backgroundColor: paper,348 alignItems: "center",349 justifyContent: "center",350 overflow: "hidden",351 }}352 >353 <div354 style={{355 position: "absolute",356 top: `${centerY * 100}%`,357 transform: "translateY(-50%)",358 width: MEASURE * width,359 display: "flex",360 flexDirection: "column",361 alignItems: "flex-start",362 }}363 >364 {/* The question. Same pill, same entrance, as `agent-steps`. */}365 <div366 style={{367 opacity: intro,368 filter: introBlur > 0.01 ? `blur(${introBlur}px)` : undefined,369 transform: `scale(${interpolate(intro, [0, 1], [INTRO_SCALE, 1])})`,370 transformOrigin: "0% 50%",371 marginBottom: PILL_GAP * height,372 }}373 >374 <div375 style={{376 fontFamily: face,377 fontSize: QUESTION_FONT * height,378 fontWeight: 500,379 lineHeight: 1,380 color: askInk,381 background: pill,382 height: PILL_H * height,383 borderRadius: PILL_R * PILL_H * height,384 padding: `0 ${PILL_PAD * PILL_H * height}px`,385 display: "flex",386 alignItems: "center",387 whiteSpace: "nowrap",388 }}389 >390 {question}391 </div>392 </div>393394 {/* The answer. Every word is its own inline span, which is what lets the395 selection band be a background rather than a measured rectangle: the396 browser wraps the spans, and a band that is painted per word wraps397 with them and breaks square at the line end, exactly like a real one.398 No DOM measurement, and it survives any copy you put in it. */}399 <div400 style={{401 fontFamily: face,402 fontSize: font,403 fontWeight: 400,404 lineHeight: ANSWER_LEADING,405 color: ink,406 }}407 >408 {words.map((w, i) => {409 const arrive = Easing.out(Easing.cubic)(410 ramp(fc, answerAt + i * stepF, WORD_IN_S * fps),411 );412 const inRun = run ? i >= run[0] && i < run[1] : false;413 const isPicked = picked ? i >= picked[0] && i < picked[1] : false;414 // How far the drag has crossed *this* word: 0 not yet, 1 fully past,415 // and everything between is where the leading edge actually is.416 const across =417 inRun && run ? Math.max(0, Math.min(1, edge - (i - run[0]))) : 0;418 const fill = isPicked419 ? withAlpha(accent, 0.16 + 0.14 * wordIn)420 : band;421422 return (423 <span424 // biome-ignore lint/suspicious/noArrayIndexKey: the answer is a fixed ordered token list, so the index is the identity425 key={i}426 style={{427 display: "inline-block",428 opacity: arrive,429 transform: `translateY(${(1 - arrive) * WORD_RISE * font}px)`,430 color: isPicked ? mixOklch(ink, accent, wordIn) : ink,431 // One background does the band, its leading edge and the432 // caret: solid behind everything the drag has passed, a hard433 // stop where it has got to, and a sliver of the accent just434 // ahead of that stop while it is still moving. A caret drawn435 // as a separate element would have to be positioned, and436 // positioning it means measuring the text.437 background: paintBand(across, fill, accent, CARET_W * font),438 // The word gap is padding, not margin, so the band is drawn439 // behind the space as well: a selection over four words comes440 // out as one unbroken run rather than four chips with holes441 // where the spaces were.442 padding: `${BAND_PAD_Y * font}px ${WORD_GAP}em ${BAND_PAD_Y * font}px 0`,443 borderTopLeftRadius:444 run && i === run[0] ? BAND_R * font : undefined,445 borderBottomLeftRadius:446 run && i === run[0] ? BAND_R * font : undefined,447 borderTopRightRadius:448 run && i === run[1] - 1 ? BAND_R * font : undefined,449 borderBottomRightRadius:450 run && i === run[1] - 1 ? BAND_R * font : undefined,451 }}452 >453 {w}454 </span>455 );456 })}457 </div>458 </div>459 </AbsoluteFill>460 );461}









