Skip to content

Commit

Permalink
restoreLastLocation: use localforage, don't redir outside Calypso (#1…
Browse files Browse the repository at this point in the history
…4196)

* restoreLastLocation: use localforage

* Address feedback + other improvements:

- Don't save from or redirect to a path that isn't relative to Calypso.
- Don't call `next` before `page`
- Move `hasInitialized` state one function down to make it a store
  global instead of a module global

* Call next() if localforage read fails
  • Loading branch information
mcsf authored May 31, 2017
1 parent 00f28f6 commit 75c13bd
Showing 1 changed file with 31 additions and 18 deletions.
49 changes: 31 additions & 18 deletions client/state/routing/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,48 @@
*/
import debugFactory from 'debug';
import page from 'page';
import store from 'store';

/**
* Internal dependencies
*/
import localforage from 'lib/localforage';
import { isOutsideCalypso } from 'lib/url';
import { ROUTE_SET } from 'state/action-types';

const debug = debugFactory( 'calypso:restore-last-location' );
const LAST_PATH = 'last_path';

let hasInitialized = false;
export const restoreLastLocation = () => {
let hasInitialized = false;

export const restoreLastLocation = () => ( next ) => ( action ) => {
if ( action.type === ROUTE_SET && action.path ) {
const lastPath = store.get( 'last_path' );

if ( ! hasInitialized && lastPath && lastPath !== '/' && action.path === '/' ) {
debug( 'redir to', action.path );
page( lastPath );
} else {
debug( 'saving', action.path );
store.set( 'last_path', action.path );
}

if ( ! hasInitialized ) {
hasInitialized = true;
return ( next ) => ( action ) => {
if ( action.type !== ROUTE_SET || ! action.path ) {
return next( action );
}
}

return next( action );
localforage.getItem( LAST_PATH ).then(
( lastPath ) => {
if ( ! hasInitialized &&
lastPath && lastPath !== '/' &&
action.path === '/' &&
! isOutsideCalypso( lastPath ) ) {
debug( 'redir to', lastPath );
page( lastPath );
} else if ( action.path !== lastPath &&
! isOutsideCalypso( action.path ) ) {
debug( 'saving', action.path );
localforage.setItem( LAST_PATH, action.path );
}

if ( ! hasInitialized ) {
hasInitialized = true;
}

return next( action );
},
() => next( action )
);
};
};

export default restoreLastLocation;

0 comments on commit 75c13bd

Please sign in to comment.