TypeScript
feat: add Analytics page
Vipul Kumarec7ca3f33734
diff --git a/src/app/analytics/page.tsx b/src/app/analytics/page.tsxnew file mode 100644index 0000000..f373a59--- /dev/null+++ b/src/app/analytics/page.tsx@@ -0,0 +1,8 @@+import type { Metadata } from "next";+import { AnalyticsPage } from "@/components/pages/analytics/analytics-page";++export const metadata: Metadata = { title: "Analytics" };++export default function Page() {+ return <AnalyticsPage />;+}diff --git a/src/components/pages/analytics/analytics-page.tsx b/src/components/pages/analytics/analytics-page.tsxnew file mode 100644index 0000000..9d2bec9--- /dev/null+++ b/src/components/pages/analytics/analytics-page.tsx@@ -0,0 +1,468 @@+"use client";++import Link from "next/link";+import { useMemo, useState } from "react";+import { ArrowRightIcon, CheckIcon, Clock3Icon, FilePenLineIcon, TriangleAlertIcon } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import {+ addDays,+ formatDuration,+ formatShort,+ fromKey,+ MONTHS,+ MONTHS_SHORT,+ startOfWeek,+ WEEKDAYS,+} from "@/lib/dates";+import { computeLeaveStats, formatDays, LEAVE_TYPES, plural, workingDays } from "@/lib/leave";+import type { Invoice, InvoiceStatus, LeaveType } from "@/lib/types";+import { cn } from "@/lib/utils";+import { useToday } from "@/hooks/use-today";+import { useAppStore } from "@/stores/app-store";+import { PageHeader, PageRoot, StatIcon, type StatGlyph } from "@/components/pages/shared/page-chrome";+import { ChartCard, ColumnChart, DataTable, SERIES, TipRow, type Column, type Series } from "./charts";++const fmtDays = (v: number) => `${formatDays(Math.round(v * 100) / 100)}d`;+const fmtHours = (minutes: number) => (minutes ? formatDuration(Math.round(minutes)) : "0h");++function invoiceTotal(inv: Invoice) {+ return inv.items.reduce((a, it) => a + it.quantity * it.rate, 0);+}++function money(amount: number, currency = "USD") {+ return new Intl.NumberFormat("en-US", { style: "currency", currency, maximumFractionDigits: 0 }).format(amount);+}++export function AnalyticsPage() {+ const today = useToday();+ const year = today.slice(0, 4);+ return (+ <PageRoot>+ <PageHeader+ title="Overview"+ description={`January 1 – ${MONTHS[fromKey(today).getMonth()]} ${fromKey(today).getDate()}, ${year} · leave, time and revenue at a glance`}+ />+ <div className="grid gap-4 p-4">+ <KpiRow />+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">+ <LeavePerMonthCard />+ <HoursCard />+ <LeaveByTypeCard />+ <InvoicesCard />+ </div>+ </div>+ </PageRoot>+ );+}++/* ------------------------------------------------------------------ KPIs */++function Kpi({ icon, label, value, hint }: { icon: StatGlyph; label: string; value: React.ReactNode; hint: React.ReactNode }) {+ return (+ <div className="flex min-w-0 flex-col gap-3 rounded-xl border border-hairline bg-surface p-4">+ <span className="flex items-center gap-2">+ <StatIcon name={icon} size={16} />+ <span className="t-14 truncate text-fg-2">{label}</span>+ </span>+ <span className="text-[28px] leading-none font-medium tracking-[-0.84px] text-fg">{value}</span>+ <span className="t-12 truncate text-fg-2">{hint}</span>+ </div>+ );+}++function KpiRow() {+ const today = useToday();+ const requests = useAppStore((s) => s.requests);+ const settings = useAppStore((s) => s.settings);+ const holidays = useAppStore((s) => s.holidays);+ const timeEntries = useAppStore((s) => s.timeEntries);+ const invoices = useAppStore((s) => s.invoices);++ const kpis = useMemo(() => {+ const year = today.slice(0, 4);+ const stats = computeLeaveStats({ requests, settings, holidays }, today);+ const thisYear = requests.filter((r) => r.from.startsWith(year));+ const approved = thisYear.filter((r) => r.status === "approved").length;+ const declined = thisYear.filter((r) => r.status === "declined").length;+ const decided = approved + declined;++ const since = addDays(today, -29);+ const recent = timeEntries.filter((e) => e.date >= since && e.date <= today);+ const minutes = recent.reduce((a, e) => a + e.minutes, 0);+ const billable = recent.filter((e) => e.billable).reduce((a, e) => a + e.minutes, 0);++ const currency = invoices[0]?.currency ?? "USD";+ const paid = invoices.filter((i) => i.status === "paid").reduce((a, i) => a + invoiceTotal(i), 0);+ const outstanding = invoices+ .filter((i) => i.status === "sent" || i.status === "overdue")+ .reduce((a, i) => a + invoiceTotal(i), 0);++ return { stats, thisYear, approved, decided, minutes, billable, currency, paid, outstanding };+ }, [requests, settings, holidays, timeEntries, invoices, today]);++ const { stats } = kpis;+ return (+ <div className="grid grid-cols-2 gap-4 xl:grid-cols-4">+ <Kpi+ icon="holidays"+ label="Days off approved"+ value={formatDays(stats.taken + stats.upcoming)}+ hint={`${formatDays(stats.taken)} taken · ${formatDays(stats.upcoming)} booked ahead`}+ />+ <Kpi+ icon="available"+ label="Approval rate"+ value={kpis.decided ? `${Math.round((kpis.approved / kpis.decided) * 100)}%` : "—"}+ hint={`${plural(kpis.thisYear.length, "request", "requests")} · ${stats.pendingCount} pending`}+ />+ <Kpi+ icon="per-year"+ label="Hours, last 30 days"+ value={fmtHours(kpis.minutes)}+ hint={kpis.minutes ? `${Math.round((kpis.billable / kpis.minutes) * 100)}% billable` : "No time tracked"}+ />+ <Kpi+ icon="upcoming"+ label="Revenue collected"+ value={money(kpis.paid, kpis.currency)}+ hint={`${money(kpis.outstanding, kpis.currency)} outstanding`}+ />+ </div>+ );+}++/* ------------------------------------------------------------------ leave per month */++function LeavePerMonthCard() {+ const today = useToday();+ const requests = useAppStore((s) => s.requests);+ const holidays = useAppStore((s) => s.holidays);+ const year = today.slice(0, 4);+ const month = fromKey(today).getMonth();++ const perMonth = useMemo(() => {+ const out = Array.from({ length: 12 }, () => 0);+ for (const r of requests) {+ if (r.status !== "approved") continue;+ // Spread a request's days over the working days it covers (so a trip+ // across a month boundary lands in both months).+ const days = workingDays(r.from, r.to, holidays).filter((d) => d.startsWith(year));+ if (days.length) {+ for (const d of days) out[Number(d.slice(5, 7)) - 1] += r.days / days.length;+ } else if (r.from.startsWith(year)) {+ out[Number(r.from.slice(5, 7)) - 1] += r.days;+ }+ }+ return out;+ }, [requests, holidays, year]);++ const series: Series[] = [{ id: "approved", label: "Approved days", color: SERIES.one }];+ const columns: Column[] = perMonth.map((v, i) => ({+ key: String(i),+ label: MONTHS_SHORT[i],+ title: `${MONTHS[i]} ${year}`,+ values: [v],+ emphasis: i === month,+ }));+ const total = perMonth.reduce((a, v) => a + v, 0);++ return (+ <ChartCard+ title="Leave taken per month"+ description={`${plural(Math.round(total * 100) / 100, "approved day", "approved days")} in ${year}`}+ chart={<ColumnChart columns={columns} series={series} format={fmtDays} formatTick={(v) => formatDays(v)} />}+ table={+ <DataTable+ head={["Month", "Approved days"]}+ rows={perMonth.map((v, i) => [MONTHS[i], formatDays(Math.round(v * 100) / 100)])}+ foot={["Total", formatDays(Math.round(total * 100) / 100)]}+ />+ }+ />+ );+}++/* ------------------------------------------------------------------ hours */++function HoursCard() {+ const today = useToday();+ const timeEntries = useAppStore((s) => s.timeEntries);+ const weekStartsOn = useAppStore((s) => s.settings.weekStartsOn);+ const [mode, setMode] = useState<"day" | "week">("day");++ const buckets = useMemo(() => {+ const sum = (from: string, to: string) => {+ let billable = 0;+ let other = 0;+ for (const e of timeEntries) {+ if (e.date < from || e.date > to) continue;+ if (e.billable) billable += e.minutes;+ else other += e.minutes;+ }+ return [billable, other];+ };+ if (mode === "day") {+ return Array.from({ length: 14 }, (_, i) => {+ const date = addDays(today, i - 13);+ const d = fromKey(date);+ return {+ key: date,+ label: String(d.getDate()),+ title: `${WEEKDAYS[d.getDay()]}, ${formatShort(date)}`,+ values: sum(date, date),+ emphasis: date === today,+ };+ });+ }+ const current = startOfWeek(today, weekStartsOn);+ return Array.from({ length: 12 }, (_, i) => {+ const from = addDays(current, (i - 11) * 7);+ const to = addDays(from, 6);+ return {+ key: from,+ label: formatShort(from),+ title: `Week of ${formatShort(from)}`,+ values: sum(from, to),+ emphasis: from === current,+ };+ });+ }, [timeEntries, today, weekStartsOn, mode]);++ const series: Series[] = [+ { id: "billable", label: "Billable", color: SERIES.one },+ { id: "non-billable", label: "Non-billable", color: SERIES.two },+ ];+ const billable = buckets.reduce((a, b) => a + b.values[0], 0);+ const other = buckets.reduce((a, b) => a + b.values[1], 0);+ const tickHours = (minutes: number) => `${Math.round((minutes / 60) * 10) / 10}h`;++ return (+ <ChartCard+ title="Hours tracked"+ description={`${fmtHours(billable + other)} in the last ${mode === "day" ? "14 days" : "12 weeks"} · ${fmtHours(billable)} billable`}+ legend={series}+ actions={+ <div className="mr-1 flex items-center rounded-lg bg-app p-0.5" role="group" aria-label="Group by">+ {(["day", "week"] as const).map((m) => (+ <button+ key={m}+ type="button"+ aria-pressed={mode === m}+ onClick={() => setMode(m)}+ className={cn(+ "t-12 h-6 rounded-md px-2 outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-brand/40",+ mode === m ? "bg-surface text-fg shadow-[0_1px_2px_rgba(0,0,0,0.06)]" : "text-fg-2 hover-fine:text-fg",+ )}+ >+ {m === "day" ? "Daily" : "Weekly"}+ </button>+ ))}+ </div>+ }+ chart={+ <ColumnChart+ columns={buckets}+ series={series}+ format={fmtHours}+ formatTick={tickHours}+ unit={60}+ labelEvery={mode === "week" ? 2 : 1}+ />+ }+ table={+ <DataTable+ head={[mode === "day" ? "Day" : "Week", "Billable", "Non-billable", "Total"]}+ rows={buckets.map((b) => [b.title, fmtHours(b.values[0]), fmtHours(b.values[1]), fmtHours(b.values[0] + b.values[1])])}+ foot={["Total", fmtHours(billable), fmtHours(other), fmtHours(billable + other)]}+ />+ }+ />+ );+}++/* ------------------------------------------------------------------ leave by type */++function LeaveByTypeCard() {+ const today = useToday();+ const requests = useAppStore((s) => s.requests);+ const year = today.slice(0, 4);++ const rows = useMemo(() => {+ const map = new Map<LeaveType, { approved: number; pending: number; count: number }>(+ LEAVE_TYPES.map((t) => [t, { approved: 0, pending: 0, count: 0 }]),+ );+ for (const r of requests) {+ if (!r.from.startsWith(year)) continue;+ const row = map.get(r.type);+ if (!row) continue;+ row.count += 1;+ if (r.status === "approved") row.approved += r.days;+ if (r.status === "pending") row.pending += r.days;+ }+ return [...map.entries()].map(([type, v]) => ({ type, ...v })).sort((a, b) => b.approved - a.approved);+ }, [requests, year]);++ const max = Math.max(0, ...rows.map((r) => r.approved));+ const total = rows.reduce((a, r) => a + r.approved, 0);++ return (+ <ChartCard+ title="Leave by type"+ description={`Approved days in ${year}, by leave type`}+ chart={+ <ul className="grid gap-1 pt-1">+ {rows.map((r) => {+ const pct = max ? (r.approved / max) * 100 : 0;+ return (+ <li key={r.type}>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label={`${r.type}: ${plural(r.approved, "approved day", "approved days")}, ${plural(r.pending, "pending day", "pending days")}`}+ className="group grid h-9 w-full grid-cols-[112px_minmax(0,1fr)] items-center gap-3 rounded-md px-1 text-left outline-none focus-visible:bg-hover"+ >+ <span className="t-14 truncate text-fg-2">{r.type}</span>+ <span className="flex min-w-0 items-center gap-2">+ {r.approved > 0 ? (+ <span+ className="h-5 rounded-r-[4px] transition-opacity duration-150 group-hover:opacity-80"+ style={{ width: `calc(${pct}% - 48px)`, minWidth: 3, background: SERIES.one }}+ />+ ) : (+ <span className="h-5 w-px bg-hairline" />+ )}+ <span className="t-12 shrink-0 text-fg-2 tabular-nums">{fmtDays(r.approved)}</span>+ </span>+ </button>+ </TooltipTrigger>+ <TooltipContent side="top" className="flex-col items-start gap-1.5 py-2">+ <span className="opacity-70">{r.type}</span>+ <TipRow color={SERIES.one} value={fmtDays(r.approved)} label="Approved" />+ <TipRow value={fmtDays(r.pending)} label="Pending" />+ <TipRow value={r.count} label={r.count === 1 ? "Request" : "Requests"} />+ </TooltipContent>+ </Tooltip>+ </li>+ );+ })}+ </ul>+ }+ table={+ <DataTable+ head={["Type", "Requests", "Approved", "Pending"]}+ rows={rows.map((r) => [r.type, r.count, fmtDays(r.approved), fmtDays(r.pending)])}+ foot={["Total", rows.reduce((a, r) => a + r.count, 0), fmtDays(total), fmtDays(rows.reduce((a, r) => a + r.pending, 0))]}+ />+ }+ />+ );+}++/* ------------------------------------------------------------------ invoices */++const INVOICE_STATUS: Record<InvoiceStatus, { label: string; tone: string; icon: React.ReactNode }> = {+ paid: { label: "Paid", tone: "success", icon: <CheckIcon /> },+ sent: { label: "Awaiting payment", tone: "warning", icon: <Clock3Icon /> },+ overdue: { label: "Overdue", tone: "danger", icon: <TriangleAlertIcon /> },+ draft: { label: "Draft", tone: "neutral", icon: <FilePenLineIcon /> },+};+const STATUS_ORDER: InvoiceStatus[] = ["paid", "sent", "overdue", "draft"];++function InvoicesCard() {+ const invoices = useAppStore((s) => s.invoices);+ const currency = invoices[0]?.currency ?? "USD";++ const rows = useMemo(+ () =>+ STATUS_ORDER.map((status) => {+ const list = invoices.filter((i) => i.status === status);+ return { status, count: list.length, amount: list.reduce((a, i) => a + invoiceTotal(i), 0) };+ }),+ [invoices],+ );+ const total = rows.reduce((a, r) => a + r.amount, 0);+ const visible = rows.filter((r) => r.amount > 0);++ return (+ <ChartCard+ title="Invoice revenue by status"+ description={`${money(total, currency)} invoiced across ${plural(invoices.length, "invoice", "invoices")}`}+ actions={+ <Button variant="ghost" size="sm" asChild className="mr-1">+ <Link href="/invoice">+ Invoices <ArrowRightIcon />+ </Link>+ </Button>+ }+ chart={+ <div className="grid gap-5 pt-1">+ <div className="flex h-3 gap-[2px]" role="img" aria-label="Share of invoiced revenue by status">+ {visible.length === 0 ? <span className="h-full flex-1 rounded-[4px] bg-hairline" /> : null}+ {visible.map((r, i) => (+ <Tooltip key={r.status}>+ <TooltipTrigger asChild>+ <span+ tabIndex={0}+ className={cn(+ "h-full outline-none transition-opacity duration-150 hover:opacity-80 focus-visible:ring-2 focus-visible:ring-brand/40",+ i === 0 && "rounded-l-[4px]",+ i === visible.length - 1 && "rounded-r-[4px]",+ )}+ style={{ flexGrow: r.amount, flexBasis: 0, background: `var(--status-${INVOICE_STATUS[r.status].tone})` }}+ />+ </TooltipTrigger>+ <TooltipContent side="top" className="flex-col items-start gap-1.5 py-2">+ <span className="opacity-70">{INVOICE_STATUS[r.status].label}</span>+ <TipRow+ color={`var(--status-${INVOICE_STATUS[r.status].tone})`}+ value={money(r.amount, currency)}+ label={`${Math.round((r.amount / total) * 100)}% of total`}+ />+ </TooltipContent>+ </Tooltip>+ ))}+ </div>+ <ul className="grid">+ {rows.map((r) => {+ const s = INVOICE_STATUS[r.status];+ return (+ <li key={r.status} className="flex h-11 items-center gap-3 border-b border-subtle last:border-b-0">+ <span+ className="inline-flex h-[22px] shrink-0 items-center gap-1 rounded-[6px] border pr-1.5 pl-1 [&_svg]:size-3.5"+ style={{+ background: `var(--status-${s.tone}-tint)`,+ borderColor: `var(--status-${s.tone}-border)`,+ color: `var(--status-${s.tone})`,+ }}+ >+ {s.icon}+ <span className="salt text-[12px] leading-none tracking-[-0.24px] whitespace-nowrap">{s.label}</span>+ </span>+ <span className="t-12 flex-1 text-fg-2">{plural(r.count, "invoice", "invoices")}</span>+ <span className="t-12 w-10 text-right text-placeholder tabular-nums">+ {total ? `${Math.round((r.amount / total) * 100)}%` : "—"}+ </span>+ <span className="t-14 w-24 text-right text-fg tabular-nums">{money(r.amount, currency)}</span>+ </li>+ );+ })}+ </ul>+ </div>+ }+ table={+ <DataTable+ head={["Status", "Invoices", "Amount", "Share"]}+ rows={rows.map((r) => [+ INVOICE_STATUS[r.status].label,+ r.count,+ money(r.amount, currency),+ total ? `${Math.round((r.amount / total) * 100)}%` : "—",+ ])}+ foot={["Total", invoices.length, money(total, currency), total ? "100%" : "—"]}+ />+ }+ />+ );+}diff --git a/src/components/pages/analytics/charts.tsx b/src/components/pages/analytics/charts.tsxnew file mode 100644index 0000000..d29f566--- /dev/null+++ b/src/components/pages/analytics/charts.tsx@@ -0,0 +1,330 @@+"use client";++import { useState } from "react";+import { ChartColumnIcon, TableIcon } from "lucide-react";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import { Card, CardHeader } from "@/components/pages/shared/page-chrome";++/**+ * Chart colors. Categorical slots are validated (dataviz validate_palette.js)+ * against both the light (#fff) and dark (#181818) surfaces:+ * slot 1 brand #8965de · slot 2 cyan #2a9fb8 → CVD ΔE 11.3, normal ΔE ≥ 15, contrast ≥ 3:1.+ * Status colors come straight from the app's status tokens.+ */+export const SERIES = {+ one: "var(--brand)",+ two: "#2a9fb8",+} as const;++export type Series = { id: string; label: string; color: string };++/* ------------------------------------------------------------------ scale */++export function niceScale(max: number, count = 4): { top: number; ticks: number[] } {+ if (!(max > 0)) return { top: 1, ticks: [0, 1] };+ const raw = max / count;+ const mag = 10 ** Math.floor(Math.log10(raw));+ const norm = raw / mag;+ const step = (norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 2.5 ? 2.5 : norm <= 5 ? 5 : 10) * mag;+ const top = Math.ceil(max / step - 1e-9) * step;+ const ticks: number[] = [];+ for (let v = 0; v <= top + step / 2; v += step) ticks.push(Math.round(v * 1000) / 1000);+ return { top, ticks };+}++/* ------------------------------------------------------------------ card */++/** Chart card with a chart/table toggle so every value is reachable without hover. */+export function ChartCard({+ title,+ description,+ legend,+ actions,+ chart,+ table,+ className,+}: {+ title: string;+ description?: React.ReactNode;+ legend?: Series[];+ actions?: React.ReactNode;+ chart: React.ReactNode;+ table: React.ReactNode;+ className?: string;+}) {+ const [view, setView] = useState<"chart" | "table">("chart");+ return (+ <Card className={className}>+ <CardHeader+ title={title}+ description={description}+ actions={+ <>+ {actions}+ <div className="flex items-center rounded-lg bg-app p-0.5" role="group" aria-label="View">+ <ToggleIcon active={view === "chart"} label="Chart view" onClick={() => setView("chart")}>+ <ChartColumnIcon />+ </ToggleIcon>+ <ToggleIcon active={view === "table"} label="Table view" onClick={() => setView("table")}>+ <TableIcon />+ </ToggleIcon>+ </div>+ </>+ }+ />+ {legend && legend.length > 1 && view === "chart" ? <Legend series={legend} className="px-4 pt-3" /> : null}+ <div className="flex-1 p-4">{view === "chart" ? chart : table}</div>+ </Card>+ );+}++function ToggleIcon({+ active,+ label,+ onClick,+ children,+}: {+ active: boolean;+ label: string;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label={label}+ aria-pressed={active}+ onClick={onClick}+ className={cn(+ "flex size-6 items-center justify-center rounded-md outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-brand/40 [&_svg]:size-3.5",+ active ? "bg-surface text-fg shadow-[0_1px_2px_rgba(0,0,0,0.06)]" : "text-icon hover-fine:text-fg",+ )}+ >+ {children}+ </button>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ );+}++export function Legend({ series, className }: { series: Series[]; className?: string }) {+ return (+ <ul className={cn("flex flex-wrap items-center gap-4", className)}>+ {series.map((s) => (+ <li key={s.id} className="t-12 flex items-center gap-1.5 text-fg-2">+ <span className="size-2.5 rounded-[3px]" style={{ background: s.color }} aria-hidden />+ {s.label}+ </li>+ ))}+ </ul>+ );+}++/** Tooltip row: short line key, strong value, secondary label. */+export function TipRow({ color, value, label }: { color?: string; value: React.ReactNode; label: React.ReactNode }) {+ return (+ <span className="flex items-center gap-2">+ {color ? <span className="h-0.5 w-2.5 rounded-full" style={{ background: color }} aria-hidden /> : null}+ <span className="font-medium tabular-nums">{value}</span>+ <span className="opacity-70">{label}</span>+ </span>+ );+}++/* ------------------------------------------------------------------ columns */++export type Column = {+ key: string;+ /** x-axis label */+ label: string;+ /** Long label for the tooltip/aria */+ title: string;+ /** One value per series, in series order */+ values: number[];+ emphasis?: boolean;+};++/**+ * Vertical (optionally stacked) column chart in HTML/CSS: hairline grid,+ * ≤24px columns with 4px rounded data-ends, 2px surface gaps between stacked+ * segments, a per-column tooltip on hover/focus and a direct label on the peak.+ */+export function ColumnChart({+ columns,+ series,+ format,+ formatTick = format,+ height = 180,+ labelEvery = 1,+ unit = 1,+}: {+ columns: Column[];+ series: Series[];+ format: (v: number) => string;+ formatTick?: (v: number) => string;+ height?: number;+ labelEvery?: number;+ /** Ticks are rounded in this unit (e.g. 60 to get whole hours from minutes). */+ unit?: number;+}) {+ const totals = columns.map((c) => c.values.reduce((a, v) => a + v, 0));+ const max = Math.max(0, ...totals);+ const scaled = niceScale(max / unit);+ const top = scaled.top * unit;+ const ticks = scaled.ticks.map((t) => t * unit);+ const peak = max > 0 ? totals.indexOf(max) : -1;+ const y = (v: number) => (v / top) * height;++ return (+ <div className="flex gap-2 pt-4">+ {/* y axis */}+ <div className="relative w-8 shrink-0" style={{ height }} aria-hidden>+ {ticks.map((t) => (+ <span+ key={t}+ className="t-12 absolute right-0 translate-y-1/2 text-placeholder tabular-nums"+ style={{ bottom: y(t) }}+ >+ {formatTick(t)}+ </span>+ ))}+ </div>+ <div className="min-w-0 flex-1">+ <div className="relative" style={{ height }}>+ {ticks.map((t) => (+ <div+ key={t}+ aria-hidden+ className={cn("pointer-events-none absolute inset-x-0 border-t", t === 0 ? "border-hairline" : "border-subtle")}+ style={{ bottom: y(t) }}+ />+ ))}+ <div+ className="relative grid h-full"+ style={{ gridTemplateColumns: `repeat(${columns.length}, minmax(0, 1fr))` }}+ >+ {columns.map((c, i) => {+ const total = totals[i];+ const topIndex = c.values.reduce((acc, v, idx) => (v > 0 ? idx : acc), -1);+ return (+ <Tooltip key={c.key}>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label={`${c.title}: ${series.map((s, si) => `${s.label} ${format(c.values[si])}`).join(", ")}`}+ className="group relative flex h-full flex-col items-center justify-end rounded-md px-0.5 outline-none focus-visible:bg-hover"+ >+ {i === peak ? (+ <span+ className="t-12 absolute left-1/2 -translate-x-1/2 text-fg-2 tabular-nums whitespace-nowrap"+ style={{ bottom: y(total) + 6 }}+ >+ {format(total)}+ </span>+ ) : null}+ <span className="flex w-full max-w-6 flex-col-reverse gap-[2px] transition-opacity duration-150 group-hover:opacity-80">+ {c.values.map((v, si) =>+ v > 0 ? (+ <span+ key={series[si].id}+ className={cn("w-full", si === topIndex && "rounded-t-[4px]")}+ style={{+ height: Math.max(2, y(v) - (si === topIndex ? 0 : 2)),+ background: series[si].color,+ }}+ />+ ) : null,+ )}+ </span>+ </button>+ </TooltipTrigger>+ <TooltipContent side="top" className="flex-col items-start gap-1.5 py-2">+ <span className="opacity-70">{c.title}</span>+ {series.length > 1 ? (+ <>+ {series.map((s, si) => (+ <TipRow key={s.id} color={s.color} value={format(c.values[si])} label={s.label} />+ ))}+ <TipRow value={format(total)} label="Total" />+ </>+ ) : (+ <TipRow value={format(total)} label={series[0].label} />+ )}+ </TooltipContent>+ </Tooltip>+ );+ })}+ </div>+ </div>+ <div+ className="mt-2 grid"+ style={{ gridTemplateColumns: `repeat(${columns.length}, minmax(0, 1fr))` }}+ aria-hidden+ >+ {columns.map((c, i) => (+ <span+ key={c.key}+ className={cn("t-12-tight salt truncate text-center", c.emphasis ? "text-fg" : "text-placeholder")}+ >+ {(columns.length - 1 - i) % labelEvery === 0 ? c.label : ""}+ </span>+ ))}+ </div>+ </div>+ </div>+ );+}++/* ------------------------------------------------------------------ table */++export function DataTable({+ head,+ rows,+ foot,+}: {+ head: string[];+ rows: React.ReactNode[][];+ foot?: React.ReactNode[];+}) {+ return (+ <div className="scroll-thin max-h-[260px] overflow-auto rounded-lg border border-hairline">+ <table className="w-full border-collapse">+ <thead className="sticky top-0 bg-app">+ <tr className="h-10">+ {head.map((h, i) => (+ <th key={h} className={cn("t-14 px-3 font-medium text-fg-2", i === 0 ? "text-left" : "text-right")}>+ {h}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.map((r, ri) => (+ <tr key={ri} className="h-10 border-t border-subtle">+ {r.map((cell, i) => (+ <td key={i} className={cn("t-14 px-3 text-table", i === 0 ? "text-left" : "text-right tabular-nums")}>+ {cell}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ {foot ? (+ <tfoot>+ <tr className="h-10 border-t border-hairline bg-app">+ {foot.map((cell, i) => (+ <td key={i} className={cn("t-14 px-3 text-fg", i === 0 ? "text-left" : "text-right tabular-nums")}>+ {cell}+ </td>+ ))}+ </tr>+ </tfoot>+ ) : null}+ </table>+ </div>+ );+}