forked from webcomponents/template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.js
330 lines (296 loc) · 12 KB
/
template.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
/**
* @license
* Copyright (c) 2016 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
*/
// minimal template polyfill
(function() {
var needsTemplate = (typeof HTMLTemplateElement === 'undefined');
// NOTE: Patch document.importNode to work around IE11 bug that
// casues children of a document fragment imported while
// there is a mutation observer to not have a parentNode (!?!)
// It's important that this is the first patch to `importNode` so that
// dom produced for later patches is correct.
if (/Trident/.test(navigator.userAgent)) {
(function() {
var Native_importNode = Document.prototype.importNode;
Document.prototype.importNode = function() {
var n = Native_importNode.apply(this, arguments);
// Copy all children to a new document fragment since
// this one may be broken
if (n.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
var f = this.createDocumentFragment();
f.appendChild(n);
return f;
} else {
return n;
}
};
})();
}
// NOTE: we rely on this cloneNode not causing element upgrade.
// This means this polyfill must load before the CE polyfill and
// this would need to be re-worked if a browser supports native CE
// but not <template>.
var Native_cloneNode = Node.prototype.cloneNode;
var Native_createElement = Document.prototype.createElement;
var Native_importNode = Document.prototype.importNode;
// returns true if nested templates cannot be cloned (they cannot be on
// some impl's like Safari 8 and Edge)
// OR if cloning a document fragment does not result in a document fragment
var needsCloning = (function() {
if (!needsTemplate) {
var t = document.createElement('template');
var t2 = document.createElement('template');
t2.content.appendChild(document.createElement('div'));
t.content.appendChild(t2);
var clone = t.cloneNode(true);
return (clone.content.childNodes.length === 0 || clone.content.firstChild.content.childNodes.length === 0
|| !(document.createDocumentFragment().cloneNode() instanceof DocumentFragment));
}
})();
// returns true if templates cannot be deep imported
var needsImport = (function() {
if (!needsTemplate) {
var t = document.createElement('template');
t.content.appendChild(document.createElement('div'));
var deepImport = document.importNode(t, true);
return (deepImport.content.childNodes.length === 0);
}
})();
var TEMPLATE_TAG = 'template';
var PolyfilledHTMLTemplateElement = function() {};
if (needsTemplate) {
var contentDoc = document.implementation.createHTMLDocument('template');
var templateStyle = document.createElement('style');
templateStyle.textContent = TEMPLATE_TAG + '{display:none;}';
var head = document.head;
head.insertBefore(templateStyle, head.firstElementChild);
/**
Provides a minimal shim for the <template> element.
*/
PolyfilledHTMLTemplateElement.prototype = Object.create(HTMLElement.prototype);
// if elements do not have `innerHTML` on instances, then
// templates can be patched by swizzling their prototypes.
var canProtoPatch = { __proto__: [] } instanceof Array &&
!(document.createElement('div').hasOwnProperty('innerHTML'));
/**
The `decorate` method moves element children to the template's `content`.
NOTE: there is no support for dynamically adding elements to templates.
*/
PolyfilledHTMLTemplateElement.decorate = function(template) {
// if the template is decorated, return fast
if (template.content) {
return;
}
template.content = contentDoc.createDocumentFragment();
var child;
while (child = template.firstChild) {
template.content.appendChild(child);
}
// NOTE: prefer prototype patching for performance and
// because on some browsers (IE11), re-defining `innerHTML`
// can result in intermittent errors.
if (canProtoPatch) {
template.__proto__ = PolyfilledHTMLTemplateElement.prototype;
} else {
template.cloneNode = function(deep) {
return PolyfilledHTMLTemplateElement._cloneNode(this, deep);
};
defineInnerHTML(template);
}
// bootstrap recursively
PolyfilledHTMLTemplateElement.bootstrap(template.content);
};
var draft = contentDoc.createElement('div');
var rTagSplit = /^(.*)(<\/[a-z][^\/]*>)$/i;
function getInnerHTML(node) {
var o = [];
for (var e = node.firstChild; e; e = e.nextSibling) {
if (e.nodeType === Node.ELEMENT_NODE) {
if (e.localName === TEMPLATE_TAG || e.childNodes.length) {
var split = rTagSplit.exec(e.cloneNode(false).outerHTML) || ["", "", ""];
o.push(
split[1],
getInnerHTML(e.localName === TEMPLATE_TAG ? e.content : e),
split[2]
);
} else {
o.push(e.outerHTML);
}
} else {
draft.appendChild(e.cloneNode(false));
o.push(draft.innerHTML);
draft.textContent = '';
}
}
return o.join('');
}
PolyfilledHTMLTemplateElement.getInnerHTML = getInnerHTML;
function defineInnerHTML(obj) {
Object.defineProperty(obj, 'innerHTML', {
get: function() {
return getInnerHTML(this.content);
},
set: function(text) {
var wrap = findWrap(text);
var body = contentDoc.body;
body.innerHTML = [wrap[1], text, wrap[2]].join('');
PolyfilledHTMLTemplateElement.bootstrap(contentDoc);
while (this.content.firstChild) {
this.content.removeChild(this.content.firstChild);
}
var j = wrap[0];
while (j--) {
body = body.lastChild;
}
while (body.firstChild) {
this.content.appendChild(body.firstChild);
}
},
configurable: true
});
}
// https://github.com/jquery/jquery/blob/a6b07052/src/manipulation
var wrapMap = {
// Support: IE <=9 only
option: [ 1, "<select multiple='multiple'>", "</select>" ],
// XHTML parsers do not magically insert elements in the
// same way that tag soup parsers do. So we cannot shorten
// this by omitting <tbody> or other required elements.
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE <=9 only
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
var rTagName = /<([a-z][^\/\0>\x20\t\r\n\f]+)/i;
function findWrap(text) {
var tag = (rTagName.exec(text) || [ "", "" ])[1].toLowerCase();
return wrapMap[tag] || wrapMap._default;
}
// end of jquery extract
defineInnerHTML(PolyfilledHTMLTemplateElement.prototype);
/**
The `bootstrap` method is called automatically and "fixes" all
<template> elements in the document referenced by the `doc` argument.
*/
PolyfilledHTMLTemplateElement.bootstrap = function(doc) {
var templates = doc.querySelectorAll(TEMPLATE_TAG);
for (var i=0, l=templates.length, t; (i<l) && (t=templates[i]); i++) {
PolyfilledHTMLTemplateElement.decorate(t);
}
};
// auto-bootstrapping for main document
document.addEventListener('DOMContentLoaded', function() {
PolyfilledHTMLTemplateElement.bootstrap(document);
});
// Patch document.createElement to ensure newly created templates have content
Document.prototype.createElement = function() {
'use strict';
var el = Native_createElement.apply(this, arguments);
if (el.localName === 'template') {
PolyfilledHTMLTemplateElement.decorate(el);
}
return el;
};
}
// make cloning/importing work!
if (needsTemplate || needsCloning || needsImport) {
PolyfilledHTMLTemplateElement._cloneNode = function(template, deep) {
var clone = Native_cloneNode.call(template, false);
// NOTE: decorate doesn't auto-fix children because they are already
// decorated so they need special clone fixup.
if (this.decorate) {
this.decorate(clone);
}
if (deep) {
// NOTE: use native clone node to make sure CE's wrapped
// cloneNode does not cause elements to upgrade.
clone.content.appendChild(
Native_cloneNode.call(template.content, true));
// now ensure nested templates are cloned correctly.
this.fixClonedDom(clone.content, template.content);
}
return clone;
};
PolyfilledHTMLTemplateElement.prototype.cloneNode = function(deep) {
return PolyfilledHTMLTemplateElement._cloneNode(this, deep);
}
// Given a source and cloned subtree, find <template>'s in the cloned
// subtree and replace them with cloned <template>'s from source.
// We must do this because only the source templates have proper .content.
PolyfilledHTMLTemplateElement.fixClonedDom = function(clone, source) {
// do nothing if cloned node is not an element
if (!source.querySelectorAll) return;
// these two lists should be coincident
var s$ = source.querySelectorAll(TEMPLATE_TAG);
var t$ = clone.querySelectorAll(TEMPLATE_TAG);
for (var i=0, l=t$.length, t, s; i<l; i++) {
s = s$[i];
t = t$[i];
if (this.decorate) {
this.decorate(s);
}
t.parentNode.replaceChild(s.cloneNode(true), t);
}
};
if (needsTemplate || needsCloning) {
// override all cloning to fix the cloned subtree to contain properly
// cloned templates.
Node.prototype.cloneNode = function(deep) {
var dom;
// workaround for Edge bug cloning documentFragments
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8619646/
if (this instanceof DocumentFragment) {
if (!deep) {
return this.ownerDocument.createDocumentFragment();
} else {
dom = this.ownerDocument.importNode(this, true);
}
} else {
dom = Native_cloneNode.call(this, deep);
}
// template.content is cloned iff `deep`.
if (deep) {
PolyfilledHTMLTemplateElement.fixClonedDom(dom, this);
}
return dom;
};
}
if (needsTemplate || needsImport) {
// NOTE: we are cloning instead of importing <template>'s.
// However, the ownerDocument of the cloned template will be correct!
// This is because the native import node creates the right document owned
// subtree and `fixClonedDom` inserts cloned templates into this subtree,
// thus updating the owner doc.
Document.prototype.importNode = function(element, deep) {
if (element.localName === TEMPLATE_TAG) {
return PolyfilledHTMLTemplateElement._cloneNode(element, deep);
} else {
var dom = Native_importNode.call(this, element, deep);
if (deep) {
PolyfilledHTMLTemplateElement.fixClonedDom(dom, element);
}
return dom;
}
};
}
if (needsCloning) {
window.HTMLTemplateElement.prototype.cloneNode = function(deep) {
return PolyfilledHTMLTemplateElement._cloneNode(this, deep);
};
}
}
if (needsTemplate) {
window.HTMLTemplateElement = PolyfilledHTMLTemplateElement;
}
})();