-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
GridTrackSizingAlgorithm.cpp
1738 lines (1484 loc) · 79 KB
/
GridTrackSizingAlgorithm.cpp
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 (C) 2017 Igalia S.L.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "GridTrackSizingAlgorithm.h"
#include "Grid.h"
#include "GridArea.h"
#include "GridLayoutFunctions.h"
#include "RenderGrid.h"
#include "rendering/style/RenderStyleConstants.h"
namespace WebCore {
LayoutUnit GridTrack::baseSize() const
{
ASSERT(isGrowthLimitBiggerThanBaseSize());
return std::max(m_baseSize, 0_lu);
}
LayoutUnit GridTrack::unclampedBaseSize() const
{
ASSERT(isGrowthLimitBiggerThanBaseSize());
return m_baseSize;
}
const LayoutUnit& GridTrack::growthLimit() const
{
ASSERT(isGrowthLimitBiggerThanBaseSize());
ASSERT(!m_growthLimitCap || m_growthLimitCap.value() >= m_growthLimit || baseSize() >= m_growthLimitCap.value());
return m_growthLimit;
}
void GridTrack::setBaseSize(LayoutUnit baseSize)
{
m_baseSize = baseSize;
ensureGrowthLimitIsBiggerThanBaseSize();
}
void GridTrack::setGrowthLimit(LayoutUnit growthLimit)
{
m_growthLimit = growthLimit == infinity ? growthLimit : std::min(growthLimit, m_growthLimitCap.value_or(growthLimit));
ensureGrowthLimitIsBiggerThanBaseSize();
}
LayoutUnit GridTrack::growthLimitIfNotInfinite() const
{
ASSERT(isGrowthLimitBiggerThanBaseSize());
return m_growthLimit == infinity ? baseSize() : m_growthLimit;
}
void GridTrack::setTempSize(const LayoutUnit& tempSize)
{
ASSERT(tempSize >= 0);
ASSERT(growthLimitIsInfinite() || growthLimit() >= tempSize);
m_tempSize = tempSize;
}
void GridTrack::growTempSize(const LayoutUnit& tempSize)
{
ASSERT(tempSize >= 0);
m_tempSize += tempSize;
}
void GridTrack::setGrowthLimitCap(std::optional<LayoutUnit> growthLimitCap)
{
ASSERT(!growthLimitCap || growthLimitCap.value() >= 0);
m_growthLimitCap = growthLimitCap;
}
const GridTrackSize& GridTrack::cachedTrackSize() const
{
RELEASE_ASSERT(m_cachedTrackSize);
return *m_cachedTrackSize;
}
void GridTrack::setCachedTrackSize(const GridTrackSize& cachedTrackSize)
{
m_cachedTrackSize = cachedTrackSize;
}
void GridTrack::ensureGrowthLimitIsBiggerThanBaseSize()
{
if (m_growthLimit != infinity && m_growthLimit < std::max(m_baseSize, 0_lu))
m_growthLimit = std::max(m_baseSize, 0_lu);
}
// Static helper methods.
static GridAxis gridAxisForDirection(GridTrackSizingDirection direction)
{
return direction == ForColumns ? GridRowAxis : GridColumnAxis;
}
static GridTrackSizingDirection gridDirectionForAxis(GridAxis axis)
{
return axis == GridRowAxis ? ForColumns : ForRows;
}
static bool hasRelativeMarginOrPaddingForChild(const RenderBox& child, GridTrackSizingDirection direction)
{
if (direction == ForColumns)
return child.style().marginStart().isPercentOrCalculated() || child.style().marginEnd().isPercentOrCalculated() || child.style().paddingStart().isPercentOrCalculated() || child.style().paddingEnd().isPercentOrCalculated();
return child.style().marginBefore().isPercentOrCalculated() || child.style().marginAfter().isPercentOrCalculated() || child.style().paddingBefore().isPercentOrCalculated() || child.style().paddingAfter().isPercentOrCalculated();
}
static bool hasRelativeOrIntrinsicSizeForChild(const RenderBox& child, GridTrackSizingDirection direction)
{
if (direction == ForColumns)
return child.hasRelativeLogicalWidth() || child.style().logicalWidth().isIntrinsicOrAuto();
return child.hasRelativeLogicalHeight() || child.style().logicalHeight().isIntrinsicOrAuto();
}
static bool shouldClearOverridingContainingBlockContentSizeForChild(const RenderBox& child, GridTrackSizingDirection direction)
{
return hasRelativeOrIntrinsicSizeForChild(child, direction) || hasRelativeMarginOrPaddingForChild(child, direction);
}
static void setOverridingContainingBlockContentSizeForChild(const RenderGrid& grid, RenderBox& child, GridTrackSizingDirection direction, std::optional<LayoutUnit> size)
{
// This function sets the dimension based on the writing mode of the containing block.
// For subgrids, this might not be the outermost grid, but could be a subgrid. If the
// writing mode of the CB and the grid for which we're doing sizing don't match, swap
// the directions.
direction = GridLayoutFunctions::flowAwareDirectionForChild(grid, *child.containingBlock(), direction);
if (direction == ForColumns)
child.setOverridingContainingBlockContentLogicalWidth(size);
else
child.setOverridingContainingBlockContentLogicalHeight(size);
}
// GridTrackSizingAlgorithm private.
void GridTrackSizingAlgorithm::setFreeSpace(GridTrackSizingDirection direction, std::optional<LayoutUnit> freeSpace)
{
if (direction == ForColumns)
m_freeSpaceColumns = freeSpace;
else
m_freeSpaceRows = freeSpace;
}
std::optional<LayoutUnit> GridTrackSizingAlgorithm::availableSpace() const
{
ASSERT(wasSetup());
return availableSpace(m_direction);
}
void GridTrackSizingAlgorithm::setAvailableSpace(GridTrackSizingDirection direction, std::optional<LayoutUnit> availableSpace)
{
if (direction == ForColumns)
m_availableSpaceColumns = availableSpace;
else
m_availableSpaceRows = availableSpace;
}
const GridTrackSize& GridTrackSizingAlgorithm::rawGridTrackSize(GridTrackSizingDirection direction, unsigned translatedIndex) const
{
bool isRowAxis = direction == ForColumns;
auto& renderStyle = m_renderGrid->style();
auto& trackStyles = isRowAxis ? renderStyle.gridColumnTrackSizes() : renderStyle.gridRowTrackSizes();
auto& autoRepeatTrackStyles = isRowAxis ? renderStyle.gridAutoRepeatColumns() : renderStyle.gridAutoRepeatRows();
auto& autoTrackStyles = isRowAxis ? renderStyle.gridAutoColumns() : renderStyle.gridAutoRows();
unsigned insertionPoint = isRowAxis ? renderStyle.gridAutoRepeatColumnsInsertionPoint() : renderStyle.gridAutoRepeatRowsInsertionPoint();
unsigned autoRepeatTracksCount = m_grid.autoRepeatTracks(direction);
// We should not use GridPositionsResolver::explicitGridXXXCount() for this because the
// explicit grid might be larger than the number of tracks in grid-template-rows|columns (if
// grid-template-areas is specified for example).
unsigned explicitTracksCount = trackStyles.size() + autoRepeatTracksCount;
int untranslatedIndexAsInt = translatedIndex - m_grid.explicitGridStart(direction);
unsigned autoTrackStylesSize = autoTrackStyles.size();
if (untranslatedIndexAsInt < 0) {
int index = untranslatedIndexAsInt % static_cast<int>(autoTrackStylesSize);
// We need to traspose the index because the first negative implicit line will get the last defined auto track and so on.
index += index ? autoTrackStylesSize : 0;
ASSERT(index >= 0);
return autoTrackStyles[index];
}
unsigned untranslatedIndex = static_cast<unsigned>(untranslatedIndexAsInt);
if (untranslatedIndex >= explicitTracksCount)
return autoTrackStyles[(untranslatedIndex - explicitTracksCount) % autoTrackStylesSize];
if (!autoRepeatTracksCount || untranslatedIndex < insertionPoint)
return trackStyles[untranslatedIndex];
if (untranslatedIndex < (insertionPoint + autoRepeatTracksCount)) {
unsigned autoRepeatLocalIndex = untranslatedIndexAsInt - insertionPoint;
return autoRepeatTrackStyles[autoRepeatLocalIndex % autoRepeatTrackStyles.size()];
}
return trackStyles[untranslatedIndex - autoRepeatTracksCount];
}
LayoutUnit GridTrackSizingAlgorithm::computeTrackBasedSize() const
{
if (isDirectionInMasonryDirection())
return m_renderGrid->masonryContentSize();
LayoutUnit size;
auto& allTracks = tracks(m_direction);
for (auto& track : allTracks)
size += track.baseSize();
size += m_renderGrid->guttersSize(m_direction, 0, allTracks.size(), availableSpace());
return size;
}
LayoutUnit GridTrackSizingAlgorithm::initialBaseSize(const GridTrackSize& trackSize) const
{
const GridLength& gridLength = trackSize.minTrackBreadth();
if (gridLength.isFlex())
return 0;
const Length& trackLength = gridLength.length();
if (trackLength.isSpecified())
return valueForLength(trackLength, std::max<LayoutUnit>(availableSpace().value_or(0), 0));
ASSERT(trackLength.isMinContent() || trackLength.isAuto() || trackLength.isMaxContent());
return 0;
}
LayoutUnit GridTrackSizingAlgorithm::initialGrowthLimit(const GridTrackSize& trackSize, LayoutUnit baseSize) const
{
const GridLength& gridLength = trackSize.maxTrackBreadth();
if (gridLength.isFlex())
return trackSize.minTrackBreadth().isContentSized() ? LayoutUnit(infinity) : baseSize;
const Length& trackLength = gridLength.length();
if (trackLength.isSpecified())
return valueForLength(trackLength, std::max<LayoutUnit>(availableSpace().value_or(0), 0));
ASSERT(trackLength.isMinContent() || trackLength.isAuto() || trackLength.isMaxContent());
return infinity;
}
void GridTrackSizingAlgorithm::sizeTrackToFitNonSpanningItem(const GridSpan& span, RenderBox& gridItem, GridTrack& track)
{
unsigned trackPosition = span.startLine();
const auto& trackSize = tracks(m_direction)[trackPosition].cachedTrackSize();
if (trackSize.hasMinContentMinTrackBreadth()) {
track.setBaseSize(std::max(track.baseSize(), m_strategy->minContentForChild(gridItem)));
} else if (trackSize.hasMaxContentMinTrackBreadth()) {
track.setBaseSize(std::max(track.baseSize(), m_strategy->maxContentForChild(gridItem)));
} else if (trackSize.hasAutoMinTrackBreadth()) {
track.setBaseSize(std::max(track.baseSize(), m_strategy->minSizeForChild(gridItem)));
}
if (trackSize.hasMinContentMaxTrackBreadth()) {
track.setGrowthLimit(std::max(track.growthLimit(), m_strategy->minContentForChild(gridItem)));
} else if (trackSize.hasMaxContentOrAutoMaxTrackBreadth()) {
LayoutUnit growthLimit = m_strategy->maxContentForChild(gridItem);
if (trackSize.isFitContent())
growthLimit = std::min(growthLimit, valueForLength(trackSize.fitContentTrackBreadth().length(), availableSpace().value_or(0)));
track.setGrowthLimit(std::max(track.growthLimit(), growthLimit));
}
}
bool GridTrackSizingAlgorithm::spanningItemCrossesFlexibleSizedTracks(const GridSpan& itemSpan) const
{
const Vector<GridTrack>& trackList = tracks(m_direction);
for (auto trackPosition : itemSpan) {
const auto& trackSize = trackList[trackPosition].cachedTrackSize();
if (trackSize.minTrackBreadth().isFlex() || trackSize.maxTrackBreadth().isFlex())
return true;
}
return false;
}
class GridItemWithSpan {
public:
GridItemWithSpan(RenderBox& gridItem, GridSpan span)
: m_gridItem(gridItem)
, m_span(span)
{
}
RenderBox& gridItem() const { return m_gridItem; }
GridSpan span() const { return m_span; }
bool operator<(const GridItemWithSpan other) const { return m_span.integerSpan() < other.m_span.integerSpan(); }
private:
std::reference_wrapper<RenderBox> m_gridItem;
GridSpan m_span;
};
struct GridItemsSpanGroupRange {
Vector<GridItemWithSpan>::iterator rangeStart;
Vector<GridItemWithSpan>::iterator rangeEnd;
};
enum TrackSizeRestriction {
AllowInfinity,
ForbidInfinity,
};
LayoutUnit GridTrackSizingAlgorithm::itemSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, RenderBox& gridItem) const
{
switch (phase) {
case ResolveIntrinsicMinimums:
return m_strategy->minSizeForChild(gridItem);
case ResolveContentBasedMinimums:
case ResolveIntrinsicMaximums:
return m_strategy->minContentForChild(gridItem);
case ResolveMaxContentMinimums:
case ResolveMaxContentMaximums:
return m_strategy->maxContentForChild(gridItem);
case MaximizeTracks:
ASSERT_NOT_REACHED();
return 0;
}
ASSERT_NOT_REACHED();
return 0;
}
static bool shouldProcessTrackForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
{
switch (phase) {
case ResolveIntrinsicMinimums:
return trackSize.hasIntrinsicMinTrackBreadth();
case ResolveContentBasedMinimums:
return trackSize.hasMinOrMaxContentMinTrackBreadth();
case ResolveMaxContentMinimums:
return trackSize.hasMaxContentMinTrackBreadth();
case ResolveIntrinsicMaximums:
return trackSize.hasIntrinsicMaxTrackBreadth();
case ResolveMaxContentMaximums:
return trackSize.hasMaxContentOrAutoMaxTrackBreadth();
case MaximizeTracks:
ASSERT_NOT_REACHED();
return false;
}
ASSERT_NOT_REACHED();
return false;
}
static LayoutUnit trackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track, TrackSizeRestriction restriction)
{
switch (phase) {
case ResolveIntrinsicMinimums:
case ResolveContentBasedMinimums:
case ResolveMaxContentMinimums:
case MaximizeTracks:
return track.baseSize();
case ResolveIntrinsicMaximums:
case ResolveMaxContentMaximums:
return restriction == AllowInfinity ? track.growthLimit() : track.growthLimitIfNotInfinite();
}
ASSERT_NOT_REACHED();
return track.baseSize();
}
static void updateTrackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
{
switch (phase) {
case ResolveIntrinsicMinimums:
case ResolveContentBasedMinimums:
case ResolveMaxContentMinimums:
track.setBaseSize(track.plannedSize());
return;
case ResolveIntrinsicMaximums:
case ResolveMaxContentMaximums:
track.setGrowthLimit(track.plannedSize());
return;
case MaximizeTracks:
ASSERT_NOT_REACHED();
return;
}
ASSERT_NOT_REACHED();
}
static bool trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
{
switch (phase) {
case ResolveIntrinsicMinimums:
case ResolveContentBasedMinimums:
return trackSize.hasAutoOrMinContentMinTrackBreadthAndIntrinsicMaxTrackBreadth();
case ResolveMaxContentMinimums:
return trackSize.hasMaxContentMinTrackBreadthAndMaxContentMaxTrackBreadth();
case ResolveIntrinsicMaximums:
case ResolveMaxContentMaximums:
return true;
case MaximizeTracks:
ASSERT_NOT_REACHED();
return false;
}
ASSERT_NOT_REACHED();
return false;
}
static void markAsInfinitelyGrowableForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
{
switch (phase) {
case ResolveIntrinsicMinimums:
case ResolveContentBasedMinimums:
case ResolveMaxContentMinimums:
return;
case ResolveIntrinsicMaximums:
if (trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity) == infinity && track.plannedSize() != infinity)
track.setInfinitelyGrowable(true);
return;
case ResolveMaxContentMaximums:
if (track.infinitelyGrowable())
track.setInfinitelyGrowable(false);
return;
case MaximizeTracks:
ASSERT_NOT_REACHED();
return;
}
ASSERT_NOT_REACHED();
}
template <TrackSizeComputationVariant variant, TrackSizeComputationPhase phase>
void GridTrackSizingAlgorithm::increaseSizesToAccommodateSpanningItems(const GridItemsSpanGroupRange& gridItemsWithSpan)
{
Vector<GridTrack>& allTracks = tracks(m_direction);
for (const auto& trackIndex : m_contentSizedTracksIndex) {
GridTrack& track = allTracks[trackIndex];
track.setPlannedSize(trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity));
}
Vector<GridTrack*> growBeyondGrowthLimitsTracks;
Vector<GridTrack*> filteredTracks;
for (auto it = gridItemsWithSpan.rangeStart; it != gridItemsWithSpan.rangeEnd; ++it) {
GridItemWithSpan& gridItemWithSpan = *it;
const GridSpan& itemSpan = gridItemWithSpan.span();
ASSERT(variant == TrackSizeComputationVariant::CrossingFlexibleTracks || itemSpan.integerSpan() > 1u);
filteredTracks.shrink(0);
growBeyondGrowthLimitsTracks.shrink(0);
LayoutUnit spanningTracksSize;
for (auto trackPosition : itemSpan) {
GridTrack& track = allTracks[trackPosition];
const auto& trackSize = track.cachedTrackSize();
spanningTracksSize += trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
if (variant == TrackSizeComputationVariant::CrossingFlexibleTracks && !trackSize.maxTrackBreadth().isFlex())
continue;
if (!shouldProcessTrackForTrackSizeComputationPhase(phase, trackSize))
continue;
filteredTracks.append(&track);
if (trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(phase, trackSize))
growBeyondGrowthLimitsTracks.append(&track);
}
if (filteredTracks.isEmpty())
continue;
spanningTracksSize += m_renderGrid->guttersSize(m_direction, itemSpan.startLine(), itemSpan.integerSpan(), availableSpace());
LayoutUnit extraSpace = itemSizeForTrackSizeComputationPhase(phase, gridItemWithSpan.gridItem()) - spanningTracksSize;
extraSpace = std::max<LayoutUnit>(extraSpace, 0);
auto& tracksToGrowBeyondGrowthLimits = growBeyondGrowthLimitsTracks.isEmpty() ? filteredTracks : growBeyondGrowthLimitsTracks;
distributeSpaceToTracks<variant, phase>(filteredTracks, &tracksToGrowBeyondGrowthLimits, extraSpace);
}
for (const auto& trackIndex : m_contentSizedTracksIndex) {
GridTrack& track = allTracks[trackIndex];
markAsInfinitelyGrowableForTrackSizeComputationPhase(phase, track);
updateTrackSizeForTrackSizeComputationPhase(phase, track);
}
}
template <TrackSizeComputationVariant variant>
void GridTrackSizingAlgorithm::increaseSizesToAccommodateSpanningItems(const GridItemsSpanGroupRange& gridItemsWithSpan)
{
increaseSizesToAccommodateSpanningItems<variant, ResolveIntrinsicMinimums>(gridItemsWithSpan);
increaseSizesToAccommodateSpanningItems<variant, ResolveContentBasedMinimums>(gridItemsWithSpan);
increaseSizesToAccommodateSpanningItems<variant, ResolveMaxContentMinimums>(gridItemsWithSpan);
increaseSizesToAccommodateSpanningItems<variant, ResolveIntrinsicMaximums>(gridItemsWithSpan);
increaseSizesToAccommodateSpanningItems<variant, ResolveMaxContentMaximums>(gridItemsWithSpan);
}
template <TrackSizeComputationVariant variant>
static double getSizeDistributionWeight(const GridTrack& track)
{
if (variant != TrackSizeComputationVariant::CrossingFlexibleTracks)
return 0;
ASSERT(track.cachedTrackSize().maxTrackBreadth().isFlex());
return track.cachedTrackSize().maxTrackBreadth().flex();
}
static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
{
// This check ensures that we respect the irreflexivity property of the strict weak ordering required by std::sort
// (forall x: NOT x < x).
bool track1HasInfiniteGrowthPotentialWithoutCap = track1->infiniteGrowthPotential() && !track1->growthLimitCap();
bool track2HasInfiniteGrowthPotentialWithoutCap = track2->infiniteGrowthPotential() && !track2->growthLimitCap();
if (track1HasInfiniteGrowthPotentialWithoutCap && track2HasInfiniteGrowthPotentialWithoutCap)
return false;
if (track1HasInfiniteGrowthPotentialWithoutCap || track2HasInfiniteGrowthPotentialWithoutCap)
return track2HasInfiniteGrowthPotentialWithoutCap;
LayoutUnit track1Limit = track1->growthLimitCap().value_or(track1->growthLimit());
LayoutUnit track2Limit = track2->growthLimitCap().value_or(track2->growthLimit());
return (track1Limit - track1->baseSize()) < (track2Limit - track2->baseSize());
}
static void clampGrowthShareIfNeeded(TrackSizeComputationPhase phase, const GridTrack& track, LayoutUnit& growthShare)
{
if (phase != ResolveMaxContentMaximums || !track.growthLimitCap())
return;
LayoutUnit distanceToCap = track.growthLimitCap().value() - track.tempSize();
if (distanceToCap <= 0)
return;
growthShare = std::min(growthShare, distanceToCap);
}
template <TrackSizeComputationPhase phase, SpaceDistributionLimit limit>
static void distributeItemIncurredIncreaseToTrack(GridTrack& track, LayoutUnit& freeSpace, double shareFraction)
{
LayoutUnit freeSpaceShare(freeSpace / shareFraction);
LayoutUnit growthShare = limit == SpaceDistributionLimit::BeyondGrowthLimit || track.infiniteGrowthPotential() ? freeSpaceShare : std::min(freeSpaceShare, track.growthLimit() - trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity));
clampGrowthShareIfNeeded(phase, track, growthShare);
ASSERT_WITH_MESSAGE(growthShare >= 0, "We must never shrink any grid track or else we can't guarantee we abide by our min-sizing function.");
track.growTempSize(growthShare);
freeSpace -= growthShare;
}
template <TrackSizeComputationVariant variant, TrackSizeComputationPhase phase, SpaceDistributionLimit limit>
static void distributeItemIncurredIncreases(Vector<GridTrack*>& tracks, LayoutUnit& freeSpace)
{
uint32_t tracksSize = tracks.size();
if (!tracksSize)
return;
if (variant == TrackSizeComputationVariant::NotCrossingFlexibleTracks) {
// We have to sort tracks according to their growth potential. This is necessary even when distributing beyond growth limits,
// because there might be tracks with growth limit caps (like the ones with fit-content()) which cannot indefinitely grow over the limits.
std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
for (uint32_t i = 0; i < tracksSize; ++i) {
ASSERT(!getSizeDistributionWeight<variant>(*tracks[i]));
distributeItemIncurredIncreaseToTrack<phase, limit>(*tracks[i], freeSpace, tracksSize - i);
}
return;
}
// We never grow flex tracks beyond growth limits, since they are infinite.
ASSERT(limit != SpaceDistributionLimit::BeyondGrowthLimit);
// For TrackSizeComputationVariant::CrossingFlexibleTracks we don't distribute equally, we need to take the weights into account.
Vector<double> fractionsOfRemainingSpace(tracksSize);
double weightSum = 0;
for (int32_t i = tracksSize - 1; i >= 0; --i) {
double weight = getSizeDistributionWeight<variant>(*tracks[i]);
weightSum += weight;
fractionsOfRemainingSpace[i] = weightSum > 0 ? weightSum / weight : tracksSize - i;
}
for (uint32_t i = 0; i < tracksSize; ++i) {
// Sorting is not needed for TrackSizeComputationVariant::CrossingFlexibleTracks, since all tracks have an infinite growth potential.
ASSERT(tracks[i]->growthLimitIsInfinite());
distributeItemIncurredIncreaseToTrack<phase, limit>(*tracks[i], freeSpace, fractionsOfRemainingSpace[i]);
}
}
template <TrackSizeComputationVariant variant, TrackSizeComputationPhase phase>
void GridTrackSizingAlgorithm::distributeSpaceToTracks(Vector<GridTrack*>& tracks, Vector<GridTrack*>* growBeyondGrowthLimitsTracks, LayoutUnit& freeSpace) const
{
ASSERT(freeSpace >= 0);
for (auto* track : tracks)
track->setTempSize(trackSizeForTrackSizeComputationPhase(phase, *track, ForbidInfinity));
if (freeSpace > 0)
distributeItemIncurredIncreases<variant, phase, SpaceDistributionLimit::UpToGrowthLimit>(tracks, freeSpace);
if (freeSpace > 0 && growBeyondGrowthLimitsTracks)
distributeItemIncurredIncreases<variant, phase, SpaceDistributionLimit::BeyondGrowthLimit>(*growBeyondGrowthLimitsTracks, freeSpace);
for (auto* track : tracks)
track->setPlannedSize(track->plannedSize() == infinity ? track->tempSize() : std::max(track->plannedSize(), track->tempSize()));
}
std::optional<LayoutUnit> GridTrackSizingAlgorithm::estimatedGridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction) const
{
const GridSpan& span = m_renderGrid->gridSpanForChild(child, direction);
LayoutUnit gridAreaSize;
bool gridAreaIsIndefinite = false;
std::optional<LayoutUnit> availableSize = availableSpace(direction);
for (auto trackPosition : span) {
// We may need to estimate the grid area size before running the track sizing algorithm in order to perform the pre-layout of orthogonal items.
// We cannot use tracks(direction)[trackPosition].cachedTrackSize() because tracks(direction) is empty, since we are either performing pre-layout
// or are running the track sizing algorithm in the opposite direction and haven't run it in the desired direction yet.
const auto& trackSize = wasSetup() ? calculateGridTrackSize(direction, trackPosition) : rawGridTrackSize(direction, trackPosition);
GridLength maxTrackSize = trackSize.maxTrackBreadth();
if (maxTrackSize.isContentSized() || maxTrackSize.isFlex() || isRelativeGridLengthAsAuto(maxTrackSize, direction))
gridAreaIsIndefinite = true;
else
gridAreaSize += valueForLength(maxTrackSize.length(), availableSize.value_or(0_lu));
}
gridAreaSize += m_renderGrid->guttersSize(direction, span.startLine(), span.integerSpan(), availableSize);
GridTrackSizingDirection childInlineDirection = GridLayoutFunctions::flowAwareDirectionForChild(*m_renderGrid, child, ForColumns);
if (gridAreaIsIndefinite)
return direction == childInlineDirection ? std::make_optional(std::max(child.maxPreferredLogicalWidth(), gridAreaSize)) : std::nullopt;
return gridAreaSize;
}
std::optional<LayoutUnit> GridTrackSizingAlgorithm::gridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction) const
{
bool addContentAlignmentOffset =
direction == ForColumns && (m_sizingState == RowSizingFirstIteration || m_sizingState == RowSizingExtraIterationForSizeContainment);
// To determine the column track's size based on an orthogonal grid item we need it's logical
// height, which may depend on the row track's size. It's possible that the row tracks sizing
// logic has not been performed yet, so we will need to do an estimation.
if (direction == ForRows && (m_sizingState == ColumnSizingFirstIteration || m_sizingState == ColumnSizingSecondIteration) && !m_renderGrid->areMasonryColumns()) {
ASSERT(GridLayoutFunctions::isOrthogonalChild(*m_renderGrid, child));
// FIXME (jfernandez) Content Alignment should account for this heuristic.
// https://github.com/w3c/csswg-drafts/issues/2697
if (m_sizingState == ColumnSizingFirstIteration)
return estimatedGridAreaBreadthForChild(child, ForRows);
addContentAlignmentOffset = true;
}
const Vector<GridTrack>& allTracks = tracks(direction);
const GridSpan& span = m_renderGrid->gridSpanForChild(child, direction);
LayoutUnit gridAreaBreadth;
for (auto trackPosition : span)
gridAreaBreadth += allTracks[trackPosition].baseSize();
if (addContentAlignmentOffset)
gridAreaBreadth += (span.integerSpan() - 1) * m_renderGrid->gridItemOffset(direction);
gridAreaBreadth += m_renderGrid->guttersSize(direction, span.startLine(), span.integerSpan(), availableSpace(direction));
return gridAreaBreadth;
}
bool GridTrackSizingAlgorithm::isRelativeGridLengthAsAuto(const GridLength& length, GridTrackSizingDirection direction) const
{
return length.isPercentage() && !availableSpace(direction);
}
bool GridTrackSizingAlgorithm::isIntrinsicSizedGridArea(const RenderBox& child, GridAxis axis) const
{
ASSERT(wasSetup());
GridTrackSizingDirection direction = gridDirectionForAxis(axis);
const GridSpan& span = m_renderGrid->gridSpanForChild(child, direction);
for (auto trackPosition : span) {
const auto& trackSize = rawGridTrackSize(direction, trackPosition);
// We consider fr units as 'auto' for the min sizing function.
// FIXME(jfernandez): https://github.com/w3c/csswg-drafts/issues/2611
//
// The use of AvailableSize function may imply different results
// for the same item when assuming indefinite or definite size
// constraints depending on the phase we evaluate the item's
// baseline participation.
// FIXME(jfernandez): https://github.com/w3c/csswg-drafts/issues/3046
if (trackSize.isContentSized() || trackSize.isFitContent() || trackSize.minTrackBreadth().isFlex() || (trackSize.maxTrackBreadth().isFlex() && !availableSpace(direction)))
return true;
}
return false;
}
GridTrackSize GridTrackSizingAlgorithm::calculateGridTrackSize(GridTrackSizingDirection direction, unsigned translatedIndex) const
{
ASSERT(wasSetup());
// Collapse empty auto repeat tracks if auto-fit.
if (m_grid.hasAutoRepeatEmptyTracks(direction) && m_grid.isEmptyAutoRepeatTrack(direction, translatedIndex))
return { Length(LengthType::Fixed), LengthTrackSizing };
auto& trackSize = rawGridTrackSize(direction, translatedIndex);
if (trackSize.isFitContent())
return isRelativeGridLengthAsAuto(trackSize.fitContentTrackBreadth(), direction) ? GridTrackSize(Length(LengthType::Auto), Length(LengthType::MaxContent)) : trackSize;
GridLength minTrackBreadth = trackSize.minTrackBreadth();
GridLength maxTrackBreadth = trackSize.maxTrackBreadth();
// If the logical width/height of the grid container is indefinite, percentage
// values are treated as <auto>.
if (isRelativeGridLengthAsAuto(trackSize.minTrackBreadth(), direction))
minTrackBreadth = Length(LengthType::Auto);
if (isRelativeGridLengthAsAuto(trackSize.maxTrackBreadth(), direction))
maxTrackBreadth = Length(LengthType::Auto);
// Flex sizes are invalid as a min sizing function. However we still can have a flexible |minTrackBreadth|
// if the track size is just a flex size (e.g. "1fr"), the spec says that in this case it implies an automatic minimum.
if (minTrackBreadth.isFlex())
minTrackBreadth = Length(LengthType::Auto);
return GridTrackSize(minTrackBreadth, maxTrackBreadth);
}
double GridTrackSizingAlgorithm::computeFlexFactorUnitSize(const Vector<GridTrack>& tracks, double flexFactorSum, LayoutUnit& leftOverSpace, const Vector<unsigned, 8>& flexibleTracksIndexes, std::unique_ptr<TrackIndexSet> tracksToTreatAsInflexible) const
{
// We want to avoid the effect of flex factors sum below 1 making the factor unit size to grow exponentially.
double hypotheticalFactorUnitSize = leftOverSpace / std::max<double>(1, flexFactorSum);
// product of the hypothetical "flex factor unit" and any flexible track's "flex factor" must be grater than such track's "base size".
bool validFlexFactorUnit = true;
for (auto index : flexibleTracksIndexes) {
if (tracksToTreatAsInflexible && tracksToTreatAsInflexible->contains(index))
continue;
LayoutUnit baseSize = tracks[index].baseSize();
double flexFactor = tracks[index].cachedTrackSize().maxTrackBreadth().flex();
// treating all such tracks as inflexible.
if (baseSize > hypotheticalFactorUnitSize * flexFactor) {
leftOverSpace -= baseSize;
flexFactorSum -= flexFactor;
if (!tracksToTreatAsInflexible)
tracksToTreatAsInflexible = makeUnique<TrackIndexSet>();
tracksToTreatAsInflexible->add(index);
validFlexFactorUnit = false;
}
}
if (!validFlexFactorUnit)
return computeFlexFactorUnitSize(tracks, flexFactorSum, leftOverSpace, flexibleTracksIndexes, WTFMove(tracksToTreatAsInflexible));
return hypotheticalFactorUnitSize;
}
void GridTrackSizingAlgorithm::computeFlexSizedTracksGrowth(double flexFraction, Vector<LayoutUnit>& increments, LayoutUnit& totalGrowth) const
{
size_t numFlexTracks = m_flexibleSizedTracksIndex.size();
ASSERT(increments.size() == numFlexTracks);
const Vector<GridTrack>& allTracks = tracks(m_direction);
// The flexFraction multiplied by the flex factor can result in a non-integer size. Since we floor the stretched size to fit in a LayoutUnit,
// we may lose the fractional part of the computation which can cause the entire free space not being distributed evenly. The leftover
// fractional part from every flexible track are accumulated here to avoid this issue.
double leftOverSize = 0;
for (size_t i = 0; i < numFlexTracks; ++i) {
unsigned trackIndex = m_flexibleSizedTracksIndex[i];
const auto& trackSize = allTracks[trackIndex].cachedTrackSize();
ASSERT(trackSize.maxTrackBreadth().isFlex());
LayoutUnit oldBaseSize = allTracks[trackIndex].baseSize();
double frShare = flexFraction * trackSize.maxTrackBreadth().flex() + leftOverSize;
auto stretchedSize = LayoutUnit(frShare);
LayoutUnit newBaseSize = std::max(oldBaseSize, stretchedSize);
increments[i] = newBaseSize - oldBaseSize;
totalGrowth += increments[i];
// In the case that stretchedSize is greater than frShare, we floor it to 0 to avoid a negative leftover.
leftOverSize = std::max(frShare - stretchedSize.toDouble(), 0.0);
}
}
double GridTrackSizingAlgorithm::findFrUnitSize(const GridSpan& tracksSpan, LayoutUnit leftOverSpace) const
{
if (leftOverSpace <= 0)
return 0;
const Vector<GridTrack>& allTracks = tracks(m_direction);
double flexFactorSum = 0;
Vector<unsigned, 8> flexibleTracksIndexes;
for (auto trackIndex : tracksSpan) {
const auto& trackSize = allTracks[trackIndex].cachedTrackSize();
if (!trackSize.maxTrackBreadth().isFlex())
leftOverSpace -= allTracks[trackIndex].baseSize();
else {
double flexFactor = trackSize.maxTrackBreadth().flex();
flexibleTracksIndexes.append(trackIndex);
flexFactorSum += flexFactor;
}
}
// We don't remove the gutters from left_over_space here, because that was already done before.
// The function is not called if we don't have <flex> grid tracks.
ASSERT(!flexibleTracksIndexes.isEmpty());
return computeFlexFactorUnitSize(allTracks, flexFactorSum, leftOverSpace, flexibleTracksIndexes);
}
void GridTrackSizingAlgorithm::computeGridContainerIntrinsicSizes()
{
if (m_direction == ForColumns && m_strategy->isComputingSizeContainment()) {
if (auto size = m_renderGrid->explicitIntrinsicInnerLogicalSize(m_direction)) {
m_minContentSize = size.value();
m_maxContentSize = size.value();
return;
}
}
m_minContentSize = m_maxContentSize = 0_lu;
Vector<GridTrack>& allTracks = tracks(m_direction);
for (auto& track : allTracks) {
ASSERT(m_strategy->isComputingSizeContainment() || m_strategy->isComputingInlineSizeContainment() || !track.infiniteGrowthPotential());
m_minContentSize += track.baseSize();
m_maxContentSize += track.growthLimitIsInfinite() ? track.baseSize() : track.growthLimit();
// The growth limit caps must be cleared now in order to properly sort
// tracks by growth potential on an eventual "Maximize Tracks".
track.setGrowthLimitCap(std::nullopt);
}
}
// GridTrackSizingAlgorithmStrategy.
LayoutUnit GridTrackSizingAlgorithmStrategy::logicalHeightForChild(RenderBox& child) const
{
GridTrackSizingDirection childBlockDirection = GridLayoutFunctions::flowAwareDirectionForChild(*renderGrid(), child, ForRows);
// If |child| has a relative logical height, we shouldn't let it override its intrinsic height, which is
// what we are interested in here. Thus we need to set the block-axis override size to nullopt (no possible resolution).
if (shouldClearOverridingContainingBlockContentSizeForChild(child, ForRows)) {
setOverridingContainingBlockContentSizeForChild(*renderGrid(), child, childBlockDirection, std::nullopt);
child.setNeedsLayout(MarkOnlyThis);
}
// We need to clear the stretched content size to properly compute logical height during layout.
if (child.needsLayout())
child.clearOverridingContentSize();
child.layoutIfNeeded();
return child.logicalHeight() + GridLayoutFunctions::marginLogicalSizeForChild(*renderGrid(), childBlockDirection, child) + m_algorithm.baselineOffsetForChild(child, gridAxisForDirection(direction()));
}
LayoutUnit GridTrackSizingAlgorithmStrategy::minContentForChild(RenderBox& child) const
{
GridTrackSizingDirection childInlineDirection = GridLayoutFunctions::flowAwareDirectionForChild(*renderGrid(), child, ForColumns);
if (direction() == childInlineDirection) {
if (isComputingInlineSizeContainment())
return { };
// FIXME: It's unclear if we should return the intrinsic width or the preferred width.
// See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
if (child.needsPreferredWidthsRecalculation())
child.setPreferredLogicalWidthsDirty(true);
return child.minPreferredLogicalWidth() + GridLayoutFunctions::marginLogicalSizeForChild(*renderGrid(), childInlineDirection, child) + m_algorithm.baselineOffsetForChild(child, gridAxisForDirection(direction()));
}
if (updateOverridingContainingBlockContentSizeForChild(child, childInlineDirection)) {
child.setNeedsLayout(MarkOnlyThis);
// For a child with relative width constraints to the grid area, such as percentaged paddings, we reset the overridingContainingBlockContentSizeForChild value for columns when we are executing a definite strategy
// for columns. Since we have updated the overridingContainingBlockContentSizeForChild inline-axis/width value here, we might need to recompute the child's relative width. For some cases, we probably will not
// be able to do it during the RenderGrid::layoutGridItems() function as the grid area does't change there any more. Also, as we are doing a layout inside GridTrackSizingAlgorithmStrategy::logicalHeightForChild()
// function, let's take the advantage and set it here.
if (shouldClearOverridingContainingBlockContentSizeForChild(child, childInlineDirection))
child.setPreferredLogicalWidthsDirty(true);
}
return logicalHeightForChild(child);
}
LayoutUnit GridTrackSizingAlgorithmStrategy::maxContentForChild(RenderBox& child) const
{
GridTrackSizingDirection childInlineDirection = GridLayoutFunctions::flowAwareDirectionForChild(*renderGrid(), child, ForColumns);
if (direction() == childInlineDirection) {
if (isComputingInlineSizeContainment())
return { };
// FIXME: It's unclear if we should return the intrinsic width or the preferred width.
// See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
if (child.needsPreferredWidthsRecalculation())
child.setPreferredLogicalWidthsDirty(true);
return child.maxPreferredLogicalWidth() + GridLayoutFunctions::marginLogicalSizeForChild(*renderGrid(), childInlineDirection, child) + m_algorithm.baselineOffsetForChild(child, gridAxisForDirection(direction()));
}
if (updateOverridingContainingBlockContentSizeForChild(child, childInlineDirection))
child.setNeedsLayout(MarkOnlyThis);
return logicalHeightForChild(child);
}
LayoutUnit GridTrackSizingAlgorithmStrategy::minSizeForChild(RenderBox& child) const
{
GridTrackSizingDirection childInlineDirection = GridLayoutFunctions::flowAwareDirectionForChild(*renderGrid(), child, ForColumns);
bool isRowAxis = direction() == childInlineDirection;
if (isRowAxis && isComputingInlineSizeContainment())
return { };
const Length& childSize = isRowAxis ? child.style().logicalWidth() : child.style().logicalHeight();
if (!childSize.isAuto() && !childSize.isPercentOrCalculated())
return minContentForChild(child);
const Length& childMinSize = isRowAxis ? child.style().logicalMinWidth() : child.style().logicalMinHeight();
bool overflowIsVisible = isRowAxis ? child.effectiveOverflowInlineDirection() == Overflow::Visible : child.effectiveOverflowBlockDirection() == Overflow::Visible;
LayoutUnit baselineShim = m_algorithm.baselineOffsetForChild(child, gridAxisForDirection(direction()));
if (childMinSize.isAuto() && overflowIsVisible) {
auto minSize = minContentForChild(child);
const GridSpan& span = m_algorithm.m_renderGrid->gridSpanForChild(child, direction());
LayoutUnit maxBreadth;
auto allTracks = m_algorithm.tracks(direction());
bool allFixed = true;
for (auto trackPosition : span) {
const auto& trackSize = allTracks[trackPosition].cachedTrackSize();
if (trackSize.maxTrackBreadth().isFlex() && span.integerSpan() > 1)
return { };
if (!trackSize.hasFixedMaxTrackBreadth())
allFixed = false;
else if (allFixed)
maxBreadth += valueForLength(trackSize.maxTrackBreadth().length(), availableSpace().value_or(0_lu));
}
if (!allFixed)
return minSize;
if (minSize > maxBreadth) {
auto marginAndBorderAndPadding = GridLayoutFunctions::marginLogicalSizeForChild(*renderGrid(), direction(), child);
marginAndBorderAndPadding += isRowAxis ? child.borderAndPaddingLogicalWidth() : child.borderAndPaddingLogicalHeight();
minSize = std::max(maxBreadth, marginAndBorderAndPadding + baselineShim);
}
return minSize;
}
std::optional<LayoutUnit> gridAreaSize = m_algorithm.gridAreaBreadthForChild(child, childInlineDirection);
return minLogicalSizeForChild(child, childMinSize, gridAreaSize) + baselineShim;
}
bool GridTrackSizingAlgorithm::canParticipateInBaselineAlignment(const RenderBox& child, GridAxis baselineAxis) const
{
ASSERT(baselineAxis == GridColumnAxis ? m_columnBaselineItemsMap.contains(&child) : m_rowBaselineItemsMap.contains(&child));
// Baseline cyclic dependencies only happen with synthesized
// baselines. These cases include orthogonal or empty grid items
// and replaced elements.
bool isParallelToBaselineAxis = baselineAxis == GridColumnAxis ? !GridLayoutFunctions::isOrthogonalChild(*m_renderGrid, child) : GridLayoutFunctions::isOrthogonalChild(*m_renderGrid, child);
if (isParallelToBaselineAxis && child.firstLineBaseline())
return true;
// FIXME: We don't currently allow items within subgrids that need to
// synthesize a baseline, since we need a layout to have been completed
// and performGridItemsPreLayout on the outer grid doesn't layout subgrid
// items.
if (child.parent() != renderGrid())
return false;
// Baseline cyclic dependencies only happen in grid areas with
// intrinsically-sized tracks.
if (!isIntrinsicSizedGridArea(child, baselineAxis))
return true;
return isParallelToBaselineAxis ? !child.hasRelativeLogicalHeight() : !child.hasRelativeLogicalWidth() && !child.style().logicalWidth().isAuto();
}
bool GridTrackSizingAlgorithm::participateInBaselineAlignment(const RenderBox& child, GridAxis baselineAxis) const
{
return baselineAxis == GridColumnAxis ? m_columnBaselineItemsMap.get(&child) : m_rowBaselineItemsMap.get(&child);
}
void GridTrackSizingAlgorithm::updateBaselineAlignmentContext(const RenderBox& child, GridAxis baselineAxis)
{
ASSERT(wasSetup());
ASSERT(canParticipateInBaselineAlignment(child, baselineAxis));
ItemPosition align = m_renderGrid->selfAlignmentForChild(baselineAxis, child).position();
const auto& span = m_renderGrid->gridSpanForChild(child, gridDirectionForAxis(baselineAxis));
auto spanForBaselineAlignment = align == ItemPosition::Baseline ? span.startLine() : span.endLine();
m_baselineAlignment.updateBaselineAlignmentContext(align, spanForBaselineAlignment, child, baselineAxis);
}
LayoutUnit GridTrackSizingAlgorithm::baselineOffsetForChild(const RenderBox& child, GridAxis baselineAxis) const
{
// If we haven't yet initialized this axis (which can be the case if we're doing
// prelayout of a subgrid), then we can't know the baseline offset.
if (tracks(gridDirectionForAxis(baselineAxis)).isEmpty())
return LayoutUnit();
if (!participateInBaselineAlignment(child, baselineAxis))
return LayoutUnit();
ItemPosition align = m_renderGrid->selfAlignmentForChild(baselineAxis, child).position();
const auto& span = m_renderGrid->gridSpanForChild(child, gridDirectionForAxis(baselineAxis));
auto spanForBaselineAlignment = align == ItemPosition::Baseline ? span.startLine() : span.endLine();
return m_baselineAlignment.baselineOffsetForChild(align, spanForBaselineAlignment, child, baselineAxis);
}
void GridTrackSizingAlgorithm::clearBaselineItemsCache()
{
m_columnBaselineItemsMap.clear();
m_rowBaselineItemsMap.clear();
}
void GridTrackSizingAlgorithm::cacheBaselineAlignedItem(const RenderBox& item, GridAxis axis)
{
ASSERT(downcast<RenderGrid>(item.parent())->isBaselineAlignmentForChild(item, axis));
if (GridLayoutFunctions::isOrthogonalParent(*m_renderGrid, *item.parent()))
axis = axis == GridColumnAxis ? GridRowAxis : GridColumnAxis;
if (axis == GridColumnAxis)
m_columnBaselineItemsMap.add(&item, true);
else
m_rowBaselineItemsMap.add(&item, true);
}