This commit is contained in:
Leo Horie 2016-03-02 16:10:51 -05:00
parent f17658e2d3
commit 501e380825
67 changed files with 11869 additions and 2 deletions

View file

@ -0,0 +1,84 @@
/*
Compiles Mithril templates
Requires sweet.js (https://github.com/mozilla/sweet.js)
Installation: npm install -g sweet.js
Usage: sjs --module /template-compiler.sjs --output <output-filename>.js <input-filename>.js
*/
macro m_impl {
case { _ ($selector, $dynAttrs ..., $children ...) } => {
var selectorSyntax = #{$selector};
var selector = unwrapSyntax(selectorSyntax);
var dynAttrsSyntax = #{$dynAttrs ...};
try {
var dynAttrs = unwrapSyntax(dynAttrsSyntax);
var parser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[.+?\])/g;
var attrParser = /\[(.+?)=("|'|)(.+?)\2\]/;
var _match = null;
var classes = [];
var cell = {tag: "div", attrs: {}, children: []};
while (_match = parser.exec(selector)) {
if (_match[1] == "") cell.tag = _match[2];
else if (_match[1] == "#") cell.attrs.id = _match[2];
else if (_match[1] == ".") classes.push(_match[2]);
else if (_match[3][0] == "[") {
var pair = attrParser.exec(_match[3]);
cell.attrs[pair[1]] = pair[3];
}
}
if (classes.length > 0) cell.attrs["class"] = classes.join(" ");
var tag = makeValue(cell.tag, #{here});
var attrsBody = Object.keys(cell.attrs).reduce(function(memo, attrName) {
return memo.concat([
makeValue(attrName, #{here}),
makePunc(":", #{here}),
makeValue(cell.attrs[attrName], #{here}),
makePunc(",", #{here})
]);
}, []).concat(dynAttrs.inner);
var attrs = [makeDelim("{}", attrsBody, #{here})];
letstx $tag = [tag], $attrs = attrs;
return #{ ({tag: $tag, attrs: $attrs , children: $children ...}) };
}
catch (e) {
return #{ m_impl($tag, {}, [$dynAttrs ..., $children ...]) }
}
}
case { _ ($selector, $partial ...) } => {
var partialSyntax = #{$partial ...};
try {
var partial = unwrapSyntax(partialSyntax);
var isTag = partial.inner && partial.inner.length > 2 && (partial.inner[0].token.value == "tag" && partial.inner[1].token.value == ":") || typeof partial != "object" || partial.value == "[]"
return !isTag ? #{m_impl($selector, $partial ..., [])} : #{m_impl($selector, {}, $partial ...)};
}
catch (e) {
return #{m_impl($selector, {}, $partial ...)}
}
}
case { _ ($selector) } => {
return #{m_impl($selector, {}, [])};
}
}
let m = macro {
case { _ ($selector, $dynAttrs ..., $children ...) } => {
return #{m_impl($selector, $dynAttrs ..., $children ...)}
}
case { _ ($selector, $partial ...) } => {
return #{m_impl($selector, $partial ...)}
}
case { _ ($selector) } => {
return #{m_impl($selector, {}, [])};
}
case { _ } => {
return #{m};
}
}
export m;

View file

@ -0,0 +1,17 @@
<!doctype html>
<title>HTML to Mithril Template Converter</title>
<h1>HTML to Mithril Template Converter</h1>
<p>
If you have HTML you want to convert into a Mithril template, paste it below
and press the "Convert" button. In case you're wondering, this itself is a
Mithril app.
</p>
<div id="converter"></div>
<script src="../mithril.min.js"></script>
<script src="template-converter.js"></script>
<script>
m.mount(document.getElementById("converter"), templateConverter)
</script>

View file

@ -0,0 +1,145 @@
/* global m: false */
// TODO: ensure this targets the current API.
window.templateConverter = (function () {
"use strict"
function each(list, f) {
for (var i = 0; i < list.length; i++) {
f(list[i], i)
}
}
function createFragment(markup) {
if (markup.indexOf("<!doctype") >= 0) {
return [
new DOMParser()
.parseFromString(markup, "text/html")
.childNodes[1]
]
}
var container = document.createElement("div")
container.insertAdjacentHTML("beforeend", markup)
return container.childNodes
}
function createVirtual(fragment) {
var list = []
each(fragment, function (el) {
if (el.nodeType === 3) {
list.push(el.nodeValue)
} else if (el.nodeType === 1) {
var attrs = {}
each(el.attributes, function (attr) {
attrs[attr.name] = attr.value
})
list.push({
tag: el.nodeName.toLowerCase(),
attrs: attrs,
children: createVirtual(el.childNodes)
})
}
})
return list
}
function TemplateBuilder(virtual, level) {
this.virtual = virtual
this.level = level
this.virtuals = []
this.indented = false
}
TemplateBuilder.prototype = {
addVirtualString: function (el) {
if (/\t| {2,}/.test(el) && /^\s*/.test(el)) {
this.indented = true
} else {
this.virtuals.push('"' + el.replace(/(["\r\n])/g, "\\$1") + '"')
}
},
addVirtualAttrs: function (el) {
var virtual = el.tag === "div" ? "" : el.tag
if (el.attrs.class) {
virtual += "." + el.attrs.class.replace(/\s+/g, ".")
delete el.attrs.class
}
each(Object.keys(el.attrs).sort(), function (attrName) {
if (attrName === "style") return
virtual += "[" + attrName + "='"
virtual += el.attrs[attrName].replace(/'/g, "\\'") + "']"
})
if (virtual === "") virtual = "div"
virtual = '"' + virtual + '"'
if (el.attrs.style) {
var style = "{\"" + el.attrs.style
.replace(/:/g, "\": \"")
.replace(/;/g, "\", \"") + "}"
virtual += ", {style: " + style.replace(/(, )"}/, "}") + "}"
}
if (el.children.length !== 0) {
var builder = new TemplateBuilder(el.children, this.level + 1)
virtual += ", " + builder.complete()
}
this.virtuals.push("m(" + virtual + ")")
},
complete: function () {
var tab = "\n"
for (var i = 0; i <= this.level; i++) tab += "\t"
each(this.virtual, function (el) {
if (typeof el === "string") {
this.addVirtualString(el)
} else {
this.addVirtualAttrs(el)
}
}.bind(this))
if (!this.indented) tab = ""
if (this.virtuals.length === 1 && this.virtuals[0][0] === "\"") {
return this.virtuals.join(", ")
} else {
var body = this.virtuals.join("," + tab)
return "[" + tab + body + tab.slice(0, -1) + "]"
}
}
}
return {
controller: function () {
this.source = m.prop("")
this.output = m.prop("")
this.convert = function () {
var source = createVirtual(createFragment(this.source()))
return this.output(new TemplateBuilder(source, 1).complete())
}.bind(this)
},
view: function (ctrl) {
return m("div", [
m("textarea", {
autofocus: true,
style: {width: "100%", height: "40%"},
onchange: m.withAttr("value", ctrl.source)
}, ctrl.source()),
m("button", {onclick: ctrl.convert}, "Convert"),
m("textarea", {style: {width: "100%", height: "40%"}},
ctrl.output())
])
}
}
})()