-
-
Save gordonbrander/36e47feca74a653495395d42efc3afa4 to your computer and use it in GitHub Desktop.
h.js - hyperscript micro implementation
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
// Set key on object, but only if value has changed. | |
// This is useful when setting keys on DOM elements, where setting the same | |
// value may trigger a style recalc. | |
// | |
// Note that the typical layout-triggering DOM properties are read-only, | |
// so this is safe to use to write to DOM element properties. | |
// See https://gist.github.com/paulirish/5d52fb081b3570c81e3a. | |
export const prop = (object, key, value) => { | |
if (object[key] !== value) { | |
object[key] = value | |
} | |
} | |
// Set properties of an element using an object | |
export const props = (element, props) => { | |
// Pluck out style and dataset for special handling. | |
// style and dataset are structured values that cannot be directly set as | |
// props. We destructure them so we can set them key-by-key. | |
let { | |
style={}, | |
dataset={}, | |
classes={}, | |
...ordinaryProps | |
} = props | |
// Set styles | |
for (let [key, value] of Object.entries(style)) { | |
prop(element.style, key, value) | |
} | |
// Set data | |
for (let [key, value] of Object.entries(dataset)) { | |
prop(element.dataset, key, value) | |
} | |
// Set classes | |
setClasses(element, classes) | |
// Set remaining properties | |
for (let [key, value] of Object.entries(ordinaryProps)) { | |
prop(element, key, value) | |
} | |
} | |
// Hyperscript-style element builder. | |
export const h = (tag, properties, ...children) => { | |
let element = document.createElement(tag) | |
props(element, properties) | |
element.replaceChildren(...children) | |
return element | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment