import { jsx } from 'react/jsx-runtime';
import * as React from 'react';
import { useEffect, useMemo } 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,
    onChange,
    onKeyDown,
    onBlur,
    value: controlledValue,
    placeholder,
    ...restProps
  } = props;
  const [value, setValue] = React.useState(controlledValue != null ? controlledValue : defaultValue);
  useEffect(() => {
    setValue(controlledValue != null ? controlledValue : defaultValue);
  }, [controlledValue, defaultValue]);
  const inputWidth = useMemo(() => {
    const displayValue = value || placeholder || "";
    const valueString = typeof displayValue === "string" ? displayValue : displayValue.toString();
    return getWidthFor(valueString, minWidth, maxWidth);
  }, [placeholder, value, minWidth, maxWidth]);
  return /* @__PURE__ */ jsx(
    Input,
    {
      ...restProps,
      placeholder,
      ref,
      value: value.toString(),
      onChange: (event) => {
        if (onChange) {
          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
