@cosva-lab/form-builder
Version:
React form builder.
1,075 lines (1,043 loc) • 68.4 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-is'), require('mobx-react'), require('@mui/material/Grid'), require('clsx'), require('mobx'), require('@mui/material/TextField'), require('@mui/material/FormControl'), require('@mui/material/FormHelperText'), require('@mui/material/Grow'), require('@mui/material/CircularProgress'), require('validator/lib/contains'), require('validator/lib/equals'), require('validator/lib/isAfter'), require('validator/lib/isAlpha'), require('validator/lib/isAlphanumeric'), require('validator/lib/isAscii'), require('validator/lib/isDecimal'), require('validator/lib/isEmail'), require('validator/lib/isEmpty'), require('validator/lib/isFloat'), require('validator/lib/isNumeric')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-is', 'mobx-react', '@mui/material/Grid', 'clsx', 'mobx', '@mui/material/TextField', '@mui/material/FormControl', '@mui/material/FormHelperText', '@mui/material/Grow', '@mui/material/CircularProgress', 'validator/lib/contains', 'validator/lib/equals', 'validator/lib/isAfter', 'validator/lib/isAlpha', 'validator/lib/isAlphanumeric', 'validator/lib/isAscii', 'validator/lib/isDecimal', 'validator/lib/isEmail', 'validator/lib/isEmpty', 'validator/lib/isFloat', 'validator/lib/isNumeric'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.FormBuilder = {}, global.React, global.ReactIs, global.mobxReact, global.Grid, global.clsx, global.mobx, global.TextField, global.FormControl, global.FormHelperText, global.Grow, global.CircularProgress, global.contains, global.equals, global.isAfter, global.isAlpha, global.isAlphanumeric, global.isAscii, global.isDecimal, global.isEmail, global.isEmpty$1, global.isFloat, global.isNumeric));
})(this, (function (exports, React, ReactIs, mobxReact, Grid, clsx, mobx, TextField, FormControl, FormHelperText, Grow, CircularProgress, contains, equals, isAfter, isAlpha, isAlphanumeric, isAscii, isDecimal, isEmail, isEmpty$1, isFloat, isNumeric) { 'use strict';
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var ReactIs__namespace = /*#__PURE__*/_interopNamespaceDefault(ReactIs);
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
var isEmpty = function (value) {
if (value === null || value === undefined)
return true;
if (typeof value === 'string')
return value.trim() === '';
if (Array.isArray(value))
return value.length === 0;
if (typeof value === 'object')
return Object.keys(value).length === 0;
return false;
};
var classes$1 = {"progress":"Loading-module_progress__sL-jU"};
var CircularIndeterminate = /** @class */ (function (_super) {
__extends(CircularIndeterminate, _super);
function CircularIndeterminate() {
return _super !== null && _super.apply(this, arguments) || this;
}
CircularIndeterminate.prototype.render = function () {
var _a = this.props, size = _a.size, color = _a.color, disableShrink = _a.disableShrink, thickness = _a.thickness, variant = _a.variant, style = _a.style;
return (React.createElement(CircularProgress, __assign({ variant: variant || 'indeterminate', className: classes$1.progress }, {
style: style,
size: size,
color: color,
disableShrink: disableShrink,
thickness: thickness,
})));
};
CircularIndeterminate.defaultProps = {
color: 'primary',
disableShrink: false,
size: 40,
thickness: 3.6,
variant: 'indeterminate',
};
return CircularIndeterminate;
}(React.PureComponent));
var Animation = function (_a) {
var children = _a.children;
return (React.createElement(Grow, __assign({ in: true, style: { transformOrigin: '0 0 0' } }, { timeout: 1000 }), children));
};
var GlobalTranslateContext = React.createContext(function (_a) {
var message = _a.message;
return message;
});
var useGlobalTranslate = function () {
return React.useContext(GlobalTranslateContext);
};
var GlobalTranslateProvider = function (_a) {
var children = _a.children, translator = _a.translator;
return (React.createElement(GlobalTranslateContext.Provider, { value: translator }, children));
};
var FieldTranslateConsumer = GlobalTranslateContext.Consumer;
var Comp = function (props) {
var translate = useGlobalTranslate();
return React.createElement("span", null, translate(props));
};
var GlobalTranslate = function (props) {
var styles = props.styles, rest = __rest(props, ["styles"]);
return (React.createElement(React.Suspense, { fallback: React.createElement(Animation, null,
React.createElement("div", { style: __assign(__assign({}, styles), { display: 'flex', justifyContent: 'center' }) },
React.createElement(CircularIndeterminate, { size: 20 }))) },
React.createElement(Comp, __assign({}, rest))));
};
GlobalTranslate.defaultProps = {
styles: {},
props: {},
};
var TransformLabel = function (_a) {
var ns = _a.ns, name = _a.name, label = _a.label;
if (React.isValidElement(label))
return label;
var message;
var props;
var nsLabel = ns;
if (typeof label === 'string')
message = label;
else {
if (label)
message = label.message || name.toString();
else
message = name.toString();
}
return (React.createElement(GlobalTranslate, __assign({}, {
message: message,
ns: nsLabel,
props: props,
})));
};
var FieldError = React.createContext({ ns: 'validations' });
var useFieldError = function () { return React.useContext(FieldError); };
var FieldErrorProvider = function (_a) {
var children = _a.children, rest = __rest(_a, ["children"]);
return (React.createElement(FieldError.Provider, { value: rest }, children));
};
var FieldErrorConsumer = FieldError.Consumer;
var TranslateFieldErrorContext = React.createContext(null);
var useTranslateFieldError = function () {
return React.useContext(TranslateFieldErrorContext);
};
var TranslateFieldErrorProvider = function (_a) {
var children = _a.children, translator = _a.translator;
return (React.createElement(TranslateFieldErrorContext.Provider, { value: translator }, children));
};
var TranslateFieldErrorConsumer = TranslateFieldErrorContext.Consumer;
var TranslateFieldError = function (props) {
var translate = useTranslateFieldError();
var fieldTranslate = useGlobalTranslate();
return React.createElement(React.Fragment, null, (translate || fieldTranslate)(props));
};
function isMessage(args) {
return (args &&
typeof args === 'object' &&
typeof args.message === 'string');
}
var Text = function (_a) {
var children = _a.children;
return (React.createElement("div", null, children));
};
var RenderErrorsDefault = function (_a) {
var errors = _a.errors, field = _a.field;
var ns = field && field.ns;
var common = useFieldError();
return (React.createElement(React.Fragment, null, errors.map(function (error, i) {
if (React.isValidElement(error))
return React.createElement(error.type, __assign({}, error.props, { key: error.key || i }));
return typeof error === 'string' ? (React.createElement(Text, { key: i }, error)) : isMessage(error) ? (React.createElement(Text, { key: i },
React.createElement(TranslateFieldError, __assign({}, __assign(__assign({ ns: ns }, common), error))))) : (Object.values(error).map(function (e, j) {
return (React.createElement(Text, { key: j }, typeof e === 'string'
? e
: (isMessage(e) && (React.createElement(TranslateFieldError, __assign({}, __assign(__assign({ ns: ns }, common), e))))) ||
null));
}));
})));
};
var classes = {"root":"Input-module_root__OxT2J","widthNormal":"Input-module_widthNormal__b-G-O","InputLabelProps":"Input-module_InputLabelProps__kYT5j","formHelperTextPropsRoot":"Input-module_formHelperTextPropsRoot__op-3l"};
var Input = /** @class */ (function (_super) {
__extends(Input, _super);
function Input(props) {
var _this = _super.call(this, props) || this;
_this.errors = [];
_this.animation = true;
_this.getProps = function (props) { return (__assign({}, props.field)); };
_this.getLastProps = function () { return _this.getProps(_this.props); };
_this.state = { type: props.type };
return _this;
}
Input.prototype.componentDidMount = function () {
var _this = this;
var field = this.props.field;
mobx.intercept(field, 'errors', function (change) {
_this.animation = true;
return change;
});
};
Input.prototype.render = function () {
var _this = this;
var _a = this.props; _a.onChangeField; var field = _a.field;
var ns = field.ns, label = field.label, name = field.name, disabled = field.disabled, _b = field.fullWidth, fullWidth = _b === void 0 ? true : _b, errors = field.errors, autoComplete = field.autoComplete, InputProps = field.InputProps, textFieldProps = field.textFieldProps, value = field.value, RenderErrors = field.renderErrors;
var type = this.state.type;
var errorsNode = errors &&
((RenderErrors && React.createElement(RenderErrors, __assign({}, { errors: errors, field: field }))) || (React.createElement(RenderErrorsDefault, __assign({}, { errors: errors, field: field }))));
return (React.createElement(FormControl, __assign({}, { fullWidth: fullWidth }, { className: classes.formControl, variant: "outlined" }),
React.createElement(TextField, __assign({ label: React.createElement(TransformLabel, __assign({}, { label: label, ns: ns, name: name })), inputRef: function (element) { return (field.inputRef = element); }, error: !isEmpty(errors), InputProps: typeof InputProps === 'function'
? InputProps({
type: type,
field: field,
changeType: function (type, callback) {
if (type !== _this.state.type)
_this.setState({ type: type }, callback);
},
})
: InputProps, InputLabelProps: {
shrink: type === 'date' ? true : undefined,
classes: {
root: clsx(classes.InputLabelProps, classes.widthNormal),
},
}, onChange: function (e) {
var onChange = field.onChange;
var value = e.target.value;
if (onChange)
onChange({ name: field.name, value: value, field: field }, e);
else
field.setValue(value);
}, onBlur: function () {
var field = _this.props.field;
field && field.markAsTouched();
}, name: name.toString() }, __assign(__assign({}, textFieldProps), { type: type, value: value, disabled: disabled, autoComplete: autoComplete }))),
errorsNode && (React.createElement(FormHelperText, { component: "div", error: true, className: classes.formHelperTextPropsRoot }, errorsNode))));
};
Input = __decorate([
mobxReact.observer
], Input);
return Input;
}(React.Component));
function Inputs(props) {
var onChangeField = props.onChangeField, field = props.field;
var type = field.type;
switch (type) {
case 'date':
case 'email':
case 'number':
case 'password':
case 'search':
case 'tel':
case 'text':
case 'time':
case 'url':
case 'week':
case 'datetime-local':
case undefined:
return React.createElement(Input, __assign({}, { field: field, onChangeField: onChangeField, type: type }));
default:
return null;
}
}
var FieldRenderObserver = function (_a) {
var component = _a.component, propsForm = _a.propsForm;
var FieldComponent = component;
try {
FieldComponent = mobxReact.observer(component);
}
catch (error) { }
return React.createElement(FieldComponent, __assign({}, propsForm));
};
var FieldRender = /** @class */ (function (_super) {
__extends(FieldRender, _super);
function FieldRender() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.onChangeField = function (e, callback) {
var onChangeField = _this.props.onChangeField;
onChangeField === null || onChangeField === void 0 ? void 0 : onChangeField(e, callback);
};
return _this;
}
FieldRender.prototype.render = function () {
var field = this.props.field;
var breakpoints = __assign({}, field.breakpoints);
var _a = breakpoints.xs, xs = _a === void 0 ? 12 : _a;
var _b = breakpoints.sm, sm = _b === void 0 ? xs : _b;
var _c = breakpoints.md, md = _c === void 0 ? sm : _c;
var _d = breakpoints.lg, lg = _d === void 0 ? md : _d;
var _e = breakpoints.xl, xl = _e === void 0 ? lg : _e;
var Component = field.component, render = field.render, type = field.type, _f = field.grid, grid = _f === void 0 ? typeof this.props.grid !== 'undefined'
? this.props.grid
: true : _f;
var propsForm = {
field: field,
onChangeField: this.onChangeField,
};
var formInput = React.createElement(Inputs, __assign({}, propsForm));
if (render)
return render({
children: formInput,
props: propsForm,
});
if (type === 'component') {
if (Component)
Component.displayName = "[fields.".concat(field.name.toString(), "].component");
if (React.isValidElement(Component))
return (React.createElement(Component.type, __assign({}, __assign(__assign({}, Component.props), propsForm))));
if (ReactIs__namespace.isValidElementType(Component))
return (React.createElement(FieldRenderObserver, { component: Component, propsForm: propsForm }));
return null;
}
return grid ? (React.createElement(Grid, { item: true, xs: xs, sm: sm, md: md, lg: lg, xl: xl }, formInput)) : (formInput);
};
return FieldRender;
}(React.PureComponent));
exports.StatusField = void 0;
(function (StatusField) {
// This control has passed all validation checks.
StatusField["VALID"] = "VALID";
// This control has failed at least one validation check.
StatusField["INVALID"] = "INVALID";
// This control is in the midst of conducting a validation check.
StatusField["PENDING"] = "PENDING";
// This control is exempt from validation checks.
StatusField["DISABLED"] = "DISABLED";
})(exports.StatusField || (exports.StatusField = {}));
var Field = /** @class */ (function () {
function Field(_a) {
var type = _a.type, name = _a.name, value = _a.value, disabled = _a.disabled, defaultInputValue = _a.defaultInputValue, label = _a.label, onChange = _a.onChange, onSetValue = _a.onSetValue;
this.fieldsBuilder = undefined;
this.type = undefined;
this.defaultInputValue = undefined;
this.errors = [];
this.onChange = undefined;
this.onSetValue = undefined;
this.pristine = true;
this.type = type;
this.name = name;
this.value = value;
if (disabled)
this.disable();
else
this.status = exports.StatusField.VALID;
this.defaultInputValue = defaultInputValue;
this.label = label;
this.onChange = onChange;
this.onSetValue = onSetValue;
mobx.makeObservable(this);
}
Object.defineProperty(Field.prototype, "dirty", {
/**
* A control is `dirty` if the user has changed the value
* in the UI.
*
* @returns True if the user has changed the value of this control in the UI; compare `pristine`.
* Programmatic changes to a control's value do not mark it dirty.
*/
get: function () {
return !this.pristine;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Field.prototype, "valid", {
/**
* A control is `valid` when its `status` is `VALID`.
*
* @see {@link Field.status}
*
* @returns True if the control has passed all of its validation tests,
* false otherwise.
*/
get: function () {
return this.status === exports.StatusField.VALID;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Field.prototype, "invalid", {
/**
* A control is `invalid` when its `status` is `INVALID`.
*
* @see {@link Field.status}
*
* @returns True if this control has failed one or more of its validation checks,
* false otherwise.
*/
get: function () {
return this.status === exports.StatusField.INVALID;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Field.prototype, "pending", {
/**
* A control is `pending` when its `status` is `PENDING`.
*
* @see {@link Field.status}
*
* @returns True if this control is in the process of conducting a validation check,
* false otherwise.
*/
get: function () {
return this.status == exports.StatusField.PENDING;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Field.prototype, "disabled", {
/**
* A control is `disabled` when its `status` is `DISABLED`.
*
* Disabled controls are exempt from validation checks and
* are not included in the aggregate value of their ancestor
* controls.
*
* @see {@link Field.status}
*
* @returns True if the control is disabled, false otherwise.
*/
get: function () {
return this.status === exports.StatusField.DISABLED;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Field.prototype, "enabled", {
/**
* A control is `enabled` as long as its `status` is not `DISABLED`.
*
* @returns True if the control has any status other than 'DISABLED',
* false if the status is 'DISABLED'.
*
* @see {@link Field.status}
*
*/
get: function () {
return this.status !== exports.StatusField.DISABLED;
},
enumerable: false,
configurable: true
});
/**
* Disables the control. This means the control is exempt from validation checks and
* excluded from the aggregate value of any parent. Its status is `DISABLED`.
*
* If the control has children, all children are also disabled.
*
* @see {@link Field.status}
*/
Field.prototype.disable = function () {
// If parent has been marked artificially dirty we don't want to re-calculate the
// parent's dirtiness based on the children.
this.status = exports.StatusField.DISABLED;
this.errors = this.errors = [];
};
/**
* Enables the control. This means the control is included in validation checks and
* the aggregate value of its parent. Its status recalculates based on its value and
* its validators.
*
* By default, if the control has children, all children are enabled.
*
* @see {@link Field.status}
*/
Field.prototype.enable = function () {
// If parent has been marked artificially dirty we don't want to re-calculate the
// parent's dirtiness based on the children.
this.status = exports.StatusField.VALID;
};
/**
* Marks the control as `dirty`. A control becomes dirty when
* the control's value is changed through the UI; compare `markAsTouched`.
*
* @see `markAsTouched()`
* @see `markAsUntouched()`
* @see `markAsPristine()`
*
*/
Field.prototype.markAsDirty = function () {
this.pristine = false;
};
/**
* Marks the control as `pristine`.
*
* If the control has any children, marks all children as `pristine`,
* and recalculates the `pristine` status of all parent
* controls.
*
* @see `markAsTouched()`
* @see `markAsUntouched()`
* @see `markAsDirty()`
*
*/
Field.prototype.markAsPristine = function () {
this.pristine = true;
};
Field.prototype._setInitialStatus = function () {
this.status = this.disabled
? exports.StatusField.DISABLED
: exports.StatusField.VALID;
};
__decorate([
mobx.observable
], Field.prototype, "type", void 0);
__decorate([
mobx.observable
], Field.prototype, "name", void 0);
__decorate([
mobx.observable
], Field.prototype, "value", void 0);
__decorate([
mobx.observable
], Field.prototype, "defaultInputValue", void 0);
__decorate([
mobx.observable
], Field.prototype, "label", void 0);
__decorate([
mobx.observable
], Field.prototype, "status", void 0);
__decorate([
mobx.observable
], Field.prototype, "errors", void 0);
__decorate([
mobx.observable
], Field.prototype, "onChange", void 0);
__decorate([
mobx.observable
], Field.prototype, "onSetValue", void 0);
__decorate([
mobx.action
], Field.prototype, "disable", null);
__decorate([
mobx.action
], Field.prototype, "enable", null);
__decorate([
mobx.action
], Field.prototype, "_setInitialStatus", null);
return Field;
}());
var validators = {
contains: contains,
equals: equals,
isAfter: isAfter,
isAlpha: isAlpha,
isAlphanumeric: isAlphanumeric,
isAscii: isAscii,
isDecimal: isDecimal,
isEmail: isEmail,
isEmpty: isEmpty$1,
isFloat: isFloat,
isNumeric: isNumeric,
};
var InputValidator = /** @class */ (function (_super) {
__extends(InputValidator, _super);
function InputValidator(props) {
var _this = _super.call(this, props) || this;
_this._validate = false;
mobx.makeObservable(_this);
var validate = props.validate, validations = props.validations, value = props.value, globalProps = props.globalProps;
if (typeof validate !== 'undefined')
_this._validate = validate;
// validations is an array of validation rules specific to a form
_this.validations = validations;
_this.originalProps = { value: value, validate: validate };
_this.globalProps = globalProps;
return _this;
}
InputValidator.getValidation = function (obj) {
return typeof obj._validate === 'function'
? obj._validate(obj)
: obj._validate;
};
Object.defineProperty(InputValidator.prototype, "validate", {
get: function () {
return InputValidator.getValidation(this);
},
set: function (validate) {
this._validate = validate;
if (validate)
this.validity();
else
this.errors = [];
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputValidator.prototype, "untouched", {
get: function () {
return !this.touched;
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputValidator.prototype, "globalProps", {
get: function () {
return ((this.fieldsBuilder && this.fieldsBuilder.globalProps) ||
this._globalProps);
},
set: function (globalProps) {
if (this.fieldsBuilder)
this.fieldsBuilder.globalProps = globalProps;
else
this._globalProps = globalProps;
},
enumerable: false,
configurable: true
});
InputValidator.prototype.hasValidationError = function (validation) {
var rule = validation.rule || 'isEmpty';
var _a = validation.args, args = _a === void 0 ? [] : _a;
if (![
'contains',
'equals',
'isAfter',
'isAlpha',
'isAlphanumeric',
'isAscii',
'isDecimal',
'isEmail',
'isEmpty',
'isFloat',
'isNumeric',
].includes(rule)) {
console.error(rule, "the rule don't exists");
rule = 'isEmpty';
}
else {
var validator_1 = validators[rule];
if (validator_1) {
var boolean = false;
switch (rule) {
case 'isEmpty':
boolean = true;
break;
}
if (typeof this.value === 'string' &&
validator_1((this.value || '').toString(), args) === boolean) {
this.status = exports.StatusField.INVALID;
return true;
}
else
this.status = exports.StatusField.VALID;
}
}
return false;
};
InputValidator.prototype.markAsTouched = function () {
this.touched = true;
};
InputValidator.prototype.markAsUntouched = function () {
this.touched = false;
};
InputValidator.prototype.validityBase = function () {
return __awaiter(this, void 0, void 0, function () {
var errors;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getErrors()];
case 1:
errors = _a.sent();
mobx.runInAction(function () {
if (errors && errors.length) {
_this.errors = errors;
_this.status = exports.StatusField.INVALID;
}
else {
_this.errors = _this.errors = [];
_this.status = exports.StatusField.VALID;
}
});
return [2 /*return*/, this.valid];
}
});
});
};
/**
* @description Returns true if the field is valid
* @return {Promise<boolean>}
*/
InputValidator.prototype.validity = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
this._validate = true;
return [2 /*return*/, this.validityBase()];
});
});
};
InputValidator.prototype._calculateStatus = function () {
if (this.disabled)
return exports.StatusField.DISABLED;
else if (this.errors && this.errors.length)
return exports.StatusField.INVALID;
return exports.StatusField.VALID;
};
InputValidator.prototype.updateValueAndValidity = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this._setInitialStatus();
if (!this.enabled) return [3 /*break*/, 2];
return [4 /*yield*/, this.validity()];
case 1:
_a.sent();
mobx.runInAction(function () {
_this.status = _this._calculateStatus();
});
_a.label = 2;
case 2: return [2 /*return*/];
}
});
});
};
InputValidator.prototype.reset = function () {
this.markAsPristine();
this.markAsUntouched();
this._setInitialStatus();
var originalProps = this.originalProps;
if (originalProps) {
var validate = originalProps.validate, value = originalProps.value;
this._validate = validate;
this.value = value;
}
};
InputValidator.prototype.addError = function (error) {
if (error) {
if (this.status !== exports.StatusField.INVALID)
this.status = exports.StatusField.INVALID;
if (!this.errors)
this.errors = [];
this.errors.unshift(error);
}
};
InputValidator.prototype.addErrors = function (errors) {
this.status = exports.StatusField.INVALID;
var oldErrors = this.errors || [];
this.errors = __spreadArray(__spreadArray([], errors, true), oldErrors, true);
};
InputValidator.prototype.setError = function (error) {
this.addError(error);
};
InputValidator.prototype.setErrors = function (errors) {
this.addErrors(errors);
};
__decorate([
mobx.observable
], InputValidator.prototype, "validations", void 0);
__decorate([
mobx.action
], InputValidator.prototype, "hasValidationError", null);
__decorate([
mobx.action
], InputValidator.prototype, "validityBase", null);
__decorate([
mobx.action
], InputValidator.prototype, "validity", null);
__decorate([
mobx.action
], InputValidator.prototype, "updateValueAndValidity", null);
__decorate([
mobx.action
], InputValidator.prototype, "reset", null);
__decorate([
mobx.action
], InputValidator.prototype, "addError", null);
__decorate([
mobx.action
], InputValidator.prototype, "addErrors", null);
return InputValidator;
}(Field));
var FieldBuilder = /** @class */ (function (_super) {
__extends(FieldBuilder, _super);
function FieldBuilder(props) {
var _this = _super.call(this, props) || this;
_this._ns = undefined;
_this.render = undefined;
_this.fullWidth = undefined;
_this.grid = undefined;
_this.autoComplete = undefined;
_this.InputProps = undefined;
_this.textFieldProps = undefined;
_this.breakpoints = undefined;
_this.component = undefined;
mobx.makeObservable(_this);
var ns = props.ns, render = props.render, _a = props.fullWidth, fullWidth = _a === void 0 ? true : _a, _b = props.grid, grid = _b === void 0 ? true : _b, autoComplete = props.autoComplete, InputProps = props.InputProps, textFieldProps = props.textFieldProps, breakpoints = props.breakpoints, component = props.component, renderErrors = props.renderErrors;
_this.validate = InputValidator.getValidation(_this);
_this.ns = ns;
_this.render = render;
_this.fullWidth = fullWidth;
_this.grid = grid;
_this.autoComplete = autoComplete;
_this.InputProps = InputProps;
_this.textFieldProps = textFieldProps;
_this.breakpoints = breakpoints;
_this.component = component;
_this.renderErrors = renderErrors;
_this.getErrors = _this.getErrors.bind(_this);
return _this;
}
Object.defineProperty(FieldBuilder.prototype, "ns", {
get: function () {
return typeof this._ns === 'undefined'
? this.fieldsBuilder && this.fieldsBuilder.ns
: this._ns;
},
set: function (ns) {
this._ns = ns;
},
enumerable: false,
configurable: true
});
FieldBuilder.prototype.getErrorsBase = function (props) {
return __awaiter(this, void 0, void 0, function () {
var _a, sequential, _b, validations, value, validate, errors, _i, validations_1, validation, error;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = __assign({}, props).sequential, sequential = _a === void 0 ? false : _a;
_b = this, validations = _b.validations, value = _b.value;
if (typeof this.validate !== 'function')
this._validate = true;
validate = this.validate;
errors = [];
if (!validate && !this.dirty && !this.enabled)
return [2 /*return*/, errors];
if (!(Array.isArray(validations) && validate)) return [3 /*break*/, 6];
_i = 0, validations_1 = validations;
_c.label = 1;
case 1:
if (!(_i < validations_1.length)) return [3 /*break*/, 6];
validation = validations_1[_i];
error = void 0;
if (!(typeof validation === 'object')) return [3 /*break*/, 2];
if (this.hasValidationError(validation))
error = validation;
return [3 /*break*/, 4];
case 2:
if (!(typeof validation === 'function')) return [3 /*break*/, 4];
return [4 /*yield*/, validation({
field: this,
fieldsBuilder: this.fieldsBuilder,
validate: validate,
value: value,
})];
case 3:
error = _c.sent();
_c.label = 4;
case 4:
if (error) {
errors = __spreadArray(__spreadArray([], errors, true), [error], false);
if (sequential)
return [3 /*break*/, 6];
}
_c.label = 5;
case 5:
_i++;
return [3 /*break*/, 1];
case 6: return [2 /*return*/, errors.length ? errors : undefined];
}
});
});
};
FieldBuilder.prototype.getErrors = function () {
return this.getErrorsBase();
};
FieldBuilder.prototype.hasErrors = function () {
return __awaiter(this, void 0, void 0, function () {
var errors;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getErrorsBase({ sequential: true })];
case 1:
errors = _a.sent();
return [2 /*return*/, !!(errors && errors.length)];
}
});
});
};
FieldBuilder.prototype.hasValid = function () {
return __awaiter(this, void 0, void 0, function () {
var hasErrors;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.hasErrors()];
case 1:
hasErrors = _a.sent();
return [2 /*return*/, !hasErrors];
}
});
});
};
FieldBuilder.prototype.setValue = function (value) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
mobx.runInAction(function () {
_this.value = value;
});
this.markAsDirty();
this.markAsTouched();
if (typeof this.validate !== 'undefined'
? this.validate
: this.dirty) {
mobx.runInAction(function () {
_this.updateValueAndValidity();
});
}
this.onSetValue &&
this.onSetValue({
lastValue: mobx.toJS(this.value),
newValue: value,
field: this,
});
return [2 /*return*/];
});
});
};
__decorate([
mobx.observable
], FieldBuilder.prototype, "_ns", void 0);
__decorate([
mobx.observable
], FieldBuilder.prototype, "render", void 0);
__decorate([
mobx.observable
], FieldBuilder.prototype, "fullWidth", void 0);
__decorate([
mobx.observable
], FieldBuilder.prototype, "grid", void 0);
__decorate([
mobx.observable
], FieldBuilder.prototype, "autoComplete", void 0);
__decorate([
mobx.observable
], FieldBuilder.prototype, "InputProps", void 0);
__decorate([
mobx.observable
], FieldBuilder.prototype, "textFieldProps", void 0);
__decorate([
mobx.observable
], FieldBuilder.prototype, "breakpoints", void 0);
__decorate([
mobx.observable
], FieldBuilder.prototype, "component", void 0);
__decorate([
mobx.action
], FieldBuilder.prototype, "setValue", null);
return FieldBuilder;
}(InputValidator));
var FieldsRender = /** @class */ (function (_super) {
__extends(FieldsRender, _super);
function FieldsRender() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
*
*
* @return {JSX.Element}
* @memberof FieldsRender
*/
FieldsRender.prototype.render = function () {
var _a = this.props, fields = _a.fields, globalProps = _a.globalProps, grid = _a.grid, onChangeField = _a.onChangeField;
return (React.createElement(React.Fragment, null, fields.map(function (field) {
if (field instanceof FieldBuilder && globalProps)
field.globalProps = globalProps;
return (React.createElement(FieldRender, __assign({ key: field.name.toString(), field: field, onChangeField: onChangeField }, {
grid: grid,