gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 252HTML 238TOML 3CSS 1626 Definitions

⎇ 11506d63f4f785ab400d0a39dbe7efbb51d5916e src/algo.rs Rust · 1187 lines · 53.6 KB History Who touched what raw

fix alignment with negative free space 11506d63f · 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::MAX))
613                } else {
614                    child.node.min_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN)
615                };
616
617                let max_main = child.node.max_main_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX);
618
619                let clamped = child.target_main_size.min(max_main).max(min_main);
620                child.violation = clamped - child.target_main_size;
621                total_violation += child.violation;
622                child.target_main_size = clamped;
623                child.outer_target_main_size = child.target_main_size
624                    + child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
625                    + child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
626            }
627
628            // e. Freeze over-flexed items. The total violation is the sum of the adjustments
629            //    from the previous step ∑(clamped size - unclamped size). If the total violation is:
630            //    - Zero
631            //        Freeze all items.
632            //    - Positive
633            //        Freeze all the items with min violations.
634            //    - Negative
635            //        Freeze all the items with max violations.
636
637            if !total_violation.is_normal() {
638                for child in &mut unfrozen {
639                    child.frozen = true;
640                }
641            } else if total_violation > 0.0 {
642                for child in &mut unfrozen {
643                    child.frozen = child.violation > 0.0;
644                }
645            } else if total_violation < 0.0 {
646                for child in &mut unfrozen {
647                    child.frozen = child.violation < 0.0;
648                }
649            }
650
651            // f. Return to the start of this loop.
652        }
653    }
654
655    // Not part of the spec from what i can see but seems correct
656    let container_main_size = if node_main.is_finite() {
657        node_main
658    } else {
659        let mut longest_line = f32::MIN;
660
661        for line in &flex_lines {
662            let length: f32 = line.items.iter().map(|item| item.outer_target_main_size).sum();
663            longest_line = if length > longest_line { length } else { longest_line };
664        }
665
666        let size = longest_line + padding_main + border_main;
667        if available_main.is_finite() && flex_lines.len() > 1 && size < available_main {
668            available_main
669        } else {
670            size
671        }
672    };
673
674    let inner_container_main_size = container_main_size - padding_main - border_main;
675
676    // 9.4. Cross Size Determination
677
678    // 7. Determine the hypothetical cross size of each item by performing layout with the
679    //    used main size and the available space, treating auto as fit-content.
680
681    for line in &mut flex_lines {
682        for child in &mut line.items {
683            let child_cross = child
684                .node
685                .cross_size(node.flex_direction)
686                .resolve(percent_calc_base_child, f32::NAN)
687                .max(child.node.min_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::NAN))
688                .min(child.node.max_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::NAN));
689
690            let size = compute_internal(
691                child.node,
692                if node.flex_direction.is_row() { child.target_main_size } else { child_cross },
693                if node.flex_direction.is_row() { child_cross } else { child.target_main_size },
694                if node.flex_direction.is_row() { container_main_size } else { available_cross },
695                if node.flex_direction.is_row() { available_cross } else { container_main_size },
696                percent_calc_base_child,
697            ).size;
698
699            child.hypothetical_inner_cross_size = size
700                .cross(node.flex_direction)
701                .max(child.node.min_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN))
702                .min(child.node.max_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX))
703                .max(0.0);
704
705            child.hypothetical_outer_cross_size = child.hypothetical_inner_cross_size
706                + child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
707                + child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
708        }
709    }
710
711    // 8. Calculate the cross size of each flex line.
712    //    If the flex container is single-line and has a definite cross size, the cross size
713    //    of the flex line is the flex container’s inner cross size. Otherwise, for each flex line:
714    //
715    //    1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose
716    //       align-self is baseline, and whose cross-axis margins are both non-auto. Find the
717    //       largest of the distances between each item’s baseline and its hypothetical outer
718    //       cross-start edge, and the largest of the distances between each item’s baseline
719    //       and its hypothetical outer cross-end edge, and sum these two values.
720    //    2. Among all the items not collected by the previous step, find the largest
721    //       outer hypothetical cross size.
722    //    3. The used cross-size of the flex line is the largest of the numbers found in the
723    //       previous two steps and zero.
724    //
725    //    If the flex container is single-line, then clamp the line’s cross-size to be within
726    //    the container’s computed min and max cross sizes. Note that if CSS 2.1’s definition
727    //    of min/max-width/height applied more generally, this behavior would fall out automatically.
728
729    if flex_lines.len() == 1 && node_cross.is_finite() {
730        flex_lines[0].cross_size = node_cross - padding_cross - border_cross;
731    } else {
732        for line in &mut flex_lines {
733            // TODO handle baseline (1)
734
735            line.cross_size =
736                line.items.iter().map(|child| child.hypothetical_outer_cross_size).fold(0.0, |acc, x| acc.max(x));
737        }
738    }
739
740    // 9. Handle 'align-content: stretch'. If the flex container has a definite cross size,
741    //    align-content is stretch, and the sum of the flex lines' cross sizes is less than
742    //    the flex container’s inner cross size, increase the cross size of each flex line
743    //    by equal amounts such that the sum of their cross sizes exactly equals the
744    //    flex container’s inner cross size.
745
746    if node.align_content == style::AlignContent::Stretch && node_cross.is_finite() {
747        let total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
748        let inner_cross = node_cross - padding_cross - border_cross;
749
750        if total_cross < inner_cross {
751            let remaining = inner_cross - total_cross;
752            let addition = remaining / flex_lines.len() as f32;
753
754            for line in &mut flex_lines {
755                line.cross_size += addition;
756            }
757        }
758    }
759
760    // 10. Collapse visibility:collapse items. If any flex items have visibility: collapse,
761    //     note the cross size of the line they’re in as the item’s strut size, and restart
762    //     layout from the beginning.
763    //
764    //     In this second layout round, when collecting items into lines, treat the collapsed
765    //     items as having zero main size. For the rest of the algorithm following that step,
766    //     ignore the collapsed items entirely (as if they were display:none) except that after
767    //     calculating the cross size of the lines, if any line’s cross size is less than the
768    //     largest strut size among all the collapsed items in the line, set its cross size to
769    //     that strut size.
770    //
771    //     Skip this step in the second layout round.
772
773    // TODO implement once (if ever) we support visibility:collapse
774
775    // 11. Determine the used cross size of each flex item. If a flex item has align-self: stretch,
776    //     its computed cross size property is auto, and neither of its cross-axis margins are auto,
777    //     the used outer cross size is the used cross size of its flex line, clamped according to
778    //     the item’s used min and max cross sizes. Otherwise, the used cross size is the item’s
779    //     hypothetical cross size.
780    //
781    //     If the flex item has align-self: stretch, redo layout for its contents, treating this
782    //     used size as its definite cross size so that percentage-sized children can be resolved.
783    //
784    //     Note that this step does not affect the main size of the flex item, even if it has an
785    //     intrinsic aspect ratio.
786
787    for line in &mut flex_lines {
788        for child in &mut line.items {
789            let is_stretch = child.node.align_self(node) == style::AlignSelf::Stretch;
790
791            child.target_cross_size = if is_stretch
792                && child.node.cross_margin_start(node.flex_direction) != style::Dimension::Auto
793                && child.node.cross_margin_end(node.flex_direction) != style::Dimension::Auto
794                && child.node.cross_size(node.flex_direction) == style::Dimension::Auto
795            {
796                (line.cross_size
797                    - child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
798                    - child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0))
799                    .max(child.node.min_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MIN))
800                    .min(child.node.max_cross_size(node.flex_direction).resolve(percent_calc_base_child, f32::MAX))
801            } else {
802                child.hypothetical_inner_cross_size
803            };
804
805            child.outer_target_cross_size = child.target_cross_size
806                + child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
807                + child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
808        }
809    }
810
811    // 9.5. Main-Axis Alignment
812
813    // 12. Distribute any remaining free space. For each flex line:
814    //     1. If the remaining free space is positive and at least one main-axis margin on this
815    //        line is auto, distribute the free space equally among these margins. Otherwise,
816    //        set all auto margins to zero.
817    //     2. Align the items along the main-axis per justify-content.
818
819    for line in &mut flex_lines {
820        let used_space: f32 = line.items.iter().map(|child| child.outer_target_main_size).sum();
821        let free_space = inner_container_main_size - used_space;
822
823        // TODO does not make a ton of sense to have this here but we want to have this somewhere.
824        for child in &mut line.items {
825            child.main_margin_start =
826                child.node.main_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0);
827            child.main_margin_end =
828                child.node.main_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
829        }
830
831        let mut num_auto_margins = 0;
832
833        for child in &mut line.items {
834            if child.node.main_margin_start(node.flex_direction) == style::Dimension::Auto {
835                num_auto_margins += 1;
836            }
837            if child.node.main_margin_end(node.flex_direction) == style::Dimension::Auto {
838                num_auto_margins += 1;
839            }
840        }
841
842        if free_space > 0.0 && num_auto_margins > 0 {
843            let margin = free_space / num_auto_margins as f32;
844
845            for child in &mut line.items {
846                if child.node.main_margin_start(node.flex_direction) == style::Dimension::Auto {
847                    child.main_margin_start = margin;
848                }
849                if child.node.main_margin_end(node.flex_direction) == style::Dimension::Auto {
850                    child.main_margin_end = margin;
851                }
852            }
853        } else {
854            let num_items = line.items.len();
855            let mut is_first = true;
856
857            for child in &mut line.items {
858                child.offset_main = match node.justify_content {
859                    style::JustifyContent::FlexStart => 0.0,
860                    style::JustifyContent::Center => if is_first {
861                        free_space / 2.0
862                    } else {
863                        0.0
864                    },
865                    style::JustifyContent::FlexEnd => if is_first {
866                        free_space
867                    } else {
868                        0.0
869                    },
870                    style::JustifyContent::SpaceBetween => if is_first {
871                        0.0
872                    } else {
873                        free_space / (num_items - 1) as f32
874                    },
875                    style::JustifyContent::SpaceAround => if is_first {
876                        (free_space / num_items as f32) / 2.0
877                    } else {
878                        free_space / num_items as f32
879                    },
880                    style::JustifyContent::SpaceEvenly => free_space / (num_items + 1) as f32,
881                };
882
883                is_first = false;
884            }
885        }
886    }
887
888    // 9.6. Cross-Axis Alignment
889
890    // 13. Resolve cross-axis auto margins. If a flex item has auto cross-axis margins:
891    //     - If its outer cross size (treating those auto margins as zero) is less than the
892    //       cross size of its flex line, distribute the difference in those sizes equally
893    //       to the auto margins.
894    //     - Otherwise, if the block-start or inline-start margin (whichever is in the cross axis)
895    //       is auto, set it to zero. Set the opposite margin so that the outer cross size of the
896    //       item equals the cross size of its flex line.
897
898    for line in &mut flex_lines {
899        // TODO this is super basic and has to be fixed to support a lot more such as custom baselines
900        // as well as nested children.
901        let baseline: f32 =
902            line.items.iter().map(|child| child.hypothetical_outer_cross_size).fold(0.0, |acc, x| acc.max(x));
903
904        for child in &mut line.items {
905            // TODO probably move this somewhere else, as with main margin resolution. Only auto margins should be resolved here.
906            child.cross_margin_start =
907                child.node.cross_margin_start(node.flex_direction).resolve(percent_calc_base_child, 0.0);
908            child.cross_margin_end =
909                child.node.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child, 0.0);
910
911            let free_space = line.cross_size - child.outer_target_cross_size;
912            
913            if child.node.cross_margin_start(node.flex_direction) == style::Dimension::Auto
914                && child.node.cross_margin_end(node.flex_direction) == style::Dimension::Auto
915            {
916                child.cross_margin_start = free_space / 2.0;
917                child.cross_margin_end = free_space / 2.0;
918            } else if child.node.cross_margin_start(node.flex_direction) == style::Dimension::Auto {
919                child.cross_margin_start = free_space;
920            } else if child.node.cross_margin_end(node.flex_direction) == style::Dimension::Auto {
921                child.cross_margin_end = free_space;
922            } else {
923                // 14. Align all flex items along the cross-axis per align-self, if neither of the item’s
924                //     cross-axis margins are auto.
925
926                child.offset_cross = match child.node.align_self(node) {
927                    style::AlignSelf::Auto => 0.0, // Should never happen
928                    style::AlignSelf::FlexStart => if wrap_reverse {
929                        free_space
930                    } else {
931                        0.0
932                    },
933                    style::AlignSelf::FlexEnd => if wrap_reverse {
934                        0.0
935                    } else {
936                        free_space
937                    },
938                    style::AlignSelf::Center => free_space / 2.0,
939                    style::AlignSelf::Baseline => {
940                        if node.flex_direction.is_row() {
941                            // TODO need more sophisticated baseline support,
942                            // especially for basline aligning text.
943                            baseline - child.target_cross_size
944                        } else {
945                            // basline alignment only makes sense if the direction is row
946                            // we treat it as flex-start alignment in columns.
947                            if wrap_reverse {
948                                free_space
949                            } else {
950                                0.0
951                            }
952                        }
953                    }
954                    style::AlignSelf::Stretch => if wrap_reverse {
955                        free_space
956                    } else {
957                        0.0
958                    },
959                };
960            }
961        }
962    }
963
964    // 15. Determine the flex container’s used cross size:
965    //     - If the cross size property is a definite size, use that, clamped by the used
966    //       min and max cross sizes of the flex container.
967    //     - Otherwise, use the sum of the flex lines' cross sizes, clamped by the used
968    //       min and max cross sizes of the flex container.
969
970    let total_cross_size: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
971    let container_cross_size =
972        if node_cross.is_finite() { node_cross } else { (total_cross_size + padding_cross + border_cross) };
973    let inner_container_cross_size = container_cross_size - padding_cross - border_cross;
974
975    // 16. Align all flex lines per align-content.
976
977    let free_space = inner_container_cross_size - total_cross_size;
978    let num_lines = flex_lines.len();
979    let mut is_first = true;
980
981    let align_line = |line: &mut FlexLine| {
982        line.offset_cross = match node.align_content {
983            style::AlignContent::FlexStart => if is_first && wrap_reverse {
984                free_space
985            } else {
986                0.0
987            },
988            style::AlignContent::FlexEnd => if is_first && !wrap_reverse {
989                free_space
990            } else {
991                0.0
992            },
993            style::AlignContent::Center => if is_first {
994                free_space / 2.0
995            } else {
996                0.0
997            },
998            style::AlignContent::Stretch => 0.0,
999            style::AlignContent::SpaceBetween => if is_first {
1000                0.0
1001            } else {
1002                free_space / (num_lines - 1) as f32
1003            },
1004            style::AlignContent::SpaceAround => if is_first {
1005                (free_space / num_lines as f32) / 2.0
1006            } else {
1007                free_space / num_lines as f32
1008            },
1009        };
1010        is_first = false;
1011    };
1012
1013    if wrap_reverse {
1014        flex_lines.iter_mut().rev().for_each(align_line);
1015    } else {
1016        flex_lines.iter_mut().for_each(align_line);
1017    }
1018
1019    // Do a final layout pass and gather the resulting layouts
1020    let percent_calc_base_child = if node.flex_direction.is_row() { container_main_size } else { container_cross_size };
1021
1022    let mut children: Vec<layout::Node> = {
1023        let mut lines: Vec<Vec<layout::Node>> = vec![];
1024        let mut total_offset_cross = padding_cross_start + border_cross_start;
1025
1026        {
1027            let layout_line = |line: &mut FlexLine| {
1028                let mut children: Vec<layout::Node> = vec![];
1029                let mut total_offset_main = padding_main_start + border_main_start;
1030
1031                for child in &mut line.items {
1032                    let result = compute_internal(
1033                        child.node,
1034                        if node.flex_direction.is_row() { child.target_main_size } else { child.target_cross_size },
1035                        if node.flex_direction.is_row() { child.target_cross_size } else { child.target_main_size },
1036                        if node.flex_direction.is_row() { container_main_size } else { container_cross_size },
1037                        if node.flex_direction.is_row() { container_cross_size } else { container_main_size },
1038                        percent_calc_base_child,
1039                    );
1040
1041                    let offset_main = {
1042                        total_offset_main
1043                            + child.offset_main
1044                            + child.main_margin_start
1045                            + (child.node.main_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
1046                                - child.node.main_end(node.flex_direction).resolve(percent_calc_base_child, 0.0))
1047                    };
1048
1049                    let offset_cross = {
1050                        total_offset_cross
1051                            + child.offset_cross
1052                            + line.offset_cross
1053                            + child.cross_margin_start
1054                            + (child.node.cross_start(node.flex_direction).resolve(percent_calc_base_child, 0.0)
1055                                - child.node.cross_end(node.flex_direction).resolve(percent_calc_base_child, 0.0))
1056                    };
1057
1058                    children.push(layout::Node {
1059                        width: result.size.width,
1060                        height: result.size.height,
1061                        x: if node.flex_direction.is_row() { offset_main } else { offset_cross },
1062                        y: if node.flex_direction.is_column() { offset_main } else { offset_cross },
1063                        children: result.children,
1064                    });
1065
1066                    total_offset_main = offset_main + result.size.main(node.flex_direction) + child.main_margin_end;
1067                }
1068
1069                total_offset_cross += line.offset_cross + line.cross_size;
1070                lines.push(children);
1071            };
1072
1073            if wrap_reverse {
1074                flex_lines.iter_mut().rev().for_each(layout_line);
1075            } else {
1076                flex_lines.iter_mut().for_each(layout_line);
1077            }
1078        }
1079
1080        if wrap_reverse {
1081            lines.into_iter().rev().flat_map(|x| x).collect()
1082        } else {
1083            lines.into_iter().flat_map(|x| x).collect()
1084        }
1085    };
1086
1087    let container_width = if node.flex_direction.is_row() { container_main_size } else { container_cross_size };
1088    let container_height = if node.flex_direction.is_column() { container_main_size } else { container_cross_size };
1089
1090    // Before returning we perform absolute layout on all absolutely positioned children
1091
1092    let absolute_children: Vec<&style::Node> =
1093        node.children.iter().filter(|child| child.position == style::Position::Absolute).collect();
1094
1095    for child in absolute_children {
1096        let start =
1097            child.start.resolve(container_width, f32::NAN) + child.margin.start.resolve(container_width, f32::NAN);
1098        let end = child.end.resolve(container_width, f32::NAN) + child.margin.end.resolve(container_width, f32::NAN);
1099        let top = child.top.resolve(container_height, f32::NAN) + child.margin.top.resolve(container_height, f32::NAN);
1100        let bottom =
1101            child.bottom.resolve(container_height, f32::NAN) + child.margin.bottom.resolve(container_height, f32::NAN);
1102
1103        let (start_main, end_main) = if node.flex_direction.is_row() { (start, end) } else { (top, bottom) };
1104        let (start_cross, end_cross) = if node.flex_direction.is_row() { (top, bottom) } else { (start, end) };
1105
1106        let child_width = child
1107            .width
1108            .resolve(container_width, f32::NAN)
1109            .max(child.min_width.resolve(container_width, f32::NAN))
1110            .min(child.max_width.resolve(container_width, f32::NAN));
1111
1112        let child_height = child
1113            .height
1114            .resolve(container_height, f32::NAN)
1115            .max(child.min_height.resolve(container_height, f32::NAN))
1116            .min(child.max_height.resolve(container_height, f32::NAN));
1117
1118        let width = if child_width.is_finite() { child_width } else { container_width - start - end };
1119
1120        let height = if child_height.is_finite() { child_height } else { container_height - top - bottom };
1121
1122        let result = compute_internal(
1123            child,
1124            width,
1125            height,
1126            if node.flex_direction.is_row() { container_main_size } else { container_cross_size },
1127            if node.flex_direction.is_row() { container_cross_size } else { container_main_size },
1128            container_main_size,
1129        );
1130
1131        let free_cross_space = container_cross_size - result.size.cross(node.flex_direction);
1132        let free_main_space = container_main_size - result.size.main(node.flex_direction);
1133
1134        let offset_main = if start_main.is_finite() {
1135            start_main + border_main_start
1136        } else if end_main.is_finite() {
1137            free_main_space - end_main - border_main_end
1138        } else {
1139            match node.justify_content {
1140                style::JustifyContent::SpaceBetween | style::JustifyContent::FlexStart => {
1141                    padding_main_start + border_main_start
1142                }
1143                style::JustifyContent::FlexEnd => free_main_space - padding_main_end - border_main_end,
1144                style::JustifyContent::SpaceEvenly
1145                | style::JustifyContent::SpaceAround
1146                | style::JustifyContent::Center => free_main_space / 2.0,
1147            }
1148        };
1149
1150        let offset_cross = if start_cross.is_finite() {
1151            start_cross + border_cross_start
1152        } else if end_cross.is_finite() {
1153            free_cross_space - end_cross - border_cross_end
1154        } else {
1155            match child.align_self(node) {
1156                style::AlignSelf::Auto => 0.0, // Should never happen
1157                style::AlignSelf::FlexStart => if wrap_reverse {
1158                    free_cross_space - padding_cross_end - border_cross_end
1159                } else {
1160                    padding_cross_start + border_cross_start
1161                },
1162                style::AlignSelf::FlexEnd => if wrap_reverse {
1163                    padding_cross_start + border_cross_start
1164                } else {
1165                    free_cross_space - padding_cross_end - border_cross_end
1166                },
1167                style::AlignSelf::Center => free_cross_space / 2.0,
1168                style::AlignSelf::Baseline => free_cross_space / 2.0, // Treat as center for now until we have baseline support
1169                style::AlignSelf::Stretch => if wrap_reverse {
1170                    free_cross_space - padding_cross_end - border_cross_end
1171                } else {
1172                    padding_cross_start + border_cross_start
1173                },
1174            }
1175        };
1176
1177        children.push(layout::Node {
1178            width: result.size.width,
1179            height: result.size.height,
1180            x: if node.flex_direction.is_row() { offset_main } else { offset_cross },
1181            y: if node.flex_direction.is_column() { offset_main } else { offset_cross },
1182            children: result.children,
1183        });
1184    }
1185
1186    ComputeResult { size: FlexSize { width: container_width, height: container_height }, children }
1187}