All components
Chart
Composable area, line, bar, sparkline, and category-bar data visualizations powered by TanStack Charts and StyleX.
12345678910111213141516171819202122import { AreaChart } from "#components/ui/base-ui/chart.tsx";
const data = [ { month: "Jan", Revenue: 4200, Expenses: 2800 }, { month: "Feb", Revenue: 4850, Expenses: 3100 }, { month: "Mar", Revenue: 5400, Expenses: 2950 }, { month: "Apr", Revenue: 6150, Expenses: 3400 }, { month: "May", Revenue: 7100, Expenses: 3650 }, { month: "Jun", Revenue: 8300, Expenses: 4100 },];
export function Example() { return ( <AreaChart data={data} index="month" categories={["Revenue", "Expenses"]} colors={["blue", "emerald"]} valueFormatter={(value) => `$${value.toLocaleString()}`} /> );}Reference line & zoomed Y-domain
Overlay a dashed horizontal `referenceLine` threshold with an optional label and narrow the vertical scale via `yDomain` so tight variance stays legible.
12345678910111213141516import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";
export function RevenueTargetChart({ data }: { data: Record<string, unknown>[] }) { return ( <AreaChart data={data} index="month" categories={["Revenue"]} colors={["emerald"]} height={210} yDomain={[3500, 9000]} referenceLine={{ value: 6000, label: "Target $6k", color: "amber" }} valueFormatter={(value) => `$${value.toLocaleString()}`} /> );}Line chart
Multi-series trends with optional point markers, crosshair hover tooltips, and click-to-toggle legend items.
123456789101112131415import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";
export function TrafficLineChart({ data }: { data: Record<string, unknown>[] }) { return ( <LineChart data={data} index="day" categories={["Organic", "Direct", "Referral"]} colors={["indigo", "cyan", "amber"]} curve="monotone" showDots height={220} /> );}Bar chart (grouped & stacked)
Switch between side-by-side grouped bars and stacked bars in vertical or horizontal layouts.
Grouped vertical ($k)
Stacked horizontal ($k)
12345678910111213141516171819202122232425import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";
export function RevenueBarCharts({ data }: { data: Record<string, unknown>[] }) { return ( <> <BarChart data={data} index="quarter" categories={["Enterprise", "SelfServe", "Usage"]} colors={["blue", "emerald", "violet"]} type="grouped" valueFormatter={(v) => `$${v}k`} /> <BarChart data={data} index="quarter" categories={["Enterprise", "SelfServe", "Usage"]} colors={["blue", "emerald", "violet"]} type="stacked" layout="horizontal" valueFormatter={(v) => `$${v}k`} /> </> );}Sparklines in KPI cards
Axis-free inline line and area sparklines with optional hover tooltips for compact metric tiles.
Net MRR+18.4%
$71.4k
p95 Latency-29.2%
34 ms
Monthly Churn+0.6%
2.5%
123456789101112131415import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";
export function KpiSparkline({ data }: { data: Record<string, unknown>[] }) { return ( <Sparkline data={data} index="day" categories={["value"]} colors={["emerald"]} variant="area" showTooltip height={42} /> );}Category bar
Proportional multi-segment horizontal bar with an optional target marker pin and inline summary legend.
Quota attainmentTarget: 75%
Closed Won42%
Commit26%
Best Case18%
Remaining14%
12345678910111213import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";
export function QuotaCategoryBar() { return ( <CategoryBar values={[42, 26, 18, 14]} labels={["Closed Won", "Commit", "Best Case", "Remaining"]} colors={["emerald", "blue", "amber", "slate"]} markerValue={75} valueFormatter={(value) => `${value}%`} /> );}Install
1npx stylexblocks add chartSource
components/ui/base-ui/chart.tsx
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324import * as stylex from "@stylexjs/stylex";import { areaY, barX, barY, defineChart, dot, group, lineY, ruleY, stack, text, whenFocused, type ChartCurve,} from "@tanstack/charts";import { crosshair } from "@tanstack/charts/crosshair";import { decorative } from "@tanstack/charts/mark/decorative";import { Chart } from "@tanstack/charts/react/tooltip";import { scaleBand } from "@tanstack/charts/scales/band";import { scaleLinear } from "@tanstack/charts/scales/linear";import { scaleOrdinal } from "@tanstack/charts/scales/ordinal";import { tooltip } from "@tanstack/charts/tooltip";import { useCallback, useMemo, useState } from "react";import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";import { semanticShadows } from "@stylexblocks/ui/semantic-tokens/shadows.stylex.ts";import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";import { lineHeights } from "@stylexblocks/ui/tokens/line-heights.stylex.ts";import { radii } from "@stylexblocks/ui/tokens/radii.stylex.ts";import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";import type { StyleOverrideProps } from "#lib/recipe-props.ts";
// ============= PALETTE =============
/** Named StyleX-token chart colors with high contrast across light & dark themes. */export const chartColors = { blue: semanticColors.blueSolid, emerald: semanticColors.emeraldSolid, amber: semanticColors.amberSolid, violet: semanticColors.violetSolid, rose: semanticColors.roseSolid, cyan: semanticColors.cyanSolid, indigo: semanticColors.indigoSolid, teal: semanticColors.tealSolid, orange: semanticColors.orangeSolid, slate: semanticColors.graySolid,} as const;
export type ChartColorName = keyof typeof chartColors;
/** Default 6-color sequence used when `colors` is omitted or shorter than `categories`. */export const DEFAULT_CHART_COLORS: readonly ChartColorName[] = [ "blue", "emerald", "amber", "violet", "rose", "cyan",] as const;
/** * Resolves a named chart color (e.g. `"emerald"`), passes through arbitrary CSS * colors / custom properties, or falls back to `DEFAULT_CHART_COLORS[index]`. */export function resolveChartColor(color: string | undefined, index = 0): string { if (color && color in chartColors) { return chartColors[color as ChartColorName]; } if (color && color.trim().length > 0) { return color; } const safeIndex = ((index % DEFAULT_CHART_COLORS.length) + DEFAULT_CHART_COLORS.length) % DEFAULT_CHART_COLORS.length; return chartColors[DEFAULT_CHART_COLORS[safeIndex]!];}
// ============= CURVE GENERATORS =============
export type ChartCurveType = "linear" | "monotone" | "step";
type Point2D = readonly [number, number];
function computeMonotoneControls( points: readonly Point2D[],): Array<readonly [number, number, number, number]> { const n = points.length; if (n < 2) return [];
const slopes: number[] = []; for (let i = 0; i < n - 1; i++) { const dx = points[i + 1]![0] - points[i]![0]; const dy = points[i + 1]![1] - points[i]![1]; slopes.push(dx === 0 ? 0 : dy / dx); }
const tangents = new Array<number>(n).fill(0); if (n === 2) { tangents[0] = slopes[0]!; tangents[1] = slopes[0]!; } else { for (let i = 1; i < n - 1; i++) { const s0 = slopes[i - 1]!; const s1 = slopes[i]!; if (s0 * s1 <= 0) { tangents[i] = 0; } else { const h0 = points[i]![0] - points[i - 1]![0]; const h1 = points[i + 1]![0] - points[i]![0]; const p = (s0 * h1 + s1 * h0) / (h0 + h1); tangents[i] = (Math.sign(s0) + Math.sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)); } } const clampEndpoint = (t: number, s: number) => { if (t * s <= 0) return 0; if (Math.abs(t) > 3 * Math.abs(s)) return 3 * s; return t; }; tangents[0] = clampEndpoint((3 * slopes[0]! - tangents[1]!) / 2, slopes[0]!); tangents[n - 1] = clampEndpoint( (3 * slopes[n - 2]! - tangents[n - 2]!) / 2, slopes[n - 2]!, ); }
const segments: Array<readonly [number, number, number, number]> = []; for (let i = 0; i < n - 1; i++) { const p0 = points[i]!; const p1 = points[i + 1]!; const dx = (p1[0] - p0[0]) / 3; segments.push([ p0[0] + dx, p0[1] + dx * tangents[i]!, p1[0] - dx, p1[1] - dx * tangents[i + 1]!, ]); } return segments;}
const MONOTONE_CURVE: ChartCurve = { line(points) { if (points.length === 0) return ""; const first = points[0]!; if (points.length === 1) return `M${first[0]},${first[1]}`; const controls = computeMonotoneControls(points); let d = `M${first[0]},${first[1]}`; for (let i = 0; i < controls.length; i++) { const [c1x, c1y, c2x, c2y] = controls[i]!; const p1 = points[i + 1]!; d += `C${c1x},${c1y},${c2x},${c2y},${p1[0]},${p1[1]}`; } return d; }, area(top, bottom) { if (top.length === 0 || bottom.length === 0) return ""; const firstTop = top[0]!; const lastBottom = bottom[bottom.length - 1]!; if (top.length === 1) { return `M${firstTop[0]},${firstTop[1]}L${lastBottom[0]},${lastBottom[1]}Z`; } const topControls = computeMonotoneControls(top); const bottomControls = computeMonotoneControls(bottom); let d = `M${firstTop[0]},${firstTop[1]}`; for (let i = 0; i < topControls.length; i++) { const [c1x, c1y, c2x, c2y] = topControls[i]!; const p1 = top[i + 1]!; d += `C${c1x},${c1y},${c2x},${c2y},${p1[0]},${p1[1]}`; } d += `L${lastBottom[0]},${lastBottom[1]}`; for (let i = bottomControls.length - 1; i >= 0; i--) { const [c1x, c1y, c2x, c2y] = bottomControls[i]!; const p0 = bottom[i]!; d += `C${c2x},${c2y},${c1x},${c1y},${p0[0]},${p0[1]}`; } return `${d}Z`; },};
const STEP_CURVE: ChartCurve = { line(points) { if (points.length === 0) return ""; const first = points[0]!; let d = `M${first[0]},${first[1]}`; for (let i = 1; i < points.length; i++) { const p = points[i]!; d += `H${p[0]}V${p[1]}`; } return d; }, area(top, bottom) { if (top.length === 0 || bottom.length === 0) return ""; const firstTop = top[0]!; const lastBottom = bottom[bottom.length - 1]!; let d = `M${firstTop[0]},${firstTop[1]}`; for (let i = 1; i < top.length; i++) { const p = top[i]!; d += `H${p[0]}V${p[1]}`; } d += `L${lastBottom[0]},${lastBottom[1]}`; for (let i = bottom.length - 1; i >= 1; i--) { const prev = bottom[i - 1]!; d += `V${prev[1]}H${prev[0]}`; } return `${d}Z`; },};
function resolveCurve(curve: ChartCurveType | undefined): ChartCurve | undefined { if (curve === "monotone") return MONOTONE_CURVE; if (curve === "step") return STEP_CURVE; return undefined;}
// ============= NUMERIC & AXIS HELPERS =============
const DEFAULT_NUMBER_FORMATTER = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2,});
function defaultValueFormatter(value: number): string { return DEFAULT_NUMBER_FORMATTER.format(value);}
function defaultCompactFormatter(value: number): string { const abs = Math.abs(value); if (abs >= 1_000_000) return `${Number((value / 1_000_000).toFixed(1))}M`; if (abs >= 10_000) return `${Number((value / 1_000).toFixed(1))}k`; return DEFAULT_NUMBER_FORMATTER.format(value);}
function toFiniteNumber(raw: unknown): number | null { if (typeof raw === "number" && Number.isFinite(raw)) return raw; return null;}
function niceStep(rawStep: number): number { if (!Number.isFinite(rawStep) || rawStep <= 0) return 1; const exponent = Math.floor(Math.log10(rawStep)); const magnitude = 10 ** exponent; const normalized = rawStep / magnitude; if (normalized <= 1) return 1 * magnitude; if (normalized <= 2) return 2 * magnitude; if (normalized <= 2.5) return 2.5 * magnitude; if (normalized <= 5) return 5 * magnitude; return 10 * magnitude;}
function computeNumericAxis( values: ReadonlyArray<number>, includeZero = true,): { min: number; max: number; ticks: number[] } { if (values.length === 0) { return { min: 0, max: 100, ticks: [0, 25, 50, 75, 100] }; } let dataMin = Number.POSITIVE_INFINITY; let dataMax = Number.NEGATIVE_INFINITY; for (const v of values) { if (v < dataMin) dataMin = v; if (v > dataMax) dataMax = v; } if (includeZero) { dataMin = Math.min(0, dataMin); dataMax = Math.max(0, dataMax); } if (dataMin === dataMax) { const pad = dataMax === 0 ? 10 : Math.abs(dataMax) * 0.2; dataMin = includeZero && dataMin >= 0 ? 0 : dataMin - pad; dataMax = dataMax + pad; }
const step = niceStep((dataMax - dataMin) / 4); const niceMin = Math.floor(dataMin / step) * step; const niceMax = Math.ceil(dataMax / step) * step; const ticks: number[] = []; const count = Math.min(8, Math.max(2, Math.round((niceMax - niceMin) / step))); for (let i = 0; i <= count; i++) { const tick = Number((niceMin + i * step).toFixed(10)); ticks.push(Object.is(tick, -0) ? 0 : tick); } return { min: ticks[0] ?? niceMin, max: ticks[ticks.length - 1] ?? niceMax, ticks, };}
function computeDomainAxis( minRaw: number, maxRaw: number,): { min: number; max: number; ticks: number[] } { let min = minRaw; let max = maxRaw; if (!Number.isFinite(min) || !Number.isFinite(max)) { return { min: 0, max: 100, ticks: [0, 25, 50, 75, 100] }; } if (min > max) [min, max] = [max, min]; if (min === max) { const pad = max === 0 ? 10 : Math.abs(max) * 0.2; min -= pad; max += pad; }
const step = niceStep((max - min) / 4); const firstTick = Math.ceil(min / step) * step; const ticks: number[] = []; for (let v = firstTick; v <= max + step * 1e-9 && ticks.length < 8; v += step) { const tick = Number(v.toFixed(10)); ticks.push(Object.is(tick, -0) ? 0 : tick); } if (ticks.length < 2) { const mid = Number(((min + max) / 2).toFixed(10)); return { min, max, ticks: [min, Object.is(mid, -0) ? 0 : mid, max] }; } return { min, max, ticks };}
function computeSlotTicks(length: number): number[] { if (length <= 0) return [0]; if (length === 1) return [0]; if (length <= 7) { return Array.from({ length }, (_, i) => i); } const last = length - 1; const segments = 4; const result = new Set<number>([0, last]); for (let i = 1; i < segments; i++) { result.add(Math.round((last * i) / segments)); } return Array.from(result).sort((a, b) => a - b);}
const CHART_THEME = { foreground: semanticColors.fg, muted: semanticColors.fgMuted, grid: semanticColors.fg, background: "transparent",} as const;
// ============= STYLES =============
const styles = stylex.create({ root: { color: semanticColors.fg, display: "flex", flexDirection: "column", fontFamily: fonts.body, gap: spacing._3, width: "100%", }, chartHost: { width: "100%", "--ts-chart-tooltip-background": "transparent", "--ts-chart-tooltip-border": "none", "--ts-chart-tooltip-border-radius": "0px", "--ts-chart-tooltip-padding": "0px", "--ts-chart-tooltip-shadow": "none", }, emptyState: { alignItems: "center", backgroundColor: semanticColors.bgMuted, borderColor: semanticColors.borderSubtle, borderRadius: radii.md, borderStyle: "dashed", borderWidth: "1px", color: semanticColors.fgMuted, display: "flex", fontSize: fontSizes.xs, justifyContent: "center", width: "100%", }, emptyHeight: (height: number) => ({ height: `${height}px`, }), tooltipCard: { backgroundColor: semanticColors.bgElevated, borderColor: semanticColors.border, borderRadius: radii.lg, borderStyle: "solid", borderWidth: "1px", boxShadow: semanticShadows.md, color: semanticColors.fg, display: "flex", flexDirection: "column", fontFamily: fonts.body, gap: spacing._1_5, minWidth: "10.5rem", paddingBlock: spacing._2_5, paddingInline: spacing._3, }, tooltipTitle: { color: semanticColors.fgMuted, fontSize: fontSizes.xs, fontWeight: fontWeights.medium, lineHeight: lineHeights.xs, }, tooltipRows: { display: "flex", flexDirection: "column", gap: spacing._1, }, tooltipRow: { alignItems: "center", borderRadius: radii.sm, display: "flex", fontSize: fontSizes.xs, gap: spacing._3, justifyContent: "space-between", marginInline: `calc(-1 * ${spacing._1_5})`, paddingBlock: "0.125rem", paddingInline: spacing._1_5, }, tooltipRowPrimary: { backgroundColor: semanticColors.interactionHover, }, tooltipLead: { alignItems: "center", color: semanticColors.fg, display: "flex", gap: spacing._2, }, tooltipValue: { color: semanticColors.fg, fontFamily: fonts.mono, fontVariantNumeric: "tabular-nums", fontWeight: fontWeights.semibold, }, tooltipReference: { borderTopColor: semanticColors.borderSubtle, borderTopStyle: "solid", borderTopWidth: "1px", color: semanticColors.fgMuted, fontFamily: fonts.mono, fontSize: fontSizes.xs, fontVariantNumeric: "tabular-nums", lineHeight: lineHeights.xs, paddingTop: spacing._1_5, }, legendRow: { alignItems: "center", display: "flex", flexWrap: "wrap", gap: spacing._4, }, legendAlignStart: { justifyContent: "flex-start", }, legendAlignCenter: { justifyContent: "center", }, legendAlignEnd: { justifyContent: "flex-end", }, legendItem: { alignItems: "center", color: semanticColors.fgMuted, display: "inline-flex", fontFamily: fonts.body, fontSize: fontSizes.xs, fontWeight: fontWeights.medium, gap: spacing._1_5, lineHeight: lineHeights.xs, }, legendButton: { alignItems: "center", backgroundColor: { default: "transparent", ":hover": semanticColors.interactionHover, }, borderRadius: radii.sm, borderStyle: "none", borderWidth: 0, color: { default: semanticColors.fgMuted, ":hover": semanticColors.fg, }, cursor: "pointer", display: "inline-flex", fontFamily: fonts.body, fontSize: fontSizes.xs, fontWeight: fontWeights.medium, gap: spacing._1_5, lineHeight: lineHeights.xs, outlineColor: semanticColors.accentFocusRing, outlineOffset: "2px", paddingBlock: spacing._0_5, paddingInline: spacing._1_5, marginInline: `calc(-1 * ${spacing._1_5})`, transitionDuration: "150ms", transitionProperty: "opacity, background-color, color", }, legendHidden: { opacity: 0.4, textDecorationLine: "line-through", }, swatch: { borderRadius: "2px", display: "inline-block", flexShrink: 0, height: "0.625rem", width: "0.625rem", }, swatchColor: (color: string) => ({ backgroundColor: color, }), sparklineRoot: { display: "block", width: "100%", }, categoryBarRoot: { color: semanticColors.fg, display: "flex", flexDirection: "column", fontFamily: fonts.body, gap: spacing._2_5, width: "100%", }, categoryBarTrackWrap: { alignItems: "center", display: "flex", position: "relative", width: "100%", }, categoryBarTrack: { backgroundColor: semanticColors.bgMuted, borderRadius: radii.full, display: "flex", gap: "2px", height: "0.5rem", overflow: "hidden", width: "100%", }, categoryBarSegment: (widthPct: number, color: string) => ({ backgroundColor: color, height: "100%", width: `${widthPct}%`, transitionDuration: "200ms", transitionProperty: "width", }), categoryBarMarker: (leftPct: number) => ({ backgroundColor: semanticColors.fg, borderRadius: radii.full, bottom: "-3px", boxShadow: `0 0 0 2px ${semanticColors.bgSurface}`, left: `calc(${leftPct}% - 1px)`, pointerEvents: "none", position: "absolute", top: "-3px", width: "2px", }), categoryBarLabels: { alignItems: "center", display: "flex", flexWrap: "wrap", gap: spacing._4, }, categoryBarLabelItem: { alignItems: "center", display: "inline-flex", fontSize: fontSizes.xs, gap: spacing._1_5, lineHeight: lineHeights.xs, }, categoryBarLabelText: { color: semanticColors.fgMuted, fontWeight: fontWeights.medium, }, categoryBarLabelValue: { color: semanticColors.fg, fontFamily: fonts.mono, fontVariantNumeric: "tabular-nums", fontWeight: fontWeights.semibold, },});
const legendAlignMap = { start: styles.legendAlignStart, center: styles.legendAlignCenter, end: styles.legendAlignEnd,} as const;
// ============= SHARED TOOLTIP BODY =============
export interface ChartReferenceLine { value: number; label?: string; color?: string;}
interface TooltipSeriesEntry { id: string; label: string; series: string; value: number;}
function ChartTooltipCard({ title, entries, primaryId, colorBySeries, formatValue, referenceLine,}: { title: string; entries: ReadonlyArray<TooltipSeriesEntry>; primaryId?: string; colorBySeries: ReadonlyMap<string, string>; formatValue: (value: number) => string; referenceLine?: ChartReferenceLine;}) { // Deduplicate by series in case multiple marks emit points for the same x slot const unique: TooltipSeriesEntry[] = []; const seen = new Set<string>(); for (const entry of entries) { if (seen.has(entry.series)) continue; seen.add(entry.series); unique.push(entry); } if (unique.length === 0) return null;
let referenceReadout: string | null = null; if (referenceLine && Number.isFinite(referenceLine.value)) { const refLabel = referenceLine.label ?? formatValue(referenceLine.value); if (unique.length === 1) { const diff = unique[0]!.value - referenceLine.value; const sign = diff > 0 ? "+" : diff < 0 ? "−" : ""; referenceReadout = `${sign}${formatValue(Math.abs(diff))} vs ${refLabel}`; } else { referenceReadout = referenceLine.label ? `${referenceLine.label}: ${formatValue(referenceLine.value)}` : `Ref: ${formatValue(referenceLine.value)}`; } }
return ( <div {...stylex.props(styles.tooltipCard)}> {title ? <div {...stylex.props(styles.tooltipTitle)}>{title}</div> : null} <div {...stylex.props(styles.tooltipRows)}> {unique.map((entry, idx) => { const swatchColor = colorBySeries.get(entry.series) ?? resolveChartColor(undefined, idx); const isPrimary = primaryId !== undefined && primaryId === entry.id; return ( <div key={entry.id} {...stylex.props( styles.tooltipRow, isPrimary && styles.tooltipRowPrimary, )} > <span {...stylex.props(styles.tooltipLead)}> <span {...stylex.props(styles.swatch, styles.swatchColor(swatchColor))} /> <span>{entry.series}</span> </span> <span {...stylex.props(styles.tooltipValue)}> {formatValue(entry.value)} </span> </div> ); })} </div> {referenceReadout ? ( <div {...stylex.props(styles.tooltipReference)}>{referenceReadout}</div> ) : null} </div> );}
// ============= HOOK: TOGGLEABLE SERIES =============
function useSeriesVisibility() { const [hiddenKeys, setHiddenKeys] = useState<ReadonlySet<string>>( () => new Set<string>(), ); const toggleSeries = useCallback((name: string) => { setHiddenKeys((prev) => { const next = new Set(prev); if (next.has(name)) next.delete(name); else next.add(name); return next; }); }, []); return { hiddenKeys, toggleSeries };}
// ============= CHART LEGEND =============
export interface ChartLegendItem { name: string; color: string;}
export interface ChartLegendProps extends StyleOverrideProps { items: ReadonlyArray<ChartLegendItem>; hiddenKeys?: ReadonlySet<string>; onToggle?: (name: string) => void; align?: "start" | "center" | "end"; ariaLabel?: string;}
/** * Interactive or static series legend strip. When `onToggle` is supplied, * items render as toggle buttons with `aria-pressed` state. */export function ChartLegend({ items, hiddenKeys, onToggle, align = "start", ariaLabel = "Chart legend", palette, style,}: ChartLegendProps) { if (items.length === 0) return null;
return ( <div role="group" aria-label={ariaLabel} {...stylex.props(palette, styles.legendRow, legendAlignMap[align], style)} > {items.map((item, idx) => { const resolved = resolveChartColor(item.color, idx); const isHidden = hiddenKeys?.has(item.name) ?? false; if (onToggle) { return ( <button key={item.name} type="button" aria-pressed={!isHidden} onClick={() => onToggle(item.name)} {...stylex.props( styles.legendButton, isHidden && styles.legendHidden, )} > <span {...stylex.props(styles.swatch, styles.swatchColor(resolved))} /> <span>{item.name}</span> </button> ); } return ( <span key={item.name} {...stylex.props(styles.legendItem, isHidden && styles.legendHidden)} > <span {...stylex.props(styles.swatch, styles.swatchColor(resolved))} /> <span>{item.name}</span> </span> ); })} </div> );}ChartLegend.displayName = "ChartLegend";
// ============= AREA CHART =============
export interface AreaChartProps extends StyleOverrideProps { data: ReadonlyArray<Record<string, unknown>>; index: string; categories: ReadonlyArray<string>; colors?: ReadonlyArray<string>; height?: number; type?: "default" | "stacked"; curve?: ChartCurveType; showLegend?: boolean; showGrid?: boolean; showTooltip?: boolean; showXAxis?: boolean; showYAxis?: boolean; valueFormatter?: (value: number) => string; connectNulls?: boolean; referenceLine?: ChartReferenceLine; yDomain?: readonly [number, number]; ariaLabel?: string;}
interface AreaRow { id: string; slot: number; label: string; series: string; value: number | null; y0: number | null; y1: number | null;}
/** * Multi-series area chart supporting overlapping (`default`) and cumulative * (`stacked`) layouts, smooth/linear/step curves, hover tooltips, optional * horizontal reference lines, custom Y-axis domains, and an interactive * toggleable legend. */export function AreaChart({ data, index, categories, colors, height = 240, type = "default", curve = "monotone", showLegend = true, showGrid = true, showTooltip = true, showXAxis = true, showYAxis = true, valueFormatter, connectNulls = false, referenceLine, yDomain, ariaLabel = "Area chart", palette, style,}: AreaChartProps) { const { hiddenKeys, toggleSeries } = useSeriesVisibility(); const formatValue = valueFormatter ?? defaultValueFormatter; const formatAxisValue = valueFormatter ?? defaultCompactFormatter;
const refValue = referenceLine?.value; const refLabel = referenceLine?.label; const refColor = referenceLine?.color; const yDomainMin = yDomain?.[0]; const yDomainMax = yDomain?.[1];
const legendItems = useMemo<ChartLegendItem[]>( () => categories.map((name, idx) => ({ name, color: resolveChartColor(colors?.[idx], idx), })), [categories, colors], );
const colorBySeries = useMemo( () => new Map(legendItems.map((item) => [item.name, item.color])), [legendItems], );
const activeCategories = useMemo( () => categories.filter((name) => !hiddenKeys.has(name)), [categories, hiddenKeys], );
const labels = useMemo( () => data.map((row, slot) => String(row[index] ?? slot)), [data, index], );
const { rows, yAxis } = useMemo(() => { const out: AreaRow[] = []; const extentValues: number[] = [];
if (type === "stacked") { const posBase = new Array<number>(data.length).fill(0); const negBase = new Array<number>(data.length).fill(0);
for (const series of activeCategories) { for (let slot = 0; slot < data.length; slot++) { const val = toFiniteNumber(data[slot]?.[series]); if (val === null) { if (!connectNulls) { out.push({ id: `${series}-${slot}`, slot, label: labels[slot] ?? String(slot), series, value: null, y0: null, y1: null, }); } continue; } let y0: number; let y1: number; if (val >= 0) { y0 = posBase[slot]!; y1 = y0 + val; posBase[slot] = y1; } else { y1 = negBase[slot]!; y0 = y1 + val; negBase[slot] = y0; } extentValues.push(y0, y1); out.push({ id: `${series}-${slot}`, slot, label: labels[slot] ?? String(slot), series, value: val, y0, y1, }); } } } else { for (const series of activeCategories) { for (let slot = 0; slot < data.length; slot++) { const val = toFiniteNumber(data[slot]?.[series]); if (val === null) { if (!connectNulls) { out.push({ id: `${series}-${slot}`, slot, label: labels[slot] ?? String(slot), series, value: null, y0: null, y1: null, }); } continue; } extentValues.push(val); out.push({ id: `${series}-${slot}`, slot, label: labels[slot] ?? String(slot), series, value: val, y0: 0, y1: val, }); } } }
if (refValue !== undefined && Number.isFinite(refValue)) { extentValues.push(refValue); }
const computedAxis = yDomainMin !== undefined && yDomainMax !== undefined ? computeDomainAxis(yDomainMin, yDomainMax) : computeNumericAxis(extentValues, true);
if (type !== "stacked") { const baseline = Math.min(computedAxis.max, Math.max(computedAxis.min, 0)); if (baseline !== 0) { for (const row of out) { if (row.y0 !== null) row.y0 = baseline; } } }
return { rows: out, yAxis: computedAxis }; }, [activeCategories, connectNulls, data, labels, refValue, type, yDomainMax, yDomainMin]);
const xTicks = useMemo(() => computeSlotTicks(data.length), [data.length]);
const definition = useMemo(() => { const resolvedCurve = resolveCurve(curve); const maxSlot = Math.max(1, data.length - 1); const domain = legendItems.map((item) => item.name); const range = legendItems.map((item) => item.color);
const hasRefLine = refValue !== undefined && Number.isFinite(refValue); const resolvedRefColor = refColor ? resolveChartColor(refColor) : semanticColors.borderEmphasized; const resolvedRefLabelColor = refColor ? resolvedRefColor : semanticColors.fgMuted; const isRefNearTop = hasRefLine && yAxis.max > yAxis.min && (yAxis.max - refValue) / (yAxis.max - yAxis.min) < 0.16;
const longestYTick = yAxis.ticks.reduce( (max, tick) => Math.max(max, formatAxisValue(tick).length), 0, ); const leftMargin = showYAxis ? Math.min(84, Math.max(48, longestYTick * 7 + 12)) : 8;
const marks = activeCategories.length > 0 && rows.length > 0 ? [ decorative( areaY(rows, { id: "area-fill", x: "slot", y1: "y0", y2: "y1", z: "series", color: "series", key: "id", fillOpacity: type === "stacked" ? 0.28 : 0.18, curve: resolvedCurve, }), ), ...(hasRefLine ? [ decorative( ruleY([refValue], { id: "area-reference-line", stroke: resolvedRefColor, strokeDasharray: "4 4", strokeOpacity: 0.85, strokeWidth: 1.25, }), ), ] : []), lineY(rows, { id: "area-line", x: "slot", y: "y1", z: "series", color: "series", key: "id", strokeWidth: 2, curve: resolvedCurve, }), ...(hasRefLine && refLabel ? [ decorative( text( [ { slot: maxSlot, value: refValue, label: refLabel, }, ], { id: "area-reference-label", x: "slot", y: "value", text: "label", anchor: "end", dx: -4, dy: isRefNearTop ? 12 : -8, fontSize: 11, fontWeight: 500, fill: resolvedRefLabelColor, }, ), ), ] : []), ...(showTooltip ? [ whenFocused( dot(rows, { id: "area-focus-dots", x: "slot", y: "y1", z: "series", color: "series", key: "id", r: 4, stroke: semanticColors.bgSurface, strokeWidth: 2, }), { match: "x" }, ), crosshair({ x: { stroke: semanticColors.borderEmphasized, strokeDasharray: "3 3", strokeWidth: 1, }, y: false, }), ] : []), ] : [];
return defineChart({ marks, scales: { x: { scale: () => scaleLinear().domain([0, maxSlot]), axis: showXAxis ? { line: false, ticks: { size: 0, values: xTicks, format: (v) => labels[Math.round(Number(v))] ?? "", }, } : false, grid: false, }, y: { scale: () => scaleLinear().domain([yAxis.min, yAxis.max]), grid: showGrid, axis: showYAxis ? { line: false, ticks: { size: 0, values: yAxis.ticks, format: (v) => formatAxisValue(Number(v)), }, } : false, }, }, color: { scale: scaleOrdinal<string, string>().domain(domain).range(range), }, theme: CHART_THEME, focus: showTooltip && activeCategories.length > 0 ? "group-x" : false, focusRing: false, maxFocusDistance: Number.POSITIVE_INFINITY, margin: { top: 10, right: 12, bottom: showXAxis ? 26 : 8, left: leftMargin, }, ...(showTooltip && activeCategories.length > 0 ? { tooltip: { use: tooltip, sort: "color-domain" as const, offset: 14, }, } : {}), }); }, [ activeCategories.length, curve, data.length, formatAxisValue, labels, legendItems, refColor, refLabel, refValue, rows, showGrid, showTooltip, showXAxis, showYAxis, type, xTicks, yAxis, ]);
if (data.length === 0 || categories.length === 0) { return ( <div {...stylex.props(palette, styles.root, style)}> <div role="img" aria-label={ariaLabel} {...stylex.props(styles.emptyState, styles.emptyHeight(height))} > No data available </div> </div> ); }
return ( <div {...stylex.props(palette, styles.root, style)}> <div {...stylex.props(styles.chartHost)}> <Chart definition={definition} height={height} initialWidth={640} ariaLabel={ariaLabel} renderTooltipBody={ showTooltip ? ({ points, primaryPoint }) => { const entries: TooltipSeriesEntry[] = []; for (const pt of points) { if (pt.datum.value === null) continue; entries.push({ id: pt.datum.id, label: pt.datum.label, series: pt.datum.series, value: pt.datum.value, }); } return ( <ChartTooltipCard title={entries[0]?.label ?? ""} entries={entries} primaryId={primaryPoint?.datum.id} colorBySeries={colorBySeries} formatValue={formatValue} referenceLine={referenceLine} /> ); } : undefined } /> </div>
{showLegend ? ( <ChartLegend items={legendItems} hiddenKeys={hiddenKeys} onToggle={toggleSeries} /> ) : null} </div> );}AreaChart.displayName = "AreaChart";
// ============= LINE CHART =============
export interface LineChartProps extends StyleOverrideProps { data: ReadonlyArray<Record<string, unknown>>; index: string; categories: ReadonlyArray<string>; colors?: ReadonlyArray<string>; height?: number; curve?: ChartCurveType; showDots?: boolean; showLegend?: boolean; showGrid?: boolean; showTooltip?: boolean; showXAxis?: boolean; showYAxis?: boolean; valueFormatter?: (value: number) => string; connectNulls?: boolean; referenceLine?: ChartReferenceLine; yDomain?: readonly [number, number]; ariaLabel?: string;}
interface LineRow { id: string; slot: number; label: string; series: string; value: number | null;}
/** * Multi-series line chart with optional data-point markers, curve styles, * horizontal reference lines, custom Y-axis domains, synchronized vertical * crosshair + tooltip, and toggleable legend. */export function LineChart({ data, index, categories, colors, height = 240, curve = "linear", showDots = false, showLegend = true, showGrid = true, showTooltip = true, showXAxis = true, showYAxis = true, valueFormatter, connectNulls = false, referenceLine, yDomain, ariaLabel = "Line chart", palette, style,}: LineChartProps) { const { hiddenKeys, toggleSeries } = useSeriesVisibility(); const formatValue = valueFormatter ?? defaultValueFormatter; const formatAxisValue = valueFormatter ?? defaultCompactFormatter;
const refValue = referenceLine?.value; const refLabel = referenceLine?.label; const refColor = referenceLine?.color; const yDomainMin = yDomain?.[0]; const yDomainMax = yDomain?.[1];
const legendItems = useMemo<ChartLegendItem[]>( () => categories.map((name, idx) => ({ name, color: resolveChartColor(colors?.[idx], idx), })), [categories, colors], );
const colorBySeries = useMemo( () => new Map(legendItems.map((item) => [item.name, item.color])), [legendItems], );
const activeCategories = useMemo( () => categories.filter((name) => !hiddenKeys.has(name)), [categories, hiddenKeys], );
const labels = useMemo( () => data.map((row, slot) => String(row[index] ?? slot)), [data, index], );
const { rows, yAxis } = useMemo(() => { const out: LineRow[] = []; const extentValues: number[] = [];
for (const series of activeCategories) { for (let slot = 0; slot < data.length; slot++) { const val = toFiniteNumber(data[slot]?.[series]); if (val === null) { if (!connectNulls) { out.push({ id: `${series}-${slot}`, slot, label: labels[slot] ?? String(slot), series, value: null, }); } continue; } extentValues.push(val); out.push({ id: `${series}-${slot}`, slot, label: labels[slot] ?? String(slot), series, value: val, }); } }
if (refValue !== undefined && Number.isFinite(refValue)) { extentValues.push(refValue); }
const computedAxis = yDomainMin !== undefined && yDomainMax !== undefined ? computeDomainAxis(yDomainMin, yDomainMax) : computeNumericAxis(extentValues, true);
return { rows: out, yAxis: computedAxis }; }, [activeCategories, connectNulls, data, labels, refValue, yDomainMax, yDomainMin]);
const xTicks = useMemo(() => computeSlotTicks(data.length), [data.length]);
const definition = useMemo(() => { const resolvedCurve = resolveCurve(curve); const maxSlot = Math.max(1, data.length - 1); const domain = legendItems.map((item) => item.name); const range = legendItems.map((item) => item.color);
const hasRefLine = refValue !== undefined && Number.isFinite(refValue); const resolvedRefColor = refColor ? resolveChartColor(refColor) : semanticColors.borderEmphasized; const resolvedRefLabelColor = refColor ? resolvedRefColor : semanticColors.fgMuted; const isRefNearTop = hasRefLine && yAxis.max > yAxis.min && (yAxis.max - refValue) / (yAxis.max - yAxis.min) < 0.16;
const longestYTick = yAxis.ticks.reduce( (max, tick) => Math.max(max, formatAxisValue(tick).length), 0, ); const leftMargin = showYAxis ? Math.min(84, Math.max(48, longestYTick * 7 + 12)) : 8;
const marks = activeCategories.length > 0 && rows.length > 0 ? [ ...(hasRefLine ? [ decorative( ruleY([refValue], { id: "line-reference-line", stroke: resolvedRefColor, strokeDasharray: "4 4", strokeOpacity: 0.85, strokeWidth: 1.25, }), ), ] : []), lineY(rows, { id: "line-series", x: "slot", y: "value", z: "series", color: "series", key: "id", strokeWidth: 2, curve: resolvedCurve, }), ...(showDots ? [ decorative( dot(rows, { id: "line-dots", x: "slot", y: "value", z: "series", color: "series", key: "id", r: 3.5, stroke: semanticColors.bgSurface, strokeWidth: 1.5, }), ), ] : []), ...(hasRefLine && refLabel ? [ decorative( text( [ { slot: maxSlot, value: refValue, label: refLabel, }, ], { id: "line-reference-label", x: "slot", y: "value", text: "label", anchor: "end", dx: -4, dy: isRefNearTop ? 12 : -8, fontSize: 11, fontWeight: 500, fill: resolvedRefLabelColor, }, ), ), ] : []), ...(showTooltip ? [ whenFocused( dot(rows, { id: "line-focus-dots", x: "slot", y: "value", z: "series", color: "series", key: "id", r: 4.5, stroke: semanticColors.bgSurface, strokeWidth: 2, }), { match: "x" }, ), crosshair({ x: { stroke: semanticColors.borderEmphasized, strokeDasharray: "3 3", strokeWidth: 1, }, y: false, }), ] : []), ] : [];
return defineChart({ marks, scales: { x: { scale: () => scaleLinear().domain([0, maxSlot]), axis: showXAxis ? { line: false, ticks: { size: 0, values: xTicks, format: (v) => labels[Math.round(Number(v))] ?? "", }, } : false, grid: false, }, y: { scale: () => scaleLinear().domain([yAxis.min, yAxis.max]), grid: showGrid, axis: showYAxis ? { line: false, ticks: { size: 0, values: yAxis.ticks, format: (v) => formatAxisValue(Number(v)), }, } : false, }, }, color: { scale: scaleOrdinal<string, string>().domain(domain).range(range), }, theme: CHART_THEME, focus: showTooltip && activeCategories.length > 0 ? "group-x" : false, focusRing: false, maxFocusDistance: Number.POSITIVE_INFINITY, margin: { top: 10, right: 12, bottom: showXAxis ? 26 : 8, left: leftMargin, }, ...(showTooltip && activeCategories.length > 0 ? { tooltip: { use: tooltip, sort: "color-domain" as const, offset: 14, }, } : {}), }); }, [ activeCategories.length, curve, data.length, formatAxisValue, labels, legendItems, refColor, refLabel, refValue, rows, showDots, showGrid, showTooltip, showXAxis, showYAxis, xTicks, yAxis, ]);
if (data.length === 0 || categories.length === 0) { return ( <div {...stylex.props(palette, styles.root, style)}> <div role="img" aria-label={ariaLabel} {...stylex.props(styles.emptyState, styles.emptyHeight(height))} > No data available </div> </div> ); }
return ( <div {...stylex.props(palette, styles.root, style)}> <div {...stylex.props(styles.chartHost)}> <Chart definition={definition} height={height} initialWidth={640} ariaLabel={ariaLabel} renderTooltipBody={ showTooltip ? ({ points, primaryPoint }) => { const entries: TooltipSeriesEntry[] = []; for (const pt of points) { if (pt.datum.value === null) continue; entries.push({ id: pt.datum.id, label: pt.datum.label, series: pt.datum.series, value: pt.datum.value, }); } return ( <ChartTooltipCard title={entries[0]?.label ?? ""} entries={entries} primaryId={primaryPoint?.datum.id} colorBySeries={colorBySeries} formatValue={formatValue} referenceLine={referenceLine} /> ); } : undefined } /> </div>
{showLegend ? ( <ChartLegend items={legendItems} hiddenKeys={hiddenKeys} onToggle={toggleSeries} /> ) : null} </div> );}LineChart.displayName = "LineChart";
// ============= BAR CHART =============
export interface BarChartProps extends StyleOverrideProps { data: ReadonlyArray<Record<string, unknown>>; index: string; categories: ReadonlyArray<string>; colors?: ReadonlyArray<string>; height?: number; type?: "default" | "grouped" | "stacked"; layout?: "vertical" | "horizontal"; showLegend?: boolean; showGrid?: boolean; showTooltip?: boolean; showXAxis?: boolean; showYAxis?: boolean; valueFormatter?: (value: number) => string; ariaLabel?: string;}
interface BarRow { id: string; label: string; series: string; value: number;}
/** * Categorical bar chart supporting vertical (`barY`) and horizontal (`barX`) * orientations, grouped and stacked multi-series modes, StyleX tooltips, and * interactive legend toggles. */export function BarChart({ data, index, categories, colors, height = 240, type, layout = "vertical", showLegend = true, showGrid = true, showTooltip = true, showXAxis = true, showYAxis = true, valueFormatter, ariaLabel = "Bar chart", palette, style,}: BarChartProps) { const { hiddenKeys, toggleSeries } = useSeriesVisibility(); const formatValue = valueFormatter ?? defaultValueFormatter; const formatAxisValue = valueFormatter ?? defaultCompactFormatter; const resolvedType = type ?? (categories.length > 1 ? "grouped" : "default");
const legendItems = useMemo<ChartLegendItem[]>( () => categories.map((name, idx) => ({ name, color: resolveChartColor(colors?.[idx], idx), })), [categories, colors], );
const colorBySeries = useMemo( () => new Map(legendItems.map((item) => [item.name, item.color])), [legendItems], );
const activeCategories = useMemo( () => categories.filter((name) => !hiddenKeys.has(name)), [categories, hiddenKeys], );
const { rows, bandLabels, valueAxis } = useMemo(() => { const out: BarRow[] = []; const uniqueLabels: string[] = []; const seenLabels = new Set<string>(); const extentValues: number[] = [];
for (let i = 0; i < data.length; i++) { const datum = data[i]!; const label = String(datum[index] ?? i); if (!seenLabels.has(label)) { seenLabels.add(label); uniqueLabels.push(label); }
let posTotal = 0; let negTotal = 0; for (const series of activeCategories) { const val = toFiniteNumber(datum[series]); if (val === null) continue; out.push({ id: `${label}-${series}-${i}`, label, series, value: val, }); if (resolvedType === "stacked") { if (val >= 0) posTotal += val; else negTotal += val; } else { extentValues.push(val); } } if (resolvedType === "stacked") { extentValues.push(posTotal, negTotal); } }
return { rows: out, bandLabels: uniqueLabels, valueAxis: computeNumericAxis(extentValues, true), }; }, [activeCategories, data, index, resolvedType]);
const { horizontalDefinition, verticalDefinition } = useMemo(() => { const domain = legendItems.map((item) => item.name); const range = legendItems.map((item) => item.color); const isStacked = resolvedType === "stacked"; const isGrouped = !isStacked && activeCategories.length > 1; const barLayout = isStacked ? stack() : isGrouped ? group({ padding: 0.14 }) : undefined;
const longestLabel = bandLabels.reduce((max, l) => Math.max(max, l.length), 0); const horizontalLeftMargin = Math.min(124, Math.max(64, longestLabel * 7 + 16));
if (layout === "horizontal") { const marks = activeCategories.length > 0 && rows.length > 0 ? [ barX(rows, { id: "bars-x", x: "value", y: "label", z: "series", color: "series", key: "id", layout: barLayout, radius: isStacked ? { end: 4, stack: "outer" } : ([0, 4, 4, 0] as const), fillOpacity: 0.92, }), ] : [];
return { horizontalDefinition: defineChart({ marks, scales: { x: { scale: () => scaleLinear().domain([valueAxis.min, valueAxis.max]), grid: showGrid, axis: showXAxis ? { line: false, ticks: { size: 0, values: valueAxis.ticks, format: (v) => formatAxisValue(Number(v)), }, } : false, }, y: { scale: () => scaleBand<string>().domain(bandLabels).padding(0.28), grid: false, axis: showYAxis ? { line: false, ticks: { size: 0 }, } : false, }, }, color: { scale: scaleOrdinal<string, string>().domain(domain).range(range), }, theme: CHART_THEME, focus: showTooltip && activeCategories.length > 0 ? "group-y" : false, focusRing: false, margin: { top: 10, right: 16, bottom: showXAxis ? 26 : 8, left: showYAxis ? horizontalLeftMargin : 8, }, ...(showTooltip && activeCategories.length > 0 ? { tooltip: { use: tooltip, sort: "color-domain" as const, offset: 12, }, } : {}), }), verticalDefinition: null, }; }
const marks = activeCategories.length > 0 && rows.length > 0 ? [ barY(rows, { id: "bars-y", x: "label", y: "value", z: "series", color: "series", key: "id", layout: barLayout, radius: isStacked ? { end: 4, stack: "outer" } : ([4, 4, 0, 0] as const), fillOpacity: 0.92, }), ] : [];
return { horizontalDefinition: null, verticalDefinition: defineChart({ marks, scales: { x: { scale: () => scaleBand<string>().domain(bandLabels).padding(0.28), grid: false, axis: showXAxis ? { line: false, ticks: { size: 0 }, } : false, }, y: { scale: () => scaleLinear().domain([valueAxis.min, valueAxis.max]), grid: showGrid, axis: showYAxis ? { line: false, ticks: { size: 0, values: valueAxis.ticks, format: (v) => formatAxisValue(Number(v)), }, } : false, }, }, color: { scale: scaleOrdinal<string, string>().domain(domain).range(range), }, theme: CHART_THEME, focus: showTooltip && activeCategories.length > 0 ? "group-x" : false, focusRing: false, margin: { top: 10, right: 12, bottom: showXAxis ? 26 : 8, left: showYAxis ? 48 : 8, }, ...(showTooltip && activeCategories.length > 0 ? { tooltip: { use: tooltip, sort: "color-domain" as const, offset: 12, }, } : {}), }), }; }, [ activeCategories.length, bandLabels, formatAxisValue, layout, legendItems, resolvedType, rows, showGrid, showTooltip, showXAxis, showYAxis, valueAxis, ]);
const renderBarTooltip = useCallback( ({ points, primaryPoint, }: { points: ReadonlyArray<{ datum: BarRow }>; primaryPoint?: { datum: BarRow } | null; }) => { const entries: TooltipSeriesEntry[] = points.map((pt) => ({ id: pt.datum.id, label: pt.datum.label, series: pt.datum.series, value: pt.datum.value, })); return ( <ChartTooltipCard title={entries[0]?.label ?? ""} entries={entries} primaryId={primaryPoint?.datum.id} colorBySeries={colorBySeries} formatValue={formatValue} /> ); }, [colorBySeries, formatValue], );
if (data.length === 0 || categories.length === 0) { return ( <div {...stylex.props(palette, styles.root, style)}> <div role="img" aria-label={ariaLabel} {...stylex.props(styles.emptyState, styles.emptyHeight(height))} > No data available </div> </div> ); }
return ( <div {...stylex.props(palette, styles.root, style)}> <div {...stylex.props(styles.chartHost)}> {horizontalDefinition ? ( <Chart definition={horizontalDefinition} height={height} initialWidth={640} ariaLabel={ariaLabel} renderTooltipBody={showTooltip ? renderBarTooltip : undefined} /> ) : verticalDefinition ? ( <Chart definition={verticalDefinition} height={height} initialWidth={640} ariaLabel={ariaLabel} renderTooltipBody={showTooltip ? renderBarTooltip : undefined} /> ) : null} </div>
{showLegend ? ( <ChartLegend items={legendItems} hiddenKeys={hiddenKeys} onToggle={toggleSeries} /> ) : null} </div> );}BarChart.displayName = "BarChart";
// ============= SPARKLINE =============
export interface SparklineProps extends StyleOverrideProps { data: ReadonlyArray<Record<string, unknown>>; categories: ReadonlyArray<string>; index?: string; colors?: ReadonlyArray<string>; height?: number; variant?: "line" | "area"; curve?: ChartCurveType; showTooltip?: boolean; valueFormatter?: (value: number) => string; ariaLabel?: string;}
interface SparklineRow { id: string; slot: number; label: string; series: string; value: number | null;}
/** * Compact axis-free inline trend chart for KPI cards, metrics strips, and table cells. */export function Sparkline({ data, categories, index, colors, height = 40, variant = "line", curve = "monotone", showTooltip = false, valueFormatter, ariaLabel = "Sparkline trend", palette, style,}: SparklineProps) { const formatValue = valueFormatter ?? defaultValueFormatter;
const seriesMeta = useMemo( () => categories.map((name, idx) => ({ name, color: resolveChartColor(colors?.[idx], idx), })), [categories, colors], );
const colorBySeries = useMemo( () => new Map(seriesMeta.map((item) => [item.name, item.color])), [seriesMeta], );
const { rows, yDomain } = useMemo(() => { const out: SparklineRow[] = []; let minVal = Number.POSITIVE_INFINITY; let maxVal = Number.NEGATIVE_INFINITY;
for (const series of categories) { for (let slot = 0; slot < data.length; slot++) { const datum = data[slot]!; const val = toFiniteNumber(datum[series]); if (val !== null) { if (val < minVal) minVal = val; if (val > maxVal) maxVal = val; } out.push({ id: `${series}-${slot}`, slot, label: index ? String(datum[index] ?? slot) : String(slot + 1), series, value: val, }); } }
if (!Number.isFinite(minVal) || !Number.isFinite(maxVal)) { return { rows: out, yDomain: [0, 1] as const }; } if (minVal === maxVal) { const pad = minVal === 0 ? 1 : Math.abs(minVal) * 0.1; return { rows: out, yDomain: [minVal - pad, maxVal + pad] as const }; } const pad = (maxVal - minVal) * 0.08; return { rows: out, yDomain: [minVal - pad, maxVal + pad] as const, }; }, [categories, data, index]);
const definition = useMemo(() => { const resolvedCurve = resolveCurve(curve); const maxSlot = Math.max(1, data.length - 1); const domain = seriesMeta.map((item) => item.name); const range = seriesMeta.map((item) => item.color);
const marks = rows.length > 0 ? [ ...(variant === "area" ? [ decorative( areaY(rows, { id: "spark-area", x: "slot", y1: yDomain[0], y2: "value", z: "series", color: "series", key: "id", fillOpacity: 0.18, curve: resolvedCurve, }), ), ] : []), lineY(rows, { id: "spark-line", x: "slot", y: "value", z: "series", color: "series", key: "id", strokeWidth: 1.75, curve: resolvedCurve, }), ...(showTooltip ? [ whenFocused( dot(rows, { id: "spark-focus-dot", x: "slot", y: "value", z: "series", color: "series", key: "id", r: 3.5, stroke: semanticColors.bgSurface, strokeWidth: 1.5, }), { match: "x" }, ), ] : []), ] : [];
return defineChart({ marks, scales: { x: { scale: () => scaleLinear().domain([0, maxSlot]), axis: false, grid: false, }, y: { scale: () => scaleLinear().domain([yDomain[0], yDomain[1]]), axis: false, grid: false, }, }, color: { scale: scaleOrdinal<string, string>().domain(domain).range(range), }, theme: CHART_THEME, focus: showTooltip ? "group-x" : false, focusRing: false, maxFocusDistance: Number.POSITIVE_INFINITY, margin: { top: 4, right: 2, bottom: 4, left: 2 }, ...(showTooltip ? { tooltip: { use: tooltip, sort: "color-domain" as const, offset: 10, }, } : {}), }); }, [curve, data.length, rows, seriesMeta, showTooltip, variant, yDomain]);
if (data.length === 0 || categories.length === 0) { return ( <div role="img" aria-label={ariaLabel} {...stylex.props(palette, styles.sparklineRoot, styles.emptyHeight(height), style)} /> ); }
return ( <div {...stylex.props(palette, styles.sparklineRoot, styles.chartHost, style)}> <Chart definition={definition} height={height} initialWidth={200} ariaLabel={ariaLabel} renderTooltipBody={ showTooltip ? ({ points, primaryPoint }) => { const entries: TooltipSeriesEntry[] = []; for (const pt of points) { if (pt.datum.value === null) continue; entries.push({ id: pt.datum.id, label: pt.datum.label, series: pt.datum.series, value: pt.datum.value, }); } return ( <ChartTooltipCard title={index ? (entries[0]?.label ?? "") : ""} entries={entries} primaryId={primaryPoint?.datum.id} colorBySeries={colorBySeries} formatValue={formatValue} /> ); } : undefined } /> </div> );}Sparkline.displayName = "Sparkline";
// ============= CATEGORY BAR =============
export interface CategoryBarProps extends StyleOverrideProps { values: ReadonlyArray<number>; labels?: ReadonlyArray<string>; colors?: ReadonlyArray<string>; markerValue?: number; showLabels?: boolean; valueFormatter?: (value: number) => string; ariaLabel?: string;}
/** * Proportional multi-segment horizontal bar with optional target marker pin * and inline summary legend. Built with pure StyleX flex segments. */export function CategoryBar({ values, labels, colors, markerValue, showLabels = true, valueFormatter, ariaLabel = "Category distribution", palette, style,}: CategoryBarProps) { const formatValue = valueFormatter ?? defaultValueFormatter;
const segments = useMemo(() => { const safeValues = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0)); const total = safeValues.reduce((sum, v) => sum + v, 0); return { total, items: safeValues.map((value, idx) => ({ value, pct: total > 0 ? (value / total) * 100 : 0, label: labels?.[idx], color: resolveChartColor(colors?.[idx], idx), })), }; }, [colors, labels, values]);
const markerPct = markerValue !== undefined && segments.total > 0 ? Math.min(100, Math.max(0, (markerValue / segments.total) * 100)) : undefined;
return ( <div {...stylex.props(palette, styles.categoryBarRoot, style)}> <div role="img" aria-label={ariaLabel} {...stylex.props(styles.categoryBarTrackWrap)} > <div {...stylex.props(styles.categoryBarTrack)}> {segments.items.map((seg, idx) => seg.pct > 0 ? ( <div key={seg.label ?? idx} title={ seg.label ? `${seg.label}: ${formatValue(seg.value)}` : formatValue(seg.value) } {...stylex.props(styles.categoryBarSegment(seg.pct, seg.color))} /> ) : null, )} </div> {markerPct !== undefined ? ( <div aria-label={`Target marker: ${formatValue(markerValue!)}`} title={formatValue(markerValue!)} {...stylex.props(styles.categoryBarMarker(markerPct))} /> ) : null} </div>
{showLabels && segments.items.length > 0 ? ( <div {...stylex.props(styles.categoryBarLabels)}> {segments.items.map((seg, idx) => ( <div key={seg.label ?? idx} {...stylex.props(styles.categoryBarLabelItem)} > <span {...stylex.props(styles.swatch, styles.swatchColor(seg.color))} /> {seg.label ? ( <span {...stylex.props(styles.categoryBarLabelText)}> {seg.label} </span> ) : null} <span {...stylex.props(styles.categoryBarLabelValue)}> {formatValue(seg.value)} </span> </div> ))} </div> ) : null} </div> );}CategoryBar.displayName = "CategoryBar";
Inspired by the Charts charts from Saas UI.