/
flex.dart
2781 lines (2479 loc) · 102 KB
/
flex.dart
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
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:kraken/module.dart';
import 'package:kraken/rendering.dart';
import 'package:kraken/dom.dart';
import 'package:kraken/css.dart';
/// Infos of each run (flex line) in flex layout
/// https://www.w3.org/TR/css-flexbox-1/#flex-lines
class _RunMetrics {
_RunMetrics(
this.mainAxisExtent,
this.crossAxisExtent,
double totalFlexGrow,
double totalFlexShrink,
this.baselineExtent,
this.runChildren,
double remainingFreeSpace,
) : _totalFlexGrow = totalFlexGrow,
_totalFlexShrink = totalFlexShrink,
_remainingFreeSpace = remainingFreeSpace;
// Main size extent of the run
final double mainAxisExtent;
// Cross size extent of the run
final double crossAxisExtent;
// Total flex grow factor in the run
double get totalFlexGrow => _totalFlexGrow;
double _totalFlexGrow;
set totalFlexGrow(double value) {
if (_totalFlexGrow != value) {
_totalFlexGrow = value;
}
}
// Total flex shrink factor in the run
double get totalFlexShrink => _totalFlexShrink;
double _totalFlexShrink;
set totalFlexShrink(double value) {
if (_totalFlexShrink != value) {
_totalFlexShrink = value;
}
}
// Max extent above each flex items in the run
final double baselineExtent;
// All the children RenderBox of layout in the run
final Map<int?, _RunChild> runChildren;
// Remaining free space in the run
double get remainingFreeSpace => _remainingFreeSpace;
double _remainingFreeSpace = 0;
set remainingFreeSpace(double value) {
if (_remainingFreeSpace != value) {
_remainingFreeSpace = value;
}
}
}
/// Infos about Flex item in the run
class _RunChild {
_RunChild(
RenderBox child,
double originalMainSize,
double adjustedMainSize,
bool frozen,
) : _child = child,
_originalMainSize = originalMainSize,
_adjustedMainSize = adjustedMainSize,
_frozen = frozen;
/// Render object of flex item
RenderBox get child => _child;
RenderBox _child;
set child(RenderBox value) {
if (_child != value) {
_child = value;
}
}
/// Original main size on first layout
double get originalMainSize => _originalMainSize;
double _originalMainSize;
set originalMainSize(double value) {
if (_originalMainSize != value) {
_originalMainSize = value;
}
}
/// Adjusted main size after flexible length resolve algorithm
double get adjustedMainSize => _adjustedMainSize;
double _adjustedMainSize;
set adjustedMainSize(double value) {
if (_adjustedMainSize != value) {
_adjustedMainSize = value;
}
}
/// Whether flex item should be frozen in flexible length resolve algorithm
bool get frozen => _frozen;
bool _frozen = false;
set frozen(bool value) {
if (_frozen != value) {
_frozen = value;
}
}
}
bool? _startIsTopLeft(FlexDirection direction) {
switch (direction) {
case FlexDirection.column:
case FlexDirection.row:
return true;
case FlexDirection.rowReverse:
case FlexDirection.columnReverse:
return false;
}
}
/// ## Layout algorithm
///
/// _This section describes how the framework causes [RenderFlexLayout] to position
/// its children._
///
/// Layout for a [RenderFlexLayout] proceeds in 5 steps:
///
/// 1. Layout placeholder child of positioned element(absolute/fixed) in new layer
/// 2. Layout no positioned children with no constraints, compare children width with flex container main axis extent
/// to caculate total flex lines
/// 3. Caculate horizontal constraints of each child according to availabe horizontal space in each flex line
/// and flex-grow and flex-shrink properties
/// 4. Caculate vertical constraints of each child accordint to availabe vertical space in flex container vertial
/// and align-content properties and set
/// 5. Layout children again with above cacluated constraints
/// 6. Caculate flex line leading space and between space and position children in each flex line
///
class RenderFlexLayout extends RenderLayoutBox {
/// Creates a flex render object.
///
/// By default, the flex layout is horizontal and children are aligned to the
/// start of the main axis and the center of the cross axis.
RenderFlexLayout({
List<RenderBox>? children,
required RenderStyle renderStyle,
required ElementDelegate elementDelegate
}) : super(
renderStyle: renderStyle,
elementDelegate: elementDelegate
) {
addAll(children);
}
// Set during layout if overflow occurred on the main axis.
double? _overflow;
// Check whether any meaningful overflow is present. Values below an epsilon
// are treated as not overflowing.
bool get _hasOverflow => _overflow != null && _overflow! > precisionErrorTolerance;
/// Flex line boxs of flex layout
List<_RunMetrics> flexLineBoxMetrics = <_RunMetrics>[];
/// Cache the intrinsic size of children before flex-grow/flex-shrink
/// to avoid relayout when style of flex items changes
Map<int, double> childrenIntrinsicMainSizes = {};
/// Cache original constraints of children on the first layout
Map<int, BoxConstraints> childrenOldConstraints = {};
@override
void setupParentData(RenderBox child) {
if (child.parentData is! RenderLayoutParentData) {
child.parentData = RenderLayoutParentData();
}
if (child is RenderBoxModel) {
child.parentData = CSSPositionedLayout.getPositionParentData(
child, child.parentData as RenderLayoutParentData);
}
}
double _getIntrinsicSize({
FlexDirection? sizingDirection,
double?
extent, // the extent in the direction that isn't the sizing direction
double Function(RenderBox child, double? extent)?
childSize, // a method to find the size in the sizing direction
}) {
if (renderStyle.flexDirection == sizingDirection) {
// INTRINSIC MAIN SIZE
// Intrinsic main size is the smallest size the flex container can take
// while maintaining the min/max-content contributions of its flex items.
double totalFlexGrow = 0.0;
double inflexibleSpace = 0.0;
double maxFlexFractionSoFar = 0.0;
RenderBox? child = firstChild;
while (child != null) {
final double flex = _getFlexGrow(child);
totalFlexGrow += flex;
if (flex > 0) {
final double flexFraction =
childSize!(child, extent) / _getFlexGrow(child);
maxFlexFractionSoFar = math.max(maxFlexFractionSoFar, flexFraction);
} else {
inflexibleSpace += childSize!(child, extent);
}
final RenderLayoutParentData childParentData =
child.parentData as RenderLayoutParentData;
child = childParentData.nextSibling;
}
return maxFlexFractionSoFar * totalFlexGrow + inflexibleSpace;
} else {
// INTRINSIC CROSS SIZE
// Intrinsic cross size is the max of the intrinsic cross sizes of the
// children, after the flexible children are fit into the available space,
// with the children sized using their max intrinsic dimensions.
// Get inflexible space using the max intrinsic dimensions of fixed children in the main direction.
final double? availableMainSpace = extent;
double totalFlexGrow = 0;
double inflexibleSpace = 0.0;
double maxCrossSize = 0.0;
RenderBox? child = firstChild;
while (child != null) {
final double flex = _getFlexGrow(child);
totalFlexGrow += flex;
double? mainSize;
late double crossSize;
if (flex == 0) {
switch (renderStyle.flexDirection) {
case FlexDirection.rowReverse:
case FlexDirection.row:
mainSize = child.getMaxIntrinsicWidth(double.infinity);
crossSize = childSize!(child, mainSize);
break;
case FlexDirection.column:
case FlexDirection.columnReverse:
mainSize = child.getMaxIntrinsicHeight(double.infinity);
crossSize = childSize!(child, mainSize);
break;
}
inflexibleSpace += mainSize;
maxCrossSize = math.max(maxCrossSize, crossSize);
}
final RenderLayoutParentData childParentData =
child.parentData as RenderLayoutParentData;
child = childParentData.nextSibling;
}
// Determine the spacePerFlex by allocating the remaining available space.
// When you're overconstrained spacePerFlex can be negative.
final double spacePerFlex = math.max(
0.0, (availableMainSpace! - inflexibleSpace) / totalFlexGrow);
// Size remaining (flexible) items, find the maximum cross size.
child = firstChild;
while (child != null) {
final double flex = _getFlexGrow(child);
if (flex > 0)
maxCrossSize =
math.max(maxCrossSize, childSize!(child, spacePerFlex * flex));
final RenderLayoutParentData childParentData =
child.parentData as RenderLayoutParentData;
child = childParentData.nextSibling;
}
return maxCrossSize;
}
}
/// Get start/end padding in the main axis according to flex direction
double flowAwareMainAxisPadding({bool isEnd = false}) {
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return isEnd ? renderStyle.paddingRight : renderStyle.paddingLeft;
} else {
return isEnd ? renderStyle.paddingBottom : renderStyle.paddingTop;
}
}
/// Get start/end padding in the cross axis according to flex direction
double flowAwareCrossAxisPadding({bool isEnd = false}) {
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return isEnd ? renderStyle.paddingBottom : renderStyle.paddingTop;
} else {
return isEnd ? renderStyle.paddingRight : renderStyle.paddingLeft;
}
}
/// Get start/end border in the main axis according to flex direction
double flowAwareMainAxisBorder({bool isEnd = false}) {
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return isEnd ? renderStyle.borderRight : renderStyle.borderLeft;
} else {
return isEnd ? renderStyle.borderBottom : renderStyle.borderTop;
}
}
/// Get start/end border in the cross axis according to flex direction
double flowAwareCrossAxisBorder({bool isEnd = false}) {
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return isEnd ? renderStyle.borderBottom : renderStyle.borderTop;
} else {
return isEnd ? renderStyle.borderRight : renderStyle.borderLeft;
}
}
/// Get start/end margin of child in the main axis according to flex direction
double? flowAwareChildMainAxisMargin(RenderBox child, {bool isEnd = false}) {
RenderBoxModel? childRenderBoxModel;
if (child is RenderBoxModel) {
childRenderBoxModel = child;
}
if (childRenderBoxModel == null) {
return 0;
}
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return isEnd
? childRenderBoxModel.renderStyle.marginRight.length
: childRenderBoxModel.renderStyle.marginLeft.length;
} else {
return isEnd
? childRenderBoxModel.renderStyle.marginBottom.length
: childRenderBoxModel.renderStyle.marginTop.length;
}
}
/// Get start/end margin of child in the cross axis according to flex direction
double? flowAwareChildCrossAxisMargin(RenderBox child, {bool isEnd = false}) {
RenderBoxModel? childRenderBoxModel;
if (child is RenderBoxModel) {
childRenderBoxModel = child;
}
if (childRenderBoxModel == null) {
return 0;
}
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return isEnd
? childRenderBoxModel.renderStyle.marginBottom.length
: childRenderBoxModel.renderStyle.marginTop.length;
} else {
return isEnd
? childRenderBoxModel.renderStyle.marginRight.length
: childRenderBoxModel.renderStyle.marginLeft.length;
}
}
@override
double computeMinIntrinsicWidth(double height) {
return _getIntrinsicSize(
sizingDirection: FlexDirection.row,
extent: height,
childSize: (RenderBox child, double? extent) =>
child.getMinIntrinsicWidth(extent!),
);
}
@override
double computeMaxIntrinsicWidth(double height) {
return _getIntrinsicSize(
sizingDirection: FlexDirection.row,
extent: height,
childSize: (RenderBox child, double? extent) =>
child.getMaxIntrinsicWidth(extent!),
);
}
@override
double computeMinIntrinsicHeight(double width) {
return _getIntrinsicSize(
sizingDirection: FlexDirection.column,
extent: width,
childSize: (RenderBox child, double? extent) =>
child.getMinIntrinsicHeight(extent!),
);
}
@override
double computeMaxIntrinsicHeight(double width) {
return _getIntrinsicSize(
sizingDirection: FlexDirection.column,
extent: width,
childSize: (RenderBox child, double? extent) =>
child.getMaxIntrinsicHeight(extent!),
);
}
double _getFlexGrow(RenderBox child) {
// Flex shrink has no effect on placeholder of positioned element
if (child is RenderPositionHolder) {
return 0;
}
return child is RenderBoxModel ? child.renderStyle.flexGrow : 0.0;
}
double _getFlexShrink(RenderBox child) {
// Flex shrink has no effect on placeholder of positioned element
if (child is RenderPositionHolder) {
return 0;
}
return child is RenderBoxModel ? child.renderStyle.flexShrink : 0.0;
}
double? _getFlexBasis(RenderBox child) {
// Flex shrink has no effect on placeholder of positioned element
if (child is RenderPositionHolder) {
return null;
}
return child is RenderBoxModel ? child.renderStyle.flexBasis : null;
}
AlignSelf _getAlignSelf(RenderBox child) {
// Flex shrink has no effect on placeholder of positioned element
if (child is RenderPositionHolder) {
return AlignSelf.auto;
}
return child is RenderBoxModel
? child.renderStyle.alignSelf
: AlignSelf.auto;
}
double _getMaxMainAxisSize(RenderBox child) {
double? maxMainSize;
if (child is RenderBoxModel) {
maxMainSize =
CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)
? child.renderStyle.maxWidth
: child.renderStyle.maxHeight;
}
return maxMainSize ?? double.infinity;
}
/// Calculate automatic minimum size of flex item
/// Refer to https://www.w3.org/TR/css-flexbox-1/#min-size-auto for detail rules
double? _getMinMainAxisSize(RenderBoxModel child) {
double? minMainSize;
double? contentSize = 0;
// Min width of flex item if min-width is not specified use auto min width instead
double? minWidth = 0;
// Min height of flex item if min-height is not specified use auto min height instead
double? minHeight = 0;
RenderStyle? childRenderStyle = child.renderStyle;
if (child is RenderBoxModel) {
minWidth = childRenderStyle.minWidth != null
? childRenderStyle.minWidth!
: child.autoMinWidth;
minHeight = childRenderStyle.minHeight != null
? childRenderStyle.minHeight!
: child.autoMinHeight;
} else if (child is RenderTextBox) {
minWidth = child.autoMinWidth;
minHeight = child.autoMinHeight;
}
contentSize = CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)
? minWidth
: minHeight;
if (child is RenderIntrinsic &&
child.intrinsicRatio != null &&
CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection) &&
childRenderStyle.width == null) {
double transferredSize = childRenderStyle.height != null
? childRenderStyle.height! * child.intrinsicRatio!
: child.intrinsicWidth!;
minMainSize = math.min(contentSize, transferredSize);
} else if (child is RenderIntrinsic &&
child.intrinsicRatio != null &&
CSSFlex.isVerticalFlexDirection(renderStyle.flexDirection) &&
childRenderStyle.height == null) {
double transferredSize = childRenderStyle.width != null
? childRenderStyle.width! / child.intrinsicRatio!
: child.intrinsicHeight!;
minMainSize = math.min(contentSize, transferredSize);
} else if (child is RenderBoxModel) {
double? specifiedMainSize =
CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)
? RenderBoxModel.getLogicalContentWidth(child)
: RenderBoxModel.getLogicalContentHeight(child);
minMainSize = specifiedMainSize != null
? math.min(contentSize, specifiedMainSize)
: contentSize;
} else if (child is RenderTextBox) {
minMainSize = contentSize;
}
return minMainSize;
}
double _getShrinkConstraints(RenderBox child,
Map<int?, _RunChild> runChildren, double remainingFreeSpace) {
double totalWeightedFlexShrink = 0;
runChildren.forEach((int? hashCode, _RunChild runChild) {
double childOriginalMainSize = runChild.originalMainSize;
RenderBox child = runChild.child;
if (!runChild.frozen) {
double childFlexShrink = _getFlexShrink(child);
totalWeightedFlexShrink += childOriginalMainSize * childFlexShrink;
}
});
if (totalWeightedFlexShrink == 0) {
return 0;
}
int? childNodeId;
if (child is RenderTextBox) {
childNodeId = child.hashCode;
} else if (child is RenderBoxModel) {
childNodeId = child.hashCode;
}
_RunChild current = runChildren[childNodeId]!;
double currentOriginalMainSize = current.originalMainSize;
double currentFlexShrink = _getFlexShrink(current.child);
double currentExtent = currentFlexShrink * currentOriginalMainSize;
double minusConstraints =
(currentExtent / totalWeightedFlexShrink) * remainingFreeSpace;
return minusConstraints;
}
double _getCrossAxisExtent(RenderBox? child) {
double marginHorizontal = 0;
double marginVertical = 0;
RenderBoxModel? childRenderBoxModel;
if (child is RenderBoxModel) {
childRenderBoxModel = child;
} else if (child is RenderPositionHolder) {
// Position placeholder of flex item need to layout as its original renderBox
// so it needs to add margin to its extent
childRenderBoxModel = child.realDisplayedBox;
}
if (childRenderBoxModel != null) {
marginHorizontal = childRenderBoxModel.renderStyle.marginLeft.length! +
childRenderBoxModel.renderStyle.marginRight.length!;
marginVertical = childRenderBoxModel.renderStyle.marginTop.length! +
childRenderBoxModel.renderStyle.marginBottom.length!;
}
Size? childSize = _getChildSize(child);
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return childSize!.height + marginVertical;
} else {
return childSize!.width + marginHorizontal;
}
}
bool _isChildMainAxisClip(RenderBoxModel renderBoxModel) {
if (renderBoxModel is RenderIntrinsic) {
return false;
}
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return renderBoxModel.clipX;
} else {
return renderBoxModel.clipY;
}
}
double _getMainAxisExtent(RenderBox child,
{bool shouldUseIntrinsicMainSize = false}) {
double marginHorizontal = 0;
double marginVertical = 0;
RenderBoxModel? childRenderBoxModel;
if (child is RenderBoxModel) {
childRenderBoxModel = child;
} else if (child is RenderPositionHolder) {
// Position placeholder of flex item need to layout as its original renderBox
// so it needs to add margin to its extent
childRenderBoxModel = child.realDisplayedBox;
}
if (childRenderBoxModel != null) {
marginHorizontal = childRenderBoxModel.renderStyle.marginLeft.length! +
childRenderBoxModel.renderStyle.marginRight.length!;
marginVertical = childRenderBoxModel.renderStyle.marginTop.length! +
childRenderBoxModel.renderStyle.marginBottom.length!;
}
double baseSize = _getMainSize(child,
shouldUseIntrinsicMainSize: shouldUseIntrinsicMainSize);
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return baseSize + marginHorizontal;
} else {
return baseSize + marginVertical;
}
}
double _getMainSize(RenderBox child,
{bool shouldUseIntrinsicMainSize = false}) {
Size? childSize = _getChildSize(child,
shouldUseIntrinsicMainSize: shouldUseIntrinsicMainSize);
if (CSSFlex.isHorizontalFlexDirection(renderStyle.flexDirection)) {
return childSize!.width;
} else {
return childSize!.height;
}
}
@override
void performLayout() {
if (kProfileMode) {
childLayoutDuration = 0;
PerformanceTiming.instance()
.mark(PERF_FLEX_LAYOUT_START, uniqueId: hashCode);
}
beforeLayout();
RenderBox? child = firstChild;
// Layout positioned element
while (child != null) {
final RenderLayoutParentData childParentData =
child.parentData as RenderLayoutParentData;
// Layout placeholder of positioned element(absolute/fixed) in new layer
if (child is RenderBoxModel && childParentData.isPositioned) {
CSSPositionedLayout.layoutPositionedChild(this, child);
} else if (child is RenderPositionHolder &&
isPlaceholderPositioned(child)) {
_layoutChildren(child);
}
child = childParentData.nextSibling;
}
// Layout non positioned element and its placeholder
_layoutChildren(null);
// Set offset of positioned and sticky element
child = firstChild;
while (child != null) {
final RenderLayoutParentData childParentData =
child.parentData as RenderLayoutParentData;
if (child is RenderBoxModel && childParentData.isPositioned) {
CSSPositionedLayout.applyPositionedChildOffset(this, child);
extendMaxScrollableSize(child);
// For scrolling box, the minimum width and height should not less than scrollableSize
if (isScrollingContentBox) {
ensureBoxSizeLargerThanScrollableSize();
}
} else if (child is RenderBoxModel &&
CSSPositionedLayout.isSticky(child)) {
RenderBoxModel scrollContainer = child.findScrollContainer()!;
// Sticky offset depends on the layout of scroll container, delay the calculation of
// sticky offset to the layout stage of scroll container if its not layouted yet
// due to the layout order of Flutter renderObject tree is from down to up.
if (scrollContainer.hasSize) {
CSSPositionedLayout.applyStickyChildOffset(scrollContainer, child);
}
}
child = childParentData.nextSibling;
}
bool isScrollContainer =
renderStyle.overflowX != CSSOverflowType.visible ||
renderStyle.overflowY != CSSOverflowType.visible;
if (isScrollContainer) {
// Find all the sticky children when scroll container is layouted
stickyChildren = findStickyChildren();
// Calculate the offset of its sticky children
for (RenderBoxModel stickyChild in stickyChildren) {
CSSPositionedLayout.applyStickyChildOffset(this, stickyChild);
}
}
_relayoutPositionedChildren();
didLayout();
if (kProfileMode) {
DateTime flexLayoutEndTime = DateTime.now();
int amendEndTime =
flexLayoutEndTime.microsecondsSinceEpoch - childLayoutDuration;
PerformanceTiming.instance().mark(PERF_FLEX_LAYOUT_END,
uniqueId: hashCode, startTime: amendEndTime);
}
}
/// Relayout positioned child if percentage size exists
void _relayoutPositionedChildren() {
RenderBox? child = firstChild;
while (child != null) {
final RenderLayoutParentData childParentData =
child.parentData as RenderLayoutParentData;
if (child is RenderBoxModel && childParentData.isPositioned) {
bool percentageOfSizingFound = child.renderStyle.isPercentageOfSizingExist(this);
bool percentageToOwnFound = child.renderStyle.isPercentageToOwnExist();
bool percentageToContainingBlockFound = child.renderStyle.resolvePercentageToContainingBlock(this);
/// When percentage exists in sizing styles(width/height) and styles relies on its own size,
/// it needs to relayout twice cause the latter relies on the size calculated in the first relayout
if (percentageOfSizingFound == true && percentageToOwnFound == true) {
/// Relayout first time to calculate percentage styles such as width/height
_layoutPositionedChild(child);
child.renderStyle.resolvePercentageToOwn();
/// Relayout second time to calculate percentage styles such as transform: translate/border-radius
_layoutPositionedChild(child);
} else if (percentageToContainingBlockFound == true ||
percentageToOwnFound == true) {
_layoutPositionedChild(child);
}
extendMaxScrollableSize(child);
}
child = childParentData.nextSibling;
}
}
void _layoutPositionedChild(RenderBoxModel child) {
CSSPositionedLayout.layoutPositionedChild(this, child, needsRelayout: true);
CSSPositionedLayout.applyPositionedChildOffset(this, child);
}
bool isPlaceholderPositioned(RenderObject child) {
if (child is RenderPositionHolder) {
RenderBoxModel realDisplayedBox = child.realDisplayedBox!;
RenderLayoutParentData parentData =
realDisplayedBox.parentData as RenderLayoutParentData;
if (parentData.isPositioned) {
return true;
}
}
return false;
}
/// There are 4 stages when layouting children
/// 1. Layout children in flow order to calculate flex lines according to its constaints and flex-wrap property
/// 2. Relayout children according to flex-grow and flex-shrink factor
/// 3. Set flex container size according to children size
/// 4. Align children according to justify-content, align-items and align-self properties
void _layoutChildren(RenderPositionHolder? placeholderChild,
{bool needsRelayout = false}) {
/// If no child exists, stop layout.
if (childCount == 0) {
Size layoutSize = getLayoutSize(
logicalContentWidth: logicalContentWidth,
logicalContentHeight: logicalContentHeight,
contentWidth: 0,
contentHeight: 0,
);
double constraintWidth = layoutSize.width;
double constraintHeight = layoutSize.height;
setMaxScrollableSize(constraintWidth, constraintHeight);
size = getBoxSize(Size(
constraintWidth,
constraintHeight,
));
return;
}
assert(contentConstraints != null);
// Metrics of each flex line
List<_RunMetrics> runMetrics = <_RunMetrics>[];
// Flex container size in main and cross direction
Map<String, double?> containerSizeMap = {
'main': 0.0,
'cross': 0.0,
};
if (placeholderChild == null) {
flexLineBoxMetrics = runMetrics;
}
/// Stage 1: Layout children in flow order to calculate flex lines
_layoutByFlexLine(
runMetrics,
placeholderChild,
containerSizeMap,
needsRelayout,
);
/// If no non positioned child exists, stop layout
if (runMetrics.isEmpty) {
Size preferredSize = Size(
logicalContentWidth ?? 0,
logicalContentHeight ?? 0,
);
setMaxScrollableSize(preferredSize.width, preferredSize.height);
size = getBoxSize(preferredSize);
return;
}
double containerCrossAxisExtent = 0.0;
bool isVerticalDirection =
CSSFlex.isVerticalFlexDirection(renderStyle.flexDirection);
if (isVerticalDirection) {
containerCrossAxisExtent = logicalContentWidth ?? 0;
} else {
containerCrossAxisExtent = logicalContentHeight ?? 0;
}
/// Calculate leading and between space between flex lines
final double crossAxisFreeSpace =
containerCrossAxisExtent - containerSizeMap['cross']!;
final int runCount = runMetrics.length;
double runLeadingSpace = 0.0;
double runBetweenSpace = 0.0;
/// Align-content only works in when flex-wrap is no nowrap
if (renderStyle.flexWrap == FlexWrap.wrap ||
renderStyle.flexWrap == FlexWrap.wrapReverse) {
switch (renderStyle.alignContent) {
case AlignContent.flexStart:
case AlignContent.start:
break;
case AlignContent.flexEnd:
case AlignContent.end:
runLeadingSpace = crossAxisFreeSpace;
break;
case AlignContent.center:
runLeadingSpace = crossAxisFreeSpace / 2.0;
break;
case AlignContent.spaceBetween:
if (crossAxisFreeSpace < 0) {
runBetweenSpace = 0;
} else {
runBetweenSpace =
runCount > 1 ? crossAxisFreeSpace / (runCount - 1) : 0.0;
}
break;
case AlignContent.spaceAround:
if (crossAxisFreeSpace < 0) {
runLeadingSpace = crossAxisFreeSpace / 2.0;
runBetweenSpace = 0;
} else {
runBetweenSpace = crossAxisFreeSpace / runCount;
runLeadingSpace = runBetweenSpace / 2.0;
}
break;
case AlignContent.spaceEvenly:
if (crossAxisFreeSpace < 0) {
runLeadingSpace = crossAxisFreeSpace / 2.0;
runBetweenSpace = 0;
} else {
runBetweenSpace = crossAxisFreeSpace / (runCount + 1);
runLeadingSpace = runBetweenSpace;
}
break;
case AlignContent.stretch:
runBetweenSpace = crossAxisFreeSpace / runCount;
if (runBetweenSpace < 0) {
runBetweenSpace = 0;
}
break;
}
}
/// Stage 2: Layout flex item second time based on flex factor and actual size
_relayoutByFlexFactor(
runMetrics,
runBetweenSpace,
placeholderChild,
containerSizeMap,
);
/// Stage 3: Set flex container size according to children size
_setContainerSize(
runMetrics,
containerSizeMap,
);
/// Stage 4: Set children offset based on flex alignment properties
_alignChildren(
runMetrics,
runBetweenSpace,
runLeadingSpace,
placeholderChild,
);
/// Make sure it will not trigger relayout again when in relayout stage
if (!needsRelayout) {
bool percentageOfSizingFound =
_isChildrenPercentageOfSizingExist(placeholderChild);
bool percentageToOwnFound =
_isChildrenPercentageToOwnExist(placeholderChild);
bool percentageToContainingBlockFound =
_resolveChildrenPercentageToContainingBlock(placeholderChild);
/// When percentage exists in sizing styles(width/height) and styles relies on its own size,
/// it needs to relayout twice cause the latter relies on the size calculated in the first relayout
if (percentageOfSizingFound == true && percentageToOwnFound == true) {
/// Relayout first time to calculate percentage styles such as width/height
_layoutChildren(placeholderChild, needsRelayout: true);
_resolveChildrenPercentageToOwn(placeholderChild);
/// Relayout second time to calculate percentage styles such as transform: translate/border-radius
_layoutChildren(placeholderChild, needsRelayout: true);
} else if (percentageToContainingBlockFound == true ||
percentageToOwnFound == true) {
_layoutChildren(placeholderChild, needsRelayout: true);
}
}
}
/// Resolve all percentage size of child based on size its containing block
bool _resolveChildrenPercentageToContainingBlock(
RenderPositionHolder? placeholderChild) {
bool percentageFound = false;
RenderBox? child = firstChild;
while (child != null) {
final RenderLayoutParentData? childParentData =
child.parentData as RenderLayoutParentData?;
// Exclude positioned placeholder renderObject when layout non placeholder object
// and positioned renderObject
if (placeholderChild == null &&
(isPlaceholderPositioned(child) || childParentData!.isPositioned)) {
child = childParentData!.nextSibling;
continue;
}
if (child is RenderBoxModel) {
bool percentageExist = child.renderStyle.resolvePercentageToContainingBlock(this);
if (percentageExist) {
percentageFound = true;
}
}
child = childParentData!.nextSibling;
}
return percentageFound;
}
/// Resolve all percentage size of child based on size its own
bool _resolveChildrenPercentageToOwn(RenderPositionHolder? placeholderChild) {
bool percentageFound = false;
RenderBox? child = firstChild;
while (child != null) {
final RenderLayoutParentData? childParentData =
child.parentData as RenderLayoutParentData?;
// Exclude positioned placeholder renderObject when layout non placeholder object
// and positioned renderObject
if (placeholderChild == null &&
(isPlaceholderPositioned(child) || childParentData!.isPositioned)) {
child = childParentData!.nextSibling;
continue;
}
if (child is RenderBoxModel) {
percentageFound = child.renderStyle.resolvePercentageToOwn();
}
child = childParentData!.nextSibling;
}
return percentageFound;
}
/// Check whether percentage sizing styles of child exists
bool _isChildrenPercentageOfSizingExist(
RenderPositionHolder? placeholderChild) {
bool percentageFound = false;
RenderBox? child = firstChild;
while (child != null) {
final RenderLayoutParentData? childParentData =
child.parentData as RenderLayoutParentData?;
// Exclude positioned placeholder renderObject when layout non placeholder object
// and positioned renderObject
if (placeholderChild == null &&
(isPlaceholderPositioned(child) || childParentData!.isPositioned)) {
child = childParentData!.nextSibling;
continue;
}
if (child is RenderBoxModel) {
bool percentageExist = child.renderStyle.isPercentageOfSizingExist(this);
if (percentageExist) {
percentageFound = true;
break;
}
}
child = childParentData!.nextSibling;
}
return percentageFound;
}
/// Check whether percentage size of child based on size its own exist
bool _isChildrenPercentageToOwnExist(RenderPositionHolder? placeholderChild) {
bool percentageFound = false;
RenderBox? child = firstChild;
while (child != null) {
final RenderLayoutParentData? childParentData =
child.parentData as RenderLayoutParentData?;
// Exclude positioned placeholder renderObject when layout non placeholder object
// and positioned renderObject
if (placeholderChild == null &&