Fix script paths and move assets to public/ folder for Vite build compatibility

This commit is contained in:
Marcos
2026-03-22 20:45:20 -03:00
parent 304504b758
commit 57ba9d1c5f
155 changed files with 10614 additions and 26 deletions

View File

@@ -0,0 +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;
}

127
public/js/ui/mobile-menu.js Normal file
View File

@@ -0,0 +1,127 @@
/**
* Mobile Menu - Hamburger Navigation
* Handles mobile sidebar drawer with smooth animations
*/
export function initMobileMenu() {
// Only initialize on mobile/tablet
if (window.innerWidth >= 1024) return;
// Create hamburger button
const hamburger = createHamburgerButton();
// Place hamburger inside header/topbar actions
const headerActions = document.querySelector('.header-actions');
if (headerActions) {
headerActions.appendChild(hamburger);
} else {
// Fallback: add to body if header not found
document.body.appendChild(hamburger);
}
// Get sidebar
const sidebar = document.querySelector('.sidebar');
if (!sidebar) return;
// Accessibility roles
sidebar.setAttribute('role', 'navigation');
sidebar.setAttribute('aria-label', 'Menu principal');
// Toggle menu function
const toggleMenu = () => {
const isOpen = hamburger.classList.contains('open');
hamburger.classList.toggle('open');
sidebar.classList.toggle('open');
// Accessibility
hamburger.setAttribute('aria-expanded', String(!isOpen));
sidebar.setAttribute('aria-hidden', String(isOpen));
};
// Event listeners
hamburger.addEventListener('click', toggleMenu);
// Close menu when clicking sidebar item
document.querySelectorAll('.sidebar-item').forEach(item => {
// Make items focusable for keyboard navigation
if (!item.hasAttribute('tabindex')) item.setAttribute('tabindex', '0');
item.addEventListener('click', () => {
if (window.innerWidth < 1024 && hamburger.classList.contains('open')) {
// Slide left then close
sidebar.classList.add('closing-left');
setTimeout(() => {
sidebar.classList.remove('closing-left');
toggleMenu();
}, 250);
}
});
// Keyboard activation closes menu
item.addEventListener('keydown', (e) => {
if ((e.key === 'Enter' || e.key === ' ') && window.innerWidth < 1024 && hamburger.classList.contains('open')) {
e.preventDefault();
sidebar.classList.add('closing-left');
setTimeout(() => {
sidebar.classList.remove('closing-left');
toggleMenu();
}, 250);
}
});
});
// Handle resize - close menu and cleanup on desktop
let resizeTimer;
window.addEventListener('resize', () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
if (window.innerWidth >= 1024) {
// Desktop - cleanup mobile menu
if (hamburger.classList.contains('open')) {
toggleMenu();
}
hamburger.style.display = 'none';
} else {
// Mobile - show menu button
hamburger.style.display = 'flex';
}
}, 250);
});
// Keyboard navigation and focus management
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && hamburger.classList.contains('open')) {
toggleMenu();
hamburger.focus();
}
});
// Manage focus when opening
hamburger.addEventListener('click', () => {
if (hamburger.classList.contains('open')) {
const firstItem = sidebar.querySelector('.sidebar-item');
if (firstItem) firstItem.focus?.();
}
});
}
function createHamburgerButton() {
const button = document.createElement('button');
button.className = 'hamburger';
button.setAttribute('aria-label', 'Menu de navegação');
button.setAttribute('aria-expanded', 'false');
button.innerHTML = `
<div class="hamburger-icon">
<span></span>
<span></span>
<span></span>
</div>
`;
return button;
}
// Auto-initialize if loaded as module
if (typeof window !== 'undefined') {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initMobileMenu);
} else {
initMobileMenu();
}
}

184
public/js/ui/navigation.js Normal file
View File

@@ -0,0 +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;
}

View File

@@ -0,0 +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>
`;
}
}

129
public/js/ui/theme.js Normal file
View File

@@ -0,0 +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;
}

View File

@@ -0,0 +1,571 @@
/**
* ToastManager - Sistema de Notificações Visuais
* Responsável por exibir mensagens de feedback ao usuário de forma elegante e não-intrusiva
*/
class ToastManager {
constructor() {
this.container = null;
this.toasts = new Map();
this.config = {
position: 'top-right',
maxToasts: 5,
duration: {
success: 3000,
error: 5000,
warning: 4000,
info: 3000
}
};
this.init();
}
/**
* Inicializa o ToastManager criando o container
*/
init() {
this.createContainer();
console.log('🍞 ToastManager inicializado');
}
/**
* Cria o container de toasts no DOM
*/
createContainer() {
// Remover container existente se houver
const existingContainer = document.querySelector('.toast-container');
if (existingContainer) {
existingContainer.remove();
}
// Criar novo container
this.container = document.createElement('div');
this.container.className = `toast-container toast-${this.config.position}`;
// Adicionar estilos CSS
this.addStyles();
// Adicionar ao body
document.body.appendChild(this.container);
}
/**
* Adiciona estilos CSS para os toasts
*/
addStyles() {
// Verificar se os estilos já existem
if (document.querySelector('#toast-styles')) {
return;
}
const styles = document.createElement('style');
styles.id = 'toast-styles';
styles.textContent = `
.toast-container {
position: fixed;
z-index: 10000;
pointer-events: none;
display: flex;
flex-direction: column;
gap: 8px;
max-width: 400px;
width: 100%;
}
.toast-top-right {
top: 20px;
right: 20px;
}
.toast-top-left {
top: 20px;
left: 20px;
}
.toast-bottom-right {
bottom: 20px;
right: 20px;
}
.toast-bottom-left {
bottom: 20px;
left: 20px;
}
.toast-top-center {
top: 20px;
left: 50%;
transform: translateX(-50%);
}
.toast-bottom-center {
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.toast {
background: var(--color-bg-2);
color: var(--color-text);
border-radius: 8px;
padding: 16px 20px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
border-left: 4px solid var(--color-primary);
display: flex;
align-items: flex-start;
gap: 12px;
animation: toast-in 0.3s ease-out;
pointer-events: auto;
position: relative;
overflow: hidden;
}
.toast-success {
border-left-color: #10b981;
background: linear-gradient(135deg, #10b98120 0%, transparent 100%);
}
.toast-error {
border-left-color: #ef4444;
background: linear-gradient(135deg, #ef444420 0%, transparent 100%);
}
.toast-warning {
border-left-color: #f59e0b;
background: linear-gradient(135deg, #f59e0b20 0%, transparent 100%);
}
.toast-info {
border-left-color: #3b82f6;
background: linear-gradient(135deg, #3b82f620 0%, transparent 100%);
}
.toast-icon {
flex-shrink: 0;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
}
.toast-content {
flex: 1;
min-width: 0;
}
.toast-title {
font-weight: 600;
margin-bottom: 4px;
font-size: 14px;
}
.toast-message {
font-size: 13px;
line-height: 1.4;
opacity: 0.9;
}
.toast-close {
flex-shrink: 0;
width: 20px;
height: 20px;
border: none;
background: transparent;
color: var(--color-text);
cursor: pointer;
opacity: 0.6;
transition: opacity 0.2s;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
padding: 0;
}
.toast-close:hover {
opacity: 1;
}
.toast-progress {
position: absolute;
bottom: 0;
left: 0;
height: 2px;
background: var(--color-primary);
opacity: 0.3;
animation: toast-progress linear forwards;
}
.toast-success .toast-progress {
background: #10b981;
}
.toast-error .toast-progress {
background: #ef4444;
}
.toast-warning .toast-progress {
background: #f59e0b;
}
.toast-info .toast-progress {
background: #3b82f6;
}
.toast.removing {
animation: toast-out 0.3s ease-in forwards;
}
@keyframes toast-in {
from {
opacity: 0;
transform: translateX(100%);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes toast-out {
from {
opacity: 1;
transform: translateX(0);
}
to {
opacity: 0;
transform: translateX(100%);
}
}
@keyframes toast-progress {
from {
width: 100%;
}
to {
width: 0%;
}
}
/* Responsividade */
@media (max-width: 480px) {
.toast-container {
left: 10px !important;
right: 10px !important;
max-width: none;
}
.toast {
padding: 14px 16px;
}
}
`;
document.head.appendChild(styles);
}
/**
* Mostra um toast genérico
* @param {string} message - Mensagem a exibir
* @param {string} type - Tipo do toast (success, error, warning, info)
* @param {number} duration - Duração em milissegundos
* @param {Object} options - Opções adicionais
*/
show(message, type = 'info', duration = null, options = {}) {
// Limitar número de toasts simultâneos
if (this.toasts.size >= this.config.maxToasts) {
// Remover o toast mais antigo
const oldestToast = this.toasts.values().next().value;
if (oldestToast) {
this.removeToast(oldestToast.id);
}
}
const toastId = `toast-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const toastDuration = duration || this.config.duration[type] || 3000;
const toast = this.createToastElement(toastId, message, type, options);
this.container.appendChild(toast);
const toastData = {
id: toastId,
element: toast,
type: type,
message: message,
startTime: Date.now(),
duration: toastDuration
};
this.toasts.set(toastId, toastData);
// Configurar remoção automática
if (toastDuration > 0) {
setTimeout(() => {
this.removeToast(toastId);
}, toastDuration);
// Configurar barra de progresso
const progressBar = toast.querySelector('.toast-progress');
if (progressBar) {
progressBar.style.animationDuration = `${toastDuration}ms`;
}
}
console.log(`🍞 Toast ${type}: ${message}`);
return toastId;
}
/**
* Cria o elemento HTML do toast
* @param {string} id - ID do toast
* @param {string} message - Mensagem
* @param {string} type - Tipo do toast
* @param {Object} options - Opções adicionais
* @returns {HTMLElement} Elemento do toast
*/
createToastElement(id, message, type, options = {}) {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.id = id;
// Ícone baseado no tipo
const icons = {
success: '✅',
error: '❌',
warning: '⚠️',
info: ''
};
const icon = options.icon || icons[type] || '💬';
const title = options.title || this.getTitleByType(type);
toast.innerHTML = `
<div class="toast-icon">${icon}</div>
<div class="toast-content">
${title ? `<div class="toast-title">${title}</div>` : ''}
<div class="toast-message">${this.escapeHtml(message)}</div>
</div>
<button class="toast-close" onclick="window.toastManager.removeToast('${id}')">✕</button>
<div class="toast-progress"></div>
`;
// Adicionar eventos de hover
toast.addEventListener('mouseenter', () => {
const progressBar = toast.querySelector('.toast-progress');
if (progressBar) {
progressBar.style.animationPlayState = 'paused';
}
});
toast.addEventListener('mouseleave', () => {
const progressBar = toast.querySelector('.toast-progress');
if (progressBar) {
progressBar.style.animationPlayState = 'running';
}
});
// Permitir clique para fechar (exceto no botão de fechar)
toast.addEventListener('click', (e) => {
if (!e.target.classList.contains('toast-close')) {
this.removeToast(id);
}
});
return toast;
}
/**
* Obtém título baseado no tipo
* @param {string} type - Tipo do toast
* @returns {string} Título
*/
getTitleByType(type) {
const titles = {
success: 'Sucesso!',
error: 'Erro!',
warning: 'Atenção!',
info: 'Informação'
};
return titles[type] || '';
}
/**
* Remove um toast específico
* @param {string} toastId - ID do toast a remover
*/
removeToast(toastId) {
const toastData = this.toasts.get(toastId);
if (!toastData) {
return;
}
const toast = toastData.element;
toast.classList.add('removing');
// Remover após animação
setTimeout(() => {
if (toast.parentNode) {
toast.parentNode.removeChild(toast);
}
this.toasts.delete(toastId);
}, 300);
}
/**
* Remove todos os toasts ativos
*/
removeAllToasts() {
const toastIds = Array.from(this.toasts.keys());
toastIds.forEach(id => this.removeToast(id));
}
/**
* Escapa HTML para prevenir XSS
* @param {string} text - Texto a escapar
* @returns {string} Texto escapado
*/
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Métodos de conveniência
/**
* Mostra um toast de sucesso
* @param {string} message - Mensagem
* @param {number} duration - Duração em milissegundos
* @param {Object} options - Opções adicionais
*/
success(message, duration = null, options = {}) {
return this.show(message, 'success', duration, options);
}
/**
* Mostra um toast de erro
* @param {string} message - Mensagem
* @param {number} duration - Duração em milissegundos
* @param {Object} options - Opções adicionais
*/
error(message, duration = null, options = {}) {
return this.show(message, 'error', duration, options);
}
/**
* Mostra um toast de aviso
* @param {string} message - Mensagem
* @param {number} duration - Duração em milissegundos
* @param {Object} options - Opções adicionais
*/
warning(message, duration = null, options = {}) {
return this.show(message, 'warning', duration, options);
}
/**
* Mostra um toast de informação
* @param {string} message - Mensagem
* @param {number} duration - Duração em milissegundos
* @param {Object} options - Opções adicionais
*/
info(message, duration = null, options = {}) {
return this.show(message, 'info', duration, options);
}
/**
* Mostra um toast de loading (persistente)
* @param {string} message - Mensagem
* @param {Object} options - Opções adicionais
*/
loading(message = 'Carregando...', options = {}) {
const toastId = this.show(message, 'info', 0, {
icon: '⏳',
title: 'Aguarde...',
...options
});
// Remover barra de progresso para loading persistente
const toast = this.toasts.get(toastId);
if (toast) {
const progressBar = toast.element.querySelector('.toast-progress');
if (progressBar) {
progressBar.remove();
}
}
return toastId;
}
/**
* Atualiza o conteúdo de um toast existente
* @param {string} toastId - ID do toast
* @param {string} message - Nova mensagem
* @param {string} type - Novo tipo (opcional)
*/
updateToast(toastId, message, type = null) {
const toastData = this.toasts.get(toastId);
if (!toastData) {
return false;
}
const toast = toastData.element;
const messageElement = toast.querySelector('.toast-message');
if (messageElement) {
messageElement.textContent = message;
}
if (type && type !== toastData.type) {
toast.className = toast.className.replace(`toast-${toastData.type}`, `toast-${type}`);
toastData.type = type;
// Atualizar ícone
const iconElement = toast.querySelector('.toast-icon');
if (iconElement) {
const icons = {
success: '✅',
error: '❌',
warning: '⚠️',
info: ''
};
iconElement.textContent = icons[type] || '💬';
}
}
return true;
}
/**
* Configura o ToastManager
* @param {Object} config - Configurações
*/
setConfig(config) {
this.config = { ...this.config, ...config };
// Recriar container se a posição mudou
if (config.position) {
this.createContainer();
}
}
/**
* Obtém estatísticas dos toasts
* @returns {Object} Estatísticas
*/
getStats() {
return {
activeToasts: this.toasts.size,
maxToasts: this.config.maxToasts,
position: this.config.position
};
}
}
// Criar instância global
window.toastManager = new ToastManager();
console.log('🍞 ToastManager inicializado com sucesso');