|
| 1 | +import * as Immutable from "immutable"; |
| 2 | +import { BaseContainer, BaseContainerParentContext } from "@simplr/react-forms"; |
| 3 | +import { FormStore } from "@simplr/react-forms/stores"; |
| 4 | +import { FormError, FieldValidationStatus } from "@simplr/react-forms/contracts"; |
| 5 | + |
| 6 | +export type BaseErrorsContainerProps = {}; |
| 7 | + |
| 8 | +export type FieldErrors = Immutable.Map<string, FormError>; |
| 9 | + |
| 10 | +export interface BaseErrorsContainerState { |
| 11 | + FieldErrors: FieldErrors; |
| 12 | + FormError?: FormError; |
| 13 | +} |
| 14 | + |
| 15 | +export abstract class BaseErrorsContainer<TProps extends BaseErrorsContainerProps, TState extends BaseErrorsContainerState> |
| 16 | + extends BaseContainer<TProps, TState> { |
| 17 | + public state: TState = { |
| 18 | + FieldErrors: Immutable.Map<string, FormError>() |
| 19 | + } as TState; |
| 20 | + |
| 21 | + protected OnStoreUpdated(): void { |
| 22 | + const storeState = this.FormStore.GetState(); |
| 23 | + |
| 24 | + if (!storeState.HasError) { |
| 25 | + this.setState(state => { |
| 26 | + state.FieldErrors = Immutable.Map<string, FormError>(); |
| 27 | + state.FormError = undefined; |
| 28 | + return state; |
| 29 | + }); |
| 30 | + return; |
| 31 | + } |
| 32 | + const formError = storeState.Form.Error; |
| 33 | + const fieldsWithError = storeState |
| 34 | + .FieldsValidationStatuses |
| 35 | + .filter(x => x != null && x === FieldValidationStatus.HasError) |
| 36 | + .keySeq() |
| 37 | + .toArray(); |
| 38 | + |
| 39 | + const fieldsErrors: { [id: string]: FormError } = {}; |
| 40 | + |
| 41 | + fieldsWithError.forEach(fieldId => { |
| 42 | + const fieldError = storeState.Fields.get(fieldId).Error; |
| 43 | + if (fieldError != null) { |
| 44 | + fieldsErrors[fieldId] = fieldError; |
| 45 | + } |
| 46 | + }); |
| 47 | + |
| 48 | + this.setState(state => { |
| 49 | + state.FormError = formError; |
| 50 | + state.FieldErrors = Immutable.Map<string, FormError>(fieldsErrors); |
| 51 | + |
| 52 | + return state; |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + public abstract render(): JSX.Element | null; |
| 57 | +} |
0 commit comments