From 614f3c68e63c07cb2f9980a785d9f8f302d9251d Mon Sep 17 00:00:00 2001 From: Hedger Wang Date: Fri, 24 Jun 2016 15:23:57 -0700 Subject: [PATCH] Add `NavigationStateUtils.back()` and `NavigationStateUtils.forward()`. Summary: This makes it easy to build Pager. Reviewed By: ericvicenti Differential Revision: D3479979 fbshipit-source-id: 71c0536eb190e8ad64feea99e4bda5e2d28801d2 --- .../NavigationStateUtils.js | 20 +++++++++++++++++++ .../__tests__/NavigationStateUtils-test.js | 14 +++++++++++++ 2 files changed, 34 insertions(+) diff --git a/Libraries/NavigationExperimental/NavigationStateUtils.js b/Libraries/NavigationExperimental/NavigationStateUtils.js index 14d5166a2..9fdb30a70 100644 --- a/Libraries/NavigationExperimental/NavigationStateUtils.js +++ b/Libraries/NavigationExperimental/NavigationStateUtils.js @@ -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, diff --git a/Libraries/NavigationExperimental/__tests__/NavigationStateUtils-test.js b/Libraries/NavigationExperimental/__tests__/NavigationStateUtils-test.js index 7b037fff8..d71d88800 100644 --- a/Libraries/NavigationExperimental/__tests__/NavigationStateUtils-test.js +++ b/Libraries/NavigationExperimental/__tests__/NavigationStateUtils-test.js @@ -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'}]};