Skip to content

Instantly share code, notes, and snippets.

@mateoKaradza
Created November 6, 2016 09:50
Show Gist options
  • Save mateoKaradza/a25be2698e01f9af284e846902cf8f54 to your computer and use it in GitHub Desktop.
Save mateoKaradza/a25be2698e01f9af284e846902cf8f54 to your computer and use it in GitHub Desktop.
import { NavigationExperimental } from 'react-native';
import _ from 'lodash';
import { PUSH_ROUTE, POP_ROUTE } from './actions';
import { LOGIN_SUCCESS, LOGOUT_SUCCESS } from '../auth/actions';
const { StateUtils: NavigationStateUtils } = NavigationExperimental;
const initialState = {
index: 0,
key: 'root',
routes: [
{
key: 'home',
title: 'Homepage',
},
],
redirect: { key: 'home', title: 'Homepage' },
authed: false,
};
export default function (state = initialState, action) {
let newState;
switch (action.type) {
case LOGIN_SUCCESS:
newState = _.cloneDeep(state);
newState.authed = true;
if (newState.routes[state.index].key === 'login')
return useRedirect(newState);
return newState;
case LOGOUT_SUCCESS:
newState = _.cloneDeep(state);
newState.authed = false;
return popToRoute(newState, 'home');
case PUSH_ROUTE:
return pushRoute(state, action.route);
case POP_ROUTE:
return popRoute(state);
default:
return state;
}
}
function popRoute(state) {
if (state.index === 0)
return state;
if (state.routes[state.index].key === 'login' && state.routes[state.index - 1].key === state.redirect.key)
return popToRoute(state, state.routes[state.index - 2].key);
return NavigationStateUtils.pop(state);
}
function pushRoute(state, route) {
if (route.requireAuth === true && !state.authed)
return setLogin(state, route);
const index = indexOfRoute(state, route.key);
if (index !== -1)
return NavigationStateUtils.jumpTo(state, route.key);
return NavigationStateUtils.push(state, route);
}
function indexOfRoute(state, key) {
return NavigationStateUtils.indexOf(state, key);
}
function popToRoute(state, key) {
const newState = state;
const index = indexOfRoute(state, key);
newState.routes = newState.routes.slice(0, index + 1);
newState.index = index;
return NavigationStateUtils.jumpToIndex(newState, index);
}
function setLogin(state, route) {
const newState = pushRoute(state, { key: 'login', title: 'Login Page' });
newState.redirect = { key: route.key, title: route.title };
return newState;
}
function useRedirect(state) {
const newState = popRoute(state);
const redirect = newState.redirect;
redirect.requireAuth = true;
return pushRoute(newState, redirect);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment