This repository has been archived by the owner on May 7, 2021. It is now read-only.
/
reducer.ts
62 lines (55 loc) · 1.53 KB
/
reducer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { matchPath } from 'react-router';
import { LOCATION_CHANGE, LocationChangeAction } from 'connected-react-router';
import { ContextState } from './state';
import { NO_SPACE_PATH } from './constants';
const INITIAL_STATE: ContextState = {
spacenamePath: NO_SPACE_PATH,
subPath: '',
};
interface MatchParams {
username: string;
spacename: string;
subPath: string;
}
function getContext(pathname: string): ContextState {
let matchResult = matchPath<MatchParams>(pathname, {
path: `/:username([^_][^/]+)/:spacename([^_][^/]+|${NO_SPACE_PATH})/:subPath(.*)?`,
exact: false,
strict: false,
});
if (!matchResult) {
matchResult = matchPath<MatchParams>(pathname, {
path: '/:username([^_][^/]+)/:subPath(.*)?',
exact: false,
strict: false,
});
}
const username = matchResult ? matchResult.params.username : undefined;
const spacename =
matchResult && matchResult.params.spacename !== NO_SPACE_PATH
? matchResult.params.spacename
: undefined;
const subPath = matchResult
? matchResult.params.subPath
? `/${matchResult.params.subPath}`
: undefined
: pathname;
const spacenamePath = spacename || NO_SPACE_PATH;
return {
username,
spacename,
subPath,
spacenamePath,
};
}
export const contextReducer = (
state: ContextState = INITIAL_STATE,
action: LocationChangeAction,
): ContextState => {
switch (action.type) {
case LOCATION_CHANGE:
return getContext(action.payload.location.pathname);
default:
return state;
}
};