A dashboard from SQL with cross-filtering
One query feeds headline numbers, two bar charts and a table. Clicking a bar filters every other view, each filter can be removed with a button, and every view asks the engine for its own summary, so nothing is filtered or grouped in the browser.
How it works:
createViewStatefrom@surfaces-ui/stateholds what was picked as a plain filter list ({ column, op, values }, the form page filters and agents use) and sorts. A second click on a bar adds its value; a click on a chosen bar takes it out. It holds choices only; the filtering happens in the engine.- Each view gets
view.filters(ownColumn). The region chart gets every filter except the one onregion, so the bar a person clicked does not filter the other bars away. Views that pick nothing getview.filters(), which is all of them. Chartreports a click throughonPointClick, and the dashboard callsview.toggle(column, value). Clicking the same bar again removes it.- A click is never the only way. Every filter is shown as a button that removes it, and "Clear filters" removes them all. The grid's own sort is kept in the same state, through
onSortsChangeandview.setSorts. - Each headline number has a comparison beside it: revenue has a
Sparklineof the last twelve months, and the order count has aBulletGraphagainst a target. A number on its own does not say whether it is good. - The charts follow the library's chart rules: bars over categories with an aggregated measure, sorted largest first by the engine, on one scale.
The dashboard expects a query with region, status, amount and ordered_at columns. Change the column names to fit your data.
Dashboard.tsx:
import { BulletGraph, Chart, ControlIcon, DataGrid, Metric, Sparkline, filterWords, sortsFromSpec } from "@surfaces-ui/components";
import { type ViewStateService, createViewState } from "@surfaces-ui/state";
import { useStore } from "@surfaces-ui/state/react";
import { useMemo } from "react";
export interface DashboardProps {
sourceId: string;
/** Any read-only query with `region`, `status`, `amount` and `ordered_at` columns. */
sql: string;
/** Pass your own to keep the filters in the address bar or in storage. Defaults to a fresh one. */
view?: ViewStateService;
/** A monthly order count to compare against. */
ordersTarget?: number;
}
/**
* Headline numbers, two charts and a table over one query. Clicking a bar
* filters every other view; each view leaves out its own column, so the
* bars a person clicked stay there to click again.
*/
export function Dashboard({ sourceId, sql, view: given, ordersTarget = 100 }: DashboardProps) {
const view = useMemo(() => given ?? createViewState(), [given]);
const state = useStore(view);
const all = view.filters();
// One chip per value chosen by a click, and one per any other filter, each with its own remove button.
const chips = state.filters.flatMap((filter) =>
filter.op === "eq" || filter.op === "in"
? (filter.values ?? []).map((value) => ({ key: `${filter.column}:${value}`, label: `${filter.column}: ${String(value)}`, name: `Remove filter ${filter.column} is ${value}`, remove: () => view.toggle(filter.column, value) }))
: [{ key: `${filter.column}:${filter.op}`, label: filterWords(filter), name: `Remove filter ${filterWords(filter)}`, remove: () => view.setFilters(state.filters.filter((f) => f !== filter)) }],
);
return (
<div className="sf-container">
{/* Every filter a click made can be removed with a button, not only by clicking the bar again. */}
<div className="sf-filter-chips" role="group" aria-label="Filters" aria-live="polite">
{chips.length === 0 ? (
<span>Click a bar to filter everything else.</span>
) : (
chips.map((chip) => (
<button key={chip.key} type="button" className="sf-button" aria-label={chip.name} onClick={chip.remove}>
{chip.label} <ControlIcon icon="close" />
</button>
))
)}
<button type="button" className="sf-button" disabled={chips.length === 0} onClick={() => view.clear()}>
Clear filters
</button>
</div>
{/* Each headline number has a comparison beside it: a trend, or a target. */}
<div className="sf-a2-grid" style={{ ["--sf-grid-columns" as string]: 2 }}>
<div>
<Metric sourceId={sourceId} sql={sql} column="amount" aggregate="sum" label="Revenue" format="currency" filters={all} />
<Sparkline sourceId={sourceId} sql={sql} x="ordered_at" grain="month" column="amount" aggregate="sum" label="Revenue by month" format="currency" points={12} filters={all} />
</div>
<div>
<Metric sourceId={sourceId} sql={sql} aggregate="count" label="Orders" filters={all} />
<BulletGraph
sourceId={sourceId}
sql={sql}
aggregate="count"
label="Orders against target"
target={ordersTarget}
ranges={[
{ to: ordersTarget * 0.6, label: "Poor" },
{ to: ordersTarget * 0.9, label: "Fair" },
{ to: ordersTarget * 1.2, label: "Good" },
]}
filters={all}
/>
</div>
</div>
<div className="sf-a2-grid">
<Chart
sourceId={sourceId}
sql={sql}
type="bar"
x="region"
y={[{ column: "amount", aggregate: "sum", label: "Revenue" }]}
filters={view.filters("region")}
onPointClick={(point) => point.x !== null && view.toggle("region", point.x)}
height={260}
label="Revenue by region. Click a bar to filter."
/>
<Chart
sourceId={sourceId}
sql={sql}
type="bar"
x="status"
y={[{ aggregate: "count", label: "Orders" }]}
filters={view.filters("status")}
onPointClick={(point) => point.x !== null && view.toggle("status", point.x)}
height={260}
label="Orders by status. Click a bar to filter."
/>
</div>
<DataGrid
sourceId={sourceId}
sql={sql}
filters={all}
sorts={sortsFromSpec(state.sorts)}
onSortsChange={(sorts) => view.setSorts(sorts)}
height={320}
label="Orders"
/>
</div>
);
}To keep the filters in the address bar or in storage, create the view state yourself and pass it in. syncUrl and persist from @surfaces-ui/state work on it; the playground's hand-built dashboard does both, and adds undo with useHistory.
Put it on a page with a theme and a backend:
import "@surfaces-ui/components/styles.css";
import { DataSourceProvider, ThemeProvider } from "@surfaces-ui/components";
import { connectDataSource } from "@surfaces-ui/client-connect";
import { createRoot } from "react-dom/client";
import { Dashboard } from "./Dashboard.js";
const data = connectDataSource({ baseUrl: "http://localhost:5220" });
createRoot(document.getElementById("root")!).render(
<ThemeProvider>
<DataSourceProvider dataSource={data}>
<Dashboard sourceId="retail" sql="SELECT * FROM orders" />
</DataSourceProvider>
</ThemeProvider>,
);The test runs the real dashboard against memoryDataSource and writes down every query the views send. It makes a selection the way a click on a bar would, then checks that the grid, the other chart and the headline numbers carry the filter, and that the chart that made the selection does not. It also removes filters with the buttons. jsdom has no canvas, so the test gives ECharts a stand-in 2D context; it checks the queries, not the drawn bars, and a real click on a bar is not exercised here.
dashboard.test.tsx:
// @vitest-environment jsdom
import { create } from "@bufbuild/protobuf";
import { DataSourceProvider } from "@surfaces-ui/components";
import { type DataSource, memoryDataSource } from "@surfaces-ui/data";
import { ExecuteRequestSchema, type ViewQuery } from "@surfaces-ui/proto";
import { createViewState } from "@surfaces-ui/state";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { Dashboard } from "./Dashboard.js";
afterEach(cleanup);
// jsdom has no canvas. ECharts only needs a 2D context that accepts calls; nothing here reads pixels.
HTMLCanvasElement.prototype.getContext = function (this: HTMLCanvasElement) {
const state: Record<string | symbol, unknown> = { canvas: this };
return new Proxy(state, {
get: (target, key) => (key in target ? target[key] : key === "measureText" ? (text: string) => ({ width: text.length * 6 }) : () => ({ addColorStop() {} })),
set: (target, key, value) => ((target[key] = value), true),
});
} as unknown as typeof HTMLCanvasElement.prototype.getContext;
const regions = ["Europe", "Americas", "Asia Pacific"];
const statuses = ["shipped", "returned", "pending"];
const orders = Array.from({ length: 60 }, (_, i) => ({
order_id: i + 1,
region: regions[i % 3]!,
status: statuses[i % 4 === 0 ? 1 : i % 5 === 0 ? 2 : 0]!,
amount: 10 + (i % 7) * 5,
ordered_at: new Date(Date.UTC(2026, i % 6, 1 + (i % 20))),
}));
/** The in-memory backend, with every query the dashboard sends written down. */
function recorded() {
const inner = memoryDataSource({ sourceId: "shop", tables: { orders } });
const queries: ViewQuery[] = [];
const dataSource: DataSource = {
...inner,
execute(request, options) {
queries.push(create(ExecuteRequestSchema, request).query!);
return inner.execute(request, options);
},
};
return { dataSource, queries };
}
const filterColumns = (query: ViewQuery) => query.filters.map((f) => f.column).sort();
/** The latest query grouped by a column: the chart for that column. */
const chartQuery = (queries: ViewQuery[], column: string) => queries.filter((q) => q.groupBy.includes(column)).at(-1);
/** The latest query for table rows: the grid. */
const gridQuery = (queries: ViewQuery[]) => queries.filter((q) => q.aggregates.length === 0 && q.groupBy.length === 0).at(-1);
describe("a cross-filtered dashboard", () => {
it("filters every other view by a selection, but never the chart that made it", async () => {
const { dataSource, queries } = recorded();
const view = createViewState();
render(
<DataSourceProvider dataSource={dataSource}>
<Dashboard sourceId="shop" sql="SELECT * FROM orders" view={view} />
</DataSourceProvider>,
);
await waitFor(() => expect(chartQuery(queries, "region") && chartQuery(queries, "status") && gridQuery(queries)).toBeTruthy());
// The charts ask the engine to summarise; nothing is grouped in the browser.
expect(chartQuery(queries, "region")!.aggregates[0]!.column).toBe("amount");
// What a click on the "Europe" bar does.
const before = queries.length;
act(() => view.toggle("region", "Europe"));
await waitFor(() => expect(gridQuery(queries.slice(before))).toBeTruthy());
const after = queries.slice(before);
expect(filterColumns(gridQuery(after)!)).toEqual(["region"]);
expect(gridQuery(after)!.filters[0]!.values[0]!.kind.value).toBe("Europe");
expect(filterColumns(chartQuery(after, "status")!)).toEqual(["region"]);
// The region chart is not asked again with a region filter: its bars stay.
expect(after.filter((q) => q.groupBy.includes("region")).every((q) => !filterColumns(q).includes("region"))).toBe(true);
expect(filterColumns(chartQuery(queries, "region")!)).toEqual([]);
// Headline numbers and their comparisons follow the filter too.
const headline = after.filter((q) => q.groupBy.length === 0 && q.aggregates.length > 0);
expect(headline.length).toBeGreaterThan(0);
expect(headline.every((q) => filterColumns(q).includes("region"))).toBe(true);
});
it("removes a filter, or all of them, with buttons", async () => {
const { dataSource, queries } = recorded();
const view = createViewState();
render(<Dashboard sourceId="shop" sql="SELECT * FROM orders" view={view} />, {
wrapper: ({ children }) => <DataSourceProvider dataSource={dataSource}>{children}</DataSourceProvider>,
});
act(() => {
view.toggle("region", "Europe");
view.toggle("status", "returned");
});
await waitFor(() => expect(filterColumns(gridQuery(queries)!)).toEqual(["region", "status"]));
// The status chart leaves out status but keeps region.
await waitFor(() => expect(filterColumns(chartQuery(queries, "status")!)).toEqual(["region"]));
fireEvent.click(screen.getByRole("button", { name: "Remove filter region is Europe" }));
await waitFor(() => expect(filterColumns(gridQuery(queries)!)).toEqual(["status"]));
expect(view.get().filters).toEqual([{ column: "status", op: "eq", values: ["returned"] }]);
fireEvent.click(screen.getByRole("button", { name: "Clear filters" }));
await waitFor(() => expect(filterColumns(gridQuery(queries)!)).toEqual([]));
expect((screen.getByRole("button", { name: "Clear filters" }) as HTMLButtonElement).disabled).toBe(true);
});
});Source and test: apps/recipes/src/cross-filter-dashboard