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