aboutsummaryrefslogtreecommitdiff
path: root/static/js/pager.ts
blob: 88e9f833859f818fa3113b0fdad0188f1777b09e (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
(function () {
  const url = self.location.href.split("#")[0];
  let settings = { pager: {} };

  self.addEventListener("DOMContentLoaded", function () {
    if (history.scrollRestoration) history.scrollRestoration = "manual";
    if (localStorage["settings"]) {
      settings = JSON.parse(localStorage["settings"]);
    }
    if (self.location.hash.length > 0) {
      settings["pager"][url] = self.pageYOffset;
      localStorage["settings"] = JSON.stringify(settings);
      document.getElementById(location.hash.slice(1)).scrollIntoView();
      self.addEventListener("load", function () {
        document.getElementById(location.hash.slice(1)).scrollIntoView();
      });
      return;
    }
    if (settings["pager"][url] > 0) {
      self.scrollTo(0, settings["pager"][url]);
      return;
    }
    settings["pager"][url] = self.pageYOffset;
    localStorage["settings"] = JSON.stringify(settings);
  });

  self.addEventListener("scroll", function () {
    const currentPosition = self.pageYOffset;
    settings["pager"][url] = currentPosition;
    localStorage["settings"] = JSON.stringify(settings);
    if (self.location.hash.length === 0) {
      history.replaceState(
        {},
        document.title,
        window.location.href.split("#")[0],
      );
    }
  });

  self.addEventListener("DOMContentLoaded", function () {
    const up = document.getElementById("top");
    const back = document.getElementById("back");

    self.addEventListener("click", function (event) {
      if (document.body.contains(up) && up.contains(event.target)) {
        event.preventDefault();
        window.scrollTo(0, 0);
      }
      if (document.body.contains(back) && back.contains(event.target)) {
        if (history.length < 2) return;
        event.preventDefault();
        history.go(-1);
      }
    });
  });
})();