import { Context, createContext, Dispatch, ReactElement, useContext, useReducer } from "react"; import { reducer, Action, ToggleType } from "./reducer" import { Status, Syllable, SylPart, Tone } from "./types"; import { isEnabled } from "./utils"; export interface IState { sylCount: number, sylPause: number, initiales: SylPart[], finales: SylPart[], allInitiales: boolean, allfinales: boolean, foundSyllables: Syllable[], foundTones: Tone[], randomTones: Tone[], allEnabled: (type: ToggleType) => false, isEnabled: (type: ToggleType, index: string) => false, isFound: () => false, status: Status } export interface IStore { state: Partial dispatch: Dispatch } export const defaultState:Object = { sylCount: 10, sylPause: 3, allfinales: false, allInitiales: false, finales: [] as SylPart[], initiales: [] as SylPart[], foundSyllables: [], foundTones: [], randomTones: [], allEnabled: function(type: ToggleType) { if ( type === ToggleType.init ) return (this as IState).allInitiales if ( type === ToggleType.fin ) return (this as IState).allfinales return false }, isEnabled: function(type: ToggleType, index: string) { if ( type === ToggleType.init ) return isEnabled((this as IState).initiales!, index) if ( type === ToggleType.fin ) return isEnabled((this as IState).finales!, index) return false }, isFound: function():boolean { return (this as IState).foundSyllables!.length > 0 }, status: Status.params } export const AppContext:Context = createContext({ state: defaultState as IState, dispatch: () => null }) export const useStateContext = () => useContext(AppContext); export const StateProvider = ({ children }: { children: ReactElement }) => { const [state, dispatch] = useReducer(reducer, defaultState as IState); return }