UNPKG

2.13 kBJavaScriptView Raw
1import warning from 'warning';
2
3var createTransitionManager = function createTransitionManager() {
4 var prompt = null;
5
6 var setPrompt = function setPrompt(nextPrompt) {
7 warning(prompt == null, 'A history supports only one prompt at a time');
8
9 prompt = nextPrompt;
10
11 return function () {
12 if (prompt === nextPrompt) prompt = null;
13 };
14 };
15
16 var confirmTransitionTo = function confirmTransitionTo(location, action, getUserConfirmation, callback) {
17 // TODO: If another transition starts while we're still confirming
18 // the previous one, we may end up in a weird state. Figure out the
19 // best way to handle this.
20 if (prompt != null) {
21 var result = typeof prompt === 'function' ? prompt(location, action) : prompt;
22
23 if (typeof result === 'string') {
24 if (typeof getUserConfirmation === 'function') {
25 getUserConfirmation(result, callback);
26 } else {
27 warning(false, 'A history needs a getUserConfirmation function in order to use a prompt message');
28
29 callback(true);
30 }
31 } else {
32 // Return false from a transition hook to cancel the transition.
33 callback(result !== false);
34 }
35 } else {
36 callback(true);
37 }
38 };
39
40 var listeners = [];
41
42 var appendListener = function appendListener(fn) {
43 var isActive = true;
44
45 var listener = function listener() {
46 if (isActive) fn.apply(undefined, arguments);
47 };
48
49 listeners.push(listener);
50
51 return function () {
52 isActive = false;
53 listeners = listeners.filter(function (item) {
54 return item !== listener;
55 });
56 };
57 };
58
59 var notifyListeners = function notifyListeners() {
60 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
61 args[_key] = arguments[_key];
62 }
63
64 listeners.forEach(function (listener) {
65 return listener.apply(undefined, args);
66 });
67 };
68
69 return {
70 setPrompt: setPrompt,
71 confirmTransitionTo: confirmTransitionTo,
72 appendListener: appendListener,
73 notifyListeners: notifyListeners
74 };
75};
76
77export default createTransitionManager;
\No newline at end of file