Field.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
  3. var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
  4. Object.defineProperty(exports, "__esModule", {
  5. value: true
  6. });
  7. exports.default = void 0;
  8. var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
  9. var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
  10. var _regeneratorRuntime2 = _interopRequireDefault(require("@babel/runtime/helpers/regeneratorRuntime"));
  11. var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
  12. var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
  13. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  14. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
  15. var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
  16. var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
  17. var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
  18. var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));
  19. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  20. var _toArray = _interopRequireDefault(require("rc-util/lib/Children/toArray"));
  21. var _isEqual = _interopRequireDefault(require("rc-util/lib/isEqual"));
  22. var _warning = _interopRequireDefault(require("rc-util/lib/warning"));
  23. var React = _interopRequireWildcard(require("react"));
  24. var _FieldContext = _interopRequireWildcard(require("./FieldContext"));
  25. var _ListContext = _interopRequireDefault(require("./ListContext"));
  26. var _typeUtil = require("./utils/typeUtil");
  27. var _validateUtil = require("./utils/validateUtil");
  28. var _valueUtil = require("./utils/valueUtil");
  29. var _excluded = ["name"];
  30. var EMPTY_ERRORS = [];
  31. function requireUpdate(shouldUpdate, prev, next, prevValue, nextValue, info) {
  32. if (typeof shouldUpdate === 'function') {
  33. return shouldUpdate(prev, next, 'source' in info ? {
  34. source: info.source
  35. } : {});
  36. }
  37. return prevValue !== nextValue;
  38. }
  39. // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
  40. // We use Class instead of Hooks here since it will cost much code by using Hooks.
  41. var Field = /*#__PURE__*/function (_React$Component) {
  42. (0, _inherits2.default)(Field, _React$Component);
  43. var _super = (0, _createSuper2.default)(Field);
  44. // ============================== Subscriptions ==============================
  45. function Field(props) {
  46. var _this;
  47. (0, _classCallCheck2.default)(this, Field);
  48. _this = _super.call(this, props);
  49. // Register on init
  50. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "state", {
  51. resetCount: 0
  52. });
  53. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "cancelRegisterFunc", null);
  54. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "mounted", false);
  55. /**
  56. * Follow state should not management in State since it will async update by React.
  57. * This makes first render of form can not get correct state value.
  58. */
  59. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "touched", false);
  60. /**
  61. * Mark when touched & validated. Currently only used for `dependencies`.
  62. * Note that we do not think field with `initialValue` is dirty
  63. * but this will be by `isFieldDirty` func.
  64. */
  65. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "dirty", false);
  66. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "validatePromise", void 0);
  67. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "prevValidating", void 0);
  68. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "errors", EMPTY_ERRORS);
  69. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "warnings", EMPTY_ERRORS);
  70. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "cancelRegister", function () {
  71. var _this$props = _this.props,
  72. preserve = _this$props.preserve,
  73. isListField = _this$props.isListField,
  74. name = _this$props.name;
  75. if (_this.cancelRegisterFunc) {
  76. _this.cancelRegisterFunc(isListField, preserve, (0, _valueUtil.getNamePath)(name));
  77. }
  78. _this.cancelRegisterFunc = null;
  79. });
  80. // ================================== Utils ==================================
  81. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getNamePath", function () {
  82. var _this$props2 = _this.props,
  83. name = _this$props2.name,
  84. fieldContext = _this$props2.fieldContext;
  85. var _fieldContext$prefixN = fieldContext.prefixName,
  86. prefixName = _fieldContext$prefixN === void 0 ? [] : _fieldContext$prefixN;
  87. return name !== undefined ? [].concat((0, _toConsumableArray2.default)(prefixName), (0, _toConsumableArray2.default)(name)) : [];
  88. });
  89. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getRules", function () {
  90. var _this$props3 = _this.props,
  91. _this$props3$rules = _this$props3.rules,
  92. rules = _this$props3$rules === void 0 ? [] : _this$props3$rules,
  93. fieldContext = _this$props3.fieldContext;
  94. return rules.map(function (rule) {
  95. if (typeof rule === 'function') {
  96. return rule(fieldContext);
  97. }
  98. return rule;
  99. });
  100. });
  101. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "refresh", function () {
  102. if (!_this.mounted) return;
  103. /**
  104. * Clean up current node.
  105. */
  106. _this.setState(function (_ref) {
  107. var resetCount = _ref.resetCount;
  108. return {
  109. resetCount: resetCount + 1
  110. };
  111. });
  112. });
  113. // Event should only trigger when meta changed
  114. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "metaCache", null);
  115. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "triggerMetaEvent", function (destroy) {
  116. var onMetaChange = _this.props.onMetaChange;
  117. if (onMetaChange) {
  118. var _meta = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _this.getMeta()), {}, {
  119. destroy: destroy
  120. });
  121. if (!(0, _isEqual.default)(_this.metaCache, _meta)) {
  122. onMetaChange(_meta);
  123. }
  124. _this.metaCache = _meta;
  125. } else {
  126. _this.metaCache = null;
  127. }
  128. });
  129. // ========================= Field Entity Interfaces =========================
  130. // Trigger by store update. Check if need update the component
  131. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onStoreChange", function (prevStore, namePathList, info) {
  132. var _this$props4 = _this.props,
  133. shouldUpdate = _this$props4.shouldUpdate,
  134. _this$props4$dependen = _this$props4.dependencies,
  135. dependencies = _this$props4$dependen === void 0 ? [] : _this$props4$dependen,
  136. onReset = _this$props4.onReset;
  137. var store = info.store;
  138. var namePath = _this.getNamePath();
  139. var prevValue = _this.getValue(prevStore);
  140. var curValue = _this.getValue(store);
  141. var namePathMatch = namePathList && (0, _valueUtil.containsNamePath)(namePathList, namePath);
  142. // `setFieldsValue` is a quick access to update related status
  143. if (info.type === 'valueUpdate' && info.source === 'external' && !(0, _isEqual.default)(prevValue, curValue)) {
  144. _this.touched = true;
  145. _this.dirty = true;
  146. _this.validatePromise = null;
  147. _this.errors = EMPTY_ERRORS;
  148. _this.warnings = EMPTY_ERRORS;
  149. _this.triggerMetaEvent();
  150. }
  151. switch (info.type) {
  152. case 'reset':
  153. if (!namePathList || namePathMatch) {
  154. // Clean up state
  155. _this.touched = false;
  156. _this.dirty = false;
  157. _this.validatePromise = undefined;
  158. _this.errors = EMPTY_ERRORS;
  159. _this.warnings = EMPTY_ERRORS;
  160. _this.triggerMetaEvent();
  161. onReset === null || onReset === void 0 || onReset();
  162. _this.refresh();
  163. return;
  164. }
  165. break;
  166. /**
  167. * In case field with `preserve = false` nest deps like:
  168. * - A = 1 => show B
  169. * - B = 1 => show C
  170. * - Reset A, need clean B, C
  171. */
  172. case 'remove':
  173. {
  174. if (shouldUpdate && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
  175. _this.reRender();
  176. return;
  177. }
  178. break;
  179. }
  180. case 'setField':
  181. {
  182. var data = info.data;
  183. if (namePathMatch) {
  184. if ('touched' in data) {
  185. _this.touched = data.touched;
  186. }
  187. if ('validating' in data && !('originRCField' in data)) {
  188. _this.validatePromise = data.validating ? Promise.resolve([]) : null;
  189. }
  190. if ('errors' in data) {
  191. _this.errors = data.errors || EMPTY_ERRORS;
  192. }
  193. if ('warnings' in data) {
  194. _this.warnings = data.warnings || EMPTY_ERRORS;
  195. }
  196. _this.dirty = true;
  197. _this.triggerMetaEvent();
  198. _this.reRender();
  199. return;
  200. } else if ('value' in data && (0, _valueUtil.containsNamePath)(namePathList, namePath, true)) {
  201. // Contains path with value should also check
  202. _this.reRender();
  203. return;
  204. }
  205. // Handle update by `setField` with `shouldUpdate`
  206. if (shouldUpdate && !namePath.length && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
  207. _this.reRender();
  208. return;
  209. }
  210. break;
  211. }
  212. case 'dependenciesUpdate':
  213. {
  214. /**
  215. * Trigger when marked `dependencies` updated. Related fields will all update
  216. */
  217. var dependencyList = dependencies.map(_valueUtil.getNamePath);
  218. // No need for `namePathMath` check and `shouldUpdate` check, since `valueUpdate` will be
  219. // emitted earlier and they will work there
  220. // If set it may cause unnecessary twice rerendering
  221. if (dependencyList.some(function (dependency) {
  222. return (0, _valueUtil.containsNamePath)(info.relatedFields, dependency);
  223. })) {
  224. _this.reRender();
  225. return;
  226. }
  227. break;
  228. }
  229. default:
  230. // 1. If `namePath` exists in `namePathList`, means it's related value and should update
  231. // For example <List name="list"><Field name={['list', 0]}></List>
  232. // If `namePathList` is [['list']] (List value update), Field should be updated
  233. // If `namePathList` is [['list', 0]] (Field value update), List shouldn't be updated
  234. // 2.
  235. // 2.1 If `dependencies` is set, `name` is not set and `shouldUpdate` is not set,
  236. // don't use `shouldUpdate`. `dependencies` is view as a shortcut if `shouldUpdate`
  237. // is not provided
  238. // 2.2 If `shouldUpdate` provided, use customize logic to update the field
  239. // else to check if value changed
  240. if (namePathMatch || (!dependencies.length || namePath.length || shouldUpdate) && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
  241. _this.reRender();
  242. return;
  243. }
  244. break;
  245. }
  246. if (shouldUpdate === true) {
  247. _this.reRender();
  248. }
  249. });
  250. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "validateRules", function (options) {
  251. // We should fixed namePath & value to avoid developer change then by form function
  252. var namePath = _this.getNamePath();
  253. var currentValue = _this.getValue();
  254. var _ref2 = options || {},
  255. triggerName = _ref2.triggerName,
  256. _ref2$validateOnly = _ref2.validateOnly,
  257. validateOnly = _ref2$validateOnly === void 0 ? false : _ref2$validateOnly;
  258. // Force change to async to avoid rule OOD under renderProps field
  259. var rootPromise = Promise.resolve().then( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee() {
  260. var _this$props5, _this$props5$validate, validateFirst, messageVariables, validateDebounce, filteredRules, promise;
  261. return (0, _regeneratorRuntime2.default)().wrap(function _callee$(_context) {
  262. while (1) switch (_context.prev = _context.next) {
  263. case 0:
  264. if (_this.mounted) {
  265. _context.next = 2;
  266. break;
  267. }
  268. return _context.abrupt("return", []);
  269. case 2:
  270. _this$props5 = _this.props, _this$props5$validate = _this$props5.validateFirst, validateFirst = _this$props5$validate === void 0 ? false : _this$props5$validate, messageVariables = _this$props5.messageVariables, validateDebounce = _this$props5.validateDebounce; // Start validate
  271. filteredRules = _this.getRules();
  272. if (triggerName) {
  273. filteredRules = filteredRules.filter(function (rule) {
  274. return rule;
  275. }).filter(function (rule) {
  276. var validateTrigger = rule.validateTrigger;
  277. if (!validateTrigger) {
  278. return true;
  279. }
  280. var triggerList = (0, _typeUtil.toArray)(validateTrigger);
  281. return triggerList.includes(triggerName);
  282. });
  283. }
  284. // Wait for debounce. Skip if no `triggerName` since its from `validateFields / submit`
  285. if (!(validateDebounce && triggerName)) {
  286. _context.next = 10;
  287. break;
  288. }
  289. _context.next = 8;
  290. return new Promise(function (resolve) {
  291. setTimeout(resolve, validateDebounce);
  292. });
  293. case 8:
  294. if (!(_this.validatePromise !== rootPromise)) {
  295. _context.next = 10;
  296. break;
  297. }
  298. return _context.abrupt("return", []);
  299. case 10:
  300. promise = (0, _validateUtil.validateRules)(namePath, currentValue, filteredRules, options, validateFirst, messageVariables);
  301. promise.catch(function (e) {
  302. return e;
  303. }).then(function () {
  304. var ruleErrors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : EMPTY_ERRORS;
  305. if (_this.validatePromise === rootPromise) {
  306. var _ruleErrors$forEach;
  307. _this.validatePromise = null;
  308. // Get errors & warnings
  309. var nextErrors = [];
  310. var nextWarnings = [];
  311. (_ruleErrors$forEach = ruleErrors.forEach) === null || _ruleErrors$forEach === void 0 || _ruleErrors$forEach.call(ruleErrors, function (_ref4) {
  312. var warningOnly = _ref4.rule.warningOnly,
  313. _ref4$errors = _ref4.errors,
  314. errors = _ref4$errors === void 0 ? EMPTY_ERRORS : _ref4$errors;
  315. if (warningOnly) {
  316. nextWarnings.push.apply(nextWarnings, (0, _toConsumableArray2.default)(errors));
  317. } else {
  318. nextErrors.push.apply(nextErrors, (0, _toConsumableArray2.default)(errors));
  319. }
  320. });
  321. _this.errors = nextErrors;
  322. _this.warnings = nextWarnings;
  323. _this.triggerMetaEvent();
  324. _this.reRender();
  325. }
  326. });
  327. return _context.abrupt("return", promise);
  328. case 13:
  329. case "end":
  330. return _context.stop();
  331. }
  332. }, _callee);
  333. })));
  334. if (validateOnly) {
  335. return rootPromise;
  336. }
  337. _this.validatePromise = rootPromise;
  338. _this.dirty = true;
  339. _this.errors = EMPTY_ERRORS;
  340. _this.warnings = EMPTY_ERRORS;
  341. _this.triggerMetaEvent();
  342. // Force trigger re-render since we need sync renderProps with new meta
  343. _this.reRender();
  344. return rootPromise;
  345. });
  346. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isFieldValidating", function () {
  347. return !!_this.validatePromise;
  348. });
  349. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isFieldTouched", function () {
  350. return _this.touched;
  351. });
  352. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isFieldDirty", function () {
  353. // Touched or validate or has initialValue
  354. if (_this.dirty || _this.props.initialValue !== undefined) {
  355. return true;
  356. }
  357. // Form set initialValue
  358. var fieldContext = _this.props.fieldContext;
  359. var _fieldContext$getInte = fieldContext.getInternalHooks(_FieldContext.HOOK_MARK),
  360. getInitialValue = _fieldContext$getInte.getInitialValue;
  361. if (getInitialValue(_this.getNamePath()) !== undefined) {
  362. return true;
  363. }
  364. return false;
  365. });
  366. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getErrors", function () {
  367. return _this.errors;
  368. });
  369. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getWarnings", function () {
  370. return _this.warnings;
  371. });
  372. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isListField", function () {
  373. return _this.props.isListField;
  374. });
  375. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isList", function () {
  376. return _this.props.isList;
  377. });
  378. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isPreserve", function () {
  379. return _this.props.preserve;
  380. });
  381. // ============================= Child Component =============================
  382. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getMeta", function () {
  383. // Make error & validating in cache to save perf
  384. _this.prevValidating = _this.isFieldValidating();
  385. var meta = {
  386. touched: _this.isFieldTouched(),
  387. validating: _this.prevValidating,
  388. errors: _this.errors,
  389. warnings: _this.warnings,
  390. name: _this.getNamePath(),
  391. validated: _this.validatePromise === null
  392. };
  393. return meta;
  394. });
  395. // Only return validate child node. If invalidate, will do nothing about field.
  396. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getOnlyChild", function (children) {
  397. // Support render props
  398. if (typeof children === 'function') {
  399. var _meta2 = _this.getMeta();
  400. return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _this.getOnlyChild(children(_this.getControlled(), _meta2, _this.props.fieldContext))), {}, {
  401. isFunction: true
  402. });
  403. }
  404. // Filed element only
  405. var childList = (0, _toArray.default)(children);
  406. if (childList.length !== 1 || ! /*#__PURE__*/React.isValidElement(childList[0])) {
  407. return {
  408. child: childList,
  409. isFunction: false
  410. };
  411. }
  412. return {
  413. child: childList[0],
  414. isFunction: false
  415. };
  416. });
  417. // ============================== Field Control ==============================
  418. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getValue", function (store) {
  419. var getFieldsValue = _this.props.fieldContext.getFieldsValue;
  420. var namePath = _this.getNamePath();
  421. return (0, _valueUtil.getValue)(store || getFieldsValue(true), namePath);
  422. });
  423. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getControlled", function () {
  424. var childProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  425. var _this$props6 = _this.props,
  426. name = _this$props6.name,
  427. trigger = _this$props6.trigger,
  428. validateTrigger = _this$props6.validateTrigger,
  429. getValueFromEvent = _this$props6.getValueFromEvent,
  430. normalize = _this$props6.normalize,
  431. valuePropName = _this$props6.valuePropName,
  432. getValueProps = _this$props6.getValueProps,
  433. fieldContext = _this$props6.fieldContext;
  434. var mergedValidateTrigger = validateTrigger !== undefined ? validateTrigger : fieldContext.validateTrigger;
  435. var namePath = _this.getNamePath();
  436. var getInternalHooks = fieldContext.getInternalHooks,
  437. getFieldsValue = fieldContext.getFieldsValue;
  438. var _getInternalHooks = getInternalHooks(_FieldContext.HOOK_MARK),
  439. dispatch = _getInternalHooks.dispatch;
  440. var value = _this.getValue();
  441. var mergedGetValueProps = getValueProps || function (val) {
  442. return (0, _defineProperty2.default)({}, valuePropName, val);
  443. };
  444. var originTriggerFunc = childProps[trigger];
  445. var valueProps = name !== undefined ? mergedGetValueProps(value) : {};
  446. // warning when prop value is function
  447. if (process.env.NODE_ENV !== 'production' && valueProps) {
  448. Object.keys(valueProps).forEach(function (key) {
  449. (0, _warning.default)(typeof valueProps[key] !== 'function', "It's not recommended to generate dynamic function prop by `getValueProps`. Please pass it to child component directly (prop: ".concat(key, ")"));
  450. });
  451. }
  452. var control = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, childProps), valueProps);
  453. // Add trigger
  454. control[trigger] = function () {
  455. // Mark as touched
  456. _this.touched = true;
  457. _this.dirty = true;
  458. _this.triggerMetaEvent();
  459. var newValue;
  460. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  461. args[_key] = arguments[_key];
  462. }
  463. if (getValueFromEvent) {
  464. newValue = getValueFromEvent.apply(void 0, args);
  465. } else {
  466. newValue = _valueUtil.defaultGetValueFromEvent.apply(void 0, [valuePropName].concat(args));
  467. }
  468. if (normalize) {
  469. newValue = normalize(newValue, value, getFieldsValue(true));
  470. }
  471. if (newValue !== value) {
  472. dispatch({
  473. type: 'updateValue',
  474. namePath: namePath,
  475. value: newValue
  476. });
  477. }
  478. if (originTriggerFunc) {
  479. originTriggerFunc.apply(void 0, args);
  480. }
  481. };
  482. // Add validateTrigger
  483. var validateTriggerList = (0, _typeUtil.toArray)(mergedValidateTrigger || []);
  484. validateTriggerList.forEach(function (triggerName) {
  485. // Wrap additional function of component, so that we can get latest value from store
  486. var originTrigger = control[triggerName];
  487. control[triggerName] = function () {
  488. if (originTrigger) {
  489. originTrigger.apply(void 0, arguments);
  490. }
  491. // Always use latest rules
  492. var rules = _this.props.rules;
  493. if (rules && rules.length) {
  494. // We dispatch validate to root,
  495. // since it will update related data with other field with same name
  496. dispatch({
  497. type: 'validateField',
  498. namePath: namePath,
  499. triggerName: triggerName
  500. });
  501. }
  502. };
  503. });
  504. return control;
  505. });
  506. if (props.fieldContext) {
  507. var getInternalHooks = props.fieldContext.getInternalHooks;
  508. var _getInternalHooks2 = getInternalHooks(_FieldContext.HOOK_MARK),
  509. initEntityValue = _getInternalHooks2.initEntityValue;
  510. initEntityValue((0, _assertThisInitialized2.default)(_this));
  511. }
  512. return _this;
  513. }
  514. (0, _createClass2.default)(Field, [{
  515. key: "componentDidMount",
  516. value: function componentDidMount() {
  517. var _this$props7 = this.props,
  518. shouldUpdate = _this$props7.shouldUpdate,
  519. fieldContext = _this$props7.fieldContext;
  520. this.mounted = true;
  521. // Register on init
  522. if (fieldContext) {
  523. var getInternalHooks = fieldContext.getInternalHooks;
  524. var _getInternalHooks3 = getInternalHooks(_FieldContext.HOOK_MARK),
  525. registerField = _getInternalHooks3.registerField;
  526. this.cancelRegisterFunc = registerField(this);
  527. }
  528. // One more render for component in case fields not ready
  529. if (shouldUpdate === true) {
  530. this.reRender();
  531. }
  532. }
  533. }, {
  534. key: "componentWillUnmount",
  535. value: function componentWillUnmount() {
  536. this.cancelRegister();
  537. this.triggerMetaEvent(true);
  538. this.mounted = false;
  539. }
  540. }, {
  541. key: "reRender",
  542. value: function reRender() {
  543. if (!this.mounted) return;
  544. this.forceUpdate();
  545. }
  546. }, {
  547. key: "render",
  548. value: function render() {
  549. var resetCount = this.state.resetCount;
  550. var children = this.props.children;
  551. var _this$getOnlyChild = this.getOnlyChild(children),
  552. child = _this$getOnlyChild.child,
  553. isFunction = _this$getOnlyChild.isFunction;
  554. // Not need to `cloneElement` since user can handle this in render function self
  555. var returnChildNode;
  556. if (isFunction) {
  557. returnChildNode = child;
  558. } else if ( /*#__PURE__*/React.isValidElement(child)) {
  559. returnChildNode = /*#__PURE__*/React.cloneElement(child, this.getControlled(child.props));
  560. } else {
  561. (0, _warning.default)(!child, '`children` of Field is not validate ReactElement.');
  562. returnChildNode = child;
  563. }
  564. return /*#__PURE__*/React.createElement(React.Fragment, {
  565. key: resetCount
  566. }, returnChildNode);
  567. }
  568. }]);
  569. return Field;
  570. }(React.Component);
  571. (0, _defineProperty2.default)(Field, "contextType", _FieldContext.default);
  572. (0, _defineProperty2.default)(Field, "defaultProps", {
  573. trigger: 'onChange',
  574. valuePropName: 'value'
  575. });
  576. function WrapperField(_ref6) {
  577. var _restProps$isListFiel;
  578. var name = _ref6.name,
  579. restProps = (0, _objectWithoutProperties2.default)(_ref6, _excluded);
  580. var fieldContext = React.useContext(_FieldContext.default);
  581. var listContext = React.useContext(_ListContext.default);
  582. var namePath = name !== undefined ? (0, _valueUtil.getNamePath)(name) : undefined;
  583. var isMergedListField = (_restProps$isListFiel = restProps.isListField) !== null && _restProps$isListFiel !== void 0 ? _restProps$isListFiel : !!listContext;
  584. var key = 'keep';
  585. if (!isMergedListField) {
  586. key = "_".concat((namePath || []).join('_'));
  587. }
  588. // Warning if it's a directly list field.
  589. // We can still support multiple level field preserve.
  590. if (process.env.NODE_ENV !== 'production' && restProps.preserve === false && isMergedListField && namePath.length <= 1) {
  591. (0, _warning.default)(false, '`preserve` should not apply on Form.List fields.');
  592. }
  593. return /*#__PURE__*/React.createElement(Field, (0, _extends2.default)({
  594. key: key,
  595. name: namePath,
  596. isListField: isMergedListField
  597. }, restProps, {
  598. fieldContext: fieldContext
  599. }));
  600. }
  601. var _default = exports.default = WrapperField;