RecursiveAI.OneApp.Browser runs OneUI components on browser-wasm. Each top-level component is registered as a custom element; a
small JavaScript module (oneui-browser.js, a plain ES module with no dependencies) applies the component model's change sets to the
real DOM and sends DOM events back. Layout and painting are the browser's.
Using it
// Program.cs of a Microsoft.NET.Sdk.WebAssembly app BrowserApp.Define("oneui-todo", host => new TodoApp { Added = t => host.Emit("added", t) }, o => o .StringParam("heading", (c, v) => c.Heading = v));
<oneui-todo heading="Groceries"></oneui-todo> <script type="module"> import { boot } from './oneui-browser.js'; await boot(); </script>
The project references RecursiveAI.OneApp.Browser (which brings OneUI and its markup compiler) and imports the package's build
targets, which copy oneui-browser.js into wwwroot. See samples/Todo.Browser. Publish with dotnet publish -c Release; the result
is a static folder (wwwroot/ with index.html, oneui-browser.js and _framework/) for any static file server. Set
WasmFingerprintAssets to false so the runtime files keep their names, as the sample does.
boot(options) loads _framework/dotnet.js next to the module (options.runtime overrides the URL), runs the app's Main, which
registers the tags, and returns when Main has returned. Elements already in the page upgrade as soon as their tag is defined.
options.onCommit receives {host, sequence, ops, bytes, ms} after each applied commit.
Custom elements
BrowserApp.Define<T>(tag, create, configure)callscustomElements.define. The tag follows the HTML custom element name rules.createruns once per element and gets anElementHost; every element has its ownUiContextand component, so several instances on one page are independent.- Lifecycle.
connectedCallbackcreates the component, applies the attributes and properties present, and mounts it (the first commit is applied before the callback returns).disconnectedCallbackunmounts it (OnDisposedruns, its nodes are removed) unless the element is connected again in the same task, so moving an element keeps its state. An element that stays disconnected and is attached again mounts a fresh component. - Parameters.
options.Param(attribute, set)and the typedStringParam,BoolParam,Int32Param,DoubleParammap an attribute, and the camel-case property of the same name (due-dateanddueDate), to a setter on the component. The attribute is observed. A property set before the element was defined or mounted is applied when it mounts. A removed attribute or anullproperty passesnull, which the typed helpers turn into"",falseor0. - Events out.
ElementHost.Emit(type, detail)dispatches a bubbling, composedCustomEventon the element. - Shadow DOM (default) renders into an open shadow root, so the component's scoped CSS cannot leak out and page CSS cannot leak
in. Its style sheets are constructable sheets adopted by the root (one
CSSStyleSheetper distinct text, shared by all instances), with a:host { display: block }default that a page rule on the tag overrides.ShadowDom = falserenders into the element itself and the sheets become<style>children of the element, which still apply to the whole document.
The bridge protocol
.NET to JavaScript, by [JSImport] from the module registered as oneui-bridge:
| Function | Meaning |
|---|---|
define(tag, shadow, attributes) | Register the custom element class. |
apply(host, packed) | Apply one commit to element host's DOM, synchronously. packed is a Uint8Array view valid only during the call. |
emit(host, type, detail) | Dispatch a CustomEvent. |
JavaScript to .NET, by [JSExport] on OneApp.Browser.Internal.Exports: Create(tag, host), SetParam(host, name, value),
Mount(host), Unmount(host), Destroy(host) and Dispatch(...). Host ids are allocated by the bridge, one per connected element.
Commits (change-set protocol versions 1 and 2, see OneUI's docs/change-sets.md) cross as one packed buffer per ChangeSet, one call
per commit, applied in order and synchronously inside the .NET batch that produced them. All integers are unsigned LEB128 varints:
format(1) protocolVersion sequence stringCount poolBytes opCount stringLength[stringCount] UTF-16 code units of each pooled string pool the strings, UTF-8, back to back (decoded with one TextDecoder call) ops... kind (1 byte, the ChangeKind number), then: CreateElement node name CreateText node text SetText node text Insert / Move parent child before Remove node SetAttribute / SetStyle / SetProperty node name value RemoveAttribute / AddClass / RemoveClass / RemoveStyle / AddListener / RemoveListener node name AddStyleSheet key css CreateElementNS (16) node name namespace Focus (17) node
Strings are indexes into the pool, so a repeated tag, class or property name travels once per commit. A bridge refuses an unknown
format, a protocol version above 2 and a gap in sequence; versions 1 and 2 are both applied. Node ids are never reused; the root container (id 1) is the shadow root, or the
element in light DOM. Move uses moveBefore where the browser has it (focus and selection survive a keyed reorder) and
insertBefore otherwise. SetProperty for value skips an assignment that would not change the control, so the caret stays put.
SVG and focus (protocol 2). CreateElementNS calls document.createElementNS(namespace, name) with the name's case kept, so inline SVG
(viewBox, linearGradient) works; attributes, classes and styles on it go through setAttribute, classList and style.setProperty, never
className. Focus calls element.focus() after every other change of the commit has applied, so a node created and inserted in the same
commit can take focus; for a node that is detached, removed again, disabled or not focusable it does nothing, and it works inside a shadow root.
The focus events focus() raises synchronously are not dispatched from inside apply: they are queued and delivered, in order, in a
microtask once the commit has finished, because the component model is not re-entered during a commit. Events the user causes (a click, a
key, Tab) are dispatched at once as before. focus and blur reach only the target's listeners, focusin and focusout bubble, as in the DOM.
Events are real DOM listeners on the nodes that have an AddListener, so bubbling is the browser's. Each call to
Dispatch(host, node, target, type, modifiers, button, clientX, clientY, deltaX, deltaY, key, code, flags, value, relatedTarget) carries
the same fields for every type (modifiers: shift 1, control 2, alt 4, meta 8; flags: repeat 1, checked 2; value and checked
are read from the target for input and change). .NET builds the payload class OneUI names for the type and returns bit 0 if a handler
stopped propagation and bit 1 if it cancelled the default action; the bridge applies both to the real event. An exception thrown by a
handler is reported as an uncaught error.
Queries and timers. Components ask the page questions synchronously (UiContext.GetBoundingClientRect and the rest of OneUI's IDocumentQueries); a commit is always applied first. The bridge module provides
queryRect(host, node) (getBoundingClientRect as [x, y, width, height], empty when the element is detached or display: none), queryViewport (documentElement.clientWidth/Height), queryScroll
(scrollLeft, scrollTop, scrollWidth, scrollHeight, clientWidth, clientHeight), queryTabbable(host, root) (ids of the elements inside root that Tab reaches: tabIndex >= 0, not :disabled, not a hidden input,
not inside an inert subtree, checkVisibility(); positive tabindex first in ascending order, then tree order), queryActive (the focused element's id in the element's tree, 0 for none), queryContains and queryInert.
Timers use startTimer(id, ms)/stopTimer(id) over setTimeout, and the bridge calls the .NET export Fire(id) when one expires, which runs the callback as one batch. All of it is on the page's one thread.
The host interface
An app talks to the page that hosts it through IHostFetch, not HttpClient, so the host decides how a request is authenticated.
// JSON over the source generator: no reflection, trim-safe. [JsonSerializable(typeof(Reply))] partial class AppJson : JsonSerializerContext { } Reply r = await BrowserHost.GetJsonAsync("/api/thing", AppJson.Default.Reply); Reply s = await BrowserHost.PostJsonAsync("/api/thing", request, AppJson.Default.Request, AppJson.Default.Reply);
BrowserHost.Fetchis theIHostFetchin use.SendAsync(HostRequest, ct)returns aHostResponse(status, reason, lower-case headers, body as UTF-8 text) for any HTTP status, and throwsHostFetchExceptiononly when no response arrived. Bodies are text. The helpers throwHostFetchException(with the response) on a non-2xx status or a body that is not the expected JSON. Tests setBrowserHost.Fetchto a fake.- The default implementation calls the bridge's
hostFetch, which uses the function given toboot({ fetch }), else the browser'sfetchwithcredentials: 'include'. A relative URL resolves against the page. aleraOsFetch, exported byoneui-browser.js, is the function for pages served by Alera OS: it delegates to the page'salera-os--sdkauthedFetchwhen that module resolves, and otherwise sends the same credentials itself (X-Alera-AuthfromWebappCore.getToken()or localStoragewebapp-core-auth-token,X-App-Namefrom<meta name="webapp-core-app">,X-Account-Id,credentials: 'include'). Boot withawait boot({ fetch: aleraOsFetch }).ElementHost.EmitJson(type, json)isEmitwith the detail parsed from JSON.OsWindowEventsuses it for the events a shell that shows the element in a window listens for:SetTitle(os-window-title),SetActivity(os-window-activity),SaveState(os-window-state) andBindDesktop(os-desktop-bind). Another page ignores them.
Serving the published folder
Some static servers refuse paths that start with an underscore, which _framework/ does. Rename the folder after publishing and
pass its URL: boot({ runtime: '.../framework/dotnet.js' }); the runtime finds its files next to dotnet.js.
Limits
- Elements are created with
document.createElement; the HTML namespace only (no SVG or MathML elements yet). - Strings and events are the only things that cross, so a component's callbacks (
Actionparameters) cannot be set from JavaScript: use attributes and properties in,Emitout. - Layout is Chrome's (or the browser's). Where it differs from OneRender's rendering of the same markup, OneRender is the one to fix.
Checking it
tools/web/run-browser.mjs drives the published sample in headless Chrome over the DevTools protocol (typing, Enter, ticking,
removing, two instances, attributes and properties, moving elements, light DOM), fails on any console error, and saves screenshots;
--bench times a 1,000-row append and a single text change. tools/BrowserCompare renders the same state natively through the
reference document and OneRender for a side-by-side.