This repository was archived by the owner on Mar 27, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathFlagContext.tsx
66 lines (58 loc) · 1.67 KB
/
FlagContext.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
import * as React from 'react';
import * as queryString from 'query-string';
export type FlagContainer = { [key: string]: any };
/**
* FlagContext stores feature flags and passes them to consumers
*/
interface IFlagContext {
/**
* Contains a list of all currently-active flags
*/
flags: FlagContainer;
}
const FlagContext = React.createContext<IFlagContext>({flags: []});
/**
* `useFlags` returns all feature flags.
*
* @return {FlagContainer} flags All project feature flags
*/
const useFlags = () : FlagContainer => {
const {flags} = React.useContext(FlagContext);
return flags;
};
interface IURLFlagProviderProps {
children: React.ReactNode,
location: Location
}
/**
* `URLFlagProvider` is a provider for FlagContext.
* It is passed the current URL and parses the
* "flags" parameter, assumed to be a comma-separated
* list of currently-active flags.
* @param {URL} location : the current URL object
* @param {ReactNode} children : the children components
* @return {ReactNode} URLFlagProvider component
**/
const URLFlagProvider = ({children, location}: IURLFlagProviderProps) => {
const flagString = queryString.parse(location.search).flags;
const flags : FlagContainer = {};
let flagList: string[] = [];
if (flagString && typeof flagString === 'string') {
flagList = (flagString as string).split(',');
}
for (const flag of flagList) {
if (flag.includes('=')) {
const [key, value] = flag.split('=');
flags[key] = value;
} else {
flags[flag] = true;
}
}
return (
<FlagContext.Provider
value={{flags}}>
{children}
</FlagContext.Provider>
);
};
export {FlagContext, URLFlagProvider, useFlags};