Skip to content
0.2.0-dev Download ZIP
992 lines ·40.6 KB Raw
1namespace EvilEngine.Html;
2
3internal sealed partial class Flow
4{
5 private ComputedStyle gridContainerStyle = ComputedStyle.Initial;
6 private bool measuringGrid;
7
8 private static long PercentOf(long basis, Length length)
9 {
10 return (long)(basis * (float)(length.Value / 100)) + ToAu(length.Px);
11 }
12
13 private static long? Resolve(Length? length, long? basis)
14 {
15 return length switch
16 {
17 null => null,
18 { Percent: false } fixedLength => ToAu(fixedLength.Value),
19 { } percent when basis is { } b => PercentOf(b, percent),
20 _ => null
21 };
22 }
23
24 private void LayGrid(BlockBox box, double x, double width, double? height, double? minHeight, double? maxHeight)
25 {
26 var style = box.Style;
27 var previousContainer = gridContainerStyle;
28 gridContainerStyle = style;
29 var widthAu = ToAu(width);
30 long? heightAu = height is { } h ? ToAu(h) : null;
31 long? minAu = minHeight is { } mn ? ToAu(mn) : null;
32 long? maxAu = maxHeight is { } mx ? ToAu(mx) : null;
33 var columnGap = Resolve(style.ColumnGap, widthAu) ?? 0;
34 var rowGap = Resolve(style.RowGap, heightAu) ?? 0;
35 var items = box.Blocks.Select((child, index) => (child, index)).OrderBy(entry => entry.child.Style.Order)
36 .ThenBy(entry => entry.index)
37 .Select(entry => MakeGridItem(entry.child, width)).ToList();
38
39 var (columns, rows) =
40 PlaceGrid(style, items, (widthAu, null, null), (heightAu, maxAu, minAu), columnGap, rowGap);
41 SizeTracks(columns, items, true, widthAu, columnGap, TrackMode.Normal, style.JustifyContent);
42 foreach (var item in items)
43 item.Width = FromAu(Span(columns, item.ColumnStart, item.ColumnEnd, columnGap));
44 foreach (var item in items)
45 item.Height = ToAu(OuterHeight(item, item.Width));
46 SizeTracks(rows, items, false, heightAu, rowGap, TrackMode.Normal, style.AlignContent, minAu, maxAu);
47
48 long contentHeight;
49 if (heightAu is { } definite)
50 {
51 contentHeight = definite;
52 }
53 else
54 {
55 var sized = Math.Max(Total(rows, rowGap), minAu ?? 0);
56 rowGap = Resolve(style.RowGap, sized) ?? 0;
57 SizeTracks(rows, items, false, sized, rowGap, TrackMode.Normal, style.AlignContent, minAu, maxAu);
58 contentHeight = Math.Min(sized, maxAu ?? long.MaxValue);
59 if (minAu is { } least)
60 contentHeight = Math.Max(contentHeight, least);
61 }
62
63 PlaceTracks(columns, widthAu, columnGap, style.JustifyContent);
64 PlaceTracks(rows, contentHeight, rowGap, style.AlignContent);
65
66 FlushMargins();
67 var top = Y;
68 var originX = ToAu(x);
69 var originY = ToAu(top);
70 var first = items.OrderBy(item => item.RowStart).ThenBy(item => item.ColumnStart).FirstOrDefault();
71 foreach (var item in items)
72 {
73 var areaX = columns[item.ColumnStart].Position;
74 var areaY = rows[item.RowStart].Position;
75 var areaWidth = Edge(columns, item.ColumnEnd - 1) - areaX;
76 var areaHeight = Edge(rows, item.RowEnd - 1) - areaY;
77 LayGridItem(item, style, originX + areaX, originY + areaY, areaWidth, areaHeight, item == first);
78 }
79
80 foreach (var outside in box.OutOfFlow)
81 Page.Pending.Add(new PendingBox(outside, x, top));
82 Y = top + FromAu(contentHeight);
83 gridContainerStyle = previousContainer;
84 }
85
86 private static long Edge(List<GridTrack> tracks, int index)
87 {
88 return tracks[index].Position + tracks[index].Base;
89 }
90
91 private static long Total(List<GridTrack> tracks, long gap)
92 {
93 var visible = tracks.Count(track => !track.Collapsed);
94 return tracks.Sum(track => track.Base) + Math.Max(0, visible - 1) * gap;
95 }
96
97 private static long Span(List<GridTrack> tracks, int start, int end, long gap)
98 {
99 long size = 0;
100 var counted = 0;
101 for (var i = start; i < end; i++)
102 {
103 size += tracks[i].Base;
104 if (!tracks[i].Collapsed)
105 counted++;
106 }
107
108 return size + Math.Max(0, counted - 1) * gap;
109 }
110
111 private GridItem MakeGridItem(BlockBox child, double width)
112 {
113 var style = child.Style;
114 return new GridItem(child)
115 {
116 Margin = Resolve(style.Margin, style.MarginPercent, width),
117 Padding = Resolve(style.Padding, style.PaddingPercent, width),
118 Border = style.BorderStyle != BorderStyle.None || style.Sides != null ? style.Border : default
119 };
120 }
121
122 private static int Repetitions(TrackList list, (long? Size, long? Max, long? Min) available, long gap)
123 {
124 if (list.Entries.OfType<TrackRepeat>().FirstOrDefault(repeat => repeat.Kind != RepeatKind.Count) is not
125 { } auto)
126 return 1;
127 var (space, roundUp) = available.Size is { } size ? (size, false) :
128 available.Max is { } max ? (max, false) :
129 available.Min is { } min ? (min, true) : (-1L, false);
130 if (space < 0)
131 return 1;
132
133 long? Counted(TrackSize track)
134 {
135 long? Fixed(Breadth breadth)
136 {
137 return breadth.Kind == BreadthKind.Fixed && (!breadth.Length.Percent || available.Size != null)
138 ? breadth.Length.Percent
139 ? PercentOf(available.Size ?? 0, breadth.Length)
140 : ToAu(breadth.Length.Value)
141 : null;
142 }
143
144 var (low, high) = (Fixed(track.Min), Fixed(track.Max));
145 return high is { } h && low is { } l ? Math.Max(h, l) : high ?? low;
146 }
147
148 long others = 0;
149 var otherCount = 0;
150 foreach (var entry in list.Entries)
151 switch (entry)
152 {
153 case TrackSize track:
154 others += Counted(track) ?? 0;
155 otherCount++;
156 break;
157 case TrackRepeat { Kind: RepeatKind.Count } counted:
158 others += counted.Count * counted.Tracks.Sum(track => Counted(track) ?? 0);
159 otherCount += counted.Count * counted.Tracks.Count;
160 break;
161 }
162
163 long repeat = 0;
164 foreach (var track in auto.Tracks)
165 {
166 if (Counted(track) is not { } each)
167 return 1;
168 repeat += Math.Max(60, each);
169 }
170
171 var used = others + repeat + (otherCount + auto.Tracks.Count - 1) * gap;
172 var free = space - used;
173 if (free <= 0)
174 return 1;
175 var step = repeat + auto.Tracks.Count * gap;
176 var extra = free / step;
177 if (roundUp && free % step != 0)
178 extra++;
179 return (int)Math.Min(10000, extra + 1);
180 }
181
182 private static (List<TrackSize> Tracks, HashSet<int> AutoFit) Explicit(TrackList? list,
183 (long? Size, long? Max, long? Min) available, long gap)
184 {
185 var tracks = new List<TrackSize>();
186 var autoFit = new HashSet<int>();
187 if (list == null)
188 return (tracks, autoFit);
189 var repetitions = Repetitions(list, available, gap);
190 foreach (var entry in list.Entries)
191 switch (entry)
192 {
193 case TrackSize track:
194 tracks.Add(track);
195 break;
196 case TrackRepeat repeat:
197 var count = repeat.Kind == RepeatKind.Count ? repeat.Count : repetitions;
198 for (var i = 0; i < count; i++)
199 foreach (var track in repeat.Tracks)
200 {
201 if (repeat.Kind == RepeatKind.AutoFit)
202 autoFit.Add(tracks.Count);
203 tracks.Add(track);
204 }
205
206 break;
207 }
208
209 return (tracks, autoFit);
210 }
211
212 private static (int? Start, int? End, int Span) Resolve(GridLine start, GridLine end, int explicitCount)
213 {
214 int Index(int line)
215 {
216 return line > 0 ? line - 1 : explicitCount + 1 + line;
217 }
218
219 switch (start.Kind, end.Kind)
220 {
221 case (LineKind.Line, LineKind.Line):
222 {
223 var (s, e) = (Index(start.Value), Index(end.Value));
224 if (e < s)
225 (s, e) = (e, s);
226 if (e == s)
227 e = s + 1;
228 return (s, e, e - s);
229 }
230 case (LineKind.Line, LineKind.Span):
231 return (Index(start.Value), Index(start.Value) + end.Value, end.Value);
232 case (LineKind.Line, LineKind.Auto):
233 return (Index(start.Value), Index(start.Value) + 1, 1);
234 case (LineKind.Span, LineKind.Line):
235 return (Index(end.Value) - start.Value, Index(end.Value), start.Value);
236 case (LineKind.Auto, LineKind.Line):
237 return (Index(end.Value) - 1, Index(end.Value), 1);
238 default:
239 var span = start.Kind == LineKind.Span ? start.Value : end.Kind == LineKind.Span ? end.Value : 1;
240 return (null, null, span);
241 }
242 }
243
244 private (List<GridTrack> Columns, List<GridTrack> Rows) PlaceGrid(ComputedStyle style, List<GridItem> items,
245 (long? Size, long? Max, long? Min) width,
246 (long? Size, long? Max, long? Min) height, long columnGap, long rowGap)
247 {
248 var (explicitColumns, fitColumns) = Explicit(style.GridColumns, width, columnGap);
249 var (explicitRows, fitRows) = Explicit(style.GridRows, height, rowGap);
250 var columnFlow = style.GridFlowColumn;
251
252 var resolved = items.Select(item =>
253 {
254 var s = item.Box.Style;
255 return (Item: item, Column: Resolve(s.ColumnStart, s.ColumnEnd, explicitColumns.Count),
256 Row: Resolve(s.RowStart, s.RowEnd, explicitRows.Count));
257 }).ToList();
258
259 var columnOffset = -Math.Min(0,
260 resolved.Where(r => r.Column.Start != null).Select(r => r.Column.Start!.Value).DefaultIfEmpty(0).Min());
261 var rowOffset = -Math.Min(0,
262 resolved.Where(r => r.Row.Start != null).Select(r => r.Row.Start!.Value).DefaultIfEmpty(0).Min());
263
264 var occupied = new HashSet<(int Major, int Minor)>();
265
266 bool Free(int major, int minor, int majorSpan, int minorSpan)
267 {
268 for (var a = major; a < major + majorSpan; a++)
269 for (var b = minor; b < minor + minorSpan; b++)
270 if (occupied.Contains((a, b)))
271 return false;
272 return true;
273 }
274
275 void Occupy(int major, int minor, int majorSpan, int minorSpan)
276 {
277 for (var a = major; a < major + majorSpan; a++)
278 for (var b = minor; b < minor + minorSpan; b++)
279 occupied.Add((a, b));
280 }
281
282 var placed = new Dictionary<GridItem, (int Major, int Minor, int MajorSpan, int MinorSpan)>();
283
284 (int? Start, int Span) Major(
285 (GridItem Item, (int? Start, int? End, int Span) Column, (int? Start, int? End, int Span) Row) r)
286 {
287 return columnFlow
288 ? (r.Column.Start + (r.Column.Start != null ? columnOffset : 0), r.Column.Span)
289 : (r.Row.Start + (r.Row.Start != null ? rowOffset : 0), r.Row.Span);
290 }
291
292 (int? Start, int Span) Minor(
293 (GridItem Item, (int? Start, int? End, int Span) Column, (int? Start, int? End, int Span) Row) r)
294 {
295 return columnFlow
296 ? (r.Row.Start + (r.Row.Start != null ? rowOffset : 0), r.Row.Span)
297 : (r.Column.Start + (r.Column.Start != null ? columnOffset : 0), r.Column.Span);
298 }
299
300 foreach (var r in resolved)
301 if (Major(r) is { Start: { } a } major && Minor(r) is { Start: { } b } minor)
302 {
303 placed[r.Item] = (a, b, major.Span, minor.Span);
304 Occupy(a, b, major.Span, minor.Span);
305 }
306
307 var majorCursors = new Dictionary<int, int>();
308 foreach (var r in resolved)
309 {
310 if (placed.ContainsKey(r.Item) || Major(r) is not { Start: { } a } major)
311 continue;
312 var minor = Minor(r);
313 var b = style.GridDense ? 0 : majorCursors.GetValueOrDefault(a);
314 while (!Free(a, b, major.Span, minor.Span))
315 b++;
316 placed[r.Item] = (a, b, major.Span, minor.Span);
317 Occupy(a, b, major.Span, minor.Span);
318 majorCursors[a] = b + minor.Span;
319 }
320
321 var minorExplicit = columnFlow ? explicitRows.Count + rowOffset : explicitColumns.Count + columnOffset;
322 var minorCount = Math.Max(minorExplicit,
323 placed.Values.Select(p => p.Minor + p.MinorSpan).DefaultIfEmpty(0).Max());
324 foreach (var r in resolved)
325 if (!placed.ContainsKey(r.Item))
326 {
327 var minor = Minor(r);
328 minorCount = Math.Max(minorCount, (minor.Start ?? 0) + minor.Span);
329 }
330
331 var (cursorMajor, cursorMinor) = (0, 0);
332 foreach (var r in resolved)
333 {
334 if (placed.ContainsKey(r.Item))
335 continue;
336 var major = Major(r);
337 var minor = Minor(r);
338 if (style.GridDense)
339 (cursorMajor, cursorMinor) = (0, 0);
340 if (minor.Start is { } fixedMinor)
341 {
342 if (fixedMinor < cursorMinor && !style.GridDense)
343 cursorMajor++;
344 cursorMinor = fixedMinor;
345 while (!Free(cursorMajor, cursorMinor, major.Span, minor.Span))
346 cursorMajor++;
347 }
348 else
349 {
350 while (true)
351 {
352 while (cursorMinor + minor.Span <= minorCount &&
353 !Free(cursorMajor, cursorMinor, major.Span, minor.Span))
354 cursorMinor++;
355 if (cursorMinor + minor.Span <= minorCount)
356 break;
357 cursorMajor++;
358 cursorMinor = 0;
359 }
360 }
361
362 placed[r.Item] = (cursorMajor, cursorMinor, major.Span, minor.Span);
363 Occupy(cursorMajor, cursorMinor, major.Span, minor.Span);
364 if (!style.GridDense)
365 cursorMinor += minor.Span;
366 }
367
368 foreach (var (item, p) in placed)
369 if (columnFlow)
370 (item.ColumnStart, item.ColumnEnd, item.RowStart, item.RowEnd) =
371 (p.Major, p.Major + p.MajorSpan, p.Minor, p.Minor + p.MinorSpan);
372 else
373 (item.RowStart, item.RowEnd, item.ColumnStart, item.ColumnEnd) =
374 (p.Major, p.Major + p.MajorSpan, p.Minor, p.Minor + p.MinorSpan);
375
376 List<GridTrack> Tracks(List<TrackSize> explicitTracks, HashSet<int> autoFit, int offset,
377 IReadOnlyList<TrackSize> auto, int needed, Func<GridItem, (int, int)> span)
378 {
379 var count = Math.Max(offset + explicitTracks.Count, needed);
380 var tracks = new List<GridTrack>();
381 for (var i = 0; i < count; i++)
382 {
383 var explicitIndex = i - offset;
384 TrackSize size;
385 if (explicitIndex >= 0 && explicitIndex < explicitTracks.Count)
386 size = explicitTracks[explicitIndex];
387 else if (explicitIndex >= explicitTracks.Count)
388 size = auto[(explicitIndex - explicitTracks.Count) % auto.Count];
389 else
390 size = auto[(explicitIndex % auto.Count + auto.Count) % auto.Count];
391 var track = new GridTrack(size);
392 if (explicitIndex >= 0 && autoFit.Contains(explicitIndex) &&
393 !items.Any(item => span(item) is var (s, e) && s <= i && i < e))
394 track.Collapsed = true;
395 tracks.Add(track);
396 }
397
398 return tracks;
399 }
400
401 var columns = Tracks(explicitColumns, fitColumns, columnOffset, style.GridAutoColumns,
402 items.Select(item => item.ColumnEnd).DefaultIfEmpty(0).Max(), item => (item.ColumnStart, item.ColumnEnd));
403 var rows = Tracks(explicitRows, fitRows, rowOffset, style.GridAutoRows,
404 items.Select(item => item.RowEnd).DefaultIfEmpty(0).Max(), item => (item.RowStart, item.RowEnd));
405 if (columns.Count == 0)
406 columns.Add(new GridTrack(TrackSize.Auto) { Collapsed = false });
407 if (rows.Count == 0)
408 rows.Add(new GridTrack(TrackSize.Auto) { Collapsed = false });
409 return (columns, rows);
410 }
411
412 private double OuterHeight(GridItem item, double areaWidth)
413 {
414 var (width, _) = ItemWidth(item, areaWidth);
415 var laid = LayItem(item.Box, width, null);
416 return laid.Height + item.Margin.Top + item.Margin.Bottom;
417 }
418
419 private (double Content, double Outer) ItemWidth(GridItem item, double areaWidth)
420 {
421 var style = item.Box.Style;
422 var extras = item.Padding.Left + item.Padding.Right + item.Border.Left + item.Border.Right;
423 var available = Math.Max(0, areaWidth - item.Margin.Left - item.Margin.Right);
424 double content;
425 if (ContentSize(style.Width, areaWidth, extras, style.BorderBox) is { } fixedWidth)
426 {
427 content = fixedWidth;
428 }
429 else
430 {
431 var justify = style.JustifySelf == Alignment.Auto ? gridContainerStyle.JustifyItems : style.JustifySelf;
432 var stretch = (justify == Alignment.Stretch || (justify == Alignment.Normal && !Replaced(item.Box))) &&
433 !style.MarginLeftAuto && !style.MarginRightAuto;
434 if (stretch && style.WidthKeyword == SizeKeyword.None)
435 content = available - extras;
436 else
437 content = KeywordWidth(item.Box,
438 style.WidthKeyword == SizeKeyword.None ? SizeKeyword.FitContent : style.WidthKeyword,
439 available - extras) ?? 0;
440 }
441
442 if (ContentSize(style.MaxWidth, areaWidth, extras, style.BorderBox) is { } max)
443 content = Math.Min(content, max);
444 if (ContentSize(style.MinWidth, areaWidth, extras, style.BorderBox) is { } min)
445 content = Math.Max(content, min);
446 content = Math.Max(0, content);
447 return (content, content + extras + item.Margin.Left + item.Margin.Right);
448 }
449
450 private (long Min, long Max, long Minimum) Contributions(GridItem item, bool columnsAxis)
451 {
452 var style = item.Box.Style;
453 if (!columnsAxis)
454 {
455 var h = item.Height ?? 0;
456 var verticalExtras = item.Padding.Top + item.Padding.Bottom + item.Border.Top + item.Border.Bottom +
457 item.Margin.Top + item.Margin.Bottom;
458 var minimum = style.MinHeight is { Percent: false } mh ? ToAu(mh.Value + verticalExtras -
459 (style.BorderBox
460 ? item.Padding.Top + item.Padding.Bottom +
461 item.Border.Top + item.Border.Bottom
462 : 0))
463 : style.Clips && style.OverflowY != Overflow.Clip ? ToAu(item.Margin.Top + item.Margin.Bottom) : h;
464 return (h, h, minimum);
465 }
466
467 var (min, max) = Outer(item.Box);
468 var extras = style.Padding.Left + style.Padding.Right + item.Border.Left + item.Border.Right +
469 style.Margin.Left + style.Margin.Right;
470 var minimumWidth = style.MinWidth is { Percent: false } mw
471 ? ToAu(mw.Value + extras - (style.BorderBox
472 ? style.Padding.Left + style.Padding.Right + item.Border.Left + item.Border.Right
473 : 0))
474 : style.Clips && style.OverflowX != Overflow.Clip
475 ? ToAu(style.Margin.Left + style.Margin.Right)
476 : ToAu(min);
477 return (ToAu(min), ToAu(max), minimumWidth);
478 }
479
480 private void SizeTracks(List<GridTrack> tracks, List<GridItem> items, bool columnsAxis, long? available, long gap,
481 TrackMode mode, Alignment distribution,
482 long? minSize = null, long? maxSize = null)
483 {
484 (int Start, int End) SpanOf(GridItem item)
485 {
486 return columnsAxis ? (item.ColumnStart, item.ColumnEnd) : (item.RowStart, item.RowEnd);
487 }
488
489 bool Percentage(Breadth b)
490 {
491 return b.Kind == BreadthKind.Fixed && b.Length.Percent;
492 }
493
494 foreach (var track in tracks)
495 {
496 track.Base = 0;
497 track.Growth = 0;
498 track.Infinite = false;
499 if (track.Collapsed)
500 continue;
501 var min = track.Size.Min;
502 var max = track.Size.Max;
503 if (min.Kind == BreadthKind.Fixed && (!min.Length.Percent || available != null))
504 track.Base = min.Length.Percent ? PercentOf(available!.Value, min.Length) : ToAu(min.Length.Value);
505 if (max.Kind == BreadthKind.Fixed && (!max.Length.Percent || available != null))
506 track.Growth = max.Length.Percent ? PercentOf(available!.Value, max.Length) : ToAu(max.Length.Value);
507 else
508 track.Infinite = true;
509 if (!track.Infinite && track.Growth < track.Base)
510 track.Growth = track.Base;
511 }
512
513 bool MinIntrinsic(GridTrack t)
514 {
515 return t.Size.Min.Intrinsic || (Percentage(t.Size.Min) && available == null);
516 }
517
518 bool MaxIntrinsic(GridTrack t)
519 {
520 return t.Size.Max.Intrinsic || (Percentage(t.Size.Max) && available == null);
521 }
522
523 BreadthKind MinKind(GridTrack t)
524 {
525 return Percentage(t.Size.Min) && available == null ? BreadthKind.Auto : t.Size.Min.Kind;
526 }
527
528 BreadthKind MaxKind(GridTrack t)
529 {
530 return Percentage(t.Size.Max) && available == null ? BreadthKind.Auto : t.Size.Max.Kind;
531 }
532
533 var contributions = items.ToDictionary(item => item, item => Contributions(item, columnsAxis));
534
535 long FixedLimit(IEnumerable<GridTrack> spanned)
536 {
537 long total = 0;
538 foreach (var t in spanned)
539 {
540 if (MaxKind(t) != BreadthKind.Fixed)
541 return long.MaxValue;
542 total += Math.Max(t.Base, t.Infinite ? t.Base : t.Growth);
543 }
544
545 return total;
546 }
547
548 foreach (var item in items)
549 {
550 var (start, end) = SpanOf(item);
551 var spanned = Enumerable.Range(start, end - start).Where(i => !tracks[i].Collapsed).ToList();
552 if (spanned.Count != 1 || tracks[spanned[0]].Flexible)
553 continue;
554 var track = tracks[spanned[0]];
555 var (minContent, maxContent, minimum) = contributions[item];
556 if (MinIntrinsic(track))
557 {
558 var value = MinKind(track) switch
559 {
560 BreadthKind.MinContent => minContent,
561 BreadthKind.MaxContent => maxContent,
562 _ => mode == TrackMode.MinContent ? minContent :
563 mode == TrackMode.MaxContent ? maxContent : Math.Min(minimum, FixedLimit([track]))
564 };
565 track.Base = Math.Max(track.Base, value);
566 }
567
568 if (MaxIntrinsic(track))
569 {
570 var value = MaxKind(track) == BreadthKind.MinContent ? minContent : maxContent;
571 if (track.Size.FitContent is { } limit)
572 value = Math.Max(minContent,
573 Math.Min(value,
574 limit.Percent ? available is { } a ? PercentOf(a, limit) : value : ToAu(limit.Value)));
575 track.Growth = track.Infinite ? value : Math.Max(track.Growth, value);
576 track.Infinite = false;
577 }
578 }
579
580 foreach (var track in tracks)
581 if (!track.Infinite && track.Growth < track.Base)
582 track.Growth = track.Base;
583
584 var spanning = items.Select(item => (Item: item, Span: SpanOf(item)))
585 .Select(entry => (entry.Item,
586 Tracks: Enumerable.Range(entry.Span.Start, entry.Span.End - entry.Span.Start)
587 .Where(i => !tracks[i].Collapsed).ToList()))
588 .Where(entry => entry.Tracks.Count > 1 && !entry.Tracks.Any(i => tracks[i].Flexible))
589 .GroupBy(entry => entry.Tracks.Count).OrderBy(group => group.Key);
590 foreach (var group in spanning)
591 {
592 void Step(Func<GridTrack, bool> affected, Func<GridItem, long> contribution, bool growth,
593 Func<GridTrack, bool> beyond)
594 {
595 var planned = new Dictionary<GridTrack, long>();
596 foreach (var (item, indices) in group)
597 {
598 var spanned = indices.Select(i => tracks[i]).ToList();
599 var targets = spanned.Where(affected).ToList();
600 if (targets.Count == 0)
601 continue;
602 var sizes = spanned.Sum(t => growth ? t.Infinite ? t.Base : t.Growth : t.Base) +
603 (spanned.Count - 1) * gap;
604 var extra = contribution(item) - sizes;
605 if (extra <= 0)
606 continue;
607 foreach (var (track, increase) in Distribute(targets, extra, growth, beyond))
608 planned[track] = Math.Max(planned.GetValueOrDefault(track), increase);
609 }
610
611 foreach (var (track, increase) in planned)
612 if (growth)
613 {
614 track.Growth = (track.Infinite ? track.Base : track.Growth) + increase;
615 track.Infinite = false;
616 }
617 else
618 {
619 track.Base += increase;
620 }
621 }
622
623 Step(MinIntrinsic,
624 item => mode == TrackMode.MinContent ? contributions[item].Min :
625 mode == TrackMode.MaxContent ? contributions[item].Max : contributions[item].Minimum,
626 false, MaxIntrinsic);
627 Step(t => MinKind(t) is BreadthKind.MinContent or BreadthKind.MaxContent, item => contributions[item].Min,
628 false, MaxIntrinsic);
629 Step(
630 t => MinKind(t) == BreadthKind.MaxContent ||
631 (MinKind(t) == BreadthKind.Auto && mode == TrackMode.MaxContent),
632 item => contributions[item].Max, false, t => MaxKind(t) is BreadthKind.MaxContent or BreadthKind.Auto);
633 foreach (var track in tracks)
634 if (!track.Infinite && track.Growth < track.Base)
635 track.Growth = track.Base;
636 Step(MaxIntrinsic, item => contributions[item].Min, true, _ => true);
637 Step(t => MaxKind(t) is BreadthKind.MaxContent or BreadthKind.Auto, item => contributions[item].Max, true,
638 _ => true);
639 }
640
641 if (!measuringGrid)
642 foreach (var item in items)
643 {
644 var (start, end) = SpanOf(item);
645 var spanned = Enumerable.Range(start, end - start).Where(i => !tracks[i].Collapsed)
646 .Select(i => tracks[i]).ToList();
647 var flexible = spanned.Where(t => t.Flexible && MinIntrinsic(t)).ToList();
648 if (flexible.Count == 0)
649 continue;
650 var (minContent, maxContent, _) = contributions[item];
651 var explicitMinimum = columnsAxis ? item.Box.Style.MinWidth : item.Box.Style.MinHeight;
652
653 long Contribution(GridTrack t)
654 {
655 return MinKind(t) switch
656 {
657 BreadthKind.MinContent => minContent,
658 BreadthKind.MaxContent => maxContent,
659 _ => mode == TrackMode.MinContent ? minContent
660 : mode == TrackMode.MaxContent ? maxContent
661 : explicitMinimum is { Percent: false } m ? ToAu(m.Value) : 0
662 };
663 }
664
665 var need = flexible.Max(Contribution) - spanned.Sum(t => t.Base) - (spanned.Count - 1) * gap;
666 if (need <= 0)
667 continue;
668 var flexSum = flexible.Sum(t => t.Size.Max.Fr);
669 foreach (var track in flexible)
670 track.Base = Math.Max(track.Base, (long)(need * track.Size.Max.Fr / Math.Max(1, flexSum)));
671 }
672
673 foreach (var track in tracks)
674 {
675 if (track.Infinite)
676 {
677 track.Growth = track.Base;
678 track.Infinite = false;
679 }
680
681 if (track.Growth < track.Base)
682 track.Growth = track.Base;
683 }
684
685 var visible = tracks.Where(t => !t.Collapsed).ToList();
686 var gaps = Math.Max(0, visible.Count - 1) * gap;
687 if (mode == TrackMode.MaxContent || (available == null && mode == TrackMode.Normal))
688 {
689 foreach (var track in visible)
690 track.Base = track.Growth;
691 }
692 else if (mode == TrackMode.Normal && available is { } space)
693 {
694 var free = space - visible.Sum(t => t.Base) - gaps;
695 if (free > 0)
696 foreach (var (track, increase) in Distribute(visible, free, false, null))
697 track.Base += increase;
698 }
699
700 var flexTracks = visible.Where(t => t.Flexible).ToList();
701 if (flexTracks.Count > 0 && mode != TrackMode.MinContent)
702 {
703 float fr;
704 if (available is { } definite && mode == TrackMode.Normal)
705 {
706 fr = FrSize(visible, definite - gaps);
707 }
708 else
709 {
710 fr = (float)flexTracks.Max(t => t.Size.Max.Fr > 1 ? t.Base / t.Size.Max.Fr : t.Base);
711 foreach (var item in items)
712 {
713 var (start, end) = SpanOf(item);
714 var spanned = Enumerable.Range(start, end - start).Where(i => !tracks[i].Collapsed)
715 .Select(i => tracks[i]).ToList();
716 if (!spanned.Any(t => t.Flexible))
717 continue;
718 fr = Math.Max(fr, FrSize(spanned, contributions[item].Max - (spanned.Count - 1) * gap));
719 }
720
721 var total = visible.Where(t => !t.Flexible).Sum(t => t.Base) +
722 flexTracks.Sum(t => Math.Max(t.Base, Round(t.Size.Max.Fr * fr))) + gaps;
723 if (minSize is { } least && total < least)
724 fr = FrSize(visible, least - gaps);
725 else if (maxSize is { } most && total > most)
726 fr = FrSize(visible, most - gaps);
727 }
728
729 foreach (var track in flexTracks)
730 track.Base = Math.Max(track.Base, Round(track.Size.Max.Fr * fr));
731 }
732
733 if (distribution is Alignment.Normal or Alignment.Stretch && mode == TrackMode.Normal &&
734 available is { } stretchTo)
735 {
736 var autos = visible.Where(t => MaxKind(t) == BreadthKind.Auto && t.Size.FitContent == null).ToList();
737 var free = stretchTo - visible.Sum(t => t.Base) - gaps;
738 if (free > 0 && autos.Count > 0)
739 foreach (var (track, increase) in Split(autos, free, _ => long.MaxValue))
740 track.Base += increase;
741 }
742 }
743
744 private static long Round(double value)
745 {
746 return (long)Math.Floor(value + 0.5);
747 }
748
749 private static Dictionary<GridTrack, long> Split(List<GridTrack> targets, long space, Func<GridTrack, long> room)
750 {
751 var increases = targets.ToDictionary(t => t, _ => 0L);
752 var open = targets.Where(t => room(t) > 0).ToList();
753 while (space > 0 && open.Count > 0)
754 {
755 var per = Math.Max(space / open.Count, 1);
756 var next = new List<GridTrack>();
757 foreach (var track in open)
758 {
759 if (space <= 0)
760 break;
761 var left = room(track) - increases[track];
762 var take = Math.Min(Math.Min(per, left), space);
763 increases[track] += take;
764 space -= take;
765 if (room(track) - increases[track] > 0)
766 next.Add(track);
767 }
768
769 open = next;
770 }
771
772 return increases;
773 }
774
775 private static Dictionary<GridTrack, long> Distribute(List<GridTrack> targets, long extra, bool growth,
776 Func<GridTrack, bool>? beyond)
777 {
778 long Size(GridTrack t)
779 {
780 return growth ? t.Infinite ? t.Base : t.Growth : t.Base;
781 }
782
783 long Limit(GridTrack t)
784 {
785 if (growth)
786 return t.Size.FitContent is { Percent: false } fit ? Math.Max(Size(t), ToAu(fit.Value)) : long.MaxValue;
787 return t.Infinite ? long.MaxValue : t.Growth;
788 }
789
790 var increases = Split(targets, extra, t => Limit(t) == long.MaxValue ? long.MaxValue : Limit(t) - Size(t));
791 var left = extra - increases.Values.Sum();
792 if (left > 0 && beyond != null)
793 {
794 var over = targets.Where(beyond).ToList();
795 if (over.Count == 0)
796 over = targets;
797 foreach (var (track, more) in Split(over, left, _ => long.MaxValue))
798 increases[track] += more;
799 }
800
801 return increases;
802 }
803
804 private static float FrSize(List<GridTrack> tracks, long space)
805 {
806 var inflexible = new HashSet<GridTrack>(tracks.Where(t => !t.Flexible));
807 while (true)
808 {
809 var leftover = space - inflexible.Sum(t => t.Base);
810 if (leftover <= 0)
811 return 0;
812 var flexSum = (float)tracks.Where(t => !inflexible.Contains(t)).Sum(t => t.Size.Max.Fr);
813 var hypothetical = leftover / Math.Max(1f, flexSum);
814 var shrunk = tracks.Where(t => !inflexible.Contains(t) && t.Base > hypothetical * t.Size.Max.Fr).ToList();
815 if (shrunk.Count == 0)
816 return hypothetical;
817 foreach (var track in shrunk)
818 inflexible.Add(track);
819 }
820 }
821
822 private static void PlaceTracks(List<GridTrack> tracks, long available, long gap, Alignment distribution)
823 {
824 var visible = tracks.Count(t => !t.Collapsed);
825 var free = available - Total(tracks, gap);
826 long start = 0, between = 0, remainder = 0;
827 var effective = distribution;
828 if (free < 0 && distribution is Alignment.SpaceBetween or Alignment.Stretch or Alignment.SpaceAround
829 or Alignment.SpaceEvenly)
830 effective = Alignment.Start;
831 switch (effective)
832 {
833 case Alignment.End or Alignment.FlexEnd:
834 start = free;
835 break;
836 case Alignment.SafeEnd or Alignment.SafeFlexEnd:
837 start = Math.Max(0, free);
838 break;
839 case Alignment.Center:
840 start = free / 2;
841 break;
842 case Alignment.SafeCenter:
843 start = Math.Max(0, free) / 2;
844 break;
845 case Alignment.SpaceBetween when visible > 1:
846 between = Math.DivRem(free, visible - 1, out remainder);
847 break;
848 case Alignment.SpaceAround when visible > 0:
849 between = Math.DivRem(free, visible, out remainder);
850 start = between / 2;
851 break;
852 case Alignment.SpaceEvenly:
853 between = Math.DivRem(free, visible + 1, out remainder);
854 start = between;
855 break;
856 }
857
858 var position = start;
859 var index = 0;
860 foreach (var track in tracks)
861 {
862 if (track.Collapsed)
863 {
864 track.Position = position;
865 continue;
866 }
867
868 if (index > 0)
869 position += gap + between + (index <= remainder ? 1 : 0);
870 track.Position = position;
871 position += track.Base;
872 index++;
873 }
874 }
875
876 private void LayGridItem(GridItem item, ComputedStyle container, long areaX, long areaY, long areaWidthAu,
877 long areaHeightAu, bool first)
878 {
879 var style = item.Box.Style;
880 var areaWidth = FromAu(areaWidthAu);
881 var areaHeight = FromAu(areaHeightAu);
882 var (contentWidth, outerWidth) = ItemWidth(item, areaWidth);
883 var verticalExtras = item.Padding.Top + item.Padding.Bottom + item.Border.Top + item.Border.Bottom;
884 var contentHeight = ContentSize(style.Height, areaHeight, verticalExtras, style.BorderBox);
885 var align = style.AlignSelf == Alignment.Auto ? container.AlignItems : style.AlignSelf;
886 if (contentHeight == null && (align == Alignment.Stretch || (align == Alignment.Normal && !Replaced(item.Box))) &&
887 !style.MarginTopAuto && !style.MarginBottomAuto)
888 {
889 var stretched = areaHeight - item.Margin.Top - item.Margin.Bottom - verticalExtras;
890 if (ContentSize(style.MaxHeight, areaHeight, verticalExtras, style.BorderBox) is { } maxH)
891 stretched = Math.Min(stretched, maxH);
892 if (ContentSize(style.MinHeight, areaHeight, verticalExtras, style.BorderBox) is { } minH)
893 stretched = Math.Max(stretched, minH);
894 contentHeight = Math.Max(0, stretched);
895 }
896
897 var laid = LayItem(item.Box, contentWidth, contentHeight);
898 var outerHeight = laid.Height + item.Margin.Top + item.Margin.Bottom;
899
900 var justify = style.JustifySelf == Alignment.Auto ? container.JustifyItems : style.JustifySelf;
901
902 static long Offset(long free, Alignment alignment, bool startAuto, bool endAuto)
903 {
904 if (startAuto || endAuto)
905 {
906 if (free <= 0)
907 return 0;
908 return startAuto && endAuto ? free / 2 : startAuto ? free : 0;
909 }
910
911 return alignment switch
912 {
913 Alignment.End or Alignment.FlexEnd => free,
914 Alignment.SafeEnd or Alignment.SafeFlexEnd => Math.Max(0, free),
915 Alignment.Center => free / 2,
916 Alignment.SafeCenter => Math.Max(0, free) / 2,
917 _ => 0
918 };
919 }
920
921 var dx = Offset(areaWidthAu - ToAu(outerWidth), justify, style.MarginLeftAuto, style.MarginRightAuto) +
922 ToAu(item.Margin.Left);
923 var dy = Offset(areaHeightAu - ToAu(outerHeight), align, style.MarginTopAuto, style.MarginBottomAuto) +
924 ToAu(item.Margin.Top);
925 var widgets = Page.Widgets.Count;
926 Page.Paste(laid.Page, FromAu(areaX + dx), FromAu(areaY + dy));
927 if (item.Box.Widget != null)
928 FillWidget(item.Box, widgets, FromAu(areaX + dx), FromAu(areaY + dy), contentWidth, contentHeight);
929 if (first)
930 FirstBaseline = FromAu(areaY + dy) + (laid.Baseline ?? laid.Height);
931 }
932
933 private static bool Replaced(BlockBox box)
934 {
935 return box.Widget?.Element.LocalName == "img";
936 }
937
938 private (double Min, double Max) GridIntrinsic(BlockBox box)
939 {
940 var style = box.Style;
941 var (previous, previousMeasuring) = (gridContainerStyle, measuringGrid);
942 gridContainerStyle = style;
943 measuringGrid = true;
944 try
945 {
946 var columnGap = style.ColumnGap is { Percent: false } gap ? ToAu(gap.Value) : 0;
947 var items = box.Blocks.Select(child => MakeGridItem(child, 0)).ToList();
948
949 double Measure(TrackMode mode)
950 {
951 var (columns, _) = PlaceGrid(style, items,
952 (null, ContentSize(style.MaxWidth, 0, 0, false) is { } mw ? ToAu(mw) : null, null),
953 (null, null, null), columnGap, 0);
954 SizeTracks(columns, items, true, null, columnGap, mode, style.JustifyContent);
955 return FromAu(Total(columns, columnGap));
956 }
957
958 return (Measure(TrackMode.MinContent), Measure(TrackMode.MaxContent));
959 }
960 finally
961 {
962 (gridContainerStyle, measuringGrid) = (previous, previousMeasuring);
963 }
964 }
965
966 private sealed class GridItem(BlockBox box)
967 {
968 public int ColumnStart, ColumnEnd, RowStart, RowEnd;
969 public long? Height;
970 public Edges Margin, Padding, Border;
971 public double Width;
972 public BlockBox Box { get; } = box;
973 }
974
975 private sealed class GridTrack(TrackSize size)
976 {
977 public long Base;
978 public bool Collapsed;
979 public long Growth;
980 public bool Infinite;
981 public long Position;
982 public TrackSize Size { get; } = size;
983 public bool Flexible => Size.Max.Kind == BreadthKind.Fr;
984 }
985
986 private enum TrackMode
987 {
988 Normal,
989 MinContent,
990 MaxContent
991 }
992}