@geastack/engine 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ui/layout.cpp CHANGED
@@ -1,24 +1,107 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  #include "internal.h"
3
+ #include "flex_balance.h"
3
4
  #include "memory.h"
5
+ #include "tree_state.h"
4
6
  #include "refresh_perf.h"
5
7
 
6
8
  #include "graphics/font.h"
7
9
 
8
10
  #include <cstdio>
11
+ #include <climits>
9
12
  #include <cstring>
13
+ #include <algorithm>
14
+ #include <cmath>
15
+ #include <vector>
10
16
 
11
17
  namespace gea::embedded::ui {
12
18
 
19
+ bool isCollapsedFlexItem(const Node &node)
20
+ {
21
+ return node.style.visibility == 2 && node.parent >= 0 &&
22
+ !isOutOfFlowPosition(node.style.position) && Tree::instance().nodes()[node.parent].style.display == kDisplayFlex;
23
+ }
24
+
25
+ bool isCollapsedFlexSubtree(const Node &node)
26
+ {
27
+ const Node *nodes = Tree::instance().nodes();
28
+ for (const Node *current = &node; current; current = current->parent >= 0 ? &nodes[current->parent] : nullptr)
29
+ if (isCollapsedFlexItem(*current)) return true;
30
+ return false;
31
+ }
32
+
13
33
  namespace {
14
34
 
15
35
  constexpr int kScratchDepth = 16;
16
36
 
37
+ int formattingEdgeNode(const Node *nodes, int id, bool last);
38
+
39
+ bool isLineBreak(const Node &node)
40
+ {
41
+ return node.type == NodeType::View && std::strcmp(tagFromId(node.tag_id), "br") == 0;
42
+ }
43
+
44
+
45
+ bool suppressAnonymousWhitespace(const Node *nodes, int parent, int child)
46
+ {
47
+ const Node &text = nodes[child];
48
+ if (!isAnonymousTextNode(text)) return false;
49
+ if (text.text.empty()) return true;
50
+ if ((text.style.white_space != 0 && text.style.white_space != 1) || text.text.find_first_not_of(" \t\r\n\f") != std::string::npos) return false;
51
+ if (nodes[parent].style.display == kDisplayFlex || isDisplayGrid(nodes[parent].style)) return true;
52
+ // Whitespace at a line boundary or between block boxes creates no line.
53
+ // Preserve the text node itself and spaces between inline siblings.
54
+ auto adjacentInline = [&](int sibling, bool forward) {
55
+ while (sibling >= 0 && (isDisplayNone(nodes[sibling].style) || isOutOfFlowPosition(nodes[sibling].style.position) ||
56
+ (isAnonymousTextNode(nodes[sibling]) && (nodes[sibling].style.white_space == 0 || nodes[sibling].style.white_space == 1) &&
57
+ nodes[sibling].text.find_first_not_of(" \t\r\n\f") == std::string::npos)))
58
+ sibling = forward ? nodes[sibling].next_sibling : nodes[sibling].prev_sibling;
59
+ if (sibling >= 0) sibling = formattingEdgeNode(nodes, sibling, !forward);
60
+ return sibling >= 0 && !isLineBreak(nodes[sibling]) && LayoutEngine::isInlineLevelNode(nodes[sibling]);
61
+ };
62
+ return !adjacentInline(text.prev_sibling, false) || !adjacentInline(text.next_sibling, true);
63
+ }
64
+
65
+ // An inline wrapper shares its parent's line. Find a definite line boundary
66
+ // through preceding siblings and inline ancestors before measuring its first
67
+ // text run; padding does not turn leading collapsible whitespace into content.
68
+ bool startsFormattingLine(const Node *nodes, int id)
69
+ {
70
+ while (LayoutEngine::isCssInlineLevelBox(nodes[id]) && LayoutEngine::isInlineLevelNode(nodes[id])) {
71
+ for (int sibling = nodes[id].prev_sibling; sibling >= 0; sibling = nodes[sibling].prev_sibling) {
72
+ const Node &previous = nodes[sibling];
73
+ if (isDisplayNone(previous.style) || isOutOfFlowPosition(previous.style.position) || previous.style.float_side)
74
+ continue;
75
+ if (isAnonymousTextNode(previous) &&
76
+ (previous.style.white_space == 0 || previous.style.white_space == 1 || previous.style.white_space == 4) &&
77
+ previous.text.find_first_not_of(" \t\r\n\f") == std::string::npos) continue;
78
+ const int edge = formattingEdgeNode(nodes, sibling, true);
79
+ if (edge < 0) continue;
80
+ return isLineBreak(nodes[edge]) || !LayoutEngine::isInlineLevelNode(nodes[edge]);
81
+ }
82
+ id = nodes[id].parent;
83
+ if (id < 0) return true;
84
+ }
85
+ return true;
86
+ }
87
+
17
88
  struct FlexLine {
18
89
  int start = 0;
19
90
  int count = 0;
20
91
  int mainSize = 0;
21
92
  int crossSize = 0;
93
+ int strutSize = 0;
94
+ };
95
+
96
+ struct InlineFlowExtent { int width, height; int firstLineHeight = 0; };
97
+
98
+ struct FirstLineFragmentCandidate {
99
+ int node = -1;
100
+ int x = 0;
101
+ int width = 0;
102
+ int height = 0;
103
+ int itemIndex = -1;
104
+ int trailingSpace = 0;
22
105
  };
23
106
 
24
107
  class LayoutScratch {
@@ -103,9 +186,84 @@ int resolvePercentSize(int basis, int percent)
103
186
  return static_cast<int>((numerator + (numerator >= 0 ? 500 : -500)) / 1000);
104
187
  }
105
188
 
189
+ // Probe the existing formatting algorithms without rewriting authored style.
190
+ // A stack of constraints keeps nested measurements finite and allocates no
191
+ // per-node storage; a final phase supplies the selected used border-box size.
192
+ struct IntrinsicSizeScope;
193
+ IntrinsicSizeScope *gIntrinsicSizeScope = nullptr;
194
+ struct IntrinsicSizeScope {
195
+ const Node &node;
196
+ bool horizontal;
197
+ int constraint; // 1=min-content, 2=max-content, 0=final used size
198
+ int borderSize = 0;
199
+ IntrinsicSizeScope *previous;
200
+ IntrinsicSizeScope(const Node &n, int mode, bool axis = true) : node(n), horizontal(axis), constraint(mode), previous(gIntrinsicSizeScope) { gIntrinsicSizeScope = this; }
201
+ ~IntrinsicSizeScope() { gIntrinsicSizeScope = previous; }
202
+ };
203
+ IntrinsicSizeScope *intrinsicSizeScope(const Node &node, bool horizontal)
204
+ {
205
+ for (auto *scope = gIntrinsicSizeScope; scope; scope = scope->previous)
206
+ if (&scope->node == &node && scope->horizontal == horizontal) return scope;
207
+ return nullptr;
208
+ }
209
+ int intrinsicSizeConstraint(const Node &node, bool horizontal)
210
+ {
211
+ if (!gIntrinsicSizeScope) return 0;
212
+ const Node *current = &node;
213
+ for (;;) {
214
+ if (auto *scope = intrinsicSizeScope(*current, horizontal)) return scope->constraint;
215
+ const int expression = horizontal ? current->style.width_expression : current->style.height_expression;
216
+ if (current->parent < 0 || (horizontal ? current->style.width : current->style.height) != kUnset ||
217
+ (expression >= 0 && !layoutSizeExpressionUsesPercentage(
218
+ static_cast<int>(current - Tree::instance().nodes()), expression))) return 0;
219
+ current = &Tree::instance().nodes()[current->parent];
220
+ }
221
+ }
222
+ int intrinsicWidthConstraint(const Node &node) { return intrinsicSizeConstraint(node, true); }
223
+ // The flex basis replaces the preferred main size for item measurement without
224
+ // changing authored style. An unresolved percentage measures content, even when
225
+ // the item also has a preferred width/height.
226
+ struct FlexBasisScope;
227
+ FlexBasisScope *gFlexBasisScope = nullptr;
228
+ struct FlexBasisScope {
229
+ const Node &node;
230
+ bool horizontal;
231
+ int value;
232
+ FlexBasisScope *previous;
233
+ FlexBasisScope(const Node &n, bool h, int v) : node(n), horizontal(h), value(v), previous(gFlexBasisScope) { gFlexBasisScope = this; }
234
+ ~FlexBasisScope() { gFlexBasisScope = previous; }
235
+ };
236
+ const FlexBasisScope *flexBasisScope(const Node &node, bool horizontal)
237
+ {
238
+ for (auto *scope = gFlexBasisScope; scope; scope = scope->previous)
239
+ if (&scope->node == &node && scope->horizontal == horizontal) return scope;
240
+ return nullptr;
241
+ }
242
+ bool hasFlexBasis(const Node &node)
243
+ {
244
+ return node.style.flex_basis != kUnset || rstyle(node.style).flex_basis_expression >= 0;
245
+ }
246
+
106
247
  bool hasExplicitWidth(const Node &node)
107
248
  {
108
- return node.style.width != kUnset || node.style.width_percent != kUnset;
249
+ if (const auto *basis = flexBasisScope(node, true)) return basis->value != kUnset;
250
+ if (const auto *scope = intrinsicSizeScope(node, true); scope && scope->constraint == 0) return true;
251
+ if (isIntrinsicSizeExpression(node.style.width_expression)) {
252
+ const auto *scope = intrinsicSizeScope(node, true);
253
+ return scope && scope->constraint == 0;
254
+ }
255
+ if (node.style.width != kUnset) return true;
256
+ if (intrinsicWidthConstraint(node)) return false;
257
+ return node.style.width_expression >= 0 || node.style.width_percent != kUnset;
258
+ }
259
+
260
+ int clampLayoutSize(const Node &node, int size, bool horizontal)
261
+ {
262
+ const auto *scope = intrinsicSizeScope(node, horizontal);
263
+ // The property's intrinsic size is measured first; its author's min/max
264
+ // constraints apply to the final used size, after resolving box edges.
265
+ if (scope && scope->constraint) return std::max(boxInsets(node.style, horizontal), size);
266
+ return clampBorderBoxSize(node.style, size, horizontal);
109
267
  }
110
268
 
111
269
  int16_t clampInt16(int value)
@@ -115,13 +273,40 @@ int16_t clampInt16(int value)
115
273
  return static_cast<int16_t>(value);
116
274
  }
117
275
 
276
+ bool percentageHeightDependsOnIntrinsicSize(const Node &node)
277
+ {
278
+ if (isOutOfFlowPosition(node.style.position)) return false;
279
+ const Node *current = &node;
280
+ while (current->parent >= 0) {
281
+ const Node &parent = Tree::instance().nodes()[current->parent];
282
+ if (isIntrinsicSizeExpression(parent.style.height_expression)) return true;
283
+ if (parent.style.height != kUnset || isOutOfFlowPosition(parent.style.position)) return false;
284
+ if (parent.style.height_expression >= 0 &&
285
+ !layoutSizeExpressionUsesPercentage(current->parent, parent.style.height_expression)) return false;
286
+ current = &parent;
287
+ }
288
+ return false;
289
+ }
290
+
118
291
  bool hasExplicitHeight(const Node &node)
119
292
  {
120
- return node.style.height != kUnset || node.style.height_percent != kUnset;
293
+ if (const auto *basis = flexBasisScope(node, false)) return basis->value != kUnset;
294
+ if (const auto *scope = intrinsicSizeScope(node, false); scope && scope->constraint == 0) return true;
295
+ if (node.style.height != kUnset) return true;
296
+ if (intrinsicSizeConstraint(node, false)) return false;
297
+ if (node.style.height_expression < 0 && node.style.height_percent == kUnset) return false;
298
+ if (!percentageHeightDependsOnIntrinsicSize(node)) return true;
299
+ return node.style.height_percent == kUnset &&
300
+ !layoutSizeExpressionUsesPercentage(static_cast<int>(&node - Tree::instance().nodes()), node.style.height_expression);
121
301
  }
122
302
 
123
303
  int resolvedStyleWidth(const Node &node, int basis)
124
304
  {
305
+ if (const auto *scope = flexBasisScope(node, true)) return scope->value == kUnset ? basis : scope->value;
306
+ if (const auto *scope = intrinsicSizeScope(node, true); scope && scope->constraint == 0)
307
+ return std::max(0, scope->borderSize - (node.style.box_sizing == 0 ? boxInsets(node.style, true) : 0));
308
+ if (!hasExplicitWidth(node)) return basis;
309
+ if (node.style.width_expression >= 0) return resolveLayoutSizeExpression(static_cast<int>(&node - Tree::instance().nodes()), node.style.width_expression, true);
125
310
  if (node.style.width != kUnset) return node.style.width;
126
311
  if (node.style.width_percent != kUnset) return resolvePercentSize(basis, node.style.width_percent);
127
312
  return basis;
@@ -129,44 +314,301 @@ int resolvedStyleWidth(const Node &node, int basis)
129
314
 
130
315
  int resolvedStyleHeight(const Node &node, int basis)
131
316
  {
317
+ if (const auto *scope = flexBasisScope(node, false)) return scope->value == kUnset ? basis : scope->value;
318
+ if (const auto *scope = intrinsicSizeScope(node, false); scope && scope->constraint == 0)
319
+ return std::max(0, scope->borderSize - (node.style.box_sizing == 0 ? boxInsets(node.style, false) : 0));
320
+ if (!hasExplicitHeight(node)) return basis;
321
+ if (node.style.height_expression >= 0) return resolveLayoutSizeExpression(static_cast<int>(&node - Tree::instance().nodes()), node.style.height_expression, false);
132
322
  if (node.style.height != kUnset) return node.style.height;
133
- if (node.style.height_percent != kUnset) return resolvePercentSize(basis, node.style.height_percent);
323
+ if (node.style.height_percent != kUnset && !percentageHeightDependsOnIntrinsicSize(node))
324
+ return resolvePercentSize(basis, node.style.height_percent);
134
325
  return basis;
135
326
  }
136
327
 
328
+ int writingMode(const Node &node)
329
+ {
330
+ const Node *current = &node;
331
+ while (current->style.writing_mode < 0 && current->parent >= 0)
332
+ current = &Tree::instance().nodes()[current->parent];
333
+ return current->style.writing_mode < 0 ? 0 : current->style.writing_mode;
334
+ }
335
+
336
+ bool rightToLeft(const Node &node)
337
+ {
338
+ const Node *current = &node;
339
+ while (current->style.direction < 0 && current->parent >= 0)
340
+ current = &Tree::instance().nodes()[current->parent];
341
+ return current->style.direction == 1;
342
+ }
343
+
344
+ struct GridAxisPlacement {
345
+ int start = kUnset, end = kUnset, span = 1;
346
+ };
347
+
348
+ GridAxisPlacement gridAxisPlacement(int start, int end, int explicitTracks, bool absolute)
349
+ {
350
+ GridAxisPlacement p;
351
+ const bool startSpan = start >= kGridLineSpan, endSpan = end >= kGridLineSpan;
352
+ p.span = std::min(kMaxGridLayoutTracks, startSpan ? start - kGridLineSpan : endSpan ? end - kGridLineSpan : 1);
353
+ auto line = [explicitTracks](int n) { return n > 0 ? n - 1 : explicitTracks + 1 + n; };
354
+ if (start && !startSpan) p.start = line(start);
355
+ if (end && !endSpan) p.end = line(end);
356
+ if (p.start != kUnset && p.end != kUnset) {
357
+ if (p.start > p.end) std::swap(p.start, p.end);
358
+ if (p.start == p.end) p.end = kUnset;
359
+ }
360
+ if (p.start != kUnset && (endSpan || !absolute) && p.end == kUnset) p.end = p.start + p.span;
361
+ if (p.end != kUnset && (startSpan || !absolute) && p.start == kUnset) p.start = p.end - p.span;
362
+ if (p.start != kUnset && p.end != kUnset) p.span = std::min(kMaxGridLayoutTracks, p.end - p.start);
363
+ return p;
364
+ }
365
+
366
+ bool gridAxisReversed(const Node &parent, bool horizontal)
367
+ {
368
+ const int mode = writingMode(parent);
369
+ const bool inlineAxis = horizontal == (mode == 0);
370
+ return inlineAxis ? rightToLeft(parent) != (mode == 4) : mode == 2 || mode == 3;
371
+ }
372
+
373
+ bool flexRowDirection(const ComputedStyle &style);
374
+
375
+ double preferredRatio(const Node &node)
376
+ {
377
+ float ratio = 0;
378
+ const int bits = rstyle(node.style).aspect_ratio;
379
+ std::memcpy(&ratio, &bits, sizeof(ratio));
380
+ if (!std::isfinite(ratio)) return 0;
381
+ if (ratio < 0 && node.type == NodeType::Image && node.image_id >= 0) return 0;
382
+ return std::abs(static_cast<double>(ratio));
383
+ }
384
+
385
+ int ratioTransferredSize(const Node &node, int crossBorderSize, bool horizontal)
386
+ {
387
+ const double ratio = preferredRatio(node);
388
+ if (ratio <= 0) return 0;
389
+ const int crossEdges = node.style.box_sizing ? 0 : boxInsets(node.style, !horizontal);
390
+ const int mainEdges = node.style.box_sizing ? 0 : boxInsets(node.style, horizontal);
391
+ const double value = std::max(0, crossBorderSize - crossEdges) * (horizontal ? ratio : 1 / ratio) + mainEdges;
392
+ return static_cast<int>(std::min(32767.0, std::round(value)));
393
+ }
394
+
395
+ bool definiteFlexCrossSize(const Node &parent, const Node &child, bool row)
396
+ {
397
+ const int alignment = child.style.align_self >= 0 ? child.style.align_self : parent.style.align_items;
398
+ const int margins = row ? 5 : 10;
399
+ return parent.style.flex_wrap == 0 && alignment == 0 && !(child.style.margin_auto & margins) &&
400
+ (row ? hasExplicitHeight(parent) : hasExplicitWidth(parent));
401
+ }
402
+
403
+ void applyPreferredRatio(Node &node, int availableWidth, int availableHeight)
404
+ {
405
+ if (!preferredRatio(node) || (node.type != NodeType::View && node.type != NodeType::Image)) return;
406
+ if (node.type != NodeType::Image && LayoutEngine::isInlineLevelNode(node)) return;
407
+ bool width = hasExplicitWidth(node), height = hasExplicitHeight(node);
408
+ if (width && height) return;
409
+ const Node *parent = node.parent >= 0 ? &Tree::instance().nodes()[node.parent] : nullptr;
410
+ const bool flexItem = parent && parent->style.display == kDisplayFlex;
411
+ if (flexItem && !width && !height) {
412
+ const bool row = flexRowDirection(parent->style) != (writingMode(*parent) != 0);
413
+ if (definiteFlexCrossSize(*parent, node, row)) {
414
+ if (row) {
415
+ node.layout.height = clampLayoutSize(node, availableHeight - node.style.margin[0] - node.style.margin[2], false);
416
+ height = true;
417
+ } else {
418
+ node.layout.width = clampLayoutSize(node, availableWidth - node.style.margin[1] - node.style.margin[3], true);
419
+ width = true;
420
+ }
421
+ }
422
+ }
423
+ if (!width && !height) {
424
+ // Normal block flow supplies a definite inline size. Shrink-to-fit
425
+ // contexts keep the intrinsic width measured from their contents.
426
+ if (!flexItem && !node.style.float_side && !isOutOfFlowPosition(node.style.position))
427
+ node.layout.width = clampLayoutSize(node, availableWidth - node.style.margin[1] - node.style.margin[3], true);
428
+ width = true;
429
+ }
430
+ const bool horizontal = !width && height;
431
+ int16_t &target = horizontal ? node.layout.width : node.layout.height;
432
+ const int fromRatio = ratioTransferredSize(node, horizontal ? node.layout.height : node.layout.width, horizontal);
433
+ // Non-scrollable boxes retain a content-based minimum on the automatic axis.
434
+ const bool contentMinimum = node.type != NodeType::Image && (horizontal ? node.style.min_width : node.style.min_height) == kUnset &&
435
+ !isScrollableOverflow(horizontal ? overflowX(node.style) : overflowY(node.style));
436
+ const int result = contentMinimum ? std::max<int>(target, fromRatio) : fromRatio;
437
+ target = clampInt16(clampLayoutSize(node, result, horizontal));
438
+ }
439
+
440
+ int baselineFallbackAlignment(const Node &parent, const Node &child, int alignment, int free, bool horizontal, bool staticPosition)
441
+ {
442
+ // Baseline self-alignment follows the subject's writing mode. Resolving
443
+ // automatic insets uses the fallback edge without overflow safety; actual
444
+ // in-flow self-alignment uses the safe fallback instead (CSS Position 3.5.1).
445
+ if (!staticPosition && free < 0)
446
+ return gridAxisReversed(parent, horizontal) ? 2 : 6;
447
+ const bool last = (alignment & 15) == kAlignLastBaseline;
448
+ return gridAxisReversed(child, horizontal) != last ? 2 : 6;
449
+ }
450
+
451
+ // Self-relative edges use the subject's writing mode, even when it differs
452
+ // from the containing box. Return physical start/end; flex positioning may
453
+ // subsequently express it relative to its reversed cross axis.
454
+ int physicalSelfAlignment(const Node &parent, const Node &child, int alignment, int free, bool horizontal)
455
+ {
456
+ const int keyword = alignment & 15;
457
+ if (keyword != kAlignSelfStart && keyword != kAlignSelfEnd && keyword != kAlignLeft && keyword != kAlignRight) return -1;
458
+ if ((alignment & kAlignSafe) && free < 0) return gridAxisReversed(parent, horizontal) ? 2 : 6;
459
+ if (keyword == kAlignLeft || keyword == kAlignRight) {
460
+ if (horizontal) return keyword == kAlignRight ? 2 : 6;
461
+ // In vertical text, left/right are line-relative and independent of
462
+ // bidi direction. Sideways-lr alone has line-left at physical bottom.
463
+ const int mode = writingMode(parent);
464
+ if (mode != 0) return (mode == 4) != (keyword == kAlignRight) ? 2 : 6;
465
+ return 6;
466
+ }
467
+ return gridAxisReversed(child, horizontal) != (keyword == kAlignSelfEnd) ? 2 : 6;
468
+ }
469
+
470
+ int usedGridAlignment(const Node &parent, const Node &child, int alignment, int free, bool horizontal, bool staticPosition = false)
471
+ {
472
+ const int self = physicalSelfAlignment(parent, child, alignment, free, horizontal);
473
+ if (self >= 0) return self;
474
+ const int keyword = alignment & 15;
475
+ if (keyword == 5 || keyword == kAlignLastBaseline)
476
+ return baselineFallbackAlignment(parent, child, alignment, free, horizontal, staticPosition);
477
+ if (keyword == 0 || keyword == 6) alignment = (alignment & ~15) | kAlignStart;
478
+ else if (keyword == 2) alignment = (alignment & ~15) | kAlignEnd;
479
+ return usedAlignment(alignment, free, gridAxisReversed(parent, horizontal));
480
+ }
481
+
482
+ void gridPhysicalRange(const Node &parent, bool columns, int start, int end, int &offset, int &size)
483
+ {
484
+ const bool horizontal = columns == (writingMode(parent) == 0);
485
+ const int available = (horizontal ? parent.layout.width : parent.layout.height) - boxInsets(parent.style, horizontal);
486
+ offset = boxInset(parent.style, horizontal ? 3 : 0) + (gridAxisReversed(parent, horizontal) ? available - end : start);
487
+ size = std::max(0, end - start);
488
+ }
489
+
490
+ bool flexRowDirection(const ComputedStyle &style)
491
+ {
492
+ return !style.flex_direction_explicit || (style.flex_direction & 1);
493
+ }
494
+
495
+ int resolvedGap(const Node &node, bool rowGap, int width, int height)
496
+ {
497
+ const int length = rowGap ? node.style.row_gap : node.style.column_gap;
498
+ const int percent = rowGap ? node.style.row_gap_percent : node.style.column_gap_percent;
499
+ const bool vertical = writingMode(node) != 0;
500
+ const bool horizontalAxis = rowGap == vertical;
501
+ if (percent != kUnset) {
502
+ // Cyclic percentage gaps have zero used size in an indefinite flex axis.
503
+ if (horizontalAxis ? !hasExplicitWidth(node) : !hasExplicitHeight(node)) return 0;
504
+ return std::max(0, resolvePercentSize(horizontalAxis ? width : height, percent));
505
+ }
506
+ return std::max(0, length == kUnset ? node.style.gap : length);
507
+ }
508
+
509
+ int clampBorderSize(LayoutEngine &engine, const Node &node, int size, bool horizontal)
510
+ {
511
+ return clampLayoutSize(node, size, horizontal);
512
+ }
513
+
137
514
  class FlexLayoutPass {
138
515
  public:
139
- FlexLayoutPass(LayoutEngine &engine, Node &node, int *children, int childCount, bool isRow, int mainAvail, int padWidth, int padHeight, FlexLine *lines, bool inlineRow = false)
516
+ FlexLayoutPass(LayoutEngine &engine, Node &node, int *children, int childCount, bool isRow, int mainAvail, int padWidth, int padHeight, FlexLine *lines, bool inlineRow = false, bool assignedSize = false)
140
517
  : engine_(engine),
141
518
  node_(node),
142
519
  children_(children),
143
520
  childCount_(childCount),
144
521
  isRow_(isRow),
145
522
  inlineRow_(inlineRow && isRow),
523
+ assignedSize_(assignedSize),
146
524
  mainAvail_(mainAvail),
147
525
  padWidth_(padWidth),
148
526
  padHeight_(padHeight),
149
527
  lines_(lines)
150
528
  {
529
+ const bool logicalRow = node.style.display == kDisplayFlex ? flexRowDirection(node.style) : isRow;
530
+ mainGap_ = resolvedGap(node, !logicalRow, padWidth, padHeight);
531
+ crossGap_ = resolvedGap(node, logicalRow, padWidth, padHeight);
532
+ // Most containers fit the shared 32-line storage. Allocate extra lines
533
+ // only for a wrapping container that can actually exceed it.
534
+ if (node.style.display == kDisplayFlex && node.style.flex_wrap && childCount > kMaxFlexLines) {
535
+ extraLines_.resize(childCount);
536
+ lines_ = extraLines_.data();
537
+ }
151
538
  }
152
539
 
153
540
  void measureChildren()
154
541
  {
155
542
  for (int i = 0; i < childCount_; i++) {
156
543
  const int child = children_[i];
157
- const int childAvailWidth = isRow_ ? mainAvail_ : padWidth_;
158
- const int childAvailHeight = isRow_ ? padHeight_ : mainAvail_;
159
- engine_.layoutNode(child, childAvailWidth, childAvailHeight);
160
- applyFlexBasis(child);
544
+ int childAvailWidth = isRow_ ? mainAvail_ : padWidth_;
545
+ int childAvailHeight = isRow_ ? padHeight_ : mainAvail_;
546
+ const int count = rstyle(node_.style).flex_line_count;
547
+ const Node &item = Tree::instance().nodes()[child];
548
+ if (node_.style.display == kDisplayFlex && node_.style.flex_wrap && count > 1) {
549
+ // The specified count limits available cross space even for normal
550
+ // wrapping. Percentage cross sizes retain the container's basis.
551
+ const auto available = [&](int size) {
552
+ return static_cast<int>(std::max<std::int64_t>(0, (static_cast<std::int64_t>(size) -
553
+ static_cast<std::int64_t>(count - 1) * crossGap_) / count));
554
+ };
555
+ if (isRow_ && hasExplicitHeight(node_) && !hasExplicitHeight(item)) childAvailHeight = available(childAvailHeight);
556
+ if (!isRow_ && !hasExplicitWidth(item)) childAvailWidth = available(childAvailWidth);
557
+ }
558
+ if (node_.style.display == kDisplayFlex && hasFlexBasis(item)) {
559
+ const int basis = resolveLayoutFlexBasis(child, flexPercentageBasis(), isRow_);
560
+ FlexBasisScope scope(item, isRow_, basis);
561
+ engine_.layoutNode(child, childAvailWidth, childAvailHeight);
562
+ } else {
563
+ engine_.layoutNode(child, childAvailWidth, childAvailHeight);
564
+ }
565
+ if (node_.style.display == kDisplayFlex) {
566
+ applyFlexBasis(child);
567
+ Node &item = Tree::instance().nodes()[child];
568
+ const int floor = automaticMinimumMainSize(item);
569
+ int16_t &main = isRow_ ? item.layout.width : item.layout.height;
570
+ if (main < floor) { main = clampInt16(floor); engine_.repositionChildren(child); }
571
+ }
161
572
  }
162
573
  }
163
574
 
575
+ void layoutLines(bool autosize)
576
+ {
577
+ const int originalWidth = node_.layout.width, originalHeight = node_.layout.height;
578
+ int lineCount = buildLines();
579
+ expandCrossSizes(lineCount, autosize);
580
+ if (autosize) autosizeParent(lineCount);
581
+ positionLines(lineCount);
582
+ if (node_.style.display != kDisplayFlex) return;
583
+ Node *nodes = Tree::instance().nodes();
584
+ bool collapsed = false;
585
+ for (int i = 0; i < childCount_; ++i) collapsed |= isCollapsedFlexItem(nodes[children_[i]]);
586
+ if (!collapsed) return;
587
+
588
+ // Flexbox 9.4: remember the original (including stretched) line size,
589
+ // then restart with zero-main-size struts. Compact the child list only
590
+ // AFTER assigning struts to lines, so allocation, gaps, auto margins,
591
+ // baselines and alignment all operate on the surviving items alone.
592
+ std::vector<int> struts(childCount_, -1);
593
+ for (int line = 0; line < lineCount; ++line)
594
+ for (int i = lines_[line].start; i < lines_[line].start + lines_[line].count; ++i)
595
+ if (isCollapsedFlexItem(nodes[children_[i]])) struts[i] = lines_[line].crossSize;
596
+ node_.layout.width = originalWidth;
597
+ node_.layout.height = originalHeight;
598
+ measureChildren();
599
+ lineCount = buildCollapsedLines(struts);
600
+ expandCrossSizes(lineCount, autosize);
601
+ if (autosize) autosizeParent(lineCount);
602
+ positionLines(lineCount);
603
+ }
604
+
164
605
  // Flex line packing. An inline formatting context does NOT come through here —
165
606
  // layoutInlineFlow owns it — because flex lines cannot express one: their items
166
607
  // are atomic, so a text run may neither share a line with its neighbours nor
167
608
  // split across two.
168
609
  int buildLines()
169
610
  {
611
+ if (node_.style.display == kDisplayFlex && (node_.style.flex_wrap & 4)) return buildBalancedLines();
170
612
  int lineStart = 0;
171
613
  int lineMain = 0;
172
614
  int lineCross = 0;
@@ -184,8 +626,8 @@ public:
184
626
  ? (childNode.layout.height + childNode.style.margin[0] + childNode.style.margin[2])
185
627
  : (childNode.layout.width + childNode.style.margin[1] + childNode.style.margin[3]);
186
628
 
187
- const int withGap = gapCount > 0 ? node_.style.gap : 0;
188
- if (node_.style.flex_wrap && lineMain + childMain + withGap > mainAvail_ && gapCount > 0) {
629
+ const int withGap = gapCount > 0 ? mainGap_ : 0;
630
+ if (node_.style.display == kDisplayFlex && node_.style.flex_wrap && lineMain + childMain + withGap > flexWrapLimit() && gapCount > 0) {
189
631
  appendLine(lineCount, lineStart, gapCount, lineMain, lineCross);
190
632
  lineStart = i;
191
633
  lineMain = childMain;
@@ -214,24 +656,87 @@ public:
214
656
  // One forward walk. Per line box it first SCANS ahead to learn which items
215
657
  // share it — and therefore the line's ascent, and so its baseline — then
216
658
  // places them. The scans partition the item list, so the pass is linear.
217
- void layoutInlineFlow(bool autosize)
659
+ InlineFlowExtent layoutInlineFlow(bool autosize, bool anonymous = false)
218
660
  {
219
661
  Node *nodes = Tree::instance().nodes();
220
- const int contentW = mainAvail_ < 0 ? 0 : mainAvail_;
221
- const int contentLeft = node_.style.padding[3];
222
- const int contentTop = node_.style.padding[0];
223
- const int gapStyle = node_.style.gap;
224
-
225
- // CSS drops leading whitespace at the start of a LINE BOX. This block opens
226
- // one only when it is not itself an inline box that its parent may have
227
- // placed part-way along a line: `<p>…baseline.<span> Inline emphasis</span>…`
228
- // runs its own flow inside the span, and the space that separates it from
229
- // the text before it is content, not indentation.
230
- const bool blockOpensItsFirstLine = !LayoutEngine::isInlineLevelNode(node_);
662
+ const int parentId = static_cast<int>(&node_ - nodes);
663
+ int firstLineStyleOwner = -1;
664
+ for (int ancestor = parentId; ancestor >= 0; ancestor = nodes[ancestor].parent) {
665
+ const NodeRareData *rare = rareDataFor(ancestor);
666
+ if (rare && rare->firstLineBackground.hasColor) {
667
+ firstLineStyleOwner = ancestor;
668
+ break;
669
+ }
670
+ // Inline boxes carry the rule down their descendants. A block child
671
+ // carries it only when it is the first in-flow formatted child of its
672
+ // parent; following block siblings start after the owner's first line.
673
+ if (!LayoutEngine::isCssInlineLevelBox(nodes[ancestor])) {
674
+ if (isOutOfFlowPosition(nodes[ancestor].style.position) || nodes[ancestor].style.float_side) break;
675
+ const int parent = nodes[ancestor].parent;
676
+ if (parent < 0) break;
677
+ if (nodes[parent].style.display == kDisplayFlex || isDisplayGrid(nodes[parent].style)) break;
678
+ bool firstInFlow = true;
679
+ for (int sibling = nodes[parent].first_child; sibling >= 0 && sibling != ancestor;
680
+ sibling = nodes[sibling].next_sibling) {
681
+ if (!isDisplayNone(nodes[sibling].style) &&
682
+ !isOutOfFlowPosition(nodes[sibling].style.position) &&
683
+ !nodes[sibling].style.float_side &&
684
+ !suppressAnonymousWhitespace(nodes, parent, sibling)) {
685
+ firstInFlow = false;
686
+ break;
687
+ }
688
+ }
689
+ if (!firstInFlow) break;
690
+ }
691
+ }
692
+ const bool captureFirstLine = firstLineStyleOwner >= 0;
693
+ // Runs that leave this formatting context must not keep an old fragment
694
+ // rectangle. A nested inline flow may write its own first-line fragment
695
+ // later in the same layout pass.
696
+ for (int i = 0; i < childCount_; ++i) {
697
+ const int child = children_[i];
698
+ if (NodeRareData *rare = rareDataFor(child)) rare->firstLineFragment.valid = false;
699
+ const int run = transparentInlineRun(nodes[child]);
700
+ if (run >= 0) if (NodeRareData *rare = rareDataFor(run)) rare->firstLineFragment.valid = false;
701
+ }
702
+ std::vector<std::pair<int, int>> staticBoundaries;
703
+ int flowIndex = 0;
704
+ for (int child = node_.first_child; child >= 0; child = nodes[child].next_sibling) {
705
+ if (isDisplayNone(nodes[child].style) || suppressAnonymousWhitespace(nodes, parentId, child)) continue;
706
+ if (isOutOfFlowPosition(nodes[child].style.position)) {
707
+ if (auto *rare = rareDataFor(child)) rare->inlineStaticPosition.valid = false;
708
+ if (LayoutEngine::isCssInlineLevelBox(nodes[child], true))
709
+ staticBoundaries.emplace_back(flowIndex, child);
710
+ continue;
711
+ }
712
+ while (flowIndex < childCount_ && children_[flowIndex] != child) ++flowIndex;
713
+ if (flowIndex < childCount_) ++flowIndex;
714
+ }
715
+ int contentW = mainAvail_ < 0 ? 0 : mainAvail_;
716
+ if (intrinsicWidthConstraint(node_) == 1) {
717
+ int pendingWord = 0;
718
+ for (int i = 0; i < childCount_; ++i) {
719
+ const Node &child = nodes[children_[i]];
720
+ if (isLineBreak(child)) { pendingWord = 0; continue; }
721
+ const int wrappedRun = transparentInlineRun(child);
722
+ if (child.type == NodeType::Text || wrappedRun >= 0) {
723
+ contentW = std::max(contentW, TextRenderer::minContentWidth(wrappedRun >= 0 ? nodes[wrappedRun] : child, &pendingWord));
724
+ } else {
725
+ contentW = std::max(contentW, child.layout.width + child.style.margin[1] + child.style.margin[3]);
726
+ pendingWord = 0;
727
+ }
728
+ }
729
+ }
730
+ const int contentLeft = boxInset(node_.style, 3);
731
+ const int contentTop = boxInset(node_.style, 0);
732
+ const int gapStyle = mainGap_;
733
+
734
+ const bool blockOpensItsFirstLine = startsFormattingLine(nodes, parentId);
231
735
  int i = 0;
232
736
  int lineTop = contentTop;
233
737
  int flowBottom = contentTop;
234
738
  int maxLineWidth = 0;
739
+ int firstLineHeight = 0;
235
740
  // Carried across a wrapped run: the pen its last line ended at, that
236
741
  // line's already-fixed baseline, and the ascent/descent it contributes.
237
742
  int penStart = 0;
@@ -239,6 +744,21 @@ public:
239
744
  int continuedBaseline = 0;
240
745
  int inheritedAscent = 0;
241
746
  int inheritedDescent = 0;
747
+ std::vector<bool> staticCaptured(staticBoundaries.size(), false);
748
+ std::vector<FirstLineFragmentCandidate> firstLineCandidates;
749
+ auto captureStaticBoundary = [&](int boundary, int pen, std::vector<int> &captured,
750
+ bool continuationLine = false) {
751
+ for (std::size_t k = 0; k < staticBoundaries.size(); ++k) {
752
+ if (staticCaptured[k] || staticBoundaries[k].first != boundary) continue;
753
+ staticCaptured[k] = true;
754
+ captured.push_back(staticBoundaries[k].second);
755
+ NodeRareData &rare = ensureRareData(staticBoundaries[k].second);
756
+ rare.inlineStaticPosition.continuationLine =
757
+ continuationLine && LayoutEngine::isCssInlineLevelBox(node_);
758
+ rare.inlineStaticPosition.x = clampInt16(
759
+ (rare.inlineStaticPosition.continuationLine ? 0 : contentLeft) + pen);
760
+ }
761
+ };
242
762
 
243
763
  while (i < childCount_) {
244
764
  // A line box that opens as the tail of a wrapped run already has content
@@ -252,21 +772,33 @@ public:
252
772
  int wrapSpans = 0;
253
773
  int wrapAdvance = 0;
254
774
  int wrapLastWidth = 0;
775
+ std::vector<int> lineStaticChildren;
255
776
 
256
777
  for (; j < childCount_; j++) {
778
+ captureStaticBoundary(j, pen, lineStaticChildren, lineIsContinuation || i > 0);
257
779
  const int child = children_[j];
258
780
  Node &cn = nodes[child];
259
781
  const int marginL = cn.style.margin[3];
260
782
  const int marginR = cn.style.margin[1];
261
783
  const int gap = pen > 0 ? gapStyle : 0;
262
784
 
785
+ if (isLineBreak(cn)) {
786
+ // A BR closes this line even under white-space:nowrap/pre.
787
+ // It contributes its inherited line metrics to an otherwise
788
+ // empty line, but does not create a trailing phantom line.
789
+ lineAscent = std::max(lineAscent, childBaseline(cn));
790
+ lineDescent = std::max(lineDescent, cn.layout.height - childBaseline(cn));
791
+ ++j;
792
+ break;
793
+ }
794
+
263
795
  // The run this item contributes to the line: itself when it IS a text
264
796
  // run, or the one inside a transparent <span> wrapper.
265
797
  const int innerRun = isFragmentableRun(cn) ? -1 : transparentInlineRun(cn);
266
798
  Node &subject = innerRun >= 0 ? nodes[innerRun] : cn;
267
799
  if (isFragmentableRun(subject)) {
268
- const int padH = subject.style.padding[1] + subject.style.padding[3];
269
- const int padV = subject.style.padding[0] + subject.style.padding[2];
800
+ const int padH = boxInset(subject.style, 1) + boxInset(subject.style, 3);
801
+ const int padV = boxInset(subject.style, 0) + boxInset(subject.style, 2);
270
802
  // Budgets are TEXT widths: the run's own padding is part of its box,
271
803
  // not of the line it can fill.
272
804
  const int rest = contentW - marginL - marginR - padH;
@@ -279,16 +811,22 @@ public:
279
811
  // run keeps flowing whole, exactly as before.
280
812
  const bool haveLineMetrics =
281
813
  m.lineAdvance > 0 &&
282
- childFirstBaseline(subject) <= subject.style.padding[0] + m.lineAdvance;
814
+ childBaseline(subject) <= boxInset(subject.style, 0) + m.lineAdvance;
283
815
  if (m.lineCount > 0 && haveLineMetrics) {
284
816
  // Its first WORD does not fit what is left: the run starts the
285
817
  // next line box rather than overflowing it or being cut open.
286
- if (pen > 0 && (m.firstLineWidth > firstAvail || m.firstLineForcedSplit)) break;
818
+ if (pen > 0 && m.firstLineWidth > firstAvail) break;
287
819
  const int boxH = m.lineCount * m.lineAdvance + padV;
288
820
  const bool wraps = m.lineCount > 1;
289
821
  const int boxW = wraps ? rest + padH : m.firstLineWidth + padH;
290
822
  const int indent =
291
823
  (wraps ? pen + gap : 0) + m.firstLineIndentAdjust;
824
+ const bool firstLineFragment = captureFirstLine && i == 0 && m.firstLineWidth > 0;
825
+ const int fragmentItemX = wraps ? contentLeft + marginL : contentLeft + pen + gap + marginL;
826
+ // The text-command indent compensates for collapsed leading
827
+ // whitespace; that discarded space is not part of the fragment.
828
+ const int firstLineFragmentX = fragmentItemX + (wraps ? pen + gap : 0);
829
+ const int firstLineFragmentWidth = m.firstLineWidth + padH;
292
830
  subject.layout.height = clampInt16(boxH);
293
831
  subject.layout.width = clampInt16(boxW);
294
832
  subject.layout.inline_indent = clampInt16(indent);
@@ -303,7 +841,7 @@ public:
303
841
  cn.layout.inline_indent = clampInt16(indent);
304
842
  }
305
843
  if (wraps) {
306
- const int ascent = cn.style.margin[0] + childFirstBaseline(cn);
844
+ const int ascent = cn.style.margin[0] + childBaseline(cn);
307
845
  const int descent = runLineDescent(subject, m.lineAdvance);
308
846
  if (ascent > lineAscent) lineAscent = ascent;
309
847
  if (descent > lineDescent) lineDescent = descent;
@@ -313,6 +851,10 @@ public:
313
851
  wrapSpans = m.lineCount;
314
852
  wrapAdvance = m.lineAdvance;
315
853
  wrapLastWidth = m.lastLineWidth + padH;
854
+ if (firstLineFragment)
855
+ firstLineCandidates.push_back({innerRun >= 0 ? innerRun : child,
856
+ firstLineFragmentX, firstLineFragmentWidth,
857
+ m.lineAdvance + padV, j, m.firstLineTrailingSpace});
316
858
  j++;
317
859
  break; // the run closes this line box
318
860
  }
@@ -323,40 +865,112 @@ public:
323
865
 
324
866
  const int itemMain = cn.layout.width + marginL + marginR;
325
867
  if (pen > 0 && pen + gap + itemMain > contentW) break;
326
- const int ascent = cn.style.margin[0] + childFirstBaseline(cn);
327
- const int descent = cn.layout.height + cn.style.margin[2] - childFirstBaseline(cn);
868
+ if (isFragmentableRun(subject) && captureFirstLine && i == 0) {
869
+ const int padH = boxInset(subject.style, 1) + boxInset(subject.style, 3);
870
+ const int rest = contentW - marginL - marginR - padH;
871
+ const InlineFlowMeasure m = TextRenderer::measureInlineFlow(
872
+ subject, rest - pen - gap, rest, pen == 0 && (j > 0 || blockOpensItsFirstLine));
873
+ if (m.lineCount > 0 && m.firstLineWidth > 0) {
874
+ firstLineCandidates.push_back({innerRun >= 0 ? innerRun : child,
875
+ contentLeft + pen + gap + marginL,
876
+ m.firstLineWidth + padH,
877
+ m.lineAdvance + boxInset(subject.style, 0) + boxInset(subject.style, 2),
878
+ j, m.firstLineTrailingSpace});
879
+ }
880
+ }
881
+ const int ascent = cn.style.margin[0] + childBaseline(cn);
882
+ const int descent = cn.layout.height + cn.style.margin[2] - childBaseline(cn);
328
883
  if (ascent > lineAscent) lineAscent = ascent;
329
884
  if (descent > lineDescent) lineDescent = descent;
330
885
  pen += gap + itemMain;
331
886
  }
887
+ const bool endedWithBreak = j > i && isLineBreak(nodes[children_[j - 1]]);
888
+ const bool trailingWrappedStaticBoundary = j >= childCount_ && !endedWithBreak && wrapIdx >= 0;
889
+ if (j >= childCount_ && !endedWithBreak && !trailingWrappedStaticBoundary)
890
+ captureStaticBoundary(childCount_, pen, lineStaticChildren, lineIsContinuation || i > 0);
332
891
 
333
892
  if (pen > maxLineWidth) maxLineWidth = pen;
334
893
 
335
894
  const int baseline = continuing ? continuedBaseline : lineTop + lineAscent;
336
895
  lineTop = baseline - lineAscent;
896
+ for (int id : lineStaticChildren) {
897
+ auto &position = ensureRareData(id).inlineStaticPosition;
898
+ position.y = clampInt16(lineTop);
899
+ position.valid = true;
900
+ }
337
901
  int lineCross = lineAscent + lineDescent;
338
902
  if (lineCross < 0) lineCross = 0;
903
+ const int actualLineCross = lineCross;
904
+ if (i == 0) firstLineHeight = lineCross;
339
905
  // The one case the flex path's expandCrossSizes is observable here: a
340
906
  // lone line box in a block with a definite height fills it, so
341
907
  // `align-self: center/end` on an inline child has room to work.
342
- if (i == 0 && j >= childCount_ && wrapIdx < 0 && hasExplicitHeight(node_) &&
908
+ if (!anonymous && i == 0 && j >= childCount_ && wrapIdx < 0 && hasExplicitHeight(node_) &&
343
909
  padHeight_ > lineCross)
344
910
  lineCross = padHeight_;
345
911
 
346
912
  placeLineItems(nodes, i, j, contentLeft, contentW, lineTop, lineCross, baseline, penStart,
347
913
  !lineIsContinuation);
914
+ if (i == 0 && captureFirstLine) {
915
+ int firstFormattedLineHeight = actualLineCross;
916
+ if (!firstLineCandidates.empty()) firstFormattedLineHeight = 0;
917
+ for (const auto &candidate : firstLineCandidates)
918
+ firstFormattedLineHeight = std::max(firstFormattedLineHeight, candidate.height);
919
+ if (firstLineStyleOwner == parentId) {
920
+ auto &style = ensureRareData(parentId).firstLineBackground;
921
+ if (!style.lineValid) {
922
+ style.lineY = clampInt16(lineTop);
923
+ style.lineHeight = clampInt16(firstFormattedLineHeight);
924
+ style.lineContextNode = static_cast<std::int16_t>(parentId);
925
+ style.lineValid = actualLineCross > 0;
926
+ }
927
+ } else if (firstLineStyleOwner >= 0 && !LayoutEngine::isCssInlineLevelBox(node_)) {
928
+ // A nested inline's local first line may ultimately land on a
929
+ // later owner line. The owner's inline pass chooses that anchor;
930
+ // only an eligible first block child can supply it from below.
931
+ auto &style = ensureRareData(firstLineStyleOwner).firstLineBackground;
932
+ if (!style.lineValid) {
933
+ style.lineY = clampInt16(lineTop);
934
+ style.lineHeight = clampInt16(firstFormattedLineHeight);
935
+ style.lineContextNode = static_cast<std::int16_t>(parentId);
936
+ style.lineValid = actualLineCross > 0;
937
+ }
938
+ }
939
+ for (const auto &candidate : firstLineCandidates) {
940
+ if (candidate.node < 0 || candidate.node >= Tree::instance().nodeCount()) continue;
941
+ auto &fragment = ensureRareData(candidate.node).firstLineFragment;
942
+ fragment.x = clampInt16(candidate.x);
943
+ fragment.y = clampInt16(lineTop);
944
+ // Spaces between inline runs remain part of the background;
945
+ // collapsible spaces at the end of the line do not.
946
+ const bool endsLine = candidate.itemIndex == j - (endedWithBreak ? 2 : 1);
947
+ fragment.width = clampInt16(std::max(0, candidate.width - (endsLine ? candidate.trailingSpace : 0)));
948
+ fragment.height = clampInt16(candidate.height);
949
+ fragment.contextNode = static_cast<std::int16_t>(parentId);
950
+ fragment.valid = fragment.width > 0 && fragment.height > 0;
951
+ }
952
+ }
348
953
 
349
954
  if (baseline + lineDescent > flowBottom) flowBottom = baseline + lineDescent;
350
955
  if (lineTop + lineCross > flowBottom) flowBottom = lineTop + lineCross;
351
956
 
352
957
  if (wrapIdx >= 0) {
353
958
  Node &run = nodes[children_[wrapIdx]];
354
- const int runBaseline = run.layout.y + childFirstBaseline(run);
959
+ const int runBaseline = run.layout.y + childBaseline(run);
355
960
  continuedBaseline = runBaseline + (wrapSpans - 1) * wrapAdvance;
356
- inheritedAscent = run.style.margin[0] + childFirstBaseline(run);
961
+ inheritedAscent = run.style.margin[0] + childBaseline(run);
357
962
  inheritedDescent = runLineDescent(run, wrapAdvance);
358
963
  penStart = run.style.margin[3] + wrapLastWidth + run.style.margin[1];
359
964
  continuing = true;
965
+ if (trailingWrappedStaticBoundary) {
966
+ std::vector<int> trailingStaticChildren;
967
+ captureStaticBoundary(childCount_, penStart, trailingStaticChildren, true);
968
+ for (int id : trailingStaticChildren) {
969
+ auto &position = ensureRareData(id).inlineStaticPosition;
970
+ position.y = clampInt16(continuedBaseline - inheritedAscent);
971
+ position.valid = true;
972
+ }
973
+ }
360
974
  if (continuedBaseline + inheritedDescent > flowBottom)
361
975
  flowBottom = continuedBaseline + inheritedDescent;
362
976
  if (penStart > maxLineWidth) maxLineWidth = penStart;
@@ -367,6 +981,15 @@ public:
367
981
  inheritedAscent = 0;
368
982
  inheritedDescent = 0;
369
983
  }
984
+ if (j >= childCount_ && endedWithBreak) {
985
+ std::vector<int> trailingStaticChildren;
986
+ captureStaticBoundary(childCount_, 0, trailingStaticChildren, true);
987
+ for (int id : trailingStaticChildren) {
988
+ auto &position = ensureRareData(id).inlineStaticPosition;
989
+ position.y = clampInt16(lineTop);
990
+ position.valid = true;
991
+ }
992
+ }
370
993
 
371
994
  // A line box that took no item and inherited no run tail would spin. The
372
995
  // scan only produces that for an item wider than the whole box, so place
@@ -375,21 +998,32 @@ public:
375
998
  if (j == i && !lineIsContinuation) j = i + 1;
376
999
  i = j;
377
1000
  }
1001
+ if (childCount_ == 0 && !staticBoundaries.empty()) {
1002
+ std::vector<int> emptyStaticChildren;
1003
+ captureStaticBoundary(0, 0, emptyStaticChildren);
1004
+ for (int id : emptyStaticChildren) {
1005
+ auto &position = ensureRareData(id).inlineStaticPosition;
1006
+ position.y = clampInt16(contentTop);
1007
+ position.valid = true;
1008
+ }
1009
+ }
378
1010
 
379
- if (!autosize) return;
1011
+ const InlineFlowExtent extent{maxLineWidth, std::max(0, flowBottom - contentTop), firstLineHeight};
1012
+ if (!autosize) return extent;
380
1013
  // Same rules as autosizeParent: a scroll container keeps the size it was
381
1014
  // given on its scrolling axis so its overflow becomes scroll range.
382
1015
  const int flowHeight = flowBottom - contentTop;
383
1016
  const bool keepScrollHeight = scrollsOverflowY(node_.style) && node_.layout.height > 0;
384
- const bool keepScrollWidth = scrollsOverflowX(node_.style) && node_.layout.width > 0;
1017
+ const bool keepScrollWidth = !intrinsicWidthConstraint(node_) && scrollsOverflowX(node_.style) && node_.layout.width > 0;
385
1018
  if (!hasExplicitHeight(node_) && !keepScrollHeight) {
386
- const int height = (flowHeight < 0 ? 0 : flowHeight) + node_.style.padding[0] + node_.style.padding[2];
387
- node_.layout.height = clampInt16(engine_.clampSize(height, node_.style.min_height, node_.style.max_height));
1019
+ const int height = (flowHeight < 0 ? 0 : flowHeight) + boxInset(node_.style, 0) + boxInset(node_.style, 2);
1020
+ node_.layout.height = clampInt16(clampLayoutSize(node_, height, false));
388
1021
  }
389
1022
  if (!hasExplicitWidth(node_) && !keepScrollWidth) {
390
- const int width = maxLineWidth + node_.style.padding[1] + node_.style.padding[3];
391
- node_.layout.width = clampInt16(engine_.clampSize(width, node_.style.min_width, node_.style.max_width));
1023
+ const int width = maxLineWidth + boxInset(node_.style, 1) + boxInset(node_.style, 3);
1024
+ node_.layout.width = clampInt16(clampLayoutSize(node_, width, true));
392
1025
  }
1026
+ return extent;
393
1027
  }
394
1028
 
395
1029
  // A text run whose line breaking this engine owns, and which therefore flows
@@ -397,7 +1031,7 @@ public:
397
1031
  // or nowrap run keeps its own box.
398
1032
  static bool isFragmentableRun(const Node &n)
399
1033
  {
400
- return n.type == NodeType::Text && !n.text.empty() && n.style.white_space != 1 &&
1034
+ return n.type == NodeType::Text && !n.text.empty() && n.style.white_space != 1 && n.style.white_space != 2 &&
401
1035
  n.style.width == kUnset && n.style.width_percent == kUnset;
402
1036
  }
403
1037
 
@@ -409,10 +1043,11 @@ public:
409
1043
  if (n.style.has_bg || n.style.border_width > 0 || hasSideBorder(n.style)) return false;
410
1044
  #if GEA_EMBEDDED_RARE_STYLE_INLINE
411
1045
  const RareStyle &r = rstyle(n.style);
412
- if (r.transform_rotate || r.transform_rotate_x || r.transform_rotate_y ||
413
- r.transform_translate_x || r.transform_translate_y || r.transform_translate_z ||
414
- r.transform_translate_x_percent || r.transform_translate_y_percent ||
415
- r.transform_scale_x != 1000 || r.transform_scale_y != 1000 || r.perspective ||
1046
+ if (r.translate_present || r.transform_present || r.rotate_present || r.scale_present || r.filter_present ||
1047
+ r.transform_rotate || r.transform_rotate_x || r.transform_rotate_y ||
1048
+ composedTranslateX(r) || composedTranslateY(r) || composedTranslateZ(r) ||
1049
+ composedTranslateXPercent(r) || composedTranslateYPercent(r) ||
1050
+ r.transform_scale_x != 1000 || r.transform_scale_y != 1000 || r.transform_scale_z != 1000 || r.perspective ||
416
1051
  r.box_shadow_alpha || r.filter_blur_radius)
417
1052
  return false;
418
1053
  #else
@@ -428,25 +1063,25 @@ public:
428
1063
  // why `<p>… <span>score value</span> …</p>` may put "score" on one line and
429
1064
  // "value" on the next. Returns that inner run, or -1 when the wrapper has a box
430
1065
  // a reader could see, or holds anything other than one plain text run.
431
- int transparentInlineRun(const Node &wrapper) const
1066
+ static int transparentInlineRun(const Node &wrapper)
432
1067
  {
433
1068
  if (wrapper.type != NodeType::View) return -1;
434
1069
  if (!paintsNoBox(wrapper)) return -1;
435
- if (wrapper.style.padding[0] || wrapper.style.padding[1] || wrapper.style.padding[2] ||
436
- wrapper.style.padding[3])
1070
+ if (boxInset(wrapper.style, 0) || boxInset(wrapper.style, 1) || boxInset(wrapper.style, 2) ||
1071
+ boxInset(wrapper.style, 3))
437
1072
  return -1;
438
1073
  if (hasExplicitWidth(wrapper) || hasExplicitHeight(wrapper)) return -1;
439
1074
  if (wrapper.style.min_width > 0 || wrapper.style.min_height > 0) return -1;
440
1075
  if (wrapper.style.max_width != kUnset || wrapper.style.max_height != kUnset) return -1;
441
1076
  if (wrapper.style.overflow_x || wrapper.style.overflow_y) return -1;
442
1077
  if (wrapper.style.align_self >= 0 || wrapper.style.flex > 0 ||
443
- wrapper.style.flex_basis != kUnset)
1078
+ hasFlexBasis(wrapper))
444
1079
  return -1;
445
1080
  const Node *nodes = Tree::instance().nodes();
446
1081
  int run = -1;
447
1082
  for (int c = wrapper.first_child; c >= 0; c = nodes[c].next_sibling) {
448
1083
  const Node &child = nodes[c];
449
- if (isDisplayNone(child.style) || child.style.position == 1) continue;
1084
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position)) continue;
450
1085
  if (run >= 0) return -1; // more than one in-flow child
451
1086
  if (child.type != NodeType::Text) return -1;
452
1087
  if (child.style.margin[0] || child.style.margin[1] || child.style.margin[2] ||
@@ -463,27 +1098,27 @@ public:
463
1098
  // actually carries — the others are flush, so this is the taller, safe value).
464
1099
  int runLineDescent(const Node &n, int lineAdvance) const
465
1100
  {
466
- const int ascender = childFirstBaseline(n) - n.style.padding[0];
467
- const int descent = lineAdvance - ascender + n.style.padding[2] + n.style.margin[2];
1101
+ const int ascender = childBaseline(n) - boxInset(n.style, 0);
1102
+ const int descent = lineAdvance - ascender + boxInset(n.style, 2) + n.style.margin[2];
468
1103
  return descent < 0 ? 0 : descent;
469
1104
  }
470
1105
 
471
1106
  void placeLineItems(Node *nodes, int from, int to, int contentLeft, int contentW, int lineTop,
472
1107
  int lineCross, int baseline, int penStart, bool ownsLineStart)
473
1108
  {
1109
+ const int contentEnd = to > from && isLineBreak(nodes[children_[to - 1]]) ? to - 1 : to;
474
1110
  const bool soleRun =
475
- ownsLineStart && (to - from) == 1 && nodes[children_[from]].type == NodeType::Text;
476
- // Anything sharing this line box is placed on its shared baseline, and must
477
- // be DRAWN there — see RenderState::inline_baseline. A run that has the line
478
- // to itself keeps the renderer's ink centring.
479
- const bool sharesLine = (to - from) > 1 || !ownsLineStart;
1111
+ ownsLineStart && (contentEnd - from) == 1 && nodes[children_[from]].type == NodeType::Text;
1112
+ // Inline layout establishes the text baseline even for a sole run.
1113
+ // Painting must not replace it with an ink-centred baseline depending
1114
+ // on whether the source happens to contain leading whitespace.
480
1115
  int pen = penStart;
481
1116
  for (int k = from; k < to; k++) {
482
1117
  const int child = children_[k];
483
1118
  Node &cn = nodes[child];
484
1119
  const int marginL = cn.style.margin[3];
485
1120
  const int marginR = cn.style.margin[1];
486
- const int gap = pen > 0 ? node_.style.gap : 0;
1121
+ const int gap = pen > 0 ? mainGap_ : 0;
487
1122
 
488
1123
  if (cn.layout.inline_indent > 0) {
489
1124
  // A wrapped continuation keeps a full-width box at the block's left
@@ -494,14 +1129,14 @@ public:
494
1129
  }
495
1130
  pen += gap + marginL + cn.layout.width + marginR;
496
1131
 
497
- if (soleRun && !hasExplicitWidth(cn)) {
1132
+ if (soleRun && cn.type == NodeType::Text && !hasExplicitWidth(cn)) {
498
1133
  // text-align needs a box as wide as the line box to align inside.
499
1134
  const int full = contentW - marginL - marginR;
500
1135
  if (full > cn.layout.width) cn.layout.width = clampInt16(full);
501
1136
  }
502
1137
 
503
- int y = baseline - childFirstBaseline(cn);
504
- const int align = crossAlignFor(cn);
1138
+ int y = baseline - childBaseline(cn);
1139
+ const int align = usedAlignment(crossAlignFor(cn), lineCross - cn.layout.height - cn.style.margin[0] - cn.style.margin[2]);
505
1140
  if (align != 5) {
506
1141
  const int crossBefore = cn.style.margin[0];
507
1142
  const int crossAfter = cn.style.margin[2];
@@ -509,18 +1144,18 @@ public:
509
1144
  y = lineTop + crossBefore;
510
1145
  if (align == 1) y += (lineCross - crossTotal) / 2;
511
1146
  else if (align == 2) y += lineCross - crossTotal;
512
- else if (align == 0 && !hasExplicitHeight(cn)) {
1147
+ else if (align == 0 && !hasExplicitHeight(cn) && !isIntrinsicSizeExpression(cn.style.height_expression)) {
513
1148
  cn.layout.height = clampInt16(lineCross - crossBefore - crossAfter);
514
1149
  engine_.repositionChildren(child);
515
1150
  }
516
1151
  }
517
1152
  cn.layout.y = clampInt16(y);
518
- cn.render.inline_baseline = sharesLine ? 1 : 0;
1153
+ cn.render.inline_baseline = 1;
519
1154
  // An inline wrapper (<span>text</span>) contributes its CHILD's glyphs to
520
1155
  // this line box, so the flag has to reach the node that actually draws.
521
1156
  if (cn.type == NodeType::View) {
522
1157
  for (int c = cn.first_child; c >= 0; c = nodes[c].next_sibling)
523
- if (nodes[c].type == NodeType::Text) nodes[c].render.inline_baseline = sharesLine ? 1 : 0;
1158
+ if (nodes[c].type == NodeType::Text) nodes[c].render.inline_baseline = 1;
524
1159
  }
525
1160
  }
526
1161
  }
@@ -528,18 +1163,28 @@ public:
528
1163
  void expandCrossSizes(int lineCount, bool onlyIfDefinite)
529
1164
  {
530
1165
  const bool hasDefiniteCross = isRow_ ? hasExplicitHeight(node_) : hasExplicitWidth(node_);
531
- if (onlyIfDefinite && !hasDefiniteCross) return;
1166
+ const bool wrappingFlex = node_.style.display == kDisplayFlex && node_.style.flex_wrap;
1167
+ if (onlyIfDefinite && !hasDefiniteCross) {
1168
+ // A single flex line's intrinsic cross size still obeys the
1169
+ // container's min/max cross size (Flexbox 9.4, step 8).
1170
+ if (node_.style.display == kDisplayFlex && lineCount == 1 && !wrappingFlex) {
1171
+ const int insets = boxInsets(node_.style, !isRow_);
1172
+ lines_[0].crossSize = std::max(0, clampLayoutSize(node_, lines_[0].crossSize + insets, !isRow_) - insets);
1173
+ }
1174
+ return;
1175
+ }
532
1176
 
533
1177
  const int crossAvail = isRow_ ? padHeight_ : padWidth_;
534
- if (lineCount == 1) {
1178
+ if (lineCount == 1 && !wrappingFlex) {
535
1179
  lines_[0].crossSize = crossAvail;
536
- } else if (lineCount > 1) {
1180
+ } else if (lineCount > 0 && (!wrappingFlex || node_.style.align_content == 0)) {
537
1181
  int totalLineCross = 0;
538
1182
  for (int i = 0; i < lineCount; i++) totalLineCross += lines_[i].crossSize;
539
- const int extra = crossAvail - totalLineCross - (lineCount - 1) * node_.style.gap;
1183
+ const int extra = crossAvail - totalLineCross - (lineCount - 1) * crossGap_;
540
1184
  if (extra > 0) {
541
- const int perLine = extra / lineCount;
542
- for (int i = 0; i < lineCount; i++) lines_[i].crossSize += perLine;
1185
+ // Distribute the integer remainder cumulatively so no pixel is lost.
1186
+ for (int i = 0; i < lineCount; i++)
1187
+ lines_[i].crossSize += extra * (i + 1) / lineCount - extra * i / lineCount;
543
1188
  }
544
1189
  }
545
1190
  }
@@ -547,7 +1192,9 @@ public:
547
1192
  void positionLines(int lineCount)
548
1193
  {
549
1194
  Node *nodes = Tree::instance().nodes();
550
- int crossOffset = isRow_ ? node_.style.padding[0] : node_.style.padding[3];
1195
+ const bool wrappingFlex = node_.style.display == kDisplayFlex && node_.style.flex_wrap;
1196
+ const bool definiteCross = isRow_ ? hasExplicitHeight(node_) : hasExplicitWidth(node_);
1197
+ bool ratioCrossChanged = false;
551
1198
 
552
1199
  // Free main-axis space is measured against the node's FINAL padded main size
553
1200
  // (set by autosizeParent before this runs), NOT the available space it was
@@ -557,8 +1204,8 @@ public:
557
1204
  // box shrinks to fit. Reading layout.{width,height} also gives the correct
558
1205
  // free space when a flex item was GROWN past its content by its parent.
559
1206
  const int mainBox = isRow_
560
- ? (node_.layout.width - node_.style.padding[1] - node_.style.padding[3])
561
- : (node_.layout.height - node_.style.padding[0] - node_.style.padding[2]);
1207
+ ? (node_.layout.width - boxInset(node_.style, 1) - boxInset(node_.style, 3))
1208
+ : (node_.layout.height - boxInset(node_.style, 0) - boxInset(node_.style, 2));
562
1209
  const int mainContentBox = mainBox < 0 ? 0 : mainBox;
563
1210
 
564
1211
  for (int lineIndex = 0; lineIndex < lineCount; lineIndex++) {
@@ -601,13 +1248,67 @@ public:
601
1248
  if (mainSize == 0) engine_.repositionChildren(child);
602
1249
  }
603
1250
  }
604
- if (remaining < 0 && node_.style.justify_content != 1 && node_.style.justify_content != 2) remaining = 0;
1251
+ bool hasRatio = false;
1252
+ int measuredCross = 0;
1253
+ for (int i = 0; i < line.count; ++i) {
1254
+ const Node &child = nodes[children_[line.start + i]];
1255
+ hasRatio |= preferredRatio(child) > 0;
1256
+ measuredCross = std::max(measuredCross, isRow_ ? child.layout.height + child.style.margin[0] + child.style.margin[2]
1257
+ : child.layout.width + child.style.margin[1] + child.style.margin[3]);
1258
+ }
1259
+ if (node_.style.display == kDisplayFlex && hasRatio && !definiteCross) {
1260
+ line.crossSize = std::max(line.strutSize, baselineCrossSize(line.start, line.count, measuredCross));
1261
+ ratioCrossChanged = true;
1262
+ }
1263
+ }
1264
+ // Resolve all flexed sizes before cross-axis placement: a changed ratio
1265
+ // height affects following lines and reversed line order as well.
1266
+ if (ratioCrossChanged) {
1267
+ expandCrossSizes(lineCount, true);
1268
+ int16_t &cross = isRow_ ? node_.layout.height : node_.layout.width;
1269
+ cross = clampInt16(clampLayoutSize(node_, totalCrossSize(lineCount) + boxInsets(node_.style, !isRow_), !isRow_));
1270
+ }
1271
+ int crossOffset = boxInset(node_.style, isRow_ ? 0 : 3);
1272
+ const int crossBox = (isRow_ ? node_.layout.height : node_.layout.width) - boxInsets(node_.style, !isRow_);
1273
+ const int crossFree = crossBox - totalCrossSize(lineCount);
1274
+ for (int lineIndex = 0; lineIndex < lineCount; ++lineIndex) {
1275
+ FlexLine &line = lines_[lineIndex];
1276
+ int occupied = std::max(0, line.count - 1) * mainGap_;
1277
+ for (int i = 0; i < line.count; ++i) {
1278
+ const Node &child = nodes[children_[line.start + i]];
1279
+ occupied += isRow_ ? child.layout.width + child.style.margin[1] + child.style.margin[3]
1280
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
1281
+ }
1282
+ int remaining = mainContentBox - occupied;
1283
+ const int mainAlignment = usedAlignment(node_.style.justify_content, remaining, node_.style.flex_direction_explicit && node_.style.flex_direction >= 2);
1284
+ if (remaining < 0 && mainAlignment != 1 && mainAlignment != 2) remaining = 0;
1285
+
1286
+ int mainOffset = isRow_ ? boxInset(node_.style, 3) : boxInset(node_.style, 0);
1287
+ int autoCount = 0;
1288
+ for (int i = 0; i < line.count; ++i) {
1289
+ const auto mask = nodes[children_[line.start + i]].style.margin_auto;
1290
+ autoCount += isRow_ ? !!(mask & 2) + !!(mask & 8) : !!(mask & 1) + !!(mask & 4);
1291
+ }
1292
+ const int autoSpace = autoCount && remaining > 0 ? remaining : 0;
1293
+ if (!isDistributedAlignment(node_.style.justify_content))
1294
+ applyJustifyContent(autoSpace ? 0 : remaining, &mainOffset);
1295
+ const int lineOffset = wrappingFlex ? crossAlignmentOffset(lineIndex, lineCount, crossFree) : 0;
1296
+ positionLineChildren(line, nodes, mainOffset, crossOffset + lineOffset, autoSpace, autoCount, autoSpace ? 0 : remaining);
1297
+ crossOffset += line.crossSize + crossGap_;
1298
+ }
1299
+ }
605
1300
 
606
- int mainOffset = isRow_ ? node_.style.padding[3] : node_.style.padding[0];
607
- int gapSpace = 0;
608
- applyJustifyContent(line, remaining, &mainOffset, &gapSpace);
609
- positionLineChildren(line, nodes, mainOffset, crossOffset, gapSpace);
610
- crossOffset += line.crossSize + node_.style.gap;
1301
+ int crossAlignmentOffset(int index, int count, int free) const
1302
+ {
1303
+ // A wrapping container is multi-line even when only one line is occupied.
1304
+ // Distributed alignments fall back to start/center for overflowing lines.
1305
+ switch (usedAlignment(node_.style.align_content, free, (node_.style.flex_wrap & 3) == 2)) {
1306
+ case 1: return free / 2;
1307
+ case 2: return free;
1308
+ case 3:
1309
+ case 4:
1310
+ case kAlignSpaceEvenly: return distributedAlignmentOffset(node_.style.align_content, free, index, count);
1311
+ default: return 0;
611
1312
  }
612
1313
  }
613
1314
 
@@ -622,47 +1323,134 @@ public:
622
1323
  // fit content. Guarded on a positive assigned size so an unsized scroll
623
1324
  // container still autosizes as before.
624
1325
  const bool keepScrollHeight = scrollsOverflowY(node_.style) && node_.layout.height > 0;
625
- const bool keepScrollWidth = scrollsOverflowX(node_.style) && node_.layout.width > 0;
1326
+ const bool keepScrollWidth = !intrinsicWidthConstraint(node_) && scrollsOverflowX(node_.style) && node_.layout.width > 0;
626
1327
 
627
1328
  if (!hasExplicitHeight(node_) && !keepScrollHeight) {
628
- const int height = (isRow_ ? totalCrossSize(lineCount) : maxMainSize(lineCount)) + node_.style.padding[0] + node_.style.padding[2];
629
- node_.layout.height = engine_.clampSize(height, node_.style.min_height, node_.style.max_height);
1329
+ const int height = (isRow_ ? totalCrossSize(lineCount) : maxMainSize(lineCount)) + boxInset(node_.style, 0) + boxInset(node_.style, 2);
1330
+ node_.layout.height = clampLayoutSize(node_, height, false);
630
1331
  }
631
1332
 
632
1333
  if (!hasExplicitWidth(node_) && !keepScrollWidth) {
633
- const int width = (isRow_ ? maxMainSize(lineCount) : totalCrossSize(lineCount)) + node_.style.padding[1] + node_.style.padding[3];
634
- node_.layout.width = engine_.clampSize(width, node_.style.min_width, node_.style.max_width);
1334
+ const int width = (isRow_ ? maxMainSize(lineCount) : totalCrossSize(lineCount)) + boxInset(node_.style, 1) + boxInset(node_.style, 3);
1335
+ node_.layout.width = clampLayoutSize(node_, width, true);
635
1336
  }
636
1337
  }
637
1338
 
638
1339
  private:
639
- void applyFlexBasis(int child)
1340
+ int flexWrapLimit() const
640
1341
  {
641
- Node &childNode = Tree::instance().nodes()[child];
642
- // A definite flex-basis (e.g. `flex: 0 0 26px`) sets the item's main-axis
643
- // size directly, overriding the size measured from content/fill. flex-grow
644
- // and flex-shrink then resize from this basis in positionLines, and a
645
- // flex:0 0 item stays exactly at its basis. This is what makes the weather
646
- // forecast's `.hour`/`.day` cards 26/40px wide instead of stretching to fill
647
- // the row. An explicit width/height still wins.
648
- if (childNode.style.flex_basis != kUnset) {
649
- if (isRow_) {
650
- if (hasExplicitWidth(childNode)) return;
651
- const int basis = clampFlexMainSize(childNode, childNode.style.flex_basis);
652
- if (childNode.layout.width != basis) {
653
- childNode.layout.width = basis;
654
- engine_.repositionChildren(child);
655
- }
656
- } else {
657
- if (hasExplicitHeight(childNode)) return;
658
- const int basis = clampFlexMainSize(childNode, childNode.style.flex_basis);
659
- if (childNode.layout.height != basis) {
660
- childNode.layout.height = basis;
661
- engine_.repositionChildren(child);
662
- }
1342
+ const bool blockAxis = isRow_ == (writingMode(node_) != 0);
1343
+ if (!blockAxis || assignedSize_ || (isRow_ ? hasExplicitWidth(node_) : hasExplicitHeight(node_))) return mainAvail_;
1344
+ // An automatic block main size grows to fit its items. min-height is
1345
+ // a floor, not a wrapping constraint; only a maximum bounds packing.
1346
+ if ((isRow_ ? node_.style.max_width : node_.style.max_height) == kUnset) return INT_MAX;
1347
+ return std::max(0, clampLayoutSize(node_, INT16_MAX, isRow_) - boxInsets(node_.style, isRow_));
1348
+ }
1349
+
1350
+ int buildCollapsedLines(const std::vector<int> &struts)
1351
+ {
1352
+ Node *nodes = Tree::instance().nodes();
1353
+ std::vector<int> balancedEnds;
1354
+ if (node_.style.flex_wrap & 4) {
1355
+ std::vector<int> sizes;
1356
+ int total = 0;
1357
+ for (int i = 0; i < childCount_; ++i) {
1358
+ if (struts[i] >= 0) continue;
1359
+ const Node &child = nodes[children_[i]];
1360
+ const int size = isRow_ ? child.layout.width + child.style.margin[1] + child.style.margin[3]
1361
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
1362
+ total += std::max(0, size) + (sizes.empty() ? 0 : mainGap_);
1363
+ sizes.push_back(size);
663
1364
  }
664
- return;
1365
+ const int available = std::min(total, flexWrapLimit());
1366
+ balancedEnds = balancedFlexLineEnds(sizes, available, mainGap_, rstyle(node_.style).flex_line_count);
1367
+ }
1368
+ int lineCount = 0, start = 0, written = 0, main = 0, cross = 0, strut = 0;
1369
+ auto finish = [&] {
1370
+ appendLine(lineCount, start, written - start, main, std::max(cross, strut));
1371
+ lines_[lineCount - 1].strutSize = strut;
1372
+ start = written; main = cross = strut = 0;
1373
+ };
1374
+ for (int i = 0; i < childCount_; ++i) {
1375
+ const int id = children_[i];
1376
+ Node &child = nodes[id];
1377
+ if (struts[i] >= 0) {
1378
+ strut = std::max(strut, struts[i]);
1379
+ // The strut belongs to the line, not to a rendered child box.
1380
+ child.layout.x = child.layout.y = child.layout.width = child.layout.height = 0;
1381
+ continue;
1382
+ }
1383
+ const int childMain = isRow_ ? child.layout.width + child.style.margin[1] + child.style.margin[3]
1384
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
1385
+ const int childCross = isRow_ ? child.layout.height + child.style.margin[0] + child.style.margin[2]
1386
+ : child.layout.width + child.style.margin[1] + child.style.margin[3];
1387
+ const bool wrap = !balancedEnds.empty() ? written == balancedEnds[lineCount]
1388
+ : node_.style.flex_wrap && main + mainGap_ + childMain > flexWrapLimit();
1389
+ if (written > start && wrap) finish();
1390
+ main += childMain + (written > start ? mainGap_ : 0);
1391
+ cross = std::max(cross, childCross);
1392
+ children_[written++] = id;
665
1393
  }
1394
+ finish();
1395
+ childCount_ = written;
1396
+ return lineCount;
1397
+ }
1398
+
1399
+ int buildBalancedLines()
1400
+ {
1401
+ Node *nodes = Tree::instance().nodes();
1402
+ std::vector<int> sizes(childCount_);
1403
+ int total = 0;
1404
+ for (int i = 0; i < childCount_; ++i) {
1405
+ const Node &child = nodes[children_[i]];
1406
+ sizes[i] = isRow_ ? child.layout.width + child.style.margin[1] + child.style.margin[3]
1407
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
1408
+ total += std::max(0, sizes[i]) + (i ? mainGap_ : 0);
1409
+ }
1410
+ // An unconstrained automatic block main size is content-based; the
1411
+ // viewport height must not manufacture additional columns.
1412
+ const int available = std::min(total, flexWrapLimit());
1413
+ const auto ends = balancedFlexLineEnds(sizes, available, mainGap_, rstyle(node_.style).flex_line_count);
1414
+ int start = 0, count = 0;
1415
+ for (const int end : ends) {
1416
+ int main = 0, cross = 0;
1417
+ for (int i = start; i < end; ++i) {
1418
+ const Node &child = nodes[children_[i]];
1419
+ main += sizes[i] + (i > start ? mainGap_ : 0);
1420
+ cross = std::max(cross, isRow_ ? child.layout.height + child.style.margin[0] + child.style.margin[2]
1421
+ : child.layout.width + child.style.margin[1] + child.style.margin[3]);
1422
+ }
1423
+ appendLine(count, start, end - start, main, cross);
1424
+ start = end;
1425
+ }
1426
+ return count;
1427
+ }
1428
+
1429
+ int flexPercentageBasis() const
1430
+ {
1431
+ if (isRow_ ? hasExplicitWidth(node_) : hasExplicitHeight(node_)) return mainAvail_;
1432
+ // A normal block's automatic inline size fills its containing block.
1433
+ // Intrinsic measurements and automatic block sizes remain indefinite.
1434
+ if (isRow_ && !intrinsicWidthConstraint(node_) && !node_.style.float_side &&
1435
+ !isIntrinsicSizeExpression(node_.style.width_expression) &&
1436
+ (node_.parent < 0 || Tree::instance().nodes()[node_.parent].style.display != kDisplayFlex)) return mainAvail_;
1437
+ if (assignedSize_ && node_.parent >= 0) {
1438
+ const Node &parent = Tree::instance().nodes()[node_.parent];
1439
+ if (parent.style.display == kDisplayFlex) {
1440
+ const bool parentRow = flexRowDirection(parent.style) != (writingMode(parent) != 0);
1441
+ if (isRow_ != parentRow ? definiteFlexCrossSize(parent, node_, parentRow)
1442
+ : (isRow_ ? hasExplicitWidth(parent) : hasExplicitHeight(parent))) return mainAvail_;
1443
+ }
1444
+ }
1445
+ return -1;
1446
+ }
1447
+
1448
+ void applyFlexBasis(int child)
1449
+ {
1450
+ Node &childNode = Tree::instance().nodes()[child];
1451
+ // Authored bases were measured on the physical main axis above. Preserve
1452
+ // that result, including content sizing for an indefinite percentage.
1453
+ if (hasFlexBasis(childNode)) return;
666
1454
  if (childNode.style.flex <= 0) return;
667
1455
  if (isRow_) {
668
1456
  if (hasExplicitWidth(childNode)) return;
@@ -681,18 +1469,39 @@ private:
681
1469
  // (free space exactly 0) is compensated in positionLines.
682
1470
  }
683
1471
 
1472
+ int baselineCrossSize(int start, int count, int crossSize) const
1473
+ {
1474
+ if (isRow_ && node_.style.display == kDisplayFlex) {
1475
+ for (int alignment : {5, kAlignLastBaseline}) {
1476
+ int ascent = 0, descent = 0;
1477
+ for (int i = start; i < start + count; ++i) {
1478
+ const Node &child = Tree::instance().nodes()[children_[i]];
1479
+ if (crossAlignFor(child) != alignment || (child.style.margin_auto & 5)) continue;
1480
+ const int baseline = childBaseline(child, alignment == kAlignLastBaseline);
1481
+ ascent = std::max(ascent, child.style.margin[0] + baseline);
1482
+ descent = std::max(descent, child.style.margin[2] + child.layout.height - baseline);
1483
+ }
1484
+ crossSize = std::max(crossSize, ascent + descent);
1485
+ }
1486
+ }
1487
+ return crossSize;
1488
+ }
1489
+
684
1490
  void appendLine(int &lineCount, int start, int count, int mainSize, int crossSize)
685
1491
  {
686
- if (lineCount >= kMaxFlexLines) return;
1492
+ if (lineCount >= (extraLines_.empty() ? kMaxFlexLines : static_cast<int>(extraLines_.size()))) return;
1493
+ crossSize = baselineCrossSize(start, count, crossSize);
687
1494
  lines_[lineCount].start = start;
688
1495
  lines_[lineCount].count = count;
689
1496
  lines_[lineCount].mainSize = mainSize;
690
1497
  lines_[lineCount].crossSize = crossSize;
1498
+ lines_[lineCount].strutSize = 0;
691
1499
  lineCount++;
692
1500
  }
693
1501
 
694
1502
  int totalFlexGrowForLine(const FlexLine &line, Node *nodes) const
695
1503
  {
1504
+ if (node_.style.display != kDisplayFlex) return 0;
696
1505
  int totalFlex = 0;
697
1506
  for (int i = 0; i < line.count; i++) {
698
1507
  totalFlex += nodes[children_[line.start + i]].style.flex;
@@ -713,6 +1522,7 @@ private:
713
1522
  // deficit redistributes to shrinkable siblings or becomes overflow.
714
1523
  bool childMainSizeIsShrinkable(const Node &childNode) const
715
1524
  {
1525
+ if (node_.style.display != kDisplayFlex) return false;
716
1526
  if (childNode.style.flex_shrink <= 0) return false;
717
1527
  if (!isRow_ && childNode.type == NodeType::Text) return false;
718
1528
  return true;
@@ -792,14 +1602,13 @@ private:
792
1602
  int automaticMinimumMainSize(const Node &childNode) const
793
1603
  {
794
1604
  const int explicitMin = isRow_ ? childNode.style.min_width : childNode.style.min_height;
795
- if (explicitMin > 0) return 0;
796
- if (isRow_ ? childNode.style.overflow_x : childNode.style.overflow_y) return 0;
797
- if (childNode.first_child < 0) return 0;
1605
+ if (explicitMin != kUnset) return 0;
1606
+ if (isScrollableOverflow(isRow_ ? overflowX(childNode.style) : overflowY(childNode.style))) return 0;
798
1607
  const Node *nodes = Tree::instance().nodes();
799
1608
  int extent = 0;
800
1609
  for (int c = childNode.first_child; c >= 0; c = nodes[c].next_sibling) {
801
1610
  const Node &grand = nodes[c];
802
- if (isDisplayNone(grand.style) || grand.style.position == 1) continue;
1611
+ if (isDisplayNone(grand.style) || isOutOfFlowPosition(grand.style.position)) continue;
803
1612
  // layout.{x,y} are still parent-relative here: resolveAbsoluteCoords runs
804
1613
  // after the whole layout pass.
805
1614
  const int end = isRow_
@@ -807,8 +1616,19 @@ private:
807
1616
  : grand.layout.y + grand.layout.height + grand.style.margin[2];
808
1617
  if (end > extent) extent = end;
809
1618
  }
1619
+ if (extent > 0) extent += isRow_ ? boxInset(childNode.style, 1) : boxInset(childNode.style, 2);
1620
+ if (preferredRatio(childNode) > 0 &&
1621
+ ((isRow_ ? hasExplicitHeight(childNode) : hasExplicitWidth(childNode)) || definiteFlexCrossSize(node_, childNode, isRow_))) {
1622
+ const int transferred = ratioTransferredSize(childNode, isRow_ ? childNode.layout.height : childNode.layout.width, isRow_);
1623
+ extent = childNode.type == NodeType::Image ? std::min(extent, transferred) : std::max(extent, transferred);
1624
+ }
810
1625
  if (extent <= 0) return 0;
811
- extent += isRow_ ? childNode.style.padding[1] : childNode.style.padding[2];
1626
+ const int max = isRow_ ? childNode.style.max_width : childNode.style.max_height;
1627
+ if (max != kUnset) extent = std::min(extent, contentSizeToBorderSize(childNode.style, max, isRow_));
1628
+ if (isRow_ ? hasExplicitWidth(childNode) : hasExplicitHeight(childNode)) {
1629
+ const int specified = isRow_ ? resolvedStyleWidth(childNode, mainAvail_) : resolvedStyleHeight(childNode, mainAvail_);
1630
+ extent = std::min(extent, contentSizeToBorderSize(childNode.style, specified, isRow_));
1631
+ }
812
1632
  return extent;
813
1633
  }
814
1634
 
@@ -828,21 +1648,23 @@ private:
828
1648
  if (after == before) return 0;
829
1649
  if (isRow_) childNode.layout.width = after;
830
1650
  else childNode.layout.height = after;
1651
+ if (preferredRatio(childNode) > 0 && !(isRow_ ? hasExplicitHeight(childNode) : hasExplicitWidth(childNode)) &&
1652
+ !definiteFlexCrossSize(node_, childNode, isRow_)) {
1653
+ int16_t &cross = isRow_ ? childNode.layout.height : childNode.layout.width;
1654
+ cross = clampInt16(clampLayoutSize(childNode, ratioTransferredSize(childNode, after, !isRow_), !isRow_));
1655
+ }
831
1656
  engine_.repositionChildren(child);
832
1657
  return delta > 0 ? after - before : before - after;
833
1658
  }
834
1659
 
835
1660
  int clampFlexMainSize(const Node &childNode, int size) const
836
1661
  {
837
- const int minSize = isRow_ ? childNode.style.min_width : childNode.style.min_height;
838
- const int maxSize = isRow_ ? childNode.style.max_width : childNode.style.max_height;
839
- const int clamped = engine_.clampSize(size, minSize, maxSize);
840
- return clamped < 0 ? 0 : clamped;
1662
+ return clampBorderSize(engine_, childNode, size, isRow_);
841
1663
  }
842
1664
 
843
- void applyJustifyContent(const FlexLine &line, int remaining, int *mainOffset, int *gapSpace) const
1665
+ void applyJustifyContent(int remaining, int *mainOffset) const
844
1666
  {
845
- switch (node_.style.justify_content) {
1667
+ switch (usedAlignment(node_.style.justify_content, remaining, node_.style.flex_direction_explicit && node_.style.flex_direction >= 2)) {
846
1668
  case 0:
847
1669
  break;
848
1670
  case 1:
@@ -851,31 +1673,45 @@ private:
851
1673
  case 2:
852
1674
  *mainOffset += remaining;
853
1675
  break;
854
- case 3:
855
- if (line.count > 1) *gapSpace = remaining / (line.count - 1);
856
- break;
857
- case 4:
858
- if (line.count > 0) {
859
- const int space = remaining / line.count;
860
- *mainOffset += space / 2;
861
- *gapSpace = space;
862
- }
863
- break;
864
1676
  }
865
1677
  }
866
1678
 
867
- void positionLineChildren(const FlexLine &line, Node *nodes, int mainOffset, int crossOffset, int gapSpace)
1679
+ void positionLineChildren(const FlexLine &line, Node *nodes, int mainOffset, int crossOffset, int autoSpace = 0, int autoCount = 0, int distributedFree = 0)
868
1680
  {
1681
+ const bool flex = node_.style.display == kDisplayFlex;
1682
+ const bool logicalRow = flexRowDirection(node_.style);
1683
+ const int mode = writingMode(node_);
1684
+ const bool blockReversed = mode == 2 || mode == 3;
1685
+ const bool inlineReversed = rightToLeft(node_) != (mode == 4);
1686
+ const bool reverseMain = flex && ((node_.style.flex_direction_explicit && node_.style.flex_direction >= 2) != (logicalRow ? inlineReversed : blockReversed));
1687
+ const bool reverseCross = flex && (((node_.style.flex_wrap & 3) == 2) != (logicalRow ? blockReversed : inlineReversed));
1688
+ const int mainBefore = isRow_ ? (reverseMain ? 1 : 3) : (reverseMain ? 2 : 0);
1689
+ const int mainAfter = (mainBefore + 2) % 4;
1690
+ const int crossBefore = isRow_ ? (reverseCross ? 2 : 0) : (reverseCross ? 1 : 3);
1691
+ const int crossAfter = (crossBefore + 2) % 4;
1692
+ int autoUsed = 0;
1693
+ auto autoMargin = [&](const Node &child, int side) {
1694
+ if (!(child.style.margin_auto & (1 << side)) || !autoCount) return 0;
1695
+ const int before = autoSpace * autoUsed / autoCount;
1696
+ return autoSpace * ++autoUsed / autoCount - before;
1697
+ };
869
1698
  // First baselines of this line's baseline-aligned children (rows only):
870
1699
  // every such child's baseline lands on the line's max baseline, matching
871
1700
  // CSS `align-items: baseline` (a 12px range label shares the 14px
872
1701
  // condition's baseline instead of top-aligning).
873
1702
  int lineMaxBaseline = 0;
1703
+ int lineMaxLastDescent = 0, lineMaxLastAscent = 0;
874
1704
  if (isRow_) {
875
1705
  for (int i = 0; i < line.count; i++) {
876
1706
  Node &probe = nodes[children_[line.start + i]];
1707
+ if (probe.style.margin_auto & 5) continue;
1708
+ if (crossAlignFor(probe) == kAlignLastBaseline) {
1709
+ const int baseline = childBaseline(probe, true);
1710
+ lineMaxLastDescent = std::max(lineMaxLastDescent, probe.style.margin[2] + probe.layout.height - baseline);
1711
+ lineMaxLastAscent = std::max(lineMaxLastAscent, probe.style.margin[0] + baseline);
1712
+ }
877
1713
  if (crossAlignFor(probe) != 5) continue;
878
- const int baseline = probe.style.margin[0] + childFirstBaseline(probe);
1714
+ const int baseline = probe.style.margin[0] + childBaseline(probe);
879
1715
  if (baseline > lineMaxBaseline) lineMaxBaseline = baseline;
880
1716
  }
881
1717
  }
@@ -884,27 +1720,44 @@ private:
884
1720
  const int child = children_[line.start + i];
885
1721
  Node &childNode = nodes[child];
886
1722
 
887
- const int mainMarginBefore = isRow_ ? childNode.style.margin[3] : childNode.style.margin[0];
888
- const int mainMarginAfter = isRow_ ? childNode.style.margin[1] : childNode.style.margin[2];
889
- const int crossMarginBefore = isRow_ ? childNode.style.margin[0] : childNode.style.margin[3];
890
- const int crossMarginAfter = isRow_ ? childNode.style.margin[2] : childNode.style.margin[1];
1723
+ const int mainMarginBefore = childNode.style.margin[mainBefore] + autoMargin(childNode, mainBefore);
1724
+ const int mainMarginAfter = childNode.style.margin[mainAfter] + autoMargin(childNode, mainAfter);
1725
+ const int crossMarginBefore = childNode.style.margin[crossBefore];
1726
+ const int crossMarginAfter = childNode.style.margin[crossAfter];
891
1727
  const int crossSize = isRow_ ? childNode.layout.height : childNode.layout.width;
892
1728
  const int crossTotal = crossSize + crossMarginBefore + crossMarginAfter;
893
1729
 
894
1730
  mainOffset += mainMarginBefore;
895
1731
  int crossPosition = crossOffset + crossMarginBefore;
896
- positionCrossAxisChild(child, childNode, line.crossSize, crossMarginBefore, crossMarginAfter, crossTotal, &crossPosition, lineMaxBaseline);
1732
+ const bool crossAutoBefore = childNode.style.margin_auto & (1 << crossBefore);
1733
+ const bool crossAutoAfter = childNode.style.margin_auto & (1 << crossAfter);
1734
+ if (crossAutoBefore || crossAutoAfter) {
1735
+ const int free = std::max(0, line.crossSize - crossTotal);
1736
+ if (crossAutoBefore) crossPosition += crossAutoAfter ? free / 2 : free;
1737
+ } else {
1738
+ positionCrossAxisChild(child, childNode, line.crossSize, crossMarginBefore, crossMarginAfter, crossTotal, &crossPosition, lineMaxBaseline, std::max(lineMaxLastAscent, line.crossSize - lineMaxLastDescent));
1739
+ // Baselines are distances from physical top. Reversing the line
1740
+ // order must not mirror each item's baseline inside that line.
1741
+ const int alignment = crossAlignFor(childNode) & 15;
1742
+ if (isRow_ && reverseCross && (alignment == 5 || alignment == kAlignLastBaseline))
1743
+ crossPosition = crossOffset + line.crossSize - (crossPosition - crossOffset) - crossSize;
1744
+ }
897
1745
 
898
1746
  if (isRow_) {
899
- childNode.layout.x = mainOffset;
1747
+ childNode.layout.x = mainOffset + distributedAlignmentOffset(node_.style.justify_content, distributedFree, i, line.count);
900
1748
  childNode.layout.y = crossPosition;
901
1749
  } else {
902
1750
  childNode.layout.x = crossPosition;
903
- childNode.layout.y = mainOffset;
1751
+ childNode.layout.y = mainOffset + distributedAlignmentOffset(node_.style.justify_content, distributedFree, i, line.count);
904
1752
  }
905
1753
 
1754
+ const bool reverseX = isRow_ ? reverseMain : reverseCross;
1755
+ const bool reverseY = isRow_ ? reverseCross : reverseMain;
1756
+ if (reverseX) childNode.layout.x = node_.layout.width - childNode.layout.x - childNode.layout.width + boxInset(node_.style, 3) - boxInset(node_.style, 1);
1757
+ if (reverseY) childNode.layout.y = node_.layout.height - childNode.layout.y - childNode.layout.height + boxInset(node_.style, 0) - boxInset(node_.style, 2);
1758
+
906
1759
  const int mainSize = isRow_ ? childNode.layout.width : childNode.layout.height;
907
- mainOffset += mainSize + mainMarginAfter + node_.style.gap + gapSpace;
1760
+ mainOffset += mainSize + mainMarginAfter + mainGap_;
908
1761
  // Flex items own their boxes; nothing here shares a line box.
909
1762
  childNode.render.inline_baseline = 0;
910
1763
  }
@@ -921,17 +1774,22 @@ private:
921
1774
  return inlineRow_ ? 5 : node_.style.align_items;
922
1775
  }
923
1776
 
924
- void positionCrossAxisChild(int child, Node &childNode, int lineCrossSize, int crossMarginBefore, int crossMarginAfter, int crossTotal, int *crossPosition, int lineMaxBaseline)
1777
+ void positionCrossAxisChild(int child, Node &childNode, int lineCrossSize, int crossMarginBefore, int crossMarginAfter, int crossTotal, int *crossPosition, int lineMaxBaseline, int lineLastBaseline)
925
1778
  {
926
- const int align = crossAlignFor(childNode);
1779
+ const int alignment = crossAlignFor(childNode);
1780
+ int align = physicalSelfAlignment(node_, childNode, alignment, lineCrossSize - crossTotal, !isRow_);
1781
+ if (align >= 0) {
1782
+ const bool reversed = gridAxisReversed(node_, !isRow_) != ((node_.style.flex_wrap & 3) == 2);
1783
+ if (reversed) align = align == 2 ? 6 : 2;
1784
+ } else align = usedAlignment(alignment, lineCrossSize - crossTotal, (node_.style.flex_wrap & 3) == 2);
927
1785
  switch (align) {
928
1786
  case 0:
929
1787
  if (isRow_) {
930
- if (!hasExplicitHeight(childNode)) {
1788
+ if (!hasExplicitHeight(childNode) && !isIntrinsicSizeExpression(childNode.style.height_expression)) {
931
1789
  childNode.layout.height = lineCrossSize - crossMarginBefore - crossMarginAfter;
932
1790
  engine_.repositionChildren(child);
933
1791
  }
934
- } else if (!hasExplicitWidth(childNode)) {
1792
+ } else if (!hasExplicitWidth(childNode) && !isIntrinsicSizeExpression(childNode.style.width_expression)) {
935
1793
  childNode.layout.width = lineCrossSize - crossMarginBefore - crossMarginAfter;
936
1794
  engine_.repositionChildren(child);
937
1795
  }
@@ -942,45 +1800,33 @@ private:
942
1800
  case 2:
943
1801
  *crossPosition += lineCrossSize - crossTotal;
944
1802
  break;
1803
+ case kAlignLastBaseline:
1804
+ if (isRow_) {
1805
+ *crossPosition += lineLastBaseline - childBaseline(childNode, true) - crossMarginBefore;
1806
+ } else if (lineCrossSize >= crossTotal) {
1807
+ *crossPosition += lineCrossSize - crossTotal;
1808
+ }
1809
+ break;
945
1810
  case 5:
946
1811
  // align-items/align-self: baseline (rows). Columns fall back to start,
947
1812
  // matching CSS, where baseline alignment only applies across an inline axis.
948
1813
  if (isRow_) {
949
- const int shift = lineMaxBaseline - (crossMarginBefore + childFirstBaseline(childNode));
1814
+ const int shift = lineMaxBaseline - (crossMarginBefore + childBaseline(childNode));
950
1815
  if (shift > 0) *crossPosition += shift;
951
1816
  }
952
1817
  break;
953
1818
  }
954
1819
  }
955
1820
 
956
- // First-baseline of a flex child, measured from its border-box top. Text
1821
+ // First/last baseline of a flex child, measured from its border-box top. Text
957
1822
  // leaves use the resolved atlas font's ascender — the glyph rasterizer
958
1823
  // places runs at `top + ascender - bearingY`, so this matches the drawn
959
- // pixels exactly. Anything without measurable text synthesizes its baseline
960
- // from the bottom margin edge, as CSS does for replaced/empty boxes.
961
- int childFirstBaseline(const Node &childNode) const
962
- {
963
- if (childNode.type == NodeType::Text && childNode.style.font_id >= 0) {
964
- const int fontSize = childNode.style.font_size > 0 ? childNode.style.font_size : 16;
965
- const gea::framework::graphics::RasterizedFont font =
966
- gea::framework::graphics::FontRegistry::rasterizedFamily(childNode.style.font_id, fontSize);
967
- if (font.valid()) {
968
- // CSS half-leading: when line-height exceeds the font's own line box the
969
- // extra room is split above and below it, so the glyphs — and the
970
- // baseline with them — sit that much lower. TextDrawer applies exactly
971
- // this offset when it paints (`lineBoxOffset`), and a baseline that
972
- // ignores it is wrong by half the difference. That went unnoticed while
973
- // every run occupied its own line; once runs of different FONTS share
974
- // one, each carries a different font line height and they visibly
975
- // stagger (typography's ", a" riding above the Inter and Oswald spans
976
- // around it).
977
- const int lineAdvance =
978
- childNode.style.line_height > 0 ? childNode.style.line_height : font.lineHeight();
979
- const int halfLeading =
980
- childNode.style.line_height > 0 ? (lineAdvance - font.lineHeight()) / 2 : 0;
981
- return childNode.style.padding[0] + halfLeading + font.ascender();
982
- }
983
- }
1824
+ // pixels exactly. Flex items synthesize missing baselines from border edges;
1825
+ // inline boxes use margin edges.
1826
+ int childBaseline(const Node &childNode, bool last = false) const
1827
+ {
1828
+ if ((childNode.type == NodeType::Text || isLineBreak(childNode)) && childNode.style.font_id >= 0)
1829
+ return TextRenderer::baselineOffset(childNode, last);
984
1830
  // An inline wrapper (a <span> around text) carries no text of its own, so
985
1831
  // CSS takes the baseline of its FIRST in-flow line box. Its children were
986
1832
  // already positioned by measureChildren, and layout.y is still parent-
@@ -990,19 +1836,19 @@ private:
990
1836
  // dropped below every bare text run beside it.
991
1837
  if (childNode.type == NodeType::View && childNode.first_child >= 0) {
992
1838
  const Node *nodes = Tree::instance().nodes();
993
- for (int c = childNode.first_child; c >= 0; c = nodes[c].next_sibling) {
1839
+ for (int c = last ? childNode.last_child : childNode.first_child; c >= 0; c = last ? nodes[c].prev_sibling : nodes[c].next_sibling) {
994
1840
  const Node &inner = nodes[c];
995
- if (isDisplayNone(inner.style) || inner.style.position == 1) continue;
996
- return inner.layout.y + childFirstBaseline(inner);
1841
+ if (isDisplayNone(inner.style) || isOutOfFlowPosition(inner.style.position)) continue;
1842
+ return inner.layout.y + childBaseline(inner, last);
997
1843
  }
998
1844
  }
999
- return childNode.layout.height + childNode.style.margin[2];
1845
+ return childNode.layout.height + (inlineRow_ ? childNode.style.margin[2] : 0);
1000
1846
  }
1001
1847
 
1002
1848
  int totalCrossSize(int lineCount) const
1003
1849
  {
1004
1850
  int total = 0;
1005
- for (int i = 0; i < lineCount; i++) total += lines_[i].crossSize + (i > 0 ? node_.style.gap : 0);
1851
+ for (int i = 0; i < lineCount; i++) total += lines_[i].crossSize + (i > 0 ? crossGap_ : 0);
1006
1852
  return total;
1007
1853
  }
1008
1854
 
@@ -1023,10 +1869,14 @@ private:
1023
1869
  // True when this row is a synthesized INLINE FORMATTING context (a block
1024
1870
  // whose in-flow children are all inline-level), not a declared flex row.
1025
1871
  bool inlineRow_ = false;
1872
+ bool assignedSize_ = false;
1026
1873
  int mainAvail_ = 0;
1027
1874
  int padWidth_ = 0;
1028
1875
  int padHeight_ = 0;
1029
1876
  FlexLine *lines_ = nullptr;
1877
+ std::vector<FlexLine> extraLines_;
1878
+ int mainGap_ = 0;
1879
+ int crossGap_ = 0;
1030
1880
  };
1031
1881
 
1032
1882
  // CSS inline-level classification. Browsers flow inline-level boxes (text,
@@ -1037,13 +1887,58 @@ private:
1037
1887
  // display:flex/grid is its own formatting context, not inline.
1038
1888
  static bool isInlineLevelTag(const char *tag)
1039
1889
  {
1040
- return std::strcmp(tag, "span") == 0 || std::strcmp(tag, "a") == 0 || std::strcmp(tag, "b") == 0 ||
1890
+ return std::strcmp(tag, "br") == 0 || std::strcmp(tag, "span") == 0 || std::strcmp(tag, "a") == 0 || std::strcmp(tag, "b") == 0 ||
1041
1891
  std::strcmp(tag, "i") == 0 || std::strcmp(tag, "em") == 0 || std::strcmp(tag, "strong") == 0 ||
1042
1892
  std::strcmp(tag, "small") == 0 || std::strcmp(tag, "label") == 0 || std::strcmp(tag, "code") == 0 ||
1043
1893
  std::strcmp(tag, "u") == 0 || std::strcmp(tag, "sub") == 0 || std::strcmp(tag, "sup") == 0 ||
1044
1894
  std::strcmp(tag, "mark") == 0;
1045
1895
  }
1046
1896
 
1897
+ // Box-tree projection for inline ancestors split by in-flow blocks. The DOM
1898
+ // ancestry still owns inheritance, events, relative translation, and painting.
1899
+ // Visible inline decorations require fragments; keep those on their own path.
1900
+ bool splitInlineWrapper(const Node *nodes, int id)
1901
+ {
1902
+ const Node &n = nodes[id];
1903
+ if (n.type != NodeType::View || n.style.display_explicit || n.style.display != kDisplayBlock ||
1904
+ !isInlineLevelTag(tagFromId(n.tag_id)) || n.style.float_side || isOutOfFlowPosition(n.style.position) ||
1905
+ !FlexLayoutPass::paintsNoBox(n) || boxInsets(n.style, true) || boxInsets(n.style, false) ||
1906
+ n.style.margin[1] || n.style.margin[3] || n.style.opacity != 255 || overflowEstablishesContext(n.style)) return false;
1907
+ bool containsBlock = false;
1908
+ for (int c = n.first_child; c >= 0; c = nodes[c].next_sibling) {
1909
+ const Node &child = nodes[c];
1910
+ if (isDisplayNone(child.style)) continue;
1911
+ if (isOutOfFlowPosition(child.style.position)) return false;
1912
+ if (child.style.float_side) continue;
1913
+ if (child.type == NodeType::View && (child.style.display_explicit || !isInlineLevelTag(tagFromId(child.tag_id)))) containsBlock = true;
1914
+ if (splitInlineWrapper(nodes, c)) containsBlock = true;
1915
+ }
1916
+ return containsBlock;
1917
+ }
1918
+
1919
+ int formattingEdgeNode(const Node *nodes, int id, bool last)
1920
+ {
1921
+ if (!splitInlineWrapper(nodes, id)) return id;
1922
+ for (int c = last ? nodes[id].last_child : nodes[id].first_child; c >= 0; c = last ? nodes[c].prev_sibling : nodes[c].next_sibling) {
1923
+ const Node &child = nodes[c];
1924
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position) || child.style.float_side) continue;
1925
+ if (isAnonymousTextNode(child) && (child.style.white_space == 0 || child.style.white_space == 1) &&
1926
+ child.text.find_first_not_of(" \t\r\n\f") == std::string::npos) continue;
1927
+ return formattingEdgeNode(nodes, c, last);
1928
+ }
1929
+ return -1;
1930
+ }
1931
+
1932
+ template<class Visit>
1933
+ void visitFormattingChildren(const Node *nodes, int parent, const Visit &visit, bool reverse = false)
1934
+ {
1935
+ const bool project = nodes[parent].style.display == kDisplayBlock && !nodes[parent].style.flex_direction_explicit;
1936
+ for (int c = reverse ? nodes[parent].last_child : nodes[parent].first_child; c >= 0; c = reverse ? nodes[c].prev_sibling : nodes[c].next_sibling) {
1937
+ if (project && splitInlineWrapper(nodes, c)) visitFormattingChildren(nodes, c, visit, reverse);
1938
+ else visit(c);
1939
+ }
1940
+ }
1941
+
1047
1942
  class LayoutNodePass {
1048
1943
  public:
1049
1944
  LayoutNodePass(LayoutEngine &engine, int id, int availWidth, int availHeight)
@@ -1053,9 +1948,19 @@ public:
1053
1948
 
1054
1949
  void run()
1055
1950
  {
1951
+ invalidateInlineChildMetadata();
1952
+ if (NodeRareData *rare = rareDataFor(id_)) rare->firstLineBackground.lineValid = false;
1056
1953
  if (isDisplayNone(node_.style)) return;
1057
1954
  prepareOwnSize();
1058
1955
 
1956
+ if (isLineBreak(node_) && LayoutEngine::isInlineLevelNode(node_) &&
1957
+ (node_.parent < 0 || (nodes_[node_.parent].style.display != kDisplayFlex && !isDisplayGrid(nodes_[node_.parent].style)))) {
1958
+ node_.layout.width = 0;
1959
+ node_.layout.height = clampInt16(TextRenderer::measureHeight(" ", node_.style.font_id,
1960
+ node_.style.font_size, 0, node_.style.line_height));
1961
+ return;
1962
+ }
1963
+
1059
1964
  if (node_.type == NodeType::Text) {
1060
1965
  const std::int64_t __tmT0 = refreshPerfNowUs();
1061
1966
  TextRenderer::layout(id_, availWidth_);
@@ -1082,8 +1987,8 @@ public:
1082
1987
  ScratchFrame scratch;
1083
1988
  if (!scratch.valid()) return;
1084
1989
 
1085
- const int childCount = engine_.collectChildren(id_, scratch.children(), kMaxChildren, true);
1086
- if (childCount == 0) {
1990
+ const int childCount = collectFormattingChildren(scratch.children(), kMaxChildren);
1991
+ if (childCount == 0 && !isDisplayGrid(node_.style)) {
1087
1992
  autosizeEmptyNode();
1088
1993
  positionAbsoluteChildren();
1089
1994
  applyRelativeOffsets();
@@ -1100,6 +2005,22 @@ public:
1100
2005
  return;
1101
2006
  }
1102
2007
 
2008
+ if (layoutFloatChildren(scratch.children(), childCount, padWidth, padHeight, true)) {
2009
+ encloseFloatDescendants();
2010
+ updateScrollContentSize();
2011
+ positionAbsoluteChildren();
2012
+ applyRelativeOffsets();
2013
+ return;
2014
+ }
2015
+ if (layoutBlockChildren(scratch.children(), childCount, padWidth, padHeight, true)) {
2016
+ encloseFloatDescendants();
2017
+ updateScrollContentSize();
2018
+ positionAbsoluteChildren();
2019
+ applyRelativeOffsets();
2020
+ applyVirtualListContentHeight();
2021
+ return;
2022
+ }
2023
+
1103
2024
  FlexLayoutPass flex(engine_, node_, scratch.children(), childCount, isRow, mainAvail, padWidth, padHeight, scratch.lines(), inlineRow);
1104
2025
  flex.measureChildren();
1105
2026
  if (inlineRow) {
@@ -1107,15 +2028,9 @@ public:
1107
2028
  // FlexLayoutPass::layoutInlineFlow.
1108
2029
  flex.layoutInlineFlow(true);
1109
2030
  } else {
1110
- const int lineCount = flex.buildLines();
1111
- flex.expandCrossSizes(lineCount, true);
1112
- // Finalize this node's own size BEFORE positioning its children: positionLines
1113
- // measures free main-axis space against the node's final padded box, so an
1114
- // auto-sized box must shrink to content first (otherwise children are placed
1115
- // against the larger available space and stranded after the shrink).
1116
- flex.autosizeParent(lineCount);
1117
- flex.positionLines(lineCount);
2031
+ flex.layoutLines(true);
1118
2032
  }
2033
+ encloseFloatDescendants();
1119
2034
  updateScrollContentSize();
1120
2035
  positionAbsoluteChildren();
1121
2036
  applyRelativeOffsets();
@@ -1125,6 +2040,8 @@ public:
1125
2040
  void repositionChildren()
1126
2041
  {
1127
2042
  if (node_.type == NodeType::Text || node_.type == NodeType::Image) return;
2043
+ invalidateInlineChildMetadata();
2044
+ if (NodeRareData *rare = rareDataFor(id_)) rare->firstLineBackground.lineValid = false;
1128
2045
 
1129
2046
  const int padWidth = paddedWidth();
1130
2047
  const int padHeight = paddedHeight();
@@ -1135,8 +2052,8 @@ public:
1135
2052
  ScratchFrame scratch;
1136
2053
  if (!scratch.valid()) return;
1137
2054
 
1138
- const int childCount = engine_.collectChildren(id_, scratch.children(), kMaxChildren, true);
1139
- if (childCount == 0) {
2055
+ const int childCount = collectFormattingChildren(scratch.children(), kMaxChildren);
2056
+ if (childCount == 0 && !isDisplayGrid(node_.style)) {
1140
2057
  positionAbsoluteChildren();
1141
2058
  return;
1142
2059
  }
@@ -1148,27 +2065,621 @@ public:
1148
2065
  return;
1149
2066
  }
1150
2067
 
1151
- FlexLayoutPass flex(engine_, node_, scratch.children(), childCount, isRow, mainAvail, padWidth, padHeight, scratch.lines(), inlineRow);
2068
+ if (layoutFloatChildren(scratch.children(), childCount, padWidth, padHeight, false)) {
2069
+ updateScrollContentSize();
2070
+ positionAbsoluteChildren();
2071
+ applyRelativeOffsets();
2072
+ return;
2073
+ }
2074
+ if (layoutBlockChildren(scratch.children(), childCount, padWidth, padHeight, false)) {
2075
+ positionAbsoluteChildren();
2076
+ applyRelativeOffsets();
2077
+ return;
2078
+ }
2079
+
2080
+ FlexLayoutPass flex(engine_, node_, scratch.children(), childCount, isRow, mainAvail, padWidth, padHeight, scratch.lines(), inlineRow, true);
1152
2081
  flex.measureChildren();
1153
2082
  if (inlineRow) {
1154
2083
  flex.layoutInlineFlow(false);
1155
2084
  } else {
1156
- const int lineCount = flex.buildLines();
1157
- flex.expandCrossSizes(lineCount, false);
1158
- flex.positionLines(lineCount);
2085
+ flex.layoutLines(false);
1159
2086
  }
1160
2087
  positionAbsoluteChildren();
1161
2088
  applyRelativeOffsets();
1162
2089
  }
1163
2090
 
2091
+ bool containsChildMargins() const
2092
+ {
2093
+ // A stable border box is not sufficient for isolated relayout: child
2094
+ // margins can change an ancestor's position/size through either edge.
2095
+ // Check the boundary itself, so removing the last collapsing child is
2096
+ // handled as well as introducing or resizing one.
2097
+ const bool horizontal = writingMode(node_) != 0;
2098
+ return !blockBox(node_) || establishesBlockContext(node_) ||
2099
+ (boxInset(node_.style, blockMarginSide(false)) > 0 &&
2100
+ (boxInset(node_.style, blockMarginSide(true)) > 0 ||
2101
+ (horizontal ? hasExplicitWidth(node_) : hasExplicitHeight(node_)) ||
2102
+ (horizontal ? node_.style.min_width : node_.style.min_height) > 0));
2103
+ }
2104
+
1164
2105
  private:
2106
+ void invalidateInlineChildMetadata()
2107
+ {
2108
+ for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
2109
+ NodeRareData *rare = rareDataFor(child);
2110
+ if (!rare) continue;
2111
+ rare->inlineStaticPosition.valid = false;
2112
+ rare->firstLineFragment.valid = false;
2113
+ }
2114
+ }
2115
+
2116
+ bool splitInlineChildren_ = false;
2117
+ int collectFormattingChildren(int *children, int capacity)
2118
+ {
2119
+ if (node_.style.display != kDisplayBlock || node_.style.flex_direction_explicit)
2120
+ return engine_.collectChildren(id_, children, capacity, true);
2121
+ int count = 0;
2122
+ auto collect = [&](auto &&self, int parent) -> void {
2123
+ for (int c = nodes_[parent].first_child; c >= 0; c = nodes_[c].next_sibling) {
2124
+ Node &child = nodes_[c];
2125
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position) || suppressAnonymousWhitespace(nodes_, parent, c)) continue;
2126
+ if (splitInlineWrapper(nodes_, c)) {
2127
+ splitInlineChildren_ = true;
2128
+ child.layout.x = child.layout.y = child.layout.width = child.layout.height = 0;
2129
+ child.layout.scroll_content_width = child.layout.scroll_content_height = 0;
2130
+ child.layout.memo_pass = child.layout.memo2_pass = 0;
2131
+ self(self, c);
2132
+ } else if (count < capacity) children[count++] = c;
2133
+ }
2134
+ };
2135
+ collect(collect, id_);
2136
+ return count;
2137
+ }
2138
+
2139
+ struct FloatBox { int left, top, right, bottom, side; };
2140
+ // One exclusion space for the entire BFC, including ordinary wrappers.
2141
+ // Coordinates exclude relative-position offsets. Clearance is used layout
2142
+ // state, not a consequence of merely authoring a non-none clear value.
2143
+ struct FloatContext {
2144
+ std::vector<FloatBox> boxes;
2145
+ std::vector<int> cleared;
2146
+ int lastTop = 0;
2147
+ bool hasClearance(int id) const { return std::find(cleared.begin(), cleared.end(), id) != cleared.end(); }
2148
+ };
2149
+ FloatContext *floatContext_ = nullptr;
2150
+
2151
+ struct CollapsedMargin {
2152
+ int positive = 0, negative = 0;
2153
+ bool trimmed = false;
2154
+ void add(int value) { positive = std::max(positive, value); negative = std::min(negative, value); }
2155
+ void add(CollapsedMargin other) { add(other.positive); add(other.negative); trimmed |= other.trimmed; }
2156
+ int value() const { return trimmed ? 0 : positive + negative; }
2157
+ };
2158
+
2159
+ bool blockBox(const Node &n) const
2160
+ {
2161
+ return n.type == NodeType::View && !isDisplayNone(n.style) &&
2162
+ (n.style.display_explicit || !isInlineLevelTag(tagFromId(n.tag_id)));
2163
+ }
2164
+
2165
+ bool flowChild(int parent, int child) const
2166
+ {
2167
+ return !isDisplayNone(nodes_[child].style) && !isOutOfFlowPosition(nodes_[child].style.position) &&
2168
+ !nodes_[child].style.float_side && !suppressAnonymousWhitespace(nodes_, parent, child);
2169
+ }
2170
+
2171
+ bool establishesBlockContext(const Node &n) const
2172
+ {
2173
+ return n.parent < 0 || isOutOfFlowPosition(n.style.position) || n.style.float_side ||
2174
+ n.style.display != kDisplayBlock || overflowEstablishesContext(n.style) ||
2175
+ (n.parent >= 0 && (nodes_[n.parent].style.display == kDisplayFlex || isDisplayGrid(nodes_[n.parent].style) ||
2176
+ writingMode(n) != writingMode(nodes_[n.parent])));
2177
+ }
2178
+
2179
+ void encloseFloatDescendants()
2180
+ {
2181
+ if (node_.style.display != kDisplayBlock || hasExplicitHeight(node_) || !establishesBlockContext(node_)) return;
2182
+ int bottom = node_.layout.height - boxInset(node_.style, 2);
2183
+ // CSS 2.2 10.6.7 includes floats through ordinary wrappers, but never
2184
+ // crosses another formatting context. Child layout is still relative;
2185
+ // offsets below the first level have already been applied by its parent.
2186
+ auto visit = [&](auto &&self, int parent, int y) -> void {
2187
+ for (int id = nodes_[parent].first_child; id >= 0; id = nodes_[id].next_sibling) {
2188
+ const Node &child = nodes_[id];
2189
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position)) continue;
2190
+ int top = y + child.layout.y;
2191
+ if (parent != id_ && child.style.position == 2) {
2192
+ LayoutNodePass owner(engine_, parent, 0, 0);
2193
+ if (hasPositionOffset(child, 0)) top -= owner.resolvedRelativePositionOffset(child, 0);
2194
+ else if (hasPositionOffset(child, 2)) top += owner.resolvedRelativePositionOffset(child, 2);
2195
+ }
2196
+ if (child.style.float_side) bottom = std::max(bottom, top + child.layout.height + child.style.margin[2]);
2197
+ else if (!establishesBlockContext(child)) self(self, id, top);
2198
+ }
2199
+ };
2200
+ visit(visit, id_, 0);
2201
+ node_.layout.height = clampBorderSize(engine_, node_, bottom + boxInset(node_.style, 2), false);
2202
+ }
2203
+
2204
+ int blockMarginSide(bool end) const
2205
+ {
2206
+ if (writingMode(node_) == 0) return end ? 2 : 0;
2207
+ return gridAxisReversed(node_, true) != end ? 1 : 3;
2208
+ }
2209
+
2210
+ bool collapsesThrough(int id) const
2211
+ {
2212
+ const Node &n = nodes_[id];
2213
+ const bool horizontal = writingMode(node_) != 0;
2214
+ if (!blockBox(n) || establishesBlockContext(n) || (horizontal ? n.layout.width : n.layout.height) != 0 ||
2215
+ (horizontal ? n.style.min_width : n.style.min_height) > 0 || boxInsets(n.style, horizontal)) return false;
2216
+ bool through = true;
2217
+ visitFormattingChildren(nodes_, id, [&](int c) {
2218
+ if (flowChild(nodes_[c].parent, c) && ((floatContext_ && floatContext_->hasClearance(c)) || !collapsesThrough(c))) through = false;
2219
+ });
2220
+ return through;
2221
+ }
2222
+
2223
+ bool collapsesWithChildren(int id, bool bottom) const
2224
+ {
2225
+ const Node &n = nodes_[id];
2226
+ const bool horizontal = writingMode(node_) != 0;
2227
+ if (!blockBox(n) || establishesBlockContext(n) || boxInset(n.style, blockMarginSide(bottom))) return false;
2228
+ if (bottom && ((horizontal ? hasExplicitWidth(n) : hasExplicitHeight(n)) ||
2229
+ isIntrinsicSizeExpression(horizontal ? n.style.width_expression : n.style.height_expression) ||
2230
+ (horizontal ? n.style.min_width : n.style.min_height) > 0)) return false;
2231
+ int edge = -1;
2232
+ visitFormattingChildren(nodes_, id, [&](int c) {
2233
+ if (!flowChild(nodes_[c].parent, c) || (edge >= 0 && !bottom)) return;
2234
+ edge = c;
2235
+ });
2236
+ return edge >= 0 && blockBox(nodes_[edge]) &&
2237
+ !(floatContext_ && floatContext_->hasClearance(edge) && (!bottom || collapsesThrough(edge)));
2238
+ }
2239
+
2240
+ CollapsedMargin edgeMargin(int id, bool bottom, bool separateBottom = false) const
2241
+ {
2242
+ const Node &n = nodes_[id];
2243
+ CollapsedMargin margin;
2244
+ margin.add(n.style.margin[blockMarginSide(bottom)]);
2245
+ CollapsedMargin descendants;
2246
+ if (!separateBottom && collapsesThrough(id)) {
2247
+ margin.add(n.style.margin[blockMarginSide(!bottom)]);
2248
+ visitFormattingChildren(nodes_, id, [&](int c) {
2249
+ if (flowChild(nodes_[c].parent, c)) descendants.add(childEdgeMargin(id, c, false));
2250
+ });
2251
+ } else if (collapsesWithChildren(id, bottom)) {
2252
+ bool stop = false;
2253
+ visitFormattingChildren(nodes_, id, [&](int c) {
2254
+ if (stop || !flowChild(nodes_[c].parent, c)) return;
2255
+ if (!blockBox(nodes_[c]) || (floatContext_ && floatContext_->hasClearance(c) && (!bottom || collapsesThrough(c)))) { stop = true; return; }
2256
+ descendants.add(childEdgeMargin(id, c, bottom));
2257
+ if (!collapsesThrough(c)) stop = true;
2258
+ }, bottom);
2259
+ }
2260
+ if (!descendants.trimmed) margin.add(descendants);
2261
+ return margin;
2262
+ }
2263
+
2264
+ // Whether this edge belongs to the collapsed group adjoining a container
2265
+ // boundary. Floats and positioned children do not consume that boundary;
2266
+ // inline content and non-empty blocks do.
2267
+ bool trimmedBlockEdge(int owner, int id, bool bottom) const
2268
+ {
2269
+ const Node &container = nodes_[owner];
2270
+ const int trim = rstyle(container.style).margin_trim;
2271
+ if (!(trim & 3) || container.style.display != kDisplayBlock || container.style.flex_direction_explicit || !blockBox(nodes_[id])) return false;
2272
+ for (bool end : {false, true}) {
2273
+ if (!(trim & (end ? 2 : 1)) || (end != bottom && !collapsesThrough(id))) continue;
2274
+ bool adjacent = true, found = false;
2275
+ visitFormattingChildren(nodes_, owner, [&](int child) {
2276
+ if (found || !adjacent || !flowChild(nodes_[child].parent, child)) return;
2277
+ if (child == id) { found = true; return; }
2278
+ if (!collapsesThrough(child) || (floatContext_ && floatContext_->hasClearance(child))) adjacent = false;
2279
+ }, end);
2280
+ if (found && adjacent) return true;
2281
+ }
2282
+ return false;
2283
+ }
2284
+
2285
+ CollapsedMargin childEdgeMargin(int owner, int id, bool bottom, bool separateBottom = false) const
2286
+ {
2287
+ auto margin = edgeMargin(id, bottom, separateBottom);
2288
+ margin.trimmed = trimmedBlockEdge(owner, id, bottom);
2289
+ return margin;
2290
+ }
2291
+
2292
+ bool layoutBlockChildren(int *children, int count, int contentWidth, int contentHeight, bool autosize)
2293
+ {
2294
+ if (node_.style.display != kDisplayBlock || node_.style.flex_direction_explicit) return false;
2295
+ const bool vertical = writingMode(node_) != 0;
2296
+ for (int i = 0; i < count; ++i)
2297
+ if (!blockBox(nodes_[children[i]]) || nodes_[children[i]].style.float_side) return false;
2298
+ if (vertical) {
2299
+ const bool measureInline = autosize && !hasExplicitHeight(node_) && node_.parent >= 0;
2300
+ int intrinsicHeight = 0;
2301
+ for (int i = 0; i < count; ++i) {
2302
+ engine_.layoutNode(children[i], contentWidth, contentHeight);
2303
+ const Node &child = nodes_[children[i]];
2304
+ intrinsicHeight = std::max(intrinsicHeight, child.layout.height + child.style.margin[0] + child.style.margin[2]);
2305
+ }
2306
+ if (measureInline) {
2307
+ node_.layout.height = clampLayoutSize(node_, intrinsicHeight + boxInsets(node_.style, false), false);
2308
+ contentHeight = paddedHeight();
2309
+ }
2310
+ for (int i = 0; i < count; ++i) {
2311
+ const int id = children[i]; Node &child = nodes_[id];
2312
+ if (measureInline) engine_.layoutNode(id, contentWidth, contentHeight);
2313
+ if (!hasExplicitHeight(child) && !isIntrinsicSizeExpression(child.style.height_expression) && writingMode(child) != 0 &&
2314
+ !(preferredRatio(child) > 0 && hasExplicitWidth(child))) {
2315
+ const int height = clampLayoutSize(child, std::max(0, contentHeight - child.style.margin[0] - child.style.margin[2]), false);
2316
+ if (child.layout.height != height) {
2317
+ child.layout.height = clampInt16(height); engine_.repositionChildren(id);
2318
+ }
2319
+ }
2320
+ const int slack = contentHeight - child.layout.height - child.style.margin[0] - child.style.margin[2];
2321
+ const bool autoTop = child.style.margin_auto & 1, autoBottom = child.style.margin_auto & 4;
2322
+ int offset = slack > 0 && autoTop ? (autoBottom ? slack / 2 : slack) : 0;
2323
+ if (!autoTop && !autoBottom && gridAxisReversed(node_, false)) offset = slack;
2324
+ child.layout.y = boxInset(node_.style, 0) + child.style.margin[0] + offset;
2325
+ }
2326
+ } else {
2327
+ // Measure content before assigning the normal-flow fill width. A flex
2328
+ // item, float, or absolute box can use this intrinsic width; its parent
2329
+ // assigns the final width and calls repositionChildren afterwards.
2330
+ const bool measureIntrinsic = autosize && (node_.parent >= 0 || node_.style.float_side || intrinsicWidthConstraint(node_)) && !hasExplicitWidth(node_);
2331
+ int intrinsicWidth = 0;
2332
+ for (int i = 0; i < count; ++i) {
2333
+ const int id = children[i];
2334
+ engine_.layoutNode(id, contentWidth, contentHeight, measureIntrinsic);
2335
+ const Node &child = nodes_[id];
2336
+ intrinsicWidth = std::max(intrinsicWidth, child.layout.width + child.style.margin[1] + child.style.margin[3]);
2337
+ }
2338
+ if (measureIntrinsic) {
2339
+ node_.layout.width = clampLayoutSize(node_, intrinsicWidth + boxInsets(node_.style, true), true);
2340
+ contentWidth = paddedWidth();
2341
+ }
2342
+ for (int i = 0; i < count; ++i) {
2343
+ const int id = children[i];
2344
+ Node &child = nodes_[id];
2345
+ if (measureIntrinsic) engine_.layoutNode(id, contentWidth, contentHeight);
2346
+ // This horizontal formatting context fills the inline size of
2347
+ // parallel children. An orthogonal child's width is its block size.
2348
+ if (!hasExplicitWidth(child) && !isIntrinsicSizeExpression(child.style.width_expression) && writingMode(child) == 0 && !(preferredRatio(child) > 0 && hasExplicitHeight(child))) {
2349
+ const int width = clampLayoutSize(child, std::max(0, contentWidth - child.style.margin[1] - child.style.margin[3]), true);
2350
+ if (child.layout.width != width) {
2351
+ child.layout.width = clampInt16(width);
2352
+ engine_.repositionChildren(id);
2353
+ }
2354
+ }
2355
+ const int slack = contentWidth - child.layout.width - child.style.margin[1] - child.style.margin[3];
2356
+ const bool autoLeft = child.style.margin_auto & (1 << 3);
2357
+ const bool autoRight = child.style.margin_auto & (1 << 1);
2358
+ int offset = slack > 0 && autoLeft ? (autoRight ? slack / 2 : slack) : 0;
2359
+ if (!autoLeft && !autoRight && rightToLeft(node_)) offset = slack;
2360
+ child.layout.x = boxInset(node_.style, 3) + child.style.margin[3] + offset;
2361
+ }
2362
+ }
2363
+ const bool mergeTop = collapsesWithChildren(id_, false);
2364
+ const bool mergeBottom = collapsesWithChildren(id_, true);
2365
+ int cursor = 0;
2366
+ bool first = true;
2367
+ CollapsedMargin pending;
2368
+ for (int i = 0; i < count; ++i) {
2369
+ const int id = children[i];
2370
+ Node &child = nodes_[id];
2371
+ if (collapsesThrough(id)) {
2372
+ // CSS 2.2 8.3.1: an empty box sharing the parent's top margin
2373
+ // starts at that edge. Otherwise position it as if it had a bottom
2374
+ // border, before its own bottom and following siblings' margins
2375
+ // join the group. Its position does not advance normal flow.
2376
+ auto before = pending;
2377
+ before.add(childEdgeMargin(id_, id, false, true));
2378
+ (vertical ? child.layout.x : child.layout.y) = boxInset(node_.style, blockMarginSide(false)) + cursor + (first && mergeTop ? 0 : before.value());
2379
+ pending.add(childEdgeMargin(id_, id, false));
2380
+ continue;
2381
+ }
2382
+ pending.add(childEdgeMargin(id_, id, false));
2383
+ cursor += first && mergeTop ? 0 : pending.value();
2384
+ (vertical ? child.layout.x : child.layout.y) = boxInset(node_.style, blockMarginSide(false)) + cursor;
2385
+ cursor += vertical ? child.layout.width : child.layout.height;
2386
+ pending = childEdgeMargin(id_, id, true);
2387
+ first = false;
2388
+ }
2389
+ cursor += mergeBottom || (first && mergeTop) ? 0 : pending.value();
2390
+ if (vertical) {
2391
+ if (autosize && !hasExplicitWidth(node_) && !(scrollsOverflowX(node_.style) && node_.layout.width > 0))
2392
+ node_.layout.width = clampLayoutSize(node_, std::max(0, cursor) + boxInsets(node_.style, true), true);
2393
+ if (gridAxisReversed(node_, true)) for (int i = 0; i < count; ++i) {
2394
+ Node &child = nodes_[children[i]];
2395
+ child.layout.x = node_.layout.width - child.layout.x - child.layout.width;
2396
+ }
2397
+ } else if (autosize && !hasExplicitHeight(node_) && !(scrollsOverflowY(node_.style) && node_.layout.height > 0)) {
2398
+ node_.layout.height = clampLayoutSize(node_, std::max(0, cursor) + boxInsets(node_.style, false), false);
2399
+ }
2400
+ return true;
2401
+ }
2402
+
2403
+ bool layoutFloatChildren(int *children, int count, int contentWidth, int contentHeight, bool autosize)
2404
+ {
2405
+ if (node_.style.display != kDisplayBlock) return false;
2406
+ auto containsFloat = [&](auto &&self, int parent) -> bool {
2407
+ for (int c = nodes_[parent].first_child; c >= 0; c = nodes_[c].next_sibling) {
2408
+ const Node &child = nodes_[c];
2409
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position)) continue;
2410
+ if (child.style.float_side || (!establishesBlockContext(child) && self(self, c))) return true;
2411
+ }
2412
+ return false;
2413
+ };
2414
+ bool blocks = false, inlines = false;
2415
+ for (int i = 0; i < count; ++i) {
2416
+ if (blockBox(nodes_[children[i]])) blocks = true;
2417
+ else if (!nodes_[children[i]].style.float_side) inlines = true;
2418
+ }
2419
+ if (!splitInlineChildren_ && !(blocks && inlines) && !containsFloat(containsFloat, id_)) return false;
2420
+ FloatContext context;
2421
+ const bool measureWidth = autosize && !hasExplicitWidth(node_) &&
2422
+ (node_.parent >= 0 || node_.style.float_side || intrinsicWidthConstraint(node_)) &&
2423
+ !(scrollsOverflowX(node_.style) && node_.layout.width > 0 && !intrinsicWidthConstraint(node_));
2424
+ layoutFloatChildrenInContext(children, count, contentWidth, contentHeight, autosize, context, 0, 0, measureWidth);
2425
+ if (measureWidth && paddedWidth() != contentWidth) {
2426
+ // As in ordinary block layout, measure first, then assign the used
2427
+ // containing width. Descendants in an existing float context already
2428
+ // have an assigned width and must not shrink it during placement.
2429
+ context = {};
2430
+ layoutFloatChildrenInContext(children, count, paddedWidth(), contentHeight, autosize, context, 0, 0);
2431
+ }
2432
+ floatContext_ = nullptr;
2433
+ return true;
2434
+ }
2435
+
2436
+ void layoutFloatChildrenInContext(int *children, int count, int contentWidth, int contentHeight, bool autosize,
2437
+ FloatContext &context, int originX, int originY, bool measureWidth = false)
2438
+ {
2439
+ floatContext_ = &context;
2440
+ auto &floats = context.boxes;
2441
+ int flowY = 0;
2442
+ int intrinsicWidth = 0;
2443
+ CollapsedMargin pending;
2444
+ bool first = true, clearedThrough = false;
2445
+ for (int i = 0; i < count; ++i) {
2446
+ Node &child = nodes_[children[i]];
2447
+ if (!blockBox(child) && !child.style.float_side) {
2448
+ int end = i + 1;
2449
+ // Keep a BR with the line it terminates, then recompute the
2450
+ // float exclusions for the next line.
2451
+ while (!isLineBreak(nodes_[children[end - 1]]) &&
2452
+ end < count && !blockBox(nodes_[children[end]]) && !nodes_[children[end]].style.float_side) ++end;
2453
+ flowY += pending.value();
2454
+ pending = {};
2455
+ ScratchFrame inlineScratch;
2456
+ if (inlineScratch.valid()) {
2457
+ auto layoutRun = [&](int width) {
2458
+ FlexLayoutPass line(engine_, node_, children + i, end - i, true, width, width, contentHeight, inlineScratch.lines(), true);
2459
+ line.measureChildren();
2460
+ return line.layoutInlineFlow(false, true);
2461
+ };
2462
+ NodeRareData *ownerRare = rareDataFor(id_);
2463
+ const bool ownerLineWasValid = ownerRare && ownerRare->firstLineBackground.lineValid;
2464
+ auto extent = layoutRun(contentWidth);
2465
+ // If even the first unbreakable unit cannot fit beside a float,
2466
+ // move this line down to the next float boundary and retry.
2467
+ // Once the whole containing width is available, the word may overflow.
2468
+ int minimum = 0;
2469
+ for (int j = i; j < end && minimum == 0; ++j) {
2470
+ const Node &item = nodes_[children[j]];
2471
+ if (isLineBreak(item)) break;
2472
+ const int inner = FlexLayoutPass::transparentInlineRun(item);
2473
+ minimum = item.type == NodeType::Text || inner >= 0
2474
+ ? TextRenderer::firstUnbreakableWidth(inner >= 0 ? nodes_[inner] : item)
2475
+ : item.layout.width;
2476
+ minimum += item.style.margin[1] + item.style.margin[3];
2477
+ if (item.type == NodeType::Text) minimum += boxInsets(item.style, true);
2478
+ }
2479
+ int left = 0, right = contentWidth;
2480
+ for (;;) {
2481
+ left = 0; right = contentWidth;
2482
+ int nextBottom = INT_MAX;
2483
+ for (const auto &f : floats) {
2484
+ if (originY + flowY >= f.bottom || originY + flowY + extent.firstLineHeight <= f.top) continue;
2485
+ if (f.side == 1) left = std::max(left, f.right - originX);
2486
+ else right = std::min(right, f.left - originX);
2487
+ nextBottom = std::min(nextBottom, f.bottom - originY);
2488
+ }
2489
+ if (minimum <= right-left || (left == 0 && right == contentWidth) || nextBottom == INT_MAX) break;
2490
+ flowY = nextBottom;
2491
+ }
2492
+ if (right - left != contentWidth) extent = layoutRun(std::max(0, right - left));
2493
+ if (!ownerLineWasValid && ownerRare && ownerRare->firstLineBackground.lineValid)
2494
+ ownerRare->firstLineBackground.lineY = clampInt16(ownerRare->firstLineBackground.lineY + flowY);
2495
+ for (int j = i; j < end; ++j) {
2496
+ const int childId = children[j];
2497
+ const int runId = FlexLayoutPass::transparentInlineRun(nodes_[childId]);
2498
+ for (int fragmentId : {childId, runId}) {
2499
+ if (fragmentId < 0) continue;
2500
+ if (NodeRareData *rare = rareDataFor(fragmentId)) {
2501
+ auto &fragment = rare->firstLineFragment;
2502
+ if (fragment.valid && fragment.contextNode == id_) {
2503
+ fragment.x = clampInt16(fragment.x + left);
2504
+ fragment.y = clampInt16(fragment.y + flowY);
2505
+ }
2506
+ }
2507
+ }
2508
+ }
2509
+ for (int j = i; j < end; ++j) {
2510
+ nodes_[children[j]].layout.x += left;
2511
+ nodes_[children[j]].layout.y += flowY;
2512
+ }
2513
+ flowY += extent.height;
2514
+ intrinsicWidth = std::max(intrinsicWidth, left + extent.width);
2515
+ const Node &last = nodes_[children[end - 1]];
2516
+ if (isLineBreak(last)) for (const auto &f : floats)
2517
+ if (last.style.clear_side & f.side) flowY = std::max(flowY, f.bottom - originY);
2518
+ }
2519
+ first = false; clearedThrough = false;
2520
+ i = end - 1;
2521
+ continue;
2522
+ }
2523
+ engine_.layoutNode(children[i], contentWidth, contentHeight, measureWidth);
2524
+ const bool block = !child.style.float_side && blockBox(child);
2525
+ const int measuredOuterW = child.layout.width + child.style.margin[3] + child.style.margin[1];
2526
+ const bool automaticWidth = block && !hasExplicitWidth(child) && !isIntrinsicSizeExpression(child.style.width_expression) &&
2527
+ writingMode(child) == 0 && !(preferredRatio(child) > 0 && hasExplicitHeight(child));
2528
+ // Ordinary blocks still fill their containing block beside floats;
2529
+ // only their line boxes are shortened by float exclusions.
2530
+ if (automaticWidth) {
2531
+ const int width = clampLayoutSize(child, std::max(0, contentWidth - child.style.margin[1] - child.style.margin[3]), true);
2532
+ if (child.layout.width != width) {
2533
+ child.layout.width = clampInt16(width);
2534
+ engine_.repositionChildren(children[i]);
2535
+ }
2536
+ }
2537
+ int outerW = child.layout.width + child.style.margin[3] + child.style.margin[1];
2538
+ int outerH = child.layout.height + child.style.margin[0] + child.style.margin[2];
2539
+ const bool mergeTop = first && collapsesWithChildren(id_, false);
2540
+ if (!block && !child.style.float_side) {
2541
+ flowY += mergeTop ? 0 : pending.value();
2542
+ pending = {};
2543
+ first = false;
2544
+ }
2545
+ auto before = pending;
2546
+ if (block) before.add(childEdgeMargin(id_, children[i], false, true));
2547
+ // Normal blocks clear their border edge, after adjoining margins
2548
+ // collapse. Floats instead clear their outer edge (CSS 2.2 9.5.2).
2549
+ int y = block ? flowY + (mergeTop ? 0 : before.value()) :
2550
+ child.style.float_side ? std::max(flowY + (mergeTop ? 0 : pending.value()), context.lastTop - originY) : flowY;
2551
+ const int hypotheticalY = y;
2552
+ int clearBottom = INT_MIN;
2553
+ for (const auto &f : floats)
2554
+ if (child.style.clear_side & f.side) clearBottom = std::max(clearBottom, f.bottom - originY);
2555
+ const bool clearance = block && clearBottom != INT_MIN && (clearBottom > hypotheticalY || context.hasClearance(children[i]));
2556
+ // Once clearance separated the margins, rebasing the wrapper must
2557
+ // not mistake the now non-collapsing margin for a new hypothetical
2558
+ // position. CSS permits aligning exactly to the float bottom, even
2559
+ // when that requires negative clearance above the top margin.
2560
+ y = clearance ? clearBottom : std::max(y, clearBottom);
2561
+ if (clearance && !context.hasClearance(children[i])) context.cleared.push_back(children[i]);
2562
+ int left = 0, right = contentWidth, contextX = 0;
2563
+ const bool independentBlock = block && establishesBlockContext(child);
2564
+ if (child.style.float_side || child.style.display != kDisplayBlock || establishesBlockContext(child)) {
2565
+ for (;;) {
2566
+ left = 0; right = contentWidth;
2567
+ int nextY = 32767;
2568
+ bool hasLeft = false, hasRight = false;
2569
+ for (const auto &global : floats) {
2570
+ const FloatBox f{global.left - originX, global.top - originY, global.right - originX, global.bottom - originY, global.side};
2571
+ if (y >= f.bottom || y + std::max(1, independentBlock ? int(child.layout.height) : outerH) <= f.top) continue;
2572
+ if (f.side == 1) { left = std::max(left, f.right); hasLeft = true; }
2573
+ else { right = std::min(right, f.left); hasRight = true; }
2574
+ nextY = std::min(nextY, f.bottom);
2575
+ }
2576
+ bool fits = outerW <= right - left;
2577
+ if (independentBlock) {
2578
+ // A BFC's border box cannot overlap float margin boxes.
2579
+ // Automatic width uses the remaining interval. Even a
2580
+ // zero-width float prevents a negative margin crossing it.
2581
+ const int start = hasLeft ? std::max<int>(child.style.margin[3], left) : child.style.margin[3];
2582
+ const int end = hasRight ? std::min<int>(contentWidth - child.style.margin[1], right) : contentWidth - child.style.margin[1];
2583
+ contextX = start - child.style.margin[3];
2584
+ if (automaticWidth) {
2585
+ const int width = clampLayoutSize(child, std::max(0, end - start), true);
2586
+ if (child.layout.width != width) {
2587
+ const int previousHeight = child.layout.height;
2588
+ engine_.layoutNode(children[i], width + child.style.margin[1] + child.style.margin[3], contentHeight);
2589
+ child.layout.width = clampInt16(width);
2590
+ engine_.repositionChildren(children[i]);
2591
+ outerW = width + child.style.margin[1] + child.style.margin[3];
2592
+ outerH = child.layout.height + child.style.margin[0] + child.style.margin[2];
2593
+ if (previousHeight != child.layout.height) continue;
2594
+ }
2595
+ }
2596
+ fits = child.layout.width <= end - start;
2597
+ }
2598
+ if (fits || nextY == 32767) break;
2599
+ y = nextY;
2600
+ }
2601
+ }
2602
+ const int x = child.style.float_side == 2 ? right - outerW : independentBlock ? contextX : left;
2603
+ intrinsicWidth = std::max(intrinsicWidth, child.style.float_side
2604
+ ? left + outerW + contentWidth - right : measuredOuterW);
2605
+ child.layout.x = boxInset(node_.style, 3) + x + child.style.margin[3];
2606
+ child.layout.y = boxInset(node_.style, 0) + y + (block ? 0 : child.style.margin[0]);
2607
+ if (block && !establishesBlockContext(child) && child.first_child >= 0) {
2608
+ LayoutNodePass nested(engine_, children[i], contentWidth, contentHeight);
2609
+ if (!nested.resolveInlineFormattingRow()) {
2610
+ ScratchFrame nestedScratch;
2611
+ if (nestedScratch.valid()) {
2612
+ const int nestedCount = nested.collectFormattingChildren(nestedScratch.children(), kMaxChildren);
2613
+ const auto precedingFloats = floats.size();
2614
+ const int precedingTop = context.lastTop;
2615
+ auto placeDescendants = [&]() {
2616
+ nested.layoutFloatChildrenInContext(nestedScratch.children(), nestedCount, nested.paddedWidth(), nested.paddedHeight(), true,
2617
+ context, originX + x + child.style.margin[3] + boxInset(child.style, 3), originY + y + boxInset(child.style, 0));
2618
+ };
2619
+ placeDescendants();
2620
+ // Actual descendant clearance can separate a margin that was
2621
+ // adjoining this wrapper's top during hypothetical placement.
2622
+ // Rebase the subtree with that separation recorded; discard
2623
+ // its provisional floats before placing them at the final edge.
2624
+ auto separated = pending;
2625
+ separated.add(childEdgeMargin(id_, children[i], false, true));
2626
+ int finalY = flowY + (first && collapsesWithChildren(id_, false) ? 0 : separated.value());
2627
+ if (clearance) finalY = clearBottom;
2628
+ for (std::size_t f = 0; f < precedingFloats; ++f)
2629
+ if (child.style.clear_side & floats[f].side) finalY = std::max(finalY, floats[f].bottom - originY);
2630
+ if (finalY != y) {
2631
+ y = finalY;
2632
+ child.layout.y = boxInset(node_.style, 0) + y;
2633
+ floats.resize(precedingFloats);
2634
+ context.lastTop = precedingTop;
2635
+ placeDescendants();
2636
+ }
2637
+ nested.updateScrollContentSize();
2638
+ nested.positionAbsoluteChildren();
2639
+ nested.applyRelativeOffsets();
2640
+ // This result depends on preceding floats, beyond the size-only memo key.
2641
+ child.layout.memo_pass = child.layout.memo2_pass = 0;
2642
+ }
2643
+ }
2644
+ }
2645
+ if (child.style.float_side) {
2646
+ floats.push_back({originX + x, originY + y, originX + x + outerW, originY + y + outerH, child.style.float_side});
2647
+ context.lastTop = originY + y;
2648
+ } else if (block && collapsesThrough(children[i])) {
2649
+ if (clearance) {
2650
+ // The cleared empty box's margins can still collapse forward,
2651
+ // but that group cannot escape through the parent's bottom.
2652
+ flowY = y - childEdgeMargin(id_, children[i], false, true).value();
2653
+ pending = {};
2654
+ first = false;
2655
+ clearedThrough = true;
2656
+ }
2657
+ pending.add(childEdgeMargin(id_, children[i], false));
2658
+ } else if (block) {
2659
+ flowY = y + child.layout.height;
2660
+ pending = childEdgeMargin(id_, children[i], true);
2661
+ first = false;
2662
+ clearedThrough = false;
2663
+ } else flowY = y + outerH;
2664
+ }
2665
+ if (clearedThrough || (!collapsesWithChildren(id_, true) && !(first && collapsesWithChildren(id_, false))))
2666
+ flowY += pending.value();
2667
+ if (measureWidth)
2668
+ node_.layout.width = clampInt16(clampLayoutSize(node_, intrinsicWidth + boxInsets(node_.style, true), true));
2669
+ if (autosize && !hasExplicitHeight(node_)) {
2670
+ // Float enclosure is finalized with all same-context descendants.
2671
+ node_.layout.height = clampBorderSize(engine_, node_, flowY + boxInsets(node_.style, false), false);
2672
+ }
2673
+ }
2674
+
1165
2675
  // Direction for FlexLayoutPass. Explicit flex-direction / display:flex win
1166
2676
  // (usesRowLayout). Otherwise a plain block whose in-flow children are all
1167
2677
  // inline-level flows them on a row (CSS inline formatting); a block with any
1168
2678
  // block-level in-flow child stacks them (column), as a browser would.
1169
2679
  bool resolveRowDirection() const
1170
2680
  {
1171
- if (usesRowLayout(node_.style)) return true;
2681
+ if (node_.style.display == kDisplayFlex)
2682
+ return flexRowDirection(node_.style) != (writingMode(node_) != 0);
1172
2683
  return resolveInlineFormattingRow();
1173
2684
  }
1174
2685
 
@@ -1181,29 +2692,15 @@ private:
1181
2692
  {
1182
2693
  if (usesRowLayout(node_.style)) return false;
1183
2694
  if (node_.style.flex_direction_explicit || node_.style.display != kDisplayBlock) return false;
1184
- bool anyInFlow = false;
1185
- for (int c = node_.first_child; c >= 0; c = nodes_[c].next_sibling) {
2695
+ bool anyInFlow = false, allInline = true;
2696
+ visitFormattingChildren(nodes_, id_, [&](int c) {
1186
2697
  const Node &child = nodes_[c];
1187
- if (child.style.display == kDisplayNone || child.style.position == 1) continue; // none / absolute
1188
- if (!LayoutEngine::isInlineLevelNode(child)) return false;
2698
+ if (child.style.display == kDisplayNone || isOutOfFlowPosition(child.style.position)) return;
2699
+ if (suppressAnonymousWhitespace(nodes_, child.parent, c)) return;
2700
+ if (!LayoutEngine::isInlineLevelNode(child)) allInline = false;
1189
2701
  anyInFlow = true;
1190
- }
1191
- return anyInFlow;
1192
- }
1193
-
1194
- int explicitGridColumnCount(int childCount) const
1195
- {
1196
- if (rstyle(node_.style).grid_column_count > 0) return rstyle(node_.style).grid_column_count;
1197
- return childCount > 0 ? 1 : 0;
1198
- }
1199
-
1200
- int explicitGridRowCount(int childCount, int columnCount) const
1201
- {
1202
- if (rstyle(node_.style).grid_row_count > 0) return rstyle(node_.style).grid_row_count;
1203
- if (columnCount <= 0) return 0;
1204
- int rows = (childCount + columnCount - 1) / columnCount;
1205
- if (rows > kMaxGridLayoutTracks) rows = kMaxGridLayoutTracks;
1206
- return rows;
2702
+ });
2703
+ return anyInFlow && allInline;
1207
2704
  }
1208
2705
 
1209
2706
  void measureGridChildren(int *children, int childCount, int padWidth, int padHeight)
@@ -1214,34 +2711,12 @@ private:
1214
2711
  }
1215
2712
  }
1216
2713
 
1217
- void computeAutoTrackSizes(int *children,
1218
- int childCount,
1219
- int columnCount,
1220
- int rowCount,
1221
- int *autoColumnSizes,
1222
- int *autoRowSizes)
1223
- {
1224
- for (int i = 0; i < kMaxGridLayoutTracks; ++i) {
1225
- autoColumnSizes[i] = 0;
1226
- autoRowSizes[i] = 0;
1227
- }
1228
- for (int i = 0; i < childCount; ++i) {
1229
- const int column = columnCount > 0 ? i % columnCount : 0;
1230
- const int row = columnCount > 0 ? i / columnCount : 0;
1231
- if (column >= columnCount || row >= rowCount) continue;
1232
- const Node &childNode = nodes_[children[i]];
1233
- const int childWidth = childNode.layout.width + childNode.style.margin[1] + childNode.style.margin[3];
1234
- const int childHeight = childNode.layout.height + childNode.style.margin[0] + childNode.style.margin[2];
1235
- if (childWidth > autoColumnSizes[column]) autoColumnSizes[column] = childWidth;
1236
- if (childHeight > autoRowSizes[row]) autoRowSizes[row] = childHeight;
1237
- }
1238
- }
1239
-
1240
2714
  void computeTrackSizes(int count,
1241
2715
  const int8_t *types,
1242
2716
  const int16_t *values,
1243
2717
  const int *autoSizes,
1244
2718
  int available,
2719
+ int gap,
1245
2720
  int *outSizes)
1246
2721
  {
1247
2722
  int fixedTotal = 0;
@@ -1259,7 +2734,7 @@ private:
1259
2734
  }
1260
2735
  }
1261
2736
 
1262
- const int gapTotal = count > 1 ? (count - 1) * node_.style.gap : 0;
2737
+ const int gapTotal = count > 1 ? (count - 1) * gap : 0;
1263
2738
  int remaining = available - fixedTotal - gapTotal;
1264
2739
  if (remaining < 0) remaining = 0;
1265
2740
 
@@ -1281,20 +2756,41 @@ private:
1281
2756
  }
1282
2757
  }
1283
2758
 
1284
- int gridTrackTotalSize(int count, const int *sizes) const
2759
+ int gridTrackTotalSize(int count, const int *sizes, int gap) const
1285
2760
  {
1286
2761
  int total = 0;
1287
- for (int i = 0; i < count; ++i) total += sizes[i] + (i > 0 ? node_.style.gap : 0);
2762
+ for (int i = 0; i < count; ++i) total += sizes[i] + (i > 0 ? gap : 0);
1288
2763
  return total;
1289
2764
  }
1290
2765
 
1291
- int gridContentOffset(int available, int total, int alignment, int paddingBefore) const
2766
+ void stretchAutoGridTracks(int count, const int8_t *types, int *sizes,
2767
+ int available, int gap, int alignment) const
2768
+ {
2769
+ // CSS Grid track sizing, "Stretch auto Tracks": normal/stretch
2770
+ // distributes remaining space equally to auto tracks, not to items.
2771
+ if (alignment != 0) return;
2772
+ int free = available - gridTrackTotalSize(count, sizes, gap);
2773
+ int autoCount = 0;
2774
+ for (int i = 0; i < count; ++i) if (types[i] == 0) ++autoCount;
2775
+ if (free <= 0 || !autoCount) return;
2776
+ for (int i = 0; i < count; ++i) {
2777
+ if (types[i] != 0) continue;
2778
+ const int extra = free / autoCount;
2779
+ sizes[i] += extra;
2780
+ free -= extra;
2781
+ --autoCount;
2782
+ }
2783
+ }
2784
+
2785
+ int gridContentOffset(int available, int total, int alignment, int index, int count) const
1292
2786
  {
1293
2787
  int free = available - total;
2788
+ if (isDistributedAlignment(alignment)) return distributedAlignmentOffset(alignment, free, index, count);
2789
+ alignment = usedAlignment(alignment, free);
1294
2790
  if (free < 0 && alignment != 1 && alignment != 2) free = 0;
1295
- if (alignment == 1) return paddingBefore + free / 2;
1296
- if (alignment == 2) return paddingBefore + free;
1297
- return paddingBefore;
2791
+ if (alignment == 1) return free / 2;
2792
+ if (alignment == 2) return free;
2793
+ return 0;
1298
2794
  }
1299
2795
 
1300
2796
  void stretchGridChild(int child, Node &childNode, int cellWidth, int cellHeight, int alignX, int alignY)
@@ -1302,13 +2798,13 @@ private:
1302
2798
  bool resized = false;
1303
2799
  const int availableWidth = cellWidth - childNode.style.margin[1] - childNode.style.margin[3];
1304
2800
  const int availableHeight = cellHeight - childNode.style.margin[0] - childNode.style.margin[2];
1305
- const int width = engine_.clampSize(availableWidth < 0 ? 0 : availableWidth, childNode.style.min_width, childNode.style.max_width);
1306
- const int height = engine_.clampSize(availableHeight < 0 ? 0 : availableHeight, childNode.style.min_height, childNode.style.max_height);
1307
- if (alignX == 0 && !hasExplicitWidth(childNode) && childNode.layout.width != width) {
2801
+ const int width = clampLayoutSize(childNode, availableWidth < 0 ? 0 : availableWidth, true);
2802
+ const int height = clampLayoutSize(childNode, availableHeight < 0 ? 0 : availableHeight, false);
2803
+ if (alignX == 0 && !(childNode.style.margin_auto & 10) && !hasExplicitWidth(childNode) && !isIntrinsicSizeExpression(childNode.style.width_expression) && childNode.layout.width != width) {
1308
2804
  childNode.layout.width = width;
1309
2805
  resized = true;
1310
2806
  }
1311
- if (alignY == 0 && !hasExplicitHeight(childNode) && childNode.layout.height != height) {
2807
+ if (alignY == 0 && !(childNode.style.margin_auto & 5) && !hasExplicitHeight(childNode) && !isIntrinsicSizeExpression(childNode.style.height_expression) && childNode.layout.height != height) {
1312
2808
  childNode.layout.height = height;
1313
2809
  resized = true;
1314
2810
  }
@@ -1317,14 +2813,86 @@ private:
1317
2813
 
1318
2814
  void layoutGridChildren(int *children, int childCount, int padWidth, int padHeight, bool allowAutosizeParent)
1319
2815
  {
1320
- if (childCount <= 0) return;
1321
- int columnCount = explicitGridColumnCount(childCount);
1322
- if (columnCount <= 0) return;
1323
- if (columnCount > kMaxGridLayoutTracks) columnCount = kMaxGridLayoutTracks;
1324
- int rowCount = explicitGridRowCount(childCount, columnCount);
1325
- if (rowCount <= 0) return;
1326
- if (rowCount > kMaxGridLayoutTracks) rowCount = kMaxGridLayoutTracks;
2816
+ if (!childCount && !rstyle(node_.style).grid_column_count && !rstyle(node_.style).grid_row_count) {
2817
+ if (auto *rare = rareDataFor(id_)) rare->gridLayout.reset();
2818
+ if (allowAutosizeParent) autosizeEmptyNode();
2819
+ return;
2820
+ }
2821
+ const bool vertical = writingMode(node_) != 0;
2822
+ int columnCount = std::max(childCount ? 1 : 0, int(rstyle(node_.style).grid_column_count));
2823
+ int rowCount = std::max(childCount ? 1 : 0, int(rstyle(node_.style).grid_row_count));
2824
+ struct Placement { GridAxisPlacement column, row; };
2825
+ std::vector<Placement> placements(childCount);
2826
+ int columnOrigin = 0, rowOrigin = 0;
2827
+ for (int i = 0; i < childCount; ++i) {
2828
+ const auto &rs = rstyle(nodes_[children[i]].style);
2829
+ auto &p = placements[i];
2830
+ p.column = gridAxisPlacement(rs.grid_line[1], rs.grid_line[3], rstyle(node_.style).grid_column_count, false);
2831
+ p.row = gridAxisPlacement(rs.grid_line[0], rs.grid_line[2], rstyle(node_.style).grid_row_count, false);
2832
+ if (p.column.start != kUnset) columnOrigin = std::max(columnOrigin, -p.column.start);
2833
+ if (p.row.start != kUnset) rowOrigin = std::max(rowOrigin, -p.row.start);
2834
+ columnCount = std::max(columnCount, p.column.end == kUnset ? p.column.span : p.column.end);
2835
+ if (p.row.end != kUnset) rowCount = std::max(rowCount, p.row.end);
2836
+ }
2837
+ columnOrigin = std::min(columnOrigin, kMaxGridLayoutTracks - 1);
2838
+ rowOrigin = std::min(rowOrigin, kMaxGridLayoutTracks - 1);
2839
+ columnCount = std::min(kMaxGridLayoutTracks, columnCount + columnOrigin);
2840
+ rowCount = std::min(kMaxGridLayoutTracks, rowCount + rowOrigin);
2841
+ uint64_t occupied[kMaxGridLayoutTracks][2] = {};
2842
+ auto fits = [&](int row, int column, int rows, int columns) {
2843
+ if (row + rows > kMaxGridLayoutTracks || column + columns > kMaxGridLayoutTracks) return false;
2844
+ for (int y = row; y < row + rows; ++y)
2845
+ for (int x = column; x < column + columns; ++x)
2846
+ if (occupied[y][x / 64] & (uint64_t{1} << (x % 64))) return false;
2847
+ return true;
2848
+ };
2849
+ auto occupy = [&](Placement &p) {
2850
+ p.row.start = std::clamp(p.row.start, 0, kMaxGridLayoutTracks - p.row.span);
2851
+ p.column.start = std::clamp(p.column.start, 0, kMaxGridLayoutTracks - p.column.span);
2852
+ p.row.end = p.row.start + p.row.span;
2853
+ p.column.end = p.column.start + p.column.span;
2854
+ rowCount = std::max(rowCount, p.row.end);
2855
+ columnCount = std::max(columnCount, p.column.end);
2856
+ for (int y = p.row.start; y < p.row.end; ++y)
2857
+ for (int x = p.column.start; x < p.column.end; ++x)
2858
+ occupied[y][x / 64] |= uint64_t{1} << (x % 64);
2859
+ };
2860
+ for (auto &p : placements) {
2861
+ if (p.row.start != kUnset) p.row.start = std::clamp(p.row.start + rowOrigin, 0, kMaxGridLayoutTracks - p.row.span);
2862
+ if (p.column.start != kUnset) p.column.start = std::clamp(p.column.start + columnOrigin, 0, kMaxGridLayoutTracks - p.column.span);
2863
+ if (p.row.start != kUnset && p.column.start != kUnset) occupy(p);
2864
+ }
2865
+ int rowCursor[kMaxGridLayoutTracks] = {};
2866
+ for (auto &p : placements) {
2867
+ if (p.row.start == kUnset || p.column.start != kUnset) continue;
2868
+ int x = rowCursor[p.row.start];
2869
+ while (x + p.column.span < kMaxGridLayoutTracks && !fits(p.row.start, x, p.row.span, p.column.span)) ++x;
2870
+ p.column.start = x;
2871
+ occupy(p);
2872
+ rowCursor[p.row.start] = p.column.end;
2873
+ }
2874
+ int cursorRow = 0, cursorColumn = 0;
2875
+ for (auto &p : placements) {
2876
+ if (p.row.start != kUnset) continue;
2877
+ if (p.column.start != kUnset) {
2878
+ if (p.column.start < cursorColumn) ++cursorRow;
2879
+ cursorColumn = p.column.start;
2880
+ while (cursorRow + p.row.span < kMaxGridLayoutTracks && !fits(cursorRow, cursorColumn, p.row.span, p.column.span)) ++cursorRow;
2881
+ } else {
2882
+ while (cursorRow + p.row.span <= kMaxGridLayoutTracks) {
2883
+ if (cursorColumn + p.column.span > columnCount) { ++cursorRow; cursorColumn = 0; continue; }
2884
+ if (fits(cursorRow, cursorColumn, p.row.span, p.column.span)) break;
2885
+ ++cursorColumn;
2886
+ }
2887
+ p.column.start = cursorColumn;
2888
+ }
2889
+ p.row.start = cursorRow;
2890
+ occupy(p);
2891
+ cursorColumn = p.column.end;
2892
+ }
1327
2893
 
2894
+ const int columnGap = resolvedGap(node_, false, padWidth, padHeight);
2895
+ const int rowGap = resolvedGap(node_, true, padWidth, padHeight);
1328
2896
  measureGridChildren(children, childCount, padWidth, padHeight);
1329
2897
 
1330
2898
  int8_t columnTypes[kMaxGridLayoutTracks] = {0};
@@ -1332,74 +2900,137 @@ private:
1332
2900
  int16_t columnValues[kMaxGridLayoutTracks] = {0};
1333
2901
  int16_t rowValues[kMaxGridLayoutTracks] = {0};
1334
2902
  for (int i = 0; i < columnCount; ++i) {
1335
- columnTypes[i] = i < rstyle(node_.style).grid_column_count ? rstyle(node_.style).grid_column_type[i] : 0;
1336
- columnValues[i] = i < rstyle(node_.style).grid_column_count ? rstyle(node_.style).grid_column_value[i] : 0;
2903
+ const int track = i - columnOrigin;
2904
+ columnTypes[i] = track >= 0 && track < rstyle(node_.style).grid_column_count ? rstyle(node_.style).grid_column_type[track] : 0;
2905
+ columnValues[i] = track >= 0 && track < rstyle(node_.style).grid_column_count ? rstyle(node_.style).grid_column_value[track] : 0;
1337
2906
  }
1338
2907
  for (int i = 0; i < rowCount; ++i) {
1339
- rowTypes[i] = i < rstyle(node_.style).grid_row_count ? rstyle(node_.style).grid_row_type[i] : 0;
1340
- rowValues[i] = i < rstyle(node_.style).grid_row_count ? rstyle(node_.style).grid_row_value[i] : 0;
2908
+ const int track = i - rowOrigin;
2909
+ rowTypes[i] = track >= 0 && track < rstyle(node_.style).grid_row_count ? rstyle(node_.style).grid_row_type[track] : 0;
2910
+ rowValues[i] = track >= 0 && track < rstyle(node_.style).grid_row_count ? rstyle(node_.style).grid_row_value[track] : 0;
1341
2911
  }
1342
2912
 
1343
2913
  int autoColumns[kMaxGridLayoutTracks] = {0};
1344
2914
  int autoRows[kMaxGridLayoutTracks] = {0};
1345
- computeAutoTrackSizes(children, childCount, columnCount, rowCount, autoColumns, autoRows);
2915
+ // Resolve increasing span lengths. Contributions with the same span
2916
+ // share one set of base sizes and commit their maximum planned growth
2917
+ // together, so source order cannot bias overlapping spans.
2918
+ for (bool columns : {true, false}) {
2919
+ int *sizes = columns ? autoColumns : autoRows;
2920
+ const int8_t *types = columns ? columnTypes : rowTypes;
2921
+ const int16_t *values = columns ? columnValues : rowValues;
2922
+ const int gap = columns ? columnGap : rowGap;
2923
+ const int count = columns ? columnCount : rowCount;
2924
+ int maxSpan = 0;
2925
+ for (const auto &p : placements) maxSpan = std::max(maxSpan, columns ? p.column.span : p.row.span);
2926
+ for (int span = 1; span <= maxSpan; ++span) {
2927
+ int planned[kMaxGridLayoutTracks] = {};
2928
+ std::copy(sizes, sizes + count, planned);
2929
+ for (int i = 0; i < childCount; ++i) {
2930
+ const auto &p = columns ? placements[i].column : placements[i].row;
2931
+ if (p.span != span) continue;
2932
+ const Node &child = nodes_[children[i]];
2933
+ const bool horizontal = columns != vertical;
2934
+ const int size = horizontal ? child.layout.width + child.style.margin[1] + child.style.margin[3]
2935
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
2936
+ int occupied = (span - 1) * gap, autos = 0;
2937
+ for (int t = p.start; t < p.end; ++t) {
2938
+ occupied += types[t] == 1 ? values[t] : sizes[t];
2939
+ if (types[t] == 0) ++autos;
2940
+ }
2941
+ int extra = size - occupied;
2942
+ for (int t = p.start; t < p.end && extra > 0 && autos; ++t) {
2943
+ if (types[t] != 0) continue;
2944
+ const int amount = extra / autos;
2945
+ planned[t] = std::max(planned[t], sizes[t] + amount);
2946
+ extra -= amount; --autos;
2947
+ }
2948
+ }
2949
+ std::copy(planned, planned + count, sizes);
2950
+ }
2951
+ }
1346
2952
 
1347
2953
  int columnSizes[kMaxGridLayoutTracks] = {0};
1348
2954
  int rowSizes[kMaxGridLayoutTracks] = {0};
1349
- computeTrackSizes(columnCount, columnTypes, columnValues, autoColumns, padWidth, columnSizes);
1350
- computeTrackSizes(rowCount, rowTypes, rowValues, autoRows, padHeight, rowSizes);
1351
- if (rstyle(node_.style).grid_column_count == 0 && columnCount == 1) columnSizes[0] = padWidth;
2955
+ computeTrackSizes(columnCount, columnTypes, columnValues, autoColumns, vertical ? padHeight : padWidth, columnGap, columnSizes);
2956
+ computeTrackSizes(rowCount, rowTypes, rowValues, autoRows, vertical ? padWidth : padHeight, rowGap, rowSizes);
2957
+ if (allowAutosizeParent && !hasExplicitWidth(node_) &&
2958
+ rstyle(node_.style).grid_column_count == 0 && columnCount == 1 &&
2959
+ writingMode(node_) == 0 && node_.style.justify_content == 0) columnSizes[0] = padWidth;
1352
2960
 
1353
2961
  if (allowAutosizeParent && !hasExplicitWidth(node_)) {
1354
- int width = node_.style.padding[1] + node_.style.padding[3];
1355
- for (int i = 0; i < columnCount; ++i) width += columnSizes[i] + (i > 0 ? node_.style.gap : 0);
1356
- node_.layout.width = engine_.clampSize(width, node_.style.min_width, node_.style.max_width);
2962
+ int width = boxInset(node_.style, 1) + boxInset(node_.style, 3);
2963
+ width += vertical ? gridTrackTotalSize(rowCount, rowSizes, rowGap) : gridTrackTotalSize(columnCount, columnSizes, columnGap);
2964
+ node_.layout.width = clampLayoutSize(node_, width, true);
1357
2965
  }
1358
2966
  if (allowAutosizeParent && !hasExplicitHeight(node_)) {
1359
- int height = node_.style.padding[0] + node_.style.padding[2];
1360
- for (int i = 0; i < rowCount; ++i) height += rowSizes[i] + (i > 0 ? node_.style.gap : 0);
1361
- node_.layout.height = engine_.clampSize(height, node_.style.min_height, node_.style.max_height);
2967
+ int height = boxInset(node_.style, 0) + boxInset(node_.style, 2);
2968
+ height += vertical ? gridTrackTotalSize(columnCount, columnSizes, columnGap) : gridTrackTotalSize(rowCount, rowSizes, rowGap);
2969
+ node_.layout.height = clampLayoutSize(node_, height, false);
1362
2970
  }
2971
+ // Auto-height grids first derive their size from intrinsic tracks.
2972
+ // A definite size (including one assigned by the parent) can then
2973
+ // contribute free space without making an auto-sized grid fill its parent.
2974
+ padWidth = paddedWidth();
2975
+ padHeight = paddedHeight();
2976
+ stretchAutoGridTracks(columnCount, columnTypes, columnSizes, vertical ? padHeight : padWidth, columnGap, node_.style.justify_content);
2977
+ stretchAutoGridTracks(rowCount, rowTypes, rowSizes, vertical ? padWidth : padHeight, rowGap, node_.style.align_content);
1363
2978
 
1364
2979
  int rowY[kMaxGridLayoutTracks] = {0};
1365
2980
  int columnX[kMaxGridLayoutTracks] = {0};
1366
- const int columnTotal = gridTrackTotalSize(columnCount, columnSizes);
1367
- const int rowTotal = gridTrackTotalSize(rowCount, rowSizes);
1368
- columnX[0] = gridContentOffset(padWidth, columnTotal, node_.style.justify_content, node_.style.padding[3]);
1369
- for (int i = 1; i < columnCount; ++i) columnX[i] = columnX[i - 1] + columnSizes[i - 1] + node_.style.gap;
1370
- // A single implicit row (no grid-template-rows) is positioned by align-items,
1371
- // not align-content, so place-items:center can vertically center a lone child
1372
- // when the container is taller than its content (e.g. a position:absolute
1373
- // inset:0 face). Without this the child pins to the top (align-content
1374
- // defaults to start). Mirrors the single implicit column filling width above.
1375
- const int rowBlockAlign = (rstyle(node_.style).grid_row_count == 0 && rowCount == 1)
1376
- ? node_.style.align_items
1377
- : node_.style.align_content;
1378
- rowY[0] = gridContentOffset(padHeight, rowTotal, rowBlockAlign, node_.style.padding[0]);
1379
- for (int i = 1; i < rowCount; ++i) rowY[i] = rowY[i - 1] + rowSizes[i - 1] + node_.style.gap;
2981
+ const int columnTotal = gridTrackTotalSize(columnCount, columnSizes, columnGap);
2982
+ const int rowTotal = gridTrackTotalSize(rowCount, rowSizes, rowGap);
2983
+ int columnPosition = 0, rowPosition = 0;
2984
+ for (int i = 0; i < columnCount; ++i) {
2985
+ columnX[i] = columnPosition + gridContentOffset(vertical ? padHeight : padWidth, columnTotal, node_.style.justify_content, i, columnCount);
2986
+ columnPosition += columnSizes[i] + columnGap;
2987
+ }
2988
+ for (int i = 0; i < rowCount; ++i) {
2989
+ rowY[i] = rowPosition + gridContentOffset(vertical ? padWidth : padHeight, rowTotal, node_.style.align_content, i, rowCount);
2990
+ rowPosition += rowSizes[i] + rowGap;
2991
+ }
1380
2992
 
2993
+ auto &rare = ensureRareData(id_);
2994
+ if (!rare.gridLayout) rare.gridLayout = std::make_unique<GridTrackLayout>();
2995
+ auto &tracks = *rare.gridLayout;
2996
+ tracks.columnOrigin = columnOrigin; tracks.rowOrigin = rowOrigin;
2997
+ tracks.columnStart.assign(columnX, columnX + columnCount);
2998
+ tracks.rowStart.assign(rowY, rowY + rowCount);
2999
+ tracks.columnEnd.resize(columnCount); tracks.rowEnd.resize(rowCount);
3000
+ for (int i = 0; i < columnCount; ++i) tracks.columnEnd[i] = columnX[i] + columnSizes[i];
3001
+ for (int i = 0; i < rowCount; ++i) tracks.rowEnd[i] = rowY[i] + rowSizes[i];
1381
3002
  for (int i = 0; i < childCount; ++i) {
1382
- const int column = i % columnCount;
1383
- const int row = i / columnCount;
1384
- if (row >= rowCount) break;
3003
+ const auto &p = placements[i];
1385
3004
  const int child = children[i];
1386
3005
  Node &childNode = nodes_[child];
1387
- const int cellWidth = columnSizes[column];
1388
- const int cellHeight = rowSizes[row];
3006
+ int cellX, cellY, cellWidth, cellHeight;
3007
+ gridPhysicalRange(node_, true, columnX[p.column.start], tracks.columnEnd[p.column.end - 1], vertical ? cellY : cellX, vertical ? cellHeight : cellWidth);
3008
+ gridPhysicalRange(node_, false, rowY[p.row.start], tracks.rowEnd[p.row.end - 1], vertical ? cellX : cellY, vertical ? cellWidth : cellHeight);
1389
3009
  engine_.layoutNode(child, cellWidth, cellHeight);
1390
-
1391
- const int alignX = childNode.style.align_self >= 0 ? childNode.style.align_self : node_.style.justify_items;
1392
- const int alignY = childNode.style.align_self >= 0 ? childNode.style.align_self : node_.style.align_items;
3010
+ const int inlineAlign = rstyle(childNode.style).justify_self >= 0 ? rstyle(childNode.style).justify_self : node_.style.justify_items;
3011
+ const int blockAlign = childNode.style.align_self >= 0 ? childNode.style.align_self : node_.style.align_items;
3012
+ const int alignX = vertical ? blockAlign : inlineAlign;
3013
+ const int alignY = vertical ? inlineAlign : blockAlign;
1393
3014
  stretchGridChild(child, childNode, cellWidth, cellHeight, alignX, alignY);
1394
3015
 
1395
- int x = columnX[column] + childNode.style.margin[3];
1396
- int y = rowY[row] + childNode.style.margin[0];
3016
+ int x = cellX + childNode.style.margin[3];
3017
+ int y = cellY + childNode.style.margin[0];
1397
3018
  const int freeX = cellWidth - childNode.layout.width - childNode.style.margin[1] - childNode.style.margin[3];
1398
3019
  const int freeY = cellHeight - childNode.layout.height - childNode.style.margin[0] - childNode.style.margin[2];
1399
- if (alignX == 1 && freeX > 0) x += freeX / 2;
1400
- else if (alignX == 2 && freeX > 0) x += freeX;
1401
- if (alignY == 1 && freeY > 0) y += freeY / 2;
1402
- else if (alignY == 2 && freeY > 0) y += freeY;
3020
+ const int usedX = usedGridAlignment(node_, childNode, alignX, freeX, true);
3021
+ const int usedY = usedGridAlignment(node_, childNode, alignY, freeY, false);
3022
+ // Auto margins consume positive free space before self-alignment and
3023
+ // suppress it even when the item overflows the grid area.
3024
+ if (childNode.style.margin_auto & 10) {
3025
+ if (freeX > 0 && (childNode.style.margin_auto & 8))
3026
+ x += (childNode.style.margin_auto & 2) ? freeX / 2 : freeX;
3027
+ } else if (usedX == 1) x += freeX / 2;
3028
+ else if (usedX == 2) x += freeX;
3029
+ if (childNode.style.margin_auto & 5) {
3030
+ if (freeY > 0 && (childNode.style.margin_auto & 1))
3031
+ y += (childNode.style.margin_auto & 4) ? freeY / 2 : freeY;
3032
+ } else if (usedY == 1) y += freeY / 2;
3033
+ else if (usedY == 2) y += freeY;
1403
3034
  childNode.layout.x = x;
1404
3035
  childNode.layout.y = y;
1405
3036
  }
@@ -1415,31 +3046,39 @@ private:
1415
3046
  if (!hasExplicitHeight(node_)) {
1416
3047
  contentHeight -= node_.style.margin[0] + node_.style.margin[2];
1417
3048
  }
1418
- contentWidth = engine_.clampSize(contentWidth, node_.style.min_width, node_.style.max_width);
1419
- contentHeight = engine_.clampSize(contentHeight, node_.style.min_height, node_.style.max_height);
1420
3049
 
1421
- node_.layout.width = contentWidth;
1422
- node_.layout.height = contentHeight;
3050
+ if (hasExplicitWidth(node_)) contentWidth = contentSizeToBorderSize(node_.style, contentWidth, true);
3051
+ if (hasExplicitHeight(node_)) contentHeight = contentSizeToBorderSize(node_.style, contentHeight, false);
3052
+ node_.layout.width = clampLayoutSize(node_, contentWidth, true);
3053
+ node_.layout.height = clampLayoutSize(node_, contentHeight, false);
3054
+ // Resolve a definite ratio-derived axis before measuring percentage
3055
+ // descendants. Final sizing can still grow to the content-based minimum.
3056
+ if (preferredRatio(node_) > 0) {
3057
+ if (hasExplicitWidth(node_) && !hasExplicitHeight(node_))
3058
+ node_.layout.height = clampLayoutSize(node_, ratioTransferredSize(node_, node_.layout.width, false), false);
3059
+ else if (hasExplicitHeight(node_) && !hasExplicitWidth(node_))
3060
+ node_.layout.width = clampLayoutSize(node_, ratioTransferredSize(node_, node_.layout.height, true), true);
3061
+ }
1423
3062
  }
1424
3063
 
1425
3064
  int paddedWidth() const
1426
3065
  {
1427
- int width = node_.layout.width - node_.style.padding[1] - node_.style.padding[3];
3066
+ int width = node_.layout.width - boxInset(node_.style, 1) - boxInset(node_.style, 3);
1428
3067
  return width < 0 ? 0 : width;
1429
3068
  }
1430
3069
 
1431
3070
  int paddedHeight() const
1432
3071
  {
1433
- int height = node_.layout.height - node_.style.padding[0] - node_.style.padding[2];
3072
+ int height = node_.layout.height - boxInset(node_.style, 0) - boxInset(node_.style, 2);
1434
3073
  return height < 0 ? 0 : height;
1435
3074
  }
1436
3075
 
1437
3076
  void autosizeEmptyNode()
1438
3077
  {
1439
- if (!hasExplicitWidth(node_)) node_.layout.width = node_.style.padding[1] + node_.style.padding[3];
1440
- if (!hasExplicitHeight(node_)) node_.layout.height = node_.style.padding[0] + node_.style.padding[2];
1441
- node_.layout.width = engine_.clampSize(node_.layout.width, node_.style.min_width, node_.style.max_width);
1442
- node_.layout.height = engine_.clampSize(node_.layout.height, node_.style.min_height, node_.style.max_height);
3078
+ if (!hasExplicitWidth(node_)) node_.layout.width = boxInset(node_.style, 1) + boxInset(node_.style, 3);
3079
+ if (!hasExplicitHeight(node_)) node_.layout.height = boxInset(node_.style, 0) + boxInset(node_.style, 2);
3080
+ node_.layout.width = clampLayoutSize(node_, node_.layout.width, true);
3081
+ node_.layout.height = clampLayoutSize(node_, node_.layout.height, false);
1443
3082
  // A <virtual-list>'s scroll geometry is owned by
1444
3083
  // applyVirtualListContentHeight() (invoked right after this in the
1445
3084
  // empty-node branch). Its recycled slot pool is entirely
@@ -1467,14 +3106,18 @@ private:
1467
3106
  if (node_.type == NodeType::VirtualList) return;
1468
3107
  int contentWidth = node_.layout.width;
1469
3108
  int contentHeight = node_.layout.height;
1470
- for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
3109
+ visitFormattingChildren(nodes_, id_, [&](int child) {
1471
3110
  Node &childNode = nodes_[child];
1472
- if (isDisplayNone(childNode.style) || childNode.style.position == 1) continue;
1473
- const int right = childNode.layout.x + childNode.layout.width + childNode.style.margin[1] + node_.style.padding[1];
3111
+ if (isCollapsedFlexItem(childNode) || isDisplayNone(childNode.style) || isOutOfFlowPosition(childNode.style.position)) return;
3112
+ // A visible axis contributes descendant overflow; a clipping axis
3113
+ // traps it at this child's border box independently of the other axis.
3114
+ const int width = overflowX(childNode.style) == 0 ? std::max<int>(childNode.layout.width, childNode.layout.scroll_content_width) : childNode.layout.width;
3115
+ const int height = overflowY(childNode.style) == 0 ? std::max<int>(childNode.layout.height, childNode.layout.scroll_content_height) : childNode.layout.height;
3116
+ const int right = childNode.layout.x + width + childNode.style.margin[1] + boxInset(node_.style, 1);
1474
3117
  if (right > contentWidth) contentWidth = right;
1475
- const int bottom = childNode.layout.y + childNode.layout.height + childNode.style.margin[2] + node_.style.padding[2];
3118
+ const int bottom = childNode.layout.y + height + childNode.style.margin[2] + boxInset(node_.style, 2);
1476
3119
  if (bottom > contentHeight) contentHeight = bottom;
1477
- }
3120
+ });
1478
3121
  node_.layout.scroll_content_width = contentWidth;
1479
3122
  node_.layout.scroll_content_height = contentHeight;
1480
3123
 
@@ -1521,14 +3164,50 @@ private:
1521
3164
  if (node_.layout.scroll_y > maxScroll) node_.layout.scroll_y = maxScroll;
1522
3165
  }
1523
3166
 
3167
+ void captureBlockStaticPositions()
3168
+ {
3169
+ for (int c = node_.first_child; c >= 0; c = nodes_[c].next_sibling)
3170
+ if (isOutOfFlowPosition(nodes_[c].style.position)) nodes_[c].layout.static_block_axis = 0;
3171
+ if (node_.style.display != kDisplayBlock || node_.style.flex_direction_explicit ||
3172
+ (LayoutEngine::isInlineLevelNode(node_) && !isOutOfFlowPosition(node_.style.position))) return;
3173
+ const bool vertical = writingMode(node_) != 0;
3174
+ const bool reversed = vertical && gridAxisReversed(node_, true);
3175
+ int cursor = boxInset(node_.style, blockMarginSide(false));
3176
+ bool first = true;
3177
+ CollapsedMargin pending;
3178
+ visitFormattingChildren(nodes_, id_, [&](int id) {
3179
+ Node &child = nodes_[id];
3180
+ if (isDisplayNone(child.style)) return;
3181
+ if (isOutOfFlowPosition(child.style.position)) {
3182
+ if (child.parent != id_ || !blockBox(child)) return;
3183
+ const int edge = cursor + (first && collapsesWithChildren(id_, false) ? 0 : pending.value());
3184
+ child.layout.static_block_start = clampInt16(reversed ? node_.layout.width - edge : edge);
3185
+ child.layout.static_block_axis = vertical ? 2 : 1;
3186
+ return;
3187
+ }
3188
+ if (child.style.float_side || suppressAnonymousWhitespace(nodes_, child.parent, id)) return;
3189
+ if (blockBox(child) && collapsesThrough(id)) {
3190
+ pending.add(childEdgeMargin(id_, id, false));
3191
+ return;
3192
+ }
3193
+ const int end = vertical ? (reversed ? node_.layout.width - child.layout.x : child.layout.x + child.layout.width)
3194
+ : child.layout.y + child.layout.height;
3195
+ cursor = blockBox(child) ? end : std::max(cursor, end);
3196
+ pending = blockBox(child) ? childEdgeMargin(id_, id, true) : CollapsedMargin{};
3197
+ first = false;
3198
+ });
3199
+ }
3200
+
1524
3201
  void positionAbsoluteChildren()
1525
3202
  {
3203
+ captureBlockStaticPositions();
1526
3204
  for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
1527
3205
  Node &childNode = nodes_[child];
1528
- if (isDisplayNone(childNode.style) || childNode.style.position != 1) continue;
3206
+ if (isDisplayNone(childNode.style) || !isOutOfFlowPosition(childNode.style.position)) continue;
1529
3207
 
1530
- const int childAvailWidth = node_.layout.width;
1531
- const int childAvailHeight = node_.layout.height;
3208
+ int childAvailWidth, childAvailHeight;
3209
+ int areaX, areaY;
3210
+ LayoutEngine::absoluteContainingArea(node_, childNode, areaX, areaY, childAvailWidth, childAvailHeight);
1532
3211
  engine_.layoutNode(child, childAvailWidth, childAvailHeight);
1533
3212
  stretchAbsoluteChild(child, childNode, childAvailWidth, childAvailHeight);
1534
3213
  positionAbsoluteChild(childNode);
@@ -1538,26 +3217,26 @@ private:
1538
3217
  void stretchAbsoluteChild(int child, Node &childNode, int childAvailWidth, int childAvailHeight)
1539
3218
  {
1540
3219
  bool resized = false;
1541
- if (!hasExplicitWidth(childNode) &&
3220
+ if (!hasExplicitWidth(childNode) && !isIntrinsicSizeExpression(childNode.style.width_expression) &&
1542
3221
  hasPositionOffset(childNode, 3) &&
1543
3222
  hasPositionOffset(childNode, 1)) {
1544
- int width = childAvailWidth - resolvedPositionOffset(childNode, 3) - resolvedPositionOffset(childNode, 1) -
3223
+ int width = childAvailWidth - resolvedPositionOffsetWithBasis(childNode, 3, childAvailWidth) - resolvedPositionOffsetWithBasis(childNode, 1, childAvailWidth) -
1545
3224
  childNode.style.margin[1] - childNode.style.margin[3];
1546
3225
  if (width < 0) width = 0;
1547
- width = engine_.clampSize(width, childNode.style.min_width, childNode.style.max_width);
3226
+ width = clampLayoutSize(childNode, width, true);
1548
3227
  if (childNode.layout.width != width) {
1549
3228
  childNode.layout.width = width;
1550
3229
  resized = true;
1551
3230
  }
1552
3231
  }
1553
3232
 
1554
- if (!hasExplicitHeight(childNode) &&
3233
+ if (!hasExplicitHeight(childNode) && !isIntrinsicSizeExpression(childNode.style.height_expression) &&
1555
3234
  hasPositionOffset(childNode, 0) &&
1556
3235
  hasPositionOffset(childNode, 2)) {
1557
- int height = childAvailHeight - resolvedPositionOffset(childNode, 0) - resolvedPositionOffset(childNode, 2) -
3236
+ int height = childAvailHeight - resolvedPositionOffsetWithBasis(childNode, 0, childAvailHeight) - resolvedPositionOffsetWithBasis(childNode, 2, childAvailHeight) -
1558
3237
  childNode.style.margin[0] - childNode.style.margin[2];
1559
3238
  if (height < 0) height = 0;
1560
- height = engine_.clampSize(height, childNode.style.min_height, childNode.style.max_height);
3239
+ height = clampLayoutSize(childNode, height, false);
1561
3240
  if (childNode.layout.height != height) {
1562
3241
  childNode.layout.height = height;
1563
3242
  resized = true;
@@ -1569,58 +3248,39 @@ private:
1569
3248
 
1570
3249
  void positionAbsoluteChild(Node &childNode)
1571
3250
  {
1572
- if (hasPositionOffset(childNode, 3))
1573
- childNode.layout.x = resolvedPositionOffset(childNode, 3);
1574
- else if (hasPositionOffset(childNode, 1))
1575
- childNode.layout.x = node_.layout.width - childNode.layout.width - resolvedPositionOffset(childNode, 1);
1576
- else
1577
- childNode.layout.x = alignedAbsoluteChildPosition(childNode, true);
1578
-
1579
- if (hasPositionOffset(childNode, 0))
1580
- childNode.layout.y = resolvedPositionOffset(childNode, 0);
1581
- else if (hasPositionOffset(childNode, 2))
1582
- childNode.layout.y = node_.layout.height - childNode.layout.height - resolvedPositionOffset(childNode, 2);
1583
- else
1584
- childNode.layout.y = alignedAbsoluteChildPosition(childNode, false);
3251
+ int x, y, width, height;
3252
+ LayoutEngine::absoluteContainingArea(node_, childNode, x, y, width, height);
3253
+ if (hasPositionOffset(childNode, 3)) childNode.layout.x = x + resolvedPositionOffsetWithBasis(childNode, 3, width) + childNode.style.margin[3];
3254
+ else if (hasPositionOffset(childNode, 1)) childNode.layout.x = x + width - childNode.layout.width - resolvedPositionOffsetWithBasis(childNode, 1, width) - childNode.style.margin[1];
3255
+ else childNode.layout.x = alignedAbsoluteChildPosition(childNode, true);
3256
+ if (hasPositionOffset(childNode, 0)) childNode.layout.y = y + resolvedPositionOffsetWithBasis(childNode, 0, height) + childNode.style.margin[0];
3257
+ else if (hasPositionOffset(childNode, 2)) childNode.layout.y = y + height - childNode.layout.height - resolvedPositionOffsetWithBasis(childNode, 2, height) - childNode.style.margin[2];
3258
+ else childNode.layout.y = alignedAbsoluteChildPosition(childNode, false);
1585
3259
  }
1586
3260
 
1587
3261
  int alignedAbsoluteChildPosition(const Node &childNode, bool horizontal) const
1588
3262
  {
1589
- const bool row = usesRowLayout(node_.style);
1590
- const int crossAlign = childNode.style.align_self >= 0 ? childNode.style.align_self : node_.style.align_items;
1591
- const int align = horizontal
1592
- ? (row ? node_.style.justify_content : crossAlign)
1593
- : (row ? crossAlign : node_.style.justify_content);
1594
- const int parentSize = horizontal ? node_.layout.width : node_.layout.height;
1595
- const int childSize = horizontal ? childNode.layout.width : childNode.layout.height;
1596
- const int beforeMargin = horizontal ? childNode.style.margin[3] : childNode.style.margin[0];
1597
- const int afterMargin = horizontal ? childNode.style.margin[1] : childNode.style.margin[2];
1598
- int available = parentSize;
1599
- if (available < 0) available = 0;
1600
- const int occupied = childSize + beforeMargin + afterMargin;
1601
- int free = available - occupied;
1602
- if (free < 0) free = 0;
1603
-
1604
- int position = beforeMargin;
1605
- if (align == 1) position += free / 2;
1606
- else if (align == 2) position += free;
1607
- return position;
3263
+ return LayoutEngine::alignedAbsoluteOffset(node_, childNode, horizontal);
1608
3264
  }
1609
3265
 
1610
3266
  void applyRelativeOffsets()
1611
3267
  {
1612
- for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
1613
- Node &childNode = nodes_[child];
1614
- if (childNode.style.position != 2) continue;
1615
- if (hasPositionOffset(childNode, 0))
1616
- childNode.layout.y += resolvedRelativePositionOffset(childNode, 0);
1617
- else if (hasPositionOffset(childNode, 2))
1618
- childNode.layout.y -= resolvedRelativePositionOffset(childNode, 2);
1619
- if (hasPositionOffset(childNode, 3))
1620
- childNode.layout.x += resolvedRelativePositionOffset(childNode, 3);
1621
- else if (hasPositionOffset(childNode, 1))
1622
- childNode.layout.x -= resolvedRelativePositionOffset(childNode, 1);
1623
- }
3268
+ auto apply = [&](auto &&self, int parent) -> void {
3269
+ for (int child = nodes_[parent].first_child; child >= 0; child = nodes_[child].next_sibling) {
3270
+ Node &childNode = nodes_[child];
3271
+ if (splitInlineChildren_ && splitInlineWrapper(nodes_, child)) self(self, child);
3272
+ if (childNode.style.position != 2) continue;
3273
+ if (hasPositionOffset(childNode, 0))
3274
+ childNode.layout.y += resolvedRelativePositionOffset(childNode, 0);
3275
+ else if (hasPositionOffset(childNode, 2))
3276
+ childNode.layout.y -= resolvedRelativePositionOffset(childNode, 2);
3277
+ if (hasPositionOffset(childNode, 3))
3278
+ childNode.layout.x += resolvedRelativePositionOffset(childNode, 3);
3279
+ else if (hasPositionOffset(childNode, 1))
3280
+ childNode.layout.x -= resolvedRelativePositionOffset(childNode, 1);
3281
+ }
3282
+ };
3283
+ apply(apply, id_);
1624
3284
  }
1625
3285
 
1626
3286
  bool hasPositionOffset(const Node &node, int side) const
@@ -1661,13 +3321,28 @@ private:
1661
3321
  Node &node_;
1662
3322
  };
1663
3323
 
3324
+ bool establishesTransformContainingBlock(const Node &node)
3325
+ {
3326
+ if (!ViewRenderer::isTransformableBox(node)) return false;
3327
+ const auto &r = rstyle(node.style);
3328
+ return r.translate_present || r.transform_present || r.rotate_present || r.scale_present || r.filter_present || r.transform_preserve_3d ||
3329
+ r.transform_rotate || r.transform_rotate_x || r.transform_rotate_y ||
3330
+ composedTranslateX(r) || composedTranslateY(r) || composedTranslateZ(r) ||
3331
+ composedTranslateXPercent(r) || composedTranslateYPercent(r) ||
3332
+ r.transform_scale_x != 1000 || r.transform_scale_y != 1000 || r.transform_scale_z != 1000 || r.perspective || r.filter_blur_radius;
3333
+ }
3334
+
1664
3335
  bool establishesAbsoluteContainingBlock(const Node &node)
1665
3336
  {
1666
- return node.style.position == 1 || node.style.position == 2;
3337
+ return isOutOfFlowPosition(node.style.position) || node.style.position == 2 || establishesTransformContainingBlock(node);
1667
3338
  }
1668
3339
 
1669
3340
  int containingBlockForAbsoluteNode(int node, int root, Node *nodes)
1670
3341
  {
3342
+ if (nodes[node].style.position == kPositionFixed) {
3343
+ const int fixed = LayoutEngine::fixedContainingBlock(nodes[node]);
3344
+ return fixed >= 0 ? fixed : root;
3345
+ }
1671
3346
  for (int cursor = nodes[node].parent; cursor >= 0; cursor = nodes[cursor].parent) {
1672
3347
  if (establishesAbsoluteContainingBlock(nodes[cursor])) return cursor;
1673
3348
  }
@@ -1709,7 +3384,7 @@ void stretchAbsoluteNodeToContainingBlock(int node, int containingWidth, int con
1709
3384
  {
1710
3385
  Node &absolute = nodes[node];
1711
3386
  bool resized = false;
1712
- if (!hasExplicitWidth(absolute) &&
3387
+ if (!hasExplicitWidth(absolute) && !isIntrinsicSizeExpression(absolute.style.width_expression) &&
1713
3388
  hasPositionOffsetValue(absolute, 3) &&
1714
3389
  hasPositionOffsetValue(absolute, 1)) {
1715
3390
  int width = containingWidth -
@@ -1717,14 +3392,14 @@ void stretchAbsoluteNodeToContainingBlock(int node, int containingWidth, int con
1717
3392
  resolvedPositionOffsetForBasis(absolute, 1, containingWidth) -
1718
3393
  absolute.style.margin[1] - absolute.style.margin[3];
1719
3394
  if (width < 0) width = 0;
1720
- width = LayoutEngine::instance().clampSize(width, absolute.style.min_width, absolute.style.max_width);
3395
+ width = clampLayoutSize(absolute, width, true);
1721
3396
  if (absolute.layout.width != width) {
1722
3397
  absolute.layout.width = width;
1723
3398
  resized = true;
1724
3399
  }
1725
3400
  }
1726
3401
 
1727
- if (!hasExplicitHeight(absolute) &&
3402
+ if (!hasExplicitHeight(absolute) && !isIntrinsicSizeExpression(absolute.style.height_expression) &&
1728
3403
  hasPositionOffsetValue(absolute, 0) &&
1729
3404
  hasPositionOffsetValue(absolute, 2)) {
1730
3405
  int height = containingHeight -
@@ -1732,7 +3407,7 @@ void stretchAbsoluteNodeToContainingBlock(int node, int containingWidth, int con
1732
3407
  resolvedPositionOffsetForBasis(absolute, 2, containingHeight) -
1733
3408
  absolute.style.margin[0] - absolute.style.margin[2];
1734
3409
  if (height < 0) height = 0;
1735
- height = LayoutEngine::instance().clampSize(height, absolute.style.min_height, absolute.style.max_height);
3410
+ height = clampLayoutSize(absolute, height, false);
1736
3411
  if (absolute.layout.height != height) {
1737
3412
  absolute.layout.height = height;
1738
3413
  resized = true;
@@ -1742,49 +3417,118 @@ void stretchAbsoluteNodeToContainingBlock(int node, int containingWidth, int con
1742
3417
  if (resized) LayoutEngine::instance().repositionChildren(node);
1743
3418
  }
1744
3419
 
3420
+ void layoutAbsoluteNode(int node, int containing, int areaX, int areaWidth, int areaHeight, Node *nodes)
3421
+ {
3422
+ Node &absolute = nodes[node];
3423
+ auto &engine = LayoutEngine::instance();
3424
+ const bool left = hasPositionOffsetValue(absolute, 3), right = hasPositionOffsetValue(absolute, 1);
3425
+ if (absolute.type != NodeType::View || writingMode(absolute) != 0 ||
3426
+ hasExplicitWidth(absolute) || isIntrinsicSizeExpression(absolute.style.width_expression) ||
3427
+ (left && right) || (preferredRatio(absolute) > 0 && hasExplicitHeight(absolute))) {
3428
+ engine.layoutNode(node, areaWidth, areaHeight);
3429
+ return;
3430
+ }
3431
+ // Auto inline sizes shrink to fit the space from their resolved inset (or
3432
+ // static position) to the opposite containing-block edge. Keep the actual
3433
+ // containing width for percentages during the final used-width layout.
3434
+ IntrinsicSizeScope scope(absolute, 1);
3435
+ engine.layoutNode(node, 1, areaHeight, true);
3436
+ const int minimum = std::max(0, absolute.layout.width - boxInsets(absolute.style, true));
3437
+ scope.constraint = 2;
3438
+ engine.layoutNode(node, 32767, areaHeight, true);
3439
+ const int maximum = std::max(minimum, absolute.layout.width - boxInsets(absolute.style, true));
3440
+ resolveLayoutBoxLengths(node, areaWidth);
3441
+ int available = areaWidth - absolute.style.margin[3] - absolute.style.margin[1];
3442
+ if (left || right) {
3443
+ available -= resolvedPositionOffsetForBasis(absolute, left ? 3 : 1, areaWidth);
3444
+ } else {
3445
+ int parentX = 0, parentY = 0;
3446
+ offsetFromAncestorToNode(containing, absolute.parent, nodes, &parentX, &parentY);
3447
+ const int staticX = parentX + engine.alignedAbsoluteOffset(nodes[absolute.parent], absolute, true);
3448
+ available = rightToLeft(nodes[absolute.parent])
3449
+ ? staticX + absolute.layout.width - areaX - absolute.style.margin[3]
3450
+ : areaX + areaWidth - staticX - absolute.style.margin[1];
3451
+ }
3452
+ const int edges = boxInsets(absolute.style, true);
3453
+ scope.borderSize = edges + std::min(maximum, std::max(minimum, available - edges));
3454
+ scope.constraint = 0;
3455
+ engine.layoutNode(node, areaWidth, areaHeight);
3456
+ }
3457
+
1745
3458
  void positionAbsoluteNodeInContainingBlock(int node, int containing, Node *nodes)
1746
3459
  {
1747
3460
  Node &absolute = nodes[node];
1748
3461
  const Node &containingNode = nodes[containing];
1749
3462
  const int parent = absolute.parent;
1750
3463
  if (parent < 0) return;
3464
+ if (LayoutEngine::isViewportFixed(absolute)) {
3465
+ const int width = containingNode.layout.memo_avail_w;
3466
+ const int height = containingNode.layout.memo_avail_h;
3467
+ LayoutEngine::instance().layoutNode(node, width, height);
3468
+ stretchAbsoluteNodeToContainingBlock(node, width, height, nodes);
3469
+ int staticX = LayoutEngine::alignedAbsoluteOffset(nodes[parent], absolute, true);
3470
+ int staticY = LayoutEngine::alignedAbsoluteOffset(nodes[parent], absolute, false);
3471
+ for (int id = parent; id >= 0; id = nodes[id].parent) {
3472
+ staticX += nodes[id].layout.x; staticY += nodes[id].layout.y;
3473
+ if (LayoutEngine::isViewportFixed(nodes[id])) break;
3474
+ }
3475
+ absolute.layout.x = hasPositionOffsetValue(absolute, 3) ? resolvedPositionOffsetForBasis(absolute, 3, width) + absolute.style.margin[3]
3476
+ : hasPositionOffsetValue(absolute, 1) ? width - absolute.layout.width - resolvedPositionOffsetForBasis(absolute, 1, width) - absolute.style.margin[1] : staticX;
3477
+ absolute.layout.y = hasPositionOffsetValue(absolute, 0) ? resolvedPositionOffsetForBasis(absolute, 0, height) + absolute.style.margin[0]
3478
+ : hasPositionOffsetValue(absolute, 2) ? height - absolute.layout.height - resolvedPositionOffsetForBasis(absolute, 2, height) - absolute.style.margin[2] : staticY;
3479
+ return;
3480
+ }
1751
3481
 
1752
- stretchAbsoluteNodeToContainingBlock(node, containingNode.layout.width, containingNode.layout.height, nodes);
1753
-
1754
- int parentOffsetX = 0;
1755
- int parentOffsetY = 0;
3482
+ int areaX, areaY, areaWidth, areaHeight;
3483
+ LayoutEngine::absoluteContainingArea(containingNode, absolute, areaX, areaY, areaWidth, areaHeight);
3484
+ // The provisional parent pass may have measured this box against a static
3485
+ // wrapper (or an as-yet-unsized grid). Resolve dimensions using the same
3486
+ // final containing block that supplies its insets. The static-position
3487
+ // rectangle still comes from the parent, but alignment must use the final
3488
+ // dimensions (for example, a percentage-sized child centered in a grid
3489
+ // whose containing block is an outer positioned ancestor).
3490
+ layoutAbsoluteNode(node, containing, areaX, areaWidth, areaHeight, nodes);
3491
+ stretchAbsoluteNodeToContainingBlock(node, areaWidth, areaHeight, nodes);
3492
+ int parentOffsetX = 0, parentOffsetY = 0;
1756
3493
  offsetFromAncestorToNode(containing, parent, nodes, &parentOffsetX, &parentOffsetY);
3494
+ if (!hasPositionOffsetValue(absolute, 3) && !hasPositionOffsetValue(absolute, 1))
3495
+ absolute.layout.x = LayoutEngine::alignedAbsoluteOffset(nodes[parent], absolute, true, &containingNode, areaX - parentOffsetX, areaWidth);
3496
+ if (!hasPositionOffsetValue(absolute, 0) && !hasPositionOffsetValue(absolute, 2))
3497
+ absolute.layout.y = LayoutEngine::alignedAbsoluteOffset(nodes[parent], absolute, false, &containingNode, areaY - parentOffsetY, areaHeight);
1757
3498
 
1758
3499
  int containingX = absolute.layout.x + parentOffsetX;
1759
3500
  if (hasPositionOffsetValue(absolute, 3))
1760
- containingX = resolvedPositionOffsetForBasis(absolute, 3, containingNode.layout.width);
3501
+ containingX = areaX + resolvedPositionOffsetForBasis(absolute, 3, areaWidth) + absolute.style.margin[3];
1761
3502
  else if (hasPositionOffsetValue(absolute, 1))
1762
- containingX = containingNode.layout.width - absolute.layout.width -
1763
- resolvedPositionOffsetForBasis(absolute, 1, containingNode.layout.width);
3503
+ containingX = areaX + areaWidth - absolute.layout.width -
3504
+ resolvedPositionOffsetForBasis(absolute, 1, areaWidth) - absolute.style.margin[1];
1764
3505
 
1765
3506
  int containingY = absolute.layout.y + parentOffsetY;
1766
3507
  if (hasPositionOffsetValue(absolute, 0))
1767
- containingY = resolvedPositionOffsetForBasis(absolute, 0, containingNode.layout.height);
3508
+ containingY = areaY + resolvedPositionOffsetForBasis(absolute, 0, areaHeight) + absolute.style.margin[0];
1768
3509
  else if (hasPositionOffsetValue(absolute, 2))
1769
- containingY = containingNode.layout.height - absolute.layout.height -
1770
- resolvedPositionOffsetForBasis(absolute, 2, containingNode.layout.height);
3510
+ containingY = areaY + areaHeight - absolute.layout.height -
3511
+ resolvedPositionOffsetForBasis(absolute, 2, areaHeight) - absolute.style.margin[2];
1771
3512
 
1772
3513
  absolute.layout.x = containingX - parentOffsetX;
1773
3514
  absolute.layout.y = containingY - parentOffsetY;
1774
3515
  }
1775
3516
 
1776
- void resolveAbsoluteContainingBlocks(int root)
3517
+ void resolvePositionedDescendants(int node, int root, Node *nodes)
1777
3518
  {
1778
- Node *nodes = Tree::instance().nodes();
1779
- const int nodeCount = Tree::instance().nodeCount();
1780
- for (int node = 0; node < nodeCount; ++node) {
1781
- if (isDisplayNone(nodes[node].style) || nodes[node].style.position != 1 || nodes[node].parent < 0) continue;
1782
- const int containing = containingBlockForAbsoluteNode(node, root, nodes);
1783
- if (containing < 0) continue;
1784
- positionAbsoluteNodeInContainingBlock(node, containing, nodes);
3519
+ for (int child = nodes[node].first_child; child >= 0; child = nodes[child].next_sibling) {
3520
+ if (isDisplayNone(nodes[child].style)) continue;
3521
+ if (isOutOfFlowPosition(nodes[child].style.position))
3522
+ positionAbsoluteNodeInContainingBlock(child, containingBlockForAbsoluteNode(child, root, nodes), nodes);
3523
+ resolvePositionedDescendants(child, root, nodes);
1785
3524
  }
1786
3525
  }
1787
3526
 
3527
+ void resolveAbsoluteContainingBlocks(int root)
3528
+ {
3529
+ resolvePositionedDescendants(root, root, Tree::instance().nodes());
3530
+ }
3531
+
1788
3532
  } // namespace
1789
3533
 
1790
3534
  LayoutEngine &LayoutEngine::instance()
@@ -1793,6 +3537,226 @@ LayoutEngine &LayoutEngine::instance()
1793
3537
  return engine;
1794
3538
  }
1795
3539
 
3540
+ int LayoutEngine::fixedContainingBlock(const Node &node)
3541
+ {
3542
+ const Node *nodes = Tree::instance().nodes();
3543
+ for (int id = node.parent; id >= 0; id = nodes[id].parent) {
3544
+ if (establishesTransformContainingBlock(nodes[id])) return id;
3545
+ }
3546
+ return -1;
3547
+ }
3548
+
3549
+ bool LayoutEngine::isViewportFixed(const Node &node)
3550
+ {
3551
+ return node.style.position == kPositionFixed && fixedContainingBlock(node) < 0;
3552
+ }
3553
+
3554
+ bool LayoutEngine::containsViewportFixed(int node)
3555
+ {
3556
+ if (!treeState().fixedPositionUsed) return false;
3557
+ const Node *nodes = Tree::instance().nodes();
3558
+ if (isViewportFixed(nodes[node])) return true;
3559
+ for (int child = nodes[node].first_child; child >= 0; child = nodes[child].next_sibling)
3560
+ if (containsViewportFixed(child)) return true;
3561
+ return false;
3562
+ }
3563
+
3564
+ void LayoutEngine::absoluteContainingArea(const Node &parent, const Node &child, int &x, int &y, int &width, int &height)
3565
+ {
3566
+ x = y = 0;
3567
+ width = parent.layout.width; height = parent.layout.height;
3568
+ if (isDocumentCanvasRoot(parent) && !establishesAbsoluteContainingBlock(parent)) {
3569
+ // The initial containing block is viewport-sized, even when the HTML
3570
+ // element has an auto height, margins, or an explicit smaller size.
3571
+ x = -parent.layout.x; y = -parent.layout.y;
3572
+ width = parent.layout.memo_avail_w; height = parent.layout.memo_avail_h;
3573
+ return;
3574
+ }
3575
+ if (establishesAbsoluteContainingBlock(parent) || child.style.position == kPositionFixed) {
3576
+ // Insets and percentages reference the padding box, excluding borders.
3577
+ x = boxInset(parent.style, 3) - parent.style.padding[3];
3578
+ y = boxInset(parent.style, 0) - parent.style.padding[0];
3579
+ width = std::max(0, width - x - boxInset(parent.style, 1) + parent.style.padding[1]);
3580
+ height = std::max(0, height - y - boxInset(parent.style, 2) + parent.style.padding[2]);
3581
+ }
3582
+ absoluteGridArea(parent, child, x, y, width, height);
3583
+ }
3584
+
3585
+ bool LayoutEngine::absoluteGridArea(const Node &parent, const Node &child, int &x, int &y, int &width, int &height)
3586
+ {
3587
+ if (!isDisplayGrid(parent.style)) return false;
3588
+ if (child.style.position == kPositionFixed) {
3589
+ if (fixedContainingBlock(child) != &parent - Tree::instance().nodes()) return false;
3590
+ } else if (!establishesAbsoluteContainingBlock(parent)) return false;
3591
+ const auto *rare = rareDataFor(static_cast<int>(&parent - Tree::instance().nodes()));
3592
+ const GridTrackLayout *tracks = rare ? rare->gridLayout.get() : nullptr;
3593
+ const bool vertical = writingMode(parent) != 0;
3594
+ for (bool columns : {true, false}) {
3595
+ const bool horizontal = columns != vertical;
3596
+ const int explicitCount = columns ? rstyle(parent.style).grid_column_count : rstyle(parent.style).grid_row_count;
3597
+ const auto &lines = rstyle(child.style).grid_line;
3598
+ const std::vector<int> *starts = tracks ? (columns ? &tracks->columnStart : &tracks->rowStart) : nullptr;
3599
+ const std::vector<int> *ends = tracks ? (columns ? &tracks->columnEnd : &tracks->rowEnd) : nullptr;
3600
+ const int origin = tracks ? (columns ? tracks->columnOrigin : tracks->rowOrigin) : 0;
3601
+ const int count = starts ? static_cast<int>(starts->size()) : 0;
3602
+ auto existing = [origin, count](int line) { return line != kUnset && line + origin >= 0 && line + origin <= count; };
3603
+ // Invalid absolute line references become auto before a dependent span
3604
+ // is resolved; otherwise an absent end line could invent a start line.
3605
+ auto validLine = [&](int value) {
3606
+ if (!value || value >= kGridLineSpan) return value;
3607
+ const int index = value > 0 ? value - 1 : explicitCount + 1 + value;
3608
+ return existing(index) ? value : 0;
3609
+ };
3610
+ auto placement = gridAxisPlacement(validLine(lines[columns ? 1 : 0]), validLine(lines[columns ? 3 : 2]), explicitCount, true);
3611
+ const bool hasStart = existing(placement.start), hasEnd = existing(placement.end);
3612
+ const int available = (horizontal ? parent.layout.width : parent.layout.height) - boxInsets(parent.style, horizontal);
3613
+ int beforeSide = horizontal ? 3 : 0, afterSide = horizontal ? 1 : 2;
3614
+ if (gridAxisReversed(parent, horizontal)) std::swap(beforeSide, afterSide);
3615
+ int start = -parent.style.padding[beforeSide], end = available + parent.style.padding[afterSide];
3616
+ if (hasStart) {
3617
+ const int index = placement.start + origin;
3618
+ start = count == 0 ? 0 : index == count ? ends->back() : (*starts)[index];
3619
+ }
3620
+ if (hasEnd) {
3621
+ const int index = placement.end + origin;
3622
+ end = count == 0 ? 0 : index == 0 ? starts->front() : (*ends)[index - 1];
3623
+ }
3624
+ gridPhysicalRange(parent, columns, start, std::max(start, end), horizontal ? x : y, horizontal ? width : height);
3625
+ }
3626
+ return true;
3627
+ }
3628
+
3629
+ int LayoutEngine::alignedAbsoluteOffset(const Node &parent, const Node &childNode, bool horizontal,
3630
+ const Node *containing, int containingStart, int containingSize)
3631
+ {
3632
+ const Node *treeNodes = Tree::instance().nodes();
3633
+ const int childId = static_cast<int>(&childNode - treeNodes);
3634
+ if (const auto *rare = rareDataFor(childId); rare && rare->inlineStaticPosition.valid) {
3635
+ int continuationOrigin = 0;
3636
+ if (horizontal && rare->inlineStaticPosition.continuationLine) {
3637
+ // Resolve fragmented inline origins here, after ancestor layout has
3638
+ // finalized their first-fragment x positions. The continuation line
3639
+ // starts at the nearest formatting block's content edge, not at the
3640
+ // inline parent's first-fragment padding edge.
3641
+ int inlineOffset = 0;
3642
+ int cursor = static_cast<int>(&parent - treeNodes);
3643
+ while (cursor >= 0 && isCssInlineLevelBox(treeNodes[cursor])) {
3644
+ inlineOffset += treeNodes[cursor].layout.x;
3645
+ cursor = treeNodes[cursor].parent;
3646
+ }
3647
+ if (cursor >= 0) continuationOrigin = boxInset(treeNodes[cursor].style, 3) - inlineOffset;
3648
+ }
3649
+ return (horizontal ? rare->inlineStaticPosition.x + continuationOrigin + childNode.style.margin[3]
3650
+ : rare->inlineStaticPosition.y + childNode.style.margin[0]);
3651
+ }
3652
+ if (parent.style.display == kDisplayBlock && !parent.style.flex_direction_explicit &&
3653
+ childNode.layout.static_block_axis == (horizontal ? 2 : 1)) {
3654
+ const bool reversed = horizontal && gridAxisReversed(parent, true);
3655
+ return childNode.layout.static_block_start + (reversed ? -childNode.layout.width - childNode.style.margin[1]
3656
+ : childNode.style.margin[horizontal ? 3 : 0]);
3657
+ }
3658
+ // In block layout the hypothetical box starts at the parent's inline
3659
+ // content edge. RTL anchors its inline-end margin edge, even when the absolute
3660
+ // box is wider than its static-position parent. Its actual containing
3661
+ // block can be an entirely different ancestor.
3662
+ if (horizontal == (writingMode(parent) == 0) && parent.style.display == kDisplayBlock &&
3663
+ (!isInlineLevelNode(parent) || isOutOfFlowPosition(parent.style.position)) &&
3664
+ !parent.style.flex_direction_explicit) {
3665
+ return rightToLeft(parent)
3666
+ ? (horizontal ? parent.layout.width : parent.layout.height) - boxInset(parent.style, horizontal ? 1 : 2) -
3667
+ (horizontal ? childNode.layout.width : childNode.layout.height) - childNode.style.margin[horizontal ? 1 : 2]
3668
+ : boxInset(parent.style, horizontal ? 3 : 0) + childNode.style.margin[horizontal ? 3 : 0];
3669
+ }
3670
+ const bool grid = isDisplayGrid(parent.style), flex = parent.style.display == kDisplayFlex;
3671
+ const bool row = flex ? flexRowDirection(parent.style) != (writingMode(parent) != 0) : usesRowLayout(parent.style);
3672
+ const int crossAlign = childNode.style.align_self >= 0 ? childNode.style.align_self : parent.style.align_items;
3673
+ const int inlineAlign = rstyle(childNode.style).justify_self >= 0 ? rstyle(childNode.style).justify_self : parent.style.justify_items;
3674
+ int align = grid
3675
+ ? (horizontal == (writingMode(parent) == 0) ? inlineAlign : crossAlign)
3676
+ : (horizontal ? (row ? parent.style.justify_content : crossAlign)
3677
+ : (row ? crossAlign : parent.style.justify_content));
3678
+ if (flex && horizontal == row && isDistributedAlignment(align)) {
3679
+ // Static position lays out the absolute box as the sole hypothetical
3680
+ // flex item: between falls back to flex-start, around/evenly to center.
3681
+ // This static center anchor remains centered even when it overflows.
3682
+ align = ((align & 15) == 3 ? 6 : 1) | kAlignUnsafe;
3683
+ }
3684
+ // A grid supplies its content box when the containing block is outside
3685
+ // it; when it is the containing block, grid placement supplies the area.
3686
+ int inset = grid || flex ? boxInset(parent.style, horizontal ? 3 : 0) : 0;
3687
+ int parentSize = (horizontal ? parent.layout.width : parent.layout.height) -
3688
+ (grid || flex ? boxInsets(parent.style, horizontal) : 0);
3689
+ int areaX, areaY, areaWidth, areaHeight;
3690
+ if (absoluteGridArea(parent, childNode, areaX, areaY, areaWidth, areaHeight)) {
3691
+ inset = horizontal ? areaX : areaY;
3692
+ parentSize = horizontal ? areaWidth : areaHeight;
3693
+ }
3694
+ const int childSize = horizontal ? childNode.layout.width : childNode.layout.height;
3695
+ const int beforeMargin = horizontal ? childNode.style.margin[3] : childNode.style.margin[0];
3696
+ const int afterMargin = horizontal ? childNode.style.margin[1] : childNode.style.margin[2];
3697
+ int available = parentSize;
3698
+ if (available < 0) available = 0;
3699
+ const int occupied = childSize + beforeMargin + afterMargin;
3700
+ int free = available - occupied;
3701
+ const bool baseline = (align & 15) == 5 || (align & 15) == kAlignLastBaseline;
3702
+ // Baseline static positions already use their specified fallback edge
3703
+ // without overflow safety; do not turn that fallback into safe alignment.
3704
+ const bool resolveInsets = containing && (grid || flex) && (align & 15) != 0 && !baseline;
3705
+ const int pointAlignment = resolveInsets ? (align & ~kAlignSafe) | kAlignUnsafe : align;
3706
+ if (!grid && !flex && !baseline && free < 0 && !(align & (kAlignSafe | kAlignUnsafe))) free = 0;
3707
+ const int self = physicalSelfAlignment(parent, childNode, pointAlignment, free, horizontal);
3708
+ int used = grid || flex ? usedGridAlignment(parent, childNode, pointAlignment, free, horizontal, true)
3709
+ : self >= 0 ? self : baseline ? baselineFallbackAlignment(parent, childNode, pointAlignment, free, horizontal, true)
3710
+ : usedAlignment(pointAlignment, free);
3711
+ const int keyword = align & 15;
3712
+ if (flex && horizontal == row && parent.style.flex_direction_explicit && parent.style.flex_direction >= 2 &&
3713
+ (keyword == 0 || keyword == 2 || keyword == 6)) used = used == 2 ? 6 : 2;
3714
+ int position = inset + beforeMargin;
3715
+ if (used == 1) position += free / 2;
3716
+ else if (used == 2) position += free;
3717
+ if (resolveInsets) {
3718
+ // CSS Position 3.5.1 resolves the automatic inset(s) from the static
3719
+ // alignment point before overflow safety uses the available rectangle.
3720
+ const int containingEnd = containingStart + containingSize;
3721
+ int start = used == 2 ? containingStart : inset;
3722
+ int end = used == 2 ? inset + available : containingEnd;
3723
+ if (used == 1) {
3724
+ const int centerTwice = 2 * inset + available;
3725
+ const int startDistanceTwice = centerTwice - 2 * containingStart;
3726
+ const int endDistanceTwice = 2 * containingEnd - centerTwice;
3727
+ if (startDistanceTwice <= endDistanceTwice) {
3728
+ start = containingStart; end = start + std::abs(startDistanceTwice);
3729
+ } else {
3730
+ end = containingEnd; start = end - std::abs(endDistanceTwice);
3731
+ }
3732
+ }
3733
+ const bool reversed = gridAxisReversed(parent, horizontal);
3734
+ if (end < start) { if (reversed) start = end; else end = start; }
3735
+ const int remaining = end - start - occupied;
3736
+ if ((align & kAlignSafe) && remaining < 0) {
3737
+ position = reversed ? end - childSize - afterMargin : start + beforeMargin;
3738
+ } else if (flex && !(align & (kAlignSafe | kAlignUnsafe)) && remaining < 0) {
3739
+ const int limitStart = std::min(start, containingStart), limitEnd = std::max(end, containingEnd);
3740
+ if (occupied > limitEnd - limitStart)
3741
+ position = reversed ? limitEnd - childSize - afterMargin : limitStart + beforeMargin;
3742
+ else position = std::clamp(position, limitStart + beforeMargin, limitEnd - childSize - afterMargin);
3743
+ }
3744
+ // Unqualified grid self-alignment keeps the unsafe fallback used by browsers
3745
+ // and CSS Align's allowance for engines without smart overflow safety.
3746
+ // Applying a partial default-safety rule here changes ordinary grid
3747
+ // center/end alignment, even when no safe keyword was specified.
3748
+ }
3749
+ if (containing && flex && horizontal == row && keyword == 0 && !(align & (kAlignSafe | kAlignUnsafe))) {
3750
+ // The hypothetical single flex item can overflow its main-axis start
3751
+ // when that axis runs opposite to the actual containing block. Default
3752
+ // alignment keeps its start side reachable in the containing block.
3753
+ if (gridAxisReversed(*containing, horizontal))
3754
+ position = std::min(position, containingStart + containingSize - childSize - afterMargin);
3755
+ else position = std::max(position, containingStart + beforeMargin);
3756
+ }
3757
+ return position;
3758
+ }
3759
+
1796
3760
  bool LayoutEngine::isInlineLevelNode(const Node &n)
1797
3761
  {
1798
3762
  if (n.style.display == kDisplayFlex || n.style.display == kDisplayGrid || n.style.display == kDisplayNone)
@@ -1813,6 +3777,18 @@ bool LayoutEngine::isInlineLevelNode(const Node &n)
1813
3777
  return isInlineLevelTag(tagFromId(n.tag_id));
1814
3778
  }
1815
3779
 
3780
+ bool LayoutEngine::isCssInlineLevelBox(const Node &n, bool hypothetical)
3781
+ {
3782
+ if (n.style.display == kDisplayNone || n.style.display_explicit) return false;
3783
+ if (!hypothetical && (n.style.float_side || isOutOfFlowPosition(n.style.position))) return false;
3784
+ if (!hypothetical && n.parent >= 0) {
3785
+ const Node &parent = Tree::instance().nodes()[n.parent];
3786
+ if (parent.style.display == kDisplayFlex || isDisplayGrid(parent.style)) return false;
3787
+ }
3788
+ if (n.type == NodeType::Text || n.type == NodeType::Image) return true;
3789
+ return n.type == NodeType::View && isInlineLevelTag(tagFromId(n.tag_id));
3790
+ }
3791
+
1816
3792
  int LayoutEngine::clampSize(int size, int minSize, int maxSize) const
1817
3793
  {
1818
3794
  if (minSize > 0 && size < minSize) size = minSize;
@@ -1826,9 +3802,26 @@ int LayoutEngine::collectChildren(int parent, int *out, int max, bool skipAbs) c
1826
3802
  Node *nodes = Tree::instance().nodes();
1827
3803
  for (int child = nodes[parent].first_child; child >= 0; child = nodes[child].next_sibling) {
1828
3804
  if (isDisplayNone(nodes[child].style)) continue;
1829
- if (skipAbs && nodes[child].style.position == 1) continue;
3805
+ if (suppressAnonymousWhitespace(nodes, parent, child)) continue;
3806
+ if (skipAbs && isOutOfFlowPosition(nodes[child].style.position)) continue;
1830
3807
  if (n < max) out[n++] = child;
1831
3808
  }
3809
+ // All consumers (layout, painting, and hit testing) start from this stable
3810
+ // order. Subsequent stable z-index/depth sorting preserves it for ties.
3811
+ // Absolutely positioned children have order 0 for painting and are excluded
3812
+ // by skipAbs when collecting actual flex/grid items for layout.
3813
+ if (nodes[parent].style.display == kDisplayFlex || isDisplayGrid(nodes[parent].style)) {
3814
+ auto order = [&](int child) { return isOutOfFlowPosition(nodes[child].style.position) ? 0 : nodes[child].style.order; };
3815
+ for (int i = 1; i < n; ++i) {
3816
+ const int child = out[i];
3817
+ int j = i;
3818
+ while (j > 0 && order(out[j - 1]) > order(child)) {
3819
+ out[j] = out[j - 1];
3820
+ --j;
3821
+ }
3822
+ out[j] = child;
3823
+ }
3824
+ }
1832
3825
  return n;
1833
3826
  }
1834
3827
 
@@ -1843,15 +3836,73 @@ void LayoutEngine::beginLayoutPass()
1843
3836
  if (++gLayoutPassSerial == 0) gLayoutPassSerial = 1;
1844
3837
  }
1845
3838
 
1846
- void LayoutEngine::layoutNode(int id, int avail_w, int avail_h)
3839
+ void LayoutEngine::layoutNode(int id, int avail_w, int avail_h, bool intrinsicBoxEdges)
1847
3840
  {
1848
3841
  Node &node = Tree::instance().nodes()[id];
1849
- const bool memoizable = avail_w >= INT16_MIN && avail_w <= INT16_MAX &&
3842
+ const Node *parent = node.parent >= 0 ? &Tree::instance().nodes()[node.parent] : nullptr;
3843
+ // Horizontal non-replaced floats use the same min/max-content measurement
3844
+ // and final used-width phase as fit-content. Floats on flex/grid items are
3845
+ // ignored; orthogonal automatic inline sizing is handled separately.
3846
+ const bool shrinkFloat = node.type == NodeType::View && node.style.float_side &&
3847
+ !isOutOfFlowPosition(node.style.position) &&
3848
+ (!parent || (parent->style.display != kDisplayFlex && !isDisplayGrid(parent->style))) &&
3849
+ node.style.width == kUnset && node.style.width_percent == kUnset && node.style.width_expression == -1 &&
3850
+ writingMode(node) == 0;
3851
+ // CSS Writing Modes 7.3.2: an orthogonal flow root's automatic inline
3852
+ // size is fit-content. Measure before fixing the used size so cyclic
3853
+ // percentage gaps are zero in the probes but resolve in final layout.
3854
+ // Flex and grid items obtain their automatic sizes from those algorithms.
3855
+ const bool horizontalInline = writingMode(node) == 0;
3856
+ const bool orthogonalAuto = node.type == NodeType::View && parent &&
3857
+ horizontalInline != (writingMode(*parent) == 0) &&
3858
+ parent->style.display != kDisplayFlex && !isDisplayGrid(parent->style) &&
3859
+ !isOutOfFlowPosition(node.style.position) &&
3860
+ (horizontalInline ? node.style.width : node.style.height) == kUnset &&
3861
+ (horizontalInline ? node.style.width_percent : node.style.height_percent) == kUnset &&
3862
+ (horizontalInline ? node.style.width_expression : node.style.height_expression) == -1;
3863
+ const bool intrinsicWidth = isIntrinsicSizeExpression(node.style.width_expression) && !intrinsicSizeScope(node, true);
3864
+ const bool horizontal = intrinsicWidth || !orthogonalAuto || horizontalInline;
3865
+ if ((intrinsicWidth || shrinkFloat || orthogonalAuto) &&
3866
+ !intrinsicSizeScope(node, horizontal) && !flexBasisScope(node, horizontal)) {
3867
+ const int inherited = parent ? intrinsicSizeConstraint(*parent, horizontal) : 0;
3868
+ const int keyword = intrinsicWidth ? node.style.width_expression : kSizeFitContent;
3869
+ IntrinsicSizeScope scope(node, 1, horizontal);
3870
+ auto measure = [&](int mode) {
3871
+ scope.constraint = mode;
3872
+ const int available = mode == 1 ? 1 : 32767;
3873
+ layoutNode(id, horizontal ? available : avail_w, horizontal ? avail_h : available, true);
3874
+ return std::max(0, (horizontal ? node.layout.width : node.layout.height) - boxInsets(node.style, horizontal));
3875
+ };
3876
+ if (inherited) {
3877
+ measure(keyword == kSizeMinContent ? 1 : keyword == kSizeMaxContent ? 2 : inherited);
3878
+ return;
3879
+ }
3880
+ const int minimum = keyword == kSizeMaxContent ? 0 : measure(1);
3881
+ const int maximum = keyword == kSizeMinContent ? minimum : std::max(minimum, measure(2));
3882
+ const int inlineBasis = node.parent >= 0 && writingMode(Tree::instance().nodes()[node.parent]) != 0 ? avail_h : avail_w;
3883
+ resolveLayoutBoxLengths(id, intrinsicBoxEdges ? 0 : inlineBasis);
3884
+ const int edges = boxInsets(node.style, horizontal);
3885
+ const int stretch = std::max(0, (horizontal ? avail_w : avail_h) -
3886
+ node.style.margin[horizontal ? 1 : 0] - node.style.margin[horizontal ? 3 : 2] - edges);
3887
+ scope.borderSize = edges + (keyword == kSizeMinContent ? minimum : keyword == kSizeMaxContent ? maximum : std::min(maximum, std::max(minimum, stretch)));
3888
+ scope.constraint = 0;
3889
+ layoutNode(id, avail_w, avail_h, intrinsicBoxEdges);
3890
+ return;
3891
+ }
3892
+ if (node.type == NodeType::Text && intrinsicWidthConstraint(node) == 1)
3893
+ avail_w = std::max(avail_w, TextRenderer::minContentWidth(node) + boxInsets(node.style, true));
3894
+ const int inlineBasis = node.parent >= 0 && writingMode(Tree::instance().nodes()[node.parent]) != 0 ? avail_h : avail_w;
3895
+ if (resolveLayoutBoxLengths(id, intrinsicBoxEdges ? 0 : inlineBasis)) {
3896
+ node.layout.memo_pass = node.layout.memo2_pass = 0;
3897
+ }
3898
+ const bool memoizable = !gIntrinsicSizeScope && !gFlexBasisScope && avail_w >= INT16_MIN && avail_w <= INT16_MAX &&
1850
3899
  avail_h >= INT16_MIN && avail_h <= INT16_MAX;
1851
3900
  if (memoizable) {
1852
3901
  if (node.layout.memo_pass == gLayoutPassSerial &&
1853
3902
  node.layout.memo_avail_w == avail_w &&
1854
- node.layout.memo_avail_h == avail_h) {
3903
+ node.layout.memo_avail_h == avail_h &&
3904
+ node.layout.memo_result_w == node.layout.width &&
3905
+ node.layout.memo_result_h == node.layout.height) {
1855
3906
  refreshPerfStatsMutable().treeLayoutMemoHits++;
1856
3907
  return;
1857
3908
  }
@@ -1872,6 +3923,18 @@ void LayoutEngine::layoutNode(int id, int avail_w, int avail_h)
1872
3923
  }
1873
3924
  refreshPerfStatsMutable().treeLayoutNodeCalls++;
1874
3925
  LayoutNodePass(*this, id, avail_w, avail_h).run();
3926
+ const int beforeRatioWidth = node.layout.width, beforeRatioHeight = node.layout.height;
3927
+ applyPreferredRatio(node, avail_w, avail_h);
3928
+ if (node.first_child >= 0 && (node.layout.width != beforeRatioWidth || node.layout.height != beforeRatioHeight))
3929
+ LayoutNodePass(*this, id, node.layout.width, node.layout.height).repositionChildren();
3930
+ if (node.parent < 0) {
3931
+ // The initial containing block places the root; there is no parent
3932
+ // layout pass to position its margin box or apply float alignment.
3933
+ node.layout.x = node.style.float_side == 2
3934
+ ? avail_w - node.layout.width - node.style.margin[1]
3935
+ : node.style.margin[3];
3936
+ node.layout.y = node.style.margin[0];
3937
+ }
1875
3938
  node.layout.memo2_avail_w = node.layout.memo_avail_w;
1876
3939
  node.layout.memo2_avail_h = node.layout.memo_avail_h;
1877
3940
  node.layout.memo2_result_w = node.layout.memo_result_w;
@@ -1907,6 +3970,11 @@ bool LayoutEngine::layoutNodeScoped(int scope, int treeRoot)
1907
3970
  refreshPerfStatsMutable().treeScopedRejectNode = scope;
1908
3971
  return false;
1909
3972
  }
3973
+ if (!LayoutNodePass(*this, scope, a.layout.memo_avail_w, a.layout.memo_avail_h).containsChildMargins()) {
3974
+ refreshPerfStatsMutable().treeScopedRejectReason = 5;
3975
+ refreshPerfStatsMutable().treeScopedRejectNode = scope;
3976
+ return false;
3977
+ }
1910
3978
 
1911
3979
  auto inScope = [&](int node) {
1912
3980
  for (int c = node; c >= 0 && c < nodeCount; c = nodes[c].parent) {
@@ -1920,7 +3988,7 @@ bool LayoutEngine::layoutNodeScoped(int scope, int treeRoot)
1920
3988
  // pre-resolve relative space) — those trees must take the full path.
1921
3989
  for (int i = 0; i < nodeCount; ++i) {
1922
3990
  const Node &n = nodes[i];
1923
- if (n.parent < 0 || n.style.position != 1 || isDisplayNone(n.style)) continue;
3991
+ if (n.parent < 0 || !isOutOfFlowPosition(n.style.position) || isDisplayNone(n.style)) continue;
1924
3992
  if (!inScope(i)) continue;
1925
3993
  const int containing = containingBlockForAbsoluteNode(i, treeRoot, nodes);
1926
3994
  if (containing >= 0 && !inScope(containing)) {
@@ -1951,13 +4019,15 @@ bool LayoutEngine::layoutNodeScoped(int scope, int treeRoot)
1951
4019
  if (a.parent >= 0 && a.parent < nodeCount) {
1952
4020
  const Node &parent = nodes[a.parent];
1953
4021
  if (isDisplayGrid(parent.style)) {
1954
- const int alignX = a.style.align_self >= 0 ? a.style.align_self : parent.style.justify_items;
1955
- const int alignY = a.style.align_self >= 0 ? a.style.align_self : parent.style.align_items;
1956
- parentOwnsWidth = parentOwnsWidth || alignX == 0;
1957
- parentOwnsHeight = parentOwnsHeight || alignY == 0;
4022
+ const int inlineAlign = rstyle(a.style).justify_self >= 0 ? rstyle(a.style).justify_self : parent.style.justify_items;
4023
+ const int blockAlign = a.style.align_self >= 0 ? a.style.align_self : parent.style.align_items;
4024
+ const int alignX = writingMode(parent) == 0 ? inlineAlign : blockAlign;
4025
+ const int alignY = writingMode(parent) == 0 ? blockAlign : inlineAlign;
4026
+ parentOwnsWidth = parentOwnsWidth || (alignX == 0 && !(a.style.margin_auto & 10));
4027
+ parentOwnsHeight = parentOwnsHeight || (alignY == 0 && !(a.style.margin_auto & 5));
1958
4028
  } else {
1959
4029
  const bool row = usesRowLayout(parent.style);
1960
- const bool parentOwnsMain = a.style.flex > 0 || a.style.flex_basis != kUnset;
4030
+ const bool parentOwnsMain = a.style.flex > 0 || hasFlexBasis(a);
1961
4031
  const int crossAlign = a.style.align_self >= 0 ? a.style.align_self : parent.style.align_items;
1962
4032
  const bool parentOwnsCross = crossAlign == 0;
1963
4033
  parentOwnsWidth = parentOwnsWidth || (row ? parentOwnsMain : parentOwnsCross);
@@ -1983,7 +4053,7 @@ bool LayoutEngine::layoutNodeScoped(int scope, int treeRoot)
1983
4053
  // Scoped equivalent of the root containing-block pass (both the node and
1984
4054
  // its containing block are inside the scope, in the same relative space).
1985
4055
  for (int i = 0; i < nodeCount; ++i) {
1986
- if (isDisplayNone(nodes[i].style) || nodes[i].style.position != 1 || nodes[i].parent < 0) continue;
4056
+ if (isDisplayNone(nodes[i].style) || !isOutOfFlowPosition(nodes[i].style.position) || nodes[i].parent < 0) continue;
1987
4057
  if (!inScope(i) || i == scope) continue;
1988
4058
  const int containing = containingBlockForAbsoluteNode(i, scope, nodes);
1989
4059
  if (containing < 0) continue;
@@ -2007,8 +4077,10 @@ void LayoutEngine::resolveAbsoluteCoords(int id, int parent_x, int parent_y)
2007
4077
  Node *nodes = Tree::instance().nodes();
2008
4078
  Node *node = &nodes[id];
2009
4079
  if (node->parent < 0) resolveAbsoluteContainingBlocks(id);
2010
- node->layout.x += parent_x;
2011
- node->layout.y += parent_y;
4080
+ if (!isViewportFixed(*node)) {
4081
+ node->layout.x += parent_x;
4082
+ node->layout.y += parent_y;
4083
+ }
2012
4084
 
2013
4085
  int childParentX = node->layout.x;
2014
4086
  int childParentY = node->layout.y;