|
| 1 | +// ref: |
| 2 | +// - <https://github.com/ReactTraining/react-router/issues/3103> |
| 3 | +// - <https://github.com/baronswindle/react-router-compose-hooks/blob/master/index.js> |
| 4 | + |
| 5 | +export default { |
| 6 | + parallel(...hooks) { |
| 7 | + let callbacksRequired = hooks.reduce((totalCallbacks, hook) => { |
| 8 | + if (hook.length >= 3) { |
| 9 | + totalCallbacks++; |
| 10 | + } |
| 11 | + return totalCallbacks; |
| 12 | + }, 0); |
| 13 | + |
| 14 | + return function onEnter(nextState, replace, executeTransition) { |
| 15 | + let callbacksInvoked = 0; |
| 16 | + hooks.forEach((hook) => { |
| 17 | + hook.call(this, nextState, replace, () => { |
| 18 | + if (++callbacksInvoked === callbacksRequired) { |
| 19 | + executeTransition(); |
| 20 | + } |
| 21 | + }); |
| 22 | + }); |
| 23 | + if (!callbacksRequired) { |
| 24 | + executeTransition(); |
| 25 | + } |
| 26 | + }; |
| 27 | + }, |
| 28 | + |
| 29 | + series(...hooks) { |
| 30 | + return function onEnter(nextState, replace, executeTransition) { |
| 31 | + (function executeHooksSynchronously(remainingHooks) { |
| 32 | + if (!remainingHooks.length) { |
| 33 | + return executeTransition(); |
| 34 | + } |
| 35 | + let nextHook = remainingHooks[0]; |
| 36 | + if (nextHook.length >= 3) { |
| 37 | + nextHook.call(this, nextState, replace, () => { |
| 38 | + executeHooksSynchronously(remainingHooks.slice(1)); |
| 39 | + }); |
| 40 | + } else { |
| 41 | + nextHook.call(this, nextState, replace); |
| 42 | + executeHooksSynchronously(remainingHooks.slice(1)); |
| 43 | + } |
| 44 | + })(hooks); |
| 45 | + }; |
| 46 | + }, |
| 47 | +}; |
0 commit comments