all files / modules/ TransitionUtils.js

100% Statements 31/31
91.67% Branches 11/12
100% Functions 9/9
100% Lines 28/28
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    19× 19×   19×     19×         92× 171× 19×   171×                           92×   92× 79× 79×     13×     13× 19× 19×   13×                 92×      
import { loopAsync } from './AsyncUtils'
 
function createEnterHook(hook, route) {
  return function (a, b, callback) {
    hook.apply(route, arguments)
 
    Eif (hook.length < 3) {
      // Assume hook executes synchronously and
      // automatically call the callback.
      callback()
    }
  }
}
 
function getEnterHooks(routes) {
  return routes.reduce(function (hooks, route) {
    if (route.onEnter)
      hooks.push(createEnterHook(route.onEnter, route))
 
    return hooks
  }, [])
}
 
/**
 * Runs all onEnter hooks in the given array of routes in order
 * with onEnter(nextState, replaceState, callback) and calls
 * callback(error, redirectInfo) when finished. The first hook
 * to use replaceState short-circuits the loop.
 *
 * If a hook needs to run asynchronously, it may use the callback
 * function. However, doing so will cause the transition to pause,
 * which could lead to a non-responsive UI if the hook is slow.
 */
export function runEnterHooks(routes, nextState, callback) {
  const hooks = getEnterHooks(routes)
 
  if (!hooks.length) {
    callback()
    return
  }
 
  let redirectInfo
  function replaceState(state, pathname, query) {
    redirectInfo = { pathname, query, state }
  }
 
  loopAsync(hooks.length, function (index, next, done) {
    hooks[index](nextState, replaceState, function (error) {
      if (error || redirectInfo) {
        done(error, redirectInfo) // No need to continue.
      } else {
        next()
      }
    })
  }, callback)
}
 
/**
 * Runs all onLeave hooks in the given array of routes in order.
 */
export function runLeaveHooks(routes) {
  for (let i = 0, len = routes.length; i < len; ++i)
    if (routes[i].onLeave)
      routes[i].onLeave.call(routes[i])
}