-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathArtifactsTab.tsx
More file actions
300 lines (269 loc) · 8.79 KB
/
Copy pathArtifactsTab.tsx
File metadata and controls
300 lines (269 loc) · 8.79 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
/*
* Copyright contributors to the Galasa project
*
* SPDX-License-Identifier: EPL-2.0
*/
'use client';
import { ArtifactIndexEntry } from '@/generated/galasaapi';
import { TreeView, TreeNode, InlineLoading, InlineNotification } from '@carbon/react';
import { useState } from 'react';
import styles from '@/styles/test-runs/test-run-details/Artifacts.module.css';
import {
CarbonIconType,
CloudDownload,
Document,
Folder,
Image,
Json,
Zip,
} from '@carbon/icons-react';
import { downloadArtifactFromServer } from '@/actions/runsAction';
import { Tile } from '@carbon/react';
import { handleDownload } from '@/utils/artifacts';
import { useTranslations } from 'next-intl';
import { Button } from '@carbon/react';
import {
FolderNode,
ArtifactDetails,
TreeNodeData,
DownloadResult,
} from '@/utils/functions/artifacts';
export function ArtifactsTab({
artifacts,
artifactsTreeData,
runId,
runName,
isLoadingArtifacts = false,
artifactsError = null,
setZos3270TerminalFolderExists,
setZos3270TerminalData,
}: {
artifacts: ArtifactIndexEntry[];
artifactsTreeData: FolderNode;
runId: string;
runName: string;
isLoadingArtifacts?: boolean;
artifactsError?: string | null;
setZos3270TerminalFolderExists: (exists: boolean) => void;
setZos3270TerminalData: (zos3270TerminalData: TreeNodeData[]) => void;
}) {
const translations = useTranslations('Artifacts');
const [artifactDetails, setArtifactDetails] = useState<ArtifactDetails>({
artifactFile: '',
fileSize: '',
fileName: '',
base64Data: '',
contentType: '',
});
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string | null>(null);
const [expandedFolders, setExpandedFolders] = useState<{ [path: string]: boolean }>({});
const ZIP_EXTENSIONS = ['zip', 'gz', 'jar', 'rar', '7z'];
const IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'svg'];
function formatFileSize(bytes: number) {
let fileSize = '';
if (bytes < 10000) {
fileSize = `${bytes} bytes`;
} else {
const mb = bytes / (1024 * 1024);
fileSize = `${mb.toFixed(2)} MB`;
}
return fileSize;
}
const handleDownloadClick = () => {
if (artifactDetails.base64Data) {
// (a) Turn Base64 string → binary string
const binaryString = atob(artifactDetails.base64Data);
// (b) Convert binary string → Uint8Array
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const cleanFileName = artifactDetails.fileName.startsWith('/')
? artifactDetails.fileName.slice(1)
: artifactDetails.fileName; //strip any leading slashes
handleDownload(bytes.buffer, cleanFileName);
}
};
const toggleFolder = (path: string) => {
setExpandedFolders((prev) => ({
...prev,
// Toggle just this folder's state
[path]: !prev[path],
}));
};
const downloadArtifact = async (runId: string, artifactUrl: string) => {
setLoading(true);
setError(null);
try {
const result: DownloadResult = await downloadArtifactFromServer(runId, artifactUrl);
setArtifactDetails({
artifactFile: result.data,
fileSize: formatFileSize(result.size),
fileName: artifactUrl,
base64Data: result.base64,
contentType: result.contentType,
});
} catch (err: unknown) {
console.error(err);
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setLoading(false);
}
};
function renderArtifactContent(artifactFile: string, contentType: string) {
let result;
// 1) Nothing selected
if (!artifactFile) {
result = <p>Select a file to display its content</p>;
}
// 2) Plain-text (or any text/* MIME)
else if (contentType.startsWith('text/')) {
result = <pre>{artifactFile}</pre>;
}
// 3) JSON (or JS object)
else if (contentType.includes('json') || typeof artifactFile === 'object') {
// if it's a string, try to parse it first
let data = artifactFile;
if (typeof artifactFile === 'string') {
try {
data = JSON.parse(artifactFile);
} catch (err) {
setError('Error parsing JSON content');
console.error('Error parsing file: ', err);
}
}
result = <pre>{JSON.stringify(data, null, 2)}</pre>; //preventing any filtering and ensuring identation of two spaces
}
// 4) Binary (zip, images, etc.)
else {
result = <p>This is a binary file ({contentType}), please download it to see its content.</p>;
}
return result;
}
const renderFileIcon = (path: string) => {
const pathSplit = path.split('.');
const extension = pathSplit[pathSplit.length - 1]; // get the last split e.g some.file.ts -> we need the extension (ts)
let icon: CarbonIconType = Document;
if (ZIP_EXTENSIONS.includes(extension)) {
icon = Zip;
} else if (extension == 'json') {
icon = Json;
} else if (IMAGE_EXTENSIONS.includes(extension)) {
icon = Image;
}
return icon;
};
// Recursive renderer: emits a <TreeNode> for each TreeNodeData
const renderNode = (node: TreeNodeData, path: string) => {
let treeNode;
const isExpanded = expandedFolders[path] || false;
if (node.isFile) {
// Leaf file node
treeNode = (
<TreeNode
key={path}
id={path}
renderIcon={renderFileIcon(path)}
label={node.name}
value={node.name}
onSelect={() => downloadArtifact(runId, node.url)}
/>
);
} else {
// Folder node: render label, then recurse on children
treeNode = (
<TreeNode
onToggle={() => toggleFolder(path)}
isExpanded={isExpanded}
key={path}
id={path}
label={node.name}
value={node.name}
renderIcon={Folder}
>
{Object.values(node.children).map((child) => {
const childPath = path ? `${path}/${child.name}` : child.name;
return renderNode(child, childPath);
})}
</TreeNode>
);
}
return treeNode;
};
return (
<>
<div className={styles.titleContainer}>
<h3>{translations('title')}</h3>
<p>{translations('description')}</p>
</div>
{isLoadingArtifacts && (
<div className={styles.artifact}>
<InlineLoading
description={translations('loading_artifacts')}
iconDescription={translations('loading_artifacts')}
/>
</div>
)}
{artifactsError && (
<InlineNotification
kind="error"
title={translations('error_title')}
subtitle={artifactsError}
hideCloseButton={false}
/>
)}
{!isLoadingArtifacts && !artifactsError && artifacts.length === 0 && (
<p>{translations('no_artifacts')}</p>
)}
{!isLoadingArtifacts && !artifactsError && artifacts.length > 0 && (
<div className={styles.artifact}>
<TreeView className={styles.tree} onSelect={() => { }}>
{Object.values(artifactsTreeData.children).map((child) => renderNode(child, child.name))}
</TreeView>
<div className={styles.artifactView}>
{loading && (
<InlineLoading
description={translations('downloading')}
iconDescription={translations('downloading')}
/>
)}
{error && (
<InlineNotification
title={translations('error_title')}
subtitle={translations('error_subtitle', { runName })}
/>
)}
{!loading && !error && (
<div>
<div>
{artifactDetails.artifactFile !== '' && (
<Tile className={styles.toolbar}>
<div>
<h5>{artifactDetails.fileName}</h5>
<p className={styles.fileSize}>{artifactDetails.fileSize}</p>
</div>
<div className={styles.toolbarOptions}>
<Button
kind="ghost"
renderIcon={CloudDownload}
hasIconOnly
iconDescription={translations('download_button')}
onClick={handleDownloadClick}
/>
</div>
</Tile>
)}
</div>
<pre className={styles.fileRenderer}>
{renderArtifactContent(artifactDetails.artifactFile, artifactDetails.contentType)}
</pre>
</div>
)}
</div>
</div>
)}
</>
);
}