hongluan-ui
Version:
Hongluan Component Library for Vue 3
460 lines (457 loc) • 18.1 kB
JavaScript
import { defineComponent, ref, reactive, inject, computed, watch, onMounted, onUpdated, openBlock, createElementBlock, normalizeClass, unref, normalizeStyle, withModifiers, withDirectives, createBlock, withCtx, renderSlot, createVNode, createCommentVNode, withKeys, createSlots } from 'vue';
import { isNil } from 'lodash-unified';
import '../../../directives/index.mjs';
import { HlInput } from '../../input/index.mjs';
import { HlButton } from '../../button/index.mjs';
import { HlIcon } from '../../icon/index.mjs';
import '../../system-icon/index.mjs';
import '../../../hooks/index.mjs';
import '../../../tokens/index.mjs';
import '../../../utils/index.mjs';
import '../../../constants/index.mjs';
import { inputNumberProps, inputNumberEmits } from './input-number.mjs';
import { useLocale } from '../../../hooks/use-locale/index.mjs';
import { useNamespace } from '../../../hooks/use-namespace/index.mjs';
import { formItemContextKey, FormItemEvents } from '../../../tokens/form.mjs';
import { isNumber, isUndefined } from '../../../utils/types.mjs';
import { debugWarn, throwError } from '../../../utils/error.mjs';
import { useConsistentProp } from '../../../hooks/use-consistent-prop/index.mjs';
import { INPUT_EVENT, UPDATE_MODEL_EVENT, CHANGE_EVENT } from '../../../constants/event.mjs';
import { isString } from '@vue/shared';
import SystemRemove from '../../system-icon/src/remove.mjs';
import { vRepeatClick } from '../../../directives/repeat-click/index.mjs';
import SystemArrowUp from '../../system-icon/src/arrow-up.mjs';
import SystemArrowDown from '../../system-icon/src/arrow-down.mjs';
import SystemAdd from '../../system-icon/src/add.mjs';
const __default__ = defineComponent({
name: "InputNumber"
});
const _sfc_main = /* @__PURE__ */ defineComponent({
...__default__,
props: inputNumberProps,
emits: inputNumberEmits,
setup(__props, { expose, emit }) {
const props = __props;
const { t } = useLocale();
const { namespace } = useNamespace();
const input = ref();
const data = reactive({
currentValue: props.modelValue,
userInput: null
});
const formItem = inject(formItemContextKey, {});
const minDisabled = computed(() => isNumber(props.modelValue) && props.modelValue <= props.min);
const maxDisabled = computed(() => isNumber(props.modelValue) && props.modelValue >= props.max);
const numPrecision = computed(() => {
const stepPrecision = getPrecision(props.step);
if (!isUndefined(props.precision)) {
if (stepPrecision > props.precision) {
debugWarn("InputNumber", "precision should not be less than the decimal places of step");
}
return props.precision;
} else {
return Math.max(getPrecision(props.modelValue), stepPrecision);
}
});
const { size: inputNumberSize, disabled: inputNumberDisabled, fill: inputNumberFill } = useConsistentProp();
const displayValue = computed(() => {
if (data.userInput !== null) {
return data.userInput;
}
let currentValue = data.currentValue;
if (isNil(currentValue))
return "";
if (isNumber(currentValue)) {
if (Number.isNaN(currentValue))
return "";
if (!isUndefined(props.precision)) {
currentValue = currentValue.toFixed(props.precision);
}
}
return currentValue;
});
const toPrecision = (num, pre) => {
if (isUndefined(pre))
pre = numPrecision.value;
if (pre === 0)
return Math.round(num);
let snum = String(num);
const pointPos = snum.indexOf(".");
if (pointPos === -1)
return num;
const nums = snum.replace(".", "").split("");
const datum = nums[pointPos + pre];
if (!datum)
return num;
const length = snum.length;
if (snum.charAt(length - 1) === "5") {
snum = `${snum.slice(0, Math.max(0, length - 1))}6`;
}
return Number.parseFloat(Number(snum).toFixed(pre));
};
const getPrecision = (value) => {
if (isNil(value))
return 0;
const valueString = value.toString();
const dotPosition = valueString.indexOf(".");
let precision = 0;
if (dotPosition !== -1) {
precision = valueString.length - dotPosition - 1;
}
return precision;
};
const ensurePrecision = (val, coefficient = 1) => {
if (!isNumber(val))
return data.currentValue;
return toPrecision(val + props.step * coefficient);
};
const increase = () => {
if (props.readonly || inputNumberDisabled.value || maxDisabled.value)
return;
const value = Number(displayValue.value) || 0;
const newVal = ensurePrecision(value);
setCurrentValue(newVal);
emit(INPUT_EVENT, data.currentValue);
setCurrentValueToModelValue();
};
const decrease = () => {
if (props.readonly || inputNumberDisabled.value || minDisabled.value)
return;
const value = Number(displayValue.value) || 0;
const newVal = ensurePrecision(value, -1);
setCurrentValue(newVal);
emit(INPUT_EVENT, data.currentValue);
setCurrentValueToModelValue();
};
const verifyValue = (value, update) => {
const { max, min, step, precision, stepStrictly, valueOnClear } = props;
if (max < min) {
throwError("InputNumber", "min should not be greater than max.");
}
let newVal = Number(value);
if (isNil(value) || Number.isNaN(newVal)) {
return null;
}
if (value === "") {
if (valueOnClear === null) {
return null;
}
newVal = isString(valueOnClear) ? { min, max }[valueOnClear] : valueOnClear;
}
if (stepStrictly) {
newVal = toPrecision(Math.round(newVal / step) * step, precision);
}
if (!isUndefined(precision)) {
newVal = toPrecision(newVal, precision);
}
if (newVal > max || newVal < min) {
newVal = newVal > max ? max : min;
update && emit(UPDATE_MODEL_EVENT, newVal);
}
return newVal;
};
const setCurrentValue = (value, emitChange = true) => {
var _a;
const oldVal = data.currentValue;
const newVal = verifyValue(value);
if (!emitChange) {
emit(UPDATE_MODEL_EVENT, newVal);
return;
}
if (oldVal === newVal && value)
return;
data.userInput = null;
emit(UPDATE_MODEL_EVENT, newVal);
if (oldVal !== newVal) {
emit(CHANGE_EVENT, newVal, oldVal);
}
if (props.validateEvent) {
(_a = formItem == null ? void 0 : formItem.validate) == null ? void 0 : _a.call(formItem, "change").catch((err) => debugWarn(err));
}
data.currentValue = newVal;
};
const handleInput = (value) => {
data.userInput = value;
const newVal = value === "" ? null : Number(value);
emit(INPUT_EVENT, newVal);
setCurrentValue(newVal, false);
};
const handleInputChange = (value) => {
const newVal = value !== "" ? Number(value) : "";
if (isNumber(newVal) && !Number.isNaN(newVal) || value === "") {
setCurrentValue(newVal);
}
setCurrentValueToModelValue();
data.userInput = null;
};
const focus = () => {
var _a, _b;
(_b = (_a = input.value) == null ? void 0 : _a.focus) == null ? void 0 : _b.call(_a);
};
const blur = () => {
var _a, _b;
(_b = (_a = input.value) == null ? void 0 : _a.blur) == null ? void 0 : _b.call(_a);
};
const handleFocus = (event) => {
emit("focus", event);
};
const handleBlur = (event) => {
var _a;
data.userInput = null;
emit("blur", event);
if (props.validateEvent) {
(_a = formItem == null ? void 0 : formItem.validate) == null ? void 0 : _a.call(formItem, FormItemEvents.blur).catch((err) => debugWarn(err));
}
};
const setCurrentValueToModelValue = () => {
if (data.currentValue !== props.modelValue) {
data.currentValue = props.modelValue;
}
};
const handleWheel = (e) => {
if (document.activeElement === e.target)
e.preventDefault();
};
watch(() => props.modelValue, (value, oldValue) => {
const newValue = verifyValue(value, true);
if (data.userInput === null && newValue !== oldValue) {
data.currentValue = newValue;
}
}, { immediate: true });
onMounted(() => {
var _a;
const { min, max, modelValue } = props;
const innerInput = (_a = input.value) == null ? void 0 : _a.input;
innerInput.setAttribute("role", "spinbutton");
if (Number.isFinite(max)) {
innerInput.setAttribute("aria-valuemax", String(max));
} else {
innerInput.removeAttribute("aria-valuemax");
}
if (Number.isFinite(min)) {
innerInput.setAttribute("aria-valuemin", String(min));
} else {
innerInput.removeAttribute("aria-valuemin");
}
innerInput.setAttribute("aria-valuenow", data.currentValue || data.currentValue === 0 ? String(data.currentValue) : "");
innerInput.setAttribute("aria-disabled", String(inputNumberDisabled.value));
if (!isNumber(modelValue) && modelValue != null) {
let val = Number(modelValue);
if (Number.isNaN(val)) {
val = null;
}
emit(UPDATE_MODEL_EVENT, val);
}
innerInput.addEventListener("wheel", handleWheel, { passive: false });
});
onUpdated(() => {
var _a, _b;
const innerInput = (_a = input.value) == null ? void 0 : _a.input;
innerInput == null ? void 0 : innerInput.setAttribute("aria-valuenow", `${(_b = data.currentValue) != null ? _b : ""}`);
});
expose({
increase,
decrease,
focus,
blur
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
class: normalizeClass([
unref(namespace) + "-input-number",
unref(namespace) + "-group",
_ctx.dir,
_ctx.merge ? "merge" : "",
_ctx.deepMerge ? "deep-merge" : "",
_ctx.indent ? "indent" : "",
_ctx.round ? "round" : "",
_ctx.block ? "block" : "",
unref(inputNumberSize) ? unref(inputNumberSize) : "",
_ctx.controlsPosition === "inner" ? "btn-inner" : "",
{ "btn-vertical": ["left", "right"].includes(_ctx.controlsPosition) },
{ "is-disabled": unref(inputNumberDisabled) },
{ "is-without-controls": !_ctx.controls }
]),
style: normalizeStyle([typeof _ctx.indent === "string" ? `--indent:${_ctx.indent}` : "", typeof _ctx.gap === "string" ? `gap: ${_ctx.gap}` : ""]),
onDragstart: withModifiers(() => {
}, ["prevent"])
}, [
_ctx.controls && _ctx.controlsPosition === "initial" || _ctx.controlsPosition === "inner" ? withDirectives((openBlock(), createBlock(unref(HlButton), {
key: 0,
class: normalizeClass(["group-item", "decrease", _ctx.round ? "round" : "", unref(inputNumberFill) ? "light" : ""]),
size: unref(inputNumberSize),
disabled: unref(minDisabled) || unref(inputNumberDisabled),
"aria-label": unref(t)("hl.inputNumber.decrease")
}, {
default: withCtx(() => [
renderSlot(_ctx.$slots, "icon-decrease", {}, () => [
createVNode(unref(HlIcon), null, {
default: withCtx(() => [
createVNode(unref(SystemRemove))
]),
_: 1
})
])
]),
_: 3
}, 8, ["class", "size", "disabled", "aria-label"])), [
[unref(vRepeatClick), decrease]
]) : createCommentVNode("v-if", true),
_ctx.controls && _ctx.controlsPosition === "left" ? (openBlock(), createElementBlock("div", {
key: 1,
class: normalizeClass([unref(namespace) + "-group", "btn-group", "vertical", "left", "merge", "indent"])
}, [
withDirectives((openBlock(), createBlock(unref(HlButton), {
class: "group-item increase",
disabled: unref(maxDisabled) || unref(inputNumberDisabled),
size: unref(inputNumberSize),
"aria-label": unref(t)("hl.inputNumber.increase")
}, {
default: withCtx(() => [
renderSlot(_ctx.$slots, "icon-increase", {}, () => [
createVNode(unref(HlIcon), null, {
default: withCtx(() => [
createVNode(unref(SystemArrowUp))
]),
_: 1
})
])
]),
_: 3
}, 8, ["disabled", "size", "aria-label"])), [
[unref(vRepeatClick), increase]
]),
withDirectives((openBlock(), createBlock(unref(HlButton), {
class: "group-item decrease",
disabled: unref(minDisabled) || unref(inputNumberDisabled),
size: unref(inputNumberSize),
"aria-label": unref(t)("hl.inputNumber.decrease")
}, {
default: withCtx(() => [
renderSlot(_ctx.$slots, "icon-decrease", {}, () => [
createVNode(unref(HlIcon), null, {
default: withCtx(() => [
createVNode(unref(SystemArrowDown))
]),
_: 1
})
])
]),
_: 3
}, 8, ["disabled", "size", "aria-label"])), [
[unref(vRepeatClick), decrease]
])
], 2)) : createCommentVNode("v-if", true),
createVNode(unref(HlInput), {
id: _ctx.id,
ref_key: "input",
ref: input,
"native-type": "number",
class: "group-item",
"validate-event": false,
"model-value": unref(displayValue),
step: _ctx.step,
placeholder: _ctx.placeholder,
readonly: _ctx.readonly,
disabled: unref(inputNumberDisabled),
size: unref(inputNumberSize),
max: _ctx.max,
min: _ctx.min,
name: _ctx.name,
"aria-label": _ctx.label || _ctx.ariaLabel,
fill: unref(inputNumberFill),
round: _ctx.round,
onKeydown: [
withKeys(withModifiers(increase, ["prevent"]), ["up"]),
withKeys(withModifiers(decrease, ["prevent"]), ["down"])
],
onBlur: handleBlur,
onFocus: handleFocus,
onInput: handleInput,
onChange: handleInputChange
}, createSlots({ _: 2 }, [
_ctx.$slots.prefix ? {
name: "prefix",
fn: withCtx(() => [
renderSlot(_ctx.$slots, "prefix")
])
} : void 0,
_ctx.$slots.suffix ? {
name: "suffix",
fn: withCtx(() => [
renderSlot(_ctx.$slots, "suffix")
])
} : void 0
]), 1032, ["id", "model-value", "step", "placeholder", "readonly", "disabled", "size", "max", "min", "name", "aria-label", "fill", "round", "onKeydown"]),
_ctx.controls && _ctx.controlsPosition === "right" ? (openBlock(), createElementBlock("div", {
key: 2,
class: normalizeClass([unref(namespace) + "-group", "btn-group", "vertical", "right", "merge", "indent"])
}, [
withDirectives((openBlock(), createBlock(unref(HlButton), {
class: "group-item increase",
disabled: unref(maxDisabled) || unref(inputNumberDisabled),
size: unref(inputNumberSize),
"aria-label": unref(t)("hl.inputNumber.increase")
}, {
default: withCtx(() => [
renderSlot(_ctx.$slots, "icon-increase", {}, () => [
createVNode(unref(HlIcon), null, {
default: withCtx(() => [
createVNode(unref(SystemArrowUp))
]),
_: 1
})
])
]),
_: 3
}, 8, ["disabled", "size", "aria-label"])), [
[unref(vRepeatClick), increase]
]),
withDirectives((openBlock(), createBlock(unref(HlButton), {
class: "group-item decrease",
disabled: unref(minDisabled) || unref(inputNumberDisabled),
size: unref(inputNumberSize),
"aria-label": unref(t)("hl.inputNumber.decrease")
}, {
default: withCtx(() => [
renderSlot(_ctx.$slots, "icon-increase", {}, () => [
createVNode(unref(HlIcon), null, {
default: withCtx(() => [
createVNode(unref(SystemArrowDown))
]),
_: 1
})
])
]),
_: 3
}, 8, ["disabled", "size", "aria-label"])), [
[unref(vRepeatClick), decrease]
])
], 2)) : createCommentVNode("v-if", true),
_ctx.controls && _ctx.controlsPosition === "initial" || _ctx.controlsPosition === "inner" ? withDirectives((openBlock(), createBlock(unref(HlButton), {
key: 3,
class: normalizeClass(["group-item", "increase", _ctx.round ? "round" : "", unref(inputNumberFill) ? "light" : ""]),
size: unref(inputNumberSize),
disabled: unref(maxDisabled) || unref(inputNumberDisabled),
"aria-label": unref(t)("hl.inputNumber.increase")
}, {
default: withCtx(() => [
renderSlot(_ctx.$slots, "icon-increase", {}, () => [
createVNode(unref(HlIcon), null, {
default: withCtx(() => [
createVNode(unref(SystemAdd))
]),
_: 1
})
])
]),
_: 3
}, 8, ["class", "size", "disabled", "aria-label"])), [
[unref(vRepeatClick), increase]
]) : createCommentVNode("v-if", true)
], 46, ["onDragstart"]);
};
}
});
export { _sfc_main as default };
//# sourceMappingURL=input-number2.mjs.map