-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
49 lines (42 loc) · 1.12 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
var Parser = require("htmlparser2").Parser;
var IncrementalDOM = require("incremental-dom");
var elementOpen = IncrementalDOM.elementOpen;
var elementClose = IncrementalDOM.elementClose;
var text = IncrementalDOM.text;
var patch = IncrementalDOM.patch;
/** Parser with callbacks that invoke Incremental DOM */
var parser = new Parser({
onopentag: function (name, attrs) {
var argsArray = [name, null, null];
// convert attribs object into a flat array
for (var attr in attrs) {
argsArray.push(attr, attrs[attr]);
}
elementOpen.apply(null, argsArray);
},
ontext: text,
onclosetag: elementClose
}, {decodeEntities: true});
/**
* build IDOM for ast node
* @private
* @param {Object} node - An AST node to render
*/
function renderToIDom(html) {
parser.write(html);
parser.end();
};
/**
* apply the HTML to an element via Incremental DOM's `patch`
* @param {Element} el - The element to apply the patch to
* @param {String} html - A string of HTML
*/
function patchHTML(el, html) {
patch(el, function() {
return renderToIDom(html);
});
}
module.exports = {
renderToIDom: renderToIDom,
patchHTML: patchHTML
}