|
| 1 | +import { createContext, useContext, useState, ReactNode } from 'react' |
| 2 | +import { ProgramType } from '@pythnetwork/xc-admin-common' |
| 3 | +import { useQueryState, parseAsStringLiteral } from 'nuqs' |
| 4 | + |
| 5 | +/** |
| 6 | + * Interface defining the shape of the Program context |
| 7 | + */ |
| 8 | +interface ProgramContextType { |
| 9 | + /** |
| 10 | + * Currently selected program type |
| 11 | + */ |
| 12 | + programType: ProgramType |
| 13 | + |
| 14 | + /** |
| 15 | + * Function to set the current program type |
| 16 | + */ |
| 17 | + setProgramType: (type: ProgramType) => void |
| 18 | + |
| 19 | + /** |
| 20 | + * Whether the selected program is supported on the current cluster |
| 21 | + */ |
| 22 | + isProgramSupported: boolean |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Default context values |
| 27 | + */ |
| 28 | +const defaultContext: ProgramContextType = { |
| 29 | + programType: ProgramType.PYTH_CORE, |
| 30 | + setProgramType: () => undefined, |
| 31 | + isProgramSupported: true, |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Context for managing the currently selected Pyth program (Core, Lazer, etc.) |
| 36 | + */ |
| 37 | +const ProgramContext = createContext<ProgramContextType>(defaultContext) |
| 38 | + |
| 39 | +/** |
| 40 | + * Provider component for the Program context |
| 41 | + */ |
| 42 | +export const ProgramProvider = ({ children }: { children: ReactNode }) => { |
| 43 | + // Use URL query parameter to persist program selection across page reloads |
| 44 | + const [programTypeParam, setProgramTypeParam] = useQueryState( |
| 45 | + 'program', |
| 46 | + parseAsStringLiteral( |
| 47 | + Object.values(ProgramType) as readonly string[] |
| 48 | + ).withDefault(ProgramType.PYTH_CORE) |
| 49 | + ) |
| 50 | + |
| 51 | + // Local state for program support |
| 52 | + const [isProgramSupported] = useState(true) |
| 53 | + |
| 54 | + /** |
| 55 | + * Update both the URL parameter and context state |
| 56 | + */ |
| 57 | + const setProgramType = (type: ProgramType) => { |
| 58 | + setProgramTypeParam(type) |
| 59 | + } |
| 60 | + |
| 61 | + // TODO: Add effect to check if the selected program is supported on the current cluster |
| 62 | + // This will be implemented when we have the adapter implementations |
| 63 | + |
| 64 | + const value = { |
| 65 | + programType: programTypeParam as ProgramType, |
| 66 | + setProgramType, |
| 67 | + isProgramSupported, |
| 68 | + } |
| 69 | + |
| 70 | + return ( |
| 71 | + <ProgramContext.Provider value={value}>{children}</ProgramContext.Provider> |
| 72 | + ) |
| 73 | +} |
| 74 | + |
| 75 | +/** |
| 76 | + * Hook for accessing the Program context |
| 77 | + * @returns The Program context values |
| 78 | + */ |
| 79 | +export const useProgramContext = () => useContext(ProgramContext) |
0 commit comments