All files / src/lib/engine NgxFormFieldDirective.ts

50.45% Statements 55/109
30.43% Branches 21/69
36.36% Functions 8/22
50.96% Lines 53/104

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              1x 1x 1x 1x 1x 1x                 1x 1x 1x                                                                   1x                           20x     20x                                             20x                                                                                                                                                                                                                                                                                                                                                               20x               20x                                       20x       20x 20x 1x                                                             20x                   20x                   20x                                                                                                                                                                                                                                                                                                     1x 1x 1x   1x                                                                           76x             24x 24x 24x 24x 24x 24x 16x               16x 16x       16x 8x     24x 24x         24x                         76x 76x 76x 76x 76x 24x 24x 24x         24x 24x                 24x 24x            
/**
 * @module lib/engine/NgxFormFieldDirective
 * @description Base directive for CRUD form fields in Decaf Angular applications.
 * @summary Provides the NgxFormFieldDirective abstract class that implements ControlValueAccessor
 * and FieldProperties to enable form field integration with Angular's reactive forms system.
 * This directive handles form control lifecycle, validation, multi-entry forms, and CRUD operations.
 */
import { Directive, Inject, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormArray, FormControl, FormGroup } from '@angular/forms';
import { CrudOperations, InternalError, OperationKeys } from '@decaf-ts/db-decorators';
import { Primitives } from '@decaf-ts/decorator-validation';
import { sf } from '@decaf-ts/logging';
import {
  ComponentEventNames,
  FieldProperties,
  HTML5InputTypes,
  RenderingError,
  UIEventProperty,
  UIValidator,
} from '@decaf-ts/ui-decorators';
import { SelectCustomEvent } from '@ionic/angular/standalone';
import { NgxFormService } from '../services/NgxFormService';
import { AngularEngineKeys, CPTKN } from './constants';
import { NgxComponentDirective } from './NgxComponentDirective';
import { FormParent, FunctionLike, KeyValue, PossibleInputTypes } from './types';
 
/**
 * @description Abstract base directive for CRUD form fields in Angular applications.
 * @summary Provides the foundation for all form field components in Decaf applications by implementing
 * Angular's ControlValueAccessor interface and FieldProperties for validation. This directive manages
 * form control integration, validation state, multi-entry forms (FormArrays), and CRUD operation context.
 * It handles form group lifecycle, error messaging, change detection, and parent-child form relationships.
 * Extend this class to create custom form field components that seamlessly integrate with Angular's
 * reactive forms and Decaf's validation system.
 * @class NgxFormFieldDirective
 * @extends {NgxComponentDirective}
 * @implements {ControlValueAccessor}
 * @implements {FieldProperties}
 * @example
 * ```typescript
 * @Component({
 *   selector: 'app-text-field',
 *   templateUrl: './text-field.component.html',
 *   providers: [{
 *     provide: NG_VALUE_ACCESSOR,
 *     useExisting: forwardRef(() => TextFieldComponent),
 *     multi: true
 *   }]
 * })
 * export class TextFieldComponent extends NgxFormFieldDirective {
 *   constructor() {
 *     super();
 *   }
 * }
 * ```
 */
@Directive()
export abstract class NgxFormFieldDirective
  extends NgxComponentDirective
  implements OnChanges, ControlValueAccessor, FieldProperties
{
  /**
   * @description Index of the currently active form group in a form array.
   * @summary When working with multiple form groups (form arrays), this indicates
   * which form group is currently active or being edited. This is used to manage
   * focus and data binding in multi-entry scenarios.
   * @type {number}
   * @default 0
   * @public
   */
  @Input()
  activeFormGroupIndex: number = 0;
 
  @Input({ required: true })
  override operation: CrudOperations = OperationKeys.CREATE;
 
  /**
   * @description Parent form container for this field.
   * @summary Reference to the parent FormGroup or FormArray that contains this field.
   * When this field is part of a multi-entry structure, this contains the FormArray
   * with all form groups. This enables management of multiple instances of the same
   * field structure within a single form.
   * @type {FormParent}
   * @public
   */
  @Input()
  parentForm!: FormParent;
 
  /**
   * @description Field mapping configuration for options.
   * @summary Defines how fields from the data model should be mapped to properties used by the component.
   * This allows for flexible data binding between the model and the component's display logic.
   * Can be either a key-value mapping object or a function that performs the mapping.
   * @type {KeyValue | FunctionLike}
   * @public
   */
  @Input()
  optionsMapper: KeyValue | FunctionLike = {};
 
  /**
   * @description Angular FormControl instance for this field.
   * @summary The FormControl that manages this field's value, validation state, and user interactions.
   * @type {FormControl}
   * @public
   */
  formControl!: FormControl;
 
  /**
   * @description Dot-separated path to this field in the form structure.
   * @summary Used to locate this field within nested form structures.
   * @type {string}
   * @public
   */
  path!: string;
 
  /**
   * @description The input type of this field.
   * @summary Determines the HTML input type or component type to render.
   * @type {PossibleInputTypes}
   * @public
   */
  type!: PossibleInputTypes;
 
  /**
   * @description Whether the field is disabled.
   * @summary When true, the field cannot be edited by the user.
   * @type {boolean}
   * @public
   */
  disabled?: boolean;
 
  /**
   * @description Page number for multi-page forms.
   * @summary Indicates which page this field belongs to in a multi-page form structure.
   * @type {number}
   * @public
   */
  page!: number;
 
  override events!: UIEventProperty;
 
  // Validation properties
 
  /**
   * @description Date/time format string for parsing and display.
   * @type {string}
   * @public
   */
  format?: string;
 
  /**
   * @description Maximum value or date allowed.
   * @type {number | Date}
   * @public
   */
  max?: number | Date;
 
  /**
   * @description Maximum length for text input.
   * @type {number}
   * @public
   */
  maxlength?: number;
 
  /**
   * @description Minimum value or date allowed.
   * @type {number | Date}
   * @public
   */
  min?: number | Date;
 
  /**
   * @description Minimum length for text input.
   * @type {number}
   * @public
   */
  minlength?: number;
 
  /**
   * @description Regex pattern for validation.
   * @type {string | undefined}
   * @public
   */
  pattern?: string | undefined;
 
  /**
   * @description Whether the field is required.
   * @type {boolean}
   * @public
   */
  required?: boolean;
 
  /**
   * @description Step value for numeric inputs.
   * @type {number}
   * @public
   */
  step?: number;
 
  /**
   * @description Field name that this field's value must equal.
   * @type {string}
   * @public
   */
  equals?: string;
 
  /**
   * @description Field name that this field's value must differ from.
   * @type {string}
   * @public
   */
  different?: string;
 
  /**
   * @description Field name that this field's value must be less than.
   * @type {string}
   * @public
   */
  lessThan?: string;
 
  /**
   * @description Field name that this field's value must be less than or equal to.
   * @type {string}
   * @public
   */
  lessThanOrEqual?: string;
 
  /**
   * @description Field name that this field's value must be greater than.
   * @type {string}
   * @public
   */
  greaterThan?: string;
 
  /**
   * @description Field name that this field's value must be greater than or equal to.
   * @type {string}
   * @public
   */
  greaterThanOrEqual?: string;
 
  /**
   * @description Current value of the field.
   * @summary Can be a string, number, date, or array of strings for multi-select fields.
   * @type {string | number | Date | string[]}
   * @public
   */
  override value!: string | number | Date | string[];
 
  /**
   * @description Whether the field supports multiple values.
   * @summary When true, the field is rendered as part of a FormArray structure.
   * @type {boolean}
   * @public
   */
  multiple!: boolean;
 
  /**
   * @description Custom type definitions for field validation.
   * @summary Allows specifying custom types beyond HTML5 input types to support specialized validation logic.
   * Can be a single type string or an array of type strings for multi-type validation scenarios.
   * @type {string | string[] | undefined}
   * @public
   */
  customTypes?: string | string[] | undefined;
 
  /**
   * @description Whether the field is currently checked.
   * @summary Used for checkbox and radio button fields to track the checked state independently from the value.
   * @type {boolean}
   * @default false
   * @public
   */
  checked: boolean = false;
 
  /**
   * @description Flag tracking if validation error event has been dispatched.
   * @summary Proverride  duplicate validation error override  from being dispatched.
   * @type {boolean}
   * @private
   */
  private validationErrorEventDispatched: boolean = false;
 
  /**
   * @description Reference to the parent HTML element.
   * @summary Used for DOM manipulation and event handling.
   * @type {HTMLElement}
   * @protected
   */
  protected parent?: HTMLElement;
 
  /**
   * @description Reference to HTML5 input type constants for template usage.
   * @summary Exposes the HTML5InputTypes enum to the component template, enabling
   * conditional rendering and behavior based on input field types. This protected
   * readonly property ensures that template logic can access input type constants
   * while maintaining encapsulation and preventing accidental modification.
   * @type {HTML5InputTypes}
   * @protected
   * @readonly
   */
  readonly HTML5InputTypes = HTML5InputTypes;
 
  // eslint-disable-next-line @angular-eslint/prefer-inject
  constructor(@Inject(CPTKN) componentName: string = 'ComponentCrudField') {
    super(componentName);
    if (!UIValidator.translateService) {
      UIValidator.translateService = this.translateService;
    }
  }
 
  /**
   * @description Gets the currently active form group based on context.
   * @summary Returns the appropriate FormGroup based on whether this field supports
   * multiple values. For single-value fields, returns the main form group.
   * For multi-value fields, returns the form group at the active index from the parent FormArray.
   * If no formGroup is set, returns the parent of the formControl.
   * @return {FormGroup} The currently active FormGroup for this field
   * @public
   */
  get activeFormGroup(): FormGroup {
    Iif (!this.formGroup) return this.formControl.parent as FormGroup;
 
    Iif (this.multiple) {
      Iif (this.formGroup instanceof FormArray) return this.formGroup.at(this.activeFormGroupIndex) as FormGroup;
      return this.formGroup;
    }
 
    return this.formGroup as FormGroup;
  }
 
  /**
   * @description String formatting utility function.
   * @summary Provides access to the sf (string format) function for formatting error messages
   * and other string templates. Used primarily for localizing and parameterizing validation messages.
   * @type {function(string, ...string): string}
   * @public
   */
  sf = sf;
 
  /**
   * @description Callback function invoked when the field value changes.
   * @summary Function registered by Angular's forms system through registerOnChange.
   * Called automatically when the field's value is updated to notify the form of the change.
   * @type {function(): unknown}
   * @public
   */
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  onChange: () => unknown = () => {};
 
  /**
   * @description Callback function invoked when the field is touched.
   * @summary Function registered by Angular's forms system through registerOnTouched.
   * Called when the field is blurred or otherwise marked as touched.
   * @type {function(): unknown}
   * @public
   */
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  onTouch: () => unknown = () => {};
 
  /**
   * @description Writes a value to the form field.
   * @summary Part of Angular's ControlValueAccessor interface. Sets the field's value
   * when the form programmatically updates it. This is called by Angular forms when
   * the model value changes.
   * @param {string} obj - The value to be set
   * @return {void}
   * @public
   */
  writeValue(obj: string): void {
    this.value = obj;
  }
 
  /**
   * @description Registers the onChange callback function.
   * @summary Part of Angular's ControlValueAccessor interface. Stores the function
   * that Angular forms provides to be called when the field value changes.
   * @param {function(): unknown} fn - The function to be called on change
   * @return {void}
   * @public
   */
  registerOnChange(fn: () => unknown): void {
    this.onChange = fn;
  }
 
  /**
   * @description Registers the onTouched callback function.
   * @summary Part of Angular's ControlValueAccessor interface. Stores the function
   * that Angular forms provides to be called when the field is touched/blurred.
   * @param {function(): unknown} fn - The function to be called on touch
   * @return {void}
   * @public
   */
  registerOnTouched(fn: () => unknown): void {
    this.onTouch = fn;
  }
 
  /**
   * @description Sets the disabled state of the field.
   * @summary Part of Angular's ControlValueAccessor interface. Called by Angular forms
   * when the disabled state of the control changes.
   * @param {boolean} isDisabled - Whether the field should be disabled
   * @return {void}
   * @public
   */
  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
 
  /**
   * @description Performs setup after the view has been initialized.
   * @summary Retrieves and returns the parent HTML element based on the current CRUD operation.
   * For READ and DELETE operations, returns the immediate parent element. For CREATE and UPDATE
   * operations, finds the parent div element and registers it with the form service.
   * @return {HTMLElement} The parent element of the field
   * @throws {RenderingError} If unable to retrieve parent form element for CREATE/UPDATE operations
   * @throws {InternalError} If the operation is invalid
   * @public
   */
  afterViewInit(): HTMLElement {
    this.checkDarkMode();
    let parent: HTMLElement;
    Iif (this.component?.nativeElement)
      this.isModalChild = this.component.nativeElement.closest('ion-modal') ? true : false;
    switch (this.operation) {
      case OperationKeys.READ:
      case OperationKeys.DELETE:
        return this.component.nativeElement.parentElement;
      case OperationKeys.CREATE:
      case OperationKeys.UPDATE:
        try {
          parent = NgxFormService.getParentEl(this.component.nativeElement, 'div');
        } catch (e: unknown) {
          throw new RenderingError(
            `Unable to retrieve parent form element for the ${this.operation}: ${e instanceof Error ? e.message : e}`
          );
        }
        // NgxFormService.register(parent.id, this.formGroup, this as AngularFieldDefinition);
        return parent;
      default:
        throw new InternalError(`Invalid operation: ${this.operation}`);
    }
  }
 
  /**
   * @description Angular lifecycle hook for detecting input property changes.
   * @summary Overrides the parent ngOnChanges to handle changes to activeFormGroupIndex and value.
   * When activeFormGroupIndex changes in a multiple field scenario, updates the active form group
   * and form control. When value changes, updates the form control value. Delegates to parent
   * implementation for initial change detection.
   * @param {SimpleChanges} changes - Object containing the changed properties
   * @return {void}
   * @public
   */
  override async ngOnChanges(changes: SimpleChanges): Promise<void> {
    Iif (!this.initialized) {
      await super.ngOnChanges(changes);
    }
    Iif (
      changes['activeFormGroupIndex'] &&
      this.multiple &&
      !changes['activeFormGroupIndex'].isFirstChange() &&
      changes['activeFormGroupIndex'].currentValue !== this.activeFormGroupIndex
    ) {
      this.activeFormGroupIndex = changes['activeFormGroupIndex'].currentValue;
      this.formGroup = this.activeFormGroup;
      this.formControl = this.formGroup.get(this.name) as FormControl;
    }
    Iif (
      changes['value'] &&
      !changes['value'].isFirstChange() &&
      changes['value'].currentValue !== undefined &&
      changes['value'].currentValue !== this.value
    )
      this.setValue(changes['value'].currentValue);
  }
 
  /**
   * @description Cleanup logic when the component is destroyed.
   * @summary Unregisters the form group from the form service to prevent memory leaks
   * and clean up form references.
   * @return {void}
   * @public
   */
  onDestroy(): void {
    Iif (this.formGroup) NgxFormService.unregister(this.formGroup);
  }
 
  getValue(): unknown {
    const value = this.formControl?.value || this.formGroup?.get(this.name)?.value;
    Iif (value) {
      this.value = value;
    }
    return value;
  }
 
  /**
   * @description Sets the value of the form control.
   * @summary Updates the form control's value and triggers validation. This is used
   * when the value needs to be programmatically updated from outside the form control.
   * @param {unknown} value - The value to set
   * @return {void}
   * @public
   */
  setValue(value: unknown): void {
    if (this.formControl) {
      this.formControl.setValue(value);
      this.formControl.updateValueAndValidity();
    }
    this.value = value as string | number | Date | string[];
  }
 
  /**
   * @description Clears the current form control value as a response to a UI interact
   * @summary Set field value as undefined and proverride  event propagation.
   * @param {Event} event - The value to set
   * @return {void}
   * @public
   */
  handleClearValue(event: Event): void {
    event.preventDefault();
    event.stopPropagation();
    this.setValue(undefined);
  }
 
  /**
   * @description Handles IonSelect change override  emitted from modal child components.
   * @summary Forces change detection when rendered inside a modal and synchronizes the select value with the directive state.
   * @param {SelectCustomEvent<SelectChangeEventDetail>} event - IonSelect change event containing the selected value.
   * @return {void}
   * @public
   */
  handleModalChildChanges(event?: SelectCustomEvent, formControl?: AbstractControl): void {
    const element = this.component?.nativeElement;
    Iif (this.type === HTML5InputTypes.SELECT && event) {
      const { value } = event.detail;
      this.value = value;
    }
    Iif (element && formControl && !formControl.valid && formControl.updateOn === 'change') {
      element.dispatchEvent(new Event('ionBlur'));
    }
    Iif (this.isModalChild) {
      this.changeDetectorRef.detectChanges();
    }
  }
 
  private validateControl(formControl: AbstractControl): boolean {
    return (
      (!formControl.valid && (formControl.touched || !formControl.pristine)) ||
      (!formControl.valid && formControl.dirty && formControl.updateOn === 'change')
    );
  }
 
  private getErrorMessage(error: Record<string, string>): string {
    const instance = this as KeyValue;
    let { message } = error;
    const { key } = error;
    const prop = instance[key];
    let args = [] as string[];
    if (typeof message === Primitives.STRING) {
      Iif (message.includes('|')) {
        const parts = message.split('|');
        message = parts[0];
        parts.shift();
        parts.forEach((part) => {
          args = [...args, part];
        });
      } else {
        if (prop) {
          args = [prop];
        }
      }
    } else {
      args = Object.values(message).map((v) => `${v || prop}`) as string[];
      message = key;
    }
    // Check if string already be translated by validator
    const translate = (message: string, args: string[]): string => {
      return this.translateService.instant(
        !message.includes(AngularEngineKeys.ERRORS) ? `${AngularEngineKeys.ERRORS}.${message}` : message,
        args
      );
    };
    return /\s/.test(message) && message !== key ? message : translate(message, args);
  }
 
  /**
   * @description Retrieves validation error messages for the field.
   * @summary Checks the form control for validation errors and returns formatted error messages.
   * If errors exist, dispatches a validation error event to parent accordion components.
   * Error messages are translated and formatted with relevant field properties.
   * @param {HTMLElement} parent - The parent HTML element used to find accordion components
   * @return {string | void} Formatted error message string, or void if no errors
   * @public
   */
  getErrors(parent: HTMLElement): string | void {
    const formControl = this.formControl;
    if (formControl) {
      const accordionComponent = parent.closest('ngx-decaf-fieldset')?.querySelector('ion-accordion-group');
      const invalid = this.validateControl(formControl);
      if (invalid) {
        const errors: Record<string, string>[] = Object.entries(formControl.errors ?? {}).map(([key, value]) => {
          const message = typeof value === 'boolean' ? key : value;
          return {
            key: key,
            message,
          };
        });
        if (errors.length) {
          Iif (accordionComponent && !this.validationErrorEventDispatched) {
            const validationErrorEvent = new CustomEvent(ComponentEventNames.ValidationError, {
              detail: { fieldName: this.name, hasErrors: true },
              bubbles: true,
            });
            accordionComponent.dispatchEvent(validationErrorEvent);
            this.validationErrorEventDispatched = true;
          }
        }
        for (const error of errors) {
          return `* ${this.getErrorMessage(error)}`;
        }
      }
    }
  }
}