@cosva-lab/form-builder
Version:
React form builder.
78 lines (76 loc) • 2.49 kB
JavaScript
import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.112.0/helpers/decorate.mjs";
import InputsValidator from "../validate/InputsValidator.mjs";
import { action, makeObservable, observable, toJS } from "mobx";
//#region src/utils/builders/FieldsBuilder.ts
var FieldsBuilder = class extends InputsValidator {
get ns() {
return this._ns;
}
set ns(ns) {
this._ns = ns;
}
get values() {
return this.getValues();
}
constructor(props) {
super(props);
this._ns = void 0;
makeObservable(this);
this._ns = props.ns;
for (const field of this.fields) field.fieldsBuilder = this;
this.validate = this._validate;
}
setField(fieldOriginal) {
const field = this.fields.find(({ name }) => fieldOriginal.name === name);
if (field) {
field.fieldsBuilder = this;
field.value = fieldOriginal.value;
field.errors = fieldOriginal.errors;
}
}
restore() {
this.fields.forEach((field) => field.reset());
}
getValues() {
return toJS(this.fields.reduce((acc, { name, value }) => {
acc[name] = value;
return acc;
}, {}));
}
get(fieldName) {
return this.fieldsMap[fieldName];
}
getField(fieldName) {
return this.get(fieldName);
}
onChangeField(event) {
this.changeValue(event);
}
onChangeFields(events) {
events.forEach((event) => this.onChangeField(event));
}
changeValue({ name, value }) {
const field = this.get(name);
if (field) field.setValue(value);
else console.warn(`Field ${name.toString()} not found`);
}
changeValues(events) {
events.forEach((event) => this.changeValue(event));
}
setValidation(validate) {
this.validate = validate;
}
};
__decorate([observable], FieldsBuilder.prototype, "_ns", void 0);
__decorate([observable], FieldsBuilder.prototype, "actionsExtra", void 0);
__decorate([action.bound], FieldsBuilder.prototype, "restore", null);
__decorate([action.bound], FieldsBuilder.prototype, "getValues", null);
__decorate([action.bound], FieldsBuilder.prototype, "get", null);
__decorate([action.bound], FieldsBuilder.prototype, "getField", null);
__decorate([action.bound], FieldsBuilder.prototype, "onChangeField", null);
__decorate([action.bound], FieldsBuilder.prototype, "onChangeFields", null);
__decorate([action.bound], FieldsBuilder.prototype, "changeValue", null);
__decorate([action.bound], FieldsBuilder.prototype, "changeValues", null);
__decorate([action.bound], FieldsBuilder.prototype, "setValidation", null);
//#endregion
export { FieldsBuilder, FieldsBuilder as default };