Skip to content

Instantly share code, notes, and snippets.

@coder0107git
Created August 26, 2023 02:09
Show Gist options
  • Save coder0107git/7cc18e017b64a99afab7f82134f8d4ba to your computer and use it in GitHub Desktop.
Save coder0107git/7cc18e017b64a99afab7f82134f8d4ba to your computer and use it in GitHub Desktop.
Use `htm` easily
import htm from "https://esm.sh/htm";
import vhtml from "https://esm.sh/vhtml";
const html = htm.bind(vhtml);
function string2Nodes(string) {
const container = document.createElement("div");
container.innerHTML = string;
return container.childNodes;
}
function render(code, parent = document.body, debug = false, debugLogger = null) {
parent ??= document.body;
debugLogger ??= console.debug;
let children = code;
debug = debug === true ? debugLogger : (...params) => {};
debug(`is Array: ${Array.isArray(code)}, typeof: ${typeof code}`);
// Put the code in an array if not iterable
if(
code === null
|| code === undefined
|| typeof code[Symbol.iterator] !== "function" // Is not iterable
) {
code = [code];
}
children.forEach((value, index) => {
if(
typeof value === "string"
|| value instanceof String
) {
// Log the current string state
debug(children);
children.splice(
index, // Index of node to replace
1, // How many nodes to replace
...string2Nodes(value), // The substitute nodes
);
}
});
// Log the final result
debug(children);
return parent.append(...children);
}
export {
htm,
vhtml,
html,
string2Nodes,
render,
};
import { render, html } from "./code.js";
render(html`
<style>
#hello {
color: blue;
}
</style>
<h1 id=hello>Hello world!</h1>
<p>Hello! 👋</p>
`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment