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