Return

All tests / src/context dialog.tsx

90.9% Statements 20/22
83.33% Branches 5/6
75% Functions 3/4
90.47% Lines 19/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 67 685x                       5x         5x   5x 5x   2x         1x         1x         1x                   5x 15x 15x       5x 16x   16x 2x   14x       14x     16x  
import * as React from 'react';
type ContextProviderProps = { children: React.ReactNode };
type StateContextType = { state: State; dispatch: Dispatch } | undefined;
type Dispatch = (action: Action) => void;
type Action = {
    type: 'alternate' | 'open' | 'close' | 'toggleLang';
};
type State = {
    open: boolean;
    lang: boolean;
};
 
const defaultValues = {
    open: true,
    lang: false,
};
 
const DialogStateContext = React.createContext<StateContextType>(undefined);
 
const dialogReducer = (state: State, action: Action) => {
    switch (action.type) {
        case 'alternate':
            return {
                ...state,
                open: !state.open,
            };
        case 'open':
            return {
                ...state,
                open: true,
            };
        case 'close':
            return {
                ...state,
                open: false,
            };
        case 'toggleLang':
            return {
                ...state,
                lang: !state.lang,
            };
 
        default:
            throw new Error(`Unknown action type: ${action.type}`);
    }
};
 
const DialogProvider = ({ children }: ContextProviderProps) => {
    const [state, dispatch] = React.useReducer(dialogReducer, defaultValues);
    const value = { state, dispatch };
    return <DialogStateContext.Provider value={value}>{children}</DialogStateContext.Provider>;
};
 
const useDialog = () => {
    const context = React.useContext(DialogStateContext);
 
    if (context === undefined) {
        throw new Error('useDialog must be used within a DialogProvider');
    }
    const dialog = (dispatch: (arg0: State, arg1: Dispatch) => void) => {
        dispatch(context.state, context.dispatch);
    };
 
    return { ...context.state, dispatch: context.dispatch, dialog };
};
 
export { DialogProvider, useDialog };