-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathuseInspect.ts
55 lines (53 loc) · 1.8 KB
/
useInspect.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
51
52
53
54
55
import {
Dispatch,
SetStateAction,
useCallback,
useEffect,
useState
} from 'react'
import {
useJsonViewerStore
} from '../stores/JsonViewerStore'
import { useIsCycleReference } from './useIsCycleReference'
export function useInspect (path: (string | number)[], value: any, nestedIndex?: number) {
const depth = path.length
const isTrap = useIsCycleReference(path, value)
const getInspectCache = useJsonViewerStore(store => store.getInspectCache)
const setInspectCache = useJsonViewerStore(store => store.setInspectCache)
const defaultInspectDepth = useJsonViewerStore(
store => store.defaultInspectDepth)
useEffect(() => {
const inspect = getInspectCache(path, nestedIndex)
if (inspect === undefined) {
if (nestedIndex !== undefined) {
setInspectCache(path, false, nestedIndex)
} else {
// do not inspect when it is a cycle reference, otherwise there will have a loop
const inspect = isTrap
? false
: depth < defaultInspectDepth
setInspectCache(path, inspect)
}
}
}, [defaultInspectDepth, depth, getInspectCache, isTrap, nestedIndex, path, setInspectCache])
const [inspect, set] = useState<boolean>(() => {
const shouldInspect = getInspectCache(path, nestedIndex)
if (shouldInspect === undefined) {
if (nestedIndex !== undefined) {
return false
}
return isTrap
? false
: depth < defaultInspectDepth
}
return shouldInspect
})
const setInspect = useCallback<Dispatch<SetStateAction<boolean>>>((apply) => {
set((oldState) => {
const newState = typeof apply === 'boolean' ? apply : apply(oldState)
setInspectCache(path, newState, nestedIndex)
return newState
})
}, [nestedIndex, path, setInspectCache])
return [inspect, setInspect] as const
}