function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import React, { forwardRef, useState } from "react";
import { cx, getSizeValueFromProp, isNumber } from "../../utils";
import { IconMinus, IconPlus } from "../_Icon";
import { ActionButton, NumberInput } from "./ui";
import { classes, privateTokens } from "./NumberInput.tokens";
import { base } from "./NumberInput.styles";
import { base as viewCSS } from "./variations/_view/base";
import { base as sizeCSS } from "./variations/_size/base";
import { base as shapeCSS } from "./variations/_shape/base";
import { base as inputBackgroundTypeCSS } from "./variations/_background-type/base";
import { base as segmentationCSS } from "./variations/_segmentation/base";
import { base as disabledCSS } from "./variations/_disabled/base";
import { getPreciseValue } from "./utils";
export var numberInputRoot = function numberInputRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), className = _ref2.className, style = _ref2.style, width = _ref2.width, outerValue = _ref2.value, min = _ref2.min, max = _ref2.max, _ref_step = _ref2.step, step = _ref_step === void 0 ? 1 : _ref_step, _ref_precision = _ref2.precision, precision = _ref_precision === void 0 ? 2 : _ref_precision, isLoading = _ref2.isLoading, loader = _ref2.loader, size = _ref2.size, view = _ref2.view, clear = _ref2.clear, shape = _ref2.shape, segmentation = _ref2.segmentation, _ref_inputBackgroundType = _ref2.inputBackgroundType, inputBackgroundType = _ref_inputBackgroundType === void 0 ? 'fill' : _ref_inputBackgroundType, disabled = _ref2.disabled, textBefore = _ref2.textBefore, textAfter = _ref2.textAfter, customIncrementButton = _ref2.customIncrementButton, incrementIcon = _ref2.incrementIcon, customDecrementButton = _ref2.customDecrementButton, decrementIcon = _ref2.decrementIcon, isManualInput = _ref2.isManualInput, _ref_displayWithoutValue = _ref2.displayWithoutValue, displayWithoutValue = _ref_displayWithoutValue === void 0 ? 'input' : _ref_displayWithoutValue, _ref_limitBehavior = _ref2.limitBehavior, limitBehavior = _ref_limitBehavior === void 0 ? 'disabled' : _ref_limitBehavior, onChange = _ref2.onChange, onIncrement = _ref2.onIncrement, onDecrement = _ref2.onDecrement, rest = _object_without_properties(_ref2, [
            "className",
            "style",
            "width",
            "value",
            "min",
            "max",
            "step",
            "precision",
            "isLoading",
            "loader",
            "size",
            "view",
            "clear",
            "shape",
            "segmentation",
            "inputBackgroundType",
            "disabled",
            "textBefore",
            "textAfter",
            "customIncrementButton",
            "incrementIcon",
            "customDecrementButton",
            "decrementIcon",
            "isManualInput",
            "displayWithoutValue",
            "limitBehavior",
            "onChange",
            "onIncrement",
            "onDecrement"
        ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
        if (outerValue && !isNumber(outerValue) && outerValue !== undefined && outerValue !== '-' && outerValue !== '.') {
            console.error('`value` должен быть undefined, числом или строкой с числом');
        }
        var _useState = _sliced_to_array(useState(false), 2), isInputFocused = _useState[0], setIsInputFocused = _useState[1];
        var _useState1 = _sliced_to_array(useState(false), 2), isAnimationRun = _useState1[0], setIsAnimationRun = _useState1[1];
        var _useState2 = _sliced_to_array(useState(''), 2), innerValue = _useState2[0], setInnerValue = _useState2[1];
        var value = outerValue !== null && outerValue !== void 0 ? outerValue : innerValue;
        var innerWidth = width ? getSizeValueFromProp(width) : '100%';
        var actionIconSize = size === 'xs' ? 'xs' : 's';
        var solidViewClass = segmentation === 'solid' ? classes.solidView : undefined;
        var segmentedViewClass = segmentation === 'segmented' ? classes.segmentedView : undefined;
        var clearViewClass = clear ? classes.clearView : undefined;
        var disabledClass = disabled ? classes.disabled : undefined;
        var loadingClass = isLoading ? classes.loading : undefined;
        var focusedClass = isInputFocused ? classes.focused : undefined;
        var isMinValue = function isMinValue(currentValue) {
            return min !== undefined && currentValue <= min;
        };
        var isMaxValue = function isMaxValue(currentValue) {
            return max !== undefined && currentValue >= max;
        };
        var isValueEmpty = (value === '' || value === undefined) && !isManualInput;
        var onlyShowIncrement = isValueEmpty && displayWithoutValue === 'increment';
        var onlyShowDecrement = isValueEmpty && displayWithoutValue === 'decrement';
        var decrementAtLimit = isNumber(value) && value !== '' && isMinValue(Number(value)) && !isAnimationRun;
        var incrementAtLimit = isNumber(value) && value !== '' && isMaxValue(Number(value)) && !isAnimationRun;
        var decrementButtonDisabled = (decrementAtLimit && limitBehavior !== 'hidden' || isLoading) && !disabled ? classes.actionButtonDecrementDisabled : undefined;
        var incrementButtonDisabled = (incrementAtLimit && limitBehavior !== 'hidden' || isLoading) && !disabled ? classes.actionButtonIncrementDisabled : undefined;
        var decrementHiddenClass = decrementAtLimit && limitBehavior === 'hidden' ? classes.decrementHidden : undefined;
        var incrementHiddenClass = incrementAtLimit && limitBehavior === 'hidden' ? classes.incrementHidden : undefined;
        var onlyIncrementShownClass = onlyShowIncrement ? classes.onlyIncrementShown : undefined;
        var onlyDecrementShownClass = onlyShowDecrement ? classes.onlyDecrementShown : undefined;
        var handleDecrement = function handleDecrement() {
            if (isLoading || disabled || isAnimationRun) {
                return;
            }
            var processedValue = isNumber(value) && value !== '' ? Number(value) : max !== null && max !== void 0 ? max : 0;
            var preciseDiff = getPreciseValue(processedValue - step, precision);
            var diffValue = Number(preciseDiff);
            var resValue = min !== undefined && diffValue <= min ? min : diffValue;
            setInnerValue(resValue);
            if (onDecrement) {
                onDecrement(resValue);
            }
            if (onChange) {
                onChange(null, resValue);
            }
        };
        var handleIncrement = function handleIncrement() {
            if (isLoading || disabled || isAnimationRun) {
                return;
            }
            var processedValue = isNumber(value) && value !== '' ? Number(value) : min !== null && min !== void 0 ? min : 0;
            var preciseDiff = getPreciseValue(processedValue + step, precision);
            var diffValue = Number(preciseDiff);
            var resValue = max !== undefined && diffValue >= max ? max : diffValue;
            setInnerValue(resValue);
            if (onIncrement) {
                onIncrement(resValue);
            }
            if (onChange) {
                onChange(null, resValue);
            }
        };
        var decrementButton = customDecrementButton || /*#__PURE__*/ React.createElement(ActionButton, {
            className: cx(classes.actionButtonDecrement, decrementButtonDisabled, solidViewClass, segmentedViewClass),
            icon: decrementIcon || /*#__PURE__*/ React.createElement(IconMinus, {
                color: "inherit",
                size: actionIconSize
            }),
            onClick: handleDecrement
        });
        var incrementButton = customIncrementButton || /*#__PURE__*/ React.createElement(ActionButton, {
            className: cx(classes.actionButtonIncrement, incrementButtonDisabled, solidViewClass, segmentedViewClass),
            icon: incrementIcon || /*#__PURE__*/ React.createElement(IconPlus, {
                color: "inherit",
                size: actionIconSize
            }),
            onClick: handleIncrement
        });
        return /*#__PURE__*/ React.createElement(Root, _object_spread_props(_object_spread({
            view: view,
            size: size,
            disabled: disabled,
            clear: clear,
            shape: shape,
            segmentation: segmentation,
            isLoading: isLoading
        }, segmentation === 'solid' ? {
            inputBackgroundType: 'clear'
        } : {
            inputBackgroundType: inputBackgroundType
        }), {
            className: cx(className, solidViewClass, segmentedViewClass, clearViewClass, disabledClass, loadingClass, focusedClass, decrementHiddenClass, incrementHiddenClass, onlyIncrementShownClass, onlyDecrementShownClass),
            style: _object_spread_props(_object_spread({}, style), _define_property({}, privateTokens.inputWidth, innerWidth))
        }), !onlyShowIncrement && decrementButton, !onlyShowIncrement && !onlyShowDecrement && /*#__PURE__*/ React.createElement(NumberInput, _object_spread({
            ref: ref,
            segmentation: segmentation,
            value: value,
            precision: precision,
            min: min,
            max: max,
            isManualInput: isManualInput,
            textBefore: textBefore,
            textAfter: textAfter,
            isLoading: isLoading,
            loader: loader,
            disabled: disabled,
            isInputFocused: isInputFocused,
            setIsInputFocused: setIsInputFocused,
            setIsAnimationRun: setIsAnimationRun,
            setInnerValue: setInnerValue,
            onChange: onChange
        }, rest)), !onlyShowDecrement && incrementButton);
    });
};
export var numberInputConfig = {
    name: 'NumberInput',
    tag: 'div',
    layout: numberInputRoot,
    base: base,
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        },
        shape: {
            css: shapeCSS
        },
        inputBackgroundType: {
            css: inputBackgroundTypeCSS
        },
        segmentation: {
            css: segmentationCSS
        },
        disabled: {
            css: disabledCSS,
            attrs: true
        }
    },
    defaults: {
        view: 'default',
        size: 'l',
        shape: 'cornered',
        segmentation: 'default'
    }
};
