client/components/pages/parts/search-results.js

"use strict";

require("core-js/modules/es.reflect.construct.js");
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/es.weak-map.js");
require("core-js/modules/web.dom-collections.iterator.js");
require("core-js/modules/es.object.get-own-property-descriptor.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
require("core-js/modules/es.array.find.js");
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/es.array.filter.js");
require("core-js/modules/es.array.concat.js");
require("core-js/modules/es.array.includes.js");
require("core-js/modules/es.array.map.js");
require("core-js/modules/es.function.name.js");
require("core-js/modules/es.array.join.js");
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _toLower2 = _interopRequireDefault(require("lodash/toLower"));
var _startCase3 = _interopRequireDefault(require("lodash/startCase"));
var _kebabCase3 = _interopRequireDefault(require("lodash/kebabCase"));
var _differenceBy3 = _interopRequireDefault(require("lodash/differenceBy"));
var bootstrap = _interopRequireWildcard(require("react-bootstrap"));
var _addToCollectionModal = _interopRequireDefault(require("./add-to-collection-modal"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireDefault(require("react"));
var _entity = require("../../../helpers/entity");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /*
                                                                                                                                                                                                                                                                                                                                           * Copyright (C) 2015  Ohm Patel
                                                                                                                                                                                                                                                                                                                                           *               2016  Sean Burke
                                                                                                                                                                                                                                                                                                                                           *
                                                                                                                                                                                                                                                                                                                                           * This program is free software; you can redistribute it and/or modify
                                                                                                                                                                                                                                                                                                                                           * it under the terms of the GNU General Public License as published by
                                                                                                                                                                                                                                                                                                                                           * the Free Software Foundation; either version 2 of the License, or
                                                                                                                                                                                                                                                                                                                                           * (at your option) any later version.
                                                                                                                                                                                                                                                                                                                                           *
                                                                                                                                                                                                                                                                                                                                           * This program 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 General Public License for more details.
                                                                                                                                                                                                                                                                                                                                           *
                                                                                                                                                                                                                                                                                                                                           * You should have received a copy of the GNU General Public License along
                                                                                                                                                                                                                                                                                                                                           * with this program; if not, write to the Free Software Foundation, Inc.,
                                                                                                                                                                                                                                                                                                                                           * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
                                                                                                                                                                                                                                                                                                                                           */
var Alert = bootstrap.Alert,
  Badge = bootstrap.Badge,
  Button = bootstrap.Button,
  ButtonGroup = bootstrap.ButtonGroup,
  Table = bootstrap.Table;

// Main entities have a BBID but some other indexed types
// have an ID field instead (collections, editors, areas)
function getId(entity) {
  var _entity$bbid;
  return (_entity$bbid = entity.bbid) !== null && _entity$bbid !== void 0 ? _entity$bbid : entity.id;
}

/**
 * Renders the document and displays the 'SearchResults' page.
 * @returns {ReactElement} a HTML document which displays the SearchResults.
 * @param {object} props - Properties passed to the component.
 */
var SearchResults = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2.default)(SearchResults, _React$Component);
  var _super = _createSuper(SearchResults);
  function SearchResults(props) {
    var _this;
    (0, _classCallCheck2.default)(this, SearchResults);
    _this = _super.call(this, props);
    _this.state = {
      message: {
        text: null,
        type: null
      },
      selected: [],
      showModal: false
    };
    _this.handleAddToCollection = _this.handleAddToCollection.bind((0, _assertThisInitialized2.default)(_this));
    _this.toggleRow = _this.toggleRow.bind((0, _assertThisInitialized2.default)(_this));
    _this.onCloseModal = _this.onCloseModal.bind((0, _assertThisInitialized2.default)(_this));
    _this.handleShowModal = _this.handleShowModal.bind((0, _assertThisInitialized2.default)(_this));
    _this.handleAlertDismiss = _this.handleAlertDismiss.bind((0, _assertThisInitialized2.default)(_this));
    _this.closeModalAndShowMessage = _this.closeModalAndShowMessage.bind((0, _assertThisInitialized2.default)(_this));
    _this.handleClearSelected = _this.handleClearSelected.bind((0, _assertThisInitialized2.default)(_this));
    return _this;
  }
  (0, _createClass2.default)(SearchResults, [{
    key: "onCloseModal",
    value: function onCloseModal() {
      this.setState({
        showModal: false
      });
    }
  }, {
    key: "handleShowModal",
    value: function handleShowModal() {
      if (this.props.user) {
        this.setState({
          showModal: true
        });
      } else {
        this.setState({
          message: {
            text: 'You need to be logged in',
            type: 'danger'
          }
        });
      }
    }
  }, {
    key: "closeModalAndShowMessage",
    value: function closeModalAndShowMessage(message) {
      this.setState({
        message: message,
        showModal: false
      });
    }
  }, {
    key: "handleAlertDismiss",
    value: function handleAlertDismiss() {
      this.setState({
        message: {}
      });
    }
  }, {
    key: "toggleRow",
    value: function toggleRow(entity) {
      // eslint-disable-next-line react/no-access-state-in-setstate
      var oldSelected = this.state.selected;
      var newSelected;
      if (oldSelected.find(function (selected) {
        return getId(selected) === getId(entity);
      })) {
        newSelected = oldSelected.filter(function (selected) {
          return getId(selected) !== getId(entity);
        });
      } else {
        newSelected = [].concat((0, _toConsumableArray2.default)(oldSelected), [entity]);
      }
      this.setState({
        selected: newSelected
      });
    }
  }, {
    key: "handleClearSelected",
    value: function handleClearSelected() {
      this.setState({
        selected: []
      });
    }
  }, {
    key: "handleAddToCollection",
    value: function handleAddToCollection() {
      var selectedEntities = this.state.selected;
      if (selectedEntities.length) {
        var areAllEntitiesOfSameType = selectedEntities.every(function (entity) {
          return entity.type === selectedEntities[0].type;
        });
        var entityTypes = ['Author', 'Edition', 'EditionGroup', 'Publisher', 'Series', 'Work'];
        if (areAllEntitiesOfSameType) {
          if (entityTypes.includes(selectedEntities[0].type)) {
            this.setState({
              message: {},
              showModal: true
            });
          } else {
            this.setState({
              message: {
                text: "".concat(selectedEntities[0].type, " cannot be added to a collection"),
                type: 'danger'
              }
            });
          }
        } else {
          this.setState({
            message: {
              text: 'Selected entities should be of same type',
              type: 'danger'
            }
          });
        }
      } else {
        this.setState({
          message: {
            text: 'Nothing Selected',
            type: 'danger'
          }
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this,
        _this$state$selected$;
      var noResults = !this.props.results || this.props.results.length === 0;
      var results = this.props.results.map(function (result) {
        var _result$authors;
        if (!result) {
          return null;
        }
        var id = getId(result);
        var name = result.defaultAlias ? result.defaultAlias.name : '(unnamed)';
        var aliases = !_this2.props.condensed && result.aliasSet && Array.isArray(result.aliasSet.aliases) && result.aliasSet.aliases;
        var secondaryAliases = !_this2.props.condensed && aliases && (0, _differenceBy3.default)(aliases, [result.defaultAlias], 'id').map(function (alias) {
          return alias.name;
        }).join(', ');
        var disambiguation = result.disambiguation ? /*#__PURE__*/_react.default.createElement("small", null, "(", result.disambiguation.comment, ")") : '';
        // No redirect link for Area entity results
        var link = result.type === 'Area' ? "//musicbrainz.org/area/".concat(id) : "/".concat((0, _kebabCase3.default)(result.type), "/").concat(id);

        /* eslint-disable react/jsx-no-bind */
        return /*#__PURE__*/_react.default.createElement("tr", {
          key: id
        }, !_this2.props.condensed && /*#__PURE__*/_react.default.createElement("td", null, _this2.props.user ? /*#__PURE__*/_react.default.createElement("input", {
          checked: _this2.state.selected.find(function (selected) {
            return getId(selected) === id;
          }),
          className: "checkboxes",
          type: "checkbox",
          onChange: function onChange() {
            return _this2.toggleRow(result);
          }
        }) : null, (0, _entity.genEntityIconHTMLElement)(result.type), (0, _startCase3.default)(result.type)), /*#__PURE__*/_react.default.createElement("td", null, /*#__PURE__*/_react.default.createElement("a", {
          href: link
        }, name, " ", disambiguation), (0, _toLower2.default)(result.type) === 'work' && Boolean((_result$authors = result.authors) === null || _result$authors === void 0 ? void 0 : _result$authors.length) && /*#__PURE__*/_react.default.createElement("span", {
          className: "small text-muted"
        }, " \u2014 ", /*#__PURE__*/_react.default.createElement("i", null, result.authors.join(', ')))), !_this2.props.condensed && /*#__PURE__*/_react.default.createElement("td", null, secondaryAliases));
      });
      var tableCssClasses = 'table table-striped';
      if (this.props.condensed) {
        tableCssClasses += ' table-condensed';
      }
      if (noResults) {
        return null;
      }
      return /*#__PURE__*/_react.default.createElement("div", null, this.props.user ? /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_addToCollectionModal.default, {
        bbids: this.state.selected.map(getId),
        closeModalAndShowMessage: this.closeModalAndShowMessage,
        entityType: (_this$state$selected$ = this.state.selected[0]) === null || _this$state$selected$ === void 0 ? void 0 : _this$state$selected$.type,
        handleCloseModal: this.onCloseModal,
        show: this.state.showModal,
        userId: this.props.user.id
      })) : null, !this.props.condensed && /*#__PURE__*/_react.default.createElement("h3", {
        className: "search-results-heading"
      }, "Search Results"), /*#__PURE__*/_react.default.createElement("hr", {
        className: "thin"
      }), /*#__PURE__*/_react.default.createElement(Table, {
        responsive: true,
        className: tableCssClasses
      }, !this.props.condensed && /*#__PURE__*/_react.default.createElement("thead", null, /*#__PURE__*/_react.default.createElement("tr", null, /*#__PURE__*/_react.default.createElement("th", {
        width: "25%"
      }, "Type"), /*#__PURE__*/_react.default.createElement("th", {
        width: "42%"
      }, "Name"), /*#__PURE__*/_react.default.createElement("th", {
        width: "33%"
      }, "Aliases"))), /*#__PURE__*/_react.default.createElement("tbody", null, results)), this.state.message.text ? /*#__PURE__*/_react.default.createElement(Alert, {
        className: "margin-top-1",
        variant: this.state.message.type,
        onDismiss: this.handleAlertDismiss
      }, this.state.message.text) : null, this.props.user ? /*#__PURE__*/_react.default.createElement(ButtonGroup, null, /*#__PURE__*/_react.default.createElement(Button, {
        disabled: !this.state.selected.length,
        type: "button",
        variant: "primary",
        onClick: this.handleAddToCollection
      }, (0, _entity.genEntityIconHTMLElement)('Collection'), "Add to Collection"), /*#__PURE__*/_react.default.createElement(Button, {
        disabled: !this.state.selected.length,
        type: "button",
        variant: "warning",
        onClick: this.handleClearSelected
      }, "Clear ", /*#__PURE__*/_react.default.createElement(Badge, {
        pill: true,
        variant: "light"
      }, this.state.selected.length), " selected")) : null);
    }
  }]);
  return SearchResults;
}(_react.default.Component);
SearchResults.displayName = 'SearchResults';
SearchResults.propTypes = {
  condensed: _propTypes.default.bool,
  results: _propTypes.default.array,
  user: _propTypes.default.object.isRequired
};
SearchResults.defaultProps = {
  condensed: false,
  results: null
};
var _default = SearchResults;
exports.default = _default;
//# sourceMappingURL=search-results.js.map