index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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} from 'react-navigation';
  21. const {navigate, back, reset} = NavigationActions;
  22. export const backButtonHandler = ({dispatch, getState}) => {
  23. if (getState().index === 0) return false;
  24. dispatch(back());
  25. return true;
  26. };
  27. export const navigationHelpers = {
  28. topOfNavigationStack: ({routes}) => routes[routes.length - 1] || {},
  29. resetRoutes: routeNames => reset({
  30. actions: routeNames.map(routeName => navigate({routeName})),
  31. index: routeNames.length - 1
  32. }),
  33. isRoute: expected => ({routeName}) => routeName === expected,
  34. isTopRoute: expected => state => isRoute(expected)(topOfNavigationStack(state)),
  35. goBackFrom: routeName => ({dispatch, getState}) => {
  36. if (isTopRoute(routeName)(getState())) {
  37. dispatch(back());
  38. }
  39. },
  40. };