Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: improve widths

Karl Seguin2dad2f08d408
diff --git a/src/browser/StyleManager.zig b/src/browser/StyleManager.zig
index 3317c9767..e6342ad62 100644
--- a/src/browser/StyleManager.zig
+++ b/src/browser/StyleManager.zig
@@ -21,6 +21,7 @@ const lp = @import("lightpanda");
const Frame = @import("Frame.zig");
const Viewport = @import("Viewport.zig");
+const text_measure = @import("text_measure.zig");
const units = @import("css/units.zig");
const CssParser = @import("css/Parser.zig");
@@ -683,6 +684,13 @@ pub fn hasDisplayNone(self: *StyleManager, el: *Element) bool {
return self.display(el) == .none;
}
+/// `display: contents`. On the root element it computes to block instead.
+pub fn hasDisplayContents(self: *StyleManager, el: *Element) bool {
+ self.assertOwns(el);
+ self.rebuildIfDirty() catch return false;
+ return self.generatesBox(el) == false;
+}
+
/// Own property, not inherited; honors the UA hidden-element rules.
pub fn display(self: *StyleManager, el: *Element) Display {
self.assertOwns(el);
@@ -750,6 +758,50 @@ pub fn ownTextTransform(self: *StyleManager, el: *Element) TextTransform {
return self.text.ownProps(self.arena.allocator(), el, self.frame).text_transform;
}
+/// The two parts of computed white-space: white-space-collapse and
+/// text-wrap-mode.
+pub fn whiteSpace(self: *StyleManager, el: *Element) text_measure.WhiteSpace {
+ self.assertOwns(el);
+ self.rebuildIfDirty() catch return .{};
+
+ var wrap: WrapMode = .inherit;
+ var collapse: SpaceCollapse = .inherit;
+
+ var current: ?*Element = el;
+ while (current) |elem| : (current = elem.asNode().flatTreeParentElement(self.frame)) {
+ const own = self.ownWhiteSpace(elem);
+ if (collapse == .inherit) {
+ collapse = own.collapse;
+ }
+ if (wrap == .inherit) {
+ wrap = own.wrap;
+ }
+ if (collapse != .inherit and wrap != .inherit) {
+ break;
+ }
+ }
+ return .{
+ .collapse = switch (collapse) {
+ .inherit, .collapse, .preserve_breaks => true,
+ .preserve, .preserve_spaces, .break_spaces => false,
+ },
+ .newlines = switch (collapse) {
+ .preserve, .preserve_breaks, .break_spaces => true,
+ .inherit, .collapse, .preserve_spaces => false,
+ },
+ .wrap = wrap != .nowrap,
+ };
+}
+
+fn ownWhiteSpace(self: *StyleManager, el: *Element) WhiteSpace {
+ if (!self.text.hasRules() and !el._flags.has_inline_style) {
+ // Most pages declare no white-space: skip the cascade and the memo.
+ return WhiteSpace.uaDefault(el.getTag()) orelse .{};
+ }
+ const p = self.text.ownProps(self.arena.allocator(), el, self.frame);
+ return .{ .collapse = p.white_space_collapse, .wrap = p.text_wrap_mode };
+}
+
/// The axes along which `el` is a scroll container: its own computed overflow
/// on that axis is auto, scroll or overlay. No ancestor walk.
pub fn overflowAxes(self: *StyleManager, el: *Element) Element.ScrollAxes {
@@ -833,17 +885,35 @@ pub fn widthSizing(self: *StyleManager, el: *Element) WidthSizing {
return if (self.geometryProps(el).flex_grow) .grow else .shrink;
}
+/// The nearest element to el that generates a box, or `el` itself it it does
+pub fn boxElement(self: *StyleManager, el: *Element) ?*Element {
+ self.assertOwns(el);
+ if (self.generatesBox(el)) {
+ return el;
+ }
+ return self.boxParent(el);
+}
+
/// The nearest ancestor that generates a box
pub fn boxParent(self: *StyleManager, el: *Element) ?*Element {
var parent = el.asNode().flatTreeParentElement(self.frame);
while (parent) |p| : (parent = p.asNode().flatTreeParentElement(self.frame)) {
- if (self.visibilityProps(p).box != .contents) {
+ if (self.generatesBox(p)) {
return p;
}
}
return null;
}
+fn generatesBox(self: *StyleManager, el: *Element) bool {
+ if (self.visibilityProps(el).box != .contents) {
+ return true;
+ }
+ const parent = el.asNode().parentNode() orelse return false;
+ // if we're at the root, and we have `display: contents`, we still force a block
+ return parent._type == .document;
+}
+
/// The children lay out side by side: a flex row or a grid. Elsewhere block
/// children stack and only inline-level ones share a line.
pub fn laysOutInRow(self: *StyleManager, el: *Element) bool {
@@ -1643,6 +1713,166 @@ pub const TextTransform = enum(u3) {
}
};
+// white-space-collapse
+const SpaceCollapse = enum(u3) {
+ inherit,
+ collapse,
+ preserve,
+ preserve_breaks,
+ preserve_spaces,
+ break_spaces,
+
+ // null when invalid
+ fn parse(value: []const u8) ?SpaceCollapse {
+ const trimmed = std.mem.trim(u8, value, &std.ascii.whitespace);
+ if (isInheritKeyword(trimmed)) {
+ return .inherit;
+ }
+ if (std.ascii.eqlIgnoreCase(trimmed, "initial")) {
+ return .collapse;
+ }
+ return keyword(trimmed);
+ }
+
+ fn keyword(token: []const u8) ?SpaceCollapse {
+ if (std.ascii.eqlIgnoreCase(token, "collapse") or std.ascii.eqlIgnoreCase(token, "discard")) {
+ return .collapse;
+ }
+ if (std.ascii.eqlIgnoreCase(token, "preserve")) {
+ return .preserve;
+ }
+ if (std.ascii.eqlIgnoreCase(token, "preserve-breaks")) {
+ return .preserve_breaks;
+ }
+ if (std.ascii.eqlIgnoreCase(token, "preserve-spaces")) {
+ return .preserve_spaces;
+ }
+ if (std.ascii.eqlIgnoreCase(token, "break-spaces")) {
+ return .break_spaces;
+ }
+ return null;
+ }
+};
+
+/// text-wrap-mode
+pub const WrapMode = enum(u2) {
+ inherit,
+ wrap,
+ nowrap,
+
+ // null when invalid
+ fn parse(value: []const u8) ?WrapMode {
+ const trimmed = std.mem.trim(u8, value, &std.ascii.whitespace);
+ if (isInheritKeyword(trimmed)) {
+ return .inherit;
+ }
+ if (std.ascii.eqlIgnoreCase(trimmed, "initial")) {
+ return .wrap;
+ }
+ return keyword(trimmed);
+ }
+
+ /// The `text-wrap` shorthand
+ fn parseTextWrap(value: []const u8) ?WrapMode {
+ const trimmed = std.mem.trim(u8, value, &std.ascii.whitespace);
+ if (isInheritKeyword(trimmed)) {
+ return .inherit;
+ }
+ if (std.ascii.eqlIgnoreCase(trimmed, "initial")) {
+ return .wrap;
+ }
+
+ var any = false;
+ var mode: ?WrapMode = null;
+
+ var it = std.mem.tokenizeAny(u8, trimmed, &std.ascii.whitespace);
+ while (it.next()) |token| {
+ any = true;
+ if (keyword(token)) |m| {
+ if (mode != null) {
+ return null;
+ }
+ mode = m;
+ } else if (isWrapStyle(token) == false) {
+ return null;
+ }
+ }
+ if (any == false) {
+ return null;
+ }
+ return mode orelse .wrap;
+ }
+
+ fn keyword(token: []const u8) ?WrapMode {
+ if (std.ascii.eqlIgnoreCase(token, "wrap")) return .wrap;
+ if (std.ascii.eqlIgnoreCase(token, "nowrap")) return .nowrap;
+ return null;
+ }
+
+ fn isWrapStyle(token: []const u8) bool {
+ inline for (.{ "auto", "balance", "pretty", "stable" }) |style| {
+ if (std.ascii.eqlIgnoreCase(token, style)) return true;
+ }
+ return false;
+ }
+};
+
+/// The `white-space` shorthand: a legacy keyword, or any of a
+/// white-space-collapse and a text-wrap-mode keyword. white-space-trim's
+/// keywords are accepted but not applied.
+const WhiteSpace = struct {
+ collapse: SpaceCollapse = .inherit,
+ wrap: WrapMode = .inherit,
+
+ // Null for an invalid value, which drops the declaration.
+ fn parse(value: []const u8) ?WhiteSpace {
+ const trimmed = std.mem.trim(u8, value, &std.ascii.whitespace);
+ if (isInheritKeyword(trimmed)) return .{};
+ if (std.ascii.eqlIgnoreCase(trimmed, "normal") or std.ascii.eqlIgnoreCase(trimmed, "initial")) return .{ .collapse = .collapse, .wrap = .wrap };
+ if (std.ascii.eqlIgnoreCase(trimmed, "pre")) return .{ .collapse = .preserve, .wrap = .nowrap };
+ if (std.ascii.eqlIgnoreCase(trimmed, "pre-wrap")) return .{ .collapse = .preserve, .wrap = .wrap };
+ if (std.ascii.eqlIgnoreCase(trimmed, "pre-line")) return .{ .collapse = .preserve_breaks, .wrap = .wrap };
+
+ var collapse: ?SpaceCollapse = null;
+ var wrap: ?WrapMode = null;
+ var any = false;
+ var it = std.mem.tokenizeAny(u8, trimmed, &std.ascii.whitespace);
+ while (it.next()) |token| {
+ any = true;
+ if (SpaceCollapse.keyword(token)) |c| {
+ if (collapse != null) return null;
+ collapse = c;
+ } else if (WrapMode.keyword(token)) |w| {
+ if (wrap != null) return null;
+ wrap = w;
+ } else if (isTrimKeyword(token) == false) {
+ return null;
+ }
+ }
+ if (any == false) return null;
+ return .{ .collapse = collapse orelse .collapse, .wrap = wrap orelse .wrap };
+ }
+
+ fn uaDefault(tag: Tag) ?WhiteSpace {
+ return switch (tag) {
+ .pre => .{ .collapse = .preserve, .wrap = .nowrap },
+ .textarea => .{ .collapse = .preserve, .wrap = .wrap },
+ else => null,
+ };
+ }
+
+ fn isTrimKeyword(token: []const u8) bool {
+ inline for (.{ "discard-before", "discard-after", "discard-inner" }) |trim| {
+ if (std.ascii.eqlIgnoreCase(token, trim)) return true;
+ }
+ return false;
+ }
+};
+
+fn isInheritKeyword(value: []const u8) bool {
+ return inheritsKeyword(value) or std.ascii.eqlIgnoreCase(value, "revert") or std.ascii.eqlIgnoreCase(value, "revert-layer");
+}
+
/// A declared width or height. Values that need layout (auto, em, calc) are
/// `auto`: they win the cascade but give no size. The intrinsic sizes, which
/// follow the content, are `content`. A `percent` resolves against the
@@ -1939,20 +2169,51 @@ const TouchAction = struct {
/// value; `.inherit` means it takes its parent's.
const Text = struct {
const Declared = struct {
- const names = [_][]const u8{"text-transform"};
+ const names = [_][]const u8{ "text-transform", "white-space", "white-space-collapse", "text-wrap-mode", "text-wrap" };
+ text_wrap_mode: ?WrapMode = null,
text_transform: ?TextTransform = null,
+ white_space_collapse: ?SpaceCollapse = null,
fn apply(self: *Declared, name: []const u8, value: []const u8) void {
if (std.ascii.eqlIgnoreCase(name, "text-transform")) {
self.text_transform = TextTransform.parse(value);
+ } else if (std.ascii.eqlIgnoreCase(name, "white-space")) {
+ if (WhiteSpace.parse(value)) |white_space| {
+ self.white_space_collapse = white_space.collapse;
+ self.text_wrap_mode = white_space.wrap;
+ }
+ } else if (std.ascii.eqlIgnoreCase(name, "white-space-collapse")) {
+ if (SpaceCollapse.parse(value)) |collapse| {
+ self.white_space_collapse = collapse;
+ }
+ } else if (std.ascii.eqlIgnoreCase(name, "text-wrap-mode")) {
+ if (WrapMode.parse(value)) |mode| {
+ self.text_wrap_mode = mode;
+ }
+ } else if (std.ascii.eqlIgnoreCase(name, "text-wrap")) {
+ if (WrapMode.parseTextWrap(value)) |mode| {
+ self.text_wrap_mode = mode;
+ }
}
}
};
- const Computed = packed struct(u3) {
+ const Computed = packed struct(u8) {
+ text_wrap_mode: WrapMode = .inherit,
text_transform: TextTransform = .inherit,
+ white_space_collapse: SpaceCollapse = .inherit,
};
+
+ pub fn finish(p: *Computed, el: *Element, _: *Frame, priorities: *const Priorities(Declared)) void {
+ const ua = WhiteSpace.uaDefault(el.getTag()) orelse return;
+ if (priorities.get(.white_space_collapse) == 0) {
+ p.white_space_collapse = ua.collapse;
+ }
+ if (priorities.get(.text_wrap_mode) == 0) {
+ p.text_wrap_mode = ua.wrap;
+ }
+ }
};
/// `inherit`, `unset` and `revert` are not handled, so they drop the
diff --git a/src/browser/tests/css/stylesheet.html b/src/browser/tests/css/stylesheet.html
index bbff96123..54bdad5ba 100644
--- a/src/browser/tests/css/stylesheet.html
+++ b/src/browser/tests/css/stylesheet.html
@@ -770,3 +770,25 @@
testing.expectTrue(sheet.cssRules[0].cssText.includes('@layer'));
}
</script>
+
+<script id="computed_display_contents_from_stylesheet">
+{
+ const style = document.createElement('style');
+ style.textContent = '.contents-rule { display: contents; }';
+ document.head.appendChild(style);
+
+ const div = document.createElement('div');
+ div.className = 'contents-rule';
+ div.textContent = 'Role';
+ document.documentElement.appendChild(div);
+ testing.expectEqual('contents', getComputedStyle(div).display);
+
+ // On the root element it computes to block
+ document.documentElement.classList.add('contents-rule');
+ testing.expectEqual('block', getComputedStyle(document.documentElement).display);
+ document.documentElement.classList.remove('contents-rule');
+
+ div.remove();
+ style.remove();
+}
+</script>
diff --git a/src/browser/tests/element/position.html b/src/browser/tests/element/position.html
index 6bcfa3197..c43e54965 100644
--- a/src/browser/tests/element/position.html
+++ b/src/browser/tests/element/position.html
@@ -422,6 +422,20 @@
testing.expectEqual(5, fixedItem.offsetWidth);
row.remove();
+ // A growing item keeps its content's width when there's no space left to
+ // share, like any shrink-to-fit item
+ const full = document.createElement('div');
+ full.style.cssText = 'display: flex; width: 300px';
+ const filler = document.createElement('div');
+ filler.style.cssText = 'width: 300px; flex-shrink: 0';
+ const grower = document.createElement('div');
+ grower.style.flex = '1';
+ grower.textContent = 'Text';
+ full.append(filler, grower);
+ document.body.appendChild(full);
+ testing.expectTrue(grower.getBoundingClientRect().width > 0);
+ full.remove();
+
const column = document.createElement('div');
column.style.cssText = 'display: flex; flex-direction: column; width: 600px';
const item = document.createElement('div');
@@ -1032,3 +1046,17 @@
testing.expectTrue(small.clientHeight < before);
}
</script>
+
+<div id="textWrapped" style="width: 100px">one two three four five six seven eight nine ten</div>
+<div id="textNowrap" style="width: 100px; white-space: nowrap">one two three four five six seven eight nine ten</div>
+<div id="textWrapModeNowrap" style="width: 100px; text-wrap: nowrap">one two three four five six seven eight nine ten</div>
+
+<script id="textNowrapIsOneLine">
+{
+ // nowrap text stays on one line, overflowing its width
+ const wrapped = $('#textWrapped').clientHeight;
+ const nowrap = $('#textNowrap').clientHeight;
+ testing.expectTrue(nowrap < wrapped);
+ testing.expectEqual(nowrap, $('#textWrapModeNowrap').clientHeight);
+}
+</script>
diff --git a/src/browser/tests/range.html b/src/browser/tests/range.html
index 8440c187a..f249545c0 100644
--- a/src/browser/tests/range.html
+++ b/src/browser/tests/range.html
@@ -1042,12 +1042,123 @@
range.selectNodeContents(p);
const rect = range.getBoundingClientRect();
testing.expectTrue(rect instanceof DOMRect);
- // Non-collapsed range delegates to the container element
+ // The text starts where its paragraph does, and has its own size
const elemRect = p.getBoundingClientRect();
testing.expectEqual(elemRect.x, rect.x);
testing.expectEqual(elemRect.y, rect.y);
- testing.expectEqual(elemRect.width, rect.width);
- testing.expectEqual(elemRect.height, rect.height);
+ testing.expectTrue(rect.width > 0);
+ testing.expectTrue(rect.height > 0);
+}
+</script>
+
+<script id=getBoundingClientRect_text>
+{
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+
+ // How Playwright decides a display: contents element's text is visible
+ function textRect(html) {
+ host.innerHTML = html;
+ const range = new Range();
+ range.selectNode(host.firstChild.firstChild);
+ return range.getBoundingClientRect();
+ }
+
+ // Text inside a display: contents element still has a box
+ for (const html of [
+ '<div style="display:contents">Role</div>',
+ '<div style="display:contents;visibility:hidden">Role</div>',
+ '<div style="display:contents">&nbsp;</div>',
+ '<div style="display:contents;white-space:pre"> </div>',
+ '<pre style="display:contents"> </pre>',
+ '<div style="display:contents;white-space:preserve nowrap"> </div>',
+ '<div style="display:contents;white-space-collapse:preserve"> </div>',
+ '<div style="display:contents;white-space:break-spaces"> </div>',
+ ]) {
+ const rect = textRect(html);
+ testing.expectTrue(rect.width > 0);
+ testing.expectTrue(rect.height > 0);
+ }
+
+ // Collapsed spaces and a zero font have no size
+ for (const html of [
+ '<div style="display:contents"> </div>',
+ '<div style="display:contents;white-space:nowrap"> </div>',
+ '<div style="display:contents;font-size:0">Role</div>',
+ '<div style="display:none">Role</div>',
+ ]) {
+ const rect = textRect(html);
+ testing.expectEqual(0, rect.width);
+ testing.expectEqual(0, rect.height);
+ }
+
+ // A word wider than its block overflows it
+ {
+ const rect = textRect('<div style="width:2px">abc</div>');
+ testing.expectTrue(rect.width > 2);
+ }
+
+ // Words wrap: two lines, as wide as the longer word
+ {
+ const one = textRect('<div style="width:2px">abc</div>');
+ const two = textRect('<div style="width:2px">abc ab</div>');
+ testing.expectEqual(one.width, two.width);
+ testing.expectTrue(two.height > one.height);
+ const nowrap = textRect('<div style="width:2px;white-space:nowrap">abc ab</div>');
+ testing.expectTrue(nowrap.width > one.width);
+ testing.expectEqual(one.height, nowrap.height);
+ }
+
+ // A range that only covers part of the text measures that part
+ {
+ host.innerHTML = '<div>abcdef</div>';
+ const text = host.firstChild.firstChild;
+ const range = new Range();
+ range.setStart(text, 0);
+ range.setEnd(text, 3);
+ const part = range.getBoundingClientRect().width;
+ range.setEnd(text, 6);
+ testing.expectTrue(range.getBoundingClientRect().width > part);
+ }
+
+ // Text directly in a shadow root lays out in its host
+ {
+ host.innerHTML = '<div></div>';
+ const shadow = host.firstChild.attachShadow({ mode: 'open' });
+ shadow.innerHTML = 'Shadow text';
+ const range = new Range();
+ range.selectNode(shadow.firstChild);
+ const rect = range.getBoundingClientRect();
+ testing.expectTrue(rect.width > 0);
+ testing.expectTrue(rect.height > 0);
+ }
+
+ // Collapsed spaces have no client rects
+ host.innerHTML = '<div> </div>';
+ const range = new Range();
+ range.selectNodeContents(host.firstChild);
+ testing.expectEqual(0, range.getClientRects().length);
+
+ host.remove();
+}
+</script>
+
+<script id=getBoundingClientRect_display_contents_root>
+{
+ // display: contents on the root element computes to block
+ const html = document.documentElement;
+ html.style.display = 'contents';
+ const wrapper = document.createElement('div');
+ wrapper.style.display = 'contents';
+ wrapper.textContent = 'Role';
+ html.appendChild(wrapper);
+ const range = new Range();
+ range.selectNodeContents(wrapper.firstChild);
+ const rect = range.getBoundingClientRect();
+ testing.expectTrue(rect.width > 0);
+ testing.expectTrue(rect.height > 0);
+ wrapper.remove();
+ html.style.display = '';
}
</script>
diff --git a/src/browser/text_measure.zig b/src/browser/text_measure.zig
index 31edde05f..6788fb9f4 100644
--- a/src/browser/text_measure.zig
+++ b/src/browser/text_measure.zig
@@ -66,44 +66,113 @@ 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;
-/// Greedy line breaking under `white-space: normal`. Text can be added in
-/// pieces (one per text node) that flow on from each other.
+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
+ newlines: bool = false, // A newline breaks the line.
+};
+
+/// The lines a run of text takes: as wide as the widest one.
+pub const Lines = struct {
+ width: f64 = 0,
+ count: u32 = 0,
+
+ pub fn height(self: Lines, font_size: f64) f64 {
+ return @as(f64, @floatFromInt(self.count)) * font_size * LINE_HEIGHT;
+ }
+};
+
+pub fn layout(text: []const u8, font_size: f64, line_width: f64, white_space: WhiteSpace) Lines {
+ var wrap: LineWrap = .{ .line_width = line_width, .font_size = font_size, .white_space = white_space };
+ wrap.add(text);
+ return wrap.lines();
+}
+
pub const LineWrap = struct {
line_width: f64,
font_size: f64,
- lines: u32 = 0,
- // Width used on the current line.
- x: f64 = 0,
- // A space is due before the next word.
- space: bool = false,
+ white_space: WhiteSpace = .{},
+ done: Lines = .{},
+ x: f64 = 0, // Width used on the current line
+ space: f64 = 0, // Spaces due before the next word
+ open: bool = false, // The current line has something on it
+ has_word: bool = false, // The current line has a word on it
+ in_word: bool = false, // The last text added ended mid-word, so the next piece continues it
pub fn add(self: *LineWrap, text: []const u8) void {
- if (text.len == 0) {
- return;
- }
- if (std.ascii.isWhitespace(text[0])) {
- self.space = true;
- }
- var words = std.mem.tokenizeAny(u8, text, &std.ascii.whitespace);
- while (words.next()) |word| {
- const w = width(word, self.font_size);
- const gap = if (self.space) advance(' ', self.font_size) else 0;
- if (self.lines == 0) {
- self.lines = 1;
- self.x = w;
- } else if (self.x + gap + w > self.line_width) {
- self.lines += 1;
- self.x = w;
+ var i: usize = 0;
+ while (i < text.len) {
+ if (text[i] == '\n' and self.white_space.newlines) {
+ self.endLine();
+ i += 1;
+ continue;
+ }
+ const is_space = std.ascii.isWhitespace(text[i]);
+ var end = i + 1;
+ while (end < text.len and std.ascii.isWhitespace(text[end]) == is_space and text[end] != '\n') {
+ end += 1;
+ }
+ if (is_space) {
+ self.addSpace(text[i..end]);
} else {
- self.x += gap + w;
+ self.addWord(text[i..end]);
}
- self.space = true;
+ i = end;
+ }
+ }
+
+ pub fn lines(self: LineWrap) Lines {
+ var copy = self;
+ if (copy.open) {
+ copy.endLine();
}
- self.space = std.ascii.isWhitespace(text[text.len - 1]);
+ return copy.done;
}
pub fn height(self: LineWrap) f64 {
- return @as(f64, @floatFromInt(self.lines)) * self.font_size * LINE_HEIGHT;
+ return self.lines().height(self.font_size);
+ }
+
+ fn addSpace(self: *LineWrap, run: []const u8) void {
+ self.in_word = false;
+ if (self.white_space.collapse == false) {
+ self.space += width(run, self.font_size);
+ self.open = true;
+ } else if (self.has_word) {
+ self.space = advance(' ', self.font_size);
+ }
+ }
+
+ fn addWord(self: *LineWrap, word: []const u8) void {
+ const w = width(word, self.font_size);
+ if (self.in_word) {
+ // No break inside a word
+ self.x += w;
+ } else if (self.white_space.wrap and self.has_word and self.x + self.space + w > self.line_width) {
+ // Spaces at the break hang off the end of the line
+ self.space = 0;
+ self.endLine();
+ self.x = w;
+ } else {
+ self.x += self.space + w;
+ }
+ self.space = 0;
+ self.open = true;
+ self.has_word = true;
+ self.in_word = true;
+ }
+
+ fn endLine(self: *LineWrap) void {
+ if (self.white_space.collapse == false) {
+ self.x += self.space;
+ }
+ self.done.count += 1;
+ self.done.width = @max(self.done.width, self.x);
+ self.x = 0;
+ self.space = 0;
+ self.open = false;
+ self.has_word = false;
+ self.in_word = false;
}
};
@@ -160,16 +229,63 @@ test "LineWrap: collapses whitespace and breaks between words" {
try std.testing.expectEqual(0, wrap.height());
wrap.add(" aaaa \n\t aaaa aaaa ");
- try std.testing.expectEqual(2, wrap.lines);
+ try std.testing.expectEqual(2, wrap.lines().count);
wrap.add("aaaa");
- try std.testing.expectEqual(2, wrap.lines);
+ try std.testing.expectEqual(2, wrap.lines().count);
+ // Continues the word, which can't break, so it overflows the line
wrap.add("aaaa");
- try std.testing.expectEqual(3, wrap.lines);
- try std.testing.expectApproxEqAbs(36, wrap.height(), 0.0001);
+ try std.testing.expectEqual(2, wrap.lines().count);
+ try std.testing.expectApproxEqAbs(24, wrap.height(), 0.0001);
+ wrap.add(" aaaa");
+ try std.testing.expectEqual(3, wrap.lines().count);
// Long words aren't split
var narrow: LineWrap = .{ .line_width = 10, .font_size = 10 };
narrow.add("aaaa aaaa");
- try std.testing.expectEqual(2, narrow.lines);
+ try std.testing.expectEqual(2, narrow.lines().count);
+}
+
+test "layout: white-space modes" {
+ // At 10px: a letter is 6px, a space 3.3px
+ const normal: WhiteSpace = .{};
+ const nowrap: WhiteSpace = .{ .wrap = false };
+ const pre: WhiteSpace = .{ .collapse = false, .newlines = true, .wrap = false };
+ const pre_line: WhiteSpace = .{ .newlines = true };
+
+ // Spaces collapse to one and vanish at the line's edges
+ var lines = layout(" ab \n\t cd ", 10, 100, normal);
+ try std.testing.expectEqual(1, lines.count);
+ try std.testing.expectApproxEqAbs(27.3, lines.width, 0.0001);
+
+ // Only spaces: no line at all, unless they're preserved
+ try std.testing.expectEqual(Lines{}, layout(" ", 10, 100, normal));
+ lines = layout(" ", 10, 100, pre);
+ try std.testing.expectEqual(1, lines.count);
+ try std.testing.expectApproxEqAbs(9.9, lines.width, 0.0001);
+
+ // nbsp is a letter, not a collapsible space
+ lines = layout("\u{a0}", 10, 100, normal);
+ try std.testing.expectEqual(1, lines.count);
+ try std.testing.expect(lines.width > 0);
+
+ // A word wider than the line overflows it
+ lines = layout("abc", 10, 2, normal);
+ try std.testing.expectEqual(1, lines.count);
+ try std.testing.expectApproxEqAbs(18, lines.width, 0.0001);
+
+ // Wraps between words: as wide as the widest line
+ lines = layout("abc de", 10, 2, normal);
+ try std.testing.expectEqual(2, lines.count);
+ try std.testing.expectApproxEqAbs(18, lines.width, 0.0001);
+ try std.testing.expectApproxEqAbs(24, lines.height(10), 0.0001);
+ try std.testing.expectEqual(1, layout("abc de", 10, 2, nowrap).count);
+
+ // Newlines break the line, but a trailing one doesn't add another
+ try std.testing.expectEqual(3, layout("ab\n\ncd\n", 10, 100, pre).count);
+ try std.testing.expectEqual(2, layout("ab \n cd", 10, 100, pre_line).count);
+ try std.testing.expectApproxEqAbs(12, layout("ab \n cd", 10, 100, pre_line).width, 0.0001);
+
+ // No font, no size
+ try std.testing.expectEqual(0, layout("abc", 0, 100, normal).height(0));
}
diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zig
index ad7cfbb7b..e35c34fa1 100644
--- a/src/browser/webapi/Element.zig
+++ b/src/browser/webapi/Element.zig
@@ -1700,7 +1700,7 @@ fn boxWidth(self: *Element, owner: *Frame) f64 {
.fixed => |width| width,
.percent => |fraction| fraction * self.containingBlockWidth(owner),
.fill => self.containingBlockWidth(owner),
- .grow => @max(self.growShare(owner), self.contentWidth(owner)),
+ .grow => @max(own.value, self.growShare(owner), self.contentWidth(owner)),
.shrink => @max(own.value, self.contentWidth(owner)),
.contents => break :blk 0,
};
@@ -1825,14 +1825,22 @@ pub fn boundingClientRectValues(self: *Element, frame: *Frame) DOMRect.Data {
// Some cases need the bounding rect but have already done the visibility check.
pub fn boundingClientRectValuesForVisible(self: *Element, frame: *Frame) DOMRect.Data {
- // Client rects are viewport-relative: offset the faux-layout document
- // position by the owning window's scroll position.
+ const origin = self.clientOrigin(frame);
+ return .{
+ .x = origin.x,
+ .y = origin.y,
+ .width = self.boxAxis(frame, .width),
+ .height = self.boxAxis(frame, .height),
+ };
+}
+
+// Client rects are viewport-relative: offset the faux-layout document
+// position by the owning window's scroll position.
+pub fn clientOrigin(self: *Element, frame: *Frame) struct { x: f64, y: f64 } {
const window = (self.ownerFrame(frame) orelse frame).window;
return .{
.x = self.horizontalPosition(frame) - @as(f64, @floatFromInt(window.getScrollX())),
.y = calculateDocumentPosition(self.asNode(), frame) - @as(f64, @floatFromInt(window.getScrollY())),
- .width = self.boxAxis(frame, .width),
- .height = self.boxAxis(frame, .height),
};
}
@@ -1982,7 +1990,11 @@ pub fn contentAxis(self: *Element, frame: *Frame, comptime axis: Axis) f64 {
if (axis == .height) {
const width = self.getElementAxis(frame, .width);
if (width.explicit) {
- wrap = .{ .line_width = width.value, .font_size = style_manager.computedFontSize(self) };
+ wrap = .{
+ .line_width = width.value,
+ .font_size = style_manager.computedFontSize(self),
+ .white_space = style_manager.whiteSpace(self),
+ };
}
}
diff --git a/src/browser/webapi/Range.zig b/src/browser/webapi/Range.zig
index 4b4f22e8d..c39309faa 100644
--- a/src/browser/webapi/Range.zig
+++ b/src/browser/webapi/Range.zig
@@ -20,11 +20,12 @@ const std = @import("std");
const js = @import("../js/js.zig");
const Frame = @import("../Frame.zig");
+const text_measure = @import("../text_measure.zig");
const Node = @import("Node.zig");
const DOMRect = @import("DOMRect.zig");
-const DocumentFragment = @import("DocumentFragment.zig");
const AbstractRange = @import("AbstractRange.zig");
+const DocumentFragment = @import("DocumentFragment.zig");
const Range = @This();
@@ -830,30 +831,119 @@ fn nextAfterSubtree(node: *Node, root: *Node) ?*Node {
}
pub fn getBoundingClientRect(self: *const Range, frame: *Frame) !*DOMRect {
- if (self._proto.getCollapsed()) {
- return DOMRect.create(.{}, frame._factory);
- }
- const element = self.getContainerElement() orelse {
- return DOMRect.create(.{}, frame._factory);
- };
- return element.getBoundingClientRect(frame);
+ const rect = try self.clientRect(frame) orelse DOMRect.Data{};
+ return DOMRect.create(rect, frame._factory);
}
fn getClientRects(self: *const Range, frame: *Frame) ![]*DOMRect {
+ const rect = try self.clientRect(frame) orelse return &.{};
+ const rects = try frame.local_arena.alloc(*DOMRect, 1);
+ rects[0] = try DOMRect.create(rect, frame._factory);
+ return rects;
+}
+
+// null when nothing in the range has a box
+fn clientRect(self: *const Range, frame: *Frame) !?DOMRect.Data {
if (self._proto.getCollapsed()) {
- return &.{};
+ return null;
+ }
+
+ if (self.textParent()) |parent| {
+ // The range is over text that is covered by a single element
+ return measureText(parent, try self.toString(frame), frame);
}
- const element = self.getContainerElement() orelse {
- return &.{};
+ const element = self.getContainerElement(frame) orelse return null;
+ if (element.isVisible(frame) == false) {
+ return null;
+ }
+ return element.boundingClientRectValuesForVisible(frame);
+}
+
+// null if the range is contained within a single element
+fn textParent(self: *const Range) ?*Node.Element {
+ const start = self._proto._start_container;
+ const end = self._proto._end_container;
+ const start_is_text = start.is(Node.CData) != null;
+ const end_is_text = end.is(Node.CData) != null;
+
+ const parent = (if (start_is_text) start.parentNode() else start) orelse return null;
+ const end_parent = (if (end_is_text) end.parentNode() else end) orelse return null;
+ if (parent != end_parent) {
+ return null;
+ }
+ const element = layoutElement(parent) orelse return null;
+ if (start == end and start_is_text) {
+ return element;
+ }
+
+ // Every child between the boundaries must be text
+ const until: ?*Node = if (end_is_text) end else end.getChildAt(self._proto._end_offset);
+ var current = if (start_is_text) start.nextSibling() else start.getChildAt(self._proto._start_offset);
+ while (current) |node| : (current = node.nextSibling()) {
+ if (node == until) {
+ break;
+ }
+ if (node.is(Node.CData) == null) {
+ return null;
+ }
+ }
+ return element;
+}
+
+// Text inside a `display: contents` element has a box even though the element
+// doesn't.
+fn measureText(parent: *Node.Element, text: []const u8, frame: *Frame) ?DOMRect.Data {
+ if (parent.isVisible(frame) == false) {
+ return null;
+ }
+ const owner = parent.ownerFrame(frame) orelse return null;
+ const style_manager = &owner._style_manager;
+ const box = style_manager.boxElement(parent) orelse return null;
+
+ const font_size = style_manager.computedFontSize(parent);
+ const lines = text_measure.layout(text, font_size, lineWidth(box, owner), style_manager.whiteSpace(parent));
+ if (lines.count == 0) {
+ return null;
+ }
+
+ const origin = box.clientOrigin(frame);
+ return .{
+ .x = origin.x,
+ .y = origin.y,
+ .width = lines.width,
+ .height = lines.height(font_size),
};
- return element.getClientRects(frame);
}
-fn getContainerElement(self: *const Range) ?*Node.Element {
+fn lineWidth(box: *Node.Element, owner: *Frame) f64 {
+ const style_manager = &owner._style_manager;
+ var current: ?*Node.Element = box;
+ while (current) |el| : (current = style_manager.boxParent(el)) {
+ if (style_manager.isBlockLevel(el)) {
+ return el.boxAxis(owner, .width);
+ }
+ }
+ return @floatFromInt(owner.page.getViewport().width);
+}
+
+fn getContainerElement(self: *const Range, frame: *Frame) ?*Node.Element {
const container = self._proto.getCommonAncestorContainer();
- if (container.is(Node.Element)) |el| return el;
- const parent = container.parentNode() orelse return null;
- return parent.is(Node.Element);
+ const el = layoutElement(container) orelse blk: {
+ const parent = container.parentNode() orelse return null;
+ break :blk layoutElement(parent) orelse return null;
+ };
+ const owner = el.ownerFrame(frame) orelse return el;
+ return owner._style_manager.boxElement(el);
+}
+
+// The element a node's children are laid out in: a shadow root's are its
+// host's.
+fn layoutElement(node: *Node) ?*Node.Element {
+ if (node.is(Node.Element)) |el| {
+ return el;
+ }
+ const shadow_root = node.is(Node.ShadowRoot) orelse return null;
+ return shadow_root.getHost();
}
pub const JsApi = struct {
diff --git a/src/browser/webapi/css/CSSStyleDeclaration.zig b/src/browser/webapi/css/CSSStyleDeclaration.zig
index c44918e3c..a3154c513 100644
--- a/src/browser/webapi/css/CSSStyleDeclaration.zig
+++ b/src/browser/webapi/css/CSSStyleDeclaration.zig
@@ -101,6 +101,9 @@ fn propertyValue(self: *const CSSStyleDeclaration, normalized: []const u8, wrapp
if (style_manager.hasDisplayNone(element)) {
return "none";
}
+ if (style_manager.hasDisplayContents(element)) {
+ return "contents";
+ }
} else if (wrapped.eql(comptime .wrap("visibility"))) {
if (style_manager.hasVisibilityHiddenInherited(element)) {
return "hidden";