BookmarkButton.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. $.post('/_api/bookmarks.add', {_csrf: token, page_id: pageId}, (res) => {
  32. if (res.ok && res.bookmark) {
  33. this.markBookmarked();
  34. }
  35. });
  36. } else {
  37. $.post('/_api/bookmarks.remove', {_csrf: token, page_id: pageId}, (res) => {
  38. if (res.ok) {
  39. this.markUnBookmarked();
  40. }
  41. });
  42. }
  43. }
  44. markBookmarked() {
  45. this.setState({bookmarked: true});
  46. }
  47. markUnBookmarked() {
  48. this.setState({bookmarked: false});
  49. }
  50. render() {
  51. const iconName = this.state.bookmarked ? 'star' : 'star-o';
  52. return (
  53. <a href="#" title="Bookmark" className="bookmark-link" onClick={this.handleClick}>
  54. <Icon name={iconName} />
  55. </a>
  56. );
  57. }
  58. }
  59. BookmarkButton.propTypes = {
  60. pageId: React.PropTypes.string,
  61. crowi: React.PropTypes.object.isRequired,
  62. };