feed.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. content.append(this.data.feed_data);
  45. }
  46. }
  47. }
  48. let feed = new Feed();
  49. $(document).ready(() => feed.refresh());
  50. $(document).on('click', '[data-refresh="feed"]', (event) => {
  51. event.preventDefault();
  52. feed.refresh(true);
  53. });
  54. export default feed;