-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
50 lines (49 loc) · 1.67 KB
/
index.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
let re = / on([a-z]+)\s*=\s*(["'])?\s*?$/
,quote = {"'": /^\s*'/, '"': /^\s*"/}
,ehs = 'data-kata-ev'
,ecs = 'data-kata-embed'
,cf = /^data-kata-embed:(\d+)$/
export default function(s, ...expr){
let e,embeds = []
,handlers = []
,predoc = ''
,strings = Array.from(s)
for (let e of expr) {
if ('function'===typeof e){
predoc += strings.shift().replace(re, (_, event, q)=>{
let i = handlers.push({event, handler:e})-1
if (q && strings[0]){
strings[0] = strings[0].replace(quote[q], '')
}
return ` ${ehs}-${event}="${i}"`
})
}
else {
predoc += strings.shift()
for (let ae of [].concat(e)){
if (('object' === typeof ae) && ('number' === typeof ae.nodeType) && [
1 // Element
,3 // Text
,8 // Comment
,11 // DocumentFragment
].includes(ae.nodeType)){
let i = embeds.push(ae)-1
predoc += `<!--${ecs}:${i}-->`
}
else predoc += ae
}
}
}
predoc+=strings.shift()
let doc = document.createRange().createContextualFragment(predoc.trim())
for (let e of new Set(handlers.map(h=>h.event))){
for (let el of Array.from(doc.querySelectorAll(`*[${ehs}-${e}]`))){
let h = handlers[el.getAttribute(`${ehs}-${e}`)]
el.addEventListener(h.event, h.handler)
el.removeAttribute(`${ehs}-${e}`)
}
}
let m,n,walker = document.createNodeIterator(doc, NodeFilter.SHOW_COMMENT, { acceptNode: function(n){if (m = n.textContent.match(cf)) return NodeFilter.FILTER_ACCEPT} })
while (n=walker.nextNode()) n.replaceWith(embeds[m[1]])
return 1==doc.childNodes.length ? doc.firstChild : doc
}