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