Skip to content

Lightpanda: the headless browser designed for AI and automation

Merge branch 'main' into incremental-insert-rule

Adrià Arrufata80e184142c0
diff --cc src/browser/StyleManager.zig
index 8fe9562b7,1b25a38b1..a243b0141
--- a/src/browser/StyleManager.zig
+++ b/src/browser/StyleManager.zig
@@@ -447,31 -441,151 +446,123 @@@ fn finalizeLayerRanks(self: *StyleManag
while (tag_it.next()) |rules| {
self.stampRuleList(rules);
}
+
- // Even if we lazilly parse custom properties, we need to stamp the priority
- // now, since the rule_layers only exist during the build
++ // Custom rules parse their selectors lazily, but the layer ranks are only
++ // known now that every sheet has been read
+ var custom_it = self.custom_rules.valueIterator();
+ while (custom_it.next()) |property| {
+ for (property.rules.items) |*rule| {
- rule.priority |= @as(u64, self.layerRank(rule.priority)) << RANK_SHIFT;
++ rule.priority |= self.layerRank(rule.priority) << RANK_SHIFT;
+ }
+ }
}
fn stampRuleList(self: *StyleManager, rules: *RuleList) void {
- const layers = self.layers.items;
- const rule_layers = self.rule_layers.items;
for (rules.items(.priority)) |*priority| {
- const doc_order: u32 = @as(u22, @truncate(priority.*));
- const layer = rule_layers[doc_order - 1];
- if (layer == NO_LAYER) {
- continue;
- }
- priority.* |= @as(u64, layers[layer].rank) << RANK_SHIFT;
- priority.* |= @as(u64, self.layerRank(priority.*)) << RANK_SHIFT;
++ priority.* |= self.layerRank(priority.*) << RANK_SHIFT;
}
}
- fn addRawRule(self: *StyleManager, selector_text: []const u8, block_text: []const u8, layer: u16) !void {
- if (selector_text.len == 0) return;
-/// The cascade-layer rank for a packed priority, via its doc_order.
-fn layerRank(self: *const StyleManager, priority: u64) u32 {
++/// The rank finalizeLayerRanks still has to stamp for a packed priority, via
++/// its doc_order: 0 for an unlayered rule, which packed UNLAYERED_RANK at
++/// creation.
++fn layerRank(self: *const StyleManager, priority: u64) u64 {
+ const doc_order: u32 = @as(u22, @truncate(priority));
+ const layer = self.rule_layers.items[doc_order - 1];
- return if (layer == NO_LAYER) UNLAYERED_RANK else self.layers.items[layer].rank;
++ if (layer == NO_LAYER) {
++ return 0;
++ }
++ return self.layers.items[layer].rank;
+ }
+
+ fn addRawRule(self: *StyleManager, build_arena: Allocator, selector_text: []const u8, block_text: []const u8, layer: u16) !void {
+ if (selector_text.len == 0) {
+ return;
+ }
-
- var props = VisibilityProperties{};
-
- // Keyed rather than appended so a block declaring the same custom property
- // twice keeps only the winner. Lives in build_arena: addSelectorRules
- // copies what it needs into the rule arena.
- var customs: std.StringArrayHashMapUnmanaged(CustomDeclaration) = .empty;
-
- var it = CssParser.parseDeclarationsList(block_text);
- while (it.next()) |decl| {
- if (isCustomProperty(decl.name)) {
- // Last one wins, except that a normal declaration never overrides
- // an earlier !important one, same as applyParsedDeclaration.
- const gop = try customs.getOrPut(build_arena, decl.name);
- if (gop.found_existing and gop.value_ptr.important and decl.important == false) {
- continue;
- }
- gop.value_ptr.* = .{ .name = decl.name, .value = decl.value, .important = decl.important };
- } else {
- props.apply(decl.name, decl.value);
- }
- }
-
- return self.addSelectorRules(build_arena, selector_text, props, customs.values(), layer);
++ var customs: CustomSink = .{ .allocator = build_arena };
++ const props = try foldDeclarations(block_text, &customs);
++ _ = try self.addSelectorRules(selector_text, props, customs.map.values(), layer);
+ }
+
+ // Visibility rules get one VisibilityRule per selector (not per selector list)
+ // so each has correct specificity, bucketed by their rightmost selector part.
+ // Custom properties are keyed by name instead, and lazily parse the selector.
++// Returns whether the rule set any tracked property.
+ fn addSelectorRules(
+ self: *StyleManager,
- build_arena: Allocator,
+ selector_text: []const u8,
+ props: VisibilityProperties,
+ customs: []const CustomDeclaration,
+ layer: u16,
-) !void {
++) !bool {
+ const relevant = props.isRelevant();
+ if (relevant == false and customs.len == 0) {
- return;
++ return false;
+ }
+
+ const arena = self.arena.allocator();
++ const before = self.next_doc_order;
- const props = foldVisibilityDeclarations(block_text);
- if (!props.isRelevant()) return;
+ if (customs.len > 0) {
- const doc_order = @min(self.next_doc_order, MAX_DOC_ORDER);
- self.next_doc_order += 1;
- try self.rule_layers.append(build_arena, layer);
-
++ const priority = try self.nextPriority(layer);
+ for (customs) |custom| {
+ const gop = try self.custom_rules.getOrPut(arena, custom.name);
+ if (gop.found_existing == false) {
+ gop.value_ptr.* = .{};
+ }
++ // An appended rule joins a property that may already be parsed
++ gop.value_ptr.parsed = null;
+ try gop.value_ptr.rules.append(arena, .{
+ .value = custom.value,
- .priority = doc_order,
++ .priority = priority,
+ .selector_text = selector_text,
+ });
+ }
+ }
- const selectors = SelectorParser.parseList(self.arena.allocator(), selector_text) catch return;
- if (relevant == false) {
- return;
- }
-
- const selectors = SelectorParser.parseList(arena, selector_text) catch return;
-
-- for (selectors) |selector| {
- try self.addVisibilityRule(selector, props, layer);
- // Get the rightmost compound (last segment, or first if no segments)
- const rightmost = if (selector.segments.len > 0)
- selector.segments[selector.segments.len - 1].compound
- else
- selector.first;
-
- // Find the bucketing key from rightmost compound
- const bucket_key = getBucketKey(rightmost) orelse continue; // skip if dynamic pseudo-class
-
- const rule = VisibilityRule{
- .props = props,
- .selector = selector,
- .priority = (@as(u64, computeSpecificity(selector)) << SPEC_SHIFT) | @min(self.next_doc_order, MAX_DOC_ORDER),
- };
- self.next_doc_order += 1;
- try self.rule_layers.append(build_arena, layer);
-
- switch (bucket_key) {
- .id => |id| {
- const gop = try self.id_rules.getOrPut(arena, id);
- if (!gop.found_existing) {
- gop.value_ptr.* = .{};
- }
- try gop.value_ptr.append(arena, rule);
- },
- .class => |class| {
- const gop = try self.class_rules.getOrPut(arena, class);
- if (!gop.found_existing) {
- gop.value_ptr.* = .{};
- }
- try gop.value_ptr.append(arena, rule);
- },
- .tag => |tag| {
- const gop = try self.tag_rules.getOrPut(arena, tag);
- if (!gop.found_existing) {
- gop.value_ptr.* = .{};
- }
- try gop.value_ptr.append(arena, rule);
- },
- .other => {
- try self.other_rules.append(arena, rule);
- },
++ if (relevant) {
++ const selectors = SelectorParser.parseList(arena, selector_text) catch &.{};
++ for (selectors) |selector| {
++ try self.addVisibilityRule(selector, props, layer);
+ }
}
++ return self.next_doc_order != before;
++}
++
++fn addVisibilityRule(self: *StyleManager, selector: Selector.Selector, props: VisibilityProperties, layer: u16) !void {
++ const key = getBucketKey(selector.rightmost()) orelse return;
++ const priority = try self.nextPriority(layer);
++ try self.bucket(key, .{
++ .props = props,
++ .selector = selector,
++ .priority = priority | (@as(u64, computeSpecificity(selector)) << SPEC_SHIFT),
++ });
++}
++
++/// Rank and document-order bits of the next rule. A rule outside any layer
++/// carries UNLAYERED_RANK from the start; finalizeLayerRanks stamps the
++/// layered ones once every layer is known.
++fn nextPriority(self: *StyleManager, layer: u16) !u64 {
++ try self.rule_layers.append(self.arena.allocator(), layer);
++ const rank: u64 = if (layer == NO_LAYER) UNLAYERED_RANK else 0;
++ const priority = (rank << RANK_SHIFT) | @min(self.next_doc_order, MAX_DOC_ORDER);
++ self.next_doc_order += 1;
++ return priority;
++}
++
++fn bucket(self: *StyleManager, key: BucketKey, rule: VisibilityRule) !void {
++ const allocator = self.arena.allocator();
++ const list: *RuleList = switch (key) {
++ .id => |id| (try self.id_rules.getOrPutValue(allocator, id, .empty)).value_ptr,
++ .class => |class| (try self.class_rules.getOrPutValue(allocator, class, .empty)).value_ptr,
++ .tag => |tag| (try self.tag_rules.getOrPutValue(allocator, tag, .empty)).value_ptr,
++ .other => &self.other_rules,
++ };
++ try list.append(allocator, rule);
+ }
+
+ fn isCustomProperty(name: []const u8) bool {
+ return std.mem.startsWith(u8, name, "--");
}
pub fn sheetModified(self: *StyleManager) void {
@@@ -531,9 -641,11 +623,12 @@@ fn rebuildIfDirty(self: *StyleManager)
self.other_rules = .{};
try self.other_rules.ensureTotalCapacity(self.arena.allocator(), other_rules_count);
+ self.custom_rules = .empty;
+ try self.custom_rules.ensureTotalCapacity(self.arena.allocator(), custom_rules_count);
+
const sheets = self.frame.document._style_sheets orelse return;
for (sheets._sheets.items) |sheet| {
+ const before = self.next_doc_order;
self.parseSheet(build_arena.allocator(), sheet) catch |err| {
log.err(.browser, "StyleManager parseSheet", .{ .err = err });
return err;
@@@ -791,98 -880,52 +866,91 @@@ fn matchesUaDisplayNoneRule(el: *Elemen
return false;
}
- /// Buckets a CSSOM style rule; returns whether it set any tracked property.
-// Extracts visibility-relevant rules and custom properties from a CSSOM rule.
-// Creates one VisibilityRule per selector (not per selector list) so each has
-// correct specificity, bucketed by the rightmost selector part for fast lookup.
-// The raw-text twin of this is addRawRule; both hand off to addSelectorRules.
-fn addRule(self: *StyleManager, build_arena: Allocator, style_rule: *CSSStyleRule) !void {
++/// The CSSOM twin of addRawRule; returns whether the rule set any tracked
++/// property.
+fn addRule(self: *StyleManager, style_rule: *CSSStyleRule) !bool {
const selector_text = style_rule._selector_text;
if (selector_text.len == 0) {
- return;
+ return false;
}
-
- const style = style_rule._style orelse return;
+ const style = style_rule._style orelse return false;
const props = extractVisibilityProperties(style);
- if (!props.isRelevant()) {
- return false;
- }
- const selectors = SelectorParser.parseList(self.arena.allocator(), selector_text) catch return false;
+ const customs = try self.extractCustomDeclarations(style);
- const before = self.next_doc_order;
- for (selectors) |selector| {
- try self.addVisibilityRule(selector, props, NO_LAYER);
- }
- return self.next_doc_order != before;
+ // A custom rule holds selector_text until the property is looked up, but it
+ // doesn't need a copy: setSelectorText allocates the replacement from the
+ // frame arena and never frees the old one. Worst case we match a stale
+ // selector, which is what the rest of this file already does when a rule is
+ // mutated without going through sheetModified().
- return self.addSelectorRules(build_arena, selector_text, props, customs, NO_LAYER);
++ return self.addSelectorRules(selector_text, props, customs, NO_LAYER);
+}
+
+/// A style rule appended at or after the sheet that emitted the last rule is
+/// last in cascade order, so it joins the buckets directly. Anything else
+/// takes the rebuild path.
+pub fn ruleInserted(self: *StyleManager, sheet: *CSSStyleSheet, rule: *CSSRule) void {
+ if (self.dirty) {
+ // The pending rebuild reads the sheet's rules and picks it up.
+ return;
+ }
+ const style_rule = switch (rule._type) {
+ .style => |s| s,
+ else => return self.sheetModified(),
+ };
+ if (!self.appendable(sheet, rule)) {
+ return self.sheetModified();
+ }
+ const added = self.addRule(style_rule) catch return self.sheetModified();
+ if (!added) {
+ // Nothing tracked changed, so every memoized answer still holds.
+ return;
+ }
+ self.last_rule_sheet = sheet;
+ self.cascadeChanged();
}
-/// The CSSOM counterpart to addRawRule's `--*` branch. Names within one
+fn appendable(self: *const StyleManager, sheet: *CSSStyleSheet, rule: *CSSRule) bool {
+ const rules = sheet._css_rules orelse return false;
+ if (rules._rules.getLastOrNull() != rule) {
+ return false;
+ }
+ const sheets = self.frame.document._style_sheets orelse return false;
+ var past_last = self.last_rule_sheet == null;
+ for (sheets._sheets.items) |s| {
+ if (s == self.last_rule_sheet) {
+ past_last = true;
+ }
+ if (s == sheet) {
+ return past_last;
+ }
+ }
+ return false;
+}
+
- /// A rule outside any layer carries UNLAYERED_RANK from the start;
- /// finalizeLayerRanks stamps the layered ones once every layer is known.
- fn addVisibilityRule(self: *StyleManager, selector: Selector.Selector, props: VisibilityProperties, layer: u16) !void {
- const key = getBucketKey(selector.rightmost()) orelse return;
- try self.rule_layers.append(self.arena.allocator(), layer);
- try self.bucket(key, .{
- .props = props,
- .selector = selector,
- .priority = self.rulePriority(selector, layer),
- });
- }
-
- fn rulePriority(self: *StyleManager, selector: Selector.Selector, layer: u16) u64 {
- const rank: u64 = if (layer == NO_LAYER) UNLAYERED_RANK else 0;
- const priority = (rank << RANK_SHIFT) |
- (@as(u64, computeSpecificity(selector)) << SPEC_SHIFT) |
- @min(self.next_doc_order, MAX_DOC_ORDER);
- self.next_doc_order += 1;
- return priority;
- }
-
- fn bucket(self: *StyleManager, key: BucketKey, rule: VisibilityRule) !void {
- const allocator = self.arena.allocator();
- const list: *RuleList = switch (key) {
- .id => |id| (try self.id_rules.getOrPutValue(allocator, id, .empty)).value_ptr,
- .class => |class| (try self.class_rules.getOrPutValue(allocator, class, .empty)).value_ptr,
- .tag => |tag| (try self.tag_rules.getOrPutValue(allocator, tag, .empty)).value_ptr,
- .other => &self.other_rules,
- };
- try list.append(allocator, rule);
++/// The CSSOM counterpart to foldDeclarations' `--*` branch. Names within one
+ /// declaration block are already unique, so there is nothing to dedup here.
+ ///
+ /// Unlike the selector text, both strings have to be copied: they can point
+ /// into the Property itself (small string optimization), and setProperty /
+ /// removeProperty destroy it without going through sheetModified(). We'd be
+ /// left reading freed memory rather than something merely stale.
+ fn extractCustomDeclarations(self: *StyleManager, style: *CSSStyleProperties) ![]const CustomDeclaration {
+ const arena = self.arena.allocator();
+
+ var customs: std.ArrayList(CustomDeclaration) = .empty;
+ var it = style.asCSSStyleDeclaration().iterator();
+ while (it.next()) |property| {
+ const name = property._name.str();
+ if (isCustomProperty(name) == false) {
+ continue;
+ }
+ try customs.append(arena, .{
+ .name = try arena.dupe(u8, name),
+ .value = try arena.dupe(u8, property._value.str()),
+ .important = property._important,
+ });
+ }
+ return customs.items;
}
const BucketKey = union(enum) {
@@@ -1120,32 -1182,11 +1206,12 @@@ fn inlineProps(el: *Element, frame: *Fr
// Neither a style object nor a style attribute; skip both lookups.
return .{};
}
- if (inlineStyle(el, access, frame)) |style| {
+ if (el.existingStyle(frame)) |style| {
return extractVisibilityProperties(style);
}
- // A JS-created object is read by both modes; `scan` folds the attribute
- // text instead of parsing it into the page arena.
- if (access == .scan) {
- if (el.getAttributeInterned("style")) |attr| {
- return foldVisibilityDeclarations(attr);
- }
- }
- return .{};
- }
-
- /// `frame` must be el's owner frame (el.ownerFrame): that is the map where
- /// the materialized style lives.
- fn inlineStyle(el: *Element, comptime access: InlineAccess, frame: *Frame) ?*CSSStyleProperties {
- if (el.getStyle(frame)) |style| {
- return style;
- }
- if (access == .scan or el.getAttributeInterned("style") == null) {
- return null;
- }
- return el.getOrCreateStyle(frame) catch |err| {
- log.err(.browser, "StyleManager getOrCreateStyle", .{ .err = err });
- return null;
- };
+ const attr = el.getAttributeInterned("style") orelse return .{};
- return scanInlineProps(attr);
++ // Without a sink nothing allocates
++ return foldDeclarations(attr, null) catch unreachable;
}
fn styleValue(style: *CSSStyleProperties, property_name: String) ?[]const u8 {
@@@ -1153,10 -1194,10 +1219,19 @@@
return property._value.str();
}
++/// `--*` declarations of one block, keyed by name so a block declaring the same
++/// custom property twice keeps only the winner.
++const CustomSink = struct {
++ allocator: Allocator,
++ map: std.StringArrayHashMapUnmanaged(CustomDeclaration) = .empty,
++};
++
// Must agree with CSSStyleDeclaration.applyDeclarations, which is what the
// materialized object was built from: a normal declaration never overrides an
--// earlier !important one, and an empty value removes the property.
- fn foldVisibilityDeclarations(attr: []const u8) VisibilityProperties {
-fn scanInlineProps(attr: []const u8) VisibilityProperties {
++// earlier !important one, and an empty value removes the property. The tracked
++// properties are matched case-insensitively; a custom property's name is
++// case-sensitive and goes to `customs` when there is one.
++fn foldDeclarations(block: []const u8, customs: ?*CustomSink) !VisibilityProperties {
const Slot = struct {
value: ?[]const u8 = null,
important: bool = false,
@@@ -1175,8 -1216,8 +1250,17 @@@
};
var slots = [_]Slot{.{}} ** property_names.len;
-- var it = CssParser.parseDeclarationsList(attr);
++ var it = CssParser.parseDeclarationsList(block);
while (it.next()) |declaration| {
++ if (isCustomProperty(declaration.name)) {
++ const sink = customs orelse continue;
++ const gop = try sink.map.getOrPut(sink.allocator, declaration.name);
++ if (gop.found_existing and gop.value_ptr.important and !declaration.important) {
++ continue;
++ }
++ gop.value_ptr.* = .{ .name = declaration.name, .value = declaration.value, .important = declaration.important };
++ continue;
++ }
for (property_names, &slots) |name, *slot| {
if (std.ascii.eqlIgnoreCase(declaration.name, name)) {
slot.apply(declaration);
@@@ -1203,6 -1244,84 +1287,79 @@@ pub fn inlineStyleValue(self: *StyleMan
return styleValue(style, property_name);
}
+ /// Computed value of a custom property (`--x`) on `el`, or null when nothing
+ /// declares it. The value is returned as-is, no var substitution
+ pub fn customPropertyValue(self: *StyleManager, el: *Element, property_name: String) ?[]const u8 {
+ self.rebuildIfDirty() catch return null;
+
+ // Only the rules declaring this name; usually a handful, often none. An
+ // element can still shadow them with an inline declaration, so a miss here
+ // means walking for inline styles, not returning early.
+ const rules = self.parsedCustomRules(property_name.str()) catch |err| blk: {
+ log.err(.browser, "StyleManager customProperty", .{ .err = err });
+ break :blk &.{};
+ };
+
+ var current: ?*Element = el;
+ while (current) |elem| : (current = elem.parentElement()) {
+ if (self.inlineStyleValue(elem, property_name)) |value| {
+ return value;
+ }
+
+ var winner: ?[]const u8 = null;
+ var priority: u64 = 0;
+ for (rules) |rule| {
+ if (rule.priority <= priority) {
+ continue;
+ }
+ if (matchesSelector(elem, rule.selector, self.frame) == false) {
+ continue;
+ }
+ winner = rule.value;
+ priority = rule.priority;
+ }
+
+ if (winner) |value| {
+ return value;
+ }
+ }
+
+ return null;
+ }
+
+ /// Gets the parsed rule for a custom property name
+ fn parsedCustomRules(self: *StyleManager, name: []const u8) ![]const ParsedCustomRule {
+ const property = self.custom_rules.getPtr(name) orelse return &.{};
+ if (property.parsed) |parsed| {
+ // the custom property exists, and we already parsed it.
+ return parsed;
+ }
+
+ const arena = self.arena.allocator();
+ var parsed: std.ArrayList(ParsedCustomRule) = .empty;
+
+ for (property.rules.items) |rule| {
+ const selectors = SelectorParser.parseList(arena, rule.selector_text) catch continue;
+ for (selectors) |selector| {
- const rightmost = if (selector.segments.len > 0)
- selector.segments[selector.segments.len - 1].compound
- else
- selector.first;
-
+ {
+ // we don't use buckets for custom properties (are property name
+ // lookup is more efficient), but we still want to skip dynamic
+ // pseudo-classes just like visibility does
- _ = getBucketKey(rightmost) orelse continue;
++ _ = getBucketKey(selector.rightmost()) orelse continue;
+ }
+
+ try parsed.append(arena, .{
+ .selector = selector,
+ .value = rule.value,
+ .priority = rule.priority | (@as(u64, computeSpecificity(selector)) << SPEC_SHIFT),
+ });
+ }
+ }
+
+ property.parsed = parsed.items;
+ return parsed.items;
+ }
+
/// Bounds computedFontSize's ancestor recursion (the parent walk and
/// `inherit`/relative-unit chains share it).
const MAX_FONT_ANCESTOR_DEPTH = 32;
@@@ -1518,50 -1638,6 +1676,57 @@@ test "StyleManager: memo: reuse and inv
// A stylesheet change resets the memo
sm.sheetModified();
- try testing.expectEqual(false, sm.isHidden(p, null, .{}, .scan));
+ try testing.expectEqual(false, sm.isHidden(p, .{}));
try testing.expectEqual(2, sm.memo.count());
}
+
+test "StyleManager: ruleInserted: append joins the buckets without a rebuild" {
+ const frame = try testing.createFrame();
+ defer testing.test_session.closeAllPages();
+ const sm = &frame._style_manager;
+
+ const doc = frame.document;
+ const html = (try doc.createElement("html", null, frame)).asNode();
+ _ = try doc.asNode().appendChild(html, frame);
+ const body = (try doc.createElement("body", null, frame)).asNode();
+ _ = try html.appendChild(body, frame);
+ // No whitespace between the elements: they must be adjacent siblings
- try Frame.parse.htmlAsChildren(frame, body, "<style>.a { display: none }</style><div class=\"a\"></div><div class=\"b\"></div><div class=\"c\"></div>");
- const style_el = body.firstChild().?.as(Element).as(Element.Html.Style);
- const b = style_el.asNode().nextSibling().?.nextSibling().?.as(Element);
++ try Frame.parse.htmlAsChildren(frame, body, "<div class=\"a\"></div><div class=\"b\"></div><div class=\"c\"></div>");
++ const a = body.firstChild().?.as(Element);
++ const b = a.asNode().nextSibling().?.as(Element);
+ const c = b.asNode().nextSibling().?.as(Element);
- const sheet = (try style_el.getSheet(frame)) orelse return error.NoSheet;
+
- try testing.expectEqual(false, sm.isHidden(b, null, .{}, .scan));
++ // The fragment parser skips a <style>'s ready work, which is what creates
++ // and registers its sheet; a connected insert runs it.
++ const style_el = (try doc.createElement("style", null, frame)).as(Element.Html.Style);
++ try style_el.asNode().setTextContent(".a { display: none }", frame);
++ _ = try body.insertBefore(style_el.asNode(), a.asNode(), frame);
++ const sheet = style_el._sheet orelse return error.NoSheet;
++
++ try testing.expectEqual(true, sm.isHidden(a, .{}));
++ try testing.expectEqual(false, sm.isHidden(b, .{}));
+ try testing.expectEqual(false, sm.dirty);
+
+ // Appended to the last sheet: no rebuild, but the memo is stale
+ _ = try sheet.insertRule(".b { display: none }", 1, frame);
+ try testing.expectEqual(false, sm.dirty);
- try testing.expectEqual(true, sm.isHidden(b, null, .{}, .scan));
- try testing.expectEqual(false, sm.isHidden(c, null, .{}, .scan));
++ try testing.expectEqual(true, sm.isHidden(b, .{}));
++ try testing.expectEqual(false, sm.isHidden(c, .{}));
+
+ // A later append wins over the earlier one at equal specificity
+ _ = try sheet.insertRule(".b { display: block }", 2, frame);
+ try testing.expectEqual(false, sm.dirty);
- try testing.expectEqual(false, sm.isHidden(b, null, .{}, .scan));
++ try testing.expectEqual(false, sm.isHidden(b, .{}));
+
+ // Inserting in the middle rebuilds; the cascade must agree either way
+ _ = try sheet.insertRule(".c { display: none }", 0, frame);
+ try testing.expectEqual(true, sm.dirty);
- try testing.expectEqual(true, sm.isHidden(c, null, .{}, .scan));
- try testing.expectEqual(false, sm.isHidden(b, null, .{}, .scan));
++ try testing.expectEqual(true, sm.isHidden(c, .{}));
++ try testing.expectEqual(false, sm.isHidden(b, .{}));
+ try testing.expectEqual(false, sm.dirty);
+
+ // At-rules always rebuild
+ _ = try sheet.insertRule("@media (min-width: 1px) { .c { display: block } }", 4, frame);
+ try testing.expectEqual(true, sm.dirty);
- try testing.expectEqual(false, sm.isHidden(c, null, .{}, .scan));
++ try testing.expectEqual(false, sm.isHidden(c, .{}));
+}
diff --cc src/browser/tests/css/custom_properties.html
index 000000000,8c34f7ee0..91fe82b51
mode 000000,100644..100644
--- a/src/browser/tests/css/custom_properties.html
+++ b/src/browser/tests/css/custom_properties.html
@@@ -1,0 -1,181 +1,201 @@@
+ <!DOCTYPE html>
+ <head>
+ <script src="../testing.js"></script>
+ </head>
+
+ <!--
+ getComputedStyle().getPropertyValue('--x') resolution.
+
+ Custom properties inherit, so the answer depends on the element asked, not
+ just on the document: the nearest ancestor that declares the property wins
+ outright, and specificity only breaks ties between rules matching that same
+ element. The declared token stream is returned verbatim - `var()` inside a
+ value is NOT substituted.
+ -->
+
+ <style>
+ :root { --brand: #336699; --theme: light; }
+ html { --from-html: html; }
+
+ .card { --pad: 16px; --dup: from-class; }
+ #card { --dup: from-id; }
+
+ /* Case-sensitive: these are two different properties. */
+ #case { --Token: upper; --token: lower; }
+
+ /* Later normal declaration wins, but never over an earlier !important. */
+ #within-block { --normal-last: first; --normal-last: second; }
+ #within-block { --important-first: kept !important; --important-first: ignored; }
+
+ /* Interaction state can't be resolved statically, so :hover is skipped. */
+ #dynamic:hover { --hover-only: nope; }
+
+ /* Values are stored as declared: no var() substitution. */
+ #alias { --base: 4px; --derived: var(--base); }
+
+ /* Nearest ancestor wins over a more specific rule further up. */
+ #outer.outer.outer { --nearest: far; }
+ .inner { --nearest: near; }
+ </style>
+
+ <body>
+ <div class="card" id="card" style="--inline: 8px; --pad: inline-wins">card</div>
+ <div class="card">plain card</div>
+ <div id="case">case</div>
+ <div id="within-block">within-block</div>
+ <div id="dynamic">dynamic</div>
+ <div id="alias">alias</div>
+ <div id="outer" class="outer"><div class="inner"><span id="nearest">nearest</span></div></div>
+ <div id="plain">plain</div>
+ <style id="dyn"></style>
+ </body>
+
+ <script id=custom_property_sources>
+ {
+ const card = getComputedStyle($('#card'));
+ // Declared on :root, reached by inheritance.
+ testing.expectEqual('#336699', card.getPropertyValue('--brand'));
+ testing.expectEqual('html', card.getPropertyValue('--from-html'));
+ // Declared on the element's own class rule.
+ testing.expectEqual('16px', getComputedStyle($('.card:not([id])')).getPropertyValue('--pad'));
+ // Inline declaration beats the class rule.
+ testing.expectEqual('inline-wins', card.getPropertyValue('--pad'));
+ testing.expectEqual('8px', card.getPropertyValue('--inline'));
+ // Higher specificity wins between two rules matching the same element.
+ testing.expectEqual('from-id', card.getPropertyValue('--dup'));
+
+ // :root is reachable from the root element itself, not only by inheritance.
+ testing.expectEqual('#336699', getComputedStyle(document.documentElement).getPropertyValue('--brand'));
+
+ // Undeclared names resolve to the empty string.
+ testing.expectEqual('', card.getPropertyValue('--nope'));
+ testing.expectEqual('', getComputedStyle($('#plain')).getPropertyValue('--nope'));
+ }
+ </script>
+
+ <script id=custom_property_case_sensitive>
+ {
+ const style = getComputedStyle($('#case'));
+ testing.expectEqual('upper', style.getPropertyValue('--Token'));
+ testing.expectEqual('lower', style.getPropertyValue('--token'));
+ testing.expectEqual('', style.getPropertyValue('--TOKEN'));
+
+ // Same on the inline path: --A and --a are distinct properties.
+ const el = document.createElement('div');
+ el.style.setProperty('--A', 'a-upper');
+ el.style.setProperty('--a', 'a-lower');
+ testing.expectEqual(2, el.style.length);
+ testing.expectEqual('a-upper', el.style.getPropertyValue('--A'));
+ testing.expectEqual('a-lower', el.style.getPropertyValue('--a'));
+ }
+ </script>
+
+ <script id=custom_property_within_block>
+ {
+ const style = getComputedStyle($('#within-block'));
+ testing.expectEqual('second', style.getPropertyValue('--normal-last'));
+ testing.expectEqual('kept', style.getPropertyValue('--important-first'));
+ }
+ </script>
+
+ <script id=custom_property_dynamic_pseudo_skipped>
+ {
+ testing.expectEqual('', getComputedStyle($('#dynamic')).getPropertyValue('--hover-only'));
+ }
+ </script>
+
+ <script id=custom_property_no_var_substitution>
+ {
+ const style = getComputedStyle($('#alias'));
+ testing.expectEqual('4px', style.getPropertyValue('--base'));
+ testing.expectEqual('var(--base)', style.getPropertyValue('--derived'));
+ }
+ </script>
+
+ <script id=custom_property_nearest_ancestor_wins>
+ {
+ // #outer.outer.outer is far more specific than .inner, but .inner is nearer,
+ // and inheritance outranks the cascade across elements.
+ testing.expectEqual('near', getComputedStyle($('#nearest')).getPropertyValue('--nearest'));
+ testing.expectEqual('far', getComputedStyle($('#outer')).getPropertyValue('--nearest'));
+ }
+ </script>
+
+ <script id=custom_property_inline_on_ancestor>
+ {
+ const parent = document.createElement('div');
+ parent.style.setProperty('--from-ancestor-inline', '4px');
+ const child = document.createElement('div');
+ parent.appendChild(child);
+ document.body.appendChild(parent);
+
+ testing.expectEqual('4px', getComputedStyle(child).getPropertyValue('--from-ancestor-inline'));
+ // Still inherits document-level tokens through the new subtree.
+ testing.expectEqual('light', getComputedStyle(child).getPropertyValue('--theme'));
+ }
+ </script>
+
+ <script id=custom_property_cssom_rules>
+ {
+ // The CSSOM path (addRule) has to agree with the raw-text path (addRawRule).
+ const sheet = $('#dyn').sheet;
+ sheet.insertRule('#plain { --Om: om-upper; --om: om-lower }', 0);
+
+ const plain = $('#plain');
+ testing.expectEqual('om-upper', getComputedStyle(plain).getPropertyValue('--Om'));
+ testing.expectEqual('om-lower', getComputedStyle(plain).getPropertyValue('--om'));
+
+ // Mutating the rule's declaration must not leave us serving a freed value.
+ sheet.cssRules[0].style.setProperty('--Om', 'x');
+ sheet.insertRule('#nothing-matches { color: red }', 0);
+ testing.expectEqual('x', getComputedStyle(plain).getPropertyValue('--Om'));
+
+ sheet.deleteRule(0);
+ sheet.deleteRule(0);
+ testing.expectEqual('', getComputedStyle(plain).getPropertyValue('--Om'));
+ }
+ </script>
+
++<script id=custom_property_insert_rule_append>
++{
++ // An append to the last sheet skips the rebuild, but still has to reach a
++ // property that was already looked up and parsed.
++ const plain = $('#plain');
++ testing.expectEqual('#336699', getComputedStyle(plain).getPropertyValue('--brand'));
++
++ const sheet = $('#dyn').sheet;
++ sheet.insertRule(':root { --brand: red }', sheet.cssRules.length);
++ testing.expectEqual('red', getComputedStyle(plain).getPropertyValue('--brand'));
++ sheet.insertRule(':root { --fresh: new }', sheet.cssRules.length);
++ testing.expectEqual('new', getComputedStyle(plain).getPropertyValue('--fresh'));
++
++ sheet.deleteRule(0);
++ sheet.deleteRule(0);
++ testing.expectEqual('#336699', getComputedStyle(plain).getPropertyValue('--brand'));
++ testing.expectEqual('', getComputedStyle(plain).getPropertyValue('--fresh'));
++}
++</script>
++
+ <script id=custom_property_not_on_inline_declaration>
+ {
+ // A non-computed declaration only ever reports its own inline properties;
+ // it must not start resolving stylesheet rules.
+ testing.expectEqual('', $('#card').style.getPropertyValue('--brand'));
+ testing.expectEqual('8px', $('#card').style.getPropertyValue('--inline'));
+ }
+ </script>
+
+ <script id=custom_property_on_rule_declaration>
+ {
+ // A CSSStyleRule's declaration is not a computed style: it reports exactly
+ // the custom properties the rule declares, and nothing inherited.
+ const rule = document.styleSheets[0].cssRules[0];
+ testing.expectEqual(':root', rule.selectorText);
+ testing.expectEqual('#336699', rule.style.getPropertyValue('--brand'));
+ testing.expectEqual('light', rule.style.getPropertyValue('--theme'));
+ testing.expectEqual(2, rule.style.length);
+ testing.expectEqual('--brand', rule.style.item(0));
+ testing.expectEqual('--brand: #336699; --theme: light;', rule.style.cssText);
+ testing.expectEqual('', rule.style.getPropertyValue('--pad'));
+ }
+ </script>
diff --cc src/browser/tests/element/check_visibility.html
index 35a49aceb,b9c8b2dd1..c8070c9ea
--- a/src/browser/tests/element/check_visibility.html
+++ b/src/browser/tests/element/check_visibility.html
@@@ -663,65 -663,77 +663,140 @@@
}
</script>
+<style id="style-insert-rule-layers">
+ @layer base {
+ .layered-hide { display: none; }
+ }
+</style>
+<script id="insert_rule_fast_path_matches_rebuild">
+ {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const first = document.createElement("style");
+ document.head.appendChild(first);
+ const last = document.createElement("style");
+ document.head.appendChild(last);
+
+ // Appends to the last sheet
+ el.className = "ins-a";
+ last.sheet.insertRule(".ins-a { display: none }", last.sheet.cssRules.length);
+ testing.expectEqual(false, el.checkVisibility());
+ last.sheet.insertRule(".ins-a { display: block }", last.sheet.cssRules.length);
+ testing.expectEqual(true, el.checkVisibility());
+ last.sheet.insertRule("div.ins-a { display: none }", last.sheet.cssRules.length);
+ testing.expectEqual(false, el.checkVisibility());
+
+ // An append to an earlier sheet and an insert at index 0 rebuild, and
+ // still lose to the later rule at equal specificity
+ first.sheet.insertRule("div.ins-a { display: block }", first.sheet.cssRules.length);
+ testing.expectEqual(false, el.checkVisibility());
+ last.sheet.insertRule("div.ins-a { display: inline }", 0);
+ testing.expectEqual(false, el.checkVisibility());
+
+ // An unlayered append outranks a layered rule from an earlier sheet
+ el.className = "layered-hide";
+ testing.expectEqual(false, el.checkVisibility());
+ last.sheet.insertRule(".layered-hide { display: block }", last.sheet.cssRules.length);
+ testing.expectEqual(true, el.checkVisibility());
+
+ // Deleting rebuilds
+ last.sheet.deleteRule(last.sheet.cssRules.length - 1);
+ testing.expectEqual(false, el.checkVisibility());
+
+ first.remove();
+ last.remove();
+ el.remove();
+ }
+</script>
+
+<style id="style-important-text">
+ .imp-text { display: none !important; display: block; }
+</style>
+<script id="important_survives_cssrules_materialization">
+ {
+ const el = document.createElement("div");
+ el.className = "imp-text";
+ document.body.appendChild(el);
+ testing.expectEqual(false, el.checkVisibility());
+ // Reading cssRules re-parses the text into rule objects; same cascade.
+ const sheet = document.getElementById("style-important-text").sheet;
+ testing.expectEqual(1, sheet.cssRules.length);
+ testing.expectEqual(false, el.checkVisibility());
+ el.remove();
+ }
+</script>
++
+ <script id="memo_focus">
+ {
+ const style = document.createElement("style");
+ style.textContent = "#memo_focus_input:focus + span { display: none; }";
+ document.head.appendChild(style);
+
+ const wrap = document.createElement("div");
+ wrap.innerHTML = '<input id="memo_focus_input"><span>s</span>';
+ document.body.appendChild(wrap);
+ const input = wrap.querySelector("input");
+ const span = wrap.querySelector("span");
+
+ testing.expectEqual(true, span.checkVisibility());
+ input.focus();
+ testing.expectEqual(false, span.checkVisibility());
+ input.blur();
+ testing.expectEqual(true, span.checkVisibility());
+
+ wrap.remove();
+ style.remove();
+ }
+ </script>
+
+ <script id="memo_checked_rollback">
+ {
+ const style = document.createElement("style");
+ style.textContent = "#memo_checked_input:checked + span { display: none; }";
+ document.head.appendChild(style);
+
+ const wrap = document.createElement("div");
+ wrap.innerHTML = '<input type="checkbox" id="memo_checked_input"><span>s</span>';
+ document.body.appendChild(wrap);
+ const input = wrap.querySelector("input");
+ const span = wrap.querySelector("span");
+
+ let during = null;
+ input.addEventListener("click", (e) => {
+ during = span.checkVisibility();
+ e.preventDefault();
+ });
+
+ testing.expectEqual(true, span.checkVisibility());
+ input.click();
+ // the toggle is visible to listeners, then rolled back by preventDefault
+ testing.expectEqual(false, during);
+ testing.expectEqual(false, input.checked);
+ testing.expectEqual(true, span.checkVisibility());
+
+ wrap.remove();
+ style.remove();
+ }
+ </script>
+
+ <script id="memo_target">
+ {
+ const style = document.createElement("style");
+ style.textContent = "#memo_target_anchor:target + span { display: none; }";
+ document.head.appendChild(style);
+
+ const wrap = document.createElement("div");
+ wrap.innerHTML = '<div id="memo_target_anchor"></div><span>s</span>';
+ document.body.appendChild(wrap);
+ const span = wrap.querySelector("span");
+
+ testing.expectEqual(true, span.checkVisibility());
+ location.hash = "#memo_target_anchor";
+ testing.expectEqual(false, span.checkVisibility());
+ location.hash = "#memo_target_other";
+ testing.expectEqual(true, span.checkVisibility());
+
+ wrap.remove();
+ style.remove();
+ }
+ </script>