2022-06-23 19:22:57 +03:00

55 lines
1.7 KiB
TypeScript

/* eslint-disable object-curly-newline */
import type { Elements } from 'Components/Calculation/config/map/values';
import { makeAutoObservable, observable } from 'mobx';
import type RootStore from 'stores/root';
import type { ElementsErrors, Error } from './types';
export default class ValidationStore {
root: RootStore;
elementsErrors: Partial<ElementsErrors> = {};
constructor(rootStore: RootStore) {
makeAutoObservable(this);
this.root = rootStore;
}
hasErrors() {
return (Object.keys(this.elementsErrors) as Elements[]).some(
(elementName) => this.elementsErrors[elementName]?.length
);
}
getValidation(elementName: Elements) {
return {
isValid: !this.elementsErrors[elementName]?.length,
errors: this.elementsErrors[elementName]?.map((x) => x.text),
};
}
addError = (elementName: Elements, error: Error) => {
if (!this.elementsErrors[elementName]) this.elementsErrors[elementName] = observable([]);
const errorIndex = this.elementsErrors[elementName]?.findIndex((x) => x.name === error.name);
const hasError = errorIndex !== undefined && errorIndex !== -1;
if (!hasError) {
this.elementsErrors[elementName]?.push(error);
} else {
this.elementsErrors[elementName]?.splice(errorIndex, 1, error);
}
// TODO: call notification
return () => this.#removeError(elementName, error.name);
};
#removeError = (elementName: Elements, errorName: Error['name']) => {
const errorIndex = this.elementsErrors[elementName]?.findIndex((x) => x.name === errorName);
if (errorIndex) this.elementsErrors[elementName]?.splice(errorIndex, 1);
};
clearErrors = (elementName: Elements) => {
this.elementsErrors[elementName]?.clear();
};
}