{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"lens-bars","type":"registry:component","title":"Lens bars","description":"A whole year of days in one card, and a lens to read them: the bars under the pointer spread apart and widen, so any one day out of 365 is easy to land on.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/lens-bars.tsx","type":"registry:component","content":"// Hairline UI · lens-bars · 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 { createSpring, type Spring } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * LENS BARS: a year of days in one card, and a lens to read them\n *\n *   arrive    the first time it's on screen the bars grow out of\n *             the baseline in a wave from the left, the total rolls\n *   point     the pointer is a lens: the bars under it spread apart\n *             and widen (the one you're on to about 18px) while the\n *             rest of the year squeezes aside, so a single day out of\n *             365 is easy to land on. The day under the pointer never\n *             moves, the bars nearest it light up, and the readout\n *             above rolls to its figure\n *   sweep     bars you pass stay lit for a moment and fade back one\n *             after another, a short trail of where you've been\n *   leave     the lens relaxes and the year lies flat again (0.3s)\n *   data      new figures ease each bar to its new height in a wave\n *             running out from the day you last read\n *\n * Drawn on one canvas, so 365 or 3,650 bars cost the same: the lens\n * is two springs (where, how open) and one pure layout function.\n * The plot is one tab stop; arrow keys move a day, Shift a week.\n * ───────────────────────────────────────────────────────── */\n\nexport interface LensBarsDatum {\n  /** Unique, e.g. \"2026-03-14\". */\n  key: string;\n  value: number;\n  /** In the readout, e.g. \"Sat, 14 Mar\". */\n  label: string;\n  /** A tick under this bar, e.g. \"Mar\" on the first of each month. */\n  tick?: string;\n}\n\nexport interface LensBarsProps extends React.HTMLAttributes<HTMLDivElement> {\n  data: LensBarsDatum[];\n  title?: string;\n  /** Under the total, e.g. \"Last 365 days\". */\n  caption?: string;\n  /** The figure in the header. Defaults to the sum of the data. */\n  total?: number;\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n  /** Any CSS colour. Defaults to your first chart colour. */\n  color?: string;\n  /** Called when the day under the lens changes, with null when it closes. */\n  onActiveChange?: (datum: LensBarsDatum | null, index: number | null) => void;\n}\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\nconst LENS_SLOT = 15; // the day under the lens, in px\nconst LENS_REACH = 8; // how many days either side the lens reaches\nconst TRAIL = 0.45; // seconds for a passed bar to fade back\nconst LINE = 2; // every bar is a stack of 2px hairlines…\nconst PITCH = 4; // …one every 4px, counted up from the baseline\nconst LEVELS = 16; // light is drawn in this many steps, one path each, so neighbouring bars never seam\nconst HEADROOM = 34; // above the tallest bar, for the readout\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\n/** A round top for the scale: 4,820 → 5,000. */\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\nconst SOFT = 1.5; // device px: the filter squeezed days are drawn through\n/** The share of a tent of radius SOFT, centred on 0, that lies left of `x`. */\nfunction tentArea(x: number) {\n  if (x <= -SOFT) return 0;\n  if (x >= SOFT) return SOFT;\n  return x <= 0 ? (x + SOFT) ** 2 / (2 * SOFT) : SOFT - (SOFT - x) ** 2 / (2 * SOFT);\n}\n\nconst easeOut = (t: number) => 1 - (1 - t) ** 3;\nconst clamp01 = (t: number) => (t < 0 ? 0 : t > 1 ? 1 : t);\n\n/**\n * Where every bar's edges go with the lens at `focus` (px), open by `open` (0–1). Days near the focus are weighted up to\n * `zoom` times, then each side of the focus is scaled back into the space it had, so the day under the pointer stays put.\n * Writes n + 1 edges into `edges` and each bar's closeness to the focus (0–1) into `near`.\n */\nfunction lensLayout(n: number, width: number, focus: number, open: number, zoom: number, edges: Float32Array, near: Float32Array) {\n  const slot = width / n;\n  const reach = LENS_REACH * slot;\n  let acc = 0;\n  edges[0] = 0;\n  for (let i = 0; i < n; i++) {\n    const d = Math.abs((i + 0.5) * slot - focus) / reach;\n    const g = d < 1 ? (1 - d * d) ** 2 : 0;\n    near[i] = g;\n    acc += slot * (1 + (zoom - 1) * open * g);\n    edges[i + 1] = acc;\n  }\n  if (open <= 0.0001) {\n    for (let i = 0; i <= n; i++) edges[i] = i * slot;\n    return;\n  }\n  const at = Math.min(Math.max(focus / slot, 0), n - 1e-6);\n  const i0 = Math.floor(at);\n  const pivot = edges[i0] + (at - i0) * (edges[i0 + 1] - edges[i0]);\n  const left = pivot > 0 ? focus / pivot : 1;\n  const right = acc - pivot > 0 ? (width - focus) / (acc - pivot) : 1;\n  for (let i = 0; i <= n; i++) {\n    const x = edges[i];\n    edges[i] = x <= pivot ? x * left : focus + (x - pivot) * right;\n  }\n}\n\nexport function LensBars({\n  data,\n  title = \"Signups\",\n  caption,\n  total,\n  format,\n  locales,\n  color = \"var(--chart-1, var(--primary))\",\n  onActiveChange,\n  className = \"\",\n  ...props\n}: LensBarsProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const n = data.length;\n  const sum = total ?? data.reduce((s, d) => s + d.value, 0);\n  const max = niceMax(Math.max(0, ...data.map((d) => d.value)));\n\n  const [active, setActive] = React.useState<number | null>(null);\n  const [keyboard, setKeyboard] = React.useState(false);\n  const [visible, setVisible] = React.useState(false);\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const probeRef = React.useRef<HTMLSpanElement>(null);\n  const inkRef = React.useRef<HTMLSpanElement>(null);\n  const tagRef = React.useRef<HTMLDivElement>(null);\n  const stemRef = React.useRef<HTMLDivElement>(null);\n  const tickRefs = React.useRef<(HTMLSpanElement | null)[]>([]);\n  const onActiveRef = React.useRef(onActiveChange);\n  React.useEffect(() => {\n    onActiveRef.current = onActiveChange;\n  });\n\n  // Everything the frame loop reads lives here, so pointer moves never re-render the chart.\n  const engine = React.useRef<{\n    width: number;\n    height: number;\n    dpr: number;\n    edges: Float32Array;\n    near: Float32Array;\n    heat: Float32Array;\n    colH: Float32Array;\n    colHeat: Float32Array;\n    colCov: Float32Array;\n    from: Float32Array;\n    to: Float32Array;\n    changedAt: number;\n    changeOrigin: number;\n    bornAt: number;\n    lastPaint: number;\n    frame: number;\n    accent: string;\n    ink: string;\n    tagWidth: number;\n    active: number | null;\n    open: Spring | null;\n    focus: Spring | null;\n    reduced: boolean;\n    paint: () => void;\n  } | null>(null);\n\n  const paint = React.useCallback(() => {\n    const e = engine.current;\n    const canvas = canvasRef.current;\n    if (!e || !canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx || !e.width || !e.height) return;\n    const count = e.to.length;\n    if (!count) return;\n    const now = performance.now();\n    const dt = e.lastPaint ? Math.min((now - e.lastPaint) / 1000, 0.1) : 0;\n    e.lastPaint = now;\n\n    const open = e.open?.get() ?? 0;\n    const focus = e.focus?.get() ?? 0;\n    const slot = e.width / count;\n    const zoom = Math.max(1, LENS_SLOT / slot);\n    lensLayout(count, e.width, focus, open, zoom, e.edges, e.near);\n\n    const plotH = e.height - HEADROOM;\n    const decay = e.reduced ? 0 : Math.exp(-dt / TRAIL);\n    let busy = false;\n\n    ctx.setTransform(e.dpr, 0, 0, e.dpr, 0, 0);\n    ctx.clearRect(0, 0, e.width, e.height);\n    ctx.fillStyle = e.accent;\n    const grown = e.bornAt ? now - e.bornAt : 0;\n    const changed = now - e.changedAt;\n\n    // Work out every bar first, then draw in a few paths: the whole series once at its resting light, then the lit bars\n    // in steps of light. Days narrower than 4px are not drawn as bars: each device pixel column takes the average of the\n    // days near it, weighted through a soft 1.5px filter. Slivers, and bars touching at fractional edges, would flip\n    // on and off every frame as the lens slides them; filtered columns change only as smoothly as the layout does. Wider\n    // bars open their gaps gradually from there.\n    // The rest of the year dims only a little while the lens is open, so opening it never flashes the whole chart.\n    const base = 0.55 * (1 - 0.2 * open);\n    const cols = Math.ceil(e.width * e.dpr);\n    if (e.colH.length !== cols) {\n      e.colH = new Float32Array(cols);\n      e.colHeat = new Float32Array(cols);\n      e.colCov = new Float32Array(cols);\n    } else {\n      e.colH.fill(0);\n      e.colHeat.fill(0);\n      e.colCov.fill(0);\n    }\n    const levels: Path2D[] = Array.from({ length: LEVELS }, () => new Path2D());\n    const rest = new Path2D();\n    const bar = (path: Path2D, x: number, y: number, w: number, h: number) => {\n      if (w >= 4) path.roundRect(x, y, w, h, [Math.min(3, w / 2), Math.min(3, w / 2), 0, 0]);\n      else path.rect(x, y, w, h);\n    };\n    for (let i = 0; i < count; i++) {\n      // Arrival: a wave from the left. A change of data: a wave out from the last day read.\n      const born = e.reduced ? 1 : e.bornAt ? easeOut(clamp01((grown - (i / count) * 520) / 640)) : 0;\n      const wait = (Math.abs(i - e.changeOrigin) / count) * 280;\n      const t = e.reduced ? 1 : easeOut(clamp01((changed - wait) / 520));\n      const value = e.from[i] + (e.to[i] - e.from[i]) * t;\n      if (born < 1 || t < 1) busy = true;\n\n      // Light falls off smoothly from the lens's centre, and what it passed keeps some for a moment.\n      const lit = open * e.near[i] ** 1.6;\n      const heat = Math.max(lit, e.heat[i] * decay);\n      e.heat[i] = heat;\n      if (heat > 0.004 && heat !== lit) busy = true;\n\n      const x0 = e.edges[i];\n      const x1 = e.edges[i + 1];\n      const span = x1 - x0;\n      const h = Math.max(value > 0 ? LINE : 0, value * plotH * born);\n      if (span < 4) {\n        const a = x0 * e.dpr;\n        const b = x1 * e.dpr;\n        const last = Math.min(cols - 1, Math.ceil(b + SOFT));\n        for (let c = Math.max(0, Math.floor(a - SOFT)); c <= last; c++) {\n          const cover = tentArea(b - c - 0.5) - tentArea(a - c - 0.5);\n          if (cover <= 0) continue;\n          e.colH[c] += h * cover;\n          e.colHeat[c] += heat * cover;\n          e.colCov[c] += cover;\n        }\n        continue;\n      }\n      // The gap opens from nothing where columns hand over to bars, so no day pops, and stops at 2px: enough to tell\n      // days apart, too little to strobe as the comb slides under the lens.\n      const gap = Math.min(2, (span - 4) * 0.25);\n      const w = Math.min(12, span - gap);\n      const x = (x0 + x1) / 2 - w / 2;\n      const right = x + w;\n      bar(rest, x, e.height - h, Math.max(right - x, 1 / e.dpr), h);\n      const level = Math.round(heat * LEVELS);\n      if (level > 0) bar(levels[level - 1], x, e.height - h, Math.max(right - x, 1 / e.dpr), h);\n    }\n    for (let c = 0; c < cols; c++) {\n      const cover = e.colCov[c];\n      if (cover <= 0.01) continue;\n      const h = e.colH[c] / cover;\n      if (h <= 0) continue;\n      rest.rect(c / e.dpr, e.height - h, 1 / e.dpr, h);\n      const level = Math.round((e.colHeat[c] / cover) * LEVELS);\n      if (level > 0) levels[level - 1].rect(c / e.dpr, e.height - h, 1 / e.dpr, h);\n    }\n    // The mark: everything is drawn through a rule of hairlines, so a bar is a stack of lines and the plot behind it is\n    // the same lines, faint. Lines are counted from the baseline and land on device pixels, so they stay crisp.\n    const rule = new Path2D();\n    for (let k = 0; ; k++) {\n      const y = Math.round((e.height - LINE - k * PITCH) * e.dpr) / e.dpr;\n      if (y < HEADROOM - LINE) break;\n      rule.rect(0, y, e.width, LINE);\n    }\n    ctx.save();\n    ctx.clip(rule);\n    ctx.fillStyle = e.ink;\n    ctx.globalAlpha = 0.04;\n    ctx.fillRect(0, HEADROOM, e.width, e.height - HEADROOM);\n    ctx.fillStyle = e.accent;\n    ctx.globalAlpha = base;\n    ctx.fill(rest);\n    for (let l = 0; l < LEVELS; l++) {\n      // Over the resting fill at `base`, a layer at `heat` brings the bar to base + heat × (1 − base).\n      ctx.globalAlpha = (l + 1) / LEVELS;\n      ctx.fill(levels[l]);\n    }\n    ctx.restore();\n    ctx.globalAlpha = 1;\n\n\n    // The readout rides the top of the plot over the day under the lens, a hairline stem down to its bar.\n    const tag = tagRef.current;\n    const stem = stemRef.current;\n    if (tag && stem && e.active !== null) {\n      const i = e.active;\n      const cx = (e.edges[i] + e.edges[i + 1]) / 2;\n      const half = e.tagWidth / 2;\n      const tx = Math.min(Math.max(cx, half), e.width - half);\n      tag.style.transform = `translate3d(${tx - half}px,0,0)`;\n      const value = e.to[i];\n      const top = e.height - value * plotH;\n      const stemTop = 28;\n      stem.style.transform = `translate3d(${cx - 0.5}px,${stemTop}px,0) scaleY(${Math.max(0, top - stemTop - 4)})`;\n    }\n    if (tag) tag.style.opacity = String(open);\n    if (stem) stem.style.opacity = String(open * 0.9);\n\n    // Ticks follow their bars through the lens and fade as the squeeze crowds them onto a neighbour, never blinking.\n    let lastTick = -Infinity;\n    for (let i = 0; i < count; i++) {\n      const el = tickRefs.current[i];\n      if (!el) continue;\n      const cx = Math.min(Math.max((e.edges[i] + e.edges[i + 1]) / 2, 12), e.width - 12);\n      el.style.transform = `translate3d(${cx}px,0,0) translateX(-50%)`;\n      el.style.opacity = String(clamp01((cx - lastTick - 22) / 12));\n      lastTick = cx;\n    }\n\n    if (busy && !e.frame) {\n      e.frame = requestAnimationFrame(() => {\n        const next = engine.current;\n        if (!next) return;\n        next.frame = 0;\n        next.paint();\n      });\n    }\n    if (!busy) e.lastPaint = 0;\n  }, []);\n\n  // Build the engine once, before the layout effects below that size and fill it; springs paint through it.\n  React.useLayoutEffect(() => {\n    const e = {\n      width: 0,\n      height: 0,\n      dpr: 1,\n      edges: new Float32Array(1),\n      near: new Float32Array(0),\n      heat: new Float32Array(0),\n      colH: new Float32Array(0),\n      colHeat: new Float32Array(0),\n      colCov: new Float32Array(0),\n      from: new Float32Array(0),\n      to: new Float32Array(0),\n      changedAt: 0,\n      changeOrigin: 0,\n      bornAt: 0,\n      lastPaint: 0,\n      frame: 0,\n      accent: \"currentColor\",\n      ink: \"currentColor\",\n      tagWidth: 0,\n      active: null as number | null,\n      open: null as Spring | null,\n      focus: null as Spring | null,\n      reduced: false,\n      paint,\n    };\n    e.open = createSpring(0, { stiffness: 420, damping: 41 }, paint, 0.001);\n    e.focus = createSpring(0, { stiffness: 1500, damping: 78 }, paint, 0.05);\n    engine.current = e;\n    return () => {\n      e.open?.stop();\n      e.focus?.stop();\n      if (e.frame) cancelAnimationFrame(e.frame);\n      e.frame = 0;\n      engine.current = null;\n    };\n  }, [paint]);\n\n  // New data: heights ease from where they are, out from the last day read.\n  React.useLayoutEffect(() => {\n    const e = engine.current;\n    if (!e) return;\n    const next = new Float32Array(data.map((d) => Math.max(0, d.value) / max));\n    if (e.to.length === next.length) {\n      const now = performance.now();\n      const changed = now - e.changedAt;\n      // Start from where each bar is now, even mid-ease.\n      for (let i = 0; i < next.length; i++) {\n        const wait = (Math.abs(i - e.changeOrigin) / next.length) * 280;\n        const t = easeOut(clamp01((changed - wait) / 520));\n        e.from[i] = e.from[i] + (e.to[i] - e.from[i]) * t;\n      }\n      e.changeOrigin = e.active ?? Math.round(((e.focus?.get() ?? 0) / Math.max(1, e.width)) * next.length);\n      e.changedAt = now;\n      e.to = next;\n    } else {\n      e.from = next.slice();\n      e.to = next;\n      e.edges = new Float32Array(next.length + 1);\n      e.near = new Float32Array(next.length);\n      e.heat = new Float32Array(next.length);\n      e.changedAt = 0;\n    }\n    paint();\n  }, [data, max, paint]);\n\n  React.useEffect(() => {\n    const e = engine.current;\n    if (!e) return;\n    e.reduced = reduced;\n    if (reduced) {\n      e.open?.jump(e.open.getTarget());\n      e.focus?.jump(e.focus.getTarget());\n    }\n  }, [reduced]);\n\n  // Size the canvas to its box at the screen's pixel density.\n  React.useLayoutEffect(() => {\n    const plot = plotRef.current;\n    const canvas = canvasRef.current;\n    if (!plot || !canvas) return;\n    const measure = () => {\n      const e = engine.current;\n      if (!e) return;\n      const w = plot.clientWidth;\n      const h = canvas.clientHeight;\n      const dpr = Math.min(window.devicePixelRatio || 1, 3);\n      if (w === e.width && h === e.height && dpr === e.dpr) return;\n      e.width = w;\n      e.height = h;\n      e.dpr = dpr;\n      canvas.width = Math.round(w * dpr);\n      canvas.height = Math.round(h * dpr);\n      paint();\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(plot);\n    return () => observer.disconnect();\n  }, [paint]);\n\n  React.useLayoutEffect(() => {\n    const tag = tagRef.current;\n    if (!tag) return;\n    const measure = () => {\n      if (engine.current) engine.current.tagWidth = tag.offsetWidth;\n      paint();\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(tag);\n    return () => observer.disconnect();\n  }, [paint]);\n\n  // The canvas takes the theme's colours: read them, and again whenever the theme changes.\n  React.useEffect(() => {\n    const probe = probeRef.current;\n    if (!probe) return;\n    const read = () => {\n      const e = engine.current;\n      if (!e) return;\n      e.accent = getComputedStyle(probe).color;\n      if (inkRef.current) e.ink = getComputedStyle(inkRef.current).color;\n      paint();\n    };\n    read();\n    const observer = new MutationObserver(read);\n    observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n    const media = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    media.addEventListener(\"change\", read);\n    return () => {\n      observer.disconnect();\n      media.removeEventListener(\"change\", read);\n    };\n  }, [color, paint]);\n\n  // Grow in the first time it's seen.\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        setVisible(true);\n        if (engine.current) engine.current.bornAt = performance.now();\n        paint();\n        observer.disconnect();\n      },\n      { rootMargin: \"0px 0px -10% 0px\" },\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [paint]);\n\n  const aim = React.useCallback(\n    (index: number | null, x?: number) => {\n      const e = engine.current;\n      if (!e) return;\n      if (index === null) {\n        e.open?.set(0);\n      } else {\n        // The lens follows the pointer and the keys through one stiff spring, a few milliseconds behind: touch events\n        // arrive unevenly, and a lens pinned to each one jerks the whole comb of bars. A lens opening from shut starts\n        // where it is aimed.\n        const slot = e.width / Math.max(1, n);\n        const to = x ?? (index + 0.5) * slot;\n        const shut = (e.open?.getTarget() ?? 0) === 0 && (e.open?.get() ?? 0) < 0.05;\n        if (shut) e.focus?.jump(to);\n        else e.focus?.set(to);\n        e.open?.set(1);\n      }\n      if (index !== e.active) {\n        if (index !== null) e.active = index;\n        setActive(index);\n        onActiveRef.current?.(index === null ? null : data[index], index);\n      }\n      paint();\n    },\n    [data, n, paint],\n  );\n\n  const indexAt = (clientX: number) => {\n    const plot = plotRef.current;\n    if (!plot || !n) return null;\n    const r = plot.getBoundingClientRect();\n    const x = Math.min(Math.max(clientX - r.left, 0), r.width - 0.01);\n    return { index: Math.min(n - 1, Math.floor((x / r.width) * n)), x };\n  };\n\n  // A finger lifts and the lens stays on that day until the next tap somewhere else.\n  const sticky = React.useRef(false);\n  React.useEffect(() => {\n    if (active === null) return;\n    const away = (ev: PointerEvent) => {\n      if (!sticky.current || plotRef.current?.contains(ev.target as Node)) return;\n      sticky.current = false;\n      aim(null);\n    };\n    document.addEventListener(\"pointerdown\", away);\n    return () => document.removeEventListener(\"pointerdown\", away);\n  }, [active, aim]);\n\n  const onKeyDown = (ev: React.KeyboardEvent) => {\n    if (!n) return;\n    const from = active ?? n - 1;\n    const step = ev.shiftKey ? 7 : 1;\n    const moves: Record<string, number> = { ArrowLeft: from - step, ArrowRight: from + step, Home: 0, End: n - 1, PageUp: from - 30, PageDown: from + 30 };\n    if (ev.key === \"Escape\") {\n      aim(null);\n      return;\n    }\n    if (!(ev.key in moves)) return;\n    ev.preventDefault();\n    setKeyboard(true);\n    aim(Math.min(n - 1, Math.max(0, active === null ? from : moves[ev.key])));\n  };\n\n  const fmt = (v: number) => new Intl.NumberFormat(locale, format).format(v);\n  const shown = active !== null ? data[active] : null;\n\n  // The strip under the plot: what a year of days is usually asked first.\n  const average = n ? data.reduce((s, d) => s + d.value, 0) / n : 0;\n  const best = data.reduce((b, d, i) => (d.value > (data[b]?.value ?? -Infinity) ? i : b), 0);\n  const recent = data.slice(-30).reduce((s, d) => s + d.value, 0);\n  const before = data.slice(-60, -30).reduce((s, d) => s + d.value, 0);\n  const trend = n >= 60 && before ? (recent - before) / before : null;\n  const rounded = { ...format, maximumFractionDigits: 0 };\n\n  return (\n    <div\n      ref={rootRef}\n      className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`}\n      {...props}\n    >\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      <span ref={probeRef} aria-hidden=\"true\" className=\"hidden\" style={{ color }} />\n      <span ref={inkRef} aria-hidden=\"true\" className=\"hidden text-foreground\" />\n      <div className=\"p-4 @md:p-5 [--plot:150px] @md:[--plot:184px]\">\n        <p className=\"text-[12px] text-muted-foreground @md:text-[13px]\">{title}</p>\n        <p className=\"mt-0.5 text-[22px] font-medium leading-tight tracking-[-0.03em] text-foreground tabular-nums @md:text-[26px]\">\n          <NumberRoll value={visible ? sum : 0} format={format} locales={locale} duration={1000} />\n        </p>\n        {caption && <p className=\"mt-0.5 text-[11.5px] text-muted-foreground @md:text-[12.5px]\">{caption}</p>}\n\n        <div\n          ref={plotRef}\n          role=\"group\"\n          tabIndex={0}\n          aria-label={`${title}, ${n} days. Use the arrow keys to read each day, Shift to move a week.`}\n          onKeyDown={onKeyDown}\n          onBlur={() => {\n            if (keyboard) {\n              setKeyboard(false);\n              aim(null);\n            }\n          }}\n          onPointerMove={(ev) => {\n            if (ev.pointerType === \"touch\" && ev.buttons === 0) return;\n            const hit = indexAt(ev.clientX);\n            if (!hit) return;\n            setKeyboard(false);\n            aim(hit.index, hit.x);\n          }}\n          onPointerDown={(ev) => {\n            const hit = indexAt(ev.clientX);\n            if (!hit) return;\n            if (ev.pointerType !== \"mouse\") sticky.current = true;\n            aim(hit.index, hit.x);\n          }}\n          onPointerLeave={(ev) => {\n            if (ev.pointerType === \"mouse\") aim(null);\n          }}\n          className={`relative mt-4 cursor-crosshair touch-pan-y select-none rounded-lg @md:mt-5 ${FOCUS}`}\n        >\n          <canvas ref={canvasRef} aria-hidden=\"true\" className=\"block w-full\" style={{ height: \"calc(var(--plot) + 34px)\" }} />\n          <div aria-hidden=\"true\" className=\"absolute inset-x-0 bottom-0 border-t border-border\" />\n          <div ref={stemRef} aria-hidden=\"true\" className=\"pointer-events-none absolute left-0 top-0 h-px w-px origin-top bg-foreground/40\" style={{ opacity: 0 }} />\n          <div\n            ref={tagRef}\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute left-0 top-0 flex h-[24px] items-center gap-1.5 whitespace-nowrap rounded-full bg-background px-2.5 text-[11.5px] shadow-[0_0_0_1px_var(--border)]\"\n            style={{ opacity: 0 }}\n          >\n            <span className=\"text-muted-foreground\">\n              {shown?.label ?? \" \"}\n            </span>\n            <span className=\"font-medium tabular-nums text-foreground\">\n              {shown ? fmt(shown.value) : \" \"}\n            </span>\n          </div>\n        </div>\n        <div aria-hidden=\"true\" className=\"relative mt-1.5 h-4 overflow-hidden\">\n          {data.map((d, i) =>\n            d.tick ? (\n              <span\n                key={d.key}\n                ref={(el) => {\n                  tickRefs.current[i] = el;\n                }}\n                className=\"absolute left-0 top-0 whitespace-nowrap text-[10.5px] leading-4 text-muted-foreground\"\n                style={{ transition: reduced ? \"none\" : `opacity 200ms ${EASE}` }}\n              >\n                {d.tick}\n              </span>\n            ) : null,\n          )}\n        </div>\n\n        <div className=\"mt-3 grid grid-cols-3 gap-3 border-t border-border pt-3 @md:mt-4 @md:pt-4\">\n          <div className=\"min-w-0\">\n            <p className=\"truncate text-[11px] text-muted-foreground @md:text-[12px]\">Daily average</p>\n            <p className=\"mt-0.5 text-[15px] font-medium tracking-[-0.02em] text-foreground tabular-nums @md:text-[17px]\">\n              <NumberRoll value={visible ? average : 0} format={rounded} locales={locale} duration={900} />\n            </p>\n          </div>\n          {/* Pointing at the best day opens the lens on it. */}\n          <button\n            type=\"button\"\n            onPointerEnter={(ev) => ev.pointerType === \"mouse\" && aim(best)}\n            onPointerLeave={(ev) => ev.pointerType === \"mouse\" && aim(null)}\n            onFocus={() => aim(best)}\n            onBlur={() => aim(null)}\n            onClick={() => {\n              sticky.current = true;\n              aim(best);\n            }}\n            className={`min-w-0 cursor-pointer rounded-md text-left ${FOCUS}`}\n          >\n            <span className=\"block truncate text-[11px] text-muted-foreground @md:text-[12px]\">Best day · {data[best]?.label}</span>\n            <span className=\"mt-0.5 block text-[15px] font-medium tracking-[-0.02em] text-foreground tabular-nums @md:text-[17px]\">\n              <NumberRoll value={visible ? (data[best]?.value ?? 0) : 0} format={format} locales={locale} duration={900} />\n            </span>\n          </button>\n          <div className=\"min-w-0\">\n            <p className=\"truncate text-[11px] text-muted-foreground @md:text-[12px]\">Last 30 days</p>\n            <p className=\"mt-0.5 flex flex-wrap items-center gap-x-1.5 text-[15px] font-medium tracking-[-0.02em] text-foreground tabular-nums @md:text-[17px]\">\n              <NumberRoll value={visible ? recent : 0} format={format} locales={locale} duration={900} />\n              {trend !== null && (\n                <span\n                  className={`inline-flex items-center gap-0.5 rounded-full px-1.5 py-px text-[11px] font-medium tracking-normal @md:text-[11.5px] ${\n                    trend >= 0 ? \"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400\" : \"bg-red-500/10 text-red-600 dark:text-red-400\"\n                  }`}\n                >\n                  <svg viewBox=\"0 0 12 12\" aria-hidden=\"true\" className=\"size-2.5\" style={{ transform: trend >= 0 ? \"none\" : \"rotate(180deg)\" }}>\n                    <path d=\"M6 9.5V2.5M2.8 5.6 6 2.5l3.2 3.1\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n                  </svg>\n                  <span className=\"sr-only\">{trend >= 0 ? \"up\" : \"down\"}</span>\n                  {new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 }).format(Math.abs(trend))}\n                </span>\n              )}\n            </p>\n          </div>\n        </div>\n\n        <p aria-live=\"polite\" className=\"sr-only\">\n          {keyboard && shown ? `${shown.label}: ${fmt(shown.value)}` : \"\"}\n        </p>\n        <div className=\"sr-only\"><table>\n          <caption>\n            {title}: {fmt(sum)}\n          </caption>\n          <tbody>\n            {data.map((d) => (\n              <tr key={d.key}>\n                <th scope=\"row\">{d.label}</th>\n                <td>{fmt(d.value)}</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 · lens-bars · 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/lens-bars. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}