Lightpanda: the headless browser designed for AI and automation
webapi: getComputedStyle().transform tries to return better value
Karl Seguin51479aaba755
diff --git a/src/browser/tests/css/computed_transform.html b/src/browser/tests/css/computed_transform.htmlnew file mode 100644index 000000000..d52657930--- /dev/null+++ b/src/browser/tests/css/computed_transform.html@@ -0,0 +1,45 @@+<!DOCTYPE html>+<head>+ <script src="../testing.js"></script>+</head>++<!--+ The resolved transform is "none" or a single matrix()/matrix3d(), as in+ Chrome. Animation libraries (popmotion) regex it and crash otherwise.+-->++<div id=translate_scale style="transform: translateX(10px) scale(2)"></div>+<div id=rotate style="transform: rotate(45deg)"></div>+<div id=rotate90 style="transform: rotate(90deg)"></div>+<div id=three_d style="transform: translate3d(1px, 2px, 3px)"></div>+<div id=identity style="transform: translate(0)"></div>+<div id=explicit_none style="transform: none"></div>+<div id=unset></div>+<div id=matrix style="transform: matrix(1, 2, 3, 4, 5, 6)"></div>++<script id=resolved_transform>+ const t = (id) => getComputedStyle(document.getElementById(id)).transform;+ testing.expectEqual('matrix(2, 0, 0, 2, 10, 0)', t('translate_scale'));+ testing.expectEqual('matrix(0.707107, 0.707107, -0.707107, 0.707107, 0, 0)', t('rotate'));+ testing.expectEqual('matrix(6.12323e-17, 1, -1, 6.12323e-17, 0, 0)', t('rotate90'));+ testing.expectEqual('matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1)', t('three_d'));+ testing.expectEqual('matrix(1, 0, 0, 1, 0, 0)', t('identity'));+ testing.expectEqual('none', t('explicit_none'));+ testing.expectEqual('none', t('unset'));+ testing.expectEqual('matrix(1, 2, 3, 4, 5, 6)', t('matrix'));++ // getPropertyValue goes through the same path; el.style keeps the+ // specified value.+ const el = document.getElementById('translate_scale');+ testing.expectEqual('matrix(2, 0, 0, 2, 10, 0)', getComputedStyle(el).getPropertyValue('transform'));+ testing.expectEqual('translateX(10px) scale(2)', el.style.transform);+</script>++<script id=popmotion_pattern>+ {+ // What popmotion's measurement does with the resolved value.+ const style = getComputedStyle(document.getElementById('translate_scale'));+ const m = style.transform.match(/^matrix\((.+)\)$/);+ testing.expectEqual(10, parseFloat(m[1].split(', ')[4]));+ }+</script>diff --git a/src/browser/webapi/css/CSSStyleDeclaration.zig b/src/browser/webapi/css/CSSStyleDeclaration.zigindex f7fbedb91..c0982c35f 100644--- a/src/browser/webapi/css/CSSStyleDeclaration.zig+++ b/src/browser/webapi/css/CSSStyleDeclaration.zig@@ -24,6 +24,7 @@ const CssParser = @import("../../css/Parser.zig");const js = @import("../../js/js.zig");const Frame = @import("../../Frame.zig");const Element = @import("../Element.zig");+const DOMMatrixReadOnly = @import("../DOMMatrixReadOnly.zig");const log = lp.log;const String = lp.String;@@ -76,6 +77,17 @@ pub fn item(self: *const CSSStyleDeclaration, index: u32) []const u8 {pub fn getPropertyValue(self: *const CSSStyleDeclaration, property_name: []const u8, frame: *Frame) []const u8 {const normalized = normalizePropertyName(property_name, &frame.buf);const wrapped = String.wrap(normalized);+ const value = self.propertyValue(normalized, wrapped, frame);++ // The resolved transform is always a matrix: animation libraries+ // (popmotion) regex it as matrix()/matrix3d() and crash on anything else.+ if (self._is_computed and wrapped.eql(comptime .wrap("transform"))) {+ return resolvedTransform(value, frame);+ }+ return value;+}++fn propertyValue(self: *const CSSStyleDeclaration, normalized: []const u8, wrapped: String, frame: *Frame) []const u8 {// Computed styles must reflect stylesheet rules, not just the element's// inline `style=` attribute. Limited to display/visibility — what aria@@ -200,6 +212,59 @@ fn axisPair(self: *const CSSStyleDeclaration, prop: *const Property) ?AxisPair {return if (longhand.is_x) .{ .name = name, .x = prop, .y = partner } else .{ .name = name, .x = partner, .y = prop };}+// "none", or the transform list collapsed into one matrix() / matrix3d(),+// like Chrome. A value that doesn't parse resolves to "none", as an invalid+// declaration never applies.+fn resolvedTransform(value: []const u8, frame: *Frame) []const u8 {+ var m = DOMMatrixReadOnly.identity();+ var is_2d = true;+ const trimmed = std.mem.trim(u8, value, " \t\r\n");+ if (trimmed.len == 0 or std.mem.eql(u8, trimmed, "none")) {+ return "none";+ }+ DOMMatrixReadOnly.parseTransformList(trimmed, &m, &is_2d) catch return "none";++ var buf = std.Io.Writer.Allocating.init(frame.local_arena);+ const writer = &buf.writer;+ const components: []const usize = if (is_2d) &.{ 0, 1, 4, 5, 12, 13 } else &.{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };+ writer.writeAll(if (is_2d) "matrix(" else "matrix3d(") catch return "none";+ for (components, 0..) |c, i| {+ if (i > 0) writer.writeAll(", ") catch return "none";+ writeCssNumber(writer, m[c]) catch return "none";+ }+ writer.writeByte(')') catch return "none";+ return buf.written();+}++// Six significant digits with trailing zeros dropped, as Chrome serializes+// computed numbers (JS toPrecision(6), trimmed): 0.707107, 6.12323e-17.+fn writeCssNumber(writer: *std.Io.Writer, value: f64) !void {+ if (value == 0 or !std.math.isFinite(value)) {+ return writer.writeAll("0");+ }+ const exponent: i32 = @intFromFloat(@floor(std.math.log10(@abs(value))));+ var tmp: [64]u8 = undefined;+ if (exponent < -6 or exponent >= 6) {+ const str = try std.fmt.bufPrint(&tmp, "{e:.5}", .{value});+ const e_index = std.mem.indexOfScalar(u8, str, 'e').?;+ try writer.writeAll(trimFraction(str[0..e_index]));+ try writer.writeByte('e');+ const exp_str = str[e_index + 1 ..];+ if (exp_str[0] != '-') try writer.writeByte('+');+ return writer.writeAll(exp_str);+ }+ const decimals: usize = @intCast(5 - exponent);+ const str = try std.fmt.bufPrint(&tmp, "{d:.[1]}", .{ value, decimals });+ const trimmed = trimFraction(str);+ // a value that rounds to zero at this precision has no sign+ try writer.writeAll(if (std.mem.eql(u8, trimmed, "-0")) "0" else trimmed);+}++fn trimFraction(str: []const u8) []const u8 {+ if (std.mem.indexOfScalar(u8, str, '.') == null) return str;+ return std.mem.trimEnd(u8, std.mem.trimEnd(u8, str, "0"), ".");+}+fn resolvedDimension(element: *Element, dimension: enum { width, height }, frame: *Frame) []const u8 {if (!element.isVisible(frame)) {return "auto";@@ -1154,6 +1219,34 @@ pub const JsApi = struct {};const testing = @import("../../../testing.zig");+test "WebApi: CSSStyleDeclaration computed transform" {+ try testing.htmlRunner("css/computed_transform.html", .{});+}++test "writeCssNumber: six significant digits" {+ const cases = [_]struct { f64, []const u8 }{+ .{ 0, "0" },+ .{ -0.0, "0" },+ .{ 1, "1" },+ .{ 10, "10" },+ .{ -2.5, "-2.5" },+ .{ 0.7071067811865476, "0.707107" },+ .{ -0.7071067811865476, "-0.707107" },+ .{ 6.123233995736766e-17, "6.12323e-17" },+ .{ 123456.7, "123457" },+ .{ 1234567, "1.23457e+6" },+ .{ 0.0001, "0.0001" },+ .{ 0.000001, "0.000001" },+ .{ -1e-7, "-1e-7" },+ };+ for (cases) |c| {+ var buf: [64]u8 = undefined;+ var writer = std.Io.Writer.fixed(&buf);+ try writeCssNumber(&writer, c[0]);+ try testing.expectEqual(c[1], writer.buffered());+ }+}+test "CSS property value storage is reused" {const frame = try testing.createFrame();defer testing.test_session.closeAllPages();