Skip to content

Lightpanda: the headless browser designed for AI and automation

svg: implement getBBox

Karl Seguin689038e9be5a
diff --git a/src/browser/tests/element/svg/text.html b/src/browser/tests/element/svg/text.html
index e52e25569..120d396be 100644
--- a/src/browser/tests/element/svg/text.html
+++ b/src/browser/tests/element/svg/text.html
@@ -9,6 +9,21 @@
<text><textPath id=textPath href="#guide" startOffset="25%" method="stretch" spacing="auto">abc</textPath></text>
</svg>
+<svg>
+ <text id=plain x=10 y=50>hello</text>
+ <text id=spaced x=10 y=50>
+ hello
+ </text>
+ <text id=middle x=100 y=50 text-anchor=middle>hello</text>
+ <g text-anchor=end><text id=end x=100 y=50>hello</text></g>
+ <text id=moved x="10 30" y=50 dx=5 dy="3 9">hello</text>
+ <text id=displayNone x=10 y=50 style="display:none">hello</text>
+ <text id=invisible x=10 y=50 style="visibility:hidden">hello</text>
+ <text id=blank x=10 y=50> </text>
+ <text x=10 y=50>he<tspan id=span>llo</tspan></text>
+ <g id=group><text x=10 y=50 transform="translate(100,0)">hello</text></g>
+</svg>
+
<script id=textIdentities>
{
const text = $('#text');
@@ -52,10 +67,59 @@
// length; without shaping we default to 0.
testing.expectEqual(0, text.textLength.baseVal.value);
- // Browsers return the shaped text box here; our text geometry is
- // unmeasured, so like the other unresolved elements getBBox answers an
- // empty box rather than an error.
- testing.expectEqual(0, text.getBBox().width);
+ // The box spans the advance, 0.8em above the baseline to 0.2em below.
+ const box = text.getBBox();
+ testing.expectEqual(0, box.x);
+ testing.expectEqual(-16, box.y);
+ testing.expectEqual(80, box.width);
+ testing.expectEqual(20, box.height);
+}
+</script>
+
+<script id=textBoxGeometry>
+{
+ const near = (a, b) => Math.abs(a - b) < 1;
+ const plain = $('#plain').getBBox();
+ testing.expectEqual(10, plain.x);
+ testing.expectEqual(true, plain.width > 0);
+ testing.expectEqual(true, plain.y < 50 && plain.y + plain.height > 50);
+
+ // Whitespace collapses as rendered.
+ const spaced = $('#spaced').getBBox();
+ testing.expectEqual(5, $('#spaced').getNumberOfChars());
+ testing.expectEqual(plain.width, spaced.width);
+ testing.expectEqual(plain.y, spaced.y);
+
+ // text-anchor, inherited or not, moves the run back from x.
+ const middle = $('#middle').getBBox();
+ testing.expectEqual(true, near(100, middle.x + middle.width / 2));
+ const end = $('#end').getBBox();
+ testing.expectEqual(true, near(100, end.x + end.width));
+
+ // The first x/y and dx/dy entries place the first glyph.
+ const moved = $('#moved').getBBox();
+ testing.expectEqual(15, moved.x);
+ testing.expectEqual(plain.y + 3, moved.y);
+
+ // display:none has no box; visibility:hidden still does.
+ testing.expectEqual(0, $('#displayNone').getBBox().width);
+ testing.expectEqual(plain.width, $('#invisible').getBBox().width);
+ testing.expectEqual(0, $('#blank').getBBox().width);
+
+ // A <tspan> without its own position continues its <text>.
+ const span = $('#span').getBBox();
+ testing.expectEqual(true, span.x > 10);
+ testing.expectEqual(true, near(plain.x + plain.width, span.x + span.width));
+
+ // The text's own transform is excluded from its box but included in its
+ // parent's.
+ const group = $('#group').getBBox();
+ testing.expectEqual(110, group.x);
+ testing.expectEqual(plain.y, group.y);
+
+ const detached = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ detached.textContent = 'hello';
+ testing.expectEqual(0, detached.getBBox().width);
}
</script>
diff --git a/src/browser/text_measure.zig b/src/browser/text_measure.zig
index 6788fb9f4..e3da38249 100644
--- a/src/browser/text_measure.zig
+++ b/src/browser/text_measure.zig
@@ -66,6 +66,11 @@ pub fn substringWidth(text: []const u8, charnum: u32, nchars: u32, font_size: f6
/// Line height for `line-height: normal`, in em.
pub const LINE_HEIGHT = 1.2;
+/// Glyph extents above and below the baseline, in em, as in a generic
+/// sans-serif face.
+pub const ASCENT = 0.8;
+pub const DESCENT = 0.2;
+
pub const WhiteSpace = struct {
wrap: bool = true, // Lines break between words to fit.
collapse: bool = true, // run of spaces becomes one and is removed at edges
diff --git a/src/browser/webapi/canvas/TextMetrics.zig b/src/browser/webapi/canvas/TextMetrics.zig
index cee44ca1a..ff6214322 100644
--- a/src/browser/webapi/canvas/TextMetrics.zig
+++ b/src/browser/webapi/canvas/TextMetrics.zig
@@ -20,11 +20,11 @@ const lp = @import("lightpanda");
const js = @import("../../js/js.zig");
const Page = @import("../../Page.zig");
+const text_measure = @import("../../text_measure.zig");
const Execution = js.Execution;
-/// Metrics from the deterministic text model in text_measure.zig: ascent is
-/// 0.8em and descent 0.2em, as in a generic sans-serif face.
+/// Metrics from the deterministic text model in text_measure.zig.
const TextMetrics = @This();
_rc: lp.RC = .{},
@@ -35,8 +35,8 @@ _descent: f64,
pub fn init(width: f64, font_size: f64, exec: *const Execution) !*TextMetrics {
return exec._factory.create(TextMetrics{
._width = width,
- ._ascent = font_size * 0.8,
- ._descent = font_size * 0.2,
+ ._ascent = font_size * text_measure.ASCENT,
+ ._descent = font_size * text_measure.DESCENT,
});
}
diff --git a/src/browser/webapi/element/svg/Graphics.zig b/src/browser/webapi/element/svg/Graphics.zig
index 28f820602..25f8c3895 100644
--- a/src/browser/webapi/element/svg/Graphics.zig
+++ b/src/browser/webapi/element/svg/Graphics.zig
@@ -144,8 +144,9 @@ fn getBBox(self: *Graphics, frame: *Frame) !*DOMRect {
bounds = path.bounds(.{});
},
.foreign_object => bounds = try self.subtype(ForeignObject).getBounds(frame),
+ .text_content => bounds = self.subtype(TextContent).getBounds(frame),
.g, .a, .svg => try accumulateChildren(self, .{}, &bounds, frame),
- .defs, .symbol, .switch_element, .use, .image, .text_content => {},
+ .defs, .symbol, .switch_element, .use, .image => {},
}
if (bounds.isEmpty()) {
return DOMRect.create(.{}, frame._factory);
@@ -191,35 +192,31 @@ fn accumulateChildren(parent: *Graphics, matrix: PathData.Matrix, bounds: *PathD
defer path.deinit(frame.local_arena);
bounds.merge(path.bounds(child_matrix));
},
- .foreign_object => {
- const child_bounds = try graphics.subtype(ForeignObject).getBounds(frame);
- if (!child_bounds.isEmpty()) {
- var foreign_path: PathData.Path = .{};
- defer foreign_path.deinit(frame.local_arena);
- const top_left = PathData.Point{ .x = child_bounds.min_x, .y = child_bounds.min_y };
- const top_right = PathData.Point{ .x = child_bounds.max_x, .y = child_bounds.min_y };
- const bottom_right = PathData.Point{ .x = child_bounds.max_x, .y = child_bounds.max_y };
- const bottom_left = PathData.Point{ .x = child_bounds.min_x, .y = child_bounds.max_y };
- try foreign_path.appendLine(top_left, top_right, frame.local_arena);
- try foreign_path.appendLine(top_right, bottom_right, frame.local_arena);
- try foreign_path.appendLine(bottom_right, bottom_left, frame.local_arena);
- try foreign_path.appendLine(bottom_left, top_left, frame.local_arena);
- bounds.merge(foreign_path.bounds(child_matrix));
- }
- },
+ .foreign_object => mergeTransformed(bounds, try graphics.subtype(ForeignObject).getBounds(frame), child_matrix),
+ // The text box covers its <tspan>s, so they aren't visited.
+ .text_content => mergeTransformed(bounds, graphics.subtype(TextContent).getBounds(frame), child_matrix),
.g, .a => try cursors.append(frame.local_arena, .{
.next = graphics.asNode().firstChild(),
.matrix = child_matrix,
}),
// <defs> and <symbol> never render. Nested viewports, <switch>,
- // <use>, <image> and text have geometry we cannot resolve yet, so
- // they contribute nothing rather than making the whole box
- // unavailable.
- .defs, .symbol, .svg, .switch_element, .use, .image, .text_content => {},
+ // <use> and <image> have geometry we cannot resolve yet, so they
+ // contribute nothing rather than making the whole box unavailable.
+ .defs, .symbol, .svg, .switch_element, .use, .image => {},
}
}
}
+fn mergeTransformed(bounds: *PathData.Bounds, rect: PathData.Bounds, matrix: PathData.Matrix) void {
+ if (rect.isEmpty()) {
+ return;
+ }
+ bounds.include(matrix.apply(.{ .x = rect.min_x, .y = rect.min_y }));
+ bounds.include(matrix.apply(.{ .x = rect.max_x, .y = rect.min_y }));
+ bounds.include(matrix.apply(.{ .x = rect.max_x, .y = rect.max_y }));
+ bounds.include(matrix.apply(.{ .x = rect.min_x, .y = rect.max_y }));
+}
+
/// Composes `transform` attributes from the element up to, excluding, its
/// nearest <svg>. Null when the element isn't in a document.
fn getCTM(self: *Graphics, frame: *Frame) !?*DOMMatrix {
diff --git a/src/browser/webapi/element/svg/TextContent.zig b/src/browser/webapi/element/svg/TextContent.zig
index 023ba4ad6..c922e1007 100644
--- a/src/browser/webapi/element/svg/TextContent.zig
+++ b/src/browser/webapi/element/svg/TextContent.zig
@@ -18,6 +18,7 @@
const std = @import("std");
const lp = @import("lightpanda");
+
const js = @import("../../../js/js.zig");
const Frame = @import("../../../Frame.zig");
const text_measure = @import("../../../text_measure.zig");
@@ -26,14 +27,18 @@ const StyleManager = @import("../../../StyleManager.zig");
const Node = @import("../../Node.zig");
const Element = @import("../../Element.zig");
const Factory = @import("../../../Factory.zig");
+const TreeWalker = @import("../../TreeWalker.zig");
-const AnimatedEnumeration = @import("../../svg/AnimatedEnumeration.zig");
+const Length = @import("../../svg/Length.zig");
+const PathData = @import("../../svg/PathData.zig");
const AnimatedLength = @import("../../svg/AnimatedLength.zig");
+const AnimatedEnumeration = @import("../../svg/AnimatedEnumeration.zig");
-const Graphics = @import("Graphics.zig");
+const SvgElement = @import("../Svg.zig");
-pub const TextPositioning = @import("TextPositioning.zig");
+const Graphics = @import("Graphics.zig");
pub const TextPath = @import("TextPath.zig");
+pub const TextPositioning = @import("TextPositioning.zig");
const TextContent = @This();
@@ -85,7 +90,160 @@ pub fn asNode(self: *TextContent) *Node {
}
fn text(self: *TextContent, frame: *Frame) []const u8 {
- return self.asNode().getTextContentAlloc(frame.local_arena) catch "";
+ const raw = self.asNode().getTextContentAlloc(frame.local_arena) catch return "";
+ return collapseSpaces(raw, self.preservesSpaces(), .both, frame.local_arena) catch "";
+}
+
+const Trim = enum { both, start };
+
+// By default, newlines and tabs become spaces. Runs collapse to one. Edges
+// are trimmmed. `xml:space="preserve"` only does the first (newlines+tabs => space)
+fn collapseSpaces(raw: []const u8, preserve: bool, trim: Trim, allocator: std.mem.Allocator) ![]const u8 {
+ const out = try allocator.alloc(u8, raw.len);
+ var len: usize = 0;
+ for (raw) |c| {
+ const char: u8 = switch (c) {
+ '\n', '\r', '\t' => ' ',
+ else => c,
+ };
+ if (preserve == false and char == ' ' and (len == 0 or out[len - 1] == ' ')) {
+ continue;
+ }
+ out[len] = char;
+ len += 1;
+ }
+ if (preserve == false and trim == .both and len > 0 and out[len - 1] == ' ') {
+ len -= 1;
+ }
+ return out[0..len];
+}
+
+fn preservesSpaces(self: *TextContent) bool {
+ var current: ?*Element = self.asElement();
+ while (current) |element| : (current = element.parentElement()) {
+ const value = element.getAttributeSafe(comptime .wrap("xml:space")) orelse continue;
+ return std.mem.eql(u8, value, "preserve");
+ }
+ return false;
+}
+
+/// The box the deterministic text model gives this element: glyphs start at
+/// the first x/y, shifted by the first dx/dy and by text-anchor, and advance
+/// along the baseline. Per-glyph positions, textPath geometry and bidi are not
+/// modelled.
+pub fn getBounds(self: *TextContent, frame: *Frame) PathData.Bounds {
+ const element = self.asElement();
+ if (element.asNode().isConnected() == false) {
+ // without a layout box, there is no geometry
+ return .{};
+ }
+ const owner = element.ownerFrame(frame) orelse return .{};
+ if (owner._style_manager.rendering(element) == .none) {
+ return .{};
+ }
+
+ const content = self.text(frame);
+ if (content.len == 0) {
+ return .{};
+ }
+ const font_size = self.fontSize(frame);
+ const width = text_measure.width(content, font_size);
+ const origin = self.baselineOrigin(width, frame);
+ return .{
+ .min_x = origin.x,
+ .min_y = origin.y - font_size * text_measure.ASCENT,
+ .max_x = origin.x + width,
+ .max_y = origin.y + font_size * text_measure.DESCENT,
+ };
+}
+
+/// Where the first glyph sits on the baseline. A <tspan> or <textPath> without
+/// its own x/y continues its <text>, after the text that precedes it.
+fn baselineOrigin(self: *TextContent, width: f64, frame: *Frame) PathData.Point {
+ const element = self.asElement();
+ const own_x = firstLength(element, "x", .horizontal, frame);
+ const own_y = firstLength(element, "y", .vertical, frame);
+ const dx = firstLength(element, "dx", .horizontal, frame) orelse 0;
+ const dy = firstLength(element, "dy", .vertical, frame) orelse 0;
+
+ const root = self.textRoot();
+ if (root == self) {
+ return .{
+ .x = (own_x orelse 0) + dx - anchorShift(element, width, frame),
+ .y = (own_y orelse 0) + dy,
+ };
+ }
+
+ const root_width = text_measure.width(root.text(frame), root.fontSize(frame));
+ const root_origin = root.baselineOrigin(root_width, frame);
+ const x = if (own_x) |value|
+ value - anchorShift(element, width, frame)
+ else
+ root_origin.x + self.precedingWidth(root, frame);
+ return .{ .x = x + dx, .y = (own_y orelse root_origin.y) + dy };
+}
+
+/// The outermost text content element this one is nested in, or itself.
+fn textRoot(self: *TextContent) *TextContent {
+ var root = self;
+ var parent = self.asElement().parentElement();
+ while (parent) |element| : (parent = element.parentElement()) {
+ if (element._namespace != .svg) {
+ break;
+ }
+ const graphics = element.as(SvgElement).is(Graphics) orelse break;
+ root = graphics.is(TextContent) orelse break;
+ }
+ return root;
+}
+
+/// Advance of the text in `root` that comes before this element.
+fn precedingWidth(self: *TextContent, root: *TextContent, frame: *Frame) f64 {
+ var preceding: std.Io.Writer.Allocating = .init(frame.local_arena);
+ const stop = self.asNode();
+ var walker = TreeWalker.FullExcludeSelf.init(root.asNode(), .{});
+ while (walker.next()) |node| {
+ if (node == stop) {
+ break;
+ }
+ const text_node = node.is(Node.CData.Text) orelse continue;
+ preceding.writer.writeAll(text_node.asCData()._data.str()) catch return 0;
+ }
+ const collapsed = collapseSpaces(preceding.written(), root.preservesSpaces(), .start, frame.local_arena) catch return 0;
+ return text_measure.width(collapsed, root.fontSize(frame));
+}
+
+/// The first entry of a length-list attribute such as x="10 20 30".
+fn firstLength(element: *Element, comptime name: []const u8, direction: Length.Direction, frame: *Frame) ?f64 {
+ const raw = element.getAttributeSafe(comptime .wrap(name)) orelse return null;
+ var entries = std.mem.tokenizeAny(u8, raw, " \t\r\n,");
+ const first = entries.next() orelse return null;
+ const value = Length.resolve(first, element, direction, frame) orelse return null;
+ return if (std.math.isFinite(value)) value else null;
+}
+
+/// How far text-anchor moves a run of `width` back from its x. Like
+/// computedFontSize, only inline styles and attributes are consulted.
+fn anchorShift(element: *Element, width: f64, frame: *Frame) f64 {
+ const owner = element.ownerFrame(frame) orelse return 0;
+ const style_manager = &owner._style_manager;
+ var current: ?*Element = element;
+ while (current) |el| : (current = el.asNode().flatTreeParentElement(owner)) {
+ const raw = style_manager.inlineStyleValue(el, comptime .wrap("text-anchor")) orelse
+ el.getAttributeSafe(comptime .wrap("text-anchor")) orelse continue;
+ const value = std.mem.trim(u8, raw, " \t\r\n\x0c");
+ if (std.ascii.eqlIgnoreCase(value, "start")) {
+ return 0;
+ }
+ if (std.ascii.eqlIgnoreCase(value, "middle")) {
+ return width / 2;
+ }
+ if (std.ascii.eqlIgnoreCase(value, "end")) {
+ return width;
+ }
+ // inherit, or a value the cascade would drop: keep looking up.
+ }
+ return 0;
}
fn fontSize(self: *TextContent, frame: *Frame) f64 {
diff --git a/src/browser/webapi/svg/Length.zig b/src/browser/webapi/svg/Length.zig
index 5b4572258..866f254de 100644
--- a/src/browser/webapi/svg/Length.zig
+++ b/src/browser/webapi/svg/Length.zig
@@ -298,6 +298,13 @@ fn resolveParsedLength(parsed: Parsed, element: *Element, direction: Direction,
return parsed.value * factor;
}
+/// Resolves one length as written in an attribute, in user units relative to
+/// `element`. Null when it doesn't parse.
+pub fn resolve(raw: []const u8, element: *Element, direction: Direction, frame: *Frame) ?f64 {
+ const parsed = parse(raw) catch return null;
+ return resolveParsedLength(parsed, element, direction, frame, 0);
+}
+
fn fontSize(self: *const Length, frame: *Frame) f64 {
const element = self._element orelse return StyleManager.DEFAULT_FONT_SIZE;
return elementFontSize(element, frame);