import { ArrayField, SelectState } from '@wix/bex-core'; import { action, makeObservable, reaction } from 'mobx'; export interface SelectFieldStateParams { select: SelectState; filter: ArrayField; } export class SelectFieldState { readonly select; readonly filter; constructor(params: SelectFieldStateParams) { this.select = params.select; this.filter = params.filter; makeObservable(this, { init: action.bound, syncSelectedItems: action.bound, }); this.syncSelectedItems(); } syncSelectedItems() { const { select, filter } = this; select.clear(); select.finalizeMany(filter.value); } init() { const disposers = [ reaction( () => this.filter.value, () => { const { select: { selectedValues }, filter, } = this; if (filter.value !== selectedValues) { this.syncSelectedItems(); } }, ), reaction( () => this.select.selectedValues, () => { const { select: { selectedValues }, filter, } = this; if (filter.value !== selectedValues) { filter.setValue(selectedValues, { emitEvents: ['change', 'beforeRefresh', 'refresh'], }); } }, ), ]; return () => { disposers.forEach((d) => d()); }; } }