Files
SteelBase/public/js/ui/section-loader.js

239 lines
7.7 KiB
JavaScript

/**
* 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>
`;
}
}