|
var tags = require('./tags'); |
|
|
|
function Domino(tag, ancestors, opts) { |
|
this.tag = tag || ''; |
|
this.ancestors = ancestors || []; |
|
|
|
this.parent = this.ancestors[0]; |
|
|
|
this.nodeCount = 1; |
|
this.nodeId = null; |
|
this.classList = []; |
|
} |
|
|
|
|
|
/* Metaprogramming for each tag */ |
|
tags.forEach(function (tag) { |
|
Object.defineProperty(Domino.prototype, tag, { |
|
get: function () { |
|
return new Domino(tag, [this].concat(this.ancestors), {}); |
|
} |
|
}); |
|
}); |
|
|
|
|
|
Domino.prototype.count = function (count) { |
|
this.nodeCount = count; |
|
return this; |
|
}; |
|
|
|
|
|
Domino.prototype.id = function (id) { |
|
this.nodeId = id; |
|
return this; |
|
}; |
|
|
|
|
|
Domino.prototype.class = Domino.prototype.addClass = function (className) { |
|
this.classList.push(className); |
|
return this; |
|
}; |
|
|
|
|
|
Domino.prototype.toString = function (inside) { |
|
inside = inside || ''; |
|
|
|
/* calculate the padding for nested tags */ |
|
var padding = new Array(this.ancestors.length).join(' '); |
|
|
|
/* generate an opening tag */ |
|
var open = '<' + this.tag; |
|
|
|
/* add the id if one exists */ |
|
if (this.nodeId) { |
|
open += ' id="' + this.nodeId + '"'; |
|
} |
|
|
|
/* add the classList */ |
|
if (this.classList.length > 0) { |
|
open += ' class="' + this.classList.join(' ') + '"'; |
|
} |
|
|
|
open += '>'; |
|
|
|
/* generate a closing tag */ |
|
var close = '</' + this.tag + '>'; |
|
var markup; |
|
|
|
if (inside.match(/^\s+/g)) { |
|
/* we have inner tags, place tags on their own line */ |
|
markup = [padding + open, inside, padding + close].join('\n'); |
|
} else { |
|
/* otherwise, the opening and closing tags share a line */ |
|
markup = padding + open + inside + close; |
|
} |
|
|
|
/* multiply by count */ |
|
if (this.nodeCount > 1) { |
|
markup = new Array(this.nodeCount + 1).join(markup + '\n').slice(0, -1); |
|
} |
|
|
|
return (this.parent.ancestors.length) ? this.parent.toString(markup) : markup; |
|
}; |
|
|
|
|
|
module.exports = new Domino(); |