{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"token-bucket","type":"registry:component","title":"Token bucket","description":"A rate limit you can watch refill: tokens grow at the real rate, requests take them, and waiting requests are carried off as each new one forms.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/token-bucket.tsx","type":"registry:component","content":"// Hairline UI · token-bucket · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { MATERIAL_RECESS } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * TOKEN BUCKET: a rate limit you can watch refill\n *\n *   tokens    what's left sits as a row of tokens packed against\n *             the outlet on the right of a recessed tube\n *   refill    the next token grows at the inlet on the left at\n *             the real refill rate, then slides down the tube to\n *             the back of the row; an empty tube is a long slide\n *   take      a request takes the front token: it slips out\n *             through the outlet and the row closes up\n *   waiting   when requests wait for a token, a queue opens past\n *             the outlet as hollow slots; each new token runs the\n *             length of the tube straight into the first slot and\n *             carries that request away\n *\n * The numbers are yours (a limiter's remaining count, e.g. the\n * X-RateLimit-Remaining header); between your updates the tube\n * refills on its own at refillPerSecond. Tokens and slots are\n * plain elements moved by transform; one frame loop grows the\n * next token and sleeps when the bucket is full or off screen.\n * ───────────────────────────────────────────────────────── */\n\nexport interface TokenBucketProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"title\"> {\n  /** How many tokens the bucket holds. */\n  limit: number;\n  /** Tokens left now, as your limiter reports them. */\n  remaining: number;\n  /** Tokens added a second. The tube refills on its own between your updates. */\n  refillPerSecond?: number;\n  /** Requests your client is holding until a token frees up. */\n  waiting?: number;\n  title?: string;\n  /** A second line under the title, e.g. the key or route. */\n  caption?: string;\n  /** What a token stands for. */\n  unit?: string;\n  /** Overrides the refill text, e.g. \"60 a minute\". */\n  rateLabel?: string;\n  /** The tokens' colour: any CSS colour. Defaults to --chart-1. */\n  color?: string;\n  locales?: string | string[];\n}\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst PAD = 8;\n/** The inlet chamber on the left, where the next token grows. */\nconst INLET = 22;\nconst RING = 10;\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () =>\n  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\nconst subscribeNothing = () => () => {};\nconst useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);\n\ninterface Engine {\n  track: HTMLDivElement | null;\n  gateEl: HTMLSpanElement | null;\n  ghosts: HTMLSpanElement | null;\n  instant: boolean;\n  w: number;\n  h: number;\n  slots: number;\n  per: number;\n  gate: number;\n  base: number;\n  t0: number;\n  rate: number;\n  limit: number;\n  stack: HTMLSpanElement[];\n  rings: HTMLSpanElement[];\n  forming: HTMLSpanElement | null;\n  serve: number;\n  ringsWanted: number;\n  frame: number;\n  visible: boolean;\n  arrived: boolean;\n  reduced: boolean;\n  shown: number;\n  onShown: (n: number) => void;\n}\n\nconst levelAt = (e: Engine, now: number) => (e.rate > 0 ? Math.min(e.limit, e.base + ((now - e.t0) / 1000) * e.rate) : Math.min(e.limit, e.base));\n\n/** Geometry for the bucket part of the tube (left of the gate). */\nfunction geometry(e: Engine) {\n  const left = INLET + 4;\n  const pitch = Math.max(1, (e.gate - PAD - left) / Math.max(1, e.slots));\n  const tw = Math.max(2, Math.min(5, pitch * 0.5));\n  const x = (i: number) => left + (e.slots - 1 - i) * pitch + (pitch - tw) / 2;\n  return { pitch, tw, x, left, inlet: (INLET - tw) / 2 + 1 };\n}\n\nfunction tokenEl(e: Engine, color: string, hollow = false) {\n  const el = document.createElement(\"span\");\n  const s = el.style;\n  s.position = \"absolute\";\n  s.left = \"0\";\n  s.top = \"8px\";\n  s.bottom = \"8px\";\n  s.borderRadius = \"999px\";\n  s.willChange = \"transform, opacity\";\n  if (hollow) {\n    s.width = `${RING - 4}px`;\n    s.boxShadow = \"inset 0 0 0 1.5px var(--tb-wait)\";\n  } else {\n    s.width = `${geometry(e).tw}px`;\n    s.background = color;\n    s.boxShadow = \"inset 0 1px 0 rgb(255 255 255 / 0.32)\";\n  }\n  e.track!.appendChild(el);\n  return el;\n}\n\nfunction place(el: HTMLElement, x: number, animate: boolean, ms = 320) {\n  el.style.transition = animate ? `transform ${ms}ms ${EASE}, opacity 200ms ${EASE}` : \"none\";\n  el.style.transform = `translateX(${x}px)`;\n}\n\nfunction leave(el: HTMLElement, x: number, reduced: boolean, after = 0) {\n  if (reduced) return el.remove();\n  el.style.transition = `transform 240ms ${EASE} ${after}ms, opacity 200ms ${EASE} ${after + 60}ms`;\n  el.style.transform = `translateX(${x}px) scaleY(0.6)`;\n  el.style.opacity = \"0\";\n  window.setTimeout(() => el.remove(), 320 + after);\n}\n\n/** Put every token and waiting slot where it belongs now. */\nfunction layout(e: Engine, animate: boolean) {\n  const g = geometry(e);\n  e.stack.forEach((el, i) => {\n    el.style.width = `${g.tw}px`;\n    place(el, g.x(i), animate && !e.reduced);\n  });\n  if (e.forming) {\n    e.forming.style.width = `${g.tw}px`;\n    e.forming.style.transform = `translateX(${g.inlet}px) scaleY(${e.forming.dataset.k ?? 0})`;\n  }\n  if (e.ghosts) {\n    // Empty slots: the same marks, faint, so the bucket's size reads at a glance.\n    const s = e.ghosts.style;\n    s.transition = animate && !e.reduced ? `width 420ms ${EASE}, background-size 420ms ${EASE}, background-position 420ms ${EASE}` : \"none\";\n    s.left = `${g.left}px`;\n    s.width = `${e.slots * g.pitch}px`;\n    s.backgroundSize = `${g.pitch}px 100%`;\n    s.backgroundPosition = `${(g.pitch - g.tw) / 2}px 0`;\n    s.backgroundImage = `linear-gradient(to right, var(--tb-ghost) 0 ${g.tw}px, transparent ${g.tw}px)`;\n  }\n  e.rings.forEach((el, i) => place(el, e.gate + 8 + i * RING, animate && !e.reduced));\n  if (e.gateEl) {\n    e.gateEl.style.transition = animate && !e.reduced ? `transform 420ms ${EASE}, opacity 300ms ${EASE}` : \"none\";\n    e.gateEl.style.transform = `translateX(${e.gate}px)`;\n    e.gateEl.style.opacity = e.gate < e.w ? \"1\" : \"0\";\n  }\n}\n\n/** How many slots the tube has at this width and limit, and how many tokens each stands for. */\nfunction fit(e: Engine) {\n  const cap = Math.max(8, Math.min(48, Math.floor((e.w - PAD * 2) / 8)));\n  const slots = Math.max(1, Math.min(Math.round(e.limit), cap));\n  if (slots !== e.slots && e.arrived) {\n    // A different number of slots: lay the row out again in place, without replaying its arrival.\n    e.stack.forEach((el) => el.remove());\n    e.stack = [];\n    e.instant = true;\n  }\n  e.slots = slots;\n  e.per = e.limit / e.slots;\n}\n\nfunction step(e: Engine, color: string, now: number) {\n  if (!e.track || !e.w) return false;\n  // The row arrives the first time it's seen.\n  if (!e.arrived && !e.visible) return false;\n  const g = geometry(e);\n  const level = levelAt(e, now);\n  const wanted = Math.min(e.slots, Math.floor(level / e.per + 1e-9));\n  // Tokens out: through the outlet, or along to the first waiting slot.\n  let out = 0;\n  while (e.stack.length > wanted) {\n    const el = e.stack.shift()!;\n    if (e.serve > 0 && e.rings.length) {\n      e.serve -= 1;\n      const ring = e.rings.shift()!;\n      const x = Number(ring.style.transform.match(/translateX\\(([-\\d.]+)px/)?.[1] ?? e.gate + 8);\n      place(el, x + (RING - 4 - g.tw) / 2, !e.reduced, 260);\n      ring.style.transition = `opacity 200ms ${EASE} 220ms, transform 240ms ${EASE} 220ms`;\n      ring.style.boxShadow = `inset 0 0 0 1.5px ${color}`;\n      ring.style.opacity = \"0\";\n      ring.style.transform += \" translateY(-6px)\";\n      window.setTimeout(() => ring.remove(), 480);\n      leave(el, x, e.reduced, 220);\n    } else leave(el, e.gate + 6 + out * 4, e.reduced, out * 30);\n    out += 1;\n  }\n  // Tokens in: they appear at the inlet and slide to the back of the row.\n  let added = 0;\n  while (e.stack.length < wanted) {\n    const el = tokenEl(e, color);\n    const i = e.stack.length;\n    e.stack.push(el);\n    if (e.reduced || e.instant) place(el, g.x(i), false);\n    else {\n      place(el, g.inlet, false);\n      el.style.opacity = e.arrived ? \"1\" : \"0\";\n      const delay = e.arrived ? added * 40 : i * 14;\n      void el.offsetWidth;\n      el.style.transition = `transform 340ms ${EASE} ${delay}ms, opacity 220ms ${EASE} ${delay}ms`;\n      el.style.transform = `translateX(${g.x(i)}px)`;\n      el.style.opacity = \"1\";\n    }\n    added += 1;\n  }\n  e.arrived = true;\n  e.instant = false;\n  if (out) layout(e, true);\n  // Waiting slots: hollow, past the gate, the oldest nearest it.\n  while (e.rings.length > e.ringsWanted) {\n    const el = e.rings.pop()!;\n    leave(el, e.w, e.reduced);\n  }\n  const room = Math.max(0, Math.floor((e.w - e.gate - 12) / RING));\n  while (e.rings.length < Math.min(e.ringsWanted, room)) {\n    const el = tokenEl(e, color, true);\n    const i = e.rings.length;\n    e.rings.push(el);\n    place(el, e.w, false);\n    el.style.opacity = \"0\";\n    void el.offsetWidth;\n    place(el, e.gate + 8 + i * RING, !e.reduced, 300);\n    el.style.opacity = \"1\";\n  }\n  // The next token grows at the inlet.\n  const full = wanted >= e.slots;\n  const k = full || e.rate <= 0 ? 0 : level / e.per - wanted;\n  if (e.forming) {\n    e.forming.dataset.k = String(k);\n    e.forming.style.width = `${g.tw}px`;\n    e.forming.style.transform = `translateX(${g.inlet}px) scaleY(${k})`;\n    e.forming.style.opacity = full ? \"0\" : \"0.5\";\n  }\n  // A serve only pairs with a token leaving in the same update.\n  e.serve = 0;\n  const shown = Math.floor(level + 1e-9);\n  if (shown !== e.shown) {\n    e.shown = shown;\n    e.onShown(shown);\n  }\n  return e.rate > 0 && !full && e.visible;\n}\n\nexport function TokenBucket({\n  limit,\n  remaining,\n  refillPerSecond = 0,\n  waiting = 0,\n  title = \"Rate limit\",\n  caption,\n  unit = \"requests\",\n  rateLabel,\n  color = \"color-mix(in oklab, var(--chart-1, var(--primary)) 74%, var(--foreground))\",\n  locales,\n  className = \"\",\n  ...props\n}: TokenBucketProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const [shown, setShown] = React.useState(() => Math.max(0, Math.floor(remaining)));\n  const trackRef = React.useRef<HTMLDivElement>(null);\n  const formingRef = React.useRef<HTMLSpanElement>(null);\n  const layerRef = React.useRef<HTMLDivElement>(null);\n  const gateRef = React.useRef<HTMLSpanElement>(null);\n  const ghostsRef = React.useRef<HTMLSpanElement>(null);\n  const colorRef = React.useRef(color);\n  const engine = React.useRef<Engine | null>(null);\n\n  const ensure = () => {\n    if (!engine.current)\n      engine.current = {\n        track: null,\n        gateEl: null,\n        ghosts: null,\n        instant: false,\n        w: 0,\n        h: 0,\n        slots: 1,\n        per: 1,\n        gate: 0,\n        base: remaining,\n        t0: 0,\n        rate: refillPerSecond,\n        limit,\n        stack: [],\n        rings: [],\n        forming: null,\n        serve: 0,\n        ringsWanted: 0,\n        frame: 0,\n        visible: false,\n        arrived: false,\n        reduced,\n        shown: -1,\n        onShown: setShown,\n      };\n    return engine.current;\n  };\n\n  const run = React.useCallback(() => {\n    const e = engine.current;\n    if (!e || e.frame) return;\n    const loop = (now: number) => {\n      e.frame = 0;\n      if (step(e, colorRef.current, now)) e.frame = requestAnimationFrame(loop);\n    };\n    e.frame = requestAnimationFrame(loop);\n  }, []);\n\n  // Size: the tube's width sets how many slots it has and where the gate sits.\n  React.useLayoutEffect(() => {\n    const e = ensure();\n    const track = trackRef.current;\n    if (!track) return;\n    e.track = layerRef.current;\n    e.gateEl = gateRef.current;\n    e.ghosts = ghostsRef.current;\n    e.forming = formingRef.current;\n    const measure = () => {\n      const w = track.clientWidth;\n      if (!w || w === e.w) return;\n      e.w = w;\n      e.gate = e.ringsWanted > 0 ? w - Math.min(96, Math.round(w * 0.26)) : w;\n      fit(e);\n      layout(e, false);\n      if (e.frame) cancelAnimationFrame(e.frame);\n      e.frame = 0;\n      step(e, colorRef.current, performance.now());\n      run();\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(track);\n    return () => observer.disconnect();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [run]);\n\n  // Your numbers: keep the part of a token already grown, so a request doesn't restart the refill.\n  React.useEffect(() => {\n    const e = ensure();\n    const now = performance.now();\n    const before = levelAt(e, now);\n    const grown = e.rate > 0 && Number.isInteger(remaining) && remaining < limit ? before - Math.floor(before) : 0;\n    if (e.limit !== limit) {\n      e.limit = limit;\n      if (e.w) {\n        fit(e);\n        layout(e, false);\n      }\n    }\n    e.rate = refillPerSecond;\n    e.reduced = reduced;\n    e.base = Math.max(0, Math.min(limit, remaining + grown));\n    e.t0 = now;\n    const ringsBefore = e.ringsWanted;\n    e.serve += Math.max(0, ringsBefore - waiting);\n    e.ringsWanted = Math.max(0, waiting);\n    // The queue opens past the outlet while anyone waits, and closes once it has emptied.\n    const gate = e.ringsWanted > 0 ? e.w - Math.min(96, Math.round(e.w * 0.26)) : e.w;\n    if (e.w && gate !== e.gate) {\n      const apply = () => {\n        e.gate = e.ringsWanted > 0 ? e.w - Math.min(96, Math.round(e.w * 0.26)) : e.w;\n        layout(e, true);\n      };\n      if (gate > e.gate) window.setTimeout(apply, 420);\n      else apply();\n    }\n    if (e.w) {\n      if (e.frame) cancelAnimationFrame(e.frame);\n      e.frame = 0;\n      step(e, colorRef.current, now);\n      run();\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [remaining, limit, refillPerSecond, waiting, reduced, run]);\n\n  React.useEffect(() => {\n    colorRef.current = color;\n    engine.current?.stack.forEach((el) => (el.style.background = color));\n  }, [color]);\n\n  // The refill runs only while the tube is on screen.\n  React.useEffect(() => {\n    const track = trackRef.current;\n    const e = ensure();\n    if (!track) return;\n    const observer = new IntersectionObserver(([entry]) => {\n      e.visible = entry.isIntersecting;\n      if (e.visible) {\n        step(e, colorRef.current, performance.now());\n        run();\n      }\n    });\n    observer.observe(track);\n    return () => {\n      observer.disconnect();\n      if (e.frame) cancelAnimationFrame(e.frame);\n      e.frame = 0;\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [run]);\n\n  React.useEffect(\n    () => () => {\n      const e = engine.current;\n      if (!e) return;\n      e.stack.forEach((el) => el.remove());\n      e.rings.forEach((el) => el.remove());\n      e.stack = [];\n      e.rings = [];\n    },\n    [],\n  );\n\n  const fmt = (v: number) => new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(v);\n  const rate = rateLabel ?? rateText(refillPerSecond, fmt);\n  const waits = waiting > 0;\n  const low = shown <= limit * 0.1;\n\n  return (\n    <div\n      className={`w-full rounded-[20px] bg-background shadow-[0_0_0_1px_var(--border)] [--tb-ghost:color-mix(in_oklab,var(--foreground)_9%,transparent)] [--tb-wait:var(--color-amber-600)] dark:[--tb-wait:var(--color-amber-400)] ${className}`}\n      {...props}\n    >\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 420px)\" }} />\n      <div className=\"@container w-full\">\n        <div className=\"p-4 @md:p-5\">\n          <div className=\"flex items-start justify-between gap-3\">\n            <div className=\"min-w-0\">\n              <p className=\"truncate text-[12.5px] text-muted-foreground\">{title}</p>\n              {caption && <p className=\"mt-0.5 truncate font-mono text-[11.5px] text-muted-foreground/80\">{caption}</p>}\n            </div>\n            <p className=\"relative h-5 shrink-0 text-right text-[12px] tabular-nums\">\n              <span\n                className=\"block whitespace-nowrap text-muted-foreground transition-[opacity,filter,translate] duration-300\"\n                style={{ opacity: waits ? 0 : 1, filter: waits && !reduced ? \"blur(3px)\" : \"none\", translate: waits && !reduced ? \"0 -4px\" : \"0 0\", transitionTimingFunction: EASE }}\n              >\n                {rate}\n              </span>\n              <span\n                aria-hidden={!waits}\n                className=\"absolute right-0 top-0 inline-flex items-center gap-1.5 whitespace-nowrap font-medium text-amber-600 transition-[opacity,filter,translate] duration-300 dark:text-amber-400\"\n                style={{ opacity: waits ? 1 : 0, filter: waits || reduced ? \"none\" : \"blur(3px)\", translate: waits || reduced ? \"0 0\" : \"0 4px\", transitionTimingFunction: EASE }}\n              >\n                <span className=\"size-1.5 rounded-full bg-current\" />\n                <NumberRoll value={Math.max(0, waiting)} locales={locale} duration={700} /> waiting\n              </span>\n            </p>\n          </div>\n\n          <div\n            role=\"meter\"\n            aria-label={title}\n            aria-valuemin={0}\n            aria-valuemax={limit}\n            aria-valuenow={shown}\n            aria-valuetext={`${fmt(shown)} of ${fmt(limit)} ${unit} left${rate ? `, refills ${rate}` : \"\"}${waits ? `, ${fmt(waiting)} waiting` : \"\"}`}\n            className=\"mt-2.5 flex items-baseline gap-1.5\"\n          >\n            <span className={`text-[26px] font-medium leading-none tracking-[-0.04em] tabular-nums @md:text-[30px] ${low ? \"text-amber-600 dark:text-amber-400\" : \"text-foreground\"}`} style={{ transition: \"color 300ms\" }}>\n              <NumberRoll value={shown} locales={locale} duration={600} />\n            </span>\n            <span className=\"text-[13px] text-muted-foreground tabular-nums\">\n              / {fmt(limit)} <TextMorph>{`${unit} left`}</TextMorph>\n            </span>\n          </div>\n\n          <div ref={trackRef} aria-hidden=\"true\" className={`relative mt-3.5 h-11 overflow-clip rounded-[12px] bg-muted ${MATERIAL_RECESS}`}>\n            {/* The gate: the outlet tokens leave by, and the queue's edge while requests wait. */}\n            <span ref={ghostsRef} className=\"absolute inset-y-2 bg-repeat-x\" />\n            {/* The inlet: the next token grows behind this line. */}\n            <span className=\"absolute inset-y-2 w-px bg-[color-mix(in_oklab,var(--foreground)_14%,var(--border))]\" style={{ left: 22 }} />\n            <span ref={gateRef} className=\"absolute left-0 inset-y-2 w-px bg-[color-mix(in_oklab,var(--foreground)_18%,var(--border))]\" style={{ opacity: 0 }} />\n            <span\n              ref={formingRef}\n              className=\"absolute left-0 top-2 bottom-2 origin-bottom rounded-full\"\n              style={{ background: color, opacity: 0, transform: \"scaleY(0)\" }}\n            />\n            <div ref={layerRef} className=\"absolute inset-0\" />\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nfunction rateText(perSecond: number, fmt: (v: number) => string) {\n  if (!(perSecond > 0)) return \"\";\n  const near = (v: number) => Math.abs(v - Math.round(v)) < 0.01;\n  if (perSecond >= 1 && near(perSecond)) return `+${fmt(Math.round(perSecond))} a second`;\n  if (near(perSecond * 60)) return `+${fmt(Math.round(perSecond * 60))} a minute`;\n  if (perSecond < 1 && near(1 / perSecond)) return `+1 every ${fmt(Math.round(1 / perSecond))}s`;\n  return `+${fmt(Math.round(perSecond * 3600))} an hour`;\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · token-bucket · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/token-bucket. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}