All files / src/lib/engine NgxFormDirective.ts

34.48% Statements 30/87
7.14% Branches 3/42
28.57% Functions 4/14
34.14% Lines 28/82

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 4283x                     3x 3x 3x 3x       3x 3x   3x 3x       3x                             2x     2x                     2x                                             2x                       2x                       2x                                                                   2x                                                                 2x                         2x     2x     2x                                                                                 2x                                 3x   3x       3x                                             2x                       2x 2x                                                                                                                                                                                                                                                                                      
import {
  AfterViewInit,
  Directive,
  ElementRef,
  EventEmitter,
  Input,
  OnDestroy,
  Output,
  SimpleChanges,
  ViewChild,
} from '@angular/core';
import { FormArray, FormGroup } from '@angular/forms';
import { CrudOperations, OperationKeys } from '@decaf-ts/db-decorators';
import { ComponentEventNames } from '@decaf-ts/ui-decorators';
import { NgxFormService } from '../services/NgxFormService';
import { IBaseCustomEvent, ICrudFormEvent, IFormElement } from './interfaces';
import { FieldUpdateMode, FormParent, HTMLFormTarget } from './types';
import { ICrudFormOptions, IRenderedModel } from './interfaces';
import { ActionRoles } from './constants';
import { NgxParentComponentDirective } from './NgxParentComponentDirective';
import { NgxFormFieldDirective } from './NgxFormFieldDirective';
import { generateRandomValue } from '../utils';
import { timer } from 'rxjs';
import { FieldDefinition, UIFunctionLike, UIModelMetadata } from '@decaf-ts/ui-decorators';
 
@Directive()
export abstract class NgxFormDirective
  extends NgxParentComponentDirective
  implements AfterViewInit, IFormElement, OnDestroy, IRenderedModel
{
  /**
   * @description Reactive form group associated with this fieldset.
   * @summary The FormGroup instance that contains all form controls within this fieldset.
   * Used for form validation, value management, and integration with Angular's reactive forms.
   *
   * @type {FormGroup}
   */
  @Input()
  parentFormId!: string;
 
  @Input()
  deepMerge: boolean = false;
 
  @Input()
  path: string = '';
 
  /**
   * @description Enables multiple item management within the fieldset.
   * @summary Boolean flag that determines if the fieldset supports adding multiple values.
   * When true, displays a reorderable list of items with add/remove functionality.
   *
   * @type {boolean}
   * @default false
   */
  @Input()
  multiple: boolean = false;
 
  /**
   * @description Reference to the reactive form DOM element.
   * @summary ViewChild reference that provides direct access to the form's DOM element.
   * This enables programmatic manipulation of the form element and access to native
   * HTML form properties and methods when needed.
   *
   * @type {ElementRef}
   */
  @ViewChild('component', { static: false, read: ElementRef })
  override component!: ElementRef;
 
  /**
   * @description Field update trigger mode for form validation.
   * @summary Determines when form field validation should be triggered. Options include
   * 'change', 'blur', or 'submit'. This affects the user experience by controlling
   * when validation feedback is shown to the user during form interaction.
   *
   * @type {FieldUpdateMode}
   * @default 'change'
   */
  @Input()
  updateOn: FieldUpdateMode = 'change';
 
  /**
   * @description Form submission target specification.
   * @summary Specifies where to display the response after form submission, similar
   * to the HTML form target attribute. Options include '_self', '_blank', '_parent',
   * '_top', or a named frame. Controls the browser behavior for form responses.
   *
   * @type {HTMLFormTarget}
   * @default '_self'
   */
  @Input()
  target: HTMLFormTarget = '_self';
 
  /**
   * @description HTTP method or submission strategy for the form.
   * @summary Defines how the form should be submitted. 'get' and 'post' correspond
   * to standard HTTP methods for traditional form submission, while 'event' uses
   * Angular event-driven submission for single-page application workflows.
   *
   * @type {'get' | 'post' | 'event'}
   * @default 'event'
   */
  @Input()
  method: 'get' | 'post' | 'event' = 'event';
 
  /**
   * @description Configuration options for the CRUD form behavior.
   * @summary Contains various configuration settings that control form rendering,
   * validation, and behavior. These options are merged with default settings
   * during component initialization to customize the form's functionality.
   *
   * @type {ICrudFormOptions}
   */
  @Input()
  options!: ICrudFormOptions;
 
  /**
   * @description Optional action identifier for form submission context.
   * @summary Specifies a custom action name that will be included in the submit event.
   * If not provided, defaults to the standard submit event constant. Used to
   * distinguish between different types of form submissions within the same component.
   *
   * @type {string | undefined}
   */
  @Input()
  action?: string;
 
  /**
   * @description The current CRUD operation being performed.
   * @summary Specifies the type of operation this form is handling (CREATE, READ, UPDATE, DELETE).
   * This is a required input that determines form behavior, validation rules, and available actions.
   * The operation affects form state, button visibility, and submission logic.
   *
   * @type {CrudOperations}
   * @required
   */
  @Input({ required: true })
  override operation: CrudOperations = OperationKeys.CREATE;
 
  /**
   * @description Custom event handlers for form actions.
   * @summary A record of event handler functions keyed by event names that can be
   * triggered during form operations. These handlers provide extensibility for
   * custom business logic and can be invoked for various form events and actions.
   *
   * @type {Record<string, UIFunctionLike>}
   */
  @Input()
  override handlers!: Record<string, UIFunctionLike>;
 
  /**
   * @description Unique identifier for the form renderer.
   * @summary A unique string identifier used to register and manage this form
   * instance within the NgxFormService. This ID is also used as the HTML id
   * attribute for the form element, enabling DOM queries and form management.
   *
   * @type {string}
   */
  @Input()
  rendererId!: string;
 
  /**
   * @description Event emitter for form submission events.
   * @summary Emits ICrudFormEvent objects when the form is submitted, providing
   * form data, component information, and any associated handlers to parent
   * components. This enables decoupled handling of form submission logic.
   *
   * @type {EventEmitter<ICrudFormEvent>}
   */
  @Output()
  submitEvent: EventEmitter<ICrudFormEvent> = new EventEmitter<ICrudFormEvent>();
 
  /**
   * @description Unique identifier for the current record instance.
   * @summary This property holds a unique string value that identifies the specific record being managed by the form.
   * It is automatically generated if not provided, ensuring each form instance has a distinct identifier.
   * The uid is used for tracking, referencing, and emitting events related to the current record, and may be used
   * in conjunction with the primary key for CRUD operations.
   *
   * @type {string}
   * @default Randomly generated 12-character string
   */
  @Input()
  allowClear: boolean = false;
 
  @Input()
  override match: boolean = false;
 
  @Output()
  private formGroupLoadedEvent: EventEmitter<IBaseCustomEvent> =
    new EventEmitter<IBaseCustomEvent>();
 
  // protected override enableDarkMode: boolean = true;
 
  //   /**
  //  * @description Angular change detection service.
  //  * @summary Injected service that provides manual control over change detection cycles.
  //  * This is essential for ensuring that programmatic DOM changes (like setting accordion
  //  * attributes) are properly reflected in the component's state and trigger appropriate
  //  * view updates when modifications occur outside the normal Angular change detection flow.
  //  *
  //  * @protected
  //  * @type {ChangeDetectorRef}
  //  * @memberOf CrudFormComponent
  //  */
  // protected changeDetectorRef: ChangeDetectorRef = inject(ChangeDetectorRef);
 
  // /**
  //  * @description Angular Renderer2 service for safe DOM manipulation.
  //  * @summary Injected service that provides a safe, platform-agnostic way to manipulate DOM elements.
  //  * This service ensures proper handling of DOM operations across different platforms and environments,
  //  * including server-side rendering and web workers.
  //  *
  //  * @protected
  //  * @type {Renderer2}
  //  * @memberOf CrudFormComponent
  //  */
  // protected renderer: Renderer2 = inject(Renderer2);
 
  // /**
  //  * @description Translation service for internationalization.
  //  * @summary Injected service that provides translation capabilities for UI text.
  //  * Used to translate button labels and validation messages based on the current locale.
  //  *
  //  * @protected
  //  * @type {TranslateService}
  //  * @memberOf CrudFormComponent
  //  */
  // protected translateService: TranslateService = inject(TranslateService);
 
  protected activeFormGroupIndex: number = 0;
 
  get activeFormGroup(): FormParent {
    return this.getFormArrayIndex(this.activeFormGroupIndex) as FormParent;
  }
 
  /**
   * @description Component initialization lifecycle method.
   * @summary Initializes the component by setting up the logger, configuring form state
   * based on the operation type, and merging configuration options. For READ and DELETE
   * operations, the formGroup is set to undefined since these operations don't require
   * form input. Configuration options are merged with default settings.
   *
   * @returns {Promise<void>}
   */
 
  override async initialize(): Promise<void> {
    await super.initialize();
 
    Iif (!this.uid) {
      this.uid = generateRandomValue(12);
    }
    // dont call super.ngOnInit to model conflicts
    Iif (this.operation === OperationKeys.READ || this.operation === OperationKeys.DELETE) {
      this.formGroup = undefined;
    }
  }
 
  override async ngOnChanges(changes: SimpleChanges): Promise<void> {
    await super.ngOnChanges(changes);
 
    // if (changes[BaseComponentProps.MODEL_ID]) {
    //   const { previousValue, currentValue } = changes[BaseComponentProps.MODEL_ID];
    //   if (!previousValue && currentValue) {
    //     await this.refresh(this.operation);
    //   }
    // }
  }
 
  async ngAfterViewInit(): Promise<void> {
    //TODO: ver se isso é necessário
    // if (this.formGroup)
    //   this.formGroupLoadedEvent.emit({
    //     name: ComponentEventNames.FormGroupLoaded,
    //     data: this.formGroup as FormParent,
    //   });
    this.changeDetectorRef.detectChanges();
  }
 
  /**
   * @description Component cleanup lifecycle method.
   * @summary Performs cleanup operations when the component is destroyed.
   * Unregisters the FormGroup from the NgxFormService to prevent memory leaks
   * and ensure proper resource cleanup.
   *
   * @returns {void}
   */
  override async ngOnDestroy(): Promise<void> {
    await super.ngOnDestroy();
    if (this.formGroup) NgxFormService.unregister(this.formGroup);
  }
 
  getFormArrayIndex(index: number): FormParent | undefined {
    Iif (!(this.formGroup instanceof FormArray) && this.formGroup) {
      Iif (this.formGroup.disabled) (this.formGroup as FormParent).enable();
      return this.formGroup;
    }
 
    const formGroup = (this.formGroup as FormArray).at(index) as FormGroup;
    Iif (formGroup.disabled) (formGroup as FormParent).enable();
    Iif (formGroup) {
      Iif (this.children.length) {
        const children = [...this.children];
        this.children = [];
        this.changeDetectorRef.detectChanges();
        this.children = [
          ...children.map((child) => {
            const props = (child.props || {}) as NgxFormFieldDirective;
            const name = props.name;
            const control = formGroup.get(name);
            child.props.value = control?.value;
            child.props.formGroup = formGroup;
            child.props.activeFormGroupIndex = index;
            child.props.formControl = control;
            return child;
          }),
        ];
        this.changeDetectorRef.detectChanges();
      }
    }
    return formGroup || undefined;
  }
 
  // override async handleEvent(event: IBaseCustomEvent): Promise<void> {
  //   await super.handleEvent(event);
  // }
 
  /**
   * @description Handles form reset or navigation back functionality.
   * @summary Provides different reset behavior based on the current operation.
   * For CREATE and UPDATE operations, resets the form to its initial state.
   * For READ and DELETE operations, navigates back in the browser history
   * since these operations don't have modifiable form data to reset.
   *
   * @returns {void}
   */
  handleReset(): void {
    Iif (this.isModalChild)
      return this.submitEventEmit(null, this.componentName, ActionRoles.cancel);
    Iif (![OperationKeys.DELETE, OperationKeys.READ].includes(this.operation) && this.allowClear)
      return NgxFormService.reset(this.formGroup as FormGroup);
    this.location.back();
  }
 
  override async submit(
    event?: SubmitEvent,
    eventName?: string,
    componentName?: string,
  ): Promise<boolean | void> {
    Iif (event) {
      event.preventDefault();
      event.stopImmediatePropagation();
    }
    const formGroup = this.formGroup as FormGroup;
    this.changeDetectorRef.detectChanges();
 
    const isValid = NgxFormService.validateFields(formGroup);
 
    Iif (!isValid) {
      NgxFormService.enableAllGroupControls(formGroup);
      return false;
    }
    const data = NgxFormService.getFormData(formGroup);
    Iif (Object.keys(data).length > 0)
      return this.submitEventEmit(data, eventName, componentName, this.handlers);
  }
  protected submitEventEmit(
    data: unknown,
    componentName?: string,
    eventName?: string,
    handlers?: Record<string, UIFunctionLike>,
    role?: CrudOperations,
  ): void {
    const name = eventName || this.action || ComponentEventNames.Submit;
    const handler = handlers?.[name] || this.handlers?.[name] || undefined;
    this.submitEvent.emit({
      data,
      component: componentName || this.componentName,
      name: eventName || this.action || ComponentEventNames.Submit,
      role: role || this.operation,
      handler: handler,
      handlers: this.handlers || {},
      ...(this.operation !== OperationKeys.CREATE ? { modelId: this.modelId } : {}),
    });
  }
 
  /**
   * @description Updates the active form group and children for the specified page.
   * @summary Extracts the FormGroup for the given page from the FormArray and filters
   * the children to show only fields belonging to that page. Uses a timer to ensure
   * proper Angular change detection when updating the activeContent.
   *
   * @param {number} page - The page number to activate
   * @return {UIModelMetadata | UIModelMetadata[] | FieldDefinition | undefined}
   *
   * @private
   * @mermaid
   * sequenceDiagram
   *   participant S as SteppedFormComponent
   *   participant F as FormArray
   *   participant T as Timer
   *
   *   S->>F: Extract FormGroup at index (page - 1)
   *   F-->>S: Return page FormGroup
   *   S->>S: Set activeContent = undefined
   *   S->>T: timer(10).subscribe()
   *   T-->>S: Filter children for active page
   *   S->>S: Set activeContent
   *
   * @memberOf SteppedFormComponent
   */
  protected override getActivePage(
    page: number,
  ): UIModelMetadata | UIModelMetadata[] | FieldDefinition | undefined {
    Iif (!(this.formGroup instanceof FormArray))
      this.formGroup = this.formGroup?.parent as FormArray;
    this.formGroup = (this.formGroup as FormArray).at(page - 1) as FormGroup;
    this.activePage = undefined;
    this.timerSubscription = timer(10).subscribe(
      () =>
        (this.activePage = (this.children as UIModelMetadata[]).filter(
          (c) => c.props?.['page'] === page,
        )),
    );
    Iif (this.activePage) return this.activePage;
    return undefined;
  }
}