tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 707HTML 660Markdown 12TOML 62344 Definiciones

⎇ 30c626da4e2af7a2ca4f8bb2b014ab2a63d44dda src/algo.rs Rust · 1335 líneas · 55.0 KB Historia Quién tocó qué crudo

Add (nightly) no_std support 30c626da4 · Maximilian Goisser ·

1#[cfg(not(feature = "std"))]
2use alloc::{vec, vec::Vec};
3#[cfg(not(feature = "std"))]
4use libm::F32Ext;
5
6use core::f32;
7
8use crate::layout;
9use crate::ref_eq::ref_eq;
10
11use crate::style;
12use crate::style::*;
13
14use crate::number::Number::*;
15use crate::number::*;
16
17use crate::geometry::{Point, Rect, Size};
18
19#[derive(Debug, Clone)]
20pub struct ComputeResult {
21    pub size: Size<f32>,
22    pub children: Vec<layout::Node>,
23}
24
25struct FlexItem<'a> {
26    node: &'a style::Node,
27
28    size: Size<Number>,
29    min_size: Size<Number>,
30    max_size: Size<Number>,
31
32    position: Rect<Number>,
33    margin: Rect<f32>,
34    padding: Rect<f32>,
35    border: Rect<f32>,
36
37    flex_basis: f32,
38    inner_flex_basis: f32,
39    violation: f32,
40    frozen: bool,
41
42    hypothetical_inner_size: Size<f32>,
43    hypothetical_outer_size: Size<f32>,
44    target_size: Size<f32>,
45    outer_target_size: Size<f32>,
46
47    baseline: f32,
48
49    // temporary values for holding offset in the main / cross direction.
50    // offset is the relative position from the item's natural flow position based on
51    // relative position values, alignment, and justification. Does not unclude margin/padding/border.
52    offset_main: f32,
53    offset_cross: f32,
54}
55
56struct FlexLine<'a> {
57    items: Vec<FlexItem<'a>>,
58    cross_size: f32,
59    offset_cross: f32,
60}
61
62pub fn compute(root: &style::Node, size: Size<Number>) -> layout::Node {
63    let has_root_min_max = root.min_size.width.is_defined()
64        || root.min_size.height.is_defined()
65        || root.max_size.width.is_defined()
66        || root.max_size.height.is_defined();
67
68    let result = if has_root_min_max {
69        let first_pass = compute_internal(
70            root,
71            Size { width: root.size.width.resolve(size.width), height: root.size.height.resolve(size.height) },
72            size,
73            size.width,
74            false,
75        );
76
77        compute_internal(
78            root,
79            Size {
80                width: first_pass
81                    .size
82                    .width
83                    .maybe_max(root.min_size.width.resolve(size.width))
84                    .maybe_min(root.max_size.width.resolve(size.width))
85                    .to_number(),
86                height: first_pass
87                    .size
88                    .height
89                    .maybe_max(root.min_size.height.resolve(size.height))
90                    .maybe_min(root.max_size.height.resolve(size.height))
91                    .to_number(),
92            },
93            size,
94            size.width,
95            true,
96        )
97    } else {
98        compute_internal(
99            root,
100            Size { width: root.size.width.resolve(size.width), height: root.size.height.resolve(size.height) },
101            size,
102            size.width,
103            true,
104        )
105    };
106
107    let mut layout = layout::Node {
108        order: 0,
109        size: Size { width: result.size.width, height: result.size.height },
110        location: Point { x: 0.0, y: 0.0 },
111        children: result.children,
112    };
113
114    round_layout(&mut layout, 0.0, 0.0);
115    layout
116}
117
118fn round_layout(layout: &mut layout::Node, abs_x: f32, abs_y: f32) {
119    let abs_x = abs_x + layout.location.x;
120    let abs_y = abs_y + layout.location.y;
121
122    layout.location.x = layout.location.x.round();
123    layout.location.y = layout.location.y.round();
124    layout.size.width = (abs_x + layout.size.width).round() - abs_x.round();
125    layout.size.height = (abs_y + layout.size.height).round() - abs_y.round();
126    layout.children.iter_mut().for_each(|child| round_layout(child, abs_x, abs_y));
127}
128
129fn compute_internal(
130    node: &style::Node,
131    node_size: Size<Number>,
132    parent_size: Size<Number>,
133    percent_calc_base: Number,
134    perform_layout: bool,
135) -> ComputeResult {
136    // First we check if we have a result for the given input
137    {
138        let layout_cache = node.layout_cache.borrow();
139        if layout_cache.is_some() {
140            let cache = layout_cache.as_ref().unwrap();
141            if cache.perform_layout || !perform_layout {
142                let width_compatible = if let Number::Defined(width) = node_size.width {
143                    (width - cache.result.size.width).abs() < f32::EPSILON
144                } else {
145                    cache.node_size.width.is_undefined()
146                };
147
148                let height_compatible = if let Number::Defined(height) = node_size.height {
149                    (height - cache.result.size.height).abs() < f32::EPSILON
150                } else {
151                    cache.node_size.height.is_undefined()
152                };
153
154                if width_compatible && height_compatible {
155                    return cache.result.clone();
156                }
157
158                if cache.node_size == node_size
159                    && cache.parent_size == parent_size
160                    && cache.percent_calc_base == percent_calc_base
161                {
162                    return cache.result.clone();
163                }
164            }
165        }
166    }
167
168    // If this is a leaf node we can skip a lot of this function in some cases
169    if node.children.is_empty() {
170        if node_size.width.is_defined() && node_size.height.is_defined() {
171            return ComputeResult { size: node_size.map(|s| s.or_else(0.0)), children: vec![] };
172        }
173
174        if let Some(ref measure) = node.measure {
175            let result = ComputeResult { size: measure(node_size), children: vec![] };
176            node.layout_cache.replace(Some(LayoutCache {
177                node_size,
178                parent_size,
179                percent_calc_base,
180                perform_layout,
181                result: result.clone(),
182            }));
183            return result;
184        }
185    }
186
187    // Define some general constants we will need for the remainder
188    // of the algorithm.
189
190    let dir = node.flex_direction;
191    let is_row = dir.is_row();
192    let is_column = dir.is_column();
193    let is_wrap_reverse = node.flex_wrap == FlexWrap::WrapReverse;
194
195    let margin = node.margin.map(|n| n.resolve(percent_calc_base).or_else(0.0));
196    let padding = node.padding.map(|n| n.resolve(percent_calc_base).or_else(0.0));
197    let border = node.border.map(|n| n.resolve(percent_calc_base).or_else(0.0));
198
199    let padding_border = Rect {
200        start: padding.start + border.start,
201        end: padding.end + border.end,
202        top: padding.top + border.top,
203        bottom: padding.bottom + border.bottom,
204    };
205
206    let node_inner_size = Size {
207        width: node_size.width - padding_border.horizontal(),
208        height: node_size.height - padding_border.vertical(),
209    };
210
211    let percent_calc_base_child = node_inner_size.width;
212    let mut container_size = Size { width: 0.0, height: 0.0 };
213    let mut inner_container_size = Size { width: 0.0, height: 0.0 };
214
215    // 9.2. Line Length Determination
216
217    // 1. Generate anonymous flex items as described in §4 Flex Items.
218
219    // 2. Determine the available main and cross space for the flex items.
220    //    For each dimension, if that dimension of the flex container’s content box
221    //    is a definite size, use that; if that dimension of the flex container is
222    //    being sized under a min or max-content constraint, the available space in
223    //    that dimension is that constraint; otherwise, subtract the flex container’s
224    //    margin, border, and padding from the space available to the flex container
225    //    in that dimension and use that value. This might result in an infinite value.
226
227    let available_space = Size {
228        width: node_size.width.or_else(parent_size.width - margin.horizontal()) - padding_border.horizontal(),
229        height: node_size.height.or_else(parent_size.height - margin.vertical()) - padding_border.vertical(),
230    };
231
232    let mut flex_items: Vec<FlexItem> = node
233        .children
234        .iter()
235        .filter(|child| child.position_type != PositionType::Absolute)
236        .filter(|child| child.display != Display::None)
237        .map(|child| FlexItem {
238            node: child,
239
240            size: child.size.map(|s| s.resolve(percent_calc_base_child)),
241            min_size: child.min_size.map(|s| s.resolve(percent_calc_base_child)),
242            max_size: child.max_size.map(|s| s.resolve(percent_calc_base_child)),
243
244            position: child.position.map(|p| p.resolve(percent_calc_base_child)),
245            margin: child.margin.map(|m| m.resolve(percent_calc_base_child).or_else(0.0)),
246            padding: child.padding.map(|p| p.resolve(percent_calc_base_child).or_else(0.0)),
247            border: child.border.map(|b| b.resolve(percent_calc_base_child).or_else(0.0)),
248
249            flex_basis: 0.0,
250            inner_flex_basis: 0.0,
251            violation: 0.0,
252            frozen: false,
253
254            hypothetical_inner_size: Size { width: 0.0, height: 0.0 },
255            hypothetical_outer_size: Size { width: 0.0, height: 0.0 },
256            target_size: Size { width: 0.0, height: 0.0 },
257            outer_target_size: Size { width: 0.0, height: 0.0 },
258
259            baseline: 0.0,
260
261            offset_main: 0.0,
262            offset_cross: 0.0,
263        })
264        .collect();
265
266    // TODO - this does not follow spec. See commented out code below
267    // 3. Determine the flex base size and hypothetical main size of each item:
268    flex_items.iter_mut().for_each(|child| {
269        // A. If the item has a definite used flex basis, that’s the flex base size.
270
271        let flex_basis = child.node.flex_basis.resolve(percent_calc_base_child);
272        if flex_basis.is_defined() {
273            child.flex_basis = flex_basis.or_else(0.0);
274            return;
275        };
276
277        // B. If the flex item has an intrinsic aspect ratio,
278        //    a used flex basis of content, and a definite cross size,
279        //    then the flex base size is calculated from its inner
280        //    cross size and the flex item’s intrinsic aspect ratio.
281
282        if let Defined(ratio) = child.node.aspect_ratio {
283            if let Defined(cross) = node_size.cross(dir) {
284                if child.node.flex_basis == Dimension::Auto {
285                    child.flex_basis = cross * ratio;
286                    return;
287                }
288            }
289        }
290
291        // C. If the used flex basis is content or depends on its available space,
292        //    and the flex container is being sized under a min-content or max-content
293        //    constraint (e.g. when performing automatic table layout [CSS21]),
294        //    size the item under that constraint. The flex base size is the item’s
295        //    resulting main size.
296
297        // TODO - Probably need to cover this case in future
298
299        // D. Otherwise, if the used flex basis is content or depends on its
300        //    available space, the available main size is infinite, and the flex item’s
301        //    inline axis is parallel to the main axis, lay the item out using the rules
302        //    for a box in an orthogonal flow [CSS3-WRITING-MODES]. The flex base size
303        //    is the item’s max-content main size.
304
305        // TODO - Probably need to cover this case in future
306
307        // E. Otherwise, size the item into the available space using its used flex basis
308        //    in place of its main size, treating a value of content as max-content.
309        //    If a cross size is needed to determine the main size (e.g. when the
310        //    flex item’s main size is in its block axis) and the flex item’s cross size
311        //    is auto and not definite, in this calculation use fit-content as the
312        //    flex item’s cross size. The flex base size is the item’s resulting main size.
313
314        let width: Number = if !child.size.width.is_defined()
315            && child.node.align_self(node) == style::AlignSelf::Stretch
316            && is_column
317        {
318            available_space.width
319        } else {
320            child.size.width
321        };
322
323        let height: Number =
324            if !child.size.height.is_defined() && child.node.align_self(node) == style::AlignSelf::Stretch && is_row {
325                available_space.height
326            } else {
327                child.size.height
328            };
329
330        child.flex_basis = compute_internal(
331            child.node,
332            Size {
333                width: width.maybe_max(child.min_size.width).maybe_min(child.max_size.width),
334                height: height.maybe_max(child.min_size.height).maybe_min(child.max_size.height),
335            },
336            available_space,
337            percent_calc_base_child,
338            false,
339        )
340        .size
341        .main(dir)
342        .maybe_max(child.min_size.main(dir))
343        .maybe_min(child.max_size.main(dir));
344    });
345
346    // The hypothetical main size is the item’s flex base size clamped according to its
347    // used min and max main sizes (and flooring the content box size at zero).
348
349    flex_items.iter_mut().for_each(|child| {
350        child.inner_flex_basis = child.flex_basis - child.padding.main(dir) - child.border.main(dir);
351
352        // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
353        // The following logic was developed not from the spec but by trail and error looking into how
354        // webkit handled various scenarios. Can probably be solved better by passing in
355        // min-content max-content constraints fromt the top
356        let min_main = if is_row {
357            compute_internal(
358                child.node,
359                Size { width: Undefined, height: Undefined },
360                available_space,
361                percent_calc_base_child,
362                false,
363            )
364            .size
365            .width
366            .maybe_max(child.min_size.width)
367            .maybe_min(child.size.width)
368            .to_number()
369        } else {
370            child.min_size.main(dir)
371        };
372
373        child
374            .hypothetical_inner_size
375            .set_main(dir, child.flex_basis.maybe_max(min_main).maybe_min(child.max_size.main(dir)));
376
377        child.hypothetical_outer_size.set_main(dir, child.hypothetical_inner_size.main(dir) + child.margin.main(dir));
378    });
379
380    // 9.3. Main Size Determination
381
382    // 5. Collect flex items into flex lines:
383    //    - If the flex container is single-line, collect all the flex items into
384    //      a single flex line.
385    //    - Otherwise, starting from the first uncollected item, collect consecutive
386    //      items one by one until the first time that the next collected item would
387    //      not fit into the flex container’s inner main size (or until a forced break
388    //      is encountered, see §10 Fragmenting Flex Layout). If the very first
389    //      uncollected item wouldn’t fit, collect just it into the line.
390    //
391    //      For this step, the size of a flex item is its outer hypothetical main size. (Note: This can be negative.)
392    //      Repeat until all flex items have been collected into flex lines
393    //
394    //      Note that the "collect as many" line will collect zero-sized flex items onto
395    //      the end of the previous line even if the last non-zero item exactly "filled up" the line.
396
397    let mut flex_lines = {
398        let mut lines: Vec<FlexLine> = vec![];
399        let mut line_length = 0.0;
400
401        if node.flex_wrap == FlexWrap::NoWrap {
402            lines.push(FlexLine { items: flex_items, cross_size: 0.0, offset_cross: 0.0 });
403        } else {
404            let mut line = FlexLine { items: vec![], cross_size: 0.0, offset_cross: 0.0 };
405
406            for child in flex_items {
407                line_length += child.hypothetical_outer_size.main(dir);
408
409                if let Defined(main) = available_space.main(dir) {
410                    if line_length > main && !line.items.is_empty() {
411                        line_length = child.hypothetical_outer_size.main(dir);
412                        lines.push(line);
413                        line = FlexLine { items: vec![], cross_size: 0.0, offset_cross: 0.0 };
414                    }
415                }
416
417                line.items.push(child);
418            }
419
420            lines.push(line);
421        }
422
423        lines
424    };
425
426    // 6. Resolve the flexible lengths of all the flex items to find their used main size.
427    //    See §9.7 Resolving Flexible Lengths.
428    //
429    // 9.7. Resolving Flexible Lengths
430
431    flex_lines.iter_mut().for_each(|line| {
432        // 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
433        //    items on the line. If the sum is less than the flex container’s inner main size,
434        //    use the flex grow factor for the rest of this algorithm; otherwise, use the
435        //    flex shrink factor.
436
437        let used_flex_factor: f32 = line.items.iter().map(|child| child.hypothetical_outer_size.main(dir)).sum();
438        let growing = used_flex_factor < node_inner_size.main(dir).or_else(0.0);
439        let shrinking = !growing;
440
441        // 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
442        //    - Any item that has a flex factor of zero
443        //    - If using the flex grow factor: any item that has a flex base size
444        //      greater than its hypothetical main size
445        //    - If using the flex shrink factor: any item that has a flex base size
446        //      smaller than its hypothetical main size
447
448        line.items.iter_mut().for_each(|child| {
449            // TODO - This is not found by reading the spec. Maybe this can be done in some other place
450            // instead. This was found by trail and error fixing tests to align with webkit output.
451            if node_inner_size.main(dir).is_undefined() && is_row {
452                child.target_size.set_main(
453                    dir,
454                    compute_internal(
455                        child.node,
456                        Size {
457                            width: child.size.width.maybe_max(child.min_size.width).maybe_min(child.max_size.width),
458                            height: child.size.height.maybe_max(child.min_size.height).maybe_min(child.max_size.height),
459                        },
460                        available_space,
461                        percent_calc_base_child,
462                        false,
463                    )
464                    .size
465                    .main(dir)
466                    .maybe_max(child.min_size.main(dir))
467                    .maybe_min(child.max_size.main(dir)),
468                );
469            } else {
470                child.target_size.set_main(dir, child.hypothetical_inner_size.main(dir));
471            }
472
473            // TODO this should really only be set inside the if-statement below but
474            // that casues the target_main_size to never be set for some items
475
476            child.outer_target_size.set_main(dir, child.target_size.main(dir) + child.margin.main(dir));
477
478            if (child.node.flex_grow == 0.0 && child.node.flex_shrink == 0.0)
479                || (growing && child.flex_basis > child.hypothetical_inner_size.main(dir))
480                || (shrinking && child.flex_basis < child.hypothetical_inner_size.main(dir))
481            {
482                child.frozen = true;
483            }
484        });
485
486        // 3. Calculate initial free space. Sum the outer sizes of all items on the line,
487        //    and subtract this from the flex container’s inner main size. For frozen items,
488        //    use their outer target main size; for other items, use their outer flex base size.
489
490        let used_space: f32 = line
491            .items
492            .iter()
493            .map(|child| {
494                child.margin.main(dir) + if child.frozen { child.target_size.main(dir) } else { child.flex_basis }
495            })
496            .sum();
497
498        let initial_free_space = (node_inner_size.main(dir) - used_space).or_else(0.0);
499
500        // 4. Loop
501
502        loop {
503            // a. Check for flexible items. If all the flex items on the line are frozen,
504            //    free space has been distributed; exit this loop.
505
506            let mut frozen: Vec<&mut FlexItem> = vec![];
507            let mut unfrozen: Vec<&mut FlexItem> = vec![];
508
509            line.items.iter_mut().for_each(|child| {
510                if child.frozen {
511                    frozen.push(child);
512                } else {
513                    unfrozen.push(child);
514                }
515            });
516
517            if unfrozen.is_empty() {
518                break;
519            }
520
521            // b. Calculate the remaining free space as for initial free space, above.
522            //    If the sum of the unfrozen flex items’ flex factors is less than one,
523            //    multiply the initial free space by this sum. If the magnitude of this
524            //    value is less than the magnitude of the remaining free space, use this
525            //    as the remaining free space.
526
527            let used_space: f32 = Iterator::chain(frozen.iter(), unfrozen.iter())
528                .map(|child| {
529                    child.margin.main(dir) + if child.frozen { child.target_size.main(dir) } else { child.flex_basis }
530                })
531                .sum();
532
533            let sum_flex_grow: f32 = unfrozen.iter().map(|item| item.node.flex_grow).sum();
534            let sum_flex_shrink: f32 = unfrozen.iter().map(|item| item.node.flex_shrink).sum();
535
536            let free_space = if growing && sum_flex_grow < 1.0 {
537                (initial_free_space * sum_flex_grow).maybe_min(node_inner_size.main(dir) - used_space)
538            } else if shrinking && sum_flex_shrink < 1.0 {
539                (initial_free_space * sum_flex_shrink).maybe_max(node_inner_size.main(dir) - used_space)
540            } else {
541                (node_inner_size.main(dir) - used_space).or_else(0.0)
542            };
543
544            // c. Distribute free space proportional to the flex factors.
545            //    - If the remaining free space is zero
546            //        Do Nothing
547            //    - If using the flex grow factor
548            //        Find the ratio of the item’s flex grow factor to the sum of the
549            //        flex grow factors of all unfrozen items on the line. Set the item’s
550            //        target main size to its flex base size plus a fraction of the remaining
551            //        free space proportional to the ratio.
552            //    - If using the flex shrink factor
553            //        For every unfrozen item on the line, multiply its flex shrink factor by
554            //        its inner flex base size, and note this as its scaled flex shrink factor.
555            //        Find the ratio of the item’s scaled flex shrink factor to the sum of the
556            //        scaled flex shrink factors of all unfrozen items on the line. Set the item’s
557            //        target main size to its flex base size minus a fraction of the absolute value
558            //        of the remaining free space proportional to the ratio. Note this may result
559            //        in a negative inner main size; it will be corrected in the next step.
560            //    - Otherwise
561            //        Do Nothing
562
563            if free_space.is_normal() {
564                if growing && sum_flex_grow > 0.0 {
565                    unfrozen.iter_mut().for_each(|child| {
566                        child
567                            .target_size
568                            .set_main(dir, child.flex_basis + free_space * (child.node.flex_grow / sum_flex_grow));
569                    });
570                } else if shrinking && sum_flex_shrink > 0.0 {
571                    let sum_scaled_shrink_factor: f32 =
572                        unfrozen.iter().map(|child| child.inner_flex_basis * child.node.flex_shrink).sum();
573
574                    if sum_scaled_shrink_factor > 0.0 {
575                        unfrozen.iter_mut().for_each(|child| {
576                            let scaled_shrink_factor = child.inner_flex_basis * child.node.flex_shrink;
577                            child.target_size.set_main(
578                                dir,
579                                child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor),
580                            )
581                        });
582                    }
583                }
584            }
585
586            // d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
587            //    used min and max main sizes and floor its content-box size at zero. If the
588            //    item’s target main size was made smaller by this, it’s a max violation.
589            //    If the item’s target main size was made larger by this, it’s a min violation.
590
591            let total_violation = unfrozen.iter_mut().fold(0.0, |acc, child| {
592                // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
593                // The following logic was developed not from the spec but by trail and error looking into how
594                // webkit handled various scenarios. Can probably be solved better by passing in
595                // min-content max-content constraints fromt the top. Need to figure out correct thing to do here as
596                // just piling on more conditionals.
597                let min_main = if is_row && child.node.measure.is_none() {
598                    compute_internal(
599                        child.node,
600                        Size { width: Undefined, height: Undefined },
601                        available_space,
602                        percent_calc_base_child,
603                        false,
604                    )
605                    .size
606                    .width
607                    .maybe_min(child.size.width)
608                    .maybe_max(child.min_size.width)
609                    .to_number()
610                } else {
611                    child.min_size.main(dir)
612                };
613
614                let max_main = child.max_size.main(dir);
615                let clamped = child.target_size.main(dir).maybe_min(max_main).maybe_max(min_main).max(0.0);
616                child.violation = clamped - child.target_size.main(dir);
617                child.target_size.set_main(dir, clamped);
618                child.outer_target_size.set_main(dir, child.target_size.main(dir) + child.margin.main(dir));
619
620                acc + child.violation
621            });
622
623            // e. Freeze over-flexed items. The total violation is the sum of the adjustments
624            //    from the previous step ∑(clamped size - unclamped size). If the total violation is:
625            //    - Zero
626            //        Freeze all items.
627            //    - Positive
628            //        Freeze all the items with min violations.
629            //    - Negative
630            //        Freeze all the items with max violations.
631
632            unfrozen.iter_mut().for_each(|child| match total_violation {
633                v if v > 0.0 => child.frozen = child.violation > 0.0,
634                v if v < 0.0 => child.frozen = child.violation < 0.0,
635                _ => child.frozen = true,
636            })
637
638            // f. Return to the start of this loop.
639        }
640    });
641
642    // Not part of the spec from what i can see but seems correct
643    container_size.set_main(
644        dir,
645        node_size.main(dir).or_else({
646            let longest_line = flex_lines.iter().fold(f32::MIN, |acc, line| {
647                let length: f32 = line.items.iter().map(|item| item.outer_target_size.main(dir)).sum();
648                acc.max(length)
649            });
650
651            let size = longest_line + padding_border.main(dir);
652            match available_space.main(dir) {
653                Defined(val) if flex_lines.len() > 1 && size < val => val,
654                _ => size,
655            }
656        }),
657    );
658
659    inner_container_size.set_main(dir, container_size.main(dir) - padding_border.main(dir));
660
661    // 9.4. Cross Size Determination
662
663    // 7. Determine the hypothetical cross size of each item by performing layout with the
664    //    used main size and the available space, treating auto as fit-content.
665
666    flex_lines.iter_mut().for_each(|line| {
667        line.items.iter_mut().for_each(|child| {
668            let child_cross =
669                child.size.cross(dir).maybe_max(child.min_size.cross(dir)).maybe_min(child.max_size.cross(dir));
670
671            child.hypothetical_inner_size.set_cross(
672                dir,
673                compute_internal(
674                    child.node,
675                    Size {
676                        width: if is_row { child.target_size.width.to_number() } else { child_cross },
677                        height: if is_row { child_cross } else { child.target_size.height.to_number() },
678                    },
679                    Size {
680                        width: if is_row { container_size.main(dir).to_number() } else { available_space.width },
681                        height: if is_row { available_space.height } else { container_size.main(dir).to_number() },
682                    },
683                    percent_calc_base_child,
684                    false,
685                )
686                .size
687                .cross(dir)
688                .maybe_max(child.min_size.cross(dir))
689                .maybe_min(child.max_size.cross(dir)),
690            );
691
692            child
693                .hypothetical_outer_size
694                .set_cross(dir, child.hypothetical_inner_size.cross(dir) + child.margin.cross(dir));
695        });
696    });
697
698    // TODO - probably should move this somewhere else as it doesn't make a ton of sense here but we need it below
699    // TODO - This is expensive and should only be done if we really require a baseline. aka, make it lazy
700
701    fn calc_baseline(layout: &layout::Node) -> f32 {
702        if layout.children.is_empty() {
703            layout.size.height
704        } else {
705            calc_baseline(&layout.children[0])
706        }
707    };
708
709    flex_lines.iter_mut().for_each(|line| {
710        line.items.iter_mut().for_each(|child| {
711            let result = compute_internal(
712                child.node,
713                Size {
714                    width: if is_row {
715                        child.target_size.width.to_number()
716                    } else {
717                        child.hypothetical_inner_size.width.to_number()
718                    },
719                    height: if is_row {
720                        child.hypothetical_inner_size.height.to_number()
721                    } else {
722                        child.target_size.height.to_number()
723                    },
724                },
725                Size {
726                    width: if is_row { container_size.width.to_number() } else { node_size.width },
727                    height: if is_row { node_size.height } else { container_size.height.to_number() },
728                },
729                percent_calc_base_child,
730                true,
731            );
732            child.baseline = calc_baseline(&layout::Node {
733                order: node.children.iter().position(|n| ref_eq(n, child.node)).unwrap() as u32,
734                size: result.size,
735                location: Point { x: 0.0, y: 0.0 },
736                children: result.children,
737            });
738        });
739    });
740
741    // 8. Calculate the cross size of each flex line.
742    //    If the flex container is single-line and has a definite cross size, the cross size
743    //    of the flex line is the flex container’s inner cross size. Otherwise, for each flex line:
744    //
745    //    If the flex container is single-line, then clamp the line’s cross-size to be within
746    //    the container’s computed min and max cross sizes. Note that if CSS 2.1’s definition
747    //    of min/max-width/height applied more generally, this behavior would fall out automatically.
748
749    if flex_lines.len() == 1 && node_size.cross(dir).is_defined() {
750        flex_lines[0].cross_size = (node_size.cross(dir) - padding_border.cross(dir)).or_else(0.0);
751    } else {
752        flex_lines.iter_mut().for_each(|line| {
753            //    1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose
754            //       align-self is baseline, and whose cross-axis margins are both non-auto. Find the
755            //       largest of the distances between each item’s baseline and its hypothetical outer
756            //       cross-start edge, and the largest of the distances between each item’s baseline
757            //       and its hypothetical outer cross-end edge, and sum these two values.
758
759            //    2. Among all the items not collected by the previous step, find the largest
760            //       outer hypothetical cross size.
761
762            //    3. The used cross-size of the flex line is the largest of the numbers found in the
763            //       previous two steps and zero.
764
765            let max_baseline: f32 = line.items.iter().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
766            line.cross_size = line
767                .items
768                .iter()
769                .map(|child| {
770                    if child.node.align_self(node) == AlignSelf::Baseline
771                        && child.node.cross_margin_start(dir) != Dimension::Auto
772                        && child.node.cross_margin_end(dir) != Dimension::Auto
773                        && child.node.cross_size(dir) == Dimension::Auto
774                    {
775                        max_baseline - child.baseline + child.hypothetical_outer_size.cross(dir)
776                    } else {
777                        child.hypothetical_outer_size.cross(dir)
778                    }
779                })
780                .fold(0.0, |acc, x| acc.max(x));
781        });
782    }
783
784    // 9. Handle 'align-content: stretch'. If the flex container has a definite cross size,
785    //    align-content is stretch, and the sum of the flex lines' cross sizes is less than
786    //    the flex container’s inner cross size, increase the cross size of each flex line
787    //    by equal amounts such that the sum of their cross sizes exactly equals the
788    //    flex container’s inner cross size.
789
790    if node.align_content == AlignContent::Stretch && node_size.cross(dir).is_defined() {
791        let total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
792        let inner_cross = (node_size.cross(dir) - padding_border.cross(dir)).or_else(0.0);
793
794        if total_cross < inner_cross {
795            let remaining = inner_cross - total_cross;
796            let addition = remaining / flex_lines.len() as f32;
797            flex_lines.iter_mut().for_each(|line| line.cross_size += addition);
798        }
799    }
800
801    // 10. Collapse visibility:collapse items. If any flex items have visibility: collapse,
802    //     note the cross size of the line they’re in as the item’s strut size, and restart
803    //     layout from the beginning.
804    //
805    //     In this second layout round, when collecting items into lines, treat the collapsed
806    //     items as having zero main size. For the rest of the algorithm following that step,
807    //     ignore the collapsed items entirely (as if they were display:none) except that after
808    //     calculating the cross size of the lines, if any line’s cross size is less than the
809    //     largest strut size among all the collapsed items in the line, set its cross size to
810    //     that strut size.
811    //
812    //     Skip this step in the second layout round.
813
814    // TODO implement once (if ever) we support visibility:collapse
815
816    // 11. Determine the used cross size of each flex item. If a flex item has align-self: stretch,
817    //     its computed cross size property is auto, and neither of its cross-axis margins are auto,
818    //     the used outer cross size is the used cross size of its flex line, clamped according to
819    //     the item’s used min and max cross sizes. Otherwise, the used cross size is the item’s
820    //     hypothetical cross size.
821    //
822    //     If the flex item has align-self: stretch, redo layout for its contents, treating this
823    //     used size as its definite cross size so that percentage-sized children can be resolved.
824    //
825    //     Note that this step does not affect the main size of the flex item, even if it has an
826    //     intrinsic aspect ratio.
827
828    flex_lines.iter_mut().for_each(|line| {
829        let line_cross_size = line.cross_size;
830
831        line.items.iter_mut().for_each(|child| {
832            child.target_size.set_cross(
833                dir,
834                if child.node.align_self(node) == AlignSelf::Stretch
835                    && child.node.cross_margin_start(dir) != Dimension::Auto
836                    && child.node.cross_margin_end(dir) != Dimension::Auto
837                    && child.node.cross_size(dir) == Dimension::Auto
838                {
839                    (line_cross_size - child.margin.cross(dir))
840                        .maybe_max(child.min_size.cross(dir))
841                        .maybe_min(child.max_size.cross(dir))
842                } else {
843                    child.hypothetical_inner_size.cross(dir)
844                },
845            );
846
847            child.outer_target_size.set_cross(dir, child.target_size.cross(dir) + child.margin.cross(dir));
848        });
849    });
850
851    // 9.5. Main-Axis Alignment
852
853    // 12. Distribute any remaining free space. For each flex line:
854    //     1. If the remaining free space is positive and at least one main-axis margin on this
855    //        line is auto, distribute the free space equally among these margins. Otherwise,
856    //        set all auto margins to zero.
857    //     2. Align the items along the main-axis per justify-content.
858
859    flex_lines.iter_mut().for_each(|line| {
860        let used_space: f32 = line.items.iter().map(|child| child.outer_target_size.main(dir)).sum();
861        let free_space = inner_container_size.main(dir) - used_space;
862        let mut num_auto_margins = 0;
863
864        line.items.iter_mut().for_each(|child| {
865            if child.node.main_margin_start(dir) == Dimension::Auto {
866                num_auto_margins += 1;
867            }
868            if child.node.main_margin_end(dir) == Dimension::Auto {
869                num_auto_margins += 1;
870            }
871        });
872
873        if free_space > 0.0 && num_auto_margins > 0 {
874            let margin = free_space / num_auto_margins as f32;
875
876            line.items.iter_mut().for_each(|child| {
877                if child.node.main_margin_start(dir) == Dimension::Auto {
878                    if is_row {
879                        child.margin.start = margin;
880                    } else {
881                        child.margin.top = margin;
882                    }
883                }
884                if child.node.main_margin_end(dir) == Dimension::Auto {
885                    if is_row {
886                        child.margin.end = margin;
887                    } else {
888                        child.margin.bottom = margin;
889                    }
890                }
891            });
892        } else {
893            let num_items = line.items.len();
894            let layout_reverse = dir.is_reverse();
895
896            let justify_item = |(i, child): (usize, &mut FlexItem)| {
897                let is_first = i == 0;
898
899                child.offset_main = match node.justify_content {
900                    JustifyContent::FlexStart => {
901                        if layout_reverse && is_first {
902                            free_space
903                        } else {
904                            0.0
905                        }
906                    }
907                    JustifyContent::Center => {
908                        if is_first {
909                            free_space / 2.0
910                        } else {
911                            0.0
912                        }
913                    }
914                    JustifyContent::FlexEnd => {
915                        if is_first && !layout_reverse {
916                            free_space
917                        } else {
918                            0.0
919                        }
920                    }
921                    JustifyContent::SpaceBetween => {
922                        if is_first {
923                            0.0
924                        } else {
925                            free_space / (num_items - 1) as f32
926                        }
927                    }
928                    JustifyContent::SpaceAround => {
929                        if is_first {
930                            (free_space / num_items as f32) / 2.0
931                        } else {
932                            free_space / num_items as f32
933                        }
934                    }
935                    JustifyContent::SpaceEvenly => free_space / (num_items + 1) as f32,
936                };
937            };
938
939            if layout_reverse {
940                line.items.iter_mut().rev().enumerate().for_each(justify_item);
941            } else {
942                line.items.iter_mut().enumerate().for_each(justify_item);
943            }
944        }
945    });
946
947    // 9.6. Cross-Axis Alignment
948
949    // 13. Resolve cross-axis auto margins. If a flex item has auto cross-axis margins:
950    //     - If its outer cross size (treating those auto margins as zero) is less than the
951    //       cross size of its flex line, distribute the difference in those sizes equally
952    //       to the auto margins.
953    //     - Otherwise, if the block-start or inline-start margin (whichever is in the cross axis)
954    //       is auto, set it to zero. Set the opposite margin so that the outer cross size of the
955    //       item equals the cross size of its flex line.
956
957    flex_lines.iter_mut().for_each(|line| {
958        let line_cross_size = line.cross_size;
959        let max_baseline: f32 = line.items.iter_mut().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
960
961        line.items.iter_mut().for_each(|child| {
962            let free_space = line_cross_size - child.outer_target_size.cross(dir);
963
964            if child.node.cross_margin_start(dir) == Dimension::Auto
965                && child.node.cross_margin_end(dir) == Dimension::Auto
966            {
967                if is_row {
968                    child.margin.top = free_space / 2.0;
969                    child.margin.bottom = free_space / 2.0;
970                } else {
971                    child.margin.start = free_space / 2.0;
972                    child.margin.end = free_space / 2.0;
973                }
974            } else if child.node.cross_margin_start(dir) == Dimension::Auto {
975                if is_row {
976                    child.margin.top = free_space;
977                } else {
978                    child.margin.start = free_space;
979                }
980            } else if child.node.cross_margin_end(dir) == Dimension::Auto {
981                if is_row {
982                    child.margin.bottom = free_space;
983                } else {
984                    child.margin.end = free_space;
985                }
986            } else {
987                // 14. Align all flex items along the cross-axis per align-self, if neither of the item’s
988                //     cross-axis margins are auto.
989
990                child.offset_cross = match child.node.align_self(node) {
991                    AlignSelf::Auto => 0.0, // Should never happen
992                    AlignSelf::FlexStart => {
993                        if is_wrap_reverse {
994                            free_space
995                        } else {
996                            0.0
997                        }
998                    }
999                    AlignSelf::FlexEnd => {
1000                        if is_wrap_reverse {
1001                            0.0
1002                        } else {
1003                            free_space
1004                        }
1005                    }
1006                    AlignSelf::Center => free_space / 2.0,
1007                    AlignSelf::Baseline => {
1008                        if is_row {
1009                            max_baseline - child.baseline
1010                        } else {
1011                            // basline alignment only makes sense if the direction is row
1012                            // we treat it as flex-start alignment in columns.
1013                            if is_wrap_reverse {
1014                                free_space
1015                            } else {
1016                                0.0
1017                            }
1018                        }
1019                    }
1020                    AlignSelf::Stretch => {
1021                        if is_wrap_reverse {
1022                            free_space
1023                        } else {
1024                            0.0
1025                        }
1026                    }
1027                };
1028            }
1029        });
1030    });
1031
1032    // 15. Determine the flex container’s used cross size:
1033    //     - If the cross size property is a definite size, use that, clamped by the used
1034    //       min and max cross sizes of the flex container.
1035    //     - Otherwise, use the sum of the flex lines' cross sizes, clamped by the used
1036    //       min and max cross sizes of the flex container.
1037
1038    let total_cross_size: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
1039    container_size.set_cross(dir, node_size.cross(dir).or_else(total_cross_size + padding_border.cross(dir)));
1040    inner_container_size.set_cross(dir, container_size.cross(dir) - padding_border.cross(dir));
1041
1042    // We have the container size. If our caller does not care about performing
1043    // layout we are done now.
1044    if !perform_layout {
1045        let result = ComputeResult { size: container_size, children: vec![] };
1046        node.layout_cache.replace(Some(LayoutCache {
1047            node_size,
1048            parent_size,
1049            percent_calc_base,
1050            perform_layout,
1051            result: result.clone(),
1052        }));
1053        return result;
1054    }
1055
1056    // 16. Align all flex lines per align-content.
1057
1058    let free_space = inner_container_size.cross(dir) - total_cross_size;
1059    let num_lines = flex_lines.len();
1060
1061    let align_line = |(i, line): (usize, &mut FlexLine)| {
1062        let is_first = i == 0;
1063
1064        line.offset_cross = match node.align_content {
1065            AlignContent::FlexStart => {
1066                if is_first && is_wrap_reverse {
1067                    free_space
1068                } else {
1069                    0.0
1070                }
1071            }
1072            AlignContent::FlexEnd => {
1073                if is_first && !is_wrap_reverse {
1074                    free_space
1075                } else {
1076                    0.0
1077                }
1078            }
1079            AlignContent::Center => {
1080                if is_first {
1081                    free_space / 2.0
1082                } else {
1083                    0.0
1084                }
1085            }
1086            AlignContent::Stretch => 0.0,
1087            AlignContent::SpaceBetween => {
1088                if is_first {
1089                    0.0
1090                } else {
1091                    free_space / (num_lines - 1) as f32
1092                }
1093            }
1094            AlignContent::SpaceAround => {
1095                if is_first {
1096                    (free_space / num_lines as f32) / 2.0
1097                } else {
1098                    free_space / num_lines as f32
1099                }
1100            }
1101        };
1102    };
1103
1104    if is_wrap_reverse {
1105        flex_lines.iter_mut().rev().enumerate().for_each(align_line);
1106    } else {
1107        flex_lines.iter_mut().enumerate().for_each(align_line);
1108    }
1109
1110    // Do a final layout pass and gather the resulting layouts
1111    let mut children: Vec<layout::Node> = {
1112        let mut lines: Vec<Vec<layout::Node>> = vec![];
1113        let mut total_offset_cross = padding_border.cross_start(dir);
1114
1115        let layout_line = |line: &mut FlexLine| {
1116            let mut children: Vec<layout::Node> = vec![];
1117            let mut total_offset_main = padding_border.main_start(dir);
1118            let line_offset_cross = line.offset_cross;
1119
1120            let layout_item = |child: &mut FlexItem| {
1121                let result = compute_internal(
1122                    child.node,
1123                    child.target_size.map(|s| s.to_number()),
1124                    container_size.map(|s| s.to_number()),
1125                    percent_calc_base_child,
1126                    true,
1127                );
1128
1129                let offset_main = total_offset_main
1130                    + child.offset_main
1131                    + child.margin.main_start(dir)
1132                    + (child.position.main_start(dir).or_else(0.0) - child.position.main_end(dir).or_else(0.0));
1133
1134                let offset_cross = total_offset_cross
1135                    + child.offset_cross
1136                    + line_offset_cross
1137                    + child.margin.cross_start(dir)
1138                    + (child.position.cross_start(dir).or_else(0.0) - child.position.cross_end(dir).or_else(0.0));
1139
1140                children.push(layout::Node {
1141                    order: node.children.iter().position(|n| ref_eq(n, child.node)).unwrap() as u32,
1142                    size: result.size,
1143                    location: Point {
1144                        x: if is_row { offset_main } else { offset_cross },
1145                        y: if is_column { offset_main } else { offset_cross },
1146                    },
1147                    children: result.children,
1148                });
1149
1150                total_offset_main += child.offset_main + child.margin.main(dir) + result.size.main(dir);
1151            };
1152
1153            if dir.is_reverse() {
1154                line.items.iter_mut().rev().for_each(layout_item);
1155            } else {
1156                line.items.iter_mut().for_each(layout_item);
1157            }
1158
1159            total_offset_cross += line_offset_cross + line.cross_size;
1160
1161            if dir.is_reverse() {
1162                children.reverse();
1163            }
1164
1165            lines.push(children);
1166        };
1167
1168        if is_wrap_reverse {
1169            flex_lines.iter_mut().rev().for_each(layout_line);
1170        } else {
1171            flex_lines.iter_mut().for_each(layout_line);
1172        }
1173
1174        if is_wrap_reverse {
1175            lines.into_iter().rev().flat_map(|x| x).collect()
1176        } else {
1177            lines.into_iter().flat_map(|x| x).collect()
1178        }
1179    };
1180
1181    // Before returning we perform absolute layout on all absolutely positioned children
1182    let mut absolute_children: Vec<layout::Node> = node
1183        .children
1184        .iter()
1185        .filter(|child| child.position_type == PositionType::Absolute)
1186        .map(|child| {
1187            let container_width = container_size.width.to_number();
1188            let container_height = container_size.height.to_number();
1189
1190            let start = child.position.start.resolve(container_width) + child.margin.start.resolve(container_width);
1191            let end = child.position.end.resolve(container_width) + child.margin.end.resolve(container_width);
1192            let top = child.position.top.resolve(container_height) + child.margin.top.resolve(container_height);
1193            let bottom =
1194                child.position.bottom.resolve(container_height) + child.margin.bottom.resolve(container_height);
1195
1196            let (start_main, end_main) = if is_row { (start, end) } else { (top, bottom) };
1197            let (start_cross, end_cross) = if is_row { (top, bottom) } else { (start, end) };
1198
1199            let width = child
1200                .size
1201                .width
1202                .resolve(container_width)
1203                .maybe_max(child.min_size.width.resolve(container_width))
1204                .maybe_min(child.max_size.width.resolve(container_width))
1205                .or_else(if start.is_defined() && end.is_defined() {
1206                    container_width - start - end
1207                } else {
1208                    Undefined
1209                });
1210
1211            let height = child
1212                .size
1213                .height
1214                .resolve(container_height)
1215                .maybe_max(child.min_size.height.resolve(container_height))
1216                .maybe_min(child.max_size.height.resolve(container_height))
1217                .or_else(if top.is_defined() && bottom.is_defined() {
1218                    container_height - top - bottom
1219                } else {
1220                    Undefined
1221                });
1222
1223            let result = compute_internal(
1224                child,
1225                Size { width, height },
1226                Size { width: container_width, height: container_height },
1227                container_width,
1228                true,
1229            );
1230
1231            let free_main_space = container_size.main(dir)
1232                - result
1233                    .size
1234                    .main(dir)
1235                    .maybe_max(child.min_main_size(dir).resolve(percent_calc_base_child))
1236                    .maybe_min(child.max_main_size(dir).resolve(percent_calc_base_child));
1237
1238            let free_cross_space = container_size.cross(dir)
1239                - result
1240                    .size
1241                    .cross(dir)
1242                    .maybe_max(child.min_cross_size(dir).resolve(percent_calc_base_child))
1243                    .maybe_min(child.max_cross_size(dir).resolve(percent_calc_base_child));
1244
1245            let offset_main = if start_main.is_defined() {
1246                start_main.or_else(0.0) + border.main_start(dir)
1247            } else if end_main.is_defined() {
1248                free_main_space - end_main.or_else(0.0) - border.main_end(dir)
1249            } else {
1250                match node.justify_content {
1251                    JustifyContent::SpaceBetween | JustifyContent::FlexStart => padding_border.main_start(dir),
1252                    JustifyContent::FlexEnd => free_main_space - padding_border.main_end(dir),
1253                    JustifyContent::SpaceEvenly | JustifyContent::SpaceAround | JustifyContent::Center => {
1254                        free_main_space / 2.0
1255                    }
1256                }
1257            };
1258
1259            let offset_cross = if start_cross.is_defined() {
1260                start_cross.or_else(0.0) + border.cross_start(dir)
1261            } else if end_cross.is_defined() {
1262                free_cross_space - end_cross.or_else(0.0) - border.cross_end(dir)
1263            } else {
1264                match child.align_self(node) {
1265                    AlignSelf::Auto => 0.0, // Should never happen
1266                    AlignSelf::FlexStart => {
1267                        if is_wrap_reverse {
1268                            free_cross_space - padding_border.cross_end(dir)
1269                        } else {
1270                            padding_border.cross_start(dir)
1271                        }
1272                    }
1273                    AlignSelf::FlexEnd => {
1274                        if is_wrap_reverse {
1275                            padding_border.cross_start(dir)
1276                        } else {
1277                            free_cross_space - padding_border.cross_end(dir)
1278                        }
1279                    }
1280                    AlignSelf::Center => free_cross_space / 2.0,
1281                    AlignSelf::Baseline => free_cross_space / 2.0, // Treat as center for now until we have baseline support
1282                    AlignSelf::Stretch => {
1283                        if is_wrap_reverse {
1284                            free_cross_space - padding_border.cross_end(dir)
1285                        } else {
1286                            padding_border.cross_start(dir)
1287                        }
1288                    }
1289                }
1290            };
1291
1292            layout::Node {
1293                order: node.children.iter().position(|n| ref_eq(n, child)).unwrap() as u32,
1294                size: result.size,
1295                location: Point {
1296                    x: if is_row { offset_main } else { offset_cross },
1297                    y: if is_column { offset_main } else { offset_cross },
1298                },
1299                children: result.children,
1300            }
1301        })
1302        .collect();
1303
1304    children.append(&mut absolute_children);
1305
1306    fn hidden_layout(parent: &style::Node, node: &style::Node) -> layout::Node {
1307        layout::Node {
1308            order: parent.children.iter().position(|n| ref_eq(n, node)).unwrap() as u32,
1309            size: Size { width: 0.0, height: 0.0 },
1310            location: Point { x: 0.0, y: 0.0 },
1311            children: node.children.iter().map(|child| hidden_layout(node, child)).collect(),
1312        }
1313    }
1314
1315    let mut hidden_children: Vec<layout::Node> = node
1316        .children
1317        .iter()
1318        .filter(|child| child.display == Display::None)
1319        .map(|child| hidden_layout(node, child))
1320        .collect();
1321
1322    children.append(&mut hidden_children);
1323
1324    children.sort_by(|c1, c2| c1.order.cmp(&c2.order));
1325
1326    let result = ComputeResult { size: container_size, children };
1327    node.layout_cache.replace(Some(LayoutCache {
1328        node_size,
1329        parent_size,
1330        percent_calc_base,
1331        perform_layout,
1332        result: result.clone(),
1333    }));
1334    result
1335}