-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh.js
258 lines (226 loc) · 5.61 KB
/
h.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
const CHILDREN = 'children'
/**
* hyperscript...
* no components; facilitates rendering into DOM
* @param {string|Node} e element
* @param {object} p props
* @param {string|string[]|Node|Node[]} c children
* @returns {Node}
*/
export function render (e, p = {}, c) {
// support for `hooked` functional components
if (typeof e === 'function') {
return withHook(e, { ...p, [CHILDREN]: c })
}
const $ = typeof e === 'string' ? document.createElement(e) : e
Object.entries(p || {}).forEach(([k, v]) => {
if (k.indexOf('on') === 0) {
$.addEventListener(k.substring(2).toLowerCase(), v)
} else if (k === 'style') {
Object.entries(v).forEach(([p, v]) => { $[k][p] = v })
} else if (k === 'ref') {
v && v($) // pass DOM reference
} else if (k.indexOf('data-') === 0) {
$.dataset[k.substring(5)] = v
} else if (k === CHILDREN) {
// do nothing
} else {
$[k] = v
}
})
$.append(...[].concat(c).filter(c => c != null).map(mapChild).flat())
return $
}
/**
* wrap hyperscript render to allow later re-render
* @param {string|Node} e element
* @param {object} p props
* @param {string|string[]|Node|Node[]} c children
* @returns {function}
*/
export const h = (e, p, c) => (np) => render(e, np || p || {}, c)
/**
* Fragment component
* @param {object} props
* @param {string|string[]|Node|Node[]} props.children
* @returns
*/
export const Fragment = (props) => props[CHILDREN]
/**
* @private
*/
const mapChild = (c) =>
(typeof c === 'function')
? c()
: c
/// ---- hooks ----
let hooks
let index = 0
let updateF
let current
/**
* guard and restore the current global state on each render
* @private
*/
const guard = (fn) => {
const state = [hooks, updateF, current]
// execute recursive fn
fn()
// restore
hooks = state[0]
updateF = state[1]
current = state[2]
}
const hasChanged = (a, b) => !a || b.some((arg, i) => arg !== a[i])
const getHook = value => {
let hook = hooks[index++]
if (!hook) {
hook = { value }
hooks.push(hook)
}
return hook
}
/**
* @see https://reactjs.org/docs/hooks-reference.html#usereducer
*/
export const useReducer = (reducer, initialState) => {
const hook = getHook(initialState)
const update = updateF
const setState = state => {
hook.value = reducer(hook.value, state)
update()
}
return [hook.value, setState]
}
/**
* @see https://reactjs.org/docs/hooks-reference.html#usestate
*/
export const useState = (initialState) => useReducer(
(_, v) => v,
initialState
)
/**
* @see https://reactjs.org/docs/hooks-reference.html#useeffect
* @note no cleanup supported; A returned function from useEffect won't be called
*/
export const useEffect = (cb, args = []) => {
const hook = getHook()
if (hasChanged(hook.value, args)) {
hook.value = args
hook.cb = cb
}
}
/**
* @see https://reactjs.org/docs/hooks-reference.html#usememo
*/
export const useMemo = (cb, args = []) => {
const hook = getHook()
if (hasChanged(hook.value, args)) {
hook.value = args
hook.memo = cb()
}
return hook.memo
}
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecallback
*/
export const useCallback = (cb, args) => useMemo(() => cb, args)
/**
* @see https://reactjs.org/docs/hooks-reference.html#useref
*/
export const useRef = () => {
function f (ref) {
f.current = ref
}
f.current = null
return f
}
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecontext
*/
export const createContext = (context) => {
const _context = {
Provider,
Consumer
}
function Provider ({ value, tag = 'div', ...p }) {
// mount provider
const $ = render(tag, { 'data-type': 'provider' }, p[CHILDREN])
$._context = _context
$._value = { ...context, ...value }
return $
}
function Consumer (p) {
const props = useContext(_context)
return p[CHILDREN][0](props)
}
return _context
}
export const useContext = (context) => {
const $ = current
if ($._value) {
const v = $._value
$._value = null
return v
}
const update = updateF
useEffect(() => {
let n = $
while ((n = n.parentNode)) {
if (n._context === context) {
$._value = n._value
// HINT start re-render of $
update()
return // break the loop
}
}
})
return {}
}
let id = 0
/**
* HoC to wrap functional components with hooks
* @param {function} fn functional component with hooks
* @param {object} [props] properties
* @returns {Node}
*/
const withHook = (fn, props) => {
let childs
// hooks and state is maintained on comment nodes
const $ = document.createComment('' + id++)
// for functional components flatten nested children arrays
props[CHILDREN] = [props[CHILDREN]].flat()
function render () {
// setup
index = 0
hooks = $._hs || []
updateF = render
current = $
// render
childs = [].concat(fn(props)).filter(c => c != null).map(mapChild).flat()
$._cs && $._cs.forEach(c => c.remove()) // brutally remove childs (e.g. scroll-state might get lost!)
$._cs = childs
$.after(...$._cs)
// update
$._hs = hooks
// postrender (only after things got mounted in DOM)
let cycle = 0
const postRender = () => {
if (!$.isConnected || !$.parentNode) {
return cycle++ < 5
? window.requestAnimationFrame(postRender)
: console.error('cycle detected in', $)
}
// call useEffect callbacks
$._hs.forEach(h => {
const cb = h.cb
h.cb = null // prevent looping through useContext
cb && cb()
})
}
postRender()
}
// initial render
guard(render)
return [$, ...childs]
}