{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"revenue-chart","type":"registry:block","title":"Revenue chart","description":"Bars for this period and a dashed line for the last, a tooltip on hover or the arrow keys, in plain SVG.","dependencies":["lucide-react"],"registryDependencies":["https://dashral.com/r/utils.json","https://dashral.com/r/lib-motion.json","https://dashral.com/r/segmented-control.json"],"files":[{"path":"registry/dashral/blocks/revenue-chart.tsx","type":"registry:file","target":"components/dashral/blocks/revenue-chart.tsx","content":"\"use client\"\n\nimport { useState } from \"react\"\nimport { ArrowDownRight, ArrowUpRight } from \"lucide-react\"\nimport { SegmentedControl } from \"../segmented-control\"\nimport { riseMotion, stagger, useCountTo } from \"../lib/motion\"\nimport { cn } from \"../lib/utils\"\n\n/** A bar: its label on the axis (\"\" for none), its full name when read, this period's value and the one before. */\nexport type Point = { label: string; long: string; value: number; previous: number }\n/** A range on the switch: its label there, what the line compares with, and its bars. */\nexport type RevenueRange = { value: string; label: string; compare: string; points: Point[] }\n\nconst months = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\nconst year = [32, 35, 33, 41, 39, 44, 47, 45, 52, 56, 54, 61].map((value, i) => ({\n  label: months[i]!,\n  long: `${months[i]} 2026`,\n  value: value * 1000,\n  previous: [28, 30, 31, 33, 34, 36, 35, 38, 41, 43, 42, 47][i]! * 1000,\n}))\nconst month = Array.from({ length: 30 }, (_, i) => {\n  const day = i + 1\n  const wave = Math.sin(i / 2.2) * 260 + Math.cos(i / 5) * 180\n  return {\n    label: day % 5 === 0 || day === 1 ? String(day) : \"\",\n    long: `Sep ${day}`,\n    value: Math.round(1450 + i * 22 + wave),\n    previous: Math.round(1380 + i * 12 + Math.sin(i / 3) * 200),\n  }\n})\nconst sampleRanges: RevenueRange[] = [\n  { value: \"year\", label: \"12 months\", compare: \"2025\", points: year },\n  { value: \"month\", label: \"30 days\", compare: \"August\", points: month },\n]\n\n/** A round top for the axis, and its four steps: 61,000 → 80,000. */\nfunction niceScale(max: number) {\n  const step = 10 ** Math.floor(Math.log10(max / 4))\n  const top = Math.ceil(max / 4 / step) * step * 4\n  return { top, ticks: [0, 1, 2, 3, 4].map((i) => (top / 4) * i) }\n}\n\nfunction change(now: number, before: number) {\n  return ((now - before) / before) * 100\n}\n\nfunction Change({ value, className }: { value: number; className?: string }) {\n  const up = value >= 0\n  const Icon = up ? ArrowUpRight : ArrowDownRight\n  return (\n    <span className={cn(\"inline-flex items-center gap-0.5 font-medium tabular-nums\", up ? \"text-success-text\" : \"text-destructive-text\", className)}>\n      <Icon className=\"size-3.5\" aria-hidden />\n      {Math.abs(value).toFixed(1)}%\n    </span>\n  )\n}\n\n/**\n * Revenue over a year or a month: bars for this period and a dashed line for the one before, on a round axis. Hover\n * a bar, or focus the chart and use the arrow keys, to read a point; the total and its change sit above it. Plain\n * SVG and divs, no chart library; with reduced motion the bars are simply there. Every part comes from props: your\n * ranges and their bars; with `range` and `onRangeChange` you load a range's bars as it's picked.\n */\nexport function RevenueChart({\n  title = \"Revenue\",\n  ranges = sampleRanges,\n  range: rangeProp,\n  onRangeChange,\n  currency = \"USD\",\n  locale = \"en-US\",\n}: {\n  title?: React.ReactNode\n  ranges?: RevenueRange[]\n  /** The range picked (the chart keeps it without it). */\n  range?: string\n  onRangeChange?: (range: string) => void\n  currency?: string\n  locale?: string\n}) {\n  const [ownRange, setOwnRange] = useState(ranges[0]?.value ?? \"\")\n  const range = rangeProp ?? ownRange\n  const [active, setActive] = useState<number | null>(null)\n  const { points, compare } = ranges.find((r) => r.value === range) ?? ranges[0] ?? { points: [], compare: \"\" }\n  const money = new Intl.NumberFormat(locale, { style: \"currency\", currency, maximumFractionDigits: 0 })\n  const symbol = money.formatToParts(0).find((part) => part.type === \"currency\")?.value ?? \"\"\n  // Axis labels by hand: Intl's compact notation differs between Node and browsers (\"$0\" vs \"$0.0\"), which breaks hydration.\n  const axis = (value: number) => (value >= 1000 ? `${symbol}${+(value / 1000).toFixed(1)}k` : `${symbol}${value}`)\n\n  const total = points.reduce((sum, p) => sum + p.value, 0)\n  // A new period counts the total to its sum.\n  const shownTotal = useCountTo(total)\n  const previousTotal = points.reduce((sum, p) => sum + p.previous, 0)\n  const { top, ticks } = niceScale(Math.max(1, ...points.flatMap((p) => [p.value, p.previous])))\n  const shown = active === null ? null : points[active]!\n\n  // The previous period as a line through the middle of each column, in a 0–100 box stretched to the plot.\n  const line = points.map((p, i) => `${((i + 0.5) / points.length) * 100},${100 - (p.previous / top) * 100}`).join(\" \")\n\n  function onKeyDown(event: React.KeyboardEvent) {\n    const last = points.length - 1\n    const keys: Record<string, number> = { ArrowRight: 1, ArrowLeft: -1, Home: -Infinity, End: Infinity }\n    if (!(event.key in keys)) return\n    event.preventDefault()\n    // The plot runs right to left in Arabic; the arrows follow what you see.\n    const rtl = getComputedStyle(event.currentTarget).direction === \"rtl\"\n    const step = keys[event.key]! * (rtl && Math.abs(keys[event.key]!) === 1 ? -1 : 1)\n    setActive((i) => Math.min(last, Math.max(0, (i ?? (step > 0 ? -1 : last + 1)) + step)))\n  }\n\n  return (\n    <section aria-labelledby=\"revenue-chart-title\" className=\"bg-background p-4 sm:p-6\">\n      <div className=\"rounded-xl border bg-card p-4 sm:p-6\">\n        <div className=\"flex flex-wrap items-start justify-between gap-4\">\n          <div>\n            <h2 id=\"revenue-chart-title\" className=\"text-sm font-medium text-muted-foreground\">\n              {title}\n            </h2>\n            <p className=\"mt-1 flex flex-wrap items-baseline gap-x-3 gap-y-1\">\n              <span className=\"text-3xl font-semibold tracking-[-0.02em] tabular-nums\">{money.format(shownTotal)}</span>\n              <span className=\"text-sm text-muted-foreground\">\n                <Change value={change(total, previousTotal)} /> vs {compare}\n              </span>\n            </p>\n          </div>\n          <SegmentedControl\n            aria-label=\"Range\"\n            value={range}\n            onValueChange={(value) => {\n              setOwnRange(value)\n              onRangeChange?.(value)\n              setActive(null)\n            }}\n            options={ranges.map(({ value, label }) => ({ value, label }))}\n          />\n        </div>\n\n        <div className=\"mt-4 flex items-center gap-4 text-xs text-muted-foreground\">\n          <span className=\"flex items-center gap-1.5\">\n            <span aria-hidden className=\"size-2.5 rounded-[3px] bg-primary\" /> This period\n          </span>\n          <span className=\"flex items-center gap-1.5\">\n            <span aria-hidden className=\"w-3.5 border-t-2 border-dashed border-muted-foreground/60\" /> {compare}\n          </span>\n        </div>\n\n        <div className=\"mt-4 flex gap-3\">\n          {/* The axis: its labels sit on the grid lines. */}\n          <div aria-hidden className=\"relative h-64 w-10 shrink-0 text-end text-[11px] text-muted-foreground tabular-nums\">\n            {ticks.map((tick) => (\n              <span key={tick} className=\"absolute end-0 translate-y-1/2\" style={{ bottom: `${(tick / top) * 100}%` }}>\n                {axis(tick)}\n              </span>\n            ))}\n          </div>\n\n          <div className=\"min-w-0 flex-1\">\n            <div\n              role=\"group\"\n              tabIndex={0}\n              aria-label={`Revenue by ${range === \"year\" ? \"month\" : \"day\"}. Use the arrow keys to read each one.`}\n              onKeyDown={onKeyDown}\n              onBlur={() => setActive(null)}\n              onPointerLeave={() => setActive(null)}\n              className=\"relative h-64 rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card\"\n            >\n              {ticks.map((tick) => (\n                <div\n                  key={tick}\n                  aria-hidden\n                  className={cn(\"absolute inset-x-0 border-t\", tick === 0 ? \"border-border\" : \"border-dashed border-divider\")}\n                  style={{ bottom: `${(tick / top) * 100}%` }}\n                />\n              ))}\n\n              {/* Keyed by the range, so a new set of bars rises in. */}\n              <div key={range} className={cn(\"absolute inset-0 flex\", range === \"year\" ? \"gap-2 sm:gap-3\" : \"gap-0.5 sm:gap-1\")}>\n                {points.map((p, i) => (\n                  <div key={p.long} className=\"relative flex h-full flex-1 items-end\" onPointerEnter={() => setActive(i)}>\n                    <div aria-hidden className={cn(\"absolute inset-x-0 inset-y-0 -mx-1 rounded-md transition-colors\", active === i && \"bg-muted/70\")} />\n                    <div className=\"relative h-full w-full overflow-hidden\" style={{ height: `${(p.value / top) * 100}%` }}>\n                      <div\n                        className={cn(\n                          riseMotion,\n                          \"size-full rounded-t-[4px] transition-colors\",\n                          active === null || active === i ? \"bg-primary\" : \"bg-primary/40\"\n                        )}\n                        style={stagger(i, range === \"year\" ? 35 : 12, 30)}\n                      />\n                    </div>\n                  </div>\n                ))}\n              </div>\n\n              <svg aria-hidden viewBox=\"0 0 100 100\" preserveAspectRatio=\"none\" className=\"pointer-events-none absolute inset-0 size-full overflow-visible rtl:-scale-x-100\">\n                <polyline points={line} fill=\"none\" className=\"stroke-muted-foreground/60\" strokeWidth={2} strokeDasharray=\"4 4\" strokeLinejoin=\"round\" vectorEffect=\"non-scaling-stroke\" />\n              </svg>\n\n              {shown && active !== null && (\n                <div\n                  aria-hidden\n                  className=\"pointer-events-none absolute top-0 z-10 w-44 -translate-x-1/2 rounded-lg border bg-popover p-3 text-xs text-popover-foreground shadow-lg rtl:translate-x-1/2\"\n                  style={{ insetInlineStart: `clamp(5.5rem, ${((active + 0.5) / points.length) * 100}%, calc(100% - 5.5rem))` }}\n                >\n                  <p className=\"font-medium\">{shown.long}</p>\n                  <dl className=\"mt-2 space-y-1\">\n                    <div className=\"flex justify-between gap-3\">\n                      <dt className=\"flex items-center gap-1.5 text-muted-foreground\">\n                        <span className=\"size-2 rounded-[2px] bg-primary\" /> Revenue\n                      </dt>\n                      <dd className=\"font-medium tabular-nums\">{money.format(shown.value)}</dd>\n                    </div>\n                    <div className=\"flex justify-between gap-3\">\n                      <dt className=\"flex items-center gap-1.5 text-muted-foreground\">\n                        <span className=\"w-2 border-t-2 border-dashed border-muted-foreground/60\" /> {compare}\n                      </dt>\n                      <dd className=\"tabular-nums\">{money.format(shown.previous)}</dd>\n                    </div>\n                  </dl>\n                  <p className=\"mt-2 border-t pt-2 text-muted-foreground\">\n                    <Change value={change(shown.value, shown.previous)} /> change\n                  </p>\n                </div>\n              )}\n            </div>\n\n            <div aria-hidden className={cn(\"mt-2 flex text-[11px] text-muted-foreground\", range === \"year\" ? \"gap-2 sm:gap-3\" : \"gap-0.5 sm:gap-1\")}>\n              {points.map((p, i) => (\n                <span key={p.long} className={cn(\"flex-1 text-center tabular-nums\", range === \"year\" && i % 2 === 1 && \"max-sm:invisible\")}>\n                  {p.label}\n                </span>\n              ))}\n            </div>\n          </div>\n        </div>\n\n        {/* What the tooltip shows, read out as the arrow keys move. */}\n        <p aria-live=\"polite\" className=\"sr-only\">\n          {shown ? `${shown.long}: ${money.format(shown.value)}, ${compare} ${money.format(shown.previous)}` : \"\"}\n        </p>\n      </div>\n    </section>\n  )\n}\n"}],"cssVars":{"theme":{"color-destructive-foreground":"var(--destructive-foreground)","color-destructive-text":"var(--destructive-text)","color-success":"var(--success)","color-success-foreground":"var(--success-foreground)","color-success-text":"var(--success-text)"},"light":{"destructive-foreground":"oklch(0.985 0 0)","destructive-text":"#bd2800","success":"oklch(0.508 0.118 165.612)","success-foreground":"oklch(0.985 0 0)","success-text":"oklch(0.432 0.095 166.913)"},"dark":{"destructive-foreground":"oklch(0.2 0 0)","destructive-text":"#ff8a5c","success":"oklch(0.696 0.17 162.48)","success-foreground":"oklch(0.2 0.04 160)","success-text":"oklch(0.765 0.177 163.223)"}}}