All files / src/route route-link.js

100% Statements 31/31
81.48% Branches 22/27
100% Functions 8/8
100% Lines 31/31

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 65 66      7x 7x 7x 7x       7x 7x 7x       7x 7x 7x       7x 7x 7x 4x   7x 1x         15x 30x         7x 7x 7x   7x 7x 2x 2x 1x   1x     6x 6x         7x         1x    
class RouteLink extends HTMLElement {
 
  constructor() {
    super()
    this._activateRouteBind = this._activateRoute.bind(this)
    this._isActivatedBind = this._isActivated.bind(this)
    this._basePath = `${window.location.origin}/`
  }
 
  connectedCallback() {
    this.addEventListener('click', this._activateRouteBind)
    window.addEventListener('url-change', this._isActivatedBind)
    window.addEventListener('popstate', this._isActivatedBind)
  }
 
  disconnectedCallback() {
    this.removeEventListener('click', this._activateRouteBind)
    window.removeEventListener('url-change', this._isActivatedBind)
    window.removeEventListener('popstate', this._isActivatedBind)
  }
 
  _isActivated() {
    const currentPath = this._getAdjustedPath(decodeURI(window.location.pathname))
    this.classList.remove('active')
    if (currentPath && this.dataset.route && this.dataset.route.includes(currentPath)) {
      this.classList.add('active')
    }
    if (!currentPath.length && this.dataset.route === '/') {
      this.classList.add('active')
    }
  }
 
  _getAdjustedPath(path) {
    return path ? path.trim().split('/')
      .filter(pathName => pathName.length)
      .join('/') : ''
  }
 
  _activateRoute() {
    Eif (!this._isDisabled()) {
      Eif (this.dataset.title && this.dataset.title.length) {
        document.title = this.dataset.title
      }
      let route = this._getAdjustedPath(this.dataset.route || '')
      if (this.dataset.back && this.dataset.back.toLowerCase() === 'true') {
        const path = window.sessionStorage.getItem('last-route-path')
        if (path) {
          route = this._getAdjustedPath(path)
        } else {
          return window.history.back()
        }
      }
      window.history.pushState(route, document.title, `${this._basePath}${route}`)
      window.dispatchEvent(new CustomEvent('url-change', { detail: route }))
    }
  }
 
  _isDisabled() {
    return this.dataset.disabled && this.dataset.disabled.toLowerCase() === 'true'
  }
 
}
 
window.customElements.define('route-link', RouteLink)
export default RouteLink