@geneui/components
Version:
The Gene UI components library designed for BI tools
84 lines (78 loc) • 2.57 kB
JavaScript
import { _ as _extends } from './_rollupPluginBabelHelpers-e8fb2e5c.js';
import React__default, { useState, useCallback } from 'react';
import { n as noop } from './index-a0e4e333.js';
import useMount from './hooks/useMount.js';
import './configs-00612ce0.js';
import { u as useFormContext } from './index-262edd7a.js';
import { g as guid } from './guid-8ddf77b3.js';
function Formable(WrappedComponent) {
return function (props) {
const {
isFieldValid = noop,
name: defaultName,
onChange = noop,
value
} = props;
const [_name, setName] = useState('');
const {
fields,
readOnlyState,
allowValidation,
handleFieldMount,
handleFieldUnMount,
handleFieldChange,
handleValidationChange
} = useFormContext();
// this function is called every time when validation changes
const handleInitialState = isValid => {
const field = fields.find(item => item.name === _name);
handleValidationChange({
...field,
_name,
isValid
});
isFieldValid(isValid);
};
// this function is called every time when value changes
// need to handle this because form submit follows form changes
const handleChange = useCallback((e, isValid, key) => {
// we need this check, because some fields return string not `event` object
const value = e && e.target ? e.target.value : e;
const field = fields.find(item => item.name === _name);
field && handleFieldChange({
...field,
isChanged: field.defaultValue !== value
});
onChange(e, isValid, key);
}, [fields, handleFieldChange, _name, onChange]);
// add fields to store when field mounted
useMount(() => {
// generate local name if `name` is undefined
const localName = defaultName || guid();
// generate default value if `value` is undefined
const defaultValue = value || '';
setName(localName);
handleFieldMount({
name: localName,
defaultValue,
isValid: true,
isChanged: false
});
return () => handleFieldUnMount({
name: localName
});
});
return /*#__PURE__*/React__default.createElement(WrappedComponent, _extends({}, props, {
name: _name,
onChange: handleChange,
isFieldValid: handleInitialState,
forceAllowValidation: allowValidation,
readOnly: readOnlyState || props.readOnly
}));
};
}
Formable.defaultProps = {
onChange: noop,
isFieldValid: noop
};
export { Formable as F };