UILab
UILab is the component layer: a small React-shaped runtime
for C#. It owns the virtual tree, component instances, hooks, context,
routing and the reconciliation that turns a new render into in-place
mutations of the live tree. That live tree is also the DOM the CSS matcher
and layout engine consume, so there is no second translation step between
the component model and the engine.
One tree, two roles
Every node implements IgniteSupportedDomNode. The same tree
that describes elements and text is the tree the selector matcher walks and
the layout engine boxes. UILab does not render pixels; it produces a live
DOM-shaped tree and a version number that tells the host when to repaint.
Component and provider nodes never appear in the live tree. They stay in the virtual tree so their instances and published context values survive across renders. The host only ever sees the materialised output.
Building a tree
_ is the terse builder: H for elements,
Text for text, C<T> for components,
F for fragments and helpers such as Show and
Each. HtmlHelper adds 138 typed element factories
that produce exactly the same nodes, so Div(...) and
H("div", ...) are interchangeable.
using static Donkeh.UILab._;
using static Donkeh.UILab.HtmlHelper;
var card = Div(new() { ClassName = "card" },
H2(new(), Text("Files")),
Show(isReady, P(new(), Text("Ready"))),
Each(files, file => Li(new() { Key = file.Id }, Text(file.Name))));
Element attributes and class names are interned immediately. A
Props value is converted into an id-based representation once,
so the diff compares integers rather than strings. Dedicated properties
such as Id, ClassName, Href and
Disabled are applied before the arbitrary
Attributes dictionary; a class entry appends
tokens, while an id entry replaces the dedicated id.
Text children are first-class. A pure-text child list is folded into the
element’s TextContent instead of allocating one
TextNode per run, which is a significant win for labels,
buttons and table cells. Numeric and boolean values obtain implicit text
conversions using invariant culture so rendered numbers stay stable across
machines.
Components and lifecycle
A component is a class with a public parameterless constructor and a
Render method. The renderer creates exactly one instance per
mounted ComponentNode, assigns props and context scope, and
reuses the instance for every later render. Unmounting discards it, which is
exactly why hook state lives as long as the component stays in the tree.
| Member | When it runs |
|---|---|
Render() | During mount and every update. Hooks are only legal inside this window. |
OnMount() | After the first subtree commit and ref attachment, before the root mount returns. |
OnUpdate() | After a committed re-render. Not called when ShouldRender vetoes a parent-driven render. |
OnUnmount() | Before hook cleanups and before the mounted flag is cleared. |
ShouldRender() | Lets a component skip a parent-driven render while still receiving new props and context. |
Component<TProps> adds a typed Props
payload. Props are assigned before ShouldRender, so an override
can compare old and new values. A null render result is a bug,
not an empty view; return an empty fragment instead.
Reconciliation
The renderer mounts an initial tree and then diffs every later render in place. It never rebuilds the whole tree. Nodes keep their identity, and mutations bump revisions only when something actually changed, which is what preserves layout cache entries for untouched subtrees.
| Step | Behaviour |
|---|---|
| Kind check | Components match by exact type, providers by Context<T> identity, elements by interned tag name, fragments and text by kind. |
| Mismatch | Unmount the old subtree and mount the new one, discarding component state below it. |
| Element match | PatchFrom rewrites attributes, classes, events and refs in place; children are diffed recursively. |
| Text match | The existing TextNode is reused; assigning identical text suppresses the revision bump. |
| Keyed children | Matched by key regardless of position, so reorders move nodes instead of remounting them. |
| Unkeyed children | Try the same index first, then the first unused positional slot of the same kind. |
| Unused old children | Unmounted after the new list is built, releasing refs, handlers and component state. |
A component whose output is another component or provider has no live node of its own. The renderer pushes the parent output slot down the logical chain until it reaches the first live node, which lets a nested component replace itself in place when its output kind changes.
Hooks
Hook identity is positional. Each component owns an append-only list of hook
slots, and BeginRender resets a cursor to zero. The nth hook
call always maps to the nth slot; adding, removing or moving a hook changes
the sequence and throws instead of silently corrupting state.
| Hook | Storage and behaviour |
|---|---|
State / StateWithUpdate | Value plus a stable setter; equality suppresses unchanged writes. Functional updates read the current value at call time. |
Reducer | State plus a stable dispatcher. The latest reducer is captured each render; unchanged results do not queue work. |
Effect / LayoutEffect | Dependency arrays compared element by element. Cleanup runs before the next body and on unmount; layout effects run before passive effects. |
Memo / Callback | Caches a value or delegate by dependency array; without dependencies the factory runs every render. |
UseRef | Stable mutable box. Writes never schedule a render; element refs are attached on mount and cleared on unmount. |
UseContext | Reads the nearest provider from the scope captured at render time, falling back to the context’s default. |
State setters throw during render. That is intentional: a render must be a pure function of the captured state. Updates belong in event handlers or effects, where they are queued and applied by the flush loop.
The flush loop
State updates mark a component dirty and enqueue it once. With
AutoFlush on, the queue flushes synchronously; with it off, the
host calls Flush from its frame loop. The loop processes every
dirty component, commits effects, and repeats if an effect queued more work.
A hard limit of 64 passes catches an effect that updates state
unconditionally.
while (dirty.Count > 0)
{
foreach (component in dirty)
UpdateComponent(component);
CommitEffects(); // layout effects, then passive effects
Version++; // host wake-up signal
}
AfterUpdate?.Invoke(); // one signal after a settled pass
Effects run only after the whole dirty queue has been applied, so they
observe a fully patched tree rather than a half-updated one. Components are
visited in render order and hooks in declaration order. Version
is a wake-up counter, not a content hash: a flush that processes a component
bumps it even if the resulting tree is identical.
Context
Context<T> is identified by instance identity, not by type.
A provider publishes a value into an immutable scope chain; consumers read
the nearest matching scope. Values are captured per render, so a later
state-driven render sees the same context it saw when it was rendered.
A provider republishing a different value does not by itself force existing
consumers to re-render; they update the next time they render for some other
reason. Providers render as transparent fragments, so context does not add a
box to the layout tree. Routing is built on the same mechanism:
AppRouter publishes Router.Path and
Router.SetPage.
Events and refs
Events are ordinary delegates stored in an element’s event map keyed by a
normalised lowercase name. Props exposes simple handlers such as
OnClick, OnPointerDown, OnContextMenu,
OnInput and OnKeyDown, plus typed
On…Event variants such as OnClickEvent and
OnKeyDownEvent. Arbitrary events can go through
On(name, handler) or Attr(name, handler). Hosts mirror
handler presence into their own event system, but the delegate stays owned by
the element.
Every host dispatch is represented by an Event subclass, even
when the payload is empty. MouseEvent adds window and
element-local coordinates, KeyDownEvent exposes the key and its
modifiers, InputEvent and ChangeEvent carry the
control value, and the media classes carry playback time. Typed handlers take
precedence over the simple delegate for the same event name.
Pointer handlers receive element-local coordinates. A
ContextMenuEvent also exposes the deepest clicked node as
Target, the node whose handler is running as
CurrentTarget, and the original pointer position in window CSS
pixels. The complete event list lives in the
event reference.
Ref<ElementNode> points at a mounted element and is cleared
on unmount. Refs are an escape hatch for host integration and measurements,
not a way to drive rendering: writing to a ref never schedules work.
Stylesheets and assets
[assembly: Stylesheet("path.css")] declares an embedded CSS
resource. Stylesheet.Load() scans assemblies and type/module
attributes, reads the matching embedded resources and concatenates them. It
is reflection-heavy and uncached, so load once at startup and keep the
string. Packed images use the parallel [Image] / Image
API.
Why it stays cheap
- Interned identity. Tag names, attribute names, class names and attribute values are integer ids, so patches compare ints.
- In-place mutation. The live tree is reused; only changed fields bump revisions, preserving layout caches for untouched subtrees.
- Text folding. All-text children collapse into one
TextContentstring instead of allocating one node per run. - One queue entry per component. Repeated state updates in one pass collapse through the
Queuedflag. - Static component factories. Reflection for the public parameterless constructor happens once per component type, then a cached delegate is reused.
- Stable keyed matching. Reorders move existing nodes and preserve component state instead of remounting a list.
- No second tree translation. The live tree is already the DOM consumed by matching and layout.
Trade-offs and sharp edges
| Decision | Cost |
|---|---|
| Positional hooks | Fast and allocation-light, but hooks must be unconditional and in stable order. |
| Mutable live nodes | No tree rebuild, but the tree is not thread-safe and must only be touched by its renderer. |
| Public parameterless constructors | Simple, cacheable construction, but components cannot receive constructor dependencies. |
| Per-render context snapshots | Predictable reads, but publishing a new value does not automatically notify every consumer. |
| No error boundaries | A throwing render or effect bubbles to the host; there is no component-level recovery boundary. |
| Keyed matching by linear scan | Fine for typical lists; very large lists pay for the scan rather than maintaining an index. |
| Silent no-op after unmount | A late state setter is harmless, which also means a missed cleanup may go unnoticed. |
| One renderer per tree | Mounted once, single-threaded, no concurrent rendering or SSR path. |
Code tour
| File | Read it for… |
|---|---|
UILab/Source/Renderer.cs | Mount, diff, keyed children, component updates, effects and the flush loop. |
UILab/Source/Component.cs | Lifecycle, typed props, render window and dirty marking. |
UILab/Source/Hooks.cs | State, reducer, effects, memo, ref, context and positional slot enforcement. |
UILab/Source/Node.cs | Live node kinds, element storage, attributes, refs, events and text handling. |
UILab/Source/Underscore.cs | The terse builders, child normalisation, fragments and conditional helpers. |
UILab/Source/Props.cs | Dedicated attributes, arbitrary attribute dictionary, event surface and the PropsWithChildren payload for child content. |
UILab/Source/Routing.cs | AppRouter, routes, links and the path/setPage contexts. |
UILab/Source/HtmlHelper.cs | 138 typed element factories. |
UILab/Source/Stylesheet.cs / Image.cs | Embedded CSS and packed image discovery. |
The useful mental model: UILab is a reconciliation engine over an already-DOM-shaped tree. Components describe output; the renderer patches nodes in place; Data and LayoutLab consume the patched tree without knowing that a component model produced it.