forked from ibm-js/delite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CustomElement.js
488 lines (440 loc) · 17 KB
/
CustomElement.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
/** @module delite/CustomElement */
define([
"dcl/advise",
"dcl/dcl",
"decor/Observable",
"decor/Destroyable",
"decor/Stateful",
"requirejs-dplugins/has",
"./on",
"./register"
], function (advise, dcl, Observable, Destroyable, Stateful, has, on, register) {
/**
* Dispatched after the CustomElement has been attached.
* This is useful to be notified when an HTMLElement has been upgraded to a
* CustomElement and attached to the DOM, in particular on browsers supporting native Custom Element.
* @example
* element.addEventListener("customelement-attached", function (evt) {
* console.log("custom element: "+evt.target.id+" has been attached");
* });
* @event module:delite/CustomElement#customelement-attached
*/
// Test if custom setters work for native properties like dir, or if they are ignored.
// They don't work on some versions of webkit (Chrome, Safari 7, iOS 7), but do work on Safari 8 and iOS 8.
// If needed, this test could probably be reduced to just use Object.defineProperty() and dcl(),
// skipping use of register().
has.add("setter-on-native-prop", function () {
var works = false,
Mixin = dcl(Stateful, { // mixin to workaround https://github.com/uhop/dcl/issues/9
getProps: function () { return {dir: true}; },
dir: "",
_setDirAttr: function () { works = true; }
}),
TestWidget = register("test-setter-on-native-prop", [HTMLElement, Mixin], {}),
tw = new TestWidget();
tw.dir = "rtl";
return works;
});
/**
* Get a property from a dot-separated string, such as "A.B.C".
*/
function getObject(name) {
try {
return name.split(".").reduce(function (context, part) {
return context[part];
}, this); // "this" is the global object (i.e. window on browsers)
} catch (e) {
// Return undefined to indicate that object doesn't exist.
}
}
var REGEXP_SHADOW_PROPS = /^_(.+)Attr$/;
/**
* Base class for all custom elements.
*
* Use this class rather that delite/Widget for non-visual custom elements.
* Custom elements can provide custom setters/getters for properties, which are called automatically
* when the value is set. For an attribute XXX, define methods _setXXXAttr() and/or _getXXXAttr().
*
* @mixin module:delite/CustomElement
* @augments module:decor/Stateful
* @augments module:decor/Destroyable
*/
var CustomElement = dcl([Stateful, Destroyable], /** @lends module:delite/CustomElement# */{
introspect: function () {
if (!has("setter-on-native-prop")) {
// Generate map from native attributes of HTMLElement to custom setters for those attributes.
// Necessary because webkit masks all custom setters for native properties on the prototype.
// For details see:
// https://bugs.webkit.org/show_bug.cgi?id=36423
// https://bugs.webkit.org/show_bug.cgi?id=49739
// https://bugs.webkit.org/show_bug.cgi?id=75297
var proto = this,
nativeProps = document.createElement(this._extends || "div"),
setterMap = this._nativePropSetterMap = {};
this._nativeAttrs = [];
do {
Object.keys(proto).forEach(function (prop) {
var lcProp = prop.toLowerCase();
if (prop in nativeProps && !setterMap[lcProp]) {
var desc = Object.getOwnPropertyDescriptor(proto, prop);
if (desc && desc.set) {
this._nativeAttrs.push(lcProp);
setterMap[lcProp] = desc.set;
}
}
}, this);
proto = Object.getPrototypeOf(proto);
} while (proto && proto.constructor !== this._baseElement);
}
},
getProps: function () {
// Override _Stateful.getProps() to ignore properties from the HTML*Element superclasses, like "style".
// You would need to explicitly declare style: "" in your widget to get it here.
// Intentionally skips methods, because it seems wasteful to have a custom
// setter for every method; not sure that would work anyway.
//
// Also sets up this._propCaseMap, a mapping from lowercase property name to actual name,
// ex: iconclass --> iconClass, which does include the methods, but again doesn't
// include props like "style" that are merely inherited from HTMLElement.
var hash = {}, proto = this,
pcm = this._propCaseMap = {};
do {
Object.keys(proto).forEach(function (prop) {
if (!REGEXP_SHADOW_PROPS.test(prop)) {
if (typeof proto[prop] !== "function") {
hash[prop] = true;
}
pcm[prop.toLowerCase()] = prop;
}
});
proto = Object.getPrototypeOf(proto);
} while (proto && proto.constructor !== this._baseElement);
return hash;
},
/**
* This method will detect and process any properties that the application has set, but the custom setter
* didn't run because `has("setter-on-native-prop") === false`.
* Used during initialization and also by `deliver()`.
* @private
*/
_processNativeProps: function () {
if (!has("setter-on-native-prop")) {
this._nativeAttrs.forEach(function (attrName) {
if (this.hasAttribute(attrName)) { // value was specified
var value = this.getAttribute(attrName);
this.removeAttribute(attrName);
if (value !== null) {
this._nativePropSetterMap[attrName].call(this, value); // call custom setter
}
}
}, this);
}
},
/**
* Set to true when `createdCallback()` has completed.
* @member {boolean}
* @protected
*/
created: false,
/**
* Called when the custom element is created, or when `register.parse()` parses a custom tag.
*
* This method is automatically chained, so subclasses generally do not need to use `dcl.superCall()`,
* `dcl.advise()`, etc.
* @method
* @protected
*/
createdCallback: dcl.advise({
before: function () {
// Mark this object as observable with Object.observe() shim
if (!this._observable) {
Observable.call(this);
}
// Get parameters that were specified declaratively on the widget DOMNode.
this._parsedAttributes = this._mapAttributes();
},
after: function () {
this.created = true;
// Now that creation has finished, apply parameters that were specified declaratively.
// This is consistent with the timing that parameters are applied for programmatic creation.
this._parsedAttributes.forEach(function (pa) {
if (pa.event) {
this.on(pa.event, pa.callback);
} else {
this[pa.prop] = pa.value;
}
}, this);
if (!has("setter-on-native-prop")) {
// Call custom setters for initial values of attributes with shadow properties (dir, tabIndex, etc)
this._processNativeProps();
// Begin watching for changes to those DOM attributes.
// Note that (at least on Chrome) I could use attributeChangedCallback() instead, which is
// synchronous, so Widget#deliver() will work as expected, but OTOH gets lots of notifications
// that I don't care about.
// If Polymer is loaded, use MutationObserver rather than WebKitMutationObserver
// to avoid error about "referencing a Node in a context where it does not exist".
/* global WebKitMutationObserver */
var MO = window.MutationObserver || WebKitMutationObserver; // for jshint
var observer = new MO(function (records) {
records.forEach(function (mr) {
var attrName = mr.attributeName,
setter = this._nativePropSetterMap[attrName],
newValue = this.getAttribute(attrName);
if (newValue !== null) {
this.removeAttribute(attrName);
setter.call(this, newValue);
}
}, this);
}.bind(this));
observer.observe(this, {
subtree: false,
attributeFilter: this._nativeAttrs,
attributes: true
});
}
}
}),
/**
* Set to true when `attachedCallback()` has completed, and false when `detachedCallback()` called.
* @member {boolean}
* @protected
*/
attached: false,
/**
* Called automatically when the element is added to the document, after `createdCallback()` completes.
* This method is automatically chained, so subclasses generally do not need to use `dcl.superCall()`,
* `dcl.advise()`, etc.
* @method
* @fires module:delite/CustomElement#customelement-attached
*/
attachedCallback: dcl.after(function () {
// Call computeProperties() and refreshRendering() for declaratively set properties.
// Do this in attachedCallback() rather than createdCallback() to avoid calling refreshRendering() etc.
// prematurely in the programmatic case (i.e. calling it before user parameters have been applied).
this.deliver();
this.attached = true;
this.emit("customelement-attached", {
bubbles: false,
cancelable: false
});
}),
/**
* Called when the element is removed the document.
* This method is automatically chained, so subclasses generally do not need to use `dcl.superCall()`,
* `dcl.advise()`, etc.
*/
detachedCallback: function () {
this.attached = false;
},
/**
* Returns value for widget property based on attribute value in markup.
* @param {string} name - Name of widget property.
* @param {string} value - Value of attribute in markup.
* @private
*/
_parsePrototypeAttr: function (name, value) {
// inner function useful to reduce cyclomatic complexity when using jshint
function stringToObject(value) {
var obj;
try {
// TODO: remove this code if it isn't being used, so we don't scare people that are afraid of eval.
/* jshint evil:true */
// This will only be executed when complex parameters are used in markup
// <my-tag constraints="max: 3, min: 2"></my-tag>
// This can be avoided by using such complex parameters only programmatically or by not using
// them at all.
// This is harmless if you make sure the JavaScript code that is passed to the attribute
// is harmless.
obj = eval("(" + (value[0] === "{" ? "" : "{") + value + (value[0] === "{" ? "" : "}") + ")");
}
catch (e) {
throw new SyntaxError("Error in attribute conversion to object: " + e.message +
"\nAttribute Value: '" + value + "'");
}
return obj;
}
switch (typeof this[name]) {
case "string":
return value;
case "number":
return value - 0;
case "boolean":
return value !== "false";
case "object":
// Try to interpret value as global variable, ex: store="myStore", array of strings
// ex: "1, 2, 3", or expression, ex: constraints="min: 10, max: 100"
return getObject(value) ||
(this[name] instanceof Array ? (value ? value.split(/\s+/) : []) : stringToObject(value));
case "function":
return this.parseFunctionAttribute(value, []);
}
},
/**
* Helper to parse function attribute in markup. Unlike `_parsePrototypeAttr()`, does not require a
* corresponding widget property. Functions can be specified as global variables or as inline javascript:
*
* ```html
* <my-widget funcAttr="globalFunction" on-click="console.log(event.pageX);">
* ```
*
* @param {string} value - Value of the attribute.
* @param {string[]} params - When generating a function from inline javascript, give it these parameter names.
* @protected
*/
parseFunctionAttribute: function (value, params) {
/* jshint evil:true */
// new Function() will only be executed if you have properties that are of function type in your widget
// and that you use them in your tag attributes as follows:
// <my-tag whatever="console.log(param)"></my-tag>
// This can be avoided by setting the function programmatically or by not setting it at all.
// This is harmless if you make sure the JavaScript code that is passed to the attribute is harmless.
// Use Function.bind to get a partial on Function constructor (trick to call it with an array
// of args instead list of args).
return getObject(value) ||
new (Function.bind.apply(Function, [undefined].concat(params).concat([value])))();
},
/**
* Helper for parsing declarative widgets. Interpret a given attribute specified in markup, returning either:
*
* - `undefined`: ignore
* - `{prop: prop, value: value}`: set `this[prop] = value`
* - `{event: event, callback: callback}`: call `this.on(event, callback)`
*
* @param {string} name - Attribute name.
* @param {string} value - Attribute value.
* @protected
*/
parseAttribute: function (name, value) {
var pcm = this._propCaseMap;
if (name in pcm) {
name = pcm[name]; // convert to correct case for widget
return {
prop: name,
value: this._parsePrototypeAttr(name, value)
};
} else if (/^on-/.test(name)) {
return {
event: name.substring(3),
callback: this.parseFunctionAttribute(value, ["event"])
};
}
},
/**
* Parse declaratively specified attributes for widget properties and connects.
* @returns {Array} Info about the attributes and their values as returned by `parseAttribute()`.
* @private
*/
_mapAttributes: function () {
var attr,
idx = 0,
parsedAttrs = [],
attrsToRemove = [];
while ((attr = this.attributes[idx++])) {
var name = attr.name.toLowerCase(); // note: will be lower case already except for IE9
var parsedAttr = this.parseAttribute(name, attr.value);
if (parsedAttr) {
parsedAttrs.push(parsedAttr);
attrsToRemove.push(attr.name);
}
}
// Remove attributes that were processed, but do it in a separate loop so we don't modify this.attributes
// while we are looping through it. (See CustomElement-attr.html test failure on IE10.)
attrsToRemove.forEach(this.removeAttribute, this);
return parsedAttrs;
},
/**
* Release resources used by this custom element and its descendants.
* After calling this method, the element can no longer be used,
* and should be removed from the document.
*/
destroy: function () {
// Destroy descendants
this.findCustomElements().forEach(function (w) {
if (w.destroy) {
w.destroy();
}
});
if (this.parentNode) {
this.parentNode.removeChild(this);
this.detachedCallback();
}
},
/**
* Emits a synthetic event of specified type, based on eventObj.
* @param {string} type - Name of event.
* @param {Object} [eventObj] - Properties to mix in to emitted event. Can also contain
* `bubbles` and `cancelable` properties to control how the event is emitted.
* @returns {boolean} True if the event was *not* canceled, false if it was canceled.
* @example
* myWidget.emit("query-success", {});
* @protected
*/
emit: function (type, eventObj) {
eventObj = eventObj || {};
var bubbles = "bubbles" in eventObj ? eventObj.bubbles : true;
var cancelable = "cancelable" in eventObj ? eventObj.cancelable : true;
// Note: can't use jQuery.trigger() because it doesn't work with addEventListener(),
// see http://bugs.jquery.com/ticket/11047
var nativeEvent = this.ownerDocument.createEvent("HTMLEvents");
nativeEvent.initEvent(type, bubbles, cancelable);
for (var i in eventObj) {
if (!(i in nativeEvent)) {
nativeEvent[i] = eventObj[i];
}
}
return this.dispatchEvent(nativeEvent);
},
/**
* Call specified function when event occurs.
*
* Note that the function is not run in any particular scope, so if (for example) you want it to run
* in the element's scope you must do `myCustomElement.on("click", myCustomElement.func.bind(myCustomElement))`.
*
* Note that `delite/Widget` overrides `on()` so that `on("focus", ...)` and `on("blur", ...) will trigger the
* listener when focus moves into or out of the widget, rather than just when the widget's root node is
* focused/blurred. In other words, the listener is called when the widget is conceptually focused or blurred.
*
* @param {string} type - Name of event (ex: "click").
* @param {Function} func - Callback function.
* @param {Element} [node] - Element to attach handler to, defaults to `this`.
* @returns {Object} Handle with `remove()` method to cancel the event.
*/
on: function (type, func, node) {
return on(node || this, type, func);
},
// Override Stateful#getPropsToObserve() because the way to get the list of properties to watch is different
// than for a plain Stateful. Especially since IE doesn't support prototype swizzling.
getPropsToObserve: function () {
return this._ctor._propsToObserve;
},
// Before deliver() runs, process any native properties (tabIndex, dir) etc. that may have been
// set without the custom setter getting called.
deliver: dcl.before(function () {
this._processNativeProps();
}),
/**
* Search subtree under root returning custom elements found.
* @param {Element} [root] - Node to search under.
*/
findCustomElements: function (root) {
var outAry = [];
function getChildrenHelper(root) {
for (var node = root.firstChild; node; node = node.nextSibling) {
if (node.nodeType === 1 && node.createdCallback) {
outAry.push(node);
} else {
getChildrenHelper(node);
}
}
}
getChildrenHelper(root || this);
return outAry;
}
});
// Setup automatic chaining for lifecycle methods.
// destroy() is chained in Destroyable.js.
dcl.chainAfter(CustomElement, "createdCallback");
dcl.chainAfter(CustomElement, "attachedCallback");
dcl.chainBefore(CustomElement, "detachedCallback");
return CustomElement;
});