UNPKG

1.79 kBJavaScriptView Raw
1import * as React from 'react';
2import { NavigationHelpersContext, getPathFromState } from '@react-navigation/core';
3import LinkingContext from './LinkingContext';
4
5const getRootStateForNavigate = (navigation, state) => {
6 const parent = navigation.dangerouslyGetParent();
7
8 if (parent) {
9 const parentState = parent.dangerouslyGetState();
10 return getRootStateForNavigate(parent, {
11 index: 0,
12 routes: [{ ...parentState.routes[parentState.index],
13 state: state
14 }]
15 });
16 }
17
18 return state;
19};
20/**
21 * Build destination link for a navigate action.
22 * Useful for showing anchor tags on the web for buttons that perform navigation.
23 */
24
25
26export default function useLinkBuilder() {
27 const navigation = React.useContext(NavigationHelpersContext);
28 const linking = React.useContext(LinkingContext);
29 const buildLink = React.useCallback((name, params) => {
30 const {
31 options
32 } = linking;
33
34 if ((options === null || options === void 0 ? void 0 : options.enabled) === false) {
35 return undefined;
36 }
37
38 const state = navigation ? getRootStateForNavigate(navigation, {
39 index: 0,
40 routes: [{
41 name,
42 params
43 }]
44 }) : // If we couldn't find a navigation object in context, we're at root
45 // So we'll construct a basic state object to use
46 {
47 index: 0,
48 routes: [{
49 name,
50 params
51 }]
52 };
53 const path = options !== null && options !== void 0 && options.getPathFromState ? options.getPathFromState(state, options === null || options === void 0 ? void 0 : options.config) : getPathFromState(state, options === null || options === void 0 ? void 0 : options.config);
54 return path;
55 }, [linking, navigation]);
56 return buildLink;
57}
58//# sourceMappingURL=useLinkBuilder.js.map
\No newline at end of file