-
Notifications
You must be signed in to change notification settings - Fork 111
/
flexbox.rs
1684 lines (1494 loc) · 73.9 KB
/
flexbox.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use core::f32;
use crate::flexbox::Number::{Defined, Undefined};
use crate::forest::{Forest, NodeData};
use crate::geometry::{Point, Rect, Size};
use crate::layout;
use crate::node::{MeasureFunc, NodeId};
use crate::number::{MinMax, OrElse};
use crate::prelude::Number;
use crate::style::{AlignContent, AlignSelf, Dimension, Display, FlexWrap, JustifyContent, PositionType};
use crate::style::{FlexDirection, Style};
use crate::sys;
#[derive(Debug, Clone)]
pub struct ComputeResult {
pub size: Size<f32>,
}
struct FlexItem {
node: NodeId,
size: Size<Number>,
min_size: Size<Number>,
max_size: Size<Number>,
position: Rect<Number>,
margin: Rect<f32>,
padding: Rect<f32>,
border: Rect<f32>,
flex_basis: f32,
inner_flex_basis: f32,
violation: f32,
frozen: bool,
hypothetical_inner_size: Size<f32>,
hypothetical_outer_size: Size<f32>,
target_size: Size<f32>,
outer_target_size: Size<f32>,
baseline: f32,
// temporary values for holding offset in the main / cross direction.
// offset is the relative position from the item's natural flow position based on
// relative position values, alignment, and justification. Does not include margin/padding/border.
offset_main: f32,
offset_cross: f32,
}
struct FlexLine<'a> {
items: &'a mut [FlexItem],
cross_size: f32,
offset_cross: f32,
}
/// Constant values that can be reused for the flexbox algorithm.
struct AlgoConstants {
dir: FlexDirection,
is_row: bool,
is_column: bool,
is_wrap_reverse: bool,
margin: Rect<f32>,
border: Rect<f32>,
padding_border: Rect<f32>,
node_inner_size: Size<Number>,
container_size: Size<f32>,
inner_container_size: Size<f32>,
}
impl Forest {
pub(crate) fn compute(&mut self, root: NodeId, size: Size<Number>) {
let style = self.nodes[root].style;
let has_root_min_max = style.min_size.width.is_defined()
|| style.min_size.height.is_defined()
|| style.max_size.width.is_defined()
|| style.max_size.height.is_defined();
let result = if has_root_min_max {
let first_pass = self.compute_internal(root, style.size.resolve(size), size, false, true);
self.compute_internal(
root,
Size {
width: first_pass
.size
.width
.maybe_max(style.min_size.width.resolve(size.width))
.maybe_min(style.max_size.width.resolve(size.width))
.into(),
height: first_pass
.size
.height
.maybe_max(style.min_size.height.resolve(size.height))
.maybe_min(style.max_size.height.resolve(size.height))
.into(),
},
size,
true,
true,
)
} else {
self.compute_internal(root, style.size.resolve(size), size, true, true)
};
self.nodes[root].layout = layout::Layout { order: 0, size: result.size, location: Point::zero() };
Self::round_layout(&mut self.nodes, &self.children, root, 0.0, 0.0);
}
fn round_layout(
nodes: &mut [NodeData],
children: &[sys::ChildrenVec<NodeId>],
root: NodeId,
abs_x: f32,
abs_y: f32,
) {
let layout = &mut nodes[root].layout;
let abs_x = abs_x + layout.location.x;
let abs_y = abs_y + layout.location.y;
layout.location.x = sys::round(layout.location.x);
layout.location.y = sys::round(layout.location.y);
layout.size.width = sys::round(abs_x + layout.size.width) - sys::round(abs_x);
layout.size.height = sys::round(abs_y + layout.size.height) - sys::round(abs_y);
for child in &children[root] {
Self::round_layout(nodes, children, *child, abs_x, abs_y);
}
}
fn cache(&mut self, node: NodeId, main_size: bool) -> &mut Option<layout::Cache> {
if main_size {
&mut self.nodes[node].main_size_layout_cache
} else {
&mut self.nodes[node].other_layout_cache
}
}
/// Try to get the computation result from the cache.
#[inline]
fn compute_from_cache(
&mut self,
node: NodeId,
node_size: Size<Number>,
parent_size: Size<Number>,
perform_layout: bool,
main_size: bool,
) -> Option<ComputeResult> {
if let Some(ref cache) = self.cache(node, main_size) {
if cache.perform_layout || !perform_layout {
let width_compatible = if let Number::Defined(width) = node_size.width {
sys::abs(width - cache.result.size.width) < f32::EPSILON
} else {
cache.node_size.width.is_undefined()
};
let height_compatible = if let Number::Defined(height) = node_size.height {
sys::abs(height - cache.result.size.height) < f32::EPSILON
} else {
cache.node_size.height.is_undefined()
};
if width_compatible && height_compatible {
return Some(cache.result.clone());
}
if cache.node_size == node_size && cache.parent_size == parent_size {
return Some(cache.result.clone());
}
}
}
None
}
/// Compute constants that can be reused during the flexbox algorithm.
#[inline]
fn compute_constants(&self, node: NodeId, node_size: Size<Number>, parent_size: Size<Number>) -> AlgoConstants {
let dir = self.nodes[node].style.flex_direction;
let is_row = dir.is_row();
let is_column = dir.is_column();
let is_wrap_reverse = self.nodes[node].style.flex_wrap == FlexWrap::WrapReverse;
let margin = self.nodes[node].style.margin.map(|n| n.resolve(parent_size.width).or_else(0.0));
let padding = self.nodes[node].style.padding.map(|n| n.resolve(parent_size.width).or_else(0.0));
let border = self.nodes[node].style.border.map(|n| n.resolve(parent_size.width).or_else(0.0));
let padding_border = Rect {
start: padding.start + border.start,
end: padding.end + border.end,
top: padding.top + border.top,
bottom: padding.bottom + border.bottom,
};
let node_inner_size = Size {
width: node_size.width - padding_border.horizontal(),
height: node_size.height - padding_border.vertical(),
};
let container_size = Size::zero();
let inner_container_size = Size::zero();
AlgoConstants {
dir,
is_row,
is_column,
is_wrap_reverse,
margin,
border,
padding_border,
node_inner_size,
container_size,
inner_container_size,
}
}
/// Generate anonymous flex items.
///
/// # [9.1. Initial Setup](https://www.w3.org/TR/css-flexbox-1/#box-manip)
///
/// - [**Generate anonymous flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-anon-box) as described in [§4 Flex Items](https://www.w3.org/TR/css-flexbox-1/#flex-items).
#[inline]
fn generate_anonymous_flex_items(&self, node: NodeId, constants: &AlgoConstants) -> sys::Vec<FlexItem> {
self.children[node]
.iter()
.map(|child| (child, &self.nodes[*child].style))
.filter(|(_, style)| style.position_type != PositionType::Absolute)
.filter(|(_, style)| style.display != Display::None)
.map(|(child, child_style)| FlexItem {
node: *child,
size: child_style.size.resolve(constants.node_inner_size),
min_size: child_style.min_size.resolve(constants.node_inner_size),
max_size: child_style.max_size.resolve(constants.node_inner_size),
position: child_style.position.zip_size(constants.node_inner_size, |p, s| p.resolve(s)),
margin: child_style.margin.map(|m| m.resolve(constants.node_inner_size.width).or_else(0.0)),
padding: child_style.padding.map(|p| p.resolve(constants.node_inner_size.width).or_else(0.0)),
border: child_style.border.map(|b| b.resolve(constants.node_inner_size.width).or_else(0.0)),
flex_basis: 0.0,
inner_flex_basis: 0.0,
violation: 0.0,
frozen: false,
hypothetical_inner_size: Size::zero(),
hypothetical_outer_size: Size::zero(),
target_size: Size::zero(),
outer_target_size: Size::zero(),
baseline: 0.0,
offset_main: 0.0,
offset_cross: 0.0,
})
.collect()
}
/// Determine the available main and cross space for the flex items.
///
/// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
///
/// - [**Determine the available main and cross space for the flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-available).
/// For each dimension, if that dimension of the flex container’s content box is a definite size, use that;
/// if that dimension of the flex container is being sized under a min or max-content constraint, the available space in that dimension is that constraint;
/// otherwise, subtract the flex container’s margin, border, and padding from the space available to the flex container in that dimension and use that value.
/// **This might result in an infinite value**.
#[inline]
fn determine_available_space(
node_size: Size<Number>,
parent_size: Size<Number>,
constants: &AlgoConstants,
) -> Size<Number> {
Size {
width: node_size.width.or_else(parent_size.width - constants.margin.horizontal())
- constants.padding_border.horizontal(),
height: node_size.height.or_else(parent_size.height - constants.margin.vertical())
- constants.padding_border.vertical(),
}
}
/// Determine the flex base size and hypothetical main size of each item.
///
/// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
///
/// - [**Determine the flex base size and hypothetical main size of each item:**](https://www.w3.org/TR/css-flexbox-1/#algo-main-item)
///
/// - A. If the item has a definite used flex basis, that’s the flex base size.
///
/// - B. If the flex item has ...
///
/// - an intrinsic aspect ratio,
/// - a used flex basis of content, and
/// - a definite cross size,
///
/// then the flex base size is calculated from its inner cross size and the flex item’s intrinsic aspect ratio.
///
/// - C. If the used flex basis is content or depends on its available space, and the flex container is being sized under a min-content
/// or max-content constraint (e.g. when performing automatic table layout \[CSS21\]), size the item under that constraint.
/// The flex base size is the item’s resulting main size.
///
/// - E. Otherwise, size the item into the available space using its used flex basis in place of its main size, treating a value of content as max-content.
/// If a cross size is needed to determine the main size (e.g. when the flex item’s main size is in its block axis) and the flex item’s cross size is auto and not definite,
/// in this calculation use fit-content as the flex item’s cross size. The flex base size is the item’s resulting main size.
///
/// When determining the flex base size, the item’s min and max main sizes are ignored (no clamping occurs).
/// Furthermore, the sizing calculations that floor the content box size at zero when applying box-sizing are also ignored.
/// (For example, an item with a specified size of zero, positive padding, and box-sizing: border-box will have an outer flex base size of zero—and hence a negative inner flex base size.)
#[inline]
fn determine_flex_base_size(
&mut self,
node: NodeId,
node_size: Size<Number>,
constants: &AlgoConstants,
available_space: Size<Number>,
flex_items: &mut sys::Vec<FlexItem>,
) {
// TODO - this does not follow spec. See the TODOs below
for child in flex_items.iter_mut() {
let child_style = self.nodes[child.node].style;
// A. If the item has a definite used flex basis, that’s the flex base size.
let flex_basis = child_style.flex_basis.resolve(constants.node_inner_size.main(constants.dir));
if flex_basis.is_defined() {
child.flex_basis = flex_basis.or_else(0.0);
continue;
};
// B. If the flex item has an intrinsic aspect ratio,
// a used flex basis of content, and a definite cross size,
// then the flex base size is calculated from its inner
// cross size and the flex item’s intrinsic aspect ratio.
if let Defined(ratio) = child_style.aspect_ratio {
if let Defined(cross) = node_size.cross(constants.dir) {
if child_style.flex_basis == Dimension::Auto {
child.flex_basis = cross * ratio;
continue;
}
}
}
// C. If the used flex basis is content or depends on its available space,
// and the flex container is being sized under a min-content or max-content
// constraint (e.g. when performing automatic table layout [CSS21]),
// size the item under that constraint. The flex base size is the item’s
// resulting main size.
// TODO - Probably need to cover this case in future
// D. Otherwise, if the used flex basis is content or depends on its
// available space, the available main size is infinite, and the flex item’s
// inline axis is parallel to the main axis, lay the item out using the rules
// for a box in an orthogonal flow [CSS3-WRITING-MODES]. The flex base size
// is the item’s max-content main size.
// TODO - Probably need to cover this case in future
// E. Otherwise, size the item into the available space using its used flex basis
// in place of its main size, treating a value of content as max-content.
// If a cross size is needed to determine the main size (e.g. when the
// flex item’s main size is in its block axis) and the flex item’s cross size
// is auto and not definite, in this calculation use fit-content as the
// flex item’s cross size. The flex base size is the item’s resulting main size.
let width: Number = if !child.size.width.is_defined()
&& child_style.align_self(&self.nodes[node].style) == AlignSelf::Stretch
&& constants.is_column
{
available_space.width
} else {
child.size.width
};
let height: Number = if !child.size.height.is_defined()
&& child_style.align_self(&self.nodes[node].style) == AlignSelf::Stretch
&& constants.is_row
{
available_space.height
} else {
child.size.height
};
child.flex_basis = self
.compute_internal(
child.node,
Size {
width: width.maybe_max(child.min_size.width).maybe_min(child.max_size.width),
height: height.maybe_max(child.min_size.height).maybe_min(child.max_size.height),
},
available_space,
false,
true,
)
.size
.main(constants.dir)
.maybe_max(child.min_size.main(constants.dir))
.maybe_min(child.max_size.main(constants.dir));
}
// The hypothetical main size is the item’s flex base size clamped according to its
// used min and max main sizes (and flooring the content box size at zero).
for child in flex_items {
child.inner_flex_basis =
child.flex_basis - child.padding.main(constants.dir) - child.border.main(constants.dir);
// TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
// The following logic was developed not from the spec but by trail and error looking into how
// webkit handled various scenarios. Can probably be solved better by passing in
// min-content max-content constraints from the top
let min_main = self
.compute_internal(child.node, Size::undefined(), available_space, false, false)
.size
.main(constants.dir)
.maybe_max(child.min_size.main(constants.dir))
.maybe_min(child.size.main(constants.dir))
.into();
child.hypothetical_inner_size.set_main(
constants.dir,
child.flex_basis.maybe_max(min_main).maybe_min(child.max_size.main(constants.dir)),
);
child.hypothetical_outer_size.set_main(
constants.dir,
child.hypothetical_inner_size.main(constants.dir) + child.margin.main(constants.dir),
);
}
}
/// Collect flex items into flex lines.
///
/// # [9.3. Main Size Determination](https://www.w3.org/TR/css-flexbox-1/#main-sizing)
///
/// - [**Collect flex items into flex lines**](https://www.w3.org/TR/css-flexbox-1/#algo-line-break):
///
/// - If the flex container is single-line, collect all the flex items into a single flex line.
///
/// - Otherwise, starting from the first uncollected item, collect consecutive items one by one until the first time that the next collected item would not fit into the flex container’s inner main size
/// (or until a forced break is encountered, see [§10 Fragmenting Flex Layout](https://www.w3.org/TR/css-flexbox-1/#pagination)).
/// If the very first uncollected item wouldn’t fit, collect just it into the line.
///
/// For this step, the size of a flex item is its outer hypothetical main size. (**Note: This can be negative**.)
///
/// Repeat until all flex items have been collected into flex lines.
///
/// **Note that the "collect as many" line will collect zero-sized flex items onto the end of the previous line even if the last non-zero item exactly "filled up" the line**.
#[inline]
fn collect_flex_lines<'a>(
&self,
node: NodeId,
constants: &AlgoConstants,
available_space: Size<Number>,
flex_items: &'a mut sys::Vec<FlexItem>,
) -> sys::Vec<FlexLine<'a>> {
let mut lines = sys::new_vec_with_capacity(1);
if self.nodes[node].style.flex_wrap == FlexWrap::NoWrap {
lines.push(FlexLine { items: flex_items.as_mut_slice(), cross_size: 0.0, offset_cross: 0.0 });
} else {
let mut flex_items = &mut flex_items[..];
while !flex_items.is_empty() {
let mut line_length = 0.0;
let index = flex_items
.iter()
.enumerate()
.find(|&(idx, child)| {
line_length += child.hypothetical_outer_size.main(constants.dir);
if let Defined(main) = available_space.main(constants.dir) {
line_length > main && idx != 0
} else {
false
}
})
.map(|(idx, _)| idx)
.unwrap_or(flex_items.len());
let (items, rest) = flex_items.split_at_mut(index);
lines.push(FlexLine { items, cross_size: 0.0, offset_cross: 0.0 });
flex_items = rest;
}
}
lines
}
/// Resolve the flexible lengths of the items within a flex line.
///
/// # [9.7. Resolving Flexible Lengths](https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-lengths)
#[inline]
fn resolve_flexible_lengths(
&mut self,
line: &mut FlexLine,
constants: &AlgoConstants,
available_space: Size<Number>,
) {
// 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
// items on the line. If the sum is less than the flex container’s inner main size,
// use the flex grow factor for the rest of this algorithm; otherwise, use the
// flex shrink factor.
let used_flex_factor: f32 =
line.items.iter().map(|child| child.hypothetical_outer_size.main(constants.dir)).sum();
let growing = used_flex_factor < constants.node_inner_size.main(constants.dir).or_else(0.0);
let shrinking = !growing;
// 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
// - Any item that has a flex factor of zero
// - If using the flex grow factor: any item that has a flex base size
// greater than its hypothetical main size
// - If using the flex shrink factor: any item that has a flex base size
// smaller than its hypothetical main size
for child in line.items.iter_mut() {
// TODO - This is not found by reading the spec. Maybe this can be done in some other place
// instead. This was found by trail and error fixing tests to align with webkit output.
if constants.node_inner_size.main(constants.dir).is_undefined() && constants.is_row {
child.target_size.set_main(
constants.dir,
self.compute_internal(
child.node,
Size {
width: child.size.width.maybe_max(child.min_size.width).maybe_min(child.max_size.width),
height: child.size.height.maybe_max(child.min_size.height).maybe_min(child.max_size.height),
},
available_space,
false,
false,
)
.size
.main(constants.dir)
.maybe_max(child.min_size.main(constants.dir))
.maybe_min(child.max_size.main(constants.dir)),
);
} else {
child.target_size.set_main(constants.dir, child.hypothetical_inner_size.main(constants.dir));
}
// TODO this should really only be set inside the if-statement below but
// that causes the target_main_size to never be set for some items
child
.outer_target_size
.set_main(constants.dir, child.target_size.main(constants.dir) + child.margin.main(constants.dir));
let child_style = &self.nodes[child.node].style;
if (child_style.flex_grow == 0.0 && child_style.flex_shrink == 0.0)
|| (growing && child.flex_basis > child.hypothetical_inner_size.main(constants.dir))
|| (shrinking && child.flex_basis < child.hypothetical_inner_size.main(constants.dir))
{
child.frozen = true;
}
}
// 3. Calculate initial free space. Sum the outer sizes of all items on the line,
// and subtract this from the flex container’s inner main size. For frozen items,
// use their outer target main size; for other items, use their outer flex base size.
let used_space: f32 = line
.items
.iter()
.map(|child| {
child.margin.main(constants.dir)
+ if child.frozen { child.target_size.main(constants.dir) } else { child.flex_basis }
})
.sum();
let initial_free_space = (constants.node_inner_size.main(constants.dir) - used_space).or_else(0.0);
// 4. Loop
loop {
// a. Check for flexible items. If all the flex items on the line are frozen,
// free space has been distributed; exit this loop.
if line.items.iter().all(|child| child.frozen) {
break;
}
// b. Calculate the remaining free space as for initial free space, above.
// If the sum of the unfrozen flex items’ flex factors is less than one,
// multiply the initial free space by this sum. If the magnitude of this
// value is less than the magnitude of the remaining free space, use this
// as the remaining free space.
let used_space: f32 = line
.items
.iter()
.map(|child| {
child.margin.main(constants.dir)
+ if child.frozen { child.target_size.main(constants.dir) } else { child.flex_basis }
})
.sum();
let mut unfrozen: sys::Vec<&mut FlexItem> = line.items.iter_mut().filter(|child| !child.frozen).collect();
let (sum_flex_grow, sum_flex_shrink): (f32, f32) =
unfrozen.iter().fold((0.0, 0.0), |(flex_grow, flex_shrink), item| {
let style = &self.nodes[item.node].style;
(flex_grow + style.flex_grow, flex_shrink + style.flex_shrink)
});
let free_space = if growing && sum_flex_grow < 1.0 {
(initial_free_space * sum_flex_grow)
.maybe_min(constants.node_inner_size.main(constants.dir) - used_space)
} else if shrinking && sum_flex_shrink < 1.0 {
(initial_free_space * sum_flex_shrink)
.maybe_max(constants.node_inner_size.main(constants.dir) - used_space)
} else {
(constants.node_inner_size.main(constants.dir) - used_space).or_else(0.0)
};
// c. Distribute free space proportional to the flex factors.
// - If the remaining free space is zero
// Do Nothing
// - If using the flex grow factor
// Find the ratio of the item’s flex grow factor to the sum of the
// flex grow factors of all unfrozen items on the line. Set the item’s
// target main size to its flex base size plus a fraction of the remaining
// free space proportional to the ratio.
// - If using the flex shrink factor
// For every unfrozen item on the line, multiply its flex shrink factor by
// its inner flex base size, and note this as its scaled flex shrink factor.
// Find the ratio of the item’s scaled flex shrink factor to the sum of the
// scaled flex shrink factors of all unfrozen items on the line. Set the item’s
// target main size to its flex base size minus a fraction of the absolute value
// of the remaining free space proportional to the ratio. Note this may result
// in a negative inner main size; it will be corrected in the next step.
// - Otherwise
// Do Nothing
if free_space.is_normal() {
if growing && sum_flex_grow > 0.0 {
for child in &mut unfrozen {
child.target_size.set_main(
constants.dir,
child.flex_basis + free_space * (self.nodes[child.node].style.flex_grow / sum_flex_grow),
);
}
} else if shrinking && sum_flex_shrink > 0.0 {
let sum_scaled_shrink_factor: f32 = unfrozen
.iter()
.map(|child| child.inner_flex_basis * self.nodes[child.node].style.flex_shrink)
.sum();
if sum_scaled_shrink_factor > 0.0 {
for child in &mut unfrozen {
let scaled_shrink_factor =
child.inner_flex_basis * self.nodes[child.node].style.flex_shrink;
child.target_size.set_main(
constants.dir,
child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor),
)
}
}
}
}
// d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
// used min and max main sizes and floor its content-box size at zero. If the
// item’s target main size was made smaller by this, it’s a max violation.
// If the item’s target main size was made larger by this, it’s a min violation.
let total_violation = unfrozen.iter_mut().fold(0.0, |acc, child| -> f32 {
// TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
// The following logic was developed not from the spec but by trail and error looking into how
// webkit handled various scenarios. Can probably be solved better by passing in
// min-content max-content constraints from the top. Need to figure out correct thing to do here as
// just piling on more conditionals.
let min_main = if constants.is_row && self.nodes[child.node].measure.is_none() {
self.compute_internal(child.node, Size::undefined(), available_space, false, false)
.size
.width
.maybe_min(child.size.width)
.maybe_max(child.min_size.width)
.into()
} else {
child.min_size.main(constants.dir)
};
let max_main = child.max_size.main(constants.dir);
let clamped = child.target_size.main(constants.dir).maybe_min(max_main).maybe_max(min_main).max(0.0);
child.violation = clamped - child.target_size.main(constants.dir);
child.target_size.set_main(constants.dir, clamped);
child
.outer_target_size
.set_main(constants.dir, child.target_size.main(constants.dir) + child.margin.main(constants.dir));
acc + child.violation
});
// e. Freeze over-flexed items. The total violation is the sum of the adjustments
// from the previous step ∑(clamped size - unclamped size). If the total violation is:
// - Zero
// Freeze all items.
// - Positive
// Freeze all the items with min violations.
// - Negative
// Freeze all the items with max violations.
for child in &mut unfrozen {
match total_violation {
v if v > 0.0 => child.frozen = child.violation > 0.0,
v if v < 0.0 => child.frozen = child.violation < 0.0,
_ => child.frozen = true,
}
}
// f. Return to the start of this loop.
}
}
/// Determine the hypothetical cross size of each item.
///
/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
///
/// - [**Determine the hypothetical cross size of each item**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-item)
/// by performing layout with the used main size and the available space, treating auto as fit-content.
#[inline]
fn determine_hypothetical_cross_size(
&mut self,
line: &mut FlexLine,
constants: &AlgoConstants,
available_space: Size<Number>,
) {
for child in line.items.iter_mut() {
let child_cross = child
.size
.cross(constants.dir)
.maybe_max(child.min_size.cross(constants.dir))
.maybe_min(child.max_size.cross(constants.dir));
child.hypothetical_inner_size.set_cross(
constants.dir,
self.compute_internal(
child.node,
Size {
width: if constants.is_row { child.target_size.width.into() } else { child_cross },
height: if constants.is_row { child_cross } else { child.target_size.height.into() },
},
Size {
width: if constants.is_row {
constants.container_size.main(constants.dir).into()
} else {
available_space.width
},
height: if constants.is_row {
available_space.height
} else {
constants.container_size.main(constants.dir).into()
},
},
false,
false,
)
.size
.cross(constants.dir)
.maybe_max(child.min_size.cross(constants.dir))
.maybe_min(child.max_size.cross(constants.dir)),
);
child.hypothetical_outer_size.set_cross(
constants.dir,
child.hypothetical_inner_size.cross(constants.dir) + child.margin.cross(constants.dir),
);
}
}
/// Calculate the base lines of the children.
#[inline]
fn calculate_children_base_lines(
&mut self,
node: NodeId,
node_size: Size<Number>,
flex_lines: &mut [FlexLine],
constants: &AlgoConstants,
) {
fn calc_baseline(db: &Forest, node: NodeId, layout: &layout::Layout) -> f32 {
if db.children[node].is_empty() {
layout.size.height
} else {
let child = db.children[node][0];
calc_baseline(db, child, &db.nodes[child].layout)
}
}
for line in flex_lines {
for child in line.items.iter_mut() {
let result = self.compute_internal(
child.node,
Size {
width: if constants.is_row {
child.target_size.width.into()
} else {
child.hypothetical_inner_size.width.into()
},
height: if constants.is_row {
child.hypothetical_inner_size.height.into()
} else {
child.target_size.height.into()
},
},
Size {
width: if constants.is_row { constants.container_size.width.into() } else { node_size.width },
height: if constants.is_row {
node_size.height
} else {
constants.container_size.height.into()
},
},
true,
false,
);
child.baseline = calc_baseline(
self,
child.node,
&layout::Layout {
order: self.children[node].iter().position(|n| *n == child.node).unwrap() as u32,
size: result.size,
location: Point::zero(),
},
);
}
}
}
/// Calculate the cross size of each flex line.
///
/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
///
/// - [**Calculate the cross size of each flex line**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-line).
///
/// If the flex container is single-line and has a definite cross size, the cross size of the flex line is the flex container’s inner cross size.
///
/// Otherwise, for each flex line:
///
/// 1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose align-self is baseline, and whose cross-axis margins are both non-auto.
/// Find the largest of the distances between each item’s baseline and its hypothetical outer cross-start edge,
/// and the largest of the distances between each item’s baseline and its hypothetical outer cross-end edge, and sum these two values.
///
/// 2. Among all the items not collected by the previous step, find the largest outer hypothetical cross size.
///
/// 3. The used cross-size of the flex line is the largest of the numbers found in the previous two steps and zero.
///
/// If the flex container is single-line, then clamp the line’s cross-size to be within the container’s computed min and max cross sizes.
/// **Note that if CSS 2.1’s definition of min/max-width/height applied more generally, this behavior would fall out automatically**.
#[inline]
fn calculate_cross_size(
&mut self,
flex_lines: &mut [FlexLine],
node: NodeId,
node_size: Size<Number>,
constants: &AlgoConstants,
) {
if flex_lines.len() == 1 && node_size.cross(constants.dir).is_defined() {
flex_lines[0].cross_size =
(node_size.cross(constants.dir) - constants.padding_border.cross(constants.dir)).or_else(0.0);
} else {
for line in flex_lines.iter_mut() {
// 1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose
// align-self is baseline, and whose cross-axis margins are both non-auto. Find the
// largest of the distances between each item’s baseline and its hypothetical outer
// cross-start edge, and the largest of the distances between each item’s baseline
// and its hypothetical outer cross-end edge, and sum these two values.
// 2. Among all the items not collected by the previous step, find the largest
// outer hypothetical cross size.
// 3. The used cross-size of the flex line is the largest of the numbers found in the
// previous two steps and zero.
let max_baseline: f32 = line.items.iter().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
line.cross_size = line
.items
.iter()
.map(|child| {
let child_style = &self.nodes[child.node].style;
if child_style.align_self(&self.nodes[node].style) == AlignSelf::Baseline
&& child_style.cross_margin_start(constants.dir) != Dimension::Auto
&& child_style.cross_margin_end(constants.dir) != Dimension::Auto
&& child_style.cross_size(constants.dir) == Dimension::Auto
{
max_baseline - child.baseline + child.hypothetical_outer_size.cross(constants.dir)
} else {
child.hypothetical_outer_size.cross(constants.dir)
}
})
.fold(0.0, |acc, x| acc.max(x));
}
}
}
/// Handle 'align-content: stretch'.
///
/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
///
/// - [**Handle 'align-content: stretch'**](https://www.w3.org/TR/css-flexbox-1/#algo-line-stretch). If the flex container has a definite cross size, align-content is stretch,
/// and the sum of the flex lines' cross sizes is less than the flex container’s inner cross size,
/// increase the cross size of each flex line by equal amounts such that the sum of their cross sizes exactly equals the flex container’s inner cross size.
#[inline]
fn handle_align_content_stretch(
&mut self,
flex_lines: &mut [FlexLine],
node: NodeId,
node_size: Size<Number>,
constants: &AlgoConstants,
) {
if self.nodes[node].style.align_content == AlignContent::Stretch && node_size.cross(constants.dir).is_defined()
{
let total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
let inner_cross =
(node_size.cross(constants.dir) - constants.padding_border.cross(constants.dir)).or_else(0.0);
if total_cross < inner_cross {
let remaining = inner_cross - total_cross;
let addition = remaining / flex_lines.len() as f32;
flex_lines.iter_mut().for_each(|line| line.cross_size += addition);
}
}
}
/// Determine the used cross size of each flex item.
///
/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
///
/// - [**Determine the used cross size of each flex item**](https://www.w3.org/TR/css-flexbox-1/#algo-stretch). If a flex item has align-self: stretch, its computed cross size property is auto,
/// and neither of its cross-axis margins are auto, the used outer cross size is the used cross size of its flex line, clamped according to the item’s used min and max cross sizes.
/// Otherwise, the used cross size is the item’s hypothetical cross size.
///
/// If the flex item has align-self: stretch, redo layout for its contents, treating this used size as its definite cross size so that percentage-sized children can be resolved.
///
/// **Note that this step does not affect the main size of the flex item, even if it has an intrinsic aspect ratio**.
#[inline]
fn determine_used_cross_size(&mut self, flex_lines: &mut [FlexLine], node: NodeId, constants: &AlgoConstants) {
for line in flex_lines {
let line_cross_size = line.cross_size;
for child in line.items.iter_mut() {
let child_style = &self.nodes[child.node].style;
child.target_size.set_cross(
constants.dir,
if child_style.align_self(&self.nodes[node].style) == AlignSelf::Stretch
&& child_style.cross_margin_start(constants.dir) != Dimension::Auto
&& child_style.cross_margin_end(constants.dir) != Dimension::Auto
&& child_style.cross_size(constants.dir) == Dimension::Auto
{
(line_cross_size - child.margin.cross(constants.dir))
.maybe_max(child.min_size.cross(constants.dir))
.maybe_min(child.max_size.cross(constants.dir))
} else {
child.hypothetical_inner_size.cross(constants.dir)
},
);
child.outer_target_size.set_cross(
constants.dir,
child.target_size.cross(constants.dir) + child.margin.cross(constants.dir),
);
}
}
}
/// Distribute any remaining free space.
///
/// # [9.5. Main-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#main-alignment)
///
/// - [**Distribute any remaining free space**](https://www.w3.org/TR/css-flexbox-1/#algo-main-align). For each flex line:
///
/// 1. If the remaining free space is positive and at least one main-axis margin on this line is `auto`, distribute the free space equally among these margins.
/// Otherwise, set all `auto` margins to zero.
///
/// 2. Align the items along the main-axis per `justify-content`.
#[inline]
fn distribute_remaining_free_space(
&mut self,
flex_lines: &mut [FlexLine],
node: NodeId,
constants: &AlgoConstants,
) {
for line in flex_lines {
let used_space: f32 = line.items.iter().map(|child| child.outer_target_size.main(constants.dir)).sum();
let free_space = constants.inner_container_size.main(constants.dir) - used_space;
let mut num_auto_margins = 0;
for child in line.items.iter_mut() {
let child_style = &self.nodes[child.node].style;
if child_style.main_margin_start(constants.dir) == Dimension::Auto {
num_auto_margins += 1;
}
if child_style.main_margin_end(constants.dir) == Dimension::Auto {
num_auto_margins += 1;
}
}