summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pager.js
blob: 843f78c5fa9729c9f20395952ed477e29d8a8643 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import $ from 'jquery';
import { getParameterByName } from '~/lib/utils/common_utils';
import axios from './lib/utils/axios_utils';
import { removeParams } from './lib/utils/url_utility';

const ENDLESS_SCROLL_BOTTOM_PX = 400;
const ENDLESS_SCROLL_FIRE_DELAY_MS = 1000;

export default {
  init(
    limit = 0,
    preload = false,
    disable = false,
    prepareData = $.noop,
    callback = $.noop,
    container = '',
  ) {
    this.url = $('.content_list').data('href') || removeParams(['limit', 'offset']);
    this.limit = limit;
    this.offset = parseInt(getParameterByName('offset'), 10) || this.limit;
    this.disable = disable;
    this.prepareData = prepareData;
    this.callback = callback;
    this.container = container;
    this.loading = $(`${container} .loading`).first();
    if (preload) {
      this.offset = 0;
      this.getOld();
    }
    this.initLoadMore();
  },

  getOld() {
    this.loading.show();
    axios
      .get(this.url, {
        params: {
          limit: this.limit,
          offset: this.offset,
        },
      })
      .then(({ data }) => {
        this.append(data.count, this.prepareData(data.html));
        this.callback();

        // keep loading until we've filled the viewport height
        if (!this.disable && !this.isScrollable()) {
          this.getOld();
        } else {
          this.loading.hide();
        }
      })
      .catch(() => this.loading.hide());
  },

  append(count, html) {
    $('.content_list').append(html);
    if (count > 0) {
      this.offset += count;
    } else {
      this.disable = true;
    }
  },

  isScrollable() {
    const $w = $(window);
    return $(document).height() > $w.height() + $w.scrollTop() + ENDLESS_SCROLL_BOTTOM_PX;
  },

  initLoadMore() {
    $(document).off('scroll');
    $(document).endlessScroll({
      bottomPixels: ENDLESS_SCROLL_BOTTOM_PX,
      fireDelay: ENDLESS_SCROLL_FIRE_DELAY_MS,
      fireOnce: true,
      ceaseFire: () => this.disable === true,
      callback: () => {
        if (!this.loading.is(':visible')) {
          this.loading.show();
          this.getOld();
        }
      },
    });
  },
};