tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 5464Rust 87Markdown 12TOML 91903 Definiciones

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

Account for margin when stretching df0293601 · 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    outer_target_cross_size: f32,
46
47    main_margin_start: f32,
48    main_margin_end: f32,
49    cross_margin_start: f32,
50    cross_margin_end: f32,
51
52    // temporary values for holding offset in the main / cross direction.
53    // offset is the relative position from the item's natural flow position based on
54    // relative position values, alignment, and justification. Does not unclude margin/padding/border.
55    offset_main: f32,
56    offset_cross: f32,
57}
58
59struct ComputeResult {
60    size: FlexSize,
61    children: Vec<layout::Node>,
62}
63
64struct FlexLine<'a> {
65    items: Vec<FlexItem<'a>>,
66    cross_size: f32,
67    offset_cross: f32,
68}
69
70pub fn compute(root: &style::Node) -> layout::Node {
71    let result = compute_internal(
72        root,
73        root.width
74            .resolve(f32::NAN, f32::NAN)
75            .max(root.min_width.resolve(f32::NAN, f32::NAN))
76            .min(root.max_width.resolve(f32::NAN, f32::NAN)),
77        root.height
78            .resolve(f32::NAN, f32::NAN)
79            .max(root.min_height.resolve(f32::NAN, f32::NAN))
80            .min(root.max_height.resolve(f32::NAN, f32::NAN)),
81        f32::NAN,
82        f32::NAN,
83        f32::NAN,
84    );
85
86    round_layout(
87        &layout::Node {
88            width: result.size.width,
89            height: result.size.height,
90            x: 0.0,
91            y: 0.0,
92            children: result.children,
93        },
94        0.0,
95        0.0,
96    )
97}
98
99fn round_layout(layout: &layout::Node, abs_x: f32, abs_y: f32) -> layout::Node {
100    let abs_x = abs_x + layout.x;
101    let abs_y = abs_y + layout.y;
102
103    let rounded_x = layout.x.round();
104    let rounded_y = layout.y.round();
105
106    let rounded_width = (abs_x + layout.width).round() - abs_x.round();
107    let rounded_height = (abs_y + layout.height).round() - abs_y.round();
108
109    let rounded_children = layout.children.iter().map(|child| round_layout(child, abs_x, abs_y)).collect();
110
111    layout::Node {
112        width: rounded_width,
113        height: rounded_height,
114        x: rounded_x,
115        y: rounded_y,
116        children: rounded_children,
117    }
118}
119
120fn compute_internal(
121    node: &style::Node,
122
123    // The width and the height of this node, if Some
124    // the node should be layed out at exactly this size.
125    // If None the node should at most be the size of
126    // available_width / available_height if present.
127    node_width: f32,
128    node_height: f32,
129
130    // This available width and height. This is the
131    // the inner node_width / node_height of the parent and should
132    // not be exceeded by this node unless node_width / node_height
133    // parameters say otherwise.
134    parent_inner_width: f32,
135    parent_inner_height: f32,
136
137    // This will always be the parent width except for the case when
138    // the child is in an absolute context. This value should only
139    // be used for calculated percentage values.
140    percent_calc_base: f32,
141) -> ComputeResult {
142    // Define some general constants we will need for the remainder
143    // of the algorithm.
144
145    let (node_main, node_cross) =
146        if node.flex_direction.is_row() { (node_width, node_height) } else { (node_height, node_width) };
147
148    let (parent_inner_main, parent_inner_cross) = if node.flex_direction.is_row() {
149        (parent_inner_width, parent_inner_height)
150    } else {
151        (parent_inner_height, parent_inner_width)
152    };
153
154    let (margin_main_start, margin_cross_start) = (
155        node.main_margin_start(node.flex_direction).resolve(percent_calc_base, 0.0),
156        node.cross_margin_start(node.flex_direction).resolve(percent_calc_base, 0.0),
157    );
158
159    let (margin_main_end, margin_cross_end) = (
160        node.main_margin_end(node.flex_direction).resolve(percent_calc_base, 0.0),
161        node.cross_margin_end(node.flex_direction).resolve(percent_calc_base, 0.0),
162    );
163
164    let (margin_main, margin_cross) = (margin_main_start + margin_main_end, margin_cross_start + margin_cross_end);
165
166    let (padding_main_start, padding_cross_start) = (
167        node.main_padding_start(node.flex_direction).resolve(percent_calc_base, 0.0),
168        node.cross_padding_start(node.flex_direction).resolve(percent_calc_base, 0.0),
169    );
170
171    let (padding_main_end, padding_cross_end) = (
172        node.main_padding_end(node.flex_direction).resolve(percent_calc_base, 0.0),
173        node.cross_padding_end(node.flex_direction).resolve(percent_calc_base, 0.0),
174    );
175
176    let (padding_main, padding_cross) =
177        (padding_main_start + padding_main_end, padding_cross_start + padding_cross_end);
178
179    let (border_main_start, border_cross_start) = (
180        node.main_border_start(node.flex_direction).resolve(percent_calc_base, 0.0),
181        node.cross_border_start(node.flex_direction).resolve(percent_calc_base, 0.0),
182    );
183
184    let (border_main_end, border_cross_end) = (
185        node.main_border_end(node.flex_direction).resolve(percent_calc_base, 0.0),
186        node.cross_border_end(node.flex_direction).resolve(percent_calc_base, 0.0),
187    );
188
189    let (border_main, border_cross) = (border_main_start + border_main_end, border_cross_start + border_cross_end);
190
191    let (node_inner_main, node_inner_cross) =
192        (node_main - border_main - padding_main, node_cross - border_cross - padding_cross);
193
194    let wrap_reverse = node.flex_wrap == style::FlexWrap::WrapReverse;
195
196    let percent_calc_base_child = node.width.resolve(percent_calc_base, f32::NAN);
197
198    // 9.2. Line Length Determination
199
200    // 1. Generate anonymous flex items as described in §4 Flex Items.
201
202    let mut flex_items: Vec<FlexItem> = node
203        .children
204        .iter()
205        .filter(|child| child.position != style::Position::Absolute)
206        .map(|child| FlexItem {
207            node: child,
208
209            flex_basis: 0.0,
210            inner_flex_basis: 0.0,
211            hypothetical_inner_main_size: 0.0,
212            hypothetical_outer_main_size: 0.0,
213            target_main_size: 0.0,
214            outer_target_main_size: 0.0,
215            violation: 0.0,
216            frozen: false,
217
218            hypothetical_inner_cross_size: 0.0,
219            hypothetical_outer_cross_size: 0.0,
220            target_cross_size: 0.0,
221            outer_target_cross_size: 0.0,
222
223            main_margin_start: 0.0,
224            main_margin_end: 0.0,
225            cross_margin_start: 0.0,
226            cross_margin_end: 0.0,
227
228            offset_main: 0.0,
229            offset_cross: 0.0,
230        }).collect();
231
232    // 2. Determine the available main and cross space for the flex items.
233    //    For each dimension, if that dimension of the flex container’s content box
234    //    is a definite size, use that; if that dimension of the flex container is
235    //    being sized under a min or max-content constraint, the available space in
236    //    that dimension is that constraint; otherwise, subtract the flex container’s
237    //    margin, border, and padding from the space available to the flex container
238    //    in that dimension and use that value. This might result in an infinite value.
239
240    let available_main = {
241        let base = if node_main.is_finite() { node_main } else { parent_inner_main - margin_main };
242        base - padding_main - border_main
243    };
244
245    let available_cross = {
246        let base = if node_cross.is_finite() { node_cross } else { parent_inner_cross - margin_cross };
247        base - padding_cross - border_cross
248    };
249
250    // 3. Determine the flex base size and hypothetical main size of each item:
251    for child in &mut flex_items {
252        // A. If the item has a definite used flex basis, that’s the flex base size.
253
254        let flex_basis = child.node.flex_basis.resolve(percent_calc_base_child, f32::NAN);
255        if flex_basis.is_finite() {
256            child.flex_basis = flex_basis;
257            continue;
258        }
259
260        // B. If the flex item has an intrinsic aspect ratio,
261        //    a used flex basis of content, and a definite cross size,
262        //    then the flex base size is calculated from its inner
263        //    cross size and the flex item’s intrinsic aspect ratio.
264
265        if let Some(ratio) = child.node.aspect_ratio {
266            if node_cross.is_finite() && child.node.flex_basis == style::Dimension::Auto {
267                child.flex_basis = ratio * node_cross;
268                continue;
269            }
270        }
271
272        // C. If the used flex basis is content or depends on its available space,
273        //    and the flex container is being sized under a min-content or max-content
274        //    constraint (e.g. when performing automatic table layout [CSS21]),
275        //    size the item under that constraint. The flex base size is the item’s
276        //    resulting main size.
277
278        // if main_constraint.min.is_finite() || main_constraint.max.is_finite() {
279        //     let size = compute_internal(
280        //         child.node,
281        //         if node.flex_direction.is_row() { main_constraint } else { SizeConstraint::undefined() },
282        //         if node.flex_direction.is_column() { main_constraint } else { SizeConstraint::undefined() },
283        //         percent_calc_base_child,
284        //     ).size;
285        //     child.flex_basis = size.main(node.flex_direction);
286        //     continue;
287        // }
288
289        // D. Otherwise, if the used flex basis is content or depends on its
290        //    available space, the available main size is infinite, and the flex item’s
291        //    inline axis is parallel to the main axis, lay the item out using the rules
292        //    for a box in an orthogonal flow [CSS3-WRITING-MODES]. The flex base size
293        //    is the item’s max-content main size.
294
295        if available_main.is_nan() {
296            let size = compute_internal(
297                child.node,
298                child
299                    .node
300                    .width
301                    .resolve(percent_calc_base_child, f32::NAN)
302                    .max(child.node.min_width.resolve(percent_calc_base_child, f32::NAN))
303                    .min(child.node.max_width.resolve(percent_calc_base_child, f32::NAN)),
304                child
305                    .node
306                    .height
307                    .resolve(percent_calc_base_child, f32::NAN)
308                    .max(child.node.min_height.resolve(percent_calc_base_child, f32::NAN))
309                    .min(child.node.max_height.resolve(percent_calc_base_child, f32::NAN)),
310                if node.flex_direction.is_row() { available_main } else { available_cross },
311                if node.flex_direction.is_row() { available_cross } else { available_main },
312                percent_calc_base_child,
313            ).size;
314            child.flex_basis = size.main(node.flex_direction);
315            continue;
316        }
317
318        // E. Otherwise, size the item into the available space using its used flex basis
319        //    in place of its main size, treating a value of content as max-content.
320        //    If a cross size is needed to determine the main size (e.g. when the
321        //    flex item’s main size is in its block axis) and the flex item’s cross size
322        //    is auto and not definite, in this calculation use fit-content as the
323        //    flex item’s cross size. The flex base size is the item’s resulting main size.
324
325        let size = compute_internal(
326            child.node,
327            child
328                .node
329                .width
330                .resolve(percent_calc_base_child, f32::NAN)
331                .max(child.node.min_width.resolve(percent_calc_base_child, f32::NAN))
332                .min(child.node.max_width.resolve(percent_calc_base_child, f32::NAN)),
333            child
334                .node
335                .height
336                .resolve(percent_calc_base_child, f32::NAN)
337                .max(child.node.min_height.resolve(percent_calc_base_child, f32::NAN))
338                .min(child.node.max_height.resolve(percent_calc_base_child, f32::NAN)),
339            if node.flex_direction.is_row() { available_main } else { available_cross },
340            if node.flex_direction.is_row() { available_cross } else { available_main },
341            percent_calc_base_child,
342        ).size;
343        child.flex_basis = size.main(node.flex_direction);
344    }
345
346    // The hypothetical main size is the item’s flex base size clamped according to its
347    // used min and max main sizes (and flooring the content box size at zero).
348
349    for child in &mut flex_items {
350        let padding_start = child.node.main_padding_start(node.flex_direction).resolve(percent_calc_base_child, 0.0);
351        let padding_end = child.node.main_padding_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
352        let border_start = child.node.main_border_start(node.flex_direction).resolve(percent_calc_base_child, 0.0);
353        let border_end = child.node.main_border_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
354        child.inner_flex_basis = child.flex_basis - (padding_start + padding_end + border_start + border_end);
355
356        child.hypothetical_inner_main_size = child
357            .flex_basis
358            .max(child.node.min_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN))
359            .min(child.node.max_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX))
360            .max(0.0);
361
362        child.hypothetical_outer_main_size = child.hypothetical_inner_main_size
363            + child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
364            + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
365    }
366
367    // 9.3. Main Size Determination
368
369    // 5. Collect flex items into flex lines:
370    //    - If the flex container is single-line, collect all the flex items into
371    //      a single flex line.
372    //    - Otherwise, starting from the first uncollected item, collect consecutive
373    //      items one by one until the first time that the next collected item would
374    //      not fit into the flex container’s inner main size (or until a forced break
375    //      is encountered, see §10 Fragmenting Flex Layout). If the very first
376    //      uncollected item wouldn’t fit, collect just it into the line.
377    //
378    //      For this step, the size of a flex item is its outer hypothetical main size. (Note: This can be negative.)
379    //      Repeat until all flex items have been collected into flex lines
380    //
381    //      Note that the "collect as many" line will collect zero-sized flex items onto
382    //      the end of the previous line even if the last non-zero item exactly "filled up" the line.
383
384    let mut flex_lines = {
385        let mut lines: Vec<FlexLine> = vec![];
386        let mut line_length = 0.0;
387
388        if node.flex_wrap == style::FlexWrap::NoWrap {
389            lines.push(FlexLine { items: flex_items, cross_size: 0.0, offset_cross: 0.0 });
390        } else {
391            let mut line = FlexLine { items: vec![], cross_size: 0.0, offset_cross: 0.0 };
392
393            for child in flex_items {
394                line_length += child.hypothetical_outer_main_size;
395
396                if line_length > available_main && line.items.len() > 0 {
397                    line_length = child.hypothetical_outer_main_size;
398                    lines.push(line);
399                    line = FlexLine { items: vec![], cross_size: 0.0, offset_cross: 0.0 };
400                }
401
402                line.items.push(child);
403            }
404
405            lines.push(line);
406        }
407
408        lines
409    };
410
411    // 6. Resolve the flexible lengths of all the flex items to find their used main size.
412    //    See §9.7 Resolving Flexible Lengths.
413    //
414    // 9.7. Resolving Flexible Lengths
415
416    for line in &mut flex_lines {
417        // 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
418        //    items on the line. If the sum is less than the flex container’s inner main size,
419        //    use the flex grow factor for the rest of this algorithm; otherwise, use the
420        //    flex shrink factor.
421
422        let used_flex_factor: f32 = line.items.iter().map(|child| child.hypothetical_outer_main_size).sum();
423        let growing = used_flex_factor < node_inner_main;
424        let shrinking = !growing;
425
426        // 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
427        //    - Any item that has a flex factor of zero
428        //    - If using the flex grow factor: any item that has a flex base size
429        //      greater than its hypothetical main size
430        //    - If using the flex shrink factor: any item that has a flex base size
431        //      smaller than its hypothetical main size
432
433        for child in line.items.iter_mut() {
434            child.target_main_size = child.hypothetical_inner_main_size;
435            child.outer_target_main_size = child.target_main_size
436                + child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
437                + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
438
439            if (child.node.flex_grow == 0.0 && child.node.flex_shrink == 0.0)
440                || (growing && child.flex_basis > child.hypothetical_inner_main_size)
441                || (shrinking && child.flex_basis < child.hypothetical_inner_main_size)
442            {
443                child.frozen = true;
444            }
445        }
446
447        // 3. Calculate initial free space. Sum the outer sizes of all items on the line,
448        //    and subtract this from the flex container’s inner main size. For frozen items,
449        //    use their outer target main size; for other items, use their outer flex base size.
450
451        let used_space: f32 = line
452            .items
453            .iter()
454            .map(|child| {
455                child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
456                    + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0)
457                    + if child.frozen { child.target_main_size } else { child.flex_basis }
458            }).sum();
459
460        let initial_free_space = node_inner_main - used_space;
461
462        // 4. Loop
463
464        loop {
465            // a. Check for flexible items. If all the flex items on the line are frozen,
466            //    free space has been distributed; exit this loop.
467
468            let mut frozen: Vec<&mut FlexItem> = vec![];
469            let mut unfrozen: Vec<&mut FlexItem> = vec![];
470
471            for child in line.items.iter_mut() {
472                if child.frozen {
473                    frozen.push(child);
474                } else {
475                    unfrozen.push(child);
476                }
477            }
478
479            if unfrozen.len() == 0 {
480                break;
481            }
482
483            // b. Calculate the remaining free space as for initial free space, above.
484            //    If the sum of the unfrozen flex items’ flex factors is less than one,
485            //    multiply the initial free space by this sum. If the magnitude of this
486            //    value is less than the magnitude of the remaining free space, use this
487            //    as the remaining free space.
488
489            let used_space: f32 = Iterator::chain(frozen.iter(), unfrozen.iter())
490                .map(|child| {
491                    child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
492                        + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0)
493                        + if child.frozen { child.target_main_size } else { child.flex_basis }
494                }).sum();
495
496            let sum_flex_grow: f32 = unfrozen.iter().map(|item| item.node.flex_grow).sum();
497            let sum_flex_shrink: f32 = unfrozen.iter().map(|item| item.node.flex_shrink).sum();
498
499            let free_space = if growing && sum_flex_grow < 1.0 {
500                (initial_free_space * sum_flex_grow).min(node_inner_main - used_space)
501            } else if shrinking && sum_flex_shrink < 1.0 {
502                (initial_free_space * sum_flex_shrink).max(node_inner_main - used_space)
503            } else {
504                node_inner_main - used_space
505            };
506
507            // c. Distribute free space proportional to the flex factors.
508            //    - If the remaining free space is zero
509            //        Do Nothing
510            //    - If using the flex grow factor
511            //        Find the ratio of the item’s flex grow factor to the sum of the
512            //        flex grow factors of all unfrozen items on the line. Set the item’s
513            //        target main size to its flex base size plus a fraction of the remaining
514            //        free space proportional to the ratio.
515            //    - If using the flex shrink factor
516            //        For every unfrozen item on the line, multiply its flex shrink factor by
517            //        its inner flex base size, and note this as its scaled flex shrink factor.
518            //        Find the ratio of the item’s scaled flex shrink factor to the sum of the
519            //        scaled flex shrink factors of all unfrozen items on the line. Set the item’s
520            //        target main size to its flex base size minus a fraction of the absolute value
521            //        of the remaining free space proportional to the ratio. Note this may result
522            //        in a negative inner main size; it will be corrected in the next step.
523            //    - Otherwise
524            //        Do Nothing
525
526            if free_space > 0.0 && growing && sum_flex_grow > 0.0 {
527                for child in &mut unfrozen {
528                    child.target_main_size = child.flex_basis + free_space * (child.node.flex_grow / sum_flex_grow);
529                }
530            } else if free_space < 0.0 && shrinking && sum_flex_shrink > 0.0 {
531                let sum_scaled_shrink_factor: f32 =
532                    unfrozen.iter().map(|child| child.inner_flex_basis * child.node.flex_shrink).sum();
533
534                for child in &mut unfrozen {
535                    let scaled_shrink_factor = child.inner_flex_basis * child.node.flex_shrink;
536                    child.target_main_size =
537                        child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor);
538                }
539            }
540
541            // d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
542            //    used min and max main sizes and floor its content-box size at zero. If the
543            //    item’s target main size was made smaller by this, it’s a max violation.
544            //    If the item’s target main size was made larger by this, it’s a min violation.
545
546            let mut total_violation = 0.0;
547            for child in &mut unfrozen {
548                let max = child.node.max_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX);
549                let min =
550                    child.node.min_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN).max(0.0);
551
552                let clamped = if child.target_main_size > max {
553                    max
554                } else if child.target_main_size < min {
555                    min
556                } else {
557                    child.target_main_size
558                };
559
560                child.violation = clamped - child.target_main_size;
561                total_violation += child.violation;
562                child.target_main_size = clamped;
563                child.outer_target_main_size = child.target_main_size
564                    + child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
565                    + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
566            }
567
568            // e. Freeze over-flexed items. The total violation is the sum of the adjustments
569            //    from the previous step ∑(clamped size - unclamped size). If the total violation is:
570            //    - Zero
571            //        Freeze all items.
572            //    - Positive
573            //        Freeze all the items with min violations.
574            //    - Negative
575            //        Freeze all the items with max violations.
576
577            if total_violation > 0.0 {
578                for child in &mut unfrozen {
579                    child.frozen = child.violation > 0.0;
580                }
581            } else if total_violation < 0.0 {
582                for child in &mut unfrozen {
583                    child.frozen = child.violation < 0.0;
584                }
585            } else {
586                for child in &mut unfrozen {
587                    child.frozen = true;
588                }
589            }
590
591            // f. Return to the start of this loop.
592        }
593    }
594
595    // Not part of the spec from what i can see but seems correct
596    let container_main_size = if node_main.is_finite() {
597        node_main
598    } else {
599        let mut longest_line = f32::MIN;
600
601        for line in &flex_lines {
602            let length: f32 = line.items.iter().map(|item| item.outer_target_main_size).sum();
603            longest_line = if length > longest_line { length } else { longest_line };
604        }
605
606        let size = longest_line + padding_main + border_main;
607        if available_main.is_finite() && flex_lines.len() > 1 && size < available_main {
608            available_main
609        } else {
610            size
611        }
612    };
613
614    let inner_container_main_size = container_main_size - padding_main - border_main;
615
616    // 9.4. Cross Size Determination
617
618    // 7. Determine the hypothetical cross size of each item by performing layout with the
619    //    used main size and the available space, treating auto as fit-content.
620
621    for line in &mut flex_lines {
622        for child in &mut line.items {
623            let child_cross = child
624                .node
625                .cross_size(node.flex_direction)
626                .resolve(percent_calc_base_child, f32::NAN)
627                .max(child.node.min_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::NAN))
628                .min(child.node.max_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::NAN));
629
630            let size = compute_internal(
631                child.node,
632                if node.flex_direction.is_row() { child.target_main_size } else { child_cross },
633                if node.flex_direction.is_row() { child_cross } else { child.target_main_size },
634                if node.flex_direction.is_row() { container_main_size } else { available_cross },
635                if node.flex_direction.is_row() { available_cross } else { container_main_size },
636                percent_calc_base_child,
637            ).size;
638
639            child.hypothetical_inner_cross_size = size
640                .cross(node.flex_direction)
641                .max(child.node.min_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN))
642                .min(child.node.max_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX))
643                .max(0.0);
644
645            child.hypothetical_outer_cross_size = child.hypothetical_inner_cross_size
646                + child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
647                + child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
648        }
649    }
650
651    // 8. Calculate the cross size of each flex line.
652    //    If the flex container is single-line and has a definite cross size, the cross size
653    //    of the flex line is the flex container’s inner cross size. Otherwise, for each flex line:
654    //
655    //    1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose
656    //       align-self is baseline, and whose cross-axis margins are both non-auto. Find the
657    //       largest of the distances between each item’s baseline and its hypothetical outer
658    //       cross-start edge, and the largest of the distances between each item’s baseline
659    //       and its hypothetical outer cross-end edge, and sum these two values.
660    //    2. Among all the items not collected by the previous step, find the largest
661    //       outer hypothetical cross size.
662    //    3. The used cross-size of the flex line is the largest of the numbers found in the
663    //       previous two steps and zero.
664    //
665    //    If the flex container is single-line, then clamp the line’s cross-size to be within
666    //    the container’s computed min and max cross sizes. Note that if CSS 2.1’s definition
667    //    of min/max-width/height applied more generally, this behavior would fall out automatically.
668
669    if flex_lines.len() == 1 && node_cross.is_finite() {
670        flex_lines[0].cross_size = node_cross - padding_cross - border_cross;
671    } else {
672        for line in &mut flex_lines {
673            // TODO handle baseline (1)
674
675            line.cross_size =
676                line.items.iter().map(|child| child.hypothetical_outer_cross_size).fold(0.0, |acc, x| acc.max(x));
677        }
678    }
679
680    // 9. Handle 'align-content: stretch'. If the flex container has a definite cross size,
681    //    align-content is stretch, and the sum of the flex lines' cross sizes is less than
682    //    the flex container’s inner cross size, increase the cross size of each flex line
683    //    by equal amounts such that the sum of their cross sizes exactly equals the
684    //    flex container’s inner cross size.
685
686    if node.align_content == style::AlignContent::Stretch && node_cross.is_finite() {
687        let total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
688        let inner_cross = node_cross - padding_cross - border_cross;
689
690        if total_cross < inner_cross {
691            let remaining = inner_cross - total_cross;
692            let addition = remaining / flex_lines.len() as f32;
693
694            for line in &mut flex_lines {
695                line.cross_size += addition;
696            }
697        }
698    }
699
700    // 10. Collapse visibility:collapse items. If any flex items have visibility: collapse,
701    //     note the cross size of the line they’re in as the item’s strut size, and restart
702    //     layout from the beginning.
703    //
704    //     In this second layout round, when collecting items into lines, treat the collapsed
705    //     items as having zero main size. For the rest of the algorithm following that step,
706    //     ignore the collapsed items entirely (as if they were display:none) except that after
707    //     calculating the cross size of the lines, if any line’s cross size is less than the
708    //     largest strut size among all the collapsed items in the line, set its cross size to
709    //     that strut size.
710    //
711    //     Skip this step in the second layout round.
712
713    // TODO implement once (if ever) we support visibility:collapse
714
715    // 11. Determine the used cross size of each flex item. If a flex item has align-self: stretch,
716    //     its computed cross size property is auto, and neither of its cross-axis margins are auto,
717    //     the used outer cross size is the used cross size of its flex line, clamped according to
718    //     the item’s used min and max cross sizes. Otherwise, the used cross size is the item’s
719    //     hypothetical cross size.
720    //
721    //     If the flex item has align-self: stretch, redo layout for its contents, treating this
722    //     used size as its definite cross size so that percentage-sized children can be resolved.
723    //
724    //     Note that this step does not affect the main size of the flex item, even if it has an
725    //     intrinsic aspect ratio.
726
727    for line in &mut flex_lines {
728        for child in &mut line.items {
729            let is_stretch = child.node.align_self(node) == style::AlignSelf::Stretch;
730
731            child.target_cross_size = if is_stretch
732                && child.node.cross_margin_start(node.flex_direction) != style::Dimension::Auto
733                && child.node.cross_margin_end(node.flex_direction) != style::Dimension::Auto
734                && child.node.cross_size(node.flex_direction) == style::Dimension::Auto
735            {
736                (line.cross_size
737                    - child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
738                    - child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0))
739                    .max(child.node.min_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN))
740                    .min(child.node.max_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX))
741            } else {
742                child.hypothetical_inner_cross_size
743            };
744
745            child.outer_target_cross_size = child.target_cross_size
746                + child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
747                + child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
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.outer_target_cross_size < line.cross_size {
849                let free_space = line.cross_size - child.outer_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}