Search Typing
Search bar typing animation for AI search and command palette demos. A search field wider than the shot: two thirds in frame, then it comes forward, types across its left half, pages to its right half, and goes back.
Source
components/kuchi/search-typing.tsx
1"use client";23import { loadFont } from "@remotion/google-fonts/Outfit";4import {5 type CSSProperties,6 useEffect,7 useLayoutEffect,8 useRef,9 useState,10} from "react";11import {12 continueRender,13 delayRender,14 Easing,15 getRemotionEnvironment,16 interpolate,17 random,18 useCurrentFrame,19 useVideoConfig,20} from "remotion";21import { Caret } from "@/components/kuchi/caret";22import { inputStyleContext } from "@/components/kuchi/input";23import {24 mixOklch,25 resolveFont,26 type KuchiTheme,27 useKuchiTheme,28} from "@/lib/kuchi-ui";2930// Outfit Light. Identified by measuring the reference's letterforms against a31// field of candidates: its stem/cap ratio is 0.121, and Outfit 300 is the only32// geometric face that hits that exactly (stem 12px at a 99px cap, like for like).33// Loaded through @remotion/google-fonts rather than a CSS variable so the Player,34// the rendered mp4 and a user's own project all get the same face.35const { fontFamily: OUTFIT } = loadFont("normal", {36 weights: ["300", "400"],37 subsets: ["latin"],38});3940/**41 * `shadcn` — the field is a shadcn Input: a card surface, a hairline border, and a42 * shadow you have to look for. Correct on a light page, and the default.43 * `glass` — the field the reference uses: a grey crown falling to white, lit from44 * below. It is measured, and it only works on a DARK backdrop; on a light one the45 * crown reads as dirt and the shadow as a smear.46 */47export type SearchTypingSurface = "shadcn" | "glass";48export type SearchTypingIcon = "search" | "sparkle" | "none";4950export interface SearchTypingProps {51 /** The sentence typed into the field, one character at a time. */52 text: string;53 /** Typing speed. 14 is what the reference does. */54 charsPerSecond?: number;55 /**56 * Keystroke-interval variance, 0–1. 0 is a metronome. Deterministic — every57 * interval is drawn from `seed`, never from a clock.58 */59 humanize?: number;60 /** Beat after a space, as a multiple of the base keystroke interval. */61 wordPause?: number;62 /** Beat after `.,!?;:`, as a multiple of the base keystroke interval. */63 punctuationPause?: number;64 /** Seconds the field holds, parked and blinking, before the first keystroke. */65 startDelay?: number;66 /** Seconds the field takes to come forward once typing starts. */67 dollyDuration?: number;68 /** Seconds the field takes to slide from its left half to its right half. */69 panDuration?: number;70 /** Seconds the finished sentence holds at the front before the field goes back. */71 holdAfter?: number;72 /**73 * Seconds the field takes to travel back. It goes back *further* than it74 * started — far enough that the whole field lands in frame, which is the only75 * moment you see it and the finished sentence at once. 0 parks it at the front.76 */77 recedeDuration?: number;78 /**79 * How much bigger the field gets as it comes forward. 1.25 is what the80 * reference measures. `frontVisible × dolly` is how much of the field is in81 * frame at rest — 0.56 × 1.25 = 0.70, roughly the two thirds you see there.82 */83 dolly?: number;84 /**85 * The field's height on screen, as a fraction of the frame's. This is the knob86 * that makes the field look long and slim rather than chunky: it sets the87 * height directly, and the text — which is a fixed ratio of it — comes with it.88 */89 fieldHeight?: number;90 /**91 * How much of the field is in frame once it has come forward. The field is92 * padded out to whatever length that needs, so this and `fieldHeight` are93 * independent — which they are not if the field is only as long as its94 * sentence. (A real search field is longer than what you type into it.)95 */96 frontVisible?: number;97 /** Margin, in px, between the field's visible cap and the edge of the frame. */98 edgeInset?: number;99 /** Blinks per second. 1 is the ~500ms-on/500ms-off of a real text field. */100 caretBlinksPerSecond?: number;101 caret?: boolean;102 surface?: SearchTypingSurface;103 /** Design-system token overrides, same shape every kuchi-ui component takes. */104 theme?: Partial<KuchiTheme>;105 mode?: "light" | "dark";106 icon?: SearchTypingIcon;107 fontFamily?: string;108 fontWeight?: number;109 /** Seeds `humanize`. Same seed, same performance, forever. */110 seed?: string;111 /** Global playback multiplier applied to the whole sequence. */112 speed?: number;113 className?: string;114}115116/**117 * Every proportion below was measured off the reference frames, as a ratio of the118 * field's height (373px there). They are ratios and not pixels so the whole119 * component scales as one piece.120 *121 * radius 103/373 = 0.276 — NOT a pill. A pill would be 0.500.122 * cap height 99/373, and cap ≈ 0.70em, so fontSize/height = 0.379123 * left cap → text start = 382/373124 * left cap → icon = 133/373; icon box 141/373; icon stroke 12/373125 * caret 9×162 /373126 */127const R = {128 radius: 0.276,129 fontSize: 0.379,130 /**131 * Left cap → the first glyph's INK. The text box has to start a touch earlier132 * than that, because the "W" carries a side bearing: measured on the render,133 * that bearing is 0.021 × the field's height.134 */135 textInk: 1.024,136 sideBearing: 0.021,137 iconInset: 0.357,138 iconSize: 0.378,139 /**140 * The reference measures 0.62 here — but the reference's field is never seen141 * whole, so nobody ever sees its right padding next to its left. This one IS142 * seen whole at the end, and 0.62 against a 0.357 left inset does not read as143 * padding, it reads as a word missing off the end of the sentence. Balanced144 * against the left instead.145 */146 rightPad: 0.4,147 caretWidth: 0.024,148 caretHeight: 0.434,149 /**150 * Outfit sits its baseline 0.017 × height lower than the reference does once the151 * line box is centred in the field. The line box's height cannot fix that — a152 * centred line box puts the baseline at `H/2 − content/2 + ascent`, which is a153 * property of the face, not of the leading — so the text is nudged instead.154 */155 baselineNudge: 0.017,156} as const;157158/**159 * The field's height in layout px. Purely a unit — every other measurement is a160 * ratio of it, and the camera rescales the whole thing to whatever `fieldHeight`161 * asks for. Nothing on screen changes if you change it.162 */163const LAYOUT_UNIT = 240;164165/** Where the text box starts, so that its first glyph's ink lands on the mark. */166const R_TEXT_LEFT = R.textInk - R.sideBearing;167/** Left cap → text, minus the icon and its inset, is the gap after the icon. */168const R_GAP = R_TEXT_LEFT - R.iconInset - R.iconSize;169170const PUNCTUATION = /[.,!?;:]/;171172/** The push runs while the sentence is being typed, so it must not crawl at the end. */173const DOLLY_EASING = Easing.inOut(Easing.sin);174/** The page across is a deliberate move: it leaves and arrives. */175const PAN_EASING = Easing.inOut(Easing.cubic);176const BACK_EASING = Easing.inOut(Easing.cubic);177178function clamp01(t: number): number {179 return Math.max(0, Math.min(1, t));180}181182function smoothstep(t: number): number {183 const x = clamp01(t);184 return x * x * (3 - 2 * x);185}186187export interface TypingScheduleOptions {188 fps: number;189 charsPerSecond: number;190 humanize: number;191 wordPause: number;192 punctuationPause: number;193 seed: string;194}195196/**197 * The frame each prefix length lands on: `schedule[n]` is the frame at which the198 * field shows exactly `n` characters. Strictly monotonic by construction, which199 * is what {@link typedCount} relies on and why a scrub can never un-type a letter.200 */201export function buildTypingSchedule(202 text: string,203 opts: TypingScheduleOptions,204): number[] {205 const { fps, charsPerSecond, humanize, wordPause, punctuationPause, seed } =206 opts;207 const base = fps / Math.max(0.1, charsPerSecond);208 const jitter = clamp01(humanize);209210 const schedule: number[] = [0];211 let acc = 0;212213 for (let i = 0; i < text.length; i++) {214 // The rest belongs to the gap *before* this character — a typist pauses after215 // finishing a word, not before typing the space itself.216 const prev = i > 0 ? text[i - 1] : "";217 let interval = base;218 if (prev === " ") {219 interval *= wordPause;220 } else if (prev !== "" && PUNCTUATION.test(prev)) {221 interval *= punctuationPause;222 }223 if (jitter > 0) {224 const r = random(`${seed}-key-${i}`) * 2 - 1;225 interval *= 1 + r * 0.35 * jitter;226 }227 acc += Math.max(0.001, interval);228 schedule.push(acc);229 }230231 return schedule;232}233234/** Characters visible at `localFrame`, given a monotonic {@link buildTypingSchedule}. */235export function typedCount(localFrame: number, schedule: number[]): number {236 if (localFrame <= 0 || schedule.length <= 1) return 0;237 let n = 0;238 while (n + 1 < schedule.length && schedule[n + 1] <= localFrame) n++;239 return n;240}241242/**243 * The character that starts the page across. Null when the sentence fits in the244 * first half and the field never has to move.245 *246 * `triggerX` is deliberately NOT the frame's edge. The pan eases in, so for its247 * first few frames the field has barely moved while the typing carries the caret248 * on rightwards — fire the pan *at* the edge and the caret spills over it before249 * the field catches up. {@link PAN_TRIGGER} keeps a couple of characters' worth of250 * lead in hand.251 */252export function pageTriggerIndex(253 advances: number[],254 textLeft: number,255 scale: number,256 triggerX: number,257): number | null {258 for (let n = 1; n < advances.length; n++) {259 if ((textLeft + advances[n]) * scale > triggerX) return n;260 }261 return null;262}263264/** Fraction of the page at which the caret hands the shot over to the pan. */265const PAN_TRIGGER = 0.88;266267export interface CameraMarks {268 typingStart: number;269 dollyEnd: number;270 panStart: number | null;271 panEnd: number;272 holdEnd: number;273 recedeEnd: number;274}275276/**277 * 0 = parked back, 1 = fully forward. Rises across the dolly and then holds — it278 * does NOT come back down. The retreat is a separate move to a separate depth.279 */280export function cameraPush(frame: number, m: CameraMarks): number {281 if (m.dollyEnd <= m.typingStart) return frame >= m.typingStart ? 1 : 0;282 return interpolate(frame, [m.typingStart, m.dollyEnd], [0, 1], {283 extrapolateLeft: "clamp",284 extrapolateRight: "clamp",285 easing: DOLLY_EASING,286 });287}288289/**290 * 0 = still at the front, 1 = fully retreated.291 *292 * The field does not go back to where it started. It goes back **further** — far293 * enough that the whole of it lands in frame, which is the only moment in the clip294 * you ever see the complete field and the complete sentence at once. That is the295 * payoff, so it gets its own depth rather than reusing the resting one.296 */297export function cameraRetreat(frame: number, m: CameraMarks): number {298 if (m.recedeEnd <= m.holdEnd) return 0;299 return interpolate(frame, [m.holdEnd, m.recedeEnd], [0, 1], {300 extrapolateLeft: "clamp",301 extrapolateRight: "clamp",302 easing: BACK_EASING,303 });304}305306/** 0 = the field's left half is in frame, 1 = its right half is. */307export function cameraPan(frame: number, m: CameraMarks): number {308 if (m.panStart === null || m.panEnd <= m.panStart) return 0;309 return interpolate(frame, [m.panStart, m.panEnd], [0, 1], {310 extrapolateLeft: "clamp",311 extrapolateRight: "clamp",312 easing: PAN_EASING,313 });314}315316export interface CaretBlinkOptions {317 fps: number;318 blinksPerSecond: number;319 softness?: number;320}321322/**323 * A real caret is a hard square wave. At 60fps a hard edge reads as a strobe, so324 * only the edges are eased — it still spends most of the cycle fully on and fully325 * off, it just doesn't snap between them.326 */327export function caretOpacity(frame: number, opts: CaretBlinkOptions): number {328 const { fps, blinksPerSecond } = opts;329 if (blinksPerSecond <= 0 || fps <= 0) return 1;330331 const period = fps / blinksPerSecond;332 if (period <= 0) return 1;333334 const t = (((frame % period) + period) % period) / period;335 const edge = Math.min(0.25, Math.max(0, opts.softness ?? 0.12));336 if (edge === 0) return t < 0.5 ? 1 : 0;337338 if (t < 0.5 - edge) return 1;339 if (t < 0.5) return 1 - smoothstep((t - (0.5 - edge)) / edge);340 if (t < 1 - edge) return 0;341 return smoothstep((t - (1 - edge)) / edge);342}343344/**345 * The magnifier's INK fills the viewBox exactly — circle at (9, 9) r=7.98 with a346 * 2.03 stroke reaches x=0, and the round-capped handle reaches x=24. That matters:347 * `iconSize` is the reference's measured ink extent (0.378 × the field's height),348 * so if the glyph sat inside its box with air around it, it would come out349 * noticeably smaller than the reference's. It did, the first time.350 */351function SearchGlyph({ size, color }: { size: number; color: string }) {352 return (353 <svg354 width={size}355 height={size}356 viewBox="0 0 24 24"357 fill="none"358 aria-hidden="true"359 style={{ display: "block", flexShrink: 0, overflow: "visible" }}360 >361 <circle cx="9" cy="9" r="7.98" stroke={color} strokeWidth={2.03} />362 <path363 d="M14.65 14.65 L22.98 22.98"364 stroke={color}365 strokeWidth={2.03}366 strokeLinecap="round"367 />368 </svg>369 );370}371372function SparkleGlyph({ size, color }: { size: number; color: string }) {373 return (374 <svg375 width={size}376 height={size}377 viewBox="0 0 24 24"378 fill="none"379 aria-hidden="true"380 style={{ display: "block", flexShrink: 0, overflow: "visible" }}381 >382 <path383 d="M12 2.6 L13.9 9.1 L20.4 11 L13.9 12.9 L12 19.4 L10.1 12.9 L3.6 11 L10.1 9.1 Z"384 fill={color}385 />386 <path387 d="M18.9 16.4 L19.7 19.1 L22.4 19.9 L19.7 20.7 L18.9 23.4 L18.1 20.7 L15.4 19.9 L18.1 19.1 Z"388 fill={color}389 opacity={0.55}390 />391 </svg>392 );393}394395interface Metrics {396 /** Cumulative advance of each character prefix, in layout px. */397 advances: number[];398 /** Y of the text baseline, in layout px from the top of the field. */399 baselineY: number;400 /** The field's full width in layout px — it is sized by its own content. */401 fieldWidth: number;402}403404/**405 * A search field that is wider than the shot, on a dolly.406 *407 * Two thirds of it are in frame to begin with, parked back. On the first keystroke408 * it comes forward, and now only its left half fits. The sentence types across that409 * half; when the caret runs out of frame the field slides, and its right half comes410 * in. The sentence finishes there, and the field goes back.411 *412 * The two things that make scaled type look cheap are both handled:413 *414 * 1. **The scale pivots on the text baseline.** A browser gives glyph origins no415 * vertical sub-pixel precision — it rounds them to a whole device pixel — so a416 * scale that *moves* the baseline makes the type climb the pixel grid in whole417 * pixel jumps. Pivot on it and its device Y never changes. Measured, not418 * guessed from a line-height.419 * 2. **`text-rendering: geometricPrecision`.** Hinting bends each glyph so its420 * stems land on whole pixels; under a sliding scale they re-snap every frame421 * and the letterforms boil.422 *423 * The sentence itself is laid out once, in full, and revealed by clipping to a424 * measured character boundary — never re-sliced, so a settled glyph cannot re-kern425 * as the next one lands.426 */427export function SearchTyping({428 text,429 charsPerSecond = 14,430 humanize = 0.35,431 wordPause = 1.55,432 punctuationPause = 2.2,433 startDelay = 0.5,434 dollyDuration = 0.8,435 panDuration = 0.5,436 holdAfter = 0.9,437 recedeDuration = 1.2,438 dolly = 1.25,439 fieldHeight = 0.27,440 frontVisible = 0.56,441 edgeInset = 40,442 caretBlinksPerSecond = 1,443 caret = true,444 surface = "shadcn",445 theme,446 mode,447 icon = "search",448 fontFamily,449 fontWeight = 300,450 seed = "search-typing",451 speed = 1,452 className,453}: SearchTypingProps) {454 const frame = useCurrentFrame();455 const { fps, width: frameWidth, height: frameHeight } = useVideoConfig();456 const t = useKuchiTheme(theme, mode);457 const face = resolveFont(fontFamily ?? t.fontFamily) ?? OUTFIT;458 // The very same context the shadcn <Input> paints itself from, so this field and459 // that one cannot drift apart.460 const ui = inputStyleContext(t);461 const resolvedFontFamily = face;462463 const H = LAYOUT_UNIT;464 const fontSize = R.fontSize * H;465 const textLeft = R_TEXT_LEFT * H;466 const caretWidth = Math.max(1, R.caretWidth * H);467 const caretHeight = R.caretHeight * H;468 const iconSize = R.iconSize * H;469 const lineHeight = Math.round(fontSize * 1.4);470471 const schedule = buildTypingSchedule(text, {472 fps,473 charsPerSecond,474 humanize,475 wordPause,476 punctuationPause,477 seed,478 });479480 const clock = frame * speed;481 const typingStart = startDelay * fps;482 const typingEnd = typingStart + (schedule[schedule.length - 1] ?? 0);483 const count = typedCount(clock - typingStart, schedule);484485 // ---- measurement -------------------------------------------------------486 const cameraRef = useRef<HTMLDivElement>(null);487 const fieldRef = useRef<HTMLDivElement>(null);488 const textRef = useRef<HTMLSpanElement>(null);489 const baselineRef = useRef<HTMLSpanElement>(null);490 const [metrics, setMetrics] = useState<Metrics | null>(null);491 const [handle] = useState(() =>492 delayRender("search-typing: measuring field, baseline and advances"),493 );494495 useLayoutEffect(() => {496 const camEl = cameraRef.current;497 const fieldEl = fieldRef.current;498 const textEl = textRef.current;499 const baseEl = baselineRef.current;500 if (!camEl || !fieldEl || !textEl || !baseEl) return;501 let cancelled = false;502503 const measure = () => {504 if (cancelled) return;505506 // getBoundingClientRect reports *device* px, so it sees the camera's scale507 // and would hand back every advance multiplied by it. Switch the transform508 // off for the read; useLayoutEffect runs before paint, so it never shows.509 const previous = camEl.style.transform;510 camEl.style.transform = "none";511512 const fieldRect = fieldEl.getBoundingClientRect();513 const baselineY = baseEl.getBoundingClientRect().top - fieldRect.top;514 const fieldWidth = fieldRect.width;515516 const advances: number[] = [0];517 const node = textEl.firstChild;518 if (node) {519 // The run is `white-space: pre` and holds the *whole* sentence, so a range520 // ending on a space is never a trailing space — its advance is real. That521 // is why the caret sits after the space in "the most |".522 const range = document.createRange();523 for (let i = 1; i <= text.length; i++) {524 range.setStart(node, 0);525 range.setEnd(node, i);526 advances.push(range.getBoundingClientRect().width);527 }528 }529530 camEl.style.transform = previous;531 setMetrics({ advances, baselineY, fieldWidth });532 };533534 // Measuring against a fallback face measures the wrong face: the real one swaps535 // in a frame later and every advance — and the baseline — moves.536 if (typeof document !== "undefined" && document.fonts) {537 if (document.fonts.status === "loaded") measure();538 else void document.fonts.ready.then(measure);539 } else {540 measure();541 }542543 return () => {544 cancelled = true;545 };546 }, [text]);547548 useEffect(() => {549 if (metrics) continueRender(handle);550 }, [metrics, handle]);551552 // ---- camera ------------------------------------------------------------553 const pageWidth = frameWidth - edgeInset * 2;554555 // The scale is set by the height we want the field to READ at, not by its556 // length. Length is then whatever the framing needs — the field is padded out557 // to it. Doing this the other way round is what made the field chunky: a field558 // only as long as its sentence has a fixed aspect, so demanding that half of it559 // fill the frame forces its height.560 const frontScale = (fieldHeight * frameHeight) / H;561 const restScale = frontScale / Math.max(1.0001, dolly);562563 // The field's natural length: icon + sentence + the reference's padding.564 const naturalWidth = metrics?.fieldWidth ?? frameWidth * 2;565 const framedWidth =566 pageWidth / Math.max(0.05, Math.min(1, frontVisible)) / frontScale;567 // Never shorter than its own content — a long sentence simply makes a long field.568 const fieldWidth = Math.max(naturalWidth, framedWidth);569570 const advances = metrics?.advances ?? null;571 const triggerIndex = advances572 ? pageTriggerIndex(advances, textLeft, frontScale, pageWidth * PAN_TRIGGER)573 : null;574575 const marks: CameraMarks = {576 typingStart,577 dollyEnd: typingStart + dollyDuration * fps,578 panStart:579 triggerIndex !== null ? typingStart + schedule[triggerIndex] : null,580 panEnd:581 triggerIndex !== null582 ? typingStart + schedule[triggerIndex] + panDuration * fps583 : 0,584 holdEnd: typingEnd + holdAfter * fps,585 recedeEnd: typingEnd + holdAfter * fps + recedeDuration * fps,586 };587588 // The depth the field ends at: exactly wide enough that the whole of it fits the589 // page. `edgeInset` then leaves it an equal margin on both sides, so anchoring590 // the retreat on its right cap lands it centred without any special case.591 const endScale = pageWidth / Math.max(1, fieldWidth);592593 const push = cameraPush(clock, marks);594 const back = cameraRetreat(clock, marks);595 const pan = cameraPan(clock, marks);596597 // rest → front on the push, then front → end on the retreat.598 const forward = restScale + (frontScale - restScale) * push;599 const scale = forward + (endScale - forward) * back;600601 // Left cap pinned to the frame's left edge, or right cap pinned to its right —602 // the pan crossfades between the two anchors. Because the right anchor is a603 // function of the *current* scale, the retreat pulls back around the right cap604 // instead of dragging it off screen.605 const leftAnchored = edgeInset;606 const rightAnchored = frameWidth - edgeInset - fieldWidth * scale;607 const originX = leftAnchored + (rightAnchored - leftAnchored) * pan;608609 const contentWidth = advances ? advances[advances.length - 1] : 0;610 const caretX = advances ? advances[Math.min(count, advances.length - 1)] : 0;611612 const blinkOpacity = caretOpacity(clock, {613 fps,614 blinksPerSecond: caretBlinksPerSecond,615 });616617 const baselineY = metrics?.baselineY ?? H / 2;618619 // NO drop shadow. shadcn defines a control with a hairline border, not with a620 // shadow doing the border's job — and a shadow big enough to be seen under a621 // field this size is a grey smear on a light page, which is what the first two622 // attempts here looked like. The border carries it, and the field is clean.623 // A hairline is specified for a ~40px control, where 1px is 2.5% of its height.624 // This field is five times that, so the same hairline all but disappears — the625 // border has to be stepped up, in weight AND in contrast, or the field has no626 // edge at all. Both still come from the design system: the width is a ratio of627 // the field's height, and the colour is the hairline walked toward the628 // foreground with the system's own `mixOklch`.629 const border = Math.max(1, 0.009 * H);630 const borderColor = mixOklch(ui.idleBorder, t.foreground, 0.28);631 const shadcnSurface = {632 background: t.card,633 border: `${border}px solid ${borderColor}`,634 boxShadow: "none",635 };636 // The reference's field, measured: a grey crown falling to white, lit from below.637 // It is lit for a DARK backdrop — on a light one the crown reads as an inner638 // shadow and the drop shadow as a smear. Opt in only over something dark.639 const glassSurface = {640 background:641 "linear-gradient(180deg, #C4C4C4 0%, #D6D6D6 15%, #E7E7E7 30%, #F3F3F3 40%, #FDFDFD 50%, #FDFDFD 100%)",642 border: "none",643 boxShadow: `0 ${0.045 * H}px ${0.12 * H}px rgba(9, 9, 12, 0.45)`,644 };645 const field = surface === "glass" ? glassSurface : shadcnSurface;646 const inkColor = surface === "glass" ? "#000000" : ui.foreground;647 const iconColor = surface === "glass" ? "#000000" : ui.mutedForeground;648649 const textStyle: CSSProperties = {650 fontSize,651 fontWeight,652 fontFamily: resolvedFontFamily,653 lineHeight: `${lineHeight}px`,654 color: inkColor,655 whiteSpace: "pre",656 // A ligature is one glyph for two characters; clipping through one would paint657 // half an "fi".658 fontVariantLigatures: "none",659 fontKerning: "normal",660 // The type rides a moving scale, so hinting would re-snap every stem to the661 // pixel grid each frame and the letterforms would boil.662 textRendering: "geometricPrecision",663 display: "block",664 };665666 // box-shadow takes no percentages, so the offsets are computed from the field's667 // height — the shadow then scales with the field instead of detaching from it.668669 return (670 <div style={{ position: "absolute", inset: 0, overflow: "hidden" }}>671 <div672 ref={cameraRef}673 style={{674 position: "absolute",675 left: 0,676 top: (frameHeight - H) / 2,677 transform: `translateX(${originX}px) scale(${scale})`,678 // x=0 is the field's left cap, so translateX places it exactly. y is the679 // baseline, so the type cannot climb the pixel grid as the scale moves.680 transformOrigin: `0px ${baselineY}px`,681 ...(getRemotionEnvironment().isRendering682 ? null683 : { willChange: "transform" as const }),684 }}685 >686 <div687 ref={fieldRef}688 className={className}689 style={{690 display: "flex",691 alignItems: "center",692 // max-content until the content has been measured; then the field is693 // padded out to the length the framing wants.694 width: metrics ? fieldWidth : "max-content",695 height: H,696 paddingLeft: R.iconInset * H,697 paddingRight: R.rightPad * H,698 gap: R_GAP * H,699 borderRadius: R.radius * H,700 background: field.background,701 border: field.border,702 boxShadow: field.boxShadow,703 boxSizing: "border-box",704 }}705 >706 {icon === "search" ? (707 <SearchGlyph size={iconSize} color={iconColor} />708 ) : null}709 {icon === "sparkle" ? (710 <SparkleGlyph size={iconSize} color={iconColor} />711 ) : null}712713 <div714 style={{715 position: "relative",716 height: lineHeight,717 flexShrink: 0,718 // Lifts the line onto the reference's baseline. The caret and the719 // measured baselineY ride along with it, so the pivot stays true.720 marginTop: -2 * R.baselineNudge * H,721 }}722 >723 <span724 ref={textRef}725 style={{726 ...textStyle,727 // Negative vertical insets so ascenders and descenders are never728 // clipped; only the right edge does any work.729 clipPath: `inset(-0.5em ${Math.max(0, contentWidth - caretX)}px -0.5em 0)`,730 }}731 >732 {text}733 <span734 ref={baselineRef}735 style={{ display: "inline-block", width: 0, height: 0 }}736 />737 </span>738739 {caret ? (740 <Caret741 color={inkColor}742 width={caretWidth}743 height={caretHeight}744 radius={0}745 opacity={blinkOpacity}746 style={{747 position: "absolute",748 left: caretX,749 top: (lineHeight - caretHeight) / 2,750 }}751 />752 ) : null}753 </div>754 </div>755 </div>756 </div>757 );758}759760export interface SearchTypingDurationOptions extends TypingScheduleOptions {761 startDelay: number;762 holdAfter: number;763 recedeDuration: number;764}765766/**767 * Frames the whole clip needs: the lead-in, the typing, the hold at the front and768 * the retreat. The camera's dolly and pan both finish inside the typing, so they769 * never extend it.770 */771export function searchTypingDuration(772 text: string,773 opts: SearchTypingDurationOptions,774): number {775 const schedule = buildTypingSchedule(text, opts);776 const typing = schedule[schedule.length - 1] ?? 0;777 return Math.ceil(778 opts.startDelay * opts.fps +779 typing +780 opts.holdAfter * opts.fps +781 opts.recedeDuration * opts.fps,782 );783}









