49 lines
1.5 KiB
TypeScript
49 lines
1.5 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 { 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();
|
|
};
|
|
}
|