import { jsx } from 'react/jsx-runtime';
import * as React from 'react';
import { useEffect } from 'react';
import { measureText } from '../../utils/measureText.js';
import { Input } from './Input.js';

const AutoSizeInput = React.forwardRef((props, ref) => {
  const {
    defaultValue = "",
    minWidth = 10,
    maxWidth,
    onCommitChange,
    onKeyDown,
    onBlur,
    value: controlledValue,
    ...restProps
  } = props;
  const [value, setValue] = React.useState(controlledValue != null ? controlledValue : defaultValue);
  const [inputWidth, setInputWidth] = React.useState(minWidth);
  useEffect(() => {
    if (controlledValue) {
      setValue(controlledValue);
    }
  }, [controlledValue]);
  useEffect(() => {
    setInputWidth(getWidthFor(value.toString(), minWidth, maxWidth));
  }, [value, minWidth, maxWidth]);
  return /* @__PURE__ */ jsx(
    Input,
    {
      ...restProps,
      ref,
      value: value.toString(),
      onChange: (event) => {
        setValue(event.currentTarget.value);
      },
      width: inputWidth,
      onBlur: (event) => {
        if (onBlur) {
          onBlur(event);
        } else if (onCommitChange) {
          onCommitChange(event);
        }
      },
      onKeyDown: (event) => {
        if (onKeyDown) {
          onKeyDown(event);
        } else if (event.key === "Enter" && onCommitChange) {
          onCommitChange(event);
        }
      },
      "data-testid": "autosize-input"
    }
  );
});
function getWidthFor(value, minWidth, maxWidth) {
  if (!value) {
    return minWidth;
  }
  const extraSpace = 3;
  const realWidth = measureText(value.toString(), 14).width / 8 + extraSpace;
  if (minWidth && realWidth < minWidth) {
    return minWidth;
  }
  if (maxWidth && realWidth > maxWidth) {
    return maxWidth;
  }
  return realWidth;
}
AutoSizeInput.displayName = "AutoSizeInput";

export { AutoSizeInput };
//# sourceMappingURL=AutoSizeInput.js.map
