import {iInputNumberPublic} from "./useInputNumber.public"; import {reactive, useModel} from "@peryl/react-compose"; import {createEffects} from "@peryl/utils/createEffects"; export function useInputNumberSingle( { hooks, props, event, utils }: iInputNumberPublic ) { const { effects } = createEffects(); /** * 绑定值变化时更新文本框的绑定值 * @author 韦胜健 * @date 2023/2/10 11:28 */ const model = useModel(() => props.modelValue as string | number | undefined, event.emit.onUpdateModelValue, { onChange: val => { state.inputValue = val; } }); const state = reactive({ /*文本框绑定值*/ inputValue: model.value }); const handler = { /** * 处理文本框值变化动作,实时检测输入的值是否正确,是则立即派发绑定值更新事件 * @author 韦胜健 * @date 2023/2/10 11:28 */ onUpdateModelValue: (val: any) => { /*没有值,直接派发新值undefined*/ if (typeof val === "string") { if (val.trim().length === 0) { state.inputValue = undefined; model.value = state.inputValue; return; } } /*更新绑定文本*/ state.inputValue = val; const strVal = String(val); /*绑定文本有效,直接派发更新值事件*/ if ( strVal.trim().length === 0 || ( val == utils.checkValue(utils.getEffectiveValue(state.inputValue, model.value)) && strVal.charAt(strVal.length - 1) !== '.' ) ) { model.value = state.inputValue; } }, }; /** * 计算当前有效的输入值 * @author 韦胜健 * @date 2023/2/10 11:31 */ effects.push( hooks.onGetEffectiveInputValue.use(() => { return utils.getEffectiveValue(state.inputValue, model.value); }) ); /** * 绑定输入文本的属性 * @author 韦胜健 * @date 2023/2/10 11:31 */ effects.push( hooks.onGetInputEditAttrs.use(() => ({ modelValue: state.inputValue, onUpdateModelValue: handler.onUpdateModelValue, })) ); /** * 失去焦点的时候重置输入的本文 * @author 韦胜健 * @date 2023/2/10 11:34 */ effects.push( hooks.onBlur.use(() => { if (state.inputValue !== model.value) { state.inputValue = model.value; } }) ); /** * 处理点击加号动作 * @author 韦胜健 * @date 2023/2/10 11:34 */ effects.push( hooks.onAdd.use(val => { state.inputValue = val; model.value = val; }) ); /** * 处理点击减号动作 * @author 韦胜健 * @date 2023/2/10 11:34 */ effects.push( hooks.onSub.use(val => { state.inputValue = val; model.value = val; }) ); /** * 处理拖拽值变化动作 * @author 韦胜健 * @date 2023/2/10 11:35 */ effects.push( hooks.onResize.use(val => { if (!props.availableUnits || !props.availableUnits.length) { return handler.onUpdateModelValue(val); } const { unit: _unit } = utils.getValueInfo(model.value); const unit = _unit || props.defaultUnit; handler.onUpdateModelValue(!unit ? val : `${val}${unit}`); }) ); return effects.clear; }