All files StateController.ts

100% Statements 67/67
100% Branches 12/12
100% Functions 25/25
100% Lines 66/66

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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183        5x 5x               57x 57x 57x 57x 57x 57x                 62x 62x 62x 62x                 5x         5x   5x   5x     42x 42x 42x     42x 42x 42x 42x 36x           13x           42x 42x       57x 57x 57x 57x       16x 16x 5x     22x         5x 192x   58x         5x 5x         154x             41x 41x 41x 41x                   63x               21x 21x 21x       42x       42x 42x       42x 42x       42x 42x 42x 36x   6x         42x 42x 29x 24x 24x           105x 105x          
import { LitElement, ReactiveController, ReactiveControllerHost } from "lit";
 
 
 
export class RootStateChangeEvent extends Event {
    static eventType = "rootstate-change";
    event:Event|string;
    rootState:RootStateContainer;
    controller:any;
    statePath:string;
    state:any;
    constructor(event:Event|string, rootState:RootStateContainer,
        controller:any, statePath:string, state:any) {
        super(RootStateChangeEvent.eventType)
        this.event = event;
        this.rootState = {...rootState};
        this.controller = controller;
        this.statePath = statePath;
        this.state = {...state};
    }
};
 
class StatePathChangeEvent extends Event {
    controller:any;
    statePath:string;
    state:any;
    constructor(controller:any, statePath:string, state:any) {
        super(statePath);
        this.controller = controller;
        this.statePath = statePath;
        this.state = state;
    }
}
 
type RootStateContainer = {[key:string]: any};
type StateChangeEventListener = (event:StatePathChangeEvent) => void;
type RootStateChangeEventListener = (event:RootStateChangeEvent) => void;
 
 
let rootState:RootStateContainer = {};
 
/**
 * Class used to track root state changes
 */
export class RootState {
 
    private static bus = new EventTarget();
 
    private static listenerCounts:{[statePath:string]:number|undefined} = {};
 
    static addStateChangeEventListener(statePath:string, listener:StateChangeEventListener, signal:AbortSignal) {
        this.bus.addEventListener(statePath, listener as EventListener, {signal} as AddEventListenerOptions);
        const count = this.listenerCounts[statePath];
        this.listenerCounts[statePath] = count === undefined ? 1 : count + 1;
 
        // delete state path when aborted
        signal.addEventListener("abort", () => {
            const count = this.listenerCounts[statePath]! - 1;
            this.listenerCounts[statePath] = count;
            if (count === 0) {
                delete rootState[statePath];
            }
        });
    }
 
    static addRootStateChangeEventListener(listener:RootStateChangeEventListener, signal?:AbortSignal) {
        this.bus.addEventListener(RootStateChangeEvent.eventType,
            listener as EventListener,
            {signal} as AddEventListenerOptions);
    }
 
    static get<T>(name:string):T|null {
        const value = rootState[name];
        return value === undefined ? null : value as T;
    }
 
    static change<T>(controller:any, event:Event|string, statePath:string, state:T):true {
        rootState[statePath] = state;
        this.bus.dispatchEvent(new StatePathChangeEvent(controller, statePath, state));
        this.bus.dispatchEvent(new RootStateChangeEvent(event, rootState, controller, statePath, state));
        return true;
    }
 
    static push(state:RootStateContainer) {
        rootState = state;
        Object.keys(state).forEach(key =>
            this.bus.dispatchEvent(new StatePathChangeEvent(null, key, rootState[key])));
    }
 
    static get current():RootStateContainer { return rootState; };
}
 
 
 
const stateControllerIndexedProxyHandler:ProxyHandler<StateController> = {
    get: (target:StateController, property:string) => target[property],
    set: (target:StateController, property:string, value:any) =>
        target[property] = value
};
 
 
 
export class StateController implements ReactiveController {
    static stateProperties:Array<string> = [];
 
    [name:string]: any;
 
    /** Returns the stateId property from the host element if defined */
    get stateId():string|null { return this.host.stateId !== undefined ? 
        this.host.stateId : null };
 
    /**
     * Initializes the StateController
     */
    constructor(host: LitElement) {
        this.host = host;
        this.abortController = new AbortController();
        this.host.addController(this);
        return new Proxy(this, stateControllerIndexedProxyHandler);
    }
 
    /** The element that the controller is attached to */
    host: LitElement & {stateId?:string};
 
    /** Used to signal when the host has been disconnected */
    abortController:AbortController;
 
    private get stateProperties():Array<string> {
        return (this.constructor as typeof StateController).stateProperties;
    }
 
    /**
     * Notifies the root state of the change and calls requestUpdate on the host.
     * @param event The event responsible for the update
     */
    requestUpdate(event:Event|string) {
        this.stateProperties.forEach(name =>
            RootState.change(this, event, this.getStateName(name), this[name]));
        this.host.requestUpdate();
    }
 
    hostConnected() {
        this.stateProperties.forEach(name => this.initState(name));
    }
 
    hostDisconnected() {
        this.abortController.abort();
        this.abortController = new AbortController();
    }
 
    private initState(name:string) {
        this.syncStateValue(name);
        this.addStateListeners(name);
    }
 
    private syncStateValue(name:string) {
        const statePath = this.getStateName(name);
        const initialState = RootState.get(statePath);
        if (initialState === null) {
            RootState.change(this, `Init.${this.constructor.name}.(${name})`, statePath, this[name]);
        } else {
            this[name] = initialState;
        }
    }
 
    private addStateListeners(name:string) {
        const statePath = this.getStateName(name);
        RootState.addStateChangeEventListener(statePath, (event:StatePathChangeEvent) => {
            if (event.controller !== this) {
                this[name] = event.state;
                this.host.requestUpdate();
            }
        }, this.abortController.signal);
    }
 
    private getStateName(name:string) {
        const stateIdPath = this.stateId ? `.${this.stateId}` : "";
        return `${this.constructor.name}${stateIdPath}.${name}`;
    }
}