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:
parent
f7eca44046
commit
614f3c68e6
|
@ -111,6 +111,24 @@ function jumpTo(state: NavigationState, key: string): NavigationState {
|
||||||
return jumpToIndex(state, index);
|
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.
|
* Replace a route by a key.
|
||||||
* Note that this moves the index to the positon to where the new route in the
|
* Note that this moves the index to the positon to where the new route in the
|
||||||
|
@ -190,6 +208,8 @@ function reset(
|
||||||
}
|
}
|
||||||
|
|
||||||
const NavigationStateUtils = {
|
const NavigationStateUtils = {
|
||||||
|
back,
|
||||||
|
forward,
|
||||||
get: get,
|
get: get,
|
||||||
has,
|
has,
|
||||||
indexOf,
|
indexOf,
|
||||||
|
|
|
@ -83,6 +83,20 @@ describe('NavigationStateUtils', () => {
|
||||||
expect(() => NavigationStateUtils.jumpTo(state, 'c')).toThrow();
|
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
|
// Replace
|
||||||
it('Replaces by key', () => {
|
it('Replaces by key', () => {
|
||||||
const state = {index: 0, routes: [{key: 'a'}, {key: 'b'}]};
|
const state = {index: 0, routes: [{key: 'a'}, {key: 'b'}]};
|
||||||
|
|
Loading…
Reference in New Issue