Skip to content

Instantly share code, notes, and snippets.

@dhilip89
Created November 7, 2018 20:46
Show Gist options
  • Save dhilip89/b32bc994ebf24bd3d2b03262905dc058 to your computer and use it in GitHub Desktop.
Save dhilip89/b32bc994ebf24bd3d2b03262905dc058 to your computer and use it in GitHub Desktop.
[Fun] HTML is a programming language!!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML is a programming language!!!</title>
</head>
<body>
<script>
class LogicBlock extends HTMLElement {
connectedCallback() {
let generatedCode = "";
const parent = this.parentNode;
const traverse = function (node) {
switch (node.nodeName) {
case "FOR": {
const init = node.getAttribute("init"),
condition = node.getAttribute("condition"),
iteration = node.getAttribute("iteration");
generatedCode += `for(${init};${condition};${iteration}){`;
node.childNodes.forEach(x => traverse(x));
generatedCode += "}";
break;
}
case "IF": {
const condition = node.getAttribute("condition");
generatedCode += `if(${condition}){`;
node.childNodes.forEach(x => traverse(x));
generatedCode += "}";
break;
}
case "ELSE": {
generatedCode += "else{";
node.childNodes.forEach(x => traverse(x));
generatedCode += "}";
break;
}
case "PRINT": {
const text = node.getAttribute("text");
generatedCode += `console.log(\`${text}\`);`;
break;
}
case "NODE": {
const html = `${node.getAttribute("content")}`;
generatedCode += `parent.insertAdjacentHTML('beforeend', \`${html}\`);`;
break;
}
}
};
// OMG This is so bad!!!
setTimeout(() => eval(generatedCode), 250);
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes.length) {
const addedNode = mutation.addedNodes[0];
traverse(addedNode);
}
});
});
observer.observe(this, { childList: true });
}
}
customElements.define("logic-block", LogicBlock);
</script>
<logic-block>
<for init="let i = 0" condition="i < 10" iteration="i++">
<if condition="i % 2 === 0">
<print text="${i} : even"></print>
<node content="<div>${i} is even</div>"></node>
</if>
<else>
<print text="${i} : odd"></print>
<node content="<div>${i} is odd</div>"></node>
</else>
<node content="<br>"></node>
</for>
<print text="done!"></print>
</logic-block>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment