forked from remix-run/react-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
387 lines (351 loc) · 9.37 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import * as React from "react";
import type {
GestureResponderEvent,
TouchableHighlightProps,
} from "react-native";
import { BackHandler, Linking, TouchableHighlight } from "react-native";
import type {
To,
MemoryRouterProps,
NavigateOptions,
RelativeRoutingType,
} from "react-router";
import { MemoryRouter, useLocation, useNavigate } from "react-router";
import URLSearchParams from "@ungap/url-search-params";
////////////////////////////////////////////////////////////////////////////////
// RE-EXPORTS
////////////////////////////////////////////////////////////////////////////////
// Note: Keep in sync with react-router exports!
export type {
ActionFunction,
ActionFunctionArgs,
AwaitProps,
Blocker,
BlockerFunction,
DataRouteMatch,
DataRouteObject,
unstable_DataStrategyFunction,
unstable_DataStrategyFunctionArgs,
unstable_DataStrategyMatch,
ErrorResponse,
Fetcher,
FutureConfig,
Hash,
IndexRouteObject,
IndexRouteProps,
JsonFunction,
LazyRouteFunction,
LayoutRouteProps,
LoaderFunction,
LoaderFunctionArgs,
Location,
MemoryRouterProps,
NavigateFunction,
NavigateOptions,
NavigateProps,
Navigation,
Navigator,
NonIndexRouteObject,
OutletProps,
Params,
ParamParseKey,
Path,
PathMatch,
Pathname,
PathParam,
PathPattern,
PathRouteProps,
RedirectFunction,
RelativeRoutingType,
RouteMatch,
RouteObject,
RouteProps,
RouterProps,
RouterProviderProps,
RoutesProps,
Search,
ShouldRevalidateFunction,
ShouldRevalidateFunctionArgs,
To,
UIMatch,
unstable_HandlerResult,
} from "react-router";
export {
AbortedDeferredError,
Await,
MemoryRouter,
Navigate,
NavigationType,
Outlet,
Route,
Router,
RouterProvider,
Routes,
createMemoryRouter,
createPath,
createRoutesFromChildren,
createRoutesFromElements,
defer,
isRouteErrorResponse,
generatePath,
json,
matchPath,
matchRoutes,
parsePath,
redirect,
redirectDocument,
renderMatches,
resolvePath,
useActionData,
useAsyncError,
useAsyncValue,
useBlocker,
useHref,
useInRouterContext,
useLoaderData,
useLocation,
useMatch,
useMatches,
useNavigate,
useNavigation,
useNavigationType,
useOutlet,
useOutletContext,
useParams,
useResolvedPath,
useRevalidator,
useRouteError,
useRouteLoaderData,
useRoutes,
} from "react-router";
///////////////////////////////////////////////////////////////////////////////
// DANGER! PLEASE READ ME!
// We provide these exports as an escape hatch in the event that you need any
// routing data that we don't provide an explicit API for. With that said, we
// want to cover your use case if we can, so if you feel the need to use these
// we want to hear from you. Let us know what you're building and we'll do our
// best to make sure we can support you!
//
// We consider these exports an implementation detail and do not guarantee
// against any breaking changes, regardless of the semver release. Use with
// extreme caution and only if you understand the consequences. Godspeed.
///////////////////////////////////////////////////////////////////////////////
/** @internal */
export {
UNSAFE_DataRouterContext,
UNSAFE_DataRouterStateContext,
UNSAFE_NavigationContext,
UNSAFE_LocationContext,
UNSAFE_RouteContext,
UNSAFE_useRouteId,
} from "react-router";
////////////////////////////////////////////////////////////////////////////////
// COMPONENTS
////////////////////////////////////////////////////////////////////////////////
export interface NativeRouterProps extends MemoryRouterProps {}
/**
* A `<Router>` that runs on React Native.
*/
export function NativeRouter(props: NativeRouterProps) {
return <MemoryRouter {...props} />;
}
export interface LinkProps extends TouchableHighlightProps {
children?: React.ReactNode;
onPress?: (event: GestureResponderEvent) => void;
relative?: RelativeRoutingType;
replace?: boolean;
state?: any;
to: To;
}
/**
* A `<TouchableHighlight>` that navigates to a different URL when touched.
*/
export function Link({
onPress,
relative,
replace = false,
state,
to,
...rest
}: LinkProps) {
let internalOnPress = useLinkPressHandler(to, { replace, state, relative });
function handlePress(event: GestureResponderEvent) {
if (onPress) onPress(event);
if (!event.defaultPrevented) {
internalOnPress(event);
}
}
return <TouchableHighlight {...rest} onPress={handlePress} />;
}
////////////////////////////////////////////////////////////////////////////////
// HOOKS
////////////////////////////////////////////////////////////////////////////////
const HardwareBackPressEventType = "hardwareBackPress";
const URLEventType = "url";
/**
* Handles the press behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same press behavior we
* use in our exported `<Link>`.
*/
export function useLinkPressHandler(
to: To,
{
replace,
state,
relative,
}: {
replace?: boolean;
state?: any;
relative?: RelativeRoutingType;
} = {}
): (event: GestureResponderEvent) => void {
let navigate = useNavigate();
return function handlePress() {
navigate(to, { replace, state, relative });
};
}
/**
* Enables support for the hardware back button on Android.
*/
export function useHardwareBackButton() {
React.useEffect(() => {
function handleHardwardBackPress() {
return undefined;
// TODO: The implementation will be something like this
// if (history.index === 0) {
// return false; // home screen
// } else {
// history.back();
// return true;
// }
}
BackHandler.addEventListener(
HardwareBackPressEventType,
handleHardwardBackPress
);
return () => {
BackHandler.removeEventListener(
HardwareBackPressEventType,
handleHardwardBackPress
);
};
}, []);
}
export { useHardwareBackButton as useAndroidBackButton };
/**
* Enables deep linking, both on the initial app launch and for
* subsequent incoming links.
*/
export function useDeepLinking() {
let navigate = useNavigate();
// Get the initial URL
React.useEffect(() => {
let current = true;
Linking.getInitialURL().then((url) => {
if (current) {
if (url) navigate(trimScheme(url));
}
});
return () => {
current = false;
};
}, [navigate]);
// Listen for URL changes
React.useEffect(() => {
function handleURLChange(event: { url: string }) {
navigate(trimScheme(event.url));
}
Linking.addEventListener(URLEventType, handleURLChange);
return () => {
Linking.removeEventListener(URLEventType, handleURLChange);
};
}, [navigate]);
}
function trimScheme(url: string) {
return url.replace(/^.*?:\/\//, "");
}
/**
* A convenient wrapper for accessing individual query parameters via the
* URLSearchParams interface.
*/
export function useSearchParams(
defaultInit?: URLSearchParamsInit
): [URLSearchParams, SetURLSearchParams] {
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
let hasSetSearchParamsRef = React.useRef(false);
let location = useLocation();
let searchParams = React.useMemo(() => {
let searchParams = createSearchParams(location.search);
if (!hasSetSearchParamsRef.current) {
for (let key of defaultSearchParamsRef.current.keys()) {
if (!searchParams.has(key)) {
defaultSearchParamsRef.current.getAll(key).forEach((value) => {
searchParams.append(key, value);
});
}
}
}
return searchParams;
}, [location.search]);
let navigate = useNavigate();
let setSearchParams = React.useCallback<SetURLSearchParams>(
(nextInit, navigateOpts) => {
const newSearchParams = createSearchParams(
typeof nextInit === "function" ? nextInit(searchParams) : nextInit
);
hasSetSearchParamsRef.current = true;
navigate("?" + newSearchParams, navigateOpts);
},
[navigate, searchParams]
);
return [searchParams, setSearchParams];
}
export type SetURLSearchParams = (
nextInit?:
| URLSearchParamsInit
| ((prev: URLSearchParams) => URLSearchParamsInit),
navigateOpts?: NavigateOptions
) => void;
export type ParamKeyValuePair = [string, string];
export type URLSearchParamsInit =
| string
| ParamKeyValuePair[]
| Record<string, string | string[]>
| URLSearchParams;
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also
* supports arrays as values in the object form of the initializer
* instead of just strings. This is convenient when you need multiple
* values for a given key, but don't want to use an array initializer.
*
* For example, instead of:
*
* let searchParams = new URLSearchParams([
* ['sort', 'name'],
* ['sort', 'price']
* ]);
*
* you can do:
*
* let searchParams = createSearchParams({
* sort: ['name', 'price']
* });
*/
export function createSearchParams(
init: URLSearchParamsInit = ""
): URLSearchParams {
return new URLSearchParams(
typeof init === "string" ||
Array.isArray(init) ||
init instanceof URLSearchParams
? init
: Object.keys(init).reduce((memo, key) => {
let value = init[key];
return memo.concat(
Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]
);
}, [] as ParamKeyValuePair[])
);
}