import { jsx as _jsx } from "react/jsx-runtime";
import React, { useRef, useEffect } from 'react';
const EditableCell = React.forwardRef(({ initialValue = '', onChange, className = '', style = {} }, ref) => {
    const cellRef = useRef(null);
    React.useImperativeHandle(ref, () => cellRef.current);
    useEffect(() => {
        if (cellRef.current && document.activeElement !== cellRef.current) {
            // We add a 'buffer' newline if the value ends in \n to force the
            // browser to render the second line for the cursor.
            const displayValue = String(initialValue)?.endsWith('\n')
                ? `${initialValue}\n`
                : initialValue;
            if (displayValue !== cellRef.current.innerText) {
                cellRef.current.innerText = displayValue;
            }
        }
    }, [initialValue]);
    const defaultStyle = {
        outline: 'none',
        transition: 'border 0.2s',
        whiteSpace: 'pre-wrap',
        wordBreak: 'break-word',
        fontFamily: 'inherit',
        fontSize: 'inherit',
        lineHeight: 'normal',
        minHeight: '24px',
        verticalAlign: 'middle',
        caretColor: 'black',
        height: 'inherit',
        maxHeight: 'inherit',
        display: 'block',
        position: 'relative',
        paddingBottom: '2px',
    };
    const handleInput = () => {
        if (cellRef.current) {
            let newValue = cellRef.current.innerText;
            // Strip the browser's layout newline before sending back to parent
            if (newValue.endsWith('\n')) {
                newValue = newValue.slice(0, -1);
            }
            onChange?.(newValue);
        }
    };
    const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
            if (e.altKey || e.shiftKey) {
                e.preventDefault();
                document.execCommand('insertLineBreak');
                return;
            }
            cellRef.current?.blur();
        }
        if (e.key === 'Delete' || e.key === 'Backspace') {
            e.stopPropagation();
        }
    };
    const handlePaste = (e) => {
        e.preventDefault();
        const text = e.clipboardData.getData('text/plain');
        document.execCommand('insertText', false, text);
    };
    return (_jsx("div", { style: style, children: _jsx("div", { ref: cellRef, className: `editable-cell ${className}`, contentEditable: true, suppressContentEditableWarning: true, onKeyDown: handleKeyDown, onInput: handleInput, onPaste: handlePaste, spellCheck: false, autoCorrect: "off", autoCapitalize: "off", style: defaultStyle }) }));
});
export default EditableCell;
//# sourceMappingURL=EditableCell.js.map