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