UNPKG

vs-form-mui-4x

Version:

A schema-based form generator component for React using material-ui 4.x

1,316 lines (1,291 loc) 135 kB
import React__default, { Component as Component$1, createElement, Fragment, createRef } from 'react'; import capitalize from 'lodash/capitalize'; export { default as o } from 'lodash/capitalize'; import cloneDeep from 'lodash/cloneDeep'; export { default as q } from 'lodash/cloneDeep'; import get from 'lodash/get'; export { default as u } from 'lodash/get'; import has from 'lodash/has'; export { default as w } from 'lodash/has'; import isArray from 'lodash/isArray'; export { default as x } from 'lodash/isArray'; import isDate from 'lodash/isDate'; export { default as y } from 'lodash/isDate'; export { default as z } from 'lodash/isBoolean'; export { default as A } from 'lodash/isEmpty'; import isFunction from 'lodash/isFunction'; export { default as E } from 'lodash/isFunction'; import isInteger from 'lodash/isInteger'; export { default as F } from 'lodash/isInteger'; import isNull from 'lodash/isNull'; export { default as G } from 'lodash/isNull'; import isNumber from 'lodash/isNumber'; export { default as H } from 'lodash/isNumber'; import isObject from 'lodash/isObject'; export { default as I } from 'lodash/isObject'; import isPlainObject from 'lodash/isPlainObject'; export { default as J } from 'lodash/isPlainObject'; import isRegExp from 'lodash/isRegExp'; export { default as K } from 'lodash/isRegExp'; import isString from 'lodash/isString'; export { default as L } from 'lodash/isString'; import isUndefined from 'lodash/isUndefined'; export { default as M } from 'lodash/isUndefined'; import merge from 'lodash/merge'; export { default as N } from 'lodash/merge'; import set from 'lodash/set'; export { default as O } from 'lodash/set'; export { default as P } from 'lodash/toInteger'; export { default as Q } from 'lodash/toNumber'; export { default as R } from 'lodash/trimEnd'; import uniq from 'lodash/uniq'; export { default as T } from 'lodash/uniq'; export { default as U } from 'lodash/debounce'; export { default as W } from 'lodash/throttle'; import FormControl from '@material-ui/core/FormControl'; import FormHelperText from '@material-ui/core/FormHelperText'; import FormLabel from '@material-ui/core/FormLabel'; import TextField from '@material-ui/core/TextField'; import InputAdornment from '@material-ui/core/InputAdornment'; import Tooltip from '@material-ui/core/Tooltip'; import { withStyles, createStyles } from '@material-ui/core/styles'; import classNames from 'classnames'; import Icon from '@material-ui/core/Icon'; import SvgIcon from '@material-ui/core/SvgIcon'; import { format } from 'date-fns'; import { EventEmitter } from 'events'; import Typography from '@material-ui/core/Typography'; import Grid from '@material-ui/core/Grid'; import IconButton from '@material-ui/core/IconButton'; class VsBaseDataComponent extends Component$1 { 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 Component$1 { 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 (createElement(FormControl, Object.assign({ error: !!dataProps.state.error }, this.FormControlProps), this.props.showLabel && createElement(FormLabel, Object.assign({}, this.FormLabelProps), comp.label), this.props.children({ ...dataProps }), formhelpertext && createElement(FormHelperText, Object.assign({ error: !!dataProps.state.error }, this.FormHelperTextProps), formhelpertext))); }; this.initProps(); } render() { return (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; } } } var Component; (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"; })(Component || (Component = {})); var DataType; (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"; })(DataType || (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 = {})); var ValidationMethod; (function (ValidationMethod) { ValidationMethod[ValidationMethod["validateOnChange"] = 1] = "validateOnChange"; ValidationMethod[ValidationMethod["validateOnSubmit"] = 2] = "validateOnSubmit"; })(ValidationMethod || (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 = {})); var ButtonAction; (function (ButtonAction) { ButtonAction["none"] = "none"; ButtonAction["save"] = "save"; ButtonAction["cancel"] = "cancel"; })(ButtonAction || (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 Component; }, get DataType () { return DataType; }, get ComponentType () { return ComponentType; }, get InputVariant () { return InputVariant; }, get ValidationMethod () { return ValidationMethod; }, get InputType () { return InputType; }, get ButtonAction () { return ButtonAction; }, get SchemaEventType () { return SchemaEventType; }, get SortDirection () { return SortDirection; } }); class ErrorBoundary extends Component$1 { 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 (createElement(Fragment, null, createElement("p", { style: { color: 'red' } }, "Component with id: \"", this.props.comp.node, "\" has errors! "), createElement("p", { style: { color: 'red' } }, "check the console for more info."))); } return this.props.children; } } const addStyles = (component, styles) => { return withStyles(styles)(component); }; const styles = 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) => (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 = createElement(Icon, Object.assign({}, other, { className: cl })); } else if (props['svg']) { const p = props; const { tooltip, tooltipProps, svg, ...other } = p; ic = (createElement(SvgIcon, Object.assign({}, other), createElement("path", { d: p.svg }))); } else if (props['component']) { const p = props; const { tooltip, tooltipProps, component, ...other } = p; ic = (createElement(SvgIcon, Object.assign({}, other, { component: p.component }))); } if (ic) { return props.tooltip ? createElement(Tooltip, Object.assign({ title: props.tooltip }, props.tooltipProps), createElement("span", null, ic)) : ic; } else { return 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 !== Component.custom ? getRegisteredComponentList().standard[type] : getRegisteredComponentList().custom[name]; if (rc) { return rc; } let imp; if (type === Component.panel) { imp = await import('./PanelWithLabel-ad4fa86b.js'); } else if (type === Component.form) { imp = await import('./Form-8580ecad.js'); } else if (type === Component.tabs) { imp = await import('./VsTabs-573552c7.js'); } else if (type === Component.tab) { imp = await import('./Tab-3d3ddf95.js'); } else if (type === Component.card) { imp = await import('./Card-1ebb87a3.js'); } else if (type === Component.accordion) { imp = await import('./Accordion-49d4b681.js'); } else if (type === Component.subschema) { imp = await import('./Subschema-857a3035.js'); } else if (type === Component.textinput) { imp = await import('./TextInput-0ea8e9f0.js'); } else if (type === Component.number) { imp = await import('./Number-963ef610.js'); } else if (type === Component.integer) { imp = await import('./Integer-6384603c.js'); } else if (type === Component.select) { imp = await import('./Select-2474d120.js'); } else if (type === Component.date || type === Component.datetime || type === Component.time) { imp = await import('./Date-d7f518b5.js'); } else if (type === Component.radiogroup) { imp = await import('./Radiogroup-99dd7dee.js'); } else if (type === Component.checkbox) { imp = await import('./Checkbox-3ac493b2.js'); } else if (type === Component.switch) { imp = await import('./Switch-d842ff76.js'); } else if (type === Component.checklistbox) { imp = await import('./Checklistbox-227283ac.js'); } else if (type === Component.text) { imp = await import('./Text-31a1db71.js'); } else if (type === Component.button) { imp = await import('./Button-db281587.js'); } else if (type === Component.iconbutton) { imp = await import('./IconButton-d1ec6e1a.js'); } else if (type === Component.icon) { imp = await import('./Icon-b2885a65.js'); } else if (type === Component.divider) { imp = await import('./Divider-3341fba0.js'); } else if (type === Component.mediastatic) { imp = await import('./MediaStatic-ac877302.js'); } if (imp) { registerComponent(type, imp.default, imp.styles); return getRegisteredComponentList().standard[type]; } else { return undefined; } }; class VsForm extends Component$1 { 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 (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) => [DataType.array, DataType.arrayString, DataType.arrayNumber, DataType.arrayObject].indexOf(dataType) > -1; const dataTypeToValue = (dataType) => { if (dataType === DataType.string) { return ''; } else if (dataType === DataType.date) { return null; } else if (dataType === DataType.number || dataType === DataType.integer) { return null; } else if (dataType === DataType.boolean) { return false; } else if (dataType === DataType.object) { return {}; } else if (dataTypeIsArray(dataType)) { return []; } else { return ''; } }; const checkType = (type, value) => { if (type === DataType.any) { return true; } else if (type === DataType.string) { return isString(value) || isNull(value); } else if (type === DataType.number) { return isNumber(value) || isNull(value); } else if (type === DataType.integer) { return isInteger(value) || isNull(value); } else if (type === DataType.date) { return isDate(value) || isNull(value); } else if (type === DataType.function) { return isFunction(value); } else if (type === DataType.regex) { return isRegExp(value); } else if (type === DataType.array) { return isArray(value); } else if (type === DataType.arrayString) { return isArray(value) && value.filter(e => !isString(e)).length === 0; } else if (type === DataType.arrayNumber) { return isArray(value) && value.filter(e => !isNumber(e)).length === 0; } else if (type === 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 === Component.date) { return format(date, htmlDateFormat); } else if (compType === Component.datetime) { return format(date, htmlDateFormat) + 'T' + format(date, f); } else if (compType === Component.time) { return format(date, f); } return ''; }; const stringToDate = (compType, val) => { let dt = null; if ([Component.date, Component.datetime].indexOf(compType) > -1) { try { dt = new Date(val); } catch (error) { } } else if (compType === 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 === Component.button || comp.type === Component.iconbutton)) { return comp; } else { return undefined; } }; const checkIsSelectComponent = (comp) => { if (comp && (comp.type === Component.select || comp.type === Component.radiogroup || comp.type === 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 === DataType.arrayString ? DataType.string : (dataType === DataType.arrayNumber || dataType === DataType.integer || dataType === DataType.arrayInteger) ? 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() === 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 ([Component.form, Component.panel, Component.card, Component.accordion, 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 === 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 === 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 === 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 === 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 !== 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 ([Component.button, Component.iconbutton, Component.icon, 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 !== 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 === Component.maskinput) { if (component.props && component.props.multiline) { return { errcode: ErrorCode.maskNotMultilineInput }; } const mask = component.maskProps.mask; if (isFunction(mask)) { return ''; } else if (isArray(mask)) { const arr = mask.filter(e => !(isString(e) || isRegExp(e))); if (arr.length > 0) { return { errcode: ErrorCode.maskArrayItemsStringOrRegExp }; } } else { return { errcode: ErrorCode.maskArrayOrFunction }; } } else { return { errcode: ErrorCode.maskOnlyInMaskInputComponent }; } return ''; }; const numberFormat = (_validSchema, component, _schema) => { const ci = component; if (!ci.numberFormatProps) { return { errcode: ErrorCode.requiredPropMissing }; } if (ci.numberFormatProps.format) { if (!(isString(ci.numberFormatProps.format) || isFunction(ci.numberFormatProps.format))) { return { errcode: ErrorCode.stringOrFunction, prop: 'numberFormatProps.format' }; } } if (ci.numberFormatProps.mask) { if (!(isString(ci.numberFormatProps.mask) || isArray(ci.numberFormatProps.mask))) { return { errcode: ErrorCode.typeStringOrArray, prop: 'numberFormatProps.mask' }; } } return ''; }; const defaultValue = (validSchema, component, _schema) => { let err = false; const cd = checkIsDataComponent(component); if (cd) { const property = get(component, validSchema.prop); if (isUndefined(property) || !cd.data.dataType) { return ''; } if (isFunction(property)) { return '';