diff --git a/packages/widget/docs/diagrams.md b/packages/widget/docs/diagrams.md index b71ae016b2a..c95e8b65b80 100644 --- a/packages/widget/docs/diagrams.md +++ b/packages/widget/docs/diagrams.md @@ -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). diff --git a/packages/widget/src/diagram.ts b/packages/widget/src/diagram.ts index 451f07aad35..695b0533aa7 100644 --- a/packages/widget/src/diagram.ts +++ b/packages/widget/src/diagram.ts @@ -539,7 +539,7 @@ export const diagrams: ReadonlyArray = [ ), 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, diff --git a/packages/widget/src/source.ts b/packages/widget/src/source.ts index 16ce2cbaa69..d599faf707a 100644 --- a/packages/widget/src/source.ts +++ b/packages/widget/src/source.ts @@ -47,4 +47,4 @@ export const flowchart = export const sequence = '// A sequence diagram: participants as columns with lifelines and messages between them, top to bottom in order.\n// Kinds: "sync" (solid, filled arrow), "async" (solid, open arrow) and "reply" (dashed, open arrow); a message to\n// itself loops back. Messages play in one after another; tap one to select it. With `choose`, the Choose button submits it.\n\nconst HEAD = 34\nconst ROW = 36\n\nfunction init(data) {\n for (const message of data.messages) [message.from, message.to].forEach((name) => participant(data, name))\n return { selected: null }\n}\n\nfunction view(state, data) {\n const picked = state.selected === null ? null : data.messages[state.selected]\n return ui.column({ gap: 1, align: "stretch" }, [\n ui.text(data.title, { style: "title" }),\n ui.canvas({\n onPointer: (state, p) => tap(state, data, p),\n height: HEAD + 14 + data.messages.length * ROW + 8,\n fps: 60,\n duration: intro(data),\n alt: summary(data),\n }),\n ui.text(picked ? describe(data, state.selected) : "Tap a message to select it", {\n style: "caption",\n tone: picked ? "default" : "muted",\n }),\n data.choose &&\n ui.row({ gap: 1 }, [\n ui.button("Choose message", { onPress: (state) => choose(state, data), variant: "primary", disabled: !picked }),\n ]),\n ])\n}\n\nfunction choose(state, data) {\n if (state.selected !== null) {\n const message = data.messages[state.selected]\n return submit({ index: state.selected, from: message.from, to: message.to, label: message.label })\n }\n return state\n}\n\nfunction tap(state, data, pointer) {\n pointer = below(pointer)\n if (pointer.kind !== "up") return state\n const hit = locate(data, pointer.y)\n return { ...state, selected: hit === state.selected ? null : hit }\n}\n\nfunction draw(state, data, frame) {\n frame = below(frame)\n const g = ui.draw()\n if (frame.top) g.translate(0, frame.top)\n const columns = layout(data, frame.width)\n const bottom = frame.height - 4\n const hover = frame.pointer && !frame.pointer.down ? locate(data, frame.pointer.y) : null\n columns.forEach((column) => {\n g.path(dashes(column.x, HEAD, column.x, bottom, 4, 4), { stroke: "border", width: 1 })\n g.rrect(column.x - column.w / 2, 2, column.w, HEAD - 6, 6, { fill: "surface", stroke: "border", width: 1 })\n g.text(column.x, HEAD / 2 + 3, column.label, { size: 12, weight: 600, align: "center" })\n })\n const step = (intro(data) - 0.5) / Math.max(1, data.messages.length - 1)\n data.messages.forEach((message, index) => {\n const grow = ease((frame.t - 0.2 - index * step) / 0.3)\n if (grow <= 0) return\n const y = HEAD + 14 + index * ROW + ROW / 2 + 6\n const from = columns[participant(data, message.from)].x\n const to = columns[participant(data, message.to)].x\n const active = index === state.selected || index === hover\n if (index === state.selected)\n g.save()\n .alpha(0.08)\n .rect(0, y - ROW + 8, frame.width, ROW, "text")\n .restore()\n const stroke = active ? "accent" : message.kind === "reply" ? "muted" : "text"\n const width = active ? 2 : 1.25\n const kind = message.kind ?? "sync"\n g.save().alpha(grow)\n if (from === to) {\n const loop = Math.min(36, frame.width - from - 8)\n g.path(\n [\n ["M", from, y - 8],\n ["L", from + loop, y - 8],\n ["L", from + loop, y + 6],\n ["L", from + 2, y + 6],\n ],\n { stroke, width },\n )\n head(g, from + 2, y + 6, -1, stroke, kind)\n g.text(from + loop + 6, y + 2, fit(number(data, index) + message.label, frame.width - from - loop - 10, 12), {\n size: 12,\n color: active ? "text" : "muted",\n })\n } else {\n const dir = to > from ? 1 : -1\n const end = from + (to - from) * grow\n if (kind === "reply") g.path(dashes(from, y, end - dir * 2, y, 6, 4), { stroke, width })\n else g.line(from, y, end - dir * 2, y, { stroke, width })\n if (grow >= 1) head(g, to, y, dir, stroke, kind)\n g.text((from + to) / 2, y - 6, fit(number(data, index) + message.label, Math.abs(to - from) - 12, 12), {\n size: 12,\n align: "center",\n weight: active ? 600 : 400,\n color: active ? "text" : kind === "reply" ? "muted" : "text",\n })\n }\n g.restore()\n })\n return g.commands\n}\n\nfunction layout(data, width) {\n const slot = (width - 8) / data.participants.length\n return data.participants.map((name, index) => ({\n label: fit(name, slot - 20, 12),\n x: 4 + slot * (index + 0.5),\n w: Math.min(slot - 10, 7.2 * name.length + 22),\n }))\n}\n\nfunction participant(data, name) {\n const index = data.participants.indexOf(name)\n if (index < 0) throw new Error(\'Unknown participant "\' + name + \'" in messages\')\n return index\n}\n\nfunction locate(data, y) {\n const index = Math.floor((y - HEAD - 14) / ROW)\n return index >= 0 && index < data.messages.length ? index : null\n}\n\n// One path of dash segments: a single draw command however long the line is.\nfunction dashes(x1, y1, x2, y2, on, off) {\n const length = Math.hypot(x2 - x1, y2 - y1)\n const dx = (x2 - x1) / (length || 1)\n const dy = (y2 - y1) / (length || 1)\n const segments = []\n for (let at = 0; at < length; at += on + off) {\n const stop = Math.min(length, at + on)\n segments.push(["M", x1 + dx * at, y1 + dy * at], ["L", x1 + dx * stop, y1 + dy * stop])\n }\n return segments\n}\n\nfunction head(g, x, y, dir, stroke, kind) {\n if (kind === "sync") g.path([["M", x, y], ["L", x - dir * 9, y - 4.5], ["L", x - dir * 9, y + 4.5], ["Z"]], stroke)\n else\n g.path(\n [\n ["M", x - dir * 9, y - 5],\n ["L", x, y],\n ["L", x - dir * 9, y + 5],\n ],\n { stroke, width: 1.5 },\n )\n}\n\nfunction intro(data) {\n return Math.round(Math.min(2.4, 0.5 + 0.12 * data.messages.length) * 100) / 100\n}\n\nfunction number(data, index) {\n return data.numbered ? index + 1 + ". " : ""\n}\n\nfunction describe(data, index) {\n const message = data.messages[index]\n return (\n index +\n 1 +\n ". " +\n message.from +\n " → " +\n message.to +\n ": " +\n message.label +\n (message.kind && message.kind !== "sync" ? " (" + message.kind + ")" : "")\n )\n}\n\nfunction summary(data) {\n return (\n "Sequence diagram between " +\n data.participants.join(", ") +\n ". " +\n data.messages.map((_, index) => describe(data, index)).join("; ")\n )\n}\n\nfunction fit(text, width, size) {\n const max = Math.max(1, Math.floor(width / (size * 0.58)))\n return text.length <= max ? text : text.slice(0, Math.max(1, max - 1)) + "…"\n}\n\nfunction ease(p) {\n const clamped = Math.max(0, Math.min(1, p))\n return 1 - Math.pow(1 - clamped, 3)\n}\n\n// In full screen, the layout starts below the close button when it overlaps this canvas (widgets-fullscreen.md):\n// `close` comes with the frame and the pointer, so drawing and hit testing agree.\nfunction below(area) {\n const top = area.close ? Math.max(0, area.close.y + area.close.height) : 0\n if (top === 0) return area\n return {\n ...area,\n top,\n height: area.height - top,\n ...(typeof area.y === "number" ? { y: area.y - top } : {}),\n ...(area.pointer ? { pointer: { ...area.pointer, y: area.pointer.y - top } } : {}),\n }\n}\n' export const table = - '// A sortable table built from regular nodes: each row is one monospace line so columns line up in every client (the\n// TUI included), sort buttons above, and a small canvas sparkline per row for its `trend`. With `choose`, rows become\n// selectable cards and the Choose button submits the selected row.\n\nconst SPARK_WIDTH = 96\nconst SPARK_HEIGHT = 22\nconst INTRO = 0.6\nconst MAX_WIDTH = 28\n\nfunction init(data) {\n return { sort: null, desc: false, selected: null }\n}\n\nfunction view(state, data) {\n // Once per view: every cell formatted, and per column its width and whether it\'s numeric. A row\'s line must not\n // rescan the rows (that made views O(rows²)).\n const cells = data.rows.map((row) => data.columns.map((_, index) => text(data, index, row.cells[index])))\n const widths = measure(data, cells)\n const numbers = data.columns.map((_, index) => numeric(data, index))\n const trend = data.rows.some((row) => row.trend)\n // Rows are keyed by their index in `data.rows`, so sorting keeps each row\'s ids.\n const wrap = (index, children) =>\n data.choose && index !== null\n ? ui.card(\n {\n key: index,\n selected: state.selected === index,\n onPress: (state) => ({ ...state, selected: state.selected === index ? null : index }),\n },\n [ui.row({ gap: 1, align: "center", wrap: true }, children)],\n )\n : ui.row({ key: index ?? "header", gap: 1, align: "center", wrap: true }, children)\n const picked = state.selected === null ? null : data.rows[state.selected]\n return ui.column({ gap: 1, align: "stretch" }, [\n ui.text(data.title, { style: "title" }),\n ui.row({ gap: 1, align: "center", wrap: true }, [\n ui.text("Sort by", { style: "caption", tone: "muted" }),\n data.columns.map((column, index) =>\n ui.button(column.label + (state.sort === index ? (state.desc ? " ↓" : " ↑") : ""), {\n variant: state.sort === index ? "primary" : "secondary",\n onPress: (state) =>\n state.sort === index\n ? { ...state, desc: !state.desc }\n : { ...state, sort: index, desc: numeric(data, index) },\n }),\n ),\n ]),\n wrap(null, [\n ui.text(\n line(\n widths,\n numbers,\n data.columns.map((column) => column.label),\n ),\n { style: "code", tone: "muted" },\n ),\n trend && ui.text(data.trendLabel ?? "Trend", { style: "caption", tone: "muted" }),\n ]),\n !data.choose && ui.divider(),\n order(state, data).map((index) =>\n wrap(index, [\n ui.text(line(widths, numbers, cells[index]), { style: "code" }),\n trend &&\n data.rows[index].trend &&\n ui.canvas({\n key: "spark" + index,\n width: SPARK_WIDTH,\n height: SPARK_HEIGHT,\n fps: 60,\n duration: INTRO,\n alt: (data.trendLabel ?? "Trend") + ": " + data.rows[index].trend.map(compact).join(", "),\n }),\n ]),\n ),\n data.choose &&\n ui.row({ gap: 1 }, [\n ui.button(picked ? "Choose " + text(data, 0, picked.cells[0]) : "Choose", {\n variant: "primary",\n disabled: !picked,\n onPress: (state) => choose(state, data),\n }),\n ]),\n ])\n}\n\nfunction choose(state, data) {\n if (state.selected === null) return state\n const row = data.rows[state.selected]\n return submit({\n index: state.selected,\n row: Object.fromEntries(data.columns.map((column, at) => [column.label, row.cells[at] ?? null])),\n })\n}\n\n// A sparkline: the trend as a line over a faint area, drawn in from the left, with the last value marked.\nfunction draw(state, data, frame) {\n const g = ui.draw()\n const values = data.rows[Number(frame.key.slice(5))].trend\n const min = Math.min(...values)\n const span = Math.max(...values) - min || 1\n const x = (index) => 3 + ((frame.width - 6) * index) / Math.max(1, values.length - 1)\n const y = (value) => 3 + (frame.height - 6) * (1 - (value - min) / span)\n const shown = Math.max(1, Math.ceil(ease(frame.t / INTRO) * values.length))\n const points = values.slice(0, shown).map((value, index) => [index === 0 ? "M" : "L", x(index), y(value)])\n const stroke = data.color ?? "accent"\n if (points.length > 1)\n g.save()\n .alpha(0.15)\n .path([...points, ["L", x(shown - 1), frame.height], ["L", x(0), frame.height], ["Z"]], stroke)\n .restore()\n g.path(points, { stroke, width: 1.5, cap: "round" })\n if (shown === values.length) g.circle(x(shown - 1), y(values[shown - 1]), 2.5, stroke)\n return g.commands\n}\n\n// Row indices in display order: stable, numbers by value, text case-insensitively, empty cells last.\nfunction order(state, data) {\n const indices = data.rows.map((_, index) => index)\n if (state.sort === null) return indices\n const key = (index) => {\n const cell = data.rows[index].cells[state.sort]\n return typeof cell === "string" ? cell.toLowerCase() : cell\n }\n return indices.sort((a, b) => {\n const left = key(a)\n const right = key(b)\n if (left === right) return a - b\n if (left === undefined || left === null) return 1\n if (right === undefined || right === null) return -1\n return (left < right ? -1 : 1) * (state.desc ? -1 : 1)\n })\n}\n\nfunction numeric(data, column) {\n return data.rows.every((row) => typeof (row.cells[column] ?? 0) === "number")\n}\n\n// Character widths of each column: the longest of the label and the formatted cells, capped at MAX_WIDTH.\nfunction measure(data, cells) {\n return data.columns.map((column, index) =>\n Math.min(\n MAX_WIDTH,\n cells.reduce((widest, row) => Math.max(widest, row[index].length), column.label.length),\n ),\n )\n}\n\n// One line of already formatted cells, cut and padded to the column widths.\nfunction line(widths, numbers, cells) {\n return cells\n .map((value, index) => {\n const cell = value.length > widths[index] ? value.slice(0, widths[index] - 1) + "…" : value\n return numbers[index] ? cell.padStart(widths[index]) : cell.padEnd(widths[index])\n })\n .join(" ")\n}\n\nfunction text(data, index, cell) {\n if (cell === undefined || cell === null) return "–"\n if (typeof cell === "string") return cell\n const column = data.columns[index]\n const digits = column.digits ?? (Number.isInteger(cell) ? 0 : 2)\n const [whole, fraction] = Math.abs(cell).toFixed(digits).split(".")\n const number = (cell < 0 ? "-" : "") + whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ",") + (fraction ? "." + fraction : "")\n const unit = column.unit\n if (!unit) return number\n if (/^[$€£¥]$/.test(unit)) return (cell < 0 ? "-" : "") + unit + number.replace("-", "")\n return unit.length > 1 && /^[a-z]/i.test(unit) ? number + " " + unit : number + unit\n}\n\nfunction compact(value) {\n return String(Math.round(value * 100) / 100)\n}\n\nfunction ease(p) {\n const clamped = Math.max(0, Math.min(1, p))\n return 1 - Math.pow(1 - clamped, 3)\n}\n' + '// A sortable data table on the native `table` node: clients draw it like their markdown tables (the TUI as aligned\n// 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\n// table\'s cells hold text, not nodes). With `choose`, a row press selects a row and the Choose button submits it.\n\nconst SPARK = "▁▂▃▄▅▆▇█"\n\nfunction init(data) {\n return { sort: null, desc: false, selected: null }\n}\n\nfunction view(state, data) {\n const trend = data.rows.some((row) => row.trend)\n // Row indices in display order; the table\'s rows are in this order, so a row press maps back through it.\n const shown = order(state, data)\n const picked = state.selected === null ? null : data.rows[state.selected]\n return ui.column({ gap: 1, align: "stretch" }, [\n ui.text(data.title, { style: "title" }),\n ui.table(\n [\n ...data.columns.map((column, index) => ({\n label: column.label,\n align: numeric(data, index) ? "end" : "start",\n })),\n ...(trend ? [data.trendLabel ?? "Trend"] : []),\n ],\n shown.map((index) => [\n ...data.columns.map((_, column) => text(data, column, data.rows[index].cells[column])),\n ...(trend ? [spark(data.rows[index].trend)] : []),\n ]),\n {\n sort: state.sort === null ? undefined : { column: state.sort, descending: state.desc },\n selected: data.choose && state.selected !== null ? shown.indexOf(state.selected) : undefined,\n // The trend column doesn\'t sort; numbers sort largest first, text A to Z, a second press the other way.\n onSort: (state, column) =>\n column >= data.columns.length\n ? state\n : state.sort === column\n ? { ...state, desc: !state.desc }\n : { ...state, sort: column, desc: numeric(data, column) },\n onPress: data.choose\n ? (state, row) => ({ ...state, selected: state.selected === shown[row] ? null : shown[row] })\n : undefined,\n },\n ),\n data.choose &&\n ui.row({ gap: 1 }, [\n ui.button(picked ? "Choose " + text(data, 0, picked.cells[0]) : "Choose", {\n variant: "primary",\n disabled: !picked,\n onPress: (state) => choose(state, data),\n }),\n ]),\n ])\n}\n\nfunction choose(state, data) {\n if (state.selected === null) return state\n const row = data.rows[state.selected]\n return submit({\n index: state.selected,\n row: Object.fromEntries(data.columns.map((column, at) => [column.label, row.cells[at] ?? null])),\n })\n}\n\n// A trend as block characters scaled to its own range, lowest ▁ to highest █; no trend is empty.\nfunction spark(values) {\n if (!values || values.length === 0) return ""\n const min = Math.min(...values)\n const span = Math.max(...values) - min || 1\n return values.map((value) => SPARK[Math.round(((value - min) / span) * (SPARK.length - 1))]).join("")\n}\n\n// Row indices in display order: stable, numbers by value, text case-insensitively, empty cells last.\nfunction order(state, data) {\n const indices = data.rows.map((_, index) => index)\n if (state.sort === null) return indices\n const key = (index) => {\n const cell = data.rows[index].cells[state.sort]\n return typeof cell === "string" ? cell.toLowerCase() : cell\n }\n return indices.sort((a, b) => {\n const left = key(a)\n const right = key(b)\n if (left === right) return a - b\n if (left === undefined || left === null) return 1\n if (right === undefined || right === null) return -1\n return (left < right ? -1 : 1) * (state.desc ? -1 : 1)\n })\n}\n\nfunction numeric(data, column) {\n return data.rows.every((row) => typeof (row.cells[column] ?? 0) === "number")\n}\n\nfunction text(data, index, cell) {\n if (cell === undefined || cell === null) return "–"\n if (typeof cell === "string") return cell\n const column = data.columns[index]\n const digits = column.digits ?? (Number.isInteger(cell) ? 0 : 2)\n const [whole, fraction] = Math.abs(cell).toFixed(digits).split(".")\n const number = (cell < 0 ? "-" : "") + whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ",") + (fraction ? "." + fraction : "")\n const unit = column.unit\n if (!unit) return number\n if (/^[$€£¥]$/.test(unit)) return (cell < 0 ? "-" : "") + unit + number.replace("-", "")\n return unit.length > 1 && /^[a-z]/i.test(unit) ? number + " " + unit : number + unit\n}\n' diff --git a/packages/widget/src/widget-templates/table.js b/packages/widget/src/widget-templates/table.js index f17761e6b8b..9fa8a7d8a3e 100644 --- a/packages/widget/src/widget-templates/table.js +++ b/packages/widget/src/widget-templates/table.js @@ -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) -} diff --git a/packages/widget/test/diagrams.test.ts b/packages/widget/test/diagrams.test.ts index fee2f6d7dfc..6fb36095ed7 100644 --- a/packages/widget/test/diagrams.test.ts +++ b/packages/widget/test/diagrams.test.ts @@ -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 + 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) => - 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 + 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 + 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 () => { diff --git a/packages/widget/test/fixtures/wire/builtin-table.json b/packages/widget/test/fixtures/wire/builtin-table.json index 921814b1489..b04dd0f204c 100644 --- a/packages/widget/test/fixtures/wire/builtin-table.json +++ b/packages/widget/test/fixtures/wire/builtin-table.json @@ -1,7 +1,7 @@ { "name": "builtin-table", "builtin": "table", - "source": "// A sortable table built from regular nodes: each row is one monospace line so columns line up in every client (the\n// TUI included), sort buttons above, and a small canvas sparkline per row for its `trend`. With `choose`, rows become\n// selectable cards and the Choose button submits the selected row.\n\nconst SPARK_WIDTH = 96\nconst SPARK_HEIGHT = 22\nconst INTRO = 0.6\nconst MAX_WIDTH = 28\n\nfunction init(data) {\n return { sort: null, desc: false, selected: null }\n}\n\nfunction view(state, data) {\n // Once per view: every cell formatted, and per column its width and whether it's numeric. A row's line must not\n // rescan the rows (that made views O(rows²)).\n const cells = data.rows.map((row) => data.columns.map((_, index) => text(data, index, row.cells[index])))\n const widths = measure(data, cells)\n const numbers = data.columns.map((_, index) => numeric(data, index))\n const trend = data.rows.some((row) => row.trend)\n // Rows are keyed by their index in `data.rows`, so sorting keeps each row's ids.\n const wrap = (index, children) =>\n data.choose && index !== null\n ? ui.card(\n {\n key: index,\n selected: state.selected === index,\n onPress: (state) => ({ ...state, selected: state.selected === index ? null : index }),\n },\n [ui.row({ gap: 1, align: \"center\", wrap: true }, children)],\n )\n : ui.row({ key: index ?? \"header\", gap: 1, align: \"center\", wrap: true }, children)\n const picked = state.selected === null ? null : data.rows[state.selected]\n return ui.column({ gap: 1, align: \"stretch\" }, [\n ui.text(data.title, { style: \"title\" }),\n ui.row({ gap: 1, align: \"center\", wrap: true }, [\n ui.text(\"Sort by\", { style: \"caption\", tone: \"muted\" }),\n data.columns.map((column, index) =>\n ui.button(column.label + (state.sort === index ? (state.desc ? \" ↓\" : \" ↑\") : \"\"), {\n variant: state.sort === index ? \"primary\" : \"secondary\",\n onPress: (state) =>\n state.sort === index\n ? { ...state, desc: !state.desc }\n : { ...state, sort: index, desc: numeric(data, index) },\n }),\n ),\n ]),\n wrap(null, [\n ui.text(\n line(\n widths,\n numbers,\n data.columns.map((column) => column.label),\n ),\n { style: \"code\", tone: \"muted\" },\n ),\n trend && ui.text(data.trendLabel ?? \"Trend\", { style: \"caption\", tone: \"muted\" }),\n ]),\n !data.choose && ui.divider(),\n order(state, data).map((index) =>\n wrap(index, [\n ui.text(line(widths, numbers, cells[index]), { style: \"code\" }),\n trend &&\n data.rows[index].trend &&\n ui.canvas({\n key: \"spark\" + index,\n width: SPARK_WIDTH,\n height: SPARK_HEIGHT,\n fps: 60,\n duration: INTRO,\n alt: (data.trendLabel ?? \"Trend\") + \": \" + data.rows[index].trend.map(compact).join(\", \"),\n }),\n ]),\n ),\n data.choose &&\n ui.row({ gap: 1 }, [\n ui.button(picked ? \"Choose \" + text(data, 0, picked.cells[0]) : \"Choose\", {\n variant: \"primary\",\n disabled: !picked,\n onPress: (state) => choose(state, data),\n }),\n ]),\n ])\n}\n\nfunction choose(state, data) {\n if (state.selected === null) return state\n const row = data.rows[state.selected]\n return submit({\n index: state.selected,\n row: Object.fromEntries(data.columns.map((column, at) => [column.label, row.cells[at] ?? null])),\n })\n}\n\n// A sparkline: the trend as a line over a faint area, drawn in from the left, with the last value marked.\nfunction draw(state, data, frame) {\n const g = ui.draw()\n const values = data.rows[Number(frame.key.slice(5))].trend\n const min = Math.min(...values)\n const span = Math.max(...values) - min || 1\n const x = (index) => 3 + ((frame.width - 6) * index) / Math.max(1, values.length - 1)\n const y = (value) => 3 + (frame.height - 6) * (1 - (value - min) / span)\n const shown = Math.max(1, Math.ceil(ease(frame.t / INTRO) * values.length))\n const points = values.slice(0, shown).map((value, index) => [index === 0 ? \"M\" : \"L\", x(index), y(value)])\n const stroke = data.color ?? \"accent\"\n if (points.length > 1)\n g.save()\n .alpha(0.15)\n .path([...points, [\"L\", x(shown - 1), frame.height], [\"L\", x(0), frame.height], [\"Z\"]], stroke)\n .restore()\n g.path(points, { stroke, width: 1.5, cap: \"round\" })\n if (shown === values.length) g.circle(x(shown - 1), y(values[shown - 1]), 2.5, stroke)\n return g.commands\n}\n\n// Row indices in display order: stable, numbers by value, text case-insensitively, empty cells last.\nfunction order(state, data) {\n const indices = data.rows.map((_, index) => index)\n if (state.sort === null) return indices\n const key = (index) => {\n const cell = data.rows[index].cells[state.sort]\n return typeof cell === \"string\" ? cell.toLowerCase() : cell\n }\n return indices.sort((a, b) => {\n const left = key(a)\n const right = key(b)\n if (left === right) return a - b\n if (left === undefined || left === null) return 1\n if (right === undefined || right === null) return -1\n return (left < right ? -1 : 1) * (state.desc ? -1 : 1)\n })\n}\n\nfunction numeric(data, column) {\n return data.rows.every((row) => typeof (row.cells[column] ?? 0) === \"number\")\n}\n\n// Character widths of each column: the longest of the label and the formatted cells, capped at MAX_WIDTH.\nfunction measure(data, cells) {\n return data.columns.map((column, index) =>\n Math.min(\n MAX_WIDTH,\n cells.reduce((widest, row) => Math.max(widest, row[index].length), column.label.length),\n ),\n )\n}\n\n// One line of already formatted cells, cut and padded to the column widths.\nfunction line(widths, numbers, cells) {\n return cells\n .map((value, index) => {\n const cell = value.length > widths[index] ? value.slice(0, widths[index] - 1) + \"…\" : value\n return numbers[index] ? cell.padStart(widths[index]) : cell.padEnd(widths[index])\n })\n .join(\" \")\n}\n\nfunction text(data, index, cell) {\n if (cell === undefined || cell === null) return \"–\"\n if (typeof cell === \"string\") return cell\n const column = data.columns[index]\n const digits = column.digits ?? (Number.isInteger(cell) ? 0 : 2)\n const [whole, fraction] = Math.abs(cell).toFixed(digits).split(\".\")\n const number = (cell < 0 ? \"-\" : \"\") + whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\") + (fraction ? \".\" + fraction : \"\")\n const unit = column.unit\n if (!unit) return number\n if (/^[$€£¥]$/.test(unit)) return (cell < 0 ? \"-\" : \"\") + unit + number.replace(\"-\", \"\")\n return unit.length > 1 && /^[a-z]/i.test(unit) ? number + \" \" + unit : number + unit\n}\n\nfunction compact(value) {\n return String(Math.round(value * 100) / 100)\n}\n\nfunction ease(p) {\n const clamped = Math.max(0, Math.min(1, p))\n return 1 - Math.pow(1 - clamped, 3)\n}\n", + "source": "// A sortable data table on the native `table` node: clients draw it like their markdown tables (the TUI as aligned\n// 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\n// table's cells hold text, not nodes). With `choose`, a row press selects a row and the Choose button submits it.\n\nconst SPARK = \"▁▂▃▄▅▆▇█\"\n\nfunction init(data) {\n return { sort: null, desc: false, selected: null }\n}\n\nfunction view(state, data) {\n const trend = data.rows.some((row) => row.trend)\n // Row indices in display order; the table's rows are in this order, so a row press maps back through it.\n const shown = order(state, data)\n const picked = state.selected === null ? null : data.rows[state.selected]\n return ui.column({ gap: 1, align: \"stretch\" }, [\n ui.text(data.title, { style: \"title\" }),\n ui.table(\n [\n ...data.columns.map((column, index) => ({\n label: column.label,\n align: numeric(data, index) ? \"end\" : \"start\",\n })),\n ...(trend ? [data.trendLabel ?? \"Trend\"] : []),\n ],\n shown.map((index) => [\n ...data.columns.map((_, column) => text(data, column, data.rows[index].cells[column])),\n ...(trend ? [spark(data.rows[index].trend)] : []),\n ]),\n {\n sort: state.sort === null ? undefined : { column: state.sort, descending: state.desc },\n selected: data.choose && state.selected !== null ? shown.indexOf(state.selected) : undefined,\n // The trend column doesn't sort; numbers sort largest first, text A to Z, a second press the other way.\n onSort: (state, column) =>\n column >= data.columns.length\n ? state\n : state.sort === column\n ? { ...state, desc: !state.desc }\n : { ...state, sort: column, desc: numeric(data, column) },\n onPress: data.choose\n ? (state, row) => ({ ...state, selected: state.selected === shown[row] ? null : shown[row] })\n : undefined,\n },\n ),\n data.choose &&\n ui.row({ gap: 1 }, [\n ui.button(picked ? \"Choose \" + text(data, 0, picked.cells[0]) : \"Choose\", {\n variant: \"primary\",\n disabled: !picked,\n onPress: (state) => choose(state, data),\n }),\n ]),\n ])\n}\n\nfunction choose(state, data) {\n if (state.selected === null) return state\n const row = data.rows[state.selected]\n return submit({\n index: state.selected,\n row: Object.fromEntries(data.columns.map((column, at) => [column.label, row.cells[at] ?? null])),\n })\n}\n\n// A trend as block characters scaled to its own range, lowest ▁ to highest █; no trend is empty.\nfunction spark(values) {\n if (!values || values.length === 0) return \"\"\n const min = Math.min(...values)\n const span = Math.max(...values) - min || 1\n return values.map((value) => SPARK[Math.round(((value - min) / span) * (SPARK.length - 1))]).join(\"\")\n}\n\n// Row indices in display order: stable, numbers by value, text case-insensitively, empty cells last.\nfunction order(state, data) {\n const indices = data.rows.map((_, index) => index)\n if (state.sort === null) return indices\n const key = (index) => {\n const cell = data.rows[index].cells[state.sort]\n return typeof cell === \"string\" ? cell.toLowerCase() : cell\n }\n return indices.sort((a, b) => {\n const left = key(a)\n const right = key(b)\n if (left === right) return a - b\n if (left === undefined || left === null) return 1\n if (right === undefined || right === null) return -1\n return (left < right ? -1 : 1) * (state.desc ? -1 : 1)\n })\n}\n\nfunction numeric(data, column) {\n return data.rows.every((row) => typeof (row.cells[column] ?? 0) === \"number\")\n}\n\nfunction text(data, index, cell) {\n if (cell === undefined || cell === null) return \"–\"\n if (typeof cell === \"string\") return cell\n const column = data.columns[index]\n const digits = column.digits ?? (Number.isInteger(cell) ? 0 : 2)\n const [whole, fraction] = Math.abs(cell).toFixed(digits).split(\".\")\n const number = (cell < 0 ? \"-\" : \"\") + whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\") + (fraction ? \".\" + fraction : \"\")\n const unit = column.unit\n if (!unit) return number\n if (/^[$€£¥]$/.test(unit)) return (cell < 0 ? \"-\" : \"\") + unit + number.replace(\"-\", \"\")\n return unit.length > 1 && /^[a-z]/i.test(unit) ? number + \" \" + unit : number + unit\n}\n", "input": { "phase": "init", "data": { @@ -108,189 +108,61 @@ "text": "Top endpoints" }, { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ + "onSort": "$function", + "onPress": "$function", + "type": "table", + "columns": [ { - "style": "caption", - "tone": "muted", - "type": "text", - "text": "Sort by" - }, - [ - { - "variant": "secondary", - "onPress": "$function", - "type": "button", - "label": "Endpoint" - }, - { - "variant": "secondary", - "onPress": "$function", - "type": "button", - "label": "Requests" - }, - { - "variant": "secondary", - "onPress": "$function", - "type": "button", - "label": "p95" - }, - { - "variant": "secondary", - "onPress": "$function", - "type": "button", - "label": "Errors" - } - ] - ] - }, - { - "key": "header", - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "tone": "muted", - "type": "text", - "text": "Endpoint Requests p95 Errors" + "label": "Endpoint", + "align": "start" }, { - "style": "caption", - "tone": "muted", - "type": "text", - "text": "7d requests" + "label": "Requests", + "align": "end" + }, + { + "label": "p95", + "align": "end" + }, + { + "label": "Errors", + "align": "end" + }, + { + "label": "7d requests" } + ], + "rows": [ + [ + "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%", + "▅▅█▅▁▅▅" + ] ] }, - false, - [ - { - "key": 0, - "selected": false, - "onPress": "$function", - "type": "card", - "children": [ - { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "type": "text", - "text": "GET /users 182,400 120 ms 0.12%" - }, - { - "key": "spark0", - "width": 96, - "height": 22, - "fps": 60, - "duration": 0.6, - "alt": "7d requests: 20, 22, 25, 24, 27, 30, 34", - "type": "canvas" - } - ] - } - ] - }, - { - "key": 1, - "selected": false, - "onPress": "$function", - "type": "card", - "children": [ - { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "type": "text", - "text": "POST /orders 64,200 340 ms 1.40%" - }, - { - "key": "spark1", - "width": 96, - "height": 22, - "fps": 60, - "duration": 0.6, - "alt": "7d requests: 12, 11, 13, 9, 8, 10, 7", - "type": "canvas" - } - ] - } - ] - }, - { - "key": 2, - "selected": false, - "onPress": "$function", - "type": "card", - "children": [ - { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "type": "text", - "text": "GET /search 120,900 210 ms 0.30%" - }, - { - "key": "spark2", - "width": 96, - "height": 22, - "fps": 60, - "duration": 0.6, - "alt": "7d requests: 15, 18, 16, 19, 21, 18, 23", - "type": "canvas" - } - ] - } - ] - }, - { - "key": 3, - "selected": false, - "onPress": "$function", - "type": "card", - "children": [ - { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "type": "text", - "text": "PUT /profile 8,800 95 ms 0.05%" - }, - { - "key": "spark3", - "width": 96, - "height": 22, - "fps": 60, - "duration": 0.6, - "alt": "7d requests: 3, 3, 4, 3, 2, 3, 3", - "type": "canvas" - } - ] - } - ] - } - ], { "gap": 1, "type": "row", @@ -317,178 +189,61 @@ "text": "Top endpoints" }, { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ + "type": "table", + "columns": [ { - "style": "caption", - "tone": "muted", - "type": "text", - "text": "Sort by" - }, - { - "variant": "secondary", - "type": "button", "label": "Endpoint", - "id": "0/1/1.0" + "align": "start" }, { - "variant": "secondary", - "type": "button", "label": "Requests", - "id": "0/1/1.1" + "align": "end" }, { - "variant": "secondary", - "type": "button", "label": "p95", - "id": "0/1/1.2" + "align": "end" }, { - "variant": "secondary", - "type": "button", "label": "Errors", - "id": "0/1/1.3" - } - ] - }, - { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "tone": "muted", - "type": "text", - "text": "Endpoint Requests p95 Errors" + "align": "end" }, { - "style": "caption", - "tone": "muted", - "type": "text", - "text": "7d requests" + "label": "7d requests" } - ] - }, - { - "selected": false, - "type": "card", - "id": "0/:0", - "children": [ - { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "type": "text", - "text": "GET /users 182,400 120 ms 0.12%" - }, - { - "width": 96, - "height": 22, - "fps": 60, - "duration": 0.6, - "alt": "7d requests: 20, 22, 25, 24, 27, 30, 34", - "type": "canvas", - "id": "0/:0/0/:spark0" - } - ] - } - ] - }, - { - "selected": false, - "type": "card", - "id": "0/:1", - "children": [ - { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "type": "text", - "text": "POST /orders 64,200 340 ms 1.40%" - }, - { - "width": 96, - "height": 22, - "fps": 60, - "duration": 0.6, - "alt": "7d requests: 12, 11, 13, 9, 8, 10, 7", - "type": "canvas", - "id": "0/:1/0/:spark1" - } - ] - } - ] - }, - { - "selected": false, - "type": "card", - "id": "0/:2", - "children": [ - { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "type": "text", - "text": "GET /search 120,900 210 ms 0.30%" - }, - { - "width": 96, - "height": 22, - "fps": 60, - "duration": 0.6, - "alt": "7d requests: 15, 18, 16, 19, 21, 18, 23", - "type": "canvas", - "id": "0/:2/0/:spark2" - } - ] - } - ] - }, - { - "selected": false, - "type": "card", - "id": "0/:3", - "children": [ - { - "gap": 1, - "align": "center", - "wrap": true, - "type": "row", - "children": [ - { - "style": "code", - "type": "text", - "text": "PUT /profile 8,800 95 ms 0.05%" - }, - { - "width": 96, - "height": 22, - "fps": 60, - "duration": 0.6, - "alt": "7d requests: 3, 3, 4, 3, 2, 3, 3", - "type": "canvas", - "id": "0/:3/0/:spark3" - } - ] - } - ] + ], + "rows": [ + [ + "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%", + "▅▅█▅▁▅▅" + ] + ], + "id": "0/1", + "selectable": true, + "sortable": true }, { "gap": 1, @@ -499,29 +254,17 @@ "disabled": true, "type": "button", "label": "Choose", - "id": "0/5/0" + "id": "0/2/0" } ] } ] }, "handlers": { - "0/1/1.0": "press", - "0/1/1.1": "press", - "0/1/1.2": "press", - "0/1/1.3": "press", - "0/:0": "press", - "0/:1": "press", - "0/:2": "press", - "0/:3": "press", - "0/5/0": "press" - }, - "canvases": { - "spark0": "0/:0/0/:spark0", - "spark1": "0/:1/0/:spark1", - "spark2": "0/:2/0/:spark2", - "spark3": "0/:3/0/:spark3" + "0/1": "press", + "0/2/0": "press" }, + "canvases": {}, "result": { "state": { "sort": null, diff --git a/packages/widget/test/tree.test.ts b/packages/widget/test/tree.test.ts index 6886b0ff3cd..d971d5a620e 100644 --- a/packages/widget/test/tree.test.ts +++ b/packages/widget/test/tree.test.ts @@ -119,7 +119,8 @@ const data: Record = { } 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]) diff --git a/packages/widget/test/wire.test.ts b/packages/widget/test/wire.test.ts index 0f6cf932cd8..d4e2487fe3e 100644 --- a/packages/widget/test/wire.test.ts +++ b/packages/widget/test/wire.test.ts @@ -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 () => {