All files / src StateController.ts

100% Statements 74/74
100% Branches 15/15
100% Functions 27/27
100% Lines 73/73

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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204        5x 5x               60x 60x 60x 60x 60x 60x                 65x 65x 65x 65x                 5x         5x   5x   5x     48x 48x 48x     48x 48x 48x 48x 40x                     13x           48x 48x       60x 60x 60x 60x       16x 16x 5x     24x         5x 222x   70x         5x 5x         234x             46x 46x 46x 46x                   69x               21x 21x 21x         48x 48x       48x 48x       16x 1x 1x 1x             46x     48x 48x       48x 48x 48x 39x   9x         48x 48x 29x 24x 24x 24x           117x 117x          
import { LitElement, ReactiveController } 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];
            }
        });
    }
 
    /**
     * Adds an event listener for any changes to the root state.
     * @param listener 
     * @param signal provide a signal for removing the listener
     */
    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() {
        // store the stateId
        this._stateId = this.stateId;
        this.stateProperties.forEach(name => this.initState(name));
    }
 
    hostDisconnected() {
        this.abortController.abort();
        this.abortController = new AbortController();
    }
 
    refreshState(force?:boolean) {
        if (force === true || this._stateId !== this.stateId) {
            this.hostDisconnected();
            this.hostConnected();
            this.host.requestUpdate();
        }
    }
 
    /** Override this method to react to state changes */
    stateUpdated() {}
 
    private _stateId:string|null = null;
 
    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.stateUpdated();
                this.host.requestUpdate();
            }
        }, this.abortController.signal);
    }
 
    private getStateName(name:string) {
        const stateIdPath = this.stateId ? `.${this.stateId}` : "";
        return `${this.constructor.name}${stateIdPath}.${name}`;
    }
}