UNPKG

2.77 kBJavaScriptView Raw
1var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
2
3import { parse as qsParse } from 'querystring';
4import getOr from 'lodash/fp/getOr';
5import get from 'lodash/fp/get';
6import isEqual from 'lodash/fp/isEqual';
7import pipe from 'lodash/fp/pipe';
8import set from 'lodash/fp/set';
9
10export const LOCATION = '@@history/LOCATION';
11export const NAVIGATE = '@@history/NAVIGATE';
12
13const REMOVE_QUESTION_MARK = /^\??(.*)/;
14const parseQuery = pipe(s => REMOVE_QUESTION_MARK.exec(s), get(1), qsParse);
15
16export const createLocation = location => {
17 const loc = pipe(getOr('', 'search'), parseQuery, query => {
18 if (isEqual(query, {})) return location;
19 return set('query', query, location);
20 })(location);
21
22 return {
23 type: LOCATION,
24 payload: _extends({}, loc)
25 };
26};
27
28const ACTIONS_HISTORY = {
29 PUSH: 'push',
30 REPLACE: 'replace',
31 GO: 'go',
32 GO_BACK: 'goBack',
33 GO_FORWARD: 'goForward'
34};
35
36const createNavigate = action => (...args) => {
37 return {
38 type: NAVIGATE,
39 payload: {
40 action,
41 args
42 }
43 };
44};
45
46export const createPushNavigate = createNavigate(ACTIONS_HISTORY.PUSH);
47export const createReplaceNavigate = createNavigate(ACTIONS_HISTORY.REPLACE);
48export const createGoNavigate = createNavigate(ACTIONS_HISTORY.GO);
49export const createGoBackNavigate = createNavigate(ACTIONS_HISTORY.GO_BACK);
50export const createGoForwardNavigate = createNavigate(ACTIONS_HISTORY.GO_FORWARD);
51
52export const INITAL_STATE = {};
53
54export const historyReducer = (state = INITAL_STATE, { type, payload }) => {
55 if (type === LOCATION) return payload;
56 return state;
57};
58
59export const historyMiddleware = ({ history }) => store => {
60 history.listen(location => {
61 store.dispatch(createLocation(location));
62 });
63
64 return next => action => {
65 if (action.type === NAVIGATE) {
66 const { payload: { action: historyAction, args } } = action;
67
68 switch (historyAction) {
69 case ACTIONS_HISTORY.PUSH:
70 history.push(...args);
71 break;
72 case ACTIONS_HISTORY.REPLACE:
73 history.replace(...args);
74 break;
75 case ACTIONS_HISTORY.GO:
76 history.go(...args);
77 break;
78 case ACTIONS_HISTORY.GO_BACK:
79 history.goBack(...args);
80 break;
81 case ACTIONS_HISTORY.GO_FORWARD:
82 history.goForward(...args);
83 break;
84 }
85 }
86
87 return next(action);
88 };
89};
90
91export const syncStoreWithHistory = (store, history) => {
92 const action = createLocation(history.location);
93 return store.dispatch(action);
94};
95//# sourceMappingURL=index.js.map
\No newline at end of file