tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 1130HTML 550Markdown 11TOML 63111 Definiciones

⎇ 5b578551d59cf98f4f9b6bc29d6b318612db4ec4 src/algo.rs Rust · 1198 líneas · 54.1 KB Historia Quién tocó qué crudo

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