Skip to content

blitz-dom,dom-shim: tighten style invalidation, lazy font gating, and CSSOM mirrors - #190

Open
BernardoPe wants to merge 7 commits into
mainfrom
bpereira/pr1-blitz-dom-fonts-dom-shim
Open

BernardoPe wants to merge 7 commits into
mainfrom
bpereira/pr1-blitz-dom-fonts-dom-shim

Conversation

@BernardoPe

Copy link
Copy Markdown
Collaborator

Part 1 of a 4-PR stack improving style/layout CPU, lazy font loading, DOM/CSSOM performance, and memory efficiency.

Summary

  • Targeted style invalidation (blitz-dom patches 0105–0107, 0109, 0113):
    • Let Stylo invalidate removed stylesheets instead of forcing every origin dirty.
    • Narrow child-list :has() invalidation to affected siblings (plus :only-child / :only-of-type TSStateForInvalidation::NTH edge flags and anchor RESTYLE_SELF when inserting between siblings under a :has() anchor) without triggering whole-subtree restyles on body:has(...).
    • Skip stylesheet registration for disconnected <style> elements, skip fetching disabled <link rel="stylesheet">, and unload/ignore stylesheets when disabled is set.
  • CSS Fonts 4 lazy @font-face gating & codepoint indexing (0108, 0110, 0111, 0113):
    • Gate lazy @font-face fetches by CSS Fonts 4 weight/style matching, visibility, variable weight ranges, fallback glyph coverage, and unmaterialized ::before/::after icon content during resolve_style.
    • Cache per-Font plans (FontRef parsed at most once per face per flush) and short-circuit repeated resolves via sticky used_font_requests when only deferred unicode-range subsets remain pending.
    • Skip non-rendered elements (<script>, <style>, <title>, <noscript>) and fast-path ASCII in codepoint indexing.
  • Core DOM exports & DOM-Shim (0112, core, dom-shim):
    • Gate between-frame animation sampling to frame intervals while keeping resolveLayout / paint sampling fresh (core/src/lib.rs, paint/render.rs).
    • Expose childCount/childIdAt, appendNodeText, styleTextEpoch, and hasPendingImageWaiter.
    • Use styleTextEpoch and appendNodeText for O(1) CSSOM insertRule mirroring while preserving CSSStyleRule object identity across unrelated <style> edits, return a live document.styleSheets list, and deep-adopt DOMParser subtrees after pre-insertion hierarchy validation.

Verification

  • cargo test -p kitesurf-core --lib -- style::tests:: dom::tests::font_face_unicode_range (passing, including new tests for :has() sibling/only-child, body:has(...) style preservation, ::before icon fonts, mixed plain/unicode-range families, link[disabled] unload + removeAttribute("href"), and non-rendered <script>/<style> text).
  • E2E tests passing: cssom-atrule-mirror, domparser-adoption-handle-privacy, domparser-move-into-document, append-large-parent, stylesheets-live.
  • pnpm run -s lint:js, pnpm run -s format:check, cargo fmt --check, and Bazel type/clippy/comment checks passing.

+ | ElementSelectorFlags::ANCHORS_RELATIVE_SELECTOR_NON_SUBJECT,
+ ) {
+ if let Some(mut data) = parent.mutate_data() {
+ data.hint |= RestyleHint::RESTYLE_SELF;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

beep-boop-rui-agent-🤖

Blocking: .p:has(> .a + .b) .y keeps its old style when a node is inserted between .a and .b.

This branch gives the anchor RESTYLE_SELF. That re-matches the anchor only, which is enough for the subject form #p:has(> .a + .b) that the new test pins. When the anchor is not the subject, the element that must change is a descendant (.y). Nothing reaches it: it is not a later sibling of the inserted node, and the inserted node has no class that the inner selector depends on.

Before this PR, an insert in a document with :has() restyled the whole parent (|| has_relative_selectors in mutator.rs, removed in 0106), so .y was matched again.

I ran this as a DomHandle host test on f236927d9 (before) and on this head. It inserts a <span> before #b and reads color of #y:

Rule Before This PR
.p:has(> .a + .b) .y { color: red } green (correct) red (stale)
.p:has(.a + .b) .y { color: red } green (correct) red (stale)
.p:has(> .a + .b) { color: red } (subject) updates updates
#[test]
fn non_subject_has_adjacent_sibling_updates_on_insert_between() {
    let html = r#"<!doctype html><style>
        .y { color: rgb(0, 128, 0); }
        .p:has(> .a + .b) .y { color: rgb(255, 0, 0); }
    </style>
    <div class="p"><i class="y" id="y"></i><span class="a"></span><span class="b" id="b"></span></div>"#;
    let dom = DomHandle::new(html, "https://example.test/");
    dom.set_viewport(800, 600);
    dom.resolve_layout();
    assert_eq!(color(&dom, "#y"), "rgb(255, 0, 0)");
    let spacer = dom.create_element("span");
    assert!(dom.insert_before_node(id(&dom, ".p"), spacer, id(&dom, "#b")));
    assert_eq!(color(&dom, "#y"), "rgb(0, 128, 0)"); // fails: still red
}

Fix: when the anchor carries ANCHORS_RELATIVE_SELECTOR_NON_SUBJECT, restyle its subtree as the old code did. Keep RESTYLE_SELF for an anchor that is only the subject. The descendant form (.p:has(.a + .b) .y) needs the same for an anchor above the parent. Please add both non-subject cases to child_list_restyle.rs.

Comment thread packages/core/src/lib.rs
#[wasm_bindgen(js_name = "loadAllFontFaces")]
pub fn load_all_font_faces(&self) {
if let Ok(mut doc) = self.doc.try_borrow_mut() {
doc.as_mut().demand_all_font_faces();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

beep-boop-rui-agent-🤖

Blocking: one document.fonts.load() call makes the document fetch every declared @font-face, and the document stays in that mode.

demand_all_font_faces sets load_all_font_faces, and nothing clears it. From then on flush_needed_font_faces skips the family, weight, style and unicode-range gates. The shim ignores the font and text arguments of load(), so a call for one family also fetches families that no style uses, and every unicode-range slice.

Before this PR, load() only waited for the fonts to be idle, and the engine fetched the faces that the styles use.

I ran this with the helpers in font_face_unicode_range.rs. The sheet has the shape of a Google Fonts css2 response: 2 families × 3 weights × 7 unicode-range slices = 42 faces. The page is <p>hello</p> with one family at weight 400:

Font fetches
no fonts.load() 1 (Body-400-latin.woff2)
after demand_all_font_faces() 42

fonts_api_demand_fetches_every_declared_face pins this, so I read it as intended. I still think it needs a decision before merge:

  • webfontloader and FontFaceObserver call document.fonts.load(). A CJK family from Google Fonts declares about 120 slices for each weight.
  • font_families() in stylo_to_parley.rs drops a family while face_pending_for_style is true. So the text stays in the fallback font until every slice has arrived, not only the slice it needs.
  • The engine font store holds 256 entries and 16 MiB, and evicts the least recently read entry.

Fix: pass the families named in the font argument down to core, and demand only their faces. The spec loads the faces that match font and cover text. Do not keep the flag for the rest of the document. That still loads a font that only a canvas uses.

Err(_) => return false,
};
let mut mutr = doc.mutate();
let ok = mutr.append_text_to_node(nid, text).is_ok();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

beep-boop-rui-agent-🤖

Blocking (small): appendNodeText passes an unchecked node id to Blitz and panics on a dropped node.

resolve_node_id still returns an id for a text node that set_node_text dropped from its parent, because remove_and_drop_all_children does not retire the handle. append_text_to_node then reads self.doc.nodes[node_id] and panics. AGENTS.md asks for node ids to be validated before they reach Blitz, and the other mutators in this file do that: set_node_text returns false when doc.get_node(nid) is None.

I ran this on this head:

let dom = DomHandle::new("<!doctype html><style id=s>a{}</style>", "https://example.test/");
let style = dom.query_selector("#s").unwrap() as u32;
let text = dom.child_id_at(style, 0) as u32;
assert!(dom.set_node_text(style, "b{}"));
assert!(!dom.append_node_text(text, "c{}"));
// panics: invalid NodeId NodeId(5v1): no live node (blitz-dom src/mutator.rs:330)

The only caller is the insertRule append path in collections.ts. It catches the error and writes the full text, so I expect a caught wasm panic and no wrong output.

Fix: return false when doc.get_node(nid) is None, before doc.mutate(). Please keep the test above.

@BernardoPe
BernardoPe force-pushed the bpereira/pr1-blitz-dom-fonts-dom-shim branch 8 times, most recently from cbedc10 to 50dd99e Compare November 21, 2026 03:46
A page that appends into a large parent paid for a fresh child-id array on
every attached-check, and every collection read rebuilt its record list. Read
child counts from the node store instead, share the record list across reads,
and mark `document.currentScript` as read so only a script that actually
observed it has to settle its microtasks before the value clears.

Adoption and DOM parsing keep the same handles, so a moved node never leaks a
second record and `adoptNode`/`importNode` results stay private to their
document.

Signed-off-by: bpereira <bpereira@cloudflare.com>
Removing a `<style>` or a `<link>` left the elements it styled on the old
cascade, and a child inserted or removed under a `:has()` anchor only
invalidated the anchor when it also had a matching sibling, so
`:has(:is(.a + .b + .c))` and `:has(> .child + .child)` kept stale matches.
Invalidate like Gecko does: let stylo handle a removed sheet and mark the
anchor for a self-restyle on any child-list change.

A disconnected element now computes with no stylesheet, which is what a
`<template>`'s contents and a freshly created node should see.

Signed-off-by: bpereira <bpereira@cloudflare.com>
Every declared `@font-face` was downloaded on the first resolve, so a page
pulled all weights, styles and unicode-range subsets of every family it
declared. Gate the flush on what the styles actually select, keep a face
queued until its `unicode-range` covers document text, and skip faces whose
only users are non-rendered. Record the style parent and a text epoch on text
appends so the flush can tell which subtrees changed.

A text-less element still loads its primary family, because `cap`, `ch`, `ex`
and `ic` read its metrics. In stylo, a `-webkit-`-prefixed function token is a
family name, so a legacy `-webkit-generic(fangsong)` falls through to the next
family instead of dropping the declaration.

Signed-off-by: bpereira <bpereira@cloudflare.com>
With a real web font loaded, `measureText("\u{0}")` shaped the NUL as .notdef
and returned a full advance; canvas ignores it. A bare `generic(fangsong)` in
`ctx.font` also matched an `@font-face` that happened to carry that name,
though CSS Fonts 5 makes it a generic name; a quoted `"generic(fangsong)"`
stays a family name.

Signed-off-by: bpereira <bpereira@cloudflare.com>
…ared faces

`document.fonts.load()` is an explicit request, so it now fetches every
declared face (new `loadAllFontFaces` export) once the stylesheets are applied,
while `document.fonts.ready` only waits for the faces already in use. The
request is retried briefly because a sheet can land after the call.

Signed-off-by: bpereira <bpereira@cloudflare.com>
`setTimeout(fn, 0)` re-armed from inside its own callback ran back to back and
monopolised the isolate, starving the load drain's own timer. Apply HTML's
nesting clamp: past five levels, a shorter timeout becomes 4 ms.

Signed-off-by: bpereira <bpereira@cloudflare.com>
Web fonts now load when they are used, so canvas text, `font-size-adjust` and
grid parsing resolve with the intended metrics and 26 tests pinned FAIL pass.

Signed-off-by: bpereira <bpereira@cloudflare.com>
@BernardoPe
BernardoPe force-pushed the bpereira/pr1-blitz-dom-fonts-dom-shim branch from 50dd99e to 34a4fd4 Compare November 21, 2026 05:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants