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