"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _classnames = _interopRequireDefault(require("classnames"));
var _react = require("react");
var _LocaleProvider = require("../LocaleProvider");
var _constants = require("../../constants");
var _Icon = _interopRequireDefault(require("../Icon"));
var _MultiValue = _interopRequireDefault(require("./MultiValue"));
var _jsxRuntime = require("react/jsx-runtime");
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

const DEFAULT_INPUT_WIDTH = 2;
let inputMeter;
const getInputWidth = target => {
  if (!inputMeter) {
    inputMeter = document.createElement('pre');
    document.body.appendChild(inputMeter);
  }
  const targetStyle = window.getComputedStyle(target);
  inputMeter.style.fontFamily = targetStyle.fontFamily;
  inputMeter.style.fontSize = targetStyle.fontSize;
  inputMeter.style.padding = '0';
  inputMeter.style.display = 'inline-block';
  inputMeter.style.width = 'auto';
  inputMeter.style.position = 'absolute';
  inputMeter.style.right = '0';
  inputMeter.style.top = '-9999px';
  inputMeter.style.visibility = 'hidden';
  inputMeter.textContent = target.value;
  const {
    width
  } = inputMeter.getBoundingClientRect();
  return width || DEFAULT_INPUT_WIDTH;
};
const SelectControl = /*#__PURE__*/(0, _react.forwardRef)(function SelectControl(_ref, ref) {
  let {
    baseClassName = `${_constants.CLS_PREFIX}select-control`,
    id,
    name,
    current,
    disabled,
    searchable,
    clearable,
    multiple,
    filterValue,
    onFilterChange,
    onHighlightChange,
    onHighlightConfirm,
    onHighlightSearch,
    onOpen,
    onClose,
    onClear,
    onValueRemove,
    placeholder,
    ...props
  } = _ref;
  const inputRef = (0, _react.useRef)(null);
  const searchBufferValue = (0, _react.useRef)('');
  const searchBufferTimer = (0, _react.useRef)(0);
  const [inputWidth, setInputWidth] = (0, _react.useState)(DEFAULT_INPUT_WIDTH);
  const [focused, setFocused] = (0, _react.useState)(false);
  const translate = (0, _LocaleProvider.useTranslate)();
  if (placeholder === undefined) {
    placeholder = translate('Select.placeholder', undefined, 'Select...');
  }
  let values = [];
  if (Array.isArray(current)) {
    values = current.map(_ref2 => {
      let {
        value
      } = _ref2;
      return value;
    });
  } else if (current) {
    values = [current.value];
  }
  const hasValue = values.length > 0;
  (0, _react.useLayoutEffect)(() => {
    if (filterValue === '') {
      setInputWidth(DEFAULT_INPUT_WIDTH);
    }
  }, [filterValue]);
  const handleClick = () => {
    if (disabled) {
      return;
    }
    onOpen();
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };
  const handleInputChange = e => {
    const width = getInputWidth(e.target);
    setInputWidth(width);
    onFilterChange(e.target.value);
  };
  const handleValueRemove = value => {
    onValueRemove(value);
  };
  const handleClear = () => {
    onClear();
  };
  const handleKeyDown = e => {
    switch (e.key) {
      case 'ArrowUp':
        e.preventDefault();
        onHighlightChange(-1);
        break;
      case 'ArrowDown':
        e.preventDefault();
        onHighlightChange(1);
        break;
      case 'PageUp':
        e.preventDefault();
        onHighlightChange(-10);
        break;
      case 'PageDown':
        e.preventDefault();
        onHighlightChange(10);
        break;
      case 'Enter':
        e.preventDefault();
        onHighlightConfirm();
        break;
      case 'Escape':
        e.preventDefault();
        onFilterChange('');
        onClose();
        break;
      case 'Backspace':
        if (filterValue === '') {
          if (multiple) {
            handleValueRemove();
          } else if (clearable) {
            handleValueRemove();
          }
        }
        break;
      default:
        if (!searchable && e.key.length === 1) {
          searchBufferValue.current += e.key;
          onHighlightSearch(searchBufferValue.current);
          window.clearTimeout(searchBufferTimer.current);
          searchBufferTimer.current = window.setTimeout(() => {
            searchBufferValue.current = '';
          }, 1000);
        }
        break;
    }
  };
  const handleFocus = () => {
    setFocused(true);
  };
  const handleBlur = () => {
    setFocused(false);
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: (0, _classnames.default)(baseClassName, {
      [`${baseClassName}--disabled`]: disabled,
      [`${baseClassName}--focused`]: focused,
      [`${baseClassName}--multiple`]: multiple
    }),
    ...props,
    onClick: handleClick,
    ref: ref,
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
      className: `${baseClassName}__value-container`,
      children: [Array.isArray(current) && current.map(_ref3 => {
        let {
          value,
          label
        } = _ref3;
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_MultiValue.default, {
          onRemove: () => handleValueRemove(value),
          children: label
        }, value);
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("input", {
        id: id,
        className: `${baseClassName}__input`,
        value: filterValue,
        type: "text",
        onChange: handleInputChange,
        onKeyDown: handleKeyDown,
        onFocus: handleFocus,
        onBlur: handleBlur,
        readOnly: !searchable,
        disabled: disabled,
        ref: inputRef,
        style: {
          width: inputWidth
        }
      }), !filterValue && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_react.Fragment, {
        children: [!Array.isArray(current) && current && /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: `${baseClassName}__value`,
          children: current.children
        }), !hasValue && placeholder && /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: `${baseClassName}__placeholder`,
          children: placeholder
        })]
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
      className: `${baseClassName}__indicators`,
      children: [clearable && hasValue && /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
        type: "button",
        className: (0, _classnames.default)(`${baseClassName}__indicator`, `${baseClassName}__indicator--clear`),
        tabIndex: -1,
        onMouseDown: e => e.preventDefault(),
        onClick: e => {
          e.stopPropagation();
          handleClear();
        },
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Icon.default, {
          className: `${baseClassName}__indicator-icon`,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("svg", {
            xmlns: "http://www.w3.org/2000/svg",
            viewBox: "-4 -4 16 16",
            "aria-hidden": "true",
            focusable: "false",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
              d: "M.85 7.854a.498.498 0 1 1-.704-.704L3.296 4 .146.85A.498.498 0 0 1 .85.146L4 3.296 7.15.146a.498.498 0 0 1 .704.704L4.704 4l3.15 3.15a.498.498 0 0 1-.704.704L4 4.704.85 7.854z"
            })
          })
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
        type: "button",
        className: (0, _classnames.default)(`${baseClassName}__indicator`, `${baseClassName}__indicator--dropdown`),
        tabIndex: -1,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Icon.default, {
          className: `${baseClassName}__indicator-icon`,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("svg", {
            xmlns: "http://www.w3.org/2000/svg",
            viewBox: "-4 -5 16 16",
            "aria-hidden": "true",
            focusable: "false",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
              d: "M4 4.048L.847.895a.496.496 0 1 0-.702.702l3.452 3.451a.5.5 0 0 0 .806 0l3.452-3.451a.496.496 0 0 0-.702-.702L4 4.048z"
            })
          })
        })
      })]
    }), name && values.map(value => /*#__PURE__*/(0, _jsxRuntime.jsx)("input", {
      type: "hidden",
      name: name,
      value: value
    }, value))]
  });
});
SelectControl.displayName = 'SelectControl';
var _default = exports.default = SelectControl;