"use strict";
const React = require("react");
const index = require("../ConfigProvider/index.js");
const index$3 = require("../Tag/index.js");
const useMergeValue = require("../_util/hooks/useMergeValue.js");
const classNames = require("../_util/classNames.js");
const inputElement = require("../Input/input-element.js");
const iconHover = require("../_class/icon-hover.js");
const index$1 = require("../../icon/react-icon/IconClose/index.js");
const is = require("../_util/is.js");
const getHotkeyHandler = require("../_util/getHotkeyHandler.js");
const keycode = require("../_util/keycode.js");
const useMergeProps = require("../_util/hooks/useMergeProps.js");
const index$2 = require("../_class/Draggable/index.js");
const omit = require("../_util/omit.js");
const emotionReactJsxRuntime_browser_esm = require("../../../../../../@emotion_react@11.10.4_3toe27fv7etiytxb5kxc7fxaw4/node_modules/@emotion/react/jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js");
const CSSTransition = require("../../../../../../react-transition-group@4.4.5_biqbaboplfbrettd7655fr4n2y/node_modules/react-transition-group/esm/CSSTransition.js");
const TransitionGroup = require("../../../../../../react-transition-group@4.4.5_biqbaboplfbrettd7655fr4n2y/node_modules/react-transition-group/esm/TransitionGroup.js");
const _interopDefaultLegacy = (e) => e && typeof e === "object" && "default" in e ? e : { default: e };
const React__default = /* @__PURE__ */ _interopDefaultLegacy(React);
var __assign = globalThis && globalThis.__assign || function() {
  __assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
var __awaiter = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator = globalThis && globalThis.__generator || function(thisArg, body) {
  var _ = {
    label: 0,
    sent: function() {
      if (t[0] & 1)
        throw t[1];
      return t[1];
    },
    trys: [],
    ops: []
  }, f, y, t, g;
  return g = {
    next: verb(0),
    "throw": verb(1),
    "return": verb(2)
  }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f)
      throw new TypeError("Generator is already executing.");
    while (_)
      try {
        if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
          return t;
        if (y = 0, t)
          op = [op[0] & 2, t.value];
        switch (op[0]) {
          case 0:
          case 1:
            t = op;
            break;
          case 4:
            _.label++;
            return {
              value: op[1],
              done: false
            };
          case 5:
            _.label++;
            y = op[1];
            op = [0];
            continue;
          case 7:
            op = _.ops.pop();
            _.trys.pop();
            continue;
          default:
            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _ = 0;
              continue;
            }
            if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
              _.label = op[1];
              break;
            }
            if (op[0] === 6 && _.label < t[1]) {
              _.label = t[1];
              t = op;
              break;
            }
            if (t && _.label < t[2]) {
              _.label = t[2];
              _.ops.push(op);
              break;
            }
            if (t[2])
              _.ops.pop();
            _.trys.pop();
            continue;
        }
        op = body.call(thisArg, _);
      } catch (e) {
        op = [6, e];
        y = 0;
      } finally {
        f = t = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return {
      value: op[0] ? op[1] : void 0,
      done: true
    };
  }
};
var __rest = globalThis && globalThis.__rest || function(s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
var __read = globalThis && globalThis.__read || function(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = {
      error
    };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
};
var __spreadArray = globalThis && globalThis.__spreadArray || function(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i = 0, l = from.length, ar; i < l; i++) {
      if (ar || !(i in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i);
        ar[i] = from[i];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
};
var CSS_TRANSITION_DURATION = 300;
var REACT_KEY_FOR_INPUT = "__input_" + Math.random().toFixed(10).slice(2);
var keepFocus = function(e) {
  e.target.tagName !== "INPUT" && e.preventDefault();
};
var formatValue = function(value) {
  if (!is.isArray(value)) {
    return [];
  }
  return value.map(function(item) {
    return is.isObject(item) ? __assign(__assign({}, item), {
      label: "label" in item ? item.label : item.value,
      value: item.value,
      closable: item.closable
    }) : {
      label: item,
      value: item
    };
  });
};
var useComputeAutoWidthDelay = function(value) {
  var refDelay = React.useRef(0);
  var refPrevValueLength = React.useRef(value.length);
  React.useEffect(function() {
    refDelay.current = value.length === 0 && refPrevValueLength.current > 0 ? CSS_TRANSITION_DURATION : 0;
    refPrevValueLength.current = value.length;
  }, [value]);
  return refDelay;
};
var UsedTransitionGroup = function(_a) {
  var prefixCls = _a.prefixCls, children = _a.children, animation = _a.animation;
  return animation ? /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(TransitionGroup, {
    component: "div",
    className: prefixCls + "-inner",
    children
  }) : /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx("div", {
    className: prefixCls + "-inner",
    children
  });
};
var defaultProps = {
  animation: true,
  validate: function(inputValue, values) {
    return inputValue && values.every(function(item) {
      return item.value !== inputValue;
    });
  }
};
function InputTag(baseProps, ref) {
  var _a;
  var _this = this;
  var _b = React.useContext(index.ConfigContext), getPrefixCls = _b.getPrefixCls, ctxSize = _b.size, componentConfig = _b.componentConfig, rtl = _b.rtl;
  var props = useMergeProps(baseProps, defaultProps, componentConfig === null || componentConfig === void 0 ? void 0 : componentConfig.InputTag);
  var className = props.className, style = props.style, placeholder = props.placeholder, error = props.error, disabled = props.disabled, readOnly = props.readOnly, allowClear = props.allowClear, autoFocus = props.autoFocus, labelInValue = props.labelInValue, disableInput = props.disableInput, animation = props.animation, saveOnBlur = props.saveOnBlur, dragToSort = props.dragToSort, icon = props.icon, suffix = props.suffix, validate = props.validate, renderTag = props.renderTag, tagClassName = props.tagClassName, onInputChange = props.onInputChange, onKeyDown = props.onKeyDown, onPaste = props.onPaste, onChange = props.onChange, onFocus = props.onFocus, onBlur = props.onBlur, onPressEnter = props.onPressEnter, onRemove = props.onRemove, onClear = props.onClear, onClick = props.onClick, rest = __rest(props, ["className", "style", "placeholder", "error", "disabled", "readOnly", "allowClear", "autoFocus", "labelInValue", "disableInput", "animation", "saveOnBlur", "dragToSort", "icon", "suffix", "validate", "renderTag", "tagClassName", "onInputChange", "onKeyDown", "onPaste", "onChange", "onFocus", "onBlur", "onPressEnter", "onRemove", "onClear", "onClick"]);
  var prefixCls = getPrefixCls("input-tag");
  var size = "size" in props ? props.size : ctxSize;
  var inputRef = React.useRef();
  var _c = __read(React.useState(false), 2), focused = _c[0], setFocused = _c[1];
  var _d = __read(useMergeValue([], {
    defaultValue: "defaultValue" in props ? formatValue(props.defaultValue) : void 0,
    value: "value" in props ? formatValue(props.value) : void 0
  }), 2), value = _d[0], setValue = _d[1];
  var _e = __read(useMergeValue("", {
    value: props.inputValue
  }), 2), inputValue = _e[0], setInputValue = _e[1];
  var refDelay = useComputeAutoWidthDelay(value);
  var draggable = !!(dragToSort && !readOnly && !disabled);
  React.useImperativeHandle(ref, function() {
    return {
      blur: inputRef.current && inputRef.current.blur,
      focus: inputRef.current && inputRef.current.focus
    };
  }, []);
  var valueChangeHandler = function(value2, reason) {
    if (disabled || readOnly) {
      return;
    }
    if (!("value" in props)) {
      setValue(value2);
    }
    onChange && onChange(labelInValue ? value2 : value2.map(function(x) {
      return x.value;
    }), reason);
  };
  var tagCloseHandler = function(itemValue, index2, event) {
    onRemove && onRemove(itemValue, index2, event);
    valueChangeHandler(__spreadArray(__spreadArray([], __read(value.slice(0, index2)), false), __read(value.slice(index2 + 1)), false), "remove");
  };
  var hotkeyHandler = getHotkeyHandler(/* @__PURE__ */ new Map([[keycode.Backspace.code, function(event) {
    if (!event.target.value && value.length) {
      for (var index2 = value.length - 1; index2 >= 0; index2--) {
        var itemValue = value[index2];
        if (itemValue.closable !== false) {
          tagCloseHandler(itemValue, index2, event);
          return;
        }
      }
    }
  }]]));
  var tryAddInputValueToTag = function() {
    return __awaiter(_this, void 0, void 0, function() {
      var validateResult, _a2, error_1;
      return __generator(this, function(_b2) {
        switch (_b2.label) {
          case 0:
            _b2.trys.push([0, 4, , 5]);
            if (!(typeof validate === "function"))
              return [
                3,
                2
              ];
            return [
              4,
              validate(inputValue, value)
            ];
          case 1:
            _a2 = _b2.sent();
            return [
              3,
              3
            ];
          case 2:
            _a2 = true;
            _b2.label = 3;
          case 3:
            validateResult = _a2;
            if (validateResult) {
              valueChangeHandler(value.concat({
                value: validateResult === true ? inputValue : validateResult,
                label: inputValue
              }), "add");
              setInputValue("");
            }
            return [
              3,
              5
            ];
          case 4:
            error_1 = _b2.sent();
            console.error(error_1);
            return [
              3,
              5
            ];
          case 5:
            return [
              2
            ];
        }
      });
    });
  };
  var mergedRenderTag = function(item, index2) {
    var _a2;
    var itemValue = item.value, label = item.label;
    var closable = !readOnly && !disabled && item.closable !== false;
    var onClose = function(event) {
      tagCloseHandler(item, index2, event);
    };
    if (renderTag) {
      return renderTag({
        value: itemValue,
        label,
        closable,
        onClose
      }, index2, value);
    }
    return /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$3, {
      visible: true,
      className: classNames(prefixCls + "-tag", (_a2 = {}, _a2[tagClassName] = tagClassName, _a2)),
      closable,
      closeIcon: icon && icon.removeIcon,
      title: typeof label === "string" ? label : void 0,
      onClose,
      children: typeof label === "string" ? label.replace(/\s/g, "\xA0") : label
    });
  };
  var clearIcon = allowClear && !disabled && !readOnly && value.length ? /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(iconHover, {
    size,
    className: prefixCls + "-clear-icon",
    onClick: function(e) {
      e.stopPropagation();
      valueChangeHandler([], "clear");
      if (!focused) {
        inputRef.current && inputRef.current.focus();
      }
      onClear && onClear();
    },
    onMouseDown: keepFocus,
    children: icon && icon.clearIcon || /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$1, {})
  }, "clearIcon") : null;
  var hasSuffix = !!(clearIcon || suffix);
  var disableInputComponent = disabled || disableInput;
  var childrenWithAnimation = value.map(function(x, i) {
    var isRepeat = value.findIndex(function(item) {
      return item.value === x.value;
    }) !== i;
    var eleTag = mergedRenderTag(x, i);
    return React__default.default.isValidElement(eleTag) ? /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(CSSTransition, {
      timeout: CSS_TRANSITION_DURATION,
      classNames: "zoomIn",
      children: eleTag
    }, typeof x.value === "object" ? i : isRepeat ? x.value + "-" + i : x.value) : eleTag;
  }).concat(/* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(CSSTransition, {
    timeout: CSS_TRANSITION_DURATION,
    classNames: "zoomIn",
    children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(inputElement, {
      autoComplete: "off",
      size,
      disabled: disableInputComponent,
      readOnly,
      ref: inputRef,
      autoFocus,
      placeholder: !value.length ? placeholder : "",
      prefixCls: prefixCls + "-input",
      autoFitWidth: {
        delay: function() {
          return refDelay.current;
        }
      },
      onPressEnter: function(e) {
        return __awaiter(_this, void 0, void 0, function() {
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                inputValue && e.preventDefault();
                onPressEnter && onPressEnter(e);
                return [
                  4,
                  tryAddInputValueToTag()
                ];
              case 1:
                _a2.sent();
                return [
                  2
                ];
            }
          });
        });
      },
      onFocus: function(e) {
        if (!disableInputComponent && !readOnly) {
          setFocused(true);
          onFocus && onFocus(e);
        }
      },
      onBlur: function(e) {
        return __awaiter(_this, void 0, void 0, function() {
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                setFocused(false);
                onBlur && onBlur(e);
                if (!saveOnBlur)
                  return [
                    3,
                    2
                  ];
                return [
                  4,
                  tryAddInputValueToTag()
                ];
              case 1:
                _a2.sent();
                _a2.label = 2;
              case 2:
                setInputValue("");
                return [
                  2
                ];
            }
          });
        });
      },
      value: inputValue,
      onChange: function(v, e) {
        setInputValue(v);
        onInputChange && onInputChange(v, e);
      },
      onKeyDown: function(event) {
        hotkeyHandler(event);
        onKeyDown && onKeyDown(event);
      },
      onPaste
    })
  }, REACT_KEY_FOR_INPUT));
  return /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx("div", {
    ...__assign({}, omit(rest, ["size", "defaultValue", "value", "inputValue"]), {
      style,
      className: classNames(prefixCls, (_a = {}, _a[prefixCls + "-size-" + size] = size, _a[prefixCls + "-disabled"] = disabled, _a[prefixCls + "-error"] = error, _a[prefixCls + "-focus"] = focused, _a[prefixCls + "-readonly"] = readOnly, _a[prefixCls + "-has-suffix"] = hasSuffix, _a[prefixCls + "-has-placeholder"] = !value.length, _a[prefixCls + "-rtl"] = rtl, _a), className),
      onMouseDown: function(event) {
        focused && keepFocus(event);
      },
      onClick: function(e) {
        !focused && inputRef.current && inputRef.current.focus();
        if (onClick) {
          onClick(e);
        }
      }
    }),
    children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsxs("div", {
      className: prefixCls + "-view",
      children: [/* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(UsedTransitionGroup, {
        prefixCls,
        animation,
        children: draggable ? /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$2, {
          itemWrapperStyle: {
            display: "inline-block"
          },
          direction: "horizontal",
          onIndexChange: function(index2, prevIndex) {
            var moveItem = function(arr, fromIndex, toIndex) {
              arr = arr.slice();
              var isMoveLeft = fromIndex > toIndex;
              var _a2 = __read(arr.splice(fromIndex, 1), 1), item = _a2[0];
              arr.splice(isMoveLeft ? toIndex : toIndex - 1, 0, item);
              return arr;
            };
            valueChangeHandler(moveItem(value, prevIndex, index2), "sort");
          },
          children: childrenWithAnimation
        }) : childrenWithAnimation
      }), hasSuffix && /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsxs("div", {
        className: prefixCls + "-suffix",
        onMouseDown: keepFocus,
        children: [clearIcon, suffix]
      })]
    })
  });
}
var InputTagRef = React__default.default.forwardRef(InputTag);
InputTagRef.displayName = "InputTag";
const InputTag$1 = InputTagRef;
module.exports = InputTag$1;
//# sourceMappingURL=input-tag.js.map
