-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdatedDatasetDetailPage.tsx
More file actions
1444 lines (1347 loc) · 47 KB
/
UpdatedDatasetDetailPage.tsx
File metadata and controls
1444 lines (1347 loc) · 47 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
import PreviewModal from "../components/PreviewModal";
import CheckIcon from "@mui/icons-material/Check";
import CloudDownloadIcon from "@mui/icons-material/CloudDownload";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import DescriptionIcon from "@mui/icons-material/Description";
import ExpandLess from "@mui/icons-material/ExpandLess";
import ExpandMore from "@mui/icons-material/ExpandMore";
import HomeIcon from "@mui/icons-material/Home";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
import {
Box,
Typography,
CircularProgress,
Backdrop,
Alert,
Button,
Collapse,
Tooltip,
IconButton,
} from "@mui/material";
import FileTree from "components/DatasetDetailPage/FileTree/FileTree";
import {
buildTreeFromDoc,
makeLinkMap,
} from "components/DatasetDetailPage/FileTree/utils";
import LoadDatasetTabs from "components/DatasetDetailPage/LoadDatasetTabs";
import MetaDataPanel from "components/DatasetDetailPage/MetaDataPanel";
import ReadMoreText from "design/ReadMoreText";
import { Colors } from "design/theme";
import { useAppDispatch } from "hooks/useAppDispatch";
import { useAppSelector } from "hooks/useAppSelector";
import React, { useEffect, useMemo, useState, useRef } from "react";
// import ReactJson from "react-json-view";
import { useParams, useNavigate, useSearchParams } from "react-router-dom";
import {
fetchDocumentDetails,
fetchDbInfoByDatasetId,
} from "redux/neurojson/neurojson.action";
import { NeurojsonSelector } from "redux/neurojson/neurojson.selector";
import { NeurojsonService } from "services/neurojson.service";
import RoutesEnum from "types/routes.enum";
interface ExternalDataLink {
name: string;
size: string;
path: string;
url: string;
index: number;
}
interface InternalDataLink {
name: string;
data: any;
index: number;
arraySize?: number[];
path: string; // for preview in tree row
}
const UpdatedDatasetDetailPage: React.FC = () => {
const { dbName, docId } = useParams<{ dbName: string; docId: string }>();
const navigate = useNavigate();
const dispatch = useAppDispatch();
const {
selectedDocument: datasetDocument,
loading,
error,
datasetViewInfo: dbViewInfo,
} = useAppSelector(NeurojsonSelector);
// get params from url
const [searchParams, setSearchParams] = useSearchParams();
const focus = searchParams.get("focus") || undefined; // get highlight from url
const rev = searchParams.get("rev") || undefined; // get revision from url
const [externalLinks, setExternalLinks] = useState<ExternalDataLink[]>([]);
const [internalLinks, setInternalLinks] = useState<InternalDataLink[]>([]);
const [isInternalExpanded, setIsInternalExpanded] = useState(true);
const [downloadScript, setDownloadScript] = useState<string>("");
const [downloadScriptSize, setDownloadScriptSize] = useState<number>(0);
const [totalFileSize, setTotalFileSize] = useState<number>(0);
const [previewIsInternal, setPreviewIsInternal] = useState(false);
const [isExternalExpanded, setIsExternalExpanded] = useState(true);
const [jsonSize, setJsonSize] = useState<number>(0);
const [previewIndex, setPreviewIndex] = useState<number>(0);
const [isPreviewLoading, setIsPreviewLoading] = useState(false);
// const [copiedToast, setCopiedToast] = useState<{
// open: boolean;
// text: string;
// }>({
// open: false,
// text: "",
// });
// const [copiedUrlOpen, setCopiedUrlOpen] = useState(false);
const [copiedKey, setCopiedKey] = useState<string | null>(null);
const copyTimer = useRef<number | null>(null);
const aiSummary = datasetDocument?.[".datainfo"]?.AISummary ?? "";
const readme = datasetDocument?.["README"] ?? "";
const handleSelectRevision = (newRev?: string | null) => {
setSearchParams((prev) => {
const p = new URLSearchParams(prev); // copy of the query url
if (newRev) p.set("rev", newRev);
else p.delete("rev");
return p;
});
};
const linkMap = useMemo(() => makeLinkMap(externalLinks), [externalLinks]); // => external Link Map
const treeData = useMemo(
() => buildTreeFromDoc(datasetDocument || {}, linkMap, ""),
[datasetDocument, linkMap]
);
const treeTitle = "Files";
// const filesCount = externalLinks.length;
// const totalBytes = useMemo(() => {
// let bytes = 0;
// for (const l of externalLinks) {
// const m = l.url.match(/size=(\d+)/);
// if (m) bytes += parseInt(m[1], 10);
// }
// return bytes;
// }, [externalLinks]);
// add spinner
const formatSize = (sizeInBytes: number): string => {
if (sizeInBytes < 1024) {
return `${sizeInBytes} Bytes`;
} else if (sizeInBytes < 1024 * 1024) {
return `${(sizeInBytes / 1024).toFixed(1)} KB`;
} else if (sizeInBytes < 1024 * 1024 * 1024) {
return `${(sizeInBytes / (1024 * 1024)).toFixed(2)} MB`;
} else if (sizeInBytes < 1024 * 1024 * 1024 * 1024) {
return `${(sizeInBytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
} else {
return `${(sizeInBytes / (1024 * 1024 * 1024 * 1024)).toFixed(2)} TB`;
}
};
// Recursive function to find `_DataLink_`
const extractDataLinks = (obj: any, path: string): ExternalDataLink[] => {
const links: ExternalDataLink[] = [];
const traverse = (
node: any,
currentPath: string,
parentKey: string = ""
) => {
if (typeof node === "object" && node !== null) {
for (const key in node) {
if (key === "_DataLink_" && typeof node[key] === "string") {
let correctedUrl = node[key].replace(/:\$.*$/, "");
const sizeMatch = node[key].match(/size=(\d+)/);
const size = sizeMatch
? `${(parseInt(sizeMatch[1], 10) / 1024 / 1024).toFixed(2)} MB`
: "Unknown Size";
const parts = currentPath.split("/");
const subpath = parts.slice(-3).join("/");
const label = parentKey || "ExternalData";
links.push({
name: `${label} (${size}) [/${subpath}]`,
size,
path: currentPath, // parent path (not include _DataLink_)
url: correctedUrl,
index: links.length,
});
} else if (typeof node[key] === "object") {
const isMetaKey = key.startsWith("_");
const newLabel = !isMetaKey ? key : parentKey;
traverse(node[key], `${currentPath}/${key}`, newLabel);
}
}
}
};
traverse(obj, path);
const seenUrls = new Set<string>();
const uniqueLinks = links.filter((link) => {
if (seenUrls.has(link.url)) return false;
seenUrls.add(link.url);
return true;
});
return uniqueLinks;
};
const extractInternalData = (obj: any, path = ""): InternalDataLink[] => {
const internalLinks: InternalDataLink[] = [];
if (obj && typeof obj === "object") {
// Handle arrays so paths match the tree (/[0], /[1], …)
if (Array.isArray(obj)) {
obj.forEach((item, i) => {
internalLinks.push(...extractInternalData(item, `${path}/[${i}]`));
});
return internalLinks;
}
if (
obj.hasOwnProperty("MeshNode") &&
(obj.hasOwnProperty("MeshSurf") || obj.hasOwnProperty("MeshElem"))
) {
if (
obj.MeshNode?.hasOwnProperty("_ArrayZipData_") &&
typeof obj.MeshNode["_ArrayZipData_"] === "string"
) {
internalLinks.push({
name: "JMesh",
data: obj,
index: internalLinks.length,
arraySize: obj.MeshNode._ArraySize_,
path: `${path}/MeshNode`, // attach to the MeshNode row in the tree
});
}
} else if (obj.hasOwnProperty("NIFTIData")) {
if (
obj.NIFTIData?.hasOwnProperty("_ArrayZipData_") &&
typeof obj.NIFTIData["_ArrayZipData_"] === "string"
) {
internalLinks.push({
name: "JNIfTI",
data: obj,
index: internalLinks.length,
arraySize: obj.NIFTIData._ArraySize_,
path: `${path}/NIFTIData`, // attach to the NIFTIData row
});
}
} else if (
obj.hasOwnProperty("_ArraySize_") &&
!/_EnumValue_$/.test(path)
) {
if (
obj.hasOwnProperty("_ArrayZipData_") &&
typeof obj["_ArrayZipData_"] === "string"
) {
internalLinks.push({
name: "JData",
data: obj,
index: internalLinks.length,
arraySize: obj._ArraySize_,
path, // attach to the current node
});
}
} else {
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === "object") {
// use slash paths to match buildTreeFromDoc
internalLinks.push(
...extractInternalData(obj[key], `${path}/${key}`)
);
}
});
}
}
return internalLinks;
};
// Build a shareable preview URL for a JSON path in this dataset
const buildPreviewUrl = (path: string) => {
const origin = window.location.origin;
const revPart = rev ? `rev=${encodeURIComponent(rev)}&` : "";
return `${origin}/db/${dbName}/${docId}?${revPart}preview=${encodeURIComponent(
path
)}`;
};
// Copy helper
const copyPreviewUrl = async (path: string) => {
const url = buildPreviewUrl(path);
try {
await navigator.clipboard.writeText(url);
// setCopiedToast({ open: true, text: "Preview link copied" });
} catch {
// fallback
const ta = document.createElement("textarea");
ta.value = url;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
// setCopiedToast({ open: true, text: "Preview link copied" });
}
};
// const handleUrlCopyClick = async (e: React.MouseEvent, path: string) => {
// await copyPreviewUrl(path);
// setCopiedUrlOpen(true);
// setTimeout(() => setCopiedUrlOpen(false), 2500);
// };
const handleUrlCopyClick = async (
e: React.MouseEvent<HTMLButtonElement>,
path: string
) => {
await copyPreviewUrl(path);
setCopiedKey(path); // mark this button as "copied"
if (copyTimer.current) clearTimeout(copyTimer.current);
copyTimer.current = window.setTimeout(() => setCopiedKey(null), 1500);
};
React.useEffect(() => {
return () => {
if (copyTimer.current) clearTimeout(copyTimer.current);
};
}, []);
useEffect(() => {
if (!dbName || !docId) return;
(async () => {
await dispatch(fetchDocumentDetails({ dbName, docId, rev })); // for dataset detail
dispatch(fetchDbInfoByDatasetId({ dbName, docId })); // for metadata panel (include modality)
})();
}, [dbName, docId, rev, dispatch]);
// for revs list storage
const [revsList, setRevsList] = React.useState<{ rev: string }[]>([]);
useEffect(() => {
const fromDoc = Array.isArray(datasetDocument?._revs_info)
? (datasetDocument._revs_info as { rev: string }[])
: [];
if (fromDoc.length && revsList.length === 0) {
setRevsList(fromDoc);
}
}, [datasetDocument, revsList.length]);
useEffect(() => {
if (datasetDocument) {
// Extract External Data & Assign `index`
// console.log("datasetDocument", datasetDocument);
const links = extractDataLinks(datasetDocument, "").map(
(link, index) => ({
...link,
index, // Assign index correctly
})
);
const bytes = new Blob([JSON.stringify(datasetDocument)], {
type: "application/json",
});
setJsonSize(bytes.size);
// const bytes = new TextEncoder().encode(
// JSON.stringify(datasetDocument)
// ).length;
// setJsonSize(bytes);
// Extract Internal Data & Assign `index`
const internalData = extractInternalData(datasetDocument).map(
(data, index) => ({
...data,
index, // Assign index correctly
})
);
setExternalLinks(links);
setInternalLinks(internalData);
// Calculate total file size from size= query param
let total = 0;
links.forEach((link) => {
const sizeMatch = link.url.match(/(?:[?&]size=)(\d+)/);
if (sizeMatch && sizeMatch[1]) {
total += parseInt(sizeMatch[1], 10);
}
});
setTotalFileSize(total);
let totalSize = 0;
// 1. Sum external link sizes (from URL like ...?size=12345678)
links.forEach((link) => {
const sizeMatch = link.url.match(/size=(\d+)/);
if (sizeMatch) {
totalSize += parseInt(sizeMatch[1], 10);
}
});
// 2. Estimate internal size from _ArraySize_ (assume Float32 = 4 bytes)
internalData.forEach((link) => {
if (link.arraySize && Array.isArray(link.arraySize)) {
const count = link.arraySize.reduce((acc, val) => acc * val, 1);
totalSize += count * 4;
}
});
// const blob = new Blob([JSON.stringify(datasetDocument, null, 2)], {
// type: "application/json",
// });
// setJsonSize(blob.size);
// Construct download script dynamically
let script = `curl -L --create-dirs "https://neurojson.io:7777/${dbName}/${docId}" -o "${docId}.json"\n`;
links.forEach((link) => {
const url = link.url;
const match = url.match(/file=([^&]+)/);
const filename = match
? (() => {
try {
return decodeURIComponent(match[1]);
} catch {
return match[1]; // fallback if decode fails
}
})()
: `file-${link.index}`;
const outputPath = `$HOME/.neurojson/io/${dbName}/${docId}/${filename}`;
script += `curl -L --create-dirs "${url}" -o "${outputPath}"\n`;
});
setDownloadScript(script);
// Calculate and set script size
const scriptBlob = new Blob([script], { type: "text/plain" });
setDownloadScriptSize(scriptBlob.size);
}
}, [datasetDocument, docId]);
// const externalMap = React.useMemo(() => {
// const m = new Map<string, { url: string; index: number }>();
// for (const it of externalLinks)
// m.set(it.path, { url: it.url, index: it.index });
// return m;
// }, [externalLinks]);
const [previewOpen, setPreviewOpen] = useState(false);
const [previewDataKey, setPreviewDataKey] = useState<any>(null);
const handleDownloadDataset = () => {
if (!datasetDocument) return;
const jsonData = JSON.stringify(datasetDocument);
const blob = new Blob([jsonData], { type: "application/json" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${docId}.json`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const handleDownloadScript = () => {
const blob = new Blob([downloadScript], { type: "text/plain" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${docId}.sh`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const handlePreview = (
dataOrUrl: string | any,
idx: number,
isInternal: boolean = false
) => {
// console.log(
// "🟢 Preview button clicked for:",
// dataOrUrl,
// "Index:",
// idx,
// "Is Internal:",
// isInternal
// );
// Clear any stale preview type from last run
delete (window as any).__previewType;
// fix spinner
setIsPreviewLoading(true); // Show the spinner overlay
setPreviewIndex(idx);
setPreviewDataKey(dataOrUrl);
setPreviewIsInternal(isInternal);
const is2DPreviewCandidate = (obj: any): boolean => {
if (typeof window !== "undefined" && (window as any).__previewType) {
return (window as any).__previewType === "2d";
}
if (!obj || typeof obj !== "object") {
return false;
}
if (!obj._ArrayType_ || !obj._ArraySize_ || !obj._ArrayZipData_) {
return false;
}
const dim = obj._ArraySize_;
return (
Array.isArray(dim) &&
(dim.length === 1 || dim.length === 2) &&
dim.every((v) => typeof v === "number" && v > 0)
);
};
// for add spinner ---- start
// When legacy preview is actually ready, turn off spinner & open modal
window.__onPreviewReady = () => {
setIsPreviewLoading(false);
// Only open modal for 3D data
if (!is2DPreviewCandidate(dataOrUrl)) {
setPreviewOpen(true);
}
delete window.__onPreviewReady;
delete (window as any).__previewType; // for is2DPreviewCandidate
};
// -----end
const extractFileName = (url: string): string => {
const match = url.match(/file=([^&]+)/);
if (match) {
// Strip any trailing query parameters
const raw = decodeURIComponent(match[1]);
return raw.split("?")[0].split("&")[0];
}
// fallback: try to get last path part if no 'file=' param
try {
const u = new URL(url);
const parts = u.pathname.split("/");
return parts[parts.length - 1];
} catch {
return url;
}
};
const fileName =
typeof dataOrUrl === "string" ? extractFileName(dataOrUrl) : "";
// console.log("🔍 Extracted fileName:", fileName);
const isPreviewableFile = (fileName: string): boolean => {
return /\.(nii\.gz|jdt|jdb|bmsh|jmsh|bnii)$/i.test(fileName);
};
// console.log("🧪 isPreviewableFile:", isPreviewableFile(fileName));
if (isInternal) {
try {
if (!(window as any).intdata) {
(window as any).intdata = [];
}
if (!(window as any).intdata[idx]) {
(window as any).intdata[idx] = ["", "", null, `Internal ${idx}`];
}
(window as any).intdata[idx][2] = JSON.parse(JSON.stringify(dataOrUrl));
const is2D = is2DPreviewCandidate(dataOrUrl);
if (is2D) {
console.log("📊 2D data → rendering inline with dopreview()");
(window as any).dopreview(dataOrUrl, idx, true);
const panel = document.getElementById("chartpanel");
if (panel) panel.style.display = "block"; // Show it!
setPreviewOpen(false); // Don't open modal
} else {
// console.log("🎬 3D data → rendering in modal");
(window as any).previewdata(dataOrUrl, idx, true, []);
}
} catch (err) {
console.error("❌ Error in internal preview:", err);
}
} else {
const fileName =
typeof dataOrUrl === "string" ? extractFileName(dataOrUrl) : "";
if (isPreviewableFile(fileName)) {
(window as any).previewdataurl(dataOrUrl, idx);
} else {
console.warn("⚠️ Unsupported file format for preview:", dataOrUrl);
}
}
};
// for preview in tree row
const internalMap = React.useMemo(() => {
const m = new Map<string, { data: any; index: number }>();
for (const it of internalLinks)
m.set(it.path, { data: it.data, index: it.index });
return m;
}, [internalLinks]);
const getInternalByPath = (path: string) => internalMap.get(path);
// returns the subtree/primitive at that path—returning the whole document if the path is empty, or undefined if any step is invalid.
const getJsonByPath = React.useCallback(
(path: string) => {
if (!datasetDocument) return undefined;
if (!path) return datasetDocument; // root
const parts = path.split("/").filter(Boolean); // "/a/b/[0]/c" → ["a","b","[0]","c"]
let cur: any = datasetDocument;
for (const p of parts) {
if (/^\[\d+\]$/.test(p)) {
const idx = parseInt(p.slice(1, -1), 10);
if (!Array.isArray(cur)) return undefined;
cur = cur[idx];
} else {
if (cur == null || typeof cur !== "object") return undefined;
cur = cur[p];
}
}
return cur;
},
[datasetDocument]
);
// check if the url has preview param
useEffect(() => {
const p = searchParams.get("preview");
if (!p || !datasetDocument) return;
const previewPath = decodeURIComponent(p);
// Try internal data first
const internal = internalMap.get(previewPath);
if (internal) {
handlePreview(internal.data, internal.index, true);
return;
}
// Then try external data by JSON path
const external = linkMap.get(previewPath);
if (external) {
handlePreview(external.url, external.index, false);
}
}, [
datasetDocument,
internalLinks,
externalLinks,
searchParams,
internalMap,
linkMap, // externalMap
]);
const handleClosePreview = () => {
setPreviewOpen(false);
setPreviewDataKey(null);
// Cancel animation frame loop
if (typeof window.reqid !== "undefined") {
cancelAnimationFrame(window.reqid);
window.reqid = undefined;
}
// Stop 2D chart if any
const panel = document.getElementById("chartpanel");
if (panel) panel.style.display = "none";
// Reset Three.js global refs
window.scene = undefined;
window.camera = undefined;
window.renderer = undefined;
};
if (loading) {
return (
<Box
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh",
}}
>
<CircularProgress sx={{ color: Colors.primary.main }} />
</Box>
);
}
if (error) {
return (
<Box sx={{ textAlign: "center", padding: 4 }}>
<Alert severity="error" sx={{ color: Colors.error }}>
{error}
</Alert>
</Box>
);
}
const onekey = datasetDocument
? datasetDocument.hasOwnProperty("README")
? "README"
: datasetDocument.hasOwnProperty("dataset_description.json")
? "dataset_description.json"
: "_id"
: "_id";
return (
<>
<Box sx={{ padding: 4 }}>
{/* <Button
variant="text"
onClick={() => navigate(-1)}
sx={{
marginBottom: 2,
color: Colors.white,
"&:hover": {
transform: "scale(1.05)",
backgroundColor: "transparent",
textDecoration: "underline",
},
}}
>
Back
</Button> */}
{/* Breadcrumb Navigation (Home → Database → Dataset) */}
<Box
sx={{
display: "flex",
alignItems: "center",
marginBottom: 2,
}}
>
{/* Home Icon Button */}
<Button
onClick={() => navigate("/")}
sx={{
backgroundColor: "transparent",
padding: 0,
minWidth: "auto",
"&:hover": { backgroundColor: "transparent" },
}}
>
<HomeIcon
sx={{
color: Colors.white,
"&:hover": {
transform: "scale(1.1)",
backgroundColor: "transparent",
},
}}
/>
</Button>
<Typography
variant="h5"
sx={{ marginX: 1, fontWeight: "bold", color: Colors.white }}
>
»
</Typography>
{/* Database Name (Clickable) */}
<Button
onClick={() => navigate(`${RoutesEnum.DATABASES}/${dbName}`)}
sx={{
textTransform: "none",
fontSize: "1.2rem",
fontWeight: "bold",
color: Colors.white,
"&:hover": {
transform: "scale(1.05)",
backgroundColor: "transparent",
},
}}
>
{dbName?.toLowerCase()}
</Button>
<Typography
variant="h5"
sx={{ marginX: 1, fontWeight: "bold", color: Colors.white }}
>
»
</Typography>
{/* Dataset Name (_id field) */}
<Typography
variant="h5"
sx={{
fontWeight: "bold",
color: Colors.white,
fontSize: "1.2rem",
}}
>
{docId}
</Typography>
</Box>
<Box
sx={{
position: "sticky",
top: 0,
backgroundColor: "white",
zIndex: 10,
padding: 2,
borderBottom: `1px solid ${Colors.lightGray}`,
borderRadius: "8px",
}}
>
{/* Dataset Title (From dataset_description.json) */}
<Typography
variant="h4"
color={Colors.darkPurple}
sx={{ fontWeight: "bold", mb: 1 }}
>
{datasetDocument?.["dataset_description.json"]?.Name ??
`Dataset: ${docId}`}
</Typography>
{/* Dataset Author (If Exists) */}
{datasetDocument?.["dataset_description.json"]?.Authors && (
<Typography
variant="h6"
sx={{ fontStyle: "italic", color: Colors.textSecondary }}
>
{Array.isArray(
datasetDocument["dataset_description.json"].Authors
)
? datasetDocument["dataset_description.json"].Authors.join(", ")
: datasetDocument["dataset_description.json"].Authors}
</Typography>
)}
{/* ai summary */}
{aiSummary ? (
<>
<Box
sx={{
display: "flex",
alignItems: "center",
mb: 0.5,
mt: 1,
gap: 0.5,
}}
>
<Typography
color={Colors.purple}
sx={{ fontWeight: "bold", mb: 0.5, mt: 1 }}
>
AI Summary
</Typography>
<Tooltip
title={
<Typography variant="body2" sx={{ color: Colors.darkGray }}>
AI Summary is generated using an AI tool that identifies
the related paper and extracts its key content to create a
concise summary.
</Typography>
}
arrow
placement="right"
slotProps={{
tooltip: {
sx: {
bgcolor: Colors.white,
border: `1px solid ${Colors.lightGray}`,
boxShadow: 3,
fontSize: "0.875rem",
},
},
arrow: {
sx: {
color: Colors.white,
"&::before": {
border: `1px solid ${Colors.lightGray}`, // subtle arrow border
},
},
},
}}
>
<InfoOutlinedIcon
fontSize="small"
sx={{
color: Colors.purple,
cursor: "pointer",
}}
/>
</Tooltip>
</Box>
<ReadMoreText text={aiSummary} />
</>
) : readme ? (
<>
<Box
sx={{
display: "flex",
alignItems: "center",
mb: 0.5,
mt: 1,
gap: 0.5,
}}
>
<Typography
color={Colors.purple}
sx={{ fontWeight: "bold", mb: 0.5, mt: 1 }}
>
Summary
</Typography>
</Box>
<ReadMoreText text={readme} />
</>
) : (
""
)}
<Box
sx={{
display: "flex",
alignItems: "center",
flexWrap: "wrap",
gap: 2,
mb: 2,
backgroundColor: "#f5f5f5",
padding: "12px",
borderRadius: "8px",
}}
>
<Button
variant="contained"
startIcon={<CloudDownloadIcon />}
onClick={handleDownloadDataset}
sx={{
backgroundColor: Colors.purple,
color: Colors.lightGray,
"&:hover": { backgroundColor: Colors.secondaryPurple },
}}
>
Download Metadata ({formatSize(jsonSize)})
</Button>
<Button
variant="contained"
startIcon={<DescriptionIcon />}
onClick={handleDownloadScript}
sx={{
backgroundColor: Colors.purple,
color: Colors.lightGray,
"&:hover": { backgroundColor: Colors.secondaryPurple },
}}
>
{/* Script to Download All Files ({downloadScript.length} Bytes) */}
Script to Download All Files ({formatSize(downloadScriptSize)})
{externalLinks.length > 0 &&
` (links: ${externalLinks.length}, total: ${formatSize(
totalFileSize
)})`}
</Button>
</Box>
</Box>
<Box
sx={{
display: "flex",
gap: 2,
alignItems: "flex-start",
marginTop: 2,
flexDirection: {
xs: "column",
md: "row",
},
height: {
xs: "auto",
md: "560px", // fixed height container
},
}}
>
{/* tree viewer (left panel) */}
<Box
sx={{
flex: 3,
backgroundColor: "#f5f5f5",
padding: 2,
borderRadius: "8px",
overflowX: "auto",
height: {
xs: "auto",
md: "100%",
},
width: {
xs: "100%",
md: "auto",
},
minWidth: {
xs: "100%",
md: "350px",
},
}}
>
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: 2,
height: "100%",
overflow: "hidden",
}}
>
{/* folder structure */}
<Box sx={{ flex: 1, minHeight: 240, overflow: "hidden" }}>
<FileTree
title={treeTitle}
tree={treeData}
onPreview={handlePreview} // pass the function down to FileTree
getInternalByPath={getInternalByPath}
getJsonByPath={getJsonByPath}
highlightText={focus} // for highlight
/>
</Box>
</Box>
</Box>