UNPKG

6.44 kBJavaScriptView Raw
1import { getActionFromState as getActionFromStateDefault, getStateFromPath as getStateFromPathDefault } from '@react-navigation/core';
2import * as React from 'react';
3import { Linking, Platform } from 'react-native';
4import extractPathFromURL from './extractPathFromURL';
5let linkingHandlers = [];
6export default function useLinking(ref, _ref) {
7 let {
8 independent,
9 enabled = true,
10 prefixes,
11 filter,
12 config,
13 getInitialURL = () => Promise.race([Linking.getInitialURL(), new Promise(resolve => // Timeout in 150ms if `getInitialState` doesn't resolve
14 // Workaround for https://github.com/facebook/react-native/issues/25675
15 setTimeout(resolve, 150))]),
16 subscribe = listener => {
17 var _Linking$removeEventL;
18
19 const callback = _ref2 => {
20 let {
21 url
22 } = _ref2;
23 return listener(url);
24 };
25
26 const subscription = Linking.addEventListener('url', callback); // Storing this in a local variable stops Jest from complaining about import after teardown
27
28 const removeEventListener = (_Linking$removeEventL = Linking.removeEventListener) === null || _Linking$removeEventL === void 0 ? void 0 : _Linking$removeEventL.bind(Linking);
29 return () => {
30 // https://github.com/facebook/react-native/commit/6d1aca806cee86ad76de771ed3a1cc62982ebcd7
31 if (subscription !== null && subscription !== void 0 && subscription.remove) {
32 subscription.remove();
33 } else {
34 removeEventListener === null || removeEventListener === void 0 ? void 0 : removeEventListener('url', callback);
35 }
36 };
37 },
38 getStateFromPath = getStateFromPathDefault,
39 getActionFromState = getActionFromStateDefault
40 } = _ref;
41 React.useEffect(() => {
42 if (process.env.NODE_ENV === 'production') {
43 return undefined;
44 }
45
46 if (independent) {
47 return undefined;
48 }
49
50 if (enabled !== false && linkingHandlers.length) {
51 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', 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());
52 }
53
54 const handler = Symbol();
55
56 if (enabled !== false) {
57 linkingHandlers.push(handler);
58 }
59
60 return () => {
61 const index = linkingHandlers.indexOf(handler);
62
63 if (index > -1) {
64 linkingHandlers.splice(index, 1);
65 }
66 };
67 }, [enabled, independent]); // We store these options in ref to avoid re-creating getInitialState and re-subscribing listeners
68 // This lets user avoid wrapping the items in `React.useCallback` or `React.useMemo`
69 // Not re-creating `getInitialState` is important coz it makes it easier for the user to use in an effect
70
71 const enabledRef = React.useRef(enabled);
72 const prefixesRef = React.useRef(prefixes);
73 const filterRef = React.useRef(filter);
74 const configRef = React.useRef(config);
75 const getInitialURLRef = React.useRef(getInitialURL);
76 const getStateFromPathRef = React.useRef(getStateFromPath);
77 const getActionFromStateRef = React.useRef(getActionFromState);
78 React.useEffect(() => {
79 enabledRef.current = enabled;
80 prefixesRef.current = prefixes;
81 filterRef.current = filter;
82 configRef.current = config;
83 getInitialURLRef.current = getInitialURL;
84 getStateFromPathRef.current = getStateFromPath;
85 getActionFromStateRef.current = getActionFromState;
86 });
87 const getStateFromURL = React.useCallback(url => {
88 if (!url || filterRef.current && !filterRef.current(url)) {
89 return undefined;
90 }
91
92 const path = extractPathFromURL(prefixesRef.current, url);
93 return path !== undefined ? getStateFromPathRef.current(path, configRef.current) : undefined;
94 }, []);
95 const getInitialState = React.useCallback(() => {
96 let state;
97
98 if (enabledRef.current) {
99 const url = getInitialURLRef.current();
100
101 if (url != null && typeof url !== 'string') {
102 return url.then(url => {
103 const state = getStateFromURL(url);
104 return state;
105 });
106 }
107
108 state = getStateFromURL(url);
109 }
110
111 const thenable = {
112 then(onfulfilled) {
113 return Promise.resolve(onfulfilled ? onfulfilled(state) : state);
114 },
115
116 catch() {
117 return thenable;
118 }
119
120 };
121 return thenable;
122 }, [getStateFromURL]);
123 React.useEffect(() => {
124 const listener = url => {
125 if (!enabled) {
126 return;
127 }
128
129 const navigation = ref.current;
130 const state = navigation ? getStateFromURL(url) : undefined;
131
132 if (navigation && state) {
133 // Make sure that the routes in the state exist in the root navigator
134 // Otherwise there's an error in the linking configuration
135 const rootState = navigation.getRootState();
136
137 if (state.routes.some(r => !(rootState !== null && rootState !== void 0 && rootState.routeNames.includes(r.name)))) {
138 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.");
139 return;
140 }
141
142 const action = getActionFromStateRef.current(state, configRef.current);
143
144 if (action !== undefined) {
145 try {
146 navigation.dispatch(action);
147 } catch (e) {
148 // Ignore any errors from deep linking.
149 // This could happen in case of malformed links, navigation object not being initialized etc.
150 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
151 e.message : e}`);
152 }
153 } else {
154 navigation.resetRoot(state);
155 }
156 }
157 };
158
159 return subscribe(listener);
160 }, [enabled, getStateFromURL, ref, subscribe]);
161 return {
162 getInitialState
163 };
164}
165//# sourceMappingURL=useLinking.native.js.map
\No newline at end of file