tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 501HTML 254C 19JavaScript 81414 Sutichaykuna

⎇ 285afdb9275c769f3f13f34616a2836f0869a73a src/algo.rs Rust · 1189 siq'ikuna · 53.8 KB Ñawpa willay Pi imata llamkarqan ch'uya

fix flex hypothetical_inner_main_size calc 285afdb92 · 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;
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    // TODO - this does not follow spec. See commented out code below
251    // 3. Determine the flex base size and hypothetical main size of each item:
252    for child in &mut flex_items {
253        // A. If the item has a definite used flex basis, that’s the flex base size.
254
255        let flex_basis = child.node.flex_basis.resolve(percent_calc_base_child, f32::NAN);
256        if flex_basis.is_finite() {
257            child.flex_basis = flex_basis;
258            continue;
259        };
260
261        // B. If the flex item has an intrinsic aspect ratio,
262        //    a used flex basis of content, and a definite cross size,
263        //    then the flex base size is calculated from its inner
264        //    cross size and the flex item’s intrinsic aspect ratio.
265
266        if let Some(ratio) = child.node.aspect_ratio {
267            if node_cross.is_finite() && child.node.flex_basis == style::Dimension::Auto {
268                child.flex_basis = ratio * node_cross;
269                continue;
270            }
271        }
272
273        // C. If the used flex basis is content or depends on its available space,
274        //    and the flex container is being sized under a min-content or max-content
275        //    constraint (e.g. when performing automatic table layout [CSS21]),
276        //    size the item under that constraint. The flex base size is the item’s
277        //    resulting main size.
278
279        // if main_constraint.min.is_finite() || main_constraint.max.is_finite() {
280        //     let size = compute_internal(
281        //         child.node,
282        //         if node.flex_direction.is_row() { main_constraint } else { SizeConstraint::undefined() },
283        //         if node.flex_direction.is_column() { main_constraint } else { SizeConstraint::undefined() },
284        //         percent_calc_base_child,
285        //     ).size;
286        //     child.flex_basis = size.main(node.flex_direction);
287        //     continue;
288        // }
289
290        // D. Otherwise, if the used flex basis is content or depends on its
291        //    available space, the available main size is infinite, and the flex item’s
292        //    inline axis is parallel to the main axis, lay the item out using the rules
293        //    for a box in an orthogonal flow [CSS3-WRITING-MODES]. The flex base size
294        //    is the item’s max-content main size.
295
296        // if available_main.is_nan() {
297        //     let size = compute_internal(
298        //         child.node,
299        //         child
300        //             .node
301        //             .width
302        //             .resolve(percent_calc_base_child, f32::NAN)
303        //             .max(child.node.min_width.resolve(percent_calc_base_child, f32::NAN))
304        //             .min(child.node.max_width.resolve(percent_calc_base_child, f32::NAN)),
305        //         child
306        //             .node
307        //             .height
308        //             .resolve(percent_calc_base_child, f32::NAN)
309        //             .max(child.node.min_height.resolve(percent_calc_base_child, f32::NAN))
310        //             .min(child.node.max_height.resolve(percent_calc_base_child, f32::NAN)),
311        //         if node.flex_direction.is_row() { available_main } else { available_cross },
312        //         if node.flex_direction.is_row() { available_cross } else { available_main },
313        //         percent_calc_base_child,
314        //     ).size;
315        //     child.flex_basis = size.main(node.flex_direction);
316        //     continue;
317        // }
318
319        // E. Otherwise, size the item into the available space using its used flex basis
320        //    in place of its main size, treating a value of content as max-content.
321        //    If a cross size is needed to determine the main size (e.g. when the
322        //    flex item’s main size is in its block axis) and the flex item’s cross size
323        //    is auto and not definite, in this calculation use fit-content as the
324        //    flex item’s cross size. The flex base size is the item’s resulting main size.
325
326        let size = compute_internal(
327            child.node,
328            child
329                .node
330                .width
331                .resolve(percent_calc_base_child, f32::NAN)
332                .max(child.node.min_width.resolve(percent_calc_base_child, f32::NAN))
333                .min(child.node.max_width.resolve(percent_calc_base_child, f32::NAN)),
334            child
335                .node
336                .height
337                .resolve(percent_calc_base_child, f32::NAN)
338                .max(child.node.min_height.resolve(percent_calc_base_child, f32::NAN))
339                .min(child.node.max_height.resolve(percent_calc_base_child, f32::NAN)),
340            if node.flex_direction.is_row() { available_main } else { available_cross },
341            if node.flex_direction.is_row() { available_cross } else { available_main },
342            percent_calc_base_child,
343        ).size;
344        child.flex_basis = size.main(node.flex_direction);
345    }
346
347    // The hypothetical main size is the item’s flex base size clamped according to its
348    // used min and max main sizes (and flooring the content box size at zero).
349
350    for child in &mut flex_items {
351        let padding_start = child.node.main_padding_start(node.flex_direction).resolve(percent_calc_base_child, 0.0);
352        let padding_end = child.node.main_padding_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
353        let border_start = child.node.main_border_start(node.flex_direction).resolve(percent_calc_base_child, 0.0);
354        let border_end = child.node.main_border_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
355        child.inner_flex_basis = child.flex_basis - (padding_start + padding_end + border_start + border_end);
356
357        // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
358        // The following logic was developed not from the spec but by trail and error looking into how
359        // webkit handled various scenarios. Can probably be solved better by passing in
360        // min-content max-content constraints fromt the top
361        let min_main = if node.flex_direction.is_row() {
362            compute_internal(
363                child.node,
364                f32::NAN,
365                f32::NAN,
366                if node.flex_direction.is_row() { available_main } else { available_cross },
367                if node.flex_direction.is_row() { available_cross } else { available_main },
368                percent_calc_base_child,
369            ).size
370            .width
371            .min(child.node.width.resolve(percent_calc_base_child, f32::NAN))
372            .max(child.node.min_width.resolve(percent_calc_base_child, f32::MIN))
373        } else {
374            child.node.min_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN)
375        };
376
377        child.hypothetical_inner_main_size = child
378            .flex_basis
379            .max(min_main)
380            .min(child.node.max_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX))
381            .max(0.0);
382
383        child.hypothetical_outer_main_size = child.hypothetical_inner_main_size
384            + child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
385            + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
386    }
387
388    // 9.3. Main Size Determination
389
390    // 5. Collect flex items into flex lines:
391    //    - If the flex container is single-line, collect all the flex items into
392    //      a single flex line.
393    //    - Otherwise, starting from the first uncollected item, collect consecutive
394    //      items one by one until the first time that the next collected item would
395    //      not fit into the flex container’s inner main size (or until a forced break
396    //      is encountered, see §10 Fragmenting Flex Layout). If the very first
397    //      uncollected item wouldn’t fit, collect just it into the line.
398    //
399    //      For this step, the size of a flex item is its outer hypothetical main size. (Note: This can be negative.)
400    //      Repeat until all flex items have been collected into flex lines
401    //
402    //      Note that the "collect as many" line will collect zero-sized flex items onto
403    //      the end of the previous line even if the last non-zero item exactly "filled up" the line.
404
405    let mut flex_lines = {
406        let mut lines: Vec<FlexLine> = vec![];
407        let mut line_length = 0.0;
408
409        if node.flex_wrap == style::FlexWrap::NoWrap {
410            lines.push(FlexLine { items: flex_items, cross_size: 0.0, offset_cross: 0.0 });
411        } else {
412            let mut line = FlexLine { items: vec![], cross_size: 0.0, offset_cross: 0.0 };
413
414            for child in flex_items {
415                line_length += child.hypothetical_outer_main_size;
416
417                if line_length > available_main && line.items.len() > 0 {
418                    line_length = child.hypothetical_outer_main_size;
419                    lines.push(line);
420                    line = FlexLine { items: vec![], cross_size: 0.0, offset_cross: 0.0 };
421                }
422
423                line.items.push(child);
424            }
425
426            lines.push(line);
427        }
428
429        lines
430    };
431
432    // 6. Resolve the flexible lengths of all the flex items to find their used main size.
433    //    See §9.7 Resolving Flexible Lengths.
434    //
435    // 9.7. Resolving Flexible Lengths
436
437    for line in &mut flex_lines {
438        // 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
439        //    items on the line. If the sum is less than the flex container’s inner main size,
440        //    use the flex grow factor for the rest of this algorithm; otherwise, use the
441        //    flex shrink factor.
442
443        let used_flex_factor: f32 = line.items.iter().map(|child| child.hypothetical_outer_main_size).sum();
444        let growing = used_flex_factor < node_inner_main;
445        let shrinking = !growing;
446
447        // 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
448        //    - Any item that has a flex factor of zero
449        //    - If using the flex grow factor: any item that has a flex base size
450        //      greater than its hypothetical main size
451        //    - If using the flex shrink factor: any item that has a flex base size
452        //      smaller than its hypothetical main size
453
454        for child in line.items.iter_mut() {
455            // TODO - This is not found by reading the spec. Maybe this can be done in some other place
456            // instead. This was found by trail and error fixing tests to align with webkit output.
457            if node_inner_main.is_nan() && node.flex_direction.is_row() {
458                child.target_main_size = compute_internal(
459                    child.node,
460                    child
461                        .node
462                        .width
463                        .resolve(percent_calc_base_child, f32::NAN)
464                        .max(child.node.min_width.resolve(percent_calc_base_child, f32::NAN))
465                        .min(child.node.max_width.resolve(percent_calc_base_child, f32::NAN)),
466                    child
467                        .node
468                        .height
469                        .resolve(percent_calc_base_child, f32::NAN)
470                        .max(child.node.min_height.resolve(percent_calc_base_child, f32::NAN))
471                        .min(child.node.max_height.resolve(percent_calc_base_child, f32::NAN)),
472                    if node.flex_direction.is_row() { available_main } else { available_cross },
473                    if node.flex_direction.is_row() { available_cross } else { available_main },
474                    percent_calc_base_child,
475                ).size
476                .main(node.flex_direction);
477            } else {
478                child.target_main_size = child.hypothetical_inner_main_size;
479            }
480
481            // TODO this should really only be set inside the if-statement below but
482            // that casues the target_main_size to never be set for some items
483
484            child.outer_target_main_size = child.target_main_size
485                + child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
486                + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
487
488            if (child.node.flex_grow == 0.0 && child.node.flex_shrink == 0.0)
489                || (growing && child.flex_basis > child.hypothetical_inner_main_size)
490                || (shrinking && child.flex_basis < child.hypothetical_inner_main_size)
491            {
492                child.frozen = true;
493            }
494        }
495
496        // 3. Calculate initial free space. Sum the outer sizes of all items on the line,
497        //    and subtract this from the flex container’s inner main size. For frozen items,
498        //    use their outer target main size; for other items, use their outer flex base size.
499
500        let used_space: f32 = line
501            .items
502            .iter()
503            .map(|child| {
504                child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
505                    + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0)
506                    + if child.frozen { child.target_main_size } else { child.flex_basis }
507            }).sum();
508
509        let initial_free_space = node_inner_main - used_space;
510
511        // 4. Loop
512
513        loop {
514            // a. Check for flexible items. If all the flex items on the line are frozen,
515            //    free space has been distributed; exit this loop.
516
517            let mut frozen: Vec<&mut FlexItem> = vec![];
518            let mut unfrozen: Vec<&mut FlexItem> = vec![];
519
520            for child in line.items.iter_mut() {
521                if child.frozen {
522                    frozen.push(child);
523                } else {
524                    unfrozen.push(child);
525                }
526            }
527
528            if unfrozen.len() == 0 {
529                break;
530            }
531
532            // b. Calculate the remaining free space as for initial free space, above.
533            //    If the sum of the unfrozen flex items’ flex factors is less than one,
534            //    multiply the initial free space by this sum. If the magnitude of this
535            //    value is less than the magnitude of the remaining free space, use this
536            //    as the remaining free space.
537
538            let used_space: f32 = Iterator::chain(frozen.iter(), unfrozen.iter())
539                .map(|child| {
540                    child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
541                        + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0)
542                        + if child.frozen { child.target_main_size } else { child.flex_basis }
543                }).sum();
544
545            let sum_flex_grow: f32 = unfrozen.iter().map(|item| item.node.flex_grow).sum();
546            let sum_flex_shrink: f32 = unfrozen.iter().map(|item| item.node.flex_shrink).sum();
547
548            let free_space = if growing && sum_flex_grow < 1.0 {
549                (initial_free_space * sum_flex_grow).min(node_inner_main - used_space)
550            } else if shrinking && sum_flex_shrink < 1.0 {
551                (initial_free_space * sum_flex_shrink).max(node_inner_main - used_space)
552            } else {
553                node_inner_main - used_space
554            };
555
556            // c. Distribute free space proportional to the flex factors.
557            //    - If the remaining free space is zero
558            //        Do Nothing
559            //    - If using the flex grow factor
560            //        Find the ratio of the item’s flex grow factor to the sum of the
561            //        flex grow factors of all unfrozen items on the line. Set the item’s
562            //        target main size to its flex base size plus a fraction of the remaining
563            //        free space proportional to the ratio.
564            //    - If using the flex shrink factor
565            //        For every unfrozen item on the line, multiply its flex shrink factor by
566            //        its inner flex base size, and note this as its scaled flex shrink factor.
567            //        Find the ratio of the item’s scaled flex shrink factor to the sum of the
568            //        scaled flex shrink factors of all unfrozen items on the line. Set the item’s
569            //        target main size to its flex base size minus a fraction of the absolute value
570            //        of the remaining free space proportional to the ratio. Note this may result
571            //        in a negative inner main size; it will be corrected in the next step.
572            //    - Otherwise
573            //        Do Nothing
574
575            if free_space.is_normal() {
576                if growing && sum_flex_grow > 0.0 {
577                    for child in &mut unfrozen {
578                        child.target_main_size = child.flex_basis + free_space * (child.node.flex_grow / sum_flex_grow);
579                    }
580                } else if shrinking && sum_flex_shrink > 0.0 {
581                    let sum_scaled_shrink_factor: f32 =
582                        unfrozen.iter().map(|child| child.inner_flex_basis * child.node.flex_shrink).sum();
583
584                    for child in &mut unfrozen {
585                        let scaled_shrink_factor = child.inner_flex_basis * child.node.flex_shrink;
586                        child.target_main_size =
587                            child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor);
588                    }
589                }
590            }
591
592            // d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
593            //    used min and max main sizes and floor its content-box size at zero. If the
594            //    item’s target main size was made smaller by this, it’s a max violation.
595            //    If the item’s target main size was made larger by this, it’s a min violation.
596
597            let mut total_violation = 0.0;
598            for child in &mut unfrozen {
599                // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
600                // The following logic was developed not from the spec but by trail and error looking into how
601                // webkit handled various scenarios. Can probably be solved better by passing in
602                // min-content max-content constraints fromt the top
603                let min_main = if node.flex_direction.is_row() {
604                    compute_internal(
605                        child.node,
606                        f32::NAN,
607                        f32::NAN,
608                        if node.flex_direction.is_row() { available_main } else { available_cross },
609                        if node.flex_direction.is_row() { available_cross } else { available_main },
610                        percent_calc_base_child,
611                    ).size
612                    .width
613                    .min(child.node.width.resolve(percent_calc_base_child, f32::NAN))
614                    .max(child.node.min_width.resolve(percent_calc_base_child, f32::MIN))
615                } else {
616                    child.node.min_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN)
617                };
618
619                let max_main = child.node.max_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX);
620
621                let clamped = child.target_main_size.min(max_main).max(min_main);
622                child.violation = clamped - child.target_main_size;
623                total_violation += child.violation;
624                child.target_main_size = clamped;
625                child.outer_target_main_size = child.target_main_size
626                    + child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
627                    + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
628            }
629
630            // e. Freeze over-flexed items. The total violation is the sum of the adjustments
631            //    from the previous step ∑(clamped size - unclamped size). If the total violation is:
632            //    - Zero
633            //        Freeze all items.
634            //    - Positive
635            //        Freeze all the items with min violations.
636            //    - Negative
637            //        Freeze all the items with max violations.
638
639            if !total_violation.is_normal() {
640                for child in &mut unfrozen {
641                    child.frozen = true;
642                }
643            } else if total_violation > 0.0 {
644                for child in &mut unfrozen {
645                    child.frozen = child.violation > 0.0;
646                }
647            } else if total_violation < 0.0 {
648                for child in &mut unfrozen {
649                    child.frozen = child.violation < 0.0;
650                }
651            }
652
653            // f. Return to the start of this loop.
654        }
655    }
656
657    // Not part of the spec from what i can see but seems correct
658    let container_main_size = if node_main.is_finite() {
659        node_main
660    } else {
661        let mut longest_line = f32::MIN;
662
663        for line in &flex_lines {
664            let length: f32 = line.items.iter().map(|item| item.outer_target_main_size).sum();
665            longest_line = if length > longest_line { length } else { longest_line };
666        }
667
668        let size = longest_line + padding_main + border_main;
669        if available_main.is_finite() && flex_lines.len() > 1 && size < available_main {
670            available_main
671        } else {
672            size
673        }
674    };
675
676    let inner_container_main_size = container_main_size - padding_main - border_main;
677
678    // 9.4. Cross Size Determination
679
680    // 7. Determine the hypothetical cross size of each item by performing layout with the
681    //    used main size and the available space, treating auto as fit-content.
682
683    for line in &mut flex_lines {
684        for child in &mut line.items {
685            let child_cross = child
686                .node
687                .cross_size(node.flex_direction)
688                .resolve(percent_calc_base_child, f32::NAN)
689                .max(child.node.min_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::NAN))
690                .min(child.node.max_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::NAN));
691
692            let size = compute_internal(
693                child.node,
694                if node.flex_direction.is_row() { child.target_main_size } else { child_cross },
695                if node.flex_direction.is_row() { child_cross } else { child.target_main_size },
696                if node.flex_direction.is_row() { container_main_size } else { available_cross },
697                if node.flex_direction.is_row() { available_cross } else { container_main_size },
698                percent_calc_base_child,
699            ).size;
700
701            child.hypothetical_inner_cross_size = size
702                .cross(node.flex_direction)
703                .max(child.node.min_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN))
704                .min(child.node.max_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX))
705                .max(0.0);
706
707            child.hypothetical_outer_cross_size = child.hypothetical_inner_cross_size
708                + child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
709                + child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
710        }
711    }
712
713    // 8. Calculate the cross size of each flex line.
714    //    If the flex container is single-line and has a definite cross size, the cross size
715    //    of the flex line is the flex container’s inner cross size. Otherwise, for each flex line:
716    //
717    //    1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose
718    //       align-self is baseline, and whose cross-axis margins are both non-auto. Find the
719    //       largest of the distances between each item’s baseline and its hypothetical outer
720    //       cross-start edge, and the largest of the distances between each item’s baseline
721    //       and its hypothetical outer cross-end edge, and sum these two values.
722    //    2. Among all the items not collected by the previous step, find the largest
723    //       outer hypothetical cross size.
724    //    3. The used cross-size of the flex line is the largest of the numbers found in the
725    //       previous two steps and zero.
726    //
727    //    If the flex container is single-line, then clamp the line’s cross-size to be within
728    //    the container’s computed min and max cross sizes. Note that if CSS 2.1’s definition
729    //    of min/max-width/height applied more generally, this behavior would fall out automatically.
730
731    if flex_lines.len() == 1 && node_cross.is_finite() {
732        flex_lines[0].cross_size = node_cross - padding_cross - border_cross;
733    } else {
734        for line in &mut flex_lines {
735            // TODO handle baseline (1)
736
737            line.cross_size =
738                line.items.iter().map(|child| child.hypothetical_outer_cross_size).fold(0.0, |acc, x| acc.max(x));
739        }
740    }
741
742    // 9. Handle 'align-content: stretch'. If the flex container has a definite cross size,
743    //    align-content is stretch, and the sum of the flex lines' cross sizes is less than
744    //    the flex container’s inner cross size, increase the cross size of each flex line
745    //    by equal amounts such that the sum of their cross sizes exactly equals the
746    //    flex container’s inner cross size.
747
748    if node.align_content == style::AlignContent::Stretch && node_cross.is_finite() {
749        let total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
750        let inner_cross = node_cross - padding_cross - border_cross;
751
752        if total_cross < inner_cross {
753            let remaining = inner_cross - total_cross;
754            let addition = remaining / flex_lines.len() as f32;
755
756            for line in &mut flex_lines {
757                line.cross_size += addition;
758            }
759        }
760    }
761
762    // 10. Collapse visibility:collapse items. If any flex items have visibility: collapse,
763    //     note the cross size of the line they’re in as the item’s strut size, and restart
764    //     layout from the beginning.
765    //
766    //     In this second layout round, when collecting items into lines, treat the collapsed
767    //     items as having zero main size. For the rest of the algorithm following that step,
768    //     ignore the collapsed items entirely (as if they were display:none) except that after
769    //     calculating the cross size of the lines, if any line’s cross size is less than the
770    //     largest strut size among all the collapsed items in the line, set its cross size to
771    //     that strut size.
772    //
773    //     Skip this step in the second layout round.
774
775    // TODO implement once (if ever) we support visibility:collapse
776
777    // 11. Determine the used cross size of each flex item. If a flex item has align-self: stretch,
778    //     its computed cross size property is auto, and neither of its cross-axis margins are auto,
779    //     the used outer cross size is the used cross size of its flex line, clamped according to
780    //     the item’s used min and max cross sizes. Otherwise, the used cross size is the item’s
781    //     hypothetical cross size.
782    //
783    //     If the flex item has align-self: stretch, redo layout for its contents, treating this
784    //     used size as its definite cross size so that percentage-sized children can be resolved.
785    //
786    //     Note that this step does not affect the main size of the flex item, even if it has an
787    //     intrinsic aspect ratio.
788
789    for line in &mut flex_lines {
790        for child in &mut line.items {
791            let is_stretch = child.node.align_self(node) == style::AlignSelf::Stretch;
792
793            child.target_cross_size = if is_stretch
794                && child.node.cross_margin_start(node.flex_direction) != style::Dimension::Auto
795                && child.node.cross_margin_end(node.flex_direction) != style::Dimension::Auto
796                && child.node.cross_size(node.flex_direction) == style::Dimension::Auto
797            {
798                (line.cross_size
799                    - child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
800                    - child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0))
801                    .max(child.node.min_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN))
802                    .min(child.node.max_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX))
803            } else {
804                child.hypothetical_inner_cross_size
805            };
806
807            child.outer_target_cross_size = child.target_cross_size
808                + child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
809                + child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
810        }
811    }
812
813    // 9.5. Main-Axis Alignment
814
815    // 12. Distribute any remaining free space. For each flex line:
816    //     1. If the remaining free space is positive and at least one main-axis margin on this
817    //        line is auto, distribute the free space equally among these margins. Otherwise,
818    //        set all auto margins to zero.
819    //     2. Align the items along the main-axis per justify-content.
820
821    for line in &mut flex_lines {
822        let used_space: f32 = line.items.iter().map(|child| child.outer_target_main_size).sum();
823        let free_space = inner_container_main_size - used_space;
824
825        // TODO does not make a ton of sense to have this here but we want to have this somewhere.
826        for child in &mut line.items {
827            child.main_margin_start =
828                child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0);
829            child.main_margin_end =
830                child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
831        }
832
833        let mut num_auto_margins = 0;
834
835        for child in &mut line.items {
836            if child.node.main_margin_start(node.flex_direction) == style::Dimension::Auto {
837                num_auto_margins += 1;
838            }
839            if child.node.main_margin_end(node.flex_direction) == style::Dimension::Auto {
840                num_auto_margins += 1;
841            }
842        }
843
844        if free_space > 0.0 && num_auto_margins > 0 {
845            let margin = free_space / num_auto_margins as f32;
846
847            for child in &mut line.items {
848                if child.node.main_margin_start(node.flex_direction) == style::Dimension::Auto {
849                    child.main_margin_start = margin;
850                }
851                if child.node.main_margin_end(node.flex_direction) == style::Dimension::Auto {
852                    child.main_margin_end = margin;
853                }
854            }
855        } else {
856            let num_items = line.items.len();
857            let mut is_first = true;
858
859            for child in &mut line.items {
860                child.offset_main = match node.justify_content {
861                    style::JustifyContent::FlexStart => 0.0,
862                    style::JustifyContent::Center => if is_first {
863                        free_space / 2.0
864                    } else {
865                        0.0
866                    },
867                    style::JustifyContent::FlexEnd => if is_first {
868                        free_space
869                    } else {
870                        0.0
871                    },
872                    style::JustifyContent::SpaceBetween => if is_first {
873                        0.0
874                    } else {
875                        free_space / (num_items - 1) as f32
876                    },
877                    style::JustifyContent::SpaceAround => if is_first {
878                        (free_space / num_items as f32) / 2.0
879                    } else {
880                        free_space / num_items as f32
881                    },
882                    style::JustifyContent::SpaceEvenly => free_space / (num_items + 1) as f32,
883                };
884
885                is_first = false;
886            }
887        }
888    }
889
890    // 9.6. Cross-Axis Alignment
891
892    // 13. Resolve cross-axis auto margins. If a flex item has auto cross-axis margins:
893    //     - If its outer cross size (treating those auto margins as zero) is less than the
894    //       cross size of its flex line, distribute the difference in those sizes equally
895    //       to the auto margins.
896    //     - Otherwise, if the block-start or inline-start margin (whichever is in the cross axis)
897    //       is auto, set it to zero. Set the opposite margin so that the outer cross size of the
898    //       item equals the cross size of its flex line.
899
900    for line in &mut flex_lines {
901        // TODO this is super basic and has to be fixed to support a lot more such as custom baselines
902        // as well as nested children.
903        let baseline: f32 =
904            line.items.iter().map(|child| child.hypothetical_outer_cross_size).fold(0.0, |acc, x| acc.max(x));
905
906        for child in &mut line.items {
907            // TODO probably move this somewhere else, as with main margin resolution. Only auto margins should be resolved here.
908            child.cross_margin_start =
909                child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0);
910            child.cross_margin_end =
911                child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
912
913            let free_space = line.cross_size - child.outer_target_cross_size;
914
915            if child.node.cross_margin_start(node.flex_direction) == style::Dimension::Auto
916                && child.node.cross_margin_end(node.flex_direction) == style::Dimension::Auto
917            {
918                child.cross_margin_start = free_space / 2.0;
919                child.cross_margin_end = free_space / 2.0;
920            } else if child.node.cross_margin_start(node.flex_direction) == style::Dimension::Auto {
921                child.cross_margin_start = free_space;
922            } else if child.node.cross_margin_end(node.flex_direction) == style::Dimension::Auto {
923                child.cross_margin_end = free_space;
924            } else {
925                // 14. Align all flex items along the cross-axis per align-self, if neither of the item’s
926                //     cross-axis margins are auto.
927
928                child.offset_cross = match child.node.align_self(node) {
929                    style::AlignSelf::Auto => 0.0, // Should never happen
930                    style::AlignSelf::FlexStart => if wrap_reverse {
931                        free_space
932                    } else {
933                        0.0
934                    },
935                    style::AlignSelf::FlexEnd => if wrap_reverse {
936                        0.0
937                    } else {
938                        free_space
939                    },
940                    style::AlignSelf::Center => free_space / 2.0,
941                    style::AlignSelf::Baseline => {
942                        if node.flex_direction.is_row() {
943                            // TODO need more sophisticated baseline support,
944                            // especially for basline aligning text.
945                            baseline - child.target_cross_size
946                        } else {
947                            // basline alignment only makes sense if the direction is row
948                            // we treat it as flex-start alignment in columns.
949                            if wrap_reverse {
950                                free_space
951                            } else {
952                                0.0
953                            }
954                        }
955                    }
956                    style::AlignSelf::Stretch => if wrap_reverse {
957                        free_space
958                    } else {
959                        0.0
960                    },
961                };
962            }
963        }
964    }
965
966    // 15. Determine the flex container’s used cross size:
967    //     - If the cross size property is a definite size, use that, clamped by the used
968    //       min and max cross sizes of the flex container.
969    //     - Otherwise, use the sum of the flex lines' cross sizes, clamped by the used
970    //       min and max cross sizes of the flex container.
971
972    let total_cross_size: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
973    let container_cross_size =
974        if node_cross.is_finite() { node_cross } else { (total_cross_size + padding_cross + border_cross) };
975    let inner_container_cross_size = container_cross_size - padding_cross - border_cross;
976
977    // 16. Align all flex lines per align-content.
978
979    let free_space = inner_container_cross_size - total_cross_size;
980    let num_lines = flex_lines.len();
981    let mut is_first = true;
982
983    let align_line = |line: &mut FlexLine| {
984        line.offset_cross = match node.align_content {
985            style::AlignContent::FlexStart => if is_first && wrap_reverse {
986                free_space
987            } else {
988                0.0
989            },
990            style::AlignContent::FlexEnd => if is_first && !wrap_reverse {
991                free_space
992            } else {
993                0.0
994            },
995            style::AlignContent::Center => if is_first {
996                free_space / 2.0
997            } else {
998                0.0
999            },
1000            style::AlignContent::Stretch => 0.0,
1001            style::AlignContent::SpaceBetween => if is_first {
1002                0.0
1003            } else {
1004                free_space / (num_lines - 1) as f32
1005            },
1006            style::AlignContent::SpaceAround => if is_first {
1007                (free_space / num_lines as f32) / 2.0
1008            } else {
1009                free_space / num_lines as f32
1010            },
1011        };
1012        is_first = false;
1013    };
1014
1015    if wrap_reverse {
1016        flex_lines.iter_mut().rev().for_each(align_line);
1017    } else {
1018        flex_lines.iter_mut().for_each(align_line);
1019    }
1020
1021    // Do a final layout pass and gather the resulting layouts
1022    let percent_calc_base_child = if node.flex_direction.is_row() { container_main_size } else { container_cross_size };
1023
1024    let mut children: Vec<layout::Node> = {
1025        let mut lines: Vec<Vec<layout::Node>> = vec![];
1026        let mut total_offset_cross = padding_cross_start + border_cross_start;
1027
1028        {
1029            let layout_line = |line: &mut FlexLine| {
1030                let mut children: Vec<layout::Node> = vec![];
1031                let mut total_offset_main = padding_main_start + border_main_start;
1032
1033                for child in &mut line.items {
1034                    let result = compute_internal(
1035                        child.node,
1036                        if node.flex_direction.is_row() { child.target_main_size } else { child.target_cross_size },
1037                        if node.flex_direction.is_row() { child.target_cross_size } else { child.target_main_size },
1038                        if node.flex_direction.is_row() { container_main_size } else { container_cross_size },
1039                        if node.flex_direction.is_row() { container_cross_size } else { container_main_size },
1040                        percent_calc_base_child,
1041                    );
1042
1043                    let offset_main = {
1044                        total_offset_main
1045                            + child.offset_main
1046                            + child.main_margin_start
1047                            + (child.node.main_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
1048                                - child.node.main_end(node.flex_direction).resolve(percent_calc_base_child, 0.0))
1049                    };
1050
1051                    let offset_cross = {
1052                        total_offset_cross
1053                            + child.offset_cross
1054                            + line.offset_cross
1055                            + child.cross_margin_start
1056                            + (child.node.cross_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
1057                                - child.node.cross_end(node.flex_direction).resolve(percent_calc_base_child, 0.0))
1058                    };
1059
1060                    children.push(layout::Node {
1061                        width: result.size.width,
1062                        height: result.size.height,
1063                        x: if node.flex_direction.is_row() { offset_main } else { offset_cross },
1064                        y: if node.flex_direction.is_column() { offset_main } else { offset_cross },
1065                        children: result.children,
1066                    });
1067
1068                    total_offset_main = offset_main + result.size.main(node.flex_direction) + child.main_margin_end;
1069                }
1070
1071                total_offset_cross += line.offset_cross + line.cross_size;
1072                lines.push(children);
1073            };
1074
1075            if wrap_reverse {
1076                flex_lines.iter_mut().rev().for_each(layout_line);
1077            } else {
1078                flex_lines.iter_mut().for_each(layout_line);
1079            }
1080        }
1081
1082        if wrap_reverse {
1083            lines.into_iter().rev().flat_map(|x| x).collect()
1084        } else {
1085            lines.into_iter().flat_map(|x| x).collect()
1086        }
1087    };
1088
1089    let container_width = if node.flex_direction.is_row() { container_main_size } else { container_cross_size };
1090    let container_height = if node.flex_direction.is_column() { container_main_size } else { container_cross_size };
1091
1092    // Before returning we perform absolute layout on all absolutely positioned children
1093
1094    let absolute_children: Vec<&style::Node> =
1095        node.children.iter().filter(|child| child.position == style::Position::Absolute).collect();
1096
1097    for child in absolute_children {
1098        let start =
1099            child.start.resolve(container_width, f32::NAN) + child.margin.start.resolve(container_width, f32::NAN);
1100        let end = child.end.resolve(container_width, f32::NAN) + child.margin.end.resolve(container_width, f32::NAN);
1101        let top = child.top.resolve(container_height, f32::NAN) + child.margin.top.resolve(container_height, f32::NAN);
1102        let bottom =
1103            child.bottom.resolve(container_height, f32::NAN) + child.margin.bottom.resolve(container_height, f32::NAN);
1104
1105        let (start_main, end_main) = if node.flex_direction.is_row() { (start, end) } else { (top, bottom) };
1106        let (start_cross, end_cross) = if node.flex_direction.is_row() { (top, bottom) } else { (start, end) };
1107
1108        let child_width = child
1109            .width
1110            .resolve(container_width, f32::NAN)
1111            .max(child.min_width.resolve(container_width, f32::NAN))
1112            .min(child.max_width.resolve(container_width, f32::NAN));
1113
1114        let child_height = child
1115            .height
1116            .resolve(container_height, f32::NAN)
1117            .max(child.min_height.resolve(container_height, f32::NAN))
1118            .min(child.max_height.resolve(container_height, f32::NAN));
1119
1120        let width = if child_width.is_finite() { child_width } else { container_width - start - end };
1121
1122        let height = if child_height.is_finite() { child_height } else { container_height - top - bottom };
1123
1124        let result = compute_internal(
1125            child,
1126            width,
1127            height,
1128            if node.flex_direction.is_row() { container_main_size } else { container_cross_size },
1129            if node.flex_direction.is_row() { container_cross_size } else { container_main_size },
1130            container_main_size,
1131        );
1132
1133        let free_cross_space = container_cross_size - result.size.cross(node.flex_direction);
1134        let free_main_space = container_main_size - result.size.main(node.flex_direction);
1135
1136        let offset_main = if start_main.is_finite() {
1137            start_main + border_main_start
1138        } else if end_main.is_finite() {
1139            free_main_space - end_main - border_main_end
1140        } else {
1141            match node.justify_content {
1142                style::JustifyContent::SpaceBetween | style::JustifyContent::FlexStart => {
1143                    padding_main_start + border_main_start
1144                }
1145                style::JustifyContent::FlexEnd => free_main_space - padding_main_end - border_main_end,
1146                style::JustifyContent::SpaceEvenly
1147                | style::JustifyContent::SpaceAround
1148                | style::JustifyContent::Center => free_main_space / 2.0,
1149            }
1150        };
1151
1152        let offset_cross = if start_cross.is_finite() {
1153            start_cross + border_cross_start
1154        } else if end_cross.is_finite() {
1155            free_cross_space - end_cross - border_cross_end
1156        } else {
1157            match child.align_self(node) {
1158                style::AlignSelf::Auto => 0.0, // Should never happen
1159                style::AlignSelf::FlexStart => if wrap_reverse {
1160                    free_cross_space - padding_cross_end - border_cross_end
1161                } else {
1162                    padding_cross_start + border_cross_start
1163                },
1164                style::AlignSelf::FlexEnd => if wrap_reverse {
1165                    padding_cross_start + border_cross_start
1166                } else {
1167                    free_cross_space - padding_cross_end - border_cross_end
1168                },
1169                style::AlignSelf::Center => free_cross_space / 2.0,
1170                style::AlignSelf::Baseline => free_cross_space / 2.0, // Treat as center for now until we have baseline support
1171                style::AlignSelf::Stretch => if wrap_reverse {
1172                    free_cross_space - padding_cross_end - border_cross_end
1173                } else {
1174                    padding_cross_start + border_cross_start
1175                },
1176            }
1177        };
1178
1179        children.push(layout::Node {
1180            width: result.size.width,
1181            height: result.size.height,
1182            x: if node.flex_direction.is_row() { offset_main } else { offset_cross },
1183            y: if node.flex_direction.is_column() { offset_main } else { offset_cross },
1184            children: result.children,
1185        });
1186    }
1187
1188    ComputeResult { size: FlexSize { width: container_width, height: container_height }, children }
1189}