all files / modules/ useRoutes.js

62.33% Statements 91/146
47.3% Branches 35/74
60% Functions 15/25
46% Lines 46/100
8 statements, 1 function, 5 branches Ignored     
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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259                                                      76×   79× 79×   96×             79×   94×       94× 94×   94× 92×                 92×   92× 92×   92×     86× 86×         86×             79×         79×                                                                                                       79×                                                                                                                                               75× 90×     90× 90×   90× 85× 84×                       79×                        
import warning from 'warning'
import { REPLACE } from 'history/lib/Actions'
import useQueries from 'history/lib/useQueries'
import computeChangedRoutes from './computeChangedRoutes'
import { runEnterHooks, runLeaveHooks } from './TransitionUtils'
import { default as _isActive } from './isActive'
import getComponents from './getComponents'
import matchRoutes from './matchRoutes'
 
function hasAnyProperties(object) {
  for (const p in object)
    if (object.hasOwnProperty(p))
      return true
 
  return false
}
 
/**
 * Returns a new createHistory function that may be used to create
 * history objects that know about routing.
 *
 * Enhances history objects with the following methods:
 *
 * - listen((error, nextState) => {})
 * - listenBeforeLeavingRoute(route, (nextLocation) => {})
 * - match(location, (error, redirectLocation, nextState) => {})
 * - isActive(pathname, query, indexOnly=false)
 */
function useRoutes(createHistory) {
  return function (options={}) {
    let { routes, ...historyOptions } = options
    let history = useQueries(createHistory)(historyOptions)
    let state = {}
 
    function isActive(pathname, query, indexOnly=false) {
      return _isActive(pathname, query, indexOnly, state.location, state.routes, state.params)
    }
 
    function createLocationFromRedirectInfo({ pathname, query, state }) {
      return history.createLocation(
        history.createPath(pathname, query), state, REPLACE
      )
    }
 
    let partialNextState
 
    function match(location, callback) {
      Iif (partialNextState && partialNextState.location === location) {
        // Continue from where we left off.
        finishMatch(partialNextState, callback)
      } else {
        matchRoutes(routes, location, function (error, nextState) {
          Iif (error) {
            callback(error)
          } else if (nextState) {
            finishMatch({ ...nextState, location }, callback)
          } else {
            callback()
          }
        })
      }
    }
 
    function finishMatch(nextState, callback) {
      let { leaveRoutes, enterRoutes } = computeChangedRoutes(state, nextState)
 
      runLeaveHooks(leaveRoutes)
 
      runEnterHooks(enterRoutes, nextState, function (error, redirectInfo) {
        Iif (error) {
          callback(error)
        } else if (redirectInfo) {
          callback(null, createLocationFromRedirectInfo(redirectInfo))
        } else {
          // TODO: Fetch components after state is updated.
          getComponents(nextState, function (error, components) {
            Iif (error) {
              callback(error)
            } else {
              // TODO: Make match a pure function and have some other API
              // for "match and update state".
              callback(null, null, (state = { ...nextState, components }))
            }
          })
        }
      })
    }
 
    let RouteGuid = 1
 
    function getRouteID(route) {
      return route.__id__ || (route.__id__ = RouteGuid++)
    }
 
    const RouteHooks = {}
 
    function getRouteHooksForRoutes(routes) {
      return routes.reduce(function (hooks, route) {
        hooks.push.apply(hooks, RouteHooks[getRouteID(route)])
        return hooks
      }, [])
    }
 
    function transitionHook(location, callback) {
      matchRoutes(routes, location, function (error, nextState) {
        if (nextState == null) {
          // TODO: We didn't actually match anything, but hang
          // onto error/nextState so we don't have to matchRoutes
          // again in the listen callback.
          callback()
          return
        }
 
        // Cache some state here so we don't have to
        // matchRoutes() again in the listen callback.
        partialNextState = { ...nextState, location }
 
        let hooks = getRouteHooksForRoutes(
          computeChangedRoutes(state, partialNextState).leaveRoutes
        )
 
        let result
        for (let i = 0, len = hooks.length; result == null && i < len; ++i) {
          // Passing the location arg here indicates to
          // the user that this is a transition hook.
          result = hooks[i](location)
        }
 
        callback(result)
      })
    }
 
    function beforeUnloadHook() {
      // Synchronously check to see if any route hooks want
      // to prevent the current window/tab from closing.
      if (state.routes) {
        let hooks = getRouteHooksForRoutes(state.routes)
 
        let message
        for (let i = 0, len = hooks.length; typeof message !== 'string' && i < len; ++i) {
          // Passing no args indicates to the user that this is a
          // beforeunload hook. We don't know the next location.
          message = hooks[i]()
        }
 
        return message
      }
    }
 
    let unlistenBefore, unlistenBeforeUnload
 
    /**
     * Registers the given hook function to run before leaving the given route.
     *
     * During a normal transition, the hook function receives the next location
     * as its only argument and must return either a) a prompt message to show
     * the user, to make sure they want to leave the page or b) false, to prevent
     * the transition.
     *
     * During the beforeunload event (in browsers) the hook receives no arguments.
     * In this case it must return a prompt message to prevent the transition.
     *
     * Returns a function that may be used to unbind the listener.
     */
    function listenBeforeLeavingRoute(route, hook) {
      // TODO: Warn if they register for a route that isn't currently
      // active. They're probably doing something wrong, like re-creating
      // route objects on every location change.
      let routeID = getRouteID(route)
      let hooks = RouteHooks[routeID]
 
      if (hooks == null) {
        let thereWereNoRouteHooks = !hasAnyProperties(RouteHooks)
 
        hooks = RouteHooks[routeID] = [ hook ]
 
        if (thereWereNoRouteHooks) {
          // setup transition & beforeunload hooks
          unlistenBefore = history.listenBefore(transitionHook)
 
          if (history.listenBeforeUnload)
            unlistenBeforeUnload = history.listenBeforeUnload(beforeUnloadHook)
        }
      } else if (hooks.indexOf(hook) === -1) {
        hooks.push(hook)
      }
 
      return function () {
        let hooks = RouteHooks[routeID]
 
        if (hooks != null) {
          let newHooks = hooks.filter(item => item !== hook)
 
          if (newHooks.length === 0) {
            delete RouteHooks[routeID]
 
            if (!hasAnyProperties(RouteHooks)) {
              // teardown transition & beforeunload hooks
              if (unlistenBefore) {
                unlistenBefore()
                unlistenBefore = null
              }
 
              if (unlistenBeforeUnload) {
                unlistenBeforeUnload()
                unlistenBeforeUnload = null
              }
            }
          } else {
            RouteHooks[routeID] = newHooks
          }
        }
      }
    }
 
    /**
     * This is the API for stateful environments. As the location
     * changes, we update state and call the listener. We can also
     * gracefully handle errors and redirects.
     */
    function listen(listener) {
      // TODO: Only use a single history listener. Otherwise we'll
      // end up with multiple concurrent calls to match.
      return history.listen(function (location) {
        Iif (state.location === location) {
          listener(null, state)
        } else {
          match(location, function (error, redirectLocation, nextState) {
            Iif (error) {
              listener(error)
            } else if (redirectLocation) {
              history.transitionTo(redirectLocation)
            } else if (nextState) {
              listener(null, nextState)
            } else {
              warning(
                false,
                'Location "%s" did not match any routes',
                location.pathname + location.search + location.hash
              )
            }
          })
        }
      })
    }
 
    return {
      ...history,
      isActive,
      match,
      listenBeforeLeavingRoute,
      listen
    }
  }
}
 
export default useRoutes