summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/signin_tabs_memoizer.js
blob: d811d1cd53abf3d6763d4cd58d708bfa4db25a4c (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
/* eslint no-param-reassign: ["error", { "props": false }]*/
/* eslint no-new: "off" */
((global) => {
  /**
   * Memorize the last selected tab after reloading a page.
   * Does that setting the current selected tab in the localStorage
   */
  class ActiveTabMemoizer {
    constructor({ currentTabKey = 'current_signin_tab', tabSelector = 'ul.nav-tabs' } = {}) {
      this.currentTabKey = currentTabKey;
      this.tabSelector = tabSelector;
      this.bootstrap();
    }

    bootstrap() {
      const tabs = document.querySelectorAll(this.tabSelector);
      if (tabs.length > 0) {
        tabs[0].addEventListener('click', (e) => {
          if (e.target && e.target.nodeName === 'A') {
            const anchorName = e.target.getAttribute('href');
            this.saveData(anchorName);
          }
        });
      }

      this.showTab();
    }

    showTab() {
      const anchorName = this.readData();
      if (anchorName) {
        const tab = document.querySelector(`${this.tabSelector} a[href="${anchorName}"]`);
        if (tab) {
          tab.click();
        }
      }
    }

    saveData(val) {
      localStorage.setItem(this.currentTabKey, val);
    }

    readData() {
      return localStorage.getItem(this.currentTabKey);
    }
  }

  global.ActiveTabMemoizer = ActiveTabMemoizer;
})(window);