-
-
Notifications
You must be signed in to change notification settings - Fork 643
Expand file tree
/
Copy pathreducer.tsx
More file actions
382 lines (335 loc) · 10.8 KB
/
reducer.tsx
File metadata and controls
382 lines (335 loc) · 10.8 KB
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
import type { StackScreenActivityMode } from 'react-native-screens/experimental';
import type {
NavigationAction,
NavigationActionBatch,
NavigationActionClearEffects,
NavigationActionNativePop,
NavigationActionPop,
NavigationActionPopCompleted,
NavigationActionPreload,
NavigationActionPush,
NavigationActionSetRouteOptions,
StackNavigationEffect,
StackNavigationState,
StackRoute,
StackRouteConfig,
StackState,
} from './StackContainer.types';
import { generateID } from '../shared/id-generator';
import { safeStringify } from '../shared/safe-stringify';
const NOT_FOUND_INDEX = -1;
export function navigationStateReducer(
state: StackNavigationState,
action: NavigationAction,
): StackNavigationState {
switch (action.type) {
case 'push': {
return navigationActionPushHandler(state, action);
}
case 'pop': {
return navigationActionPopHandler(state, action);
}
case 'pop-completed': {
return navigationActionPopCompletedHandler(state, action);
}
case 'pop-native': {
return navigationActionNativePopHandler(state, action);
}
case 'preload': {
return navigationActionPreloadHandler(state, action);
}
case 'batch': {
return navigationActionBatchHandler(state, action);
}
case 'clear-effects': {
return navigationActionClearEffectsHandler(state, action);
}
case 'set-options': {
return navigationActionSetOptionsHandler(state, action);
}
}
// @ts-ignore
throw new Error(
`[Stack] Unhandled navigation action: ${JSON.stringify(action)}`,
);
}
export function navigationStateReducerWithLogging(
state: StackNavigationState,
action: NavigationAction,
): StackNavigationState {
console.debug(`[Stack] Handling action: ${safeStringify(action)}`);
console.debug(`[Stack] BEFORE state: ${safeStringify(state, 2)}`);
const newState = navigationStateReducer(state, action);
if (state === newState) {
console.debug('[Stack] AFTER state: unchanged');
} else {
console.debug(`[Stack] AFTER state: ${safeStringify(newState, 2)}`);
}
return newState;
}
function navigationActionPushHandler(
state: StackNavigationState,
action: NavigationActionPush,
): StackNavigationState {
// 1 - Check whether the route is already rendered
const stack = state.stack;
const renderedRouteIndex = stack.findIndex(
route =>
route.name === action.routeName && route.activityMode === 'detached' && !route.isMarkedForDismissal,
);
if (renderedRouteIndex !== NOT_FOUND_INDEX) {
const route = stack[renderedRouteIndex];
console.info(`[Stack] Route ${route.name} already rendered, attaching it`);
const newStack = stack.toSpliced(renderedRouteIndex, 1);
const routeCopy = { ...route };
routeCopy.activityMode = 'attached';
return stateWithStack(state, applyPush(newStack, routeCopy));
}
// 2 - Try to render new route
const newRouteConfig = action.ctx.routeConfigs.find(
route => route.name === action.routeName,
);
if (newRouteConfig == null) {
throw new Error(
`[Stack] Unable to find route with name: ${action.routeName}`,
);
}
const newRoute = createRouteFromConfig(newRouteConfig, 'attached');
return stateWithStack(state, applyPush(state.stack, newRoute));
}
function navigationActionPopHandler(
state: StackNavigationState,
action: NavigationActionPop,
): StackNavigationState {
// FIXME: We have a problem here. We can not really determine, which route is currently at the very top!
// For now let's just accept routeKey as param here.
const stack = state.stack;
const attachedCount = stack.reduce((count, route) => {
if (route.activityMode === 'attached') {
return count + 1;
} else {
return count;
}
}, 0);
if (attachedCount <= 1) {
console.warn(
`[Stack] Can not perform pop action on route: ${action.routeKey} - at least one route must be present`,
);
if (
state.effects.findIndex(effect => effect.type === 'pop-container') !==
NOT_FOUND_INDEX
) {
// If there is already a pop-container effect, do nothing
return state;
}
return stateWithEffects(
state,
applyEffect(state.effects, { type: 'pop-container' }),
);
}
const routeIndex = stack.findIndex(
route => route.routeKey === action.routeKey,
);
if (routeIndex === NOT_FOUND_INDEX) {
console.warn(
`[Stack] Can not perform pop action on route: ${action.routeKey} - no such route in state!`,
);
return state;
}
const route = stack[routeIndex];
if (route.activityMode === 'detached') {
console.warn(
`[Stack] Can not perform pop action on route: ${action.routeKey} - already in detached mode!`,
);
return state;
}
// Pop operation on not-top screen is forbidden and might crash.
const topAttachedRouteIndex = state.stack.findLastIndex(r => r.activityMode === 'attached');
if (topAttachedRouteIndex > routeIndex) {
console.warn(`[Stack] Can not perform pop action on route: ${action.routeKey} - not a top screen`);
return state;
}
const newStack = [...stack];
// NOTE: This modifies existing state, possibly impacting calculations done before new state is updated.
// Consider doing deep copy of the state here.
// EDIT: not sure really whether this is really a problem or not, since the updates are queued
// and the original state won't be immediatelly affected.
route.activityMode = 'detached';
route.isMarkedForDismissal = true;
return stateWithStack(state, newStack);
}
function navigationActionPopCompletedHandler(
state: StackNavigationState,
action: NavigationActionPopCompleted,
): StackNavigationState {
const stack = state.stack;
const routeIndex = stack.findIndex(
route => route.routeKey === action.routeKey,
);
if (routeIndex === NOT_FOUND_INDEX) {
console.error(
`[Stack] Can not perform 'pop-completed' action - popped screen is no longer in state!`,
);
return state;
}
const route = stack[routeIndex];
if (route.activityMode !== 'detached') {
console.warn(`[Stack] Popped non-detached route!`);
}
console.debug(`Remove route: ${action.routeKey} from index: ${routeIndex}`);
// Let's remove the route from the state
// TODO: Consider adding option for keeping it in state.
const newStack = stack.toSpliced(routeIndex, 1);
return stateWithStack(state, newStack);
}
function navigationActionNativePopHandler(
state: StackNavigationState,
action: NavigationActionNativePop,
): StackNavigationState {
const stack = state.stack;
if (stack.length <= 1) {
throw new Error(
'[Stack] action: "pop-native" can not be performed with less than 2 routes!',
);
}
const routeIndex = stack.findIndex(
route => route.routeKey === action.routeKey,
);
if (routeIndex === NOT_FOUND_INDEX) {
console.error(
`[Stack] Can not perform 'pop-native' action - popped screen is not in state!`,
);
return state;
}
const route = stack[routeIndex];
if (route.activityMode === 'detached') {
console.warn('[Stack] natively popped route has "detached" state');
}
const newStack = stack.toSpliced(routeIndex, 1);
return stateWithStack(state, newStack);
}
function navigationActionPreloadHandler(
state: StackNavigationState,
action: NavigationActionPreload,
): StackNavigationState {
const routeConfig = action.ctx.routeConfigs.find(
config => config.name === action.routeName,
);
if (!routeConfig) {
console.error(
`[Stack] Can not perform 'preload' action - route config with name: ${action.routeName} not found!`,
);
return state;
}
// Preloaded routes are kept at the end of the list to allow order manipulations
// that won't result in problems on native platform.
// More info: https://github.com/software-mansion/react-native-screens/pull/3531.
const newStack = [...state.stack, createRouteFromConfig(routeConfig)];
return stateWithStack(state, newStack);
}
function navigationActionBatchHandler(
state: StackNavigationState,
action: NavigationActionBatch,
): StackNavigationState {
return action.actions.reduce(navigationStateReducer, state);
}
function createRouteFromConfig(
config: StackRouteConfig,
activityMode: StackScreenActivityMode = 'detached',
): StackRoute {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { Component, ...rest } = config;
return {
...rest,
activityMode,
routeKey: generateRouteKeyForRouteName(config.name),
isMarkedForDismissal: false,
};
}
function navigationActionClearEffectsHandler(
state: StackNavigationState,
_action: NavigationActionClearEffects,
): StackNavigationState {
if (state.effects.length === 0) {
return state;
}
return stateWithEffects(state, []);
}
function navigationActionSetOptionsHandler(
state: StackNavigationState,
action: NavigationActionSetRouteOptions,
): StackNavigationState {
const routeIndex = state.stack.findIndex(
route => route.routeKey === action.routeKey,
);
if (routeIndex === NOT_FOUND_INDEX) {
throw new Error(
`[Stack] Can not set options. Route with key ${action.routeKey} not found`,
);
}
const routeCopy = { ...state.stack[routeIndex] };
routeCopy.options = {
...routeCopy.options,
...action.options,
};
return stateWithStack(
state,
stackWithReplacedRoute(state.stack, routeCopy, routeIndex),
);
}
// Ensures correct order of screens (attached first, detached at the end).
// This will help with state restoration but WILL NOT help with inspector.
function applyPush(state: StackState, newRoute: StackRoute): StackState {
const lastAttachedIndex = state.findLastIndex(
route => route.activityMode === 'attached',
);
if (lastAttachedIndex === NOT_FOUND_INDEX) {
throw new Error(
`[Stack] Invalid stack state: there should be at least one attached route on the stack.`,
);
}
return state.toSpliced(lastAttachedIndex + 1, 0, newRoute);
}
function applyEffect(
effects: StackNavigationEffect[],
newEffect: StackNavigationEffect,
): StackNavigationEffect[] {
return effects.concat(newEffect);
}
export function determineInitialNavigationState(
routeConfigs: StackRouteConfig[],
): StackNavigationState {
const firstRoute = createRouteFromConfig(routeConfigs[0], 'attached');
return {
stack: [firstRoute],
effects: [],
};
}
function generateRouteKeyForRouteName(routeName: string): string {
return `r-${routeName}-${generateID()}`;
}
function stateWithStack(
navState: StackNavigationState,
newStack: StackState,
): StackNavigationState {
return {
...navState,
stack: newStack,
};
}
function stateWithEffects(
navState: StackNavigationState,
newEffects: StackNavigationEffect[],
): StackNavigationState {
return {
...navState,
effects: newEffects,
};
}
function stackWithReplacedRoute(
state: StackState,
newRoute: StackRoute,
routeIndex: number,
): StackState {
return state.toSpliced(routeIndex, 1, newRoute);
}