gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 252HTML 238TOML 3CSS 1626 Sutichaykuna

⎇ f3e43252aa7638855abd0de1f972853a5ec4d1a8 src/algo.rs Rust · 1389 siq'ikuna · 58.8 KB Ñawpa willay Pi imata llamkarqan ch'uya

Move to iterators instead of loops to get ready for parrallel layout f3e43252a · Emil Sjölander ·

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