54 lines
1.5 KiB
TypeScript
54 lines
1.5 KiB
TypeScript
import { ElementsTypes, getValueName } from 'Components/Calculation/config/map';
|
|
import { Elements } from 'Components/Calculation/types/elements';
|
|
import { makeAutoObservable } from 'mobx';
|
|
import { RootStore } from '../../root';
|
|
import { Values, ValuesTypes } from './types';
|
|
|
|
export class ValuesStore {
|
|
root: RootStore;
|
|
#values: Partial<ValuesTypes> = {};
|
|
|
|
constructor(rootStore: RootStore) {
|
|
makeAutoObservable(this);
|
|
this.root = rootStore;
|
|
}
|
|
|
|
hydrate = (initialValues: Partial<ValuesTypes>) => {
|
|
this.#values = initialValues;
|
|
};
|
|
|
|
getValue<V extends Values>(valueName: V) {
|
|
return this.#values[valueName];
|
|
}
|
|
|
|
getValueByElement<E extends Elements>(elementName: E) {
|
|
const valueName = getValueName(elementName);
|
|
return this.getValue(valueName) as ElementsTypes[E] | undefined;
|
|
}
|
|
|
|
getValues<K extends Values>(valuesNames: readonly K[]) {
|
|
return valuesNames.reduce((values, valueName) => {
|
|
values[valueName] = this.getValue(valueName);
|
|
return values;
|
|
}, {} as Pick<Partial<ValuesTypes>, typeof valuesNames[number]>);
|
|
}
|
|
|
|
setValue(valueName: Values, value: any) {
|
|
this.#values[valueName] = value;
|
|
}
|
|
|
|
setValues(values: Partial<ValuesTypes>, options: { replace?: boolean }) {
|
|
if (options.replace) this.#values = values;
|
|
this.#values = Object.assign(this.#values, values);
|
|
}
|
|
|
|
clearValue(valueName: Values) {
|
|
this.setValue(valueName, null);
|
|
}
|
|
|
|
clearValueOfElement(elementName: Elements) {
|
|
const valueName = getValueName(elementName);
|
|
this.clearValue(valueName);
|
|
}
|
|
}
|