docs: implement Antigravity global rules
This commit is contained in:
@@ -1,402 +1,402 @@
|
||||
/**
|
||||
* CSV Manager UI
|
||||
* User interface for CRUD operations on CSV files
|
||||
*/
|
||||
|
||||
import {
|
||||
loadCSV,
|
||||
toCSV,
|
||||
downloadCSV,
|
||||
getAvailableCSVFiles,
|
||||
validateCSVData
|
||||
} from '../utils/csv-manager.js';
|
||||
|
||||
// Current state
|
||||
let currentCSVData = [];
|
||||
let currentFilename = '';
|
||||
let currentFileId = '';
|
||||
let editingIndex = -1;
|
||||
|
||||
/**
|
||||
* Open CSV Manager Modal
|
||||
*/
|
||||
export function openCSVManager() {
|
||||
const modal = document.getElementById('csvManagerModal');
|
||||
const select = document.getElementById('csvFileSelect');
|
||||
|
||||
// Populate file selector
|
||||
const files = getAvailableCSVFiles();
|
||||
select.innerHTML = '<option value="">-- Selecione um arquivo --</option>';
|
||||
files.forEach(file => {
|
||||
const option = document.createElement('option');
|
||||
option.value = file.id;
|
||||
option.textContent = `${file.icon} ${file.name} - ${file.description}`;
|
||||
select.appendChild(option);
|
||||
});
|
||||
|
||||
modal.classList.add('active');
|
||||
}
|
||||
|
||||
/**
|
||||
* Close CSV Manager Modal
|
||||
*/
|
||||
export function closeCSVManager() {
|
||||
const modal = document.getElementById('csvManagerModal');
|
||||
modal.classList.remove('active');
|
||||
|
||||
// Reset state
|
||||
currentCSVData = [];
|
||||
currentFilename = '';
|
||||
currentFileId = '';
|
||||
|
||||
// Reset UI
|
||||
document.getElementById('csvFileSelect').value = '';
|
||||
document.getElementById('csvContent').innerHTML = `
|
||||
<div style="text-align: center; padding: 60px 20px; color: var(--color-text-secondary);">
|
||||
<div style="font-size: 64px; margin-bottom: 16px;">📁</div>
|
||||
<p style="font-size: 18px; margin-bottom: 8px;">Selecione um arquivo CSV para começar</p>
|
||||
<p style="font-size: 14px;">Você poderá visualizar, editar, adicionar e remover registros</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Hide buttons
|
||||
document.getElementById('btnAddRecord').style.display = 'none';
|
||||
document.getElementById('btnDownload').style.display = 'none';
|
||||
}
|
||||
|
||||
/**
|
||||
* Load selected CSV file
|
||||
*/
|
||||
export async function loadSelectedCSV() {
|
||||
const select = document.getElementById('csvFileSelect');
|
||||
const fileId = select.value;
|
||||
|
||||
if (!fileId) {
|
||||
closeCSVManager();
|
||||
openCSVManager();
|
||||
return;
|
||||
}
|
||||
|
||||
const files = getAvailableCSVFiles();
|
||||
const file = files.find(f => f.id === fileId);
|
||||
|
||||
if (!file) return;
|
||||
|
||||
// Show loading
|
||||
document.getElementById('csvContent').innerHTML = `
|
||||
<div style="text-align: center; padding: 60px 20px;">
|
||||
<div style="font-size: 48px; margin-bottom: 16px;">⏳</div>
|
||||
<p style="font-size: 18px;">Carregando ${file.name}...</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
try {
|
||||
// Load CSV
|
||||
const data = await loadCSV(file.filename);
|
||||
|
||||
// Update state
|
||||
currentCSVData = data;
|
||||
currentFilename = file.filename;
|
||||
currentFileId = fileId;
|
||||
|
||||
// Render table
|
||||
renderCSVTable(data, file);
|
||||
|
||||
// Show buttons
|
||||
document.getElementById('btnAddRecord').style.display = 'inline-block';
|
||||
document.getElementById('btnDownload').style.display = 'inline-block';
|
||||
|
||||
} catch (error) {
|
||||
document.getElementById('csvContent').innerHTML = `
|
||||
<div style="text-align: center; padding: 60px 20px;">
|
||||
<div style="font-size: 48px; margin-bottom: 16px; color: var(--color-error);">❌</div>
|
||||
<p style="font-size: 18px; color: var(--color-error); margin-bottom: 8px;">Erro ao carregar arquivo</p>
|
||||
<p style="font-size: 14px; color: var(--color-text-secondary);">${error.message}</p>
|
||||
<button class="btn btn-primary" onclick="location.reload()" style="margin-top: 20px;">Recarregar Página</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render CSV data as table
|
||||
* @param {Array<object>} data - CSV data
|
||||
* @param {object} file - File metadata
|
||||
*/
|
||||
function renderCSVTable(data, file) {
|
||||
if (data.length === 0) {
|
||||
document.getElementById('csvContent').innerHTML = `
|
||||
<div style="text-align: center; padding: 60px 20px;">
|
||||
<div style="font-size: 48px; margin-bottom: 16px;">📭</div>
|
||||
<p style="font-size: 18px; margin-bottom: 8px;">Arquivo vazio</p>
|
||||
<p style="font-size: 14px; color: var(--color-text-secondary);">Adicione o primeiro registro</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = Object.keys(data[0]);
|
||||
|
||||
let html = `
|
||||
<div style="margin-bottom: 20px; padding: 16px; background: var(--color-bg-1); border-radius: 8px;">
|
||||
<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
|
||||
<span style="font-size: 32px;">${file.icon}</span>
|
||||
<div>
|
||||
<h3 style="margin: 0; font-size: 18px;">${file.name}</h3>
|
||||
<p style="margin: 0; font-size: 13px; color: var(--color-text-secondary);">${file.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display: flex; gap: 20px; margin-top: 12px; font-size: 13px; color: var(--color-text-secondary);">
|
||||
<span>📄 <strong>${data.length}</strong> registros</span>
|
||||
<span>📊 <strong>${headers.length}</strong> colunas</span>
|
||||
<span>💾 <strong>${currentFilename}</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-wrapper" style="overflow-x: auto;">
|
||||
<table style="width: 100%; border-collapse: collapse; font-size: 13px;">
|
||||
<thead>
|
||||
<tr style="background: var(--color-primary); color: white;">
|
||||
<th style="padding: 12px; text-align: left; position: sticky; left: 0; background: var(--color-primary);">#</th>
|
||||
${headers.map(h => `<th style="padding: 12px; text-align: left; white-space: nowrap;">${h}</th>`).join('')}
|
||||
<th style="padding: 12px; text-align: center; width: 120px;">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${data.map((row, index) => `
|
||||
<tr style="border-bottom: 1px solid var(--color-border); ${index % 2 === 0 ? 'background: var(--color-surface);' : ''}">
|
||||
<td style="padding: 12px; font-weight: bold; position: sticky; left: 0; background: ${index % 2 === 0 ? 'var(--color-surface)' : 'var(--color-background)'};">${index + 1}</td>
|
||||
${headers.map(h => `<td style="padding: 12px; white-space: nowrap;">${row[h] || '-'}</td>`).join('')}
|
||||
<td style="padding: 12px; text-align: center;">
|
||||
<button class="btn-icon-small" onclick="editRecord(${index})" title="Editar" style="background: var(--color-primary); color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; margin-right: 4px;">✏️</button>
|
||||
<button class="btn-icon-small" onclick="deleteRecord(${index})" title="Deletar" style="background: var(--color-error); color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer;">🗑️</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.getElementById('csvContent').innerHTML = html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add new record
|
||||
*/
|
||||
export function addNewRecord() {
|
||||
if (currentCSVData.length === 0) {
|
||||
alert('⚠️ Não é possível adicionar registro em arquivo vazio. Faça upload de um arquivo com estrutura.');
|
||||
return;
|
||||
}
|
||||
|
||||
editingIndex = -1;
|
||||
const headers = Object.keys(currentCSVData[0]);
|
||||
showRecordModal('➕ Adicionar Novo Registro', headers, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit existing record
|
||||
* @param {number} index - Record index
|
||||
*/
|
||||
export function editRecord(index) {
|
||||
editingIndex = index;
|
||||
const record = currentCSVData[index];
|
||||
const headers = Object.keys(record);
|
||||
showRecordModal(`✏️ Editar Registro #${index + 1}`, headers, record);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete record
|
||||
* @param {number} index - Record index
|
||||
*/
|
||||
export function deleteRecord(index) {
|
||||
const record = currentCSVData[index];
|
||||
const recordName = record.nome || record.id || `Registro #${index + 1}`;
|
||||
|
||||
if (!confirm(`🗑️ Tem certeza que deseja deletar:\n\n"${recordName}"?\n\nEsta ação não pode ser desfeita.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove from array
|
||||
currentCSVData.splice(index, 1);
|
||||
|
||||
// Re-render table
|
||||
const files = getAvailableCSVFiles();
|
||||
const file = files.find(f => f.id === currentFileId);
|
||||
renderCSVTable(currentCSVData, file);
|
||||
|
||||
// Show success message
|
||||
showToast('✅ Registro deletado com sucesso!', 'success');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show record editor modal
|
||||
* @param {string} title - Modal title
|
||||
* @param {Array<string>} headers - Field names
|
||||
* @param {object} data - Current data
|
||||
*/
|
||||
function showRecordModal(title, headers, data) {
|
||||
document.getElementById('recordModalTitle').textContent = title;
|
||||
|
||||
let html = '<div style="display: flex; flex-direction: column; gap: 16px;">';
|
||||
|
||||
headers.forEach(header => {
|
||||
const value = data[header] || '';
|
||||
html += `
|
||||
<div class="form-group" style="margin-bottom: 0;">
|
||||
<label class="form-label">${header}</label>
|
||||
<input
|
||||
type="text"
|
||||
class="form-control"
|
||||
id="field_${header}"
|
||||
value="${value}"
|
||||
placeholder="Digite ${header}"
|
||||
${header === 'id' ? 'required' : ''}
|
||||
>
|
||||
${header === 'id' ? '<small style="color: var(--color-text-secondary);">Campo obrigatório e único</small>' : ''}
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
html += '</div>';
|
||||
|
||||
document.getElementById('recordModalBody').innerHTML = html;
|
||||
document.getElementById('csvRecordModal').classList.add('active');
|
||||
}
|
||||
|
||||
/**
|
||||
* Close record editor modal
|
||||
*/
|
||||
export function closeRecordModal() {
|
||||
document.getElementById('csvRecordModal').classList.remove('active');
|
||||
editingIndex = -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save record (add or edit)
|
||||
*/
|
||||
export function saveRecord() {
|
||||
const headers = Object.keys(currentCSVData[0] || {});
|
||||
const newRecord = {};
|
||||
|
||||
// Collect form data
|
||||
headers.forEach(header => {
|
||||
const input = document.getElementById(`field_${header}`);
|
||||
if (input) {
|
||||
newRecord[header] = input.value.trim();
|
||||
}
|
||||
});
|
||||
|
||||
// Validate required fields
|
||||
if (!newRecord.id) {
|
||||
alert('⚠️ O campo "id" é obrigatório!');
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for duplicate ID (only when adding new)
|
||||
if (editingIndex === -1) {
|
||||
const duplicate = currentCSVData.find(r => r.id === newRecord.id);
|
||||
if (duplicate) {
|
||||
alert(`⚠️ Já existe um registro com o ID "${newRecord.id}"!\n\nEscolha um ID único.`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Add or update
|
||||
if (editingIndex === -1) {
|
||||
// Add new
|
||||
currentCSVData.push(newRecord);
|
||||
showToast('✅ Registro adicionado com sucesso!', 'success');
|
||||
} else {
|
||||
// Update existing
|
||||
currentCSVData[editingIndex] = newRecord;
|
||||
showToast('✅ Registro atualizado com sucesso!', 'success');
|
||||
}
|
||||
|
||||
// Re-render table
|
||||
const files = getAvailableCSVFiles();
|
||||
const file = files.find(f => f.id === currentFileId);
|
||||
renderCSVTable(currentCSVData, file);
|
||||
|
||||
// Close modal
|
||||
closeRecordModal();
|
||||
}
|
||||
|
||||
/**
|
||||
* Download current CSV
|
||||
*/
|
||||
export function downloadCurrentCSV() {
|
||||
if (currentCSVData.length === 0) {
|
||||
alert('⚠️ Não há dados para download!');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate data
|
||||
const validation = validateCSVData(currentCSVData);
|
||||
if (!validation.valid) {
|
||||
const proceed = confirm(`⚠️ Dados contêm erros:\n\n${validation.errors.join('\n')}\n\nDeseja fazer download mesmo assim?`);
|
||||
if (!proceed) return;
|
||||
}
|
||||
|
||||
// Convert to CSV
|
||||
const csvText = toCSV(currentCSVData);
|
||||
|
||||
// Download
|
||||
downloadCSV(currentFilename, csvText);
|
||||
|
||||
showToast('💾 CSV baixado com sucesso!', 'success');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show toast notification
|
||||
* @param {string} message - Message text
|
||||
* @param {string} type - Type (success, error, warning)
|
||||
*/
|
||||
function showToast(message, type = 'success') {
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast toast-${type}`;
|
||||
toast.textContent = message;
|
||||
toast.style.cssText = `
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
right: 24px;
|
||||
padding: 16px 24px;
|
||||
background: ${type === 'success' ? 'var(--color-success)' : 'var(--color-error)'};
|
||||
color: white;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
||||
z-index: 10000;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
transition: all 0.3s ease;
|
||||
`;
|
||||
|
||||
document.body.appendChild(toast);
|
||||
|
||||
setTimeout(() => {
|
||||
toast.style.opacity = '1';
|
||||
toast.style.transform = 'translateY(0)';
|
||||
}, 10);
|
||||
|
||||
setTimeout(() => {
|
||||
toast.style.opacity = '0';
|
||||
toast.style.transform = 'translateY(20px)';
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Export to global scope for onclick handlers
|
||||
if (typeof window !== 'undefined') {
|
||||
window.openCSVManager = openCSVManager;
|
||||
window.closeCSVManager = closeCSVManager;
|
||||
window.loadSelectedCSV = loadSelectedCSV;
|
||||
window.addNewRecord = addNewRecord;
|
||||
window.editRecord = editRecord;
|
||||
window.deleteRecord = deleteRecord;
|
||||
window.closeRecordModal = closeRecordModal;
|
||||
window.saveRecord = saveRecord;
|
||||
window.downloadCurrentCSV = downloadCurrentCSV;
|
||||
}
|
||||
/**
|
||||
* CSV Manager UI
|
||||
* User interface for CRUD operations on CSV files
|
||||
*/
|
||||
|
||||
import {
|
||||
loadCSV,
|
||||
toCSV,
|
||||
downloadCSV,
|
||||
getAvailableCSVFiles,
|
||||
validateCSVData
|
||||
} from '../utils/csv-manager.js';
|
||||
|
||||
// Current state
|
||||
let currentCSVData = [];
|
||||
let currentFilename = '';
|
||||
let currentFileId = '';
|
||||
let editingIndex = -1;
|
||||
|
||||
/**
|
||||
* Open CSV Manager Modal
|
||||
*/
|
||||
export function openCSVManager() {
|
||||
const modal = document.getElementById('csvManagerModal');
|
||||
const select = document.getElementById('csvFileSelect');
|
||||
|
||||
// Populate file selector
|
||||
const files = getAvailableCSVFiles();
|
||||
select.innerHTML = '<option value="">-- Selecione um arquivo --</option>';
|
||||
files.forEach(file => {
|
||||
const option = document.createElement('option');
|
||||
option.value = file.id;
|
||||
option.textContent = `${file.icon} ${file.name} - ${file.description}`;
|
||||
select.appendChild(option);
|
||||
});
|
||||
|
||||
modal.classList.add('active');
|
||||
}
|
||||
|
||||
/**
|
||||
* Close CSV Manager Modal
|
||||
*/
|
||||
export function closeCSVManager() {
|
||||
const modal = document.getElementById('csvManagerModal');
|
||||
modal.classList.remove('active');
|
||||
|
||||
// Reset state
|
||||
currentCSVData = [];
|
||||
currentFilename = '';
|
||||
currentFileId = '';
|
||||
|
||||
// Reset UI
|
||||
document.getElementById('csvFileSelect').value = '';
|
||||
document.getElementById('csvContent').innerHTML = `
|
||||
<div style="text-align: center; padding: 60px 20px; color: var(--color-text-secondary);">
|
||||
<div style="font-size: 64px; margin-bottom: 16px;">📁</div>
|
||||
<p style="font-size: 18px; margin-bottom: 8px;">Selecione um arquivo CSV para começar</p>
|
||||
<p style="font-size: 14px;">Você poderá visualizar, editar, adicionar e remover registros</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Hide buttons
|
||||
document.getElementById('btnAddRecord').style.display = 'none';
|
||||
document.getElementById('btnDownload').style.display = 'none';
|
||||
}
|
||||
|
||||
/**
|
||||
* Load selected CSV file
|
||||
*/
|
||||
export async function loadSelectedCSV() {
|
||||
const select = document.getElementById('csvFileSelect');
|
||||
const fileId = select.value;
|
||||
|
||||
if (!fileId) {
|
||||
closeCSVManager();
|
||||
openCSVManager();
|
||||
return;
|
||||
}
|
||||
|
||||
const files = getAvailableCSVFiles();
|
||||
const file = files.find(f => f.id === fileId);
|
||||
|
||||
if (!file) return;
|
||||
|
||||
// Show loading
|
||||
document.getElementById('csvContent').innerHTML = `
|
||||
<div style="text-align: center; padding: 60px 20px;">
|
||||
<div style="font-size: 48px; margin-bottom: 16px;">⏳</div>
|
||||
<p style="font-size: 18px;">Carregando ${file.name}...</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
try {
|
||||
// Load CSV
|
||||
const data = await loadCSV(file.filename);
|
||||
|
||||
// Update state
|
||||
currentCSVData = data;
|
||||
currentFilename = file.filename;
|
||||
currentFileId = fileId;
|
||||
|
||||
// Render table
|
||||
renderCSVTable(data, file);
|
||||
|
||||
// Show buttons
|
||||
document.getElementById('btnAddRecord').style.display = 'inline-block';
|
||||
document.getElementById('btnDownload').style.display = 'inline-block';
|
||||
|
||||
} catch (error) {
|
||||
document.getElementById('csvContent').innerHTML = `
|
||||
<div style="text-align: center; padding: 60px 20px;">
|
||||
<div style="font-size: 48px; margin-bottom: 16px; color: var(--color-error);">❌</div>
|
||||
<p style="font-size: 18px; color: var(--color-error); margin-bottom: 8px;">Erro ao carregar arquivo</p>
|
||||
<p style="font-size: 14px; color: var(--color-text-secondary);">${error.message}</p>
|
||||
<button class="btn btn-primary" onclick="location.reload()" style="margin-top: 20px;">Recarregar Página</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render CSV data as table
|
||||
* @param {Array<object>} data - CSV data
|
||||
* @param {object} file - File metadata
|
||||
*/
|
||||
function renderCSVTable(data, file) {
|
||||
if (data.length === 0) {
|
||||
document.getElementById('csvContent').innerHTML = `
|
||||
<div style="text-align: center; padding: 60px 20px;">
|
||||
<div style="font-size: 48px; margin-bottom: 16px;">📭</div>
|
||||
<p style="font-size: 18px; margin-bottom: 8px;">Arquivo vazio</p>
|
||||
<p style="font-size: 14px; color: var(--color-text-secondary);">Adicione o primeiro registro</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = Object.keys(data[0]);
|
||||
|
||||
let html = `
|
||||
<div style="margin-bottom: 20px; padding: 16px; background: var(--color-bg-1); border-radius: 8px;">
|
||||
<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
|
||||
<span style="font-size: 32px;">${file.icon}</span>
|
||||
<div>
|
||||
<h3 style="margin: 0; font-size: 18px;">${file.name}</h3>
|
||||
<p style="margin: 0; font-size: 13px; color: var(--color-text-secondary);">${file.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display: flex; gap: 20px; margin-top: 12px; font-size: 13px; color: var(--color-text-secondary);">
|
||||
<span>📄 <strong>${data.length}</strong> registros</span>
|
||||
<span>📊 <strong>${headers.length}</strong> colunas</span>
|
||||
<span>💾 <strong>${currentFilename}</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-wrapper" style="overflow-x: auto;">
|
||||
<table style="width: 100%; border-collapse: collapse; font-size: 13px;">
|
||||
<thead>
|
||||
<tr style="background: var(--color-primary); color: white;">
|
||||
<th style="padding: 12px; text-align: left; position: sticky; left: 0; background: var(--color-primary);">#</th>
|
||||
${headers.map(h => `<th style="padding: 12px; text-align: left; white-space: nowrap;">${h}</th>`).join('')}
|
||||
<th style="padding: 12px; text-align: center; width: 120px;">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${data.map((row, index) => `
|
||||
<tr style="border-bottom: 1px solid var(--color-border); ${index % 2 === 0 ? 'background: var(--color-surface);' : ''}">
|
||||
<td style="padding: 12px; font-weight: bold; position: sticky; left: 0; background: ${index % 2 === 0 ? 'var(--color-surface)' : 'var(--color-background)'};">${index + 1}</td>
|
||||
${headers.map(h => `<td style="padding: 12px; white-space: nowrap;">${row[h] || '-'}</td>`).join('')}
|
||||
<td style="padding: 12px; text-align: center;">
|
||||
<button class="btn-icon-small" onclick="editRecord(${index})" title="Editar" style="background: var(--color-primary); color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; margin-right: 4px;">✏️</button>
|
||||
<button class="btn-icon-small" onclick="deleteRecord(${index})" title="Deletar" style="background: var(--color-error); color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer;">🗑️</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.getElementById('csvContent').innerHTML = html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add new record
|
||||
*/
|
||||
export function addNewRecord() {
|
||||
if (currentCSVData.length === 0) {
|
||||
alert('⚠️ Não é possível adicionar registro em arquivo vazio. Faça upload de um arquivo com estrutura.');
|
||||
return;
|
||||
}
|
||||
|
||||
editingIndex = -1;
|
||||
const headers = Object.keys(currentCSVData[0]);
|
||||
showRecordModal('➕ Adicionar Novo Registro', headers, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit existing record
|
||||
* @param {number} index - Record index
|
||||
*/
|
||||
export function editRecord(index) {
|
||||
editingIndex = index;
|
||||
const record = currentCSVData[index];
|
||||
const headers = Object.keys(record);
|
||||
showRecordModal(`✏️ Editar Registro #${index + 1}`, headers, record);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete record
|
||||
* @param {number} index - Record index
|
||||
*/
|
||||
export function deleteRecord(index) {
|
||||
const record = currentCSVData[index];
|
||||
const recordName = record.nome || record.id || `Registro #${index + 1}`;
|
||||
|
||||
if (!confirm(`🗑️ Tem certeza que deseja deletar:\n\n"${recordName}"?\n\nEsta ação não pode ser desfeita.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove from array
|
||||
currentCSVData.splice(index, 1);
|
||||
|
||||
// Re-render table
|
||||
const files = getAvailableCSVFiles();
|
||||
const file = files.find(f => f.id === currentFileId);
|
||||
renderCSVTable(currentCSVData, file);
|
||||
|
||||
// Show success message
|
||||
showToast('✅ Registro deletado com sucesso!', 'success');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show record editor modal
|
||||
* @param {string} title - Modal title
|
||||
* @param {Array<string>} headers - Field names
|
||||
* @param {object} data - Current data
|
||||
*/
|
||||
function showRecordModal(title, headers, data) {
|
||||
document.getElementById('recordModalTitle').textContent = title;
|
||||
|
||||
let html = '<div style="display: flex; flex-direction: column; gap: 16px;">';
|
||||
|
||||
headers.forEach(header => {
|
||||
const value = data[header] || '';
|
||||
html += `
|
||||
<div class="form-group" style="margin-bottom: 0;">
|
||||
<label class="form-label">${header}</label>
|
||||
<input
|
||||
type="text"
|
||||
class="form-control"
|
||||
id="field_${header}"
|
||||
value="${value}"
|
||||
placeholder="Digite ${header}"
|
||||
${header === 'id' ? 'required' : ''}
|
||||
>
|
||||
${header === 'id' ? '<small style="color: var(--color-text-secondary);">Campo obrigatório e único</small>' : ''}
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
html += '</div>';
|
||||
|
||||
document.getElementById('recordModalBody').innerHTML = html;
|
||||
document.getElementById('csvRecordModal').classList.add('active');
|
||||
}
|
||||
|
||||
/**
|
||||
* Close record editor modal
|
||||
*/
|
||||
export function closeRecordModal() {
|
||||
document.getElementById('csvRecordModal').classList.remove('active');
|
||||
editingIndex = -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save record (add or edit)
|
||||
*/
|
||||
export function saveRecord() {
|
||||
const headers = Object.keys(currentCSVData[0] || {});
|
||||
const newRecord = {};
|
||||
|
||||
// Collect form data
|
||||
headers.forEach(header => {
|
||||
const input = document.getElementById(`field_${header}`);
|
||||
if (input) {
|
||||
newRecord[header] = input.value.trim();
|
||||
}
|
||||
});
|
||||
|
||||
// Validate required fields
|
||||
if (!newRecord.id) {
|
||||
alert('⚠️ O campo "id" é obrigatório!');
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for duplicate ID (only when adding new)
|
||||
if (editingIndex === -1) {
|
||||
const duplicate = currentCSVData.find(r => r.id === newRecord.id);
|
||||
if (duplicate) {
|
||||
alert(`⚠️ Já existe um registro com o ID "${newRecord.id}"!\n\nEscolha um ID único.`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Add or update
|
||||
if (editingIndex === -1) {
|
||||
// Add new
|
||||
currentCSVData.push(newRecord);
|
||||
showToast('✅ Registro adicionado com sucesso!', 'success');
|
||||
} else {
|
||||
// Update existing
|
||||
currentCSVData[editingIndex] = newRecord;
|
||||
showToast('✅ Registro atualizado com sucesso!', 'success');
|
||||
}
|
||||
|
||||
// Re-render table
|
||||
const files = getAvailableCSVFiles();
|
||||
const file = files.find(f => f.id === currentFileId);
|
||||
renderCSVTable(currentCSVData, file);
|
||||
|
||||
// Close modal
|
||||
closeRecordModal();
|
||||
}
|
||||
|
||||
/**
|
||||
* Download current CSV
|
||||
*/
|
||||
export function downloadCurrentCSV() {
|
||||
if (currentCSVData.length === 0) {
|
||||
alert('⚠️ Não há dados para download!');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate data
|
||||
const validation = validateCSVData(currentCSVData);
|
||||
if (!validation.valid) {
|
||||
const proceed = confirm(`⚠️ Dados contêm erros:\n\n${validation.errors.join('\n')}\n\nDeseja fazer download mesmo assim?`);
|
||||
if (!proceed) return;
|
||||
}
|
||||
|
||||
// Convert to CSV
|
||||
const csvText = toCSV(currentCSVData);
|
||||
|
||||
// Download
|
||||
downloadCSV(currentFilename, csvText);
|
||||
|
||||
showToast('💾 CSV baixado com sucesso!', 'success');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show toast notification
|
||||
* @param {string} message - Message text
|
||||
* @param {string} type - Type (success, error, warning)
|
||||
*/
|
||||
function showToast(message, type = 'success') {
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast toast-${type}`;
|
||||
toast.textContent = message;
|
||||
toast.style.cssText = `
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
right: 24px;
|
||||
padding: 16px 24px;
|
||||
background: ${type === 'success' ? 'var(--color-success)' : 'var(--color-error)'};
|
||||
color: white;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
||||
z-index: 10000;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
transition: all 0.3s ease;
|
||||
`;
|
||||
|
||||
document.body.appendChild(toast);
|
||||
|
||||
setTimeout(() => {
|
||||
toast.style.opacity = '1';
|
||||
toast.style.transform = 'translateY(0)';
|
||||
}, 10);
|
||||
|
||||
setTimeout(() => {
|
||||
toast.style.opacity = '0';
|
||||
toast.style.transform = 'translateY(20px)';
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Export to global scope for onclick handlers
|
||||
if (typeof window !== 'undefined') {
|
||||
window.openCSVManager = openCSVManager;
|
||||
window.closeCSVManager = closeCSVManager;
|
||||
window.loadSelectedCSV = loadSelectedCSV;
|
||||
window.addNewRecord = addNewRecord;
|
||||
window.editRecord = editRecord;
|
||||
window.deleteRecord = deleteRecord;
|
||||
window.closeRecordModal = closeRecordModal;
|
||||
window.saveRecord = saveRecord;
|
||||
window.downloadCurrentCSV = downloadCurrentCSV;
|
||||
}
|
||||
|
||||
@@ -1,184 +1,184 @@
|
||||
/**
|
||||
* Navigation System
|
||||
* Handles section switching and sidebar management
|
||||
*/
|
||||
|
||||
import { appState, updateState } from '../core/state.js';
|
||||
import { loadSection, showLoading, showError } from './section-loader.js';
|
||||
|
||||
/**
|
||||
* Show a section
|
||||
* @param {string} sectionId - Section identifier
|
||||
*/
|
||||
export async function showSection(sectionId) {
|
||||
console.log(`🔄 Navegando para: ${sectionId}`);
|
||||
|
||||
// Update state
|
||||
updateState('currentSection', sectionId);
|
||||
|
||||
// Update sidebar active state
|
||||
updateSidebarActive(sectionId);
|
||||
|
||||
// Show loading
|
||||
showLoading();
|
||||
|
||||
try {
|
||||
// Load section content
|
||||
const content = await loadSection(sectionId);
|
||||
|
||||
// Inject content
|
||||
const mainContent = document.getElementById('main-content');
|
||||
if (mainContent) {
|
||||
mainContent.innerHTML = content;
|
||||
}
|
||||
|
||||
// Add help button after content loads
|
||||
setTimeout(() => {
|
||||
if (typeof window.addHelpButton === 'function') {
|
||||
// For sections with tabs, show help for first tab
|
||||
if (sectionId === 'preaquecimento') {
|
||||
window.addHelpButton('preaquecimento');
|
||||
} else if (sectionId === 'parafusos') {
|
||||
window.addHelpButton('parafusos-cisalhamento');
|
||||
} else {
|
||||
window.addHelpButton(sectionId);
|
||||
}
|
||||
}
|
||||
}, 100);
|
||||
|
||||
// Scroll to top
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
|
||||
console.log(`✅ Seção ${sectionId} exibida`);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ Erro ao exibir seção ${sectionId}:`, error);
|
||||
showError('Erro ao carregar seção. Tente novamente.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update sidebar active state
|
||||
* @param {string} sectionId - Active section ID
|
||||
*/
|
||||
function updateSidebarActive(sectionId) {
|
||||
document.querySelectorAll('.sidebar-item').forEach(item => {
|
||||
const isActive = item.dataset.section === sectionId;
|
||||
item.classList.toggle('active', isActive);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch sidebar tab
|
||||
* @param {number} tabIndex - Tab index
|
||||
*/
|
||||
export function switchSidebarTab(tabIndex) {
|
||||
console.log(`🔄 Mudando para aba: ${tabIndex}`);
|
||||
|
||||
// Update state
|
||||
updateState('currentSidebarTab', tabIndex);
|
||||
|
||||
// Update tab buttons
|
||||
document.querySelectorAll('.sidebar-tab').forEach((tab, i) => {
|
||||
tab.classList.toggle('active', i === tabIndex);
|
||||
});
|
||||
|
||||
// Update tab content
|
||||
document.querySelectorAll('.sidebar-content').forEach((content, i) => {
|
||||
content.classList.toggle('active', i === tabIndex);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch tab within a section
|
||||
* @param {number} tabIndex - Tab index
|
||||
*/
|
||||
export function switchTab(tabIndex) {
|
||||
document.querySelectorAll('.tab-btn').forEach((btn, i) => {
|
||||
btn.classList.toggle('active', i === tabIndex);
|
||||
});
|
||||
document.querySelectorAll('.tab-content').forEach((content, i) => {
|
||||
content.classList.toggle('active', i === tabIndex);
|
||||
});
|
||||
|
||||
// Update help button for the active tab (for parafusos section)
|
||||
const tabIds = ['parafusos-cisalhamento', 'parafusos-esmagamento', 'parafusos-bloco', 'layout', 'parafuso-vs-solda'];
|
||||
if (tabIds[tabIndex] && typeof window.addHelpButton === 'function') {
|
||||
window.addHelpButton(tabIds[tabIndex]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch welding tab
|
||||
* @param {number} index - Tab index
|
||||
*/
|
||||
export function switchWeldTab(index) {
|
||||
document.querySelectorAll('.tabs-nav .tab-btn').forEach((btn, i) => {
|
||||
if (btn.textContent.includes('Pré-Aquecimento') || btn.textContent.includes('Filete') ||
|
||||
btn.textContent.includes('Energia') || btn.textContent.includes('Consumo') ||
|
||||
btn.textContent.includes('Sequência') || btn.textContent.includes('Padrões')) {
|
||||
btn.classList.toggle('active', i === index);
|
||||
}
|
||||
});
|
||||
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const tab = document.getElementById(`weld-tab-${i}`);
|
||||
if (tab) {
|
||||
tab.classList.toggle('active', i === index);
|
||||
}
|
||||
}
|
||||
|
||||
// Update help button for the active tab
|
||||
const tabIds = ['preaquecimento', 'filete', 'energia', 'consumo-eletrodo', 'sequencia-soldagem', 'padroes-soldagem'];
|
||||
if (typeof window.addHelpButton === 'function') {
|
||||
window.addHelpButton(tabIds[index]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to a specific tool/tab (used by global search)
|
||||
* @param {string} toolId - Tool identifier
|
||||
* @param {number|null} tabIndex - Optional tab index
|
||||
*/
|
||||
export async function navegarParaFerramenta(toolId, tabIndex) {
|
||||
// Close search modal if open
|
||||
if (typeof window.closeGlobalSearchModal === 'function') {
|
||||
window.closeGlobalSearchModal();
|
||||
}
|
||||
|
||||
// Determine which section to show
|
||||
let sectionId = toolId;
|
||||
|
||||
// Handle tabs within sections
|
||||
if (toolId.startsWith('parafusos-')) {
|
||||
sectionId = 'parafusos';
|
||||
} else if (['filete', 'energia', 'consumo-eletrodo', 'sequencia-soldagem', 'padroes-soldagem'].includes(toolId)) {
|
||||
sectionId = 'preaquecimento';
|
||||
}
|
||||
|
||||
// Show the section
|
||||
await showSection(sectionId);
|
||||
|
||||
// Switch to specific tab if needed
|
||||
setTimeout(() => {
|
||||
if (tabIndex !== null && tabIndex !== undefined) {
|
||||
if (sectionId === 'parafusos') {
|
||||
switchTab(tabIndex);
|
||||
} else if (sectionId === 'preaquecimento') {
|
||||
switchWeldTab(tabIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// Scroll to top
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}, 200);
|
||||
}
|
||||
|
||||
// Export to global scope for compatibility
|
||||
if (typeof window !== 'undefined') {
|
||||
window.showSection = showSection;
|
||||
window.switchSidebarTab = switchSidebarTab;
|
||||
window.switchTab = switchTab;
|
||||
window.switchWeldTab = switchWeldTab;
|
||||
window.navegarParaFerramenta = navegarParaFerramenta;
|
||||
}
|
||||
/**
|
||||
* Navigation System
|
||||
* Handles section switching and sidebar management
|
||||
*/
|
||||
|
||||
import { appState, updateState } from '../core/state.js';
|
||||
import { loadSection, showLoading, showError } from './section-loader.js';
|
||||
|
||||
/**
|
||||
* Show a section
|
||||
* @param {string} sectionId - Section identifier
|
||||
*/
|
||||
export async function showSection(sectionId) {
|
||||
console.log(`🔄 Navegando para: ${sectionId}`);
|
||||
|
||||
// Update state
|
||||
updateState('currentSection', sectionId);
|
||||
|
||||
// Update sidebar active state
|
||||
updateSidebarActive(sectionId);
|
||||
|
||||
// Show loading
|
||||
showLoading();
|
||||
|
||||
try {
|
||||
// Load section content
|
||||
const content = await loadSection(sectionId);
|
||||
|
||||
// Inject content
|
||||
const mainContent = document.getElementById('main-content');
|
||||
if (mainContent) {
|
||||
mainContent.innerHTML = content;
|
||||
}
|
||||
|
||||
// Add help button after content loads
|
||||
setTimeout(() => {
|
||||
if (typeof window.addHelpButton === 'function') {
|
||||
// For sections with tabs, show help for first tab
|
||||
if (sectionId === 'preaquecimento') {
|
||||
window.addHelpButton('preaquecimento');
|
||||
} else if (sectionId === 'parafusos') {
|
||||
window.addHelpButton('parafusos-cisalhamento');
|
||||
} else {
|
||||
window.addHelpButton(sectionId);
|
||||
}
|
||||
}
|
||||
}, 100);
|
||||
|
||||
// Scroll to top
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
|
||||
console.log(`✅ Seção ${sectionId} exibida`);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ Erro ao exibir seção ${sectionId}:`, error);
|
||||
showError('Erro ao carregar seção. Tente novamente.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update sidebar active state
|
||||
* @param {string} sectionId - Active section ID
|
||||
*/
|
||||
function updateSidebarActive(sectionId) {
|
||||
document.querySelectorAll('.sidebar-item').forEach(item => {
|
||||
const isActive = item.dataset.section === sectionId;
|
||||
item.classList.toggle('active', isActive);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch sidebar tab
|
||||
* @param {number} tabIndex - Tab index
|
||||
*/
|
||||
export function switchSidebarTab(tabIndex) {
|
||||
console.log(`🔄 Mudando para aba: ${tabIndex}`);
|
||||
|
||||
// Update state
|
||||
updateState('currentSidebarTab', tabIndex);
|
||||
|
||||
// Update tab buttons
|
||||
document.querySelectorAll('.sidebar-tab').forEach((tab, i) => {
|
||||
tab.classList.toggle('active', i === tabIndex);
|
||||
});
|
||||
|
||||
// Update tab content
|
||||
document.querySelectorAll('.sidebar-content').forEach((content, i) => {
|
||||
content.classList.toggle('active', i === tabIndex);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch tab within a section
|
||||
* @param {number} tabIndex - Tab index
|
||||
*/
|
||||
export function switchTab(tabIndex) {
|
||||
document.querySelectorAll('.tab-btn').forEach((btn, i) => {
|
||||
btn.classList.toggle('active', i === tabIndex);
|
||||
});
|
||||
document.querySelectorAll('.tab-content').forEach((content, i) => {
|
||||
content.classList.toggle('active', i === tabIndex);
|
||||
});
|
||||
|
||||
// Update help button for the active tab (for parafusos section)
|
||||
const tabIds = ['parafusos-cisalhamento', 'parafusos-esmagamento', 'parafusos-bloco', 'layout', 'parafuso-vs-solda'];
|
||||
if (tabIds[tabIndex] && typeof window.addHelpButton === 'function') {
|
||||
window.addHelpButton(tabIds[tabIndex]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch welding tab
|
||||
* @param {number} index - Tab index
|
||||
*/
|
||||
export function switchWeldTab(index) {
|
||||
document.querySelectorAll('.tabs-nav .tab-btn').forEach((btn, i) => {
|
||||
if (btn.textContent.includes('Pré-Aquecimento') || btn.textContent.includes('Filete') ||
|
||||
btn.textContent.includes('Energia') || btn.textContent.includes('Consumo') ||
|
||||
btn.textContent.includes('Sequência') || btn.textContent.includes('Padrões')) {
|
||||
btn.classList.toggle('active', i === index);
|
||||
}
|
||||
});
|
||||
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const tab = document.getElementById(`weld-tab-${i}`);
|
||||
if (tab) {
|
||||
tab.classList.toggle('active', i === index);
|
||||
}
|
||||
}
|
||||
|
||||
// Update help button for the active tab
|
||||
const tabIds = ['preaquecimento', 'filete', 'energia', 'consumo-eletrodo', 'sequencia-soldagem', 'padroes-soldagem'];
|
||||
if (typeof window.addHelpButton === 'function') {
|
||||
window.addHelpButton(tabIds[index]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to a specific tool/tab (used by global search)
|
||||
* @param {string} toolId - Tool identifier
|
||||
* @param {number|null} tabIndex - Optional tab index
|
||||
*/
|
||||
export async function navegarParaFerramenta(toolId, tabIndex) {
|
||||
// Close search modal if open
|
||||
if (typeof window.closeGlobalSearchModal === 'function') {
|
||||
window.closeGlobalSearchModal();
|
||||
}
|
||||
|
||||
// Determine which section to show
|
||||
let sectionId = toolId;
|
||||
|
||||
// Handle tabs within sections
|
||||
if (toolId.startsWith('parafusos-')) {
|
||||
sectionId = 'parafusos';
|
||||
} else if (['filete', 'energia', 'consumo-eletrodo', 'sequencia-soldagem', 'padroes-soldagem'].includes(toolId)) {
|
||||
sectionId = 'preaquecimento';
|
||||
}
|
||||
|
||||
// Show the section
|
||||
await showSection(sectionId);
|
||||
|
||||
// Switch to specific tab if needed
|
||||
setTimeout(() => {
|
||||
if (tabIndex !== null && tabIndex !== undefined) {
|
||||
if (sectionId === 'parafusos') {
|
||||
switchTab(tabIndex);
|
||||
} else if (sectionId === 'preaquecimento') {
|
||||
switchWeldTab(tabIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// Scroll to top
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}, 200);
|
||||
}
|
||||
|
||||
// Export to global scope for compatibility
|
||||
if (typeof window !== 'undefined') {
|
||||
window.showSection = showSection;
|
||||
window.switchSidebarTab = switchSidebarTab;
|
||||
window.switchTab = switchTab;
|
||||
window.switchWeldTab = switchWeldTab;
|
||||
window.navegarParaFerramenta = navegarParaFerramenta;
|
||||
}
|
||||
|
||||
@@ -1,238 +1,238 @@
|
||||
/**
|
||||
* Section Loader - Dynamic content loading with lazy loading
|
||||
* Loads sections on-demand to improve initial load time
|
||||
*/
|
||||
|
||||
// Cache for loaded sections
|
||||
const sectionCache = new Map();
|
||||
|
||||
// Loading state
|
||||
let isLoading = false;
|
||||
|
||||
/**
|
||||
* Load section content dynamically
|
||||
* @param {string} sectionId - Section identifier
|
||||
* @returns {Promise<string>} Section HTML content
|
||||
*/
|
||||
export async function loadSection(sectionId) {
|
||||
// Check cache first
|
||||
if (sectionCache.has(sectionId)) {
|
||||
console.log(`📦 Carregando ${sectionId} do cache`);
|
||||
return sectionCache.get(sectionId);
|
||||
}
|
||||
|
||||
// Prevent concurrent loads
|
||||
if (isLoading) {
|
||||
console.warn('⚠️ Já está carregando uma seção');
|
||||
return '';
|
||||
}
|
||||
|
||||
isLoading = true;
|
||||
|
||||
try {
|
||||
console.log(`⏳ Carregando seção: ${sectionId}`);
|
||||
|
||||
// Map section to content function
|
||||
const content = await getSectionContent(sectionId);
|
||||
|
||||
// Cache the content
|
||||
sectionCache.set(sectionId, content);
|
||||
|
||||
console.log(`✅ Seção ${sectionId} carregada`);
|
||||
return content;
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ Erro ao carregar seção ${sectionId}:`, error);
|
||||
return `<div class="error-message">Erro ao carregar seção. Tente novamente.</div>`;
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get section content from global functions
|
||||
* This maintains compatibility with existing code
|
||||
* @param {string} sectionId - Section identifier
|
||||
* @returns {Promise<string>} Section HTML
|
||||
*/
|
||||
async function getSectionContent(sectionId) {
|
||||
// Map of section IDs to their content functions
|
||||
const sectionMap = {
|
||||
// MATERIAIS - Aços Estruturais
|
||||
'cev': 'getCEVContent',
|
||||
'seletor': 'getSeletorContent',
|
||||
'equivalencias': 'getEquivalenciasContent',
|
||||
'comparativo': 'getComparativoContent',
|
||||
'assistente-inteligente': 'getAssistenteInteligenteContent',
|
||||
|
||||
// MATERIAIS - Consumíveis de Soldagem
|
||||
'eletrodos': 'getEletrodosContent',
|
||||
'arames': 'getAramesContent',
|
||||
'fluxos': 'getFluxosContent',
|
||||
'gases': 'getGasesContent',
|
||||
|
||||
// MATERIAIS - Fixadores
|
||||
'parafusos-catalogo': 'getParafusosCatalogoContent',
|
||||
'porcas': 'getPorcasContent',
|
||||
'arruelas': 'getArruelasContent',
|
||||
'chumbadores': 'getChumbadoresContent',
|
||||
|
||||
// MATERIAIS - Tintas e Revestimentos
|
||||
'tintas-catalogo': 'getTintasCatalogoContent',
|
||||
'sistemas-pintura': 'getSistemasPinturaContent',
|
||||
'abrasivos': 'getAbrasivosContent',
|
||||
'granalha': 'getGranalhaContent',
|
||||
|
||||
// MATERIAIS - Elementos Complementares
|
||||
'telhas': 'getTelhasContent',
|
||||
'paineis': 'getPaineisContent',
|
||||
'steel-deck': 'getSteelDeckContent',
|
||||
'perfis-formados': 'getPerfisFormadosContent',
|
||||
|
||||
// MATERIAIS - Catálogo de Perfis (novos)
|
||||
'cantoneiras': 'getCantoneirasContent',
|
||||
'barras-redondas': 'getBarrasRedondasContent',
|
||||
'tubos-circulares': 'getTubosCircularesContent',
|
||||
'perfis-i': 'getPerfisIContent',
|
||||
'perfis-w': 'getPerfisWContent',
|
||||
'tubos-rhs': 'getTubosRHSContent',
|
||||
'chapas': 'getChapasContent',
|
||||
'perfis-hp': 'getPerfisHPContent',
|
||||
'barras-roscadas': 'getBarrasRoscadasContent',
|
||||
'barras-chatas': 'getBarrasChatasContent',
|
||||
|
||||
// CONEXÕES
|
||||
'parafusos': 'getParafusosContent',
|
||||
'layout': 'getLayoutContent',
|
||||
'parafuso-vs-solda': 'getParafusoVsSoldaContent',
|
||||
|
||||
// SOLDAGEM
|
||||
'preaquecimento': 'getPreaquecimentoContent',
|
||||
'solda-filete': 'getSoldaFileteContent',
|
||||
'energia-soldagem': 'getEnergiaSoldagemContent',
|
||||
'consumo-eletrodos': 'getConsumoEletrodosContent',
|
||||
|
||||
// ENSAIOS
|
||||
'dureza': 'getDurezaContent',
|
||||
'charpy': 'getCharpyContent',
|
||||
'certificado': 'getCertificadoContent',
|
||||
'ultrassom': 'getUltrassomContent',
|
||||
|
||||
// PINTURA
|
||||
'area-pintura': 'getAreaPinturaContent',
|
||||
'consumo-tinta': 'getConsumoTintaContent',
|
||||
'galvanizacao': 'getGalvanizacaoContent',
|
||||
'custo-pintura': 'getCustoPinturaContent',
|
||||
'secagem': 'getSecagemContent',
|
||||
'inspecao-pintura': 'getInspecaoPinturaContent',
|
||||
|
||||
// ORÇAMENTO
|
||||
'orcamento': 'getOrcamentoContent',
|
||||
'peso-rigging': 'getPesoRiggingContent',
|
||||
'referencia': 'getReferenciaContent'
|
||||
};
|
||||
|
||||
const functionName = sectionMap[sectionId];
|
||||
|
||||
if (!functionName) {
|
||||
throw new Error(`Seção não encontrada: ${sectionId}`);
|
||||
}
|
||||
|
||||
// Check if function exists in global scope
|
||||
if (typeof window[functionName] !== 'function') {
|
||||
throw new Error(`Função não encontrada: ${functionName}`);
|
||||
}
|
||||
|
||||
// Call the function and return content
|
||||
return window[functionName]();
|
||||
}
|
||||
|
||||
/**
|
||||
* Preload sections for faster navigation
|
||||
* @param {string[]} sectionIds - Array of section IDs to preload
|
||||
*/
|
||||
export async function preloadSections(sectionIds) {
|
||||
console.log('🔄 Pré-carregando seções:', sectionIds);
|
||||
|
||||
const promises = sectionIds.map(id => loadSection(id));
|
||||
|
||||
try {
|
||||
await Promise.all(promises);
|
||||
console.log('✅ Seções pré-carregadas');
|
||||
} catch (error) {
|
||||
console.warn('⚠️ Erro ao pré-carregar seções:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear section cache
|
||||
* @param {string} sectionId - Optional section ID to clear, or all if not provided
|
||||
*/
|
||||
export function clearCache(sectionId = null) {
|
||||
if (sectionId) {
|
||||
sectionCache.delete(sectionId);
|
||||
console.log(`🗑️ Cache limpo: ${sectionId}`);
|
||||
} else {
|
||||
sectionCache.clear();
|
||||
console.log('🗑️ Todo cache limpo');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache statistics
|
||||
* @returns {object} Cache stats
|
||||
*/
|
||||
export function getCacheStats() {
|
||||
return {
|
||||
size: sectionCache.size,
|
||||
sections: Array.from(sectionCache.keys()),
|
||||
memoryEstimate: estimateCacheSize()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate cache size in bytes
|
||||
* @returns {number} Estimated size
|
||||
*/
|
||||
function estimateCacheSize() {
|
||||
let size = 0;
|
||||
for (const content of sectionCache.values()) {
|
||||
size += new Blob([content]).size;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show loading indicator
|
||||
*/
|
||||
export function showLoading() {
|
||||
const content = document.getElementById('main-content');
|
||||
if (content) {
|
||||
content.innerHTML = `
|
||||
<div style="display: flex; align-items: center; justify-content: center; min-height: 400px; flex-direction: column; gap: 16px;">
|
||||
<div style="font-size: 48px;">⏳</div>
|
||||
<div style="font-size: 18px; color: var(--color-text-secondary);">Carregando...</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show error message
|
||||
* @param {string} message - Error message
|
||||
*/
|
||||
export function showError(message) {
|
||||
const content = document.getElementById('main-content');
|
||||
if (content) {
|
||||
content.innerHTML = `
|
||||
<div class="card" style="background: var(--color-bg-4); border-color: var(--color-error);">
|
||||
<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
|
||||
<span style="font-size: 32px;">❌</span>
|
||||
<h3 style="margin: 0; color: var(--color-error);">Erro</h3>
|
||||
</div>
|
||||
<p>${message}</p>
|
||||
<button class="btn btn-primary" onclick="location.reload()">Recarregar Página</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Section Loader - Dynamic content loading with lazy loading
|
||||
* Loads sections on-demand to improve initial load time
|
||||
*/
|
||||
|
||||
// Cache for loaded sections
|
||||
const sectionCache = new Map();
|
||||
|
||||
// Loading state
|
||||
let isLoading = false;
|
||||
|
||||
/**
|
||||
* Load section content dynamically
|
||||
* @param {string} sectionId - Section identifier
|
||||
* @returns {Promise<string>} Section HTML content
|
||||
*/
|
||||
export async function loadSection(sectionId) {
|
||||
// Check cache first
|
||||
if (sectionCache.has(sectionId)) {
|
||||
console.log(`📦 Carregando ${sectionId} do cache`);
|
||||
return sectionCache.get(sectionId);
|
||||
}
|
||||
|
||||
// Prevent concurrent loads
|
||||
if (isLoading) {
|
||||
console.warn('⚠️ Já está carregando uma seção');
|
||||
return '';
|
||||
}
|
||||
|
||||
isLoading = true;
|
||||
|
||||
try {
|
||||
console.log(`⏳ Carregando seção: ${sectionId}`);
|
||||
|
||||
// Map section to content function
|
||||
const content = await getSectionContent(sectionId);
|
||||
|
||||
// Cache the content
|
||||
sectionCache.set(sectionId, content);
|
||||
|
||||
console.log(`✅ Seção ${sectionId} carregada`);
|
||||
return content;
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ Erro ao carregar seção ${sectionId}:`, error);
|
||||
return `<div class="error-message">Erro ao carregar seção. Tente novamente.</div>`;
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get section content from global functions
|
||||
* This maintains compatibility with existing code
|
||||
* @param {string} sectionId - Section identifier
|
||||
* @returns {Promise<string>} Section HTML
|
||||
*/
|
||||
async function getSectionContent(sectionId) {
|
||||
// Map of section IDs to their content functions
|
||||
const sectionMap = {
|
||||
// MATERIAIS - Aços Estruturais
|
||||
'cev': 'getCEVContent',
|
||||
'seletor': 'getSeletorContent',
|
||||
'equivalencias': 'getEquivalenciasContent',
|
||||
'comparativo': 'getComparativoContent',
|
||||
'assistente-inteligente': 'getAssistenteInteligenteContent',
|
||||
|
||||
// MATERIAIS - Consumíveis de Soldagem
|
||||
'eletrodos': 'getEletrodosContent',
|
||||
'arames': 'getAramesContent',
|
||||
'fluxos': 'getFluxosContent',
|
||||
'gases': 'getGasesContent',
|
||||
|
||||
// MATERIAIS - Fixadores
|
||||
'parafusos-catalogo': 'getParafusosCatalogoContent',
|
||||
'porcas': 'getPorcasContent',
|
||||
'arruelas': 'getArruelasContent',
|
||||
'chumbadores': 'getChumbadoresContent',
|
||||
|
||||
// MATERIAIS - Tintas e Revestimentos
|
||||
'tintas-catalogo': 'getTintasCatalogoContent',
|
||||
'sistemas-pintura': 'getSistemasPinturaContent',
|
||||
'abrasivos': 'getAbrasivosContent',
|
||||
'granalha': 'getGranalhaContent',
|
||||
|
||||
// MATERIAIS - Elementos Complementares
|
||||
'telhas': 'getTelhasContent',
|
||||
'paineis': 'getPaineisContent',
|
||||
'steel-deck': 'getSteelDeckContent',
|
||||
'perfis-formados': 'getPerfisFormadosContent',
|
||||
|
||||
// MATERIAIS - Catálogo de Perfis (novos)
|
||||
'cantoneiras': 'getCantoneirasContent',
|
||||
'barras-redondas': 'getBarrasRedondasContent',
|
||||
'tubos-circulares': 'getTubosCircularesContent',
|
||||
'perfis-i': 'getPerfisIContent',
|
||||
'perfis-w': 'getPerfisWContent',
|
||||
'tubos-rhs': 'getTubosRHSContent',
|
||||
'chapas': 'getChapasContent',
|
||||
'perfis-hp': 'getPerfisHPContent',
|
||||
'barras-roscadas': 'getBarrasRoscadasContent',
|
||||
'barras-chatas': 'getBarrasChatasContent',
|
||||
|
||||
// CONEXÕES
|
||||
'parafusos': 'getParafusosContent',
|
||||
'layout': 'getLayoutContent',
|
||||
'parafuso-vs-solda': 'getParafusoVsSoldaContent',
|
||||
|
||||
// SOLDAGEM
|
||||
'preaquecimento': 'getPreaquecimentoContent',
|
||||
'solda-filete': 'getSoldaFileteContent',
|
||||
'energia-soldagem': 'getEnergiaSoldagemContent',
|
||||
'consumo-eletrodos': 'getConsumoEletrodosContent',
|
||||
|
||||
// ENSAIOS
|
||||
'dureza': 'getDurezaContent',
|
||||
'charpy': 'getCharpyContent',
|
||||
'certificado': 'getCertificadoContent',
|
||||
'ultrassom': 'getUltrassomContent',
|
||||
|
||||
// PINTURA
|
||||
'area-pintura': 'getAreaPinturaContent',
|
||||
'consumo-tinta': 'getConsumoTintaContent',
|
||||
'galvanizacao': 'getGalvanizacaoContent',
|
||||
'custo-pintura': 'getCustoPinturaContent',
|
||||
'secagem': 'getSecagemContent',
|
||||
'inspecao-pintura': 'getInspecaoPinturaContent',
|
||||
|
||||
// ORÇAMENTO
|
||||
'orcamento': 'getOrcamentoContent',
|
||||
'peso-rigging': 'getPesoRiggingContent',
|
||||
'referencia': 'getReferenciaContent'
|
||||
};
|
||||
|
||||
const functionName = sectionMap[sectionId];
|
||||
|
||||
if (!functionName) {
|
||||
throw new Error(`Seção não encontrada: ${sectionId}`);
|
||||
}
|
||||
|
||||
// Check if function exists in global scope
|
||||
if (typeof window[functionName] !== 'function') {
|
||||
throw new Error(`Função não encontrada: ${functionName}`);
|
||||
}
|
||||
|
||||
// Call the function and return content
|
||||
return window[functionName]();
|
||||
}
|
||||
|
||||
/**
|
||||
* Preload sections for faster navigation
|
||||
* @param {string[]} sectionIds - Array of section IDs to preload
|
||||
*/
|
||||
export async function preloadSections(sectionIds) {
|
||||
console.log('🔄 Pré-carregando seções:', sectionIds);
|
||||
|
||||
const promises = sectionIds.map(id => loadSection(id));
|
||||
|
||||
try {
|
||||
await Promise.all(promises);
|
||||
console.log('✅ Seções pré-carregadas');
|
||||
} catch (error) {
|
||||
console.warn('⚠️ Erro ao pré-carregar seções:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear section cache
|
||||
* @param {string} sectionId - Optional section ID to clear, or all if not provided
|
||||
*/
|
||||
export function clearCache(sectionId = null) {
|
||||
if (sectionId) {
|
||||
sectionCache.delete(sectionId);
|
||||
console.log(`🗑️ Cache limpo: ${sectionId}`);
|
||||
} else {
|
||||
sectionCache.clear();
|
||||
console.log('🗑️ Todo cache limpo');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache statistics
|
||||
* @returns {object} Cache stats
|
||||
*/
|
||||
export function getCacheStats() {
|
||||
return {
|
||||
size: sectionCache.size,
|
||||
sections: Array.from(sectionCache.keys()),
|
||||
memoryEstimate: estimateCacheSize()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate cache size in bytes
|
||||
* @returns {number} Estimated size
|
||||
*/
|
||||
function estimateCacheSize() {
|
||||
let size = 0;
|
||||
for (const content of sectionCache.values()) {
|
||||
size += new Blob([content]).size;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show loading indicator
|
||||
*/
|
||||
export function showLoading() {
|
||||
const content = document.getElementById('main-content');
|
||||
if (content) {
|
||||
content.innerHTML = `
|
||||
<div style="display: flex; align-items: center; justify-content: center; min-height: 400px; flex-direction: column; gap: 16px;">
|
||||
<div style="font-size: 48px;">⏳</div>
|
||||
<div style="font-size: 18px; color: var(--color-text-secondary);">Carregando...</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show error message
|
||||
* @param {string} message - Error message
|
||||
*/
|
||||
export function showError(message) {
|
||||
const content = document.getElementById('main-content');
|
||||
if (content) {
|
||||
content.innerHTML = `
|
||||
<div class="card" style="background: var(--color-bg-4); border-color: var(--color-error);">
|
||||
<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
|
||||
<span style="font-size: 32px;">❌</span>
|
||||
<h3 style="margin: 0; color: var(--color-error);">Erro</h3>
|
||||
</div>
|
||||
<p>${message}</p>
|
||||
<button class="btn btn-primary" onclick="location.reload()">Recarregar Página</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,129 +1,129 @@
|
||||
/**
|
||||
* Theme Management
|
||||
* Handles dark/light mode and visual customization
|
||||
*/
|
||||
|
||||
import { appState, userPreferences, updateState, updatePreference } from '../core/state.js';
|
||||
import { savePreferences } from '../core/storage.js';
|
||||
|
||||
/**
|
||||
* Toggle between dark and light theme
|
||||
*/
|
||||
export function toggleTheme() {
|
||||
const newTheme = appState.currentTheme === 'dark' ? 'light' : 'dark';
|
||||
updateState('currentTheme', newTheme);
|
||||
updatePreference('theme', newTheme);
|
||||
savePreferences();
|
||||
applyTheme();
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply current theme to document
|
||||
*/
|
||||
export function applyTheme() {
|
||||
const theme = appState.currentTheme;
|
||||
|
||||
// Apply theme attributes
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
document.documentElement.setAttribute('data-color-scheme', theme);
|
||||
|
||||
// Update theme toggle button
|
||||
const btn = document.getElementById('theme-toggle');
|
||||
if (btn) {
|
||||
btn.textContent = theme === 'dark' ? '☀️ Claro' : '🌙 Escuro';
|
||||
btn.classList.toggle('light', theme === 'light');
|
||||
}
|
||||
|
||||
console.log(`🎨 Tema aplicado: ${theme}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply all user preferences (theme, colors, fonts)
|
||||
*/
|
||||
export function applyUserPreferences() {
|
||||
// Apply theme
|
||||
updateState('currentTheme', userPreferences.theme);
|
||||
applyTheme();
|
||||
|
||||
// Apply color scheme variant
|
||||
document.documentElement.setAttribute('data-color-scheme-variant', userPreferences.colorScheme);
|
||||
|
||||
// Apply font size
|
||||
document.documentElement.setAttribute('data-font-size', userPreferences.fontSize);
|
||||
|
||||
// Apply font family
|
||||
document.documentElement.setAttribute('data-font-family', userPreferences.fontFamily);
|
||||
|
||||
console.log('🎨 Preferências aplicadas:', userPreferences);
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview color scheme (used in admin panel)
|
||||
* @param {string} scheme - Color scheme name
|
||||
*/
|
||||
export function previewColorScheme(scheme) {
|
||||
updatePreference('colorScheme', scheme);
|
||||
applyUserPreferences();
|
||||
savePreferences();
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview font size (used in admin panel)
|
||||
* @param {string} size - Font size name
|
||||
*/
|
||||
export function previewFontSize(size) {
|
||||
updatePreference('fontSize', size);
|
||||
applyUserPreferences();
|
||||
savePreferences();
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview font family (used in admin panel)
|
||||
* @param {string} family - Font family name
|
||||
*/
|
||||
export function previewFontFamily(family) {
|
||||
updatePreference('fontFamily', family);
|
||||
applyUserPreferences();
|
||||
savePreferences();
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle expert mode
|
||||
*/
|
||||
export function toggleExpertMode() {
|
||||
const newMode = !appState.expertMode;
|
||||
updateState('expertMode', newMode);
|
||||
|
||||
document.documentElement.classList.toggle('expert-mode', newMode);
|
||||
|
||||
// Update header toggle if it exists (legacy)
|
||||
const headerBtn = document.getElementById('expert-toggle');
|
||||
if (headerBtn) {
|
||||
headerBtn.textContent = newMode ? '🔬 Expert' : '🎯 Simples';
|
||||
headerBtn.classList.toggle('active', newMode);
|
||||
}
|
||||
// Update Admin panel toggle if present
|
||||
const adminBtn = document.getElementById('adminExpertToggle');
|
||||
if (adminBtn) {
|
||||
adminBtn.classList.toggle('active', newMode);
|
||||
adminBtn.textContent = newMode ? '🔬 Expert Ativo' : '🎯 Alternar Expert';
|
||||
}
|
||||
|
||||
// Filter tools by mode
|
||||
if (typeof window.filterToolsByMode === 'function') {
|
||||
window.filterToolsByMode();
|
||||
}
|
||||
|
||||
console.log(`🎯 Modo expert: ${newMode ? 'ativado' : 'desativado'}`);
|
||||
}
|
||||
|
||||
// Export to global scope for compatibility
|
||||
if (typeof window !== 'undefined') {
|
||||
window.toggleTheme = toggleTheme;
|
||||
window.applyTheme = applyTheme;
|
||||
window.applyUserPreferences = applyUserPreferences;
|
||||
window.previewColorScheme = previewColorScheme;
|
||||
window.previewFontSize = previewFontSize;
|
||||
window.previewFontFamily = previewFontFamily;
|
||||
window.toggleExpertMode = toggleExpertMode;
|
||||
}
|
||||
/**
|
||||
* Theme Management
|
||||
* Handles dark/light mode and visual customization
|
||||
*/
|
||||
|
||||
import { appState, userPreferences, updateState, updatePreference } from '../core/state.js';
|
||||
import { savePreferences } from '../core/storage.js';
|
||||
|
||||
/**
|
||||
* Toggle between dark and light theme
|
||||
*/
|
||||
export function toggleTheme() {
|
||||
const newTheme = appState.currentTheme === 'dark' ? 'light' : 'dark';
|
||||
updateState('currentTheme', newTheme);
|
||||
updatePreference('theme', newTheme);
|
||||
savePreferences();
|
||||
applyTheme();
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply current theme to document
|
||||
*/
|
||||
export function applyTheme() {
|
||||
const theme = appState.currentTheme;
|
||||
|
||||
// Apply theme attributes
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
document.documentElement.setAttribute('data-color-scheme', theme);
|
||||
|
||||
// Update theme toggle button
|
||||
const btn = document.getElementById('theme-toggle');
|
||||
if (btn) {
|
||||
btn.textContent = theme === 'dark' ? '☀️ Claro' : '🌙 Escuro';
|
||||
btn.classList.toggle('light', theme === 'light');
|
||||
}
|
||||
|
||||
console.log(`🎨 Tema aplicado: ${theme}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply all user preferences (theme, colors, fonts)
|
||||
*/
|
||||
export function applyUserPreferences() {
|
||||
// Apply theme
|
||||
updateState('currentTheme', userPreferences.theme);
|
||||
applyTheme();
|
||||
|
||||
// Apply color scheme variant
|
||||
document.documentElement.setAttribute('data-color-scheme-variant', userPreferences.colorScheme);
|
||||
|
||||
// Apply font size
|
||||
document.documentElement.setAttribute('data-font-size', userPreferences.fontSize);
|
||||
|
||||
// Apply font family
|
||||
document.documentElement.setAttribute('data-font-family', userPreferences.fontFamily);
|
||||
|
||||
console.log('🎨 Preferências aplicadas:', userPreferences);
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview color scheme (used in admin panel)
|
||||
* @param {string} scheme - Color scheme name
|
||||
*/
|
||||
export function previewColorScheme(scheme) {
|
||||
updatePreference('colorScheme', scheme);
|
||||
applyUserPreferences();
|
||||
savePreferences();
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview font size (used in admin panel)
|
||||
* @param {string} size - Font size name
|
||||
*/
|
||||
export function previewFontSize(size) {
|
||||
updatePreference('fontSize', size);
|
||||
applyUserPreferences();
|
||||
savePreferences();
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview font family (used in admin panel)
|
||||
* @param {string} family - Font family name
|
||||
*/
|
||||
export function previewFontFamily(family) {
|
||||
updatePreference('fontFamily', family);
|
||||
applyUserPreferences();
|
||||
savePreferences();
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle expert mode
|
||||
*/
|
||||
export function toggleExpertMode() {
|
||||
const newMode = !appState.expertMode;
|
||||
updateState('expertMode', newMode);
|
||||
|
||||
document.documentElement.classList.toggle('expert-mode', newMode);
|
||||
|
||||
// Update header toggle if it exists (legacy)
|
||||
const headerBtn = document.getElementById('expert-toggle');
|
||||
if (headerBtn) {
|
||||
headerBtn.textContent = newMode ? '🔬 Expert' : '🎯 Simples';
|
||||
headerBtn.classList.toggle('active', newMode);
|
||||
}
|
||||
// Update Admin panel toggle if present
|
||||
const adminBtn = document.getElementById('adminExpertToggle');
|
||||
if (adminBtn) {
|
||||
adminBtn.classList.toggle('active', newMode);
|
||||
adminBtn.textContent = newMode ? '🔬 Expert Ativo' : '🎯 Alternar Expert';
|
||||
}
|
||||
|
||||
// Filter tools by mode
|
||||
if (typeof window.filterToolsByMode === 'function') {
|
||||
window.filterToolsByMode();
|
||||
}
|
||||
|
||||
console.log(`🎯 Modo expert: ${newMode ? 'ativado' : 'desativado'}`);
|
||||
}
|
||||
|
||||
// Export to global scope for compatibility
|
||||
if (typeof window !== 'undefined') {
|
||||
window.toggleTheme = toggleTheme;
|
||||
window.applyTheme = applyTheme;
|
||||
window.applyUserPreferences = applyUserPreferences;
|
||||
window.previewColorScheme = previewColorScheme;
|
||||
window.previewFontSize = previewFontSize;
|
||||
window.previewFontFamily = previewFontFamily;
|
||||
window.toggleExpertMode = toggleExpertMode;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user