1 | import * as React from 'react';
|
2 | import { getStateFromPath, getActionFromState, NavigationContext } from '@react-navigation/core';
|
3 | import LinkingContext from './LinkingContext';
|
4 | export default function useLinkTo() {
|
5 | const navigation = React.useContext(NavigationContext);
|
6 | const linking = React.useContext(LinkingContext);
|
7 | const linkTo = React.useCallback(path => {
|
8 | if (!path.startsWith('/')) {
|
9 | throw new Error("The path must start with '/' (".concat(path, ")."));
|
10 | }
|
11 |
|
12 | if (navigation === undefined) {
|
13 | throw new Error("Couldn't find a navigation object. Is your component inside a screen in a navigator?");
|
14 | }
|
15 |
|
16 | const {
|
17 | options
|
18 | } = linking;
|
19 | const state = options !== null && options !== void 0 && options.getStateFromPath ? options.getStateFromPath(path, options.config) : getStateFromPath(path, options === null || options === void 0 ? void 0 : options.config);
|
20 |
|
21 | if (state) {
|
22 | let root = navigation;
|
23 | let current;
|
24 |
|
25 | while (current = root.dangerouslyGetParent()) {
|
26 | root = current;
|
27 | }
|
28 |
|
29 | const action = getActionFromState(state, options === null || options === void 0 ? void 0 : options.config);
|
30 |
|
31 | if (action !== undefined) {
|
32 | root.dispatch(action);
|
33 | } else {
|
34 | root.reset(state);
|
35 | }
|
36 | } else {
|
37 | throw new Error('Failed to parse the path to a navigation state.');
|
38 | }
|
39 | }, [linking, navigation]);
|
40 | return linkTo;
|
41 | }
|
42 |
|
\ | No newline at end of file |