import {iInputNumberCompositionParam, iInputNumberEffectiveValueInfo, iInputNumberValueInfo} from "./input-number.utils";
import {computed, getComponentCls, iHTMLElement, iMouseEvent, reactive, RenderNode, useClasses, useNumber, useRefs} from "@peryl/react-compose";
import {useStyle} from "../../uses/useStyle";
import {useEdit} from "../../uses/useEdit";
import {roundFixed} from "@peryl/utils/roundFixed";
import {eKeyboardKeys, getKeyNameByKeyboardEvent} from "@peryl/utils/keyboard";
import {NumberResize} from "./NumberResize";
import {NumberButtonTypes} from "./number.utils";
import {Input} from "../Input";
import Icon from "../Icon";
import {delay} from "@peryl/utils/delay";
const NAN = 'NAN';
const numberPattern = /([\d.-]+)([a-zA-Z%]*)/;
export function useInputNumberPublic(param: iInputNumberCompositionParam) {
const { props, slots, hooks, event: { emit } } = param;
const { refs, onRef } = useRefs({ add: iHTMLElement, sub: iHTMLElement, input: Input, });
const { styleComputed } = useStyle({ status: undefined });
const { editComputed } = useEdit();
const state = reactive({
interval: null as null | number, // 进步器长摁定时器
timer: null as null | number,
});
const { numberState } = useNumber(props, ['step', 'max', 'min', 'precision']);
/*---------------------------------------utils-------------------------------------------*/
const utils = {
/**
* 将任意值格式化为{val:undefined|number|'NAN',unit?:string}
* @author 韦胜健
* @date 2022.5.24 12:30
*/
getValueInfo: (val: any): iInputNumberValueInfo => {
if (!props.availableUnits || props.availableUnits.length === 0) {
/*---------------------------------------不允许带单位-------------------------------------------*/
if (val == null) return { val: undefined };
val = String(val).trim();
if (val === '') return { val: undefined };
val = Number(val);
if (isNaN(val)) {
return { val: NAN };
}
if (!!props.isValueEffective && !props.isValueEffective(val)) {
return { val: NAN };
}
return { val: val };
} else {
/*---------------------------------------允许带单位-------------------------------------------*/
if (val == null) return { val: undefined, unit: props.defaultUnit };
if (typeof val === "string") {
val = val.trim();
if (val === '') return { val: undefined, unit: props.defaultUnit };
const match = numberPattern.exec(val);
if (!match) {
return { val: NAN };
} else {
let num = Number(match[1]);
let unit: string | null | undefined = match[2];
if (props.availableUnits.indexOf(unit) === -1) {
unit = undefined;
}
if (isNaN(num)) {
return { val: NAN, unit };
}
if (!!props.requireUnit && !unit) {
return { val: NAN, unit };
}
if (!!props.isValueEffective && !props.isValueEffective(num, unit)) {
return { val: NAN, unit };
}
return { val: num, unit: !!unit ? unit : undefined };
}
}
}
return { val };
},
/**
* 检查值的有效性
* @author 韦胜健
* @date 2023.2.10 0:01
*/
checkValue: ({ val, unit }: { val: number | undefined, unit?: string }): string | number | undefined => {
if (val != null) {
// min
if (numberState.min != null && val < numberState.min) {
val = numberState.min;
}
// max
if (numberState.max != null && val! > numberState.max) {
val = numberState.max;
}
// stepStrictly
if (props.stepStrictly && val! % numberState.step! !== 0) {
// console.log('props.value', props.modelValue)
val = props.modelValue == undefined ? undefined : Number(props.modelValue);
}
// precision
if (numberState.precision != null) {
val = roundFixed(val, numberState.precision)!;
}
}
return !!unit && val != null ? (val + unit) : val;
},
/**
* 获取有效值,从formatModelValue以及formatValue 中去一个有效值
* @author 韦胜健
* @date 2022.5.24 12:32
* @param inputValue 正在输入的值
* @param modelValue 已经绑定的有效值
*/
getEffectiveValue: (inputValue: any, modelValue: any): iInputNumberEffectiveValueInfo => {
let { val, unit } = utils.getValueInfo(inputValue);
const modelValueInfo = utils.getValueInfo(modelValue);
if (val === NAN) {
val = modelValueInfo.val;
unit = modelValueInfo.unit;
if (val === NAN) {
if (numberState.min != null) return { val: numberState.min, unit };
else if (numberState.max != null) return { val: numberState.max, unit };
else if (props.stepStrictly) return { val: numberState.step, unit };
else return { val: 0, unit };
}
}
return { val, unit };
},
};
/*---------------------------------------computer-------------------------------------------*/
const classes = useClasses(() => ([
getComponentCls('number'),
{
'number-disabled': editComputed.value.disabled,
[`number-button-type-${props.button}`]: !!props.button,
}
]));
/**
* 当前可用的有效值
* @author 韦胜健
* @date 2023/2/10 11:35
*/
const effectiveInputValue = computed(() => hooks.onGetEffectiveInputValue.exec({ val: undefined }));
/*---------------------------------------methods-------------------------------------------*/
const methods = {
/**
* 添加值或者减少值之间的检查动作
* 如果是up或者down快捷点触发的,如果当前suggestion面板已经打开,则不做值加减处理
* 如果是点击加减按钮触发的,就一定做值加减处理
* @author 韦胜健
* @date 2023/2/10 14:51
*/
beforeAddSub: (param?: { ignoreSuggestion: boolean }): iInputNumberEffectiveValueInfo | void => {
if (!editComputed.value.editable) {return;}
if (!param?.ignoreSuggestion && !!unitSuggestion.value?.length && refs.input?.isSuggestionOpen()) {return;}
let value = { ...effectiveInputValue.value };
if (value.val == null) {value.val = 0;}
return value;
},
/**
* 加值动作
* @author 韦胜健
* @date 2023/2/10 14:53
*/
add: (param?: { ignoreSuggestion: boolean }) => {
const value = methods.beforeAddSub(param);
if (!value) {return;}
value.val! += numberState.step;
const checkValue = utils.checkValue(value);
hooks.onAdd.exec(checkValue);
},
/**
* 减值动作
* @author 韦胜健
* @date 2023/2/10 14:53
*/
minus: (param?: { ignoreSuggestion: boolean }) => {
const value = methods.beforeAddSub(param);
if (!value) {return;}
value.val! -= numberState.step;
const checkValue = utils.checkValue(value);
hooks.onSub.exec(checkValue);
},
/**
* 清空定时器
* @author 韦胜健
* @date 2023/2/10 14:53
*/
clearInterval: () => { // 清除定时器
if (state.interval != null) {clearInterval(state.interval);}
if (state.timer != null) {clearTimeout(state.timer);}
window.removeEventListener('mouseup', methods.clearInterval);
},
focus: () => {refs.input!.focus();},
blur: () => {refs.input!.blur();},
};
/*---------------------------------------handler-------------------------------------------*/
const handler = {
/**
* 定时器加值
* @author 韦胜健
* @date 2023/2/10 14:53
*/
intervalAdd: () => {
props.multiple && delay().then(() => {refs.input?.focus();});
methods.add({ ignoreSuggestion: true });
state.timer = setTimeout(() => {
state.interval = setInterval(methods.add, 100) as any as number;
}, 500) as any as number;
window.addEventListener('mouseup', methods.clearInterval);
},
/**
* 定时器减值
* @author 韦胜健
* @date 2023/2/10 14:54
*/
intervalMinus: () => {
props.multiple && delay().then(() => {refs.input?.focus();});
methods.minus({ ignoreSuggestion: true });
state.timer = setTimeout(() => {
state.interval = setInterval(methods.minus, 100) as any as number;
}, 500) as any as number;
window.addEventListener('mouseup', methods.clearInterval);
},
onResize: (val: number) => {hooks.onResize.exec(val);},
onFocus: (e: FocusEvent) => {hooks.onFocus.exec(e);},
onBlur: (e: FocusEvent) => {hooks.onBlur.exec(e);},
onMousedownResize: (e: iMouseEvent) => {hooks.onMousedownResize.exec(e);},
/**
* keyup 以及 keydown处理值加减动作
* @author 韦胜健
* @date 2023/2/10 14:55
*/
onKeydown: (e: KeyboardEvent) => {
const key = getKeyNameByKeyboardEvent(e);
switch (key) {
case eKeyboardKeys.up:
e.preventDefault();
e.stopPropagation();
methods.add();
break;
case eKeyboardKeys.down:
e.preventDefault();
e.stopPropagation();
methods.minus();
break;
}
},
onInput: (val: any) => {hooks.onInput.exec(val);},
};
/**
* 点击加减按钮的时候阻止事件冒泡,避免触发打开suggestion面板
* @author 韦胜健
* @date 2023/2/10 14:55
*/
const stopClickPropagation = (e: iMouseEvent) => {e.stopPropagation();};
/**
* 支持的按钮类型
* @author 韦胜健
* @date 2023/2/10 14:55
*/
const buttonTypes = {
/**
* 左右加减按钮
* @author 韦胜健
* @date 2023/2/10 11:36
*/
button: {
prefix: () => (
),
suffix: () => (
),
},
/**
* 右侧上下加减按钮
* @author 韦胜健
* @date 2023/2/10 11:36
*/
right: {
suffix: () => (
)
},
/**
* 拖拽按钮
* @author 韦胜健
* @date 2023/2/10 11:36
*/
resize: {
suffix: () => (
)
},
} as const;
/**
* 传递给input的插槽
* @author 韦胜健
* @date 2023/2/10 11:37
*/
const inputSlots = computed<{ prefix?: () => RenderNode, suffix?: () => RenderNode }>(() => {
if (!props.button || editComputed.value.disabled) {
return {};
}
return buttonTypes[typeof props.button !== "string" ? NumberButtonTypes.right : props.button];
});
/**
* 推荐输入,如果有可用的单位的话,自动补全单位作为推荐文本
* @author 韦胜健
* @date 2023/2/10 11:37
*/
const unitSuggestion = computed(() => {
if (props.suggestion !== undefined) {
return props.suggestion;
}
if (!props.availableUnits) {
return undefined;
}
const valInfo = effectiveInputValue.value;
if (typeof valInfo.val === "number") {
return props.availableUnits.map(i => `${valInfo.val}${i}`);
}
});
/**
* 传递给input的属性
* @author 韦胜健
* @date 2023/2/10 11:37
*/
const inputAttrs = computed(() => {
return {
class: classes.value,
ref: onRef.input,
suggestionIgnoreSearchText: true,
suggestion: unitSuggestion.value,
noClear: true,
onFocus: handler.onFocus,
onBlur: handler.onBlur,
onKeydown: handler.onKeydown,
onInput: handler.onInput,
...props.inputAttrs,
...hooks.onGetInputEditAttrs.exec({}),
};
});
/**
* 输入文本的时候,如果有推荐输入文本,则自动打开推荐输入文本
* @author 韦胜健
* @date 2023/2/10 11:38
*/
hooks.onInput.use(() => {
if (!!unitSuggestion.value?.length) {
delay().then(() => {refs.input?.openSuggestion();});
}
});
hooks.onFocus.use(e => emit.onFocus(e));
hooks.onBlur.use(e => emit.onBlur(e));
/**
* 渲染Input
* @author 韦胜健
* @date 2023/2/10 11:38
*/
hooks.onRender.use({
processor: ({ list, render }) => {list.push({ render, seq: 1, key: 'single' });},
render: () => (
{/*直接返回inputSlots.value会有运行时错误*/}
{(() => {
const { prefix, suffix } = inputSlots.value;
const result = {} as any;
if (!!prefix || slots.prefix.isExist()) {result.prefix = () => <>{slots.prefix()}{prefix?.()}>;}
if (!!suffix || slots.suffix.isExist()) {result.suffix = () => <>{slots.suffix()}{suffix?.()}>;}
return result;
})()}
)
});
/**
* 点击resize按钮的时候,令input重新获取焦点
* @author 韦胜健
* @date 2023/2/10 14:56
*/
hooks.onMousedownResize.use(() => {
delay().then(() => {refs.input?.focus();});
});
return {
utils,
styleComputed,
editComputed,
refs,
onRef,
inputAttrs,
inputSlots,
effectiveInputValue,
unitSuggestion,
...param,
};
}
export type iInputNumberPublic = ReturnType