BookmarkButton.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import React from 'react';
  2. import Icon from './Common/Icon'
  3. export default class BookmarkButton extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. this.state = {
  7. bookmarked: false,
  8. token: null,
  9. };
  10. this.handleClick = this.handleClick.bind(this);
  11. }
  12. componentWillMount() {
  13. // FIXME(property?)
  14. this.setState({
  15. token: $('#bookmark-button').data('csrftoken'),
  16. });
  17. }
  18. componentDidMount() {
  19. this.props.crowi.apiGet('/bookmarks.get', {page_id: this.props.pageId})
  20. .then(res => {
  21. if (res.bookmark) {
  22. this.markBookmarked();
  23. }
  24. });
  25. }
  26. handleClick(event) {
  27. event.preventDefault();
  28. const token = this.state.token;
  29. const pageId = this.props.pageId;
  30. if (!this.state.bookmarked) {
  31. this.props.crowi.apiPost('/bookmarks.add', {_csrf: token, page_id: pageId})
  32. .then(res => {
  33. this.markBookmarked();
  34. });
  35. } else {
  36. this.props.crowi.apiPost('/bookmarks.remove', {_csrf: token, page_id: pageId})
  37. .then(res => {
  38. this.markUnBookmarked();
  39. });
  40. }
  41. }
  42. markBookmarked() {
  43. this.setState({bookmarked: true});
  44. }
  45. markUnBookmarked() {
  46. this.setState({bookmarked: false});
  47. }
  48. render() {
  49. const iconName = this.state.bookmarked ? 'star' : 'star-o';
  50. return (
  51. <a href="#" title="Bookmark" className="bookmark-link" onClick={this.handleClick}>
  52. <Icon name={iconName} />
  53. </a>
  54. );
  55. }
  56. }
  57. BookmarkButton.propTypes = {
  58. pageId: React.PropTypes.string,
  59. crowi: React.PropTypes.object.isRequired,
  60. };