# Chart Foundations

> The scales, formats, legend and tooltip every chart shares.

Page: https://uicontext.com/docs/components/chart-foundations

Group: Charts.

## When to use

The scales, formats, legend and tooltip every chart shares. Use [Line Chart](https://uicontext.com/docs/components/line-chart.md) instead when you want a finished chart, not its parts.

## Usage

```ts
import { formatShort, formatTime, formatValue, tickFormatter } from "./ui/uicontext/components/charts/Format.ts"
import { niceTicks } from "./ui/uicontext/components/charts/Scale.ts"

const usd = { style: "currency", currency: "USD" } as const

export const revenueText = formatValue(248_120, usd) // "$248,120.00"
export const revenueShort = formatShort(248_120, usd) // "$248.1K"
export const month = formatTime(Date.UTC(2026, 10, 1), "month") // "November 2026"

const ticks = niceTicks(0, 248_120, 5) // 0, 50,000 … 250,000
export const axisLabels = ticks.values.map(tickFormatter(ticks.values, usd)) // "$0", "$50K" … "$250K"
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### States

The example the page opens with: Chart Foundations in “States”.

This example also uses Line Chart and Segmented Control. Install them too:

```sh
npx shadcn@latest add checkfu/uicontext/line-chart checkfu/uicontext/segmented-control
```

```ts title="src/demo.ts" source="www/src/examples/chart-foundations/demo.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { Chart } from "./ui/uicontext/components/charts/Chart.ts"
import { ChartStatus } from "./ui/uicontext/components/charts/Data.ts"
import { SegmentedControl } from "./ui/uicontext/components/SegmentedControl.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { space } from "./ui/uicontext/components/tokens.stylex.ts"
import { signupsByPlan } from "./metrics.ts"

const styles = stylex.create({ root: { display: "grid", gap: space.lg, inlineSize: "100%" } })

const Shown = Schema.Literals(["ready", "loading", "refreshing", "error", "empty"])
const labels = { ready: "Data", loading: "Loading", refreshing: "Refreshing", error: "Failed", empty: "Empty" } as const

const Message = UiSchema.TaggedEnum({
	PickedChartState: { state: Shown },
	RequestedRetrySignups: {},
})

// Every chart shares these states, in the plot's own height so nothing shifts: a quiet placeholder
// on first load, the last data dimmed while it refreshes, a failure with Retry, and an empty period.
export const ChartStates = Html.component({
	name: "ChartStates",
	model: Schema.Struct({ state: Shown }),
	message: Message,
}).make({
	init: () => ({ state: "error" as const }),
	update: {
		PickedChartState: ($, { state }) => $.evolve({ state }),
		RequestedRetrySignups: ($) => $.evolve({ state: "ready" }),
	},
	view: (h, model) => {
		const status: ChartStatus = model.state === "empty" ? "ready" : model.state
		return h.div.attrs(sx(styles.root)).children(
			SegmentedControl(h, {
				label: "State",
				value: model.state,
				options: Shown.literals.map((value) => ({ value, label: labels[value] })),
				onChange: (state) => Message.PickedChartState({ state: Schema.is(Shown)(state) ? state : "ready" }),
			}),
			Chart(h, {
				props: {
					type: "bar",
					stacked: "stacked",
					label: "Weekly signups by plan",
					series: model.state === "empty" ? signupsByPlan.map((s) => ({ ...s, points: [] })) : signupsByPlan,
					x: { kind: "time", unit: "week" },
					status,
					error: "The analytics service didn't answer in time.",
					empty: "No signups in this period. Try a longer range.",
				},
				onEmit: {
					RequestedRetry: () => Message.RequestedRetrySignups(),
					Highlighted: () => undefined,
					RequestedSelect: () => undefined,
					RequestedToggle: () => undefined,
				},
			}),
		)
	},
})
```

### Formats

Every value goes through Intl, so another locale gets its own digits and symbols.

```ts title="src/formats.ts" source="www/src/examples/chart-foundations/formats.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import type { ChartFormat } from "./ui/uicontext/components/charts/Data.ts"
import { formatDelta, formatShort, formatValue, tickFormatter } from "./ui/uicontext/components/charts/Format.ts"
import { niceTicks } from "./ui/uicontext/components/charts/Scale.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	table: { inlineSize: "min(100%, 40rem)", borderCollapse: "collapse", fontSize: font.sm },
	th: { textAlign: "start", fontWeight: 500, color: color.muted, paddingBlock: space.sm, paddingInline: space.md, borderBottomWidth: 1, borderBottomStyle: "solid", borderBottomColor: color.line },
	rowHead: { textAlign: "start", fontWeight: 500 },
	td: { paddingBlock: space.sm, paddingInline: space.md, borderBottomWidth: 1, borderBottomStyle: "solid", borderBottomColor: color.line, fontVariantNumeric: "tabular-nums", overflowWrap: "anywhere" },
})

const rows: ReadonlyArray<{ readonly name: string; readonly value: number; readonly format: ChartFormat; readonly max: number }> = [
	{ name: "Revenue", value: 248_120.5, format: { style: "currency", currency: "USD" }, max: 260_000 },
	{ name: "Revenue in euros", value: 1_204_880, format: { style: "currency", currency: "EUR", digits: 0 }, max: 1_300_000 },
	{ name: "Seats", value: 1_284, format: { style: "number" }, max: 1_400 },
	{ name: "Requests", value: 48_213_904_117, format: { style: "compact" }, max: 50_000_000_000 },
	{ name: "Churn", value: 0.0214, format: { style: "percent" }, max: 0.03 },
	{ name: "p95 latency", value: 412.6, format: { style: "unit", unit: "millisecond", digits: 0 }, max: 500 },
	{ name: "Net change", value: -18_400, format: { style: "currency", currency: "USD", digits: 0 }, max: 20_000 },
]

// The same value in full (tooltips and tables), short (stats and labels), as a change, and the axis
// it would sit on.
export const Formats = <M>(h: Html.H<M>) =>
	h.table.attrs(sx(styles.table)).children(
		h.thead.children(h.tr.children(...["Measure", "In full", "Short", "Change", "Axis"].map((c) => h.th.key(c).attrs({ scope: "col", ...sx(styles.th) }).children(c)))),
		h.tbody.children(...rows.map((row) => {
			const ticks = niceTicks(Math.min(0, row.value), row.max, 4)
			return h.tr.key(row.name).children(
				h.th.attrs({ scope: "row", ...sx(styles.td, styles.rowHead) }).children(row.name),
				h.td.attrs(sx(styles.td)).children(formatValue(row.value, row.format)),
				h.td.attrs(sx(styles.td)).children(formatShort(row.value, row.format)),
				h.td.attrs(sx(styles.td)).children(formatDelta(row.value / row.max - 0.9)),
				h.td.attrs(sx(styles.td)).children(ticks.values.map(tickFormatter(ticks.values, row.format)).join(" · ")),
			)
		})),
	)
```

### Sample data

The examples above import these files.

```ts title="src/metrics.ts" source="www/src/examples/_shared/metrics.ts"
import type { ChartDatum, ChartDay, ChartSeries } from "./ui/uicontext/components/charts/Data.ts"

// Sample metrics for a software business: revenue, plans, support, deploys, latency and seats.
// Generated from a fixed seed, so every render and every screenshot shows the same numbers.

const seeded = (seed: number) => {
	let state = seed >>> 0
	return () => {
		state = (state * 1664525 + 1013904223) >>> 0
		return state / 2 ** 32
	}
}

const months = ["2025-12", "2026-01", "2026-02", "2026-03", "2026-04", "2026-05", "2026-06", "2026-07", "2026-08", "2026-09", "2026-10", "2026-11"]
const monthStart = (m: string) => `${m}-01`

/** Monthly recurring revenue by source, a year to November 2026. */
export const mrr: ReadonlyArray<ChartSeries> = (() => {
	const random = seeded(7)
	let base = 182_000
	let expansion = 21_000
	let added = 14_000
	const rows = months.map((m) => {
		base *= 1.018 + random() * 0.012
		expansion *= 1.03 + random() * 0.03
		added = added * (0.94 + random() * 0.16)
		return { x: monthStart(m), base: Math.round(base), expansion: Math.round(expansion), added: Math.round(added) }
	})
	return [
		{ id: "existing", label: "Existing", points: rows.map((r) => ({ x: r.x, y: r.base })) },
		{ id: "expansion", label: "Expansion", points: rows.map((r) => ({ x: r.x, y: r.expansion })) },
		{ id: "new", label: "New", points: rows.map((r) => ({ x: r.x, y: r.added })) },
	]
})()

/** Revenue this year, and last year's as a dashed comparison. */
export const revenueVsLastYear: ReadonlyArray<ChartSeries> = (() => {
	const random = seeded(11)
	let now = 168_000
	let before = 121_000
	const rows = months.map((m) => {
		now *= 1.02 + random() * 0.025
		before *= 1.015 + random() * 0.02
		return { x: monthStart(m), now: Math.round(now), before: Math.round(before) }
	})
	return [
		{ id: "2026", label: "This year", points: rows.map((r) => ({ x: r.x, y: r.now })) },
		{ id: "2025", label: "Last year", line: "dashed", color: "quiet", points: rows.map((r) => ({ x: r.x, y: r.before })) },
	]
})()

/** Revenue, then a forecast drawn dashed from the last actual month. */
export const revenueForecast: ReadonlyArray<ChartSeries> = (() => {
	const actual = revenueVsLastYear[0]?.points ?? []
	const last = actual[actual.length - 1]
	const ahead = ["2026-12-01", "2027-01-01", "2027-02-01", "2027-03-01"]
	let value = last?.y ?? 0
	return [
		{ id: "actual", label: "Revenue", points: [...actual, ...ahead.map((x) => ({ x, y: null }))] },
		{
			id: "forecast",
			label: "Forecast",
			line: "dashed",
			color: 1,
			points: [...actual.map((p, i) => ({ x: p.x, y: i === actual.length - 1 ? p.y : null })), ...ahead.map((x) => ({ x, y: Math.round((value *= 1.028)) }))],
		},
	]
})()

/** New signups each week, by plan. */
export const signupsByPlan: ReadonlyArray<ChartSeries> = (() => {
	const random = seeded(23)
	const weeks = Array.from({ length: 12 }, (_, i) => new Date(Date.UTC(2026, 8, 7 + i * 7)).toISOString().slice(0, 10))
	const plan = (id: string, label: string, base: number, growth: number) => {
		let v = base
		return { id, label, points: weeks.map((x) => ({ x, y: Math.round((v *= growth + (random() - 0.5) * 0.18)) })) }
	}
	return [plan("free", "Free", 420, 1.02), plan("pro", "Pro", 160, 1.035), plan("team", "Team", 64, 1.05), plan("enterprise", "Enterprise", 9, 1.04)]
})()

/** Active customers by plan, for a share-of-total donut. */
export const customersByPlan: ReadonlyArray<ChartDatum> = [
	{ id: "free", label: "Free", value: 8_412 },
	{ id: "pro", label: "Pro", value: 2_960 },
	{ id: "team", label: "Team", value: 1_184 },
	{ id: "enterprise", label: "Enterprise", value: 96 },
]

/** Support tickets this week, by status and by day. */
export const ticketsByStatus: ReadonlyArray<ChartSeries> = (() => {
	const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
	const opened = [42, 51, 38, 47, 55, 12, 9]
	const pending = [18, 22, 19, 25, 21, 8, 6]
	const solved = [61, 58, 64, 52, 70, 15, 11]
	return [
		{ id: "open", label: "Open", points: days.map((x, i) => ({ x, y: opened[i] ?? 0 })) },
		{ id: "pending", label: "Pending", points: days.map((x, i) => ({ x, y: pending[i] ?? 0 })) },
		{ id: "solved", label: "Solved", points: days.map((x, i) => ({ x, y: solved[i] ?? 0 })) },
	]
})()

/** Open tickets by queue: long names, for sideways bars. */
export const ticketsByQueue: ReadonlyArray<ChartSeries> = [
	{
		id: "open",
		label: "Open tickets",
		points: [
			{ x: "Billing and invoices", y: 184 },
			{ x: "Account access and sign-in", y: 142 },
			{ x: "Integrations", y: 97 },
			{ x: "Data import and export", y: 66 },
			{ x: "Mobile app", y: 41 },
			{ x: "Feature requests", y: 23 },
		],
	},
]

/** Production deploys per day for 90 days, and how many failed. */
export const deploysPerDay: ReadonlyArray<ChartSeries> = (() => {
	const random = seeded(31)
	const days = Array.from({ length: 90 }, (_, i) => new Date(Date.UTC(2026, 8, 2 + i)))
	const rows = days.map((d) => {
		const weekend = d.getUTCDay() === 0 || d.getUTCDay() === 6
		const total = weekend ? Math.round(random() * 3) : Math.round(8 + random() * 14)
		const failed = Math.round(total * random() * 0.18)
		return { x: d.toISOString().slice(0, 10), succeeded: total - failed, failed }
	})
	return [
		{ id: "succeeded", label: "Succeeded", points: rows.map((r) => ({ x: r.x, y: r.succeeded })) },
		{ id: "failed", label: "Failed", color: 8, points: rows.map((r) => ({ x: r.x, y: r.failed })) },
	]
})()

/** Deploys per day as a calendar of activity: a year to Nov 30, 2026. */
export const deployDays: ReadonlyArray<ChartDay> = (() => {
	const random = seeded(37)
	return Array.from({ length: 364 }, (_, i) => {
		const d = new Date(Date.UTC(2025, 11, 2 + i))
		const weekend = d.getUTCDay() === 0 || d.getUTCDay() === 6
		const busy = random()
		const value = weekend ? (busy > 0.8 ? Math.round(random() * 3) : 0) : busy < 0.08 ? 0 : Math.round(2 + busy * busy * 18)
		return { date: d.toISOString().slice(0, 10), value }
	})
})()

/** API latency every 5 minutes for 24 hours: p50 and p95, in milliseconds. */
export const latency: ReadonlyArray<ChartSeries> = (() => {
	const random = seeded(41)
	const start = Date.UTC(2026, 10, 30, 0, 0)
	const rows = Array.from({ length: 288 }, (_, i) => {
		const hour = (i * 5) / 60
		const load = 0.6 + 0.4 * Math.sin(((hour - 9) / 24) * Math.PI * 2)
		const spike = i > 180 && i < 192 ? 2.4 : 1
		const p50 = (82 + load * 30 + random() * 12) * (spike > 1 ? 1.4 : 1)
		return { x: start + i * 300_000, p50: Math.round(p50), p95: Math.round((p50 * (2.1 + random() * 0.5)) * spike) }
	})
	return [
		{ id: "p50", label: "p50", points: rows.map((r) => ({ x: r.x, y: r.p50 })) },
		{ id: "p95", label: "p95", points: rows.map((r) => ({ x: r.x, y: r.p95 })) },
	]
})()

/** Hours of use per seat this month, for the busiest seats. */
export const usagePerSeat: ReadonlyArray<ChartSeries> = [
	{
		id: "hours",
		label: "Hours this month",
		points: [
			{ x: "Priya Raman", y: 128 },
			{ x: "Mateo Alvarez", y: 117 },
			{ x: "Hana Kobayashi", y: 96 },
			{ x: "Ben Okafor", y: 88 },
			{ x: "Aleksandra Wiśniewska-Kowalczyk", y: 74 },
			{ x: "Sam Lee", y: 31 },
			{ x: "Jo", y: 4 },
		],
	},
]

/** Weekly revenue as bars and paying customers as a line, on their own axes. */
export const revenueAndCustomers: ReadonlyArray<ChartSeries> = (() => {
	const random = seeded(53)
	const weeks = Array.from({ length: 10 }, (_, i) => new Date(Date.UTC(2026, 8, 21 + i * 7)).toISOString().slice(0, 10))
	let revenue = 41_000
	let customers = 3_820
	const rows = weeks.map((x) => ({ x, revenue: Math.round((revenue *= 1 + (random() - 0.35) * 0.1)), customers: Math.round((customers *= 1.008 + random() * 0.01)) }))
	return [
		{ id: "revenue", label: "Revenue", mark: "bar", format: { style: "currency", currency: "USD", digits: 0 }, points: rows.map((r) => ({ x: r.x, y: r.revenue })) },
		{ id: "customers", label: "Paying customers", mark: "line", axis: "end", format: { style: "number" }, points: rows.map((r) => ({ x: r.x, y: r.customers })) },
	]
})()

/** Trial to paid, step by step, last 30 days. */
export const trialFunnel: ReadonlyArray<ChartDatum> = [
	{ id: "visited", label: "Visited pricing", value: 48_210 },
	{ id: "started", label: "Started a trial", value: 6_904 },
	{ id: "invited", label: "Invited a teammate", value: 2_871 },
	{ id: "connected", label: "Connected a repository", value: 1_966 },
	{ id: "paid", label: "Upgraded to paid", value: 742 },
]

/** A long run for the performance demo: 10,000 readings, one a minute. */
export const tenThousand = (seed = 5): ReadonlyArray<ChartSeries> => {
	const random = seeded(seed)
	const start = Date.UTC(2026, 10, 24)
	let cpu = 42
	let memory = 61
	const xs = Array.from({ length: 10_000 }, (_, i) => start + i * 60_000)
	return [
		{ id: "cpu", label: "CPU", points: xs.map((x) => ({ x, y: Math.round((cpu = Math.max(2, Math.min(98, cpu + (random() - 0.5) * 6 + (random() > 0.998 ? 30 : 0)))) * 10) / 10 })) },
		{ id: "memory", label: "Memory", points: xs.map((x) => ({ x, y: Math.round((memory = Math.max(20, Math.min(96, memory + (random() - 0.5) * 2))) * 10) / 10 })) },
	]
}
```

## API reference

### Legend (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `label` (required) | `string` | — |
| `entries` (required) | `LegendEntry[]` | — |
| `toggle` | `((id: string) => Message)` | — |
| `style` | `Style` | — |

### Tooltip (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `x` (required) | `number` | — |
| `y` (required) | `number` | — |
| `width` (required) | `number` | — |
| `title` (required) | `string` | — |
| `rows` (required) | `TipRow[]` | — |
| `total` | `string` | — |

### DataTable (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `caption` (required) | `string` | — |
| `columns` (required) | `string[]` | The first column's header, then one per value column |
| `rows` (required) | `ReadonlyArray<{ readonly key: string; readonly head: string; readonly cells: string[] }>` | — |

### ChartState (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `status` (required) | `ChartStatus` | — |
| `height` (required) | `number` | — |
| `empty` (required) | `boolean` | — |
| `emptyText` (required) | `string` | What nothing-to-show means here: "No deploys in this period." |
| `error` | `string` | — |
| `retry` | `Message` | — |
| `allHidden` | `Message` | Every series is hidden: offer them back |

## Keyboard and accessibility

- Every chart is a named figure with a hidden table of its data, and View as table shows that table instead of the plot.
- The legend's entries are toggle buttons (`aria-pressed`). A hidden series keeps its color when it comes back.
- Loading is a status, a failure is an alert with Retry, and both keep the plot's height so nothing moves.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/chart-foundations
```

With npm: `npx shadcn@latest add checkfu/uicontext/chart-foundations`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/chart-foundations`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/chart-foundations`.

It writes these files:

- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/charts/Data.ts`
- `src/ui/uicontext/components/charts/Format.ts`
- `src/ui/uicontext/components/charts/Frame.ts`
- `src/ui/uicontext/components/charts/Scale.ts`
- `src/ui/uicontext/components/charts/chart.stylex.ts`
- `src/ui/uicontext/components/charts/slots.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/charts/Frame.ts](https://github.com/checkfu/uicontext/blob/main/src/charts/Frame.ts)
- [src/charts/Scale.ts](https://github.com/checkfu/uicontext/blob/main/src/charts/Scale.ts)
- [src/charts/Format.ts](https://github.com/checkfu/uicontext/blob/main/src/charts/Format.ts)
- [src/charts/Data.ts](https://github.com/checkfu/uicontext/blob/main/src/charts/Data.ts)

## Used in

- [SaaS dashboard](https://uicontext.com/blocks/saas-dashboard.md)
- [CRM](https://uicontext.com/blocks/crm.md)
- [Analytics dashboard](https://uicontext.com/blocks/analytics.md)
- [Storefront](https://uicontext.com/blocks/storefront.md)
- [Helpdesk](https://uicontext.com/blocks/helpdesk.md)

## Related

- [Line Chart](https://uicontext.com/docs/components/line-chart.md) (`line-chart`): Values over time for one or many series, with dashed comparisons and forecasts.
- [Area Chart](https://uicontext.com/docs/components/area-chart.md) (`area-chart`): Totals over time and what makes them up, stacked or as shares of 100%.
- [Bar Chart](https://uicontext.com/docs/components/bar-chart.md) (`bar-chart`): Compare categories with grouped, stacked or sideways bars.
- [Combo Chart](https://uicontext.com/docs/components/combo-chart.md) (`combo-chart`): Bars and a line on one time axis, each read against its own scale.
- [Donut Chart](https://uicontext.com/docs/components/donut-chart.md) (`donut-chart`): Shares of one total, with the total in the middle.
- [Progress Ring](https://uicontext.com/docs/components/progress-ring.md) (`progress-ring`): Progress toward a goal as a ring, alone or several nested.
