forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSuspenseTreeContext.js
More file actions
468 lines (437 loc) · 16.6 KB
/
SuspenseTreeContext.js
File metadata and controls
468 lines (437 loc) · 16.6 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
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
468
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {ReactContext} from 'shared/ReactTypes';
import type {SuspenseNode} from 'react-devtools-shared/src/frontend/types';
import type Store from '../../store';
import * as React from 'react';
import {
createContext,
startTransition,
useContext,
useEffect,
useMemo,
useReducer,
} from 'react';
import {StoreContext} from '../context';
export type SuspenseTreeState = {
lineage: $ReadOnlyArray<SuspenseNode['id']> | null,
roots: $ReadOnlyArray<SuspenseNode['id']>,
selectedSuspenseID: SuspenseNode['id'] | null,
timeline: $ReadOnlyArray<SuspenseNode['id']>,
timelineIndex: number | -1,
hoveredTimelineIndex: number | -1,
uniqueSuspendersOnly: boolean,
playing: boolean,
autoSelect: boolean,
autoScroll: {id: number}, // Ref that's set to 0 after scrolling once.
};
type ACTION_SUSPENSE_TREE_MUTATION = {
type: 'HANDLE_SUSPENSE_TREE_MUTATION',
payload: [Map<SuspenseNode['id'], SuspenseNode['id']>],
};
type ACTION_SET_SUSPENSE_LINEAGE = {
type: 'SET_SUSPENSE_LINEAGE',
payload: SuspenseNode['id'],
};
type ACTION_SELECT_SUSPENSE_BY_ID = {
type: 'SELECT_SUSPENSE_BY_ID',
payload: SuspenseNode['id'],
};
type ACTION_SET_SUSPENSE_TIMELINE = {
type: 'SET_SUSPENSE_TIMELINE',
payload: [
$ReadOnlyArray<SuspenseNode['id']>,
// The next Suspense ID to select in the timeline
SuspenseNode['id'] | null,
// Whether this timeline includes only unique suspenders
boolean,
],
};
type ACTION_SUSPENSE_SET_TIMELINE_INDEX = {
type: 'SUSPENSE_SET_TIMELINE_INDEX',
payload: number,
};
type ACTION_SUSPENSE_SKIP_TIMELINE_INDEX = {
type: 'SUSPENSE_SKIP_TIMELINE_INDEX',
payload: boolean,
};
type ACTION_SUSPENSE_PLAY_PAUSE = {
type: 'SUSPENSE_PLAY_PAUSE',
payload: 'toggle' | 'play' | 'pause',
};
type ACTION_SUSPENSE_PLAY_TICK = {
type: 'SUSPENSE_PLAY_TICK',
};
type ACTION_TOGGLE_TIMELINE_FOR_ID = {
type: 'TOGGLE_TIMELINE_FOR_ID',
payload: SuspenseNode['id'],
};
type ACTION_HOVER_TIMELINE_FOR_ID = {
type: 'HOVER_TIMELINE_FOR_ID',
payload: SuspenseNode['id'],
};
export type SuspenseTreeAction =
| ACTION_SUSPENSE_TREE_MUTATION
| ACTION_SET_SUSPENSE_LINEAGE
| ACTION_SELECT_SUSPENSE_BY_ID
| ACTION_SET_SUSPENSE_TIMELINE
| ACTION_SUSPENSE_SET_TIMELINE_INDEX
| ACTION_SUSPENSE_SKIP_TIMELINE_INDEX
| ACTION_SUSPENSE_PLAY_PAUSE
| ACTION_SUSPENSE_PLAY_TICK
| ACTION_TOGGLE_TIMELINE_FOR_ID
| ACTION_HOVER_TIMELINE_FOR_ID;
export type SuspenseTreeDispatch = (action: SuspenseTreeAction) => void;
const SuspenseTreeStateContext: ReactContext<SuspenseTreeState> =
createContext<SuspenseTreeState>(((null: any): SuspenseTreeState));
SuspenseTreeStateContext.displayName = 'SuspenseTreeStateContext';
const SuspenseTreeDispatcherContext: ReactContext<SuspenseTreeDispatch> =
createContext<SuspenseTreeDispatch>(((null: any): SuspenseTreeDispatch));
SuspenseTreeDispatcherContext.displayName = 'SuspenseTreeDispatcherContext';
type Props = {
children: React$Node,
};
function getInitialState(store: Store): SuspenseTreeState {
const uniqueSuspendersOnly = true;
const timeline =
store.getSuspendableDocumentOrderSuspense(uniqueSuspendersOnly);
const timelineIndex = timeline.length - 1;
const selectedSuspenseID =
timelineIndex === -1 ? null : timeline[timelineIndex];
const lineage =
selectedSuspenseID !== null
? store.getSuspenseLineage(selectedSuspenseID)
: [];
const initialState: SuspenseTreeState = {
selectedSuspenseID,
lineage,
roots: store.roots,
timeline,
timelineIndex,
hoveredTimelineIndex: -1,
uniqueSuspendersOnly,
playing: false,
autoSelect: true,
autoScroll: {id: 0}, // Don't auto-scroll initially
};
return initialState;
}
function SuspenseTreeContextController({children}: Props): React.Node {
const store = useContext(StoreContext);
// This reducer is created inline because it needs access to the Store.
// The store is mutable, but the Store itself is global and lives for the lifetime of the DevTools,
// so it's okay for the reducer to have an empty dependencies array.
const reducer = useMemo(
() =>
(
state: SuspenseTreeState,
action: SuspenseTreeAction,
): SuspenseTreeState => {
switch (action.type) {
case 'HANDLE_SUSPENSE_TREE_MUTATION': {
let {selectedSuspenseID} = state;
// If the currently-selected Element has been removed from the tree, update selection state.
const removedIDs = action.payload[0];
// Find the closest parent that wasn't removed during this batch.
// We deduce the parent-child mapping from removedIDs (id -> parentID)
// because by now it's too late to read them from the store.
while (
selectedSuspenseID !== null &&
removedIDs.has(selectedSuspenseID)
) {
// $FlowExpectedError[incompatible-type]
selectedSuspenseID = removedIDs.get(selectedSuspenseID);
}
if (selectedSuspenseID === 0) {
// The whole root was removed.
selectedSuspenseID = null;
}
let selectedTimelineID =
state.timeline === null
? null
: state.timeline[state.timelineIndex];
while (
selectedTimelineID !== null &&
removedIDs.has(selectedTimelineID)
) {
// $FlowExpectedError[incompatible-type]
selectedTimelineID = removedIDs.get(selectedTimelineID);
}
// TODO: Handle different timeline modes (e.g. random order)
const nextTimeline = store.getSuspendableDocumentOrderSuspense(
state.uniqueSuspendersOnly,
);
let nextTimelineIndex =
selectedTimelineID === null || nextTimeline.length === 0
? -1
: nextTimeline.indexOf(selectedTimelineID);
if (
nextTimeline.length > 0 &&
(nextTimelineIndex === -1 || state.autoSelect)
) {
nextTimelineIndex = nextTimeline.length - 1;
selectedSuspenseID = nextTimeline[nextTimelineIndex];
}
if (selectedSuspenseID === null && nextTimeline.length > 0) {
selectedSuspenseID = nextTimeline[nextTimeline.length - 1];
}
const nextLineage =
selectedSuspenseID !== null &&
state.selectedSuspenseID !== selectedSuspenseID
? store.getSuspenseLineage(selectedSuspenseID)
: state.lineage;
return {
...state,
lineage: nextLineage,
roots: store.roots,
selectedSuspenseID,
timeline: nextTimeline,
timelineIndex: nextTimelineIndex,
};
}
case 'SELECT_SUSPENSE_BY_ID': {
const selectedSuspenseID = action.payload;
return {
...state,
selectedSuspenseID,
playing: false, // pause
autoSelect: false,
autoScroll: {id: selectedSuspenseID}, // scroll
};
}
case 'SET_SUSPENSE_LINEAGE': {
const suspenseID = action.payload;
const lineage = store.getSuspenseLineage(suspenseID);
return {
...state,
lineage,
selectedSuspenseID: suspenseID,
playing: false, // pause
autoSelect: false,
};
}
case 'SET_SUSPENSE_TIMELINE': {
const previousMilestoneIndex = state.timelineIndex;
const previousTimeline = state.timeline;
const nextTimeline = action.payload[0];
const nextRootID: SuspenseNode['id'] | null = action.payload[1];
const nextUniqueSuspendersOnly = action.payload[2];
let nextLineage = state.lineage;
let nextMilestoneIndex: number | -1 = -1;
let nextSelectedSuspenseID = state.selectedSuspenseID;
// Action has indicated it has no preference for the selected Node.
// Try to reconcile the new timeline with the previous index.
if (
nextRootID === null &&
previousTimeline !== null &&
previousMilestoneIndex !== null
) {
const previousMilestoneID =
previousTimeline[previousMilestoneIndex];
nextMilestoneIndex = nextTimeline.indexOf(previousMilestoneID);
if (nextMilestoneIndex === -1 && nextTimeline.length > 0) {
nextMilestoneIndex = nextTimeline.length - 1;
nextSelectedSuspenseID = nextTimeline[nextMilestoneIndex];
nextLineage = store.getSuspenseLineage(nextSelectedSuspenseID);
}
} else if (nextRootID !== null) {
nextMilestoneIndex = nextTimeline.length - 1;
nextSelectedSuspenseID = nextTimeline[nextMilestoneIndex];
nextLineage = store.getSuspenseLineage(nextSelectedSuspenseID);
}
return {
...state,
selectedSuspenseID: nextSelectedSuspenseID,
lineage: nextLineage,
timeline: nextTimeline,
timelineIndex: nextMilestoneIndex,
uniqueSuspendersOnly: nextUniqueSuspendersOnly,
};
}
case 'SUSPENSE_SET_TIMELINE_INDEX': {
const nextTimelineIndex = action.payload;
const nextSelectedSuspenseID = state.timeline[nextTimelineIndex];
const nextLineage = store.getSuspenseLineage(
nextSelectedSuspenseID,
);
return {
...state,
lineage: nextLineage,
selectedSuspenseID: nextSelectedSuspenseID,
timelineIndex: nextTimelineIndex,
playing: false, // pause
autoSelect: false,
autoScroll: {id: nextSelectedSuspenseID}, // scroll
};
}
case 'SUSPENSE_SKIP_TIMELINE_INDEX': {
const direction = action.payload;
const nextTimelineIndex =
state.timelineIndex + (direction ? 1 : -1);
if (
nextTimelineIndex < 0 ||
nextTimelineIndex > state.timeline.length - 1
) {
return state;
}
const nextSelectedSuspenseID = state.timeline[nextTimelineIndex];
const nextLineage = store.getSuspenseLineage(
nextSelectedSuspenseID,
);
return {
...state,
lineage: nextLineage,
selectedSuspenseID: nextSelectedSuspenseID,
timelineIndex: nextTimelineIndex,
playing: false, // pause
autoSelect: false,
autoScroll: {id: nextSelectedSuspenseID}, // scroll
};
}
case 'SUSPENSE_PLAY_PAUSE': {
const mode = action.payload;
let nextTimelineIndex = state.timelineIndex;
let nextSelectedSuspenseID = state.selectedSuspenseID;
let nextLineage = state.lineage;
if (
!state.playing &&
mode !== 'pause' &&
nextTimelineIndex === state.timeline.length - 1
) {
// If we're restarting at the end. Then loop around and start again from the beginning.
nextTimelineIndex = 0;
nextSelectedSuspenseID = state.timeline[nextTimelineIndex];
nextLineage = store.getSuspenseLineage(nextSelectedSuspenseID);
}
return {
...state,
lineage: nextLineage,
selectedSuspenseID: nextSelectedSuspenseID,
timelineIndex: nextTimelineIndex,
playing: mode === 'toggle' ? !state.playing : mode === 'play',
autoSelect: false,
};
}
case 'SUSPENSE_PLAY_TICK': {
if (!state.playing) {
// We stopped but haven't yet cleaned up the callback. Noop.
return state;
}
// Advance time
const nextTimelineIndex = state.timelineIndex + 1;
if (nextTimelineIndex > state.timeline.length - 1) {
return state;
}
const nextSelectedSuspenseID = state.timeline[nextTimelineIndex];
const nextLineage = store.getSuspenseLineage(
nextSelectedSuspenseID,
);
// Stop once we reach the end.
const nextPlaying = nextTimelineIndex < state.timeline.length - 1;
return {
...state,
lineage: nextLineage,
selectedSuspenseID: nextSelectedSuspenseID,
timelineIndex: nextTimelineIndex,
playing: nextPlaying,
autoScroll: {id: nextSelectedSuspenseID}, // scroll
};
}
case 'TOGGLE_TIMELINE_FOR_ID': {
const suspenseID = action.payload;
const timelineIndexForSuspenseID =
state.timeline.indexOf(suspenseID);
if (timelineIndexForSuspenseID === -1) {
// This boundary is no longer in the timeline.
return state;
}
const nextTimelineIndex =
timelineIndexForSuspenseID === 0
? // For roots, there's no toggling. It's always just jump to beginning.
0
: // For boundaries, we'll either jump to before or after its reveal depending
// on if we're currently displaying it or not according to the timeline.
state.timelineIndex < timelineIndexForSuspenseID
? // We're currently before this suspense boundary has been revealed so we
// should jump ahead to reveal it.
timelineIndexForSuspenseID
: // Otherwise, if we're currently showing it, jump to right before to hide it.
timelineIndexForSuspenseID - 1;
const nextSelectedSuspenseID = state.timeline[nextTimelineIndex];
const nextLineage = store.getSuspenseLineage(
nextSelectedSuspenseID,
);
return {
...state,
lineage: nextLineage,
selectedSuspenseID: nextSelectedSuspenseID,
timelineIndex: nextTimelineIndex,
playing: false, // pause
autoSelect: false,
autoScroll: {id: nextSelectedSuspenseID},
};
}
case 'HOVER_TIMELINE_FOR_ID': {
const suspenseID = action.payload;
const timelineIndexForSuspenseID =
state.timeline.indexOf(suspenseID);
return {
...state,
hoveredTimelineIndex: timelineIndexForSuspenseID,
};
}
default:
throw new Error(`Unrecognized action "${action.type}"`);
}
},
[],
);
const [state, dispatch] = useReducer(reducer, store, getInitialState);
const initialRevision = useMemo(() => store.revisionSuspense, [store]);
// We're currently storing everything Suspense related in the same Store as
// Components. However, most reads are currently stateless. This ensures
// the latest state is always read from the Store.
useEffect(() => {
const handleSuspenseTreeMutated = ([removedElementIDs]: [
Map<number, number>,
]) => {
dispatch({
type: 'HANDLE_SUSPENSE_TREE_MUTATION',
payload: [removedElementIDs],
});
};
// Since this is a passive effect, the tree may have been mutated before our initial subscription.
if (store.revisionSuspense !== initialRevision) {
// At the moment, we can treat this as a mutation.
handleSuspenseTreeMutated([new Map()]);
}
store.addListener('suspenseTreeMutated', handleSuspenseTreeMutated);
return () =>
store.removeListener('suspenseTreeMutated', handleSuspenseTreeMutated);
}, [initialRevision, store]);
const transitionDispatch = useMemo(
() => (action: SuspenseTreeAction) =>
startTransition(() => {
dispatch(action);
}),
[dispatch],
);
return (
<SuspenseTreeStateContext.Provider value={state}>
<SuspenseTreeDispatcherContext.Provider value={transitionDispatch}>
{children}
</SuspenseTreeDispatcherContext.Provider>
</SuspenseTreeStateContext.Provider>
);
}
export {
SuspenseTreeDispatcherContext,
SuspenseTreeStateContext,
SuspenseTreeContextController,
};