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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | /**
* Form Hydration for Coherent.js
*
* Progressive enhancement for server-rendered forms
* Reads validation metadata from HTML and attaches client-side behavior
*
* @module forms/form-hydration
*/
import { validators } from './validators.js';
/**
* Hydrate a server-rendered form with client-side validation and behavior
*
* @param {string|HTMLFormElement} formSelector - Form selector or element
* @param {Object} options - Hydration options
* @returns {Object} Form controller
*/
export function hydrateForm(formSelector, options = {}) {
// Browser-only check
if (typeof document === 'undefined') {
console.warn('hydrateForm can only run in browser environment');
return null;
}
const form = typeof formSelector === 'string'
? document.querySelector(formSelector)
: formSelector;
if (!form) {
console.warn(`Form not found: ${formSelector}`);
return null;
}
const opts = {
validateOnBlur: true,
validateOnChange: false,
validateOnSubmit: true,
showErrorsOnTouch: true,
debounce: 300,
...options
};
// Form state
const state = {
values: {},
errors: {},
touched: {},
isSubmitting: false,
fields: new Map()
};
// Debounce timers
const debounceTimers = new Map();
/**
* Parse validators from data-validators attribute
*/
function parseValidators(validatorString) {
if (!validatorString) return [];
return validatorString.split(',').map(v => {
const trimmed = v.trim();
// Handle validators with parameters: minLength:8
const [name, ...params] = trimmed.split(':');
if (validators[name]) {
return params.length > 0
? validators[name](...params.map(p => isNaN(p) ? p : Number(p)))
: validators[name];
}
return null;
}).filter(Boolean);
}
/**
* Discover and register fields from form HTML
*/
function discoverFields() {
const inputs = form.querySelectorAll('[name]');
inputs.forEach(input => {
const name = input.getAttribute('name');
const field = {
name,
element: input,
type: input.getAttribute('type') || 'text',
required: input.hasAttribute('required') || input.dataset.required === 'true',
validators: parseValidators(input.dataset.validators),
errorElement: null
};
// Find or create error display element
const errorId = `${name}-error`;
field.errorElement = document.getElementById(errorId) || createErrorElement(name, input);
state.fields.set(name, field);
state.values[name] = getFieldValue(input);
state.touched[name] = false;
state.errors[name] = null;
});
}
/**
* Create error display element
*/
function createErrorElement(name, inputElement) {
const errorDiv = document.createElement('div');
errorDiv.id = `${name}-error`;
errorDiv.className = 'error-message';
errorDiv.setAttribute('role', 'alert');
errorDiv.style.display = 'none';
// Insert after input or its parent field wrapper
const fieldWrapper = inputElement.closest('.form-field') || inputElement.parentElement;
fieldWrapper.appendChild(errorDiv);
return errorDiv;
}
/**
* Get field value based on input type
*/
function getFieldValue(input) {
if (input.type === 'checkbox') {
return input.checked;
} else if (input.type === 'radio') {
const checked = form.querySelector(`[name="${input.name}"]:checked`);
return checked ? checked.value : null;
} else {
return input.value;
}
}
/**
* Set field value
*/
function setFieldValue(name, value) {
const field = state.fields.get(name);
if (!field) return;
const { element } = field;
if (element.type === 'checkbox') {
element.checked = Boolean(value);
} else if (element.type === 'radio') {
const radio = form.querySelector(`[name="${name}"][value="${value}"]`);
if (radio) radio.checked = true;
} else {
element.value = value;
}
state.values[name] = value;
}
/**
* Validate a single field
*/
function validateField(name) {
const field = state.fields.get(name);
if (!field) return true;
const value = state.values[name];
let error = null;
// Required validation
if (field.required && (value === null || value === undefined || value === '')) {
error = 'This field is required';
}
// Run custom validators
if (!error && field.validators.length > 0) {
for (const validator of field.validators) {
const result = validator.validate
? validator.validate(value, state.values)
: validator(value, state.values);
if (result !== true && result !== undefined && result !== null) {
error = validator.message || result || 'Validation failed';
break;
}
}
}
state.errors[name] = error;
displayError(name, error);
return !error;
}
/**
* Display error message
*/
function displayError(name, error) {
const field = state.fields.get(name);
if (!field) return;
const { element, errorElement } = field;
if (error && state.touched[name] && opts.showErrorsOnTouch) {
// Show error
errorElement.textContent = error;
errorElement.style.display = 'block';
element.setAttribute('aria-invalid', 'true');
element.classList.add('error');
} else {
// Hide error
errorElement.textContent = '';
errorElement.style.display = 'none';
element.setAttribute('aria-invalid', 'false');
element.classList.remove('error');
}
}
/**
* Validate entire form
*/
function validateForm() {
let isValid = true;
for (const name of state.fields.keys()) {
const fieldValid = validateField(name);
if (!fieldValid) isValid = false;
}
return isValid;
}
/**
* Handle input change
*/
function handleChange(event) {
const input = event.target;
const name = input.getAttribute('name');
if (!state.fields.has(name)) return;
state.values[name] = getFieldValue(input);
if (opts.validateOnChange) {
// Debounce validation
if (debounceTimers.has(name)) {
clearTimeout(debounceTimers.get(name));
}
const timer = setTimeout(() => {
validateField(name);
debounceTimers.delete(name);
}, opts.debounce);
debounceTimers.set(name, timer);
}
}
/**
* Handle input blur
*/
function handleBlur(event) {
const input = event.target;
const name = input.getAttribute('name');
if (!state.fields.has(name)) return;
state.touched[name] = true;
if (opts.validateOnBlur) {
validateField(name);
}
}
/**
* Handle form submission
*/
function handleSubmit(event) {
event.preventDefault();
// Mark all fields as touched
for (const name of state.fields.keys()) {
state.touched[name] = true;
}
const isValid = validateForm();
if (!isValid) {
// Focus first error field
const firstErrorField = Array.from(state.fields.values())
.find(field => state.errors[field.name]);
if (firstErrorField) {
firstErrorField.element.focus();
}
// Call onError callback
if (options.onError) {
options.onError(state.errors);
}
return;
}
// Form is valid, prepare submission
state.isSubmitting = true;
const submitData = { ...state.values };
// Call onSubmit callback
if (options.onSubmit) {
const result = options.onSubmit(submitData, event);
// If onSubmit returns false, don't submit
if (result === false) {
state.isSubmitting = false;
return;
}
// If onSubmit returns a promise, wait for it
if (result && typeof result.then === 'function') {
result
.then(() => {
state.isSubmitting = false;
if (options.onSuccess) {
options.onSuccess(submitData);
}
})
.catch(error => {
state.isSubmitting = false;
if (options.onError) {
options.onError(error);
}
});
return;
}
}
// Default: submit the form normally
if (!options.onSubmit) {
form.submit();
}
state.isSubmitting = false;
}
/**
* Attach event listeners
*/
function attachEventListeners() {
// Input change events
state.fields.forEach(field => {
field.element.addEventListener('input', handleChange);
field.element.addEventListener('blur', handleBlur);
});
// Form submit
form.addEventListener('submit', handleSubmit);
}
/**
* Detach event listeners (cleanup)
*/
function detachEventListeners() {
state.fields.forEach(field => {
field.element.removeEventListener('input', handleChange);
field.element.removeEventListener('blur', handleBlur);
});
form.removeEventListener('submit', handleSubmit);
// Clear debounce timers
debounceTimers.forEach(timer => clearTimeout(timer));
debounceTimers.clear();
}
/**
* Reset form to initial state
*/
function reset() {
state.fields.forEach(field => {
setFieldValue(field.name, '');
state.touched[field.name] = false;
state.errors[field.name] = null;
displayError(field.name, null);
});
state.isSubmitting = false;
form.reset();
}
// Initialize
discoverFields();
attachEventListeners();
// Public API
return {
validateField,
validateForm,
setFieldValue,
getFieldValue: (name) => state.values[name],
getError: (name) => state.errors[name],
getErrors: () => ({ ...state.errors }),
getValues: () => ({ ...state.values }),
setTouched: (name, touched = true) => {
state.touched[name] = touched;
},
reset,
destroy: detachEventListeners,
isValid: () => Object.values(state.errors).every(e => !e),
isSubmitting: () => state.isSubmitting,
getState: () => ({
values: { ...state.values },
errors: { ...state.errors },
touched: { ...state.touched },
isSubmitting: state.isSubmitting
})
};
}
export default hydrateForm;
|