{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"metric-bento","type":"registry:block","title":"Metric bento","description":"A free three-cell analytics bento: headline numbers that roll when you change the period, a bar split into four channels and a live event list you can filter.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/metric-bento.tsx","type":"registry:component","content":"// Hairline UI · metric-bento · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { ArrowUpRight, Filter } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  useInteractionReducedMotion,\n} from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * METRIC BENTO — free MIT 3-cell asymmetric analytics bento\n *\n *   cell 1 (left 5 cols, lit hero)  headline KPI stack rolled\n *                                   across 7d / 30d / 90d / 12m\n *   cell 2 (top-right 7 cols)       4-channel interactive share\n *                                   strip in --chart-1..4\n *   cell 3 (bottom-right 7 cols)    filterable live event feed\n *                                   with crisp category chips\n * ───────────────────────────────────────────────────────── */\n\nexport interface MetricPeriod {\n  id: string;\n  label: string;\n  headlineValue: number;\n  headlinePrefix?: string;\n  headlineSuffix?: string;\n  headlineLabel: string;\n  changeLabel: string;\n  secondaryStats: [\n    { label: string; value: number; suffix?: string; decimals?: number },\n    { label: string; value: number; suffix?: string; decimals?: number },\n  ];\n  /** Percentage shares (sum = 100) aligned with `channels` */\n  channelShares: [number, number, number, number];\n}\n\nexport interface MetricChannel {\n  id: string;\n  name: string;\n  delta: string;\n}\n\nexport interface MetricFeedRow {\n  id: string;\n  category: string;\n  title: string;\n  meta: string;\n  value: string;\n}\n\nexport interface MetricBentoProps extends Omit<React.HTMLAttributes<HTMLElement>, \"title\"> {\n  eyebrow?: string;\n  heading?: string;\n  subheading?: string;\n  periods?: MetricPeriod[];\n  channelsTitle?: string;\n  channels?: [MetricChannel, MetricChannel, MetricChannel, MetricChannel];\n  feedTitle?: string;\n  feedRows?: MetricFeedRow[];\n  accent?: string;\n}\n\nconst DEFAULT_PERIODS: MetricPeriod[] = [\n  {\n    id: \"7d\",\n    label: \"7d\",\n    headlineValue: 18420,\n    headlineLabel: \"Unique visitors\",\n    changeLabel: \"+14.2% vs prior 7 days\",\n    secondaryStats: [\n      { label: \"Pages / visit\", value: 9.4, decimals: 1 },\n      { label: \"Avg. duration\", value: 274, suffix: \"s\" },\n    ],\n    channelShares: [44, 28, 17, 11],\n  },\n  {\n    id: \"30d\",\n    label: \"30d\",\n    headlineValue: 74910,\n    headlineLabel: \"Unique visitors\",\n    changeLabel: \"+28.6% vs prior 30 days\",\n    secondaryStats: [\n      { label: \"Pages / visit\", value: 10.2, decimals: 1 },\n      { label: \"Avg. duration\", value: 298, suffix: \"s\" },\n    ],\n    channelShares: [49, 24, 16, 11],\n  },\n  {\n    id: \"90d\",\n    label: \"90d\",\n    headlineValue: 214600,\n    headlineLabel: \"Unique visitors\",\n    changeLabel: \"+61.4% vs prior quarter\",\n    secondaryStats: [\n      { label: \"Pages / visit\", value: 9.8, decimals: 1 },\n      { label: \"Avg. duration\", value: 286, suffix: \"s\" },\n    ],\n    channelShares: [52, 22, 15, 11],\n  },\n  {\n    id: \"12m\",\n    label: \"12m\",\n    headlineValue: 812400,\n    headlineLabel: \"Unique visitors\",\n    changeLabel: \"+142% year over year\",\n    secondaryStats: [\n      { label: \"Pages / visit\", value: 10.6, decimals: 1 },\n      { label: \"Avg. duration\", value: 312, suffix: \"s\" },\n    ],\n    channelShares: [56, 20, 14, 10],\n  },\n];\n\nconst DEFAULT_CHANNELS: [MetricChannel, MetricChannel, MetricChannel, MetricChannel] = [\n  { id: \"search\", name: \"Organic search\", delta: \"+31%\" },\n  { id: \"direct\", name: \"Direct & CLI\", delta: \"+18%\" },\n  { id: \"social\", name: \"Social clips\", delta: \"+24%\" },\n  { id: \"referrals\", name: \"Directories\", delta: \"+12%\" },\n];\n\nconst DEFAULT_FEED: MetricFeedRow[] = [\n  { id: \"f1\", category: \"Install\", title: \"Desktop app installed\", meta: \"San Francisco · 14s ago\", value: \"macOS\" },\n  { id: \"f2\", category: \"Signup\", title: \"New workspace verified\", meta: \"Berlin · 1m ago\", value: \"Free plan\" },\n  { id: \"f3\", category: \"Checkout\", title: \"Team plan, yearly\", meta: \"Bengaluru · 3m ago\", value: \"$480\" },\n  { id: \"f4\", category: \"Install\", title: \"iPhone app installed\", meta: \"Tokyo · 4m ago\", value: \"iOS\" },\n  { id: \"f5\", category: \"Checkout\", title: \"Pro plan, monthly\", meta: \"London · 7m ago\", value: \"$24\" },\n];\n\nconst SERIES_VARS = [\n  \"var(--chart-1, var(--primary))\",\n  \"var(--chart-2, var(--primary))\",\n  \"var(--chart-3, var(--primary))\",\n  \"var(--chart-4, var(--primary))\",\n] as const;\n\nconst DECIMAL_FORMATS: Record<number, Intl.NumberFormatOptions> = {\n  0: { maximumFractionDigits: 0 },\n  1: { minimumFractionDigits: 1, maximumFractionDigits: 1 },\n  2: { minimumFractionDigits: 2, maximumFractionDigits: 2 },\n};\n\nexport function MetricBento({\n  eyebrow = \"Analytics overview\",\n  heading = \"Every number you check, on one surface.\",\n  subheading = \"Switch time windows to roll traffic and engagement figures, inspect channel share, and filter live product events.\",\n  periods = DEFAULT_PERIODS,\n  channelsTitle = \"Acquisition mix\",\n  channels = DEFAULT_CHANNELS,\n  feedTitle = \"Live product stream\",\n  feedRows = DEFAULT_FEED,\n  accent = \"var(--primary)\",\n  className = \"\",\n  ...rest\n}: MetricBentoProps) {\n  const reduced = useInteractionReducedMotion();\n  const [periodIdx, setPeriodIdx] = React.useState(1);\n  const [hoveredChannel, setHoveredChannel] = React.useState<number | null>(null);\n  const [category, setCategory] = React.useState(\"All\");\n\n  const period = periods[periodIdx] ?? periods[0];\n  const categories = React.useMemo(() => [\"All\", ...new Set(feedRows.map((r) => r.category))], [feedRows]);\n  const visibleRows = React.useMemo(\n    () => (category === \"All\" ? feedRows : feedRows.filter((r) => r.category === category)),\n    [feedRows, category],\n  );\n\n  // Gliding solid-grey period thumb\n  const tabRefs = React.useRef<(HTMLButtonElement | null)[]>([]);\n  const [thumb, setThumb] = React.useState({ left: 0, width: 0, ready: false });\n\n  React.useLayoutEffect(() => {\n    const btn = tabRefs.current[periodIdx];\n    if (!btn) return;\n    const left = btn.offsetLeft;\n    const width = btn.offsetWidth;\n    setThumb((prev) => (prev.left === left && prev.width === width && prev.ready ? prev : { left, width, ready: true }));\n  }, [periodIdx, periods.length]);\n\n  const litHeroStyle: React.CSSProperties = {\n    backgroundImage: `linear-gradient(160deg, color-mix(in oklab, ${accent} 10%, var(--card)) 0%, var(--card) 58%)`,\n    boxShadow: `inset 0 1px 0 color-mix(in oklab, ${accent} 24%, transparent)`,\n  };\n\n  return (\n    <section\n      data-natural-width\n      className={`grid w-full grid-cols-[minmax(0,1200px)] justify-center ${className}`}\n      {...rest}\n    >\n      <div className=\"@container w-full\">\n        <div className=\"rounded-[22px] border border-border bg-background p-4 @[36rem]:p-6 @[54rem]:p-8\">\n          {/* Header + gliding period switcher */}\n          <div className=\"flex flex-col gap-5 @[48rem]:flex-row @[48rem]:items-end @[48rem]:justify-between\">\n            <div className=\"max-w-xl\">\n              <p className=\"text-[13px] font-medium text-muted-foreground\">{eyebrow}</p>\n              <h2 className=\"mt-2 text-balance text-[26px] font-medium leading-[1.1] tracking-[-0.03em] text-foreground @[36rem]:text-[34px]\">\n                {heading}\n              </h2>\n              <p className=\"mt-2.5 text-pretty text-[14.5px] leading-relaxed text-muted-foreground\">{subheading}</p>\n            </div>\n\n            <div\n              role=\"tablist\"\n              aria-label=\"Reporting window\"\n              className=\"relative inline-flex w-fit max-w-full shrink-0 items-center overflow-x-auto rounded-full border border-border bg-card p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n            >\n              <span\n                aria-hidden=\"true\"\n                className=\"pointer-events-none absolute bottom-1 top-1 left-0 rounded-full bg-muted\"\n                style={{\n                  width: thumb.width,\n                  transform: `translateX(${thumb.left}px)`,\n                  opacity: thumb.ready ? 1 : 0,\n                  transition: thumb.ready && !reduced ? `transform 340ms ${EASE_OUT}, width 280ms ${EASE_OUT}` : \"none\",\n                }}\n              />\n              {periods.map((p, i) => {\n                const selected = i === periodIdx;\n                return (\n                  <button\n                    key={p.id}\n                    ref={(el) => {\n                      tabRefs.current[i] = el;\n                    }}\n                    type=\"button\"\n                    role=\"tab\"\n                    aria-selected={selected}\n                    onClick={() => setPeriodIdx(i)}\n                    className={`relative z-10 cursor-pointer whitespace-nowrap rounded-full px-3 py-1.5 text-[12.5px] font-medium tabular-nums transition-colors @[36rem]:text-[13px] ${INTERACTION_FOCUS} ${\n                      selected ? \"text-foreground\" : \"text-muted-foreground hover:text-foreground\"\n                    }`}\n                  >\n                    {p.label}\n                  </button>\n                );\n              })}\n            </div>\n          </div>\n\n          {/* 3-cell asymmetric hairline frame */}\n          <div className=\"mt-6 overflow-clip rounded-[18px] border border-border bg-card\">\n            <div className=\"grid grid-cols-1 divide-y divide-border @[52rem]:grid-cols-12 @[52rem]:divide-x @[52rem]:divide-y-0\">\n              {/* CELL 1 (5 cols): Lit hero KPI column */}\n              <div style={litHeroStyle} className=\"flex flex-col justify-between p-5 @[36rem]:p-6 @[52rem]:col-span-5\">\n                <div>\n                  <p className=\"text-[13px] font-medium text-muted-foreground\">{period.headlineLabel}</p>\n                  <div className=\"mt-3 flex items-baseline gap-1 text-[44px] font-medium leading-none tracking-[-0.045em] text-foreground tabular-nums @[36rem]:text-[52px]\">\n                    {period.headlinePrefix && <span className=\"text-[28px] font-normal text-muted-foreground\">{period.headlinePrefix}</span>}\n                    <NumberRoll value={period.headlineValue} />\n                    {period.headlineSuffix && <span className=\"text-[20px] font-normal text-muted-foreground\">{period.headlineSuffix}</span>}\n                  </div>\n                  <p className=\"mt-2.5 inline-flex items-center gap-1 text-[13px] font-medium text-emerald-600 dark:text-emerald-400\">\n                    <ArrowUpRight className=\"size-3.5\" aria-hidden=\"true\" />\n                    <span>{period.changeLabel}</span>\n                  </p>\n                </div>\n\n                {/* Hairline secondary stats strip */}\n                <dl className=\"mt-8 grid grid-cols-2 gap-4 border-t border-border pt-5\">\n                  {period.secondaryStats.map((stat) => (\n                    <div key={stat.label}>\n                      <dt className=\"text-[12px] text-muted-foreground\">{stat.label}</dt>\n                      <dd className=\"mt-1.5 flex items-baseline gap-0.5 text-[24px] font-medium leading-none tracking-[-0.03em] text-foreground tabular-nums\">\n                        <NumberRoll value={stat.value} format={DECIMAL_FORMATS[stat.decimals ?? 0] ?? DECIMAL_FORMATS[0]} />\n                        {stat.suffix && <span className=\"text-[13px] font-normal text-muted-foreground\">{stat.suffix}</span>}\n                      </dd>\n                    </div>\n                  ))}\n                </dl>\n              </div>\n\n              {/* RIGHT 7 COLS: Stacked Share Strip + Filterable Stream */}\n              <div className=\"flex min-w-0 flex-col divide-y divide-border @[52rem]:col-span-7\">\n                {/* CELL 2: Interactive 4-channel comparison strip */}\n                <div className=\"p-5 @[36rem]:p-6\">\n                  <div className=\"flex flex-wrap items-baseline justify-between gap-2\">\n                    <h3 className=\"text-[15.5px] font-medium tracking-[-0.015em] text-foreground\">{channelsTitle}</h3>\n                    <span className=\"text-[12.5px] tabular-nums text-muted-foreground\">\n                      {hoveredChannel !== null\n                        ? `${channels[hoveredChannel].name} · ${period.channelShares[hoveredChannel]}% (${channels[hoveredChannel].delta})`\n                        : \"Hover or focus a channel\"}\n                    </span>\n                  </div>\n\n                  {/* Proportional 4-segment stacked bar */}\n                  <div\n                    role=\"list\"\n                    aria-label=\"Channel share breakdown\"\n                    className=\"mt-4 flex h-3 w-full gap-1 overflow-clip rounded-full bg-muted/50\"\n                  >\n                    {channels.map((ch, i) => {\n                      const share = period.channelShares[i] ?? 25;\n                      const dimmed = hoveredChannel !== null && hoveredChannel !== i;\n                      return (\n                        <button\n                          key={ch.id}\n                          type=\"button\"\n                          aria-label={`${ch.name}: ${share}% (${ch.delta})`}\n                          onPointerEnter={() => setHoveredChannel(i)}\n                          onPointerLeave={() => setHoveredChannel(null)}\n                          onFocus={() => setHoveredChannel(i)}\n                          onBlur={() => setHoveredChannel(null)}\n                          className={`h-full cursor-pointer rounded-full transition-[width,opacity] duration-500 ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none ${INTERACTION_FOCUS}`}\n                          style={{\n                            width: `${share}%`,\n                            backgroundColor: SERIES_VARS[i],\n                            opacity: dimmed ? 0.28 : 1,\n                          }}\n                        />\n                      );\n                    })}\n                  </div>\n\n                  {/* Aligned channel legend */}\n                  <div className=\"mt-4 grid grid-cols-2 gap-2.5 @[36rem]:grid-cols-4\">\n                    {channels.map((ch, i) => {\n                      const share = period.channelShares[i] ?? 25;\n                      const focused = hoveredChannel === i;\n                      return (\n                        <button\n                          key={ch.id}\n                          type=\"button\"\n                          onPointerEnter={() => setHoveredChannel(i)}\n                          onPointerLeave={() => setHoveredChannel(null)}\n                          onFocus={() => setHoveredChannel(i)}\n                          onBlur={() => setHoveredChannel(null)}\n                          className={`flex min-w-0 cursor-pointer flex-col rounded-[10px] px-2.5 py-2 text-left transition-colors ${INTERACTION_FOCUS} ${\n                            focused ? \"bg-muted\" : \"hover:bg-muted/60\"\n                          }`}\n                        >\n                          <span className=\"flex items-center gap-1.5 text-[12px] text-muted-foreground\">\n                            <span aria-hidden=\"true\" className=\"h-[2px] w-2.5 rounded-full\" style={{ backgroundColor: SERIES_VARS[i] }} />\n                            <span className=\"truncate\">{ch.name}</span>\n                          </span>\n                          <span className=\"mt-1 flex items-baseline gap-1.5 tabular-nums\">\n                            <span className=\"whitespace-nowrap text-[16px] font-medium text-foreground\">\n                              <NumberRoll value={share} />%\n                            </span>\n                            <span className=\"text-[11.5px] text-emerald-600 dark:text-emerald-400\">{ch.delta}</span>\n                          </span>\n                        </button>\n                      );\n                    })}\n                  </div>\n                </div>\n\n                {/* CELL 3: Filterable live event stream */}\n                <div className=\"p-5 @[36rem]:p-6\">\n                  <div className=\"flex flex-wrap items-center justify-between gap-2.5\">\n                    <h3 className=\"flex items-center gap-2 text-[15.5px] font-medium tracking-[-0.015em] text-foreground\">\n                      <Filter className=\"size-3.5 text-muted-foreground\" aria-hidden=\"true\" />\n                      <span>{feedTitle}</span>\n                    </h3>\n                    <div role=\"radiogroup\" aria-label=\"Filter stream by type\" className=\"flex flex-wrap items-center gap-1\">\n                      {categories.map((cat) => {\n                        const selected = cat === category;\n                        return (\n                          <button\n                            key={cat}\n                            type=\"button\"\n                            role=\"radio\"\n                            aria-checked={selected}\n                            onClick={() => setCategory(cat)}\n                            className={`cursor-pointer rounded-full px-2.5 py-1 text-[12px] font-medium transition-colors ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${\n                              selected ? \"bg-muted text-foreground\" : \"text-muted-foreground hover:bg-muted/60 hover:text-foreground\"\n                            }`}\n                          >\n                            {cat}\n                          </button>\n                        );\n                      })}\n                    </div>\n                  </div>\n\n                  <ul className=\"mt-4 divide-y divide-border/70 border-t border-border/70\">\n                    {visibleRows.map((row) => (\n                      <li key={row.id} className=\"flex items-center justify-between gap-3 py-2.5 text-[13px]\">\n                        <div className=\"min-w-0\">\n                          <p className=\"truncate font-medium text-foreground\">{row.title}</p>\n                          <p className=\"truncate text-[12px] text-muted-foreground\">\n                            {row.category} · {row.meta}\n                          </p>\n                        </div>\n                        <span className=\"shrink-0 rounded-full bg-muted px-2.5 py-0.5 font-mono text-[11.5px] tabular-nums text-foreground\">\n                          {row.value}\n                        </span>\n                      </li>\n                    ))}\n                  </ul>\n                </div>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n    </section>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · metric-bento · 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/blocks/metric-bento. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}