"use strict";
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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importStar(require("react"));
var classNames_1 = __importDefault(require("../_util/classNames"));
var omit_1 = __importDefault(require("../_util/omit"));
var resizeObserver_1 = __importDefault(require("../_util/resizeObserver"));
var IconClose_1 = __importDefault(require("../../icon/react-icon-cjs/IconClose"));
var icon_hover_1 = __importDefault(require("../_class/icon-hover"));
var is_1 = require("../_util/is");
var useComposition_1 = __importDefault(require("./useComposition"));
var useKeyboardEvent_1 = __importDefault(require("../_util/hooks/useKeyboardEvent"));
var fillNBSP_1 = __importDefault(require("../_util/fillNBSP"));
var InputComponent = react_1.default.forwardRef(function (props, ref) {
    var _a;
    var allowClear = props.allowClear, disabled = props.disabled, placeholder = props.placeholder, className = props.className, style = props.style, height = props.height, prefixCls = props.prefixCls, hasParent = props.hasParent, size = props.size, value = props.value, autoFitWidth = props.autoFitWidth, onClear = props.onClear, readOnly = props.readOnly, onChange = props.onChange, onKeyDown = props.onKeyDown, onPressEnter = props.onPressEnter, propMaxLength = props.maxLength, clearIcon = props.clearIcon, rest = __rest(props, ["allowClear", "disabled", "placeholder", "className", "style", "height", "prefixCls", "hasParent", "size", "value", "autoFitWidth", "onClear", "readOnly", "onChange", "onKeyDown", "onPressEnter", "maxLength", "clearIcon"]);
    var otherProps = (0, omit_1.default)(rest, [
        'error',
        'status',
        'showWordLimit',
        'className',
        'defaultValue',
        'addBefore',
        'addAfter',
        'afterStyle',
        'beforeStyle',
        'prefix',
        'suffix',
        'normalize',
        'normalizeTrigger',
    ]);
    var getKeyboardEvents = (0, useKeyboardEvent_1.default)();
    var refInput = (0, react_1.useRef)();
    var refInputMirror = (0, react_1.useRef)();
    var refPrevInputWidth = (0, react_1.useRef)(null);
    var maxLength = (0, is_1.isObject)(propMaxLength)
        ? propMaxLength.errorOnly
            ? undefined
            : propMaxLength.length
        : propMaxLength;
    var normalizeHandler = function (type) {
        var handler = function (v) { return v; };
        var normalizeTrigger = props.normalizeTrigger || ['onBlur'];
        if (Array.isArray(normalizeTrigger) &&
            normalizeTrigger.indexOf(type) > -1 &&
            (0, is_1.isFunction)(props.normalize)) {
            handler = props.normalize;
        }
        return handler;
    };
    var _b = (0, useComposition_1.default)({
        value: value,
        maxLength: maxLength,
        onChange: onChange,
        onKeyDown: onKeyDown,
        onPressEnter: onPressEnter,
        normalizeHandler: normalizeHandler,
    }), compositionValue = _b.compositionValue, valueChangeHandler = _b.valueChangeHandler, compositionHandler = _b.compositionHandler, keyDownHandler = _b.keyDownHandler, triggerValueChangeCallback = _b.triggerValueChangeCallback;
    var inputClassNames = (0, classNames_1.default)(prefixCls, prefixCls && (_a = {},
        _a[prefixCls + "-size-" + size] = size,
        _a[prefixCls + "-" + props.status] = props.status,
        _a[prefixCls + "-disabled"] = disabled,
        _a), hasParent ? undefined : className);
    var inputProps = __assign(__assign({ 'aria-invalid': props.status === 'error' || undefined }, otherProps), { readOnly: readOnly, maxLength: maxLength, disabled: disabled, placeholder: placeholder, value: compositionValue || value || '', className: inputClassNames, onKeyDown: keyDownHandler, onChange: valueChangeHandler, onCompositionStart: compositionHandler, onCompositionUpdate: compositionHandler, onCompositionEnd: compositionHandler, onBlur: function (e) {
            var _a;
            (_a = props.onBlur) === null || _a === void 0 ? void 0 : _a.call(props, e);
            triggerValueChangeCallback(normalizeHandler('onBlur')(e.target.value), e);
        } });
    (0, react_1.useImperativeHandle)(ref, function () {
        return {
            dom: refInput.current,
            focus: function () {
                refInput.current && refInput.current.focus && refInput.current.focus();
            },
            blur: function () {
                refInput.current && refInput.current.blur && refInput.current.blur();
            },
        };
    }, []);
    var updateInputWidth = function () {
        if (refInputMirror.current && refInput.current) {
            var needToShowPlaceholder = !inputProps.value && placeholder;
            // use default width of input when placeholder is visible
            if (needToShowPlaceholder) {
                refInput.current.style.width = null;
            }
            else {
                var width = refInputMirror.current.offsetWidth;
                refInput.current.style.width = width + (width ? 8 : 4) + "px";
            }
        }
    };
    // Set the initial width of <input>, and subsequent updates are triggered by ResizeObserver
    (0, react_1.useEffect)(function () { return autoFitWidth && updateInputWidth(); }, []);
    // Here also need placeholder to trigger updateInputWidth after user-input is cleared
    var mirrorValue = inputProps.value || placeholder;
    var handleClear = function (e) {
        if (refInput.current && refInput.current.focus) {
            refInput.current.focus();
        }
        triggerValueChangeCallback('', e);
        onClear && onClear();
    };
    return (react_1.default.createElement(react_1.default.Fragment, null,
        allowClear ? (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement("input", __assign({ ref: refInput }, inputProps)),
            !readOnly && !disabled && allowClear && value ? (clearIcon !== undefined ? (react_1.default.createElement("span", __assign({ tabIndex: 0, className: prefixCls + "-clear-icon" }, getKeyboardEvents({ onPressEnter: handleClear }), { onClick: function (e) {
                    e.stopPropagation();
                    handleClear(e);
                }, onMouseDown: function (e) {
                    e.preventDefault();
                } }), clearIcon)) : (react_1.default.createElement(icon_hover_1.default, __assign({ tabIndex: 0, className: prefixCls + "-clear-icon" }, getKeyboardEvents({ onPressEnter: handleClear }), { onClick: function (e) {
                    e.stopPropagation();
                    handleClear(e);
                } }),
                react_1.default.createElement(IconClose_1.default
                // keep focus status
                , { 
                    // keep focus status
                    onMouseDown: function (e) {
                        e.preventDefault();
                    } })))) : null)) : (react_1.default.createElement("input", __assign({ ref: refInput }, inputProps, { style: hasParent
                ? {}
                : __assign(__assign({}, style), ('height' in props ? { height: height } : {})) }))),
        autoFitWidth && (react_1.default.createElement(resizeObserver_1.default, { onResize: function () {
                var inputWidth = refInputMirror.current.offsetWidth;
                if (typeof autoFitWidth === 'object') {
                    var delay = typeof autoFitWidth.delay === 'function'
                        ? autoFitWidth.delay(inputWidth, refPrevInputWidth.current)
                        : autoFitWidth.delay;
                    delay ? setTimeout(updateInputWidth, delay) : updateInputWidth();
                }
                else {
                    updateInputWidth();
                }
                refPrevInputWidth.current = inputWidth;
            } },
            react_1.default.createElement("span", { className: prefixCls + "-mirror", ref: refInputMirror }, (0, fillNBSP_1.default)(mirrorValue))))));
});
InputComponent.displayName = 'InputComponent';
exports.default = InputComponent;
