1 |
|
2 | import { warning } from './log';
|
3 | const createTransitionManager = () => {
|
4 | let prompt;
|
5 | let listeners = [];
|
6 | const setPrompt = (nextPrompt) => {
|
7 | warning(prompt == null, 'A history supports only one prompt at a time');
|
8 | prompt = nextPrompt;
|
9 | return () => {
|
10 | if (prompt === nextPrompt) {
|
11 | prompt = null;
|
12 | }
|
13 | };
|
14 | };
|
15 | const confirmTransitionTo = (location, action, getUserConfirmation, callback) => {
|
16 |
|
17 |
|
18 |
|
19 | if (prompt != null) {
|
20 | const result = typeof prompt === 'function' ? prompt(location, action) : prompt;
|
21 | if (typeof result === 'string') {
|
22 | if (typeof getUserConfirmation === 'function') {
|
23 | getUserConfirmation(result, callback);
|
24 | }
|
25 | else {
|
26 | warning(false, 'A history needs a getUserConfirmation function in order to use a prompt message');
|
27 | callback(true);
|
28 | }
|
29 | }
|
30 | else {
|
31 |
|
32 | callback(result !== false);
|
33 | }
|
34 | }
|
35 | else {
|
36 | callback(true);
|
37 | }
|
38 | };
|
39 | const appendListener = (fn) => {
|
40 | let isActive = true;
|
41 | const listener = (...args) => {
|
42 | if (isActive) {
|
43 | fn(...args);
|
44 | }
|
45 | };
|
46 | listeners.push(listener);
|
47 | return () => {
|
48 | isActive = false;
|
49 | listeners = listeners.filter(item => item !== listener);
|
50 | };
|
51 | };
|
52 | const notifyListeners = (...args) => {
|
53 | listeners.forEach(listener => listener(...args));
|
54 | };
|
55 | return {
|
56 | setPrompt,
|
57 | confirmTransitionTo,
|
58 | appendListener,
|
59 | notifyListeners
|
60 | };
|
61 | };
|
62 | export default createTransitionManager;
|