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::>>() + else { + return; + }; + s.tag(39, K_STRS); + s.int(labels.len() as u32); + for label in &labels { + s.str(label); + } + s.tag(40, K_F64S); + s.int(columns.len() as u32); + for c in columns.iter().flatten() { + let end = + matches!(field(c, "align"), Some(HostValue::String(a)) if a.as_str() == Some("end")); + s.f64(if end { 1.0 } else { 0.0 }); + } + fn cell(c: Option<&HostValue>) -> Option> { + match c { + None | Some(HostValue::Undefined) => Some(Cow::Borrowed("")), + Some(HostValue::String(t)) => Some(lossy(t)), + Some(HostValue::Number(n)) if n.is_finite() => { + Some(Cow::Owned(crate::native::js_number(*n))) + } + _ => None, + } + } + let rows = match field(v, "rows") { + Some(HostValue::Array(rows)) => rows + .iter() + .map(|row| match row { + Some(HostValue::Array(cells)) if cells.len() <= labels.len() => (0..labels.len()) + .map(|i| cell(cells.get(i).and_then(Option::as_ref))) + .collect::>>(), + _ => None, + }) + .collect::>>(), + _ => None, + }; + if let Some(rows) = rows { + s.tag(41, K_STRS); + s.int((rows.len() * labels.len()) as u32); + for c in rows.iter().flatten() { + s.str(c); + } + } + if let Some(sort) = field(v, "sort") + && let Some(column) = field(sort, "column").and_then(finite) + { + s.tag(42, K_F64S); + s.int(2); + s.f64(column); + s.f64( + if matches!(field(sort, "descending"), Some(HostValue::Bool(true))) { + 1.0 + } else { + 0.0 + }, + ); + } + if let Some(row) = field(v, "selected") + .and_then(finite) + .filter(|r| *r >= 0.0 && r.fract() == 0.0) + { + s.tag(43, K_INT); + s.int(row as u32); + } +} + pub(crate) fn prop(s: &mut Streams, key: &str, v: &HostValue) { let id = prop_id(key); if id == 0 { @@ -1083,6 +1164,10 @@ pub(crate) fn write_node(s: &mut Streams, v: &HostValue, depth: usize) -> Result return Ok(()); } let mut kids: &[Option] = &[]; + // A table's columns and rows first, as the native walk writes them. + if t == T_TABLE { + table_props(s, v); + } for (k, v) in fields { let Some(k) = k.as_str() else { continue }; match k { diff --git a/packages/widgets-rs/crates/widget-wire/src/native.rs b/packages/widgets-rs/crates/widget-wire/src/native.rs index a2ba65dc069..4c38428b897 100644 --- a/packages/widgets-rs/crates/widget-wire/src/native.rs +++ b/packages/widgets-rs/crates/widget-wire/src/native.rs @@ -10,7 +10,7 @@ use std::fmt::Write as _; use psychoscript::HostValue; use crate::encode::{Streams, field, json_value, prop, write_node}; -use crate::schema::{K_INT, K_STR, T_UNKNOWN, is_container, type_id}; +use crate::schema::{K_INT, K_STR, T_TABLE, T_UNKNOWN, is_container, type_id}; /// The most levels a view nests (`widgets.md`, Keys and depth). pub const LEVELS: usize = 100; @@ -51,6 +51,8 @@ pub(crate) enum Stop { struct Control { handler: &'static str, event: &'static str, + /// A table's second handler, a header's press (`change`). + sort: Option<&'static str>, always: bool, canvas: bool, } @@ -62,18 +64,20 @@ fn control(ty: &str) -> Option { "checkbox" | "slider" | "select" | "input" => ("onChange", "change", true, false), "carousel" => ("onChange", "change", false, false), "canvas" => ("onPointer", "pointer", false, true), + "table" => ("onPress", "press", false, false), _ => return None, }; Some(Control { handler, event, + sort: (ty == "table").then_some("onSort"), always, canvas, }) } fn handler_prop(k: &str) -> bool { - matches!(k, "onPress" | "onChange" | "onPointer") + matches!(k, "onPress" | "onChange" | "onPointer" | "onSort") } /// Whether `v` holds a function marker anywhere. @@ -267,6 +271,12 @@ impl Walk { Some(s) if t != T_UNKNOWN => Some(s), _ => None, }; + // A table's columns and rows first (`encode::table_props`). + if t == T_TABLE + && let Some(st) = props.as_deref_mut() + { + crate::encode::table_props(st, &json_value(v)); + } for (k, pv) in fields { let Some(k) = k.as_str() else { if marked(pv) { @@ -281,15 +291,21 @@ impl Walk { return Err(Stop::Function); } if let Some(st) = props.as_deref_mut() - && !matches!(k, "type" | "key" | "id" | "pointer") + && !matches!( + k, + "type" | "key" | "id" | "pointer" | "selectable" | "sortable" + ) { prop(st, k, &json_value(pv)); } } if let Some(c) = control(&name) { let handled = matches!(field(v, c.handler), Some(HostValue::FunctionMarker)); + let sorted = c + .sort + .is_some_and(|k| matches!(field(v, k), Some(HostValue::FunctionMarker))); let keyed = if c.canvas { key(v)? } else { None }; - if handled || c.always || keyed.is_some() { + if handled || sorted || c.always || keyed.is_some() { if let Some(st) = props.as_deref_mut() { st.tag(10, K_STR); st.str(&self.path); @@ -297,9 +313,20 @@ impl Walk { st.tag(35, K_INT); st.int(1); } + if t == T_TABLE && handled { + st.tag(44, K_INT); + st.int(1); + } + if sorted { + st.tag(45, K_INT); + st.int(1); + } } - if handled { - self.found.handlers.push((self.path.clone(), c.event)); + // A table with both handlers is listed by its row press. + if handled || sorted { + self.found + .handlers + .push((self.path.clone(), if handled { c.event } else { "change" })); } if let Some(k) = keyed { let k = key_string(k); diff --git a/packages/widgets-rs/crates/widget-wire/src/node.rs b/packages/widgets-rs/crates/widget-wire/src/node.rs index c3d932b3b7a..d82613c9272 100644 --- a/packages/widgets-rs/crates/widget-wire/src/node.rs +++ b/packages/widgets-rs/crates/widget-wire/src/node.rs @@ -55,6 +55,53 @@ pub enum ButtonVariant { Secondary, } +/// Where a table column's cells sit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ColumnAlign { + End, + #[default] + #[serde(other)] + Start, +} + +#[derive(Clone, Debug, PartialEq, Deserialize)] +pub struct TableColumn { + pub label: String, + #[serde(default)] + pub align: ColumnAlign, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] +pub struct TableSort { + pub column: usize, + #[serde(default)] + pub descending: bool, +} + +/// A table cell as it shows: a string, or a number as `String(number)`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Cell(pub String); + +impl<'de> Deserialize<'de> for Cell { + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Text(String), + Number(f64), + } + Ok(Cell(match Raw::deserialize(d)? { + Raw::Text(t) => t, + Raw::Number(n) => crate::native::js_number(n), + })) + } +} + +/// A table's limits (`widgets.md`, Table). +pub const MAX_COLUMNS: usize = 16; +pub const MAX_ROWS: usize = 500; + #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct SelectOption { pub value: String, @@ -187,6 +234,21 @@ pub enum Node { multiline: bool, }, Divider, + /// Rows of text under a header (`widgets.md`, Table). Decoded, every row is as wide as `columns`. + Table { + #[serde(default)] + id: Option, + columns: Vec, + rows: Vec>, + #[serde(default)] + sort: Option, + #[serde(default)] + selected: Option, + #[serde(default)] + selectable: bool, + #[serde(default)] + sortable: bool, + }, Canvas { #[serde(default)] id: Option, @@ -260,6 +322,31 @@ impl Node { pub(crate) fn check(&self) -> Result<(), String> { let mut bad = None; self.walk(&mut |n| { + if let Node::Table { + columns, + rows, + sort, + selected, + .. + } = n + { + let why = if columns.is_empty() || columns.len() > MAX_COLUMNS { + Some(format!("a table has 1 to {MAX_COLUMNS} columns")) + } else if rows.len() > MAX_ROWS { + Some(format!("a table has at most {MAX_ROWS} rows")) + } else if rows.iter().any(|r| r.len() > columns.len()) { + Some("a row has more cells than there are columns".to_owned()) + } else if sort.is_some_and(|s| s.column >= columns.len()) { + Some("`sort.column` must be one of the columns".to_owned()) + } else if selected.is_some_and(|r| r >= rows.len()) { + Some("`selected` must be one of the rows".to_owned()) + } else { + None + }; + if let Some(why) = why { + bad.get_or_insert(why); + } + } if let Node::Canvas { wgsl, values, gpu, .. } = n diff --git a/packages/widgets-rs/crates/widget-wire/src/schema.rs b/packages/widgets-rs/crates/widget-wire/src/schema.rs index 6f7d2565461..1ba8ece3491 100644 --- a/packages/widgets-rs/crates/widget-wire/src/schema.rs +++ b/packages/widgets-rs/crates/widget-wire/src/schema.rs @@ -11,6 +11,7 @@ pub(crate) const K_OPTS: u32 = 5; /// A node type the host doesn't know; its name follows in the string stream. pub(crate) const T_UNKNOWN: u32 = 63; pub(crate) const T_STACK: u32 = 16; +pub(crate) const T_TABLE: u32 = 17; /// Top-level message kinds, after the version byte. pub(crate) const STEP: u8 = b'S'; @@ -43,6 +44,7 @@ pub(crate) fn type_id(name: &str) -> u32 { "divider" => 13, "canvas" => 14, "stack" => T_STACK, + "table" => T_TABLE, _ => T_UNKNOWN, } } @@ -91,6 +93,10 @@ pub(crate) fn prop_id(key: &str) -> u32 { "place" => 36, "inset" => 37, "gpu" => 38, + // A table's `columns`, `rows`, `sort` and row `selected` (39 to 43) are written from the whole node + // (`encode::table_props`). + "selectable" => 44, + "sortable" => 45, _ => 0, } } @@ -135,7 +141,7 @@ pub(crate) fn shape(id: u32) -> Shape { 6 => Shape::Enum(TONE), 14 => Shape::Enum(VARIANT), 36 => Shape::Enum(PLACE), - 3 | 12 | 15 | 16 | 22 | 24 | 32 | 33 | 35 | 38 => Shape::Bool, + 3 | 12 | 15 | 16 | 22 | 24 | 32 | 33 | 35 | 38 | 44 | 45 => Shape::Bool, 4 | 7 | 8 | 10 | 13 | 23 | 29 | 31 | 34 => Shape::Str, 17 => Shape::Value, 21 => Shape::Options, diff --git a/packages/widgets-rs/crates/widget-wire/tests/native.rs b/packages/widgets-rs/crates/widget-wire/tests/native.rs index 6f285edd7e0..0338befc8b5 100644 --- a/packages/widgets-rs/crates/widget-wire/tests/native.rs +++ b/packages/widgets-rs/crates/widget-wire/tests/native.rs @@ -37,7 +37,7 @@ fn fixtures() -> Vec<(String, Value)> { }) .collect(); list.sort_by(|a, b| a.0.cmp(&b.0)); - assert_eq!(list.len(), 58); + assert_eq!(list.len(), 59); list } @@ -107,7 +107,7 @@ fn steps_encode_the_fixtures() { } checked += 1; } - assert_eq!(checked, 57); + assert_eq!(checked, 58); } #[test] diff --git a/packages/widgets-rs/crates/widget-wire/tests/roundtrip.rs b/packages/widgets-rs/crates/widget-wire/tests/roundtrip.rs index f3d50c8d8ae..779e2a31f73 100644 --- a/packages/widgets-rs/crates/widget-wire/tests/roundtrip.rs +++ b/packages/widgets-rs/crates/widget-wire/tests/roundtrip.rs @@ -301,6 +301,7 @@ fn every_post_kind_decodes_as_its_json() { return [ {{ type: "render", node: {EVERY_NODE}.view }}, {{ type: "render", node: {{ type: "text", text: "small" }} }}, + {{ type: "render", node: {{ type: "table", columns: [{{ label: "Day" }}, {{ label: "kg", align: "end" }}], rows: [["Nov 27", 79.6], ["Nov 26", 1e21]], sort: {{ column: 1, descending: true }}, selected: 1, id: "0/:t", selectable: true, sortable: true }} }}, {{ type: "draw", id: "0/:chart", commands: {EVERY_COMMAND} }}, {{ type: "draw", id: "", commands: [] }}, {{ type: "frame" }}, @@ -327,11 +328,11 @@ fn every_post_kind_decodes_as_its_json() { }}) }})()"## )); - assert_eq!(pairs.len(), 21); + assert_eq!(pairs.len(), 22); for (i, (bin, json)) in pairs.iter().enumerate() { assert_eq!(bin, json, "post {i}"); } - let Post::FrameGpu(b) = &pairs[5].0 else { + let Post::FrameGpu(b) = &pairs[6].0 else { panic!() }; assert_eq!(&b.bytes[..4], &0.5f32.to_le_bytes()); diff --git a/packages/widgets-rs/web/src/render.ts b/packages/widgets-rs/web/src/render.ts index 392168cc039..ea28c84a0a0 100644 --- a/packages/widgets-rs/web/src/render.ts +++ b/packages/widgets-rs/web/src/render.ts @@ -79,6 +79,7 @@ const KNOWN = new Set([ "select", "input", "divider", + "table", "canvas", "stack", ]) @@ -524,6 +525,49 @@ const BUILDERS: Record = { } return { el, rec } }, + // A table (widgets.md, Table): a header with the sort indicator, rows as text, scrolling sideways when it is wider + // than the widget; a row press sends `press` with its index and a header press `change` with the column's. + table(ctx) { + const el = h(ctx, "div", "pw-table") + const rec: Rec = { + type: "table", + node: { type: "table" }, + update(n) { + const columns = (Array.isArray(n.columns) ? n.columns : []) as { label?: unknown; align?: unknown }[] + const rows = (Array.isArray(n.rows) ? n.rows : []) as unknown[][] + const sort = n.sort as { column?: unknown; descending?: unknown } | undefined + const table = h(ctx, "table") + const head = table.createTHead().insertRow() + columns.forEach((column, index) => { + const cell = h(ctx, "th") + cell.textContent = str(column.label) + if (sort?.column === index) cell.textContent += sort.descending === true ? " ▼" : " ▲" + if (column.align === "end") cell.className = "pw-end" + if (n.sortable === true && !ctx.readOnly()) { + cell.classList.add("pw-press") + cell.addEventListener("click", () => ctx.emit({ id: str(rec.node.id), type: "change", value: index })) + } + head.append(cell) + }) + const body = table.createTBody() + rows.forEach((cells, row) => { + const tr = body.insertRow() + if (n.selected === row) tr.className = "pw-on" + if (n.selectable === true && !ctx.readOnly()) { + tr.classList.add("pw-press") + tr.addEventListener("click", () => ctx.emit({ id: str(rec.node.id), type: "press", value: row })) + } + columns.forEach((column, index) => { + const cell = tr.insertCell() + cell.textContent = str(Array.isArray(cells) ? cells[index] : undefined) + if (column.align === "end") cell.className = "pw-end" + }) + }) + el.replaceChildren(table) + }, + } + return { el, rec } + }, divider(ctx) { const el = h(ctx, "hr", "pw-divider") return { el, rec: { type: "divider", node: { type: "divider" }, update() {} } } diff --git a/packages/widgets-rs/web/src/styles.ts b/packages/widgets-rs/web/src/styles.ts index 3ae24a9f020..23fdd8adc02 100644 --- a/packages/widgets-rs/web/src/styles.ts +++ b/packages/widgets-rs/web/src/styles.ts @@ -108,6 +108,14 @@ export const CSS: string = /* css */ ` .pw-option[aria-checked="true"] .pw-mark { border-color: var(--pw-accent); background: var(--pw-accent); box-shadow: inset 0 0 0 2px var(--pw-bg); } .pw-option-text { display: flex; flex-direction: column; min-width: 0; } .pw-option-desc { font-size: 12px; color: var(--pw-muted); } +.pw-table { overflow-x: auto; max-width: 100%; } +.pw-table table { border-collapse: collapse; font-size: 13px; line-height: 1.4; } +.pw-table th, .pw-table td { border: 1px solid var(--pw-border); padding: 6px 10px; text-align: left; white-space: nowrap; } +.pw-table th { font-weight: 600; background: var(--pw-surface); } +.pw-table .pw-end { text-align: right; font-variant-numeric: tabular-nums; } +.pw-table .pw-press { cursor: pointer; } +.pw-table tr.pw-press:hover td, .pw-table th.pw-press:hover { background: var(--pw-surface); } +.pw-table tr.pw-on td { background: color-mix(in srgb, var(--pw-accent) 14%, transparent); } .pw-divider { border: 0; border-top: 1px solid var(--pw-border); margin: 2px 0; width: 100%; } .pw-carousel { position: relative; overflow: hidden; border-radius: calc(var(--pw-radius) - 2px); touch-action: pan-y; outline: none; min-width: 0; } .pw-carousel:focus-visible { box-shadow: 0 0 0 2px var(--pw-accent); } diff --git a/specs/v2/widgets-binary.md b/specs/v2/widgets-binary.md index 7dd777a394a..699122d0638 100644 --- a/specs/v2/widgets-binary.md +++ b/specs/v2/widgets-binary.md @@ -72,7 +72,7 @@ varint type, (varint tag, value)*, varint 0, [varint childCount, node × childCo ``` **Types:** 1 column, 2 row, 3 text, 4 markdown, 5 image, 6 carousel, 7 card, 8 button, 9 checkbox, 10 slider, -11 select, 12 input, 13 divider, 14 canvas, 16 stack. Containers: 1, 2, 6, 7, 16. Type 63 is a node type the host +11 select, 12 input, 13 divider, 14 canvas, 16 stack, 17 table. Containers: 1, 2, 6, 7, 16. Type 63 is a node type the host doesn't know: the I stream holds 63 and then 0, and the S stream holds its name. Clients drop it like an unknown type today. @@ -111,6 +111,13 @@ today. | 18 | min | f64 | 36 | place | int: top-left 0, top 1, top-right 2, left 3, center 4, right 5, bottom-left 6, bottom 7, bottom-right 8, fill 9 | | | | | 37 | inset | f64 (all sides) or f64 list of 4 (top, right, bottom, left) | | | | | 38 | gpu | int (a GPU canvas, `widgets-gpu.md`) | +| | | | 39 | columns | str list: the columns' labels | +| | | | 40 | columns' `align` | f64 list, one per column: start 0, end 1 | +| | | | 41 | rows | str list: the cells row by row, each row as wide as `columns` (a missing cell is `""`; a number as `String(number)`) | +| | | | 42 | sort | f64 list: column, then 1 when `descending` else 0 | +| | | | 43 | table's `selected` | int: the row | +| | | | 44 | selectable | int | +| | | | 45 | sortable | int | **Rules for the encoder** (`write_node`). It writes the props the tree has, in its key order: - `type` and `children` are never props. @@ -119,6 +126,9 @@ today. knows (the client then uses its default), or a value of the wrong JSON type. - It doesn't check required props: the client does, as today, and an invalid view stays a program error. - `place`/`inset` go on any node. They mean something only for a stack's children: the reader keeps them per child. +- A table's `columns` go out as props 39 and 40, its `rows` as prop 41 (as many cells per row as there are columns), + `sort` as 42 and a number `selected` as 43. A table whose `columns` or `rows` aren't lists, or whose cells aren't + strings or numbers, has them left out, and the client takes the view as invalid. **Rules for the decoder.** It skips a tag whose id it doesn't know, by kind. That is the forward-compatibility rule: new props get new ids, and a changed meaning gets a new id. diff --git a/specs/v2/widgets-live.md b/specs/v2/widgets-live.md index 0948439ccb8..c1eddd42dcf 100644 --- a/specs/v2/widgets-live.md +++ b/specs/v2/widgets-live.md @@ -58,7 +58,8 @@ The prelude exposes a `widget` object inside `main` (implemented with `__host`): handlers, and `widget.frame()`, `widget.sleep()` and `Promise.race` cover waiting. **Handlers.** The node props are the same as in step mode (`onPress`, `onChange`, `onPointer`; `widgets.md`, Events), -but a live handler gets only the value (`onPress()`, `onChange(value)`, `onPointer(p)`) and its return value is +but a live handler gets only the value (`onPress()`, `onChange(value)`, `onPointer(p)`; a table's `onPress(row)` and +`onSort(column)`) and its return value is ignored: it changes the program's variables or calls `widget.*`. `render` keeps the node, whose handlers the prelude finds by the ids' paths, and whether the host found any. While the view has handlers, hooks are registered or a frame is awaited, the prelude keeps a `__host.receive()` in flight and diff --git a/specs/v2/widgets.md b/specs/v2/widgets.md index d2f831a93e3..666d11768b8 100644 --- a/specs/v2/widgets.md +++ b/specs/v2/widgets.md @@ -96,7 +96,8 @@ programs use (`widget`, with `widget.gpu`, and `__widget_live`; `widgets-live.md - `ui`: pure node builders, one per node type. Required fields are positional, optional ones and handlers go in `props`: `column|row|carousel|card(props, children)` (or `(children)`), `text(text, props?)`, `markdown(text)`, `image(src, props?)`, `button(label, props?)`, `checkbox(label, checked, props?)`, `slider(props)` (`props` holds - `value`, `min`, `max`), `select(options, props?)` (options may be strings), `input(value, props?)`, `divider()`. + `value`, `min`, `max`), `select(options, props?)` (options may be strings), `input(value, props?)`, `divider()`, + `table(columns, rows, props?)` (columns may be strings). `children` may nest arrays and contain `null`/`undefined`/`false`, which are dropped (`cond && ui.text(...)`). Also `canvas(props)` (with `wgsl` in `props` for a GPU canvas) and `draw()`, the draw command builder (see Canvas). Authors never set `id`; a node's `key` (a string, a number or a boolean) names it among its siblings (Keys and depth). @@ -264,10 +265,12 @@ the widget encoder of `widget-mobile`, Rune's reader, the web host) and the Type 1. The root's path is `:` + enc(root `key`) when the root is an object (not an array) with a key (Keys and depth); otherwise `0`. 2. A value that isn't an object, or is an array, goes out as in 5. An object (a node) goes out with its props in their - order, leaving out `key`, `id`, `pointer`, `onPress`, `onChange`, `onPointer` and `children`. If its `type` is in - the Events table, its handler prop is that type's (`onPress`, `onChange` or `onPointer`); when that prop is a - marker, or the type is `button`, `checkbox`, `slider`, `select` or `input`, or it is a `canvas` with a key, the - node gets `id` (its path) after its props. A `canvas` with a handler then gets `pointer: true`. If `children` + order, leaving out `key`, `id`, `pointer`, `selectable`, `sortable`, `onPress`, `onChange`, `onPointer`, `onSort` + and `children`. If its `type` is in the Events table, its handler props are that type's (`onPress`, `onChange` or + `onPointer`; a `table`'s `onPress` and `onSort`); when one is a marker, or the type is `button`, `checkbox`, + `slider`, `select` or `input`, or it is a `canvas` with a key, the node gets `id` (its path) after its props. A + `canvas` with a handler then gets `pointer: true`; a `table` gets `selectable: true` with an `onPress` and + `sortable: true` with an `onSort`, in that order. If `children` isn't `undefined`, the node gets `children` last: the items below. 3. A `children` value that isn't an array is a list of one. Its items in order, at index `i`: a falsy item (a hole, `undefined`, `null`, `false`, `0`, `NaN`, `""`) is skipped and keeps its index; an array's items come in its place @@ -282,7 +285,7 @@ the widget encoder of `widget-mobile`, Rune's reader, the web host) and the Type 5. Every value goes out as JSON holds it: an `undefined` prop is left out and an `undefined` item is `null`, a non-finite number is `null`. - **Functions where none may go.** A marker in a host call's argument anywhere but the value of a node's `onPress`, - `onChange` or `onPointer` (a node: the view's root, or an object among `children` or an array in them) fails the + `onChange`, `onPointer` or `onSort` (a node: the view's root, or an object among `children` or an array in them) fails the call as a function did without `"mark"`: the host throws, from that call, its runtime's `TypeError` `Argument to contains a function, which cannot be passed to the host.`, with `` the argument's position from 1 and `` the function as the program called it (`__widget_emit`, `__host.post`, `__host.fetch`, ...). So a function @@ -343,6 +346,8 @@ handlers and never see them. The value a client sends, and what the handler gets | `select` | `change`, `value: string` or `string[]` when `multiple` | `onChange(state, value)`, only known option values | | `input` | `change`, `value: string` (on commit / blur / debounce >= 300 ms) | `onChange(state, text)` | | `carousel` | `change`, `value: number` (new page index) | `onChange(state, index)` | +| `table` | `press`, `value: number` (the row pressed, an index into `rows`) | `onPress(state, row)` | +| `table` | `change`, `value: number` (the column whose header was pressed) | `onSort(state, column)` | | `canvas` | `pointer`, `value: { kind, x, y, width, height }` in the node's logical pixels; `move` only while down, at most once per frame (see Canvas) | `onPointer(state, p)`; under pointer capture `p` is `{ kind, dx, dy, button }`, or a wheel's `{ kind, dx, dy }` (`widgets-input.md`, Wheel) | | none (`id: ""`) | `key`, `focus`, `fullscreen`, `capture` | the hooks (Widget template source) | @@ -373,6 +378,10 @@ type Node = ( value?: string | string[]; multiple?: boolean } | { type: "input"; id: string; label?: string; value: string; placeholder?: string; multiline?: boolean } | { type: "divider" } + | { type: "table"; id?: string; columns: { label: string; align?: "start" | "end" }[]; rows: (string | number)[][]; + sort?: { column: number; descending?: boolean }; selected?: number + selectable?: true // set by the prelude when it has onPress: only then do its rows take presses + sortable?: true } // set by the prelude when it has onSort: only then do its headers take presses | { type: "canvas"; id?: string; height: number; width?: number; fps?: number; duration?: number; alt?: string; poster?: string; wgsl?: string; values?: number[] // values only with wgsl pointer?: true // set by the prelude when it has onPointer: only then does it take input @@ -394,6 +403,17 @@ Image `src`: an `https:`/`http:` URL, a `data:` URI, or a path relative to the s relative paths through the server's existing file content endpoint for the session's location. TUI shows `alt` (or the file name) plus the source instead of pixels where it cannot draw images. +Table: a grid of text with a header row, for data (a history, a comparison, a list of records). `columns` holds 1 to +16 columns, each with a `label` and an `align` (`start`, the default, or `end`: use `end` for numbers); `rows` at most +500 rows of at most that many cells, each a string or a number, which shows as JavaScript's `String(number)` (a row +with fewer cells leaves the rest empty). `sort` marks the header of column `sort.column` with an ascending (or, with +`descending`, a descending) indicator; the program sorts `rows` itself. `selected` highlights that row. A table with +more columns or cells, a `sort.column` or `selected` outside them, or a cell that is neither a string nor a number is +an invalid view. With `onPress`, pressing a row sends `press` with its index; with `onSort`, pressing a header sends +`change` with the column's index. Clients draw it like the tables in their markdown (the same fonts, borders, header, +colors and spacing), scroll it sideways when it is wider than the widget, and give it no height limit of its own; the +TUI writes it as aligned text, a line per row. + Carousel: one child visible at a time with paging (swipe on touch, arrows on desktop, left/right keys in the TUI) and a page indicator. A carousel without `id` pages locally; with one (it has an `onChange`) it also emits `change`.