Add `NavigationStateUtils.back()` and `NavigationStateUtils.forward()`.

Summary: This makes it easy to build Pager.

Reviewed By: ericvicenti

Differential Revision: D3479979

fbshipit-source-id: 71c0536eb190e8ad64feea99e4bda5e2d28801d2
This commit is contained in:
Hedger Wang 2016-06-24 15:23:57 -07:00 committed by Facebook Github Bot 4
parent f7eca44046
commit 614f3c68e6
2 changed files with 34 additions and 0 deletions

View File

@ -111,6 +111,24 @@ function jumpTo(state: NavigationState, key: string): NavigationState {
return jumpToIndex(state, index);
}
/**
* Sets the focused route to the previous route.
*/
function back(state: NavigationState): NavigationState {
const index = state.index - 1;
const route = state.routes[index];
return route ? jumpToIndex(state, index) : state;
}
/**
* Sets the focused route to the next route.
*/
function forward(state: NavigationState): NavigationState {
const index = state.index + 1;
const route = state.routes[index];
return route ? jumpToIndex(state, index) : state;
}
/**
* Replace a route by a key.
* Note that this moves the index to the positon to where the new route in the
@ -190,6 +208,8 @@ function reset(
}
const NavigationStateUtils = {
back,
forward,
get: get,
has,
indexOf,

View File

@ -83,6 +83,20 @@ describe('NavigationStateUtils', () => {
expect(() => NavigationStateUtils.jumpTo(state, 'c')).toThrow();
});
it('move backwards', () => {
const state = {index: 1, routes: [{key: 'a'}, {key: 'b'}]};
const newState = {index: 0, routes: [{key: 'a'}, {key: 'b'}]};
expect(NavigationStateUtils.back(state)).toEqual(newState);
expect(NavigationStateUtils.back(newState)).toBe(newState);
});
it('move forwards', () => {
const state = {index: 0, routes: [{key: 'a'}, {key: 'b'}]};
const newState = {index: 1, routes: [{key: 'a'}, {key: 'b'}]};
expect(NavigationStateUtils.forward(state)).toEqual(newState);
expect(NavigationStateUtils.forward(newState)).toBe(newState);
});
// Replace
it('Replaces by key', () => {
const state = {index: 0, routes: [{key: 'a'}, {key: 'b'}]};