UNPKG

7.8 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = useLinking;
7
8var _core = require("@react-navigation/core");
9
10var React = _interopRequireWildcard(require("react"));
11
12var _reactNative = require("react-native");
13
14var _extractPathFromURL = _interopRequireDefault(require("./extractPathFromURL"));
15
16function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
18function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
19
20function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
21
22let linkingHandlers = [];
23
24function useLinking(ref, _ref) {
25 let {
26 independent,
27 enabled = true,
28 prefixes,
29 filter,
30 config,
31 getInitialURL = () => Promise.race([_reactNative.Linking.getInitialURL(), new Promise(resolve => // Timeout in 150ms if `getInitialState` doesn't resolve
32 // Workaround for https://github.com/facebook/react-native/issues/25675
33 setTimeout(resolve, 150))]),
34 subscribe = listener => {
35 var _Linking$removeEventL;
36
37 const callback = _ref2 => {
38 let {
39 url
40 } = _ref2;
41 return listener(url);
42 };
43
44 const subscription = _reactNative.Linking.addEventListener('url', callback); // Storing this in a local variable stops Jest from complaining about import after teardown
45
46
47 const removeEventListener = (_Linking$removeEventL = _reactNative.Linking.removeEventListener) === null || _Linking$removeEventL === void 0 ? void 0 : _Linking$removeEventL.bind(_reactNative.Linking);
48 return () => {
49 // https://github.com/facebook/react-native/commit/6d1aca806cee86ad76de771ed3a1cc62982ebcd7
50 if (subscription !== null && subscription !== void 0 && subscription.remove) {
51 subscription.remove();
52 } else {
53 removeEventListener === null || removeEventListener === void 0 ? void 0 : removeEventListener('url', callback);
54 }
55 };
56 },
57 getStateFromPath = _core.getStateFromPath,
58 getActionFromState = _core.getActionFromState
59 } = _ref;
60 React.useEffect(() => {
61 if (process.env.NODE_ENV === 'production') {
62 return undefined;
63 }
64
65 if (independent) {
66 return undefined;
67 }
68
69 if (enabled !== false && linkingHandlers.length) {
70 console.error(['Looks like you have configured linking in multiple places. This is likely an error since deep links should only be handled in one place to avoid conflicts. Make sure that:', "- You don't have multiple NavigationContainers in the app each with 'linking' enabled", '- Only a single instance of the root component is rendered', _reactNative.Platform.OS === 'android' ? "- You have set 'android:launchMode=singleTask' in the '<activity />' section of the 'AndroidManifest.xml' file to avoid launching multiple instances" : ''].join('\n').trim());
71 }
72
73 const handler = Symbol();
74
75 if (enabled !== false) {
76 linkingHandlers.push(handler);
77 }
78
79 return () => {
80 const index = linkingHandlers.indexOf(handler);
81
82 if (index > -1) {
83 linkingHandlers.splice(index, 1);
84 }
85 };
86 }, [enabled, independent]); // We store these options in ref to avoid re-creating getInitialState and re-subscribing listeners
87 // This lets user avoid wrapping the items in `React.useCallback` or `React.useMemo`
88 // Not re-creating `getInitialState` is important coz it makes it easier for the user to use in an effect
89
90 const enabledRef = React.useRef(enabled);
91 const prefixesRef = React.useRef(prefixes);
92 const filterRef = React.useRef(filter);
93 const configRef = React.useRef(config);
94 const getInitialURLRef = React.useRef(getInitialURL);
95 const getStateFromPathRef = React.useRef(getStateFromPath);
96 const getActionFromStateRef = React.useRef(getActionFromState);
97 React.useEffect(() => {
98 enabledRef.current = enabled;
99 prefixesRef.current = prefixes;
100 filterRef.current = filter;
101 configRef.current = config;
102 getInitialURLRef.current = getInitialURL;
103 getStateFromPathRef.current = getStateFromPath;
104 getActionFromStateRef.current = getActionFromState;
105 });
106 const getStateFromURL = React.useCallback(url => {
107 if (!url || filterRef.current && !filterRef.current(url)) {
108 return undefined;
109 }
110
111 const path = (0, _extractPathFromURL.default)(prefixesRef.current, url);
112 return path !== undefined ? getStateFromPathRef.current(path, configRef.current) : undefined;
113 }, []);
114 const getInitialState = React.useCallback(() => {
115 let state;
116
117 if (enabledRef.current) {
118 const url = getInitialURLRef.current();
119
120 if (url != null && typeof url !== 'string') {
121 return url.then(url => {
122 const state = getStateFromURL(url);
123 return state;
124 });
125 }
126
127 state = getStateFromURL(url);
128 }
129
130 const thenable = {
131 then(onfulfilled) {
132 return Promise.resolve(onfulfilled ? onfulfilled(state) : state);
133 },
134
135 catch() {
136 return thenable;
137 }
138
139 };
140 return thenable;
141 }, [getStateFromURL]);
142 React.useEffect(() => {
143 const listener = url => {
144 if (!enabled) {
145 return;
146 }
147
148 const navigation = ref.current;
149 const state = navigation ? getStateFromURL(url) : undefined;
150
151 if (navigation && state) {
152 // Make sure that the routes in the state exist in the root navigator
153 // Otherwise there's an error in the linking configuration
154 const rootState = navigation.getRootState();
155
156 if (state.routes.some(r => !(rootState !== null && rootState !== void 0 && rootState.routeNames.includes(r.name)))) {
157 console.warn("The navigation state parsed from the URL contains routes not present in the root navigator. This usually means that the linking configuration doesn't match the navigation structure. See https://reactnavigation.org/docs/configuring-links for more details on how to specify a linking configuration.");
158 return;
159 }
160
161 const action = getActionFromStateRef.current(state, configRef.current);
162
163 if (action !== undefined) {
164 try {
165 navigation.dispatch(action);
166 } catch (e) {
167 // Ignore any errors from deep linking.
168 // This could happen in case of malformed links, navigation object not being initialized etc.
169 console.warn(`An error occurred when trying to handle the link '${url}': ${typeof e === 'object' && e != null && 'message' in e ? // @ts-expect-error: we're already checking for this
170 e.message : e}`);
171 }
172 } else {
173 navigation.resetRoot(state);
174 }
175 }
176 };
177
178 return subscribe(listener);
179 }, [enabled, getStateFromURL, ref, subscribe]);
180 return {
181 getInitialState
182 };
183}
184//# sourceMappingURL=useLinking.native.js.map
\No newline at end of file