{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"search-typing","type":"registry:component","title":"Search Typing","description":"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.","dependencies":["remotion","@remotion/google-fonts"],"docs":"Needs a Remotion project. If a frame renders black, the component is drawing on a transparent layer: put a background behind it, e.g. <AbsoluteFill style={{ background: \"#faf9f6\" }}><Component /></AbsoluteFill>. Pass mode=\"dark\" for dark frames.","registryDependencies":["https://kuchi.kalarislabs.com/r/kuchi-ui.json","https://kuchi.kalarislabs.com/r/caret.json","https://kuchi.kalarislabs.com/r/input.json"],"files":[{"path":"components/kuchi/search-typing.tsx","type":"registry:component","target":"components/kuchi/search-typing.tsx","content":"/*! Portions Copyright (c) 2026 Sri Nath (snap-cn). MIT License. See THIRD_PARTY_LICENSES. */\n\"use client\";\r\n\r\nimport { loadFont } from \"@remotion/google-fonts/Outfit\";\r\nimport {\r\n  type CSSProperties,\r\n  useEffect,\r\n  useLayoutEffect,\r\n  useRef,\r\n  useState,\r\n} from \"react\";\r\nimport {\r\n  continueRender,\r\n  delayRender,\r\n  Easing,\r\n  getRemotionEnvironment,\r\n  interpolate,\r\n  random,\r\n  useCurrentFrame,\r\n  useVideoConfig,\r\n} from \"remotion\";\r\nimport { Caret } from \"@/components/kuchi/caret\";\r\nimport { inputStyleContext } from \"@/components/kuchi/input\";\r\nimport {\r\n  mixOklch,\r\n  resolveFont,\r\n  type KuchiTheme,\r\n  useKuchiTheme,\r\n} from \"@/lib/kuchi-ui\";\r\n\r\n// Outfit Light. Identified by measuring the reference's letterforms against a\r\n// field of candidates: its stem/cap ratio is 0.121, and Outfit 300 is the only\r\n// geometric face that hits that exactly (stem 12px at a 99px cap, like for like).\r\n// Loaded through @remotion/google-fonts rather than a CSS variable so the Player,\r\n// the rendered mp4 and a user's own project all get the same face.\r\nconst { fontFamily: OUTFIT } = loadFont(\"normal\", {\r\n  weights: [\"300\", \"400\"],\r\n  subsets: [\"latin\"],\r\n});\r\n\r\n/**\r\n * `shadcn` — the field is a shadcn Input: a card surface, a hairline border, and a\r\n * shadow you have to look for. Correct on a light page, and the default.\r\n * `glass`  — the field the reference uses: a grey crown falling to white, lit from\r\n * below. It is measured, and it only works on a DARK backdrop; on a light one the\r\n * crown reads as dirt and the shadow as a smear.\r\n */\r\nexport type SearchTypingSurface = \"shadcn\" | \"glass\";\r\nexport type SearchTypingIcon = \"search\" | \"sparkle\" | \"none\";\r\n\r\nexport interface SearchTypingProps {\r\n  /** The sentence typed into the field, one character at a time. */\r\n  text: string;\r\n  /** Typing speed. 14 is what the reference does. */\r\n  charsPerSecond?: number;\r\n  /**\r\n   * Keystroke-interval variance, 0–1. 0 is a metronome. Deterministic — every\r\n   * interval is drawn from `seed`, never from a clock.\r\n   */\r\n  humanize?: number;\r\n  /** Beat after a space, as a multiple of the base keystroke interval. */\r\n  wordPause?: number;\r\n  /** Beat after `.,!?;:`, as a multiple of the base keystroke interval. */\r\n  punctuationPause?: number;\r\n  /** Seconds the field holds, parked and blinking, before the first keystroke. */\r\n  startDelay?: number;\r\n  /** Seconds the field takes to come forward once typing starts. */\r\n  dollyDuration?: number;\r\n  /** Seconds the field takes to slide from its left half to its right half. */\r\n  panDuration?: number;\r\n  /** Seconds the finished sentence holds at the front before the field goes back. */\r\n  holdAfter?: number;\r\n  /**\r\n   * Seconds the field takes to travel back. It goes back *further* than it\r\n   * started — far enough that the whole field lands in frame, which is the only\r\n   * moment you see it and the finished sentence at once. 0 parks it at the front.\r\n   */\r\n  recedeDuration?: number;\r\n  /**\r\n   * How much bigger the field gets as it comes forward. 1.25 is what the\r\n   * reference measures. `frontVisible × dolly` is how much of the field is in\r\n   * frame at rest — 0.56 × 1.25 = 0.70, roughly the two thirds you see there.\r\n   */\r\n  dolly?: number;\r\n  /**\r\n   * The field's height on screen, as a fraction of the frame's. This is the knob\r\n   * that makes the field look long and slim rather than chunky: it sets the\r\n   * height directly, and the text — which is a fixed ratio of it — comes with it.\r\n   */\r\n  fieldHeight?: number;\r\n  /**\r\n   * How much of the field is in frame once it has come forward. The field is\r\n   * padded out to whatever length that needs, so this and `fieldHeight` are\r\n   * independent — which they are not if the field is only as long as its\r\n   * sentence. (A real search field is longer than what you type into it.)\r\n   */\r\n  frontVisible?: number;\r\n  /** Margin, in px, between the field's visible cap and the edge of the frame. */\r\n  edgeInset?: number;\r\n  /** Blinks per second. 1 is the ~500ms-on/500ms-off of a real text field. */\r\n  caretBlinksPerSecond?: number;\r\n  caret?: boolean;\r\n  surface?: SearchTypingSurface;\r\n  /** Design-system token overrides, same shape every kuchi-ui component takes. */\r\n  theme?: Partial<KuchiTheme>;\r\n  mode?: \"light\" | \"dark\";\r\n  icon?: SearchTypingIcon;\r\n  fontFamily?: string;\r\n  fontWeight?: number;\r\n  /** Seeds `humanize`. Same seed, same performance, forever. */\r\n  seed?: string;\r\n  /** Global playback multiplier applied to the whole sequence. */\r\n  speed?: number;\r\n  className?: string;\r\n}\r\n\r\n/**\r\n * Every proportion below was measured off the reference frames, as a ratio of the\r\n * field's height (373px there). They are ratios and not pixels so the whole\r\n * component scales as one piece.\r\n *\r\n *   radius 103/373 = 0.276  — NOT a pill. A pill would be 0.500.\r\n *   cap height 99/373, and cap ≈ 0.70em, so fontSize/height = 0.379\r\n *   left cap → text start = 382/373\r\n *   left cap → icon = 133/373;  icon box 141/373;  icon stroke 12/373\r\n *   caret 9×162 /373\r\n */\r\nconst R = {\r\n  radius: 0.276,\r\n  fontSize: 0.379,\r\n  /**\r\n   * Left cap → the first glyph's INK. The text box has to start a touch earlier\r\n   * than that, because the \"W\" carries a side bearing: measured on the render,\r\n   * that bearing is 0.021 × the field's height.\r\n   */\r\n  textInk: 1.024,\r\n  sideBearing: 0.021,\r\n  iconInset: 0.357,\r\n  iconSize: 0.378,\r\n  /**\r\n   * The reference measures 0.62 here — but the reference's field is never seen\r\n   * whole, so nobody ever sees its right padding next to its left. This one IS\r\n   * seen whole at the end, and 0.62 against a 0.357 left inset does not read as\r\n   * padding, it reads as a word missing off the end of the sentence. Balanced\r\n   * against the left instead.\r\n   */\r\n  rightPad: 0.4,\r\n  caretWidth: 0.024,\r\n  caretHeight: 0.434,\r\n  /**\r\n   * Outfit sits its baseline 0.017 × height lower than the reference does once the\r\n   * line box is centred in the field. The line box's height cannot fix that — a\r\n   * centred line box puts the baseline at `H/2 − content/2 + ascent`, which is a\r\n   * property of the face, not of the leading — so the text is nudged instead.\r\n   */\r\n  baselineNudge: 0.017,\r\n} as const;\r\n\r\n/**\r\n * The field's height in layout px. Purely a unit — every other measurement is a\r\n * ratio of it, and the camera rescales the whole thing to whatever `fieldHeight`\r\n * asks for. Nothing on screen changes if you change it.\r\n */\r\nconst LAYOUT_UNIT = 240;\r\n\r\n/** Where the text box starts, so that its first glyph's ink lands on the mark. */\r\nconst R_TEXT_LEFT = R.textInk - R.sideBearing;\r\n/** Left cap → text, minus the icon and its inset, is the gap after the icon. */\r\nconst R_GAP = R_TEXT_LEFT - R.iconInset - R.iconSize;\r\n\r\nconst PUNCTUATION = /[.,!?;:]/;\r\n\r\n/** The push runs while the sentence is being typed, so it must not crawl at the end. */\r\nconst DOLLY_EASING = Easing.inOut(Easing.sin);\r\n/** The page across is a deliberate move: it leaves and arrives. */\r\nconst PAN_EASING = Easing.inOut(Easing.cubic);\r\nconst BACK_EASING = Easing.inOut(Easing.cubic);\r\n\r\nfunction clamp01(t: number): number {\r\n  return Math.max(0, Math.min(1, t));\r\n}\r\n\r\nfunction smoothstep(t: number): number {\r\n  const x = clamp01(t);\r\n  return x * x * (3 - 2 * x);\r\n}\r\n\r\nexport interface TypingScheduleOptions {\r\n  fps: number;\r\n  charsPerSecond: number;\r\n  humanize: number;\r\n  wordPause: number;\r\n  punctuationPause: number;\r\n  seed: string;\r\n}\r\n\r\n/**\r\n * The frame each prefix length lands on: `schedule[n]` is the frame at which the\r\n * field shows exactly `n` characters. Strictly monotonic by construction, which\r\n * is what {@link typedCount} relies on and why a scrub can never un-type a letter.\r\n */\r\nexport function buildTypingSchedule(\r\n  text: string,\r\n  opts: TypingScheduleOptions,\r\n): number[] {\r\n  const { fps, charsPerSecond, humanize, wordPause, punctuationPause, seed } =\r\n    opts;\r\n  const base = fps / Math.max(0.1, charsPerSecond);\r\n  const jitter = clamp01(humanize);\r\n\r\n  const schedule: number[] = [0];\r\n  let acc = 0;\r\n\r\n  for (let i = 0; i < text.length; i++) {\r\n    // The rest belongs to the gap *before* this character — a typist pauses after\r\n    // finishing a word, not before typing the space itself.\r\n    const prev = i > 0 ? text[i - 1] : \"\";\r\n    let interval = base;\r\n    if (prev === \" \") {\r\n      interval *= wordPause;\r\n    } else if (prev !== \"\" && PUNCTUATION.test(prev)) {\r\n      interval *= punctuationPause;\r\n    }\r\n    if (jitter > 0) {\r\n      const r = random(`${seed}-key-${i}`) * 2 - 1;\r\n      interval *= 1 + r * 0.35 * jitter;\r\n    }\r\n    acc += Math.max(0.001, interval);\r\n    schedule.push(acc);\r\n  }\r\n\r\n  return schedule;\r\n}\r\n\r\n/** Characters visible at `localFrame`, given a monotonic {@link buildTypingSchedule}. */\r\nexport function typedCount(localFrame: number, schedule: number[]): number {\r\n  if (localFrame <= 0 || schedule.length <= 1) return 0;\r\n  let n = 0;\r\n  while (n + 1 < schedule.length && schedule[n + 1] <= localFrame) n++;\r\n  return n;\r\n}\r\n\r\n/**\r\n * The character that starts the page across. Null when the sentence fits in the\r\n * first half and the field never has to move.\r\n *\r\n * `triggerX` is deliberately NOT the frame's edge. The pan eases in, so for its\r\n * first few frames the field has barely moved while the typing carries the caret\r\n * on rightwards — fire the pan *at* the edge and the caret spills over it before\r\n * the field catches up. {@link PAN_TRIGGER} keeps a couple of characters' worth of\r\n * lead in hand.\r\n */\r\nexport function pageTriggerIndex(\r\n  advances: number[],\r\n  textLeft: number,\r\n  scale: number,\r\n  triggerX: number,\r\n): number | null {\r\n  for (let n = 1; n < advances.length; n++) {\r\n    if ((textLeft + advances[n]) * scale > triggerX) return n;\r\n  }\r\n  return null;\r\n}\r\n\r\n/** Fraction of the page at which the caret hands the shot over to the pan. */\r\nconst PAN_TRIGGER = 0.88;\r\n\r\nexport interface CameraMarks {\r\n  typingStart: number;\r\n  dollyEnd: number;\r\n  panStart: number | null;\r\n  panEnd: number;\r\n  holdEnd: number;\r\n  recedeEnd: number;\r\n}\r\n\r\n/**\r\n * 0 = parked back, 1 = fully forward. Rises across the dolly and then holds — it\r\n * does NOT come back down. The retreat is a separate move to a separate depth.\r\n */\r\nexport function cameraPush(frame: number, m: CameraMarks): number {\r\n  if (m.dollyEnd <= m.typingStart) return frame >= m.typingStart ? 1 : 0;\r\n  return interpolate(frame, [m.typingStart, m.dollyEnd], [0, 1], {\r\n    extrapolateLeft: \"clamp\",\r\n    extrapolateRight: \"clamp\",\r\n    easing: DOLLY_EASING,\r\n  });\r\n}\r\n\r\n/**\r\n * 0 = still at the front, 1 = fully retreated.\r\n *\r\n * The field does not go back to where it started. It goes back **further** — far\r\n * enough that the whole of it lands in frame, which is the only moment in the clip\r\n * you ever see the complete field and the complete sentence at once. That is the\r\n * payoff, so it gets its own depth rather than reusing the resting one.\r\n */\r\nexport function cameraRetreat(frame: number, m: CameraMarks): number {\r\n  if (m.recedeEnd <= m.holdEnd) return 0;\r\n  return interpolate(frame, [m.holdEnd, m.recedeEnd], [0, 1], {\r\n    extrapolateLeft: \"clamp\",\r\n    extrapolateRight: \"clamp\",\r\n    easing: BACK_EASING,\r\n  });\r\n}\r\n\r\n/** 0 = the field's left half is in frame, 1 = its right half is. */\r\nexport function cameraPan(frame: number, m: CameraMarks): number {\r\n  if (m.panStart === null || m.panEnd <= m.panStart) return 0;\r\n  return interpolate(frame, [m.panStart, m.panEnd], [0, 1], {\r\n    extrapolateLeft: \"clamp\",\r\n    extrapolateRight: \"clamp\",\r\n    easing: PAN_EASING,\r\n  });\r\n}\r\n\r\nexport interface CaretBlinkOptions {\r\n  fps: number;\r\n  blinksPerSecond: number;\r\n  softness?: number;\r\n}\r\n\r\n/**\r\n * A real caret is a hard square wave. At 60fps a hard edge reads as a strobe, so\r\n * only the edges are eased — it still spends most of the cycle fully on and fully\r\n * off, it just doesn't snap between them.\r\n */\r\nexport function caretOpacity(frame: number, opts: CaretBlinkOptions): number {\r\n  const { fps, blinksPerSecond } = opts;\r\n  if (blinksPerSecond <= 0 || fps <= 0) return 1;\r\n\r\n  const period = fps / blinksPerSecond;\r\n  if (period <= 0) return 1;\r\n\r\n  const t = (((frame % period) + period) % period) / period;\r\n  const edge = Math.min(0.25, Math.max(0, opts.softness ?? 0.12));\r\n  if (edge === 0) return t < 0.5 ? 1 : 0;\r\n\r\n  if (t < 0.5 - edge) return 1;\r\n  if (t < 0.5) return 1 - smoothstep((t - (0.5 - edge)) / edge);\r\n  if (t < 1 - edge) return 0;\r\n  return smoothstep((t - (1 - edge)) / edge);\r\n}\r\n\r\n/**\r\n * The magnifier's INK fills the viewBox exactly — circle at (9, 9) r=7.98 with a\r\n * 2.03 stroke reaches x=0, and the round-capped handle reaches x=24. That matters:\r\n * `iconSize` is the reference's measured ink extent (0.378 × the field's height),\r\n * so if the glyph sat inside its box with air around it, it would come out\r\n * noticeably smaller than the reference's. It did, the first time.\r\n */\r\nfunction SearchGlyph({ size, color }: { size: number; color: string }) {\r\n  return (\r\n    <svg\r\n      width={size}\r\n      height={size}\r\n      viewBox=\"0 0 24 24\"\r\n      fill=\"none\"\r\n      aria-hidden=\"true\"\r\n      style={{ display: \"block\", flexShrink: 0, overflow: \"visible\" }}\r\n    >\r\n      <circle cx=\"9\" cy=\"9\" r=\"7.98\" stroke={color} strokeWidth={2.03} />\r\n      <path\r\n        d=\"M14.65 14.65 L22.98 22.98\"\r\n        stroke={color}\r\n        strokeWidth={2.03}\r\n        strokeLinecap=\"round\"\r\n      />\r\n    </svg>\r\n  );\r\n}\r\n\r\nfunction SparkleGlyph({ size, color }: { size: number; color: string }) {\r\n  return (\r\n    <svg\r\n      width={size}\r\n      height={size}\r\n      viewBox=\"0 0 24 24\"\r\n      fill=\"none\"\r\n      aria-hidden=\"true\"\r\n      style={{ display: \"block\", flexShrink: 0, overflow: \"visible\" }}\r\n    >\r\n      <path\r\n        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\"\r\n        fill={color}\r\n      />\r\n      <path\r\n        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\"\r\n        fill={color}\r\n        opacity={0.55}\r\n      />\r\n    </svg>\r\n  );\r\n}\r\n\r\ninterface Metrics {\r\n  /** Cumulative advance of each character prefix, in layout px. */\r\n  advances: number[];\r\n  /** Y of the text baseline, in layout px from the top of the field. */\r\n  baselineY: number;\r\n  /** The field's full width in layout px — it is sized by its own content. */\r\n  fieldWidth: number;\r\n}\r\n\r\n/**\r\n * A search field that is wider than the shot, on a dolly.\r\n *\r\n * Two thirds of it are in frame to begin with, parked back. On the first keystroke\r\n * it comes forward, and now only its left half fits. The sentence types across that\r\n * half; when the caret runs out of frame the field slides, and its right half comes\r\n * in. The sentence finishes there, and the field goes back.\r\n *\r\n * The two things that make scaled type look cheap are both handled:\r\n *\r\n *  1. **The scale pivots on the text baseline.** A browser gives glyph origins no\r\n *     vertical sub-pixel precision — it rounds them to a whole device pixel — so a\r\n *     scale that *moves* the baseline makes the type climb the pixel grid in whole\r\n *     pixel jumps. Pivot on it and its device Y never changes. Measured, not\r\n *     guessed from a line-height.\r\n *  2. **`text-rendering: geometricPrecision`.** Hinting bends each glyph so its\r\n *     stems land on whole pixels; under a sliding scale they re-snap every frame\r\n *     and the letterforms boil.\r\n *\r\n * The sentence itself is laid out once, in full, and revealed by clipping to a\r\n * measured character boundary — never re-sliced, so a settled glyph cannot re-kern\r\n * as the next one lands.\r\n */\r\nexport function SearchTyping({\r\n  text,\r\n  charsPerSecond = 14,\r\n  humanize = 0.35,\r\n  wordPause = 1.55,\r\n  punctuationPause = 2.2,\r\n  startDelay = 0.5,\r\n  dollyDuration = 0.8,\r\n  panDuration = 0.5,\r\n  holdAfter = 0.9,\r\n  recedeDuration = 1.2,\r\n  dolly = 1.25,\r\n  fieldHeight = 0.27,\r\n  frontVisible = 0.56,\r\n  edgeInset = 40,\r\n  caretBlinksPerSecond = 1,\r\n  caret = true,\r\n  surface = \"shadcn\",\r\n  theme,\r\n  mode,\r\n  icon = \"search\",\r\n  fontFamily,\r\n  fontWeight = 300,\r\n  seed = \"search-typing\",\r\n  speed = 1,\r\n  className,\r\n}: SearchTypingProps) {\r\n  const frame = useCurrentFrame();\r\n  const { fps, width: frameWidth, height: frameHeight } = useVideoConfig();\r\n  const t = useKuchiTheme(theme, mode);\r\n  const face = resolveFont(fontFamily ?? t.fontFamily) ?? OUTFIT;\r\n  // The very same context the shadcn <Input> paints itself from, so this field and\r\n  // that one cannot drift apart.\r\n  const ui = inputStyleContext(t);\r\n  const resolvedFontFamily = face;\r\n\r\n  const H = LAYOUT_UNIT;\r\n  const fontSize = R.fontSize * H;\r\n  const textLeft = R_TEXT_LEFT * H;\r\n  const caretWidth = Math.max(1, R.caretWidth * H);\r\n  const caretHeight = R.caretHeight * H;\r\n  const iconSize = R.iconSize * H;\r\n  const lineHeight = Math.round(fontSize * 1.4);\r\n\r\n  const schedule = buildTypingSchedule(text, {\r\n    fps,\r\n    charsPerSecond,\r\n    humanize,\r\n    wordPause,\r\n    punctuationPause,\r\n    seed,\r\n  });\r\n\r\n  const clock = frame * speed;\r\n  const typingStart = startDelay * fps;\r\n  const typingEnd = typingStart + (schedule[schedule.length - 1] ?? 0);\r\n  const count = typedCount(clock - typingStart, schedule);\r\n\r\n  // ---- measurement -------------------------------------------------------\r\n  const cameraRef = useRef<HTMLDivElement>(null);\r\n  const fieldRef = useRef<HTMLDivElement>(null);\r\n  const textRef = useRef<HTMLSpanElement>(null);\r\n  const baselineRef = useRef<HTMLSpanElement>(null);\r\n  const [metrics, setMetrics] = useState<Metrics | null>(null);\r\n  const [handle] = useState(() =>\r\n    delayRender(\"search-typing: measuring field, baseline and advances\"),\r\n  );\r\n\r\n  useLayoutEffect(() => {\r\n    const camEl = cameraRef.current;\r\n    const fieldEl = fieldRef.current;\r\n    const textEl = textRef.current;\r\n    const baseEl = baselineRef.current;\r\n    if (!camEl || !fieldEl || !textEl || !baseEl) return;\r\n    let cancelled = false;\r\n\r\n    const measure = () => {\r\n      if (cancelled) return;\r\n\r\n      // getBoundingClientRect reports *device* px, so it sees the camera's scale\r\n      // and would hand back every advance multiplied by it. Switch the transform\r\n      // off for the read; useLayoutEffect runs before paint, so it never shows.\r\n      const previous = camEl.style.transform;\r\n      camEl.style.transform = \"none\";\r\n\r\n      const fieldRect = fieldEl.getBoundingClientRect();\r\n      const baselineY = baseEl.getBoundingClientRect().top - fieldRect.top;\r\n      const fieldWidth = fieldRect.width;\r\n\r\n      const advances: number[] = [0];\r\n      const node = textEl.firstChild;\r\n      if (node) {\r\n        // The run is `white-space: pre` and holds the *whole* sentence, so a range\r\n        // ending on a space is never a trailing space — its advance is real. That\r\n        // is why the caret sits after the space in \"the most |\".\r\n        const range = document.createRange();\r\n        for (let i = 1; i <= text.length; i++) {\r\n          range.setStart(node, 0);\r\n          range.setEnd(node, i);\r\n          advances.push(range.getBoundingClientRect().width);\r\n        }\r\n      }\r\n\r\n      camEl.style.transform = previous;\r\n      setMetrics({ advances, baselineY, fieldWidth });\r\n    };\r\n\r\n    // Measuring against a fallback face measures the wrong face: the real one swaps\r\n    // in a frame later and every advance — and the baseline — moves.\r\n    if (typeof document !== \"undefined\" && document.fonts) {\r\n      if (document.fonts.status === \"loaded\") measure();\r\n      else void document.fonts.ready.then(measure);\r\n    } else {\r\n      measure();\r\n    }\r\n\r\n    return () => {\r\n      cancelled = true;\r\n    };\r\n  }, [text]);\r\n\r\n  useEffect(() => {\r\n    if (metrics) continueRender(handle);\r\n  }, [metrics, handle]);\r\n\r\n  // ---- camera ------------------------------------------------------------\r\n  const pageWidth = frameWidth - edgeInset * 2;\r\n\r\n  // The scale is set by the height we want the field to READ at, not by its\r\n  // length. Length is then whatever the framing needs — the field is padded out\r\n  // to it. Doing this the other way round is what made the field chunky: a field\r\n  // only as long as its sentence has a fixed aspect, so demanding that half of it\r\n  // fill the frame forces its height.\r\n  const frontScale = (fieldHeight * frameHeight) / H;\r\n  const restScale = frontScale / Math.max(1.0001, dolly);\r\n\r\n  // The field's natural length: icon + sentence + the reference's padding.\r\n  const naturalWidth = metrics?.fieldWidth ?? frameWidth * 2;\r\n  const framedWidth =\r\n    pageWidth / Math.max(0.05, Math.min(1, frontVisible)) / frontScale;\r\n  // Never shorter than its own content — a long sentence simply makes a long field.\r\n  const fieldWidth = Math.max(naturalWidth, framedWidth);\r\n\r\n  const advances = metrics?.advances ?? null;\r\n  const triggerIndex = advances\r\n    ? pageTriggerIndex(advances, textLeft, frontScale, pageWidth * PAN_TRIGGER)\r\n    : null;\r\n\r\n  const marks: CameraMarks = {\r\n    typingStart,\r\n    dollyEnd: typingStart + dollyDuration * fps,\r\n    panStart:\r\n      triggerIndex !== null ? typingStart + schedule[triggerIndex] : null,\r\n    panEnd:\r\n      triggerIndex !== null\r\n        ? typingStart + schedule[triggerIndex] + panDuration * fps\r\n        : 0,\r\n    holdEnd: typingEnd + holdAfter * fps,\r\n    recedeEnd: typingEnd + holdAfter * fps + recedeDuration * fps,\r\n  };\r\n\r\n  // The depth the field ends at: exactly wide enough that the whole of it fits the\r\n  // page. `edgeInset` then leaves it an equal margin on both sides, so anchoring\r\n  // the retreat on its right cap lands it centred without any special case.\r\n  const endScale = pageWidth / Math.max(1, fieldWidth);\r\n\r\n  const push = cameraPush(clock, marks);\r\n  const back = cameraRetreat(clock, marks);\r\n  const pan = cameraPan(clock, marks);\r\n\r\n  // rest → front on the push, then front → end on the retreat.\r\n  const forward = restScale + (frontScale - restScale) * push;\r\n  const scale = forward + (endScale - forward) * back;\r\n\r\n  // Left cap pinned to the frame's left edge, or right cap pinned to its right —\r\n  // the pan crossfades between the two anchors. Because the right anchor is a\r\n  // function of the *current* scale, the retreat pulls back around the right cap\r\n  // instead of dragging it off screen.\r\n  const leftAnchored = edgeInset;\r\n  const rightAnchored = frameWidth - edgeInset - fieldWidth * scale;\r\n  const originX = leftAnchored + (rightAnchored - leftAnchored) * pan;\r\n\r\n  const contentWidth = advances ? advances[advances.length - 1] : 0;\r\n  const caretX = advances ? advances[Math.min(count, advances.length - 1)] : 0;\r\n\r\n  const blinkOpacity = caretOpacity(clock, {\r\n    fps,\r\n    blinksPerSecond: caretBlinksPerSecond,\r\n  });\r\n\r\n  const baselineY = metrics?.baselineY ?? H / 2;\r\n\r\n  // NO drop shadow. shadcn defines a control with a hairline border, not with a\r\n  // shadow doing the border's job — and a shadow big enough to be seen under a\r\n  // field this size is a grey smear on a light page, which is what the first two\r\n  // attempts here looked like. The border carries it, and the field is clean.\r\n  // A hairline is specified for a ~40px control, where 1px is 2.5% of its height.\r\n  // This field is five times that, so the same hairline all but disappears — the\r\n  // border has to be stepped up, in weight AND in contrast, or the field has no\r\n  // edge at all. Both still come from the design system: the width is a ratio of\r\n  // the field's height, and the colour is the hairline walked toward the\r\n  // foreground with the system's own `mixOklch`.\r\n  const border = Math.max(1, 0.009 * H);\r\n  const borderColor = mixOklch(ui.idleBorder, t.foreground, 0.28);\r\n  const shadcnSurface = {\r\n    background: t.card,\r\n    border: `${border}px solid ${borderColor}`,\r\n    boxShadow: \"none\",\r\n  };\r\n  // The reference's field, measured: a grey crown falling to white, lit from below.\r\n  // It is lit for a DARK backdrop — on a light one the crown reads as an inner\r\n  // shadow and the drop shadow as a smear. Opt in only over something dark.\r\n  const glassSurface = {\r\n    background:\r\n      \"linear-gradient(180deg, #C4C4C4 0%, #D6D6D6 15%, #E7E7E7 30%, #F3F3F3 40%, #FDFDFD 50%, #FDFDFD 100%)\",\r\n    border: \"none\",\r\n    boxShadow: `0 ${0.045 * H}px ${0.12 * H}px rgba(9, 9, 12, 0.45)`,\r\n  };\r\n  const field = surface === \"glass\" ? glassSurface : shadcnSurface;\r\n  const inkColor = surface === \"glass\" ? \"#000000\" : ui.foreground;\r\n  const iconColor = surface === \"glass\" ? \"#000000\" : ui.mutedForeground;\r\n\r\n  const textStyle: CSSProperties = {\r\n    fontSize,\r\n    fontWeight,\r\n    fontFamily: resolvedFontFamily,\r\n    lineHeight: `${lineHeight}px`,\r\n    color: inkColor,\r\n    whiteSpace: \"pre\",\r\n    // A ligature is one glyph for two characters; clipping through one would paint\r\n    // half an \"fi\".\r\n    fontVariantLigatures: \"none\",\r\n    fontKerning: \"normal\",\r\n    // The type rides a moving scale, so hinting would re-snap every stem to the\r\n    // pixel grid each frame and the letterforms would boil.\r\n    textRendering: \"geometricPrecision\",\r\n    display: \"block\",\r\n  };\r\n\r\n  // box-shadow takes no percentages, so the offsets are computed from the field's\r\n  // height — the shadow then scales with the field instead of detaching from it.\r\n\r\n  return (\r\n    <div style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}>\r\n      <div\r\n        ref={cameraRef}\r\n        style={{\r\n          position: \"absolute\",\r\n          left: 0,\r\n          top: (frameHeight - H) / 2,\r\n          transform: `translateX(${originX}px) scale(${scale})`,\r\n          // x=0 is the field's left cap, so translateX places it exactly. y is the\r\n          // baseline, so the type cannot climb the pixel grid as the scale moves.\r\n          transformOrigin: `0px ${baselineY}px`,\r\n          ...(getRemotionEnvironment().isRendering\r\n            ? null\r\n            : { willChange: \"transform\" as const }),\r\n        }}\r\n      >\r\n        <div\r\n          ref={fieldRef}\r\n          className={className}\r\n          style={{\r\n            display: \"flex\",\r\n            alignItems: \"center\",\r\n            // max-content until the content has been measured; then the field is\r\n            // padded out to the length the framing wants.\r\n            width: metrics ? fieldWidth : \"max-content\",\r\n            height: H,\r\n            paddingLeft: R.iconInset * H,\r\n            paddingRight: R.rightPad * H,\r\n            gap: R_GAP * H,\r\n            borderRadius: R.radius * H,\r\n            background: field.background,\r\n            border: field.border,\r\n            boxShadow: field.boxShadow,\r\n            boxSizing: \"border-box\",\r\n          }}\r\n        >\r\n          {icon === \"search\" ? (\r\n            <SearchGlyph size={iconSize} color={iconColor} />\r\n          ) : null}\r\n          {icon === \"sparkle\" ? (\r\n            <SparkleGlyph size={iconSize} color={iconColor} />\r\n          ) : null}\r\n\r\n          <div\r\n            style={{\r\n              position: \"relative\",\r\n              height: lineHeight,\r\n              flexShrink: 0,\r\n              // Lifts the line onto the reference's baseline. The caret and the\r\n              // measured baselineY ride along with it, so the pivot stays true.\r\n              marginTop: -2 * R.baselineNudge * H,\r\n            }}\r\n          >\r\n            <span\r\n              ref={textRef}\r\n              style={{\r\n                ...textStyle,\r\n                // Negative vertical insets so ascenders and descenders are never\r\n                // clipped; only the right edge does any work.\r\n                clipPath: `inset(-0.5em ${Math.max(0, contentWidth - caretX)}px -0.5em 0)`,\r\n              }}\r\n            >\r\n              {text}\r\n              <span\r\n                ref={baselineRef}\r\n                style={{ display: \"inline-block\", width: 0, height: 0 }}\r\n              />\r\n            </span>\r\n\r\n            {caret ? (\r\n              <Caret\r\n                color={inkColor}\r\n                width={caretWidth}\r\n                height={caretHeight}\r\n                radius={0}\r\n                opacity={blinkOpacity}\r\n                style={{\r\n                  position: \"absolute\",\r\n                  left: caretX,\r\n                  top: (lineHeight - caretHeight) / 2,\r\n                }}\r\n              />\r\n            ) : null}\r\n          </div>\r\n        </div>\r\n      </div>\r\n    </div>\r\n  );\r\n}\r\n\r\nexport interface SearchTypingDurationOptions extends TypingScheduleOptions {\r\n  startDelay: number;\r\n  holdAfter: number;\r\n  recedeDuration: number;\r\n}\r\n\r\n/**\r\n * Frames the whole clip needs: the lead-in, the typing, the hold at the front and\r\n * the retreat. The camera's dolly and pan both finish inside the typing, so they\r\n * never extend it.\r\n */\r\nexport function searchTypingDuration(\r\n  text: string,\r\n  opts: SearchTypingDurationOptions,\r\n): number {\r\n  const schedule = buildTypingSchedule(text, opts);\r\n  const typing = schedule[schedule.length - 1] ?? 0;\r\n  return Math.ceil(\r\n    opts.startDelay * opts.fps +\r\n      typing +\r\n      opts.holdAfter * opts.fps +\r\n      opts.recedeDuration * opts.fps,\r\n  );\r\n}\r\n"}]}