BookmarkButton.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. const addedClassName = this.state.bookmarked ? 'active' : '';
  56. return (
  57. <button href="#" title="Bookmark" onClick={this.handleClick}
  58. className={`bookmark-link btn btn-default btn-circle btn-outline ${addedClassName}`}>
  59. <Icon name={iconName} />
  60. </button>
  61. );
  62. }
  63. }
  64. BookmarkButton.propTypes = {
  65. pageId: PropTypes.string,
  66. crowi: PropTypes.object.isRequired,
  67. };