form.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. var __extends = (this && this.__extends) || (function () {
  2. var extendStatics = function (d, b) {
  3. extendStatics = Object.setPrototypeOf ||
  4. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  6. return extendStatics(d, b);
  7. };
  8. return function (d, b) {
  9. if (typeof b !== "function" && b !== null)
  10. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  11. extendStatics(d, b);
  12. function __() { this.constructor = d; }
  13. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14. };
  15. })();
  16. var __assign = (this && this.__assign) || function () {
  17. __assign = Object.assign || function(t) {
  18. for (var s, i = 1, n = arguments.length; i < n; i++) {
  19. s = arguments[i];
  20. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  21. t[p] = s[p];
  22. }
  23. return t;
  24. };
  25. return __assign.apply(this, arguments);
  26. };
  27. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  28. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  29. return new (P || (P = Promise))(function (resolve, reject) {
  30. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  31. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  32. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  33. step((generator = generator.apply(thisArg, _arguments || [])).next());
  34. });
  35. };
  36. var __generator = (this && this.__generator) || function (thisArg, body) {
  37. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  38. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  39. function verb(n) { return function (v) { return step([n, v]); }; }
  40. function step(op) {
  41. if (f) throw new TypeError("Generator is already executing.");
  42. while (g && (g = 0, op[0] && (_ = 0)), _) try {
  43. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  44. if (y = 0, t) op = [op[0] & 2, t.value];
  45. switch (op[0]) {
  46. case 0: case 1: t = op; break;
  47. case 4: _.label++; return { value: op[1], done: false };
  48. case 5: _.label++; y = op[1]; op = [0]; continue;
  49. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  50. default:
  51. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  52. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  53. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  54. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  55. if (t[2]) _.ops.pop();
  56. _.trys.pop(); continue;
  57. }
  58. op = body.call(thisArg, _);
  59. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  60. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  61. }
  62. };
  63. import AsyncValidator from 'async-validator';
  64. var EventEmitter = /** @class */ (function () {
  65. function EventEmitter() {
  66. this.listenders = {};
  67. }
  68. EventEmitter.prototype.on = function (event, listener) {
  69. this.listenders[event] = this.listenders[event] || [];
  70. this.listenders[event].push(listener);
  71. return this;
  72. };
  73. EventEmitter.prototype.emit = function (event) {
  74. var args = [];
  75. for (var _i = 1; _i < arguments.length; _i++) {
  76. args[_i - 1] = arguments[_i];
  77. }
  78. var arr = this.listenders[event];
  79. if (arr) {
  80. arr.forEach(function (listener) { return listener.apply(void 0, args); });
  81. }
  82. };
  83. return EventEmitter;
  84. }());
  85. var Field = /** @class */ (function (_super) {
  86. __extends(Field, _super);
  87. /**
  88. * Field构建
  89. * @param ref field ref对象
  90. * @param initialValue 初始值
  91. */
  92. function Field(ref, name, initialValues, rules, validateMessages, required, label, message, validateTrigger) {
  93. var _this = _super.call(this) || this;
  94. _this.ref = ref;
  95. _this.formRules = rules;
  96. _this.create(name, initialValues[name], rules[name], validateMessages, required, label, message, validateTrigger);
  97. _this.ref.on(function (trigger, value, extraInfo) {
  98. if (trigger === 'onChange') {
  99. _this.setValue(value);
  100. _this.touched = true;
  101. _this.emit('valueChange', value);
  102. }
  103. else if (trigger === 'didUnmount') {
  104. _this.emit('didUnmount');
  105. }
  106. else if (trigger === 'deriveDataFromProps') {
  107. var props = extraInfo ? extraInfo : _this.ref.getProps();
  108. if ((value.name && value.name !== props.name) ||
  109. value.required !== props.required ||
  110. value.label !== props.label ||
  111. value.message !== props.message ||
  112. value.validateTrigger !== props.validateTrigger) {
  113. _this.create(value.name, initialValues[value.name], _this.formRules[value.name], validateMessages, value.required, value.message, value.label, value.validateTrigger, true);
  114. }
  115. if (value.name !== props.name) {
  116. _this.emit('replaceName', value.name);
  117. }
  118. }
  119. _this.validateTrigger.forEach(function (item) {
  120. if (item === trigger) {
  121. _this.validate();
  122. }
  123. });
  124. });
  125. return _this;
  126. }
  127. Field.prototype.create = function (name, initialValue, rule, validateMessages, required, label, message, validateTrigger, update) {
  128. this.name = name;
  129. this.required = this.transformValidatorRules(name, rule, required, label, message, validateMessages);
  130. if (!update) {
  131. this.reset(initialValue);
  132. }
  133. else {
  134. this.ref.setFormData({
  135. required: this.required,
  136. });
  137. }
  138. var validateTriggerList = validateTrigger || 'onChange';
  139. if (!Array.isArray(validateTriggerList)) {
  140. validateTriggerList = [validateTriggerList];
  141. }
  142. this.validateTrigger = validateTriggerList;
  143. };
  144. Field.prototype.updateFieldRules = function (rules, validateMessages) {
  145. var props = this.ref.getProps();
  146. this.formRules = rules;
  147. this.create(props.name, null, rules[props.name], validateMessages, props.required, props.label, props.message, props.validateTrigger, true);
  148. };
  149. /**
  150. *
  151. * @param rule 修改 Validator
  152. * @param name
  153. * @param required
  154. * @param message
  155. * @param validateMessages
  156. * @returns
  157. */
  158. Field.prototype.transformValidatorRules = function (name, rule, required, label, message, validateMessages) {
  159. var _a, _b;
  160. var requiredRule = false;
  161. var validator;
  162. if (rule) {
  163. var ruleList = Array.isArray(rule) ? rule : [rule];
  164. var result = ruleList.find(function (item) { return item.required; });
  165. if (result) {
  166. if (message) {
  167. result.message = message;
  168. }
  169. requiredRule = true;
  170. }
  171. else if (required) {
  172. ruleList.push({
  173. required: required,
  174. // message 不允许为 null
  175. message: message !== null && message !== void 0 ? message : undefined,
  176. });
  177. requiredRule = true;
  178. }
  179. validator = new AsyncValidator((_a = {},
  180. _a[name] = ruleList,
  181. _a));
  182. }
  183. else if (required) {
  184. validator = new AsyncValidator((_b = {},
  185. _b[name] = {
  186. required: required,
  187. // message 不允许为 null
  188. message: message !== null && message !== void 0 ? message : undefined,
  189. },
  190. _b));
  191. requiredRule = true;
  192. }
  193. if (validator) {
  194. var obj_1 = {
  195. label: label,
  196. };
  197. Object.keys(validator.rules).forEach(function (name) {
  198. validator.rules[name].forEach(function (item) {
  199. if (typeof item.len !== 'undefined') {
  200. obj_1['len'] = item.len;
  201. }
  202. if (typeof item.min !== 'undefined') {
  203. obj_1['min'] = item.min;
  204. }
  205. if (typeof item.max !== 'undefined') {
  206. obj_1['max'] = item.max;
  207. }
  208. if (typeof item.pattern !== 'undefined') {
  209. obj_1['pattern'] = item.pattern;
  210. }
  211. });
  212. });
  213. validator.messages(this.transformValidateMessages(validateMessages, obj_1));
  214. }
  215. this.validator = validator;
  216. return requiredRule;
  217. };
  218. Field.prototype.transformValidateMessages = function (validateMessages, obj) {
  219. if (!validateMessages) {
  220. return;
  221. }
  222. function replaceLabel(validateMessages, target) {
  223. Object.keys(validateMessages).forEach(function (item) {
  224. if (typeof validateMessages[item] === 'string') {
  225. target[item] = validateMessages[item].replace('${label}', obj.label || '');
  226. if (typeof obj.len !== 'undefined') {
  227. target[item] = target[item].replace('${len}', obj.len);
  228. }
  229. if (typeof obj.min !== 'undefined') {
  230. target[item] = target[item].replace('${min}', obj.min);
  231. }
  232. if (typeof obj.max !== 'undefined') {
  233. target[item] = target[item].replace('${max}', obj.max);
  234. }
  235. if (typeof obj.pattern !== 'undefined') {
  236. target[item] = target[item].replace('${pattern}', obj.pattern);
  237. }
  238. return;
  239. }
  240. if (typeof validateMessages[item] === 'object') {
  241. var val = (target[item] = {});
  242. replaceLabel(validateMessages[item], val);
  243. return;
  244. }
  245. target[item] = validateMessages[item];
  246. });
  247. }
  248. var messages = {};
  249. replaceLabel(validateMessages, messages);
  250. return messages;
  251. };
  252. /**
  253. * 设置 Field 值
  254. * @param value Field 值
  255. */
  256. Field.prototype.setValue = function (value) {
  257. this.ref.setFormData({
  258. value: value,
  259. });
  260. };
  261. /**
  262. * 得到 Field 值
  263. */
  264. Field.prototype.getValue = function () {
  265. var value = this.ref.getFormData().value;
  266. return value;
  267. };
  268. /**
  269. * 设置 Field 校验器状态
  270. * @param validatorStatue
  271. */
  272. Field.prototype.setValidatorStatus = function (validatorStatue) {
  273. this.ref.setFormData(validatorStatue);
  274. };
  275. /**
  276. * 得到 Field 校验器状态
  277. * @returns
  278. */
  279. Field.prototype.getValidatorStatus = function () {
  280. var _a = this.ref.getFormData(), status = _a.status, errors = _a.errors;
  281. return {
  282. status: status,
  283. errors: errors,
  284. };
  285. };
  286. /**
  287. * 校验 Field
  288. */
  289. Field.prototype.validate = function () {
  290. return __awaiter(this, void 0, void 0, function () {
  291. var validatorStatusSuccess, value, validator, needUpdateStatus_1, err_1, errors, validatorStatus;
  292. var _a;
  293. var _this = this;
  294. return __generator(this, function (_b) {
  295. switch (_b.label) {
  296. case 0:
  297. validatorStatusSuccess = {
  298. status: 'success',
  299. errors: [],
  300. };
  301. value = this.getValue();
  302. if (!this.validator) {
  303. this.setValidatorStatus(validatorStatusSuccess);
  304. return [2 /*return*/, {
  305. validatorStatus: validatorStatusSuccess,
  306. value: value,
  307. }];
  308. }
  309. validator = this.validator;
  310. _b.label = 1;
  311. case 1:
  312. _b.trys.push([1, 3, , 4]);
  313. needUpdateStatus_1 = true;
  314. Promise.resolve().then(function () {
  315. Promise.resolve().then(function () {
  316. if (needUpdateStatus_1) {
  317. _this.setValidatorStatus({
  318. status: 'validating',
  319. errors: [],
  320. });
  321. }
  322. });
  323. });
  324. return [4 /*yield*/, this.validator.validate((_a = {},
  325. _a[this.name] = value,
  326. _a), function () {
  327. needUpdateStatus_1 = false;
  328. })];
  329. case 2:
  330. _b.sent();
  331. if (validator !== this.validator) {
  332. return [2 /*return*/];
  333. }
  334. this.setValidatorStatus(validatorStatusSuccess);
  335. return [2 /*return*/, {
  336. validatorStatus: validatorStatusSuccess,
  337. value: value,
  338. }];
  339. case 3:
  340. err_1 = _b.sent();
  341. if (validator !== this.validator) {
  342. return [2 /*return*/];
  343. }
  344. errors = err_1.errors;
  345. validatorStatus = {
  346. status: 'error',
  347. errors: errors.map(function (_a) {
  348. var _b = _a.message, message = _b === void 0 ? '' : _b;
  349. return message;
  350. }),
  351. };
  352. this.setValidatorStatus(validatorStatus);
  353. return [2 /*return*/, {
  354. validatorStatus: validatorStatus,
  355. value: value,
  356. }];
  357. case 4: return [2 /*return*/];
  358. }
  359. });
  360. });
  361. };
  362. /**
  363. * 重置 Field
  364. * @param initialValue
  365. */
  366. Field.prototype.reset = function (initialValue) {
  367. this.touched = false;
  368. this.ref.setFormData({
  369. value: initialValue,
  370. required: this.required,
  371. status: 'default',
  372. errors: [],
  373. });
  374. };
  375. /**
  376. * Field 是否被操作
  377. */
  378. Field.prototype.isTouched = function () {
  379. return this.touched;
  380. };
  381. return Field;
  382. }(EventEmitter));
  383. var Form = /** @class */ (function () {
  384. /**
  385. * Form构建
  386. * @param formConfig 表单配置项
  387. */
  388. function Form(formConfig) {
  389. if (formConfig === void 0) { formConfig = {}; }
  390. /**
  391. * 表单ref组件对象
  392. */
  393. this.fields = {};
  394. /**
  395. * 表单字段 change侦听
  396. */
  397. this.changeListeners = [];
  398. /**
  399. * 依赖表
  400. */
  401. this.dependenciesMap = {};
  402. this.setInitialValues(formConfig.initialValues || {});
  403. this.setRules(formConfig.rules || {});
  404. this.validateMessages = formConfig.validateMessages;
  405. }
  406. /**
  407. * 用户传入的rules转换成async-validator rules
  408. * @param rules 校验规则
  409. */
  410. Form.prototype.transformRules = function (rules) {
  411. var _this = this;
  412. var result = {};
  413. Object.keys(rules).forEach(function (name) {
  414. var rule = rules[name];
  415. var list = (result[name] = []);
  416. var arr = Array.isArray(rule) ? rule : [rule];
  417. arr.forEach(function (item) {
  418. if (typeof item === 'function') {
  419. list.push(item(_this).validator);
  420. }
  421. else {
  422. list.push(__assign({}, item));
  423. }
  424. });
  425. });
  426. return result;
  427. };
  428. /**
  429. * 遍历表单field对象
  430. * @param callback
  431. */
  432. Form.prototype.eachField = function (callback) {
  433. var fields = this.fields;
  434. Object.keys(fields).forEach(function (name) {
  435. var field = fields[name];
  436. callback(field, name);
  437. });
  438. };
  439. /**
  440. * 更新 rules
  441. * @param rules
  442. */
  443. Form.prototype.updateRules = function (rules) {
  444. var _this = this;
  445. var rawRules = this.transformRules(rules);
  446. this.rules = rawRules;
  447. Object.keys(this.fields).forEach(function (name) {
  448. _this.fields[name].updateFieldRules(rawRules, _this.validateMessages);
  449. });
  450. };
  451. /**
  452. * 设置 rules
  453. * @param rules
  454. */
  455. Form.prototype.setRules = function (rules) {
  456. this.rules = this.transformRules(rules);
  457. };
  458. /**
  459. * 添加表单对象
  460. * @param ref 表单ref对象
  461. */
  462. Form.prototype.addItem = function (ref, customName) {
  463. var _this = this;
  464. var props = ref.getProps();
  465. var name = customName || props.name;
  466. if (!name) {
  467. ref.on(function (trigger, value) {
  468. if (trigger === 'deriveDataFromProps') {
  469. if (value.name) {
  470. _this.addItem(ref, value.name);
  471. }
  472. }
  473. });
  474. return;
  475. }
  476. if (this.fields[name]) {
  477. throw new Error("Form \"addItem\" same name: \"".concat(name, "\""));
  478. }
  479. var field = new Field(ref, name, this.initialValues, this.rules, this.validateMessages, props.required, props.label, props.message, props.validateTrigger);
  480. if (props.dependencies) {
  481. props.dependencies.forEach(function (item) {
  482. _this.dependenciesMap[item] = _this.dependenciesMap[item] || [];
  483. if (_this.dependenciesMap[item].indexOf(name) < 0) {
  484. _this.dependenciesMap[item].push(name);
  485. }
  486. });
  487. }
  488. field
  489. .on('valueChange', function (value) {
  490. if (name) {
  491. var arr = _this.dependenciesMap[name];
  492. if (arr) {
  493. arr.forEach(function (item) {
  494. if (_this.fields[item]) {
  495. _this.fields[item].validate();
  496. }
  497. });
  498. }
  499. _this.changeListeners.forEach(function (item) {
  500. var _a;
  501. return item((_a = {},
  502. _a[name] = value,
  503. _a), _this.getFieldsValue());
  504. });
  505. }
  506. })
  507. .on('didUnmount', function () {
  508. delete _this.fields[name];
  509. })
  510. .on('replaceName', function (newName) {
  511. if (!newName) {
  512. delete _this.fields[name];
  513. return;
  514. }
  515. if (_this.fields[newName]) {
  516. throw new Error("Form \"addItem\" same name: \"".concat(newName, "\""));
  517. }
  518. _this.fields[newName] = field;
  519. delete _this.fields[name];
  520. name = newName;
  521. });
  522. if (name) {
  523. this.fields[name] = field;
  524. }
  525. };
  526. /**
  527. * 设置表单值
  528. * @param name 表单名称
  529. * @param value 表单初始值
  530. */
  531. Form.prototype.setFieldValue = function (name, value) {
  532. var field = this.fields[name];
  533. if (field) {
  534. field.setValue(value);
  535. field.setValidatorStatus({
  536. status: 'success',
  537. errors: [],
  538. });
  539. }
  540. };
  541. /**
  542. * 设置表单值
  543. * @param name 表单名称
  544. * @param value 表单初始值
  545. */
  546. Form.prototype.setFieldsValue = function (values) {
  547. var _this = this;
  548. Object.keys(values).forEach(function (name) {
  549. _this.setFieldValue(name, values[name]);
  550. });
  551. };
  552. /**
  553. * 设置 initialValues,这个操作不会对页面进行修改,要是需要重置表单可跟上 reset 方法;
  554. * 这样是对于表单已经在编辑,但是需要重新initialValues的场景
  555. *
  556. * eg:
  557. * this.setInitialValues(initialValues);
  558. * this.reset();
  559. *
  560. * @param initialValues
  561. */
  562. Form.prototype.setInitialValues = function (initialValues) {
  563. this.initialValues = initialValues;
  564. };
  565. /**
  566. * 获取对应字段名的值
  567. * @param name
  568. * @returns
  569. */
  570. Form.prototype.getFieldValue = function (name) {
  571. var field = this.fields[name];
  572. if (!field) {
  573. return;
  574. }
  575. return field.getValue();
  576. };
  577. /**
  578. * 获取一组字段名对应的值
  579. * @param nameList
  580. * @returns
  581. */
  582. Form.prototype.getFieldsValue = function (nameList) {
  583. var _this = this;
  584. var fieldsValue = {};
  585. nameList = nameList || Object.keys(this.fields);
  586. nameList.forEach(function (name) {
  587. fieldsValue[name] = _this.getFieldValue(name);
  588. });
  589. return fieldsValue;
  590. };
  591. /**
  592. * 获取对应字段名的校验器状态
  593. * @param name
  594. * @returns
  595. */
  596. Form.prototype.getFieldValidatorStatus = function (name) {
  597. var field = this.fields[name];
  598. if (!field) {
  599. return;
  600. }
  601. return field.getValidatorStatus();
  602. };
  603. /**
  604. * 获取一组字段名的校验器状态
  605. * @param nameList
  606. * @returns
  607. */
  608. Form.prototype.getFieldsValidatorStatus = function (nameList) {
  609. var _this = this;
  610. var fieldsValidatorStatus = {};
  611. nameList = nameList || Object.keys(this.fields);
  612. nameList.forEach(function (name) {
  613. fieldsValidatorStatus[name] = _this.getFieldValidatorStatus(name);
  614. });
  615. return fieldsValidatorStatus;
  616. };
  617. /**
  618. * 设置对应字段名的校验器状态
  619. * @param name 表单名称
  620. * @param validatorStatus 校验状态
  621. * @returns
  622. */
  623. Form.prototype.setFieldValidatorStatus = function (name, validatorStatus) {
  624. var field = this.fields[name];
  625. if (!field) {
  626. return;
  627. }
  628. return field.setValidatorStatus(validatorStatus);
  629. };
  630. /**
  631. * 设置一组字段名的校验器状态
  632. * @param fieldsValidatorStatus 表单校验状态
  633. * @returns
  634. */
  635. Form.prototype.setFieldsValidatorStatus = function (fieldsValidatorStatus) {
  636. var _this = this;
  637. Object.keys(fieldsValidatorStatus).forEach(function (name) {
  638. _this.setFieldValidatorStatus(name, fieldsValidatorStatus[name]);
  639. });
  640. };
  641. /**
  642. * 检查对应字段是否被用户操作过
  643. * @param name 字段名称
  644. * @returns
  645. */
  646. Form.prototype.isFieldTouched = function (name) {
  647. var field = this.fields[name];
  648. if (!field) {
  649. return false;
  650. }
  651. return field.isTouched();
  652. };
  653. /**
  654. * 指定表单字段值更新时触发回调方法
  655. * @param name 表单字段名称
  656. * @param callback 回调方法
  657. */
  658. Form.prototype.onValueChange = function (name, callback) {
  659. this.changeListeners.push(function (changedValues, allValues) {
  660. if (name in changedValues) {
  661. callback(changedValues[name], allValues);
  662. }
  663. });
  664. };
  665. /**
  666. * 表单字段值更新时触发回调方法
  667. * @param name 表单字段名称
  668. * @param callback 回调方法
  669. */
  670. Form.prototype.onValuesChange = function (callback) {
  671. this.changeListeners.push(function (changedValues, allValues) {
  672. callback(changedValues, allValues);
  673. });
  674. };
  675. /**
  676. * 表单提交
  677. */
  678. Form.prototype.submit = function () {
  679. return __awaiter(this, void 0, void 0, function () {
  680. var values, arr, result, errorFields;
  681. var _this = this;
  682. return __generator(this, function (_a) {
  683. switch (_a.label) {
  684. case 0:
  685. values = {};
  686. arr = [];
  687. this.eachField(function (field, name) {
  688. arr.push((function () { return __awaiter(_this, void 0, void 0, function () {
  689. var _a;
  690. return __generator(this, function (_b) {
  691. switch (_b.label) {
  692. case 0:
  693. _a = [{}];
  694. return [4 /*yield*/, field.validate()];
  695. case 1: return [2 /*return*/, __assign.apply(void 0, [__assign.apply(void 0, _a.concat([(_b.sent())])), { name: name }])];
  696. }
  697. });
  698. }); })());
  699. });
  700. return [4 /*yield*/, Promise.all(arr)];
  701. case 1:
  702. result = _a.sent();
  703. errorFields = [];
  704. result.forEach(function (obj) {
  705. if (!obj) {
  706. return;
  707. }
  708. var name = obj.name, value = obj.value, validatorStatus = obj.validatorStatus;
  709. if (validatorStatus.status === 'error') {
  710. errorFields.push({
  711. name: name,
  712. errors: validatorStatus.errors,
  713. });
  714. }
  715. values[name] = value;
  716. });
  717. if (errorFields.length > 0) {
  718. throw {
  719. values: values,
  720. errorFields: errorFields,
  721. };
  722. }
  723. return [2 /*return*/, values];
  724. }
  725. });
  726. });
  727. };
  728. /**
  729. * 表单重置
  730. */
  731. Form.prototype.reset = function () {
  732. var _this = this;
  733. this.eachField(function (field, name) {
  734. var initialValue = _this.initialValues[name];
  735. field.reset(initialValue);
  736. });
  737. };
  738. return Form;
  739. }());
  740. export { Form };
  741. export function createForm(_a) {
  742. var _b = _a === void 0 ? {} : _a, _c = _b.methods, methods = _c === void 0 ? {} : _c;
  743. return {
  744. data: {
  745. formData: {
  746. value: undefined,
  747. status: 'default',
  748. errors: [],
  749. },
  750. },
  751. didUnmount: function () {
  752. this.emit('didUnmount');
  753. },
  754. deriveDataFromProps: function (nextProps) {
  755. this.emit('deriveDataFromProps', nextProps);
  756. },
  757. methods: __assign({ emit: function (trigger, value) { }, setFormData: function (values) {
  758. this.setData(__assign(__assign({}, this.data), { formData: __assign(__assign({}, this.data.formData), values) }));
  759. }, getFormData: function () {
  760. return this.data.formData;
  761. }, on: function (callback) {
  762. this.emit = callback;
  763. }, getProps: function () {
  764. return this.props;
  765. } }, methods),
  766. };
  767. }