⎇ 2ca609ecf19c2e34bca2ce1fe1f4e73b09d62a97
src/compute/block.rs
Ñawpa willay
Pi imata llamkarqan
ch'uya
Fix double application of inset
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 let scrollbar_size = Size {
1002 width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1003 height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1004 };
1005
1006 tree.set_unrounded_layout(
1007 item.node_id,
1008 &Layout {
1009 order: item.order,
1010 size: item_layout.size,
1011 #[cfg(feature = "content_size")]
1012 content_size: item_layout.content_size,
1013 scrollbar_size,
1014 location,
1015 padding: item.padding,
1016 border: item.border,
1017 margin: resolved_margin,
1018 },
1019 );
1020
1021 #[cfg(feature = "content_size")]
1022 {
1023 inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
1024 location + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
1025 final_size,
1026 item_layout.content_size,
1027 item.overflow,
1028 ));
1029 }
1030
1031 // Update first_child_top_margin_set
1032 if is_collapsing_with_first_margin_set {
1033 if item.can_be_collapsed_through {
1034 first_child_top_margin_set = first_child_top_margin_set
1035 .collapse_with_set(top_margin_set)
1036 .collapse_with_set(bottom_margin_set);
1037 } else {
1038 first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
1039 is_collapsing_with_first_margin_set = false;
1040 }
1041 }
1042
1043 // Update active_collapsible_margin_set
1044 if item.can_be_collapsed_through {
1045 active_collapsible_margin_set = active_collapsible_margin_set
1046 .collapse_with_set(top_margin_set)
1047 .collapse_with_set(bottom_margin_set);
1048 y_offset_for_absolute = committed_y_offset + item_layout.size.height + y_margin_offset;
1049 #[cfg(feature = "float_layout")]
1050 {
1051 y_offset_for_float = committed_y_offset + item_layout.size.height + y_margin_offset;
1052 }
1053 } else {
1054 committed_y_offset = location.y - inset_offset.y + item_layout.size.height;
1055 active_collapsible_margin_set = bottom_margin_set;
1056 y_offset_for_absolute = committed_y_offset + active_collapsible_margin_set.resolve();
1057 #[cfg(feature = "float_layout")]
1058 {
1059 y_offset_for_float = committed_y_offset;
1060 }
1061 }
1062 }
1063 }
1064
1065 let last_child_bottom_margin_set = active_collapsible_margin_set;
1066 let bottom_y_margin_offset =
1067 if own_margins_collapse_with_children.end { 0.0 } else { last_child_bottom_margin_set.resolve() };
1068
1069 committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
1070 let content_height = f32_max(0.0, committed_y_offset);
1071 (inflow_content_size, content_height, first_child_top_margin_set, last_child_bottom_margin_set)
1072}
1073
1074/// Perform absolute layout on all absolutely positioned children.
1075#[inline]
1076fn perform_absolute_layout_on_absolute_children(
1077 tree: &mut impl LayoutBlockContainer,
1078 items: &[BlockItem],
1079 area_size: Size<f32>,
1080 area_offset: Point<f32>,
1081 direction: Direction,
1082) -> Size<f32> {
1083 let area_width = area_size.width;
1084 let area_height = area_size.height;
1085
1086 #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
1087 let mut absolute_content_size = Size::ZERO;
1088
1089 for item in items.iter().filter(|item| item.position == Position::Absolute) {
1090 let child_style = tree.get_block_child_style(item.node_id);
1091
1092 // Skip items that are display:none or are not position:absolute
1093 if child_style.box_generation_mode() == BoxGenerationMode::None || child_style.position() != Position::Absolute
1094 {
1095 continue;
1096 }
1097
1098 let aspect_ratio = child_style.aspect_ratio();
1099 let margin =
1100 child_style.margin().map(|margin| margin.resolve_to_option(area_width, |val, basis| tree.calc(val, basis)));
1101 let padding = child_style.padding().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1102 let border = child_style.border().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1103 let padding_border_sum = (padding + border).sum_axes();
1104 let box_sizing_adjustment =
1105 if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
1106
1107 // Resolve inset
1108 let left = child_style.inset().left.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1109 let right = child_style.inset().right.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1110 let top = child_style.inset().top.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1111 let bottom = child_style.inset().bottom.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1112
1113 // Compute known dimensions from min/max/inherent size styles
1114 let style_size = child_style
1115 .size()
1116 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1117 .maybe_apply_aspect_ratio(aspect_ratio)
1118 .maybe_add(box_sizing_adjustment);
1119 let min_size = child_style
1120 .min_size()
1121 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1122 .maybe_apply_aspect_ratio(aspect_ratio)
1123 .maybe_add(box_sizing_adjustment)
1124 .or(padding_border_sum.map(Some))
1125 .maybe_max(padding_border_sum);
1126 let max_size = child_style
1127 .max_size()
1128 .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1129 .maybe_apply_aspect_ratio(aspect_ratio)
1130 .maybe_add(box_sizing_adjustment);
1131 let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
1132
1133 drop(child_style);
1134
1135 // Fill in width from left/right and reapply aspect ratio if:
1136 // - Width is not already known
1137 // - Item has both left and right inset properties set
1138 if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
1139 let new_width_raw = area_width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
1140 known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
1141 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1142 }
1143
1144 // Fill in height from top/bottom and reapply aspect ratio if:
1145 // - Height is not already known
1146 // - Item has both top and bottom inset properties set
1147 if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
1148 let new_height_raw = area_height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
1149 known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
1150 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1151 }
1152
1153 let measured_size = tree.measure_child_size_both(
1154 item.node_id,
1155 known_dimensions,
1156 area_size.map(Some),
1157 Size {
1158 width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1159 height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1160 },
1161 SizingMode::ContentSize,
1162 item.direction,
1163 Line::FALSE,
1164 );
1165
1166 let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
1167
1168 let layout_output = tree.perform_child_layout(
1169 item.node_id,
1170 final_size.map(Some),
1171 area_size.map(Some),
1172 Size {
1173 width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1174 height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1175 },
1176 SizingMode::ContentSize,
1177 item.direction,
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 location = Point {
1254 x: left
1255 .map(|left| left + resolved_margin.left)
1256 .or(right.map(|right| area_size.width - final_size.width - right - resolved_margin.right))
1257 .maybe_add(area_offset.x)
1258 .unwrap_or_else(|| {
1259 if direction.is_rtl() {
1260 item.static_position.x - final_size.width - resolved_margin.right
1261 } else {
1262 item.static_position.x + resolved_margin.left
1263 }
1264 }),
1265 y: top
1266 .map(|top| top + resolved_margin.top)
1267 .or(bottom.map(|bottom| area_size.height - final_size.height - bottom - resolved_margin.bottom))
1268 .maybe_add(area_offset.y)
1269 .unwrap_or(item.static_position.y + resolved_margin.top),
1270 };
1271 // Note: axis intentionally switched here as scrollbars take up space in the opposite axis
1272 // to the axis in which scrolling is enabled.
1273 let scrollbar_size = Size {
1274 width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1275 height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1276 };
1277
1278 tree.set_unrounded_layout(
1279 item.node_id,
1280 &Layout {
1281 order: item.order,
1282 size: final_size,
1283 #[cfg(feature = "content_size")]
1284 content_size: layout_output.content_size,
1285 scrollbar_size,
1286 location,
1287 padding,
1288 border,
1289 margin: resolved_margin,
1290 },
1291 );
1292
1293 #[cfg(feature = "content_size")]
1294 {
1295 absolute_content_size = absolute_content_size.f32_max(compute_content_size_contribution(
1296 location,
1297 final_size,
1298 layout_output.content_size,
1299 item.overflow,
1300 ));
1301 }
1302 }
1303
1304 absolute_content_size
1305}