UNPKG

ant-design-vue

Version:

An enterprise-class UI design language and Vue-based implementation

374 lines (303 loc) 13.1 kB
import _regeneratorRuntime from "@babel/runtime/regenerator"; function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } 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."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _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; } 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); } 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); } var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import RawAsyncValidator from 'async-validator'; import { cloneVNode } from 'vue'; import { warning } from '../../vc-util/warning'; import { setValues } from './valueUtil'; import { defaultValidateMessages } from './messages'; import { isValidElement } from '../../_util/props-util'; // Remove incorrect original ts define var AsyncValidator = RawAsyncValidator; /** * Replace with template. * `I'm ${name}` + { name: 'bamboo' } = I'm bamboo */ function replaceMessage(template, kv) { return template.replace(/\$\{\w+\}/g, function (str) { var key = str.slice(2, -1); return kv[key]; }); } /** * We use `async-validator` to validate rules. So have to hot replace the message with validator. * { required: '${name} is required' } => { required: () => 'field is required' } */ function convertMessages(messages, name, rule, messageVariables) { var kv = _extends(_extends({}, rule), { name: name, enum: (rule.enum || []).join(', ') }); var replaceFunc = function replaceFunc(template, additionalKV) { return function () { return replaceMessage(template, _extends(_extends({}, kv), additionalKV)); }; }; /* eslint-disable no-param-reassign */ function fillTemplate(source) { var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; Object.keys(source).forEach(function (ruleName) { var value = source[ruleName]; if (typeof value === 'string') { target[ruleName] = replaceFunc(value, messageVariables); } else if (value && _typeof(value) === 'object') { target[ruleName] = {}; fillTemplate(value, target[ruleName]); } else { target[ruleName] = value; } }); return target; } /* eslint-enable */ return fillTemplate(setValues({}, defaultValidateMessages, messages)); } function validateRule(name, value, rule, options, messageVariables) { return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { var cloneRule, subRuleField, validator, messages, result, subResults; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: cloneRule = _extends({}, rule); // We should special handle array validate subRuleField = null; if (cloneRule && cloneRule.type === 'array' && cloneRule.defaultField) { subRuleField = cloneRule.defaultField; delete cloneRule.defaultField; } if (!rule.type && typeof rule.validator !== 'function' && typeof value !== 'string' && typeof value !== 'undefined') { warning(false, "Form rules must provide type property when validating the form item named [".concat(name, "] which is not string type")); } validator = new AsyncValidator(_defineProperty({}, name, [cloneRule])); messages = convertMessages(options.validateMessages, name, cloneRule, messageVariables); validator.messages(messages); result = []; _context.prev = 8; _context.next = 11; return Promise.resolve(validator.validate(_defineProperty({}, name, value), _extends({}, options))); case 11: _context.next = 16; break; case 13: _context.prev = 13; _context.t0 = _context["catch"](8); if (_context.t0.errors) { result = _context.t0.errors.map(function (_ref, index) { var message = _ref.message; return (// Wrap VueNode with `key` isValidElement(message) ? cloneVNode(message, { key: "error_".concat(index) }) : message ); }); } else { console.error(_context.t0); result = [messages.default()]; } case 16: if (!(!result.length && subRuleField)) { _context.next = 21; break; } _context.next = 19; return Promise.all(value.map(function (subValue, i) { return validateRule("".concat(name, ".").concat(i), subValue, subRuleField, options, messageVariables); })); case 19: subResults = _context.sent; return _context.abrupt("return", subResults.reduce(function (prev, errors) { return [].concat(_toConsumableArray(prev), _toConsumableArray(errors)); }, [])); case 21: return _context.abrupt("return", result); case 22: case "end": return _context.stop(); } } }, _callee, null, [[8, 13]]); })); } /** * We use `async-validator` to validate the value. * But only check one value in a time to avoid namePath validate issue. */ export function validateRules(namePath, value, rules, options, validateFirst, messageVariables) { var _this = this; var name = namePath.join('.'); // Fill rule with context var filledRules = rules.map(function (currentRule) { var originValidatorFunc = currentRule.validator; if (!originValidatorFunc) { return currentRule; } return _extends(_extends({}, currentRule), { validator: function validator(rule, val, callback) { var hasPromise = false; // Wrap callback only accept when promise not provided var wrappedCallback = function wrappedCallback() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } // Wait a tick to make sure return type is a promise Promise.resolve().then(function () { warning(!hasPromise, 'Your validator function has already return a promise. `callback` will be ignored.'); if (!hasPromise) { callback.apply(void 0, args); } }); }; // Get promise var promise = originValidatorFunc(rule, val, wrappedCallback); hasPromise = promise && typeof promise.then === 'function' && typeof promise.catch === 'function'; /** * 1. Use promise as the first priority. * 2. If promise not exist, use callback with warning instead */ warning(hasPromise, '`callback` is deprecated. Please return a promise instead.'); if (hasPromise) { promise.then(function () { callback(); }).catch(function (err) { callback(err); }); } } }); }); var summaryPromise; if (validateFirst === true) { // >>>>> Validate by serialization summaryPromise = new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { var i, errors; return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: i = 0; case 1: if (!(i < filledRules.length)) { _context2.next = 11; break; } _context2.next = 4; return validateRule(name, value, filledRules[i], options, messageVariables); case 4: errors = _context2.sent; if (!errors.length) { _context2.next = 8; break; } resolve(errors); return _context2.abrupt("return"); case 8: i += 1; _context2.next = 1; break; case 11: /* eslint-enable */ resolve([]); case 12: case "end": return _context2.stop(); } } }, _callee2); })); }); } else { // >>>>> Validate by parallel var rulePromises = filledRules.map(function (rule) { return validateRule(name, value, rule, options, messageVariables); }); summaryPromise = (validateFirst ? finishOnFirstFailed(rulePromises) : finishOnAllFailed(rulePromises)).then(function (errors) { if (!errors.length) { return []; } return Promise.reject(errors); }); } // Internal catch error to avoid console error log. summaryPromise.catch(function (e) { return e; }); return summaryPromise; } function finishOnAllFailed(rulePromises) { return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { return _regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: return _context3.abrupt("return", Promise.all(rulePromises).then(function (errorsList) { var _ref2; var errors = (_ref2 = []).concat.apply(_ref2, _toConsumableArray(errorsList)); return errors; })); case 1: case "end": return _context3.stop(); } } }, _callee3); })); } function finishOnFirstFailed(rulePromises) { return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { var count; return _regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: count = 0; return _context4.abrupt("return", new Promise(function (resolve) { rulePromises.forEach(function (promise) { promise.then(function (errors) { if (errors.length) { resolve(errors); } count += 1; if (count === rulePromises.length) { resolve([]); } }); }); })); case 2: case "end": return _context4.stop(); } } }, _callee4); })); }