"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.baseClassName = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const rebass_1 = require("rebass");
const join_1 = tslib_1.__importDefault(require("../utils/join"));
exports.baseClassName = 'ab-Textarea';
const Textarea = React.forwardRef((props, ref) => {
    const internalRef = React.useRef(null);
    let { disabled, autoResizeOnFocus, className } = props, textareaProps = tslib_1.__rest(props, ["disabled", "autoResizeOnFocus", "className"]);
    const initialHeight = React.useRef(null);
    let type = 'text';
    if (textareaProps && textareaProps.type) {
        type = textareaProps.type;
    }
    if (type === 'string') {
        type = 'text';
    }
    const expandToFitContent = () => {
        if (autoResizeOnFocus && initialHeight.current !== null && internalRef.current) {
            internalRef.current.style.height = `0px`; // makes sure it shrinks when needed
            const height = internalRef.current.scrollHeight;
            internalRef.current.style.height = `${height}px`;
        }
    };
    const shrinkToInitialHeight = () => {
        if (autoResizeOnFocus) {
            internalRef.current.style.height = `${initialHeight.current}px`;
        }
    };
    return (React.createElement(rebass_1.Box, Object.assign({}, textareaProps, { onFocus: (e) => {
            var _a;
            expandToFitContent();
            (_a = props.onFocus) === null || _a === void 0 ? void 0 : _a.call(props, e);
            if (internalRef.current && initialHeight.current === null) {
                const height = internalRef.current.getBoundingClientRect().height;
                initialHeight.current = height;
            }
        }, onBlur: (e) => {
            var _a;
            shrinkToInitialHeight();
            (_a = props.onBlur) === null || _a === void 0 ? void 0 : _a.call(props, e);
        }, ref: (elRef) => {
            // SAVE INITIAL HEIGHT
            // if (elRef && initialHeight.current === null) {
            //   const height = elRef.getBoundingClientRect().height;
            //   initialHeight.current = isNaN(height) ? 'auto' : height;
            // }
            // SAVE REF
            if (internalRef) {
                internalRef.current = elRef;
            }
            // CALL EXTERNAL REF
            if (ref) {
                if (typeof ref === 'function') {
                    ref(elRef);
                }
                else {
                    ref.current = elRef;
                }
            }
        }, onChange: (e) => {
            expandToFitContent();
            props.onChange && props.onChange(e);
        }, as: "textarea", type: type, disabled: disabled, className: (0, join_1.default)(className, exports.baseClassName, disabled ? `${exports.baseClassName}--disabled` : ''), spellCheck: false })));
});
exports.default = Textarea;
