{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"story-text","type":"registry:component","title":"Story Text","description":"Story-style text types in word by word on rounded gradient highlight bubbles.","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>.","registryDependencies":["https://kuchi.kalarislabs.com/r/gradient-ground.json"],"files":[{"path":"components/kuchi/story-text.tsx","type":"registry:component","target":"components/kuchi/story-text.tsx","content":"/*! Portions Copyright (c) 2026 Remocn. MIT License. See THIRD_PARTY_LICENSES. */\n\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Figtree\";\nimport type React from \"react\";\nimport { useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport {\n  AbsoluteFill,\n  continueRender,\n  delayRender,\n  Easing,\n  interpolate,\n  interpolateColors,\n  spring,\n  useCurrentFrame,\n  useVideoConfig,\n} from \"remotion\";\nimport type { GradientParams } from \"@/lib/kuchi/gsh/gradient-engine\";\nimport { GshGround } from \"@/lib/kuchi/gsh/gsh-ground\";\nimport type { GshPresetId } from \"@/lib/kuchi/gsh/presets\";\n\nconst figtree = loadFont(\"normal\", {\n  weights: [\"400\"],\n  subsets: [\"latin\"],\n});\nconst sans = figtree.fontFamily;\n\nexport interface StoryTextProps {\n  text?: string;\n  measure?: number;\n  accent?: string;\n  /** Text and sticker color; overrides the theme ink. */\n  ink?: string;\n  /** Solid fill in place of the gradient ground; \"transparent\" drops it. */\n  background?: string;\n  /** Typeface for the text. Load it yourself; Figtree by default. */\n  fontFamily?: string;\n  /** Frames between words as they type in. */\n  stagger?: number;\n  /** Frames the typed text holds before the sticker styles cycle. */\n  hold?: number;\n  /** Size of the sticker, around the frame's center. */\n  scale?: number;\n  /** Frames to hold the first frame before anything moves. */\n  delay?: number;\n  theme?: \"dark\" | \"light\";\n  ground?: GshPresetId;\n  groundParams?: Partial<GradientParams>;\n  speed?: number;\n}\n\nconst FONT_PX = 100;\nconst TRACK = -0.012;\n\nconst ENTER = Easing.bezier(0.22, 1, 0.36, 1);\nconst MOVE = Easing.bezier(0.65, 0, 0.35, 1);\nconst EXIT = Easing.bezier(0.55, 0, 1, 0.45);\nconst CARD = { mass: 0.8, damping: 18, stiffness: 160 };\nconst CLAMP = {\n  extrapolateLeft: \"clamp\",\n  extrapolateRight: \"clamp\",\n} as const;\n\nconst LIGHT_GROUND: Partial<GradientParams> = {\n  kind: \"mist\",\n  background: \"#F2EDE6\",\n  colors: [\"#F58C3D\", \"#F7C79B\", \"#E889B5\", \"#FFF6EC\"],\n};\n\nconst THEMES = {\n  dark: {\n    ground: \"static-sunset\" as GshPresetId,\n    base: \"#0A0510\",\n    fg: \"#FBF7F1\",\n    sticker: \"#FBF7F1\",\n    onFill: \"#17120E\",\n    scrim: \"10,5,16\",\n    scrimA: 0.34,\n    lift: \"rgba(20,6,12,0.38)\",\n    shadow: \"0 2px 22px rgba(10,5,16,0.45)\",\n  },\n  light: {\n    ground: undefined,\n    base: \"#F2EDE6\",\n    fg: \"#17140F\",\n    sticker: \"#17140F\",\n    onFill: \"#FBF7F1\",\n    scrim: \"242,237,230\",\n    scrimA: 0.3,\n    lift: \"rgba(80,40,20,0.22)\",\n    shadow: \"0 1px 16px rgba(242,237,230,0.6)\",\n  },\n} as const;\n\nconst FIRST_WORD = -2;\nconst WORD_GAP = 5;\nconst WORD_IN = 8;\n\nfunction measureWith(_version: number, family: string) {\n  const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n  const cache: Record<string, number> = {};\n  return (s: string) => {\n    if (cache[s] === undefined) {\n      if (!ctx) return s.length * 0.52;\n      ctx.font = `400 ${FONT_PX}px \"${family}\"`;\n      cache[s] = ctx.measureText(s).width / FONT_PX + TRACK * [...s].length;\n    }\n    return cache[s];\n  };\n}\n\nfunction useMeasure(family: string) {\n  const [version, setVersion] = useState(0);\n  const [handle] = useState(() => delayRender(\"story-text: measuring\"));\n  const released = useRef(false);\n  useEffect(() => {\n    let live = true;\n    const bump = () => {\n      if (live) setVersion((v) => v + 1);\n    };\n    document.fonts.addEventListener(\"loadingdone\", bump);\n    Promise.all([\n      figtree.waitUntilDone(),\n      document.fonts.load(`400 ${FONT_PX}px \"${family}\"`),\n    ])\n      .catch(() => undefined)\n      .then(() => {\n        bump();\n        if (!released.current) {\n          released.current = true;\n          continueRender(handle);\n        }\n      });\n    return () => {\n      live = false;\n      document.fonts.removeEventListener(\"loadingdone\", bump);\n    };\n  }, [handle, family]);\n  return useMemo(() => measureWith(version, family), [version, family]);\n}\n\nfunction wrap(widths: number[], space: number, max: number) {\n  const lineOf: number[] = [];\n  let line = 0;\n  let run = 0;\n  widths.forEach((w, i) => {\n    const next = run === 0 ? w : run + space + w;\n    if (run > 0 && next > max) {\n      line += 1;\n      run = w;\n    } else {\n      run = next;\n    }\n    lineOf[i] = line;\n  });\n  return lineOf;\n}\n\ntype Pt = [number, number];\n\nfunction roundedPath(raw: Pt[], R: number) {\n  const pts: Pt[] = [];\n  for (const p of raw) {\n    const q = pts[pts.length - 1];\n    if (!q || Math.hypot(p[0] - q[0], p[1] - q[1]) > 0.25) pts.push(p);\n  }\n  if (pts.length > 1) {\n    const a = pts[0];\n    const b = pts[pts.length - 1];\n    if (Math.hypot(a[0] - b[0], a[1] - b[1]) <= 0.25) pts.pop();\n  }\n  const clean = pts.filter((v, i) => {\n    const p = pts[(i - 1 + pts.length) % pts.length];\n    const n = pts[(i + 1) % pts.length];\n    const cross = (v[0] - p[0]) * (n[1] - v[1]) - (v[1] - p[1]) * (n[0] - v[0]);\n    return Math.abs(cross) > 0.01;\n  });\n  const N = clean.length;\n  if (N < 3) return \"\";\n  let d = \"\";\n  clean.forEach((v, i) => {\n    const p = clean[(i - 1 + N) % N];\n    const n = clean[(i + 1) % N];\n    const lin = Math.hypot(v[0] - p[0], v[1] - p[1]);\n    const lout = Math.hypot(n[0] - v[0], n[1] - v[1]);\n    const r = Math.min(R, lin / 2, lout / 2);\n    const a: Pt = [\n      v[0] + ((p[0] - v[0]) / lin) * r,\n      v[1] + ((p[1] - v[1]) / lin) * r,\n    ];\n    const b: Pt = [\n      v[0] + ((n[0] - v[0]) / lout) * r,\n      v[1] + ((n[1] - v[1]) / lout) * r,\n    ];\n    const cross = (v[0] - p[0]) * (n[1] - v[1]) - (v[1] - p[1]) * (n[0] - v[0]);\n    const sweep = cross > 0 ? 1 : 0;\n    d += `${i === 0 ? \"M\" : \"L\"}${a[0].toFixed(2)} ${a[1].toFixed(2)}`;\n    d += `A${r.toFixed(2)} ${r.toFixed(2)} 0 0 ${sweep} ${b[0].toFixed(2)} ${b[1].toFixed(2)}`;\n  });\n  return `${d}Z`;\n}\n\n/** The foreground at `scale`, around the frame's center; nothing extra at 1. */\nfunction ScaleLayer({\n  scale,\n  children,\n}: {\n  scale: number;\n  children: React.ReactNode;\n}) {\n  if (scale === 1) return children;\n  return (\n    <AbsoluteFill style={{ transform: `scale(${scale})` }}>\n      {children}\n    </AbsoluteFill>\n  );\n}\n\nexport function StoryText({\n  text = \"okay, it’s live — the update you kept asking for is finally here\",\n  measure,\n  accent = \"#3B5BFD\",\n  ink: inkColor,\n  background,\n  fontFamily = sans,\n  stagger = WORD_GAP,\n  hold = 14,\n  scale = 1,\n  delay = 0,\n  theme = \"dark\",\n  ground,\n  groundParams,\n  speed = 1,\n}: StoryTextProps) {\n  const frame = Math.max(0, useCurrentFrame() - delay) * speed;\n  const { width: W, height: H, fps } = useVideoConfig();\n  const t = THEMES[theme];\n  const fg = inkColor ?? t.fg;\n  const uid = useId().replace(/[^a-zA-Z0-9_-]/g, \"\");\n  const width = useMeasure(fontFamily);\n  const tall = H > W;\n\n  const words = text.split(/\\s+/).filter(Boolean);\n  const F = tall ? W * 0.115 : H * 0.125;\n  const space = width(\" \");\n  const widths = words.map((w) => width(w));\n  const lineOf = wrap(\n    widths,\n    space,\n    (W * (measure ?? (tall ? 0.8 : 0.76))) / F,\n  );\n  const lineCount = (lineOf[lineOf.length - 1] ?? 0) + 1;\n\n  const lh = F * 1.34;\n  const padX = F * 0.36;\n  const R = lh * 0.3;\n\n  const appear = words.map((_, i) =>\n    Math.max(\n      0,\n      spring({\n        frame: frame - (FIRST_WORD + i * stagger),\n        fps,\n        config: CARD,\n      }),\n    ),\n  );\n  const ink = words.map((_, i) =>\n    interpolate(\n      frame,\n      [FIRST_WORD + i * stagger + 2, FIRST_WORD + i * stagger + WORD_IN + 1],\n      [0, 1],\n      { ...CLAMP, easing: ENTER },\n    ),\n  );\n  const typedEnd = FIRST_WORD + (words.length - 1) * stagger + WORD_IN;\n\n  const C1 = typedEnd + hold;\n  const C2 = C1 + 22;\n  const C3 = C2 + 22;\n  const step = (a: number) =>\n    interpolate(frame, [a, a + 9], [0, 1], { ...CLAMP, easing: MOVE });\n  const toOutline = step(C1);\n  const toNone = step(C2);\n  const toFill = step(C3);\n  const fillAmt = 1 - toOutline + toFill;\n  const strokeAmt = toOutline * (1 - toNone);\n  const textColor = interpolateColors(fillAmt, [0, 1], [fg, t.onFill]);\n  const pop = spring({ frame: frame - C3, fps, config: CARD });\n  const settle =\n    frame >= C3 ? 1 + 0.035 * Math.sin(Math.min(1, pop) * Math.PI) : 1;\n\n  const lines = Array.from({ length: lineCount }, (_, l) => {\n    const idx = words.map((_, i) => i).filter((i) => lineOf[i] === l);\n    let w = 0;\n    const xs: number[] = [];\n    idx.forEach((i, k) => {\n      const a = appear[i];\n      if (k > 0) w += space * F * Math.min(1, a * 3);\n      xs.push(w);\n      w += widths[i] * F * a;\n    });\n    const grow = appear[idx[0]] ?? 0;\n    return { idx, xs, w, grow };\n  });\n  const lineH = (g: number) => lh * MOVE(Math.min(1, g * 1.6));\n  const totalH = lines.reduce((acc, l) => acc + lineH(l.grow), 0);\n  let y = H / 2 - totalH / 2;\n  const geo = lines.map((l) => {\n    const h = lineH(l.grow);\n    const top = y;\n    y += h;\n    const half = l.w / 2 + padX * Math.min(1, l.grow * 2);\n    return { ...l, top, h, x0: W / 2 - half, x1: W / 2 + half };\n  });\n  const shown = geo.filter((g) => g.h > 0.5 && g.x1 - g.x0 > 1);\n\n  let path = \"\";\n  if (shown.length) {\n    const pts: Pt[] = [];\n    const first = shown[0];\n    pts.push([first.x0, first.top], [first.x1, first.top]);\n    shown.forEach((g, i) => {\n      pts.push([g.x1, g.top + g.h]);\n      const next = shown[i + 1];\n      if (next) pts.push([next.x1, g.top + g.h]);\n    });\n    const last = shown[shown.length - 1];\n    pts.push([last.x0, last.top + last.h]);\n    for (let i = shown.length - 1; i > 0; i--) {\n      pts.push([shown[i].x0, shown[i].top], [shown[i - 1].x0, shown[i].top]);\n    }\n    path = roundedPath(pts, R);\n  }\n\n  const caretOpacity = interpolate(\n    frame,\n    [typedEnd - 2, typedEnd + 6],\n    [1, 0],\n    { ...CLAMP, easing: EXIT },\n  );\n  let caret: { x: number; top: number } | null = null;\n  for (let i = words.length - 1; i >= 0; i--) {\n    if (appear[i] > 0 || i === 0) {\n      const g = geo[lineOf[i]];\n      const k = g.idx.indexOf(i);\n      caret = {\n        x: W / 2 - g.w / 2 + g.xs[k] + widths[i] * F * appear[i] + F * 0.06,\n        top: g.top + (lh - F * 1.08) / 2,\n      };\n      break;\n    }\n  }\n\n  const push = interpolate(frame, [0, 200], [1, 1.04], CLAMP);\n\n  return (\n    <AbsoluteFill\n      style={{\n        background: background === undefined ? t.base : undefined,\n        overflow: \"hidden\",\n      }}\n    >\n      {background === undefined ? (\n        <>\n          <AbsoluteFill style={{ transform: `scale(${push})` }}>\n            <GshGround\n              preset={groundParams ? undefined : (ground ?? t.ground)}\n              params={\n                groundParams ??\n                (theme === \"light\" && !ground ? LIGHT_GROUND : undefined)\n              }\n              timeOffset={theme === \"dark\" ? 3 : 5}\n              timeScale={0.4}\n            />\n          </AbsoluteFill>\n          <AbsoluteFill\n            style={{\n              background: `radial-gradient(${tall ? \"90% 40%\" : \"60% 55%\"} at 50% 50%, rgba(${t.scrim},${t.scrimA}) 0%, rgba(${t.scrim},0) 100%)`,\n            }}\n          />\n        </>\n      ) : (\n        <AbsoluteFill\n          style={{\n            background: background === \"transparent\" ? undefined : background,\n          }}\n        />\n      )}\n      <ScaleLayer scale={scale}>\n        <AbsoluteFill\n          style={{ transform: `scale(${settle})`, transformOrigin: \"50% 50%\" }}\n        >\n          <svg\n            width={W}\n            height={H}\n            style={{ position: \"absolute\", inset: 0, overflow: \"visible\" }}\n            aria-hidden\n          >\n            {path ? (\n              <>\n                <defs>\n                  <filter\n                    id={`${uid}-lift`}\n                    x=\"-20%\"\n                    y=\"-40%\"\n                    width=\"140%\"\n                    height=\"180%\"\n                  >\n                    <feDropShadow\n                      dx=\"0\"\n                      dy={F * 0.12}\n                      stdDeviation={F * 0.22}\n                      floodColor={t.lift}\n                    />\n                  </filter>\n                </defs>\n                <path\n                  d={path}\n                  fill={inkColor ?? t.sticker}\n                  opacity={Math.min(1, fillAmt)}\n                  filter={`url(#${uid}-lift)`}\n                />\n                <path\n                  d={path}\n                  fill=\"none\"\n                  stroke={fg}\n                  strokeWidth={Math.max(2, F * 0.045)}\n                  opacity={strokeAmt}\n                />\n              </>\n            ) : null}\n          </svg>\n          <div\n            style={{\n              position: \"absolute\",\n              inset: 0,\n              fontFamily,\n              fontWeight: 400,\n              clipPath: path ? `path(\"${path}\")` : undefined,\n            }}\n          >\n            {geo.map((g) =>\n              g.idx.map((i, k) => {\n                const a = ink[i];\n                if (a <= 0) return null;\n                return (\n                  <span\n                    key={`w-${i}`}\n                    style={{\n                      position: \"absolute\",\n                      left: W / 2 - g.w / 2 + g.xs[k],\n                      top: g.top + (lh - F) / 2,\n                      fontSize: F,\n                      lineHeight: 1,\n                      letterSpacing: `${TRACK}em`,\n                      whiteSpace: \"pre\",\n                      color: textColor,\n                      textShadow: fillAmt < 0.5 ? t.shadow : undefined,\n                      opacity: a,\n                      transformOrigin: \"0% 80%\",\n                      transform: `translateY(${(1 - a) * F * 0.22}px) scale(${0.9 + 0.1 * a})`,\n                    }}\n                  >\n                    {words[i]}\n                  </span>\n                );\n              }),\n            )}\n            {caret ? (\n              <div\n                style={{\n                  position: \"absolute\",\n                  left: caret.x,\n                  top: caret.top,\n                  width: Math.max(2, F * 0.045),\n                  height: F * 1.08,\n                  borderRadius: F,\n                  background: accent,\n                  opacity: caretOpacity,\n                }}\n              />\n            ) : null}\n          </div>\n        </AbsoluteFill>\n      </ScaleLayer>\n    </AbsoluteFill>\n  );\n}\n"}]}