UNPKG

preact-arco-design

Version:

Arco Design React UI Library.

355 lines (295 loc) 11.7 kB
var __assign = this && this.__assign || function () { __assign = Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } } return t; }; return __assign.apply(this, arguments); }; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; } if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __read = this && this.__read || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) { ar.push(r.value); } } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; import React, { useCallback, useContext, useEffect, useImperativeHandle, useRef, useState } from "preact/compat"; import NP from 'number-precision'; import IconUp from "../../icon/react-icon/IconUp"; import IconDown from "../../icon/react-icon/IconDown"; import IconPlus from "../../icon/react-icon/IconPlus"; import IconMinus from "../../icon/react-icon/IconMinus"; import { isNumber } from "../_util/is"; import cs from "../_util/classNames"; import { ArrowUp, ArrowDown } from "../_util/keycode"; import { ConfigContext } from "../ConfigProvider"; import Input from "../Input"; import useMergeProps from "../_util/hooks/useMergeProps"; import omit from "../_util/omit"; import { toFixed, toSafeString } from "./utils"; NP.enableBoundaryChecking(false); // Value's auto change speed when user holds on plus or minus var AUTO_CHANGE_INTERVAL = 200; // Delay to auto change value when user holds on plus or minus var AUTO_CHANGE_START_DELAY = 1000; var defaultProps = { max: Infinity, min: -Infinity, step: 1, mode: 'embed', parser: function parser(input) { return input.replace(/[^\w\.-]+/g, ''); } }; function InputNumber(baseProps, ref) { var _a; var _b = useContext(ConfigContext), getPrefixCls = _b.getPrefixCls, ctxSize = _b.size, componentConfig = _b.componentConfig; var props = useMergeProps(baseProps, defaultProps, componentConfig === null || componentConfig === void 0 ? void 0 : componentConfig.InputNumber); var className = props.className, style = props.style, defaultValue = props.defaultValue, disabled = props.disabled, error = props.error, readOnly = props.readOnly, placeholder = props.placeholder, hideControl = props.hideControl, suffix = props.suffix, prefix = props.prefix, icons = props.icons, mode = props.mode, size = props.size, step = props.step, precision = props.precision, min = props.min, max = props.max, parser = props.parser, formatter = props.formatter, _onBlur = props.onBlur, _onFocus = props.onFocus, onChange = props.onChange, _onKeyDown = props.onKeyDown, rest = __rest(props, ["className", "style", "defaultValue", "disabled", "error", "readOnly", "placeholder", "hideControl", "suffix", "prefix", "icons", "mode", "size", "step", "precision", "min", "max", "parser", "formatter", "onBlur", "onFocus", "onChange", "onKeyDown"]); var prefixCls = getPrefixCls('input-number'); var mergedSize = size || ctxSize; var mergedPrecision = function () { if (isNumber(precision)) { var decimal = "".concat(step).split('.')[1]; var stepPrecision = decimal && decimal.length || 0; return Math.max(stepPrecision, precision); } return null; }(); var _c = __read(useState('defaultValue' in props ? defaultValue : undefined), 2), innerValue = _c[0], setInnerValue = _c[1]; var value = function () { var mergedValue = 'value' in props ? props.value : innerValue; return typeof mergedValue === 'string' && mergedValue !== '' ? +mergedValue : mergedValue; }(); var _d = __read(useState(''), 2), inputValue = _d[0], setInputValue = _d[1]; var _e = __read(useState(false), 2), isOutOfRange = _e[0], setIsOutOfRange = _e[1]; var _f = __read(useState(false), 2), isUserInputting = _f[0], setIsUserInputting = _f[1]; // Value is not set var isEmptyValue = value === '' || value === undefined || value === null; var refAutoTimer = useRef(null); var refInput = useRef(null); // Ref to keep track of whether user has taken operations since the last change of prop value var refHasOperateSincePropValueChanged = useRef(false); useImperativeHandle(ref, function () { return refInput.current; }, []); var setValue = function setValue(newVal) { setInnerValue(newVal); var newValue = isNumber(+newVal) ? +newVal : undefined; if (newValue !== value) { onChange && onChange(newValue); } }; var stop = function stop() { refAutoTimer.current && clearTimeout(refAutoTimer.current); refAutoTimer.current = null; }; var getLegalValue = useCallback(function (changedValue) { var finalValue = Number(changedValue); if (!changedValue && changedValue !== 0) { finalValue = undefined; } else if (!isNumber(finalValue)) { finalValue = changedValue === '-' ? changedValue : ''; } if (finalValue < min) { finalValue = min; } if (finalValue > max) { finalValue = max; } return isNumber(finalValue) ? isNumber(mergedPrecision) ? Number(toFixed(finalValue, mergedPrecision)) : finalValue : undefined; }, [min, max, mergedPrecision]); useEffect(function () { return function () { return stop(); }; }, []); useEffect(function () { refHasOperateSincePropValueChanged.current = false; }, [props.value]); useEffect(function () { var _isOutOfRange = isNumber(min) && value < min || isNumber(max) && value > max; // Don't correct the illegal value caused by prop value. Wait for user to take actions. if (_isOutOfRange && refHasOperateSincePropValueChanged.current) { setValue(getLegalValue(value)); } setIsOutOfRange(_isOutOfRange); }, [min, max, value, getLegalValue]); var handleArrowKey = function handleArrowKey(event, method, needRepeat) { if (needRepeat === void 0) { needRepeat = false; } event.persist(); event.preventDefault(); setIsUserInputting(false); if (disabled || readOnly) { return; } var finalValue = min === -Infinity ? 0 : min; if (!isEmptyValue) { finalValue = NP[method](value, step); } setValue(getLegalValue(finalValue)); refInput.current && refInput.current.focus(); // auto change while holding if (needRepeat) { var isFirstRepeat = refAutoTimer.current === null; refAutoTimer.current = setTimeout(function () { return event.target.dispatchEvent(event.nativeEvent); }, isFirstRepeat ? AUTO_CHANGE_START_DELAY : AUTO_CHANGE_INTERVAL); } }; var getDisplayInputValue = function getDisplayInputValue() { var _value; if (isUserInputting) { _value = inputValue; } else if (isNumber(value) && isNumber(mergedPrecision)) { _value = toFixed(value, mergedPrecision); } else if (value == null) { _value = ''; } else { _value = toSafeString(value); } return formatter ? formatter(_value) : _value; }; var inputEventHandlers = { onChange: function onChange(value) { setIsUserInputting(true); var targetValue = value.trim().replace(/。/g, '.'); targetValue = parser ? parser(targetValue) : targetValue; if (isNumber(+targetValue) || targetValue === '-' || !targetValue || targetValue === '.') { var formatValue = getLegalValue(targetValue); setInputValue(targetValue); setValue(formatValue); } }, onKeyDown: function onKeyDown(e) { e.stopPropagation(); var key = e.key; if (key === ArrowDown.key) { handleArrowKey(e, 'minus'); } else if (key === ArrowUp.key) { handleArrowKey(e, 'plus'); } stop(); _onKeyDown && _onKeyDown(e); }, onFocus: function onFocus(e) { var _a, _b; // Both tab and button click trigger focus event. This can be used to determine whether user has taken operations refHasOperateSincePropValueChanged.current = true; setInputValue((_b = (_a = refInput.current) === null || _a === void 0 ? void 0 : _a.dom) === null || _b === void 0 ? void 0 : _b.value); _onFocus && _onFocus(e); }, onBlur: function onBlur(e) { setValue(getLegalValue(value)); setIsUserInputting(false); _onBlur && _onBlur(e); } }; var getControlButtonEventsHandlers = function getControlButtonEventsHandlers(method) { return readOnly ? {} : { onMouseDown: function onMouseDown(e) { return handleArrowKey(e, method, true); }, onMouseLeave: stop, onMouseUp: stop }; }; var shouldRenderButton = !hideControl && mode === 'button'; var shouldRenderLayer = !hideControl && !readOnly && mode === 'embed'; var renderStepButton = function renderStepButton(method, icon) { var _a; return React.createElement("div", __assign({ className: cs("".concat(prefixCls, "-step-button"), (_a = {}, _a["".concat(prefixCls, "-step-button-disabled")] = disabled || (method === 'plus' ? +value >= +max : +value <= +min), _a)) }, getControlButtonEventsHandlers(method)), icon); }; return React.createElement(Input, __assign({ _ignorePropsFromGlobal: true, role: "spinbutton", "aria-valuemax": max, "aria-valuemin": min, "aria-valuenow": value }, omit(rest, ['allowClear']), inputEventHandlers, { style: style, className: cs(prefixCls, "".concat(prefixCls, "-mode-").concat(mode), "".concat(prefixCls, "-size-").concat(mergedSize), (_a = {}, _a["".concat(prefixCls, "-readonly")] = readOnly, _a["".concat(prefixCls, "-illegal-value")] = !isEmptyValue && isOutOfRange, _a), className), ref: refInput, size: mergedSize, error: error, disabled: disabled, readOnly: readOnly, value: getDisplayInputValue(), placeholder: placeholder, prefix: prefix && React.createElement("div", { className: "".concat(prefixCls, "-prefix") }, prefix), suffix: React.createElement(React.Fragment, null, shouldRenderLayer && React.createElement("div", { className: "".concat(prefixCls, "-step-layer") }, renderStepButton('plus', icons && icons.up ? icons.up : React.createElement(IconUp, null)), renderStepButton('minus', icons && icons.down ? icons.down : React.createElement(IconDown, null))), suffix && React.createElement("div", { className: "".concat(prefixCls, "-suffix") }, suffix)), addBefore: shouldRenderButton && renderStepButton('minus', icons && icons.minus ? icons.minus : React.createElement(IconMinus, null)), addAfter: shouldRenderButton && renderStepButton('plus', icons && icons.plus ? icons.plus : React.createElement(IconPlus, null)) })); } var InputNumberComponent = React.forwardRef(InputNumber); InputNumberComponent.displayName = 'InputNumber'; export default InputNumberComponent;