-
-
Notifications
You must be signed in to change notification settings - Fork 209
Expand file tree
/
Copy pathActionContainer.tsx
More file actions
252 lines (234 loc) · 10.4 KB
/
Copy pathActionContainer.tsx
File metadata and controls
252 lines (234 loc) · 10.4 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
/* eslint-disable max-len */
import React, { useEffect, useState, useRef } from 'react';
import Action from '../components/Actions/Action';
import { emptySnapshots, changeSlider } from '../slices/mainSlice';
import { useDispatch, useSelector } from 'react-redux';
import RouteDescription from '../components/Actions/RouteDescription';
import DropDown from '../components/Actions/DropDown';
import ProvConContainer from './ProvConContainer';
import { ActionContainerProps, CurrentTab, MainState, Obj, RootState } from '../FrontendTypes';
import {
Button,
Dialog,
DialogTitle,
DialogContent,
DialogContentText,
DialogActions,
} from '@mui/material';
import RecordButton from '../components/Actions/RecordButton';
import { toast } from 'react-hot-toast';
import { REACTIME_TOAST_DEFAULTS } from '../utils/toastConfig';
/*
This file renders the 'ActionContainer'. The action container is the leftmost column in the application. It includes the button that shrinks and expands the action container, a dropdown to select the active site, a clear button, the current selected Route, and a list of selectable snapshots with timestamps.
*/
function ActionContainer(props: ActionContainerProps): JSX.Element {
const [dropdownSelection, setDropdownSelection] = useState('Time Jump');
const actionsEndRef = useRef(null as unknown as HTMLDivElement);
const [expandedIndex, setExpandedIndex] = useState(null as number | null); // Track which snapshot is expanded
const [clearDialogOpen, setClearDialogOpen] = useState(false); // Confirm dialog for Clear
const dispatch = useDispatch();
const { currentTab, tabs, port }: MainState = useSelector((state: RootState) => state.main);
const { currLocation, hierarchy, sliderIndex, viewIndex }: Partial<CurrentTab> = tabs[currentTab]; // we destructure the currentTab object
const { snapshots } = props;
const [recordingActions, setRecordingActions] = useState(true); // We create a local state 'recordingActions' and set it to true
// Clears all snapshots, resets the slider/expanded state, and surfaces toast feedback.
const clearSnapshotsWithFeedback = (): void => {
const clearedCount = snapshots?.length ?? 0;
dispatch(emptySnapshots()); // set slider back to zero, visually
dispatch(changeSlider(0));
setExpandedIndex(null); // Reset expanded state when clearing
if (clearedCount > 0) {
toast.success(`Cleared ${clearedCount} snapshot${clearedCount === 1 ? '' : 's'}`, {
...REACTIME_TOAST_DEFAULTS,
id: 'snapshots-cleared',
});
} else {
toast('No snapshots to clear', {
...REACTIME_TOAST_DEFAULTS,
id: 'snapshots-cleared',
icon: 'ℹ️',
});
}
};
let actionsArr: JSX.Element[] = []; // we create an array 'actionsArr' that will hold elements we create later on
// we create an array 'hierarchyArr' that will hold objects and numbers
const hierarchyArr: (number | {})[] = [];
// Auto scroll when snapshots change - but only if user hasn't manually scrolled
useEffect(() => {
if (actionsEndRef.current && snapshots && snapshots.length > 0) {
// Small delay to ensure DOM is updated
setTimeout(() => {
if (actionsEndRef.current) {
actionsEndRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' });
}
}, 100);
}
}, [snapshots?.length]);
const displayArray = (obj: Obj): void => {
if (
obj.stateSnapshot.children.length > 0 && // if the 'stateSnapshot' has a non-empty 'children' array
obj.stateSnapshot.children[0] && // and there is an element
obj.stateSnapshot.children[0].state && // with a 'state'
obj.stateSnapshot.children[0].name // and a 'name'
) {
const newObj: Record<string, unknown> = {
// we create a new Record object (whose property keys are Keys and whose property values are Type.
//This utility can be used to map the properties of a type to another type) and populate it's properties with
//relevant values from our argument 'obj'.
index: obj.index,
displayName: `${obj.index + 1}`,
state: obj.stateSnapshot.children[0].state,
componentName: obj.stateSnapshot.children[0].name,
routePath: obj.stateSnapshot.route.url,
componentData:
JSON.stringify(obj.stateSnapshot.children[0].componentData) === '{}'
? ''
: obj.stateSnapshot.children[0].componentData,
};
hierarchyArr.push(newObj); // we push our record object into 'hiearchyArr' defined on line 35
}
if (obj.children) {
// if argument has a 'children' array, we iterate through it and run 'displayArray' on each element
obj.children.forEach((element): void => {
//recursive call
displayArray(element);
});
}
};
// the hierarchy gets set on the first click in the page
if (hierarchy) displayArray(hierarchy); // when page is refreshed we may not have a hierarchy so we need to check if hierarchy was initialized. If it was initialized, invoke displayArray to display the hierarchy
// Sort hierarchyArr by index property of each object. This will be useful when later when we build our components so that our components will be displayed in index/chronological order
hierarchyArr.sort((a: Obj, b: Obj): number => a.index - b.index);
// we create a map of components that are constructed from "hierarchyArr's" elements/snapshots
actionsArr = hierarchyArr.map(
(snapshot: {
routePath: any;
state?: Record<string, unknown>;
index: number;
displayName: string;
componentName: string;
componentData: { actualDuration: number } | undefined;
}) => {
const { index } = snapshot; // destructure index from snapshot
const selected = index === viewIndex; // boolean on whether the current index is the same as the viewIndex
const last = viewIndex === -1 && index === hierarchyArr.length - 1; // boolean on whether the view index is less than 0 and if the index is the same as the last snapshot's index value in hierarchyArr
const isCurrIndex = index === currLocation.index;
return (
<Action
key={`action${index}`}
index={index}
state={snapshot.state}
displayName={snapshot.displayName}
componentName={snapshot.componentName}
componentData={snapshot.componentData}
selected={selected}
last={last}
sliderIndex={sliderIndex}
viewIndex={viewIndex}
isCurrIndex={isCurrIndex}
routePath={snapshot.routePath}
snapshots={snapshots}
hierarchy={hierarchy}
expandedIndex={expandedIndex}
setExpandedIndex={setExpandedIndex}
/>
);
},
);
// Function sends message to background.js which sends message to the content script
const toggleRecord = (): void => {
port.postMessage({
action: 'toggleRecord',
tabId: currentTab,
});
setRecordingActions(!recordingActions); // Record button's icon is being togggled on click
};
type routes = {
[route: string]: [];
};
const routes: {} = {}; // Logic to create the route description components begin
for (let i = 0; i < actionsArr.length; i += 1) {
// iterate through our actionsArr
if (!routes.hasOwnProperty(actionsArr[i].props.routePath)) {
routes[actionsArr[i].props.routePath] = [actionsArr[i]]; // if 'routes' doesn't have a property key that is the same as the current component at index[i] routePath we create an array with the first element being the component at index [i].
} else {
routes[actionsArr[i].props.routePath].push(actionsArr[i]); // If it does exist, we push the component at index [i] to the apporpriate routes[routePath]
}
}
// the conditional logic below will cause ActionContainer.test.tsx to fail as it cannot find the Empty button
// UNLESS actionView={true} is passed into <ActionContainer /> in the beforeEach() call in ActionContainer.test.tsx
return (
<div id='action-id' className='action-container'>
<div className='action-button-wrapper'>
<RecordButton
isRecording={recordingActions}
onToggle={() => {
toggleRecord();
setRecordingActions(!recordingActions);
}}
/>
<DropDown
dropdownSelection={dropdownSelection}
setDropdownSelection={setDropdownSelection}
/>
<div className='clear-button-container'>
<Button
className='clear-button-modern'
variant='text'
onClick={() => {
// Confirm before discarding a non-trivial recording session; otherwise clear directly.
if (snapshots && snapshots.length > 1) {
setClearDialogOpen(true);
} else {
clearSnapshotsWithFeedback();
}
}}
type='button'
>
Clear
</Button>
</div>
<Dialog
open={clearDialogOpen}
onClose={() => setClearDialogOpen(false)}
aria-labelledby='clear-snapshots-dialog-title'
aria-describedby='clear-snapshots-dialog-description'
>
<DialogTitle id='clear-snapshots-dialog-title'>Clear all snapshots?</DialogTitle>
<DialogContent>
<DialogContentText id='clear-snapshots-dialog-description'>
This will discard your current recording session and cannot be undone. Export your
snapshots first if you need to keep them.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => setClearDialogOpen(false)} autoFocus>
Cancel
</Button>
<Button
onClick={() => {
clearSnapshotsWithFeedback();
setClearDialogOpen(false);
}}
color='error'
>
Clear
</Button>
</DialogActions>
</Dialog>
<div className='snapshots'>
{dropdownSelection === 'Providers / Consumers' && (
<ProvConContainer currentSnapshot={currLocation.stateSnapshot} />
)}
{dropdownSelection === 'Time Jump' &&
Object.keys(routes).map((route, i) => (
<RouteDescription key={`route${i}`} actions={routes[route]} />
))}
{/* Add ref for scrolling */}
<div ref={actionsEndRef} />
</div>
</div>
</div>
);
}
export default ActionContainer;