1use std::f32;
2
3use crate::layout;
4use crate::style;
5
6use crate::number::MinMax;
7use crate::number::Number;
8use crate::number::Number::*;
9use crate::number::OrElse;
10use crate::number::ToNumber;
11
12#[derive(Debug, Copy, Clone)]
13struct FlexSize {
14 width: f32,
15 height: f32,
16}
17
18impl FlexSize {
19 fn main(&self, direction: style::FlexDirection) -> f32 {
20 match direction {
21 style::FlexDirection::Row | style::FlexDirection::RowReverse => self.width,
22 style::FlexDirection::Column | style::FlexDirection::ColumnReverse => self.height,
23 }
24 }
25
26 fn cross(&self, direction: style::FlexDirection) -> f32 {
27 match direction {
28 style::FlexDirection::Row | style::FlexDirection::RowReverse => self.height,
29 style::FlexDirection::Column | style::FlexDirection::ColumnReverse => self.width,
30 }
31 }
32}
33
34#[derive(Debug)]
35struct ComputeResult {
36 size: FlexSize,
37 children: Vec<layout::Node>,
38}
39
40struct FlexItem<'a> {
41 node: &'a style::Node,
42
43 width: Number,
44 min_width: Number,
45 max_width: Number,
46
47 height: Number,
48 min_height: Number,
49 max_height: Number,
50
51 main: Number,
52 min_main: Number,
53 max_main: Number,
54
55 cross: Number,
56 min_cross: Number,
57 max_cross: Number,
58
59 main_start: Number,
60 main_end: Number,
61 cross_start: Number,
62 cross_end: Number,
63
64 margin_main_start: f32,
65 margin_main_end: f32,
66 margin_cross_start: f32,
67 margin_cross_end: f32,
68
69 padding_main_start: f32,
70 padding_main_end: f32,
71 padding_cross_start: f32,
72 padding_cross_end: f32,
73
74 border_main_start: f32,
75 border_main_end: f32,
76 border_cross_start: f32,
77 border_cross_end: f32,
78
79 // temporary values for main size determination
80 flex_basis: f32,
81 inner_flex_basis: f32,
82 hypothetical_inner_main_size: f32,
83 hypothetical_outer_main_size: f32,
84 target_main_size: f32,
85 outer_target_main_size: f32,
86 violation: f32,
87 frozen: bool,
88
89 // temporary values for cross size determination
90 hypothetical_inner_cross_size: f32,
91 hypothetical_outer_cross_size: f32,
92 target_cross_size: f32,
93 outer_target_cross_size: f32,
94
95 baseline: f32,
96
97 // temporary values for holding offset in the main / cross direction.
98 // offset is the relative position from the item's natural flow position based on
99 // relative position values, alignment, and justification. Does not unclude margin/padding/border.
100 offset_main: f32,
101 offset_cross: f32,
102}
103
104struct FlexLine<'a> {
105 items: Vec<FlexItem<'a>>,
106 cross_size: f32,
107 offset_cross: f32,
108}
109
110pub fn compute(root: &style::Node) -> layout::Node {
111 // TODO - Don't do two passes here just to handle min/max.
112 // Probably want to pass min/max down as top level paramerer instead.
113 let first_pass = compute_internal(
114 root,
115 root.width.resolve(Undefined),
116 root.height.resolve(Undefined),
117 Undefined,
118 Undefined,
119 Undefined,
120 );
121
122 let result = compute_internal(
123 root,
124 first_pass
125 .size
126 .width
127 .maybe_max(root.min_width.resolve(Undefined))
128 .maybe_min(root.max_width.resolve(Undefined))
129 .to_number(),
130 first_pass
131 .size
132 .height
133 .maybe_max(root.min_height.resolve(Undefined))
134 .maybe_min(root.max_height.resolve(Undefined))
135 .to_number(),
136 Undefined,
137 Undefined,
138 Undefined,
139 );
140
141 let mut layout = layout::Node {
142 width: result.size.width,
143 height: result.size.height,
144 x: 0.0,
145 y: 0.0,
146 children: result.children,
147 };
148
149 round_layout(&mut layout, 0.0, 0.0);
150 layout
151}
152
153fn round_layout(layout: &mut layout::Node, abs_x: f32, abs_y: f32) {
154 let abs_x = abs_x + layout.x;
155 let abs_y = abs_y + layout.y;
156
157 layout.x = layout.x.round();
158 layout.y = layout.y.round();
159 layout.width = (abs_x + layout.width).round() - abs_x.round();
160 layout.height = (abs_y + layout.height).round() - abs_y.round();
161 layout.children.iter_mut().for_each(|child| round_layout(child, abs_x, abs_y));
162}
163
164fn compute_internal(
165 node: &style::Node,
166
167 // The width and the height of this node, if Some
168 // the node should be layed out at exactly this size.
169 // If None the node should at most be the size of
170 // available_width / available_height if present.
171 node_width: Number,
172 node_height: Number,
173
174 // This available width and height. This is the
175 // the inner node_width / node_height of the parent and should
176 // not be exceeded by this node unless node_width / node_height
177 // parameters say otherwise.
178 parent_inner_width: Number,
179 parent_inner_height: Number,
180
181 // This will always be the parent width except for the case when
182 // the child is in an absolute context. This value should only
183 // be used for calculated percentage values.
184 percent_calc_base: Number,
185) -> ComputeResult {
186 // Define some general constants we will need for the remainder
187 // of the algorithm.
188
189 let is_row = node.flex_direction.is_row();
190 let is_column = node.flex_direction.is_column();
191 let is_wrap_reverse = node.flex_wrap == style::FlexWrap::WrapReverse;
192
193 let parent_inner_main = if is_row { parent_inner_width } else { parent_inner_height };
194 let parent_inner_cross = if is_row { parent_inner_height } else { parent_inner_width };
195
196 let (margin_main_start, margin_cross_start, margin_main_end, margin_cross_end) = (
197 node.main_margin_start(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
198 node.cross_margin_start(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
199 node.main_margin_end(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
200 node.cross_margin_end(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
201 );
202
203 let margin_main = margin_main_start + margin_main_end;
204 let margin_cross = margin_cross_start + margin_cross_end;
205
206 let (padding_main_start, padding_cross_start, padding_main_end, padding_cross_end) = (
207 node.main_padding_start(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
208 node.cross_padding_start(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
209 node.main_padding_end(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
210 node.cross_padding_end(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
211 );
212
213 let padding_main = padding_main_start + padding_main_end;
214 let padding_cross = padding_cross_start + padding_cross_end;
215
216 let (border_main_start, border_cross_start, border_main_end, border_cross_end) = (
217 node.main_border_start(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
218 node.cross_border_start(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
219 node.main_border_end(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
220 node.cross_border_end(node.flex_direction).resolve(percent_calc_base).or_else(0.0),
221 );
222
223 let border_main = border_main_start + border_main_end;
224 let border_cross = border_cross_start + border_cross_end;
225
226 let node_main = if is_row { node_width } else { node_height };
227 let node_cross = if is_row { node_height } else { node_width };
228
229 let node_inner_main = node_main - border_main - padding_main;
230 let node_inner_cross = node_cross - border_cross - padding_cross;
231
232 let percent_calc_base_child = if is_row { node_inner_main } else { node_inner_cross };
233
234 // 9.2. Line Length Determination
235
236 // 1. Generate anonymous flex items as described in §4 Flex Items.
237
238 let mut flex_items: Vec<FlexItem> = node
239 .children
240 .iter()
241 .filter(|child| child.position != style::Position::Absolute)
242 .map(|child| FlexItem {
243 node: child,
244
245 width: child.width.resolve(percent_calc_base_child),
246 min_width: child.min_width.resolve(percent_calc_base_child),
247 max_width: child.max_width.resolve(percent_calc_base_child),
248
249 height: child.height.resolve(percent_calc_base_child),
250 min_height: child.min_height.resolve(percent_calc_base_child),
251 max_height: child.max_height.resolve(percent_calc_base_child),
252
253 main: child.main_size(node.flex_direction).resolve(percent_calc_base_child),
254 min_main: child.min_main_size(node.flex_direction).resolve(percent_calc_base_child),
255 max_main: child.max_main_size(node.flex_direction).resolve(percent_calc_base_child),
256
257 cross: child.cross_size(node.flex_direction).resolve(percent_calc_base_child),
258 min_cross: child.min_cross_size(node.flex_direction).resolve(percent_calc_base_child),
259 max_cross: child.max_cross_size(node.flex_direction).resolve(percent_calc_base_child),
260
261 main_start: child.main_start(node.flex_direction).resolve(percent_calc_base_child),
262 main_end: child.main_end(node.flex_direction).resolve(percent_calc_base_child),
263 cross_start: child.cross_start(node.flex_direction).resolve(percent_calc_base_child),
264 cross_end: child.cross_end(node.flex_direction).resolve(percent_calc_base_child),
265
266 margin_main_start: child
267 .main_margin_start(node.flex_direction)
268 .resolve(percent_calc_base_child)
269 .or_else(0.0),
270
271 margin_main_end: child.main_margin_end(node.flex_direction).resolve(percent_calc_base_child).or_else(0.0),
272
273 margin_cross_start: child
274 .cross_margin_start(node.flex_direction)
275 .resolve(percent_calc_base_child)
276 .or_else(0.0),
277
278 margin_cross_end: child.cross_margin_end(node.flex_direction).resolve(percent_calc_base_child).or_else(0.0),
279
280 padding_main_start: child
281 .main_padding_start(node.flex_direction)
282 .resolve(percent_calc_base_child)
283 .or_else(0.0),
284
285 padding_main_end: child.main_padding_end(node.flex_direction).resolve(percent_calc_base_child).or_else(0.0),
286
287 padding_cross_start: child
288 .cross_padding_start(node.flex_direction)
289 .resolve(percent_calc_base_child)
290 .or_else(0.0),
291
292 padding_cross_end: child
293 .cross_padding_end(node.flex_direction)
294 .resolve(percent_calc_base_child)
295 .or_else(0.0),
296
297 border_main_start: child
298 .main_border_start(node.flex_direction)
299 .resolve(percent_calc_base_child)
300 .or_else(0.0),
301
302 border_main_end: child.main_border_end(node.flex_direction).resolve(percent_calc_base_child).or_else(0.0),
303
304 border_cross_start: child
305 .cross_border_start(node.flex_direction)
306 .resolve(percent_calc_base_child)
307 .or_else(0.0),
308
309 border_cross_end: child.cross_border_end(node.flex_direction).resolve(percent_calc_base_child).or_else(0.0),
310
311 flex_basis: 0.0,
312 inner_flex_basis: 0.0,
313 hypothetical_inner_main_size: 0.0,
314 hypothetical_outer_main_size: 0.0,
315 target_main_size: 0.0,
316 outer_target_main_size: 0.0,
317 violation: 0.0,
318 frozen: false,
319
320 hypothetical_inner_cross_size: 0.0,
321 hypothetical_outer_cross_size: 0.0,
322 target_cross_size: 0.0,
323 outer_target_cross_size: 0.0,
324
325 baseline: 0.0,
326
327 offset_main: 0.0,
328 offset_cross: 0.0,
329 })
330 .collect();
331
332 // 2. Determine the available main and cross space for the flex items.
333 // For each dimension, if that dimension of the flex container’s content box
334 // is a definite size, use that; if that dimension of the flex container is
335 // being sized under a min or max-content constraint, the available space in
336 // that dimension is that constraint; otherwise, subtract the flex container’s
337 // margin, border, and padding from the space available to the flex container
338 // in that dimension and use that value. This might result in an infinite value.
339
340 let available_main = node_main.or_else(parent_inner_main - margin_main) - padding_main - border_main;
341 let available_cross = node_cross.or_else(parent_inner_cross - margin_cross) - padding_cross - border_cross;
342
343 // TODO - this does not follow spec. See commented out code below
344 // 3. Determine the flex base size and hypothetical main size of each item:
345 flex_items.iter_mut().for_each(|child| {
346 // A. If the item has a definite used flex basis, that’s the flex base size.
347
348 let flex_basis = child.node.flex_basis.resolve(percent_calc_base_child);
349 if flex_basis.is_defined() {
350 child.flex_basis = flex_basis.or_else(0.0);
351 return;
352 };
353
354 // B. If the flex item has an intrinsic aspect ratio,
355 // a used flex basis of content, and a definite cross size,
356 // then the flex base size is calculated from its inner
357 // cross size and the flex item’s intrinsic aspect ratio.
358
359 if let Defined(ratio) = child.node.aspect_ratio {
360 if node_cross.is_defined() && child.node.flex_basis == style::Dimension::Auto {
361 child.flex_basis = (node_cross * ratio).or_else(0.0);
362 return;
363 }
364 }
365
366 // C. If the used flex basis is content or depends on its available space,
367 // and the flex container is being sized under a min-content or max-content
368 // constraint (e.g. when performing automatic table layout [CSS21]),
369 // size the item under that constraint. The flex base size is the item’s
370 // resulting main size.
371
372 // TODO - Probably need to cover this case in future
373
374 // D. Otherwise, if the used flex basis is content or depends on its
375 // available space, the available main size is infinite, and the flex item’s
376 // inline axis is parallel to the main axis, lay the item out using the rules
377 // for a box in an orthogonal flow [CSS3-WRITING-MODES]. The flex base size
378 // is the item’s max-content main size.
379
380 // TODO - Probably need to cover this case in future
381
382 // E. Otherwise, size the item into the available space using its used flex basis
383 // in place of its main size, treating a value of content as max-content.
384 // If a cross size is needed to determine the main size (e.g. when the
385 // flex item’s main size is in its block axis) and the flex item’s cross size
386 // is auto and not definite, in this calculation use fit-content as the
387 // flex item’s cross size. The flex base size is the item’s resulting main size.
388
389 child.flex_basis = compute_internal(
390 child.node,
391 child.width.maybe_max(child.min_width).maybe_min(child.max_width),
392 child.height.maybe_max(child.min_height).maybe_min(child.max_height),
393 if is_row { available_main } else { available_cross },
394 if is_row { available_cross } else { available_main },
395 percent_calc_base_child,
396 )
397 .size
398 .main(node.flex_direction)
399 .maybe_max(child.min_main)
400 .maybe_min(child.max_main);
401 });
402
403 // The hypothetical main size is the item’s flex base size clamped according to its
404 // used min and max main sizes (and flooring the content box size at zero).
405
406 flex_items.iter_mut().for_each(|child| {
407 child.inner_flex_basis = child.flex_basis
408 - (child.padding_main_start + child.padding_main_end + child.border_main_start + child.border_main_end);
409
410 // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
411 // The following logic was developed not from the spec but by trail and error looking into how
412 // webkit handled various scenarios. Can probably be solved better by passing in
413 // min-content max-content constraints fromt the top
414 let min_main = if is_row {
415 compute_internal(
416 child.node,
417 Undefined,
418 Undefined,
419 if is_row { available_main } else { available_cross },
420 if is_row { available_cross } else { available_main },
421 percent_calc_base_child,
422 )
423 .size
424 .width
425 .maybe_min(child.width)
426 .maybe_max(child.min_width)
427 .to_number()
428 } else {
429 child.min_main
430 };
431
432 child.hypothetical_inner_main_size = child.flex_basis.maybe_max(min_main).maybe_min(child.max_main);
433
434 child.hypothetical_outer_main_size =
435 child.hypothetical_inner_main_size + child.margin_main_start + child.margin_main_end;
436 });
437
438 // 9.3. Main Size Determination
439
440 // 5. Collect flex items into flex lines:
441 // - If the flex container is single-line, collect all the flex items into
442 // a single flex line.
443 // - Otherwise, starting from the first uncollected item, collect consecutive
444 // items one by one until the first time that the next collected item would
445 // not fit into the flex container’s inner main size (or until a forced break
446 // is encountered, see §10 Fragmenting Flex Layout). If the very first
447 // uncollected item wouldn’t fit, collect just it into the line.
448 //
449 // For this step, the size of a flex item is its outer hypothetical main size. (Note: This can be negative.)
450 // Repeat until all flex items have been collected into flex lines
451 //
452 // Note that the "collect as many" line will collect zero-sized flex items onto
453 // the end of the previous line even if the last non-zero item exactly "filled up" the line.
454
455 let mut flex_lines = {
456 let mut lines: Vec<FlexLine> = vec![];
457 let mut line_length = 0.0;
458
459 if node.flex_wrap == style::FlexWrap::NoWrap {
460 lines.push(FlexLine { items: flex_items, cross_size: 0.0, offset_cross: 0.0 });
461 } else {
462 let mut line = FlexLine { items: vec![], cross_size: 0.0, offset_cross: 0.0 };
463
464 for child in flex_items {
465 line_length += child.hypothetical_outer_main_size;
466
467 if let Defined(main) = available_main {
468 if line_length > main && line.items.len() > 0 {
469 line_length = child.hypothetical_outer_main_size;
470 lines.push(line);
471 line = FlexLine { items: vec![], cross_size: 0.0, offset_cross: 0.0 };
472 }
473 }
474
475 line.items.push(child);
476 }
477
478 lines.push(line);
479 }
480
481 lines
482 };
483
484 // 6. Resolve the flexible lengths of all the flex items to find their used main size.
485 // See §9.7 Resolving Flexible Lengths.
486 //
487 // 9.7. Resolving Flexible Lengths
488
489 flex_lines.iter_mut().for_each(|line| {
490 // 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
491 // items on the line. If the sum is less than the flex container’s inner main size,
492 // use the flex grow factor for the rest of this algorithm; otherwise, use the
493 // flex shrink factor.
494
495 let used_flex_factor: f32 = line.items.iter().map(|child| child.hypothetical_outer_main_size).sum();
496 let growing = used_flex_factor < node_inner_main.or_else(0.0);
497 let shrinking = !growing;
498
499 // 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
500 // - Any item that has a flex factor of zero
501 // - If using the flex grow factor: any item that has a flex base size
502 // greater than its hypothetical main size
503 // - If using the flex shrink factor: any item that has a flex base size
504 // smaller than its hypothetical main size
505
506 line.items.iter_mut().for_each(|child| {
507 // TODO - This is not found by reading the spec. Maybe this can be done in some other place
508 // instead. This was found by trail and error fixing tests to align with webkit output.
509 if node_inner_main.is_undefined() && is_row {
510 child.target_main_size = compute_internal(
511 child.node,
512 child.width.maybe_max(child.min_width).maybe_min(child.max_width),
513 child.height.maybe_max(child.min_height).maybe_min(child.max_height),
514 if is_row { available_main } else { available_cross },
515 if is_row { available_cross } else { available_main },
516 percent_calc_base_child,
517 )
518 .size
519 .main(node.flex_direction)
520 .maybe_max(child.min_main)
521 .maybe_min(child.max_main);
522 } else {
523 child.target_main_size = child.hypothetical_inner_main_size;
524 }
525
526 // TODO this should really only be set inside the if-statement below but
527 // that casues the target_main_size to never be set for some items
528
529 child.outer_target_main_size = child.target_main_size + child.margin_main_start + child.margin_main_end;
530
531 if (child.node.flex_grow == 0.0 && child.node.flex_shrink == 0.0)
532 || (growing && child.flex_basis > child.hypothetical_inner_main_size)
533 || (shrinking && child.flex_basis < child.hypothetical_inner_main_size)
534 {
535 child.frozen = true;
536 }
537 });
538
539 // 3. Calculate initial free space. Sum the outer sizes of all items on the line,
540 // and subtract this from the flex container’s inner main size. For frozen items,
541 // use their outer target main size; for other items, use their outer flex base size.
542
543 let used_space: f32 = line
544 .items
545 .iter()
546 .map(|child| {
547 child.margin_main_start
548 + child.margin_main_end
549 + if child.frozen { child.target_main_size } else { child.flex_basis }
550 })
551 .sum();
552
553 let initial_free_space = (node_inner_main - used_space).or_else(0.0);
554
555 // 4. Loop
556
557 loop {
558 // a. Check for flexible items. If all the flex items on the line are frozen,
559 // free space has been distributed; exit this loop.
560
561 let mut frozen: Vec<&mut FlexItem> = vec![];
562 let mut unfrozen: Vec<&mut FlexItem> = vec![];
563
564 line.items.iter_mut().for_each(|child| {
565 if child.frozen {
566 frozen.push(child);
567 } else {
568 unfrozen.push(child);
569 }
570 });
571
572 if unfrozen.len() == 0 {
573 break;
574 }
575
576 // b. Calculate the remaining free space as for initial free space, above.
577 // If the sum of the unfrozen flex items’ flex factors is less than one,
578 // multiply the initial free space by this sum. If the magnitude of this
579 // value is less than the magnitude of the remaining free space, use this
580 // as the remaining free space.
581
582 let used_space: f32 = Iterator::chain(frozen.iter(), unfrozen.iter())
583 .map(|child| {
584 child.margin_main_start
585 + child.margin_main_end
586 + if child.frozen { child.target_main_size } else { child.flex_basis }
587 })
588 .sum();
589
590 let sum_flex_grow: f32 = unfrozen.iter().map(|item| item.node.flex_grow).sum();
591 let sum_flex_shrink: f32 = unfrozen.iter().map(|item| item.node.flex_shrink).sum();
592
593 let free_space = if growing && sum_flex_grow < 1.0 {
594 (initial_free_space * sum_flex_grow).maybe_min(node_inner_main - used_space)
595 } else if shrinking && sum_flex_shrink < 1.0 {
596 (initial_free_space * sum_flex_shrink).maybe_max(node_inner_main - used_space)
597 } else {
598 (node_inner_main - used_space).or_else(0.0)
599 };
600
601 // c. Distribute free space proportional to the flex factors.
602 // - If the remaining free space is zero
603 // Do Nothing
604 // - If using the flex grow factor
605 // Find the ratio of the item’s flex grow factor to the sum of the
606 // flex grow factors of all unfrozen items on the line. Set the item’s
607 // target main size to its flex base size plus a fraction of the remaining
608 // free space proportional to the ratio.
609 // - If using the flex shrink factor
610 // For every unfrozen item on the line, multiply its flex shrink factor by
611 // its inner flex base size, and note this as its scaled flex shrink factor.
612 // Find the ratio of the item’s scaled flex shrink factor to the sum of the
613 // scaled flex shrink factors of all unfrozen items on the line. Set the item’s
614 // target main size to its flex base size minus a fraction of the absolute value
615 // of the remaining free space proportional to the ratio. Note this may result
616 // in a negative inner main size; it will be corrected in the next step.
617 // - Otherwise
618 // Do Nothing
619
620 if free_space.is_normal() {
621 if growing && sum_flex_grow > 0.0 {
622 unfrozen.iter_mut().for_each(|child| {
623 child.target_main_size = child.flex_basis + free_space * (child.node.flex_grow / sum_flex_grow);
624 });
625 } else if shrinking && sum_flex_shrink > 0.0 {
626 let sum_scaled_shrink_factor: f32 =
627 unfrozen.iter().map(|child| child.inner_flex_basis * child.node.flex_shrink).sum();
628
629 if sum_scaled_shrink_factor > 0.0 {
630 unfrozen.iter_mut().for_each(|child| {
631 let scaled_shrink_factor = child.inner_flex_basis * child.node.flex_shrink;
632 child.target_main_size =
633 child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor);
634 });
635 }
636 }
637 }
638
639 // d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
640 // used min and max main sizes and floor its content-box size at zero. If the
641 // item’s target main size was made smaller by this, it’s a max violation.
642 // If the item’s target main size was made larger by this, it’s a min violation.
643
644 let total_violation = unfrozen.iter_mut().fold(0.0, |acc, child| {
645 // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
646 // The following logic was developed not from the spec but by trail and error looking into how
647 // webkit handled various scenarios. Can probably be solved better by passing in
648 // min-content max-content constraints fromt the top
649 let min_main = if is_row {
650 compute_internal(
651 child.node,
652 Undefined,
653 Undefined,
654 if is_row { available_main } else { available_cross },
655 if is_row { available_cross } else { available_main },
656 percent_calc_base_child,
657 )
658 .size
659 .width
660 .maybe_min(child.width)
661 .maybe_max(child.min_width)
662 .to_number()
663 } else {
664 child.min_main
665 };
666
667 let max_main = child.max_main;
668 let clamped = child.target_main_size.maybe_min(max_main).maybe_max(min_main).max(0.0);
669 child.violation = clamped - child.target_main_size;
670 child.target_main_size = clamped;
671 child.outer_target_main_size = child.target_main_size + child.margin_main_start + child.margin_main_end;
672
673 acc + child.violation
674 });
675
676 // e. Freeze over-flexed items. The total violation is the sum of the adjustments
677 // from the previous step ∑(clamped size - unclamped size). If the total violation is:
678 // - Zero
679 // Freeze all items.
680 // - Positive
681 // Freeze all the items with min violations.
682 // - Negative
683 // Freeze all the items with max violations.
684
685 unfrozen.iter_mut().for_each(|child| match total_violation {
686 v if v > 0.0 => child.frozen = child.violation > 0.0,
687 v if v < 0.0 => child.frozen = child.violation < 0.0,
688 _ => child.frozen = true,
689 })
690
691 // f. Return to the start of this loop.
692 }
693 });
694
695 // Not part of the spec from what i can see but seems correct
696 let container_main_size = node_main.or_else({
697 let longest_line = flex_lines.iter().fold(f32::MIN, |acc, line| {
698 let length: f32 = line.items.iter().map(|item| item.outer_target_main_size).sum();
699 acc.max(length)
700 });
701
702 let size = longest_line + padding_main + border_main;
703 match available_main {
704 Defined(val) if flex_lines.len() > 1 && size < val => val,
705 _ => size,
706 }
707 });
708
709 let inner_container_main_size = container_main_size - padding_main - border_main;
710
711 // 9.4. Cross Size Determination
712
713 // 7. Determine the hypothetical cross size of each item by performing layout with the
714 // used main size and the available space, treating auto as fit-content.
715
716 flex_lines.iter_mut().for_each(|line| {
717 line.items.iter_mut().for_each(|child| {
718 let child_cross = child.cross.maybe_max(child.min_cross).maybe_min(child.max_cross);
719
720 child.hypothetical_inner_cross_size = compute_internal(
721 child.node,
722 if is_row { child.target_main_size.to_number() } else { child_cross },
723 if is_row { child_cross } else { child.target_main_size.to_number() },
724 if is_row { container_main_size.to_number() } else { available_cross },
725 if is_row { available_cross } else { container_main_size.to_number() },
726 percent_calc_base_child,
727 )
728 .size
729 .cross(node.flex_direction)
730 .maybe_max(child.min_cross)
731 .maybe_min(child.max_cross);
732
733 child.hypothetical_outer_cross_size =
734 child.hypothetical_inner_cross_size + child.margin_cross_start + child.margin_cross_end;
735 });
736 });
737
738 // TODO - probably should move this somewhere else as it doesn't make a ton of sense here but we need it below
739 // TODO - This is expensive and should only be done if we really require a baseline. aka, make it lazy
740
741 fn calc_baseline(layout: &layout::Node) -> f32 {
742 if layout.children.len() > 0 {
743 calc_baseline(&layout.children[0])
744 } else {
745 layout.height
746 }
747 };
748
749 flex_lines.iter_mut().for_each(|line| {
750 line.items.iter_mut().for_each(|child| {
751 let result = compute_internal(
752 child.node,
753 if is_row {
754 child.target_main_size.to_number()
755 } else {
756 child.hypothetical_inner_cross_size.to_number()
757 },
758 if is_row {
759 child.hypothetical_inner_cross_size.to_number()
760 } else {
761 child.target_main_size.to_number()
762 },
763 if is_row { container_main_size.to_number() } else { node_cross },
764 if is_row { node_cross } else { container_main_size.to_number() },
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 // Do a final layout pass and gather the resulting layouts
1111 let mut children: Vec<layout::Node> = {
1112 let mut lines: Vec<Vec<layout::Node>> = vec![];
1113 let mut total_offset_cross = padding_cross_start + border_cross_start;
1114
1115 {
1116 let layout_line = |line: &mut FlexLine| {
1117 let mut children: Vec<layout::Node> = vec![];
1118 let mut total_offset_main = padding_main_start + border_main_start;
1119 let line_offset_cross = line.offset_cross;
1120
1121 {
1122 let layout_item = |child: &mut FlexItem| {
1123 let result = compute_internal(
1124 child.node,
1125 if is_row {
1126 child.target_main_size.to_number()
1127 } else {
1128 child.target_cross_size.to_number()
1129 },
1130 if is_row {
1131 child.target_cross_size.to_number()
1132 } else {
1133 child.target_main_size.to_number()
1134 },
1135 if is_row { container_main_size.to_number() } else { container_cross_size.to_number() },
1136 if is_row { container_cross_size.to_number() } else { container_main_size.to_number() },
1137 percent_calc_base_child,
1138 );
1139
1140 let offset_main = total_offset_main
1141 + child.offset_main
1142 + child.margin_main_start
1143 + (child.main_start.or_else(0.0) - child.main_end.or_else(0.0));
1144
1145 let offset_cross = total_offset_cross
1146 + child.offset_cross
1147 + line_offset_cross
1148 + child.margin_cross_start
1149 + (child.cross_start.or_else(0.0) - child.cross_end.or_else(0.0));
1150
1151 children.push(layout::Node {
1152 width: result.size.width,
1153 height: result.size.height,
1154 x: if is_row { offset_main } else { offset_cross },
1155 y: if is_column { offset_main } else { offset_cross },
1156 children: result.children,
1157 });
1158
1159 total_offset_main += child.offset_main
1160 + child.margin_main_start
1161 + result.size.main(node.flex_direction)
1162 + child.margin_main_end;
1163 };
1164
1165 if node.flex_direction.is_reverse() {
1166 line.items.iter_mut().rev().for_each(layout_item);
1167 } else {
1168 line.items.iter_mut().for_each(layout_item);
1169 }
1170 }
1171
1172 total_offset_cross += line_offset_cross + line.cross_size;
1173
1174 if node.flex_direction.is_reverse() {
1175 children.reverse();
1176 }
1177
1178 lines.push(children);
1179 };
1180
1181 if is_wrap_reverse {
1182 flex_lines.iter_mut().rev().for_each(layout_line);
1183 } else {
1184 flex_lines.iter_mut().for_each(layout_line);
1185 }
1186 }
1187
1188 if is_wrap_reverse {
1189 lines.into_iter().rev().flat_map(|x| x).collect()
1190 } else {
1191 lines.into_iter().flat_map(|x| x).collect()
1192 }
1193 };
1194
1195 let container_width = if is_row { container_main_size } else { container_cross_size };
1196 let container_height = if is_column { container_main_size } else { container_cross_size };
1197
1198 // Before returning we perform absolute layout on all absolutely positioned children
1199 let mut absolute_children: Vec<layout::Node> = node
1200 .children
1201 .iter()
1202 .filter(|child| child.position == style::Position::Absolute)
1203 .map(|child| {
1204 let container_width = container_width.to_number();
1205 let container_height = container_height.to_number();
1206
1207 let start = child.start.resolve(container_width) + child.margin.start.resolve(container_width);
1208 let end = child.end.resolve(container_width) + child.margin.end.resolve(container_width);
1209 let top = child.top.resolve(container_height) + child.margin.top.resolve(container_height);
1210 let bottom = child.bottom.resolve(container_height) + child.margin.bottom.resolve(container_height);
1211
1212 let (start_main, end_main) = if is_row { (start, end) } else { (top, bottom) };
1213 let (start_cross, end_cross) = if is_row { (top, bottom) } else { (start, end) };
1214
1215 let child_width = child
1216 .width
1217 .resolve(container_width)
1218 .maybe_max(child.min_width.resolve(container_width))
1219 .maybe_min(child.max_width.resolve(container_width));
1220
1221 let child_height = child
1222 .height
1223 .resolve(container_height)
1224 .maybe_max(child.min_height.resolve(container_height))
1225 .maybe_min(child.max_height.resolve(container_height));
1226
1227 let width = child_width.or_else(container_width - start - end);
1228 let height = child_height.or_else(container_height - top - bottom);
1229
1230 let result = compute_internal(
1231 child,
1232 width,
1233 height,
1234 if is_row { container_main_size.to_number() } else { container_cross_size.to_number() },
1235 if is_row { container_cross_size.to_number() } else { container_main_size.to_number() },
1236 container_width,
1237 );
1238
1239 let free_main_space = container_main_size
1240 - result
1241 .size
1242 .main(node.flex_direction)
1243 .maybe_max(child.min_main_size(node.flex_direction).resolve(percent_calc_base_child))
1244 .maybe_min(child.max_main_size(node.flex_direction).resolve(percent_calc_base_child));
1245
1246 let free_cross_space = container_cross_size
1247 - result
1248 .size
1249 .cross(node.flex_direction)
1250 .maybe_max(child.min_cross_size(node.flex_direction).resolve(percent_calc_base_child))
1251 .maybe_min(child.max_cross_size(node.flex_direction).resolve(percent_calc_base_child));
1252
1253 let offset_main = if start_main.is_defined() {
1254 start_main.or_else(0.0) + border_main_start
1255 } else if end_main.is_defined() {
1256 free_main_space - end_main.or_else(0.0) - border_main_end
1257 } else {
1258 match node.justify_content {
1259 style::JustifyContent::SpaceBetween | style::JustifyContent::FlexStart => {
1260 padding_main_start + border_main_start
1261 }
1262 style::JustifyContent::FlexEnd => free_main_space - padding_main_end - border_main_end,
1263 style::JustifyContent::SpaceEvenly
1264 | style::JustifyContent::SpaceAround
1265 | style::JustifyContent::Center => free_main_space / 2.0,
1266 }
1267 };
1268
1269 let offset_cross = if start_cross.is_defined() {
1270 start_cross.or_else(0.0) + border_cross_start
1271 } else if end_cross.is_defined() {
1272 free_cross_space - end_cross.or_else(0.0) - border_cross_end
1273 } else {
1274 match child.align_self(node) {
1275 style::AlignSelf::Auto => 0.0, // Should never happen
1276 style::AlignSelf::FlexStart => {
1277 if is_wrap_reverse {
1278 free_cross_space - padding_cross_end - border_cross_end
1279 } else {
1280 padding_cross_start + border_cross_start
1281 }
1282 }
1283 style::AlignSelf::FlexEnd => {
1284 if is_wrap_reverse {
1285 padding_cross_start + border_cross_start
1286 } else {
1287 free_cross_space - padding_cross_end - border_cross_end
1288 }
1289 }
1290 style::AlignSelf::Center => free_cross_space / 2.0,
1291 style::AlignSelf::Baseline => free_cross_space / 2.0, // Treat as center for now until we have baseline support
1292 style::AlignSelf::Stretch => {
1293 if is_wrap_reverse {
1294 free_cross_space - padding_cross_end - border_cross_end
1295 } else {
1296 padding_cross_start + border_cross_start
1297 }
1298 }
1299 }
1300 };
1301
1302 layout::Node {
1303 width: result.size.width,
1304 height: result.size.height,
1305 x: if is_row { offset_main } else { offset_cross },
1306 y: if is_column { offset_main } else { offset_cross },
1307 children: result.children,
1308 }
1309 })
1310 .collect();
1311
1312 children.append(&mut absolute_children);
1313
1314 ComputeResult { size: FlexSize { width: container_width, height: container_height }, children }
1315}