All files / app/assets/javascripts/pages/sessions/new signin_tabs_memoizer.js

100% Statements 28/28
90.47% Branches 19/21
100% Functions 6/6
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  12x 12x 12x   12x 1x     12x       14x 14x   9x 9x 6x 6x 6x         14x       14x 14x 3x 3x 2x   1x 1x 1x             11x   10x       18x   17x      
import AccessorUtilities from '~/lib/utils/accessor';
import { GlTabsBehavior } from '~/tabs';
 
/**
 * Memorize the last selected tab after reloading a page.
 * Does that setting the current selected tab in the localStorage
 */
export default class SigninTabsMemoizer {
  constructor({ currentTabKey = 'current_signin_tab', tabSelector = '#js-signin-tabs' } = {}) {
    this.currentTabKey = currentTabKey;
    this.tabSelector = tabSelector;
    this.isLocalStorageAvailable = AccessorUtilities.canUseLocalStorage();
    // sets selected tab if given as hash tag
    if (window.location.hash) {
      this.saveData(window.location.hash);
    }
 
    this.bootstrap();
  }
 
  bootstrap() {
    const tabNav = document.querySelector(this.tabSelector);
    if (tabNav) {
      // eslint-disable-next-line no-new
      new GlTabsBehavior(tabNav);
      tabNav.addEventListener('click', (e) => {
        Eif (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();
      } else {
        const firstTab = document.querySelector(`${this.tabSelector} a`);
        Eif (firstTab) {
          firstTab.click();
        }
      }
    }
  }
 
  saveData(val) {
    if (!this.isLocalStorageAvailable) return undefined;
 
    return window.localStorage.setItem(this.currentTabKey, val);
  }
 
  readData() {
    if (!this.isLocalStorageAvailable) return null;
 
    return window.localStorage.getItem(this.currentTabKey);
  }
}