gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 684HTML 640Markdown 12TOML 62290 Definitions

⎇ 812e02b5d39012fe614bb18966d7aadf06163a31 src/algo.rs Rust · 1188 lines · 53.7 KB History Who touched what raw

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