2024-01-26 09:23:48 +00:00
|
|
|
import { createContext, FC, useContext, useMemo } from 'react'
|
|
|
|
import getMeta from '../../utils/meta'
|
2024-10-08 08:25:49 +00:00
|
|
|
import { SplitTestInfo } from '../../../../types/split-test'
|
2024-01-26 09:23:48 +00:00
|
|
|
|
|
|
|
export const SplitTestContext = createContext<
|
|
|
|
| {
|
2024-10-08 08:25:49 +00:00
|
|
|
splitTestVariants: Record<string, string>
|
|
|
|
splitTestInfo: Record<string, SplitTestInfo>
|
2024-01-26 09:23:48 +00:00
|
|
|
}
|
|
|
|
| undefined
|
|
|
|
>(undefined)
|
|
|
|
|
|
|
|
export const SplitTestProvider: FC = ({ children }) => {
|
|
|
|
const value = useMemo(
|
|
|
|
() => ({
|
|
|
|
splitTestVariants: getMeta('ol-splitTestVariants') || {},
|
|
|
|
splitTestInfo: getMeta('ol-splitTestInfo') || {},
|
|
|
|
}),
|
|
|
|
[]
|
|
|
|
)
|
|
|
|
|
|
|
|
return (
|
|
|
|
<SplitTestContext.Provider value={value}>
|
|
|
|
{children}
|
|
|
|
</SplitTestContext.Provider>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useSplitTestContext() {
|
|
|
|
const context = useContext(SplitTestContext)
|
|
|
|
|
|
|
|
if (!context) {
|
|
|
|
throw new Error(
|
|
|
|
'useSplitTestContext is only available within SplitTestProvider'
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return context
|
|
|
|
}
|
2024-04-30 14:58:34 +00:00
|
|
|
|
|
|
|
export function useFeatureFlag(name: string) {
|
|
|
|
const { splitTestVariants } = useSplitTestContext()
|
|
|
|
return splitTestVariants[name] === 'enabled'
|
|
|
|
}
|
2024-10-08 08:25:49 +00:00
|
|
|
|
|
|
|
export function useSplitTest(name: string): {
|
|
|
|
variant: string | undefined
|
|
|
|
info: SplitTestInfo | undefined
|
|
|
|
} {
|
|
|
|
const { splitTestVariants, splitTestInfo } = useSplitTestContext()
|
|
|
|
|
|
|
|
return {
|
|
|
|
variant: splitTestVariants[name],
|
|
|
|
info: splitTestInfo[name],
|
|
|
|
}
|
|
|
|
}
|