Skip to content

Lightpanda: the headless browser designed for AI and automation

The width of a container is now determined with respect to its parent. In a normal flow, a block container is the same width as its parent, an inline container is sized by its content, as are floats, absolute positioned, table, ... We also now support % width, min/max-width and basic support for flex layouts. While this still isn't going to be the "real" width, it should represent more realistic values and, most importantly, more realistic values between a child and its parents.

Karl Seguin2e658267e743
diff --git a/src/browser/StyleManager.zig b/src/browser/StyleManager.zig
index e01780157..9b15b26b9 100644
--- a/src/browser/StyleManager.zig
+++ b/src/browser/StyleManager.zig
@@ -60,6 +60,8 @@ touch_action: Group(TouchAction) = .{},
text: Group(Text) = .{},
flow: Group(Flow) = .{},
+widths: WidthMemo = .{},
+
// Keyed by property name, pruning to what is (hopefully) one or few rules
custom_rules: std.StringHashMapUnmanaged(CustomProperty) = .empty,
@@ -597,6 +599,7 @@ fn rebuildIfDirty(self: *StyleManager) !void {
const custom_rules_count = self.custom_rules.count();
self.arena.resetRetain();
+ self.widths = .{};
self.next_doc_order = 1;
self.rule_layers = .empty;
@@ -758,26 +761,158 @@ pub fn inlineSize(self: *StyleManager, el: *Element, comptime axis: Element.Axis
return length.resolve(self.frame.page.getViewport());
}
-/// A block-level flex or grid container in normal flow, with an auto width,
-/// that isn't a flex or grid item itself. Its width comes from its containing
-/// block: its items overflow it instead of widening it.
-pub fn widthFromContainingBlock(self: *StyleManager, el: *Element) bool {
+pub const WidthSizing = union(enum) {
+ fixed: f64, // A resolved length
+ percent: f64, // A fraction of the containing block
+ fill, // The containing block's width
+ grow, // A flex item that grows
+ shrink, // Shrink-to-fit its content
+ contents, // display: contents generates no box
+};
+
+pub fn widthSizing(self: *StyleManager, el: *Element) WidthSizing {
self.assertOwns(el);
- self.rebuildIfDirty() catch return false;
- if (!self.visibilityProps(el).block_flex_or_grid or self.geometryProps(el).width.unit != .auto) {
- return false;
+ self.rebuildIfDirty() catch return .shrink;
+
+ const vis = self.visibilityProps(el);
+ if (vis.box == .contents) {
+ return .contents;
+ }
+
+ const width = self.geometryProps(el).width;
+ switch (width.unit) {
+ .px, .vw, .vh => return .{ .fixed = width.resolve(self.frame.page.getViewport()).? },
+ .percent => return .{ .percent = @as(f64, width.value) / 100.0 },
+ .content => return .shrink,
+ .auto => {},
+ }
+ if (vis.box != .block_level or el.getTag().isReplacedOrControl()) {
+ return .shrink;
}
const flow = self.flow.ownProps(self.arena.allocator(), el, self.frame);
if (flow.absolutely_positioned or flow.floated) {
- return false;
+ return .shrink;
+ }
+ const parent = self.boxParent(el) orelse return .fill;
+ const parent_vis = self.visibilityProps(parent);
+ if (parent_vis.display != .flex or parent_vis.flex_column) {
+ // Block, grid and column-flex containers stretch their children
+ return .fill;
}
- const parent = el.asNode().flatTreeParentElement(self.frame) orelse return true;
- return switch (self.visibilityProps(parent).display) {
- .flex, .grid => false,
- else => true,
+ return if (self.geometryProps(el).flex_grow) .grow else .shrink;
+}
+
+/// 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) {
+ return p;
+ }
+ }
+ return null;
+}
+
+/// 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 {
+ self.assertOwns(el);
+ self.rebuildIfDirty() catch return false;
+ const vis = self.visibilityProps(el);
+ return vis.display == .grid or (vis.display == .flex and vis.flex_column == false);
+}
+
+pub fn isBlockLevel(self: *StyleManager, el: *Element) bool {
+ self.assertOwns(el);
+ self.rebuildIfDirty() catch return false;
+ switch (self.visibilityProps(el).box) {
+ .block_level, .table => {},
+ .inline_level, .contents => return false,
+ }
+ const flow = self.flow.ownProps(self.arena.allocator(), el, self.frame);
+ return flow.absolutely_positioned == false and flow.floated == false;
+}
+
+/// Overflow along x is clipped or scrolled within the box, so it doesn't
+/// widen the ancestors' scrollable area.
+pub fn clipsOverflowX(self: *StyleManager, el: *Element) bool {
+ self.assertOwns(el);
+ self.rebuildIfDirty() catch return false;
+ return self.geometryProps(el).overflow_x_clips;
+}
+
+pub const WidthLimit = union(enum) {
+ px: f64,
+ percent: f64, // A fraction of the containing block
+};
+
+/// min-width and max-width. Null where they don't limit: auto, none, the
+/// intrinsic keywords, and values that need layout (em, calc).
+pub fn widthLimits(self: *StyleManager, el: *Element) struct { min: ?WidthLimit, max: ?WidthLimit } {
+ self.assertOwns(el);
+ self.rebuildIfDirty() catch return .{ .min = null, .max = null };
+ const geometry = self.geometryProps(el);
+ return .{ .min = self.widthLimit(geometry.min_width), .max = self.widthLimit(geometry.max_width) };
+}
+
+fn widthLimit(self: *StyleManager, length: Length) ?WidthLimit {
+ return switch (length.unit) {
+ .auto, .content => null,
+ .percent => .{ .percent = @as(f64, length.value) / 100.0 },
+ .px, .vw, .vh => .{ .px = length.resolve(self.frame.page.getViewport()).? },
};
}
+pub const WidthKind = enum { box, content };
+
+/// Element's computed widths (see Element.boxWidth), valid for one style
+/// version and viewport. Each read otherwise walks up to the root and down
+/// the subtree.
+const WidthMemo = struct {
+ version: usize = 0,
+ viewport_width: u32 = 0,
+ viewport_height: u32 = 0,
+ map: std.AutoHashMapUnmanaged(*Element, Entry) = .empty,
+
+ const Entry = struct {
+ box: ?f64 = null,
+ content: ?f64 = null,
+ };
+};
+
+pub fn cachedWidth(self: *StyleManager, el: *Element, comptime kind: WidthKind) ?f64 {
+ const memo = self.freshWidthMemo() orelse return null;
+ const entry = memo.map.get(el) orelse return null;
+ return @field(entry, @tagName(kind));
+}
+
+pub fn cacheWidth(self: *StyleManager, el: *Element, comptime kind: WidthKind, width: f64) void {
+ const memo = self.freshWidthMemo() orelse return;
+ const gop = memo.map.getOrPut(self.arena.allocator(), el) catch |err| {
+ log.warn(.browser, "StyleManager width memo", .{ .err = err });
+ return;
+ };
+ if (gop.found_existing == false) {
+ gop.value_ptr.* = .{};
+ }
+ @field(gop.value_ptr, @tagName(kind)) = width;
+}
+
+// Rebuilding resets the arena the memo lives in, so it runs first.
+fn freshWidthMemo(self: *StyleManager) ?*WidthMemo {
+ self.rebuildIfDirty() catch return null;
+ const memo = &self.widths;
+ const version = self.frame.page.style_version;
+ const viewport = self.frame.page.getViewport();
+ if (memo.version != version or memo.viewport_width != viewport.width or memo.viewport_height != viewport.height) {
+ memo.map.clearRetainingCapacity();
+ memo.version = version;
+ memo.viewport_width = viewport.width;
+ memo.viewport_height = viewport.height;
+ }
+ return memo;
+}
+
/// Callers must have run rebuildIfDirty, which resets the memo.
fn visibilityProps(self: *StyleManager, el: *Element) Visibility.Computed {
return self.visibility.inheritedProps(self.arena.allocator(), el, self.frame);
@@ -1318,6 +1453,48 @@ pub const Display = enum(u2) {
}
};
+const Box = enum(u2) {
+ block_level,
+ inline_level,
+ contents,
+ table,
+
+ fn parse(value: []const u8) ?Box {
+ const trimmed = std.mem.trim(u8, value, &std.ascii.whitespace);
+ if (std.ascii.eqlIgnoreCase(trimmed, "contents")) {
+ return .contents;
+ }
+
+ if (std.ascii.eqlIgnoreCase(trimmed, "table")) {
+ return .table;
+ }
+
+ if (std.ascii.startsWithIgnoreCase(trimmed, "inline")) {
+ return .inline_level;
+ }
+
+ inline for (.{ "block", "flow-root", "list-item", "flex", "grid", "flow" }) |keyword| {
+ if (std.ascii.eqlIgnoreCase(trimmed, keyword)) {
+ return .block_level;
+ }
+ }
+
+ // Multi-keyword values start with the outer type
+ if (std.ascii.startsWithIgnoreCase(trimmed, "block ")) {
+ return .block_level;
+ }
+ return null;
+ }
+
+ fn uaDefault(tag: Tag) Box {
+ return switch (tag) {
+ .table => .table,
+ .form, .li, .dd, .dt, .details, .summary, .menu, .dir, .hgroup, .legend, .html, .body, .optgroup, .option => .block_level,
+ else => if (tag.isBlock()) .block_level else .inline_level,
+ };
+ }
+};
+
/// The case-changing part of `text-transform`. innerText applies `uppercase`
/// and `lowercase`; `capitalize` is a computed value only, and `full-width`,
/// `full-size-kana` and `math-auto` are accepted but not applied. `.inherit` is both the
@@ -1375,14 +1552,15 @@ pub const TextTransform = enum(u3) {
}
};
-/// A declared width or height. Values that need layout (auto, %, em) are
+/// 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`.
+/// follow the content, are `content`. A `percent` resolves against the
+/// containing block, which only the width axis knows.
pub const Length = packed struct(u35) {
value: f32 = 0,
unit: Unit = .auto,
- const Unit = enum(u3) { auto, content, px, vw, vh };
+ const Unit = enum(u3) { auto, content, px, vw, vh, percent };
fn parse(text: []const u8) Length {
if (isIntrinsic(text)) {
@@ -1394,6 +1572,7 @@ pub const Length = packed struct(u35) {
}
return switch (parsed.unit) {
inline .vw, .vh => |unit| .{ .value = @floatCast(parsed.value), .unit = @field(Unit, @tagName(unit)) },
+ .percentage => .{ .value = @floatCast(parsed.value), .unit = .percent },
else => .{
.value = @floatCast(parsed.value * (units.absoluteLengthFactor(parsed.unit) orelse return .{})),
.unit = .px,
@@ -1413,7 +1592,7 @@ pub const Length = packed struct(u35) {
fn resolve(self: Length, viewport: Viewport) ?f64 {
const value: f64 = self.value;
return switch (self.unit) {
- .auto, .content => null,
+ .auto, .content, .percent => null,
.px => value,
.vw, .vh => value * @as(f64, @floatFromInt(if (self.unit == .vw) viewport.width else viewport.height)) / 100.0,
};
@@ -1423,10 +1602,11 @@ pub const Length = packed struct(u35) {
/// Whether an element is rendered and takes pointer input.
const Visibility = struct {
const Declared = struct {
- const names = [_][]const u8{ "display", "visibility", "opacity", "pointer-events" };
+ const names = [_][]const u8{ "display", "visibility", "opacity", "pointer-events", "flex-direction", "flex-flow" };
display: ?Display = null,
- block_flex_or_grid: ?bool = null,
+ box: ?Box = null,
+ flex_column: ?bool = null,
// Inner null: an explicit inherit, which still wins the cascade
visibility_hidden: ??bool = null,
opacity_zero: ?bool = null,
@@ -1435,7 +1615,10 @@ const Visibility = struct {
fn apply(self: *Declared, name: []const u8, value: []const u8) void {
if (std.ascii.eqlIgnoreCase(name, "display")) {
self.display = Display.parse(value);
- self.block_flex_or_grid = std.ascii.eqlIgnoreCase(value, "flex") or std.ascii.eqlIgnoreCase(value, "grid");
+ self.box = Box.parse(value);
+ } else if (std.ascii.eqlIgnoreCase(name, "flex-direction") or std.ascii.eqlIgnoreCase(name, "flex-flow")) {
+ // flex-flow's direction keyword comes first
+ self.flex_column = std.ascii.startsWithIgnoreCase(std.mem.trimStart(u8, value, &std.ascii.whitespace), "column");
} else if (std.ascii.eqlIgnoreCase(name, "visibility")) {
self.visibility_hidden = parseInheritedFlag(value, &.{ "hidden", "collapse" }, &.{ "visible", "initial" });
} else if (std.ascii.eqlIgnoreCase(name, "opacity")) {
@@ -1455,7 +1638,9 @@ const Visibility = struct {
// Author value (inline or sheet). Without `author_display` it's the UA
// fallback: .none when matchesUaDisplayNoneRule, else .other.
display: Display = .other,
- block_flex_or_grid: bool = false,
+ // Without an author `display` it's the tag's UA default, see finish
+ box: Box = .inline_level,
+ flex_column: bool = false,
author_display: bool = false,
// Null takes the parent's value
visibility_hidden: ?bool = null,
@@ -1463,9 +1648,10 @@ const Visibility = struct {
pointer_events_none: ?bool = null,
};
- const Computed = packed struct(u8) {
+ const Computed = packed struct(u10) {
display: Display = .other,
- block_flex_or_grid: bool = false,
+ box: Box = .inline_level,
+ flex_column: bool = false,
author_display: bool = false,
visibility_hidden: bool = false, // inherited
pointer_events_none: bool = false, // inherited
@@ -1475,7 +1661,8 @@ const Visibility = struct {
fn resolve(own: Cascaded, parent: Computed) Computed {
return .{
.display = own.display,
- .block_flex_or_grid = own.block_flex_or_grid,
+ .box = own.box,
+ .flex_column = own.flex_column,
.author_display = own.author_display,
.visibility_hidden = own.visibility_hidden orelse parent.visibility_hidden,
.pointer_events_none = own.pointer_events_none orelse parent.pointer_events_none,
@@ -1498,6 +1685,9 @@ const Visibility = struct {
// `<div class="x" hidden>` must report visible.
pub fn finish(p: *Cascaded, el: *Element, frame: *Frame, priorities: *const Priorities(Declared)) void {
p.author_display = priorities.get(.display) != 0;
+ if (priorities.get(.box) == 0) {
+ p.box = Box.uaDefault(el.getTag());
+ }
if (!p.author_display and matchesUaDisplayNoneRule(el, frame)) {
p.display = .none;
}
@@ -1507,18 +1697,27 @@ const Visibility = struct {
/// An element's box: its size and how it scrolls.
const Geometry = struct {
const Declared = struct {
- const names = [_][]const u8{ "overflow-x", "overflow-y", "overscroll-behavior-x", "overscroll-behavior-y", "width", "height" };
+ const names = [_][]const u8{ "overflow-x", "overflow-y", "overscroll-behavior-x", "overscroll-behavior-y", "width", "height", "min-width", "max-width", "flex", "flex-grow" };
overflow_x_scrolls: ?bool = null,
+ overflow_x_clips: ?bool = null,
+ flex_grow: ?bool = null,
overflow_y_scrolls: ?bool = null,
overscroll_x_contains: ?bool = null,
overscroll_y_contains: ?bool = null,
width: ?Length = null,
height: ?Length = null,
+ min_width: ?Length = null,
+ max_width: ?Length = null,
fn apply(self: *Declared, name: []const u8, value: []const u8) void {
if (std.ascii.eqlIgnoreCase(name, "overflow-x")) {
self.overflow_x_scrolls = overflowScrolls(value);
+ self.overflow_x_clips = overflowClips(value);
+ } else if (std.ascii.eqlIgnoreCase(name, "flex-grow")) {
+ self.flex_grow = flexGrows(value);
+ } else if (std.ascii.eqlIgnoreCase(name, "flex")) {
+ self.flex_grow = flexShorthandGrows(value);
} else if (std.ascii.eqlIgnoreCase(name, "overflow-y")) {
self.overflow_y_scrolls = overflowScrolls(value);
} else if (std.ascii.eqlIgnoreCase(name, "overscroll-behavior-x")) {
@@ -1529,6 +1728,10 @@ const Geometry = struct {
self.width = Length.parse(value);
} else if (std.ascii.eqlIgnoreCase(name, "height")) {
self.height = Length.parse(value);
+ } else if (std.ascii.eqlIgnoreCase(name, "min-width")) {
+ self.min_width = Length.parse(value);
+ } else if (std.ascii.eqlIgnoreCase(name, "max-width")) {
+ self.max_width = Length.parse(value);
}
}
@@ -1539,6 +1742,27 @@ const Geometry = struct {
std.ascii.eqlIgnoreCase(value, "overlay");
}
+ // Clipped or scrolled within the box: hidden, clip and the scrolling values.
+ fn overflowClips(value: []const u8) bool {
+ return overflowScrolls(value) or
+ std.ascii.eqlIgnoreCase(value, "hidden") or
+ std.ascii.eqlIgnoreCase(value, "clip");
+ }
+
+ fn flexGrows(value: []const u8) bool {
+ const number = std.fmt.parseFloat(f64, std.mem.trim(u8, value, &std.ascii.whitespace)) catch return false;
+ return number > 0;
+ }
+
+ // `flex: <grow> [<shrink>] [<basis>]`; `auto` grows, `none` and
+ // `initial` don't, and a lone width (`flex: 200px`) is a basis.
+ fn flexShorthandGrows(value: []const u8) bool {
+ var it = std.mem.tokenizeAny(u8, value, &std.ascii.whitespace);
+ const first = it.next() orelse return false;
+ if (std.ascii.eqlIgnoreCase(first, "auto")) return true;
+ return flexGrows(first);
+ }
+
// `contain` keeps the scroll in the box, `none` also kills the bounce we
// don't render anyway; only `auto` lets a scroll chain outward.
fn overscrollContains(value: []const u8) bool {
@@ -1547,13 +1771,18 @@ const Geometry = struct {
}
};
- const Computed = packed struct(u74) {
+ const Computed = packed struct(u146) {
overflow_x_scrolls: bool = false,
+ overflow_x_clips: bool = false,
+ flex_grow: bool = false,
overflow_y_scrolls: bool = false,
overscroll_x_contains: bool = false,
overscroll_y_contains: bool = false,
width: Length = .{},
height: Length = .{},
+ // auto, none and the intrinsic keywords don't limit
+ min_width: Length = .{},
+ max_width: Length = .{},
};
};
@@ -2325,29 +2554,29 @@ test "StyleManager: inlineDeclared: scan matches the parsed style object" {
\\<i style="width: fit-content(10px); position: relative; float: none"></i>
);
const expected = [_]Declarations{
- .{ .visibility = .{ .display = .none, .block_flex_or_grid = false } },
- .{ .visibility = .{ .display = .none, .block_flex_or_grid = false } },
- .{ .visibility = .{ .display = .none, .block_flex_or_grid = false } },
- .{ .visibility = .{ .display = .other, .block_flex_or_grid = false } },
- .{ .visibility = .{ .display = .none, .block_flex_or_grid = false, .visibility_hidden = true } },
+ .{ .visibility = .{ .display = .none } },
+ .{ .visibility = .{ .display = .none } },
+ .{ .visibility = .{ .display = .none } },
+ .{ .visibility = .{ .display = .other, .box = .block_level } },
+ .{ .visibility = .{ .display = .none, .visibility_hidden = true } },
.{ .visibility = .{ .opacity_zero = true, .pointer_events_none = true } },
.{ .visibility = .{ .opacity_zero = false, .pointer_events_none = true } },
.{ .visibility = .{ .visibility_hidden = true } },
.{},
.{},
- .{ .geometry = .{ .overflow_x_scrolls = true, .overflow_y_scrolls = true } },
- .{ .geometry = .{ .overflow_x_scrolls = false, .overflow_y_scrolls = true } },
- .{ .geometry = .{ .overflow_x_scrolls = false, .overflow_y_scrolls = true } },
- .{ .geometry = .{ .overflow_x_scrolls = false, .overflow_y_scrolls = false } },
- .{ .geometry = .{ .overflow_x_scrolls = false, .overflow_y_scrolls = true } },
- .{ .geometry = .{ .overflow_x_scrolls = true } },
+ .{ .geometry = .{ .overflow_x_scrolls = true, .overflow_x_clips = true, .overflow_y_scrolls = true } },
+ .{ .geometry = .{ .overflow_x_scrolls = false, .overflow_x_clips = true, .overflow_y_scrolls = true } },
+ .{ .geometry = .{ .overflow_x_scrolls = false, .overflow_x_clips = true, .overflow_y_scrolls = true } },
+ .{ .geometry = .{ .overflow_x_scrolls = false, .overflow_x_clips = true, .overflow_y_scrolls = false } },
+ .{ .geometry = .{ .overflow_x_scrolls = false, .overflow_x_clips = true, .overflow_y_scrolls = true } },
+ .{ .geometry = .{ .overflow_x_scrolls = true, .overflow_x_clips = true } },
.{},
.{ .geometry = .{ .width = .{ .value = 100, .unit = .px }, .height = .{ .value = 96, .unit = .px } } },
.{ .geometry = .{ .height = .{} } },
- .{ .geometry = .{ .width = .{}, .height = .{} } },
+ .{ .geometry = .{ .width = .{ .value = 50, .unit = .percent }, .height = .{} } },
.{ .geometry = .{ .width = .{} } },
- .{ .visibility = .{ .display = .flex, .block_flex_or_grid = true } },
- .{ .visibility = .{ .display = .grid, .block_flex_or_grid = false } },
+ .{ .visibility = .{ .display = .flex, .box = .block_level } },
+ .{ .visibility = .{ .display = .grid, .box = .inline_level } },
.{ .geometry = .{ .width = .{ .unit = .content } }, .flow = .{ .absolutely_positioned = true, .floated = true } },
.{ .geometry = .{ .width = .{ .unit = .content } }, .flow = .{ .absolutely_positioned = false, .floated = false } },
};
@@ -2471,7 +2700,7 @@ test "StyleManager: memo: inherited values, any query order" {
try testing.expectEqual(6, sm.visibility.memo.count());
try testing.expectEqual(Visibility.Computed{ .visibility_hidden = true, .pointer_events_none = true, .in_opacity_zero = true }, sm.visibility.memo.get(u).?);
try testing.expectEqual(Visibility.Computed{ .visibility_hidden = true, .pointer_events_none = true }, sm.visibility.memo.get(i).?);
- try testing.expectEqual(Visibility.Computed{}, sm.visibility.memo.get(p).?);
+ try testing.expectEqual(Visibility.Computed{ .box = .block_level }, sm.visibility.memo.get(p).?);
try testing.expectEqual(false, sm.isHidden(u, .{}));
try testing.expectEqual(true, sm.isHidden(u, .{ .check_visibility = true }));
diff --git a/src/browser/tests/element/position.html b/src/browser/tests/element/position.html
index 76ef84db9..6bcfa3197 100644
--- a/src/browser/tests/element/position.html
+++ b/src/browser/tests/element/position.html
@@ -43,9 +43,18 @@
document.body.appendChild(empty);
testing.expectEqual(empty.clientWidth, empty.scrollWidth);
- // Each added child strictly increases scrollWidth, and enough of them push
- // it past the element's own box.
+ // A block in normal flow is as wide as its container however little it
+ // holds; inline children share one line, so a few of them don't overflow.
+ const block = document.createElement('div');
+ document.body.appendChild(block);
+ block.appendChild(document.createElement('span'));
+ testing.expectEqual(document.body.clientWidth, block.clientWidth);
+ testing.expectEqual(block.clientWidth, block.scrollWidth);
+
+ // A shrink-to-fit box follows its content: each added child strictly
+ // increases scrollWidth, and clientWidth tracks the same sum.
const box = document.createElement('div');
+ box.style.display = 'inline-block';
document.body.appendChild(box);
box.appendChild(document.createElement('span'));
const oneChild = box.scrollWidth;
@@ -53,7 +62,6 @@
box.appendChild(document.createElement('span'));
testing.expectTrue(box.scrollWidth > oneChild);
- // An unsized box shrink-wraps: clientWidth tracks the same content sum.
testing.expectEqual(box.scrollWidth, box.clientWidth);
// Text contributes nothing, however long. Estimating a run from its length
@@ -116,9 +124,12 @@
{
// Regression: the infinite-marquee idiom duplicates content until it is
// twice the width of its container. scrollWidth has to respond to the
- // insertion or the loop never terminates.
+ // insertion or the loop never terminates. The lane is a non-wrapping strip,
+ // as on the sites: a block lane would wrap its items and never outgrow the
+ // track in a real browser either.
const track = document.createElement('div');
const lane = document.createElement('div');
+ lane.style.cssText = 'display: inline-block; white-space: nowrap';
lane.innerHTML = '<span>item</span>';
track.appendChild(lane);
document.body.appendChild(track);
@@ -140,12 +151,15 @@
<script id="clientWidthMarqueeLoop">
{
// The clientWidth variant of the marquee idiom (amivoice.com): clone items
- // into an unsized wrap until it is twice the width of its container.
+ // into a shrink-to-fit wrap until it is twice the width of its container.
// clientWidth of the wrap has to respond to the insertion, while the
// container — whose direct child is the wrap, not the items — must not
- // grow in lockstep or the loop still never terminates.
+ // grow in lockstep or the loop still never terminates. The container is
+ // narrow so the guard stays small: an item without text measures 5px.
const container = document.createElement('div');
+ container.style.width = '100px';
const wrap = document.createElement('div');
+ wrap.style.display = 'inline-block';
const item = document.createElement('span');
wrap.appendChild(item);
container.appendChild(wrap);
@@ -255,7 +269,9 @@
// carry the same content fallback as clientWidth or the loop never
// terminates.
const container = document.createElement('div');
+ container.style.width = '100px';
const wrap = document.createElement('div');
+ wrap.style.display = 'inline-block';
const item = document.createElement('span');
wrap.appendChild(item);
container.appendChild(wrap);
@@ -288,10 +304,12 @@
{
// A marquee clones its item into a block-level flex container until there
// are ceil(container / item) + 2 of them, re-reading both widths after each
- // clone.
+ // clone. The container must not grow with its items. It is narrow so the
+ // guard stays small: an item without a declared width measures 5px.
const width = (el) => el.getBoundingClientRect().width;
const container = document.createElement('div');
container.className = 'flex-row';
+ container.style.width = '100px';
const item = document.createElement('div');
item.textContent = 'item';
container.appendChild(item);
@@ -307,6 +325,270 @@
}
</script>
+<script id="widthFlowsDown">
+{
+ // A block in normal flow is as wide as its containing block, whatever it
+ // holds; the width flows down from the root rather than up from the
+ // children. A carousel shell holding a flex track of fixed slides reports
+ // the page width, so slides-per-page is never 0 (and pages never Infinity).
+ const section = document.createElement('div');
+ const shell = document.createElement('div');
+ shell.style.overflow = 'hidden';
+ const track = document.createElement('div');
+ track.className = 'flex-row';
+ for (let i = 0; i < 24; i++) {
+ const slide = document.createElement('div');
+ slide.style.cssText = 'width: 300px; flex-shrink: 0';
+ track.appendChild(slide);
+ }
+ shell.appendChild(track);
+ section.appendChild(shell);
+ document.body.appendChild(section);
+
+ testing.expectEqual(document.body.offsetWidth, shell.offsetWidth);
+ testing.expectEqual(document.body.offsetWidth, track.offsetWidth);
+ testing.expectEqual(7200, track.scrollWidth);
+ // The track doesn't clip, so its overflow is the shell's scrollable area
+ testing.expectEqual(7200, shell.scrollWidth);
+ track.style.overflowX = 'auto';
+ testing.expectEqual(shell.offsetWidth, shell.scrollWidth);
+
+ const perPage = Math.floor(shell.offsetWidth / 320);
+ testing.expectTrue(perPage >= 1);
+ testing.expectEqual(Math.ceil(24 / perPage), 4);
+
+ // Percentages and intermediate auto blocks resolve against the ancestor
+ section.style.width = '700px';
+ testing.expectEqual(700, shell.offsetWidth);
+ shell.style.width = '50%';
+ testing.expectEqual(350, shell.offsetWidth);
+ testing.expectEqual(350, track.offsetWidth);
+ section.remove();
+}
+</script>
+
+<script id="shrinkToFitBoxes">
+{
+ // Inline-level, floated, absolutely positioned, intrinsically sized and
+ // replaced boxes follow their content instead of filling the container.
+ const section = document.createElement('div');
+ section.style.width = '700px';
+ document.body.appendChild(section);
+ for (const css of ['display: inline-block', 'display: inline-flex', 'display: inline-grid', 'display: table', 'position: absolute', 'position: fixed', 'float: left', 'width: max-content', 'width: min-content', 'width: fit-content']) {
+ const box = document.createElement('div');
+ box.style.cssText = css;
+ const child = document.createElement('div');
+ child.style.width = '40px';
+ box.appendChild(child);
+ section.appendChild(box);
+ testing.expectEqual(40, box.offsetWidth, css);
+ box.remove();
+ }
+ // Custom elements are inline by default; a declared display: block fills
+ const custom = document.createElement('my-widget');
+ section.appendChild(custom);
+ testing.expectEqual(5, custom.offsetWidth);
+ custom.style.display = 'block';
+ testing.expectEqual(700, custom.offsetWidth);
+ section.remove();
+}
+</script>
+
+<script id="flexAndGridItemWidths">
+{
+ // Row-flex items shrink to their content unless they grow, in which case
+ // they share the row's free space (#3921: a flex:1 pane beside a 40px menu
+ // in an 800px row is 760px, not 5). Column-flex and grid items stretch.
+ const row = document.createElement('div');
+ row.style.cssText = 'display: flex; width: 800px';
+ const menu = document.createElement('div');
+ menu.style.cssText = 'width: 40px; flex-shrink: 0';
+ const pane = document.createElement('div');
+ pane.style.cssText = 'flex: 1; min-width: 0';
+ row.append(menu, pane);
+ document.body.appendChild(row);
+ testing.expectEqual(760, pane.offsetWidth);
+ testing.expectEqual(760, pane.getBoundingClientRect().width);
+
+ const second = document.createElement('div');
+ second.style.flexGrow = '1';
+ row.appendChild(second);
+ testing.expectEqual(380, pane.offsetWidth);
+ testing.expectEqual(380, second.offsetWidth);
+
+ const fixedItem = document.createElement('div');
+ fixedItem.appendChild(document.createElement('span'));
+ row.appendChild(fixedItem);
+ testing.expectEqual(5, fixedItem.offsetWidth);
+ row.remove();
+
+ const column = document.createElement('div');
+ column.style.cssText = 'display: flex; flex-direction: column; width: 600px';
+ const item = document.createElement('div');
+ column.appendChild(item);
+ document.body.appendChild(column);
+ testing.expectEqual(600, item.offsetWidth);
+ column.style.flexFlow = 'column wrap';
+ testing.expectEqual(600, item.offsetWidth);
+ column.remove();
+
+ const grid = document.createElement('div');
+ grid.style.cssText = 'display: grid; width: 600px';
+ const cell = document.createElement('div');
+ grid.appendChild(cell);
+ document.body.appendChild(grid);
+ testing.expectEqual(600, cell.offsetWidth);
+ grid.remove();
+}
+</script>
+
+<script id="displayContentsIsTransparent">
+{
+ // display: contents generates no box: it reports no size, and its children
+ // resolve against the nearest ancestor that does.
+ const section = document.createElement('div');
+ section.style.width = '700px';
+ const contents = document.createElement('div');
+ contents.style.display = 'contents';
+ const child = document.createElement('div');
+ contents.appendChild(child);
+ section.appendChild(contents);
+ document.body.appendChild(section);
+ testing.expectEqual(0, contents.offsetWidth);
+ testing.expectEqual(700, child.offsetWidth);
+ section.remove();
+}
+</script>
+
+<script id="growShareAfterPercentSiblings">
+{
+ // A percentage sibling takes its share of the row before the growers
+ // split what's left, and its percentage limits count too.
+ const row = document.createElement('div');
+ row.style.cssText = 'display: flex; width: 800px';
+ const sidebar = document.createElement('div');
+ sidebar.style.cssText = 'width: 25%; flex-shrink: 0';
+ const pane = document.createElement('div');
+ pane.style.flex = '1';
+ row.append(sidebar, pane);
+ document.body.appendChild(row);
+ testing.expectEqual(200, sidebar.offsetWidth);
+ testing.expectEqual(600, pane.offsetWidth);
+
+ sidebar.style.cssText = 'min-width: 50%; flex-shrink: 0';
+ testing.expectEqual(400, pane.offsetWidth);
+
+ // display: contents lends its children to the row
+ sidebar.style.cssText = 'display: contents';
+ const fixed = document.createElement('div');
+ fixed.style.cssText = 'width: 100px; flex-shrink: 0';
+ sidebar.appendChild(fixed);
+ testing.expectEqual(700, pane.offsetWidth);
+ row.remove();
+}
+</script>
+
+<script id="growingItemInShrinkToFitRow">
+{
+ // The row sizes from its items and a growing item from the row: the row
+ // takes the item's content, the item fills what's left of the row.
+ const row = document.createElement('span');
+ row.style.display = 'inline-flex';
+ const item = document.createElement('div');
+ item.style.flexGrow = '1';
+ const child = document.createElement('div');
+ child.style.width = '40px';
+ item.appendChild(child);
+ row.appendChild(item);
+ document.body.appendChild(row);
+ testing.expectEqual(40, row.offsetWidth);
+ testing.expectEqual(40, item.offsetWidth);
+ row.remove();
+}
+</script>
+
+<script id="minAndMaxWidth">
+{
+ const section = document.createElement('div');
+ section.style.width = '1000px';
+ const box = document.createElement('div');
+ section.appendChild(box);
+ document.body.appendChild(section);
+
+ // A filling block is capped, in px or against the containing block
+ box.style.maxWidth = '600px';
+ testing.expectEqual(600, box.offsetWidth);
+ testing.expectEqual(600, box.clientWidth);
+ testing.expectEqual(600, box.getBoundingClientRect().width);
+ box.style.maxWidth = '50%';
+ testing.expectEqual(500, box.offsetWidth);
+ box.style.maxWidth = 'none';
+ testing.expectEqual(1000, box.offsetWidth);
+
+ // An explicit width is clamped too; min-width wins over max-width
+ box.style.width = '2000px';
+ box.style.maxWidth = '100%';
+ testing.expectEqual(1000, box.offsetWidth);
+ box.style.minWidth = '1200px';
+ testing.expectEqual(1200, box.offsetWidth);
+
+ // A shrink-to-fit box grows to its min-width
+ box.style.cssText = 'display: inline-block; min-width: 300px';
+ testing.expectEqual(300, box.offsetWidth);
+
+ // A capped child caps what it adds to a shrink-to-fit parent
+ const parent = document.createElement('div');
+ parent.style.display = 'inline-block';
+ const wide = document.createElement('div');
+ wide.style.cssText = 'width: 800px; max-width: 200px';
+ parent.appendChild(wide);
+ section.appendChild(parent);
+ testing.expectEqual(200, parent.offsetWidth);
+
+ // A percentage limit inside a shrink-to-fit parent doesn't limit what
+ // the child adds: there is no width yet to take a percentage of
+ wide.style.maxWidth = '10%';
+ testing.expectEqual(800, parent.offsetWidth);
+ testing.expectEqual(80, wide.offsetWidth);
+
+ // The rule a carousel uses: slides capped by the viewport
+ const style = document.createElement('style');
+ style.textContent = '.capped { max-width: 320px }';
+ document.head.appendChild(style);
+ box.style.cssText = '';
+ box.className = 'capped';
+ testing.expectEqual(320, box.offsetWidth);
+ style.remove();
+ testing.expectEqual(1000, box.offsetWidth);
+ section.remove();
+}
+</script>
+
+<script id="widthsAcrossFrames">
+{
+ // Read from the parent, an iframe's elements size within their own document
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const doc = iframe.contentDocument;
+ const section = doc.createElement('div');
+ section.style.width = '300px';
+ const block = doc.createElement('div');
+ block.style.maxWidth = '50%';
+ const inline = doc.createElement('span');
+ inline.style.display = 'inline-block';
+ const child = doc.createElement('div');
+ child.style.width = '40px';
+ inline.appendChild(child);
+ section.append(block, inline);
+ doc.body.appendChild(section);
+ testing.expectEqual(300, section.offsetWidth);
+ testing.expectEqual(150, block.offsetWidth);
+ testing.expectEqual(40, inline.offsetWidth);
+ testing.expectEqual(300, section.scrollWidth);
+ iframe.remove();
+}
+</script>
+
<script id="boxesSizedByTheirItems">
{
const grows = (setup) => {
@@ -628,14 +910,15 @@
deep.id = 'deep';
document.body.appendChild(deep);
- // Room to scroll it to the top
- const room = document.createElement('div');
- room.style.height = '10000px';
- document.body.appendChild(room);
-
const targetY = deep.getBoundingClientRect().y;
testing.expectTrue(targetY > 0);
+ // Room to scroll it to the top. The position counts every preceding node,
+ // the document height only body's children, so size the room to the target.
+ const room = document.createElement('div');
+ room.style.height = `${targetY + window.innerHeight}px`;
+ document.body.appendChild(room);
+
// scrollIntoView() always brings the element's top to the scroll offset.
window.scrollTo(0, 999999);
deep.scrollIntoView();
diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zig
index 42d4bbd8c..99e2051e4 100644
--- a/src/browser/webapi/Element.zig
+++ b/src/browser/webapi/Element.zig
@@ -23,6 +23,7 @@ const js = @import("../js/js.zig");
const dump = @import("../dump.zig");
const Frame = @import("../Frame.zig");
const Factory = @import("../Factory.zig");
+const StyleManager = @import("../StyleManager.zig");
const text_measure = @import("../text_measure.zig");
const CSS = @import("CSS.zig");
@@ -1707,6 +1708,11 @@ fn viewportAxis(self: *Element, frame: *Frame, comptime axis: Axis) ?f64 {
// Caller must have made sure self is visible.
pub fn boxAxis(self: *Element, frame: *Frame, comptime axis: Axis) f64 {
+ if (axis == .width) {
+ const owner = self.ownerFrame(frame) orelse return self.getElementAxis(frame, .width).value;
+ return self.boxWidth(owner);
+ }
+
const own = self.getElementAxis(frame, axis);
if (own.explicit) {
// an explicitly set value always wins
@@ -1717,15 +1723,134 @@ pub fn boxAxis(self: *Element, frame: *Frame, comptime axis: Axis) f64 {
// html/body return their set value regardless of children.
return own.value;
}
+ return @max(own.value, self.contentAxis(frame, axis));
+}
- if (axis == .width) {
- const owner = self.ownerFrame(frame) orelse return own.value;
- if (owner._style_manager.widthFromContainingBlock(self)) {
- return own.value;
+// Width flows down (height flows up): a block in normal flow is as wide as
+// its containing block.
+fn boxWidth(self: *Element, owner: *Frame) f64 {
+ const style_manager = &owner._style_manager;
+ if (style_manager.cachedWidth(self, .box)) |width| {
+ return width;
+ }
+
+ const own = self.getElementAxis(owner, .width);
+ const width = blk: {
+ if (self.isRootContainer()) {
+ // html/body return their set value regardless of children.
+ break :blk own.value;
}
+ const width = if (own.explicit) own.value else switch (style_manager.widthSizing(self)) {
+ .fixed => |width| width,
+ .percent => |fraction| fraction * self.containingBlockWidth(owner),
+ .fill => self.containingBlockWidth(owner),
+ .grow => @max(self.growShare(owner), self.contentWidth(owner)),
+ .shrink => @max(own.value, self.contentWidth(owner)),
+ .contents => break :blk 0,
+ };
+ break :blk self.clampWidth(width, .box, owner);
+ };
+ style_manager.cacheWidth(self, .box, width);
+ return width;
+}
+
+// What the box adds to its parent's content width.
+fn widthContribution(self: *Element, owner: *Frame) f64 {
+ const style_manager = &owner._style_manager;
+ const own = self.getElementAxis(owner, .width);
+ const width = if (own.explicit) own.value else switch (style_manager.widthSizing(self)) {
+ .fixed => |width| width,
+ .shrink, .grow => @max(own.value, self.contentWidth(owner)),
+ .percent, .fill => if (style_manager.clipsOverflowX(self)) 0 else self.contentWidth(owner),
+ .contents => return self.contentWidth(owner),
+ };
+ return self.clampWidth(width, .contribution, owner);
+}
+
+// max-width caps the width, min-width wins over both.
+fn clampWidth(self: *Element, width: f64, comptime of: enum { box, contribution }, owner: *Frame) f64 {
+ const limits = owner._style_manager.widthLimits(self);
+ var clamped = width;
+ if (limits.max) |max| {
+ clamped = @min(clamped, self.resolveWidthLimit(max, of == .box, owner) orelse clamped);
+ }
+ if (limits.min) |min| {
+ clamped = @max(clamped, self.resolveWidthLimit(min, of == .box, owner) orelse clamped);
}
+ return clamped;
+}
- return @max(own.value, self.contentAxis(frame, axis));
+fn resolveWidthLimit(self: *Element, limit: StyleManager.WidthLimit, resolve_percent: bool, owner: *Frame) ?f64 {
+ return switch (limit) {
+ .px => |px| px,
+ .percent => |fraction| if (resolve_percent) fraction * self.containingBlockWidth(owner) else null,
+ };
+}
+
+/// The width of the nearest ancestor with a box; the viewport above the root.
+fn containingBlockWidth(self: *Element, owner: *Frame) f64 {
+ const parent = owner._style_manager.boxParent(self) orelse {
+ return @floatFromInt(owner.page.getViewport().width);
+ };
+ return parent.boxWidth(owner);
+}
+
+/// A growing flex item's share: the row's free space, after the siblings
+/// that don't grow, split evenly among those that do.
+fn growShare(self: *Element, owner: *Frame) f64 {
+ const style_manager = &owner._style_manager;
+ const parent = style_manager.boxParent(self) orelse return 0;
+ var taken: f64 = 0;
+ var growers: f64 = 0;
+ var children: TreeWalker.FlatChildren = .init(parent.asNode(), .{ .frame = owner });
+ while (children.next()) |node| {
+ const el = node.is(Element) orelse continue;
+ if (style_manager.hasDisplayNone(el)) {
+ continue;
+ }
+ switch (style_manager.widthSizing(el)) {
+ .grow => growers += 1,
+ // Its children are the row's items
+ .contents => taken += el.widthContribution(owner),
+ // Only walks up, and the row's width never reads a child's box
+ else => taken += el.boxWidth(owner),
+ }
+ }
+ return @max(0, parent.boxWidth(owner) - taken) / @max(1, growers);
+}
+
+// The width the children would take unconstrained: the sum of their
+// contributions. In a flex row or grid they sit side by side; elsewhere
+// block-level children stack, so the widest counts, and inline-level ones
+// share one line that never wraps (the dummy layout has no line breaking,
+// which keeps the "append until the lane outgrows its shell" idiom
+// terminating).
+fn contentWidth(self: *Element, owner: *Frame) f64 {
+ const style_manager = &owner._style_manager;
+ if (style_manager.cachedWidth(self, .content)) |width| {
+ return width;
+ }
+
+ const in_row = style_manager.laysOutInRow(self);
+ var widest: f64 = 0;
+ var line: f64 = 0;
+ var children: TreeWalker.FlatChildren = .init(self.asNode(), .{ .frame = owner });
+ while (children.next()) |node| {
+ const el = node.is(Element) orelse continue;
+ if (style_manager.hasDisplayNone(el)) {
+ continue;
+ }
+ const width = el.widthContribution(owner);
+ if (in_row or style_manager.isBlockLevel(el) == false) {
+ line += width;
+ } else {
+ widest = @max(widest, line, width);
+ line = 0;
+ }
+ }
+ const width = @max(widest, line);
+ style_manager.cacheWidth(self, .content, width);
+ return width;
}
pub fn getBoundingClientRect(self: *Element, frame: *Frame) !*DOMRect {
@@ -1843,15 +1968,14 @@ pub fn getScrollWidth(self: *Element, frame: *Frame) f64 {
return 0.0;
}
- const width = self.getElementAxis(frame, .width).value;
-
// Roots don't sum their children side by side. The root scroller
// reports what the viewport scrolls over.
if (self.isRootContainer()) {
- return self.rootScrollSize(frame, .width) orelse width;
+ return self.rootScrollSize(frame, .width) orelse self.getElementAxis(frame, .width).value;
}
- return @max(width, self.contentAxis(frame, .width));
+ const owner = self.ownerFrame(frame) orelse return self.getElementAxis(frame, .width).value;
+ return @max(self.boxWidth(owner), self.contentWidth(owner));
}
/// Null where we can't prove a limit, which leaves the offset unbounded:
@@ -2628,6 +2752,15 @@ pub const Tag = enum {
// zig fmt: on
}
+ // Replaced elements and form controls: sized by what they show, never
+ // stretched to their container.
+ pub fn isReplacedOrControl(self: Tag) bool {
+ return switch (self) {
+ .img, .iframe, .canvas, .video, .audio, .media, .object, .embed, .svg, .input, .select, .textarea, .button, .meter, .progress => true,
+ else => false,
+ };
+ }
+
pub fn isMetadata(self: Tag) bool {
return switch (self) {
.base, .head, .link, .meta, .noscript, .script, .style, .template, .title => true,
diff --git a/src/server/cdp/domains/dom.zig b/src/server/cdp/domains/dom.zig
index 5919676c1..8f83e821c 100644
--- a/src/server/cdp/domains/dom.zig
+++ b/src/server/cdp/domains/dom.zig
@@ -1584,12 +1584,13 @@ test "cdp.dom: getBoxModel" {
.method = "DOM.getBoxModel",
.params = .{ .nodeId = 3 },
});
+ // A block in normal flow is as wide as the body.
try ctx.expectSentResult(.{ .model = BoxModel{
- .content = Quad{ 0.0, 25.0, 5.0, 25.0, 5.0, 30.0, 0.0, 30.0 },
- .padding = Quad{ 0.0, 25.0, 5.0, 25.0, 5.0, 30.0, 0.0, 30.0 },
- .border = Quad{ 0.0, 25.0, 5.0, 25.0, 5.0, 30.0, 0.0, 30.0 },
- .margin = Quad{ 0.0, 25.0, 5.0, 25.0, 5.0, 30.0, 0.0, 30.0 },
- .width = 5,
+ .content = Quad{ 0.0, 25.0, 1920.0, 25.0, 1920.0, 30.0, 0.0, 30.0 },
+ .padding = Quad{ 0.0, 25.0, 1920.0, 25.0, 1920.0, 30.0, 0.0, 30.0 },
+ .border = Quad{ 0.0, 25.0, 1920.0, 25.0, 1920.0, 30.0, 0.0, 30.0 },
+ .margin = Quad{ 0.0, 25.0, 1920.0, 25.0, 1920.0, 30.0, 0.0, 30.0 },
+ .width = 1920,
.height = 5,
} }, .{ .id = 5 });
}