babelute-html-dom-pragmatics
Version:
Pure DOM engine for babelue-html-lexicon
103 lines (92 loc) • 2.97 kB
JavaScript
import babelute from 'babelute';
import { insertHTML } from 'nomocas-webutils/lib/dom-utils';
import htmlLexicon from 'babelute-html-lexicon';
/**
************** HTML to DOM Actions (just for demo) ***********
*
* @author Gilles Coomans
* @licence MIT
* @copyright 2016-2017 Gilles Coomans
*/
/**
* @external {FacadePragmatics} https://github.com/nomocas/babelute
*/
var $baseOutput = babelute.FacadePragmatics.prototype.$output;
/**
* Dom Pragmatics
* @type {FacadePragmatics}
* @public
* @example
* import domPragmas from 'babelute-html/src/html-to-dom.js';
* import htmlLexicon from 'babelute-html/src/html-lexicon.js';
*
* const h = htmlLexicon.initializer;
* const sentence = h.div(state.intro).section(h.class('my-section').h1(state.title));
* const $root = document.getElementById('foo');
*
* domPragmas.$output($root, sentence);
*/
var domPragmas = babelute.createFacadePragmatics({
html: true
}, {
// we only need to provides language atoms implementations.
tag: function tag($tag, args /* tagName, babelutes */) {
var child = document.createElement(args[0]),
babelutes = args[1];
var templ = void 0;
$tag.appendChild(child);
for (var i = 0, len = babelutes.length; i < len; ++i) {
templ = babelutes[i];
if (typeof templ === 'undefined') continue;
if (templ && templ.__babelute__) this.$output(child, templ);else child.appendChild(document.createTextNode(templ)); // auto escaped when added to dom.
}
},
text: function text($tag, args /* value */) {
$tag.appendChild(document.createTextNode(args[0])); // auto escaped when added to dom.
},
class: function _class($tag, args /* className, flag */) {
if (args[0] && (args.length === 1 || args[1])) $tag.classList.add(args[0]);
},
classes: function classes($tag, args /* classes */) {
var splitted = args[0].split(/\s+/);
splitted.forEach(function (cl) {
$tag.classList.add(cl);
});
},
style: function style($tag, args /* name, value */) {
$tag.style[args[0]] = args[1];
},
attr: function attr($tag, args /* name, value */) {
$tag.setAttribute(args[0], args[1]);
},
prop: function prop($tag, args /* name, value */) {
$tag[args[0]] = args[1];
},
data: function data($tag, args /* name, value */) {
$tag.dataset[args[0]] = args[1];
},
id: function id($tag, args /* value */) {
$tag.id = args[0];
},
on: function on($tag, args /* eventName, callback */) {
$tag.addEventListener(args[0], args[1]);
},
// custom output
onDom: function onDom($tag, args /* render */) {
var onRender = args[0];
if (onRender) onRender($tag, null);
},
$output: function $output($tag, babelute$$1) {
return $baseOutput.call(this, $tag, babelute$$1).children;
},
html: function html($tag, args) {
if (args[0]) insertHTML(args[0], $tag);
}
});
htmlLexicon.addAliases({
$toDOM: function $toDOM(domElement) {
return domPragmas.$output(domElement, this);
}
});
export default domPragmas;
//# sourceMappingURL=index.mjs.map