/
index.js
87 lines (76 loc) · 2.88 KB
/
index.js
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
const assert = require('assert');
const { adapt } = require('@cycle/run/lib/adapt');
const { createBrowserHistory, createMemoryHistory } = require('history');
const historyIntent = require('./historyIntent');
const intents = require('./intents');
const UniversalRouter = require('universal-router');
const xs = require('xstream').default;
let history = null, unlisten = null;
module.exports = {
go: payload => ({ type: intents.GO, payload }),
goBack: () => ({ type: intents.GO_BACK }),
goForward: () => ({ type: intents.GO_FORWARD }),
push: (...payload) => ({ type: intents.PUSH, payload }),
redirect: payload => ({ type: intents.REDIRECT, payload }),
replace: (...payload) => ({ type: intents.REPLACE, payload }),
intents: intents,
makeRouterDriver: function makeRouterDriver(
routes,
{ url = false, options = {} } = {}
) {
assert.ok(
routes,
'Cycle.js router Error: `routes` cannot be undefined.'
);
history = typeof window !== 'undefined'
? createBrowserHistory(options)
: createMemoryHistory(options);
const uRouter = new UniversalRouter(routes),
onNextState = historyIntent(history);
function routerDriver(input$) {
input$.addListener({
next: onNextState,
error: error => {
assert.fail(`Cycle.js router Error: ${error}.`);
},
complete: () => {}
});
const output$ = xs.create({
start: listener => {
uRouter
.resolve(url || history.location.pathname)
.then(vtree => {
listener.shamefullySendNext(vtree);
})
.catch(err => listener.shamefullySendError(err));
unlisten = history.listen((location, action) => {
uRouter
.resolve(location.pathname)
.then(vtree => {
listener.shamefullySendNext(vtree);
})
.catch(err => listener.shamefullySendError(err));
});
},
stop: () => {
if (unlisten) {
unlisten();
}
}
});
return adapt(output$);
}
return routerDriver;
},
mockRouterSource: function mockRouterSource(routes, { url }) {
const output$ = xs.create({
start: listener => {
new UniversalRouter(routes)
.resolve(url)
.then(vtree => listener.shamefullySendNext(vtree));
},
stop: () => {}
});
return adapt(output$);
}
};