summaryrefslogtreecommitdiff
path: root/static/js/controllers/pagination_controller.js
blob: bfb1a48cdb08d89bf78ec3a1078e3e8534c961d2 (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
import { BaseController } from "./base_controller.js";

export class PaginationController extends BaseController {
  constructor(host, context, path, replies_controller) {
    super();
    this.replies_controller = replies_controller;
    this.endpoint = `${host}${context}?path=${path}`;
    this.comments_node = document.getElementById("comments-thread");
  }

  populatePageAnchors() {
    const pagination_widget = document.querySelector(".pagination");
    var anchors = pagination_widget.querySelectorAll('a');

    for (let anchor of anchors) {
      var page = /\d/.exec(anchor.id)[0];
      anchor.setAttribute("href", `${this.endpoint}&page=${page}`);
    }

    this.listenForPageChange(anchors);
  }

  listenForPageChange(page_selectors) {
    for (let anchor of page_selectors) {
      anchor.addEventListener("click", this.changeCommentsPage.bind(this))
    }
  }

  changeCommentsPage(event) {
    event.preventDefault();

    fetch(event.target.getAttribute("href"))
      .then((response) => {
        return response.text();
      })
      .then((data) => {
        this.loadComments(this.htmlFromResponse(data));
      });
  }

  loadComments(body) {
    const previous_comments = document.getElementById("comment-section");
    const comments = body?.getElementById("comment-section");

    if(comments) {
      previous_comments.remove();
      this.comments_node.appendChild(comments);
      this.replies_controller.init();
      this.populatePageAnchors();
    }
  }
}