{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"micro-trend","title":"Micro trend","description":"A small inline chart of one or more lines over time for a table cell or tile: sales vs forecast with a dashed forecast, P10–P90 band and a this-week marker; gaps left blank; a gliding crosshair with a tooltip reading every series.","registryDependencies":["tooltip"],"files":[{"path":"src/registry/catman/ui/micro-trend.tsx","content":"\"use client\"\n\nimport { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent, type PointerEvent, type ReactNode } from \"react\"\n\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"@/components/ui/tooltip\"\nimport { cn } from \"@/lib/utils\"\n\n/**\n * A small inline chart of one or more lines over time, for a table cell or a\n * tile: sales against forecast, this year against last, stock against the\n * reorder point, sell-through against plan.\n *\n * - A gap in the data is left blank, never joined: a missing sample is not a\n *   flat line.\n * - A forecast reads as a forecast: a dashed series, a shaded band between two\n *   series (P10 to P90), and a marker where actuals stop.\n * - Hover (or focus and use the arrow keys) to read any sample: a crosshair\n *   glides to it, the other samples dim, and a tooltip reads every series.\n * - Lines draw in on mount; reduced motion skips it.\n * - `footer` sits under the chart, for a change indicator and a figure or two\n *   (see `@twelfth/micro-stat`).\n *\n * Part of the twelfth catman registry (`@twelfth/micro-trend`).\n */\nexport type MicroTrendSeries = {\n  key: string\n  label: string\n  /** Any CSS colour. Defaults run through a palette that reads in light and dark. */\n  color?: string\n  /** Stroke width; the most important series is usually drawn heavier. */\n  weight?: number\n  /** Dashed, for a projection or a forecast. */\n  dashed?: boolean\n}\n\n/** A shaded range between two value keys, e.g. a forecast's P10 and P90. */\nexport type MicroTrendBand = {\n  lower: string\n  upper: string\n  label: string\n  color?: string\n}\n\n/** A vertical marker, e.g. \"this week\" between actuals and forecast. */\nexport type MicroTrendMarker = {\n  at: string | number | Date\n  label: string\n}\n\nexport type MicroTrendPoint = {\n  at: string | number | Date\n  values: Record<string, number | null>\n}\n\nexport type MicroTrendReference = {\n  value: number\n  label?: string\n  tone?: \"favourable\" | \"exposed\" | \"muted\"\n}\n\nconst PALETTE = [\"#f43f5e\", \"#f59e0b\", \"#14b8a6\", \"#6366f1\", \"#64748b\"]\nconst REFERENCE_STROKE: Record<NonNullable<MicroTrendReference[\"tone\"]>, string> = {\n  favourable: \"stroke-favourable-foreground\",\n  exposed: \"stroke-exposed-foreground\",\n  muted: \"stroke-muted-foreground\",\n}\nconst AT = new Intl.DateTimeFormat(\"en-AU\", { weekday: \"short\", day: \"numeric\", month: \"short\", hour: \"2-digit\", minute: \"2-digit\", hour12: false })\nconst useIsomorphicLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect\n\nconst REDUCED_MOTION = \"(prefers-reduced-motion: reduce)\"\nfunction usePrefersReducedMotion() {\n  return useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(REDUCED_MOTION)\n      query.addEventListener(\"change\", onChange)\n      return () => query.removeEventListener(\"change\", onChange)\n    },\n    () => window.matchMedia(REDUCED_MOTION).matches,\n    () => false,\n  )\n}\n\ntype Coord = { point: MicroTrendPoint; time: number }\n\n/** Polyline point strings for one series, split at a null or a long silence. */\nfunction segments(coords: Coord[], key: string, gapAfter: number | undefined, x: (t: number) => number, y: (v: number) => number) {\n  const out: string[] = []\n  let path = \"\"\n  let previous: number | null = null\n  for (const { point, time } of coords) {\n    const value = point.values[key]\n    const broken = value === null || value === undefined || !Number.isFinite(value)\n    if (broken || (previous !== null && gapAfter !== undefined && time - previous > gapAfter)) {\n      if (path) out.push(path)\n      path = \"\"\n    }\n    if (!broken) path += `${path ? \" \" : \"\"}${x(time).toFixed(1)},${y(value).toFixed(1)}`\n    previous = time\n  }\n  if (path) out.push(path)\n  return out\n}\n\n/** Closed polygons for a band, split wherever either edge is missing. */\nfunction bandPolygons(coords: Coord[], band: MicroTrendBand, x: (t: number) => number, y: (v: number) => number) {\n  const out: string[] = []\n  let run: Array<[number, number, number]> = []\n  const flush = () => {\n    if (run.length > 1) {\n      const top = run.map(([t, , hi]) => `${x(t).toFixed(1)},${y(hi).toFixed(1)}`)\n      const bottom = [...run].reverse().map(([t, lo]) => `${x(t).toFixed(1)},${y(lo).toFixed(1)}`)\n      out.push([...top, ...bottom].join(\" \"))\n    }\n    run = []\n  }\n  for (const { point, time } of coords) {\n    const lo = point.values[band.lower]\n    const hi = point.values[band.upper]\n    if (typeof lo === \"number\" && typeof hi === \"number\" && Number.isFinite(lo) && Number.isFinite(hi)) run.push([time, lo, hi])\n    else flush()\n  }\n  flush()\n  return out\n}\n\nexport function MicroTrend({\n  points,\n  series,\n  label,\n  width = 120,\n  height = 34,\n  domain,\n  zeroBased = false,\n  range,\n  reference,\n  bands = [],\n  marker,\n  gapAfter,\n  formatValue = (value) => value.toLocaleString(\"en-AU\", { maximumFractionDigits: 1 }),\n  formatAt = (date) => AT.format(date),\n  readout,\n  footer,\n  onExpand,\n  axes = true,\n  align = \"end\",\n  className,\n}: {\n  points: MicroTrendPoint[]\n  series: MicroTrendSeries[]\n  /** What the chart shows, for screen readers and the tooltip. */\n  label: string\n  width?: number\n  height?: number\n  /** The value axis. Defaults to the lowest value up to the highest, references and bands included. */\n  domain?: [number, number]\n  /** Start the default axis at zero, for a quantity whose distance from zero is the point. */\n  zeroBased?: boolean\n  /** The time axis. Defaults to the first sample to the last. */\n  range?: [Date | number, Date | number]\n  /** A dashed line to read against: a target, a reorder point, parity. */\n  reference?: MicroTrendReference\n  /** Shaded ranges between two keys, e.g. a forecast's P10 to P90. */\n  bands?: MicroTrendBand[]\n  /** A vertical line at a moment, e.g. where actuals stop and forecast starts. */\n  marker?: MicroTrendMarker\n  /** Break a line where two samples are further apart than this many milliseconds. */\n  gapAfter?: number\n  formatValue?: (value: number, series: MicroTrendSeries) => string\n  formatAt?: (date: Date) => string\n  /** Extra lines for the tooltip, for the sample under the cursor. */\n  readout?: (point: MicroTrendPoint) => ReactNode\n  /** Under the chart: a change indicator and a figure or two. */\n  footer?: ReactNode\n  /** Makes the chart a button, e.g. to open a full-size view. */\n  onExpand?: () => void\n  /** A faint left edge and baseline, so the lines read as a size and a direction. */\n  axes?: boolean\n  align?: \"start\" | \"end\"\n  className?: string\n}) {\n  const [hover, setHover] = useState<number | null>(null)\n  const reducedMotion = usePrefersReducedMotion()\n  const svgRef = useRef<SVGSVGElement>(null)\n\n  const coords: Coord[] = points\n    .map((point) => ({ point, time: new Date(point.at).getTime() }))\n    .filter(({ time }) => Number.isFinite(time))\n    .sort((a, b) => a.time - b.time)\n\n  // Lines draw in once, on mount.\n  useIsomorphicLayoutEffect(() => {\n    if (reducedMotion || !svgRef.current) return\n    const easing = \"cubic-bezier(0.22, 1, 0.36, 1)\"\n    for (const line of svgRef.current.querySelectorAll<SVGPolylineElement>(\"polyline[data-series]\")) {\n      if (line.dataset.dashed) line.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 500, delay: 350, easing, fill: \"backwards\" })\n      else line.animate([{ strokeDashoffset: 1 }, { strokeDashoffset: 0 }], { duration: 700, easing })\n    }\n    for (const area of svgRef.current.querySelectorAll<SVGPolygonElement>(\"polygon[data-band]\")) {\n      area.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 600, delay: 250, easing, fill: \"backwards\" })\n    }\n  }, [])\n\n  if (coords.length < 2) return <span className={cn(\"text-xs text-muted-foreground\", className)}>collecting</span>\n\n  const colored = series.map((s, i) => ({ ...s, color: s.color ?? PALETTE[i % PALETTE.length], weight: s.weight ?? (i === 0 ? 1.6 : 1.3) }))\n  const start = range ? new Date(range[0]).getTime() : coords[0].time\n  const end = range ? new Date(range[1]).getTime() : coords[coords.length - 1].time\n  const values = coords.flatMap(({ point }) => colored.map((s) => point.values[s.key]).filter((v): v is number => typeof v === \"number\" && Number.isFinite(v)))\n  for (const band of bands) for (const { point } of coords) for (const key of [band.lower, band.upper]) {\n    const value = point.values[key]\n    if (typeof value === \"number\" && Number.isFinite(value)) values.push(value)\n  }\n  if (reference) values.push(reference.value)\n  const [lo, hi] = domain ?? (() => {\n    const min = Math.min(...values)\n    const max = Math.max(...values)\n    const slack = (max - min) * 0.08\n    return [zeroBased ? Math.min(0, min) : min - slack, max + slack]\n  })()\n  const pad = 2\n  const x = (time: number) => (end === start ? width / 2 : ((time - start) / (end - start)) * width)\n  const y = (value: number) => {\n    const clamped = Math.min(Math.max(value, lo), hi)\n    return hi === lo ? height / 2 : height - pad - ((clamped - lo) / (hi - lo)) * (height - 2 * pad)\n  }\n\n  const active = coords[hover ?? coords.length - 1]\n  const nearest = (clientX: number) => {\n    const box = svgRef.current?.getBoundingClientRect()\n    if (!box?.width) return coords.length - 1\n    const at = ((clientX - box.left) / box.width) * width\n    let best = 0\n    for (let i = 1; i < coords.length; i++) if (Math.abs(x(coords[i].time) - at) < Math.abs(x(coords[best].time) - at)) best = i\n    return best\n  }\n  const onPointerMove = (event: PointerEvent) => setHover(nearest(event.clientX))\n  const onKeyDown = (event: KeyboardEvent) => {\n    if (![\"ArrowLeft\", \"ArrowRight\", \"Home\", \"End\"].includes(event.key)) return\n    event.preventDefault()\n    const current = hover ?? coords.length - 1\n    setHover(event.key === \"Home\" ? 0 : event.key === \"End\" ? coords.length - 1 : Math.max(0, Math.min(coords.length - 1, current + (event.key === \"ArrowLeft\" ? -1 : 1))))\n  }\n  const latest = coords[coords.length - 1].point\n  const summary = colored.map((s) => {\n    const value = latest.values[s.key]\n    return `${s.label} ${value === null || value === undefined ? \"no value\" : formatValue(value, s)}`\n  }).join(\", \")\n\n  const chart = (\n    <svg ref={svgRef} viewBox={`0 0 ${width} ${height}`} width={width} height={height} aria-hidden className=\"block overflow-visible\" onPointerMove={onPointerMove} onPointerLeave={() => setHover(null)}>\n      {axes ? <polyline points={`0.5,0 0.5,${height - 0.5} ${width},${height - 0.5}`} fill=\"none\" stroke=\"currentColor\" strokeOpacity={0.16} strokeWidth={1} pointerEvents=\"none\" /> : null}\n      {bands.map((band, b) =>\n        bandPolygons(coords, band, x, y).map((polygon, index) => (\n          <polygon key={`band-${b}-${index}`} data-band points={polygon} fill={band.color ?? colored[0]?.color ?? PALETTE[0]} fillOpacity={0.2} className=\"transition-opacity duration-200\" opacity={hover === null ? 1 : 0.7} />\n        )),\n      )}\n      {marker ? (\n        <line x1={x(new Date(marker.at).getTime())} x2={x(new Date(marker.at).getTime())} y1={0} y2={height} stroke=\"currentColor\" strokeOpacity={0.3} strokeWidth={1} strokeDasharray=\"2 2\" />\n      ) : null}\n      {reference ? (\n        <line x1={0} x2={width} y1={y(reference.value)} y2={y(reference.value)} className={REFERENCE_STROKE[reference.tone ?? \"muted\"]} strokeOpacity={0.6} strokeWidth={1} strokeDasharray=\"3 3\" />\n      ) : null}\n      {colored.map((s) =>\n        segments(coords, s.key, gapAfter, x, y).map((segment, index) =>\n          segment.includes(\" \") ? (\n            <polyline\n              key={`${s.key}-${index}`}\n              data-series={s.key}\n              data-dashed={s.dashed ? \"\" : undefined}\n              points={segment}\n              pathLength={s.dashed ? undefined : 1}\n              strokeDasharray={s.dashed ? \"3 2\" : reducedMotion ? undefined : 1}\n              fill=\"none\"\n              stroke={s.color}\n              strokeWidth={s.weight}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              className=\"transition-opacity duration-200\"\n              opacity={hover === null ? 1 : 0.5}\n            />\n          ) : (\n            <circle key={`${s.key}-${index}`} cx={segment.split(\",\")[0]} cy={segment.split(\",\")[1]} r={1.2} fill={s.color} />\n          ),\n        ),\n      )}\n      {/* The crosshair and its dots glide between samples rather than jump. */}\n      <g\n        pointerEvents=\"none\"\n        className={cn(\"transition-[transform,opacity] duration-150 ease-out motion-reduce:transition-none\", hover === null ? \"opacity-0\" : \"opacity-100\")}\n        style={{ transform: `translateX(${x(active.time)}px)` }}\n      >\n        <line x1={0} x2={0} y1={0} y2={height} stroke=\"currentColor\" strokeOpacity={0.35} strokeWidth={1} />\n      </g>\n      {colored.map((s) => {\n        const value = active.point.values[s.key]\n        if (value === null || value === undefined || !Number.isFinite(value)) return null\n        return (\n          <g\n            key={s.key}\n            pointerEvents=\"none\"\n            className={cn(\"transition-[transform,opacity] duration-150 ease-out motion-reduce:transition-none\", hover === null ? \"opacity-0\" : \"opacity-100\")}\n            style={{ transform: `translate(${x(active.time)}px, ${y(value)}px)` }}\n          >\n            <circle r={2.6} fill={s.color} stroke=\"var(--background)\" strokeWidth={1} />\n          </g>\n        )\n      })}\n      {/* Transparent hit area, so the space between lines still tracks. */}\n      <rect width={width} height={height} fill=\"transparent\" />\n    </svg>\n  )\n\n  return (\n    <span className={cn(\"inline-flex flex-col gap-0.5\", align === \"end\" ? \"items-end\" : \"items-start\", className)}>\n      <Tooltip trackCursorAxis=\"x\">\n        <TooltipTrigger\n          delay={0}\n          render={<button type=\"button\" />}\n          aria-label={`${label}: ${summary}. Use left and right arrows to move between samples.${onExpand ? \" Click to expand.\" : \"\"}`}\n          onClick={onExpand}\n          onKeyDown={onKeyDown}\n          onBlur={() => setHover(null)}\n          className={cn(\"inline-flex rounded-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring\", onExpand ? \"cursor-zoom-in\" : \"cursor-crosshair\")}\n        >\n          {chart}\n        </TooltipTrigger>\n        <TooltipContent side=\"top\" className=\"block w-52 py-2 text-left text-xs\">\n          <p className=\"font-medium tabular-nums\">{formatAt(new Date(active.time))}</p>\n          <div className=\"mt-1.5 space-y-0.5 tabular-nums\">\n            {colored.filter((s) => active.point.values[s.key] != null || colored.every((c) => active.point.values[c.key] == null)).map((s) => {\n              const value = active.point.values[s.key]\n              return (\n                <p key={s.key} className=\"flex items-center gap-2\">\n                  <span className=\"size-2 shrink-0 rounded-full\" style={{ backgroundColor: s.color }} />\n                  <span className=\"opacity-80\">{s.label}</span>\n                  <span className=\"ml-auto font-medium\">{value === null || value === undefined ? \"—\" : formatValue(value, s)}</span>\n                </p>\n              )\n            })}\n          </div>\n          {bands.map((band) => {\n            const lo = active.point.values[band.lower]\n            const hi = active.point.values[band.upper]\n            if (typeof lo !== \"number\" || typeof hi !== \"number\") return null\n            const s0 = colored[0]\n            return <p key={band.label} className=\"mt-1 tabular-nums opacity-80\">{band.label}: {formatValue(lo, s0)}–{formatValue(hi, s0)}</p>\n          })}\n          {marker && active.time >= new Date(marker.at).getTime() && colored.some((s) => s.dashed && active.point.values[s.key] != null) ? <p className=\"mt-1 opacity-70\">{marker.label} onward is forecast</p> : null}\n          {reference?.label ? <p className=\"mt-1.5 opacity-70\">Reference: {reference.label}</p> : null}\n          {readout ? <div className=\"mt-1.5 opacity-80\">{readout(active.point)}</div> : null}\n          {onExpand ? <p className=\"mt-1.5 text-[10px] opacity-60\">Click to expand</p> : null}\n        </TooltipContent>\n      </Tooltip>\n      {footer ? <span className=\"flex items-center gap-1.5 text-[10px] tabular-nums text-muted-foreground\">{footer}</span> : null}\n    </span>\n  )\n}\n","type":"registry:ui"}],"type":"registry:ui"}