135 lines
5.3 KiB
TypeScript
135 lines
5.3 KiB
TypeScript
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<Record<string, number>>
|
||
/** Дополнительные строки подсказки (доли, итог). */
|
||
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<HTMLDivElement>()
|
||
const { hover, bind } = useChartHover<ColumnRow>()
|
||
|
||
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 (
|
||
<div ref={ref} data-chart-root className={cn("relative select-none", className)} style={{ height }}>
|
||
{width > 0 && (
|
||
<svg width={width} height={height} className="block overflow-visible text-3xs">
|
||
{ticks.map((t) => (
|
||
<g key={t}>
|
||
<line x1={pad.left} x2={width - pad.right} y1={y(t)} y2={y(t)} stroke="var(--chart-grid)" />
|
||
<text x={pad.left - 6} y={y(t)} dy="0.32em" textAnchor="end" className="fill-muted-foreground tabular">
|
||
{compact.format(t)}
|
||
</text>
|
||
</g>
|
||
))}
|
||
{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 (
|
||
<g key={row.key} {...bind(row)}>
|
||
<rect
|
||
x={pad.left + band * i}
|
||
y={pad.top}
|
||
width={band}
|
||
height={innerH}
|
||
className={active ? "fill-muted" : "fill-transparent"}
|
||
/>
|
||
{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 ? (
|
||
<path key={seg.s.id} d={columnPath(cx - barW / 2, y1, barW, h, 4)} fill={seg.s.color} />
|
||
) : (
|
||
<rect key={seg.s.id} x={cx - barW / 2} y={y1} width={barW} height={h} fill={seg.s.color} />
|
||
)
|
||
})}
|
||
{i % labelEvery === 0 && (
|
||
<text x={cx} y={height - 6} textAnchor="middle" className="fill-muted-foreground tabular">
|
||
{row.label}
|
||
</text>
|
||
)}
|
||
</g>
|
||
)
|
||
})}
|
||
<line x1={pad.left} x2={width - pad.right} y1={y(0)} y2={y(0)} stroke="var(--border)" />
|
||
</svg>
|
||
)}
|
||
{hover && (
|
||
<ChartTooltip x={hover.x} y={hover.y} width={width}>
|
||
<div className="mb-1 font-semibold first-letter:uppercase">{hover.item.title}</div>
|
||
{series.toReversed().map((s) => (
|
||
<TooltipRow key={s.id} color={s.color} label={s.label} value={format(hover.item.values[s.id] ?? 0)} />
|
||
))}
|
||
{hover.item.extra}
|
||
</ChartTooltip>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|