Spaces:
Running
Running
File size: 11,737 Bytes
56bf851 826a975 56bf851 826a975 56bf851 826a975 56bf851 826a975 56bf851 826a975 56bf851 |
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 |
import React, { useState, useEffect, useCallback } from "react";
import { debugLog } from "../utils/config";
import TroubleshootingGuide from "./TroubleshootingGuide";
import "./DataViewer.css";
const DataViewer = ({ s3Url, onDownload, showPreviewOnly = false }) => {
const [data, setData] = useState([]);
const [columns, setColumns] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [currentPage, setCurrentPage] = useState(1);
const [rowsPerPage] = useState(10);
const fetchData = useCallback(async () => {
try {
setLoading(true);
setError(null);
debugLog("Fetching data from S3 URL:", s3Url);
// Try multiple approaches to fetch the data
let response;
// Method 1: Direct fetch with CORS
try {
response = await fetch(s3Url, {
method: "GET",
headers: {
Accept: "text/csv,text/plain,application/octet-stream,*/*",
},
mode: "cors",
});
} catch (corsError) {
debugLog("CORS fetch failed, trying no-cors:", corsError);
// Method 2: Try with no-cors mode (limited but might work)
try {
response = await fetch(s3Url, {
method: "GET",
mode: "no-cors",
});
} catch (noCorsError) {
debugLog("No-cors fetch also failed:", noCorsError);
throw new Error(
"Unable to preview data due to CORS restrictions. You can still download the file directly."
);
}
}
if (!response.ok && response.status !== 0) {
// If direct fetch fails, provide helpful error messages
if (response.status === 403 || response.status === 401) {
throw new Error(
"Access denied. The file may require authentication or have expired."
);
} else if (response.status === 404) {
throw new Error(
"File not found. The download link may have expired."
);
} else {
throw new Error(
`Unable to fetch data (${response.status}). You can still download the file directly.`
);
}
}
// For no-cors responses, we can't read the content
if (response.type === "opaque") {
throw new Error(
"Preview not available due to CORS restrictions. Please download the file to view the data."
);
}
const csvText = await response.text();
if (!csvText || csvText.trim().length === 0) {
throw new Error("The downloaded file appears to be empty");
}
const parsedData = parseCSV(csvText);
if (parsedData.length > 0) {
setColumns(Object.keys(parsedData[0]));
setData(parsedData);
debugLog("Data parsed successfully:", {
rows: parsedData.length,
columns: Object.keys(parsedData[0]).length,
sampleData: parsedData.slice(0, 2),
});
} else {
throw new Error("No valid data rows found in the file");
}
} catch (err) {
setError(err.message);
debugLog("Error fetching data:", err);
} finally {
setLoading(false);
}
}, [s3Url]);
useEffect(() => {
if (s3Url) {
fetchData();
}
}, [s3Url, fetchData]);
const parseCSV = (csvText) => {
try {
const lines = csvText.trim().split("\n");
if (lines.length < 2) return [];
// Handle different CSV formats and potential quotes
const parseCSVLine = (line) => {
const result = [];
let current = "";
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"') {
inQuotes = !inQuotes;
} else if (char === "," && !inQuotes) {
result.push(current.trim());
current = "";
} else {
current += char;
}
}
result.push(current.trim());
return result.map((value) => value.replace(/^"(.*)"$/, "$1")); // Remove outer quotes
};
const headers = parseCSVLine(lines[0]);
const rows = [];
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim() === "") continue; // Skip empty lines
const values = parseCSVLine(lines[i]);
if (values.length > 0 && values.some((val) => val.trim() !== "")) {
const row = {};
headers.forEach((header, index) => {
row[header] = values[index] || "";
});
rows.push(row);
}
}
return rows;
} catch (err) {
debugLog("Error parsing CSV:", err);
throw new Error(
"Failed to parse CSV data. The file format may be invalid."
);
}
};
const getPaginatedData = () => {
const startIndex = (currentPage - 1) * rowsPerPage;
const endIndex = startIndex + rowsPerPage;
return data.slice(startIndex, endIndex);
};
const totalPages = Math.ceil(data.length / rowsPerPage);
const handleDownload = () => {
if (onDownload) {
onDownload();
} else {
window.open(s3Url, "_blank");
}
};
if (loading) {
return (
<div className="data-viewer loading">
<div className="spinner"></div>
<p>Loading data preview...</p>
</div>
);
}
if (error) {
return (
<div className="data-viewer error">
<div className="status-message error">
<div className="status-message-icon">β</div>
<div className="status-message-content">
<h4>Unable to Preview Data</h4>
<p>{error}</p>
<div
className="error-help"
style={{ marginTop: "0.75rem", fontSize: "0.875rem" }}
>
<strong>
Don't worry! Your data has been generated successfully.
</strong>
<br />
<strong>Possible solutions:</strong>
<ul
style={{
marginTop: "0.5rem",
paddingLeft: "1.5rem",
textAlign: "left",
}}
>
{!showPreviewOnly && (
<li>
<strong>Download the file directly</strong> using the button
below
</li>
)}
<li>
The preview may fail due to browser security restrictions
</li>
<li>
Your generated data is still available and ready
{showPreviewOnly ? "" : " to download"}
</li>
</ul>
</div>
</div>
</div>
<div
className="error-actions"
style={{ marginTop: "1.5rem", textAlign: "center" }}
>
{!showPreviewOnly && (
<button
className="btn btn-primary btn-large"
onClick={handleDownload}
style={{
marginRight: "0.75rem",
padding: "12px 24px",
fontSize: "1rem",
}}
>
π₯ Download Generated Data
</button>
)}
<button
className="btn btn-secondary"
onClick={() => fetchData()}
style={{ marginLeft: showPreviewOnly ? "0" : "0.75rem" }}
>
π Try Preview Again
</button>
</div>
<div
className="success-note"
style={{
marginTop: "1.5rem",
padding: "1rem",
background: "var(--success-light, #e8f5e8)",
borderRadius: "8px",
border: "1px solid var(--success, #28a745)",
textAlign: "center",
}}
>
<div
style={{
color: "var(--success, #28a745)",
fontWeight: "bold",
marginBottom: "0.5rem",
}}
>
β
Data Generation Completed Successfully!
</div>
<div style={{ fontSize: "0.875rem", color: "var(--text-secondary)" }}>
The preview failed, but your synthetic data has been generated and
is ready for download.
</div>
</div>
<TroubleshootingGuide
generatedDataLink={s3Url}
onDownload={handleDownload}
/>
</div>
);
}
if (data.length === 0) {
return (
<div className="data-viewer empty">
<div className="status-message warning">
<div className="status-message-icon">β οΈ</div>
<div className="status-message-content">
<h4>No Data Available</h4>
<p>The generated file appears to be empty.</p>
</div>
</div>
{!showPreviewOnly && (
<div className="download-section" style={{ marginTop: "1rem" }}>
<button className="btn btn-primary" onClick={handleDownload}>
π₯ Download File
</button>
</div>
)}
</div>
);
}
return (
<div className="data-viewer">
<div className="data-viewer-header">
<div className="data-info">
<h4>π Generated Data {showPreviewOnly ? "Preview" : ""}</h4>
<p>
Showing {getPaginatedData().length} of {data.length} rows β’{" "}
{columns.length} columns
</p>
</div>
{!showPreviewOnly && (
<button
className="btn btn-success download-btn"
onClick={handleDownload}
>
π₯ Download Complete File
</button>
)}
</div>
<div className="data-table-container">
<table className="data-table">
<thead>
<tr>
{columns.map((column, index) => (
<th key={index} title={column}>
{column}
</th>
))}
</tr>
</thead>
<tbody>
{getPaginatedData().map((row, index) => (
<tr key={index}>
{columns.map((column, colIndex) => (
<td key={colIndex} title={row[column]}>
{row[column]}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
{totalPages > 1 && (
<div className="pagination">
<button
className="btn btn-secondary"
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
>
β Previous
</button>
<span className="pagination-info">
Page {currentPage} of {totalPages}
</span>
<button
className="btn btn-secondary"
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
disabled={currentPage === totalPages}
>
Next β
</button>
</div>
)}
{showPreviewOnly && data.length > 0 && (
<div
className="preview-note"
style={{
marginTop: "1rem",
padding: "0.75rem",
background: "var(--bg-tertiary)",
borderRadius: "8px",
fontSize: "0.875rem",
color: "var(--text-secondary)",
textAlign: "center",
}}
>
π‘ Showing first {Math.min(data.length, rowsPerPage * totalPages)}{" "}
rows. Download the complete file to view all {data.length} rows.
</div>
)}
</div>
);
};
export default DataViewer;
|