import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { inputStyle, typographySizes } from "./styles.js";
export function TextInput(props) {
    const [state, setState] = useState({
        value: props.value || "",
        hasFocus: false,
        pressingEnter: false,
    });
    useEffect(() => {
        setState({ ...state, value: props.value || "" });
    }, [props]);
    const onKeyDown = (e) => {
        if (e.key === "Enter") {
            setState({ ...state, pressingEnter: true });
            e.preventDefault();
        }
    };
    const onKeyUp = (e) => {
        if (e.key === "Enter") {
            if (props.onSubmit) {
                props.onSubmit(e.target.value);
            }
            if (props.clearOnSubmit) {
                setState({ ...state, value: "", pressingEnter: false });
            }
            else {
                setState({ ...state, pressingEnter: false });
            }
            e.preventDefault();
        }
        if (e.key === "Backspace" || e.key === "Delete") {
            if (props.onEmpty && e.target.value.length < 1) {
                props.onEmpty(props.id || "");
            }
            e.preventDefault();
        }
    };
    const onInput = (e) => {
        if (!state.pressingEnter) {
            const target = e.target;
            setState({ ...state, value: target.value });
            target.style.height = "1px";
            target.style.height = target.scrollHeight + "px";
        }
    };
    const setFocus = (f) => {
        setState({ ...state, hasFocus: f });
        if (!f) {
            const newValue = ref.current?.value || "";
            const origValue = props.value || "";
            if (newValue !== origValue && props.onSubmit) {
                props.onSubmit(newValue);
            }
        }
    };
    const ref = useRef(null);
    useEffect(() => {
        const resizeTextArea = () => {
            if (ref.current) {
                ref.current.style.height = "1px";
                ref.current.style.height = ref.current.scrollHeight + "px";
            }
        };
        window.addEventListener("resize", resizeTextArea);
        resizeTextArea();
        return () => {
            window.removeEventListener("resize", resizeTextArea);
        };
    });
    const style = {
        ...inputStyle(props.theme, state.hasFocus),
        ...typographySizes[props.size || "small"],
    };
    return (_jsxs("div", { children: [props.horizontalLine ? (_jsx("hr", { style: {
                    borderColor: inputStyle(props.theme, false).backgroundColor,
                } }, "line")) : (""), _jsx("textarea", { autoFocus: props.autoFocus || false, onBlur: () => setFocus(false), onFocus: () => setFocus(true), onInput: onInput, onKeyDown: onKeyDown, onKeyUp: onKeyUp, placeholder: props.placeholder || "", ref: ref, style: style, value: state.value }, "text")] }));
}
//# sourceMappingURL=textInput.js.map