Lightpanda: the headless browser designed for AI and automation
internal: Always correct StyleManager context
Karl Seguincea3b815d5f1
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 9c0c000f1..7e8061eab 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -2664,6 +2664,7 @@ const RemoveNodeOpts = struct {// Set to false when the caller queues its own combined mutation recordnotify_observers: bool = true,};+pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOpts) void {// NodeIterator pre-removing steps must run while the tree is intact.if (self._live_node_iterators.first != null) {@@ -2761,15 +2762,21 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOptpopover.removeFromOpen(el, self);- // If a <style> element is being removed, remove its sheet from the list+ // If a <style> element is being removed, remove its sheet from the list.+ // `self` is the calling frame — Node.removeChild passes its own — so+ // both the list and the rebuild belong to the element's frame, which is+ // the one holding the sheet in its cascade.+ const sheet_owner = el.ownerFrame(self);if (el.is(Element.Html.Style)) |style| {if (style._sheet) |sheet| {- if (self.document._style_sheets) |sheets| {- sheets.remove(sheet);- }+ removeStyleSheet(sheet_owner, sheet);style._sheet = null;}- self._style_manager.sheetModified();+ // Unconditional: with no materialized sheet the manager still holds+ // the rules it parsed straight from the element's text.+ if (sheet_owner) |owner| {+ owner._style_manager.sheetModified();+ }} else if (el.is(Element.Html.Link)) |link| {// External stylesheet links registered via Frame.loadExternalStylesheet// must be symmetrically deregistered on disconnect, or@@ -2778,16 +2785,22 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOpt// exactly the SPA theme-switch pattern (append new sheet,// remove old) the feature exists to serve.if (link._sheet) |sheet| {- if (self.document._style_sheets) |sheets| {- sheets.remove(sheet);- }+ removeStyleSheet(sheet_owner, sheet);link._sheet = null;- self._style_manager.sheetModified();+ if (sheet_owner) |owner| {+ owner._style_manager.sheetModified();+ }}}}}+fn removeStyleSheet(owner: ?*Frame, sheet: *CSSStyleSheet) void {+ const frame = owner orelse return;+ const sheets = frame.document._style_sheets orelse return;+ sheets.remove(sheet);+}+// The TreeWalker isn't shadow DOM aware, so this is correctly scoped to direct// descendants (ids nested under a shadow DOM are owned by that shadow DOM).fn unregisterSubtreeIds(self: *Frame, node: *Node, id_maps: ElementIdMaps) void {diff --git a/src/browser/RenderTree.zig b/src/browser/RenderTree.zigindex 3e248e817..a8af2099a 100644--- a/src/browser/RenderTree.zig+++ b/src/browser/RenderTree.zig@@ -172,7 +172,9 @@ fn visibleDisplay(el: *Element, frame: *Frame) ?StyleManager.Display {if (tag.isMetadata() or tag == .svg) {return null;}- const d = frame._style_manager.display(el);++ const owner = el.ownerFrame(frame) orelse return .other;+ const d = owner._style_manager.display(el);if (d == .none) {return null;}diff --git a/src/browser/StyleManager.zig b/src/browser/StyleManager.zigindex 2fb24b388..894a73913 100644--- a/src/browser/StyleManager.zig+++ b/src/browser/StyleManager.zig@@ -100,6 +100,16 @@ pub fn deinit(self: *StyleManager) void {self.arena.release();}+// StyleManager methods should always be invoked on the StyleManager of the+// Frame associated with an Element's document.+fn assertOwns(self: *const StyleManager, el_: ?*const Element) void {+ if (comptime lp.IS_DEBUG == false) {+ return;+ }+ const el = el_ orelse return;+ std.debug.assert(el.ownerFrame(self.frame) == self.frame);+}+/// Hard cap on `@media` / `@layer` nesting depth. CSS allows arbitrarily-deep/// at-rule nesting; without a cap a hostile inline stylesheet could blow the/// Zig stack via the mutually-recursive `applyMediaAtRule` / `applyLayerAtRule`@@ -671,6 +681,7 @@ const Probe = enum { hidden, visibility, pointer_events };const Memo = std.AutoHashMapUnmanaged(*Element, Props);pub fn isHidden(self: *StyleManager, el: *Element, options: CheckVisibilityOptions) bool {+ self.assertOwns(el);self.rebuildIfDirty() catch return false;if (!options.ancestors) {return self.ownProps(el).probe(.hidden, options);@@ -686,6 +697,7 @@ pub fn hasDisplayNone(self: *StyleManager, el: *Element) bool {/// Own property, no ancestor walk; honors the UA hidden-element rules.pub fn display(self: *StyleManager, el: *Element) Display {+ self.assertOwns(el);self.rebuildIfDirty() catch return .other;return self.ownProps(el).display;}@@ -695,6 +707,7 @@ pub fn display(self: *StyleManager, el: *Element) Display {/// are NOT counted, so document scaffolding is preserved. Used by the HTML/// dump's "invisible" strip mode.pub fn hasAuthorDisplayNone(self: *StyleManager, el: *Element) bool {+ self.assertOwns(el);self.rebuildIfDirty() catch return false;const p = self.ownProps(el);return p.author_display and p.display == .none;@@ -705,11 +718,13 @@ pub fn hasAuthorDisplayNone(self: *StyleManager, el: *Element) bool {/// display:none: an ancestor with display:none means the element isn't/// rendered, but its computed `visibility` still reflects inherited visibility.pub fn hasVisibilityHiddenInherited(self: *StyleManager, el: *Element) bool {+ self.assertOwns(el);self.rebuildIfDirty() catch return false;return self.anyInChain(el, .visibility, .{});}pub fn hasPointerEventsNone(self: *StyleManager, el: *Element) bool {+ self.assertOwns(el);self.rebuildIfDirty() catch return false;return self.anyInChain(el, .pointer_events, .{});}@@ -1315,6 +1330,7 @@ const Slots = struct {/// inline style (the same source `el.style` exposes), so `getComputedStyle` and/// `el.style` agree on inline values instead of resolving them independently.pub fn inlineStyleValue(self: *StyleManager, el: *Element, property_name: String) ?[]const u8 {+ self.assertOwns(el);const style = el.inlineStyle(self.frame) orelse return null;return style.asCSSStyleDeclaration().declaredValue(property_name, self.frame);}@@ -1322,6 +1338,7 @@ pub fn inlineStyleValue(self: *StyleManager, el: *Element, property_name: String/// Computed value of a custom property (`--x`) on `el`, or null when nothing/// declares it. The value is returned as-is, no var substitutionpub fn customPropertyValue(self: *StyleManager, el: *Element, property_name: String) ?[]const u8 {+ self.assertOwns(el);self.rebuildIfDirty() catch return null;// Only the rules declaring this name; usually a handful, often none. An@@ -1396,17 +1413,22 @@ fn parsedCustomRules(self: *StyleManager, name: []const u8) ![]const ParsedCusto/// `inherit`/relative-unit chains share it).const MAX_FONT_ANCESTOR_DEPTH = 32;+/// The font-size an element inherits when nothing declares one and when an+/// element is part of a frameless document.+pub const DEFAULT_FONT_SIZE = 16;+/// Computed font-size in CSS pixels. We do what we can, namely inline styles/// font-related attributes, up the parent chain.pub fn computedFontSize(self: *StyleManager, element: ?*Element) f64 {+ self.assertOwns(element);return self.computedFontSizeAt(element, 0);}fn computedFontSizeAt(self: *StyleManager, element: ?*Element, depth: u8) f64 {if (depth >= MAX_FONT_ANCESTOR_DEPTH) {- return 16;+ return DEFAULT_FONT_SIZE;}- const current = element orelse return 16;+ const current = element orelse return DEFAULT_FONT_SIZE;const parent = current.parentElement();if (self.inlineStyleValue(current, comptime .wrap("font-size"))) |raw| {diff --git a/src/browser/dump.zig b/src/browser/dump.zigindex 7fd5802bd..b487f5dc9 100644--- a/src/browser/dump.zig+++ b/src/browser/dump.zig@@ -426,8 +426,12 @@ pub fn shouldStripElement(el: *Node.Element, strip: Opts.Strip, pruned: ?*constif (std.mem.eql(u8, tag_name, "iframe")) return true;}- if (strip.invisible and frame._style_manager.hasAuthorDisplayNone(el)) {- return true;+ if (strip.invisible) {+ if (el.ownerFrame(frame)) |owner| {+ if (owner._style_manager.hasAuthorDisplayNone(el)) {+ return true;+ }+ }}if (strip.shell and isShellElement(el)) {diff --git a/src/browser/interactive.zig b/src/browser/interactive.zigindex a25a3941e..c6f4e219f 100644--- a/src/browser/interactive.zig+++ b/src/browser/interactive.zig@@ -213,9 +213,11 @@ fn walkInteractive(else => {},}- if (frame._style_manager.hasDisplayNone(el)) {- tw.skipChildren();- continue;+ if (el.ownerFrame(frame)) |owner| {+ if (owner._style_manager.hasDisplayNone(el)) {+ tw.skipChildren();+ continue;+ }}const html_el = el.is(Element.Html) orelse continue;diff --git a/src/browser/tests/frames/cross_realm_style.html b/src/browser/tests/frames/cross_realm_style.htmlnew file mode 100644index 000000000..947cf1ad1--- /dev/null+++ b/src/browser/tests/frames/cross_realm_style.html@@ -0,0 +1,82 @@+<!DOCTYPE html>+<head>+ <style>+ .hidden { color: red; }+ </style>+</head>+<body>+<script src="../testing.js"></script>++<!--+A stylesheet feeds the cascade of the document that owns it, not of whichever+realm happens to mutate it. The parent reaches into an iframe's sheet here, and+the iframe helpers read the result back through the iframe's own StyleManager.++The parent's own `.hidden` rule sets color, not display: an edit that landed in+the parent's cascade instead would leave the iframe reporting the old display.++`sheet` is the iframe that gets its stylesheet mutated; `text` is left alone by+those blocks so the innerText and removal cases see the document as parsed.+-->+<iframe id="sheet" src="support/cross_realm_style.html"></iframe>+<iframe id="text" src="support/cross_realm_style.html"></iframe>++<script id="insert_rule_from_parent">+ testing.onload(() => {+ const idf = document.getElementById('sheet');+ const iwin = idf.contentWindow;++ testing.expectEqual('block', iwin.displayOf('probe'));++ idf.contentDocument.styleSheets[0].insertRule('#probe { display: none; }', 0);+ testing.expectEqual('none', iwin.displayOf('probe'));+ });+</script>++<script id="delete_rule_from_parent">+ testing.onload(() => {+ const idf = document.getElementById('sheet');+ const iwin = idf.contentWindow;++ // The rule the previous block inserted at index 0.+ testing.expectEqual('none', iwin.displayOf('probe'));+ idf.contentDocument.styleSheets[0].deleteRule(0);+ testing.expectEqual('block', iwin.displayOf('probe'));+ });+</script>++<script id="replace_sync_from_parent">+ testing.onload(() => {+ const idf = document.getElementById('sheet');+ const iwin = idf.contentWindow;++ idf.contentDocument.styleSheets[0].replaceSync('#probe { display: none; }');+ testing.expectEqual('none', iwin.displayOf('probe'));+ });+</script>++<script id="inner_text_reads_owner_cascade">+ testing.onload(() => {+ // `.hidden` is display:none in the iframe's sheet only. Read from the+ // parent realm, the hidden span must still be dropped.+ const idoc = document.getElementById('text').contentDocument;+ testing.expectEqual('keep', idoc.getElementById('host').innerText);+ });+</script>++<script id="remove_style_element_from_parent">+ testing.onload(() => {+ const idf = document.getElementById('text');+ const iwin = idf.contentWindow;+ const idoc = idf.contentDocument;++ testing.expectEqual('none', iwin.displayOf('gone'));++ // Removing it through the parent has to drop it from the iframe's list and+ // rebuild the iframe's cascade.+ idoc.getElementById('sheet').remove();+ testing.expectEqual(0, idoc.styleSheets.length);+ testing.expectEqual('inline', iwin.displayOf('gone'));+ });+</script>+</body>diff --git a/src/browser/tests/frames/support/cross_realm_style.html b/src/browser/tests/frames/support/cross_realm_style.htmlnew file mode 100644index 000000000..4877a9f1c--- /dev/null+++ b/src/browser/tests/frames/support/cross_realm_style.html@@ -0,0 +1,17 @@+<!DOCTYPE html>+<head>+ <style id="sheet">+ .hidden { display: none; }+ </style>+</head>+<body>+ <div id="probe">p</div>+ <div id="host">keep<span id="gone" class="hidden">drop</span></div>+ <script>+ // Called by the parent test: these execute in this frame's realm, so they+ // read this frame's StyleManager.+ function displayOf(id) {+ return getComputedStyle(document.getElementById(id)).display;+ }+ </script>+</body>diff --git a/src/browser/webapi/css/CSSStyleSheet.zig b/src/browser/webapi/css/CSSStyleSheet.zigindex 9cfc76082..744b8dccb 100644--- a/src/browser/webapi/css/CSSStyleSheet.zig+++ b/src/browser/webapi/css/CSSStyleSheet.zig@@ -4,6 +4,7 @@ const lp = @import("lightpanda");const js = @import("../../js/js.zig");const Frame = @import("../../Frame.zig");const Parser = @import("../../css/Parser.zig");+const StyleManager = @import("../../StyleManager.zig");const Element = @import("../Element.zig");@@ -42,6 +43,11 @@ pub fn getOwnerNode(self: *const CSSStyleSheet) ?*Element {return self._owner_node;}+fn ownerStyleManager(self: *const CSSStyleSheet, frame: *Frame) ?*StyleManager {+ const owner = self._owner_node orelse return null;+ return &(owner.ownerFrame(frame) orelse return null)._style_manager;+}+pub fn getHref(self: *const CSSStyleSheet) ?[]const u8 {return self._href;}@@ -115,7 +121,9 @@ pub fn insertRule(self: *CSSStyleSheet, rule: []const u8, maybe_index: ?u32, fralog.debug(.not_implemented, "insertRule clamped index", .{});}try rules.insert(index, inserted, frame);- frame._style_manager.ruleInserted(self, inserted);+ if (self.ownerStyleManager(frame)) |style_manager| {+ style_manager.ruleInserted(self, inserted);+ }return index;}@@ -155,7 +163,9 @@ fn deleteRule(self: *CSSStyleSheet, index: u32, frame: *Frame) !void {try rules.remove(index);// Notify StyleManager that rules have changed- frame._style_manager.sheetModified();+ if (self.ownerStyleManager(frame)) |style_manager| {+ style_manager.sheetModified();+ }}pub fn replace(self: *CSSStyleSheet, text: []const u8, frame: *Frame) CSSError!js.Promise {@@ -167,7 +177,9 @@ pub fn replaceSync(self: *CSSStyleSheet, text: []const u8, frame: *Frame) CSSErrconst rules = try self.getCssRules(frame);rules.clear();try self.parseInto(text, frame);- frame._style_manager.sheetModified();+ if (self.ownerStyleManager(frame)) |style_manager| {+ style_manager.sheetModified();+ }}fn parseInto(self: *CSSStyleSheet, text: []const u8, frame: *Frame) CSSError!void {diff --git a/src/browser/webapi/element/Html.zig b/src/browser/webapi/element/Html.zigindex 0835b0bb3..51637d7e2 100644--- a/src/browser/webapi/element/Html.zig+++ b/src/browser/webapi/element/Html.zig@@ -1638,8 +1638,11 @@ fn handleChildElement(// is hidden through its parent. If you can el.innerText on an element, the// visibility of el.parent doesn't matter. So we only care about visibility// on the element itself and then on each child. This is much simpler too.- if (state.frame._style_manager.hasDisplayNone(he.asElement())) {- return;+ const el = he.asElement();+ if (el.ownerFrame(state.frame)) |owner| {+ if (owner._style_manager.hasDisplayNone(el)) {+ return;+ }}if (he._type == .br) {diff --git a/src/browser/webapi/element/svg/TextContent.zig b/src/browser/webapi/element/svg/TextContent.zigindex 71511997e..134df9e5c 100644--- a/src/browser/webapi/element/svg/TextContent.zig+++ b/src/browser/webapi/element/svg/TextContent.zig@@ -21,6 +21,7 @@ const lp = @import("lightpanda");const js = @import("../../../js/js.zig");const Frame = @import("../../../Frame.zig");const text_measure = @import("../../../text_measure.zig");+const StyleManager = @import("../../../StyleManager.zig");const Node = @import("../../Node.zig");const Element = @import("../../Element.zig");@@ -89,7 +90,7 @@ fn text(self: *TextContent, frame: *Frame) []const u8 {fn fontSize(self: *TextContent, frame: *Frame) f64 {const element = self.asElement();- const owner = element.ownerFrame(frame) orelse return frame._style_manager.computedFontSize(null);+ const owner = element.ownerFrame(frame) orelse return StyleManager.DEFAULT_FONT_SIZE;return owner._style_manager.computedFontSize(element);}diff --git a/src/browser/webapi/svg/Length.zig b/src/browser/webapi/svg/Length.zigindex 61d5c833f..e250b808b 100644--- a/src/browser/webapi/svg/Length.zig+++ b/src/browser/webapi/svg/Length.zig@@ -23,6 +23,7 @@ const js = @import("../../js/js.zig");const Frame = @import("../../Frame.zig");const Page = @import("../../Page.zig");const units = @import("../../css/units.zig");+const StyleManager = @import("../../StyleManager.zig");const Element = @import("../Element.zig");const String = lp.String;@@ -298,12 +299,12 @@ fn resolveParsedLength(parsed: Parsed, element: *Element, direction: Direction,}fn fontSize(self: *const Length, frame: *Frame) f64 {- const element = self._element orelse return frame._style_manager.computedFontSize(null);+ const element = self._element orelse return StyleManager.DEFAULT_FONT_SIZE;return elementFontSize(element, frame);}fn elementFontSize(element: *Element, frame: *Frame) f64 {- const owner = element.ownerFrame(frame) orelse return frame._style_manager.computedFontSize(null);+ const owner = element.ownerFrame(frame) orelse return StyleManager.DEFAULT_FONT_SIZE;return owner._style_manager.computedFontSize(element);}diff --git a/src/server/cdp/AXNode.zig b/src/server/cdp/AXNode.zigindex b34da361c..64dc8e703 100644--- a/src/server/cdp/AXNode.zig+++ b/src/server/cdp/AXNode.zig@@ -1258,7 +1258,11 @@ const HiddenOptions = struct { ancestors: bool = true };/// Chromium's AX tree prunes display:none and visibility:hidden alike.fn isHidden(elt: *DOMNode.Element, frame: *Frame, options: HiddenOptions) bool {- return hasHidingAttribute(elt) or frame._style_manager.isHidden(elt, .{+ if (hasHidingAttribute(elt)) {+ return true;+ }+ const owner = elt.ownerFrame(frame) orelse return false;+ return owner._style_manager.isHidden(elt, .{.check_visibility = true,.ancestors = options.ancestors,});