Browser
Donkeh.Windowing.Browser is a DOM host, not a renderer. It
mounts the same UILab application, then mirrors the reconciled virtual tree
into real browser elements. CSS layout, focus, carets, selection, scrolling,
form controls and pseudo-classes stay with the browser; the host only keeps
the DOM in sync and forwards events to the same delegates a desktop host
would invoke.
Bootstrap
DonkehBrowser.RunAsync creates a default Blazor WebAssembly
host, registers DomHost as a singleton and starts it. Blazor is
used only for its WebAssembly runtime and JavaScript interop. No Blazor
components are rendered; UILab owns the UI tree.
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddSingleton<DomHost>();
var host = builder.Build();
await host.Services.GetRequiredService<DomHost>().StartAsync();
await host.RunAsync();
DomHost.StartAsync discovers the [AppRoot],
imports an embedded JavaScript module, initializes it against the container
element, installs the browser permission provider, applies the merged
stylesheet and title, subscribes to Renderer.AfterUpdate,
mounts the component tree and performs the first sync.
data:text/javascript;base64,... URL. Apps do not need a
wwwroot folder, static web asset manifest or _content
path. The bridge is a framework concern, not an app packaging detail.
Stable ids and snapshots
Every virtual node gets a stable integer id the first time it is synced. The browser stores the same id on its DOM node, and the C# host keeps both directions:
| State | Purpose |
|---|---|
Node → int | Stable identity for patching, even across keyed reorders. |
int → Node | Resolves the handler and target for an incoming browser event. |
NodeSnapshot | Last applied tag, text, attribute map, event list, child order and folded text content. |
| Root child ids | Tracks the flattened top-level order, with fragments removed from the DOM shape. |
A sync walks the live tree, compares each node with its snapshot and emits only changed patches. Fragments have no DOM counterpart, so their children occupy the fragment’s slot in the parent. Nodes that disappear from the walk are removed from the maps and get a remove patch. The DOM node is never recreated just because its position changed.
The patch protocol
The patch vocabulary is deliberately small. The browser owns the real DOM; the host only describes how it differs from the last applied snapshot.
| Patch | Effect |
|---|---|
create | Create an element or text node with a stable id. |
remove | Remove a node and forget its id. |
children | Set the exact child order, inserting and moving existing nodes instead of rebuilding. |
text | Replace a text node’s value. |
content | Set folded element text, or clear it when real children return. |
attrs | Replace the full attribute map; the bridge preserves its own data-donkeh-* bookkeeping. |
events | Replace the event-name list stored on the element for delegation. |
Patches are serialized with a source-generated JsonSerializerContext,
which keeps the bridge trim-safe in published WebAssembly builds. The JS side
applies them in order and maintains a Map<number, Node>.
It also handles the cases where the DOM’s live state must win:
- A focused text input keeps the user’s live value unless the virtual tree changed it to a different value.
value,checkedandselectedare mirrored as properties as well as attributes, without disturbing a caret.- Removing
checkedorselectedclears the corresponding property. data-donkeh-*attributes are reserved for the bridge and never removed by an attribute replacement.
Event delegation
The bridge installs one delegated listener per event family on the container, not one listener per element. Each element carries its event-name list in a data attribute. When a browser event fires, the bridge walks from the physical target up to the nearest element that declares a handler for that event, then calls back into .NET with:
| Argument | Meaning |
|---|---|
handlerId | The nearest virtual element that owns the handler. |
targetId | The deepest virtual node under the physical event target. |
eventName | Normalized name such as click, pointerdown, input or change. |
x, y | Element-local coordinates, scroll deltas or media time, depending on the event. |
text, value | Key name, pasted text or control value. |
DomHost.HandleEventAsync resolves both ids, updates control state
for input/change/Enter and invokes the same delegate shapes as the desktop
host: typed event-class handlers, parameterless actions, string handlers and
two-float pointer handlers. Each callback builds the matching
Event subclass, so a browser handler sees the same
ClickEvent, KeyDownEvent or ScrollEvent
as a native one. Browser key names are mapped to the desktop names:
Space, Left, Right, Up,
Down, Escape and single letters. A throwing handler
is contained, as it is on desktop.
Scroll and media tracking are opt-in per element. When an element declares
scroll, the bridge records its previous offsets and reports the
delta. Declaring media events attaches play, pause, ended and timeupdate
tracking. Both use passive listeners where possible.
What the browser owns
The browser path intentionally does not run LayoutLab or the OpenGL renderer. It delegates far more to the platform than the desktop host:
| Concern | Owner |
|---|---|
| CSS layout, cascade and pseudo-classes | The browser. |
| Focus, caret, selection and IME | The browser’s native form controls. |
| Scrolling and scrollbars | The browser; the host consumes scroll deltas. |
img, video, audio | Native browser elements and media APIs. |
canvas | The element exists, but no C# draw callback is wired. |
| Inspector | Not part of the browser host; devtools are desktop-only. |
Browser permissions
BrowserPermissionService forwards the supported capabilities to
the embedded module, which uses the corresponding browser API:
| Permission | Browser mechanism |
|---|---|
| Camera | getUserMedia({ video: true }); the temporary stream is stopped immediately. |
| Microphone | getUserMedia({ audio: true }); same stop-after-check policy. |
| Location | navigator.geolocation.getCurrentPosition with a 15-second timeout. |
| Notifications | Notification.requestPermission(), with existing grant/deny states short-circuited. |
| Storage | navigator.storage.persist(). |
| Motion | DeviceMotionEvent.requestPermission() where available; otherwise true. |
| Clipboard | A clipboard read, which requires a user gesture in most browsers. |
| Photos, contacts, calendar, Bluetooth | Unsupported; returns false. |
Host.Permissions.Camera() from a button
click works; calling it during startup may be rejected even though the same
API succeeds later. Failures resolve false rather than throwing.
Why the bridge stays small
- Stable ids. Keyed reorders move existing DOM nodes; they do not recreate subtrees or lose browser focus.
- Snapshot diffs. Only changed text, attributes, events and child orders cross the interop boundary.
- Coalesced sync. Multiple renderer updates in flight collapse into one drain loop; the newest tree wins.
- Delegated events. One listener per event family on the container, not per element.
- No layout engine. The browser performs layout and paint; the host never builds boxes or instructions.
- Trim-safe JSON. Source-generated serialization avoids reflection metadata in published WASM builds.
Trade-offs and sharp edges
| Decision | Cost |
|---|---|
| DOM is authoritative | Native form behaviour is excellent, but the host must reconcile browser-driven value changes back into virtual node state. |
| No layout engine | Browser CSS and layout do the real work, so desktop-specific layout behaviour and the inspector are unavailable. |
| Data-URL module | No app packaging requirements, but the bridge is loaded as a generated module rather than a cacheable static asset. |
| Full attribute replacement | Simple and correct, but every attribute map crosses the interop boundary when any attribute changes. |
| Delegated events | One listener setup, but every event walks ancestors to find a handler. |
| No canvas drawing | Native canvas exists, but C# callbacks are not bridged; there is no WebGL interop yet. |
| Permission gesture rules | Apps must trigger prompts from interaction; startup checks can fail for reasons the host cannot control. |
| WASM startup and trimming | The Blazor runtime is large compared with a native host; source-generated JSON and rooting keep the bridge safe under trimming. |
Code tour
| File | Read it for… |
|---|---|
DonkehBrowser.cs | The Blazor WebAssembly bootstrap and singleton host registration. |
DomHost.cs | App mount, id maps, snapshots, patch generation, event dispatch and control-state reconciliation. |
DomPatch.cs | The small patch vocabulary and source-generated JSON contract. |
wwwroot/donkeh.js | DOM creation/patching, delegated listeners, scroll/media tracking and browser permission APIs. |
BrowserPermissionService.cs | The Donkeh-to-browser permission mapping and failure policy. |
The mental model: desktop paints a tree; the browser mirrors it. UILab remains the source of truth for structure, but the browser is the source of truth for layout, focus, form state and native interaction.