All files / src/custom-element/mixins StateChangeHandlerMixin.ts

88.89% Statements 16/18
75% Branches 6/8
100% Functions 4/4
88.89% Lines 16/18

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  19x   19x   29x         92x       92x   92x               92x       14x   14x     12x               20x         20x   20x         20x   20x         19x  
import { CustomElementStateMetadata } from "../interfaces";
import StateMetadataInitializerMixin from "./StateMetadataInitializerMixin";
 
const StateChangeHandlerMixin = Base =>
 
    class StateChangeHandler extends StateMetadataInitializerMixin(Base) { // This mixin requires an implementation of setState
 
        /**
         * The state of the instance
         */
        private _state: Record<string, any> = {};
 
        constructor() {
 
            super();
            
            this._initializeStateWithDefaultValues((this.constructor as any).metadata.state);
        }
        /**
         * Initializes the state that have a default value
         * @param stateMetadata 
         */
        private _initializeStateWithDefaultValues(stateMetadata: Map<string, CustomElementStateMetadata>) {
 
            for (const [name, state] of stateMetadata) {
 
                const {
                    value
                } = state;
 
                if (this._state[name] === undefined &&
                    value !== undefined) {
 
                    this.setState(name, value);
                }
            }
        }
 
        protected setState(key: string, value: any): boolean {
 
            // Verify that the property of the state is one of the configured in the custom element
            Iif ((this.constructor as any).metadata.state.get(key) === undefined) {
 
                throw Error(`There is no configured property for state: '${key}' in type: '${this.constructor.name}'`)
            }
 
            const oldValue = this._state[key];
 
            Iif (oldValue === value) {
 
                return false;
            }
 
            this._state[key] = value;
 
            return true;
        }
 
    }
 
export default StateChangeHandlerMixin;