All files / coherent.js/packages/core/src/forms forms.js

91.49% Statements 495/541
81.81% Branches 99/121
87.09% Functions 27/31
91.49% Lines 495/541

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 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 6331x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x   62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x   62x 62x   62x 62x 62x 62x 62x 62x 62x 62x 62x   62x 62x 62x 62x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x   94x 94x 92x 92x 92x 92x 94x 94x 94x 94x 94x   62x 62x 62x 62x 1x 1x   62x 62x 62x 62x 44x 44x         44x 44x 2x 2x   44x   44x 44x 43x 43x 43x   44x 44x     44x   62x 62x 62x 62x 8x 8x   62x 62x 62x 62x 3x   3x   3x 3x 3x 3x 3x   62x 62x 62x 62x 1x 1x 1x   62x 62x 62x 62x 40x 40x   40x   40x 40x 1x 1x 1x   39x 39x   39x 40x 6x 6x   39x 40x 8x 8x 8x 8x 8x   8x 8x 8x   31x 40x 30x 30x   30x 30x 30x   30x 30x 29x 29x 29x 29x 27x   28x 30x       28x 30x 9x 9x 9x 9x 9x   9x     9x 30x                     30x   29x 29x 40x   62x 62x 62x 62x 16x   16x 23x 16x   16x   16x   16x 23x 23x 8x 8x 23x 16x   16x   16x 16x 16x 16x 16x   62x 62x 62x 62x 35x   9x   9x   35x 12x 12x 12x 12x       12x   9x 35x   62x 62x 62x 62x 11x   11x 14x 1x 1x 11x   11x 11x   62x 62x 62x 62x 13x   13x 13x 13x       13x 13x 10x 10x   13x 13x 13x   13x 13x 11x   11x 2x 1x 1x   2x 2x 2x 11x   11x 11x   11x 11x   11x 11x   10x 10x   10x 10x   10x 13x 1x 1x   13x 1x 1x   10x   13x 1x   1x       1x 1x   1x   13x 13x 13x 13x   62x 62x 62x 62x 3x   3x 3x 3x 3x 3x 3x   3x 3x 5x 5x 2x 2x 2x 2x 5x 5x 5x 5x 3x 3x   62x 62x 62x 62x 4x 1x 1x   4x 1x 1x   4x 1x 1x 1x   1x 1x 4x   62x 62x 62x 62x 2x 2x   62x 62x 62x 62x 5x 2x 2x 3x 5x   62x 62x 62x 62x 6x 3x 3x 3x 6x   62x 62x 62x 62x 1x 1x   62x 62x 62x 62x 1x 2x 1x 1x   62x 62x 62x 62x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   62x 62x 62x 62x 3x 3x 3x 3x 3x 3x   62x 62x 94x 62x   62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x   1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 15x 15x 15x 1x 1x 1x   1x 39x 39x 10x 10x 39x 39x 1x   1x             1x   1x             1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                 1x   1x 1x  
/**
 * Enhanced Form System
 *
 * Provides advanced form features:
 * - Async validation
 * - Custom validators
 * - Field transformations
 * - Form middleware
 */
 
/**
 * Create an enhanced form with advanced validation and middleware
 *
 * @param {Object} options - Configuration options
 * @param {Object} [options.fields] - Field configurations
 * @param {Object} [options.validation] - Validation options
 * @param {Array} [options.middleware] - Form middleware functions
 * @param {Object} [options.submission] - Submission options
 * @returns {Object} Enhanced form instance
 */
export function createForm(options = {}) {
  const opts = {
    fields: {},
    validation: {
      strategy: 'blur',
      debounce: 300,
      async: true,
      stopOnFirstError: false,
      revalidateOn: ['change', 'blur'],
      ...options.validation
    },
    errors: {
      format: 'detailed',
      display: 'inline',
      customFormatter: null,
      ...options.errors
    },
    submission: {
      preventDefault: true,
      validateBeforeSubmit: true,
      disableOnSubmit: true,
      resetOnSuccess: false,
      onSuccess: null,
      onError: null,
      ...options.submission
    },
    state: {
      trackDirty: true,
      trackTouched: true,
      trackVisited: true,
      initialValues: {},
      resetValues: null,
      ...options.state
    },
    middleware: options.middleware || [],
    ...options
  };
 
  // Form state
  const state = {
    values: { ...opts.state.initialValues },
    errors: {},
    touched: {},
    dirty: {},
    visited: {},
    isSubmitting: false,
    isValidating: false,
    submitCount: 0,
    asyncValidations: new Map()
  };
 
  // Field metadata
  const fields = new Map();
 
  // Statistics
  const stats = {
    validations: 0,
    asyncValidations: 0,
    submissions: 0,
    successfulSubmissions: 0,
    failedSubmissions: 0,
    middlewareExecutions: 0
  };
 
  /**
   * Register a field
   */
  function registerField(name, config) {
    fields.set(name, {
      name,
      type: config.type || 'text',
      validators: config.validators || [],
      transform: config.transform || {},
      validateWhen: config.validateWhen,
      required: config.required || false,
      defaultValue: config.defaultValue,
      ...config
    });
 
    // Initialize field state
    if (!(name in state.values)) {
      state.values[name] = config.defaultValue !== undefined
        ? config.defaultValue
        : '';
    }
    state.errors[name] = [];
    state.touched[name] = false;
    state.dirty[name] = false;
    state.visited[name] = false;
  }
 
  /**
   * Get field configuration
   */
  function getField(name) {
    return fields.get(name);
  }
 
  /**
   * Set field value
   */
  function setFieldValue(name, value, shouldValidate = true) {
    const field = fields.get(name);
    if (!field) {
      console.warn(`Field ${name} not registered`);
      return;
    }
 
    // Apply input transformation
    if (field.transform?.input) {
      value = field.transform.input(value);
    }
 
    state.values[name] = value;
 
    // Track dirty state
    if (opts.state.trackDirty) {
      const initialValue = opts.state.initialValues[name];
      state.dirty[name] = value !== initialValue;
    }
 
    // Validate if needed
    if (shouldValidate && opts.validation.revalidateOn.includes('change')) {
      validateField(name);
    }
  }
 
  /**
   * Get field value
   */
  function getFieldValue(name) {
    return state.values[name];
  }
 
  /**
   * Set field touched
   */
  function setFieldTouched(name, touched = true) {
    if (!opts.state.trackTouched) return;
 
    state.touched[name] = touched;
 
    // Validate on blur if configured
    if (touched && opts.validation.revalidateOn.includes('blur')) {
      validateField(name);
    }
  }
 
  /**
   * Set field visited
   */
  function setFieldVisited(name, visited = true) {
    if (!opts.state.trackVisited) return;
    state.visited[name] = visited;
  }
 
  /**
   * Validate a single field
   */
  async function validateField(name) {
    const field = fields.get(name);
    if (!field) return { valid: true, errors: [] };
 
    stats.validations++;
 
    // Check conditional validation
    if (field.validateWhen && !field.validateWhen(state.values)) {
      state.errors[name] = [];
      return { valid: true, errors: [] };
    }
 
    const value = state.values[name];
    const errors = [];
 
    // Cancel previous async validation if any
    if (state.asyncValidations.has(name)) {
      clearTimeout(state.asyncValidations.get(name));
    }
 
    // Required validation
    if (field.required && (value === '' || value === null || value === undefined)) {
      errors.push({
        field: name,
        type: 'required',
        message: `${name} is required`
      });
 
      state.errors[name] = errors;
      return { valid: false, errors };
    }
 
    // Run validators
    for (const validator of field.validators) {
      try {
        let result;
 
        // Check if validator is async
        if (validator.validate.constructor.name === 'AsyncFunction' || opts.validation.async) {
          stats.asyncValidations++;
 
          // Debounce async validation
          if (validator.debounce || opts.validation.debounce) {
            await new Promise(resolve => {
              const timeoutId = setTimeout(resolve, validator.debounce || opts.validation.debounce);
              state.asyncValidations.set(name, timeoutId);
            });
          }
 
          result = await validator.validate(value, state.values);
        } else {
          result = validator.validate(value, state.values);
        }
 
        // Check result
        if (result !== true && result !== undefined && result !== null) {
          errors.push({
            field: name,
            type: validator.name || 'custom',
            message: validator.message || result || 'Validation failed'
          });
 
          if (opts.validation.stopOnFirstError) {
            break;
          }
        }
      } catch (error) {
        errors.push({
          field: name,
          type: 'error',
          message: error.message || 'Validation error'
        });
 
        if (opts.validation.stopOnFirstError) {
          break;
        }
      }
    }
 
    state.errors[name] = errors;
    return { valid: errors.length === 0, errors };
  }
 
  /**
   * Validate all fields
   */
  async function validateForm() {
    state.isValidating = true;
 
    const validationPromises = Array.from(fields.keys()).map(name =>
      validateField(name)
    );
 
    const results = await Promise.all(validationPromises);
 
    state.isValidating = false;
 
    const allErrors = results.reduce((acc, result, index) => {
      const fieldName = Array.from(fields.keys())[index];
      if (result.errors.length > 0) {
        acc[fieldName] = result.errors;
      }
      return acc;
    }, {});
 
    const isValid = Object.keys(allErrors).length === 0;
 
    return {
      valid: isValid,
      errors: allErrors
    };
  }
 
  /**
   * Execute middleware
   */
  async function executeMiddleware(action, data) {
    if (opts.middleware.length === 0) return data;
 
    stats.middlewareExecutions++;
 
    let result = data;
 
    for (const middleware of opts.middleware) {
      try {
        const next = () => result;
        result = await middleware(action, result, next, state);
      } catch (error) {
        console.error('Middleware error:', error);
        throw error;
      }
    }
 
    return result;
  }
 
  /**
   * Apply field transformations
   */
  function applyTransformations(values) {
    const transformed = { ...values };
 
    fields.forEach((field, name) => {
      if (field.transform?.output && name in transformed) {
        transformed[name] = field.transform.output(transformed[name]);
      }
    });
 
    return transformed;
  }
 
  /**
   * Submit the form
   */
  async function handleSubmit(onSubmit) {
    stats.submissions++;
 
    try {
      // Prevent default if needed
      if (opts.submission.preventDefault && typeof event !== 'undefined') {
        event.preventDefault();
      }
 
      // Disable form during submission
      if (opts.submission.disableOnSubmit) {
        state.isSubmitting = true;
      }
 
      // Execute beforeSubmit middleware
      let values = { ...state.values };
      values = await executeMiddleware('beforeSubmit', values);
 
      // Validate before submit
      if (opts.submission.validateBeforeSubmit) {
        const validation = await validateForm();
 
        if (!validation.valid) {
          if (opts.submission.onError) {
            opts.submission.onError(validation.errors);
          }
 
          stats.failedSubmissions++;
          return { success: false, errors: validation.errors };
        }
      }
 
      // Apply transformations
      values = applyTransformations(values);
 
      // Execute afterValidation middleware
      values = await executeMiddleware('afterValidation', values);
 
      // Submit
      const result = await onSubmit(values);
 
      // Execute afterSubmit middleware
      await executeMiddleware('afterSubmit', result);
 
      state.submitCount++;
      stats.successfulSubmissions++;
 
      // Reset on success
      if (opts.submission.resetOnSuccess) {
        reset();
      }
 
      if (opts.submission.onSuccess) {
        opts.submission.onSuccess(result);
      }
 
      return { success: true, data: result };
 
    } catch (error) {
      stats.failedSubmissions++;
 
      if (opts.submission.onError) {
        opts.submission.onError(error);
      }
 
      // Execute onError middleware
      await executeMiddleware('onError', error);
 
      return { success: false, error };
 
    } finally {
      state.isSubmitting = false;
    }
  }
 
  /**
   * Reset form to initial state
   */
  function reset(values) {
    const resetValues = values || opts.state.resetValues || opts.state.initialValues;
 
    state.values = { ...resetValues };
    state.errors = {};
    state.touched = {};
    state.dirty = {};
    state.visited = {};
    state.submitCount = 0;
 
    // Re-initialize field states
    fields.forEach((field, name) => {
      // Ensure field has a value from resetValues or defaultValue
      if (!(name in state.values)) {
        state.values[name] = field.defaultValue !== undefined
          ? field.defaultValue
          : '';
      }
      state.errors[name] = [];
      state.touched[name] = false;
      state.dirty[name] = false;
      state.visited[name] = false;
    });
  }
 
  /**
   * Get form errors
   */
  function getErrors(fieldName) {
    if (fieldName) {
      return state.errors[fieldName] || [];
    }
 
    if (opts.errors.customFormatter) {
      return opts.errors.customFormatter(state.errors);
    }
 
    if (opts.errors.format === 'simple') {
      // Return array of error messages
      return Object.values(state.errors).flat().map(e => e.message);
    }
 
    // Return detailed errors
    return state.errors;
  }
 
  /**
   * Check if form is valid
   */
  function isValid() {
    return Object.values(state.errors).every(errors => errors.length === 0);
  }
 
  /**
   * Check if form is dirty
   */
  function isDirty(fieldName) {
    if (fieldName) {
      return state.dirty[fieldName] || false;
    }
    return Object.values(state.dirty).some(dirty => dirty);
  }
 
  /**
   * Check if form is touched
   */
  function isTouched(fieldName) {
    if (fieldName) {
      return state.touched[fieldName] || false;
    }
    return Object.values(state.touched).some(touched => touched);
  }
 
  /**
   * Get form values
   */
  function getValues() {
    return { ...state.values };
  }
 
  /**
   * Set form values
   */
  function setValues(values, shouldValidate = false) {
    Object.entries(values).forEach(([name, value]) => {
      setFieldValue(name, value, shouldValidate);
    });
  }
 
  /**
   * Get form state
   */
  function getState() {
    return {
      values: { ...state.values },
      errors: { ...state.errors },
      touched: { ...state.touched },
      dirty: { ...state.dirty },
      visited: { ...state.visited },
      isSubmitting: state.isSubmitting,
      isValidating: state.isValidating,
      submitCount: state.submitCount,
      isValid: isValid(),
      isDirty: isDirty(),
      isTouched: isTouched()
    };
  }
 
  /**
   * Get statistics
   */
  function getStats() {
    return {
      ...stats,
      fieldsRegistered: fields.size,
      activeAsyncValidations: state.asyncValidations.size
    };
  }
 
  // Register initial fields
  Object.entries(opts.fields).forEach(([name, config]) => {
    registerField(name, config);
  });
 
  return {
    registerField,
    getField,
    setFieldValue,
    getFieldValue,
    setFieldTouched,
    setFieldVisited,
    validateField,
    validateForm,
    handleSubmit,
    reset,
    getErrors,
    isValid,
    isDirty,
    isTouched,
    getValues,
    setValues,
    getState,
    getStats,
    // Expose state for testing
    _state: state
  };
}
 
// Export built-in validators
export const formValidators = {
  required: {
    name: 'required',
    validate: (value) => {
      return value !== '' && value !== null && value !== undefined;
    },
    message: 'This field is required'
  },
 
  email: {
    name: 'email',
    validate: (value) => {
      if (!value) return true;
      const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return regex.test(value);
    },
    message: 'Please enter a valid email address'
  },
 
  minLength: (min) => ({
    name: 'minLength',
    validate: (value) => {
      if (!value) return true;
      return String(value).length >= min;
    },
    message: `Must be at least ${min} characters`
  }),
 
  maxLength: (max) => ({
    name: 'maxLength',
    validate: (value) => {
      if (!value) return true;
      return String(value).length <= max;
    },
    message: `Must be no more than ${max} characters`
  }),
 
  pattern: (regex, message) => ({
    name: 'pattern',
    validate: (value) => {
      if (!value) return true;
      return regex.test(value);
    },
    message: message || 'Invalid format'
  }),
 
  asyncEmail: {
    name: 'asyncEmail',
    validate: async (value) => {
      if (!value) return true;
      // Simulate async validation (e.g., check if email exists)
      await new Promise(resolve => setTimeout(resolve, 100));
      const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return regex.test(value);
    },
    message: 'Please enter a valid email address',
    debounce: 500
  },
 
  asyncUnique: (checkFn) => ({
    name: 'asyncUnique',
    validate: async (value) => {
      if (!value) return true;
      return await checkFn(value);
    },
    message: 'This value is already taken',
    debounce: 500
  })
};
 
// Export default instance
export const enhancedForm = createForm();