stores: add validation store

This commit is contained in:
Chika 2022-05-10 10:49:51 +03:00
parent b5c0ecd8bd
commit f0efc075fb
3 changed files with 58 additions and 0 deletions

View File

@ -2,16 +2,19 @@
import RootStore from 'stores/root';
import OptionsStore from './options';
import StatusStore from './statuses';
import ValidationStore from './validation';
import ValuesStore from './values';
export default class CalculationStore {
$values: ValuesStore;
$status: StatusStore;
$options: OptionsStore;
$validation: ValidationStore;
constructor(rootStore: RootStore) {
this.$values = new ValuesStore(rootStore);
this.$status = new StatusStore(rootStore);
this.$options = new OptionsStore(rootStore);
this.$validation = new ValidationStore(rootStore);
}
}

View File

@ -0,0 +1,50 @@
/* eslint-disable import/no-cycle */
/* eslint-disable implicit-arrow-linebreak */
/* eslint-disable object-curly-newline */
import type { Elements } from 'Components/Calculation/config/map';
import { makeAutoObservable, observable } from 'mobx';
import RootStore from 'stores/root';
import type { Error, Messages } from './types';
export default class ValidationStore {
root: RootStore;
#messages: Partial<Messages> = {};
constructor(rootStore: RootStore) {
makeAutoObservable(this);
this.root = rootStore;
}
getValidation(elementName: Elements) {
return {
isValid: !this.#messages[elementName]?.length,
messages: this.#messages[elementName]?.map((x) => x.text),
};
}
addError(elementName: Elements, error: Error) {
if (!this.#messages[elementName]) this.#messages[elementName] = observable([]);
const errorIndex = this.#messages[elementName]?.findIndex((x) => x.name === error.name);
const hasError = errorIndex !== undefined && errorIndex !== -1;
if (!hasError) {
this.#messages[elementName]?.push(error);
} else {
this.#messages[elementName]?.splice(errorIndex, 1, error);
}
// TODO: call notification
return () => this.#removeError(elementName, error.name);
}
#removeError(elementName: Elements, errorName: string) {
const messageIndex = this.#messages[elementName]?.findIndex((x) => x.name === errorName);
if (messageIndex) this.#messages[elementName]?.splice(messageIndex, 1);
}
clearErrors(elementName: Elements) {
this.#messages[elementName]?.clear();
}
}

View File

@ -0,0 +1,5 @@
import type { Elements } from 'Components/Calculation/config/map';
import type { IObservableArray } from 'mobx';
export type Error = { name: string; text: string };
export type Messages = Record<Elements, IObservableArray<Error>>;