Spaces:
Running
Running
File size: 20,357 Bytes
7013d65 71cdd8f 716c855 71cdd8f fc96140 71cdd8f fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 bdcfc0b fc96140 bdcfc0b fc96140 bdcfc0b fc96140 bdcfc0b fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 fc96140 7013d65 bdcfc0b 7013d65 fc96140 | 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 |
// Inicializar clipboard
let clipboard = new ClipboardJS('.copy-btn');
clipboard.on('success', function(e) {
showAlert("Copiado al portapapeles", "success");
e.clearSelection();
});
clipboard.on('error', function(e) {
showAlert("Error al copiar", "error");
});
// Check saved theme preference
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
document.addEventListener('DOMContentLoaded', function() {
const fileInput = document.getElementById('xmlFileInput');
const dashboard = document.getElementById('dashboard');
const saveBtn = document.getElementById('saveBtn');
const resetBtn = document.getElementById('resetBtn');
const expandAllBtn = document.getElementById('expandAllBtn');
const addRowBtn = document.getElementById('addRowBtn');
const exportExcelBtn = document.getElementById('exportExcelBtn');
const exportCsvBtn = document.getElementById('exportCsvBtn');
const exportJsonBtn = document.getElementById('exportJsonBtn');
const exportXmlBtn = document.getElementById('exportXmlBtn');
const dataExport = document.getElementById('dataExport');
// Variables globales para el estado
let currentData = null;
let originalData = null;
let currentFileType = null;
fileInput.addEventListener('change', handleFileSelect);
saveBtn.addEventListener('click', saveChanges);
resetBtn.addEventListener('click', resetData);
expandAllBtn.addEventListener('click', expandAllNodes);
addRowBtn.addEventListener('click', addNewRow);
exportExcelBtn.addEventListener('click', () => exportData('xlsx'));
exportCsvBtn.addEventListener('click', () => exportData('csv'));
exportJsonBtn.addEventListener('click', () => exportData('json'));
exportXmlBtn.addEventListener('click', () => exportData('xml'));
function handleFileSelect(event) {
const file = event.target.files[0];
if (!file) return;
const fileExtension = file.name.split('.').pop().toLowerCase();
currentFileType = fileExtension;
// Actualizar timestamp
document.getElementById('timestamp').textContent = new Date().toLocaleString();
if (fileExtension === 'xml') {
const reader = new FileReader();
reader.onload = function(e) {
try {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(e.target.result, "application/xml");
if (xmlDoc.getElementsByTagName("parsererror").length > 0) {
showAlert("El archivo XML no es v谩lido. Por favor, verifica su formato.", "error");
return;
}
currentData = xmlDoc;
originalData = xmlDoc.cloneNode(true);
processXML(xmlDoc);
showDashboard();
} catch (error) {
console.error("Error parsing XML:", error);
showAlert("Ocurri贸 un error al procesar el archivo XML.", "error");
}
};
reader.readAsText(file);
} else if (['xlsx', 'xls', 'csv'].includes(fileExtension)) {
// Cargar SheetJS (xlsx) din谩micamente
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js';
script.onload = () => {
const reader = new FileReader();
reader.onload = function(e) {
try {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
// Procesar la primera hoja
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
// Convertir a JSON
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
// Calcular m茅tricas
const elementCount = jsonData.length - 1; // Excluyendo encabezados
const attributeCount = jsonData[0] ? jsonData[0].length : 0;
// Actualizar UI
document.getElementById('elementCount').textContent = elementCount;
document.getElementById('depthCount').textContent = 1; // Excel tiene solo 1 nivel
document.getElementById('attributeCount').textContent = attributeCount;
// Generar vista de 谩rbol
const treeView = generateExcelTreeView(jsonData, firstSheetName);
document.getElementById('xmlTree').innerHTML = treeView;
// Generar tabla de datos
generateExcelTable(jsonData, firstSheetName);
dashboard.classList.remove('hidden');
} catch (error) {
console.error("Error processing Excel file:", error);
alert("Ocurri贸 un error al procesar el archivo Excel.");
}
};
reader.readAsArrayBuffer(file);
};
document.head.appendChild(script);
} else {
alert("Formato de archivo no soportado. Por favor, sube un archivo XML o Excel.");
}
}
function generateExcelTreeView(data, sheetName) {
let html = `<span class="xml-tag">[Hoja: ${sheetName}]</span><br><br>`;
// Encabezados
html += '<span class="excel-sheet">Encabezados:</span><br>';
if (data[0]) {
html += data[0].map(header =>
` <span class="excel-cell">${header || '(vac铆o)'}</span><br>`
).join('');
}
// Datos de ejemplo
html += '<br><span class="excel-sheet">Datos (primeras 5 filas):</span><br>';
const sampleRows = data.slice(1, 6);
sampleRows.forEach((row, i) => {
html += ` <span class="xml-tag">[Fila ${i + 1}]</span><br>`;
row.forEach((cell, j) => {
const header = data[0] ? data[0][j] : `Col${j+1}`;
html += ` <span class="excel-cell">${header}</span>: <span class="xml-value">${cell || '(vac铆o)'}</span><br>`;
});
});
if (data.length > 6) {
html += ` <span class="xml-value">... y ${data.length - 6} filas m谩s</span><br>`;
}
return html;
}
function generateExcelTable(data, sheetName) {
const tableBody = document.getElementById('tableBody');
tableBody.innerHTML = '';
if (!data.length) return;
const headers = data[0] || [];
const rows = data.slice(1);
// Limitar a 100 filas para no sobrecargar la UI
const displayRows = rows.slice(0, 100);
displayRows.forEach((row, rowIndex) => {
row.forEach((cell, colIndex) => {
const header = headers[colIndex] || `Col${colIndex+1}`;
const rowNum = rowIndex + 2; // +1 para base 1, +1 porque saltamos encabezados
const tr = document.createElement('tr');
tr.className = 'hover:bg-gray-50';
tr.innerHTML = `
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${sheetName}!${header}${rowNum}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${cell || '(vac铆o)'}</td>
`;
tableBody.appendChild(tr);
});
});
if (rows.length > 100) {
const tr = document.createElement('tr');
tr.innerHTML = `
<td colspan="2" class="px-6 py-4 text-center text-sm text-gray-500">
Mostrando 100 de ${rows.length} filas
</td>
`;
tableBody.appendChild(tr);
}
}
function processXML(xmlDoc) {
// Contar elementos
const elements = xmlDoc.getElementsByTagName('*');
document.getElementById('elementCount').textContent = elements.length;
// Analizar estructura y profundidad
const root = xmlDoc.documentElement;
const maxDepth = getMaxDepth(root);
document.getElementById('depthCount').textContent = maxDepth;
// Contar atributos
let attributeCount = 0;
const allElements = xmlDoc.getElementsByTagName('*');
for (let el of allElements) {
attributeCount += el.attributes.length;
}
document.getElementById('attributeCount').textContent = attributeCount;
// Generar vista de 谩rbol
const treeView = generateTreeView(root);
document.getElementById('xmlTree').innerHTML = treeView;
// Generar tabla de datos
generateDataTable(root);
}
function getMaxDepth(node, currentDepth = 1) {
if (!node.children || node.children.length === 0) return currentDepth;
let maxDepth = currentDepth;
for (let child of node.children) {
const depth = getMaxDepth(child, currentDepth + 1);
if (depth > maxDepth) maxDepth = depth;
}
return maxDepth;
}
function generateTreeView(node, indent = 0) {
let html = '';
const indentStr = ' '.repeat(indent * 4);
// Abrir etiqueta
html += `${indentStr}<span class="xml-tag"><${node.nodeName.toLowerCase()}</span>`;
// Atributos
if (node.attributes && node.attributes.length > 0) {
for (let attr of node.attributes) {
html += ` <span class="xml-attr">${attr.name}</span>=<span class="text-red-500">"${attr.value}"</span>`;
}
}
html += '<span class="xml-tag">></span><br>';
// Contenido y nodos hijos
if (node.childNodes.length > 0) {
let hasElementChildren = false;
for (let child of node.childNodes) {
if (child.nodeType === Node.ELEMENT_NODE) {
hasElementChildren = true;
html += generateTreeView(child, indent + 1);
} else if (child.nodeType === Node.TEXT_NODE && child.nodeValue.trim() !== '') {
html += `${indentStr} <span class="xml-value">${child.nodeValue.trim()}</span><br>`;
}
}
if (hasElementChildren) {
html += `${indentStr}`;
}
}
// Cerrar etiqueta
html += `<span class="xml-tag"></${node.nodeName.toLowerCase()}></span><br>`;
return html;
}
function generateDataTable(node) {
const tableBody = document.getElementById('tableBody');
tableBody.innerHTML = '';
// Funci贸n recursiva para extraer datos
function extractData(node, path = '') {
const currentPath = path ? `${path}.${node.nodeName}` : node.nodeName;
// Atributos
if (node.attributes && node.attributes.length > 0) {
for (let attr of node.attributes) {
addRow(`${currentPath}@${attr.name}`, attr.value);
}
}
// Contenido de texto
let textContent = '';
for (let child of node.childNodes) {
if (child.nodeType === Node.TEXT_NODE && child.nodeValue.trim() !== '') {
textContent += child.nodeValue.trim();
}
}
if (textContent) {
addRow(currentPath, textContent);
}
// Nodos hijos
for (let child of node.childNodes) {
if (child.nodeType === Node.ELEMENT_NODE) {
extractData(child, currentPath);
}
}
}
function addRow(key, value) {
const row = document.createElement('tr');
row.className = 'hover:bg-gray-50 group';
const keyCell = document.createElement('td');
keyCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-900';
keyCell.textContent = key;
const valueCell = document.createElement('td');
valueCell.className = 'px-6 py-4 whitespace-nowrap';
const valueInput = document.createElement('input');
valueInput.type = 'text';
valueInput.className = 'w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-primary focus:border-primary';
valueInput.value = value || '';
valueInput.addEventListener('change', () => {
saveBtn.classList.remove('hidden');
resetBtn.classList.remove('hidden');
});
valueCell.appendChild(valueInput);
const actionCell = document.createElement('td');
actionCell.className = 'px-2 py-4 whitespace-nowrap text-right text-sm font-medium opacity-0 group-hover:opacity-100 transition-opacity';
const deleteBtn = document.createElement('button');
deleteBtn.className = 'text-red-500 hover:text-red-700';
deleteBtn.innerHTML = '<i data-feather="trash-2" class="w-4 h-4"></i>';
deleteBtn.addEventListener('click', () => {
row.remove();
saveBtn.classList.remove('hidden');
resetBtn.classList.remove('hidden');
});
actionCell.appendChild(deleteBtn);
row.appendChild(keyCell);
row.appendChild(valueCell);
row.appendChild(actionCell);
tableBody.appendChild(row);
feather.replace();
}
extractData(node);
}
function addNewRow() {
const row = document.createElement('tr');
row.className = 'hover:bg-gray-50 group bg-blue-50';
const keyCell = document.createElement('td');
keyCell.className = 'px-6 py-4 whitespace-nowrap';
const keyInput = document.createElement('input');
keyInput.type = 'text';
keyInput.className = 'w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-primary focus:border-primary';
keyInput.placeholder = 'Nueva clave';
keyCell.appendChild(keyInput);
const valueCell = document.createElement('td');
valueCell.className = 'px-6 py-4 whitespace-nowrap';
const valueInput = document.createElement('input');
valueInput.type = 'text';
valueInput.className = 'w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-primary focus:border-primary';
valueInput.placeholder = 'Nuevo valor';
valueCell.appendChild(valueInput);
const actionCell = document.createElement('td');
actionCell.className = 'px-2 py-4 whitespace-nowrap text-right text-sm font-medium';
const confirmBtn = document.createElement('button');
confirmBtn.className = 'text-green-500 hover:text-green-700 mr-2';
confirmBtn.innerHTML = '<i data-feather="check" class="w-4 h-4"></i>';
confirmBtn.addEventListener('click', () => {
if (!keyInput.value.trim()) {
showAlert("Por favor ingresa una clave v谩lida", "warning");
return;
}
row.className = 'hover:bg-gray-50 group';
keyCell.innerHTML = keyInput.value;
valueCell.innerHTML = `<input type="text" class="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-primary focus:border-primary" value="${valueInput.value}">`;
actionCell.innerHTML = '<button class="text-red-500 hover:text-red-700"><i data-feather="trash-2" class="w-4 h-4"></i></button>';
saveBtn.classList.remove('hidden');
resetBtn.classList.remove('hidden');
feather.replace();
});
const cancelBtn = document.createElement('button');
cancelBtn.className = 'text-gray-500 hover:text-gray-700';
cancelBtn.innerHTML = '<i data-feather="x" class="w-4 h-4"></i>';
cancelBtn.addEventListener('click', () => row.remove());
actionCell.appendChild(confirmBtn);
actionCell.appendChild(cancelBtn);
row.appendChild(keyCell);
row.appendChild(valueCell);
row.appendChild(actionCell);
tableBody.appendChild(row);
feather.replace();
}
function showDashboard() {
dashboard.classList.remove('hidden');
dataExport.classList.remove('hidden');
feather.replace();
}
function expandAllNodes() {
// Implementar l贸gica para expandir todos los nodos del 谩rbol XML
const tree = document.getElementById('xmlTree');
// Simulaci贸n de expansi贸n
tree.querySelectorAll('.collapsible').forEach(node => {
node.classList.remove('hidden');
});
}
function saveChanges() {
// Implementar l贸gica para guardar cambios
showAlert("Cambios guardados correctamente", "success");
saveBtn.classList.add('hidden');
resetBtn.classList.add('hidden');
}
function resetData() {
if (confirm("驴Est谩s seguro de que deseas descartar todos los cambios?")) {
if (currentFileType === 'xml') {
processXML(originalData);
} else {
// Resetear datos Excel/CSV
}
saveBtn.classList.add('hidden');
resetBtn.classList.add('hidden');
showAlert("Cambios descartados", "info");
}
}
function exportData(format) {
let fileName = 'exported_data';
let mimeType = '';
let data = '';
switch(format) {
case 'xlsx':
fileName += '.xlsx';
mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
// Implementar exportaci贸n a Excel
break;
case 'csv':
fileName += '.csv';
mimeType = 'text/csv';
// Implementar exportaci贸n a CSV
break;
case 'json':
fileName += '.json';
mimeType = 'application/json';
// Implementar exportaci贸n a JSON
break;
case 'xml':
fileName += '.xml';
mimeType = 'application/xml';
// Implementar exportaci贸n a XML
break;
}
const blob = new Blob([data], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showAlert(`Datos exportados como ${format.toUpperCase()}`, "success");
}
function showAlert(message, type) {
// Implementar sistema de notificaciones
console.log(`${type}: ${message}`);
}
}); |