forked from vuejs/vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfragment.js
84 lines (71 loc) · 2.12 KB
/
fragment.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
// string -> DOM conversion
// wrappers originally from jQuery, scooped from component/domify
var map = {
legend : [1, '<fieldset>', '</fieldset>'],
tr : [2, '<table><tbody>', '</tbody></table>'],
col : [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
_default : [0, '', '']
}
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']
map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>']
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>']
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']
var TAG_RE = /<([\w:]+)/
module.exports = function (template) {
if (typeof template !== 'string') {
return template
}
// template by ID
if (template.charAt(0) === '#') {
var templateNode = document.getElementById(template.slice(1))
if (!templateNode) return
// if its a template tag and the browser supports it,
// its content is already a document fragment!
if (templateNode.tagName === 'TEMPLATE' && templateNode.content) {
return templateNode.content
}
template = templateNode.innerHTML
}
var frag = document.createDocumentFragment(),
m = TAG_RE.exec(template)
// text only
if (!m) {
frag.appendChild(document.createTextNode(template))
return frag
}
var tag = m[1],
wrap = map[tag] || map._default,
depth = wrap[0],
prefix = wrap[1],
suffix = wrap[2],
node = document.createElement('div')
node.innerHTML = prefix + template.trim() + suffix
while (depth--) node = node.lastChild
// one element
if (node.firstChild === node.lastChild) {
frag.appendChild(node.firstChild)
return frag
}
// multiple nodes, return a fragment
var child
/* jshint boss: true */
while (child = node.firstChild) {
if (node.nodeType === 1) {
frag.appendChild(child)
}
}
return frag
}