Created
March 24, 2019 23:23
-
-
Save ForsakenHarmony/ec6ae7d3e9b9d67def37b771c525e20b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function h (tagName, attributes = {}, children = []) { | |
return { | |
tagName, | |
attributes, | |
children, | |
}; | |
} | |
function diffAttrs (element, attributes) { | |
const newAttrs = Object.keys(attributes); | |
const attrs = element.attributes; | |
for (let i = attrs.length - 1; i >= 0; i--) { | |
let name = attrs[i].name; | |
let value = attrs[i].value; | |
if (attributes[name]) { | |
newAttrs.splice(newAttrs.indexOf(name), 1); | |
if (attributes[name].toString() !== value) { | |
attrs[i].value = attributes[name]; | |
} | |
} else { | |
element.removeAttribute(name); | |
} | |
} | |
newAttrs.map(a => { | |
if (a[0] === 'o' && a[1] === 'n') { | |
const name = a.toLowerCase().substr(2); | |
if (!element._listen || !element._listen[name]) | |
element.addEventListener(name, eventProxy, false); | |
(element._listen || (element._listen = {}))[name] = attributes[a]; | |
} else { | |
element.setAttribute(a, attributes[a]); | |
} | |
}); | |
} | |
function eventProxy(e) { | |
return this._listen[e.type](e); | |
} | |
function diff (parent, nodes, isSvg = false) { | |
const children = Array.from(parent.childNodes).reverse(); | |
nodes.map(n => { | |
if (!n) return; | |
n = n.tagName ? n : n.toString(); | |
isSvg = n.tagName === 'svg' || isSvg; | |
let el = children.pop(); | |
while (el && (el.tagName && el.tagName.toLowerCase()) !== n.tagName && children.length >= 0) { | |
el.remove(); | |
el = children.pop(); | |
} | |
if (!el) { | |
el = typeof n === 'string' ? document.createTextNode(n) : isSvg ? document.createElementNS('http://www.w3.org/2000/svg', n.tagName) : document.createElement(n.tagName); | |
parent.appendChild(el); | |
} | |
if (typeof n === 'string') return; | |
diffAttrs(el, n.attributes); | |
diff(el, n.children, isSvg); | |
}); | |
children.map(c => parent.removeChild(c)); | |
} | |
const parent = document.querySelector('main'); | |
diff(parent, [h('span')]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment