The style engine
How zgui drives Stylo — the DOM traits, stylesheets, the mutation filter, the restyle pass, selector matching, custom-property narrowing, computed-style sharing, damage translation and animations.
zgui-style computes a style for every element using Stylo, the CSS engine from the Servo project.
It runs in the f.restyle step of the frame: after the reactive
flush has changed the document, and before the box tree is patched and laid out. It takes the
elements that owe a restyle, matches selectors and runs the cascade for them, and turns the result
into invalidation marks that tell layout, text and paint what to redo.
The sections follow that flow: what zgui gives the engine (the document and the sheets), how a document change reaches the restyle, the pass itself, and what comes out of it. The user-facing model is in Styling.
Stylo and the crates around it
Stylo is used as a Rust library (stylo = "=0.19.0", pinned exactly). It provides four things:
| Part | What it does |
|---|---|
| Parser | Turns sheet text into rules, at-rules and declaration blocks. |
Rule set (Stylist) | Indexes rules so the ones that can match an element are found without a scan. |
| Selector matcher | Answers whether one selector matches one element. |
| Cascade | Resolves every property on an element to one computed value. |
It has no HTML parser, script engine, layout, painter or window. Those are all zgui's.
| Crate | Role |
|---|---|
zgui-css | The public face of the engine. Re-exports ComputedStyle, the computed value types, the engine's length unit, the feature flags and the parity register. |
zgui-dom | Implements the engine's DOM traits over Node<'doc>. This is the tree the engine walks. |
zgui-style | Owns the Stylist, the device and the installed sheets. Runs the traversal and turns its result into invalidation marks. |
Only these three crates name Stylo directly. Every other crate that reads computed styles (layout,
text style, paint, runtime and others) goes through zgui-css, so an engine upgrade touches three
manifests rather than every consumer.
Two engine-wide settings are fixed:
- Quirks mode is always off.
Stylist::new(device, QuirksMode::NoQuirks)incrates/zgui-style/src/engine/stylist.rs, andTDocument::quirks_modeanswers the same. - Feature preferences are set before any sheet is parsed.
StyleEngine::newcallszgui_css::enable_css_features()first. Stylo reads these flags at parse time, so a sheet parsed earlier would silently lose the gated declarations.
The DOM traits
Stylo reads the document only through a set of traits. All of zgui's implementations are on one
handle, Node<'doc>, a Copy value the size of a usize. They live under
crates/zgui-dom/src/stylo/.
| Trait | File | What it answers |
|---|---|---|
TDocument | document.rs | HTML or not, the quirks mode, and the lock shared by sheets, style attributes and restyle guards. |
NodeInfo | node.rs | Element or text. |
TNode | node.rs | Tree links, opaque identity, whether the node is attached. |
TShadowRoot | shadow_root.rs | Nothing. There are no shadow trees; the type exists only because TNode must name one. |
TElement | element/mod.rs | Traversal children, inline declarations, animation rules, the state word, id, classes, custom states, attribute names, per-element style data, and layout damage. |
selectors::Element | selectors/mod.rs | One method per simple selector, plus steps to parent, sibling and first element child. |
AttributeProvider | attributes.rs | One attribute's value by name. |
Rules that hold across all of them:
- Reads are stateless. Every method reads the node record or a table it points to, so several style workers can call them at once, even on neighbouring elements.
- Only two kinds of write exist, and both use atomics:
apply_selector_flags(which writes on the element and its parent) and the bookkeeping-bit setters. A plain read-modify-write inapply_selector_flagscould lose a flag when two workers match two siblings (crates/zgui-dom/src/stylo/selectors/flags.rs). - Element methods are never called on a text node. The matcher reaches elements only through links that already filter to elements. Debug assertions enforce this.
Some methods always return the same answer:
| Method | Answer | Effect |
|---|---|---|
parent_node_is_shadow_root, containing_shadow_host, shadow_root, is_html_slot_element | never | :host, ::slotted() and ::part() parse but never match. |
is_html_element, is_html_document and friends | false | Names match case-sensitively as written. |
query_container_size | (None, None) | Unused: @container blocks are dropped at parse time and reported as dropped at-rules. |
subtree_bloom_filter | u64::MAX | "Anything may be below." A real summary would cost an update on every ancestor of every insertion. |
lang_attribute, matches_lang | None, false | :lang(...) never matches. |
may_generate_pseudo | true except ::first-letter | Inline layout builds no first-letter box, so its style is never resolved. |
Stylesheets and origins
pub enum SheetOrigin { UserAgent, User, Author }
pub fn add_sheet(&mut self, document: &Document, origin: SheetOrigin, source: SheetSource<'_>)
-> (SheetHandle, CssDiagnostics);
pub fn insert_sheet_before(&mut self, document: &Document, origin: SheetOrigin,
source: SheetSource<'_>, before: &SheetHandle) -> (SheetHandle, CssDiagnostics);
pub fn replace_sheet(&mut self, document: &Document, handle: &SheetHandle,
source: SheetSource<'_>) -> CssDiagnostics;
pub fn force_author_rules_dirty(&mut self);- Installation never fails. An unknown declaration drops that declaration, a rejected selector
drops its rule, an unsupported at-rule (
@container, for example) drops its block. Everything else applies. TheCssDiagnosticslist each dropped item with its line; the runtime logs them under the tracing targetzgui::css. - Removal is by dropping the handle. The drop is recorded thread-safely and applied the next time
sheets_have_changed()runs. - Replacement keeps the sheet's position in the cascade. Removing and re-adding would move it to the end of its origin, where it would start winning against sheets that used to beat it.
Specificity, inheritance, !important and the initial / inherit / unset / revert keywords
are all handled by Stylo unchanged:
| Rule | Behaviour |
|---|---|
| Normal declarations, equal specificity | Later origin wins: author over user over user-agent. |
!important declarations | Order reverses: user-agent !important beats author !important. |
| Within one origin | Later-installed sheet wins at equal specificity. |
crates/zgui-style/tests/device.rs asserts the origin order, the !important reversal and
insertion order. The user-agent sheet is installed by StyleEngine::new, must parse completely
(checked by a debug_assert!), and gives every element name its default display.
View sheets
Components install their own sheets at run time (install_stylesheet, used by style!). The view
queues a command, and the window applies it after the reactive flush and before the restyle
(crates/zgui-runtime/src/window/sheets.rs), so a component is styled by its own sheet in the frame
it first appears.
| Case | What happens |
|---|---|
| New name | add_sheet appends it. Stylo invalidates existing elements by the new sheet's own selectors, and the component's new elements have no style yet, so they are styled against it anyway. The rest of the author rules are not rebuilt. |
| Existing name, new text | replace_sheet keeps its position, then force_author_rules_dirty makes the next restyle re-collect the author origin and re-match the document. Rules that were removed have no selector left to invalidate by, so this is the only correct option. |
| Same name, same text | No-op. |
A sheet that arrives while the document is being built ("late sheet") therefore still reaches the elements already in the tree: a new sheet through its selectors, a replaced one through the forced author re-collection.
The mutation filter
Most writes from a running interface cannot change any computed value. Before a class, attribute
or state write is recorded for the restyle, the document asks a StyleFilter whether any selector
could depend on it. A write the filter rules out takes no snapshot and causes no restyle.
The document describes the filter's methods, its
defaults and the per-element state-mask cache.
The style engine implements the filter as StyleFilterView (crates/zgui-style/src/deps/),
answering from the rule set's dependency index:
| Question | Source | Answered from |
|---|---|---|
| Does any selector mention this class? | deps/class_set.rs | The dependency index, so .theme-dark .btn reports theme-dark. |
| Does any selector mention this attribute? | deps/attr_set.rs | The same index. |
| Which state bits could selectors matching this element depend on? | deps/state_mask.rs | invalidation_map().state_affecting_selectors, looked up by the element's root-ness, id, classes and local name. |
Sheet and media-query changes
A sheet change marks no node. It reaches the frame through sheets_have_changed(), and its main
cost is the mutation filter:
- Before the reactive flush, the frame calls
disable_filters_if_sheets_changed(crates/zgui-runtime/src/window/frame.rs). If the sheet set changed,states_forreturnsElementState::all()and both name checks returntrue, so every mutation in that frame takes the full path (snapshot, ancestor mark, traversal). - The restyle flushes the rule set.
stylist.flush(guards).process_style(root, …)also reports the elements the sheet change invalidates, which is how a sheet reaches a document where nothing else changed. - At the end of the same restyle,
self.deps.rebuild(&self.stylist)rebuilds the dependency index. This is the only point where the index matches the installed sheets: earlier, it would read the previous sheet set, and the flush clears the flag that would trigger a later rebuild.
Media queries follow the same pattern. crates/zgui-style/tests/device.rs checks both directions:
| Event | Result |
|---|---|
| Resize that crosses no media-query boundary | epoch.origins is empty (OriginMask::EMPTY), pass.styled == 0, pass.traversed is false. |
| Resize that crosses a boundary | pass.styled == harness.element_count(): the whole origin is re-collected. |
The restyle pass
pub fn restyle(&mut self, document: &mut Document, pool: Option<&StylePool>) -> Restyle;StyleEngine::restyle (crates/zgui-style/src/engine/restyle.rs) runs the traversal, translates
damage and retires the style marks in one call.
needs_restyle is true when an animation marked an element, when the document has style marks, or
when sheets_have_changed(). The last input matters because adding, replacing or dropping a sheet
marks no node.
Order of work
- Settle the readers column (
zgui_dom::side::readers::settle), which records which subtrees read which custom properties. See Custom properties. - Trim the rule-chain cache. If the sheet set changed it is cleared; otherwise it is cleared only when it holds more than 4,096 chains.
- Take the snapshots (
RestyleSnapshots::take). A snapshot records an element's state word and attributes before the first change in the batch, so the engine can re-evaluate selectors that reach it from a sibling or ancestor (.item:hover + .label). Without one, only the changed element itself would be re-matched. - Run the animation-only traversal, if an animation marked an element. See Animations.
- Run up to two ordinary passes, the second only for root-relative units.
- Translate each pass's records into invalidation marks and text-colour updates. See Damage translation.
- Apply the marks, garbage-collect the rule tree, rebuild the dependency index if it was disabled, and drop text keys for removed nodes.
- Retire
RESTYLE | RECASCADEwith onewalk::walk. The engine owns the traversal, so this pair of bits has no other stage to retire it.
What is visited
The traversal descends only where a node's invalidation word has Dirty::RESTYLE or
Dirty::RECASCADE at or below it (STYLE_WORK in crates/zgui-dom/src/stylo/flags.rs). The
engine's has_dirty_descendants reads the subtree half of that word.
unset_dirty_descendants is a no-op. The word is cleared once, at the end of restyle. Keeping a
separate copy of the engine's flag would store one obligation twice, cleared at different times, and
a mark set between the two clears would be lost.
zgui also replaces the engine's per-element step (crates/zgui-style/src/driver/recalc.rs, derived
from Stylo's traversal.rs). Stylo's version tells every child to recascade after any change to a
reset property or a custom property. zgui's version derives the children's hint from what they can
actually inherit, so a subtree is left alone when no inherited group moved.
Root-relative units
rem, rlh, rex, rch, rcap and ric depend on the root element's computed style, which is
known only after the root is styled. At the end of each pass, push_root_metrics
(crates/zgui-style/src/engine/stylist.rs) writes the root's font size, line height and font
metrics into the device. It requests a second pass only if a metric changed and something had
already resolved a unit against the old value. A document that does not use these units always
finishes in one pass. The limit is two passes; a third could not settle anything the second did not.
What each element reports
RecalcStyle::process_preorder (crates/zgui-style/src/driver/traversal.rs) records each styled
element as a Restyled (node, index, the engine's damage, and the fields below):
| Field | Meaning |
|---|---|
initial | First-time cascade. Read before styling, because styling erases it. A first cascade produces no engine damage, so this is the only signal that new content needs layout. |
matched | Selector matching ran (Counter::ElementsRestyled), as opposed to only the cascade (Counter::ElementsRecascaded). |
pseudos | Identities of the ::before / ::after results, or zero. Pseudo-elements have no node, so without these a colour change on generated content would produce no damage. |
readers | The bloom set of custom properties this element's rules read, for the readers column. |
Elements the traversal only passed through are not recorded. Records go into one
Mutex<Vec<Restyled>> per worker and are concatenated at the end; reading them back off the tree
afterwards would cost far more than the incremental restyle itself.
The worker pool
StylePool::new(threads) clamps to zgui_css::MAX_STYLE_THREADS (6); more workers would
overflow the engine's per-worker storage. Workers are named zgui-style-{index} and get a 512 KiB
stack.
The application sets the worker count with App::with_style_threads (default: the machine's
parallelism; ZGUI_STYLE_THREADS overrides it; 0 or 1 means no pool). The window hands the pool
to restyle only for broad restyles:
- the first cascade of a window;
- a device change that flips a media query (
epoch.originsis non-empty); - a resize that invalidates 32 or more elements using viewport units.
Incremental restyles stay on the frame thread. Waking the pool for a handful of elements costs more than it saves (measured at about 4% of a scroll-recycle frame). On an ordinary resize step, viewport units are checked read-only first and the element data is borrowed for writing only where a unit was actually used.
Selector matching
A selector is a chain of compound selectors joined by combinators. The matcher works right to left: it tests the rightmost compound against the element, then steps to a parent or sibling and tests the next one.
Simple selectors
Each simple selector maps to one constant-time method on selectors::Element:
| Selector | Method | How it is answered |
|---|---|---|
row | has_local_name | Comparison of two interned web_atoms::LocalName handles. |
#main | has_id | The id is an interned handle stored in the node record. |
.card | has_class | A scan over the node's pre-interned class run. |
[data-state="open" i] | attr_matches | Look up the value, then the engine's own operation.eval_str, which handles the operator and the i/s flag. |
:hover, :checked, … | match_non_ts_pseudo_class | One mask test against the state word. |
:state(selected) | has_custom_state | A lookup in the element's custom-state column. |
:empty | is_empty | No element child and no non-empty text child. |
:root | is_root | The parent is the document node (read from the link, not a stored bit). |
:nth-child() and similar | — | Counted by the selector library along the element-only sibling chain. |
::before, ::after | match_pseudo_element | Always false. Generated content has no node, so it does not shift :nth-child or +. |
Attribute selectors see id and class. The id and class list live in the node record, not in
the attribute table, for speed. Node::attr_text reads them anyway: class is returned as the
class names joined by single spaces, in the order they were set. So [class], [id],
[class*=card], [class~=red], [class^="swatch gr"] and attr(id) all see the same values that
.card and #id do. The element also reports id and class in its attribute-name list, so
attribute-selector invalidation fires when either changes.
Every test result passes through tally::tested, which increments Counter::SelectorMatches.
Steps between elements are not counted, so the counter reflects the rule set, not the tree depth.
Matching fast paths
- Class names are interned at write time.
"btn btn-primary large"is split and interned once. The node record holds only aClassSpaninto the document's append-onlyClassPool(crates/zgui-dom/src/arena/class_pool.rs), so matching never splits, allocates or compares characters. Rewriting a node's classes appends a new run and leaves the old one in place. - Combinators are one pointer hop. Each node keeps a plain sibling chain (with text, walked by
the style traversal) and an element-only chain (
first_element_child,next_element,prev_element, walked by matching). Both are written when the node is linked (crates/zgui-dom/src/stylo/element/tree.rs). - An ancestor bloom filter rejects most descendant selectors in one word. It is filled by
add_element_unique_hashes, which calls the engine's owneach_relevant_element_hash(crates/zgui-dom/src/stylo/bloom.rs) so it inserts exactly the hashes the matcher looks for. A missing hash would make a rule silently stop matching.
The state word
Each element has one u64 state word, stored as an AtomicU64 in the node record. It is the only
store of interaction state: input routing writes it, selector matching reads it, and the engine
invalidates by comparing it before and after a change.
Code above the document uses zgui_vocab::UiState; the engine uses ElementState. They share the
same bit layout, so conversion is a reinterpretation:
pub const fn to_engine(state: UiState) -> ElementState {
ElementState::from_bits_retain(state.bits())
}Both sides assert every bit position at compile time (crates/zgui-vocab/src/state/assert.rs and
crates/zgui-dom/src/node/element/state.rs). If a bit moves on either side, the build fails.
A state pseudo-class is then one mask test: self.element_state().intersects(class.state_flag()),
using the flag the engine itself assigns. Only :lang(), :state() and one engine-internal class
have no flag and need their own branch.
Consequences:
:linkand:visitedare stored in the word when attributes are written. Computing them during matching would change the answer without changing the word, so nothing would invalidate.- Author-defined states (
:state(...)) are not in the word. They live in their own column. - Views may set only eight bits:
UiState::AUTHOR_SETTABLEisCHECKED | DISABLED | OPEN | INDETERMINATE | PLACEHOLDER_SHOWN | READ_ONLY | REQUIRED | INVALID. The framework computes the rest (:hover,:focus, and so on).
Custom properties
A custom property reaches descendants only through var(). When an element's inherited
custom-property map changes, zgui narrows the work in three steps.
1. Skip subtrees that read none of the changed names. The traversal records the names that
changed (ChangedNames). Each element stores a 64-bit bloom set of the names its own rule chains
read, plus the union over its subtree (zgui_dom::side::readers). A child subtree whose union has
no bit in common with the change is skipped and counted in Counter::CustomSubtreesSkipped.
2. Refresh, don't recascade, elements that don't read the change. An element inside a visited
subtree whose rules read none of the changed names keeps every property group and only swaps in the
parent's new map (Counter::CustomMapsRefreshed). Elements that read a changed name, or declare
custom properties of their own, recascade.
3. Diff only the names that can have changed. When a declaring element recascades only because
its parent's map moved, its own map can differ only in the parent's changed names plus the names its
own rules declare. zgui compares just those candidates instead of the whole map, and passes the
resulting (possibly smaller) set down. A row that sets --accent itself stops an --accent change
from reaching anything below it.
The narrowing falls back to treating every descendant as a reader when:
- more than 16 names changed (
NAMED_AT_MOST); - a changed name starts with
--zgui-(properties the framework reads on the element's behalf); - the element declares
--zgui-shader,--zgui-shape,--zgui-filteror--zgui-backdrop-filter(zgui_css::values::custom::WILDCARD_DECLARERS), because effects read parameters by name with novar()in any declaration; - for step 3 only: the element has running animations, which can write custom properties.
Rule-chain reads are cached across restyles. Finding which names a rule chain reads means
serialising its declarations and scanning the text, because Stylo keeps parsed references private.
The answer (RuleRefs: names read, names declared, and the bloom set) is cached in a RefsCache
owned by the engine, keyed by a hash of the declaration-block addresses in the chain. The cache holds
a strong reference to each chain, so those addresses stay valid. It is cleared when the sheet set
changes and when it exceeds 4,096 chains, since every new inline style value creates a new chain.
Computed-style sharing
A computed style is a reference-counted pointer, and so is each property group behind it (background, border, font, text, position, …):
pub type ComputedStyle = ServoArc<ComputedValues>; // servo_arc::ArcElements that cascade to the same result share allocations, and elements that differ only in their
background still share the same font group. Downstream stages key caches on group identity through
zgui_css::StructPtr (StructPtr::of(group), plus helpers such as StructPtr::font(style) and
StructPtr::inherited_text(style)).
Equal identity proves equal values. Unequal identity proves nothing. Each cascade worker keeps its own sharing cache, so n workers can produce n allocations for one logical style. An identity-keyed cache is a fast path, never the only lookup.
PaintStyleCache in crates/zgui-paint/src/lower/cache.rs shows the pattern:
| Lookup | Type | Purpose |
|---|---|---|
by_identity | FxHashMap<LoweringKey, Identity> | Fast path on group addresses. The entry holds the source style, so its addresses cannot be reused while cached. |
by_content | FxHashMap<u64, SmallVec<[PaintStyleRef; 1]>> | Fallback. The hash narrows the search and an equality check confirms it. |
On an identity miss the style is lowered, the lowering is hashed, and a content hit reuses the
existing entry. Read Counter::StylesLowered against Counter::StylesLoweredFromCache for the
sharing ratio. Identity entries are swept once the table holds more than 1,024 entries and has
doubled since the previous sweep; entries whose style only the cache still holds are removed.
Anonymous boxes rely on sharing too. zgui_css::inherited_style(parent) builds the style for a box
that CSS requires but no element declares. It reuses the parent's inherited group allocations and a
shared OnceLock of reset values. Copying the values instead would break identity: text in that box
would claim a colour slot no element owns, and a later colour change would not reach it.
Damage translation
After the traversal, translate (crates/zgui-style/src/damage/translate.rs) turns each element's
record into dirty bits on its node, and the marks are applied once the pass is done. In outline:
| Source | Marks |
|---|---|
A first cascade (record.initial) | RELAYOUT | REBUILD_BOX |
| Layout damage from zgui's damage hook | RELAYOUT, plus REBUILD_BOX, RESHAPE or REBREAK as needed |
| Ink or stacking changes without relayout | REFRAGMENT or RESTACK, with REHIT | REPAINT |
| A changed paint key | REPAINT |
| A changed accessibility key | A11Y |
Stylo's own damage bits are not used directly: its relayout bit is set for changes that only need a
repaint, and its repaint bit is missing for border colours, radii, visibility, masks and shadows.
zgui therefore classifies layout changes through its own damage hook
(TElement::compute_layout_damage), decides repainting by comparing paint keys (addresses of
shared computed-value groups), and narrows text work to a reshape or a rebreak by comparing each
element's previous text keys in TextKeyStore. The
invalidation page has the full
mapping, the paint key and the
reshape and rebreak rules.
One detail of the paint key is specific to custom properties: Stylo exposes no address for a custom-property map's allocation, so the key derives its identity from the address of the map's first entry and its length. A fresh map with the same contents causes an extra repaint, never a missed one.
Text colour
A shaped paragraph stores a brush slot rather than a colour, so a colour change rewrites a slot
instead of reshaping text. After a restyle, StyleEngine::text_paint_updates() lists a
TextPaintUpdate for each text run whose colour group changed. An element has up to three runs
(TextRun::Own, Before, After), each cascaded and coloured separately. The restyled flag says
the element was reported before; if the consumer has no record of it, its shaping is treated as
stale.
The runtime applies these in the f.brushes step (crates/zgui-runtime/src/window/brushes.rs).
Slots are claimed per cascade result, and several elements can share one. Two rules keep colours
correct:
- A slot is rewritten in place only if every element drawn through it is being re-coloured in the same batch, to the same colour.
- If an element's new cascade result already owns a different slot (claimed by another element), the element moves onto that slot and its text is reported for reshaping. Staying on the old slot would let a later re-colour of this element overwrite a slot that other elements share.
Animations
CSS animations and transitions run inside Stylo. zgui adds two entry points
(crates/zgui-style/src/engine/animate/):
StyleEngine::animation_tickadvances the clock, moves every running animation on and reports what is still running. It returns immediately when nothing is animating.StyleEngine::mark_animation_restyleis called when an animated value cannot be applied as a repaint. It gives the element an animation-only hint (replace animation and transition declarations, keep selector matches) and records it.
Reaching marked elements
The animation-only traversal starts at the root and descends only through ancestors flagged as
having animation work below. Those flags are raised at the start of the restyle
(settle_animation_marks), from where each marked element stands at that moment, not where it
was when marked. So an element that a view moved between the mark and the restyle is still reached.
An element that is out of the document at restyle time keeps its hint and waits
(StyleEngine::animation_waiting reports how many) until a later restyle finds it back in the tree.
The flags are cleared by the traversal that reads them.
Fill-forwards animations
Stylo drops a finished animation from its table when it restyles the element, whatever the fill
mode. The table is also where later matches read animation declarations, so an element with
animation-fill-mode: forwards would jump back to its base style on the next restyle (a theme
change, for example). driver/animations/fill.rs keeps these animations in place:
- Before each traversal, every finished fill-forwards animation is set back to running with its start time unchanged, so it evaluates at its end.
- After the traversal, each one that is still running (or that the traversal paused) and has ended is marked finished again, with no second end event.
- One that the traversal cancelled is removed without a cancel event, since it had already ended.
- One that a new style moved away from its end keeps whatever state the traversal gave it.
Reading computed values
Most consumers read groups directly from ComputedStyle. zgui-css adds helpers for values that
need conversion:
- Colours.
zgui_css::values::color::to_colorconverts an engine colour to azgui_color::Color, keeping its colour space. Stylo stores the second and third components ofhsl()andhwb()as percentages (0–100); zgui stores them as fractions (0–1), andto_colorscales them. - Custom properties.
zgui_css::values::customhastext,color,number,lengthandnamesfor reading a computed custom property by name (without the--prefix). - Test styles.
zgui_css::StyleDraftbuilds a computed style without a cascade, from initial values (StyleDraft::initial()) or an existing style (from_style). It performs no inheritance and resolves no units.with_custom_property(name, value)declares an inherited custom property, so code that reads custom properties can be tested without a sheet.
The parity register
The parity register records, for every CSS property, whether zgui implements it, and tests check that record against the engine and against real output.
Declarations. Each property is classified by a register_properties! call in the module that
reads it, for example in crates/zgui-paint/src/lower/background.rs:
register_properties! {
background_color => Support::Implemented("zgui-paint::lower::background"),
background_size => Support::Ignored("a background layer fills the box it is painted on"),
}| Classification | Meaning |
|---|---|
Implemented(module) | Parsed, cascaded and read by that module. |
Ignored(reason) | Parsed and cascaded but not read. |
Absent(reason) | The engine does not provide it (PrefOff, GeckoOnly, NotInStylo, NeedsFork or NotInLayout). |
Checks. Registration::check fails when the engine contradicts a declaration.
Registry::unclassified lists longhands with no declaration (parity::catalog::longhands). The
evidence probe lays out a fixture with and without each implemented property and compares fragment
geometry, hit testing, clip shapes and paint lowering; Verdict::Unchanged fails as an over-claim,
and Verdict::Inert (the declaration never reached a computed style) is reported separately. A timed
survey covers animations and transitions.
Report. crates/zgui-conformance/src/report.rs generates docs/parity.md byte-deterministically,
and a test checks the committed file matches. As committed, all 250 distinct longhands (behind 322
generated property names) are classified: 178 implemented, 72 parsed and cascaded but not yet
implemented, and 159 shown by probe to change what a frame produces.
Some implemented properties cannot be observed by the deterministic fixture (font selection needs
real faces; cursor, caret-color and user-select need a window). These carry a stated reason in
the report. An implemented property with no observable effect and no reason fails the build.
Cost
cargo xtask perf regenerates docs/performance.md with current values. The style-relevant
measurements and their limits:
| Measurement | Band | Budget | What it measures |
|---|---|---|---|
kitchen.click | 15.12 µs | — | One class on one element, 1 851 boxes. |
hover.crossing | 266.00 µs | 500 µs | One pointer crossing over a 1 000-row table: two elements restyled, two boxes repainted. |
hover.primitives_emitted | 200 prims | 200 | Only two rows changed, so emitting the whole table is a defect. |
scroll.translation.restyles | 0 elements | 0 | Scrolling changes no computed style. |
cold.first_frame | 140 ms | 250 ms | Headless: font enumeration, sheet parsing, first cascade, first layout, first emission. |
idle.frames | 0 frames | 0 | A still document draws nothing. |
Counters to check when a number moves:
| Counter | Meaning |
|---|---|
ElementsRestyled | Elements whose selector matching ran. |
ElementsRecascaded | Elements whose cascade ran with their existing matches. |
ElementsTraversed | Elements the traversal entered, styled or not. |
SelectorMatches | Simple-selector tests. A broken bloom filter shows here first. |
CustomSubtreesSkipped | Subtrees a custom-property change skipped. |
CustomMapsRefreshed | Elements that took a new custom-property map without a cascade. |
NodesVisited | Nodes any phase traversal looked at. |
StylesLowered / StylesLoweredFromCache | The sharing ratio. |
Rules of thumb:
- A class toggle restyles only elements whose selectors mention that class. If no selector mentions it, nothing is restyled.
- A colour change costs one paint-key comparison per restyled element and produces
REPAINTonly. - A custom-property change visits only subtrees that read it. Theming through custom properties on a container is cheap.
- Adding a sheet invalidates only what its selectors match; replacing a view sheet re-matches the author origin. Prefer classes or custom properties to swapping sheets.
Next
The layout engine
The box tree, the Cephal integration, incremental patching and fragments.
Invalidation
Every bit, how obligations propagate and retire, and how damage rectangles merge.
Paint and the scene
The display list as a value, the stacking-order walk and culling against damage.
Caches
Every cache in the pipeline, what fills it, what invalidates it, and what a miss costs.
Reactive internals
How zgui-reactive wraps reactive_graph — signal storage, subscriptions, marking and the flush, waking from other threads, owners, task cancellation, conditional branches, and Selector.
The layout engine
How zgui-layout builds and patches the box tree, drives the retained Cephal engine incrementally and in parallel, and produces fragments, paint order and the hit index.