vs-form-mui-4x
Version:
A schema-based form generator component for React using material-ui 4.x
1,250 lines (1,223 loc) • 140 kB
JavaScript
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var React = require('react');
var React__default = _interopDefault(React);
var capitalize = _interopDefault(require('lodash/capitalize'));
var cloneDeep = _interopDefault(require('lodash/cloneDeep'));
var get = _interopDefault(require('lodash/get'));
var has = _interopDefault(require('lodash/has'));
var isArray = _interopDefault(require('lodash/isArray'));
var isDate = _interopDefault(require('lodash/isDate'));
var isBoolean = _interopDefault(require('lodash/isBoolean'));
var isEmpty = _interopDefault(require('lodash/isEmpty'));
var isFunction = _interopDefault(require('lodash/isFunction'));
var isInteger = _interopDefault(require('lodash/isInteger'));
var isNull = _interopDefault(require('lodash/isNull'));
var isNumber = _interopDefault(require('lodash/isNumber'));
var isObject = _interopDefault(require('lodash/isObject'));
var isPlainObject = _interopDefault(require('lodash/isPlainObject'));
var isRegExp = _interopDefault(require('lodash/isRegExp'));
var isString = _interopDefault(require('lodash/isString'));
var isUndefined = _interopDefault(require('lodash/isUndefined'));
var merge = _interopDefault(require('lodash/merge'));
var set = _interopDefault(require('lodash/set'));
var toInteger = _interopDefault(require('lodash/toInteger'));
var toNumber = _interopDefault(require('lodash/toNumber'));
var trimEnd = _interopDefault(require('lodash/trimEnd'));
var uniq = _interopDefault(require('lodash/uniq'));
var debounce = _interopDefault(require('lodash/debounce'));
var throttle = _interopDefault(require('lodash/throttle'));
var FormControl = _interopDefault(require('@material-ui/core/FormControl'));
var FormHelperText = _interopDefault(require('@material-ui/core/FormHelperText'));
var FormLabel = _interopDefault(require('@material-ui/core/FormLabel'));
var TextField = _interopDefault(require('@material-ui/core/TextField'));
var InputAdornment = _interopDefault(require('@material-ui/core/InputAdornment'));
var Tooltip = _interopDefault(require('@material-ui/core/Tooltip'));
var styles$2 = require('@material-ui/core/styles');
var classNames = _interopDefault(require('classnames'));
var Icon = _interopDefault(require('@material-ui/core/Icon'));
var SvgIcon = _interopDefault(require('@material-ui/core/SvgIcon'));
var dateFns = require('date-fns');
var events = require('events');
var Typography = _interopDefault(require('@material-ui/core/Typography'));
var Grid = _interopDefault(require('@material-ui/core/Grid'));
var IconButton = _interopDefault(require('@material-ui/core/IconButton'));
class VsBaseDataComponent extends React.Component {
constructor(props) {
super(props);
this.updateValue = (value, schemaValue) => {
this.setState({ value });
const _schemaValue = !isUndefined(schemaValue) ? schemaValue : value;
this.updateSchemaValue(_schemaValue);
};
this.getSchemaValue = () => {
this.props.schemaManager.getSchemaValue(this.props.comp, this.props.arrayId);
};
this.updateSchemaValue = (value) => {
this.props.schemaManager.updateSchemaValue(this.props.comp, value, this.props.arrayId);
const error = this.errorsToString(this.props.schemaManager.getValueErrorsComp(this.props.comp, this.props.arrayId));
this.setError(error);
};
this.errorsToString = (errors) => {
return errors.map(e => e.error).join('\n');
};
this.setError = (error) => {
this.setState({ error });
};
this.state = {
value: this.props.schemaManager.getSchemaValue(this.props.comp, this.props.arrayId),
error: this.errorsToString(this.props.schemaManager.getValueErrorsComp(this.props.comp, this.props.arrayId)),
};
}
render() {
const { state, updateValue, getSchemaValue, setError } = this;
return this.props.children({ state, updateValue, getSchemaValue, setError, ...this.props });
}
}
class VsBaseFormControl extends React.Component {
constructor(props) {
super(props);
this.FormControlProps = {};
this.FormHelperTextProps = {};
this.FormLabelProps = {};
this.renderComp = (dataProps) => {
const comp = this.props.comp;
const formhelpertext = dataProps.state.error || this.props.comp.hint || '';
return (React.createElement(FormControl, Object.assign({ error: !!dataProps.state.error }, this.FormControlProps),
this.props.showLabel && React.createElement(FormLabel, Object.assign({}, this.FormLabelProps), comp.label),
this.props.children({ ...dataProps }),
formhelpertext && React.createElement(FormHelperText, Object.assign({ error: !!dataProps.state.error }, this.FormHelperTextProps), formhelpertext)));
};
this.initProps();
}
render() {
return (React.createElement(VsBaseDataComponent, Object.assign({}, this.props), this.renderComp));
}
initProps() {
const { FormControlProps, FormHelperTextProps, FormLabelProps } = this.props.comp.props;
if (FormControlProps) {
this.FormControlProps = FormControlProps;
}
if (FormHelperTextProps) {
this.FormHelperTextProps = FormHelperTextProps;
}
if (FormLabelProps) {
this.FormLabelProps = FormLabelProps;
}
if (isUndefined(this.FormControlProps.fullWidth)) {
this.FormControlProps.fullWidth = true;
}
}
}
(function (Component) {
Component["card"] = "card";
Component["panel"] = "panel";
Component["tabs"] = "tabs";
Component["tab"] = "tab";
Component["accordion"] = "accordion ";
Component["form"] = "form";
Component["subschema"] = "subschema";
Component["textinput"] = "textinput";
Component["maskinput"] = "maskinput";
Component["select"] = "select";
Component["selectext"] = "selectext";
Component["integer"] = "integer";
Component["number"] = "number";
Component["numberformat"] = "numberformat";
Component["date"] = "date";
Component["dateext"] = "dateext";
Component["time"] = "time";
Component["datetime"] = "datetime";
Component["radiogroup"] = "radiogroup";
Component["slider"] = "slider";
Component["checkbox"] = "checkbox";
Component["checklistbox"] = "checklistbox";
Component["switch"] = "switch";
Component["text"] = "text";
Component["button"] = "button";
Component["speeddial"] = "speeddial";
Component["iconbutton"] = "iconbutton";
Component["icon"] = "icon";
Component["divider"] = "divider";
Component["mediastatic"] = "mediastatic";
Component["dataTable"] = "dataTable";
Component["custom"] = "custom";
})(exports.Component || (exports.Component = {}));
(function (DataType) {
DataType["string"] = "string";
DataType["number"] = "number";
DataType["integer"] = "integer";
DataType["boolean"] = "boolean";
DataType["date"] = "date";
DataType["array"] = "array";
DataType["arrayString"] = "arrayString";
DataType["arrayNumber"] = "arrayNumber";
DataType["arrayInteger"] = "arrayInteger";
DataType["arrayObject"] = "arrayObject";
DataType["object"] = "object";
DataType["function"] = "function";
DataType["regex"] = "regex";
DataType["any"] = "any";
})(exports.DataType || (exports.DataType = {}));
var ComponentType;
(function (ComponentType) {
ComponentType["field"] = "field";
ComponentType["container"] = "container";
ComponentType["subschema"] = "subschema";
ComponentType["static"] = "static";
})(ComponentType || (ComponentType = {}));
var InputVariant;
(function (InputVariant) {
InputVariant["standard"] = "standard";
InputVariant["outlined"] = "outlined";
InputVariant["filled"] = "filled";
})(InputVariant || (InputVariant = {}));
(function (ValidationMethod) {
ValidationMethod[ValidationMethod["validateOnChange"] = 1] = "validateOnChange";
ValidationMethod[ValidationMethod["validateOnSubmit"] = 2] = "validateOnSubmit";
})(exports.ValidationMethod || (exports.ValidationMethod = {}));
var InputType;
(function (InputType) {
InputType["button"] = "button";
InputType["checkbox"] = "checkbox";
InputType["color"] = "color";
InputType["date"] = "date";
InputType["datetime"] = "datetime";
InputType["datetimelocal"] = "datetime-local";
InputType["email"] = "email";
InputType["file"] = "file";
InputType["hidden"] = "hidden";
InputType["image"] = "image";
InputType["month"] = "month";
InputType["number"] = "number";
InputType["password"] = "password";
InputType["radio"] = "radio";
InputType["range"] = "range";
InputType["reset"] = "reset";
InputType["search"] = "search";
InputType["submit"] = "submit";
InputType["tel"] = "tel";
InputType["text"] = "text";
InputType["time"] = "time";
InputType["url"] = "url";
InputType["week"] = "week";
})(InputType || (InputType = {}));
(function (ButtonAction) {
ButtonAction["none"] = "none";
ButtonAction["save"] = "save";
ButtonAction["cancel"] = "cancel";
})(exports.ButtonAction || (exports.ButtonAction = {}));
var SchemaEventType;
(function (SchemaEventType) {
SchemaEventType["onDataChanges"] = "onDataChanges";
SchemaEventType["onSelectionChangeStarted"] = "onSelectionChangeStarted";
SchemaEventType["onSelectionChanged"] = "onSelectionChanged";
SchemaEventType["onBeforeChangeSelection"] = "onBeforeChangeSelection";
SchemaEventType["onComponentAdded"] = "onComponentAdded";
SchemaEventType["onComponentDelete"] = "onComponentDelete";
SchemaEventType["onPropertyUpdated"] = "onPropertyUpdated";
SchemaEventType["onSchemaPropertyUpdated"] = "onSchemaPropertyUpdated";
SchemaEventType["onCompileErrorClicked"] = "onCompileErrorClicked";
SchemaEventType["onRenderComponent"] = "onRenderComponent";
SchemaEventType["onFocusComponent"] = "onFocusComponent";
})(SchemaEventType || (SchemaEventType = {}));
var SortDirection;
(function (SortDirection) {
SortDirection["none"] = "none";
SortDirection["asc"] = "asc";
SortDirection["desc"] = "desc";
})(SortDirection || (SortDirection = {}));
var enums = /*#__PURE__*/Object.freeze({
__proto__: null,
get Component () { return exports.Component; },
get DataType () { return exports.DataType; },
get ComponentType () { return ComponentType; },
get InputVariant () { return InputVariant; },
get ValidationMethod () { return exports.ValidationMethod; },
get InputType () { return InputType; },
get ButtonAction () { return exports.ButtonAction; },
get SchemaEventType () { return SchemaEventType; },
get SortDirection () { return SortDirection; }
});
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
this.setState({ hasError: true });
console.log(this.props, error, info);
}
render() {
if (this.state.hasError) {
return (React.createElement(React.Fragment, null,
React.createElement("p", { style: { color: 'red' } },
"Component with id: \"",
this.props.comp.node,
"\" has errors! "),
React.createElement("p", { style: { color: 'red' } }, "check the console for more info.")));
}
return this.props.children;
}
}
const addStyles = (component, styles) => {
return styles$2.withStyles(styles)(component);
};
const styles = styles$2.createStyles({
itemSelected: {
boxSizing: 'border-box',
position: 'absolute',
width: '10px',
height: '10px',
background: 'lightgray',
border: '1px solid #333',
zIndex: 1,
},
dragArea: {
minHeight: '50px',
},
itemFocused: {
boxSizing: 'border-box',
position: 'absolute',
width: '10px',
height: '10px',
background: 'greenyellow',
border: '1px solid #333',
zIndex: 1,
}
});
const getSelectedClass = (props) => {
if (isFocused(props)) {
return props.classes.itemFocused;
}
else if (isSelected(props)) {
return props.classes.itemSelected;
}
else {
return '';
}
};
const isFocused = (props) => {
return props.schemaManager.selection.length >= 1 && props.schemaManager.selection[0] === props.comp;
};
const isSelected = (props) => {
return !isFocused(props) && props.schemaManager.selection.includes(props.comp);
};
const SelectDiv = (props) => (React.createElement("div", { className: getSelectedClass(props) }));
var SelectDiv$1 = addStyles(SelectDiv, styles);
const BaseIcon = (props) => {
let ic;
if (props['icon']) {
const p = props;
const { tooltip, tooltipProps, icon, ...other } = p;
const cl = classNames('mdi', 'mdi-' + icon, p.className);
ic = React.createElement(Icon, Object.assign({}, other, { className: cl }));
}
else if (props['svg']) {
const p = props;
const { tooltip, tooltipProps, svg, ...other } = p;
ic = (React.createElement(SvgIcon, Object.assign({}, other),
React.createElement("path", { d: p.svg })));
}
else if (props['component']) {
const p = props;
const { tooltip, tooltipProps, component, ...other } = p;
ic = (React.createElement(SvgIcon, Object.assign({}, other, { component: p.component })));
}
if (ic) {
return props.tooltip ? React.createElement(Tooltip, Object.assign({ title: props.tooltip }, props.tooltipProps),
React.createElement("span", null, ic)) : ic;
}
else {
return React.createElement("div", null, "Icon: property icon, svg or component must be provided");
}
};
const getRegisteredComponentList = () => {
if (!window.vsformregisteredComponents) {
window.vsformregisteredComponents = {
standard: {},
custom: {}
};
}
return window.vsformregisteredComponents;
};
const registerComponent = (type, component, defaultStyle) => {
getRegisteredComponentList().standard[type] = { component, defaultStyle };
};
const registerCustomComponent = (name, component, defaultStyle) => {
getRegisteredComponentList().custom[name] = { component, defaultStyle };
};
const getRegisteredComponent = async (type, name) => {
const rc = type !== exports.Component.custom ? getRegisteredComponentList().standard[type] : getRegisteredComponentList().custom[name];
if (rc) {
return rc;
}
let imp;
if (type === exports.Component.panel) {
imp = await new Promise(function (resolve) { resolve(require('./PanelWithLabel-07e64023.js')); });
}
else if (type === exports.Component.form) {
imp = await new Promise(function (resolve) { resolve(require('./Form-90ea99e5.js')); });
}
else if (type === exports.Component.tabs) {
imp = await new Promise(function (resolve) { resolve(require('./VsTabs-7b5ab7cb.js')); });
}
else if (type === exports.Component.tab) {
imp = await new Promise(function (resolve) { resolve(require('./Tab-47ed75ae.js')); });
}
else if (type === exports.Component.card) {
imp = await new Promise(function (resolve) { resolve(require('./Card-552fb4a5.js')); });
}
else if (type === exports.Component.accordion) {
imp = await new Promise(function (resolve) { resolve(require('./Accordion-8908c7b9.js')); });
}
else if (type === exports.Component.subschema) {
imp = await new Promise(function (resolve) { resolve(require('./Subschema-2ba61b84.js')); });
}
else if (type === exports.Component.textinput) {
imp = await new Promise(function (resolve) { resolve(require('./TextInput-3dc1cc49.js')); });
}
else if (type === exports.Component.number) {
imp = await new Promise(function (resolve) { resolve(require('./Number-2fd32587.js')); });
}
else if (type === exports.Component.integer) {
imp = await new Promise(function (resolve) { resolve(require('./Integer-63ec6409.js')); });
}
else if (type === exports.Component.select) {
imp = await new Promise(function (resolve) { resolve(require('./Select-cc0c92ee.js')); });
}
else if (type === exports.Component.date || type === exports.Component.datetime || type === exports.Component.time) {
imp = await new Promise(function (resolve) { resolve(require('./Date-8e73d5f0.js')); });
}
else if (type === exports.Component.radiogroup) {
imp = await new Promise(function (resolve) { resolve(require('./Radiogroup-1234e45e.js')); });
}
else if (type === exports.Component.checkbox) {
imp = await new Promise(function (resolve) { resolve(require('./Checkbox-0e1a5b6f.js')); });
}
else if (type === exports.Component.switch) {
imp = await new Promise(function (resolve) { resolve(require('./Switch-9c02356b.js')); });
}
else if (type === exports.Component.checklistbox) {
imp = await new Promise(function (resolve) { resolve(require('./Checklistbox-81578c49.js')); });
}
else if (type === exports.Component.text) {
imp = await new Promise(function (resolve) { resolve(require('./Text-4e318c60.js')); });
}
else if (type === exports.Component.button) {
imp = await new Promise(function (resolve) { resolve(require('./Button-34afdaa0.js')); });
}
else if (type === exports.Component.iconbutton) {
imp = await new Promise(function (resolve) { resolve(require('./IconButton-b28f7a77.js')); });
}
else if (type === exports.Component.icon) {
imp = await new Promise(function (resolve) { resolve(require('./Icon-266e0e93.js')); });
}
else if (type === exports.Component.divider) {
imp = await new Promise(function (resolve) { resolve(require('./Divider-4be3271f.js')); });
}
else if (type === exports.Component.mediastatic) {
imp = await new Promise(function (resolve) { resolve(require('./MediaStatic-49e7870a.js')); });
}
if (imp) {
registerComponent(type, imp.default, imp.styles);
return getRegisteredComponentList().standard[type];
}
else {
return undefined;
}
};
class VsForm extends React.Component {
constructor(props) {
super(props);
this.counter = 0;
this.getKey = () => {
const s = this.props.schemaManager.schema;
return s.name + (this.counter > 0 ? '_' + this.counter : '');
};
}
render() {
return (React.createElement(Item, Object.assign({}, this.props, { schema: this.props.schemaManager.schema, node: this.props.node, comp: this.props.schemaManager.schema.components[this.props.node], key: this.getKey() })));
}
componentDidMount() {
this.props.schemaManager.callSchemaEvent('onDidMount');
}
componentWillUnmount() {
this.props.schemaManager.clearInputRefList();
this.props.schemaManager.callSchemaEvent('onWillUnmount');
}
}
VsForm.defaultProps = {
node: 'root',
designMode: false
};
var propTypes = /*#__PURE__*/Object.freeze({
__proto__: null
});
const buttons = {
btnOk: 'btnOk',
btnCancel: 'btnCancel',
};
const arrayKeyField = '__rec_id__';
const htmlDateFormat = 'yyyy-MM-dd';
const htmlTimeFormat = 'HH:mm';
const htmlTimeFormatWithSeconds = 'HH:mm:ss';
var constants = /*#__PURE__*/Object.freeze({
__proto__: null,
buttons: buttons,
arrayKeyField: arrayKeyField,
htmlDateFormat: htmlDateFormat,
htmlTimeFormat: htmlTimeFormat,
htmlTimeFormatWithSeconds: htmlTimeFormatWithSeconds
});
const dataTypeIsArray = (dataType) => [exports.DataType.array, exports.DataType.arrayString, exports.DataType.arrayNumber, exports.DataType.arrayObject].indexOf(dataType) > -1;
const dataTypeToValue = (dataType) => {
if (dataType === exports.DataType.string) {
return '';
}
else if (dataType === exports.DataType.date) {
return null;
}
else if (dataType === exports.DataType.number || dataType === exports.DataType.integer) {
return null;
}
else if (dataType === exports.DataType.boolean) {
return false;
}
else if (dataType === exports.DataType.object) {
return {};
}
else if (dataTypeIsArray(dataType)) {
return [];
}
else {
return '';
}
};
const checkType = (type, value) => {
if (type === exports.DataType.any) {
return true;
}
else if (type === exports.DataType.string) {
return isString(value) || isNull(value);
}
else if (type === exports.DataType.number) {
return isNumber(value) || isNull(value);
}
else if (type === exports.DataType.integer) {
return isInteger(value) || isNull(value);
}
else if (type === exports.DataType.date) {
return isDate(value) || isNull(value);
}
else if (type === exports.DataType.function) {
return isFunction(value);
}
else if (type === exports.DataType.regex) {
return isRegExp(value);
}
else if (type === exports.DataType.array) {
return isArray(value);
}
else if (type === exports.DataType.arrayString) {
return isArray(value) && value.filter(e => !isString(e)).length === 0;
}
else if (type === exports.DataType.arrayNumber) {
return isArray(value) && value.filter(e => !isNumber(e)).length === 0;
}
else if (type === exports.DataType.arrayObject) {
return isArray(value) && value.filter(e => !isObject(e)).length === 0;
}
if (dataTypeIsArray(type)) {
return isArray(value);
}
if (isArray(value)) {
return (dataTypeIsArray(type));
}
return typeof value === type;
};
const formatJSON = (obj) => {
return JSON.stringify(obj, null, 2);
};
const valueIsNumber = (val) => {
if (typeof val === 'string') {
return !isNaN(Number(val));
}
return typeof val === 'number';
};
const dateToString = (date, compType, withSeconds) => {
const f = withSeconds ? htmlTimeFormatWithSeconds : htmlTimeFormat;
if (compType === exports.Component.date) {
return dateFns.format(date, htmlDateFormat);
}
else if (compType === exports.Component.datetime) {
return dateFns.format(date, htmlDateFormat) + 'T' + dateFns.format(date, f);
}
else if (compType === exports.Component.time) {
return dateFns.format(date, f);
}
return '';
};
const stringToDate = (compType, val) => {
let dt = null;
if ([exports.Component.date, exports.Component.datetime].indexOf(compType) > -1) {
try {
dt = new Date(val);
}
catch (error) {
}
}
else if (compType === exports.Component.time) {
try {
dt = new Date('1970-01-01T' + val);
}
catch (error) {
}
}
return dt;
};
const checkIsParentComponent = (comp) => {
if (comp && has(comp, 'children')) {
return comp;
}
else {
return undefined;
}
};
const checkIsDataComponent = (comp) => {
if (comp && has(comp, 'data.field')) {
return comp;
}
else {
return undefined;
}
};
const checkIsButtonComponent = (comp) => {
if (comp && (comp.type === exports.Component.button || comp.type === exports.Component.iconbutton)) {
return comp;
}
else {
return undefined;
}
};
const checkIsSelectComponent = (comp) => {
if (comp && (comp.type === exports.Component.select || comp.type === exports.Component.radiogroup || comp.type === exports.Component.selectext)) {
return comp;
}
else {
return undefined;
}
};
var common = /*#__PURE__*/Object.freeze({
__proto__: null,
dataTypeIsArray: dataTypeIsArray,
dataTypeToValue: dataTypeToValue,
checkType: checkType,
formatJSON: formatJSON,
valueIsNumber: valueIsNumber,
dateToString: dateToString,
stringToDate: stringToDate,
checkIsParentComponent: checkIsParentComponent,
checkIsDataComponent: checkIsDataComponent,
checkIsButtonComponent: checkIsButtonComponent,
checkIsSelectComponent: checkIsSelectComponent
});
var SchemaErrorType;
(function (SchemaErrorType) {
SchemaErrorType["error"] = "error";
SchemaErrorType["warning"] = "warning";
})(SchemaErrorType || (SchemaErrorType = {}));
var types = /*#__PURE__*/Object.freeze({
__proto__: null,
get SchemaErrorType () { return SchemaErrorType; }
});
var ErrorCode;
(function (ErrorCode) {
ErrorCode["rootnotContainer"] = "rootnotContainer";
ErrorCode["rootChildrenEmpty"] = "rootChildrenEmpty";
ErrorCode["errParseString"] = "errParseString";
ErrorCode["schemaNotFound"] = "schemaNotFound";
ErrorCode["subSchemaNotFound"] = "subSchemaNotFound";
ErrorCode["subSchemaKeyInvalid"] = "subSchemaKeyInvalid";
ErrorCode["componentsnotdefined"] = "componentsnotdefined";
ErrorCode["valuesnotdefined"] = "valuesnotdefined";
ErrorCode["namePropMissing"] = "namePropMissing";
ErrorCode["duplicateFields"] = "duplicateFields";
ErrorCode["duplicateFieldPaths"] = "duplicateFieldPaths";
ErrorCode["duplicateIds"] = "duplicateIds";
ErrorCode["fieldsHasNoParent"] = "fieldsHasNoParent";
ErrorCode["fieldhasDuplicatesInChildren"] = "fieldhasDuplicatesInChildren";
ErrorCode["valuesKeyHasNoField"] = "valuesKeyHasNoField";
ErrorCode["onlyFormTagForRootComp"] = "onlyFormTagForRootComp";
ErrorCode["recursiveChildren"] = "recursiveChildren";
ErrorCode["possibleRecursion"] = "possibleRecursion";
ErrorCode["hasnotype"] = "hasnotype";
ErrorCode["invalidtype"] = "invalidtype";
ErrorCode["invalidComponentType"] = "invalidComponentType";
ErrorCode["hasNoComponentType"] = "hasNoComponentType";
ErrorCode["requiredPropMissing"] = "requiredPropMissing";
ErrorCode["wrongPropertyType"] = "wrongPropertyType";
ErrorCode["wrongPropertyTypeInArray"] = "wrongPropertyTypeInArray";
ErrorCode["arrayIsEmpty"] = "arrayIsEmpty";
ErrorCode["noChildrenKeys"] = "noChildrenKeys";
ErrorCode["invalidChildrenKeys"] = "invalidChildrenKeys";
ErrorCode["invalidTabsKeys"] = "invalidTabsKeys";
ErrorCode["invalidColumns"] = "invalidColumns";
ErrorCode["notDataFieldColumns"] = "notDataFieldColumns";
ErrorCode["valueNotInEnum"] = "valueNotInEnum";
ErrorCode["valueSmallerThanMin"] = "valueSmallerThanMin";
ErrorCode["valueGreaterThanMax"] = "valueGreaterThanMax";
ErrorCode["valueNotInMinMax"] = "valueNotInMinMax";
ErrorCode["fieldNotInValues"] = "fieldNotInValues";
ErrorCode["wrongDataTypeInValues"] = "wrongDataTypeInValues";
ErrorCode["hasInvalidProp"] = "hasInvalidProp";
ErrorCode["wrongDataType"] = "wrongDataType";
ErrorCode["wrongDataTypeDefaultValue"] = "wrongDataTypeDefaultValue";
ErrorCode["selectItemsMustBeObjects"] = "selectItemsMustBeObjects";
ErrorCode["selectItemsMustHaveValueAndText"] = "selectItemsMustHaveValueAndText";
ErrorCode["selectItemsMustHaveCorrectDataType"] = "selectItemsMustHaveCorrectDataType";
ErrorCode["selectItemsUnique"] = "selectItemsUnique";
ErrorCode["selectItemsTextMusBeString"] = "selectItemsTextMusBeString";
ErrorCode["selectItemsTextOnlyOneEmpty"] = "selectItemsTextOnlyOneEmpty";
ErrorCode["selectItemsTextNotUnique"] = "selectItemsTextNotUnique";
ErrorCode["typeStringOrArray"] = "typeStringOrArray";
ErrorCode["compNotFound"] = "compNotFound";
ErrorCode["invalidPrefixType"] = "invalidPrefixType";
ErrorCode["invalidIconType"] = "invalidIconType";
ErrorCode["maskOnlyInMaskInputComponent"] = "maskOnlyInMaskInputComponent";
ErrorCode["maskNotMultilineInput"] = "maskNotMultilineInput";
ErrorCode["maskArrayOrFunction"] = "maskArrayOrFunction";
ErrorCode["maskArrayItemsStringOrRegExp"] = "maskArrayItemsStringOrRegExp";
ErrorCode["stringOrFunction"] = "stringOrFunction";
ErrorCode["styleMustBeObject"] = "styleMustBeObject";
ErrorCode["styleAttrNotObject"] = "styleAttrNotObject";
ErrorCode["speedDialActionObject"] = "speedDialActionObject";
ErrorCode["iconOrSvg"] = "iconOrSvg";
})(ErrorCode || (ErrorCode = {}));
const ErrorStrings = {
rootnotContainer: 'Root component type must be a container',
rootChildrenEmpty: 'the children array may not be empty',
errParseString: 'String parsing error',
schemaNotFound: 'ISchema not found in List',
subSchemaNotFound: 'Sub-Schema not found',
subSchemaKeyInvalid: 'The keyField is not a valid field.',
componentsnotdefined: 'components not defined!',
valuesnotdefined: 'values not defined!',
namePropMissing: 'schema has no name property',
duplicateFields: 'duplicate fields are present',
duplicateFieldPaths: 'duplicate Field Paths are present',
duplicateIds: 'duplicate Ids are present',
fieldsHasNoParent: 'field has no parent (not in any children)',
fieldhasDuplicatesInChildren: 'field is in several parents',
valuesKeyHasNoField: 'For the following value key(s) the component is missing:',
onlyFormTagForRootComp: 'Form component is only allowed for the root component',
recursiveChildren: 'Possible Recursion with children in containers',
possibleRecursion: 'Possible Recursion : More than 100 Sub-Schemas found',
hasnotype: 'has no type',
invalidtype: 'has invalid type',
requiredPropMissing: 'required Property missing',
wrongPropertyType: 'property has wrong type',
wrongPropertyTypeInArray: 'Items in the array has the wrong type',
arrayIsEmpty: 'array should not be empty',
noChildrenKeys: 'Container has no children',
invalidChildrenKeys: 'Container contains invalid keys',
invalidTabsKeys: 'Only tabs-Component are allowed',
invalidColumns: 'Data Table has invalid columns',
notDataFieldColumns: 'The columns of the Data Table must be data fields',
valueNotInEnum: 'value is not in the list of allowed values',
valueSmallerThanMin: 'value is smaller than minimum',
valueGreaterThanMax: 'value is greater than maximum',
valueNotInMinMax: 'value is not between min and max',
fieldNotInValues: 'field not present in schema.values',
wrongDataTypeInValues: 'field has wrong Value Type in schema.values',
hasInvalidProp: 'invalid (unnecessary) property',
wrongDataType: 'the value has a wrong data-type',
wrongDataTypeDefaultValue: 'the default value has the wrong data-type',
invalidComponentType: 'IComponent has an invalid type',
hasNoComponentType: 'Component has no type',
selectItemsMustBeObjects: 'Items in select must objects',
selectItemsMustHaveValueAndText: 'All Items in select must have a text and a value property',
selectItemsMustHaveCorrectDataType: 'All Item-Values must have the type defined in the datatype',
selectItemsUnique: 'All Item-Values must be unique',
selectItemsTextMusBeString: 'All Item-Texts must be string',
selectItemsTextOnlyOneEmpty: 'Only one Item should have empty string',
selectItemsTextNotUnique: 'Text in items are not unique',
typeStringOrArray: 'property must be either string or array of strings',
compNotFound: 'Prefix/Suffix: Component not found',
invalidPrefixType: 'Prefix/Suffix-Components must be either text, button or iconbutton',
invalidIconType: 'Icon-Component is not an icon',
maskOnlyInMaskInputComponent: 'mask can only be defined in the input component',
maskNotMultilineInput: 'masks cannot be applied to multiline inputs',
maskArrayOrFunction: 'mask must be either an array or a function',
maskArrayItemsStringOrRegExp: 'each item in the mask array mmust be either a string or a regexp',
stringOrFunction: 'property must be either string or a function',
styleMustBeObject: 'Style must be an object',
styleAttrNotObject: 'Style attribute should not be an object',
speedDialActionObject: 'Each Speed Dial Action must be an object',
iconOrSvg: 'Icon or svg property must be provided for Icon-Component',
};
var str_err = /*#__PURE__*/Object.freeze({
__proto__: null,
get ErrorCode () { return ErrorCode; },
ErrorStrings: ErrorStrings
});
const required = (name) => (v) => !!v || `${name} is required`;
const checkItemsInSelect = (_items, dataType) => {
if (isFunction(_items)) {
return '';
}
const items = _items;
let arr = [];
let sortedArr = [];
const dataTypeValue = () => dataType === exports.DataType.arrayString ? exports.DataType.string : (dataType === exports.DataType.arrayNumber || dataType === exports.DataType.integer || dataType === exports.DataType.arrayInteger) ? exports.DataType.number : dataType;
const getLineNumbers = (orig, error) => {
return error.map(el => orig.indexOf(el) + 1);
};
const arrToString = (a) => {
return a.map(e => e && e.value ? e.value.toString() : '' + ',' + (e ? e.text : '')).toString();
};
arr = items.filter(el => !(isObject(el)));
if (arr.length > 0) {
return { errcode: ErrorCode.selectItemsMustBeObjects, addOn: arrToString(arr), itemNo: getLineNumbers(items, arr).toString() };
}
arr = items.filter(el => !(has(el, 'value') && has(el, 'text')));
if (arr.length > 0) {
return { errcode: ErrorCode.selectItemsMustHaveValueAndText, addOn: arrToString(arr), itemNo: getLineNumbers(items, arr).toString() };
}
arr = items.filter((el) => typeof el.value !== dataTypeValue());
if (arr.length > 0) {
return { errcode: ErrorCode.selectItemsMustHaveCorrectDataType, addOn: arrToString(arr), itemNo: getLineNumbers(items, arr).toString() };
}
sortedArr = items.map(e => e);
if (dataTypeValue() === exports.DataType.number) {
sortedArr.sort((a, b) => (a.value - b.value));
}
else {
sortedArr.sort((a, b) => {
if (a.value < b.value) {
return -1;
}
else if (a.value > b.value) {
return 1;
}
else {
return 0;
}
});
}
arr = [];
for (let i = 0; i < sortedArr.length - 2; i++) {
if (sortedArr[i + 1] && sortedArr[i + 1].value === sortedArr[i].value) {
arr.push(sortedArr[i]);
}
}
arr = uniq(arr);
if (arr.length > 0) {
return { errcode: ErrorCode.selectItemsUnique, addOn: arrToString(arr), itemNo: getLineNumbers(items, arr).toString() };
}
arr = items.filter(el => !isString(el.text));
if (arr.length > 0) {
return { errcode: ErrorCode.selectItemsTextMusBeString, addOn: arrToString(arr) };
}
arr = items.filter(el => (el.text.trim() === ''));
if (arr.length > 1) {
return { errcode: ErrorCode.selectItemsTextOnlyOneEmpty, addOn: arrToString(arr) };
}
sortedArr = items.sort((a, b) => {
if (a.text < b.text) {
return -1;
}
else if (a.text > b.text) {
return 1;
}
else {
return 0;
}
});
arr = [];
for (let i = 0; i < sortedArr.length - 1; i++) {
if (sortedArr[i + 1].text === sortedArr[i].text) {
arr.push(sortedArr[i]);
}
}
arr = uniq(arr);
if (arr.length > 0) {
return { errcode: ErrorCode.selectItemsTextNotUnique, type: SchemaErrorType.warning, addOn: arrToString(arr), itemNo: getLineNumbers(items, arr).toString() };
}
return '';
};
var fieldValidators = /*#__PURE__*/Object.freeze({
__proto__: null,
required: required,
checkItemsInSelect: checkItemsInSelect
});
const rootIsWrong = sm => {
const comp = sm.schema.components.root;
if ([exports.Component.form, exports.Component.panel, exports.Component.card, exports.Component.accordion, exports.Component.tabs].indexOf(comp.type) === -1) {
return { errcode: ErrorCode.rootnotContainer, schemaName: sm.schema.name };
}
if (comp.children && isArray(comp.children) && comp.children.length === 0) {
return { errcode: ErrorCode.rootChildrenEmpty, schemaName: sm.schema.name };
}
return '';
};
const hasRecursion = sm => {
const counter = { count: 0, max: 100 };
hasRecursion1(sm, sm.schema, sm.schemaList, counter);
return counter.count >= counter.max
? { errcode: ErrorCode.possibleRecursion, schemaName: sm.schema.name }
: '';
};
function hasRecursion1(schemaManager, schema, schemaList, counter) {
if (counter.count >= counter.max) {
counter.count = counter.max + 1;
return;
}
Object.keys(schema.components).forEach(key => {
const comp = schema.components[key];
if (comp.type === exports.Component.subschema) {
counter.count++;
if (comp.schemaName && counter.count < counter.max) {
const s = schemaManager.getSchemaFromList(comp.schemaName);
if (s) {
hasRecursion1(schemaManager, s, schemaList, counter);
}
}
}
});
}
const hasUnresolvedSubschemaNames = sm => {
const arr = [];
const componentCallback = p => {
if (p.comp && p.comp.type === exports.Component.subschema && p.comp.schemaName) {
const s = sm.getSchemaFromList(p.comp.schemaName);
if (!s) {
arr.push(p.comp.schemaName);
}
}
};
const options = { processSubSchemas: true };
SchemaManager.processSchema({ componentCallback, schema: sm.schema, options });
return arr.length > 0
? {
errcode: ErrorCode.subSchemaNotFound,
addOn: arr.toString(),
schemaName: sm.schema.name
}
: '';
};
const onlyFormTagForRoot = sm => {
const arr = [];
const componentCallback = p => {
if (p.comp && p.comp.type === exports.Component.form && p.comp.id !== 'root') {
arr.push(p.comp.id);
}
};
const options = { processSubSchemas: false };
SchemaManager.processSchema({ componentCallback, schema: sm.schema, options });
return arr.length > 0
? {
errcode: ErrorCode.onlyFormTagForRootComp,
addOn: arr.toString(),
schemaName: sm.schema.name
}
: '';
};
const isDuplicateInChildren = sm => {
const parents = Object.keys(sm.schema.components).map(c => sm.schema.components[c]).filter(c => has(c, 'children'));
const getParents = (key) => parents.filter(c => c.children.includes(key));
const dup = [];
const componentCallback = p => {
const pr = getParents(p.comp.node);
if (pr.length > 1) {
dup.push(p.comp.node);
}
};
const options = { processSubSchemas: true };
SchemaManager.processSchema({ componentCallback, schema: sm.schema, options });
if (dup.length > 0) {
return {
errcode: ErrorCode.fieldhasDuplicatesInChildren,
type: SchemaErrorType.warning,
addOn: dup.toString(),
schemaName: sm.schema.name
};
}
else {
return '';
}
};
const childrenHasRecursion = sm => {
const dup = [];
const recursiveChildren = (comp, counter) => {
if (counter.count >= counter.max) {
counter.count = counter.max + 1;
return;
}
const cp = checkIsParentComponent(comp);
if (cp) {
cp.children.forEach((child) => {
counter.count++;
if (has(sm.schema.components, child) && counter.count < counter.max) {
recursiveChildren(sm.schema.components[child], counter);
}
});
}
};
const componentCallback = p => {
const counter = { count: 0, max: 500 };
recursiveChildren(p.comp, counter);
if (counter.count >= counter.max) {
const key = p.key;
if (!dup.includes(key)) {
dup.push(key);
}
}
};
const options = { processSubSchemas: true };
SchemaManager.processSchema({ componentCallback, schema: sm.schema, options });
if (dup.length > 0) {
return { errcode: ErrorCode.recursiveChildren, addOn: dup.toString(), schemaName: sm.schema.name };
}
else {
return '';
}
};
const hasDuplicateFields = sm => {
const arr = [];
let dup = [];
const componentCallback = p => {
const cd = checkIsDataComponent(p.comp);
if (cd) {
const field = cd.data.field;
if (arr.includes(field)) {
dup.push(field);
}
arr.push(field);
}
};
const options = { processSubSchemas: false };
SchemaManager.processSchema({ componentCallback, schema: sm.schema, options });
dup = uniq(dup);
if (dup.length > 0) {
return { errcode: ErrorCode.duplicateFields, addOn: dup.toString(), type: SchemaErrorType.warning, schemaName: sm.schema.name };
}
else {
return '';
}
};
const hasFieldsNotInChildren = sm => {
const missing = sm.getComponentsWithNoParent();
return missing.length > 0
? {
errcode: ErrorCode.fieldsHasNoParent,
addOn: missing.toString(),
type: SchemaErrorType.warning,
schemaName: sm.schema.name
}
: '';
};
const valuesKeyHasNoComponent = sm => {
const arr = [];
const getFields = (values, parent) => {
Object.keys(values).forEach(key => {
const comp = sm.getComponentByFieldPath(parent + key);
if (!comp) {
arr.push(parent + key);
}
else if (comp.type === exports.Component.subschema) {
getFields(values[key], parent + key + '.');
}
});
};
if (sm.schema.values) {
getFields(sm.schema.values, '');
}
if (arr.length > 0) {
return { errcode: ErrorCode.valuesKeyHasNoField, addOn: arr.toString(), type: SchemaErrorType.warning, schemaName: sm.schema.name };
}
else {
return '';
}
};
const hasValidChildrenKeys = (validSchema, component, schema) => {
const property = get(component, validSchema.prop);
if (property.length === 0) {
return { errcode: ErrorCode.noChildrenKeys, type: SchemaErrorType.warning };
}
const arr = [];
property.forEach((el) => {
if (!has(schema.components, el)) {
arr.push(el);
}
});
if (arr.length > 0) {
return { errcode: ErrorCode.invalidChildrenKeys, addOn: arr.toString() };
}
return '';
};
const hasValidTabsKeys = (validSchema, component, schema) => {
const property = get(component, validSchema.prop);
if (property.length === 0) {
return { errcode: ErrorCode.noChildrenKeys, type: SchemaErrorType.warning };
}
let arr = [];
property.forEach((el) => {
if (!has(schema.components, el)) {
arr.push(el);
}
});
if (arr.length > 0) {
return { errcode: ErrorCode.invalidChildrenKeys, addOn: arr.toString() };
}
arr = [];
property.forEach((el) => {
if (schema.components[el].type !== exports.Component.tab) {
arr.push(el);
}
});
if (arr.length > 0) {
return { errcode: ErrorCode.invalidTabsKeys, addOn: arr.toString() };
}
return '';
};
const stylesValid = (validSchema, component, _schema) => {
let err = '';
const property = get(component, validSchema.prop);
if (isObject(property)) {
Object.keys(property).forEach(key => {
if (!isObject(property[key])) {
err = { errcode: ErrorCode.styleMustBeObject, prop: 'styles.' + key };
return;
}
});
}
return err;
};
const speedDialActionsValid = (validSchema, component, _schema) => {
let err = '';
const property = get(component, validSchema.prop);
if (isArray(property)) {
if (property.length === 0) {
return { errcode: ErrorCode.arrayIsEmpty };
}
property.forEach((obj, ind) => {
const sInd = (ind + 1).toString();
if (isObject(obj)) {
if (isUndefined(obj['icon'])) {
err = { errcode: ErrorCode.requiredPropMissing, addOn: 'prop: icon', itemNo: sInd };
return;
}
if (!isString(obj['icon'])) {
err = { errcode: ErrorCode.wrongPropertyTypeInArray, addOn: 'prop: icon', itemNo: sInd };
return;
}
if (isUndefined(obj['tooltip'])) {
err = { errcode: ErrorCode.requiredPropMissing, addOn: 'prop: tooltip', itemNo: sInd };
return;
}
if (!isString(obj['tooltip'])) {
err = { errcode: ErrorCode.wrongPropertyTypeInArray, addOn: 'prop: tooltip', itemNo: sInd };
return;
}
if (isUndefined(obj['onClick'])) {
err = { errcode: ErrorCode.requiredPropMissing, addOn: 'prop: onClick', itemNo: sInd, type: SchemaErrorType.warning };
return;
}
if (!isFunction(obj['onClick'])) {
err = { errcode: ErrorCode.wrongPropertyTypeInArray, addOn: 'prop: onClick', itemNo: sInd };
return;
}
}
else {
err = { errcode: ErrorCode.speedDialActionObject, addOn: 'Entry No.: ' + sInd, itemNo: sInd };
return;
}
});
}
return err;
};
const prefixSuffixCompValid = (validSchema, component, schema) => {
const property = get(component, validSchema.prop);
if (!(isArray(property) || isString(property))) {
return { errcode: ErrorCode.typeStringOrArray };
}
if (isArray(property)) {
const arr = [];
property.forEach((s) => {
const c = schema.components[s];
if (!c) {
arr.push(s);
}
});
if (arr.length > 0) {
return { errcode: ErrorCode.compNotFound, addOn: arr.toString() };
}
property.forEach((s) => {
const c = schema.components[s];
if ([exports.Component.button, exports.Component.iconbutton, exports.Component.icon, exports.Component.text].indexOf(c.type) === -1) {
arr.push(s);
}
});
if (arr.length > 0) {
return { errcode: ErrorCode.invalidPrefixType, addOn: arr.toString() };
}
}
return '';
};
const iconValid = (_validSchema, component, _schema) => {
if (!(component['icon'] || component['svg'] || component['component'])) {
return { errcode: ErrorCode.iconOrSvg };
}
return '';
};
const iconCompValid = (validSchema, component, schema) => {
const property = get(component, validSchema.prop);
if (!(isArray(property) || isString(property))) {
return { errcode: ErrorCode.typeStringOrArray };
}
if (isArray(property)) {
const arr = [];
property.forEach((s) => {
const c = schema.components[s];
if (!c) {
arr.push(s);
}
});
if (arr.length > 0) {
return { errcode: ErrorCode.compNotFound, addOn: arr.toString() };
}
property.forEach((s) => {
const c = schema.components[s];
if (c.type !== exports.Component.icon) {
arr.push(s);
}
});
if (arr.length > 0) {
return { errcode: ErrorCode.invalidIconType, addOn: arr.toString() };
}
}
return '';
};
const subschemaKeyField = (validSchema, component, schema) => {
const property = get(component, validSchema.prop);
const subschema = component['schema'];
const options = { done: false };
let fieldFound = false;
const componentCallback = p => {
const cd = checkIsDataComponent(p.comp);
if (cd) {
if (cd.data.field === property) {
options.done = true;
fieldFound = true;
}
}
};
SchemaManager.processSchema({ componentCallback, schema: subschema, options });
if (!fieldFound) {
return { errcode: ErrorCode.subSchemaKeyInvalid };
}
return '';
};
const maskInput = (_validSchema, component, _schema) => {
if (component.type === exports.Component.maskinput) {