BookmarkButton.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. export default class BookmarkButton extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. this.state = {
  7. bookmarked: false,
  8. };
  9. this.handleClick = this.handleClick.bind(this);
  10. }
  11. componentDidMount() {
  12. // if guest user
  13. if (!this.isUserLoggedIn()) {
  14. // do nothing
  15. return;
  16. }
  17. this.props.crowi.apiGet('/bookmarks.get', {page_id: this.props.pageId})
  18. .then(res => {
  19. if (res.bookmark) {
  20. this.markBookmarked();
  21. }
  22. });
  23. }
  24. handleClick(event) {
  25. event.preventDefault();
  26. const pageId = this.props.pageId;
  27. if (!this.state.bookmarked) {
  28. this.props.crowi.apiPost('/bookmarks.add', {page_id: pageId})
  29. .then(res => {
  30. this.markBookmarked();
  31. });
  32. } else {
  33. this.props.crowi.apiPost('/bookmarks.remove', {page_id: pageId})
  34. .then(res => {
  35. this.markUnBookmarked();
  36. });
  37. }
  38. }
  39. markBookmarked() {
  40. this.setState({bookmarked: true});
  41. }
  42. markUnBookmarked() {
  43. this.setState({bookmarked: false});
  44. }
  45. isUserLoggedIn() {
  46. return this.props.crowi.me !== '';
  47. }
  48. render() {
  49. // if guest user
  50. if (!this.isUserLoggedIn()) {
  51. return <div></div>;
  52. }
  53. const btnSizeClassName = this.props.size ? `btn-${this.props.size}` : 'btn-md';
  54. const addedClassNames = [
  55. this.state.bookmarked ? 'active' : '',
  56. btnSizeClassName,
  57. ];
  58. const addedClassName = addedClassNames.join(' ');
  59. return (
  60. <button href="#" title="Bookmark" onClick={this.handleClick}
  61. className={`bookmark-link btn btn-default btn-circle btn-outline ${addedClassName}`}>
  62. <i className="icon-star"></i>
  63. </button>
  64. );
  65. }
  66. }
  67. BookmarkButton.propTypes = {
  68. pageId: PropTypes.string,
  69. crowi: PropTypes.object.isRequired,
  70. size: PropTypes.string,
  71. };