@coko/client
Version:
Client side common code for coko apps
218 lines (205 loc) • 12.7 kB
JavaScript
;
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _lodash = require("lodash");
var _antd = require("antd");
var _toolkit = require("../../toolkit");
var _Ribbon = _interopRequireDefault(require("./Ribbon"));
var _excluded = ["children", "onBlur", "validateTrigger"],
_excluded2 = ["autoSave", "autoSaveDebounceDelay", "children", "feedbackComponent", "form", "onAutoSave", "onValuesChange", "onFinishFailed", "ribbonMessage", "ribbonPosition", "submissionStatus", "scrollErrorIntoView"];
var _templateObject, _templateObject2;
/* eslint-disable react/jsx-props-no-spreading */
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
var FormWrapper = _styledComponents["default"].div(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n .ant-form-item-explain-error {\n color: ", ";\n }\n"])), (0, _toolkit.th)('colorError'));
var Ribbon = (0, _styledComponents["default"])(_Ribbon["default"])(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n margin: ", " ", ";\n"])), (0, _toolkit.grid)(2), (0, _toolkit.grid)(4));
var FormItem = function FormItem(props) {
/**
* Disable prop types as these props will be checked in the `AntForm.Item`
* component. Enable again if you introduce custom props.
*/
/* eslint-disable-next-line react/prop-types */
var children = props.children,
onBlur = props.onBlur,
validateTrigger = props.validateTrigger,
rest = _objectWithoutProperties(props, _excluded);
var _useState = (0, _react.useState)(false),
_useState2 = _slicedToArray(_useState, 2),
lostFocusOnce = _useState2[0],
setLostFocusOnce = _useState2[1];
/**
* Default behaviour is that errors only appear once you have touched the
* input and moved away from it. Once touched, validations are run on every
* change. Submitting a form will touch all fields. Setting validateTrigger
* in the props will override the default behaviour. All we're doing here is
* changing the default.
*/
var useDefaultTrigger = !validateTrigger;
var defaultTrigger = !lostFocusOnce ? 'onBlur' : 'onChange';
var trigger = useDefaultTrigger ? defaultTrigger : validateTrigger;
var handleBlur = function handleBlur() {
if (useDefaultTrigger && !lostFocusOnce) setLostFocusOnce(true);
onBlur && onBlur();
};
return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, _extends({
onBlur: handleBlur,
validateTrigger: trigger
}, rest), children);
};
// Disable the prop types that are the same as the underlying component
var Form = function Form(props) {
var autoSave = props.autoSave,
autoSaveDebounceDelay = props.autoSaveDebounceDelay,
children = props.children,
FeedbackComponent = props.feedbackComponent,
propsForm = props.form,
onAutoSave = props.onAutoSave,
onValuesChange = props.onValuesChange,
onFinishFailed = props.onFinishFailed,
ribbonMessage = props.ribbonMessage,
ribbonPosition = props.ribbonPosition,
submissionStatus = props.submissionStatus,
scrollErrorIntoView = props.scrollErrorIntoView,
rest = _objectWithoutProperties(props, _excluded2);
var showRibbon = !!submissionStatus && !!ribbonMessage;
var _AntForm$useForm = _antd.Form.useForm(),
_AntForm$useForm2 = _slicedToArray(_AntForm$useForm, 1),
internalForm = _AntForm$useForm2[0];
var form = propsForm || internalForm;
// eslint-disable-next-line react/prop-types
var runAutoSave = (0, _lodash.debounce)(function () {
return onAutoSave(form.getFieldsValue());
}, 500);
var handleValuesChange = function handleValuesChange(changedValues, allValues) {
if (autoSave && onAutoSave) runAutoSave();
onValuesChange && onValuesChange();
};
var FeedbackElement = showRibbon && /*#__PURE__*/_react["default"].createElement(FeedbackComponent, {
"data-testid": "feedback-element",
role: "alert",
status: submissionStatus
}, ribbonMessage);
// const FeedbackElement = (
// <FeedbackComponent hide={!showRibbon} status={submissionStatus}>
// {ribbonMessage}
// </FeedbackComponent>
// )
// if form validation fails, scroll to first error field (if applicable) and focus
var focusErrorField = function focusErrorField(errorFields) {
var firstErrorField = document.getElementById(errorFields[0].name.join('_'));
// handle case when input is a radio group
if (firstErrorField.matches('div[role="radiogroup"]')) {
// should focus it's first radio button, since radiogroup is not focusable
firstErrorField = firstErrorField.querySelector('input[type="radio"]');
}
// create intersection observer to to check when scroll target is in view
var observer = new IntersectionObserver(function (entries) {
var _entries = _slicedToArray(entries, 1),
entry = _entries[0];
if (entry.isIntersecting) {
setTimeout(function () {
// focus element after it becomes visible
entry.target.focus();
observer.unobserve(entry.target);
}, 100);
}
});
observer.observe(firstErrorField);
// scroll to first error field
form.scrollToField(errorFields[0].name, {
// specify custom scrolling behavior
behavior: function behavior(actions) {
if (actions.length === 0) {
// no element to scroll to, field is visible
firstErrorField.focus();
} else {
// check motion preferences; avoid scrolling if users prefers reduced motion
var motionQuery = window.matchMedia('(prefers-reduced-motion)');
// start observing for when field becomes visible
observer.observe(firstErrorField);
var action = actions.find(function (el) {
return el.top > 0;
});
var el = action.el,
top = action.top,
left = action.left;
el.scrollTo({
top: top - 50,
left: left,
behavior: motionQuery.matches ? 'auto' : 'smooth'
});
}
}
});
};
var handleFinishFailed = function handleFinishFailed(data) {
if (scrollErrorIntoView) {
var errorFields = data.errorFields;
focusErrorField(errorFields);
}
onFinishFailed(data);
};
return /*#__PURE__*/_react["default"].createElement(FormWrapper, null, ribbonPosition === 'top' && FeedbackElement, /*#__PURE__*/_react["default"].createElement(_antd.Form, _extends({
"data-testid": "form-content",
form: form,
onFinishFailed: handleFinishFailed,
onValuesChange: handleValuesChange
}, rest), children), ribbonPosition === 'bottom' && FeedbackElement);
};
Form.propTypes = {
autoSave: _propTypes["default"].bool,
autoSaveDebounceDelay: _propTypes["default"].number,
feedbackComponent: _propTypes["default"].elementType,
onAutoSave: _propTypes["default"].func,
onFinishFailed: _propTypes["default"].func,
ribbonMessage: _propTypes["default"].string,
ribbonPosition: _propTypes["default"].oneOf(['top', 'bottom']),
submissionStatus: _propTypes["default"].oneOf(['success', 'error', 'danger']),
scrollErrorIntoView: _propTypes["default"].bool
};
Form.defaultProps = {
autoSave: false,
autoSaveDebounceDelay: 500,
feedbackComponent: Ribbon,
onAutoSave: null,
onFinishFailed: function onFinishFailed() {},
ribbonMessage: null,
ribbonPosition: 'top',
submissionStatus: null,
scrollErrorIntoView: true
};
// const Form = {}
// Object.setPrototypeOf(Form, AntForm)
/* Replicate exports from https://github.com/ant-design/ant-design/blob/master/components/form/index.tsx#L24-L35 */
Form.render = Form;
Form.Item = FormItem;
Form.List = _antd.Form.List;
Form.ErrorList = _antd.Form.ErrorList;
Form.useForm = _antd.Form.useForm;
Form.Provider = _antd.Form.FormProvider;
// Form.create = () => {
// devWarning(
// false,
// 'Form',
// 'antd v4 removed `Form.create`. Please remove or use `@ant-design/compatible` instead.',
// )
// }
var _default = Form;
exports["default"] = _default;