-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
ng_flex_layout_algorithm.cc
2827 lines (2540 loc) · 123 KB
/
ng_flex_layout_algorithm.cc
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.h"
#include <memory>
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/layout/flexible_box_algorithm.h"
#include "third_party/blink/renderer/core/layout/geometry/logical_size.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_button.h"
#include "third_party/blink/renderer/core/layout/layout_flexible_box.h"
#include "third_party/blink/renderer/core/layout/ng/flex/layout_ng_flexible_box.h"
#include "third_party/blink/renderer/core/layout/ng/flex/ng_flex_child_iterator.h"
#include "third_party/blink/renderer/core/layout/ng/flex/ng_flex_data.h"
#include "third_party/blink/renderer/core/layout/ng/flex/ng_flex_item_iterator.h"
#include "third_party/blink/renderer/core/layout/ng/flex/ng_flex_line.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h"
#include "third_party/blink/renderer/core/layout/ng/ng_baseline_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_space_utils.h"
#include "third_party/blink/renderer/core/layout/ng/table/ng_table_node.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/computed_style_base_constants.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
namespace {
class BaselineAccumulator {
STACK_ALLOCATED();
public:
explicit BaselineAccumulator(const ComputedStyle& style)
: font_baseline_(style.GetFontBaseline()) {}
void AccumulateItem(const NGBoxFragment& fragment,
const LayoutUnit block_offset,
bool is_first_line,
bool is_last_line) {
if (is_first_line) {
if (!first_fallback_baseline_) {
first_fallback_baseline_ =
block_offset + fragment.FirstBaselineOrSynthesize(font_baseline_);
}
}
if (is_last_line) {
last_fallback_baseline_ =
block_offset + fragment.LastBaselineOrSynthesize(font_baseline_);
}
}
void AccumulateLine(const NGFlexLine& line,
bool is_first_line,
bool is_last_line) {
if (is_first_line) {
if (line.major_baseline != LayoutUnit::Min()) {
first_major_baseline_ = line.cross_axis_offset + line.major_baseline;
}
if (line.minor_baseline != LayoutUnit::Min()) {
first_minor_baseline_ =
line.cross_axis_offset + line.line_cross_size - line.minor_baseline;
}
}
if (is_last_line) {
if (line.major_baseline != LayoutUnit::Min()) {
last_major_baseline_ = line.cross_axis_offset + line.major_baseline;
}
if (line.minor_baseline != LayoutUnit::Min()) {
last_minor_baseline_ =
line.cross_axis_offset + line.line_cross_size - line.minor_baseline;
}
}
}
absl::optional<LayoutUnit> FirstBaseline() const {
if (first_major_baseline_)
return *first_major_baseline_;
if (first_minor_baseline_)
return *first_minor_baseline_;
return first_fallback_baseline_;
}
absl::optional<LayoutUnit> LastBaseline() const {
if (last_minor_baseline_)
return *last_minor_baseline_;
if (last_major_baseline_)
return *last_major_baseline_;
return last_fallback_baseline_;
}
private:
FontBaseline font_baseline_;
absl::optional<LayoutUnit> first_major_baseline_;
absl::optional<LayoutUnit> first_minor_baseline_;
absl::optional<LayoutUnit> first_fallback_baseline_;
absl::optional<LayoutUnit> last_major_baseline_;
absl::optional<LayoutUnit> last_minor_baseline_;
absl::optional<LayoutUnit> last_fallback_baseline_;
};
bool ContainsNonWhitespace(const LayoutBox* box) {
const LayoutObject* next = box;
while ((next = next->NextInPreOrder(box))) {
if (const auto* text = DynamicTo<LayoutText>(next)) {
if (!text->GetText().ContainsOnlyWhitespaceOrEmpty())
return true;
}
}
return false;
}
} // anonymous namespace
NGFlexLayoutAlgorithm::NGFlexLayoutAlgorithm(
const NGLayoutAlgorithmParams& params,
const HashMap<wtf_size_t, LayoutUnit>* cross_size_adjustments)
: NGLayoutAlgorithm(params),
is_column_(Style().ResolvedIsColumnFlexDirection()),
is_horizontal_flow_(FlexLayoutAlgorithm::IsHorizontalFlow(Style())),
is_cross_size_definite_(IsContainerCrossSizeDefinite()),
child_percentage_size_(
CalculateChildPercentageSize(ConstraintSpace(),
Node(),
ChildAvailableSize())),
algorithm_(&Style(),
MainAxisContentExtent(LayoutUnit::Max()),
child_percentage_size_,
&Node().GetDocument()),
cross_size_adjustments_(cross_size_adjustments) {
// TODO(layout-dev): Devtools support when there are multiple fragments.
if (Node().GetLayoutBox()->NeedsDevtoolsInfo() &&
!InvolvedInBlockFragmentation(container_builder_))
layout_info_for_devtools_ = std::make_unique<DevtoolsFlexInfo>();
}
bool NGFlexLayoutAlgorithm::MainAxisIsInlineAxis(
const NGBlockNode& child) const {
return child.Style().IsHorizontalWritingMode() == is_horizontal_flow_;
}
LayoutUnit NGFlexLayoutAlgorithm::MainAxisContentExtent(
LayoutUnit sum_hypothetical_main_size) const {
if (is_column_) {
// Even though we only pass border_padding in the third parameter, the
// return value includes scrollbar, so subtract scrollbar to get content
// size.
// We add |border_scrollbar_padding| to the fourth parameter because
// |content_size| needs to be the size of the border box. We've overloaded
// the term "content".
const LayoutUnit border_scrollbar_padding =
BorderScrollbarPadding().BlockSum();
absl::optional<LayoutUnit> inline_size;
if (container_builder_.InlineSize() != kIndefiniteSize)
inline_size = container_builder_.InlineSize();
return ComputeBlockSizeForFragment(
ConstraintSpace(), Style(), BorderPadding(),
sum_hypothetical_main_size.ClampNegativeToZero() +
border_scrollbar_padding,
inline_size) -
border_scrollbar_padding;
}
return ChildAvailableSize().inline_size;
}
namespace {
enum AxisEdge { kStart, kCenter, kEnd };
// Maps the resolved justify-content value to a static-position edge.
AxisEdge MainAxisStaticPositionEdge(const ComputedStyle& style,
bool is_column) {
const StyleContentAlignmentData justify =
FlexLayoutAlgorithm::ResolvedJustifyContent(style);
const ContentPosition content_position = justify.GetPosition();
bool is_reverse_flex = is_column
? style.ResolvedIsColumnReverseFlexDirection()
: style.ResolvedIsRowReverseFlexDirection();
DCHECK_NE(content_position, ContentPosition::kLeft);
DCHECK_NE(content_position, ContentPosition::kRight);
if (content_position == ContentPosition::kFlexEnd)
return is_reverse_flex ? AxisEdge::kStart : AxisEdge::kEnd;
if (content_position == ContentPosition::kCenter ||
justify.Distribution() == ContentDistributionType::kSpaceAround ||
justify.Distribution() == ContentDistributionType::kSpaceEvenly)
return AxisEdge::kCenter;
if (content_position == ContentPosition::kStart)
return AxisEdge::kStart;
if (content_position == ContentPosition::kEnd)
return AxisEdge::kEnd;
return is_reverse_flex ? AxisEdge::kEnd : AxisEdge::kStart;
}
// Maps the resolved alignment value to a static-position edge.
AxisEdge CrossAxisStaticPositionEdge(const ComputedStyle& style,
const ComputedStyle& child_style) {
ItemPosition alignment =
FlexLayoutAlgorithm::AlignmentForChild(style, child_style);
// AlignmentForChild already accounted for wrap-reverse for kFlexStart and
// kFlexEnd, but not kStretch. kStretch is supposed to act like kFlexStart.
if (style.FlexWrap() == EFlexWrap::kWrapReverse &&
alignment == ItemPosition::kStretch) {
return AxisEdge::kEnd;
}
if (alignment == ItemPosition::kFlexEnd ||
alignment == ItemPosition::kLastBaseline)
return AxisEdge::kEnd;
if (alignment == ItemPosition::kCenter)
return AxisEdge::kCenter;
return AxisEdge::kStart;
}
} // namespace
void NGFlexLayoutAlgorithm::HandleOutOfFlowPositionedItems(
HeapVector<Member<LayoutBox>>& oof_children) {
if (oof_children.empty())
return;
HeapVector<Member<LayoutBox>> oofs;
std::swap(oofs, oof_children);
bool should_process_block_end = true;
bool should_process_block_center = true;
const LayoutUnit previous_consumed_block_size =
BreakToken() ? BreakToken()->ConsumedBlockSize() : LayoutUnit();
// We will attempt to add OOFs in the fragment in which their static
// position belongs. However, the last fragment has the most up-to-date flex
// size information (e.g. any expanded rows, etc), so for center aligned
// items, we could end up with an incorrect static position.
if (UNLIKELY(InvolvedInBlockFragmentation(container_builder_))) {
should_process_block_end = !container_builder_.DidBreakSelf() &&
!container_builder_.ShouldBreakInside();
if (should_process_block_end) {
// Recompute the total block size in case |total_intrinsic_block_size_|
// changed as a result of fragmentation.
total_block_size_ = ComputeBlockSizeForFragment(
ConstraintSpace(), Style(), BorderPadding(),
total_intrinsic_block_size_, container_builder_.InlineSize());
} else {
LayoutUnit center = total_block_size_ / 2;
should_process_block_center = center - previous_consumed_block_size <=
FragmentainerCapacity(ConstraintSpace());
}
}
using InlineEdge = NGLogicalStaticPosition::InlineEdge;
using BlockEdge = NGLogicalStaticPosition::BlockEdge;
NGBoxStrut border_scrollbar_padding = BorderScrollbarPadding();
border_scrollbar_padding.block_start =
OriginalBorderScrollbarPaddingBlockStart();
LogicalSize total_fragment_size = {container_builder_.InlineSize(),
total_block_size_};
total_fragment_size =
ShrinkLogicalSize(total_fragment_size, border_scrollbar_padding);
for (LayoutBox* oof_child : oofs) {
NGBlockNode child(oof_child);
AxisEdge main_axis_edge = MainAxisStaticPositionEdge(Style(), is_column_);
AxisEdge cross_axis_edge =
CrossAxisStaticPositionEdge(Style(), child.Style());
// This code block just collects UMA stats.
if (!IsBreakInside(BreakToken())) {
const auto& style = Style();
const auto& child_style = child.Style();
const PhysicalToLogical<Length> insets_in_flexbox_writing_mode(
Style().GetWritingDirection(), child_style.Top(), child_style.Right(),
child_style.Bottom(), child_style.Left());
if (is_column_) {
const ItemPosition normalized_alignment =
FlexLayoutAlgorithm::AlignmentForChild(style, child_style);
const ItemPosition default_justify_self_behavior =
child.IsReplaced() ? ItemPosition::kStart : ItemPosition::kStretch;
const ItemPosition normalized_justify =
FlexLayoutAlgorithm::TranslateItemPosition(
style, child_style,
child_style.ResolvedJustifySelf(default_justify_self_behavior)
.GetPosition());
const bool are_cross_axis_insets_auto =
insets_in_flexbox_writing_mode.InlineStart().IsAuto() &&
insets_in_flexbox_writing_mode.InlineEnd().IsAuto();
if (normalized_alignment != normalized_justify &&
are_cross_axis_insets_auto) {
UseCounter::Count(Node().GetDocument(),
WebFeature::kFlexboxNewAbsPos);
}
}
if (main_axis_edge != AxisEdge::kStart) {
const bool are_main_axis_insets_auto =
is_column_
? insets_in_flexbox_writing_mode.BlockStart().IsAuto() &&
insets_in_flexbox_writing_mode.BlockEnd().IsAuto()
: insets_in_flexbox_writing_mode.InlineStart().IsAuto() &&
insets_in_flexbox_writing_mode.InlineEnd().IsAuto();
if (are_main_axis_insets_auto) {
UseCounter::Count(Node().GetDocument(),
WebFeature::kFlexboxAbsPosJustifyContent);
}
}
}
AxisEdge inline_axis_edge = is_column_ ? cross_axis_edge : main_axis_edge;
AxisEdge block_axis_edge = is_column_ ? main_axis_edge : cross_axis_edge;
InlineEdge inline_edge;
BlockEdge block_edge;
LogicalOffset offset = border_scrollbar_padding.StartOffset();
// Determine the static-position based off the axis-edge.
if (block_axis_edge == AxisEdge::kStart) {
DCHECK(!IsBreakInside(BreakToken()));
block_edge = BlockEdge::kBlockStart;
} else if (block_axis_edge == AxisEdge::kCenter) {
if (!should_process_block_center) {
oof_children.emplace_back(oof_child);
continue;
}
block_edge = BlockEdge::kBlockCenter;
offset.block_offset += total_fragment_size.block_size / 2;
} else {
if (!should_process_block_end) {
oof_children.emplace_back(oof_child);
continue;
}
block_edge = BlockEdge::kBlockEnd;
offset.block_offset += total_fragment_size.block_size;
}
if (inline_axis_edge == AxisEdge::kStart) {
inline_edge = InlineEdge::kInlineStart;
} else if (inline_axis_edge == AxisEdge::kCenter) {
inline_edge = InlineEdge::kInlineCenter;
offset.inline_offset += total_fragment_size.inline_size / 2;
} else {
inline_edge = InlineEdge::kInlineEnd;
offset.inline_offset += total_fragment_size.inline_size;
}
// Make the child offset relative to our fragment.
offset.block_offset -= previous_consumed_block_size;
container_builder_.AddOutOfFlowChildCandidate(child, offset, inline_edge,
block_edge);
}
}
bool NGFlexLayoutAlgorithm::IsColumnContainerMainSizeDefinite() const {
DCHECK(is_column_);
return ChildAvailableSize().block_size != kIndefiniteSize;
}
bool NGFlexLayoutAlgorithm::IsContainerCrossSizeDefinite() const {
// A column flexbox's cross axis is an inline size, so is definite.
if (is_column_)
return true;
return ChildAvailableSize().block_size != kIndefiniteSize;
}
bool NGFlexLayoutAlgorithm::DoesItemStretch(const NGBlockNode& child) const {
// Note: Unresolvable % cross size doesn't count as auto for stretchability.
// As discussed in https://github.com/w3c/csswg-drafts/issues/4312.
if (!DoesItemCrossSizeComputeToAuto(child))
return false;
const ComputedStyle& child_style = child.Style();
// https://drafts.csswg.org/css-flexbox/#valdef-align-items-stretch
// If the cross size property of the flex item computes to auto, and neither
// of the cross-axis margins are auto, the flex item is stretched.
if (is_horizontal_flow_ &&
(child_style.MarginTop().IsAuto() || child_style.MarginBottom().IsAuto()))
return false;
if (!is_horizontal_flow_ &&
(child_style.MarginLeft().IsAuto() || child_style.MarginRight().IsAuto()))
return false;
return FlexLayoutAlgorithm::AlignmentForChild(Style(), child_style) ==
ItemPosition::kStretch;
}
bool NGFlexLayoutAlgorithm::IsUsedFlexBasisDefinite(
const NGBlockNode& child,
Length* out_flex_basis = nullptr) const {
const Length& flex_basis = GetUsedFlexBasis(child);
if (out_flex_basis)
*out_flex_basis = flex_basis;
if (flex_basis.IsAuto() || flex_basis.IsContent())
return false;
const NGConstraintSpace& space = BuildSpaceForFlexBasis(child);
if (MainAxisIsInlineAxis(child))
return !InlineLengthUnresolvable(space, flex_basis);
return !BlockLengthUnresolvable(space, flex_basis);
}
bool NGFlexLayoutAlgorithm::IsItemCrossAxisLengthDefinite(
const NGBlockNode& child,
const Length& length) const {
// We don't consider inline value of 'auto' for the cross-axis min/main/max
// size to be definite. Block value of 'auto' is always indefinite.
if (length.IsAuto())
return false;
if (MainAxisIsInlineAxis(child))
return !BlockLengthUnresolvable(BuildSpaceForFlexBasis(child), length);
return !InlineLengthUnresolvable(BuildSpaceForFlexBasis(child), length);
}
bool NGFlexLayoutAlgorithm::DoesItemCrossSizeComputeToAuto(
const NGBlockNode& child) const {
const ComputedStyle& child_style = child.Style();
if (is_horizontal_flow_)
return child_style.Height().IsAuto();
return child_style.Width().IsAuto();
}
bool NGFlexLayoutAlgorithm::AspectRatioProvidesMainSize(
const NGBlockNode& child) const {
const Length& cross_axis_length =
is_horizontal_flow_ ? child.Style().Height() : child.Style().Width();
return child.HasAspectRatio() &&
(IsItemCrossAxisLengthDefinite(child, cross_axis_length) ||
WillChildCrossSizeBeContainerCrossSize(child));
}
bool NGFlexLayoutAlgorithm::WillChildCrossSizeBeContainerCrossSize(
const NGBlockNode& child) const {
return !algorithm_.IsMultiline() && is_cross_size_definite_ &&
DoesItemStretch(child);
}
NGConstraintSpace NGFlexLayoutAlgorithm::BuildSpaceForIntrinsicInlineSize(
const NGBlockNode& child) const {
NGMinMaxConstraintSpaceBuilder builder(ConstraintSpace(), Style(), child,
/* is_new_fc */ true);
builder.SetAvailableBlockSize(ChildAvailableSize().block_size);
builder.SetPercentageResolutionBlockSize(child_percentage_size_.block_size);
builder.SetReplacedPercentageResolutionBlockSize(
child_percentage_size_.block_size);
if (!is_column_ && WillChildCrossSizeBeContainerCrossSize(child))
builder.SetBlockAutoBehavior(NGAutoBehavior::kStretchExplicit);
return builder.ToConstraintSpace();
}
NGConstraintSpace NGFlexLayoutAlgorithm::BuildSpaceForIntrinsicBlockSize(
const NGBlockNode& flex_item,
absl::optional<LayoutUnit> override_inline_size) const {
const ComputedStyle& child_style = flex_item.Style();
NGConstraintSpaceBuilder space_builder(ConstraintSpace(),
child_style.GetWritingDirection(),
/* is_new_fc */ true);
SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item, &space_builder);
space_builder.SetCacheSlot(NGCacheSlot::kMeasure);
space_builder.SetIsPaintedAtomically(true);
if (WillChildCrossSizeBeContainerCrossSize(flex_item)) {
if (is_column_)
space_builder.SetInlineAutoBehavior(NGAutoBehavior::kStretchExplicit);
else
space_builder.SetBlockAutoBehavior(NGAutoBehavior::kStretchExplicit);
}
// For determining the intrinsic block-size we make %-block-sizes resolve
// against an indefinite size.
LogicalSize child_percentage_size = child_percentage_size_;
if (is_column_) {
child_percentage_size.block_size = kIndefiniteSize;
space_builder.SetIsInitialBlockSizeIndefinite(true);
}
if (override_inline_size.has_value()) {
LogicalSize available_size = ChildAvailableSize();
available_size.inline_size = *override_inline_size;
space_builder.SetIsFixedInlineSize(true);
space_builder.SetAvailableSize(available_size);
} else {
space_builder.SetAvailableSize(ChildAvailableSize());
}
space_builder.SetPercentageResolutionSize(child_percentage_size);
// TODO(dgrogan): The SetReplacedPercentageResolutionSize calls in this file
// may be untested. Write a test or determine why they're unnecessary.
space_builder.SetReplacedPercentageResolutionSize(child_percentage_size);
return space_builder.ToConstraintSpace();
}
NGConstraintSpace NGFlexLayoutAlgorithm::BuildSpaceForFlexBasis(
const NGBlockNode& flex_item) const {
NGConstraintSpaceBuilder space_builder(
ConstraintSpace(), flex_item.Style().GetWritingDirection(),
/* is_new_fc */ true);
SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item, &space_builder);
// This space is only used for resolving lengths, not for layout. We only
// need the available and percentage sizes.
space_builder.SetAvailableSize(ChildAvailableSize());
space_builder.SetPercentageResolutionSize(child_percentage_size_);
space_builder.SetReplacedPercentageResolutionSize(child_percentage_size_);
return space_builder.ToConstraintSpace();
}
// This can return an indefinite Length.
Length NGFlexLayoutAlgorithm::GetUsedFlexBasis(const NGBlockNode& child) const {
const ComputedStyle& child_style = child.Style();
const Length& specified_length_in_main_axis =
is_horizontal_flow_ ? child_style.Width() : child_style.Height();
const Length& specified_flex_basis = child_style.FlexBasis();
if (specified_flex_basis.IsAuto()) {
if (specified_length_in_main_axis.IsAuto() &&
Style().IsDeprecatedWebkitBox() &&
(Style().BoxOrient() == EBoxOrient::kHorizontal ||
Style().BoxAlign() != EBoxAlignment::kStretch)) {
// 'auto' for items within a -webkit-box resolve as 'fit-content'.
return Length::FitContent();
}
return specified_length_in_main_axis;
}
return specified_flex_basis;
}
NGConstraintSpace NGFlexLayoutAlgorithm::BuildSpaceForLayout(
const NGBlockNode& flex_item_node,
LayoutUnit item_main_axis_final_size,
absl::optional<LayoutUnit> override_inline_size,
absl::optional<LayoutUnit> line_cross_size_for_stretch,
absl::optional<LayoutUnit> block_offset_for_fragmentation,
bool min_block_size_should_encompass_intrinsic_size) const {
const ComputedStyle& child_style = flex_item_node.Style();
NGConstraintSpaceBuilder space_builder(ConstraintSpace(),
child_style.GetWritingDirection(),
/* is_new_fc */ true);
SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item_node,
&space_builder);
space_builder.SetIsPaintedAtomically(true);
LogicalSize available_size;
if (is_column_) {
available_size.inline_size = line_cross_size_for_stretch
? *line_cross_size_for_stretch
: ChildAvailableSize().inline_size;
if (override_inline_size) {
DCHECK(!line_cross_size_for_stretch.has_value())
<< "We only override inline size when we are calculating intrinsic "
"width of multiline column flexboxes, and we don't do any "
"stretching during the intrinsic width calculation.";
available_size.inline_size = *override_inline_size;
space_builder.SetIsFixedInlineSize(true);
}
available_size.block_size = item_main_axis_final_size;
space_builder.SetIsFixedBlockSize(true);
if (line_cross_size_for_stretch ||
WillChildCrossSizeBeContainerCrossSize(flex_item_node))
space_builder.SetInlineAutoBehavior(NGAutoBehavior::kStretchExplicit);
// https://drafts.csswg.org/css-flexbox/#definite-sizes
// If the flex container has a definite main size, a flex item's
// post-flexing main size is treated as definite, even though it can
// rely on the indefinite sizes of any flex items in the same line.
if (!IsColumnContainerMainSizeDefinite() &&
!IsUsedFlexBasisDefinite(flex_item_node) &&
!AspectRatioProvidesMainSize(flex_item_node)) {
space_builder.SetIsInitialBlockSizeIndefinite(true);
}
} else {
DCHECK(!override_inline_size.has_value());
available_size.inline_size = item_main_axis_final_size;
available_size.block_size = line_cross_size_for_stretch
? *line_cross_size_for_stretch
: ChildAvailableSize().block_size;
space_builder.SetIsFixedInlineSize(true);
if (line_cross_size_for_stretch ||
WillChildCrossSizeBeContainerCrossSize(flex_item_node))
space_builder.SetBlockAutoBehavior(NGAutoBehavior::kStretchExplicit);
}
if (!line_cross_size_for_stretch && DoesItemStretch(flex_item_node)) {
// For the first layout pass of stretched items, the goal is to determine
// the post-flexed, pre-stretched cross-axis size. Stretched items will
// later get a final layout with a potentially different cross size so use
// the "measure" slot for this layout. We will use the "layout" cache slot
// for the item's final layout.
//
// Setting the "measure" cache slot on the space writes the result
// into both the "measure" and "layout" cache slots. So the stretch
// layout will reuse this "measure" result if it can.
space_builder.SetCacheSlot(NGCacheSlot::kMeasure);
} else if (block_offset_for_fragmentation &&
ConstraintSpace().HasBlockFragmentation()) {
if (min_block_size_should_encompass_intrinsic_size)
space_builder.SetMinBlockSizeShouldEncompassIntrinsicSize();
SetupSpaceBuilderForFragmentation(
ConstraintSpace(), flex_item_node, *block_offset_for_fragmentation,
&space_builder,
/* is_new_fc */ true,
container_builder_.RequiresContentBeforeBreaking());
}
space_builder.SetAvailableSize(available_size);
space_builder.SetPercentageResolutionSize(child_percentage_size_);
space_builder.SetReplacedPercentageResolutionSize(child_percentage_size_);
// For a button child, we need the baseline type same as the container's
// baseline type for UseCounter. For example, if the container's display
// property is 'inline-block', we need the last-line baseline of the
// child. See the bottom of GiveItemsFinalPositionAndSize().
if (Node().IsButton()) {
space_builder.SetBaselineAlgorithmType(
ConstraintSpace().BaselineAlgorithmType());
}
return space_builder.ToConstraintSpace();
}
void NGFlexLayoutAlgorithm::ConstructAndAppendFlexItems(
Phase phase,
HeapVector<Member<LayoutBox>>* oof_children) {
// This block sets up data collection for
// https://github.com/w3c/csswg-drafts/issues/3052
bool all_items_have_non_auto_cross_sizes = true;
bool all_items_match_container_alignment = true;
const StyleContentAlignmentData align_content =
algorithm_.ResolvedAlignContent(Style());
bool is_alignment_behavior_change_possible =
!algorithm_.IsMultiline() &&
align_content.Distribution() != ContentDistributionType::kStretch &&
align_content.GetPosition() != ContentPosition::kBaseline;
const LayoutUnit kAvailableFreeSpace(100);
LayoutUnit line_offset = FlexLayoutAlgorithm::InitialContentPositionOffset(
Style(), kAvailableFreeSpace, align_content,
/* number_of_items */ 1,
/* is_reversed */ false);
bool is_wrap_reverse = Style().FlexWrap() == EFlexWrap::kWrapReverse;
NGFlexChildIterator iterator(Node());
for (NGBlockNode child = iterator.NextChild(); child;
child = iterator.NextChild()) {
if (child.IsOutOfFlowPositioned()) {
if (phase == Phase::kLayout) {
DCHECK(oof_children);
oof_children->emplace_back(child.GetLayoutBox());
}
continue;
}
absl::optional<LayoutUnit> max_content_contribution;
if (phase == Phase::kColumnWrapIntrinsicSize) {
auto space = BuildSpaceForIntrinsicInlineSize(child);
MinMaxSizesResult child_contributions =
ComputeMinAndMaxContentContribution(Style(), child, space);
max_content_contribution = child_contributions.sizes.max_size;
NGBoxStrut child_margins =
ComputeMarginsFor(space, child.Style(), ConstraintSpace());
child_contributions.sizes += child_margins.InlineSum();
largest_min_content_contribution_ =
std::max(child_contributions.sizes.min_size,
largest_min_content_contribution_);
}
const ComputedStyle& child_style = child.Style();
const auto child_writing_mode = child_style.GetWritingMode();
if (is_alignment_behavior_change_possible &&
all_items_match_container_alignment && phase == Phase::kLayout) {
LayoutUnit item_offset = FlexItem::AlignmentOffset(
kAvailableFreeSpace,
FlexLayoutAlgorithm::AlignmentForChild(Style(), child_style),
LayoutUnit(), /* is_wrap_reverse */ false,
Style().IsDeprecatedWebkitBox());
all_items_match_container_alignment = (item_offset == line_offset);
}
NGConstraintSpace flex_basis_space = BuildSpaceForFlexBasis(child);
NGPhysicalBoxStrut physical_child_margins =
ComputePhysicalMargins(flex_basis_space, child_style);
NGBoxStrut border_padding_in_child_writing_mode =
ComputeBorders(flex_basis_space, child) +
ComputePadding(flex_basis_space, child_style);
NGPhysicalBoxStrut physical_border_padding(
border_padding_in_child_writing_mode.ConvertToPhysical(
child_style.GetWritingDirection()));
LayoutUnit main_axis_border_padding =
is_horizontal_flow_ ? physical_border_padding.HorizontalSum()
: physical_border_padding.VerticalSum();
LayoutUnit cross_axis_border_padding =
is_horizontal_flow_ ? physical_border_padding.VerticalSum()
: physical_border_padding.HorizontalSum();
const Length& cross_axis_length =
is_horizontal_flow_ ? child.Style().Height() : child.Style().Width();
all_items_have_non_auto_cross_sizes &= !cross_axis_length.IsAuto();
absl::optional<MinMaxSizesResult> min_max_sizes;
auto MinMaxSizesFunc = [&](MinMaxSizesType type) -> MinMaxSizesResult {
if (!min_max_sizes) {
// We want the child's intrinsic inline sizes in its writing mode, so
// pass child's writing mode as the first parameter, which is nominally
// |container_writing_mode|.
const auto child_space =
BuildSpaceForIntrinsicBlockSize(child, max_content_contribution);
min_max_sizes =
child.ComputeMinMaxSizes(child_writing_mode, type, child_space);
}
return *min_max_sizes;
};
MinMaxSizes min_max_sizes_in_main_axis_direction{main_axis_border_padding,
LayoutUnit::Max()};
MinMaxSizes min_max_sizes_in_cross_axis_direction{LayoutUnit(),
LayoutUnit::Max()};
const Length& max_property_in_main_axis = is_horizontal_flow_
? child.Style().MaxWidth()
: child.Style().MaxHeight();
if (MainAxisIsInlineAxis(child)) {
min_max_sizes_in_main_axis_direction.max_size = ResolveMaxInlineLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
MinMaxSizesFunc, max_property_in_main_axis);
min_max_sizes_in_cross_axis_direction = ComputeMinMaxBlockSizes(
flex_basis_space, child_style, border_padding_in_child_writing_mode);
} else {
min_max_sizes_in_main_axis_direction.max_size = ResolveMaxBlockLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
max_property_in_main_axis);
min_max_sizes_in_cross_axis_direction = ComputeMinMaxInlineSizes(
flex_basis_space, child, border_padding_in_child_writing_mode,
MinMaxSizesFunc);
}
auto ComputeTransferredMainSize = [&]() -> LayoutUnit {
DCHECK(!IsItemCrossAxisLengthDefinite(child, cross_axis_length) ||
!WillChildCrossSizeBeContainerCrossSize(child))
<< "IsItemCrossAxisLengthDefinite and "
"WillChildCrossSizeBeContainerCrossSize should be mutually "
"exclusive.";
LayoutUnit cross_size;
Length cross_axis_length_to_resolve = Length::FitContent();
if (IsItemCrossAxisLengthDefinite(child, cross_axis_length))
cross_axis_length_to_resolve = cross_axis_length;
else if (WillChildCrossSizeBeContainerCrossSize(child))
cross_axis_length_to_resolve = Length::FillAvailable();
if (MainAxisIsInlineAxis(child)) {
cross_size = ResolveMainBlockLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
cross_axis_length_to_resolve, kIndefiniteSize);
} else {
if (cross_axis_length_to_resolve.IsFitContent() &&
flex_basis_space.AvailableSize().inline_size == kIndefiniteSize) {
// TODO(dgrogan): Figure out if orthogonal items require a similar
// branch in the MainAxisIsInlineAxis case just above this.
DCHECK(phase == Phase::kColumnWrapIntrinsicSize);
cross_size = *max_content_contribution;
} else {
cross_size = ResolveMainInlineLength(
flex_basis_space, child_style,
border_padding_in_child_writing_mode, MinMaxSizesFunc,
cross_axis_length_to_resolve);
}
}
DCHECK_GE(cross_size, LayoutUnit());
cross_size = min_max_sizes_in_cross_axis_direction.ClampSizeToMinAndMax(
cross_size);
if (MainAxisIsInlineAxis(child)) {
return InlineSizeFromAspectRatio(
border_padding_in_child_writing_mode, child.GetAspectRatio(),
child_style.BoxSizingForAspectRatio(), cross_size);
}
return BlockSizeFromAspectRatio(
border_padding_in_child_writing_mode, child.GetAspectRatio(),
child_style.BoxSizingForAspectRatio(), cross_size);
};
const NGLayoutResult* layout_result = nullptr;
auto IntrinsicBlockSizeFunc =
[&](MinMaxSizesType type = MinMaxSizesType::kIntrinsic) -> LayoutUnit {
if (type == MinMaxSizesType::kContent && child.HasAspectRatio() &&
!child.IsReplaced()) {
// We don't enter here for replaced children because (a) this block
// doesn't account for natural sizes so wouldn't work for replaced
// elements, and (b) IntrinsicBlockSize() below already returns the
// kContent block size for replaced elements.
DCHECK(!AspectRatioProvidesMainSize(child))
<< "We only ever call IntrinsicBlockSizeFunc with kContent for "
"determing flex base size in case E. If "
"AspectRatioProvidesMainSize==true, we would have fallen into "
"case B, not case E.";
DCHECK(!MainAxisIsInlineAxis(child))
<< "We assume that the main axis is block axis in the call to "
"BlockSum() below.";
return AdjustMainSizeForAspectRatioCrossAxisMinAndMax(
child, ComputeTransferredMainSize(),
min_max_sizes_in_cross_axis_direction,
border_padding_in_child_writing_mode);
}
if (!layout_result) {
NGConstraintSpace child_space =
BuildSpaceForIntrinsicBlockSize(child, max_content_contribution);
layout_result = child.Layout(child_space, /* break_token */ nullptr);
DCHECK(layout_result);
}
return layout_result->IntrinsicBlockSize();
};
Length flex_basis_length;
LayoutUnit flex_base_border_box;
if (is_column_ && child_style.FlexBasis().IsPercentOrCalc())
has_column_percent_flex_basis_ = true;
if (!IsUsedFlexBasisDefinite(child, &flex_basis_length)) {
// This block means that the used flex-basis is 'content'. In here we
// implement parts B,C,D,E of 9.2.3
// https://drafts.csswg.org/css-flexbox/#algo-main-item
if (AspectRatioProvidesMainSize(child)) {
// This is Part B of 9.2.3
// https://drafts.csswg.org/css-flexbox/#algo-main-item It requires that
// the item has a definite cross size.
flex_base_border_box = ComputeTransferredMainSize();
} else if (MainAxisIsInlineAxis(child)) {
// We're now in parts C, D, and E for what are usually (horizontal-tb
// containers AND children) row flex containers. I _think_ the C and D
// cases are correctly handled by this code, which was originally
// written for case E.
flex_base_border_box =
MinMaxSizesFunc(MinMaxSizesType::kContent).sizes.max_size;
} else {
// Parts C, D, and E for what are usually column flex containers.
flex_base_border_box =
IntrinsicBlockSizeFunc(MinMaxSizesType::kContent);
}
} else {
DCHECK(!flex_basis_length.IsAuto());
DCHECK(!flex_basis_length.IsContent());
// Part A of 9.2.3 https://drafts.csswg.org/css-flexbox/#algo-main-item
if (MainAxisIsInlineAxis(child)) {
flex_base_border_box = ResolveMainInlineLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
MinMaxSizesFunc, flex_basis_length);
} else {
// Flex container's main axis is in child's block direction. Child's
// flex basis is in child's block direction.
flex_base_border_box = ResolveMainBlockLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
flex_basis_length, IntrinsicBlockSizeFunc);
if (const NGTableNode* table_child = DynamicTo<NGTableNode>(&child)) {
// (1) A table interprets forced block size as the height of its
// captions + rows.
// (2) The specified height of a table only applies to the rows.
// (3) So when we read the specified height here, we have to add the
// height of the captions before sending it through the flexing
// algorithm, which will eventually lead to a forced block size.
LayoutUnit caption_block_size = table_child->ComputeCaptionBlockSize(
BuildSpaceForIntrinsicBlockSize(*table_child,
max_content_contribution));
flex_base_border_box += caption_block_size;
}
}
}
// Spec calls this "flex base size"
// https://www.w3.org/TR/css-flexbox-1/#algo-main-item
// Blink's FlexibleBoxAlgorithm expects it to be content + scrollbar widths,
// but no padding or border.
DCHECK_GE(flex_base_border_box, main_axis_border_padding);
LayoutUnit flex_base_content_size =
flex_base_border_box - main_axis_border_padding;
const Length& min = is_horizontal_flow_ ? child.Style().MinWidth()
: child.Style().MinHeight();
if (algorithm_.ShouldApplyMinSizeAutoForChild(*child.GetLayoutBox())) {
LayoutUnit content_size_suggestion;
if (MainAxisIsInlineAxis(child)) {
content_size_suggestion =
MinMaxSizesFunc(MinMaxSizesType::kContent).sizes.min_size;
} else {
content_size_suggestion = IntrinsicBlockSizeFunc();
}
DCHECK_GE(content_size_suggestion, main_axis_border_padding);
if (child.HasAspectRatio() && !MainAxisIsInlineAxis(child)) {
content_size_suggestion =
AdjustMainSizeForAspectRatioCrossAxisMinAndMax(
child, content_size_suggestion,
min_max_sizes_in_cross_axis_direction,
border_padding_in_child_writing_mode);
}
LayoutUnit specified_size_suggestion = LayoutUnit::Max();
const Length& specified_length_in_main_axis =
is_horizontal_flow_ ? child_style.Width() : child_style.Height();
// If the item’s computed main size property is definite, then the
// specified size suggestion is that size.
if (MainAxisIsInlineAxis(child)) {
if (!specified_length_in_main_axis.IsAuto() &&
!InlineLengthUnresolvable(flex_basis_space,
specified_length_in_main_axis)) {
// Note: we may have already resolved specified_length_in_main_axis
// when calculating flex basis. Reusing that in the current code
// structure is a lot of work, so just recalculate here.
specified_size_suggestion = ResolveMainInlineLength(
flex_basis_space, child_style,
border_padding_in_child_writing_mode, MinMaxSizesFunc,
specified_length_in_main_axis);
}
} else if (!BlockLengthUnresolvable(flex_basis_space,
specified_length_in_main_axis)) {
specified_size_suggestion = ResolveMainBlockLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
specified_length_in_main_axis, IntrinsicBlockSizeFunc);
DCHECK_NE(specified_size_suggestion, kIndefiniteSize);
}
LayoutUnit transferred_size_suggestion = LayoutUnit::Max();
if (specified_size_suggestion == LayoutUnit::Max() &&
child.IsReplaced() && AspectRatioProvidesMainSize(child)) {
transferred_size_suggestion = ComputeTransferredMainSize();
}
DCHECK(specified_size_suggestion == LayoutUnit::Max() ||
transferred_size_suggestion == LayoutUnit::Max());
min_max_sizes_in_main_axis_direction.min_size =
std::min({specified_size_suggestion, content_size_suggestion,
transferred_size_suggestion,
min_max_sizes_in_main_axis_direction.max_size});
} else if (MainAxisIsInlineAxis(child)) {
min_max_sizes_in_main_axis_direction.min_size = ResolveMinInlineLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
MinMaxSizesFunc, min);
} else {
min_max_sizes_in_main_axis_direction.min_size =
ResolveMinBlockLength(flex_basis_space, child_style,
border_padding_in_child_writing_mode, min);
}
// Flex needs to never give a table a flexed main size that is less than its
// min-content size, so floor the min main-axis size by min-content size.
if (child.IsTable()) {
if (MainAxisIsInlineAxis(child)) {
min_max_sizes_in_main_axis_direction.Encompass(
MinMaxSizesFunc(MinMaxSizesType::kContent).sizes.min_size);
} else {
min_max_sizes_in_main_axis_direction.Encompass(
IntrinsicBlockSizeFunc());
}
}
min_max_sizes_in_main_axis_direction -= main_axis_border_padding;
DCHECK_GE(min_max_sizes_in_main_axis_direction.min_size, 0);
DCHECK_GE(min_max_sizes_in_main_axis_direction.max_size, 0);
const NGBoxStrut scrollbars = ComputeScrollbarsForNonAnonymous(child);
const auto container_writing_direction =
ConstraintSpace().GetWritingDirection();
bool is_last_baseline =
FlexLayoutAlgorithm::AlignmentForChild(Style(), child_style) ==
ItemPosition::kLastBaseline;
const auto baseline_writing_mode = DetermineBaselineWritingMode(
container_writing_direction, child_writing_mode,
/* is_parallel_context */ !is_column_);
const auto baseline_group = DetermineBaselineGroup(
container_writing_direction, baseline_writing_mode,
/* is_parallel_context */ !is_column_, is_last_baseline,
/* is_flipped */ is_wrap_reverse);
algorithm_
.emplace_back(nullptr, child.Style(), flex_base_content_size,
min_max_sizes_in_main_axis_direction,
min_max_sizes_in_cross_axis_direction,
main_axis_border_padding, cross_axis_border_padding,
physical_child_margins, scrollbars, baseline_writing_mode,