UNPKG

2.91 kBJavaScriptView Raw
1import _set from "lodash/fp/set";
2import _pipe from "lodash/fp/pipe";
3import _isEqual from "lodash/fp/isEqual";
4import _get from "lodash/fp/get";
5import _getOr from "lodash/fp/getOr";
6
7function _extends() { _extends = Object.assign ? Object.assign.bind() : 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; }; return _extends.apply(this, arguments); }
8
9import { parse as qsParse } from 'querystring';
10export const LOCATION = '@@history/LOCATION';
11export const NAVIGATE = '@@history/NAVIGATE';
12const REMOVE_QUESTION_MARK = /^\??(.*)/;
13
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};
27const ACTIONS_HISTORY = {
28 PUSH: 'push',
29 REPLACE: 'replace',
30 GO: 'go',
31 GO_BACK: 'goBack',
32 GO_FORWARD: 'goForward'
33};
34
35const createNavigate = action => (...args) => {
36 return {
37 type: NAVIGATE,
38 payload: {
39 action,
40 args
41 }
42 };
43};
44
45export const createPushNavigate = createNavigate(ACTIONS_HISTORY.PUSH);
46export const createReplaceNavigate = createNavigate(ACTIONS_HISTORY.REPLACE);
47export const createGoNavigate = createNavigate(ACTIONS_HISTORY.GO);
48export const createGoBackNavigate = createNavigate(ACTIONS_HISTORY.GO_BACK);
49export const createGoForwardNavigate = createNavigate(ACTIONS_HISTORY.GO_FORWARD);
50export const INITAL_STATE = {};
51export const historyReducer = (state, {
52 type,
53 payload
54}) => {
55 if (type === LOCATION) return payload;
56 return state || INITAL_STATE;
57};
58export const historyMiddleware = ({
59 history
60}) => store => {
61 history.listen(location => {
62 store.dispatch(createLocation(location));
63 });
64 return next => action => {
65 if (action.type === NAVIGATE) {
66 const {
67 payload: {
68 action: historyAction,
69 args
70 }
71 } = action;
72
73 switch (historyAction) {
74 case ACTIONS_HISTORY.PUSH:
75 history.push(...args);
76 break;
77
78 case ACTIONS_HISTORY.REPLACE:
79 history.replace(...args);
80 break;
81
82 case ACTIONS_HISTORY.GO:
83 history.go(...args);
84 break;
85
86 case ACTIONS_HISTORY.GO_BACK:
87 history.goBack(...args);
88 break;
89
90 case ACTIONS_HISTORY.GO_FORWARD:
91 history.goForward(...args);
92 break;
93 }
94 }
95
96 return next(action);
97 };
98};
99export const syncStoreWithHistory = (store, history) => {
100 const action = createLocation(history.location);
101 return store.dispatch(action);
102};
103//# sourceMappingURL=index.js.map
\No newline at end of file