import { action, makeObservable, observable } from 'mobx'; import { ConditionalModalState } from '@wix/bex-core'; import type { FieldSpec } from '../../types/SchemaConfig'; import { CmsFormState } from './CmsFormState'; import { toFieldSpec } from './toFieldSpec'; import { getFieldTypeValidationRulesList } from './fieldValidationRulesMap'; /** * Pure field-editor modal state. Opens the CMS field form pre-filled from a * field draft and, on confirm, hands the edited field spec to `onSubmit`. Unlike * `CmsFieldModalState` it has no server side effect — it never calls * `fieldActions` and needs no schema. It's a plain input (draft) → output * (spec) editor; the consumer decides what to do with the result (e.g. the CSV * import captures it into a column's pending new field). */ export interface FieldEditorModalStateProps { /** Receives the edited field spec on confirm. Pure — no server side effect. */ onSubmit: (field: FieldSpec) => void; } export class FieldEditorModalState { readonly modal: ConditionalModalState; formState: CmsFormState | null = null; private readonly onSubmit: (field: FieldSpec) => void; constructor(props: FieldEditorModalStateProps) { this.onSubmit = props.onSubmit; this.modal = new ConditionalModalState({ onConfirm: () => this.submit(), }); makeObservable(this, { formState: observable.ref, open: action, reset: action, }); } open(draft: FieldSpec) { this.formState = new CmsFormState({ getValidationRules: getFieldTypeValidationRulesList, }); this.formState.prefill(draft); this.modal.open(null); } reset() { this.formState = null; } private submit() { const { formState } = this; if (!formState) { return; } if (formState.hasInvalidFields || !formState.properties.type) { formState.enableShowValidationError(); // Throwing keeps the modal open (ModalState.confirm swallows it). throw new Error('validation'); } const { type, ...rest } = formState.properties; this.onSubmit(toFieldSpec({ ...rest, type }, formState.fieldRules)); } }