forked from googlemaps/fleet-debugger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
1411 lines (1273 loc) · 48.4 KB
/
App.js
File metadata and controls
1411 lines (1273 loc) · 48.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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// src/App.js
import React from "react";
import { createRoot } from "react-dom/client";
import Map from "./Map";
import Dataframe from "./Dataframe";
import TimeSlider from "./TimeSlider";
import LogTable from "./LogTable";
import ToggleBar from "./ToggleBar";
import TripLogs from "./TripLogs";
import TaskLogs from "./TaskLogs";
import DatasetLoading from "./DatasetLoading";
import ExtraDataSource from "./ExtraDataSource";
import {
uploadFile,
getUploadedData,
deleteUploadedData,
uploadCloudLogs,
saveDatasetAsJson,
saveToIndexedDB,
} from "./localStorage";
import {
exportToGoogleSheet,
requestSheetsToken,
extractSpreadsheetId,
importFromGoogleSheet,
getApiType,
} from "./GoogleSheets";
import _ from "lodash";
import { getQueryStringValue, setQueryStringValue } from "./queryString";
import "./global.css";
import Utils, { log } from "./Utils";
import { toast, ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { ALL_TOGGLES, getVisibleToggles } from "./MapToggles";
const HAS_EXTRA_DATA_SOURCE = ExtraDataSource.isAvailable();
const MARKER_COLORS = [
"#EA4335", // Red
"#E91E63", // Pink
"#34A853", // Green
"#FBBC05", // Yellow
"#9C27B0", // Purple
"#FF6D00", // Orange
"#00BFA5", // Teal
"#26A69A", // Darker Teal
];
const ODRD_FILTERS = ["createVehicle", "getVehicle", "updateVehicle", "createTrip", "getTrip", "updateTrip"];
function FilterBar({ availableFilters, filterState, clickHandler }) {
const [isOpen, setIsOpen] = React.useState(false);
const filterBarRef = React.useRef(null);
React.useEffect(() => {
function handleClickOutside(event) {
if (filterBarRef.current && !filterBarRef.current.contains(event.target)) {
log("Clicked outside FilterBar, closing menu.");
setIsOpen(false);
}
}
if (isOpen) {
log("Filter menu is open, adding click outside listener.");
document.addEventListener("mousedown", handleClickOutside);
}
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [isOpen]);
if (!availableFilters || availableFilters.length === 0) {
return null;
}
const handleButtonClick = () => {
log(`Filter button clicked. Menu will be ${!isOpen ? "opened" : "closed"}.`);
setIsOpen(!isOpen);
};
const activeFilterCount = availableFilters.filter((type) => filterState[type]).length;
const totalFilterCount = availableFilters.length;
const buttonText = `Filter Log Types (${activeFilterCount}/${totalFilterCount})`;
const isFiltered = activeFilterCount !== totalFilterCount;
return (
<div style={{ position: "relative", display: "inline-block" }} ref={filterBarRef}>
<button
className={`toggle-button ${isOpen || isFiltered ? "toggle-button-active" : ""}`}
onClick={handleButtonClick}
>
{buttonText}
</button>
{isOpen && (
<div className="filter-menu">
{availableFilters.map((filterType) => (
<label key={filterType} className="filter-menu-item">
<input type="checkbox" checked={!!filterState[filterType]} onChange={() => clickHandler(filterType)} />
{filterType}
</label>
))}
</div>
)}
</div>
);
}
function TripIdFilter({ value, onChange }) {
return (
<div style={{ marginLeft: "10px" }}>
<input
type="text"
placeholder="Filter by Trip ID"
value={value}
onChange={onChange}
className="trip-id-filter-input"
/>
</div>
);
}
class App extends React.Component {
constructor(props) {
super(props);
this.centerOnLocation = null;
this.renderMarkerOnMap = null;
this.nextColorIndex = 0;
const nowDate = new Date();
let urlMinTime = getQueryStringValue("minTime");
let urlMaxTime = getQueryStringValue("maxTime");
this.initialMinTime = urlMinTime ? parseInt(urlMinTime) : 0;
this.initialMaxTime = urlMaxTime ? parseInt(urlMaxTime) : nowDate.setFullYear(nowDate.getFullYear() + 1);
this.focusOnRowFunction = null;
this.state = {
timeRange: { minTime: this.initialMinTime, maxTime: this.initialMaxTime },
isPlaying: false,
playSpeed: 1000,
featuredObject: { msg: "Click a table row to select object" },
extraColumns: [],
toggleOptions: Object.fromEntries(ALL_TOGGLES.map((t) => [t.id, false])),
isDataframeCollapsed: false,
filters: {
logTypes: {
createVehicle: true,
getVehicle: true,
updateVehicle: true,
createTrip: true,
getTrip: true,
updateTrip: true,
createDeliveryVehicle: true,
getDeliveryVehicle: true,
updateDeliveryVehicle: true,
createTask: true,
getTask: true,
updateTask: true,
},
tripId: "",
},
uploadedDatasets: [null, null, null, null, null],
activeDatasetIndex: null,
activeMenuIndex: null,
initialMapBounds: null,
selectedRowIndexPerDataset: [-1, -1, -1, -1, -1],
useResponseLocationPerDataset: [false, false, false, false, false],
currentLogData: {
...this.props.logData,
taskLogs: new TaskLogs(this.props.logData.tripLogs),
},
dynamicMarkerLocations: {},
visibleToggles: getVisibleToggles(this.props.logData.solutionType),
};
this.onSliderChangeDebounced = _.debounce((timeRange) => this.onSliderChange(timeRange), 25);
this.setFeaturedObject = this.setFeaturedObject.bind(this);
this.setTimeRange = this.setTimeRange.bind(this);
}
updateMapAndAssociatedData = () => {
this.setTimeRange(this.state.timeRange.minTime, this.state.timeRange.maxTime);
};
componentDidMount() {
log(`Initial device pixel ratio: ${window.devicePixelRatio}`);
this.initializeData().then(() => {
this.updateMapAndAssociatedData();
});
const pendingSheetId = getQueryStringValue("sheetId");
if (pendingSheetId) {
// Remove the sheetId from the URL to prevent reload loops
const url = new URL(window.location.href);
url.searchParams.delete("sheetId");
window.history.replaceState({}, document.title, url.toString());
this.loadSharedSheet(pendingSheetId);
}
// Initialize the Broadcast Channel
this.syncChannel = new BroadcastChannel("app_playback_sync");
this.syncChannel.onmessage = this.handleSyncMessage;
document.addEventListener("keydown", this.handleKeyPress);
}
// Handle incoming signals from the other tab
handleSyncMessage = (event) => {
const { action } = event.data;
// We pass 'true' to these methods to indicate the action came from a sync.
// This tells the method NOT to broadcast it back, preventing infinite loops.
if (action === "NEXT") this.handleNextEvent(true);
if (action === "PREVIOUS") this.handlePreviousEvent(true);
if (action === "TOGGLE_PLAY") this.handlePlayStop(true);
if (action === "SET_SPEED") this.handleSpeedChange(event.data.speed, true);
};
initializeData = async () => {
const datasets = await this.checkUploadedDatasets();
if (!datasets[0]) {
await this.checkForDemoFile();
}
};
loadSharedSheet = async (sheetId) => {
this.setState({ pendingSheetId: null });
try {
toast.info("Loading Google Sheet...");
const token = await requestSheetsToken();
const logs = await importFromGoogleSheet(sheetId, token);
const logsWithTimestamp = logs.map((logEntry) => ({
...logEntry,
timestamp: logEntry.timestamp || new Date().toISOString(),
}));
await uploadCloudLogs(logsWithTimestamp, "_clipboard");
toast.success("Dataset from Google Sheet loaded. You can now Paste into any dataset.", { autoClose: false });
} catch (error) {
log(`Error loading shared sheet: ${error.message}`, error);
// If the browser blocks the popup (often happens on page load without user gesture)
if (error.message && error.message.includes("Failed to open login popup window")) {
toast.warning(
<div>
Popup blocked by browser.
<br />
<br />
<button
className="toggle-button toggle-button-active"
onClick={() => {
toast.dismiss();
this.loadSharedSheet(sheetId);
}}
style={{ padding: "4px 8px", fontSize: "14px" }}
>
Load Google Sheet
</button>
</div>,
{ autoClose: false, closeOnClick: false }
);
} else {
toast.error(`Failed to load shared sheet: ${error.message}`);
}
}
};
updateToggleState(newValue, toggleName, jsonPaths) {
this.setState((prevState) => {
const newToggleOptions = {
...prevState.toggleOptions,
[toggleName]: newValue,
};
const newExtraColumns = newValue
? _.union(prevState.extraColumns, jsonPaths)
: _.difference(prevState.extraColumns, jsonPaths);
return {
toggleOptions: newToggleOptions,
extraColumns: newExtraColumns,
};
});
}
onSliderChange(timeRange) {
this.setTimeRange(timeRange.minTime, timeRange.maxTime);
}
onSelectionChange(selectedRow, rowIndex) {
if (this.state.activeDatasetIndex !== null && rowIndex !== undefined) {
this.setState((prevState) => {
const newSelectedIndexes = [...prevState.selectedRowIndexPerDataset];
newSelectedIndexes[prevState.activeDatasetIndex] = rowIndex;
return {
selectedRowIndexPerDataset: newSelectedIndexes,
featuredObject: selectedRow,
};
});
} else {
log("Unable to save index:", rowIndex, "for dataset:", this.state.activeDatasetIndex);
this.setFeaturedObject(selectedRow);
}
}
setFeaturedObject(featuredObject) {
this.setState({ featuredObject: featuredObject });
}
setUseResponseLocation = (useResponseLocation) => {
if (this.state.activeDatasetIndex !== null) {
this.setState((prevState) => {
const newValues = [...prevState.useResponseLocationPerDataset];
newValues[prevState.activeDatasetIndex] = useResponseLocation;
return { useResponseLocationPerDataset: newValues };
});
}
};
setFocusOnRowFunction = (func) => {
this.focusOnRowFunction = func;
};
focusOnSelectedRow = () => {
if (this.focusOnRowFunction && this.state.featuredObject) {
this.focusOnRowFunction(this.state.featuredObject);
}
};
setTimeRange(minTime, maxTime, callback) {
setQueryStringValue("minTime", minTime);
setQueryStringValue("maxTime", maxTime);
this.setState(
{
timeRange: { minTime: minTime, maxTime: maxTime },
},
callback
);
}
/*
* Callback to handle clicks on properties in the json viewer.
* Adds/removes row from the log viewer based on which property
* in the json object was clicked on
*/
onDataframePropClick(jsonPath) {
this.setState((prevState) => {
let newColumns;
if (_.find(prevState.extraColumns, (x) => x === jsonPath)) {
newColumns = _.without(prevState.extraColumns, jsonPath);
} else {
newColumns = [...prevState.extraColumns, jsonPath];
}
return { extraColumns: newColumns };
});
}
getFilteredLogs = () => {
const { currentLogData, timeRange, filters, activeDatasetIndex } = this.state;
if (!currentLogData || !currentLogData.tripLogs) return [];
const cacheKey = `${activeDatasetIndex}-${timeRange.minTime}-${timeRange.maxTime}-${JSON.stringify(filters)}`;
if (this._logsCache && this._logsCache.key === cacheKey) {
return this._logsCache.logs;
}
const logs = currentLogData.tripLogs
.getLogs_(new Date(timeRange.minTime), new Date(timeRange.maxTime), filters)
.value();
this._logsCache = { key: cacheKey, logs };
return logs;
};
selectFirstRow = () => {
return new Promise((resolve) => {
const logs = this.getFilteredLogs();
if (logs.length > 0) {
const firstRow = logs[0];
this.setState({ featuredObject: firstRow }, () => {
this.focusOnSelectedRow();
resolve(firstRow);
});
} else {
console.log("selectFirstRow: No logs found in the current time range");
resolve(null);
}
});
};
selectLastRow = () => {
const logs = this.getFilteredLogs();
if (logs.length > 0) {
const lastRow = logs[logs.length - 1];
this.setFeaturedObject(lastRow);
this.focusOnRowFunction(lastRow);
} else {
console.log("selectLastRow: No logs found in the current time range");
}
};
handleRowChange = async (direction) => {
const { featuredObject } = this.state;
const logs = this.getFilteredLogs();
let newFeaturedObject = featuredObject;
const currentIndex = logs.findIndex((log) => log.timestamp === featuredObject.timestamp);
if (currentIndex === -1) {
if (logs.length > 0) {
newFeaturedObject = logs[0];
} else {
return;
}
} else if (direction === "next" && currentIndex < logs.length - 1) {
newFeaturedObject = logs[currentIndex + 1];
} else if (direction === "previous" && currentIndex > 0) {
newFeaturedObject = logs[currentIndex - 1];
}
if (newFeaturedObject !== featuredObject) {
this.setState({ featuredObject: newFeaturedObject }, () => {
this.focusOnSelectedRow();
});
}
};
handleNextEvent = (fromSync = false) => {
this.handleRowChange("next");
// Only broadcast if this action originated from this tab
if (!fromSync && this.syncChannel) {
this.syncChannel.postMessage({ action: "NEXT" });
}
};
handlePreviousEvent = (fromSync = false) => {
this.handleRowChange("previous");
// Only broadcast if this action originated from this tab
if (!fromSync && this.syncChannel) {
this.syncChannel.postMessage({ action: "PREVIOUS" });
}
};
handlePlayStop = (fromSync = false) => {
this.setState((prevState) => {
if (!prevState.isPlaying) {
this.timerID = setInterval(() => {
this.handleNextEvent(true);
}, prevState.playSpeed);
} else {
clearInterval(this.timerID);
}
return { isPlaying: !prevState.isPlaying };
});
// Only broadcast the play/stop toggle if it originated from this tab
if (!fromSync && this.syncChannel) {
this.syncChannel.postMessage({ action: "TOGGLE_PLAY" });
}
};
handleSpeedChange = (eventOrSpeed, fromSync = false) => {
// Determine the new speed depending on if it came from an event or a direct value
const newSpeed =
typeof eventOrSpeed === "object" && eventOrSpeed.target
? parseInt(eventOrSpeed.target.value)
: parseInt(eventOrSpeed);
this.setState({ playSpeed: newSpeed }, () => {
if (this.state.isPlaying) {
clearInterval(this.timerID);
this.timerID = setInterval(() => {
this.handleNextEvent(true);
}, newSpeed);
}
});
// Broadcast the speed change to other tabs
if (!fromSync && this.syncChannel) {
this.syncChannel.postMessage({ action: "SET_SPEED", speed: newSpeed });
}
};
handleKeyPress = (event) => {
// Ignore keystrokes if the user is typing in an input or select box
if (["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName)) return;
if (["ArrowLeft", ",", "<"].includes(event.key)) {
this.handlePreviousEvent(); // Defaults to fromSync=false, so it broadcasts!
} else if (["ArrowRight", ".", ">"].includes(event.key)) {
this.handleNextEvent(); // Defaults to fromSync=false, so it broadcasts!
}
};
componentWillUnmount() {
if (this.syncChannel) {
this.syncChannel.close();
}
clearInterval(this.timerID);
document.removeEventListener("keydown", this.handleKeyPress);
if (this._outsideClickHandler) {
document.removeEventListener("click", this._outsideClickHandler);
this._outsideClickHandler = null;
}
}
checkForDemoFile = async () => {
try {
const response = await fetch("./data.json");
const contentType = response.headers.get("content-type");
if (!response.ok || !contentType || !contentType.includes("application/json")) {
return;
}
console.log("data.json demo file found on the server root, saving it to Dataset 1");
const blob = await response.blob();
const file = new File([blob], "data.json", { type: "application/json" });
const event = { target: { files: [file] } };
await this.handleFileUpload(event, 0);
} catch (error) {
return;
}
};
handleFileUpload = async (event, index) => {
const file = event.target.files[0];
log(`Attempting to upload file for button ${index}:`, file ? file.name : "No file selected");
if (file) {
try {
log(`Uploading file ${file.name} for button ${index}`);
await uploadFile(file, index);
log(`File ${file.name} uploaded successfully for button ${index}`);
this.setState(
(prevState) => {
const newUploadedDatasets = [...prevState.uploadedDatasets];
newUploadedDatasets[index] = "Uploaded";
log(`Updated dataset button state for index ${index}:`, newUploadedDatasets);
return { uploadedDatasets: newUploadedDatasets };
},
() => {
console.log(`handleFileUpload: setState callback executed for index ${index}, now switching dataset.`);
this.switchDataset(index);
}
);
} catch (error) {
console.error("Error uploading file:", error);
}
}
};
checkUploadedDatasets = async () => {
const newUploadedDatasets = await Promise.all(
[0, 1, 2, 3, 4].map(async (index) => {
const data = await getUploadedData(index);
log(`Dataset ${index}:`, data);
if (data && data.rawLogs && Array.isArray(data.rawLogs) && data.rawLogs.length > 0) {
if (HAS_EXTRA_DATA_SOURCE && data.retentionDate) {
const retentionDate = new Date(data.retentionDate);
if (retentionDate <= new Date()) {
log(`Startup: Dataset ${index} expired. Deleting...`);
await deleteUploadedData(index);
log(`Dataset ${index + 1} has expired and was deleted.`, "error");
return { status: null, index };
} else {
const now = new Date();
const timeLeftMs = retentionDate - now;
const daysLeft = timeLeftMs / (1000 * 60 * 60 * 24);
if (daysLeft <= 10) {
log(`Dataset ${index + 1} will expire in ${Utils.formatTTLRemaining(timeLeftMs)}.`, "warn");
}
}
}
return { status: "Uploaded", index };
}
return { status: null, index };
})
);
this.setState(
{
uploadedDatasets: newUploadedDatasets.map((d) => d.status),
},
() => {
if (this.state.activeDatasetIndex === null) {
const firstAvailableIndex = newUploadedDatasets.find((dataset) => dataset.status === "Uploaded")?.index;
if (firstAvailableIndex !== undefined) {
this.switchDataset(firstAvailableIndex);
}
}
}
);
return newUploadedDatasets.map((d) => d.status);
};
renderUploadButton = (index) => {
const isUploaded = this.state.uploadedDatasets[index] === "Uploaded";
const isActive = this.state.activeDatasetIndex === index;
const isMenuOpen = this.state.activeMenuIndex === index;
const toggleMenu = (e) => {
e.stopPropagation();
this.setState((prevState) => ({
activeMenuIndex: prevState.activeMenuIndex === index ? null : index,
}));
};
const handleDeleteClick = async (e) => {
e.stopPropagation();
log(`Delete initiated for dataset ${index}`);
this.setState({ activeMenuIndex: null }); // Close menu
try {
await deleteUploadedData(index);
log(`Data deleted successfully for dataset ${index}`);
this.setState((prevState) => {
const newUploadedDatasets = [...prevState.uploadedDatasets];
newUploadedDatasets[index] = null;
return {
uploadedDatasets: newUploadedDatasets,
activeDatasetIndex: prevState.activeDatasetIndex === index ? null : prevState.activeDatasetIndex,
};
});
} catch (error) {
log("Error deleting local storage data. Please try again.", error);
}
};
const handleSaveClick = async (e) => {
e.stopPropagation();
log(`Export initiated for dataset ${index}`);
this.setState({ activeMenuIndex: null }); // Close menu
try {
await saveDatasetAsJson(index);
log(`Dataset ${index + 1} exported successfully`, "success");
} catch (error) {
log(`Error exporting dataset: ${error.message}`, error);
}
};
const handleGoogleSheetExport = async (e) => {
e.stopPropagation();
log(`Google Sheet export initiated for dataset ${index}`);
this.setState({ activeMenuIndex: null });
try {
const token = await requestSheetsToken();
const sheetUrl = await exportToGoogleSheet(index, token);
const spreadsheetId = extractSpreadsheetId(sheetUrl);
const deepLink = `${window.location.origin}${window.location.pathname}?sheetId=${spreadsheetId}`;
toast.success(
<span>
Exported to{" "}
<a href={sheetUrl} target="_blank" rel="noopener noreferrer">
Google Sheet
</a>
<br />
Shareable Fleet Debugger URL <a href={deepLink}>{deepLink}</a>
</span>,
{ autoClose: false }
);
} catch (error) {
log(`Error exporting to Google Sheet: ${error.message}`, error);
toast.error(`Google Sheet export failed: ${error.message}`);
}
};
const handleCopyClick = async (e) => {
e.stopPropagation();
log(`Copy dataset ${index} initiated`);
this.setState({ activeMenuIndex: null });
try {
const data = await getUploadedData(index);
if (!data || !data.rawLogs || data.rawLogs.length === 0) {
toast.warning("Dataset is empty, nothing to copy.");
return;
}
let logsToCopy = data.rawLogs;
const { logTypes } = this.state.filters;
const totalFilterCount = Object.keys(logTypes).length;
const activeFilterCount = Object.values(logTypes).filter(Boolean).length;
if (activeFilterCount !== totalFilterCount) {
if (window.confirm("Do you want to copy only the currently filtered log types?")) {
logsToCopy = data.rawLogs.filter((logEntry) => {
const apiType = getApiType(logEntry);
return logTypes[apiType] !== false;
});
}
}
const dataToSave = { ...data, rawLogs: logsToCopy };
await saveToIndexedDB(dataToSave, "_clipboard");
toast.success(`Dataset ${index + 1} copied to clipboard!`);
} catch (error) {
log(`Error copying dataset: ${error.message}`, error);
toast.error(`Error copying dataset: ${error.message}`);
}
};
const handlePasteClick = async (e) => {
e.stopPropagation();
log(`Paste to dataset ${index} initiated`);
this.setState({ activeMenuIndex: null });
try {
const clipboardData = await getUploadedData("_clipboard");
if (!clipboardData || !clipboardData.rawLogs) {
toast.warning("Clipboard is empty.");
return;
}
await saveToIndexedDB(clipboardData, index);
toast.success(`Pasted into Dataset ${index + 1}!`);
this.setState(
(prevState) => {
const newUploadedDatasets = [...prevState.uploadedDatasets];
newUploadedDatasets[index] = "Uploaded";
return { uploadedDatasets: newUploadedDatasets };
},
() => {
this.switchDataset(index);
}
);
} catch (error) {
log(`Error pasting dataset: ${error.message}`, error);
toast.error(`Error pasting dataset: ${error.message}`);
}
};
const handlePruneClick = async (e) => {
e.stopPropagation();
log(`Prune initiated for dataset ${index}`);
this.setState({ activeMenuIndex: null }); // Close menu
try {
const { minTime, maxTime } = this.state.timeRange;
const data = await getUploadedData(index);
if (!data || !data.rawLogs || !Array.isArray(data.rawLogs)) {
throw new Error("No valid data to prune");
}
// Calculate how many logs will be removed
const originalLength = data.rawLogs.length;
const minDate = new Date(minTime);
const maxDate = new Date(maxTime);
const remainingLogs = data.rawLogs.filter((log) => {
const logTime = new Date(log.timestamp || log.insertTime);
return logTime >= minDate && logTime <= maxDate;
});
const removeCount = originalLength - remainingLogs.length;
if (
!confirm(
`This will remove ${removeCount} logs outside the selected time range.\nAre you sure you want to continue?`
)
) {
log("Prune operation cancelled by user");
return;
}
log(`Pruning dataset ${index}: removing ${removeCount} logs outside time range`);
data.rawLogs = remainingLogs;
await saveToIndexedDB(data, index); // Save the pruned dataset back to storage
// Update the current dataset if this is the active one
if (this.state.activeDatasetIndex === index) {
log(`handlePruneClick: Pruning active dataset ${index}, updating state.`);
const tripLogs = new TripLogs(data.rawLogs, data.solutionType);
const taskLogs = new TaskLogs(tripLogs);
this.setState(
(prevState) => ({
currentLogData: {
...prevState.currentLogData,
tripLogs: tripLogs,
taskLogs: taskLogs,
solutionType: data.solutionType,
},
}),
() => {
log("handlePruneClick: setState callback executed, selecting first row.");
this.selectFirstRow(); // Select first row after pruning
}
);
}
log(`Dataset pruned: removed ${removeCount} logs outside the selected time range.`, "info");
} catch (error) {
log(`Error pruning dataset: ${error.message}`, error);
}
};
const handleClick = async () => {
if (isUploaded) {
this.switchDataset(index);
} else {
const result = await this.showDatasetLoadingDialog();
if (!result) {
log("Dataset loading dialog was cancelled or returned no data.");
return; // User cancelled the dialog
}
try {
if (result.pasteClipboard) {
const clipboardData = await getUploadedData("_clipboard");
if (!clipboardData || !clipboardData.rawLogs) {
toast.warning("Clipboard is empty.");
return;
}
await saveToIndexedDB(clipboardData, index);
toast.success(`Pasted into Dataset ${index + 1}!`);
this.setState(
(prevState) => {
const newUploadedDatasets = [...prevState.uploadedDatasets];
newUploadedDatasets[index] = "Uploaded";
return { uploadedDatasets: newUploadedDatasets };
},
() => this.switchDataset(index)
);
return;
}
if (result.file) {
const uploadEvent = { target: { files: [result.file] } };
await this.handleFileUpload(uploadEvent, index);
return;
}
let logsToProcess;
if (result.logs) {
logsToProcess = result.logs;
} else if (result.extraLogs) {
// The 'extraLogs' are raw payloads, so we wrap them in the structure
// that our uploader and processor expects ({ jsonPayload: ... }).
logsToProcess = result.extraLogs.map((logEntry) => ({
jsonPayload: logEntry,
timestamp: logEntry.timestamp,
}));
}
if (logsToProcess) {
await uploadCloudLogs(logsToProcess, index);
this.setState(
(prevState) => {
const newUploadedDatasets = [...prevState.uploadedDatasets];
newUploadedDatasets[index] = "Uploaded";
return { uploadedDatasets: newUploadedDatasets };
},
() => {
this.switchDataset(index);
}
);
}
} catch (error) {
log(`Failed to process data from dialog: ${error.message}`, error);
}
}
};
// Close menu when clicking outside
const handleOutsideClick = () => {
if (isMenuOpen) {
this.setState({ activeMenuIndex: null });
}
};
// Add event listener for outside clicks when a menu is open
if (isMenuOpen && !this._outsideClickHandler) {
this._outsideClickHandler = () => {
handleOutsideClick();
};
document.addEventListener("click", this._outsideClickHandler);
} else if (!isMenuOpen && this._outsideClickHandler) {
document.removeEventListener("click", this._outsideClickHandler);
this._outsideClickHandler = null;
}
return (
<div key={index} style={{ display: "inline-block", marginRight: "10px", position: "relative" }}>
<input
type="file"
accept=".zip,.json"
onChange={(e) => this.handleFileUpload(e, index)}
style={{ display: "none" }}
id={`fileInput${index}`}
/>
<button
onClick={handleClick}
className={`dataset-button ${
isActive ? "dataset-button-active" : isUploaded ? "dataset-button-uploaded" : "dataset-button-empty"
}`}
>
{isUploaded ? `Dataset ${index + 1}` : `Select Data ${index + 1}`}
{isUploaded && isActive && (
<span className="dataset-button-actions" onClick={toggleMenu}>
▼
</span>
)}
{isMenuOpen && (
<div className="dataset-button-menu" style={{ top: "100%", right: 0 }}>
<div className="dataset-button-menu-item paste" onClick={handlePasteClick}>
Paste Dataset
</div>
<div className="dataset-button-menu-item copy" onClick={handleCopyClick}>
Copy Dataset
</div>
<div className="dataset-button-menu-item export" onClick={handleSaveClick}>
Export File
</div>
<div className="dataset-button-menu-item export" onClick={handleGoogleSheetExport}>
Export GSheet
</div>
<div className="dataset-button-menu-item prune" onClick={handlePruneClick}>
Prune
</div>
<div className="dataset-button-menu-item delete" onClick={handleDeleteClick}>
Delete
</div>
</div>
)}
</button>
</div>
);
};
async showDataSourceDialog(index) {
log("showDataSourceDialog");
const dialog = document.createElement("dialog");
dialog.innerHTML = `
<div>
<h3>Choose Data Source for Dataset ${index + 1}</h3>
<button id="fileUpload">Load JSON/ZIP File</button>
<button id="cloudLogging">Connect to Cloud Logging</button>
<button id="cancel">Cancel</button>
</div>
`;
document.body.appendChild(dialog);
dialog.showModal();
return new Promise((resolve) => {
dialog.querySelector("#fileUpload").onclick = () => {
dialog.remove();
resolve("file");
};
dialog.querySelector("#cloudLogging").onclick = () => {
dialog.remove();
resolve("cloud");
};
dialog.querySelector("#cancel").onclick = () => {
dialog.remove();
resolve(null);
};
});
}
async showDatasetLoadingDialog() {
log("Executing showDatasetLoadingDialog");
const dialog = document.createElement("dialog");
dialog.className = "cloud-logging-dialog";
document.body.appendChild(dialog);
const dialogRootElement = document.createElement("div");
dialog.appendChild(dialogRootElement);
const dialogRoot = createRoot(dialogRootElement);
dialog.showModal();
return new Promise((resolve) => {
const cleanupAndResolve = (result) => {
log("Closing and cleaning up DatasetLoading dialog");
dialogRoot.unmount();
dialog.remove();
resolve(result);
};
dialog.addEventListener("close", () => {
cleanupAndResolve(null);
});
const handleFileUpload = (event) => {
log("File upload selected from DatasetLoading dialog");
const file = event?.target?.files?.[0];
if (file) {
cleanupAndResolve({ file });
}
};
const handleCloudLogsReceived = (logs) => {
log(`Received ${logs.length} logs from Cloud Logging`);
if (logs.length > 0) {
cleanupAndResolve({ logs });
} else {
// If no logs, we don't close the dialog, just show a toast.
// The user might want to adjust params.
toast.warning("No logs found matching your criteria.");
}