All files / custom-element/mixins AttributeChangeHandlerMixin.ts

94.23% Statements 49/52
87.5% Branches 28/32
81.82% Functions 9/11
94.23% Lines 49/52

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 205 206 207 20815x 15x   15x   15x   25x         84x         84x       84x   84x                 84x       138x   138x     29x             80x       80x   80x                           127x   127x                 80x   80x         131x   131x     9x       80x   6x                                             127x   7x       120x         120x   120x   120x         160x   160x   4x     156x   14x       142x       156x           156x   156x   156x   7x   7x   3x         4x         156x   156x                               88x         15x  
import { attributeMarkerPrefix } from "../../renderer/createTemplate";
import valueConverter from "../helpers/valueConverter";
import { CustomElementPropertyMetadata } from "../interfaces";
import PropertyMetadataInitializerMixin from "./PropertyMetadataInitializerMixin";
 
const AttributeChangeHandlerMixin = Base =>
 
    class AttributeChangeHandler extends PropertyMetadataInitializerMixin(Base) { // This mixin requires an implementation of setProperty
 
        /**
         * The properties of the instance
         */
        private _properties: Record<string, any> = {};
 
        /**
         * Map of the metadata of the changed properties so that the "change" method can be called after the update of the DOM
         */
        private _changedProperties: Map<string, CustomElementPropertyMetadata> = new Map<string, CustomElementPropertyMetadata>();
 
        constructor() {
 
            super();
 
            this._initializePropertiesWithDefaultValues((this.constructor as any).metadata.properties);
        }
 
        /**
         * Initializes the properties that have a default value
         * @param propertiesMetadata 
         */
        private _initializePropertiesWithDefaultValues(propertiesMetadata: Map<string, CustomElementPropertyMetadata>) {
 
            for (const [name, property] of propertiesMetadata) {
 
                const {
                    value
                } = property;
 
                if (this._properties[name] === undefined &&
                    value !== undefined) {
 
                    this.setProperty(name, value);
                }
            }
        }
 
        connectedCallback() {
 
            super.connectedCallback?.();
 
            const {
                properties
            } = (this.constructor as any).metadata;
 
            this._validateRequiredProperties(properties);
        }
 
        // Without defining this method, the observedAttributes getter will not be called
        // Also no need to check that the property was configured because if it is not configured, 
        // it will not generate the observedAttribute and therefore this method won't be called for that attribute
        /**
         * Called when there is a change in an attribute
         * @param attributeName
         * @param oldValue 
         * @param newValue 
         */
        attributeChangedCallback(attributeName: string, oldValue: string | null, newValue: string | null) {
 
            super.attributeChangedCallback?.(attributeName, oldValue, newValue);
 
            this._setAttribute(attributeName, newValue);
        }
 
        /**
         * Validates that all the required properties have been set
         * @param propertiesMetadata 
         */
        private _validateRequiredProperties(propertiesMetadata: Map<string, CustomElementPropertyMetadata>) {
 
            const missingValueAttributes: string[] = [];
 
            for (const [, property] of propertiesMetadata) {
 
                const {
                    required,
                    attribute
                } = property;
 
                if (required === true &&
                    this.attributes[attribute] === undefined) { // The attribute for that property has not been set
 
                    missingValueAttributes.push(attribute);
                }
            }
 
            if (missingValueAttributes.length > 0) {
 
                throw Error(`The attributes: [${missingValueAttributes.join(', ')}] must have a value`)
            }
        }
 
        // /**
        //  * Overrides the parent method to verify that it is accessing a configured property
        //  * @param attribute 
        //  * @param value 
        //  */
        // setAttribute(attribute: string, value: any) {
 
        //     // Verify that the property is one of the configured in the custom element
        //     if ((this.constructor as any)._propertiesByAttribute[attribute] === undefined &&
        //         !(this.constructor as any).metadata.htmlElementProperties.has(attribute)) {
 
        //         throw Error(`There is no configured property for attribute: '${attribute}' in type: '${this.constructor.name}'`)
        //     }
 
        //     super.setAttribute(attribute, value);
        // }
 
        private _setAttribute(attribute: string, value: any): boolean {
 
            if (value.startsWith(attributeMarkerPrefix)) { // Coming from a template ... ignore
 
                return false;
            }
    
            // Verify that the property is one of the configured in the custom element
            let propertyMetadata = (this.constructor as any).metadata.propertiesByAttribute.get(attribute);
 
            const {
                name,
                type
            } = propertyMetadata;
 
            value = valueConverter.toProperty(value, type); // Convert from the value returned by the parameter
 
            return this.setProperty(name, value);           
        }
 
        protected setProperty(name: string, value: any): boolean {
 
            const oldValue = this._properties[name];
 
            if (oldValue === value) {
 
                return false;
            }
 
            if (typeof value === 'function') {
 
                this._properties[name] = (value as Function).bind(this);
            }
            else {
 
                this._properties[name] = value;
            }
 
            // Verify that the property is one of the configured in the custom element
            let propertyMetadata: CustomElementPropertyMetadata = (this.constructor as any).metadata.properties.get(name);
 
            const {
                attribute,
                reflect,
                //change We call change after the element was updated in the DOM
            } = propertyMetadata;
 
            const reflectOnAttribute = reflect === true ? attribute : undefined;
 
            if (reflectOnAttribute !== undefined) { // Synchronize with the attribute of the element
 
                value = valueConverter.toAttribute(value);
 
                if (value === '') {
 
                    this.removeAttribute(reflectOnAttribute);
                }
                else {
 
                    // This will trigger the attributeChangedCallback
                    this.setAttribute(reflectOnAttribute, value);
                }
 
            }
 
            this._changedProperties.set(name, (this.constructor as any).metadata.properties.get(name));
 
            return true;
        }
 
        protected callAttributesChange() {
 
            this._changedProperties.forEach((p, k) => {
 
                if (p.afterUpdate !== undefined) { // Call the change function if defined
 
                    p.afterUpdate.call(this);
                }
            });
        }
 
        protected clearChangedProperties() {
 
            this._changedProperties.clear();
        }
 
    }
 
export default AttributeChangeHandlerMixin;