feat(widgets): the built-in table on the native table node

Same data and behaviour: columns (numbers aligned to the end, with their unit and digits), sorting by a header press
(numbers largest first, text A to Z, again the other way), choose submitting { index, row }. A table's cells hold
text, so each row's trend is a text sparkline (▁▂▃▅▇) in a column of its own instead of a canvas. The TUI writes it
as aligned text.
This commit is contained in:
Sebastian Herrlinger 2026-11-27 13:48:23 +01:00
parent b8e45c537a
commit fb93fdad19
8 changed files with 186 additions and 515 deletions

View file

@ -23,6 +23,6 @@ from `widget_template` action `list`; `packages/widget/test/fixtures/diagrams.ts
| `boxplot` | `groups: { label, values? \| stats? }[]` (≤ 12) | Comparing distributions across groups (build times per runner) including spread and outliers. |
| `flowchart` | `nodes: { id, label?, shape? }[]` (process, decision, terminal, io), `edges: { from, to, label? }[]` | Processes and decision logic; laid out top down automatically, loops allowed. |
| `sequence` | `participants: string[]`, `messages: { from, to, label, kind? }[]` (sync, async, reply) | Interactions over time between systems or people (request flows, protocols). |
| `table` | `columns: { label, unit?, digits? }[]`, `rows: { cells, trend? }[]` (≤ 50) | Exact values the user wants to scan and sort, with a sparkline trend per row. |
| `table` | `columns: { label, unit?, digits? }[]`, `rows: { cells, trend? }[]` (≤ 50) | Exact values the user wants to scan and sort, with a sparkline trend per row. A native `table` node: clients draw it like their markdown tables (the TUI as aligned text); a header press sorts, the trend is a text sparkline column (`▁▂▃▅▇`). |
For one or two plain series over categories or time, use `chart` (bar or line).

View file

@ -539,7 +539,7 @@ export const diagrams: ReadonlyArray<WidgetTemplate> = [
),
make(
"table",
"A sortable data table with aligned columns and an optional sparkline per row. Choose submits { index, row: { [column]: cell } }.",
"A sortable data table, drawn as the client's native table, with an optional text sparkline per row. Choose submits { index, row: { [column]: cell } }.",
object(
{
title,

File diff suppressed because one or more lines are too long

View file

@ -1,76 +1,46 @@
// A sortable table built from regular nodes: each row is one monospace line so columns line up in every client (the
// TUI included), sort buttons above, and a small canvas sparkline per row for its `trend`. With `choose`, rows become
// selectable cards and the Choose button submits the selected row.
// A sortable data table on the native `table` node: clients draw it like their markdown tables (the TUI as aligned
// text), a header press sorts by its column, and each row's `trend` shows as a text sparkline in a column of its own (a
// table's cells hold text, not nodes). With `choose`, a row press selects a row and the Choose button submits it.
const SPARK_WIDTH = 96
const SPARK_HEIGHT = 22
const INTRO = 0.6
const MAX_WIDTH = 28
const SPARK = "▁▂▃▄▅▆▇█"
function init(data) {
return { sort: null, desc: false, selected: null }
}
function view(state, data) {
// Once per view: every cell formatted, and per column its width and whether it's numeric. A row's line must not
// rescan the rows (that made views O(rows²)).
const cells = data.rows.map((row) => data.columns.map((_, index) => text(data, index, row.cells[index])))
const widths = measure(data, cells)
const numbers = data.columns.map((_, index) => numeric(data, index))
const trend = data.rows.some((row) => row.trend)
// Rows are keyed by their index in `data.rows`, so sorting keeps each row's ids.
const wrap = (index, children) =>
data.choose && index !== null
? ui.card(
{
key: index,
selected: state.selected === index,
onPress: (state) => ({ ...state, selected: state.selected === index ? null : index }),
},
[ui.row({ gap: 1, align: "center", wrap: true }, children)],
)
: ui.row({ key: index ?? "header", gap: 1, align: "center", wrap: true }, children)
// Row indices in display order; the table's rows are in this order, so a row press maps back through it.
const shown = order(state, data)
const picked = state.selected === null ? null : data.rows[state.selected]
return ui.column({ gap: 1, align: "stretch" }, [
ui.text(data.title, { style: "title" }),
ui.row({ gap: 1, align: "center", wrap: true }, [
ui.text("Sort by", { style: "caption", tone: "muted" }),
data.columns.map((column, index) =>
ui.button(column.label + (state.sort === index ? (state.desc ? " ↓" : " ↑") : ""), {
variant: state.sort === index ? "primary" : "secondary",
onPress: (state) =>
state.sort === index
? { ...state, desc: !state.desc }
: { ...state, sort: index, desc: numeric(data, index) },
}),
),
]),
wrap(null, [
ui.text(
line(
widths,
numbers,
data.columns.map((column) => column.label),
),
{ style: "code", tone: "muted" },
),
trend && ui.text(data.trendLabel ?? "Trend", { style: "caption", tone: "muted" }),
]),
!data.choose && ui.divider(),
order(state, data).map((index) =>
wrap(index, [
ui.text(line(widths, numbers, cells[index]), { style: "code" }),
trend &&
data.rows[index].trend &&
ui.canvas({
key: "spark" + index,
width: SPARK_WIDTH,
height: SPARK_HEIGHT,
fps: 60,
duration: INTRO,
alt: (data.trendLabel ?? "Trend") + ": " + data.rows[index].trend.map(compact).join(", "),
}),
ui.table(
[
...data.columns.map((column, index) => ({
label: column.label,
align: numeric(data, index) ? "end" : "start",
})),
...(trend ? [data.trendLabel ?? "Trend"] : []),
],
shown.map((index) => [
...data.columns.map((_, column) => text(data, column, data.rows[index].cells[column])),
...(trend ? [spark(data.rows[index].trend)] : []),
]),
{
sort: state.sort === null ? undefined : { column: state.sort, descending: state.desc },
selected: data.choose && state.selected !== null ? shown.indexOf(state.selected) : undefined,
// The trend column doesn't sort; numbers sort largest first, text A to Z, a second press the other way.
onSort: (state, column) =>
column >= data.columns.length
? state
: state.sort === column
? { ...state, desc: !state.desc }
: { ...state, sort: column, desc: numeric(data, column) },
onPress: data.choose
? (state, row) => ({ ...state, selected: state.selected === shown[row] ? null : shown[row] })
: undefined,
},
),
data.choose &&
ui.row({ gap: 1 }, [
@ -92,25 +62,12 @@ function choose(state, data) {
})
}
// A sparkline: the trend as a line over a faint area, drawn in from the left, with the last value marked.
function draw(state, data, frame) {
const g = ui.draw()
const values = data.rows[Number(frame.key.slice(5))].trend
// A trend as block characters scaled to its own range, lowest ▁ to highest █; no trend is empty.
function spark(values) {
if (!values || values.length === 0) return ""
const min = Math.min(...values)
const span = Math.max(...values) - min || 1
const x = (index) => 3 + ((frame.width - 6) * index) / Math.max(1, values.length - 1)
const y = (value) => 3 + (frame.height - 6) * (1 - (value - min) / span)
const shown = Math.max(1, Math.ceil(ease(frame.t / INTRO) * values.length))
const points = values.slice(0, shown).map((value, index) => [index === 0 ? "M" : "L", x(index), y(value)])
const stroke = data.color ?? "accent"
if (points.length > 1)
g.save()
.alpha(0.15)
.path([...points, ["L", x(shown - 1), frame.height], ["L", x(0), frame.height], ["Z"]], stroke)
.restore()
g.path(points, { stroke, width: 1.5, cap: "round" })
if (shown === values.length) g.circle(x(shown - 1), y(values[shown - 1]), 2.5, stroke)
return g.commands
return values.map((value) => SPARK[Math.round(((value - min) / span) * (SPARK.length - 1))]).join("")
}
// Row indices in display order: stable, numbers by value, text case-insensitively, empty cells last.
@ -135,26 +92,6 @@ function numeric(data, column) {
return data.rows.every((row) => typeof (row.cells[column] ?? 0) === "number")
}
// Character widths of each column: the longest of the label and the formatted cells, capped at MAX_WIDTH.
function measure(data, cells) {
return data.columns.map((column, index) =>
Math.min(
MAX_WIDTH,
cells.reduce((widest, row) => Math.max(widest, row[index].length), column.label.length),
),
)
}
// One line of already formatted cells, cut and padded to the column widths.
function line(widths, numbers, cells) {
return cells
.map((value, index) => {
const cell = value.length > widths[index] ? value.slice(0, widths[index] - 1) + "…" : value
return numbers[index] ? cell.padStart(widths[index]) : cell.padEnd(widths[index])
})
.join(" ")
}
function text(data, index, cell) {
if (cell === undefined || cell === null) return "–"
if (typeof cell === "string") return cell
@ -167,12 +104,3 @@ function text(data, index, cell) {
if (/^[$€£¥]$/.test(unit)) return (cell < 0 ? "-" : "") + unit + number.replace("-", "")
return unit.length > 1 && /^[a-z]/i.test(unit) ? number + " " + unit : number + unit
}
function compact(value) {
return String(Math.round(value * 100) / 100)
}
function ease(p) {
const clamped = Math.max(0, Math.min(1, p))
return 1 - Math.pow(1 - clamped, 3)
}

View file

@ -78,8 +78,10 @@ describe("every diagram", () => {
expect(widgetTemplate(name).description.length).toBeGreaterThan(20)
const session = await start(name, examples[name])
expect(texts(session.view)[0]).toBe(examples[name].title)
const list = canvases(session.view)
expect(list.length).toBeGreaterThan(0)
// The table is a native table node, not a canvas.
if (name === "table") expect(nodes(session.view).some((node) => node.type === "table")).toBe(true)
const list = name === "table" ? [] : canvases(session.view)
if (name !== "table") expect(list.length).toBeGreaterThan(0)
for (const canvas of list) {
expect(canvas.id).toBeString()
expect(canvas.alt?.length).toBeGreaterThan(10)
@ -428,46 +430,37 @@ test("sequence: messages in rows, tap one, choose; unknown participants fail", a
).rejects.toBeInstanceOf(StepError)
})
test("table: aligned monospace rows, sort, sparklines, select a row, choose", async () => {
test("table: a native table, sorted by a header press, text sparklines, select a row, choose", async () => {
const session = await start("table", examples.table)
const rows = () =>
texts(session.view).filter((text) => text.startsWith("GET") || text.startsWith("POST") || text.startsWith("PUT"))
expect(rows()).toEqual([
"GET /users 182,400 120 ms 0.12%",
"POST /orders 64,200 340 ms 1.40%",
"GET /search 120,900 210 ms 0.30%",
"PUT /profile 8,800 95 ms 0.05%",
type Table = Extract<Node, { type: "table" }>
const table = () => nodes(session.view).find((node): node is Table => node.type === "table")!
const first = () => table().rows.map((row) => row[0])
expect(table().columns).toEqual([
{ label: "Endpoint", align: "start" },
{ label: "Requests", align: "end" },
{ label: "p95", align: "end" },
{ label: "Errors", align: "end" },
{ label: "7d requests" },
])
await press(session, "Requests")
expect(rows().map((row) => row.split(" ")[0].trim())).toEqual([
"GET /users",
"GET /search",
"POST /orders",
"PUT /profile",
])
expect(button(session.view, "Requests")).toMatchObject({ label: "Requests ↓", variant: "primary" })
await press(session, "Requests")
expect(rows()[0].startsWith("PUT /profile")).toBe(true)
await press(session, "Endpoint")
expect(rows()[0].startsWith("GET /search")).toBe(true)
// Rows are keyed by their index in the data, so sorting keeps each row's (and its sparkline's) id.
expect(canvases(session.view).map((canvas) => canvas.id)).toEqual([
"0/:2/0/:spark2",
"0/:0/0/:spark0",
"0/:1/0/:spark1",
"0/:3/0/:spark3",
])
const spark = canvases(session.view)[1]
expect(spark).toMatchObject({ width: 96, height: 22, alt: "7d requests: 20, 22, 25, 24, 27, 30, 34" })
const first = (await session.draw(frame(spark, 0))).commands
const end = (await session.draw(frame(spark, 1))).commands
const line = (commands: ReadonlyArray<Command>) =>
commands.find((command) => command[0] === "path" && command[2].width === 1.5)
expect(line(first)?.[1]).toHaveLength(1)
expect(line(end)?.[1]).toHaveLength(7)
expect(end.filter((command) => command[0] === "circle")).toHaveLength(1)
const row = nodes(session.view).find((node) => node.type === "card" && node.id?.endsWith("/:2"))
await session.dispatch({ id: row?.type === "card" ? (row.id ?? "") : "", type: "press" })
expect(table().rows[0]).toEqual(["GET /users", "182,400", "120 ms", "0.12%", "▁▂▄▃▅▆█"])
expect([table().sortable, table().selectable, table().sort]).toEqual([true, true, undefined])
const sort = (column: number) => session.dispatch({ id: table().id!, type: "change", value: column })
await sort(1)
expect(first()).toEqual(["GET /users", "GET /search", "POST /orders", "PUT /profile"])
expect(table().sort).toEqual({ column: 1, descending: true })
await sort(1)
expect(first()[0]).toBe("PUT /profile")
await sort(0)
expect(first()[0]).toBe("GET /search")
expect(table().sort).toEqual({ column: 0, descending: false })
// The trend column doesn't sort.
await sort(4)
expect(table().sort).toEqual({ column: 0, descending: false })
// A row press selects the row shown there, which stays selected when the order changes.
await session.dispatch({ id: table().id!, type: "press", value: 0 })
expect(table().selected).toBe(0)
await sort(0)
expect(table().selected).toBe(3)
expect(button(session.view, "Choose")).toMatchObject({ label: "Choose GET /search", disabled: false })
expect(await choose(session)).toEqual({
index: 2,
@ -475,9 +468,20 @@ test("table: aligned monospace rows, sort, sparklines, select a row, choose", as
})
})
test("table: a large table builds in linear time and lines up exactly", async () => {
// Past the 50-row schema cap on purpose: clients may run old or hand-written data, and a view that rescans every row
// per row (as `line` once did) blows the step and slice budgets there.
test("table: without choose, rows take no presses; without trends, no trend column", async () => {
const data = { title: "t", columns: [{ label: "Name" }, { label: "Count" }], rows: [{ cells: ["a", 1] }] }
const view = (await step(program(widgetTemplate("table").source), { phase: "init", data }, { timeoutMs: 5000 })).view
const table = nodes(view).find((node) => node.type === "table") as Extract<Node, { type: "table" }>
expect([table.selectable, table.sortable, table.columns.length, table.rows]).toEqual([
undefined,
true,
2,
[["a", "1"]],
])
})
test("table: a large table builds in linear time", async () => {
// Past the 50-row schema cap on purpose: clients may run old or hand-written data.
const rows = 300
const data = {
title: "Big",
@ -495,15 +499,10 @@ test("table: a large table builds in linear time and lines up exactly", async ()
view = (await step(source, { phase: "init", data }, { timeoutMs: 5000 })).view
times.push(performance.now() - started)
}
// About 50 ms on a laptop; the quadratic version took over twice that, and 800 rows hit the 250 ms step timeout.
expect(times.toSorted((a, b) => a - b)[1]).toBeLessThan(200)
const lines = texts(view!).filter((text) => text.startsWith("item "))
expect(lines).toHaveLength(rows)
// Names pad right and counts left, to the widest cell of each column.
const count = (index: number) => String(index * 7).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
expect(lines.slice(0, 2)).toEqual(["item 0 " + "0".padStart(5), "item 1 " + "7".padStart(5)])
expect(lines.at(-1)).toBe("item 299 " + count(299).padStart(5))
expect(canvases(view!)).toHaveLength(rows)
const table = nodes(view!).find((node) => node.type === "table") as Extract<Node, { type: "table" }>
expect(table.rows).toHaveLength(rows)
expect(table.rows.at(-1)).toEqual(["item 299", "2,093", "▁▅█"])
})
test("in full screen, diagrams with content in the top-right corner lay out below the close button", async () => {

File diff suppressed because one or more lines are too long

View file

@ -119,7 +119,8 @@ const data: Record<string, unknown> = {
}
test("every built-in's view comes out byte-identical to the reference tree building", async () => {
const step = builtins.filter((template) => template.mode === "step")
// The reference predates the table node, which the built-in `table` is (its wire fixture covers it).
const step = builtins.filter((template) => template.mode === "step" && template.name !== "table")
expect(step.map((template) => template.name).filter((name) => !(name in data))).toEqual([])
for (const template of step) {
const [fast, slow] = await trees(template.source, data[template.name])

View file

@ -91,7 +91,7 @@ const emitted = (value: unknown): unknown =>
const drops = new Set(["function-in-a-prop", "function-as-a-child", "function-in-an-option", "function-as-an-id"])
// Events protocol 1's prelude doesn't know: it can't agree on them.
const newer = new Set(cases.flatMap((item) => (item.newer ? [item.name] : [])))
const newer = new Set([...cases.flatMap((item) => (item.newer ? [item.name] : [])), "builtin-table"])
for (const file of files) {
test(`wire fixture ${file}`, async () => {