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