import { html, property } from '@skhemata/skhemata-base'; import { faExclamationTriangle, faSearch, } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@riovir/wc-fontawesome'; import { SkhemataFormInput } from './SkhemataFormInput'; import validator from './validator/index'; export class SkhemataFormTextbox extends SkhemataFormInput { @property({ type: Number }) minlength = -1; @property({ type: Number }) maxlength = -1; @property({ type: Boolean }) submitOnEnter = false; @property({ type: String }) type = 'text'; static get scopedElements() { return { 'fa-icon': FontAwesomeIcon, }; } constructor() { super(); this.value = ''; } validate() { this.helpClass = ''; if ( (this.minlength !== -1 && this.value.length < this.minlength) || (this.maxlength !== -1 && this.value.length > this.maxlength) || (this.required && this.value.length < 1) || (this.type === 'email' && !validator.isEmail(this.value)) ) { if (this.required && this.value.length < 1) { this.errorMessage = this.getStr('formErrorRequired'); } else if (this.minlength !== -1 && this.value.length < this.minlength) { this.errorMessage = this.getStr('formErrorMinlength'); } else if (this.maxlength !== -1 && this.value.length > this.maxlength) { this.errorMessage = this.getStr('formErrorMaxlength'); } else if (this.type === 'email' && !validator.isEmail(this.value)) { this.errorMessage = this.getStr('formErrorEmail'); } this.valid = false; this.helpClass = 'is-danger'; this.requestUpdate(); } this.dispatchEvent( new CustomEvent('is-valid', { detail: { valid: this.valid }, bubbles: true, composed: true, }) ); } handleInput(event: any) { this.clearError(); this.setAttribute('value', event.target.value); } handleKeydown(event: any) { this.clearError(); if (event.keyCode === '13' && this.submitOnEnter) { this.validate(); if (!this.valid) { return; } this.dispatchEvent(new CustomEvent('submit')); event.preventDefault(); } } render() { const faTriangleIcon = html` `; const faSearchIcon = html` `; let inputIcon = this.type === 'search' ? faSearchIcon : null; inputIcon = this.valid ? inputIcon : faTriangleIcon; const field = html`
${this.label && !this.horizontal ? html`` : null}
${this.description && !this.horizontal ? html`

${this.description}

` : null} ${inputIcon}
${!this.valid ? html`

${this.errorMessage}

` : ``}
`; const horizontalFieldLabel = html`
${this.label ? html`` : null} ${this.description ? html`

${this.description}

` : null}
`; const horizontalField = html`
${this.label || this.description ? horizontalFieldLabel : null}
${field}
`; return this.horizontal ? horizontalField : field; } }