-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathpolicy.js
More file actions
1839 lines (1656 loc) · 73 KB
/
policy.js
File metadata and controls
1839 lines (1656 loc) · 73 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 { arr, fun, grid, string, tree, promise, obj } from 'lively.lang';
import { pt } from 'lively.graphics';
import { morph, getDefaultValuesFor, sanitizeFont, getStylePropertiesFor, getDefaultValueFor } from '../helpers.js';
import { withSuperclasses } from 'lively.classes/util.js';
import { ExpressionSerializer, serializeSpec, mergeBindings } from 'lively.serializer2';
import { Text, Label, Morph } from 'lively.morphic';
import { Icons } from '../text/icons.js';
const skippedValue = Symbol.for('lively.skip-property');
const PROPS_TO_RESET = ['dropShadow', 'fill', 'opacity', 'borderWidth', 'fontColor'];
const expressionSerializer = new ExpressionSerializer();
export function sanitizeSpec (spec) {
for (let prop in spec) {
if (spec[prop]?.isDefaultValue) spec[prop] = spec[prop].value;
}
return spec;
}
export function standardValueTransform (key, val, aMorph, protoVal) {
if (val && val.isPoint) return val.roundTo(0.1);
if (key === 'label' || key === 'textAndAttributes') {
let hit;
if (Array.isArray(val) && (hit = Object.entries(Icons).find(([iconName, iconValue]) => iconValue.code === val[0]))) {
return {
__serialize__ () {
return {
__expr__: `Icon.textAttribute("${hit[0]}")`,
bindings: {
'lively.morphic/text/icons.js': ['Icon']
}
};
}
};
}
}
return val;
}
/**
* Function that will wrap a morph definition and declares
* that this morph is added to the submorph array it is placed in.
* This is meant to be used inside overriden props of `part(C, {...})` or `component(C, {...})`
* calls. It will not make sense on `morph({...})` or `component({...})` calls.
* If before is specified this will ensure that the morph is added before the morph
* named as before.
* @param { object } props - A nested properties object that specs out the submorph hierarchy to be added. (This can also be a `part()` call).
* @param { string } [before] - An optional parameter that denotes the name of the morph this new one should be placed in front of.
*/
export function add (props, before = null) {
props.__wasAddedToDerived__ = true;
return {
COMMAND: 'add',
props,
before
};
}
/**
* Function that will wrap a morph's name and declare
* that this morph is removed from the submorph array it is located in.
* This is meant to be used inside overriden props of `part(C, {...})` or `component(C, {...})`
* calls. It will not make sense on `morph({...})` or `component({...})` calls.
* @param { string } removedSiblingName - The name of the submorph that is to be removed from the hierarchy.
*/
export function without (removedSiblingName) {
return {
COMMAND: 'remove',
target: removedSiblingName
};
}
export function replace (replacedSiblingName, props) {
return {
COMMAND: 'replace',
target: replacedSiblingName,
props
};
}
function handleTextProps (props) {
if (arr.intersect(
['text', 'label', Text, Label], withSuperclasses(props.type)).length === 0) { return props; }
if (props.textAndAttributes) {
delete props.textString;
delete props.value;
}
if (props.textString) {
props.textAndAttributes = [props.textString, null];
delete props.textString;
}
if (props.value && obj.isArray(props.value)) {
props.textAndAttributes = props.value;
delete props.value;
}
if (props.value && obj.isString(props.value)) {
props.textAndAttributes = [props.value, null];
delete props.value;
}
if (props.fontFamily) {
const ff = props.fontFamily.isDefaultValue ? props.fontFamily.value : props.fontFamily;
if (ff !== skippedValue) { props.fontFamily = sanitizeFont(ff); }
}
return props;
}
function ensureOrder (originalSubmorphs, adjustedSubmorphs = []) {
return arr.sortBy(adjustedSubmorphs, (spec) => originalSubmorphs?.indexOf(originalSubmorphs?.find(elem => elem.name === spec.name)));
}
/**
* Merges two different specs.
*/
function mergeInHierarchy (
root,
props,
iterator,
executeCommands = false,
removeFn = (parent, aMorph) => aMorph.remove(),
addFn = (parent, aMorph, before) => parent.addMorph(aMorph, before).__wasAddedToDerived__ = true) {
const orderedSubmorphs = ensureOrder(root.submorphs, props.submorphs);
if (props.submorphs) {
iterator(root, { ...props, submorphs: orderedSubmorphs });
} else {
iterator(root, props);
}
// at this point, we need to ensure that the order of the props.submorphs matches
// the original submorph order
let [commands, nextPropsToApply] = arr.partition(orderedSubmorphs, (prop) => !!prop.COMMAND);
props = nextPropsToApply.shift();
for (let submorph of root.submorphs || []) {
if (!props) break;
if (submorph.name === props.name) {
mergeInHierarchy(submorph, props, iterator, executeCommands, removeFn, addFn);
props = nextPropsToApply.shift();
}
}
// finally we apply the commands
if (!executeCommands) return;
for (let cmd of commands) {
if (cmd.COMMAND === 'remove' && root.submorphs) {
const morphToRemove = root.submorphs.find(m => m.name === cmd.target);
if (morphToRemove) removeFn(root, morphToRemove);
}
if (cmd.COMMAND === 'replace' && root.submorphs) {
const morphToReplace = root.submorphs.find(m => m.name === cmd.target);
let specOrPolicyToAdd = cmd.props;
if (specOrPolicyToAdd.isPolicy) specOrPolicyToAdd = specOrPolicyToAdd.spec;
if (morphToReplace) {
if (!specOrPolicyToAdd.hasOwnProperty('position')) { specOrPolicyToAdd.position = morphToReplace.spec?.position || morphToReplace.position; }
if (!specOrPolicyToAdd.hasOwnProperty('rotation')) { specOrPolicyToAdd.rotation = morphToReplace.spec?.rotation || morphToReplace.rotation; }
if (typeof specOrPolicyToAdd.position === 'undefined') delete specOrPolicyToAdd.position;
if (typeof specOrPolicyToAdd.rotation === 'undefined') delete specOrPolicyToAdd.rotation;
specOrPolicyToAdd.name = morphToReplace.name;
addFn(root, cmd.props, morphToReplace);
removeFn(root, morphToReplace);
}
}
if (cmd.COMMAND === 'add') {
if (!root.submorphs) root.submorphs = [];
const beforeMorph = cmd.before && root.submorphs.find(m => m.name === cmd.before);
addFn(root, cmd.props, beforeMorph);
}
}
return root;
}
/**
* Returns the event state a given morph is currently in.
* This is usually with respect system specific settings/input, such as: Hover/Click state or light/dark mode.
* However we can also provide custom breakpoints of the viewport, which coincide with a particular width or height
* of the morph to check for. With this we are able to implement responsive design with master components.
* @param { Morph } targetMorph - The morph to check the state for.
* @param { object[] } customBreakpoints - A list of custom breakpoints in response to the width/height of the `targetMorph`.
* @returns { object } The event state corresponding to the morph.
*/
function getEventState (targetMorph, breakpointStore, localComponentStates) {
const stateMaster = localComponentStates?.[targetMorph.master?._componentState];
const { world, eventDispatcher } = targetMorph.env;
const mode = world && world.colorScheme; // "dark" | "light"
const isHovered = eventDispatcher && eventDispatcher.isMorphHovered(targetMorph); // bool
const isClicked = eventDispatcher && isHovered && eventDispatcher.isMorphClicked(targetMorph); // bool
const breakpointComponent = breakpointStore?.getMatchingBreakpointMaster(targetMorph);
return {
breakpointMaster: !breakpointComponent?.isPolicy ? breakpointComponent?.stylePolicy : breakpointComponent,
mode,
isHovered,
isClicked,
stateMaster
};
}
export function withAllViewModelsDo (inst, cb) {
const toAttach = [];
inst.withAllSubmorphsDo(m => {
if (m.viewModel) toAttach.unshift(m);
});
toAttach.forEach(cb);
}
export class BreakpointStore {
constructor () {
this._horizontalBreakpoints = [0];
this._verticalBreakpoints = [0];
this._breakpointMasters = [[null]];
}
copy () {
return BreakpointStore.from(this.getConfig());
}
static from (breakpointSpec) {
const store = new this();
const vbps = store._verticalBreakpoints;
const hbps = store._horizontalBreakpoints;
breakpointSpec.forEach(([bp, componentDescriptor]) => {
store.addHorizontalBreakpoint(bp.x);
store.addVerticalBreakpoint(bp.y);
});
breakpointSpec.forEach(([bp, componentDescriptor]) => {
store.setBreakpointMaster(vbps.indexOf(bp.y), hbps.indexOf(bp.x), componentDescriptor);
});
return store;
}
getConfig () {
return arr.compact(grid.map(this._breakpointMasters, (componentDescriptor, row, col) => {
if (!componentDescriptor) return null;
const y = this._verticalBreakpoints[row];
const x = this._horizontalBreakpoints[col];
return [pt(x, y), componentDescriptor];
}).flat());
}
__serialize__ () {
if (!arr.compact(this._breakpointMasters.flat()).every(descr => descr[Symbol.for('lively-module-meta')])) return;
const bindings = { 'lively.graphics': ['pt'] };
const masterStrings = this.getConfig().map(([pos, componentDescriptor]) => {
const expr = componentDescriptor.__serialize__();
mergeBindings(expr.bindings, bindings);
return `[${pos.toString()}, ${expr.__expr__}]`;
});
if (masterStrings.length === 0) return;
const __expr__ = `[\n${masterStrings.join(',\n')}\n]`;
return { __expr__, bindings };
}
setBreakpointMaster (vi, hi, componentDescriptor) {
grid.set(this._breakpointMasters, vi, hi, componentDescriptor);
}
setVerticalBreakpointMaster (idx, componentDescriptor) {
const n = grid.getRow(this._breakpointMasters, 0)?.length || 1;
grid.setRow(this._breakpointMasters, idx, arr.genN(n, () => componentDescriptor));
}
setHorizontalBreakpointMaster (idx, componentDescriptor) {
const n = grid.getCol(this._breakpointMasters, 0)?.length || 1;
grid.setCol(this._breakpointMasters, idx, arr.genN(n, () => componentDescriptor));
}
addVerticalBreakpoint (bp, componentDescriptor = null) {
if (this._verticalBreakpoints.includes(bp)) return;
const n = grid.getRow(this._breakpointMasters, 0)?.length || 1;
this._verticalBreakpoints.push(bp);
grid.addRow(this._breakpointMasters, arr.genN(n, () => componentDescriptor));
}
addHorizontalBreakpoint (bp, componentDescriptor = null) {
if (this._horizontalBreakpoints.includes(bp)) return;
const n = grid.getCol(this._breakpointMasters, 0)?.length || 1;
this._horizontalBreakpoints.push(bp);
grid.addCol(this._breakpointMasters, arr.genN(n, () => componentDescriptor));
}
removeVerticalBreakpoint (idx) {
arr.removeAt(this._verticalBreakpoints, idx);
grid.removeRow(this._breakpointMasters, idx);
}
removeHorizontalBreakpoint (idx) {
arr.removeAt(this._horizontalBreakpoints, idx);
grid.removeCol(this._breakpointMasters, idx);
}
getMatchingBreakpointMaster (targetMorph) {
const [vbp, hbp] = this.getMatchingBreakpoint(targetMorph);
return grid.get(this._breakpointMasters, vbp, hbp);
}
getMatchingBreakpoint (targetMorph) {
const hbp = this._horizontalBreakpoints.length - 1 - this._horizontalBreakpoints.toReversed().findIndex((x) => {
return x <= targetMorph.width;
});
const vbp = this._verticalBreakpoints.length - 1 - this._verticalBreakpoints.toReversed().findIndex((y) => {
return y <= targetMorph.height;
});
return [vbp, hbp];
}
getLimitExtent ([v, h]) {
let hOffset = this._horizontalBreakpoints[h];
let vOffset = this._verticalBreakpoints[v];
if (hOffset === 0) hOffset = this._horizontalBreakpoints[h + 1] - 1;
if (vOffset === 0) vOffset = this._verticalBreakpoints[v + 1] - 1;
return pt(hOffset, vOffset);
}
}
/**
* We use StylePolicies to implement 2 kinds of abstractions in the system:
* 1. Component Definitions:
* These are top level definitions of reusable UI Elements that we can apply to morphs or use to create morphs from.
* We can also define new components that are derived from other components.
* 2. Inline Style Policies:
* In cases where we want to reuse a particular component definition, but do not want to create
* a dedicated top level definition (since there is not scenario for reuse) we can insert *Inline Policies*
* into a component definition.
*/
export class StylePolicy {
/**
* Creates a new StylePolicy.
* @param { object } spec - The structural composition of the component, similar to morphic build specs.
* @param { StylePolicy | ComponentDescriptor } parent - The policy that we are derived from.
* @param { boolean } [inheritStructure = true] - Wether or not we are supposed to inherit the structure of the parent policy.
*/
constructor (spec, parent) {
if (parent) this.parent = parent;
this._dependants = new Set();
this._verticalBreakpoints = [];
this._horizontalBreakpoints = [];
this._originalSpec = spec;
this.spec = this.ensureStylePoliciesInSpec(spec);
if (this.spec.isPolicy) return this.spec; // eslint-disable-line no-constructor-return
}
/**
* StylePolicies usually have a parent policy they are derived from
* except if they are are a master component completely created from scratch.
* @returns { StylePolicy | null } The policy that we are derived from.
*/
get parent () {
return this._parent?.isComponentDescriptor ? this._parent.stylePolicy : this._parent;
}
/**
* @type { [string] } The morph type of the root element of this policy.
*/
get type () {
return this.spec.type;
}
/**
* @type { [string] } The name of the root element of this policy.
*/
get name () {
return this.spec?.name;
}
set name (v) {
this.spec.name = v;
}
/**
* The parent of the policy. If not overridden the `auto` master defaults to this policy.
* We also inherit all the structure (submorphs) from this policy.
* @type { object | StylePolicy | ComponentDescriptor }
*/
set parent (policyOrDescriptor) {
if (policyOrDescriptor.isPolicy || policyOrDescriptor.isComponentDescriptor) {
this._parent = policyOrDescriptor;
} else {
const { auto, breakpoints } = policyOrDescriptor;
this._parent = auto?.isComponentDescriptor ? auto.stylePolicy : auto;
if (!this._parent && breakpoints) {
this._parent = breakpoints[0][1].stylePolicy;
}
this.applyConfiguration(policyOrDescriptor);
}
}
reset () {
delete this._autoMaster;
delete this._hoverMaster;
delete this._clickMaster;
delete this._localComponentStates;
delete this._breakpointStore;
}
applyConfiguration (config) {
const {
click, hover, light, dark, breakpoints, states,
auto, statePartitionedInline = false
} = config;
this._statePartitionedInline = statePartitionedInline;
if (auto) this._autoMaster = auto.isComponentDescriptor ? auto.stylePolicy : auto;
// mouse event component dispatch
if (click) this._clickMaster = click.isComponentDescriptor ? click.stylePolicy : click;
if (hover) this._hoverMaster = hover.isComponentDescriptor ? hover.stylePolicy : hover;
// light/dark component dispatch
if (light) this._lightModeMaster = light.isComponentDescriptor ? light.stylePolicy : light;
if (dark) this._darkModeMaster = dark.isComponentDescriptor ? dark.stylePolicy : dark;
// breakpoint component dispatch
// sort them
if (breakpoints) {
this.setBreakpoints(breakpoints);
}
if (states) {
this._localComponentStates = {};
for (let state in states) {
this._localComponentStates[state] = states[state]?.isComponentDescriptor ? states[state].stylePolicy : states[state];
}
}
return this;
}
get isPolicy () { return true; }
get isEventPolicy () { return this._clickMaster || this._hoverMaster; }
get isLightDarkModePolicy () { return this._lightModeMaster || this._darkModeMaster; }
get isBreakpointPolicy () {
return !!this.getBreakpointStore();
}
getBreakpointStore () {
if (this._breakpointStore) return this._breakpointStore;
return this.parent?.getBreakpointStore();
}
/**
* Allows to set the breakpoints by means of pt(x,y) -> componentDescriptor
* which allows for convenient definition of breakpoints
* @param {type} breakpoints - Nested array of [Point, ComponentDescriptor]
*/
setBreakpoints (breakpointSpec) {
this._breakpointStore = BreakpointStore.from(breakpointSpec);
}
clearBreakpoints () { delete this._breakpointStore; }
getMatchingBreakpointMaster (targetMorph) {
return this.getBreakpointStore()?.getMatchingBreakpointMaster(targetMorph);
}
performSafeBreakpointTransition (targetMorph, previousTarget) {
const bpStore = this.getBreakpointStore();
if (!bpStore) return;
fun.guardNamed('apply-' + targetMorph.id, () => {
const currIndex = bpStore.getMatchingBreakpoint(targetMorph);
if (targetMorph._lastIndex && !obj.equals(targetMorph._lastIndex, currIndex)) {
const limitExtent = bpStore.getLimitExtent(currIndex);
const actualExtent = targetMorph.extent;
targetMorph.withMetaDo({
metaInteraction: true, // do not record
reconcileChanges: false,
doNotFit: true,
doNotOverride: true
}, () => {
const origLayoutableFlag = targetMorph.isLayoutable;
targetMorph.isLayoutable = false; // avoid any resizing interference here
targetMorph.extent = limitExtent;
targetMorph.applyLayoutIfNeeded(true);
// implement the handshake and potential layout switch at exactly this point
this.apply(targetMorph, previousTarget);
targetMorph.isLayoutable = false;
targetMorph.applyLayoutIfNeeded(true);
targetMorph.extent = actualExtent;
targetMorph.isLayoutable = origLayoutableFlag;
});
}
targetMorph._lastIndex = currIndex;
})();
}
getLastMatchingBreakpoint (target) {
let curr = this;
let matchingBreakpoint;
while (curr = curr.getMatchingBreakpointMaster(target)) {
matchingBreakpoint = curr = curr.stylePolicy || curr;
}
return matchingBreakpoint || curr;
}
needsBreakpointUpdate (target) {
const matchingBreakpoint = this.getLastMatchingBreakpoint(target);
if (typeof matchingBreakpoint === 'undefined') return false;
if (matchingBreakpoint === (target._lastBreakpoint || null)) { return false; }
target._lastBreakpoint = matchingBreakpoint;
return true;
}
/**
* Evaluates to true, in case the policy changes its style in response to click states.
*/
get respondsToClick () {
if (this._clickMaster) return true;
if (this._localComponentStates && Object.values(this._localComponentStates).find(policy => policy.respondsToClick)) return true;
return !!this.parent?.respondsToClick || !!this._autoMaster?.respondsToClick;
}
/**
* Sets the policy to a given component state, that takes precedence over all other
* dispatched components (i.e. click, hover, auto ...). If we pass null,
* we reset the component state, reverting to the normal dispatch.
* @param { null|string} componentState - The string encoding a component state known to the policy.
*/
setState (componentState) {
if (this._componentState === componentState) return;
this._componentState = componentState;
this.targetMorph?.requestMasterStyling();
}
getState () {
return this._componentState;
}
/**
* Checks wether or not another policy is in the derivation chain of this
* policy.
*/
uses (aPolicy, immediate = false) {
if (aPolicy.isComponentDescriptor) aPolicy = aPolicy.stylePolicy;
if (this.parent === aPolicy) {
return true;
}
if (obj.equals(
obj.select(this.parent?.[Symbol.for('lively-module-meta')] || {}, ['moduleId', 'exportedName', 'path']),
obj.select(aPolicy[Symbol.for('lively-module-meta')] || {}, ['moduleId', 'exportedName', 'path']))) { return true; }
if (immediate) return false;
if (this.parent?.uses(aPolicy)) return true;
return false;
}
/**
* Registers itself as a derived style policy at its parent.
*/
registerAtParent () {
const { parent } = this;
if (parent) {
const dependants = parent._dependants || new Set();
dependants.add(expressionSerializer.exprStringEncode(this.__serialize__()));
parent._dependants = dependants;
}
}
get statePartitionedInline () {
return this._statePartitionedInline || this.parent?.statePartitionedInline || this.spec.master?.statePartitionedInline;
}
/**
* Evaluates to true, in case the policy changes its style in response to hover events.
*/
get respondsToHover () {
if (this._hoverMaster) return true;
if (this._localComponentStates && Object.values(this._localComponentStates).find(policy => policy.respondsToHover)) return true;
return !!this.parent?.respondsToHover || !!this._autoMaster?.respondsToHover;
}
_getSpecAsExpression (opts = {}) {
let { __expr__: expr, bindings } = serializeSpec(this.targetMorph, {
asExpression: true,
keepFunctions: false,
exposeMasterRefs: true,
dropMorphsWithNameOnly: true,
skipUnchangedFromDefault: false, // if true, this will lead to incorrect specs
skipUnchangedFromMaster: true,
onlyIncludeStyleProps: true,
valueTransform: standardValueTransform,
...opts
}) || { __expr__: false };
if (!expr) return;
expr = `${expr.match(/^(morph|part)\(([^]*)\)/)?.[2] || expr}`;
expr = expr.match(/^.*\, (\{[^]*\})/)?.[1] || expr;
if (this.parent?.[Symbol.for('lively-module-meta')]) {
delete bindings[this.parent[Symbol.for('lively-module-meta')].exportedName];
}
return {
bindings,
__expr__: expr
};
}
_generateInlineExpression () {
const klassName = this.constructor[Symbol.for('__LivelyClassName__')];
const parentExpr = this.parent?.__serialize__();
let masterConfigExpr = this.getConfigAsExpression();
if (masterConfigExpr) masterConfigExpr.__expr__ = 'master: ' + masterConfigExpr.__expr__;
const specExpression = this._getSpecAsExpression({
skipAttributes: ['textAndAttributes'], // this avoids overly large expressions, which include text information that is not of concern for applying a style
valueTransform: (key, val, target, protoVal) => {
// in order to properly store information about
// overridden properties within the expression we
// directly embedd the overriden prop symbols in the expression
if (protoVal === Symbol.for('lively.skip-property')) return Symbol.for('lively.skip-property');
if (key === 'submorphs') return val.filter(m => !m.isEpiMorph);
else return standardValueTransform(key, val, target, protoVal);
}
});
const bindings = { 'lively.morphic/components/policy.js': [klassName] };
if (parentExpr) mergeBindings(parentExpr.bindings, bindings);
if (masterConfigExpr) mergeBindings(masterConfigExpr.bindings, bindings);
mergeBindings(specExpression.bindings, bindings);
// now we technically also need to properly serialize the spec into an expression...
return {
__expr__: `new ${klassName}(${specExpression.__expr__}, ${parentExpr?.__expr__ || 'null'})`,
bindings
};
}
getConfig () {
let {
_autoMaster: auto, _clickMaster: click, _hoverMaster: hover,
_localComponentStates: states
} = this;
const breakpoints = this._breakpointStore?.getConfig();
const spec = {};
if (auto) spec.auto = auto;
if (click) spec.click = click;
if (hover) spec.hover = hover;
if (states) spec.states = states;
if (breakpoints) spec.breakpoints = breakpoints;
return obj.isEmpty(spec) ? null : spec;
}
getConfigAsExpression () {
const {
_autoMaster: auto, _clickMaster: click, _hoverMaster: hover,
_localComponentStates: states
} = this;
const bpStore = this._breakpointStore;
if (!arr.compact([auto, click, hover, ...obj.values(states)]).every(c => c[Symbol.for('lively-module-meta')])) return;
if (this.statePartitionedInline) return;
const masters = [];
const bindings = {};
if (auto) masters.push(['auto', auto.__serialize__()]);
if (click) masters.push(['click', click.__serialize__()]);
if (hover) masters.push(['hover', hover.__serialize__()]);
if (states) masters.push(['states', Object.entries(states).map(([state, master]) => [state, master.__serialize__()])]);
let bps;
if (bpStore && (bps = bpStore.__serialize__())) masters.push(['breakpoints', bps]);
if (masters.length === 0) return;
if (masters.length === 1 && auto) {
return auto.__serialize__();
}
const printMasters = (masters) => {
let __expr__ = '';
for (let [name, expr] of masters) {
let printed;
if (obj.isArray(expr)) printed = `{\n${printMasters(expr)}}`;
else {
printed = expr.__expr__;
if (!printed) continue;
mergeBindings(expr.bindings, bindings);
}
__expr__ += `${name}: ${printed},\n`;
}
return __expr__;
};
const printed = printMasters(masters);
if (printed === '') return;
return { __expr__: `{\n${printMasters(masters)}}`, bindings };
}
__serialize__ () {
const meta = this[Symbol.for('lively-module-meta')];
if (!meta) {
return this._generateInlineExpression();
}
return {
__expr__: meta.exportedName + (meta.path.length ? `.stylePolicy.getSubSpecAt([${meta.path.map(name => JSON.stringify(name)).join(',')}])` : ''),
bindings: { [meta.moduleId]: [meta.exportedName] }
};
}
/**
* Add meta info about module and retrieval to policy and its sub policies.
* @param { object } metaInfo
* @param { string } metaInfo.exportedName - The exported variable name the root policy.
* @param { string } metaInfo.moduleId - The module id where this policy was declared in.
* @param { string[] } metaInfo.path - If we are a sub style policy, this contains the names of the policy's parents. This info is important for expression generation and serialization.
*/
addMetaInfo ({ exportedName, moduleId, path = [], range = false }, spec = this) {
if (spec.isPolicy) {
spec[Symbol.for('lively-module-meta')] = {
exportedName, moduleId, path, range
};
spec.registerAtParent();
spec = spec.spec;
}
for (let subSpec of spec.submorphs || []) {
if (subSpec.COMMAND === 'add') subSpec = subSpec.props;
this.addMetaInfo({ exportedName, moduleId, path: subSpec.isPolicy ? [...path, subSpec.name] : [...path], range }, subSpec);
}
}
generateUniqueNameFor (node) {
const type = node.type?.[Symbol.for('__LivelyClassName__')] || node.type || 'morph';
let candidate = string.incName(type);
while (StylePolicy.usedNames.has(candidate)) candidate = string.incName(candidate);
StylePolicy.usedNames.add(candidate);
return candidate;
}
generateBaseSpecFromLocal (spec) {
const klass = this.constructor;
return tree.mapTree(spec, (node, submorphs) => {
if (node.props) {
if (!node.props.name) { node.props.name = this.generateUniqueNameFor(node); }
} else if (!node.name && node !== spec) { node.name = this.generateUniqueNameFor(node); }
if (node.isPolicy) return node.copy(); // duplicate the node to prevent in place modification or the original spec
if (node.master) {
return new klass({ ...node, submorphs }, null);
}
// The way styles are calculated right now is that we check if there is a autoMaster and if no
// autoMaster is present (which is rare) we proceed to utilize the default value dictated by the morph class.
// It may make sense to further dig for more "appropriate" default values by taking a look at other masters
// such as the ones found in the breakpoints or the custom states.
const defaultProps = !this._autoMaster?.managesMorph(node !== spec ? node.name : null) && getDefaultValuesFor(node.type || Morph) || {};
for (let prop in defaultProps) {
defaultProps[prop] = { isDefaultValue: true, value: defaultProps[prop] };
}
if (node.textAndAttributes) {
return {
...defaultProps,
...node,
submorphs,
textAndAttributes: node.textAndAttributes.map(textOrAttr => {
if (textOrAttr?.__isSpec__) {
return this.generateBaseSpecFromLocal(textOrAttr);
}
return textOrAttr;
})
};
}
// also insert the default values here if not defined
return { ...defaultProps, ...node, submorphs };
}, node => node.submorphs || []);
}
generateBaseSpecFromParent () {
const klass = this.constructor;
return tree.mapTree(this.parent.spec, (node, submorphs) => {
if (node.COMMAND === 'add') {
node = node.props;
if (!node.name) { node.name = this.generateUniqueNameFor(node); }
}
if (node.COMMAND === 'replace') {
node = node.props;
}
if (node.COMMAND === 'remove') return null; // drop specs that are removed
if (node.isPolicy) {
node._needsDerivation = true;
return node; // this will be derived and replaced later on
}
node = obj.dissoc(node, ['master', 'submorphs', '__wasAddedToDerived__', ...getStylePropertiesFor(node.type)]);
if (node.textAndAttributes) {
node.textAndAttributes = node.textAndAttributes.map(textOrAttr => {
if (textOrAttr?.isPolicy) return new klass({}, textOrAttr);
return textOrAttr;
});
}
if (submorphs.length > 0) node.submorphs = arr.compact(submorphs);
return node;
}, node => node.submorphs || node.props?.submorphs || []); // get the fully collapsed spec
}
/**
* The main purpose of this method is to properly initialize style policies within our spec in order to reify
* what is called "inline policies".
* Usually, we declare an inline policy by placing a part() within one
* of the submorph arrays in the spec we pass to component().
* However inline policies can also be declared "implicitly".
* Overriding the master property in one of our submorphs in the component or
* declaring a 2nd, 3rd, etc rate inline policy is not signified by a part call. We however we still need to wrap
* these cases. This is why this routing scans our current spec for these cases and ensures
* they are stored as StylePolicies accordingly.
* We also ensure the presence of "empty" style policies, that did not get adressed
* in the derivation at all. This is mainly for the purpose of simplifying the generation
* of build specs.
* @param { object } spec - The spec object to scan for policies that need to be inserted.
* @returns { object } The spec with the explicit/implicit style policies inserted.
*/
ensureStylePoliciesInSpec (spec) {
const klass = this.constructor;
if (spec.master) {
if (spec.master.isPolicy || spec.master.isComponentDescriptor) {
this.applyConfiguration({ auto: spec.master });
} else {
this.applyConfiguration(spec.master);
}
spec = obj.dissoc(spec, ['master']);
}
if (!this.parent) {
return this.generateBaseSpecFromLocal(spec);
}
if (this.parent) {
// we need to traverse the spec and the parent's build spec simultaneously
const overriddenMaster = this._autoMaster;
const partitioningPolicy = this;
const toBeReplaced = new WeakMap();
const baseSpec = this.generateBaseSpecFromParent();
function replace (node, replacement) {
toBeReplaced.set(node, replacement);
}
const handleRemove = (parent, toBeRemoved) => {
// insert remove command directly into the baseSpec
replace(toBeRemoved, {
COMMAND: 'remove',
target: toBeRemoved.name
});
};
const handleAdd = (parent, toBeAdded, before) => {
// insert add command directly into the baseSpec
const index = before ? parent.submorphs.indexOf(before) : parent.submorphs.length;
if (!toBeAdded.isPolicyApplicator) {
toBeAdded = this.generateBaseSpecFromLocal(toBeAdded);
}
if (!toBeAdded.name) toBeAdded.name = this.generateUniqueNameFor(toBeAdded);
arr.pushAt(parent.submorphs, {
COMMAND: 'add',
props: toBeAdded
}, index);
};
const mergeSpecs = (parentSpec, localSpec) => {
// handle viewModel
const parentViewModel = parentSpec.spec?.viewModel || parentSpec.viewModel;
if (parentViewModel && localSpec.viewModel) {
parentSpec.viewModel = obj.deepMerge(parentViewModel, localSpec.viewModel);
}
// handle text and attribute merging
if (localSpec.textAndAttributes && parentSpec.textAndAttributes &&
localSpec.textAndAttributes.length === parentSpec.textAndAttributes.length) {
localSpec.textAndAttributes = arr.zip(
localSpec.textAndAttributes,
parentSpec.textAndAttributes).map(([localAttr, parentAttr]) => {
if (parentAttr?.isPolicy) {
return new klass(localAttr, parentAttr.parent);
}
if (parentAttr?.__isSpec__) {
return mergeInHierarchy({ ...parentAttr }, localAttr, mergeSpecs, true, handleRemove, handleAdd);
}
return localAttr;
});
}
// up to here everything regarding the root is done.
// last thing we do is carry over the name, if nothing was provided
// for convenience sake
if (localSpec === spec) {
if (!localSpec.name && parentSpec.name) localSpec.name = parentSpec.name;
return;
}
let localMaster = localSpec.master;
const overridden = overriddenMaster?.synthesizeSubSpec(localSpec.name);
if (!localMaster) localMaster = overridden?.isPolicy && overridden;
delete parentSpec._needsDerivation;
if (localMaster && parentSpec.isPolicy) {
// rms 13.7.22 OK to get rid of the descriptor here,
// since we are "inside" of a def which is reevaluated on change anyways.
localMaster = localMaster.isComponentDescriptor ? localMaster.stylePolicy : localMaster; // ensure the local master
return replace(parentSpec, new klass({ ...localSpec, master: localMaster }, parentSpec));
}
if (parentSpec.isPolicy) { // we did not introduce a master and just adjusted stuff
return replace(parentSpec, new klass(localSpec, parentSpec).splitBy(partitioningPolicy, parentSpec.name)); // insert a different style policy that has the correct overrides
}
if (localMaster) { // parent spec is not a policy, and we introduced a master here
localMaster = localMaster.isComponentDescriptor ? localMaster.stylePolicy : localMaster; // ensure the local master
return replace(parentSpec, new klass({ ...localSpec, master: localMaster }, this.parent.extractStylePolicyFor(parentSpec.name)));
}
Object.assign(parentSpec, obj.dissoc(localSpec, ['submorphs'])); // just apply the current local spec
};
mergeInHierarchy(baseSpec, spec, mergeSpecs, true, handleRemove, handleAdd);
// afterwards perform the replacement of nodes as requested by the replace() fn
const finalSpec = tree.mapTree(baseSpec, (node, submorphs) => {
if (toBeReplaced.has(node)) return toBeReplaced.get(node);
else {
// this allows us to skip the unnessecary creation of an object
if (!node.isPolicy && submorphs.length > 0) { node.submorphs = submorphs; }
// if we encounter a node that was left untouched, we need to derive it now
if (node.isPolicy && node._needsDerivation) {
delete node._needsDerivation;
const args = {};
const overridden = overriddenMaster?.synthesizeSubSpec(node.name);
if (overridden) args.master = overridden;
return new klass(args, node).splitBy(partitioningPolicy, node.name);
}
return node;
}
}, node => node.submorphs || []);
// replace the marked entries
return {
...obj.dissoc(baseSpec, ['master', 'submorphs', ...getStylePropertiesFor(baseSpec.type)]),
...spec,
...finalSpec.viewModel ? { viewModel: finalSpec.viewModel } : {},
submorphs: finalSpec.submorphs || []
};
}
}
/**
* Turns a spec object that used to not be a style policy before into a style policy.
* This involves traversing the parents and initializing the previously missing style policies
* for every time the sub spec was mentioned. Note, that this process does not "alter" the parent
* component definitions.
* @param { string } specName - The name of the sub spec.
* @returns { StylePolicy|null} If sub spec is found in this policy, the newly initialized style policy based on that sub spec.
*/
extractStylePolicyFor (specName) {
const subSpec = this.lookForMatchingSpec(specName, this._originalSpec, false);
const klass = this.constructor;
if (subSpec) return new klass(subSpec, this.parent ? this.parent.extractStylePolicyFor(specName) : null);
return null;
}
/**
* This is called in response to changes in either breakpoints or component states.
* Any adustments in those warrant a update in the partitioned "split" policies that
* sit in the next level.
*/
updateSplitPolicies () {
tree.mapTree(this.spec, (node, submorphs) => {
if (node.isPolicy) {
node.splitBy(this, node.name, true); // in-place update
}
}, node => node?.submorphs || []);
}
/**
* Creates a new morph from the fully synthesized spec.
* @returns { Morph } The new morph based off the sully synthesized spec.
*/
instantiate (props = {}) {
// we may be able to avoid this explicit wrapping of the policies
// by moving that logic into the master setter at a later stage
const inst = morph(new PolicyApplicator(props, this).asFullySynthesizedSpec()); // eslint-disable-line no-use-before-define
// FIXME: This is temporary and should be moved into the viewModel setter after transition is complete.
withAllViewModelsDo(inst, m => {
m.viewModel.attach(m); // as fully synthesized spec does not seem to assign all viewModels
});
return inst;
}
asFullySynthesizedSpec () {
const extractBuildSpecs = (specOrPolicy, submorphs) => {
if (specOrPolicy.__alreadySynthesized__) return specOrPolicy;
if (specOrPolicy.COMMAND === 'add') {
specOrPolicy = specOrPolicy.props;
}
if (specOrPolicy.COMMAND === 'remove') return null; // target is already removed so just ignore the command
if (specOrPolicy.isPolicy) return specOrPolicy.asFullySynthesizedSpec();
if (!submorphs) submorphs = specOrPolicy.submorphs || [];
const modelClass = specOrPolicy.defaultViewModel || specOrPolicy.viewModelClass;
const modelParams = { ...specOrPolicy.viewModel } || {}; // accumulate the derivation chain for the viewModel
const virtualMorph = {
env: {},
width: specOrPolicy.width || specOrPolicy.extent?.x || 10,
height: specOrPolicy.height || specOrPolicy.extent?.y || 10
};
// if the owner of this morph has a layout, the extent or width may be different
const synthesized = this.synthesizeSubSpec(specOrPolicy === this.spec ? null : specOrPolicy.name, virtualMorph, virtualMorph);
if (specOrPolicy.__wasAddedToDerived__) synthesized.__wasAddedToDerived__ = true;
if (specOrPolicy.name) synthesized.name = specOrPolicy.name;
// remove the props that are equal to the default value
getStylePropertiesFor(specOrPolicy.type).forEach(prop => {
if (synthesized[prop]?.isDefaultValue) {
delete synthesized[prop];
}
if (prop === 'layout' && synthesized[prop]?.isLayout) synthesized[prop] = synthesized[prop].copy();
});
if (synthesized.textAndAttributes) {
synthesized.textAndAttributes = synthesized.textAndAttributes.map(textOrAttr => {
if (textOrAttr?.__isSpec__) return morph(tree.mapTree(textOrAttr, extractBuildSpecs, node => node.submorphs)); // ensure sub build specs...
if (textOrAttr?.isPolicy) return textOrAttr.instantiate();