Skip to content

View protocol

This specification defines the contract between the JS logic layer (@weft-ui/runtime/remote and generated remote-mode logic modules) and the view layer (mini program WXML, native platforms, and the headless renderer).

The headless renderer in @weft-ui/runtime/testing is the reference implementation. It encodes and decodes each batch of ops, validates it against the layout, and applies it to an in-memory tree. The golden files in tests/conformance/golden/ contain the op text recorded by this renderer.

ViewLayout (crates/transformer/src/view.rs) is derived from the entire application’s Program. WASM exposes the JSON form through compileApp(...).layout; see crates/transformer/tests/snapshots/TodoList/layout.json for an example.

{
"hash": "a6bb96edf9a9ad2d",
"templates": [
{
"label": "TodoList",
"kind": "component",
"roots": [0],
"nodes": [{"element": "Column", "props": {}, "children": [1, 2]}, {"point": 0}],
"values": [{"node": 1, "prop": "value", "type": "String"}],
"events": [{"node": 1, "event": "onChange", "payload": "String", "controls": 0}],
"points": [{"node": 2, "kind": "branch", "templates": [1]}]
}
]
}
  • Template numbering: Component bodies come first, in Program order, so template i is the body of component i. Next come the if branches (one template per branch), for row bodies, and slot contents within each component, in order of appearance. label is for debugging only: TodoList, TodoList:if8.0 (branch 0 of node 8), TodoList:for7, Board:slot12.
  • Nodes: nodes is the template-local node table, and roots lists the top-level nodes. Element nodes have static props (unbound literals that the platform inlines directly into the template without allocating slots) and children. {"point": n} marks the position of mount point n in the tree.
  • Value slot values[i]: A dynamic property of a node. type is the declared type of the element property: Int / Bool / String / Color. The value of a Color slot is a string parsed by the platform (see Built-in elements and layout for the rules). Static colors are validated at compile time and written in props as normalized #rrggbb or #rrggbbaa values. Controlled properties (Input.value, Checkbox.checked) always use value slots, even when constant.
  • Event slot events[i]: An event property of a node. payload specifies the payload type (null means no payload). Input / Checkbox always have an onChange event slot. Its controls field is the index of the value slot it controls; for all other events, controls is null. JS handles lifecycle properties (onMount / onUnmount), which do not appear in the layout.
  • Mount point points[i]: branch (templates lists branch templates in order), list (template is the row body), instance (template is the body of the instantiated component), or slot (the caller supplies the slot content, which may be any template of kind slot).
  • Hash: The 64-bit FNV-1a hash of the JSON with the hash field removed, represented as 16 hexadecimal digits. It is written into both the JS logic (as an App constructor argument) and the platform view. The sink compares the hashes at open and reports an error if they differ.

At runtime, each template instance is a scope. JS allocates IDs per app, starting at 1 and increasing without reuse. Scope 0 is the virtual root and has only mount point 0. The root component instance is mounted with attach 0 0 <id>.

A scope is created by create and is not yet mounted in the tree. It is implicitly destroyed if it is replaced by branch, no longer appears in rows, or an ancestor is destroyed. Its descendants are destroyed with it. On unmount, the sink receives close, which invalidates all scopes at once.

op Parameters Meaning
create scope, template Create an instance.
set scope, slot, value Write a value to a value slot. The value type matches the slot type.
branch scope, point, child | 0 Switch a branch mount point to child (0 means no branch). The previous child scope is destroyed.
rows scope, point, [child…] Replace the full row order at a list mount point. Rows absent from the new list are destroyed.
attach scope, point, child Mount child at an instance / slot mount point. This op is sent only once per mount point.

Guarantees:

  • One batch of ops corresponds to one flush. The sink applies the entire batch at commit.
  • A new scope’s create and the set ops for all of its value slots are in the same batch, before the op that mounts it. The platform always builds the subtree before inserting it.
  • A new scope’s branch mount points are empty and its list mount points have no rows. No op is sent when state is unchanged: no rows for an initially empty list, no repeat rows for an unchanged order, and no set for an unchanged value.
  • A child at a mount point must be an instance of a template allowed by that mount point. A scope can be mounted at most once.

Only one message goes in the opposite direction: Session.dispatch(scope, slot, payload) → boolean. slot is the event slot index, and the event slot determines the type of payload. JS runs the handler and flushes synchronously, so the sink receives any ops caused by the event before the call returns. The return value indicates whether a controlled edit was accepted. It is true if the event slot has no controls, the scope has been destroyed, or the current value of the controlled value slot equals the payload. On false, the view restores the control to the current value of the controlled value slot (any value rewritten by the host has already arrived via set). Events for destroyed or unknown scopes are ignored and return true.

A batch of ops is a byte sequence: the first byte is the version number 1, followed by consecutive ops. All integers are little-endian u32 values.

opcode op Fields
1 create scope, template
2 set scope, slot, value
3 branch scope, point, child
4 rows scope, point, count, child × count
5 attach scope, point, child

Each value starts with a u8 tag: 0 for false, 1 for true, 2 for a number (little-endian f64, including values in Int slots), or 3 for a string (u32 byte length followed by UTF-8). On the JS side, OpWriter (src/ops.ts in @weft-ui/runtime) reuses the same buffer. The bytes of a batch are valid only until the next write.

Debug dumps and golden files use one op per line, with strings and booleans written as JSON:

create 3 2
set 3 0 "milk"
rows 2 0 [3 4 5]
branch 1 0 0
attach 0 0 1

The headless renderer appends a template label or slot description after #, for example create 1 0 # TodoList or set 1 0 "" # Input.value.

Sink is the platform-side interface (src/remote.ts):

  • open(session): Called once at mount. session provides hash, dispatch, and detach (called when the platform view disappears before the app).
  • create / set / branch / rows / attach: Record ops in the current batch.
  • commit(): Apply the entire batch at the end of a flush.
  • close(): On unmount, discard all scopes.

The mini program sink (./wechat) does not encode ops. It translates them directly into setData paths, using the data layout below. The headless renderer uses binary encoding. The native sink (./native) passes the buffer to __weft.commit; see the next section.

WXML renders only {{key}}. The setData paths are paths in the block data tree (N is the node number in the IR):

Key Contents
n{N}_{i} Property value or text.
e{N} Event handler ID (assigned by the sink), written as data-h in WXML and dispatched by the view component’s $e.
i{N} / b{N} Current if branch index / branch data.
l{N} Array of for rows. Each row carries k (the row’s scope ID, used as wx:key).
c{N} Component instance data.
y{N} Slot data. t is the slot template name ({Component}-s{N}).

setData rules:

  • Each view calls setData only once per flush. The block’s set compares old and new values with === and sends only changed leaves, using paths such as r.b8.l7[2].n3_0.
  • For append-only list changes, send the new rows by index path (l7[3]). On deletion, movement, or insertion, send the full row array. Reused rows retain their handler IDs. Nothing is sent if the order is unchanged.
  • Within a flush, discard paths covered by other paths because an entire ancestor is already being sent.

On native platforms, the JS bundle runs in the kernel in native/core. The kernel embeds Hermes, executes bundle.hbc, and communicates with the platform shell through the C ABI (native/core/include/weft/runtime.h). The platform shell is WeftKit in native/apple for iOS / macOS, the Kotlin module in native/android for Android (loads libweft.so through JNI), Weft.WinUI in native/windows for Windows (loads weft_core.dll through P/Invoke), and the C++ library in native/linux for Linux (links against libweft_core.so). The kernel does not create threads. All functions are called on the UI thread and must not be called reentrantly from a weft_host callback.

The kernel installs this global before running the bundle. The native implementations of @weft-ui/runtime/native and @weft-ui/platform use it:

Member Meaning
open(hash, dispatch) The sink’s open. Throws if hash does not match the layout hash the platform shell passed to weft_runtime_new, or if an app is already open.
commit(buffer, offset, length) A batch of ops. The kernel passes this byte range directly to weft_host.commit without copying it.
close() The sink’s close. Subsequent events are ignored.
supports(module) Whether the platform shell implements the platform module module.
call(module, method, args?) A platform call returning Promise<ArrayBuffer>. args is a string (sent as UTF-8), an ArrayBuffer, or a view of one. If the module is unsupported, the promise immediately rejects with an Error.
version The system version reported by the platform shell (weft_host.version).

The kernel also injects setTimeout / setInterval / clearTimeout / clearInterval, queueMicrotask, and console (debug / log / info / warn / error map to levels 0–3 of weft_host.log; non-string arguments are output as JSON and error objects are output as their stack). Hermes provides TextEncoder / TextDecoder.

  • weft_runtime_new executes the bundle, which mounts the app. Every entry point that executes JS (new, tick, dispatch, resolve) drains the microtask queue before returning. The first batch of ops has therefore been committed by the time weft_runtime_new returns.
  • Timers run in order of expiration, with ties broken by the order in which they were set. The microtask queue is drained after each timer. Timers set during a tick are deferred to the next one. The kernel requests the next tick with weft_host.schedule(delay). The platform shell may coalesce requests; early or redundant calls to tick are harmless.
  • Uncaught exceptions in the bundle, timers, microtasks, or event handlers are reported as WEFT_LOG_ERROR without terminating the runtime. If the bundle itself throws (including on a layout hash mismatch), weft_runtime_new returns NULL.

The payload in weft_runtime_dispatch(rt, scope, slot, payload, len) is a value in the binary encoding (tag byte followed by data). Pass an empty payload for an event with no payload. The return value is that of Session.dispatch.

__weft.call allocates a call ID and calls weft_host.call(id, module, method, args). On asynchronous completion, the platform shell calls weft_runtime_resolve(id, ok, result) on the UI thread, exactly once per ID. If ok is true, the promise resolves with an ArrayBuffer copy of result. Otherwise, it rejects with an Error whose message is result (UTF-8). Each module defines how to interpret the bytes:

Module Method Arguments Result
fetch request Frame: u32 header length (little-endian) | header (UTF-8 JSON) | body. The header is {"url", "method", "headers"}. Same frame format, with a {"status"} header followed by the response body.
storage get / set / remove JSON array: [key] or [key, value]. get: a JSON string or null; otherwise empty.

If supports(api) is false, @weft-ui/platform throws PlatformError without making the call.

Platform shells that move native rows themselves (WinUI, GTK) can use weft_stable_rows(old, new, stable). It marks the rows that stay in place in the new order (the longest increasing subsequence of the old positions). Other rows must be moved or inserted. C++ platform shells can use weft/ops.hpp to decode ops without allocating memory. Strings and row lists point directly into the batch’s bytes.