# Dashboard

A named section, number cards with a trend behind them, and panels in a row.

Section: Blocks / Layouts
Page: https://ui.heyramzi.com/components/dashboard
Import path: `@heyramzi/ui/charts/dashboard`

## Import

```ts
import { AreaChart, BarChart } from "@heyramzi/ui/charts";
import { DetailPanel } from "@heyramzi/ui/components/list-page";
import { DataTable, DashboardSection, PanelGrid, PeriodFilter, StatBand, StatTile, CHART_HEIGHT, DAY_WINDOWS, type DataColumn, } from "@heyramzi/ui/charts/dashboard";
```

## Usage

```svelte
<DashboardSection title="Sales">
  <StatBand columns={2}>
    <StatTile label="Revenue" value="$48,200" deltaPct={12.4} direction="up-good" lead />
    <StatTile label="Orders" value="1,284" deltaPct={-3.1} direction="up-good" />
  </StatBand>
  <PanelGrid columns={2}>
    <section aria-label="Top products">
      <DataTable rows={top} {columns} rowKey={(row) => row.id} leadLabel="Product" emptyLabel="No sales">
        {#snippet lead(row)}{row.name}{/snippet}
      </DataTable>
    </section>
  </PanelGrid>
</DashboardSection>
```

## Demo

```svelte
<script lang="ts">
	import { AreaChart, BarChart } from "@heyramzi/ui/charts";
	import { DetailPanel } from "@heyramzi/ui/components/list-page";
	import {
		DataTable,
		DashboardSection,
		PanelGrid,
		PeriodFilter,
		StatBand,
		StatTile,
		CHART_HEIGHT,
		DAY_WINDOWS,
		type DataColumn,
	} from "@heyramzi/ui/charts/dashboard";

	// A small coffee roaster's shop: 180 days of orders, so every window has a previous one to
	// compare against. Built from a formula, not random, so the server and the browser agree.
	const END = Date.UTC(2026, 10, 9);
	const DAY = 86_400_000;
	// Monday to Sunday. Orders peak midweek and sag at the weekend, like most B2C shops.
	const WEEKDAY_PULL = [1.04, 1.12, 1.16, 1.08, 0.98, 0.78, 0.72];
	const days = Array.from({ length: 180 }, (_, i) => {
		const date = END - (179 - i) * DAY;
		const weekday = (new Date(date).getUTCDay() + 6) % 7;
		const wobble = 1 + 0.05 * Math.sin(i * 2.3) + 0.06 * Math.sin(i * 0.21);
		const orders = Math.round((17 + i * 0.045) * WEEKDAY_PULL[weekday] * wobble);
		const basket = 38 + 4 * Math.sin(i * 0.19) + (i % 5);
		const refunds = (i * 7) % 23 === 0 ? 2 : i % 4 === 0 ? 1 : 0;
		return { date, weekday, orders, revenue: Math.round(orders * basket), refunds };
	});

	const products = [
		{ id: "espresso", name: "House espresso, 1 kg", share: 0.34 },
		{ id: "guji", name: "Ethiopia Guji, 250 g", share: 0.21 },
		{ id: "decaf", name: "Colombia decaf, 500 g", share: 0.15 },
		{ id: "sub", name: "Monthly subscription", share: 0.19 },
		{ id: "kettle", name: "Gooseneck kettle", share: 0.11 },
	];

	const windows = DAY_WINDOWS.map((n) => ({ value: String(n), label: `${n}d` }));
	let period = $state("30");

	const n = $derived(Number(period));
	const current = $derived(days.slice(-n));
	const previous = $derived(days.slice(-2 * n, -n));

	const sum = (rows: typeof days, key: "orders" | "revenue" | "refunds") =>
		rows.reduce((total, row) => total + row[key], 0);
	const change = (now: number, before: number) =>
		before ? Math.round(((now - before) / before) * 1000) / 10 : null;

	const money = new Intl.NumberFormat("en-US", {
		style: "currency",
		currency: "USD",
		maximumFractionDigits: 0,
	});
	const cents = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
	const day = new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", timeZone: "UTC" });

	const stats = $derived.by(() => {
		const revenue = sum(current, "revenue");
		const orders = sum(current, "orders");
		const refunds = sum(current, "refunds");
		const before = {
			revenue: sum(previous, "revenue"),
			orders: sum(previous, "orders"),
			refunds: sum(previous, "refunds"),
		};
		const basket = revenue / orders;
		const basketBefore = before.revenue / before.orders;
		const rate = refunds / orders;
		const rateBefore = before.refunds / before.orders;
		return {
			revenue: { value: money.format(revenue), delta: change(revenue, before.revenue) },
			orders: { value: orders.toLocaleString("en-US"), delta: change(orders, before.orders) },
			basket: { value: cents.format(basket), delta: change(basket, basketBefore) },
			refunds: { value: `${(rate * 100).toFixed(1)}%`, delta: change(rate, rateBefore) },
			total: revenue,
		};
	});

	// Each tile's shape: weekly figures read as a trend, where 90 daily points read as noise. A
	// 7-day window has one week, so it draws its days instead.
	// `end` is where the slice stops in the window, for a figure that looks further back.
	const weekly = (figure: (rows: typeof days, end: number) => number) => {
		const weeks: number[] = [];
		for (let i = current.length % 7; i < current.length; i += 7)
			weeks.push(figure(current.slice(i, i + 7), i + 7));
		return weeks.length > 2 ? weeks : current.map((row, i) => figure([row], i + 1));
	};
	const shapes = $derived({
		revenue: weekly((rows) => sum(rows, "revenue")),
		orders: weekly((rows) => sum(rows, "orders")),
		basket: weekly((rows) => sum(rows, "revenue") / sum(rows, "orders")),
		// Refunds per hundred orders over the trailing 3 weeks: one refund in a quiet week
		// otherwise draws a cliff.
		refunds: weekly((_, end) => {
			const span = current.slice(Math.max(0, end - 21), end);
			return sum(span, "refunds") / sum(span, "orders");
		}),
	});

	const daily = $derived(current.map((row) => ({ date: row.date, revenue: row.revenue })));
	const average = $derived(Math.round(stats.total / n));

	const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
	const byWeekday = $derived(
		WEEKDAYS.map((label, weekday) => ({
			label,
			orders: sum(
				current.filter((row) => row.weekday === weekday),
				"orders",
			),
		})),
	);

	type Product = (typeof products)[number] & { revenue: number };
	const top = $derived(
		products
			.map((p) => ({ ...p, revenue: Math.round(stats.total * p.share) }))
			.sort((a, b) => b.revenue - a.revenue),
	);
	const columns: DataColumn<Product>[] = [
		{
			key: "revenue",
			label: "Revenue",
			// Narrower on a phone, so the bar never runs into a long product name.
			width: "w-32 sm:w-40",
			align: "end",
			strong: true,
			value: (row) => money.format(row.revenue),
			bar: (row) => row.share / products[0].share,
		},
	];
</script>

<div class="flex w-full max-w-4xl flex-col">
	<DashboardSection title="Sales" note="{day.format(current[0].date)} to {day.format(END)}">
		{#snippet actions()}
			<PeriodFilter
				options={windows}
				value={period}
				onValueChange={(next) => (period = next)}
				ariaLabel="Window"
			/>
		{/snippet}

		<StatBand columns={4}>
			<StatTile
				label="Revenue"
				value={stats.revenue.value}
				deltaPct={stats.revenue.delta}
				direction="up-good"
				lead
				series={shapes.revenue}
			/>
			<StatTile
				label="Orders"
				value={stats.orders.value}
				deltaPct={stats.orders.delta}
				direction="up-good"
				series={shapes.orders}
			/>
			<StatTile
				label="Average order"
				value={stats.basket.value}
				deltaPct={stats.basket.delta}
				direction="up-good"
				series={shapes.basket}
			/>
			<StatTile
				label="Refund rate"
				value={stats.refunds.value}
				deltaPct={stats.refunds.delta}
				direction="down-good"
				series={shapes.refunds}
			/>
		</StatBand>

		<DetailPanel label="Revenue per day">
			<AreaChart
				data={daily}
				xKey="date"
				series={[{ key: "revenue", label: "Revenue" }]}
				height={CHART_HEIGHT}
				formatValue={(v) => money.format(v)}
				formatX={(v) => day.format(Number(v))}
				resting={{ value: average, label: "Daily average" }}
			/>
		</DetailPanel>

		<PanelGrid columns={2}>
			<DetailPanel label="Top products" pad={false}>
				<DataTable
					rows={top}
					{columns}
					rowKey={(row) => row.id}
					leadLabel="Product"
					emptyLabel="No sales"
					minWidth="min-w-0"
				>
					{#snippet lead(row)}<span class="truncate">{row.name}</span>{/snippet}
				</DataTable>
			</DetailPanel>
			<DetailPanel label="Orders by weekday">
				<BarChart
					data={byWeekday}
					xKey="label"
					yKey="orders"
					height={232}
					showFigure={false}
					label="Orders by weekday"
					yLabel="Orders"
				/>
			</DetailPanel>
		</PanelGrid>
	</DashboardSection>
</div>
```

## API

### DashboardSection

| Prop | Type | Default | Notes |
| --- | --- | --- | --- |
| `title` | `string` |  | required |
| `note` | `string` |  | One line on the right: a window, a provenance, a count. Never a sentence. |
| `href` | `string` |  | The page that owns this area, when one page does. |
| `openLabel` | `string` | `"Open"` | The link's wording. Translated at the call site. |
| `actions` | `Snippet` |  | Controls that scope the whole area, like a period filter. Pinned right, after the note. |
| `children` | `Snippet` |  | required |
| `class` | `string` |  |  |

### PeriodFilter

| Prop | Type | Default | Notes |
| --- | --- | --- | --- |
| `options` | `readonly TabDef<T>[]` |  | required |
| `value` | `T` |  | required |
| `href` | `(value: T) => string` |  | Give this and the strip is links, so the choice survives reload, back and a shared link. Omit it and the strip is a `<SegmentedFilter>` the caller owns. |
| `onValueChange` | `(value: T) => void` |  | Filter mode only. Ignored when `href` is set. |
| `ariaLabel` | `string` |  | required |
| `class` | `string` |  |  |

### StatBand

| Prop | Type | Default | Notes |
| --- | --- | --- | --- |
| `children` | `Snippet` |  | required. `<StatTile>` children. Four to a row on a desk, two on a phone. |
| `columns` | `2 \| 3 \| 4 \| 5 \| 6` | `4` | Cards per row at the widest breakpoint, four unless the set is smaller. Five and six are only for a fixed scorecard. The headline stays one row. |
| `class` | `string` |  |  |

### StatTile

| Prop | Type | Default | Notes |
| --- | --- | --- | --- |
| `label` | `string` |  | required |
| `value` | `string` |  | required. Already formatted. The tile never guesses a currency or a locale. |
| `deltaPct` | `number \| null` |  | Percent change against the previous period. `null` means nothing to compare yet and draws a dash. Omit it when the figure has no period at all. |
| `direction` | `"up-good"` \| `"down-good"` \| `"neutral"` | `"neutral"` |  |
| `lead` | `boolean` | `false` | The one figure the screen was opened to read. Set it on exactly one tile. |
| `hint` | `string` |  | A quiet line under the value: what it was measured over, or why it is a dash. |
| `share` | `number` |  | 0 to 1, drawn as a track under the value: share of a total or progress to a target. Omit it for a cash balance. |
| `shareLabel` | `string` |  | What `share` is measured against, e.g. "of revenue". Only with `share`. |
| `color` | `string` |  | Track colour. The first series token unless a tile means something else. |
| `series` | `number[]` |  | A shape behind the figure, oldest first, bled along the card's bottom. The treatment every tile gives a number with a history. Omit when there is none. |
| `icon` | `PhosphorIcon` |  | Leading mark before the label. |
| `href` | `string` |  | Makes the tile a link, like a balance that opens the bank. It lives here so a linked figure isn't drawn as a second, different card style. |
| `hrefLabel` | `string` |  | What the link opens, shown on hover. Only with `href`. |
| `target` | `"_self" \| "_blank"` | `"_blank"` | `_blank` for a figure that leaves the app (a bank, a provider console), `_self` for one that is another page of this app. Only with `href`. |
| `badge` | `Snippet` |  | A chip at the end of the label row: the limit the figure is judged against, the state it is in. Wins over `hrefLabel`, which is only a hover hint. |
| `negative` | `boolean` | `false` | A loss or an overrun: the figure turns the destructive colour. |
| `class` | `string` |  |  |

### DetailPanel

| Prop | Type | Default | Notes |
| --- | --- | --- | --- |
| `label` | `string` |  | What this panel is, drawn as the app's one panel label. No label, no actions: no header. |
| `labelIcon` | `PhosphorIcon` |  |  |
| `labelLead` | `Snippet` |  | A mark the icon set lacks (a platform logo), drawn ahead of the label at the same size. |
| `sublabel` | `string` |  | A line under the label, for the scope a number was measured over. |
| `hint` | `string` |  | A row count, total or freshness stamp. A prop, not an action, because hand-placed hints ended up at three type sizes on one screen. |
| `actions` | `Snippet` |  | Controls that act on this panel. Pinned right, after the hint. |
| `pad` | `boolean` | `true` | Off for a body that supplies its own padding: a table, a media grid, a full-bleed list. |
| `scroll` | `boolean` | `false` | The body scrolls sideways rather than squeezing, for a table wider than the window. |
| `grow` | `boolean` | `false` | Takes the height the panels above it left, inside a `fill` stack. One per stack. |
| `children` | `Snippet` |  | required |
| `class` | `string` |  |  |
| `bodyClass` | `string` |  |  |

### PanelGrid

| Prop | Type | Default | Notes |
| --- | --- | --- | --- |
| `children` | `Snippet` |  | required. `<DetailPanel>` children, or tiles standing beside one. |
| `columns` | `2 \| 3 \| "main"` | `2` | Panels per row: two charts, three breakdowns, or `main`, where the first child takes two thirds and the rates beside it one third. |
| `class` | `string` |  |  |

### DataTable

| Prop | Type | Default | Notes |
| --- | --- | --- | --- |
| `rows` | `T[]` |  | required |
| `columns` | `DataColumn<T>[]` |  | required |
| `rowKey` | `(row: T) => string` |  | required |
| `leadLabel` | `string` |  | required |
| `lead` | `Snippet<[T]>` |  | required |
| `emptyLabel` | `string` |  | required. Drawn where a value or rating is null. |
| `leadWidth` | `string` |  | A Tailwind width class. Omit and the lead takes whatever the figures leave. |
| `minWidth` | `string` | `"min-w-[48rem]"` | A Tailwind min-width class, past which the panel scrolls sideways. |
| `pageSize` | `number` |  | Omit for every row on one page. |
| `sort` | `SortState` | `null` | bindable. The ranked column and its direction. Bind it; a column with `sort` sets it. |
| `page` | `number` | `1` | bindable |
| `rowHref` | `(row: T) => string` |  | The row opens a page. The lead becomes the link. |
| `onRowClick` | `(row: T) => void` |  | The row opens in place: a panel, a detail view. The lead becomes the button. |
| `loading` | `boolean` | `false` | Placeholder rows while the data is on its way. |
| `empty` | `Snippet` |  | Drawn in place of the body when there are no rows. |

### RatingChip

| Prop | Type | Default | Notes |
| --- | --- | --- | --- |
| `grade` | `string` |  | required |
| `hint` | `string` |  | What the letter hides: the score and what it was charged for. |
| `class` | `string` |  |  |
