Skip to content

Lightpanda: the headless browser designed for AI and automation

css: support native CSS nesting

Navid EMAD0a7f01db07c4
diff --git a/src/browser/StyleManager.zig b/src/browser/StyleManager.zig
index 54b7769ce..5edca978e 100644
--- a/src/browser/StyleManager.zig
+++ b/src/browser/StyleManager.zig
@@ -114,18 +114,21 @@ fn assertOwns(self: *const StyleManager, el_: ?*const Element) void {
/// at-rule nesting; without a cap a hostile inline stylesheet could blow the
/// Zig stack via the mutually-recursive `applyMediaAtRule` / `applyLayerAtRule`
/// `applyInnerRules` frames. 32 is well past anything seen in the wild.
-const MAX_AT_RULE_NESTING: u8 = 32;
+pub const MAX_AT_RULE_NESTING: u8 = 32;
fn parseSheet(self: *StyleManager, build_arena: Allocator, sheet: *CSSStyleSheet) !void {
if (sheet._css_rules) |css_rules| {
for (css_rules._rules.items) |rule| {
switch (rule._type) {
- .style => |sr| _ = try self.addRule(sr),
+ .style => |sr| {
+ _ = try self.addRule(sr);
+ try self.addNestedCssomRules(build_arena, sr, sr._selector_text, 0);
+ },
// Re-parse the stored source so an `@media` rule inserted via
// `insertRule` / `replaceSync` participates in the cascade
// when its query matches the viewport.
- .media => try self.applyMediaAtRule(build_arena, rule._text, 0, NO_LAYER),
- .layer => try self.applyLayerAtRule(build_arena, rule._text, 0, NO_LAYER),
+ .media => try self.applyMediaAtRule(build_arena, rule._text, 0, NO_LAYER, null),
+ .layer => try self.applyLayerAtRule(build_arena, rule._text, 0, NO_LAYER, null),
else => {},
}
}
@@ -138,7 +141,7 @@ fn parseSheet(self: *StyleManager, build_arena: Allocator, sheet: *CSSStyleSheet
var it = CssParser.parseStylesheet(text);
while (it.next()) |parsed_rule| {
switch (parsed_rule) {
- .style => |s| try self.addRawRule(build_arena, s.selector, s.block, NO_LAYER),
+ .style => |s| try self.addRawRule(build_arena, s.selector, s.block, 0, NO_LAYER),
.at_rule => |a| {
// Only `@media` and `@layer` participate in the cascade
// here. Other at-rules (`@keyframes`, `@supports`,
@@ -146,9 +149,9 @@ fn parseSheet(self: *StyleManager, build_arena: Allocator, sheet: *CSSStyleSheet
// relevant to the visibility filter and stay skipped as
// before.
if (std.ascii.eqlIgnoreCase(a.keyword, "media")) {
- try self.applyMediaAtRule(build_arena, a.text, 0, NO_LAYER);
+ try self.applyMediaAtRule(build_arena, a.text, 0, NO_LAYER, null);
} else if (std.ascii.eqlIgnoreCase(a.keyword, "layer")) {
- try self.applyLayerAtRule(build_arena, a.text, 0, NO_LAYER);
+ try self.applyLayerAtRule(build_arena, a.text, 0, NO_LAYER, null);
}
},
}
@@ -161,7 +164,10 @@ fn parseSheet(self: *StyleManager, build_arena: Allocator, sheet: *CSSStyleSheet
/// lived at the top level. Non-matching queries silently drop the inner
/// rules. Inline-only by design: external `<link rel="stylesheet">` is out
/// of scope for the headless engine.
-fn applyMediaAtRule(self: *StyleManager, build_arena: Allocator, text: []const u8, depth: u8, layer: u16) Allocator.Error!void {
+///
+/// `nest` is the selector of the style rule the at-rule is nested in (CSS
+/// Nesting), whose block the inner block then is; null at the top level.
+fn applyMediaAtRule(self: *StyleManager, build_arena: Allocator, text: []const u8, depth: u8, layer: u16, nest: ?[]const u8) Allocator.Error!void {
if (depth >= MAX_AT_RULE_NESTING) {
return;
}
@@ -173,7 +179,7 @@ fn applyMediaAtRule(self: *StyleManager, build_arena: Allocator, text: []const u
return;
}
- try self.applyInnerRules(build_arena, block.body, depth + 1, layer);
+ try self.applyAtRuleBody(build_arena, block.body, depth + 1, layer, nest);
}
/// Apply an `@layer` rule (css-cascade-5). Layers have two forms:
@@ -184,8 +190,8 @@ fn applyMediaAtRule(self: *StyleManager, build_arena: Allocator, text: []const u
/// The layer parameter is the enclosing layer, or NO_LAYER at the top level.
/// Priority is not assigned here, we need all the layers parsed to do that
/// (since a layer statement can alter the ordering). So we'll do one final pass
-// in finalizerLayerRanks
-fn applyLayerAtRule(self: *StyleManager, build_arena: Allocator, text: []const u8, depth: u8, layer: u16) Allocator.Error!void {
+// in finalizerLayerRanks. `nest` is as for applyMediaAtRule.
+fn applyLayerAtRule(self: *StyleManager, build_arena: Allocator, text: []const u8, depth: u8, layer: u16, nest: ?[]const u8) Allocator.Error!void {
if (depth >= MAX_AT_RULE_NESTING) {
return;
}
@@ -227,7 +233,16 @@ fn applyLayerAtRule(self: *StyleManager, build_arena: Allocator, text: []const u
else
try self.registerLayerPath(build_arena, layer, prelude);
- try self.applyInnerRules(build_arena, block.body, depth + 1, id);
+ try self.applyAtRuleBody(build_arena, block.body, depth + 1, id, nest);
+}
+
+/// The block of an at-rule nested in a style rule is a block of that rule:
+/// `.a { @media (…) { color: red } }` is `@media (…) { .a { color: red } }`.
+fn applyAtRuleBody(self: *StyleManager, build_arena: Allocator, body: []const u8, depth: u8, layer: u16, nest: ?[]const u8) Allocator.Error!void {
+ if (nest) |selector| {
+ return self.addRawRule(build_arena, selector, body, depth, layer);
+ }
+ return self.applyInnerRules(build_arena, body, depth, layer);
}
/// Parse a conditional at-rule's inner block, adding style rules to the
@@ -238,12 +253,12 @@ fn applyInnerRules(self: *StyleManager, build_arena: Allocator, inner: []const u
var it = CssParser.parseStylesheet(inner);
while (it.next()) |nested_rule| {
switch (nested_rule) {
- .style => |s| try self.addRawRule(build_arena, s.selector, s.block, layer),
+ .style => |s| try self.addRawRule(build_arena, s.selector, s.block, depth, layer),
.at_rule => |nested| {
if (std.ascii.eqlIgnoreCase(nested.keyword, "media")) {
- try self.applyMediaAtRule(build_arena, nested.text, depth, layer);
+ try self.applyMediaAtRule(build_arena, nested.text, depth, layer, null);
} else if (std.ascii.eqlIgnoreCase(nested.keyword, "layer")) {
- try self.applyLayerAtRule(build_arena, nested.text, depth, layer);
+ try self.applyLayerAtRule(build_arena, nested.text, depth, layer, null);
}
},
}
@@ -471,13 +486,40 @@ fn layerRank(self: *const StyleManager, priority: u64) u64 {
return rank;
}
-fn addRawRule(self: *StyleManager, build_arena: Allocator, selector_text: []const u8, block_text: []const u8, layer: u16) !void {
+/// `depth` bounds the recursion through nested rules and at-rules, as
+/// MAX_AT_RULE_NESTING does for at-rules alone.
+fn addRawRule(self: *StyleManager, build_arena: Allocator, selector_text: []const u8, block_text: []const u8, depth: u8, layer: u16) Allocator.Error!void {
if (selector_text.len == 0) {
return;
}
var customs: CustomSink = .{ .allocator = build_arena };
const folded = try foldDeclarations(Declarations, CssParser.parseStyleBlock(block_text), &customs);
_ = try self.addSelectorRules(selector_text, folded.props(.normal), folded.props(.important), customs.map.values(), layer);
+
+ // CSS Nesting: the rules nested in the block follow their parent in
+ // cascade order. Most blocks have none, and every nested rule needs a `{`.
+ if (depth >= MAX_AT_RULE_NESTING or std.mem.findScalar(u8, block_text, '{') == null) {
+ return;
+ }
+ var it = CssParser.parseStyleBlock(block_text);
+ while (it.nextItem()) |item| {
+ switch (item) {
+ .declaration => {},
+ .rule => |nested| {
+ // The arena, not build_arena: a custom property's rule keeps
+ // its selector text past the rebuild.
+ const selector = try CssParser.resolveNestedSelector(self.arena.allocator(), selector_text, nested.selector);
+ try self.addRawRule(build_arena, selector, nested.block, depth + 1, layer);
+ },
+ .at_rule => |nested| {
+ if (std.ascii.eqlIgnoreCase(nested.keyword, "media")) {
+ try self.applyMediaAtRule(build_arena, nested.text, depth + 1, layer, selector_text);
+ } else if (std.ascii.eqlIgnoreCase(nested.keyword, "layer")) {
+ try self.applyLayerAtRule(build_arena, nested.text, depth + 1, layer, selector_text);
+ }
+ },
+ }
+ }
}
// Tracked rules get one group Rule per selector (not per selector list)
@@ -1236,7 +1278,12 @@ fn matchesUaDisplayNoneRule(el: *Element, frame: *Frame) bool {
/// 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;
+ return self.addRuleAs(style_rule, style_rule._selector_text);
+}
+
+/// Add a style rule's declarations under `selector_text`: its own selector,
+/// or for a nested rule, that selector resolved against its parent's.
+fn addRuleAs(self: *StyleManager, style_rule: *CSSStyleRule, selector_text: []const u8) !bool {
if (selector_text.len == 0) {
return false;
}
@@ -1252,6 +1299,29 @@ fn addRule(self: *StyleManager, style_rule: *CSSStyleRule) !bool {
return self.addSelectorRules(selector_text, folded.props(.normal), folded.props(.important), customs, NO_LAYER);
}
+/// The CSSOM counterpart to the nested rules addRawRule adds: a style rule
+/// keeps the rules nested in its block in `_rules`. `parent_selector` is the
+/// parent's selector, already resolved when the parent is itself nested.
+fn addNestedCssomRules(self: *StyleManager, build_arena: Allocator, parent: *CSSStyleRule, parent_selector: []const u8, depth: u8) Allocator.Error!void {
+ const nested_rules = parent._rules orelse return;
+ if (depth >= MAX_AT_RULE_NESTING) {
+ return;
+ }
+ for (nested_rules._rules.items) |rule| {
+ switch (rule._type) {
+ .style => |sr| {
+ // The arena, as in addRawRule.
+ const selector = try CssParser.resolveNestedSelector(self.arena.allocator(), parent_selector, sr._selector_text);
+ _ = try self.addRuleAs(sr, selector);
+ try self.addNestedCssomRules(build_arena, sr, selector, depth + 1);
+ },
+ .media => try self.applyMediaAtRule(build_arena, rule._text, depth + 1, NO_LAYER, parent_selector),
+ .layer => try self.applyLayerAtRule(build_arena, rule._text, depth + 1, NO_LAYER, parent_selector),
+ else => {},
+ }
+ }
+}
+
/// 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.
@@ -1264,7 +1334,8 @@ pub fn ruleInserted(self: *StyleManager, sheet: *CSSStyleSheet, rule: *CSSRule)
.style => |s| s,
else => return self.sheetModified(),
};
- if (!self.appendable(sheet, rule)) {
+ // A rule with nested rules takes the rebuild path, which adds them.
+ if (style_rule._rules != null or !self.appendable(sheet, rule)) {
return self.sheetModified();
}
const added = self.addRule(style_rule) catch return self.sheetModified();
diff --git a/src/browser/css/Parser.zig b/src/browser/css/Parser.zig
index 1deabbd63..fc024bf41 100644
--- a/src/browser/css/Parser.zig
+++ b/src/browser/css/Parser.zig
@@ -383,8 +383,8 @@ const Rule = union(enum) {
/// An item of a style rule's block. With CSS Nesting, a block holds style
/// rules and at-rules next to its declarations. A nested style rule's
-/// selector is its raw source (`&.active`, `> li`), not yet resolved against
-/// the enclosing rule's selector.
+/// selector is its raw source (`&.active`, `> li`); `resolveNestedSelector`
+/// resolves it against the enclosing rule's selector.
pub const BlockItem = union(enum) {
declaration: Declaration,
rule: StyleRule,
@@ -566,6 +566,73 @@ fn consumeNestedRule(stream: *TokenStream, input: []const u8) ?StyleRule {
return null;
}
+/// Resolve the selector list of a style rule nested in `parent` (CSS Nesting
+/// §3): each `&` becomes `:is(<parent>)`, and a selector without one is
+/// relative to the parent, as if it started with `& `. Using `:is()` keeps
+/// the spec's specificity (the most specific parent selector) and lets a
+/// parent selector list stand in for a single `&`. Selectors are split on
+/// the commas outside parentheses and brackets; tokens are copied verbatim.
+pub fn resolveNestedSelector(allocator: std.mem.Allocator, parent: []const u8, nested: []const u8) ![]const u8 {
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(allocator);
+ var stream = TokenStream.init(nested);
+
+ // Start of the current complex selector in `out`, and whether it holds
+ // an `&` yet. Each selector is written as it streams by, and the parent is
+ // inserted at `selector_start` when it turns out to have no `&`.
+ var selector_start: usize = 0;
+ var has_nesting = false;
+ var pending_space = false;
+ var depth: usize = 0;
+
+ while (true) {
+ const span = stream.next();
+ const at_comma = if (span) |sp| depth == 0 and sp.token == .comma else true;
+ if (at_comma) {
+ if (out.items.len > selector_start and !has_nesting) {
+ // Inserted back to front, to read `:is(<parent>) <selector>`.
+ try out.insertSlice(allocator, selector_start, ") ");
+ try out.insertSlice(allocator, selector_start, parent);
+ try out.insertSlice(allocator, selector_start, ":is(");
+ }
+ if (span == null) {
+ break;
+ }
+ if (out.items.len > selector_start) {
+ try out.appendSlice(allocator, ", ");
+ }
+ selector_start = out.items.len;
+ has_nesting = false;
+ pending_space = false;
+ continue;
+ }
+
+ const sp = span.?;
+ if (isWhitespaceOrComment(sp.token)) {
+ pending_space = out.items.len > selector_start;
+ continue;
+ }
+ if (pending_space) {
+ try out.append(allocator, ' ');
+ pending_space = false;
+ }
+ updateDepth(sp.token, &depth);
+ switch (sp.token) {
+ .delim => |c| if (c == '&') {
+ try out.appendSlice(allocator, ":is(");
+ try out.appendSlice(allocator, parent);
+ try out.append(allocator, ')');
+ has_nesting = true;
+ continue;
+ },
+ else => {},
+ }
+ try out.appendSlice(allocator, nested[sp.start..sp.end]);
+ }
+
+ return out.toOwnedSlice(allocator);
+}
+
const testing = std.testing;
test "RulesIterator: single rule" {
@@ -710,3 +777,25 @@ test "DeclarationsIterator: a declarations list has no nested rules" {
try testing.expectEqual(null, it.nextItem());
}
+
+test "resolveNestedSelector" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const allocator = arena.allocator();
+
+ const cases = [_]struct { parent: []const u8, nested: []const u8, want: []const u8 }{
+ .{ .parent = ".a", .nested = "&.b", .want = ":is(.a).b" },
+ .{ .parent = ".a", .nested = ".b", .want = ":is(.a) .b" },
+ .{ .parent = ".a", .nested = "> li", .want = ":is(.a) > li" },
+ .{ .parent = ".a", .nested = "& + &", .want = ":is(.a) + :is(.a)" },
+ .{ .parent = ".a", .nested = ".x &", .want = ".x :is(.a)" },
+ .{ .parent = ".a", .nested = ":not(&) .b", .want = ":not(:is(.a)) .b" },
+ .{ .parent = ".a, .b", .nested = "&:hover", .want = ":is(.a, .b):hover" },
+ .{ .parent = ".a", .nested = "&.b, .c , :is(.d, .e)", .want = ":is(.a).b, :is(.a) .c, :is(.a) :is(.d, .e)" },
+ .{ .parent = ".a", .nested = "[data-x='&']", .want = ":is(.a) [data-x='&']" },
+ .{ .parent = ".a", .nested = " /* c */ & .b ", .want = ":is(.a) .b" },
+ };
+ for (cases) |c| {
+ try testing.expectEqualStrings(c.want, try resolveNestedSelector(allocator, c.parent, c.nested));
+ }
+}
diff --git a/src/browser/tests/css/nesting.html b/src/browser/tests/css/nesting.html
new file mode 100644
index 000000000..1d6481e2b
--- /dev/null
+++ b/src/browser/tests/css/nesting.html
@@ -0,0 +1,176 @@
+<!DOCTYPE html>
+<head>
+ <script src="../testing.js"></script>
+</head>
+
+<!--
+ CSS Nesting: style rules and conditional at-rules written inside a style
+ rule's block. A nested selector resolves against its parent's: `&` stands
+ for the parent, and a selector without `&` is relative to it (descendant
+ unless it starts with a combinator).
+
+ The first <style> is read through the text path; the rules the scripts
+ insert or replace go through the CSSOM path.
+-->
+
+<style>
+ .card { visibility: hidden; &.ready { visibility: visible; } }
+ .list { .item { display: none; } }
+ .menu { > .entry { display: none; } }
+ .tabs { .label & { display: none; } }
+ .a, .b { &:not(.keep) { display: none; } }
+ /* A declaration after a nested rule still applies. */
+ .after { &.unused { color: red; } display: none; }
+ /* `div:hover {}` looks like a `div: hover` declaration until its block. */
+ .typed { span { display: none; } }
+ .deep { .mid { .leaf { display: none; } } }
+ .media-hit { @media (min-width: 1px) { display: none; .inner { display: none; } } }
+ .media-miss { @media (max-width: 1px) { display: none; } }
+ /* Specificity is the parent's: :is(#by-id) beats the later .weak rule. */
+ #by-id { & { display: none; } }
+ .weak { display: block; }
+</style>
+
+<body>
+ <div id="card" class="card ready">card</div>
+ <div id="card-pending" class="card">pending</div>
+ <div class="list"><span id="item" class="item">item</span></div>
+ <div id="item-outside" class="item">item outside</div>
+ <div class="menu"><div id="entry" class="entry">entry</div><div><div id="entry-deep" class="entry">deep</div></div></div>
+ <div class="label"><div id="tab" class="tabs">tab</div></div>
+ <div id="tab-alone" class="tabs">tab alone</div>
+ <div id="list-a" class="a">a</div>
+ <div id="list-b" class="b">b</div>
+ <div id="list-keep" class="a keep">keep</div>
+ <div id="after" class="after">after</div>
+ <div class="typed"><span id="typed">typed</span></div>
+ <div class="deep"><div class="mid"><div id="leaf" class="leaf">leaf</div></div></div>
+ <div id="media-hit" class="media-hit"><div id="media-inner" class="inner">inner</div></div>
+ <div id="media-miss" class="media-miss">miss</div>
+ <div id="by-id" class="weak">by id</div>
+ <div id="om" class="om hide"><span id="om-inner" class="inner">om inner</span></div>
+ <div id="inserted"><i id="inserted-inner">inserted inner</i></div>
+ <style id="replaced"></style>
+ <style id="dynamic"></style>
+</body>
+
+<script id=nesting_ampersand_compound>
+{
+ testing.expectEqual('visible', getComputedStyle($('#card')).visibility);
+ testing.expectEqual('hidden', getComputedStyle($('#card-pending')).visibility);
+}
+</script>
+
+<script id=nesting_relative_descendant>
+{
+ testing.expectFalse($('#item').checkVisibility());
+ testing.expectTrue($('#item-outside').checkVisibility());
+}
+</script>
+
+<script id=nesting_leading_combinator>
+{
+ testing.expectFalse($('#entry').checkVisibility());
+ testing.expectTrue($('#entry-deep').checkVisibility());
+}
+</script>
+
+<script id=nesting_ampersand_not_first>
+{
+ testing.expectFalse($('#tab').checkVisibility());
+ testing.expectTrue($('#tab-alone').checkVisibility());
+}
+</script>
+
+<script id=nesting_parent_selector_list>
+{
+ testing.expectFalse($('#list-a').checkVisibility());
+ testing.expectFalse($('#list-b').checkVisibility());
+ testing.expectTrue($('#list-keep').checkVisibility());
+}
+</script>
+
+<script id=nesting_declaration_after_rule>
+{
+ testing.expectFalse($('#after').checkVisibility());
+}
+</script>
+
+<script id=nesting_type_selector>
+{
+ testing.expectFalse($('#typed').checkVisibility());
+}
+</script>
+
+<script id=nesting_deep>
+{
+ testing.expectFalse($('#leaf').checkVisibility());
+}
+</script>
+
+<script id=nesting_media>
+{
+ testing.expectFalse($('#media-hit').checkVisibility());
+ testing.expectFalse($('#media-inner').checkVisibility());
+ testing.expectTrue($('#media-miss').checkVisibility());
+}
+</script>
+
+<script id=nesting_specificity>
+{
+ testing.expectFalse($('#by-id').checkVisibility());
+}
+</script>
+
+<script id=nesting_cssom_surface>
+{
+ const rules = document.styleSheets[0].cssRules;
+ testing.expectEqual(12, rules.length);
+
+ const card = rules[0];
+ testing.expectEqual('.card', card.selectorText);
+ testing.expectEqual('hidden', card.style.visibility);
+ testing.expectEqual(1, card.cssRules.length);
+ testing.expectEqual('&.ready', card.cssRules[0].selectorText);
+ testing.expectEqual('visible', card.cssRules[0].style.visibility);
+
+ const media = rules[8];
+ testing.expectEqual(1, media.cssRules.length);
+ testing.expectEqual(4, media.cssRules[0].type);
+
+ testing.expectEqual(0, rules[11].cssRules.length);
+}
+</script>
+
+<script id=nesting_cascade_after_cssom_read>
+{
+ // Reading cssRules makes the cascade come from the CSSOM rules. A rebuild
+ // from them keeps the nested rules.
+ document.styleSheets[0].insertRule('.unrelated { color: red; }', 0);
+ testing.expectEqual('visible', getComputedStyle($('#card')).visibility);
+ testing.expectFalse($('#item').checkVisibility());
+ testing.expectFalse($('#leaf').checkVisibility());
+ testing.expectFalse($('#media-inner').checkVisibility());
+ testing.expectFalse($('#by-id').checkVisibility());
+}
+</script>
+
+<script id=nesting_replace_sync>
+{
+ const sheet = $('#replaced').sheet;
+ sheet.replaceSync('.om { &.hide { display: none; } .inner { visibility: hidden; } }');
+ testing.expectFalse($('#om').checkVisibility());
+ testing.expectEqual('hidden', getComputedStyle($('#om-inner')).visibility);
+ testing.expectEqual(2, sheet.cssRules[0].cssRules.length);
+}
+</script>
+
+<script id=nesting_insert_rule>
+{
+ const sheet = $('#dynamic').sheet;
+ sheet.insertRule('#inserted { & > i { display: none; } }', 0);
+ testing.expectFalse($('#inserted-inner').checkVisibility());
+ testing.expectTrue($('#inserted').checkVisibility());
+ testing.expectEqual('#inserted { & > i { display: none; } }', sheet.cssRules[0].cssText);
+}
+</script>
diff --git a/src/browser/webapi/css/CSSStyleRule.zig b/src/browser/webapi/css/CSSStyleRule.zig
index 30110f741..62d9229ee 100644
--- a/src/browser/webapi/css/CSSStyleRule.zig
+++ b/src/browser/webapi/css/CSSStyleRule.zig
@@ -2,6 +2,7 @@ const std = @import("std");
const js = @import("../../js/js.zig");
const Frame = @import("../../Frame.zig");
const CSSRule = @import("CSSRule.zig");
+const CSSRuleList = @import("CSSRuleList.zig");
const CSSStyleProperties = @import("CSSStyleProperties.zig");
const CSSStyleRule = @This();
@@ -11,6 +12,9 @@ pub const Proto = CSSRule;
_proto: *CSSRule,
_selector_text: []const u8 = "",
_style: ?*CSSStyleProperties = null,
+/// The rules nested in this rule's block (CSS Nesting), null when there are
+/// none. A nested style rule keeps its selector as written (`&.active`).
+_rules: ?*CSSRuleList = null,
pub fn init(frame: *Frame) !*CSSStyleRule {
const style_rule = try frame._factory.chained(.{
@@ -38,12 +42,34 @@ pub fn getStyle(self: *CSSStyleRule, frame: *Frame) !*CSSStyleProperties {
return style;
}
+fn getCssRules(self: *CSSStyleRule, frame: *Frame) !*CSSRuleList {
+ if (self._rules) |rules| {
+ return rules;
+ }
+ const rules = try CSSRuleList.init(frame);
+ self._rules = rules;
+ return rules;
+}
+
pub fn getCssText(self: *CSSStyleRule, frame: *Frame) ![]const u8 {
const style_props = try self.getStyle(frame);
const style = style_props.asCSSStyleDeclaration();
var buf = std.Io.Writer.Allocating.init(frame.local_arena);
try buf.writer.print("{s} {{ ", .{self._selector_text});
+ const start = buf.written().len;
try style.format(&buf.writer);
+ if (self._rules) |rules| {
+ for (rules._rules.items) |rule| {
+ if (buf.written().len > start) {
+ try buf.writer.writeByte(' ');
+ }
+ const text = switch (rule._type) {
+ .style => |nested| try nested.getCssText(frame),
+ else => rule._text,
+ };
+ try buf.writer.writeAll(text);
+ }
+ }
try buf.writer.writeAll(" }");
return buf.written();
}
@@ -59,4 +85,5 @@ pub const JsApi = struct {
pub const selectorText = bridge.accessor(CSSStyleRule.getSelectorText, CSSStyleRule.setSelectorText, .{});
pub const style = bridge.accessor(CSSStyleRule.getStyle, null, .{});
pub const cssText = bridge.accessor(CSSStyleRule.getCssText, null, .{});
+ pub const cssRules = bridge.accessor(CSSStyleRule.getCssRules, null, .{});
};
diff --git a/src/browser/webapi/css/CSSStyleSheet.zig b/src/browser/webapi/css/CSSStyleSheet.zig
index 540c02987..08f5077de 100644
--- a/src/browser/webapi/css/CSSStyleSheet.zig
+++ b/src/browser/webapi/css/CSSStyleSheet.zig
@@ -93,15 +93,7 @@ pub fn insertRule(self: *CSSStyleSheet, rule: []const u8, maybe_index: ?u32, fra
if (it.next() != null) return error.SyntaxError;
const inserted: *CSSRule = switch (parsed_rule) {
- .style => |s| blk: {
- const style_rule = try CSSStyleRule.init(frame);
- try style_rule.setSelectorText(s.selector, frame);
-
- const style_props = try style_rule.getStyle(frame);
- const style = style_props.asCSSStyleDeclaration();
- try style.replaceStyleBlock(s.block, frame);
- break :blk style_rule._proto;
- },
+ .style => |s| try initStyleRule(s.selector, s.block, 0, frame),
// Opaque placeholder for at-rules. The CSS engine doesn't apply
// these (`@keyframes`, `@media`, ...) but JS-side reads must see
// them via `cssRules` so CSS-in-JS libraries don't fall back to
@@ -128,6 +120,37 @@ pub fn insertRule(self: *CSSStyleSheet, rule: []const u8, maybe_index: ?u32, fra
return index;
}
+/// A style rule from source: its declarations, and the rules nested in its
+/// block (CSS Nesting) as child rules. `depth` caps the nesting like
+/// StyleManager's cap on the cascade side.
+fn initStyleRule(selector: []const u8, block: []const u8, depth: u8, frame: *Frame) CSSError!*CSSRule {
+ const style_rule = try CSSStyleRule.init(frame);
+ try style_rule.setSelectorText(selector, frame);
+
+ const style_props = try style_rule.getStyle(frame);
+ const style = style_props.asCSSStyleDeclaration();
+ try style.replaceStyleBlock(block, frame);
+
+ if (depth >= StyleManager.MAX_AT_RULE_NESTING or std.mem.findScalar(u8, block, '{') == null) {
+ return style_rule._proto;
+ }
+ var it = Parser.parseStyleBlock(block);
+ while (it.nextItem()) |item| {
+ const nested: *CSSRule = switch (item) {
+ .declaration => continue,
+ .rule => |r| try initStyleRule(r.selector, r.block, depth + 1, frame),
+ .at_rule => |a| try CSSRule.initAtRule(atRuleTypeFor(a.keyword), a.text, frame),
+ };
+ const rules = style_rule._rules orelse blk: {
+ const rules = try CSSRuleList.init(frame);
+ style_rule._rules = rules;
+ break :blk rules;
+ };
+ try rules.insert(rules.length(), nested, frame);
+ }
+ return style_rule._proto;
+}
+
/// Map an at-rule keyword (without `@`) to the matching `CSSRule.Type`
/// variant. Vendor prefixes are stripped before matching
/// (`-webkit-keyframes` -> `keyframes`). Unrecognized keywords fall back
@@ -188,15 +211,7 @@ fn parseInto(self: *CSSStyleSheet, text: []const u8, frame: *Frame) CSSError!voi
var index: u32 = 0;
while (it.next()) |parsed_rule| {
const inserted: *CSSRule = switch (parsed_rule) {
- .style => |s| blk: {
- const style_rule = try CSSStyleRule.init(frame);
- try style_rule.setSelectorText(s.selector, frame);
-
- const style_props = try style_rule.getStyle(frame);
- const style = style_props.asCSSStyleDeclaration();
- try style.replaceStyleBlock(s.block, frame);
- break :blk style_rule._proto;
- },
+ .style => |s| try initStyleRule(s.selector, s.block, 0, frame),
.at_rule => |a| try CSSRule.initAtRule(atRuleTypeFor(a.keyword), a.text, frame),
};
@@ -239,3 +254,7 @@ test "WebApi: layer @-rule cascade" {
test "WebApi: layer order cascade" {
try testing.htmlRunner("css/layer_order_cascade.html", .{});
}
+
+test "WebApi: CSS nesting" {
+ try testing.htmlRunner("css/nesting.html", .{});
+}