hongluan-ui
Version:
Hongluan Component Library for Vue 3
363 lines (356 loc) • 13.9 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var vue = require('vue');
var AsyncValidator = require('async-validator');
var lodashUnified = require('lodash-unified');
var core = require('@vueuse/core');
require('../../../utils/index.js');
require('../../../hooks/index.js');
require('../../../tokens/index.js');
var index = require('../../row/index.js');
var index$1 = require('../../col/index.js');
var formItem = require('./form-item2.js');
var pluginVue_exportHelper = require('../../../_virtual/plugin-vue_export-helper.js');
var index$2 = require('../../../hooks/use-global-config/index.js');
var index$3 = require('../../../hooks/use-namespace/index.js');
var form = require('../../../tokens/form.js');
var index$4 = require('../../../hooks/use-id/index.js');
var shared = require('@vue/shared');
var objects = require('../../../utils/objects.js');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var AsyncValidator__default = /*#__PURE__*/_interopDefaultLegacy(AsyncValidator);
const _sfc_main = vue.defineComponent({
name: "FormItem",
components: { HlRow: index.HlRow, HlCol: index$1.HlCol },
props: formItem.formItemProps,
setup(props, { slots }) {
const HL = index$2.useGlobalConfig();
const { namespace } = index$3.useNamespace("form-item");
const formContext = vue.inject(form.formContextKey, void 0);
const labelId = index$4.useId().value;
const inputIds = vue.ref([]);
const validateState = vue.ref("");
const validateStateDebounced = core.refDebounced(validateState, 100);
const validateMessage = vue.ref("");
const formItemRef = vue.ref();
let initialValue = void 0;
let isResettingField = false;
const propString = vue.computed(() => {
if (!props.prop)
return "";
return shared.isString(props.prop) ? props.prop : props.prop.join(".");
});
const hasLabel = vue.computed(() => {
return !!(props.label || slots.label);
});
const labelFor = vue.computed(() => {
return props.for || (inputIds.value.length === 1 ? inputIds.value[0] : void 0);
});
const isGroup = vue.computed(() => {
return !labelFor.value && hasLabel.value;
});
const labelStyle = vue.computed(() => {
let width = props.width || (formContext == null ? void 0 : formContext.width);
width = Array.isArray(width) ? width : [width];
const labelWidth = width && width[0];
return labelWidth;
});
const contentStyle = vue.computed(() => {
let width = props.width || (formContext == null ? void 0 : formContext.width);
width = Array.isArray(width) ? width : [width];
const contentWidth = width && width[1];
const style = {};
if (contentWidth && !Number.isNaN(Number.parseInt(contentWidth, 10))) {
style.width = contentWidth;
}
return style;
});
const labelClass = vue.computed(() => {
let width = props.width || (formContext == null ? void 0 : formContext.width);
width = Array.isArray(width) ? width : [width];
const labelClazz = width && width[0];
let labelPosition = props.labelPosition || (formContext == null ? void 0 : formContext.labelPosition);
let clazz = "";
if (labelPosition) {
labelPosition = Array.isArray(labelPosition) ? labelPosition : [labelPosition];
clazz = labelPosition.join(" ");
}
if (labelClazz && Number.isNaN(Number.parseInt(labelClazz, 10))) {
clazz += " " + labelClazz;
}
return clazz;
});
const contentClass = vue.computed(() => {
let width = props.width || (formContext == null ? void 0 : formContext.width);
width = Array.isArray(width) ? width : [width];
const contentClazz = width && width[1];
if (contentClazz && Number.isNaN(Number.parseInt(contentClazz, 10))) {
return contentClazz;
}
return "";
});
const itemGap = vue.computed(() => {
return props.gap || (formContext == null ? void 0 : formContext.itemGap);
});
const sizeClass = vue.computed(() => {
return props.size || (formContext == null ? void 0 : formContext.size) || HL.value.size;
});
const formItemClass = vue.computed(() => [
{
[namespace.value]: true,
"form-item-feedback": formContext == null ? void 0 : formContext.statusIcon,
"is-error": validateState.value === "error",
"is-validating": validateState.value === "validating",
"is-success": validateState.value === "success",
"is-required": isRequired.value || props.required,
"is-no-asterisk": formContext == null ? void 0 : formContext.hideRequiredAsterisk
},
sizeClass.value ? sizeClass.value : "",
(formContext == null ? void 0 : formContext.requireAsteriskPosition) === "right" ? "asterisk-right" : "asterisk-left"
]);
const fieldValue = vue.computed(() => {
const model = formContext == null ? void 0 : formContext.model;
if (!model || !props.prop) {
return;
}
return objects.getProp(model, props.prop).value;
});
const normalizedRules = vue.computed(() => {
const { required } = props;
const rules = [];
if (props.rules) {
rules.push(...lodashUnified.castArray(props.rules));
}
const formRules = formContext == null ? void 0 : formContext.rules;
if (formRules && props.prop) {
const _rules = objects.getProp(formRules, props.prop).value;
if (_rules) {
rules.push(...lodashUnified.castArray(_rules));
}
}
if (required !== void 0) {
const requiredRules = rules.map((rule, i) => [rule, i]).filter(([rule]) => Object.keys(rule).includes("required"));
if (requiredRules.length > 0) {
for (const [rule, i] of requiredRules) {
if (rule.required === required)
continue;
rules[i] = { ...rule, required };
}
} else {
rules.push({ required });
}
}
return rules;
});
const validateEnabled = vue.computed(() => normalizedRules.value.length > 0);
const getFilteredRule = (trigger) => {
const rules = normalizedRules.value;
return rules.filter((rule) => {
if (!rule.trigger || !trigger)
return true;
if (Array.isArray(rule.trigger)) {
return rule.trigger.includes(trigger);
} else {
return rule.trigger === trigger;
}
}).map(({ trigger: trigger2, ...rule }) => rule);
};
const isRequired = vue.computed(() => normalizedRules.value.some((rule) => rule.required));
const shouldShowError = vue.computed(() => {
return validateStateDebounced.value === "error" && props.showMessage && formContext.showMessage;
});
const currentLabel = vue.computed(() => ((formContext == null ? void 0 : formContext.labelPrefix) || "") + (props.label || "") + ((formContext == null ? void 0 : formContext.labelSuffix) || ""));
const setValidationState = (state) => {
validateState.value = state;
};
const onValidationFailed = (error) => {
var _a, _b;
const { errors, fields } = error;
if (!errors || !fields) {
console.error(error);
}
setValidationState("error");
validateMessage.value = errors ? (_b = (_a = errors == null ? void 0 : errors[0]) == null ? void 0 : _a.message) != null ? _b : `${props.prop} is required` : "";
formContext == null ? void 0 : formContext.emit("validate", props.prop, false, validateMessage.value);
};
const onValidationSucceeded = () => {
setValidationState("success");
formContext == null ? void 0 : formContext.emit("validate", props.prop, true, "");
};
const doValidate = async (rules) => {
const modelName = propString.value;
const validator = new AsyncValidator__default["default"]({
[modelName]: rules
});
return validator.validate({ [modelName]: fieldValue.value }, { firstFields: true }).then(() => {
onValidationSucceeded();
return true;
}).catch((err) => {
onValidationFailed(err);
return Promise.reject(err);
});
};
const validate = async (trigger, callback) => {
if (isResettingField || !props.prop) {
return false;
}
const hasCallback = shared.isFunction(callback);
if (!validateEnabled.value) {
callback == null ? void 0 : callback(false);
return false;
}
const rules = getFilteredRule(trigger);
if (rules.length === 0) {
callback == null ? void 0 : callback(true);
return true;
}
setValidationState("validating");
return doValidate(rules).then(() => {
callback == null ? void 0 : callback(true);
return true;
}).catch((err) => {
const { fields } = err;
callback == null ? void 0 : callback(false, fields);
return hasCallback ? false : Promise.reject(fields);
});
};
const clearValidate = () => {
setValidationState("");
validateMessage.value = "";
isResettingField = false;
};
const resetField = async () => {
const model = formContext == null ? void 0 : formContext.model;
if (!model || !props.prop)
return;
const computedValue = objects.getProp(model, props.prop);
isResettingField = true;
computedValue.value = lodashUnified.clone(initialValue);
await vue.nextTick();
clearValidate();
isResettingField = false;
};
const addInputId = (id) => {
if (!inputIds.value.includes(id)) {
inputIds.value.push(id);
}
};
const removeInputId = (id) => {
inputIds.value = inputIds.value.filter((listId) => listId !== id);
};
vue.watch(() => props.error, (val) => {
validateMessage.value = val || "";
setValidationState(val ? "error" : "");
}, { immediate: true });
vue.watch(() => props.validateStatus, (val) => setValidationState(val || ""));
const formItemContext = vue.reactive({
...vue.toRefs(props),
size: sizeClass,
labelId,
inputIds,
isGroup,
fieldValue,
addInputId,
removeInputId,
validateState,
$el: formItemRef,
resetField,
clearValidate,
validate
});
vue.provide(form.formItemContextKey, formItemContext);
vue.onMounted(() => {
if (props.prop) {
formContext == null ? void 0 : formContext.addField(formItemContext);
initialValue = lodashUnified.clone(fieldValue.value);
}
});
vue.onBeforeUnmount(() => {
formContext == null ? void 0 : formContext.removeField(formItemContext);
});
return {
formItemRef,
formItemClass,
validate,
resetField,
clearValidate,
validateState,
hasLabel,
labelId,
inputIds,
isGroup,
shouldShowError,
formContext,
labelStyle,
contentStyle,
labelClass,
contentClass,
validateMessage,
labelFor,
itemGap,
currentLabel
};
}
});
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
var _a, _b;
const _component_hl_col = vue.resolveComponent("hl-col");
const _component_hl_row = vue.resolveComponent("hl-row");
return vue.openBlock(), vue.createBlock(_component_hl_row, {
ref: "formItemRef",
role: _ctx.isGroup ? "group" : void 0,
"aria-labelledby": _ctx.isGroup ? _ctx.labelId : void 0,
class: vue.normalizeClass([_ctx.formItemClass]),
gap: _ctx.itemGap,
"gap-x": (_a = _ctx.formContext) == null ? void 0 : _a.itemGapX,
"gap-y": (_b = _ctx.formContext) == null ? void 0 : _b.itemGapY
}, {
default: vue.withCtx(() => [
_ctx.label || _ctx.$slots.label ? (vue.openBlock(), vue.createBlock(_component_hl_col, {
key: 0,
class: vue.normalizeClass([_ctx.labelClass, "form-label"]),
style: vue.normalizeStyle({ width: _ctx.labelStyle })
}, {
default: vue.withCtx(() => [
_ctx.hasLabel ? (vue.openBlock(), vue.createBlock(vue.resolveDynamicComponent(_ctx.labelFor ? "label" : "div"), {
key: 0,
id: _ctx.labelId,
for: _ctx.labelFor
}, {
default: vue.withCtx(() => [
vue.renderSlot(_ctx.$slots, "label", { label: _ctx.currentLabel }, () => [
vue.createTextVNode(vue.toDisplayString(_ctx.currentLabel), 1)
])
]),
_: 3
}, 8, ["id", "for"])) : vue.createCommentVNode("v-if", true)
]),
_: 3
}, 8, ["class", "style"])) : vue.createCommentVNode("v-if", true),
vue.createVNode(_component_hl_col, {
class: vue.normalizeClass(["form-content", [_ctx.contentClass, _ctx.offset]]),
style: vue.normalizeStyle(_ctx.contentStyle)
}, {
default: vue.withCtx(() => [
vue.renderSlot(_ctx.$slots, "default"),
vue.createVNode(vue.TransitionGroup, { name: "zoom-in-top" }, {
default: vue.withCtx(() => [
_ctx.shouldShowError ? vue.renderSlot(_ctx.$slots, "error", {
key: 0,
error: _ctx.validateMessage
}, () => [
vue.createElementVNode("div", { class: "form-content-info" }, vue.toDisplayString(_ctx.validateMessage), 1)
]) : vue.createCommentVNode("v-if", true)
]),
_: 3
})
]),
_: 3
}, 8, ["class", "style"])
]),
_: 3
}, 8, ["role", "aria-labelledby", "class", "gap", "gap-x", "gap-y"]);
}
var FormItem = /* @__PURE__ */ pluginVue_exportHelper["default"](_sfc_main, [["render", _sfc_render]]);
exports["default"] = FormItem;
//# sourceMappingURL=form-item.js.map