Add the **Split Bar** component from uibrik to my project. Parts of a whole on one bar, linked to a list, with segments that slide to new shares when the data changes. Add exactly this component and nothing else. Use the files below verbatim: do not rewrite, restyle, rename, simplify or "improve" them, and do not add other components, dependencies or dummy pages. Keep every file's path and its relative imports unchanged. ## Requirements - React 19, Tailwind CSS v4, TypeScript. Works in Next.js (App Router) and Vite. - Files go inside the project's `components` folder (the `@/components` alias), keeping the `uibrik/split-bar` layout, so that `@/components/uibrik/split-bar/split-bar` resolves. - Install these npm packages: `@number-flow/react`, `@tabler/icons-react`, `motion`, `react-use-measure`. - Import `cn` from `@/lib/utils`. It is shadcn's `clsx` + `tailwind-merge` helper; create it if the project has no `lib/utils.ts`: ```ts import { clsx, type ClassValue } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } ``` Shortcut when you can run commands: `npx shadcn@latest add https://uibrik.com/r/split-bar.json` writes the same files and installs the packages. Then skip to Usage. ## Files ### components/uibrik/split-bar/split-bar.tsx ```tsx "use client"; import { useEffect, useMemo, useState, type PointerEvent } from "react"; import { motion, useReducedMotion } from "motion/react"; import NumberFlow from "@number-flow/react"; import { cn } from "@/lib/utils"; import { Announce, ChartCard, DataTable, Headline, Tooltip, useChartCursor, useWidth, EASE_OUT, GAP, SETTLE, SERIES_COUNT, seriesColor, tint, TRACK, formatShare, formatValue, type ValueFormat, } from "../_charts/chart-kit"; export type SplitItem = { label: string; value: number; color?: string }; const SAMPLE: SplitItem[] = [ { label: "Photos", value: 38.4 }, { label: "Documents", value: 21.7 }, { label: "Apps", value: 16.2 }, { label: "System", value: 12.6 }, { label: "Mail", value: 3.2 }, ]; const SAMPLE_TOTAL = 128; const SAMPLE_FORMAT: ValueFormat = { style: "unit", unit: "gigabyte", maximumFractionDigits: 1 }; const HEIGHT = 12; // Air above and below the bar that still counts as hovering it. const HIT = 12; // Past the palette, the tail folds into one neutral "Other" so colours never repeat. const MAX_SEGMENTS = SERIES_COUNT; const OTHER = tint("var(--foreground)", 32); // Mount: each segment grows in a little after the one before it. const GROW = 0.3; const STAGGER_TOTAL = 0.18; export type SplitBarProps = { /** Names the whole. */ title?: string; /** The parts, in the order they sit on the bar. */ items?: SplitItem[]; /** Full capacity. The rest of the bar shows what's left. Empty makes the parts the whole. */ total?: number; /** Intl.NumberFormat options for every number, e.g. { style: "currency", currency: "USD" }. */ format?: ValueFormat; /** List every part under the bar. */ showList?: boolean; /** Called with the part picked from the bar or the list. */ onSelect?: (item: SplitItem) => void; className?: string; }; export function SplitBar({ title = "Storage", items = SAMPLE, total: totalProp, format: formatProp, showList = true, onSelect, className, }: SplitBarProps) { const reduce = useReducedMotion(); const [ref, width] = useWidth(); // The sample's capacity and units only apply to the sample, so `total={undefined}` // with your own items really means "no capacity". const sample = items === SAMPLE; const total = totalProp ?? (sample ? SAMPLE_TOTAL : undefined); const format = formatProp ?? (sample ? SAMPLE_FORMAT : {}); // Fold the tail into "Other" so there are never more segments than colours. const parts = useMemo(() => { const colored = items.map((d, i) => ({ ...d, color: d.color ?? seriesColor(i) })); if (colored.length <= MAX_SEGMENTS) return colored; const keep = colored.slice(0, MAX_SEGMENTS - 1); const rest = colored.slice(MAX_SEGMENTS - 1).reduce((n, d) => n + Math.max(0, d.value), 0); return [...keep, { label: "Other", value: rest, color: OTHER }]; }, [items]); const cursor = useChartCursor(parts.length); const [row, setRow] = useState(null); const active = row ?? cursor.active; const used = parts.reduce((n, d) => n + Math.max(0, d.value), 0); const whole = total !== undefined ? Math.max(total, used) : used; const share = (v: number) => (whole ? v / whole : 0); const fmt = (v: number) => formatValue(v, format); // With percent values and no capacity, the share would repeat the value. const showShare = !(format.style === "percent" && total === undefined); // Every segment's place in px, plus the track for what's left. const layout = useMemo(() => { if (!width) return { segs: [], track: { x: 0, w: 0 } }; const left = total !== undefined ? Math.max(0, whole - used) : 0; const count = parts.length + (left > 0 ? 1 : 0); const room = Math.max(0, width - GAP * (count - 1)); const unit = whole ? room / whole : 0; let x = 0; const segs = parts.map((d) => { const w = Math.max(0, d.value) * unit; const seg = { x, w }; x += w + GAP; return seg; }); return { segs, track: left > 0 ? { x, w: Math.max(0, width - x) } : { x: width, w: 0 } }; }, [parts, width, whole, used, total]); // The staggered grow plays once; after that, segments settle into new values. const [grown, setGrown] = useState(false); useEffect(() => { if (!width || grown) return; const t = setTimeout(() => setGrown(true), (GROW + STAGGER_TOTAL) * 1000 + 50); return () => clearTimeout(t); }, [width, grown]); const stagger = parts.length > 1 ? STAGGER_TOTAL / (parts.length - 1) : 0; const move = (i: number) => reduce ? { duration: 0 } : grown ? SETTLE : { duration: GROW, ease: EASE_OUT, delay: i * stagger }; const onPointerMove = (e: PointerEvent) => { const x = e.clientX - e.currentTarget.getBoundingClientRect().left; const i = layout.segs.findIndex((s) => x >= s.x - GAP / 2 && x < s.x + s.w + GAP / 2); setRow(null); cursor.point(i >= 0 ? i : null); }; const at = active !== null ? layout.segs[active] : undefined; const pick = active !== null ? parts[active] : undefined; return ( } meta={total !== undefined ? of {fmt(total)} : undefined} aside={ total !== undefined ? (  used ) : undefined } className={cn("max-w-120", className)} > {/* A little air above the bar so the tooltip clears the headline. */}
pick && onSelect?.(pick)} {...cursor.bind} onKeyDown={(e) => { if (e.key === "Enter" && pick) onSelect?.(pick); cursor.bind.onKeyDown(e); }} >
{width > 0 && ( <> {/* What's left. Sits under the segments while they grow in, then slides to its place. */} {layout.segs.map((s, i) => ( ))} )}
{/* Keyboard ring, outside the clip so it isn't cut off. */} {at && cursor.keyboard && row === null && ( )}
{pick && ( <> {pick.label} · {fmt(pick.value)} {showShare && · {formatShare(share(pick.value))}} )}
{showList && (
    setRow(null)}> {parts.map((d, i) => (
  • ))}
)} {pick ? `${pick.label}: ${fmt(pick.value)}, ${formatShare(share(pick.value))}` : ""} [d.label, fmt(d.value), formatShare(share(d.value))])} />
); } ``` ### components/uibrik/_charts/chart-kit.tsx ```tsx "use client"; // Everything the charts share, in one file: colours and motion, scales and // paths, number formats, sample data, axis labels, and the card, tooltip and // legend every chart is built from. Copy this one file next to a chart. import { useId, useState, type CSSProperties, type FocusEvent, type KeyboardEvent, type ReactNode } from "react"; import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import NumberFlow from "@number-flow/react"; import useMeasure from "react-use-measure"; import { IconArrowDownRight, IconArrowUpRight } from "@tabler/icons-react"; import { cn } from "@/lib/utils"; // ═══ Theme ═══════════════════════════════════════════════════════════════════ // Shared look for every chart: colours, motion and sizes. Charts read colours // through CSS variables, so light and dark each get their own validated steps // and a single `accent` prop can still take over the first series. // ─── Colour ─────────────────────────────────────────────────────────────────── // Categorical series, in a fixed order that keeps neighbours apart for // colour-blind readers. Series take slots in order and keep them when others // are hidden, so a colour always means the same thing. /** * Put on a chart's outer element. Defines `--series-1` … `--series-6`, with * steps of their own for dark mode. Written out in full so Tailwind can see * every class. */ export const SERIES_VARS = "[--series-1:#2a78d6] [--series-2:#eb6834] [--series-3:#1baf7a] [--series-4:#eda100] [--series-5:#e87ba4] [--series-6:#6250d6] " + "dark:[--series-1:#3987e5] dark:[--series-2:#d95926] dark:[--series-3:#199e70] dark:[--series-4:#c98500] dark:[--series-5:#d55181] dark:[--series-6:#9085e9]"; export const SERIES_COUNT = 6; /** Colour for the series in slot `i` (0-based); past the palette it repeats. */ export const seriesColor = (i: number) => `var(--series-${(i % SERIES_COUNT) + 1})`; /** Lets an `accent` prop replace the first series colour. Empty keeps the palette. */ export const accentVars = (accent?: string): CSSProperties | undefined => accent ? ({ "--series-1": accent } as CSSProperties) : undefined; /** * Status colours, kept apart from the series colours so a state never looks * like a series. Always pair one with a label or icon, never colour alone. */ export const STATUS = { good: "#22c55e", warning: "#f5a524", critical: "#ef4444", /** No data. */ empty: "color-mix(in srgb, var(--foreground) 10%, transparent)", } as const; export type Status = keyof typeof STATUS; /** `color` at `percent`% strength over transparent, for washes and tracks. */ export const tint = (color: string, percent: number) => `color-mix(in srgb, ${color} ${percent}%, transparent)`; /** Hairline grid and empty track: the foreground at low strength. */ export const GRID = tint("var(--foreground)", 8); export const TRACK = tint("var(--foreground)", 7); // ─── Motion ─────────────────────────────────────────────────────────────────── /** Strong ease-out for entrances and value changes. */ export const EASE_OUT = [0.23, 1, 0.32, 1] as const; /** Ease-in-out for shapes that are on screen the whole time they move. */ export const EASE_IN_OUT = [0.45, 0, 0.2, 1] as const; /** Tooltips and crosshairs: quick, with no overshoot. */ export const FOLLOW = { type: "spring", stiffness: 700, damping: 45 } as const; /** Marks settling into a new value or position. */ export const SETTLE = { type: "spring", bounce: 0, duration: 0.5 } as const; /** How long a line or bar takes to draw in on mount, in seconds. */ export const DRAW_IN = 0.6; // ─── Marks ──────────────────────────────────────────────────────────────────── /** Line stroke width in px. */ export const LINE = 2; /** Radius of an end or hover dot in px; it also gets a 2px ring of the background. */ export const DOT = 4; /** Most a bar can be across, in px. The rest of its slot is air. */ export const BAR_MAX = 24; /** Corner radius on a bar's value end, in px. */ export const BAR_RADIUS = 4; /** Gap between touching marks, in px. */ export const GAP = 2; /** Area fill strength under a line, in percent. */ export const AREA = 14; // ═══ Scale ═══════════════════════════════════════════════════════════════════ // Scales, ticks and paths: the small amount of maths every chart needs. /** Maps `domain` onto `range` in a straight line. */ export function linear([d0, d1]: readonly [number, number], [r0, r1]: readonly [number, number]) { const span = d1 - d0 || 1; return (v: number) => r0 + ((v - d0) / span) * (r1 - r0); } /** Smallest and largest of `values`; [0, 0] when empty. */ export function extent(values: readonly number[]): [number, number] { if (!values.length) return [0, 0]; let lo = Infinity; let hi = -Infinity; for (const v of values) { if (v < lo) lo = v; if (v > hi) hi = v; } return [lo, hi]; } /** A round step near `span / count`: 1, 2, 2.5 or 5 times a power of ten. */ function niceStep(span: number, count: number) { const raw = span / Math.max(1, count); const power = 10 ** Math.floor(Math.log10(raw)); const unit = raw / power; const nice = unit <= 1 ? 1 : unit <= 2 ? 2 : unit <= 2.5 ? 2.5 : unit <= 5 ? 5 : 10; return nice * power; } /** * Round tick values covering [min, max], about `count` of them. The first and * last ticks become the scale's domain, so the grid always ends on a label. */ export function niceTicks(min: number, max: number, count = 4): number[] { if (min === max) { if (min === 0) return [0, 1]; [min, max] = min > 0 ? [0, max] : [min, 0]; } const step = niceStep(max - min, count); const start = Math.floor(min / step) * step; const end = Math.ceil(max / step) * step; const ticks: number[] = []; // Rounded so float drift never shows up as 0.30000000000000004. for (let v = start; v <= end + step / 2; v += step) ticks.push(Number(v.toPrecision(12))); return ticks; } /** Index of the point in `xs` (sorted ascending) closest to `x`. */ export function nearest(xs: readonly number[], x: number) { let lo = 0; let hi = xs.length - 1; while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (xs[mid] < x) lo = mid; else hi = mid; } return Math.abs(xs[hi] - x) < Math.abs(xs[lo] - x) ? hi : lo; } export const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); // ─── Paths ──────────────────────────────────────────────────────────────────── export type Point = readonly [x: number, y: number]; /** * A smooth line through every point that never overshoots them (monotone cubic, * like d3's curveMonotoneX), so peaks and dips stay where the data puts them. */ export function linePath(points: readonly Point[]) { const n = points.length; if (n === 0) return ""; if (n === 1) return `M${points[0][0]},${points[0][1]}`; if (n === 2) return `M${points[0][0]},${points[0][1]}L${points[1][0]},${points[1][1]}`; // Secant slopes, then tangents limited so each segment stays monotone. const dx: number[] = []; const slope: number[] = []; for (let i = 0; i < n - 1; i++) { dx[i] = points[i + 1][0] - points[i][0]; slope[i] = dx[i] ? (points[i + 1][1] - points[i][1]) / dx[i] : 0; } const tangent: number[] = [slope[0]]; for (let i = 1; i < n - 1; i++) { const a = slope[i - 1]; const b = slope[i]; tangent[i] = a * b <= 0 ? 0 : (3 * (dx[i - 1] + dx[i])) / ((2 * dx[i] + dx[i - 1]) / a + (dx[i] + 2 * dx[i - 1]) / b); } tangent[n - 1] = slope[n - 2]; const f = (v: number) => Math.round(v * 100) / 100; let d = `M${f(points[0][0])},${f(points[0][1])}`; for (let i = 0; i < n - 1; i++) { const [x0, y0] = points[i]; const [x1, y1] = points[i + 1]; const h = dx[i] / 3; d += `C${f(x0 + h)},${f(y0 + h * tangent[i])},${f(x1 - h)},${f(y1 - h * tangent[i + 1])},${f(x1)},${f(y1)}`; } return d; } /** The line closed down to `baseY`, for an area fill under it. */ export function areaPath(points: readonly Point[], baseY: number) { if (points.length < 2) return ""; const first = points[0]; const last = points[points.length - 1]; return `${linePath(points)}L${last[0]},${baseY}L${first[0]},${baseY}Z`; } /** * A bar with rounded corners on its value end and square corners on its * baseline. `x`, `y`, `w`, `h` describe the box; `from` is the baseline side. */ export function barPath(x: number, y: number, w: number, h: number, r: number, from: "bottom" | "left" = "bottom") { if (w <= 0 || h <= 0) return ""; if (from === "bottom") { const rr = Math.min(r, w / 2, h); 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`; } const rr = Math.min(r, h / 2, w); return `M${x},${y}H${x + w - rr}Q${x + w},${y} ${x + w},${y + rr}V${y + h - rr}Q${x + w},${y + h} ${x + w - rr},${y + h}H${x}Z`; } // ═══ Format ══════════════════════════════════════════════════════════════════ // Number formatting shared by every chart. A chart takes one `format` prop // (plain Intl.NumberFormat options), so the headline, tooltip, axis and table // all agree, and NumberFlow can animate with the same options. export type ValueFormat = Intl.NumberFormatOptions & { notation?: "standard" | "compact"; }; const LOCALE = "en-US"; const cache = new Map(); const formatter = (format: ValueFormat) => { const key = JSON.stringify(format); let f = cache.get(key); if (!f) { f = new Intl.NumberFormat(LOCALE, format); cache.set(key, f); } return f; }; /** 1284 -> "1,284"; with { style: "currency", currency: "USD" } -> "$1,284". */ export const formatValue = (value: number, format: ValueFormat = {}) => formatter(format).format(value); /** Short form for axis ticks and tight labels: 12,900 -> "12.9K", $4,200,000 -> "$4.2M". */ export const formatCompact = (value: number, format: ValueFormat = {}) => formatter({ ...format, notation: "compact", maximumFractionDigits: 1, minimumFractionDigits: 0 }).format(value); /** Signed share: 0.124 -> "+12.4%", -0.03 -> "−3%". */ export const formatDelta = (fraction: number) => { const text = formatter({ style: "percent", maximumFractionDigits: 1, signDisplay: "exceptZero" }).format(fraction); // A true minus sign lines up with the plus. return text.replace("-", "−"); }; /** Share of a whole: 0.4213 -> "42.1%". */ export const formatShare = (fraction: number) => formatter({ style: "percent", maximumFractionDigits: fraction < 0.1 && fraction > 0 ? 1 : 0 }).format(fraction); /** Ready-made formats for a meta.ts `select` control. */ export const FORMATS = { number: {}, currency: { style: "currency", currency: "USD", maximumFractionDigits: 0 }, percent: { style: "percent", maximumFractionDigits: 1 }, compact: { notation: "compact", maximumFractionDigits: 1 }, } satisfies Record; export type FormatName = keyof typeof FORMATS; // ═══ Sample data ═════════════════════════════════════════════════════════════ // Seeded sample data, so every demo shows the same believable numbers on the // server and the client (no hydration mismatch) and changes only with its seed. /** Repeatable random numbers in [0, 1) from a seed (mulberry32). */ export function seeded(seed: number) { let s = seed >>> 0; return () => { s = (s + 0x6d2b79f5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } /** * `count` values that wander from `start` with a gentle `trend` per step and * `noise` as a share of the current value. Never drops below zero. */ export function walk(count: number, { seed = 1, start = 100, trend = 0.01, noise = 0.06 } = {}) { const rand = seeded(seed); const out: number[] = []; let v = start; for (let i = 0; i < count; i++) { out.push(Math.max(0, Math.round(v))); v *= 1 + trend + (rand() * 2 - 1) * noise; } return out; } const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; /** * Labels for `count` consecutive days ending on `end`: "Oct 12". A fixed end * date keeps the server and client in agreement. */ export function dayLabels(count: number, end = new Date(2026, 9, 12)) { return Array.from({ length: count }, (_, i) => { const d = new Date(end); d.setDate(end.getDate() - (count - 1 - i)); return `${MONTHS[d.getMonth()]} ${d.getDate()}`; }); } /** Labels for `count` months ending on `end`: "Oct", or "Oct 2026" with `year`. */ export function monthLabels(count: number, { end = new Date(2026, 9, 1), year = false } = {}) { return Array.from({ length: count }, (_, i) => { const d = new Date(end.getFullYear(), end.getMonth() - (count - 1 - i), 1); return year ? `${MONTHS[d.getMonth()]} ${d.getFullYear()}` : MONTHS[d.getMonth()]; }); } /** * `count` values that swell and ebb like a slow wave around `base`: `amp` is * the swing as a share of `base`, `period` the steps per cycle. */ export function wave(count: number, { seed = 1, base = 100, amp = 0.4, period = 10, phase = 0, noise = 0.08 } = {}) { const rand = seeded(seed); return Array.from({ length: count }, (_, i) => Math.max(0, Math.round(base * (1 + amp * Math.sin((i / period) * Math.PI * 2 + phase)) * (1 + (rand() * 2 - 1) * noise))), ); } // ═══ Axis ════════════════════════════════════════════════════════════════════ // Axis label placement shared by charts that draw their own x axis. // Rough width of one 11px tabular character, for laying out labels without measuring the DOM. export const CHAR = 6.4; const LABEL_GAP = 16; /** * Which rows get an x label: as many as fit (6 at most, 2 at least), evenly * spread, with the first and last pinned to the plot's edges. */ export function xLabelIndices(labels: readonly string[], left: number, right: number) { const n = labels.length; if (n < 2) return n ? [0] : []; const w = (i: number) => labels[i].length * CHAR; for (let k = Math.min(6, n); k >= 2; k--) { const idx = Array.from({ length: k }, (_, j) => Math.round((j * (n - 1)) / (k - 1))); const at = (i: number) => left + ((right - left) * i) / (n - 1); // Each label's box: first grows right, last grows left, the rest are centred. const boxes = idx.map((i, j) => { const x = at(i); if (j === 0) return [x, x + w(i)]; if (j === k - 1) return [x - w(i), x]; return [x - w(i) / 2, x + w(i) / 2]; }); if (boxes.every((b, j) => j === 0 || b[0] - boxes[j - 1][1] >= LABEL_GAP)) return idx; } return [0, n - 1]; } // ═══ Parts ═══════════════════════════════════════════════════════════════════ // The pieces every chart is built from, so they all share one shell, one // tooltip, one legend and one way to read a change. // ─── Shell ──────────────────────────────────────────────────────────────────── export type ChartCardProps = { /** Names what is plotted. */ title: ReactNode; /** The headline, usually a . */ value?: ReactNode; /** Sits on the headline's baseline, usually a . */ meta?: ReactNode; /** Top-right corner: range tabs, a live badge. */ aside?: ReactNode; /** Under the plot panel: a legend or a note. */ footer?: ReactNode; /** Padding inside the plot panel. Default true. */ padded?: boolean; className?: string; style?: CSSProperties; children: ReactNode; }; /** Outer surface with the heading, and an inset panel holding the plot. */ export function ChartCard({ title, value, meta, aside, footer, padded = true, className, style, children }: ChartCardProps) { return (
{/* On narrow cards the corner controls drop under the heading rather than squeeze it. */}
{title}
{(value !== undefined || meta) && (
{value} {meta}
)}
{aside &&
{aside}
}
{children}
{footer &&
{footer}
}
); } /** The big number in a card's heading. Rolls between values. */ export function Headline({ value, format, className }: { value: number; format?: ValueFormat; className?: string }) { return ( ); } // ─── Change ─────────────────────────────────────────────────────────────────── export type DeltaProps = { /** Change as a fraction: 0.124 is +12.4%. */ value: number; /** Set when lower is better (churn, latency, cost): a fall reads as good. */ invert?: boolean; /** Period the change is measured against, e.g. "vs last month". */ label?: ReactNode; className?: string; }; /** A signed change in a tinted pill, green when it's good news and red when it's not. */ export function Delta({ value, invert = false, label, className }: DeltaProps) { const flat = Math.abs(value) < 0.0005; const good = flat ? null : value > 0 !== invert; const Arrow = value >= 0 ? IconArrowUpRight : IconArrowDownRight; return ( {label && {label}} ); } // ─── Tooltip ────────────────────────────────────────────────────────────────── export type TooltipProps = { /** Anchor point in px, relative to the positioned parent. The tip sits above it. */ x: number; y: number; /** Width of the area the tip must stay inside, in px. */ bounds: number; visible: boolean; children: ReactNode; }; /** * One tooltip for every chart: inverted, above its anchor, gliding from point * to point and leaning inward near the edges instead of hanging off the card. * When there's no room above (a peak near the top of the plot) it drops below * the anchor, so it never covers the card's heading. */ export function Tooltip({ x, y, bounds, visible, children }: TooltipProps) { const reduce = useReducedMotion(); const [ref, { width, height }] = useMeasure(); const left = clamp(x - width / 2, 0, Math.max(0, bounds - width)); const top = y - 8 - height >= 0 ? y - 8 - height : y + 14; return ( {visible && (
{children}
)}
); } /** Heading line of a tooltip, usually the date or category. */ export function TooltipTitle({ children }: { children: ReactNode }) { return
{children}
; } /** One series in a tooltip: a short stroke of its colour, the value, then its name. */ export function TooltipRow({ color, value, label }: { color: string; value: ReactNode; label: ReactNode }) { return (
{value} {label}
); } // ─── Legend ─────────────────────────────────────────────────────────────────── export type LegendItem = { key: string; label: string; color: string }; export type LegendProps = { items: readonly LegendItem[]; /** "line" for line charts, "square" for bars and areas, "dot" for points. */ mark?: "line" | "square" | "dot"; /** Keys switched off. With `onToggle`, each item becomes a button. */ hidden?: readonly string[]; onToggle?: (key: string) => void; /** Key under the pointer, to dim the rest. */ active?: string | null; onActiveChange?: (key: string | null) => void; className?: string; }; /** Names every series. Optionally switches them on and off. */ export function Legend({ items, mark = "square", hidden = [], onToggle, active, onActiveChange, className }: LegendProps) { return (
    onActiveChange?.(null)}> {items.map((item) => { const off = hidden.includes(item.key); const dim = off || (active != null && active !== item.key); const body = ( <> {item.label} ); const base = "flex h-7 items-center gap-1.5 rounded-lg px-2 text-xs font-medium text-muted-foreground"; return (
  • {onToggle ? ( ) : ( onActiveChange?.(item.key)}> {body} )}
  • ); })}
); } // ─── Segmented control ──────────────────────────────────────────────────────── /** Small pill tabs for a card's corner: time ranges, views. */ export function Segmented({ options, value, onChange, label, fill = false, }: { options: readonly { value: T; label: string }[]; value: T; onChange: (value: T) => void; /** Names the group for screen readers. */ label: string; /** Span the container with equal-width options, for form fields. Otherwise it hugs its options. */ fill?: boolean; }) { const reduce = useReducedMotion(); const id = useId(); return (
{options.map((o) => { const on = o.value === value; return ( ); })}
); } // ─── Accessibility ──────────────────────────────────────────────────────────── /** * The chart's numbers as a table only screen readers see. The table sits in a * clipped wrapper: `sr-only` on the table itself is ignored by its rows, which * would stretch the page and put a scrollbar on previews. */ export function DataTable({ caption, columns, rows, }: { caption: string; columns: readonly string[]; rows: readonly (readonly ReactNode[])[]; }) { return (
{columns.map((c) => ( ))} {rows.map((r, i) => ( {r.map((cell, j) => (j === 0 ? : ))} ))}
{caption}
{c}
{cell}{cell}
); } /** Reads `children` aloud when it changes, e.g. the point under the keyboard cursor. */ export function Announce({ children }: { children: ReactNode }) { return ( {children} ); } // ─── Cursor ─────────────────────────────────────────────────────────────────── /** * Which point is active, from the pointer or the keyboard. Spread `bind` on * the focusable plot: arrows step, Home and End jump, Escape clears. `keyboard` * says whether to draw a focus ring on the active point. */ export function useChartCursor(count: number) { const [active, setActive] = useState(null); const [keyboard, setKeyboard] = useState(false); const onKeyDown = (e: KeyboardEvent) => { if (!count) return; const at = active ?? count - 1; const next = e.key === "ArrowLeft" || e.key === "ArrowDown" ? at - 1 : e.key === "ArrowRight" || e.key === "ArrowUp" ? at + 1 : e.key === "Home" ? 0 : e.key === "End" ? count - 1 : undefined; if (e.key === "Escape") { setActive(null); return; } if (next === undefined) return; e.preventDefault(); setKeyboard(true); setActive(clamp(next, 0, count - 1)); }; return { active: active !== null && active < count ? active : null, keyboard, /** For pointer moves: activates `index` and hides the keyboard ring. */ point: (index: number | null) => { setKeyboard(false); setActive(index); }, bind: { tabIndex: 0, onKeyDown, onFocus: (e: FocusEvent) => { if (!e.currentTarget.matches(":focus-visible")) return; setKeyboard(true); setActive((a) => a ?? count - 1); }, onBlur: () => { setKeyboard(false); setActive(null); }, onPointerLeave: () => { if (!keyboard) setActive(null); }, }, }; } /** Width of an element, for charts that fill their container. 0 until measured. */ export function useWidth() { const [ref, { width }] = useMeasure(); return [ref, width] as const; } ``` ## Usage ```tsx import { SplitBar } from "@/components/uibrik/split-bar/split-bar"; const items = [ { label: "Photos", value: 38.4 }, { label: "Documents", value: 21.7 }, // …3 more ]; {}} // total={0} // format={…} /> ``` ## Props of `SplitBar` | Prop | Type | Default | Description | | --- | --- | --- | --- | | title | `string` | `""` | Names the whole. Empty uses the sample's name. | | showList | `boolean` | `true` | List every part under the bar. | | items | `{ label: string; value: number; color?: string }[]` | | The parts, in bar order. Past six, the rest fold into Other. | | total | `number` | | Full capacity. The rest of the bar shows what's left. | | format | `Intl.NumberFormatOptions` | `GB for the sample` | Formats every number, e.g. { style: "currency", currency: "USD" }. | | onSelect | `(item: SplitItem) => void` | | Called with the part picked from the bar or the list. | | className | `string` | | Classes for the outer shell. | Source and live preview: https://uibrik.com/components/split-bar