Fix float placement, clearance, and percentage margin resolution in block layout (#990)
1//! Computes the CSS block layout algorithm in the case that the block container being laid out contains only block-level boxes
2use crate::geometry::{Line, Point, Rect, Size};
3use crate::style::{AvailableSpace, CoreStyle, LengthPercentageAuto, Overflow, Position};
4use crate::style_helpers::TaffyMaxContent;
5use crate::tree::{CollapsibleMarginSet, Layout, LayoutInput, LayoutOutput, RunMode, SizingMode};
6use crate::tree::{LayoutPartialTree, LayoutPartialTreeExt, NodeId};
7use crate::util::debug::debug_log;
8use crate::util::sys::f32_max;
9use crate::util::sys::Vec;
10use crate::util::MaybeMath;
11use crate::util::{MaybeResolve, ResolveOrZero};
12use crate::{
13 BlockContainerStyle, BlockItemStyle, BoxGenerationMode, BoxSizing, Direction, LayoutBlockContainer, RequestedAxis,
14 TextAlign,
15};
16
17#[cfg(feature = "float_layout")]
18use super::float::{ContentSlot, FloatContext, FloatIntrinsicWidthCalculator};
19#[cfg(feature = "float_layout")]
20use crate::{Clear, Float, FloatDirection};
21
22/// Context for positioning Block and Float boxes within a Block Formatting Context
23pub struct BlockFormattingContext {
24 /// The float positioning context that handles positioning floats within this Block Formatting Context
25 #[cfg(feature = "float_layout")]
26 float_context: FloatContext,
27}
28
29impl Default for BlockFormattingContext {
30 fn default() -> Self {
31 Self {
32 #[cfg(feature = "float_layout")]
33 float_context: FloatContext::new(),
34 }
35 }
36}
37
38impl BlockFormattingContext {
39 /// Create a new `BlockFormattingContext` with the specified width constraint
40 pub fn new() -> Self {
41 Default::default()
42 }
43
44 /// Create an initial `BlockContext` for this `BlockFormattingContext`
45 pub fn root_block_context(&mut self) -> BlockContext<'_> {
46 BlockContext {
47 bfc: self,
48 y_offset: 0.0,
49 insets: [0.0, 0.0],
50 content_box_insets: [0.0, 0.0],
51 float_content_contribution: 0.0,
52 is_root: true,
53 }
54 }
55}
56
57/// Context for each individual Block within a Block Formatting Context
58///
59/// Contains a mutable reference to the BlockFormattingContext + block-specific data
60pub struct BlockContext<'bfc> {
61 /// A mutable reference to the root BlockFormatttingContext that this BlockContext belongs to
62 bfc: &'bfc mut BlockFormattingContext,
63 /// The y-offset of the border-top of the block node, relative to the to the border-top of the
64 /// root node of the Block Formatting Context it belongs to.
65 y_offset: f32,
66 /// The x-inset of the border-box in from each side of the block node, relative to the root node of the Block Formatting Context it belongs to.
67 insets: [f32; 2],
68 /// The x-insets of the content box
69 content_box_insets: [f32; 2],
70 /// The height that floats take up in the element
71 float_content_contribution: f32,
72 /// Whether the node is the root of the Block Formatting Context is belongs to.
73 is_root: bool,
74}
75
76impl BlockContext<'_> {
77 /// Create a sub-`BlockContext` for a child block node
78 pub fn sub_context(&mut self, additional_y_offset: f32, insets: [f32; 2]) -> BlockContext<'_> {
79 let insets = [self.insets[0] + insets[0], self.insets[1] + insets[1]];
80 BlockContext {
81 bfc: self.bfc,
82 y_offset: self.y_offset + additional_y_offset,
83 insets,
84 content_box_insets: insets,
85 float_content_contribution: 0.0,
86 is_root: false,
87 }
88 }
89
90 /// Returns whether this block is the root block of it's Block Formatting Context
91 pub fn is_bfc_root(&self) -> bool {
92 self.is_root
93 }
94}
95
96#[cfg(feature = "float_layout")]
97impl BlockContext<'_> {
98 /// Set the width of the overall Block Formatting Context. This is used to resolve positions
99 /// that are relative to the right of the context such as right-floated boxes.
100 ///
101 /// Sub-blocks within a Block Formatting Context should use the `Self::sub_context` method to create
102 /// a sub-`BlockContext` with `insets` instead.
103 pub fn set_width(&mut self, available_width: f32) {
104 self.bfc.float_context.set_width(available_width);
105 }
106
107 /// Set the x-axis content-box insets of the `BlockContext`. These are the difference between the border-box
108 /// and the content-box of the box (padding + border + scrollbar_gutter).
109 pub fn apply_content_box_inset(&mut self, content_box_x_insets: [f32; 2]) {
110 self.content_box_insets[0] = self.insets[0] + content_box_x_insets[0];
111 self.content_box_insets[1] = self.insets[1] + content_box_x_insets[1];
112 }
113
114 /// Whether the float context contains any floats
115 #[inline(always)]
116 pub fn has_floats(&self) -> bool {
117 self.bfc.float_context.has_floats()
118 }
119
120 /// Whether the float context contains any floats that extend to or below min_y
121 #[inline(always)]
122 pub fn has_active_floats(&self, min_y: f32) -> bool {
123 self.bfc.float_context.has_active_floats(min_y + self.y_offset)
124 }
125
126 /// Position a floated box with the context
127 pub fn place_floated_box(
128 &mut self,
129 floated_box: Size<f32>,
130 min_y: f32,
131 direction: FloatDirection,
132 clear: Clear,
133 ) -> Point<f32> {
134 let mut pos = self.bfc.float_context.place_floated_box(
135 floated_box,
136 min_y + self.y_offset,
137 self.content_box_insets,
138 direction,
139 clear,
140 );
141 pos.y -= self.y_offset;
142 pos.x -= self.insets[0];
143
144 self.float_content_contribution = self.float_content_contribution.max(pos.y + floated_box.height);
145
146 pos
147 }
148
149 /// Search a space suitable for laying out non-floated content into
150 pub fn find_content_slot(&self, min_y: f32, clear: Clear, after: Option<usize>) -> ContentSlot {
151 let mut slot =
152 self.bfc.float_context.find_content_slot(min_y + self.y_offset, self.content_box_insets, clear, after);
153 slot.y -= self.y_offset;
154 slot.x -= self.insets[0];
155 slot
156 }
157
158 /// Get the bottom of lowest relevant float for the specific clear property
159 pub fn cleared_threshold(&self, clear: Clear) -> Option<f32> {
160 self.bfc.float_context.cleared_threshold(clear).map(|threshold| threshold - self.y_offset)
161 }
162
163 /// Update the height that descendent floats with the height that floats consume
164 /// within a particular child
165 fn add_child_floated_content_height_contribution(&mut self, child_contribution: f32) {
166 self.float_content_contribution = self.float_content_contribution.max(child_contribution);
167 }
168
169 /// Returns the height that descendent floats consume
170 pub fn floated_content_height_contribution(&self) -> f32 {
171 self.float_content_contribution
172 }
173}
174
175#[cfg(not(feature = "float_layout"))]
176impl BlockContext<'_> {
177 #[inline(always)]
178 /// Returns the height that descendent floats consume (always 0.0 when the float feature is disabled)
179 fn float_content_contribution(&self) -> f32 {
180 0.0
181 }
182}
183
184use super::common::alignment::{apply_alignment_fallback, compute_alignment_offset};
185#[cfg(feature = "content_size")]
186use super::common::content_size::compute_content_size_contribution;
187
188/// Per-child data that is accumulated and modified over the course of the layout algorithm
189struct BlockItem {
190 /// The identifier for the associated node
191 node_id: NodeId,
192
193 /// The "source order" of the item. This is the index of the item within the children iterator,
194 /// and controls the order in which the nodes are placed
195 order: u32,
196
197 /// Items that are tables don't have stretch sizing applied to them
198 is_table: bool,
199
200 /// Whether the child is a non-independent block or inline node
201 is_in_same_bfc: bool,
202
203 #[cfg(feature = "float_layout")]
204 /// The `float` style of the node
205 float: Float,
206 #[cfg(feature = "float_layout")]
207 /// The `clear` style of the node
208 clear: Clear,
209
210 /// The base size of this item
211 size: Size<Option<f32>>,
212 /// The minimum allowable size of this item
213 min_size: Size<Option<f32>>,
214 /// The maximum allowable size of this item
215 max_size: Size<Option<f32>>,
216
217 /// The overflow style of the item
218 overflow: Point<Overflow>,
219 /// The width of the item's scrollbars (if it has scrollbars)
220 scrollbar_width: f32,
221
222 /// The position style of the item
223 position: Position,
224 /// The final offset of this item
225 inset: Rect<LengthPercentageAuto>,
226 /// The margin of this item
227 margin: Rect<LengthPercentageAuto>,
228 /// The margin of this item
229 padding: Rect<f32>,
230 /// The margin of this item
231 border: Rect<f32>,
232 /// The sum of padding and border for this item
233 padding_border_sum: Size<f32>,
234
235 /// The computed border box size of this item
236 computed_size: Size<f32>,
237 /// The computed "static position" of this item. The static position is the position
238 /// taking into account padding, border, margins, and scrollbar_gutters but not inset
239 static_position: Point<f32>,
240 /// Whether margins can be collapsed through this item
241 can_be_collapsed_through: bool,
242
243 /// Pending layout for in-flow non-floated items. Held back from `set_unrounded_layout` so the
244 /// post-loop `align-content` pass in `compute_inner` can shift `location.y` before commit.
245 final_layout: Option<Layout>,
246}
247
248/// Computes the layout of [`LayoutPartialTree`] according to the block layout algorithm
249pub fn compute_block_layout(
250 tree: &mut impl LayoutBlockContainer,
251 node_id: NodeId,
252 inputs: LayoutInput,
253 block_ctx: Option<&mut BlockContext<'_>>,
254) -> LayoutOutput {
255 let LayoutInput { known_dimensions, parent_size, run_mode, .. } = inputs;
256 let style = tree.get_block_container_style(node_id);
257
258 // Pull these out earlier to avoid borrowing issues
259 let overflow = style.overflow();
260 let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
261 let aspect_ratio = style.aspect_ratio();
262 let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
263 let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
264 let padding_border_size = (padding + border).sum_axes();
265 let box_sizing_adjustment =
266 if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
267
268 let min_size = style
269 .min_size()
270 .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
271 .maybe_apply_aspect_ratio(aspect_ratio)
272 .maybe_add(box_sizing_adjustment);
273 let max_size = style
274 .max_size()
275 .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
276 .maybe_apply_aspect_ratio(aspect_ratio)
277 .maybe_add(box_sizing_adjustment);
278 let clamped_style_size = if inputs.sizing_mode == SizingMode::InherentSize {
279 style
280 .size()
281 .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
282 .maybe_apply_aspect_ratio(aspect_ratio)
283 .maybe_add(box_sizing_adjustment)
284 .maybe_clamp(min_size, max_size)
285 } else {
286 Size::NONE
287 };
288
289 drop(style);
290
291 // If both min and max in a given axis are set and max <= min then this determines the size in that axis
292 let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
293 (Some(min), Some(max)) if max <= min => Some(min),
294 _ => None,
295 });
296
297 let styled_based_known_dimensions =
298 known_dimensions.or(min_max_definite_size).or(clamped_style_size).maybe_max(padding_border_size);
299
300 // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
301 // is ComputeSize (and thus the container's size is all that we're interested in)
302 if run_mode == RunMode::ComputeSize {
303 if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
304 return LayoutOutput::from_outer_size(Size { width, height });
305 }
306
307 // We can also short-circuit if the width is known and only the width has been requested.
308 if inputs.axis == RequestedAxis::Horizontal {
309 if let Some(width) = styled_based_known_dimensions.width {
310 return LayoutOutput::from_outer_size(Size { width, height: 0.0 });
311 }
312 }
313 }
314
315 // Unwrap the block formatting context if one was passed, or else create a new one
316 debug_log!("BLOCK");
317 match block_ctx {
318 Some(inherited_bfc) if !is_scroll_container => compute_inner(
319 tree,
320 node_id,
321 LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs },
322 inherited_bfc,
323 ),
324 _ => {
325 let mut root_bfc = BlockFormattingContext::new();
326 let mut root_ctx = root_bfc.root_block_context();
327 compute_inner(
328 tree,
329 node_id,
330 LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs },
331 &mut root_ctx,
332 )
333 }
334 }
335}
336
337/// Computes the layout of [`LayoutBlockContainer`] according to the block layout algorithm
338fn compute_inner(
339 tree: &mut impl LayoutBlockContainer,
340 node_id: NodeId,
341 inputs: LayoutInput,
342 #[allow(unused_mut)] mut block_ctx: &mut BlockContext<'_>,
343) -> LayoutOutput {
344 let LayoutInput {
345 known_dimensions, parent_size, available_space, run_mode, vertical_margins_are_collapsible, ..
346 } = inputs;
347
348 let style = tree.get_block_container_style(node_id);
349 let raw_padding = style.padding();
350 let raw_border = style.border();
351 let raw_margin = style.margin();
352 let aspect_ratio = style.aspect_ratio();
353 let padding = raw_padding.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
354 let border = raw_border.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
355 let direction = style.direction();
356
357 // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
358 // However, the axis are switched (transposed) because a node that scrolls vertically needs
359 // *horizontal* space to be reserved for a scrollbar
360 let scrollbar_gutter = {
361 let offsets = style.overflow().transpose().map(|overflow| match overflow {
362 Overflow::Scroll => style.scrollbar_width(),
363 _ => 0.0,
364 });
365 match direction {
366 Direction::Ltr => Rect { top: 0.0, left: 0.0, right: offsets.x, bottom: offsets.y },
367 Direction::Rtl => Rect { top: 0.0, left: offsets.x, right: 0.0, bottom: offsets.y },
368 }
369 };
370 let padding_border = padding + border;
371 let padding_border_size = padding_border.sum_axes();
372 let content_box_inset = padding_border + scrollbar_gutter;
373
374 // Apply content box inset
375 #[cfg(feature = "float_layout")]
376 block_ctx.apply_content_box_inset([content_box_inset.left, content_box_inset.right]);
377
378 let box_sizing_adjustment =
379 if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
380 let size = style
381 .size()
382 .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
383 .maybe_apply_aspect_ratio(aspect_ratio)
384 .maybe_add(box_sizing_adjustment);
385 let min_size = style
386 .min_size()
387 .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
388 .maybe_apply_aspect_ratio(aspect_ratio)
389 .maybe_add(box_sizing_adjustment);
390 let max_size = style
391 .max_size()
392 .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
393 .maybe_apply_aspect_ratio(aspect_ratio)
394 .maybe_add(box_sizing_adjustment);
395
396 // css-sizing-4: a definite size in one axis transfers through `aspect-ratio`
397 // to make the other definite. Deriving it from `known_dimensions` self-gates
398 // the transfer — a block parent fills an axis only when it's a real
399 // constraint (e.g. the stretched width at final layout) and leaves it None
400 // while probing intrinsic sizes, so measure passes stay content-based. Only a
401 // newly-filled axis is adopted (and clamped); an incoming known size is left
402 // as the parent resolved it (re-clamping would undo padding/border overrides).
403 let known_dimensions = {
404 let derived = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
405 Size { width: known_dimensions.width.or(derived.width), height: known_dimensions.height.or(derived.height) }
406 };
407 let container_content_box_size = known_dimensions.maybe_sub(content_box_inset.sum_axes());
408
409 let overflow = style.overflow();
410 let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
411
412 // Determine margin collapsing behaviour
413 let own_margins_collapse_with_children = Line {
414 start: vertical_margins_are_collapsible.start
415 && !is_scroll_container
416 && style.position() == Position::Relative
417 && padding.top == 0.0
418 && border.top == 0.0,
419 end: vertical_margins_are_collapsible.end
420 && !is_scroll_container
421 && style.position() == Position::Relative
422 && padding.bottom == 0.0
423 && border.bottom == 0.0
424 && size.height.is_none(),
425 };
426 let has_styles_preventing_being_collapsed_through = !style.is_block()
427 || block_ctx.is_bfc_root()
428 || is_scroll_container
429 || style.position() == Position::Absolute
430 || padding.top > 0.0
431 || padding.bottom > 0.0
432 || border.top > 0.0
433 || border.bottom > 0.0
434 || matches!(size.height, Some(h) if h > 0.0)
435 || matches!(min_size.height, Some(h) if h > 0.0);
436
437 let text_align = style.text_align();
438 let align_content = style.align_content();
439 drop(style);
440
441 // 1. Generate items
442 let mut items = generate_item_list(tree, node_id, container_content_box_size);
443
444 // 2. Compute container width
445 let container_outer_width = known_dimensions.width.unwrap_or_else(|| {
446 let available_width = available_space.width.maybe_sub(content_box_inset.horizontal_axis_sum());
447 let intrinsic_width = determine_content_based_container_width(tree, &items, available_width)
448 + content_box_inset.horizontal_axis_sum();
449 intrinsic_width.maybe_clamp(min_size.width, max_size.width).maybe_max(Some(padding_border_size.width))
450 });
451
452 // Short-circuit if computing size and both dimensions known
453 if let (RunMode::ComputeSize, Some(container_outer_height)) = (run_mode, known_dimensions.height) {
454 return LayoutOutput::from_outer_size(Size { width: container_outer_width, height: container_outer_height });
455 }
456
457 // We can also short-circuit if the width is known and only the width has been requested.
458 if run_mode == RunMode::ComputeSize && inputs.axis == RequestedAxis::Horizontal {
459 return LayoutOutput::from_outer_size(Size { width: container_outer_width, height: 0.0 });
460 }
461
462 let container_percentage_resolution_height =
463 known_dimensions.height.or(size.height.maybe_max(min_size.height)).or(min_size.height);
464
465 // 3. Perform final item layout and return content height
466 let resolved_padding = raw_padding.resolve_or_zero(Some(container_outer_width), |val, basis| tree.calc(val, basis));
467 let resolved_border = raw_border.resolve_or_zero(Some(container_outer_width), |val, basis| tree.calc(val, basis));
468 let resolved_content_box_inset = resolved_padding + resolved_border + scrollbar_gutter;
469 #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
470 let (mut inflow_content_size, mut intrinsic_outer_height, first_child_top_margin_set, last_child_bottom_margin_set) =
471 perform_final_layout_on_in_flow_children(
472 tree,
473 run_mode,
474 &mut items,
475 container_outer_width,
476 container_percentage_resolution_height,
477 content_box_inset,
478 resolved_content_box_inset,
479 text_align,
480 direction,
481 own_margins_collapse_with_children,
482 block_ctx,
483 );
484
485 // Root BFCs contain floats
486 #[cfg(feature = "float_layout")]
487 if block_ctx.is_bfc_root() || is_scroll_container {
488 intrinsic_outer_height = intrinsic_outer_height.max(block_ctx.floated_content_height_contribution());
489 }
490
491 let container_outer_height = known_dimensions
492 .height
493 .unwrap_or(intrinsic_outer_height.maybe_clamp(min_size.height, max_size.height))
494 .maybe_max(Some(padding_border_size.height));
495 let final_outer_size = Size { width: container_outer_width, height: container_outer_height };
496
497 // Apply `align-content` to in-flow non-floated items if requested. The per-item layouts were
498 // held back in `item.final_layout` so that this step can shift `location.y` before tree commit.
499 //
500 // For block layout the entire stack of in-flow children is treated as a single alignment
501 // subject. That means distribution keywords (`space-between`, `space-around`,
502 // `space-evenly`, `stretch`) must invoke the single-subject fallback unconditionally —
503 // which is what passing `num_items = 1` to `apply_alignment_fallback` does. The whole
504 // group then shifts by one offset, with zero inter-item gap.
505 if let Some(align_content) = align_content {
506 let container_inner_height = container_outer_height - resolved_content_box_inset.vertical_axis_sum();
507 let inflow_content_height = intrinsic_outer_height - resolved_content_box_inset.vertical_axis_sum();
508 let free_space = container_inner_height - inflow_content_height;
509 let any_in_flow = items.iter().any(|item| item.final_layout.is_some());
510 if any_in_flow {
511 let keyword = apply_alignment_fallback(free_space, 1, align_content);
512 let group_offset = compute_alignment_offset(free_space, 1, 0.0, keyword, false, true);
513 for item in items.iter_mut() {
514 if let Some(layout) = item.final_layout.as_mut() {
515 layout.location.y += group_offset;
516 }
517 }
518
519 #[cfg(feature = "content_size")]
520 {
521 inflow_content_size = Size::ZERO;
522 for item in items.iter() {
523 if let Some(layout) = item.final_layout.as_ref() {
524 inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
525 layout.location
526 + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
527 layout.size,
528 layout.content_size,
529 item.overflow,
530 ));
531 }
532 }
533 }
534 }
535 }
536
537 // Determine whether this node can be collapsed through
538 let all_in_flow_children_can_be_collapsed_through =
539 items.iter().all(|item| item.position == Position::Absolute || item.can_be_collapsed_through);
540 let can_be_collapsed_through =
541 !has_styles_preventing_being_collapsed_through && all_in_flow_children_can_be_collapsed_through;
542
543 let mut output = LayoutOutput {
544 size: final_outer_size,
545 #[cfg(feature = "content_size")]
546 content_size: Size::ZERO,
547 first_baselines: Point::NONE,
548 top_margin: if own_margins_collapse_with_children.start {
549 first_child_top_margin_set
550 } else {
551 let margin_top = raw_margin.top.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
552 CollapsibleMarginSet::from_margin(margin_top)
553 },
554 bottom_margin: if own_margins_collapse_with_children.end {
555 last_child_bottom_margin_set
556 } else {
557 let margin_bottom =
558 raw_margin.bottom.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
559 CollapsibleMarginSet::from_margin(margin_bottom)
560 },
561 margins_can_collapse_through: can_be_collapsed_through,
562 };
563
564 // Short-circuit if computing size.
565 //
566 // Note: it is important that we return the margin-collapsing related outputs here as Parent block containers
567 // rely on the `top_margin`/`bottom_margin` of their children to compute their own intrinsic height.
568 if run_mode == RunMode::ComputeSize {
569 return output;
570 }
571
572 // Commit deferred in-flow layouts to the tree. Floated items already wrote their own layouts.
573 for item in items.iter() {
574 if let Some(layout) = item.final_layout.as_ref() {
575 tree.set_unrounded_layout(item.node_id, layout);
576 }
577 }
578
579 // 4. Layout absolutely positioned children
580 let absolute_position_inset = resolved_border + scrollbar_gutter;
581 let absolute_position_area = final_outer_size - absolute_position_inset.sum_axes();
582 let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
583 let absolute_content_size = perform_absolute_layout_on_absolute_children(
584 tree,
585 &items,
586 absolute_position_area,
587 absolute_position_offset,
588 direction,
589 );
590
591 #[cfg(feature = "content_size")]
592 {
593 output.content_size = inflow_content_size.f32_max(absolute_content_size);
594 }
595
596 // 5. Perform hidden layout on hidden children
597 let len = tree.child_count(node_id);
598 for order in 0..len {
599 let child = tree.get_child_id(node_id, order);
600 let child_style = tree.get_block_child_style(child);
601 if child_style.box_generation_mode() == BoxGenerationMode::None {
602 drop(child_style);
603 tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
604 tree.perform_child_layout(
605 child,
606 Size::NONE,
607 Size::NONE,
608 Size::MAX_CONTENT,
609 SizingMode::InherentSize,
610 Line::FALSE,
611 );
612 }
613 }
614
615 output
616}
617
618/// Create a `Vec` of `BlockItem` structs where each item in the `Vec` represents a child of the current node
619#[inline]
620fn generate_item_list(
621 tree: &impl LayoutBlockContainer,
622 node: NodeId,
623 node_inner_size: Size<Option<f32>>,
624) -> Vec<BlockItem> {
625 tree.child_ids(node)
626 .map(|child_node_id| (child_node_id, tree.get_block_child_style(child_node_id)))
627 .filter(|(_, style)| style.box_generation_mode() != BoxGenerationMode::None)
628 .enumerate()
629 .map(|(order, (child_node_id, child_style))| {
630 let aspect_ratio = child_style.aspect_ratio();
631 let padding = child_style.padding().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
632 let border = child_style.border().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
633 let pb_sum = (padding + border).sum_axes();
634 let box_sizing_adjustment =
635 if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
636
637 let position = child_style.position();
638 let overflow = child_style.overflow();
639
640 #[cfg(feature = "float_layout")]
641 let float = child_style.float();
642 #[cfg(feature = "float_layout")]
643 let is_not_floated = float == Float::None;
644
645 #[cfg(not(feature = "float_layout"))]
646 let is_not_floated = true;
647
648 let is_block = child_style.is_block();
649 let is_table = child_style.is_table();
650 let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
651
652 let is_in_same_bfc: bool =
653 is_block && !is_table && position != Position::Absolute && is_not_floated && !is_scroll_container;
654
655 BlockItem {
656 node_id: child_node_id,
657 order: order as u32,
658 is_table,
659 is_in_same_bfc,
660 #[cfg(feature = "float_layout")]
661 float,
662 #[cfg(feature = "float_layout")]
663 clear: child_style.clear(),
664 size: child_style
665 .size()
666 .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
667 .maybe_apply_aspect_ratio(aspect_ratio)
668 .maybe_add(box_sizing_adjustment),
669 min_size: child_style
670 .min_size()
671 .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
672 .maybe_apply_aspect_ratio(aspect_ratio)
673 .maybe_add(box_sizing_adjustment),
674 max_size: child_style
675 .max_size()
676 .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
677 .maybe_apply_aspect_ratio(aspect_ratio)
678 .maybe_add(box_sizing_adjustment),
679 overflow,
680 scrollbar_width: child_style.scrollbar_width(),
681 position,
682 inset: child_style.inset(),
683 margin: child_style.margin(),
684 padding,
685 border,
686 padding_border_sum: pb_sum,
687
688 // Fields to be computed later (for now we initialise with dummy values)
689 computed_size: Size::zero(),
690 static_position: Point::zero(),
691 can_be_collapsed_through: false,
692 final_layout: None,
693 }
694 })
695 .collect()
696}
697
698/// Compute the content-based width in the case that the width of the container is not known
699#[inline]
700fn determine_content_based_container_width(
701 tree: &mut impl LayoutPartialTree,
702 items: &[BlockItem],
703 available_width: AvailableSpace,
704) -> f32 {
705 let available_space = Size { width: available_width, height: AvailableSpace::MinContent };
706
707 let mut max_child_width = 0.0;
708 #[cfg(feature = "float_layout")]
709 let mut float_contribution = FloatIntrinsicWidthCalculator::new(available_width);
710 for item in items.iter().filter(|item| item.position != Position::Absolute) {
711 let known_dimensions = item.size.maybe_clamp(item.min_size, item.max_size);
712
713 let item_x_margin_sum = item
714 .margin
715 .resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis))
716 .horizontal_axis_sum();
717 let width = known_dimensions.width.unwrap_or_else(|| {
718 tree.measure_child_size(
719 item.node_id,
720 known_dimensions,
721 Size::NONE,
722 available_space.map_width(|w| w.maybe_sub(item_x_margin_sum)),
723 SizingMode::InherentSize,
724 crate::AbsoluteAxis::Horizontal,
725 Line::TRUE,
726 )
727 });
728
729 let width = f32_max(width, item.padding_border_sum.width) + item_x_margin_sum;
730
731 #[cfg(feature = "float_layout")]
732 if let Some(direction) = item.float.float_direction() {
733 float_contribution.add_float(width, direction, item.clear);
734 continue;
735 }
736
737 max_child_width = f32_max(max_child_width, width);
738 }
739
740 #[cfg(feature = "float_layout")]
741 {
742 max_child_width = max_child_width.max(float_contribution.result());
743 }
744
745 max_child_width
746}
747
748/// Compute each child's final size and position
749#[inline]
750#[allow(clippy::too_many_arguments)]
751fn perform_final_layout_on_in_flow_children(
752 tree: &mut impl LayoutBlockContainer,
753 run_mode: RunMode,
754 items: &mut [BlockItem],
755 container_outer_width: f32,
756 container_percentage_resolution_height: Option<f32>,
757 content_box_inset: Rect<f32>,
758 resolved_content_box_inset: Rect<f32>,
759 text_align: TextAlign,
760 direction: Direction,
761 own_margins_collapse_with_children: Line<bool>,
762 block_ctx: &mut BlockContext<'_>,
763) -> (Size<f32>, f32, CollapsibleMarginSet, CollapsibleMarginSet) {
764 // Resolve container_inner_width for sizing child nodes using initial content_box_inset
765 let container_inner_width = container_outer_width - resolved_content_box_inset.horizontal_axis_sum();
766 let container_percentage_resolution_height =
767 container_percentage_resolution_height.maybe_sub(resolved_content_box_inset.vertical_axis_sum());
768 let parent_size = Size { width: Some(container_inner_width), height: container_percentage_resolution_height };
769 // Vertical available space in block flow is indefinite, NOT a min-content
770 // constraint: MaxContent is taffy's representation of "indefinite".
771 // Passing MinContent here made every descendant grid believe it was being
772 // sized under a min-content constraint, in which the maximize-tracks step
773 // has zero free space — so auto rows containing only scroll-container
774 // items (overflow != visible, automatic minimum size = 0) collapsed to
775 // zero height. Browsers size such rows to the item's content.
776 let available_space =
777 Size { width: AvailableSpace::Definite(container_inner_width), height: AvailableSpace::MaxContent };
778
779 // TODO: handle nested blocks with different widths
780 #[cfg(feature = "float_layout")]
781 if block_ctx.is_bfc_root() {
782 block_ctx.set_width(container_outer_width);
783 block_ctx.apply_content_box_inset([resolved_content_box_inset.left, resolved_content_box_inset.right]);
784 }
785
786 #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
787 let mut inflow_content_size = Size::ZERO;
788 let mut committed_y_offset = resolved_content_box_inset.top;
789 let mut y_offset_for_absolute = resolved_content_box_inset.top;
790 let mut first_child_top_margin_set = CollapsibleMarginSet::ZERO;
791 let mut active_collapsible_margin_set = CollapsibleMarginSet::ZERO;
792 let mut is_collapsing_with_first_margin_set = true;
793
794 #[cfg(feature = "float_layout")]
795 let mut has_active_floats = block_ctx.has_active_floats(committed_y_offset);
796 #[cfg(not(feature = "float_layout"))]
797 let has_active_floats = false;
798 #[cfg(feature = "float_layout")]
799 let mut y_offset_for_float = resolved_content_box_inset.top;
800
801 for item in items.iter_mut() {
802 if item.position == Position::Absolute {
803 let x = match direction {
804 Direction::Ltr => resolved_content_box_inset.left,
805 Direction::Rtl => container_outer_width - resolved_content_box_inset.right,
806 };
807 item.static_position = Point { x, y: y_offset_for_absolute }
808 } else {
809 let item_margin = item
810 .margin
811 .map(|margin| margin.resolve_to_option(container_inner_width, |val, basis| tree.calc(val, basis)));
812 let item_non_auto_margin = item_margin.map(|m| m.unwrap_or(0.0));
813 let item_non_auto_x_margin_sum = item_non_auto_margin.horizontal_axis_sum();
814
815 let scrollbar_size = Size {
816 width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
817 height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
818 };
819
820 // Handle floated boxes
821 #[cfg(feature = "float_layout")]
822 if let Some(float_direction) = item.float.float_direction() {
823 has_active_floats = true;
824
825 let item_layout = tree.perform_child_layout(
826 item.node_id,
827 Size::NONE,
828 parent_size,
829 // available_space,
830 Size::MAX_CONTENT,
831 SizingMode::InherentSize,
832 Line::TRUE,
833 );
834 let margin_box = item_layout.size + item_non_auto_margin.sum_axes();
835
836 let mut location =
837 block_ctx.place_floated_box(margin_box, y_offset_for_float, float_direction, item.clear);
838
839 // Ensure that content that appears after a float does not get positioned before/above the float
840 //
841 // FIXME: this isn't quite right, because a second float at the same location
842 // shouldn't cause content to push down to it's level
843 // committed_y_offset = committed_y_offset.max(location.y);
844 // y_offset_for_absolute = y_offset_for_absolute.max(location.y);
845 // y_offset_for_float = y_offset_for_float.max(location.y);
846
847 // Convert the margin-box location returned by float placement into a border-box location
848 // for the output Layout
849 location.y += item_non_auto_margin.top;
850 location.x += item_non_auto_margin.left;
851
852 // println!("BLOCK FLOATED BOX ({:?}) {:?}", item.node_id, float_direction);
853 // println!("w:{} h:{} x:{}, y:{}", margin_box.width, margin_box.height, location.x, location.y);
854
855 tree.set_unrounded_layout(
856 item.node_id,
857 &Layout {
858 order: item.order,
859 size: item_layout.size,
860 #[cfg(feature = "content_size")]
861 content_size: item_layout.content_size,
862 scrollbar_size,
863 location,
864 padding: item.padding,
865 border: item.border,
866 margin: item_non_auto_margin,
867 },
868 );
869
870 #[cfg(feature = "content_size")]
871 {
872 // TODO: Should content size of floated boxes count as "inflow_content_size"
873 // or should it be counted separately?
874 inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
875 location,
876 item_layout.size,
877 item_layout.content_size,
878 item.overflow,
879 ));
880 }
881
882 continue;
883 }
884
885 // Handle non-floated boxes
886
887 let mut y_margin_offset: f32 = 0.0;
888
889 let (stretch_width, float_avoiding_position, float_avoiding_width) = if item.is_in_same_bfc {
890 let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
891 let position = Point { x: 0.0, y: 0.0 };
892 let width = 0.0;
893
894 (stretch_width, position, width)
895 } else {
896 'block: {
897 // Set y_margin_offset (different bfc child)
898 if !is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start {
899 y_margin_offset =
900 active_collapsible_margin_set.collapse_with_margin(item_non_auto_margin.top).resolve();
901 };
902 let min_y = committed_y_offset + y_margin_offset;
903
904 #[cfg(feature = "float_layout")]
905 if has_active_floats {
906 let slot = block_ctx.find_content_slot(min_y, item.clear, None);
907 has_active_floats = slot.segment_id.is_some();
908 let stretch_width = slot.width - item_non_auto_x_margin_sum;
909 break 'block (stretch_width, Point { x: slot.x, y: slot.y }, slot.width);
910 }
911
912 if !has_active_floats {
913 let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
914 break 'block (
915 stretch_width,
916 Point { x: resolved_content_box_inset.left, y: min_y },
917 container_inner_width,
918 );
919 }
920
921 unreachable!("One of the above cases will always be hit");
922 }
923 };
924
925 let known_dimensions = if item.is_table {
926 Size::NONE
927 } else {
928 item.size
929 .map_width(|width| {
930 // TODO: Allow stretch-sizing to be conditional, as there are exceptions.
931 // e.g. Table children of blocks do not stretch fit
932 Some(width.unwrap_or(stretch_width).maybe_clamp(item.min_size.width, item.max_size.width))
933 })
934 .maybe_clamp(item.min_size, item.max_size)
935 };
936
937 //
938
939 let inputs = LayoutInput {
940 run_mode,
941 sizing_mode: SizingMode::InherentSize,
942 axis: RequestedAxis::Both,
943 known_dimensions,
944 parent_size,
945 available_space: available_space.map_width(|_| AvailableSpace::Definite(stretch_width)),
946 vertical_margins_are_collapsible: if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
947 };
948
949 #[cfg(feature = "float_layout")]
950 let clear_pos = block_ctx.cleared_threshold(item.clear).unwrap_or(f32::NEG_INFINITY);
951 #[cfg(not(feature = "float_layout"))]
952 let clear_pos = f32::NEG_INFINITY;
953
954 let item_layout = if item.is_in_same_bfc {
955 let width = known_dimensions
956 .width
957 .expect("Same-bfc child will always have defined width due to stretch sizing");
958
959 // TODO: account for auto margins
960 let inset_left = item_non_auto_margin.left + content_box_inset.left;
961 let inset_right = container_outer_width - width - inset_left;
962 let insets = [inset_left, inset_right];
963
964 // Compute child layout
965 let mut child_block_ctx =
966 block_ctx.sub_context((y_offset_for_absolute + item_non_auto_margin.top).max(clear_pos), insets);
967 let output = tree.compute_block_child_layout(item.node_id, inputs, Some(&mut child_block_ctx));
968
969 // Extract float contribution from child block context
970 #[cfg(feature = "float_layout")]
971 {
972 let child_contribution = child_block_ctx.floated_content_height_contribution();
973 block_ctx.add_child_floated_content_height_contribution(y_offset_for_absolute + child_contribution);
974 }
975
976 output
977 } else {
978 tree.compute_child_layout(item.node_id, inputs)
979 };
980 let final_size = item_layout.size;
981
982 let top_margin_set = item_layout.top_margin.collapse_with_margin(item_margin.top.unwrap_or(0.0));
983 let bottom_margin_set = item_layout.bottom_margin.collapse_with_margin(item_margin.bottom.unwrap_or(0.0));
984
985 // Expand auto margins to fill available space
986 // Note: Vertical auto-margins for relatively positioned block items simply resolve to 0.
987 // See: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
988 let free_x_space = f32_max(0.0, stretch_width - final_size.width);
989 let x_axis_auto_margin_size = {
990 let auto_margin_count = item_margin.left.is_none() as u8 + item_margin.right.is_none() as u8;
991 if auto_margin_count > 0 {
992 free_x_space / auto_margin_count as f32
993 } else {
994 0.0
995 }
996 };
997 let resolved_margin = Rect {
998 left: item_margin.left.unwrap_or(x_axis_auto_margin_size),
999 right: item_margin.right.unwrap_or(x_axis_auto_margin_size),
1000 top: top_margin_set.resolve(),
1001 bottom: bottom_margin_set.resolve(),
1002 };
1003
1004 // Resolve item inset
1005 let inset = item.inset.zip_size(Size { width: container_inner_width, height: 0.0 }, |p, s| {
1006 p.maybe_resolve(s, |val, basis| tree.calc(val, basis))
1007 });
1008 let inset_offset = Point {
1009 x: if direction.is_rtl() {
1010 inset.right.map(|x| -x).or(inset.left).unwrap_or(0.0)
1011 } else {
1012 inset.left.or(inset.right.map(|x| -x)).unwrap_or(0.0)
1013 },
1014 y: inset.top.or(inset.bottom.map(|x| -x)).unwrap_or(0.0),
1015 };
1016
1017 // Set y_margin_offset (same bfc child)
1018 if item.is_in_same_bfc
1019 && (!is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start)
1020 {
1021 y_margin_offset = active_collapsible_margin_set.collapse_with_margin(resolved_margin.top).resolve()
1022 };
1023
1024 #[cfg(feature = "float_layout")]
1025 let float_or_not_clear = item.float.is_floated() || item.clear == Clear::None;
1026 #[cfg(not(feature = "float_layout"))]
1027 let float_or_not_clear = true;
1028
1029 item.computed_size = item_layout.size;
1030 item.can_be_collapsed_through = item_layout.margins_can_collapse_through && float_or_not_clear;
1031 item.static_position = if item.is_in_same_bfc {
1032 let uncleared_y = committed_y_offset + active_collapsible_margin_set.resolve();
1033 Point {
1034 x: match direction {
1035 Direction::Ltr => resolved_content_box_inset.left,
1036 Direction::Rtl => container_outer_width - resolved_content_box_inset.right - final_size.width,
1037 },
1038 y: uncleared_y.max(clear_pos),
1039 }
1040 } else {
1041 // TODO: handle inset and margins
1042 Point {
1043 x: match direction {
1044 Direction::Ltr => float_avoiding_position.x,
1045 Direction::Rtl => float_avoiding_position.x + float_avoiding_width - final_size.width,
1046 },
1047 y: float_avoiding_position.y,
1048 }
1049 };
1050 let mut location = if item.is_in_same_bfc {
1051 Point {
1052 x: match direction {
1053 Direction::Ltr => resolved_content_box_inset.left + inset_offset.x + resolved_margin.left,
1054 Direction::Rtl => {
1055 container_outer_width
1056 - resolved_content_box_inset.right
1057 - final_size.width
1058 - resolved_margin.right
1059 + inset_offset.x
1060 }
1061 },
1062 y: (committed_y_offset + y_margin_offset).max(clear_pos) + inset_offset.y,
1063 }
1064 } else {
1065 // TODO: handle inset and margins
1066 Point {
1067 x: match direction {
1068 Direction::Ltr => float_avoiding_position.x + resolved_margin.left + inset_offset.x,
1069 Direction::Rtl => {
1070 float_avoiding_position.x + float_avoiding_width - final_size.width - resolved_margin.right
1071 + inset_offset.x
1072 }
1073 },
1074 y: float_avoiding_position.y + inset_offset.y,
1075 }
1076 };
1077
1078 // Apply alignment
1079 let item_outer_width = item_layout.size.width + resolved_margin.horizontal_axis_sum();
1080 if item_outer_width < container_inner_width {
1081 let free_x_space = container_inner_width - item_outer_width;
1082 match (text_align, direction) {
1083 (TextAlign::Auto, _) => {
1084 // Do nothing
1085 }
1086 (TextAlign::LegacyLeft, Direction::Ltr) => {
1087 // Do nothing. Left aligned by default.
1088 }
1089 (TextAlign::LegacyLeft, Direction::Rtl) => location.x -= free_x_space,
1090 (TextAlign::LegacyRight, Direction::Ltr) => location.x += free_x_space,
1091 (TextAlign::LegacyRight, Direction::Rtl) => {
1092 // Do nothing. Right aligned by default.
1093 }
1094 (TextAlign::LegacyCenter, Direction::Ltr) => location.x += free_x_space / 2.0,
1095 (TextAlign::LegacyCenter, Direction::Rtl) => location.x -= free_x_space / 2.0,
1096 }
1097 }
1098
1099 // Defer `set_unrounded_layout` to the post-loop pass in `compute_inner` so that
1100 // `align-content` can shift `location.y` before the layout is committed to the tree.
1101 item.final_layout = Some(Layout {
1102 order: item.order,
1103 size: item_layout.size,
1104 #[cfg(feature = "content_size")]
1105 content_size: item_layout.content_size,
1106 scrollbar_size,
1107 location,
1108 padding: item.padding,
1109 border: item.border,
1110 margin: resolved_margin,
1111 });
1112
1113 #[cfg(feature = "content_size")]
1114 {
1115 inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
1116 location + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
1117 final_size,
1118 item_layout.content_size,
1119 item.overflow,
1120 ));
1121 }
1122
1123 // Update first_child_top_margin_set
1124 if is_collapsing_with_first_margin_set {
1125 if item.can_be_collapsed_through {
1126 first_child_top_margin_set = first_child_top_margin_set
1127 .collapse_with_set(top_margin_set)
1128 .collapse_with_set(bottom_margin_set);
1129 } else {
1130 first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
1131 is_collapsing_with_first_margin_set = false;
1132 }
1133 }
1134
1135 // Update active_collapsible_margin_set
1136 if item.can_be_collapsed_through {
1137 active_collapsible_margin_set = active_collapsible_margin_set
1138 .collapse_with_set(top_margin_set)
1139 .collapse_with_set(bottom_margin_set);
1140 y_offset_for_absolute = committed_y_offset + item_layout.size.height + y_margin_offset;
1141 #[cfg(feature = "float_layout")]
1142 {
1143 y_offset_for_float = committed_y_offset + item_layout.size.height + y_margin_offset;
1144 }
1145 } else {
1146 committed_y_offset = location.y - inset_offset.y + item_layout.size.height;
1147 active_collapsible_margin_set = bottom_margin_set;
1148 y_offset_for_absolute = committed_y_offset + active_collapsible_margin_set.resolve();
1149 #[cfg(feature = "float_layout")]
1150 {
1151 y_offset_for_float = committed_y_offset + active_collapsible_margin_set.resolve();
1152 }
1153 }
1154 }
1155 }
1156
1157 let last_child_bottom_margin_set = active_collapsible_margin_set;
1158 let bottom_y_margin_offset =
1159 if own_margins_collapse_with_children.end { 0.0 } else { last_child_bottom_margin_set.resolve() };
1160
1161 committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
1162 let content_height = f32_max(0.0, committed_y_offset);
1163 (inflow_content_size, content_height, first_child_top_margin_set, last_child_bottom_margin_set)
1164}
1165
1166/// Perform absolute layout on all absolutely positioned children.
1167#[inline]
1168fn perform_absolute_layout_on_absolute_children(
1169 tree: &mut impl LayoutBlockContainer,
1170 items: &[BlockItem],
1171 area_size: Size<f32>,
1172 area_offset: Point<f32>,
1173 direction: Direction,
1174) -> Size<f32> {
1175 let area_width = area_size.width;
1176 let area_height = area_size.height;
1177
1178 #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
1179 let mut absolute_content_size = Size::ZERO;
1180
1181 for item in items.iter().filter(|item| item.position == Position::Absolute) {
1182 let child_style = tree.get_block_child_style(item.node_id);
1183
1184 // Skip items that are display:none or are not position:absolute
1185 if child_style.box_generation_mode() == BoxGenerationMode::None || child_style.position() != Position::Absolute
1186 {
1187 continue;
1188 }
1189
1190 let aspect_ratio = child_style.aspect_ratio();
1191 let margin =
1192 child_style.margin().map(|margin| margin.resolve_to_option(area_width, |val, basis| tree.calc(val, basis)));
1193 let padding = child_style.padding().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1194 let border = child_style.border().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1195 let padding_border_sum = (padding + border).sum_axes();
1196 let box_sizing_adjustment =
1197 if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
1198
1199 // Resolve inset
1200 let left = child_style.inset().left.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1201 let right = child_style.inset().right.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1202 let top = child_style.inset().top.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1203 let bottom = child_style.inset().bottom.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1204
1205 // Compute known dimensions from min/max/inherent size styles
1206 let style_size = child_style
1207 .size()
1208 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1209 .maybe_apply_aspect_ratio(aspect_ratio)
1210 .maybe_add(box_sizing_adjustment);
1211 let min_size = child_style
1212 .min_size()
1213 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1214 .maybe_apply_aspect_ratio(aspect_ratio)
1215 .maybe_add(box_sizing_adjustment)
1216 .or(padding_border_sum.map(Some))
1217 .maybe_max(padding_border_sum);
1218 let max_size = child_style
1219 .max_size()
1220 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1221 .maybe_apply_aspect_ratio(aspect_ratio)
1222 .maybe_add(box_sizing_adjustment);
1223 let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
1224
1225 drop(child_style);
1226
1227 // Fill in width from left/right and reapply aspect ratio if:
1228 // - Width is not already known
1229 // - Item has both left and right inset properties set
1230 if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
1231 let new_width_raw = area_width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
1232 known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
1233 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1234 }
1235
1236 // Fill in height from top/bottom and reapply aspect ratio if:
1237 // - Height is not already known
1238 // - Item has both top and bottom inset properties set
1239 if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
1240 let new_height_raw = area_height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
1241 known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
1242 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1243 }
1244
1245 let measured_size = tree.measure_child_size_both(
1246 item.node_id,
1247 known_dimensions,
1248 area_size.map(Some),
1249 Size {
1250 width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1251 height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1252 },
1253 SizingMode::ContentSize,
1254 Line::FALSE,
1255 );
1256
1257 let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
1258
1259 let layout_output = tree.perform_child_layout(
1260 item.node_id,
1261 final_size.map(Some),
1262 area_size.map(Some),
1263 Size {
1264 width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1265 height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1266 },
1267 SizingMode::ContentSize,
1268 Line::FALSE,
1269 );
1270
1271 let non_auto_margin = Rect {
1272 left: if left.is_some() { margin.left.unwrap_or(0.0) } else { 0.0 },
1273 right: if right.is_some() { margin.right.unwrap_or(0.0) } else { 0.0 },
1274 top: if top.is_some() { margin.top.unwrap_or(0.0) } else { 0.0 },
1275 bottom: if bottom.is_some() { margin.bottom.unwrap_or(0.0) } else { 0.0 },
1276 };
1277
1278 // Expand auto margins to fill available space
1279 // https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
1280 let auto_margin = {
1281 // Auto margins for absolutely positioned elements in block containers only resolve
1282 // if inset is set. Otherwise they resolve to 0.
1283 let absolute_auto_margin_space = Point {
1284 x: right.map(|right| area_size.width - right - left.unwrap_or(0.0)).unwrap_or(final_size.width),
1285 y: bottom.map(|bottom| area_size.height - bottom - top.unwrap_or(0.0)).unwrap_or(final_size.height),
1286 };
1287 let free_space = Size {
1288 width: absolute_auto_margin_space.x - final_size.width - non_auto_margin.horizontal_axis_sum(),
1289 height: absolute_auto_margin_space.y - final_size.height - non_auto_margin.vertical_axis_sum(),
1290 };
1291
1292 let auto_margin_size = Size {
1293 // If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0.
1294 // Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the
1295 // static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.
1296 //
1297 // If none of the three is 'auto': If both 'margin-left' and 'margin-right' are 'auto', solve the equation under the extra constraint
1298 // that the two margins get equal values, unless this would make them negative, in which case when direction of the containing block is
1299 // 'ltr' ('rtl'), set 'margin-left' ('margin-right') to zero and solve for 'margin-right' ('margin-left'). If one of 'margin-left' or
1300 // 'margin-right' is 'auto', solve the equation for that value. If the values are over-constrained, ignore the value for 'left' (in case
1301 // the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value.
1302 width: {
1303 let auto_margin_count = margin.left.is_none() as u8 + margin.right.is_none() as u8;
1304 if auto_margin_count == 2
1305 && (style_size.width.is_none() || style_size.width.unwrap() >= free_space.width)
1306 {
1307 0.0
1308 } else if auto_margin_count > 0 {
1309 free_space.width / auto_margin_count as f32
1310 } else {
1311 0.0
1312 }
1313 },
1314 height: {
1315 let auto_margin_count = margin.top.is_none() as u8 + margin.bottom.is_none() as u8;
1316 if auto_margin_count == 2
1317 && (style_size.height.is_none() || style_size.height.unwrap() >= free_space.height)
1318 {
1319 0.0
1320 } else if auto_margin_count > 0 {
1321 free_space.height / auto_margin_count as f32
1322 } else {
1323 0.0
1324 }
1325 },
1326 };
1327
1328 Rect {
1329 left: margin.left.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1330 right: margin.right.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1331 top: margin.top.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1332 bottom: margin.bottom.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1333 }
1334 };
1335
1336 let resolved_margin = Rect {
1337 left: margin.left.unwrap_or(auto_margin.left),
1338 right: margin.right.unwrap_or(auto_margin.right),
1339 top: margin.top.unwrap_or(auto_margin.top),
1340 bottom: margin.bottom.unwrap_or(auto_margin.bottom),
1341 };
1342
1343 let x_offset = match (left, right) {
1344 (Some(left), Some(right)) => {
1345 if direction.is_rtl() {
1346 area_size.width - final_size.width - right - resolved_margin.right
1347 } else {
1348 left + resolved_margin.left
1349 }
1350 }
1351 (Some(left), None) => left + resolved_margin.left,
1352 (None, Some(right)) => area_size.width - final_size.width - right - resolved_margin.right,
1353 (None, None) => {
1354 if direction.is_rtl() {
1355 item.static_position.x - final_size.width - resolved_margin.right - area_offset.x
1356 } else {
1357 item.static_position.x + resolved_margin.left - area_offset.x
1358 }
1359 }
1360 };
1361 let location = Point {
1362 x: x_offset + area_offset.x,
1363 y: top
1364 .map(|top| top + resolved_margin.top)
1365 .or(bottom.map(|bottom| area_size.height - final_size.height - bottom - resolved_margin.bottom))
1366 .maybe_add(area_offset.y)
1367 .unwrap_or(item.static_position.y + resolved_margin.top),
1368 };
1369 // Note: axis intentionally switched here as scrollbars take up space in the opposite axis
1370 // to the axis in which scrolling is enabled.
1371 let scrollbar_size = Size {
1372 width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1373 height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1374 };
1375
1376 tree.set_unrounded_layout(
1377 item.node_id,
1378 &Layout {
1379 order: item.order,
1380 size: final_size,
1381 #[cfg(feature = "content_size")]
1382 content_size: layout_output.content_size,
1383 scrollbar_size,
1384 location,
1385 padding,
1386 border,
1387 margin: resolved_margin,
1388 },
1389 );
1390
1391 #[cfg(feature = "content_size")]
1392 {
1393 let relative_location = Point { x: location.x - area_offset.x, y: location.y - area_offset.y };
1394 absolute_content_size = absolute_content_size.f32_max(compute_content_size_contribution(
1395 relative_location,
1396 final_size,
1397 layout_output.content_size,
1398 item.overflow,
1399 ));
1400 }
1401 }
1402
1403 absolute_content_size
1404}