gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 5364Rust 86Markdown 12TOML 91822 Sutichaykuna

⎇ d1d357f2a316aca030e9820a02ef33110c38e4f3 src/algo.rs Rust · 1227 siq'ikuna · 51.7 KB Ñawpa willay Pi imata llamkarqan ch'uya

update readme and box measurte d1d357f2a · Emil Sjölander ·

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