Simplify routing logic

This commit is contained in:
Ken-Håvard Lieng 2018-12-08 11:08:01 +01:00
parent 35c2d682e3
commit c1ca29511e
3 changed files with 131 additions and 151 deletions

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,4 @@
import Cookie from 'js-cookie';
import { select, updateSelection, tabExists } from 'state/tab';
import { updateSelection } from 'state/tab';
import { observe, when } from 'utils/observe';
export default function route({ store }) {
@ -14,43 +13,7 @@ export default function route({ store }) {
state => state.router,
router => {
if (!router.route || router.route === 'chat') {
const state = store.getState();
let redirect = true;
const tabs = [];
if (router.route === 'chat') {
if (tabExists(router.params, state)) {
redirect = false;
} else {
tabs.push(router.params);
}
}
if (redirect && first) {
const cookie = Cookie.get('tab');
if (cookie) {
const [server, name = null] = cookie.split(/;(.+)/);
tabs.unshift({ server, name });
}
}
if (redirect) {
let found = false;
for (let i = 0; i < tabs.length; i++) {
const tab = tabs[i];
if (tabExists(tab, state)) {
store.dispatch(select(tab.server, tab.name, true));
found = true;
break;
}
}
if (!found) {
store.dispatch(updateSelection());
}
}
store.dispatch(updateSelection(first));
first = false;
}
}

View File

@ -1,4 +1,5 @@
import get from 'lodash/get';
import Cookie from 'js-cookie';
import createReducer from 'utils/createReducer';
import { push, replace, LOCATION_CHANGED } from 'utils/router';
import * as actions from './actions';
@ -67,17 +68,33 @@ export function tabExists(
);
}
export function updateSelection() {
function parseTabCookie() {
const cookie = Cookie.get('tab');
if (cookie) {
const [server, name = null] = cookie.split(/;(.+)/);
return { server, name };
}
return null;
}
export function updateSelection(tryCookie) {
return (dispatch, getState) => {
const state = getState();
const { history } = state.tab;
const { servers } = state;
const { server, name } = state.tab.selected;
if (tabExists({ server, name }, state)) {
if (tabExists(state.tab.selected, state)) {
return;
}
if (tryCookie) {
const tab = parseTabCookie();
if (tab && tabExists(tab, state)) {
return dispatch(select(tab.server, tab.name, true));
}
}
const { servers } = state;
const { history } = state.tab;
const { server } = state.tab.selected;
const serverAddrs = Object.keys(servers);
if (serverAddrs.length === 0) {