-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfragment.js
67 lines (57 loc) · 1.63 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
// 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 (templateString) {
var frag = document.createDocumentFragment(),
m = TAG_RE.exec(templateString)
// text only
if (!m) {
frag.appendChild(document.createTextNode(templateString))
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 + templateString.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
}