BookmarkButton.js 1.5 KB

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