1 | import type {
|
2 | NavigationState,
|
3 | ParamListBase,
|
4 | Route,
|
5 | } from '@react-navigation/routers';
|
6 | import * as React from 'react';
|
7 |
|
8 | import type { RouteProp } from './types';
|
9 |
|
10 | type RouteCache = Map<Route<string>, RouteProp<ParamListBase>>;
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | export const CHILD_STATE = Symbol('CHILD_STATE');
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | export default function useRouteCache<State extends NavigationState>(
|
24 | routes: State['routes']
|
25 | ) {
|
26 |
|
27 | const cache = React.useMemo(() => ({ current: new Map() as RouteCache }), []);
|
28 |
|
29 | if (process.env.NODE_ENV === 'production') {
|
30 |
|
31 | return routes;
|
32 | }
|
33 |
|
34 | cache.current = routes.reduce((acc, route) => {
|
35 | const previous = cache.current.get(route);
|
36 |
|
37 | if (previous) {
|
38 |
|
39 | acc.set(route, previous);
|
40 | } else {
|
41 | const { state, ...proxy } = route;
|
42 |
|
43 | Object.defineProperty(proxy, CHILD_STATE, {
|
44 | enumerable: false,
|
45 | value: state,
|
46 | });
|
47 |
|
48 | acc.set(route, proxy);
|
49 | }
|
50 |
|
51 | return acc;
|
52 | }, new Map() as RouteCache);
|
53 |
|
54 | return Array.from(cache.current.values());
|
55 | }
|