Last active
July 14, 2019 20:38
-
-
Save ezekielchentnik/239ea373fbbc95ececefbf91266336a7 to your computer and use it in GitHub Desktop.
replace react
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
let I = 'data-id' | |
let s = 'string' | |
let n = 'number' | |
let d = document | |
let O = Object | |
let a = (el, x) => | |
x.reduce((e, c) => { | |
e.appendChild(c instanceof HTMLElement ? c : d.createTextNode(c)) | |
return e | |
}, el) | |
let _a = (el, h) => | |
O.keys(h || {}).reduce((e, key) => { | |
if (key.includes('on')) { | |
e.addEventListener(key.split('on')[1].toLowerCase(), h[key]) | |
} else { | |
e.setAttribute(key, h[key]) | |
} | |
return e | |
}, el) | |
let c = h => (el, i) => { | |
if (typeof el === s || typeof el === n) { | |
return el | |
} | |
let _h = { | |
...el.h, | |
[I]: h[I]+'.'+i | |
} | |
return { | |
...el, | |
h: _h, | |
x: (el.x || []).map(c(_h)) | |
} | |
} | |
let h = (tag, h, ...x) => { | |
let _h = { | |
...h, | |
[I]: ((h || {})[I] || '1') | |
} | |
if (x.length === 1 && (typeof x[0] === 'object' && O.keys(x[0]).reduce((acc, k) => acc && !isNaN(k), !0))) { | |
x = O.values(x[0]) | |
} | |
return { | |
tag, | |
h: _h, | |
x: x.map(c(_h)) | |
} | |
} | |
let _ = el => { | |
if (typeof el === s || typeof el === n) { | |
return el | |
} | |
let { | |
h, | |
x = [] | |
} = el | |
let Tag = el.tag | |
return typeof Tag === 'function' ? (new Tag((h || {}), ...x))._ : a(_a(d.createElement(Tag), h), x.map(_)) | |
} | |
class Component { | |
constructor(props = {}, ...x) { | |
this.props = props | |
this.x = x | |
} | |
get el() { | |
return (els => els.length > 1 ? els : els[0])(d.querySelectorAll(`[${I}=${this.props[I]}]`)) | |
} | |
get _() { | |
return _( | |
h( | |
'div', { | |
[I]: this.props[I] | |
}, | |
[this.render()] | |
).x[0] | |
) | |
} | |
setState(part) { | |
let self = this | |
let b = self.el | |
self.state = { | |
...self.state, | |
...part | |
} | |
if (b) { | |
b.parentNode.replaceChild(self._, b, self._) | |
} | |
} | |
} | |
let render = (C, target) => a(target, [new C()._]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment