UNPKG

14.6 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = useLinking;
7var _core = require("@react-navigation/core");
8var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal"));
9var React = _interopRequireWildcard(require("react"));
10var _createMemoryHistory = _interopRequireDefault(require("./createMemoryHistory"));
11var _ServerContext = _interopRequireDefault(require("./ServerContext"));
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; }
14function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15/**
16 * Find the matching navigation state that changed between 2 navigation states
17 * e.g.: a -> b -> c -> d and a -> b -> c -> e -> f, if history in b changed, b is the matching state
18 */
19const findMatchingState = (a, b) => {
20 if (a === undefined || b === undefined || a.key !== b.key) {
21 return [undefined, undefined];
22 }
23
24 // Tab and drawer will have `history` property, but stack will have history in `routes`
25 const aHistoryLength = a.history ? a.history.length : a.routes.length;
26 const bHistoryLength = b.history ? b.history.length : b.routes.length;
27 const aRoute = a.routes[a.index];
28 const bRoute = b.routes[b.index];
29 const aChildState = aRoute.state;
30 const bChildState = bRoute.state;
31
32 // Stop here if this is the state object that changed:
33 // - history length is different
34 // - focused routes are different
35 // - one of them doesn't have child state
36 // - child state keys are different
37 if (aHistoryLength !== bHistoryLength || aRoute.key !== bRoute.key || aChildState === undefined || bChildState === undefined || aChildState.key !== bChildState.key) {
38 return [a, b];
39 }
40 return findMatchingState(aChildState, bChildState);
41};
42
43/**
44 * Run async function in series as it's called.
45 */
46const series = cb => {
47 // Whether we're currently handling a callback
48 let handling = false;
49 let queue = [];
50 const callback = async () => {
51 try {
52 if (handling) {
53 // If we're currently handling a previous event, wait before handling this one
54 // Add the callback to the beginning of the queue
55 queue.unshift(callback);
56 return;
57 }
58 handling = true;
59 await cb();
60 } finally {
61 handling = false;
62 if (queue.length) {
63 // If we have queued items, handle the last one
64 const last = queue.pop();
65 last === null || last === void 0 ? void 0 : last();
66 }
67 }
68 };
69 return callback;
70};
71let linkingHandlers = [];
72function useLinking(ref, _ref) {
73 let {
74 independent,
75 enabled = true,
76 config,
77 getStateFromPath = _core.getStateFromPath,
78 getPathFromState = _core.getPathFromState,
79 getActionFromState = _core.getActionFromState
80 } = _ref;
81 React.useEffect(() => {
82 if (process.env.NODE_ENV === 'production') {
83 return undefined;
84 }
85 if (independent) {
86 return undefined;
87 }
88 if (enabled !== false && linkingHandlers.length) {
89 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'].join('\n').trim());
90 }
91 const handler = Symbol();
92 if (enabled !== false) {
93 linkingHandlers.push(handler);
94 }
95 return () => {
96 const index = linkingHandlers.indexOf(handler);
97 if (index > -1) {
98 linkingHandlers.splice(index, 1);
99 }
100 };
101 }, [enabled, independent]);
102 const [history] = React.useState(_createMemoryHistory.default);
103
104 // We store these options in ref to avoid re-creating getInitialState and re-subscribing listeners
105 // This lets user avoid wrapping the items in `React.useCallback` or `React.useMemo`
106 // Not re-creating `getInitialState` is important coz it makes it easier for the user to use in an effect
107 const enabledRef = React.useRef(enabled);
108 const configRef = React.useRef(config);
109 const getStateFromPathRef = React.useRef(getStateFromPath);
110 const getPathFromStateRef = React.useRef(getPathFromState);
111 const getActionFromStateRef = React.useRef(getActionFromState);
112 React.useEffect(() => {
113 enabledRef.current = enabled;
114 configRef.current = config;
115 getStateFromPathRef.current = getStateFromPath;
116 getPathFromStateRef.current = getPathFromState;
117 getActionFromStateRef.current = getActionFromState;
118 });
119 const server = React.useContext(_ServerContext.default);
120 const getInitialState = React.useCallback(() => {
121 let value;
122 if (enabledRef.current) {
123 const location = (server === null || server === void 0 ? void 0 : server.location) ?? (typeof window !== 'undefined' ? window.location : undefined);
124 const path = location ? location.pathname + location.search : undefined;
125 if (path) {
126 value = getStateFromPathRef.current(path, configRef.current);
127 }
128 }
129 const thenable = {
130 then(onfulfilled) {
131 return Promise.resolve(onfulfilled ? onfulfilled(value) : value);
132 },
133 catch() {
134 return thenable;
135 }
136 };
137 return thenable;
138 // eslint-disable-next-line react-hooks/exhaustive-deps
139 }, []);
140 const previousIndexRef = React.useRef(undefined);
141 const previousStateRef = React.useRef(undefined);
142 const pendingPopStatePathRef = React.useRef(undefined);
143 React.useEffect(() => {
144 previousIndexRef.current = history.index;
145 return history.listen(() => {
146 const navigation = ref.current;
147 if (!navigation || !enabled) {
148 return;
149 }
150 const path = location.pathname + location.search;
151 const index = history.index;
152 const previousIndex = previousIndexRef.current ?? 0;
153 previousIndexRef.current = index;
154 pendingPopStatePathRef.current = path;
155
156 // When browser back/forward is clicked, we first need to check if state object for this index exists
157 // If it does we'll reset to that state object
158 // Otherwise, we'll handle it like a regular deep link
159 const record = history.get(index);
160 if ((record === null || record === void 0 ? void 0 : record.path) === path && record !== null && record !== void 0 && record.state) {
161 navigation.resetRoot(record.state);
162 return;
163 }
164 const state = getStateFromPathRef.current(path, configRef.current);
165
166 // We should only dispatch an action when going forward
167 // Otherwise the action will likely add items to history, which would mess things up
168 if (state) {
169 // Make sure that the routes in the state exist in the root navigator
170 // Otherwise there's an error in the linking configuration
171 const rootState = navigation.getRootState();
172 if (state.routes.some(r => !(rootState !== null && rootState !== void 0 && rootState.routeNames.includes(r.name)))) {
173 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.");
174 return;
175 }
176 if (index > previousIndex) {
177 const action = getActionFromStateRef.current(state, configRef.current);
178 if (action !== undefined) {
179 try {
180 navigation.dispatch(action);
181 } catch (e) {
182 // Ignore any errors from deep linking.
183 // This could happen in case of malformed links, navigation object not being initialized etc.
184 console.warn(`An error occurred when trying to handle the link '${path}': ${typeof e === 'object' && e != null && 'message' in e ?
185 // @ts-expect-error: we're already checking for this
186 e.message : e}`);
187 }
188 } else {
189 navigation.resetRoot(state);
190 }
191 } else {
192 navigation.resetRoot(state);
193 }
194 } else {
195 // if current path didn't return any state, we should revert to initial state
196 navigation.resetRoot(state);
197 }
198 });
199 }, [enabled, history, ref]);
200 React.useEffect(() => {
201 var _ref$current;
202 if (!enabled) {
203 return;
204 }
205 const getPathForRoute = (route, state) => {
206 // If the `route` object contains a `path`, use that path as long as `route.name` and `params` still match
207 // This makes sure that we preserve the original URL for wildcard routes
208 if (route !== null && route !== void 0 && route.path) {
209 const stateForPath = getStateFromPathRef.current(route.path, configRef.current);
210 if (stateForPath) {
211 const focusedRoute = (0, _core.findFocusedRoute)(stateForPath);
212 if (focusedRoute && focusedRoute.name === route.name && (0, _fastDeepEqual.default)(focusedRoute.params, route.params)) {
213 return route.path;
214 }
215 }
216 }
217 return getPathFromStateRef.current(state, configRef.current);
218 };
219 if (ref.current) {
220 // We need to record the current metadata on the first render if they aren't set
221 // This will allow the initial state to be in the history entry
222 const state = ref.current.getRootState();
223 if (state) {
224 const route = (0, _core.findFocusedRoute)(state);
225 const path = getPathForRoute(route, state);
226 if (previousStateRef.current === undefined) {
227 previousStateRef.current = state;
228 }
229 history.replace({
230 path,
231 state
232 });
233 }
234 }
235 const onStateChange = async () => {
236 const navigation = ref.current;
237 if (!navigation || !enabled) {
238 return;
239 }
240 const previousState = previousStateRef.current;
241 const state = navigation.getRootState();
242
243 // root state may not available, for example when root navigators switch inside the container
244 if (!state) {
245 return;
246 }
247 const pendingPath = pendingPopStatePathRef.current;
248 const route = (0, _core.findFocusedRoute)(state);
249 const path = getPathForRoute(route, state);
250 previousStateRef.current = state;
251 pendingPopStatePathRef.current = undefined;
252
253 // To detect the kind of state change, we need to:
254 // - Find the common focused navigation state in previous and current state
255 // - If only the route keys changed, compare history/routes.length to check if we go back/forward/replace
256 // - If no common focused navigation state found, it's a replace
257 const [previousFocusedState, focusedState] = findMatchingState(previousState, state);
258 if (previousFocusedState && focusedState &&
259 // We should only handle push/pop if path changed from what was in last `popstate`
260 // Otherwise it's likely a change triggered by `popstate`
261 path !== pendingPath) {
262 const historyDelta = (focusedState.history ? focusedState.history.length : focusedState.routes.length) - (previousFocusedState.history ? previousFocusedState.history.length : previousFocusedState.routes.length);
263 if (historyDelta > 0) {
264 // If history length is increased, we should pushState
265 // Note that path might not actually change here, for example, drawer open should pushState
266 history.push({
267 path,
268 state
269 });
270 } else if (historyDelta < 0) {
271 // If history length is decreased, i.e. entries were removed, we want to go back
272
273 const nextIndex = history.backIndex({
274 path
275 });
276 const currentIndex = history.index;
277 try {
278 if (nextIndex !== -1 && nextIndex < currentIndex) {
279 // An existing entry for this path exists and it's less than current index, go back to that
280 await history.go(nextIndex - currentIndex);
281 } else {
282 // We couldn't find an existing entry to go back to, so we'll go back by the delta
283 // This won't be correct if multiple routes were pushed in one go before
284 // Usually this shouldn't happen and this is a fallback for that
285 await history.go(historyDelta);
286 }
287
288 // Store the updated state as well as fix the path if incorrect
289 history.replace({
290 path,
291 state
292 });
293 } catch (e) {
294 // The navigation was interrupted
295 }
296 } else {
297 // If history length is unchanged, we want to replaceState
298 history.replace({
299 path,
300 state
301 });
302 }
303 } else {
304 // If no common navigation state was found, assume it's a replace
305 // This would happen if the user did a reset/conditionally changed navigators
306 history.replace({
307 path,
308 state
309 });
310 }
311 };
312
313 // We debounce onStateChange coz we don't want multiple state changes to be handled at one time
314 // This could happen since `history.go(n)` is asynchronous
315 // If `pushState` or `replaceState` were called before `history.go(n)` completes, it'll mess stuff up
316 return (_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : _ref$current.addListener('state', series(onStateChange));
317 }, [enabled, history, ref]);
318 return {
319 getInitialState
320 };
321}
322//# sourceMappingURL=useLinking.js.map
\No newline at end of file