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