"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiCompressedFilePicker = exports.EuiFilePicker = exports.DISPLAYS = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _common = require("../../common");
var _validatable_control = require("../validatable_control");
var _button = require("../../button");
var _progress = require("../../progress");
var _icon = require("../../icon");
var _i18n = require("../../i18n");
var _loading = require("../../loading");
var _accessibility = require("../../../services/accessibility");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) { ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) { o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) { if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } } return t; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) { ; } } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */ /*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var displayToClassNameMap = {
  default: null,
  large: 'euiFilePicker--large'
};
var DISPLAYS = (0, _common.keysOf)(displayToClassNameMap);
exports.DISPLAYS = DISPLAYS;
var EuiFilePicker = /*#__PURE__*/function (_Component) {
  _inherits(EuiFilePicker, _Component);
  var _super = _createSuper(EuiFilePicker);
  function EuiFilePicker() {
    var _this;
    _classCallCheck(this, EuiFilePicker);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    _defineProperty(_assertThisInitialized(_this), "state", {
      promptText: null,
      isHoveringDrop: false
    });
    _defineProperty(_assertThisInitialized(_this), "fileInput", null);
    _defineProperty(_assertThisInitialized(_this), "handleChange", function (filesSelected) {
      if (!_this.fileInput) return;
      if (_this.fileInput.files && _this.fileInput.files.length > 1) {
        _this.setState({
          promptText: "".concat(_this.fileInput.files.length, " ").concat(filesSelected)
        });
      } else if (_this.fileInput.files && _this.fileInput.files.length === 0) {
        _this.setState({
          promptText: null
        });
      } else {
        _this.setState({
          promptText: _this.fileInput.value.split('\\').pop()
        });
      }
      var onChange = _this.props.onChange;
      if (onChange) {
        onChange(_this.fileInput.files);
      }
    });
    _defineProperty(_assertThisInitialized(_this), "removeFiles", function (e) {
      e.stopPropagation();
      e.preventDefault();
      if (!_this.fileInput) return;
      _this.fileInput.value = '';
      _this.handleChange(null);
    });
    _defineProperty(_assertThisInitialized(_this), "showDrop", function () {
      if (!_this.props.disabled) {
        _this.setState({
          isHoveringDrop: true
        });
      }
    });
    _defineProperty(_assertThisInitialized(_this), "hideDrop", function () {
      _this.setState({
        isHoveringDrop: false
      });
    });
    return _this;
  }
  _createClass(EuiFilePicker, [{
    key: "render",
    value: function render() {
      var _this2 = this;
      return /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
        tokens: ['euiFilePicker.clearSelectedFiles', 'euiFilePicker.filesSelected'],
        defaults: ['Clear selected files', 'files selected']
      }, function (_ref) {
        var _ref2 = _slicedToArray(_ref, 2),
          clearSelectedFiles = _ref2[0],
          filesSelected = _ref2[1];
        var _this2$props = _this2.props,
          id = _this2$props.id,
          name = _this2$props.name,
          initialPromptText = _this2$props.initialPromptText,
          className = _this2$props.className,
          disabled = _this2$props.disabled,
          compressed = _this2$props.compressed,
          onChange = _this2$props.onChange,
          isInvalid = _this2$props.isInvalid,
          fullWidth = _this2$props.fullWidth,
          isLoading = _this2$props.isLoading,
          display = _this2$props.display,
          rest = _objectWithoutProperties(_this2$props, ["id", "name", "initialPromptText", "className", "disabled", "compressed", "onChange", "isInvalid", "fullWidth", "isLoading", "display"]);
        var promptId = (0, _accessibility.htmlIdGenerator)()();
        if (id) {
          promptId = "".concat(id, "-filePicker__prompt");
        }
        var isOverridingInitialPrompt = _this2.state.promptText != null;
        var normalFormControl = display === 'default';
        var classes = (0, _classnames.default)('euiFilePicker', displayToClassNameMap[display], {
          euiFilePicker__showDrop: _this2.state.isHoveringDrop,
          'euiFilePicker--compressed': compressed,
          'euiFilePicker--fullWidth': fullWidth,
          'euiFilePicker-isInvalid': isInvalid,
          'euiFilePicker-isLoading': isLoading,
          'euiFilePicker-hasFiles': isOverridingInitialPrompt
        }, className);
        var clearButton;
        if (isLoading && normalFormControl) {
          // Override clear button with loading spinner if it is in loading state
          clearButton = /*#__PURE__*/_react.default.createElement(_loading.EuiLoadingSpinner, {
            className: "euiFilePicker__loadingSpinner"
          });
        } else if (isOverridingInitialPrompt) {
          if (normalFormControl) {
            clearButton = /*#__PURE__*/_react.default.createElement("button", {
              type: "button",
              "aria-label": clearSelectedFiles,
              className: "euiFilePicker__clearButton",
              onClick: _this2.removeFiles
            }, /*#__PURE__*/_react.default.createElement(_icon.EuiIcon, {
              className: "euiFilePicker__clearIcon",
              type: "cross"
            }));
          } else {
            clearButton = /*#__PURE__*/_react.default.createElement(_button.EuiButtonEmpty, {
              "aria-label": clearSelectedFiles,
              className: "euiFilePicker__clearButton",
              size: "xs",
              onClick: _this2.removeFiles
            }, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
              token: "euiFilePicker.removeSelected",
              default: "Remove"
            }));
          }
        } else {
          clearButton = null;
        }
        var loader = !normalFormControl && isLoading && /*#__PURE__*/_react.default.createElement(_progress.EuiProgress, {
          size: "xs",
          color: "accent",
          position: "absolute"
        });
        return /*#__PURE__*/_react.default.createElement("div", {
          className: classes
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "euiFilePicker__wrap"
        }, /*#__PURE__*/_react.default.createElement(_validatable_control.EuiValidatableControl, {
          isInvalid: isInvalid
        }, /*#__PURE__*/_react.default.createElement("input", _extends({
          type: "file",
          id: id,
          name: name,
          className: "euiFilePicker__input",
          onChange: function onChange() {
            return _this2.handleChange(filesSelected);
          },
          ref: function ref(input) {
            _this2.fileInput = input;
          },
          onDragOver: _this2.showDrop,
          onDragLeave: _this2.hideDrop,
          onDrop: _this2.hideDrop,
          disabled: disabled,
          "aria-describedby": promptId
        }, rest))), /*#__PURE__*/_react.default.createElement("div", {
          className: "euiFilePicker__prompt",
          id: promptId
        }, /*#__PURE__*/_react.default.createElement(_icon.EuiIcon, {
          className: "euiFilePicker__icon",
          type: "importAction",
          size: normalFormControl ? 'm' : 'l',
          "aria-hidden": "true"
        }), /*#__PURE__*/_react.default.createElement("div", {
          className: "euiFilePicker__promptText"
        }, _this2.state.promptText || initialPromptText), clearButton, loader)));
      });
    }
  }]);
  return EuiFilePicker;
}(_react.Component); // @internal
exports.EuiFilePicker = EuiFilePicker;
_defineProperty(EuiFilePicker, "defaultProps", {
  initialPromptText: 'Select or drag and drop a file',
  compressed: false,
  display: 'large'
});
EuiFilePicker.propTypes = {
  id: _propTypes.default.string,
  name: _propTypes.default.string,
  className: _propTypes.default.string,
  /**
     * The content that appears in the dropzone if no file is attached
     */
  initialPromptText: _propTypes.default.node,
  /**
     * Use as a callback to access the HTML FileList API
     */
  onChange: _propTypes.default.func,
  /**
     * Reduces the size to a typical (compressed) input
     */
  compressed: _propTypes.default.bool,
  /**
     * Size or type of display;
     * `default` for normal height, similar to other controls;
     * `large` for taller size
     */
  display: _propTypes.default.oneOf(["default", "large"]),
  fullWidth: _propTypes.default.bool,
  isInvalid: _propTypes.default.bool,
  isLoading: _propTypes.default.bool,
  disabled: _propTypes.default.bool,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string
};
// @internal
var EuiCompressedFilePicker = /*#__PURE__*/function (_EuiFilePicker) {
  _inherits(EuiCompressedFilePicker, _EuiFilePicker);
  var _super2 = _createSuper(EuiCompressedFilePicker);
  function EuiCompressedFilePicker() {
    _classCallCheck(this, EuiCompressedFilePicker);
    return _super2.apply(this, arguments);
  }
  return EuiCompressedFilePicker;
}(EuiFilePicker);
exports.EuiCompressedFilePicker = EuiCompressedFilePicker;
_defineProperty(EuiCompressedFilePicker, "defaultProps", _objectSpread(_objectSpread({}, EuiFilePicker.defaultProps), {}, {
  compressed: true
}));