Lightpanda: the headless browser designed for AI and automation
webapi: add live SVG scalar values
Madison Steinerc40a2ccac695
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 8ab70b904..6c221b85d 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -42,6 +42,8 @@ const Event = @import("webapi/Event.zig");const EventTarget = @import("webapi/EventTarget.zig");const Element = @import("webapi/Element.zig");const HtmlElement = @import("webapi/element/Html.zig");+const AnimatedLength = @import("webapi/svg/AnimatedLength.zig");+const AnimatedPreserveAspectRatio = @import("webapi/svg/AnimatedPreserveAspectRatio.zig");const AnimatedString = @import("webapi/svg/AnimatedString.zig");const Window = @import("webapi/Window.zig");const Location = @import("webapi/Location.zig");@@ -142,6 +144,8 @@ _element_shadow_roots: Element.ShadowRootLookup = .empty,_node_owner_documents: Node.OwnerDocumentLookup = .empty,_element_scroll_positions: Element.ScrollPositionLookup = .empty,_element_namespace_uris: Element.NamespaceUriLookup = .empty,+_svg_animated_lengths: AnimatedLength.Lookup = .empty,+_svg_animated_preserve_aspect_ratios: AnimatedPreserveAspectRatio.Lookup = .empty,_svg_animated_strings: AnimatedString.Lookup = .empty,// Same as above, but for Nodes (slot assigments apply to both Element ANDdiff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex 8dcc00568..cdb6c021d 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -1070,6 +1070,12 @@ pub const PageJsApis = flattenTypes(&.{@import("../webapi/element/svg/Polyline.zig"),@import("../webapi/svg/AnimatedString.zig"),@import("../webapi/svg/Number.zig"),+ @import("../webapi/svg/Length.zig"),+ @import("../webapi/svg/Angle.zig"),+ @import("../webapi/svg/Transform.zig"),+ @import("../webapi/svg/AnimatedLength.zig"),+ @import("../webapi/svg/PreserveAspectRatio.zig"),+ @import("../webapi/svg/AnimatedPreserveAspectRatio.zig"),@import("../webapi/encoding/TextDecoder.zig"),@import("../webapi/encoding/TextEncoder.zig"),@import("../webapi/encoding/TextEncoderStream.zig"),diff --git a/src/browser/tests/element/svg/svgsvg.html b/src/browser/tests/element/svg/svgsvg.htmlindex e73b55587..8fa1379f8 100644--- a/src/browser/tests/element/svg/svgsvg.html+++ b/src/browser/tests/element/svg/svgsvg.html@@ -1,7 +1,7 @@<!DOCTYPE html><script src="../../testing.js"></script>-<svg id=first>+<svg id=first x="10" y="20px" width="25%" height="2.54cm" preserveAspectRatio="xMinYMax slice"><g><rect id=inner-rect></rect><svg id=nested>@@ -27,6 +27,163 @@}</script>+<script id=scalarFactories>+{+ const svg = $('#first');++ const length = svg.createSVGLength();+ testing.expectEqual(true, length instanceof SVGLength);+ testing.expectEqual(false, length === svg.createSVGLength());+ testing.expectEqual(SVGLength.SVG_LENGTHTYPE_NUMBER, length.unitType);+ testing.expectEqual(0, length.value);+ testing.expectEqual('0', length.valueAsString);++ length.valueAsString = '2.54cm';+ testing.expectEqual(SVGLength.SVG_LENGTHTYPE_CM, length.unitType);+ testing.expectEqual(2.54, length.valueInSpecifiedUnits);+ testing.expectEqual(96, Math.round(length.value));+ testing.expectEqual('2.54cm', length.valueAsString);++ // `value` is an absolute user-unit setter and resets the unit to NUMBER.+ length.value = 12;+ testing.expectEqual(SVGLength.SVG_LENGTHTYPE_NUMBER, length.unitType);+ testing.expectEqual('12', length.valueAsString);+ length.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX, 4.5);+ testing.expectEqual('4.5px', length.valueAsString);+ testing.expectError('NotSupportedError', () => length.newValueSpecifiedUnits(0, 1));+ testing.expectError('TypeError', () => { length.value = Infinity; });+ testing.expectError('SyntaxError', () => { length.valueAsString = 'calc(1px + 2%)'; });+ testing.expectError('SyntaxError', () => { length.valueAsString = 'NaN'; });++ const angle = svg.createSVGAngle();+ testing.expectEqual(true, angle instanceof SVGAngle);+ testing.expectEqual(false, angle === svg.createSVGAngle());+ testing.expectEqual(SVGAngle.SVG_ANGLETYPE_UNSPECIFIED, angle.unitType);+ angle.valueAsString = '3.141592653589793rad';+ testing.expectEqual(SVGAngle.SVG_ANGLETYPE_RAD, angle.unitType);+ testing.expectEqual(180, Math.round(angle.value));+ angle.convertToSpecifiedUnits(SVGAngle.SVG_ANGLETYPE_DEG);+ testing.expectEqual(180, Math.round(angle.valueInSpecifiedUnits));+ testing.expectEqual('180deg', angle.valueAsString);+ angle.value = 45;+ testing.expectEqual(SVGAngle.SVG_ANGLETYPE_UNSPECIFIED, angle.unitType);+ testing.expectEqual('45', angle.valueAsString);+ testing.expectError('NotSupportedError', () => angle.convertToSpecifiedUnits(0));+ testing.expectError('TypeError', () => { angle.value = NaN; });++ const transform = svg.createSVGTransform();+ testing.expectEqual(true, transform instanceof SVGTransform);+ testing.expectEqual(false, transform === svg.createSVGTransform());+ testing.expectEqual(SVGTransform.SVG_TRANSFORM_MATRIX, transform.type);+ testing.expectEqual(true, transform.matrix === transform.matrix);+ testing.expectEqual(1, transform.matrix.a);+ transform.setTranslate(3, 4);+ testing.expectEqual(SVGTransform.SVG_TRANSFORM_TRANSLATE, transform.type);+ testing.expectEqual(3, transform.matrix.e);+ testing.expectEqual(4, transform.matrix.f);++ const source = svg.createSVGMatrix();+ source.e = 8;+ const copied = svg.createSVGTransformFromMatrix(source);+ testing.expectEqual(8, copied.matrix.e);+ source.e = 9;+ testing.expectEqual(8, copied.matrix.e);+ copied.setRotate(90, 10, 20);+ testing.expectEqual(SVGTransform.SVG_TRANSFORM_ROTATE, copied.type);+ testing.expectEqual(90, copied.angle);+ testing.expectEqual(30, Math.round(copied.matrix.e));+ testing.expectEqual(10, Math.round(copied.matrix.f));+ testing.expectError('TypeError', () => copied.setScale(Infinity, 1));++ const matrix3d = new DOMMatrix();+ matrix3d.m13 = 7;+ const copied2d = svg.createSVGTransformFromMatrix(matrix3d);+ testing.expectEqual(true, copied2d.matrix.is2D);+ testing.expectEqual(0, copied2d.matrix.m13);+}+</script>++<script id=liveScalarProperties>+{+ const svg = $('#first');++ testing.expectEqual(true, svg.x instanceof SVGAnimatedLength);+ testing.expectEqual(true, svg.x === svg.x);+ testing.expectEqual(true, svg.x.baseVal === svg.x.baseVal);+ testing.expectEqual(true, svg.x.animVal === svg.x.animVal);+ testing.expectEqual(false, svg.x.baseVal === svg.x.animVal);+ testing.expectEqual(SVGLength.SVG_LENGTHTYPE_NUMBER, svg.x.baseVal.unitType);+ testing.expectEqual(SVGLength.SVG_LENGTHTYPE_PX, svg.y.baseVal.unitType);+ testing.expectEqual(SVGLength.SVG_LENGTHTYPE_PERCENTAGE, svg.width.baseVal.unitType);+ testing.expectEqual(SVGLength.SVG_LENGTHTYPE_CM, svg.height.baseVal.unitType);+ testing.expectEqual(96, Math.round(svg.height.baseVal.value));++ const nested = $('#nested');+ nested.setAttribute('width', '50%');+ testing.expectEqual(+ Math.round(svg.width.baseVal.value / 2),+ Math.round(nested.width.baseVal.value),+ );+ nested.setAttribute('style', 'font-size: 20px');+ nested.setAttribute('x', '2em');+ testing.expectEqual(40, nested.x.baseVal.value);+ nested.setAttribute('font-size', '30px');+ testing.expectEqual(40, nested.x.baseVal.value);+ nested.style.fontSize = '';+ testing.expectEqual(60, nested.x.baseVal.value);++ const deep = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ deep.setAttribute('width', '50%');+ let deepest = deep;+ for (let i = 0; i < 40; i++) {+ const child = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ child.setAttribute('width', '50%');+ child.setAttribute('font-size', '1em');+ deepest.appendChild(child);+ deepest = child;+ }+ deepest.setAttribute('x', '1em');+ document.body.appendChild(deep);+ testing.expectEqual(true, Number.isFinite(deepest.width.baseVal.value));+ testing.expectEqual(16, deepest.x.baseVal.value);+ deep.remove();++ svg.setAttribute('x', '12px');+ testing.expectEqual(SVGLength.SVG_LENGTHTYPE_PX, svg.x.baseVal.unitType);+ testing.expectEqual(12, svg.x.baseVal.value);+ testing.expectEqual(12, svg.x.animVal.value);+ svg.x.baseVal.valueInSpecifiedUnits = 4.5;+ testing.expectEqual('4.5px', svg.getAttribute('x'));+ svg.x.baseVal.value = 7;+ testing.expectEqual('7', svg.getAttribute('x'));+ testing.expectEqual(SVGLength.SVG_LENGTHTYPE_NUMBER, svg.x.animVal.unitType);+ testing.expectError('NoModificationAllowedError', () => { svg.x.animVal.value = 3; });+ testing.expectError('NoModificationAllowedError', () => { svg.x.animVal.valueAsString = '3px'; });++ const aspect = svg.preserveAspectRatio;+ testing.expectEqual(true, aspect instanceof SVGAnimatedPreserveAspectRatio);+ testing.expectEqual(true, aspect === svg.preserveAspectRatio);+ testing.expectEqual(true, aspect.baseVal === aspect.baseVal);+ testing.expectEqual(true, aspect.animVal === aspect.animVal);+ testing.expectEqual(false, aspect.baseVal === aspect.animVal);+ testing.expectEqual(SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_XMINYMAX, aspect.baseVal.align);+ testing.expectEqual(SVGPreserveAspectRatio.SVG_MEETORSLICE_SLICE, aspect.baseVal.meetOrSlice);++ aspect.baseVal.align = SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_XMIDYMID;+ testing.expectEqual('xMidYMid slice', svg.getAttribute('preserveAspectRatio'));+ svg.setAttribute('preserveAspectRatio', 'none meet');+ testing.expectEqual(SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_NONE, aspect.baseVal.align);+ testing.expectEqual(SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_NONE, aspect.animVal.align);+ testing.expectError('TypeError', () => { aspect.baseVal.align = 0; });+ testing.expectError('NoModificationAllowedError', () => { aspect.animVal.meetOrSlice = 2; });++ const empty = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ testing.expectEqual(SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_XMIDYMID, empty.preserveAspectRatio.baseVal.align);+ testing.expectEqual(SVGPreserveAspectRatio.SVG_MEETORSLICE_MEET, empty.preserveAspectRatio.baseVal.meetOrSlice);+ testing.expectEqual(null, empty.getAttribute('preserveAspectRatio'));+}+</script>+<script id=factories>{// SVG2 defines SVGPoint/SVGMatrix/SVGRect as aliases of the DOM geometrydiff --git a/src/browser/webapi/element/svg/Svg.zig b/src/browser/webapi/element/svg/Svg.zigindex 11b809b43..ae6ae220b 100644--- a/src/browser/webapi/element/svg/Svg.zig+++ b/src/browser/webapi/element/svg/Svg.zig@@ -28,6 +28,11 @@ const DOMRect = @import("../../DOMRect.zig");const DOMPoint = @import("../../DOMPoint.zig");const DOMMatrix = @import("../../DOMMatrix.zig");const SvgNumber = @import("../../svg/Number.zig");+const SvgLength = @import("../../svg/Length.zig");+const SvgAngle = @import("../../svg/Angle.zig");+const SvgTransform = @import("../../svg/Transform.zig");+const AnimatedLength = @import("../../svg/AnimatedLength.zig");+const AnimatedPreserveAspectRatio = @import("../../svg/AnimatedPreserveAspectRatio.zig");const Graphics = @import("Graphics.zig");@@ -56,6 +61,64 @@ pub fn getElementById(self: *Svg, id: []const u8) ?*Element {return null;}+pub fn getX(self: *Svg, frame: *Frame) !*AnimatedLength {+ return AnimatedLength.getOrCreate(self.asElement(), .x, frame);+}++pub fn getY(self: *Svg, frame: *Frame) !*AnimatedLength {+ return AnimatedLength.getOrCreate(self.asElement(), .y, frame);+}++pub fn getWidth(self: *Svg, frame: *Frame) !*AnimatedLength {+ return AnimatedLength.getOrCreate(self.asElement(), .width, frame);+}++pub fn getHeight(self: *Svg, frame: *Frame) !*AnimatedLength {+ return AnimatedLength.getOrCreate(self.asElement(), .height, frame);+}++pub fn getPreserveAspectRatio(self: *Svg, frame: *Frame) !*AnimatedPreserveAspectRatio {+ return AnimatedPreserveAspectRatio.getOrCreate(self.asElement(), frame);+}++pub fn createSVGPoint(_: *Svg, frame: *Frame) !*DOMPoint {+ return DOMPoint.create(0, 0, 0, 1, frame._page);+}++pub fn createSVGMatrix(_: *Svg, frame: *Frame) !*DOMMatrix {+ const identity: [16]f64 = .{+ 1, 0, 0, 0,+ 0, 1, 0, 0,+ 0, 0, 1, 0,+ 0, 0, 0, 1,+ };+ return DOMMatrix.create(identity, true, frame._page);+}++pub fn createSVGRect(_: *Svg, frame: *Frame) !*DOMRect {+ return DOMRect.create(.{}, frame._factory);+}++pub fn createSVGNumber(_: *Svg, frame: *Frame) !*SvgNumber {+ return frame._factory.create(SvgNumber{});+}++pub fn createSVGLength(_: *Svg, frame: *Frame) !*SvgLength {+ return SvgLength.detached(frame);+}++pub fn createSVGAngle(_: *Svg, frame: *Frame) !*SvgAngle {+ return SvgAngle.detached(frame);+}++pub fn createSVGTransform(_: *Svg, frame: *Frame) !*SvgTransform {+ return SvgTransform.detached(frame);+}++pub fn createSVGTransformFromMatrix(_: *Svg, init: ?SvgTransform.DOMMatrix2DInit, frame: *Frame) !*SvgTransform {+ return SvgTransform.fromMatrix(init, frame);+}+pub const JsApi = struct {pub const bridge = js.Bridge(Svg);@@ -67,29 +130,18 @@ pub const JsApi = struct {pub const getElementById = bridge.function(Svg.getElementById, .{});- pub const createSVGPoint = bridge.function(_createSVGPoint, .{});- fn _createSVGPoint(_: *Svg, frame: *Frame) !*DOMPoint {- return DOMPoint.create(0, 0, 0, 1, frame._page);- }-- pub const createSVGMatrix = bridge.function(_createSVGMatrix, .{});- fn _createSVGMatrix(_: *Svg, frame: *Frame) !*DOMMatrix {- const identity: [16]f64 = .{- 1, 0, 0, 0,- 0, 1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1,- };- return DOMMatrix.create(identity, true, frame._page);- }-- pub const createSVGRect = bridge.function(_createSVGRect, .{});- fn _createSVGRect(_: *Svg, frame: *Frame) !*DOMRect {- return DOMRect.create(.{}, frame._factory);- }+ pub const x = bridge.accessor(Svg.getX, null, .{});+ pub const y = bridge.accessor(Svg.getY, null, .{});+ pub const width = bridge.accessor(Svg.getWidth, null, .{});+ pub const height = bridge.accessor(Svg.getHeight, null, .{});+ pub const preserveAspectRatio = bridge.accessor(Svg.getPreserveAspectRatio, null, .{});- pub const createSVGNumber = bridge.function(_createSVGNumber, .{});- fn _createSVGNumber(_: *Svg, frame: *Frame) !*SvgNumber {- return frame._factory.create(SvgNumber{});- }+ pub const createSVGPoint = bridge.function(Svg.createSVGPoint, .{});+ pub const createSVGMatrix = bridge.function(Svg.createSVGMatrix, .{});+ pub const createSVGRect = bridge.function(Svg.createSVGRect, .{});+ pub const createSVGNumber = bridge.function(Svg.createSVGNumber, .{});+ pub const createSVGLength = bridge.function(Svg.createSVGLength, .{});+ pub const createSVGAngle = bridge.function(Svg.createSVGAngle, .{});+ pub const createSVGTransform = bridge.function(Svg.createSVGTransform, .{});+ pub const createSVGTransformFromMatrix = bridge.function(Svg.createSVGTransformFromMatrix, .{});};diff --git a/src/browser/webapi/svg/Angle.zig b/src/browser/webapi/svg/Angle.zignew file mode 100644index 000000000..f9f7011d8--- /dev/null+++ b/src/browser/webapi/svg/Angle.zig@@ -0,0 +1,252 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");+const lp = @import("lightpanda");++const js = @import("../../js/js.zig");+const Frame = @import("../../Frame.zig");+const Element = @import("../Element.zig");++const String = lp.String;+const Angle = @This();++_value: f64 = 0,+_unit: Unit = .unspecified,+_element: ?*Element = null,+_attr_name: String = .empty,+_read_only: bool = false,++const Unit = enum(u16) {+ unknown = 0,+ unspecified = 1,+ deg = 2,+ rad = 3,+ grad = 4,+ turn = 5,+};++pub fn detached(frame: *Frame) !*Angle {+ return frame._factory.create(Angle{});+}++pub fn getUnitType(self: *Angle) u16 {+ self.syncFromAttribute();+ return switch (self._unit) {+ .turn => 0,+ else => @intFromEnum(self._unit),+ };+}++pub fn getValue(self: *Angle) f64 {+ self.syncFromAttribute();+ return toDegrees(self._value, self._unit);+}++pub fn setValue(self: *Angle, value: f64, frame: *Frame) !void {+ try self.ensureWritable();+ try ensureFinite(value);+ self._value = value;+ self._unit = .unspecified;+ try self.writeBack(frame);+}++pub fn getValueInSpecifiedUnits(self: *Angle) f64 {+ self.syncFromAttribute();+ return self._value;+}++pub fn setValueInSpecifiedUnits(self: *Angle, value: f64, frame: *Frame) !void {+ try self.ensureWritable();+ try ensureFinite(value);+ self.syncFromAttribute();+ if (self._unit == .unknown) {+ self._unit = .unspecified;+ }+ self._value = value;+ try self.writeBack(frame);+}++pub fn getValueAsString(self: *Angle, frame: *Frame) ![]const u8 {+ self.syncFromAttribute();+ return self.serialize(frame);+}++pub fn setValueAsString(self: *Angle, value: String, frame: *Frame) !void {+ try self.ensureWritable();+ const parsed = parse(value.str()) catch return error.SyntaxError;+ self._value = parsed.value;+ self._unit = parsed.unit;+ try self.writeBack(frame);+}++pub fn newValueSpecifiedUnits(self: *Angle, unit_type: u16, value: f64, frame: *Frame) !void {+ try self.ensureWritable();+ const unit = try checkedUnit(unit_type);+ try ensureFinite(value);+ self._unit = unit;+ self._value = value;+ try self.writeBack(frame);+}++pub fn convertToSpecifiedUnits(self: *Angle, unit_type: u16, frame: *Frame) !void {+ try self.ensureWritable();+ const target = try checkedUnit(unit_type);+ const degrees = self.getValue();+ self._unit = target;+ self._value = fromDegrees(degrees, target);+ try self.writeBack(frame);+}++fn ensureWritable(self: *const Angle) !void {+ if (self._read_only) {+ return error.NoModificationAllowed;+ }+}++fn ensureFinite(value: f64) !void {+ if (!std.math.isFinite(value)) {+ return error.TypeError;+ }+}++fn syncFromAttribute(self: *Angle) void {+ const element = self._element orelse return;+ const raw = element.getAttributeSafe(self._attr_name) orelse {+ self._value = 0;+ self._unit = .unspecified;+ return;+ };+ const parsed = parse(raw) catch {+ self._value = 0;+ self._unit = .unknown;+ return;+ };+ self._value = parsed.value;+ self._unit = parsed.unit;+}++fn writeBack(self: *Angle, frame: *Frame) !void {+ const element = self._element orelse return;+ const value = try self.serialize(frame);+ try element.setAttributeSafe(self._attr_name, .wrap(value), frame);+}++fn serialize(self: *const Angle, frame: *Frame) ![]const u8 {+ return std.fmt.allocPrint(frame.local_arena, "{d}{s}", .{ self._value, unitSuffix(self._unit) });+}++const Parsed = struct {+ value: f64,+ unit: Unit,+};++fn parse(input: []const u8) !Parsed {+ const value = std.mem.trim(u8, input, " \t\r\n\x0c");+ if (value.len == 0) {+ return error.SyntaxError;+ }++ const suffixes = [_]struct { []const u8, Unit }{+ .{ "turn", .turn },+ .{ "grad", .grad },+ .{ "deg", .deg },+ .{ "rad", .rad },+ };+ for (suffixes) |entry| {+ const suffix, const unit = entry;+ if (value.len <= suffix.len) {+ continue;+ }+ if (!std.ascii.eqlIgnoreCase(value[value.len - suffix.len ..], suffix)) {+ continue;+ }+ const number = std.mem.trim(u8, value[0 .. value.len - suffix.len], " \t\r\n\x0c");+ return .{ .value = try parseNumber(number), .unit = unit };+ }+ return .{ .value = try parseNumber(value), .unit = .unspecified };+}++fn parseNumber(value: []const u8) !f64 {+ const number = std.fmt.parseFloat(f64, value) catch return error.SyntaxError;+ if (!std.math.isFinite(number)) {+ return error.SyntaxError;+ }+ return number;+}++fn checkedUnit(value: u16) !Unit {+ return switch (value) {+ 1 => .unspecified,+ 2 => .deg,+ 3 => .rad,+ 4 => .grad,+ else => error.NotSupported,+ };+}++fn toDegrees(value: f64, unit: Unit) f64 {+ return switch (unit) {+ .unknown, .unspecified, .deg => value,+ .rad => value * 180.0 / std.math.pi,+ .grad => value * 0.9,+ .turn => value * 360.0,+ };+}++fn fromDegrees(value: f64, unit: Unit) f64 {+ return switch (unit) {+ .unknown, .unspecified, .deg => value,+ .rad => value * std.math.pi / 180.0,+ .grad => value / 0.9,+ .turn => value / 360.0,+ };+}++fn unitSuffix(unit: Unit) []const u8 {+ return switch (unit) {+ .unknown, .unspecified => "",+ .deg => "deg",+ .rad => "rad",+ .grad => "grad",+ .turn => "turn",+ };+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(Angle);++ pub const Meta = struct {+ pub const name = "SVGAngle";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const SVG_ANGLETYPE_UNKNOWN = bridge.property(0, .{ .template = true });+ pub const SVG_ANGLETYPE_UNSPECIFIED = bridge.property(1, .{ .template = true });+ pub const SVG_ANGLETYPE_DEG = bridge.property(2, .{ .template = true });+ pub const SVG_ANGLETYPE_RAD = bridge.property(3, .{ .template = true });+ pub const SVG_ANGLETYPE_GRAD = bridge.property(4, .{ .template = true });++ pub const unitType = bridge.accessor(Angle.getUnitType, null, .{});+ pub const value = bridge.accessor(Angle.getValue, Angle.setValue, .{});+ pub const valueInSpecifiedUnits = bridge.accessor(Angle.getValueInSpecifiedUnits, Angle.setValueInSpecifiedUnits, .{});+ pub const valueAsString = bridge.accessor(Angle.getValueAsString, Angle.setValueAsString, .{});+ pub const newValueSpecifiedUnits = bridge.function(Angle.newValueSpecifiedUnits, .{});+ pub const convertToSpecifiedUnits = bridge.function(Angle.convertToSpecifiedUnits, .{});+};diff --git a/src/browser/webapi/svg/AnimatedLength.zig b/src/browser/webapi/svg/AnimatedLength.zignew file mode 100644index 000000000..299b344ea--- /dev/null+++ b/src/browser/webapi/svg/AnimatedLength.zig@@ -0,0 +1,103 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");+const lp = @import("lightpanda");++const js = @import("../../js/js.zig");+const Frame = @import("../../Frame.zig");+const Element = @import("../Element.zig");+const Length = @import("Length.zig");++const AnimatedLength = @This();++_base_val: *Length,+_anim_val: *Length,++pub const Kind = enum {+ x,+ y,+ width,+ height,++ fn attributeName(self: Kind) lp.String {+ return switch (self) {+ .x => comptime .wrap("x"),+ .y => comptime .wrap("y"),+ .width => comptime .wrap("width"),+ .height => comptime .wrap("height"),+ };+ }++ fn direction(self: Kind) Length.Direction {+ return switch (self) {+ .x, .width => .horizontal,+ .y, .height => .vertical,+ };+ }+};++pub const Key = struct {+ element: *Element,+ kind: Kind,+};++pub const Lookup = std.AutoHashMapUnmanaged(Key, *AnimatedLength);++pub fn getOrCreate(element: *Element, kind: Kind, frame: *Frame) !*AnimatedLength {+ const key: Key = .{+ .element = element,+ .kind = kind,+ };+ const gop = try frame._svg_animated_lengths.getOrPut(frame.arena, key);+ if (!gop.found_existing) {+ errdefer _ = frame._svg_animated_lengths.remove(key);+ gop.value_ptr.* = try create(element, kind.attributeName(), kind.direction(), frame);+ }+ return gop.value_ptr.*;+}++pub fn create(element: *Element, attr_name: lp.String, direction: Length.Direction, frame: *Frame) !*AnimatedLength {+ const base_val = try Length.reflected(element, attr_name, direction, false, frame);+ const anim_val = try Length.reflected(element, attr_name, direction, true, frame);+ return frame._factory.create(AnimatedLength{+ ._base_val = base_val,+ ._anim_val = anim_val,+ });+}++pub fn getBaseVal(self: *AnimatedLength) *Length {+ return self._base_val;+}++pub fn getAnimVal(self: *AnimatedLength) *Length {+ return self._anim_val;+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(AnimatedLength);++ pub const Meta = struct {+ pub const name = "SVGAnimatedLength";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const baseVal = bridge.accessor(AnimatedLength.getBaseVal, null, .{});+ pub const animVal = bridge.accessor(AnimatedLength.getAnimVal, null, .{});+};diff --git a/src/browser/webapi/svg/AnimatedPreserveAspectRatio.zig b/src/browser/webapi/svg/AnimatedPreserveAspectRatio.zignew file mode 100644index 000000000..2fcefcea9--- /dev/null+++ b/src/browser/webapi/svg/AnimatedPreserveAspectRatio.zig@@ -0,0 +1,70 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");++const js = @import("../../js/js.zig");+const Frame = @import("../../Frame.zig");+const Element = @import("../Element.zig");+const PreserveAspectRatio = @import("PreserveAspectRatio.zig");++const AnimatedPreserveAspectRatio = @This();++_base_val: *PreserveAspectRatio,+_anim_val: *PreserveAspectRatio,++pub const Lookup = std.AutoHashMapUnmanaged(*Element, *AnimatedPreserveAspectRatio);++pub fn getOrCreate(element: *Element, frame: *Frame) !*AnimatedPreserveAspectRatio {+ const gop = try frame._svg_animated_preserve_aspect_ratios.getOrPut(frame.arena, element);+ if (!gop.found_existing) {+ errdefer _ = frame._svg_animated_preserve_aspect_ratios.remove(element);+ gop.value_ptr.* = try create(element, frame);+ }+ return gop.value_ptr.*;+}++pub fn create(element: *Element, frame: *Frame) !*AnimatedPreserveAspectRatio {+ const base_val = try PreserveAspectRatio.create(element, false, frame);+ const anim_val = try PreserveAspectRatio.create(element, true, frame);+ return frame._factory.create(AnimatedPreserveAspectRatio{+ ._base_val = base_val,+ ._anim_val = anim_val,+ });+}++pub fn getBaseVal(self: *AnimatedPreserveAspectRatio) *PreserveAspectRatio {+ return self._base_val;+}++pub fn getAnimVal(self: *AnimatedPreserveAspectRatio) *PreserveAspectRatio {+ return self._anim_val;+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(AnimatedPreserveAspectRatio);++ pub const Meta = struct {+ pub const name = "SVGAnimatedPreserveAspectRatio";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const baseVal = bridge.accessor(AnimatedPreserveAspectRatio.getBaseVal, null, .{});+ pub const animVal = bridge.accessor(AnimatedPreserveAspectRatio.getAnimVal, null, .{});+};diff --git a/src/browser/webapi/svg/AnimatedString.zig b/src/browser/webapi/svg/AnimatedString.zigindex 0f3d6cc5f..d53de59bc 100644--- a/src/browser/webapi/svg/AnimatedString.zig+++ b/src/browser/webapi/svg/AnimatedString.zig@@ -40,8 +40,10 @@ pub const Key = struct {// Identity map for AnimatedString, help by the framepub fn getOrCreate(element: *Element, kind: Kind, frame: *Frame) !*AnimatedString {- const gop = try frame._svg_animated_strings.getOrPut(frame.arena, .{ .element = element, .kind = kind });+ const key: Key = .{ .element = element, .kind = kind };+ const gop = try frame._svg_animated_strings.getOrPut(frame.arena, key);if (!gop.found_existing) {+ errdefer _ = frame._svg_animated_strings.remove(key);gop.value_ptr.* = try frame._factory.create(AnimatedString{._element = element,._kind = kind,diff --git a/src/browser/webapi/svg/Length.zig b/src/browser/webapi/svg/Length.zignew file mode 100644index 000000000..45a81ddbb--- /dev/null+++ b/src/browser/webapi/svg/Length.zig@@ -0,0 +1,425 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");+const lp = @import("lightpanda");++const js = @import("../../js/js.zig");+const Frame = @import("../../Frame.zig");+const Element = @import("../Element.zig");++const String = lp.String;+const Length = @This();++_value: f64 = 0,+_unit: Unit = .number,+_element: ?*Element = null,+_attr_name: String = .empty,+_direction: Direction = .unspecified,+_read_only: bool = false,++pub const Direction = enum {+ horizontal,+ vertical,+ unspecified,+};++const Unit = enum(u16) {+ unknown = 0,+ number = 1,+ percentage = 2,+ em = 3,+ ex = 4,+ px = 5,+ cm = 6,+ mm = 7,+ in = 8,+ pt = 9,+ pc = 10,+};++const MAX_ANCESTOR_DEPTH = 32;++pub fn detached(frame: *Frame) !*Length {+ return frame._factory.create(Length{});+}++pub fn reflected(element: *Element, attr_name: String, direction: Direction, read_only: bool, frame: *Frame) !*Length {+ return frame._factory.create(Length{+ ._element = element,+ ._attr_name = attr_name,+ ._direction = direction,+ ._read_only = read_only,+ });+}++pub fn getUnitType(self: *Length) u16 {+ self.syncFromAttribute();+ return @intFromEnum(self._unit);+}++pub fn getValue(self: *Length, frame: *Frame) f64 {+ self.syncFromAttribute();+ return self._value * self.unitToUserUnits(self._unit, frame);+}++pub fn setValue(self: *Length, value: f64, frame: *Frame) !void {+ try self.ensureWritable();+ try ensureFinite(value);+ self._value = value;+ self._unit = .number;+ try self.writeBack(frame);+}++pub fn getValueInSpecifiedUnits(self: *Length) f64 {+ self.syncFromAttribute();+ return self._value;+}++pub fn setValueInSpecifiedUnits(self: *Length, value: f64, frame: *Frame) !void {+ try self.ensureWritable();+ try ensureFinite(value);+ self.syncFromAttribute();+ if (self._unit == .unknown) {+ self._unit = .number;+ }+ self._value = value;+ try self.writeBack(frame);+}++pub fn getValueAsString(self: *Length, frame: *Frame) ![]const u8 {+ self.syncFromAttribute();+ return self.serialize(frame);+}++pub fn setValueAsString(self: *Length, value: String, frame: *Frame) !void {+ try self.ensureWritable();+ const parsed = parse(value.str()) catch return error.SyntaxError;+ self._value = parsed.value;+ self._unit = parsed.unit;+ try self.writeBack(frame);+}++pub fn newValueSpecifiedUnits(self: *Length, unit_type: u16, value: f64, frame: *Frame) !void {+ try self.ensureWritable();+ const unit = try checkedUnit(unit_type);+ try ensureFinite(value);+ self._unit = unit;+ self._value = value;+ try self.writeBack(frame);+}++pub fn convertToSpecifiedUnits(self: *Length, unit_type: u16, frame: *Frame) !void {+ try self.ensureWritable();+ const target = try checkedUnit(unit_type);+ const absolute = self.getValue(frame);+ const factor = self.unitToUserUnits(target, frame);+ self._unit = target;+ self._value = if (factor == 0) 0 else absolute / factor;+ try self.writeBack(frame);+}++fn ensureWritable(self: *const Length) !void {+ if (self._read_only) {+ return error.NoModificationAllowed;+ }+}++fn ensureFinite(value: f64) !void {+ if (!std.math.isFinite(value)) {+ return error.TypeError;+ }+}++fn syncFromAttribute(self: *Length) void {+ const element = self._element orelse return;+ const raw = element.getAttributeSafe(self._attr_name) orelse {+ self._value = 0;+ self._unit = .number;+ return;+ };+ const parsed = parse(raw) catch {+ self._value = 0;+ self._unit = .unknown;+ return;+ };+ self._value = parsed.value;+ self._unit = parsed.unit;+}++fn writeBack(self: *Length, frame: *Frame) !void {+ const element = self._element orelse return;+ const value = try self.serialize(frame);+ try element.setAttributeSafe(self._attr_name, .wrap(value), frame);+}++fn serialize(self: *const Length, frame: *Frame) ![]const u8 {+ return std.fmt.allocPrint(frame.local_arena, "{d}{s}", .{ self._value, unitSuffix(self._unit) });+}++fn unitToUserUnits(self: *const Length, unit: Unit, frame: *Frame) f64 {+ if (absoluteUnitFactor(unit)) |factor| {+ return factor;+ }+ return switch (unit) {+ .unknown => 1,+ .percentage => self.percentageBasis(frame) / 100.0,+ .em => self.fontSize(frame),+ // Lightpanda does not load font metrics for DOM-only SVG values. CSS+ // defines 0.5em as the fallback when the x-height is unavailable.+ .ex => self.fontSize(frame) / 2.0,+ else => unreachable,+ };+}++fn percentageBasis(self: *const Length, frame: *Frame) f64 {+ const element = self._element orelse return 100;++ return switch (self._direction) {+ .horizontal => ancestorViewportDimension(element, .horizontal, frame),+ .vertical => ancestorViewportDimension(element, .vertical, frame),+ .unspecified => blk: {+ const width = ancestorViewportDimension(element, .horizontal, frame);+ const height = ancestorViewportDimension(element, .vertical, frame);+ break :blk @sqrt((width * width + height * height) / 2.0);+ },+ };+}++fn ancestorViewportDimension(element: *Element, direction: Direction, frame: *Frame) f64 {+ return ancestorViewportDimensionAt(element, direction, frame, 0);+}++fn ancestorViewportDimensionAt(element: *Element, direction: Direction, frame: *Frame, depth: u8) f64 {+ if (depth >= MAX_ANCESTOR_DEPTH) {+ return pageViewportDimension(direction, frame);+ }+ const viewport_element = nearestSvgViewport(element) orelse return pageViewportDimension(direction, frame);+ const attr_name: String = switch (direction) {+ .horizontal => comptime .wrap("width"),+ .vertical => comptime .wrap("height"),+ .unspecified => unreachable,+ };++ const raw = viewport_element.getAttributeSafe(attr_name) orelse {+ // SVG2 treats an omitted nested width/height as auto, whose used value+ // is 100% of the containing SVG viewport.+ return ancestorViewportDimensionAt(viewport_element, direction, frame, depth + 1);+ };+ const parsed = parse(raw) catch return ancestorViewportDimensionAt(viewport_element, direction, frame, depth + 1);+ return resolveParsedLength(parsed, viewport_element, direction, frame, depth + 1);+}++fn nearestSvgViewport(element: *Element) ?*Element {+ var current = element.parentElement();+ while (current) |parent| : (current = parent.parentElement()) {+ if (parent._namespace != .svg) return null;+ if (std.mem.eql(u8, parent.getTagNameLower(), "svg")) return parent;+ }+ return null;+}++fn pageViewportDimension(direction: Direction, frame: *Frame) f64 {+ const viewport = frame._page.getViewport();+ return switch (direction) {+ .horizontal => @floatFromInt(viewport.width),+ .vertical => @floatFromInt(viewport.height),+ .unspecified => unreachable,+ };+}++fn resolveParsedLength(parsed: Parsed, element: *Element, direction: Direction, frame: *Frame, depth: u8) f64 {+ const factor = absoluteUnitFactor(parsed.unit) orelse switch (parsed.unit) {+ .unknown => 1,+ .percentage => ancestorViewportDimensionAt(element, direction, frame, depth) / 100.0,+ .em => resolvedFontSizeAt(element, frame, depth),+ .ex => resolvedFontSizeAt(element, frame, depth) / 2.0,+ else => unreachable,+ };+ return parsed.value * factor;+}++fn fontSize(self: *const Length, frame: *Frame) f64 {+ return resolvedFontSize(self._element, frame);+}++// The style engine currently exposes inline declarations but does not compute+// stylesheet font inheritance. Resolve the sources it can represent exactly,+// then fall back to CSS's initial medium size (16px).+fn resolvedFontSize(element: ?*Element, frame: *Frame) f64 {+ return resolvedFontSizeAt(element, frame, 0);+}++fn resolvedFontSizeAt(element: ?*Element, frame: *Frame, depth: u8) f64 {+ if (depth >= MAX_ANCESTOR_DEPTH) {+ return 16;+ }+ const current = element orelse return 16;+ const parent = current.parentElement();++ if (frame._style_manager.inlineStyleValue(current, comptime .wrap("font-size"))) |raw| {+ if (parseFontSize(raw, parent, frame, depth + 1)) |size| {+ return size;+ }+ }+ if (current.getAttributeSafe(comptime .wrap("font-size"))) |raw| {+ if (parseFontSize(raw, parent, frame, depth + 1)) |size| {+ return size;+ }+ }+ return resolvedFontSizeAt(parent, frame, depth + 1);+}++fn parseFontSize(raw: []const u8, parent: ?*Element, frame: *Frame, depth: u8) ?f64 {+ const value = std.mem.trim(u8, raw, " \t\r\n\x0c");+ if (std.ascii.eqlIgnoreCase(value, "inherit") or std.ascii.eqlIgnoreCase(value, "unset")) {+ return resolvedFontSizeAt(parent, frame, depth);+ }+ if (std.ascii.eqlIgnoreCase(value, "initial") or std.ascii.eqlIgnoreCase(value, "medium")) {+ return 16;+ }++ const parsed = parse(value) catch return null;+ const parent_size = resolvedFontSizeAt(parent, frame, depth);+ const factor = absoluteUnitFactor(parsed.unit) orelse switch (parsed.unit) {+ .unknown => return null,+ .percentage => parent_size / 100.0,+ .em => parent_size,+ .ex => parent_size / 2.0,+ else => unreachable,+ };+ return parsed.value * factor;+}++fn absoluteUnitFactor(unit: Unit) ?f64 {+ return switch (unit) {+ .number, .px => 1,+ .cm => 96.0 / 2.54,+ .mm => 96.0 / 25.4,+ .in => 96,+ .pt => 96.0 / 72.0,+ .pc => 16,+ .unknown, .percentage, .em, .ex => null,+ };+}++const Parsed = struct {+ value: f64,+ unit: Unit,+};++fn parse(input: []const u8) !Parsed {+ const value = std.mem.trim(u8, input, " \t\r\n\x0c");+ if (value.len == 0) {+ return error.SyntaxError;+ }++ const suffixes = [_]struct { []const u8, Unit }{+ .{ "%", .percentage },+ .{ "em", .em },+ .{ "ex", .ex },+ .{ "px", .px },+ .{ "cm", .cm },+ .{ "mm", .mm },+ .{ "in", .in },+ .{ "pt", .pt },+ .{ "pc", .pc },+ };++ for (suffixes) |entry| {+ const suffix, const unit = entry;+ if (value.len <= suffix.len) {+ continue;+ }+ if (!std.ascii.eqlIgnoreCase(value[value.len - suffix.len ..], suffix)) {+ continue;+ }+ const number = std.mem.trim(u8, value[0 .. value.len - suffix.len], " \t\r\n\x0c");+ return .{ .value = try parseNumber(number), .unit = unit };+ }++ return .{ .value = try parseNumber(value), .unit = .number };+}++fn parseNumber(value: []const u8) !f64 {+ const number = std.fmt.parseFloat(f64, value) catch return error.SyntaxError;+ if (!std.math.isFinite(number)) {+ return error.SyntaxError;+ }+ return number;+}++fn checkedUnit(value: u16) !Unit {+ return switch (value) {+ 1 => .number,+ 2 => .percentage,+ 3 => .em,+ 4 => .ex,+ 5 => .px,+ 6 => .cm,+ 7 => .mm,+ 8 => .in,+ 9 => .pt,+ 10 => .pc,+ else => error.NotSupported,+ };+}++fn unitSuffix(unit: Unit) []const u8 {+ return switch (unit) {+ .unknown, .number => "",+ .percentage => "%",+ .em => "em",+ .ex => "ex",+ .px => "px",+ .cm => "cm",+ .mm => "mm",+ .in => "in",+ .pt => "pt",+ .pc => "pc",+ };+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(Length);++ pub const Meta = struct {+ pub const name = "SVGLength";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const SVG_LENGTHTYPE_UNKNOWN = bridge.property(0, .{ .template = true });+ pub const SVG_LENGTHTYPE_NUMBER = bridge.property(1, .{ .template = true });+ pub const SVG_LENGTHTYPE_PERCENTAGE = bridge.property(2, .{ .template = true });+ pub const SVG_LENGTHTYPE_EMS = bridge.property(3, .{ .template = true });+ pub const SVG_LENGTHTYPE_EXS = bridge.property(4, .{ .template = true });+ pub const SVG_LENGTHTYPE_PX = bridge.property(5, .{ .template = true });+ pub const SVG_LENGTHTYPE_CM = bridge.property(6, .{ .template = true });+ pub const SVG_LENGTHTYPE_MM = bridge.property(7, .{ .template = true });+ pub const SVG_LENGTHTYPE_IN = bridge.property(8, .{ .template = true });+ pub const SVG_LENGTHTYPE_PT = bridge.property(9, .{ .template = true });+ pub const SVG_LENGTHTYPE_PC = bridge.property(10, .{ .template = true });++ pub const unitType = bridge.accessor(Length.getUnitType, null, .{});+ pub const value = bridge.accessor(Length.getValue, Length.setValue, .{});+ pub const valueInSpecifiedUnits = bridge.accessor(Length.getValueInSpecifiedUnits, Length.setValueInSpecifiedUnits, .{});+ pub const valueAsString = bridge.accessor(Length.getValueAsString, Length.setValueAsString, .{});+ pub const newValueSpecifiedUnits = bridge.function(Length.newValueSpecifiedUnits, .{});+ pub const convertToSpecifiedUnits = bridge.function(Length.convertToSpecifiedUnits, .{});+};diff --git a/src/browser/webapi/svg/PreserveAspectRatio.zig b/src/browser/webapi/svg/PreserveAspectRatio.zignew file mode 100644index 000000000..4a07a2c10--- /dev/null+++ b/src/browser/webapi/svg/PreserveAspectRatio.zig@@ -0,0 +1,161 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");+const lp = @import("lightpanda");++const js = @import("../../js/js.zig");+const Frame = @import("../../Frame.zig");+const Element = @import("../Element.zig");++const String = lp.String;+const PreserveAspectRatio = @This();++_element: *Element,+_read_only: bool = false,++const Value = struct {+ alignment: u16 = 6,+ meet_or_slice: u16 = 1,+};++pub fn create(element: *Element, read_only: bool, frame: *Frame) !*PreserveAspectRatio {+ return frame._factory.create(PreserveAspectRatio{+ ._element = element,+ ._read_only = read_only,+ });+}++pub fn getAlign(self: *const PreserveAspectRatio) u16 {+ return self.current().alignment;+}++pub fn setAlign(self: *PreserveAspectRatio, alignment: u16, frame: *Frame) !void {+ try self.ensureWritable();+ if (alignName(alignment) == null) return error.TypeError;+ var value = self.current();+ value.alignment = alignment;+ try self.write(value, frame);+}++pub fn getMeetOrSlice(self: *const PreserveAspectRatio) u16 {+ return self.current().meet_or_slice;+}++pub fn setMeetOrSlice(self: *PreserveAspectRatio, meet_or_slice: u16, frame: *Frame) !void {+ try self.ensureWritable();+ if (meetOrSliceName(meet_or_slice) == null) return error.TypeError;+ var value = self.current();+ value.meet_or_slice = meet_or_slice;+ try self.write(value, frame);+}++fn ensureWritable(self: *const PreserveAspectRatio) !void {+ if (self._read_only) {+ return error.NoModificationAllowed;+ }+}++fn current(self: *const PreserveAspectRatio) Value {+ const raw = self._element.getAttributeSafe(String.wrap("preserveAspectRatio")) orelse return .{};+ var parts = std.mem.tokenizeAny(u8, raw, " \t\r\n\x0c");+ const alignment = alignValue(parts.next() orelse return .{}) orelse return .{};+ const meet_or_slice = meetOrSliceValue(parts.next() orelse "meet") orelse return .{};+ if (parts.next() != null) {+ return .{};+ }+ return .{ .alignment = alignment, .meet_or_slice = meet_or_slice };+}++fn write(self: *PreserveAspectRatio, value: Value, frame: *Frame) !void {+ const alignment = alignName(value.alignment) orelse return error.TypeError;+ const meet_or_slice = meetOrSliceName(value.meet_or_slice) orelse return error.TypeError;+ const serialized = try std.fmt.allocPrint(frame.local_arena, "{s} {s}", .{ alignment, meet_or_slice });+ try self._element.setAttributeSafe(String.wrap("preserveAspectRatio"), .wrap(serialized), frame);+}++fn alignName(value: u16) ?[]const u8 {+ return switch (value) {+ 1 => "none",+ 2 => "xMinYMin",+ 3 => "xMidYMin",+ 4 => "xMaxYMin",+ 5 => "xMinYMid",+ 6 => "xMidYMid",+ 7 => "xMaxYMid",+ 8 => "xMinYMax",+ 9 => "xMidYMax",+ 10 => "xMaxYMax",+ else => null,+ };+}++fn alignValue(value: []const u8) ?u16 {+ inline for (1..11) |i| {+ if (std.mem.eql(u8, value, alignName(i).?)) {+ return i;+ }+ }+ return null;+}++fn meetOrSliceName(value: u16) ?[]const u8 {+ return switch (value) {+ 1 => "meet",+ 2 => "slice",+ else => null,+ };+}++fn meetOrSliceValue(value: []const u8) ?u16 {+ if (std.mem.eql(u8, value, "meet")) {+ return 1;+ }+ if (std.mem.eql(u8, value, "slice")) {+ return 2;+ }+ return null;+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(PreserveAspectRatio);++ pub const Meta = struct {+ pub const name = "SVGPreserveAspectRatio";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const SVG_PRESERVEASPECTRATIO_UNKNOWN = bridge.property(0, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_NONE = bridge.property(1, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_XMINYMIN = bridge.property(2, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_XMIDYMIN = bridge.property(3, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_XMAXYMIN = bridge.property(4, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_XMINYMID = bridge.property(5, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_XMIDYMID = bridge.property(6, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_XMAXYMID = bridge.property(7, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_XMINYMAX = bridge.property(8, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_XMIDYMAX = bridge.property(9, .{ .template = true });+ pub const SVG_PRESERVEASPECTRATIO_XMAXYMAX = bridge.property(10, .{ .template = true });+ pub const SVG_MEETORSLICE_UNKNOWN = bridge.property(0, .{ .template = true });+ pub const SVG_MEETORSLICE_MEET = bridge.property(1, .{ .template = true });+ pub const SVG_MEETORSLICE_SLICE = bridge.property(2, .{ .template = true });++ pub const @"align" = bridge.accessor(PreserveAspectRatio.getAlign, PreserveAspectRatio.setAlign, .{});+ pub const meetOrSlice = bridge.accessor(PreserveAspectRatio.getMeetOrSlice, PreserveAspectRatio.setMeetOrSlice, .{});+};diff --git a/src/browser/webapi/svg/Transform.zig b/src/browser/webapi/svg/Transform.zignew file mode 100644index 000000000..fe6c09e30--- /dev/null+++ b/src/browser/webapi/svg/Transform.zig@@ -0,0 +1,183 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");++const js = @import("../../js/js.zig");+const Frame = @import("../../Frame.zig");+const Page = @import("../../Page.zig");+const DOMMatrix = @import("../DOMMatrix.zig");+const RO = @import("../DOMMatrixReadOnly.zig");++const Transform = @This();++pub const DOMMatrix2DInit = struct {+ a: ?f64 = null,+ b: ?f64 = null,+ c: ?f64 = null,+ d: ?f64 = null,+ e: ?f64 = null,+ f: ?f64 = null,+ m11: ?f64 = null,+ m12: ?f64 = null,+ m21: ?f64 = null,+ m22: ?f64 = null,+ m41: ?f64 = null,+ m42: ?f64 = null,+};++_type: u16 = 1,+_angle: f64 = 0,+_matrix: *DOMMatrix,++// The transform owns the matrix arena even when no JS wrapper currently+// references `matrix`. Forwarding the transform's bridge lifetime keeps the+// stable SameObject pointer valid across garbage collections.+pub fn acquireRef(self: *Transform) void {+ self._matrix._proto.acquireRef();+}++pub fn releaseRef(self: *Transform, page: *Page) void {+ self._matrix._proto.releaseRef(page);+}++pub fn detached(frame: *Frame) !*Transform {+ const matrix = try DOMMatrix.create(RO.identity(), true, frame._page);+ return frame._factory.create(Transform{ ._matrix = matrix });+}++pub fn fromMatrix(init: ?DOMMatrix2DInit, frame: *Frame) !*Transform {+ const parsed = try fixup2D(init orelse .{});+ const matrix = try DOMMatrix.create(parsed.m, true, frame._page);+ return frame._factory.create(Transform{ ._matrix = matrix });+}++pub fn getType(self: *const Transform) u16 {+ return self._type;+}++pub fn getMatrix(self: *Transform) *DOMMatrix {+ return self._matrix;+}++pub fn getAngle(self: *const Transform) f64 {+ return self._angle;+}++pub fn setMatrix(self: *Transform, init: ?DOMMatrix2DInit) !void {+ const parsed = try fixup2D(init orelse .{});+ self.replaceMatrix(parsed.m, true);+ self._type = 1;+ self._angle = 0;+}++pub fn setTranslate(self: *Transform, tx: f64, ty: f64) !void {+ try ensureFinite(&.{ tx, ty });+ self.replaceMatrix(RO.translationMatrix(tx, ty, 0), true);+ self._type = 2;+ self._angle = 0;+}++pub fn setScale(self: *Transform, sx: f64, sy: f64) !void {+ try ensureFinite(&.{ sx, sy });+ self.replaceMatrix(RO.scaleMatrix(sx, sy, 1), true);+ self._type = 3;+ self._angle = 0;+}++pub fn setRotate(self: *Transform, angle: f64, cx: f64, cy: f64) !void {+ try ensureFinite(&.{ angle, cx, cy });+ const radians = angle * std.math.pi / 180.0;+ var matrix = RO.translationMatrix(cx, cy, 0);+ matrix = RO.multiplyMatrix(matrix, RO.rotateZMatrix(radians));+ matrix = RO.multiplyMatrix(matrix, RO.translationMatrix(-cx, -cy, 0));+ self.replaceMatrix(matrix, true);+ self._type = 4;+ self._angle = angle;+}++pub fn setSkewX(self: *Transform, angle: f64) !void {+ try ensureFinite(&.{angle});+ self.replaceMatrix(RO.skewMatrix(angle * std.math.pi / 180.0, 0), true);+ self._type = 5;+ self._angle = angle;+}++pub fn setSkewY(self: *Transform, angle: f64) !void {+ try ensureFinite(&.{angle});+ self.replaceMatrix(RO.skewMatrix(0, angle * std.math.pi / 180.0), true);+ self._type = 6;+ self._angle = angle;+}++fn replaceMatrix(self: *Transform, matrix: [16]f64, is_2d: bool) void {+ self._matrix._proto._m = matrix;+ self._matrix._proto._is_2d = is_2d;+}++fn fixup2D(init: DOMMatrix2DInit) !RO.Parsed {+ return RO.fixupDict(.{+ .a = init.a,+ .b = init.b,+ .c = init.c,+ .d = init.d,+ .e = init.e,+ .f = init.f,+ .m11 = init.m11,+ .m12 = init.m12,+ .m21 = init.m21,+ .m22 = init.m22,+ .m41 = init.m41,+ .m42 = init.m42,+ .is2D = true,+ });+}++fn ensureFinite(values: []const f64) !void {+ for (values) |value| {+ if (!std.math.isFinite(value)) return error.TypeError;+ }+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(Transform);++ pub const Meta = struct {+ pub const name = "SVGTransform";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const SVG_TRANSFORM_UNKNOWN = bridge.property(0, .{ .template = true });+ pub const SVG_TRANSFORM_MATRIX = bridge.property(1, .{ .template = true });+ pub const SVG_TRANSFORM_TRANSLATE = bridge.property(2, .{ .template = true });+ pub const SVG_TRANSFORM_SCALE = bridge.property(3, .{ .template = true });+ pub const SVG_TRANSFORM_ROTATE = bridge.property(4, .{ .template = true });+ pub const SVG_TRANSFORM_SKEWX = bridge.property(5, .{ .template = true });+ pub const SVG_TRANSFORM_SKEWY = bridge.property(6, .{ .template = true });++ pub const @"type" = bridge.accessor(Transform.getType, null, .{});+ pub const matrix = bridge.accessor(Transform.getMatrix, null, .{});+ pub const angle = bridge.accessor(Transform.getAngle, null, .{});+ pub const setMatrix = bridge.function(Transform.setMatrix, .{});+ pub const setTranslate = bridge.function(Transform.setTranslate, .{});+ pub const setScale = bridge.function(Transform.setScale, .{});+ pub const setRotate = bridge.function(Transform.setRotate, .{});+ pub const setSkewX = bridge.function(Transform.setSkewX, .{});+ pub const setSkewY = bridge.function(Transform.setSkewY, .{});+};