//! Block layout engine: box generation, block/inline layout, and text wrapping.
//!
//! Builds a layout tree from a styled tree (DOM + computed styles) and positions
//! block-level elements vertically with proper inline formatting context.
use std::collections::HashMap;
use we_css::values::Color;
use we_dom::{Document, NodeData, NodeId};
use we_style::computed::{
BorderStyle, BoxSizing, ComputedStyle, Display, LengthOrAuto, Overflow, Position, StyledNode,
TextAlign, TextDecoration, Visibility,
};
use we_text::font::Font;
/// Width of scroll bars in pixels.
pub const SCROLLBAR_WIDTH: f32 = 15.0;
/// Edge sizes for box model (margin, padding, border).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct EdgeSizes {
pub top: f32,
pub right: f32,
pub bottom: f32,
pub left: f32,
}
/// A positioned rectangle with content area dimensions.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Rect {
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
}
/// The type of layout box.
#[derive(Debug)]
pub enum BoxType {
/// Block-level box from an element.
Block(NodeId),
/// Inline-level box from an element.
Inline(NodeId),
/// A run of text from a text node.
TextRun { node: NodeId, text: String },
/// Anonymous block wrapping inline content within a block container.
Anonymous,
}
/// A single positioned text fragment with its own styling.
///
/// Multiple fragments can share the same y-coordinate when they are
/// on the same visual line (e.g. `
Hello world
` produces
/// two fragments at the same y).
#[derive(Debug, Clone, PartialEq)]
pub struct TextLine {
pub text: String,
pub x: f32,
pub y: f32,
pub width: f32,
pub font_size: f32,
pub color: Color,
pub text_decoration: TextDecoration,
pub background_color: Color,
}
/// A box in the layout tree with dimensions and child boxes.
#[derive(Debug)]
pub struct LayoutBox {
pub box_type: BoxType,
pub rect: Rect,
pub margin: EdgeSizes,
pub padding: EdgeSizes,
pub border: EdgeSizes,
pub children: Vec,
pub font_size: f32,
/// Positioned text fragments (populated for boxes with inline content).
pub lines: Vec,
/// Text color.
pub color: Color,
/// Background color.
pub background_color: Color,
/// Text decoration (underline, etc.).
pub text_decoration: TextDecoration,
/// Border styles (top, right, bottom, left).
pub border_styles: [BorderStyle; 4],
/// Border colors (top, right, bottom, left).
pub border_colors: [Color; 4],
/// Text alignment for this box's inline content.
pub text_align: TextAlign,
/// Computed line height in px.
pub line_height: f32,
/// For replaced elements (e.g., `
`): content dimensions (width, height).
pub replaced_size: Option<(f32, f32)>,
/// CSS `position` property.
pub position: Position,
/// Relative position offset (dx, dy) applied after normal flow layout.
pub relative_offset: (f32, f32),
/// CSS `overflow` property.
pub overflow: Overflow,
/// CSS `box-sizing` property.
pub box_sizing: BoxSizing,
/// CSS `width` property (explicit or auto, may contain percentage).
pub css_width: LengthOrAuto,
/// CSS `height` property (explicit or auto, may contain percentage).
pub css_height: LengthOrAuto,
/// CSS margin values (may contain percentages for layout resolution).
pub css_margin: [LengthOrAuto; 4],
/// CSS padding values (may contain percentages for layout resolution).
pub css_padding: [LengthOrAuto; 4],
/// CSS position offset values (top, right, bottom, left) for relative positioning.
pub css_offsets: [LengthOrAuto; 4],
/// CSS `visibility` property.
pub visibility: Visibility,
/// Natural content height before CSS height override.
/// Used to determine overflow for scroll containers.
pub content_height: f32,
}
impl LayoutBox {
fn new(box_type: BoxType, style: &ComputedStyle) -> Self {
LayoutBox {
box_type,
rect: Rect::default(),
margin: EdgeSizes::default(),
padding: EdgeSizes::default(),
border: EdgeSizes::default(),
children: Vec::new(),
font_size: style.font_size,
lines: Vec::new(),
color: style.color,
background_color: style.background_color,
text_decoration: style.text_decoration,
border_styles: [
style.border_top_style,
style.border_right_style,
style.border_bottom_style,
style.border_left_style,
],
border_colors: [
style.border_top_color,
style.border_right_color,
style.border_bottom_color,
style.border_left_color,
],
text_align: style.text_align,
line_height: style.line_height,
replaced_size: None,
position: style.position,
relative_offset: (0.0, 0.0),
overflow: style.overflow,
box_sizing: style.box_sizing,
css_width: style.width,
css_height: style.height,
css_margin: [
style.margin_top,
style.margin_right,
style.margin_bottom,
style.margin_left,
],
css_padding: [
style.padding_top,
style.padding_right,
style.padding_bottom,
style.padding_left,
],
css_offsets: [style.top, style.right, style.bottom, style.left],
visibility: style.visibility,
content_height: 0.0,
}
}
/// Total height including margin, border, and padding.
pub fn margin_box_height(&self) -> f32 {
self.margin.top
+ self.border.top
+ self.padding.top
+ self.rect.height
+ self.padding.bottom
+ self.border.bottom
+ self.margin.bottom
}
/// Iterate over all boxes in depth-first pre-order.
pub fn iter(&self) -> LayoutBoxIter<'_> {
LayoutBoxIter { stack: vec![self] }
}
}
/// Depth-first pre-order iterator over layout boxes.
pub struct LayoutBoxIter<'a> {
stack: Vec<&'a LayoutBox>,
}
impl<'a> Iterator for LayoutBoxIter<'a> {
type Item = &'a LayoutBox;
fn next(&mut self) -> Option<&'a LayoutBox> {
let node = self.stack.pop()?;
for child in node.children.iter().rev() {
self.stack.push(child);
}
Some(node)
}
}
/// The result of laying out a document.
#[derive(Debug)]
pub struct LayoutTree {
pub root: LayoutBox,
pub width: f32,
pub height: f32,
}
impl LayoutTree {
/// Iterate over all layout boxes in depth-first pre-order.
pub fn iter(&self) -> LayoutBoxIter<'_> {
self.root.iter()
}
}
// ---------------------------------------------------------------------------
// Resolve LengthOrAuto to f32
// ---------------------------------------------------------------------------
/// Resolve a `LengthOrAuto` to px. Percentages are resolved against
/// `reference` (typically the containing block width). Auto resolves to 0.
fn resolve_length_against(value: LengthOrAuto, reference: f32) -> f32 {
match value {
LengthOrAuto::Length(px) => px,
LengthOrAuto::Percentage(p) => p / 100.0 * reference,
LengthOrAuto::Auto => 0.0,
}
}
/// Resolve horizontal offset for `position: relative`.
/// If both `left` and `right` are specified, `left` wins (CSS2 §9.4.3, ltr).
fn resolve_relative_horizontal(left: LengthOrAuto, right: LengthOrAuto, cb_width: f32) -> f32 {
match left {
LengthOrAuto::Length(px) => px,
LengthOrAuto::Percentage(p) => p / 100.0 * cb_width,
LengthOrAuto::Auto => match right {
LengthOrAuto::Length(px) => -px,
LengthOrAuto::Percentage(p) => -(p / 100.0 * cb_width),
LengthOrAuto::Auto => 0.0,
},
}
}
/// Resolve vertical offset for `position: relative`.
/// If both `top` and `bottom` are specified, `top` wins (CSS2 §9.4.3).
fn resolve_relative_vertical(top: LengthOrAuto, bottom: LengthOrAuto, cb_height: f32) -> f32 {
match top {
LengthOrAuto::Length(px) => px,
LengthOrAuto::Percentage(p) => p / 100.0 * cb_height,
LengthOrAuto::Auto => match bottom {
LengthOrAuto::Length(px) => -px,
LengthOrAuto::Percentage(p) => -(p / 100.0 * cb_height),
LengthOrAuto::Auto => 0.0,
},
}
}
// ---------------------------------------------------------------------------
// Build layout tree from styled tree
// ---------------------------------------------------------------------------
fn build_box(
styled: &StyledNode,
doc: &Document,
image_sizes: &HashMap,
) -> Option {
let node = styled.node;
let style = &styled.style;
match doc.node_data(node) {
NodeData::Document => {
let mut children = Vec::new();
for child in &styled.children {
if let Some(child_box) = build_box(child, doc, image_sizes) {
children.push(child_box);
}
}
if children.len() == 1 {
children.into_iter().next()
} else if children.is_empty() {
None
} else {
let mut b = LayoutBox::new(BoxType::Anonymous, style);
b.children = children;
Some(b)
}
}
NodeData::Element { .. } => {
if style.display == Display::None {
return None;
}
// Margin and padding: resolve absolute lengths now; percentages
// will be re-resolved in compute_layout against containing block.
// Use 0.0 as a placeholder reference for percentages — they'll be
// resolved properly in compute_layout.
let margin = EdgeSizes {
top: resolve_length_against(style.margin_top, 0.0),
right: resolve_length_against(style.margin_right, 0.0),
bottom: resolve_length_against(style.margin_bottom, 0.0),
left: resolve_length_against(style.margin_left, 0.0),
};
let padding = EdgeSizes {
top: resolve_length_against(style.padding_top, 0.0),
right: resolve_length_against(style.padding_right, 0.0),
bottom: resolve_length_against(style.padding_bottom, 0.0),
left: resolve_length_against(style.padding_left, 0.0),
};
let border = EdgeSizes {
top: if style.border_top_style != BorderStyle::None {
style.border_top_width
} else {
0.0
},
right: if style.border_right_style != BorderStyle::None {
style.border_right_width
} else {
0.0
},
bottom: if style.border_bottom_style != BorderStyle::None {
style.border_bottom_width
} else {
0.0
},
left: if style.border_left_style != BorderStyle::None {
style.border_left_width
} else {
0.0
},
};
let mut children = Vec::new();
for child in &styled.children {
if let Some(child_box) = build_box(child, doc, image_sizes) {
children.push(child_box);
}
}
let box_type = match style.display {
Display::Block => BoxType::Block(node),
Display::Inline => BoxType::Inline(node),
Display::None => unreachable!(),
};
if style.display == Display::Block {
children = normalize_children(children, style);
}
let mut b = LayoutBox::new(box_type, style);
b.margin = margin;
b.padding = padding;
b.border = border;
b.children = children;
// Check for replaced element (e.g.,
).
if let Some(&(w, h)) = image_sizes.get(&node) {
b.replaced_size = Some((w, h));
}
// Relative position offsets are resolved in compute_layout
// where the containing block dimensions are known.
Some(b)
}
NodeData::Text { data } => {
let collapsed = collapse_whitespace(data);
if collapsed.is_empty() {
return None;
}
Some(LayoutBox::new(
BoxType::TextRun {
node,
text: collapsed,
},
style,
))
}
NodeData::Comment { .. } => None,
}
}
/// Collapse runs of whitespace to a single space.
fn collapse_whitespace(s: &str) -> String {
let mut result = String::new();
let mut in_ws = false;
for ch in s.chars() {
if ch.is_whitespace() {
if !in_ws {
result.push(' ');
}
in_ws = true;
} else {
in_ws = false;
result.push(ch);
}
}
result
}
/// If a block container has a mix of block-level and inline-level children,
/// wrap consecutive inline runs in anonymous block boxes.
fn normalize_children(children: Vec, parent_style: &ComputedStyle) -> Vec {
if children.is_empty() {
return children;
}
let has_block = children.iter().any(is_block_level);
if !has_block {
return children;
}
let has_inline = children.iter().any(|c| !is_block_level(c));
if !has_inline {
return children;
}
let mut result = Vec::new();
let mut inline_group: Vec = Vec::new();
for child in children {
if is_block_level(&child) {
if !inline_group.is_empty() {
let mut anon = LayoutBox::new(BoxType::Anonymous, parent_style);
anon.children = std::mem::take(&mut inline_group);
result.push(anon);
}
result.push(child);
} else {
inline_group.push(child);
}
}
if !inline_group.is_empty() {
let mut anon = LayoutBox::new(BoxType::Anonymous, parent_style);
anon.children = inline_group;
result.push(anon);
}
result
}
fn is_block_level(b: &LayoutBox) -> bool {
matches!(b.box_type, BoxType::Block(_) | BoxType::Anonymous)
}
// ---------------------------------------------------------------------------
// Layout algorithm
// ---------------------------------------------------------------------------
/// Position and size a layout box within `available_width` at position (`x`, `y`).
///
/// `available_width` is the containing block width — used as the reference for
/// percentage widths, margins, and paddings (per CSS spec, even vertical margins/
/// padding resolve against the containing block width).
fn compute_layout(
b: &mut LayoutBox,
x: f32,
y: f32,
available_width: f32,
viewport_height: f32,
font: &Font,
doc: &Document,
) {
// Resolve percentage margins against containing block width.
// Only re-resolve percentages — absolute margins may have been modified
// by margin collapsing and must not be overwritten.
if matches!(b.css_margin[0], LengthOrAuto::Percentage(_)) {
b.margin.top = resolve_length_against(b.css_margin[0], available_width);
}
if matches!(b.css_margin[1], LengthOrAuto::Percentage(_)) {
b.margin.right = resolve_length_against(b.css_margin[1], available_width);
}
if matches!(b.css_margin[2], LengthOrAuto::Percentage(_)) {
b.margin.bottom = resolve_length_against(b.css_margin[2], available_width);
}
if matches!(b.css_margin[3], LengthOrAuto::Percentage(_)) {
b.margin.left = resolve_length_against(b.css_margin[3], available_width);
}
// Resolve percentage padding against containing block width.
if matches!(b.css_padding[0], LengthOrAuto::Percentage(_)) {
b.padding.top = resolve_length_against(b.css_padding[0], available_width);
}
if matches!(b.css_padding[1], LengthOrAuto::Percentage(_)) {
b.padding.right = resolve_length_against(b.css_padding[1], available_width);
}
if matches!(b.css_padding[2], LengthOrAuto::Percentage(_)) {
b.padding.bottom = resolve_length_against(b.css_padding[2], available_width);
}
if matches!(b.css_padding[3], LengthOrAuto::Percentage(_)) {
b.padding.left = resolve_length_against(b.css_padding[3], available_width);
}
let content_x = x + b.margin.left + b.border.left + b.padding.left;
let content_y = y + b.margin.top + b.border.top + b.padding.top;
let horizontal_extra = b.border.left + b.border.right + b.padding.left + b.padding.right;
// Resolve content width: explicit CSS width (adjusted for box-sizing) or auto.
let content_width = match b.css_width {
LengthOrAuto::Length(w) => match b.box_sizing {
BoxSizing::ContentBox => w.max(0.0),
BoxSizing::BorderBox => (w - horizontal_extra).max(0.0),
},
LengthOrAuto::Percentage(p) => {
let resolved = p / 100.0 * available_width;
match b.box_sizing {
BoxSizing::ContentBox => resolved.max(0.0),
BoxSizing::BorderBox => (resolved - horizontal_extra).max(0.0),
}
}
LengthOrAuto::Auto => {
(available_width - b.margin.left - b.margin.right - horizontal_extra).max(0.0)
}
};
b.rect.x = content_x;
b.rect.y = content_y;
b.rect.width = content_width;
// For overflow:scroll, reserve space for vertical scrollbar.
if b.overflow == Overflow::Scroll {
b.rect.width = (b.rect.width - SCROLLBAR_WIDTH).max(0.0);
}
// Replaced elements (e.g.,
) have intrinsic dimensions.
if let Some((rw, rh)) = b.replaced_size {
b.rect.width = rw.min(b.rect.width);
b.rect.height = rh;
apply_relative_offset(b, available_width, viewport_height);
return;
}
match &b.box_type {
BoxType::Block(_) | BoxType::Anonymous => {
if has_block_children(b) {
layout_block_children(b, viewport_height, font, doc);
} else {
layout_inline_children(b, font, doc);
}
}
BoxType::TextRun { .. } | BoxType::Inline(_) => {
// Handled by the parent's inline layout.
}
}
// Save the natural content height before CSS height override.
b.content_height = b.rect.height;
// Apply explicit CSS height (adjusted for box-sizing), overriding auto height.
match b.css_height {
LengthOrAuto::Length(h) => {
let vertical_extra = b.border.top + b.border.bottom + b.padding.top + b.padding.bottom;
b.rect.height = match b.box_sizing {
BoxSizing::ContentBox => h.max(0.0),
BoxSizing::BorderBox => (h - vertical_extra).max(0.0),
};
}
LengthOrAuto::Percentage(p) => {
// Height percentage resolves against containing block height.
// For the root element, use viewport height.
let cb_height = viewport_height;
let resolved = p / 100.0 * cb_height;
let vertical_extra = b.border.top + b.border.bottom + b.padding.top + b.padding.bottom;
b.rect.height = match b.box_sizing {
BoxSizing::ContentBox => resolved.max(0.0),
BoxSizing::BorderBox => (resolved - vertical_extra).max(0.0),
};
}
LengthOrAuto::Auto => {}
}
apply_relative_offset(b, available_width, viewport_height);
}
/// Apply `position: relative` offset to a box and all its descendants.
///
/// Resolves the CSS position offsets (which may contain percentages) and
/// shifts the visual position without affecting the normal-flow layout.
fn apply_relative_offset(b: &mut LayoutBox, cb_width: f32, cb_height: f32) {
if b.position != Position::Relative {
return;
}
let [top, right, bottom, left] = b.css_offsets;
let dx = resolve_relative_horizontal(left, right, cb_width);
let dy = resolve_relative_vertical(top, bottom, cb_height);
b.relative_offset = (dx, dy);
if dx == 0.0 && dy == 0.0 {
return;
}
shift_box(b, dx, dy);
}
/// Recursively shift a box and all its descendants by (dx, dy).
fn shift_box(b: &mut LayoutBox, dx: f32, dy: f32) {
b.rect.x += dx;
b.rect.y += dy;
for line in &mut b.lines {
line.x += dx;
line.y += dy;
}
for child in &mut b.children {
shift_box(child, dx, dy);
}
}
fn has_block_children(b: &LayoutBox) -> bool {
b.children.iter().any(is_block_level)
}
/// Collapse two adjoining margins per CSS2 §8.3.1.
///
/// Both non-negative → use the larger.
/// Both negative → use the more negative.
/// Mixed → sum the largest positive and most negative.
fn collapse_margins(a: f32, b: f32) -> f32 {
if a >= 0.0 && b >= 0.0 {
a.max(b)
} else if a < 0.0 && b < 0.0 {
a.min(b)
} else {
a + b
}
}
/// Returns `true` if this box establishes a new block formatting context,
/// which prevents its margins from collapsing with children.
fn establishes_bfc(b: &LayoutBox) -> bool {
b.overflow != Overflow::Visible
}
/// Returns `true` if a block box has no in-flow content (empty block).
fn is_empty_block(b: &LayoutBox) -> bool {
b.children.is_empty()
&& b.lines.is_empty()
&& b.replaced_size.is_none()
&& matches!(b.css_height, LengthOrAuto::Auto)
}
/// Pre-collapse parent-child margins (CSS2 §8.3.1).
///
/// When a parent has no border/padding/BFC separating it from its first/last
/// child, the child's margin collapses into the parent's margin. This must
/// happen *before* positioning so the parent is placed using the collapsed
/// value. The function walks bottom-up: children are pre-collapsed first, then
/// their (possibly enlarged) margins are folded into the parent.
fn pre_collapse_margins(b: &mut LayoutBox) {
// Recurse into block children first (bottom-up).
for child in &mut b.children {
if is_block_level(child) {
pre_collapse_margins(child);
}
}
if !matches!(b.box_type, BoxType::Block(_) | BoxType::Anonymous) {
return;
}
if establishes_bfc(b) {
return;
}
if !has_block_children(b) {
return;
}
// --- Top: collapse with first non-empty child ---
if b.border.top == 0.0 && b.padding.top == 0.0 {
if let Some(child_top) = first_block_top_margin(&b.children) {
b.margin.top = collapse_margins(b.margin.top, child_top);
}
}
// --- Bottom: collapse with last non-empty child ---
if b.border.bottom == 0.0 && b.padding.bottom == 0.0 {
if let Some(child_bottom) = last_block_bottom_margin(&b.children) {
b.margin.bottom = collapse_margins(b.margin.bottom, child_bottom);
}
}
}
/// Top margin of the first non-empty block child (already pre-collapsed).
fn first_block_top_margin(children: &[LayoutBox]) -> Option {
for child in children {
if is_block_level(child) {
if is_empty_block(child) {
continue;
}
return Some(child.margin.top);
}
}
// All block children empty — fold all their collapsed margins.
let mut m = 0.0f32;
for child in children.iter().filter(|c| is_block_level(c)) {
m = collapse_margins(m, collapse_margins(child.margin.top, child.margin.bottom));
}
if m != 0.0 {
Some(m)
} else {
None
}
}
/// Bottom margin of the last non-empty block child (already pre-collapsed).
fn last_block_bottom_margin(children: &[LayoutBox]) -> Option {
for child in children.iter().rev() {
if is_block_level(child) {
if is_empty_block(child) {
continue;
}
return Some(child.margin.bottom);
}
}
let mut m = 0.0f32;
for child in children.iter().filter(|c| is_block_level(c)) {
m = collapse_margins(m, collapse_margins(child.margin.top, child.margin.bottom));
}
if m != 0.0 {
Some(m)
} else {
None
}
}
/// Lay out block-level children with vertical margin collapsing (CSS2 §8.3.1).
///
/// Handles adjacent-sibling collapsing, empty-block collapsing, and
/// parent-child internal spacing (the parent's external margins were already
/// updated by `pre_collapse_margins`).
fn layout_block_children(
parent: &mut LayoutBox,
viewport_height: f32,
font: &Font,
doc: &Document,
) {
let content_x = parent.rect.x;
let content_width = parent.rect.width;
let mut cursor_y = parent.rect.y;
let parent_top_open =
parent.border.top == 0.0 && parent.padding.top == 0.0 && !establishes_bfc(parent);
let parent_bottom_open =
parent.border.bottom == 0.0 && parent.padding.bottom == 0.0 && !establishes_bfc(parent);
// Pending bottom margin from the previous sibling.
let mut pending_margin: Option = None;
let child_count = parent.children.len();
for i in 0..child_count {
let child_top_margin = parent.children[i].margin.top;
let child_bottom_margin = parent.children[i].margin.bottom;
// --- Empty block: top+bottom margins self-collapse ---
if is_empty_block(&parent.children[i]) {
let self_collapsed = collapse_margins(child_top_margin, child_bottom_margin);
pending_margin = Some(match pending_margin {
Some(prev) => collapse_margins(prev, self_collapsed),
None => self_collapsed,
});
// Position at cursor_y with zero height.
let child = &mut parent.children[i];
child.rect.x = content_x + child.border.left + child.padding.left;
child.rect.y = cursor_y + child.border.top + child.padding.top;
child.rect.width = (content_width
- child.border.left
- child.border.right
- child.padding.left
- child.padding.right)
.max(0.0);
child.rect.height = 0.0;
continue;
}
// --- Compute effective top spacing ---
let collapsed_top = if let Some(prev_bottom) = pending_margin.take() {
// Sibling collapsing: previous bottom vs this top.
collapse_margins(prev_bottom, child_top_margin)
} else if i == 0 && parent_top_open {
// First child, parent top open: margin was already pulled into
// parent by pre_collapse_margins — no internal spacing.
0.0
} else {
child_top_margin
};
// `compute_layout` adds `child.margin.top` internally, so compensate.
let y_for_child = cursor_y + collapsed_top - child_top_margin;
compute_layout(
&mut parent.children[i],
content_x,
y_for_child,
content_width,
viewport_height,
font,
doc,
);
let child = &parent.children[i];
// Use the normal-flow position (before relative offset) so that
// `position: relative` does not affect sibling placement.
let (_, rel_dy) = child.relative_offset;
cursor_y = (child.rect.y - rel_dy)
+ child.rect.height
+ child.padding.bottom
+ child.border.bottom;
pending_margin = Some(child_bottom_margin);
}
// Trailing margin.
if let Some(trailing) = pending_margin {
if !parent_bottom_open {
// Parent has border/padding at bottom — margin stays inside.
cursor_y += trailing;
}
// If parent_bottom_open, the margin was already pulled into the
// parent by pre_collapse_margins.
}
parent.rect.height = cursor_y - parent.rect.y;
}
// ---------------------------------------------------------------------------
// Inline formatting context
// ---------------------------------------------------------------------------
/// An inline item produced by flattening the inline tree.
enum InlineItemKind {
/// A word of text with associated styling.
Word {
text: String,
font_size: f32,
color: Color,
text_decoration: TextDecoration,
background_color: Color,
},
/// Whitespace between words.
Space { font_size: f32 },
/// Forced line break (`
`).
ForcedBreak,
/// Start of an inline box (for margin/padding/border tracking).
InlineStart {
margin_left: f32,
padding_left: f32,
border_left: f32,
},
/// End of an inline box.
InlineEnd {
margin_right: f32,
padding_right: f32,
border_right: f32,
},
}
/// A pending fragment on the current line.
struct PendingFragment {
text: String,
x: f32,
width: f32,
font_size: f32,
color: Color,
text_decoration: TextDecoration,
background_color: Color,
}
/// Flatten the inline children tree into a sequence of items.
fn flatten_inline_tree(children: &[LayoutBox], doc: &Document, items: &mut Vec) {
for child in children {
match &child.box_type {
BoxType::TextRun { text, .. } => {
let words = split_into_words(text);
for segment in words {
match segment {
WordSegment::Word(w) => {
items.push(InlineItemKind::Word {
text: w,
font_size: child.font_size,
color: child.color,
text_decoration: child.text_decoration,
background_color: child.background_color,
});
}
WordSegment::Space => {
items.push(InlineItemKind::Space {
font_size: child.font_size,
});
}
}
}
}
BoxType::Inline(node_id) => {
if let NodeData::Element { tag_name, .. } = doc.node_data(*node_id) {
if tag_name == "br" {
items.push(InlineItemKind::ForcedBreak);
continue;
}
}
items.push(InlineItemKind::InlineStart {
margin_left: child.margin.left,
padding_left: child.padding.left,
border_left: child.border.left,
});
flatten_inline_tree(&child.children, doc, items);
items.push(InlineItemKind::InlineEnd {
margin_right: child.margin.right,
padding_right: child.padding.right,
border_right: child.border.right,
});
}
_ => {}
}
}
}
enum WordSegment {
Word(String),
Space,
}
/// Split text into alternating words and spaces.
fn split_into_words(text: &str) -> Vec {
let mut segments = Vec::new();
let mut current_word = String::new();
for ch in text.chars() {
if ch == ' ' {
if !current_word.is_empty() {
segments.push(WordSegment::Word(std::mem::take(&mut current_word)));
}
segments.push(WordSegment::Space);
} else {
current_word.push(ch);
}
}
if !current_word.is_empty() {
segments.push(WordSegment::Word(current_word));
}
segments
}
/// Lay out inline children using a proper inline formatting context.
fn layout_inline_children(parent: &mut LayoutBox, font: &Font, doc: &Document) {
let available_width = parent.rect.width;
let text_align = parent.text_align;
let line_height = parent.line_height;
let mut items = Vec::new();
flatten_inline_tree(&parent.children, doc, &mut items);
if items.is_empty() {
parent.rect.height = 0.0;
return;
}
// Process items into line boxes.
let mut all_lines: Vec> = Vec::new();
let mut current_line: Vec = Vec::new();
let mut cursor_x: f32 = 0.0;
for item in &items {
match item {
InlineItemKind::Word {
text,
font_size,
color,
text_decoration,
background_color,
} => {
let word_width = measure_text_width(font, text, *font_size);
// If this word doesn't fit and the line isn't empty, break.
if cursor_x > 0.0 && cursor_x + word_width > available_width {
all_lines.push(std::mem::take(&mut current_line));
cursor_x = 0.0;
}
current_line.push(PendingFragment {
text: text.clone(),
x: cursor_x,
width: word_width,
font_size: *font_size,
color: *color,
text_decoration: *text_decoration,
background_color: *background_color,
});
cursor_x += word_width;
}
InlineItemKind::Space { font_size } => {
// Only add space if we have content on the line.
if !current_line.is_empty() {
let space_width = measure_text_width(font, " ", *font_size);
if cursor_x + space_width <= available_width {
cursor_x += space_width;
}
}
}
InlineItemKind::ForcedBreak => {
all_lines.push(std::mem::take(&mut current_line));
cursor_x = 0.0;
}
InlineItemKind::InlineStart {
margin_left,
padding_left,
border_left,
} => {
cursor_x += margin_left + padding_left + border_left;
}
InlineItemKind::InlineEnd {
margin_right,
padding_right,
border_right,
} => {
cursor_x += margin_right + padding_right + border_right;
}
}
}
// Flush the last line.
if !current_line.is_empty() {
all_lines.push(current_line);
}
if all_lines.is_empty() {
parent.rect.height = 0.0;
return;
}
// Position lines vertically and apply text-align.
let mut text_lines = Vec::new();
let mut y = parent.rect.y;
let num_lines = all_lines.len();
for (line_idx, line_fragments) in all_lines.iter().enumerate() {
if line_fragments.is_empty() {
y += line_height;
continue;
}
// Compute line width from last fragment.
let line_width = match line_fragments.last() {
Some(last) => last.x + last.width,
None => 0.0,
};
// Compute text-align offset.
let is_last_line = line_idx == num_lines - 1;
let align_offset =
compute_align_offset(text_align, available_width, line_width, is_last_line);
for frag in line_fragments {
text_lines.push(TextLine {
text: frag.text.clone(),
x: parent.rect.x + frag.x + align_offset,
y,
width: frag.width,
font_size: frag.font_size,
color: frag.color,
text_decoration: frag.text_decoration,
background_color: frag.background_color,
});
}
y += line_height;
}
parent.rect.height = num_lines as f32 * line_height;
parent.lines = text_lines;
}
/// Compute the horizontal offset for text alignment.
fn compute_align_offset(
align: TextAlign,
available_width: f32,
line_width: f32,
is_last_line: bool,
) -> f32 {
let extra_space = (available_width - line_width).max(0.0);
match align {
TextAlign::Left => 0.0,
TextAlign::Center => extra_space / 2.0,
TextAlign::Right => extra_space,
TextAlign::Justify => {
// Don't justify the last line (CSS spec behavior).
if is_last_line {
0.0
} else {
// For justify, we shift the whole line by 0 — the actual distribution
// of space between words would need per-word spacing. For now, treat
// as left-aligned; full justify support is a future enhancement.
0.0
}
}
}
}
// ---------------------------------------------------------------------------
// Text measurement
// ---------------------------------------------------------------------------
/// Measure the total advance width of a text string at the given font size.
fn measure_text_width(font: &Font, text: &str, font_size: f32) -> f32 {
let shaped = font.shape_text(text, font_size);
match shaped.last() {
Some(last) => last.x_offset + last.x_advance,
None => 0.0,
}
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/// Build and lay out from a styled tree (produced by `resolve_styles`).
///
/// Returns a `LayoutTree` with positioned boxes ready for rendering.
pub fn layout(
styled_root: &StyledNode,
doc: &Document,
viewport_width: f32,
viewport_height: f32,
font: &Font,
image_sizes: &HashMap,
) -> LayoutTree {
let mut root = match build_box(styled_root, doc, image_sizes) {
Some(b) => b,
None => {
return LayoutTree {
root: LayoutBox::new(BoxType::Anonymous, &ComputedStyle::default()),
width: viewport_width,
height: 0.0,
};
}
};
// Pre-collapse parent-child margins before positioning.
pre_collapse_margins(&mut root);
compute_layout(
&mut root,
0.0,
0.0,
viewport_width,
viewport_height,
font,
doc,
);
let height = root.margin_box_height();
LayoutTree {
root,
width: viewport_width,
height,
}
}
#[cfg(test)]
mod tests {
use super::*;
use we_dom::Document;
use we_style::computed::{extract_stylesheets, resolve_styles};
fn test_font() -> Font {
let paths = [
"/System/Library/Fonts/Geneva.ttf",
"/System/Library/Fonts/Monaco.ttf",
];
for path in &paths {
let p = std::path::Path::new(path);
if p.exists() {
return Font::from_file(p).expect("failed to parse font");
}
}
panic!("no test font found");
}
fn layout_doc(doc: &Document) -> LayoutTree {
let font = test_font();
let sheets = extract_stylesheets(doc);
let styled = resolve_styles(doc, &sheets, (800.0, 600.0)).unwrap();
layout(&styled, doc, 800.0, 600.0, &font, &HashMap::new())
}
#[test]
fn empty_document() {
let doc = Document::new();
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0));
if let Some(styled) = styled {
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
assert_eq!(tree.width, 800.0);
}
}
#[test]
fn single_paragraph() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let p = doc.create_element("p");
let text = doc.create_text("Hello world");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, p);
doc.append_child(p, text);
let tree = layout_doc(&doc);
assert!(matches!(tree.root.box_type, BoxType::Block(_)));
let body_box = &tree.root.children[0];
assert!(matches!(body_box.box_type, BoxType::Block(_)));
let p_box = &body_box.children[0];
assert!(matches!(p_box.box_type, BoxType::Block(_)));
assert!(!p_box.lines.is_empty(), "p should have text fragments");
// Collect all text on the first visual line.
let first_y = p_box.lines[0].y;
let line_text: String = p_box
.lines
.iter()
.filter(|l| (l.y - first_y).abs() < 0.01)
.map(|l| l.text.as_str())
.collect::>()
.join(" ");
assert!(
line_text.contains("Hello") && line_text.contains("world"),
"line should contain Hello and world, got: {line_text}"
);
assert_eq!(p_box.margin.top, 16.0);
assert_eq!(p_box.margin.bottom, 16.0);
}
#[test]
fn blocks_stack_vertically() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let p1 = doc.create_element("p");
let t1 = doc.create_text("First");
let p2 = doc.create_element("p");
let t2 = doc.create_text("Second");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, p1);
doc.append_child(p1, t1);
doc.append_child(body, p2);
doc.append_child(p2, t2);
let tree = layout_doc(&doc);
let body_box = &tree.root.children[0];
let first = &body_box.children[0];
let second = &body_box.children[1];
assert!(
second.rect.y > first.rect.y,
"second p (y={}) should be below first p (y={})",
second.rect.y,
first.rect.y
);
}
#[test]
fn heading_larger_than_body() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let h1 = doc.create_element("h1");
let h1_text = doc.create_text("Title");
let p = doc.create_element("p");
let p_text = doc.create_text("Text");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, h1);
doc.append_child(h1, h1_text);
doc.append_child(body, p);
doc.append_child(p, p_text);
let tree = layout_doc(&doc);
let body_box = &tree.root.children[0];
let h1_box = &body_box.children[0];
let p_box = &body_box.children[1];
assert!(
h1_box.font_size > p_box.font_size,
"h1 font_size ({}) should be > p font_size ({})",
h1_box.font_size,
p_box.font_size
);
assert_eq!(h1_box.font_size, 32.0);
assert!(
h1_box.rect.height > p_box.rect.height,
"h1 height ({}) should be > p height ({})",
h1_box.rect.height,
p_box.rect.height
);
}
#[test]
fn body_has_default_margin() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let p = doc.create_element("p");
let text = doc.create_text("Test");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, p);
doc.append_child(p, text);
let tree = layout_doc(&doc);
let body_box = &tree.root.children[0];
// body default margin is 8px, but it collapses with p's 16px margin
// (parent-child collapsing: no border/padding on body).
assert_eq!(body_box.margin.top, 16.0);
assert_eq!(body_box.margin.right, 8.0);
assert_eq!(body_box.margin.bottom, 16.0);
assert_eq!(body_box.margin.left, 8.0);
assert_eq!(body_box.rect.x, 8.0);
// body.rect.y = collapsed margin (16) from viewport top.
assert_eq!(body_box.rect.y, 16.0);
}
#[test]
fn text_wraps_at_container_width() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let p = doc.create_element("p");
let text =
doc.create_text("The quick brown fox jumps over the lazy dog and more words to wrap");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, p);
doc.append_child(p, text);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 100.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
// Count distinct y-positions to count visual lines.
let mut ys: Vec = p_box.lines.iter().map(|l| l.y).collect();
ys.sort_by(|a, b| a.partial_cmp(b).unwrap());
ys.dedup_by(|a, b| (*a - *b).abs() < 0.01);
assert!(
ys.len() > 1,
"text should wrap to multiple lines, got {} visual lines",
ys.len()
);
}
#[test]
fn layout_produces_positive_dimensions() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let div = doc.create_element("div");
let text = doc.create_text("Content");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, div);
doc.append_child(div, text);
let tree = layout_doc(&doc);
for b in tree.iter() {
assert!(b.rect.width >= 0.0, "width should be >= 0");
assert!(b.rect.height >= 0.0, "height should be >= 0");
}
assert!(tree.height > 0.0, "layout height should be > 0");
}
#[test]
fn head_is_hidden() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let head = doc.create_element("head");
let title = doc.create_element("title");
let title_text = doc.create_text("Page Title");
let body = doc.create_element("body");
let p = doc.create_element("p");
let p_text = doc.create_text("Visible");
doc.append_child(root, html);
doc.append_child(html, head);
doc.append_child(head, title);
doc.append_child(title, title_text);
doc.append_child(html, body);
doc.append_child(body, p);
doc.append_child(p, p_text);
let tree = layout_doc(&doc);
assert_eq!(
tree.root.children.len(),
1,
"html should have 1 child (body), head should be hidden"
);
}
#[test]
fn mixed_block_and_inline() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let div = doc.create_element("div");
let text1 = doc.create_text("Text");
let p = doc.create_element("p");
let p_text = doc.create_text("Block");
let text2 = doc.create_text("More");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, div);
doc.append_child(div, text1);
doc.append_child(div, p);
doc.append_child(p, p_text);
doc.append_child(div, text2);
let tree = layout_doc(&doc);
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert_eq!(
div_box.children.len(),
3,
"div should have 3 children (anon, block, anon), got {}",
div_box.children.len()
);
assert!(matches!(div_box.children[0].box_type, BoxType::Anonymous));
assert!(matches!(div_box.children[1].box_type, BoxType::Block(_)));
assert!(matches!(div_box.children[2].box_type, BoxType::Anonymous));
}
#[test]
fn inline_elements_contribute_text() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let p = doc.create_element("p");
let t1 = doc.create_text("Hello ");
let em = doc.create_element("em");
let t2 = doc.create_text("world");
let t3 = doc.create_text("!");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, p);
doc.append_child(p, t1);
doc.append_child(p, em);
doc.append_child(em, t2);
doc.append_child(p, t3);
let tree = layout_doc(&doc);
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
assert!(!p_box.lines.is_empty());
let first_y = p_box.lines[0].y;
let line_texts: Vec<&str> = p_box
.lines
.iter()
.filter(|l| (l.y - first_y).abs() < 0.01)
.map(|l| l.text.as_str())
.collect();
let combined = line_texts.join("");
assert!(
combined.contains("Hello") && combined.contains("world") && combined.contains("!"),
"line should contain all text, got: {combined}"
);
}
#[test]
fn collapse_whitespace_works() {
assert_eq!(collapse_whitespace("hello world"), "hello world");
assert_eq!(collapse_whitespace(" spaces "), " spaces ");
assert_eq!(collapse_whitespace("\n\ttabs\n"), " tabs ");
assert_eq!(collapse_whitespace("no-extra"), "no-extra");
assert_eq!(collapse_whitespace(" "), " ");
}
#[test]
fn content_width_respects_body_margin() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let div = doc.create_element("div");
let text = doc.create_text("Content");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, div);
doc.append_child(div, text);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
assert_eq!(body_box.rect.width, 784.0);
let div_box = &body_box.children[0];
assert_eq!(div_box.rect.width, 784.0);
}
#[test]
fn multiple_heading_levels() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
doc.append_child(root, html);
doc.append_child(html, body);
let tags = ["h1", "h2", "h3"];
for tag in &tags {
let h = doc.create_element(tag);
let t = doc.create_text(tag);
doc.append_child(body, h);
doc.append_child(h, t);
}
let tree = layout_doc(&doc);
let body_box = &tree.root.children[0];
let h1 = &body_box.children[0];
let h2 = &body_box.children[1];
let h3 = &body_box.children[2];
assert!(h1.font_size > h2.font_size);
assert!(h2.font_size > h3.font_size);
assert!(h2.rect.y > h1.rect.y);
assert!(h3.rect.y > h2.rect.y);
}
#[test]
fn layout_tree_iteration() {
let mut doc = Document::new();
let root = doc.root();
let html = doc.create_element("html");
let body = doc.create_element("body");
let p = doc.create_element("p");
let text = doc.create_text("Test");
doc.append_child(root, html);
doc.append_child(html, body);
doc.append_child(body, p);
doc.append_child(p, text);
let tree = layout_doc(&doc);
let count = tree.iter().count();
assert!(count >= 3, "should have at least html, body, p boxes");
}
#[test]
fn css_style_affects_layout() {
let html_str = r#"
First
Second
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let first = &body_box.children[0];
let second = &body_box.children[1];
assert_eq!(first.margin.top, 50.0);
assert_eq!(first.margin.bottom, 50.0);
// Adjacent sibling margins collapse: gap = max(50, 50) = 50, not 100.
let gap = second.rect.y - (first.rect.y + first.rect.height);
assert!(
(gap - 50.0).abs() < 1.0,
"collapsed margin gap should be ~50px, got {gap}"
);
}
#[test]
fn inline_style_affects_layout() {
let html_str = r#"
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert_eq!(div_box.padding.top, 20.0);
assert_eq!(div_box.padding.bottom, 20.0);
}
#[test]
fn css_color_propagates_to_layout() {
let html_str = r#"
Colored
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
assert_eq!(p_box.color, Color::rgb(255, 0, 0));
assert_eq!(p_box.background_color, Color::rgb(0, 0, 255));
}
// --- New inline layout tests ---
#[test]
fn inline_elements_have_per_fragment_styling() {
let html_str = r#"
Hello world
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
let colors: Vec = p_box.lines.iter().map(|l| l.color).collect();
assert!(
colors.iter().any(|c| *c == Color::rgb(0, 0, 0)),
"should have black text"
);
assert!(
colors.iter().any(|c| *c == Color::rgb(255, 0, 0)),
"should have red text from "
);
}
#[test]
fn br_element_forces_line_break() {
let html_str = r#"
Line one
Line two
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
let mut ys: Vec = p_box.lines.iter().map(|l| l.y).collect();
ys.sort_by(|a, b| a.partial_cmp(b).unwrap());
ys.dedup_by(|a, b| (*a - *b).abs() < 0.01);
assert!(
ys.len() >= 2,
"
should produce 2 visual lines, got {}",
ys.len()
);
}
#[test]
fn text_align_center() {
let html_str = r#"
Hi
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
assert!(!p_box.lines.is_empty());
let first = &p_box.lines[0];
// Center-aligned: text should be noticeably offset from content x.
assert!(
first.x > p_box.rect.x + 10.0,
"center-aligned text x ({}) should be offset from content x ({})",
first.x,
p_box.rect.x
);
}
#[test]
fn text_align_right() {
let html_str = r#"
Hi
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
assert!(!p_box.lines.is_empty());
let first = &p_box.lines[0];
let right_edge = p_box.rect.x + p_box.rect.width;
assert!(
(first.x + first.width - right_edge).abs() < 1.0,
"right-aligned text end ({}) should be near right edge ({})",
first.x + first.width,
right_edge
);
}
#[test]
fn inline_padding_offsets_text() {
let html_str = r#"
ABC
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
// Should have at least 3 fragments: A, B, C
assert!(
p_box.lines.len() >= 3,
"should have fragments for A, B, C, got {}",
p_box.lines.len()
);
// B should be offset by the span's padding.
let a_frag = &p_box.lines[0];
let b_frag = &p_box.lines[1];
let gap = b_frag.x - (a_frag.x + a_frag.width);
// Gap should include the 20px padding-left from the span.
assert!(
gap >= 19.0,
"gap between A and B ({gap}) should include span padding-left (20px)"
);
}
#[test]
fn text_fragments_have_correct_font_size() {
let html_str = r#"
Big
Small
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let h1_box = &body_box.children[0];
let p_box = &body_box.children[1];
assert!(!h1_box.lines.is_empty());
assert!(!p_box.lines.is_empty());
assert_eq!(h1_box.lines[0].font_size, 32.0);
assert_eq!(p_box.lines[0].font_size, 16.0);
}
#[test]
fn line_height_from_computed_style() {
let html_str = r#"
Line one Line two Line three
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
// Narrow viewport to force wrapping.
let tree = layout(&styled, &doc, 100.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
let mut ys: Vec = p_box.lines.iter().map(|l| l.y).collect();
ys.sort_by(|a, b| a.partial_cmp(b).unwrap());
ys.dedup_by(|a, b| (*a - *b).abs() < 0.01);
if ys.len() >= 2 {
let gap = ys[1] - ys[0];
assert!(
(gap - 30.0).abs() < 1.0,
"line spacing ({gap}) should be ~30px from line-height"
);
}
}
// --- Relative positioning tests ---
#[test]
fn relative_position_top_left() {
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert_eq!(div_box.position, Position::Relative);
assert_eq!(div_box.relative_offset, (20.0, 10.0));
// The div should be shifted from where it would be in normal flow.
// Normal flow position: body.rect.x + margin, body.rect.y + margin.
// With relative offset: shifted by (20, 10).
// Body has 8px margin by default, so content starts at x=8, y=8.
assert!(
(div_box.rect.x - (8.0 + 20.0)).abs() < 0.01,
"div x ({}) should be 28.0 (8 + 20)",
div_box.rect.x
);
assert!(
(div_box.rect.y - (8.0 + 10.0)).abs() < 0.01,
"div y ({}) should be 18.0 (8 + 10)",
div_box.rect.y
);
}
#[test]
fn relative_position_does_not_affect_siblings() {
let html_str = r#"
First
Second
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let first = &body_box.children[0];
let second = &body_box.children[1];
// The first paragraph is shifted down by 50px visually.
assert_eq!(first.relative_offset, (0.0, 50.0));
// But the second paragraph should be at its normal-flow position,
// as if the first paragraph were NOT shifted. The second paragraph
// should come right after the first's normal-flow height.
// Body content starts at y=8 (default body margin). First p has 0 margin.
// Second p should start right after first p's height (without offset).
let first_normal_y = 8.0; // body margin
let first_height = first.rect.height;
let expected_second_y = first_normal_y + first_height;
assert!(
(second.rect.y - expected_second_y).abs() < 1.0,
"second y ({}) should be at normal-flow position ({expected_second_y}), not affected by first's relative offset",
second.rect.y
);
}
#[test]
fn relative_position_conflicting_offsets() {
// When both top and bottom are specified, top wins.
// When both left and right are specified, left wins.
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// top wins over bottom: dy = 10 (not -20)
// left wins over right: dx = 30 (not -40)
assert_eq!(div_box.relative_offset, (30.0, 10.0));
}
#[test]
fn relative_position_auto_offsets() {
// auto offsets should resolve to 0 (no movement).
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert_eq!(div_box.position, Position::Relative);
assert_eq!(div_box.relative_offset, (0.0, 0.0));
}
#[test]
fn relative_position_bottom_right() {
// bottom: 15px should shift up by 15px (negative direction).
// right: 25px should shift left by 25px (negative direction).
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert_eq!(div_box.relative_offset, (-25.0, -15.0));
}
#[test]
fn relative_position_shifts_text_lines() {
let html_str = r#"
Hello
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
assert!(!p_box.lines.is_empty(), "p should have text lines");
let first_line = &p_box.lines[0];
// Text should be shifted by the relative offset.
// Body content starts at x=8, y=8. With offset: x=48, y=38.
assert!(
first_line.x >= 8.0 + 40.0 - 1.0,
"text x ({}) should be shifted by left offset",
first_line.x
);
assert!(
first_line.y >= 8.0 + 30.0 - 1.0,
"text y ({}) should be shifted by top offset",
first_line.y
);
}
#[test]
fn static_position_has_no_offset() {
let html_str = r#"
Normal flow
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert_eq!(div_box.position, Position::Static);
assert_eq!(div_box.relative_offset, (0.0, 0.0));
}
// --- Margin collapsing tests ---
#[test]
fn adjacent_sibling_margins_collapse() {
// Two elements each with margin 16px: gap should be 16px (max), not 32px (sum).
let html_str = r#"
First
Second
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let first = &body_box.children[0];
let second = &body_box.children[1];
// Gap between first's bottom border-box and second's top border-box
// should be the collapsed margin: max(16, 16) = 16.
let first_bottom =
first.rect.y + first.rect.height + first.padding.bottom + first.border.bottom;
let gap = second.rect.y - second.border.top - second.padding.top - first_bottom;
assert!(
(gap - 16.0).abs() < 1.0,
"collapsed sibling margin should be ~16px, got {gap}"
);
}
#[test]
fn sibling_margins_collapse_unequal() {
// p1 bottom-margin 20, p2 top-margin 30: gap should be 30 (max).
let html_str = r#"
First
Second
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let first = &body_box.children[0];
let second = &body_box.children[1];
let first_bottom =
first.rect.y + first.rect.height + first.padding.bottom + first.border.bottom;
let gap = second.rect.y - second.border.top - second.padding.top - first_bottom;
assert!(
(gap - 30.0).abs() < 1.0,
"collapsed margin should be max(20, 30) = 30, got {gap}"
);
}
#[test]
fn parent_first_child_margin_collapsing() {
// Parent with no padding/border: first child's top margin collapses.
let html_str = r#"
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let parent_box = &body_box.children[0];
// Parent margin collapses with child's: max(10, 20) = 20.
assert_eq!(parent_box.margin.top, 20.0);
}
#[test]
fn negative_margin_collapsing() {
// One positive (20) and one negative (-10): collapsed = 20 + (-10) = 10.
let html_str = r#"
First
Second
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let first = &body_box.children[0];
let second = &body_box.children[1];
let first_bottom =
first.rect.y + first.rect.height + first.padding.bottom + first.border.bottom;
let gap = second.rect.y - second.border.top - second.padding.top - first_bottom;
// 20 + (-10) = 10
assert!(
(gap - 10.0).abs() < 1.0,
"positive + negative margin collapse should be 10, got {gap}"
);
}
#[test]
fn both_negative_margins_collapse() {
// Both negative: use the more negative value.
let html_str = r#"
First
Second
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let first = &body_box.children[0];
let second = &body_box.children[1];
let first_bottom =
first.rect.y + first.rect.height + first.padding.bottom + first.border.bottom;
let gap = second.rect.y - second.border.top - second.padding.top - first_bottom;
// Both negative: min(-10, -20) = -20
assert!(
(gap - (-20.0)).abs() < 1.0,
"both-negative margin collapse should be -20, got {gap}"
);
}
#[test]
fn border_blocks_margin_collapsing() {
// When border separates margins, they don't collapse.
let html_str = r#"
First
Second
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let first = &body_box.children[0];
let second = &body_box.children[1];
// Borders are on the elements themselves, but the MARGINS are still
// between the border boxes — sibling margins still collapse regardless
// of borders on the elements. The margin gap = max(20, 20) = 20.
let first_bottom =
first.rect.y + first.rect.height + first.padding.bottom + first.border.bottom;
let gap = second.rect.y - second.border.top - second.padding.top - first_bottom;
assert!(
(gap - 20.0).abs() < 1.0,
"sibling margins collapse even with borders on elements, gap should be 20, got {gap}"
);
}
#[test]
fn padding_blocks_parent_child_collapsing() {
// Parent with padding-top prevents margin collapsing with first child.
let html_str = r#"
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let parent_box = &body_box.children[0];
// Parent has padding-top, so no collapsing: margin stays at 10.
assert_eq!(parent_box.margin.top, 10.0);
}
#[test]
fn empty_block_margins_collapse() {
// An empty div's top and bottom margins collapse with adjacent margins.
let html_str = r#"
Before
After
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let before = &body_box.children[0];
let after = &body_box.children[2]; // [0]=p, [1]=empty div, [2]=p
// Empty div's margins (10+10) self-collapse to max(10,10)=10.
// Then collapse with before's bottom (5) and after's top (5):
// collapse(5, collapse(10, 10)) = collapse(5, 10) = 10
// Then collapse(10, 5) = 10.
// So total gap between before and after = 10.
let before_bottom =
before.rect.y + before.rect.height + before.padding.bottom + before.border.bottom;
let gap = after.rect.y - after.border.top - after.padding.top - before_bottom;
assert!(
(gap - 10.0).abs() < 1.0,
"empty block margin collapse gap should be ~10px, got {gap}"
);
}
#[test]
fn collapse_margins_unit() {
// Unit tests for the collapse_margins helper.
assert_eq!(collapse_margins(10.0, 20.0), 20.0);
assert_eq!(collapse_margins(20.0, 10.0), 20.0);
assert_eq!(collapse_margins(0.0, 15.0), 15.0);
assert_eq!(collapse_margins(-5.0, -10.0), -10.0);
assert_eq!(collapse_margins(20.0, -5.0), 15.0);
assert_eq!(collapse_margins(-5.0, 20.0), 15.0);
assert_eq!(collapse_margins(0.0, 0.0), 0.0);
}
// --- Box-sizing tests ---
#[test]
fn content_box_default_width_applies_to_content() {
// Default box-sizing (content-box): width = content width only.
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// content-box: rect.width = 200 (the specified width IS the content)
assert_eq!(div_box.rect.width, 200.0);
assert_eq!(div_box.padding.left, 10.0);
assert_eq!(div_box.padding.right, 10.0);
assert_eq!(div_box.border.left, 5.0);
assert_eq!(div_box.border.right, 5.0);
}
#[test]
fn border_box_width_includes_padding_and_border() {
// box-sizing: border-box: width includes padding and border.
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// border-box: content width = 200 - 10*2 (padding) - 5*2 (border) = 170
assert_eq!(div_box.rect.width, 170.0);
assert_eq!(div_box.padding.left, 10.0);
assert_eq!(div_box.padding.right, 10.0);
assert_eq!(div_box.border.left, 5.0);
assert_eq!(div_box.border.right, 5.0);
}
#[test]
fn border_box_padding_exceeds_width_clamps_to_zero() {
// border-box with padding+border > specified width: content clamps to 0.
let html_str = r#"
X
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// border-box: content = 20 - 15*2 - 5*2 = 20 - 40 = -20 → clamped to 0
assert_eq!(div_box.rect.width, 0.0);
}
#[test]
fn box_sizing_is_not_inherited() {
// box-sizing is not inherited: child should use default content-box.
let html_str = r#"
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let parent_box = &body_box.children[0];
let child_box = &parent_box.children[0];
// Parent: border-box → content = 300 - 20 - 10 = 270
assert_eq!(parent_box.rect.width, 270.0);
// Child: default content-box → content = 100 (not reduced by padding/border)
assert_eq!(child_box.rect.width, 100.0);
}
#[test]
fn border_box_height() {
// box-sizing: border-box also applies to height.
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// border-box: content height = 100 - 10*2 (padding) - 5*2 (border) = 70
assert_eq!(div_box.rect.height, 70.0);
}
#[test]
fn content_box_explicit_height() {
// content-box: height applies to content only.
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// content-box: rect.height = 100 (specified height IS content height)
assert_eq!(div_box.rect.height, 100.0);
}
// --- Visibility / display:none tests ---
#[test]
fn display_none_excludes_from_layout_tree() {
let html_str = r#"
First
Hidden content
Second
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
// display:none element is excluded — body should have only 2 children.
assert_eq!(body_box.children.len(), 2);
let first = &body_box.children[0];
let second = &body_box.children[1];
// Second paragraph should be directly below first (no gap for hidden).
assert!(
second.rect.y == first.rect.y + first.rect.height,
"display:none should not occupy space"
);
}
#[test]
fn visibility_hidden_preserves_layout_space() {
let html_str = r#"
First
Hidden
Second
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
// visibility:hidden still in layout tree — body has 3 children.
assert_eq!(body_box.children.len(), 3);
let hidden_box = &body_box.children[1];
assert_eq!(hidden_box.visibility, Visibility::Hidden);
assert_eq!(hidden_box.rect.height, 50.0);
let second = &body_box.children[2];
// Second paragraph should be below hidden div (it occupies 50px).
assert!(
second.rect.y >= hidden_box.rect.y + 50.0,
"visibility:hidden should preserve layout space"
);
}
#[test]
fn visibility_inherited_by_children() {
let html_str = r#"
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let parent_box = &body_box.children[0];
let child_box = &parent_box.children[0];
assert_eq!(parent_box.visibility, Visibility::Hidden);
assert_eq!(child_box.visibility, Visibility::Hidden);
}
#[test]
fn visibility_visible_overrides_hidden_parent() {
let html_str = r#"
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let parent_box = &body_box.children[0];
let child_box = &parent_box.children[0];
assert_eq!(parent_box.visibility, Visibility::Hidden);
assert_eq!(child_box.visibility, Visibility::Visible);
}
#[test]
fn visibility_collapse_on_non_table_treated_as_hidden() {
let html_str = r#"
Collapsed
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert_eq!(div_box.visibility, Visibility::Collapse);
// Still occupies space (non-table collapse = hidden behavior).
assert_eq!(div_box.rect.height, 50.0);
}
// --- Viewport units and percentage resolution tests ---
#[test]
fn width_50_percent_resolves_to_half_containing_block() {
let html_str = r#"
Half width
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert!(
(div_box.rect.width - 400.0).abs() < 0.01,
"width: 50% should be 400px on 800px viewport, got {}",
div_box.rect.width
);
}
#[test]
fn margin_10_percent_resolves_against_containing_block_width() {
let html_str = r#"
Box
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// All margins (including top/bottom) resolve against containing block WIDTH.
assert!(
(div_box.margin.left - 80.0).abs() < 0.01,
"margin-left: 10% should be 80px on 800px viewport, got {}",
div_box.margin.left
);
assert!(
(div_box.margin.top - 80.0).abs() < 0.01,
"margin-top: 10% should be 80px (against width, not height), got {}",
div_box.margin.top
);
}
#[test]
fn width_50vw_resolves_to_half_viewport() {
let html_str = r#"
Half viewport
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert!(
(div_box.rect.width - 400.0).abs() < 0.01,
"width: 50vw should be 400px on 800px viewport, got {}",
div_box.rect.width
);
}
#[test]
fn height_100vh_resolves_to_full_viewport() {
let html_str = r#"
Full height
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
assert!(
(div_box.rect.height - 600.0).abs() < 0.01,
"height: 100vh should be 600px on 600px viewport, got {}",
div_box.rect.height
);
}
#[test]
fn font_size_5vmin_resolves_to_smaller_dimension() {
let html_str = r#"
Text
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
// viewport 800x600 → vmin = 600
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let p_box = &body_box.children[0];
// 5vmin = 5% of min(800, 600) = 5% of 600 = 30px
assert!(
(p_box.font_size - 30.0).abs() < 0.01,
"font-size: 5vmin should be 30px, got {}",
p_box.font_size
);
}
#[test]
fn nested_percentage_widths_compound() {
let html_str = r#"
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let outer_box = &body_box.children[0];
let inner_box = &outer_box.children[0];
// outer = 50% of 800 = 400
assert!(
(outer_box.rect.width - 400.0).abs() < 0.01,
"outer width should be 400px, got {}",
outer_box.rect.width
);
// inner = 50% of 400 = 200
assert!(
(inner_box.rect.width - 200.0).abs() < 0.01,
"inner width should be 200px (50% of 400), got {}",
inner_box.rect.width
);
}
#[test]
fn padding_percent_resolves_against_width() {
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// padding: 5% resolves against containing block width (800px)
assert!(
(div_box.padding.top - 40.0).abs() < 0.01,
"padding-top: 5% should be 40px (5% of 800), got {}",
div_box.padding.top
);
assert!(
(div_box.padding.left - 40.0).abs() < 0.01,
"padding-left: 5% should be 40px (5% of 800), got {}",
div_box.padding.left
);
}
#[test]
fn vmax_uses_larger_dimension() {
let html_str = r#"
Content
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
// viewport 800x600 → vmax = 800
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// 10vmax = 10% of max(800, 600) = 10% of 800 = 80px
assert!(
(div_box.rect.width - 80.0).abs() < 0.01,
"width: 10vmax should be 80px, got {}",
div_box.rect.width
);
}
#[test]
fn height_50_percent_resolves_against_viewport() {
let html_str = r#"
Half height
"#;
let doc = we_html::parse_html(html_str);
let font = test_font();
let sheets = extract_stylesheets(&doc);
let styled = resolve_styles(&doc, &sheets, (800.0, 600.0)).unwrap();
let tree = layout(&styled, &doc, 800.0, 600.0, &font, &HashMap::new());
let body_box = &tree.root.children[0];
let div_box = &body_box.children[0];
// height: 50% resolves against viewport height (600)
assert!(
(div_box.rect.height - 300.0).abs() < 0.01,
"height: 50% should be 300px on 600px viewport, got {}",
div_box.rect.height
);
}
}