Rename Rect field start->left end->right (#257)
1//! Computes the [flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) layout algorithm on [`Taffy`](crate::Taffy) according to the [spec](https://www.w3.org/TR/css-flexbox-1/)
2//!
3//! Note that some minor steps appear to be missing: see https://github.com/DioxusLabs/taffy/issues for more information.
4use core::f32;
5
6use crate::compute::compute_node_layout;
7use crate::geometry::{Point, Rect, Size};
8use crate::layout::{AvailableSpace, Layout, RunMode, SizingMode};
9use crate::math::MaybeMath;
10use crate::node::Node;
11use crate::resolve::{MaybeResolve, ResolveOrDefault};
12use crate::style::{AlignContent, AlignSelf, Dimension, Display, FlexWrap, JustifyContent, PositionType};
13use crate::style::{FlexDirection, Style};
14use crate::sys::Vec;
15use crate::tree::LayoutTree;
16
17#[cfg(feature = "debug")]
18use crate::debug::NODE_LOGGER;
19
20/// The intermediate results of a flexbox calculation for a single item
21struct FlexItem {
22 /// The identifier for the associated [`Node`](crate::node::Node)
23 node: Node,
24
25 /// The base size of this item
26 size: Size<Option<f32>>,
27 /// The minimum allowable size of this item
28 min_size: Size<Option<f32>>,
29 /// The maximum allowable size of this item
30 max_size: Size<Option<f32>>,
31
32 /// The final offset of this item
33 position: Rect<Option<f32>>,
34 /// The margin of this item
35 margin: Rect<f32>,
36 /// The padding of this item
37 padding: Rect<f32>,
38 /// The border of this item
39 border: Rect<f32>,
40
41 /// The default size of this item
42 flex_basis: f32,
43 /// The default size of this item, minus padding and border
44 inner_flex_basis: f32,
45 /// The amount by which this item has deviated from its target size
46 violation: f32,
47 /// Is the size of this item locked
48 frozen: bool,
49
50 /// The proposed inner size of this item
51 hypothetical_inner_size: Size<f32>,
52 /// The proposed outer size of this item
53 hypothetical_outer_size: Size<f32>,
54 /// The size that this item wants to be
55 target_size: Size<f32>,
56 /// The size that this item wants to be, plus any padding and border
57 outer_target_size: Size<f32>,
58
59 /// The position of the bottom edge of this item
60 baseline: f32,
61
62 /// A temporary value for the main offset
63 ///
64 /// Offset is the relative position from the item's natural flow position based on
65 /// relative position values, alignment, and justification. Does not include margin/padding/border.
66 offset_main: f32,
67 /// A temporary value for the cross offset
68 ///
69 /// Offset is the relative position from the item's natural flow position based on
70 /// relative position values, alignment, and justification. Does not include margin/padding/border.
71 offset_cross: f32,
72}
73
74/// A line of [`FlexItem`] used for intermediate computation
75struct FlexLine<'a> {
76 /// The slice of items to iterate over during computation of this line
77 items: &'a mut [FlexItem],
78 /// The length in the main-axis that this line contributes to the overall main
79 /// main size of the container.
80 container_main_size_contribution: f32,
81 /// The dimensions of the cross-axis
82 cross_size: f32,
83 /// The relative offset of the cross-axis
84 offset_cross: f32,
85}
86
87/// Values that can be cached during the flexbox algorithm
88struct AlgoConstants {
89 /// The direction of the current segment being laid out
90 dir: FlexDirection,
91 /// Is this segment a row
92 is_row: bool,
93 /// Is this segment a column
94 is_column: bool,
95 /// Is the wrap direction inverted
96 is_wrap_reverse: bool,
97
98 /// The margin of this section
99 margin: Rect<f32>,
100 /// The border of this section
101 border: Rect<f32>,
102 /// The padding of this section
103 padding_border: Rect<f32>,
104 /// The gap of this section
105 gap: Size<f32>,
106
107 /// The size of the internal node
108 node_inner_size: Size<Option<f32>>,
109 /// The size of the surrounding container
110 container_size: Size<f32>,
111 /// The size of the internal container
112 inner_container_size: Size<f32>,
113}
114
115/// Computes the layout of [`LayoutTree`] according to the flexbox algorithm
116pub fn compute(
117 tree: &mut impl LayoutTree,
118 node: Node,
119 known_dimensions: Size<Option<f32>>,
120 available_space: Size<AvailableSpace>,
121 run_mode: RunMode,
122) -> Size<f32> {
123 let style = tree.style(node);
124 let has_min_max_sizes = style.min_size.width.is_defined()
125 || style.min_size.height.is_defined()
126 || style.max_size.width.is_defined()
127 || style.max_size.height.is_defined();
128
129 // Pull these out earlier to avoid borrowing issues
130 let min_size = style.min_size.maybe_resolve(known_dimensions);
131 let max_size = style.max_size.maybe_resolve(known_dimensions);
132 let clamped_style_size = style.size.maybe_resolve(known_dimensions).maybe_clamp(min_size, max_size);
133
134 if has_min_max_sizes {
135 #[cfg(feature = "debug")]
136 NODE_LOGGER.log("FLEX: two-pass");
137 let first_pass = compute_preliminary(
138 tree,
139 node,
140 // style.size.maybe_resolve(known_dimensions),
141 known_dimensions.zip_map(clamped_style_size, |known, style| known.or(style)),
142 available_space,
143 RunMode::ComputeSize,
144 );
145
146 let clamped_first_pass_size = first_pass.maybe_clamp(min_size, max_size);
147
148 compute_preliminary(
149 tree,
150 node,
151 known_dimensions.zip_map(clamped_first_pass_size, |known, first_pass| known.or_else(|| first_pass.into())),
152 available_space,
153 run_mode,
154 )
155 } else {
156 #[cfg(feature = "debug")]
157 NODE_LOGGER.log("FLEX: single-pass");
158 compute_preliminary(tree, node, known_dimensions.or(clamped_style_size), available_space, run_mode)
159 }
160}
161
162/// Compute a preliminary size for an item
163fn compute_preliminary(
164 tree: &mut impl LayoutTree,
165 node: Node,
166 known_dimensions: Size<Option<f32>>,
167 parent_size: Size<AvailableSpace>,
168 run_mode: RunMode,
169) -> Size<f32> {
170 // Define some general constants we will need for the remainder of the algorithm.
171 let mut constants = compute_constants(tree.style(node), known_dimensions, parent_size);
172
173 // 9. Flex Layout Algorithm
174
175 // 9.1. Initial Setup
176
177 // 1. Generate anonymous flex items as described in §4 Flex Items.
178 #[cfg(feature = "debug")]
179 NODE_LOGGER.log("generate_anonymous_flex_items");
180 let mut flex_items = generate_anonymous_flex_items(tree, node, &constants);
181
182 // 9.2. Line Length Determination
183
184 // 2. Determine the available main and cross space for the flex items
185 #[cfg(feature = "debug")]
186 NODE_LOGGER.log("determine_available_space");
187 let available_space = determine_available_space(known_dimensions, parent_size, &constants);
188
189 let has_baseline_child =
190 flex_items.iter().any(|child| tree.style(child.node).align_self(tree.style(node)) == AlignSelf::Baseline);
191
192 // 3. Determine the flex base size and hypothetical main size of each item.
193 #[cfg(feature = "debug")]
194 NODE_LOGGER.log("determine_flex_base_size");
195 determine_flex_base_size(tree, node, known_dimensions, &constants, available_space, &mut flex_items);
196
197 // TODO: Add step 4 according to spec: https://www.w3.org/TR/css-flexbox-1/#algo-main-container
198 // 9.3. Main Size Determination
199
200 // 5. Collect flex items into flex lines.
201 #[cfg(feature = "debug")]
202 NODE_LOGGER.log("collect_flex_lines");
203 let mut flex_lines = collect_flex_lines(tree, node, &constants, available_space, &mut flex_items);
204
205 // If container size is undefined, re-resolve gap based on resolved base sizes
206 let original_gap = constants.gap;
207 if constants.node_inner_size.main(constants.dir).is_none() {
208 let longest_line_length = flex_lines.iter().fold(f32::MIN, |acc, line| {
209 let length: f32 = line.items.iter().map(|item| item.hypothetical_outer_size.main(constants.dir)).sum();
210 acc.max(length)
211 });
212
213 let style = tree.style(node);
214 let new_gap = style.gap.width.maybe_resolve(longest_line_length).unwrap_or(0.0);
215 constants.gap.set_main(constants.dir, new_gap);
216 }
217
218 // 6. Resolve the flexible lengths of all the flex items to find their used main size.
219 #[cfg(feature = "debug")]
220 NODE_LOGGER.log("resolve_flexible_lengths");
221 for line in &mut flex_lines {
222 resolve_flexible_lengths(tree, line, &constants, original_gap, available_space);
223 }
224
225 // TODO: Cleanup and make according to spec
226 // Not part of the spec from what i can see but seems correct
227 constants.container_size.set_main(
228 constants.dir,
229 known_dimensions.main(constants.dir).unwrap_or({
230 let longest_line =
231 flex_lines.iter().fold(f32::MIN, |acc, line| acc.max(line.container_main_size_contribution));
232 let size = longest_line + constants.padding_border.main_axis_sum(constants.dir);
233 match available_space.main(constants.dir) {
234 AvailableSpace::Definite(val) if flex_lines.len() > 1 && size < val => val,
235 _ => size,
236 }
237 }),
238 );
239
240 constants.inner_container_size.set_main(
241 constants.dir,
242 constants.container_size.main(constants.dir) - constants.padding_border.main_axis_sum(constants.dir),
243 );
244
245 // 9.4. Cross Size Determination
246
247 // 7. Determine the hypothetical cross size of each item.
248 #[cfg(feature = "debug")]
249 NODE_LOGGER.log("determine_hypothetical_cross_size");
250 for line in &mut flex_lines {
251 determine_hypothetical_cross_size(tree, line, &constants, available_space);
252 }
253
254 // TODO - probably should move this somewhere else as it doesn't make a ton of sense here but we need it below
255 // TODO - This is expensive and should only be done if we really require a baseline. aka, make it lazy
256 if has_baseline_child {
257 #[cfg(feature = "debug")]
258 NODE_LOGGER.log("calculate_children_base_lines");
259 calculate_children_base_lines(tree, node, known_dimensions, available_space, &mut flex_lines, &constants);
260 }
261
262 // 8. Calculate the cross size of each flex line.
263 #[cfg(feature = "debug")]
264 NODE_LOGGER.log("calculate_cross_size");
265 calculate_cross_size(tree, &mut flex_lines, node, known_dimensions, &constants);
266
267 // 9. Handle 'align-content: stretch'.
268 #[cfg(feature = "debug")]
269 NODE_LOGGER.log("handle_align_content_stretch");
270 handle_align_content_stretch(tree, &mut flex_lines, node, known_dimensions, &constants);
271
272 // 10. Collapse visibility:collapse items. If any flex items have visibility: collapse,
273 // note the cross size of the line they’re in as the item’s strut size, and restart
274 // layout from the beginning.
275 //
276 // In this second layout round, when collecting items into lines, treat the collapsed
277 // items as having zero main size. For the rest of the algorithm following that step,
278 // ignore the collapsed items entirely (as if they were display:none) except that after
279 // calculating the cross size of the lines, if any line’s cross size is less than the
280 // largest strut size among all the collapsed items in the line, set its cross size to
281 // that strut size.
282 //
283 // Skip this step in the second layout round.
284
285 // TODO implement once (if ever) we support visibility:collapse
286
287 // 11. Determine the used cross size of each flex item.
288 #[cfg(feature = "debug")]
289 NODE_LOGGER.log("determine_used_cross_size");
290 determine_used_cross_size(tree, &mut flex_lines, node, &constants);
291
292 // 9.5. Main-Axis Alignment
293
294 // 12. Distribute any remaining free space.
295 #[cfg(feature = "debug")]
296 NODE_LOGGER.log("distribute_remaining_free_space");
297 distribute_remaining_free_space(tree, &mut flex_lines, node, &constants);
298
299 // 9.6. Cross-Axis Alignment
300
301 // 13. Resolve cross-axis auto margins (also includes 14).
302 #[cfg(feature = "debug")]
303 NODE_LOGGER.log("resolve_cross_axis_auto_margins");
304 resolve_cross_axis_auto_margins(tree, &mut flex_lines, node, &constants);
305
306 // 15. Determine the flex container’s used cross size.
307 #[cfg(feature = "debug")]
308 NODE_LOGGER.log("determine_container_cross_size");
309 let total_line_cross_size = determine_container_cross_size(&mut flex_lines, known_dimensions, &mut constants);
310
311 // We have the container size.
312 // If our caller does not care about performing layout we are done now.
313 if run_mode == RunMode::ComputeSize {
314 let container_size = constants.container_size;
315 return container_size;
316 }
317
318 // 16. Align all flex lines per align-content.
319 #[cfg(feature = "debug")]
320 NODE_LOGGER.log("align_flex_lines_per_align_content");
321 align_flex_lines_per_align_content(tree, &mut flex_lines, node, &constants, total_line_cross_size);
322
323 // Do a final layout pass and gather the resulting layouts
324 #[cfg(feature = "debug")]
325 NODE_LOGGER.log("final_layout_pass");
326 final_layout_pass(tree, node, &mut flex_lines, &constants);
327
328 // Before returning we perform absolute layout on all absolutely positioned children
329 #[cfg(feature = "debug")]
330 NODE_LOGGER.log("perform_absolute_layout_on_absolute_children");
331 perform_absolute_layout_on_absolute_children(tree, node, &constants);
332
333 #[cfg(feature = "debug")]
334 NODE_LOGGER.log("hidden_layout");
335 let len = tree.children(node).len();
336 for order in 0..len {
337 let child = tree.child(node, order);
338 if tree.style(child).display == Display::None {
339 // if self.nodes[*child].style.display == Display::None {
340 hidden_layout(tree, child, order as _);
341 }
342 }
343
344 constants.container_size
345}
346
347/// Compute constants that can be reused during the flexbox algorithm.
348#[inline]
349fn compute_constants(style: &Style, node_size: Size<Option<f32>>, parent_size: Size<AvailableSpace>) -> AlgoConstants {
350 let dir = style.flex_direction;
351 let is_row = dir.is_row();
352 let is_column = dir.is_column();
353 let is_wrap_reverse = style.flex_wrap == FlexWrap::WrapReverse;
354
355 let margin = style.margin.resolve_or_default(parent_size.width.into_option());
356 let padding = style.padding.resolve_or_default(parent_size.width.into_option());
357 let border = style.border.resolve_or_default(parent_size.width.into_option());
358
359 let padding_border = Rect {
360 left: padding.left + border.left,
361 right: padding.right + border.right,
362 top: padding.top + border.top,
363 bottom: padding.bottom + border.bottom,
364 };
365
366 let node_inner_size = Size {
367 width: node_size.width.maybe_sub(padding_border.horizontal_axis_sum()),
368 height: node_size.height.maybe_sub(padding_border.vertical_axis_sum()),
369 };
370 let gap = style.gap.resolve_or_default(node_inner_size.or(Size { width: Some(0.0), height: Some(0.0) }));
371
372 let container_size = Size::ZERO;
373 let inner_container_size = Size::ZERO;
374
375 AlgoConstants {
376 dir,
377 is_row,
378 is_column,
379 is_wrap_reverse,
380 margin,
381 border,
382 gap,
383 padding_border,
384 node_inner_size,
385 container_size,
386 inner_container_size,
387 }
388}
389
390/// Generate anonymous flex items.
391///
392/// # [9.1. Initial Setup](https://www.w3.org/TR/css-flexbox-1/#box-manip)
393///
394/// - [**Generate anonymous flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-anon-box) as described in [§4 Flex Items](https://www.w3.org/TR/css-flexbox-1/#flex-items).
395#[inline]
396fn generate_anonymous_flex_items(tree: &impl LayoutTree, node: Node, constants: &AlgoConstants) -> Vec<FlexItem> {
397 tree.children(node)
398 .iter()
399 .map(|child| (child, tree.style(*child)))
400 .filter(|(_, style)| style.position_type != PositionType::Absolute)
401 .filter(|(_, style)| style.display != Display::None)
402 .map(|(child, child_style)| FlexItem {
403 node: *child,
404 size: child_style.size.maybe_resolve(constants.node_inner_size),
405 min_size: child_style.min_size.maybe_resolve(constants.node_inner_size),
406 max_size: child_style.max_size.maybe_resolve(constants.node_inner_size),
407
408 position: child_style.position.zip_size(constants.node_inner_size, |p, s| p.maybe_resolve(s)),
409 margin: child_style.margin.resolve_or_default(constants.node_inner_size.width),
410 padding: child_style.padding.resolve_or_default(constants.node_inner_size.width),
411 border: child_style.border.resolve_or_default(constants.node_inner_size.width),
412 flex_basis: 0.0,
413 inner_flex_basis: 0.0,
414 violation: 0.0,
415 frozen: false,
416
417 hypothetical_inner_size: Size::ZERO,
418 hypothetical_outer_size: Size::ZERO,
419 target_size: Size::ZERO,
420 outer_target_size: Size::ZERO,
421
422 baseline: 0.0,
423
424 offset_main: 0.0,
425 offset_cross: 0.0,
426 })
427 .collect()
428}
429
430/// Determine the available main and cross space for the flex items.
431///
432/// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
433///
434/// - [**Determine the available main and cross space for the flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-available).
435/// For each dimension, if that dimension of the flex container’s content box is a definite size, use that;
436/// if that dimension of the flex container is being sized under a min or max-content constraint, the available space in that dimension is that constraint;
437/// otherwise, subtract the flex container’s margin, border, and padding from the space available to the flex container in that dimension and use that value.
438/// **This might result in an infinite value**.
439#[inline]
440#[must_use]
441fn determine_available_space(
442 known_dimensions: Size<Option<f32>>,
443 outer_available_space: Size<AvailableSpace>,
444 constants: &AlgoConstants,
445) -> Size<AvailableSpace> {
446 let width = match known_dimensions.width {
447 Some(node_width) => AvailableSpace::Definite(node_width),
448 None => outer_available_space
449 .width
450 .maybe_sub(constants.margin.horizontal_axis_sum())
451 .maybe_sub(constants.padding_border.horizontal_axis_sum()),
452 };
453
454 let height = match known_dimensions.height {
455 Some(node_height) => AvailableSpace::Definite(node_height),
456 None => outer_available_space
457 .height
458 .maybe_sub(constants.margin.vertical_axis_sum())
459 .maybe_sub(constants.padding_border.vertical_axis_sum()),
460 };
461
462 Size { width, height }
463}
464
465/// Determine the flex base size and hypothetical main size of each item.
466///
467/// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
468///
469/// - [**Determine the flex base size and hypothetical main size of each item:**](https://www.w3.org/TR/css-flexbox-1/#algo-main-item)
470///
471/// - A. If the item has a definite used flex basis, that’s the flex base size.
472///
473/// - B. If the flex item has ...
474///
475/// - an intrinsic aspect ratio,
476/// - a used flex basis of content, and
477/// - a definite cross size,
478///
479/// then the flex base size is calculated from its inner cross size and the flex item’s intrinsic aspect ratio.
480///
481/// - C. If the used flex basis is content or depends on its available space, and the flex container is being sized under a min-content
482/// or max-content constraint (e.g. when performing automatic table layout \[CSS21\]), size the item under that constraint.
483/// The flex base size is the item’s resulting main size.
484///
485/// - E. Otherwise, size the item into the available space using its used flex basis in place of its main size, treating a value of content as max-content.
486/// If a cross size is needed to determine the main size (e.g. when the flex item’s main size is in its block axis) and the flex item’s cross size is auto and not definite,
487/// in this calculation use fit-content as the flex item’s cross size. The flex base size is the item’s resulting main size.
488///
489/// When determining the flex base size, the item’s min and max main sizes are ignored (no clamping occurs).
490/// Furthermore, the sizing calculations that floor the content box size at zero when applying box-sizing are also ignored.
491/// (For example, an item with a specified size of zero, positive padding, and box-sizing: border-box will have an outer flex base size of zero—and hence a negative inner flex base size.)
492#[inline]
493fn determine_flex_base_size(
494 tree: &mut impl LayoutTree,
495 node: Node,
496 node_size: Size<Option<f32>>,
497 constants: &AlgoConstants,
498 available_space: Size<AvailableSpace>,
499 flex_items: &mut Vec<FlexItem>,
500) {
501 // TODO - this does not follow spec. See the TODOs below
502 for child in flex_items.iter_mut() {
503 let child_style = tree.style(child.node);
504
505 // A. If the item has a definite used flex basis, that’s the flex base size.
506
507 let flex_basis = child_style.flex_basis.maybe_resolve(constants.node_inner_size.main(constants.dir));
508 if flex_basis.is_some() {
509 child.flex_basis = flex_basis.unwrap_or(0.0);
510 continue;
511 };
512
513 // B. If the flex item has an intrinsic aspect ratio,
514 // a used flex basis of content, and a definite cross size,
515 // then the flex base size is calculated from its inner
516 // cross size and the flex item’s intrinsic aspect ratio.
517
518 if let Some(ratio) = child_style.aspect_ratio {
519 if let Some(cross) = node_size.cross(constants.dir) {
520 if child_style.flex_basis == Dimension::Auto {
521 child.flex_basis = cross * ratio;
522 continue;
523 }
524 }
525 }
526
527 // C. If the used flex basis is content or depends on its available space,
528 // and the flex container is being sized under a min-content or max-content
529 // constraint (e.g. when performing automatic table layout [CSS21]),
530 // size the item under that constraint. The flex base size is the item’s
531 // resulting main size.
532
533 // TODO - Probably need to cover this case in future
534
535 // D. Otherwise, if the used flex basis is content or depends on its
536 // available space, the available main size is infinite, and the flex item’s
537 // inline axis is parallel to the main axis, lay the item out using the rules
538 // for a box in an orthogonal flow [CSS3-WRITING-MODES]. The flex base size
539 // is the item’s max-content main size.
540
541 // TODO - Probably need to cover this case in future
542
543 // E. Otherwise, size the item into the available space using its used flex basis
544 // in place of its main size, treating a value of content as max-content.
545 // If a cross size is needed to determine the main size (e.g. when the
546 // flex item’s main size is in its block axis) and the flex item’s cross size
547 // is auto and not definite, in this calculation use fit-content as the
548 // flex item’s cross size. The flex base size is the item’s resulting main size.
549
550 let child_known_dimensions = {
551 let mut ckd = child.size;
552 if child_style.align_self(tree.style(node)) == AlignSelf::Stretch {
553 if constants.is_column && ckd.width.is_none() {
554 ckd.width = available_space.width.into_option();
555 }
556 if constants.is_row && ckd.height.is_none() {
557 ckd.height = available_space.height.into_option();
558 }
559 }
560 ckd
561 };
562
563 child.flex_basis = compute_node_layout(
564 tree,
565 child.node,
566 child_known_dimensions.maybe_min(child.max_size),
567 available_space,
568 RunMode::ComputeSize,
569 SizingMode::ContentSize,
570 )
571 .main(constants.dir)
572 .maybe_min(child.max_size.main(constants.dir));
573 }
574
575 // The hypothetical main size is the item’s flex base size clamped according to its
576 // used min and max main sizes (and flooring the content box size at zero).
577
578 for child in flex_items {
579 child.inner_flex_basis =
580 child.flex_basis - child.padding.main_axis_sum(constants.dir) - child.border.main_axis_sum(constants.dir);
581
582 // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
583 // The following logic was developed not from the spec but by trail and error looking into how
584 // webkit handled various scenarios. Can probably be solved better by passing in
585 // min-content max-content constraints from the top
586 let min_main = compute_node_layout(
587 tree,
588 child.node,
589 Size::NONE,
590 available_space,
591 RunMode::ComputeSize,
592 SizingMode::ContentSize,
593 )
594 .main(constants.dir)
595 .maybe_clamp(child.min_size.main(constants.dir), child.size.main(constants.dir))
596 .into();
597
598 child
599 .hypothetical_inner_size
600 .set_main(constants.dir, child.flex_basis.maybe_clamp(min_main, child.max_size.main(constants.dir)));
601
602 child.hypothetical_outer_size.set_main(
603 constants.dir,
604 child.hypothetical_inner_size.main(constants.dir) + child.margin.main_axis_sum(constants.dir),
605 );
606 }
607}
608
609/// Collect flex items into flex lines.
610///
611/// # [9.3. Main Size Determination](https://www.w3.org/TR/css-flexbox-1/#main-sizing)
612///
613/// - [**Collect flex items into flex lines**](https://www.w3.org/TR/css-flexbox-1/#algo-line-break):
614///
615/// - If the flex container is single-line, collect all the flex items into a single flex line.
616///
617/// - Otherwise, starting from the first uncollected item, collect consecutive items one by one until the first time that the next collected item would not fit into the flex container’s inner main size
618/// (or until a forced break is encountered, see [§10 Fragmenting Flex Layout](https://www.w3.org/TR/css-flexbox-1/#pagination)).
619/// If the very first uncollected item wouldn't fit, collect just it into the line.
620///
621/// For this step, the size of a flex item is its outer hypothetical main size. (**Note: This can be negative**.)
622///
623/// Repeat until all flex items have been collected into flex lines.
624///
625/// **Note that the "collect as many" line will collect zero-sized flex items onto the end of the previous line even if the last non-zero item exactly "filled up" the line**.
626#[inline]
627fn collect_flex_lines<'a>(
628 tree: &impl LayoutTree,
629 node: Node,
630 constants: &AlgoConstants,
631 available_space: Size<AvailableSpace>,
632 flex_items: &'a mut Vec<FlexItem>,
633) -> Vec<FlexLine<'a>> {
634 let mut lines = crate::sys::new_vec_with_capacity(1);
635
636 if tree.style(node).flex_wrap == FlexWrap::NoWrap {
637 lines.push(FlexLine {
638 items: flex_items.as_mut_slice(),
639 container_main_size_contribution: 0.0,
640 cross_size: 0.0,
641 offset_cross: 0.0,
642 });
643 } else {
644 let mut flex_items = &mut flex_items[..];
645 let main_axis_gap = constants.gap.main(constants.dir);
646
647 while !flex_items.is_empty() {
648 let mut line_length = 0.0;
649 let index = flex_items
650 .iter()
651 .enumerate()
652 .find(|&(idx, child)| {
653 // Gaps only occur between items (not before the first one or after the last one)
654 // So first item in the line does not contribute a gap to the line length
655 let gap_contribution = if idx == 0 { 0.0 } else { main_axis_gap };
656 line_length += child.hypothetical_outer_size.main(constants.dir) + gap_contribution;
657 if let AvailableSpace::Definite(main) = available_space.main(constants.dir) {
658 line_length > main && idx != 0
659 } else {
660 false
661 }
662 })
663 .map(|(idx, _)| idx)
664 .unwrap_or(flex_items.len());
665
666 let (items, rest) = flex_items.split_at_mut(index);
667 lines.push(FlexLine { items, container_main_size_contribution: 0.0, cross_size: 0.0, offset_cross: 0.0 });
668 flex_items = rest;
669 }
670 }
671
672 lines
673}
674
675/// Resolve the flexible lengths of the items within a flex line.
676///
677/// # [9.7. Resolving Flexible Lengths](https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-lengths)
678#[inline]
679fn resolve_flexible_lengths(
680 tree: &mut impl LayoutTree,
681 line: &mut FlexLine,
682 constants: &AlgoConstants,
683 original_gap: Size<f32>,
684 available_space: Size<AvailableSpace>,
685) {
686 let total_original_main_axis_gap = sum_axis_gaps(original_gap.main(constants.dir), line.items.len());
687 let total_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
688
689 // 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
690 // items on the line. If the sum is less than the flex container’s inner main size,
691 // use the flex grow factor for the rest of this algorithm; otherwise, use the
692 // flex shrink factor.
693
694 let total_hypothetical_outer_main_size =
695 line.items.iter().map(|child| child.hypothetical_outer_size.main(constants.dir)).sum::<f32>();
696 let used_flex_factor: f32 = total_original_main_axis_gap + total_hypothetical_outer_main_size;
697 let growing = used_flex_factor < constants.node_inner_size.main(constants.dir).unwrap_or(0.0);
698 let shrinking = !growing;
699
700 // 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
701 // - Any item that has a flex factor of zero
702 // - If using the flex grow factor: any item that has a flex base size
703 // greater than its hypothetical main size
704 // - If using the flex shrink factor: any item that has a flex base size
705 // smaller than its hypothetical main size
706
707 for child in line.items.iter_mut() {
708 // TODO - This is not found by reading the spec. Maybe this can be done in some other place
709 // instead. This was found by trail and error fixing tests to align with webkit output.
710 if constants.node_inner_size.main(constants.dir).is_none() && constants.is_row {
711 child.target_size.set_main(
712 constants.dir,
713 compute_node_layout(
714 tree,
715 child.node,
716 child.size.maybe_clamp(child.min_size, child.max_size),
717 available_space,
718 RunMode::ComputeSize,
719 SizingMode::ContentSize,
720 )
721 .main(constants.dir)
722 .maybe_clamp(child.min_size.main(constants.dir), child.max_size.main(constants.dir)),
723 );
724 } else {
725 child.target_size.set_main(constants.dir, child.hypothetical_inner_size.main(constants.dir));
726 }
727
728 // TODO this should really only be set inside the if-statement below but
729 // that causes the target_main_size to never be set for some items
730
731 child
732 .outer_target_size
733 .set_main(constants.dir, child.target_size.main(constants.dir) + child.margin.main_axis_sum(constants.dir));
734
735 let child_style = tree.style(child.node);
736 if (child_style.flex_grow == 0.0 && child_style.flex_shrink == 0.0)
737 || (growing && child.flex_basis > child.hypothetical_inner_size.main(constants.dir))
738 || (shrinking && child.flex_basis < child.hypothetical_inner_size.main(constants.dir))
739 {
740 child.frozen = true;
741 }
742 }
743
744 let total_target_size = line.items.iter().map(|child| child.outer_target_size.main(constants.dir)).sum::<f32>();
745 line.container_main_size_contribution = total_target_size + total_original_main_axis_gap;
746
747 // 3. Calculate initial free space. Sum the outer sizes of all items on the line,
748 // and subtract this from the flex container’s inner main size. For frozen items,
749 // use their outer target main size; for other items, use their outer flex base size.
750
751 let used_space: f32 = total_main_axis_gap
752 + line
753 .items
754 .iter()
755 .map(|child| {
756 child.margin.main_axis_sum(constants.dir)
757 + if child.frozen { child.target_size.main(constants.dir) } else { child.flex_basis }
758 })
759 .sum::<f32>();
760
761 let initial_free_space = constants.node_inner_size.main(constants.dir).maybe_sub(used_space).unwrap_or(0.0);
762
763 // 4. Loop
764
765 loop {
766 // a. Check for flexible items. If all the flex items on the line are frozen,
767 // free space has been distributed; exit this loop.
768
769 if line.items.iter().all(|child| child.frozen) {
770 break;
771 }
772
773 // b. Calculate the remaining free space as for initial free space, above.
774 // If the sum of the unfrozen flex items’ flex factors is less than one,
775 // multiply the initial free space by this sum. If the magnitude of this
776 // value is less than the magnitude of the remaining free space, use this
777 // as the remaining free space.
778
779 let used_space: f32 = total_main_axis_gap
780 + line
781 .items
782 .iter()
783 .map(|child| {
784 child.margin.main_axis_sum(constants.dir)
785 + if child.frozen { child.target_size.main(constants.dir) } else { child.flex_basis }
786 })
787 .sum::<f32>();
788
789 let mut unfrozen: Vec<&mut FlexItem> = line.items.iter_mut().filter(|child| !child.frozen).collect();
790
791 let (sum_flex_grow, sum_flex_shrink): (f32, f32) =
792 unfrozen.iter().fold((0.0, 0.0), |(flex_grow, flex_shrink), item| {
793 let style = tree.style(item.node);
794 (flex_grow + style.flex_grow, flex_shrink + style.flex_shrink)
795 });
796
797 let free_space = if growing && sum_flex_grow < 1.0 {
798 (initial_free_space * sum_flex_grow - total_main_axis_gap)
799 .maybe_min(constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
800 } else if shrinking && sum_flex_shrink < 1.0 {
801 (initial_free_space * sum_flex_shrink - total_main_axis_gap)
802 .maybe_max(constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
803 } else {
804 (constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
805 .unwrap_or(used_flex_factor - used_space)
806 };
807
808 // c. Distribute free space proportional to the flex factors.
809 // - If the remaining free space is zero
810 // Do Nothing
811 // - If using the flex grow factor
812 // Find the ratio of the item’s flex grow factor to the sum of the
813 // flex grow factors of all unfrozen items on the line. Set the item’s
814 // target main size to its flex base size plus a fraction of the remaining
815 // free space proportional to the ratio.
816 // - If using the flex shrink factor
817 // For every unfrozen item on the line, multiply its flex shrink factor by
818 // its inner flex base size, and note this as its scaled flex shrink factor.
819 // Find the ratio of the item’s scaled flex shrink factor to the sum of the
820 // scaled flex shrink factors of all unfrozen items on the line. Set the item’s
821 // target main size to its flex base size minus a fraction of the absolute value
822 // of the remaining free space proportional to the ratio. Note this may result
823 // in a negative inner main size; it will be corrected in the next step.
824 // - Otherwise
825 // Do Nothing
826
827 if free_space.is_normal() {
828 if growing && sum_flex_grow > 0.0 {
829 for child in &mut unfrozen {
830 child.target_size.set_main(
831 constants.dir,
832 child.flex_basis + free_space * (tree.style(child.node).flex_grow / sum_flex_grow),
833 );
834 }
835 } else if shrinking && sum_flex_shrink > 0.0 {
836 let sum_scaled_shrink_factor: f32 =
837 unfrozen.iter().map(|child| child.inner_flex_basis * tree.style(child.node).flex_shrink).sum();
838
839 if sum_scaled_shrink_factor > 0.0 {
840 for child in &mut unfrozen {
841 let scaled_shrink_factor = child.inner_flex_basis * tree.style(child.node).flex_shrink;
842 child.target_size.set_main(
843 constants.dir,
844 child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor),
845 )
846 }
847 }
848 }
849 }
850
851 // d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
852 // used min and max main sizes and floor its content-box size at zero. If the
853 // item’s target main size was made smaller by this, it’s a max violation.
854 // If the item’s target main size was made larger by this, it’s a min violation.
855
856 let total_violation = unfrozen.iter_mut().fold(0.0, |acc, child| -> f32 {
857 // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
858 // The following logic was developed not from the spec but by trial and error looking into how
859 // webkit handled various scenarios. Can probably be solved better by passing in
860 // min-content max-content constraints from the top. Need to figure out correct thing to do here as
861 // just piling on more conditionals.
862 let min_main = if constants.is_row && !tree.needs_measure(child.node) {
863 compute_node_layout(
864 tree,
865 child.node,
866 Size::NONE,
867 available_space,
868 RunMode::ComputeSize,
869 SizingMode::ContentSize,
870 )
871 .width
872 .maybe_clamp(child.min_size.width, child.size.width)
873 .into()
874 } else {
875 child.min_size.main(constants.dir)
876 };
877
878 let max_main = child.max_size.main(constants.dir);
879 let clamped = child.target_size.main(constants.dir).maybe_clamp(min_main, max_main).max(0.0);
880 child.violation = clamped - child.target_size.main(constants.dir);
881 child.target_size.set_main(constants.dir, clamped);
882 child.outer_target_size.set_main(
883 constants.dir,
884 child.target_size.main(constants.dir) + child.margin.main_axis_sum(constants.dir),
885 );
886
887 acc + child.violation
888 });
889
890 // e. Freeze over-flexed items. The total violation is the sum of the adjustments
891 // from the previous step ∑(clamped size - unclamped size). If the total violation is:
892 // - Zero
893 // Freeze all items.
894 // - Positive
895 // Freeze all the items with min violations.
896 // - Negative
897 // Freeze all the items with max violations.
898
899 for child in &mut unfrozen {
900 match total_violation {
901 v if v > 0.0 => child.frozen = child.violation > 0.0,
902 v if v < 0.0 => child.frozen = child.violation < 0.0,
903 _ => child.frozen = true,
904 }
905 }
906
907 // f. Return to the start of this loop.
908 }
909}
910
911/// Determine the hypothetical cross size of each item.
912///
913/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
914///
915/// - [**Determine the hypothetical cross size of each item**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-item)
916/// by performing layout with the used main size and the available space, treating auto as fit-content.
917#[inline]
918fn determine_hypothetical_cross_size(
919 tree: &mut impl LayoutTree,
920 line: &mut FlexLine,
921 constants: &AlgoConstants,
922 available_space: Size<AvailableSpace>,
923) {
924 for child in line.items.iter_mut() {
925 let child_cross = child
926 .size
927 .cross(constants.dir)
928 .maybe_clamp(child.min_size.cross(constants.dir), child.max_size.cross(constants.dir));
929
930 child.hypothetical_inner_size.set_cross(
931 constants.dir,
932 compute_node_layout(
933 tree,
934 child.node,
935 Size {
936 width: if constants.is_row { child.target_size.width.into() } else { child_cross },
937 height: if constants.is_row { child_cross } else { child.target_size.height.into() },
938 },
939 Size {
940 width: if constants.is_row {
941 constants.container_size.main(constants.dir).into()
942 } else {
943 available_space.width
944 },
945 height: if constants.is_row {
946 available_space.height
947 } else {
948 constants.container_size.main(constants.dir).into()
949 },
950 },
951 RunMode::ComputeSize,
952 SizingMode::ContentSize,
953 )
954 .cross(constants.dir)
955 .maybe_clamp(child.min_size.cross(constants.dir), child.max_size.cross(constants.dir)),
956 );
957
958 child.hypothetical_outer_size.set_cross(
959 constants.dir,
960 child.hypothetical_inner_size.cross(constants.dir) + child.margin.cross_axis_sum(constants.dir),
961 );
962 }
963}
964
965/// Calculate the base lines of the children.
966#[inline]
967fn calculate_children_base_lines(
968 tree: &mut impl LayoutTree,
969 node: Node,
970 node_size: Size<Option<f32>>,
971 available_space: Size<AvailableSpace>,
972 flex_lines: &mut [FlexLine],
973 constants: &AlgoConstants,
974) {
975 /// Recursively calculates the baseline for children
976 fn calc_baseline(db: &impl LayoutTree, node: Node, layout: &Layout) -> f32 {
977 let children = db.children(node);
978 if children.is_empty() {
979 layout.size.height
980 } else {
981 let child = children[0];
982 let layout = db.layout(child);
983 calc_baseline(db, child, layout)
984 }
985 // if db.children[node].is_empty() {
986 // layout.size.height
987 // } else {
988 // let child = db.children[node][0];
989 // calc_baseline(db, child, &db.nodes[child].layout)
990 // }
991 }
992
993 for line in flex_lines {
994 for child in line.items.iter_mut() {
995 let preliminary_size = compute_node_layout(
996 tree,
997 child.node,
998 Size {
999 width: if constants.is_row {
1000 child.target_size.width.into()
1001 } else {
1002 child.hypothetical_inner_size.width.into()
1003 },
1004 height: if constants.is_row {
1005 child.hypothetical_inner_size.height.into()
1006 } else {
1007 child.target_size.height.into()
1008 },
1009 },
1010 Size {
1011 width: if constants.is_row {
1012 constants.container_size.width.into()
1013 } else {
1014 available_space.width.maybe_set(node_size.width)
1015 },
1016 height: if constants.is_row {
1017 available_space.height.maybe_set(node_size.height)
1018 } else {
1019 constants.container_size.height.into()
1020 },
1021 },
1022 RunMode::PeformLayout,
1023 SizingMode::ContentSize,
1024 );
1025
1026 child.baseline = calc_baseline(
1027 tree,
1028 child.node,
1029 &Layout {
1030 order: tree.children(node).iter().position(|n| *n == child.node).unwrap() as u32,
1031 size: preliminary_size,
1032 location: Point::ZERO,
1033 },
1034 );
1035 }
1036 }
1037}
1038
1039/// Calculate the cross size of each flex line.
1040///
1041/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
1042///
1043/// - [**Calculate the cross size of each flex line**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-line).
1044///
1045/// If the flex container is single-line and has a definite cross size, the cross size of the flex line is the flex container’s inner cross size.
1046///
1047/// Otherwise, for each flex line:
1048///
1049/// 1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose align-self is baseline, and whose cross-axis margins are both non-auto.
1050/// Find the largest of the distances between each item’s baseline and its hypothetical outer cross-start edge,
1051/// and the largest of the distances between each item’s baseline and its hypothetical outer cross-end edge, and sum these two values.
1052///
1053/// 2. Among all the items not collected by the previous step, find the largest outer hypothetical cross size.
1054///
1055/// 3. The used cross-size of the flex line is the largest of the numbers found in the previous two steps and zero.
1056///
1057/// If the flex container is single-line, then clamp the line’s cross-size to be within the container’s computed min and max cross sizes.
1058/// **Note that if CSS 2.1’s definition of min/max-width/height applied more generally, this behavior would fall out automatically**.
1059#[inline]
1060fn calculate_cross_size(
1061 tree: &mut impl LayoutTree,
1062 flex_lines: &mut [FlexLine],
1063 node: Node,
1064 node_size: Size<Option<f32>>,
1065 constants: &AlgoConstants,
1066) {
1067 if flex_lines.len() == 1 && node_size.cross(constants.dir).is_some() {
1068 flex_lines[0].cross_size =
1069 (node_size.cross(constants.dir).maybe_sub(constants.padding_border.cross_axis_sum(constants.dir)))
1070 .unwrap_or(0.0);
1071 } else {
1072 for line in flex_lines.iter_mut() {
1073 // 1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose
1074 // align-self is baseline, and whose cross-axis margins are both non-auto. Find the
1075 // largest of the distances between each item’s baseline and its hypothetical outer
1076 // cross-start edge, and the largest of the distances between each item’s baseline
1077 // and its hypothetical outer cross-end edge, and sum these two values.
1078
1079 // 2. Among all the items not collected by the previous step, find the largest
1080 // outer hypothetical cross size.
1081
1082 // 3. The used cross-size of the flex line is the largest of the numbers found in the
1083 // previous two steps and zero.
1084
1085 let max_baseline: f32 = line.items.iter().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
1086 line.cross_size = line
1087 .items
1088 .iter()
1089 .map(|child| {
1090 let child_style = tree.style(child.node);
1091 if child_style.align_self(tree.style(node)) == AlignSelf::Baseline
1092 && child_style.cross_margin_start(constants.dir) != Dimension::Auto
1093 && child_style.cross_margin_end(constants.dir) != Dimension::Auto
1094 && child_style.cross_size(constants.dir) == Dimension::Auto
1095 {
1096 max_baseline - child.baseline + child.hypothetical_outer_size.cross(constants.dir)
1097 } else {
1098 child.hypothetical_outer_size.cross(constants.dir)
1099 }
1100 })
1101 .fold(0.0, |acc, x| acc.max(x));
1102 }
1103 }
1104}
1105
1106/// Handle 'align-content: stretch'.
1107///
1108/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
1109///
1110/// - [**Handle 'align-content: stretch'**](https://www.w3.org/TR/css-flexbox-1/#algo-line-stretch). If the flex container has a definite cross size, align-content is stretch,
1111/// and the sum of the flex lines' cross sizes is less than the flex container’s inner cross size,
1112/// increase the cross size of each flex line by equal amounts such that the sum of their cross sizes exactly equals the flex container’s inner cross size.
1113#[inline]
1114fn handle_align_content_stretch(
1115 tree: &mut impl LayoutTree,
1116 flex_lines: &mut [FlexLine],
1117 node: Node,
1118 node_size: Size<Option<f32>>,
1119 constants: &AlgoConstants,
1120) {
1121 if tree.style(node).align_content == AlignContent::Stretch && node_size.cross(constants.dir).is_some() {
1122 let total_cross_axis_gap = sum_axis_gaps(constants.gap.cross(constants.dir), flex_lines.len());
1123 let total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum::<f32>() + total_cross_axis_gap;
1124 let inner_cross =
1125 (node_size.cross(constants.dir).maybe_sub(constants.padding_border.cross_axis_sum(constants.dir)))
1126 .unwrap_or(0.0);
1127
1128 if total_cross < inner_cross {
1129 let remaining = inner_cross - total_cross;
1130 let addition = remaining / flex_lines.len() as f32;
1131 flex_lines.iter_mut().for_each(|line| line.cross_size += addition);
1132 }
1133 }
1134}
1135
1136/// Determine the used cross size of each flex item.
1137///
1138/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
1139///
1140/// - [**Determine the used cross size of each flex item**](https://www.w3.org/TR/css-flexbox-1/#algo-stretch). If a flex item has align-self: stretch, its computed cross size property is auto,
1141/// and neither of its cross-axis margins are auto, the used outer cross size is the used cross size of its flex line, clamped according to the item’s used min and max cross sizes.
1142/// Otherwise, the used cross size is the item’s hypothetical cross size.
1143///
1144/// If the flex item has align-self: stretch, redo layout for its contents, treating this used size as its definite cross size so that percentage-sized children can be resolved.
1145///
1146/// **Note that this step does not affect the main size of the flex item, even if it has an intrinsic aspect ratio**.
1147#[inline]
1148fn determine_used_cross_size(
1149 tree: &mut impl LayoutTree,
1150 flex_lines: &mut [FlexLine],
1151 node: Node,
1152 constants: &AlgoConstants,
1153) {
1154 for line in flex_lines {
1155 let line_cross_size = line.cross_size;
1156
1157 for child in line.items.iter_mut() {
1158 let child_style = tree.style(child.node);
1159 child.target_size.set_cross(
1160 constants.dir,
1161 if child_style.align_self(tree.style(node)) == AlignSelf::Stretch
1162 && child_style.cross_margin_start(constants.dir) != Dimension::Auto
1163 && child_style.cross_margin_end(constants.dir) != Dimension::Auto
1164 && child_style.cross_size(constants.dir) == Dimension::Auto
1165 {
1166 (line_cross_size - child.margin.cross_axis_sum(constants.dir))
1167 .maybe_clamp(child.min_size.cross(constants.dir), child.max_size.cross(constants.dir))
1168 } else {
1169 child.hypothetical_inner_size.cross(constants.dir)
1170 },
1171 );
1172
1173 child.outer_target_size.set_cross(
1174 constants.dir,
1175 child.target_size.cross(constants.dir) + child.margin.cross_axis_sum(constants.dir),
1176 );
1177 }
1178 }
1179}
1180
1181/// Distribute any remaining free space.
1182///
1183/// # [9.5. Main-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#main-alignment)
1184///
1185/// - [**Distribute any remaining free space**](https://www.w3.org/TR/css-flexbox-1/#algo-main-align). For each flex line:
1186///
1187/// 1. If the remaining free space is positive and at least one main-axis margin on this line is `auto`, distribute the free space equally among these margins.
1188/// Otherwise, set all `auto` margins to zero.
1189///
1190/// 2. Align the items along the main-axis per `justify-content`.
1191#[inline]
1192fn distribute_remaining_free_space(
1193 tree: &mut impl LayoutTree,
1194 flex_lines: &mut [FlexLine],
1195 node: Node,
1196 constants: &AlgoConstants,
1197) {
1198 for line in flex_lines {
1199 let total_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
1200 let used_space: f32 = total_main_axis_gap
1201 + line.items.iter().map(|child| child.outer_target_size.main(constants.dir)).sum::<f32>();
1202 let free_space = constants.inner_container_size.main(constants.dir) - used_space;
1203 let mut num_auto_margins = 0;
1204
1205 for child in line.items.iter_mut() {
1206 let child_style = tree.style(child.node);
1207 if child_style.main_margin_start(constants.dir) == Dimension::Auto {
1208 num_auto_margins += 1;
1209 }
1210 if child_style.main_margin_end(constants.dir) == Dimension::Auto {
1211 num_auto_margins += 1;
1212 }
1213 }
1214
1215 if free_space > 0.0 && num_auto_margins > 0 {
1216 let margin = free_space / num_auto_margins as f32;
1217
1218 for child in line.items.iter_mut() {
1219 let child_style = tree.style(child.node);
1220 if child_style.main_margin_start(constants.dir) == Dimension::Auto {
1221 if constants.is_row {
1222 child.margin.left = margin;
1223 } else {
1224 child.margin.top = margin;
1225 }
1226 }
1227 if child_style.main_margin_end(constants.dir) == Dimension::Auto {
1228 if constants.is_row {
1229 child.margin.right = margin;
1230 } else {
1231 child.margin.bottom = margin;
1232 }
1233 }
1234 }
1235 } else {
1236 let num_items = line.items.len();
1237 let layout_reverse = constants.dir.is_reverse();
1238 let gap = constants.gap.main(constants.dir);
1239
1240 let justify_item = |(i, child): (usize, &mut FlexItem)| {
1241 let is_first = i == 0;
1242
1243 child.offset_main = match tree.style(node).justify_content {
1244 JustifyContent::FlexStart => {
1245 if is_first {
1246 if layout_reverse {
1247 free_space
1248 } else {
1249 0.0
1250 }
1251 } else {
1252 gap
1253 }
1254 }
1255 JustifyContent::Center => {
1256 if is_first {
1257 free_space / 2.0
1258 } else {
1259 gap
1260 }
1261 }
1262 JustifyContent::FlexEnd => {
1263 if is_first {
1264 if !layout_reverse {
1265 free_space
1266 } else {
1267 0.0
1268 }
1269 } else {
1270 gap
1271 }
1272 }
1273 JustifyContent::SpaceBetween => {
1274 if is_first {
1275 0.0
1276 } else {
1277 gap + (free_space / (num_items - 1) as f32)
1278 }
1279 }
1280 JustifyContent::SpaceAround => {
1281 if is_first {
1282 (free_space / num_items as f32) / 2.0
1283 } else {
1284 gap + (free_space / num_items as f32)
1285 }
1286 }
1287 JustifyContent::SpaceEvenly => {
1288 if is_first {
1289 free_space / (num_items + 1) as f32
1290 } else {
1291 gap + (free_space / (num_items + 1) as f32)
1292 }
1293 }
1294 };
1295 };
1296
1297 if layout_reverse {
1298 line.items.iter_mut().rev().enumerate().for_each(justify_item);
1299 } else {
1300 line.items.iter_mut().enumerate().for_each(justify_item);
1301 }
1302 }
1303 }
1304}
1305
1306/// Resolve cross-axis `auto` margins.
1307///
1308/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
1309///
1310/// - [**Resolve cross-axis `auto` margins**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-margins).
1311/// If a flex item has auto cross-axis margins:
1312///
1313/// - If its outer cross size (treating those auto margins as zero) is less than the cross size of its flex line,
1314/// distribute the difference in those sizes equally to the auto margins.
1315///
1316/// - Otherwise, if the block-start or inline-start margin (whichever is in the cross axis) is auto, set it to zero.
1317/// Set the opposite margin so that the outer cross size of the item equals the cross size of its flex line.
1318#[inline]
1319fn resolve_cross_axis_auto_margins(
1320 tree: &mut impl LayoutTree,
1321 flex_lines: &mut [FlexLine],
1322 node: Node,
1323 constants: &AlgoConstants,
1324) {
1325 for line in flex_lines {
1326 let line_cross_size = line.cross_size;
1327 let max_baseline: f32 = line.items.iter_mut().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
1328
1329 for child in line.items.iter_mut() {
1330 let free_space = line_cross_size - child.outer_target_size.cross(constants.dir);
1331 let child_style = tree.style(child.node);
1332
1333 if child_style.cross_margin_start(constants.dir) == Dimension::Auto
1334 && child_style.cross_margin_end(constants.dir) == Dimension::Auto
1335 {
1336 if constants.is_row {
1337 child.margin.top = free_space / 2.0;
1338 child.margin.bottom = free_space / 2.0;
1339 } else {
1340 child.margin.left = free_space / 2.0;
1341 child.margin.right = free_space / 2.0;
1342 }
1343 } else if child_style.cross_margin_start(constants.dir) == Dimension::Auto {
1344 if constants.is_row {
1345 child.margin.top = free_space;
1346 } else {
1347 child.margin.left = free_space;
1348 }
1349 } else if child_style.cross_margin_end(constants.dir) == Dimension::Auto {
1350 if constants.is_row {
1351 child.margin.bottom = free_space;
1352 } else {
1353 child.margin.right = free_space;
1354 }
1355 } else {
1356 // 14. Align all flex items along the cross-axis.
1357 child.offset_cross = align_flex_items_along_cross_axis(
1358 tree,
1359 node,
1360 child,
1361 child_style,
1362 free_space,
1363 max_baseline,
1364 constants,
1365 );
1366 }
1367 }
1368 }
1369}
1370
1371/// Align all flex items along the cross-axis.
1372///
1373/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
1374///
1375/// - [**Align all flex items along the cross-axis**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-align) per `align-self`,
1376/// if neither of the item's cross-axis margins are `auto`.
1377#[inline]
1378fn align_flex_items_along_cross_axis(
1379 tree: &impl LayoutTree,
1380 node: Node,
1381 child: &mut FlexItem,
1382 child_style: &Style,
1383 free_space: f32,
1384 max_baseline: f32,
1385 constants: &AlgoConstants,
1386) -> f32 {
1387 match child_style.align_self(tree.style(node)) {
1388 AlignSelf::Auto => unreachable!(),
1389 AlignSelf::FlexStart => {
1390 if constants.is_wrap_reverse {
1391 free_space
1392 } else {
1393 0.0
1394 }
1395 }
1396 AlignSelf::FlexEnd => {
1397 if constants.is_wrap_reverse {
1398 0.0
1399 } else {
1400 free_space
1401 }
1402 }
1403 AlignSelf::Center => free_space / 2.0,
1404 AlignSelf::Baseline => {
1405 if constants.is_row {
1406 max_baseline - child.baseline
1407 } else {
1408 // baseline alignment only makes sense if the constants.direction is row
1409 // we treat it as flex-start alignment in columns.
1410 if constants.is_wrap_reverse {
1411 free_space
1412 } else {
1413 0.0
1414 }
1415 }
1416 }
1417 AlignSelf::Stretch => {
1418 if constants.is_wrap_reverse {
1419 free_space
1420 } else {
1421 0.0
1422 }
1423 }
1424 }
1425}
1426
1427/// Determine the flex container’s used cross size.
1428///
1429/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
1430///
1431/// - [**Determine the flex container’s used cross size**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-container):
1432///
1433/// - If the cross size property is a definite size, use that, clamped by the used min and max cross sizes of the flex container.
1434///
1435/// - Otherwise, use the sum of the flex lines' cross sizes, clamped by the used min and max cross sizes of the flex container.
1436#[inline]
1437#[must_use]
1438fn determine_container_cross_size(
1439 flex_lines: &mut [FlexLine],
1440 node_size: Size<Option<f32>>,
1441 constants: &mut AlgoConstants,
1442) -> f32 {
1443 let total_cross_axis_gap = sum_axis_gaps(constants.gap.cross(constants.dir), flex_lines.len());
1444 let total_line_cross_size: f32 = flex_lines.iter().map(|line| line.cross_size).sum::<f32>();
1445
1446 constants.container_size.set_cross(
1447 constants.dir,
1448 node_size.cross(constants.dir).unwrap_or(
1449 total_line_cross_size + total_cross_axis_gap + constants.padding_border.cross_axis_sum(constants.dir),
1450 ),
1451 );
1452
1453 constants.inner_container_size.set_cross(
1454 constants.dir,
1455 constants.container_size.cross(constants.dir) - constants.padding_border.cross_axis_sum(constants.dir),
1456 );
1457
1458 total_line_cross_size
1459}
1460
1461/// Align all flex lines per `align-content`.
1462///
1463/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
1464///
1465/// - [**Align all flex lines**](https://www.w3.org/TR/css-flexbox-1/#algo-line-align) per `align-content`.
1466#[inline]
1467fn align_flex_lines_per_align_content(
1468 tree: &impl LayoutTree,
1469 flex_lines: &mut [FlexLine],
1470 node: Node,
1471 constants: &AlgoConstants,
1472 total_cross_size: f32,
1473) {
1474 let num_lines = flex_lines.len();
1475 let gap = constants.gap.cross(constants.dir);
1476 let total_cross_axis_gap = sum_axis_gaps(gap, num_lines);
1477 let free_space = constants.inner_container_size.cross(constants.dir) - total_cross_size - total_cross_axis_gap;
1478
1479 let align_line = |(i, line): (usize, &mut FlexLine)| {
1480 let is_first = i == 0;
1481
1482 line.offset_cross = match tree.style(node).align_content {
1483 AlignContent::FlexStart => {
1484 if is_first {
1485 if constants.is_wrap_reverse {
1486 free_space
1487 } else {
1488 0.0
1489 }
1490 } else {
1491 gap
1492 }
1493 }
1494 AlignContent::FlexEnd => {
1495 if is_first {
1496 if !constants.is_wrap_reverse {
1497 free_space
1498 } else {
1499 0.0
1500 }
1501 } else {
1502 gap
1503 }
1504 }
1505 AlignContent::Center => {
1506 if is_first {
1507 free_space / 2.0
1508 } else {
1509 gap
1510 }
1511 }
1512 AlignContent::Stretch => {
1513 if is_first {
1514 0.0
1515 } else {
1516 gap
1517 }
1518 }
1519 AlignContent::SpaceEvenly => {
1520 if is_first {
1521 free_space / (num_lines + 1) as f32
1522 } else {
1523 gap + (free_space / (num_lines + 1) as f32)
1524 }
1525 }
1526 AlignContent::SpaceBetween => {
1527 if is_first {
1528 0.0
1529 } else {
1530 gap + (free_space / (num_lines - 1) as f32)
1531 }
1532 }
1533 AlignContent::SpaceAround => {
1534 if is_first {
1535 (free_space / num_lines as f32) / 2.0
1536 } else {
1537 gap + (free_space / num_lines as f32)
1538 }
1539 }
1540 };
1541 };
1542
1543 if constants.is_wrap_reverse {
1544 flex_lines.iter_mut().rev().enumerate().for_each(align_line);
1545 } else {
1546 flex_lines.iter_mut().enumerate().for_each(align_line);
1547 }
1548}
1549
1550/// Calculates the layout for a flex-item
1551#[allow(clippy::too_many_arguments)]
1552fn calculate_flex_item(
1553 tree: &mut impl LayoutTree,
1554 node: Node,
1555 item: &mut FlexItem,
1556 total_offset_main: &mut f32,
1557 total_offset_cross: f32,
1558 line_offset_cross: f32,
1559 container_size: Size<f32>,
1560 direction: FlexDirection,
1561) {
1562 let preliminary_size = compute_node_layout(
1563 tree,
1564 item.node,
1565 item.target_size.map(|s| s.into()),
1566 container_size.map(|s| s.into()),
1567 RunMode::PeformLayout,
1568 SizingMode::ContentSize,
1569 );
1570
1571 let offset_main = *total_offset_main
1572 + item.offset_main
1573 + item.margin.main_start(direction)
1574 + (item.position.main_start(direction).unwrap_or(0.0) - item.position.main_end(direction).unwrap_or(0.0));
1575
1576 let offset_cross = total_offset_cross
1577 + item.offset_cross
1578 + line_offset_cross
1579 + item.margin.cross_start(direction)
1580 + (item.position.cross_start(direction).unwrap_or(0.0) - item.position.cross_end(direction).unwrap_or(0.0));
1581
1582 *tree.layout_mut(item.node) = Layout {
1583 order: tree.children(node).iter().position(|n| *n == item.node).unwrap() as u32,
1584 size: preliminary_size,
1585 location: Point {
1586 x: if direction.is_row() { offset_main } else { offset_cross },
1587 y: if direction.is_column() { offset_main } else { offset_cross },
1588 },
1589 };
1590
1591 *total_offset_main += item.offset_main + item.margin.main_axis_sum(direction) + preliminary_size.main(direction);
1592}
1593
1594/// Calculates the layout line
1595fn calculate_layout_line(
1596 tree: &mut impl LayoutTree,
1597 node: Node,
1598 line: &mut FlexLine,
1599 total_offset_cross: &mut f32,
1600 container_size: Size<f32>,
1601 padding_border: Rect<f32>,
1602 direction: FlexDirection,
1603) {
1604 let mut total_offset_main = padding_border.main_start(direction);
1605 let line_offset_cross = line.offset_cross;
1606
1607 if direction.is_reverse() {
1608 for item in line.items.iter_mut().rev() {
1609 calculate_flex_item(
1610 tree,
1611 node,
1612 item,
1613 &mut total_offset_main,
1614 *total_offset_cross,
1615 line_offset_cross,
1616 container_size,
1617 direction,
1618 );
1619 }
1620 } else {
1621 for item in line.items.iter_mut() {
1622 calculate_flex_item(
1623 tree,
1624 node,
1625 item,
1626 &mut total_offset_main,
1627 *total_offset_cross,
1628 line_offset_cross,
1629 container_size,
1630 direction,
1631 );
1632 }
1633 }
1634
1635 *total_offset_cross += line_offset_cross + line.cross_size;
1636}
1637
1638/// Do a final layout pass and collect the resulting layouts.
1639#[inline]
1640fn final_layout_pass(tree: &mut impl LayoutTree, node: Node, flex_lines: &mut [FlexLine], constants: &AlgoConstants) {
1641 let mut total_offset_cross = constants.padding_border.cross_start(constants.dir);
1642
1643 if constants.is_wrap_reverse {
1644 for line in flex_lines.iter_mut().rev() {
1645 calculate_layout_line(
1646 tree,
1647 node,
1648 line,
1649 &mut total_offset_cross,
1650 constants.container_size,
1651 constants.padding_border,
1652 constants.dir,
1653 );
1654 }
1655 } else {
1656 for line in flex_lines.iter_mut() {
1657 calculate_layout_line(
1658 tree,
1659 node,
1660 line,
1661 &mut total_offset_cross,
1662 constants.container_size,
1663 constants.padding_border,
1664 constants.dir,
1665 );
1666 }
1667 }
1668}
1669
1670/// Perform absolute layout on all absolutely positioned children.
1671#[inline]
1672fn perform_absolute_layout_on_absolute_children(tree: &mut impl LayoutTree, node: Node, constants: &AlgoConstants) {
1673 // TODO: remove number of Vec<_> generated
1674 let candidates = tree
1675 .children(node)
1676 .iter()
1677 .cloned()
1678 .enumerate()
1679 .filter(|(_, child)| tree.style(*child).position_type == PositionType::Absolute)
1680 .collect::<Vec<_>>();
1681
1682 for (order, child) in candidates {
1683 let container_width = constants.container_size.width;
1684 let container_height = constants.container_size.height;
1685
1686 let child_style = tree.style(child);
1687
1688 // X-axis
1689 let child_position_start = child_style.position.left.maybe_resolve(container_width);
1690 let child_margin_start = child_style.margin.left.maybe_resolve(container_width);
1691 let start = child_position_start.maybe_add(child_margin_start);
1692
1693 let child_position_end = child_style.position.right.maybe_resolve(container_width);
1694 let child_margin_end = child_style.margin.right.maybe_resolve(container_width);
1695 let end = child_position_end.maybe_add(child_margin_end);
1696
1697 // Y-axis
1698 let child_position_top = child_style.position.top.maybe_resolve(container_height);
1699 let child_margin_top = child_style.margin.top.maybe_resolve(container_height);
1700 let top = child_position_top.maybe_add(child_margin_top);
1701
1702 let child_position_bottom = child_style.position.bottom.maybe_resolve(container_height);
1703 let child_margin_bottom = child_style.margin.bottom.maybe_resolve(container_height);
1704 let bottom = child_position_bottom.maybe_add(child_margin_bottom);
1705
1706 let (start_main, end_main) = if constants.is_row { (start, end) } else { (top, bottom) };
1707 let (start_cross, end_cross) = if constants.is_row { (top, bottom) } else { (start, end) };
1708
1709 // Compute known dimensions from min/max/inherent size styles
1710 let style_size = child_style.size.maybe_resolve(constants.container_size);
1711 let min_size = child_style.min_size.maybe_resolve(constants.container_size);
1712 let max_size = child_style.max_size.maybe_resolve(constants.container_size);
1713 let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
1714
1715 // Fill in width from left/right and height from top/bottom is appropriate
1716 if known_dimensions.width.is_none() && start.is_some() && end.is_some() {
1717 known_dimensions.width = Some(container_width.maybe_sub(start).maybe_sub(end));
1718 }
1719 if known_dimensions.height.is_none() && top.is_some() && bottom.is_some() {
1720 known_dimensions.height = Some(container_height.maybe_sub(top).maybe_sub(bottom));
1721 }
1722
1723 let preliminary_size = compute_node_layout(
1724 tree,
1725 child,
1726 known_dimensions,
1727 Size {
1728 width: AvailableSpace::Definite(container_width),
1729 height: AvailableSpace::Definite(container_height),
1730 },
1731 RunMode::PeformLayout,
1732 SizingMode::ContentSize,
1733 );
1734
1735 // Satisfy the borrow checker by re-requesting the style from above.
1736 // This shortens the lifetime of the original binding
1737 let child_style = tree.style(child);
1738
1739 let free_main_space = constants.container_size.main(constants.dir)
1740 - preliminary_size
1741 .main(constants.dir)
1742 .maybe_max(
1743 child_style
1744 .min_main_size(constants.dir)
1745 .maybe_resolve(constants.node_inner_size.main(constants.dir)),
1746 )
1747 .maybe_min(
1748 child_style
1749 .max_main_size(constants.dir)
1750 .maybe_resolve(constants.node_inner_size.main(constants.dir)),
1751 );
1752
1753 let free_cross_space = constants.container_size.cross(constants.dir)
1754 - preliminary_size
1755 .cross(constants.dir)
1756 .maybe_max(
1757 child_style
1758 .min_cross_size(constants.dir)
1759 .maybe_resolve(constants.node_inner_size.cross(constants.dir)),
1760 )
1761 .maybe_min(
1762 child_style
1763 .max_cross_size(constants.dir)
1764 .maybe_resolve(constants.node_inner_size.cross(constants.dir)),
1765 );
1766
1767 let offset_main = if start_main.is_some() {
1768 start_main.unwrap_or(0.0) + constants.border.main_start(constants.dir)
1769 } else if end_main.is_some() {
1770 free_main_space - end_main.unwrap_or(0.0) - constants.border.main_end(constants.dir)
1771 } else {
1772 match tree.style(node).justify_content {
1773 JustifyContent::SpaceBetween | JustifyContent::FlexStart => {
1774 constants.padding_border.main_start(constants.dir)
1775 }
1776 JustifyContent::FlexEnd => free_main_space - constants.padding_border.main_end(constants.dir),
1777 JustifyContent::SpaceEvenly | JustifyContent::SpaceAround | JustifyContent::Center => {
1778 free_main_space / 2.0
1779 }
1780 }
1781 };
1782
1783 let offset_cross = if start_cross.is_some() {
1784 start_cross.unwrap_or(0.0) + constants.border.cross_start(constants.dir)
1785 } else if end_cross.is_some() {
1786 free_cross_space - end_cross.unwrap_or(0.0) - constants.border.cross_end(constants.dir)
1787 } else {
1788 match child_style.align_self(tree.style(node)) {
1789 AlignSelf::Auto => unreachable!(),
1790 AlignSelf::FlexStart => {
1791 if constants.is_wrap_reverse {
1792 free_cross_space - constants.padding_border.cross_end(constants.dir)
1793 } else {
1794 constants.padding_border.cross_start(constants.dir)
1795 }
1796 }
1797 AlignSelf::FlexEnd => {
1798 if constants.is_wrap_reverse {
1799 constants.padding_border.cross_start(constants.dir)
1800 } else {
1801 free_cross_space - constants.padding_border.cross_end(constants.dir)
1802 }
1803 }
1804 AlignSelf::Center => free_cross_space / 2.0,
1805 AlignSelf::Baseline => free_cross_space / 2.0, // Treat as center for now until we have baseline support
1806 AlignSelf::Stretch => {
1807 if constants.is_wrap_reverse {
1808 free_cross_space - constants.padding_border.cross_end(constants.dir)
1809 } else {
1810 constants.padding_border.cross_start(constants.dir)
1811 }
1812 }
1813 }
1814 };
1815
1816 *tree.layout_mut(child) = Layout {
1817 order: order as u32,
1818 size: preliminary_size,
1819 location: Point {
1820 x: if constants.is_row { offset_main } else { offset_cross },
1821 y: if constants.is_column { offset_main } else { offset_cross },
1822 },
1823 };
1824 }
1825}
1826
1827/// Creates a layout for this node and its children, recursively.
1828/// Each hidden node has zero size and is placed at the origin
1829fn hidden_layout(tree: &mut impl LayoutTree, node: Node, order: u32) {
1830 *tree.layout_mut(node) = Layout::with_order(order);
1831
1832 let len = tree.children(node).len();
1833 for order in 0..len {
1834 hidden_layout(tree, tree.child(node, order), order as _);
1835 }
1836}
1837
1838/// Computes the total space taken up by gaps in an axis given:
1839/// - The size of each gap
1840/// - The number of items (children or flex-lines) between which there are gaps
1841#[inline(always)]
1842fn sum_axis_gaps(gap: f32, num_items: usize) -> f32 {
1843 // Gaps only exist between items, so...
1844 if num_items <= 1 {
1845 // ...if there are less than 2 items then there are no gaps
1846 0.0
1847 } else {
1848 // ...otherwise there are (num_items - 1) gaps
1849 gap * (num_items - 1) as f32
1850 }
1851}
1852
1853#[cfg(test)]
1854mod tests {
1855 use super::hidden_layout;
1856 use crate::geometry::Point;
1857 use crate::style::Display;
1858 use crate::style::Display::Flex;
1859 use crate::{
1860 math::MaybeMath,
1861 prelude::{Rect, Size},
1862 resolve::ResolveOrDefault,
1863 style::{FlexWrap, Style},
1864 Taffy,
1865 };
1866
1867 // Make sure we get correct constants
1868 #[test]
1869 fn correct_constants() {
1870 let mut tree = Taffy::with_capacity(16);
1871
1872 let style = Style::default();
1873 let node_id = tree.new_leaf(style).unwrap();
1874
1875 let node_size = Size::NONE;
1876 let parent_size = Size::MAX_CONTENT;
1877
1878 let constants = super::compute_constants(tree.style(node_id).unwrap(), node_size, parent_size);
1879 // let constants = super::compute_constants(&tree.nodes[node_id], node_size, parent_size);
1880
1881 assert!(constants.dir == style.flex_direction);
1882 assert!(constants.is_row == style.flex_direction.is_row());
1883 assert!(constants.is_column == style.flex_direction.is_column());
1884 assert!(constants.is_wrap_reverse == (style.flex_wrap == FlexWrap::WrapReverse));
1885
1886 let margin = style.margin.resolve_or_default(parent_size.as_options());
1887 assert_eq!(constants.margin, margin);
1888
1889 let border = style.border.resolve_or_default(parent_size.as_options());
1890 assert_eq!(constants.border, border);
1891
1892 let padding = style.padding.resolve_or_default(parent_size.as_options());
1893
1894 // TODO: Replace with something less hardcoded?
1895 let padding_border = Rect {
1896 left: padding.left + border.left,
1897 right: padding.right + border.right,
1898 top: padding.top + border.top,
1899 bottom: padding.bottom + border.bottom,
1900 };
1901
1902 assert_eq!(constants.padding_border, padding_border);
1903
1904 // TODO: Replace with something less hardcoded?
1905 let inner_size = Size {
1906 width: node_size.width.maybe_sub(padding_border.horizontal_axis_sum()),
1907 height: node_size.height.maybe_sub(padding_border.vertical_axis_sum()),
1908 };
1909 assert_eq!(constants.node_inner_size, inner_size);
1910
1911 assert_eq!(constants.container_size, Size::ZERO);
1912 assert_eq!(constants.inner_container_size, Size::ZERO);
1913 }
1914
1915 #[test]
1916 fn hidden_layout_should_hide_recursively() {
1917 let mut taffy = Taffy::new();
1918
1919 let style: Style = Style { display: Flex, size: Size::from_points(50.0, 50.0), ..Default::default() };
1920
1921 let grandchild_00 = taffy.new_leaf(style).unwrap();
1922
1923 let grandchild_01 = taffy.new_leaf(style).unwrap();
1924
1925 let grandchild_02 = taffy.new_leaf(style).unwrap();
1926
1927 let child_00 = taffy.new_with_children(style, &[grandchild_00, grandchild_01]).unwrap();
1928
1929 let child_01 = taffy.new_with_children(style, &[grandchild_02]).unwrap();
1930
1931 let root = taffy
1932 .new_with_children(
1933 Style { display: Display::None, size: Size::from_points(50.0, 50.0), ..Default::default() },
1934 &[child_00, child_01],
1935 )
1936 .unwrap();
1937
1938 hidden_layout(&mut taffy, root, 0);
1939
1940 // Whatever size and display-mode the nodes had previously,
1941 // all layouts should resolve to ZERO due to the root's DISPLAY::NONE
1942 for (node, _) in &taffy.nodes {
1943 if let Ok(layout) = taffy.layout(node) {
1944 assert_eq!(layout.size, Size::ZERO);
1945 assert_eq!(layout.location, Point::ZERO);
1946 }
1947 }
1948 }
1949}