LayoutLab
LayoutLab is the largest package and the one with the widest
job: take a matched CSS table, resolve styles, generate boxes, run the
formatting contexts, measure text, evaluate animations, and emit a compact
paint-instruction stream. It is not a browser engine clone; it is a
deliberate approximation that covers the CSS a real application uses and
keeps the frame path predictable.
The frame pipeline
One engine instance is reused across frames. A full layout pass is a sequence of well-defined phases, not a recursive box routine hidden in a renderer:
The engine keeps the box tree in unscrolled absolute coordinates. Scroll offsets are clamped per scroll container and applied as paint-time translations. Scrolling can therefore repaint without rebuilding geometry, and a viewport resize invalidates only the parts whose styles or metrics actually depend on the new environment.
Style resolution
StyleResolver receives the node, the parent’s computed style
and the already-ordered matched rules from Donkeh.Data. It
applies declarations weakest-first and runs important declarations in a
second pass, which lets !important win without allocating a
per-property cascade map.
- Inherited scalars — colour, font, writing mode and similar — are copied from the parent. Custom properties stay linked through
StyleParentand are resolved lazily. - Text nodes are forced to
display: inlineand fragments todisplay: contents; these are framework constructs, not authored CSS. - Percentages,
em,rem, viewport units andautostay asCssLengthvalues. Layout resolves them later against the correct containing block. - Parsed declaration values are cached by interned value id in
StyleValueCache, so repeated0 8pxvalues parse once.
ComputedStyle is a large mutable object rather than a frozen
record. That is deliberate: the animation runtime writes interpolated
values into the style between frames and reuses the same instance. Arrays,
filters and animation lists referenced by a style are treated as immutable
once published.
Caches and invalidation
LayoutLab is built around the assumption that most of a frame does not change. Several caches sit between the DOM and the geometry:
| Cache | Key / invalidation | What it saves |
|---|---|---|
| Style cache | Node revision, parent inherited-value hash, frame signature, renderer-context version, interaction version. | Re-cascading unchanged subtrees. |
| Inherited-value hash | Memoised per ComputedStyle instance for the current pass. | Recomputing whether a child inherited something different. |
| Value cache | Interned declaration value id. | Parsing the same CSS value over and over. |
| Text layout cache | Text, text style and quantised available width; two generations of up to 1024 entries. | Re-wrapping and re-measuring identical runs. |
| Box cache | Node identity, optional and explicit. | Allocating the box tree and child lists every frame. |
| Animation state | Node identity and a monotonic frame stamp. | Restarting clocks and tracks for live nodes. |
The style signature includes viewport, font metrics, orientation, device pixel ratio and renderer context. Interaction state is a separate version, because hover or focus on one node can change a sibling through a selector without changing either node’s DOM revision. Height-only resizes are special-cased: they do not invalidate width-based queries unless the table contains height media queries or a style uses viewport-height units.
SnapshotResults enabled the instruction stream and node
map are copied into the result. The box tree is still owned by the engine
and may be mutated in place when ReuseLayoutBoxes is enabled.
Treat a result as read-only, and snapshot it when it must outlive the next
frame.
Box generation
BuildBox walks the DOM once. It creates a box for every
generated element, skips display: none, flattens
display: contents into its children, creates synthetic text
nodes for direct text in flex/grid containers, and materialises generated
::before/::after content from the CSS table. The
resulting LayoutBox carries the node, style, parent, children,
border/padding/content rectangles, margins, scroll metrics and float context.
Boxes are the unit of layout reuse. With reuse enabled, a cached box is reset — geometry, children, text, scroll and float state — while its node identity and child-list capacity are kept. That removes the per-frame allocation of the entire tree at the cost of mutating the previous result.
Formatting contexts
LayoutContent dispatches on the box’s formatting context. The
implementations share intrinsic-size measurement, length resolution,
floats and caching, so a nested flex item inside a grid cell inside a table
cell still behaves consistently.
| Context | Coverage |
|---|---|
| Block and inline flow | Block flow, inline runs, line boxes, text wrapping, inline-blocks, floats and block formatting contexts. |
| Flex | Row/column, reverse axes, wrapping, grow/shrink, basis, gaps, auto margins, order, justify and align, multi-line cross sizing. |
| Grid | Explicit tracks, fr, minmax(), auto-fit/auto-fill, named areas, row/column placement, spans, gaps and intrinsic contributions. |
| Table | Row/cell collection, colspan/rowspan, max-content column sizing, collapsed or separate borders, border spacing and row-height refinement. |
| Floats | Float context with clearance, avoidance by BFC roots and inline content flowing around active floats. |
| Out of flow | Absolute and fixed boxes deferred until normal flow finishes; static positions seeded before flex/grid/table skip them. |
Flex is a good example of the engineering style. It rents scratch arrays
from ArrayPool<T>, sorts by order, calculates
base and minimum sizes, wraps lines, distributes positive and negative free
space, and runs up to four extra shrink passes to remove clamping overflow.
Auto minimum sizes use measured max-content as a floor, which is what keeps
a busy toolbar from crushing its buttons.
Grid uses a flattened track model (Fixed, Percent,
Fr, Auto, MinContent,
MaxContent, FitContent) and handles column flow by
transposing placement, line names and named areas. Table layout is
intentionally simpler: max-content column sizing with spanning-cell
distribution, then a second cell layout with final row heights.
Text and line layout
Text is deliberately decoupled from fonts. ITextMeasurer reports
advance width, ascent and descent for a run; the default
SimpleTextMeasurer uses a deterministic per-character advance
table rather than font files. The window host can replace it with a
font-backed measurer without changing layout code.
TextLayoutEngine performs line breaking, whitespace handling,
alignment, direction, letter spacing, text transforms and decoration
metadata. The result is a TextLayout of positioned lines, cached
by text, style and quantised width. Because the cache is bounded to two
generations, a live performance monitor or other constantly changing text
can disable text caching without affecting style resolution.
Paint instructions
Layout does not call OpenGL. It emits a portable display list. Each
Instruction is a fixed 24-byte value: four floats, an opcode,
flags, a 16-bit auxiliary index and a 32-bit payload. Small draws use the
floats directly; text, gradients, borders, transforms and other large
payloads live in a ConstantPool and are addressed by index.
| Paint stage | What it emits |
|---|---|
| Background | Colour, gradients, background images, layers, clipping and repeat. |
| Borders and outlines | Per-side borders, rounded corners, collapsed table edges, outline offsets and triangle borders. |
| Shadows and effects | Outer and inset shadows, filters, backdrop filters, blend modes and opacity scopes. |
| Text | Line runs, decoration, selection/caret overlays and placeholder colours. |
| Replaced content | Images, video frames and other host-supplied content. |
| Scrollbars | Host-painted scrollbar tracks and thumbs derived from scroll metrics. |
The display-list builder walks stacking contexts in paint order, defers fixed boxes to a second pass with inherited opacity, and applies scroll translations while emitting. Transform, opacity, filter, clip-path, mask, blend and composited-layer pushes are represented as explicit scoped instructions so the renderer can batch and the optimiser can reason about them.
The optimiser
Optimiser.Run is a small, semantics-preserving pass over the
instruction stream. It drops no-op instructions and optional frame markers,
intersects clips, removes empty or redundant clips, drops identity opacity
scopes, culls draws outside the active clip when no transform or filter is
active, merges adjacent opaque rectangles, and optionally compacts the
constant pool. Rounded clips are never treated as redundant, and unmatched
pops are ignored rather than truncating the frame.
Animations and transitions
AnimationRuntime is frame-driven and owns all per-node timing
state. The host supplies a monotonic time through
LayoutOptions.AnimationTimeSeconds; the runtime never reads the
wall clock. Keyframe tracks are parsed lazily from the DataTable
and cached by interned animation name. Transitions and keyframes share the
same interpolation model: supported properties interpolate, discrete
properties switch at the segment midpoint, and unsupported values keep their
base style.
The runtime distinguishes paint-only animations from layout animations.
Transform and opacity changes can refresh the display list without a full
layout pass; width, height, margin and similar changes cannot. A per-frame
stamp lets Prune drop state for nodes that left the tree, which
prevents unmounted panels and removed carousel slides from staying alive
through their animation state.
Repaint without relayout
Repaint rebuilds the display list from an existing box tree
when geometry is still valid. Scroll offsets never move boxes, so scrolling
refreshes scroll metrics and re-emits instructions without re-resolving
styles. RepaintAnimated is the same idea for paint-only
animations. This split is the main reason a scrolled or hovered UI does not
pay for a full style and layout pass.
Trade-offs and sharp edges
| Decision | Cost |
|---|---|
| Approximate text metrics by default | Layout widths are deterministic but not pixel-identical to the final font rasteriser. A host can plug in real metrics. |
| CSS subset, not a browser clone | Some advanced layout modes, generated-content functions and font features are approximated or unsupported. |
| Mutable computed styles | Animation can write in place, but sharing a style across threads or assuming immutability is unsafe. |
| Box reuse mutates results | Fast, but a LayoutResult is only stable when snapshotted and never mutated by the next frame. |
| Single layout thread | No locking in the hot path, but the engine, caches and animation runtime cannot be driven concurrently. |
| Depth cap | MaxLayoutDepth defaults to 512; nodes at the limit receive a box but their children are not visited. |
| Table layout is simplified | Max-content column sizing and equal extra-space distribution, not the full CSS table algorithm. |
| Display list is a contract | The renderer must respect scoped opcodes and the constant-pool layout; changing opcode semantics is a cross-package change. |
Code tour
| File | Read it for… |
|---|---|
LayoutEngine.cs | Frame orchestration, box generation, caches, text measurement, absolute positioning and layout dispatch. |
LayoutEngine.Block.cs | Block and inline flow, line groups, floats and BFC rules. |
LayoutEngine.Flex.cs | Flex base sizes, wrapping, grow/shrink, alignment and scratch pooling. |
LayoutEngine.Grid.cs | Track expansion, placement, spans, named areas and column flow. |
LayoutEngine.Table.cs | Row/cell collection, spanning, column sizing and collapsed borders. |
LayoutEngine.Paint.cs | Stacking contexts, backgrounds, borders, text, shadows, scrollbars and display-list emission. |
StyleResolver.cs + partials | Cascade application, property parsing, keywords, custom properties and animation specs. |
ComputedStyle.cs | The mutable, layout-ready style model and inherited-value copying. |
Text.cs | Text measurement, line breaking, whitespace, alignment and the text-layout cache. |
Instruction.cs / PaintSpecs.cs | The 24-byte instruction format, opcodes and constant-pool payloads. |
Optimiser.cs | Clip culling, scope collapsing, rectangle merging and constant compaction. |
AnimationRuntime.cs | Keyframe tracks, interpolation, transition state and per-node clocks. |
The useful way to read LayoutLab is as a pipeline of representations: matched rules → computed styles → boxes → geometry → paint instructions. Each stage caches what it can, invalidates narrowly, and hands the next stage a compact value-oriented shape rather than a tree of rich objects.