-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.tsx
84 lines (72 loc) · 2.08 KB
/
index.tsx
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
/**
* @file index.ts
* @author 余聪
*
*/
import { useContext } from 'react'
import * as React from 'react'
export interface Replacer<T = any, P extends T = T> {
with: T
as?: P
transformAs?: (input: T, replacer: this, ...args: any[]) => P
}
export function factory() {
const globalReplacerContextValues: Replacer[] = []
const ReplacerContext = React.createContext<Replacer[]>(globalReplacerContextValues)
// eslint-disable-next-line no-underscore-dangle
const _ReplacerProvider = ReplacerContext.Provider
const ReplacerConsumer = ReplacerContext.Consumer
const ReplacerProvider: React.FC<{
replacers?: Replacer[]
}> = ({ children, replacers = globalReplacerContextValues }) => (
// eslint-disable-next-line react/jsx-pascal-case
<_ReplacerProvider value={replacers}>{children}</_ReplacerProvider>
)
function useReplacers() {
return useContext(ReplacerContext)
}
function useReplacedValue<T, P extends T = T>(value: T, { extraArgs = [] }: { extraArgs?: any[] } = {}): P {
const replacers = useReplacers()
const extraArgsRef = React.useRef(extraArgs)
extraArgsRef.current = extraArgs
const matchReplacer = React.useMemo(() => {
if (replacers && replacers.length) {
return replacers.find((replacer) => replacer.with === value)
}
}, [replacers, value])
return (
React.useMemo(() => {
if (matchReplacer) {
if (typeof matchReplacer.transformAs === 'function') {
return matchReplacer.transformAs(matchReplacer.with, matchReplacer, ...extraArgsRef.current)
}
return matchReplacer.as
}
}, [matchReplacer]) || value
)
}
return {
globalReplacerContextValues,
ReplacerContext,
ReplacerConsumer,
ReplacerProvider,
useReplacers,
useReplacedValue
}
}
const {
globalReplacerContextValues,
ReplacerContext,
ReplacerConsumer,
ReplacerProvider,
useReplacers,
useReplacedValue
} = factory()
export {
globalReplacerContextValues,
ReplacerContext,
ReplacerConsumer,
ReplacerProvider,
useReplacers,
useReplacedValue
}