Lightpanda: the headless browser designed for AI and automation
css: parse nested rules only in a stylesheet's style blocks
Navid EMAD1c6b571e1705
diff --git a/src/browser/StyleManager.zig b/src/browser/StyleManager.zigindex d45cb1471..850ffb51b 100644--- a/src/browser/StyleManager.zig+++ b/src/browser/StyleManager.zig@@ -473,7 +473,7 @@ fn addRawRule(self: *StyleManager, build_arena: Allocator, selector_text: []consreturn;}var customs: CustomSink = .{ .allocator = build_arena };- const folded = try foldDeclarations(Declarations, block_text, &customs);+ 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);}@@ -1715,7 +1715,7 @@ fn inlineDeclared(comptime Declared: type, el: *Element, frame: *Frame) Slots(De}const attr = el.getAttributeInterned("style") orelse return .{};// Without a sink nothing allocates- return foldDeclarations(Declared, attr, null) catch unreachable;+ return foldDeclarations(Declared, CssParser.parseDeclarationsList(attr), null) catch unreachable;}/// `--*` declarations of one block, keyed by name so a block declaring the same@@ -1730,9 +1730,9 @@ const CustomSink = struct {// 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(comptime Declared: type, block: []const u8, customs: ?*CustomSink) !Slots(Declared) {+fn foldDeclarations(comptime Declared: type, declarations: CssParser.DeclarationsIterator, customs: ?*CustomSink) !Slots(Declared) {var slots: Slots(Declared) = .{};- var it = CssParser.parseDeclarationsList(block);+ var it = declarations;while (it.next()) |declaration| {if (isCustomProperty(declaration.name)) {const sink = customs orelse continue;diff --git a/src/browser/css/Parser.zig b/src/browser/css/Parser.zigindex 5533b765b..1deabbd63 100644--- a/src/browser/css/Parser.zig+++ b/src/browser/css/Parser.zig@@ -124,18 +124,31 @@ const TokenStream = struct {}};+/// The declarations of a `style` attribute or of a `cssText` assignment, on an+/// element's style or a rule's. Browsers don't parse nested rules there: a+/// `&.x { … }` is an invalid declaration, skipped through the next top-level+/// `;` along with whatever follows it.pub fn parseDeclarationsList(input: []const u8) DeclarationsIterator {- return DeclarationsIterator.init(input);+ return DeclarationsIterator.init(input, false);}-const DeclarationsIterator = struct {+/// The block of a style rule read from a stylesheet (`<style>`, `insertRule`,+/// `replace`). CSS Nesting applies: a nested rule ends at its own `}`, so the+/// declarations after it still parse.+pub fn parseStyleBlock(input: []const u8) DeclarationsIterator {+ return DeclarationsIterator.init(input, true);+}++pub const DeclarationsIterator = struct {input: []const u8,stream: TokenStream,+ nesting: bool,- pub fn init(input: []const u8) DeclarationsIterator {+ pub fn init(input: []const u8, nesting: bool) DeclarationsIterator {return .{.input = input,.stream = TokenStream.init(input),+ .nesting = nesting,};}@@ -151,32 +164,32 @@ const DeclarationsIterator = struct {}/// 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.+ /// declarations and at-rules and, from `parseStyleBlock`, the style rules+ /// nested in it (CSS Nesting).pub fn nextItem(self: *DeclarationsIterator) ?BlockItem {while (true) {self.skipTriviaAndSemicolons();const peeked = self.stream.peek() orelse return null;- switch (peeked.token) {- .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 = 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 => if (consumeNestedRule(&self.stream, self.input)) |rule| {- return .{ .rule = rule };- },+ if (peeked.token == .at_keyword) {+ return .{ .at_rule = consumeAtRule(&self.stream, self.input) };+ }++ const mark = self.stream;+ if (peeked.token == .ident) {+ _ = self.stream.next();+ if (self.consumeDeclaration(peeked.token.ident)) |declaration| {+ return .{ .declaration = declaration };+ }+ }++ // Not a declaration, e.g. `&.x { … }` or `div:hover { … }`:+ // consume it again, as a nested rule where nesting applies.+ self.stream = mark;+ if (!self.nesting) {+ skipInvalidDeclaration(&self.stream);+ } else if (consumeNestedRule(&self.stream, self.input)) |rule| {+ return .{ .rule = rule };}}}@@ -190,7 +203,8 @@ const DeclarationsIterator = struct {}// Only a custom property's value may hold a `{}` block. Anywhere- // else, the block makes this a nested rule.+ // else, the block makes this a nested rule or, without nesting, an+ // invalid declaration.const value = self.consumeValue(std.mem.startsWith(u8, name, "--")) orelse return null;return .{.name = name,@@ -511,6 +525,18 @@ fn consumeBlockBody(stream: *TokenStream, input: []const u8, block_start: usize)return input[block_start..];}+/// Consume an invalid declaration through the next top-level `;`. A `{}`+/// block in it is skipped whole, `;`s included.+fn skipInvalidDeclaration(stream: *TokenStream) void {+ var depth: usize = 0;+ while (stream.next()) |span| {+ if (depth == 0 and isSemicolon(span.token)) {+ return;+ }+ updateDepth(span.token, &depth);+ }+}+/// 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.@@ -618,7 +644,7 @@ test "RulesIterator: top-level semicolons" {}test "DeclarationsIterator: nested rules end at their own block" {- var it = parseDeclarationsList(+ var it = parseStyleBlock(\\ color: red;\\ &.active { color: blue; }\\ .child { display: none }@@ -658,7 +684,7 @@ test "DeclarationsIterator: nested rules end at their own block" {}test "DeclarationsIterator: next skips nested rules" {- var it = parseDeclarationsList("&.a { color: blue; } color: red; .b { x: y } invalid; margin: 0");+ var it = parseStyleBlock("&.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);@@ -666,3 +692,21 @@ test "DeclarationsIterator: next skips nested rules" {try testing.expectEqualStrings("margin", declaration.name);try testing.expectEqual(null, it.next());}++test "DeclarationsIterator: a declarations list has no nested rules" {+ // `style=` and cssText: a nested rule is an invalid declaration, skipped+ // through the next top-level `;`, so `display: none` goes with it.+ var it = parseDeclarationsList("color: red; &.x { color: blue; } display: none; div:hover { color: green } opacity: 0; --custom: { a: b }; margin: 0");++ 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("--custom", item.declaration.name);+ try testing.expectEqualStrings("{ a: b }", item.declaration.value);++ item = it.nextItem() orelse return error.MissingItem;+ try testing.expectEqualStrings("margin", item.declaration.name);++ try testing.expectEqual(null, it.nextItem());+}diff --git a/src/browser/tests/css/stylesheet.html b/src/browser/tests/css/stylesheet.htmlindex 4d4543744..bbff96123 100644--- a/src/browser/tests/css/stylesheet.html+++ b/src/browser/tests/css/stylesheet.html@@ -242,17 +242,53 @@}</script>-<script id="CSSStyleDeclaration_setCssText_after_nested_rule">+<script id="CSSStyleDeclaration_setCssText_nested_rule_is_invalid">{+ // cssText takes no nested rules (Chrome, Firefox): `&.x { … }` is an+ // invalid declaration, skipped through the next top-level `;` with the+ // `display: none` after it.+ const text = 'color: red; &.x { color: blue; } display: none; opacity: 0';+const div = document.createElement('div');- const style = div.style;+ div.style.cssText = text;+ testing.expectEqual('color: red; opacity: 0;', div.style.cssText);++ div.setAttribute('style', text);+ testing.expectEqual('color: red; opacity: 0;', div.style.cssText);++ // Not even on a style rule's own declarations.+ const sheet = new CSSStyleSheet();+ sheet.replaceSync('.t {}');+ const rule = sheet.cssRules[0];+ rule.style.cssText = text;+ testing.expectEqual('color: red; opacity: 0;', rule.style.cssText);+}+</script>++<script id="CSSStyleSheet_nested_rule_ends_at_its_block">+{+ // In a stylesheet, a nested rule (CSS Nesting) ends at its own `}`: the+ // declarations after it still apply.+ const style = document.createElement('style');+ style.textContent = '.nested-after { color: red; &.x { color: blue; } display: none; div:hover { color: green } opacity: 0 }';+ document.head.append(style);++ const declarations = style.sheet.cssRules[0].style;+ testing.expectEqual('red', declarations.color);+ testing.expectEqual('none', declarations.display);+ testing.expectEqual('0', declarations.opacity);++ const div = document.createElement('div');+ div.className = 'nested-after';+ document.documentElement.append(div);+ testing.expectEqual('none', getComputedStyle(div).display);++ const sheet = new CSSStyleSheet();+ sheet.insertRule('.t { &.x { color: blue; } display: none; }');+ testing.expectEqual('none', sheet.cssRules[0].style.display);- // 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);+ div.remove();+ style.remove();}</script>diff --git a/src/browser/webapi/css/CSSStyleDeclaration.zig b/src/browser/webapi/css/CSSStyleDeclaration.zigindex 8da10cd39..9d36fb1f5 100644--- a/src/browser/webapi/css/CSSStyleDeclaration.zig+++ b/src/browser/webapi/css/CSSStyleDeclaration.zig@@ -45,11 +45,11 @@ pub fn parseInlineStyle(self: *CSSStyleDeclaration, frame: *Frame) !void {}const el = self._element orelse return;const attr_value = el.getAttributeInterned("style") orelse return;- try self.applyDeclarations(attr_value, frame);+ try self.applyDeclarations(CssParser.parseDeclarationsList(attr_value), frame);}-fn applyDeclarations(self: *CSSStyleDeclaration, text: []const u8, frame: *Frame) !void {- var it = CssParser.parseDeclarationsList(text);+fn applyDeclarations(self: *CSSStyleDeclaration, declarations: CssParser.DeclarationsIterator, frame: *Frame) !void {+ var it = declarations;while (it.next()) |declaration| {try self.applyParsedDeclaration(declaration, frame);}@@ -360,7 +360,7 @@ pub fn styleAttributeChanged(self: *CSSStyleDeclaration, text: ?[]const u8, fram// we need to get this declaration back in syncself.clearProperties(frame);if (text) |t| {- try self.applyDeclarations(t, frame);+ try self.applyDeclarations(CssParser.parseDeclarationsList(t), frame);}}@@ -399,15 +399,20 @@ pub fn setCssText(self: *CSSStyleDeclaration, text: []const u8, frame: *Frame) !if (self._is_computed) {return error.NoModificationAllowed;}- try self.replaceCssText(text, frame);+ try self.replaceDeclarations(CssParser.parseDeclarationsList(text), frame);}-// setCssText without the read-only check, for declarations that are never-// computed (a CSSStyleRule's style).-pub fn replaceCssText(self: *CSSStyleDeclaration, text: []const u8, frame: *Frame) !void {+// A CSSStyleRule's style, from the rule's block in a stylesheet. Unlike+// cssText, the block may nest rules (CSS Nesting); its declarations are the+// ones around them.+pub fn replaceStyleBlock(self: *CSSStyleDeclaration, block: []const u8, frame: *Frame) !void {+ try self.replaceDeclarations(CssParser.parseStyleBlock(block), frame);+}++fn replaceDeclarations(self: *CSSStyleDeclaration, declarations: CssParser.DeclarationsIterator, frame: *Frame) !void {self.clearProperties(frame);- try self.applyDeclarations(text, frame);+ try self.applyDeclarations(declarations, frame);try self.syncStyleAttribute(frame);}diff --git a/src/browser/webapi/css/CSSStyleSheet.zig b/src/browser/webapi/css/CSSStyleSheet.zigindex 744b8dccb..8f96fc409 100644--- a/src/browser/webapi/css/CSSStyleSheet.zig+++ b/src/browser/webapi/css/CSSStyleSheet.zig@@ -99,7 +99,7 @@ pub fn insertRule(self: *CSSStyleSheet, rule: []const u8, maybe_index: ?u32, fraconst style_props = try style_rule.getStyle(frame);const style = style_props.asCSSStyleDeclaration();- try style.replaceCssText(s.block, frame);+ try style.replaceStyleBlock(s.block, frame);break :blk style_rule._proto;},// Opaque placeholder for at-rules. The CSS engine doesn't apply@@ -194,7 +194,7 @@ fn parseInto(self: *CSSStyleSheet, text: []const u8, frame: *Frame) CSSError!voiconst style_props = try style_rule.getStyle(frame);const style = style_props.asCSSStyleDeclaration();- try style.replaceCssText(s.block, frame);+ try style.replaceStyleBlock(s.block, frame);break :blk style_rule._proto;},.at_rule => |a| try CSSRule.initAtRule(atRuleTypeFor(a.keyword), a.text, frame),