@zat-design/sisyphus-react 3.13.2-beta.4 → 3.13.2-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import React from 'react';
2
- import { ModifiedFormInstance } from '../ProForm/utils/useForm';
3
- type Forms = Record<string, ModifiedFormInstance<any>>;
2
+ import { ModifiedFormInstanceType } from '../ProForm/utils/useForm';
3
+ type Forms = Record<string, ModifiedFormInstanceType<any>>;
4
4
  export declare const FormsContext: React.Context<Forms>;
5
5
  /**
6
6
  * @param formKey 表单实例key
@@ -38,12 +38,25 @@ var FormFooter = function FormFooter(props) {
38
38
  }
39
39
  }, [formId]);
40
40
  var _onOk = function _onOk() {
41
+ var _modifiedForm$__INTER;
41
42
  if (formId) {
42
43
  var values = form.getFieldsValue();
43
44
  searchCache[formId] = values;
44
45
  window.sessionStorage.setItem(PRO_FORM_CACHE, JSON.stringify(searchCache));
45
46
  }
46
- onOk();
47
+ // 支持 stopOnFirstError
48
+ // @ts-ignore 使用类型断言处理自定义属性
49
+ var modifiedForm = form;
50
+ if ((_modifiedForm$__INTER = modifiedForm.__INTERNAL_CONFIG__) === null || _modifiedForm$__INTER === void 0 ? void 0 : _modifiedForm$__INTER.stopOnFirstError) {
51
+ // 使用自定义验证逻辑
52
+ form.validateFields().then(function () {
53
+ onOk();
54
+ }).catch(function () {
55
+ // 验证失败,不执行 onOk
56
+ });
57
+ } else {
58
+ onOk();
59
+ }
47
60
  };
48
61
  var _onCancel = function _onCancel() {
49
62
  if (formId && searchCache[formId]) {
@@ -1,4 +1,5 @@
1
1
  import { ButtonProps, ColProps, FormInstance } from 'antd';
2
+ import { ModifiedFormInstanceType } from '../../utils/useForm';
2
3
  export interface ButtonItem extends ButtonProps {
3
4
  children?: any;
4
5
  }
@@ -15,7 +16,7 @@ export interface FooterRenderType {
15
16
  footer?: FooterButtonType;
16
17
  confirmLoading?: boolean;
17
18
  formId?: string;
18
- form: FormInstance;
19
+ form: FormInstance | ModifiedFormInstanceType<any>;
19
20
  }
20
21
  /**
21
22
  * 兼容旧命名导出
@@ -12,7 +12,7 @@ import _Form from "antd/es/form";
12
12
  import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
13
13
  import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
14
14
  import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
15
- var _excluded = ["labelWidth", "hiddenNames", "trim", "upperCase", "className", "rules", "required", "labelRequired", "tooltip"];
15
+ var _excluded = ["labelWidth", "hiddenNames", "trim", "upperCase", "className", "rules", "required", "labelRequired", "tooltip", "validateFirst"];
16
16
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
17
17
  /* eslint-disable prefer-destructuring */
18
18
 
@@ -64,6 +64,8 @@ var Render = function Render(props) {
64
64
  required = formItemProps.required,
65
65
  labelRequired = formItemProps.labelRequired,
66
66
  tooltip = formItemProps.tooltip,
67
+ _formItemProps$valida = formItemProps.validateFirst,
68
+ validateFirst = _formItemProps$valida === void 0 ? true : _formItemProps$valida,
67
69
  otherFormItemProps = _objectWithoutProperties(formItemProps, _excluded);
68
70
  // 更新show & disabled & rules
69
71
  var _useShouldUpdate = useShouldUpdate({
@@ -156,7 +158,7 @@ var Render = function Render(props) {
156
158
  required: false
157
159
  } : null, _objectSpread({}, isTrim(type, trim, useProConfig())), // 优先取传进来的,其次取ProConfigProvider配置的
158
160
  _objectSpread({}, isUpperCase(type, upperCase)), {
159
- validateFirst: true
161
+ validateFirst: validateFirst
160
162
  },
161
163
  // 当某一规则校验不通过时,是否停止剩下的规则的校验
162
164
  {
@@ -11,17 +11,17 @@ import "antd/es/space/style";
11
11
  import _Space from "antd/es/space";
12
12
  import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
13
13
  import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
14
- var _excluded = ["mode", "span", "disabled", "isView", "columns", "footer", "onOk", "okText", "onCancel", "confirmLoading", "cancelText", "form", "children", "rowProps", "className", "expand", "expandOpen", "expandOpenChange", "viewEmpty", "labelAlign", "labelWidth", "onValuesChange", "onFinish", "diffConfig", "submitOnEnter", "clearNotShow", "initialValues", "requiredOnView", "formId", "required", "formKey", "globalControl", "scrollToError", "optimize", "desensitizationKey"];
14
+ var _excluded = ["mode", "span", "disabled", "isView", "columns", "footer", "onOk", "okText", "onCancel", "confirmLoading", "cancelText", "form", "children", "rowProps", "className", "expand", "expandOpen", "expandOpenChange", "viewEmpty", "labelAlign", "labelWidth", "onValuesChange", "onFinish", "diffConfig", "submitOnEnter", "clearNotShow", "initialValues", "requiredOnView", "formId", "required", "formKey", "globalControl", "scrollToError", "optimize", "desensitizationKey", "stopOnFirstError"];
15
15
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
16
16
  import { DoubleLeftOutlined } from '@ant-design/icons';
17
17
  import classnames from 'classnames';
18
- import React, { forwardRef, useImperativeHandle, useMemo } from 'react';
18
+ import React, { forwardRef, useImperativeHandle, useMemo, useEffect } from 'react';
19
19
  import { isObject, merge, omit } from 'lodash';
20
20
  import { FormFooter, InputRange, ProAddress, ProCascader, ProCertNo, ProCertValidity, ProCombination, ProModalSelect, ProNumberRange, ProRangeBox, ProTimeLimit, transferAddressInfoToRegion, ProUpload, ProTreeModal, ProTree, EnumSelect } from './components';
21
21
  import RenderFields from './components/render/RenderFields';
22
22
  import { useProConfig } from '../ProConfigProvider';
23
23
  import { useProDrawerFormContext } from '../ProDrawerForm';
24
- import { getLayout, splitNameStr, useControlled, initialValuesToNames, filterInternalFields } from './utils/index';
24
+ import { getLayout, splitNameStr, useControlled, initialValuesToNames, filterInternalFields, getFormFieldPaths } from './utils/index';
25
25
  import { useForm } from './utils/useForm';
26
26
  import { useFieldProps } from './utils/useFieldProps';
27
27
  import locale from '../locale';
@@ -73,6 +73,8 @@ var ProForm = function ProForm(props, ref) {
73
73
  optimize = _props$optimize === void 0 ? false : _props$optimize,
74
74
  _props$desensitizatio = props.desensitizationKey,
75
75
  desensitizationKey = _props$desensitizatio === void 0 ? 'zat-design-pro-component-desensitization' : _props$desensitizatio,
76
+ _props$stopOnFirstErr = props.stopOnFirstError,
77
+ stopOnFirstError = _props$stopOnFirstErr === void 0 ? false : _props$stopOnFirstErr,
76
78
  otherProps = _objectWithoutProperties(props, _excluded);
77
79
  var config = useProConfig('ProForm');
78
80
  // source: 用于区分是哪个组件调用,用于错误提示
@@ -91,6 +93,14 @@ var ProForm = function ProForm(props, ref) {
91
93
  }),
92
94
  _useForm2 = _slicedToArray(_useForm, 1),
93
95
  form = _useForm2[0];
96
+ // 保存内部配置
97
+ useEffect(function () {
98
+ if (!form.__INTERNAL_CONFIG__) {
99
+ form.__INTERNAL_CONFIG__ = {};
100
+ }
101
+ form.__INTERNAL_CONFIG__.fields = getFormFieldPaths(form);
102
+ form.__INTERNAL_CONFIG__.stopOnFirstError = stopOnFirstError;
103
+ }, [stopOnFirstError, form]);
94
104
  var _useControlled = useControlled({
95
105
  value: expandOpen,
96
106
  onChange: expandOpenChange
@@ -101,6 +101,8 @@ export interface ProFormType<Values = any> extends FormProps<Values> {
101
101
  optimize?: boolean;
102
102
  /** 全局脱敏开关的key、默认 zat-design-pro-component-desensitization */
103
103
  desensitizationKey?: string;
104
+ /** 是否在遇到第一个错误时停止验证 */
105
+ stopOnFirstError?: boolean;
104
106
  }
105
107
  export interface TransformType<T = any> {
106
108
  normalize?: (value: StoreValue, prevValue: StoreValue, allValues: Store) => StoreValue;
@@ -1,4 +1,4 @@
1
- import { ColProps, FormProps } from 'antd';
1
+ import { ColProps, FormProps, FormInstance } from 'antd';
2
2
  import { InternalNamePath, NamePath } from 'antd/es/form/interface';
3
3
  interface transProps {
4
4
  formProps: FormProps;
@@ -95,6 +95,11 @@ export declare const findOptionByValue: (treeData: any[], value: string | number
95
95
  export declare const equalDependencies: (dependencies: any, prevValues: any, currentValues: any) => any;
96
96
  /** 解析namePath */
97
97
  export declare const parseNamePath: (input: string) => any;
98
- /** 解析namePath */
98
+ /**
99
+ * 获取表单所有字段路径的简化函数
100
+ * @param form 表单实例
101
+ * @returns 所有字段路径数组
102
+ */
103
+ export declare const getFormFieldPaths: (form: FormInstance) => any[];
99
104
  export declare function findNamesKeyInArray(arr: string[], key: string): string | null;
100
105
  export {};
@@ -413,7 +413,25 @@ export var parseNamePath = function parseNamePath(input) {
413
413
  });
414
414
  return [result];
415
415
  };
416
- /** 解析namePath */
416
+ /**
417
+ * 获取表单所有字段路径的简化函数
418
+ * @param form 表单实例
419
+ * @returns 所有字段路径数组
420
+ */
421
+ export var getFormFieldPaths = function getFormFieldPaths(form) {
422
+ try {
423
+ // @ts-ignore
424
+ var _form$getInternalHook = form.getInternalHooks('RC_FORM_INTERNAL_HOOKS'),
425
+ getFields = _form$getInternalHook.getFields;
426
+ var allFields = getFields();
427
+ return allFields.map(function (field) {
428
+ return field.name;
429
+ });
430
+ } catch (error) {
431
+ console.error('获取表单字段失败:', error);
432
+ return [];
433
+ }
434
+ };
417
435
  export function findNamesKeyInArray(arr, key) {
418
436
  var _iterator = _createForOfIteratorHelper(arr),
419
437
  _step;
@@ -1,12 +1,17 @@
1
1
  import { FormInstance } from 'antd';
2
2
  import { NamePath } from 'antd/es/form/interface';
3
3
  import { ValuedNotifyInfo } from 'rc-field-form/es/interface';
4
- export type ModifiedFormInstance<T> = FormInstance<T> & {
4
+ export type ModifiedFormInstanceType<T> = FormInstance<T> & {
5
5
  isModified?: boolean;
6
6
  /** 默认清空设置值的报错状态 */
7
7
  setFieldValue: (name: NamePath, value: any, info?: ValuedNotifyInfo) => void;
8
8
  formKey?: string;
9
9
  _init?: boolean;
10
+ __INTERNAL_CONFIG__?: {
11
+ fields?: any[];
12
+ stopOnFirstError?: boolean;
13
+ [key: string]: any;
14
+ };
10
15
  };
11
16
  export interface FormInstanceOption {
12
17
  scrollToError?: boolean;
@@ -14,4 +19,4 @@ export interface FormInstanceOption {
14
19
  formKey?: string;
15
20
  source?: string;
16
21
  }
17
- export declare const useForm: <T>(originForm?: ModifiedFormInstance<T> | FormInstanceOption, options?: FormInstanceOption) => [ModifiedFormInstance<T>];
22
+ export declare const useForm: <T>(originForm?: ModifiedFormInstanceType<T> | FormInstanceOption, options?: FormInstanceOption) => [ModifiedFormInstanceType<T>];
@@ -1,12 +1,13 @@
1
- import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
2
1
  import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
3
2
  import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
3
+ import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
4
+ import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
4
5
  import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
5
6
  import "antd/es/form/style";
6
7
  import _Form from "antd/es/form";
7
8
  import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
8
9
  import { useContext } from 'react';
9
- import { filterInternalFields } from './index';
10
+ import { filterInternalFields, getFormFieldPaths } from './index';
10
11
  import { handleScrollToError as handleScrollToErrorProEditTable } from '../../ProEditTable/utils/tools';
11
12
  import { FormsContext } from '../../FormsProvider';
12
13
  export var useForm = function useForm(originForm, options) {
@@ -50,10 +51,19 @@ export var useForm = function useForm(originForm, options) {
50
51
  var _validateFields = /*#__PURE__*/function () {
51
52
  var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(nameList) {
52
53
  var _rest$,
54
+ _form$__INTERNAL_CONF,
53
55
  _len,
54
56
  rest,
55
57
  _key,
56
58
  isRecursive,
59
+ stopOnFirstError,
60
+ allFields,
61
+ _iterator,
62
+ _step,
63
+ field,
64
+ _options2,
65
+ _error$errorFields,
66
+ _error$errorFields$,
57
67
  validateNames,
58
68
  _form$getInternalHook,
59
69
  getFields,
@@ -61,8 +71,8 @@ export var useForm = function useForm(originForm, options) {
61
71
  _document,
62
72
  tablePagination,
63
73
  _tablePagination$clic,
64
- _error$errorFields,
65
- _error$errorFields$,
74
+ _error$errorFields2,
75
+ _error$errorFields$2,
66
76
  _args = arguments;
67
77
  return _regeneratorRuntime().wrap(function _callee$(_context) {
68
78
  while (1) switch (_context.prev = _context.next) {
@@ -71,11 +81,68 @@ export var useForm = function useForm(originForm, options) {
71
81
  for (_len = _args.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
72
82
  rest[_key - 1] = _args[_key];
73
83
  }
74
- // @ts-ignore
75
84
  isRecursive = rest === null || rest === void 0 ? void 0 : (_rest$ = rest[0]) === null || _rest$ === void 0 ? void 0 : _rest$.recursive;
85
+ stopOnFirstError = form === null || form === void 0 ? void 0 : (_form$__INTERNAL_CONF = form.__INTERNAL_CONFIG__) === null || _form$__INTERNAL_CONF === void 0 ? void 0 : _form$__INTERNAL_CONF.stopOnFirstError; // 如果启用了 stopOnFirstError 且没有指定字段列表
86
+ if (!(stopOnFirstError && !nameList)) {
87
+ _context.next = 33;
88
+ break;
89
+ }
90
+ // 获取所有表单字段
91
+ allFields = getFormFieldPaths(form); // 单独验证每个字段
92
+ // eslint-disable-next-line no-restricted-syntax
93
+ _iterator = _createForOfIteratorHelper(allFields);
94
+ _context.prev = 7;
95
+ _iterator.s();
96
+ case 9:
97
+ if ((_step = _iterator.n()).done) {
98
+ _context.next = 24;
99
+ break;
100
+ }
101
+ field = _step.value;
102
+ _context.prev = 11;
103
+ // 创建不包含 stopOnFirstError 的选项
104
+ // @ts-ignore
105
+ _options2 = (rest === null || rest === void 0 ? void 0 : rest[0]) ? _objectSpread({}, rest[0]) : {};
106
+ delete _options2.stopOnFirstError;
107
+ // 验证单个字段
108
+ // eslint-disable-next-line no-await-in-loop
109
+ _context.next = 16;
110
+ return validateFields([field], _options2);
111
+ case 16:
112
+ _context.next = 22;
113
+ break;
114
+ case 18:
115
+ _context.prev = 18;
116
+ _context.t0 = _context["catch"](11);
117
+ // 遇到错误,滚动到错误位置
118
+ if (scrollToError && (_context.t0 === null || _context.t0 === void 0 ? void 0 : (_error$errorFields = _context.t0.errorFields) === null || _error$errorFields === void 0 ? void 0 : _error$errorFields.length)) {
119
+ form.scrollToField((_error$errorFields$ = _context.t0.errorFields[0]) === null || _error$errorFields$ === void 0 ? void 0 : _error$errorFields$.name, {
120
+ block: 'center',
121
+ behavior: 'smooth'
122
+ });
123
+ }
124
+ // 中止验证,抛出错误
125
+ throw _context.t0;
126
+ case 22:
127
+ _context.next = 9;
128
+ break;
129
+ case 24:
130
+ _context.next = 29;
131
+ break;
132
+ case 26:
133
+ _context.prev = 26;
134
+ _context.t1 = _context["catch"](7);
135
+ _iterator.e(_context.t1);
136
+ case 29:
137
+ _context.prev = 29;
138
+ _iterator.f();
139
+ return _context.finish(29);
140
+ case 32:
141
+ return _context.abrupt("return", form.getFieldsValue());
142
+ case 33:
76
143
  validateNames = []; // 前缀校验模式
77
144
  if (!isRecursive) {
78
- _context.next = 12;
145
+ _context.next = 42;
79
146
  break;
80
147
  }
81
148
  // @ts-ignore
@@ -92,13 +159,13 @@ export var useForm = function useForm(originForm, options) {
92
159
  }
93
160
  // @ts-ignore
94
161
  // delete rest[0].recursive;
95
- _context.next = 11;
162
+ _context.next = 41;
96
163
  return validateFields.apply(void 0, [validateNames].concat(rest)).then(function (values) {
97
164
  return filterInternalFields(values, optimize);
98
165
  });
99
- case 11:
166
+ case 41:
100
167
  return _context.abrupt("return", _context.sent);
101
- case 12:
168
+ case 42:
102
169
  // 解决,单个pro-edit-table的表单校验
103
170
  if ((nameList === null || nameList === void 0 ? void 0 : nameList.length) && !nameList.join('-').includes(',')) {
104
171
  tablePagination = document && ((_document = document) === null || _document === void 0 ? void 0 : _document.querySelector("#pro-edit-table-pagination-".concat(nameList.join('-'))));
@@ -106,28 +173,28 @@ export var useForm = function useForm(originForm, options) {
106
173
  tablePagination === null || tablePagination === void 0 ? void 0 : (_tablePagination$clic = tablePagination.click) === null || _tablePagination$clic === void 0 ? void 0 : _tablePagination$clic.call(tablePagination);
107
174
  }
108
175
  }
109
- _context.next = 15;
176
+ _context.next = 45;
110
177
  return validateFields.apply(void 0, [nameList].concat(rest)).then(function (values) {
111
178
  return nameList ? values : _getFieldsValue();
112
179
  });
113
- case 15:
180
+ case 45:
114
181
  return _context.abrupt("return", _context.sent);
115
- case 18:
116
- _context.prev = 18;
117
- _context.t0 = _context["catch"](0);
118
- if (scrollToError && (_context.t0 === null || _context.t0 === void 0 ? void 0 : (_error$errorFields = _context.t0.errorFields) === null || _error$errorFields === void 0 ? void 0 : _error$errorFields.length) && source === 'ProForm') {
119
- form.scrollToField((_error$errorFields$ = _context.t0.errorFields[0]) === null || _error$errorFields$ === void 0 ? void 0 : _error$errorFields$.name, {
182
+ case 48:
183
+ _context.prev = 48;
184
+ _context.t2 = _context["catch"](0);
185
+ if (scrollToError && (_context.t2 === null || _context.t2 === void 0 ? void 0 : (_error$errorFields2 = _context.t2.errorFields) === null || _error$errorFields2 === void 0 ? void 0 : _error$errorFields2.length) && source === 'ProForm') {
186
+ form.scrollToField((_error$errorFields$2 = _context.t2.errorFields[0]) === null || _error$errorFields$2 === void 0 ? void 0 : _error$errorFields$2.name, {
120
187
  block: 'center',
121
188
  behavior: 'smooth'
122
189
  });
123
190
  }
124
191
  handleScrollToErrorProEditTable();
125
- throw _context.t0;
126
- case 23:
192
+ throw _context.t2;
193
+ case 53:
127
194
  case "end":
128
195
  return _context.stop();
129
196
  }
130
- }, _callee, null, [[0, 18]]);
197
+ }, _callee, null, [[0, 48], [7, 26, 29, 32], [11, 18]]);
131
198
  }));
132
199
  return function _validateFields(_x) {
133
200
  return _ref2.apply(this, arguments);
@@ -175,8 +242,8 @@ export var useForm = function useForm(originForm, options) {
175
242
  form.getFieldsValue = _getFieldsValue;
176
243
  form.setFieldValue = _setFieldValue;
177
244
  form.setFieldsValue = _setFieldsValue;
178
- form.getFieldsValue = _getFieldsValue;
179
245
  form.validateFields = _validateFields;
180
246
  form.isModified = true;
247
+ form.__INTERNAL_CONFIG__ = {};
181
248
  return [form];
182
249
  };
@@ -1,6 +1,11 @@
1
- import { InternalNamePath, FormInstance, NamePath } from 'rc-field-form/es/interface';
1
+ import { FormInstance, NamePath } from 'rc-field-form/es/interface';
2
2
  export declare function toArray<T>(value?: T | T[] | null): T[];
3
- export declare function getNamePath(path: NamePath | null): InternalNamePath;
4
- export declare function stringify(value: any): string | number;
3
+ /**
4
+ * ProForm的useWatch hook,用于监听表单字段变化
5
+ * @param dependencies 监听的字段路径
6
+ * @param form 表单实例
7
+ * @param wait 防抖等待时间
8
+ * @returns 表单值
9
+ */
5
10
  declare function useWatch(dependencies: string | NamePath[], form?: FormInstance, wait?: number): any;
6
11
  export default useWatch;
@@ -1,93 +1,159 @@
1
+ import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
1
2
  import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
2
3
  import { debounce } from 'lodash';
3
- import { HOOK_MARK } from 'rc-field-form/es/FieldContext';
4
4
  import warning from 'rc-util/lib/warning';
5
5
  import { useState, useEffect, useRef, useMemo } from 'react';
6
+ import isEqual from 'lodash/isEqual';
6
7
  export function toArray(value) {
7
8
  if (value === undefined || value === null) {
8
9
  return [];
9
10
  }
10
11
  return Array.isArray(value) ? value : [value];
11
12
  }
12
- export function getNamePath(path) {
13
- return toArray(path);
13
+ // 从一个对象或Form值中获取特定路径的值
14
+ function get(source, path) {
15
+ if (!source || path.length === 0) {
16
+ return source;
17
+ }
18
+ var current = source;
19
+ for (var i = 0; i < path.length; i++) {
20
+ if (current === undefined || current === null) {
21
+ return undefined;
22
+ }
23
+ current = current[path[i]];
24
+ }
25
+ return current;
14
26
  }
15
- export function stringify(value) {
16
- try {
17
- return JSON.stringify(value);
18
- } catch (err) {
19
- return Math.random();
27
+ /**
28
+ * 将值设置到指定路径的嵌套对象中
29
+ * @param obj 目标对象
30
+ * @param path 路径数组
31
+ * @param value 要设置的值
32
+ */
33
+ function setValueByPath(obj, path, value) {
34
+ if (path.length === 0) return;
35
+ // 处理单层路径
36
+ if (path.length === 1) {
37
+ obj[path[0]] = value;
38
+ return;
39
+ }
40
+ // 处理多层嵌套路径
41
+ var current = obj;
42
+ for (var i = 0; i < path.length - 1; i++) {
43
+ var key = path[i];
44
+ if (!current[key]) {
45
+ current[key] = {};
46
+ }
47
+ current = current[key];
20
48
  }
49
+ current[path[path.length - 1]] = value;
21
50
  }
22
- // 创建之后namepath就不可变
23
- var useWatchWarning = process.env.NODE_ENV !== 'production' ? function (namePath) {
24
- var fullyStr = JSON.stringify(namePath);
25
- var nameStrRef = useRef(fullyStr);
26
- warning(nameStrRef.current === fullyStr, '`useWatch` is not support dynamic `namePath`. Please provide static instead.');
51
+ // 创建之后namepath就不可变的警告
52
+ var useWatchWarning = process.env.NODE_ENV !== 'production' ? function (dependencies) {
53
+ var depsStr = JSON.stringify(dependencies);
54
+ var depsStrRef = useRef(depsStr);
55
+ warning(depsStrRef.current === depsStr, '`useWatch` is not support dynamic `namePath`. Please provide static instead.');
27
56
  } : function () {};
57
+ /**
58
+ * ProForm的useWatch hook,用于监听表单字段变化
59
+ * @param dependencies 监听的字段路径
60
+ * @param form 表单实例
61
+ * @param wait 防抖等待时间
62
+ * @returns 表单值
63
+ */
28
64
  function useWatch(dependencies, form, wait) {
29
- var isSingle = typeof dependencies === 'string';
65
+ // 处理开发环境警告
66
+ useWatchWarning(dependencies);
67
+ // 获取表单实例
68
+ var formInstance = form;
69
+ // 用于存储最终结果
30
70
  var _useState = useState({}),
31
71
  _useState2 = _slicedToArray(_useState, 2),
32
- value = _useState2[0],
33
- setValue = _useState2[1];
34
- var valueStr = useMemo(function () {
35
- return stringify(value);
36
- }, [value]);
37
- var valueStrRef = useRef(valueStr);
38
- valueStrRef.current = valueStr;
39
- var formInstance = form;
40
- var isValidForm = formInstance && formInstance._init;
41
- var _dependencies = isSingle ? [dependencies] : dependencies;
42
- var namePaths = _dependencies === null || _dependencies === void 0 ? void 0 : _dependencies.map(function (item) {
43
- return getNamePath(item);
44
- });
45
- var namePathsRef = useRef(namePaths);
46
- namePathsRef.current = namePaths;
47
- useWatchWarning(namePaths);
48
- useEffect(function () {
49
- if (!isValidForm) return;
50
- var getFieldsValue = formInstance.getFieldsValue,
51
- getInternalHooks = formInstance.getInternalHooks;
52
- var _getInternalHooks = getInternalHooks(HOOK_MARK),
53
- registerWatch = _getInternalHooks.registerWatch;
54
- // 创建回调函数
55
- var callback = function callback() {
56
- // 只获取一次新值
57
- var newValue = getFieldsValue(_dependencies);
58
- var nextValueStr = stringify(newValue);
59
- // Compare stringify in case it's nest object
60
- if (valueStrRef.current !== nextValueStr) {
61
- valueStrRef.current = nextValueStr;
62
- // 关键修改:使用已获取的newValue,避免重复调用getFieldsValue
63
- setValue(newValue);
72
+ state = _useState2[0],
73
+ setState = _useState2[1];
74
+ // 使用ref存储中间状态,避免不必要的渲染
75
+ var valueRef = useRef({});
76
+ var prevStateRef = useRef({});
77
+ // 标准化依赖为路径数组的数组
78
+ var namePaths = useMemo(function () {
79
+ // 将依赖标准化为数组的数组形式
80
+ var paths = [];
81
+ // 字符串形式: 'fieldName'
82
+ if (typeof dependencies === 'string') {
83
+ paths.push(dependencies);
84
+ // 数组形式
85
+ } else if (Array.isArray(dependencies)) {
86
+ // 检查是否是路径数组的集合,例如:[['a', 'number'], 'fieldName']
87
+ var isPathsCollection = dependencies.length > 0 && (typeof dependencies[0] === 'string' || Array.isArray(dependencies[0]));
88
+ if (isPathsCollection) {
89
+ // 每个元素都是一个路径
90
+ dependencies.forEach(function (path) {
91
+ paths.push(path);
92
+ });
93
+ } else {
94
+ // 整个数组是一个单一路径
95
+ paths.push(dependencies);
64
96
  }
65
- };
66
- // 增加防抖
67
- var cancelDebounce = null;
97
+ }
98
+ return paths;
99
+ }, [/* dependencies 故意忽略,与原实现一致 */]);
100
+ // 保存防抖函数引用,避免重复创建
101
+ var debouncedFn = useMemo(function () {
68
102
  if (wait) {
69
- var debouncedCallback = debounce(callback, wait);
70
- callback = debouncedCallback;
71
- cancelDebounce = function cancelDebounce() {
72
- return debouncedCallback.cancel();
73
- };
103
+ return debounce(function (value) {
104
+ // 只在值真正变化时才更新状态
105
+ if (!isEqual(prevStateRef.current, value)) {
106
+ prevStateRef.current = _objectSpread({}, value);
107
+ setState(value);
108
+ }
109
+ }, wait);
74
110
  }
75
- // 注册监听
76
- var cancelRegister = registerWatch(callback);
77
- // 设置初始值
78
- var initialValue = getFieldsValue(_dependencies);
79
- setValue(initialValue);
80
- // 清理函数
111
+ // 非防抖版本
112
+ return function (value) {
113
+ if (!isEqual(prevStateRef.current, value)) {
114
+ prevStateRef.current = _objectSpread({}, value);
115
+ setState(value);
116
+ }
117
+ };
118
+ }, [wait]);
119
+ useEffect(function () {
120
+ if (!formInstance) return undefined;
121
+ // 创建更新状态的函数
122
+ var updateState = function updateState() {
123
+ var values = formInstance.getFieldsValue(true);
124
+ var newState = {};
125
+ // 处理每个监听路径
126
+ namePaths.forEach(function (path) {
127
+ // 将路径转换为数组形式
128
+ var namePath = toArray(path);
129
+ // 获取路径对应的值
130
+ var value = get(values, namePath);
131
+ // 将值设置到正确的嵌套结构中
132
+ setValueByPath(newState, namePath, value);
133
+ });
134
+ // 存储并更新状态
135
+ valueRef.current = newState;
136
+ debouncedFn(newState);
137
+ };
138
+ // 初始调用一次
139
+ updateState();
140
+ // 注册表单变化监听
141
+ var getInternalHooks = formInstance.getInternalHooks;
142
+ var _getInternalHooks = getInternalHooks('RC_FORM_INTERNAL_HOOKS'),
143
+ registerWatch = _getInternalHooks.registerWatch;
144
+ var cancelWatch = registerWatch(function (values) {
145
+ if (values) {
146
+ updateState();
147
+ }
148
+ });
149
+ // 清理订阅
81
150
  return function () {
82
- cancelRegister();
83
- if (cancelDebounce) {
84
- cancelDebounce();
151
+ if (wait) {
152
+ debouncedFn.cancel();
85
153
  }
154
+ cancelWatch();
86
155
  };
87
- },
88
- // We do not need re-register since namePath content is the same
89
- // eslint-disable-next-line react-hooks/exhaustive-deps
90
- [isValidForm]);
91
- return value;
156
+ }, [formInstance, namePaths, debouncedFn, wait]);
157
+ return state;
92
158
  }
93
159
  export default useWatch;
@@ -1,6 +1,6 @@
1
1
  import React from 'react';
2
- import { ModifiedFormInstance } from '../ProForm/utils/useForm';
3
- type Forms = Record<string, ModifiedFormInstance<any>>;
2
+ import { ModifiedFormInstanceType } from '../ProForm/utils/useForm';
3
+ type Forms = Record<string, ModifiedFormInstanceType<any>>;
4
4
  export declare const FormsContext: React.Context<Forms>;
5
5
  /**
6
6
  * @param formKey 表单实例key