D Donkeh docs
GitHub

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:

Layout(root, options) ├── frame setup viewport, fonts, renderer context, signatures ├── style caches resolve or reuse ComputedStyle per node ├── BuildBox element boxes, anonymous text, ::before/::after ├── prune drop cache entries for detached nodes ├── LayoutRootBox block / inline / flex / grid / table / floats ├── ProcessAbsoluteBoxes absolute and fixed boxes, static positions ├── BuildDisplayList stacking contexts, paint ops, scroll translations └── Optimiser.Run cull, merge, collapse scopes, compact constants └── LayoutResult (boxes, instructions, constants)

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.

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:

CacheKey / invalidationWhat it saves
Style cacheNode revision, parent inherited-value hash, frame signature, renderer-context version, interaction version.Re-cascading unchanged subtrees.
Inherited-value hashMemoised per ComputedStyle instance for the current pass.Recomputing whether a child inherited something different.
Value cacheInterned declaration value id.Parsing the same CSS value over and over.
Text layout cacheText, text style and quantised available width; two generations of up to 1024 entries.Re-wrapping and re-measuring identical runs.
Box cacheNode identity, optional and explicit.Allocating the box tree and child lists every frame.
Animation stateNode 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.

Results can alias engine storage With 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.

ContextCoverage
Block and inline flowBlock flow, inline runs, line boxes, text wrapping, inline-blocks, floats and block formatting contexts.
FlexRow/column, reverse axes, wrapping, grow/shrink, basis, gaps, auto margins, order, justify and align, multi-line cross sizing.
GridExplicit tracks, fr, minmax(), auto-fit/auto-fill, named areas, row/column placement, spans, gaps and intrinsic contributions.
TableRow/cell collection, colspan/rowspan, max-content column sizing, collapsed or separate borders, border spacing and row-height refinement.
FloatsFloat context with clearance, avoidance by BFC roots and inline content flowing around active floats.
Out of flowAbsolute 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.

Approximation is a feature Simple metrics make layout deterministic and cheap, and they keep the engine independent of platform font stacks. The visible renderer still measures real glyphs when it draws; LayoutLab only needs consistent advance widths to decide line boxes.

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 stageWhat it emits
BackgroundColour, gradients, background images, layers, clipping and repeat.
Borders and outlinesPer-side borders, rounded corners, collapsed table edges, outline offsets and triangle borders.
Shadows and effectsOuter and inset shadows, filters, backdrop filters, blend modes and opacity scopes.
TextLine runs, decoration, selection/caret overlays and placeholder colours.
Replaced contentImages, video frames and other host-supplied content.
ScrollbarsHost-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

DecisionCost
Approximate text metrics by defaultLayout widths are deterministic but not pixel-identical to the final font rasteriser. A host can plug in real metrics.
CSS subset, not a browser cloneSome advanced layout modes, generated-content functions and font features are approximated or unsupported.
Mutable computed stylesAnimation can write in place, but sharing a style across threads or assuming immutability is unsafe.
Box reuse mutates resultsFast, but a LayoutResult is only stable when snapshotted and never mutated by the next frame.
Single layout threadNo locking in the hot path, but the engine, caches and animation runtime cannot be driven concurrently.
Depth capMaxLayoutDepth defaults to 512; nodes at the limit receive a box but their children are not visited.
Table layout is simplifiedMax-content column sizing and equal extra-space distribution, not the full CSS table algorithm.
Display list is a contractThe renderer must respect scoped opcodes and the constant-pool layout; changing opcode semantics is a cross-package change.

Code tour

FileRead it for…
LayoutEngine.csFrame orchestration, box generation, caches, text measurement, absolute positioning and layout dispatch.
LayoutEngine.Block.csBlock and inline flow, line groups, floats and BFC rules.
LayoutEngine.Flex.csFlex base sizes, wrapping, grow/shrink, alignment and scratch pooling.
LayoutEngine.Grid.csTrack expansion, placement, spans, named areas and column flow.
LayoutEngine.Table.csRow/cell collection, spanning, column sizing and collapsed borders.
LayoutEngine.Paint.csStacking contexts, backgrounds, borders, text, shadows, scrollbars and display-list emission.
StyleResolver.cs + partialsCascade application, property parsing, keywords, custom properties and animation specs.
ComputedStyle.csThe mutable, layout-ready style model and inherited-value copying.
Text.csText measurement, line breaking, whitespace, alignment and the text-layout cache.
Instruction.cs / PaintSpecs.csThe 24-byte instruction format, opcodes and constant-pool payloads.
Optimiser.csClip culling, scope collapsing, rectangle merging and constant compaction.
AnimationRuntime.csKeyframe 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.