{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "charts",
  "title": "Charts",
  "description": "Dashboard metric charts on Recharts: a headline with a period-over-period change badge, line charts with previous-period comparisons that stop at today, a category share bar, and a hook that fetches when a chart scrolls into view.",
  "dependencies": [
    "recharts@^3.8.0",
    "lucide-react"
  ],
  "registryDependencies": [
    "chart",
    "https://dentil.dev/r/badge.json?via=charts",
    "https://dentil.dev/r/link.json?via=charts"
  ],
  "files": [
    {
      "path": "components/dentil/charts/category-bar-chart.tsx",
      "content": "'use client';\n\nimport type { ReactNode } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport {\n  Chart,\n  ChartContent,\n  ChartFooter,\n  ChartHeader,\n  useChartContext,\n  type ChartFooterProps,\n  type ChartHeaderProps,\n  type ChartProps,\n} from './chart';\nimport { chartColor } from './colors';\n\nexport interface CategoryBarItem {\n  id: string | number;\n  title: ReactNode;\n  /** Second line under the title, for example \"12% of total\". */\n  subtitle?: ReactNode;\n  value: number;\n  /** Makes the row a link, rendered with the chart's `linkComponent`. */\n  href?: string;\n  /** Any CSS color. Defaults to `var(--chart-1)` through `var(--chart-5)` in order. */\n  color?: string;\n}\n\nexport interface CategoryBarChartProps\n  extends\n    Pick<ChartProps, 'loading' | 'embedded' | 'timezone' | 'locale' | 'linkComponent' | 'className'>,\n    Pick<ChartHeaderProps, 'title' | 'meta' | 'previousValue' | 'previousLabel' | 'change' | 'lowerIsBetter'>,\n    Pick<ChartFooterProps, 'href' | 'hrefLabel' | 'updatedAt'> {\n  items: ReadonlyArray<CategoryBarItem>;\n  /** Headline. Defaults to the sum of `items`. */\n  value?: ReactNode;\n  /** Formats each row's value. */\n  formatValue?: (value: number) => string;\n  /** Formats the headline. Defaults to `formatValue`. */\n  formatHeadlineValue?: (value: number) => string;\n  error?: ReactNode;\n  emptyMessage?: ReactNode;\n}\n\n/** A total split into categories: one stacked bar showing each share, and a row per category with its value. */\nexport function CategoryBarChart({\n  items,\n  value,\n  formatValue: formatValueProp,\n  formatHeadlineValue,\n  error,\n  emptyMessage,\n  title,\n  meta,\n  previousValue,\n  previousLabel,\n  change,\n  lowerIsBetter,\n  href,\n  hrefLabel,\n  updatedAt,\n  loading,\n  embedded,\n  timezone,\n  locale,\n  linkComponent,\n  className,\n}: CategoryBarChartProps) {\n  const total = items.reduce((sum, item) => sum + item.value, 0);\n  const formatValue = formatValueProp ?? ((v: number) => v.toLocaleString(locale));\n\n  return (\n    <Chart\n      loading={loading}\n      embedded={embedded}\n      timezone={timezone}\n      locale={locale}\n      linkComponent={linkComponent}\n      className={className}>\n      <ChartHeader\n        title={title}\n        meta={meta}\n        value={value ?? total}\n        previousValue={previousValue}\n        previousLabel={previousLabel}\n        change={change}\n        lowerIsBetter={lowerIsBetter}\n        formatValue={formatHeadlineValue ?? formatValue}\n      />\n      <ChartContent\n        error={error}\n        empty={items.length === 0}\n        emptyMessage={emptyMessage}\n        className=\"flex flex-col gap-4\">\n        <div aria-hidden className=\"bg-muted flex h-4 overflow-hidden rounded-md\">\n          {total > 0 &&\n            items.map((item, index) => (\n              <div\n                key={item.id}\n                className=\"h-full\"\n                style={{ width: `${(item.value / total) * 100}%`, backgroundColor: item.color ?? chartColor(index) }}\n              />\n            ))}\n        </div>\n        <ul className=\"flex flex-col gap-2\">\n          {items.map((item, index) => (\n            <CategoryRow key={item.id} item={item} color={item.color ?? chartColor(index)} formatValue={formatValue} />\n          ))}\n        </ul>\n      </ChartContent>\n      <ChartFooter href={href} hrefLabel={hrefLabel} updatedAt={updatedAt} />\n    </Chart>\n  );\n}\n\nfunction CategoryRow({\n  item,\n  color,\n  formatValue,\n}: {\n  item: CategoryBarItem;\n  color: string;\n  formatValue: (value: number) => string;\n}) {\n  const { linkComponent: Anchor = 'a' } = useChartContext();\n  const className = 'flex items-center justify-between gap-3 border-b pb-2';\n\n  const content = (\n    <>\n      <div className=\"flex min-w-0 items-center gap-3\">\n        <div aria-hidden className=\"size-3 shrink-0 rounded-xs\" style={{ backgroundColor: color }} />\n        <div className=\"flex min-w-0 flex-col\">\n          <div className=\"truncate text-sm leading-tight\">{item.title}</div>\n          {item.subtitle && <div className=\"text-muted-foreground truncate text-xs leading-tight\">{item.subtitle}</div>}\n        </div>\n      </div>\n      <div className=\"shrink-0 text-sm leading-tight tabular-nums\">{formatValue(item.value)}</div>\n    </>\n  );\n\n  return (\n    <li data-slot=\"chart-category\">\n      {item.href ? (\n        <Anchor\n          href={item.href}\n          className={cn(\n            className,\n            'hover:bg-muted/50 focus-visible:ring-ring/50 rounded-xs transition-colors outline-none focus-visible:ring-[3px]'\n          )}>\n          {content}\n        </Anchor>\n      ) : (\n        <div className={className}>{content}</div>\n      )}\n    </li>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/charts/category-bar-chart.tsx"
    },
    {
      "path": "components/dentil/charts/chart.tsx",
      "content": "'use client';\n\nimport { AlertCircle, Loader2 } from 'lucide-react';\nimport { createContext, use, useMemo, type ComponentProps, type ReactNode } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport { Badge } from '../badge/badge';\nimport { Link, type LinkComponent } from '../link/link';\nimport { getPercentChange, type PercentChange } from './percent-change';\nimport { formatChartTime, type ChartDate } from './time';\n\ntype ChartContextValue = {\n  loading: boolean;\n  embedded: boolean;\n  timezone?: string;\n  locale?: string;\n  linkComponent?: LinkComponent;\n};\n\nconst ChartContext = createContext<ChartContextValue>({ loading: false, embedded: false });\n\n/** Shared state from the nearest `Chart`: loading, embedded, timezone, locale and link component. */\nexport function useChartContext() {\n  return use(ChartContext);\n}\n\nexport interface ChartProps extends ComponentProps<'div'> {\n  /** Shows a skeleton headline and a spinner in place of the plot. Each part can override it. */\n  loading?: boolean;\n  /** Compact mode for a chart inside another surface: no title or footer, and a 160px plot instead of 240px. */\n  embedded?: boolean;\n  /** IANA time zone for axis, tooltip and footer times. Omit it to use the runtime zone. */\n  timezone?: string;\n  /** BCP 47 language tag for dates and numbers. Omit it to use the runtime locale. */\n  locale?: string;\n  /** Renders links in the footer and category rows, e.g. `next/link`. Defaults to `'a'`. */\n  linkComponent?: LinkComponent;\n}\n\n/** Root of a chart. It has no border or padding, so place it in your own card or grid cell. */\nexport function Chart({\n  loading = false,\n  embedded = false,\n  timezone,\n  locale,\n  linkComponent,\n  className,\n  ...props\n}: ChartProps) {\n  const value = useMemo(\n    () => ({ loading, embedded, timezone, locale, linkComponent }),\n    [loading, embedded, timezone, locale, linkComponent]\n  );\n\n  return (\n    <ChartContext value={value}>\n      <div\n        data-slot=\"chart-root\"\n        data-embedded={embedded || undefined}\n        className={cn('flex min-w-0 flex-col', embedded ? 'gap-1' : 'gap-2.5', className)}\n        {...props}\n      />\n    </ChartContext>\n  );\n}\n\nexport interface ChartHeaderProps extends Omit<ComponentProps<'div'>, 'title'> {\n  title?: ReactNode;\n  /** Shown beside the title, for example \"All time\". */\n  meta?: ReactNode;\n  /** Headline. A number goes through `formatValue`; anything else renders as is. */\n  value?: ReactNode;\n  /** The comparison period's value. Drives the change badge and the \"… previous period\" line. */\n  previousValue?: number;\n  /** Replaces the \"… previous period\" line, for example \"98.1% previous period\". */\n  previousLabel?: ReactNode;\n  formatValue?: (value: number) => string;\n  /** The badge beside the headline. Worked out from `value` and `previousValue` when both are numbers. `false` hides it. */\n  change?: PercentChange | false;\n  /** Treat a decrease as the improvement when working out the badge color. */\n  lowerIsBetter?: boolean;\n  loading?: boolean;\n}\n\nexport function ChartHeader({\n  title,\n  meta,\n  value,\n  previousValue,\n  previousLabel,\n  formatValue: formatValueProp,\n  change,\n  lowerIsBetter,\n  loading: loadingProp,\n  className,\n  ...props\n}: ChartHeaderProps) {\n  const context = useChartContext();\n  const loading = loadingProp ?? context.loading;\n  const { embedded, locale } = context;\n  const formatValue = formatValueProp ?? ((v: number) => v.toLocaleString(locale));\n\n  const hasHeadline = value !== undefined && value !== null && value !== '';\n  if (embedded && !loading && !hasHeadline) return null;\n\n  const badge =\n    change === false\n      ? null\n      : (change ??\n        (typeof value === 'number' && previousValue !== undefined\n          ? getPercentChange(value, previousValue, { lowerIsBetter })\n          : null));\n\n  const previousLine =\n    previousLabel ?? (previousValue !== undefined ? `${formatValue(previousValue)} previous period` : null);\n\n  return (\n    <div data-slot=\"chart-header\" className={cn('flex flex-col gap-0.5', className)} {...props}>\n      {!embedded && (title || meta) && (\n        <div className=\"flex items-center justify-between gap-2\">\n          <div className=\"leading-none font-semibold\">{title}</div>\n          {meta && <div className=\"text-muted-foreground text-sm\">{meta}</div>}\n        </div>\n      )}\n      {loading ? (\n        <div className=\"bg-muted mt-1 h-8 w-24 animate-pulse rounded-md\" />\n      ) : (\n        hasHeadline && (\n          <div className=\"flex flex-col\">\n            <div className=\"flex items-center gap-2\">\n              <div className=\"text-2xl font-medium tabular-nums\">\n                {typeof value === 'number' ? formatValue(value) : value}\n              </div>\n              {badge && (\n                <Badge variant={badge.variant} className=\"tabular-nums\">\n                  {badge.label}\n                </Badge>\n              )}\n            </div>\n            {!embedded && previousLine && <div className=\"text-muted-foreground text-sm\">{previousLine}</div>}\n          </div>\n        )\n      )}\n    </div>\n  );\n}\n\nexport interface ChartContentProps extends ComponentProps<'div'> {\n  loading?: boolean;\n  /** Replaces the plot with a dashed error box. */\n  error?: ReactNode;\n  /** Replaces the plot with `emptyMessage`. */\n  empty?: boolean;\n  emptyMessage?: ReactNode;\n}\n\nexport function ChartContent({\n  loading: loadingProp,\n  error,\n  empty,\n  emptyMessage = 'No data',\n  className,\n  children,\n  ...props\n}: ChartContentProps) {\n  const context = useChartContext();\n  const loading = loadingProp ?? context.loading;\n  const height = context.embedded ? 'h-40' : 'h-60';\n\n  let content = children;\n  if (error) {\n    content = (\n      <div\n        role=\"alert\"\n        className={cn(\n          'text-muted-foreground flex flex-col items-center justify-center gap-2 rounded-md border border-dashed p-4 text-center text-sm sm:flex-row',\n          height\n        )}>\n        <AlertCircle aria-hidden className=\"text-foreground size-4 shrink-0\" />\n        {error}\n      </div>\n    );\n  } else if (loading) {\n    content = (\n      <div className={cn('flex items-center justify-center', height)}>\n        <Loader2 aria-label=\"Loading\" className=\"text-muted-foreground size-5 animate-spin\" />\n      </div>\n    );\n  } else if (empty) {\n    content = (\n      <div className={cn('text-muted-foreground flex items-center justify-center text-sm', height)}>{emptyMessage}</div>\n    );\n  }\n\n  return (\n    <div data-slot=\"chart-content\" aria-busy={loading || undefined} className={cn('min-w-0', className)} {...props}>\n      {content}\n    </div>\n  );\n}\n\nexport interface ChartFooterProps extends ComponentProps<'div'> {\n  /** Shows a \"View more\" link. */\n  href?: string;\n  /** Link text. */\n  hrefLabel?: ReactNode;\n  /** When the data was last refreshed, shown as \"Last updated HH:mm\". */\n  updatedAt?: ChartDate;\n}\n\nexport function ChartFooter({ href, hrefLabel = 'View more', updatedAt, className, ...props }: ChartFooterProps) {\n  const { embedded, timezone, locale, linkComponent } = useChartContext();\n  if (embedded || (!href && updatedAt === undefined)) return null;\n\n  const updated = formatChartTime(updatedAt, { timezone, locale });\n\n  return (\n    <div\n      data-slot=\"chart-footer\"\n      className={cn('flex min-h-5 items-center justify-between gap-4 text-sm', className)}\n      {...props}>\n      <div className=\"min-w-0\">\n        {href && (\n          <Link href={href} linkComponent={linkComponent}>\n            {hrefLabel}\n          </Link>\n        )}\n      </div>\n      {updated && <div className=\"text-muted-foreground shrink-0\">Last updated {updated}</div>}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/charts/chart.tsx"
    },
    {
      "path": "components/dentil/charts/colors.ts",
      "content": "import type { ChartSeries } from './tooltip';\n\n/** Default color for comparison series: the theme's muted text at reduced strength. */\nexport const COMPARISON_COLOR = 'color-mix(in oklab, var(--muted-foreground) 45%, transparent)';\n\n/** Theme chart color for position `index`, cycling through `--chart-1` to `--chart-5`. */\nexport const chartColor = (index: number) => `var(--chart-${(index % 5) + 1})`;\n\n/** Fills in each series' default color. Comparison series get `COMPARISON_COLOR`; the rest cycle the theme colors. */\nexport function resolveSeriesColors(series: ReadonlyArray<ChartSeries>) {\n  let index = 0;\n  return series.map((item) => ({\n    ...item,\n    color: item.color ?? (item.comparison ? COMPARISON_COLOR : chartColor(index++)),\n  }));\n}\n",
      "type": "registry:lib",
      "target": "components/dentil/charts/colors.ts"
    },
    {
      "path": "components/dentil/charts/cursor.tsx",
      "content": "/** Props Recharts injects into a custom tooltip cursor on a line chart. */\nexport interface ChartCursorProps {\n  points?: ReadonlyArray<{ x: number; y: number }>;\n  height?: number;\n  /** Band and rule color. */\n  fill?: string;\n  /** Band width in pixels. Recharts injects its own `width` (the plot width), so this has a different name. */\n  bandWidth?: number;\n}\n\n/** A soft band behind the hovered point with a 1px rule through its center. Pass it to `ChartTooltip`'s `cursor`. */\nexport function ChartCursor({ points, height, fill = 'var(--chart-1)', bandWidth = 24 }: ChartCursorProps) {\n  const top = points?.[0];\n  if (!top) return null;\n\n  const bottom = points?.[1];\n  const bandHeight = height ?? (bottom ? bottom.y - top.y : 0);\n  if (bandHeight <= 0) return null;\n\n  return (\n    <g data-slot=\"chart-cursor\" pointerEvents=\"none\">\n      <rect x={top.x - bandWidth / 2} y={top.y} width={bandWidth} height={bandHeight} fill={fill} fillOpacity={0.12} />\n      <rect x={top.x - 0.5} y={top.y} width={1} height={bandHeight} fill={fill} fillOpacity={0.5} />\n    </g>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/charts/cursor.tsx"
    },
    {
      "path": "components/dentil/charts/line-chart.tsx",
      "content": "'use client';\n\nimport { useMemo, type ReactNode } from 'react';\nimport { CartesianGrid, Line, LineChart as RechartsLineChart, XAxis, YAxis } from 'recharts';\n\nimport { ChartContainer, ChartTooltip, type ChartConfig } from '@/components/ui/chart';\nimport { cn } from '@/lib/utils';\n\nimport {\n  Chart,\n  ChartContent,\n  ChartFooter,\n  ChartHeader,\n  type ChartFooterProps,\n  type ChartHeaderProps,\n  type ChartProps,\n} from './chart';\nimport { resolveSeriesColors } from './colors';\nimport { ChartCursor } from './cursor';\nimport { formatChartDate, formatCompactNumber, maskFuture, toChartTime, type ChartDate, type ChartUnit } from './time';\nimport { ChartTooltipContent, type ChartSeries } from './tooltip';\n\n/** One bucket: its start `date`, plus a field per series key (and per `dateKey`). `null` leaves a gap. */\nexport type ChartPoint = { date: ChartDate } & { [key: string]: ChartDate | null | undefined };\n\nconst X_KEY = '__x';\n\ntype EdgeTickProps = {\n  x?: number | string;\n  y?: number | string;\n  payload?: { value?: unknown };\n  tickFormatter?: (value: unknown, index: number) => string;\n  index?: number;\n};\n\n/** First and last date labels, anchored inward so neither runs off the edge of the plot. */\nfunction EdgeTick({ x, y, payload, tickFormatter, index = 0, last }: EdgeTickProps & { last: boolean }) {\n  const label = tickFormatter ? tickFormatter(payload?.value, index) : String(payload?.value ?? '');\n  return (\n    <text\n      x={Number(x)}\n      y={Number(y)}\n      dy=\"0.71em\"\n      textAnchor={last ? 'end' : 'start'}\n      className=\"fill-muted-foreground text-xs\">\n      {label}\n    </text>\n  );\n}\n\nexport interface LineChartProps\n  extends\n    Pick<ChartProps, 'loading' | 'embedded' | 'timezone' | 'locale' | 'linkComponent' | 'className'>,\n    Pick<ChartHeaderProps, 'title' | 'meta' | 'value' | 'previousValue' | 'previousLabel' | 'change' | 'lowerIsBetter'>,\n    Pick<ChartFooterProps, 'href' | 'hrefLabel' | 'updatedAt'> {\n  data: ReadonlyArray<ChartPoint>;\n  series: ReadonlyArray<ChartSeries>;\n  /** Bucket size, which picks the date format. */\n  unit?: ChartUnit;\n  /** Formats the headline, the \"previous period\" line and tooltip values. */\n  formatValue?: (value: number) => string;\n  /** Formats axis and tooltip dates. Defaults to `formatChartDate` with `unit`, `timezone` and `locale`. */\n  formatDate?: (date: ChartDate) => string;\n  /** Formats y-axis ticks. Defaults to compact numbers such as `12.3K`. */\n  formatAxisValue?: (value: number) => string;\n  /** Show the first and last dates under the plot. */\n  showXAxis?: boolean;\n  /** Show the zero and maximum values beside the plot. */\n  showYAxis?: boolean;\n  /** Points after this are cut off on non-comparison series. Defaults to the current time. */\n  now?: ChartDate;\n  /** Replaces the plot with an error message. */\n  error?: ReactNode;\n  emptyMessage?: ReactNode;\n}\n\n/** A metric over time: headline, change badge, one or more lines with optional previous-period comparisons, and a footer. */\nexport function LineChart({\n  data,\n  series,\n  unit = 'day',\n  formatValue: formatValueProp,\n  formatDate: formatDateProp,\n  formatAxisValue: formatAxisValueProp,\n  showXAxis = true,\n  showYAxis = false,\n  now,\n  error,\n  emptyMessage,\n  title,\n  meta,\n  value,\n  previousValue,\n  previousLabel,\n  change,\n  lowerIsBetter,\n  href,\n  hrefLabel,\n  updatedAt,\n  loading,\n  embedded,\n  timezone,\n  locale,\n  linkComponent,\n  className,\n}: LineChartProps) {\n  const resolved = useMemo(() => resolveSeriesColors(series), [series]);\n\n  const config = useMemo(\n    () =>\n      Object.fromEntries(resolved.map((item) => [item.key, { label: item.label, color: item.color }])) as ChartConfig,\n    [resolved]\n  );\n\n  const plotted = useMemo(() => {\n    const liveKeys = resolved.filter((item) => !item.comparison).map((item) => item.key);\n    return maskFuture([...data], liveKeys, now).map((point): ChartPoint => ({\n      ...point,\n      [X_KEY]: toChartTime(point.date),\n    }));\n  }, [data, resolved, now]);\n\n  const maxValue =\n    Math.max(\n      0,\n      ...plotted.flatMap((point) =>\n        resolved.map((item) => {\n          const v = point[item.key];\n          return typeof v === 'number' && Number.isFinite(v) ? v : 0;\n        })\n      )\n    ) || 1;\n\n  const formatValue = formatValueProp ?? ((v: number) => v.toLocaleString(locale));\n  const formatDate = formatDateProp ?? ((date: ChartDate) => formatChartDate(date, { unit, timezone, locale }));\n  const formatAxisValue = formatAxisValueProp ?? ((v: number) => formatCompactNumber(v, locale));\n\n  const first = plotted[0];\n  const last = plotted[plotted.length - 1];\n  const ticks = [...new Set([first?.[X_KEY], last?.[X_KEY]])].filter((x): x is number => typeof x === 'number');\n\n  const comparisons = resolved.filter((item) => item.comparison);\n  const lines = resolved.filter((item) => !item.comparison);\n  const cursorColor = lines[0]?.color ?? 'var(--chart-1)';\n\n  return (\n    <Chart\n      loading={loading}\n      embedded={embedded}\n      timezone={timezone}\n      locale={locale}\n      linkComponent={linkComponent}\n      className={className}>\n      <ChartHeader\n        title={title}\n        meta={meta}\n        value={value}\n        previousValue={previousValue}\n        previousLabel={previousLabel}\n        change={change}\n        lowerIsBetter={lowerIsBetter}\n        formatValue={formatValue}\n      />\n      <ChartContent error={error} empty={plotted.length === 0} emptyMessage={emptyMessage}>\n        <ChartContainer config={config} className={cn('aspect-auto w-full', embedded ? 'h-40' : 'h-60')}>\n          <RechartsLineChart\n            accessibilityLayer\n            data={plotted}\n            margin={{ left: showYAxis ? 0 : 12, right: 12, top: 12 }}>\n            <CartesianGrid vertical={false} strokeDasharray=\"2 2\" stroke=\"var(--border)\" />\n            <XAxis\n              dataKey={X_KEY}\n              ticks={ticks}\n              interval={0}\n              tickLine={false}\n              tickMargin={12}\n              tick={(props: EdgeTickProps) => (\n                <EdgeTick {...props} last={ticks.length > 1 && props.payload?.value === ticks[ticks.length - 1]} />\n              )}\n              tickFormatter={(x: unknown) => (typeof x === 'number' ? formatDate(x) : '')}\n              stroke=\"var(--border)\"\n              padding={{ left: 12, right: 12 }}\n              hide={!showXAxis}\n            />\n            <YAxis\n              width=\"auto\"\n              axisLine={false}\n              tickLine={false}\n              tickCount={2}\n              tickFormatter={formatAxisValue}\n              domain={[0, maxValue]}\n              interval=\"preserveStartEnd\"\n              hide={!showYAxis}\n            />\n            <ChartTooltip\n              cursor={<ChartCursor fill={cursorColor} />}\n              content={<ChartTooltipContent series={resolved} formatValue={formatValue} formatDate={formatDate} />}\n            />\n            {comparisons.map((item) => (\n              <Line\n                key={item.key}\n                type=\"linear\"\n                dataKey={item.key}\n                stroke={item.color}\n                strokeWidth={2}\n                dot={false}\n                activeDot={false}\n                connectNulls={false}\n              />\n            ))}\n            {lines.map((item) => (\n              <Line\n                key={item.key}\n                type=\"linear\"\n                dataKey={item.key}\n                stroke={item.color}\n                strokeWidth={2}\n                dot={false}\n                connectNulls={false}\n                activeDot={{ r: 5, fill: item.color, stroke: 'var(--background)', strokeWidth: 2 }}\n              />\n            ))}\n          </RechartsLineChart>\n        </ChartContainer>\n      </ChartContent>\n      <ChartFooter href={href} hrefLabel={hrefLabel} updatedAt={updatedAt} />\n    </Chart>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/charts/line-chart.tsx"
    },
    {
      "path": "components/dentil/charts/percent-change.ts",
      "content": "export type PercentChange = {\n  /** Signed percentage, for example `+12.5%`, `-3.0%` or `+140%`. */\n  label: string;\n  /** Badge color: `green` for an improvement, `yellow` for a decline, `zinc` for no change. */\n  variant: 'green' | 'yellow' | 'zinc';\n};\n\nexport type PercentChangeOptions = {\n  /** Treat a decrease as the improvement, for metrics such as churn, refunds or latency. */\n  lowerIsBetter?: boolean;\n};\n\n/**\n * Change from `previous` to `current` as a badge label and color. A rise from zero reads as `+100%`, since there is no\n * finite percentage to show. Changes of 100% or more drop the decimal.\n */\nexport function getPercentChange(current: number, previous: number, options: PercentChangeOptions = {}): PercentChange {\n  const { lowerIsBetter = false } = options;\n\n  if (current === previous) return { label: '0%', variant: 'zinc' };\n\n  if (previous === 0) {\n    const up = current > 0;\n    return { label: up ? '+100%' : '-100%', variant: up !== lowerIsBetter ? 'green' : 'yellow' };\n  }\n\n  const change = ((current - previous) / Math.abs(previous)) * 100;\n  const prefix = change > 0 ? '+' : '';\n  const improved = lowerIsBetter ? change < 0 : change > 0;\n\n  return {\n    label: `${prefix}${Math.abs(change) >= 100 ? change.toFixed(0) : change.toFixed(1)}%`,\n    variant: improved ? 'green' : 'yellow',\n  };\n}\n",
      "type": "registry:lib",
      "target": "components/dentil/charts/percent-change.ts"
    },
    {
      "path": "components/dentil/charts/time.ts",
      "content": "/** Unix timestamps in seconds are what most APIs return; anything above this is treated as milliseconds. */\nconst MAX_UNIX_SECONDS = 1e11;\n\n/** Unix seconds, unix milliseconds, an ISO string or a `Date`. */\nexport type ChartDate = number | string | Date;\n\n/** Size of the bucket each point covers. Picks the axis and tooltip date format. */\nexport type ChartUnit = 'hour' | 'day' | 'week' | 'month';\n\nexport type ChartDateFormatOptions = {\n  unit?: ChartUnit;\n  /** IANA time zone, for example `Europe/London`. Omit it to use the runtime zone. */\n  timezone?: string;\n  /** BCP 47 language tag. Omit it to use the runtime locale. */\n  locale?: string;\n};\n\n/** Milliseconds since the epoch, or `null` when the value cannot be parsed. */\nexport function toChartTime(value: ChartDate | null | undefined): number | null {\n  if (value === null || value === undefined || value === '') return null;\n  if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.getTime();\n  if (typeof value === 'number') {\n    if (!Number.isFinite(value)) return null;\n    return value < MAX_UNIX_SECONDS ? value * 1000 : value;\n  }\n  const time = new Date(value).getTime();\n  return Number.isNaN(time) ? null : time;\n}\n\nconst DATE_FORMATS: Record<ChartUnit, Intl.DateTimeFormatOptions> = {\n  hour: { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' },\n  day: { day: 'numeric', month: 'short', year: '2-digit' },\n  week: { day: 'numeric', month: 'short', year: '2-digit' },\n  month: { month: 'short', year: '2-digit' },\n};\n\nfunction dateTimeFormat(options: Intl.DateTimeFormatOptions, timezone?: string, locale?: string) {\n  try {\n    return new Intl.DateTimeFormat(locale, { ...options, timeZone: timezone });\n  } catch {\n    // A zone or locale `Intl` rejects falls back to UTC and the runtime locale, so a bad setting does not throw.\n    return new Intl.DateTimeFormat(undefined, { ...options, timeZone: timezone ? 'UTC' : undefined });\n  }\n}\n\n/** Formats a bucket start for the axis and tooltip: `3 Nov 26` for days and weeks, `Nov 26` for months, `14:00` for hours. */\nexport function formatChartDate(value: ChartDate | null | undefined, options: ChartDateFormatOptions = {}) {\n  const time = toChartTime(value);\n  if (time === null) return '';\n  return dateTimeFormat(DATE_FORMATS[options.unit ?? 'day'], options.timezone, options.locale).format(time);\n}\n\n/** Formats the footer's \"Last updated\" time as 24-hour `HH:mm`. */\nexport function formatChartTime(\n  value: ChartDate | null | undefined,\n  options: Omit<ChartDateFormatOptions, 'unit'> = {}\n) {\n  const time = toChartTime(value);\n  if (time === null) return '';\n  return dateTimeFormat(DATE_FORMATS.hour, options.timezone, options.locale).format(time);\n}\n\n/** Short axis numbers: `950`, `12.3K`, `4.5M`. */\nexport function formatCompactNumber(value: number, locale?: string) {\n  return new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: 1 }).format(value);\n}\n\n/**\n * Sets `keys` to `null` on points whose bucket starts after `now`. Recharts joins adjacent numbers, so future buckets\n * an API fills with `0` would read as a real drop. A `null` ends the line at the last bucket that has started.\n */\nexport function maskFuture<T extends { date: ChartDate }>(\n  data: T[],\n  keys: readonly string[],\n  now: ChartDate = Date.now()\n): T[] {\n  const cutoff = toChartTime(now) ?? Date.now();\n  if (keys.length === 0) return data;\n\n  return data.map((point) => {\n    const time = toChartTime(point.date);\n    if (time === null || time <= cutoff) return point;\n\n    const masked: Record<string, unknown> = { ...point };\n    for (const key of keys) {\n      if (key in masked) masked[key] = null;\n    }\n    return masked as T;\n  });\n}\n",
      "type": "registry:lib",
      "target": "components/dentil/charts/time.ts"
    },
    {
      "path": "components/dentil/charts/tooltip.tsx",
      "content": "import { cn } from '@/lib/utils';\n\nimport type { ChartDate } from './time';\n\n/** A line on a `LineChart`. */\nexport interface ChartSeries {\n  /** Field on each point that holds this series' value. */\n  key: string;\n  label: string;\n  /** Any CSS color. Defaults to `var(--chart-1)` through `var(--chart-5)` in order, or a muted gray for a comparison. */\n  color?: string;\n  /** A previous-period line: drawn underneath with no hover dot, never cut off at today, and left out of the axis label. */\n  comparison?: boolean;\n  /** Field on each point that holds the date this value belongs to. The tooltip shows that date in place of `label`. */\n  dateKey?: string;\n}\n\ntype TooltipEntry = {\n  dataKey?: unknown;\n  value?: unknown;\n  payload?: Record<string, unknown>;\n};\n\nexport interface ChartTooltipContentProps {\n  /** Injected by Recharts. */\n  active?: boolean;\n  /** Injected by Recharts. */\n  payload?: ReadonlyArray<TooltipEntry>;\n  /** Rows, in this order. Series without a value at the hovered point are skipped. */\n  series: ReadonlyArray<ChartSeries & { color: string }>;\n  formatValue?: (value: number) => string;\n  formatDate?: (date: ChartDate) => string;\n  className?: string;\n}\n\n/**\n * Tooltip body for `ChartTooltip`'s `content`. When any series has a `dateKey`, each row is labelled with its own date\n * (this period against the previous one). Otherwise the hovered date is the heading and rows use the series labels.\n */\nexport function ChartTooltipContent({\n  active,\n  payload,\n  series,\n  formatValue = (value) => value.toLocaleString(),\n  formatDate = (date) => String(date),\n  className,\n}: ChartTooltipContentProps) {\n  if (!active || !payload?.length) return null;\n\n  const point = payload[0]?.payload;\n  if (!point) return null;\n\n  const rows = series.flatMap((item) => {\n    const value = point[item.key];\n    return typeof value === 'number' && Number.isFinite(value) ? [{ item, value }] : [];\n  });\n  if (rows.length === 0) return null;\n\n  const dated = series.some((item) => item.dateKey);\n  const pointDate = point.date as ChartDate | undefined;\n\n  const rowLabel = (item: ChartSeries) => {\n    if (!dated) return item.label;\n    const date = (item.dateKey ? point[item.dateKey] : pointDate) as ChartDate | null | undefined;\n    return date === null || date === undefined ? item.label : formatDate(date);\n  };\n\n  return (\n    <div\n      data-slot=\"chart-tooltip\"\n      className={cn(\n        'bg-popover text-popover-foreground grid min-w-32 gap-1.5 rounded-lg border px-3 py-1.5 text-xs shadow-lg',\n        className\n      )}>\n      {!dated && pointDate !== undefined && <div className=\"font-medium\">{formatDate(pointDate)}</div>}\n      {rows.map(({ item, value }) => (\n        <div key={item.key} className=\"flex items-center justify-between gap-3\">\n          <div className=\"flex min-w-0 items-center gap-2\">\n            <div aria-hidden className=\"size-2 shrink-0 rounded-xs\" style={{ backgroundColor: item.color }} />\n            <span className=\"text-muted-foreground truncate\">{rowLabel(item)}</span>\n          </div>\n          <span className=\"text-foreground font-mono font-medium tabular-nums\">{formatValue(value)}</span>\n        </div>\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/charts/tooltip.tsx"
    },
    {
      "path": "components/dentil/charts/use-in-view-fetch.ts",
      "content": "'use client';\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nexport type UseInViewFetchOptions = {\n  /** Grows the viewport so a chart starts loading just before it scrolls in. */\n  rootMargin?: string;\n};\n\n/**\n * Runs `fetch` once the element behind `ref` is near the viewport, then again only when `deps` change. Scrolling a\n * chart away and back does not refetch. If `deps` change while it is off screen, the fetch waits until it is back.\n *\n * `deps` are compared by value with `JSON.stringify`, so pass primitives such as timestamps.\n */\nexport function useInViewFetch<T extends Element = HTMLDivElement>(\n  fetch: () => void | Promise<void>,\n  deps: readonly unknown[],\n  { rootMargin = '200px 0px' }: UseInViewFetchOptions = {}\n) {\n  const [inView, setInView] = useState(false);\n\n  const fetchRef = useRef(fetch);\n  useEffect(() => {\n    fetchRef.current = fetch;\n  });\n\n  const key = JSON.stringify(deps);\n  const lastFetchedKey = useRef<string | null>(null);\n\n  const ref = useCallback(\n    (node: T | null) => {\n      if (!node) return;\n      if (typeof IntersectionObserver === 'undefined') {\n        setInView(true);\n        return;\n      }\n      const observer = new IntersectionObserver(\n        (entries) => {\n          const entry = entries[entries.length - 1];\n          if (entry) setInView(entry.isIntersecting);\n        },\n        { rootMargin }\n      );\n      observer.observe(node);\n      return () => observer.disconnect();\n    },\n    [rootMargin]\n  );\n\n  useEffect(() => {\n    if (!inView || lastFetchedKey.current === key) return;\n    lastFetchedKey.current = key;\n    void fetchRef.current();\n  }, [inView, key]);\n\n  return { ref, inView };\n}\n",
      "type": "registry:lib",
      "target": "components/dentil/charts/use-in-view-fetch.ts"
    }
  ],
  "type": "registry:block"
}
