Commit a135ef38c8c0beeb470b9dff43aa1231415a6659

Authored by 邢晴晴
1 parent 77e7daf6

回退版本到1.7.3

Showing 35 changed files with 487 additions and 3233 deletions

Too many changes to show.

To preserve performance only 35 of 95 files are displayed.

es/atom.css renamed from es/form-render-core/src/atom.css
es/connectForm.js renamed from es/form-render-core/src/connectForm.js
es/core/RenderChildren/RenderList/CardList.js renamed from es/form-render-core/src/core/RenderChildren/RenderList/CardList.js
1 import "antd/es/button/style"; 1 import "antd/es/button/style";
2 import _Button from "antd/es/button"; 2 import _Button from "antd/es/button";
3 -import "antd/es/popconfirm/style";  
4 -import _Popconfirm from "antd/es/popconfirm";  
5 -import _CloseOutlined from "@ant-design/icons/lib/icons/CloseOutlined";  
6 -import _CopyOutlined from "@ant-design/icons/lib/icons/CopyOutlined"; 3 +import "antd/es/space/style";
  4 +import _Space from "antd/es/space";
7 import _ArrowDownOutlined from "@ant-design/icons/lib/icons/ArrowDownOutlined"; 5 import _ArrowDownOutlined from "@ant-design/icons/lib/icons/ArrowDownOutlined";
8 import _ArrowUpOutlined from "@ant-design/icons/lib/icons/ArrowUpOutlined"; 6 import _ArrowUpOutlined from "@ant-design/icons/lib/icons/ArrowUpOutlined";
  7 +import _CopyOutlined from "@ant-design/icons/lib/icons/CopyOutlined";
  8 +import "antd/es/popconfirm/style";
  9 +import _Popconfirm from "antd/es/popconfirm";
  10 +import _DeleteOutlined from "@ant-design/icons/lib/icons/DeleteOutlined";
9 11
10 function _extends() { _extends = Object.assign || 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); } 12 function _extends() { _extends = Object.assign || 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); }
11 13
@@ -56,44 +58,44 @@ var CardList = function CardList(_ref) { @@ -56,44 +58,44 @@ var CardList = function CardList(_ref) {
56 key: idx 58 key: idx
57 }, /*#__PURE__*/React.createElement("div", { 59 }, /*#__PURE__*/React.createElement("div", {
58 className: "fr-card-index" 60 className: "fr-card-index"
59 - }, idx + 1), /*#__PURE__*/React.createElement(Core, fieldsProps), /*#__PURE__*/React.createElement("div", { 61 + }, idx + 1), /*#__PURE__*/React.createElement(Core, fieldsProps), /*#__PURE__*/React.createElement(_Space, {
60 direction: "horizontal", 62 direction: "horizontal",
61 className: "fr-card-toolbar" 63 className: "fr-card-toolbar"
62 - }, !props.hideMove && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_ArrowUpOutlined, { 64 + }, !props.hideDelete && /*#__PURE__*/React.createElement(_Popconfirm, {
  65 + title: "\u786E\u5B9A\u5220\u9664?",
  66 + onConfirm: function onConfirm() {
  67 + return deleteItem(idx);
  68 + },
  69 + okText: "\u786E\u5B9A",
  70 + cancelText: "\u53D6\u6D88"
  71 + }, /*#__PURE__*/React.createElement(_DeleteOutlined, {
  72 + style: {
  73 + fontSize: 17,
  74 + marginLeft: 8
  75 + }
  76 + })), !props.hideAdd && !props.hideCopy && /*#__PURE__*/React.createElement(_CopyOutlined, {
63 style: { 77 style: {
64 fontSize: 16, 78 fontSize: 16,
65 - marginLeft: 4 79 + marginLeft: 8
66 }, 80 },
67 onClick: function onClick() { 81 onClick: function onClick() {
68 - return moveItemUp(idx); 82 + return copyItem(idx);
69 } 83 }
70 - }), /*#__PURE__*/React.createElement(_ArrowDownOutlined, { 84 + }), !props.hideMove && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_ArrowUpOutlined, {
71 style: { 85 style: {
72 fontSize: 16, 86 fontSize: 16,
73 marginLeft: 4 87 marginLeft: 4
74 }, 88 },
75 onClick: function onClick() { 89 onClick: function onClick() {
76 - return moveItemDown(idx); 90 + return moveItemUp(idx);
77 } 91 }
78 - })), !props.hideAdd && !props.hideCopy && /*#__PURE__*/React.createElement(_CopyOutlined, { 92 + }), /*#__PURE__*/React.createElement(_ArrowDownOutlined, {
79 style: { 93 style: {
80 fontSize: 16, 94 fontSize: 16,
81 - marginLeft: 8 95 + marginLeft: 4
82 }, 96 },
83 onClick: function onClick() { 97 onClick: function onClick() {
84 - return copyItem(idx);  
85 - }  
86 - }), !props.hideDelete && /*#__PURE__*/React.createElement(_Popconfirm, {  
87 - title: "\u786E\u5B9A\u5220\u9664?",  
88 - onConfirm: function onConfirm() {  
89 - return deleteItem(idx);  
90 - },  
91 - okText: "\u786E\u5B9A",  
92 - cancelText: "\u53D6\u6D88"  
93 - }, /*#__PURE__*/React.createElement(_CloseOutlined, {  
94 - style: {  
95 - fontSize: 16,  
96 - marginLeft: 8 98 + return moveItemDown(idx);
97 } 99 }
98 })))); 100 }))));
99 })), /*#__PURE__*/React.createElement("div", { 101 })), /*#__PURE__*/React.createElement("div", {
@@ -4,6 +4,8 @@ import "antd/es/drawer/style"; @@ -4,6 +4,8 @@ import "antd/es/drawer/style";
4 import _Drawer from "antd/es/drawer"; 4 import _Drawer from "antd/es/drawer";
5 import "antd/es/button/style"; 5 import "antd/es/button/style";
6 import _Button from "antd/es/button"; 6 import _Button from "antd/es/button";
  7 +import "antd/es/space/style";
  8 +import _Space from "antd/es/space";
7 import _ArrowDownOutlined from "@ant-design/icons/lib/icons/ArrowDownOutlined"; 9 import _ArrowDownOutlined from "@ant-design/icons/lib/icons/ArrowDownOutlined";
8 import _ArrowUpOutlined from "@ant-design/icons/lib/icons/ArrowUpOutlined"; 10 import _ArrowUpOutlined from "@ant-design/icons/lib/icons/ArrowUpOutlined";
9 import "antd/es/popconfirm/style"; 11 import "antd/es/popconfirm/style";
@@ -124,7 +126,7 @@ var DrawerList = function DrawerList(_ref) { @@ -124,7 +126,7 @@ var DrawerList = function DrawerList(_ref) {
124 width: 120, 126 width: 120,
125 render: function render(value, record, idx) { 127 render: function render(value, record, idx) {
126 var index = value && value.$idx || 0; 128 var index = value && value.$idx || 0;
127 - return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("a", { 129 + return /*#__PURE__*/React.createElement(_Space, null, /*#__PURE__*/React.createElement("a", {
128 onClick: function onClick() { 130 onClick: function onClick() {
129 return openDrawer(index); 131 return openDrawer(index);
130 } 132 }
es/core/RenderChildren/RenderList/SimpleList.js renamed from es/form-render-core/src/core/RenderChildren/RenderList/SimpleList.js
@@ -2,6 +2,8 @@ import "antd/es/table/style"; @@ -2,6 +2,8 @@ import "antd/es/table/style";
2 import _Table from "antd/es/table"; 2 import _Table from "antd/es/table";
3 import "antd/es/button/style"; 3 import "antd/es/button/style";
4 import _Button from "antd/es/button"; 4 import _Button from "antd/es/button";
  5 +import "antd/es/space/style";
  6 +import _Space from "antd/es/space";
5 import _ArrowDownOutlined from "@ant-design/icons/lib/icons/ArrowDownOutlined"; 7 import _ArrowDownOutlined from "@ant-design/icons/lib/icons/ArrowDownOutlined";
6 import _ArrowUpOutlined from "@ant-design/icons/lib/icons/ArrowUpOutlined"; 8 import _ArrowUpOutlined from "@ant-design/icons/lib/icons/ArrowUpOutlined";
7 import "antd/es/popconfirm/style"; 9 import "antd/es/popconfirm/style";
@@ -105,7 +107,7 @@ var TableList = function TableList(_ref) { @@ -105,7 +107,7 @@ var TableList = function TableList(_ref) {
105 fixed: 'right', 107 fixed: 'right',
106 width: 120, 108 width: 120,
107 render: function render(value, record, idx) { 109 render: function render(value, record, idx) {
108 - return /*#__PURE__*/React.createElement("div", null, !props.hideAdd && !props.hideCopy && /*#__PURE__*/React.createElement("a", { 110 + return /*#__PURE__*/React.createElement(_Space, null, !props.hideAdd && !props.hideCopy && /*#__PURE__*/React.createElement("a", {
109 onClick: function onClick() { 111 onClick: function onClick() {
110 return copyItem(idx); 112 return copyItem(idx);
111 } 113 }
es/core/RenderChildren/RenderList/VirtualList.js renamed from es/form-render-core/src/core/RenderChildren/RenderList/VirtualList.js
@@ -123,7 +123,7 @@ var VirtualList = function VirtualList(_ref) { @@ -123,7 +123,7 @@ var VirtualList = function VirtualList(_ref) {
123 style: { 123 style: {
124 color: '#1890ff', 124 color: '#1890ff',
125 fontSize: 16, 125 fontSize: 16,
126 - marginLeft: 8 126 + marginLeft: 4
127 }, 127 },
128 onClick: function onClick() { 128 onClick: function onClick() {
129 return moveItemUp(idx); 129 return moveItemUp(idx);
@@ -132,7 +132,7 @@ var VirtualList = function VirtualList(_ref) { @@ -132,7 +132,7 @@ var VirtualList = function VirtualList(_ref) {
132 style: { 132 style: {
133 color: '#1890ff', 133 color: '#1890ff',
134 fontSize: 16, 134 fontSize: 16,
135 - marginLeft: 8 135 + marginLeft: 4
136 }, 136 },
137 onClick: function onClick() { 137 onClick: function onClick() {
138 return moveItemDown(idx); 138 return moveItemDown(idx);
es/core/RenderChildren/RenderList/index.js renamed from es/form-render-core/src/core/RenderChildren/RenderList/index.js
@@ -28,7 +28,6 @@ import CardList from './CardList'; @@ -28,7 +28,6 @@ import CardList from './CardList';
28 import TableList from './TableList'; 28 import TableList from './TableList';
29 import DrawerList from './DrawerList'; 29 import DrawerList from './DrawerList';
30 import VirtualList from './VirtualList'; 30 import VirtualList from './VirtualList';
31 -import TabList from './TabList';  
32 31
33 var RenderList = function RenderList(_ref) { 32 var RenderList = function RenderList(_ref) {
34 var parentId = _ref.parentId, 33 var parentId = _ref.parentId,
@@ -177,9 +176,6 @@ var RenderList = function RenderList(_ref) { @@ -177,9 +176,6 @@ var RenderList = function RenderList(_ref) {
177 case 'virtualList': 176 case 'virtualList':
178 return /*#__PURE__*/React.createElement(VirtualList, displayProps); 177 return /*#__PURE__*/React.createElement(VirtualList, displayProps);
179 178
180 - case 'tabList':  
181 - return /*#__PURE__*/React.createElement(TabList, displayProps);  
182 -  
183 default: 179 default:
184 return /*#__PURE__*/React.createElement(CardList, displayProps); 180 return /*#__PURE__*/React.createElement(CardList, displayProps);
185 } 181 }
es/core/RenderChildren/RenderList/list.css renamed from es/form-render-core/src/core/RenderChildren/RenderList/list.css
es/core/RenderChildren/RenderObject.js renamed from es/form-render-core/src/core/RenderChildren/RenderObject.js
es/core/RenderField/ErrorMessage.css renamed from es/form-render-core/src/core/RenderField/ErrorMessage.css
es/core/RenderField/ErrorMessage.js renamed from es/form-render-core/src/core/RenderField/ErrorMessage.js
es/core/RenderField/ExtendedWidget.js renamed from es/form-render-core/src/core/RenderField/ExtendedWidget.js
@@ -152,14 +152,8 @@ var ExtendedWidget = function ExtendedWidget(_ref) { @@ -152,14 +152,8 @@ var ExtendedWidget = function ExtendedWidget(_ref) {
152 }; 152 };
153 153
154 var areEqual = function areEqual(prev, current) { 154 var areEqual = function areEqual(prev, current) {
155 - if (prev.schema && current.schema) {  
156 - if (prev.schema.$id === '#') {  
157 - return false;  
158 - }  
159 -  
160 - if (prev.schema.hidden && current.schema.hidden) {  
161 - return true;  
162 - } 155 + if (prev.schema && prev.schema.$id === '#') {
  156 + return false;
163 } 157 }
164 158
165 if (prev.readOnly !== current.readOnly) { 159 if (prev.readOnly !== current.readOnly) {
es/core/RenderField/Extra.css renamed from es/form-render-core/src/core/RenderField/Extra.css
es/core/RenderField/Extra.js renamed from es/form-render-core/src/core/RenderField/Extra.js
es/core/RenderField/Title.js renamed from es/form-render-core/src/core/RenderField/Title.js
es/core/RenderField/index.js renamed from es/form-render-core/src/core/RenderField/index.js
@@ -2,18 +2,6 @@ function _extends() { _extends = Object.assign || function (target) { for (var i @@ -2,18 +2,6 @@ function _extends() { _extends = Object.assign || function (target) { for (var i
2 2
3 function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 3 function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4 4
5 -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }  
6 -  
7 -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }  
8 -  
9 -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); }  
10 -  
11 -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }  
12 -  
13 -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }  
14 -  
15 -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; }  
16 -  
17 import React, { useEffect, useRef } from 'react'; 5 import React, { useEffect, useRef } from 'react';
18 import { useStore, useStore2, useTools } from '../../hooks'; 6 import { useStore, useStore2, useTools } from '../../hooks';
19 import useDebouncedCallback from '../../useDebounce'; 7 import useDebouncedCallback from '../../useDebounce';
@@ -21,7 +9,6 @@ import { getValueByPath, isCheckBoxType, isObjType } from '../../utils'; @@ -21,7 +9,6 @@ import { getValueByPath, isCheckBoxType, isObjType } from '../../utils';
21 import ErrorMessage from './ErrorMessage'; 9 import ErrorMessage from './ErrorMessage';
22 import Extra from './Extra'; 10 import Extra from './Extra';
23 import FieldTitle from './Title'; 11 import FieldTitle from './Title';
24 -import { validateField } from '../../validator';  
25 import ExtendedWidget from './ExtendedWidget'; // TODO: 之后不要直接用get,收口到一个内部方法getValue,便于全局 ctrl + f 查找 12 import ExtendedWidget from './ExtendedWidget'; // TODO: 之后不要直接用get,收口到一个内部方法getValue,便于全局 ctrl + f 查找
26 13
27 var RenderField = function RenderField(props) { 14 var RenderField = function RenderField(props) {
@@ -41,23 +28,19 @@ var RenderField = function RenderField(props) { @@ -41,23 +28,19 @@ var RenderField = function RenderField(props) {
41 displayType = props.displayType; 28 displayType = props.displayType;
42 29
43 var _useStore = useStore(), 30 var _useStore = useStore(),
44 - formData = _useStore.formData,  
45 - flatten = _useStore.flatten; 31 + formData = _useStore.formData;
46 32
47 var _useStore2 = useStore2(), 33 var _useStore2 = useStore2(),
48 debounceInput = _useStore2.debounceInput, 34 debounceInput = _useStore2.debounceInput,
49 readOnly = _useStore2.readOnly, 35 readOnly = _useStore2.readOnly,
50 disabled = _useStore2.disabled, 36 disabled = _useStore2.disabled,
51 - showValidate = _useStore2.showValidate,  
52 - validateMessages = _useStore2.validateMessages,  
53 - locale = _useStore2.locale; 37 + showValidate = _useStore2.showValidate;
54 38
55 var _useTools = useTools(), 39 var _useTools = useTools(),
56 onValuesChange = _useTools.onValuesChange, 40 onValuesChange = _useTools.onValuesChange,
57 onItemChange = _useTools.onItemChange, 41 onItemChange = _useTools.onItemChange,
58 setEditing = _useTools.setEditing, 42 setEditing = _useTools.setEditing,
59 - touchKey = _useTools.touchKey,  
60 - _setErrors = _useTools._setErrors; 43 + touchKey = _useTools.touchKey;
61 44
62 var formDataRef = useRef(); 45 var formDataRef = useRef();
63 formDataRef.current = formData; // console.log('<renderField>', $id); 46 formDataRef.current = formData; // console.log('<renderField>', $id);
@@ -75,38 +58,7 @@ var RenderField = function RenderField(props) { @@ -75,38 +58,7 @@ var RenderField = function RenderField(props) {
75 58
76 var _readOnly = readOnly !== undefined ? readOnly : _schema.readOnly; 59 var _readOnly = readOnly !== undefined ? readOnly : _schema.readOnly;
77 60
78 - var _disabled = disabled !== undefined ? disabled : _schema.disabled;  
79 -  
80 - var removeDupErrors = function removeDupErrors(arr) {  
81 - if (!Array.isArray(arr)) {  
82 - console.log('in removeDups: param is not an array');  
83 - return;  
84 - }  
85 -  
86 - var array = [];  
87 -  
88 - for (var i = 0; i < arr.length; i++) {  
89 - var sameNameIndex = array.findIndex(function (item) {  
90 - return item.name === arr[i].name;  
91 - });  
92 -  
93 - if (sameNameIndex > -1) {  
94 - var sameNameItem = array[sameNameIndex];  
95 - var error1 = sameNameItem.error;  
96 - var error2 = arr[i].error;  
97 - array[sameNameIndex] = {  
98 - name: sameNameItem.name,  
99 - error: error1.length > 0 && error2.length > 0 ? [].concat(_toConsumableArray(error1), _toConsumableArray(error2)) : []  
100 - };  
101 - } else {  
102 - array.push(arr[i]);  
103 - }  
104 - }  
105 -  
106 - return array.filter(function (item) {  
107 - return Array.isArray(item.error) && item.error.length > 0;  
108 - });  
109 - }; // TODO: 优化一下,只有touch还是false的时候,setTouched 61 + var _disabled = disabled !== undefined ? disabled : _schema.disabled; // TODO: 优化一下,只有touch还是false的时候,setTouched
110 62
111 63
112 var onChange = function onChange(value) { 64 var onChange = function onChange(value) {
@@ -126,20 +78,6 @@ var RenderField = function RenderField(props) { @@ -126,20 +78,6 @@ var RenderField = function RenderField(props) {
126 if (typeof onValuesChange === 'function') { 78 if (typeof onValuesChange === 'function') {
127 onValuesChange(_defineProperty({}, dataPath, value), formDataRef.current); 79 onValuesChange(_defineProperty({}, dataPath, value), formDataRef.current);
128 } 80 }
129 -  
130 - validateField({  
131 - path: dataPath,  
132 - formData: formDataRef.current,  
133 - flatten: flatten,  
134 - options: {  
135 - locale: locale,  
136 - validateMessages: validateMessages  
137 - }  
138 - }).then(function (res) {  
139 - _setErrors(function (errors) {  
140 - return removeDupErrors([].concat(_toConsumableArray(errors), _toConsumableArray(res)));  
141 - });  
142 - });  
143 }; 81 };
144 82
145 var titleProps = { 83 var titleProps = {
es/core/index.js renamed from es/form-render-core/src/core/index.js
@@ -133,12 +133,11 @@ var CoreRender = function CoreRender(_ref2) { @@ -133,12 +133,11 @@ var CoreRender = function CoreRender(_ref2) {
133 effectiveLabelWidth = _ref2.effectiveLabelWidth, 133 effectiveLabelWidth = _ref2.effectiveLabelWidth,
134 rest = _objectWithoutProperties(_ref2, _excluded2); 134 rest = _objectWithoutProperties(_ref2, _excluded2);
135 135
136 - if (schema.hidden) {  
137 - return null;  
138 - } // 样式的逻辑全放在这层 136 + // if (schema.hidden) {
  137 + // return null;
  138 + // }
  139 + // 样式的逻辑全放在这层
139 // displayType 一层层网上找值 140 // displayType 一层层网上找值
140 -  
141 -  
142 var _displayType = schema.displayType || rest.displayType || displayType || 'column'; 141 var _displayType = schema.displayType || rest.displayType || displayType || 'column';
143 142
144 var isList = isListType(schema); 143 var isList = isListType(schema);
@@ -321,8 +320,7 @@ var CoreRender = function CoreRender(_ref2) { @@ -321,8 +320,7 @@ var CoreRender = function CoreRender(_ref2) {
321 style: columnStyle, 320 style: columnStyle,
322 className: "".concat(containerClass, " ").concat(debugCss ? 'debug' : '') 321 className: "".concat(containerClass, " ").concat(debugCss ? 'debug' : '')
323 }, /*#__PURE__*/React.createElement(RenderField, fieldProps, _children)); 322 }, /*#__PURE__*/React.createElement(RenderField, fieldProps, _children));
324 -}; // haven't used  
325 - 323 +};
326 324
327 var areEqual = function areEqual(prev, current) { 325 var areEqual = function areEqual(prev, current) {
328 if (prev.allTouched !== current.allTouched) { 326 if (prev.allTouched !== current.allTouched) {
@@ -341,24 +339,6 @@ var areEqual = function areEqual(prev, current) { @@ -341,24 +339,6 @@ var areEqual = function areEqual(prev, current) {
341 return false; 339 return false;
342 } 340 }
343 341
344 - if (prev.readOnly !== current.readOnly) {  
345 - return false;  
346 - }  
347 -  
348 - if (prev.disabled !== current.disabled) {  
349 - return false;  
350 - }  
351 -  
352 - if (prev.schema && current.schema) {  
353 - if (prev.schema.$id === '#') {  
354 - return false;  
355 - }  
356 - }  
357 -  
358 - if (isObjType(prev.schema) && isObjType(current.schema)) {  
359 - return false;  
360 - }  
361 -  
362 if (JSON.stringify(prev.dependValues) !== JSON.stringify(current.dependValues)) { 342 if (JSON.stringify(prev.dependValues) !== JSON.stringify(current.dependValues)) {
363 return false; 343 return false;
364 } 344 }
@@ -370,4 +350,5 @@ var areEqual = function areEqual(prev, current) { @@ -370,4 +350,5 @@ var areEqual = function areEqual(prev, current) {
370 return false; 350 return false;
371 }; 351 };
372 352
  353 +var MCore = /*#__PURE__*/React.memo(CoreRender, areEqual);
373 export default Core; 354 export default Core;
es/createWidget.js renamed from es/form-render-core/src/createWidget.js
1 -/* eslint-disable react-hooks/exhaustive-deps */  
2 -import { useEffect } from 'react';  
3 -import { getValueByPath } from './utils';  
4 -  
5 -var Watcher = function Watcher(_ref) {  
6 - var watchKey = _ref.watchKey,  
7 - watch = _ref.watch,  
8 - formData = _ref.formData,  
9 - firstMount = _ref.firstMount;  
10 - var value = getValueByPath(formData, watchKey);  
11 - var watchObj = watch[watchKey];  
12 - useEffect(function () {  
13 - var runWatcher = function runWatcher() {  
14 - if (typeof watchObj === 'function') {  
15 - try {  
16 - watchObj(value);  
17 - } catch (error) {  
18 - console.log("".concat(watchKey, "\u5BF9\u5E94\u7684watch\u51FD\u6570\u6267\u884C\u62A5\u9519\uFF1A"), error);  
19 - }  
20 - } else if (watchObj && typeof watchObj.handler === 'function') {  
21 - try {  
22 - watchObj.handler(value);  
23 - } catch (error) {  
24 - console.log("".concat(watchKey, "\u5BF9\u5E94\u7684watch\u51FD\u6570\u6267\u884C\u62A5\u9519\uFF1A"), error);  
25 - }  
26 - }  
27 - };  
28 -  
29 - if (firstMount) {  
30 - var immediate = watchObj && watchObj.immediate;  
31 -  
32 - if (immediate) {  
33 - runWatcher();  
34 - }  
35 - } else {  
36 - runWatcher();  
37 - }  
38 - }, [JSON.stringify(value), firstMount]);  
39 - return null;  
40 -};  
41 -  
42 -export default Watcher;  
1 -import "antd/es/table/style";  
2 -import _Table from "antd/es/table";  
3 -import "antd/es/drawer/style";  
4 -import _Drawer from "antd/es/drawer";  
5 -import "antd/es/button/style";  
6 -import _Button from "antd/es/button";  
7 -import _ArrowDownOutlined from "@ant-design/icons/lib/icons/ArrowDownOutlined";  
8 -import _ArrowUpOutlined from "@ant-design/icons/lib/icons/ArrowUpOutlined";  
9 -import "antd/es/popconfirm/style";  
10 -import _Popconfirm from "antd/es/popconfirm";  
11 -var _excluded = ["buttons"],  
12 - _excluded2 = ["pagination"];  
13 -  
14 -function _extends() { _extends = Object.assign || 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); }  
15 -  
16 -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }  
17 -  
18 -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."); }  
19 -  
20 -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); }  
21 -  
22 -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; }  
23 -  
24 -function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }  
25 -  
26 -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }  
27 -  
28 -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }  
29 -  
30 -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }  
31 -  
32 -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }  
33 -  
34 -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; }  
35 -  
36 -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; }  
37 -  
38 -/* eslint-disable jsx-a11y/anchor-is-valid */  
39 -import React, { useRef } from 'react';  
40 -import Core from '../../index';  
41 -import { useSet } from '../../../hooks';  
42 -import { getDataPath, getKeyFromPath, getDisplayValue } from '../../../utils';  
43 -import ErrorMessage from '../../RenderField/ErrorMessage';  
44 -var FIELD_LENGTH = 170;  
45 -  
46 -var DrawerList = function DrawerList(_ref) {  
47 - var _extends2;  
48 -  
49 - var _ref$displayList = _ref.displayList,  
50 - displayList = _ref$displayList === void 0 ? [] : _ref$displayList,  
51 - dataPath = _ref.dataPath,  
52 - children = _ref.children,  
53 - deleteItem = _ref.deleteItem,  
54 - addItem = _ref.addItem,  
55 - moveItemDown = _ref.moveItemDown,  
56 - moveItemUp = _ref.moveItemUp,  
57 - flatten = _ref.flatten,  
58 - errorFields = _ref.errorFields,  
59 - getFieldsProps = _ref.getFieldsProps,  
60 - schema = _ref.schema,  
61 - changeList = _ref.changeList,  
62 - listData = _ref.listData;  
63 - var _schema$props = schema.props,  
64 - props = _schema$props === void 0 ? {} : _schema$props,  
65 - _schema$itemProps = schema.itemProps,  
66 - itemProps = _schema$itemProps === void 0 ? {} : _schema$itemProps;  
67 -  
68 - var buttons = itemProps.buttons,  
69 - columnProps = _objectWithoutProperties(itemProps, _excluded);  
70 -  
71 - var _props$pagination = props.pagination,  
72 - pagination = _props$pagination === void 0 ? {} : _props$pagination,  
73 - rest = _objectWithoutProperties(props, _excluded2);  
74 -  
75 - var paginationConfig = pagination && _objectSpread({  
76 - size: 'small',  
77 - hideOnSinglePage: true  
78 - }, pagination);  
79 -  
80 - var currentIndex = useRef(-1);  
81 -  
82 - var _useSet = useSet({  
83 - showDrawer: false  
84 - }),  
85 - _useSet2 = _slicedToArray(_useSet, 2),  
86 - state = _useSet2[0],  
87 - setState = _useSet2[1];  
88 -  
89 - var showDrawer = state.showDrawer;  
90 - var dataSource = displayList.map(function (item, index) {  
91 - return _objectSpread(_objectSpread({}, item), {}, {  
92 - $idx: index  
93 - });  
94 - });  
95 - var columns = children.map(function (child) {  
96 - var item = flatten[child];  
97 - var schema = item && item.schema || {};  
98 -  
99 - var _dataIndex = getKeyFromPath(child);  
100 -  
101 - return _objectSpread({  
102 - dataIndex: _dataIndex,  
103 - title: schema.required ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {  
104 - className: "fr-label-required"  
105 - }, " *"), /*#__PURE__*/React.createElement("span", null, schema.title)) : schema.title,  
106 - width: FIELD_LENGTH,  
107 - render: function render(value, record) {  
108 - var childPath = getDataPath(child, [record.$idx]);  
109 - var errorObj = errorFields.find(function (item) {  
110 - return item.name == childPath;  
111 - }) || {}; //TODO: 万一error在更深的层,这个办法是find不到的,会展示那一行没有提示。可以整一行加一个红线的方式处理  
112 -  
113 - return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", null, getDisplayValue(value, schema)), errorObj.error && /*#__PURE__*/React.createElement(ErrorMessage, {  
114 - message: errorObj.error,  
115 - schema: schema  
116 - }));  
117 - }  
118 - }, columnProps);  
119 - });  
120 - columns.push({  
121 - title: '操作',  
122 - key: '$action',  
123 - fixed: 'right',  
124 - width: 120,  
125 - render: function render(value, record, idx) {  
126 - var index = value && value.$idx || 0;  
127 - return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("a", {  
128 - onClick: function onClick() {  
129 - return openDrawer(index);  
130 - }  
131 - }, "\u7F16\u8F91"), !props.hideDelete && /*#__PURE__*/React.createElement(_Popconfirm, {  
132 - title: "\u786E\u5B9A\u5220\u9664?",  
133 - onConfirm: function onConfirm() {  
134 - return deleteItem(index);  
135 - },  
136 - okText: "\u786E\u5B9A",  
137 - cancelText: "\u53D6\u6D88"  
138 - }, /*#__PURE__*/React.createElement("a", {  
139 - style: {  
140 - marginLeft: 8  
141 - }  
142 - }, "\u5220\u9664")), !props.hideMove && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_ArrowUpOutlined, {  
143 - style: {  
144 - color: '#1890ff',  
145 - fontSize: 16,  
146 - marginLeft: 8  
147 - },  
148 - onClick: function onClick() {  
149 - return moveItemUp(idx);  
150 - }  
151 - }), /*#__PURE__*/React.createElement(_ArrowDownOutlined, {  
152 - style: {  
153 - color: '#1890ff',  
154 - fontSize: 16,  
155 - marginLeft: 8  
156 - },  
157 - onClick: function onClick() {  
158 - return moveItemDown(idx);  
159 - }  
160 - })));  
161 - }  
162 - });  
163 - var fieldsProps = getFieldsProps(currentIndex.current);  
164 -  
165 - var openDrawer = function openDrawer(index) {  
166 - currentIndex.current = index;  
167 - setState({  
168 - showDrawer: true  
169 - });  
170 - };  
171 -  
172 - var closeDrawer = function closeDrawer() {  
173 - currentIndex.current = -1;  
174 - setState({  
175 - showDrawer: false  
176 - });  
177 - };  
178 -  
179 - var handleAdd = function handleAdd() {  
180 - var newIndex = addItem();  
181 - openDrawer(newIndex);  
182 - };  
183 -  
184 - return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {  
185 - className: "w-100 mb2 tr"  
186 - }, !props.hideAdd && /*#__PURE__*/React.createElement(_Button, {  
187 - type: "primary",  
188 - size: "small",  
189 - onClick: handleAdd  
190 - }, "\u65B0\u589E"), Array.isArray(props.buttons) ? props.buttons.map(function (item, idx) {  
191 - var callback = item.callback,  
192 - text = item.text,  
193 - html = item.html;  
194 -  
195 - var onClick = function onClick() {  
196 - console.log({  
197 - value: listData,  
198 - onChange: changeList,  
199 - schema: schema  
200 - });  
201 - };  
202 -  
203 - if (typeof window[callback] === 'function') {  
204 - onClick = function onClick() {  
205 - window[callback]({  
206 - value: listData,  
207 - onChange: changeList,  
208 - schema: schema  
209 - });  
210 - };  
211 - }  
212 -  
213 - return /*#__PURE__*/React.createElement(_Button, {  
214 - key: idx.toString(),  
215 - style: {  
216 - marginLeft: 8  
217 - },  
218 - size: "small",  
219 - onClick: onClick  
220 - }, /*#__PURE__*/React.createElement("span", {  
221 - dangerouslySetInnerHTML: {  
222 - __html: html || text  
223 - }  
224 - }));  
225 - }) : null), /*#__PURE__*/React.createElement(_Drawer, {  
226 - width: "600",  
227 - title: "\u7F16\u8F91",  
228 - placement: "right",  
229 - onClose: closeDrawer,  
230 - visible: showDrawer,  
231 - destroyOnClose: true // 必须要加,currentIndex不是一个state,Core不会重新渲染就跪了  
232 -  
233 - }, /*#__PURE__*/React.createElement("div", {  
234 - className: "fr-container"  
235 - }, /*#__PURE__*/React.createElement(Core, fieldsProps))), /*#__PURE__*/React.createElement(_Table, _extends((_extends2 = {  
236 - size: "small",  
237 - scroll: {  
238 - x: 'max-content'  
239 - },  
240 - columns: columns,  
241 - dataSource: dataSource,  
242 - rowClassName: function rowClassName(record, idx) {  
243 - var index = record && record.$idx;  
244 - var hasError = errorFields.find(function (item) {  
245 - return item.name.indexOf("".concat(dataPath, "[").concat(index, "]")) > -1;  
246 - });  
247 - return hasError ? 'fr-row-error' : '';  
248 - },  
249 - rowKey: "$idx"  
250 - }, _defineProperty(_extends2, "size", "small"), _defineProperty(_extends2, "pagination", paginationConfig), _extends2), rest)));  
251 -};  
252 -  
253 -export default DrawerList;  
1 -import "antd/es/tabs/style";  
2 -import _Tabs from "antd/es/tabs";  
3 -var _excluded = ["tabName", "type"];  
4 -  
5 -function _extends() { _extends = Object.assign || 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); }  
6 -  
7 -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; }  
8 -  
9 -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; }  
10 -  
11 -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }  
12 -  
13 -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."); }  
14 -  
15 -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); }  
16 -  
17 -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; }  
18 -  
19 -function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }  
20 -  
21 -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }  
22 -  
23 -/* eslint-disable jsx-a11y/anchor-is-valid */  
24 -import React, { useState } from 'react';  
25 -import Core from '../../index';  
26 -var TabPane = _Tabs.TabPane;  
27 -  
28 -var TabList = function TabList(_ref) {  
29 - var _ref$displayList = _ref.displayList,  
30 - displayList = _ref$displayList === void 0 ? [] : _ref$displayList,  
31 - listData = _ref.listData,  
32 - changeList = _ref.changeList,  
33 - schema = _ref.schema,  
34 - deleteItem = _ref.deleteItem,  
35 - copyItem = _ref.copyItem,  
36 - addItem = _ref.addItem,  
37 - moveItemUp = _ref.moveItemUp,  
38 - moveItemDown = _ref.moveItemDown,  
39 - displayType = _ref.displayType,  
40 - getFieldsProps = _ref.getFieldsProps;  
41 -  
42 - var _useState = useState('0'),  
43 - _useState2 = _slicedToArray(_useState, 2),  
44 - activeKey = _useState2[0],  
45 - setActiveKey = _useState2[1];  
46 -  
47 - var _schema$props = schema.props,  
48 - props = _schema$props === void 0 ? {} : _schema$props,  
49 - itemProps = schema.itemProps;  
50 -  
51 - var tabName = props.tabName,  
52 - type = props.type,  
53 - restProps = _objectWithoutProperties(props, _excluded);  
54 -  
55 - var onEdit = function onEdit(targetKey, action) {  
56 - if (action === 'add') {  
57 - var currentKey = addItem();  
58 - setActiveKey("".concat(currentKey));  
59 - } else if (action === 'remove') {  
60 - deleteItem(Number(targetKey));  
61 - setActiveKey("".concat(targetKey > 1 ? targetKey - 1 : 0));  
62 - } else {  
63 - return null;  
64 - }  
65 - };  
66 -  
67 - var getCurrentTabPaneName = function getCurrentTabPaneName(idx) {  
68 - return tabName instanceof Array ? tabName[idx] || idx + 1 : "".concat(tabName || '项目', " ").concat(idx + 1);  
69 - };  
70 -  
71 - return /*#__PURE__*/React.createElement(_Tabs, _extends({  
72 - type: type || 'line',  
73 - onChange: setActiveKey,  
74 - activeKey: activeKey,  
75 - onEdit: onEdit  
76 - }, restProps), displayList.map(function (item, idx) {  
77 - var fieldsProps = getFieldsProps(idx);  
78 - fieldsProps.displayType = displayType;  
79 - return /*#__PURE__*/React.createElement(TabPane, {  
80 - tab: getCurrentTabPaneName(idx),  
81 - key: "".concat(idx)  
82 - }, /*#__PURE__*/React.createElement(Core, fieldsProps));  
83 - }));  
84 -};  
85 -  
86 -export default TabList;  
1 -import "antd/es/table/style";  
2 -import _Table from "antd/es/table";  
3 -import "antd/es/button/style";  
4 -import _Button from "antd/es/button";  
5 -import _ArrowDownOutlined from "@ant-design/icons/lib/icons/ArrowDownOutlined";  
6 -import _ArrowUpOutlined from "@ant-design/icons/lib/icons/ArrowUpOutlined";  
7 -import "antd/es/popconfirm/style";  
8 -import _Popconfirm from "antd/es/popconfirm";  
9 -var _excluded = ["buttons"],  
10 - _excluded2 = ["pagination"];  
11 -  
12 -function _extends() { _extends = Object.assign || 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); }  
13 -  
14 -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }  
15 -  
16 -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }  
17 -  
18 -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); }  
19 -  
20 -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }  
21 -  
22 -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }  
23 -  
24 -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; }  
25 -  
26 -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }  
27 -  
28 -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }  
29 -  
30 -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }  
31 -  
32 -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; }  
33 -  
34 -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; }  
35 -  
36 -/* eslint-disable jsx-a11y/anchor-is-valid */  
37 -import React from 'react';  
38 -import Core from '../../index';  
39 -// import ArrowDown from '../../../components/ArrowDown';  
40 -var FIELD_LENGTH = 170;  
41 -  
42 -var TableList = function TableList(_ref) {  
43 - var _ref$displayList = _ref.displayList,  
44 - displayList = _ref$displayList === void 0 ? [] : _ref$displayList,  
45 - dataIndex = _ref.dataIndex,  
46 - children = _ref.children,  
47 - deleteItem = _ref.deleteItem,  
48 - copyItem = _ref.copyItem,  
49 - addItem = _ref.addItem,  
50 - moveItemUp = _ref.moveItemUp,  
51 - moveItemDown = _ref.moveItemDown,  
52 - flatten = _ref.flatten,  
53 - schema = _ref.schema,  
54 - listData = _ref.listData,  
55 - changeList = _ref.changeList;  
56 - var _schema$props = schema.props,  
57 - props = _schema$props === void 0 ? {} : _schema$props,  
58 - _schema$itemProps = schema.itemProps,  
59 - itemProps = _schema$itemProps === void 0 ? {} : _schema$itemProps;  
60 -  
61 - var buttons = itemProps.buttons,  
62 - columnProps = _objectWithoutProperties(itemProps, _excluded);  
63 -  
64 - var _props$pagination = props.pagination,  
65 - pagination = _props$pagination === void 0 ? {} : _props$pagination,  
66 - rest = _objectWithoutProperties(props, _excluded2);  
67 -  
68 - var paginationConfig = pagination && _objectSpread({  
69 - size: 'small',  
70 - hideOnSinglePage: true  
71 - }, pagination);  
72 -  
73 - var dataSource = displayList.map(function (item, idx) {  
74 - return {  
75 - index: idx  
76 - };  
77 - });  
78 - var columns = children.map(function (child) {  
79 - var item = flatten[child];  
80 - var schema = item && item.schema || {};  
81 - return _objectSpread({  
82 - dataIndex: child,  
83 - title: schema.required ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {  
84 - className: "fr-label-required"  
85 - }, " *"), /*#__PURE__*/React.createElement("span", null, schema.title)) : schema.title,  
86 - width: FIELD_LENGTH,  
87 - render: function render(value, record, index) {  
88 - // Check: record.index 似乎是antd自己会给的,不错哦  
89 - var childIndex = [].concat(_toConsumableArray(dataIndex), [record.index]);  
90 - return /*#__PURE__*/React.createElement(Core, {  
91 - hideTitle: true,  
92 - displayType: "inline",  
93 - key: index.toString(),  
94 - id: child,  
95 - dataIndex: childIndex  
96 - });  
97 - }  
98 - }, columnProps);  
99 - });  
100 -  
101 - if (!props.hideDelete || !props.hideAdd || !props.hideCopy || !props.hideMove) {  
102 - columns.push({  
103 - title: '操作',  
104 - key: '$action',  
105 - fixed: 'right',  
106 - width: 120,  
107 - render: function render(value, record, idx) {  
108 - return /*#__PURE__*/React.createElement("div", null, !props.hideAdd && !props.hideCopy && /*#__PURE__*/React.createElement("a", {  
109 - onClick: function onClick() {  
110 - return copyItem(idx);  
111 - }  
112 - }, "\u590D\u5236"), !props.hideDelete && /*#__PURE__*/React.createElement(_Popconfirm, {  
113 - title: "\u786E\u5B9A\u5220\u9664?",  
114 - onConfirm: function onConfirm() {  
115 - return deleteItem(idx);  
116 - },  
117 - okText: "\u786E\u5B9A",  
118 - cancelText: "\u53D6\u6D88"  
119 - }, /*#__PURE__*/React.createElement("a", {  
120 - style: {  
121 - marginLeft: 8  
122 - }  
123 - }, "\u5220\u9664")), !props.hideMove && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_ArrowUpOutlined, {  
124 - style: {  
125 - color: '#1890ff',  
126 - fontSize: 16,  
127 - marginLeft: 8  
128 - },  
129 - onClick: function onClick() {  
130 - return moveItemUp(idx);  
131 - }  
132 - }), /*#__PURE__*/React.createElement(_ArrowDownOutlined, {  
133 - style: {  
134 - color: '#1890ff',  
135 - fontSize: 16,  
136 - marginLeft: 8  
137 - },  
138 - onClick: function onClick() {  
139 - return moveItemDown(idx);  
140 - }  
141 - })));  
142 - }  
143 - });  
144 - }  
145 -  
146 - return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {  
147 - className: "w-100 mb2 tr"  
148 - }, !props.hideAdd && /*#__PURE__*/React.createElement(_Button, {  
149 - type: "primary",  
150 - size: "small",  
151 - onClick: addItem  
152 - }, "\u65B0\u589E"), Array.isArray(props.buttons) ? props.buttons.map(function (item, idx) {  
153 - var callback = item.callback,  
154 - text = item.text,  
155 - html = item.html;  
156 -  
157 - var onClick = function onClick() {  
158 - console.log({  
159 - value: listData,  
160 - onChange: changeList,  
161 - schema: schema  
162 - });  
163 - };  
164 -  
165 - if (typeof window[callback] === 'function') {  
166 - onClick = function onClick() {  
167 - window[callback]({  
168 - value: listData,  
169 - onChange: changeList,  
170 - schema: schema  
171 - });  
172 - };  
173 - }  
174 -  
175 - return /*#__PURE__*/React.createElement(_Button, {  
176 - key: idx.toString(),  
177 - style: {  
178 - marginLeft: 8  
179 - },  
180 - size: "small",  
181 - onClick: onClick  
182 - }, /*#__PURE__*/React.createElement("span", {  
183 - dangerouslySetInnerHTML: {  
184 - __html: html || text  
185 - }  
186 - }));  
187 - }) : null), /*#__PURE__*/React.createElement(_Table, _extends({  
188 - scroll: {  
189 - x: 'max-content'  
190 - },  
191 - columns: columns,  
192 - dataSource: dataSource,  
193 - rowKey: "index",  
194 - size: "small",  
195 - pagination: paginationConfig  
196 - }, rest)));  
197 -};  
198 -  
199 -export default TableList;  
1 -import * as React from 'react';  
2 -export interface Error {  
3 - /** 错误的数据路径 */  
4 - name: string;  
5 - /** 错误的内容 */  
6 - error: string[];  
7 -}  
8 -export interface FormParams {  
9 - formData?: any;  
10 - onChange?: (data: any) => void;  
11 - onValidate?: (valid: any) => void;  
12 - showValidate?: boolean;  
13 - /** 数据分析接口,表单展示完成渲染时触发 */  
14 - logOnMount?: (stats: any) => void;  
15 - /** 数据分析接口,表单提交成功时触发,获得本次表单填写的总时长 */  
16 - logOnSubmit?: (stats: any) => void;  
17 -}  
18 -  
19 -export interface ValidateParams {  
20 - formData: any;  
21 - schema: any;  
22 - error: Error[];  
23 - [k: string]: any;  
24 -}  
25 -export interface FormInstance {  
26 - formData: any;  
27 - schema: any;  
28 - flatten: any;  
29 - touchedKeys: string[];  
30 - touchKey: (key: string) => void;  
31 - onItemChange: (path: string, value: any) => void;  
32 - setValueByPath: (path: string, value: any) => void;  
33 - getSchemaByPath: (path: string) => object;  
34 - setSchemaByPath: (path: string, value: any) => void;  
35 - setSchema: (settings: any) => void;  
36 - setValues: (formData: any) => void;  
37 - getValues: () => any;  
38 - resetFields: () => void;  
39 - submit: () => Promise<void> | Promise<any[]>;  
40 - submitData: any;  
41 - errorFields: Error[];  
42 - isValidating: boolean;  
43 - outsideValidating: boolean;  
44 - isSubmitting: boolean;  
45 - endValidating: () => void;  
46 - endSubmitting: () => void;  
47 - setErrorFields: (error: Error[]) => void;  
48 - removeErrorField: (path: string) => void;  
49 - removeTouched: (path: string) => void;  
50 - changeTouchedKeys: (pathArray: string[]) => void;  
51 - isEditing: boolean;  
52 - setEditing: (status: boolean) => void;  
53 - syncStuff: (args: any) => void;  
54 - /** 折中升级方案中使用到,正常用不到 */  
55 - init: () => void;  
56 - /** 数据分析接口,表单展示完成渲染时触发 */  
57 - logOnMount: (args: any) => void;  
58 - /** 数据分析接口,表单提交成功时触发,获得本次表单填写的总时长 */  
59 - logOnSubmit: (args: any) => void;  
60 - _setErrors: (args: any) => void;  
61 -}  
62 -  
63 -export type WatchProperties = {  
64 - [path: string]:  
65 - | {  
66 - handler: (value: any) => void;  
67 - immediate?: boolean;  
68 - }  
69 - | ((value: any) => void);  
70 -};  
71 -  
72 -export interface FRProps {  
73 - /** 表单 id */  
74 - id?: string | number;  
75 - /** 表单顶层的className */  
76 - className?: string;  
77 - /** 表单顶层的样式 */  
78 - style?: any;  
79 - /** 表单 schema */  
80 - schema: any;  
81 - /** form单例 */  
82 - form: FormInstance;  
83 - /** 组件和schema的映射规则 */  
84 - mapping?: any;  
85 - /** 自定义组件 */  
86 - widgets?: any;  
87 - /** 表单提交前钩子 */  
88 - displayType?: string;  
89 - /** 只读模式 */  
90 - readOnly?: boolean;  
91 - /** 禁用模式 */  
92 - disabled?: boolean;  
93 - /** 标签宽度 */  
94 - labelWidth?: string | number;  
95 - /** antd的全局config */  
96 - configProvider?: any;  
97 - theme?: string | number;  
98 - /** 覆盖默认的校验信息 */  
99 - validateMessages?: any;  
100 - /** 显示当前表单内部状态 */  
101 - debug?: boolean;  
102 - /** 显示css布局提示线 */  
103 - debugCss?: boolean;  
104 - locale?: string;  
105 - column?: number;  
106 - debounceInput?: boolean;  
107 - size?: string;  
108 - // 数据会作为 beforeFinish 的第四个参数传入  
109 - config?: any;  
110 - // 类似于 vuejs 的 watch 的用法,监控值的变化,触发 callback  
111 - watch?: WatchProperties;  
112 - /** 对象组件是否折叠(全局的控制) */  
113 - allCollapsed?: boolean;  
114 - /** 表单的全局共享属性 */  
115 - globalProps?: any;  
116 - /** 表单首次加载钩子 */  
117 - onMount?: () => void;  
118 - /** 表单提交前钩子 */  
119 - beforeFinish?: (params: ValidateParams) => Error[] | Promise<Error[]>;  
120 - /** 表单提交后钩子 */  
121 - onFinish?: (formData: any, error: Error[]) => void;  
122 - /** 时时与外部更新同步的钩子 */  
123 - onValuesChange?: (changedValues: any, formData: any) => void;  
124 - /** 隐藏的数据是否去掉,默认不去掉(false) */  
125 - removeHiddenData?: boolean;  
126 -}  
127 -  
128 -declare const FR: React.FC<FRProps>;  
129 -  
130 -export declare function useForm(params?: FormParams): FormInstance;  
131 -  
132 -export type ConnectedForm<T> = T & {  
133 - form: FormInstance;  
134 -};  
135 -  
136 -export declare function connectForm<T extends {} = any>(  
137 - component: React.ComponentType<ConnectedForm<T>>  
138 -): React.ComponentType<T>;  
139 -  
140 -export default FR;  
1 -var _excluded = ["id", "widgets", "mapping", "form", "className", "style", "beforeFinish", "onFinish", "displayType", "schema", "debug", "debugCss", "locale", "debounceInput", "size", "configProvider", "theme", "validateMessages", "watch", "config", "onMount", "labelWidth", "readOnly", "disabled", "allCollapsed", "onValuesChange", "column", "removeHiddenData", "globalProps"],  
2 - _excluded2 = ["onItemChange", "setEditing", "touchKey", "setValueByPath", "getSchemaByPath", "setSchemaByPath", "setSchema", "setValues", "getValues", "resetFields", "submit", "endValidating", "endSubmitting", "setErrorFields", "removeErrorField", "removeTouched", "changeTouchedKeys", "syncStuff", "logOnMount", "logOnSubmit", "setFirstMount", "_setErrors"],  
3 - _excluded3 = ["isOldVersion", "schema"];  
4 -  
5 -function _extends() { _extends = Object.assign || 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); }  
6 -  
7 -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }  
8 -  
9 -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }  
10 -  
11 -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }  
12 -  
13 -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }  
14 -  
15 -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; }  
16 -  
17 -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; }  
18 -  
19 -/* eslint-disable react-hooks/exhaustive-deps */  
20 -import React, { useEffect, useMemo, useRef } from 'react';  
21 -import { updateSchemaToNewVersion, msToTime, yymmdd, getParamByName } from './utils';  
22 -import Core from './core';  
23 -import Watcher from './Watcher';  
24 -import { Ctx, StoreCtx, Store2Ctx } from './hooks';  
25 -import "./atom.css";  
26 -import "./index.css";  
27 -import { mapping as defaultMapping } from './mapping';  
28 -  
29 -var defaultFinish = function defaultFinish(data, errors) {  
30 - console.log('onFinish:', {  
31 - data: data,  
32 - errors: errors  
33 - });  
34 -};  
35 -  
36 -export { default as useForm } from './useForm';  
37 -export { defaultMapping as mapping };  
38 -export { default as connectForm } from './connectForm';  
39 -  
40 -function App(_ref) {  
41 - var id = _ref.id,  
42 - widgets = _ref.widgets,  
43 - mapping = _ref.mapping,  
44 - form = _ref.form,  
45 - className = _ref.className,  
46 - style = _ref.style,  
47 - beforeFinish = _ref.beforeFinish,  
48 - _ref$onFinish = _ref.onFinish,  
49 - onFinish = _ref$onFinish === void 0 ? defaultFinish : _ref$onFinish,  
50 - _ref$displayType = _ref.displayType,  
51 - displayType = _ref$displayType === void 0 ? 'column' : _ref$displayType,  
52 - schema = _ref.schema,  
53 - debug = _ref.debug,  
54 - debugCss = _ref.debugCss,  
55 - _ref$locale = _ref.locale,  
56 - locale = _ref$locale === void 0 ? 'cn' : _ref$locale,  
57 - _ref$debounceInput = _ref.debounceInput,  
58 - debounceInput = _ref$debounceInput === void 0 ? false : _ref$debounceInput,  
59 - size = _ref.size,  
60 - configProvider = _ref.configProvider,  
61 - theme = _ref.theme,  
62 - validateMessages = _ref.validateMessages,  
63 - _ref$watch = _ref.watch,  
64 - watch = _ref$watch === void 0 ? {} : _ref$watch,  
65 - config = _ref.config,  
66 - onMount = _ref.onMount,  
67 - labelWidth = _ref.labelWidth,  
68 - readOnly = _ref.readOnly,  
69 - disabled = _ref.disabled,  
70 - _ref$allCollapsed = _ref.allCollapsed,  
71 - allCollapsed = _ref$allCollapsed === void 0 ? false : _ref$allCollapsed,  
72 - onValuesChange = _ref.onValuesChange,  
73 - column = _ref.column,  
74 - _ref$removeHiddenData = _ref.removeHiddenData,  
75 - removeHiddenData = _ref$removeHiddenData === void 0 ? false : _ref$removeHiddenData,  
76 - _ref$globalProps = _ref.globalProps,  
77 - globalProps = _ref$globalProps === void 0 ? {} : _ref$globalProps,  
78 - rest = _objectWithoutProperties(_ref, _excluded);  
79 -  
80 - try {  
81 - var _ = form.submit;  
82 - } catch (error) {  
83 - console.error('form 为必填 props,<FormRender /> 没有接收到 form 属性!');  
84 - }  
85 -  
86 - var _column = schema && schema.column || column;  
87 -  
88 - var onItemChange = form.onItemChange,  
89 - setEditing = form.setEditing,  
90 - touchKey = form.touchKey,  
91 - setValueByPath = form.setValueByPath,  
92 - getSchemaByPath = form.getSchemaByPath,  
93 - setSchemaByPath = form.setSchemaByPath,  
94 - setSchema = form.setSchema,  
95 - setValues = form.setValues,  
96 - getValues = form.getValues,  
97 - resetFields = form.resetFields,  
98 - submit = form.submit,  
99 - endValidating = form.endValidating,  
100 - endSubmitting = form.endSubmitting,  
101 - setErrorFields = form.setErrorFields,  
102 - removeErrorField = form.removeErrorField,  
103 - removeTouched = form.removeTouched,  
104 - changeTouchedKeys = form.changeTouchedKeys,  
105 - syncStuff = form.syncStuff,  
106 - logOnMount = form.logOnMount,  
107 - logOnSubmit = form.logOnSubmit,  
108 - setFirstMount = form.setFirstMount,  
109 - _setErrors = form._setErrors,  
110 - valuesThatWillChange = _objectWithoutProperties(form, _excluded2);  
111 -  
112 - var submitData = valuesThatWillChange.submitData,  
113 - errorFields = valuesThatWillChange.errorFields,  
114 - isValidating = valuesThatWillChange.isValidating,  
115 - outsideValidating = valuesThatWillChange.outsideValidating,  
116 - isSubmitting = valuesThatWillChange.isSubmitting,  
117 - formData = valuesThatWillChange.formData,  
118 - flatten = valuesThatWillChange.flatten,  
119 - showValidate = valuesThatWillChange.showValidate,  
120 - firstMount = valuesThatWillChange.firstMount;  
121 - useEffect(function () {  
122 - // Schema最外层的type是object来判断,没有的话,认为schema没有传  
123 - if (schema && schema.type) {  
124 - setFirstMount(true);  
125 - syncStuff({  
126 - schema: schema,  
127 - locale: locale,  
128 - validateMessages: validateMessages,  
129 - beforeFinish: beforeFinish,  
130 - onMount: onMount,  
131 - removeHiddenData: removeHiddenData  
132 - });  
133 - } else {}  
134 - }, [JSON.stringify(schema)]);  
135 - useEffect(function () {  
136 - if (!firstMount && schema && schema.type) {  
137 - if (typeof onMount === 'function') {  
138 - // 等一下 useForm 里接到第一份schema时,计算第一份data的骨架  
139 - setTimeout(function () {  
140 - onMount();  
141 - }, 0);  
142 - }  
143 -  
144 - setTimeout(onMountLogger, 0);  
145 - }  
146 - }, [JSON.stringify(schema), firstMount]);  
147 -  
148 - var onMountLogger = function onMountLogger() {  
149 - var start = new Date().getTime();  
150 -  
151 - if (typeof logOnMount === 'function' || typeof logOnSubmit === 'function') {  
152 - sessionStorage.setItem('FORM_MOUNT_TIME', start);  
153 - sessionStorage.setItem('FORM_START', start);  
154 - }  
155 -  
156 - if (typeof logOnMount === 'function') {  
157 - var logParams = {  
158 - schema: schema,  
159 - url: location.href,  
160 - formData: JSON.stringify(form.getValues()),  
161 - formMount: yymmdd(start)  
162 - };  
163 -  
164 - if (id) {  
165 - logParams.id = id;  
166 - }  
167 -  
168 - logOnMount(logParams);  
169 - } // 如果是要计算时间,在 onMount 时存一个时间戳  
170 -  
171 -  
172 - if (typeof logOnSubmit === 'function') {  
173 - sessionStorage.setItem('NUMBER_OF_SUBMITS', 0);  
174 - sessionStorage.setItem('FAILED_ATTEMPTS', 0);  
175 - }  
176 - }; // 组件destroy的时候,destroy form,因为useForm可能在上层,所以不一定会跟着destroy  
177 -  
178 -  
179 - useEffect(function () {  
180 - return function () {  
181 - form.resetFields();  
182 - };  
183 - }, []);  
184 - var store = useMemo(function () {  
185 - return _objectSpread(_objectSpread({}, valuesThatWillChange), {}, {  
186 - globalProps: globalProps  
187 - }, rest);  
188 - }, [JSON.stringify(flatten), JSON.stringify(formData), JSON.stringify(errorFields), JSON.stringify(globalProps)]); // 不常用的context单独放一个地方  
189 -  
190 - var store2 = useMemo(function () {  
191 - return {  
192 - displayType: displayType,  
193 - theme: theme,  
194 - column: _column,  
195 - debounceInput: debounceInput,  
196 - debug: debug,  
197 - labelWidth: labelWidth,  
198 - locale: locale,  
199 - validateMessages: validateMessages,  
200 - readOnly: readOnly,  
201 - disabled: disabled,  
202 - allCollapsed: allCollapsed,  
203 - showValidate: showValidate  
204 - };  
205 - }, [displayType, theme, _column, debounceInput, debug, labelWidth, locale, validateMessages, readOnly, disabled, allCollapsed, showValidate]);  
206 - var tools = useMemo(function () {  
207 - return _objectSpread({  
208 - widgets: widgets,  
209 - mapping: _objectSpread(_objectSpread({}, defaultMapping), mapping),  
210 - onValuesChange: onValuesChange  
211 - }, form);  
212 - }, []);  
213 - useEffect(function () {  
214 - // 需要外部校验的情况,此时 submitting 还是 false  
215 - if (outsideValidating === true) {  
216 - Promise.resolve(beforeFinish(_objectSpread({  
217 - data: submitData,  
218 - schema: schema,  
219 - errors: errorFields  
220 - }, config))).then(function (error) {  
221 - if (error) {  
222 - setErrorFields(error);  
223 - }  
224 -  
225 - endValidating();  
226 - });  
227 - return;  
228 - } // 如果validation结束,submitting开始  
229 -  
230 -  
231 - if (isValidating === false && isSubmitting === true) {  
232 - endSubmitting();  
233 - onFinish(submitData, errorFields);  
234 -  
235 - if (typeof logOnSubmit === 'function') {  
236 - var start = sessionStorage.getItem('FORM_START');  
237 - var mount = sessionStorage.getItem('FORM_MOUNT_TIME');  
238 - var numberOfSubmits = Number(sessionStorage.getItem('NUMBER_OF_SUBMITS')) + 1;  
239 - var end = new Date().getTime();  
240 - var failedAttempts = Number(sessionStorage.getItem('FAILED_ATTEMPTS'));  
241 -  
242 - if (errorFields.length > 0) {  
243 - failedAttempts = failedAttempts + 1;  
244 - }  
245 -  
246 - var logParams = {  
247 - formMount: yymmdd(mount),  
248 - ms: end - start,  
249 - duration: msToTime(end - start),  
250 - numberOfSubmits: numberOfSubmits,  
251 - failedAttempts: failedAttempts,  
252 - url: location.href,  
253 - formData: JSON.stringify(submitData),  
254 - errors: JSON.stringify(errorFields),  
255 - schema: JSON.stringify(schema)  
256 - };  
257 -  
258 - if (id) {  
259 - logParams.id = id;  
260 - }  
261 -  
262 - logOnSubmit(logParams);  
263 - sessionStorage.setItem('FORM_START', end);  
264 - sessionStorage.setItem('NUMBER_OF_SUBMITS', numberOfSubmits);  
265 - sessionStorage.setItem('FAILED_ATTEMPTS', failedAttempts);  
266 - }  
267 - }  
268 - }, [isValidating, isSubmitting, outsideValidating]); // TODO: fk doesn't work  
269 -  
270 - var sizeCls = '';  
271 -  
272 - if (size === 'small') {  
273 - sizeCls = 'fr-form-small';  
274 - } else if (size === 'large') {  
275 - sizeCls = 'fr-form-large';  
276 - }  
277 -  
278 - var rootProps = {  
279 - className: "fr-container ".concat(sizeCls, " ").concat(className || '')  
280 - };  
281 -  
282 - if (style && _typeof(style) === 'object') {  
283 - rootProps.style = style;  
284 - }  
285 -  
286 - if (id && ['number', 'string'].indexOf(_typeof(id)) > -1) {  
287 - rootProps.id = id;  
288 - }  
289 -  
290 - var debugForm = getParamByName('_debug_form');  
291 - var debugFormCss = getParamByName('_debug_form_css');  
292 - var isPre = location.href.indexOf('pre') > -1;  
293 - var watchList = Object.keys(watch);  
294 - return /*#__PURE__*/React.createElement(StoreCtx.Provider, {  
295 - value: store  
296 - }, /*#__PURE__*/React.createElement(Store2Ctx.Provider, {  
297 - value: store2  
298 - }, /*#__PURE__*/React.createElement(Ctx.Provider, {  
299 - value: tools  
300 - }, /*#__PURE__*/React.createElement("div", rootProps, isPre && debugForm || debug ? /*#__PURE__*/React.createElement("div", {  
301 - className: "mv2 bg-black-05 pa2 br2"  
302 - }, /*#__PURE__*/React.createElement("div", {  
303 - style: {  
304 - display: 'flex'  
305 - }  
306 - }, /*#__PURE__*/React.createElement("span", null, "formData:"), /*#__PURE__*/React.createElement("span", {  
307 - style: {  
308 - display: 'inline-block',  
309 - wordBreak: 'break-all',  
310 - maxWidth: 600  
311 - }  
312 - }, JSON.stringify(form.formData))), /*#__PURE__*/React.createElement("div", null, 'errorFields:' + JSON.stringify(form.errorFields)), /*#__PURE__*/React.createElement("div", null, 'touchedKeys:' + JSON.stringify(form.touchedKeys)), /*#__PURE__*/React.createElement("div", null, 'allTouched:' + JSON.stringify(form.allTouched)), /*#__PURE__*/React.createElement("div", null, 'descriptor:' + JSON.stringify(window.descriptor))) : null, watchList.length > 0 ? watchList.map(function (item, idx) {  
313 - return /*#__PURE__*/React.createElement(Watcher, {  
314 - key: idx.toString(),  
315 - watchKey: item,  
316 - watch: watch,  
317 - formData: formData,  
318 - firstMount: firstMount  
319 - });  
320 - }) : null, /*#__PURE__*/React.createElement(Core, {  
321 - debugCss: isPre && debugFormCss || debugCss  
322 - })))));  
323 -}  
324 -  
325 -export { createWidget } from './createWidget';  
326 -  
327 -var Wrapper = function Wrapper(props) {  
328 - var _ref2 = props || {},  
329 - _ref2$isOldVersion = _ref2.isOldVersion,  
330 - isOldVersion = _ref2$isOldVersion === void 0 ? true : _ref2$isOldVersion,  
331 - schema = _ref2.schema,  
332 - rest = _objectWithoutProperties(_ref2, _excluded3);  
333 -  
334 - var _schema = useRef(schema);  
335 -  
336 - if (isOldVersion) {  
337 - _schema.current = updateSchemaToNewVersion(schema);  
338 - }  
339 -  
340 - return /*#__PURE__*/React.createElement(App, _extends({  
341 - schema: _schema.current  
342 - }, rest));  
343 -};  
344 -  
345 -export default Wrapper;  
1 -export var mapping = {  
2 - default: 'input',  
3 - string: 'input',  
4 - array: 'list',  
5 - boolean: 'checkbox',  
6 - integer: 'number',  
7 - number: 'number',  
8 - object: 'map',  
9 - html: 'html',  
10 - 'string:upload': 'upload',  
11 - 'string:url': 'url',  
12 - 'string:dateTime': 'date',  
13 - 'string:date': 'date',  
14 - 'string:year': 'date',  
15 - 'string:month': 'date',  
16 - 'string:week': 'date',  
17 - 'string:quarter': 'date',  
18 - 'string:time': 'time',  
19 - 'string:textarea': 'textarea',  
20 - 'string:color': 'color',  
21 - 'string:image': 'imageInput',  
22 - 'range:time': 'timeRange',  
23 - 'range:dateTime': 'dateRange',  
24 - 'range:date': 'dateRange',  
25 - 'range:year': 'dateRange',  
26 - 'range:month': 'dateRange',  
27 - 'range:week': 'dateRange',  
28 - 'range:quarter': 'dateRange',  
29 - '*?enum': 'radio',  
30 - '*?enum_long': 'select',  
31 - 'array?enum': 'checkboxes',  
32 - 'array?enum_long': 'multiSelect',  
33 - '*?readOnly': 'html' // TODO: html widgets for list / object  
34 -  
35 -};  
36 -export function getWidgetName(schema) {  
37 - var _mapping = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : mapping;  
38 -  
39 - var type = schema.type,  
40 - format = schema.format,  
41 - enums = schema.enum,  
42 - readOnly = schema.readOnly,  
43 - widget = schema.widget; // 如果已经注明了渲染widget,那最好  
44 - // if (schema['ui:widget']) {  
45 - // return schema['ui:widget'];  
46 - // }  
47 -  
48 - var list = [];  
49 -  
50 - if (readOnly) {  
51 - list.push("".concat(type, "?readOnly"));  
52 - list.push('*?readOnly');  
53 - }  
54 -  
55 - if (enums) {  
56 - // 根据enum长度来智能选择控件  
57 - if (Array.isArray(enums) && (type === 'array' && enums.length > 6 || type !== 'array' && enums.length > 2)) {  
58 - list.push("".concat(type, "?enum_long"));  
59 - list.push('*?enum_long');  
60 - } else {  
61 - list.push("".concat(type, "?enum")); // array 默认使用list,array?enum 默认使用checkboxes,*?enum 默认使用select  
62 -  
63 - list.push('*?enum');  
64 - }  
65 - }  
66 -  
67 - var _widget = widget || format;  
68 -  
69 - if (_widget) {  
70 - list.push("".concat(type, ":").concat(_widget));  
71 - }  
72 -  
73 - list.push(type); // 放在最后兜底,其他都不match时使用type默认的组件  
74 -  
75 - var found = '';  
76 - list.some(function (item) {  
77 - found = _mapping[item];  
78 - return !!found;  
79 - });  
80 - return found;  
81 -}  
82 -export var extraSchemaList = {  
83 - checkbox: {  
84 - valuePropName: 'checked'  
85 - },  
86 - switch: {  
87 - valuePropName: 'checked'  
88 - }  
89 -};  
1 -var _excluded = ["propsSchema"],  
2 - _excluded2 = ["schema"];  
3 -  
4 -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }  
5 -  
6 -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }  
7 -  
8 -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }  
9 -  
10 -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }  
11 -  
12 -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; }  
13 -  
14 -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; }  
15 -  
16 -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }  
17 -  
18 -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }  
19 -  
20 -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }  
21 -  
22 -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }  
23 -  
24 -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }  
25 -  
26 -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."); }  
27 -  
28 -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); }  
29 -  
30 -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; }  
31 -  
32 -function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }  
33 -  
34 -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }  
35 -  
36 -import { get, set, cloneDeep } from 'lodash-es'; // window.log1 = value => {  
37 -// console.log('%ccommon:', 'color: #00A7F7; font-weight: 500;', value);  
38 -// };  
39 -// window.log2 = value => {  
40 -// console.log('%cwarning:', 'color: #f50; font-weight: 500;', value);  
41 -// };  
42 -// window.log3 = value => {  
43 -// console.log('%csuccess:', 'color: #87d068; font-weight: 500;', value);  
44 -// };  
45 -// window.log4 = value => {  
46 -// console.log('%cspecial:', 'color: #722ed1; font-weight: 500;', value);  
47 -// };  
48 -  
49 -export function getParamByName(name) {  
50 - var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location.href;  
51 - name = name.replace(/[\[\]]/g, '\\$&');  
52 - var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),  
53 - results = regex.exec(url);  
54 - if (!results) return null;  
55 - if (!results[2]) return '';  
56 - return decodeURIComponent(results[2].replace(/\+/g, ' '));  
57 -}  
58 -export function isUrl(string) {  
59 - var protocolRE = /^(?:\w+:)?\/\/(\S+)$/; // const domainRE = /^[^\s\.]+\.\S{2,}$/;  
60 -  
61 - if (typeof string !== 'string') return false;  
62 - return protocolRE.test(string);  
63 -}  
64 -export function isCheckBoxType(schema, readOnly) {  
65 - if (readOnly) return false;  
66 - if (schema.widget === 'checkbox') return true;  
67 -  
68 - if (schema && schema.type === 'boolean') {  
69 - if (schema.enum) return false;  
70 - if (schema.widget === undefined) return true;  
71 - return false;  
72 - }  
73 -} // a[].b.c => a.b.c  
74 -  
75 -function removeBrackets(string) {  
76 - if (typeof string === 'string') {  
77 - return string.replace(/\[\]/g, '');  
78 - } else {  
79 - return string;  
80 - }  
81 -}  
82 -  
83 -export function getParentPath(path) {  
84 - if (typeof path === 'string') {  
85 - var pathArr = path.split('.');  
86 -  
87 - if (pathArr.length === 1) {  
88 - return '#';  
89 - }  
90 -  
91 - pathArr.pop();  
92 - return pathArr.join('.');  
93 - }  
94 -  
95 - return '#';  
96 -}  
97 -export function getValueByPath(formData, path) {  
98 - if (path === '#' || !path) {  
99 - return formData || {};  
100 - } else if (typeof path === 'string') {  
101 - return get(formData, path);  
102 - } else {  
103 - console.error('path has to be a string');  
104 - }  
105 -} // path: 'a.b[1].c[0]' => { id: 'a.b[].c[]' dataIndex: [1,0] }  
106 -  
107 -export function destructDataPath(path) {  
108 - var id;  
109 - var dataIndex;  
110 -  
111 - if (path === '#') {  
112 - return {  
113 - id: '#',  
114 - dataIndex: []  
115 - };  
116 - }  
117 -  
118 - if (typeof path !== 'string') {  
119 - throw Error("path ".concat(path, " is not a string!!! Something wrong here"));  
120 - }  
121 -  
122 - var pattern = /\[[0-9]+\]/g;  
123 - var matchList = path.match(pattern);  
124 -  
125 - if (!matchList) {  
126 - id = path;  
127 - } else {  
128 - id = path.replace(pattern, '[]'); // 这个是match下来的结果,可安全处理  
129 -  
130 - dataIndex = matchList.map(function (item) {  
131 - return Number(item.substring(1, item.length - 1));  
132 - });  
133 - }  
134 -  
135 - return {  
136 - id: id,  
137 - dataIndex: dataIndex  
138 - };  
139 -} // id: 'a.b[].c[]' dataIndex: [1,0] => 'a.b[1].c[0]'  
140 -  
141 -export function getDataPath(id, dataIndex) {  
142 - if (id === '#') {  
143 - return id;  
144 - }  
145 -  
146 - if (typeof id !== 'string') {  
147 - throw Error("id ".concat(id, " is not a string!!! Something wrong here"));  
148 - }  
149 -  
150 - var _id = id;  
151 -  
152 - if (Array.isArray(dataIndex)) {  
153 - // const matches = id.match(/\[\]/g) || [];  
154 - // const count = matches.length;  
155 - dataIndex.forEach(function (item) {  
156 - _id = _id.replace(/\[\]/, "[".concat(item, "]"));  
157 - });  
158 - }  
159 -  
160 - return removeBrackets(_id);  
161 -}  
162 -export function isObjType(schema) {  
163 - return schema && schema.type === 'object' && schema.properties && !schema.widget;  
164 -} // TODO: to support case that item is not an object  
165 -  
166 -export function isListType(schema) {  
167 - return schema && schema.type === 'array' && isObjType(schema.items) && schema.enum === undefined;  
168 -} // TODO: more tests to make sure weird & wrong schema won't crush  
169 -  
170 -export function flattenSchema() {  
171 - var _schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};  
172 -  
173 - var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '#';  
174 - var parent = arguments.length > 2 ? arguments[2] : undefined;  
175 - var result = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};  
176 - var schema = clone(_schema);  
177 - var _name = name;  
178 -  
179 - if (!schema.$id) {  
180 - schema.$id = _name; // path as $id, for easy access to path in schema  
181 - }  
182 -  
183 - var children = [];  
184 -  
185 - if (isObjType(schema)) {  
186 - Object.entries(schema.properties).forEach(function (_ref) {  
187 - var _ref2 = _slicedToArray(_ref, 2),  
188 - key = _ref2[0],  
189 - value = _ref2[1];  
190 -  
191 - var _key = isListType(value) ? key + '[]' : key;  
192 -  
193 - var uniqueName = _name === '#' ? _key : _name + '.' + _key;  
194 - children.push(uniqueName);  
195 - flattenSchema(value, uniqueName, _name, result);  
196 - });  
197 - schema.properties = {};  
198 - }  
199 -  
200 - if (isListType(schema)) {  
201 - Object.entries(schema.items.properties).forEach(function (_ref3) {  
202 - var _ref4 = _slicedToArray(_ref3, 2),  
203 - key = _ref4[0],  
204 - value = _ref4[1];  
205 -  
206 - var _key = isListType(value) ? key + '[]' : key;  
207 -  
208 - var uniqueName = _name === '#' ? _key : _name + '.' + _key;  
209 - children.push(uniqueName);  
210 - flattenSchema(value, uniqueName, _name, result);  
211 - });  
212 - schema.items.properties = {};  
213 - }  
214 -  
215 - if (schema.type) {  
216 - result[_name] = {  
217 - parent: parent,  
218 - schema: schema,  
219 - children: children  
220 - };  
221 - }  
222 -  
223 - return result;  
224 -}  
225 -export function getSchemaFromFlatten(flatten) {  
226 - var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '#';  
227 - var schema = {};  
228 - var item = clone(flatten[path]);  
229 -  
230 - if (item) {  
231 - schema = item.schema; // schema.$id && delete schema.$id;  
232 -  
233 - if (item.children.length > 0) {  
234 - item.children.forEach(function (child) {  
235 - if (!flatten[child]) return;  
236 - var key = getKeyFromPath(child);  
237 -  
238 - if (isObjType(schema)) {  
239 - schema.properties[key] = getSchemaFromFlatten(flatten, child);  
240 - }  
241 -  
242 - if (isListType(schema)) {  
243 - schema.items.properties[key] = getSchemaFromFlatten(flatten, child);  
244 - }  
245 - });  
246 - }  
247 - }  
248 -  
249 - return schema;  
250 -}  
251 -  
252 -function stringContains(str, text) {  
253 - return str.indexOf(text) > -1;  
254 -}  
255 -  
256 -export var isObject = function isObject(a) {  
257 - return stringContains(Object.prototype.toString.call(a), 'Object');  
258 -};  
259 -export var clone = cloneDeep; // '3' => true, 3 => true, undefined => false  
260 -  
261 -export function isLooselyNumber(num) {  
262 - if (typeof num === 'number') return true;  
263 -  
264 - if (typeof num === 'string') {  
265 - return !Number.isNaN(Number(num));  
266 - }  
267 -  
268 - return false;  
269 -}  
270 -export function isCssLength(str) {  
271 - if (typeof str !== 'string') return false;  
272 - return str.match(/^([0-9])*(%|px|rem|em)$/i);  
273 -}  
274 -export function isDeepEqual(param1, param2) {  
275 - if (param1 === undefined && param2 === undefined) return true;else if (param1 === undefined || param2 === undefined) return false;  
276 - if (param1 === null && param2 === null) return true;else if (param1 === null || param2 === null) return false;else if (param1.constructor !== param2.constructor) return false;  
277 -  
278 - if (param1.constructor === Array) {  
279 - if (param1.length !== param2.length) return false;  
280 -  
281 - for (var i = 0; i < param1.length; i++) {  
282 - if (param1[i].constructor === Array || param1[i].constructor === Object) {  
283 - if (!isDeepEqual(param1[i], param2[i])) return false;  
284 - } else if (param1[i] !== param2[i]) return false;  
285 - }  
286 - } else if (param1.constructor === Object) {  
287 - if (Object.keys(param1).length !== Object.keys(param2).length) return false;  
288 -  
289 - for (var _i2 = 0; _i2 < Object.keys(param1).length; _i2++) {  
290 - var key = Object.keys(param1)[_i2];  
291 -  
292 - if (param1[key] && typeof param1[key] !== 'number' && (param1[key].constructor === Array || param1[key].constructor === Object)) {  
293 - if (!isDeepEqual(param1[key], param2[key])) return false;  
294 - } else if (param1[key] !== param2[key]) return false;  
295 - }  
296 - } else if (param1.constructor === String || param1.constructor === Number) {  
297 - return param1 === param2;  
298 - }  
299 -  
300 - return true;  
301 -}  
302 -export function getFormat(format) {  
303 - var dateFormat;  
304 -  
305 - switch (format) {  
306 - case 'date':  
307 - dateFormat = 'YYYY-MM-DD';  
308 - break;  
309 -  
310 - case 'time':  
311 - dateFormat = 'HH:mm:ss';  
312 - break;  
313 -  
314 - case 'dateTime':  
315 - dateFormat = 'YYYY-MM-DD HH:mm:ss';  
316 - break;  
317 -  
318 - case 'week':  
319 - dateFormat = 'YYYY-w';  
320 - break;  
321 -  
322 - case 'year':  
323 - dateFormat = 'YYYY';  
324 - break;  
325 -  
326 - case 'quarter':  
327 - dateFormat = 'YYYY-Q';  
328 - break;  
329 -  
330 - case 'month':  
331 - dateFormat = 'YYYY-MM';  
332 - break;  
333 -  
334 - default:  
335 - // dateTime  
336 - if (typeof format === 'string') {  
337 - dateFormat = format;  
338 - } else {  
339 - dateFormat = 'YYYY-MM-DD';  
340 - }  
341 -  
342 - }  
343 -  
344 - return dateFormat;  
345 -}  
346 -export function hasRepeat(list) {  
347 - return list.find(function (x, i, self) {  
348 - return i !== self.findIndex(function (y) {  
349 - return JSON.stringify(x) === JSON.stringify(y);  
350 - });  
351 - });  
352 -}  
353 -export function combineSchema() {  
354 - var propsSchema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};  
355 - var uiSchema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};  
356 - var propList = getChildren(propsSchema);  
357 - var newList = propList.map(function (p) {  
358 - var name = p.name;  
359 - var _p$schema = p.schema,  
360 - type = _p$schema.type,  
361 - options = _p$schema.enum,  
362 - properties = _p$schema.properties,  
363 - items = _p$schema.items;  
364 - var isObj = type === 'object' && properties;  
365 - var isArr = type === 'array' && items && !options; // enum + array 代表的多选框,没有sub  
366 -  
367 - var ui = name && uiSchema[p.name];  
368 -  
369 - if (!ui) {  
370 - return p;  
371 - } // 如果是list,递归合并items  
372 -  
373 -  
374 - if (isArr) {  
375 - var newItems = combineSchema(items, ui.items || {});  
376 - return _objectSpread(_objectSpread({}, p), {}, {  
377 - schema: _objectSpread(_objectSpread(_objectSpread({}, p.schema), ui), {}, {  
378 - items: newItems  
379 - })  
380 - });  
381 - } // object递归合并整个schema  
382 -  
383 -  
384 - if (isObj) {  
385 - var newSchema = combineSchema(p.schema, ui);  
386 - return _objectSpread(_objectSpread({}, p), {}, {  
387 - schema: newSchema  
388 - });  
389 - }  
390 -  
391 - return _objectSpread(_objectSpread({}, p), {}, {  
392 - schema: _objectSpread(_objectSpread({}, p.schema), ui)  
393 - });  
394 - });  
395 - var newObj = {};  
396 - newList.forEach(function (s) {  
397 - newObj[s.name] = s.schema;  
398 - });  
399 - var topLevelUi = {};  
400 - Object.keys(uiSchema).forEach(function (key) {  
401 - if (typeof key === 'string' && key.substring(0, 3) === 'ui:') {  
402 - topLevelUi[key] = uiSchema[key];  
403 - }  
404 - });  
405 -  
406 - if (isEmpty(newObj)) {  
407 - return _objectSpread(_objectSpread({}, propsSchema), topLevelUi);  
408 - }  
409 -  
410 - return _objectSpread(_objectSpread(_objectSpread({}, propsSchema), topLevelUi), {}, {  
411 - properties: newObj  
412 - });  
413 -}  
414 -  
415 -function isEmpty(obj) {  
416 - return Object.keys(obj).length === 0;  
417 -}  
418 -  
419 -function getChildren(schema) {  
420 - if (!schema) return [];  
421 - var properties = schema.properties,  
422 - items = schema.items,  
423 - type = schema.type;  
424 -  
425 - if (!properties && !items) {  
426 - return [];  
427 - }  
428 -  
429 - var schemaSubs = {};  
430 -  
431 - if (type === 'object') {  
432 - schemaSubs = properties;  
433 - }  
434 -  
435 - if (type === 'array') {  
436 - schemaSubs = items;  
437 - }  
438 -  
439 - return Object.keys(schemaSubs).map(function (name) {  
440 - return {  
441 - schema: schemaSubs[name],  
442 - name: name  
443 - };  
444 - });  
445 -}  
446 -  
447 -export var parseString = function parseString(string) {  
448 - return Function('"use strict";return (' + string + ')')();  
449 -};  
450 -export var evaluateString = function evaluateString(string, formData, rootValue) {  
451 - return Function("\"use strict\";\n const rootValue = ".concat(JSON.stringify(rootValue), ";\n const formData = ").concat(JSON.stringify(formData), ";\n return (").concat(string, ")"))();  
452 -};  
453 -export function isExpression(func) {  
454 - // if (typeof func === 'function') {  
455 - // const funcString = func.toString();  
456 - // return (  
457 - // funcString.indexOf('formData') > -1 ||  
458 - // funcString.indexOf('rootValue') > -1  
459 - // );  
460 - // }  
461 - if (typeof func !== 'string') return false;  
462 - var pattern = /^{{(.+)}}$/;  
463 - var reg1 = /^{{function\(.+}}$/; // const reg2 = /^{{(.+=>.+)}}$/;  
464 -  
465 - if (typeof func === 'string' && func.match(pattern) && !func.match(reg1)) {  
466 - return true;  
467 - }  
468 -  
469 - return false;  
470 -}  
471 -export var parseRootValueInSchema = function parseRootValueInSchema(schema, rootValue) {  
472 - var result = clone(schema);  
473 -  
474 - if (isObject(schema)) {  
475 - Object.keys(schema).forEach(function (key) {  
476 - var item = schema[key];  
477 -  
478 - if (isObject(item)) {  
479 - result[key] = parseRootValueInSchema(item, rootValue);  
480 - } else if (typeof item === 'string') {  
481 - result[key] = parseSingleRootValue(item, rootValue);  
482 - }  
483 - });  
484 - } else {  
485 - console.error('schema is not an object:', schema);  
486 - }  
487 -  
488 - return result;  
489 -}; // handle rootValue inside List  
490 -  
491 -export var parseSingleRootValue = function parseSingleRootValue(expression) {  
492 - var rootValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};  
493 -  
494 - if (typeof expression === 'string' && expression.indexOf('rootValue') > 0) {  
495 - var funcBody = expression.substring(2, expression.length - 2);  
496 - var str = "\n return ".concat(funcBody.replace(/rootValue/g, JSON.stringify(rootValue)));  
497 -  
498 - try {  
499 - return Function(str)();  
500 - } catch (error) {  
501 - console.error(error, 'expression:', expression, 'rootValue:', rootValue);  
502 - return null; // 如果计算有错误,return null 最合适  
503 - }  
504 - } else {  
505 - return expression;  
506 - }  
507 -};  
508 -export function parseSingleExpression(func) {  
509 - var formData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};  
510 - var dataPath = arguments.length > 2 ? arguments[2] : undefined;  
511 - var parentPath = getParentPath(dataPath);  
512 - var parent = getValueByPath(formData, parentPath) || {};  
513 -  
514 - if (typeof func === 'string') {  
515 - var funcBody = func.substring(2, func.length - 2);  
516 - var str = "\n return ".concat(funcBody.replace(/formData/g, JSON.stringify(formData)).replace(/rootValue/g, JSON.stringify(parent)));  
517 -  
518 - try {  
519 - return Function(str)();  
520 - } catch (error) {  
521 - console.log(error, func, dataPath);  
522 - return null; // 如果计算有错误,return null 最合适  
523 - } // const funcBody = func.substring(2, func.length - 2);  
524 - // //TODO: 这样有问题,例如 a.b.indexOf(), 会把 a.b.indexOf 当做值  
525 - // const match1 = /formData.([a-zA-Z0-9.$_\[\]]+)/g;  
526 - // const match2 = /rootValue.([a-zA-Z0-9.$_\[\]]+)/g;  
527 - // const str = `  
528 - // return (${funcBody  
529 - // .replaceAll(match1, (v, m1) =>  
530 - // JSON.stringify(getValueByPath(formData, m1))  
531 - // )  
532 - // .replaceAll(match2, (v, m1) =>  
533 - // JSON.stringify(getValueByPath(parent, m1))  
534 - // )})`;  
535 - // try {  
536 - // return Function(str)();  
537 - // } catch (error) {  
538 - // console.log(error);  
539 - // return func;  
540 - // }  
541 -  
542 - } else return func;  
543 -}  
544 -export var schemaContainsExpression = function schemaContainsExpression(schema) {  
545 - if (isObject(schema)) {  
546 - return Object.keys(schema).some(function (key) {  
547 - var value = schema[key];  
548 -  
549 - if (typeof value === 'string') {  
550 - return isExpression(value);  
551 - } else if (isObject(value)) {  
552 - return schemaContainsExpression(value);  
553 - } else {  
554 - return false;  
555 - }  
556 - });  
557 - }  
558 -  
559 - return false;  
560 -};  
561 -export var parseAllExpression = function parseAllExpression(_schema, formData, dataPath) {  
562 - var schema = clone(_schema);  
563 - Object.keys(schema).forEach(function (key) {  
564 - var value = schema[key];  
565 -  
566 - if (isObject(value)) {  
567 - schema[key] = parseAllExpression(value, formData, dataPath);  
568 - } else if (isExpression(value)) {  
569 - schema[key] = parseSingleExpression(value, formData, dataPath);  
570 - } else if (typeof key === 'string' && key.toLowerCase().indexOf('props') > -1) {  
571 - // 有可能叫 xxxProps  
572 - var propsObj = schema[key];  
573 -  
574 - if (isObject(propsObj)) {  
575 - Object.keys(propsObj).forEach(function (k) {  
576 - schema[key][k] = parseSingleExpression(propsObj[k], formData, dataPath);  
577 - });  
578 - }  
579 - }  
580 - });  
581 - return schema;  
582 -};  
583 -export function isFunctionSchema(schema) {  
584 - return Object.keys(schema).some(function (key) {  
585 - if (typeof schema[key] === 'function') {  
586 - return true;  
587 - } else if (typeof schema[key] === 'string') {  
588 - return isExpression(schema[key]);  
589 - } else if (_typeof(schema[key]) === 'object') {  
590 - return isFunctionSchema(schema[key]);  
591 - } else {  
592 - return false;  
593 - }  
594 - });  
595 -}  
596 -export var getParentProps = function getParentProps(propName, id, flatten) {  
597 - try {  
598 - var item = flatten[id];  
599 - if (item.schema[propName] !== undefined) return item.schema[propName];  
600 -  
601 - if (item && item.parent) {  
602 - var parentSchema = flatten[item.parent].schema;  
603 -  
604 - if (parentSchema[propName] !== undefined) {  
605 - return parentSchema[propName];  
606 - } else {  
607 - return getParentProps(propName, item.parent, flatten);  
608 - }  
609 - }  
610 - } catch (error) {  
611 - return undefined;  
612 - }  
613 -};  
614 -export var getSaveNumber = function getSaveNumber() {  
615 - var searchStr = localStorage.getItem('SAVES');  
616 -  
617 - if (searchStr) {  
618 - try {  
619 - var saves = JSON.parse(searchStr);  
620 - var length = saves.length;  
621 - if (length) return length + 1;  
622 - } catch (error) {  
623 - return 1;  
624 - }  
625 - } else {  
626 - return 1;  
627 - }  
628 -};  
629 -export function looseJsonParse(obj) {  
630 - return Function('"use strict";return (' + obj + ')')();  
631 -}  
632 -export var isFunctionString = function isFunctionString(fString) {  
633 - return typeof fString === 'string' && fString.indexOf('function(') === 0;  
634 -};  
635 -export function parseFunction(fString) {  
636 - if (isFunctionString(fString)) {  
637 - return Function('return ' + fString)();  
638 - }  
639 -  
640 - return fString;  
641 -} // 获得propsSchema的children  
642 -// function getChildren2(schema) {  
643 -// if (!schema) return [];  
644 -// const {  
645 -// // object  
646 -// properties,  
647 -// // array  
648 -// items,  
649 -// type,  
650 -// } = schema;  
651 -// if (!properties && !items) {  
652 -// return [];  
653 -// }  
654 -// let schemaSubs = {};  
655 -// if (type === 'object') {  
656 -// schemaSubs = properties;  
657 -// }  
658 -// if (type === 'array') {  
659 -// schemaSubs = items.properties;  
660 -// }  
661 -// return Object.keys(schemaSubs).map(name => ({  
662 -// schema: schemaSubs[name],  
663 -// name,  
664 -// }));  
665 -// }  
666 -  
667 -export var oldSchemaToNew = function oldSchemaToNew(schema) {  
668 - if (schema && schema.propsSchema) {  
669 - var propsSchema = schema.propsSchema,  
670 - rest = _objectWithoutProperties(schema, _excluded);  
671 -  
672 - return _objectSpread({  
673 - schema: propsSchema  
674 - }, rest);  
675 - }  
676 -  
677 - return schema;  
678 -};  
679 -export var newSchemaToOld = function newSchemaToOld(setting) {  
680 - if (setting && setting.schema) {  
681 - var schema = setting.schema,  
682 - rest = _objectWithoutProperties(setting, _excluded2);  
683 -  
684 - return _objectSpread({  
685 - propsSchema: schema  
686 - }, rest);  
687 - }  
688 -  
689 - return setting;  
690 -}; // from FR  
691 -  
692 -export var getEnum = function getEnum(schema) {  
693 - if (!schema) return undefined;  
694 - var itemEnum = schema && schema.items && schema.items.enum;  
695 - var schemaEnum = schema && schema.enum;  
696 - return itemEnum ? itemEnum : schemaEnum;  
697 -};  
698 -export var getArray = function getArray(arr) {  
699 - var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];  
700 - if (Array.isArray(arr)) return arr;  
701 - return defaultValue;  
702 -};  
703 -export var isEmail = function isEmail(value) {  
704 - var regex = '^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$';  
705 -  
706 - if (value && new RegExp(regex).test(value)) {  
707 - return true;  
708 - }  
709 -  
710 - return false;  
711 -};  
712 -export function defaultGetValueFromEvent(valuePropName) {  
713 - var event = arguments.length <= 1 ? undefined : arguments[1];  
714 -  
715 - if (event && event.target && valuePropName in event.target) {  
716 - return event.target[valuePropName];  
717 - }  
718 -  
719 - return event;  
720 -}  
721 -export var getKeyFromPath = function getKeyFromPath() {  
722 - var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '#';  
723 -  
724 - try {  
725 - var arr = path.split('.');  
726 - var last = arr.slice(-1)[0];  
727 - var result = last.replace('[]', '');  
728 - return result;  
729 - } catch (error) {  
730 - console.error(error, 'getKeyFromPath');  
731 - return '';  
732 - }  
733 -}; // 更多的值获取  
734 -  
735 -export var getDisplayValue = function getDisplayValue(value, schema) {  
736 - if (typeof value === 'boolean') {  
737 - return value ? 'yes' : 'no';  
738 - }  
739 -  
740 - if (isObjType(schema) || isListType(schema)) {  
741 - return '-';  
742 - }  
743 -  
744 - if (Array.isArray(schema.enum) && Array.isArray(schema.enumNames)) {  
745 - try {  
746 - return schema.enumNames[schema.enum.indexOf(value)];  
747 - } catch (error) {  
748 - return value;  
749 - }  
750 - }  
751 -  
752 - return value;  
753 -}; // 去掉数组里的空元素 {a: [null, {x:1}]} => {a: [{x:1}]}  
754 -  
755 -export var removeEmptyItemFromList = function removeEmptyItemFromList(formData) {  
756 - var result = {};  
757 -  
758 - if (isObject(formData)) {  
759 - Object.keys(formData).forEach(function (key) {  
760 - result[key] = removeEmptyItemFromList(formData[key]);  
761 - });  
762 - } else if (Array.isArray(formData)) {  
763 - result = formData.filter(function (item) {  
764 - if ([false, 0, ''].indexOf(item) > -1) return true;  
765 -  
766 - if (item && JSON.stringify(item) !== '{}') {  
767 - return true;  
768 - }  
769 -  
770 - return false;  
771 - });  
772 - } else {  
773 - result = formData;  
774 - }  
775 -  
776 - return result;  
777 -};  
778 -export var getDescriptorSimple = function getDescriptorSimple() {  
779 - var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};  
780 - var path = arguments.length > 1 ? arguments[1] : undefined;  
781 - var result = {};  
782 -  
783 - if (isObject(schema)) {  
784 - if (schema.type) {  
785 - switch (schema.type) {  
786 - case 'range':  
787 - result.type = 'array';  
788 - break;  
789 -  
790 - case 'html':  
791 - result.type = 'string';  
792 - break;  
793 -  
794 - default:  
795 - result.type = schema.type;  
796 - break;  
797 - }  
798 - }  
799 -  
800 - ['pattern', 'min', 'max', 'len', 'required'].forEach(function (key) {  
801 - if (Object.keys(schema).indexOf(key) > -1) {  
802 - result[key] = schema[key];  
803 - }  
804 - });  
805 -  
806 - switch (schema.format) {  
807 - case 'email':  
808 - case 'url':  
809 - result.type = schema.format;  
810 - break;  
811 -  
812 - default:  
813 - break;  
814 - }  
815 -  
816 - var handleRegx = function handleRegx(desc) {  
817 - if (desc.pattern && typeof desc.pattern === 'string') {  
818 - desc.pattern = new RegExp(desc.pattern);  
819 - }  
820 -  
821 - return desc;  
822 - }; // result be array  
823 -  
824 -  
825 - if (schema.rules) {  
826 - if (Array.isArray(schema.rules)) {  
827 - var requiredRule = schema.rules.find(function (rule) {  
828 - return rule.required === true;  
829 - });  
830 -  
831 - if (requiredRule) {  
832 - result = _objectSpread(_objectSpread({}, result), requiredRule);  
833 - }  
834 -  
835 - result = [result].concat(_toConsumableArray(schema.rules));  
836 - result = result.map(function (r) {  
837 - return handleRegx(r);  
838 - });  
839 - } else if (isObject(schema.rules)) {  
840 - result = [result, schema.rules];  
841 - result = result.map(function (r) {  
842 - return handleRegx(r);  
843 - });  
844 - }  
845 - } else {  
846 - result = [result];  
847 - }  
848 - }  
849 -  
850 - return _defineProperty({}, path, result);  
851 -}; // export const getDescriptorFromSchema = ({ schema, isRequired = true }) => {  
852 -// let result = {};  
853 -// let singleResult = {};  
854 -// if (schema.hidden === true) return { validator: () => true };  
855 -// if (isObjType(schema)) {  
856 -// result.type = 'object';  
857 -// if (isRequired && schema.required === true) {  
858 -// result.required = true;  
859 -// }  
860 -// result.fields = {};  
861 -// Object.keys(schema.properties).forEach(key => {  
862 -// const item = schema.properties[key];  
863 -// // 兼容旧的!  
864 -// if (Array.isArray(schema.required) && schema.required.indexOf(key) > -1) {  
865 -// item.required = true;  
866 -// }  
867 -// result.fields[key] = getDescriptorFromSchema({  
868 -// schema: item,  
869 -// isRequired,  
870 -// });  
871 -// });  
872 -// } else if (isListType(schema)) {  
873 -// result.type = 'array';  
874 -// if (isRequired && schema.required === true) {  
875 -// result.required = true;  
876 -// }  
877 -// if (typeof schema.min === 'number') {  
878 -// result.min = schema.min;  
879 -// }  
880 -// if (typeof schema.max === 'number') {  
881 -// result.max = schema.max;  
882 -// }  
883 -// result.defaultField = { type: 'object', fields: {} }; // 目前就默认只有object类型的 TODO:  
884 -// Object.keys(schema.items.properties).forEach(key => {  
885 -// const item = schema.items.properties[key];  
886 -// // 兼容旧的!  
887 -// if (Array.isArray(schema.required) && schema.required.indexOf(key) > -1) {  
888 -// item.required = true;  
889 -// }  
890 -// result.defaultField.fields[key] = getDescriptorFromSchema({  
891 -// schema: item,  
892 -// isRequired,  
893 -// });  
894 -// });  
895 -// } else {  
896 -// // 单个的逻辑  
897 -// const processRule = item => {  
898 -// if (schema.type) return { ...item, type: schema.type };  
899 -// if (item.pattern && typeof item.pattern === 'string') {  
900 -// return { ...item, pattern: new RegExp(item.pattern) };  
901 -// }  
902 -// return item;  
903 -// };  
904 -// const { required, ...rest } = schema;  
905 -// ['type', 'pattern', 'min', 'max', 'len'].forEach(key => {  
906 -// if (Object.keys(rest).indexOf(key) > -1) {  
907 -// singleResult[key] = rest[key];  
908 -// }  
909 -// });  
910 -// switch (schema.type) {  
911 -// case 'range':  
912 -// singleResult.type = 'array';  
913 -// break;  
914 -// case 'html':  
915 -// singleResult.type = 'string';  
916 -// break;  
917 -// default:  
918 -// break;  
919 -// }  
920 -// switch (schema.format) {  
921 -// case 'email':  
922 -// case 'url':  
923 -// singleResult.type = schema.format;  
924 -// break;  
925 -// default:  
926 -// break;  
927 -// }  
928 -// let requiredRule;  
929 -// if (isRequired && schema.required === true) {  
930 -// requiredRule = { required: true, type: singleResult.type || 'string' };  
931 -// }  
932 -// if (schema.rules) {  
933 -// if (Array.isArray(schema.rules)) {  
934 -// const _rules = [];  
935 -// schema.rules.forEach(item => {  
936 -// if (item.required === true) {  
937 -// if (isRequired) {  
938 -// requiredRule = item;  
939 -// }  
940 -// } else {  
941 -// _rules.push(processRule(item));  
942 -// }  
943 -// });  
944 -// result = [singleResult, ..._rules];  
945 -// } else if (isObject(schema.rules)) {  
946 -// // TODO: 规范上不允许rules是object,省一点事儿  
947 -// result = [singleResult, processRule(schema.rules)];  
948 -// } else {  
949 -// result = singleResult;  
950 -// }  
951 -// } else {  
952 -// result = singleResult;  
953 -// }  
954 -// if (requiredRule) {  
955 -// if (Array.isArray(result)) {  
956 -// result.push(requiredRule);  
957 -// } else if (isObject(result)) {  
958 -// result = [result, requiredRule];  
959 -// }  
960 -// }  
961 -// if (schema.format === 'image') {  
962 -// const imgValidator = {  
963 -// validator: (rule, value) => {  
964 -// const pattern = /([/|.|w|s|-])*.(jpg|gif|png|bmp|apng|webp|jpeg|json)/;  
965 -// if (!value) return true; // 这里判断宽一点,undefined、null、'' 都当做没有填写  
966 -// return !!pattern.exec(value) || isUrl(value);  
967 -// },  
968 -// message: '${title}的类型不是image',  
969 -// };  
970 -// if (Array.isArray(result)) {  
971 -// result.push(imgValidator);  
972 -// } else if (isObject(result)) {  
973 -// result = [result, imgValidator];  
974 -// }  
975 -// }  
976 -// }  
977 -// return result;  
978 -// };  
979 -// schema = {  
980 -// type: 'object',  
981 -// properties: {  
982 -// x: {  
983 -// type: 'object',  
984 -// properties: {  
985 -// y: {  
986 -// type: 'string',  
987 -// required: true,  
988 -// },  
989 -// },  
990 -// },  
991 -// },  
992 -// };  
993 -// path = 'x.y'  
994 -// return {required: true, message?: 'xxxx'}  
995 -// export const isPathRequired = (path, schema) => {  
996 -// let pathArr = path.split('.');  
997 -// while (pathArr.length > 0) {  
998 -// let [_path, ...rest] = pathArr;  
999 -// _path = _path.split('[')[0];  
1000 -// let childSchema;  
1001 -// if (isObjType(schema)) {  
1002 -// childSchema = schema.properties[_path];  
1003 -// } else if (isListType(schema)) {  
1004 -// childSchema = schema.items.properties[_path];  
1005 -// }  
1006 -// pathArr = rest;  
1007 -// if (childSchema) {  
1008 -// return isPathRequired(rest.join('.'), childSchema);  
1009 -// }  
1010 -// // 单个的逻辑  
1011 -// let result = { required: false };  
1012 -// if (schema.required === true) {  
1013 -// result.required = true;  
1014 -// }  
1015 -// if (schema.rules) {  
1016 -// const requiredItem = schema.rules.find(item => item.required);  
1017 -// if (requiredItem) {  
1018 -// result = requiredItem;  
1019 -// }  
1020 -// }  
1021 -// return result;  
1022 -// }  
1023 -// };  
1024 -// _path 只供内部递归使用  
1025 -  
1026 -export var generateDataSkeleton = function generateDataSkeleton(schema, formData) {  
1027 - var _formData = clone(formData);  
1028 -  
1029 - var result = _formData;  
1030 -  
1031 - if (isObjType(schema)) {  
1032 - if (_formData === undefined || _typeof(_formData) !== 'object') {  
1033 - _formData = {};  
1034 - result = {};  
1035 - }  
1036 -  
1037 - Object.keys(schema.properties).forEach(function (key) {  
1038 - var childSchema = schema.properties[key];  
1039 - var childData = _formData[key];  
1040 - var childResult = generateDataSkeleton(childSchema, childData);  
1041 - result[key] = childResult;  
1042 - });  
1043 - } else if (_formData !== undefined) {// result = _formData;  
1044 - } else {  
1045 - if (schema.default !== undefined) {  
1046 - result = clone(schema.default);  
1047 - } else if (schema.type === 'boolean' && !schema.widget) {  
1048 - // result = false;  
1049 - result = undefined;  
1050 - } else {  
1051 - result = undefined;  
1052 - }  
1053 - }  
1054 -  
1055 - return result;  
1056 -};  
1057 -export var translateMessage = function translateMessage(msg, schema) {  
1058 - if (typeof msg !== 'string') {  
1059 - return '';  
1060 - }  
1061 -  
1062 - if (!schema) return msg;  
1063 - msg = msg.replace('${title}', schema.title);  
1064 - msg = msg.replace('${type}', schema.format || schema.type); // 兼容代码  
1065 -  
1066 - if (typeof schema.min === 'number') {  
1067 - msg = msg.replace('${min}', schema.min);  
1068 - }  
1069 -  
1070 - if (typeof schema.max === 'number') {  
1071 - msg = msg.replace('${max}', schema.max);  
1072 - }  
1073 -  
1074 - if (schema.rules) {  
1075 - var minRule = schema.rules.find(function (r) {  
1076 - return r.min !== undefined;  
1077 - });  
1078 -  
1079 - if (minRule) {  
1080 - msg = msg.replace('${min}', minRule.min);  
1081 - }  
1082 -  
1083 - var maxRule = schema.rules.find(function (r) {  
1084 - return r.max !== undefined;  
1085 - });  
1086 -  
1087 - if (maxRule) {  
1088 - msg = msg.replace('${max}', maxRule.max);  
1089 - }  
1090 -  
1091 - var lenRule = schema.rules.find(function (r) {  
1092 - return r.len !== undefined;  
1093 - });  
1094 -  
1095 - if (lenRule) {  
1096 - msg = msg.replace('${len}', lenRule.len);  
1097 - }  
1098 -  
1099 - var patternRule = schema.rules.find(function (r) {  
1100 - return r.pattern !== undefined;  
1101 - });  
1102 -  
1103 - if (patternRule) {  
1104 - msg = msg.replace('${pattern}', patternRule.pattern);  
1105 - }  
1106 - }  
1107 -  
1108 - return msg;  
1109 -}; // "objectName": {  
1110 -// "title": "对象",  
1111 -// "description": "这是一个对象类型",  
1112 -// "type": "object",  
1113 -// "properties": {  
1114 -// }  
1115 -// }  
1116 -// "listName": {  
1117 -// "title": "对象数组",  
1118 -// "description": "对象数组嵌套功能",  
1119 -// "type": "array",  
1120 -// "items": {  
1121 -// "type": "object",  
1122 -// "properties": {  
1123 -// }  
1124 -// }  
1125 -// }  
1126 -  
1127 -var changeSchema = function changeSchema(_schema, singleChange) {  
1128 - var schema = clone(_schema);  
1129 - schema = singleChange(schema);  
1130 -  
1131 - if (isObjType(schema)) {  
1132 - var requiredKeys = [];  
1133 -  
1134 - if (Array.isArray(schema.required)) {  
1135 - requiredKeys = schema.required;  
1136 - delete schema.required;  
1137 - }  
1138 -  
1139 - Object.keys(schema.properties).forEach(function (key) {  
1140 - var item = schema.properties[key];  
1141 -  
1142 - if (requiredKeys.indexOf(key) > -1) {  
1143 - item.required = true;  
1144 - }  
1145 -  
1146 - schema.properties[key] = changeSchema(item, singleChange);  
1147 - });  
1148 - } else if (isListType(schema)) {  
1149 - Object.keys(schema.items.properties).forEach(function (key) {  
1150 - var item = schema.items.properties[key];  
1151 - schema.items.properties[key] = changeSchema(item, singleChange);  
1152 - });  
1153 - }  
1154 -  
1155 - return schema;  
1156 -};  
1157 -  
1158 -export var updateSchemaToNewVersion = function updateSchemaToNewVersion(schema) {  
1159 - return changeSchema(schema, updateSingleSchema);  
1160 -};  
1161 -  
1162 -var updateSingleSchema = function updateSingleSchema(schema) {  
1163 - try {  
1164 - schema.rules = schema.rules || [];  
1165 - schema.props = schema.props || {};  
1166 -  
1167 - if (schema['ui:options']) {  
1168 - schema.props = schema['ui:options'];  
1169 - delete schema['ui:options'];  
1170 - }  
1171 -  
1172 - if (schema.pattern) {  
1173 - var validItem = {  
1174 - pattern: schema.pattern  
1175 - };  
1176 -  
1177 - if (schema.message && schema.message.pattern) {  
1178 - validItem.message = schema.message.pattern;  
1179 - }  
1180 -  
1181 - schema.rules.push(validItem);  
1182 - delete schema.pattern;  
1183 - delete schema.message;  
1184 - } // min / max  
1185 -  
1186 -  
1187 - if (schema.minLength) {  
1188 - schema.min = schema.minLength;  
1189 - delete schema.minLength;  
1190 - }  
1191 -  
1192 - if (schema.maxLength) {  
1193 - schema.max = schema.maxLength;  
1194 - delete schema.maxLength;  
1195 - }  
1196 -  
1197 - if (schema.minItems) {  
1198 - schema.min = schema.minItems;  
1199 - delete schema.minItems;  
1200 - }  
1201 -  
1202 - if (schema.maxItems) {  
1203 - schema.max = schema.maxItems;  
1204 - delete schema.maxItems;  
1205 - }  
1206 -  
1207 - if (schema.step) {  
1208 - schema.props.step = schema.step;  
1209 - delete schema.step;  
1210 - } // ui:xxx  
1211 -  
1212 -  
1213 - if (schema['ui:className']) {  
1214 - schema.className = schema['ui:className'];  
1215 - delete schema['ui:className'];  
1216 - }  
1217 -  
1218 - if (schema['ui:hidden']) {  
1219 - schema.hidden = schema['ui:hidden'];  
1220 - delete schema['ui:hidden'];  
1221 - }  
1222 -  
1223 - if (schema['ui:readonly']) {  
1224 - schema.readOnly = schema['ui:readonly']; // 改成驼峰了  
1225 -  
1226 - delete schema['ui:readonly'];  
1227 - }  
1228 -  
1229 - if (schema['ui:disabled']) {  
1230 - schema.disabled = schema['ui:disabled'];  
1231 - delete schema['ui:disabled'];  
1232 - }  
1233 -  
1234 - if (schema['ui:width']) {  
1235 - schema.width = schema['ui:width'];  
1236 - delete schema['ui:width'];  
1237 - }  
1238 -  
1239 - if (schema['ui:displayType']) {  
1240 - schema.displayType = schema['ui:displayType'];  
1241 - delete schema['ui:displayType'];  
1242 - }  
1243 -  
1244 - if (schema['ui:column']) {  
1245 - schema.column = schema['ui:column'];  
1246 - delete schema['ui:column'];  
1247 - }  
1248 -  
1249 - if (schema['ui:widget']) {  
1250 - schema.widget = schema['ui:widget'];  
1251 - delete schema['ui:widget'];  
1252 - }  
1253 -  
1254 - if (schema['ui:labelWidth']) {  
1255 - schema.labelWidth = schema['ui:labelWidth'];  
1256 - delete schema['ui:labelWidth'];  
1257 - }  
1258 -  
1259 - if (schema.rules && schema.rules.length === 0) {  
1260 - delete schema.rules;  
1261 - }  
1262 -  
1263 - if (typeof schema.props === 'function' || isObject(schema.props) && Object.keys(schema.props).length > 0) {} else {  
1264 - delete schema.props;  
1265 - }  
1266 -  
1267 - return schema;  
1268 - } catch (error) {  
1269 - console.error('schema转换失败!', error);  
1270 - return schema;  
1271 - }  
1272 -}; // 检验一个string是 function(传统活箭头函数)  
1273 -  
1274 -  
1275 -export var parseFunctionString = function parseFunctionString(string) {  
1276 - if (typeof string !== 'string') return false;  
1277 - var reg1 = /^{{(function.+)}}$/;  
1278 - var reg2 = /^{{(.+=>.+)}}$/;  
1279 -  
1280 - if (string.match(reg1)) {  
1281 - return string.match(reg1)[1];  
1282 - }  
1283 -  
1284 - if (string.match(reg2)) {  
1285 - return string.match(reg2)[1];  
1286 - }  
1287 -  
1288 - return false;  
1289 -};  
1290 -export var completeSchemaWithTheme = function completeSchemaWithTheme() {  
1291 - var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};  
1292 - var theme = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};  
1293 - var result = {};  
1294 -  
1295 - if (isObject(schema)) {  
1296 - if (schema.theme && theme[schema.theme]) {  
1297 - result = _objectSpread(_objectSpread({}, schema), theme[schema.theme]);  
1298 - }  
1299 -  
1300 - Object.keys(schema).forEach(function (key) {  
1301 - result[key] = completeSchemaWithTheme(schema[key], theme);  
1302 - });  
1303 - } else {  
1304 - result = schema;  
1305 - }  
1306 -  
1307 - return result;  
1308 -};  
1309 -export var cleanEmpty = function cleanEmpty(obj) {  
1310 - if (Array.isArray(obj)) {  
1311 - return obj.map(function (v) {  
1312 - return v && isObject(v) ? cleanEmpty(v) : v;  
1313 - }).filter(function (v) {  
1314 - return !(v == undefined);  
1315 - });  
1316 - } else if (isObject(obj)) {  
1317 - return Object.entries(obj).map(function (_ref6) {  
1318 - var _ref7 = _slicedToArray(_ref6, 2),  
1319 - k = _ref7[0],  
1320 - v = _ref7[1];  
1321 -  
1322 - return [k, v && isObject(v) ? cleanEmpty(v) : v];  
1323 - }).reduce(function (a, _ref8) {  
1324 - var _ref9 = _slicedToArray(_ref8, 2),  
1325 - k = _ref9[0],  
1326 - v = _ref9[1];  
1327 -  
1328 - return v == undefined ? a : (a[k] = v, a);  
1329 - }, {});  
1330 - } else {  
1331 - return obj;  
1332 - }  
1333 -}; // const x = { a: 1, b: { c: 2 }, d: [{ e: 3, f: [{ g: 5 }] }, { e: 4 }] };  
1334 -// ['a', 'b.c', 'd[0].e', 'd[0].f[0].g', 'd[1].e']  
1335 -  
1336 -export var dataToKeys = function dataToKeys(data) {  
1337 - var rootKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';  
1338 - var result = [];  
1339 -  
1340 - if (rootKey && rootKey.slice(-1) !== ']') {  
1341 - result.push(rootKey);  
1342 - }  
1343 -  
1344 - var isComplex = function isComplex(data) {  
1345 - return isObject(data) || Array.isArray(data);  
1346 - };  
1347 -  
1348 - if (isObject(data)) {  
1349 - Object.keys(data).forEach(function (key) {  
1350 - var item = data[key];  
1351 - var itemRootKey = rootKey ? rootKey + '.' + key : key;  
1352 -  
1353 - if (isComplex(item)) {  
1354 - var itemKeys = dataToKeys(item, itemRootKey);  
1355 - result = [].concat(_toConsumableArray(result), _toConsumableArray(itemKeys));  
1356 - } else {  
1357 - result.push(itemRootKey);  
1358 - }  
1359 - });  
1360 - } else if (Array.isArray(data)) {  
1361 - data.forEach(function (item, idx) {  
1362 - var itemRootKey = rootKey ? "".concat(rootKey, "[").concat(idx, "]") : "[".concat(idx, "]");  
1363 -  
1364 - if (isComplex(item)) {  
1365 - var itemKeys = dataToKeys(item, itemRootKey);  
1366 - result = [].concat(_toConsumableArray(result), _toConsumableArray(itemKeys));  
1367 - } else {  
1368 - result.push(itemRootKey);  
1369 - }  
1370 - });  
1371 - } else {}  
1372 -  
1373 - return result;  
1374 -};  
1375 -export var removeHiddenFromResult = function removeHiddenFromResult(data, flatten) {  
1376 - var result = clone(data);  
1377 - var keys = dataToKeys(result);  
1378 - keys.forEach(function (key) {  
1379 - var _destructDataPath = destructDataPath(key),  
1380 - id = _destructDataPath.id,  
1381 - dataIndex = _destructDataPath.dataIndex;  
1382 -  
1383 - if (flatten[id]) {  
1384 - var _ref10 = flatten[id].schema || {},  
1385 - hidden = _ref10.hidden;  
1386 -  
1387 - if (isExpression(hidden)) {  
1388 - hidden = parseSingleExpression(hidden, result, key);  
1389 - }  
1390 -  
1391 - if (get(result, key) !== undefined && hidden) {  
1392 - set(result, key, undefined);  
1393 - }  
1394 - }  
1395 - });  
1396 - return result;  
1397 -};  
1398 -export function msToTime(duration) {  
1399 - var seconds = Math.floor(duration / 1000 % 60);  
1400 - var minutes = Math.floor(duration / (1000 * 60) % 60);  
1401 - var hours = Math.floor(duration / (1000 * 60 * 60) % 24);  
1402 - hours = hours < 10 ? '0' + hours : hours;  
1403 - minutes = minutes < 10 ? '0' + minutes : minutes;  
1404 - seconds = seconds < 10 ? '0' + seconds : seconds;  
1405 - return hours + ':' + minutes + ':' + seconds;  
1406 -}  
1407 -export function yymmdd(timeStamp) {  
1408 - var date_ob = new Date(Number(timeStamp));  
1409 -  
1410 - var adjustZero = function adjustZero(num) {  
1411 - return ('0' + num).slice(-2);  
1412 - };  
1413 -  
1414 - var day = adjustZero(date_ob.getDate());  
1415 - var month = adjustZero(date_ob.getMonth());  
1416 - var year = date_ob.getFullYear();  
1417 - var hours = adjustZero(date_ob.getHours());  
1418 - var minutes = adjustZero(date_ob.getMinutes());  
1419 - var seconds = adjustZero(date_ob.getSeconds());  
1420 - return "".concat(year, "-").concat(month, "-").concat(day, " ").concat(hours, ":").concat(minutes, ":").concat(seconds);  
1421 -}  
1422 -export function allPromiseFinish(promiseList) {  
1423 - var hasError = false;  
1424 - var count = promiseList.length;  
1425 - var results = [];  
1426 -  
1427 - if (!promiseList.length) {  
1428 - return Promise.resolve([]);  
1429 - }  
1430 -  
1431 - return new Promise(function (resolve, reject) {  
1432 - promiseList.forEach(function (promise, index) {  
1433 - promise.catch(function (e) {  
1434 - hasError = true;  
1435 - return e;  
1436 - }).then(function (result) {  
1437 - count -= 1;  
1438 - results[index] = result;  
1439 -  
1440 - if (count > 0) {  
1441 - return;  
1442 - }  
1443 -  
1444 - if (hasError) {  
1445 - reject(results);  
1446 - }  
1447 -  
1448 - resolve(results);  
1449 - });  
1450 - });  
1451 - });  
1452 -}  
1453 -export var removeDups = function removeDups(arr) {  
1454 - if (!Array.isArray(arr)) {  
1455 - console.log('in removeDups: param is not an array');  
1456 - return;  
1457 - }  
1458 -  
1459 - var array = [];  
1460 -  
1461 - for (var i = 0; i < arr.length; i++) {  
1462 - if (array.indexOf(arr[i]) === -1) {  
1463 - array.push(arr[i]);  
1464 - }  
1465 - }  
1466 -  
1467 - return array;  
1468 -};  
1 -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }  
2 -  
3 -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }  
4 -  
5 -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }  
6 -  
7 -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); }  
8 -  
9 -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }  
10 -  
11 -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }  
12 -  
13 -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; }  
14 -  
15 -/* eslint-disable react-hooks/exhaustive-deps */  
16 -import { getDescriptorSimple, dataToKeys, destructDataPath, getDataPath, isExpression, parseSingleExpression, isObject, allPromiseFinish, removeDups } from './utils';  
17 -import { defaultValidateMessagesCN } from './validateMessageCN';  
18 -import { defaultValidateMessages } from './validateMessage';  
19 -import Validator from 'async-validator';  
20 -import { get, merge } from 'lodash-es';  
21 -export var parseSchemaExpression = function parseSchemaExpression(schema, formData, path) {  
22 - if (!isObject(schema)) return schema;  
23 - var result = {};  
24 - Object.keys(schema).forEach(function (key) {  
25 - var item = schema[key];  
26 -  
27 - if (isObject(item)) {  
28 - result[key] = parseSchemaExpression(item, formData, path);  
29 - } else if (isExpression(item)) {  
30 - result[key] = parseSingleExpression(item, formData, path);  
31 - } else {  
32 - result[key] = item;  
33 - }  
34 - });  
35 - return result;  
36 -};  
37 -  
38 -var getRelatedPaths = function getRelatedPaths(path, flatten) {  
39 - var parentPaths = [];  
40 - var pathArr = path.split('.');  
41 -  
42 - while (pathArr.length > 0) {  
43 - parentPaths.push(pathArr.join('.'));  
44 - pathArr.pop();  
45 - }  
46 -  
47 - var result = [].concat(parentPaths);  
48 - parentPaths.forEach(function (path) {  
49 - var _destructDataPath = destructDataPath(path),  
50 - id = _destructDataPath.id,  
51 - dataIndex = _destructDataPath.dataIndex;  
52 -  
53 - if (flatten[id] && flatten[id].schema && Array.isArray(flatten[id].schema.dependecies)) {  
54 - var deps = flatten[id].schema.dependecies;  
55 - var fullPathDeps = deps.map(function (dep) {  
56 - return getDataPath(dep, dataIndex);  
57 - });  
58 - result = [].concat(_toConsumableArray(result), _toConsumableArray(fullPathDeps));  
59 - }  
60 - });  
61 - return removeDups(result).map(function (path) {  
62 - if (path.slice(-1) === ']') {  
63 - var pattern = /\[[0-9]+\]$/;  
64 - return path.replace(pattern, '');  
65 - } else {  
66 - return path;  
67 - }  
68 - });  
69 -};  
70 -  
71 -export var validateField = function validateField(_ref) {  
72 - var path = _ref.path,  
73 - formData = _ref.formData,  
74 - flatten = _ref.flatten,  
75 - options = _ref.options;  
76 - var paths = getRelatedPaths(path, flatten); // console.log('all relevant paths:', paths);  
77 -  
78 - var promiseArray = paths.map(function (path) {  
79 - var _destructDataPath2 = destructDataPath(path),  
80 - id = _destructDataPath2.id,  
81 - dataIndex = _destructDataPath2.dataIndex;  
82 -  
83 - if (flatten[id] || flatten["".concat(id, "[]")]) {  
84 - var item = flatten[id] || flatten["".concat(id, "[]")];  
85 - var singleData = get(formData, path);  
86 - var schema = item.schema || {};  
87 - var finalSchema = parseSchemaExpression(schema, formData, path);  
88 - return validateSingle(singleData, finalSchema, path, options); // is a promise  
89 - } else {  
90 - return Promise.resolve();  
91 - }  
92 - });  
93 - return allPromiseFinish(promiseArray).then(function (res) {  
94 - var errorFields = res.filter(function (item) {  
95 - return Array.isArray(item) && item.length > 0;  
96 - }).map(function (item) {  
97 - var name = item[0].field;  
98 - var error = item.map(function (m) {  
99 - return m.message;  
100 - }).filter(function (m) {  
101 - return !!m;  
102 - });  
103 - return {  
104 - name: name,  
105 - error: error  
106 - };  
107 - });  
108 - return errorFields;  
109 - }).catch(function (e) {  
110 - console.log(e);  
111 - });  
112 -}; // pathFromData => allPath  
113 -  
114 -var getAllPaths = function getAllPaths(paths, flatten) {  
115 - if (!Array.isArray(paths)) return [];  
116 -  
117 - var result = _toConsumableArray(paths).filter(function (p) {  
118 - return p.indexOf(']') > -1;  
119 - }).map(function (p1) {  
120 - var last = p1.lastIndexOf(']');  
121 - return p1.substring(0, last + 1);  
122 - });  
123 -  
124 - var uniqueResult = removeDups(result);  
125 - var allFlattenPath = Object.keys(flatten);  
126 -  
127 - var res = _toConsumableArray(paths);  
128 -  
129 - uniqueResult.forEach(function (result) {  
130 - var _destructDataPath3 = destructDataPath(result),  
131 - id = _destructDataPath3.id,  
132 - dataIndex = _destructDataPath3.dataIndex;  
133 -  
134 - if (flatten[id]) {  
135 - var children = allFlattenPath.filter(function (f) {  
136 - return f.indexOf(id) === 0 && f !== id;  
137 - });  
138 - var childrenWithIndex = children.map(function (child) {  
139 - var p = getDataPath(child, dataIndex);  
140 - return p.split('[]')[0];  
141 - }).filter(function (i) {  
142 - return !!i;  
143 - });  
144 - res = [].concat(_toConsumableArray(res), _toConsumableArray(removeDups(childrenWithIndex)));  
145 - }  
146 - });  
147 - return removeDups(res);  
148 -};  
149 -  
150 -export var validateAll = function validateAll(_ref2) {  
151 - var formData = _ref2.formData,  
152 - flatten = _ref2.flatten,  
153 - options = _ref2.options;  
154 - var paths = dataToKeys(formData);  
155 - var allPaths = getAllPaths(paths, flatten); // console.log(formData, dataToKeys(formData), 'dataToKeysdataToKeys');  
156 - // console.log('allPaths', allPaths);  
157 -  
158 - var promiseArray = allPaths.map(function (path) {  
159 - var _destructDataPath4 = destructDataPath(path),  
160 - id = _destructDataPath4.id,  
161 - dataIndex = _destructDataPath4.dataIndex;  
162 -  
163 - if (flatten[id] || flatten["".concat(id, "[]")]) {  
164 - var item = flatten[id] || flatten["".concat(id, "[]")];  
165 - var singleData = get(formData, path);  
166 - var schema = item.schema || {};  
167 - var finalSchema = parseSchemaExpression(schema, formData, path);  
168 - return validateSingle(singleData, finalSchema, path, options); // is a promise  
169 - } else {  
170 - return Promise.resolve();  
171 - }  
172 - });  
173 - return allPromiseFinish(promiseArray).then(function (res) {  
174 - var errorFields = res.filter(function (item) {  
175 - return Array.isArray(item) && item.length > 0 && item[0].message !== null;  
176 - }) // NOTICE: different from validateField  
177 - .map(function (item) {  
178 - var name = item[0].field;  
179 - var error = item.map(function (m) {  
180 - return m.message;  
181 - }).filter(function (m) {  
182 - return !!m;  
183 - });  
184 - return {  
185 - name: name,  
186 - error: error  
187 - };  
188 - });  
189 - return errorFields;  
190 - }).catch(function (e) {  
191 - console.log(e);  
192 - });  
193 -};  
194 -  
195 -var validateSingle = function validateSingle(data) {  
196 - var schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};  
197 - var path = arguments.length > 2 ? arguments[2] : undefined;  
198 - var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};  
199 -  
200 - if (schema.hidden) {  
201 - return Promise.resolve();  
202 - }  
203 -  
204 - var _options$validateMess = options.validateMessages,  
205 - validateMessages = _options$validateMess === void 0 ? {} : _options$validateMess,  
206 - _options$locale = options.locale,  
207 - locale = _options$locale === void 0 ? 'cn' : _options$locale;  
208 - var cn = defaultValidateMessagesCN;  
209 - var en = defaultValidateMessages;  
210 - var descriptor = getDescriptorSimple(schema, path); // console.log('descriptor, schema, path', descriptor, schema, path, data);  
211 - // TODO: 有些情况会出现没有rules,需要看一下,先兜底  
212 -  
213 - var validator;  
214 -  
215 - try {  
216 - validator = new Validator(descriptor);  
217 - } catch (error) {  
218 - return Promise.resolve();  
219 - }  
220 -  
221 - var messageFeed = locale === 'en' ? en : cn;  
222 - merge(messageFeed, validateMessages);  
223 - validator.messages(messageFeed);  
224 - return validator.validate(_defineProperty({}, path, data)).then(function (res) {  
225 - return [{  
226 - field: path,  
227 - message: null  
228 - }];  
229 - }).catch(function (_ref3) {  
230 - var errors = _ref3.errors,  
231 - fields = _ref3.fields;  
232 - return errors;  
233 - });  
234 -}; // 无用  
235 -// const theRest = () => {  
236 -// let _schema = getSchemaFromFlatten(flatten);  
237 -// if (Object.keys(_schema).length === 0) return Promise.resolve();  
238 -// const descriptor = getDescriptorFromSchema({  
239 -// schema: _schema,  
240 -// isRequired,  
241 -// }).fields;  
242 -// window.descriptor = descriptor;  
243 -// let touchVerifyList = [];  
244 -// // 如果是最后的校验,所有key都touch了,就不用算这个了  
245 -// // 因为要整个构建validator在list的情况太复杂了,所以required单独拿出来处理,但是这边有不少单独处理逻辑,例如message  
246 -// if (!isRequired) {  
247 -// touchedKeys.forEach(key => {  
248 -// const keyRequired = isPathRequired(key, _schema);  
249 -// const val = get(formData, key);  
250 -// const nullValue = [undefined, null, ''].indexOf(val) > -1; // 注意 0 不是  
251 -// const isEmptyMultiSelect = Array.isArray(val) && val.length === 0;  
252 -// if ((nullValue || isEmptyMultiSelect) && keyRequired.required) {  
253 -// const _message =  
254 -// keyRequired.message || validateMessages.required || '${title}必填';  
255 -// touchVerifyList.push({ name: key, error: [_message] });  
256 -// }  
257 -// });  
258 -// }  
259 -// const cn = defaultValidateMessagesCN;  
260 -// const en = defaultValidateMessages;  
261 -// // TODO: 有些情况会出现没有rules,需要看一下,先兜底  
262 -// let validator;  
263 -// try {  
264 -// validator = new Validator(descriptor);  
265 -// } catch (error) {  
266 -// return Promise.resolve([]);  
267 -// }  
268 -// let messageFeed = locale === 'en' ? en : cn;  
269 -// merge(messageFeed, validateMessages);  
270 -// validator.messages(messageFeed);  
271 -// return validator  
272 -// .validate(formData || {})  
273 -// .then(res => {  
274 -// if (touchVerifyList.length > 0) return touchVerifyList;  
275 -// return [];  
276 -// })  
277 -// .catch(({ errors, fields }) => {  
278 -// // error的name改成正常的path  
279 -// let normalizedErrors = getArray(errors).map(err => {  
280 -// const _path = formatPathFromValidator(err.field);  
281 -// return { name: _path, error: [err.message] };  
282 -// });  
283 -// // 添加touched的required  
284 -// normalizedErrors = [...normalizedErrors, ...touchVerifyList];  
285 -// // 合并同名的error  
286 -// let _errorFields = [];  
287 -// normalizedErrors.forEach(item => {  
288 -// const matchIndex = _errorFields.findIndex(  
289 -// ele => ele.name === item.name  
290 -// );  
291 -// if (matchIndex === -1) {  
292 -// _errorFields.push(item);  
293 -// } else {  
294 -// _errorFields[matchIndex].error = [  
295 -// ..._errorFields[matchIndex].error,  
296 -// ...item.error,  
297 -// ];  
298 -// }  
299 -// });  
300 -// return _errorFields;  
301 -// });  
302 -// };  
303 -// var d3 = {  
304 -// list: {  
305 -// type: 'array',  
306 -// defaultField: {  
307 -// type: 'object',  
308 -// fields: {  
309 -// userName: [  
310 -// {  
311 -// bind: false,  
312 -// title: 'User Name',  
313 -// type: 'string',  
314 -// rules: [  
315 -// {  
316 -// min: 5,  
317 -// message: '长度需要大于5',  
318 -// },  
319 -// {  
320 -// max: 12,  
321 -// },  
322 -// ],  
323 -// },  
324 -// {  
325 -// min: 5,  
326 -// message: '长度需要大于5',  
327 -// },  
328 -// {  
329 -// max: 12,  
330 -// },  
331 -// ],  
332 -// selectName: {  
333 -// title: '单选',  
334 -// type: 'string',  
335 -// enum: ['a', 'b', 'c'],  
336 -// enumNames: ['早', '中', '晚'],  
337 -// required: true,  
338 -// },  
339 -// checkboxName: {  
340 -// title: '是否判断',  
341 -// type: 'boolean',  
342 -// valuePropName: 'checked',  
343 -// },  
344 -// },  
345 -// },  
346 -// },  
347 -// };  
348 -// var d2 = {  
349 -// list: {  
350 -// type: 'array',  
351 -// defaultField: {  
352 -// type: 'object',  
353 -// fields: {  
354 -// userName: [  
355 -// {  
356 -// bind: false,  
357 -// title: 'User Name',  
358 -// type: 'string',  
359 -// rules: [  
360 -// {  
361 -// min: 5,  
362 -// message: '长度需要大于5',  
363 -// },  
364 -// {  
365 -// max: 12,  
366 -// },  
367 -// ],  
368 -// },  
369 -// {  
370 -// min: 5,  
371 -// message: '长度需要大于5',  
372 -// },  
373 -// {  
374 -// max: 12,  
375 -// },  
376 -// ],  
377 -// selectName: {  
378 -// title: '单选',  
379 -// type: 'string',  
380 -// enum: ['a', 'b', 'c'],  
381 -// enumNames: ['早', '中', '晚'],  
382 -// required: true,  
383 -// },  
384 -// checkboxName: {  
385 -// title: '是否判断',  
386 -// type: 'boolean',  
387 -// valuePropName: 'checked',  
388 -// },  
389 -// },  
390 -// },  
391 -// },  
392 -// };  
es/hooks.js renamed from es/form-render-core/src/hooks.js
es/index.css renamed from es/form-render-core/src/index.css
@@ -62,6 +62,7 @@ @@ -62,6 +62,7 @@
62 .fr-container .fr-label-title { 62 .fr-container .fr-label-title {
63 display: inline-flex; 63 display: inline-flex;
64 color: #333; 64 color: #333;
  65 + font-size: 14px;
65 min-height: 22px; 66 min-height: 22px;
66 /* ""的标签页占位 */ 67 /* ""的标签页占位 */
67 line-height: 22px; 68 line-height: 22px;
@@ -54,10 +54,9 @@ export interface FormInstance { @@ -54,10 +54,9 @@ export interface FormInstance {
54 /** 折中升级方案中使用到,正常用不到 */ 54 /** 折中升级方案中使用到,正常用不到 */
55 init: () => void; 55 init: () => void;
56 /** 数据分析接口,表单展示完成渲染时触发 */ 56 /** 数据分析接口,表单展示完成渲染时触发 */
57 - logOnMount: (args: any) => void; 57 + logOnMount?: (any) => void;
58 /** 数据分析接口,表单提交成功时触发,获得本次表单填写的总时长 */ 58 /** 数据分析接口,表单提交成功时触发,获得本次表单填写的总时长 */
59 - logOnSubmit: (args: any) => void;  
60 - _setErrors: (args: any) => void; 59 + logOnSubmit?: (any) => void;
61 } 60 }
62 61
63 export type WatchProperties = { 62 export type WatchProperties = {
1 import "antd/es/config-provider/style"; 1 import "antd/es/config-provider/style";
2 import _ConfigProvider from "antd/es/config-provider"; 2 import _ConfigProvider from "antd/es/config-provider";
3 -var _excluded = ["widgets", "configProvider"]; 3 +var _excluded = ["id", "widgets", "mapping", "form", "className", "style", "beforeFinish", "onFinish", "displayType", "schema", "debug", "debugCss", "locale", "debounceInput", "size", "configProvider", "theme", "validateMessages", "watch", "config", "onMount", "labelWidth", "readOnly", "disabled", "allCollapsed", "onValuesChange", "column", "removeHiddenData", "globalProps"],
  4 + _excluded2 = ["onItemChange", "setEditing", "touchKey", "setValueByPath", "getSchemaByPath", "setSchemaByPath", "setSchema", "setValues", "getValues", "resetFields", "submit", "endValidating", "endSubmitting", "setErrorFields", "removeErrorField", "removeTouched", "changeTouchedKeys", "syncStuff", "logOnMount", "logOnSubmit", "setFirstMount"],
  5 + _excluded3 = ["isOldVersion", "schema"];
4 6
5 function _extends() { _extends = Object.assign || 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); } 7 function _extends() { _extends = Object.assign || 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); }
6 8
  9 +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  10 +
7 function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } 11 function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
8 12
9 function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } 13 function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
@@ -14,23 +18,364 @@ function _objectWithoutProperties(source, excluded) { if (source == null) return @@ -14,23 +18,364 @@ function _objectWithoutProperties(source, excluded) { if (source == null) return
14 18
15 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; } 19 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; }
16 20
17 -import React from 'react';  
18 -import zhCN from 'antd/lib/locale/zh_CN';  
19 -import FRCore from './form-render-core/src'; 21 +/* eslint-disable react-hooks/exhaustive-deps */
  22 +import React, { useEffect, useMemo, useRef } from 'react';
  23 +import { updateSchemaToNewVersion, getValueByPath, msToTime, yymmdd } from './utils';
  24 +import Core from './core';
  25 +import { Ctx, StoreCtx, Store2Ctx } from './hooks';
20 import { widgets as defaultWidgets } from './widgets/antd'; 26 import { widgets as defaultWidgets } from './widgets/antd';
21 -export { defaultWidgets as widgets };  
22 -export { useForm, connectForm, createWidget, mapping } from './form-render-core/src'; 27 +import { mapping as defaultMapping } from './mapping';
  28 +import zhCN from 'antd/lib/locale/zh_CN';
  29 +import "./atom.css";
  30 +import "./index.css";
  31 +
  32 +var defaultFinish = function defaultFinish(data, errors) {
  33 + console.log('onFinish:', {
  34 + data: data,
  35 + errors: errors
  36 + });
  37 +};
  38 +
  39 +export { defaultWidgets as widgets, defaultMapping as mapping };
  40 +export { default as useForm } from './useForm';
  41 +export { default as connectForm } from './connectForm';
23 42
24 -var FR = function FR(_ref) {  
25 - var widgets = _ref.widgets, 43 +function App(_ref) {
  44 + var id = _ref.id,
  45 + widgets = _ref.widgets,
  46 + mapping = _ref.mapping,
  47 + form = _ref.form,
  48 + className = _ref.className,
  49 + style = _ref.style,
  50 + beforeFinish = _ref.beforeFinish,
  51 + _ref$onFinish = _ref.onFinish,
  52 + onFinish = _ref$onFinish === void 0 ? defaultFinish : _ref$onFinish,
  53 + _ref$displayType = _ref.displayType,
  54 + displayType = _ref$displayType === void 0 ? 'column' : _ref$displayType,
  55 + schema = _ref.schema,
  56 + debug = _ref.debug,
  57 + debugCss = _ref.debugCss,
  58 + _ref$locale = _ref.locale,
  59 + locale = _ref$locale === void 0 ? 'cn' : _ref$locale,
  60 + _ref$debounceInput = _ref.debounceInput,
  61 + debounceInput = _ref$debounceInput === void 0 ? false : _ref$debounceInput,
  62 + size = _ref.size,
26 configProvider = _ref.configProvider, 63 configProvider = _ref.configProvider,
  64 + theme = _ref.theme,
  65 + validateMessages = _ref.validateMessages,
  66 + _ref$watch = _ref.watch,
  67 + watch = _ref$watch === void 0 ? {} : _ref$watch,
  68 + config = _ref.config,
  69 + onMount = _ref.onMount,
  70 + labelWidth = _ref.labelWidth,
  71 + readOnly = _ref.readOnly,
  72 + disabled = _ref.disabled,
  73 + _ref$allCollapsed = _ref.allCollapsed,
  74 + allCollapsed = _ref$allCollapsed === void 0 ? false : _ref$allCollapsed,
  75 + onValuesChange = _ref.onValuesChange,
  76 + column = _ref.column,
  77 + _ref$removeHiddenData = _ref.removeHiddenData,
  78 + removeHiddenData = _ref$removeHiddenData === void 0 ? false : _ref$removeHiddenData,
  79 + _ref$globalProps = _ref.globalProps,
  80 + globalProps = _ref$globalProps === void 0 ? {} : _ref$globalProps,
27 rest = _objectWithoutProperties(_ref, _excluded); 81 rest = _objectWithoutProperties(_ref, _excluded);
28 82
  83 + try {
  84 + var _ = form.submit;
  85 + } catch (error) {
  86 + console.error('form 为必填 props,<FormRender /> 没有接收到 form 属性!');
  87 + }
  88 +
  89 + var _column = schema && schema.column || column;
  90 +
  91 + var onItemChange = form.onItemChange,
  92 + setEditing = form.setEditing,
  93 + touchKey = form.touchKey,
  94 + setValueByPath = form.setValueByPath,
  95 + getSchemaByPath = form.getSchemaByPath,
  96 + setSchemaByPath = form.setSchemaByPath,
  97 + setSchema = form.setSchema,
  98 + setValues = form.setValues,
  99 + getValues = form.getValues,
  100 + resetFields = form.resetFields,
  101 + submit = form.submit,
  102 + endValidating = form.endValidating,
  103 + endSubmitting = form.endSubmitting,
  104 + setErrorFields = form.setErrorFields,
  105 + removeErrorField = form.removeErrorField,
  106 + removeTouched = form.removeTouched,
  107 + changeTouchedKeys = form.changeTouchedKeys,
  108 + syncStuff = form.syncStuff,
  109 + logOnMount = form.logOnMount,
  110 + logOnSubmit = form.logOnSubmit,
  111 + setFirstMount = form.setFirstMount,
  112 + valuesThatWillChange = _objectWithoutProperties(form, _excluded2);
  113 +
  114 + var submitData = valuesThatWillChange.submitData,
  115 + errorFields = valuesThatWillChange.errorFields,
  116 + isValidating = valuesThatWillChange.isValidating,
  117 + outsideValidating = valuesThatWillChange.outsideValidating,
  118 + isSubmitting = valuesThatWillChange.isSubmitting,
  119 + formData = valuesThatWillChange.formData,
  120 + flatten = valuesThatWillChange.flatten,
  121 + showValidate = valuesThatWillChange.showValidate,
  122 + firstMount = valuesThatWillChange.firstMount;
  123 + useEffect(function () {
  124 + // Schema最外层的type是object来判断,没有的话,认为schema没有传
  125 + if (schema && schema.type) {
  126 + setFirstMount(true);
  127 + syncStuff({
  128 + schema: schema,
  129 + locale: locale,
  130 + validateMessages: validateMessages,
  131 + beforeFinish: beforeFinish,
  132 + onMount: onMount,
  133 + removeHiddenData: removeHiddenData
  134 + });
  135 + } else {}
  136 + }, [JSON.stringify(schema)]);
  137 + useEffect(function () {
  138 + if (!firstMount && schema && schema.type) {
  139 + if (typeof onMount === 'function') {
  140 + // 等一下 useForm 里接到第一份schema时,计算第一份data的骨架
  141 + setTimeout(function () {
  142 + onMount();
  143 + }, 0);
  144 + }
  145 +
  146 + setTimeout(onMountLogger, 0);
  147 + }
  148 + }, [JSON.stringify(schema), firstMount]);
  149 +
  150 + var onMountLogger = function onMountLogger() {
  151 + var start = new Date().getTime();
  152 +
  153 + if (typeof logOnMount === 'function' || typeof logOnSubmit === 'function') {
  154 + sessionStorage.setItem('FORM_MOUNT_TIME', start);
  155 + sessionStorage.setItem('FORM_START', start);
  156 + }
  157 +
  158 + if (typeof logOnMount === 'function') {
  159 + var logParams = {
  160 + schema: schema,
  161 + url: location.href,
  162 + formData: JSON.stringify(form.getValues()),
  163 + formMount: yymmdd(start)
  164 + };
  165 +
  166 + if (id) {
  167 + logParams.id = id;
  168 + }
  169 +
  170 + logOnMount(logParams);
  171 + } // 如果是要计算时间,在 onMount 时存一个时间戳
  172 +
  173 +
  174 + if (typeof logOnSubmit === 'function') {
  175 + sessionStorage.setItem('NUMBER_OF_SUBMITS', 0);
  176 + sessionStorage.setItem('FAILED_ATTEMPTS', 0);
  177 + }
  178 + }; // 组件destroy的时候,destroy form,因为useForm可能在上层,所以不一定会跟着destroy
  179 +
  180 +
  181 + useEffect(function () {
  182 + return function () {
  183 + form.resetFields();
  184 + };
  185 + }, []);
  186 + var store = useMemo(function () {
  187 + return _objectSpread(_objectSpread({}, valuesThatWillChange), {}, {
  188 + globalProps: globalProps
  189 + }, rest);
  190 + }, [JSON.stringify(flatten), JSON.stringify(formData), JSON.stringify(errorFields), JSON.stringify(globalProps)]); // 不常用的context单独放一个地方
  191 +
  192 + var store2 = useMemo(function () {
  193 + return {
  194 + displayType: displayType,
  195 + theme: theme,
  196 + column: _column,
  197 + debounceInput: debounceInput,
  198 + debug: debug,
  199 + labelWidth: labelWidth,
  200 + locale: locale,
  201 + readOnly: readOnly,
  202 + disabled: disabled,
  203 + allCollapsed: allCollapsed,
  204 + showValidate: showValidate
  205 + };
  206 + }, [displayType, theme, _column, debounceInput, debug, labelWidth, locale, readOnly, disabled, allCollapsed, showValidate]);
  207 + var tools = useMemo(function () {
  208 + return _objectSpread({
  209 + widgets: _objectSpread(_objectSpread({}, defaultWidgets), widgets),
  210 + mapping: _objectSpread(_objectSpread({}, defaultMapping), mapping),
  211 + onValuesChange: onValuesChange
  212 + }, form);
  213 + }, []);
  214 + useEffect(function () {
  215 + // 需要外部校验的情况,此时 submitting 还是 false
  216 + if (outsideValidating === true) {
  217 + Promise.resolve(beforeFinish(_objectSpread({
  218 + data: submitData,
  219 + schema: schema,
  220 + errors: errorFields
  221 + }, config))).then(function (error) {
  222 + if (error) {
  223 + setErrorFields(error);
  224 + }
  225 +
  226 + endValidating();
  227 + });
  228 + return;
  229 + } // 如果validation结束,submitting开始
  230 +
  231 +
  232 + if (isValidating === false && isSubmitting === true) {
  233 + endSubmitting();
  234 + onFinish(submitData, errorFields);
  235 +
  236 + if (typeof logOnSubmit === 'function') {
  237 + var start = sessionStorage.getItem('FORM_START');
  238 + var mount = sessionStorage.getItem('FORM_MOUNT_TIME');
  239 + var numberOfSubmits = Number(sessionStorage.getItem('NUMBER_OF_SUBMITS')) + 1;
  240 + var end = new Date().getTime();
  241 + var failedAttempts = Number(sessionStorage.getItem('FAILED_ATTEMPTS'));
  242 +
  243 + if (errorFields.length > 0) {
  244 + failedAttempts = failedAttempts + 1;
  245 + }
  246 +
  247 + var logParams = {
  248 + formMount: yymmdd(mount),
  249 + ms: end - start,
  250 + duration: msToTime(end - start),
  251 + numberOfSubmits: numberOfSubmits,
  252 + failedAttempts: failedAttempts,
  253 + url: location.href,
  254 + formData: JSON.stringify(submitData),
  255 + errors: JSON.stringify(errorFields),
  256 + schema: JSON.stringify(schema)
  257 + };
  258 +
  259 + if (id) {
  260 + logParams.id = id;
  261 + }
  262 +
  263 + logOnSubmit(logParams);
  264 + sessionStorage.setItem('FORM_START', end);
  265 + sessionStorage.setItem('NUMBER_OF_SUBMITS', numberOfSubmits);
  266 + sessionStorage.setItem('FAILED_ATTEMPTS', failedAttempts);
  267 + }
  268 + }
  269 + }, [isValidating, isSubmitting, outsideValidating]); // TODO: fk doesn't work
  270 +
  271 + var sizeCls = '';
  272 +
  273 + if (size === 'small') {
  274 + sizeCls = 'fr-form-small';
  275 + } else if (size === 'large') {
  276 + sizeCls = 'fr-form-large';
  277 + }
  278 +
  279 + var rootProps = {
  280 + className: "fr-container ".concat(sizeCls, " ").concat(className || '')
  281 + };
  282 +
  283 + if (style && _typeof(style) === 'object') {
  284 + rootProps.style = style;
  285 + }
  286 +
  287 + if (id && ['number', 'string'].indexOf(_typeof(id)) > -1) {
  288 + rootProps.id = id;
  289 + }
  290 +
  291 + var watchList = Object.keys(watch);
29 return /*#__PURE__*/React.createElement(_ConfigProvider, _extends({ 292 return /*#__PURE__*/React.createElement(_ConfigProvider, _extends({
30 locale: zhCN 293 locale: zhCN
31 - }, configProvider), /*#__PURE__*/React.createElement(FRCore, _extends({  
32 - widgets: _objectSpread(_objectSpread({}, defaultWidgets), widgets)  
33 - }, rest))); 294 + }, configProvider), /*#__PURE__*/React.createElement(StoreCtx.Provider, {
  295 + value: store
  296 + }, /*#__PURE__*/React.createElement(Store2Ctx.Provider, {
  297 + value: store2
  298 + }, /*#__PURE__*/React.createElement(Ctx.Provider, {
  299 + value: tools
  300 + }, /*#__PURE__*/React.createElement("div", rootProps, debug ? /*#__PURE__*/React.createElement("div", {
  301 + className: "mv2 bg-black-05 pa2 br2"
  302 + }, /*#__PURE__*/React.createElement("div", {
  303 + style: {
  304 + display: 'flex'
  305 + }
  306 + }, /*#__PURE__*/React.createElement("span", null, "formData:"), /*#__PURE__*/React.createElement("span", {
  307 + style: {
  308 + display: 'inline-block',
  309 + wordBreak: 'break-all',
  310 + maxWidth: 600
  311 + }
  312 + }, JSON.stringify(form.formData))), /*#__PURE__*/React.createElement("div", null, 'errorFields:' + JSON.stringify(form.errorFields)), /*#__PURE__*/React.createElement("div", null, 'touchedKeys:' + JSON.stringify(form.touchedKeys)), /*#__PURE__*/React.createElement("div", null, 'allTouched:' + JSON.stringify(form.allTouched)), /*#__PURE__*/React.createElement("div", null, 'descriptor:' + JSON.stringify(window.descriptor))) : null, watchList.length > 0 ? watchList.map(function (item, idx) {
  313 + return /*#__PURE__*/React.createElement(Watcher, {
  314 + key: idx.toString(),
  315 + watchKey: item,
  316 + watch: watch,
  317 + formData: formData,
  318 + firstMount: firstMount
  319 + });
  320 + }) : null, /*#__PURE__*/React.createElement(Core, {
  321 + debugCss: debugCss
  322 + }))))));
  323 +}
  324 +
  325 +export { createWidget } from './createWidget';
  326 +
  327 +var Wrapper = function Wrapper(props) {
  328 + var _props$isOldVersion = props.isOldVersion,
  329 + isOldVersion = _props$isOldVersion === void 0 ? true : _props$isOldVersion,
  330 + schema = props.schema,
  331 + rest = _objectWithoutProperties(props, _excluded3);
  332 +
  333 + var _schema = useRef(schema);
  334 +
  335 + if (isOldVersion) {
  336 + _schema.current = updateSchemaToNewVersion(schema);
  337 + }
  338 +
  339 + return /*#__PURE__*/React.createElement(App, _extends({
  340 + schema: _schema.current
  341 + }, rest));
34 }; 342 };
35 343
36 -export default FR;  
  344 +export default Wrapper;
  345 +
  346 +var Watcher = function Watcher(_ref2) {
  347 + var watchKey = _ref2.watchKey,
  348 + watch = _ref2.watch,
  349 + formData = _ref2.formData,
  350 + firstMount = _ref2.firstMount;
  351 + var value = getValueByPath(formData, watchKey);
  352 + var watchObj = watch[watchKey];
  353 + useEffect(function () {
  354 + var runWatcher = function runWatcher() {
  355 + if (typeof watchObj === 'function') {
  356 + try {
  357 + watchObj(value);
  358 + } catch (error) {
  359 + console.log("".concat(watchKey, "\u5BF9\u5E94\u7684watch\u51FD\u6570\u6267\u884C\u62A5\u9519\uFF1A"), error);
  360 + }
  361 + } else if (watchObj && typeof watchObj.handler === 'function') {
  362 + try {
  363 + watchObj.handler(value);
  364 + } catch (error) {
  365 + console.log("".concat(watchKey, "\u5BF9\u5E94\u7684watch\u51FD\u6570\u6267\u884C\u62A5\u9519\uFF1A"), error);
  366 + }
  367 + }
  368 + };
  369 +
  370 + if (firstMount) {
  371 + var immediate = watchObj && watchObj.immediate;
  372 +
  373 + if (immediate) {
  374 + runWatcher();
  375 + }
  376 + } else {
  377 + runWatcher();
  378 + }
  379 + }, [JSON.stringify(value), firstMount]);
  380 + return null;
  381 +};
es/processData.js renamed from es/form-render-core/src/processData.js
es/useDebounce.js renamed from es/form-render-core/src/useDebounce.js
es/useForm.js renamed from es/form-render-core/src/useForm.js
@@ -65,6 +65,8 @@ var useForm = function useForm(props) { @@ -65,6 +65,8 @@ var useForm = function useForm(props) {
65 // 是否所有表单元素都被碰过了(一键开关,用于提交的时候,默认所有都被touch了) 65 // 是否所有表单元素都被碰过了(一键开关,用于提交的时候,默认所有都被touch了)
66 touchedKeys: [], 66 touchedKeys: [],
67 // 碰过的key(用于submit之前,判断哪些被碰过了) 67 // 碰过的key(用于submit之前,判断哪些被碰过了)
  68 + flatten: {},
  69 + // schema 的转换结构,便于处理
68 finalFlatten: {}, 70 finalFlatten: {},
69 // 表达式等被处理过的flatten,用于渲染 71 // 表达式等被处理过的flatten,用于渲染
70 firstMount: true 72 firstMount: true
@@ -110,11 +112,13 @@ var useForm = function useForm(props) { @@ -110,11 +112,13 @@ var useForm = function useForm(props) {
110 isEditing = state.isEditing, 112 isEditing = state.isEditing,
111 allTouched = state.allTouched, 113 allTouched = state.allTouched,
112 touchedKeys = state.touchedKeys, 114 touchedKeys = state.touchedKeys,
  115 + flatten = state.flatten,
113 finalFlatten = state.finalFlatten, 116 finalFlatten = state.finalFlatten,
114 firstMount = state.firstMount; 117 firstMount = state.firstMount;
115 _errorFields.current = errorFields; 118 _errorFields.current = errorFields;
116 _outErrorFields.current = outErrorFields; 119 _outErrorFields.current = outErrorFields;
117 _touchedKeys.current = touchedKeys; 120 _touchedKeys.current = touchedKeys;
  121 + _flatten.current = flatten;
118 _finalFlatten.current = finalFlatten; 122 _finalFlatten.current = finalFlatten;
119 var dataFromOutside = props && props.hasOwnProperty('formData'); 123 var dataFromOutside = props && props.hasOwnProperty('formData');
120 var formData = dataFromOutside ? _formData : innerData; // 生成一个基础结构,确保对象内的必填元素也被校验 124 var formData = dataFromOutside ? _formData : innerData; // 生成一个基础结构,确保对象内的必填元素也被校验
@@ -137,39 +141,55 @@ var useForm = function useForm(props) { @@ -137,39 +141,55 @@ var useForm = function useForm(props) {
137 } 141 }
138 }, [JSON.stringify(_errorFields.current), JSON.stringify(_outErrorFields.current)]); 142 }, [JSON.stringify(_errorFields.current), JSON.stringify(_outErrorFields.current)]);
139 useEffect(function () { 143 useEffect(function () {
140 - if (schemaRef.current) {  
141 - var newFlatten = clone(_flatten.current);  
142 -  
143 - if (firstMount) {  
144 - _flatten.current = flattenSchema(schemaRef.current);  
145 - setState({  
146 - firstMount: false  
147 - });  
148 - } else {  
149 - // 统一的处理expression  
150 - Object.entries(_flatten.current).forEach(function (_ref2) {  
151 - var _ref3 = _slicedToArray(_ref2, 2),  
152 - path = _ref3[0],  
153 - info = _ref3[1];  
154 -  
155 - if (schemaContainsExpression(info.schema)) {  
156 - var arrayLikeIndex = path.indexOf(']');  
157 - var isArrayItem = arrayLikeIndex > -1 && arrayLikeIndex < path.length - 1;  
158 - var hasRootValue = JSON.stringify(info.schema).indexOf('rootValue') > -1;  
159 -  
160 - if (isArrayItem && hasRootValue) {// do nothing  
161 - } else {  
162 - newFlatten[path].schema = parseAllExpression(info.schema, _data.current, path);  
163 - }  
164 - }  
165 - });  
166 - } 144 + if (schemaRef.current && firstMount) {
  145 + var _flatten2 = flattenSchema(schemaRef.current);
167 146
168 setState({ 147 setState({
169 - finalFlatten: newFlatten 148 + flatten: _flatten2,
  149 + firstMount: false
170 }); 150 });
171 } 151 }
172 - }, [JSON.stringify(schemaRef.current), JSON.stringify(_data.current), firstMount]); // All form methods are down here ---------------------------------------------------------------- 152 + }, [JSON.stringify(schemaRef.current), firstMount]); // 统一的处理expression
  153 +
  154 + useEffect(function () {
  155 + if (firstMount) {
  156 + return;
  157 + }
  158 +
  159 + var newFlatten = clone(_flatten.current);
  160 + Object.entries(_flatten.current).forEach(function (_ref2) {
  161 + var _ref3 = _slicedToArray(_ref2, 2),
  162 + path = _ref3[0],
  163 + info = _ref3[1];
  164 +
  165 + if (schemaContainsExpression(info.schema)) {
  166 + var arrayLikeIndex = path.indexOf(']');
  167 + var isArrayItem = arrayLikeIndex > -1 && arrayLikeIndex < path.length - 1;
  168 + var hasRootValue = JSON.stringify(info.schema).indexOf('rootValue') > -1;
  169 +
  170 + if (isArrayItem && hasRootValue) {// do nothing
  171 + } else {
  172 + newFlatten[path].schema = parseAllExpression(info.schema, _data.current, path);
  173 + }
  174 + }
  175 + });
  176 + setState({
  177 + finalFlatten: newFlatten
  178 + });
  179 + }, [JSON.stringify(_flatten.current), JSON.stringify(_data.current), firstMount]);
  180 + useEffect(function () {
  181 + if (firstMount) return;
  182 + validateAll({
  183 + formData: _data.current,
  184 + flatten: _finalFlatten.current,
  185 + isRequired: allTouched,
  186 + touchedKeys: _touchedKeys.current,
  187 + locale: localeRef.current,
  188 + validateMessages: validateMessagesRef.current
  189 + }).then(function (res) {
  190 + _setErrors(res);
  191 + });
  192 + }, [JSON.stringify(_data.current)]); // All form methods are down here ----------------------------------------------------------------
173 // 两个兼容 0.x 的函数 193 // 两个兼容 0.x 的函数
174 194
175 var _setData = function _setData(data) { 195 var _setData = function _setData(data) {
@@ -180,8 +200,7 @@ var useForm = function useForm(props) { @@ -180,8 +200,7 @@ var useForm = function useForm(props) {
180 formData: data 200 formData: data
181 }); 201 });
182 } 202 }
183 - }; // Allow function to get the old value  
184 - 203 + };
185 204
186 var _setErrors = function _setErrors(errors) { 205 var _setErrors = function _setErrors(errors) {
187 if (typeof _onValidate === 'function') { 206 if (typeof _onValidate === 'function') {
@@ -192,18 +211,9 @@ var useForm = function useForm(props) { @@ -192,18 +211,9 @@ var useForm = function useForm(props) {
192 _onValidate(oldFormatErrors); 211 _onValidate(oldFormatErrors);
193 } 212 }
194 213
195 - if (typeof errors === 'function') {  
196 - setState(function (_ref4) {  
197 - var errorFields = _ref4.errorFields;  
198 - return {  
199 - errorFields: errors(errorFields)  
200 - };  
201 - });  
202 - } else {  
203 - setState({  
204 - errorFields: errors  
205 - });  
206 - } 214 + setState({
  215 + errorFields: errors
  216 + });
207 }; 217 };
208 218
209 var setFirstMount = function setFirstMount(value) { 219 var setFirstMount = function setFirstMount(value) {
@@ -262,12 +272,12 @@ var useForm = function useForm(props) { @@ -262,12 +272,12 @@ var useForm = function useForm(props) {
262 // ] 272 // ]
263 273
264 274
265 - var syncStuff = function syncStuff(_ref5) {  
266 - var schema = _ref5.schema,  
267 - locale = _ref5.locale,  
268 - validateMessages = _ref5.validateMessages,  
269 - beforeFinish = _ref5.beforeFinish,  
270 - removeHiddenData = _ref5.removeHiddenData; 275 + var syncStuff = function syncStuff(_ref4) {
  276 + var schema = _ref4.schema,
  277 + locale = _ref4.locale,
  278 + validateMessages = _ref4.validateMessages,
  279 + beforeFinish = _ref4.beforeFinish,
  280 + removeHiddenData = _ref4.removeHiddenData;
271 schemaRef.current = schema; 281 schemaRef.current = schema;
272 localeRef.current = locale; 282 localeRef.current = locale;
273 validateMessagesRef.current = validateMessages; 283 validateMessagesRef.current = validateMessages;
@@ -277,11 +287,11 @@ var useForm = function useForm(props) { @@ -277,11 +287,11 @@ var useForm = function useForm(props) {
277 }; 287 };
278 288
279 var setSchema = function setSchema(settings) { 289 var setSchema = function setSchema(settings) {
280 - var newFlatten = clone(_finalFlatten.current); 290 + var newFlatten = clone(_flatten.current);
281 291
282 try { 292 try {
283 Object.keys(settings).forEach(function (path) { 293 Object.keys(settings).forEach(function (path) {
284 - if (!_finalFlatten.current[path]) { 294 + if (!_flatten.current[path]) {
285 console.error("path\uFF1A'".concat(path, "' \u4E0D\u5B58\u5728(form.setSchemaByPath)")); 295 console.error("path\uFF1A'".concat(path, "' \u4E0D\u5B58\u5728(form.setSchemaByPath)"));
286 } else { 296 } else {
287 var newSchema = settings[path]; 297 var newSchema = settings[path];
@@ -292,30 +302,30 @@ var useForm = function useForm(props) { @@ -292,30 +302,30 @@ var useForm = function useForm(props) {
292 } 302 }
293 }); 303 });
294 setState({ 304 setState({
295 - finalFlatten: newFlatten 305 + flatten: newFlatten
296 }); 306 });
297 - _finalFlatten.current = newFlatten; 307 + _flatten.current = newFlatten;
298 } catch (error) { 308 } catch (error) {
299 console.error(error, 'setSchema'); 309 console.error(error, 'setSchema');
300 } 310 }
301 }; 311 };
302 312
303 var setSchemaByPath = function setSchemaByPath(path, newSchema) { 313 var setSchemaByPath = function setSchemaByPath(path, newSchema) {
304 - if (!_finalFlatten.current[path]) { 314 + if (!_flatten.current[path]) {
305 console.error("path\uFF1A'".concat(path, "' \u4E0D\u5B58\u5728(form.setSchemaByPath)")); 315 console.error("path\uFF1A'".concat(path, "' \u4E0D\u5B58\u5728(form.setSchemaByPath)"));
306 return; 316 return;
307 } 317 }
308 318
309 - var newFlatten = clone(_finalFlatten.current); 319 + var newFlatten = clone(_flatten.current);
310 320
311 try { 321 try {
312 var _newSchema = typeof newSchema === 'function' ? newSchema(newFlatten[path].schema) : newSchema; 322 var _newSchema = typeof newSchema === 'function' ? newSchema(newFlatten[path].schema) : newSchema;
313 323
314 newFlatten[path].schema = _objectSpread(_objectSpread({}, newFlatten[path].schema), _newSchema); 324 newFlatten[path].schema = _objectSpread(_objectSpread({}, newFlatten[path].schema), _newSchema);
315 setState({ 325 setState({
316 - finalFlatten: newFlatten 326 + flatten: newFlatten
317 }); 327 });
318 - _finalFlatten.current = newFlatten; 328 + _flatten.current = newFlatten;
319 } catch (error) { 329 } catch (error) {
320 console.error(error, 'setSchemaByPath'); 330 console.error(error, 'setSchemaByPath');
321 } 331 }
@@ -323,7 +333,7 @@ var useForm = function useForm(props) { @@ -323,7 +333,7 @@ var useForm = function useForm(props) {
323 333
324 var getSchemaByPath = function getSchemaByPath(path) { 334 var getSchemaByPath = function getSchemaByPath(path) {
325 try { 335 try {
326 - return _finalFlatten.current[path].schema; 336 + return _flatten.current[path].schema;
327 } catch (error) { 337 } catch (error) {
328 console.log(error, 'getSchemaByPath'); 338 console.log(error, 'getSchemaByPath');
329 return {}; 339 return {};
@@ -365,7 +375,7 @@ var useForm = function useForm(props) { @@ -365,7 +375,7 @@ var useForm = function useForm(props) {
365 }; 375 };
366 376
367 var setValues = function setValues(newFormData) { 377 var setValues = function setValues(newFormData) {
368 - var newData = transformDataWithBind2(newFormData, _finalFlatten.current); 378 + var newData = transformDataWithBind2(newFormData, _flatten.current);
369 379
370 _setData(newData); 380 _setData(newData);
371 }; 381 };
@@ -380,10 +390,10 @@ var useForm = function useForm(props) { @@ -380,10 +390,10 @@ var useForm = function useForm(props) {
380 return validateAll({ 390 return validateAll({
381 formData: _data.current, 391 formData: _data.current,
382 flatten: _finalFlatten.current, 392 flatten: _finalFlatten.current,
383 - options: {  
384 - locale: localeRef.current,  
385 - validateMessages: validateMessagesRef.current  
386 - } 393 + touchedKeys: [],
  394 + isRequired: true,
  395 + locale: localeRef.current,
  396 + validateMessages: validateMessagesRef.current
387 }).then(function (errors) { 397 }).then(function (errors) {
388 setState({ 398 setState({
389 errorFields: errors 399 errorFields: errors
@@ -426,13 +436,13 @@ var useForm = function useForm(props) { @@ -426,13 +436,13 @@ var useForm = function useForm(props) {
426 }); 436 });
427 }; 437 };
428 438
429 - var resetFields = function resetFields(options) { 439 + var resetFields = function resetFields() {
430 setState({ 440 setState({
431 - formData: (options === null || options === void 0 ? void 0 : options.formData) || {},  
432 - submitData: (options === null || options === void 0 ? void 0 : options.submitData) || {},  
433 - errorFields: (options === null || options === void 0 ? void 0 : options.errorFields) || [],  
434 - touchedKeys: (options === null || options === void 0 ? void 0 : options.touchedKeys) || [],  
435 - allTouched: (options === null || options === void 0 ? void 0 : options.allTouched) || false 441 + formData: {},
  442 + submitData: {},
  443 + errorFields: [],
  444 + touchedKeys: [],
  445 + allTouched: false
436 }); 446 });
437 }; 447 };
438 448
@@ -492,9 +502,7 @@ var useForm = function useForm(props) { @@ -492,9 +502,7 @@ var useForm = function useForm(props) {
492 setFirstMount: setFirstMount, 502 setFirstMount: setFirstMount,
493 // logs 503 // logs
494 logOnMount: logOnMount, 504 logOnMount: logOnMount,
495 - logOnSubmit: logOnSubmit,  
496 - // inner api, DON'T USE  
497 - _setErrors: _setErrors 505 + logOnSubmit: logOnSubmit
498 }; 506 };
499 return form; 507 return form;
500 }; 508 };