Lightpanda: the headless browser designed for AI and automation
cache the computed-style object per element
Pierre Tachoire7e353927b995
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex f903f3e1d..4b44f1576 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -119,6 +119,10 @@ _attribute_named_node_map_lookup: std.AutoHashMapUnmanaged(usize, *Element.Attri// Lazily-created style, classList, and dataset objects. Only stored for elements// that actually access these features via JavaScript, saving 24 bytes per element._element_styles: Element.StyleLookup = .empty,+// Computed-style views handed out by window.getComputedStyle. The computed+// variant is a stateless lazy view, so one per element suffices — and Chrome+// returns the same object for repeated calls, so identity is also conformance.+_element_computed_styles: Element.StyleLookup = .empty,_element_datasets: Element.DatasetLookup = .empty,_element_class_lists: Element.ClassListLookup = .empty,_element_rel_lists: Element.RelListLookup = .empty,diff --git a/src/browser/tests/element/styles.html b/src/browser/tests/element/styles.htmlindex b4e81aa2b..7418d0ef3 100644--- a/src/browser/tests/element/styles.html+++ b/src/browser/tests/element/styles.html@@ -216,6 +216,14 @@document.body.appendChild(plainDiv);testing.expectEqual('block', window.getComputedStyle(plainDiv).getPropertyValue('display'));+ // Repeated calls return the same object (as in Chrome); distinct per element.+ testing.expectTrue(window.getComputedStyle(div) === window.getComputedStyle(div));+ testing.expectTrue(window.getComputedStyle(div) === cs);+ testing.expectFalse(window.getComputedStyle(div) === window.getComputedStyle(plainDiv));+ // The cached object stays a live view.+ div.style.setProperty('text-transform', 'lowercase');+ testing.expectEqual('lowercase', window.getComputedStyle(div).getPropertyValue('text-transform'));+// A normal declaration must not override an earlier !important one, and the// computed and inline (el.style) paths must agree on the resolved value.const impDiv = document.createElement('div');diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zigindex 7a488fac7..e74077d00 100644--- a/src/browser/webapi/Window.zig+++ b/src/browser/webapi/Window.zig@@ -506,9 +506,16 @@ pub fn getComputedStyle(_: *const Window, element: *Element, pseudo_element: ?[]if (pseudo_element) |pe| {if (pe.len != 0) {log.warn(.not_implemented, "window.GetComputedStyle", .{ .pseudo_element = pe });+ // Chrome hands out a distinct object per pseudo-element, so these+ // can't share the per-element cache entry.+ return CSSStyleProperties.init(element, true, frame);}}- return CSSStyleProperties.init(element, true, frame);+ const gop = try frame._element_computed_styles.getOrPut(frame.arena, element);+ if (!gop.found_existing) {+ gop.value_ptr.* = try CSSStyleProperties.init(element, true, frame);+ }+ return gop.value_ptr.*;}// window.open(url?, target?, features?) — v1 scope: