{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"dot-meter","type":"registry:component","title":"Dot meter","description":"Several goals at once, each a small field of dots that pours in like grains: protein, carbs and fat, or seats, storage and API calls.","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/dot-meter.tsx","type":"registry:component","content":"// Hairline UI · dot-meter · 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\";\n\n/* ─────────────────────────────────────────────────────────\n * DOT METER: several goals at once, each a small field of dots\n *\n *   arrive    each goal's dots pour in from above like grains and\n *             settle bottom row first, one goal after another\n *   grow      a bigger value pours only the new grains, from the\n *             top of the field down onto the ones already there\n *   shrink    the top grains lift out, last in first out\n *   over      past the goal a second, deeper lap of grains falls\n *             onto the first, from the bottom again\n *   point     point at (or focus) a goal and the others dim; its\n *             name becomes its share of the goal\n *\n * Every grain moves by transform only (one Web Animation each);\n * nothing re-renders while they fall.\n * ───────────────────────────────────────────────────────── */\n\nexport interface DotMeterItem {\n  key: string;\n  label: string;\n  value: number;\n  goal: number;\n  /** Shown after the figures, e.g. \"g\" or \"GB\". */\n  unit?: string;\n  /** Any CSS colour. Defaults to your chart colours in turn. */\n  color?: string;\n  /** A small icon before the name. */\n  icon?: React.ReactNode;\n}\n\nexport interface DotMeterProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"title\"> {\n  items: DotMeterItem[];\n  title?: string;\n  /** A headline figure beside the title, e.g. today's calories. */\n  total?: number;\n  totalUnit?: string;\n  /** Dots across and down in each field; together they stand for one goal. */\n  columns?: number;\n  rows?: number;\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\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 focus-visible:ring-offset-4 focus-visible:ring-offset-background\";\nconst GAP = 3;\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\nconst mix = (color: string, amount: number, into = \"transparent\") => `color-mix(in oklab, ${color} ${amount}%, ${into})`;\n\nexport function DotMeter({\n  items,\n  title = \"Today\",\n  total,\n  totalUnit,\n  columns = 8,\n  rows = 5,\n  format,\n  locales,\n  className = \"\",\n  ...props\n}: DotMeterProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const [visible, setVisible] = React.useState(false);\n  const [active, setActive] = React.useState<string | null>(null);\n  const rootRef = React.useRef<HTMLDivElement>(null);\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 fmt = (v: number) => new Intl.NumberFormat(locale, format).format(v);\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, 440px)\" }} />\n      <div className=\"@container w-full\">\n        <div className=\"p-4 @md:p-5\">\n          <div className=\"flex items-baseline justify-between gap-3\">\n            <p className=\"truncate text-[12.5px] text-muted-foreground @md:text-[13px]\">{title}</p>\n            {total !== undefined && (\n              <p className=\"shrink-0 text-[15px] font-medium tracking-[-0.02em] text-foreground tabular-nums @md:text-[17px]\">\n                <NumberRoll value={visible ? total : 0} format={format} locales={locale} duration={1100} />\n                {totalUnit && <span className=\"ml-1 text-[12px] font-normal tracking-normal text-muted-foreground @md:text-[13px]\">{totalUnit}</span>}\n              </p>\n            )}\n          </div>\n\n          <div\n            className=\"mt-4 grid gap-x-4 @md:mt-5 @md:gap-x-6\"\n            style={{ gridTemplateColumns: `repeat(${Math.max(1, items.length)}, minmax(0, 1fr))` }}\n            onPointerLeave={(e) => {\n              if (e.pointerType !== \"touch\") setActive(null);\n            }}\n          >\n            {items.map((item, i) => (\n              <Field\n                key={item.key}\n                item={item}\n                color={item.color ?? `var(--chart-${(i % 5) + 1}, var(--primary))`}\n                index={i}\n                columns={columns}\n                rows={rows}\n                visible={visible}\n                reduced={reduced}\n                dim={active !== null && active !== item.key}\n                pointed={active === item.key}\n                onPoint={setActive}\n                fmt={fmt}\n                format={format}\n                locale={locale}\n              />\n            ))}\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\ninterface FieldProps {\n  item: DotMeterItem;\n  color: string;\n  index: number;\n  columns: number;\n  rows: number;\n  visible: boolean;\n  reduced: boolean;\n  dim: boolean;\n  pointed: boolean;\n  onPoint: (key: string | null) => void;\n  fmt: (v: number) => string;\n  format?: Intl.NumberFormatOptions;\n  locale?: string | string[];\n}\n\nconst Field = React.memo(function Field({ item, color, index, columns, rows, visible, reduced, dim, pointed, onPoint, fmt, format, locale }: FieldProps) {\n  const n = columns * rows;\n  const ratio = item.goal > 0 ? Math.max(0, item.value) / item.goal : 0;\n  const grains = Math.round(ratio * n);\n  // Before it's seen the field is empty, so the first pour is the arrival.\n  const first = visible ? Math.min(grains, n) : 0;\n  const second = visible ? Math.min(Math.max(grains - n, 0), n) : 0;\n\n  const gridRef = React.useRef<HTMLDivElement>(null);\n  const laps = React.useRef<(HTMLSpanElement | null)[][]>([[], []]);\n  const shown = React.useRef([0, 0]);\n  const arrived = React.useRef(false);\n\n  // Pour new grains in and lift old ones out, by fill order (bottom row first, left to right).\n  React.useLayoutEffect(() => {\n    const grid = gridRef.current;\n    if (!grid) return;\n    const targets = [first, second];\n    const cell = grid.firstElementChild as HTMLElement | null;\n    const pitch = (cell?.offsetHeight ?? 10) + GAP;\n    const opening = !arrived.current && first > 0;\n    if (opening) arrived.current = true;\n    // When both laps pour at once, the second waits for the first to land.\n    let landed = 0;\n    targets.forEach((target, lap) => {\n      const from = shown.current[lap];\n      if (target === from) return;\n      shown.current[lap] = target;\n      const els = laps.current[lap];\n      if (target > from) {\n        const count = target - from;\n        const step = Math.min(opening ? 16 : 26, 640 / count);\n        const wait = (opening ? index * 110 : 0) + (lap === 1 ? landed : 0);\n        if (lap === 0) landed = count * step + 420;\n        for (let i = from; i < target; i++) {\n          const el = els[i];\n          if (!el) continue;\n          el.getAnimations().forEach((a) => a.cancel());\n          el.style.opacity = \"1\";\n          if (reduced) continue;\n          const rowFromTop = rows - 1 - Math.floor(i / columns);\n          const drop = (rowFromTop + 1.6) * pitch;\n          const fall = 240 + 70 * Math.sqrt(rowFromTop + 1.6);\n          el.animate(\n            [\n              { transform: `translate3d(0,${-drop}px,0)`, opacity: 0, offset: 0, easing: \"cubic-bezier(0.5,0,0.95,0.6)\" },\n              { opacity: 1, offset: 0.3 },\n              { transform: \"translate3d(0,0,0)\", offset: 0.76, easing: \"cubic-bezier(0.2,0.7,0.4,1)\" },\n              { transform: `translate3d(0,${-Math.min(2, pitch * 0.18)}px,0)`, offset: 0.88, easing: \"cubic-bezier(0.6,0,0.8,0.4)\" },\n              { transform: \"translate3d(0,0,0)\", opacity: 1, offset: 1 },\n            ],\n            { duration: fall / 0.76, delay: wait + (i - from) * step, easing: \"linear\", fill: \"backwards\" },\n          );\n        }\n      } else {\n        const count = from - target;\n        const step = Math.min(18, 360 / count);\n        for (let i = from - 1; i >= target; i--) {\n          const el = els[i];\n          if (!el) continue;\n          el.getAnimations().forEach((a) => a.cancel());\n          el.style.opacity = \"0\";\n          if (reduced) continue;\n          el.animate(\n            [\n              { transform: \"translate3d(0,0,0) scale(1)\", opacity: 1 },\n              { transform: `translate3d(0,${-pitch * 0.9}px,0) scale(0.5)`, opacity: 0 },\n            ],\n            { duration: 280, delay: (from - 1 - i) * step, easing: EASE, fill: \"backwards\" },\n          );\n        }\n      }\n    });\n  }, [first, second, columns, rows, index, reduced]);\n\n  const unit = item.unit ? ` ${item.unit}` : \"\";\n  const share = Math.round(ratio * 100);\n  // Short enough for the narrowest field: the share alone, in the goal's colour.\n  const caption = pointed ? `${share}%` : item.label;\n  // The second lap is ink with a trace of the colour: darker in light, lighter in dark, never a muddy shade of it.\n  const deep = mix(color, 30, \"var(--foreground)\");\n\n  // The DOM lists the field top-down; fill order counts from the bottom-left.\n  const cells = [];\n  for (let p = 0; p < n; p++) {\n    const fromTop = Math.floor(p / columns);\n    const i = (rows - 1 - fromTop) * columns + (p % columns);\n    cells.push(\n      <span key={p} className=\"relative aspect-square rounded-full\" style={{ background: mix(color, 17) }}>\n        <span\n          ref={(el) => {\n            laps.current[0][i] = el;\n          }}\n          className=\"absolute inset-0 rounded-full opacity-0\"\n          style={{ background: color, willChange: \"transform\" }}\n        />\n        <span\n          ref={(el) => {\n            laps.current[1][i] = el;\n          }}\n          className=\"absolute inset-0 rounded-full opacity-0\"\n          style={{ background: deep, willChange: \"transform\" }}\n        />\n      </span>,\n    );\n  }\n\n  return (\n    <div\n      role=\"meter\"\n      tabIndex={0}\n      aria-label={item.label}\n      aria-valuemin={0}\n      aria-valuemax={item.goal}\n      aria-valuenow={item.value}\n      aria-valuetext={`${fmt(item.value)}${unit} of ${fmt(item.goal)}${unit}`}\n      onPointerMove={(e) => {\n        if (e.pointerType === \"mouse\") onPoint(item.key);\n      }}\n      onPointerDown={() => onPoint(pointed ? null : item.key)}\n      onFocus={() => onPoint(item.key)}\n      onBlur={() => onPoint(null)}\n      className={`min-w-0 cursor-default rounded-[6px] outline-none transition-opacity duration-200 ${FOCUS}`}\n      style={{ opacity: dim ? 0.38 : 1, transitionTimingFunction: EASE }}\n    >\n      <div ref={gridRef} aria-hidden=\"true\" className=\"grid max-w-[132px]\" style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`, gap: GAP }}>\n        {cells}\n      </div>\n      <p className=\"mt-2.5 text-[15px] font-medium leading-tight tracking-[-0.02em] text-foreground tabular-nums @md:text-[17px]\">\n        <NumberRoll value={visible ? item.value : 0} format={format} locales={locale} duration={1000} />\n        {item.unit && <span className=\"ml-0.5 text-[12px] font-normal tracking-normal text-muted-foreground @md:text-[13px]\">{item.unit}</span>}\n      </p>\n      <p className=\"mt-0.5 flex min-w-0 items-center gap-1.5 text-[11.5px] text-muted-foreground @md:text-[12.5px]\">\n        {item.icon ? (\n          <span className=\"flex size-3.5 shrink-0 items-center justify-center [&>svg]:size-3.5\" style={{ color }}>\n            {item.icon}\n          </span>\n        ) : (\n          <span className=\"size-2 shrink-0 rounded-[2px]\" style={{ background: color }} />\n        )}\n        <span className=\"min-w-0 truncate whitespace-nowrap\">\n          <TextMorph>{caption}</TextMorph>\n        </span>\n      </p>\n    </div>\n  );\n});\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/dot-meter. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}