-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathlayout.js
More file actions
3800 lines (3404 loc) · 124 KB
/
layout.js
File metadata and controls
3800 lines (3404 loc) · 124 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
import { pt, Transform, Point, Rectangle, rect } from 'lively.graphics';
import { arr, promise, Closure, num, obj, fun } from 'lively.lang';
import { once, signal } from 'lively.bindings';
import { loadYoga } from 'yoga-layout/dist/src/load.js';
let Yoga, _yoga, yogaConfig, ALIGN, ALIGN_CSS, JUSTIFY, JUSTIFY_CSS;
if (!Yoga) {
_yoga = loadYoga().then((l) => {
Yoga = l;
yogaConfig = Yoga.Config.create();
yogaConfig.setPointScaleFactor(1);
yogaConfig.setErrata(Yoga.ERRATA_CLASSIC);
JUSTIFY = {
left: Yoga.JUSTIFY_FLEX_START,
center: Yoga.JUSTIFY_CENTER,
right: Yoga.JUSTIFY_FLEX_END
};
ALIGN = {
center: Yoga.ALIGN_CENTER,
left: Yoga.ALIGN_FLEX_START,
right: Yoga.ALIGN_FLEX_END
};
JUSTIFY_CSS = {
[Yoga.JUSTIFY_CENTER]: 'center',
[Yoga.JUSTIFY_FLEX_START]: 'flex-start',
[Yoga.JUSTIFY_FLEX_END]: 'flex-end'
};
ALIGN_CSS = {
[Yoga.ALIGN_CENTER]: 'center',
[Yoga.ALIGN_FLEX_START]: 'flex-start',
[Yoga.ALIGN_FLEX_END]: 'flex-end'
};
});
}
export function ensureYoga () {
return _yoga;
}
export function getYoga () { return Yoga; }
class Layout {
constructor (config = {}) {
const {
spacing, padding, border, container, manualUpdate,
ignore, onScheduleApply, layoutOrder,
reactToSubmorphAnimations
} = config;
this.config = config;
this.applyRequests = false;
this.border = { top: 0, left: 0, right: 0, bottom: 0, ...border };
this.ignore = ignore || [];
this.active = false;
this.container = container;
this.manualUpdate = manualUpdate;
this.reactToSubmorphAnimations = reactToSubmorphAnimations || false;
this.onScheduleApply = onScheduleApply || ((submorph, animation, change) => {}); // eslint-disable-line no-unused-vars
if (layoutOrder) {
this.layoutOrder = layoutOrder;
this.layoutOrderSource = JSON.stringify(String(layoutOrder));
}
this._spacing = spacing || 0;
this._padding = !padding ? Rectangle.inset(0) : typeof padding === 'number' ? Rectangle.inset(padding) : Rectangle.fromLiteral(padding);
}
get isLayout () { return true; }
hasEmbeddedContainer () {
if (this.container?.owner?.isText) return false;
return this.container.owner?.embeddedMorphMap?.has(this.container);
}
attach () {
if (this.renderViaCSS) {
this.layoutableSubmorphs.forEach(m => m.makeDirty());
return;
}
this.apply();
if (this.container.master) {
this.container.master.whenApplied().then(() => {
this.applyRequests = true;
this.forceLayout();
});
}
this.refreshBoundsCache();
}
getNodeFor (aMorph) {
const { renderer } = aMorph.env;
if (!renderer) return null;
return renderer.getNodeForMorph(aMorph);
}
measureSubmorph (layoutableSubmorph) {
if (layoutableSubmorph.ownerChain().find(m => !m.visible)) return;
const submorphNode = this.getNodeFor(layoutableSubmorph);
if (!layoutableSubmorph.isLayoutable) return;
this.onDomResize(submorphNode, layoutableSubmorph);
}
copy () { return new this.constructor(this); }
with (props) {
const c = this.copy();
Object.assign(c, props);
return c;
}
description () { return 'Describe the layout behavior here.'; }
name () { return 'Name presented to the user.'; }
isEnabled () { /* FIXME! */ return !this.active; }
disable () { this.active = true; }
enable (animation) {
this.active = false;
this.scheduleApply(null, animation);
}
get padding () { return this._padding; }
set padding (padding) {
if (typeof padding === 'number') {
padding = Rectangle.inset(padding);
}
this._padding = padding;
this.apply();
}
boundsChanged (container) {
return container.isClip() ? this.extentChanged(container) : !(this.lastBoundsExtent && container.bounds().extent().equals(this.lastBoundsExtent));
}
extentChanged (container) {
return !(this.lastExtent && container.extent.equals(this.lastExtent));
}
equals (otherLayout) {
return otherLayout?.isLayout && otherLayout.name() === this.name();
}
get layoutableSubmorphs () {
if (!this.layoutOrder) { this.layoutOrder = Closure.fromSource(JSON.parse(this.layoutOrderSource)).recreateFunc(); }
if (!this.container) return [];
let { submorphs } = this.container;
if (this.container.isWorld) submorphs = submorphs.filter(m => !m.hasFixedPosition);
return arr.sortBy(submorphs.filter(
m => m.isLayoutable && !this.ignore.includes(m.name)),
m => this.layoutOrder(m));
}
layoutOrder (aMorph) {
// helps orderdSubmorphs order my morphs
return this.container.submorphs.indexOf(aMorph);
}
get submorphBoundsChanged () {
const { layoutableSubmorphs, layoutableSubmorphBounds } = this;
if (!layoutableSubmorphBounds ||
(layoutableSubmorphs.length !== layoutableSubmorphBounds.length)) {
return true;
}
for (let i = 0; i < layoutableSubmorphs.length; i++) {
const m = layoutableSubmorphs[i];
const b = layoutableSubmorphBounds[i];
if (!b.equals(m.bounds())) {
return true;
}
}
return false;
}
refreshBoundsCache () {
this.lastExtent = this.container.extent;
this.lastBoundsExtent = this.container.bounds().extent();
this.layoutableSubmorphBounds = this.layoutableSubmorphs.map(m => m.bounds());
}
onContainerRender () {
this.forceLayout();
}
get noLayoutActionNeeded () {
const containerNotDisplayed = !this.container.visible || !!this.container.ownerChain().find(m => !m.visible);
return (containerNotDisplayed ||
!this.container.needsRerender() &&
!this.submorphsChanged && // submorphs have not changed
!this.submorphBoundsChanged); // submorph bounds have changed
}
get __dont_serialize__ () { return ['lastAnim', 'animationPromise']; }
forceLayout () {
if (this.applyRequests) {
this.applyRequests = false;
if (this.noLayoutActionNeeded) return;
this.container.withMetaDo({
isLayoutAction: true,
animation: this.lastAnim
}, () => {
this.refreshBoundsCache();
this.apply(this.lastAnim);
});
this.lastAnim = false;
}
}
computeLayout () {}
forceLayoutsOfMorph (m) {
m.layout?.forceLayout();
}
forceLayoutsInNextLevel () {
this.layoutableSubmorphs.forEach(m => this.forceLayoutsOfMorph(m));
}
scheduleApply (submorph, animation, change = {}) {
if (typeof this.onScheduleApply === 'function') { this.onScheduleApply(submorph, animation, change); }
if (this.active) return;
if (animation) this.lastAnim = animation;
this.applyRequests = true;
}
onSubmorphResized (submorph, change) {
this.scheduleApply(submorph, this.reactToSubmorphAnimations && change.meta.animation, change);
}
onSubmorphAdded (submorph, animation) {
this.submorphsChanged = true;
this.scheduleApply(submorph, animation);
}
onSubmorphRemoved (submorph, animation) {
this.submorphsChanged = true;
this.scheduleApply(submorph, animation);
}
onOwnerChanged (newOwner) {}
onChange ({ selector, args, prop, value, prevValue, meta }) {
const anim = this.reactToSubmorphAnimations && meta && meta.animation;
const submorph = args && args[0];
switch (selector) {
case 'removeMorph':
this.onSubmorphRemoved(submorph, anim);
break;
case 'addMorphAt':
this.onSubmorphAdded(submorph, anim);
break;
}
if (prop === 'borderWidth' && this.renderViaCSS) this.layoutableSubmorphs.forEach(m => m.makeDirty());
if (prop === 'extent' && value && prevValue &&
(prevValue.x !== value.x || prevValue.y !== value.y)) {
this.scheduleApply(submorph, anim, { prop: 'extent', meta });
}
}
getAffectedPolicy () {
let curr = this.container;
while (curr && !curr.master) curr = curr.owner;
if (curr?.master?.managesMorph(this.container)) {
return curr.master;
}
}
affectsLayout (submorph, { prop, value, prevValue, meta }) {
return ['position', 'scale', 'rotation', 'isLayoutable', 'extent', 'visible'].includes(prop) &&
!obj.equals(value, prevValue) && !meta.metaInteraction;
}
get isLayoutAction () {
return this.container?.env.changeManager.defaultMeta.isLayoutAction;
}
onConfigUpdate () {
this.scheduleApply();
if (!this._configChanged) {
this._configChanged = true;
if (!this.isLayoutAction) this.layoutableSubmorphs.forEach(m => m.makeDirty());
if (this.container) {
this.container.renderingState.hasStructuralChanges = true;
this.container.renderingState.hasCSSLayoutChange = true;
}
}
if (this._initializingPolicies) return;
if (!this.isLayoutAction) this.getAffectedPolicy()?.overrideProp(this.container, 'layout');
}
onSubmorphChange (submorph, change) {
if (!change.meta?.isLayoutAction) {
return this.scheduleApply(submorph, this.reactToSubmorphAnimation && change.meta.animation);
}
if (this.affectsLayout(submorph, change)) {
this.onSubmorphResized(submorph, change);
}
}
changePropertyAnimated (target, propName, value, animate) {
if (animate) {
const { duration, easing } = animate;
this.animationPromise = target.animate({ [propName]: value, duration, easing });
} else {
target[propName] = value;
}
}
attachAnimated (duration = 0, container, easing) {
if (this.active) return;
this.container = container;
this.active = true;
container.layout = this;
this.active = false;
this.lastAnim = { duration, easing };
}
apply (animated) { // eslint-disable-line no-unused-vars
if (this.active) return;
this.active = true;
this.submorphsChanged = false;
this.lastBoundsExtent = this.container && this.container.bounds().extent();
this.active = false;
}
estimateSubmorphExtents (containerSpec) {
}
estimateContainerExtent (containerSpec) {
}
resizesMorphVertically (aMorph) { // eslint-disable-line no-unused-vars
return false;
}
resizesMorphHorizontally (aMorph) { // eslint-disable-line no-unused-vars
return false;
}
measureAfterRender (layoutableSubmorph) {
if (!this.renderViaCSS) return;
if (layoutableSubmorph.isText) {
layoutableSubmorph.renderingState.needsFit = true;
}
layoutableSubmorph.renderingState.cssLayoutToMeasureWith = this;
}
}
/**
Tiling Layouts align morphs either horizontally or vertically,
much like vertical or horizontal Layouts. The key difference is that they
wrap the flow of the positioned morphs according to the size of the container.
Essentially Tiling Layouts are just Vertical or Horizontal layouts that have
wrapping enabled.
*/
export class TilingLayout extends Layout {
constructor (props = {}) {
super(props);
this._renderViaCSS = typeof props.renderViaCSS !== 'undefined' ? props.renderViaCSS : true;
this._axis = props.axis || 'row';
this._align = props.align || 'left';
this._axisAlign = props.axisAlign || 'left';
this._justifySubmorphs = props.justifySubmorphs || 'packed';
this._hugContentsVertically = props.hugContentsVertically || false;
this._hugContentsHorizontally = props.hugContentsHorizontally || false;
this._orderByIndex = props.orderByIndex || true;
this._wrapSubmorphs = false;
if (typeof props.wrapSubmorphs !== 'undefined') {
this._wrapSubmorphs = props.wrapSubmorphs;
}
this._resizePolicies = props.resizePolicies || new WeakMap();
}
equals (other) {
return super.equals(other) && this.__serialize__().__expr__ === (other && other.__serialize__().__expr__);
}
name () { return 'Tiling'; }
__serialize__ () {
// fixme: serialize padding as rect
const rectSerializer = (anObject, ignoreSignal) => {
if (anObject && anObject.isRectangle) { return anObject.toString(); } else return ignoreSignal;
};
return {
__expr__: `new TilingLayout(${obj.inspect(this.getSpec(), {
customPrinter: rectSerializer
})})`,
bindings: { 'lively.morphic': ['TilingLayout'], 'lively.graphics/geometry-2d.js': ['rect'] }
};
}
attach () {
this.initializeResizePolicies();
super.attach();
}
initializeResizePolicies (_initializingPoliciesAfterwards = false) {
this._initializingPolicies = true;
const resizePolicies = this._resizePolicies;
if (resizePolicies && !Array.isArray(resizePolicies)) {
this._initializingPolicies = _initializingPoliciesAfterwards;
return;
}
const { layoutableSubmorphs } = this;
this._resizePolicies = new WeakMap();
if (Array.isArray(resizePolicies)) {
resizePolicies.map(([morphName, policy]) => {
const m = this.container.submorphs.find(m => m.name === morphName);
if (m) this.setResizePolicyFor(m, policy);
arr.remove(layoutableSubmorphs, m);
});
delete this._policiesSynthesized;
} else {
this.layoutableSubmorphs.forEach(m => {
this.setResizePolicyFor(m, {
width: 'fixed', height: 'fixed'
});
});
}
this._initializingPolicies = _initializingPoliciesAfterwards;
}
scheduleApply (submorph, animation, change = {}) {
if (change.meta?.deferLayoutApplication) {
return;
}
if (!change.meta?.isLayoutAction || !this.container?._yogaNode?.getParent()) {
this._alreadyComputed = false;
}
if (change.prop === 'extent' &&
!change.meta?.isLayoutAction &&
this.renderViaCSS) {
this.computeLayoutIfNeeded();
}
super.scheduleApply(submorph, animation, change);
}
get layoutableSubmorphs () {
const layoutableSubmorphs = super.layoutableSubmorphs;
if (this.renderViaCSS) return layoutableSubmorphs;
else return layoutableSubmorphs.filter(m => m.visible);
}
get reactToSubmorphAnimations () {
return this._reactToSubmorphAnimations;
}
set reactToSubmorphAnimations (v) {
this._reactToSubmorphAnimations = v;
}
get resizePolicies () {
return this.layoutableSubmorphs.map(m => [m.name, this._resizePolicies.get(m) || { width: 'fixed', height: 'fixed' }]);
}
set padding (padding) {
this._padding = padding;
this.onConfigUpdate();
}
get padding () { return this._padding; }
/**
* Returns a copy of the tile layout based on the spec.
* @type {TileLayout}
*/
copy () {
return new this.constructor(this.getSpec());
}
sanitizeConfig (config) {
const spec = {};
for (let prop of obj.keys(config)) {
switch (prop) {
case 'resizePolicies':
spec.resizePolicies = [...config.resizePolicies];
break;
case 'spacing':
if (config.spacing !== 0) spec.spacing = config.spacing;
break;
case 'renderViaCSS':
if (config.renderViaCSS !== true) spec.renderViaCSS = config.renderViaCSS;
break;
case 'axis':
if (config.axis !== 'row') spec.axis = config.axis;
break;
case 'align':
if (config.align !== 'left') spec.align = config.align;
break;
case 'axisAlign':
if (config.axisAlign !== 'left') spec.axisAlign = config.axisAlign;
break;
case 'justifySubmorphs':
if (config.justifySubmorphs !== 'packed') spec.justifySubmorphs = config.justifySubmorphs;
break;
case 'hugContentsVertically':
if (config.hugContentsVertically !== false) spec.hugContentsVertically = true;
break;
case 'hugContentsHorizontally':
if (config.hugContentsHorizontally !== false) spec.hugContentsHorizontally = true;
break;
case 'orderByIndex':
if (config.orderByIndex !== false && config.renderViaCSS === false) spec.orderByIndex = true;
break;
case 'wrapSubmorphs':
if (config.wrapSubmorphs !== false) spec.wrapSubmorphs = true;
break;
case 'padding':
if (rect(0).equals(config.padding)) break;
if (obj.isNumber(config.padding)) { spec.padding = rect(config.padding, config.padding); break; }
if (!config.padding.isRectangle) { spec.padding = Rectangle.fromLiteral(config.padding); break; }
spec.padding = config.padding;
break;
case 'reactToSubmorphAnimations':
if (config.reactToSubmorphAnimations) spec.reactToSubmorphAnimations = true;
break;
}
}
return spec;
}
/**
* Returns the current values of the layout's parameters as key-values.
* Useful for safely copying layout objects.
* @todo Also return the resizePolicies in a declarative manner.
* @returns {TileLayoutSpec}
*/
getSpec () {
if (!this.container) return this.sanitizeConfig(this.config);
if (Array.isArray(this._resizePolicies)) {
this.initializeResizePolicies();
}
let {
axis, align, axisAlign, spacing, orderByIndex, resizePolicies,
reactToSubmorphAnimations, renderViaCSS, padding, wrapSubmorphs,
justifySubmorphs,
_hugContentsVertically: hugContentsVertically,
_hugContentsHorizontally: hugContentsHorizontally
} = this;
const spec = this.sanitizeConfig({
axis,
align,
axisAlign,
spacing,
orderByIndex: !renderViaCSS && orderByIndex,
reactToSubmorphAnimations,
renderViaCSS,
padding,
wrapSubmorphs,
justifySubmorphs,
hugContentsVertically,
hugContentsHorizontally
});
// only set the ones different to the default value
for (let [morphName, policy] of resizePolicies) {
if (policy.width !== 'fixed' || policy.height !== 'fixed') {
if (!spec.resizePolicies) spec.resizePolicies = [];
spec.resizePolicies.push([morphName, { ...policy }]);
}
}
if (!this._policiesSynthesized && this.config.resizePolicies) {
spec.resizePolicies = [...this.config.resizePolicies];
if (spec.resizePolicies.length === 0) delete spec.resizePolicies;
}
return spec;
}
get possibleAxisValues () { return ['row', 'column']; }
get possibleAlignValues () { return ['left', 'center', 'right']; } // better for morphs: ['start', 'center', 'end'] ?
/**
* Defines how the positioned submorphs are to be ordered.
* If set to false, the layoutable submorphs are ordered by their relative offset to the container.
* If set to true, the layoutable submorphs are ordered by the index they are found at from their owner.
* Warning: This property is not supported when the layout is rendered via CSS and defaults to true in this case.
* @type {Boolean}
*/
get orderByIndex () { return this._orderByIndex || this.renderViaCSS; }
set orderByIndex (active) { this._orderByIndex = active; this.onConfigUpdate(); }
/**
* Defines the flow direction of the positioned morphs.
* If set to "row", the morphs flow horizontally.
* If set to "column" the morphs flow vertically.
* @enum {string}
*/
get axis () { return this._axis; }
set axis (a) { this._axis = a; this.onConfigUpdate(); }
/**
* Defines how the morphs are positioned along their axis.
* Possible values are floating to the "left", floating to the "right", or "centered".
* @enum {string}
*/
get align () { return this._align; }
set align (a) { this._align = a; this.onConfigUpdate(); }
/**
* Defines how the axis themselves are distributed within the container.
* By default the axis are floating to the "left". Other options: "right" or "centered".
* @enum {string}
*/
get axisAlign () { return this._axisAlign; }
set axisAlign (a) {
this._axisAlign = a; this.onConfigUpdate();
}
/**
* Defines the space in pixels between the positioned submorphs.
* @type {number}
*/
get spacing () { return this._spacing; }
set spacing (offset) {
this._spacing = offset;
this.onConfigUpdate();
}
/**
* Defines wether or not the morphs are supposed to be wrapped
* and lined up on multiple axis.
* @type {Boolean}
*/
get wrapSubmorphs () { return this._wrapSubmorphs; }
set wrapSubmorphs (wrappingEnabled) {
this._wrapSubmorphs = wrappingEnabled;
this.onConfigUpdate();
}
/**
* If set to true, the container auto adjusts its height to fit the content.
* Warning: This property is inactive when wrapping is enabled AND the axis are columns. It also is inactive when none of the layoutable submorphs are set for their height to be fixed. The reason is that then there is no way for the layout to determine what height to hug to.
* @type {Boolean}
*/
get hugContentsVertically () {
if (this.wrapSubmorphs && this.axis === 'column') return false;
for (let m of this.layoutableSubmorphs) {
if (!m.visible) continue;
const h = this._resizePolicies.get(m)?.height;
if (!h) continue;
if (h === 'fill') return false;
}
return this._hugContentsVertically;
}
set hugContentsVertically (active) {
this._hugContentsVertically = active;
this.onConfigUpdate();
}
get stretchedVertically () {
const { container } = this;
if (
container.owner?.layout?.name() === 'Tiling' &&
container.owner.layout.getResizeHeightPolicyFor(container) === 'fill' &&
container.isLayoutable) return true;
return false;
}
/**
* If set to true, the container auto adjusts its width to fit the content.
* Warning: This property is inactive when wrapping is enabled AND the axis are rows. It also is inactive when none of the layoutable submorphs are set for their width to be fixed. The reason is that then there is no way for the layout to determine what width to hug to.
* @type {Boolean}
*/
get hugContentsHorizontally () {
if (this.wrapSubmorphs && this.axis === 'row') return false;
for (let m of this.layoutableSubmorphs) {
if (!m.visible) continue;
const w = this._resizePolicies.get(m)?.width;
if (!w) continue;
if (w === 'fill') return false;
}
return this._hugContentsHorizontally;
}
set hugContentsHorizontally (active) {
this._hugContentsHorizontally = active;
this.onConfigUpdate();
}
get stretchedHorizontally () {
const { container } = this;
if (container.owner?.layout?.name() === 'Tiling' &&
container.owner.layout.getResizeWidthPolicyFor(container) === 'fill' &&
container.isLayoutable) return true;
return false;
}
/**
* Defines the justificaton of submorphs:
* "packed": distributes the morphs along a chain as close as possible.
* "spaced": makes the morphs cover the entire possible axis they fit into.
* @enum {string}
*/
get justifySubmorphs () {
return this._justifySubmorphs;
}
set justifySubmorphs (val) {
this._justifySubmorphs = val;
this.onConfigUpdate();
}
/**
* Each submorph can define its own resizing policy, that is how its width and height
* should respond with respect to the container. Fixed width/height will make the respective
* submorph maintain its height/width. If set to fill, the submorph will fill the
* container vertically/horizontally.
*
* Warning: When wrapping of submorphs is enabled, the policies for the morphs are disabled.
* This means that all morphs can only carry a fixed width/height since a fill behavior in any
* dimension would compromise the wrapping of morphs.
*/
getResizeHeightPolicyFor (aLayoutableSubmorph) {
const policy = this._resizePolicies.get(aLayoutableSubmorph) || { width: 'fixed', height: 'fixed' };
return this.wrapSubmorphs ? 'fixed' : policy.height;
}
getResizeWidthPolicyFor (aLayoutableSubmorph) {
const policy = this._resizePolicies.get(aLayoutableSubmorph) || { width: 'fixed', height: 'fixed' };
return this.wrapSubmorphs ? 'fixed' : policy.width;
}
setResizePolicyFor (aLayoutableSubmorph, policy) {
// policy : width = fixed/fill, height = fixed/fill
if (Array.isArray(this._resizePolicies)) {
let entry = this._resizePolicies.find(([name]) => aLayoutableSubmorph.name === name);
if (entry) { entry[1] = policy; } else this._resizePolicies.push([aLayoutableSubmorph.name, policy]);
} else {
this._policiesSynthesized = true;
this._resizePolicies.set(aLayoutableSubmorph, policy);
this.onConfigUpdate();
if (!this._initializingPolicies) this.resetYoga();
}
}
resizesMorphHorizontally (aMorph) {
return this.getResizeWidthPolicyFor(aMorph) === 'fill';
}
resizesMorphVertically (aMorph) {
return this.getResizeHeightPolicyFor(aMorph) === 'fill';
}
/**
* Defines wether or not this specific layout object should be rendered via CSS
* (therefore dispatching any layout ops to the browser stack) or manually computing
* the submorph positions through JavaScript.
* CSS renders generally have a much better performance but lack precision with regards
* transitioning smoothly between different configurations (layout animations).
* When you animate your layout operations it's best to set this property to false.
* @type {Boolean}
*/
get renderViaCSS () {
return this._renderViaCSS;
}
set renderViaCSS (active) {
this._renderViaCSS = active;
this.onConfigUpdate();
}
/**
* Invoked once a new morph is added to the container.
* @override
*/
onSubmorphAdded (submorph) {
if (!this._resizePolicies.get(submorph)) {
submorph.withMetaDo({ isLayoutAction: true }, () => {
this.setResizePolicyFor(submorph, {
width: 'fixed', height: 'fixed'
});
});
}
}
onSubmorphRemoved (submorph) {
this._resizePolicies.delete(submorph);
// Ensure correct propagation of layout propert and adaption of resizePolicies.
if (this.config.resizePolicies) { arr.remove(this.config.resizePolicies, this.config.resizePolicies.find(entry => entry[0] === submorph.name)); }
this.container.layout = this.copy();
this.container.renderingState.cssLayoutToMeasureWith = this.container.layout;
}
handleRenamingOf (oldName, newName) {
if (this.config.resizePolicies) {
this.config.resizePolicies = this.config.resizePolicies.map(([target, policy]) => {
if (target === oldName) return [newName, policy];
else return [target, policy];
});
}
}
/**************
* CSS LAYOUT *
**************/
/**
* In reaction to changes in the DOM that have happend due to a
* render pass, we update the morphic model to align with the
* values in the DOM. Since we delegate the placement of morphs
* to the browser, we need to confirm the definite bounds of
* the layoutable submorphs from there.
*/
onDomResize (node, morph) {} // eslint-disable-line no-unused-vars
measureSubmorph () {} // do nothing
onContainerResized (morph) {} // eslint-disable-line no-unused-vars
onOwnerChanged (newOwner) {
if (newOwner) return;
// Resetting Yoga nodes too frequently leads to weird behavior.
// This is a heuristic to delay the reset a bit.
// Additionally, this is basically a check to differentiate between removing a morph and abandoning it,
// so it also has positive performance implications.
setTimeout(() => !this.container?.world() && this.resetYoga());
}
ensureLayoutComputed (curr) {
while (curr.owner?.layout?.name() === 'Tiling' && curr.isLayoutable) curr = curr.owner;
if (curr.isWorld) {
const { width, height } = curr;
curr.layout.computeLayout().calculateLayout(width, height);
curr.layout.computeLayoutWithMargin().calculateLayout(width, height);
} else {
curr.layout.computeLayout().calculateLayout();
curr.layout.computeLayoutWithMargin().calculateLayout();
}
}
ensureYogaNodeFor (aMorph) {
if (aMorph._yogaNode) return aMorph._yogaNode;
aMorph._yogaNode = Yoga.Node.create(yogaConfig);
if (aMorph.isText) {
aMorph._yogaNode.setMeasureFunc((width, widthMode, height, heightMode) => {
if (aMorph.fixedWidth && widthMode !== 0) aMorph.withMetaDo({ doNotOverride: true }, () => aMorph.width = width);
if (aMorph.fixedHeight && heightMode !== 0) aMorph.withMetaDo({ doNotOverride: true }, () => aMorph.height = height);
if (!aMorph.visible) return { width: aMorph.width, height: aMorph.height };
if (!aMorph.fixedWidth || !aMorph.fixedHeight) aMorph.withMetaDo({ doNotFit: false, skipRerender: true }, () => aMorph.fitIfNeeded());
if (!aMorph.fixedWidth) width = aMorph.width;
if (!aMorph.fixedHeight) height = aMorph.height;
return { width, height };
});
}
return aMorph._yogaNode;
}
resetYogaNodeFor (aMorph) {
if (!aMorph._yogaNode) return;
// clear and free the yoga object
aMorph._yogaNode.free();
delete aMorph._yogaNode;
// ensure that the morph gets rendered again, so that yoga is getting re-initialize
aMorph.makeDirty();
delete aMorph._lastComputed;
}
resetYoga () {
if (!this.container || !this.container._yogaNode) return;
this.resetYogaNodeFor(this.container);
delete this.layoutableSubmorphBounds;
this.container.submorphs.forEach(m => {
if (m.layout?.name() !== 'Tiling') this.resetYogaNodeFor(m);
});
this.container
.withAllSubmorphsSelect(m => m.layout?.name() === 'Tiling')
.forEach(m => {
m.layout.resetYoga();
});
}
/**
* Attempt an immediate measure of the morph's rendered node
* to retrieve bounds from the DOM. If not possible, defer to
* the next render pass.
*/
tryToMeasureNodeNow (aSubmorph) {
this.updateSubmorphBounds(aSubmorph);
}
updateSubmorphBounds (morph) {
const node = this.ensureYogaNodeFor(morph);
const isPreliminary = !node._computedMargin;
const computed = node.getComputedLayout();
const { top: newPosY, left: newPosX, width: newWidth, height: newHeight } = computed;
const needsUpdate = !(num.roundTo(morph.height, .1) === num.roundTo(newHeight, .1) &&
num.roundTo(morph.width, .1) === num.roundTo(newWidth, .1) &&
morph.position.y === newPosY &&
morph.position.x === newPosX);
const computedStringified = JSON.stringify(computed);
if (morph._lastComputed === computedStringified && !needsUpdate) {
return;
}
const heightPolicy = this.getResizeHeightPolicyFor(morph);
const widthPolicy = this.getResizeWidthPolicyFor(morph);
if (newPosX !== morph.position.x || newPosY !== morph.position.y) {
morph.withMetaDo({ isLayoutAction: true, skipRender: true }, () => morph.position = pt(newPosX, newPosY));
}
if (!isPreliminary && widthPolicy === 'fill' && String(newWidth) !== 'NaN' && newWidth !== morph.width) {
morph.withMetaDo({ isLayoutAction: true, skipRender: false, metaInteraction: true }, () => morph.width = newWidth);
if (morph.isText && !morph.fixedHeight) {
if (!morph.canBeMeasuredViaCanvas) {
console.warn(`The text morph ${morph.id} is set to hug its content vertically but can not measure via canvas. This causes expensive rountrips for the layout on ${this.container.id}.`);
}
}
if (morph.isText && !morph.fixedWidth) {
console.warn(`The text morph ${morph.id} is set to hug its contents yet configure to fill the container horizontally!`);
}
}
if (!isPreliminary && heightPolicy === 'fill' && String(newHeight) !== 'NaN' && newHeight !== morph.height) {
morph.withMetaDo({ isLayoutAction: true, skipRender: false }, () => morph.height = newHeight);
}
if (morph.layout?.name() !== 'Tiling') morph._lastComputed = computedStringified;
if (morph.layout?.name() === 'Constraint') morph.layout.refreshBoundsCache();
}
updateContainerBounds () {
const { container, hugContentsVertically, hugContentsHorizontally } = this;
const node = container._yogaNode;
const computed = node.getComputedLayout();
const computedStringified = JSON.stringify(computed);
this.container._lastComputed = computedStringified;
const isPreliminary = node.getParent() && !node._computedMargin;
let width = isPreliminary ? container.width : computed.width;
let height = isPreliminary ? container.height : computed.height;
if (this.container.submorphs.length > 0) {
if (hugContentsVertically && container.height !== height) {
container.withMetaDo({ isLayoutAction: true, skipRender: true, doNotOverride: true }, () => container.height = height);
}
if (hugContentsHorizontally && container.width !== width) {
container.withMetaDo({ isLayoutAction: true, skipRender: true, doNotOverride: true }, () => container.width = width);
}
}
}
addSubmorphCSS (morph, style) {
let node = morph._yogaNode;
if (!node) return; // no yoga no layout
const nestedLayout = morph.layout;
style['z-index'] = this.container.submorphs.indexOf(morph);
style['min-height'] = '0px';
style['min-width'] = '0px';
if (!node?._computedMargin) {
node._computedMargin = this.defaultMargin();
}
if (!morph.isLayoutable) return;
let margin = node._computedMargin;
const { axis, layoutableSubmorphs } = this;
const { scrollbarVisible } = this.container;
const isVertical = axis === 'column';
if (this.getResizeWidthPolicyFor(morph) === 'fill') {
if (isVertical) {
style.width = '100%';
} else {
let paddingOffset = 0;
if (nestedLayout?.padding) {
paddingOffset = nestedLayout.padding.left() + nestedLayout.padding.right();
}
style.width = `calc(100% + ${margin.offsetH - morph.borderWidthLeft - morph.borderWidthRight - 2 * paddingOffset}px)`;
style['flex-grow'] = 1;
style['flex-shrink'] = 1;
}
}
if (this.getResizeHeightPolicyFor(morph) === 'fill') {
if (isVertical) {
let paddingOffset = 0;
if (nestedLayout?.padding) {
paddingOffset = nestedLayout.padding.top() + nestedLayout.padding.bottom();
}
style.height = `calc(100% + ${margin.offsetV - morph.borderWidthTop - morph.borderWidthBottom - 2 * paddingOffset}px)`;
style['flex-grow'] = 1; // let flex handle that
style['flex-shrink'] = 1;
} else {
style.height = '100%';
}
}
style.position = 'relative';
if (morph.owner && morph.owner.isText && morph.owner.embeddedMorphMap.get(morph)) {
style.position = 'sticky';
}
style.top = 'unset';
style.left = 'unset';