/
util.ts
50 lines (45 loc) · 1.12 KB
/
util.ts
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
import { watch as _watch } from '@histoire/vendors/vue'
import { applyState, clone } from '@histoire/shared'
function cleanupState (state: Record<string, any>): Record<string, any> {
const result = {}
for (const key in state) {
if (key === 'Hst') continue
const value = state[key]
if (typeof value === 'function') continue
if (typeof value === 'undefined') continue
if (value instanceof HTMLElement) continue
if (typeof value === 'object' && value.$$) continue
result[key] = value
}
return result
}
export function syncState (variantState, onChange: (state) => unknown) {
let syncing = false
const _stop = _watch(() => variantState, value => {
if (value == null) return
if (!syncing) {
syncing = true
onChange(cleanupState(value))
} else {
syncing = false
}
}, {
deep: true,
immediate: true,
})
function apply (value) {
if (value == null) return
if (!syncing) {
syncing = true
applyState(variantState, clone(cleanupState(value)))
} else {
syncing = false
}
}
return {
apply,
stop () {
_stop()
},
}
}