{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "text-ribbon",
  "title": "Text ribbon",
  "description": "A phrase travelling along an arch or a wave, measured by pretext. Drag, keys and scroll take over; pause holds it in place.",
  "dependencies": [
    "@chenglou/pretext"
  ],
  "registryDependencies": [
    "https://thedirectors.agency/ui/r/0nlytype.json"
  ],
  "files": [
    {
      "path": "registry/0nlytype/ui/text-ribbon.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/** The attributes on <html> that can change the face. Not class: smooth scrolling toggles one on every scroll. */\nconst FACE = [\"data-pair\", \"data-scheme\", \"data-mode\", \"data-key\"]\n\n/** The arc: how much of a circle it spans, how far the guide sits inside the letters, and what the scroll moves. */\nconst ARC = { span: (100 * Math.PI) / 180, scroll: 0.6 }\nconst WAVE = { amp: 0.6 }\n/** How far under the letters the guide runs, in ems: the dots between the phrases ride on it. */\nconst GUIDE = 0.55\n\ntype TextRibbonProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n  /** The phrase. Plain text: pretext measures every letter. It is read once; the ribbon repeats it for the eye. */\n  children: string\n  /** arc: after WOVE, the phrase round an arch, largest and in ink at the crest, shrinking and fading toward the ends.\n   *  wave: the phrase rides a slow wave across the measure, fading in and out at the edges. */\n  variant?: \"arc\" | \"wave\"\n  /** The name of the handle you move it by. */\n  label?: string\n  autoplay?: boolean\n  defaultPaused?: boolean\n  pauseLabel?: string\n  playLabel?: string\n  \"data-force\"?: string\n}\n\ntype Glyph = { el: HTMLSpanElement; x: number; dot?: boolean }\n\n/**\n * A phrase laid along a curve by pretext, repeated round like a ribbon with a dot between each time.\n * It drifts until you take over: drag it along, press the arrow keys, scroll the page, or pause it.\n */\nfunction TextRibbon({ children: text, variant = \"arc\", label = \"Move the phrase\", autoplay = true, defaultPaused = false, pauseLabel = \"pause\", playLabel = \"play\", \"data-force\": force, className, ...props }: TextRibbonProps) {\n  const ref = React.useRef<HTMLDivElement>(null)\n  const stage = React.useRef<HTMLDivElement>(null)\n  const [paused, setPaused] = React.useState(defaultPaused)\n  const drift = React.useRef<(delta: number) => void>(() => {})\n\n  React.useEffect(() => {\n    const root = ref.current, box = stage.current\n    if (!root || !box) return\n    let cancelled = false\n    const off: (() => void)[] = []\n\n    ;(async () => {\n      let lib: typeof import(\"@chenglou/pretext\")\n      try {\n        lib = await import(\"@chenglou/pretext\")\n      } catch {\n        return // the plain phrase stays\n      }\n      if (cancelled) return\n      const graphemes = new Intl.Segmenter(undefined, { granularity: \"grapheme\" })\n      const layer = document.createElement(\"span\")\n      layer.className = \"ot-ribbon-letters\"\n      layer.setAttribute(\"aria-hidden\", \"true\")\n      const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\")\n      svg.setAttribute(\"class\", \"ot-ribbon-guide\")\n      svg.setAttribute(\"aria-hidden\", \"true\")\n      const path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\")\n      svg.append(path)\n      box.append(svg, layer)\n      off.push(() => {\n        svg.remove()\n        layer.remove()\n        delete root.dataset.laid\n      })\n\n      let glyphs: Glyph[] = []\n      let W = 0, size = 16, period = 1, length = 1\n      let hand = 0, scrolled = 0, carried = 0\n      const reduced = matchMedia(\"(prefers-reduced-motion: reduce)\")\n      const still = () => reduced.matches || !!force?.split(\" \").includes(\"reduced\")\n      let place: (s: number) => { x: number; y: number; a: number } = () => ({ x: 0, y: 0, a: 0 })\n\n      async function lay() {\n        if (cancelled || !box!.isConnected) return\n        const style = getComputedStyle(box!)\n        const font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`\n        await document.fonts.load(font, text)\n        if (cancelled || !box!.clientWidth) return\n        W = box!.clientWidth\n        size = parseFloat(style.fontSize)\n        const letterSpacing = parseFloat(style.letterSpacing) || 0\n        const measure = (s: string) => lib.measureNaturalWidth(lib.prepareWithSegments(s, font, { letterSpacing }))\n        const phrase = text.trim()\n        const gap = 2 * size\n        period = measure(phrase) + gap\n\n        let d: string\n        if (variant === \"wave\") {\n          const amp = WAVE.amp * size, k = (2 * Math.PI) / Math.max(12 * size, W / 2), mid = 1.1 * size + amp\n          length = W\n          place = (s) => ({ x: s, y: mid + amp * Math.sin(k * s), a: Math.atan(amp * k * Math.cos(k * s)) })\n          const g = GUIDE * size\n          d = Array.from({ length: 65 }, (_, i) => {\n            const s = (i / 64) * W\n            return `${i ? \"L\" : \"M\"}${s.toFixed(1)} ${(mid + g + amp * Math.sin(k * s)).toFixed(1)}`\n          }).join(\"\")\n        } else {\n          const chord = W - 1.5 * size, R = chord / (2 * Math.sin(ARC.span / 2)), cx = W / 2, cy = 1.2 * size + R\n          length = R * ARC.span\n          place = (s) => {\n            const a = -ARC.span / 2 + s / R\n            return { x: cx + R * Math.sin(a), y: cy - R * Math.cos(a), a }\n          }\n          const r = R - GUIDE * size, h = ARC.span / 2\n          d = `M${cx - r * Math.sin(h)} ${cy - r * Math.cos(h)}A${r} ${r} 0 0 1 ${cx + r * Math.sin(h)} ${cy - r * Math.cos(h)}`\n        }\n        svg.setAttribute(\"viewBox\", `0 0 ${W} ${box!.clientHeight}`)\n        path.setAttribute(\"d\", d)\n\n        // One period: the letters of the phrase at their centres, kerning included, then a dot in the gap. Enough\n        // periods to cover the curve with one to spare either side, so a letter is always coming in as one goes out.\n        const one: { g: string; x: number; dot?: boolean }[] = []\n        let before = \"\"\n        for (const { segment: g } of graphemes.segment(phrase)) {\n          if (g.trim()) {\n            const gw = measure(g)\n            one.push({ g, x: measure(before + g) - gw / 2 })\n          }\n          before += g\n        }\n        one.push({ g: \"\", x: period - gap / 2, dot: true })\n        const copies = Math.ceil(length / period) + 2\n        glyphs = []\n        for (let c = 0; c < copies; c++)\n          for (const p of one) {\n            const el = document.createElement(\"span\")\n            if (p.dot) el.className = \"ot-ribbon-dot\"\n            else el.textContent = p.g\n            glyphs.push({ el, x: (c - 1) * period + p.x, dot: p.dot })\n          }\n        layer.replaceChildren(...glyphs.map((g) => g.el))\n        root!.dataset.laid = \"\"\n        paint()\n      }\n\n      const turn = (v: number) => ((v % period) + period) % period\n      function paint() {\n        const shift = turn(hand + (still() ? 0 : scrolled + carried))\n        for (const g of glyphs) {\n          const s = g.x + shift - period\n          const d = Math.min(1, Math.abs(s - length / 2) / (length / 2))\n          if (s < -size || s > length + size) {\n            g.el.style.visibility = \"hidden\"\n            continue\n          }\n          const { x, y, a } = place(s)\n          // WOVE: the figures shrink and fade by their distance from the crest. On the wave, only the edges fade.\n          const k = variant === \"arc\" ? 1 - 0.42 * d * d : 1\n          g.el.style.visibility = \"\"\n          g.el.style.setProperty(\"--d\", d.toFixed(3))\n          g.el.style.transform = `translate(${x.toFixed(2)}px,${y.toFixed(2)}px) rotate(${a.toFixed(4)}rad) ${g.dot ? `translate(0,${GUIDE}em) scale(${k.toFixed(3)}) translate(-50%,-50%)` : `scale(${k.toFixed(3)}) translate(-50%,-0.8em)`}`\n        }\n        box!.setAttribute(\"aria-valuenow\", String(Math.round((turn(hand) / period) * 100)))\n      }\n      let frame = 0\n      const ask = () => {\n        cancelAnimationFrame(frame)\n        frame = requestAnimationFrame(paint)\n      }\n\n      await lay()\n      if (cancelled) return\n      drift.current = (delta) => {\n        carried = turn(carried + delta * size * 0.0006)\n        paint()\n      }\n\n      const resized = new ResizeObserver(() => box.clientWidth !== W && lay())\n      resized.observe(box)\n      // A change of pair or scheme on <html> can change the face: measure again.\n      const restyled = new MutationObserver(() => lay())\n      restyled.observe(document.documentElement, { attributeFilter: FACE })\n      off.push(() => {\n        cancelAnimationFrame(frame)\n        resized.disconnect()\n        restyled.disconnect()\n        drift.current = () => {}\n      })\n\n      // The hand: a drag along it moves it as far as the pointer goes, and it stays where it's let go.\n      let from: number | null = null\n      const down = (e: PointerEvent) => {\n        if (!e.isPrimary || e.button !== 0) return\n        from = e.clientX\n        box.setPointerCapture(e.pointerId)\n        root.dataset.held = \"\"\n      }\n      const move = (e: PointerEvent) => {\n        if (from === null) return\n        hand += e.clientX - from\n        from = e.clientX\n        ask()\n      }\n      const up = () => {\n        from = null\n        delete root.dataset.held\n      }\n      const key = (e: KeyboardEvent) => {\n        const step = e.key === \"ArrowRight\" ? size : e.key === \"ArrowLeft\" ? -size : e.key === \"PageDown\" ? 4 * size : e.key === \"PageUp\" ? -4 * size : 0\n        if (step) hand += step\n        else if (e.key === \"Home\") hand = 0\n        else return\n        e.preventDefault()\n        ask()\n      }\n      box.addEventListener(\"pointerdown\", down)\n      box.addEventListener(\"pointermove\", move)\n      box.addEventListener(\"pointerup\", up)\n      box.addEventListener(\"pointercancel\", up)\n      box.addEventListener(\"keydown\", key)\n      off.push(() => {\n        box.removeEventListener(\"pointerdown\", down)\n        box.removeEventListener(\"pointermove\", move)\n        box.removeEventListener(\"pointerup\", up)\n        box.removeEventListener(\"pointercancel\", up)\n        box.removeEventListener(\"keydown\", key)\n      })\n\n      // The page: scrolling moves it along as the ribbon rises through the view, read from the real layout in a frame\n      // asked for by the scroll event, which runs after a smooth scroller has moved the page. Not under reduced motion.\n      const onScroll = () => {\n        if (still()) return\n        cancelAnimationFrame(frame)\n        frame = requestAnimationFrame(() => {\n          scrolled = -box.getBoundingClientRect().top * ARC.scroll\n          paint()\n        })\n      }\n      const onMotion = () => {\n        cancelAnimationFrame(frame)\n        // Restore the still curve now; resuming reads any scrolling that happened while it was still.\n        scrolled = still() ? 0 : -box.getBoundingClientRect().top * ARC.scroll\n        paint()\n      }\n      onScroll()\n      reduced.addEventListener(\"change\", onMotion)\n      addEventListener(\"scroll\", onScroll, { passive: true })\n      off.push(() => {\n        reduced.removeEventListener(\"change\", onMotion)\n        removeEventListener(\"scroll\", onScroll)\n      })\n    })()\n\n    return () => {\n      cancelled = true\n      off.splice(0).forEach((f) => f())\n    }\n  }, [text, variant, force])\n\n  // A single clock for idle motion. Every pause cancels it; resuming starts with a fresh delta.\n  React.useEffect(() => {\n    const root = ref.current\n    if (!root) return\n    const reduced = matchMedia(\"(prefers-reduced-motion: reduce)\")\n    let running = false, held = false, visible = false, hovered = root.matches(\":hover\"), frame = 0, last = 0, timer = 0, restUntil = 0\n    const forced = force?.split(\" \") ?? []\n    const tick = (time: number) => {\n      if (!running) return\n      const delta = last ? Math.min(time - last, 64) : 0\n      last = time\n      drift.current(delta)\n      if (running) frame = requestAnimationFrame(tick)\n    }\n    const sync = () => {\n      running = false\n      cancelAnimationFrame(frame)\n      clearTimeout(timer)\n      last = 0\n      const resting = performance.now() < restUntil\n      const stopped = !autoplay || paused || reduced.matches || forced.includes(\"reduced\") || forced.includes(\"hover\") || forced.includes(\"focus\") || !visible || hovered || held || root.contains(document.activeElement) || document.hidden\n      root.dataset.autoplay = stopped || resting ? \"paused\" : \"playing\"\n      if (stopped) return\n      if (resting) timer = window.setTimeout(sync, restUntil - performance.now())\n      else { running = true; frame = requestAnimationFrame(tick) }\n    }\n    const rest = () => {\n      restUntil = performance.now() + 1600\n      sync()\n    }\n    const enter = (event: PointerEvent) => {\n      if (event.pointerType === \"touch\") return\n      hovered = true\n      rest()\n    }\n    const leave = () => { hovered = false; rest() }\n    const down = () => { held = true; rest() }\n    const up = () => { if (held) { held = false; rest() } }\n    const seen = new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; sync() })\n    seen.observe(root)\n    root.addEventListener(\"pointerenter\", enter)\n    root.addEventListener(\"pointerleave\", leave)\n    root.addEventListener(\"pointerdown\", down)\n    addEventListener(\"pointerup\", up)\n    addEventListener(\"pointercancel\", up)\n    root.addEventListener(\"keydown\", rest)\n    root.addEventListener(\"focusin\", rest)\n    root.addEventListener(\"focusout\", rest)\n    addEventListener(\"scroll\", rest, { passive: true })\n    document.addEventListener(\"visibilitychange\", sync)\n    reduced.addEventListener(\"change\", sync)\n    sync()\n    return () => {\n      running = false\n      cancelAnimationFrame(frame)\n      clearTimeout(timer)\n      seen.disconnect()\n      root.removeEventListener(\"pointerenter\", enter)\n      root.removeEventListener(\"pointerleave\", leave)\n      root.removeEventListener(\"pointerdown\", down)\n      removeEventListener(\"pointerup\", up)\n      removeEventListener(\"pointercancel\", up)\n      root.removeEventListener(\"keydown\", rest)\n      root.removeEventListener(\"focusin\", rest)\n      root.removeEventListener(\"focusout\", rest)\n      removeEventListener(\"scroll\", rest)\n      document.removeEventListener(\"visibilitychange\", sync)\n      reduced.removeEventListener(\"change\", sync)\n    }\n  }, [autoplay, paused, force])\n\n  return (\n    <div ref={ref} data-slot=\"text-ribbon\" data-force={force} data-variant={variant === \"arc\" ? undefined : variant} className={cn(\"ot-ribbon\", className)} {...props}>\n      <span className=\"ot-sr\">{text}</span>\n      <div\n        ref={stage}\n        className=\"ot-ribbon-stage\"\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={label}\n        aria-orientation=\"horizontal\"\n        aria-valuemin={0}\n        aria-valuemax={100}\n        aria-valuenow={0}\n        aria-keyshortcuts=\"ArrowLeft ArrowRight PageUp PageDown Home\"\n      >\n        <span className=\"ot-ribbon-plain\" aria-hidden=\"true\">{text}</span>\n      </div>\n      {autoplay && <button type=\"button\" className=\"ot-ribbon-pause\" onClick={() => setPaused((value) => !value)}>{paused ? playLabel : pauseLabel}</button>}\n    </div>\n  )\n}\n\nexport { TextRibbon, type TextRibbonProps }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/0nlytype/styles/text-ribbon.css",
      "content": "@layer components {\n  /* ── ot-ribbon ── a phrase laid along a curve by pretext, repeated round with a dot between each time. Each letter is placed\n     by the hook (translate, rotate, scale) and carries --d, its distance from the middle of the curve, 0 to 1; the colour and\n     the fade follow it here. The idle drift yields to the hand; pause, hover and focus hold the phrase in place. */\n  .ot-ribbon { container-type: inline-size; min-width: 0; }\n  .ot-ribbon-stage {\n    position: relative; overflow: clip; touch-action: pan-y; user-select: none; -webkit-user-select: none; cursor: grab;\n    /* The arch's height, reserved before it's laid, so nothing moves: its rise over the chord, plus a line above and below. */\n    block-size: calc(0.2331 * (100cqi - 1.5em) + 2.4em);\n    color: var(--ot-ink); line-height: 1; white-space: nowrap;\n  }\n  .ot-ribbon[data-held] .ot-ribbon-stage { cursor: grabbing; }\n  .ot-ribbon-stage:focus-visible { outline: var(--ot-stroke) solid var(--ot-accent); outline-offset: var(--ot-space-2); }\n  .ot-ribbon-plain { position: absolute; inset-inline: 0; top: 0.4em; text-align: center; }\n  .ot-ribbon[data-laid] .ot-ribbon-plain { visibility: hidden; }\n  .ot-ribbon-guide { position: absolute; inset: 0; inline-size: 100%; block-size: 100%; overflow: visible; pointer-events: none; }\n  .ot-ribbon-guide path { fill: none; stroke: var(--ot-rule); stroke-width: var(--ot-hairline); vector-effect: non-scaling-stroke; }\n  .ot-ribbon-letters > span {\n    position: absolute; left: 0; top: 0; transform-origin: 0 0; will-change: transform;\n    /* WOVE: ink at the crest, falling to pencil by distance, and gone at the very ends. */\n    color: color-mix(in oklab, var(--ot-ink) calc((1 - var(--d, 0)) * 100%), var(--ot-pencil));\n    opacity: calc(1 - max(0, var(--d, 0) - 0.72) / 0.28);\n  }\n  /* The dots between the phrases ride on the guide, in pencil, as WOVE's dots stand on its arc. */\n  .ot-ribbon-letters > .ot-ribbon-dot { inline-size: 0.16em; block-size: 0.16em; border-radius: 50%; background: var(--ot-pencil); }\n  /* The crest: one ink dot on the guide where the phrase stands tallest, the \"here\" of WOVE's dial. Focus inks it in the accent. */\n  .ot-ribbon[data-laid]:not([data-variant]) .ot-ribbon-stage::after {\n    content: \"\"; position: absolute; left: calc(50% - 0.11em); top: calc(1.75em - 0.11em); inline-size: 0.22em; block-size: 0.22em; border-radius: 50%;\n    background: var(--ot-ink); pointer-events: none;\n  }\n  .ot-ribbon-stage:focus-visible::after { background: var(--ot-accent); }\n\n  /* wave: the phrase rides a slow wave across the measure, like the script that sweeps through the capitals of\n     \"Less stress. More creativity.\"; every letter the same size, fading in and out at the edges only. */\n  .ot-ribbon[data-variant=\"wave\"] .ot-ribbon-stage { block-size: 3.4em; }\n  .ot-ribbon[data-variant=\"wave\"] .ot-ribbon-letters > span { color: var(--ot-ink); opacity: calc(1 - max(0, var(--d, 0) - 0.8) / 0.2); }\n  .ot-ribbon[data-variant=\"wave\"] .ot-ribbon-letters > .ot-ribbon-dot { background: var(--ot-pencil); }\n  @media (forced-colors: active) {\n    .ot-ribbon-letters > span { color: CanvasText; }\n    .ot-ribbon-letters > .ot-ribbon-dot, .ot-ribbon-stage::after { background: CanvasText; forced-color-adjust: none; }\n    .ot-ribbon-guide path { stroke: GrayText; }\n  }\n  /* The same small word beneath each autoplaying phrase; the parentheses are its only frame. */\n  .ot-ribbon-pause {\n    display: block; justify-self: start; appearance: none; border: 0; background: none; margin: 0; margin-block-start: var(--ot-space-3); padding: var(--ot-space-1) 0;\n    min-block-size: var(--ot-space-5); color: var(--ot-pencil); font: 400 var(--ot-pp) / var(--ot-pp-lh) var(--ot-voice); letter-spacing: 0; text-transform: none; cursor: pointer;\n  }\n  .ot-ribbon-pause::before { content: \"( \"; }\n  .ot-ribbon-pause::after { content: \" )\"; }\n  .ot-ribbon-pause:hover { color: var(--ot-ink); }\n  .ot-ribbon-pause:focus-visible { outline: var(--ot-stroke) solid var(--ot-accent); outline-offset: var(--ot-space-1); }\n  .ot-ribbon-pause:disabled { color: var(--ot-pencil); cursor: not-allowed; }\n  .ot-ribbon[data-force~=\"reduced\"] .ot-ribbon-pause { display: none; }\n  @media (prefers-reduced-motion: reduce) {\n    .ot-ribbon-pause { display: none; }\n  }\n  @media (forced-colors: active) {\n    .ot-ribbon-pause { color: ButtonText; }\n    .ot-ribbon-pause:focus-visible { outline-color: Highlight; }\n  }\n\n}\n",
      "type": "registry:file",
      "target": "styles/0nlytype/text-ribbon.css"
    }
  ],
  "css": {
    "@import \"../styles/0nlytype/text-ribbon.css\"": {}
  },
  "meta": {
    "movement": "II",
    "underneath": "hook",
    "contract": "ot-ribbon"
  },
  "type": "registry:ui"
}
