tdesign-vue
Version:
1,074 lines (1,030 loc) • 43.3 kB
JavaScript
/**
* tdesign v1.11.2
* (c) 2025 tdesign
* @license MIT
*/
;
Object.defineProperty(exports, '__esModule', { value: true });
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _typeof = require('@babel/runtime/helpers/typeof');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var Vue = require('vue');
var tdesignIconsVue = require('tdesign-icons-vue');
var form_formModel = require('./form-model.js');
var form_formItemProps = require('./form-item-props.js');
var utils_mixins = require('../utils/mixins.js');
var configProvider_configReceiver = require('../config-provider/config-receiver.js');
var _common_js_log_log = require('../_common/js/log/log.js');
var utils_renderTnode = require('../utils/render-tnode.js');
var isNil = require('../_chunks/dep-8b3c7277.js');
var get = require('../_chunks/dep-f84d1ea5.js');
var cloneDeep = require('../_chunks/dep-f45125c9.js');
var _initCloneObject = require('../_chunks/dep-87c765cc.js');
var configProvider_context = require('../_chunks/dep-07fb8c0e.js');
var _overRest = require('../_chunks/dep-b3120c1b.js');
var isArrayLikeObject = require('../_chunks/dep-9f4caea4.js');
var _baseGetTag = require('../_chunks/dep-a4308f57.js');
var isObjectLike = require('../_chunks/dep-e4278c54.js');
var isPlainObject = require('../_chunks/dep-68ba2357.js');
var toString = require('../_chunks/dep-201f7798.js');
var eq = require('../_chunks/dep-ab142eaf.js');
var _isIterateeCall = require('../_chunks/dep-173eb46c.js');
var _getAllKeys = require('../_chunks/dep-63b02f7b.js');
var _createCompounder = require('../_chunks/dep-6478392e.js');
var set = require('../_chunks/dep-7a2463e1.js');
require('../_chunks/dep-27dd8cc6.js');
require('../utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('@babel/runtime/helpers/slicedToArray');
require('../_chunks/dep-7c854ec6.js');
require('../_chunks/dep-eceed11d.js');
require('../_chunks/dep-f8a85d6a.js');
require('../_chunks/dep-5b117689.js');
require('../_chunks/dep-a6490a32.js');
require('../_chunks/dep-3eec664c.js');
require('../_chunks/dep-8b1e056e.js');
require('../_chunks/dep-5db8defc.js');
require('../_chunks/dep-ecccff93.js');
require('../_chunks/dep-a4cecac4.js');
require('../_chunks/dep-6e4c473c.js');
require('../_chunks/dep-3d8ab37d.js');
require('../_chunks/dep-eeb2e214.js');
require('../_chunks/dep-6ad3de7c.js');
require('../_chunks/dep-fcf0662d.js');
require('../_chunks/dep-aa0a4aac.js');
require('@babel/runtime/helpers/readOnlyError');
require('@vue/composition-api');
require('../_chunks/dep-47bca35e.js');
require('../_chunks/dep-362bc4d7.js');
require('../_chunks/dep-d3015b4c.js');
require('../_chunks/dep-a4747856.js');
require('../_chunks/dep-f33eb57d.js');
require('../_chunks/dep-75cd6d52.js');
require('../_chunks/dep-b1a02818.js');
require('../_chunks/dep-bebcd284.js');
require('../_chunks/dep-234b7c02.js');
require('../_common/js/global-config/default-config.js');
require('../_common/js/global-config/locale/zh_CN.js');
require('../_chunks/dep-a4a18104.js');
require('dayjs');
require('../_chunks/dep-932dd69e.js');
require('../_chunks/dep-dbd838d6.js');
require('../_chunks/dep-73fb598e.js');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator);
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
var Vue__default = /*#__PURE__*/_interopDefaultLegacy(Vue);
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = configProvider_context.createAssigner(function (object, source, srcIndex, customizer) {
_initCloneObject.copyObject(source, _initCloneObject.keysIn(source), object, customizer);
});
/** `Object#toString` result references. */
var domExcTag = '[object DOMException]',
errorTag = '[object Error]';
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
if (!isObjectLike.isObjectLike(value)) {
return false;
}
var tag = _baseGetTag.baseGetTag(value);
return tag == errorTag || tag == domExcTag || typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject.isPlainObject(value);
}
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
*/
var attempt = isArrayLikeObject.baseRest(function (func, args) {
try {
return _overRest.apply(func, undefined, args);
} catch (e) {
return isError(e) ? e : new Error(e);
}
});
var attempt$1 = attempt;
/** Used to map characters to HTML entities. */
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/**
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
var escapeHtmlChar = _createCompounder.basePropertyOf(htmlEscapes);
/** Used to match HTML entities and HTML characters. */
var reUnescapedHtml = /[&<>"']/g,
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/**
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional
* characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value. See
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* When working with HTML you should always
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
* XSS vectors.
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function escape(string) {
string = toString.toString(string);
return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string;
}
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return toString.arrayMap(props, function (key) {
return object[key];
});
}
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined || eq.eq(objValue, objectProto$1[key]) && !hasOwnProperty$1.call(object, key)) {
return srcValue;
}
return objValue;
}
/** Used to escape characters for inclusion in compiled string literals. */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
"\u2028": 'u2028',
"\u2029": 'u2029'
};
/**
* Used by `_.template` to escape characters for inclusion in compiled string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(chr) {
return '\\' + stringEscapes[chr];
}
/** Used to match template delimiters. */
var reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match template delimiters. */
var reEscape = /<%-([\s\S]+?)%>/g;
/** Used to match template delimiters. */
var reEvaluate = /<%([\s\S]+?)%>/g;
/**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB) as well as ES2015 template strings. Change the
* following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type {Object}
*/
var templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'escape': reEscape,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'evaluate': reEvaluate,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type {string}
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type {Object}
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type {Function}
*/
'_': {
'escape': escape
}
}
};
/** Error message constants. */
var INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/**
* Used to validate the `validate` option in `_.template` variable.
*
* Forbids characters which could potentially change the meaning of the function argument definition:
* - "()," (modification of function parameters)
* - "=" (default value)
* - "[]{}" (destructuring of function parameters)
* - "/" (beginning of a comment)
* - whitespace
*/
var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
/**
* Used to match
* [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to ensure capturing order of template delimiters. */
var reNoMatch = /($^)/;
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is given, it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options={}] The options object.
* @param {RegExp} [options.escape=_.templateSettings.escape]
* The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
* The "evaluate" delimiter.
* @param {Object} [options.imports=_.templateSettings.imports]
* An object to import into the template as free variables.
* @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
* The "interpolate" delimiter.
* @param {string} [options.sourceURL='templateSources[n]']
* The sourceURL of the compiled template.
* @param {string} [options.variable='obj']
* The data object variable name.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the compiled template function.
* @example
*
* // Use the "interpolate" delimiter to create a compiled template.
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // Use the HTML "escape" delimiter to escape data property values.
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b><script></b>'
*
* // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the internal `print` function in "evaluate" delimiters.
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // Use the ES template literal delimiter as an "interpolate" delimiter.
* // Disable support by replacing the "interpolate" delimiter.
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // Use backslashes to treat delimiters as plain text.
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // Use the `imports` option to import `jQuery` as `jq`.
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the `sourceURL` option to specify a custom sourceURL for the template.
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
*
* // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
*
* // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // Use the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and stack traces.
* fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(string, options, guard) {
// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = templateSettings.imports._.templateSettings || templateSettings;
if (guard && _isIterateeCall.isIterateeCall(string, options, guard)) {
options = undefined;
}
string = toString.toString(string);
options = assignInWith({}, options, settings, customDefaultsAssignIn);
var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
importsKeys = _getAllKeys.keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp((options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$', 'g');
// Use a sourceURL for easier debugging.
// The sourceURL gets injected into the source that's eval-ed, so be careful
// to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
// and escape the comment, thus injecting code that gets evaled.
var sourceURL = hasOwnProperty.call(options, 'sourceURL') ? '//# sourceURL=' + (options.sourceURL + '').replace(/\s/g, ' ') + '\n' : '';
string.replace(reDelimiters, function (match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = hasOwnProperty.call(options, 'variable') && options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// Throw an error if a forbidden character was found in `variable`, to prevent
// potential command injection attacks.
else if (reForbiddenIdentifierChars.test(variable)) {
throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
}
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source).replace(reEmptyStringMiddle, '$1').replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n') + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '') + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n') + source + 'return __p\n}';
var result = attempt$1(function () {
return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty__default["default"](e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var VALIDATE_STATUS = /* @__PURE__ */function (VALIDATE_STATUS2) {
VALIDATE_STATUS2["TO_BE_VALIDATED"] = "not";
VALIDATE_STATUS2["SUCCESS"] = "success";
VALIDATE_STATUS2["FAIL"] = "fail";
return VALIDATE_STATUS2;
}(VALIDATE_STATUS || {});
function getFormItemClassName(componentName, name) {
if (!name) return "";
return "".concat(componentName, "-item__").concat(name).replace(/(\[|\]\.|'|")/g, "_");
}
var _FormItem = utils_mixins["default"](configProvider_configReceiver["default"]("form"), configProvider_configReceiver.getGlobalIconMixins()).extend({
name: "TFormItem",
props: _objectSpread({}, form_formItemProps["default"]),
inject: {
form: {
"default": void 0
}
},
provide: function provide() {
return {
tFormItem: this
};
},
data: function data() {
return {
errorList: [],
successList: [],
verifyStatus: "not" /* TO_BE_VALIDATED */,
resetValidating: false,
needResetField: false,
initialValue: void 0,
freeShowErrorMessage: void 0
};
},
computed: {
needErrorMessage: function needErrorMessage() {
if (this.freeShowErrorMessage !== void 0) return this.freeShowErrorMessage;
if (typeof this.showErrorMessage === "boolean") return this.showErrorMessage;
var parent = this.form;
return parent === null || parent === void 0 ? void 0 : parent.showErrorMessage;
},
classes: function classes() {
return ["".concat(this.componentName, "__item"), getFormItemClassName(this.componentName, this.name), _defineProperty__default["default"](_defineProperty__default["default"]({}, "".concat(this.componentName, "__item-with-help"), this.help), "".concat(this.componentName, "__item-with-extra"), this.extraNode)];
},
extraNode: function extraNode() {
var h = this.$createElement;
var list = this.errorList;
if (this.needErrorMessage && list && list[0] && list[0].message) {
return h("div", {
"class": "".concat(this.classPrefix, "-input__extra")
}, [list[0].message]);
}
if (this.successList.length) {
return h("div", {
"class": "".concat(this.classPrefix, "-input__extra")
}, [this.successList[0].message]);
}
return null;
},
labelClasses: function labelClasses() {
var parent = this.form;
var labelAlign = isNil.isNil(this.labelAlign) ? parent === null || parent === void 0 ? void 0 : parent.labelAlign : this.labelAlign;
var labelWidth = isNil.isNil(this.labelWidth) ? parent === null || parent === void 0 ? void 0 : parent.labelWidth : this.labelWidth;
return ["".concat(this.componentName, "__label"), _defineProperty__default["default"](_defineProperty__default["default"](_defineProperty__default["default"](_defineProperty__default["default"](_defineProperty__default["default"]({}, "".concat(this.componentName, "__label--required"), this.needRequiredMark), "".concat(this.componentName, "__label--required-right"), this.needRequiredMark && this.requiredMarkPosition === "right"), "".concat(this.componentName, "__label--top"), this.getLabelContent() && (labelAlign === "top" || !labelWidth)), "".concat(this.componentName, "__label--left"), labelAlign === "left" && labelWidth), "".concat(this.componentName, "__label--right"), labelAlign === "right" && labelWidth)];
},
errorClasses: function errorClasses() {
if (!this.needErrorMessage) return "";
if (this.verifyStatus === "success" /* SUCCESS */) {
return this.successBorder ? [this.commonStatusClassName.success, "".concat(this.componentName, "--success-border")].join(" ") : this.commonStatusClassName.success;
}
if (this.status) return this.statusClass;
var list = this.errorList;
if (!list.length) return;
var type = list[0].type || "error";
return type === "error" ? this.commonStatusClassName.error : this.commonStatusClassName.warning;
},
disabled: function disabled() {
return this.form.disabled;
},
contentClasses: function contentClasses() {
var getErrorClass = this.errorClasses;
return ["".concat(this.componentName, "__controls"), getErrorClass];
},
contentStyle: function contentStyle() {
var parent = this.form;
var labelAlign = isNil.isNil(this.labelAlign) ? parent === null || parent === void 0 ? void 0 : parent.labelAlign : this.labelAlign;
var labelWidth = isNil.isNil(this.labelWidth) ? parent === null || parent === void 0 ? void 0 : parent.labelWidth : this.labelWidth;
var contentStyle = {};
if (this.getLabelContent() && labelWidth && labelAlign !== "top") {
if (typeof labelWidth === "number") {
contentStyle = {
marginLeft: "".concat(labelWidth, "px")
};
} else {
contentStyle = {
marginLeft: labelWidth
};
}
}
return contentStyle;
},
value: function value() {
var parent = this.form;
return parent && parent.data && get.get(parent.data, this.name);
},
hasColon: function hasColon() {
var parent = this.form;
return !!(parent && parent.colon && this.getLabelContent());
},
needRequiredMark: function needRequiredMark() {
var _ref3, _this$$props$required;
var requiredMark = (_ref3 = (_this$$props$required = this.$props.requiredMark) !== null && _this$$props$required !== void 0 ? _this$$props$required : this.form.requiredMark) !== null && _ref3 !== void 0 ? _ref3 : this.global.requiredMark;
var isRequired = this.innerRules.filter(function (rule) {
return rule.required;
}).length > 0;
return requiredMark || (requiredMark !== null && requiredMark !== void 0 ? requiredMark : isRequired);
},
requiredMarkPosition: function requiredMarkPosition() {
var _this$form$requiredMa;
return (_this$form$requiredMa = this.form.requiredMarkPosition) !== null && _this$form$requiredMa !== void 0 ? _this$form$requiredMa : "left";
},
innerRules: function innerRules() {
var _this$rules;
var parent = this.form;
if ((_this$rules = this.rules) !== null && _this$rules !== void 0 && _this$rules.length) return this.rules || [];
if (!this.name) return [];
var index = String(this.name || "").lastIndexOf(".") || -1;
var pRuleName = String(this.name || "").slice(index + 1);
return get.get(parent === null || parent === void 0 ? void 0 : parent.rules, this.name) || get.get(parent === null || parent === void 0 ? void 0 : parent.rules, pRuleName) || [];
},
errorMessages: function errorMessages() {
var _this$form$errorMessa;
return (_this$form$errorMessa = this.form.errorMessage) !== null && _this$form$errorMessa !== void 0 ? _this$form$errorMessa : this.global.errorMessage;
},
statusClass: function statusClass() {
return "".concat(this.classPrefix, "-is-").concat(this.$props.status || "default", " ").concat(this.$props.status === "success" ? "".concat(this.componentName, "--success-border") : "");
}
},
created: function created() {
var _this = this;
this.addWatch();
this.$watch(function () {
if (_typeof__default["default"](_this.value) === "object") return JSON.stringify(_this.value);
return _this.value;
}, function () {
_this.validate("change");
});
this.$watch(function () {
return [_this.name, JSON.stringify(_this.rules)].join(",");
}, function () {
_this.validate("change");
});
},
mounted: function mounted() {
this.initialValue = cloneDeep.cloneDeep(this.value);
this.form.$emit("form-item-created", this);
},
beforeDestroy: function beforeDestroy() {
this.form.$emit("form-item-destroyed", this);
},
methods: {
addWatch: function addWatch() {
var _this2 = this;
if (this.disabled === void 0) return;
this.$watch("disabled", function (val) {
_this2.$nextTick(function () {
_this2.setChildrenDisabled(val, _this2.$children);
});
}, {
immediate: true
});
},
setChildrenDisabled: function setChildrenDisabled(disabled, children) {
var _this3 = this;
children.forEach(function (item) {
var _this3$form$controlle, _item$$children;
if ((_this3$form$controlle = _this3.form.controlledComponents) !== null && _this3$form$controlle !== void 0 && _this3$form$controlle.includes(item.$options.name)) {
item.$data.formDisabled = disabled;
}
if ((_item$$children = item.$children) !== null && _item$$children !== void 0 && _item$$children.length) {
_this3.setChildrenDisabled(disabled, item.$children);
}
});
},
setValidateMessage: function setValidateMessage(validateMessage) {
if (!validateMessage || !Array.isArray(validateMessage)) return;
if (validateMessage.length === 0) {
this.errorList = [];
this.verifyStatus = "success" /* SUCCESS */;
return;
}
this.errorList = validateMessage;
this.verifyStatus = "fail" /* FAIL */;
},
validate: function validate(trigger) {
var _arguments = arguments,
_this4 = this;
return _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
var showErrorMessage, source, _yield$_this4$analysi, errorList, resultList, successList, rules, allowSetValue;
return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
showErrorMessage = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : true;
source = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : "submit-event";
_this4.freeShowErrorMessage = source === "submit-function" ? showErrorMessage : void 0;
_this4.resetValidating = true;
_context.next = 6;
return _this4.analysisValidateResult(trigger);
case 6:
_yield$_this4$analysi = _context.sent;
errorList = _yield$_this4$analysi.errorList;
resultList = _yield$_this4$analysi.resultList;
successList = _yield$_this4$analysi.successList;
rules = _yield$_this4$analysi.rules;
allowSetValue = _yield$_this4$analysi.allowSetValue;
if (allowSetValue) {
_this4.errorList = errorList;
_this4.successList = successList;
}
if (rules.length) {
_this4.verifyStatus = errorList.length ? "fail" /* FAIL */ : "success" /* SUCCESS */;
} else {
_this4.verifyStatus = "not" /* TO_BE_VALIDATED */;
}
if (_this4.needResetField) {
_this4.resetHandler();
}
_this4.resetValidating = false;
return _context.abrupt("return", _defineProperty__default["default"]({}, _this4.name, errorList.length === 0 ? true : resultList));
case 17:
case "end":
return _context.stop();
}
}, _callee);
}))();
},
validateOnly: function validateOnly(trigger) {
var _this5 = this;
return _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2() {
var _yield$_this5$analysi, errorList, resultList;
return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return _this5.analysisValidateResult(trigger);
case 2:
_yield$_this5$analysi = _context2.sent;
errorList = _yield$_this5$analysi.errorList;
resultList = _yield$_this5$analysi.resultList;
return _context2.abrupt("return", _defineProperty__default["default"]({}, _this5.name, errorList.length === 0 ? true : resultList));
case 6:
case "end":
return _context2.stop();
}
}, _callee2);
}))();
},
analysisValidateResult: function analysisValidateResult(trigger) {
var _this6 = this;
return _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3() {
var result;
return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
result = {
successList: [],
errorList: [],
rules: [],
resultList: [],
allowSetValue: false
};
result.rules = trigger === "all" ? _this6.innerRules : _this6.innerRules.filter(function (item) {
var _item$trigger = item.trigger,
validateTrigger = _item$trigger === void 0 ? "change" : _item$trigger;
if (Array.isArray(validateTrigger)) {
return validateTrigger.includes(trigger);
}
return trigger === validateTrigger;
});
if (!(_this6.innerRules.length && !result.rules.length)) {
_context3.next = 4;
break;
}
return _context3.abrupt("return", result);
case 4:
result.allowSetValue = true;
_context3.next = 7;
return form_formModel.validate(_this6.value, result.rules);
case 7:
result.resultList = _context3.sent;
result.errorList = result.resultList.filter(function (item) {
return item.result !== true;
}).map(function (item) {
Object.keys(item).forEach(function (key) {
if (typeof item.message === "undefined" && _this6.errorMessages[key]) {
var compiled = template(_this6.errorMessages[key]);
var name = typeof _this6.label === "string" ? _this6.label : _this6.name;
item.message = compiled({
name: name,
validate: item[key]
});
}
});
return item;
});
result.successList = result.resultList.filter(function (item) {
return item.result === true && item.message && item.type === "success";
});
return _context3.abrupt("return", result);
case 11:
case "end":
return _context3.stop();
}
}, _callee3);
}))();
},
getLabelContent: function getLabelContent() {
if (typeof this.label === "function") {
return this.label(this.$createElement);
}
if (typeof this.$scopedSlots.label === "function") {
return this.$scopedSlots.label(null);
}
return this.label;
},
getLabel: function getLabel() {
var h = this.$createElement;
var parent = this.form;
var labelWidth = isNil.isNil(this.labelWidth) ? parent === null || parent === void 0 ? void 0 : parent.labelWidth : this.labelWidth;
var labelAlign = isNil.isNil(this.labelAlign) ? parent === null || parent === void 0 ? void 0 : parent.labelAlign : this.labelAlign;
if (Number(labelWidth) === 0) return;
var labelContent = this.getLabelContent();
if (!labelContent) return null;
var labelStyle = {};
if (labelWidth && labelAlign !== "top") {
if (typeof labelWidth === "number") {
labelStyle = {
width: "".concat(labelWidth, "px")
};
} else {
labelStyle = {
width: labelWidth
};
}
}
return h("div", {
"class": this.labelClasses,
"style": labelStyle
}, [h("label", {
"attrs": {
"for": this["for"]
}
}, [labelContent]), this.hasColon && this.global.colonText]);
},
getDefaultIcon: function getDefaultIcon() {
var _this7 = this;
var h = this.$createElement;
var resultIcon = function resultIcon(Icon) {
return h("span", {
"class": "".concat(_this7.componentName, "__status")
}, [h(Icon)]);
};
var list = this.errorList;
var _this$useGlobalIcon = this.useGlobalIcon({
CheckCircleFilledIcon: tdesignIconsVue.CheckCircleFilledIcon,
CloseCircleFilledIcon: tdesignIconsVue.CloseCircleFilledIcon,
ErrorCircleFilledIcon: tdesignIconsVue.ErrorCircleFilledIcon
}),
CheckCircleFilledIcon = _this$useGlobalIcon.CheckCircleFilledIcon,
CloseCircleFilledIcon = _this$useGlobalIcon.CloseCircleFilledIcon,
ErrorCircleFilledIcon = _this$useGlobalIcon.ErrorCircleFilledIcon;
if (this.verifyStatus === "success" /* SUCCESS */) {
return resultIcon(CheckCircleFilledIcon);
}
if (list && list[0]) {
var type = list[0].type || "error";
var icon = {
error: CloseCircleFilledIcon,
warning: ErrorCircleFilledIcon
}[type] || CheckCircleFilledIcon;
return resultIcon(icon);
}
return null;
},
getIcon: function getIcon(statusIcon, slotStatusIcon, props2) {
var _this8 = this;
var h = this.$createElement;
var resultIcon = function resultIcon(otherContent) {
return h("span", {
"class": "".concat(_this8.componentName, "__status")
}, [otherContent]);
};
if (statusIcon === true) {
return this.getDefaultIcon();
}
if (typeof statusIcon === "function") {
return resultIcon(statusIcon(this.$createElement, props2));
}
if (typeof slotStatusIcon === "function") {
return resultIcon(slotStatusIcon(null));
}
return null;
},
getSuffixIcon: function getSuffixIcon() {
var parent = this.form;
var statusIcon = this.statusIcon;
var slotStatusIcon = this.$scopedSlots.statusIcon;
var parentStatusIcon = parent.statusIcon;
var parentSlotStatusIcon = parent.$scopedSlots.statusIcon;
if (statusIcon === false) return;
var resultIcon = this.getIcon(statusIcon, slotStatusIcon);
if (resultIcon) return resultIcon;
if (resultIcon === false) return;
resultIcon = this.getIcon(parentStatusIcon, parentSlotStatusIcon, this.$props);
if (resultIcon) return resultIcon;
},
getEmptyValue: function getEmptyValue() {
var parent = this.form;
var type = Object.prototype.toString.call(get.get(parent.data, this.name));
var emptyValue;
if (type === "[object String]") {
emptyValue = "";
}
if (type === "[object Array]") {
emptyValue = [];
}
if (type === "[object Object]") {
emptyValue = {};
}
return emptyValue;
},
resetField: function resetField() {
var _this9 = this;
var resetType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "initial";
var parent = this.form;
if (!this.name && this.label) {
_common_js_log_log["default"].warn("Form", "name is required for validating.");
return;
}
var tResetType = resetType || parent.resetType;
if (tResetType === "empty") {
set.set(parent.data, this.name, this.getEmptyValue());
}
if (tResetType === "initial") {
set.set(parent.data, this.name, this.initialValue);
}
Vue__default["default"].nextTick(function () {
if (_this9.resetValidating) {
_this9.needResetField = true;
} else {
_this9.resetHandler();
}
});
},
resetHandler: function resetHandler() {
this.needResetField = false;
this.errorList = [];
this.successList = [];
this.verifyStatus = "not" /* TO_BE_VALIDATED */;
}
},
render: function render() {
var h = arguments[0];
var helpNode = utils_renderTnode.renderTNodeJSX(this, "help");
var tipsNode = utils_renderTnode.renderTNodeJSX(this, "tips");
return h("div", {
"class": this.classes
}, [this.getLabel(), h("div", {
"class": this.contentClasses,
"style": this.contentStyle
}, [h("div", {
"class": "".concat(this.componentName, "__controls-content")
}, [this.$slots["default"], this.getSuffixIcon()]), helpNode && h("div", {
"class": "".concat(this.classPrefix, "-input__help")
}, [helpNode]), tipsNode && h("div", {
"class": ["".concat(this.componentName, "-tips"), "".concat(this.classPrefix, "-tips"), this.statusClass]
}, [tipsNode]), this.extraNode])]);
}
});
exports.VALIDATE_STATUS = VALIDATE_STATUS;
exports["default"] = _FormItem;
exports.getFormItemClassName = getFormItemClassName;
//# sourceMappingURL=form-item.js.map