feat(widgets): a native table node

ui.table(columns, rows, props) is a header and rows of text: columns with a label and an align (end for numbers),
rows of strings and numbers, an optional sort indicator and selected row. onPress(state, row) takes a row's press and
onSort(state, column) a header's (as change); the host walk sets selectable and sortable. widget-wire writes it as
type 17 with props 39 to 45, and widget-web walks it too. The web host draws an HTML table that scrolls sideways; the
TUI writes aligned text. Clients draw it like their markdown tables.
This commit is contained in:
Sebastian Herrlinger 2026-11-27 13:38:04 +01:00
parent e3fae462d8
commit 256ba026e4
32 changed files with 784 additions and 59 deletions

View file

@ -107,6 +107,10 @@ async function main(data) {
· `carousel({ index, onChange }, children)` · `card({ selected, onPress }, children)` · `button(label, { variant,
disabled, onPress })` · `checkbox(label, checked, { onChange })` · `slider({ label, value, min, max, step, onChange })`
· `select(options, { value, multiple, onChange })` · `input(value, { placeholder, multiline, onChange })` · `divider()`
· `table(columns, rows, { sort, selected, onPress, onSort })`: data as a real table, drawn like the client's markdown
tables; columns are labels or `{ label, align: "end" }` (numbers), rows arrays of strings and numbers (≤ 16 columns,
≤ 500 rows). `onPress(state, row)` on a row; `onSort(state, column)` on a header, and `sort: { column, descending }`
shows the indicator: sort `rows` yourself
· `stack(props, children)`: layers children, the last on top, each placed by its `place` (`top-left` … `bottom-right`,
`center`, `fill`) and `inset`; taps pass through text and images to what's below (a HUD over a canvas)
· `canvas({ height, width, fps, duration, alt, poster, fill, key, onPointer, wgsl, values })`: drawn by `draw` with 2D

View file

@ -323,6 +323,9 @@ function NodeView(props: { item: Item }): JSX.Element {
<Match when={node().type === "divider"}>
<DividerNode />
</Match>
<Match when={node().type === "table"}>
<TableNode item={props.item} />
</Match>
<Match when={node().type === "canvas"}>
<SurfaceNode item={props.item} />
</Match>
@ -805,6 +808,47 @@ function InputNode(props: { item: Item }) {
)
}
// A terminal writes a table as aligned text, a line per row (widgets.md, Table): the header in bold with the sort
// indicator, numbers aligned to the end of their column.
function TableNode(props: { item: Item }) {
const theme = useTheme()
const node = () => props.item.node as Extract<Node, { type: "table" }>
const lines = () => {
const table = node()
const header = table.columns.map((column, index) =>
table.sort?.column === index ? column.label + (table.sort.descending ? " ▼" : " ▲") : column.label,
)
const rows = table.rows.map((row) => table.columns.map((_, index) => String(row[index] ?? "")))
const widths = header.map((label, index) => Math.max(label.length, ...rows.map((row) => row[index]!.length)))
const line = (cells: ReadonlyArray<string>) =>
cells
.map((cell, index) =>
table.columns[index]!.align === "end" ? cell.padStart(widths[index]!) : cell.padEnd(widths[index]!),
)
.join(" ")
.trimEnd()
return { header: line(header), rows: rows.map(line) }
}
return (
<box flexDirection="column" flexShrink={0}>
<text fg={theme.text.base} attributes={TextAttributes.BOLD} wrapMode="none">
{lines().header}
</text>
<For each={lines().rows}>
{(row, index) => (
<text
fg={index() === node().selected ? theme.text.base : theme.markdown.text}
attributes={index() === node().selected ? TextAttributes.BOLD : undefined}
wrapMode="none"
>
{row}
</text>
)}
</For>
</box>
)
}
function DividerNode() {
const theme = useTheme()
return <box height={1} flexShrink={0} border={["top"]} borderStyle="single" borderColor={theme.border.base} />

View file

@ -92,6 +92,21 @@ export interface Input {
export interface Divider {
readonly type: "divider"
}
/** Text in rows and columns with a header (see the spec's Table): 1 to 16 columns, at most 500 rows. */
export interface Table {
readonly type: "table"
readonly id?: string
readonly columns: ReadonlyArray<{ readonly label: string; readonly align?: "start" | "end" }>
/** At most as many cells as columns; a number shows as `String(number)`. */
readonly rows: ReadonlyArray<ReadonlyArray<string | number>>
/** The column whose header shows the sort indicator; the program sorts `rows`. */
readonly sort?: { readonly column: number; readonly descending?: boolean }
readonly selected?: number
/** Set by the prelude when the table has an `onPress` handler: only then do its rows take presses. */
readonly selectable?: true
/** Set by the prelude when the table has an `onSort` handler: only then do its headers take presses. */
readonly sortable?: true
}
/**
* A drawing surface, drawn one of two ways, never both: with 2D commands from the widget template's
* `draw(state, data, frame)`, or, when it has `wgsl`, by that WGSL fragment shader on the GPU (see the spec's Canvas
@ -161,6 +176,7 @@ export type Node = (
| Select
| Input
| Divider
| Table
| Canvas
| Stack
) &
@ -446,6 +462,36 @@ export const Node: Schema.Codec<Node> = Schema.Union([
multiline: optional(Schema.Boolean),
}),
Schema.Struct({ type: Schema.Literal("divider"), ...layer }),
Schema.Struct({
type: Schema.Literal("table"),
...layer,
id: optional(Schema.String),
columns: Schema.Array(
Schema.Struct({ label: Schema.String, align: optional(Schema.Literals(["start", "end"])) }),
).check(Schema.isMinLength(1), Schema.isMaxLength(16)),
rows: Schema.Array(Schema.Array(Schema.Union([Schema.String, Schema.Finite]))).check(Schema.isMaxLength(500)),
sort: optional(Schema.Struct({ column: Schema.Int, descending: optional(Schema.Boolean) })),
selected: optional(Schema.Int),
selectable: optional(Schema.Literal(true)),
sortable: optional(Schema.Literal(true)),
}).check(
Schema.makeFilter(
(table: { readonly columns: ReadonlyArray<unknown>; readonly rows: ReadonlyArray<ReadonlyArray<unknown>> }) =>
table.rows.every((row) => row.length <= table.columns.length) || "a row has more cells than there are columns",
),
Schema.makeFilter(
(table: { readonly columns: ReadonlyArray<unknown>; readonly sort?: { readonly column: number } }) =>
table.sort === undefined ||
(table.sort.column >= 0 && table.sort.column < table.columns.length) ||
"`sort.column` must be one of the columns",
),
Schema.makeFilter(
(table: { readonly rows: ReadonlyArray<unknown>; readonly selected?: number }) =>
table.selected === undefined ||
(table.selected >= 0 && table.selected < table.rows.length) ||
"`selected` must be one of the rows",
),
),
Schema.Struct({
type: Schema.Literal("canvas"),
...layer,
@ -490,6 +536,7 @@ export const types: ReadonlyArray<Node["type"]> = [
"select",
"input",
"divider",
"table",
"canvas",
"stack",
]

View file

@ -693,11 +693,11 @@ const widget = (() => {
// A wheel isn't where the pointer is held: `widget.pointer` keeps the last down, move or up.
if (event.type === "pointer" && event.value?.kind !== "wheel")
api.pointer = __widget_pointer(event.value) ?? api.pointer
const entry = __widget_find(live.root, event.id)
const entry = __widget_find(live.root, event.id, event.type)
if (!entry || entry.event !== event.type) return
const value = __widget_value(entry, event.value)
if (value === undefined) return
if (event.type === "press") call(entry.handler)
if (event.type === "press" && entry.node.type !== "table") call(entry.handler)
else call(entry.handler, value)
}
const accept = (message) => {

View file

@ -11,6 +11,7 @@ const ui = (() => {
const container = (type) => (props, nodes) =>
Array.isArray(props) ? { type, children: props } : { ...props, type, children: nodes ?? [] }
const option = (item) => (typeof item === "string" ? { value: item, label: item } : item)
const column = (item) => (typeof item === "string" ? { label: item } : item)
return {
column: container("column"),
row: container("row"),
@ -31,6 +32,12 @@ const ui = (() => {
select: (options, props) => ({ ...props, type: "select", options: (options ?? []).map(option) }),
input: (value, props) => ({ ...props, type: "input", value: value ?? "" }),
divider: () => ({ type: "divider" }),
table: (columns, rows, props) => ({
...props,
type: "table",
columns: (columns ?? []).map(column),
rows: rows ?? [],
}),
canvas: (props) => ({ ...props, type: "canvas" }),
draw: () => new __WidgetDraw(),
}
@ -46,6 +53,11 @@ const __WIDGET_CONTROLS = {
input: { event: "change", handler: "onChange" },
carousel: { event: "change", handler: "onChange" },
canvas: { event: "pointer", handler: "onPointer" },
// A table takes two: a row's press, and a header's press as `change`.
table: [
{ event: "press", handler: "onPress" },
{ event: "change", handler: "onSort" },
],
}
// A view nests at most 100 levels (specs/v2/widgets.md, Keys and depth): the root is level 1, the items of a node's
@ -73,17 +85,18 @@ function __widget_deep(list, level) {
// The handler of the node with id `id` in the view `root` as built, found by following the id's path (the host assigns
// the ids, specs/v2/widgets.md, Native hosts). Where two siblings share a segment (a key that looks like a repeat,
// `k~2`), the later one's subtree wins.
function __widget_find(root, id) {
function __widget_find(root, id, type) {
if (!root || typeof root !== "object" || Array.isArray(root)) return undefined
const segments = String(id).split("/")
const named = root.key !== undefined && root.key !== null
if (segments[0] !== (named ? ":" + encodeURIComponent(String(root.key)) : "0")) return undefined
return __widget_found(root, segments, 1)
return __widget_found(root, segments, 1, type)
}
function __widget_found(node, segments, at) {
function __widget_found(node, segments, at, type) {
if (at === segments.length) {
const control = __WIDGET_CONTROLS[node.type]
const controls = __WIDGET_CONTROLS[node.type]
const control = Array.isArray(controls) ? controls.find((each) => each.event === type) : controls
const handler = control ? node[control.handler] : undefined
if (typeof handler !== "function") return undefined
if (node.type !== "carousel" || node.children === undefined) return { event: control.event, handler, node }
@ -98,7 +111,7 @@ function __widget_found(node, segments, at) {
const matches = []
__widget_segments(__widget_list(node.children), "", segments[at], matches, null)
for (let index = matches.length - 1; index >= 0; index--) {
const found = __widget_found(matches[index], segments, at + 1)
const found = __widget_found(matches[index], segments, at + 1, type)
if (found) return found
}
return undefined
@ -142,6 +155,10 @@ function __widget_segments(list, prefix, segment, into, seen) {
// The value a handler gets for a client event, checked against the node; undefined drops the event.
function __widget_value(entry, value) {
const node = entry.node
if (node.type === "table") {
const count = (entry.event === "press" ? node.rows : node.columns)?.length ?? 0
return Number.isInteger(value) && value >= 0 && value < count ? value : undefined
}
if (entry.event === "press") return true
if (entry.event === "pointer") return __widget_pointer(value)
if (node.type === "checkbox") return typeof value === "boolean" ? value : undefined
@ -355,9 +372,9 @@ function __widget_dispatch(state, event, data) {
if (event.type === "capture")
return typeof onCapture === "function" ? onCapture(state, event.value === true) : undefined
if (event.type !== "press" && event.type !== "change" && event.type !== "pointer") return undefined
const entry = __widget_find(view(state, data), event.id)
const entry = __widget_find(view(state, data), event.id, event.type)
if (!entry || entry.event !== event.type) return undefined
const value = __widget_value(entry, event.value)
if (value === undefined) return undefined
return event.type === "press" ? entry.handler(state) : entry.handler(state, value)
return event.type === "press" && entry.node.type !== "table" ? entry.handler(state) : entry.handler(state, value)
}

File diff suppressed because one or more lines are too long

View file

@ -4,7 +4,10 @@ import { Host } from "psychoscript"
// program built it, which crossed under `translate: { functions: "mark" }` with `Host.functionMarker` where each
// function was.
const CONTROLS: Record<string, { readonly handler: string; readonly always?: boolean; readonly keyed?: boolean }> = {
const CONTROLS: Record<
string,
{ readonly handler: string; readonly sort?: string; readonly always?: boolean; readonly keyed?: boolean }
> = {
button: { handler: "onPress", always: true },
card: { handler: "onPress" },
checkbox: { handler: "onChange", always: true },
@ -13,9 +16,12 @@ const CONTROLS: Record<string, { readonly handler: string; readonly always?: boo
input: { handler: "onChange", always: true },
carousel: { handler: "onChange" },
canvas: { handler: "onPointer", keyed: true },
table: { handler: "onPress", sort: "onSort" },
}
const HANDLERS = new Set(["onPress", "onChange", "onPointer"])
const HANDLERS = new Set(["onPress", "onChange", "onPointer", "onSort"])
// Props the host sets from the handlers, never the program's.
const SET = new Set(["key", "id", "pointer", "selectable", "sortable"])
/** The most levels a view nests (specs/v2/widgets.md, Keys and depth), and the failures of a view that breaks the rules. */
export const LEVELS = 100
@ -115,17 +121,20 @@ export function tree(root: unknown, label: string): Tree {
for (const name in value) {
if (name === "children" || HANDLERS.has(name)) continue
const item = clean(value[name], label, true)
if (item !== omitted && name !== "key" && name !== "id" && name !== "pointer") out[name] = item
if (item !== omitted && !SET.has(name)) out[name] = item
}
const control =
typeof value.type === "string" && Object.hasOwn(CONTROLS, value.type) ? CONTROLS[value.type] : undefined
if (control) {
const handled = value[control.handler] === marker
const sorted = control.sort !== undefined && value[control.sort] === marker
const canvas = control.keyed === true && keyed
if (handled || control.always || canvas) {
if (handled || sorted || control.always || canvas) {
out.id = path
if (handled) handlers.add(path)
if (handled || sorted) handlers.add(path)
if (value.type === "canvas" && handled) out.pointer = true
if (value.type === "table" && handled) out.selectable = true
if (sorted) out.sortable = true
if (canvas && !canvases.has(String(value.key)))
canvases.set(String(value.key), { id: path, wgsl: typeof value.wgsl === "string", gpu: value.gpu === true })
}

View file

@ -192,4 +192,14 @@ export const cases: ReadonlyArray<{
`ui.column({ gap: 1 }, [ui.row({ wrap: true, gap: 1 }, Array.from({ length: 200 }, (_, i) => ui.card({ selected: i === 3, onPress: (s) => s }, [ui.row({ gap: 1 }, [ui.text("Item " + i, { style: "body" }), ui.text(String(i * 7), { tone: "muted" })]), ui.text("Note " + i, { style: "caption" }), ui.button("Go", { onPress: (s) => s })])))])`,
),
},
{
// Tables: rows and a header that take presses (selectable, sortable, in that order, after the id), one that takes
// only header presses, and one with no handlers (no id). Numbers stay numbers in the view. Protocol 1's prelude
// doesn't know tables or onSort.
name: "tables",
source: view(
`ui.column([ui.table(["Day", { label: "kg", align: "end" }, { label: "kcal", align: "end" }], [["Nov 27", 79.6, 1150], ["Nov 26", 80.1]], { sort: { column: 0, descending: true }, selected: 0, onPress: (s, row) => s, onSort: (s, column) => s }), ui.table(["a"], [["x"]], { key: "sorted", onSort: (s) => s }), ui.table([{ label: "n", align: "end" }], [[1e21], [0.1]])])`,
),
newer: true,
},
]

View file

@ -17,6 +17,6 @@
},
"error": {
"view": false,
"message": "TypeError: Argument 1 to __widget_emit contains a function, which cannot be passed to the host. (line 335, col 5)"
"message": "TypeError: Argument 1 to __widget_emit contains a function, which cannot be passed to the host. (line 352, col 5)"
}
}

View file

@ -12,6 +12,6 @@
},
"error": {
"view": false,
"message": "TypeError: Argument 1 to __widget_emit contains a function, which cannot be passed to the host. (line 335, col 5)"
"message": "TypeError: Argument 1 to __widget_emit contains a function, which cannot be passed to the host. (line 352, col 5)"
}
}

View file

@ -17,6 +17,6 @@
},
"error": {
"view": false,
"message": "TypeError: Argument 1 to __widget_emit contains a function, which cannot be passed to the host. (line 335, col 5)"
"message": "TypeError: Argument 1 to __widget_emit contains a function, which cannot be passed to the host. (line 352, col 5)"
}
}

View file

@ -17,6 +17,6 @@
},
"error": {
"view": false,
"message": "TypeError: Argument 1 to __widget_emit contains a function, which cannot be passed to the host. (line 335, col 5)"
"message": "TypeError: Argument 1 to __widget_emit contains a function, which cannot be passed to the host. (line 352, col 5)"
}
}

View file

@ -0,0 +1,159 @@
{
"name": "tables",
"source": "function view(state, data) {\n return ui.column([ui.table([\"Day\", { label: \"kg\", align: \"end\" }, { label: \"kcal\", align: \"end\" }], [[\"Nov 27\", 79.6, 1150], [\"Nov 26\", 80.1]], { sort: { column: 0, descending: true }, selected: 0, onPress: (s, row) => s, onSort: (s, column) => s }), ui.table([\"a\"], [[\"x\"]], { key: \"sorted\", onSort: (s) => s }), ui.table([{ label: \"n\", align: \"end\" }], [[1e21], [0.1]])])\n}",
"input": {
"phase": "init",
"data": null
},
"built": {
"type": "column",
"children": [
{
"sort": {
"column": 0,
"descending": true
},
"selected": 0,
"onPress": "$function",
"onSort": "$function",
"type": "table",
"columns": [
{
"label": "Day"
},
{
"label": "kg",
"align": "end"
},
{
"label": "kcal",
"align": "end"
}
],
"rows": [
[
"Nov 27",
79.6,
1150
],
[
"Nov 26",
80.1
]
]
},
{
"key": "sorted",
"onSort": "$function",
"type": "table",
"columns": [
{
"label": "a"
}
],
"rows": [
[
"x"
]
]
},
{
"type": "table",
"columns": [
{
"label": "n",
"align": "end"
}
],
"rows": [
[
1e+21
],
[
0.1
]
]
}
]
},
"view": {
"type": "column",
"children": [
{
"sort": {
"column": 0,
"descending": true
},
"selected": 0,
"type": "table",
"columns": [
{
"label": "Day"
},
{
"label": "kg",
"align": "end"
},
{
"label": "kcal",
"align": "end"
}
],
"rows": [
[
"Nov 27",
79.6,
1150
],
[
"Nov 26",
80.1
]
],
"id": "0/0",
"selectable": true,
"sortable": true
},
{
"type": "table",
"columns": [
{
"label": "a"
}
],
"rows": [
[
"x"
]
],
"id": "0/:sorted",
"sortable": true
},
{
"type": "table",
"columns": [
{
"label": "n",
"align": "end"
}
],
"rows": [
[
1e+21
],
[
0.1
]
]
}
]
},
"handlers": {
"0/0": "press",
"0/:sorted": "change"
},
"canvases": {},
"result": {
"state": {}
}
}

View file

@ -0,0 +1,79 @@
import { expect, test } from "bun:test"
import { LiveWidget, ManualClock, program, step, type StepError } from "../src/index.js"
import { LIVE, STEP } from "./limits.js"
// A table's two events (specs/v2/widgets.md, Events): a row's press with its index to onPress, a header's press as
// `change` with the column's index to onSort; anything outside the rows or columns changes nothing.
const source = `
function init() { return { row: null, column: null } }
function view(state) {
return ui.column([
ui.text(state.row + " " + state.column),
ui.table(["a", { label: "b", align: "end" }], [["x", 1], ["y", 2], ["z", 3]], {
onPress: (state, row) => ({ ...state, row }),
onSort: (state, column) => ({ ...state, column }),
}),
])
}`
const text = (output: { readonly view: unknown }) => {
const view = output.view as { children: { text?: string; id?: string }[] }
return view.children[0]!.text
}
test("a step routes a row's press to onPress and a header's press to onSort, with checked indices", async () => {
const init = await step(program(source), { phase: "init", data: null }, STEP)
const id = (init.view as unknown as { children: { id?: string }[] }).children[1]!.id!
const event = async (state: unknown, type: "press" | "change", value: unknown) =>
text(await step(program(source), { phase: "event", data: null, state, event: { id, type, value } }, STEP))
expect(await event(init.state, "press", 2)).toBe("2 null")
expect(await event({ row: 2, column: null }, "change", 1)).toBe("2 1")
for (const value of [3, -1, 1.5, "1", null]) expect(await event(init.state, "press", value)).toBe("null null")
expect(await event(init.state, "change", 2)).toBe("null null")
})
test("a live table's handlers get only the index", async () => {
const widget = LiveWidget.start(
program(
`async function main() {
const show = (picked) => widget.render(ui.column([ui.text(picked), ui.table(["a", "b"], [["x", 1], ["y", 2]], {
onPress: (row) => show("row " + row),
onSort: (column) => show("column " + column),
})]))
show("none")
}`,
"live",
),
{},
{ clock: new ManualClock(), ...LIVE },
)
const shown = (expected: string) =>
widget.when((current) => {
const view = current.view as { children?: { text?: string }[] } | undefined
return view?.children?.[0]?.text === expected
})
await shown("none")
const id = (widget.view as unknown as { children: { id?: string; selectable?: true; sortable?: true }[] })
.children[1]!
expect([id.selectable, id.sortable]).toEqual([true, true])
widget.event({ id: id.id!, type: "press", value: 1 })
await shown("row 1")
widget.event({ id: id.id!, type: "change", value: 0 })
await shown("column 0")
await widget.stop()
})
test("a table with a row wider than its columns, or a sort or selection outside them, is an invalid view", async () => {
const invalid = async (props: string, rows = `[["x"]]`) => {
const failed = (await step(
program(`function view() {\n return ui.table(["a"], ${rows}, ${props})\n}`),
{ phase: "init", data: null },
STEP,
).catch((error: unknown) => error)) as StepError
return failed.message
}
expect(await invalid("{}", `[["x", "y"]]`)).toContain("a row has more cells than there are columns")
expect(await invalid("{ sort: { column: 1 } }")).toContain("`sort.column` must be one of the columns")
expect(await invalid("{ selected: 1 }")).toContain("`selected` must be one of the rows")
expect(await invalid("{}", `[[{ a: 1 }]]`)).toBeDefined()
})

View file

@ -124,7 +124,8 @@ for (const file of files) {
test(`wire fixture ${file}, handlers by path`, async () => {
const fixture = await Bun.file(path.join(dir, file)).json()
if (fixture.error || fixture.input.phase !== "init") return
// Protocol 1's prelude has no handlers for what it doesn't know (a table's).
if (fixture.error || fixture.input.phase !== "init" || newer.has(file.replace(/\.json$/, ""))) return
const checked = await handlers(fixture.source, fixture.input)
for (const [id, table, found] of checked) expect({ id, found }).toEqual({ id, found: table })
expect(checked.filter(([, table]) => table !== null).length).toBe(Object.keys(fixture.handlers).length)

View file

@ -29,7 +29,7 @@ cargo test --locked --workspace # on a Mac: --fe
The shorthand's tests (`widget-wire/tests/shorthand.rs`) run on Vulkan (lavapipe on a machine without a GPU, or a real
one), or on Metal with `--features widget-wire/metal`. widget-wire's tests read `packages/widget/test/fixtures/wire`
(the 58 native-host fixtures) and `draw.json` in place; widget-mobile's are in its `README.md`, Tests.
(the 59 native-host fixtures) and `draw.json` in place; widget-mobile's are in its `README.md`, Tests.
The apps' libraries are built by `crates/widget-mobile/scripts/build-ios.sh` and `build-android.sh`
(`crates/widget-mobile/README.md`, Building).

View file

@ -762,7 +762,7 @@ fn native_steps_give_the_conformance_fixtures() {
"{name}"
);
}
assert_eq!(n, 58);
assert_eq!(n, 59);
}
/// A fixture's JSON, read without serde_json's recursion limit: views nest up to 150 levels (`depth-150`).

View file

@ -54,7 +54,7 @@ error raised in the preludes, a batch's `at` and an invalid draw are then at the
89 shared cases of `packages/widget/test/fixtures/draw.json`). A key that isn't a string, number or boolean, or a view over 100 levels, fails with type `view` (a step
once it has run; a live run at once); a function anywhere but a node's handler props, in any host call's argument,
throws the runtime's `TypeError` `Argument <n> to <name> contains a function, which cannot be passed to the host.`,
located at the call (`HostError::located`, sync and async calls alike), as the host's other errors are. `tests/tree.rs` runs the 58 conformance fixtures (`packages/widget/test/fixtures/wire`). The tests read the fixtures
located at the call (`HostError::located`, sync and async calls alike), as the host's other errors are. `tests/tree.rs` runs the 59 conformance fixtures (`packages/widget/test/fixtures/wire`). The tests read the fixtures
and preludes in place from `packages/widget`.
A live run has `__host.post/receive/sleep/now/fetch` as in `psychoscript-mobile` (and `widgets-live.md`), but nothing

View file

@ -77,11 +77,13 @@ fn control(kind: &str) -> Option<(&'static str, &'static str, bool, bool)> {
"input" => ("onChange", "change", true, false),
"carousel" => ("onChange", "change", false, false),
"canvas" => ("onPointer", "pointer", false, true),
// A table's rows; its headers' handler is `onSort` (`change`).
"table" => ("onPress", "press", false, false),
_ => return None,
})
}
const HANDLERS: [&str; 3] = ["onPress", "onChange", "onPointer"];
const HANDLERS: [&str; 4] = ["onPress", "onChange", "onPointer", "onSort"];
/// What the walk learned of a view besides its JSON.
#[derive(Debug, Default)]
@ -166,7 +168,7 @@ impl Walk {
match name {
Some("type") if prop.kind() == Kind::String => {
if let Text::Str(s) = prop.text() {
kind = control(s).map(|c| (s == "canvas", c));
kind = control(s).map(|c| (s == "canvas", s == "table", c));
}
}
Some("children") => {
@ -174,7 +176,7 @@ impl Walk {
continue;
}
Some(n) if HANDLERS.contains(&n) => continue,
Some("key" | "id" | "pointer") => {
Some("key" | "id" | "pointer" | "selectable" | "sortable") => {
if carries_function(prop) {
return Err(WalkError::Function);
}
@ -195,15 +197,16 @@ impl Walk {
out.push(':');
write_json(prop, out)?;
}
if let Some((canvas, (handler, event, always, by_key))) = kind {
if let Some((canvas, table, (handler, event, always, by_key))) = kind {
let handled = v.get(handler).is_some_and(|h| h.kind() == Kind::Function);
let sorted = table && v.get("onSort").is_some_and(|h| h.kind() == Kind::Function);
let key = if by_key {
v.get("key")
.filter(|k| !matches!(k.kind(), Kind::Undefined | Kind::Null))
} else {
None
};
if handled || always || key.is_some() {
if handled || sorted || always || key.is_some() {
if !first {
out.push(',');
}
@ -212,15 +215,22 @@ impl Walk {
out.push_str("\"id\":\"");
out.push_str(&self.path);
out.push('"');
if handled {
if handled || sorted {
self.tree.has_handlers = true;
if let Some(list) = &mut self.tree.handlers {
list.push((self.path.clone(), event));
}
if canvas {
out.push_str(",\"pointer\":true");
// A table with both handlers is listed by its row press.
list.push((self.path.clone(), if handled { event } else { "change" }));
}
}
if handled && canvas {
out.push_str(",\"pointer\":true");
}
if handled && table {
out.push_str(",\"selectable\":true");
}
if sorted {
out.push_str(",\"sortable\":true");
}
if let Some(key) = key {
let name = string_of(key);
if !self.tree.canvases.contains_key(&name) {

View file

@ -169,7 +169,7 @@ fn fixtures() -> Vec<Fixture> {
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
assert_eq!(out.len(), 58);
assert_eq!(out.len(), 59);
out
}
@ -240,7 +240,7 @@ fn every_fixture_walks_from_its_built_view() {
}
walked += 1;
}
assert_eq!(walked, 57);
assert_eq!(walked, 58);
}
/// Each fixture's program run natively on its input with real function markers: the view `__widget_emit` gets is
@ -330,7 +330,7 @@ fn every_fixture_runs_natively_to_its_view_result_or_error() {
}
count += 1;
}
assert_eq!(count, 58);
assert_eq!(count, 59);
}
/// The walk counts levels itself, for views the boundary lets through (its default depth stops them at 16 levels).

View file

@ -11,8 +11,8 @@ use crate::draw::{
};
use crate::gpu::{self, Batch};
use crate::node::{
Align, ButtonVariant, Inset, Layer, Layers, Node, Place, SelectOption, SelectValue, TextStyle,
Tone,
Align, ButtonVariant, Cell, ColumnAlign, Inset, Layer, Layers, Node, Place, SelectOption,
SelectValue, TableColumn, TableSort, TextStyle, Tone,
};
use crate::schema::*;
use crate::step::{SendMessage, StepOutput};
@ -391,6 +391,13 @@ struct Props {
gpu: bool,
place: Option<u32>,
inset: Option<Inset>,
columns: Option<Vec<String>>,
aligns: Vec<f64>,
cells: Option<Vec<String>>,
sort: Option<Vec<f64>>,
row: Option<u32>,
selectable: bool,
sortable: bool,
}
fn read_prop(s: &mut Streams, p: &mut Props, tag: u32) -> Result<(), Malformed> {
@ -435,6 +442,13 @@ fn read_prop(s: &mut Streams, p: &mut Props, tag: u32) -> Result<(), Malformed>
(34, K_STR) => p.capture = Some(s.str()?),
(35, K_INT) => p.pointer = b(s)?,
(38, K_INT) => p.gpu = b(s)?,
(39, K_STRS) => p.columns = Some(s.strs()?),
(40, K_F64S) => p.aligns = s.f64s()?,
(41, K_STRS) => p.cells = Some(s.strs()?),
(42, K_F64S) => p.sort = Some(s.f64s()?),
(43, K_INT) => p.row = Some(s.ints.int()?),
(44, K_INT) => p.selectable = b(s)?,
(45, K_INT) => p.sortable = b(s)?,
(36, K_INT) => p.place = Some(s.ints.int()?),
(37, K_F64) => {
let v = s.floats.f64()?;
@ -502,7 +516,7 @@ fn node(s: &mut Streams) -> Result<(Node, Layer), DecodeError> {
s.strs.str()?;
(Node::Unknown, Layer::default())
} else {
if !matches!(t, 1..=14 | T_STACK) {
if !matches!(t, 1..=14 | T_STACK | T_TABLE) {
return Err(Malformed(format!("unknown node type {t}")).into());
}
// The node without its children; its failure waits for the children's reading, which may find the bytes
@ -715,6 +729,48 @@ fn shell(t: u32, mut p: Props) -> Result<(Node, Layer), DecodeError> {
multiline: p.multiline,
},
13 => Node::Divider,
17 => {
let labels = need(p.columns.take(), "columns")?;
let cells = need(p.cells.take(), "rows")?;
if labels.is_empty() || cells.len() % labels.len() != 0 {
return invalid("a table's cells don't fill its rows");
}
let columns = labels
.into_iter()
.enumerate()
.map(|(i, label)| TableColumn {
label,
align: if p.aligns.get(i) == Some(&1.0) {
ColumnAlign::End
} else {
ColumnAlign::Start
},
})
.collect::<Vec<_>>();
let rows = cells
.chunks(columns.len())
.map(|row| row.iter().cloned().map(Cell).collect())
.collect();
let sort = match p.sort.as_deref() {
None => None,
Some([column, descending]) if column.fract() == 0.0 && *column >= 0.0 => {
Some(TableSort {
column: *column as usize,
descending: *descending == 1.0,
})
}
Some(_) => return invalid("a table's sort is a column and a direction"),
};
Node::Table {
id: p.id,
columns,
rows,
sort,
selected: p.row.map(|r| r as usize),
selectable: p.selectable,
sortable: p.sortable,
}
}
14 => Node::Canvas {
id: p.id,
height: need(p.height, "height")?,

View file

@ -959,6 +959,87 @@ fn option(o: &Option<HostValue>) -> Option<SelectOption<'_>> {
}
/// One prop, when the format knows its key and its value has a shape the prop takes; otherwise it's left out.
/// A table's `columns` (props 39 and 40), `rows` (41, as many cells per row as there are columns), `sort` (42) and a
/// number `selected` (43) (`widgets-binary.md`), written from the whole node, since a row is as wide as `columns`.
/// `columns` or `rows` that aren't lists of the right things are left out, and the client takes the view as invalid.
pub(crate) fn table_props(s: &mut Streams, v: &HostValue) {
let Some(HostValue::Array(columns)) = field(v, "columns") else {
return;
};
let Some(labels) = columns
.iter()
.map(|c| match c.as_ref().and_then(|c| field(c, "label")) {
Some(HostValue::String(t)) => Some(lossy(t)),
_ => None,
})
.collect::<Option<Vec<_>>>()
else {
return;
};
s.tag(39, K_STRS);
s.int(labels.len() as u32);
for label in &labels {
s.str(label);
}
s.tag(40, K_F64S);
s.int(columns.len() as u32);
for c in columns.iter().flatten() {
let end =
matches!(field(c, "align"), Some(HostValue::String(a)) if a.as_str() == Some("end"));
s.f64(if end { 1.0 } else { 0.0 });
}
fn cell(c: Option<&HostValue>) -> Option<Cow<'_, str>> {
match c {
None | Some(HostValue::Undefined) => Some(Cow::Borrowed("")),
Some(HostValue::String(t)) => Some(lossy(t)),
Some(HostValue::Number(n)) if n.is_finite() => {
Some(Cow::Owned(crate::native::js_number(*n)))
}
_ => None,
}
}
let rows = match field(v, "rows") {
Some(HostValue::Array(rows)) => rows
.iter()
.map(|row| match row {
Some(HostValue::Array(cells)) if cells.len() <= labels.len() => (0..labels.len())
.map(|i| cell(cells.get(i).and_then(Option::as_ref)))
.collect::<Option<Vec<_>>>(),
_ => None,
})
.collect::<Option<Vec<_>>>(),
_ => None,
};
if let Some(rows) = rows {
s.tag(41, K_STRS);
s.int((rows.len() * labels.len()) as u32);
for c in rows.iter().flatten() {
s.str(c);
}
}
if let Some(sort) = field(v, "sort")
&& let Some(column) = field(sort, "column").and_then(finite)
{
s.tag(42, K_F64S);
s.int(2);
s.f64(column);
s.f64(
if matches!(field(sort, "descending"), Some(HostValue::Bool(true))) {
1.0
} else {
0.0
},
);
}
if let Some(row) = field(v, "selected")
.and_then(finite)
.filter(|r| *r >= 0.0 && r.fract() == 0.0)
{
s.tag(43, K_INT);
s.int(row as u32);
}
}
pub(crate) fn prop(s: &mut Streams, key: &str, v: &HostValue) {
let id = prop_id(key);
if id == 0 {
@ -1083,6 +1164,10 @@ pub(crate) fn write_node(s: &mut Streams, v: &HostValue, depth: usize) -> Result
return Ok(());
}
let mut kids: &[Option<HostValue>] = &[];
// A table's columns and rows first, as the native walk writes them.
if t == T_TABLE {
table_props(s, v);
}
for (k, v) in fields {
let Some(k) = k.as_str() else { continue };
match k {

View file

@ -10,7 +10,7 @@ use std::fmt::Write as _;
use psychoscript::HostValue;
use crate::encode::{Streams, field, json_value, prop, write_node};
use crate::schema::{K_INT, K_STR, T_UNKNOWN, is_container, type_id};
use crate::schema::{K_INT, K_STR, T_TABLE, T_UNKNOWN, is_container, type_id};
/// The most levels a view nests (`widgets.md`, Keys and depth).
pub const LEVELS: usize = 100;
@ -51,6 +51,8 @@ pub(crate) enum Stop {
struct Control {
handler: &'static str,
event: &'static str,
/// A table's second handler, a header's press (`change`).
sort: Option<&'static str>,
always: bool,
canvas: bool,
}
@ -62,18 +64,20 @@ fn control(ty: &str) -> Option<Control> {
"checkbox" | "slider" | "select" | "input" => ("onChange", "change", true, false),
"carousel" => ("onChange", "change", false, false),
"canvas" => ("onPointer", "pointer", false, true),
"table" => ("onPress", "press", false, false),
_ => return None,
};
Some(Control {
handler,
event,
sort: (ty == "table").then_some("onSort"),
always,
canvas,
})
}
fn handler_prop(k: &str) -> bool {
matches!(k, "onPress" | "onChange" | "onPointer")
matches!(k, "onPress" | "onChange" | "onPointer" | "onSort")
}
/// Whether `v` holds a function marker anywhere.
@ -267,6 +271,12 @@ impl Walk {
Some(s) if t != T_UNKNOWN => Some(s),
_ => None,
};
// A table's columns and rows first (`encode::table_props`).
if t == T_TABLE
&& let Some(st) = props.as_deref_mut()
{
crate::encode::table_props(st, &json_value(v));
}
for (k, pv) in fields {
let Some(k) = k.as_str() else {
if marked(pv) {
@ -281,15 +291,21 @@ impl Walk {
return Err(Stop::Function);
}
if let Some(st) = props.as_deref_mut()
&& !matches!(k, "type" | "key" | "id" | "pointer")
&& !matches!(
k,
"type" | "key" | "id" | "pointer" | "selectable" | "sortable"
)
{
prop(st, k, &json_value(pv));
}
}
if let Some(c) = control(&name) {
let handled = matches!(field(v, c.handler), Some(HostValue::FunctionMarker));
let sorted = c
.sort
.is_some_and(|k| matches!(field(v, k), Some(HostValue::FunctionMarker)));
let keyed = if c.canvas { key(v)? } else { None };
if handled || c.always || keyed.is_some() {
if handled || sorted || c.always || keyed.is_some() {
if let Some(st) = props.as_deref_mut() {
st.tag(10, K_STR);
st.str(&self.path);
@ -297,9 +313,20 @@ impl Walk {
st.tag(35, K_INT);
st.int(1);
}
if t == T_TABLE && handled {
st.tag(44, K_INT);
st.int(1);
}
if sorted {
st.tag(45, K_INT);
st.int(1);
}
}
if handled {
self.found.handlers.push((self.path.clone(), c.event));
// A table with both handlers is listed by its row press.
if handled || sorted {
self.found
.handlers
.push((self.path.clone(), if handled { c.event } else { "change" }));
}
if let Some(k) = keyed {
let k = key_string(k);

View file

@ -55,6 +55,53 @@ pub enum ButtonVariant {
Secondary,
}
/// Where a table column's cells sit.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ColumnAlign {
End,
#[default]
#[serde(other)]
Start,
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct TableColumn {
pub label: String,
#[serde(default)]
pub align: ColumnAlign,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
pub struct TableSort {
pub column: usize,
#[serde(default)]
pub descending: bool,
}
/// A table cell as it shows: a string, or a number as `String(number)`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cell(pub String);
impl<'de> Deserialize<'de> for Cell {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Cell, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Raw {
Text(String),
Number(f64),
}
Ok(Cell(match Raw::deserialize(d)? {
Raw::Text(t) => t,
Raw::Number(n) => crate::native::js_number(n),
}))
}
}
/// A table's limits (`widgets.md`, Table).
pub const MAX_COLUMNS: usize = 16;
pub const MAX_ROWS: usize = 500;
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct SelectOption {
pub value: String,
@ -187,6 +234,21 @@ pub enum Node {
multiline: bool,
},
Divider,
/// Rows of text under a header (`widgets.md`, Table). Decoded, every row is as wide as `columns`.
Table {
#[serde(default)]
id: Option<String>,
columns: Vec<TableColumn>,
rows: Vec<Vec<Cell>>,
#[serde(default)]
sort: Option<TableSort>,
#[serde(default)]
selected: Option<usize>,
#[serde(default)]
selectable: bool,
#[serde(default)]
sortable: bool,
},
Canvas {
#[serde(default)]
id: Option<String>,
@ -260,6 +322,31 @@ impl Node {
pub(crate) fn check(&self) -> Result<(), String> {
let mut bad = None;
self.walk(&mut |n| {
if let Node::Table {
columns,
rows,
sort,
selected,
..
} = n
{
let why = if columns.is_empty() || columns.len() > MAX_COLUMNS {
Some(format!("a table has 1 to {MAX_COLUMNS} columns"))
} else if rows.len() > MAX_ROWS {
Some(format!("a table has at most {MAX_ROWS} rows"))
} else if rows.iter().any(|r| r.len() > columns.len()) {
Some("a row has more cells than there are columns".to_owned())
} else if sort.is_some_and(|s| s.column >= columns.len()) {
Some("`sort.column` must be one of the columns".to_owned())
} else if selected.is_some_and(|r| r >= rows.len()) {
Some("`selected` must be one of the rows".to_owned())
} else {
None
};
if let Some(why) = why {
bad.get_or_insert(why);
}
}
if let Node::Canvas {
wgsl, values, gpu, ..
} = n

View file

@ -11,6 +11,7 @@ pub(crate) const K_OPTS: u32 = 5;
/// A node type the host doesn't know; its name follows in the string stream.
pub(crate) const T_UNKNOWN: u32 = 63;
pub(crate) const T_STACK: u32 = 16;
pub(crate) const T_TABLE: u32 = 17;
/// Top-level message kinds, after the version byte.
pub(crate) const STEP: u8 = b'S';
@ -43,6 +44,7 @@ pub(crate) fn type_id(name: &str) -> u32 {
"divider" => 13,
"canvas" => 14,
"stack" => T_STACK,
"table" => T_TABLE,
_ => T_UNKNOWN,
}
}
@ -91,6 +93,10 @@ pub(crate) fn prop_id(key: &str) -> u32 {
"place" => 36,
"inset" => 37,
"gpu" => 38,
// A table's `columns`, `rows`, `sort` and row `selected` (39 to 43) are written from the whole node
// (`encode::table_props`).
"selectable" => 44,
"sortable" => 45,
_ => 0,
}
}
@ -135,7 +141,7 @@ pub(crate) fn shape(id: u32) -> Shape {
6 => Shape::Enum(TONE),
14 => Shape::Enum(VARIANT),
36 => Shape::Enum(PLACE),
3 | 12 | 15 | 16 | 22 | 24 | 32 | 33 | 35 | 38 => Shape::Bool,
3 | 12 | 15 | 16 | 22 | 24 | 32 | 33 | 35 | 38 | 44 | 45 => Shape::Bool,
4 | 7 | 8 | 10 | 13 | 23 | 29 | 31 | 34 => Shape::Str,
17 => Shape::Value,
21 => Shape::Options,

View file

@ -37,7 +37,7 @@ fn fixtures() -> Vec<(String, Value)> {
})
.collect();
list.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(list.len(), 58);
assert_eq!(list.len(), 59);
list
}
@ -107,7 +107,7 @@ fn steps_encode_the_fixtures() {
}
checked += 1;
}
assert_eq!(checked, 57);
assert_eq!(checked, 58);
}
#[test]

View file

@ -301,6 +301,7 @@ fn every_post_kind_decodes_as_its_json() {
return [
{{ type: "render", node: {EVERY_NODE}.view }},
{{ type: "render", node: {{ type: "text", text: "small" }} }},
{{ type: "render", node: {{ type: "table", columns: [{{ label: "Day" }}, {{ label: "kg", align: "end" }}], rows: [["Nov 27", 79.6], ["Nov 26", 1e21]], sort: {{ column: 1, descending: true }}, selected: 1, id: "0/:t", selectable: true, sortable: true }} }},
{{ type: "draw", id: "0/:chart", commands: {EVERY_COMMAND} }},
{{ type: "draw", id: "", commands: [] }},
{{ type: "frame" }},
@ -327,11 +328,11 @@ fn every_post_kind_decodes_as_its_json() {
}})
}})()"##
));
assert_eq!(pairs.len(), 21);
assert_eq!(pairs.len(), 22);
for (i, (bin, json)) in pairs.iter().enumerate() {
assert_eq!(bin, json, "post {i}");
}
let Post::FrameGpu(b) = &pairs[5].0 else {
let Post::FrameGpu(b) = &pairs[6].0 else {
panic!()
};
assert_eq!(&b.bytes[..4], &0.5f32.to_le_bytes());

View file

@ -79,6 +79,7 @@ const KNOWN = new Set([
"select",
"input",
"divider",
"table",
"canvas",
"stack",
])
@ -524,6 +525,49 @@ const BUILDERS: Record<string, Builder> = {
}
return { el, rec }
},
// A table (widgets.md, Table): a header with the sort indicator, rows as text, scrolling sideways when it is wider
// than the widget; a row press sends `press` with its index and a header press `change` with the column's.
table(ctx) {
const el = h(ctx, "div", "pw-table")
const rec: Rec = {
type: "table",
node: { type: "table" },
update(n) {
const columns = (Array.isArray(n.columns) ? n.columns : []) as { label?: unknown; align?: unknown }[]
const rows = (Array.isArray(n.rows) ? n.rows : []) as unknown[][]
const sort = n.sort as { column?: unknown; descending?: unknown } | undefined
const table = h(ctx, "table")
const head = table.createTHead().insertRow()
columns.forEach((column, index) => {
const cell = h(ctx, "th")
cell.textContent = str(column.label)
if (sort?.column === index) cell.textContent += sort.descending === true ? " ▼" : " ▲"
if (column.align === "end") cell.className = "pw-end"
if (n.sortable === true && !ctx.readOnly()) {
cell.classList.add("pw-press")
cell.addEventListener("click", () => ctx.emit({ id: str(rec.node.id), type: "change", value: index }))
}
head.append(cell)
})
const body = table.createTBody()
rows.forEach((cells, row) => {
const tr = body.insertRow()
if (n.selected === row) tr.className = "pw-on"
if (n.selectable === true && !ctx.readOnly()) {
tr.classList.add("pw-press")
tr.addEventListener("click", () => ctx.emit({ id: str(rec.node.id), type: "press", value: row }))
}
columns.forEach((column, index) => {
const cell = tr.insertCell()
cell.textContent = str(Array.isArray(cells) ? cells[index] : undefined)
if (column.align === "end") cell.className = "pw-end"
})
})
el.replaceChildren(table)
},
}
return { el, rec }
},
divider(ctx) {
const el = h(ctx, "hr", "pw-divider")
return { el, rec: { type: "divider", node: { type: "divider" }, update() {} } }

View file

@ -108,6 +108,14 @@ export const CSS: string = /* css */ `
.pw-option[aria-checked="true"] .pw-mark { border-color: var(--pw-accent); background: var(--pw-accent); box-shadow: inset 0 0 0 2px var(--pw-bg); }
.pw-option-text { display: flex; flex-direction: column; min-width: 0; }
.pw-option-desc { font-size: 12px; color: var(--pw-muted); }
.pw-table { overflow-x: auto; max-width: 100%; }
.pw-table table { border-collapse: collapse; font-size: 13px; line-height: 1.4; }
.pw-table th, .pw-table td { border: 1px solid var(--pw-border); padding: 6px 10px; text-align: left; white-space: nowrap; }
.pw-table th { font-weight: 600; background: var(--pw-surface); }
.pw-table .pw-end { text-align: right; font-variant-numeric: tabular-nums; }
.pw-table .pw-press { cursor: pointer; }
.pw-table tr.pw-press:hover td, .pw-table th.pw-press:hover { background: var(--pw-surface); }
.pw-table tr.pw-on td { background: color-mix(in srgb, var(--pw-accent) 14%, transparent); }
.pw-divider { border: 0; border-top: 1px solid var(--pw-border); margin: 2px 0; width: 100%; }
.pw-carousel { position: relative; overflow: hidden; border-radius: calc(var(--pw-radius) - 2px); touch-action: pan-y; outline: none; min-width: 0; }
.pw-carousel:focus-visible { box-shadow: 0 0 0 2px var(--pw-accent); }

View file

@ -72,7 +72,7 @@ varint type, (varint tag, value)*, varint 0, [varint childCount, node × childCo
```
**Types:** 1 column, 2 row, 3 text, 4 markdown, 5 image, 6 carousel, 7 card, 8 button, 9 checkbox, 10 slider,
11 select, 12 input, 13 divider, 14 canvas, 16 stack. Containers: 1, 2, 6, 7, 16. Type 63 is a node type the host
11 select, 12 input, 13 divider, 14 canvas, 16 stack, 17 table. Containers: 1, 2, 6, 7, 16. Type 63 is a node type the host
doesn't know: the I stream holds 63 and then 0, and the S stream holds its name. Clients drop it like an unknown type
today.
@ -111,6 +111,13 @@ today.
| 18 | min | f64 | 36 | place | int: top-left 0, top 1, top-right 2, left 3, center 4, right 5, bottom-left 6, bottom 7, bottom-right 8, fill 9 |
| | | | 37 | inset | f64 (all sides) or f64 list of 4 (top, right, bottom, left) |
| | | | 38 | gpu | int (a GPU canvas, `widgets-gpu.md`) |
| | | | 39 | columns | str list: the columns' labels |
| | | | 40 | columns' `align` | f64 list, one per column: start 0, end 1 |
| | | | 41 | rows | str list: the cells row by row, each row as wide as `columns` (a missing cell is `""`; a number as `String(number)`) |
| | | | 42 | sort | f64 list: column, then 1 when `descending` else 0 |
| | | | 43 | table's `selected` | int: the row |
| | | | 44 | selectable | int |
| | | | 45 | sortable | int |
**Rules for the encoder** (`write_node`). It writes the props the tree has, in its key order:
- `type` and `children` are never props.
@ -119,6 +126,9 @@ today.
knows (the client then uses its default), or a value of the wrong JSON type.
- It doesn't check required props: the client does, as today, and an invalid view stays a program error.
- `place`/`inset` go on any node. They mean something only for a stack's children: the reader keeps them per child.
- A table's `columns` go out as props 39 and 40, its `rows` as prop 41 (as many cells per row as there are columns),
`sort` as 42 and a number `selected` as 43. A table whose `columns` or `rows` aren't lists, or whose cells aren't
strings or numbers, has them left out, and the client takes the view as invalid.
**Rules for the decoder.** It skips a tag whose id it doesn't know, by kind. That is the forward-compatibility rule:
new props get new ids, and a changed meaning gets a new id.

View file

@ -58,7 +58,8 @@ The prelude exposes a `widget` object inside `main` (implemented with `__host`):
handlers, and `widget.frame()`, `widget.sleep()` and `Promise.race` cover waiting.
**Handlers.** The node props are the same as in step mode (`onPress`, `onChange`, `onPointer`; `widgets.md`, Events),
but a live handler gets only the value (`onPress()`, `onChange(value)`, `onPointer(p)`) and its return value is
but a live handler gets only the value (`onPress()`, `onChange(value)`, `onPointer(p)`; a table's `onPress(row)` and
`onSort(column)`) and its return value is
ignored: it changes the program's variables or calls `widget.*`. `render` keeps the node, whose handlers the prelude finds by
the ids' paths, and whether the host found any. While
the view has handlers, hooks are registered or a frame is awaited, the prelude keeps a `__host.receive()` in flight and

View file

@ -96,7 +96,8 @@ programs use (`widget`, with `widget.gpu`, and `__widget_live`; `widgets-live.md
- `ui`: pure node builders, one per node type. Required fields are positional, optional ones and handlers go in
`props`: `column|row|carousel|card(props, children)` (or `(children)`), `text(text, props?)`, `markdown(text)`,
`image(src, props?)`, `button(label, props?)`, `checkbox(label, checked, props?)`, `slider(props)` (`props` holds
`value`, `min`, `max`), `select(options, props?)` (options may be strings), `input(value, props?)`, `divider()`.
`value`, `min`, `max`), `select(options, props?)` (options may be strings), `input(value, props?)`, `divider()`,
`table(columns, rows, props?)` (columns may be strings).
`children` may nest arrays and contain `null`/`undefined`/`false`, which are dropped (`cond && ui.text(...)`).
Also `canvas(props)` (with `wgsl` in `props` for a GPU canvas) and `draw()`, the draw command builder (see Canvas). Authors never set
`id`; a node's `key` (a string, a number or a boolean) names it among its siblings (Keys and depth).
@ -264,10 +265,12 @@ the widget encoder of `widget-mobile`, Rune's reader, the web host) and the Type
1. The root's path is `:` + enc(root `key`) when the root is an object (not an array) with a key (Keys and depth);
otherwise `0`.
2. A value that isn't an object, or is an array, goes out as in 5. An object (a node) goes out with its props in their
order, leaving out `key`, `id`, `pointer`, `onPress`, `onChange`, `onPointer` and `children`. If its `type` is in
the Events table, its handler prop is that type's (`onPress`, `onChange` or `onPointer`); when that prop is a
marker, or the type is `button`, `checkbox`, `slider`, `select` or `input`, or it is a `canvas` with a key, the
node gets `id` (its path) after its props. A `canvas` with a handler then gets `pointer: true`. If `children`
order, leaving out `key`, `id`, `pointer`, `selectable`, `sortable`, `onPress`, `onChange`, `onPointer`, `onSort`
and `children`. If its `type` is in the Events table, its handler props are that type's (`onPress`, `onChange` or
`onPointer`; a `table`'s `onPress` and `onSort`); when one is a marker, or the type is `button`, `checkbox`,
`slider`, `select` or `input`, or it is a `canvas` with a key, the node gets `id` (its path) after its props. A
`canvas` with a handler then gets `pointer: true`; a `table` gets `selectable: true` with an `onPress` and
`sortable: true` with an `onSort`, in that order. If `children`
isn't `undefined`, the node gets `children` last: the items below.
3. A `children` value that isn't an array is a list of one. Its items in order, at index `i`: a falsy item (a hole,
`undefined`, `null`, `false`, `0`, `NaN`, `""`) is skipped and keeps its index; an array's items come in its place
@ -282,7 +285,7 @@ the widget encoder of `widget-mobile`, Rune's reader, the web host) and the Type
5. Every value goes out as JSON holds it: an `undefined` prop is left out and an `undefined` item is `null`, a
non-finite number is `null`.
- **Functions where none may go.** A marker in a host call's argument anywhere but the value of a node's `onPress`,
`onChange` or `onPointer` (a node: the view's root, or an object among `children` or an array in them) fails the
`onChange`, `onPointer` or `onSort` (a node: the view's root, or an object among `children` or an array in them) fails the
call as a function did without `"mark"`: the host throws, from that call, its runtime's `TypeError` `Argument <n> to
<name> contains a function, which cannot be passed to the host.`, with `<n>` the argument's position from 1 and
`<name>` the function as the program called it (`__widget_emit`, `__host.post`, `__host.fetch`, ...). So a function
@ -343,6 +346,8 @@ handlers and never see them. The value a client sends, and what the handler gets
| `select` | `change`, `value: string` or `string[]` when `multiple` | `onChange(state, value)`, only known option values |
| `input` | `change`, `value: string` (on commit / blur / debounce >= 300 ms) | `onChange(state, text)` |
| `carousel` | `change`, `value: number` (new page index) | `onChange(state, index)` |
| `table` | `press`, `value: number` (the row pressed, an index into `rows`) | `onPress(state, row)` |
| `table` | `change`, `value: number` (the column whose header was pressed) | `onSort(state, column)` |
| `canvas` | `pointer`, `value: { kind, x, y, width, height }` in the node's logical pixels; `move` only while down, at most once per frame (see Canvas) | `onPointer(state, p)`; under pointer capture `p` is `{ kind, dx, dy, button }`, or a wheel's `{ kind, dx, dy }` (`widgets-input.md`, Wheel) |
| none (`id: ""`) | `key`, `focus`, `fullscreen`, `capture` | the hooks (Widget template source) |
@ -373,6 +378,10 @@ type Node = (
value?: string | string[]; multiple?: boolean }
| { type: "input"; id: string; label?: string; value: string; placeholder?: string; multiline?: boolean }
| { type: "divider" }
| { type: "table"; id?: string; columns: { label: string; align?: "start" | "end" }[]; rows: (string | number)[][];
sort?: { column: number; descending?: boolean }; selected?: number
selectable?: true // set by the prelude when it has onPress: only then do its rows take presses
sortable?: true } // set by the prelude when it has onSort: only then do its headers take presses
| { type: "canvas"; id?: string; height: number; width?: number; fps?: number; duration?: number; alt?: string;
poster?: string; wgsl?: string; values?: number[] // values only with wgsl
pointer?: true // set by the prelude when it has onPointer: only then does it take input
@ -394,6 +403,17 @@ Image `src`: an `https:`/`http:` URL, a `data:` URI, or a path relative to the s
relative paths through the server's existing file content endpoint for the session's location. TUI shows `alt` (or the
file name) plus the source instead of pixels where it cannot draw images.
Table: a grid of text with a header row, for data (a history, a comparison, a list of records). `columns` holds 1 to
16 columns, each with a `label` and an `align` (`start`, the default, or `end`: use `end` for numbers); `rows` at most
500 rows of at most that many cells, each a string or a number, which shows as JavaScript's `String(number)` (a row
with fewer cells leaves the rest empty). `sort` marks the header of column `sort.column` with an ascending (or, with
`descending`, a descending) indicator; the program sorts `rows` itself. `selected` highlights that row. A table with
more columns or cells, a `sort.column` or `selected` outside them, or a cell that is neither a string nor a number is
an invalid view. With `onPress`, pressing a row sends `press` with its index; with `onSort`, pressing a header sends
`change` with the column's index. Clients draw it like the tables in their markdown (the same fonts, borders, header,
colors and spacing), scroll it sideways when it is wider than the widget, and give it no height limit of its own; the
TUI writes it as aligned text, a line per row.
Carousel: one child visible at a time with paging (swipe on touch, arrows on desktop, left/right keys in the TUI) and a
page indicator. A carousel without `id` pages locally; with one (it has an `onChange`) it also emits `change`.