UNPKG

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