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