gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 1111HTML 1039Markdown 12TOML 94524 Definiciones

⎇ c1bf9f3d7c170cc97691ebb8bb5805db1c5ead32 src/algo.rs Rust · 1346 líneas · 57.6 KB Historia Quién tocó qué crudo

code cleanup c1bf9f3d7 · Emil Sjölander ·

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