UNPKG

2.4 kBJavaScriptView Raw
1import { CommonActions } from '@react-navigation/routers';
2export const NOT_INITIALIZED_ERROR = "The 'navigation' object hasn't been initialized yet. This might happen if you don't have a navigator mounted, or if the navigator hasn't finished mounting. See https://reactnavigation.org/docs/navigating-without-navigation-prop#handling-initialization for more details.";
3export default function createNavigationContainerRef() {
4 const methods = [...Object.keys(CommonActions), 'addListener', 'removeListener', 'resetRoot', 'dispatch', 'isFocused', 'canGoBack', 'getRootState', 'getState', 'getParent', 'getCurrentRoute', 'getCurrentOptions'];
5 const listeners = {};
6
7 const removeListener = (event, callback) => {
8 if (listeners[event]) {
9 listeners[event] = listeners[event].filter(cb => cb !== callback);
10 }
11 };
12
13 let current = null;
14 const ref = {
15 get current() {
16 return current;
17 },
18
19 set current(value) {
20 current = value;
21
22 if (value != null) {
23 Object.entries(listeners).forEach(_ref => {
24 let [event, callbacks] = _ref;
25 callbacks.forEach(callback => {
26 value.addListener(event, callback);
27 });
28 });
29 }
30 },
31
32 isReady: () => {
33 if (current == null) {
34 return false;
35 }
36
37 return current.isReady();
38 },
39 ...methods.reduce((acc, name) => {
40 acc[name] = function () {
41 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
42 args[_key] = arguments[_key];
43 }
44
45 if (current == null) {
46 switch (name) {
47 case 'addListener':
48 {
49 const [event, callback] = args;
50 listeners[event] = listeners[event] || [];
51 listeners[event].push(callback);
52 return () => removeListener(event, callback);
53 }
54
55 case 'removeListener':
56 {
57 const [event, callback] = args;
58 removeListener(event, callback);
59 break;
60 }
61
62 default:
63 console.error(NOT_INITIALIZED_ERROR);
64 }
65 } else {
66 // @ts-expect-error: this is ok
67 return current[name](...args);
68 }
69 };
70
71 return acc;
72 }, {})
73 };
74 return ref;
75}
76//# sourceMappingURL=createNavigationContainerRef.js.map
\No newline at end of file