"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.styles = void 0;

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _react = _interopRequireWildcard(require("react"));

var _CSSTransitionGroup = _interopRequireDefault(require("react-transition-group/CSSTransitionGroup"));

var _formatMessage = _interopRequireDefault(require("../../format-message"));

var _ScreenReaderContent = _interopRequireDefault(require("@instructure/ui-a11y/lib/components/ScreenReaderContent"));

var _Select = _interopRequireDefault(require("@instructure/ui-core/lib/components/Select"));

var _Button = _interopRequireDefault(require("@instructure/ui-buttons/lib/components/Button"));

var _Alert = _interopRequireDefault(require("@instructure/ui-alerts/lib/components/Alert"));

var _IconAdd = _interopRequireDefault(require("@instructure/ui-icons/lib/Solid/IconAdd"));

var _IconMinimize = _interopRequireDefault(require("@instructure/ui-icons/lib/Solid/IconMinimize"));

var _Loading = _interopRequireDefault(require("../../common/components/Loading"));

var _UsageRightsForm = _interopRequireDefault(require("./UsageRightsForm"));

var _AltTextForm = _interopRequireDefault(require("./AltTextForm"));

var _aphrodite = require("aphrodite");

/*
 * Copyright (C) 2018 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */
var UploadForm =
/*#__PURE__*/
function (_Component) {
  (0, _inherits2.default)(UploadForm, _Component);

  function UploadForm(props) {
    var _this;

    (0, _classCallCheck2.default)(this, UploadForm);
    _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(UploadForm).call(this, props));

    _this.setAltResolved = function (resolved) {
      _this.setState((0, _objectSpread2.default)({}, _this.state, {
        altResolved: resolved
      }));
    };

    _this.state = {
      file: {},
      altResolved: false
    };
    return _this;
  }

  (0, _createClass2.default)(UploadForm, [{
    key: "componentWillMount",
    value: function componentWillMount() {
      if (this.props.fetchFolders) {
        this.props.fetchFolders();
      }
    }
  }, {
    key: "flattenFolderTreeDepthFirst",
    value: function flattenFolderTreeDepthFirst(folderId, folderTree, accum, depth) {
      var _this2 = this;

      if (!folderId) {
        return [];
      }

      accum = accum || [];
      depth = depth || 0;
      accum.push({
        folderId: folderId,
        depth: depth
      });

      if (!folderTree[folderId]) {
        return accum;
      }

      folderTree[folderId].forEach(function (sfId) {
        _this2.flattenFolderTreeDepthFirst(sfId, folderTree, accum, depth + 1);
      });
      return accum;
    }
  }, {
    key: "parentFolderId",
    value: function parentFolderId() {
      var stateId = this.state.file.parentFolderId;

      if (stateId) {
        return stateId;
      }

      var firstKey = Object.keys(this.props.upload.folders)[0];
      var firstFolder = this.props.upload.folders[firstKey];

      if (firstFolder) {
        return firstFolder.id;
      }

      return null;
    }
  }, {
    key: "showForm",
    value: function showForm(e) {
      e.preventDefault();
      this.props.toggleUploadForm();
      this.setState({
        file: {}
      });
    }
  }, {
    key: "handleUpload",
    value: function handleUpload(e) {
      e.preventDefault();
      var fileMetaProps = (0, _objectSpread2.default)({}, this.state.file);

      if (this._usageRights) {
        fileMetaProps.usageRights = this._usageRights.value();
      }

      if (this._altText) {
        fileMetaProps.altText = this._altText.value();
      }

      this.props.startUpload(fileMetaProps);
    }
  }, {
    key: "handleFolderChange",
    value: function handleFolderChange(e) {
      e.preventDefault();
      this.setState({
        file: {
          parentFolderId: e.target.value,
          name: this.state.file.name,
          size: this.state.file.size,
          contentType: this.state.file.contentType,
          domObject: this.state.file.domObject
        }
      });
    }
  }, {
    key: "handleFileClick",
    value: function handleFileClick(e) {
      e.target.value = "";
      this.setState({
        file: {
          parentFolderId: this.parentFolderId()
        }
      });
    }
  }, {
    key: "handleFileChange",
    value: function handleFileChange(e) {
      var file = e.target.files[0];
      var fileStateUpdate = {
        file: {}
      };

      if (file !== undefined) {
        fileStateUpdate = {
          file: {
            parentFolderId: this.parentFolderId(),
            name: file.name,
            size: file.size,
            contentType: file.type,
            domObject: file
          }
        };
      }

      this.setState(fileStateUpdate);
    }
  }, {
    key: "isImageSelected",
    value: function isImageSelected(file) {
      return file && file.name;
    }
  }, {
    key: "uploadLink",
    value: function uploadLink() {
      var screenreaderMessage = this.props.messages.expandScreenreader;
      var message = this.props.messages.expand;
      var icon;

      if (this.props.upload.formExpanded) {
        screenreaderMessage = this.props.messages.collapseScreenreader;
        message = this.props.messages.collapse;
        icon = _react.default.createElement(_IconMinimize.default, {
          className: (0, _aphrodite.css)(styles.icon)
        });
      } else {
        icon = _react.default.createElement(_IconAdd.default, {
          className: (0, _aphrodite.css)(styles.icon)
        });
      }

      return _react.default.createElement(_Button.default, {
        "aria-expanded": this.props.upload.formExpanded,
        variant: "link",
        onClick: this.showForm.bind(this)
      }, _react.default.createElement("span", {
        "aria-hidden": true
      }, icon, " " + message), _react.default.createElement(_ScreenReaderContent.default, null, screenreaderMessage));
    }
  }, {
    key: "renderFolderOption",
    value: function renderFolderOption(_ref) {
      var folderId = _ref.folderId,
          depth = _ref.depth;
      var folder = this.props.upload.folders[folderId];

      if (!folder) {
        return;
      }

      var space = "";

      for (var i = 0; i < depth; i++) {
        space += "\xA0\xA0";
      }

      return _react.default.createElement("option", {
        key: "folder_" + folder.id,
        value: folder.id
      }, space, folder.name);
    }
  }, {
    key: "renderFolderSelect",
    value: function renderFolderSelect() {
      var label = _react.default.createElement("span", null, _react.default.createElement("span", {
        "aria-hidden": true
      }, "\uD3F4\uB354"), _react.default.createElement(_ScreenReaderContent.default, null, "Select a folder to upload your file into"));

      var flattenedFolders = this.flattenFolderTreeDepthFirst(this.props.upload.rootFolderId, this.props.upload.folderTree);
      return _react.default.createElement(_Select.default, {
        label: label,
        onChange: this.handleFolderChange.bind(this),
        name: "folder_id"
      }, this.props.upload.loadingFolders && _react.default.createElement("option", {
        key: "loading",
        value: "loading"
      }, "Loading folders..."), flattenedFolders.map(this.renderFolderOption, this));
    }
  }, {
    key: "shouldDisableUpload",
    value: function shouldDisableUpload(props, state) {
      var ret;

      if (props.showAltTextForm) {
        ret = !(state.file && state.file.name && state.altResolved);
      } else {
        ret = !(state.file && state.file.name);
      }

      return ret;
    }
  }, {
    key: "renderFormSubmit",
    value: function renderFormSubmit() {
      if (this.props.upload.uploading) {
        return _react.default.createElement(_Loading.default, null);
      } else {
        return _react.default.createElement("div", {
          className: (0, _aphrodite.css)(styles.uploadButtonContainer)
        }, _react.default.createElement(_Button.default, {
          type: "submit",
          disabled: this.shouldDisableUpload(this.props, this.state)
        }, "\uC5C5\uB85C\uB4DC"));
      }
    }
  }, {
    key: "renderForm",
    value: function renderForm() {
      var _this3 = this;

      if (this.props.upload.formExpanded) {
        var errorMessage = this.props.upload.error && this.props.upload.error.type === "QUOTA_EXCEEDED_UPLOAD" ? "This upload exceeds the file storage quota. Please speak to your system administrator." : null;
        return _react.default.createElement("form", {
          onSubmit: this.handleUpload.bind(this),
          className: (0, _aphrodite.css)(styles.uploadForm),
          encType: "multipart/form-data"
        }, _react.default.createElement("div", null, _react.default.createElement("div", {
          className: (0, _aphrodite.css)(styles.uploadLimit)
        }, _react.default.createElement("label", {
          htmlFor: "upload-form-file-input"
        }, _react.default.createElement(_ScreenReaderContent.default, null, "Select a file")), errorMessage && _react.default.createElement(_Alert.default, {
          variant: "error"
        }, errorMessage), _react.default.createElement("input", {
          className: (0, _aphrodite.css)(styles.uploadedData),
          type: "file",
          onChange: this.handleFileChange.bind(this),
          onClick: this.handleFileClick.bind(this),
          style: {
            width: "100%"
          }
        })), this.props.showAltTextForm && this.isImageSelected(this.state.file) && _react.default.createElement(_AltTextForm.default, {
          ref: function ref(_ref2) {
            return _this3._altText = _ref2;
          },
          altResolved: this.setAltResolved
        }), this.renderFolderSelect(), this.props.usageRightsRequired && _react.default.createElement(_UsageRightsForm.default, {
          ref: function ref(_ref3) {
            return _this3._usageRights = _ref3;
          }
        })), this.renderFormSubmit());
      }

      return null;
    }
  }, {
    key: "render",
    value: function render() {
      return _react.default.createElement("div", {
        className: (0, _aphrodite.css)(styles.container)
      }, this.uploadLink(), _react.default.createElement(_CSSTransitionGroup.default, {
        transitionName: {
          enter: (0, _aphrodite.css)(styles.slideDownEnter),
          enterActive: (0, _aphrodite.css)(styles.slideDownEnter, styles.slideDownEnterActive),
          leave: (0, _aphrodite.css)(styles.slideDownLeave),
          leaveActive: (0, _aphrodite.css)(styles.slideDownLeave, styles.slideDownLeaveActive)
        },
        transitionEnterTimeout: 500,
        transitionLeaveTimeout: 300
      }, this.renderForm()));
    }
  }]);
  UploadForm.displayName = "UploadForm";
  return UploadForm;
}(_react.Component);

UploadForm.propTypes = {
  upload: _propTypes.default.shape({
    loading: _propTypes.default.bool,
    folders: _propTypes.default.objectOf(_propTypes.default.shape({
      id: _propTypes.default.number,
      name: _propTypes.default.string,
      parentId: _propTypes.default.number
    })).isRequired,
    uploading: _propTypes.default.bool.isRequired,
    formExpanded: _propTypes.default.bool.isRequired,
    rootFolderId: _propTypes.default.number,
    folderTree: _propTypes.default.object.isRequired,
    error: _propTypes.default.shape({
      type: _propTypes.default.string
    })
  }).isRequired,
  toggleUploadForm: _propTypes.default.func.isRequired,
  fetchFolders: _propTypes.default.func.isRequired,
  startUpload: _propTypes.default.func.isRequired,
  usageRightsRequired: _propTypes.default.bool,
  messages: _propTypes.default.shape({
    expand: _propTypes.default.string.isRequired,
    expandScreenreader: _propTypes.default.string.isRequired,
    collapse: _propTypes.default.string.isRequired,
    collapseScreenreader: _propTypes.default.string.isRequired
  }).isRequired,
  showAltTextForm: _propTypes.default.bool.isRequired
};

var styles = _aphrodite.StyleSheet.create({
  slideDownEnter: {
    maxHeight: 0,
    overflowY: "hidden"
  },
  slideDownEnterActive: {
    maxHeight: "500px",
    transition: "max-height 500ms ease-in"
  },
  slideDownLeave: {
    maxHeight: "500px",
    overflowY: "hidden"
  },
  slideDownLeaveActive: {
    maxHeight: 0,
    transition: "max-height 300ms ease-in"
  },
  container: {
    marginTop: "10px"
  },
  uploadForm: {
    marginTop: "6px",
    lineHeight: 1.5,
    maxWidth: "100%"
  },
  uploadLimit: {
    fontSize: "11px",
    margin: "10px 0 1em",
    display: "block"
  },
  uploadButtonContainer: {
    marginTop: "0.5em"
  },
  uploadedData: {
    display: "block",
    marginBottom: "10px"
  },
  folderId: {
    marginBottom: "10px"
  },
  icon: {
    verticalAlign: "middle"
  }
});

exports.styles = styles;
var _default = UploadForm;
exports.default = _default;