{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"word-flip","type":"registry:component","title":"Word Flip","description":"Word flip text rotator: a typewriter headline with a 3D rotating word. A headline types itself out, then one word cycles on a 3D flip — it sinks into an anticipation dip, throws up and away about its baseline under motion blur, and the next word unfurls from below.","dependencies":["remotion"],"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"],"files":[{"path":"components/kuchi/word-flip.tsx","type":"registry:component","target":"components/kuchi/word-flip.tsx","content":"/*! Portions Copyright (c) 2026 Sri Nath (snap-cn). MIT License. See THIRD_PARTY_LICENSES. */\n\"use client\";\r\n\r\nimport { useEffect, useRef, useState } from \"react\";\r\nimport {\r\n  AbsoluteFill,\r\n  continueRender,\r\n  delayRender,\r\n  Easing,\r\n  getRemotionEnvironment,\r\n  interpolate,\r\n  useCurrentFrame,\r\n  useVideoConfig,\r\n} from \"remotion\";\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/**\r\n * Pure animation math for WordFlip. Everything above the component is\r\n * frame-deterministic and side-effect free so it can be unit tested.\r\n */\r\n\r\nconst CLAMP = {\r\n  extrapolateLeft: \"clamp\",\r\n  extrapolateRight: \"clamp\",\r\n} as const;\r\n\r\n/** Frames each character takes, from a characters-per-second rate. */\r\nexport function framesPerChar(cps: number, fps: number): number {\r\n  return fps / Math.max(0.001, cps);\r\n}\r\n\r\n/**\r\n * A deterministic, seedless wobble on the keystroke clock so the typing does not\r\n * land on a metronome. Real typing is uneven; a perfectly regular cadence is the\r\n * single thing that gives a \"typewriter\" away. Bounded to ±`jitter` of one\r\n * keystroke and summed into an *offset*, never a per-key delay, so the sentence\r\n * still finishes exactly when the timeline says it does.\r\n */\r\nexport function keystrokeOffset(index: number, jitter: number): number {\r\n  if (jitter <= 0) return 0;\r\n  // Two incommensurable sines: no repeat over any realistic sentence, and no RNG,\r\n  // so a render and the Player agree frame for frame.\r\n  const w = Math.sin(index * 12.9898) * 0.6 + Math.sin(index * 4.1414) * 0.4;\r\n  return w * jitter;\r\n}\r\n\r\n/** Frame at which character `index` starts to appear. */\r\nexport function charStartFrame(\r\n  index: number,\r\n  opts: { typeStart: number; cps: number; fps: number; jitter: number },\r\n): number {\r\n  const per = framesPerChar(opts.cps, opts.fps);\r\n  return (\r\n    opts.typeStart + index * per + keystrokeOffset(index, opts.jitter) * per\r\n  );\r\n}\r\n\r\n/** Frame the last character has finished fading in. */\r\nexport function typingEndFrame(opts: {\r\n  charCount: number;\r\n  typeStart: number;\r\n  cps: number;\r\n  fps: number;\r\n  jitter: number;\r\n  charFade: number;\r\n}): number {\r\n  const last = charStartFrame(Math.max(0, opts.charCount - 1), opts);\r\n  return last + opts.charFade;\r\n}\r\n\r\n/** Frame at which flip `i` (0-based) begins. */\r\nexport function flipStartFrame(\r\n  i: number,\r\n  opts: { typingEnd: number; pause: number; cycle: number },\r\n): number {\r\n  return opts.typingEnd + opts.pause + i * opts.cycle;\r\n}\r\n\r\n/**\r\n * Which word is showing at `frame`, and how far into its flip we are.\r\n *\r\n * `index` is the word entering (or resting); `local` is frames since that\r\n * flip began, and is negative while the previous word is still holding.\r\n */\r\nexport function wordAt(\r\n  frame: number,\r\n  opts: {\r\n    typingEnd: number;\r\n    pause: number;\r\n    cycle: number;\r\n    wordCount: number;\r\n    loop: boolean;\r\n  },\r\n): { index: number; local: number } {\r\n  const first = flipStartFrame(0, opts);\r\n  if (frame < first) return { index: 0, local: frame - first };\r\n  const n = Math.floor((frame - first) / opts.cycle);\r\n  const local = frame - first - n * opts.cycle;\r\n  // Flip n takes word n -> word n+1. Before the first flip the slot is empty, so\r\n  // flip 0 brings in word 0 and flip k brings in word k.\r\n  const raw = n;\r\n  const index = opts.loop\r\n    ? ((raw % opts.wordCount) + opts.wordCount) % opts.wordCount\r\n    : Math.min(raw, opts.wordCount - 1);\r\n  return { index, local };\r\n}\r\n\r\n/**\r\n * The anticipation curve — `easeInBack`.\r\n *\r\n * The reference does not simply throw the word upward: it sinks it first. That\r\n * backswing is the whole reason the flip reads as weight rather than as a cut,\r\n * and it is not a separate keyframe — one `easeInBack` progress drives the\r\n * translate and the rotation together, so the dip and the throw are the same\r\n * gesture.\r\n *\r\n * Its minimum is `p = -0.100` at `t = 2s/(3(s+1)) = 0.42`. Measured off the\r\n * reference: the dip bottoms out at t = 0.44 of the exit and is worth 0.100 of\r\n * the exit travel. That is the curve, not an approximation of it.\r\n */\r\nexport function easeInBack(t: number, s = 1.70158): number {\r\n  return t * t * ((s + 1) * t - s);\r\n}\r\n\r\n/**\r\n * Speed of {@link easeInBack}, normalised so the fastest instant is 1.\r\n *\r\n * The blur is a shutter, not a ramp: it has to be proportional to how fast the\r\n * word is actually travelling. That is not a stylistic preference, it is what\r\n * the reference does — at the bottom of the dip the word has *stopped* to turn\r\n * around, and it is sharp there; three frames later it is flying and it is\r\n * smeared. A blur keyed to progress instead of speed blurs the word while it is\r\n * standing still, which reads as a focus pull.\r\n *\r\n * `easeInBack` is a cubic, so this is exact rather than sampled — and its\r\n * derivative is zero precisely at the turnaround, which is the frame that has\r\n * to be sharp.\r\n */\r\nexport function easeInBackSpeed(t: number, s = 1.70158): number {\r\n  const d = 3 * (s + 1) * t * t - 2 * s * t;\r\n  const peak = 3 * (s + 1) - 2 * s; // the derivative at t = 1, its maximum\r\n  return Math.abs(d) / peak;\r\n}\r\n\r\n/**\r\n * Uniform scale that makes every word fill the same slot.\r\n *\r\n * The reference pins *both* edges of the slot: all three words measure the same\r\n * width to within 1%, while their heights differ by up to 6% — exactly inversely\r\n * with their aspect ratios. That identity only closes if each word is scaled to\r\n * a common width, and it is what makes the layout incapable of reflowing: the\r\n * widest word sits at scale 1 and the rest are scaled up to meet it.\r\n */\r\nexport function fitScales(widths: number[]): number[] {\r\n  const max = Math.max(...widths, 1);\r\n  return widths.map((w) => (w > 0 ? max / w : 1));\r\n}\r\n\r\nexport interface WordFlipMotion {\r\n  /** How far the outgoing word is thrown, in em. Negative is up. */\r\n  exitY: number;\r\n  /** How far below rest the incoming word starts, in em. */\r\n  enterY: number;\r\n  /** Degrees the word rotates about the baseline. */\r\n  rotate: number;\r\n  /** Scale the outgoing word shrinks to (and the incoming grows from). */\r\n  scale: number;\r\n  /** Peak blur, in em. */\r\n  blur: number;\r\n}\r\n\r\n/** Measured off the reference. See the doc page for the derivation. */\r\nexport const DEFAULT_MOTION: WordFlipMotion = {\r\n  // 0.100 x 1.29em = 0.13em of backswing, which is the ~10px dip the reference\r\n  // shows at a 72px font.\r\n  exitY: -1.29,\r\n  enterY: 0.135,\r\n  rotate: 90,\r\n  scale: 0.98,\r\n  blur: 0.085,\r\n};\r\n\r\nexport interface WordFlipProps {\r\n  /** Text before the flipping word. */\r\n  prefix?: string;\r\n  /** The words that cycle through the slot. */\r\n  words?: string[];\r\n  /** Text after the flipping word. */\r\n  suffix?: string;\r\n  /**\r\n   * Gradient painted on the flipping word, left to right. Defaults to the\r\n   * design system's accent walked toward `destructive` — a two-stop ramp that\r\n   * follows a user's theme instead of a fixed blue-to-pink.\r\n   */\r\n  gradient?: string[];\r\n  /** Typing speed, characters per second. */\r\n  cps?: number;\r\n  /** Frames before the first keystroke. */\r\n  typeStart?: number;\r\n  /** Frames each character takes to fade in. */\r\n  charFade?: number;\r\n  /** Keystroke unevenness, as a fraction of one keystroke. 0 is a metronome. */\r\n  jitter?: number;\r\n  /** Frames held after the sentence completes, before the first flip. */\r\n  pause?: number;\r\n  /** Frames from one flip to the next. */\r\n  cycle?: number;\r\n  /** Frames the outgoing word takes to leave. */\r\n  exitDuration?: number;\r\n  /** Frames the incoming word takes to settle. */\r\n  enterDuration?: number;\r\n  /** Frames the incoming word starts before the outgoing one is gone. */\r\n  overlap?: number;\r\n  /** Show a blinking caret while typing. The reference has none. */\r\n  caret?: boolean;\r\n  /** Keep cycling the words forever. */\r\n  loop?: boolean;\r\n  motion?: Partial<WordFlipMotion>;\r\n  /** 3D depth, in em. Smaller is a stronger perspective. */\r\n  perspective?: number;\r\n  /**\r\n   * The typeface. Defaults to the shadcn app's sans stack. A headline is set in\r\n   * *your* type, and the inline style would otherwise beat anything a className\r\n   * could say — so this is the prop that lets it.\r\n   */\r\n  fontFamily?: string;\r\n  fontSize?: number;\r\n  /** Overrides the design system's `foreground`. */\r\n  color?: string;\r\n  fontWeight?: number;\r\n  speed?: number;\r\n  className?: string;\r\n  /** Design-system token overrides. */\r\n  theme?: Partial<KuchiTheme>;\r\n  mode?: \"light\" | \"dark\";\r\n}\r\n\r\nconst FONT_FAMILY = \"-apple-system, BlinkMacSystemFont, sans-serif\";\r\n\r\nexport function WordFlip({\r\n  prefix = \"Looking For A\",\r\n  words = [\"Modern\", \"Stunning\", \"Minimal\"],\r\n  suffix = \"Portfolio\",\r\n  gradient,\r\n  cps = 9,\r\n  typeStart = 4,\r\n  charFade = 6,\r\n  jitter = 0.18,\r\n  pause = 6,\r\n  cycle = 35,\r\n  exitDuration = 9,\r\n  enterDuration = 9,\r\n  overlap = 3,\r\n  caret = true,\r\n  loop = true,\r\n  motion,\r\n  perspective = 6.5,\r\n  fontFamily,\r\n  fontSize = 72,\r\n  color,\r\n  fontWeight = 600,\r\n  speed = 1,\r\n  className,\r\n  theme,\r\n  mode,\r\n}: WordFlipProps) {\r\n  const frame = useCurrentFrame() * speed;\r\n  const { fps } = useVideoConfig();\r\n  const t = useKuchiTheme(theme, mode);\r\n  const face = resolveFont(fontFamily ?? t.fontFamily) ?? FONT_FAMILY;\r\n  const fill = color ?? t.foreground;\r\n  const stops = gradient ?? [\r\n    t.primary,\r\n    mixOklch(t.primary, t.destructive, 0.45),\r\n  ];\r\n\r\n  const m = { ...DEFAULT_MOTION, ...motion };\r\n\r\n  // ---------------------------------------------------------------------------\r\n  // Measure. offsetWidth/offsetTop are *layout* px — untouched by the transforms\r\n  // we are about to apply, which is exactly why they are the right tool here. We\r\n  // measure in a hidden, untransformed copy so frame 0 can never be captured\r\n  // against the wrong geometry.\r\n  // ---------------------------------------------------------------------------\r\n  const [metrics, setMetrics] = useState<{\r\n    widths: number[];\r\n    baseline: number;\r\n  } | null>(null);\r\n  const [handle] = useState(() => delayRender(\"word-flip: measuring the slot\"));\r\n  const wordRefs = useRef<(HTMLSpanElement | null)[]>([]);\r\n  const baselineRef = useRef<HTMLSpanElement | null>(null);\r\n\r\n  useEffect(() => {\r\n    if (metrics) {\r\n      // Only now has the measured geometry actually rendered.\r\n      continueRender(handle);\r\n      return;\r\n    }\r\n    const widths = words.map((_, i) => wordRefs.current[i]?.offsetWidth ?? 0);\r\n    const baseline = baselineRef.current?.offsetTop ?? 0;\r\n    if (widths.length > 0 && widths.every((w) => w > 0)) {\r\n      setMetrics({ widths, baseline });\r\n    }\r\n  }, [metrics, handle, words]);\r\n\r\n  const scales = metrics ? fitScales(metrics.widths) : words.map(() => 1);\r\n  const slotWidth = metrics ? Math.max(...metrics.widths) : 0;\r\n  const baseline = metrics?.baseline ?? 0;\r\n\r\n  // ---------------------------------------------------------------------------\r\n  // Timeline\r\n  // ---------------------------------------------------------------------------\r\n  const chars = [...prefix, ...suffix];\r\n  const clock = { typeStart, cps, fps, jitter };\r\n  const typingEnd = typingEndFrame({\r\n    charCount: chars.length,\r\n    charFade,\r\n    ...clock,\r\n  });\r\n  const schedule = { typingEnd, pause, cycle, wordCount: words.length, loop };\r\n  const { index: entering, local } = wordAt(frame, schedule);\r\n\r\n  const em = fontSize;\r\n  const outgoing = entering - 1;\r\n  const enterStart = Math.max(0, exitDuration - overlap);\r\n\r\n  /** The word that is leaving: one `easeInBack` progress drives everything. */\r\n  const exitAt = (localFrame: number) => {\r\n    const t = interpolate(localFrame, [0, exitDuration], [0, 1], CLAMP);\r\n    const p = easeInBack(t);\r\n    return {\r\n      y: p * m.exitY * em,\r\n      rotate: p * m.rotate,\r\n      scale: 1 + p * (m.scale - 1),\r\n      blur: easeInBackSpeed(t) * m.blur * em,\r\n      // Solid until it is genuinely on its way out. A word that starts dimming on\r\n      // the backswing reads as a crossfade; the reference holds it almost fully\r\n      // opaque through the throw and then it is simply gone.\r\n      opacity: interpolate(t, [0.65, 1], [1, 0], CLAMP),\r\n    };\r\n  };\r\n\r\n  /** The word that is arriving. A moderate decelerate — see motion-quality. */\r\n  const enterAt = (localFrame: number) => {\r\n    const p = interpolate(\r\n      localFrame,\r\n      [enterStart, enterStart + enterDuration],\r\n      [0, 1],\r\n      { ...CLAMP, easing: Easing.bezier(0.2, 0.6, 0.35, 1) },\r\n    );\r\n    return {\r\n      y: (1 - p) * m.enterY * em,\r\n      rotate: -(1 - p) * m.rotate,\r\n      scale: m.scale + p * (1 - m.scale),\r\n      blur: (1 - p) * m.blur * em,\r\n      opacity: interpolate(p, [0, 0.45], [0, 1], CLAMP),\r\n    };\r\n  };\r\n\r\n  const stateFor = (i: number) => {\r\n    if (i === entering && local >= enterStart) return enterAt(local);\r\n    if (i === outgoing && local >= 0 && local <= exitDuration)\r\n      return exitAt(local);\r\n    if (i === entering && local > exitDuration) return enterAt(local);\r\n    // Resting: the word that is showing between flips.\r\n    if (i === entering && local < 0)\r\n      return { y: 0, rotate: 0, scale: 1, blur: 0, opacity: 0 };\r\n    return null;\r\n  };\r\n\r\n  // The Player is one continuous tab and hands the transform to the compositor;\r\n  // a render is spread across tabs that each inherit a stale raster, so the same\r\n  // hint there makes the type shimmer while standing still.\r\n  const gpu = getRemotionEnvironment().isRendering\r\n    ? null\r\n    : ({ willChange: \"transform, opacity, filter\" } as const);\r\n\r\n  const lineStyle: React.CSSProperties = {\r\n    fontSize,\r\n    fontWeight,\r\n    color: fill,\r\n    letterSpacing: \"-0.02em\",\r\n    fontFamily: face,\r\n    lineHeight: 1.25,\r\n    whiteSpace: \"pre\",\r\n    // Hinting re-snaps every stem to the pixel grid as the size slides, so the\r\n    // letterforms change shape frame to frame. Off, the type reads a shade\r\n    // softer — that is the absence of a lie, not blur.\r\n    textRendering: \"geometricPrecision\",\r\n  };\r\n\r\n  const wordPaint: React.CSSProperties = {\r\n    backgroundImage: `linear-gradient(90deg, ${stops.join(\", \")})`,\r\n    WebkitBackgroundClip: \"text\",\r\n    backgroundClip: \"text\",\r\n    color: \"transparent\",\r\n    WebkitTextFillColor: \"transparent\",\r\n  };\r\n\r\n  const typedChar = (ch: string, i: number) => {\r\n    const start = charStartFrame(i, clock);\r\n    return (\r\n      <span\r\n        key={i}\r\n        style={{\r\n          opacity: interpolate(frame, [start, start + charFade], [0, 1], CLAMP),\r\n        }}\r\n      >\r\n        {ch}\r\n      </span>\r\n    );\r\n  };\r\n\r\n  // The caret rides the typing head. It is a zero-width inline-block with an\r\n  // absolutely-positioned bar inside, so it cannot push a single glyph sideways\r\n  // — the sentence's geometry has to be identical with it and without it.\r\n  const caretIndex = Math.max(\r\n    0,\r\n    Math.min(\r\n      chars.length,\r\n      Math.floor((frame - typeStart) / framesPerChar(cps, fps)) + 1,\r\n    ),\r\n  );\r\n  const caretDone = frame > typingEnd + pause;\r\n  const showCaret = caret && !caretDone && frame >= typeStart;\r\n  const blink = Math.floor((frame / fps) * 2) % 2 === 0 ? 1 : 0.15;\r\n\r\n  const Caret = () => (\r\n    <span\r\n      style={{\r\n        position: \"relative\",\r\n        display: \"inline-block\",\r\n        width: 0,\r\n        verticalAlign: \"baseline\",\r\n      }}\r\n    >\r\n      <span\r\n        style={{\r\n          position: \"absolute\",\r\n          left: 0.06 * em,\r\n          bottom: 0,\r\n          width: Math.max(2, 0.055 * em),\r\n          height: 0.78 * em,\r\n          background: fill,\r\n          opacity: blink,\r\n          borderRadius: 1,\r\n        }}\r\n      />\r\n    </span>\r\n  );\r\n\r\n  const prefixChars = chars.slice(0, prefix.length);\r\n  const suffixChars = chars.slice(prefix.length);\r\n  const caretInPrefix = caretIndex <= prefix.length;\r\n\r\n  return (\r\n    <AbsoluteFill\r\n      className={className}\r\n      style={{\r\n        alignItems: \"center\",\r\n        justifyContent: \"center\",\r\n        background: \"transparent\",\r\n      }}\r\n    >\r\n      {/*\r\n        The measuring copy. Hidden, never transformed, laid out exactly like the\r\n        real line so the widths and the baseline it reports are the ones the real\r\n        line will use.\r\n      */}\r\n      {!metrics && (\r\n        <span\r\n          aria-hidden\r\n          style={{\r\n            ...lineStyle,\r\n            position: \"absolute\",\r\n            visibility: \"hidden\",\r\n            pointerEvents: \"none\",\r\n            left: 0,\r\n            top: 0,\r\n          }}\r\n        >\r\n          {words.map((w, i) => (\r\n            <span\r\n              // biome-ignore lint/suspicious/noArrayIndexKey: words are positional\r\n              key={i}\r\n              ref={(el) => {\r\n                wordRefs.current[i] = el;\r\n              }}\r\n              style={{ display: \"inline-block\" }}\r\n            >\r\n              {w}\r\n              {i === 0 && (\r\n                // A zero-sized inline-block sits ON the baseline, so its\r\n                // offsetTop *is* the baseline. Never derive it from line-height.\r\n                <span\r\n                  ref={baselineRef}\r\n                  style={{ display: \"inline-block\", width: 0, height: 0 }}\r\n                />\r\n              )}\r\n            </span>\r\n          ))}\r\n        </span>\r\n      )}\r\n\r\n      <span style={lineStyle}>\r\n        {prefixChars.map((ch, i) => typedChar(ch, i))}\r\n        {showCaret && caretInPrefix && <Caret />}{\" \"}\r\n        {/*\r\n          The slot. Fixed width from the widest word, so it is reserved before the\r\n          first word ever arrives — during typing it is the gap the reference\r\n          shows between \"A\" and \"Portfolio\" — and nothing downstream of it can\r\n          ever move.\r\n        */}\r\n        <span\r\n          style={{\r\n            display: \"inline-block\",\r\n            position: \"relative\",\r\n            width: slotWidth || undefined,\r\n            perspective: perspective * em,\r\n            verticalAlign: \"baseline\",\r\n          }}\r\n        >\r\n          {/* In-flow strut: gives the inline-block its height and its baseline. */}\r\n          <span aria-hidden style={{ visibility: \"hidden\" }}>\r\n            {words[0] ?? \"\"}\r\n          </span>\r\n\r\n          {words.map((w, i) => {\r\n            const s = stateFor(i);\r\n            if (!s || s.opacity <= 0) return null;\r\n            return (\r\n              <span\r\n                // biome-ignore lint/suspicious/noArrayIndexKey: words are positional\r\n                key={i}\r\n                style={{\r\n                  ...wordPaint,\r\n                  ...gpu,\r\n                  position: \"absolute\",\r\n                  left: 0,\r\n                  top: 0,\r\n                  display: \"inline-block\",\r\n                  width: \"max-content\",\r\n                  // Everything pivots on the baseline. Anywhere else and the\r\n                  // glyph origins climb the pixel grid in whole-pixel jumps as\r\n                  // the scale moves the baseline, and the word sits still, jumps,\r\n                  // sits still.\r\n                  transformOrigin: `0px ${baseline}px`,\r\n                  transform: `translateY(${s.y}px) rotateX(${s.rotate}deg) scale(${\r\n                    scales[i] * s.scale\r\n                  })`,\r\n                  opacity: s.opacity,\r\n                  filter: s.blur > 0.01 ? `blur(${s.blur}px)` : undefined,\r\n                }}\r\n              >\r\n                {w}\r\n              </span>\r\n            );\r\n          })}\r\n        </span>{\" \"}\r\n        {suffixChars.map((ch, i) => typedChar(ch, prefix.length + i))}\r\n        {showCaret && !caretInPrefix && <Caret />}\r\n      </span>\r\n    </AbsoluteFill>\r\n  );\r\n}\r\n"}]}