Skip to content

Commit

Permalink
Add NavigationStateUtils.back() and NavigationStateUtils.forward().
Browse files Browse the repository at this point in the history
Summary: This makes it easy to build Pager.

Reviewed By: ericvicenti

Differential Revision: D3479979

fbshipit-source-id: 71c0536eb190e8ad64feea99e4bda5e2d28801d2
  • Loading branch information
Hedger Wang authored and Facebook Github Bot 4 committed Jun 24, 2016
1 parent f7eca44 commit 614f3c6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Libraries/NavigationExperimental/NavigationStateUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -190,6 +208,8 @@ function reset(
}

const NavigationStateUtils = {
back,
forward,
get: get,
has,
indexOf,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'}]};
Expand Down

0 comments on commit 614f3c6

Please sign in to comment.