index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. import React, {Component} from 'react';
  3. import {createReactNavigationReduxMiddleware, createReduxBoundAddListener} from 'react-navigation-redux-helpers';
  4. import {connect} from 'react-redux';
  5. export const navigatorPieces = (BareNavigator, name = "root") => {
  6. const middleware = createReactNavigationReduxMiddleware(name, x => x);
  7. const addListener = createReduxBoundAddListener(name);
  8. const reducer = (state, action) => BareNavigator.router.getStateForAction(action, state);
  9. class Navigator extends Component {
  10. render () {
  11. const {dispatch, navigationState} = this.props;
  12. return <BareNavigator
  13. navigation={{dispatch, state: navigationState, addListener}}
  14. />;
  15. }
  16. }
  17. return {Navigator, reducer, middleware};
  18. };
  19. export const connectNavigator = selectorFn => connect(state => ({navigationState: selectorFn(state)}));
  20. import {NavigationActions, StackActions} from 'react-navigation';
  21. const {navigate, back} = NavigationActions;
  22. const {reset} = StackActions;
  23. export const backButtonHandler = ({dispatch, getState}) => {
  24. if (getState().index === 0) return false;
  25. dispatch(back());
  26. return true;
  27. };
  28. const topOfNavigationStack = ({routes}) => routes[routes.length - 1] || {};
  29. const isRoute = expected => ({routeName}) => routeName === expected;
  30. const isTopRoute = expected => state => isRoute(expected)(topOfNavigationStack(state));
  31. export const navigationHelpers = {
  32. topOfNavigationStack,
  33. resetRoutes: routeNames => reset({
  34. actions: routeNames.map(routeName => navigate({routeName})),
  35. index: routeNames.length - 1
  36. }),
  37. isRoute,
  38. isTopRoute,
  39. goBackFrom: routeName => ({dispatch, getState}) => {
  40. if (isTopRoute(routeName)(getState())) {
  41. dispatch(back());
  42. }
  43. },
  44. };