BookmarkButton.jsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. }
  33. else {
  34. this.props.crowi.apiPost('/bookmarks.remove', { page_id: pageId })
  35. .then((res) => {
  36. this.markUnBookmarked();
  37. });
  38. }
  39. }
  40. markBookmarked() {
  41. this.setState({ bookmarked: true });
  42. }
  43. markUnBookmarked() {
  44. this.setState({ bookmarked: false });
  45. }
  46. isUserLoggedIn() {
  47. return this.props.crowi.me != null;
  48. }
  49. render() {
  50. // if guest user
  51. if (!this.isUserLoggedIn()) {
  52. return <div></div>;
  53. }
  54. const btnSizeClassName = this.props.size ? `btn-${this.props.size}` : 'btn-md';
  55. const addedClassNames = [
  56. this.state.bookmarked ? 'active' : '',
  57. btnSizeClassName,
  58. ];
  59. const addedClassName = addedClassNames.join(' ');
  60. return (
  61. <button
  62. type="button"
  63. href="#"
  64. title="Bookmark"
  65. onClick={this.handleClick}
  66. className={`btn-bookmark btn btn-default btn-circle btn-outline ${addedClassName}`}
  67. >
  68. <i className="icon-star"></i>
  69. </button>
  70. );
  71. }
  72. }
  73. BookmarkButton.propTypes = {
  74. pageId: PropTypes.string,
  75. crowi: PropTypes.object.isRequired,
  76. size: PropTypes.string,
  77. };