aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/shared-forms/form-reactive.ts
blob: acaeaba33e529c9738194809634334b37e200da6 (plain) (blame)
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
import { AbstractControl, FormGroup } from '@angular/forms'
import { wait } from '@root-helpers/utils'
import { BuildFormArgument, BuildFormDefaultValues } from '../form-validators/form-validator.model'
import { FormReactiveErrors, FormReactiveValidationMessages } from './form-reactive.service'
import { FormValidatorService } from './form-validator.service'

export abstract class FormReactive {
  protected abstract formValidatorService: FormValidatorService
  protected formChanged = false

  form: FormGroup
  formErrors: any // To avoid casting in template because of string | FormReactiveErrors
  validationMessages: FormReactiveValidationMessages

  buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) {
    const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues)

    this.form = form
    this.formErrors = formErrors
    this.validationMessages = validationMessages

    this.form.statusChanges.subscribe(async () => {
      // FIXME: remove when https://github.com/angular/angular/issues/41519 is fixed
      await this.waitPendingCheck()

      this.onStatusChanged(this.form, this.formErrors, this.validationMessages)
    })
  }

  protected async waitPendingCheck () {
    if (this.form.status !== 'PENDING') return

    // FIXME: the following line does not work: https://github.com/angular/angular/issues/41519
    // return firstValueFrom(this.form.statusChanges.pipe(filter(status => status !== 'PENDING')))
    // So we have to fallback to active wait :/

    do {
      await wait(10)
    } while (this.form.status === 'PENDING')
  }

  protected markAllAsDirty (controlsArg?: { [ key: string ]: AbstractControl }) {
    const controls = controlsArg || this.form.controls

    for (const key of Object.keys(controls)) {
      const control = controls[key]

      if (control instanceof FormGroup) {
        this.markAllAsDirty(control.controls)
        continue
      }

      control.markAsDirty()
    }
  }

  protected forceCheck () {
    this.onStatusChanged(this.form, this.formErrors, this.validationMessages, false)
  }

  private onStatusChanged (
    form: FormGroup,
    formErrors: FormReactiveErrors,
    validationMessages: FormReactiveValidationMessages,
    onlyDirty = true
  ) {
    for (const field of Object.keys(formErrors)) {
      if (formErrors[field] && typeof formErrors[field] === 'object') {
        this.onStatusChanged(
          form.controls[field] as FormGroup,
          formErrors[field] as FormReactiveErrors,
          validationMessages[field] as FormReactiveValidationMessages,
          onlyDirty
        )
        continue
      }

      // clear previous error message (if any)
      formErrors[field] = ''
      const control = form.get(field)

      if (control.dirty) this.formChanged = true

      if (!control || (onlyDirty && !control.dirty) || !control.enabled || !control.errors) continue

      const staticMessages = validationMessages[field]
      for (const key of Object.keys(control.errors)) {
        const formErrorValue = control.errors[key]

        // Try to find error message in static validation messages first
        // Then check if the validator returns a string that is the error
        if (staticMessages[key]) formErrors[field] += staticMessages[key] + ' '
        else if (typeof formErrorValue === 'string') formErrors[field] += control.errors[key]
        else throw new Error('Form error value of ' + field + ' is invalid')
      }
    }
  }
}