Skip to content

Instantly share code, notes, and snippets.

@pvdz
Created May 29, 2012 20:22
Show Gist options
  • Save pvdz/2830474 to your computer and use it in GitHub Desktop.
Save pvdz/2830474 to your computer and use it in GitHub Desktop.
ZeParser tagliteral post to DOM syntax
// requires ZeParser (see repo)
// input is a string, your js input with tagliterals
function compile(input){
var tree = [];
var tokenizer = new Tokenizer(input);
tokenizer.tagLiterals = true; // enable tag literals in the engine
var parser = new ZeParser(input, tokenizer, tree);
parser.parse();
tokenizer.fixValues();
return tokenizer.wtree.map(function(t){
if (t.name == 15) {
return (function reify(node, _indent){
// first call, initialize
if (!_indent) {
var lineStart = input.lastIndexOf('\n', t.start)+1;
var r = /\s*/g;
r.lastIndex = lineStart;
_indent = r.exec(input)+' ';
}
var arr = [];
arr.push('var e = document.createElement(\''+node.name+'\');');
Object.keys(node.attributes).forEach(function(key){
if (node.attributes[key] instanceof Array) {
if (!node.attributes[key][node.attributes[key].length-1]) node.attributes[key].length--; // remove last element, it's the empty string
arr.push(
'e.setAttribute(\''+key+'\', '+
node.attributes[key].map(function(s,i){
if (i%2) { // uneven, js
return '('+(s||'""')+')';
} else { // even, string
return '\''+s.replace(/\\(.|$)/g, '$1').replace(/(['\\])/g,'\\$1')+'\'';
}
}).join('+')+
');'
);
}
else if (typeof node.attributes[key] != 'string') arr.push('e.setAttribute(\''+key+'\', true);');
else arr.push('e.setAttribute(\''+key+'\', \''+node.attributes[key].replace(/\\(.|$)/g, '$1').replace(/(['\\])/g,'\\$1')+'\');');
});
if (!node.unary && node.children.length) {
node.children.forEach(function(c){
if (typeof c == 'string') {
arr.push('e.appendChild(document.createTextNode(\''+c.replace(/\\(.|$)/g, '$1').replace(/(['\\])/g,'\\$1').replace(/\n/g,'\\n')+'\'));');
}
else if (c instanceof Array) {
arr.push('e.appendChild(document.createTextNode('+c.map(function(s,i){
if (i%2) { // uneven, js
return '('+(s||'""')+')';
} else { // even, string
return '\''+s.replace(/\\(.|$)/g, '$1').replace(/(['\\])/g,'\\$1')+'\'';
}
}).join('+')+'));');
}
else arr.push('e.appendChild('+reify(c,_indent+' ')+');');
});
}
arr.push('return e;\n');
return 'new function(){\n'+_indent+arr.join('\n'+_indent)+_indent.slice(0,-2)+'}';
})(t.root);
}
return t.value;
}).join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment