-
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
BaseNavigationContainer.tsx
467 lines (395 loc) · 15.2 KB
/
BaseNavigationContainer.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import {
CommonActions,
InitialState,
NavigationAction,
NavigationState,
ParamListBase,
PartialState,
Route,
} from '@react-navigation/routers';
import * as React from 'react';
import useLatestCallback from 'use-latest-callback';
import { usePrevious } from '../utils/usePrevious';
import { checkDuplicateRouteNames } from './checkDuplicateRouteNames';
import { checkSerializable } from './checkSerializable';
import { NOT_INITIALIZED_ERROR } from './createNavigationContainerRef';
import { DeprecatedNavigationInChildContext } from './DeprecatedNavigationInChildContext';
import { EnsureSingleNavigator } from './EnsureSingleNavigator';
import { findFocusedRoute } from './findFocusedRoute';
import { NavigationBuilderContext } from './NavigationBuilderContext';
import { NavigationContainerRefContext } from './NavigationContainerRefContext';
import { NavigationIndependentTreeContext } from './NavigationIndependentTreeContext';
import { NavigationStateContext } from './NavigationStateContext';
import type {
NavigationContainerEventMap,
NavigationContainerProps,
NavigationContainerRef,
} from './types';
import { UnhandledActionContext } from './UnhandledActionContext';
import { useChildListeners } from './useChildListeners';
import { useEventEmitter } from './useEventEmitter';
import { useKeyedChildListeners } from './useKeyedChildListeners';
import { useNavigationIndependentTree } from './useNavigationIndependentTree';
import { useOptionsGetters } from './useOptionsGetters';
import { ScheduleUpdateContext } from './useScheduleUpdate';
import { useSyncState } from './useSyncState';
type State = NavigationState | PartialState<NavigationState> | undefined;
const serializableWarnings: string[] = [];
const duplicateNameWarnings: string[] = [];
/**
* Remove `key` and `routeNames` from the state objects recursively to get partial state.
*
* @param state Initial state object.
*/
const getPartialState = (
state: InitialState | undefined
): PartialState<NavigationState> | undefined => {
if (state === undefined) {
return;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { key, routeNames, ...partialState } = state;
return {
...partialState,
stale: true,
routes: state.routes.map((route) => {
if (route.state === undefined) {
return route as Route<string> & {
state?: PartialState<NavigationState>;
};
}
return { ...route, state: getPartialState(route.state) };
}),
};
};
/**
* Container component which holds the navigation state.
* This should be rendered at the root wrapping the whole app.
*
* @param props.initialState Initial state object for the navigation tree.
* @param props.onReady Callback which is called after the navigation tree mounts.
* @param props.onStateChange Callback which is called with the latest navigation state when it changes.
* @param props.onUnhandledAction Callback which is called when an action is not handled.
* @param props.children Child elements to render the content.
* @param props.ref Ref object which refers to the navigation object containing helper methods.
*/
export const BaseNavigationContainer = React.forwardRef(
function BaseNavigationContainer(
{
initialState,
onStateChange,
onReady,
onUnhandledAction,
navigationInChildEnabled = false,
children,
}: NavigationContainerProps,
ref?: React.Ref<NavigationContainerRef<ParamListBase>>
) {
const parent = React.useContext(NavigationStateContext);
const independent = useNavigationIndependentTree();
if (!parent.isDefault && !independent) {
throw new Error(
"Looks like you have nested a 'NavigationContainer' inside another. Normally you need only one container at the root of the app, so this was probably an error. If this was intentional, wrap the container in 'NavigationIndependentTree' explicitly. Note that this will make the child navigators disconnected from the parent and you won't be able to navigate between them."
);
}
const [state, getState, setState, scheduleUpdate, flushUpdates] =
useSyncState<State>(() =>
getPartialState(initialState == null ? undefined : initialState)
);
const isFirstMountRef = React.useRef<boolean>(true);
const navigatorKeyRef = React.useRef<string | undefined>();
const getKey = React.useCallback(() => navigatorKeyRef.current, []);
const setKey = React.useCallback((key: string) => {
navigatorKeyRef.current = key;
}, []);
const { listeners, addListener } = useChildListeners();
const { keyedListeners, addKeyedListener } = useKeyedChildListeners();
const dispatch = useLatestCallback(
(
action:
| NavigationAction
| ((state: NavigationState) => NavigationAction)
) => {
if (listeners.focus[0] == null) {
console.error(NOT_INITIALIZED_ERROR);
} else {
listeners.focus[0]((navigation) => navigation.dispatch(action));
}
}
);
const canGoBack = useLatestCallback(() => {
if (listeners.focus[0] == null) {
return false;
}
const { result, handled } = listeners.focus[0]((navigation) =>
navigation.canGoBack()
);
if (handled) {
return result;
} else {
return false;
}
});
const resetRoot = useLatestCallback(
(state?: PartialState<NavigationState> | NavigationState) => {
const target = state?.key ?? keyedListeners.getState.root?.().key;
if (target == null) {
console.error(NOT_INITIALIZED_ERROR);
} else {
listeners.focus[0]((navigation) =>
navigation.dispatch({
...CommonActions.reset(state),
target,
})
);
}
}
);
const getRootState = useLatestCallback(() => {
return keyedListeners.getState.root?.();
});
const getCurrentRoute = useLatestCallback(() => {
const state = getRootState();
if (state == null) {
return undefined;
}
const route = findFocusedRoute(state);
return route as Route<string> | undefined;
});
const isReady = useLatestCallback(() => listeners.focus[0] != null);
const emitter = useEventEmitter<NavigationContainerEventMap>();
const { addOptionsGetter, getCurrentOptions } = useOptionsGetters({});
const navigation: NavigationContainerRef<ParamListBase> = React.useMemo(
() => ({
...Object.keys(CommonActions).reduce<any>((acc, name) => {
acc[name] = (...args: any[]) =>
// @ts-expect-error: this is ok
dispatch(CommonActions[name](...args));
return acc;
}, {}),
...emitter.create('root'),
dispatch,
resetRoot,
isFocused: () => true,
canGoBack,
getParent: () => undefined,
getState: () => stateRef.current,
getRootState,
getCurrentRoute,
getCurrentOptions,
isReady,
}),
[
canGoBack,
dispatch,
emitter,
getCurrentOptions,
getCurrentRoute,
getRootState,
isReady,
resetRoot,
]
);
React.useImperativeHandle(ref, () => navigation, [navigation]);
const onDispatchAction = useLatestCallback(
(action: NavigationAction, noop: boolean) => {
emitter.emit({
type: '__unsafe_action__',
data: { action, noop, stack: stackRef.current },
});
}
);
const lastEmittedOptionsRef = React.useRef<object | undefined>();
const onOptionsChange = useLatestCallback((options: object) => {
if (lastEmittedOptionsRef.current === options) {
return;
}
lastEmittedOptionsRef.current = options;
emitter.emit({
type: 'options',
data: { options },
});
});
const stackRef = React.useRef<string | undefined>();
const builderContext = React.useMemo(
() => ({
addListener,
addKeyedListener,
onDispatchAction,
onOptionsChange,
stackRef,
}),
[addListener, addKeyedListener, onDispatchAction, onOptionsChange]
);
const scheduleContext = React.useMemo(
() => ({ scheduleUpdate, flushUpdates }),
[scheduleUpdate, flushUpdates]
);
const isInitialRef = React.useRef(true);
const getIsInitial = React.useCallback(() => isInitialRef.current, []);
const context = React.useMemo(
() => ({
state,
getState,
setState,
getKey,
setKey,
getIsInitial,
addOptionsGetter,
}),
[
state,
getState,
setState,
getKey,
setKey,
getIsInitial,
addOptionsGetter,
]
);
const onReadyRef = React.useRef(onReady);
const onStateChangeRef = React.useRef(onStateChange);
const stateRef = React.useRef(state);
React.useEffect(() => {
isInitialRef.current = false;
onStateChangeRef.current = onStateChange;
onReadyRef.current = onReady;
stateRef.current = state;
});
const onReadyCalledRef = React.useRef(false);
React.useEffect(() => {
if (!onReadyCalledRef.current && isReady()) {
onReadyCalledRef.current = true;
onReadyRef.current?.();
}
}, [state, isReady]);
React.useEffect(() => {
const hydratedState = getRootState();
if (process.env.NODE_ENV !== 'production') {
if (hydratedState !== undefined) {
const serializableResult = checkSerializable(hydratedState);
if (!serializableResult.serializable) {
const { location, reason } = serializableResult;
let path = '';
let pointer: Record<any, any> = hydratedState;
let params = false;
for (let i = 0; i < location.length; i++) {
const curr = location[i];
const prev = location[i - 1];
pointer = pointer[curr];
if (!params && curr === 'state') {
continue;
} else if (!params && curr === 'routes') {
if (path) {
path += ' > ';
}
} else if (
!params &&
typeof curr === 'number' &&
prev === 'routes'
) {
path += pointer?.name;
} else if (!params) {
path += ` > ${curr}`;
params = true;
} else {
if (typeof curr === 'number' || /^[0-9]+$/.test(curr)) {
path += `[${curr}]`;
} else if (/^[a-z$_]+$/i.test(curr)) {
path += `.${curr}`;
} else {
path += `[${JSON.stringify(curr)}]`;
}
}
}
const message = `Non-serializable values were found in the navigation state. Check:\n\n${path} (${reason})\n\nThis can break usage such as persisting and restoring state. This might happen if you passed non-serializable values such as function, class instances etc. in params. If you need to use components with callbacks in your options, you can use 'navigation.setOptions' instead. See https://reactnavigation.org/docs/troubleshooting#i-get-the-warning-non-serializable-values-were-found-in-the-navigation-state for more details.`;
if (!serializableWarnings.includes(message)) {
serializableWarnings.push(message);
console.warn(message);
}
}
const duplicateRouteNamesResult =
checkDuplicateRouteNames(hydratedState);
if (duplicateRouteNamesResult.length) {
const message = `Found screens with the same name nested inside one another. Check:\n${duplicateRouteNamesResult.map(
(locations) => `\n${locations.join(', ')}`
)}\n\nThis can cause confusing behavior during navigation. Consider using unique names for each screen instead.`;
if (!duplicateNameWarnings.includes(message)) {
duplicateNameWarnings.push(message);
console.warn(message);
}
}
}
}
emitter.emit({ type: 'state', data: { state } });
if (!isFirstMountRef.current && onStateChangeRef.current) {
onStateChangeRef.current(hydratedState);
}
isFirstMountRef.current = false;
}, [getRootState, emitter, state]);
const defaultOnUnhandledAction = useLatestCallback(
(action: NavigationAction) => {
if (process.env.NODE_ENV === 'production') {
return;
}
const payload: Record<string, any> | undefined = action.payload;
let message = `The action '${action.type}'${
payload ? ` with payload ${JSON.stringify(action.payload)}` : ''
} was not handled by any navigator.`;
switch (action.type) {
case 'NAVIGATE':
case 'PUSH':
case 'REPLACE':
case 'JUMP_TO':
if (payload?.name) {
message += `\n\nDo you have a screen named '${payload.name}'?\n\nIf you're trying to navigate to a screen in a nested navigator, see https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator.`;
} else {
message += `\n\nYou need to pass the name of the screen to navigate to.\n\nSee https://reactnavigation.org/docs/navigation-actions for usage.`;
}
break;
case 'GO_BACK':
case 'POP':
case 'POP_TO_TOP':
message += `\n\nIs there any screen to go back to?`;
break;
case 'OPEN_DRAWER':
case 'CLOSE_DRAWER':
case 'TOGGLE_DRAWER':
message += `\n\nIs your screen inside a Drawer navigator?`;
break;
}
message += `\n\nThis is a development-only warning and won't be shown in production.`;
console.error(message);
}
);
const [stateForNextRouteNamesChange, setStateForNextRouteNamesChange] =
React.useState<Record<string, PartialState<NavigationState>> | null>(
null
);
const previousState = usePrevious(state);
if (state !== previousState && stateForNextRouteNamesChange !== null) {
setStateForNextRouteNamesChange(null);
}
return (
<NavigationIndependentTreeContext.Provider value={false}>
<NavigationContainerRefContext.Provider value={navigation}>
<ScheduleUpdateContext.Provider value={scheduleContext}>
<NavigationBuilderContext.Provider value={builderContext}>
<NavigationStateContext.Provider value={context}>
<UnhandledActionContext.Provider
value={onUnhandledAction ?? defaultOnUnhandledAction}
>
<DeprecatedNavigationInChildContext.Provider
value={navigationInChildEnabled}
>
<EnsureSingleNavigator>{children}</EnsureSingleNavigator>
</DeprecatedNavigationInChildContext.Provider>
</UnhandledActionContext.Provider>
</NavigationStateContext.Provider>
</NavigationBuilderContext.Provider>
</ScheduleUpdateContext.Provider>
</NavigationContainerRefContext.Provider>
</NavigationIndependentTreeContext.Provider>
);
}
);