// 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 = `[Hoja: ${sheetName}]

`; // Encabezados html += 'Encabezados:
'; if (data[0]) { html += data[0].map(header => `    ${header || '(vacío)'}
` ).join(''); } // Datos de ejemplo html += '
Datos (primeras 5 filas):
'; const sampleRows = data.slice(1, 6); sampleRows.forEach((row, i) => { html += `  [Fila ${i + 1}]
`; row.forEach((cell, j) => { const header = data[0] ? data[0][j] : `Col${j+1}`; html += `    ${header}: ${cell || '(vacío)'}
`; }); }); if (data.length > 6) { html += `  ... y ${data.length - 6} filas más
`; } 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 = ` ${sheetName}!${header}${rowNum} ${cell || '(vacío)'} `; tableBody.appendChild(tr); }); }); if (rows.length > 100) { const tr = document.createElement('tr'); tr.innerHTML = ` Mostrando 100 de ${rows.length} filas `; 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}<${node.nodeName.toLowerCase()}`; // Atributos if (node.attributes && node.attributes.length > 0) { for (let attr of node.attributes) { html += ` ${attr.name}="${attr.value}"`; } } html += '>
'; // 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}    ${child.nodeValue.trim()}
`; } } if (hasElementChildren) { html += `${indentStr}`; } } // Cerrar etiqueta html += `</${node.nodeName.toLowerCase()}>
`; 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 = ''; 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 = ''; 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 = ``; actionCell.innerHTML = ''; 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 = ''; 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}`); } });