All files router.js

93.48% Statements 86/92
78.85% Branches 41/52
90.63% Functions 29/32
93.41% Lines 85/91

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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194      1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x       16x       8x 8x   25x       57x 87x         3x 3x   3x 2x   3x       2x 2x       8x 1x   8x   8x 8x 1x     8x 8x 7x   8x   8x 8x         8x 7x 6x 6x 6x       8x 6x         59x       8x 8x 8x       17x       17x       17x       17x 17x 17x         17x 17x       20x       26x       6x 6x 6x   6x       1x 1x 1x 1x   1x       8x       6x               1x       34x 39x 37x   34x       8x 8x 8x 8x 8x 8x 2x 2x 2x     8x                  
class Router {
 
  constructor() {
    Iif (this.instance) {
      return this.instance
    }
    this.instance = this
    this._paths = new Map()
    this._basePath = window.location.origin
    this._exitFn = null
    this.paramRegex = /[:](\w+)/
    this.lastRoutePath = window.sessionStorage.getItem('last-route-path') || ''
    this.historyChangeBind = this.historyChange.bind(this)
    window.addEventListener('url-change', this.historyChangeBind)
    window.addEventListener('popstate', this.historyChangeBind)
    this.$defaultPath
 
    const path = this.urlFullPath()
    window.addEventListener('load', this.goto.bind(this, path))
  }
 
  getCurrentPath() {
    return window.decodeURIComponent(window.location.pathname)
  }
 
  getRoute() {
    let currentPath = this.getAdjustedPath(this.getCurrentPath())
    return [...this._paths.keys()]
      .map(this.fromBase64.bind(this))
      .find(routeRE => this._pathToRegex(routeRE).test(currentPath))
  }
 
  getAdjustedPath(path = '') {
    return path.trim() === '/' ? path : path.trim().split('/')
      .filter(pathName => pathName.length)
      .join('/')
  }
 
  _safeDefaultPath() {
    let safePath = ''
    Iif (this.$defaultPath === '/') {
      safePath = this.$defaultPath
    } else if (this.$defaultPath) {
      safePath = this.$defaultPath.split('/').shift().replace(/[^\w]/g, '')
    }
    return safePath
  }
 
  _defaultPathOption() {
    const safePath = this._safeDefaultPath()
    return this.$defaultPath ? this._pathToRegex(this.$defaultPath).test(safePath) : false
  }
 
  historyChange() {
    if (typeof this._exitFn === 'function') {
      this._exitFn()
    }
    this._exitFn = null
 
    const route = this.getRoute()
    if ((!route || !this.hasPath(route)) && this._defaultPathOption()) {
      this.goto(this._safeDefaultPath())
    }
 
    const fullPath = window.decodeURIComponent(this.urlFullPath())
    if (this.lastRoutePath !== fullPath) {
      window.sessionStorage.setItem('last-route-path', this.lastRoutePath)
    }
    this.lastRoutePath = fullPath
 
    let handlers = this.getPath(route)
    let req = {
      exit: this._exit.bind(this),
      params: this._pathParams(route),
      search: new URLSearchParams(window.location.search)
    }
    const pipeNext = callbacks => {
      if (Array.isArray(callbacks) && callbacks.length) {
        const next = callbacks.shift()
        Eif (typeof next === 'function') {
          next(req, pipeNext.bind(this, callbacks))
        }
      }
    }
    if (Array.isArray(handlers)) {
      pipeNext(handlers.slice())
    }
  }
 
  get basePath() {
    return this._basePath
  }
 
  goto(path, title = '') {
    window.history.pushState(path, title, `${this.basePath}${this.urlFullPath(path)}`)
    window.dispatchEvent(new CustomEvent('url-change', { detail: path }))
    return this
  }
 
  urlFullPath(path = window.location.href) {
    return this.urlPathname(path) + this.urlHash(path) + this.urlParams(path)
  }
 
  urlPathname(path) {
    return new URL(path, this.basePath).pathname
  }
 
  urlHash(path) {
    return new URL(path, this.basePath).hash
  }
 
  urlParams(path) {
    const pathURL = Array.from(new URL(path, this.basePath).searchParams.entries())
    const searchParams = new URLSearchParams(window.location.search)
    pathURL.forEach(([key, value]) => {
      if (!searchParams.has(key)) {
        searchParams.append(key, value)
      }
    })
    const params = searchParams.toString()
    return params.length ? `?${params}` : ''
  }
 
  toBase64(str) {
    return window.btoa(window.unescape(window.encodeURIComponent(str)))
  }
 
  fromBase64(str) {
    return window.decodeURIComponent(window.escape(window.atob(str)))
  }
 
  setPath(path, ...callbacks) {
    path = this.getAdjustedPath(path)
    Eif (path.length) {
      this._paths.set(this.toBase64(path), callbacks)
    }
    return this
  }
 
  defaultPath(path, ...callbacks) {
    path = this.getAdjustedPath(path)
    Eif (path.length) {
      this.$defaultPath = path
      this.setPath(this.$defaultPath, ...callbacks)
    }
    return this
  }
 
  getPath(path) {
    return this._paths.get(this.toBase64(path))
  }
 
  hasPath(path) {
    return this._paths.has(this.toBase64(path))
  }
 
  reload() {
    this.goto(this.urlFullPath())
  }
 
  _exit(fn) {
    this._exitFn = fn
  }
 
  _pathToRegex(path = '') {
    const pattern = this.getAdjustedPath(path).split('/')
      .filter(pathName => pathName.length)
      .map(pathName => this.paramRegex.test(pathName) ? `([\\w\\s&!$*:\\-+]+)${pathName.includes('?') ? '?' : ''}` : pathName)
      .join('/?')
    return new RegExp(`^/?${pattern || '/'}/?$`)
  }
 
  _pathParams(path = '') {
    const paramRegexGlobal = /[:](\w+)/g
    const matches = path.match(paramRegexGlobal)
    const currentPath = this.getAdjustedPath(this.getCurrentPath())
    const routeParams = currentPath.match(this._pathToRegex(path))
    let params = new Map()
    if (matches && routeParams) {
      routeParams.shift()
      matches.map(param => param.replace(':', '')).forEach(param => {
        params.set(param, routeParams.shift())
      })
    }
    return params
  }
 
  removeURLSearchParams() {
    window.history.replaceState({}, document.title, window.location.pathname)
  }
}
 
export default new Router()