import * as React from "react" import { cn } from "../lib/utils" import { ChartTooltip, TooltipRow, useChartHover, useElementWidth } from "./chart-hover" export interface ChartSeries { readonly id: string readonly label: string readonly color: string } export interface ColumnRow { readonly key: string readonly label: string /** Заголовок подсказки — полная дата. */ readonly title: string readonly values: Readonly> /** Дополнительные строки подсказки (доли, итог). */ readonly extra?: React.ReactNode } /** «Красивый» шаг сетки: 1, 2, 5 × 10ⁿ. */ function niceStep(max: number, ticks: number) { const raw = max / ticks const pow = 10 ** Math.floor(Math.log10(raw || 1)) const n = raw / pow return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * pow } const compact = new Intl.NumberFormat("ru-RU", { notation: "compact", maximumFractionDigits: 1 }) /** Верхний сегмент столбика — скруглённый, у основания — прямой. */ function columnPath(x: number, y: number, w: number, h: number, r: number) { const rr = Math.min(r, h, w / 2) return `M${x},${y + h}V${y + rr}Q${x},${y} ${x + rr},${y}H${x + w - rr}Q${x + w},${y} ${x + w},${y + rr}V${y + h}Z` } /** * Столбики с накоплением: серия снизу вверх, между сегментами — зазор 2px цвета фона. * Подписи оси X прореживаются, значения — в подсказке. */ export function ColumnChart({ series, rows, height = 220, format = (v) => compact.format(v), className, }: { series: readonly ChartSeries[] rows: readonly ColumnRow[] height?: number format?: (value: number) => string className?: string }) { const [ref, width] = useElementWidth() const { hover, bind } = useChartHover() const pad = { top: 8, right: 4, bottom: 22, left: 36 } const innerW = Math.max(0, width - pad.left - pad.right) const innerH = height - pad.top - pad.bottom const totals = rows.map((r) => series.reduce((s, x) => s + (r.values[x.id] ?? 0), 0)) const step = niceStep(Math.max(1, ...totals), 4) const top = Math.max(step, Math.ceil(Math.max(1, ...totals) / step) * step) const ticks = Array.from({ length: Math.round(top / step) + 1 }, (_, i) => i * step) const y = (v: number) => pad.top + innerH - (v / top) * innerH const band = rows.length ? innerW / rows.length : 0 const barW = Math.max(2, Math.min(24, band * 0.62)) const labelEvery = Math.max(1, Math.ceil(rows.length / Math.max(1, Math.floor(innerW / 44)))) return (
{width > 0 && ( {ticks.map((t) => ( {compact.format(t)} ))} {rows.map((row, i) => { const cx = pad.left + band * i + band / 2 let acc = 0 const segments = series .map((s) => ({ s, v: row.values[s.id] ?? 0 })) .filter((seg) => seg.v > 0) const active = hover?.item.key === row.key return ( {segments.map((seg, j) => { const y0 = y(acc) acc += seg.v const y1 = y(acc) const gap = j > 0 ? 2 : 0 const h = Math.max(0, y0 - y1 - gap) const isTop = j === segments.length - 1 return isTop ? ( ) : ( ) })} {i % labelEvery === 0 && ( {row.label} )} ) })} )} {hover && (
{hover.item.title}
{series.toReversed().map((s) => ( ))} {hover.item.extra}
)}
) }