{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "candlestick-chart",
  "type": "registry:component",
  "title": "Candlestick Chart",
  "description": "Opening, highest, lowest and closing values per period (a price, a reading): a thin line from low to high, a body from open to close, filled when it closed lower and hollow when it closed higher, so the direction is never colour alone.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale"
  ],
  "devDependencies": [
    "@types/d3-scale"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/candlestick-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/candlestick-chart.tsx",
      "content": "\"use client\";\n/**\n * @name candlestick-chart\n * @category viz\n * @description Opening, highest, lowest and closing values per period (a price, a reading): a thin line from low to high, a body from open to close, filled when it closed lower and hollow when it closed higher, so the direction is never colour alone.\n * @when Showing the range and the direction of a value within each period: prices by day, temperatures by day with their extremes. For the close alone use line-chart; for spread across many observations use box-plot.\n * @example\n * <CandlestickChart\n *   label=\"Price by day\"\n *   data={[\n *     { day: new Date(\"2026-03-02\"), open: 10, high: 12, low: 9.5, close: 11.4 },\n *     { day: new Date(\"2026-03-03\"), open: 11.4, high: 11.8, low: 10.1, close: 10.3 },\n *     { day: new Date(\"2026-03-04\"), open: 10.3, high: 11, low: 10, close: 10.9 },\n *   ]}\n *   x=\"day\"\n * />\n */\nimport { scaleBand } from \"d3-scale\";\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartEmpty,\n  ChartGrid,\n  chartLinear,\n  ChartSvg,\n  ChartTooltip,\n  dateFormatter,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  widestText,\n  type ChartBaseProps,\n} from \"@/components/viz/chart\";\n\nexport type CandlestickChartLabels = { open: string; high: string; low: string; close: string; up: string; down: string; period: string };\n\nexport type CandlestickChartProps<T extends object> = ChartBaseProps & {\n  /** One object per period, in time order. */\n  data: readonly T[];\n  /** The field naming the period: a Date, a number or a text. */\n  x: keyof T & string;\n  open?: keyof T & string;\n  high?: keyof T & string;\n  low?: keyof T & string;\n  close?: keyof T & string;\n  /** Replaces the period format. */\n  formatX?: (value: unknown) => string;\n  timeZone?: string;\n  showGrid?: boolean;\n  labels?: Partial<CandlestickChartLabels>;\n};\n\nconst LABELS: CandlestickChartLabels = { open: \"Open\", high: \"High\", low: \"Low\", close: \"Close\", up: \"Closed higher\", down: \"Closed lower\", period: \"Period\" };\n\ntype Candle = { name: string; open: number; high: number; low: number; close: number };\n\nexport function CandlestickChart<T extends object>({\n  data,\n  x,\n  open = \"open\" as keyof T & string,\n  high = \"high\" as keyof T & string,\n  low = \"low\" as keyof T & string,\n  close = \"close\" as keyof T & string,\n  formatX,\n  timeZone,\n  showGrid = true,\n  labels: given,\n  label,\n  aspect,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: CandlestickChartProps<T>) {\n  const labels = { ...LABELS, ...given };\n  const candles = useMemo(() => {\n    const dates = data.map((row) => (row as Record<string, unknown>)[x]).filter((v): v is Date => v instanceof Date);\n    const span = dates.length > 1 ? Math.abs((dates[dates.length - 1]?.getTime() ?? 0) - (dates[0]?.getTime() ?? 0)) : 0;\n    const dateText = dateFormatter(Math.min(span, 300 * 86400000), \"full\", locale, timeZone);\n    return data.flatMap((row): Candle[] => {\n      const o = readNumber(row, open);\n      const h = readNumber(row, high);\n      const l = readNumber(row, low);\n      const c = readNumber(row, close);\n      if (o === null || h === null || l === null || c === null) return [];\n      const raw = (row as Record<string, unknown>)[x];\n      const name = formatX ? formatX(raw) : raw instanceof Date ? dateText(raw) : String(raw ?? \"\");\n      return [{ name, open: o, high: Math.max(h, o, c), low: Math.min(l, o, c), close: c }];\n    });\n  }, [data, x, open, high, low, close, formatX, locale, timeZone]);\n  const cursor = useChartCursor(candles.length);\n  const number = formatValue ?? ((value: number) => formatNumber(value, locale));\n  const table = {\n    caption: label,\n    columns: [labels.period, labels.open, labels.high, labels.low, labels.close],\n    rows: candles.map((c) => [c.name, number(c.open), number(c.high), number(c.low), number(c.close)]),\n  };\n  const current = cursor.active === null ? undefined : candles[cursor.active];\n  const rowsOf = (c: Candle): { label: string; value: string }[] => [\n    { label: labels.open, value: number(c.open) },\n    { label: labels.high, value: number(c.high) },\n    { label: labels.low, value: number(c.low) },\n    { label: labels.close, value: number(c.close) },\n    { label: \"\", value: c.close >= c.open ? labels.up : labels.down },\n  ];\n\n  return (\n    <div data-slot=\"candlestick-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer\n        aspect={aspect}\n        height={height}\n        table={table}\n        announcement={\n          cursor.keyboard && current\n            ? `${current.name}: ${rowsOf(current)\n                .map((row) => `${row.label} ${row.value}`.trim())\n                .join(\", \")}`\n            : \"\"\n        }\n      >\n        {({ width, height: plotHeight }) => {\n          if (candles.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const top = 10;\n          const bottom = 26;\n          const lowest = Math.min(...candles.map((c) => c.low));\n          const highest = Math.max(...candles.map((c) => c.high));\n          const sy = chartLinear(lowest, highest, [plotHeight - bottom, top]);\n          const axisY = formatValue ?? axisNumberFormatter(Math.max(Math.abs(lowest), Math.abs(highest)), locale);\n          const left = widestText(sy.ticks.map(axisY)) + 12;\n          const band = scaleBand<number>()\n            .domain(candles.map((_, i) => i))\n            .range([left, width - 4])\n            .paddingInner(0.3)\n            .paddingOuter(0.15);\n          const body = Math.max(1, Math.min(14, band.bandwidth()));\n          const centre = (i: number): number => (band(i) ?? 0) + band.bandwidth() / 2;\n          const every = Math.max(1, Math.ceil((widestText(candles.map((c) => c.name)) + 10) / band.step()));\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps}>\n                {showGrid ? <ChartGrid offsets={sy.ticks.map((tick) => sy.scale(tick))} from={left} to={width - 4} /> : null}\n                <ChartAxis side=\"left\" at={left - 8} ticks={sy.ticks.map((tick) => ({ offset: sy.scale(tick), label: axisY(tick) }))} />\n                <ChartAxis side=\"bottom\" at={plotHeight - bottom + 6} ticks={candles.flatMap((c, i) => (i % every === 0 ? [{ offset: centre(i), label: c.name }] : []))} />\n                <g aria-hidden=\"true\">\n                  {candles.map((c, i) => {\n                    const up = c.close >= c.open;\n                    const y0 = sy.scale(Math.max(c.open, c.close));\n                    const y1 = sy.scale(Math.min(c.open, c.close));\n                    return (\n                      <g\n                        key={i}\n                        onPointerEnter={() => cursor.point(i)}\n                        className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", cursor.active !== null && cursor.active !== i && \"opacity-40\")}\n                      >\n                        <rect x={band(i) ?? 0} y={top} width={band.bandwidth()} height={plotHeight - bottom - top} fill=\"transparent\" />\n                        <line x1={centre(i)} x2={centre(i)} y1={sy.scale(c.high)} y2={sy.scale(c.low)} className={up ? \"stroke-chart-1\" : \"stroke-chart-2\"} strokeWidth={1.25} />\n                        <rect\n                          x={centre(i) - body / 2}\n                          y={y0}\n                          width={body}\n                          height={Math.max(1, y1 - y0)}\n                          className={up ? \"fill-background stroke-chart-1\" : \"fill-chart-2 stroke-chart-2\"}\n                          strokeWidth={1.5}\n                        />\n                      </g>\n                    );\n                  })}\n                </g>\n              </ChartSvg>\n              {current && cursor.active !== null ? (\n                <ChartTooltip\n                  x={centre(cursor.active) + body / 2}\n                  y={sy.scale((current.high + current.low) / 2)}\n                  side={centre(cursor.active) > width / 2 ? \"left\" : \"right\"}\n                  title={current.name}\n                  rows={rowsOf(current)}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing the range and the direction of a value within each period: prices by day, temperatures by day with their extremes. For the close alone use line-chart; for spread across many observations use box-plot.",
    "example": "<CandlestickChart\n  label=\"Price by day\"\n  data={[\n    { day: new Date(\"2026-03-02\"), open: 10, high: 12, low: 9.5, close: 11.4 },\n    { day: new Date(\"2026-03-03\"), open: 11.4, high: 11.8, low: 10.1, close: 10.3 },\n    { day: new Date(\"2026-03-04\"), open: 10.3, high: 11, low: 10, close: 10.9 },\n  ]}\n  x=\"day\"\n/>",
    "client": true
  }
}
