BookmarkButton.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import Icon from './Common/Icon'
  4. export default class BookmarkButton extends React.Component {
  5. constructor(props) {
  6. super(props);
  7. this.state = {
  8. bookmarked: false,
  9. };
  10. this.handleClick = this.handleClick.bind(this);
  11. }
  12. componentDidMount() {
  13. // if guest user
  14. if (!this.isUserLoggedIn()) {
  15. // do nothing
  16. return;
  17. }
  18. this.props.crowi.apiGet('/bookmarks.get', {page_id: this.props.pageId})
  19. .then(res => {
  20. if (res.bookmark) {
  21. this.markBookmarked();
  22. }
  23. });
  24. }
  25. handleClick(event) {
  26. event.preventDefault();
  27. const pageId = this.props.pageId;
  28. if (!this.state.bookmarked) {
  29. this.props.crowi.apiPost('/bookmarks.add', {page_id: pageId})
  30. .then(res => {
  31. this.markBookmarked();
  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 !== '';
  48. }
  49. render() {
  50. // if guest user
  51. if (!this.isUserLoggedIn()) {
  52. return <div></div>;
  53. }
  54. const iconName = this.state.bookmarked ? 'star' : 'star-o';
  55. return (
  56. <a href="#" title="Bookmark" className="bookmark-link" onClick={this.handleClick}>
  57. <Icon name={iconName} />
  58. </a>
  59. );
  60. }
  61. }
  62. BookmarkButton.propTypes = {
  63. pageId: PropTypes.string,
  64. crowi: PropTypes.object.isRequired,
  65. };