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;
};
import React, { useRef, useImperativeHandle, useEffect } from 'react';
import cs from '../_util/classNames';
import omit from '../_util/omit';
import ResizeObserver from '../_util/resizeObserver';
import IconClose from '../../icon/react-icon/IconClose';
import IconHover from '../_class/icon-hover';
import { isFunction, isObject } from '../_util/is';
import useComposition from './useComposition';
import useKeyboardEvent from '../_util/hooks/useKeyboardEvent';
import fillNBSP from '../_util/fillNBSP';
var InputComponent = React.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 = omit(rest, [
        'error',
        'status',
        'showWordLimit',
        'className',
        'defaultValue',
        'addBefore',
        'addAfter',
        'afterStyle',
        'beforeStyle',
        'prefix',
        'suffix',
        'normalize',
        'normalizeTrigger',
    ]);
    var getKeyboardEvents = useKeyboardEvent();
    var refInput = useRef();
    var refInputMirror = useRef();
    var refPrevInputWidth = useRef(null);
    var maxLength = 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 &&
            isFunction(props.normalize)) {
            handler = props.normalize;
        }
        return handler;
    };
    var _b = useComposition({
        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 = cs(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);
        } });
    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
    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.createElement(React.Fragment, null,
        allowClear ? (React.createElement(React.Fragment, null,
            React.createElement("input", __assign({ ref: refInput }, inputProps)),
            !readOnly && !disabled && allowClear && value ? (clearIcon !== undefined ? (React.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.createElement(IconHover, __assign({ tabIndex: 0, className: prefixCls + "-clear-icon" }, getKeyboardEvents({ onPressEnter: handleClear }), { onClick: function (e) {
                    e.stopPropagation();
                    handleClear(e);
                } }),
                React.createElement(IconClose
                // keep focus status
                , { 
                    // keep focus status
                    onMouseDown: function (e) {
                        e.preventDefault();
                    } })))) : null)) : (React.createElement("input", __assign({ ref: refInput }, inputProps, { style: hasParent
                ? {}
                : __assign(__assign({}, style), ('height' in props ? { height: height } : {})) }))),
        autoFitWidth && (React.createElement(ResizeObserver, { 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.createElement("span", { className: prefixCls + "-mirror", ref: refInputMirror }, fillNBSP(mirrorValue))))));
});
InputComponent.displayName = 'InputComponent';
export default InputComponent;
