diff --git a/packages/plugin-widgets/src/skill.md b/packages/plugin-widgets/src/skill.md
index f13c3d19d71..76627061d2a 100644
--- a/packages/plugin-widgets/src/skill.md
+++ b/packages/plugin-widgets/src/skill.md
@@ -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
diff --git a/packages/tui/src/component/widget/view.tsx b/packages/tui/src/component/widget/view.tsx
index 2872f2ea3f6..ab7cd79036f 100644
--- a/packages/tui/src/component/widget/view.tsx
+++ b/packages/tui/src/component/widget/view.tsx
@@ -323,6 +323,9 @@ function NodeView(props: { item: Item }): JSX.Element {
+
+
+
@@ -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
+ 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) =>
+ 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 (
+
+
+ {lines().header}
+
+
+ {(row, index) => (
+
+ {row}
+
+ )}
+
+
+ )
+}
+
function DividerNode() {
const theme = useTheme()
return
diff --git a/packages/widget/src/node.ts b/packages/widget/src/node.ts
index 4026cc4b05e..9fd3b33424b 100644
--- a/packages/widget/src/node.ts
+++ b/packages/widget/src/node.ts
@@ -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>
+ /** 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 = 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; readonly rows: ReadonlyArray> }) =>
+ table.rows.every((row) => row.length <= table.columns.length) || "a row has more cells than there are columns",
+ ),
+ Schema.makeFilter(
+ (table: { readonly columns: ReadonlyArray; 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; 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 = [
"select",
"input",
"divider",
+ "table",
"canvas",
"stack",
]
diff --git a/packages/widget/src/prelude-live.js b/packages/widget/src/prelude-live.js
index fe46a8bbe40..a726a913ba1 100644
--- a/packages/widget/src/prelude-live.js
+++ b/packages/widget/src/prelude-live.js
@@ -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) => {
diff --git a/packages/widget/src/prelude.js b/packages/widget/src/prelude.js
index 2e89b1b0126..ba339879217 100644
--- a/packages/widget/src/prelude.js
+++ b/packages/widget/src/prelude.js
@@ -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)
}
diff --git a/packages/widget/src/source.ts b/packages/widget/src/source.ts
index a573418265f..16ce2cbaa69 100644
--- a/packages/widget/src/source.ts
+++ b/packages/widget/src/source.ts
@@ -1,9 +1,9 @@
// Generated by script/generate.ts from prelude.js, prelude-live.js and widget-templates/*.js. Do not edit; run `bun run generate`.
export const prelude =
- 'const __widget_protocol = 2\n// Widget prelude (specs/v2/widgets.md): a program is this, a newline, (live: prelude-live.js and a newline,) the source.\n// The first line is the prelude<->host contract\'s version, which hosts read before running the program. Hosts\n// (specs/v2/widgets.md, Native hosts) run `\\nreturn __widget_native_step(__input())` with `__input` and\n// `__widget_emit` as host globals, and live programs with `__widget_live(__input(), true)`: they build the tree clients\n// get themselves, so the prelude hands them views as built and finds handlers by their ids\' paths.\n\nconst ui = (() => {\n // Children may nest arrays and contain null, undefined or false, so widget templates can write `cond && node` and `...list`;\n // the host flattens them when it turns the view into the tree clients get.\n const container = (type) => (props, nodes) =>\n Array.isArray(props) ? { type, children: props } : { ...props, type, children: nodes ?? [] }\n const option = (item) => (typeof item === "string" ? { value: item, label: item } : item)\n return {\n column: container("column"),\n row: container("row"),\n carousel: container("carousel"),\n card: container("card"),\n stack: container("stack"),\n text: (text, props) => ({ ...props, type: "text", text: String(text) }),\n markdown: (text) => ({ type: "markdown", text: String(text) }),\n image: (src, props) => ({ ...props, type: "image", src }),\n button: (label, props) => ({ ...props, type: "button", label: String(label) }),\n checkbox: (label, checked, props) => ({\n ...props,\n type: "checkbox",\n label: String(label),\n checked: checked === true,\n }),\n slider: (props) => ({ ...props, type: "slider" }),\n select: (options, props) => ({ ...props, type: "select", options: (options ?? []).map(option) }),\n input: (value, props) => ({ ...props, type: "input", value: value ?? "" }),\n divider: () => ({ type: "divider" }),\n canvas: (props) => ({ ...props, type: "canvas" }),\n draw: () => new __WidgetDraw(),\n }\n})()\n\n// Interactive nodes: the event clients send for them and the handler prop that takes it.\nconst __WIDGET_CONTROLS = {\n button: { event: "press", handler: "onPress" },\n card: { event: "press", handler: "onPress" },\n checkbox: { event: "change", handler: "onChange" },\n slider: { event: "change", handler: "onChange" },\n select: { event: "change", handler: "onChange" },\n input: { event: "change", handler: "onChange" },\n carousel: { event: "change", handler: "onChange" },\n canvas: { event: "pointer", handler: "onPointer" },\n}\n\n// 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\n// children one level below it, and the items of an array among them one level below that array.\nconst __WIDGET_LEVELS = 100\nconst __WIDGET_DEEP = "The view nests more than 100 levels"\n\n// Whether `list`, the items at `level`, holds a node or an array below the last level. It runs only for a view that\n// failed to cross to the host, and goes no deeper than that level.\nfunction __widget_deep(list, level) {\n for (let index = 0; index < list.length; index++) {\n const item = list[index]\n if (!item || typeof item !== "object") continue\n if (level > __WIDGET_LEVELS) return true\n if (\n Array.isArray(item)\n ? __widget_deep(item, level + 1)\n : item.children !== undefined && __widget_deep(__widget_list(item.children), level + 1)\n )\n return true\n }\n return false\n}\n\n// The handler of the node with id `id` in the view `root` as built, found by following the id\'s path (the host assigns\n// the ids, specs/v2/widgets.md, Native hosts). Where two siblings share a segment (a key that looks like a repeat,\n// `k~2`), the later one\'s subtree wins.\nfunction __widget_find(root, id) {\n if (!root || typeof root !== "object" || Array.isArray(root)) return undefined\n const segments = String(id).split("/")\n const named = root.key !== undefined && root.key !== null\n if (segments[0] !== (named ? ":" + encodeURIComponent(String(root.key)) : "0")) return undefined\n return __widget_found(root, segments, 1)\n}\n\nfunction __widget_found(node, segments, at) {\n if (at === segments.length) {\n const control = __WIDGET_CONTROLS[node.type]\n const handler = control ? node[control.handler] : undefined\n if (typeof handler !== "function") return undefined\n if (node.type !== "carousel" || node.children === undefined) return { event: control.event, handler, node }\n // A carousel\'s change is checked against its pages: its children as flattened.\n return {\n event: control.event,\n handler,\n node: { ...node, children: __widget_items(__widget_list(node.children), []) },\n }\n }\n if (node.children === undefined) return undefined\n const matches = []\n __widget_segments(__widget_list(node.children), "", segments[at], matches, null)\n for (let index = matches.length - 1; index >= 0; index--) {\n const found = __widget_found(matches[index], segments, at + 1)\n if (found) return found\n }\n return undefined\n}\n\nfunction __widget_list(children) {\n return Array.isArray(children) ? children : [children]\n}\n\nfunction __widget_items(list, into) {\n for (let index = 0; index < list.length; index++) {\n const child = list[index]\n if (Array.isArray(child)) __widget_items(child, into)\n else if (child) into.push(child)\n }\n return into\n}\n\n// Pushes onto `into` the children in `list` whose path segment is `segment`, numbering them as hosts do.\nfunction __widget_segments(list, prefix, segment, into, seen) {\n for (let index = 0; index < list.length; index++) {\n const child = list[index]\n if (!child || typeof child !== "object") continue\n if (Array.isArray(child)) {\n seen = __widget_segments(child, prefix + index + ".", segment, into, seen)\n continue\n }\n let next\n if (child.key !== undefined && child.key !== null) {\n next = ":" + encodeURIComponent(String(child.key))\n if (seen === null) seen = new Map()\n const count = (seen.get(next) ?? 0) + 1\n seen.set(next, count)\n if (count > 1) next = next + "~" + count\n } else next = prefix + index\n if (next === segment) into.push(child)\n }\n return seen\n}\n\n// The value a handler gets for a client event, checked against the node; undefined drops the event.\nfunction __widget_value(entry, value) {\n const node = entry.node\n if (entry.event === "press") return true\n if (entry.event === "pointer") return __widget_pointer(value)\n if (node.type === "checkbox") return typeof value === "boolean" ? value : undefined\n if (node.type === "input") return typeof value === "string" ? value : undefined\n if (node.type === "slider") {\n const number = Number(value)\n if (typeof value !== "number" || !Number.isFinite(number)) return undefined\n return Math.min(node.max ?? number, Math.max(node.min ?? number, number))\n }\n if (node.type === "carousel") {\n const index = Number(value)\n return Number.isInteger(index) && index >= 0 && index < node.children.length ? index : undefined\n }\n if (node.type === "select") {\n const known = (node.options ?? []).map((option) => option.value)\n if (node.multiple) return Array.isArray(value) ? value.filter((item) => known.includes(item)) : undefined\n return known.includes(value) ? value : undefined\n }\n return undefined\n}\n\n// The full-screen close button\'s area a client reports (widgets-fullscreen.md), or null.\nfunction __widget_rect(value) {\n if (!value || typeof value !== "object") return null\n const fields = [value.x, value.y, value.width, value.height]\n if (!fields.every((field) => typeof field === "number" && Number.isFinite(field))) return null\n return { x: value.x, y: value.y, width: value.width, height: value.height }\n}\n\n// A pointer event\'s value: absolute `{ kind, x, y, width, height, close? }`, or `{ kind, dx, dy, button }` under\n// capture; a wheel\'s `{ kind, x, y, dx, dy }`, or `{ kind, dx, dy }` under capture. `close` is the full-screen close\n// button\'s area in the node\'s coordinates, when it overlaps the node.\nfunction __widget_pointer(value) {\n if (!value || typeof value !== "object" || !["down", "move", "up", "wheel"].includes(value.kind)) return undefined\n const number = (field) => (typeof field === "number" && Number.isFinite(field) ? field : 0)\n if (value.kind === "wheel") {\n const at = typeof value.x === "number" ? { x: number(value.x), y: number(value.y) } : {}\n return { kind: "wheel", ...at, dx: number(value.dx), dy: number(value.dy) }\n }\n if (typeof value.x !== "number" && (typeof value.dx === "number" || typeof value.button === "number"))\n return { kind: value.kind, dx: number(value.dx), dy: number(value.dy), button: number(value.button) }\n const close = __widget_rect(value.close)\n return {\n kind: value.kind,\n x: number(value.x),\n y: number(value.y),\n width: number(value.width),\n height: number(value.height),\n ...(close ? { close } : {}),\n }\n}\n\nfunction __widget_key(value) {\n if (!value || typeof value !== "object" || (value.kind !== "down" && value.kind !== "up")) return undefined\n return {\n kind: value.kind,\n key: String(value.key ?? ""),\n code: String(value.code ?? ""),\n repeat: value.repeat === true,\n shift: value.shift === true,\n alt: value.alt === true,\n ctrl: value.ctrl === true,\n meta: value.meta === true,\n }\n}\n\n// Draw command builder for `draw(state, data, frame)`. It runs every frame, so it only pushes compact arrays. A paint\n// may be a color string: the fill of a shape, the stroke of a line. No paint draws in the "text" color.\nclass __WidgetDraw {\n constructor() {\n this.commands = []\n }\n save() {\n this.commands.push(["save"])\n return this\n }\n restore() {\n this.commands.push(["restore"])\n return this\n }\n translate(x, y) {\n this.commands.push(["translate", x, y])\n return this\n }\n rotate(radians) {\n this.commands.push(["rotate", radians])\n return this\n }\n scale(sx, sy) {\n this.commands.push(["scale", sx, sy ?? sx])\n return this\n }\n alpha(a) {\n this.commands.push(["alpha", a])\n return this\n }\n rect(x, y, w, h, paint) {\n this.commands.push(["rect", x, y, w, h, __widget_fill(paint)])\n return this\n }\n rrect(x, y, w, h, r, paint) {\n this.commands.push(["rrect", x, y, w, h, r, __widget_fill(paint)])\n return this\n }\n circle(cx, cy, r, paint) {\n this.commands.push(["circle", cx, cy, r, __widget_fill(paint)])\n return this\n }\n line(x1, y1, x2, y2, paint) {\n this.commands.push([\n "line",\n x1,\n y1,\n x2,\n y2,\n paint && typeof paint === "object" ? paint : { stroke: paint || "text" },\n ])\n return this\n }\n path(segments, paint) {\n this.commands.push(["path", segments, __widget_fill(paint)])\n return this\n }\n text(x, y, text, style) {\n this.commands.push(["text", x, y, String(text), style ?? {}])\n return this\n }\n image(src, x, y, w, h) {\n this.commands.push(["image", src, x, y, w, h])\n return this\n }\n}\n\nfunction __widget_fill(paint) {\n return paint && typeof paint === "object" ? paint : { fill: paint || "text" }\n}\n\nclass __WidgetResult {\n constructor(kind, value, state) {\n this.kind = kind\n this.value = value\n this.state = state\n }\n}\n\n// What a step handler or hook may return instead of the next state. Each keeps the current state; `send` may set one.\nfunction submit(value) {\n return new __WidgetResult("submit", value ?? null, undefined)\n}\n\nfunction dismiss() {\n return new __WidgetResult("dismiss", undefined, undefined)\n}\n\n// Sends a message to the agent without closing the widget; `wake: false` lets the agent see it only on its next turn.\nfunction send(value, options) {\n return new __WidgetResult("send", { value: value ?? null, wake: options?.wake !== false }, options?.state)\n}\n\n// One step (specs/v2/widgets.md, Native hosts): the view goes to `__widget_emit` as built, and the run\'s result is the\n// rest of the step output (`state`, `submit`, `dismiss`, `send`); a draw\'s commands go to `__widget_emit` too, and\n// the run has no result. A view the host can\'t take because it nests too deep goes as `__widget_emit(null, message)`.\nfunction __widget_native_step(input) {\n const data = input.data\n if (input.phase === "draw") {\n const { id, ...frame } = input.frame ?? {}\n const last = typeof id === "string" ? id.slice(id.lastIndexOf("/") + 1) : ""\n frame.key = last.startsWith(":") ? decodeURIComponent(last.slice(1).replace(/~\\d+$/, "")) : null\n const drawn = typeof draw === "function" ? draw(input.state, data, frame) : undefined\n __widget_emit((drawn instanceof __WidgetDraw ? drawn.commands : drawn) ?? [])\n return\n }\n const output = {}\n if (input.phase === "init") output.state = (typeof init === "function" ? init(data) : undefined) ?? {}\n else {\n const next = __widget_dispatch(input.state, input.event ?? {}, data)\n const result = next instanceof __WidgetResult ? next : undefined\n output.state = result\n ? result.state === undefined\n ? input.state\n : result.state\n : next === undefined\n ? input.state\n : next\n if (result?.kind === "dismiss") output.dismiss = true\n if (result?.kind === "send") output.send = result.value\n if (result?.kind === "submit") output.submit = result.value\n }\n const root = view(output.state, data)\n try {\n __widget_emit(root)\n } catch (error) {\n if (!__widget_deep([root], 1)) throw error\n __widget_emit(null, __WIDGET_DEEP)\n }\n return output\n}\n\n// Routes one client event: system events to the widget template\'s hooks, control events to the handler of the node with\n// that id in the view of the current state. Nothing else sees either; an event nobody takes changes nothing.\nfunction __widget_dispatch(state, event, data) {\n if (event.type === "key") {\n const key = __widget_key(event.value)\n return key && typeof onKey === "function" ? onKey(state, key) : undefined\n }\n if (event.type === "focus") return typeof onFocus === "function" ? onFocus(state, event.value === true) : undefined\n if (event.type === "fullscreen")\n return typeof onFullscreen === "function"\n ? onFullscreen(state, event.value === true, __widget_rect(event.close))\n : undefined\n if (event.type === "capture")\n return typeof onCapture === "function" ? onCapture(state, event.value === true) : undefined\n if (event.type !== "press" && event.type !== "change" && event.type !== "pointer") return undefined\n const entry = __widget_find(view(state, data), event.id)\n if (!entry || entry.event !== event.type) return undefined\n const value = __widget_value(entry, event.value)\n if (value === undefined) return undefined\n return event.type === "press" ? entry.handler(state) : entry.handler(state, value)\n}\n'
+ 'const __widget_protocol = 2\n// Widget prelude (specs/v2/widgets.md): a program is this, a newline, (live: prelude-live.js and a newline,) the source.\n// The first line is the prelude<->host contract\'s version, which hosts read before running the program. Hosts\n// (specs/v2/widgets.md, Native hosts) run `\\nreturn __widget_native_step(__input())` with `__input` and\n// `__widget_emit` as host globals, and live programs with `__widget_live(__input(), true)`: they build the tree clients\n// get themselves, so the prelude hands them views as built and finds handlers by their ids\' paths.\n\nconst ui = (() => {\n // Children may nest arrays and contain null, undefined or false, so widget templates can write `cond && node` and `...list`;\n // the host flattens them when it turns the view into the tree clients get.\n const container = (type) => (props, nodes) =>\n Array.isArray(props) ? { type, children: props } : { ...props, type, children: nodes ?? [] }\n const option = (item) => (typeof item === "string" ? { value: item, label: item } : item)\n const column = (item) => (typeof item === "string" ? { label: item } : item)\n return {\n column: container("column"),\n row: container("row"),\n carousel: container("carousel"),\n card: container("card"),\n stack: container("stack"),\n text: (text, props) => ({ ...props, type: "text", text: String(text) }),\n markdown: (text) => ({ type: "markdown", text: String(text) }),\n image: (src, props) => ({ ...props, type: "image", src }),\n button: (label, props) => ({ ...props, type: "button", label: String(label) }),\n checkbox: (label, checked, props) => ({\n ...props,\n type: "checkbox",\n label: String(label),\n checked: checked === true,\n }),\n slider: (props) => ({ ...props, type: "slider" }),\n select: (options, props) => ({ ...props, type: "select", options: (options ?? []).map(option) }),\n input: (value, props) => ({ ...props, type: "input", value: value ?? "" }),\n divider: () => ({ type: "divider" }),\n table: (columns, rows, props) => ({\n ...props,\n type: "table",\n columns: (columns ?? []).map(column),\n rows: rows ?? [],\n }),\n canvas: (props) => ({ ...props, type: "canvas" }),\n draw: () => new __WidgetDraw(),\n }\n})()\n\n// Interactive nodes: the event clients send for them and the handler prop that takes it.\nconst __WIDGET_CONTROLS = {\n button: { event: "press", handler: "onPress" },\n card: { event: "press", handler: "onPress" },\n checkbox: { event: "change", handler: "onChange" },\n slider: { event: "change", handler: "onChange" },\n select: { event: "change", handler: "onChange" },\n input: { event: "change", handler: "onChange" },\n carousel: { event: "change", handler: "onChange" },\n canvas: { event: "pointer", handler: "onPointer" },\n // A table takes two: a row\'s press, and a header\'s press as `change`.\n table: [\n { event: "press", handler: "onPress" },\n { event: "change", handler: "onSort" },\n ],\n}\n\n// 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\n// children one level below it, and the items of an array among them one level below that array.\nconst __WIDGET_LEVELS = 100\nconst __WIDGET_DEEP = "The view nests more than 100 levels"\n\n// Whether `list`, the items at `level`, holds a node or an array below the last level. It runs only for a view that\n// failed to cross to the host, and goes no deeper than that level.\nfunction __widget_deep(list, level) {\n for (let index = 0; index < list.length; index++) {\n const item = list[index]\n if (!item || typeof item !== "object") continue\n if (level > __WIDGET_LEVELS) return true\n if (\n Array.isArray(item)\n ? __widget_deep(item, level + 1)\n : item.children !== undefined && __widget_deep(__widget_list(item.children), level + 1)\n )\n return true\n }\n return false\n}\n\n// The handler of the node with id `id` in the view `root` as built, found by following the id\'s path (the host assigns\n// the ids, specs/v2/widgets.md, Native hosts). Where two siblings share a segment (a key that looks like a repeat,\n// `k~2`), the later one\'s subtree wins.\nfunction __widget_find(root, id, type) {\n if (!root || typeof root !== "object" || Array.isArray(root)) return undefined\n const segments = String(id).split("/")\n const named = root.key !== undefined && root.key !== null\n if (segments[0] !== (named ? ":" + encodeURIComponent(String(root.key)) : "0")) return undefined\n return __widget_found(root, segments, 1, type)\n}\n\nfunction __widget_found(node, segments, at, type) {\n if (at === segments.length) {\n const controls = __WIDGET_CONTROLS[node.type]\n const control = Array.isArray(controls) ? controls.find((each) => each.event === type) : controls\n const handler = control ? node[control.handler] : undefined\n if (typeof handler !== "function") return undefined\n if (node.type !== "carousel" || node.children === undefined) return { event: control.event, handler, node }\n // A carousel\'s change is checked against its pages: its children as flattened.\n return {\n event: control.event,\n handler,\n node: { ...node, children: __widget_items(__widget_list(node.children), []) },\n }\n }\n if (node.children === undefined) return undefined\n const matches = []\n __widget_segments(__widget_list(node.children), "", segments[at], matches, null)\n for (let index = matches.length - 1; index >= 0; index--) {\n const found = __widget_found(matches[index], segments, at + 1, type)\n if (found) return found\n }\n return undefined\n}\n\nfunction __widget_list(children) {\n return Array.isArray(children) ? children : [children]\n}\n\nfunction __widget_items(list, into) {\n for (let index = 0; index < list.length; index++) {\n const child = list[index]\n if (Array.isArray(child)) __widget_items(child, into)\n else if (child) into.push(child)\n }\n return into\n}\n\n// Pushes onto `into` the children in `list` whose path segment is `segment`, numbering them as hosts do.\nfunction __widget_segments(list, prefix, segment, into, seen) {\n for (let index = 0; index < list.length; index++) {\n const child = list[index]\n if (!child || typeof child !== "object") continue\n if (Array.isArray(child)) {\n seen = __widget_segments(child, prefix + index + ".", segment, into, seen)\n continue\n }\n let next\n if (child.key !== undefined && child.key !== null) {\n next = ":" + encodeURIComponent(String(child.key))\n if (seen === null) seen = new Map()\n const count = (seen.get(next) ?? 0) + 1\n seen.set(next, count)\n if (count > 1) next = next + "~" + count\n } else next = prefix + index\n if (next === segment) into.push(child)\n }\n return seen\n}\n\n// The value a handler gets for a client event, checked against the node; undefined drops the event.\nfunction __widget_value(entry, value) {\n const node = entry.node\n if (node.type === "table") {\n const count = (entry.event === "press" ? node.rows : node.columns)?.length ?? 0\n return Number.isInteger(value) && value >= 0 && value < count ? value : undefined\n }\n if (entry.event === "press") return true\n if (entry.event === "pointer") return __widget_pointer(value)\n if (node.type === "checkbox") return typeof value === "boolean" ? value : undefined\n if (node.type === "input") return typeof value === "string" ? value : undefined\n if (node.type === "slider") {\n const number = Number(value)\n if (typeof value !== "number" || !Number.isFinite(number)) return undefined\n return Math.min(node.max ?? number, Math.max(node.min ?? number, number))\n }\n if (node.type === "carousel") {\n const index = Number(value)\n return Number.isInteger(index) && index >= 0 && index < node.children.length ? index : undefined\n }\n if (node.type === "select") {\n const known = (node.options ?? []).map((option) => option.value)\n if (node.multiple) return Array.isArray(value) ? value.filter((item) => known.includes(item)) : undefined\n return known.includes(value) ? value : undefined\n }\n return undefined\n}\n\n// The full-screen close button\'s area a client reports (widgets-fullscreen.md), or null.\nfunction __widget_rect(value) {\n if (!value || typeof value !== "object") return null\n const fields = [value.x, value.y, value.width, value.height]\n if (!fields.every((field) => typeof field === "number" && Number.isFinite(field))) return null\n return { x: value.x, y: value.y, width: value.width, height: value.height }\n}\n\n// A pointer event\'s value: absolute `{ kind, x, y, width, height, close? }`, or `{ kind, dx, dy, button }` under\n// capture; a wheel\'s `{ kind, x, y, dx, dy }`, or `{ kind, dx, dy }` under capture. `close` is the full-screen close\n// button\'s area in the node\'s coordinates, when it overlaps the node.\nfunction __widget_pointer(value) {\n if (!value || typeof value !== "object" || !["down", "move", "up", "wheel"].includes(value.kind)) return undefined\n const number = (field) => (typeof field === "number" && Number.isFinite(field) ? field : 0)\n if (value.kind === "wheel") {\n const at = typeof value.x === "number" ? { x: number(value.x), y: number(value.y) } : {}\n return { kind: "wheel", ...at, dx: number(value.dx), dy: number(value.dy) }\n }\n if (typeof value.x !== "number" && (typeof value.dx === "number" || typeof value.button === "number"))\n return { kind: value.kind, dx: number(value.dx), dy: number(value.dy), button: number(value.button) }\n const close = __widget_rect(value.close)\n return {\n kind: value.kind,\n x: number(value.x),\n y: number(value.y),\n width: number(value.width),\n height: number(value.height),\n ...(close ? { close } : {}),\n }\n}\n\nfunction __widget_key(value) {\n if (!value || typeof value !== "object" || (value.kind !== "down" && value.kind !== "up")) return undefined\n return {\n kind: value.kind,\n key: String(value.key ?? ""),\n code: String(value.code ?? ""),\n repeat: value.repeat === true,\n shift: value.shift === true,\n alt: value.alt === true,\n ctrl: value.ctrl === true,\n meta: value.meta === true,\n }\n}\n\n// Draw command builder for `draw(state, data, frame)`. It runs every frame, so it only pushes compact arrays. A paint\n// may be a color string: the fill of a shape, the stroke of a line. No paint draws in the "text" color.\nclass __WidgetDraw {\n constructor() {\n this.commands = []\n }\n save() {\n this.commands.push(["save"])\n return this\n }\n restore() {\n this.commands.push(["restore"])\n return this\n }\n translate(x, y) {\n this.commands.push(["translate", x, y])\n return this\n }\n rotate(radians) {\n this.commands.push(["rotate", radians])\n return this\n }\n scale(sx, sy) {\n this.commands.push(["scale", sx, sy ?? sx])\n return this\n }\n alpha(a) {\n this.commands.push(["alpha", a])\n return this\n }\n rect(x, y, w, h, paint) {\n this.commands.push(["rect", x, y, w, h, __widget_fill(paint)])\n return this\n }\n rrect(x, y, w, h, r, paint) {\n this.commands.push(["rrect", x, y, w, h, r, __widget_fill(paint)])\n return this\n }\n circle(cx, cy, r, paint) {\n this.commands.push(["circle", cx, cy, r, __widget_fill(paint)])\n return this\n }\n line(x1, y1, x2, y2, paint) {\n this.commands.push([\n "line",\n x1,\n y1,\n x2,\n y2,\n paint && typeof paint === "object" ? paint : { stroke: paint || "text" },\n ])\n return this\n }\n path(segments, paint) {\n this.commands.push(["path", segments, __widget_fill(paint)])\n return this\n }\n text(x, y, text, style) {\n this.commands.push(["text", x, y, String(text), style ?? {}])\n return this\n }\n image(src, x, y, w, h) {\n this.commands.push(["image", src, x, y, w, h])\n return this\n }\n}\n\nfunction __widget_fill(paint) {\n return paint && typeof paint === "object" ? paint : { fill: paint || "text" }\n}\n\nclass __WidgetResult {\n constructor(kind, value, state) {\n this.kind = kind\n this.value = value\n this.state = state\n }\n}\n\n// What a step handler or hook may return instead of the next state. Each keeps the current state; `send` may set one.\nfunction submit(value) {\n return new __WidgetResult("submit", value ?? null, undefined)\n}\n\nfunction dismiss() {\n return new __WidgetResult("dismiss", undefined, undefined)\n}\n\n// Sends a message to the agent without closing the widget; `wake: false` lets the agent see it only on its next turn.\nfunction send(value, options) {\n return new __WidgetResult("send", { value: value ?? null, wake: options?.wake !== false }, options?.state)\n}\n\n// One step (specs/v2/widgets.md, Native hosts): the view goes to `__widget_emit` as built, and the run\'s result is the\n// rest of the step output (`state`, `submit`, `dismiss`, `send`); a draw\'s commands go to `__widget_emit` too, and\n// the run has no result. A view the host can\'t take because it nests too deep goes as `__widget_emit(null, message)`.\nfunction __widget_native_step(input) {\n const data = input.data\n if (input.phase === "draw") {\n const { id, ...frame } = input.frame ?? {}\n const last = typeof id === "string" ? id.slice(id.lastIndexOf("/") + 1) : ""\n frame.key = last.startsWith(":") ? decodeURIComponent(last.slice(1).replace(/~\\d+$/, "")) : null\n const drawn = typeof draw === "function" ? draw(input.state, data, frame) : undefined\n __widget_emit((drawn instanceof __WidgetDraw ? drawn.commands : drawn) ?? [])\n return\n }\n const output = {}\n if (input.phase === "init") output.state = (typeof init === "function" ? init(data) : undefined) ?? {}\n else {\n const next = __widget_dispatch(input.state, input.event ?? {}, data)\n const result = next instanceof __WidgetResult ? next : undefined\n output.state = result\n ? result.state === undefined\n ? input.state\n : result.state\n : next === undefined\n ? input.state\n : next\n if (result?.kind === "dismiss") output.dismiss = true\n if (result?.kind === "send") output.send = result.value\n if (result?.kind === "submit") output.submit = result.value\n }\n const root = view(output.state, data)\n try {\n __widget_emit(root)\n } catch (error) {\n if (!__widget_deep([root], 1)) throw error\n __widget_emit(null, __WIDGET_DEEP)\n }\n return output\n}\n\n// Routes one client event: system events to the widget template\'s hooks, control events to the handler of the node with\n// that id in the view of the current state. Nothing else sees either; an event nobody takes changes nothing.\nfunction __widget_dispatch(state, event, data) {\n if (event.type === "key") {\n const key = __widget_key(event.value)\n return key && typeof onKey === "function" ? onKey(state, key) : undefined\n }\n if (event.type === "focus") return typeof onFocus === "function" ? onFocus(state, event.value === true) : undefined\n if (event.type === "fullscreen")\n return typeof onFullscreen === "function"\n ? onFullscreen(state, event.value === true, __widget_rect(event.close))\n : undefined\n if (event.type === "capture")\n return typeof onCapture === "function" ? onCapture(state, event.value === true) : undefined\n if (event.type !== "press" && event.type !== "change" && event.type !== "pointer") return undefined\n const entry = __widget_find(view(state, data), event.id, event.type)\n if (!entry || entry.event !== event.type) return undefined\n const value = __widget_value(entry, event.value)\n if (value === undefined) return undefined\n return event.type === "press" && entry.node.type !== "table" ? entry.handler(state) : entry.handler(state, value)\n}\n'
export const preludeLive =
- '// The live prelude (specs/v2/widgets.md, Prelude and step ABI): what only live programs use, after the prelude in a\n// live widget template\'s program: `widget` with `widget.gpu`, and `__widget_live`. Steps never load it.\n\n// WebGPU\'s flags, for the subset widgets have (specs/v2/widgets-gpu.md).\nconst GPUBufferUsage = Object.freeze({ COPY_SRC: 4, COPY_DST: 8, INDEX: 16, VERTEX: 32, UNIFORM: 64, STORAGE: 128 })\nconst GPUTextureUsage = Object.freeze({ COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, RENDER_ATTACHMENT: 16 })\nconst GPUShaderStage = Object.freeze({ VERTEX: 1, FRAGMENT: 2 })\nconst GPUColorWrite = Object.freeze({ RED: 1, GREEN: 2, BLUE: 4, ALPHA: 8, ALL: 15 })\n\n// `widget.gpu` (specs/v2/widgets-gpu.md): WebGPU\'s shapes, recorded as ops and bytes into the batch the host replays.\n// `start` takes the live input\'s `gpu`; `take` gives the pending batch (or null); `accept` takes the host\'s `canvas`\n// and `gpu` messages; `watched` tells whether the program waits on the device\'s loss, which `watch` is told of.\nfunction __widget_gpu(watch) {\n const LIMITS = Object.freeze({\n maxTextureDimension2D: 4096,\n maxTextureArrayLayers: 256,\n maxBindGroups: 4,\n maxBindingsPerBindGroup: 1000,\n maxDynamicUniformBuffersPerPipelineLayout: 8,\n maxDynamicStorageBuffersPerPipelineLayout: 4,\n maxSampledTexturesPerShaderStage: 16,\n maxSamplersPerShaderStage: 16,\n maxStorageBuffersPerShaderStage: 8,\n maxUniformBuffersPerShaderStage: 12,\n maxUniformBufferBindingSize: 65536,\n maxStorageBufferBindingSize: 67108864,\n minUniformBufferOffsetAlignment: 256,\n minStorageBufferOffsetAlignment: 256,\n maxVertexBuffers: 8,\n maxBufferSize: 67108864,\n maxVertexAttributes: 16,\n maxVertexBufferArrayStride: 2048,\n maxInterStageShaderVariables: 16,\n maxColorAttachments: 8,\n maxColorAttachmentBytesPerSample: 32,\n })\n // `device`: the live device or null, and `lost` its resolver; `ops` and `bytes` (`length` of them used): the pending\n // batch. `sizes`: the GPU canvases\' sizes by key, from the host; `contexts` by key.\n const gpu = {\n watched: false,\n available: false,\n format: "rgba8unorm",\n next: 1,\n device: null,\n lost: null,\n ops: [],\n bytes: null,\n length: 0,\n }\n const sizes = {}\n const contexts = {}\n const handle = () => gpu.next++\n // Records an op for `device`; a lost device\'s calls, and every call without a GPU, record nothing.\n const record = (device, op) => {\n if (gpu.available && device === gpu.device) gpu.ops.push(op)\n }\n const kind = (value, expected, what) => {\n if (!value || value.__kind !== expected) throw new TypeError(what + " must be a GPU " + expected)\n return value.__handle\n }\n const object = (value, what) => {\n if (!value || typeof value !== "object") throw new TypeError(what + " must be an object")\n return value\n }\n // Appends `data`\'s bytes (an ArrayBuffer, or a typed array whose offset and size count elements) to the batch and\n // returns `[byteOffset, byteLength]`. They are copied now, as WebGPU\'s writes copy them.\n const append = (data, offset, size) => {\n const view = ArrayBuffer.isView(data)\n if (!view && !(data instanceof ArrayBuffer)) throw new TypeError("data must be an ArrayBuffer or a typed array")\n const unit = view ? data.BYTES_PER_ELEMENT : 1\n const skip = (offset ?? 0) * unit\n const length = size === undefined ? data.byteLength - skip : size * unit\n const bytes = new Uint8Array(view ? data.buffer : data, (view ? data.byteOffset : 0) + skip, length)\n if (!gpu.bytes || gpu.length + length > gpu.bytes.length) {\n const grown = new Uint8Array(Math.max(1024, (gpu.length + length) * 2))\n if (gpu.bytes) grown.set(new Uint8Array(gpu.bytes.buffer, 0, gpu.length))\n gpu.bytes = grown\n }\n gpu.bytes.set(bytes, gpu.length)\n gpu.length += length\n return [gpu.length - length, length]\n }\n // An origin or extent as WebGPU takes one (an array, or an object), as `[x, y, z]`.\n const triple = (value, fill) =>\n Array.isArray(value)\n ? [value[0] ?? fill[0], value[1] ?? fill[1], value[2] ?? fill[2]]\n : value && typeof value === "object"\n ? [\n value.x ?? value.width ?? fill[0],\n value.y ?? value.height ?? fill[1],\n value.z ?? value.depthOrArrayLayers ?? fill[2],\n ]\n : fill\n const extent = (value) => triple(value, [undefined, 1, 1])\n const origin = (value) => triple(value, [0, 0, 0])\n const component = (value) => ({\n operation: value?.operation ?? "add",\n srcFactor: value?.srcFactor ?? "one",\n dstFactor: value?.dstFactor ?? "zero",\n })\n\n const texture = (device, h, props) => {\n // Views are immutable, so equal ones are one handle: a frame\'s view of the canvas too.\n const views = {}\n return {\n __kind: "texture",\n __handle: h,\n __device: device,\n ...props,\n createView: (descriptor) => {\n const d = descriptor ?? {}\n const layers = props.depthOrArrayLayers\n const dimension = d.dimension ?? (layers > 1 ? "2d-array" : "2d")\n const base = d.baseArrayLayer ?? 0\n const mip = d.baseMipLevel ?? 0\n const normal = {\n dimension,\n baseMipLevel: mip,\n mipLevelCount: d.mipLevelCount ?? props.mipLevelCount - mip,\n baseArrayLayer: base,\n arrayLayerCount: d.arrayLayerCount ?? (dimension === "2d" ? 1 : dimension === "cube" ? 6 : layers - base),\n }\n const key = JSON.stringify(normal)\n if (views[key]) return views[key]\n const view = { __kind: "view", __handle: handle(), __device: device }\n record(device, ["view", view.__handle, h, normal])\n views[key] = view\n return view\n },\n destroy: () => record(device, ["destroy", h]),\n }\n }\n\n const pass = (encoder, descriptor) => {\n const d = object(descriptor, "beginRenderPass\'s descriptor")\n const depth = d.depthStencilAttachment\n const clear = (value) =>\n Array.isArray(value) ? [...value] : value ? [value.r, value.g, value.b, value.a] : [0, 0, 0, 0]\n encoder.add(\n [\n "pass",\n {\n colorAttachments: (d.colorAttachments ?? []).map((a) =>\n a\n ? {\n view: kind(a.view, "view", "a color attachment\'s view"),\n resolveTarget: a.resolveTarget ? kind(a.resolveTarget, "view", "a resolveTarget") : null,\n clearValue: clear(a.clearValue),\n loadOp: a.loadOp,\n storeOp: a.storeOp,\n }\n : null,\n ),\n depthStencilAttachment: depth\n ? {\n view: kind(depth.view, "view", "the depth attachment\'s view"),\n depthClearValue: depth.depthClearValue ?? null,\n depthLoadOp: depth.depthLoadOp ?? null,\n depthStoreOp: depth.depthStoreOp ?? null,\n depthReadOnly: depth.depthReadOnly ?? false,\n }\n : null,\n },\n ],\n true,\n )\n const open = { ended: false }\n const add = (op) => (open.ended ? encoder.fail("the render pass has ended") : encoder.add(op, true))\n return {\n setPipeline: (pipeline) => add(["setPipeline", kind(pipeline, "renderPipeline", "setPipeline\'s pipeline")]),\n setBindGroup: (index, group, offsets) =>\n add([\n "setBindGroup",\n index,\n kind(group, "bindGroup", "setBindGroup\'s group"),\n offsets ? Array.from(offsets) : [],\n ]),\n setVertexBuffer: (slot, buffer, offset, size) =>\n add(["setVertexBuffer", slot, kind(buffer, "buffer", "setVertexBuffer\'s buffer"), offset ?? 0, size ?? -1]),\n setIndexBuffer: (buffer, format, offset, size) =>\n add(["setIndexBuffer", kind(buffer, "buffer", "setIndexBuffer\'s buffer"), format, offset ?? 0, size ?? -1]),\n setViewport: (x, y, width, height, minDepth, maxDepth) =>\n add(["setViewport", x, y, width, height, minDepth, maxDepth]),\n setScissorRect: (x, y, width, height) => add(["setScissorRect", x, y, width, height]),\n draw: (count, instances, first, firstInstance) =>\n add(["draw", count, instances ?? 1, first ?? 0, firstInstance ?? 0]),\n drawIndexed: (count, instances, first, base, firstInstance) =>\n add(["drawIndexed", count, instances ?? 1, first ?? 0, base ?? 0, firstInstance ?? 0]),\n end: () => {\n if (open.ended) return encoder.fail("the render pass has ended")\n open.ended = true\n encoder.add(["end"], true)\n encoder.close()\n },\n }\n }\n\n // A command encoder keeps its commands until `queue.submit` takes its command buffer. Misuse that WebGPU reports as\n // a validation error goes into the batch as an `error` op, once per encoder, and the encoder records nothing more.\n const encoder = (device) => {\n const state = { ops: gpu.available ? [] : null, pass: false, finished: false, failed: false }\n const self = {\n add: (op, inPass) => {\n if (state.failed) return\n if (state.finished) return self.fail("the command encoder is finished")\n if (state.pass && !inPass) return self.fail("a render pass is open on this command encoder")\n state.ops?.push(op)\n },\n close: () => (state.pass = false),\n fail: (message) => {\n if (state.failed) return\n state.failed = true\n record(device, ["error", message])\n },\n }\n const dead = { add: () => {}, fail: () => {}, close: () => {} }\n return {\n __kind: "encoder",\n beginRenderPass: (descriptor) => {\n if (state.finished) self.fail("the command encoder is finished")\n else if (state.pass) self.fail("a render pass is open on this command encoder")\n if (state.failed) return pass(dead, descriptor)\n state.pass = true\n return pass(self, descriptor)\n },\n copyBufferToBuffer: (source, sourceOffset, destination, destinationOffset, size) =>\n self.add([\n "copyBufferToBuffer",\n kind(source, "buffer", "the source"),\n sourceOffset,\n kind(destination, "buffer", "the destination"),\n destinationOffset,\n size,\n ]),\n copyBufferToTexture: (source, destination, size) =>\n self.add([\n "copyBufferToTexture",\n kind(source?.buffer, "buffer", "the source\'s buffer"),\n source.offset ?? 0,\n source.bytesPerRow,\n source.rowsPerImage ?? null,\n kind(destination?.texture, "texture", "the destination\'s texture"),\n destination.mipLevel ?? 0,\n origin(destination.origin),\n extent(size),\n ]),\n copyTextureToTexture: (source, destination, size) =>\n self.add([\n "copyTextureToTexture",\n kind(source?.texture, "texture", "the source\'s texture"),\n source.mipLevel ?? 0,\n origin(source.origin),\n kind(destination?.texture, "texture", "the destination\'s texture"),\n destination.mipLevel ?? 0,\n origin(destination.origin),\n extent(size),\n ]),\n finish: () => {\n if (state.pass) self.fail("a render pass is open on this command encoder")\n else if (state.finished) self.fail("the command encoder is finished")\n state.finished = true\n return { __kind: "commandBuffer", ops: state.failed ? null : state.ops, submitted: false }\n },\n }\n }\n\n const createDevice = () => {\n const lost = new Promise((resolve) => (gpu.lost = resolve))\n const device = {\n __kind: "device",\n limits: LIMITS,\n features: new Set(),\n // Reading it waits for the loss: the host\'s messages keep coming until then.\n get lost() {\n gpu.watched = true\n watch()\n return lost\n },\n createBuffer: (descriptor) => {\n const d = object(descriptor, "createBuffer\'s descriptor")\n const h = handle()\n record(device, ["buffer", h, d.size, d.usage])\n return {\n __kind: "buffer",\n __handle: h,\n __device: device,\n size: d.size,\n usage: d.usage,\n destroy: () => record(device, ["destroy", h]),\n }\n },\n createTexture: (descriptor) => {\n const d = object(descriptor, "createTexture\'s descriptor")\n const [width, height, depthOrArrayLayers] = extent(d.size)\n const props = {\n width,\n height,\n depthOrArrayLayers,\n format: d.format,\n usage: d.usage,\n mipLevelCount: d.mipLevelCount ?? 1,\n sampleCount: d.sampleCount ?? 1,\n dimension: "2d",\n }\n const h = handle()\n if (d.dimension !== undefined && d.dimension !== "2d")\n record(device, ["error", \'a texture\\\'s dimension must be "2d"\'])\n record(device, [\n "texture",\n h,\n width,\n height,\n depthOrArrayLayers,\n d.format,\n d.usage,\n props.mipLevelCount,\n props.sampleCount,\n ])\n return texture(device, h, props)\n },\n createSampler: (descriptor) => {\n const d = descriptor ?? {}\n const h = handle()\n record(device, [\n "sampler",\n h,\n {\n addressModeU: d.addressModeU ?? "clamp-to-edge",\n addressModeV: d.addressModeV ?? "clamp-to-edge",\n addressModeW: d.addressModeW ?? "clamp-to-edge",\n magFilter: d.magFilter ?? "nearest",\n minFilter: d.minFilter ?? "nearest",\n mipmapFilter: d.mipmapFilter ?? "nearest",\n lodMinClamp: d.lodMinClamp ?? 0,\n lodMaxClamp: d.lodMaxClamp ?? 32,\n compare: d.compare ?? null,\n maxAnisotropy: d.maxAnisotropy ?? 1,\n },\n ])\n return { __kind: "sampler", __handle: h, __device: device }\n },\n createShaderModule: (descriptor) => {\n const h = handle()\n record(device, ["shader", h, object(descriptor, "createShaderModule\'s descriptor").code])\n return { __kind: "shader", __handle: h, __device: device }\n },\n createBindGroupLayout: (descriptor) => {\n const h = handle()\n const entries = (object(descriptor, "createBindGroupLayout\'s descriptor").entries ?? []).map((e) => ({\n binding: e.binding,\n visibility: e.visibility,\n buffer: e.buffer\n ? {\n type: e.buffer.type ?? "uniform",\n hasDynamicOffset: e.buffer.hasDynamicOffset ?? false,\n minBindingSize: e.buffer.minBindingSize ?? 0,\n }\n : null,\n sampler: e.sampler ? { type: e.sampler.type ?? "filtering" } : null,\n texture: e.texture\n ? {\n sampleType: e.texture.sampleType ?? "float",\n viewDimension: e.texture.viewDimension ?? "2d",\n multisampled: e.texture.multisampled ?? false,\n }\n : null,\n }))\n record(device, ["bindGroupLayout", h, { entries }])\n return { __kind: "bindGroupLayout", __handle: h, __device: device }\n },\n createPipelineLayout: (descriptor) => {\n const h = handle()\n const layouts = (object(descriptor, "createPipelineLayout\'s descriptor").bindGroupLayouts ?? []).map((l) =>\n kind(l, "bindGroupLayout", "a bind group layout"),\n )\n record(device, ["pipelineLayout", h, layouts])\n return { __kind: "pipelineLayout", __handle: h, __device: device }\n },\n createBindGroup: (descriptor) => {\n const d = object(descriptor, "createBindGroup\'s descriptor")\n const h = handle()\n // A buffer, a buffer binding, a sampler or a texture view.\n const resource = (r) =>\n r?.__kind === "sampler"\n ? { sampler: r.__handle }\n : r?.__kind === "view"\n ? { view: r.__handle }\n : r?.__kind === "buffer"\n ? { buffer: r.__handle, offset: 0, size: -1 }\n : {\n buffer: kind(r?.buffer, "buffer", "a bind group entry\'s resource"),\n offset: r.offset ?? 0,\n size: r.size ?? -1,\n }\n record(device, [\n "bindGroup",\n h,\n {\n layout: kind(d.layout, "bindGroupLayout", "createBindGroup\'s layout"),\n entries: (d.entries ?? []).map((e) => ({ binding: e.binding, resource: resource(e.resource) })),\n },\n ])\n return { __kind: "bindGroup", __handle: h, __device: device }\n },\n createRenderPipeline: (descriptor) => {\n const d = object(descriptor, "createRenderPipeline\'s descriptor")\n const h = handle()\n const vertex = object(d.vertex, "the vertex stage")\n const fragment = d.fragment\n const depth = d.depthStencil\n record(device, [\n "renderPipeline",\n h,\n {\n layout: d.layout === "auto" ? "auto" : kind(d.layout, "pipelineLayout", "the layout"),\n vertex: {\n module: kind(vertex.module, "shader", "the vertex module"),\n entryPoint: vertex.entryPoint ?? null,\n buffers: (vertex.buffers ?? []).map((b) =>\n b\n ? {\n arrayStride: b.arrayStride,\n stepMode: b.stepMode ?? "vertex",\n attributes: (b.attributes ?? []).map((a) => ({\n format: a.format,\n offset: a.offset,\n shaderLocation: a.shaderLocation,\n })),\n }\n : null,\n ),\n },\n fragment: fragment\n ? {\n module: kind(fragment.module, "shader", "the fragment module"),\n entryPoint: fragment.entryPoint ?? null,\n targets: (fragment.targets ?? []).map((t) =>\n t\n ? {\n format: t.format,\n blend: t.blend ? { color: component(t.blend.color), alpha: component(t.blend.alpha) } : null,\n writeMask: t.writeMask ?? 15,\n }\n : null,\n ),\n }\n : null,\n primitive: {\n topology: d.primitive?.topology ?? "triangle-list",\n stripIndexFormat: d.primitive?.stripIndexFormat ?? null,\n frontFace: d.primitive?.frontFace ?? "ccw",\n cullMode: d.primitive?.cullMode ?? "none",\n },\n depthStencil: depth\n ? {\n format: depth.format,\n depthWriteEnabled: depth.depthWriteEnabled ?? false,\n depthCompare: depth.depthCompare ?? "always",\n }\n : null,\n multisample: {\n count: d.multisample?.count ?? 1,\n mask: d.multisample?.mask ?? 4294967295,\n alphaToCoverageEnabled: d.multisample?.alphaToCoverageEnabled ?? false,\n },\n },\n ])\n // `layout: "auto"`\'s layouts: one handle per index.\n const layouts = {}\n return {\n __kind: "renderPipeline",\n __handle: h,\n __device: device,\n getBindGroupLayout: (index) => {\n if (layouts[index]) return layouts[index]\n const layout = { __kind: "bindGroupLayout", __handle: handle(), __device: device }\n record(device, ["autoLayout", layout.__handle, h, index])\n layouts[index] = layout\n return layout\n },\n }\n },\n createCommandEncoder: () => encoder(device),\n queue: {\n writeBuffer: (buffer, offset, data, dataOffset, size) => {\n const h = kind(buffer, "buffer", "writeBuffer\'s buffer")\n if (gpu.available && device === gpu.device)\n gpu.ops.push(["writeBuffer", h, offset, ...append(data, dataOffset, size)])\n },\n writeTexture: (destination, data, layout, size) => {\n const h = kind(destination?.texture, "texture", "writeTexture\'s texture")\n if (!gpu.available || device !== gpu.device) return\n const skip = layout?.offset ?? 0\n const [byteOffset, byteLength] = append(data)\n gpu.ops.push([\n "writeTexture",\n h,\n destination.mipLevel ?? 0,\n origin(destination.origin),\n byteOffset + skip,\n byteLength - skip,\n layout?.bytesPerRow,\n layout?.rowsPerImage ?? null,\n extent(size),\n ])\n },\n submit: (buffers) => {\n for (const buffer of buffers) {\n kind(buffer, "commandBuffer", "submit\'s command buffer")\n if (buffer.submitted) {\n record(device, ["error", "a command buffer can be submitted once"])\n continue\n }\n buffer.submitted = true\n if (buffer.ops && gpu.available && device === gpu.device) for (const op of buffer.ops) gpu.ops.push(op)\n }\n record(device, ["submit"])\n },\n },\n }\n return device\n }\n\n const api = {\n get available() {\n return gpu.available\n },\n getPreferredCanvasFormat: () => gpu.format,\n // One device per widget, until it is lost.\n requestDevice: async () => {\n if (!gpu.device) gpu.device = createDevice()\n return gpu.device\n },\n getContext: (key) => {\n const name = String(key)\n if (contexts[name]) return contexts[name]\n const state = { device: null, handle: 0, texture: null }\n const context = {\n get width() {\n return sizes[name]?.width ?? 0\n },\n get height() {\n return sizes[name]?.height ?? 0\n },\n configure: (configuration) => {\n const c = object(configuration, "configure\'s configuration")\n kind(c.device, "device", "configure\'s device")\n // A new device\'s context is a new handle; configuring again keeps it.\n if (c.device !== state.device) state.handle = handle()\n state.device = c.device\n record(c.device, ["context", state.handle, name, c.format, c.alphaMode ?? "opaque"])\n const props = {\n format: c.format,\n usage: 16,\n mipLevelCount: 1,\n sampleCount: 1,\n depthOrArrayLayers: 1,\n dimension: "2d",\n }\n state.texture = texture(c.device, state.handle, props)\n // The canvas\'s texture is the client\'s: destroying it does nothing.\n state.texture.destroy = () => {}\n Object.defineProperty(state.texture, "width", { get: () => context.width })\n Object.defineProperty(state.texture, "height", { get: () => context.height })\n },\n getCurrentTexture: () => {\n if (!state.texture) throw new Error("configure the context before getCurrentTexture")\n return state.texture\n },\n }\n contexts[name] = context\n return context\n },\n }\n\n return {\n api,\n start: (input) => {\n gpu.available = input?.available === true\n if (input?.format === "bgra8unorm" || input?.format === "rgba8unorm") gpu.format = input.format\n },\n take: () => {\n if (gpu.ops.length === 0) return null\n const batch = { ops: gpu.ops, bytes: gpu.bytes ? gpu.bytes.buffer.slice(0, gpu.length) : new ArrayBuffer(0) }\n gpu.ops = []\n gpu.length = 0\n return batch\n },\n watched: () => gpu.watched && gpu.available && gpu.device !== null,\n accept: (message) => {\n if (message.type === "canvas") {\n sizes[String(message.key)] = { width: message.width, height: message.height }\n return\n }\n if (message.type !== "gpu" || message.lost === undefined || !gpu.device) return\n // Every handle is gone: the lost device\'s calls record nothing, and `requestDevice` makes a new one.\n const resolve = gpu.lost\n gpu.device = null\n gpu.watched = false\n gpu.ops = []\n gpu.length = 0\n resolve({ reason: message.lost, message: typeof message.message === "string" ? message.message : "" })\n },\n }\n}\n\n// `widget.storage` limits (widgets-live.md, Storage): a key\'s characters, a value\'s UTF-8 bytes of JSON, and per\n// widget template the keys and the UTF-8 bytes of keys and values together.\nconst __WIDGET_STORAGE = { key: 256, value: 64 * 1024, keys: 1000, bytes: 1024 * 1024 }\n\n// A storage error: an Error, so it fails the program at the template\'s line, with a `kind` like fetch\'s errors.\nfunction __widget_storage_error(kind, message) {\n const error = new Error(kind + ": widget.storage: " + message)\n error.kind = kind\n return error\n}\n\n// The UTF-8 length of a string, counting a lone surrogate as the 3 bytes of U+FFFD.\nfunction __widget_utf8(text) {\n let bytes = 0\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index)\n if (code < 0x80) bytes += 1\n else if (code < 0x800) bytes += 2\n else if (code >= 0xd800 && code < 0xdc00 && index + 1 < text.length) {\n const next = text.charCodeAt(index + 1)\n if (next >= 0xdc00 && next < 0xe000) {\n bytes += 4\n index++\n } else bytes += 3\n } else bytes += 3\n }\n return bytes\n}\n\n// Live mode (specs/v2/widgets-live.md): `main(data)` runs once, on the host\'s `__host.post`, `__host.receive`,\n// `__host.sleep`, `__host.now` and `__host.fetch`. While the view has handlers, hooks are registered or a frame is\n// awaited, a pump receives client messages and calls handlers and hooks between the program\'s awaits.\nconst widget = (() => {\n const hooks = { key: [], focus: [], fullscreen: [], capture: [], resumed: [], storage: [] }\n // `widget.storage` (widgets-live.md, Storage): the client\'s copy of the widget template\'s space, JSON text by key,\n // from `__input().storage`; `undefined` on a client without storage, `null` without the capability.\n const store = { input: undefined, values: new Map(), bytes: 0 }\n const live = {\n frame: null,\n requested: false,\n waiting: [],\n // The last rendered view as built, and whether the host found handlers in it.\n root: undefined,\n interactive: false,\n pumping: false,\n done: false,\n idle: null,\n reject: null,\n }\n const api = {}\n // `widget.gpu`, made for a live run only: steps never pay for it.\n const made = { gpu: null }\n const gpu = () => (made.gpu ??= __widget_gpu(() => pump()))\n const post = (message) => (live.done ? undefined : __host.post(message))\n // The pending GPU batch goes out on its own before any wait on the host but a frame request, which carries it.\n const flush = () => {\n const batch = gpu().take()\n if (batch) post({ type: "gpu", ops: batch.ops, bytes: batch.bytes })\n }\n const wanted = () =>\n !live.done &&\n (live.waiting.length > 0 ||\n live.interactive ||\n gpu().watched() ||\n Object.values(hooks).some((list) => list.length > 0))\n const fail = (error) => live.reject?.(error)\n // Runs a handler or hook; an async one that rejects fails the program like a throw.\n const call = (handler, ...args) => {\n const result = handler(...args)\n if (result && typeof result.then === "function") result.then(undefined, fail)\n }\n const emit = (kind, ...values) => hooks[kind].slice().forEach((hook) => call(hook, ...values))\n const dispatch = (event) => {\n if (event.type === "key") {\n const key = __widget_key(event.value)\n if (!key) return\n if (key.kind === "down") api.keys.add(key.code)\n else api.keys.delete(key.code)\n return emit("key", key)\n }\n if (event.type === "focus") {\n if (event.value !== true) api.keys.clear()\n return emit("focus", event.value === true)\n }\n if (event.type === "fullscreen") return emit("fullscreen", event.value === true, __widget_rect(event.close))\n if (event.type === "capture") return emit("capture", event.value === true)\n // A wheel isn\'t where the pointer is held: `widget.pointer` keeps the last down, move or up.\n if (event.type === "pointer" && event.value?.kind !== "wheel")\n api.pointer = __widget_pointer(event.value) ?? api.pointer\n const entry = __widget_find(live.root, event.id)\n if (!entry || entry.event !== event.type) return\n const value = __widget_value(entry, event.value)\n if (value === undefined) return\n if (event.type === "press") call(entry.handler)\n else call(entry.handler, value)\n }\n const accept = (message) => {\n if (message.type === "event") return dispatch(message.event ?? {})\n if (message.type === "canvas" || message.type === "gpu") return gpu().accept(message)\n if (message.type === "resumed") return emit("resumed", message.pausedMs)\n if (message.type === "storage") return changed(message)\n if (message.type !== "frame") return\n live.requested = false\n live.frame = message.frame\n // Every waiter gets this frame: one left over from a race (`Promise.race([widget.frame(), ...])`) too.\n const waiting = live.waiting.splice(0)\n if (waiting.length > 0) {\n const frame = take()\n waiting.forEach((resolve) => resolve(frame))\n }\n }\n const pump = async () => {\n if (live.pumping) return\n live.pumping = true\n try {\n while (wanted()) {\n flush()\n accept(await __host.receive())\n }\n } catch (error) {\n fail(error)\n } finally {\n live.pumping = false\n if (!wanted()) live.idle?.()\n }\n }\n const request = () => {\n const batch = gpu().take()\n if (live.requested || live.frame) {\n if (batch) post({ type: "gpu", ops: batch.ops, bytes: batch.bytes })\n return\n }\n live.requested = true\n post(batch ? { type: "frame", gpu: batch } : { type: "frame" })\n }\n // A change to the space from elsewhere (another device or another widget of this template), in the server\'s order.\n // One that leaves the copy as it is, such as this run\'s own write coming back, fires no hook.\n const changed = (message) => {\n if (!store.input || typeof message.key !== "string") return\n const value = typeof message.value === "string" ? message.value : undefined\n if (store.values.get(message.key) === value) return\n keep(message.key, value)\n emit("storage", { key: message.key, value: value === undefined ? null : parsed(value) })\n }\n const keep = (key, value) => {\n const before = store.values.get(key)\n if (before !== undefined) store.bytes -= __widget_utf8(key) + __widget_utf8(before)\n if (value === undefined) return void store.values.delete(key)\n store.values.set(key, value)\n store.bytes += __widget_utf8(key) + __widget_utf8(value)\n }\n const parsed = (text) => {\n try {\n return JSON.parse(text)\n } catch (error) {\n return text\n }\n }\n const storage = () => {\n if (store.input === undefined)\n throw __widget_storage_error(\n "Unsupported",\n "storage needs a client with spaces sync (OpenCode desktop or Android); this client has none",\n )\n if (store.input === null)\n throw __widget_storage_error(\n "CapabilityDenied",\n "storage is not declared: save the widget template with capabilities: { storage: {} }",\n )\n return store\n }\n const key = (call, value) => {\n if (typeof value !== "string" || value.length === 0)\n throw new TypeError("widget.storage." + call + " needs a key that is a non-empty string")\n if (value.length > __WIDGET_STORAGE.key)\n throw __widget_storage_error("TooLarge", "a key is longer than " + __WIDGET_STORAGE.key + " characters")\n return value\n }\n const take = () => {\n const frame = live.frame\n live.frame = null\n return frame\n }\n const response = (raw) => {\n const text = raw.body ?? atob(raw.body64 ?? "")\n return {\n ok: raw.status >= 200 && raw.status < 300,\n status: raw.status,\n headers: raw.headers ?? {},\n text: async () => text,\n json: async () => JSON.parse(text),\n }\n }\n Object.assign(api, {\n keys: new Set(),\n pointer: null,\n render: (node) => {\n live.root = node\n try {\n live.interactive = post({ type: "render", node }) === true\n } catch (error) {\n // A view too deep to cross: the host fails the run with the reason.\n if (!__widget_deep([node], 1)) throw error\n post({ type: "render", node: null, failure: __WIDGET_DEEP })\n }\n pump()\n },\n // The host knows the canvases by key, and throws for an unknown one or a GPU canvas.\n draw: (key, commands) =>\n void post({\n type: "draw",\n key: String(key),\n commands: commands instanceof __WidgetDraw ? commands.commands : commands,\n }),\n frame: async () => {\n request()\n if (live.frame) return take()\n const next = new Promise((resolve) => live.waiting.push(resolve))\n pump()\n return next\n },\n on: (kind, hook) => {\n if (!hooks[kind]) throw new Error(\'widget.on: unknown event "\' + kind + \'"\')\n if (typeof hook !== "function") throw new Error("widget.on needs a function")\n hooks[kind].push(hook)\n pump()\n return () => {\n const index = hooks[kind].indexOf(hook)\n if (index !== -1) hooks[kind].splice(index, 1)\n }\n },\n sleep: (ms) => {\n flush()\n return __host.sleep(ms)\n },\n now: () => __host.now(),\n submit: (value) => {\n post({ type: "submit", value: value ?? null })\n live.done = true\n },\n dismiss: () => {\n post({ type: "dismiss" })\n live.done = true\n },\n fetch: async (url, init) => {\n flush()\n const request = { url: String(url), method: init?.method ?? "GET", headers: init?.headers ?? {} }\n if (init?.body !== undefined) request.body = String(init.body)\n try {\n return response(await __host.fetch(request))\n } catch (error) {\n throw error?.kind ? error : { kind: "Network", message: error?.message ?? String(error) }\n }\n },\n storage: {\n get: (name) => {\n const text = storage().values.get(key("get", name))\n return text === undefined ? undefined : parsed(text)\n },\n keys: (prefix) => {\n const start = prefix === undefined ? "" : String(prefix)\n return [...storage().values.keys()].filter((name) => name.startsWith(start)).sort()\n },\n set: (name, value) => {\n const current = storage()\n name = key("set", name)\n const text = JSON.stringify(value === undefined ? null : value)\n if (typeof text !== "string") throw new TypeError("widget.storage.set needs a JSON value")\n if (__widget_utf8(text) > __WIDGET_STORAGE.value)\n throw __widget_storage_error("TooLarge", "a value is over " + (__WIDGET_STORAGE.value >> 10) + " KiB of JSON")\n const before = current.values.get(name)\n if (before === undefined && current.values.size >= __WIDGET_STORAGE.keys)\n throw __widget_storage_error("TooLarge", "storage holds " + __WIDGET_STORAGE.keys + " keys already")\n const bytes =\n current.bytes +\n __widget_utf8(name) +\n __widget_utf8(text) -\n (before === undefined ? 0 : __widget_utf8(name) + __widget_utf8(before))\n if (bytes > __WIDGET_STORAGE.bytes)\n throw __widget_storage_error("TooLarge", "storage would hold over " + (__WIDGET_STORAGE.bytes >> 20) + " MiB")\n keep(name, text)\n post({ type: "storage", key: name, value: text })\n return Promise.resolve()\n },\n delete: (name) => {\n const current = storage()\n name = key("delete", name)\n if (!current.values.has(name)) return Promise.resolve()\n keep(name, undefined)\n post({ type: "storage", key: name })\n return Promise.resolve()\n },\n },\n send: (value, options) => post({ type: "send", value: value ?? null, wake: options?.wake !== false }),\n capturePointer: () => post({ type: "capture", value: true }),\n releasePointer: () => post({ type: "capture", value: false }),\n })\n Object.defineProperty(api, "gpu", { get: () => gpu().api, enumerable: true })\n // Runs `main`, then keeps the widget interactive while its view has handlers or hooks are registered.\n // `gpu`: the live input\'s `{ available, format }` (specs/v2/widgets-gpu.md), none without a GPU.\n api.__run = async (data, gpuInput, storageInput) => {\n gpu().start(gpuInput)\n store.input = storageInput === undefined ? undefined : storageInput && { entries: storageInput.entries ?? [] }\n store.input?.entries.forEach((entry) => keep(String(entry.key), String(entry.value)))\n const failed = new Promise((_, reject) => (live.reject = reject))\n failed.catch(() => {})\n await Promise.race([main(data), failed])\n flush()\n if (!wanted()) return\n await Promise.race([new Promise((resolve) => (live.idle = resolve)), failed])\n }\n return api\n})()\n\n// Hosts run `return await __widget_live(__input(), true)` (specs/v2/widgets.md, Native hosts).\nasync function __widget_live(input) {\n await widget.__run(input.data, input.gpu, input.storage)\n return null\n}\n'
+ '// The live prelude (specs/v2/widgets.md, Prelude and step ABI): what only live programs use, after the prelude in a\n// live widget template\'s program: `widget` with `widget.gpu`, and `__widget_live`. Steps never load it.\n\n// WebGPU\'s flags, for the subset widgets have (specs/v2/widgets-gpu.md).\nconst GPUBufferUsage = Object.freeze({ COPY_SRC: 4, COPY_DST: 8, INDEX: 16, VERTEX: 32, UNIFORM: 64, STORAGE: 128 })\nconst GPUTextureUsage = Object.freeze({ COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, RENDER_ATTACHMENT: 16 })\nconst GPUShaderStage = Object.freeze({ VERTEX: 1, FRAGMENT: 2 })\nconst GPUColorWrite = Object.freeze({ RED: 1, GREEN: 2, BLUE: 4, ALPHA: 8, ALL: 15 })\n\n// `widget.gpu` (specs/v2/widgets-gpu.md): WebGPU\'s shapes, recorded as ops and bytes into the batch the host replays.\n// `start` takes the live input\'s `gpu`; `take` gives the pending batch (or null); `accept` takes the host\'s `canvas`\n// and `gpu` messages; `watched` tells whether the program waits on the device\'s loss, which `watch` is told of.\nfunction __widget_gpu(watch) {\n const LIMITS = Object.freeze({\n maxTextureDimension2D: 4096,\n maxTextureArrayLayers: 256,\n maxBindGroups: 4,\n maxBindingsPerBindGroup: 1000,\n maxDynamicUniformBuffersPerPipelineLayout: 8,\n maxDynamicStorageBuffersPerPipelineLayout: 4,\n maxSampledTexturesPerShaderStage: 16,\n maxSamplersPerShaderStage: 16,\n maxStorageBuffersPerShaderStage: 8,\n maxUniformBuffersPerShaderStage: 12,\n maxUniformBufferBindingSize: 65536,\n maxStorageBufferBindingSize: 67108864,\n minUniformBufferOffsetAlignment: 256,\n minStorageBufferOffsetAlignment: 256,\n maxVertexBuffers: 8,\n maxBufferSize: 67108864,\n maxVertexAttributes: 16,\n maxVertexBufferArrayStride: 2048,\n maxInterStageShaderVariables: 16,\n maxColorAttachments: 8,\n maxColorAttachmentBytesPerSample: 32,\n })\n // `device`: the live device or null, and `lost` its resolver; `ops` and `bytes` (`length` of them used): the pending\n // batch. `sizes`: the GPU canvases\' sizes by key, from the host; `contexts` by key.\n const gpu = {\n watched: false,\n available: false,\n format: "rgba8unorm",\n next: 1,\n device: null,\n lost: null,\n ops: [],\n bytes: null,\n length: 0,\n }\n const sizes = {}\n const contexts = {}\n const handle = () => gpu.next++\n // Records an op for `device`; a lost device\'s calls, and every call without a GPU, record nothing.\n const record = (device, op) => {\n if (gpu.available && device === gpu.device) gpu.ops.push(op)\n }\n const kind = (value, expected, what) => {\n if (!value || value.__kind !== expected) throw new TypeError(what + " must be a GPU " + expected)\n return value.__handle\n }\n const object = (value, what) => {\n if (!value || typeof value !== "object") throw new TypeError(what + " must be an object")\n return value\n }\n // Appends `data`\'s bytes (an ArrayBuffer, or a typed array whose offset and size count elements) to the batch and\n // returns `[byteOffset, byteLength]`. They are copied now, as WebGPU\'s writes copy them.\n const append = (data, offset, size) => {\n const view = ArrayBuffer.isView(data)\n if (!view && !(data instanceof ArrayBuffer)) throw new TypeError("data must be an ArrayBuffer or a typed array")\n const unit = view ? data.BYTES_PER_ELEMENT : 1\n const skip = (offset ?? 0) * unit\n const length = size === undefined ? data.byteLength - skip : size * unit\n const bytes = new Uint8Array(view ? data.buffer : data, (view ? data.byteOffset : 0) + skip, length)\n if (!gpu.bytes || gpu.length + length > gpu.bytes.length) {\n const grown = new Uint8Array(Math.max(1024, (gpu.length + length) * 2))\n if (gpu.bytes) grown.set(new Uint8Array(gpu.bytes.buffer, 0, gpu.length))\n gpu.bytes = grown\n }\n gpu.bytes.set(bytes, gpu.length)\n gpu.length += length\n return [gpu.length - length, length]\n }\n // An origin or extent as WebGPU takes one (an array, or an object), as `[x, y, z]`.\n const triple = (value, fill) =>\n Array.isArray(value)\n ? [value[0] ?? fill[0], value[1] ?? fill[1], value[2] ?? fill[2]]\n : value && typeof value === "object"\n ? [\n value.x ?? value.width ?? fill[0],\n value.y ?? value.height ?? fill[1],\n value.z ?? value.depthOrArrayLayers ?? fill[2],\n ]\n : fill\n const extent = (value) => triple(value, [undefined, 1, 1])\n const origin = (value) => triple(value, [0, 0, 0])\n const component = (value) => ({\n operation: value?.operation ?? "add",\n srcFactor: value?.srcFactor ?? "one",\n dstFactor: value?.dstFactor ?? "zero",\n })\n\n const texture = (device, h, props) => {\n // Views are immutable, so equal ones are one handle: a frame\'s view of the canvas too.\n const views = {}\n return {\n __kind: "texture",\n __handle: h,\n __device: device,\n ...props,\n createView: (descriptor) => {\n const d = descriptor ?? {}\n const layers = props.depthOrArrayLayers\n const dimension = d.dimension ?? (layers > 1 ? "2d-array" : "2d")\n const base = d.baseArrayLayer ?? 0\n const mip = d.baseMipLevel ?? 0\n const normal = {\n dimension,\n baseMipLevel: mip,\n mipLevelCount: d.mipLevelCount ?? props.mipLevelCount - mip,\n baseArrayLayer: base,\n arrayLayerCount: d.arrayLayerCount ?? (dimension === "2d" ? 1 : dimension === "cube" ? 6 : layers - base),\n }\n const key = JSON.stringify(normal)\n if (views[key]) return views[key]\n const view = { __kind: "view", __handle: handle(), __device: device }\n record(device, ["view", view.__handle, h, normal])\n views[key] = view\n return view\n },\n destroy: () => record(device, ["destroy", h]),\n }\n }\n\n const pass = (encoder, descriptor) => {\n const d = object(descriptor, "beginRenderPass\'s descriptor")\n const depth = d.depthStencilAttachment\n const clear = (value) =>\n Array.isArray(value) ? [...value] : value ? [value.r, value.g, value.b, value.a] : [0, 0, 0, 0]\n encoder.add(\n [\n "pass",\n {\n colorAttachments: (d.colorAttachments ?? []).map((a) =>\n a\n ? {\n view: kind(a.view, "view", "a color attachment\'s view"),\n resolveTarget: a.resolveTarget ? kind(a.resolveTarget, "view", "a resolveTarget") : null,\n clearValue: clear(a.clearValue),\n loadOp: a.loadOp,\n storeOp: a.storeOp,\n }\n : null,\n ),\n depthStencilAttachment: depth\n ? {\n view: kind(depth.view, "view", "the depth attachment\'s view"),\n depthClearValue: depth.depthClearValue ?? null,\n depthLoadOp: depth.depthLoadOp ?? null,\n depthStoreOp: depth.depthStoreOp ?? null,\n depthReadOnly: depth.depthReadOnly ?? false,\n }\n : null,\n },\n ],\n true,\n )\n const open = { ended: false }\n const add = (op) => (open.ended ? encoder.fail("the render pass has ended") : encoder.add(op, true))\n return {\n setPipeline: (pipeline) => add(["setPipeline", kind(pipeline, "renderPipeline", "setPipeline\'s pipeline")]),\n setBindGroup: (index, group, offsets) =>\n add([\n "setBindGroup",\n index,\n kind(group, "bindGroup", "setBindGroup\'s group"),\n offsets ? Array.from(offsets) : [],\n ]),\n setVertexBuffer: (slot, buffer, offset, size) =>\n add(["setVertexBuffer", slot, kind(buffer, "buffer", "setVertexBuffer\'s buffer"), offset ?? 0, size ?? -1]),\n setIndexBuffer: (buffer, format, offset, size) =>\n add(["setIndexBuffer", kind(buffer, "buffer", "setIndexBuffer\'s buffer"), format, offset ?? 0, size ?? -1]),\n setViewport: (x, y, width, height, minDepth, maxDepth) =>\n add(["setViewport", x, y, width, height, minDepth, maxDepth]),\n setScissorRect: (x, y, width, height) => add(["setScissorRect", x, y, width, height]),\n draw: (count, instances, first, firstInstance) =>\n add(["draw", count, instances ?? 1, first ?? 0, firstInstance ?? 0]),\n drawIndexed: (count, instances, first, base, firstInstance) =>\n add(["drawIndexed", count, instances ?? 1, first ?? 0, base ?? 0, firstInstance ?? 0]),\n end: () => {\n if (open.ended) return encoder.fail("the render pass has ended")\n open.ended = true\n encoder.add(["end"], true)\n encoder.close()\n },\n }\n }\n\n // A command encoder keeps its commands until `queue.submit` takes its command buffer. Misuse that WebGPU reports as\n // a validation error goes into the batch as an `error` op, once per encoder, and the encoder records nothing more.\n const encoder = (device) => {\n const state = { ops: gpu.available ? [] : null, pass: false, finished: false, failed: false }\n const self = {\n add: (op, inPass) => {\n if (state.failed) return\n if (state.finished) return self.fail("the command encoder is finished")\n if (state.pass && !inPass) return self.fail("a render pass is open on this command encoder")\n state.ops?.push(op)\n },\n close: () => (state.pass = false),\n fail: (message) => {\n if (state.failed) return\n state.failed = true\n record(device, ["error", message])\n },\n }\n const dead = { add: () => {}, fail: () => {}, close: () => {} }\n return {\n __kind: "encoder",\n beginRenderPass: (descriptor) => {\n if (state.finished) self.fail("the command encoder is finished")\n else if (state.pass) self.fail("a render pass is open on this command encoder")\n if (state.failed) return pass(dead, descriptor)\n state.pass = true\n return pass(self, descriptor)\n },\n copyBufferToBuffer: (source, sourceOffset, destination, destinationOffset, size) =>\n self.add([\n "copyBufferToBuffer",\n kind(source, "buffer", "the source"),\n sourceOffset,\n kind(destination, "buffer", "the destination"),\n destinationOffset,\n size,\n ]),\n copyBufferToTexture: (source, destination, size) =>\n self.add([\n "copyBufferToTexture",\n kind(source?.buffer, "buffer", "the source\'s buffer"),\n source.offset ?? 0,\n source.bytesPerRow,\n source.rowsPerImage ?? null,\n kind(destination?.texture, "texture", "the destination\'s texture"),\n destination.mipLevel ?? 0,\n origin(destination.origin),\n extent(size),\n ]),\n copyTextureToTexture: (source, destination, size) =>\n self.add([\n "copyTextureToTexture",\n kind(source?.texture, "texture", "the source\'s texture"),\n source.mipLevel ?? 0,\n origin(source.origin),\n kind(destination?.texture, "texture", "the destination\'s texture"),\n destination.mipLevel ?? 0,\n origin(destination.origin),\n extent(size),\n ]),\n finish: () => {\n if (state.pass) self.fail("a render pass is open on this command encoder")\n else if (state.finished) self.fail("the command encoder is finished")\n state.finished = true\n return { __kind: "commandBuffer", ops: state.failed ? null : state.ops, submitted: false }\n },\n }\n }\n\n const createDevice = () => {\n const lost = new Promise((resolve) => (gpu.lost = resolve))\n const device = {\n __kind: "device",\n limits: LIMITS,\n features: new Set(),\n // Reading it waits for the loss: the host\'s messages keep coming until then.\n get lost() {\n gpu.watched = true\n watch()\n return lost\n },\n createBuffer: (descriptor) => {\n const d = object(descriptor, "createBuffer\'s descriptor")\n const h = handle()\n record(device, ["buffer", h, d.size, d.usage])\n return {\n __kind: "buffer",\n __handle: h,\n __device: device,\n size: d.size,\n usage: d.usage,\n destroy: () => record(device, ["destroy", h]),\n }\n },\n createTexture: (descriptor) => {\n const d = object(descriptor, "createTexture\'s descriptor")\n const [width, height, depthOrArrayLayers] = extent(d.size)\n const props = {\n width,\n height,\n depthOrArrayLayers,\n format: d.format,\n usage: d.usage,\n mipLevelCount: d.mipLevelCount ?? 1,\n sampleCount: d.sampleCount ?? 1,\n dimension: "2d",\n }\n const h = handle()\n if (d.dimension !== undefined && d.dimension !== "2d")\n record(device, ["error", \'a texture\\\'s dimension must be "2d"\'])\n record(device, [\n "texture",\n h,\n width,\n height,\n depthOrArrayLayers,\n d.format,\n d.usage,\n props.mipLevelCount,\n props.sampleCount,\n ])\n return texture(device, h, props)\n },\n createSampler: (descriptor) => {\n const d = descriptor ?? {}\n const h = handle()\n record(device, [\n "sampler",\n h,\n {\n addressModeU: d.addressModeU ?? "clamp-to-edge",\n addressModeV: d.addressModeV ?? "clamp-to-edge",\n addressModeW: d.addressModeW ?? "clamp-to-edge",\n magFilter: d.magFilter ?? "nearest",\n minFilter: d.minFilter ?? "nearest",\n mipmapFilter: d.mipmapFilter ?? "nearest",\n lodMinClamp: d.lodMinClamp ?? 0,\n lodMaxClamp: d.lodMaxClamp ?? 32,\n compare: d.compare ?? null,\n maxAnisotropy: d.maxAnisotropy ?? 1,\n },\n ])\n return { __kind: "sampler", __handle: h, __device: device }\n },\n createShaderModule: (descriptor) => {\n const h = handle()\n record(device, ["shader", h, object(descriptor, "createShaderModule\'s descriptor").code])\n return { __kind: "shader", __handle: h, __device: device }\n },\n createBindGroupLayout: (descriptor) => {\n const h = handle()\n const entries = (object(descriptor, "createBindGroupLayout\'s descriptor").entries ?? []).map((e) => ({\n binding: e.binding,\n visibility: e.visibility,\n buffer: e.buffer\n ? {\n type: e.buffer.type ?? "uniform",\n hasDynamicOffset: e.buffer.hasDynamicOffset ?? false,\n minBindingSize: e.buffer.minBindingSize ?? 0,\n }\n : null,\n sampler: e.sampler ? { type: e.sampler.type ?? "filtering" } : null,\n texture: e.texture\n ? {\n sampleType: e.texture.sampleType ?? "float",\n viewDimension: e.texture.viewDimension ?? "2d",\n multisampled: e.texture.multisampled ?? false,\n }\n : null,\n }))\n record(device, ["bindGroupLayout", h, { entries }])\n return { __kind: "bindGroupLayout", __handle: h, __device: device }\n },\n createPipelineLayout: (descriptor) => {\n const h = handle()\n const layouts = (object(descriptor, "createPipelineLayout\'s descriptor").bindGroupLayouts ?? []).map((l) =>\n kind(l, "bindGroupLayout", "a bind group layout"),\n )\n record(device, ["pipelineLayout", h, layouts])\n return { __kind: "pipelineLayout", __handle: h, __device: device }\n },\n createBindGroup: (descriptor) => {\n const d = object(descriptor, "createBindGroup\'s descriptor")\n const h = handle()\n // A buffer, a buffer binding, a sampler or a texture view.\n const resource = (r) =>\n r?.__kind === "sampler"\n ? { sampler: r.__handle }\n : r?.__kind === "view"\n ? { view: r.__handle }\n : r?.__kind === "buffer"\n ? { buffer: r.__handle, offset: 0, size: -1 }\n : {\n buffer: kind(r?.buffer, "buffer", "a bind group entry\'s resource"),\n offset: r.offset ?? 0,\n size: r.size ?? -1,\n }\n record(device, [\n "bindGroup",\n h,\n {\n layout: kind(d.layout, "bindGroupLayout", "createBindGroup\'s layout"),\n entries: (d.entries ?? []).map((e) => ({ binding: e.binding, resource: resource(e.resource) })),\n },\n ])\n return { __kind: "bindGroup", __handle: h, __device: device }\n },\n createRenderPipeline: (descriptor) => {\n const d = object(descriptor, "createRenderPipeline\'s descriptor")\n const h = handle()\n const vertex = object(d.vertex, "the vertex stage")\n const fragment = d.fragment\n const depth = d.depthStencil\n record(device, [\n "renderPipeline",\n h,\n {\n layout: d.layout === "auto" ? "auto" : kind(d.layout, "pipelineLayout", "the layout"),\n vertex: {\n module: kind(vertex.module, "shader", "the vertex module"),\n entryPoint: vertex.entryPoint ?? null,\n buffers: (vertex.buffers ?? []).map((b) =>\n b\n ? {\n arrayStride: b.arrayStride,\n stepMode: b.stepMode ?? "vertex",\n attributes: (b.attributes ?? []).map((a) => ({\n format: a.format,\n offset: a.offset,\n shaderLocation: a.shaderLocation,\n })),\n }\n : null,\n ),\n },\n fragment: fragment\n ? {\n module: kind(fragment.module, "shader", "the fragment module"),\n entryPoint: fragment.entryPoint ?? null,\n targets: (fragment.targets ?? []).map((t) =>\n t\n ? {\n format: t.format,\n blend: t.blend ? { color: component(t.blend.color), alpha: component(t.blend.alpha) } : null,\n writeMask: t.writeMask ?? 15,\n }\n : null,\n ),\n }\n : null,\n primitive: {\n topology: d.primitive?.topology ?? "triangle-list",\n stripIndexFormat: d.primitive?.stripIndexFormat ?? null,\n frontFace: d.primitive?.frontFace ?? "ccw",\n cullMode: d.primitive?.cullMode ?? "none",\n },\n depthStencil: depth\n ? {\n format: depth.format,\n depthWriteEnabled: depth.depthWriteEnabled ?? false,\n depthCompare: depth.depthCompare ?? "always",\n }\n : null,\n multisample: {\n count: d.multisample?.count ?? 1,\n mask: d.multisample?.mask ?? 4294967295,\n alphaToCoverageEnabled: d.multisample?.alphaToCoverageEnabled ?? false,\n },\n },\n ])\n // `layout: "auto"`\'s layouts: one handle per index.\n const layouts = {}\n return {\n __kind: "renderPipeline",\n __handle: h,\n __device: device,\n getBindGroupLayout: (index) => {\n if (layouts[index]) return layouts[index]\n const layout = { __kind: "bindGroupLayout", __handle: handle(), __device: device }\n record(device, ["autoLayout", layout.__handle, h, index])\n layouts[index] = layout\n return layout\n },\n }\n },\n createCommandEncoder: () => encoder(device),\n queue: {\n writeBuffer: (buffer, offset, data, dataOffset, size) => {\n const h = kind(buffer, "buffer", "writeBuffer\'s buffer")\n if (gpu.available && device === gpu.device)\n gpu.ops.push(["writeBuffer", h, offset, ...append(data, dataOffset, size)])\n },\n writeTexture: (destination, data, layout, size) => {\n const h = kind(destination?.texture, "texture", "writeTexture\'s texture")\n if (!gpu.available || device !== gpu.device) return\n const skip = layout?.offset ?? 0\n const [byteOffset, byteLength] = append(data)\n gpu.ops.push([\n "writeTexture",\n h,\n destination.mipLevel ?? 0,\n origin(destination.origin),\n byteOffset + skip,\n byteLength - skip,\n layout?.bytesPerRow,\n layout?.rowsPerImage ?? null,\n extent(size),\n ])\n },\n submit: (buffers) => {\n for (const buffer of buffers) {\n kind(buffer, "commandBuffer", "submit\'s command buffer")\n if (buffer.submitted) {\n record(device, ["error", "a command buffer can be submitted once"])\n continue\n }\n buffer.submitted = true\n if (buffer.ops && gpu.available && device === gpu.device) for (const op of buffer.ops) gpu.ops.push(op)\n }\n record(device, ["submit"])\n },\n },\n }\n return device\n }\n\n const api = {\n get available() {\n return gpu.available\n },\n getPreferredCanvasFormat: () => gpu.format,\n // One device per widget, until it is lost.\n requestDevice: async () => {\n if (!gpu.device) gpu.device = createDevice()\n return gpu.device\n },\n getContext: (key) => {\n const name = String(key)\n if (contexts[name]) return contexts[name]\n const state = { device: null, handle: 0, texture: null }\n const context = {\n get width() {\n return sizes[name]?.width ?? 0\n },\n get height() {\n return sizes[name]?.height ?? 0\n },\n configure: (configuration) => {\n const c = object(configuration, "configure\'s configuration")\n kind(c.device, "device", "configure\'s device")\n // A new device\'s context is a new handle; configuring again keeps it.\n if (c.device !== state.device) state.handle = handle()\n state.device = c.device\n record(c.device, ["context", state.handle, name, c.format, c.alphaMode ?? "opaque"])\n const props = {\n format: c.format,\n usage: 16,\n mipLevelCount: 1,\n sampleCount: 1,\n depthOrArrayLayers: 1,\n dimension: "2d",\n }\n state.texture = texture(c.device, state.handle, props)\n // The canvas\'s texture is the client\'s: destroying it does nothing.\n state.texture.destroy = () => {}\n Object.defineProperty(state.texture, "width", { get: () => context.width })\n Object.defineProperty(state.texture, "height", { get: () => context.height })\n },\n getCurrentTexture: () => {\n if (!state.texture) throw new Error("configure the context before getCurrentTexture")\n return state.texture\n },\n }\n contexts[name] = context\n return context\n },\n }\n\n return {\n api,\n start: (input) => {\n gpu.available = input?.available === true\n if (input?.format === "bgra8unorm" || input?.format === "rgba8unorm") gpu.format = input.format\n },\n take: () => {\n if (gpu.ops.length === 0) return null\n const batch = { ops: gpu.ops, bytes: gpu.bytes ? gpu.bytes.buffer.slice(0, gpu.length) : new ArrayBuffer(0) }\n gpu.ops = []\n gpu.length = 0\n return batch\n },\n watched: () => gpu.watched && gpu.available && gpu.device !== null,\n accept: (message) => {\n if (message.type === "canvas") {\n sizes[String(message.key)] = { width: message.width, height: message.height }\n return\n }\n if (message.type !== "gpu" || message.lost === undefined || !gpu.device) return\n // Every handle is gone: the lost device\'s calls record nothing, and `requestDevice` makes a new one.\n const resolve = gpu.lost\n gpu.device = null\n gpu.watched = false\n gpu.ops = []\n gpu.length = 0\n resolve({ reason: message.lost, message: typeof message.message === "string" ? message.message : "" })\n },\n }\n}\n\n// `widget.storage` limits (widgets-live.md, Storage): a key\'s characters, a value\'s UTF-8 bytes of JSON, and per\n// widget template the keys and the UTF-8 bytes of keys and values together.\nconst __WIDGET_STORAGE = { key: 256, value: 64 * 1024, keys: 1000, bytes: 1024 * 1024 }\n\n// A storage error: an Error, so it fails the program at the template\'s line, with a `kind` like fetch\'s errors.\nfunction __widget_storage_error(kind, message) {\n const error = new Error(kind + ": widget.storage: " + message)\n error.kind = kind\n return error\n}\n\n// The UTF-8 length of a string, counting a lone surrogate as the 3 bytes of U+FFFD.\nfunction __widget_utf8(text) {\n let bytes = 0\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index)\n if (code < 0x80) bytes += 1\n else if (code < 0x800) bytes += 2\n else if (code >= 0xd800 && code < 0xdc00 && index + 1 < text.length) {\n const next = text.charCodeAt(index + 1)\n if (next >= 0xdc00 && next < 0xe000) {\n bytes += 4\n index++\n } else bytes += 3\n } else bytes += 3\n }\n return bytes\n}\n\n// Live mode (specs/v2/widgets-live.md): `main(data)` runs once, on the host\'s `__host.post`, `__host.receive`,\n// `__host.sleep`, `__host.now` and `__host.fetch`. While the view has handlers, hooks are registered or a frame is\n// awaited, a pump receives client messages and calls handlers and hooks between the program\'s awaits.\nconst widget = (() => {\n const hooks = { key: [], focus: [], fullscreen: [], capture: [], resumed: [], storage: [] }\n // `widget.storage` (widgets-live.md, Storage): the client\'s copy of the widget template\'s space, JSON text by key,\n // from `__input().storage`; `undefined` on a client without storage, `null` without the capability.\n const store = { input: undefined, values: new Map(), bytes: 0 }\n const live = {\n frame: null,\n requested: false,\n waiting: [],\n // The last rendered view as built, and whether the host found handlers in it.\n root: undefined,\n interactive: false,\n pumping: false,\n done: false,\n idle: null,\n reject: null,\n }\n const api = {}\n // `widget.gpu`, made for a live run only: steps never pay for it.\n const made = { gpu: null }\n const gpu = () => (made.gpu ??= __widget_gpu(() => pump()))\n const post = (message) => (live.done ? undefined : __host.post(message))\n // The pending GPU batch goes out on its own before any wait on the host but a frame request, which carries it.\n const flush = () => {\n const batch = gpu().take()\n if (batch) post({ type: "gpu", ops: batch.ops, bytes: batch.bytes })\n }\n const wanted = () =>\n !live.done &&\n (live.waiting.length > 0 ||\n live.interactive ||\n gpu().watched() ||\n Object.values(hooks).some((list) => list.length > 0))\n const fail = (error) => live.reject?.(error)\n // Runs a handler or hook; an async one that rejects fails the program like a throw.\n const call = (handler, ...args) => {\n const result = handler(...args)\n if (result && typeof result.then === "function") result.then(undefined, fail)\n }\n const emit = (kind, ...values) => hooks[kind].slice().forEach((hook) => call(hook, ...values))\n const dispatch = (event) => {\n if (event.type === "key") {\n const key = __widget_key(event.value)\n if (!key) return\n if (key.kind === "down") api.keys.add(key.code)\n else api.keys.delete(key.code)\n return emit("key", key)\n }\n if (event.type === "focus") {\n if (event.value !== true) api.keys.clear()\n return emit("focus", event.value === true)\n }\n if (event.type === "fullscreen") return emit("fullscreen", event.value === true, __widget_rect(event.close))\n if (event.type === "capture") return emit("capture", event.value === true)\n // A wheel isn\'t where the pointer is held: `widget.pointer` keeps the last down, move or up.\n if (event.type === "pointer" && event.value?.kind !== "wheel")\n api.pointer = __widget_pointer(event.value) ?? api.pointer\n const entry = __widget_find(live.root, event.id, event.type)\n if (!entry || entry.event !== event.type) return\n const value = __widget_value(entry, event.value)\n if (value === undefined) return\n if (event.type === "press" && entry.node.type !== "table") call(entry.handler)\n else call(entry.handler, value)\n }\n const accept = (message) => {\n if (message.type === "event") return dispatch(message.event ?? {})\n if (message.type === "canvas" || message.type === "gpu") return gpu().accept(message)\n if (message.type === "resumed") return emit("resumed", message.pausedMs)\n if (message.type === "storage") return changed(message)\n if (message.type !== "frame") return\n live.requested = false\n live.frame = message.frame\n // Every waiter gets this frame: one left over from a race (`Promise.race([widget.frame(), ...])`) too.\n const waiting = live.waiting.splice(0)\n if (waiting.length > 0) {\n const frame = take()\n waiting.forEach((resolve) => resolve(frame))\n }\n }\n const pump = async () => {\n if (live.pumping) return\n live.pumping = true\n try {\n while (wanted()) {\n flush()\n accept(await __host.receive())\n }\n } catch (error) {\n fail(error)\n } finally {\n live.pumping = false\n if (!wanted()) live.idle?.()\n }\n }\n const request = () => {\n const batch = gpu().take()\n if (live.requested || live.frame) {\n if (batch) post({ type: "gpu", ops: batch.ops, bytes: batch.bytes })\n return\n }\n live.requested = true\n post(batch ? { type: "frame", gpu: batch } : { type: "frame" })\n }\n // A change to the space from elsewhere (another device or another widget of this template), in the server\'s order.\n // One that leaves the copy as it is, such as this run\'s own write coming back, fires no hook.\n const changed = (message) => {\n if (!store.input || typeof message.key !== "string") return\n const value = typeof message.value === "string" ? message.value : undefined\n if (store.values.get(message.key) === value) return\n keep(message.key, value)\n emit("storage", { key: message.key, value: value === undefined ? null : parsed(value) })\n }\n const keep = (key, value) => {\n const before = store.values.get(key)\n if (before !== undefined) store.bytes -= __widget_utf8(key) + __widget_utf8(before)\n if (value === undefined) return void store.values.delete(key)\n store.values.set(key, value)\n store.bytes += __widget_utf8(key) + __widget_utf8(value)\n }\n const parsed = (text) => {\n try {\n return JSON.parse(text)\n } catch (error) {\n return text\n }\n }\n const storage = () => {\n if (store.input === undefined)\n throw __widget_storage_error(\n "Unsupported",\n "storage needs a client with spaces sync (OpenCode desktop or Android); this client has none",\n )\n if (store.input === null)\n throw __widget_storage_error(\n "CapabilityDenied",\n "storage is not declared: save the widget template with capabilities: { storage: {} }",\n )\n return store\n }\n const key = (call, value) => {\n if (typeof value !== "string" || value.length === 0)\n throw new TypeError("widget.storage." + call + " needs a key that is a non-empty string")\n if (value.length > __WIDGET_STORAGE.key)\n throw __widget_storage_error("TooLarge", "a key is longer than " + __WIDGET_STORAGE.key + " characters")\n return value\n }\n const take = () => {\n const frame = live.frame\n live.frame = null\n return frame\n }\n const response = (raw) => {\n const text = raw.body ?? atob(raw.body64 ?? "")\n return {\n ok: raw.status >= 200 && raw.status < 300,\n status: raw.status,\n headers: raw.headers ?? {},\n text: async () => text,\n json: async () => JSON.parse(text),\n }\n }\n Object.assign(api, {\n keys: new Set(),\n pointer: null,\n render: (node) => {\n live.root = node\n try {\n live.interactive = post({ type: "render", node }) === true\n } catch (error) {\n // A view too deep to cross: the host fails the run with the reason.\n if (!__widget_deep([node], 1)) throw error\n post({ type: "render", node: null, failure: __WIDGET_DEEP })\n }\n pump()\n },\n // The host knows the canvases by key, and throws for an unknown one or a GPU canvas.\n draw: (key, commands) =>\n void post({\n type: "draw",\n key: String(key),\n commands: commands instanceof __WidgetDraw ? commands.commands : commands,\n }),\n frame: async () => {\n request()\n if (live.frame) return take()\n const next = new Promise((resolve) => live.waiting.push(resolve))\n pump()\n return next\n },\n on: (kind, hook) => {\n if (!hooks[kind]) throw new Error(\'widget.on: unknown event "\' + kind + \'"\')\n if (typeof hook !== "function") throw new Error("widget.on needs a function")\n hooks[kind].push(hook)\n pump()\n return () => {\n const index = hooks[kind].indexOf(hook)\n if (index !== -1) hooks[kind].splice(index, 1)\n }\n },\n sleep: (ms) => {\n flush()\n return __host.sleep(ms)\n },\n now: () => __host.now(),\n submit: (value) => {\n post({ type: "submit", value: value ?? null })\n live.done = true\n },\n dismiss: () => {\n post({ type: "dismiss" })\n live.done = true\n },\n fetch: async (url, init) => {\n flush()\n const request = { url: String(url), method: init?.method ?? "GET", headers: init?.headers ?? {} }\n if (init?.body !== undefined) request.body = String(init.body)\n try {\n return response(await __host.fetch(request))\n } catch (error) {\n throw error?.kind ? error : { kind: "Network", message: error?.message ?? String(error) }\n }\n },\n storage: {\n get: (name) => {\n const text = storage().values.get(key("get", name))\n return text === undefined ? undefined : parsed(text)\n },\n keys: (prefix) => {\n const start = prefix === undefined ? "" : String(prefix)\n return [...storage().values.keys()].filter((name) => name.startsWith(start)).sort()\n },\n set: (name, value) => {\n const current = storage()\n name = key("set", name)\n const text = JSON.stringify(value === undefined ? null : value)\n if (typeof text !== "string") throw new TypeError("widget.storage.set needs a JSON value")\n if (__widget_utf8(text) > __WIDGET_STORAGE.value)\n throw __widget_storage_error("TooLarge", "a value is over " + (__WIDGET_STORAGE.value >> 10) + " KiB of JSON")\n const before = current.values.get(name)\n if (before === undefined && current.values.size >= __WIDGET_STORAGE.keys)\n throw __widget_storage_error("TooLarge", "storage holds " + __WIDGET_STORAGE.keys + " keys already")\n const bytes =\n current.bytes +\n __widget_utf8(name) +\n __widget_utf8(text) -\n (before === undefined ? 0 : __widget_utf8(name) + __widget_utf8(before))\n if (bytes > __WIDGET_STORAGE.bytes)\n throw __widget_storage_error("TooLarge", "storage would hold over " + (__WIDGET_STORAGE.bytes >> 20) + " MiB")\n keep(name, text)\n post({ type: "storage", key: name, value: text })\n return Promise.resolve()\n },\n delete: (name) => {\n const current = storage()\n name = key("delete", name)\n if (!current.values.has(name)) return Promise.resolve()\n keep(name, undefined)\n post({ type: "storage", key: name })\n return Promise.resolve()\n },\n },\n send: (value, options) => post({ type: "send", value: value ?? null, wake: options?.wake !== false }),\n capturePointer: () => post({ type: "capture", value: true }),\n releasePointer: () => post({ type: "capture", value: false }),\n })\n Object.defineProperty(api, "gpu", { get: () => gpu().api, enumerable: true })\n // Runs `main`, then keeps the widget interactive while its view has handlers or hooks are registered.\n // `gpu`: the live input\'s `{ available, format }` (specs/v2/widgets-gpu.md), none without a GPU.\n api.__run = async (data, gpuInput, storageInput) => {\n gpu().start(gpuInput)\n store.input = storageInput === undefined ? undefined : storageInput && { entries: storageInput.entries ?? [] }\n store.input?.entries.forEach((entry) => keep(String(entry.key), String(entry.value)))\n const failed = new Promise((_, reject) => (live.reject = reject))\n failed.catch(() => {})\n await Promise.race([main(data), failed])\n flush()\n if (!wanted()) return\n await Promise.race([new Promise((resolve) => (live.idle = resolve)), failed])\n }\n return api\n})()\n\n// Hosts run `return await __widget_live(__input(), true)` (specs/v2/widgets.md, Native hosts).\nasync function __widget_live(input) {\n await widget.__run(input.data, input.gpu, input.storage)\n return null\n}\n'
export const suggestions =
'function init(data) {\n return { picked: null, note: "" }\n}\n\nfunction view(state, data) {\n return ui.column({ gap: 2 }, [\n ui.text(data.title, { style: "title" }),\n ui.row(\n { gap: 2, align: "start", wrap: true },\n data.options.map((option, index) =>\n ui.card({ selected: state.picked === index, onPress: (state) => ({ ...state, picked: index }) }, [\n option.images.length === 1\n ? ui.image(option.images[0], { alt: option.label, aspect: 4 / 3 })\n : ui.carousel(\n {},\n option.images.map((src, page) =>\n ui.image(src, {\n alt: option.label + " (" + (page + 1) + "/" + option.images.length + ")",\n aspect: 4 / 3,\n }),\n ),\n ),\n ui.row({ gap: 1, align: "center", wrap: true }, [\n ui.text(option.label, { style: "body" }),\n option.recommended && ui.text("(Recommended)", { style: "caption", tone: "accent" }),\n ]),\n option.note && ui.text(option.note, { style: "caption", tone: "muted" }),\n ]),\n ),\n ),\n data.allowNote !== false &&\n ui.input(state.note, {\n label: "Note",\n placeholder: "Add a note (optional)",\n onChange: (state, note) => ({ ...state, note }),\n }),\n ui.row({ gap: 1, align: "center" }, [\n ui.button("Choose", {\n variant: "primary",\n disabled: state.picked === null,\n onPress: (state) => choose(state, data),\n }),\n ui.button("Dismiss", { variant: "secondary", onPress: () => dismiss() }),\n ]),\n ])\n}\n\nfunction choose(state, data) {\n if (state.picked === null) return state\n const note = state.note.trim()\n const choice = { choice: data.options[state.picked].label, index: state.picked }\n return submit(note ? { ...choice, note } : choice)\n}\n'
export const form =
diff --git a/packages/widget/src/tree.ts b/packages/widget/src/tree.ts
index 647d613844d..b7ac79a85b4 100644
--- a/packages/widget/src/tree.ts
+++ b/packages/widget/src/tree.ts
@@ -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 = {
+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 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,
+ },
]
diff --git a/packages/widget/test/fixtures/wire/function-as-a-child.json b/packages/widget/test/fixtures/wire/function-as-a-child.json
index a4f72cfbe8a..4d7217570c1 100644
--- a/packages/widget/test/fixtures/wire/function-as-a-child.json
+++ b/packages/widget/test/fixtures/wire/function-as-a-child.json
@@ -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)"
}
}
diff --git a/packages/widget/test/fixtures/wire/function-as-an-id.json b/packages/widget/test/fixtures/wire/function-as-an-id.json
index b0a764341ea..dc19b1e109d 100644
--- a/packages/widget/test/fixtures/wire/function-as-an-id.json
+++ b/packages/widget/test/fixtures/wire/function-as-an-id.json
@@ -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)"
}
}
diff --git a/packages/widget/test/fixtures/wire/function-in-a-prop.json b/packages/widget/test/fixtures/wire/function-in-a-prop.json
index 7345ef9f5f1..aaefbbb3abf 100644
--- a/packages/widget/test/fixtures/wire/function-in-a-prop.json
+++ b/packages/widget/test/fixtures/wire/function-in-a-prop.json
@@ -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)"
}
}
diff --git a/packages/widget/test/fixtures/wire/function-in-an-option.json b/packages/widget/test/fixtures/wire/function-in-an-option.json
index 875623cd97f..720bf837f9c 100644
--- a/packages/widget/test/fixtures/wire/function-in-an-option.json
+++ b/packages/widget/test/fixtures/wire/function-in-an-option.json
@@ -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)"
}
}
diff --git a/packages/widget/test/fixtures/wire/tables.json b/packages/widget/test/fixtures/wire/tables.json
new file mode 100644
index 00000000000..63e434afb29
--- /dev/null
+++ b/packages/widget/test/fixtures/wire/tables.json
@@ -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": {}
+ }
+}
diff --git a/packages/widget/test/table.test.ts b/packages/widget/test/table.test.ts
new file mode 100644
index 00000000000..95ca46dd146
--- /dev/null
+++ b/packages/widget/test/table.test.ts
@@ -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()
+})
diff --git a/packages/widget/test/wire.test.ts b/packages/widget/test/wire.test.ts
index dcb517d0b67..0f6cf932cd8 100644
--- a/packages/widget/test/wire.test.ts
+++ b/packages/widget/test/wire.test.ts
@@ -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)
diff --git a/packages/widgets-rs/README.md b/packages/widgets-rs/README.md
index 03b209c660f..d1f93564f7c 100644
--- a/packages/widgets-rs/README.md
+++ b/packages/widgets-rs/README.md
@@ -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).
diff --git a/packages/widgets-rs/crates/widget-mobile/tests/wire.rs b/packages/widgets-rs/crates/widget-mobile/tests/wire.rs
index 700dad2c205..d4ffe9ffcce 100644
--- a/packages/widgets-rs/crates/widget-mobile/tests/wire.rs
+++ b/packages/widgets-rs/crates/widget-mobile/tests/wire.rs
@@ -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`).
diff --git a/packages/widgets-rs/crates/widget-web/README.md b/packages/widgets-rs/crates/widget-web/README.md
index 7eed618a4b2..f4dd5b8810c 100644
--- a/packages/widgets-rs/crates/widget-web/README.md
+++ b/packages/widgets-rs/crates/widget-web/README.md
@@ -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 to 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
diff --git a/packages/widgets-rs/crates/widget-web/src/tree.rs b/packages/widgets-rs/crates/widget-web/src/tree.rs
index 9d3128ebce6..b640a4bc981 100644
--- a/packages/widgets-rs/crates/widget-web/src/tree.rs
+++ b/packages/widgets-rs/crates/widget-web/src/tree.rs
@@ -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) {
diff --git a/packages/widgets-rs/crates/widget-web/tests/tree.rs b/packages/widgets-rs/crates/widget-web/tests/tree.rs
index 78aa115dc1c..65cc6f89934 100644
--- a/packages/widgets-rs/crates/widget-web/tests/tree.rs
+++ b/packages/widgets-rs/crates/widget-web/tests/tree.rs
@@ -169,7 +169,7 @@ fn fixtures() -> Vec {
});
}
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).
diff --git a/packages/widgets-rs/crates/widget-wire/src/decode.rs b/packages/widgets-rs/crates/widget-wire/src/decode.rs
index 39d1a09265f..c7b502a372e 100644
--- a/packages/widgets-rs/crates/widget-wire/src/decode.rs
+++ b/packages/widgets-rs/crates/widget-wire/src/decode.rs
@@ -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,
inset: Option,
+ columns: Option>,
+ aligns: Vec,
+ cells: Option>,
+ sort: Option>,
+ row: Option,
+ 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::>();
+ 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")?,
diff --git a/packages/widgets-rs/crates/widget-wire/src/encode.rs b/packages/widgets-rs/crates/widget-wire/src/encode.rs
index af2cc716f1a..4e05ec8cbe2 100644
--- a/packages/widgets-rs/crates/widget-wire/src/encode.rs
+++ b/packages/widgets-rs/crates/widget-wire/src/encode.rs
@@ -959,6 +959,87 @@ fn option(o: &Option) -> Option> {
}
/// 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::