{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"threshold-line","type":"registry:component","title":"Threshold line","description":"Set an alert by seeing what it would have done: drag a line across the last 30 days and every day over it turns red while the count of alerts rolls.","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/threshold-line.tsx","type":"registry:component","content":"// Hairline UI · threshold-line · 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 { createSpring, projectInertia, releaseVelocity, rubberBand, samplePointer, type PointerSample, type Spring } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * THRESHOLD LINE: set an alert by seeing what it would have done\n *\n *   arrive    the bars grow out of the baseline one after another\n *   drag      grab the line (or its value tag) and pull it up or\n *             down. Every bar it passes under turns red from the line\n *             up, so the part of each day over the limit is the part\n *             that's red; a dot drops into the strip under each day\n *             that would have fired, and the count in the header rolls\n *   throw     let go mid-pull and the line keeps its speed, then\n *             settles on the nearest round step; past the ends it\n *             pulls back like a rubber band\n *   below     for \"alert when below\", days under the line turn red\n *             and the shortfall up to the line shows as a pale block\n *\n * The value tag is a slider: arrow keys move a step, Page keys ten.\n * The line is one spring; the bars are moved by transforms, so\n * dragging never lays out the page.\n * ───────────────────────────────────────────────────────── */\n\nexport interface ThresholdLineDatum {\n  key: string;\n  value: number;\n  /** For screen readers and the hidden table, e.g. \"Tue, 14 Oct\". */\n  label: string;\n  /** A tick under this bar, e.g. \"14 Oct\". */\n  tick?: string;\n}\n\nexport interface ThresholdLineProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"defaultValue\" | \"onChange\"> {\n  data: ThresholdLineDatum[];\n  value?: number;\n  defaultValue?: number;\n  /** Called as the line settles on a new step, while dragging too. */\n  onValueChange?: (value: number) => void;\n  /** Called once when a drag or key press is done. */\n  onValueCommit?: (value: number) => void;\n  /** Fire when a day is above the line, or below it. */\n  direction?: \"above\" | \"below\";\n  min?: number;\n  /** The top of the scale. Defaults to a round number over the data and the line. */\n  max?: number;\n  /** What the line snaps to. Defaults to a round step about a fortieth of the scale. */\n  step?: number;\n  /** Over the count, e.g. \"Alert when p95 latency is above the line\". */\n  title?: string;\n  /** Under the count, e.g. \"would have fired in the last 30 days\". */\n  period?: string;\n  /** Names the slider, e.g. \"p95 latency threshold\". */\n  label?: string;\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n}\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst THROW = \"cubic-bezier(0.34,1.36,0.64,1)\";\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\nconst HIT = 28; // the grab band around the line, in px\n/** The mark: 2px hairlines every 4px, counted up from the baseline. */\nconst RULE = \"repeating-linear-gradient(to top, #000 0 2px, transparent 2px 4px)\";\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);\n\n// Formatting waits for hydration: the server and the hydrating render share one fixed locale, then the visitor's takes over.\nconst subscribeNothing = () => () => {};\nconst useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);\n\nfunction niceMax(value: number) {\n  if (value <= 0) return 1;\n  const step = 10 ** Math.floor(Math.log10(value));\n  for (const m of [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (m * step >= value) return m * step;\n  return 10 * step;\n}\n\nfunction niceStep(range: number) {\n  const raw = range / 40;\n  const base = 10 ** Math.floor(Math.log10(raw || 1));\n  for (const m of [1, 2, 2.5, 5, 10]) if (m * base >= raw) return m * base;\n  return 10 * base;\n}\n\nconst snap = (v: number, step: number, min: number, max: number) => Math.min(max, Math.max(min, Math.round((v - min) / step) * step + min));\n\nexport function ThresholdLine({\n  data,\n  value,\n  defaultValue,\n  onValueChange,\n  onValueCommit,\n  direction = \"above\",\n  min = 0,\n  max,\n  step,\n  title = \"Alert when above the line\",\n  period = \"would have fired in this period\",\n  label = \"Threshold\",\n  format,\n  locales,\n  className = \"\",\n  ...props\n}: ThresholdLineProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const dataMax = Math.max(0, ...data.map((d) => d.value));\n  const [own, setOwn] = React.useState(() => defaultValue ?? Math.round(dataMax * 0.7));\n  const current = value ?? own;\n  const top = max ?? niceMax(Math.max(dataMax, current) * 1.08);\n  const unit = step ?? niceStep(top - min);\n  const above = direction === \"above\";\n\n  const [visible, setVisible] = React.useState(false);\n  const [firing, setFiring] = React.useState(() => data.map((d) => (above ? d.value > current : d.value < current)));\n  const [plotH, setPlotH] = React.useState(160);\n  const [dragging, setDragging] = React.useState(false);\n  const count = firing.filter(Boolean).length;\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const lineRef = React.useRef<HTMLDivElement>(null);\n  const tagTextRef = React.useRef<HTMLSpanElement>(null);\n  const fillRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const ghostRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const springRef = React.useRef<Spring | null>(null);\n  const live = React.useRef({ data, top, min, unit, plotH, above, shown: current, firingKey: \"\", format, locales: locale });\n  const callbacks = React.useRef({ onValueChange, onValueCommit, setOwn: (v: number) => setOwn(v), controlled: value !== undefined });\n  // Layout effect, declared first: the paints below must see this render's sizes.\n  React.useLayoutEffect(() => {\n    live.current = { ...live.current, data, top, min, unit, plotH, above, format, locales: locale };\n    callbacks.current = { onValueChange, onValueCommit, setOwn: (v: number) => setOwn(v), controlled: value !== undefined };\n  });\n\n  const fmt = React.useCallback((v: number) => new Intl.NumberFormat(locale, format).format(v), [format, locale]);\n\n  // One frame: the line, every bar's red part, and the count when the set of firing days changes.\n  const paint = React.useCallback(() => {\n    const s = springRef.current;\n    const L = live.current;\n    if (!s) return;\n    const v = s.get();\n    const h = L.plotH;\n    const px = ((v - L.min) / (L.top - L.min)) * h; // the line's height over the baseline\n    if (lineRef.current) lineRef.current.style.transform = `translate3d(0,${h - px}px,0)`;\n    let key = \"\";\n    for (let i = 0; i < L.data.length; i++) {\n      const fill = fillRefs.current[i];\n      if (fill) fill.style.transform = L.above ? `translate3d(0,${-px}px,0)` : \"none\";\n      const ghost = ghostRefs.current[i];\n      // The shortfall block hangs in a box from the plot's top down to the bar; its top edge rides the line.\n      if (ghost) ghost.style.transform = `translate3d(0,${Math.max(0, h - px)}px,0)`;\n      key += (L.above ? L.data[i].value > v : L.data[i].value < v) ? \"1\" : \"0\";\n    }\n    if (key !== L.firingKey) {\n      L.firingKey = key;\n      setFiring(Array.from(key, (c) => c === \"1\"));\n    }\n    const shown = snap(v, L.unit, L.min, L.top);\n    if (shown !== L.shown) {\n      L.shown = shown;\n      if (tagTextRef.current) tagTextRef.current.textContent = new Intl.NumberFormat(L.locales, L.format).format(shown);\n    }\n  }, []);\n\n  React.useEffect(() => {\n    const s = createSpring(live.current.shown, { stiffness: 520, damping: 44 }, paint, 0.0005 * (live.current.top - live.current.min));\n    springRef.current = s;\n    paint();\n    return () => {\n      s.stop();\n      springRef.current = null;\n    };\n  }, [paint]);\n\n  // A value from outside (controlled, or a key press) moves the line on its spring.\n  React.useEffect(() => {\n    const s = springRef.current;\n    if (!s || dragging) return;\n    if (reduced) s.jump(current);\n    else s.set(current);\n  }, [current, dragging, reduced]);\n\n  React.useLayoutEffect(() => paint(), [paint, plotH, top, data, direction]);\n\n  React.useLayoutEffect(() => {\n    const el = plotRef.current;\n    if (!el) return;\n    const measure = () => setPlotH((p) => (el.offsetHeight === p || !el.offsetHeight ? p : el.offsetHeight));\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (entry.isIntersecting) {\n          setVisible(true);\n          observer.disconnect();\n        }\n      },\n      { rootMargin: \"0px 0px -10% 0px\" },\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  const settle = React.useCallback((next: number, commit: boolean) => {\n    const C = callbacks.current;\n    if (!C.controlled) C.setOwn(next);\n    C.onValueChange?.(next);\n    if (commit) C.onValueCommit?.(next);\n  }, []);\n\n  // Dragging: the line follows the hand 1:1, rubber-bands past the ends, and is thrown onto a step when let go.\n  const drag = React.useRef<{ id: number; startY: number; startV: number; samples: PointerSample[]; lastStep: number } | null>(null);\n  const toValue = (dy: number) => {\n    const L = live.current;\n    return (dy / L.plotH) * (L.top - L.min);\n  };\n\n  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (e.button !== 0) return;\n    const s = springRef.current;\n    if (!s) return;\n    e.currentTarget.setPointerCapture(e.pointerId);\n    drag.current = { id: e.pointerId, startY: e.clientY, startV: s.get(), samples: [], lastStep: snap(s.get(), unit, min, top) };\n    samplePointer(drag.current.samples, e.clientY, e.timeStamp);\n    s.jump(s.get());\n    setDragging(true);\n  };\n\n  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    const s = springRef.current;\n    if (!d || d.id !== e.pointerId || !s) return;\n    samplePointer(d.samples, e.clientY, e.timeStamp);\n    const L = live.current;\n    let v = d.startV + toValue(d.startY - e.clientY);\n    // Past either end the line gives less and less, in pixels so it feels the same at any scale.\n    const span = L.top - L.min;\n    if (v > L.top) v = L.top + toValue(rubberBand(((v - L.top) / span) * L.plotH, L.plotH));\n    if (v < L.min) v = L.min - toValue(rubberBand(((L.min - v) / span) * L.plotH, L.plotH));\n    s.jump(v);\n    const stepped = snap(v, L.unit, L.min, L.top);\n    if (stepped !== d.lastStep) {\n      d.lastStep = stepped;\n      callbacks.current.onValueChange?.(stepped);\n    }\n  };\n\n  const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    const s = springRef.current;\n    if (!d || d.id !== e.pointerId || !s) return;\n    drag.current = null;\n    const L = live.current;\n    const vy = -releaseVelocity(d.samples, e.timeStamp); // px per ms, up is positive\n    const speed = toValue(vy * 1000); // value per second\n    const projected = projectInertia(s.get(), toValue(vy), 0.12);\n    const next = snap(projected, L.unit, L.min, L.top);\n    if (!reduced) {\n      // Keep the throw's speed, but never so much that it slams past the step it is headed for.\n      const room = Math.abs(next - s.get()) * 10;\n      s.push(Math.sign(speed) * Math.min(Math.abs(speed), room));\n      s.set(next);\n    } else s.jump(next);\n    setDragging(false);\n    settle(next, true);\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const moves: Record<string, number> = {\n      ArrowUp: current + unit,\n      ArrowRight: current + unit,\n      ArrowDown: current - unit,\n      ArrowLeft: current - unit,\n      PageUp: current + unit * 10,\n      PageDown: current - unit * 10,\n      Home: min,\n      End: top,\n    };\n    if (!(e.key in moves)) return;\n    e.preventDefault();\n    const next = snap(moves[e.key], unit, min, top);\n    if (next !== current) settle(next, true);\n  };\n\n  const slot = data.length ? 100 / data.length : 100;\n  const every = data.length > 16 ? Math.ceil(data.length / 7) : 1;\n  const compact = { ...format, notation: \"compact\" as const, minimumFractionDigits: 0, maximumFractionDigits: 1 };\n\n  return (\n    <div ref={rootRef} className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}>\n      {/* Its natural width where the parent sizes to its content (a centred flex column), without forcing it on narrow screens. */}\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 600px)\" }} />\n      <div className=\"@container w-full\">\n      <div className=\"p-4 @md:p-5 [--plot:150px] @md:[--plot:180px] [--gutter:30px] @md:[--gutter:38px]\">\n        <p className=\"text-[12px] text-muted-foreground @md:text-[13px]\">{title}</p>\n        <p className=\"mt-0.5 flex items-baseline gap-1.5 text-foreground\">\n          <span className=\"text-[22px] font-medium leading-tight tracking-[-0.03em] tabular-nums @md:text-[26px]\">\n            <NumberRoll value={count} duration={700} />\n          </span>\n          <span className=\"text-[13px] text-muted-foreground @md:text-[14px]\">\n            <TextMorph>{count === 1 ? \"alert\" : \"alerts\"}</TextMorph>\n          </span>\n        </p>\n        <p className=\"mt-0.5 text-[11.5px] text-muted-foreground @md:text-[12.5px]\">{period}</p>\n\n        <div className=\"relative mt-4 select-none @md:mt-5\" style={{ paddingLeft: \"var(--gutter)\" }}>\n          {/* The scale: top and middle as hairlines with rolling labels. */}\n          {[1, 0.5].map((f) => (\n            <div key={f} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-x-0\" style={{ top: (1 - f) * plotH }}>\n              <span\n                className=\"absolute left-0 top-0 -translate-y-1/2 text-right text-[10.5px] tabular-nums leading-none text-muted-foreground/80\"\n                style={{ width: \"calc(var(--gutter) - 8px)\" }}\n              >\n                <NumberRoll value={min + (top - min) * f} format={compact} locales={locale} duration={700} />\n              </span>\n              <div className=\"border-t border-dashed border-border\" style={{ marginLeft: \"var(--gutter)\" }} />\n            </div>\n          ))}\n\n          <div ref={plotRef} className=\"relative\" style={{ height: \"var(--plot)\" }}>\n            {data.map((d, i) => {\n              const barH = (Math.max(0, d.value - min) / (top - min)) * plotH;\n              const fires = firing[i];\n              return (\n                <div key={d.key} aria-hidden=\"true\" className=\"absolute inset-y-0\" style={{ left: `${i * slot}%`, width: `${slot}%` }}>\n                  {/* The mark: one column of 2px hairlines (a mask counted up from the baseline). Its empty part is the\n                      same lines, faint; the bar lights the lines it reaches, and the alert colour lights the lines past the line. */}\n                  <div className=\"absolute inset-y-0 left-1/2 w-[min(18px,64%)] -translate-x-1/2\" style={{ maskImage: RULE, WebkitMaskImage: RULE }}>\n                    <div className=\"absolute inset-0 bg-foreground/[0.07]\" />\n                    {/* Below mode: the shortfall from the bar's top up to the line. */}\n                    {!above && (\n                      <div className=\"absolute inset-x-0 top-0 overflow-clip\" style={{ bottom: barH, opacity: visible ? 1 : 0, transition: reduced ? \"none\" : `opacity 300ms ${EASE}` }}>\n                        <div\n                          ref={(el) => {\n                            ghostRefs.current[i] = el;\n                          }}\n                          className=\"absolute inset-x-0 top-0 bg-red-500/40 dark:bg-red-400/45\"\n                          style={{ height: plotH, willChange: \"transform\" }}\n                        />\n                      </div>\n                    )}\n                    <div\n                      className=\"absolute inset-x-0 bottom-0 overflow-clip bg-foreground/[0.3]\"\n                      style={{\n                        height: visible ? Math.max(2, barH) : 0,\n                        transition: reduced ? \"none\" : `height 640ms ${EASE} ${Math.min(i, 30) * 18}ms`,\n                      }}\n                    >\n                      <div\n                        ref={(el) => {\n                          fillRefs.current[i] = el;\n                        }}\n                        className=\"absolute inset-x-0 bottom-0 bg-red-500 dark:bg-red-400\"\n                        style={{\n                          height: above ? plotH : \"100%\",\n                          opacity: above || fires ? 1 : 0,\n                          willChange: above ? \"transform\" : undefined,\n                          transition: reduced || above ? \"none\" : `opacity 220ms ${EASE}`,\n                        }}\n                      />\n                    </div>\n                  </div>\n                </div>\n              );\n            })}\n\n            {/* The line and its tag: a wide grab band with a 1px line through it. */}\n            <div\n              ref={lineRef}\n              className=\"absolute inset-x-0 top-0 z-10\"\n              style={{ height: 0, willChange: \"transform\", marginLeft: \"calc(var(--gutter) * -1)\" }}\n            >\n              <div\n                onPointerDown={onPointerDown}\n                onPointerMove={onPointerMove}\n                onPointerUp={onPointerUp}\n                onPointerCancel={onPointerUp}\n                className=\"group absolute inset-x-0 flex cursor-ns-resize touch-none items-center\"\n                style={{ top: -HIT / 2, height: HIT }}\n              >\n                <div\n                  className={`h-px flex-1 transition-colors duration-300 ${count ? \"bg-red-500 dark:bg-red-400\" : \"bg-foreground/55\"}`}\n                  style={{ marginLeft: \"var(--gutter)\" }}\n                />\n                <div\n                  role=\"slider\"\n                  tabIndex={0}\n                  aria-label={label}\n                  aria-valuemin={min}\n                  aria-valuemax={top}\n                  aria-valuenow={current}\n                  aria-valuetext={`${fmt(current)}, ${count} ${count === 1 ? \"alert\" : \"alerts\"} ${period}`}\n                  aria-orientation=\"vertical\"\n                  onKeyDown={onKeyDown}\n                  className={`flex h-[24px] shrink-0 cursor-ns-resize items-center gap-1.5 rounded-full bg-background pl-2 pr-2.5 text-[11.5px] font-medium tabular-nums text-foreground shadow-[0_0_0_1px_var(--border)] transition-[scale,box-shadow] duration-200 ${FOCUS} ${\n                    dragging ? \"scale-[1.04]\" : \"group-hover:shadow-[0_0_0_1px_color-mix(in_oklab,var(--foreground)_30%,var(--border))]\"\n                  }`}\n                  style={{ transitionTimingFunction: EASE }}\n                >\n                  <svg viewBox=\"0 0 8 10\" aria-hidden=\"true\" className=\"h-2.5 w-2 text-muted-foreground\">\n                    <path d=\"M1 3.5 4 1l3 2.5M1 6.5 4 9l3-2.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n                  </svg>\n                  <span ref={tagTextRef}>{fmt(snap(current, unit, min, top))}</span>\n                </div>\n              </div>\n            </div>\n          </div>\n\n          <div aria-hidden=\"true\" className=\"border-t border-border\" />\n          {/* One dot under each day that would have fired. */}\n          <div aria-hidden=\"true\" className=\"relative h-3\">\n            {data.map((d, i) => (\n              <span\n                key={d.key}\n                className=\"absolute top-[5px] size-[5px] -translate-x-1/2 rounded-full bg-red-500 dark:bg-red-400\"\n                style={{\n                  left: `${(i + 0.5) * slot}%`,\n                  scale: firing[i] ? \"1\" : \"0\",\n                  opacity: firing[i] ? 1 : 0,\n                  transition: reduced ? \"none\" : `scale 320ms ${firing[i] ? THROW : EASE}, opacity 200ms ${EASE}`,\n                }}\n              />\n            ))}\n          </div>\n          <div aria-hidden=\"true\" className=\"relative h-4\">\n            {data.map((d, i) =>\n              d.tick && (data.length - 1 - i) % every === 0 ? (\n                <span\n                  key={d.key}\n                  className=\"absolute top-0 -translate-x-1/2 whitespace-nowrap text-[10.5px] leading-4 text-muted-foreground\"\n                  style={{ left: `clamp(14px, ${(i + 0.5) * slot}%, calc(100% - 14px))` }}\n                >\n                  {d.tick}\n                </span>\n              ) : null,\n            )}\n          </div>\n        </div>\n\n        <div className=\"sr-only\"><table>\n          <caption>\n            {label} at {fmt(current)}: {count} {count === 1 ? \"alert\" : \"alerts\"} {period}\n          </caption>\n          <tbody>\n            {data.map((d, i) => (\n              <tr key={d.key}>\n                <th scope=\"row\">{d.label}</th>\n                <td>\n                  {fmt(d.value)}\n                  {firing[i] ? \", would fire\" : \"\"}\n                </td>\n              </tr>\n            ))}\n          </tbody>\n        </table></div>\n      </div>\n      </div>\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · threshold-line · 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/threshold-line. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}