-
Notifications
You must be signed in to change notification settings - Fork 127
/
LoggingView.tsx
392 lines (346 loc) · 11.3 KB
/
LoggingView.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
import React, {
useState,
useEffect,
useReducer,
useRef,
FormEventHandler,
} from 'react';
import { useSelector } from 'react-redux';
import { Transition, Switch } from '@headlessui/react';
import { RootState } from '../../store/reducers';
import { TelemetryItem, STOP_OP_MODE_TAG } from '../../store/types';
import { OpModeStatus } from '../../enums/OpModeStatus';
import BaseView, {
BaseViewHeading,
BaseViewBody,
BaseViewProps,
BaseViewHeadingProps,
} from '../BaseView';
import CustomVirtualGrid from './CustomVirtualGrid';
import { DateToHHMMSS } from './DateFormatting';
import ToolTip from '../../components/ToolTip';
import useDelayedTooltip from '../../hooks/useDelayedTooltip';
import useOnClickOutside from '../../hooks/useOnClickOutside';
import { ReactComponent as DownloadSVG } from '../../assets/icons/file_download.svg';
import { ReactComponent as DownloadOffSVG } from '../../assets/icons/file_download_off.svg';
import { ReactComponent as MoreVertSVG } from '../../assets/icons/more_vert.svg';
type LoggingViewProps = BaseViewProps & BaseViewHeadingProps;
export type TelemetryStoreItem = {
timestamp: number;
data: unknown[];
log: string[];
};
enum TelemetryStoreCommand {
SET,
APPEND,
SET_KEY_SHOWING,
}
type TelemetryStoreState = {
store: TelemetryStoreItem[];
keys: string[];
raw: unknown[];
keysShowing: boolean[];
};
type TelemetryStoreAction =
| { type: TelemetryStoreCommand.SET; payload: TelemetryStoreState }
| { type: TelemetryStoreCommand.APPEND; payload: TelemetryItem }
| {
type: TelemetryStoreCommand.SET_KEY_SHOWING;
payload: { index: number; value: boolean };
};
const telemetryStoreReducer = (
state: TelemetryStoreState,
action: TelemetryStoreAction,
): TelemetryStoreState => {
switch (action.type) {
case TelemetryStoreCommand.SET: {
return action.payload;
}
case TelemetryStoreCommand.APPEND: {
const { store, keys, raw, keysShowing } = state;
const { timestamp, data, log } = action.payload;
const newTelemetryStoreItem: TelemetryStoreItem = {
timestamp,
log,
data: new Array(keys.length).fill(null),
};
for (const [key, value] of Object.entries(data)) {
if (!keys.includes(key)) {
keys.push(key);
keysShowing.push(true);
}
newTelemetryStoreItem.data[keys.indexOf(key)] = value;
}
store.push(newTelemetryStoreItem);
raw.push([
DateToHHMMSS(new Date(timestamp)),
...newTelemetryStoreItem.data,
]);
return {
store,
keys,
raw,
keysShowing,
};
}
case TelemetryStoreCommand.SET_KEY_SHOWING: {
const newKeysShowing = [...state.keysShowing];
newKeysShowing[action.payload.index] = action.payload.value;
return { ...state, keysShowing: newKeysShowing };
}
}
};
const MenuItemSwitch = ({
checked,
onChange,
children,
}: {
checked: boolean;
onChange:
| ((checked: boolean) => void)
| (FormEventHandler<HTMLButtonElement> & ((checked: boolean) => void));
children: JSX.Element | string;
}) => (
<Switch.Group as="div" className="flex items-center space-x-4 py-1 px-3">
<Switch
as="button"
checked={checked}
onChange={onChange}
className={`${
checked ? 'bg-indigo-600' : 'bg-gray-200'
} relative inline-flex flex-shrink-0 h-4 transition-colors duration-200 ease-in-out border-2 border-transparent rounded-full cursor-pointer w-7 focus:outline-none focus:shadow-outline`}
>
{({ checked }) => (
<span
className={`${
checked ? 'translate-x-3' : 'translate-x-0'
} inline-block w-3 h-3 transition duration-200 ease-in-out transform bg-white rounded-full`}
/>
)}
</Switch>
<Switch.Label className="ml-2">{children}</Switch.Label>
</Switch.Group>
);
const LoggingView = ({
isDraggable = false,
isUnlocked = false,
}: LoggingViewProps) => {
const { activeOpMode, activeOpModeStatus, opModeList } = useSelector(
(state: RootState) => state.status,
);
const telemetry = useSelector((state: RootState) => state.telemetry);
const [telemetryStore, dispatchTelemetryStore] = useReducer(
telemetryStoreReducer,
{
store: [],
keys: [],
raw: [],
keysShowing: [],
},
);
const [isRecording, setIsRecording] = useState(false);
const [currentOpModeName, setCurrentOpModeName] = useState('');
const [isDownloadable, setIsDownloadable] = useState(false);
const [isKeyShowingMenuVisible, setIsKeyShowingMenuVisible] = useState(false);
const [isTimeShowing, setIsTimeShowing] = useState(true);
const downloadButtonRef = useRef(null);
const isShowingDownloadTooltip = useDelayedTooltip(0.5, downloadButtonRef);
const keyShowingMenuRef = useRef(null);
const keyShowingMenuButtonRef = useRef(null);
useOnClickOutside(
keyShowingMenuRef,
() => {
if (isKeyShowingMenuVisible) setIsKeyShowingMenuVisible(false);
},
[keyShowingMenuButtonRef],
);
useEffect(() => {
if (opModeList?.length === 0) {
setIsRecording(false);
} else if (activeOpMode === STOP_OP_MODE_TAG) {
setIsRecording(false);
} else if (
(activeOpModeStatus === OpModeStatus.RUNNING || telemetry.length > 1) &&
!isRecording
) {
setIsRecording(true);
clearPastTelemetry();
} else if (activeOpModeStatus === OpModeStatus.STOPPED) {
setIsRecording(false);
}
}, [activeOpMode, activeOpModeStatus, isRecording, opModeList, telemetry]);
useEffect(() => {
if (activeOpModeStatus === OpModeStatus.RUNNING) {
setCurrentOpModeName(activeOpMode ?? '');
}
}, [activeOpMode, activeOpModeStatus]);
useEffect(() => {
if (!isRecording && telemetryStore.store.length !== 0) {
setIsDownloadable(true);
} else {
setIsDownloadable(false);
}
}, [isRecording, telemetryStore.store.length]);
useEffect(() => {
if (telemetry.length === 1 && telemetry[0].timestamp === 0) return;
telemetry.forEach((e) => {
dispatchTelemetryStore({
type: TelemetryStoreCommand.APPEND,
payload: e,
});
});
}, [telemetry]);
const clearPastTelemetry = () => {
dispatchTelemetryStore({
type: TelemetryStoreCommand.SET,
payload: { store: [], keys: [], raw: [], keysShowing: [] },
});
};
const downloadCSV = () => {
if (!isDownloadable) return;
function downloadBlob(data: string, fileName: string, mime: string) {
const a = document.createElement('a');
a.style.display = 'none';
document.body.appendChild(a);
const blob = new Blob([data], { type: mime });
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
const storeCopy = [...telemetryStore.store];
storeCopy.sort((a, b) => a.timestamp - b.timestamp);
const firstRow = ['time', ...telemetryStore.keys, 'logs'];
const body = storeCopy
.map(
(e) =>
`${DateToHHMMSS(new Date(e.timestamp))},${[
...e.data,
...new Array(telemetryStore.keys.length - e.data.length),
].join(',')},"${e.log.join('\n')}"`,
)
.join('\r\n');
const csv = `${firstRow}\r\n${body}`;
const fileDate = new Date(storeCopy[0].timestamp);
const year = fileDate.getFullYear();
const month = `0${fileDate.getMonth()}`.slice(-2);
const date = `0${fileDate.getDay()}`.slice(-2);
const hourlyDate = DateToHHMMSS(fileDate)
.replaceAll(':', '_')
.split('.')[0];
downloadBlob(
csv,
`${currentOpModeName} ${year}-${month}-${date} ${hourlyDate}.csv`,
'text/csv',
);
};
const getToolTipError = () => {
if (
telemetryStore.store.length === 0 &&
activeOpModeStatus !== OpModeStatus.RUNNING
) {
return 'No logs to download';
} else if (
activeOpModeStatus === OpModeStatus.RUNNING &&
activeOpMode !== STOP_OP_MODE_TAG
) {
return 'Cannot download logs while OpMode is running';
}
return `Download logs for ${currentOpModeName}`;
};
return (
<BaseView isUnlocked={isUnlocked}>
<div className="flex-center">
<BaseViewHeading isDraggable={isDraggable}>Logging</BaseViewHeading>
<div className="flex items-center mr-3 space-x-1">
<button
className={`icon-btn w-8 h-8 ${
isDownloadable ? '' : 'border-gray-400'
}`}
onClick={downloadCSV}
ref={downloadButtonRef}
>
{isDownloadable ? (
<DownloadSVG className="w-6 h-6" />
) : (
<DownloadOffSVG className="w-6 h-6 text-neutral-gray-400" />
)}
<ToolTip
hoverRef={downloadButtonRef}
isShowing={isShowingDownloadTooltip}
>
{getToolTipError()}
</ToolTip>
</button>
<div className="relative inline-block">
<button
ref={keyShowingMenuButtonRef}
className="icon-btn w-8 h-8"
onClick={() =>
setIsKeyShowingMenuVisible(!isKeyShowingMenuVisible)
}
>
<MoreVertSVG className="w-6 h-6" />
</button>
<Transition
show={isKeyShowingMenuVisible}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<div
ref={keyShowingMenuRef}
className="absolute right-0 mt-2 py-2 origin-top-right bg-white border border-gray-200 rounded-md shadow-lg outline-none"
style={{ zIndex: 99 }}
>
<p className="text-sm leading-5 border-b border-gray-100 pl-3 pb-1 mb-1 text-gray-500">
Toggle Items
</p>
<MenuItemSwitch
checked={isTimeShowing}
onChange={setIsTimeShowing}
>
Time
</MenuItemSwitch>
{[...telemetryStore.keys].map((e, i) => (
<MenuItemSwitch
key={e}
checked={telemetryStore.keysShowing[i]}
onChange={() =>
dispatchTelemetryStore({
type: TelemetryStoreCommand.SET_KEY_SHOWING,
payload: {
index: i,
value: !telemetryStore.keysShowing[i],
},
})
}
>
{e}
</MenuItemSwitch>
))}
</div>
</Transition>
</div>
</div>
</div>
<BaseViewBody>
<CustomVirtualGrid
header={
telemetryStore.keys.length !== 0
? ['Time', ...telemetryStore.keys]
: []
}
data={telemetryStore.raw}
columnsShowing={[isTimeShowing, ...telemetryStore.keysShowing]}
/>
</BaseViewBody>
</BaseView>
);
};
export default LoggingView;