This repository has been archived by the owner on Feb 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
412 lines (350 loc) · 12 KB
/
index.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import setHooks, * as hooks from "any-hooks"
export * from 'any-hooks'
export default setHooks
const listeners = globalThis.__uhxListeners || (globalThis.__uhxListeners = {}),
values = globalThis.__uhxValues || (globalThis.__uhxValues = {})
export function useChannel(key, init, deps=[]) {
let [, setState] = hooks.useState()
let initKey = hooks.useRef()
hooks.useMemo(() => {
(listeners[key] || (listeners[key] = [])).push(setState)
if (init === undefined) return
// if (key in values) return console.warn(`Channel ${key} is already initialized.`)
if (
!(key in values) || // init run
initKey.current === key // or deps changed
) {
initKey.current = key
if (typeof init === 'function') init = init()
values[key] = init
if (init && init.then) init.then(init => setState(values[key] = init))
}
}, [key, ...deps])
hooks.useLayoutEffect(() => () => {
listeners[key].splice(listeners[key].indexOf(setState) >>> 0, 1)
if (!listeners[key].length) {
delete values[key]
}
}, [key, ...deps])
return [values[key], (value) => {
values[key] = typeof value === 'function' ? value(values[key]) : value
listeners[key].map((setState) => setState(value))
}]
}
export function useAction(key, init, deps = []) {
let [action, setAction] = useChannel('__uhx:action-' + key, init !== undefined ? () => init : undefined, deps)
return hooks.useMemo(() => {
if (typeof action !== 'function') return [action]
action[Symbol.iterator] = function*() { yield action; yield setAction; }
return action
}, [action, ...deps])
}
export function useStorage(key, init, o) {
o = { storage: window.localStorage, prefix: '__uhx:storage-', ...(o || {}) }
let storeKey = o.prefix + key
let [value, setValue] = useChannel(key, () => {
// init from stored value, if any
let stored = o.storage.getItem(storeKey)
if (stored != null) stored = JSON.parse(stored)
if (typeof init === 'function') return init(stored)
return stored == null ? init : stored
})
hooks.useMemo(() => {
// persist initial value, if store is rewired
if (init === undefined) return
if (o.storage.getItem(storeKey) == null) o.storage.setItem(storeKey, JSON.stringify(value))
}, [key])
hooks.useEffect(() => {
// notify listeners, subscribe to storage changes
let update = e => {
if (e.key !== storeKey) return
setValue(e.newValue)
}
window.addEventListener('storage', update)
return () => window.removeEventListener('storage', update)
}, [key])
return [value, (value) => {
setValue(value)
// side-effect write
o.storage.setItem(storeKey, JSON.stringify(value))
}]
}
wrapHistory('push')
wrapHistory('replace')
enableNavigateEvent()
export function useSearchParam(key, init) {
let [value, setValue] = useChannel('__uhx:search-param-' + key, () => {
let params = new URLSearchParams(window.location.search)
let param
if (params.has(key)) param = params.get(key)
if (typeof init === 'function') return init(param)
return param == null ? init : param
})
hooks.useMemo(() => {
if (init === undefined) return
let params = new URLSearchParams(window.location.search)
if (!params.has(key)) {
params.set(key, value)
setURLSearchParams(params)
}
}, [key])
hooks.useEffect(() => {
const update = (e) => {
let params = new URLSearchParams(window.location.search)
let newValue = params.get(key)
// FIXME: there's a test case failing here from wishbox - lang didn't switch more than once.
// if (newValue !== value) setValue(newValue)
setValue(newValue)
}
window.addEventListener('popstate', update)
window.addEventListener('pushstate', update)
window.addEventListener('replacestate', update)
window.addEventListener('navigate', update)
return () => {
window.removeEventListener('popstate', update)
window.removeEventListener('pushstate', update)
window.removeEventListener('replacestate', update)
window.removeEventListener('navigate', update)
}
}, [key])
return [value, value => {
let params = new URLSearchParams(window.location.search)
params.set(key, value)
setURLSearchParams(params)
}]
}
function setURLSearchParams(params) {
let str = params.toString()
window.history.replaceState(null, '', str ? '?' + str : window.location.href.split('?')[0])
}
// https://stackoverflow.com/a/25673946/1052640
// https://github.com/lukeed/navaid/blob/master/src/index.js#L80-L90
function wrapHistory(type) {
type += 'State'
const fn = history[type]
history[type] = function (uri) {
let result = fn.apply(this, arguments)
let ev = new Event(type.toLowerCase())
ev.uri = uri
ev.arguments = arguments
window.dispatchEvent(ev)
return result
}
return () => {
history[type] = fn
}
}
// https://github.com/WebReflection/onpushstate
// https://github.com/lukeed/navaid/blob/master/src/index.js#L52-L60
function enableNavigateEvent() {
const handleNavigate = (e) => {
// find the link node (even if inside an opened Shadow DOM)
var target = e.target.shadowRoot ? e.path[0] : e.target;
// find the anchor
var anchor = target.closest('A')
// if found
if (!anchor) return
// it's not a click with ctrl/shift/alt keys pressed
// => (let the browser do it's job instead)
if (!e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey && !e.button && !e.defaultPrevented) return
// it's for the current page
if (!/^(?:_self)?$/i.test(anchor.target)) return
// same origin
if (anchor.host !== location.host) return
// it's not a download
if (anchor.hasAttribute('download')) return
// it's not a resource handled externally
if (anchor.getAttribute('rel') === 'external') return
// let empty links be (see issue #5)
if (!anchor.href) return
var e = new Event('navigate');
window.dispatchEvent(e);
}
document.addEventListener('click', handleNavigate, true)
return () => document.removeEventListener('click', handleNavigate)
}
export function useCountdown(n, interval = 1000) {
const [count, set] = hooks.useState(n)
const reset = hooks.useCallback(() => set(n), [n])
const schedule = hooks.useMemo(() => {
return typeof interval === 'function' ? interval : fn => {
let id = setInterval(fn, interval)
return () => clearInterval(id)
}
}, [interval])
hooks.useEffect(() => {
const unschedule = schedule(() => {
set(count => {
if (count <= 0) return (unschedule(), 0)
else return count - 1
})
})
return unschedule
}, [n, schedule])
return [count, reset]
}
export function usePrevious(value) {
let ref = hooks.useRef()
hooks.useEffect(() => {
ref.current = value
}, [value])
return ref.current
}
export function useUpdate() {
let [, set] = hooks.useState(0)
let update = hooks.useCallback(() => set(s => ~s), [])
return update
}
export function useValidate(validator, init) {
let check = hooks.useCallback((value) => {
if (!validator) return null
let check = (value, validator) => {
try {
var valid = validator(value)
if (valid === true || valid == null) {
return null
}
throw valid
} catch (e) {
return e
}
}
if (Array.isArray(validator)) {
for (let i = 0, error; i < validator.length; i++) {
error = check(value, validator[i])
if (error !== null) return error
}
return null
}
return check(value, validator)
}, [])
let [error, setError] = hooks.useState(init != null ? () => check(init) : null)
let validate = hooks.useCallback((value) => {
let error = check(value, validator)
setError(error)
return error == null
}, [])
return [error, validate]
}
export function useFormField(props = {}) {
const prefix = '__uhx:form-field-'
let { value='', validate: rules, required, persist, ...inputProps } = props
let key = inputProps.name || inputProps.id || inputProps.key
let inputRef = hooks.useRef()
let [init, setValue] = persist ? useStorage(key, value, { storage: window.sessionStorage, prefix }) : useChannel(key, value)
let [focus, setFocus] = hooks.useState(false)
let [error, validate] = useValidate(rules || (required ? v => !!v : null))
let field = hooks.useMemo(() => {
let getValue = () => field.value
let field = Object.create(
// invisible, not enumerable (interface)
{
valueOf: getValue,
[Symbol.toPrimitive]: getValue,
[Symbol.iterator]: function* () {
yield { ...field } // leave only enumerables (input props)
yield field
}
}, {
// invisible, enumerable (input props)
// FIXME: there's no way to define invisible + enumerable for spread
onBlur: {
enumerable: true, value: e => {
setFocus(field.focus = false)
// revert error to the last value
field.validate()
}
},
onFocus: {
enumerable: true, value: e => {
field.touched = true
field.error = null
field.valid = true
setFocus(field.focus = true)
}
},
onChange: { enumerable: true, value: e => field.set(e.target.value) },
onInput: { enumerable: true, value: e => field.set(e.target.value) },
// visible, not enumerable (field state)
error: { enumerable: false, writable: true, value: null },
valid: { enumerable: false, writable: true, value: true },
focus: { enumerable: false, writable: true, value: false },
touched: { enumerable: false, writable: true, value: false },
set: {
enumerable: false, value: (v) => {
setValue(field.value = v)
if (!field.focus) field.validate()
}
},
reset: {
enumerable: false, value: () => {
setValue(field.value = init)
field.error = null
field.valid = true
field.touched = false
}
},
validate: {
enumerable: false, value: (value = field.value) => field.valid = validate(value)
}
})
// visible, enumerable (field state + input props)
Object.assign(field, {
value: init,
required,
ref: inputRef,
})
return field
}, [])
// sync error with useValidate, recover from focus as well
hooks.useMemo(() => {
if (!field.focus) field.error = error
}, [error, field.focus])
// update input props whenever they change
hooks.useMemo(() => {
Object.assign(field, inputProps)
}, Object.keys(inputProps).map(key => inputProps[key]))
return field
}
export function useInput(ref, init) {
if (ref.nodeType) ref = { current: ref }
let key = '__uhx:input-' + (ref.current && `${ref.current.id || ''}:${ref.current.type || 'text'}:${ref.current.name || ''}`)
let [value, setValue] = useChannel(key, () => {
// init from input
let value = ref.current && ref.current.value
if (value != null) {
if (typeof init === 'function') return init(value)
return value
}
return init
})
hooks.useMemo(() => {
// write value if input is rewired
if (init === undefined) return
if (ref.current && ref.current.value == null) {
ref.current.setAttribute('value', ref.current.value = value)
if (value == null) ref.current.removeAttribute(value)
}
}, [ref.current])
hooks.useEffect(() => {
// notify listeners, subscribe to input changes
let update = e => setValue(e.target.value)
ref.current.addEventListener('input', update)
ref.current.addEventListener('change', update)
return () => {
ref.current.removeEventListener('input', update)
ref.current.removeEventListener('change', update)
}
}, [ref.current])
return [value, (value) => {
setValue(value)
// main write to input
ref.current.setAttribute('value', ref.current.value = value)
if (value == null) ref.current.removeAttribute('value')
}]
}
export function useObservable(v) {
let [state, setState] = hooks.useState(v())
hooks.useEffect(() => v(v => setState(v)), [])
return [state, state => v(state)]
}