tdesign-vue
Version:
517 lines (513 loc) • 22.4 kB
JavaScript
/**
* tdesign v1.14.1
* (c) 2025 tdesign
* @license MIT
*/
import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _typeof from '@babel/runtime/helpers/typeof';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import Vue from 'vue';
import { isNil, get, cloneDeep, template, set } from 'lodash-es';
import { CheckCircleFilledIcon, CloseCircleFilledIcon, ErrorCircleFilledIcon } from 'tdesign-icons-vue';
import { validate } from './form-model.js';
import props from './form-item-props.js';
import mixins from '../utils/mixins.js';
import getConfigReceiverMixins, { getGlobalIconMixins } from '../config-provider/config-receiver.js';
import log from '../_common/js/log/log.js';
import { renderTNodeJSX } from '../utils/render-tnode.js';
import '../_chunks/dep-fdb1b253.js';
import '../utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import '@babel/runtime/helpers/slicedToArray';
import '../config-provider/context.js';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.js';
import '../_chunks/dep-ba613a02.js';
import 'dayjs';
import '../_common/js/global-config/t.js';
import '@babel/runtime/helpers/readOnlyError';
import '@vue/composition-api';
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(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 = mixins(getConfigReceiverMixins("form"), getGlobalIconMixins()).extend({
name: "TFormItem",
props: _objectSpread({}, props),
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(_defineProperty({}, "".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(this.labelAlign) ? parent === null || parent === void 0 ? void 0 : parent.labelAlign : this.labelAlign;
var labelWidth = isNil(this.labelWidth) ? parent === null || parent === void 0 ? void 0 : parent.labelWidth : this.labelWidth;
return ["".concat(this.componentName, "__label"), _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, "".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(this.labelAlign) ? parent === null || parent === void 0 ? void 0 : parent.labelAlign : this.labelAlign;
var labelWidth = 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(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(parent === null || parent === void 0 ? void 0 : parent.rules, this.name) || 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(_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(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(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var showErrorMessage, source, _yield$_this4$analysi, errorList, resultList, successList, rules, allowSetValue;
return _regeneratorRuntime.wrap(function (_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 = 1;
return _this4.analysisValidateResult(trigger);
case 1:
_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({}, _this4.name, errorList.length === 0 ? true : resultList));
case 2:
case "end":
return _context.stop();
}
}, _callee);
}))();
},
validateOnly: function validateOnly(trigger) {
var _this5 = this;
return _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
var _yield$_this5$analysi, errorList, resultList;
return _regeneratorRuntime.wrap(function (_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 1;
return _this5.analysisValidateResult(trigger);
case 1:
_yield$_this5$analysi = _context2.sent;
errorList = _yield$_this5$analysi.errorList;
resultList = _yield$_this5$analysi.resultList;
return _context2.abrupt("return", _defineProperty({}, _this5.name, errorList.length === 0 ? true : resultList));
case 2:
case "end":
return _context2.stop();
}
}, _callee2);
}))();
},
analysisValidateResult: function analysisValidateResult(trigger) {
var _this6 = this;
return _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
var result;
return _regeneratorRuntime.wrap(function (_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 = 1;
break;
}
return _context3.abrupt("return", result);
case 1:
result.allowSetValue = true;
_context3.next = 2;
return validate(_this6.value, result.rules);
case 2:
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 3:
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(this.labelWidth) ? parent === null || parent === void 0 ? void 0 : parent.labelWidth : this.labelWidth;
var labelAlign = 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: CheckCircleFilledIcon,
CloseCircleFilledIcon: CloseCircleFilledIcon,
ErrorCircleFilledIcon: ErrorCircleFilledIcon
}),
CheckCircleFilledIcon$1 = _this$useGlobalIcon.CheckCircleFilledIcon,
CloseCircleFilledIcon$1 = _this$useGlobalIcon.CloseCircleFilledIcon,
ErrorCircleFilledIcon$1 = _this$useGlobalIcon.ErrorCircleFilledIcon;
if (this.verifyStatus === "success" /* SUCCESS */) {
return resultIcon(CheckCircleFilledIcon$1);
}
if (list && list[0]) {
var type = list[0].type || "error";
var icon = {
error: CloseCircleFilledIcon$1,
warning: ErrorCircleFilledIcon$1
}[type] || CheckCircleFilledIcon$1;
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(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) {
log.warn("Form", "name is required for validating.");
return;
}
var tResetType = resetType || parent.resetType;
if (tResetType === "empty") {
set(parent.data, this.name, this.getEmptyValue());
}
if (tResetType === "initial") {
set(parent.data, this.name, this.initialValue);
}
Vue.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 = renderTNodeJSX(this, "help");
var tipsNode = 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])]);
}
});
export { VALIDATE_STATUS, _FormItem as default, getFormItemClassName };
//# sourceMappingURL=form-item.js.map