All files index.js

93.62% Statements 44/47
80% Branches 16/20
85.71% Functions 12/14
92.68% Lines 38/41
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 761x   1x 229x 74x 11x   27x 21x   1x           18x   18x 28x 7x       18x 18x       3x 3x 3x         1x 18x 18x 18x   198x 198x 18x 18x 18x 18x   180x         1x 3x 3x 3x 3x         3x     1x       1x     1x 1x    
const { createComponent } = typeof module !== 'undefined' ? require('gruujs') : Gruu
 
const GruuRouter = ((function () {
  const isPathCorrect = (regex, locationPath) => regex.test(locationPath)
  const getParams = path => path.replace(/(\^|\$)/g, '').split('/').map(v => (/:[^/]*/g).test(v) && v.slice(1))
  const getParamsValues = (path, regex, params) => path.match(regex)[0]
    .split('/')
    .reduce((acc, v, i) => Object.assign({}, acc, params[i] ? { [params[i]]: v } : {}))
  const getPathRegex = path => new RegExp(path.replace(/:[^/$]*/g, '[^/]*'))
 
  const router = createComponent({
    subs: [],
    state: {
      locationPath: window.location.pathname
    },
    goTo (path, popEvent) {
      router.state.locationPath = path
 
      router.subs.forEach(([regex, params, fn]) => {
        if (isPathCorrect(regex, path)) {
          fn(getParamsValues(path, regex, params))
        }
      })
 
      Eif (!popEvent) {
        window.history.pushState(null, null, path)
      }
    },
    addSub (sub) {
      router.subs.push(sub)
      return () => {
        router.subs = router.subs.filter(s => s !== sub)
      }
    }
  })
 
  const route = (path, component) => {
    const params = getParams(path)
    const regex = getPathRegex(path)
    return createComponent({
      $children () {
        const currentPath = router.state.locationPath
        if (isPathCorrect(regex, currentPath)) {
          const componentAsAFunction = typeof component === 'function'
          const values = !componentAsAFunction ? [] : getParamsValues(currentPath, regex, params)
          const comp = componentAsAFunction ? component(values) : component
          return [comp]
        }
        return []
      }
    })
  }
 
  const routeSub = (path, fn) => {
    const params = getParams(path)
    const regex = getPathRegex(path)
    const currentPath = window.location.pathname
    Iif (isPathCorrect(regex, currentPath)) {
      setTimeout(() => {
        fn(getParamsValues(currentPath, regex, params))
      })
    }
    return router.addSub([regex, params, fn])
  }
 
  window.onpopstate = () => {
    router.goTo(window.location.pathname, true)
  }
 
  return { router, route, routeSub }
})())
 
Eif (typeof module !== 'undefined') {
  module.exports = GruuRouter
}