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