import { Controller } from '@hotwired/stimulus'; import { html } from 'lit-html'; export default class AriadneFormWith extends Controller { constructor() { super(...arguments); this.onBlur = (event) => { this.validateField(event.target); }; this.onSubmit = (event) => { var _a; if (!this.validateForm()) { event.preventDefault(); (_a = this.firstInvalidField) === null || _a === void 0 ? void 0 : _a.focus(); } }; this.getRenderString = (data) => { const { strings, values } = data; const v = [...values, ''].map(e => (typeof e === 'object' ? this.getRenderString(e) : e)); return strings.reduce((acc, s, i) => acc + s + v[i], ''); }; } connect() { this.element.setAttribute('novalidate', 'true'); this.element.addEventListener('blur', this.onBlur, true); this.element.addEventListener('submit', this.onSubmit); this.element.addEventListener('ajax:beforeSend', this.onSubmit); } disconnect() { this.element.removeEventListener('blur', this.onBlur); this.element.removeEventListener('submit', this.onSubmit); this.element.removeEventListener('ajax:beforeSend', this.onSubmit); } validateForm() { let isValid = true; // Not using `find` because we want to validate all the fields for (const field of this.formFields) { if (this.shouldValidateField(field) && !this.validateField(field)) isValid = false; } return isValid; } validateField(field) { if (!this.shouldValidateField(field)) return true; const isValid = field.checkValidity(); field.classList.toggle('invalid', !isValid); this.refreshErrorForInvalidField(field, isValid); return isValid; } shouldValidateField(field) { return (!field.disabled && !field.classList.contains('ProseMirror') && !['file', 'reset', 'submit', 'button'].includes(field.type)); } refreshErrorForInvalidField(field, isValid) { this.removeExistingErrorMessage(field); if (!isValid) this.showErrorForInvalidField(field); } removeExistingErrorMessage(field) { var _a; const fieldContainer = field.closest('.field'); if (!fieldContainer) return; const existingErrorMessageElement = fieldContainer.querySelector('.error'); if (existingErrorMessageElement) { (_a = existingErrorMessageElement === null || existingErrorMessageElement === void 0 ? void 0 : existingErrorMessageElement.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(existingErrorMessageElement); } } showErrorForInvalidField(field) { field.insertAdjacentHTML('afterend', this.buildFieldErrorHtml(field)); } buildFieldErrorHtml(field) { const data = html `
${field.validationMessage}
`; return this.getRenderString(data); } get formFields() { return Array.from(this.formFieldTargets); } get firstInvalidField() { return this.formFields.find(field => !field.checkValidity()); } } AriadneFormWith.targets = ['formField'];