@react-navigation/core 6.2.0 → 6.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -11
- package/lib/commonjs/PreventRemoveContext.js +17 -0
- package/lib/commonjs/PreventRemoveContext.js.map +1 -0
- package/lib/commonjs/PreventRemoveProvider.js +114 -0
- package/lib/commonjs/PreventRemoveProvider.js.map +1 -0
- package/lib/commonjs/getStateFromPath.js +1 -1
- package/lib/commonjs/getStateFromPath.js.map +1 -1
- package/lib/commonjs/index.js +36 -0
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/types.js.map +1 -1
- package/lib/commonjs/useChildListeners.js +6 -3
- package/lib/commonjs/useChildListeners.js.map +1 -1
- package/lib/commonjs/useComponent.js +22 -12
- package/lib/commonjs/useComponent.js.map +1 -1
- package/lib/commonjs/useEventEmitter.js +13 -3
- package/lib/commonjs/useEventEmitter.js.map +1 -1
- package/lib/commonjs/useFocusEffect.js +1 -1
- package/lib/commonjs/useFocusEffect.js.map +1 -1
- package/lib/commonjs/useKeyedChildListeners.js +4 -2
- package/lib/commonjs/useKeyedChildListeners.js.map +1 -1
- package/lib/commonjs/useNavigationBuilder.js +4 -2
- package/lib/commonjs/useNavigationBuilder.js.map +1 -1
- package/lib/commonjs/useNavigationHelpers.js +0 -4
- package/lib/commonjs/useNavigationHelpers.js.map +1 -1
- package/lib/commonjs/usePreventRemove.js +59 -0
- package/lib/commonjs/usePreventRemove.js.map +1 -0
- package/lib/commonjs/usePreventRemoveContext.js +27 -0
- package/lib/commonjs/usePreventRemoveContext.js.map +1 -0
- package/lib/module/PreventRemoveContext.js +9 -0
- package/lib/module/PreventRemoveContext.js.map +1 -0
- package/lib/module/PreventRemoveProvider.js +96 -0
- package/lib/module/PreventRemoveProvider.js.map +1 -0
- package/lib/module/getStateFromPath.js +1 -1
- package/lib/module/getStateFromPath.js.map +1 -1
- package/lib/module/index.js +4 -0
- package/lib/module/index.js.map +1 -1
- package/lib/module/types.js.map +1 -1
- package/lib/module/useChildListeners.js +6 -3
- package/lib/module/useChildListeners.js.map +1 -1
- package/lib/module/useComponent.js +23 -12
- package/lib/module/useComponent.js.map +1 -1
- package/lib/module/useEventEmitter.js +13 -3
- package/lib/module/useEventEmitter.js.map +1 -1
- package/lib/module/useFocusEffect.js +1 -1
- package/lib/module/useFocusEffect.js.map +1 -1
- package/lib/module/useKeyedChildListeners.js +4 -2
- package/lib/module/useKeyedChildListeners.js.map +1 -1
- package/lib/module/useNavigationBuilder.js +3 -2
- package/lib/module/useNavigationBuilder.js.map +1 -1
- package/lib/module/useNavigationHelpers.js +0 -4
- package/lib/module/useNavigationHelpers.js.map +1 -1
- package/lib/module/usePreventRemove.js +41 -0
- package/lib/module/usePreventRemove.js.map +1 -0
- package/lib/module/usePreventRemoveContext.js +12 -0
- package/lib/module/usePreventRemoveContext.js.map +1 -0
- package/lib/typescript/src/NavigationBuilderContext.d.ts +1 -1
- package/lib/typescript/src/PreventRemoveContext.d.ts +13 -0
- package/lib/typescript/src/PreventRemoveProvider.d.ts +9 -0
- package/lib/typescript/src/index.d.ts +4 -0
- package/lib/typescript/src/types.d.ts +10 -6
- package/lib/typescript/src/useComponent.d.ts +5 -1
- package/lib/typescript/src/useDescriptors.d.ts +3 -3
- package/lib/typescript/src/useNavigationBuilder.d.ts +9 -7
- package/lib/typescript/src/useNavigationHelpers.d.ts +3 -3
- package/lib/typescript/src/usePreventRemove.d.ts +12 -0
- package/lib/typescript/src/usePreventRemoveContext.d.ts +4 -0
- package/package.json +10 -9
- package/src/PreventRemoveContext.tsx +21 -0
- package/src/PreventRemoveProvider.tsx +126 -0
- package/src/getStateFromPath.tsx +4 -1
- package/src/index.tsx +4 -0
- package/src/types.tsx +39 -14
- package/src/useChildListeners.tsx +5 -3
- package/src/useComponent.tsx +19 -12
- package/src/useEventEmitter.tsx +14 -3
- package/src/useFocusEffect.tsx +1 -1
- package/src/useKeyedChildListeners.tsx +8 -4
- package/src/useNavigationBuilder.tsx +6 -3
- package/src/useNavigationHelpers.tsx +0 -6
- package/src/usePreventRemove.tsx +51 -0
- package/src/usePreventRemoveContext.tsx +15 -0
package/README.md
CHANGED
|
@@ -15,22 +15,28 @@ yarn add @react-navigation/core
|
|
|
15
15
|
A basic custom navigator bundling a router and a view looks like this:
|
|
16
16
|
|
|
17
17
|
```js
|
|
18
|
-
import {
|
|
18
|
+
import {
|
|
19
|
+
createNavigatorFactory,
|
|
20
|
+
useNavigationBuilder,
|
|
21
|
+
} from '@react-navigation/core';
|
|
19
22
|
import { StackRouter } from '@react-navigation/routers';
|
|
20
23
|
|
|
21
24
|
function StackNavigator({ initialRouteName, children, ...rest }) {
|
|
22
|
-
const { state, navigation, descriptors } =
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
const { state, navigation, descriptors, NavigationContent } =
|
|
26
|
+
useNavigationBuilder(StackRouter, {
|
|
27
|
+
initialRouteName,
|
|
28
|
+
children,
|
|
29
|
+
});
|
|
26
30
|
|
|
27
31
|
return (
|
|
28
|
-
<
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
<NavigationContent>
|
|
33
|
+
<StackView
|
|
34
|
+
state={state}
|
|
35
|
+
navigation={navigation}
|
|
36
|
+
descriptors={descriptors}
|
|
37
|
+
{...rest}
|
|
38
|
+
/>
|
|
39
|
+
</NavigationContent>
|
|
34
40
|
);
|
|
35
41
|
}
|
|
36
42
|
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.default = void 0;
|
|
7
|
+
|
|
8
|
+
var React = _interopRequireWildcard(require("react"));
|
|
9
|
+
|
|
10
|
+
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); }
|
|
11
|
+
|
|
12
|
+
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; }
|
|
13
|
+
|
|
14
|
+
const PreventRemoveContext = /*#__PURE__*/React.createContext(undefined);
|
|
15
|
+
var _default = PreventRemoveContext;
|
|
16
|
+
exports.default = _default;
|
|
17
|
+
//# sourceMappingURL=PreventRemoveContext.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["PreventRemoveContext.tsx"],"names":["PreventRemoveContext","React","createContext","undefined"],"mappings":";;;;;;;AAAA;;;;;;AAQA,MAAMA,oBAAoB,gBAAGC,KAAK,CAACC,aAAN,CAU3BC,SAV2B,CAA7B;eAYeH,oB","sourcesContent":["import * as React from 'react';\n\n/**\n * A type of an object that have a route key as an object key\n * and a value whether to prevent that route.\n */\nexport type PreventedRoutes = Record<string, { preventRemove: boolean }>;\n\nconst PreventRemoveContext = React.createContext<\n | {\n preventedRoutes: PreventedRoutes;\n setPreventRemove: (\n id: string,\n routeKey: string,\n preventRemove: boolean\n ) => void;\n }\n | undefined\n>(undefined);\n\nexport default PreventRemoveContext;\n"]}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.default = PreventRemoveProvider;
|
|
7
|
+
|
|
8
|
+
var _nonSecure = require("nanoid/non-secure");
|
|
9
|
+
|
|
10
|
+
var React = _interopRequireWildcard(require("react"));
|
|
11
|
+
|
|
12
|
+
var _useLatestCallback = _interopRequireDefault(require("use-latest-callback"));
|
|
13
|
+
|
|
14
|
+
var _NavigationHelpersContext = _interopRequireDefault(require("./NavigationHelpersContext"));
|
|
15
|
+
|
|
16
|
+
var _NavigationRouteContext = _interopRequireDefault(require("./NavigationRouteContext"));
|
|
17
|
+
|
|
18
|
+
var _PreventRemoveContext = _interopRequireDefault(require("./PreventRemoveContext"));
|
|
19
|
+
|
|
20
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
21
|
+
|
|
22
|
+
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); }
|
|
23
|
+
|
|
24
|
+
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; }
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Util function to transform map of prevented routes to a simpler object.
|
|
28
|
+
*/
|
|
29
|
+
const transformPreventedRoutes = preventedRoutesMap => {
|
|
30
|
+
const preventedRoutesToTransform = [...preventedRoutesMap.values()];
|
|
31
|
+
const preventedRoutes = preventedRoutesToTransform.reduce((acc, _ref) => {
|
|
32
|
+
var _acc$routeKey;
|
|
33
|
+
|
|
34
|
+
let {
|
|
35
|
+
routeKey,
|
|
36
|
+
preventRemove
|
|
37
|
+
} = _ref;
|
|
38
|
+
acc[routeKey] = {
|
|
39
|
+
preventRemove: ((_acc$routeKey = acc[routeKey]) === null || _acc$routeKey === void 0 ? void 0 : _acc$routeKey.preventRemove) || preventRemove
|
|
40
|
+
};
|
|
41
|
+
return acc;
|
|
42
|
+
}, {});
|
|
43
|
+
return preventedRoutes;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Component used for managing which routes have to be prevented from removal in native-stack.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
function PreventRemoveProvider(_ref2) {
|
|
51
|
+
let {
|
|
52
|
+
children
|
|
53
|
+
} = _ref2;
|
|
54
|
+
const [parentId] = React.useState(() => (0, _nonSecure.nanoid)());
|
|
55
|
+
const [preventedRoutesMap, setPreventedRoutesMap] = React.useState(new Map());
|
|
56
|
+
const navigation = React.useContext(_NavigationHelpersContext.default);
|
|
57
|
+
const route = React.useContext(_NavigationRouteContext.default);
|
|
58
|
+
const preventRemoveContextValue = React.useContext(_PreventRemoveContext.default); // take `setPreventRemove` from parent context - if exist it means we're in a nested context
|
|
59
|
+
|
|
60
|
+
const setParentPrevented = preventRemoveContextValue === null || preventRemoveContextValue === void 0 ? void 0 : preventRemoveContextValue.setPreventRemove;
|
|
61
|
+
const setPreventRemove = (0, _useLatestCallback.default)((id, routeKey, preventRemove) => {
|
|
62
|
+
if (preventRemove && (navigation == null || navigation !== null && navigation !== void 0 && navigation.getState().routes.every(route => route.key !== routeKey))) {
|
|
63
|
+
throw new Error(`Couldn't find a route with the key ${routeKey}. Is your component inside NavigationContent?`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
setPreventedRoutesMap(prevPrevented => {
|
|
67
|
+
var _prevPrevented$get, _prevPrevented$get2;
|
|
68
|
+
|
|
69
|
+
// values haven't changed - do nothing
|
|
70
|
+
if (routeKey === ((_prevPrevented$get = prevPrevented.get(id)) === null || _prevPrevented$get === void 0 ? void 0 : _prevPrevented$get.routeKey) && preventRemove === ((_prevPrevented$get2 = prevPrevented.get(id)) === null || _prevPrevented$get2 === void 0 ? void 0 : _prevPrevented$get2.preventRemove)) {
|
|
71
|
+
return prevPrevented;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const nextPrevented = new Map(prevPrevented);
|
|
75
|
+
|
|
76
|
+
if (preventRemove) {
|
|
77
|
+
nextPrevented.set(id, {
|
|
78
|
+
routeKey,
|
|
79
|
+
preventRemove
|
|
80
|
+
});
|
|
81
|
+
} else {
|
|
82
|
+
nextPrevented.delete(id);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return nextPrevented;
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
const isPrevented = [...preventedRoutesMap.values()].some(_ref3 => {
|
|
89
|
+
let {
|
|
90
|
+
preventRemove
|
|
91
|
+
} = _ref3;
|
|
92
|
+
return preventRemove;
|
|
93
|
+
});
|
|
94
|
+
React.useEffect(() => {
|
|
95
|
+
if ((route === null || route === void 0 ? void 0 : route.key) !== undefined && setParentPrevented !== undefined) {
|
|
96
|
+
// when route is defined (and setParentPrevented) it means we're in a nested stack
|
|
97
|
+
// route.key then will be the route key of parent
|
|
98
|
+
setParentPrevented(parentId, route.key, isPrevented);
|
|
99
|
+
return () => {
|
|
100
|
+
setParentPrevented(parentId, route.key, false);
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return;
|
|
105
|
+
}, [parentId, isPrevented, route === null || route === void 0 ? void 0 : route.key, setParentPrevented]);
|
|
106
|
+
const value = React.useMemo(() => ({
|
|
107
|
+
setPreventRemove,
|
|
108
|
+
preventedRoutes: transformPreventedRoutes(preventedRoutesMap)
|
|
109
|
+
}), [setPreventRemove, preventedRoutesMap]);
|
|
110
|
+
return /*#__PURE__*/React.createElement(_PreventRemoveContext.default.Provider, {
|
|
111
|
+
value: value
|
|
112
|
+
}, children);
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=PreventRemoveProvider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["PreventRemoveProvider.tsx"],"names":["transformPreventedRoutes","preventedRoutesMap","preventedRoutesToTransform","values","preventedRoutes","reduce","acc","routeKey","preventRemove","PreventRemoveProvider","children","parentId","React","useState","setPreventedRoutesMap","Map","navigation","useContext","NavigationHelpersContext","route","NavigationRouteContext","preventRemoveContextValue","PreventRemoveContext","setParentPrevented","setPreventRemove","id","getState","routes","every","key","Error","prevPrevented","get","nextPrevented","set","delete","isPrevented","some","useEffect","undefined","value","useMemo"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AAEA;;AACA;;AACA;;;;;;;;AAcA;AACA;AACA;AACA,MAAMA,wBAAwB,GAC5BC,kBAD+B,IAEX;AACpB,QAAMC,0BAA0B,GAAG,CAAC,GAAGD,kBAAkB,CAACE,MAAnB,EAAJ,CAAnC;AAEA,QAAMC,eAAe,GAAGF,0BAA0B,CAACG,MAA3B,CACtB,CAACC,GAAD,WAAsC;AAAA;;AAAA,QAAhC;AAAEC,MAAAA,QAAF;AAAYC,MAAAA;AAAZ,KAAgC;AACpCF,IAAAA,GAAG,CAACC,QAAD,CAAH,GAAgB;AACdC,MAAAA,aAAa,EAAE,kBAAAF,GAAG,CAACC,QAAD,CAAH,gEAAeC,aAAf,KAAgCA;AADjC,KAAhB;AAGA,WAAOF,GAAP;AACD,GANqB,EAOtB,EAPsB,CAAxB;AAUA,SAAOF,eAAP;AACD,CAhBD;AAkBA;AACA;AACA;;;AACe,SAASK,qBAAT,QAAoD;AAAA,MAAr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nanoid } from 'nanoid/non-secure';\nimport * as React from 'react';\nimport useLatestCallback from 'use-latest-callback';\n\nimport NavigationHelpersContext from './NavigationHelpersContext';\nimport NavigationRouteContext from './NavigationRouteContext';\nimport PreventRemoveContext, { PreventedRoutes } from './PreventRemoveContext';\n\ntype Props = {\n children: React.ReactNode;\n};\n\ntype PreventedRoutesMap = Map<\n string,\n {\n routeKey: string;\n preventRemove: boolean;\n }\n>;\n\n/**\n * Util function to transform map of prevented routes to a simpler object.\n */\nconst transformPreventedRoutes = (\n preventedRoutesMap: PreventedRoutesMap\n): PreventedRoutes => {\n const preventedRoutesToTransform = [...preventedRoutesMap.values()];\n\n const preventedRoutes = preventedRoutesToTransform.reduce<PreventedRoutes>(\n (acc, { routeKey, preventRemove }) => {\n acc[routeKey] = {\n preventRemove: acc[routeKey]?.preventRemove || preventRemove,\n };\n return acc;\n },\n {}\n );\n\n return preventedRoutes;\n};\n\n/**\n * Component used for managing which routes have to be prevented from removal in native-stack.\n */\nexport default function PreventRemoveProvider({ children }: Props) {\n const [parentId] = React.useState(() => nanoid());\n const [preventedRoutesMap, setPreventedRoutesMap] =\n React.useState<PreventedRoutesMap>(new Map());\n\n const navigation = React.useContext(NavigationHelpersContext);\n const route = React.useContext(NavigationRouteContext);\n\n const preventRemoveContextValue = React.useContext(PreventRemoveContext);\n // take `setPreventRemove` from parent context - if exist it means we're in a nested context\n const setParentPrevented = preventRemoveContextValue?.setPreventRemove;\n\n const setPreventRemove = useLatestCallback(\n (id: string, routeKey: string, preventRemove: boolean): void => {\n if (\n preventRemove &&\n (navigation == null ||\n navigation\n ?.getState()\n .routes.every((route) => route.key !== routeKey))\n ) {\n throw new Error(\n `Couldn't find a route with the key ${routeKey}. Is your component inside NavigationContent?`\n );\n }\n\n setPreventedRoutesMap((prevPrevented) => {\n // values haven't changed - do nothing\n if (\n routeKey === prevPrevented.get(id)?.routeKey &&\n preventRemove === prevPrevented.get(id)?.preventRemove\n ) {\n return prevPrevented;\n }\n\n const nextPrevented = new Map(prevPrevented);\n\n if (preventRemove) {\n nextPrevented.set(id, {\n routeKey,\n preventRemove,\n });\n } else {\n nextPrevented.delete(id);\n }\n\n return nextPrevented;\n });\n }\n );\n\n const isPrevented = [...preventedRoutesMap.values()].some(\n ({ preventRemove }) => preventRemove\n );\n\n React.useEffect(() => {\n if (route?.key !== undefined && setParentPrevented !== undefined) {\n // when route is defined (and setParentPrevented) it means we're in a nested stack\n // route.key then will be the route key of parent\n setParentPrevented(parentId, route.key, isPrevented);\n return () => {\n setParentPrevented(parentId, route.key, false);\n };\n }\n\n return;\n }, [parentId, isPrevented, route?.key, setParentPrevented]);\n\n const value = React.useMemo(\n () => ({\n setPreventRemove,\n preventedRoutes: transformPreventedRoutes(preventedRoutesMap),\n }),\n [setPreventRemove, preventedRoutesMap]\n );\n\n return (\n <PreventRemoveContext.Provider value={value}>\n {children}\n </PreventRemoveContext.Provider>\n );\n}\n"]}
|
|
@@ -449,7 +449,7 @@ const parseQueryParams = (path, parseConfig) => {
|
|
|
449
449
|
|
|
450
450
|
if (parseConfig) {
|
|
451
451
|
Object.keys(params).forEach(name => {
|
|
452
|
-
if (parseConfig
|
|
452
|
+
if (Object.hasOwnProperty.call(parseConfig, name) && typeof params[name] === 'string') {
|
|
453
453
|
params[name] = parseConfig[name](params[name]);
|
|
454
454
|
}
|
|
455
455
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["getStateFromPath.tsx"],"names":["getStateFromPath","path","options","initialRoutes","initialRouteName","push","parentScreens","screens","remaining","replace","endsWith","undefined","routes","split","filter","Boolean","map","segment","name","decodeURIComponent","length","createNestedStateObject","configs","concat","Object","keys","key","createNormalizedConfigs","sort","a","b","pattern","routeNames","join","localeCompare","startsWith","aParts","bParts","i","Math","max","aWildCard","bWildCard","reduce","acc","config","intersects","every","it","Error","assign","match","find","c","screen","result","current","remainingPath","matchAgainstConfigs","regex","RegExp","source","joinPaths","paths","p","matchedParams","params","value","parse","routeConfig","initials","parentPattern","createConfigItem","exact","forEach","nestedConfig","pop","findParseConfigForRoute","routeName","flatConfig","findInitialRoute","sameParents","createStateObject","initialRoute","route","isEmpty","index","state","shift","nestedState","nestedStateIndex","parseQueryParams","parseConfig","query","queryString"],"mappings":";;;;;;;AAKA;;AACA;;AAEA;;AAEA;;;;;;;;AAiCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASA,gBAAT,CACbC,IADa,EAEbC,OAFa,EAGY;AACzB,MAAIA,OAAJ,EAAa;AACX,qCAAmBA,OAAnB;AACD;;AAED,MAAIC,aAAmC,GAAG,EAA1C;;AAEA,MAAID,OAAJ,aAAIA,OAAJ,eAAIA,OAAO,CAAEE,gBAAb,EAA+B;AAC7BD,IAAAA,aAAa,CAACE,IAAd,CAAmB;AACjBD,MAAAA,gBAAgB,EAAEF,OAAO,CAACE,gBADT;AAEjBE,MAAAA,aAAa,EAAE;AAFE,KAAnB;AAID;;AAED,QAAMC,OAAO,GAAGL,OAAH,aAAGA,OAAH,uBAAGA,OAAO,CAAEK,OAAzB;AAEA,MAAIC,SAAS,GAAGP,IAAI,CACjBQ,OADa,CACL,MADK,EACG,GADH,EACQ;AADR,GAEbA,OAFa,CAEL,KAFK,EAEE,EAFF,EAEM;AAFN,GAGbA,OAHa,CAGL,OAHK,EAGI,EAHJ,CAAhB,CAhByB,CAmBA;AAEzB;;AACAD,EAAAA,SAAS,GAAGA,SAAS,CAACE,QAAV,CAAmB,GAAnB,IAA0BF,SAA1B,GAAuC,GAAEA,SAAU,GAA/D;;AAEA,MAAID,OAAO,KAAKI,SAAhB,EAA2B;AACzB;AACA,UAAMC,MAAM,GAAGJ,SAAS,CACrBK,KADY,CACN,GADM,EAEZC,MAFY,CAELC,OAFK,EAGZC,GAHY,CAGPC,OAAD,IAAa;AAChB,YAAMC,IAAI,GAAGC,kBAAkB,CAACF,OAAD,CAA/B;AACA,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,MAAM,CAACC,IAAP,CAAYyC,MAAZ,EAAoB9C,MAApB,GAA6B8C,MAA7B,GAAsCvD,SAA7C;AACD,CAhBD","sourcesContent":["import type {\n InitialState,\n NavigationState,\n PartialState,\n} from '@react-navigation/routers';\nimport escape from 'escape-string-regexp';\nimport * as queryString from 'query-string';\n\nimport findFocusedRoute from './findFocusedRoute';\nimport type { PathConfigMap } from './types';\nimport validatePathConfig from './validatePathConfig';\n\ntype Options<ParamList extends {}> = {\n initialRouteName?: string;\n screens: PathConfigMap<ParamList>;\n};\n\ntype ParseConfig = Record<string, (value: string) => any>;\n\ntype RouteConfig = {\n screen: string;\n regex?: RegExp;\n path: string;\n pattern: string;\n routeNames: string[];\n parse?: ParseConfig;\n};\n\ntype InitialRouteConfig = {\n initialRouteName: string;\n parentScreens: string[];\n};\n\ntype ResultState = PartialState<NavigationState> & {\n state?: ResultState;\n};\n\ntype ParsedRoute = {\n name: string;\n path?: string;\n params?: Record<string, any> | undefined;\n};\n\n/**\n * Utility to parse a path string to initial state object accepted by the container.\n * This is useful for deep linking when we need to handle the incoming URL.\n *\n * @example\n * ```js\n * getStateFromPath(\n * '/chat/jane/42',\n * {\n * screens: {\n * Chat: {\n * path: 'chat/:author/:id',\n * parse: { id: Number }\n * }\n * }\n * }\n * )\n * ```\n * @param path Path string to parse and convert, e.g. /foo/bar?count=42.\n * @param options Extra options to fine-tune how to parse the path.\n */\nexport default function getStateFromPath<ParamList extends {}>(\n path: string,\n options?: Options<ParamList>\n): ResultState | undefined {\n if (options) {\n validatePathConfig(options);\n }\n\n let initialRoutes: InitialRouteConfig[] = [];\n\n if (options?.initialRouteName) {\n initialRoutes.push({\n initialRouteName: options.initialRouteName,\n parentScreens: [],\n });\n }\n\n const screens = options?.screens;\n\n let remaining = path\n .replace(/\\/+/g, '/') // Replace multiple slash (//) with single ones\n .replace(/^\\//, '') // Remove extra leading slash\n .replace(/\\?.*$/, ''); // Remove query params which we will handle later\n\n // Make sure there is a trailing slash\n remaining = remaining.endsWith('/') ? remaining : `${remaining}/`;\n\n if (screens === undefined) {\n // When no config is specified, use the path segments as route names\n const routes = remaining\n .split('/')\n .filter(Boolean)\n .map((segment) => {\n const name = decodeURIComponent(segment);\n return { name };\n });\n\n if (routes.length) {\n return createNestedStateObject(path, routes, initialRoutes);\n }\n\n return undefined;\n }\n\n // Create a normalized configs array which will be easier to use\n const configs = ([] as RouteConfig[])\n .concat(\n ...Object.keys(screens).map((key) =>\n createNormalizedConfigs(\n key,\n screens as PathConfigMap<object>,\n [],\n initialRoutes,\n []\n )\n )\n )\n .sort((a, b) => {\n // Sort config so that:\n // - the most exhaustive ones are always at the beginning\n // - patterns with wildcard are always at the end\n\n // If 2 patterns are same, move the one with less route names up\n // This is an error state, so it's only useful for consistent error messages\n if (a.pattern === b.pattern) {\n return b.routeNames.join('>').localeCompare(a.routeNames.join('>'));\n }\n\n // If one of the patterns starts with the other, it's more exhaustive\n // So move it up\n if (a.pattern.startsWith(b.pattern)) {\n return -1;\n }\n\n if (b.pattern.startsWith(a.pattern)) {\n return 1;\n }\n\n const aParts = a.pattern.split('/');\n const bParts = b.pattern.split('/');\n\n for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {\n // if b is longer, b get higher priority\n if (aParts[i] == null) {\n return 1;\n }\n // if a is longer, a get higher priority\n if (bParts[i] == null) {\n return -1;\n }\n const aWildCard = aParts[i] === '*' || aParts[i].startsWith(':');\n const bWildCard = bParts[i] === '*' || bParts[i].startsWith(':');\n // if both are wildcard we compare next component\n if (aWildCard && bWildCard) {\n continue;\n }\n // if only a is wild card, b get higher priority\n if (aWildCard) {\n return 1;\n }\n // if only b is wild card, a get higher priority\n if (bWildCard) {\n return -1;\n }\n }\n return bParts.length - aParts.length;\n });\n\n // Check for duplicate patterns in the config\n configs.reduce<Record<string, RouteConfig>>((acc, config) => {\n if (acc[config.pattern]) {\n const a = acc[config.pattern].routeNames;\n const b = config.routeNames;\n\n // It's not a problem if the path string omitted from a inner most screen\n // For example, it's ok if a path resolves to `A > B > C` or `A > B`\n const intersects =\n a.length > b.length\n ? b.every((it, i) => a[i] === it)\n : a.every((it, i) => b[i] === it);\n\n if (!intersects) {\n throw new Error(\n `Found conflicting screens with the same pattern. The pattern '${\n config.pattern\n }' resolves to both '${a.join(' > ')}' and '${b.join(\n ' > '\n )}'. Patterns must be unique and cannot resolve to more than one screen.`\n );\n }\n }\n\n return Object.assign(acc, {\n [config.pattern]: config,\n });\n }, {});\n\n if (remaining === '/') {\n // We need to add special handling of empty path so navigation to empty path also works\n // When handling empty path, we should only look at the root level config\n const match = configs.find(\n (config) =>\n config.path === '' &&\n config.routeNames.every(\n // Make sure that none of the parent configs have a non-empty path defined\n (name) => !configs.find((c) => c.screen === name)?.path\n )\n );\n\n if (match) {\n return createNestedStateObject(\n path,\n match.routeNames.map((name) => ({ name })),\n initialRoutes,\n configs\n );\n }\n\n return undefined;\n }\n\n let result: PartialState<NavigationState> | undefined;\n let current: PartialState<NavigationState> | undefined;\n\n // We match the whole path against the regex instead of segments\n // This makes sure matches such as wildcard will catch any unmatched routes, even if nested\n const { routes, remainingPath } = matchAgainstConfigs(\n remaining,\n configs.map((c) => ({\n ...c,\n // Add `$` to the regex to make sure it matches till end of the path and not just beginning\n regex: c.regex ? new RegExp(c.regex.source + '$') : undefined,\n }))\n );\n\n if (routes !== undefined) {\n // This will always be empty if full path matched\n current = createNestedStateObject(path, routes, initialRoutes, configs);\n remaining = remainingPath;\n result = current;\n }\n\n if (current == null || result == null) {\n return undefined;\n }\n\n return result;\n}\n\nconst joinPaths = (...paths: string[]): string =>\n ([] as string[])\n .concat(...paths.map((p) => p.split('/')))\n .filter(Boolean)\n .join('/');\n\nconst matchAgainstConfigs = (remaining: string, configs: RouteConfig[]) => {\n let routes: ParsedRoute[] | undefined;\n let remainingPath = remaining;\n\n // Go through all configs, and see if the next path segment matches our regex\n for (const config of configs) {\n if (!config.regex) {\n continue;\n }\n\n const match = remainingPath.match(config.regex);\n\n // If our regex matches, we need to extract params from the path\n if (match) {\n const matchedParams = config.pattern\n ?.split('/')\n .filter((p) => p.startsWith(':'))\n .reduce<Record<string, any>>(\n (acc, p, i) =>\n Object.assign(acc, {\n // The param segments appear every second item starting from 2 in the regex match result\n [p]: match![(i + 1) * 2].replace(/\\//, ''),\n }),\n {}\n );\n\n routes = config.routeNames.map((name) => {\n const config = configs.find((c) => c.screen === name);\n const params = config?.path\n ?.split('/')\n .filter((p) => p.startsWith(':'))\n .reduce<Record<string, any>>((acc, p) => {\n const value = matchedParams[p];\n\n if (value) {\n const key = p.replace(/^:/, '').replace(/\\?$/, '');\n acc[key] = config.parse?.[key] ? config.parse[key](value) : value;\n }\n\n return acc;\n }, {});\n\n if (params && Object.keys(params).length) {\n return { name, params };\n }\n\n return { name };\n });\n\n remainingPath = remainingPath.replace(match[1], '');\n\n break;\n }\n }\n\n return { routes, remainingPath };\n};\n\nconst createNormalizedConfigs = (\n screen: string,\n routeConfig: PathConfigMap<object>,\n routeNames: string[] = [],\n initials: InitialRouteConfig[],\n parentScreens: string[],\n parentPattern?: string\n): RouteConfig[] => {\n const configs: RouteConfig[] = [];\n\n routeNames.push(screen);\n\n parentScreens.push(screen);\n\n // @ts-expect-error: we can't strongly typecheck this for now\n const config = routeConfig[screen];\n\n if (typeof config === 'string') {\n // If a string is specified as the value of the key(e.g. Foo: '/path'), use it as the pattern\n const pattern = parentPattern ? joinPaths(parentPattern, config) : config;\n\n configs.push(createConfigItem(screen, routeNames, pattern, config));\n } else if (typeof config === 'object') {\n let pattern: string | undefined;\n\n // if an object is specified as the value (e.g. Foo: { ... }),\n // it can have `path` property and\n // it could have `screens` prop which has nested configs\n if (typeof config.path === 'string') {\n if (config.exact && config.path === undefined) {\n throw new Error(\n \"A 'path' needs to be specified when specifying 'exact: true'. If you don't want this screen in the URL, specify it as empty string, e.g. `path: ''`.\"\n );\n }\n\n pattern =\n config.exact !== true\n ? joinPaths(parentPattern || '', config.path || '')\n : config.path || '';\n\n configs.push(\n createConfigItem(\n screen,\n routeNames,\n pattern!,\n config.path,\n config.parse\n )\n );\n }\n\n if (config.screens) {\n // property `initialRouteName` without `screens` has no purpose\n if (config.initialRouteName) {\n initials.push({\n initialRouteName: config.initialRouteName,\n parentScreens,\n });\n }\n\n Object.keys(config.screens).forEach((nestedConfig) => {\n const result = createNormalizedConfigs(\n nestedConfig,\n config.screens as PathConfigMap<object>,\n routeNames,\n initials,\n [...parentScreens],\n pattern ?? parentPattern\n );\n\n configs.push(...result);\n });\n }\n }\n\n routeNames.pop();\n\n return configs;\n};\n\nconst createConfigItem = (\n screen: string,\n routeNames: string[],\n pattern: string,\n path: string,\n parse?: ParseConfig\n): RouteConfig => {\n // Normalize pattern to remove any leading, trailing slashes, duplicate slashes etc.\n pattern = pattern.split('/').filter(Boolean).join('/');\n\n const regex = pattern\n ? new RegExp(\n `^(${pattern\n .split('/')\n .map((it) => {\n if (it.startsWith(':')) {\n return `(([^/]+\\\\/)${it.endsWith('?') ? '?' : ''})`;\n }\n\n return `${it === '*' ? '.*' : escape(it)}\\\\/`;\n })\n .join('')})`\n )\n : undefined;\n\n return {\n screen,\n regex,\n pattern,\n path,\n // The routeNames array is mutated, so copy it to keep the current state\n routeNames: [...routeNames],\n parse,\n };\n};\n\nconst findParseConfigForRoute = (\n routeName: string,\n flatConfig: RouteConfig[]\n): ParseConfig | undefined => {\n for (const config of flatConfig) {\n if (routeName === config.routeNames[config.routeNames.length - 1]) {\n return config.parse;\n }\n }\n\n return undefined;\n};\n\n// Try to find an initial route connected with the one passed\nconst findInitialRoute = (\n routeName: string,\n parentScreens: string[],\n initialRoutes: InitialRouteConfig[]\n): string | undefined => {\n for (const config of initialRoutes) {\n if (parentScreens.length === config.parentScreens.length) {\n let sameParents = true;\n for (let i = 0; i < parentScreens.length; i++) {\n if (parentScreens[i].localeCompare(config.parentScreens[i]) !== 0) {\n sameParents = false;\n break;\n }\n }\n if (sameParents) {\n return routeName !== config.initialRouteName\n ? config.initialRouteName\n : undefined;\n }\n }\n }\n return undefined;\n};\n\n// returns state object with values depending on whether\n// it is the end of state and if there is initialRoute for this level\nconst createStateObject = (\n initialRoute: string | undefined,\n route: ParsedRoute,\n isEmpty: boolean\n): InitialState => {\n if (isEmpty) {\n if (initialRoute) {\n return {\n index: 1,\n routes: [{ name: initialRoute }, route],\n };\n } else {\n return {\n routes: [route],\n };\n }\n } else {\n if (initialRoute) {\n return {\n index: 1,\n routes: [{ name: initialRoute }, { ...route, state: { routes: [] } }],\n };\n } else {\n return {\n routes: [{ ...route, state: { routes: [] } }],\n };\n }\n }\n};\n\nconst createNestedStateObject = (\n path: string,\n routes: ParsedRoute[],\n initialRoutes: InitialRouteConfig[],\n flatConfig?: RouteConfig[]\n) => {\n let state: InitialState;\n let route = routes.shift() as ParsedRoute;\n const parentScreens: string[] = [];\n\n let initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);\n\n parentScreens.push(route.name);\n\n state = createStateObject(initialRoute, route, routes.length === 0);\n\n if (routes.length > 0) {\n let nestedState = state;\n\n while ((route = routes.shift() as ParsedRoute)) {\n initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);\n\n const nestedStateIndex =\n nestedState.index || nestedState.routes.length - 1;\n\n nestedState.routes[nestedStateIndex].state = createStateObject(\n initialRoute,\n route,\n routes.length === 0\n );\n\n if (routes.length > 0) {\n nestedState = nestedState.routes[nestedStateIndex]\n .state as InitialState;\n }\n\n parentScreens.push(route.name);\n }\n }\n\n route = findFocusedRoute(state) as ParsedRoute;\n route.path = path;\n\n const params = parseQueryParams(\n path,\n flatConfig ? findParseConfigForRoute(route.name, flatConfig) : undefined\n );\n\n if (params) {\n route.params = { ...route.params, ...params };\n }\n\n return state;\n};\n\nconst parseQueryParams = (\n path: string,\n parseConfig?: Record<string, (value: string) => any>\n) => {\n const query = path.split('?')[1];\n const params = queryString.parse(query);\n\n if (parseConfig) {\n Object.keys(params).forEach((name) => {\n if (parseConfig[name] && typeof params[name] === 'string') {\n params[name] = parseConfig[name](params[name] as string);\n }\n });\n }\n\n return Object.keys(params).length ? params : undefined;\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["getStateFromPath.tsx"],"names":["getStateFromPath","path","options","initialRoutes","initialRouteName","push","parentScreens","screens","remaining","replace","endsWith","undefined","routes","split","filter","Boolean","map","segment","name","decodeURIComponent","length","createNestedStateObject","configs","concat","Object","keys","key","createNormalizedConfigs","sort","a","b","pattern","routeNames","join","localeCompare","startsWith","aParts","bParts","i","Math","max","aWildCard","bWildCard","reduce","acc","config","intersects","every","it","Error","assign","match","find","c","screen","result","current","remainingPath","matchAgainstConfigs","regex","RegExp","source","joinPaths","paths","p","matchedParams","params","value","parse","routeConfig","initials","parentPattern","createConfigItem","exact","forEach","nestedConfig","pop","findParseConfigForRoute","routeName","flatConfig","findInitialRoute","sameParents","createStateObject","initialRoute","route","isEmpty","index","state","shift","nestedState","nestedStateIndex","parseQueryParams","parseConfig","query","queryString","hasOwnProperty","call"],"mappings":";;;;;;;AAKA;;AACA;;AAEA;;AAEA;;;;;;;;AAiCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASA,gBAAT,CACbC,IADa,EAEbC,OAFa,EAGY;AACzB,MAAIA,OAAJ,EAAa;AACX,qCAAmBA,OAAnB;AACD;;AAED,MAAIC,aAAmC,GAAG,EAA1C;;AAEA,MAAID,OAAJ,aAAIA,OAAJ,eAAIA,OAAO,CAAEE,gBAAb,EAA+B;AAC7BD,IAAAA,aAAa,CAACE,IAAd,CAAmB;AACjBD,MAAAA,gBAAgB,EAAEF,OAAO,CAACE,gBADT;AAEjBE,MAAAA,aAAa,EAAE;AAFE,KAAnB;AAID;;AAED,QAAMC,OAAO,GAAGL,OAAH,aAAGA,OAAH,uBAAGA,OAAO,CAAEK,OAAzB;AAEA,MAAIC,SAAS,GAAGP,IAAI,CACjBQ,OADa,CACL,MADK,EACG,GADH,EACQ;AADR,GAEbA,OA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D,MAAM,GAAG4B,WAAW,CAAC1B,KAAZ,CAAkByB,KAAlB,CAAf;;AAEA,MAAID,WAAJ,EAAiB;AACfpE,IAAAA,MAAM,CAACC,IAAP,CAAYyC,MAAZ,EAAoBQ,OAApB,CAA6BxD,IAAD,IAAU;AACpC,UACEM,MAAM,CAACuE,cAAP,CAAsBC,IAAtB,CAA2BJ,WAA3B,EAAwC1E,IAAxC,KACA,OAAOgD,MAAM,CAAChD,IAAD,CAAb,KAAwB,QAF1B,EAGE;AACAgD,QAAAA,MAAM,CAAChD,IAAD,CAAN,GAAe0E,WAAW,CAAC1E,IAAD,CAAX,CAAkBgD,MAAM,CAAChD,IAAD,CAAxB,CAAf;AACD;AACF,KAPD;AAQD;;AAED,SAAOM,MAAM,CAACC,IAAP,CAAYyC,MAAZ,EAAoB9C,MAApB,GAA6B8C,MAA7B,GAAsCvD,SAA7C;AACD,CAnBD","sourcesContent":["import type {\n InitialState,\n NavigationState,\n PartialState,\n} from '@react-navigation/routers';\nimport escape from 'escape-string-regexp';\nimport * as queryString from 'query-string';\n\nimport findFocusedRoute from './findFocusedRoute';\nimport type { PathConfigMap } from './types';\nimport validatePathConfig from './validatePathConfig';\n\ntype Options<ParamList extends {}> = {\n initialRouteName?: string;\n screens: PathConfigMap<ParamList>;\n};\n\ntype ParseConfig = Record<string, (value: string) => any>;\n\ntype RouteConfig = {\n screen: string;\n regex?: RegExp;\n path: string;\n pattern: string;\n routeNames: string[];\n parse?: ParseConfig;\n};\n\ntype InitialRouteConfig = {\n initialRouteName: string;\n parentScreens: string[];\n};\n\ntype ResultState = PartialState<NavigationState> & {\n state?: ResultState;\n};\n\ntype ParsedRoute = {\n name: string;\n path?: string;\n params?: Record<string, any> | undefined;\n};\n\n/**\n * Utility to parse a path string to initial state object accepted by the container.\n * This is useful for deep linking when we need to handle the incoming URL.\n *\n * @example\n * ```js\n * getStateFromPath(\n * '/chat/jane/42',\n * {\n * screens: {\n * Chat: {\n * path: 'chat/:author/:id',\n * parse: { id: Number }\n * }\n * }\n * }\n * )\n * ```\n * @param path Path string to parse and convert, e.g. /foo/bar?count=42.\n * @param options Extra options to fine-tune how to parse the path.\n */\nexport default function getStateFromPath<ParamList extends {}>(\n path: string,\n options?: Options<ParamList>\n): ResultState | undefined {\n if (options) {\n validatePathConfig(options);\n }\n\n let initialRoutes: InitialRouteConfig[] = [];\n\n if (options?.initialRouteName) {\n initialRoutes.push({\n initialRouteName: options.initialRouteName,\n parentScreens: [],\n });\n }\n\n const screens = options?.screens;\n\n let remaining = path\n .replace(/\\/+/g, '/') // Replace multiple slash (//) with single ones\n .replace(/^\\//, '') // Remove extra leading slash\n .replace(/\\?.*$/, ''); // Remove query params which we will handle later\n\n // Make sure there is a trailing slash\n remaining = remaining.endsWith('/') ? remaining : `${remaining}/`;\n\n if (screens === undefined) {\n // When no config is specified, use the path segments as route names\n const routes = remaining\n .split('/')\n .filter(Boolean)\n .map((segment) => {\n const name = decodeURIComponent(segment);\n return { name };\n });\n\n if (routes.length) {\n return createNestedStateObject(path, routes, initialRoutes);\n }\n\n return undefined;\n }\n\n // Create a normalized configs array which will be easier to use\n const configs = ([] as RouteConfig[])\n .concat(\n ...Object.keys(screens).map((key) =>\n createNormalizedConfigs(\n key,\n screens as PathConfigMap<object>,\n [],\n initialRoutes,\n []\n )\n )\n )\n .sort((a, b) => {\n // Sort config so that:\n // - the most exhaustive ones are always at the beginning\n // - patterns with wildcard are always at the end\n\n // If 2 patterns are same, move the one with less route names up\n // This is an error state, so it's only useful for consistent error messages\n if (a.pattern === b.pattern) {\n return b.routeNames.join('>').localeCompare(a.routeNames.join('>'));\n }\n\n // If one of the patterns starts with the other, it's more exhaustive\n // So move it up\n if (a.pattern.startsWith(b.pattern)) {\n return -1;\n }\n\n if (b.pattern.startsWith(a.pattern)) {\n return 1;\n }\n\n const aParts = a.pattern.split('/');\n const bParts = b.pattern.split('/');\n\n for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {\n // if b is longer, b get higher priority\n if (aParts[i] == null) {\n return 1;\n }\n // if a is longer, a get higher priority\n if (bParts[i] == null) {\n return -1;\n }\n const aWildCard = aParts[i] === '*' || aParts[i].startsWith(':');\n const bWildCard = bParts[i] === '*' || bParts[i].startsWith(':');\n // if both are wildcard we compare next component\n if (aWildCard && bWildCard) {\n continue;\n }\n // if only a is wild card, b get higher priority\n if (aWildCard) {\n return 1;\n }\n // if only b is wild card, a get higher priority\n if (bWildCard) {\n return -1;\n }\n }\n return bParts.length - aParts.length;\n });\n\n // Check for duplicate patterns in the config\n configs.reduce<Record<string, RouteConfig>>((acc, config) => {\n if (acc[config.pattern]) {\n const a = acc[config.pattern].routeNames;\n const b = config.routeNames;\n\n // It's not a problem if the path string omitted from a inner most screen\n // For example, it's ok if a path resolves to `A > B > C` or `A > B`\n const intersects =\n a.length > b.length\n ? b.every((it, i) => a[i] === it)\n : a.every((it, i) => b[i] === it);\n\n if (!intersects) {\n throw new Error(\n `Found conflicting screens with the same pattern. The pattern '${\n config.pattern\n }' resolves to both '${a.join(' > ')}' and '${b.join(\n ' > '\n )}'. Patterns must be unique and cannot resolve to more than one screen.`\n );\n }\n }\n\n return Object.assign(acc, {\n [config.pattern]: config,\n });\n }, {});\n\n if (remaining === '/') {\n // We need to add special handling of empty path so navigation to empty path also works\n // When handling empty path, we should only look at the root level config\n const match = configs.find(\n (config) =>\n config.path === '' &&\n config.routeNames.every(\n // Make sure that none of the parent configs have a non-empty path defined\n (name) => !configs.find((c) => c.screen === name)?.path\n )\n );\n\n if (match) {\n return createNestedStateObject(\n path,\n match.routeNames.map((name) => ({ name })),\n initialRoutes,\n configs\n );\n }\n\n return undefined;\n }\n\n let result: PartialState<NavigationState> | undefined;\n let current: PartialState<NavigationState> | undefined;\n\n // We match the whole path against the regex instead of segments\n // This makes sure matches such as wildcard will catch any unmatched routes, even if nested\n const { routes, remainingPath } = matchAgainstConfigs(\n remaining,\n configs.map((c) => ({\n ...c,\n // Add `$` to the regex to make sure it matches till end of the path and not just beginning\n regex: c.regex ? new RegExp(c.regex.source + '$') : undefined,\n }))\n );\n\n if (routes !== undefined) {\n // This will always be empty if full path matched\n current = createNestedStateObject(path, routes, initialRoutes, configs);\n remaining = remainingPath;\n result = current;\n }\n\n if (current == null || result == null) {\n return undefined;\n }\n\n return result;\n}\n\nconst joinPaths = (...paths: string[]): string =>\n ([] as string[])\n .concat(...paths.map((p) => p.split('/')))\n .filter(Boolean)\n .join('/');\n\nconst matchAgainstConfigs = (remaining: string, configs: RouteConfig[]) => {\n let routes: ParsedRoute[] | undefined;\n let remainingPath = remaining;\n\n // Go through all configs, and see if the next path segment matches our regex\n for (const config of configs) {\n if (!config.regex) {\n continue;\n }\n\n const match = remainingPath.match(config.regex);\n\n // If our regex matches, we need to extract params from the path\n if (match) {\n const matchedParams = config.pattern\n ?.split('/')\n .filter((p) => p.startsWith(':'))\n .reduce<Record<string, any>>(\n (acc, p, i) =>\n Object.assign(acc, {\n // The param segments appear every second item starting from 2 in the regex match result\n [p]: match![(i + 1) * 2].replace(/\\//, ''),\n }),\n {}\n );\n\n routes = config.routeNames.map((name) => {\n const config = configs.find((c) => c.screen === name);\n const params = config?.path\n ?.split('/')\n .filter((p) => p.startsWith(':'))\n .reduce<Record<string, any>>((acc, p) => {\n const value = matchedParams[p];\n\n if (value) {\n const key = p.replace(/^:/, '').replace(/\\?$/, '');\n acc[key] = config.parse?.[key] ? config.parse[key](value) : value;\n }\n\n return acc;\n }, {});\n\n if (params && Object.keys(params).length) {\n return { name, params };\n }\n\n return { name };\n });\n\n remainingPath = remainingPath.replace(match[1], '');\n\n break;\n }\n }\n\n return { routes, remainingPath };\n};\n\nconst createNormalizedConfigs = (\n screen: string,\n routeConfig: PathConfigMap<object>,\n routeNames: string[] = [],\n initials: InitialRouteConfig[],\n parentScreens: string[],\n parentPattern?: string\n): RouteConfig[] => {\n const configs: RouteConfig[] = [];\n\n routeNames.push(screen);\n\n parentScreens.push(screen);\n\n // @ts-expect-error: we can't strongly typecheck this for now\n const config = routeConfig[screen];\n\n if (typeof config === 'string') {\n // If a string is specified as the value of the key(e.g. Foo: '/path'), use it as the pattern\n const pattern = parentPattern ? joinPaths(parentPattern, config) : config;\n\n configs.push(createConfigItem(screen, routeNames, pattern, config));\n } else if (typeof config === 'object') {\n let pattern: string | undefined;\n\n // if an object is specified as the value (e.g. Foo: { ... }),\n // it can have `path` property and\n // it could have `screens` prop which has nested configs\n if (typeof config.path === 'string') {\n if (config.exact && config.path === undefined) {\n throw new Error(\n \"A 'path' needs to be specified when specifying 'exact: true'. If you don't want this screen in the URL, specify it as empty string, e.g. `path: ''`.\"\n );\n }\n\n pattern =\n config.exact !== true\n ? joinPaths(parentPattern || '', config.path || '')\n : config.path || '';\n\n configs.push(\n createConfigItem(\n screen,\n routeNames,\n pattern!,\n config.path,\n config.parse\n )\n );\n }\n\n if (config.screens) {\n // property `initialRouteName` without `screens` has no purpose\n if (config.initialRouteName) {\n initials.push({\n initialRouteName: config.initialRouteName,\n parentScreens,\n });\n }\n\n Object.keys(config.screens).forEach((nestedConfig) => {\n const result = createNormalizedConfigs(\n nestedConfig,\n config.screens as PathConfigMap<object>,\n routeNames,\n initials,\n [...parentScreens],\n pattern ?? parentPattern\n );\n\n configs.push(...result);\n });\n }\n }\n\n routeNames.pop();\n\n return configs;\n};\n\nconst createConfigItem = (\n screen: string,\n routeNames: string[],\n pattern: string,\n path: string,\n parse?: ParseConfig\n): RouteConfig => {\n // Normalize pattern to remove any leading, trailing slashes, duplicate slashes etc.\n pattern = pattern.split('/').filter(Boolean).join('/');\n\n const regex = pattern\n ? new RegExp(\n `^(${pattern\n .split('/')\n .map((it) => {\n if (it.startsWith(':')) {\n return `(([^/]+\\\\/)${it.endsWith('?') ? '?' : ''})`;\n }\n\n return `${it === '*' ? '.*' : escape(it)}\\\\/`;\n })\n .join('')})`\n )\n : undefined;\n\n return {\n screen,\n regex,\n pattern,\n path,\n // The routeNames array is mutated, so copy it to keep the current state\n routeNames: [...routeNames],\n parse,\n };\n};\n\nconst findParseConfigForRoute = (\n routeName: string,\n flatConfig: RouteConfig[]\n): ParseConfig | undefined => {\n for (const config of flatConfig) {\n if (routeName === config.routeNames[config.routeNames.length - 1]) {\n return config.parse;\n }\n }\n\n return undefined;\n};\n\n// Try to find an initial route connected with the one passed\nconst findInitialRoute = (\n routeName: string,\n parentScreens: string[],\n initialRoutes: InitialRouteConfig[]\n): string | undefined => {\n for (const config of initialRoutes) {\n if (parentScreens.length === config.parentScreens.length) {\n let sameParents = true;\n for (let i = 0; i < parentScreens.length; i++) {\n if (parentScreens[i].localeCompare(config.parentScreens[i]) !== 0) {\n sameParents = false;\n break;\n }\n }\n if (sameParents) {\n return routeName !== config.initialRouteName\n ? config.initialRouteName\n : undefined;\n }\n }\n }\n return undefined;\n};\n\n// returns state object with values depending on whether\n// it is the end of state and if there is initialRoute for this level\nconst createStateObject = (\n initialRoute: string | undefined,\n route: ParsedRoute,\n isEmpty: boolean\n): InitialState => {\n if (isEmpty) {\n if (initialRoute) {\n return {\n index: 1,\n routes: [{ name: initialRoute }, route],\n };\n } else {\n return {\n routes: [route],\n };\n }\n } else {\n if (initialRoute) {\n return {\n index: 1,\n routes: [{ name: initialRoute }, { ...route, state: { routes: [] } }],\n };\n } else {\n return {\n routes: [{ ...route, state: { routes: [] } }],\n };\n }\n }\n};\n\nconst createNestedStateObject = (\n path: string,\n routes: ParsedRoute[],\n initialRoutes: InitialRouteConfig[],\n flatConfig?: RouteConfig[]\n) => {\n let state: InitialState;\n let route = routes.shift() as ParsedRoute;\n const parentScreens: string[] = [];\n\n let initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);\n\n parentScreens.push(route.name);\n\n state = createStateObject(initialRoute, route, routes.length === 0);\n\n if (routes.length > 0) {\n let nestedState = state;\n\n while ((route = routes.shift() as ParsedRoute)) {\n initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);\n\n const nestedStateIndex =\n nestedState.index || nestedState.routes.length - 1;\n\n nestedState.routes[nestedStateIndex].state = createStateObject(\n initialRoute,\n route,\n routes.length === 0\n );\n\n if (routes.length > 0) {\n nestedState = nestedState.routes[nestedStateIndex]\n .state as InitialState;\n }\n\n parentScreens.push(route.name);\n }\n }\n\n route = findFocusedRoute(state) as ParsedRoute;\n route.path = path;\n\n const params = parseQueryParams(\n path,\n flatConfig ? findParseConfigForRoute(route.name, flatConfig) : undefined\n );\n\n if (params) {\n route.params = { ...route.params, ...params };\n }\n\n return state;\n};\n\nconst parseQueryParams = (\n path: string,\n parseConfig?: Record<string, (value: string) => any>\n) => {\n const query = path.split('?')[1];\n const params = queryString.parse(query);\n\n if (parseConfig) {\n Object.keys(params).forEach((name) => {\n if (\n Object.hasOwnProperty.call(parseConfig, name) &&\n typeof params[name] === 'string'\n ) {\n params[name] = parseConfig[name](params[name] as string);\n }\n });\n }\n\n return Object.keys(params).length ? params : undefined;\n};\n"]}
|
package/lib/commonjs/index.js
CHANGED
|
@@ -17,12 +17,16 @@ var _exportNames = {
|
|
|
17
17
|
NavigationContext: true,
|
|
18
18
|
NavigationHelpersContext: true,
|
|
19
19
|
NavigationRouteContext: true,
|
|
20
|
+
PreventRemoveContext: true,
|
|
21
|
+
PreventRemoveProvider: true,
|
|
20
22
|
useFocusEffect: true,
|
|
21
23
|
useIsFocused: true,
|
|
22
24
|
useNavigation: true,
|
|
23
25
|
useNavigationBuilder: true,
|
|
24
26
|
useNavigationContainerRef: true,
|
|
25
27
|
useNavigationState: true,
|
|
28
|
+
UNSTABLE_usePreventRemove: true,
|
|
29
|
+
usePreventRemoveContext: true,
|
|
26
30
|
useRoute: true,
|
|
27
31
|
validatePathConfig: true
|
|
28
32
|
};
|
|
@@ -62,6 +66,24 @@ Object.defineProperty(exports, "NavigationRouteContext", {
|
|
|
62
66
|
return _NavigationRouteContext.default;
|
|
63
67
|
}
|
|
64
68
|
});
|
|
69
|
+
Object.defineProperty(exports, "PreventRemoveContext", {
|
|
70
|
+
enumerable: true,
|
|
71
|
+
get: function () {
|
|
72
|
+
return _PreventRemoveContext.default;
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
Object.defineProperty(exports, "PreventRemoveProvider", {
|
|
76
|
+
enumerable: true,
|
|
77
|
+
get: function () {
|
|
78
|
+
return _PreventRemoveProvider.default;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
Object.defineProperty(exports, "UNSTABLE_usePreventRemove", {
|
|
82
|
+
enumerable: true,
|
|
83
|
+
get: function () {
|
|
84
|
+
return _usePreventRemove.default;
|
|
85
|
+
}
|
|
86
|
+
});
|
|
65
87
|
Object.defineProperty(exports, "createNavigationContainerRef", {
|
|
66
88
|
enumerable: true,
|
|
67
89
|
get: function () {
|
|
@@ -140,6 +162,12 @@ Object.defineProperty(exports, "useNavigationState", {
|
|
|
140
162
|
return _useNavigationState.default;
|
|
141
163
|
}
|
|
142
164
|
});
|
|
165
|
+
Object.defineProperty(exports, "usePreventRemoveContext", {
|
|
166
|
+
enumerable: true,
|
|
167
|
+
get: function () {
|
|
168
|
+
return _usePreventRemoveContext.default;
|
|
169
|
+
}
|
|
170
|
+
});
|
|
143
171
|
Object.defineProperty(exports, "useRoute", {
|
|
144
172
|
enumerable: true,
|
|
145
173
|
get: function () {
|
|
@@ -179,6 +207,10 @@ var _NavigationHelpersContext = _interopRequireDefault(require("./NavigationHelp
|
|
|
179
207
|
|
|
180
208
|
var _NavigationRouteContext = _interopRequireDefault(require("./NavigationRouteContext"));
|
|
181
209
|
|
|
210
|
+
var _PreventRemoveContext = _interopRequireDefault(require("./PreventRemoveContext"));
|
|
211
|
+
|
|
212
|
+
var _PreventRemoveProvider = _interopRequireDefault(require("./PreventRemoveProvider"));
|
|
213
|
+
|
|
182
214
|
var _types = require("./types");
|
|
183
215
|
|
|
184
216
|
Object.keys(_types).forEach(function (key) {
|
|
@@ -205,6 +237,10 @@ var _useNavigationContainerRef = _interopRequireDefault(require("./useNavigation
|
|
|
205
237
|
|
|
206
238
|
var _useNavigationState = _interopRequireDefault(require("./useNavigationState"));
|
|
207
239
|
|
|
240
|
+
var _usePreventRemove = _interopRequireDefault(require("./usePreventRemove"));
|
|
241
|
+
|
|
242
|
+
var _usePreventRemoveContext = _interopRequireDefault(require("./usePreventRemoveContext"));
|
|
243
|
+
|
|
208
244
|
var _useRoute = _interopRequireDefault(require("./useRoute"));
|
|
209
245
|
|
|
210
246
|
var _validatePathConfig = _interopRequireDefault(require("./validatePathConfig"));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["index.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"sources":["index.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","sourcesContent":["export { default as BaseNavigationContainer } from './BaseNavigationContainer';\nexport { default as createNavigationContainerRef } from './createNavigationContainerRef';\nexport { default as createNavigatorFactory } from './createNavigatorFactory';\nexport { default as CurrentRenderContext } from './CurrentRenderContext';\nexport { default as findFocusedRoute } from './findFocusedRoute';\nexport { default as getActionFromState } from './getActionFromState';\nexport { default as getFocusedRouteNameFromRoute } from './getFocusedRouteNameFromRoute';\nexport { default as getPathFromState } from './getPathFromState';\nexport { default as getStateFromPath } from './getStateFromPath';\nexport { default as NavigationContainerRefContext } from './NavigationContainerRefContext';\nexport { default as NavigationContext } from './NavigationContext';\nexport { default as NavigationHelpersContext } from './NavigationHelpersContext';\nexport { default as NavigationRouteContext } from './NavigationRouteContext';\nexport { default as PreventRemoveContext } from './PreventRemoveContext';\nexport { default as PreventRemoveProvider } from './PreventRemoveProvider';\nexport * from './types';\nexport { default as useFocusEffect } from './useFocusEffect';\nexport { default as useIsFocused } from './useIsFocused';\nexport { default as useNavigation } from './useNavigation';\nexport { default as useNavigationBuilder } from './useNavigationBuilder';\nexport { default as useNavigationContainerRef } from './useNavigationContainerRef';\nexport { default as useNavigationState } from './useNavigationState';\nexport { default as UNSTABLE_usePreventRemove } from './usePreventRemove';\nexport { default as usePreventRemoveContext } from './usePreventRemoveContext';\nexport { default as useRoute } from './useRoute';\nexport { default as validatePathConfig } from './validatePathConfig';\nexport * from '@react-navigation/routers';\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["types.tsx"],"names":["PrivateValueStore"],"mappings":";;;;;;;;;AA+JO,MAAMA,iBAAN,CAAmD;AAAA;AAAA,0BAW9C,EAX8C;AAAA;;AAAA","sourcesContent":["import type {\n DefaultRouterOptions,\n InitialState,\n NavigationAction,\n NavigationState,\n ParamListBase,\n PartialState,\n Route,\n} from '@react-navigation/routers';\nimport type * as React from 'react';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace ReactNavigation {\n // eslint-disable-next-line @typescript-eslint/no-empty-interface\n interface RootParamList {}\n }\n}\n\ntype Keyof<T extends {}> = Extract<keyof T, string>;\n\nexport type DefaultNavigatorOptions<\n ParamList extends ParamListBase,\n State extends NavigationState,\n ScreenOptions extends {},\n EventMap extends EventMapBase\n> = DefaultRouterOptions<Keyof<ParamList>> & {\n /**\n * Optional ID for the navigator. Can be used with `navigation.getParent(id)` to refer to a parent.\n */\n id?: string;\n /**\n * Children React Elements to extract the route configuration from.\n * Only `Screen`, `Group` and `React.Fragment` are supported as children.\n */\n children: React.ReactNode;\n /**\n * Event listeners for all the screens in the navigator.\n */\n screenListeners?:\n | ScreenListeners<State, EventMap>\n | ((props: {\n route: RouteProp<ParamList>;\n navigation: any;\n }) => ScreenListeners<State, EventMap>);\n /**\n * Default options for all screens under this navigator.\n */\n screenOptions?:\n | ScreenOptions\n | ((props: {\n route: RouteProp<ParamList>;\n navigation: any;\n }) => ScreenOptions);\n /**\n * Default options specified by the navigator.\n * It receives the custom options in the arguments if a function is specified.\n */\n defaultScreenOptions?:\n | ScreenOptions\n | ((props: {\n route: RouteProp<ParamList>;\n navigation: any;\n options: ScreenOptions;\n }) => ScreenOptions);\n};\n\nexport type EventMapBase = Record<\n string,\n { data?: any; canPreventDefault?: boolean }\n>;\n\nexport type EventMapCore<State extends NavigationState> = {\n focus: { data: undefined };\n blur: { data: undefined };\n state: { data: { state: State } };\n beforeRemove: { data: { action: NavigationAction }; canPreventDefault: true };\n};\n\nexport type EventArg<\n EventName extends string,\n CanPreventDefault extends boolean | undefined = false,\n Data = undefined\n> = {\n /**\n * Type of the event (e.g. `focus`, `blur`)\n */\n readonly type: EventName;\n readonly target?: string;\n} & (CanPreventDefault extends true\n ? {\n /**\n * Whether `event.preventDefault()` was called on this event object.\n */\n readonly defaultPrevented: boolean;\n /**\n * Prevent the default action which happens on this event.\n */\n preventDefault(): void;\n }\n : {}) &\n (undefined extends Data\n ? { readonly data?: Readonly<Data> }\n : { readonly data: Readonly<Data> });\n\nexport type EventListenerCallback<\n EventMap extends EventMapBase,\n EventName extends keyof EventMap\n> = (\n e: EventArg<\n Extract<EventName, string>,\n EventMap[EventName]['canPreventDefault'],\n EventMap[EventName]['data']\n >\n) => void;\n\nexport type EventConsumer<EventMap extends EventMapBase> = {\n /**\n * Subscribe to events from the parent navigator.\n *\n * @param type Type of the event (e.g. `focus`, `blur`)\n * @param callback Callback listener which is executed upon receiving the event.\n */\n addListener<EventName extends Keyof<EventMap>>(\n type: EventName,\n callback: EventListenerCallback<EventMap, EventName>\n ): () => void;\n removeListener<EventName extends Keyof<EventMap>>(\n type: EventName,\n callback: EventListenerCallback<EventMap, EventName>\n ): void;\n};\n\nexport type EventEmitter<EventMap extends EventMapBase> = {\n /**\n * Emit an event to child screens.\n *\n * @param options.type Type of the event (e.g. `focus`, `blur`)\n * @param [options.data] Optional information regarding the event.\n * @param [options.target] Key of the target route which should receive the event.\n * If not specified, all routes receive the event.\n */\n emit<EventName extends Keyof<EventMap>>(\n options: {\n type: EventName;\n target?: string;\n } & (EventMap[EventName]['canPreventDefault'] extends true\n ? { canPreventDefault: true }\n : {}) &\n (undefined extends EventMap[EventName]['data']\n ? { data?: EventMap[EventName]['data'] }\n : { data: EventMap[EventName]['data'] })\n ): EventArg<\n EventName,\n EventMap[EventName]['canPreventDefault'],\n EventMap[EventName]['data']\n >;\n};\n\nexport class PrivateValueStore<T extends [any, any, any]> {\n /**\n * UGLY HACK! DO NOT USE THE TYPE!!!\n *\n * TypeScript requires a type to be used to be able to infer it.\n * The type should exist as its own without any operations such as union.\n * So we need to figure out a way to store this type in a property.\n * The problem with a normal property is that it shows up in intelliSense.\n * Adding private keyword works, but the annotation is stripped away in declaration.\n * Turns out if we use an empty string, it doesn't show up in intelliSense.\n */\n protected ''?: T;\n}\n\ntype NavigationHelpersCommon<\n ParamList extends ParamListBase,\n State extends NavigationState = NavigationState\n> = {\n /**\n * Dispatch an action or an update function to the router.\n * The update function will receive the current state,\n *\n * @param action Action object or update function.\n */\n dispatch(\n action: NavigationAction | ((state: State) => NavigationAction)\n ): void;\n\n /**\n * Navigate to a route in current navigation tree.\n *\n * @param name Name of the route to navigate to.\n * @param [params] Params object for the route.\n */\n navigate<RouteName extends keyof ParamList>(\n ...args: undefined extends ParamList[RouteName]\n ? [screen: RouteName] | [screen: RouteName, params: ParamList[RouteName]]\n : [screen: RouteName, params: ParamList[RouteName]]\n ): void;\n\n /**\n * Navigate to a route in current navigation tree.\n *\n * @param route Object with `key` or `name` for the route to navigate to, and a `params` object.\n */\n navigate<RouteName extends keyof ParamList>(\n options:\n | { key: string; params?: ParamList[RouteName]; merge?: boolean }\n | {\n name: RouteName;\n key?: string;\n params: ParamList[RouteName];\n merge?: boolean;\n }\n ): void;\n\n /**\n * Reset the navigation state to the provided state.\n *\n * @param state Navigation state object.\n */\n reset(state: PartialState<State> | State): void;\n\n /**\n * Go back to the previous route in history.\n */\n goBack(): void;\n\n /**\n * Check if the screen is focused. The method returns `true` if focused, `false` otherwise.\n * Note that this method doesn't re-render screen when the focus changes. So don't use it in `render`.\n * To get notified of focus changes, use `addListener('focus', cb)` and `addListener('blur', cb)`.\n * To conditionally render content based on focus state, use the `useIsFocused` hook.\n */\n isFocused(): boolean;\n\n /**\n * Check if dispatching back action will be handled by navigation.\n * Note that this method doesn't re-render screen when the result changes. So don't use it in `render`.\n */\n canGoBack(): boolean;\n\n /**\n * Returns the name of the navigator specified in the `name` prop.\n * If no name is specified, returns `undefined`.\n */\n getId(): string | undefined;\n\n /**\n * Returns the navigation helpers from a parent navigator based on the ID.\n * If an ID is provided, the navigation helper from the parent navigator with matching ID (including current) will be returned.\n * If no ID is provided, the navigation helper from the immediate parent navigator will be returned.\n *\n * @param id Optional ID of a parent navigator.\n */\n getParent<T = NavigationHelpers<ParamListBase> | undefined>(id?: string): T;\n\n /**\n * Returns the navigator's state.\n * Note that this method doesn't re-render screen when the result changes. So don't use it in `render`.\n */\n getState(): State;\n} & PrivateValueStore<[ParamList, unknown, unknown]>;\n\nexport type NavigationHelpers<\n ParamList extends ParamListBase,\n EventMap extends EventMapBase = {}\n> = NavigationHelpersCommon<ParamList> &\n EventEmitter<EventMap> & {\n /**\n * Update the param object for the route.\n * The new params will be shallow merged with the old one.\n *\n * @param params Params object for the current route.\n */\n setParams<RouteName extends keyof ParamList>(\n params: Partial<ParamList[RouteName]>\n ): void;\n };\n\nexport type NavigationContainerProps = {\n /**\n * Initial navigation state for the child navigators.\n */\n initialState?: InitialState;\n /**\n * Callback which is called with the latest navigation state when it changes.\n */\n onStateChange?: (state: NavigationState | undefined) => void;\n /**\n * Callback which is called when an action is not handled.\n */\n onUnhandledAction?: (action: NavigationAction) => void;\n /**\n * Whether this navigation container should be independent of parent containers.\n * If this is not set to `true`, this container cannot be nested inside another container.\n * Setting it to `true` disconnects any children navigators from parent container.\n */\n independent?: boolean;\n /**\n * Children elements to render.\n */\n children: React.ReactNode;\n};\n\nexport type NavigationProp<\n ParamList extends {},\n RouteName extends keyof ParamList = Keyof<ParamList>,\n NavigatorID extends string | undefined = undefined,\n State extends NavigationState = NavigationState<ParamList>,\n ScreenOptions extends {} = {},\n EventMap extends EventMapBase = {}\n> = Omit<NavigationHelpersCommon<ParamList, State>, 'getParent'> & {\n /**\n * Returns the navigation prop from a parent navigator based on the ID.\n * If an ID is provided, the navigation prop from the parent navigator with matching ID (including current) will be returned.\n * If no ID is provided, the navigation prop from the immediate parent navigator will be returned.\n *\n * @param id Optional ID of a parent navigator.\n */\n getParent<T = NavigationProp<ParamListBase> | undefined>(id?: NavigatorID): T;\n\n /**\n * Update the param object for the route.\n * The new params will be shallow merged with the old one.\n *\n * @param params Params object for the current route.\n */\n setParams(params: Partial<ParamList[RouteName]>): void;\n\n /**\n * Update the options for the route.\n * The options object will be shallow merged with default options object.\n *\n * @param options Options object for the route.\n */\n setOptions(options: Partial<ScreenOptions>): void;\n} & EventConsumer<EventMap & EventMapCore<State>> &\n PrivateValueStore<[ParamList, RouteName, EventMap]>;\n\nexport type RouteProp<\n ParamList extends ParamListBase,\n RouteName extends keyof ParamList = Keyof<ParamList>\n> = Route<Extract<RouteName, string>, ParamList[RouteName]>;\n\nexport type CompositeNavigationProp<\n A extends NavigationProp<ParamListBase, string, any, any, any>,\n B extends NavigationHelpersCommon<ParamListBase, any>\n> = Omit<A & B, keyof NavigationProp<any>> &\n NavigationProp<\n /**\n * Param list from both navigation objects needs to be combined\n * For example, we should be able to navigate to screens in both A and B\n */\n (A extends NavigationHelpersCommon<infer T> ? T : never) &\n (B extends NavigationHelpersCommon<infer U> ? U : never),\n /**\n * The route name should refer to the route name specified in the first type\n * Ideally it should work for any of them, but it's not possible to infer that way\n */\n A extends NavigationProp<any, infer R> ? R : string,\n /**\n * ID from both navigation objects needs to be combined for `getParent`\n */\n | (A extends NavigationProp<any, any, infer I> ? I : never)\n | (B extends NavigationProp<any, any, infer J> ? J : never),\n /**\n * The type of state should refer to the state specified in the first type\n */\n A extends NavigationProp<any, any, any, infer S> ? S : NavigationState,\n /**\n * Screen options from both navigation objects needs to be combined\n * This allows typechecking `setOptions`\n */\n (A extends NavigationProp<any, any, any, any, infer O> ? O : {}) &\n (B extends NavigationProp<any, any, any, any, infer P> ? P : {}),\n /**\n * Event consumer config should refer to the config specified in the first type\n * This allows typechecking `addListener`/`removeListener`\n */\n A extends NavigationProp<any, any, any, any, any, infer E> ? E : {}\n >;\n\nexport type CompositeScreenProps<\n A extends {\n navigation: NavigationProp<\n ParamListBase,\n string,\n string | undefined,\n any,\n any,\n any\n >;\n route: RouteProp<ParamListBase>;\n },\n B extends {\n navigation: NavigationHelpersCommon<any, any>;\n }\n> = {\n navigation: CompositeNavigationProp<A['navigation'], B['navigation']>;\n route: A['route'];\n};\n\nexport type Descriptor<\n ScreenOptions extends {},\n Navigation extends NavigationProp<any, any, any, any, any, any>,\n Route extends RouteProp<any, any>\n> = {\n /**\n * Render the component associated with this route.\n */\n render(): JSX.Element;\n\n /**\n * Options for the route.\n */\n options: ScreenOptions;\n\n /**\n * Route object for the screen\n */\n route: Route;\n\n /**\n * Navigation object for the screen\n */\n navigation: Navigation;\n};\n\nexport type ScreenListeners<\n State extends NavigationState,\n EventMap extends EventMapBase\n> = Partial<{\n [EventName in keyof (EventMap & EventMapCore<State>)]: EventListenerCallback<\n EventMap,\n EventName\n >;\n}>;\n\nexport type RouteConfigComponent<\n ParamList extends ParamListBase,\n RouteName extends keyof ParamList\n> =\n | {\n /**\n * React component to render for this screen.\n */\n component: React.ComponentType<any>;\n getComponent?: never;\n children?: never;\n }\n | {\n /**\n * Lazily get a React component to render for this screen.\n */\n getComponent: () => React.ComponentType<any>;\n component?: never;\n children?: never;\n }\n | {\n /**\n * Render callback to render content of this screen.\n */\n children: (props: {\n route: RouteProp<ParamList, RouteName>;\n navigation: any;\n }) => React.ReactNode;\n component?: never;\n getComponent?: never;\n };\n\nexport type RouteConfig<\n ParamList extends ParamListBase,\n RouteName extends keyof ParamList,\n State extends NavigationState,\n ScreenOptions extends {},\n EventMap extends EventMapBase\n> = {\n /**\n * Optional key for this screen. This doesn't need to be unique.\n * If the key changes, existing screens with this name will be removed or reset.\n * Useful when we have some common screens and have conditional rendering.\n */\n navigationKey?: string;\n\n /**\n * Route name of this screen.\n */\n name: RouteName;\n\n /**\n * Navigator options for this screen.\n */\n options?:\n | ScreenOptions\n | ((props: {\n route: RouteProp<ParamList, RouteName>;\n navigation: any;\n }) => ScreenOptions);\n\n /**\n * Event listeners for this screen.\n */\n listeners?:\n | ScreenListeners<State, EventMap>\n | ((props: {\n route: RouteProp<ParamList, RouteName>;\n navigation: any;\n }) => ScreenListeners<State, EventMap>);\n\n /**\n * Function to return an unique ID for this screen.\n * Receives an object with the route params.\n * For a given screen name, there will always be only one screen corresponding to an ID.\n * If `undefined` is returned, it acts same as no `getId` being specified.\n */\n getId?: ({ params }: { params: ParamList[RouteName] }) => string | undefined;\n\n /**\n * Initial params object for the route.\n */\n initialParams?: Partial<ParamList[RouteName]>;\n} & RouteConfigComponent<ParamList, RouteName>;\n\nexport type RouteGroupConfig<\n ParamList extends ParamListBase,\n ScreenOptions extends {}\n> = {\n /**\n * Optional key for the screens in this group.\n * If the key changes, all existing screens in this group will be removed or reset.\n */\n navigationKey?: string;\n\n /**\n * Navigator options for this screen.\n */\n screenOptions?:\n | ScreenOptions\n | ((props: {\n route: RouteProp<ParamList, keyof ParamList>;\n navigation: any;\n }) => ScreenOptions);\n /**\n * Children React Elements to extract the route configuration from.\n * Only `Screen`, `Group` and `React.Fragment` are supported as children.\n */\n children: React.ReactNode;\n};\n\nexport type NavigationContainerEventMap = {\n /**\n * Event which fires when the navigation state changes.\n */\n state: {\n data: {\n /**\n * The updated state object after the state change.\n */\n state: NavigationState | PartialState<NavigationState> | undefined;\n };\n };\n /**\n * Event which fires when current options changes.\n */\n options: { data: { options: object } };\n /**\n * Event which fires when an action is dispatched.\n * Only intended for debugging purposes, don't use it for app logic.\n * This event will be emitted before state changes have been applied.\n */\n __unsafe_action__: {\n data: {\n /**\n * The action object which was dispatched.\n */\n action: NavigationAction;\n /**\n * Whether the action was a no-op, i.e. resulted any state changes.\n */\n noop: boolean;\n /**\n * Stack trace of the action, this will only be available during development.\n */\n stack: string | undefined;\n };\n };\n};\n\nexport type NavigationContainerRef<ParamList extends {}> =\n NavigationHelpers<ParamList> &\n EventConsumer<NavigationContainerEventMap> & {\n /**\n * Reset the navigation state of the root navigator to the provided state.\n *\n * @param state Navigation state object.\n */\n resetRoot(state?: PartialState<NavigationState> | NavigationState): void;\n /**\n * Get the rehydrated navigation state of the navigation tree.\n */\n getRootState(): NavigationState;\n /**\n * Get the currently focused navigation route.\n */\n getCurrentRoute(): Route<string> | undefined;\n /**\n * Get the currently focused route's options.\n */\n getCurrentOptions(): object | undefined;\n /**\n * Whether the navigation container is ready to handle actions.\n */\n isReady(): boolean;\n };\n\nexport type NavigationContainerRefWithCurrent<ParamList extends {}> =\n NavigationContainerRef<ParamList> & {\n current: NavigationContainerRef<ParamList> | null;\n };\n\nexport type TypedNavigator<\n ParamList extends ParamListBase,\n State extends NavigationState,\n ScreenOptions extends {},\n EventMap extends EventMapBase,\n Navigator extends React.ComponentType<any>\n> = {\n /**\n * Navigator component which manages the child screens.\n */\n Navigator: React.ComponentType<\n Omit<\n React.ComponentProps<Navigator>,\n keyof DefaultNavigatorOptions<any, any, any, any>\n > &\n DefaultNavigatorOptions<ParamList, State, ScreenOptions, EventMap>\n >;\n /**\n * Component used for grouping multiple route configuration.\n */\n Group: React.ComponentType<RouteGroupConfig<ParamList, ScreenOptions>>;\n /**\n * Component used for specifying route configuration.\n */\n Screen: <RouteName extends keyof ParamList>(\n _: RouteConfig<ParamList, RouteName, State, ScreenOptions, EventMap>\n ) => null;\n};\n\nexport type NavigatorScreenParams<\n ParamList,\n State extends NavigationState = NavigationState\n> =\n | {\n screen?: never;\n params?: never;\n initial?: never;\n path?: string;\n state: PartialState<State> | State | undefined;\n }\n | {\n [RouteName in keyof ParamList]: undefined extends ParamList[RouteName]\n ? {\n screen: RouteName;\n params?: ParamList[RouteName];\n initial?: boolean;\n path?: string;\n state?: never;\n }\n : {\n screen: RouteName;\n params: ParamList[RouteName];\n initial?: boolean;\n path?: string;\n state?: never;\n };\n }[keyof ParamList];\n\nexport type PathConfig<ParamList extends {}> = {\n path?: string;\n exact?: boolean;\n parse?: Record<string, (value: string) => any>;\n stringify?: Record<string, (value: any) => string>;\n screens?: PathConfigMap<ParamList>;\n initialRouteName?: keyof ParamList;\n};\n\nexport type PathConfigMap<ParamList extends {}> = {\n [RouteName in keyof ParamList]?: NonNullable<\n ParamList[RouteName]\n > extends NavigatorScreenParams<infer T, any>\n ? string | PathConfig<T>\n : string | Omit<PathConfig<{}>, 'screens' | 'initialRouteName'>;\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["types.tsx"],"names":["PrivateValueStore"],"mappings":";;;;;;;;;AA+JO,MAAMA,iBAAN,CAAmD;AAAA;AAAA,0BAW9C,EAX8C;AAAA;;AAAA","sourcesContent":["import type {\n DefaultRouterOptions,\n InitialState,\n NavigationAction,\n NavigationState,\n ParamListBase,\n PartialState,\n Route,\n} from '@react-navigation/routers';\nimport type * as React from 'react';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace ReactNavigation {\n // eslint-disable-next-line @typescript-eslint/no-empty-interface\n interface RootParamList {}\n }\n}\n\ntype Keyof<T extends {}> = Extract<keyof T, string>;\n\nexport type DefaultNavigatorOptions<\n ParamList extends ParamListBase,\n State extends NavigationState,\n ScreenOptions extends {},\n EventMap extends EventMapBase\n> = DefaultRouterOptions<Keyof<ParamList>> & {\n /**\n * Optional ID for the navigator. Can be used with `navigation.getParent(id)` to refer to a parent.\n */\n id?: string;\n /**\n * Children React Elements to extract the route configuration from.\n * Only `Screen`, `Group` and `React.Fragment` are supported as children.\n */\n children: React.ReactNode;\n /**\n * Event listeners for all the screens in the navigator.\n */\n screenListeners?:\n | ScreenListeners<State, EventMap>\n | ((props: {\n route: RouteProp<ParamList>;\n navigation: any;\n }) => ScreenListeners<State, EventMap>);\n /**\n * Default options for all screens under this navigator.\n */\n screenOptions?:\n | ScreenOptions\n | ((props: {\n route: RouteProp<ParamList>;\n navigation: any;\n }) => ScreenOptions);\n /**\n * Default options specified by the navigator.\n * It receives the custom options in the arguments if a function is specified.\n */\n defaultScreenOptions?:\n | ScreenOptions\n | ((props: {\n route: RouteProp<ParamList>;\n navigation: any;\n options: ScreenOptions;\n }) => ScreenOptions);\n};\n\nexport type EventMapBase = Record<\n string,\n { data?: any; canPreventDefault?: boolean }\n>;\n\nexport type EventMapCore<State extends NavigationState> = {\n focus: { data: undefined };\n blur: { data: undefined };\n state: { data: { state: State } };\n beforeRemove: { data: { action: NavigationAction }; canPreventDefault: true };\n};\n\nexport type EventArg<\n EventName extends string,\n CanPreventDefault extends boolean | undefined = false,\n Data = undefined\n> = {\n /**\n * Type of the event (e.g. `focus`, `blur`)\n */\n readonly type: EventName;\n readonly target?: string;\n} & (CanPreventDefault extends true\n ? {\n /**\n * Whether `event.preventDefault()` was called on this event object.\n */\n readonly defaultPrevented: boolean;\n /**\n * Prevent the default action which happens on this event.\n */\n preventDefault(): void;\n }\n : {}) &\n (undefined extends Data\n ? { readonly data?: Readonly<Data> }\n : { readonly data: Readonly<Data> });\n\nexport type EventListenerCallback<\n EventMap extends EventMapBase,\n EventName extends keyof EventMap\n> = (\n e: EventArg<\n Extract<EventName, string>,\n EventMap[EventName]['canPreventDefault'],\n EventMap[EventName]['data']\n >\n) => void;\n\nexport type EventConsumer<EventMap extends EventMapBase> = {\n /**\n * Subscribe to events from the parent navigator.\n *\n * @param type Type of the event (e.g. `focus`, `blur`)\n * @param callback Callback listener which is executed upon receiving the event.\n */\n addListener<EventName extends Keyof<EventMap>>(\n type: EventName,\n callback: EventListenerCallback<EventMap, EventName>\n ): () => void;\n removeListener<EventName extends Keyof<EventMap>>(\n type: EventName,\n callback: EventListenerCallback<EventMap, EventName>\n ): void;\n};\n\nexport type EventEmitter<EventMap extends EventMapBase> = {\n /**\n * Emit an event to child screens.\n *\n * @param options.type Type of the event (e.g. `focus`, `blur`)\n * @param [options.data] Optional information regarding the event.\n * @param [options.target] Key of the target route which should receive the event.\n * If not specified, all routes receive the event.\n */\n emit<EventName extends Keyof<EventMap>>(\n options: {\n type: EventName;\n target?: string;\n } & (EventMap[EventName]['canPreventDefault'] extends true\n ? { canPreventDefault: true }\n : {}) &\n (undefined extends EventMap[EventName]['data']\n ? { data?: EventMap[EventName]['data'] }\n : { data: EventMap[EventName]['data'] })\n ): EventArg<\n EventName,\n EventMap[EventName]['canPreventDefault'],\n EventMap[EventName]['data']\n >;\n};\n\nexport class PrivateValueStore<T extends [any, any, any]> {\n /**\n * UGLY HACK! DO NOT USE THE TYPE!!!\n *\n * TypeScript requires a type to be used to be able to infer it.\n * The type should exist as its own without any operations such as union.\n * So we need to figure out a way to store this type in a property.\n * The problem with a normal property is that it shows up in intelliSense.\n * Adding private keyword works, but the annotation is stripped away in declaration.\n * Turns out if we use an empty string, it doesn't show up in intelliSense.\n */\n protected ''?: T;\n}\n\ntype NavigationHelpersCommon<\n ParamList extends ParamListBase,\n State extends NavigationState = NavigationState\n> = {\n /**\n * Dispatch an action or an update function to the router.\n * The update function will receive the current state,\n *\n * @param action Action object or update function.\n */\n dispatch(\n action: NavigationAction | ((state: State) => NavigationAction)\n ): void;\n\n /**\n * Navigate to a route in current navigation tree.\n *\n * @param name Name of the route to navigate to.\n * @param [params] Params object for the route.\n */\n navigate<RouteName extends keyof ParamList>(\n ...args: // this first condition allows us to iterate over a union type\n // This is to avoid getting a union of all the params from `ParamList[RouteName]`,\n // which will get our types all mixed up if a union RouteName is passed in.\n RouteName extends unknown\n ? // This condition checks if the params are optional,\n // which means it's either undefined or a union with undefined\n undefined extends ParamList[RouteName]\n ?\n | [screen: RouteName] // if the params are optional, we don't have to provide it\n | [screen: RouteName, params: ParamList[RouteName]]\n : [screen: RouteName, params: ParamList[RouteName]]\n : never\n ): void;\n\n /**\n * Navigate to a route in current navigation tree.\n *\n * @param route Object with `key` or `name` for the route to navigate to, and a `params` object.\n */\n navigate<RouteName extends keyof ParamList>(\n options: RouteName extends unknown\n ?\n | { key: string; params?: ParamList[RouteName]; merge?: boolean }\n | {\n name: RouteName;\n key?: string;\n params: ParamList[RouteName];\n merge?: boolean;\n }\n : never\n ): void;\n\n /**\n * Reset the navigation state to the provided state.\n *\n * @param state Navigation state object.\n */\n reset(state: PartialState<State> | State): void;\n\n /**\n * Go back to the previous route in history.\n */\n goBack(): void;\n\n /**\n * Check if the screen is focused. The method returns `true` if focused, `false` otherwise.\n * Note that this method doesn't re-render screen when the focus changes. So don't use it in `render`.\n * To get notified of focus changes, use `addListener('focus', cb)` and `addListener('blur', cb)`.\n * To conditionally render content based on focus state, use the `useIsFocused` hook.\n */\n isFocused(): boolean;\n\n /**\n * Check if dispatching back action will be handled by navigation.\n * Note that this method doesn't re-render screen when the result changes. So don't use it in `render`.\n */\n canGoBack(): boolean;\n\n /**\n * Returns the name of the navigator specified in the `name` prop.\n * If no name is specified, returns `undefined`.\n */\n getId(): string | undefined;\n\n /**\n * Returns the navigation helpers from a parent navigator based on the ID.\n * If an ID is provided, the navigation helper from the parent navigator with matching ID (including current) will be returned.\n * If no ID is provided, the navigation helper from the immediate parent navigator will be returned.\n *\n * @param id Optional ID of a parent navigator.\n */\n getParent<T = NavigationHelpers<ParamListBase> | undefined>(id?: string): T;\n\n /**\n * Returns the navigator's state.\n * Note that this method doesn't re-render screen when the result changes. So don't use it in `render`.\n */\n getState(): State;\n} & PrivateValueStore<[ParamList, unknown, unknown]>;\n\nexport type NavigationHelpers<\n ParamList extends ParamListBase,\n EventMap extends EventMapBase = {}\n> = NavigationHelpersCommon<ParamList> &\n EventEmitter<EventMap> & {\n /**\n * Update the param object for the route.\n * The new params will be shallow merged with the old one.\n *\n * @param params Params object for the current route.\n */\n setParams<RouteName extends keyof ParamList>(\n params: Partial<ParamList[RouteName]>\n ): void;\n };\n\nexport type NavigationContainerProps = {\n /**\n * Initial navigation state for the child navigators.\n */\n initialState?: InitialState;\n /**\n * Callback which is called with the latest navigation state when it changes.\n */\n onStateChange?: (state: NavigationState | undefined) => void;\n /**\n * Callback which is called when an action is not handled.\n */\n onUnhandledAction?: (action: NavigationAction) => void;\n /**\n * Whether this navigation container should be independent of parent containers.\n * If this is not set to `true`, this container cannot be nested inside another container.\n * Setting it to `true` disconnects any children navigators from parent container.\n */\n independent?: boolean;\n /**\n * Children elements to render.\n */\n children: React.ReactNode;\n};\n\nexport type NavigationProp<\n ParamList extends {},\n RouteName extends keyof ParamList = Keyof<ParamList>,\n NavigatorID extends string | undefined = undefined,\n State extends NavigationState = NavigationState<ParamList>,\n ScreenOptions extends {} = {},\n EventMap extends EventMapBase = {}\n> = Omit<NavigationHelpersCommon<ParamList, State>, 'getParent'> & {\n /**\n * Returns the navigation prop from a parent navigator based on the ID.\n * If an ID is provided, the navigation prop from the parent navigator with matching ID (including current) will be returned.\n * If no ID is provided, the navigation prop from the immediate parent navigator will be returned.\n *\n * @param id Optional ID of a parent navigator.\n */\n getParent<T = NavigationProp<ParamListBase> | undefined>(id?: NavigatorID): T;\n\n /**\n * Update the param object for the route.\n * The new params will be shallow merged with the old one.\n *\n * @param params Params object for the current route.\n */\n setParams(\n params: ParamList[RouteName] extends undefined\n ? undefined\n : Partial<ParamList[RouteName]>\n ): void;\n\n /**\n * Update the options for the route.\n * The options object will be shallow merged with default options object.\n *\n * @param options Options object for the route.\n */\n setOptions(options: Partial<ScreenOptions>): void;\n} & EventConsumer<EventMap & EventMapCore<State>> &\n PrivateValueStore<[ParamList, RouteName, EventMap]>;\n\nexport type RouteProp<\n ParamList extends ParamListBase,\n RouteName extends keyof ParamList = Keyof<ParamList>\n> = Route<Extract<RouteName, string>, ParamList[RouteName]>;\n\nexport type CompositeNavigationProp<\n A extends NavigationProp<ParamListBase, string, any, any, any>,\n B extends NavigationHelpersCommon<ParamListBase, any>\n> = Omit<A & B, keyof NavigationProp<any>> &\n NavigationProp<\n /**\n * Param list from both navigation objects needs to be combined\n * For example, we should be able to navigate to screens in both A and B\n */\n (A extends NavigationHelpersCommon<infer T> ? T : never) &\n (B extends NavigationHelpersCommon<infer U> ? U : never),\n /**\n * The route name should refer to the route name specified in the first type\n * Ideally it should work for any of them, but it's not possible to infer that way\n */\n A extends NavigationProp<any, infer R> ? R : string,\n /**\n * ID from both navigation objects needs to be combined for `getParent`\n */\n | (A extends NavigationProp<any, any, infer I> ? I : never)\n | (B extends NavigationProp<any, any, infer J> ? J : never),\n /**\n * The type of state should refer to the state specified in the first type\n */\n A extends NavigationProp<any, any, any, infer S> ? S : NavigationState,\n /**\n * Screen options from both navigation objects needs to be combined\n * This allows typechecking `setOptions`\n */\n (A extends NavigationProp<any, any, any, any, infer O> ? O : {}) &\n (B extends NavigationProp<any, any, any, any, infer P> ? P : {}),\n /**\n * Event consumer config should refer to the config specified in the first type\n * This allows typechecking `addListener`/`removeListener`\n */\n A extends NavigationProp<any, any, any, any, any, infer E> ? E : {}\n >;\n\nexport type CompositeScreenProps<\n A extends {\n navigation: NavigationProp<\n ParamListBase,\n string,\n string | undefined,\n any,\n any,\n any\n >;\n route: RouteProp<ParamListBase>;\n },\n B extends {\n navigation: NavigationHelpersCommon<any, any>;\n }\n> = {\n navigation: CompositeNavigationProp<A['navigation'], B['navigation']>;\n route: A['route'];\n};\n\nexport type Descriptor<\n ScreenOptions extends {},\n Navigation extends NavigationProp<any, any, any, any, any, any>,\n Route extends RouteProp<any, any>\n> = {\n /**\n * Render the component associated with this route.\n */\n render(): JSX.Element;\n\n /**\n * Options for the route.\n */\n options: ScreenOptions;\n\n /**\n * Route object for the screen\n */\n route: Route;\n\n /**\n * Navigation object for the screen\n */\n navigation: Navigation;\n};\n\nexport type ScreenListeners<\n State extends NavigationState,\n EventMap extends EventMapBase\n> = Partial<{\n [EventName in keyof (EventMap & EventMapCore<State>)]: EventListenerCallback<\n EventMap,\n EventName\n >;\n}>;\n\ntype ScreenComponentType<\n ParamList extends ParamListBase,\n RouteName extends keyof ParamList\n> =\n | React.ComponentType<{\n route: RouteProp<ParamList, RouteName>;\n navigation: any;\n }>\n | React.ComponentType<{}>;\n\nexport type RouteConfigComponent<\n ParamList extends ParamListBase,\n RouteName extends keyof ParamList\n> =\n | {\n /**\n * React component to render for this screen.\n */\n component: ScreenComponentType<ParamList, RouteName>;\n getComponent?: never;\n children?: never;\n }\n | {\n /**\n * Lazily get a React component to render for this screen.\n */\n getComponent: () => ScreenComponentType<ParamList, RouteName>;\n component?: never;\n children?: never;\n }\n | {\n /**\n * Render callback to render content of this screen.\n */\n children: (props: {\n route: RouteProp<ParamList, RouteName>;\n navigation: any;\n }) => React.ReactNode;\n component?: never;\n getComponent?: never;\n };\n\nexport type RouteConfig<\n ParamList extends ParamListBase,\n RouteName extends keyof ParamList,\n State extends NavigationState,\n ScreenOptions extends {},\n EventMap extends EventMapBase\n> = {\n /**\n * Optional key for this screen. This doesn't need to be unique.\n * If the key changes, existing screens with this name will be removed or reset.\n * Useful when we have some common screens and have conditional rendering.\n */\n navigationKey?: string;\n\n /**\n * Route name of this screen.\n */\n name: RouteName;\n\n /**\n * Navigator options for this screen.\n */\n options?:\n | ScreenOptions\n | ((props: {\n route: RouteProp<ParamList, RouteName>;\n navigation: any;\n }) => ScreenOptions);\n\n /**\n * Event listeners for this screen.\n */\n listeners?:\n | ScreenListeners<State, EventMap>\n | ((props: {\n route: RouteProp<ParamList, RouteName>;\n navigation: any;\n }) => ScreenListeners<State, EventMap>);\n\n /**\n * Function to return an unique ID for this screen.\n * Receives an object with the route params.\n * For a given screen name, there will always be only one screen corresponding to an ID.\n * If `undefined` is returned, it acts same as no `getId` being specified.\n */\n getId?: ({ params }: { params: ParamList[RouteName] }) => string | undefined;\n\n /**\n * Initial params object for the route.\n */\n initialParams?: Partial<ParamList[RouteName]>;\n} & RouteConfigComponent<ParamList, RouteName>;\n\nexport type RouteGroupConfig<\n ParamList extends ParamListBase,\n ScreenOptions extends {}\n> = {\n /**\n * Optional key for the screens in this group.\n * If the key changes, all existing screens in this group will be removed or reset.\n */\n navigationKey?: string;\n\n /**\n * Navigator options for this screen.\n */\n screenOptions?:\n | ScreenOptions\n | ((props: {\n route: RouteProp<ParamList, keyof ParamList>;\n navigation: any;\n }) => ScreenOptions);\n /**\n * Children React Elements to extract the route configuration from.\n * Only `Screen`, `Group` and `React.Fragment` are supported as children.\n */\n children: React.ReactNode;\n};\n\nexport type NavigationContainerEventMap = {\n /**\n * Event which fires when the navigation state changes.\n */\n state: {\n data: {\n /**\n * The updated state object after the state change.\n */\n state: NavigationState | PartialState<NavigationState> | undefined;\n };\n };\n /**\n * Event which fires when current options changes.\n */\n options: { data: { options: object } };\n /**\n * Event which fires when an action is dispatched.\n * Only intended for debugging purposes, don't use it for app logic.\n * This event will be emitted before state changes have been applied.\n */\n __unsafe_action__: {\n data: {\n /**\n * The action object which was dispatched.\n */\n action: NavigationAction;\n /**\n * Whether the action was a no-op, i.e. resulted any state changes.\n */\n noop: boolean;\n /**\n * Stack trace of the action, this will only be available during development.\n */\n stack: string | undefined;\n };\n };\n};\n\nexport type NavigationContainerRef<ParamList extends {}> =\n NavigationHelpers<ParamList> &\n EventConsumer<NavigationContainerEventMap> & {\n /**\n * Reset the navigation state of the root navigator to the provided state.\n *\n * @param state Navigation state object.\n */\n resetRoot(state?: PartialState<NavigationState> | NavigationState): void;\n /**\n * Get the rehydrated navigation state of the navigation tree.\n */\n getRootState(): NavigationState;\n /**\n * Get the currently focused navigation route.\n */\n getCurrentRoute(): Route<string> | undefined;\n /**\n * Get the currently focused route's options.\n */\n getCurrentOptions(): object | undefined;\n /**\n * Whether the navigation container is ready to handle actions.\n */\n isReady(): boolean;\n };\n\nexport type NavigationContainerRefWithCurrent<ParamList extends {}> =\n NavigationContainerRef<ParamList> & {\n current: NavigationContainerRef<ParamList> | null;\n };\n\nexport type TypedNavigator<\n ParamList extends ParamListBase,\n State extends NavigationState,\n ScreenOptions extends {},\n EventMap extends EventMapBase,\n Navigator extends React.ComponentType<any>\n> = {\n /**\n * Navigator component which manages the child screens.\n */\n Navigator: React.ComponentType<\n Omit<\n React.ComponentProps<Navigator>,\n keyof DefaultNavigatorOptions<any, any, any, any>\n > &\n DefaultNavigatorOptions<ParamList, State, ScreenOptions, EventMap>\n >;\n /**\n * Component used for grouping multiple route configuration.\n */\n Group: React.ComponentType<RouteGroupConfig<ParamList, ScreenOptions>>;\n /**\n * Component used for specifying route configuration.\n */\n Screen: <RouteName extends keyof ParamList>(\n _: RouteConfig<ParamList, RouteName, State, ScreenOptions, EventMap>\n ) => null;\n};\n\nexport type NavigatorScreenParams<\n ParamList,\n State extends NavigationState = NavigationState\n> =\n | {\n screen?: never;\n params?: never;\n initial?: never;\n path?: string;\n state: PartialState<State> | State | undefined;\n }\n | {\n [RouteName in keyof ParamList]: undefined extends ParamList[RouteName]\n ? {\n screen: RouteName;\n params?: ParamList[RouteName];\n initial?: boolean;\n path?: string;\n state?: never;\n }\n : {\n screen: RouteName;\n params: ParamList[RouteName];\n initial?: boolean;\n path?: string;\n state?: never;\n };\n }[keyof ParamList];\n\nexport type PathConfig<ParamList extends {}> = {\n path?: string;\n exact?: boolean;\n parse?: Record<string, (value: string) => any>;\n stringify?: Record<string, (value: any) => string>;\n screens?: PathConfigMap<ParamList>;\n initialRouteName?: keyof ParamList;\n};\n\nexport type PathConfigMap<ParamList extends {}> = {\n [RouteName in keyof ParamList]?: NonNullable<\n ParamList[RouteName]\n > extends NavigatorScreenParams<infer T, any>\n ? string | PathConfig<T>\n : string | Omit<PathConfig<{}>, 'screens' | 'initialRouteName'>;\n};\n"]}
|
|
@@ -22,12 +22,15 @@ function useChildListeners() {
|
|
|
22
22
|
focus: []
|
|
23
23
|
});
|
|
24
24
|
const addListener = React.useCallback((type, listener) => {
|
|
25
|
-
// @ts-expect-error: listener should be correct type according to `type`
|
|
26
25
|
listeners[type].push(listener);
|
|
26
|
+
let removed = false;
|
|
27
27
|
return () => {
|
|
28
|
-
// @ts-expect-error: listener should be correct type according to `type`
|
|
29
28
|
const index = listeners[type].indexOf(listener);
|
|
30
|
-
|
|
29
|
+
|
|
30
|
+
if (!removed && index > -1) {
|
|
31
|
+
removed = true;
|
|
32
|
+
listeners[type].splice(index, 1);
|
|
33
|
+
}
|
|
31
34
|
};
|
|
32
35
|
}, [listeners]);
|
|
33
36
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["useChildListeners.tsx"],"names":["useChildListeners","current","listeners","React","useRef","action","focus","addListener","useCallback","type","listener","push","index","indexOf","splice"],"mappings":";;;;;;;AAAA;;;;;;AAIA;AACA;AACA;AACe,SAASA,iBAAT,GAA6B;AAC1C,QAAM;AAAEC,IAAAA,OAAO,EAAEC;AAAX,MAAyBC,KAAK,CAACC,MAAN,CAE5B;AACDC,IAAAA,MAAM,EAAE,EADP;AAEDC,IAAAA,KAAK,EAAE;AAFN,GAF4B,CAA/B;AAOA,QAAMC,WAAW,GAAGJ,KAAK,CAACK,WAAN,CAClB,CAA8BC,IAA9B,EAAuCC,QAAvC,KAAoE;
|
|
1
|
+
{"version":3,"sources":["useChildListeners.tsx"],"names":["useChildListeners","current","listeners","React","useRef","action","focus","addListener","useCallback","type","listener","push","removed","index","indexOf","splice"],"mappings":";;;;;;;AAAA;;;;;;AAIA;AACA;AACA;AACe,SAASA,iBAAT,GAA6B;AAC1C,QAAM;AAAEC,IAAAA,OAAO,EAAEC;AAAX,MAAyBC,KAAK,CAACC,MAAN,CAE5B;AACDC,IAAAA,MAAM,EAAE,EADP;AAEDC,IAAAA,KAAK,EAAE;AAFN,GAF4B,CAA/B;AAOA,QAAMC,WAAW,GAAGJ,KAAK,CAACK,WAAN,CAClB,CAA8BC,IAA9B,EAAuCC,QAAvC,KAAoE;AAClER,IAAAA,SAAS,CAACO,IAAD,CAAT,CAAgBE,IAAhB,CAAqBD,QAArB;AAEA,QAAIE,OAAO,GAAG,KAAd;AACA,WAAO,MAAM;AACX,YAAMC,KAAK,GAAGX,SAAS,CAACO,IAAD,CAAT,CAAgBK,OAAhB,CAAwBJ,QAAxB,CAAd;;AAEA,UAAI,CAACE,OAAD,IAAYC,KAAK,GAAG,CAAC,CAAzB,EAA4B;AAC1BD,QAAAA,OAAO,GAAG,IAAV;AACAV,QAAAA,SAAS,CAACO,IAAD,CAAT,CAAgBM,MAAhB,CAAuBF,KAAvB,EAA8B,CAA9B;AACD;AACF,KAPD;AAQD,GAbiB,EAclB,CAACX,SAAD,CAdkB,CAApB;AAiBA,SAAO;AACLA,IAAAA,SADK;AAELK,IAAAA;AAFK,GAAP;AAID","sourcesContent":["import * as React from 'react';\n\nimport type { ListenerMap } from './NavigationBuilderContext';\n\n/**\n * Hook which lets child navigators add action listeners.\n */\nexport default function useChildListeners() {\n const { current: listeners } = React.useRef<{\n [K in keyof ListenerMap]: ListenerMap[K][];\n }>({\n action: [],\n focus: [],\n });\n\n const addListener = React.useCallback(\n <T extends keyof ListenerMap>(type: T, listener: ListenerMap[T]) => {\n listeners[type].push(listener);\n\n let removed = false;\n return () => {\n const index = listeners[type].indexOf(listener);\n\n if (!removed && index > -1) {\n removed = true;\n listeners[type].splice(index, 1);\n }\n };\n },\n [listeners]\n );\n\n return {\n listeners,\n addListener,\n };\n}\n"]}
|