client/helpers/entity.js

"use strict";

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.ENTITY_TYPE_ICONS = exports.ENTITY_TYPES = void 0;
exports.addAuthorsDataToWorks = addAuthorsDataToWorks;
exports.areaToOption = areaToOption;
exports.authorCreditToString = authorCreditToString;
exports.deletedEntityMessage = void 0;
exports.entityToOption = entityToOption;
exports.extractAttribute = extractAttribute;
exports.filterOutRelationshipTypeById = filterOutRelationshipTypeById;
exports.genEntityIconHTMLElement = genEntityIconHTMLElement;
exports.getAuthorCreditNames = getAuthorCreditNames;
exports.getEditionFormat = getEditionFormat;
exports.getEditionPublishers = getEditionPublishers;
exports.getEditionReleaseDate = getEditionReleaseDate;
exports.getEntityDisambiguation = getEntityDisambiguation;
exports.getEntityLabel = getEntityLabel;
exports.getEntitySecondaryAliases = getEntitySecondaryAliases;
exports.getEntityUrl = getEntityUrl;
exports.getISBNOfEdition = getISBNOfEdition;
exports.getLanguageAttribute = getLanguageAttribute;
exports.getRelationshipSourceByTypeId = getRelationshipSourceByTypeId;
exports.getRelationshipTargetBBIDByTypeId = getRelationshipTargetBBIDByTypeId;
exports.getRelationshipTargetByTypeId = getRelationshipTargetByTypeId;
exports.getSortNameOfDefaultAlias = getSortNameOfDefaultAlias;
exports.getTypeAttribute = getTypeAttribute;
exports.transformISODateForDisplay = transformISODateForDisplay;
exports.transformISODateForSelect = transformISODateForSelect;
require("core-js/modules/es.array.join.js");
require("core-js/modules/es.array.map.js");
require("core-js/modules/es.function.name.js");
require("core-js/modules/es.array.slice.js");
require("core-js/modules/es.regexp.exec.js");
require("core-js/modules/es.string.split.js");
require("core-js/modules/es.array.concat.js");
require("core-js/modules/es.array.filter.js");
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/es.array.find.js");
var _upperFirst2 = _interopRequireDefault(require("lodash/upperFirst"));
var _kebabCase3 = _interopRequireDefault(require("lodash/kebabCase"));
var _isNil3 = _interopRequireDefault(require("lodash/isNil"));
var _get3 = _interopRequireDefault(require("lodash/get"));
var React = _interopRequireWildcard(require("react"));
var _reactFontawesome = require("@fortawesome/react-fontawesome");
var _freeSolidSvgIcons = require("@fortawesome/free-solid-svg-icons");
var _dateFns = require("date-fns");
var _utils = require("./utils");
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; }
/*
 * Copyright (C) 2016  Daniel Hsing
 * 				 2019  Akhilesh Kumar (@akhilesh26)
 *
 * 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.
 */

// eslint-disable-next-line import/named

function extractAttribute(attr, path) {
  if (attr) {
    if (path) {
      return (0, _get3.default)(attr, path, '?');
    }
    return attr;
  }
  return '?';
}
function getLanguageAttribute(entity) {
  var languages = entity.languageSet && entity.languageSet.languages ? entity.languageSet.languages.map(function (language) {
    return language.name;
  }).join(', ') : '?';
  return {
    data: languages,
    title: 'Languages'
  };
}
function getTypeAttribute(entityType) {
  return {
    data: extractAttribute(entityType, 'label'),
    title: 'Type'
  };
}

/**
 * Transforms an extended ISO 8601-2004 string to a more human-firendly result
 * @function transformISODateForDisplay
 * @param {string} ISODateString - an extended ISO date string (±YYYYYY-MM-DD)
 * @returns {string} A date string with less padding zeros
 */
function transformISODateForDisplay(ISODateString) {
  if ((0, _isNil3.default)(ISODateString)) {
    return ISODateString;
  }
  var dateStringWithoutSign = ISODateString.slice(1);
  var parts = dateStringWithoutSign.split('-');
  var formatting;
  switch (parts.length) {
    case 1:
      formatting = 'uuuu';
      break;
    case 2:
      formatting = 'uuuu-MM';
      break;
    case 3:
      formatting = 'uuuu-MM-dd';
      break;
    default:
      return ISODateString;
  }
  var parsedDate = (0, _dateFns.parseISO)(ISODateString, {
    additionalDigits: 2
  });
  if (!(0, _dateFns.isValid)(parsedDate)) {
    return ISODateString;
  }
  return (0, _dateFns.format)(parsedDate, formatting);
}

/**
 * Transforms an extended ISO 8601-2004 date string to an option fit for react-select
 * @function transformISODateForSelect
 * @param {string|object} dateValue - an extended ISO date string (±YYYYYY-MM-DD) or date object {day,month,year}
 * @returns {object} - A {label,value} object for react-select option
 */
function transformISODateForSelect(dateValue) {
  var dateString = dateValue;
  if (typeof dateValue !== 'string') {
    dateString = (0, _utils.dateObjectToISOString)(dateValue);
  }
  return {
    label: transformISODateForDisplay(dateString),
    value: dateString
  };
}

/**
 * Determines whether an entity provided to the EntitySearch component is an
 * Area, using the present attributes.
 *
 * @param {Object} entity the entity to test
 * @returns {boolean} true if the entity looks like an Area
 */
function isArea(entity) {
  if (entity.type === 'Area') {
    return true;
  }
  return Boolean(entity.gid);
}

/**
 * Transforms an Area entity to a react-select component option
 * @param {object} area - The Area entity to transfrom
 * @returns {object} option - A react-select option
 */
function areaToOption(area) {
  if (!area) {
    return null;
  }
  var id = area.id;
  return {
    disambiguation: area.comment,
    id: id,
    text: area.name,
    type: 'area'
    // value: id
  };
}

/**
 * Transforms an entity to a react-select component option
 * @param {object} entity - The entity to transfrom
 * @returns {object} option - A react-select option
 */
function entityToOption(entity) {
  if ((0, _isNil3.default)(entity)) {
    return null;
  }
  if (isArea(entity)) {
    return areaToOption(entity);
  }
  return {
    disambiguation: entity.disambiguation ? entity.disambiguation.comment : null,
    id: entity.bbid,
    text: entity.defaultAlias ? entity.defaultAlias.name : '(unnamed)',
    type: entity.type
  };
}
function getEntityLabel(entity) {
  var returnHTML = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  if (entity.defaultAlias) {
    return "".concat(entity.defaultAlias.name);
  }

  // Deleted entities
  if (!entity.dataId) {
    var deletedEntityName = "Deleted ".concat(entity.type, " ").concat(entity.bbid);
    if (entity.parentAlias) {
      deletedEntityName = entity.parentAlias.name;
    }
    if (returnHTML) {
      return /*#__PURE__*/React.createElement("span", {
        className: "deleted"
      }, /*#__PURE__*/React.createElement("span", {
        className: "text-muted",
        title: "This ".concat(entity.type, " was deleted")
      }, deletedEntityName));
    }
    return "".concat(deletedEntityName);
  }
  if (returnHTML) {
    return /*#__PURE__*/React.createElement("span", {
      title: "Unnamed ".concat(entity.type, " ").concat(entity.bbid)
    }, "(unnamed)");
  }
  return 'Unnamed';
}
function getEditionReleaseDate(edition) {
  var hasReleaseEvents = edition.releaseEventSet && edition.releaseEventSet.releaseEvents && edition.releaseEventSet.releaseEvents.length;
  if (hasReleaseEvents) {
    return transformISODateForDisplay(edition.releaseEventSet.releaseEvents[0].date);
  }
  return '?';
}
function getAuthorCreditNames(edition) {
  if (edition.authorCreditId === null) {
    return [];
  }
  return edition.authorCredit.names;
}
function getEditionPublishers(edition) {
  var hasPublishers = edition.publisherSet && edition.publisherSet.publishers.length > 0;
  if (hasPublishers) {
    return edition.publisherSet.publishers.map(function (publisher, index) {
      return /*#__PURE__*/React.createElement("span", {
        key: publisher.bbid
      }, /*#__PURE__*/React.createElement("a", {
        href: "/publisher/".concat(publisher.bbid)
      }, (0, _get3.default)(publisher, 'defaultAlias.name', publisher.bbid)), index < edition.publisherSet.publishers.length - 1 ? ', ' : '');
    });
  }
  return '?';
}
function authorCreditToString(authorCredit) {
  if (authorCredit) {
    var names = authorCredit.names;
    return names.map(function (acName) {
      return "".concat(acName.name).concat(acName.joinPhrase);
    });
  }
  return null;
}
function getEntityDisambiguation(entity) {
  var _entity$disambiguatio;
  if ((_entity$disambiguatio = entity.disambiguation) !== null && _entity$disambiguatio !== void 0 && _entity$disambiguatio.comment) {
    return /*#__PURE__*/React.createElement("small", null, " (".concat(entity.disambiguation.comment, ")"));
  } else if (entity.disambiguation) {
    return /*#__PURE__*/React.createElement("small", null, " (".concat(entity.disambiguation, ")"), " ");
  }
  return null;
}
function getEntitySecondaryAliases(entity) {
  if (entity.aliasSet && Array.isArray(entity.aliasSet.aliases) && entity.aliasSet.aliases.length > 1) {
    var aliases = entity.aliasSet.aliases.filter(function (item) {
      return item.id !== entity.defaultAlias.id;
    }).map(function (item) {
      return /*#__PURE__*/React.createElement("li", {
        key: item.id
      }, item.name);
    });
    return /*#__PURE__*/React.createElement("ul", {
      className: "inline-aliases"
    }, aliases);
  }
  return null;
}
function getEntityUrl(entity) {
  var entityType = (0, _kebabCase3.default)(entity.type);
  var entityId = entity.bbid;
  return "/".concat(entityType, "/").concat(entityId);
}
var ENTITY_TYPE_ICONS = {
  Area: _freeSolidSvgIcons.faGlobe,
  Author: _freeSolidSvgIcons.faUser,
  Book: _freeSolidSvgIcons.faMagicWandSparkles,
  Collection: _freeSolidSvgIcons.faGripVertical,
  Edition: _freeSolidSvgIcons.faBook,
  EditionGroup: _freeSolidSvgIcons.faWindowRestore,
  Editor: _freeSolidSvgIcons.faUserCircle,
  Publisher: _freeSolidSvgIcons.faUniversity,
  Series: _freeSolidSvgIcons.faLayerGroup,
  Work: _freeSolidSvgIcons.faPenNib
};
exports.ENTITY_TYPE_ICONS = ENTITY_TYPE_ICONS;
var ENTITY_TYPES = ['Author', 'Work', 'Series', 'Edition', 'EditionGroup', 'Publisher'];
exports.ENTITY_TYPES = ENTITY_TYPES;
function genEntityIconHTMLElement(entityType) {
  var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '1x';
  var margin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  var correctCaseEntityType = (0, _upperFirst2.default)(entityType);
  if (!ENTITY_TYPE_ICONS[correctCaseEntityType]) {
    return null;
  }
  return /*#__PURE__*/React.createElement(_reactFontawesome.FontAwesomeIcon, {
    className: margin ? 'margin-right-0-3' : '',
    icon: ENTITY_TYPE_ICONS[correctCaseEntityType],
    size: size,
    title: correctCaseEntityType
  });
}
function getSortNameOfDefaultAlias(entity) {
  return entity.defaultAlias ? entity.defaultAlias.sortName : '?';
}
function getISBNOfEdition(entity) {
  if (entity.identifierSet && entity.identifierSet.identifiers) {
    var identifiers = entity.identifierSet.identifiers;
    return identifiers.find(function (identifier) {
      return identifier.type.label === 'ISBN-13' || identifier.type.label === 'ISBN-10';
    });
  }
  return null;
}
function getEditionFormat(entity) {
  return entity.editionFormat && entity.editionFormat.label || '?';
}

/**
 * Remove the all relationships which are belongs to given relationshipTypeId.
 *
 * @param {object} entity - Entity with all relationships
 * @param {number} relationshipTypeId - typeId of spacific relationshipType
 * @returns {array} retrun the all relationships after removing the relatioships for given relationshipTypeId
 */
function filterOutRelationshipTypeById(entity, relationshipTypeId) {
  return Array.isArray(entity.relationships) && entity.relationships.filter(function (relation) {
    return relation.typeId !== relationshipTypeId;
  }) || [];
}

/**
 * Get an array of all targets from relationships of an entity belongs to given relationshipTypeId
 *
 * @param {object} entity - an entity with all relationships
 * @param {number} relationshipTypeId - typeId of spacific relationshipType
 * @returns {array} Return array of all the targets belongs to entity relationships for given relationshipTypeId
 */
function getRelationshipTargetByTypeId(entity, relationshipTypeId) {
  var targets = [];
  if (Array.isArray(entity.relationships)) {
    targets = entity.relationships.filter(function (relation) {
      return relation.typeId === relationshipTypeId;
    }).map(function (relation) {
      var target = relation.target;
      return target;
    });
  }
  return targets;
}

/**
 * Get an array of works contained in an edition, along with the authorAlias of those works
 *
 * @param {object} authorsData - an object which contains the authorAlias and authorBBID with workBBIDs as keys
 * @param {array} works - the array containing all the works in an edition
 * @returns {array} - return the works array after adding authorsData to each work in the array
 */
function addAuthorsDataToWorks(authorsData, works) {
  works.map(function (work) {
    if (authorsData[work.bbid]) {
      work.authorsData = authorsData[work.bbid];
    } else {
      work.authorsData = [];
    }
    return work;
  });
  return works;
}

/**
 * Get an array of all target BBIDs from relationships of an entity belongs to given relationshipTypeId
 *
 * @param {object} entity - an entity with all relationships
 * @param {number} relationshipTypeId - typeId of spacific relationshipType
 * @returns {array} Return array of all the targetBBIDs belongs to entity relationships for given relationshipTypeId
 */
function getRelationshipTargetBBIDByTypeId(entity, relationshipTypeId) {
  var targets = [];
  if (Array.isArray(entity.relationships)) {
    targets = entity.relationships.filter(function (relation) {
      return relation.typeId === relationshipTypeId;
    }).map(function (relation) {
      var target = relation.target;
      return target.bbid;
    });
  }
  return targets;
}

/**
 * Get an array of all sources from relationships of an entity belongs to given relationshipTypeId
 *
 * @param {object} entity - main entity
 * @param {number} relationshipTypeId - typeId of spacific relationshipType
 * @returns {array} Return array of all the sources belongs to entity relationships for given relationshipTypeId
 */
function getRelationshipSourceByTypeId(entity, relationshipTypeId) {
  var sources = [];
  if (Array.isArray(entity.relationships)) {
    sources = entity.relationships.filter(function (relation) {
      return relation.typeId === relationshipTypeId;
    }).map(function (relation) {
      var source = relation.source;
      return source;
    });
  }
  return sources;
}
var deletedEntityMessage = /*#__PURE__*/React.createElement("p", null, "This entity has been deleted by an editor. This is most likely because it was added accidentally or incorrectly.", /*#__PURE__*/React.createElement("br", null), "The edit history has been preserved, and you can see the revisions by clicking the history button below.", /*#__PURE__*/React.createElement("br", null), "If you\u2019re sure this entity should still exist, you will be able to restore it to a previous revision in a future version of BookBrainz, but that\u2019s not quite ready yet.");
exports.deletedEntityMessage = deletedEntityMessage;
//# sourceMappingURL=entity.js.map