All files / components/fields Field.ts

31.82% Statements 14/44
18.75% Branches 3/16
30.77% Functions 4/13
31.82% Lines 14/44

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 2002x 2x   2x 2x 2x 2x   2x   2x   2x                 2x       4x         12x                                                                     2x   2x                                                                                                                                                                                                                                                                        
import CustomElement from "../../custom-element/CustomElement";
import mergeStyles from "../../custom-element/helpers/mergeStyles";
import { CustomElementPropertyMetadata } from "../../custom-element/interfaces";
import SizableMixin from "../../custom-element/mixins/components/sizable/SizableMixin";
import ValidatableMixin from "../../custom-element/mixins/components/validatable/ValidatableMixin";
import RequiredValidator from "../../utils/validation/validators/field/RequiredValidator";
import styles from "./Field.css";
 
export const changeEvent = "changeEvent";
 
export const fieldAddedEvent = "fieldAddedEvent";
 
export abstract class Field extends
    SizableMixin(
        ValidatableMixin(
            CustomElement
        )
    ) {
 
    // The temporary value being validated on input
    // Since it is not the final one there is no need to refresh
    private _tempValue: any = undefined;
 
    static get styles(): string {
 
        return mergeStyles(super.styles, styles);
    }
 
    static get properties(): Record<string, CustomElementPropertyMetadata> {
 
        return {
 
            /**
             * The name of the field
             */
            name: {
                type: String,
                required: true
            },
 
            /**
             * The initial value of the field
             */
            value: {
                type: [String, Object], // Ideally is a string but could be a more complex object
                mutable: true,
                reflect: true
            },
 
            disabled: {
                type: Boolean,
                mutable: true,
                reflect: true
            },
 
            required: {
                type: Boolean,
                mutable: true,
                reflect: true
            }
        };
    }
 
    didAdoptChildCallback(parent, child) {
 
        super.didAdoptChildCallback?.(parent, child);
 
        this.dispatchCustomEvent(fieldAddedEvent, {
            field: child
        });
    }
 
    handleBlur(event) {
 
        //this.validate();
    }
 
    /**
     * Called every time the input changes
     * Perform validation to give instantaneous feedback but do not update the current value since it might keep changing
     * @param event 
     * @returns 
     */
    handleInput(event) {
 
        // Retrieve the new value
        const target = event.target as HTMLInputElement;
 
        this._tempValue = this.getNewValue(target);
 
        return this.validate(); // Validate the field on input
    }
 
    createValidationContext() /*: ValidationContext */ {
 
        const label = this.getLabel();
 
        const value = this._tempValue ?? this.value;
 
        return {
            label,
            value,
            warnings: [],
            errors: []
        };
    }
 
    initializeValidator(validator: string) {
 
        switch(validator) {
 
            case 'required': return new RequiredValidator();
            default: throw new Error(`initializeValidator is not implemented for validator: '${validator}'`);
        }
    }
 
    getLabel() : string {
 
        return "kuku";
    }
 
    handleChange(event): void {
 
        // Reset the temporary value
        this._tempValue = undefined;
 
        // Retrieve the new value
        const target = event.target as HTMLInputElement;
 
        const oldValue = this.value;
 
        this.value = this.getNewValue(target);
 
        const {
            name,
            value
        } = this;
 
        setTimeout(() => { // Repaint before dispatching the event
 
            this.dispatchCustomEvent(changeEvent, {
                name,
                oldValue,
                newValue: value
            });
 
        }, 0);
    }
 
    getNewValue(input: HTMLInputElement): any {
 
        let value: any;
 
        switch (input.type) {
            case 'file':
                {
                    const {
                        files
                    } = input;
 
                    if (files.length === 0) { // No files selected
 
                        return value;
                    }
 
                    if (input.multiple === true) {
 
                        value = Array.from(files).map(f => {
 
                            return {
                                name: f.name,
                                type: f.type,
                                size: f.size,
                                content: URL.createObjectURL(f)
                            };
                        });
                    }
                    else {
 
                        const f = files[0];
 
                        value = {
                            name: f.name,
                            type: f.type,
                            size: f.size,
                            content: URL.createObjectURL(f)
                        };
                    }
                }
                break;
            default:
                {
                    value = input.value;
                }
                break;
        }
 
        return value;
    }
}