-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdata.ts
87 lines (76 loc) · 2.56 KB
/
data.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import {TemplateAction, TemplateReducer, IRouterTemplate} from '../types';
/**
* A data router will display data as the routeKey in either the pathname or query params
* depending on if the router is a `pathRouter` or not.
* Furthermore, a data router will only be shown if data exits.
* This process involves:
* 1. Checking for data either passed in directly (via options) or existing
* on the router state
* 2. Checking if the router is a path router or not
* 3. Adding the scene router to either the path or query params
*/
const show: TemplateAction<CustomState, CustomActionNames> = (
_options,
oldLocation,
router,
ctx
) => {
const location = {...oldLocation};
const data = (ctx && ctx.pathData && ctx.pathData[router.name]
? ctx.pathData[router.name]
: router.data) as CustomState;
if (!data) {
throw new Error(`Can't show data router ${router.name} b/c the data field is not set`);
}
if (router.isPathRouter) {
location.pathname[router.pathLocation] = data;
// drop pathname after this pathLocation
location.pathname = location.pathname.slice(0, router.pathLocation + 1);
} else {
location.search[router.routeKey] = data;
}
return location;
};
const hide: TemplateAction<CustomState, CustomActionNames> = (
_options,
oldLocation,
router,
_ctx
) => {
const location = {...oldLocation};
if (router.isPathRouter) {
location.pathname = location.pathname.slice(0, router.pathLocation);
} else {
location.search[router.routeKey] = undefined;
}
return location;
};
const setData: TemplateAction<CustomState, CustomActionNames> = (
options,
location,
router,
ctx
) => {
return router.show(options, location, router, ctx);
};
const reducer: TemplateReducer<string, 'setData'> = (location, router, _ctx) => {
// TODO change this to ValueOf<IInputSearch> when data supports more than just `string` types
let routerData: string;
if (router.isPathRouter) {
routerData = location.pathname[router.pathLocation];
} else {
routerData = location.search[router.routeKey] as string;
}
return {
visible: !!routerData,
data: routerData || router.state.data
};
};
type CustomState = string;
type CustomActionNames = 'setData';
const template: IRouterTemplate<CustomState, CustomActionNames> = {
actions: {show, hide, setData},
reducer,
config: {canBePathRouter: true, isPathRouter: false, isDependentOnExternalData: true}
};
export default template;