UNPKG

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