split-test-context.tsx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { createContext, FC, useContext, useMemo } from 'react'
  2. import getMeta from '../../utils/meta'
  3. import { SplitTestInfo } from '../../../../types/split-test'
  4. export const SplitTestContext = createContext<
  5. | {
  6. splitTestVariants: Record<string, string>
  7. splitTestInfo: Record<string, SplitTestInfo>
  8. }
  9. | undefined
  10. >(undefined)
  11. export const SplitTestProvider: FC<React.PropsWithChildren> = ({
  12. children,
  13. }) => {
  14. const value = useMemo(
  15. () => ({
  16. splitTestVariants: getMeta('ol-splitTestVariants') || {},
  17. splitTestInfo: getMeta('ol-splitTestInfo') || {},
  18. }),
  19. []
  20. )
  21. return (
  22. <SplitTestContext.Provider value={value}>
  23. {children}
  24. </SplitTestContext.Provider>
  25. )
  26. }
  27. export function useSplitTestContext() {
  28. const context = useContext(SplitTestContext)
  29. if (!context) {
  30. throw new Error(
  31. 'useSplitTestContext is only available within SplitTestProvider'
  32. )
  33. }
  34. return context
  35. }
  36. export function useFeatureFlag(name: string) {
  37. const { splitTestVariants } = useSplitTestContext()
  38. return splitTestVariants[name] === 'enabled'
  39. }
  40. export function useSplitTest(name: string): {
  41. variant: string | undefined
  42. info: SplitTestInfo | undefined
  43. } {
  44. const { splitTestVariants, splitTestInfo } = useSplitTestContext()
  45. return {
  46. variant: splitTestVariants[name],
  47. info: splitTestInfo[name],
  48. }
  49. }