]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/forms/form-reactive.ts
Fix adding captions to a video
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / forms / form-reactive.ts
1 import { FormGroup } from '@angular/forms'
2 import { BuildFormArgument, BuildFormDefaultValues, FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service'
3
4 export type FormReactiveErrors = { [ id: string ]: string }
5 export type FormReactiveValidationMessages = {
6 [ id: string ]: {
7 [ name: string ]: string
8 }
9 }
10
11 export abstract class FormReactive {
12 protected abstract formValidatorService: FormValidatorService
13 protected formChanged = false
14
15 form: FormGroup
16 formErrors: FormReactiveErrors
17 validationMessages: FormReactiveValidationMessages
18
19 buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) {
20 const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues)
21
22 this.form = form
23 this.formErrors = formErrors
24 this.validationMessages = validationMessages
25
26 this.form.valueChanges.subscribe(() => this.onValueChanged(false))
27 }
28
29 protected onValueChanged (forceCheck = false) {
30 for (const field in this.formErrors) {
31 // clear previous error message (if any)
32 this.formErrors[ field ] = ''
33 const control = this.form.get(field)
34
35 if (control.dirty) this.formChanged = true
36
37 // Don't care if dirty on force check
38 const isDirty = control.dirty || forceCheck === true
39 if (control && isDirty && !control.valid) {
40 const messages = this.validationMessages[ field ]
41 for (const key in control.errors) {
42 this.formErrors[ field ] += messages[ key ] + ' '
43 }
44 }
45 }
46 }
47
48 protected forceCheck () {
49 return this.onValueChanged(true)
50 }
51 }