{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart",
  "type": "registry:ui",
  "title": "Chart",
  "dependencies": [
    "@base-ui-next/react",
    "@unovis/react@1.7.1",
    "@unovis/ts@1.7.1"
  ],
  "registryDependencies": [
    "https://hamur.dev/r/react/utils.json"
  ],
  "files": [
    {
      "path": "react/chart.tsx",
      "content": "'use client'\n\nimport * as React from 'react' // base-ui-next/ui chart@0.1.0\nimport { Toolbar as ToolbarPrimitive } from '@base-ui-next/react/toolbar'\nimport { Tooltip as TooltipPrimitive } from '@base-ui-next/react/tooltip'\nimport { VisXYContainer } from '@unovis/react'\nimport { cn } from '@/lib/utils'\n\nconst chartContainerClassName =\n  'flex aspect-video flex-col justify-center text-xs [--vis-axis-domain-color:var(--border)] [--vis-axis-font-family:inherit] [--vis-axis-grid-color:var(--border)] [--vis-axis-tick-color:var(--border)] [--vis-axis-tick-label-color:var(--muted-foreground)] [--vis-color0:var(--chart-1)] [--vis-color1:var(--chart-2)] [--vis-color2:var(--chart-3)] [--vis-color3:var(--chart-4)] [--vis-color4:var(--chart-5)] [--vis-font-family:inherit]'\n\n/** The Unovis XY container: the plot fills what the legend leaves. */\nconst chartPlotClassName = 'relative min-h-0 w-full flex-1'\n\n/** The table view: every value of the chart, for screen readers. */\nconst chartTableClassName = 'sr-only'\n\n/** The hover and keyboard layer over the plot area: one column per datum. */\nconst chartTooltipClassName = 'absolute grid outline-hidden'\n\nconst chartTooltipTriggerClassName =\n  'relative h-full min-w-0 outline-hidden focus-visible:inset-ring-2 focus-visible:inset-ring-ring/50'\n\n/** `cursor=\"band\"`: the column under the pointer or focus is shaded, base-vega's `fill-muted`. */\nconst chartTooltipCursorBandClassName = 'data-popup-open:bg-muted/50'\n\n/** `cursor=\"line\"`: a hairline at the column's centre, base-vega's `stroke-border`. */\nconst chartTooltipCursorLineClassName =\n  'before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-border before:opacity-0 data-popup-open:before:opacity-100'\n\nconst chartTooltipPositionerClassName = 'isolate z-50'\n\nconst chartTooltipPopupClassName =\n  'z-50 origin-(--transform-origin) data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95'\n\nconst chartTooltipContentClassName =\n  'grid min-w-32 items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl'\n\nconst chartTooltipLabelClassName = 'font-medium'\n\nconst chartTooltipListClassName = 'grid gap-1.5'\n\nconst chartTooltipItemClassName =\n  'flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground'\n\n/** `indicator=\"dot\"`, added to the item. */\nconst chartTooltipItemDotClassName = 'items-center'\n\nconst chartTooltipIndicatorClassName =\n  'shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)'\n\nconst chartTooltipIndicatorDotClassName = 'h-2.5 w-2.5'\n\nconst chartTooltipIndicatorLineClassName = 'w-1'\n\nconst chartTooltipIndicatorDashedClassName =\n  'w-0 border-[1.5px] border-dashed bg-transparent'\n\n/** `indicator=\"dashed\"` with a single series, whose label then sits beside the value. */\nconst chartTooltipIndicatorNestedDashedClassName = 'my-0.5'\n\nconst chartTooltipValueRowClassName = 'flex flex-1 justify-between leading-none'\n\nconst chartTooltipValueRowNestedClassName = 'items-end'\n\nconst chartTooltipValueRowFlatClassName = 'items-center'\n\nconst chartTooltipNameClassName = 'text-muted-foreground'\n\nconst chartTooltipValueClassName = 'font-mono font-medium text-foreground tabular-nums'\n\nconst chartLegendContentClassName = 'flex items-center justify-center gap-4'\n\n/** `verticalAlign=\"top\"`: the legend moves above the plot. */\nconst chartLegendContentTopClassName = 'order-first pb-3'\n\nconst chartLegendContentBottomClassName = 'pt-3'\n\nconst chartLegendItemClassName =\n  'flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground'\n\nconst chartLegendIndicatorClassName = 'h-2 w-2 shrink-0 rounded-[2px]'\n\n// Format: { THEME_NAME: CSS_SELECTOR }\nconst THEMES = { light: '', dark: '.dark' } as const\n\n// The plot area's inset. Unovis's auto margin is off, so the axes draw into this margin and the\n// tooltip layer, positioned from the same numbers, covers exactly the plot.\nconst MARGIN = { top: 8, right: 12, bottom: 24, left: 40 }\n\nexport type ChartConfig = Record<\n  string,\n  {\n    label?: React.ReactNode\n    icon?: React.ComponentType\n  } & (\n    | { color?: string; theme?: never }\n    | { color?: never; theme: Record<keyof typeof THEMES, string> }\n  )\n>\n\ntype ChartDatum = Record<string, unknown>\n\ntype ChartMargin = { top?: number; right?: number; bottom?: number; left?: number }\n\ntype ChartContextProps = {\n  config: ChartConfig\n  data: readonly ChartDatum[]\n  index: string\n  margin: Required<ChartMargin>\n}\n\nconst ChartContext = React.createContext<ChartContextProps | null>(null)\n\nfunction useChart() {\n  const context = React.useContext(ChartContext)\n\n  if (!context) {\n    throw new Error(\n      'Base UI: chart parts must be placed inside a <ChartContainer />. ' +\n        'They read the config and data from it. ' +\n        'Render ChartTooltip, ChartLegend and their contents as children of ChartContainer.',\n    )\n  }\n\n  return context\n}\n\n/** The series of a chart: the keys of its config, in order. */\ntype ChartSeries = { dataKey: string; name: string; color: string }\n\nfunction seriesOf(config: ChartConfig): ChartSeries[] {\n  return Object.keys(config).map((key) => ({\n    dataKey: key,\n    name: key,\n    color: `var(--color-${key})`,\n  }))\n}\n\nfunction formatValue(value: unknown) {\n  return typeof value === 'number' ? value.toLocaleString() : String(value)\n}\n\nfunction textOf(node: React.ReactNode, fallback: string) {\n  return typeof node === 'string' || typeof node === 'number' ? String(node) : fallback\n}\n\n/**\n * The chart: the config's colours as `--color-<key>`, a Unovis XY container for the marks and\n * axes (its children), the legend and a table view of `data`. Each datum's x is its position:\n * give the Unovis components `x={(_, i) => i}`.\n */\nfunction ChartContainer({\n  id,\n  className,\n  children,\n  config,\n  data,\n  index,\n  margin,\n  ...props\n}: React.ComponentProps<'div'> & {\n  config: ChartConfig\n  /** The chart's data, one object per x position. */\n  data: readonly ChartDatum[]\n  /** The key of each datum's label: the x axis category, the tooltip's title, the table's rows. */\n  index: string\n  /** The plot area's inset in pixels, where the axes draw. */\n  margin?: ChartMargin\n}) {\n  const uniqueId = React.useId()\n  const chartId = `chart-${id ?? uniqueId.replace(/:/g, '')}`\n  const inset = { ...MARGIN, ...margin }\n  const series = seriesOf(config)\n  // A legend is a sibling of the plot, not one of its children; one is added for two or more series\n  // when the children have none.\n  const nodes = React.Children.toArray(children)\n  const legends = nodes.filter((node) => React.isValidElement(node) && node.type === ChartLegend)\n  const marks = nodes.filter((node) => !legends.includes(node))\n\n  return (\n    <ChartContext.Provider value={{ config, data, index, margin: inset }}>\n      <div\n        data-slot=\"chart\"\n        data-chart={chartId}\n        className={cn(chartContainerClassName, className)}\n        {...props}\n      >\n        <ChartStyle id={chartId} config={config} />\n        <VisXYContainer\n          data={data as ChartDatum[]}\n          margin={inset}\n          autoMargin={false}\n          // Datum i spans [i - 0.5, i + 0.5]: bars and points sit at the centre of equal columns.\n          xDomain={[-0.5, data.length - 0.5]}\n          bleed={{ left: 0, right: 0 }}\n          className={chartPlotClassName}\n        >\n          {marks}\n        </VisXYContainer>\n        {legends.length > 0 ? (\n          legends\n        ) : series.length > 1 ? (\n          <ChartLegend content={<ChartLegendContent />} />\n        ) : null}\n        <table data-slot=\"chart-table\" className={chartTableClassName}>\n          <thead>\n            <tr>\n              <th scope=\"col\">{config[index]?.label ?? index}</th>\n              {series.map((item) => (\n                <th key={item.dataKey} scope=\"col\">\n                  {config[item.dataKey]?.label ?? item.dataKey}\n                </th>\n              ))}\n            </tr>\n          </thead>\n          <tbody>\n            {data.map((datum, row) => (\n              <tr key={row}>\n                <th scope=\"row\">{formatValue(datum[index])}</th>\n                {series.map((item) => (\n                  <td key={item.dataKey}>{formatValue(datum[item.dataKey])}</td>\n                ))}\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      </div>\n    </ChartContext.Provider>\n  )\n}\n\nconst ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {\n  // A series without `color` or `theme` takes the next of the five chart tokens.\n  const colorConfig = Object.entries(config).map(([key, itemConfig], position) => [\n    key,\n    itemConfig.theme ??\n      itemConfig.color ??\n      (position < 5 ? `var(--chart-${position + 1})` : undefined),\n  ]) as [string, string | Record<keyof typeof THEMES, string> | undefined][]\n\n  if (!colorConfig.some(([, color]) => color)) {\n    return null\n  }\n\n  return (\n    <style\n      dangerouslySetInnerHTML={{\n        __html: Object.entries(THEMES)\n          .map(\n            ([theme, prefix]) => `\n${prefix} [data-chart=${id}] {\n${colorConfig\n  .map(([key, color]) => {\n    const value = typeof color === 'object' ? color[theme as keyof typeof THEMES] : color\n    return value ? `  --color-${key}: ${value};` : null\n  })\n  .filter(Boolean)\n  .join('\\n')}\n}\n`,\n          )\n          .join('\\n'),\n      }}\n    />\n  )\n}\n\ntype ChartTooltipItem = ChartSeries & { value: unknown; payload: ChartDatum }\n\n/**\n * The tooltip, on Base UI's Tooltip: one column per datum over the plot area, a toolbar of\n * buttons (Tab reaches it, the arrow keys move between data), each a trigger that opens the\n * tooltip on hover and on keyboard focus with every series at that x.\n */\nfunction ChartTooltip({\n  content = <ChartTooltipContent />,\n  cursor = 'band',\n  className,\n  style,\n  'aria-label': ariaLabel = 'Chart data',\n  ...props\n}: Omit<ToolbarPrimitive.Root.Props, 'content'> & {\n  /** The tooltip's content, given `active`, `payload` and `label` for the datum. */\n  content?: React.ReactElement<ChartTooltipContentProps>\n  /** What marks the datum under the pointer or focus: a shaded column, a hairline, or nothing. */\n  cursor?: 'band' | 'line' | false\n}) {\n  const { config, data, index, margin } = useChart()\n  const series = seriesOf(config)\n  const itemsOf = (datum: ChartDatum): ChartTooltipItem[] =>\n    series\n      .filter((item) => datum[item.dataKey] !== undefined)\n      .map((item) => ({\n        ...item,\n        value: datum[item.dataKey],\n        payload: datum,\n      }))\n\n  return (\n    <TooltipPrimitive.Root>\n      {({ payload }) => {\n        // The column of the trigger that opened the tooltip.\n        const position = payload as number | undefined\n        return (\n          <React.Fragment>\n            <ToolbarPrimitive.Root\n              data-slot=\"chart-tooltip\"\n              aria-label={ariaLabel}\n              className={cn(chartTooltipClassName, className)}\n              style={{\n                top: margin.top,\n                right: margin.right,\n                bottom: margin.bottom,\n                left: margin.left,\n                gridTemplateColumns: `repeat(${data.length}, minmax(0, 1fr))`,\n                ...style,\n              }}\n              {...props}\n            >\n              {data.map((datum, column) => (\n                <TooltipPrimitive.Trigger\n                  key={column}\n                  payload={column}\n                  delay={0}\n                  closeDelay={0}\n                  render={<ToolbarPrimitive.Button />}\n                  data-slot=\"chart-tooltip-trigger\"\n                  aria-label={[\n                    formatValue(datum[index]),\n                    ...itemsOf(datum).map(\n                      (item) =>\n                        `${textOf(config[item.dataKey]?.label, item.dataKey)} ${formatValue(item.value)}`,\n                    ),\n                  ].join(', ')}\n                  className={cn(\n                    chartTooltipTriggerClassName,\n                    cursor === 'band' && chartTooltipCursorBandClassName,\n                    cursor === 'line' && chartTooltipCursorLineClassName,\n                  )}\n                />\n              ))}\n            </ToolbarPrimitive.Root>\n            <TooltipPrimitive.Portal>\n              <TooltipPrimitive.Positioner\n                side=\"top\"\n                sideOffset={8}\n                className={chartTooltipPositionerClassName}\n              >\n                <TooltipPrimitive.Popup\n                  data-slot=\"chart-tooltip-popup\"\n                  className={chartTooltipPopupClassName}\n                >\n                  {position !== undefined && data[position]\n                    ? React.cloneElement(content, {\n                        active: true,\n                        payload: itemsOf(data[position]),\n                        label: data[position][index],\n                      })\n                    : null}\n                </TooltipPrimitive.Popup>\n              </TooltipPrimitive.Positioner>\n            </TooltipPrimitive.Portal>\n          </React.Fragment>\n        )\n      }}\n    </TooltipPrimitive.Root>\n  )\n}\n\ntype ChartTooltipContentProps = React.ComponentProps<'div'> & {\n  active?: boolean\n  payload?: ChartTooltipItem[]\n  label?: unknown\n  hideLabel?: boolean\n  hideIndicator?: boolean\n  indicator?: 'line' | 'dot' | 'dashed'\n  labelFormatter?: (label: React.ReactNode, payload: ChartTooltipItem[]) => React.ReactNode\n  labelClassName?: string\n  formatter?: (\n    value: unknown,\n    name: string,\n    item: ChartTooltipItem,\n    index: number,\n    payload: ChartDatum,\n  ) => React.ReactNode\n  color?: string\n  nameKey?: string\n  labelKey?: string\n}\n\nfunction ChartTooltipContent({\n  active,\n  payload,\n  className,\n  indicator = 'dot',\n  hideLabel = false,\n  hideIndicator = false,\n  label,\n  labelFormatter,\n  labelClassName,\n  formatter,\n  color,\n  nameKey,\n  labelKey,\n  ...props\n}: ChartTooltipContentProps) {\n  const { config } = useChart()\n\n  if (!active || !payload?.length) {\n    return null\n  }\n\n  const [first] = payload\n  const labelValue = labelKey ? first.payload[labelKey] : label\n  const value =\n    typeof labelValue === 'string'\n      ? (config[labelValue]?.label ?? labelValue)\n      : labelValue == null\n        ? null\n        : formatValue(labelValue)\n  const tooltipLabel =\n    hideLabel || (!value && !labelFormatter) ? null : (\n      <div className={cn(chartTooltipLabelClassName, labelClassName)}>\n        {labelFormatter ? labelFormatter(value, payload) : value}\n      </div>\n    )\n  const nestLabel = payload.length === 1 && indicator !== 'dot'\n\n  return (\n    <div\n      data-slot=\"chart-tooltip-content\"\n      className={cn(chartTooltipContentClassName, className)}\n      {...props}\n    >\n      {!nestLabel ? tooltipLabel : null}\n      <div className={chartTooltipListClassName}>\n        {payload.map((item, position) => {\n          const key = nameKey ? String(item.payload[nameKey] ?? item.dataKey) : item.dataKey\n          const itemConfig = config[key] ?? config[item.dataKey]\n          const indicatorColor = color ?? item.color\n\n          return (\n            <div\n              key={item.dataKey}\n              className={cn(\n                chartTooltipItemClassName,\n                indicator === 'dot' && chartTooltipItemDotClassName,\n              )}\n            >\n              {formatter && item.value !== undefined ? (\n                formatter(item.value, item.name, item, position, item.payload)\n              ) : (\n                <React.Fragment>\n                  {itemConfig?.icon ? (\n                    <itemConfig.icon />\n                  ) : (\n                    !hideIndicator && (\n                      <div\n                        data-slot=\"chart-tooltip-indicator\"\n                        className={cn(\n                          chartTooltipIndicatorClassName,\n                          indicator === 'dot' && chartTooltipIndicatorDotClassName,\n                          indicator === 'line' && chartTooltipIndicatorLineClassName,\n                          indicator === 'dashed' && chartTooltipIndicatorDashedClassName,\n                          nestLabel &&\n                            indicator === 'dashed' &&\n                            chartTooltipIndicatorNestedDashedClassName,\n                        )}\n                        style={\n                          {\n                            '--color-bg': indicatorColor,\n                            '--color-border': indicatorColor,\n                          } as React.CSSProperties\n                        }\n                      />\n                    )\n                  )}\n                  <div\n                    className={cn(\n                      chartTooltipValueRowClassName,\n                      nestLabel\n                        ? chartTooltipValueRowNestedClassName\n                        : chartTooltipValueRowFlatClassName,\n                    )}\n                  >\n                    <div className={chartTooltipListClassName}>\n                      {nestLabel ? tooltipLabel : null}\n                      <span className={chartTooltipNameClassName}>\n                        {itemConfig?.label ?? item.name}\n                      </span>\n                    </div>\n                    {item.value != null && (\n                      <span className={chartTooltipValueClassName}>{formatValue(item.value)}</span>\n                    )}\n                  </div>\n                </React.Fragment>\n              )}\n            </div>\n          )\n        })}\n      </div>\n    </div>\n  )\n}\n\ntype ChartLegendItem = ChartSeries & { value: string }\n\n/**\n * The legend, below the plot (or above it, with `verticalAlign=\"top\"`); for one series there is\n * none, the chart's title names it.\n */\nfunction ChartLegend({\n  content = <ChartLegendContent />,\n  verticalAlign = 'bottom',\n}: {\n  /** The legend's content, given `payload` (one item per series) and `verticalAlign`. */\n  content?: React.ReactElement<ChartLegendContentProps>\n  verticalAlign?: 'top' | 'bottom'\n}) {\n  const { config } = useChart()\n  const series = seriesOf(config)\n\n  if (series.length < 2) {\n    return null\n  }\n\n  return React.cloneElement(content, {\n    payload: series.map((item) => ({ ...item, value: item.dataKey })),\n    verticalAlign: content.props.verticalAlign ?? verticalAlign,\n  })\n}\n\ntype ChartLegendContentProps = React.ComponentProps<'div'> & {\n  hideIcon?: boolean\n  nameKey?: string\n  payload?: ChartLegendItem[]\n  verticalAlign?: 'top' | 'bottom'\n}\n\nfunction ChartLegendContent({\n  className,\n  hideIcon = false,\n  payload,\n  verticalAlign = 'bottom',\n  nameKey,\n  ...props\n}: ChartLegendContentProps) {\n  const { config } = useChart()\n\n  if (!payload?.length) {\n    return null\n  }\n\n  return (\n    <div\n      data-slot=\"chart-legend-content\"\n      className={cn(\n        chartLegendContentClassName,\n        verticalAlign === 'top'\n          ? chartLegendContentTopClassName\n          : chartLegendContentBottomClassName,\n        className,\n      )}\n      {...props}\n    >\n      {payload.map((item) => {\n        const itemConfig = config[nameKey ?? item.dataKey]\n\n        return (\n          <div key={item.dataKey} className={chartLegendItemClassName}>\n            {itemConfig?.icon && !hideIcon ? (\n              <itemConfig.icon />\n            ) : (\n              <div\n                data-slot=\"chart-legend-indicator\"\n                className={chartLegendIndicatorClassName}\n                style={{ backgroundColor: item.color }}\n              />\n            )}\n            {itemConfig?.label}\n          </div>\n        )\n      })}\n    </div>\n  )\n}\n\nexport {\n  ChartContainer,\n  ChartTooltip,\n  ChartTooltipContent,\n  ChartLegend,\n  ChartLegendContent,\n  ChartStyle,\n}\n",
      "type": "registry:ui",
      "target": "@ui/chart.tsx"
    }
  ],
  "meta": {
    "baseUiNext": {
      "version": "0.1.0",
      "hash": "c685a35632a069247fc27520b1b07e87428b450d244d0baaa79952476ccf2ea5",
      "files": {
        "@ui/chart.tsx": "6ee5e1e9f8764f3b4f6ccf39f3c75191c02ac35ac085a3adf833a1d05d6b1fc6"
      }
    }
  }
}
