-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_layout.js
More file actions
2579 lines (2251 loc) · 80.7 KB
/
ui_layout.js
File metadata and controls
2579 lines (2251 loc) · 80.7 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
class UILayout {
constructor(runtime) {
this.runtime = runtime;
// Map to store registered classes and their styles
this.registeredClasses = new Map();
this.cachedBboxes = new WeakMap();
}
/**
* Register a class with its style definition
* @param {string} className - Name of the class
* @param {string} styleString - CSS-like style string
*/
registerClass(className, styleString) {
const parsedStyle = this.parseStyle(styleString);
this.registeredClasses.set(className, parsedStyle);
}
getClassStyle(className) {
if (!this.registeredClasses.has(className)) {
this.registerClass(className, "");
}
return this.registeredClasses.get(className);
}
/**
* Parses CSS-like text into a style object
* Enhanced to support flex properties and shorthand
*
* @param {string} cssText - CSS-like text with properties
* @returns {Object} Object containing computed style and important properties
*/
parseStyle(cssText) {
if (!cssText) return { computedStyle: {}, importantProperties: [] };
const computedStyle = {};
const importantProperties = [];
// Split the input text by line breaks
const lines = cssText.split("\n").join(";").split(";");
for (let line of lines) {
// Remove any whitespace and optional semicolon
line = line.trim();
if (!line) continue;
if (line.endsWith(";")) {
line = line.slice(0, -1);
}
// Split by the first colon
const colonIndex = line.indexOf(":");
if (colonIndex === -1) continue;
const property = line.substring(0, colonIndex).trim();
let value = line.substring(colonIndex + 1).trim();
if (!property || !value) continue;
// Check for !important
const isImportant = value.includes("!important");
if (isImportant) {
value = value.replace(/\s*!important\s*$/, "").trim();
// Convert kebab-case to camelCase for the important list
importantProperties.push(this.kebabToCamel(property));
}
// Convert kebab-case to camelCase if needed
const camelProperty = this.kebabToCamel(property);
// Special handling for flex shorthand
if (camelProperty === "flex") {
this.parseFlexShorthand(value, computedStyle);
continue;
}
// Convert value if needed (handling numbers)
computedStyle[camelProperty] = this.convertValue(value);
}
return {
computedStyle,
importantProperties,
};
}
removePropertyFromStyle(style, property) {
const camelProperty = this.kebabToCamel(property);
if (style.computedStyle.hasOwnProperty(camelProperty)) {
delete style.computedStyle[camelProperty];
}
const importantIndex = style.importantProperties.indexOf(camelProperty);
if (importantIndex !== -1) {
style.importantProperties.splice(importantIndex, 1);
}
}
setPropertyInStyle(style, property, value) {
this.removePropertyFromStyle(style, property);
if (!value) {
return;
}
const extraStyle = this.parseStyle(`${property}: ${value};`);
style.computedStyle = {
...style.computedStyle,
...extraStyle.computedStyle,
};
style.importantProperties = [
...style.importantProperties,
...extraStyle.importantProperties,
];
}
/**
* Parse flex shorthand property into individual flex properties
* @param {string} value - The flex shorthand value
* @param {Object} computedStyle - The style object to update
*/
parseFlexShorthand(value, computedStyle) {
const parts = value.split(/\s+/);
// Handle different formats of the flex shorthand
if (parts.length === 1) {
// Single value can be either a number (flex-grow) or a keyword
if (parts[0] === "auto") {
computedStyle["flexGrow"] = 1;
computedStyle["flexShrink"] = 1;
computedStyle["flexBasis"] = "auto";
} else if (parts[0] === "none") {
computedStyle["flexGrow"] = 0;
computedStyle["flexShrink"] = 0;
computedStyle["flexBasis"] = "auto";
} else if (parts[0] === "initial") {
computedStyle["flexGrow"] = 0;
computedStyle["flexShrink"] = 1;
computedStyle["flexBasis"] = "auto";
} else {
// Assume it's a flex-grow value
computedStyle["flexGrow"] = this.convertValue(parts[0]);
computedStyle["flexShrink"] = 1;
computedStyle["flexBasis"] = "0";
}
} else if (parts.length === 2) {
// Two values: flex-grow and flex-shrink or flex-basis
computedStyle["flexGrow"] = this.convertValue(parts[0]);
// Check if second part is a number (flex-shrink) or has units (flex-basis)
if (/^\d+(\.\d+)?$/.test(parts[1])) {
computedStyle["flexShrink"] = this.convertValue(parts[1]);
computedStyle["flexBasis"] = "0";
} else {
computedStyle["flexShrink"] = 1;
computedStyle["flexBasis"] = parts[1];
}
} else if (parts.length >= 3) {
// Three values: flex-grow, flex-shrink, and flex-basis
computedStyle["flexGrow"] = this.convertValue(parts[0]);
computedStyle["flexShrink"] = this.convertValue(parts[1]);
computedStyle["flexBasis"] = parts[2];
}
}
/**
* Converts kebab-case to camelCase (e.g., min-width → minWidth)
* @param {string} str - Property name to convert
* @returns {string} camelCase property name
*/
kebabToCamel(str) {
return str.replace(/-([a-z])/g, (match, group) => group.toUpperCase());
}
/**
* Converts string values to appropriate types
* @param {string} value - Value to convert
* @returns {string|number} Converted value
*/
convertValue(value) {
// If it's a pure number (no units), convert to number type
if (/^-?\d+(\.\d+)?$/.test(value)) {
return parseFloat(value);
}
// Special case for zero with units - just return 0
if (/^0(px|%|em|rem|pt|vh|vw)$/.test(value)) {
return 0;
}
// Otherwise keep as string (for percentages, auto, etc.)
return value;
}
/**
* Merges multiple style objects while respecting !important declarations
*
* @param {Array} styleObjects - Array of style objects from parseStyle
* @returns {Object} Final merged style object
*/
mergeStyles(styleObjects) {
if (!styleObjects || !Array.isArray(styleObjects)) return {};
// Track properties that have been applied with !important
const appliedImportantProps = new Set();
// Final computed style to apply to the node
const finalStyle = {};
// Process each style object in order (like CSS cascade)
for (const styleObj of styleObjects) {
if (!styleObj || !styleObj.computedStyle) continue;
const { computedStyle, importantProperties = [] } = styleObj;
// Process each property in the current style
for (const [prop, value] of Object.entries(computedStyle)) {
const isCurrentPropImportant = importantProperties.includes(prop);
// Apply the property if:
// 1. This property hasn't been applied yet as !important, OR
// 2. This property is being applied with !important now
if (!appliedImportantProps.has(prop) || isCurrentPropImportant) {
finalStyle[prop] = value;
// Track if we're applying this as important
if (isCurrentPropImportant) {
appliedImportantProps.add(prop);
}
}
}
}
return finalStyle;
}
/**
* Process an instance and its children following correct cascade order
* @param {WorldInstance} instance - The instance to process
*/
processInstance(instance) {
// 1. Calculate and apply styles to current instance
const instanceAngle = instance.angleDegrees;
instance.angleDegrees = 0; // Temporarily reset angle for layout calculations
// this.invalidateInstanceBBox(instance);
const styles = this.getInstanceStyles(instance);
this.applyStylesToInstance(instance, styles);
// 2. Get layout properties for current instance
const layoutProps = this.getLayoutProperties(instance);
if (!instance.getParent()) {
layoutProps.position = "relative";
}
// 3. Separate children into in-flow and out-of-flow
const children = [...instance.children()];
const inFlowChildren = [];
const outOfFlowChildren = [];
const percentSizedChildren = [];
for (const child of children) {
// Skip non-visible or explicitly disabled children
if (!child.isVisible || child.__flexbox_ui_element?.enabled === false) {
continue;
}
// Apply preliminary styles to determine positioning
const childStyles = this.getInstanceStyles(child);
// Check if child has percentage-based sizing
if (this.hasPercentageSizing(childStyles)) {
percentSizedChildren.push(child);
}
const childPosition = childStyles.position || "relative";
if (childPosition === "absolute" || childPosition === "anchor") {
outOfFlowChildren.push(child);
} else {
inFlowChildren.push(child);
}
}
// 4. FIRST recursively process all in-flow children to establish their base sizes
for (const child of inFlowChildren) {
this.processInstance(child);
}
// 5. THEN apply normal flow layout now that children are properly sized
if (
layoutProps.display &&
layoutProps.position !== "absolute" &&
layoutProps.position !== "anchor"
) {
this.applyNormalFlowLayout(instance, layoutProps, inFlowChildren);
}
// 6. Apply fit-content sizing if needed (after children are sized)
if (layoutProps.fitContent) {
this.applyFitContentSizing(instance, layoutProps);
// 6.1 If size changed and we have percentage-sized children, reapply their sizing
if (percentSizedChildren.length > 0) {
for (const child of percentSizedChildren) {
// Reapply the percentage sizing now that parent dimensions are finalized
this.applyPercentageSizing(child);
}
// 6.2 And reapply layout to ensure positions are correct with new sizes
if (
layoutProps.display &&
layoutProps.position !== "absolute" &&
layoutProps.position !== "anchor"
) {
this.applyNormalFlowLayout(instance, layoutProps, inFlowChildren);
}
}
// 6.3 Reapply normal flow layout if the container size changed and we have flex children
else if (
layoutProps.display &&
layoutProps.position !== "absolute" &&
layoutProps.position !== "anchor" &&
this.hasFlexChildren(inFlowChildren)
) {
this.applyNormalFlowLayout(instance, layoutProps, inFlowChildren);
}
}
// 7. Process out-of-flow positioned elements AFTER regular flow
for (const child of outOfFlowChildren) {
// Process the out-of-flow child first to ensure its size is calculated
this.processInstance(child);
// Now position it relative to its container or anchor target
this.applyOutOfFlowLayout(child);
}
instance.angleDegrees = instanceAngle;
}
/**
* Check if any children have flex properties set
* @param {Array} children - Array of child instances
* @returns {boolean} True if any child has flex properties
*/
hasFlexChildren(children) {
return children.some((child) => {
const styles = this.getInstanceStyles(child);
return (
(styles.flexGrow && styles.flexGrow > 0) ||
typeof styles.flexShrink !== "undefined" ||
(styles.flexBasis && styles.flexBasis !== "auto")
);
});
}
/**
* Get styles for an instance based on its inline style and classes
* @param {WorldInstance} instance - The instance to get styles for
* @returns {Object} Merged style object
*/
getInstanceStyles(instance) {
if (!instance.__flexbox_ui_element) return {};
if (instance.__flexbox_ui_element._computedStyle !== undefined) {
return instance.__flexbox_ui_element._computedStyle;
}
const stylesToMerge = [];
// Get classes from instance variables
const classes = instance.__flexbox_ui_element.classes || [];
// Add styles from each class
for (const className of classes) {
if (this.registeredClasses.has(className)) {
stylesToMerge.push(this.registeredClasses.get(className));
}
}
// Add inline style if present
const inlineStyle = instance.__flexbox_ui_element.style || {};
if (inlineStyle) {
stylesToMerge.push(inlineStyle);
}
// Merge all styles
instance.__flexbox_ui_element._computedStyle =
this.mergeStyles(stylesToMerge);
return instance.__flexbox_ui_element._computedStyle;
}
/**
* Check if an element has percentage-based sizing
* @param {Object} styles - Element styles
* @returns {boolean} True if element has percentage sizing
*/
hasPercentageSizing(styles) {
// Check for percentWidth/percentHeight properties
if ("percentWidth" in styles || "percentHeight" in styles) {
return true;
}
// Check for width/height with percentage strings
if (
styles.width &&
typeof styles.width === "string" &&
styles.width.endsWith("%")
) {
return true;
}
if (
styles.height &&
typeof styles.height === "string" &&
styles.height.endsWith("%")
) {
return true;
}
// Check for flex-basis with percentage
if (
styles.flexBasis &&
typeof styles.flexBasis === "string" &&
styles.flexBasis.endsWith("%")
) {
return true;
}
return false;
}
/**
* Apply percentage-based sizing to an element
* @param {WorldInstance} instance - The instance to size
*/
applyPercentageSizing(instance) {
if (!instance.getParent()) {
return;
}
const styles = this.getInstanceStyles(instance);
if (!styles) return;
const parent = instance.getParent();
const parentBoxModel = this.getBoxModel(parent);
const isRow = styles.display === "row" || styles.display === "row-reverse";
const isColumn =
styles.display === "column" ||
styles.display === "column-reverse" ||
!styles.display;
// Apply width percentages if present
if (
"percentWidth" in styles ||
(styles.width &&
typeof styles.width === "string" &&
styles.width.endsWith("%"))
) {
const percentValue =
"percentWidth" in styles
? styles.percentWidth
: parseFloat(styles.width) || 0;
if (percentValue >= 0) {
const availableWidth =
this.getInstanceWidth(parent) -
parentBoxModel.padding.left -
parentBoxModel.padding.right -
parentBoxModel.border.left -
parentBoxModel.border.right;
this.setInstanceWidth(instance, (availableWidth * percentValue) / 100);
}
}
// Apply height percentages if present
if (
"percentHeight" in styles ||
(styles.height &&
typeof styles.height === "string" &&
styles.height.endsWith("%"))
) {
const percentValue =
"percentHeight" in styles
? styles.percentHeight
: parseFloat(styles.height) || 0;
if (percentValue >= 0) {
const availableHeight =
this.getInstanceHeight(parent) -
parentBoxModel.padding.top -
parentBoxModel.padding.bottom -
parentBoxModel.border.top -
parentBoxModel.border.bottom;
this.setInstanceHeight(
instance,
(availableHeight * percentValue) / 100
);
}
}
// Apply flex-basis percentages if appropriate for the main axis
if (
styles.flexBasis &&
typeof styles.flexBasis === "string" &&
styles.flexBasis.endsWith("%")
) {
const percentValue = parseFloat(styles.flexBasis) || 0;
if (percentValue >= 0) {
if (isRow) {
const availableWidth =
this.getInstanceWidth(parent) -
parentBoxModel.padding.left -
parentBoxModel.padding.right -
parentBoxModel.border.left -
parentBoxModel.border.right;
this.setInstanceWidth(
instance,
(availableWidth * percentValue) / 100
);
} else if (isColumn) {
const availableHeight =
this.getInstanceHeight(parent) -
parentBoxModel.padding.top -
parentBoxModel.padding.bottom -
parentBoxModel.border.top -
parentBoxModel.border.bottom;
this.setInstanceHeight(
instance,
(availableHeight * percentValue) / 100
);
}
}
}
// Apply min/max constraints
this.applyMinMaxConstraints(instance, styles);
}
/**
* Apply min/max constraints to an instance
* @param {WorldInstance} instance - The instance to constrain
* @param {Object} styles - Style object with constraints
* @returns {Object} Info about which constraints were applied
*/
applyMinMaxConstraints(instance, styles) {
const constraints = {
minWidth: styles.minWidth,
maxWidth: styles.maxWidth,
minHeight: styles.minHeight,
maxHeight: styles.maxHeight,
};
let widthConstrained = false;
let heightConstrained = false;
// Apply min width constraint
if (
constraints.minWidth !== undefined &&
this.getInstanceWidth(instance) < constraints.minWidth
) {
this.setInstanceWidth(instance, constraints.minWidth);
widthConstrained = true;
}
// Apply max width constraint
if (
constraints.maxWidth !== undefined &&
this.getInstanceWidth(instance) > constraints.maxWidth
) {
this.setInstanceWidth(instance, constraints.maxWidth);
widthConstrained = true;
}
// Apply min height constraint
if (
constraints.minHeight !== undefined &&
this.getInstanceHeight(instance) < constraints.minHeight
) {
this.setInstanceHeight(instance, constraints.minHeight);
heightConstrained = true;
}
// Apply max height constraint
if (
constraints.maxHeight !== undefined &&
this.getInstanceHeight(instance) > constraints.maxHeight
) {
this.setInstanceHeight(instance, constraints.maxHeight);
heightConstrained = true;
}
return { widthConstrained, heightConstrained };
}
/**
* Get computed layout properties from styles
* @param {WorldInstance} instance - The instance to get layout properties for
* @returns {Object} Layout properties
*/
getLayoutProperties(instance) {
const styles = this.getInstanceStyles(instance);
return {
display: styles.display || "column", // column, row, column-reverse, row-reverse, grid
position: styles.position || "relative", // relative, absolute, anchor
gap: styles.gap || 0,
padding: styles.padding || 0,
alignItems: styles.alignItems || styles.alignment || "start", // start, center, end
justifyContent: styles.justifyContent || "start", // start, center, end, space-between, space-around
flexWrap: styles.flexWrap || "nowrap", // nowrap, wrap, wrap-reverse
columns: styles.columns || 2,
fitContent: styles.fitContent === "true",
top: styles.top,
right: styles.right,
bottom: styles.bottom,
left: styles.left,
// Anchor positioning properties
anchorTarget: styles.anchorTarget, // ID or instance reference
anchorPoint: styles.anchorPoint || "center", // Anchor point on target
selfAnchor: styles.selfAnchor || "center", // Anchor point on self
anchorOffsetX: styles.anchorOffsetX || 0,
anchorOffsetY: styles.anchorOffsetY || 0,
};
}
/**
* Apply normal flow layout (static/relative positioning)
* @param {WorldInstance} instance - The instance to layout
* @param {Object} layoutProps - Layout properties
* @param {Array} children - Children to layout (optional, if already filtered)
*/
applyNormalFlowLayout(instance, layoutProps, children) {
// Use provided children or get them if not provided
const layoutChildren = children || this.getLayoutChildren(instance);
switch (layoutProps.display) {
case "column":
this.layoutColumn(instance, layoutProps, layoutChildren);
break;
case "column-reverse":
this.layoutColumnReverse(instance, layoutProps, layoutChildren);
break;
case "row":
this.layoutRow(instance, layoutProps, layoutChildren);
break;
case "row-reverse":
this.layoutRowReverse(instance, layoutProps, layoutChildren);
break;
case "grid":
this.layoutGrid(instance, layoutProps, layoutChildren);
break;
}
}
/**
* Apply fit-content sizing to a container based on its children
* @param {WorldInstance} instance - The container to apply fit-content to
* @param {Object} layoutProps - Layout properties
*/
applyFitContentSizing(instance, layoutProps) {
const children = this.getLayoutChildren(instance);
const containerBoxModel = this.getBoxModel(instance);
// Different sizing logic based on display type
switch (layoutProps.display) {
case "column":
case "column-reverse":
// Calculate total height and max width
let totalHeightVertical =
containerBoxModel.padding.top + containerBoxModel.padding.bottom;
let maxWidth = 0;
children.forEach((child, index) => {
totalHeightVertical += this.getOuterHeight(child);
if (index < children.length - 1) {
totalHeightVertical += layoutProps.gap;
}
maxWidth = Math.max(maxWidth, this.getOuterWidth(child));
});
// Apply new dimensions
this.setInstanceHeight(
instance,
totalHeightVertical +
containerBoxModel.border.top +
containerBoxModel.border.bottom
);
this.setInstanceWidth(
instance,
maxWidth +
containerBoxModel.padding.left +
containerBoxModel.padding.right +
containerBoxModel.border.left +
containerBoxModel.border.right
);
break;
case "row":
case "row-reverse":
// Calculate total width and max height
let totalWidthHorizontal =
containerBoxModel.padding.left + containerBoxModel.padding.right;
let maxHeight = 0;
children.forEach((child, index) => {
totalWidthHorizontal += this.getOuterWidth(child);
if (index < children.length - 1) {
totalWidthHorizontal += layoutProps.gap;
}
maxHeight = Math.max(maxHeight, this.getOuterHeight(child));
});
// Apply new dimensions
this.setInstanceWidth(
instance,
totalWidthHorizontal +
containerBoxModel.border.left +
containerBoxModel.border.right
);
this.setInstanceHeight(
instance,
maxHeight +
containerBoxModel.padding.top +
containerBoxModel.padding.bottom +
containerBoxModel.border.top +
containerBoxModel.border.bottom
);
break;
case "grid":
// Grid is more complex, we need to calculate row/column count
const columns = layoutProps.columns || 2;
const rows = Math.ceil(children.length / columns);
// Find max cell dimensions
let maxCellWidth = 0;
let maxCellHeight = 0;
children.forEach((child) => {
const childBoxModel = this.getBoxModel(child);
maxCellWidth = Math.max(
maxCellWidth,
this.getInstanceWidth(child) +
childBoxModel.margin.left +
childBoxModel.margin.right
);
maxCellHeight = Math.max(
maxCellHeight,
this.getInstanceHeight(child) +
childBoxModel.margin.top +
childBoxModel.margin.bottom
);
});
// Calculate total dimensions
const totalWidthGrid =
columns * maxCellWidth +
(columns - 1) * layoutProps.gap +
containerBoxModel.padding.left +
containerBoxModel.padding.right +
containerBoxModel.border.left +
containerBoxModel.border.right;
const totalHeightGrid =
rows * maxCellHeight +
(rows - 1) * layoutProps.gap +
containerBoxModel.padding.top +
containerBoxModel.padding.bottom +
containerBoxModel.border.top +
containerBoxModel.border.bottom;
// Apply new dimensions
this.setInstanceWidth(instance, totalWidthGrid);
this.setInstanceHeight(instance, totalHeightGrid);
break;
}
}
/**
* Apply out-of-flow layout (absolute/anchor positioning)
* @param {WorldInstance} instance - The instance to layout
*/
applyOutOfFlowLayout(instance) {
const layoutProps = this.getLayoutProperties(instance);
switch (layoutProps.position) {
case "absolute":
this.positionAbsolute(instance, layoutProps);
break;
case "anchor":
this.positionAnchor(instance, layoutProps);
break;
}
}
/**
* Position an element absolutely within its parent
* @param {WorldInstance} instance - The instance to position
* @param {Object} layoutProps - Layout properties
*/
positionAbsolute(instance, layoutProps) {
if (!instance.getParent()) return;
const parent = instance.getParent();
const parentBoxModel = this.getBoxModel(parent);
const instanceBoxModel = this.getBoxModel(instance);
// Get content area boundaries (inside padding/border)
const contentLeft =
this.getInstanceX(parent) +
parentBoxModel.padding.left +
parentBoxModel.border.left;
const contentTop =
this.getInstanceY(parent) +
parentBoxModel.padding.top +
parentBoxModel.border.top;
const contentRight =
this.getInstanceX(parent) +
this.getInstanceWidth(parent) -
parentBoxModel.padding.right -
parentBoxModel.border.right;
const contentBottom =
this.getInstanceY(parent) +
this.getInstanceHeight(parent) -
parentBoxModel.padding.bottom -
parentBoxModel.border.bottom;
// Calculate position based on properties
let x, y;
// Handle horizontal positioning
if (layoutProps.left !== undefined) {
x = contentLeft + layoutProps.left + instanceBoxModel.margin.left;
} else if (layoutProps.right !== undefined) {
x =
contentRight -
layoutProps.right -
this.getInstanceWidth(instance) -
instanceBoxModel.margin.right;
} else {
// Default to left: 0
x = contentLeft + instanceBoxModel.margin.left;
}
// Handle vertical positioning
if (layoutProps.top !== undefined) {
y = contentTop + layoutProps.top + instanceBoxModel.margin.top;
} else if (layoutProps.bottom !== undefined) {
y =
contentBottom -
layoutProps.bottom -
this.getInstanceHeight(instance) -
instanceBoxModel.margin.bottom;
} else {
// Default to top: 0
y = contentTop + instanceBoxModel.margin.top;
}
// Apply the position
this.setInstanceX(instance, x);
this.setInstanceY(instance, y);
}
getInstanceBBox(instance) {
return instance.getBoundingBox();
}
getInstanceBBoxCached(instance) {
if (this.cachedBboxes.has(instance)) {
return this.cachedBboxes.get(instance);
}
// Get the bounding box from the instance
const bbox = instance.getBoundingBox();
// Cache the bounding box for future use
this.cachedBboxes.set(instance, bbox);
return bbox;
}
invalidateInstanceBBox(instance) {
this.cachedBboxes.delete(instance);
}
getInstanceX(instance) {
return instance.getBoundingBox().left;
}
getInstanceY(instance) {
return instance.getBoundingBox().top;
}
setInstanceX(instance, x) {
let bbox = instance.getBoundingBox();
instance.x = x + instance.x - bbox.left;
// this.invalidateInstanceBBox(instance);
}
setInstanceY(instance, y) {
let bbox = instance.getBoundingBox();
instance.y = y + instance.y - bbox.top;
// this.invalidateInstanceBBox(instance);
}
getInstanceWidth(instance) {
return instance.getBoundingBox().width;
}
getInstanceHeight(instance) {
return instance.getBoundingBox().height;
}
setInstanceWidth(instance, width) {
if (instance.width === 0) {
instance.width = width;
// this.invalidateInstanceBBox(instance);
}
let bbox = instance.getBoundingBox();
instance.width = width * (instance.width / bbox.width);
// this.invalidateInstanceBBox(instance);
}
setInstanceHeight(instance, height) {
if (instance.height === 0) {
instance.height = height;
// this.invalidateInstanceBBox(instance);
}
let bbox = instance.getBoundingBox();
instance.height = height * (instance.height / bbox.height);
// this.invalidateInstanceBBox(instance);
}
/**
* Position an element using anchor positioning
* @param {WorldInstance} instance - The instance to position
* @param {Object} layoutProps - Layout properties
*/
positionAnchor(instance, layoutProps) {
let target = null;
// If no anchor target specified, default to parent
if (!layoutProps.anchorTarget) {
target = instance.getParent();
if (!target) return; // No parent to anchor to
} else {
// Find the target element by tag/name
if (typeof layoutProps.anchorTarget === "string") {
// Special case: "parent" refers to the parent element
if (layoutProps.anchorTarget === "parent") {
target = instance.getParent();
} else {
// Look through all objects to find one with matching tag
for (const objectType of Object.values(this.runtime.objects)) {
for (const inst of objectType.getAllInstances()) {
if (inst.hasTags(layoutProps.anchorTarget)) {
target = inst;
break;
}
}
if (target) break;
}
}
} else if (
layoutProps.anchorTarget instanceof this.runtime.objects.WorldInstance
) {
// Direct instance reference
target = layoutProps.anchorTarget;
}
}
if (!target) return;
// Ensure we have the current position
const originalX = this.getInstanceX(instance);
const originalY = this.getInstanceY(instance);
// Get anchor points
const targetPoint = this.getAnchorPoint(target, layoutProps.anchorPoint);
const selfPoint = this.getAnchorPoint(
instance,
layoutProps.selfAnchor,
true
);
// Calculate offset between anchor points
const offsetX =
targetPoint.x -
(originalX + selfPoint.offsetX) +
layoutProps.anchorOffsetX;
const offsetY =
targetPoint.y -
(originalY + selfPoint.offsetY) +
layoutProps.anchorOffsetY;
// Apply position
this.setInstanceX(instance, originalX + offsetX);