⎇ b9bfa1d143ab759039d379123f2049f3eafe0611
src/compute/block.rs
Ñawpa willay
Pi imata llamkarqan
ch'uya
Propagate first baselines through block layout (#996)
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 (
471 mut inflow_content_size,
472 mut intrinsic_outer_height,
473 first_child_top_margin_set,
474 last_child_bottom_margin_set,
475 mut first_baseline,
476 ) = perform_final_layout_on_in_flow_children(
477 tree,
478 run_mode,
479 &mut items,
480 container_outer_width,
481 container_percentage_resolution_height,
482 content_box_inset,
483 resolved_content_box_inset,
484 text_align,
485 direction,
486 own_margins_collapse_with_children,
487 block_ctx,
488 );
489
490 // Root BFCs contain floats
491 #[cfg(feature = "float_layout")]
492 if block_ctx.is_bfc_root() || is_scroll_container {
493 intrinsic_outer_height = intrinsic_outer_height.max(block_ctx.floated_content_height_contribution());
494 }
495
496 let container_outer_height = known_dimensions
497 .height
498 .unwrap_or(intrinsic_outer_height.maybe_clamp(min_size.height, max_size.height))
499 .maybe_max(Some(padding_border_size.height));
500 let final_outer_size = Size { width: container_outer_width, height: container_outer_height };
501
502 // Apply `align-content` to in-flow non-floated items if requested. The per-item layouts were
503 // held back in `item.final_layout` so that this step can shift `location.y` before tree commit.
504 //
505 // For block layout the entire stack of in-flow children is treated as a single alignment
506 // subject. That means distribution keywords (`space-between`, `space-around`,
507 // `space-evenly`, `stretch`) must invoke the single-subject fallback unconditionally —
508 // which is what passing `num_items = 1` to `apply_alignment_fallback` does. The whole
509 // group then shifts by one offset, with zero inter-item gap.
510 if let Some(align_content) = align_content {
511 let container_inner_height = container_outer_height - resolved_content_box_inset.vertical_axis_sum();
512 let inflow_content_height = intrinsic_outer_height - resolved_content_box_inset.vertical_axis_sum();
513 let free_space = container_inner_height - inflow_content_height;
514 let any_in_flow = items.iter().any(|item| item.final_layout.is_some());
515 if any_in_flow {
516 let keyword = apply_alignment_fallback(free_space, 1, align_content);
517 let group_offset = compute_alignment_offset(free_space, 1, 0.0, keyword, false, true);
518 first_baseline = first_baseline.map(|baseline| baseline + group_offset);
519 for item in items.iter_mut() {
520 if let Some(layout) = item.final_layout.as_mut() {
521 layout.location.y += group_offset;
522 }
523 }
524
525 #[cfg(feature = "content_size")]
526 {
527 inflow_content_size = Size::ZERO;
528 for item in items.iter() {
529 if let Some(layout) = item.final_layout.as_ref() {
530 inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
531 layout.location
532 + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
533 layout.size,
534 layout.content_size,
535 item.overflow,
536 ));
537 }
538 }
539 }
540 }
541 }
542
543 // Determine whether this node can be collapsed through
544 let all_in_flow_children_can_be_collapsed_through =
545 items.iter().all(|item| item.position == Position::Absolute || item.can_be_collapsed_through);
546 let can_be_collapsed_through =
547 !has_styles_preventing_being_collapsed_through && all_in_flow_children_can_be_collapsed_through;
548
549 let mut output = LayoutOutput {
550 size: final_outer_size,
551 #[cfg(feature = "content_size")]
552 content_size: Size::ZERO,
553 first_baselines: Point { x: None, y: first_baseline },
554 top_margin: if own_margins_collapse_with_children.start {
555 first_child_top_margin_set
556 } else {
557 let margin_top = raw_margin.top.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
558 CollapsibleMarginSet::from_margin(margin_top)
559 },
560 bottom_margin: if own_margins_collapse_with_children.end {
561 last_child_bottom_margin_set
562 } else {
563 let margin_bottom =
564 raw_margin.bottom.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
565 CollapsibleMarginSet::from_margin(margin_bottom)
566 },
567 margins_can_collapse_through: can_be_collapsed_through,
568 };
569
570 // Short-circuit if computing size.
571 //
572 // Note: it is important that we return the margin-collapsing related outputs here as Parent block containers
573 // rely on the `top_margin`/`bottom_margin` of their children to compute their own intrinsic height.
574 if run_mode == RunMode::ComputeSize {
575 return output;
576 }
577
578 // Commit deferred in-flow layouts to the tree. Floated items already wrote their own layouts.
579 for item in items.iter() {
580 if let Some(layout) = item.final_layout.as_ref() {
581 tree.set_unrounded_layout(item.node_id, layout);
582 }
583 }
584
585 // 4. Layout absolutely positioned children
586 let absolute_position_inset = resolved_border + scrollbar_gutter;
587 let absolute_position_area = final_outer_size - absolute_position_inset.sum_axes();
588 let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
589 let absolute_content_size = perform_absolute_layout_on_absolute_children(
590 tree,
591 &items,
592 absolute_position_area,
593 absolute_position_offset,
594 direction,
595 );
596
597 #[cfg(feature = "content_size")]
598 {
599 output.content_size = inflow_content_size.f32_max(absolute_content_size);
600 }
601
602 // 5. Perform hidden layout on hidden children
603 let len = tree.child_count(node_id);
604 for order in 0..len {
605 let child = tree.get_child_id(node_id, order);
606 let child_style = tree.get_block_child_style(child);
607 if child_style.box_generation_mode() == BoxGenerationMode::None {
608 drop(child_style);
609 tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
610 tree.perform_child_layout(
611 child,
612 Size::NONE,
613 Size::NONE,
614 Size::MAX_CONTENT,
615 SizingMode::InherentSize,
616 Line::FALSE,
617 );
618 }
619 }
620
621 output
622}
623
624/// Create a `Vec` of `BlockItem` structs where each item in the `Vec` represents a child of the current node
625#[inline]
626fn generate_item_list(
627 tree: &impl LayoutBlockContainer,
628 node: NodeId,
629 node_inner_size: Size<Option<f32>>,
630) -> Vec<BlockItem> {
631 tree.child_ids(node)
632 .map(|child_node_id| (child_node_id, tree.get_block_child_style(child_node_id)))
633 .filter(|(_, style)| style.box_generation_mode() != BoxGenerationMode::None)
634 .enumerate()
635 .map(|(order, (child_node_id, child_style))| {
636 let aspect_ratio = child_style.aspect_ratio();
637 let padding = child_style.padding().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
638 let border = child_style.border().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
639 let pb_sum = (padding + border).sum_axes();
640 let box_sizing_adjustment =
641 if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
642
643 let position = child_style.position();
644 let overflow = child_style.overflow();
645
646 #[cfg(feature = "float_layout")]
647 let float = child_style.float();
648 #[cfg(feature = "float_layout")]
649 let is_not_floated = float == Float::None;
650
651 #[cfg(not(feature = "float_layout"))]
652 let is_not_floated = true;
653
654 let is_block = child_style.is_block();
655 let is_table = child_style.is_table();
656 let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
657
658 let is_in_same_bfc: bool =
659 is_block && !is_table && position != Position::Absolute && is_not_floated && !is_scroll_container;
660
661 BlockItem {
662 node_id: child_node_id,
663 order: order as u32,
664 is_table,
665 is_in_same_bfc,
666 #[cfg(feature = "float_layout")]
667 float,
668 #[cfg(feature = "float_layout")]
669 clear: child_style.clear(),
670 size: child_style
671 .size()
672 .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
673 .maybe_apply_aspect_ratio(aspect_ratio)
674 .maybe_add(box_sizing_adjustment),
675 min_size: child_style
676 .min_size()
677 .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
678 .maybe_apply_aspect_ratio(aspect_ratio)
679 .maybe_add(box_sizing_adjustment),
680 max_size: child_style
681 .max_size()
682 .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
683 .maybe_apply_aspect_ratio(aspect_ratio)
684 .maybe_add(box_sizing_adjustment),
685 overflow,
686 scrollbar_width: child_style.scrollbar_width(),
687 position,
688 inset: child_style.inset(),
689 margin: child_style.margin(),
690 padding,
691 border,
692 padding_border_sum: pb_sum,
693
694 // Fields to be computed later (for now we initialise with dummy values)
695 computed_size: Size::zero(),
696 static_position: Point::zero(),
697 can_be_collapsed_through: false,
698 final_layout: None,
699 }
700 })
701 .collect()
702}
703
704/// Compute the content-based width in the case that the width of the container is not known
705#[inline]
706fn determine_content_based_container_width(
707 tree: &mut impl LayoutPartialTree,
708 items: &[BlockItem],
709 available_width: AvailableSpace,
710) -> f32 {
711 let available_space = Size { width: available_width, height: AvailableSpace::MinContent };
712
713 let mut max_child_width = 0.0;
714 #[cfg(feature = "float_layout")]
715 let mut float_contribution = FloatIntrinsicWidthCalculator::new(available_width);
716 for item in items.iter().filter(|item| item.position != Position::Absolute) {
717 let known_dimensions = item.size.maybe_clamp(item.min_size, item.max_size);
718
719 let item_x_margin_sum = item
720 .margin
721 .resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis))
722 .horizontal_axis_sum();
723 let width = known_dimensions.width.unwrap_or_else(|| {
724 tree.measure_child_size(
725 item.node_id,
726 known_dimensions,
727 Size::NONE,
728 available_space.map_width(|w| w.maybe_sub(item_x_margin_sum)),
729 SizingMode::InherentSize,
730 crate::AbsoluteAxis::Horizontal,
731 Line::TRUE,
732 )
733 });
734
735 let width = f32_max(width, item.padding_border_sum.width) + item_x_margin_sum;
736
737 #[cfg(feature = "float_layout")]
738 if let Some(direction) = item.float.float_direction() {
739 float_contribution.add_float(width, direction, item.clear);
740 continue;
741 }
742
743 max_child_width = f32_max(max_child_width, width);
744 }
745
746 #[cfg(feature = "float_layout")]
747 {
748 max_child_width = max_child_width.max(float_contribution.result());
749 }
750
751 max_child_width
752}
753
754/// Compute each child's final size and position
755#[inline]
756#[allow(clippy::too_many_arguments)]
757fn perform_final_layout_on_in_flow_children(
758 tree: &mut impl LayoutBlockContainer,
759 run_mode: RunMode,
760 items: &mut [BlockItem],
761 container_outer_width: f32,
762 container_percentage_resolution_height: Option<f32>,
763 content_box_inset: Rect<f32>,
764 resolved_content_box_inset: Rect<f32>,
765 text_align: TextAlign,
766 direction: Direction,
767 own_margins_collapse_with_children: Line<bool>,
768 block_ctx: &mut BlockContext<'_>,
769) -> (Size<f32>, f32, CollapsibleMarginSet, CollapsibleMarginSet, Option<f32>) {
770 // Resolve container_inner_width for sizing child nodes using initial content_box_inset
771 let container_inner_width = container_outer_width - resolved_content_box_inset.horizontal_axis_sum();
772 let container_percentage_resolution_height =
773 container_percentage_resolution_height.maybe_sub(resolved_content_box_inset.vertical_axis_sum());
774 let parent_size = Size { width: Some(container_inner_width), height: container_percentage_resolution_height };
775 // Vertical available space in block flow is indefinite, NOT a min-content
776 // constraint: MaxContent is taffy's representation of "indefinite".
777 // Passing MinContent here made every descendant grid believe it was being
778 // sized under a min-content constraint, in which the maximize-tracks step
779 // has zero free space — so auto rows containing only scroll-container
780 // items (overflow != visible, automatic minimum size = 0) collapsed to
781 // zero height. Browsers size such rows to the item's content.
782 let available_space =
783 Size { width: AvailableSpace::Definite(container_inner_width), height: AvailableSpace::MaxContent };
784
785 // TODO: handle nested blocks with different widths
786 #[cfg(feature = "float_layout")]
787 if block_ctx.is_bfc_root() {
788 block_ctx.set_width(container_outer_width);
789 block_ctx.apply_content_box_inset([resolved_content_box_inset.left, resolved_content_box_inset.right]);
790 }
791
792 #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
793 let mut inflow_content_size = Size::ZERO;
794 let mut committed_y_offset = resolved_content_box_inset.top;
795 let mut y_offset_for_absolute = resolved_content_box_inset.top;
796 let mut first_child_top_margin_set = CollapsibleMarginSet::ZERO;
797 let mut active_collapsible_margin_set = CollapsibleMarginSet::ZERO;
798 let mut is_collapsing_with_first_margin_set = true;
799 let mut first_baseline: Option<f32> = None;
800
801 #[cfg(feature = "float_layout")]
802 let mut has_active_floats = block_ctx.has_active_floats(committed_y_offset);
803 #[cfg(not(feature = "float_layout"))]
804 let has_active_floats = false;
805 #[cfg(feature = "float_layout")]
806 let mut y_offset_for_float = resolved_content_box_inset.top;
807
808 for item in items.iter_mut() {
809 if item.position == Position::Absolute {
810 let x = match direction {
811 Direction::Ltr => resolved_content_box_inset.left,
812 Direction::Rtl => container_outer_width - resolved_content_box_inset.right,
813 };
814 item.static_position = Point { x, y: y_offset_for_absolute }
815 } else {
816 let item_margin = item
817 .margin
818 .map(|margin| margin.resolve_to_option(container_inner_width, |val, basis| tree.calc(val, basis)));
819 let item_non_auto_margin = item_margin.map(|m| m.unwrap_or(0.0));
820 let item_non_auto_x_margin_sum = item_non_auto_margin.horizontal_axis_sum();
821
822 let scrollbar_size = Size {
823 width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
824 height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
825 };
826
827 // Handle floated boxes
828 #[cfg(feature = "float_layout")]
829 if let Some(float_direction) = item.float.float_direction() {
830 has_active_floats = true;
831
832 // A float with `width: auto` is shrink-to-fit (fit-content) sized: the available
833 // space clamped between its min-content and max-content sizes.
834 let available_width = container_inner_width - item_non_auto_x_margin_sum;
835 let item_layout = tree.perform_child_layout(
836 item.node_id,
837 Size::NONE,
838 parent_size,
839 Size { width: AvailableSpace::Definite(available_width), height: AvailableSpace::MaxContent },
840 SizingMode::InherentSize,
841 Line::TRUE,
842 );
843 let margin_box = item_layout.size + item_non_auto_margin.sum_axes();
844
845 let mut location =
846 block_ctx.place_floated_box(margin_box, y_offset_for_float, float_direction, item.clear);
847
848 // Ensure that content that appears after a float does not get positioned before/above the float
849 //
850 // FIXME: this isn't quite right, because a second float at the same location
851 // shouldn't cause content to push down to it's level
852 // committed_y_offset = committed_y_offset.max(location.y);
853 // y_offset_for_absolute = y_offset_for_absolute.max(location.y);
854 // y_offset_for_float = y_offset_for_float.max(location.y);
855
856 // Convert the margin-box location returned by float placement into a border-box location
857 // for the output Layout
858 location.y += item_non_auto_margin.top;
859 location.x += item_non_auto_margin.left;
860
861 // println!("BLOCK FLOATED BOX ({:?}) {:?}", item.node_id, float_direction);
862 // println!("w:{} h:{} x:{}, y:{}", margin_box.width, margin_box.height, location.x, location.y);
863
864 tree.set_unrounded_layout(
865 item.node_id,
866 &Layout {
867 order: item.order,
868 size: item_layout.size,
869 #[cfg(feature = "content_size")]
870 content_size: item_layout.content_size,
871 scrollbar_size,
872 location,
873 padding: item.padding,
874 border: item.border,
875 margin: item_non_auto_margin,
876 },
877 );
878
879 #[cfg(feature = "content_size")]
880 {
881 // TODO: Should content size of floated boxes count as "inflow_content_size"
882 // or should it be counted separately?
883 inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
884 location,
885 item_layout.size,
886 item_layout.content_size,
887 item.overflow,
888 ));
889 }
890
891 continue;
892 }
893
894 // Handle non-floated boxes
895
896 let mut y_margin_offset: f32 = 0.0;
897
898 let (stretch_width, float_avoiding_position, float_avoiding_width) = if item.is_in_same_bfc {
899 let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
900 let position = Point { x: 0.0, y: 0.0 };
901 let width = 0.0;
902
903 (stretch_width, position, width)
904 } else {
905 'block: {
906 // Set y_margin_offset (different bfc child)
907 if !is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start {
908 y_margin_offset =
909 active_collapsible_margin_set.collapse_with_margin(item_non_auto_margin.top).resolve();
910 };
911 let min_y = committed_y_offset + y_margin_offset;
912
913 #[cfg(feature = "float_layout")]
914 if has_active_floats {
915 let slot = block_ctx.find_content_slot(min_y, item.clear, None);
916 has_active_floats = slot.segment_id.is_some();
917 let stretch_width = slot.width - item_non_auto_x_margin_sum;
918 break 'block (stretch_width, Point { x: slot.x, y: slot.y }, slot.width);
919 }
920
921 if !has_active_floats {
922 let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
923 break 'block (
924 stretch_width,
925 Point { x: resolved_content_box_inset.left, y: min_y },
926 container_inner_width,
927 );
928 }
929
930 unreachable!("One of the above cases will always be hit");
931 }
932 };
933
934 let known_dimensions = if item.is_table {
935 Size::NONE
936 } else {
937 item.size
938 .map_width(|width| {
939 // TODO: Allow stretch-sizing to be conditional, as there are exceptions.
940 // e.g. Table children of blocks do not stretch fit
941 Some(width.unwrap_or(stretch_width).maybe_clamp(item.min_size.width, item.max_size.width))
942 })
943 .maybe_clamp(item.min_size, item.max_size)
944 };
945
946 //
947
948 let inputs = LayoutInput {
949 run_mode,
950 sizing_mode: SizingMode::InherentSize,
951 axis: RequestedAxis::Both,
952 known_dimensions,
953 parent_size,
954 available_space: available_space.map_width(|_| AvailableSpace::Definite(stretch_width)),
955 vertical_margins_are_collapsible: if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
956 };
957
958 #[cfg(feature = "float_layout")]
959 let clear_pos = block_ctx.cleared_threshold(item.clear).unwrap_or(f32::NEG_INFINITY);
960 #[cfg(not(feature = "float_layout"))]
961 let clear_pos = f32::NEG_INFINITY;
962
963 let item_layout = if item.is_in_same_bfc {
964 let width = known_dimensions
965 .width
966 .expect("Same-bfc child will always have defined width due to stretch sizing");
967
968 // TODO: account for auto margins
969 let inset_left = item_non_auto_margin.left + content_box_inset.left;
970 let inset_right = container_outer_width - width - inset_left;
971 let insets = [inset_left, inset_right];
972
973 // Compute child layout
974 let mut child_block_ctx =
975 block_ctx.sub_context((y_offset_for_absolute + item_non_auto_margin.top).max(clear_pos), insets);
976 let output = tree.compute_block_child_layout(item.node_id, inputs, Some(&mut child_block_ctx));
977
978 // Extract float contribution from child block context
979 #[cfg(feature = "float_layout")]
980 {
981 let child_contribution = child_block_ctx.floated_content_height_contribution();
982 block_ctx.add_child_floated_content_height_contribution(y_offset_for_absolute + child_contribution);
983 }
984
985 output
986 } else {
987 tree.compute_child_layout(item.node_id, inputs)
988 };
989 let final_size = item_layout.size;
990
991 let top_margin_set = item_layout.top_margin.collapse_with_margin(item_margin.top.unwrap_or(0.0));
992 let bottom_margin_set = item_layout.bottom_margin.collapse_with_margin(item_margin.bottom.unwrap_or(0.0));
993
994 // Expand auto margins to fill available space
995 // Note: Vertical auto-margins for relatively positioned block items simply resolve to 0.
996 // See: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
997 let free_x_space = f32_max(0.0, stretch_width - final_size.width);
998 let x_axis_auto_margin_size = {
999 let auto_margin_count = item_margin.left.is_none() as u8 + item_margin.right.is_none() as u8;
1000 if auto_margin_count > 0 {
1001 free_x_space / auto_margin_count as f32
1002 } else {
1003 0.0
1004 }
1005 };
1006 let resolved_margin = Rect {
1007 left: item_margin.left.unwrap_or(x_axis_auto_margin_size),
1008 right: item_margin.right.unwrap_or(x_axis_auto_margin_size),
1009 top: top_margin_set.resolve(),
1010 bottom: bottom_margin_set.resolve(),
1011 };
1012
1013 // Resolve item inset
1014 let inset = item.inset.zip_size(Size { width: container_inner_width, height: 0.0 }, |p, s| {
1015 p.maybe_resolve(s, |val, basis| tree.calc(val, basis))
1016 });
1017 let inset_offset = Point {
1018 x: if direction.is_rtl() {
1019 inset.right.map(|x| -x).or(inset.left).unwrap_or(0.0)
1020 } else {
1021 inset.left.or(inset.right.map(|x| -x)).unwrap_or(0.0)
1022 },
1023 y: inset.top.or(inset.bottom.map(|x| -x)).unwrap_or(0.0),
1024 };
1025
1026 // Set y_margin_offset (same bfc child)
1027 if item.is_in_same_bfc
1028 && (!is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start)
1029 {
1030 y_margin_offset = active_collapsible_margin_set.collapse_with_margin(resolved_margin.top).resolve()
1031 };
1032
1033 #[cfg(feature = "float_layout")]
1034 let float_or_not_clear = item.float.is_floated() || item.clear == Clear::None;
1035 #[cfg(not(feature = "float_layout"))]
1036 let float_or_not_clear = true;
1037
1038 item.computed_size = item_layout.size;
1039 item.can_be_collapsed_through = item_layout.margins_can_collapse_through && float_or_not_clear;
1040 item.static_position = if item.is_in_same_bfc {
1041 let uncleared_y = committed_y_offset + active_collapsible_margin_set.resolve();
1042 Point {
1043 x: match direction {
1044 Direction::Ltr => resolved_content_box_inset.left,
1045 Direction::Rtl => container_outer_width - resolved_content_box_inset.right - final_size.width,
1046 },
1047 y: uncleared_y.max(clear_pos),
1048 }
1049 } else {
1050 // TODO: handle inset and margins
1051 Point {
1052 x: match direction {
1053 Direction::Ltr => float_avoiding_position.x,
1054 Direction::Rtl => float_avoiding_position.x + float_avoiding_width - final_size.width,
1055 },
1056 y: float_avoiding_position.y,
1057 }
1058 };
1059 let mut location = if item.is_in_same_bfc {
1060 Point {
1061 x: match direction {
1062 Direction::Ltr => resolved_content_box_inset.left + inset_offset.x + resolved_margin.left,
1063 Direction::Rtl => {
1064 container_outer_width
1065 - resolved_content_box_inset.right
1066 - final_size.width
1067 - resolved_margin.right
1068 + inset_offset.x
1069 }
1070 },
1071 y: (committed_y_offset + y_margin_offset).max(clear_pos) + inset_offset.y,
1072 }
1073 } else {
1074 // TODO: handle inset and margins
1075 Point {
1076 x: match direction {
1077 Direction::Ltr => float_avoiding_position.x + resolved_margin.left + inset_offset.x,
1078 Direction::Rtl => {
1079 float_avoiding_position.x + float_avoiding_width - final_size.width - resolved_margin.right
1080 + inset_offset.x
1081 }
1082 },
1083 y: float_avoiding_position.y + inset_offset.y,
1084 }
1085 };
1086
1087 // Apply alignment
1088 let item_outer_width = item_layout.size.width + resolved_margin.horizontal_axis_sum();
1089 if item_outer_width < container_inner_width {
1090 let free_x_space = container_inner_width - item_outer_width;
1091 match (text_align, direction) {
1092 (TextAlign::Auto, _) => {
1093 // Do nothing
1094 }
1095 (TextAlign::LegacyLeft, Direction::Ltr) => {
1096 // Do nothing. Left aligned by default.
1097 }
1098 (TextAlign::LegacyLeft, Direction::Rtl) => location.x -= free_x_space,
1099 (TextAlign::LegacyRight, Direction::Ltr) => location.x += free_x_space,
1100 (TextAlign::LegacyRight, Direction::Rtl) => {
1101 // Do nothing. Right aligned by default.
1102 }
1103 (TextAlign::LegacyCenter, Direction::Ltr) => location.x += free_x_space / 2.0,
1104 (TextAlign::LegacyCenter, Direction::Rtl) => location.x -= free_x_space / 2.0,
1105 }
1106 }
1107
1108 // A block container's first baseline is the first baseline of its first in-flow child
1109 // that has one.
1110 if first_baseline.is_none() {
1111 first_baseline = item_layout.first_baselines.y.map(|baseline| location.y + baseline);
1112 }
1113
1114 // Defer `set_unrounded_layout` to the post-loop pass in `compute_inner` so that
1115 // `align-content` can shift `location.y` before the layout is committed to the tree.
1116 item.final_layout = Some(Layout {
1117 order: item.order,
1118 size: item_layout.size,
1119 #[cfg(feature = "content_size")]
1120 content_size: item_layout.content_size,
1121 scrollbar_size,
1122 location,
1123 padding: item.padding,
1124 border: item.border,
1125 margin: resolved_margin,
1126 });
1127
1128 #[cfg(feature = "content_size")]
1129 {
1130 inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
1131 location + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
1132 final_size,
1133 item_layout.content_size,
1134 item.overflow,
1135 ));
1136 }
1137
1138 // Update first_child_top_margin_set
1139 if is_collapsing_with_first_margin_set {
1140 if item.can_be_collapsed_through {
1141 first_child_top_margin_set = first_child_top_margin_set
1142 .collapse_with_set(top_margin_set)
1143 .collapse_with_set(bottom_margin_set);
1144 } else {
1145 first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
1146 is_collapsing_with_first_margin_set = false;
1147 }
1148 }
1149
1150 // Update active_collapsible_margin_set
1151 if item.can_be_collapsed_through {
1152 active_collapsible_margin_set = active_collapsible_margin_set
1153 .collapse_with_set(top_margin_set)
1154 .collapse_with_set(bottom_margin_set);
1155 y_offset_for_absolute = committed_y_offset + item_layout.size.height + y_margin_offset;
1156 #[cfg(feature = "float_layout")]
1157 {
1158 y_offset_for_float = committed_y_offset + item_layout.size.height + y_margin_offset;
1159 }
1160 } else {
1161 committed_y_offset = location.y - inset_offset.y + item_layout.size.height;
1162 active_collapsible_margin_set = bottom_margin_set;
1163 y_offset_for_absolute = committed_y_offset + active_collapsible_margin_set.resolve();
1164 #[cfg(feature = "float_layout")]
1165 {
1166 y_offset_for_float = committed_y_offset + active_collapsible_margin_set.resolve();
1167 }
1168 }
1169 }
1170 }
1171
1172 let last_child_bottom_margin_set = active_collapsible_margin_set;
1173 let bottom_y_margin_offset =
1174 if own_margins_collapse_with_children.end { 0.0 } else { last_child_bottom_margin_set.resolve() };
1175
1176 committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
1177 let content_height = f32_max(0.0, committed_y_offset);
1178 (inflow_content_size, content_height, first_child_top_margin_set, last_child_bottom_margin_set, first_baseline)
1179}
1180
1181/// Perform absolute layout on all absolutely positioned children.
1182#[inline]
1183fn perform_absolute_layout_on_absolute_children(
1184 tree: &mut impl LayoutBlockContainer,
1185 items: &[BlockItem],
1186 area_size: Size<f32>,
1187 area_offset: Point<f32>,
1188 direction: Direction,
1189) -> Size<f32> {
1190 let area_width = area_size.width;
1191 let area_height = area_size.height;
1192
1193 #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
1194 let mut absolute_content_size = Size::ZERO;
1195
1196 for item in items.iter().filter(|item| item.position == Position::Absolute) {
1197 let child_style = tree.get_block_child_style(item.node_id);
1198
1199 // Skip items that are display:none or are not position:absolute
1200 if child_style.box_generation_mode() == BoxGenerationMode::None || child_style.position() != Position::Absolute
1201 {
1202 continue;
1203 }
1204
1205 let aspect_ratio = child_style.aspect_ratio();
1206 let margin =
1207 child_style.margin().map(|margin| margin.resolve_to_option(area_width, |val, basis| tree.calc(val, basis)));
1208 let padding = child_style.padding().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1209 let border = child_style.border().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1210 let padding_border_sum = (padding + border).sum_axes();
1211 let box_sizing_adjustment =
1212 if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
1213
1214 // Resolve inset
1215 let left = child_style.inset().left.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1216 let right = child_style.inset().right.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1217 let top = child_style.inset().top.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1218 let bottom = child_style.inset().bottom.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1219
1220 // Compute known dimensions from min/max/inherent size styles
1221 let style_size = child_style
1222 .size()
1223 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1224 .maybe_apply_aspect_ratio(aspect_ratio)
1225 .maybe_add(box_sizing_adjustment);
1226 let min_size = child_style
1227 .min_size()
1228 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1229 .maybe_apply_aspect_ratio(aspect_ratio)
1230 .maybe_add(box_sizing_adjustment)
1231 .or(padding_border_sum.map(Some))
1232 .maybe_max(padding_border_sum);
1233 let max_size = child_style
1234 .max_size()
1235 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1236 .maybe_apply_aspect_ratio(aspect_ratio)
1237 .maybe_add(box_sizing_adjustment);
1238 let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
1239
1240 drop(child_style);
1241
1242 // Fill in width from left/right and reapply aspect ratio if:
1243 // - Width is not already known
1244 // - Item has both left and right inset properties set
1245 if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
1246 let new_width_raw = area_width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
1247 known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
1248 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1249 }
1250
1251 // Fill in height from top/bottom and reapply aspect ratio if:
1252 // - Height is not already known
1253 // - Item has both top and bottom inset properties set
1254 if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
1255 let new_height_raw = area_height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
1256 known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
1257 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1258 }
1259
1260 let measured_size = tree.measure_child_size_both(
1261 item.node_id,
1262 known_dimensions,
1263 area_size.map(Some),
1264 Size {
1265 width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1266 height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1267 },
1268 SizingMode::ContentSize,
1269 Line::FALSE,
1270 );
1271
1272 let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
1273
1274 let layout_output = tree.perform_child_layout(
1275 item.node_id,
1276 final_size.map(Some),
1277 area_size.map(Some),
1278 Size {
1279 width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1280 height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1281 },
1282 SizingMode::ContentSize,
1283 Line::FALSE,
1284 );
1285
1286 let non_auto_margin = Rect {
1287 left: if left.is_some() { margin.left.unwrap_or(0.0) } else { 0.0 },
1288 right: if right.is_some() { margin.right.unwrap_or(0.0) } else { 0.0 },
1289 top: if top.is_some() { margin.top.unwrap_or(0.0) } else { 0.0 },
1290 bottom: if bottom.is_some() { margin.bottom.unwrap_or(0.0) } else { 0.0 },
1291 };
1292
1293 // Expand auto margins to fill available space
1294 // https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
1295 let auto_margin = {
1296 // Auto margins for absolutely positioned elements in block containers only resolve
1297 // if inset is set. Otherwise they resolve to 0.
1298 let absolute_auto_margin_space = Point {
1299 x: right.map(|right| area_size.width - right - left.unwrap_or(0.0)).unwrap_or(final_size.width),
1300 y: bottom.map(|bottom| area_size.height - bottom - top.unwrap_or(0.0)).unwrap_or(final_size.height),
1301 };
1302 let free_space = Size {
1303 width: absolute_auto_margin_space.x - final_size.width - non_auto_margin.horizontal_axis_sum(),
1304 height: absolute_auto_margin_space.y - final_size.height - non_auto_margin.vertical_axis_sum(),
1305 };
1306
1307 let auto_margin_size = Size {
1308 // If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0.
1309 // Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the
1310 // static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.
1311 //
1312 // If none of the three is 'auto': If both 'margin-left' and 'margin-right' are 'auto', solve the equation under the extra constraint
1313 // that the two margins get equal values, unless this would make them negative, in which case when direction of the containing block is
1314 // 'ltr' ('rtl'), set 'margin-left' ('margin-right') to zero and solve for 'margin-right' ('margin-left'). If one of 'margin-left' or
1315 // 'margin-right' is 'auto', solve the equation for that value. If the values are over-constrained, ignore the value for 'left' (in case
1316 // the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value.
1317 width: {
1318 let auto_margin_count = margin.left.is_none() as u8 + margin.right.is_none() as u8;
1319 if auto_margin_count == 2
1320 && (style_size.width.is_none() || style_size.width.unwrap() >= free_space.width)
1321 {
1322 0.0
1323 } else if auto_margin_count > 0 {
1324 free_space.width / auto_margin_count as f32
1325 } else {
1326 0.0
1327 }
1328 },
1329 height: {
1330 let auto_margin_count = margin.top.is_none() as u8 + margin.bottom.is_none() as u8;
1331 if auto_margin_count == 2
1332 && (style_size.height.is_none() || style_size.height.unwrap() >= free_space.height)
1333 {
1334 0.0
1335 } else if auto_margin_count > 0 {
1336 free_space.height / auto_margin_count as f32
1337 } else {
1338 0.0
1339 }
1340 },
1341 };
1342
1343 Rect {
1344 left: margin.left.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1345 right: margin.right.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1346 top: margin.top.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1347 bottom: margin.bottom.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1348 }
1349 };
1350
1351 let resolved_margin = Rect {
1352 left: margin.left.unwrap_or(auto_margin.left),
1353 right: margin.right.unwrap_or(auto_margin.right),
1354 top: margin.top.unwrap_or(auto_margin.top),
1355 bottom: margin.bottom.unwrap_or(auto_margin.bottom),
1356 };
1357
1358 let x_offset = match (left, right) {
1359 (Some(left), Some(right)) => {
1360 if direction.is_rtl() {
1361 area_size.width - final_size.width - right - resolved_margin.right
1362 } else {
1363 left + resolved_margin.left
1364 }
1365 }
1366 (Some(left), None) => left + resolved_margin.left,
1367 (None, Some(right)) => area_size.width - final_size.width - right - resolved_margin.right,
1368 (None, None) => {
1369 if direction.is_rtl() {
1370 item.static_position.x - final_size.width - resolved_margin.right - area_offset.x
1371 } else {
1372 item.static_position.x + resolved_margin.left - area_offset.x
1373 }
1374 }
1375 };
1376 let location = Point {
1377 x: x_offset + area_offset.x,
1378 y: top
1379 .map(|top| top + resolved_margin.top)
1380 .or(bottom.map(|bottom| area_size.height - final_size.height - bottom - resolved_margin.bottom))
1381 .maybe_add(area_offset.y)
1382 .unwrap_or(item.static_position.y + resolved_margin.top),
1383 };
1384 // Note: axis intentionally switched here as scrollbars take up space in the opposite axis
1385 // to the axis in which scrolling is enabled.
1386 let scrollbar_size = Size {
1387 width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1388 height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1389 };
1390
1391 tree.set_unrounded_layout(
1392 item.node_id,
1393 &Layout {
1394 order: item.order,
1395 size: final_size,
1396 #[cfg(feature = "content_size")]
1397 content_size: layout_output.content_size,
1398 scrollbar_size,
1399 location,
1400 padding,
1401 border,
1402 margin: resolved_margin,
1403 },
1404 );
1405
1406 #[cfg(feature = "content_size")]
1407 {
1408 let relative_location = Point { x: location.x - area_offset.x, y: location.y - area_offset.y };
1409 absolute_content_size = absolute_content_size.f32_max(compute_content_size_contribution(
1410 relative_location,
1411 final_size,
1412 layout_output.content_size,
1413 item.overflow,
1414 ));
1415 }
1416 }
1417
1418 absolute_content_size
1419}