-
Notifications
You must be signed in to change notification settings - Fork 2k
/
g-component.html
567 lines (508 loc) · 17.5 KB
/
g-component.html
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
<!--
Copyright 2012 The Toolkitchen Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<element name="g-component">
<script>
this.lifecycle({
shadowRootCreated: function() {
}
});
</script>
<script>
// conventional names for automation
var conventions = {
ATTRIBUTES_ATTRIBUTE: "attributes",
DELEGATES_DIRECTIVE: "bind",
OBSERVE_DIRECTIVE: "observe",
PROPERTY_CHANGED_SUFFIX: "Changed",
CUSTOM_EVENT_PREFIX: "on-",
BINDING_OUT_SUFFIX: "Output",
BINDING_IN_SUFFIX: "Input"
};
// polyfill for DOMTokenList features:
// add/remove multiple classes
// arity-2 toggle
(function() {
'use strict';
var add = DOMTokenList.prototype.add;
var remove = DOMTokenList.prototype.remove;
DOMTokenList.prototype.add = function() {
for (var i = 0; i < arguments.length; i++) {
add.call(this, arguments[i]);
}
};
DOMTokenList.prototype.remove = function() {
for (var i = 0; i < arguments.length; i++) {
remove.call(this, arguments[i]);
}
};
DOMTokenList.prototype.toggle = function(name, value) {
if (value == undefined) {
value = !this.contains(name);
}
value ? this.add(name) : this.remove(name);
};
})();
(function(){
// attribute bindings
//
// <element attributes="attr1, attr2..."
//
// create matching observed properties attr1, attr2, etc.
// and attaches MutationObserver so that changes in the attributes
// are reflected in the matching properties
var bindAttrs = function(inAttributes) {
var attrs = this.boundAttributes = [];
if (inAttributes) {
var bindables = inAttributes.value.split(",");
bindables.forEach(function(a) {
a = a.trim();
attrs.push(a);
bindProperty.call(this, a, this[a]);
}, this);
}
};
// event bindings
//
// <element handlers="onclick: click, onkeypress: keypress, ..."
//
// create listeners on instances that map named events to
// methods on the instance
var bindEvents = function(inEvents) {
if (inEvents) {
var bindables = inEvents.value.split(",");
bindables.forEach(function(e) {
// event name: handler name pairs
var pair = e.split(":");
var event = pair[0].trim();
var handler = pair[1].trim();
if (this[handler]) {
this.addEventListener(event, this[handler].bind(this));
}
}, this);
}
};
// model bindings
//
// convert {{macro}} strings in markup into MDV bindings
//
// MDV usually does this work but requires an additional
// nested template and functions asynchronously
var bindModel = function(inNodes) {
var m = bindModel.mustache;
Array.prototype.forEach.call(inNodes, function(n) {
n = n.baby || n;
if (n.nodeName == "#text") {
if (n.textContent.search(m) >= 0) {
//console.log('addBinding', n.textContent, n);
n.addBinding(n.textContent);
}
} else if (n.attributes && n.tagName !== "TEMPLATE") {
// attribute bindings
Array.prototype.forEach.call(n.attributes, function(a) {
if (a.value.search(m) >= 0) {
//console.log('addBinding', a.name, a.value, n);
n.addBinding(a.name, a.value);
}
});
bindModel(n.childNodes);
}
});
};
bindModel.mustache = /\{\{([^{}]*)}}/g;
// property bindings
//
// sets up observable properties
//
// an observable property with <name> will automatically call
// <name>Changed method when the property value changes
// (if <name>Changed exists)
var propertyChanged = function(inName, inOld) {
var fn = inName + conventions.PROPERTY_CHANGED_SUFFIX;
if (this[fn]) {
this[fn](inOld);
}
};
var sideEffectFactory = function(inName) {
var fn = inName + conventions.PROPERTY_CHANGED_SUFFIX;
return function(inOld) {
if (this[fn]) {
this[fn](inOld);
}
};
};
var squelchSideEffects = false;
var setPropertySilently = function(inName, inValue) {
squelchSideEffects = true;
try {
this[inName] = inValue;
} finally {
squelchSideEffects = false;
}
};
var bindProperty = function(inName, inValue) {
if (inName in this) {
// set default value in a property already bound via attrs
setPropertySilently.call(this, inName, inValue);
} else {
//console.log('binding', inName, this)
var value = inValue;
var sideEffect = sideEffectFactory(inName);
Object.defineProperty(this, inName, {
get: function() {
return value;
},
set: function(v) {
var old = value;
value = v;
if (!squelchSideEffects && (old !== v)) {
sideEffect.call(this, old);
}
}
});
}
};
var bindProperties = function(inProperties) {
if (inProperties) {
Object.keys(inProperties).forEach(function(n) {
bindProperty.call(this, n, inProperties[n]);
}, this);
}
};
// node bindings
//
// local nodes that have ID and store references to them in
// this.$ hash
var deref = function(inNode) {
return inNode && (inNode.baby || inNode);
};
var establishNodeReferences = function(inRoot) {
// establish $ instance variable
this.$ = this.$ || {};
// populate $ from nodes with ID from the LOCAL tree
if (inRoot) {
var nodes = ShadowDOM.localQueryAll(inRoot, "[id]");
Array.prototype.forEach.call(nodes, function(n) {
this.$[n.id] = deref(n);
}, this);
}
};
// data bindings
//
// <name>: ['<path dependency>', '<path dependency>'...]
//
// bind MDV macros of the form {{<name>}} to formatting methods
// in inNode using MDV delegates
//
var bindDelegates = function(inDelegates) {
if (inDelegates) {
var node = this;
this.modelDelegate = function(inBinding) {
if (inBinding in inDelegates) {
var dependencies = inDelegates[inBinding] || [inBinding];
if (typeof dependencies == 'string') {
dependencies = [dependencies];
}
//console.log("bindDelegates:", inBinding, dependencies, node);
var inMethod = inBinding + conventions.BINDING_IN_SUFFIX;
var outMethod = inBinding + conventions.BINDING_OUT_SUFFIX;
return [
dependencies,
function(/*inValues*/) {
return delegateBinding(node, outMethod, arguments);
},
function(/*inValues*/) {
return delegateBinding(node, inMethod, arguments);
}
];
}
};
}
};
var delegateBinding = function(inNode, inDelegate, inValues) {
// late binding to named delegate function
var fn = inNode[inDelegate];
var value = fn ? fn.apply(inNode, inValues) : undefined;
// whenever undefined, echo back first input value
if (value === undefined) {
value = inValues[0];
}
//console.log(inDelegate, inValues, value);
return value;
};
var deref = function(inNode) {
return inNode && (inNode.baby || inNode);
};
var establishNodeReferences = function(inRoot) {
this.$ = this.$ || {};
// search the LOCAL tree
if (inRoot) {
var nodes = ShadowDOM.localQueryAll(inRoot, "[id]");
Array.prototype.forEach.call(nodes, function(n) {
this.$[n.id] = deref(n);
}, this);
}
};
// attribute mutations
var deserializeValue = function(inValue) {
switch (inValue) {
case "":
case "true":
return true;
case "false":
return false;
case "\\false":
return "false";
}
return isNaN(inValue) ? inValue : parseFloat(inValue);
};
// propagate initial bound-attribute values into properties
// as a batch, invoking side-effects only after all
// properties are initialized
var takeAttributes = function() {
var changed = [];
try {
squelchSideEffects = true;
this.boundAttributes.forEach(function(a) {
if (this.hasAttribute(a)) {
// get raw attribute value
var value = this.getAttribute(a);
// filter out 'mustached' values, these are to be
// replaced with bound-data and are not runtime
// values themselves
if (value.indexOf(bindModel.mustache) >= 0) {
return;
}
// deserialize Boolean or Number values from attribute
value = deserializeValue(value);
if (this[a] !== value) {
// track values that differ from property values
changed.push({name: a, old: this[a]});
// install new value (side-effects squelched)
this[a] = value;
}
}
}, this);
} finally {
squelchSideEffects = false;
}
// invoke side-effects in a batch after initializing
// all values
changed.forEach(function(c) {
propertyChanged.call(this, c.name, c.old);
}, this);
};
var attributeChanged = function(inName) {
this[inName] = deserializeValue(this.getAttribute(inName));
};
var handleMutations = function(inMxns) {
inMxns.forEach(function(inMxn) {
var name = inMxn.attributeName;
if (this.boundAttributes.indexOf(name) >= 0) {
attributeChanged.call(this, name);
}
}, this);
};
var AttrObserver = function(inNode) {
var observer = new WebKitMutationObserver(handleMutations.bind(inNode));
observer.observe(inNode, {
attributes: true,
attributeOldValue: true
});
return observer;
};
// lifecycle
// per-root
var initialize = function(inRoot, inUber) {
establishNodeReferences.call(this, inRoot);
if (inUber.shadowRootCreated) {
inUber.shadowRootCreated.call(this, inRoot);
}
bindAllCustomEvents(inRoot);
if (inRoot) {
bindModel(inRoot.childNodes);
}
};
// per-instance
var automate = function(inAttributes, inPublished, inDelegates) {
bindAttrs.call(this, inAttributes[conventions.ATTRIBUTES_ATTRIBUTE]);
// TODO(sjmiles): replace with on-* syntax
bindEvents.call(this, inAttributes.handlers);
bindProperties.call(this, inPublished);
bindDelegates.call(this, inDelegates);
};
// fireEvent impl
var fireEvent = function(inType, inDetail) {
this.asyncMethod("dispatchEvent", [
new CustomEvent(inType, {bubbles: true, detail: inDetail})
]);
};
// asyncMethod impl
var asyncMethod = function(inMethod, inArgs, inTimeout) {
return window.setTimeout(function() {
this[inMethod].apply(this, inArgs);
}.bind(this), inTimeout || 0);
};
// decorate HTMLElementElement with toolkit API
HTMLElementElement.prototype.component = function(inLifecycle) {
var attributes = this.element.attributes;
this.lifecycle({
shadowRootCreated: function(inRoot) {
initialize.call(this, inRoot, inLifecycle);
},
created: function() {
// TODO(sjmiles): notional event delegate attached to DOM tree
// to explore declarative event mapping as platform feature
this.controller = this;
// automate basic tasks, so applications never have to
automate.call(this,
attributes,
// TODO(sjmiles): remove deprecated expressions
inLifecycle[conventions.OBSERVE_DIRECTIVE]
|| inLifecycle.published,
inLifecycle[conventions.DELEGATES_DIRECTIVE]
|| inLifecycle.bindings || inLifecycle.delegates
);
takeAttributes.call(this);
if (inLifecycle.created) {
inLifecycle.created.call(this);
}
this.attrObserver = new AttrObserver(this);
}
});
var p = inLifecycle.prototype || {};
// attach some API
// TODO(sjmiles): this is probably not the best way to do this;
// probably better to insert another link in the prototype chain
p.utils = utils;
p.setPropertySilently = setPropertySilently;
p.fireEvent = fireEvent;
p.asyncMethod = asyncMethod;
// install our prototype
this.generatedConstructor.prototype = p;
};
// utility methods (utils)
// job
var job = function(inJobName, inJob, inWait) {
var name = inJobName || ("__" + Math.random());
job.stop(name);
job._jobs[name] = setTimeout(function() {
job.stop(name);
inJob();
}, inWait);
return name;
};
job.stop = function(inJobName) {
if (job._jobs[inJobName]) {
clearTimeout(job._jobs[inJobName]);
delete job._jobs[inJobName];
}
};
job._jobs = {};
// target finding
var findDistributedTarget = function(inTarget, inNodes) {
// find first ancestor of target (including itself) that
// is in inNodes, if any
var n = inTarget;
while (n && n != this) {
var i = Array.prototype.indexOf.call(inNodes, n);
if (i >= 0) {
return i;
}
n = n.parentNode;
}
};
// string interpolation
var macroize = function(inText, inMap, inPattern) {
var result = inText, pattern = inPattern || macroize.pattern;
var fn = function(macro, name) {
var v = inMap[name];
return (v === undefined || v === null) ? macro : v;
};
result = result.replace(pattern, fn);
return result;
};
// Matches macros of the form {{name}}.
macroize.pattern = /\{{([^{}]*)\}}/g;
// collect utils
var utils = {
job: job,
macroize: macroize,
findDistributedTarget: findDistributedTarget
};
// newer experimental event handler
var findController = function(inNode) {
// find the shadow root that contains inNode
var n = inNode.changeling || inNode;
while (n.parentNode && n.tagName !== 'SHADOW-ROOT') {
n = n.parentNode;
if (n.changeling) {
n = n.changeling;
}
}
return n.host.controller;
};
var _ = function(inHandlerName) {
var controller = findController(event.currentTarget);
//console.log(inHandler, owner, event);
if (controller && controller[inHandlerName]) {
controller[inHandlerName](event);
}
};
// automagic event mapping
//
// locate attributes of the form <prefix><eventName>="<methodName>" and
// map <eventName> events to method <methodName> to inNode's controller
//
var bindCustomEvent = function(inNode, inEventName, inHandler) {
var h = inNode.__athandlers = inNode.__athandlers || {};
if (!h[inEventName]) {
//console.log("bindCustomEvent:", inEventName, inHandler, inNode);
h[inEventName] = function() {
_(inHandler);
};
inNode.addEventListener(inEventName, h[inEventName]);
}
};
var bindCustomEvents = function(inNode) {
var prefix = conventions.CUSTOM_EVENT_PREFIX;
var a$ = inNode.attributes;
if (a$) {
for (var i=0, a; a=a$[i]; i++) {
if (a.name.slice(0, prefix.length) == prefix) {
bindCustomEvent(inNode, a.name.slice(prefix.length), a.value);
}
}
}
};
// TODO(sjmiles): improper tree walking (?)
var _bindAllCustomEvents = function(inNode) {
bindCustomEvents(inNode);
if (inNode.childNodes) {
for (var i=0, c; c=deref(inNode.childNodes[i]); i++) {
if (c.tagName !== 'SHADOW') {
bindAllCustomEvents(c);
}
}
}
};
var eventsObserver = function(inNode) {
// TODO(sjmiles): optimize so we only bind new nodes
new WebKitMutationObserver(_bindAllCustomEvents.bind(this, inNode))
.observe(inNode, {
childList: true,
subTree: true
});
};
var bindAllCustomEvents = function(inNode) {
if (inNode) {
_bindAllCustomEvents(inNode);
// we need this for custom events in iterated templates
eventsObserver(inNode);
}
};
})();
</script>
</element>