Lightpanda: the headless browser designed for AI and automation
css: end nested rules at their own block in declaration lists
Navid EMAD9cd5a96fc20d
diff --git a/src/browser/css/Parser.zig b/src/browser/css/Parser.zigindex 5e7f5c12e..5533b765b 100644--- a/src/browser/css/Parser.zig+++ b/src/browser/css/Parser.zig@@ -139,30 +139,46 @@ const DeclarationsIterator = struct {};}+ /// The block's declarations, skipping the rules nested in it.pub fn next(self: *DeclarationsIterator) ?Declaration {+ while (self.nextItem()) |item| {+ switch (item) {+ .declaration => |declaration| return declaration,+ .rule, .at_rule => {},+ }+ }+ return null;+ }++ /// The block's contents (css-syntax-3 "consume a block's contents"): its+ /// declarations, and the style rules and at-rules nested in it (CSS+ /// Nesting). A nested rule ends at its own `}`, so the declarations after+ /// it still parse.+ pub fn nextItem(self: *DeclarationsIterator) ?BlockItem {while (true) {self.skipTriviaAndSemicolons();const peeked = self.stream.peek() orelse return null;switch (peeked.token) {- .at_keyword => {- _ = self.stream.next();- self.skipAtRule();- },+ .at_keyword => return .{ .at_rule = consumeAtRule(&self.stream, self.input) },.ident => |name| {+ const mark = self.stream;_ = self.stream.next();if (self.consumeDeclaration(name)) |declaration| {- return declaration;+ return .{ .declaration = declaration };+ }+ // Not a declaration, e.g. `div:hover { … }`: consume it+ // again as a nested rule.+ self.stream = mark;+ if (consumeNestedRule(&self.stream, self.input)) |rule| {+ return .{ .rule = rule };}},- else => {- _ = self.stream.next();- self.skipInvalidDeclaration();+ else => if (consumeNestedRule(&self.stream, self.input)) |rule| {+ return .{ .rule = rule };},}}-- return null;}fn consumeDeclaration(self: *DeclarationsIterator, name: []const u8) ?Declaration {@@ -170,11 +186,12 @@ const DeclarationsIterator = struct {const colon = self.stream.next() orelse return null;if (!isColon(colon.token)) {- self.skipInvalidDeclaration();return null;}- const value = self.consumeValue() orelse return null;+ // Only a custom property's value may hold a `{}` block. Anywhere+ // else, the block makes this a nested rule.+ const value = self.consumeValue(std.mem.startsWith(u8, name, "--")) orelse return null;return .{.name = name,.value = value.value,@@ -187,7 +204,7 @@ const DeclarationsIterator = struct {important: bool,};- fn consumeValue(self: *DeclarationsIterator) ?ValueResult {+ fn consumeValue(self: *DeclarationsIterator, allow_block: bool) ?ValueResult {self.skipTrivia();var depth: usize = 0;@@ -201,6 +218,9 @@ const DeclarationsIterator = struct {_ = self.stream.next();break;}+ if (!allow_block and depth == 0 and peeked.token == .curly_bracket_block) {+ return null;+ }const span = self.stream.next() orelse break;if (isWhitespaceOrComment(span.token)) {@@ -249,45 +269,6 @@ const DeclarationsIterator = struct {}}}-- fn skipAtRule(self: *DeclarationsIterator) void {- var depth: usize = 0;- var saw_block = false;-- while (true) {- const peeked = self.stream.peek() orelse return;- if (!saw_block and isSemicolon(peeked.token) and depth == 0) {- _ = self.stream.next();- return;- }-- const span = self.stream.next() orelse return;- if (isWhitespaceOrComment(span.token)) continue;-- if (isBlockStart(span.token)) {- depth += 1;- saw_block = true;- } else if (isBlockEnd(span.token)) {- if (depth > 0) depth -= 1;- if (saw_block and depth == 0) return;- }- }- }-- fn skipInvalidDeclaration(self: *DeclarationsIterator) void {- var depth: usize = 0;-- while (self.stream.peek()) |peeked| {- if (isSemicolon(peeked.token) and depth == 0) {- _ = self.stream.next();- return;- }-- const span = self.stream.next() orelse return;- if (isWhitespaceOrComment(span.token)) continue;- updateDepth(span.token, &depth);- }- }};fn isWhitespaceOrComment(token: Tokenizer.Token) bool {@@ -386,6 +367,16 @@ const Rule = union(enum) {at_rule: AtRule,};+/// 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.+pub const BlockItem = union(enum) {+ declaration: Declaration,+ rule: StyleRule,+ at_rule: AtRule,+};+pub fn parseStylesheet(input: []const u8) RulesIterator {return RulesIterator.init(input);}@@ -415,37 +406,18 @@ pub const RulesIterator = struct {}const open_brace = self.stream.next() orelse return null;- const block_start = open_brace.end;- var block_end = block_start;-- var depth: usize = 1;- while (true) {- const span = self.stream.next() orelse {- block_end = self.input.len;- break;- };- if (span.token == .curly_bracket_block) {- depth += 1;- } else if (span.token == .close_curly_bracket) {- depth -= 1;- if (depth == 0) {- block_end = span.start;- break;- }- }- }var selector = self.input[selector_start.?..selector_end.?];selector = std.mem.trim(u8, selector, &std.ascii.whitespace);return .{ .style = .{.selector = selector,- .block = self.input[block_start..block_end],+ .block = consumeBlockBody(&self.stream, self.input, open_brace.end),} };}if (peeked.token == .at_keyword) {- return .{ .at_rule = self.consumeAtRule() };+ return .{ .at_rule = consumeAtRule(&self.stream, self.input) };}if (selector_start == null and (isWhitespaceOrComment(peeked.token) or isSemicolon(peeked.token))) {@@ -476,51 +448,97 @@ pub const RulesIterator = struct {}}}+};- /// Consume a full at-rule (statement or block form) and return its- /// keyword (without `@`) and full source span. Mirrors `skipAtRule`'s- /// termination logic but records spans instead of discarding.- fn consumeAtRule(self: *RulesIterator) AtRule {- const at_span = self.stream.next() orelse unreachable; // caller peeked an at_keyword- const start = at_span.start;- const keyword = switch (at_span.token) {- .at_keyword => |name| name,- else => "",- };- var end = at_span.end;- var depth: usize = 0;- var saw_block = false;+/// Consume a full at-rule (statement or block form) and return its keyword+/// (without `@`) and full source span. The caller peeked the `at_keyword`.+fn consumeAtRule(stream: *TokenStream, input: []const u8) AtRule {+ const at_span = stream.next() orelse unreachable; // caller peeked an at_keyword+ const start = at_span.start;+ const keyword = switch (at_span.token) {+ .at_keyword => |name| name,+ else => "",+ };+ var end = at_span.end;+ var depth: usize = 0;+ var saw_block = false;++ while (true) {+ const peeked = stream.peek() orelse break;+ if (!saw_block and isSemicolon(peeked.token) and depth == 0) {+ const semi = stream.next() orelse break;+ end = semi.end;+ break;+ }- while (true) {- const peeked = self.stream.peek() orelse break;- if (!saw_block and isSemicolon(peeked.token) and depth == 0) {- const semi = self.stream.next() orelse break;- end = semi.end;- break;- }+ const span = stream.next() orelse break;+ if (isWhitespaceOrComment(span.token)) {+ end = span.end;+ continue;+ }- const span = self.stream.next() orelse break;- if (isWhitespaceOrComment(span.token)) {- end = span.end;- continue;+ end = span.end;+ if (span.token == .curly_bracket_block) {+ depth += 1;+ saw_block = true;+ } else if (span.token == .close_curly_bracket) {+ if (depth > 0) depth -= 1;+ if (saw_block and depth == 0) break;+ }+ }++ return .{+ .keyword = keyword,+ .text = input[start..end],+ };+}++/// Consume the rest of a `{}` block whose `{` was just consumed (it ended at+/// `block_start`), through its matching `}`, and return the body between the+/// braces. An unclosed block runs to the end of the input.+fn consumeBlockBody(stream: *TokenStream, input: []const u8, block_start: usize) []const u8 {+ var depth: usize = 1;+ while (stream.next()) |span| {+ if (span.token == .curly_bracket_block) {+ depth += 1;+ } else if (span.token == .close_curly_bracket) {+ depth -= 1;+ if (depth == 0) {+ return input[block_start..span.start];}+ }+ }+ return input[block_start..];+}- end = span.end;+/// Consume a style rule nested in a block: a selector then a `{}` block.+/// Returns null, having consumed it, for anything that reaches a top-level+/// `;` before a block, or a block with no selector.+fn consumeNestedRule(stream: *TokenStream, input: []const u8) ?StyleRule {+ var start: ?usize = null;+ var end: usize = 0;+ var depth: usize = 0;++ while (stream.next()) |span| {+ if (depth == 0) {if (span.token == .curly_bracket_block) {- depth += 1;- saw_block = true;- } else if (span.token == .close_curly_bracket) {- if (depth > 0) depth -= 1;- if (saw_block and depth == 0) break;+ const body = consumeBlockBody(stream, input, span.end);+ const selector_start = start orelse return null;+ return .{ .selector = input[selector_start..end], .block = body };+ }+ if (isSemicolon(span.token)) {+ return null;}}-- return .{- .keyword = keyword,- .text = self.input[start..end],- };+ if (isWhitespaceOrComment(span.token)) {+ continue;+ }+ if (start == null) start = span.start;+ end = span.end;+ updateDepth(span.token, &depth);}-};+ return null;+}const testing = std.testing;@@ -598,3 +616,53 @@ test "RulesIterator: top-level semicolons" {try testing.expectEqualStrings("p", rule.style.selector);try testing.expectEqual(@as(?Rule, null), it.next());}++test "DeclarationsIterator: nested rules end at their own block" {+ var it = parseDeclarationsList(+ \\ color: red;+ \\ &.active { color: blue; }+ \\ .child { display: none }+ \\ div:hover { color: green; }+ \\ margin: 0;+ \\ @media (min-width: 1px) { padding: 0 }+ \\ --custom: { a: b };+ );++ var item = it.nextItem() orelse return error.MissingItem;+ try testing.expectEqualStrings("color", item.declaration.name);++ item = it.nextItem() orelse return error.MissingItem;+ try testing.expectEqualStrings("&.active", item.rule.selector);+ try testing.expectEqualStrings(" color: blue; ", item.rule.block);++ item = it.nextItem() orelse return error.MissingItem;+ try testing.expectEqualStrings(".child", item.rule.selector);++ item = it.nextItem() orelse return error.MissingItem;+ try testing.expectEqualStrings("div:hover", item.rule.selector);+ try testing.expectEqualStrings(" color: green; ", item.rule.block);++ item = it.nextItem() orelse return error.MissingItem;+ try testing.expectEqualStrings("margin", item.declaration.name);+ try testing.expectEqualStrings("0", item.declaration.value);++ item = it.nextItem() orelse return error.MissingItem;+ try testing.expectEqualStrings("media", item.at_rule.keyword);+ try testing.expectEqualStrings("@media (min-width: 1px) { padding: 0 }", item.at_rule.text);++ item = it.nextItem() orelse return error.MissingItem;+ try testing.expectEqualStrings("--custom", item.declaration.name);+ try testing.expectEqualStrings("{ a: b }", item.declaration.value);++ try testing.expectEqual(null, it.nextItem());+}++test "DeclarationsIterator: next skips nested rules" {+ var it = parseDeclarationsList("&.a { color: blue; } color: red; .b { x: y } invalid; margin: 0");+ var declaration = it.next() orelse return error.MissingDeclaration;+ try testing.expectEqualStrings("color", declaration.name);+ try testing.expectEqualStrings("red", declaration.value);+ declaration = it.next() orelse return error.MissingDeclaration;+ try testing.expectEqualStrings("margin", declaration.name);+ try testing.expectEqual(null, it.next());+}diff --git a/src/browser/tests/css/stylesheet.html b/src/browser/tests/css/stylesheet.htmlindex a29bd23da..4d4543744 100644--- a/src/browser/tests/css/stylesheet.html+++ b/src/browser/tests/css/stylesheet.html@@ -242,6 +242,20 @@}</script>+<script id="CSSStyleDeclaration_setCssText_after_nested_rule">+{+ const div = document.createElement('div');+ const style = div.style;++ // A nested rule (CSS Nesting) ends at its own `}`: the declarations+ // after it still apply instead of being skipped along with it.+ style.cssText = 'color: red; &.x { color: blue; } display: none; div:hover { color: green } opacity: 0';+ testing.expectEqual('red', style.color);+ testing.expectEqual('none', style.display);+ testing.expectEqual('0', style.opacity);+}+</script>+<script id="CSSStyleDeclaration_style_syncs_to_attribute">{// JS style modifications must be reflected in getAttribute.