All files create.ts

96.87% Statements 62/64
95.65% Branches 22/23
100% Functions 11/11
96.87% Lines 62/64

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84          1x   1x 20x 20x     20x   20x 20x 20x   20x 96x 51x 51x 45x 96x   20x 22x 22x   20x 28x 28x   20x 22x 22x   20x 25x 25x 10x 25x 15x 15x 15x 15x 15x 25x   20x 1x 1x 1x 1x 1x     1x 1x 1x 20x   20x 20x 20x   1x 40x 40x 20x 20x 20x 20x 20x   20x 20x   1x 20x 20x 20x 20x  
import type { StoreContext } from './connect';
 
export interface State {
    value: Record<string, any>;
}
const rootMap = new WeakMap<State, any>();
 
export class StateContext {
    public readonly state: State;
    private readonly storeContext: Map<string, StoreContext<any>> = new Map<
        string,
        StoreContext<any>
    >();
 
    public constructor(state: State) {
        this.state = state;
    }
 
    public depend(fullPath?: string): unknown {
        if (fullPath) {
            return this.state.value[fullPath];
        }
        return this.state.value;
    }
 
    public hasState(name: string): boolean {
        return name in this.state.value;
    }
 
    public get(name: string): StoreContext<any> | null {
        return this.storeContext.get(name) ?? null;
    }
 
    public add(name: string, storeContext: StoreContext<any>) {
        this.storeContext.set(name, storeContext);
    }
 
    public updateState(name: string, nextState: any) {
        const { state } = this;
        if (name in state.value) {
            state.value[name] = nextState;
        } else {
            state.value = {
                ...state.value,
                [name]: nextState
            };
        }
    }
 
    public del(name: string) {
        const { state } = this;
        this.storeContext.delete(name);
        const newValue: Record<string, any> = {};
        Object.keys(state.value).forEach((key) => {
            if (key !== name) {
                newValue[key] = state.value[key];
            }
        });
        state.value = newValue;
    }
}
 
function setStateContext(state: State, stateContext: StateContext) {
    rootMap.set(state, stateContext);
}
 
export function getStateContext(state: State): StateContext {
    let stateContext = rootMap.get(state);
    if (stateContext) {
        return stateContext;
    } else {
        stateContext = new StateContext(state);
        setStateContext(state, stateContext);
    }
 
    return stateContext;
}
 
export function createState(state?: State): State {
    return getStateContext(
        state?.value && typeof state.value === 'object' ? state : { value: {} }
    ).state;
}