-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathreact.tsx
187 lines (163 loc) · 5.64 KB
/
react.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
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
import React, {
createContext,
FC,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import Emitter from './utils/emitter';
const events = new Emitter();
import { IFlagsmith, IFlagsmithTrait, IFlagsmithFeature, IState } from './types'
export const FlagsmithContext = createContext<IFlagsmith<string,string> | null>(null)
export type FlagsmithContextType = {
flagsmith: IFlagsmith // The flagsmith instance
options?: Parameters<IFlagsmith['init']>[0] // Initialisation options, if you do not provide this you will have to call init manually
serverState?: IState
children: React.ReactNode;
}
export const FlagsmithProvider: FC<FlagsmithContextType> = ({
flagsmith, options, serverState, children,
}) => {
const firstRenderRef = useRef(true)
if (flagsmith && !flagsmith?._trigger) {
flagsmith._trigger = () => {
// @ts-expect-error using internal function, consumers would never call this
flagsmith.log("React - trigger event received")
events.emit('event');
}
}
if (flagsmith && !flagsmith?._triggerLoadingState) {
flagsmith._triggerLoadingState = () => {
events.emit('loading_event');
}
}
if (serverState && !flagsmith.initialised) {
flagsmith.setState(serverState)
}
if (firstRenderRef.current) {
firstRenderRef.current = false
if (options) {
flagsmith.init({
...options,
state: options.state || serverState,
onChange: (...args) => {
if (options.onChange) {
options.onChange(...args)
}
},
})
}
}
return (
<FlagsmithContext.Provider value={flagsmith}>
{children}
</FlagsmithContext.Provider>
)
}
const useConstant = function <T>(value: T): T {
const ref = useRef(value)
if (!ref.current) {
ref.current = value
}
return ref.current
}
const flagsAsArray = (_flags: any): string[] => {
if (typeof _flags === 'string') {
return [_flags]
} else if (typeof _flags === 'object') {
// eslint-disable-next-line no-prototype-builtins
if (_flags.hasOwnProperty('length')) {
return _flags
}
}
throw new Error(
'Flagsmith: please supply an array of strings or a single string of flag keys to useFlags',
)
}
const getRenderKey = (flagsmith: IFlagsmith, flags: string[], traits: string[] = []) => {
return flags
.map((k) => {
return `${flagsmith.getValue(k)}${flagsmith.hasFeature(k)}`
}).concat(traits.map((t) => (
`${flagsmith.getTrait(t)}`
)))
.join(',')
}
export function useFlagsmithLoading() {
const flagsmith = useContext(FlagsmithContext);
const [loadingState, setLoadingState] = useState(flagsmith?.loadingState);
const [subscribed, setSubscribed] = useState(false);
const refSubscribed = useRef(subscribed)
const eventListener = useCallback(() => {
setLoadingState(flagsmith?.loadingState);
}, [flagsmith])
if (!refSubscribed.current) {
events.on('loading_event', eventListener)
refSubscribed.current = true
}
useEffect(() => {
if (!subscribed && flagsmith?.initialised) {
events.on('loading_event', eventListener)
setSubscribed(true)
}
return () => {
if (subscribed) {
events.off('loading_event', eventListener)
}
};
}, [flagsmith, subscribed, eventListener])
return loadingState
}
export function useFlags<F extends string=string, T extends string=string>(_flags: readonly F[], _traits: readonly T[] = []): {
[K in F]: IFlagsmithFeature
} & {
[K in T]: IFlagsmithTrait
} {
const firstRender = useRef(true)
const flags = useConstant<string[]>(flagsAsArray(_flags))
const traits = useConstant<string[]>(flagsAsArray(_traits))
const flagsmith = useContext(FlagsmithContext)
const [renderRef, setRenderRef] = useState(getRenderKey(flagsmith as IFlagsmith, flags, traits));
const eventListener = useCallback(() => {
const newRenderKey = getRenderKey(flagsmith as IFlagsmith, flags, traits)
if (newRenderKey !== renderRef) {
// @ts-expect-error using internal function, consumers would never call this
flagsmith?.log("React - useFlags flags and traits have changed")
setRenderRef(newRenderKey)
}
}, [renderRef])
const emitterRef = useRef(events.once('event', eventListener));
if (firstRender.current) {
firstRender.current = false;
// @ts-expect-error using internal function, consumers would never call this
flagsmith?.log("React - Initialising event listeners")
}
useEffect(()=>{
return () => {
emitterRef.current?.()
}
}, [])
const res = useMemo(() => {
const res: any = {}
flags.map((k) => {
res[k] = {
enabled: flagsmith!.hasFeature(k),
value: flagsmith!.getValue(k),
}
}).concat(traits?.map((v) => {
res[v] = flagsmith!.getTrait(v)
}))
return res
}, [renderRef])
return res
}
export function useFlagsmith<F extends string=string, T extends string=string>() {
const context = useContext(FlagsmithContext)
if (!context) {
throw new Error('useFlagsmith must be used with in a FlagsmithProvider')
}
return context as IFlagsmith<F, T>
}