56 lines
1.6 KiB
TypeScript
56 lines
1.6 KiB
TypeScript
import { Elements } from 'Components/Calculation/types/elements';
|
|
import { mergeWith } from 'lodash';
|
|
import { makeAutoObservable } from 'mobx';
|
|
import { RootStore } from 'stores/root';
|
|
import { BaseOption } from './types';
|
|
|
|
type Options = BaseOption[];
|
|
type CalculationOptions = Record<Elements, Options>;
|
|
type OptionsFilters = Record<Elements, (options: Options) => Options>;
|
|
|
|
export class OptionsStore {
|
|
root: RootStore;
|
|
#options: Partial<CalculationOptions> = {};
|
|
#filters: Partial<OptionsFilters> = {};
|
|
|
|
constructor(rootStore: RootStore) {
|
|
makeAutoObservable(this);
|
|
this.root = rootStore;
|
|
}
|
|
|
|
hydrate = (initialOptions: Partial<CalculationOptions>) => {
|
|
this.#options = initialOptions;
|
|
};
|
|
|
|
getOption(elementName: Elements) {
|
|
const value = this.root.$calculation.$values.getValueByElement(elementName);
|
|
return this.#options[elementName]?.find(x => x.value === value);
|
|
}
|
|
|
|
getOptions(elementName: Elements, { filtered = true }) {
|
|
const options = this.#options[elementName];
|
|
if (!options) return;
|
|
|
|
if (!filtered) return options;
|
|
|
|
const filter = this.#filters[elementName];
|
|
return filter ? filter(options) : options;
|
|
}
|
|
|
|
setOptions(elementName: Elements, options: Options) {
|
|
this.#options[elementName] = options;
|
|
}
|
|
|
|
mergeOptions(options: Partial<CalculationOptions>) {
|
|
mergeWith(this.#options, options, function (objValue, srcValue) {
|
|
return objValue === undefined ? srcValue : objValue;
|
|
});
|
|
}
|
|
|
|
clearOptions(elementName: Elements) {
|
|
this.#options[elementName] = [];
|
|
|
|
this.root.$calculation.$values.clearValueOfElement(elementName);
|
|
}
|
|
}
|