Lay out floats with definite available width (#994)
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 // A float with `width: auto` is shrink-to-fit (fit-content) sized: the available
826 // space clamped between its min-content and max-content sizes.
827 let available_width = container_inner_width - item_non_auto_x_margin_sum;
828 let item_layout = tree.perform_child_layout(
829 item.node_id,
830 Size::NONE,
831 parent_size,
832 Size { width: AvailableSpace::Definite(available_width), height: AvailableSpace::MaxContent },
833 SizingMode::InherentSize,
834 Line::TRUE,
835 );
836 let margin_box = item_layout.size + item_non_auto_margin.sum_axes();
837
838 let mut location =
839 block_ctx.place_floated_box(margin_box, y_offset_for_float, float_direction, item.clear);
840
841 // Ensure that content that appears after a float does not get positioned before/above the float
842 //
843 // FIXME: this isn't quite right, because a second float at the same location
844 // shouldn't cause content to push down to it's level
845 // committed_y_offset = committed_y_offset.max(location.y);
846 // y_offset_for_absolute = y_offset_for_absolute.max(location.y);
847 // y_offset_for_float = y_offset_for_float.max(location.y);
848
849 // Convert the margin-box location returned by float placement into a border-box location
850 // for the output Layout
851 location.y += item_non_auto_margin.top;
852 location.x += item_non_auto_margin.left;
853
854 // println!("BLOCK FLOATED BOX ({:?}) {:?}", item.node_id, float_direction);
855 // println!("w:{} h:{} x:{}, y:{}", margin_box.width, margin_box.height, location.x, location.y);
856
857 tree.set_unrounded_layout(
858 item.node_id,
859 &Layout {
860 order: item.order,
861 size: item_layout.size,
862 #[cfg(feature = "content_size")]
863 content_size: item_layout.content_size,
864 scrollbar_size,
865 location,
866 padding: item.padding,
867 border: item.border,
868 margin: item_non_auto_margin,
869 },
870 );
871
872 #[cfg(feature = "content_size")]
873 {
874 // TODO: Should content size of floated boxes count as "inflow_content_size"
875 // or should it be counted separately?
876 inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
877 location,
878 item_layout.size,
879 item_layout.content_size,
880 item.overflow,
881 ));
882 }
883
884 continue;
885 }
886
887 // Handle non-floated boxes
888
889 let mut y_margin_offset: f32 = 0.0;
890
891 let (stretch_width, float_avoiding_position, float_avoiding_width) = if item.is_in_same_bfc {
892 let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
893 let position = Point { x: 0.0, y: 0.0 };
894 let width = 0.0;
895
896 (stretch_width, position, width)
897 } else {
898 'block: {
899 // Set y_margin_offset (different bfc child)
900 if !is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start {
901 y_margin_offset =
902 active_collapsible_margin_set.collapse_with_margin(item_non_auto_margin.top).resolve();
903 };
904 let min_y = committed_y_offset + y_margin_offset;
905
906 #[cfg(feature = "float_layout")]
907 if has_active_floats {
908 let slot = block_ctx.find_content_slot(min_y, item.clear, None);
909 has_active_floats = slot.segment_id.is_some();
910 let stretch_width = slot.width - item_non_auto_x_margin_sum;
911 break 'block (stretch_width, Point { x: slot.x, y: slot.y }, slot.width);
912 }
913
914 if !has_active_floats {
915 let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
916 break 'block (
917 stretch_width,
918 Point { x: resolved_content_box_inset.left, y: min_y },
919 container_inner_width,
920 );
921 }
922
923 unreachable!("One of the above cases will always be hit");
924 }
925 };
926
927 let known_dimensions = if item.is_table {
928 Size::NONE
929 } else {
930 item.size
931 .map_width(|width| {
932 // TODO: Allow stretch-sizing to be conditional, as there are exceptions.
933 // e.g. Table children of blocks do not stretch fit
934 Some(width.unwrap_or(stretch_width).maybe_clamp(item.min_size.width, item.max_size.width))
935 })
936 .maybe_clamp(item.min_size, item.max_size)
937 };
938
939 //
940
941 let inputs = LayoutInput {
942 run_mode,
943 sizing_mode: SizingMode::InherentSize,
944 axis: RequestedAxis::Both,
945 known_dimensions,
946 parent_size,
947 available_space: available_space.map_width(|_| AvailableSpace::Definite(stretch_width)),
948 vertical_margins_are_collapsible: if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
949 };
950
951 #[cfg(feature = "float_layout")]
952 let clear_pos = block_ctx.cleared_threshold(item.clear).unwrap_or(f32::NEG_INFINITY);
953 #[cfg(not(feature = "float_layout"))]
954 let clear_pos = f32::NEG_INFINITY;
955
956 let item_layout = if item.is_in_same_bfc {
957 let width = known_dimensions
958 .width
959 .expect("Same-bfc child will always have defined width due to stretch sizing");
960
961 // TODO: account for auto margins
962 let inset_left = item_non_auto_margin.left + content_box_inset.left;
963 let inset_right = container_outer_width - width - inset_left;
964 let insets = [inset_left, inset_right];
965
966 // Compute child layout
967 let mut child_block_ctx =
968 block_ctx.sub_context((y_offset_for_absolute + item_non_auto_margin.top).max(clear_pos), insets);
969 let output = tree.compute_block_child_layout(item.node_id, inputs, Some(&mut child_block_ctx));
970
971 // Extract float contribution from child block context
972 #[cfg(feature = "float_layout")]
973 {
974 let child_contribution = child_block_ctx.floated_content_height_contribution();
975 block_ctx.add_child_floated_content_height_contribution(y_offset_for_absolute + child_contribution);
976 }
977
978 output
979 } else {
980 tree.compute_child_layout(item.node_id, inputs)
981 };
982 let final_size = item_layout.size;
983
984 let top_margin_set = item_layout.top_margin.collapse_with_margin(item_margin.top.unwrap_or(0.0));
985 let bottom_margin_set = item_layout.bottom_margin.collapse_with_margin(item_margin.bottom.unwrap_or(0.0));
986
987 // Expand auto margins to fill available space
988 // Note: Vertical auto-margins for relatively positioned block items simply resolve to 0.
989 // See: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
990 let free_x_space = f32_max(0.0, stretch_width - final_size.width);
991 let x_axis_auto_margin_size = {
992 let auto_margin_count = item_margin.left.is_none() as u8 + item_margin.right.is_none() as u8;
993 if auto_margin_count > 0 {
994 free_x_space / auto_margin_count as f32
995 } else {
996 0.0
997 }
998 };
999 let resolved_margin = Rect {
1000 left: item_margin.left.unwrap_or(x_axis_auto_margin_size),
1001 right: item_margin.right.unwrap_or(x_axis_auto_margin_size),
1002 top: top_margin_set.resolve(),
1003 bottom: bottom_margin_set.resolve(),
1004 };
1005
1006 // Resolve item inset
1007 let inset = item.inset.zip_size(Size { width: container_inner_width, height: 0.0 }, |p, s| {
1008 p.maybe_resolve(s, |val, basis| tree.calc(val, basis))
1009 });
1010 let inset_offset = Point {
1011 x: if direction.is_rtl() {
1012 inset.right.map(|x| -x).or(inset.left).unwrap_or(0.0)
1013 } else {
1014 inset.left.or(inset.right.map(|x| -x)).unwrap_or(0.0)
1015 },
1016 y: inset.top.or(inset.bottom.map(|x| -x)).unwrap_or(0.0),
1017 };
1018
1019 // Set y_margin_offset (same bfc child)
1020 if item.is_in_same_bfc
1021 && (!is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start)
1022 {
1023 y_margin_offset = active_collapsible_margin_set.collapse_with_margin(resolved_margin.top).resolve()
1024 };
1025
1026 #[cfg(feature = "float_layout")]
1027 let float_or_not_clear = item.float.is_floated() || item.clear == Clear::None;
1028 #[cfg(not(feature = "float_layout"))]
1029 let float_or_not_clear = true;
1030
1031 item.computed_size = item_layout.size;
1032 item.can_be_collapsed_through = item_layout.margins_can_collapse_through && float_or_not_clear;
1033 item.static_position = if item.is_in_same_bfc {
1034 let uncleared_y = committed_y_offset + active_collapsible_margin_set.resolve();
1035 Point {
1036 x: match direction {
1037 Direction::Ltr => resolved_content_box_inset.left,
1038 Direction::Rtl => container_outer_width - resolved_content_box_inset.right - final_size.width,
1039 },
1040 y: uncleared_y.max(clear_pos),
1041 }
1042 } else {
1043 // TODO: handle inset and margins
1044 Point {
1045 x: match direction {
1046 Direction::Ltr => float_avoiding_position.x,
1047 Direction::Rtl => float_avoiding_position.x + float_avoiding_width - final_size.width,
1048 },
1049 y: float_avoiding_position.y,
1050 }
1051 };
1052 let mut location = if item.is_in_same_bfc {
1053 Point {
1054 x: match direction {
1055 Direction::Ltr => resolved_content_box_inset.left + inset_offset.x + resolved_margin.left,
1056 Direction::Rtl => {
1057 container_outer_width
1058 - resolved_content_box_inset.right
1059 - final_size.width
1060 - resolved_margin.right
1061 + inset_offset.x
1062 }
1063 },
1064 y: (committed_y_offset + y_margin_offset).max(clear_pos) + inset_offset.y,
1065 }
1066 } else {
1067 // TODO: handle inset and margins
1068 Point {
1069 x: match direction {
1070 Direction::Ltr => float_avoiding_position.x + resolved_margin.left + inset_offset.x,
1071 Direction::Rtl => {
1072 float_avoiding_position.x + float_avoiding_width - final_size.width - resolved_margin.right
1073 + inset_offset.x
1074 }
1075 },
1076 y: float_avoiding_position.y + inset_offset.y,
1077 }
1078 };
1079
1080 // Apply alignment
1081 let item_outer_width = item_layout.size.width + resolved_margin.horizontal_axis_sum();
1082 if item_outer_width < container_inner_width {
1083 let free_x_space = container_inner_width - item_outer_width;
1084 match (text_align, direction) {
1085 (TextAlign::Auto, _) => {
1086 // Do nothing
1087 }
1088 (TextAlign::LegacyLeft, Direction::Ltr) => {
1089 // Do nothing. Left aligned by default.
1090 }
1091 (TextAlign::LegacyLeft, Direction::Rtl) => location.x -= free_x_space,
1092 (TextAlign::LegacyRight, Direction::Ltr) => location.x += free_x_space,
1093 (TextAlign::LegacyRight, Direction::Rtl) => {
1094 // Do nothing. Right aligned by default.
1095 }
1096 (TextAlign::LegacyCenter, Direction::Ltr) => location.x += free_x_space / 2.0,
1097 (TextAlign::LegacyCenter, Direction::Rtl) => location.x -= free_x_space / 2.0,
1098 }
1099 }
1100
1101 // Defer `set_unrounded_layout` to the post-loop pass in `compute_inner` so that
1102 // `align-content` can shift `location.y` before the layout is committed to the tree.
1103 item.final_layout = Some(Layout {
1104 order: item.order,
1105 size: item_layout.size,
1106 #[cfg(feature = "content_size")]
1107 content_size: item_layout.content_size,
1108 scrollbar_size,
1109 location,
1110 padding: item.padding,
1111 border: item.border,
1112 margin: resolved_margin,
1113 });
1114
1115 #[cfg(feature = "content_size")]
1116 {
1117 inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
1118 location + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
1119 final_size,
1120 item_layout.content_size,
1121 item.overflow,
1122 ));
1123 }
1124
1125 // Update first_child_top_margin_set
1126 if is_collapsing_with_first_margin_set {
1127 if item.can_be_collapsed_through {
1128 first_child_top_margin_set = first_child_top_margin_set
1129 .collapse_with_set(top_margin_set)
1130 .collapse_with_set(bottom_margin_set);
1131 } else {
1132 first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
1133 is_collapsing_with_first_margin_set = false;
1134 }
1135 }
1136
1137 // Update active_collapsible_margin_set
1138 if item.can_be_collapsed_through {
1139 active_collapsible_margin_set = active_collapsible_margin_set
1140 .collapse_with_set(top_margin_set)
1141 .collapse_with_set(bottom_margin_set);
1142 y_offset_for_absolute = committed_y_offset + item_layout.size.height + y_margin_offset;
1143 #[cfg(feature = "float_layout")]
1144 {
1145 y_offset_for_float = committed_y_offset + item_layout.size.height + y_margin_offset;
1146 }
1147 } else {
1148 committed_y_offset = location.y - inset_offset.y + item_layout.size.height;
1149 active_collapsible_margin_set = bottom_margin_set;
1150 y_offset_for_absolute = committed_y_offset + active_collapsible_margin_set.resolve();
1151 #[cfg(feature = "float_layout")]
1152 {
1153 y_offset_for_float = committed_y_offset + active_collapsible_margin_set.resolve();
1154 }
1155 }
1156 }
1157 }
1158
1159 let last_child_bottom_margin_set = active_collapsible_margin_set;
1160 let bottom_y_margin_offset =
1161 if own_margins_collapse_with_children.end { 0.0 } else { last_child_bottom_margin_set.resolve() };
1162
1163 committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
1164 let content_height = f32_max(0.0, committed_y_offset);
1165 (inflow_content_size, content_height, first_child_top_margin_set, last_child_bottom_margin_set)
1166}
1167
1168/// Perform absolute layout on all absolutely positioned children.
1169#[inline]
1170fn perform_absolute_layout_on_absolute_children(
1171 tree: &mut impl LayoutBlockContainer,
1172 items: &[BlockItem],
1173 area_size: Size<f32>,
1174 area_offset: Point<f32>,
1175 direction: Direction,
1176) -> Size<f32> {
1177 let area_width = area_size.width;
1178 let area_height = area_size.height;
1179
1180 #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
1181 let mut absolute_content_size = Size::ZERO;
1182
1183 for item in items.iter().filter(|item| item.position == Position::Absolute) {
1184 let child_style = tree.get_block_child_style(item.node_id);
1185
1186 // Skip items that are display:none or are not position:absolute
1187 if child_style.box_generation_mode() == BoxGenerationMode::None || child_style.position() != Position::Absolute
1188 {
1189 continue;
1190 }
1191
1192 let aspect_ratio = child_style.aspect_ratio();
1193 let margin =
1194 child_style.margin().map(|margin| margin.resolve_to_option(area_width, |val, basis| tree.calc(val, basis)));
1195 let padding = child_style.padding().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1196 let border = child_style.border().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1197 let padding_border_sum = (padding + border).sum_axes();
1198 let box_sizing_adjustment =
1199 if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
1200
1201 // Resolve inset
1202 let left = child_style.inset().left.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1203 let right = child_style.inset().right.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1204 let top = child_style.inset().top.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1205 let bottom = child_style.inset().bottom.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1206
1207 // Compute known dimensions from min/max/inherent size styles
1208 let style_size = child_style
1209 .size()
1210 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1211 .maybe_apply_aspect_ratio(aspect_ratio)
1212 .maybe_add(box_sizing_adjustment);
1213 let min_size = child_style
1214 .min_size()
1215 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1216 .maybe_apply_aspect_ratio(aspect_ratio)
1217 .maybe_add(box_sizing_adjustment)
1218 .or(padding_border_sum.map(Some))
1219 .maybe_max(padding_border_sum);
1220 let max_size = child_style
1221 .max_size()
1222 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1223 .maybe_apply_aspect_ratio(aspect_ratio)
1224 .maybe_add(box_sizing_adjustment);
1225 let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
1226
1227 drop(child_style);
1228
1229 // Fill in width from left/right and reapply aspect ratio if:
1230 // - Width is not already known
1231 // - Item has both left and right inset properties set
1232 if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
1233 let new_width_raw = area_width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
1234 known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
1235 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1236 }
1237
1238 // Fill in height from top/bottom and reapply aspect ratio if:
1239 // - Height is not already known
1240 // - Item has both top and bottom inset properties set
1241 if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
1242 let new_height_raw = area_height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
1243 known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
1244 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1245 }
1246
1247 let measured_size = tree.measure_child_size_both(
1248 item.node_id,
1249 known_dimensions,
1250 area_size.map(Some),
1251 Size {
1252 width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1253 height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1254 },
1255 SizingMode::ContentSize,
1256 Line::FALSE,
1257 );
1258
1259 let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
1260
1261 let layout_output = tree.perform_child_layout(
1262 item.node_id,
1263 final_size.map(Some),
1264 area_size.map(Some),
1265 Size {
1266 width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1267 height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1268 },
1269 SizingMode::ContentSize,
1270 Line::FALSE,
1271 );
1272
1273 let non_auto_margin = Rect {
1274 left: if left.is_some() { margin.left.unwrap_or(0.0) } else { 0.0 },
1275 right: if right.is_some() { margin.right.unwrap_or(0.0) } else { 0.0 },
1276 top: if top.is_some() { margin.top.unwrap_or(0.0) } else { 0.0 },
1277 bottom: if bottom.is_some() { margin.bottom.unwrap_or(0.0) } else { 0.0 },
1278 };
1279
1280 // Expand auto margins to fill available space
1281 // https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
1282 let auto_margin = {
1283 // Auto margins for absolutely positioned elements in block containers only resolve
1284 // if inset is set. Otherwise they resolve to 0.
1285 let absolute_auto_margin_space = Point {
1286 x: right.map(|right| area_size.width - right - left.unwrap_or(0.0)).unwrap_or(final_size.width),
1287 y: bottom.map(|bottom| area_size.height - bottom - top.unwrap_or(0.0)).unwrap_or(final_size.height),
1288 };
1289 let free_space = Size {
1290 width: absolute_auto_margin_space.x - final_size.width - non_auto_margin.horizontal_axis_sum(),
1291 height: absolute_auto_margin_space.y - final_size.height - non_auto_margin.vertical_axis_sum(),
1292 };
1293
1294 let auto_margin_size = Size {
1295 // If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0.
1296 // Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the
1297 // static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.
1298 //
1299 // If none of the three is 'auto': If both 'margin-left' and 'margin-right' are 'auto', solve the equation under the extra constraint
1300 // that the two margins get equal values, unless this would make them negative, in which case when direction of the containing block is
1301 // 'ltr' ('rtl'), set 'margin-left' ('margin-right') to zero and solve for 'margin-right' ('margin-left'). If one of 'margin-left' or
1302 // 'margin-right' is 'auto', solve the equation for that value. If the values are over-constrained, ignore the value for 'left' (in case
1303 // the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value.
1304 width: {
1305 let auto_margin_count = margin.left.is_none() as u8 + margin.right.is_none() as u8;
1306 if auto_margin_count == 2
1307 && (style_size.width.is_none() || style_size.width.unwrap() >= free_space.width)
1308 {
1309 0.0
1310 } else if auto_margin_count > 0 {
1311 free_space.width / auto_margin_count as f32
1312 } else {
1313 0.0
1314 }
1315 },
1316 height: {
1317 let auto_margin_count = margin.top.is_none() as u8 + margin.bottom.is_none() as u8;
1318 if auto_margin_count == 2
1319 && (style_size.height.is_none() || style_size.height.unwrap() >= free_space.height)
1320 {
1321 0.0
1322 } else if auto_margin_count > 0 {
1323 free_space.height / auto_margin_count as f32
1324 } else {
1325 0.0
1326 }
1327 },
1328 };
1329
1330 Rect {
1331 left: margin.left.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1332 right: margin.right.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1333 top: margin.top.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1334 bottom: margin.bottom.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1335 }
1336 };
1337
1338 let resolved_margin = Rect {
1339 left: margin.left.unwrap_or(auto_margin.left),
1340 right: margin.right.unwrap_or(auto_margin.right),
1341 top: margin.top.unwrap_or(auto_margin.top),
1342 bottom: margin.bottom.unwrap_or(auto_margin.bottom),
1343 };
1344
1345 let x_offset = match (left, right) {
1346 (Some(left), Some(right)) => {
1347 if direction.is_rtl() {
1348 area_size.width - final_size.width - right - resolved_margin.right
1349 } else {
1350 left + resolved_margin.left
1351 }
1352 }
1353 (Some(left), None) => left + resolved_margin.left,
1354 (None, Some(right)) => area_size.width - final_size.width - right - resolved_margin.right,
1355 (None, None) => {
1356 if direction.is_rtl() {
1357 item.static_position.x - final_size.width - resolved_margin.right - area_offset.x
1358 } else {
1359 item.static_position.x + resolved_margin.left - area_offset.x
1360 }
1361 }
1362 };
1363 let location = Point {
1364 x: x_offset + area_offset.x,
1365 y: top
1366 .map(|top| top + resolved_margin.top)
1367 .or(bottom.map(|bottom| area_size.height - final_size.height - bottom - resolved_margin.bottom))
1368 .maybe_add(area_offset.y)
1369 .unwrap_or(item.static_position.y + resolved_margin.top),
1370 };
1371 // Note: axis intentionally switched here as scrollbars take up space in the opposite axis
1372 // to the axis in which scrolling is enabled.
1373 let scrollbar_size = Size {
1374 width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1375 height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1376 };
1377
1378 tree.set_unrounded_layout(
1379 item.node_id,
1380 &Layout {
1381 order: item.order,
1382 size: final_size,
1383 #[cfg(feature = "content_size")]
1384 content_size: layout_output.content_size,
1385 scrollbar_size,
1386 location,
1387 padding,
1388 border,
1389 margin: resolved_margin,
1390 },
1391 );
1392
1393 #[cfg(feature = "content_size")]
1394 {
1395 let relative_location = Point { x: location.x - area_offset.x, y: location.y - area_offset.y };
1396 absolute_content_size = absolute_content_size.f32_max(compute_content_size_contribution(
1397 relative_location,
1398 final_size,
1399 layout_output.content_size,
1400 item.overflow,
1401 ));
1402 }
1403 }
1404
1405 absolute_content_size
1406}