{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"metric","title":"Metric explainer","description":"A metric that explains itself: the number, the change in words, the AI’s reading of why it moved, and the drivers behind it ranked by how much each one counted.","type":"registry:component","author":"Detent","dependencies":["motion"],"registryDependencies":["https://detentui.com/r/theme.json"],"files":[{"path":"components/detent/components/metric/MetricExplainer.tsx","target":"components/detent/components/metric/MetricExplainer.tsx","type":"registry:component","content":"'use client'\n\nimport { Fragment, useId, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport { AnimatePresence, LayoutGroup, motion, useReducedMotion } from 'motion/react'\nimport { ease, spring, dur } from '@/components/detent/lib/motion'\nimport { RollingText } from '@/components/detent/ui/RollingText'\n\nexport type Driver = {\n  name: string\n  note?: string\n  amount: number\n  phrase?: string\n}\n\nexport type Metric = {\n  id: string\n  name: string\n  value: number\n  previous: number\n  format?: (n: number) => string\n  vs: string\n  reason: string\n  drivers: Driver[]\n  basis?: string\n}\n\nconst topDrivers = (m: Metric) => [...m.drivers].sort((a, b) => Math.abs(b.amount) - Math.abs(a.amount)).slice(0, 4)\nconst plain = (n: number) => Math.round(n).toLocaleString('en-US')\nconst signed = (n: number, format: (n: number) => string) => `${n < 0 ? '−' : '+'}${format(Math.abs(n))}`\n\nexport function MetricExplainer({\n  metrics,\n  metric,\n  defaultMetric,\n  onMetricChange,\n  period,\n  width = 640,\n  footer,\n  highlight = null,\n  tabs = true,\n}: {\n  metrics: Metric[]\n  metric?: string\n  defaultMetric?: string\n  onMetricChange?: (id: string) => void\n  period?: string\n  width?: number\n  footer?: ReactNode\n  highlight?: string | null\n  tabs?: boolean\n}) {\n  const [own, setOwn] = useState(defaultMetric ?? metrics[0]?.id)\n  const at = metric ?? own\n  const m = metrics.find((x) => x.id === at) ?? metrics[0]\n  const reduce = useReducedMotion()\n  const group = useId()\n  const [aim, setAim] = useState<{ metric: string; name: string } | null>(null)\n  if (!m) return null\n\n  const pick = (id: string) => {\n    if (metric === undefined) setOwn(id)\n    onMetricChange?.(id)\n  }\n  const format = m.format ?? plain\n  const diff = m.value - m.previous\n  const up = diff >= 0\n  const pct = m.previous ? Math.abs(diff / m.previous) * 100 : 0\n  const drivers = topDrivers(m)\n  const withIt = (d: Driver) => (d.amount >= 0) === up\n  const lit = (aim?.metric === m.id ? aim.name : null) ?? highlight\n  const without = drivers.find((d) => d.name === lit)\n  const point = (name: string | null) => setAim(name ? { metric: m.id, name } : null)\n  const pointers = (name: string) => ({ onPointerEnter: () => point(name), onPointerLeave: () => point(null), onFocus: () => point(name), onBlur: () => point(null) })\n\n  const parts: { text: string; driver?: string }[] = []\n  let rest = m.reason\n  for (;;) {\n    const hits = drivers.filter((d) => d.phrase && rest.includes(d.phrase)).map((d) => ({ d, at: rest.indexOf(d.phrase!) }))\n    if (!hits.length) break\n    const first = hits.reduce((a, b) => (b.at < a.at ? b : a))\n    if (first.at) parts.push({ text: rest.slice(0, first.at) })\n    parts.push({ text: first.d.phrase!, driver: first.d.name })\n    rest = rest.slice(first.at + first.d.phrase!.length)\n  }\n  if (rest) parts.push({ text: rest })\n  let w = 0\n\n  return (\n    <div className=\"@container\" style={{ width, maxWidth: '100%' }}>\n    <div className=\"rounded-[22px] bg-surface p-5 shadow-[var(--dt-card-edge)] @min-[520px]:p-7\">\n      <div className=\"flex flex-col gap-2 @min-[520px]:flex-row @min-[520px]:items-center @min-[520px]:justify-between @min-[520px]:gap-4\">\n        {tabs && (\n        <LayoutGroup id={group}>\n          <div role=\"tablist\" aria-label=\"Metric\" className=\"-ml-1 flex min-w-0 gap-0.5 overflow-x-auto [scrollbar-width:none]\">\n            {metrics.map((x) => {\n              const on = x.id === m.id\n              return (\n                <button\n                  key={x.id}\n                  type=\"button\"\n                  role=\"tab\"\n                  aria-selected={on}\n                  onClick={() => pick(x.id)}\n                  className={`ring-focus relative h-8 shrink-0 rounded-full px-3 text-footnote transition-colors ease-detent duration-150 pointer-coarse:h-9 @max-[400px]:px-2 ${on ? 'text-ink' : 'text-ink-3 hover:text-ink-2'}`}\n                >\n                  {on && <motion.span layoutId=\"metric-tab\" className=\"absolute inset-0 rounded-full bg-surface-2\" transition={spring.snappy} />}\n                  <span className=\"relative z-[1]\">{x.name}</span>\n                </button>\n              )\n            })}\n          </div>\n        </LayoutGroup>\n        )}\n        {!tabs && <span className=\"text-footnote font-medium text-ink\">{m.name}</span>}\n        {period && <span className=\"shrink-0 text-footnote text-ink-3\">{period}</span>}\n      </div>\n\n      <div className=\"mt-7\">\n        <p className={`tnum flex text-[40px] @min-[520px]:text-[52px] font-normal leading-none tracking-[-0.045em] transition-colors ease-detent duration-300 ${without ? 'text-quiet' : 'text-ink'}`}>\n          <RollingText text={format(without ? m.value - without.amount : m.value)} proportional />\n        </p>\n        <div className=\"mt-2.5 grid min-h-5 text-callout text-ink-3 @min-[520px]:h-5\">\n          <p className=\"col-start-1 row-start-1 @min-[520px]:truncate\">\n            {without ? (\n              <>\n                <span className=\"text-ink\">without {without.name}</span> · {signed(-without.amount, format)}, the rest of the change stays\n              </>\n            ) : (\n              <>\n                <span className=\"text-ink\">\n                  {up ? 'up' : 'down'} {format(Math.abs(diff))}\n                </span>{' '}\n                on {m.vs}, {pct.toFixed(1)}% {up ? 'more' : 'less'}\n              </>\n            )}\n          </p>\n          {metrics.map((x) => {\n            const f = x.format ?? plain\n            const d = x.value - x.previous\n            const pc = x.previous ? Math.abs(d / x.previous) * 100 : 0\n            const top = topDrivers(x)[0]\n            return (\n              <Fragment key={x.id}>\n                <span aria-hidden className=\"invisible col-start-1 row-start-1 @min-[520px]:hidden\">\n                  {d >= 0 ? 'up' : 'down'} {f(Math.abs(d))} on {x.vs}, {pc.toFixed(1)}% {d >= 0 ? 'more' : 'less'}\n                </span>\n                {top && (\n                  <span aria-hidden className=\"invisible col-start-1 row-start-1 @min-[520px]:hidden\">\n                    without {top.name} · {signed(-top.amount, f)}, the rest of the change stays\n                  </span>\n                )}\n              </Fragment>\n            )\n          })}\n        </div>\n      </div>\n\n      <div className=\"mt-6 grid min-h-[120px] @min-[520px]:h-[72px] @min-[520px]:min-h-0 @min-[520px]:overflow-hidden\">\n        <AnimatePresence mode=\"wait\" initial={false}>\n          <motion.p key={m.id} className=\"col-start-1 row-start-1 text-[15px] leading-6 text-ink [text-wrap:wrap] @min-[520px]:line-clamp-3\" exit={{ opacity: 0, transition: { duration: dur.exit, ease: ease.out } }}>\n            {parts.map((part, k) => {\n              const words = part.text.split(/(\\s+)/).map((x, i) =>\n                /^\\s+$/.test(x) || !x ? (\n                  x\n                ) : (\n                  <motion.span key={i} initial={reduce ? false : { opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.28, delay: reduce ? 0 : 0.08 + w++ * 0.024, ease: ease.out }}>\n                    {x}\n                  </motion.span>\n                ),\n              )\n              if (!part.driver) return <span key={k}>{words}</span>\n              const on = lit === part.driver\n              return (\n                <span\n                  key={k}\n                  {...pointers(part.driver)}\n                  className={`cursor-default rounded-[4px] underline decoration-1 underline-offset-[5px] transition-[background-color,text-decoration-color] ease-detent duration-200 ${on ? 'bg-[color-mix(in_oklch,var(--dt-accent)_12%,transparent)] decoration-[var(--dt-accent)]' : 'decoration-[color-mix(in_oklch,var(--ink)_16%,transparent)]'}`}\n                >\n                  {words}\n                </span>\n              )\n            })}\n          </motion.p>\n        </AnimatePresence>\n        {metrics.map((x) => (\n          <p key={x.id} aria-hidden className=\"invisible col-start-1 row-start-1 text-[15px] leading-6 [text-wrap:wrap] @min-[520px]:hidden\">\n            {x.reason}\n          </p>\n        ))}\n      </div>\n\n      <div className=\"mt-4 grid @min-[520px]:h-[196px]\">\n        <AnimatePresence mode=\"wait\" initial={false}>\n          <motion.ul key={m.id} className=\"col-start-1 row-start-1\" exit={{ opacity: 0, transition: { duration: dur.exit, ease: ease.out } }}>\n            {drivers.map((d, i) => (\n              <motion.li\n                key={d.name}\n                tabIndex={0}\n                aria-label={`${d.name}, ${signed(d.amount, format)}. Show the number without it.`}\n                {...pointers(d.name)}\n                className=\"ring-focus grid cursor-default grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-0.5 rounded-[2px] py-2.5 shadow-[inset_0_1px_0_var(--line)] outline-none @min-[520px]:h-[49px] @min-[520px]:grid-cols-[minmax(96px,128px)_minmax(0,1fr)_auto] @min-[520px]:gap-4 @min-[520px]:py-0\"\n                initial={reduce ? false : { opacity: 0, y: 4 }}\n                animate={{ opacity: lit && lit !== d.name ? 0.45 : 1, y: 0, transition: { ...spring.smooth, delay: reduce || lit ? 0 : 0.06 + i * 0.04, opacity: { duration: 0.2, ease: ease.out } } }}\n              >\n                <span className=\"truncate text-callout text-ink\">{d.name}</span>\n                <span className=\"col-span-2 row-start-2 text-footnote text-ink-3 @min-[520px]:col-span-1 @min-[520px]:row-start-auto @min-[520px]:truncate\">{d.note}</span>\n                <span className={`tnum text-right text-callout ${withIt(d) || lit === d.name ? 'text-ink' : 'text-ink-3'}`}>{signed(d.amount, format)}</span>\n              </motion.li>\n            ))}\n          </motion.ul>\n        </AnimatePresence>\n        {metrics.map((x) => (\n          <ul key={x.id} aria-hidden className=\"invisible col-start-1 row-start-1 @min-[520px]:hidden\">\n            {topDrivers(x).map((d) => (\n              <li key={d.name} className=\"grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-0.5 py-2.5\">\n                <span className=\"truncate text-callout\">{d.name}</span>\n                <span className=\"col-span-2 row-start-2 text-footnote\">{d.note}</span>\n                <span className=\"tnum text-right text-callout\">{signed(d.amount, x.format ?? plain)}</span>\n              </li>\n            ))}\n          </ul>\n        ))}\n      </div>\n\n      <div className=\"mt-3 flex min-h-5 flex-col gap-2 @min-[520px]:h-5 @min-[520px]:flex-row @min-[520px]:items-center @min-[520px]:justify-between @min-[520px]:gap-4\">\n        <div className=\"grid min-w-0\">\n          <p className=\"col-start-1 row-start-1 min-w-0 text-footnote text-ink-3 @min-[520px]:truncate\">{m.basis}</p>\n          {metrics.map((x) => (\n            <p key={x.id} aria-hidden className=\"invisible col-start-1 row-start-1 text-footnote @min-[520px]:hidden\">\n              {x.basis}\n            </p>\n          ))}\n        </div>\n        {footer && <div className=\"flex shrink-0 gap-4 text-footnote\">{footer}</div>}\n      </div>\n    </div>\n    </div>\n  )\n}\n"},{"path":"components/detent/ui/RollingText.tsx","target":"components/detent/ui/RollingText.tsx","type":"registry:component","content":"'use client'\n\nimport { useLayoutEffect, useRef, useState } from 'react'\nimport { animate, motion, useMotionValue } from 'motion/react'\n\nconst roll = { type: 'spring', stiffness: 380, damping: 34, mass: 0.8 } as const\n\nexport function RollingText({ text, className = '', proportional = false, still = false }: { text: string; className?: string; proportional?: boolean; still?: boolean }) {\n  const chars = [...text]\n  const probe = useRef<HTMLSpanElement>(null)\n  const [widths, setWidths] = useState<number[] | null>(null)\n\n  useLayoutEffect(() => {\n    if (!proportional || !probe.current) return\n    const read = () => {\n      const box = probe.current!\n      const z = box.offsetWidth ? box.getBoundingClientRect().width / box.offsetWidth : 1\n      const em = parseFloat(getComputedStyle(box).fontSize) || 16\n      setWidths([...box.children].map((c) => (c as HTMLElement).getBoundingClientRect().width / z / em))\n    }\n    read()\n    document.fonts?.ready.then(read)\n  }, [proportional])\n\n  return (\n    <span className={`relative inline-flex ${proportional ? '' : 'tnum'} ${className}`} style={{ lineHeight: '1.25em', height: '1.25em' }}>\n      <span className=\"sr-only\">{text}</span>\n      {proportional && (\n        <span aria-hidden className=\"pointer-events-none absolute left-0 top-0 size-0 overflow-hidden\">\n          <span ref={probe} className=\"invisible flex w-max whitespace-pre\">\n            {Array.from({ length: 10 }, (_, n) => (\n              <span key={n}>{n}</span>\n            ))}\n          </span>\n        </span>\n      )}\n      {chars.map((c, i) => {\n        const key = chars.length - i\n        return /\\d/.test(c) ? (\n          <Digit key={key} d={+c} width={proportional && widths ? widths[+c] : undefined} still={still} />\n        ) : (\n          <span key={`${key}${c}`} aria-hidden className=\"whitespace-pre\">\n            {c}\n          </span>\n        )\n      })}\n    </span>\n  )\n}\n\nfunction Digit({ d, width, still }: { d: number; width?: number; still: boolean }) {\n  const w = useMotionValue<string>(width === undefined ? '1ch' : `${width}em`)\n  const had = useRef(width !== undefined)\n  useLayoutEffect(() => {\n    if (width === undefined) return\n    if (!had.current) {\n      had.current = true\n      w.set(`${width}em`)\n      return\n    }\n    const ctl = animate(w, `${width}em`, roll)\n    return () => ctl.stop()\n  }, [width, w])\n\n  return (\n    <motion.span aria-hidden className=\"relative inline-block overflow-hidden\" style={{ height: '1.25em', width: w }}>\n      <motion.span className=\"absolute inset-x-0 top-0 flex flex-col items-center\" initial={false} animate={{ y: `${-d * 10}%` }} transition={still ? { duration: 0 } : roll}>\n        {Array.from({ length: 10 }, (_, n) => (\n          <span key={n} className=\"block\" style={{ height: '1.25em' }}>\n            {n}\n          </span>\n        ))}\n      </motion.span>\n    </motion.span>\n  )\n}\n"},{"path":"components/detent/lib/motion.ts","target":"components/detent/lib/motion.ts","type":"registry:component","content":"export const ease = {\n  out: [0.2, 0.9, 0.25, 1] as const,\n  inOut: [0.6, 0, 0.3, 1] as const,\n}\n\nexport const dur = {\n  exit: 0.12,\n  hover: 0.15,\n  enter: 0.2,\n  swap: 0.24,\n  panel: 0.34,\n}\n\nexport const spring = {\n  snappy: { type: 'spring', stiffness: 560, damping: 42, mass: 0.6 } as const,\n  smooth: { type: 'spring', bounce: 0, duration: 0.36 } as const,\n  soft: { type: 'spring', bounce: 0.12, duration: 0.5 } as const,\n  release: { type: 'spring', stiffness: 320, damping: 32 } as const,\n  move: { type: 'spring', stiffness: 420, damping: 38 } as const,\n  data: { type: 'spring', stiffness: 170, damping: 26 } as const,\n  pop: { type: 'spring', bounce: 0.3, duration: 0.4 } as const,\n}\n\nexport const appear = {\n  initial: { opacity: 0, scale: 0.96 },\n  animate: { opacity: 1, scale: 1, transition: { duration: dur.swap, ease: ease.out } },\n  exit: { opacity: 0, scale: 0.97, transition: { duration: dur.exit, ease: ease.out } },\n}\n\nexport const slide = {\n  enter: (dir: number) => ({ x: dir * 24, opacity: 0 }),\n  center: { x: 0, opacity: 1 },\n  exit: (dir: number) => ({ x: dir * -24, opacity: 0 }),\n}\n\nexport const press = { scale: 0.97 }\n\nexport const staggerFor = (count: number) => Math.min(0.04, 0.2 / Math.max(1, count))\n"}]}