diff --git a/src/charts/chart-hover.tsx b/src/charts/chart-hover.tsx new file mode 100644 index 0000000..41ba585 --- /dev/null +++ b/src/charts/chart-hover.tsx @@ -0,0 +1,99 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +/** Ширина контейнера — чтобы SVG рисовался в реальных пикселях и текст не масштабировался. */ +export function useElementWidth() { + const ref = React.useRef(null) + const [width, setWidth] = React.useState(0) + React.useLayoutEffect(() => { + const el = ref.current + if (!el) return + const observer = new ResizeObserver(([entry]) => setWidth(Math.round(entry.contentRect.width))) + observer.observe(el) + setWidth(Math.round(el.getBoundingClientRect().width)) + return () => observer.disconnect() + }, []) + return [ref, width] as const +} + +export interface HoverState { + readonly item: T + /** Якорь подсказки относительно контейнера графика. */ + readonly x: number + readonly y: number +} + +/** Одна подсказка на весь график: координаты считаются от контейнера с `relative`. */ +export function useChartHover() { + const [hover, setHover] = React.useState | null>(null) + const bind = React.useCallback((item: T) => { + const move = (e: React.MouseEvent) => { + const box = (e.currentTarget as Element).closest("[data-chart-root]")?.getBoundingClientRect() + if (box) setHover({ item, x: e.clientX - box.left, y: e.clientY - box.top }) + } + return { onMouseEnter: move, onMouseMove: move, onMouseLeave: () => setHover(null) } + }, []) + return { hover, bind, clear: () => setHover(null) } +} + +/** Плашка подсказки: справа от курсора, у правого края — слева. */ +export function ChartTooltip({ + x, + y, + width, + className, + children, +}: { + x: number + y: number + width: number + className?: string + children: React.ReactNode +}) { + const flip = x > width * 0.6 + return ( +
+ {children} +
+ ) +} + +/** Строка подсказки: цветная метка, подпись, значение справа. */ +export function TooltipRow({ color, label, value }: { color?: string; label: React.ReactNode; value: React.ReactNode }) { + return ( +
+ {color && } + {label} + {value} +
+ ) +} + +/** Легенда: всегда при двух и более сериях. */ +export function ChartLegend({ + items, + className, +}: { + items: readonly { label: string; color: string; value?: React.ReactNode }[] + className?: string +}) { + return ( +
    + {items.map((item) => ( +
  • + + {item.label} + {item.value !== undefined && {item.value}} +
  • + ))} +
+ ) +} diff --git a/src/charts/column-chart.tsx b/src/charts/column-chart.tsx new file mode 100644 index 0000000..2c41395 --- /dev/null +++ b/src/charts/column-chart.tsx @@ -0,0 +1,134 @@ +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} +
+ )} +
+ ) +} diff --git a/src/charts/sparkline.tsx b/src/charts/sparkline.tsx new file mode 100644 index 0000000..d4c36bd --- /dev/null +++ b/src/charts/sparkline.tsx @@ -0,0 +1,32 @@ +import { useElementWidth } from "./chart-hover" + +/** Мини-тренд для плитки: линия 2px и точка на последнем значении. */ +export function Sparkline({ + values, + height = 28, + color = "var(--chart-1)", +}: { + values: readonly (number | null)[] + height?: number + color?: string +}) { + const [ref, width] = useElementWidth() + const points = values.map((v, i) => ({ i, v })).filter((p): p is { i: number; v: number } => p.v !== null) + const min = Math.min(...points.map((p) => p.v)) + const max = Math.max(...points.map((p) => p.v)) + const x = (i: number) => 4 + (i / Math.max(1, values.length - 1)) * (width - 8) + const y = (v: number) => 4 + (max === min ? 0.5 : 1 - (v - min) / (max - min)) * (height - 8) + const d = points.map((p, k) => `${k ? "L" : "M"}${x(p.i).toFixed(1)},${y(p.v).toFixed(1)}`).join("") + const last = points.at(-1) + + return ( +
+ {width > 0 && points.length > 1 && ( + + + {last && } + + )} +
+ ) +}