Repository navigation
Expand file tree
/
Copy pathui_layout.js
More file actions
1276 lines (1116 loc) · 46.1 KB
/
Copy pathui_layout.js
File metadata and controls
1276 lines (1116 loc) · 46.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* UILayout: the layout engine behind the Construct 3 UI addons.
*
* It lays out a hierarchy of Construct instances with a CSS-like style language
* (flexbox rows and columns, wrapping, a simple grid, absolute and anchor
* positioning, fit-content sizing). It only touches these instance members:
* getBoundingBox(), getParent(), children(), x, y, width, height, angleDegrees,
* isVisible, hasTags() and the `__flexbox_ui_element` bag the UI Element
* behavior installs ({ enabled, classes, style, _computedStyle }).
*
* How a tick works (processInstance):
*
* 1. measure(root): bottom-up. Every in-flow instance gets its intrinsic size:
* its authored size, or an explicit numeric width/height, or, for a
* fit-content axis, the extent of its children. Percent sizes and flex are
* ignored here; they depend on the parent, which is not final yet.
* 2. layout(root): top-down. The instance's size is final, so it resolves its
* children's percent sizes and flex bases, distributes free space, positions
* the children, then recurses. Out-of-flow children (absolute, anchor) are
* sized, positioned and laid out after the in-flow ones.
*
* Authored size. Construct instances have no "content" to measure, so the
* engine remembers, per instance, the size the engine itself last wrote. If the
* instance's size differs from that, someone else (the editor, an event, a
* tween) set it, and that becomes the authored size. Flex `auto` bases, percent
* children of fit-content parents and fit-content wrapping all start from the
* authored size, which keeps every layout stable from one tick to the next and
* independent of what the engine wrote before.
*
* Incremental layout. The measure pass doubles as the change detector. A node
* is dirty when its merged style object changed (invalidateStyles gives it a
* new one), when its size, bounding box or position relative to its parent
* differs from what the engine last wrote, when its list of active children
* changed, or when the target it is anchored to moved. A dirty node lays out
* its children; its parent lays out too when the node's styles, intrinsic size
* or position changed, and so on upwards until a parent is unaffected. Children
* whose size the parent changed are laid out in turn. On a quiet tick nothing
* below the measure pass runs. `forceFullLayout = true` disables this.
*
* Construct is expected to move children with their parent (hierarchy
* "transform X/Y" flags). It must not scale them with the parent (width/height
* flags off): the engine sets child sizes itself.
*/
const AXES = {
x: {
name: "x",
size: "width",
start: "left",
end: "right",
min: "minWidth",
max: "maxWidth",
fitContent: "fitContentX",
},
y: {
name: "y",
size: "height",
start: "top",
end: "bottom",
min: "minHeight",
max: "maxHeight",
fitContent: "fitContentY",
},
};
const ROW_DISPLAYS = new Set(["row", "row-reverse"]);
/** Box-model shorthands and the four longhands they expand to (top, right, bottom, left). */
const BOX_SHORTHANDS = {
margin: ["marginTop", "marginRight", "marginBottom", "marginLeft"],
padding: ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"],
border: ["borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth"],
borderWidth: ["borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth"],
};
const EMPTY_STYLE = Object.freeze({});
function toNumber(value, fallback) {
const n = parseFloat(value);
return Number.isFinite(n) ? n : fallback;
}
function isPercent(value) {
return typeof value === "string" && value.endsWith("%");
}
const EPSILON = 1e-6;
function near(a, b) {
return a !== undefined && Math.abs(a - b) <= EPSILON;
}
function sameList(a, b) {
if (!a || a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
function clamp(value, min, max) {
if (min !== undefined && value < min) value = min;
if (max !== undefined && value > max) value = max;
return value;
}
class UILayout {
constructor(runtime) {
this.runtime = runtime;
// className -> parsed style ({ computedStyle, importantProperties })
this.registeredClasses = new Map();
// instance -> per-node bookkeeping, see node()
this.nodeData = new WeakMap();
// Set to true to lay out every node every tick (used by tests and benchmarks).
this.forceFullLayout = false;
// Counters for the last processInstance call.
this.stats = { measured: 0, laidOut: 0 };
// Bounding boxes read during the current pass. Construct allocates a
// DOMRect per getBoundingBox() call and recomputes the box (walking the
// parent chain for the angle) after every write, so each instance is read
// once per pass and the engine updates the cached box itself on writes.
this.boxCache = new WeakMap();
// Derived data keyed by the merged style object. Styles are recomputed as a
// new object on invalidation, so these caches never go stale.
this.boxModelCache = new WeakMap();
this.layoutPropsCache = new WeakMap();
}
// ---------------------------------------------------------------------------
// Style text
// ---------------------------------------------------------------------------
registerClass(className, styleString) {
this.registeredClasses.set(className, this.parseStyle(styleString));
}
getClassStyle(className) {
if (!this.registeredClasses.has(className)) {
this.registerClass(className, "");
}
return this.registeredClasses.get(className);
}
/**
* Parses CSS-like text ("width: 100; align-items: center !important") into
* { computedStyle, importantProperties }. Declarations are separated by
* semicolons or line breaks. Property names may be kebab-case or camelCase.
*/
parseStyle(cssText) {
const computedStyle = {};
const importantProperties = [];
if (!cssText) return { computedStyle, importantProperties };
for (let line of cssText.split("\n").join(";").split(";")) {
line = line.trim();
if (!line) continue;
const colonIndex = line.indexOf(":");
if (colonIndex === -1) continue;
const property = this.kebabToCamel(line.substring(0, colonIndex).trim());
let value = line.substring(colonIndex + 1).trim();
if (!property || !value) continue;
const isImportant = value.includes("!important");
if (isImportant) {
value = value.replace(/\s*!important\s*$/, "").trim();
}
if (property === "flex") {
this.parseFlexShorthand(value, computedStyle);
if (isImportant) {
importantProperties.push("flexGrow", "flexShrink", "flexBasis");
}
continue;
}
if (property in BOX_SHORTHANDS) {
const sides = this.parseBoxShorthand(value);
if (!sides) continue;
const longhands = BOX_SHORTHANDS[property];
for (let i = 0; i < 4; i++) computedStyle[longhands[i]] = sides[i];
if (isImportant) importantProperties.push(...longhands);
continue;
}
computedStyle[property] = this.convertValue(value);
if (isImportant) importantProperties.push(property);
}
return { computedStyle, importantProperties };
}
/**
* Expands a CSS box shorthand ("10", "10 20", "10 20 30", "10 20 30 40") into
* [top, right, bottom, left]. Returns null when any token is not a number or
* there are more than four, in which case the declaration is ignored.
*/
parseBoxShorthand(value) {
const parts = value.split(/\s+/).map((part) => this.convertValue(part));
if (parts.length === 0 || parts.length > 4 || parts.some((n) => typeof n !== "number")) return null;
const [a, b = a, c = a, d = b] = parts;
return [a, b, c, d];
}
/** Removes a property; a box shorthand removes its four longhands. */
removePropertyFromStyle(style, property) {
const camelProperty = this.kebabToCamel(property);
const names = BOX_SHORTHANDS[camelProperty] || [camelProperty];
for (const name of names) {
delete style.computedStyle[name];
const index = style.importantProperties.indexOf(name);
if (index !== -1) style.importantProperties.splice(index, 1);
}
}
setPropertyInStyle(style, property, value) {
this.removePropertyFromStyle(style, property);
if (!value) return;
const extra = this.parseStyle(`${property}: ${value};`);
for (const prop of Object.keys(extra.computedStyle)) {
style.computedStyle[prop] = extra.computedStyle[prop];
const index = style.importantProperties.indexOf(prop);
if (index !== -1) style.importantProperties.splice(index, 1);
}
style.importantProperties.push(...extra.importantProperties);
}
/**
* Expands the `flex` shorthand into flexGrow, flexShrink and flexBasis.
* Forms: "1", "auto", "none", "initial", "1 0" (grow shrink),
* "1 50%" (grow basis), "1 1 100" (grow shrink basis).
*/
parseFlexShorthand(value, computedStyle) {
const parts = value.split(/\s+/);
let grow = 0;
let shrink = 1;
let basis = "auto";
if (parts.length === 1) {
if (parts[0] === "auto") {
grow = 1;
} else if (parts[0] === "none") {
shrink = 0;
} else if (parts[0] === "initial") {
// 0 1 auto
} else {
grow = this.convertValue(parts[0]);
basis = "0";
}
} else if (parts.length === 2) {
grow = this.convertValue(parts[0]);
if (/^\d+(\.\d+)?$/.test(parts[1])) {
shrink = this.convertValue(parts[1]);
basis = "0";
} else {
basis = parts[1];
}
} else {
grow = this.convertValue(parts[0]);
shrink = this.convertValue(parts[1]);
basis = parts[2];
}
computedStyle.flexGrow = grow;
computedStyle.flexShrink = shrink;
computedStyle.flexBasis = basis;
}
kebabToCamel(str) {
return str.replace(/-([a-z])/g, (match, group) => group.toUpperCase());
}
/** "100" -> 100, "0px" -> 0, everything else stays a string. */
convertValue(value) {
if (/^-?\d+(\.\d+)?$/.test(value)) return parseFloat(value);
if (/^0(px|%|em|rem|pt|vh|vw)$/.test(value)) return 0;
return value;
}
/**
* Merges parsed styles in cascade order. A later value wins unless an
* earlier one was !important; a later !important wins over an earlier one.
*/
mergeStyles(styleObjects) {
if (!Array.isArray(styleObjects)) return {};
const importantSoFar = new Set();
const finalStyle = {};
for (const styleObj of styleObjects) {
if (!styleObj || !styleObj.computedStyle) continue;
const { computedStyle, importantProperties = [] } = styleObj;
for (const [prop, value] of Object.entries(computedStyle)) {
const isImportant = importantProperties.includes(prop);
if (!importantSoFar.has(prop) || isImportant) {
finalStyle[prop] = value;
if (isImportant) importantSoFar.add(prop);
}
}
}
return finalStyle;
}
// ---------------------------------------------------------------------------
// Instance styles
// ---------------------------------------------------------------------------
/** Merged style of an instance (classes in order, then the inline style), cached on the bag. */
getInstanceStyles(instance) {
const bag = instance.__flexbox_ui_element;
if (!bag) return EMPTY_STYLE;
if (bag._computedStyle !== undefined) return bag._computedStyle;
const stylesToMerge = [];
for (const className of bag.classes || []) {
if (this.registeredClasses.has(className)) {
stylesToMerge.push(this.registeredClasses.get(className));
}
}
if (bag.style) stylesToMerge.push(bag.style);
bag._computedStyle = this.mergeStyles(stylesToMerge);
return bag._computedStyle;
}
/** Call after changing an instance's classes or inline style, or a class it uses. */
invalidateStyles(instance) {
const bag = instance.__flexbox_ui_element;
if (bag) bag._computedStyle = undefined;
}
getLayoutProperties(instance) {
const styles = this.getInstanceStyles(instance);
let props = this.layoutPropsCache.get(styles);
if (!props) {
props = this.computeLayoutProperties(styles);
this.layoutPropsCache.set(styles, props);
}
return props;
}
computeLayoutProperties(styles) {
const fit = styles.fitContent;
const fitBoth = fit === "true" || fit === "both" || fit === "xy";
const fitContentX = fitBoth || fit === "x" || styles.width === "fit-content";
const fitContentY = fitBoth || fit === "y" || styles.height === "fit-content";
return {
display: styles.display || "column", // column, row, column-reverse, row-reverse, grid
position: styles.position || "relative", // relative, absolute, anchor
gap: styles.gap || 0,
alignItems: styles.alignItems || "start", // start, center, end
alignContent: styles.alignContent || "start", // start, center, end, space-between, space-around, stretch
justifyContent: styles.justifyContent || "start", // start, center, end, space-between, space-around
flexWrap: styles.flexWrap || "nowrap", // nowrap, wrap, wrap-reverse
columns: styles.columns || 2,
fitContent: fitContentX || fitContentY,
fitContentX,
fitContentY,
top: styles.top,
right: styles.right,
bottom: styles.bottom,
left: styles.left,
anchorTarget: styles.anchorTarget, // tag, "parent", or an instance
anchorPoint: styles.anchorPoint || "center",
selfAnchor: styles.selfAnchor || "center",
anchorOffsetX: styles.anchorOffsetX || 0,
anchorOffsetY: styles.anchorOffsetY || 0,
};
}
/** Margin, padding and border per side. Shorthands are expanded at parse time, so only longhands exist here. */
getBoxModel(instance) {
const styles = this.getInstanceStyles(instance);
let boxModel = this.boxModelCache.get(styles);
if (!boxModel) {
boxModel = this.computeBoxModel(styles);
this.boxModelCache.set(styles, boxModel);
}
return boxModel;
}
computeBoxModel(s) {
return {
margin: {
top: s.marginTop ?? 0,
right: s.marginRight ?? 0,
bottom: s.marginBottom ?? 0,
left: s.marginLeft ?? 0,
},
padding: {
top: s.paddingTop ?? 0,
right: s.paddingRight ?? 0,
bottom: s.paddingBottom ?? 0,
left: s.paddingLeft ?? 0,
},
border: {
top: s.borderTopWidth ?? 0,
right: s.borderRightWidth ?? 0,
bottom: s.borderBottomWidth ?? 0,
left: s.borderLeftWidth ?? 0,
},
};
}
getOuterWidth(instance) {
return this.getOuterSize(instance, AXES.x);
}
getOuterHeight(instance) {
return this.getOuterSize(instance, AXES.y);
}
hasPercentageSizing(styles) {
return (
isPercent(styles.width) ||
isPercent(styles.height) ||
isPercent(styles.flexBasis)
);
}
/** Clamps the instance to its min/max styles. Max wins over min. */
applyMinMaxConstraints(instance, styles) {
const result = { widthConstrained: false, heightConstrained: false };
for (const ax of [AXES.x, AXES.y]) {
const size = this.getSize(instance, ax);
const clamped = clamp(size, styles[ax.min], styles[ax.max]);
if (clamped !== size) {
this.setSize(instance, ax, clamped);
result[ax.size + "Constrained"] = true;
}
}
return result;
}
/** Visible, enabled children that take part in the parent's flow. */
getLayoutChildren(instance) {
return this.partitionChildren(instance).inFlow;
}
/** Visible, enabled children positioned absolutely or by anchor. */
getOutOfFlowChildren(instance) {
return this.partitionChildren(instance).outOfFlow;
}
/** Splits the visible, enabled children into in-flow and out-of-flow lists. */
partitionChildren(instance) {
const inFlow = [];
const outOfFlow = [];
for (const child of instance.children()) {
if (!child.isVisible || child.__flexbox_ui_element?.enabled === false) continue;
(this.isOutOfFlow(child) ? outOfFlow : inFlow).push(child);
}
inFlow.sort((a, b) => (a._layoutOrder || 0) - (b._layoutOrder || 0));
return { inFlow, outOfFlow };
}
isOutOfFlow(instance) {
const position = this.getInstanceStyles(instance).position || "relative";
return position === "absolute" || position === "anchor";
}
// ---------------------------------------------------------------------------
// Geometry helpers. Sizes and positions are bounding-box based, so a rotated
// instance is laid out by its axis-aligned box.
// ---------------------------------------------------------------------------
/**
* The instance's bounding box as read once during this pass. Valid because
* a pass only writes through setStart/setSize, which update or drop the
* entry, and because both passes visit parents before children, so a child
* is first read after its parent has been placed.
*/
box(instance) {
let rect = this.boxCache.get(instance);
if (!rect) {
const b = instance.getBoundingBox();
rect = { left: b.left, top: b.top, width: b.width, height: b.height };
this.boxCache.set(instance, rect);
}
return rect;
}
getInstanceX(instance) {
return this.box(instance).left;
}
getInstanceY(instance) {
return this.box(instance).top;
}
getInstanceWidth(instance) {
return this.box(instance).width;
}
getInstanceHeight(instance) {
return this.box(instance).height;
}
setInstanceX(instance, x) {
this.setStart(instance, AXES.x, x);
}
setInstanceY(instance, y) {
this.setStart(instance, AXES.y, y);
}
setInstanceWidth(instance, width) {
this.setSize(instance, AXES.x, width);
}
setInstanceHeight(instance, height) {
this.setSize(instance, AXES.y, height);
}
getSize(instance, ax) {
return this.box(instance)[ax.size];
}
getStart(instance, ax) {
return this.box(instance)[ax.start];
}
/** Moves the instance so its box starts at `value` on one axis. */
setStart(instance, ax, value) {
const rect = this.box(instance);
const data = this.node(instance);
if (!near(rect[ax.start], value)) {
instance[ax.name] += value - rect[ax.start];
rect[ax.start] = value;
data.moved = true;
}
const parent = instance.getParent();
if (parent) data.seen[ax.start] = value - this.box(parent)[ax.start];
}
/**
* Sets the bounding-box size on one axis, keeping the origin in place.
* Construct's setters skip a write whose value is unchanged (and the bbox
* invalidation that goes with it), so an unchanged size is left alone
* rather than rewritten through the rotation ratio, which could drift.
*/
setSize(instance, ax, value) {
const data = this.node(instance);
const before = this.box(instance)[ax.size];
if (!near(before, value)) {
// Raw size and box size differ on a rotated instance; scale the raw size
// by the ratio unless there is none to keep (zero size).
const raw = instance[ax.size];
instance[ax.size] = raw === 0 || before === 0 ? value : value * (raw / before);
data.resized = true;
// The origin stays put, so the box's start edge moved by an amount that
// depends on the origin: read the box again.
this.boxCache.delete(instance);
const parent = instance.getParent();
if (parent) data.seen[ax.start] = this.box(instance)[ax.start] - this.box(parent)[ax.start];
}
data.written[ax.size] = instance[ax.size];
data.seen[ax.size] = this.box(instance)[ax.size];
}
getOuterSize(instance, ax) {
const margin = this.getBoxModel(instance).margin;
return this.getSize(instance, ax) + margin[ax.start] + margin[ax.end];
}
/** Intrinsic size from the last measure plus margins; what a parent measures children by. */
getIntrinsicOuterSize(instance, ax) {
const margin = this.getBoxModel(instance).margin;
return this.node(instance).intrinsic[ax.size] + margin[ax.start] + margin[ax.end];
}
/** Size available to children on one axis: size minus padding and border. */
getContentSize(instance, ax, boxModel = this.getBoxModel(instance)) {
return (
this.getSize(instance, ax) -
boxModel.padding[ax.start] -
boxModel.padding[ax.end] -
boxModel.border[ax.start] -
boxModel.border[ax.end]
);
}
/** Where the content box starts on one axis, in layout coordinates. */
getContentStart(instance, ax, boxModel = this.getBoxModel(instance)) {
return this.getStart(instance, ax) + boxModel.padding[ax.start] + boxModel.border[ax.start];
}
node(instance) {
let data = this.nodeData.get(instance);
if (!data) {
data = {
written: {}, // raw width/height the engine last wrote
base: {}, // authored size, see getBaseSize
seen: {}, // bbox width/height and left/top relative to the parent after the last write
seenTarget: null, // anchor target's box at the last measure
styles: null, // merged style object at the last measure
intrinsic: {}, // size after the last measure
inFlow: null, // active children at the last measure
outOfFlow: null,
resized: false, // size changed by a write this tick
moved: false, // position changed by a write this tick
affectsParent: false, // parent must lay out again because of this node
needsLayout: false, // this node must place its children
visit: false, // this node or a descendant needs layout
};
this.nodeData.set(instance, data);
}
return data;
}
/**
* The authored size on one axis: the instance's size unless the engine set
* it, in which case the size the engine started from.
*/
getBaseSize(instance, ax) {
const data = this.node(instance);
const bboxSize = this.getSize(instance, ax);
if (
data.base[ax.size] === undefined ||
data.written[ax.size] !== instance[ax.size] ||
!near(data.seen[ax.size], bboxSize)
) {
data.base[ax.size] = bboxSize;
}
return data.base[ax.size];
}
// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------
/** Lays out an instance and its whole subtree. Call on layout roots every tick. */
processInstance(instance) {
const angle = instance.angleDegrees;
instance.angleDegrees = 0;
this.stats.measured = 0;
this.stats.laidOut = 0;
this.boxCache = new WeakMap();
this.measure(instance);
this.boxCache = new WeakMap();
this.run(instance, this.forceFullLayout);
instance.angleDegrees = angle;
}
// ---------------------------------------------------------------------------
// Measure pass
// ---------------------------------------------------------------------------
/**
* Sets the instance's intrinsic size after measuring its children, and
* decides what has changed since the last tick (see the header).
*/
measure(instance) {
const data = this.node(instance);
const styles = this.getInstanceStyles(instance);
const props = this.getLayoutProperties(instance);
const { inFlow: children, outOfFlow } = this.partitionChildren(instance);
const stylesChanged = data.styles !== styles;
const listChanged = !sameList(data.inFlow, children) || !sameList(data.outOfFlow, outOfFlow);
data.styles = styles;
data.inFlow = children;
data.outOfFlow = outOfFlow;
data.resized = false;
data.moved = false;
this.stats.measured++;
for (const child of children) this.measure(child);
for (const child of outOfFlow) this.measure(child);
const externalChanged = this.detectExternalChange(instance, data, props);
const selfChanged = stylesChanged || listChanged || externalChanged;
const size = {};
for (const ax of [AXES.x, AXES.y]) {
// Always read the authored size first so it is captured before the first write.
const base = this.getBaseSize(instance, ax);
size[ax.size] = typeof styles[ax.size] === "number" ? styles[ax.size] : base;
}
if (props.fitContent) {
const boxModel = this.getBoxModel(instance);
const content = this.measureContent(instance, props, children, size, boxModel);
for (const ax of [AXES.x, AXES.y]) {
if (!props[ax.fitContent]) continue;
size[ax.size] =
content[ax.size] +
boxModel.padding[ax.start] +
boxModel.padding[ax.end] +
boxModel.border[ax.start] +
boxModel.border[ax.end];
}
}
for (const ax of [AXES.x, AXES.y]) {
size[ax.size] = clamp(size[ax.size], styles[ax.min], styles[ax.max]);
}
const intrinsicChanged = !near(data.intrinsic.width, size.width) || !near(data.intrinsic.height, size.height);
data.intrinsic = size;
// The parent re-places this node when its styles, intrinsic size or
// position changed; only then is the size reset to the intrinsic one.
// Otherwise the node keeps the size its parent gave it (flex, percent).
const affectsParent = stylesChanged || externalChanged || intrinsicChanged;
if (affectsParent) {
for (const ax of [AXES.x, AXES.y]) this.setSize(instance, ax, size[ax.size]);
}
let childrenAffect = false;
let childrenVisit = false;
for (const child of children) {
const c = this.node(child);
childrenAffect = childrenAffect || c.affectsParent;
childrenVisit = childrenVisit || c.visit;
}
for (const child of outOfFlow) {
const c = this.node(child);
childrenAffect = childrenAffect || c.affectsParent;
childrenVisit = childrenVisit || c.visit;
}
// A changed child list only matters here; the parent sees the same node.
data.affectsParent = affectsParent;
data.needsLayout = selfChanged || childrenAffect;
data.visit = data.needsLayout || childrenVisit;
}
/**
* True when something outside the engine changed this instance since the
* engine last wrote it: its raw size, its bounding box (an angle change),
* its position relative to the parent, or the box of the instance it is
* anchored to.
*/
detectExternalChange(instance, data, props) {
const bbox = this.box(instance);
let changed = false;
for (const ax of [AXES.x, AXES.y]) {
if (data.written[ax.size] !== undefined && data.written[ax.size] !== instance[ax.size]) changed = true;
if (!near(data.seen[ax.size], bbox[ax.size])) changed = true;
}
const parent = instance.getParent();
if (parent) {
const parentBox = this.box(parent);
for (const ax of [AXES.x, AXES.y]) {
if (!near(data.seen[ax.start], bbox[ax.start] - parentBox[ax.start])) changed = true;
}
}
if (props.position === "anchor" && props.anchorTarget && props.anchorTarget !== "parent") {
const target = this.findAnchorTarget(instance, props.anchorTarget);
const box = target ? this.box(target) : null;
const seen = data.seenTarget;
if (!box || !seen) {
changed = changed || box !== seen;
} else if (
!near(seen.left, box.left) ||
!near(seen.top, box.top) ||
!near(seen.width, box.width) ||
!near(seen.height, box.height)
) {
changed = true;
}
data.seenTarget = box ? { left: box.left, top: box.top, width: box.width, height: box.height } : null;
}
return changed;
}
/**
* The extent of the children (their intrinsic sizes, margins and gaps) for
* the container's display mode. `size` is the container's size before fitting;
* wrapping happens within it.
*/
measureContent(instance, props, children, size, boxModel) {
const gap = props.gap;
const outer = (child, ax) => this.getIntrinsicOuterSize(child, ax);
if (props.display === "grid") {
const cell = this.getGridCellSize(children, outer);
const columns = props.columns;
const rows = Math.ceil(children.length / columns);
return {
width: columns * cell.width + Math.max(0, columns - 1) * gap,
height: rows * cell.height + Math.max(0, rows - 1) * gap,
};
}
const { main, cross } = this.getAxes(props.display);
const content = {};
if (props.flexWrap === "nowrap") {
let mainSize = 0;
let crossSize = 0;
children.forEach((child, index) => {
mainSize += outer(child, main) + (index > 0 ? gap : 0);
crossSize = Math.max(crossSize, outer(child, cross));
});
content[main.size] = mainSize;
content[cross.size] = crossSize;
} else {
const available =
size[main.size] -
boxModel.padding[main.start] -
boxModel.padding[main.end] -
boxModel.border[main.start] -
boxModel.border[main.end];
const lines = this.breakLines(children, main, cross, available, gap, outer);
content[main.size] = lines.reduce((max, line) => Math.max(max, line.main), 0);
content[cross.size] = lines.reduce((sum, line, i) => sum + line.cross + (i > 0 ? gap : 0), 0);
}
return content;
}
getAxes(display) {
return ROW_DISPLAYS.has(display)
? { main: AXES.x, cross: AXES.y }
: { main: AXES.y, cross: AXES.x };
}
// ---------------------------------------------------------------------------
// Layout pass
// ---------------------------------------------------------------------------
/**
* Walks the tree after measure. A node places its children when it needs
* layout (or when forced); the walk continues into children that need
* layout, contain a node that does, or were resized or moved by this
* placement. Moved children are re-placed so their own children land in
* the right spot this tick even when Construct does not move them along
* (hierarchy transform X/Y off).
*/
run(instance, forced) {
const data = this.node(instance);
const needs = forced || data.needsLayout;
if (needs) this.placeChildren(instance, data);
for (const child of data.inFlow) {
const c = this.node(child);
if (forced || c.visit || c.resized || c.moved) this.run(child, forced || c.resized || c.moved);
}
for (const child of data.outOfFlow) {
const c = this.node(child);
if (forced || c.visit || c.resized || c.moved) this.run(child, forced || c.resized || c.moved);
}
}
/** Lays out the whole subtree unconditionally. */
layout(instance) {
this.run(instance, true);
}
/** Sizes and positions the children of an instance whose own size is final. */
placeChildren(instance, data = this.node(instance)) {
const props = this.getLayoutProperties(instance);
const children = data.inFlow;
if (children.length + data.outOfFlow.length === 0) return;
this.stats.laidOut++;
for (const child of children) this.resolveChildSize(instance, child);
if (props.display === "grid") {
this.layoutGrid(instance, props, children);
} else {
const { main, cross } = this.getAxes(props.display);
const ordered = props.display.endsWith("-reverse") ? [...children].reverse() : children;
if (props.flexWrap === "nowrap") {
this.layoutFlexLine(instance, props, ordered, main, cross);
} else {
this.layoutFlexWrap(instance, props, ordered, main, cross);
}
}
for (const child of data.outOfFlow) {
this.resolveChildSize(instance, child);
this.positionOutOfFlow(child);
}
}
/** Resolves a child's percent width/height against the parent's content box, then min/max. */
resolveChildSize(parent, child) {
const styles = this.getInstanceStyles(child);
if (!this.hasPercentageSizing(styles)) return;
const parentBoxModel = this.getBoxModel(parent);
for (const ax of [AXES.x, AXES.y]) {
if (!isPercent(styles[ax.size])) continue;
const percent = toNumber(styles[ax.size], 0);
if (percent < 0) continue;
const available = this.getContentSize(parent, ax, parentBoxModel);
this.setSize(child, ax, (available * percent) / 100);
}
this.applyMinMaxConstraints(child, styles);
}
/**
* Flex properties of a child as an item record. Children without any flex
* property are rigid (grow 0, shrink 0). Any flex property present gives the
* CSS default shrink of 1.
*/
getFlexItem(child, main, contentMain) {
const styles = this.getInstanceStyles(child);
const boxModel = this.getBoxModel(child);
const hasFlex =
styles.flexGrow !== undefined || styles.flexShrink !== undefined || styles.flexBasis !== undefined;
let basis = this.getSize(child, main);
const rawBasis = styles.flexBasis;
if (typeof rawBasis === "number") basis = rawBasis;
else if (isPercent(rawBasis)) basis = (contentMain * toNumber(rawBasis, 0)) / 100;
else if (typeof rawBasis === "string" && rawBasis !== "auto") basis = toNumber(rawBasis, basis);
return {
instance: child,
styles,
boxModel,
grow: Math.max(0, toNumber(styles.flexGrow, 0)),
shrink: Math.max(0, toNumber(styles.flexShrink, hasFlex ? 1 : 0)),
basis,
min: styles[main.min],
max: styles[main.max],
margin: boxModel.margin[main.start] + boxModel.margin[main.end],
target: 0,
frozen: false,
};
}
/**
* Resolves the main sizes of the items on one line (CSS Flexbox 9.7): items
* start at their flex basis, free space is shared by grow or shrink factor,
* and items that hit a min or max are frozen there and the rest is shared
* again among the others.
*/
resolveFlexSizes(items, main, contentMain, gap) {
const gaps = Math.max(0, items.length - 1) * gap;
let hypothetical = gaps;
for (const item of items) {
item.target = clamp(item.basis, item.min, item.max);
hypothetical += item.target + item.margin;
}
const growing = hypothetical < contentMain;
for (const item of items) {
const factor = growing ? item.grow : item.shrink;
const wrongWay = growing ? item.basis > item.target : item.basis < item.target;
if (factor === 0 || wrongWay) item.frozen = true;
}
for (let pass = 0; pass <= items.length; pass++) {
const unfrozen = items.filter((item) => !item.frozen);
if (unfrozen.length === 0) break;
let remaining = contentMain - gaps;
for (const item of items) {
remaining -= (item.frozen ? item.target : item.basis) + item.margin;
}
if (growing) {
const totalGrow = unfrozen.reduce((sum, item) => sum + item.grow, 0);
for (const item of unfrozen) {
item.target = item.basis + (totalGrow > 0 ? (remaining * item.grow) / totalGrow : 0);
}
} else {
const totalWeight = unfrozen.reduce((sum, item) => sum + item.shrink * item.basis, 0);
for (const item of unfrozen) {
const weight = totalWeight > 0 ? (item.shrink * item.basis) / totalWeight : 0;
item.target = Math.max(0, item.basis + remaining * weight);
}
}
let totalViolation = 0;
for (const item of unfrozen) {
item.clamped = clamp(item.target, item.min, item.max);
item.violation = item.clamped - item.target;
totalViolation += item.violation;
}
for (const item of unfrozen) {
const freeze =
totalViolation === 0 ||
(totalViolation > 0 && item.violation > 0) ||
(totalViolation < 0 && item.violation < 0);
if (freeze) {
item.target = item.clamped;
item.frozen = true;
}
}
}
for (const item of items) this.setSize(item.instance, main, item.target);
}
/** Column or row without wrapping. `children` are already in layout order. */
layoutFlexLine(container, props, children, main, cross) {
const boxModel = this.getBoxModel(container);
const contentMain = this.getContentSize(container, main, boxModel);
const contentCross = this.getContentSize(container, cross, boxModel);
const gap = props.gap;