-
Notifications
You must be signed in to change notification settings - Fork 2k
/
template-stamp.js
500 lines (475 loc) · 19.4 KB
/
template-stamp.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
/**
@license
Copyright (c) 2017 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
*/
import '../utils/boot.js';
import { dedupingMixin } from '../utils/mixin.js';
const walker = document.createTreeWalker(document, NodeFilter.SHOW_ALL,
null, false);
// 1.x backwards-compatible auto-wrapper for template type extensions
// This is a clear layering violation and gives favored-nation status to
// dom-if and dom-repeat templates. This is a conceit we're choosing to keep
// a.) to ease 1.x backwards-compatibility due to loss of `is`, and
// b.) to maintain if/repeat capability in parser-constrained elements
// (e.g. table, select) in lieu of native CE type extensions without
// massive new invention in this space (e.g. directive system)
const templateExtensions = {
'dom-if': true,
'dom-repeat': true
};
function wrapTemplateExtension(node) {
let is = node.getAttribute('is');
if (is && templateExtensions[is]) {
let t = node;
t.removeAttribute('is');
node = t.ownerDocument.createElement(is);
t.parentNode.replaceChild(node, t);
node.appendChild(t);
while(t.attributes.length) {
node.setAttribute(t.attributes[0].name, t.attributes[0].value);
t.removeAttribute(t.attributes[0].name);
}
}
return node;
}
function findTemplateNode(root, nodeInfo) {
// recursively ascend tree until we hit root
let parent = nodeInfo.parentInfo && findTemplateNode(root, nodeInfo.parentInfo);
// unwind the stack, returning the indexed node at each level
if (parent) {
// note: marginally faster than indexing via childNodes
// (http://jsperf.com/childnodes-lookup)
walker.currentNode = parent;
for (let n=walker.firstChild(), i=0; n; n=walker.nextSibling()) {
if (nodeInfo.parentIndex === i++) {
return n;
}
}
} else {
return root;
}
}
// construct `$` map (from id annotations)
function applyIdToMap(inst, map, node, nodeInfo) {
if (nodeInfo.id) {
map[nodeInfo.id] = node;
}
}
// install event listeners (from event annotations)
function applyEventListener(inst, node, nodeInfo) {
if (nodeInfo.events && nodeInfo.events.length) {
for (let j=0, e$=nodeInfo.events, e; (j<e$.length) && (e=e$[j]); j++) {
inst._addMethodEventListenerToNode(node, e.name, e.value, inst);
}
}
}
// push configuration references at configure time
function applyTemplateContent(inst, node, nodeInfo) {
if (nodeInfo.templateInfo) {
node._templateInfo = nodeInfo.templateInfo;
}
}
function createNodeEventHandler(context, eventName, methodName) {
// Instances can optionally have a _methodHost which allows redirecting where
// to find methods. Currently used by `templatize`.
context = context._methodHost || context;
let handler = function(e) {
if (context[methodName]) {
context[methodName](e, e.detail);
} else {
console.warn('listener method `' + methodName + '` not defined');
}
};
return handler;
}
/**
* Element mixin that provides basic template parsing and stamping, including
* the following template-related features for stamped templates:
*
* - Declarative event listeners (`on-eventname="listener"`)
* - Map of node id's to stamped node instances (`this.$.id`)
* - Nested template content caching/removal and re-installation (performance
* optimization)
*
* @mixinFunction
* @polymer
* @summary Element class mixin that provides basic template parsing and stamping
*/
export const TemplateStamp = dedupingMixin(
/**
* @template T
* @param {function(new:T)} superClass Class to apply mixin to.
* @return {function(new:T)} superClass with mixin applied.
*/
(superClass) => {
/**
* @polymer
* @mixinClass
* @implements {Polymer_TemplateStamp}
*/
class TemplateStamp extends superClass {
/**
* Scans a template to produce template metadata.
*
* Template-specific metadata are stored in the object returned, and node-
* specific metadata are stored in objects in its flattened `nodeInfoList`
* array. Only nodes in the template that were parsed as nodes of
* interest contain an object in `nodeInfoList`. Each `nodeInfo` object
* contains an `index` (`childNodes` index in parent) and optionally
* `parent`, which points to node info of its parent (including its index).
*
* The template metadata object returned from this method has the following
* structure (many fields optional):
*
* ```js
* {
* // Flattened list of node metadata (for nodes that generated metadata)
* nodeInfoList: [
* {
* // `id` attribute for any nodes with id's for generating `$` map
* id: {string},
* // `on-event="handler"` metadata
* events: [
* {
* name: {string}, // event name
* value: {string}, // handler method name
* }, ...
* ],
* // Notes when the template contained a `<slot>` for shady DOM
* // optimization purposes
* hasInsertionPoint: {boolean},
* // For nested `<template>`` nodes, nested template metadata
* templateInfo: {object}, // nested template metadata
* // Metadata to allow efficient retrieval of instanced node
* // corresponding to this metadata
* parentInfo: {number}, // reference to parent nodeInfo>
* parentIndex: {number}, // index in parent's `childNodes` collection
* infoIndex: {number}, // index of this `nodeInfo` in `templateInfo.nodeInfoList`
* },
* ...
* ],
* // When true, the template had the `strip-whitespace` attribute
* // or was nested in a template with that setting
* stripWhitespace: {boolean},
* // For nested templates, nested template content is moved into
* // a document fragment stored here; this is an optimization to
* // avoid the cost of nested template cloning
* content: {DocumentFragment}
* }
* ```
*
* This method kicks off a recursive treewalk as follows:
*
* ```
* _parseTemplate <---------------------+
* _parseTemplateContent |
* _parseTemplateNode <------------|--+
* _parseTemplateNestedTemplate --+ |
* _parseTemplateChildNodes ---------+
* _parseTemplateNodeAttributes
* _parseTemplateNodeAttribute
*
* ```
*
* These methods may be overridden to add custom metadata about templates
* to either `templateInfo` or `nodeInfo`.
*
* Note that this method may be destructive to the template, in that
* e.g. event annotations may be removed after being noted in the
* template metadata.
*
* @param {!HTMLTemplateElement} template Template to parse
* @param {TemplateInfo=} outerTemplateInfo Template metadata from the outer
* template, for parsing nested templates
* @return {!TemplateInfo} Parsed template metadata
*/
static _parseTemplate(template, outerTemplateInfo) {
// since a template may be re-used, memo-ize metadata
if (!template._templateInfo) {
let templateInfo = template._templateInfo = {};
templateInfo.nodeInfoList = [];
templateInfo.stripWhiteSpace =
(outerTemplateInfo && outerTemplateInfo.stripWhiteSpace) ||
template.hasAttribute('strip-whitespace');
this._parseTemplateContent(template, templateInfo, {parent: null});
}
return template._templateInfo;
}
static _parseTemplateContent(template, templateInfo, nodeInfo) {
return this._parseTemplateNode(template.content, templateInfo, nodeInfo);
}
/**
* Parses template node and adds template and node metadata based on
* the current node, and its `childNodes` and `attributes`.
*
* This method may be overridden to add custom node or template specific
* metadata based on this node.
*
* @param {Node} node Node to parse
* @param {!TemplateInfo} templateInfo Template metadata for current template
* @param {!NodeInfo} nodeInfo Node metadata for current template.
* @return {boolean} `true` if the visited node added node-specific
* metadata to `nodeInfo`
*/
static _parseTemplateNode(node, templateInfo, nodeInfo) {
let noted;
let element = /** @type {Element} */(node);
if (element.localName == 'template' && !element.hasAttribute('preserve-content')) {
noted = this._parseTemplateNestedTemplate(element, templateInfo, nodeInfo) || noted;
} else if (element.localName === 'slot') {
// For ShadyDom optimization, indicating there is an insertion point
templateInfo.hasInsertionPoint = true;
}
walker.currentNode = element;
if (walker.firstChild()) {
noted = this._parseTemplateChildNodes(element, templateInfo, nodeInfo) || noted;
}
if (element.hasAttributes && element.hasAttributes()) {
noted = this._parseTemplateNodeAttributes(element, templateInfo, nodeInfo) || noted;
}
return noted;
}
/**
* Parses template child nodes for the given root node.
*
* This method also wraps whitelisted legacy template extensions
* (`is="dom-if"` and `is="dom-repeat"`) with their equivalent element
* wrappers, collapses text nodes, and strips whitespace from the template
* if the `templateInfo.stripWhitespace` setting was provided.
*
* @param {Node} root Root node whose `childNodes` will be parsed
* @param {!TemplateInfo} templateInfo Template metadata for current template
* @param {!NodeInfo} nodeInfo Node metadata for current template.
* @return {void}
*/
static _parseTemplateChildNodes(root, templateInfo, nodeInfo) {
if (root.localName === 'script' || root.localName === 'style') {
return;
}
walker.currentNode = root;
for (let node=walker.firstChild(), parentIndex=0, next; node; node=next) {
// Wrap templates
if (node.localName == 'template') {
node = wrapTemplateExtension(node);
}
// collapse adjacent textNodes: fixes an IE issue that can cause
// text nodes to be inexplicably split =(
// note that root.normalize() should work but does not so we do this
// manually.
walker.currentNode = node;
next = walker.nextSibling();
if (node.nodeType === Node.TEXT_NODE) {
let /** Node */ n = next;
while (n && (n.nodeType === Node.TEXT_NODE)) {
node.textContent += n.textContent;
next = walker.nextSibling();
root.removeChild(n);
n = next;
}
// optionally strip whitespace
if (templateInfo.stripWhiteSpace && !node.textContent.trim()) {
root.removeChild(node);
continue;
}
}
let childInfo = { parentIndex, parentInfo: nodeInfo };
if (this._parseTemplateNode(node, templateInfo, childInfo)) {
childInfo.infoIndex = templateInfo.nodeInfoList.push(/** @type {!NodeInfo} */(childInfo)) - 1;
}
// Increment if not removed
walker.currentNode = node;
if (walker.parentNode()) {
parentIndex++;
}
}
}
/**
* Parses template content for the given nested `<template>`.
*
* Nested template info is stored as `templateInfo` in the current node's
* `nodeInfo`. `template.content` is removed and stored in `templateInfo`.
* It will then be the responsibility of the host to set it back to the
* template and for users stamping nested templates to use the
* `_contentForTemplate` method to retrieve the content for this template
* (an optimization to avoid the cost of cloning nested template content).
*
* @param {HTMLTemplateElement} node Node to parse (a <template>)
* @param {TemplateInfo} outerTemplateInfo Template metadata for current template
* that includes the template `node`
* @param {!NodeInfo} nodeInfo Node metadata for current template.
* @return {boolean} `true` if the visited node added node-specific
* metadata to `nodeInfo`
*/
static _parseTemplateNestedTemplate(node, outerTemplateInfo, nodeInfo) {
let templateInfo = this._parseTemplate(node, outerTemplateInfo);
let content = templateInfo.content =
node.content.ownerDocument.createDocumentFragment();
content.appendChild(node.content);
nodeInfo.templateInfo = templateInfo;
return true;
}
/**
* Parses template node attributes and adds node metadata to `nodeInfo`
* for nodes of interest.
*
* @param {Element} node Node to parse
* @param {TemplateInfo} templateInfo Template metadata for current template
* @param {NodeInfo} nodeInfo Node metadata for current template.
* @return {boolean} `true` if the visited node added node-specific
* metadata to `nodeInfo`
*/
static _parseTemplateNodeAttributes(node, templateInfo, nodeInfo) {
// Make copy of original attribute list, since the order may change
// as attributes are added and removed
let noted = false;
let attrs = Array.from(node.attributes);
for (let i=attrs.length-1, a; (a=attrs[i]); i--) {
noted = this._parseTemplateNodeAttribute(node, templateInfo, nodeInfo, a.name, a.value) || noted;
}
return noted;
}
/**
* Parses a single template node attribute and adds node metadata to
* `nodeInfo` for attributes of interest.
*
* This implementation adds metadata for `on-event="handler"` attributes
* and `id` attributes.
*
* @param {Element} node Node to parse
* @param {!TemplateInfo} templateInfo Template metadata for current template
* @param {!NodeInfo} nodeInfo Node metadata for current template.
* @param {string} name Attribute name
* @param {string} value Attribute value
* @return {boolean} `true` if the visited node added node-specific
* metadata to `nodeInfo`
*/
static _parseTemplateNodeAttribute(node, templateInfo, nodeInfo, name, value) {
// events (on-*)
if (name.slice(0, 3) === 'on-') {
node.removeAttribute(name);
nodeInfo.events = nodeInfo.events || [];
nodeInfo.events.push({
name: name.slice(3),
value
});
return true;
}
// static id
else if (name === 'id') {
nodeInfo.id = value;
return true;
}
return false;
}
/**
* Returns the `content` document fragment for a given template.
*
* For nested templates, Polymer performs an optimization to cache nested
* template content to avoid the cost of cloning deeply nested templates.
* This method retrieves the cached content for a given template.
*
* @param {HTMLTemplateElement} template Template to retrieve `content` for
* @return {DocumentFragment} Content fragment
*/
static _contentForTemplate(template) {
let templateInfo = /** @type {HTMLTemplateElementWithInfo} */ (template)._templateInfo;
return (templateInfo && templateInfo.content) || template.content;
}
/**
* Clones the provided template content and returns a document fragment
* containing the cloned dom.
*
* The template is parsed (once and memoized) using this library's
* template parsing features, and provides the following value-added
* features:
* * Adds declarative event listeners for `on-event="handler"` attributes
* * Generates an "id map" for all nodes with id's under `$` on returned
* document fragment
* * Passes template info including `content` back to templates as
* `_templateInfo` (a performance optimization to avoid deep template
* cloning)
*
* Note that the memoized template parsing process is destructive to the
* template: attributes for bindings and declarative event listeners are
* removed after being noted in notes, and any nested `<template>.content`
* is removed and stored in notes as well.
*
* @param {!HTMLTemplateElement} template Template to stamp
* @return {!StampedTemplate} Cloned template content
* @override
*/
_stampTemplate(template) {
// Polyfill support: bootstrap the template if it has not already been
if (template && !template.content &&
window.HTMLTemplateElement && HTMLTemplateElement.decorate) {
HTMLTemplateElement.decorate(template);
}
let templateInfo = this.constructor._parseTemplate(template);
let nodeInfo = templateInfo.nodeInfoList;
let content = templateInfo.content || template.content;
let dom = /** @type {DocumentFragment} */ (document.importNode(content, true));
// NOTE: ShadyDom optimization indicating there is an insertion point
dom.__noInsertionPoint = !templateInfo.hasInsertionPoint;
let nodes = dom.nodeList = new Array(nodeInfo.length);
dom.$ = {};
for (let i=0, l=nodeInfo.length, info; (i<l) && (info=nodeInfo[i]); i++) {
let node = nodes[i] = findTemplateNode(dom, info);
applyIdToMap(this, dom.$, node, info);
applyTemplateContent(this, node, info);
applyEventListener(this, node, info);
}
dom = /** @type {!StampedTemplate} */(dom); // eslint-disable-line no-self-assign
return dom;
}
/**
* Adds an event listener by method name for the event provided.
*
* This method generates a handler function that looks up the method
* name at handling time.
*
* @param {!EventTarget} node Node to add listener on
* @param {string} eventName Name of event
* @param {string} methodName Name of method
* @param {*=} context Context the method will be called on (defaults
* to `node`)
* @return {Function} Generated handler function
* @override
*/
_addMethodEventListenerToNode(node, eventName, methodName, context) {
context = context || node;
let handler = createNodeEventHandler(context, eventName, methodName);
this._addEventListenerToNode(node, eventName, handler);
return handler;
}
/**
* Override point for adding custom or simulated event handling.
*
* @param {!EventTarget} node Node to add event listener to
* @param {string} eventName Name of event
* @param {function(!Event):void} handler Listener function to add
* @return {void}
* @override
*/
_addEventListenerToNode(node, eventName, handler) {
node.addEventListener(eventName, handler);
}
/**
* Override point for adding custom or simulated event handling.
*
* @param {!EventTarget} node Node to remove event listener from
* @param {string} eventName Name of event
* @param {function(!Event):void} handler Listener function to remove
* @return {void}
* @override
*/
_removeEventListenerFromNode(node, eventName, handler) {
node.removeEventListener(eventName, handler);
}
}
return TemplateStamp;
});