Skip to content

Lightpanda: the headless browser designed for AI and automation

chore: dedupe unit parsing found in CSS and SVG

Karl Seguin2781ce174ede
diff --git a/src/browser/StyleManager.zig b/src/browser/StyleManager.zig
index 0001991dc..25ad4f29e 100644
--- a/src/browser/StyleManager.zig
+++ b/src/browser/StyleManager.zig
@@ -22,6 +22,7 @@ const lp = @import("lightpanda");
const Frame = @import("Frame.zig");
+const units = @import("css/units.zig");
const CssParser = @import("css/Parser.zig");
const MediaQuery = @import("css/MediaQuery.zig");
const Element = @import("webapi/Element.zig");
@@ -1214,6 +1215,56 @@ pub fn inlineStyleValue(self: *StyleManager, el: *Element, property_name: String
return property._value.str();
}
+/// Bounds computedFontSize's ancestor recursion (the parent walk and
+/// `inherit`/relative-unit chains share it).
+const MAX_FONT_ANCESTOR_DEPTH = 32;
+
+/// 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 {
+ return self.computedFontSizeAt(element, 0);
+}
+
+fn computedFontSizeAt(self: *StyleManager, element: ?*Element, depth: u8) f64 {
+ if (depth >= MAX_FONT_ANCESTOR_DEPTH) {
+ return 16;
+ }
+ const current = element orelse return 16;
+ const parent = current.parentElement();
+
+ if (self.inlineStyleValue(current, comptime .wrap("font-size"))) |raw| {
+ if (self.parseFontSize(raw, parent, depth + 1)) |size| {
+ return size;
+ }
+ }
+ if (current.getAttributeSafe(comptime .wrap("font-size"))) |raw| {
+ if (self.parseFontSize(raw, parent, depth + 1)) |size| {
+ return size;
+ }
+ }
+ return self.computedFontSizeAt(parent, depth + 1);
+}
+
+fn parseFontSize(self: *StyleManager, raw: []const u8, parent: ?*Element, 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 self.computedFontSizeAt(parent, depth);
+ }
+ if (std.ascii.eqlIgnoreCase(value, "initial") or std.ascii.eqlIgnoreCase(value, "medium")) {
+ return 16;
+ }
+
+ const parsed = units.parse(value) catch return null;
+ const factor = units.absoluteLengthFactor(parsed.unit) orelse switch (parsed.unit) {
+ .percentage => self.computedFontSizeAt(parent, depth) / 100.0,
+ .em => self.computedFontSizeAt(parent, depth),
+ .ex => self.computedFontSizeAt(parent, depth) / 2.0,
+ else => return null,
+ };
+ const size = parsed.value * factor;
+ return if (size >= 0 and std.math.isFinite(size)) size else null;
+}
+
const testing = @import("../testing.zig");
test "StyleManager: computeSpecificity: element selector" {
// div -> (0, 0, 1)
diff --git a/src/browser/css/units.zig b/src/browser/css/units.zig
new file mode 100644
index 000000000..a87cffdb9
--- /dev/null
+++ b/src/browser/css/units.zig
@@ -0,0 +1,168 @@
+// 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/>.
+
+//! Shared lexing and conversion for CSS/SVG dimension values: one suffix
+//! table and one set of absolute-length factors. Consumers (svg/Length,
+//! svg/Angle, webapi/CSS, StyleManager's font-size resolution) map the
+//! result onto their own domain, rejecting units that don't apply.
+//!
+//! css/MediaQuery keeps its own parser on purpose: MQ4 is fail-closed and
+//! deliberately more restrictive than this lenient attribute-value lexer.
+
+const std = @import("std");
+
+pub const Unit = enum {
+ none, // bare number, no suffix
+ percentage,
+ em,
+ ex,
+ px,
+ cm,
+ mm,
+ in,
+ pt,
+ pc,
+ vh,
+ vw,
+ deg,
+ rad,
+ grad,
+ turn,
+};
+
+pub const Parsed = struct {
+ value: f64,
+ unit: Unit,
+};
+
+const WHITESPACE = " \t\r\n\x0c";
+
+// Longer suffixes first: "5grad" must not match the "rad" entry.
+const suffixes = [_]struct { []const u8, Unit }{
+ .{ "turn", .turn },
+ .{ "grad", .grad },
+ .{ "deg", .deg },
+ .{ "rad", .rad },
+ .{ "%", .percentage },
+ .{ "em", .em },
+ .{ "ex", .ex },
+ .{ "px", .px },
+ .{ "cm", .cm },
+ .{ "mm", .mm },
+ .{ "in", .in },
+ .{ "pt", .pt },
+ .{ "pc", .pc },
+ .{ "vh", .vh },
+ .{ "vw", .vw },
+};
+
+pub fn parse(input: []const u8) error{SyntaxError}!Parsed {
+ const value = std.mem.trim(u8, input, WHITESPACE);
+ if (value.len == 0) {
+ return error.SyntaxError;
+ }
+
+ for (suffixes) |entry| {
+ const sfx, const unit = entry;
+ if (value.len <= sfx.len) {
+ continue;
+ }
+ if (!std.ascii.eqlIgnoreCase(value[value.len - sfx.len ..], sfx)) {
+ continue;
+ }
+ const number = std.mem.trim(u8, value[0 .. value.len - sfx.len], WHITESPACE);
+ return .{ .value = try parseNumber(number), .unit = unit };
+ }
+ return .{ .value = try parseNumber(value), .unit = .none };
+}
+
+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;
+}
+
+/// CSS pixels per unit for the absolute length units (CSS Values §6.2,
+/// 96px per inch). Null for relative and angle units, which need context.
+pub fn absoluteLengthFactor(unit: Unit) ?f64 {
+ return switch (unit) {
+ .none, .px => 1,
+ .cm => 96.0 / 2.54,
+ .mm => 96.0 / 25.4,
+ .in => 96,
+ .pt => 96.0 / 72.0,
+ .pc => 16,
+ else => null,
+ };
+}
+
+pub fn suffix(unit: Unit) []const u8 {
+ return switch (unit) {
+ .none => "",
+ .percentage => "%",
+ else => @tagName(unit),
+ };
+}
+
+const testing = @import("../../testing.zig");
+
+test "css units: parse" {
+ try testing.expectEqual(Parsed{ .value = 12, .unit = .none }, try parse("12"));
+ try testing.expectEqual(Parsed{ .value = -3.5, .unit = .px }, try parse("-3.5px"));
+ try testing.expectEqual(Parsed{ .value = 50, .unit = .percentage }, try parse("50%"));
+ try testing.expectEqual(Parsed{ .value = 2.54, .unit = .cm }, try parse("2.54cm"));
+ try testing.expectEqual(Parsed{ .value = 1.5, .unit = .em }, try parse("1.5EM"));
+ try testing.expectEqual(Parsed{ .value = 90, .unit = .deg }, try parse("90deg"));
+ try testing.expectEqual(Parsed{ .value = 100, .unit = .grad }, try parse("100grad"));
+ try testing.expectEqual(Parsed{ .value = 0.5, .unit = .turn }, try parse("0.5turn"));
+ try testing.expectEqual(Parsed{ .value = 50, .unit = .vh }, try parse("50vh"));
+
+ // surrounding whitespace, and the historical leniency between number
+ // and suffix, are both accepted
+ try testing.expectEqual(Parsed{ .value = 10, .unit = .px }, try parse(" 10px "));
+ try testing.expectEqual(Parsed{ .value = 10, .unit = .px }, try parse("10 px"));
+
+ try testing.expectError(error.SyntaxError, parse(""));
+ try testing.expectError(error.SyntaxError, parse(" "));
+ try testing.expectError(error.SyntaxError, parse("px"));
+ try testing.expectError(error.SyntaxError, parse("abc"));
+ try testing.expectError(error.SyntaxError, parse("10furlong"));
+ try testing.expectError(error.SyntaxError, parse("inf"));
+ try testing.expectError(error.SyntaxError, parse("nan"));
+ try testing.expectError(error.SyntaxError, parse("infpx"));
+}
+
+test "css units: absoluteLengthFactor" {
+ try testing.expectEqual(1, absoluteLengthFactor(.none).?);
+ try testing.expectEqual(1, absoluteLengthFactor(.px).?);
+ try testing.expectEqual(96, absoluteLengthFactor(.in).?);
+ try testing.expectEqual(16, absoluteLengthFactor(.pc).?);
+ try testing.expectEqual(null, absoluteLengthFactor(.percentage));
+ try testing.expectEqual(null, absoluteLengthFactor(.em));
+ try testing.expectEqual(null, absoluteLengthFactor(.vh));
+ try testing.expectEqual(null, absoluteLengthFactor(.deg));
+}
+
+test "css units: suffix" {
+ try testing.expectEqual("", suffix(.none));
+ try testing.expectEqual("%", suffix(.percentage));
+ try testing.expectEqual("px", suffix(.px));
+ try testing.expectEqual("turn", suffix(.turn));
+}
diff --git a/src/browser/webapi/CSS.zig b/src/browser/webapi/CSS.zig
index 0df73dcad..d93970074 100644
--- a/src/browser/webapi/CSS.zig
+++ b/src/browser/webapi/CSS.zig
@@ -19,6 +19,7 @@
const std = @import("std");
const js = @import("../js/js.zig");
const Frame = @import("../Frame.zig");
+const units = @import("../css/units.zig");
const CSS = @This();
_pad: bool = false,
@@ -26,39 +27,23 @@ _pad: bool = false,
pub const init: CSS = .{};
pub fn parseDimension(value: []const u8) ?f64 {
- if (value.len == 0) {
- return null;
- }
- return parseNonEmptyDimension(value);
+ const parsed = units.parse(value) catch return null;
+ return switch (parsed.unit) {
+ .none, .px => parsed.value,
+ else => null,
+ };
}
// parseDimension plus viewport-relative units, which the faux layout
// resolves against the page viewport.
pub fn parseDimensionViewport(value: []const u8, frame: *Frame) ?f64 {
- if (value.len == 0) {
- return null;
- }
-
- if (std.mem.endsWith(u8, value, "vh")) {
- const n = std.fmt.parseFloat(f64, value[0 .. value.len - 2]) catch return null;
- return n * @as(f64, @floatFromInt(frame._page.getViewport().height)) / 100.0;
- }
-
- if (std.mem.endsWith(u8, value, "vw")) {
- const n = std.fmt.parseFloat(f64, value[0 .. value.len - 2]) catch return null;
- return n * @as(f64, @floatFromInt(frame._page.getViewport().width)) / 100.0;
- }
-
- return parseNonEmptyDimension(value);
-}
-
-fn parseNonEmptyDimension(value: []const u8) ?f64 {
- var num_str = value;
- if (std.mem.endsWith(u8, value, "px")) {
- num_str = value[0 .. value.len - 2];
- }
-
- return std.fmt.parseFloat(f64, num_str) catch null;
+ const parsed = units.parse(value) catch return null;
+ return switch (parsed.unit) {
+ .none, .px => parsed.value,
+ .vh => parsed.value * @as(f64, @floatFromInt(frame._page.getViewport().height)) / 100.0,
+ .vw => parsed.value * @as(f64, @floatFromInt(frame._page.getViewport().width)) / 100.0,
+ else => null,
+ };
}
/// Escapes a CSS identifier string
diff --git a/src/browser/webapi/element/svg/TextContent.zig b/src/browser/webapi/element/svg/TextContent.zig
index 57322d707..e78323730 100644
--- a/src/browser/webapi/element/svg/TextContent.zig
+++ b/src/browser/webapi/element/svg/TextContent.zig
@@ -25,7 +25,6 @@ const Element = @import("../../Element.zig");
const AnimatedEnumeration = @import("../../svg/AnimatedEnumeration.zig");
const AnimatedLength = @import("../../svg/AnimatedLength.zig");
-const Length = @import("../../svg/Length.zig");
const Graphics = @import("Graphics.zig");
@@ -63,7 +62,7 @@ fn text(self: *TextContent, frame: *Frame) []const u8 {
}
fn fontSize(self: *TextContent, frame: *Frame) f64 {
- return Length.fontSizeForElement(self.asElement(), frame);
+ return frame._style_manager.computedFontSize(self.asElement());
}
fn getTextLength(self: *TextContent, frame: *Frame) !*AnimatedLength {
diff --git a/src/browser/webapi/svg/Angle.zig b/src/browser/webapi/svg/Angle.zig
index 4cedaf54e..feeb8cd6c 100644
--- a/src/browser/webapi/svg/Angle.zig
+++ b/src/browser/webapi/svg/Angle.zig
@@ -22,6 +22,7 @@ const lp = @import("lightpanda");
const js = @import("../../js/js.zig");
const Frame = @import("../../Frame.zig");
const Page = @import("../../Page.zig");
+const units = @import("../../css/units.zig");
const Element = @import("../Element.zig");
const String = lp.String;
@@ -176,37 +177,16 @@ const Parsed = struct {
};
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 },
+ const parsed = try units.parse(input);
+ const unit: Unit = switch (parsed.unit) {
+ .none => .unspecified,
+ .deg => .deg,
+ .rad => .rad,
+ .grad => .grad,
+ .turn => .turn,
+ else => return error.SyntaxError,
};
- 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;
+ return .{ .value = parsed.value, .unit = unit };
}
fn checkedUnit(value: u16) !Unit {
diff --git a/src/browser/webapi/svg/Length.zig b/src/browser/webapi/svg/Length.zig
index ede68e82a..933de0cc7 100644
--- a/src/browser/webapi/svg/Length.zig
+++ b/src/browser/webapi/svg/Length.zig
@@ -22,6 +22,7 @@ const lp = @import("lightpanda");
const js = @import("../../js/js.zig");
const Frame = @import("../../Frame.zig");
const Page = @import("../../Page.zig");
+const units = @import("../../css/units.zig");
const Element = @import("../Element.zig");
const String = lp.String;
@@ -210,21 +211,17 @@ fn writeBack(self: *Length, frame: *Frame) !void {
}
fn serialize(self: *const Length, frame: *Frame) ![]const u8 {
- return std.fmt.allocPrint(frame.local_arena, "{d}{s}", .{ self._value, unitSuffix(self._unit) });
+ return std.fmt.allocPrint(frame.local_arena, "{d}{s}", .{ self._value, units.suffix(toShared(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,
+ else => units.absoluteLengthFactor(toShared(unit)).?,
};
}
@@ -285,83 +282,17 @@ fn pageViewportDimension(direction: Direction, frame: *Frame) f64 {
}
fn resolveParsedLength(parsed: Parsed, element: *Element, direction: Direction, frame: *Frame, depth: u8) f64 {
- const factor = absoluteUnitFactor(parsed.unit) orelse switch (parsed.unit) {
- .unknown => 1,
+ const factor = switch (parsed.unit) {
.percentage => ancestorViewportDimensionAt(element, direction, frame, depth) / 100.0,
- .em => resolvedFontSizeAt(element, frame, depth),
- .ex => resolvedFontSizeAt(element, frame, depth) / 2.0,
- else => unreachable,
+ .em => frame._style_manager.computedFontSize(element),
+ .ex => frame._style_manager.computedFontSize(element) / 2.0,
+ else => units.absoluteLengthFactor(toShared(parsed.unit)).?,
};
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);
-}
-
-pub fn fontSizeForElement(element: *Element, frame: *Frame) f64 {
- return resolvedFontSize(element, frame);
-}
-
-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,
- };
- const size = parsed.value * factor;
- return if (size >= 0 and std.math.isFinite(size)) size else null;
-}
-
-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,
- };
+ return frame._style_manager.computedFontSize(self._element);
}
const Parsed = struct {
@@ -370,44 +301,40 @@ const Parsed = struct {
};
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 parsed = try units.parse(input);
+ const unit = fromShared(parsed.unit) orelse return error.SyntaxError;
+ return .{ .value = parsed.value, .unit = unit };
+}
- const suffixes = [_]struct { []const u8, Unit }{
- .{ "%", .percentage },
- .{ "em", .em },
- .{ "ex", .ex },
- .{ "px", .px },
- .{ "cm", .cm },
- .{ "mm", .mm },
- .{ "in", .in },
- .{ "pt", .pt },
- .{ "pc", .pc },
+fn fromShared(unit: units.Unit) ?Unit {
+ return switch (unit) {
+ .none => .number,
+ .percentage => .percentage,
+ .em => .em,
+ .ex => .ex,
+ .px => .px,
+ .cm => .cm,
+ .mm => .mm,
+ .in => .in,
+ .pt => .pt,
+ .pc => .pc,
+ .vh, .vw, .deg, .rad, .grad, .turn => null,
};
-
- 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 toShared(unit: Unit) units.Unit {
+ return switch (unit) {
+ .unknown, .number => .none,
+ .percentage => .percentage,
+ .em => .em,
+ .ex => .ex,
+ .px => .px,
+ .cm => .cm,
+ .mm => .mm,
+ .in => .in,
+ .pt => .pt,
+ .pc => .pc,
+ };
}
fn checkedUnit(value: u16) !Unit {
@@ -426,21 +353,6 @@ fn checkedUnit(value: u16) !Unit {
};
}
-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);