1+ // string -> DOM conversion
2+ // wrappers originally from jQuery, scooped from component/domify
3+ var map = {
4+ legend : [ 1 , '<fieldset>' , '</fieldset>' ] ,
5+ tr : [ 2 , '<table><tbody>' , '</tbody></table>' ] ,
6+ col : [ 2 , '<table><tbody></tbody><colgroup>' , '</colgroup></table>' ] ,
7+ _default : [ 0 , '' , '' ]
8+ }
9+
10+ map . td =
11+ map . th = [ 3 , '<table><tbody><tr>' , '</tr></tbody></table>' ]
12+
13+ map . option =
14+ map . optgroup = [ 1 , '<select multiple="multiple">' , '</select>' ]
15+
16+ map . thead =
17+ map . tbody =
18+ map . colgroup =
19+ map . caption =
20+ map . tfoot = [ 1 , '<table>' , '</table>' ]
21+
22+ map . text =
23+ map . circle =
24+ map . ellipse =
25+ map . line =
26+ map . path =
27+ map . polygon =
28+ map . polyline =
29+ map . rect = [ 1 , '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">' , '</svg>' ]
30+
31+ var TAG_RE = / < ( [ \w : ] + ) /
32+
33+ module . exports = function ( template ) {
34+
35+ if ( typeof template !== 'string' ) {
36+ return template
37+ }
38+
39+ // template by ID
40+ if ( template . charAt ( 0 ) === '#' ) {
41+ var templateNode = document . getElementById ( template . slice ( 1 ) )
42+ if ( ! templateNode ) return
43+ // if its a template tag and the browser supports it,
44+ // its content is already a document fragment!
45+ if ( templateNode . tagName === 'TEMPLATE' && templateNode . content ) {
46+ return templateNode . content
47+ }
48+ template = templateNode . innerHTML
49+ }
50+
51+ var frag = document . createDocumentFragment ( ) ,
52+ m = TAG_RE . exec ( template )
53+ // text only
54+ if ( ! m ) {
55+ frag . appendChild ( document . createTextNode ( template ) )
56+ return frag
57+ }
58+
59+ var tag = m [ 1 ] ,
60+ wrap = map [ tag ] || map . _default ,
61+ depth = wrap [ 0 ] ,
62+ prefix = wrap [ 1 ] ,
63+ suffix = wrap [ 2 ] ,
64+ node = document . createElement ( 'div' )
65+
66+ node . innerHTML = prefix + template . trim ( ) + suffix
67+ while ( depth -- ) node = node . lastChild
68+
69+ // one element
70+ if ( node . firstChild === node . lastChild ) {
71+ frag . appendChild ( node . firstChild )
72+ return frag
73+ }
74+
75+ // multiple nodes, return a fragment
76+ var child
77+ /* jshint boss: true */
78+ while ( child = node . firstChild ) {
79+ if ( node . nodeType === 1 ) {
80+ frag . appendChild ( child )
81+ }
82+ }
83+ return frag
84+ }
0 commit comments