Repository navigation
blitz-dom,dom-shim: tighten style invalidation, lazy font gating, and CSSOM mirrors - #190
BernardoPe wants to merge 7 commits into
Conversation
e217693 to
f6752a0
Compare
f6752a0 to
8ec4747
Compare
| + | ElementSelectorFlags::ANCHORS_RELATIVE_SELECTOR_NON_SUBJECT, | ||
| + ) { | ||
| + if let Some(mut data) = parent.mutate_data() { | ||
| + data.hint |= RestyleHint::RESTYLE_SELF; |
There was a problem hiding this comment.
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.
| #[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(); |
There was a problem hiding this comment.
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()instylo_to_parley.rsdrops a family whileface_pending_for_styleis 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(); |
There was a problem hiding this comment.
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.
cbedc10 to
50dd99e
Compare
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>
50dd99e to
34a4fd4
Compare
Part 1 of a 4-PR stack improving style/layout CPU, lazy font loading, DOM/CSSOM performance, and memory efficiency.
Summary
blitz-dompatches0105–0107,0109,0113)::has()invalidation to affected siblings (plus:only-child/:only-of-typeTSStateForInvalidation::NTHedge flags and anchorRESTYLE_SELFwhen inserting between siblings under a:has()anchor) without triggering whole-subtree restyles onbody:has(...).<style>elements, skip fetching disabled<link rel="stylesheet">, and unload/ignore stylesheets whendisabledis set.@font-facegating & codepoint indexing (0108,0110,0111,0113):@font-facefetches by CSS Fonts 4 weight/style matching, visibility, variable weight ranges, fallback glyph coverage, and unmaterialized::before/::aftericon content duringresolve_style.Fontplans (FontRefparsed at most once per face per flush) and short-circuit repeated resolves via stickyused_font_requestswhen only deferredunicode-rangesubsets remain pending.<script>,<style>,<title>,<noscript>) and fast-path ASCII in codepoint indexing.0112,core,dom-shim):resolveLayout/ paint sampling fresh (core/src/lib.rs,paint/render.rs).childCount/childIdAt,appendNodeText,styleTextEpoch, andhasPendingImageWaiter.styleTextEpochandappendNodeTextfor O(1) CSSOMinsertRulemirroring while preservingCSSStyleRuleobject identity across unrelated<style>edits, return a livedocument.styleSheetslist, and deep-adoptDOMParsersubtrees 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,::beforeicon fonts, mixed plain/unicode-rangefamilies,link[disabled]unload +removeAttribute("href"), and non-rendered<script>/<style>text).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.