⎇ d4374b93f0ec2c0ace42d3feafec22d3af1940d8
src/compute/block.rs
Ñawpa willay
Pi imata llamkarqan
ch'uya
Refactor `LayoutTree` + add examples of custom trees (#564)
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, Display, LengthPercentageAuto, Overflow, Position};
4use crate::style_helpers::TaffyMaxContent;
5use crate::tree::{CollapsibleMarginSet, Layout, LayoutInput, LayoutOutput, RunMode, SizingMode};
6use crate::tree::{NodeId, PartialLayoutTree, PartialLayoutTreeExt};
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};
12
13/// Per-child data that is accumulated and modified over the course of the layout algorithm
14struct BlockItem {
15 /// The identifier for the associated node
16 node_id: NodeId,
17
18 /// The "source order" of the item. This is the index of the item within the children iterator,
19 /// and controls the order in which the nodes are placed
20 order: u32,
21
22 /// The base size of this item
23 size: Size<Option<f32>>,
24 /// The minimum allowable size of this item
25 min_size: Size<Option<f32>>,
26 /// The maximum allowable size of this item
27 max_size: Size<Option<f32>>,
28
29 /// The position style of the item
30 position: Position,
31 /// The final offset of this item
32 inset: Rect<LengthPercentageAuto>,
33 /// The margin of this item
34 margin: Rect<LengthPercentageAuto>,
35 /// The sum of padding and border for this item
36 padding_border_sum: Size<f32>,
37
38 /// The computed border box size of this item
39 computed_size: Size<f32>,
40 /// The computed "static position" of this item. The static position is the position
41 /// taking into account padding, border, margins, and scrollbar_gutters but not inset
42 static_position: Point<f32>,
43 /// Whether margins can be collapsed through this item
44 can_be_collapsed_through: bool,
45}
46
47/// Computes the layout of [`PartialLayoutTree`] according to the block layout algorithm
48pub fn compute_block_layout(tree: &mut impl PartialLayoutTree, node_id: NodeId, inputs: LayoutInput) -> LayoutOutput {
49 let LayoutInput { known_dimensions, parent_size, available_space, run_mode, .. } = inputs;
50 let style = tree.get_style(node_id);
51
52 // Pull these out earlier to avoid borrowing issues
53 let aspect_ratio = style.aspect_ratio;
54 let margin = style.margin.resolve_or_zero(parent_size.width);
55 let min_size = style.min_size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio);
56 let max_size = style.max_size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio);
57 let padding = style.padding.resolve_or_zero(parent_size.width);
58 let border = style.border.resolve_or_zero(parent_size.width);
59 let padding_border_size = (padding + border).sum_axes();
60 let clamped_style_size =
61 style.size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
62
63 // If both min and max in a given axis are set and max <= min then this determines the size in that axis
64 let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
65 (Some(min), Some(max)) if max <= min => Some(min),
66 _ => None,
67 });
68
69 // Block nodes automatically stretch fit their width to fit available space if available space is definite
70 let available_space_based_size =
71 Size { width: available_space.width.into_option().maybe_sub(margin.horizontal_axis_sum()), height: None };
72
73 let styled_based_known_dimensions = known_dimensions
74 .or(min_max_definite_size)
75 .or(clamped_style_size)
76 .or(available_space_based_size)
77 .maybe_max(padding_border_size);
78
79 // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
80 // is ComputeSize (and thus the container's size is all that we're interested in)
81 if run_mode == RunMode::ComputeSize {
82 if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
83 return Size { width, height }.into();
84 }
85 }
86
87 debug_log!("BLOCK");
88 compute_inner(tree, node_id, LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs })
89}
90
91/// Computes the layout of [`PartialLayoutTree`] according to the block layout algorithm
92fn compute_inner(tree: &mut impl PartialLayoutTree, node_id: NodeId, inputs: LayoutInput) -> LayoutOutput {
93 let LayoutInput {
94 known_dimensions, parent_size, available_space, run_mode, vertical_margins_are_collapsible, ..
95 } = inputs;
96
97 let style = tree.get_style(node_id);
98 let raw_padding = style.padding;
99 let raw_border = style.border;
100 let raw_margin = style.margin;
101 let aspect_ratio = style.aspect_ratio;
102 let size = style.size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio);
103 let min_size = style.min_size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio);
104 let max_size = style.max_size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio);
105 let padding = style.padding.resolve_or_zero(parent_size.width);
106 let border = style.border.resolve_or_zero(parent_size.width);
107
108 // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
109 // However, the axis are switched (transposed) because a node that scrolls vertically needs
110 // *horizontal* space to be reserved for a scrollbar
111 let scrollbar_gutter = {
112 let offsets = style.overflow.transpose().map(|overflow| match overflow {
113 Overflow::Scroll => style.scrollbar_width,
114 _ => 0.0,
115 });
116 // TODO: make side configurable based on the `direction` property
117 Rect { top: 0.0, left: 0.0, right: offsets.x, bottom: offsets.y }
118 };
119 let padding_border = padding + border;
120 let padding_border_size = padding_border.sum_axes();
121 let content_box_inset = padding_border + scrollbar_gutter;
122 let container_content_box_size = known_dimensions.maybe_sub(content_box_inset.sum_axes());
123
124 // Determine margin collapsing behaviour
125 let own_margins_collapse_with_children = Line {
126 start: vertical_margins_are_collapsible.start
127 && !style.overflow.x.is_scroll_container()
128 && !style.overflow.y.is_scroll_container()
129 && style.position == Position::Relative
130 && padding.top == 0.0
131 && border.top == 0.0,
132 end: vertical_margins_are_collapsible.end
133 && !style.overflow.x.is_scroll_container()
134 && !style.overflow.y.is_scroll_container()
135 && style.position == Position::Relative
136 && padding.bottom == 0.0
137 && border.bottom == 0.0
138 && size.height.is_none(),
139 };
140 let has_styles_preventing_being_collapsed_through = style.display != Display::Block
141 || style.overflow.x.is_scroll_container()
142 || style.overflow.y.is_scroll_container()
143 || style.position == Position::Absolute
144 || padding.top > 0.0
145 || padding.bottom > 0.0
146 || border.top > 0.0
147 || border.bottom > 0.0;
148
149 // 1. Generate items
150 let mut items = generate_item_list(tree, node_id, container_content_box_size);
151
152 // 2. Compute container width
153 let container_outer_width = known_dimensions.width.unwrap_or_else(|| {
154 let available_width = available_space.width.maybe_sub(content_box_inset.horizontal_axis_sum());
155 let intrinsic_width = determine_content_based_container_width(tree, &items, available_width)
156 + content_box_inset.horizontal_axis_sum();
157 intrinsic_width.maybe_clamp(min_size.width, max_size.width).maybe_max(Some(padding_border_size.width))
158 });
159
160 // Short-circuit if computing size and both dimensions known
161 if let (RunMode::ComputeSize, Some(container_outer_height)) = (run_mode, known_dimensions.height) {
162 return Size { width: container_outer_width, height: container_outer_height }.into();
163 }
164
165 // 3. Perform final item layout and return content height
166 let resolved_padding = raw_padding.resolve_or_zero(Some(container_outer_width));
167 let resolved_border = raw_border.resolve_or_zero(Some(container_outer_width));
168 let resolved_content_box_inset = resolved_padding + resolved_border + scrollbar_gutter;
169 let (intrinsic_outer_height, first_child_top_margin_set, last_child_bottom_margin_set) =
170 perform_final_layout_on_in_flow_children(
171 tree,
172 &mut items,
173 container_outer_width,
174 content_box_inset,
175 resolved_content_box_inset,
176 own_margins_collapse_with_children,
177 );
178 let container_outer_height = known_dimensions
179 .height
180 .unwrap_or(intrinsic_outer_height.maybe_clamp(min_size.height, max_size.height))
181 .maybe_max(Some(padding_border_size.height));
182 let final_outer_size = Size { width: container_outer_width, height: container_outer_height };
183
184 // Short-circuit if computing size
185 if run_mode == RunMode::ComputeSize {
186 return final_outer_size.into();
187 }
188
189 // 4. Layout absolutely positioned children
190 let absolute_position_inset = resolved_border + scrollbar_gutter;
191 let absolute_position_area = final_outer_size - absolute_position_inset.sum_axes();
192 let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
193 perform_absolute_layout_on_absolute_children(tree, &items, absolute_position_area, absolute_position_offset);
194
195 // 5. Perform hidden layout on hidden children
196 let len = tree.child_count(node_id);
197 for order in 0..len {
198 let child = tree.get_child_id(node_id, order);
199 if tree.get_style(child).display == Display::None {
200 *tree.get_unrounded_layout_mut(child) = Layout::with_order(order as u32);
201 tree.perform_child_layout(
202 child,
203 Size::NONE,
204 Size::NONE,
205 Size::MAX_CONTENT,
206 SizingMode::InherentSize,
207 Line::FALSE,
208 );
209 }
210 }
211
212 // 7. Determine whether this node can be collapsed through
213 let all_in_flow_children_can_be_collapsed_through =
214 items.iter().all(|item| item.position == Position::Absolute || item.can_be_collapsed_through);
215 let can_be_collapsed_through =
216 !has_styles_preventing_being_collapsed_through && all_in_flow_children_can_be_collapsed_through;
217
218 LayoutOutput {
219 size: final_outer_size,
220 first_baselines: Point::NONE,
221 top_margin: if own_margins_collapse_with_children.start {
222 first_child_top_margin_set
223 } else {
224 let margin_top = raw_margin.top.resolve_or_zero(parent_size.width);
225 CollapsibleMarginSet::from_margin(margin_top)
226 },
227 bottom_margin: if own_margins_collapse_with_children.end {
228 last_child_bottom_margin_set
229 } else {
230 let margin_bottom = raw_margin.bottom.resolve_or_zero(parent_size.width);
231 CollapsibleMarginSet::from_margin(margin_bottom)
232 },
233 margins_can_collapse_through: can_be_collapsed_through,
234 }
235}
236
237/// Create a `Vec` of `BlockItem` structs where each item in the `Vec` represents a child of the current node
238#[inline]
239fn generate_item_list(
240 tree: &impl PartialLayoutTree,
241 node: NodeId,
242 node_inner_size: Size<Option<f32>>,
243) -> Vec<BlockItem> {
244 tree.child_ids(node)
245 .map(|child_node_id| (child_node_id, tree.get_style(child_node_id)))
246 .filter(|(_, style)| style.display != Display::None)
247 .enumerate()
248 .map(|(order, (child_node_id, child_style))| {
249 let aspect_ratio = child_style.aspect_ratio;
250 let padding = child_style.padding.resolve_or_zero(node_inner_size);
251 let border = child_style.border.resolve_or_zero(node_inner_size);
252 BlockItem {
253 node_id: child_node_id,
254 order: order as u32,
255
256 size: child_style.size.maybe_resolve(node_inner_size).maybe_apply_aspect_ratio(aspect_ratio),
257 min_size: child_style.min_size.maybe_resolve(node_inner_size).maybe_apply_aspect_ratio(aspect_ratio),
258 max_size: child_style.max_size.maybe_resolve(node_inner_size).maybe_apply_aspect_ratio(aspect_ratio),
259 position: child_style.position,
260 inset: child_style.inset,
261 margin: child_style.margin,
262 padding_border_sum: (padding + border).sum_axes(),
263
264 // Fields to be computed later (for now we initialise with dummy values)
265 computed_size: Size::zero(),
266 static_position: Point::zero(),
267 can_be_collapsed_through: false,
268 }
269 })
270 .collect()
271}
272
273/// Compute the content-based width in the case that the width of the container is not known
274#[inline]
275fn determine_content_based_container_width(
276 tree: &mut impl PartialLayoutTree,
277 items: &[BlockItem],
278 available_width: AvailableSpace,
279) -> f32 {
280 let available_space = Size { width: available_width, height: AvailableSpace::MinContent };
281
282 let mut max_child_width = 0.0;
283 for item in items.iter().filter(|item| item.position != Position::Absolute) {
284 let known_dimensions = item.size.maybe_clamp(item.min_size, item.max_size);
285
286 let width = known_dimensions.width.unwrap_or_else(|| {
287 let item_x_margin_sum =
288 item.margin.resolve_or_zero(available_space.width.into_option()).horizontal_axis_sum();
289 let size_and_baselines = tree.perform_child_layout(
290 item.node_id,
291 known_dimensions,
292 Size::NONE,
293 available_space.map_width(|w| w.maybe_sub(item_x_margin_sum)),
294 SizingMode::InherentSize,
295 Line::TRUE,
296 );
297
298 size_and_baselines.size.width + item_x_margin_sum
299 });
300 let width = f32_max(width, item.padding_border_sum.width);
301
302 max_child_width = f32_max(max_child_width, width);
303 }
304
305 max_child_width
306}
307
308/// Compute each child's final size and position
309#[inline]
310fn perform_final_layout_on_in_flow_children(
311 tree: &mut impl PartialLayoutTree,
312 items: &mut [BlockItem],
313 container_outer_width: f32,
314 content_box_inset: Rect<f32>,
315 resolved_content_box_inset: Rect<f32>,
316 own_margins_collapse_with_children: Line<bool>,
317) -> (f32, CollapsibleMarginSet, CollapsibleMarginSet) {
318 // Resolve container_inner_width for sizing child nodes using intial content_box_inset
319 let container_inner_width = container_outer_width - content_box_inset.horizontal_axis_sum();
320 let parent_size = Size { width: Some(container_outer_width), height: None };
321 let available_space =
322 Size { width: AvailableSpace::Definite(container_inner_width), height: AvailableSpace::MinContent };
323
324 let mut committed_y_offset = resolved_content_box_inset.top;
325 let mut first_child_top_margin_set = CollapsibleMarginSet::ZERO;
326 let mut active_collapsible_margin_set = CollapsibleMarginSet::ZERO;
327 let mut is_collapsing_with_first_margin_set = true;
328 for item in items.iter_mut() {
329 if item.position == Position::Absolute {
330 item.static_position.y = committed_y_offset;
331 } else {
332 let item_margin = item.margin.map(|margin| margin.resolve_to_option(container_outer_width));
333 let item_non_auto_margin = item_margin.map(|m| m.unwrap_or(0.0));
334 let item_non_auto_x_margin_sum = item_non_auto_margin.horizontal_axis_sum();
335 let known_dimensions = item
336 .size
337 .map_width(|width| Some(width.unwrap_or(container_inner_width - item_non_auto_x_margin_sum)))
338 .maybe_clamp(item.min_size, item.max_size);
339
340 let item_layout = tree.perform_child_layout(
341 item.node_id,
342 known_dimensions,
343 parent_size,
344 available_space.map_width(|w| w.maybe_sub(item_non_auto_x_margin_sum)),
345 SizingMode::InherentSize,
346 Line::TRUE,
347 );
348 let final_size = item_layout.size;
349
350 let top_margin_set = item_layout.top_margin.collapse_with_margin(item_margin.top.unwrap_or(0.0));
351 let bottom_margin_set = item_layout.bottom_margin.collapse_with_margin(item_margin.bottom.unwrap_or(0.0));
352
353 // Expand auto margins to fill available space
354 // Note: Vertical auto-margins for relatively positioned block items simply resolve to 0.
355 // See: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
356 let free_x_space = f32_max(0.0, container_inner_width - final_size.width - item_non_auto_x_margin_sum);
357 let x_axis_auto_margin_size = {
358 let auto_margin_count = item_margin.left.is_none() as u8 + item_margin.right.is_none() as u8;
359 if auto_margin_count == 2 && item.size.width.is_none() {
360 0.0
361 } else if auto_margin_count > 0 {
362 free_x_space / auto_margin_count as f32
363 } else {
364 0.0
365 }
366 };
367 let resolved_margin = Rect {
368 left: item_margin.left.unwrap_or(x_axis_auto_margin_size),
369 right: item_margin.right.unwrap_or(x_axis_auto_margin_size),
370 top: top_margin_set.resolve(),
371 bottom: bottom_margin_set.resolve(),
372 };
373
374 // Resolve item inset
375 let inset =
376 item.inset.zip_size(Size { width: container_inner_width, height: 0.0 }, |p, s| p.maybe_resolve(s));
377 let inset_offset = Point {
378 x: inset.left.or(inset.right.map(|x| -x)).unwrap_or(0.0),
379 y: inset.top.or(inset.bottom.map(|x| -x)).unwrap_or(0.0),
380 };
381
382 let y_margin_offset = if is_collapsing_with_first_margin_set && own_margins_collapse_with_children.start {
383 0.0
384 } else {
385 active_collapsible_margin_set.collapse_with_margin(resolved_margin.top).resolve()
386 };
387
388 item.computed_size = item_layout.size;
389 item.can_be_collapsed_through = item_layout.margins_can_collapse_through;
390 item.static_position = Point {
391 x: resolved_content_box_inset.left,
392 y: committed_y_offset + active_collapsible_margin_set.resolve(),
393 };
394
395 *tree.get_unrounded_layout_mut(item.node_id) = Layout {
396 order: item.order,
397 size: item_layout.size,
398 location: Point {
399 x: resolved_content_box_inset.left + inset_offset.x + resolved_margin.left,
400 y: committed_y_offset + inset_offset.y + y_margin_offset,
401 },
402 };
403
404 // Update first_child_top_margin_set
405 if is_collapsing_with_first_margin_set {
406 if item.can_be_collapsed_through {
407 first_child_top_margin_set = first_child_top_margin_set
408 .collapse_with_set(top_margin_set)
409 .collapse_with_set(bottom_margin_set);
410 } else {
411 first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
412 is_collapsing_with_first_margin_set = false;
413 }
414 }
415
416 // Update active_collapsible_margin_set
417 if item.can_be_collapsed_through {
418 active_collapsible_margin_set = active_collapsible_margin_set
419 .collapse_with_set(top_margin_set)
420 .collapse_with_set(bottom_margin_set);
421 } else {
422 committed_y_offset += item_layout.size.height + y_margin_offset;
423 active_collapsible_margin_set = bottom_margin_set;
424 }
425 }
426 }
427
428 let last_child_bottom_margin_set = active_collapsible_margin_set;
429 let bottom_y_margin_offset =
430 if own_margins_collapse_with_children.end { 0.0 } else { last_child_bottom_margin_set.resolve() };
431
432 committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
433 let content_height = f32_max(0.0, committed_y_offset);
434 (content_height, first_child_top_margin_set, last_child_bottom_margin_set)
435}
436
437/// Perform absolute layout on all absolutely positioned children.
438#[inline]
439fn perform_absolute_layout_on_absolute_children(
440 tree: &mut impl PartialLayoutTree,
441 items: &[BlockItem],
442 area_size: Size<f32>,
443 area_offset: Point<f32>,
444) {
445 let area_width = area_size.width;
446 let area_height = area_size.height;
447
448 for item in items.iter().filter(|item| item.position == Position::Absolute) {
449 let child_style = tree.get_style(item.node_id);
450
451 // Skip items that are display:none or are not position:absolute
452 if child_style.display == Display::None || child_style.position != Position::Absolute {
453 continue;
454 }
455
456 let aspect_ratio = child_style.aspect_ratio;
457 let margin = child_style.margin.map(|margin| margin.resolve_to_option(area_width));
458 let padding = child_style.padding.resolve_or_zero(Some(area_width));
459 let border = child_style.border.resolve_or_zero(Some(area_width));
460 let padding_border_sum = (padding + border).sum_axes();
461
462 // Resolve inset
463 let left = child_style.inset.left.maybe_resolve(area_width);
464 let right = child_style.inset.right.maybe_resolve(area_width);
465 let top = child_style.inset.top.maybe_resolve(area_height);
466 let bottom = child_style.inset.bottom.maybe_resolve(area_height);
467
468 // Compute known dimensions from min/max/inherent size styles
469 let style_size = child_style.size.maybe_resolve(area_size).maybe_apply_aspect_ratio(aspect_ratio);
470 let min_size = child_style
471 .min_size
472 .maybe_resolve(area_size)
473 .maybe_apply_aspect_ratio(aspect_ratio)
474 .or(padding_border_sum.map(Some))
475 .maybe_max(padding_border_sum);
476 let max_size = child_style.max_size.maybe_resolve(area_size).maybe_apply_aspect_ratio(aspect_ratio);
477 let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
478
479 // Fill in width from left/right and reapply aspect ratio if:
480 // - Width is not already known
481 // - Item has both left and right inset properties set
482 if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
483 let new_width_raw = area_width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
484 known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
485 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
486 }
487
488 // Fill in height from top/bottom and reapply aspect ratio if:
489 // - Height is not already known
490 // - Item has both top and bottom inset properties set
491 if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
492 let new_height_raw = area_height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
493 known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
494 known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
495 }
496
497 let measured_size_and_baselines = tree.perform_child_layout(
498 item.node_id,
499 known_dimensions,
500 area_size.map(Some),
501 Size {
502 width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
503 height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
504 },
505 SizingMode::ContentSize,
506 Line::FALSE,
507 );
508 let measured_size = measured_size_and_baselines.size;
509 let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
510
511 let non_auto_margin = Rect {
512 left: if left.is_some() { margin.left.unwrap_or(0.0) } else { 0.0 },
513 right: if right.is_some() { margin.right.unwrap_or(0.0) } else { 0.0 },
514 top: if top.is_some() { margin.top.unwrap_or(0.0) } else { 0.0 },
515 bottom: if bottom.is_some() { margin.left.unwrap_or(0.0) } else { 0.0 },
516 };
517
518 // Expand auto margins to fill available space
519 // https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
520 let auto_margin = {
521 // Auto margins for absolutely positioned elements in block containers only resolve
522 // if inset is set. Otherwise they resolve to 0.
523 let absolute_auto_margin_space = Point {
524 x: right.map(|right| area_size.width - right - left.unwrap_or(0.0)).unwrap_or(final_size.width),
525 y: bottom.map(|bottom| area_size.height - bottom - top.unwrap_or(0.0)).unwrap_or(final_size.height),
526 };
527 let free_space = Size {
528 width: absolute_auto_margin_space.x - final_size.width - non_auto_margin.horizontal_axis_sum(),
529 height: absolute_auto_margin_space.y - final_size.height - non_auto_margin.vertical_axis_sum(),
530 };
531
532 let auto_margin_size = Size {
533 // If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0.
534 // Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the
535 // static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.
536 //
537 // If none of the three is 'auto': If both 'margin-left' and 'margin-right' are 'auto', solve the equation under the extra constraint
538 // that the two margins get equal values, unless this would make them negative, in which case when direction of the containing block is
539 // 'ltr' ('rtl'), set 'margin-left' ('margin-right') to zero and solve for 'margin-right' ('margin-left'). If one of 'margin-left' or
540 // 'margin-right' is 'auto', solve the equation for that value. If the values are over-constrained, ignore the value for 'left' (in case
541 // the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value.
542 width: {
543 let auto_margin_count = margin.left.is_none() as u8 + margin.right.is_none() as u8;
544 if auto_margin_count == 2
545 && (style_size.width.is_none() || style_size.width.unwrap() >= free_space.width)
546 {
547 0.0
548 } else if auto_margin_count > 0 {
549 free_space.width / auto_margin_count as f32
550 } else {
551 0.0
552 }
553 },
554 height: {
555 let auto_margin_count = margin.top.is_none() as u8 + margin.bottom.is_none() as u8;
556 if auto_margin_count == 2
557 && (style_size.height.is_none() || style_size.height.unwrap() >= free_space.height)
558 {
559 0.0
560 } else if auto_margin_count > 0 {
561 free_space.height / auto_margin_count as f32
562 } else {
563 0.0
564 }
565 },
566 };
567
568 Rect {
569 left: margin.left.map(|_| 0.0).unwrap_or(auto_margin_size.width),
570 right: margin.right.map(|_| 0.0).unwrap_or(auto_margin_size.width),
571 top: margin.top.map(|_| 0.0).unwrap_or(auto_margin_size.height),
572 bottom: margin.bottom.map(|_| 0.0).unwrap_or(auto_margin_size.height),
573 }
574 };
575
576 let resolved_margin = Rect {
577 left: margin.left.unwrap_or(auto_margin.left),
578 right: margin.right.unwrap_or(auto_margin.right),
579 top: margin.top.unwrap_or(auto_margin.top),
580 bottom: margin.bottom.unwrap_or(auto_margin.bottom),
581 };
582
583 let item_offset = Point {
584 x: left
585 .map(|left| left + resolved_margin.left)
586 .or(right.map(|right| area_size.width - final_size.width - right - resolved_margin.right))
587 .unwrap_or(resolved_margin.left),
588 y: top
589 .map(|top| top + resolved_margin.top)
590 .or(bottom.map(|bottom| area_size.height - final_size.height - bottom - resolved_margin.bottom))
591 .unwrap_or(item.static_position.y + resolved_margin.top),
592 };
593
594 *tree.get_unrounded_layout_mut(item.node_id) =
595 Layout { order: item.order, size: final_size, location: area_offset + item_offset };
596 }
597}