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 _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_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, useEffect, useRef, useState } from "react";
import { useForkRef } from "../../hooks";
import { constants } from "../../utils";
import { clearSelection, selectText } from "./utils";
import { classes } from "./Editable.tokens";
import { base, EditButton, StyledInput, StyledPlacehpolder } from "./Editable.styles";
import { base as viewCSS } from "./variations/_view/base";
import { base as sizeCSS } from "./variations/_size/base";
export var editableRoot = function editableRoot(typographyVariants) {
    return function(Root) {
        return /*#__PURE__*/ forwardRef(function(_0, _1) {
            var _ref = [
                _0,
                _1
            ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), textComponent = _ref2.textComponent, value = _ref2.value, icon = _ref2.icon, maxLength = _ref2.maxLength, _ref_spellCheck = _ref2.spellCheck, spellCheck = _ref_spellCheck === void 0 ? 'false' : _ref_spellCheck, placeholder = _ref2.placeholder, name = _ref2.name, onChange = _ref2.onChange, onBlur = _ref2.onBlur, onPaste = _ref2.onPaste, props = _object_without_properties(_ref2, [
                "textComponent",
                "value",
                "icon",
                "maxLength",
                "spellCheck",
                "placeholder",
                "name",
                "onChange",
                "onBlur",
                "onPaste"
            ]), _rest1 = _sliced_to_array(_rest, 1), outerRef = _rest1[0];
            var _prevValueRef_current;
            var Component = textComponent;
            var _useState = _sliced_to_array(useState(false), 2), isEditing = _useState[0], setIsEditing = _useState[1];
            var inputRef = useRef(null);
            var innerRef = useForkRef(inputRef, outerRef);
            var prevValueRef = useRef(value || '');
            var handlePaste = function handlePaste(e) {
                if (!inputRef.current) {
                    return;
                }
                e.preventDefault();
                var text = e.clipboardData.getData('text/plain').replace(/[\n\r]/gi, '');
                if (document.queryCommandSupported('insertText')) {
                    document.execCommand('insertText', false, text);
                } else {
                    try {
                        navigator.clipboard.writeText(text);
                    } catch (unused) {
                        inputRef.current.textContent = text;
                    }
                }
                if (onPaste) {
                    onPaste(e);
                }
            };
            var handleBlur = function handleBlur(e) {
                setIsEditing(false);
                clearSelection();
                // NOTE: Remove <br> tag inserted by Safari
                var editableElement = inputRef.current;
                if (editableElement && editableElement.innerHTML === '<br>') {
                    editableElement.innerHTML = '';
                }
                if (onBlur) {
                    onBlur(e);
                }
            };
            var handleFocus = function handleFocus() {
                setIsEditing(true);
                inputRef.current && selectText(inputRef.current);
            };
            var handleEditClick = function handleEditClick() {
                var _inputRef_current;
                (_inputRef_current = inputRef.current) === null || _inputRef_current === void 0 ? void 0 : _inputRef_current.focus();
            };
            var handleKeyDown = function handleKeyDown(e) {
                if ([
                    constants.keyCodes.Enter,
                    constants.keyCodes.Escape
                ].includes(e.keyCode)) {
                    var _inputRef_current;
                    (_inputRef_current = inputRef.current) === null || _inputRef_current === void 0 ? void 0 : _inputRef_current.blur();
                }
            };
            var handleChange = function handleChange(e) {
                var _inputRef_current_textContent;
                if (!inputRef.current) {
                    return;
                }
                var contentLength = ((_inputRef_current_textContent = inputRef.current.textContent) === null || _inputRef_current_textContent === void 0 ? void 0 : _inputRef_current_textContent.length) || 0;
                if (!maxLength || contentLength <= maxLength) {
                    prevValueRef.current = inputRef.current.textContent || '';
                    onChange && onChange(e);
                } else {
                    inputRef.current.textContent = prevValueRef.current;
                }
            };
            useEffect(function() {
                if (!inputRef.current || typeof value === 'undefined' || value === inputRef.current.textContent) {
                    return;
                }
                inputRef.current.textContent = value;
            }, [
                value,
                textComponent
            ]);
            return /*#__PURE__*/ React.createElement(Root, props, /*#__PURE__*/ React.createElement(Component, {
                ref: innerRef,
                className: classes.editableTextBox,
                role: "textbox",
                spellCheck: spellCheck,
                contentEditable: true,
                onPaste: handlePaste,
                onInput: handleChange,
                onBlur: handleBlur,
                onFocus: handleFocus,
                onKeyDown: handleKeyDown,
                "aria-label": placeholder
            }), ((_prevValueRef_current = prevValueRef.current) === null || _prevValueRef_current === void 0 ? void 0 : _prevValueRef_current.length) === 0 && !isEditing && /*#__PURE__*/ React.createElement(Component, null, /*#__PURE__*/ React.createElement(StyledPlacehpolder, {
                onClick: handleEditClick
            }, placeholder)), /*#__PURE__*/ React.createElement(StyledInput, {
                type: "hidden",
                value: prevValueRef.current,
                name: name
            }), /*#__PURE__*/ React.createElement(EditButton, {
                onClick: handleEditClick,
                isHidden: isEditing
            }, icon));
        });
    };
};
export var editableConfig = function editableConfig(typographyVariants) {
    return {
        name: 'Editable',
        tag: 'span',
        layout: editableRoot(typographyVariants),
        base: base,
        variations: {
            view: {
                css: viewCSS
            },
            size: {
                css: sizeCSS
            }
        },
        defaults: {
            view: 'default',
            size: 'm'
        }
    };
};
