BookmarkButton.jsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { UncontrolledTooltip } from 'reactstrap';
  4. import { withTranslation } from 'react-i18next';
  5. import { withUnstatedContainers } from './UnstatedUtils';
  6. import { toastError } from '~/client/util/apiNotification';
  7. import { apiv3Put } from '~/client/util/apiv3-client';
  8. import AppContainer from '~/client/services/AppContainer';
  9. class BookmarkButton extends React.Component {
  10. constructor(props) {
  11. super(props);
  12. this.handleClick = this.handleClick.bind(this);
  13. }
  14. async handleClick() {
  15. const {
  16. appContainer, pageId, isBookmarked, onChangeInvoked,
  17. } = this.props;
  18. const { isGuestUser } = appContainer;
  19. if (isGuestUser) {
  20. return;
  21. }
  22. try {
  23. const bool = !isBookmarked;
  24. await apiv3Put('/bookmarks', { pageId, bool });
  25. if (onChangeInvoked != null) {
  26. onChangeInvoked();
  27. }
  28. }
  29. catch (err) {
  30. toastError(err);
  31. }
  32. }
  33. render() {
  34. const {
  35. appContainer, t, isBookmarked, sumOfBookmarks,
  36. } = this.props;
  37. const { isGuestUser } = appContainer;
  38. return (
  39. <div>
  40. <button
  41. type="button"
  42. id="bookmark-button"
  43. onClick={this.handleClick}
  44. className={`btn btn-bookmark border-0
  45. ${`btn-${this.props.size}`} ${isBookmarked ? 'active' : ''} ${isGuestUser ? 'disabled' : ''}`}
  46. >
  47. <i className="icon-star mr-3"></i>
  48. {sumOfBookmarks && (
  49. <span className="total-bookmarks">
  50. {sumOfBookmarks}
  51. </span>
  52. )}
  53. </button>
  54. {isGuestUser && (
  55. <UncontrolledTooltip placement="top" target="bookmark-button" fade={false}>
  56. {t('Not available for guest')}
  57. </UncontrolledTooltip>
  58. )}
  59. </div>
  60. );
  61. }
  62. }
  63. /**
  64. * Wrapper component for using unstated
  65. */
  66. const BookmarkButtonWrapper = withUnstatedContainers(BookmarkButton, [AppContainer]);
  67. BookmarkButton.propTypes = {
  68. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  69. pageId: PropTypes.string.isRequired,
  70. isBookmarked: PropTypes.bool.isRequired,
  71. sumOfBookmarks: PropTypes.number,
  72. onChangeInvoked: PropTypes.func,
  73. t: PropTypes.func.isRequired,
  74. size: PropTypes.string,
  75. };
  76. BookmarkButton.defaultProps = {
  77. size: 'md',
  78. };
  79. export default withTranslation()(BookmarkButtonWrapper);