-
Notifications
You must be signed in to change notification settings - Fork 0
/
mint.js
651 lines (550 loc) · 24.4 KB
/
mint.js
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
import * as REF from './ref.js'
import * as Relays from './relay.js'
import { funcs } from './funcs.js'
import { GelSheet } from './sheet.js'
import { MicroQueue } from './list.js'
import { gel } from './base.js'
import { is } from './is.js'
import { GelPlates } from './template.js'
import { Subscription } from './classes.js'
import { Behavior } from './classes.js'
export const mint = (function() {
// Analyzes all properties on the user-provided Gel.mint config object
// ('$g') and sorts them into different groups, one for the getter/setter
// (accessor) props, one for extra (non-reserved) user-provided props, and
// one group that includes all properties
function describeAndSortProps($g) {
const orig = Object.entries(Object.getOwnPropertyDescriptors($g))
const accessors = orig.filter(([prop,desc])=> is.func(desc.get))
const accPropNames = accessors.map(([prop,])=> prop);
const filteredExtra = orig.filter(([prop,desc])=>
!(gel.reserved.has(prop)) && !(accPropNames.includes(prop))
)
return {
allProps: orig,
accessorProps: accessors,
extraProps: filteredExtra
}
}
// defines + binds the provided array of accessor property entries
// generated by 'describeAndSortProps' to this element
function initAccessorProps(accessorPropEntries) {
accessorPropEntries.forEach(([accprop,desc])=> {
const bound = desc.get.bind(this);
Object.defineProperty(this, accprop, {
enumerable: true,
get: desc.get.bind(this),
...( is.func(desc.set) ? {
set: desc.set.bind(this)
} : {})
})
})
}
// Extend this element instance with all properties in the provided
// 'extensionProperties' object.
// (Used to add arbitrary user-provided properties from the Gel.mint
// configuration object to each element instance.)
function initExtraUserProps(extensionProperties) {
return funcs.extend(this, extensionProperties)
}
// Immediately calls the onConstruct() method with appropriate context
// if such a method was provided by the user in the Gel.mint config object.
// Note - this one does not need to be added as a hook, because by the
// time hooks can be configured, this lifecycle hook is already ready to be
// triggered
function onConstructCall($gonConstruct) {
return $gonConstruct.call(this)
}
// these six methods are used to trigger the appropriate hook for calling any
// user-provided lifecycle methods from the Gel.mint config object
function onConnectCall($gonConnect) {
return this.hooks.onConnect.add(()=> $gonConnect.call(this))
}
function afterConnectCall($gafterConnect) {
return this.hooks.afterConnect.add(()=> $gafterConnect.call(this))
}
function afterAllConnectCall($gafterAllConnect) {
return this.hooks.afterAllConnect.add(()=> $gafterAllConnect.call(this))
}
function afterFirstContentCall($gafterFirstContent) {
return this.hooks.afterFirstContent.add(()=> $gafterFirstContent.call(this))
}
function afterRenderCall($gafterRender) {
return this.hooks.afterRender.add(()=> $gafterRender.call(this))
}
function beforeRenderCall($gbeforeRender) {
return this.hooks.beforeRender.add(()=> $gbeforeRender.call(this))
}
// calls the initSlots method from the parent 'gel' class
function initSlotsCall() {
return gel.prototype.initSlots.call(this)
}
// Used to bind certain DOM queries to element properties.
// Called when the 'bindElements' property is included on the user-provided
// Gel.mint config object. The value of the 'bindElements' property is
// '$gbindelem', and this function iterates through each property on
// $gbindelem and sets up the bound query
function initElemBindings($gbindelem) {
Object.entries($gbindelem).forEach(([identifier, queryStr]) => {
Object.defineProperty(this, identifier, {
enumerable: true,
configurable: true,
get: function() {
return (this.shadowRoot ?? this).querySelector(queryStr)
}
})
})
}
// iterates through the list of attribute name strings '$gbindattr' and
// creates a new Attribute Relay instance for each one.
function initAttrBindings($gbindattr) {
$gbindattr.forEach((aprop)=> {
const aName = funcs.toCamelCase(aprop)
this.relays[aName] = new Relays.AttrRelay(this, { attr : aprop })
this.addExitHook(()=> this.relays[aName].disable())
})
}
// for the table of style pipe definitions '$gbindstyle', iterate through
// each property and call the GelSheet method 'initStylePipes' to init each
// binding
function initStyleBindings($gbindstyle) {
Object.entries(funcs.evalTilNotFunc(this, $gbindstyle)).forEach(([name, def])=>
this.instanceStyles.initStylePipes(this.style, name, def)
)
}
// for template-markup-generating function '$gtemplate'
// bind it to this element and assign it to the property
// 'template'
function initTemplateF($gtemplate) {
this.template = (
(bound)=> function (...args) {
return bound(...args)
}
)( $gtemplate.bind(this) )
}
// for markup string '$gtemplate', assign a function that returns the string
// unmodified to this element's 'template' property
function initTemplateS($gtemplate) {
this.template = function(...args) {
return $gtemplate
}
}
// queries this element's dom subtree for all input elements that have the
// 'relay' attribute set - then iterates through each matching input element
// and initializes the input relay bindings for each one
function initInputRelays() {
this.hooks.afterRender.add(()=> {
(this.shadowRoot ?? this).querySelectorAll('input[relay]').forEach(el=> {
const [owner, prop, name, type] = gel.prototype
.getAttributes.call(el, 'owner','prop','name','type');
if (prop != null && owner != null) {
// create the actual Relay instance
this.relays[name] = new Relays.InputRelay(this, {
prop, name,
target: el,
owner: Reflect.get(this, owner)
?? Reflect.get(this.pubs, owner)?.target
?? Reflect.get(this.subs, owner)?.target
})
if (el.relay === undefined) {
// define the 'relay' property on the input element,
// linking to the Relay instance we created above
Object.defineProperty(el, 'relay', {
configurable: true,
enumerable: true,
get:()=> this.relays[name]
})
}
if (this[name] === undefined) {
// add a property w/ the same name as the input relay's name
// on this element
Object.defineProperty(this, name, {
enumerable: true,
get:()=> this.relays[name]
})
}
this.addExitHook(()=> {
this.relays[name].disable();
// overwrite the 'relay' property we created on the input
// element with the value 'undefined'
Object.defineProperty(el, 'relay', {
value: undefined,
writable: true,
configurable: true,
enumerable: true
})
})
}
})
})
}
// If the 'publishers' option is included on the gel.mint configuration
// object, its value is sent to this function as '$gpublishers'. PubSub Relay
// instances are created for each property on the publishers def object
function initPublishers($gpublishers) {
Object.entries( funcs.evalTilNotFunc(this, $gpublishers)).forEach(([id, pub])=> {
this.pubs[id] = new Relays.PubSubRelay(this, { target: pub })
this.addExitHook(()=> this.pubs[id].disable())
})
}
// If the 'subscriptions' option is included on the gel.mint configuration
// object, its val is sent to this function as '$gsubscriptions'. Subscription
// instances are created for each property on the subscriptions def object
function initSubscriptions($gsubscriptions){
this.hooks.onConnect.add(()=> {
Object.entries( funcs.evalTilNotFunc(this, $gsubscriptions))
.forEach(([id, args])=> {
this.subs[id] = new Subscription(id, ...args)
this.addExitHook(()=> this.subs[id].end())
})
})
}
function initListenerQueue($g) {
const topLvlListeners = [];
// search for any top-level properties on the gel.mint configuration
// object '$g' that match any of the names in DOMEVENTNAMES,
Object.keys($g).forEach(key=> {
if (REF.DOMEVENTNAMES.has(key) && typeof $g[key] === 'function') {
topLvlListeners.push([ this, key.slice(2).toLowerCase(), $g[key] ])
}
})
// if any functions were identified from above, add them to this
// element's behaviors init queue
if (topLvlListeners.length) {
this.behaviors.push(()=> new Behavior(this, topLvlListeners))
}
// if the gel.mint config object '$g' has a 'listeners' property that is
// an array, object, or function, add its evaluated value to this element's
// behaviors init queue
if (is.like($g.listeners,'arr','func','obj')) {
this.behaviors.push(
()=> new Behavior(this, funcs.evalTilNotFunc(this, $g.listeners))
)
}
}
// if the 'eventDefaultsPrevented' option is included on the gel.mint
// configuration object, its value is passed to this function as
// '$geventDefaultsPrevented'. For each event name, an event handler is
// bound to it that calls the event's 'preventDefault' and 'stopPropagation'
// methods
function initEvtDefaultsPrevent($geventDefaultsPrevented) {
this.behaviors.push(()=>
new Behavior(
this,
$geventDefaultsPrevented.map((eName)=>
[
this,
eName,
e=> { e.preventDefault(); e.stopPropagation() },
{}
]
)
)
);
}
// a helper method inserted into every element's custom init queue that queues
// up the right order of different lifecycle hooks in relation to the
// initialization of the component's Behaviors
function prepFirstRender() {
this.hooks.afterFirstContent.add(()=> {
if ( is.func(this.behaviors.at(0))
&& !(this.behaviors.at(0) instanceof Behavior) ) {
// unpack the behaviors list to assign proper 'this' context
this.behaviors.unpack(this)
}
this.addExitHook(()=> this.behaviors.disable())
this.hooks.afterRender.add(()=> this.behaviors.enable())
this.behaviors.enable()
})
this.hooks.onConnect.add(()=> this.hooks.afterConnect.run.call(this))
this.hooks.afterConnect.add(()=> this.initComplete = true )
}
// if an 'observers' property has been included on the gel.mint
// configuration object, its value is passed to this function
// as '$gobservers', where the appropriate Relay instances
// are created for each observer definition found
function initObservers($gobservers) {
const processor = (key, origFunc, targetDef)=> {
if (targetDef.throttle)
origFunc = funcs.throttle(origFunc, targetDef.throttle)
if (targetDef.debounce)
origFunc = funcs.debounce(origFunc, targetDef.debounce)
return origFunc
}
const obs = funcs.evalTilNotFunc(this, $gobservers)
;[ 'resize','intersection','mutation' ].forEach(type=> {
const def = obs[type]
const relayIdent = funcs.capitalize(type)+'Relay'
if (def) {
this.relays[type+'Observer'] = new Relays[relayIdent](this, {
target: def.observe ?? this,
...(def.onEnter && def.onLeave ?
{
onEnter: processor(type, def.onEnter.bind(this), def),
onLeave: processor(type, def.onLeave.bind(this), def)
} : {
callback: processor(
type,
def.callback?.bind(this) ?? def.bind(this),
def
)
}
)
})
this.addExitHook(()=> this.relays[type+'Observer'].disable())
}
})
}
// if an 'attrObservers' property was included on the gel.mint config
// object, its value is passed to this function as '$gattrObservers',
// and the appropriate add function on this element's 'attrObs' instance
// is called to initialize the attribute observer callbacks
function initAttrObservers($gattrObservers) {
this.attrObs.addObservers( this, funcs.evalTilNotFunc(this, $gattrObservers));
this.addExitHook(()=> this.attrObs.disable() )
}
// if an 'attrBehaviors' property was included on the gel.mint config
// object, its value is passed to this function as '$gattrBehaviors',
// and the appropriate add function on this element's 'attrObs' instance
// is called to initialize the attribute behaviors
function initAttrBehaviors($gattrBehaviors) {
this.attrObs.addBehaviors( this, funcs.evalTilNotFunc(this, $gattrBehaviors));
this.addExitHook(()=> this.attrObs.disable() )
}
// this function prepares the array of strings for the standard web
// component static property getter 'observedAttributes' by determining
// from the gel.mint configuration object '$g' which attributes need to
// be included in the observed array and compiling the appropriate list
function prepObservedAttributeList($g) {
if ($g.observedAttributes === undefined)
$g.observedAttributes = [];
$g.observedAttributes = Array.from( new Set(
$g.observedAttributes
.concat(
[ $g.attrBehaviors, $g.attrObservers ].map(
confObj=> Object.keys(confObj ?
funcs.evalTilNotFunc(this, confObj)
: {}
)
).flat()
)
.concat(
$g.bind?.attr ?? []
)
.map(prop=> prop.startsWith('not_') ?
prop.replace('not_','')
: prop
)
));
return $g.observedAttributes
}
const gEl = {
// some keys for pseudo-hidden properties on the class definitions created
// by gel.mint
build: Symbol('gel_build'),
attrs: Symbol('gel_attrs'),
// debug print function for testing the init script / queue building
// functions that happen in the static initialization block of the
// generated class definition
outlineBuildInstructions: (tagName, init1, init2)=>
`\n<<< gel Build Instructions: '${tagName}' >>>`
+ `\n PreRender: \n${'\n -'
+ init1.copy.map(([func,])=> func.name).join('\n -')}`
+ `\n PostRender:\n${'\n -'
+ init2.copy.map(([func,])=> func.name).join('\n -')}`
}
// createCustomGelamintClass - this function is called by the 'mint' function
// to create the custom class definition that is supplied to the
// customElements.define method in order to create a custom
// element / web component
function createCustomGelamintClass(Gel_dot_MintInputConfigurationObject) {
const $g = Gel_dot_MintInputConfigurationObject;
return class extends gel {
static [gEl.attrs] = prepObservedAttributeList($g);
static get name() {
return $g._tagName
}
static get classStyles() {
return $g._styles
}
static get observedAttributes() {
return this[gEl.attrs]
}
static {
const bld = this[gEl.build] = {
// queue of functions to be executed by instance constructor
// before first render call
preRender: new MicroQueue(),
// queue of functions to be executed by instance constructor
// after first render call
postRender: new MicroQueue()
};
// some shortcut variables for brevity
const addPre = bld.preRender.add;
const addPost= bld.postRender.add;
const {
allProps: props,
extraProps: extensionsList,
accessorProps: accessorEntries,
} = this.initConfiguration = describeAndSortProps($g);
// save the original state of the config object
this.initConfiguration = props ;
// these help keep things neat below
const afo = ['arr','func','obj']
const fo = afo.slice(1)
const $gEdf = $g.eventDefaultsPrevented
if (accessorEntries.length) {
addPre([ initAccessorProps, accessorEntries ])
}
if (Object.keys(extensionsList).length) {
addPre([ initExtraUserProps, extensionsList ])
}
if (is.arr($g.bindAttributes)) {
addPre([ initAttrBindings, $g.bindAttributes ])
}
if (is.obj($g.bindElements)) {
addPre([ initElemBindings, $g.bindElements ])
}
if (is.like($g.bindStyles,...afo)) {
addPre([ initStyleBindings, $g.bindStyles ])
}
if (is.func($g.onConstruct)) {
addPre([ onConstructCall, $g.onConstruct ])
}
addPre([ prepFirstRender, null ])
addPre([ initInputRelays, null ])
if (is.like($g.subscriptions,...afo)) {
addPre([ initSubscriptions, $g.subscriptions ])
}
if (is.func($g.template)) {
addPre([ initTemplateF, $g.template ])
}
else if (is.str($g.template)) {
addPre([ initTemplateS, $g.template ])
}
if (is.func($g.afterFirstContent)) {
addPre([ afterFirstContentCall, $g.afterFirstContent ])
}
if (is.func($g.onConnect)) {
addPre([ onConnectCall, $g.onConnect ])
}
if (is.func($g.afterConnect)) {
addPre([ afterConnectCall, $g.afterConnect ])
}
if (is.func($g.beforeRender)) {
addPre([ beforeRenderCall, $g.beforeRender ])
}
if (is.func($g.afterRender)) {
addPre([ afterRenderCall, $g.afterRender ])
}
if (is.like($g.publishers,...afo)) {
addPre([ initPublishers, $g.publishers ])
}
addPre([ initListenerQueue, $g ])
if (is.like($g.commandResponses,...fo)) {
addPre([ initCommandResponses, $g.commandResponses ])
}
if (is.arr($gEdf)) {
addPre([ initEvtDefaultsPrevent, $gEdf ]);
}
// pre ^ / post v
addPost([ initSlotsCall, null ]);
if (is.like($g.observers,...fo)) {
addPost([ initObservers, $g.observers ])
}
if (is.like($g.attrObservers,...fo)) {
addPost([ initAttrObservers, $g.attrObservers ])
}
if (is.like($g.attrBehaviors,...fo)) {
addPost([ initAttrBehaviors, $g.attrBehaviors ]);
}
if (!(this.styleCatalog.has($g._tagName))) {
this.styleCatalog.set($g._tagName, this.classStyles)
}
}// end static initialization block
constructor() {
super(); // <- base.js
this.initComplete = false;
this.renderCount = 0;
// apply styles
[ this.constructor.classStyles, this.instanceStyles ].forEach(
styleSheet=> styleSheet.applyTo(this)
);
// reverse styleSheet order so that instanceStyles takes priority,
// then classStyles, then commonStyles
this.shadowRoot.adoptedStyleSheets = [
...this.shadowRoot.adoptedStyleSheets
].reverse();
// run pre-render hooks
Array.from(this.constructor[gEl.build].preRender).forEach(
([fn, arg])=> fn.call(this, arg)
);
}
connectedCallback() {
this.render();
// run post-render hooks
Array.from(this.constructor[gEl.build].postRender).forEach(
([fn, arg])=> fn.call(this, arg)
);
// finish init hooks
this.hooks.afterFirstContent.run.call(this);
this.hooks.onConnect.run.call(this)
this.attrObs.ready = true
}
}
}
// The main user-facing function used to create gel web components
return Object.defineProperty(async function _mint(elName, config) {
// only create a new class definition if a custom element with the
// specified tag name does not already exist on the registry
if ( customElements.get(elName) === undefined ) {
config["_tagName"] = elName;
return new Promise(async success => {
if (typeof config === 'function') {
// if a function was passed in as the config object,
// evaluate it and use the value as our config object
config = config()
}
// create a new GelSheet for our class styles
config._styles = new GelSheet();
if (config.stylesUrl) {
// add remote fetched styles to class styles
config._styles.appendNewRules(
await funcs.cachedFetch(config.stylesUrl,'text')
)
}
if (config.styles) {
// add styles from the 'styles' property to the class styles sheet
config._styles.appendNewRules(config.styles);
}
// if a templateUrl property was provided, fetch the remote
// html content from the url, and assign it to the config object's
// 'template' property
if (config.templateUrl) {
config.template = await funcs.cachedFetch(config.templateUrl,'text');
}
// This is where the gel is born
_mint.blueprints[elName] = createCustomGelamintClass( config )
// actually register our new class definition with the customElements
// registry by passing the tag name, and the generated class def
// to the window.customElements.define function
customElements.define(elName, _mint.blueprints[elName]);
// resolve promise by returning the generated class definition
success(_mint.blueprints[elName])
})
}
// if a custom element with the specified tag name already exists on the
// custom element registry, return a link to its class definition from
// the mint.blueprints object
else {
return new Promise( g => g(_mint.blueprints[elName]))
}
},
'blueprints',
{
value: {},
enumerable: true,
configurable: true,
writable: true
})
})()