feed.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import $ from 'jquery';
  2. import { config } from 'grav-config';
  3. import request from '../utils/request';
  4. const URI = `${config.base_url_relative}/ajax.json/task${config.param_sep}getnewsfeed`;
  5. class Feed {
  6. constructor() {
  7. this.data = null;
  8. }
  9. fetch(refresh = false, callback = function() {}) {
  10. request(URI, {
  11. method: 'post',
  12. body: { refresh }
  13. }, (response) => {
  14. this.data = response;
  15. callback(response);
  16. });
  17. }
  18. refresh(refresh = false) {
  19. const feed = $('#news-feed .widget-content');
  20. if (!feed.length) { return; }
  21. let loader = feed.find('.widget-loader');
  22. loader.find('div').remove();
  23. loader.find('.fa-warning').removeClass('fa-warning').addClass('fa-refresh fa-spin');
  24. loader.show();
  25. feed.find('> ul').hide();
  26. if (!this.data || this.data.error || refresh) {
  27. this.fetch(refresh, this.updateContent.bind(this));
  28. } else {
  29. this.updateContent();
  30. }
  31. }
  32. updateContent() {
  33. const feed = $('#news-feed .widget-content');
  34. if (!feed.length) { return; }
  35. let loader = feed.find('.widget-loader').hide();
  36. let content = feed.find('> ul').empty().show();
  37. if (this.data.error || this.data.status === 'error') {
  38. loader.show().find('div').remove();
  39. loader.find('.fa-refresh').removeClass('fa-refresh fa-spin').addClass('fa-warning');
  40. loader.append(`<div>${this.data.error ? this.data.error.message : this.data.message || 'Unable to download news feed'}</div>`);
  41. return;
  42. }
  43. if (this.data && this.data.feed_data) {
  44. this.data.feed_data.forEach((data) => {
  45. content.append(data);
  46. });
  47. }
  48. }
  49. }
  50. let feed = new Feed();
  51. $(document).ready(() => feed.refresh());
  52. $(document).on('click', '[data-refresh="feed"]', (event) => {
  53. event.preventDefault();
  54. feed.refresh(true);
  55. });
  56. export default feed;