Last active
November 13, 2021 21:43
-
-
Save SimonHauguel/49032dcdb4182ce890d65dd56ce24c77 to your computer and use it in GitHub Desktop.
Write macros directly into your html code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I'm not a web mad scientist developer, but use `defer` can be a good thing | |
function isNotNested(macroElement) { | |
let elementNode = macroElement; | |
while ((elementNode = elementNode.parentNode) != document) { | |
if (elementNode.className.split().includes("macro")) | |
return false | |
} | |
return true | |
} | |
while ((allMacro = | |
Array.from(document.getElementsByClassName("macro")) | |
.filter(isNotNested) | |
).length !== 0) { | |
for (macroElement of allMacro) { | |
macroElement.hidden = "" | |
let allArg = macroElement.className.split(":")[1] | |
if (allArg !== undefined) allArg = allArg.trim().split(" ") | |
const name = macroElement.id ? macroElement.id : "macro-expand-default" | |
let toSubstitute = Array.from(document.getElementsByClassName(name)) | |
for (toReplace of toSubstitute) { | |
const tempAllParam = toReplace.className.split(":")[1] | |
if (tempAllParam === undefined) console.error("Arguments needed") | |
const allParam = tempAllParam.trim().split(" ") | |
if (allParam.length !== allArg.length) console.error("Number of arguments missmatch") | |
let toExpand = macroElement.innerHTML | |
for (let i = 0; i < allParam.length; i++) { | |
toExpand = toExpand.replace( | |
"{" + allArg[i] + "}", allParam[i]) | |
} | |
toReplace.outerHTML = toExpand | |
} | |
macroElement.className = macroElement | |
.className | |
.replace("macro", "already-expand") | |
} | |
} | |
// Here some examples : | |
<div class="macro : arg1 arg2" id="test"> | |
<div class="{arg2}" style="color:{arg1};"> | |
cat | |
</div> | |
</div> | |
<div class="test : red some"></div> | |
// Became : | |
<div class="already-expand : arg1 arg2" id="test" hidden=""> | |
<div class="{arg2}" style="color:{arg1};">cat</div> | |
</div> | |
<div class="some" style="color:red;"> | |
cat | |
</div> | |
// Nested and dependant macros are allowed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment