-
Notifications
You must be signed in to change notification settings - Fork 2k
/
base.js
415 lines (387 loc) · 13.6 KB
/
base.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
/*
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function(scope) {
/**
* Common prototype for all Polymer Elements.
*
* @class polymer-base
* @homepage polymer.github.io
*/
var base = {
/**
* Tags this object as the canonical Base prototype.
*
* @property PolymerBase
* @type boolean
* @default true
*/
PolymerBase: true,
/**
* Debounce signals.
*
* Call `job` to defer a named signal, and all subsequent matching signals,
* until a wait time has elapsed with no new signal.
*
* debouncedClickAction: function(e) {
* // processClick only when it's been 100ms since the last click
* this.job('click', function() {
* this.processClick;
* }, 100);
* }
*
* @method job
* @param String {String} job A string identifier for the job to debounce.
* @param Function {Function} callback A function that is called (with `this` context) when the wait time elapses.
* @param Number {Number} wait Time in milliseconds (ms) after the last signal that must elapse before invoking `callback`
* @type Handle
*/
job: function(job, callback, wait) {
if (typeof job === 'string') {
var n = '___' + job;
this[n] = Polymer.job.call(this, this[n], callback, wait);
} else {
// TODO(sjmiles): suggest we deprecate this call signature
return Polymer.job.call(this, job, callback, wait);
}
},
/**
* Invoke a superclass method.
*
* Use `super()` to invoke the most recently overridden call to the
* currently executing function.
*
* To pass arguments through, use the literal `arguments` as the parameter
* to `super()`.
*
* nextPageAction: function(e) {
* // invoke the superclass version of `nextPageAction`
* this.super(arguments);
* }
*
* To pass custom arguments, arrange them in an array.
*
* appendSerialNo: function(value, serial) {
* // prefix the superclass serial number with our lot # before
* // invoking the superlcass
* return this.super([value, this.lotNo + serial])
* }
*
* @method super
* @type Any
* @param {args) An array of arguments to use when calling the superclass method, or null.
*/
super: Polymer.super,
/**
* Lifecycle method called when the element is instantiated.
*
* Override `created` to perform custom create-time tasks. No need to call
* super-class `created` unless you are extending another Polymer element.
* Created is called before the element creates `shadowRoot` or prepares
* data-observation.
*
* @method created
* @type void
*/
created: function() {
},
/**
* Lifecycle method called when the element has populated it's `shadowRoot`,
* prepared data-observation, and made itself ready for API interaction.
*
* @method ready
* @type void
*/
ready: function() {
},
/**
* Low-level lifecycle method called as part of standard Custom Elements
* operation. Polymer implements this method to provide basic default
* functionality. For custom create-time tasks, implement `created`
* instead, which is called immediately after `createdCallback`.
*
* @method createdCallback
*/
createdCallback: function() {
if (this.templateInstance && this.templateInstance.model) {
console.warn('Attributes on ' + this.localName + ' were data bound ' +
'prior to Polymer upgrading the element. This may result in ' +
'incorrect binding types.');
}
this.created();
this.prepareElement();
if (!this.ownerDocument.isStagingDocument) {
this.makeElementReady();
}
},
// system entry point, do not override
prepareElement: function() {
if (this._elementPrepared) {
console.warn('Element already prepared', this.localName);
return;
}
this._elementPrepared = true;
// storage for shadowRoots info
this.shadowRoots = {};
// install property observers
this.createPropertyObserver();
this.openPropertyObserver();
// install boilerplate attributes
this.copyInstanceAttributes();
// process input attributes
this.takeAttributes();
// add event listeners
this.addHostListeners();
},
// system entry point, do not override
makeElementReady: function() {
if (this._readied) {
return;
}
this._readied = true;
this.createComputedProperties();
this.parseDeclarations(this.__proto__);
// NOTE: Support use of the `unresolved` attribute to help polyfill
// custom elements' `:unresolved` feature.
this.removeAttribute('unresolved');
// user entry point
this.ready();
},
/**
* Low-level lifecycle method called as part of standard Custom Elements
* operation. Polymer implements this method to provide basic default
* functionality. For custom tasks in your element, implement `attributeChanged`
* instead, which is called immediately after `attributeChangedCallback`.
*
* @method attributeChangedCallback
*/
attributeChangedCallback: function(name, oldValue) {
// TODO(sjmiles): adhoc filter
if (name !== 'class' && name !== 'style') {
this.attributeToProperty(name, this.getAttribute(name));
}
if (this.attributeChanged) {
this.attributeChanged.apply(this, arguments);
}
},
/**
* Low-level lifecycle method called as part of standard Custom Elements
* operation. Polymer implements this method to provide basic default
* functionality. For custom create-time tasks, implement `attached`
* instead, which is called immediately after `attachedCallback`.
*
* @method attachedCallback
*/
attachedCallback: function() {
// when the element is attached, prevent it from unbinding.
this.cancelUnbindAll();
// invoke user action
if (this.attached) {
this.attached();
}
if (!this.hasBeenAttached) {
this.hasBeenAttached = true;
if (this.domReady) {
this.async('domReady');
}
}
},
/**
* Implement to access custom elements in dom descendants, ancestors,
* or siblings. Because custom elements upgrade in document order,
* elements accessed in `ready` or `attached` may not be upgraded. When
* `domReady` is called, all registered custom elements are guaranteed
* to have been upgraded.
*
* @method domReady
*/
/**
* Low-level lifecycle method called as part of standard Custom Elements
* operation. Polymer implements this method to provide basic default
* functionality. For custom create-time tasks, implement `detached`
* instead, which is called immediately after `detachedCallback`.
*
* @method detachedCallback
*/
detachedCallback: function() {
if (!this.preventDispose) {
this.asyncUnbindAll();
}
// invoke user action
if (this.detached) {
this.detached();
}
// TODO(sorvell): bc
if (this.leftView) {
this.leftView();
}
},
/**
* Walks the prototype-chain of this element and allows specific
* classes a chance to process static declarations.
*
* In particular, each polymer-element has it's own `template`.
* `parseDeclarations` is used to accumulate all element `template`s
* from an inheritance chain.
*
* `parseDeclaration` static methods implemented in the chain are called
* recursively, oldest first, with the `<polymer-element>` associated
* with the current prototype passed as an argument.
*
* An element may override this method to customize shadow-root generation.
*
* @method parseDeclarations
*/
parseDeclarations: function(p) {
if (p && p.element) {
this.parseDeclarations(p.__proto__);
p.parseDeclaration.call(this, p.element);
}
},
/**
* Perform init-time actions based on static information in the
* `<polymer-element>` instance argument.
*
* For example, the standard implementation locates the template associated
* with the given `<polymer-element>` and stamps it into a shadow-root to
* implement shadow inheritance.
*
* An element may override this method for custom behavior.
*
* @method parseDeclaration
*/
parseDeclaration: function(elementElement) {
var template = this.fetchTemplate(elementElement);
if (template) {
var root = this.shadowFromTemplate(template);
this.shadowRoots[elementElement.name] = root;
}
},
/**
* Given a `<polymer-element>`, find an associated template (if any) to be
* used for shadow-root generation.
*
* An element may override this method for custom behavior.
*
* @method fetchTemplate
*/
fetchTemplate: function(elementElement) {
return elementElement.querySelector('template');
},
/**
* Create a shadow-root in this host and stamp `template` as it's
* content.
*
* An element may override this method for custom behavior.
*
* @method shadowFromTemplate
*/
shadowFromTemplate: function(template) {
if (template) {
// make a shadow root
var root = this.createShadowRoot();
// stamp template
// which includes parsing and applying MDV bindings before being
// inserted (to avoid {{}} in attribute values)
// e.g. to prevent <img src="images/{{icon}}"> from generating a 404.
var dom = this.instanceTemplate(template);
// append to shadow dom
root.appendChild(dom);
// perform post-construction initialization tasks on shadow root
this.shadowRootReady(root, template);
// return the created shadow root
return root;
}
},
// utility function that stamps a <template> into light-dom
lightFromTemplate: function(template, refNode) {
if (template) {
// TODO(sorvell): mark this element as an eventController so that
// event listeners on bound nodes inside it will be called on it.
// Note, the expectation here is that events on all descendants
// should be handled by this element.
this.eventController = this;
// stamp template
// which includes parsing and applying MDV bindings before being
// inserted (to avoid {{}} in attribute values)
// e.g. to prevent <img src="images/{{icon}}"> from generating a 404.
var dom = this.instanceTemplate(template);
// append to shadow dom
if (refNode) {
this.insertBefore(dom, refNode);
} else {
this.appendChild(dom);
}
// perform post-construction initialization tasks on ahem, light root
this.shadowRootReady(this);
// return the created shadow root
return dom;
}
},
shadowRootReady: function(root) {
// locate nodes with id and store references to them in this.$ hash
this.marshalNodeReferences(root);
},
// locate nodes with id and store references to them in this.$ hash
marshalNodeReferences: function(root) {
// establish $ instance variable
var $ = this.$ = this.$ || {};
// populate $ from nodes with ID from the LOCAL tree
if (root) {
var n$ = root.querySelectorAll("[id]");
for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) {
$[n.id] = n;
};
}
},
/**
* Register a one-time callback when a child-list or sub-tree mutation
* occurs on node.
*
* For persistent callbacks, call onMutation from your listener.
*
* @method onMutation
* @param Node {Node} node Node to watch for mutations.
* @param Function {Function} listener Function to call on mutation. The function is invoked as `listener.call(this, observer, mutations);` where `observer` is the MutationObserver that triggered the notification, and `mutations` is the native mutation list.
*/
onMutation: function(node, listener) {
var observer = new MutationObserver(function(mutations) {
listener.call(this, observer, mutations);
observer.disconnect();
}.bind(this));
observer.observe(node, {childList: true, subtree: true});
}
};
/**
* @class Polymer
*/
/**
* Returns true if the object includes <a href="#polymer-base">polymer-base</a> in it's prototype chain.
*
* @method isBase
* @param Object {Object} object Object to test.
* @type Boolean
*/
function isBase(object) {
return object.hasOwnProperty('PolymerBase')
}
// name a base constructor for dev tools
/**
* The Polymer base-class constructor.
*
* @property Base
* @type Function
*/
function PolymerBase() {};
PolymerBase.prototype = base;
base.constructor = PolymerBase;
// exports
scope.Base = PolymerBase;
scope.isBase = isBase;
scope.api.instance.base = base;
})(Polymer);