UNPKG

5.52 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 isUsingLinking = false;
6export default function useLinking(ref, {
7 independent,
8 enabled = true,
9 prefixes,
10 filter,
11 config,
12 getInitialURL = () => Promise.race([Linking.getInitialURL(), new Promise(resolve => // Timeout in 150ms if `getInitialState` doesn't resolve
13 // Workaround for https://github.com/facebook/react-native/issues/25675
14 setTimeout(resolve, 150))]),
15 subscribe = listener => {
16 const callback = ({
17 url
18 }) => listener(url);
19
20 const subscription = Linking.addEventListener('url', callback);
21 return () => {
22 // https://github.com/facebook/react-native/commit/6d1aca806cee86ad76de771ed3a1cc62982ebcd7
23 if (subscription !== null && subscription !== void 0 && subscription.remove) {
24 subscription.remove();
25 } else {
26 Linking.removeEventListener('url', callback);
27 }
28 };
29 },
30 getStateFromPath = getStateFromPathDefault,
31 getActionFromState = getActionFromStateDefault
32}) {
33 React.useEffect(() => {
34 if (independent) {
35 return undefined;
36 }
37
38 if (enabled !== false && isUsingLinking) {
39 throw new 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 are not using both 'linking' prop and 'useLinking'", "- You don't have 'useLinking' in multiple components", 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());
40 } else {
41 isUsingLinking = enabled !== false;
42 }
43
44 return () => {
45 isUsingLinking = false;
46 };
47 }); // We store these options in ref to avoid re-creating getInitialState and re-subscribing listeners
48 // This lets user avoid wrapping the items in `React.useCallback` or `React.useMemo`
49 // Not re-creating `getInitialState` is important coz it makes it easier for the user to use in an effect
50
51 const enabledRef = React.useRef(enabled);
52 const prefixesRef = React.useRef(prefixes);
53 const filterRef = React.useRef(filter);
54 const configRef = React.useRef(config);
55 const getInitialURLRef = React.useRef(getInitialURL);
56 const getStateFromPathRef = React.useRef(getStateFromPath);
57 const getActionFromStateRef = React.useRef(getActionFromState);
58 React.useEffect(() => {
59 enabledRef.current = enabled;
60 prefixesRef.current = prefixes;
61 filterRef.current = filter;
62 configRef.current = config;
63 getInitialURLRef.current = getInitialURL;
64 getStateFromPathRef.current = getStateFromPath;
65 getActionFromStateRef.current = getActionFromState;
66 });
67 const getStateFromURL = React.useCallback(url => {
68 if (!url || filterRef.current && !filterRef.current(url)) {
69 return undefined;
70 }
71
72 const path = extractPathFromURL(prefixesRef.current, url);
73 return path ? getStateFromPathRef.current(path, configRef.current) : undefined;
74 }, []);
75 const getInitialState = React.useCallback(() => {
76 let state;
77
78 if (enabledRef.current) {
79 const url = getInitialURLRef.current();
80
81 if (url != null && typeof url !== 'string') {
82 return url.then(url => {
83 const state = getStateFromURL(url);
84 return state;
85 });
86 }
87
88 state = getStateFromURL(url);
89 }
90
91 const thenable = {
92 then(onfulfilled) {
93 return Promise.resolve(onfulfilled ? onfulfilled(state) : state);
94 },
95
96 catch() {
97 return thenable;
98 }
99
100 };
101 return thenable;
102 }, [getStateFromURL]);
103 React.useEffect(() => {
104 const listener = url => {
105 if (!enabled) {
106 return;
107 }
108
109 const navigation = ref.current;
110 const state = navigation ? getStateFromURL(url) : undefined;
111
112 if (navigation && state) {
113 // Make sure that the routes in the state exist in the root navigator
114 // Otherwise there's an error in the linking configuration
115 const rootState = navigation.getRootState();
116
117 if (state.routes.some(r => !(rootState !== null && rootState !== void 0 && rootState.routeNames.includes(r.name)))) {
118 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.");
119 return;
120 }
121
122 const action = getActionFromStateRef.current(state, configRef.current);
123
124 if (action !== undefined) {
125 try {
126 navigation.dispatch(action);
127 } catch (e) {
128 // Ignore any errors from deep linking.
129 // This could happen in case of malformed links, navigation object not being initialized etc.
130 console.warn(`An error occurred when trying to handle the link '${url}': ${e.message}`);
131 }
132 } else {
133 navigation.resetRoot(state);
134 }
135 }
136 };
137
138 return subscribe(listener);
139 }, [enabled, getStateFromURL, ref, subscribe]);
140 return {
141 getInitialState
142 };
143}
144//# sourceMappingURL=useLinking.native.js.map
\No newline at end of file