tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 5334Rust 85Markdown 12TOML 91813 Definiciones

⎇ 5fcf209b58c668fa892f2157a8db1a3bcf6ae39f src/algo.rs Rust · 1119 líneas · 49.7 KB Historia Quién tocó qué crudo

random small fixes 5fcf209b5 · Emil Sjölander ·

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