Skip to content

Instantly share code, notes, and snippets.

@lieuwex
Last active August 29, 2015 14:21
Show Gist options
  • Save lieuwex/bc555a8aa3f643450d65 to your computer and use it in GitHub Desktop.
Save lieuwex/bc555a8aa3f643450d65 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
html, body {
height: 100%;
margin: 0;
}
#msg {
position: fixed;
top: 0;
right: 0;
left: 0;
z-index: 500;
background-color: white;
color: black;
font-size: 17px;
}
#ta {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 50vh;
padding-top: 30px;
white-space: pre;
font-family: monospace;
width: 100%;
}
#dump {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 40vh;
}
</style>
<script src="./json2dom.js"></script>
<script>
function f () {
var func;
var msg = document.getElementById("msg");
var ta = document.getElementById("ta");
var dump = document.getElementById("dump");
ta.oninput = ta.onpropertychange = func = function (event) {
var text = event.target.value;
try { var json = JSON.parse(text); }
catch (err) { msg.innerText = "Error while parsing text"; return; }
try {
var res = parseObjectToDom(json);
msg.innerText = dump.innerHTML = "";
res.forEach(function (node) {
dump.appendChild(node);
});
} catch (err) { console.error(err); msg.innerText = "Error while converting JSON."; return; }
};
func({ target: ta }); // Render placeholder.
}
</script>
</head>
<body onload="f()">
<div id="msg"></div>
<textarea id="ta">[{"type":"div","style":"position:absolute;left:50%;margin-left:-175px;top:50%;margin-top:-135px;width:350px;height:220px;background-color:gray;padding:15px;","content":[{"type":"input","Type": "email", "placeholder":"email","style":"width:100%;font-size:17px;margin-bottom:5px"},{"type":"input","Type":"password","placeholder":"password","style":"width:100%;font-size:17px;"},{"type":"button","content":"login","style":"font-size:15px;width:100%;margin-top:15px;padding-top:5px;padding-bottom:5px"}]}]</textarea>
<div id="dump"></div>
</body>
</html>
Array.prototype.flatten = function () {
return [].concat.apply([], this);
}
function parseObjectToDom (node) {
if (typeof(node) === "string") { // text
return [ document.createTextNode(node) ];
} else if (node.length != null) { // inline array
return node.map(parseObjectToDom).flatten();
} else { // object.
var elem = document.createElement(node.type);
for (key in node) {
if (key != "content" && key != "type") {
elem.setAttribute(key, node[key]);
}
}
parseObjectToDom(node.content || []).forEach(function (x) {
elem.appendChild(x);
});
return elem;
}
}
@lieuwex
Copy link
Author

lieuwex commented May 24, 2015

"Better than XHTML" — Anonymous

@tomsmeding
Copy link

Better than Malbolge

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment