4U Code Optimizer

v2.5 Pro

Minificador Seguro • Beautifier • Diff Viewer • SVG & Web Toolkit

Presets rápidos:
Código de Entrada

Arraste seu arquivo aqui ou clique para selecionar

Sintaxe Pronta
.js
// O código processado (minificado ou formatado) aparecerá aqui...

Painel de Métricas e Economia de Transferência

Simulador de Compressão Gzip / Brotli
Tamanho Original
0 B
0 caracteres
Tamanho Processado
0 B
0 caracteres
Economia / Redução
0%
0 bytes salvos
Linhas de Código
0 → 0
Variação de linhas
Gzip Estimado
0 B
Compressão web
Ganho em Rede Móvel
~0 ms
Conexão 4G/3G
`, json: `{ "project": "4U Code Optimizer", "version": "2.5.0", "features": ["minification", "beautification", "diff-viewer", "zip-export"], "settings": { "theme": "dark", "removeConsole": true, "gzipSimulation": true, "indentSize": 2 }, "metrics": { "rating": 5, "activeUsers": 1840 } }`, sql: `-- Relatório financeiro por cliente SELECT c.id AS cliente_id, c.nome AS cliente_nome, COUNT(p.id) AS total_pedidos, SUM(p.valor_total) AS faturamento_acumulado FROM clientes c LEFT JOIN pedidos p ON p.cliente_id = c.id WHERE p.status = 'pago' AND p.data_pedido >= '2026-01-01' GROUP BY c.id, c.nome HAVING faturamento_acumulado > 1000 ORDER BY faturamento_acumulado DESC LIMIT 50;`, svg: ` Created for 4U Labs `, yaml: `version: '3.8' services: web: image: nginx:alpine ports: - "80:80" - "443:443" environment: NODE_ENV: production APP_NAME: "4U Minifier" volumes: - ./public_html:/usr/share/nginx/html` }; function loadSamplePreset(presetKey) { const code = samplePresets[presetKey]; if (!code) return; document.getElementById('inputCode1').value = code; document.getElementById('studioLangSelect').value = presetKey; editors[1].manualLanguage = presetKey; editors[1].language = presetKey; updateLangBadge(1, presetKey); handleStudioInput(); // Auto run beautify for clear preview beautifyCode(1); showToast(`Exemplo "${presetKey.toUpperCase()}" carregado!`, 'success'); } function loadSavedSession() { try { const raw = localStorage.getItem('4u_minifier_session'); if (raw) { const session = JSON.parse(raw); if (session.input1 && session.input1.trim()) { document.getElementById('inputCode1').value = session.input1; if (session.lang1) { editors[1].manualLanguage = session.lang1; editors[1].language = session.lang1; document.getElementById('studioLangSelect').value = session.lang1; } if (session.output1) { editors[1].rawCode = session.output1; displayOutput(1, session.output1); updateStats(1, session.input1, session.output1); } handleStudioInput(); return true; } } } catch (e) {} return false; } // DOM Ready Initialization document.addEventListener('DOMContentLoaded', () => { loadSavedOptions(); setupDragAndDrop(); const restored = loadSavedSession(); if (!restored) { loadSamplePreset('javascript'); } }); // ========================================== // VIEW SWITCHING (STUDIO vs MULTI) // ========================================== function switchViewMode(mode) { state.viewMode = mode; const studioSec = document.getElementById('studioModeSection'); const multiSec = document.getElementById('multiModeSection'); const multiToolbar = document.getElementById('multiGlobalToolbar'); const studioBtn = document.getElementById('viewModeStudioBtn'); const multiBtn = document.getElementById('viewModeMultiBtn'); if (mode === 'studio') { studioSec.classList.remove('hidden'); multiSec.classList.add('hidden'); multiToolbar.classList.add('hidden'); studioBtn.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-2 transition-all bg-indigo-600 text-white shadow-md'; multiBtn.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-2 transition-all text-gray-400 hover:text-white'; // Sync Editor 1 into Studio document.getElementById('inputCode1').value = document.getElementById('inputCodeMulti1').value || document.getElementById('inputCode1').value; handleStudioInput(); } else { studioSec.classList.add('hidden'); multiSec.classList.remove('hidden'); multiToolbar.classList.remove('hidden'); multiBtn.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-2 transition-all bg-indigo-600 text-white shadow-md'; studioBtn.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-2 transition-all text-gray-400 hover:text-white'; // Sync Studio into Multi Editor 1 document.getElementById('inputCodeMulti1').value = document.getElementById('inputCode1').value; document.getElementById('outputCodeMulti1').innerHTML = document.getElementById('outputCode1').innerHTML; document.getElementById('fileNameMulti1').value = document.getElementById('fileName1').value; updateMultiStatsFromStudio(1); } } function switchStudioTab(tab) { state.studioTab = tab; const tabOutputBtn = document.getElementById('tabOutputBtn'); const tabDiffBtn = document.getElementById('tabDiffBtn'); const tabPreviewBtn = document.getElementById('tabPreviewBtn'); const conOutput = document.getElementById('containerOutputTab'); const conDiff = document.getElementById('containerDiffTab'); const conPreview = document.getElementById('containerPreviewTab'); [tabOutputBtn, tabDiffBtn, tabPreviewBtn].forEach(b => { b.className = 'px-3 py-1 rounded-lg text-xs font-semibold text-gray-400 hover:text-white flex items-center gap-1.5 transition-all'; }); [conOutput, conDiff, conPreview].forEach(c => c.classList.add('hidden')); if (tab === 'output') { tabOutputBtn.className = 'px-3 py-1 rounded-lg text-xs font-semibold bg-indigo-600 text-white shadow-sm flex items-center gap-1.5 transition-all'; conOutput.classList.remove('hidden'); } else if (tab === 'diff') { tabDiffBtn.className = 'px-3 py-1 rounded-lg text-xs font-semibold bg-purple-600 text-white shadow-sm flex items-center gap-1.5 transition-all'; conDiff.classList.remove('hidden'); renderDiff(1); } else if (tab === 'preview') { tabPreviewBtn.className = 'px-3 py-1 rounded-lg text-xs font-semibold bg-cyan-600 text-white shadow-sm flex items-center gap-1.5 transition-all'; conPreview.classList.remove('hidden'); renderLivePreview(); } } function openDiffView() { switchStudioTab('diff'); } // ========================================== // TOKEN-AWARE SAFE MINIFICATION ENGINES // ========================================== // 1. SAFE JAVASCRIPT MINIFIER function safeMinifyJS(code, options = {}) { const { removeConsole = true, removeDebugger = true, keepLicense = true } = options; let i = 0; const len = code.length; let result = ''; function isIdent(ch) { return /[a-zA-Z0-9_$]/.test(ch); } while (i < len) { const c = code[i]; const next = code[i + 1]; // Single-line comment // if (c === '/' && next === '/') { const commentStart = i; let end = code.indexOf('\n', i + 2); if (end === -1) end = len; const comment = code.slice(commentStart, end); if (keepLicense && (comment.includes('/*!') || comment.includes('@license') || comment.includes('@preserve'))) { result += comment + '\n'; } i = end; continue; } // Multi-line comment /* if (c === '/' && next === '*') { const commentStart = i; let end = code.indexOf('*/', i + 2); if (end === -1) end = len; else end += 2; const comment = code.slice(commentStart, end); if (keepLicense && (comment.startsWith('/*!') || comment.includes('@license') || comment.includes('@preserve'))) { result += comment + '\n'; } i = end; continue; } // String literal: "..." or '...' if (c === '"' || c === "'") { const quote = c; let str = quote; i++; while (i < len) { const sc = code[i]; str += sc; if (sc === '\\') { i++; if (i < len) str += code[i]; } else if (sc === quote) { i++; break; } i++; } result += str; continue; } // Template literal: `...` if (c === '`') { let tpl = '`'; i++; let depth = 0; while (i < len) { const tc = code[i]; tpl += tc; if (tc === '\\') { i++; if (i < len) tpl += code[i]; } else if (tc === '`' && depth === 0) { i++; break; } else if (tc === '$' && code[i + 1] === '{') { depth++; tpl += '{'; i++; } else if (tc === '}' && depth > 0) { depth--; } i++; } result += tpl; continue; } // Regex literal vs Division operator: if (c === '/') { const prevTrimmed = result.trimEnd(); const lastChar = prevTrimmed[prevTrimmed.length - 1]; const isRegex = !lastChar || /[=([{:;,!?&|~^<>+*/%\\-]/.test(lastChar) || /\b(return|typeof|instanceof|void|delete|throw|case|in|of|yield|await)$/.test(prevTrimmed); if (isRegex) { let rx = '/'; i++; let inClass = false; while (i < len) { const rc = code[i]; rx += rc; if (rc === '\\') { i++; if (i < len) rx += code[i]; } else if (rc === '[') { inClass = true; } else if (rc === ']') { inClass = false; } else if (rc === '/' && !inClass) { i++; while (i < len && /[a-z]/i.test(code[i])) { rx += code[i]; i++; } break; } i++; } result += rx; continue; } } // Whitespace handling: if (/\s/.test(c)) { const prevChar = result[result.length - 1]; let j = i + 1; while (j < len && /\s/.test(code[j])) j++; const nextChar = code[j]; if (prevChar && nextChar && isIdent(prevChar) && isIdent(nextChar)) { result += ' '; } else if ((prevChar === '+' && nextChar === '+') || (prevChar === '-' && nextChar === '-')) { result += ' '; } i = j; continue; } result += c; i++; } if (removeDebugger) { result = result.replace(/\bdebugger\s*;?/g, ''); } if (removeConsole) { result = result.replace(/\bconsole\s*\.\s*(log|debug|info|trace|warn|error)\s*\([^()]*(\([^()]*\)[^()]*)*\)\s*;?/g, ''); } result = result.replace(/;+/g, ';') .replace(/\{;/g, '{') .replace(/;\}/g, '}') .trim(); return result; } // 2. SAFE CSS MINIFIER function safeMinifyCSS(code, options = {}) { const { keepLicense = true } = options; let result = code; // 1. Protect strings first const strings = []; result = result.replace(/(["\'])(?:\\.|[^\\])*?\1/g, m => { strings.push(m); return '___CSS_STR_' + (strings.length - 1) + '___'; }); // 2. Protect licenses const licenses = []; if (keepLicense) { result = result.replace(/\/\*![\s\S]*?\*\//g, m => { licenses.push(m); return '___CSS_LIC_' + (licenses.length - 1) + '___'; }); } // 3. Remove standard comments result = result.replace(/\/\*[\s\S]*?\*\//g, ''); // 4. Protect calc(...) expressions (operators require whitespace!) const calcs = []; result = result.replace(/calc\([^)]+\)/gi, m => { calcs.push(m); return '___CSS_CALC_' + (calcs.length - 1) + '___'; }); // 5. Minify rules result = result.replace(/\s+/g, ' '); result = result.replace(/\s*([{}:;,>+~])\s*/g, '$1'); result = result.replace(/;}/g, '}'); result = result.replace(/#([0-9a-fA-F])\1([0-9a-fA-F])\2([0-9a-fA-F])\3\b/g, '#$1$2$3'); result = result.replace(/(:|\s)0(?:px|em|rem|%|in|cm|mm|pc|pt|ex|vh|vw|vmin|vmax)/gi, '$10'); // 6. Restore result = result.replace(/___CSS_CALC_(\d+)___/g, (_, i) => calcs[i]); result = result.replace(/___CSS_STR_(\d+)___/g, (_, i) => strings[i]); result = result.replace(/___CSS_LIC_(\d+)___/g, (_, i) => licenses[i]); return result.trim(); } // 3. SAFE HTML MINIFIER function safeMinifyHTML(code) { let result = code; // Protect preformatted tags and code blocks const protectedBlocks = []; const protectTags = ['pre', 'code', 'textarea', 'script', 'style', 'svg']; protectTags.forEach(tag => { const regex = new RegExp('<' + tag + '\\b[^>]*>[\\s\\S]*?<\\/' + tag + '>', 'gi'); result = result.replace(regex, m => { protectedBlocks.push(m); return '___HTML_BLOCK_' + (protectedBlocks.length - 1) + '___'; }); }); // Remove comments (preserve conditional IE comments) result = result.replace(//g, ''); // Collapse spaces between tags result = result.replace(/>\s+<'); // Collapse multiple spaces to single space result = result.replace(/\s{2,}/g, ' '); // Restore protected blocks result = result.replace(/___HTML_BLOCK_(\d+)___/g, (_, i) => protectedBlocks[i]); return result.trim(); } // 4. JSON MINIFIER & BEAUTIFIER & KEY SORTER function sortJsonKeys(value) { if (Array.isArray(value)) { return value.map(sortJsonKeys); } else if (value !== null && typeof value === 'object') { const sorted = {}; Object.keys(value).sort().forEach(k => { sorted[k] = sortJsonKeys(value[k]); }); return sorted; } return value; } function minifyJSON(code, options = {}) { let parsed = JSON.parse(code); if (options.sortKeys) { parsed = sortJsonKeys(parsed); } return JSON.stringify(parsed); } function beautifyJSON(code, options = {}) { let parsed = JSON.parse(code); if (options.sortKeys) { parsed = sortJsonKeys(parsed); } const indent = options.indentSize === 'tab' ? '\t' : (parseInt(options.indentSize) || 2); return JSON.stringify(parsed, null, indent); } // 5. SQL MINIFIER & BEAUTIFIER function minifySQL(sql) { let result = sql; const strings = []; result = result.replace(/(["\'])(?:\\.|[^\\])*?\1/g, m => { strings.push(m); return '___SQL_STR_' + (strings.length - 1) + '___'; }); result = result.replace(/--.*$/gm, ''); result = result.replace(/\/\*[\s\S]*?\*\//g, ''); result = result.replace(/\s+/g, ' '); result = result.replace(/\s*([,();])\s*/g, '$1 '); result = result.replace(/\s*([=<>!]+)\s*/g, ' $1 '); result = result.replace(/\(\s+/g, '(').replace(/\s+\)/g, ')'); result = result.replace(/___SQL_STR_(\d+)___/g, (_, i) => strings[i]); return result.trim(); } function beautifySQL(sql) { let text = minifySQL(sql); const majorKeywords = [ 'LEFT JOIN', 'RIGHT JOIN', 'INNER JOIN', 'OUTER JOIN', 'CROSS JOIN', 'GROUP BY', 'ORDER BY', 'INSERT INTO', 'DELETE FROM', 'UNION ALL', 'CREATE TABLE', 'ALTER TABLE', 'DROP TABLE', 'SELECT', 'FROM', 'WHERE', 'JOIN', 'HAVING', 'LIMIT', 'OFFSET', 'VALUES', 'UPDATE', 'SET', 'UNION' ]; const subKeywords = ['AND', 'OR', 'ON', 'WHEN', 'THEN', 'ELSE']; majorKeywords.forEach(kw => { const rx = new RegExp('\\b' + kw.replace(' ', '\\s+') + '\\b', 'gi'); text = text.replace(rx, '\n' + kw); }); subKeywords.forEach(kw => { const rx = new RegExp('\\b' + kw + '\\b', 'gi'); text = text.replace(rx, '\n ' + kw); }); const lines = text.split('\n').map(l => l.trim()).filter(Boolean); let formatted = ''; lines.forEach(line => { const upper = line.toUpperCase(); if (subKeywords.some(kw => upper.startsWith(kw))) { formatted += ' ' + line + '\n'; } else if (majorKeywords.some(kw => upper.startsWith(kw))) { formatted += line + '\n'; } else { formatted += ' ' + line + '\n'; } }); return formatted.trim(); } // 6. SVG OPTIMIZER function optimizeSVG(svg) { let result = svg; // Remove XML declaration and DOCTYPE result = result.replace(/<\?xml[\s\S]*?\?>/gi, ''); result = result.replace(//gi, ''); // Remove comments result = result.replace(//g, ''); // Remove metadata tags result = result.replace(//gi, ''); // Remove vector editor namespaces (Inkscape, Sodipodi, Sketch, Illustrator) result = result.replace(/\s+(xmlns:inkscape|xmlns:sodipodi|xmlns:sketch|xmlns:adobe|inkscape:[a-z-]+|sodipodi:[a-z-]+|sketch:[a-z-]+)="[^"]*"/gi, ''); // Collapse tag whitespace result = result.replace(/>\s+<'); // Clean path coordinates result = result.replace(/d="([^"]+)"/g, (m, d) => { const cleanD = d.replace(/\s*([MLHVCSQTAZmlhvcsqtaz])\s*/g, '$1') .replace(/\s+/g, ' ') .trim(); return `d="${cleanD}"`; }); result = result.replace(/\s{2,}/g, ' '); return result.trim(); } // 7. XML MINIFIER & BEAUTIFIER function minifyXML(code) { return code .replace(//g, '') .replace(/>\s+<') .replace(/\s+/g, ' ') .trim(); } function beautifyXML(code) { let formatted = '', indent = 0; const lines = code.replace(/>\s*\n<').split('\n'); lines.forEach(line => { line = line.trim(); if (!line) return; if (line.match(/^<\/\w/)) indent--; formatted += ' '.repeat(Math.max(0, indent)) + line + '\n'; if (line.match(/^<\w[^>]*[^/]>$/) && !line.match(/^<\?/)) indent++; }); return formatted.trim(); } // 8. GRAPHQL MINIFIER & BEAUTIFIER function minifyGraphQL(code) { return code .replace(/#.*$/gm, '') .replace(/\s+/g, ' ') .replace(/\s*([{}():,$])\s*/g, '$1') .trim(); } function beautifyGraphQL(code) { const minified = minifyGraphQL(code); let formatted = ''; let indent = 0; for (let i = 0; i < minified.length; i++) { const char = minified[i]; if (char === '{') { indent++; formatted += ' {\n' + ' '.repeat(indent); } else if (char === '}') { indent = Math.max(0, indent - 1); formatted += '\n' + ' '.repeat(indent) + '}'; } else if (char === '\n') { formatted += '\n' + ' '.repeat(indent); } else { formatted += char; } } return formatted.trim(); } // ========================================== // MAIN PROCESSING DISPATCHER // ========================================== function minifyCode(id) { const input = (id === 1 && state.viewMode === 'studio') ? document.getElementById('inputCode1').value : document.getElementById('inputCodeMulti' + id)?.value || document.getElementById('inputCode' + id).value; if (!input.trim()) { showToast('Insira ou cole algum código primeiro!', 'warning'); return; } const lang = editors[id].language || detectLanguage(id); let output = ''; try { switch (lang) { case 'javascript': output = safeMinifyJS(input, state.options); break; case 'css': output = safeMinifyCSS(input, state.options); break; case 'html': output = safeMinifyHTML(input); break; case 'json': output = minifyJSON(input, { sortKeys: state.options.sortJsonKeys }); break; case 'sql': output = minifySQL(input); break; case 'svg': output = optimizeSVG(input); break; case 'xml': output = minifyXML(input); break; case 'yaml': if (window.jsyaml) { const parsed = jsyaml.load(input); output = JSON.stringify(parsed); } else { output = input.replace(/#.*$/gm, '').replace(/\n\s*\n/g, '\n').trim(); } break; case 'graphql': output = minifyGraphQL(input); break; default: output = safeMinifyJS(input, state.options); } editors[id].originalCode = input; editors[id].rawCode = output; displayOutput(id, output); updateStats(id, input, output); saveStateToStorage(); showToast(`Editor ${id}: Minificado com sucesso!`, 'success'); if (id === 1 && state.studioTab === 'diff') renderDiff(1); if (id === 1 && state.studioTab === 'preview') renderLivePreview(); } catch (e) { showToast(`Erro na minificação: ${e.message}`, 'error'); } } function beautifyCode(id) { const input = (id === 1 && state.viewMode === 'studio') ? document.getElementById('inputCode1').value : document.getElementById('inputCodeMulti' + id)?.value || document.getElementById('inputCode' + id).value; if (!input.trim()) { showToast('Insira ou cole algum código primeiro!', 'warning'); return; } const lang = editors[id].language || detectLanguage(id); let output = ''; const indent_size = state.options.indentSize === 'tab' ? 2 : (parseInt(state.options.indentSize) || 2); try { switch (lang) { case 'javascript': output = js_beautify(input, { indent_size, space_after_anon_function: true }); break; case 'css': output = css_beautify(input, { indent_size }); break; case 'html': output = html_beautify(input, { indent_size, wrap_line_length: 100, unformatted: ['pre', 'code'] }); break; case 'json': output = beautifyJSON(input, { sortKeys: state.options.sortJsonKeys, indentSize: state.options.indentSize }); break; case 'sql': output = beautifySQL(input); break; case 'svg': case 'xml': output = beautifyXML(input); break; case 'yaml': if (window.jsyaml) { const parsed = jsyaml.load(input); output = jsyaml.dump(parsed, { indent: indent_size }); } else { output = input; } break; case 'graphql': output = beautifyGraphQL(input); break; default: output = js_beautify(input, { indent_size }); } editors[id].originalCode = input; editors[id].rawCode = output; displayOutput(id, output); updateStats(id, input, output); saveStateToStorage(); showToast(`Editor ${id}: Formatado com sucesso!`, 'success'); if (id === 1 && state.studioTab === 'diff') renderDiff(1); if (id === 1 && state.studioTab === 'preview') renderLivePreview(); } catch (e) { showToast(`Erro na formatação: ${e.message}`, 'error'); } } // ========================================== // DYNAMIC CONTEXTUAL ACTIONS // ========================================== function updateContextualActionButton(lang) { const btnText = document.getElementById('studioConvertBtnText'); const btnIcon = document.getElementById('studioConvertBtnIcon'); const btn = document.getElementById('studioConvertBtn'); if (!btn || !btnText) return; const iconSvg = { clean: '', swap: '', palette: '', vector: '', sql: '', code: '' }; const map = { javascript: { text: 'Limpar Logs & Debug', title: 'Remove console.log e debugger mantendo o código formatado', icon: iconSvg.clean }, css: { text: 'Otimizar Cores & Unidades', title: 'Encurta cores hexadecimais (#ffffff -> #fff) e colapsa unidades zero', icon: iconSvg.palette }, json: { text: 'JSON ➔ YAML', title: 'Converte estrutura JSON para formato YAML legível', icon: iconSvg.swap }, yaml: { text: 'YAML ➔ JSON', title: 'Converte arquivo YAML para objeto JSON formatado', icon: iconSvg.swap }, svg: { text: 'Otimizar Vetor SVG', title: 'Remove metadados de editores e limpa coordenadas de path', icon: iconSvg.vector }, sql: { text: 'Formatar Cláusulas', title: 'Indenta e destaca palavras-chave SQL (SELECT, JOIN, WHERE)', icon: iconSvg.sql }, html: { text: 'Limpar Comentários', title: 'Remove comentários HTML preservando scripts e styles', icon: iconSvg.code }, xml: { text: 'Indentar XML', title: 'Organiza hierarquia das tags XML com indentação limpa', icon: iconSvg.code }, graphql: { text: 'Formatar Query', title: 'Indenta campos e argumentos de queries GraphQL', icon: iconSvg.code }, markdown: { text: 'Normalizar Markdown', title: 'Remove espaçamentos redundantes no texto Markdown', icon: iconSvg.code } }; const action = map[lang] || { text: 'Ação Rápida', title: 'Ação de produtividade para este formato', icon: iconSvg.code }; btnText.textContent = action.text; btn.title = action.title; if (btnIcon && action.icon) btnIcon.innerHTML = action.icon; } function handleSpecialConversion(id) { const input = (id === 1 && state.viewMode === 'studio') ? document.getElementById('inputCode1').value : document.getElementById('inputCodeMulti' + id)?.value || document.getElementById('inputCode' + id).value; if (!input.trim()) { showToast('Insira código para aplicar a ação!', 'warning'); return; } const lang = editors[id].language || detectLanguage(id); let output = ''; try { switch (lang) { case 'javascript': output = input.replace(/\bdebugger\s*;?/g, '') .replace(/\bconsole\s*\.\s*(log|debug|info|trace|warn|error)\s*\([^()]*(\([^()]*\)[^()]*)*\)\s*;?/g, ''); output = js_beautify(output, { indent_size: 2, space_after_anon_function: true }); showToast('Logs e debugger removidos com sucesso!', 'success'); break; case 'css': output = input.replace(/#([0-9a-fA-F])\1([0-9a-fA-F])\2([0-9a-fA-F])\3\b/g, '#$1$2$3') .replace(/(:|\s)0(?:px|em|rem|%|in|cm|mm|pc|pt|ex|vh|vw|vmin|vmax)/gi, '$10'); output = css_beautify(output, { indent_size: 2 }); showToast('Cores e unidades CSS otimizadas!', 'success'); break; case 'json': const parsedJson = JSON.parse(input); output = jsyaml.dump(parsedJson, { indent: 2 }); showToast('Convertido de JSON para YAML!', 'success'); break; case 'yaml': const parsedYaml = jsyaml.load(input); output = JSON.stringify(parsedYaml, null, 2); showToast('Convertido de YAML para JSON!', 'success'); break; case 'svg': output = optimizeSVG(input); output = beautifyXML(output); showToast('Vetor SVG otimizado e limpo!', 'success'); break; case 'sql': output = beautifySQL(input); showToast('Cláusulas SQL formatadas!', 'success'); break; case 'html': output = input.replace(//g, ''); output = html_beautify(output, { indent_size: 2 }); showToast('Comentários HTML removidos!', 'success'); break; case 'xml': output = beautifyXML(input); showToast('XML indentado com sucesso!', 'success'); break; case 'graphql': output = beautifyGraphQL(input); showToast('GraphQL formatado!', 'success'); break; case 'markdown': output = input.replace(/[ \t]+$/gm, '').replace(/\n{3,}/g, '\n\n').trim(); showToast('Markdown normalizado!', 'success'); break; default: output = js_beautify(input, { indent_size: 2 }); showToast('Formatado com sucesso!', 'success'); } editors[id].originalCode = input; editors[id].rawCode = output; displayOutput(id, output); updateStats(id, input, output); saveStateToStorage(); if (id === 1 && state.studioTab === 'diff') renderDiff(1); if (id === 1 && state.studioTab === 'preview') renderLivePreview(); } catch (e) { showToast(`Erro na ação: ${e.message}`, 'error'); } } // ========================================== // SYNTAX VALIDATION & LANGUAGE DETECTION // ========================================== function detectLanguage(id) { const inputEl = (id === 1 && state.viewMode === 'studio') ? document.getElementById('inputCode1') : (document.getElementById('inputCodeMulti' + id) || document.getElementById('inputCode' + id)); const code = inputEl.value.trim(); const badgeEl = id === 1 ? document.getElementById('studioDetectedBadge') : document.getElementById('detectedLang' + id); if (!code) { editors[id].language = null; if (badgeEl) badgeEl.classList.add('hidden'); return 'javascript'; } if (editors[id].manualLanguage && editors[id].manualLanguage !== 'auto') { editors[id].language = editors[id].manualLanguage; updateLangBadge(id, editors[id].language); return editors[id].language; } // Score-based detection const scores = { javascript: 0, css: 0, html: 0, json: 0, sql: 0, svg: 0, yaml: 0, xml: 0, graphql: 0 }; // Check direct parsers try { JSON.parse(code); scores.json += 15; } catch (e) {} for (const lang in patterns) { patterns[lang].forEach(rx => { if (rx.test(code)) scores[lang] = (scores[lang] || 0) + 4; }); } let maxScore = 0, detected = 'javascript'; for (const lang in scores) { if (scores[lang] > maxScore) { maxScore = scores[lang]; detected = lang; } } editors[id].language = detected; updateLangBadge(id, detected); return detected; } function updateLangBadge(id, lang) { const config = languageConfig[lang] || { text: lang.toUpperCase(), ext: '.txt' }; if (id === 1) { const studioBadge = document.getElementById('studioDetectedBadge'); studioBadge.textContent = config.text; studioBadge.classList.remove('hidden'); document.getElementById('fileExtBadge1').textContent = config.ext; // Dynamically update the 3rd contextual button updateContextualActionButton(lang); } else { const multiBadge = document.getElementById('detectedLang' + id); if (multiBadge) multiBadge.textContent = `(${config.text})`; } } function validateSyntaxRealtime(id) { const input = document.getElementById('inputCode' + id).value.trim(); const statusEl = document.getElementById('studioSyntaxStatus'); if (!statusEl) return; if (!input) { statusEl.innerHTML = `Sintaxe Pronta`; statusEl.className = 'absolute bottom-3 right-3 text-[11px] font-mono px-2.5 py-1 rounded-lg bg-gray-500/10 text-gray-400 border border-gray-500/20 flex items-center gap-1.5 backdrop-blur-md'; return; } const lang = editors[id].language || 'javascript'; let isValid = true; let errorMsg = ''; if (lang === 'json') { try { JSON.parse(input); } catch (e) { isValid = false; errorMsg = e.message; } } else if (lang === 'xml' || lang === 'svg') { const parser = new DOMParser(); const doc = parser.parseFromString(input, 'application/xml'); const err = doc.querySelector('parsererror'); if (err) { isValid = false; errorMsg = 'Erro de tags XML/SVG não balanceadas'; } } if (isValid) { statusEl.innerHTML = `✓ Sintaxe Válida`; statusEl.className = 'absolute bottom-3 right-3 text-[11px] font-mono px-2.5 py-1 rounded-lg bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 flex items-center gap-1.5 backdrop-blur-md'; } else { statusEl.innerHTML = `⚠ Erro: ${errorMsg}`; statusEl.className = 'absolute bottom-3 right-3 text-[11px] font-mono px-2.5 py-1 rounded-lg bg-rose-500/10 text-rose-400 border border-rose-500/20 flex items-center gap-1.5 backdrop-blur-md'; } } function handleStudioInput() { detectLanguage(1); validateSyntaxRealtime(1); } function setStudioLanguage(lang) { if (lang === 'auto') { editors[1].manualLanguage = null; detectLanguage(1); } else { editors[1].manualLanguage = lang; editors[1].language = lang; updateLangBadge(1, lang); } if (editors[1].rawCode) displayOutput(1, editors[1].rawCode); } function setMultiLanguage(id, lang) { if (lang === 'auto') { editors[id].manualLanguage = null; detectLanguage(id); } else { editors[id].manualLanguage = lang; editors[id].language = lang; updateLangBadge(id, lang); } if (editors[id].rawCode) displayOutput(id, editors[id].rawCode); } // ========================================== // OUTPUT DISPLAY & SYNTAX HIGHLIGHTING // ========================================== function displayOutput(id, code) { const codeEl = id === 1 ? document.getElementById('outputCode1') : document.getElementById('outputCode' + id); const multiCodeEl = id === 1 ? document.getElementById('outputCodeMulti1') : null; if (!code) { const placeholder = '// Resultado...'; if (codeEl) codeEl.innerHTML = placeholder; if (multiCodeEl) multiCodeEl.innerHTML = placeholder; return; } try { const lang = editors[id].language || 'javascript'; const hljsLang = languageConfig[lang]?.hljs || 'plaintext'; const result = hljs.highlight(code, { language: hljsLang, ignoreIllegals: true }); if (codeEl) { codeEl.innerHTML = result.value; codeEl.className = 'hljs mono-font text-xs leading-relaxed language-' + hljsLang; } if (multiCodeEl) { multiCodeEl.innerHTML = result.value; multiCodeEl.className = 'hljs mono-font text-xs leading-relaxed language-' + hljsLang; } } catch (e) { if (codeEl) codeEl.textContent = code; if (multiCodeEl) multiCodeEl.textContent = code; } } // ========================================== // STATS & METRICS ENGINE // ========================================== async function updateStats(id, input, output) { const originalBytes = new Blob([input]).size; const finalBytes = new Blob([output]).size; const deltaBytes = originalBytes - finalBytes; const diff = ((deltaBytes) / originalBytes * 100) || 0; const origLines = input ? input.split('\n').length : 0; const finalLines = output ? output.split('\n').length : 0; // Estimate gzip size let gzipBytes = Math.round(finalBytes * 0.35); try { if (window.CompressionStream && output) { const stream = new Blob([output]).stream().pipeThrough(new CompressionStream('gzip')); const res = await new Response(stream); const blob = await res.blob(); gzipBytes = blob.size; } } catch (e) {} // Estimate mobile network savings (4G = ~15Mbps, 3G = ~750kbps) const ms4G = deltaBytes > 0 ? Math.round((deltaBytes * 8) / (15 * 1024)) : 0; const ms3G = deltaBytes > 0 ? Math.round((deltaBytes * 8) / (0.75 * 1024)) : 0; if (id === 1) { document.getElementById('originalSize1').textContent = formatBytes(originalBytes); document.getElementById('originalChars1').textContent = `${input.length.toLocaleString()} caracteres`; document.getElementById('finalSize1').textContent = formatBytes(finalBytes); document.getElementById('finalChars1').textContent = `${output.length.toLocaleString()} caracteres`; const diffEl = document.getElementById('sizeDiff1'); const badgeEl = document.getElementById('reductionBadge'); if (diff > 0) { diffEl.textContent = `-${diff.toFixed(1)}%`; diffEl.className = 'text-base font-bold text-emerald-400 mt-0.5'; badgeEl.textContent = `${formatBytes(deltaBytes)} economizados`; badgeEl.className = 'text-[10px] text-emerald-400 font-mono'; } else if (diff < 0) { diffEl.textContent = `+${Math.abs(diff).toFixed(1)}%`; diffEl.className = 'text-base font-bold text-rose-400 mt-0.5'; badgeEl.textContent = `${formatBytes(Math.abs(deltaBytes))} adicionados`; badgeEl.className = 'text-[10px] text-rose-400 font-mono'; } else { diffEl.textContent = '0%'; diffEl.className = 'text-base font-bold text-gray-400 mt-0.5'; badgeEl.textContent = 'Tamanho inalterado'; badgeEl.className = 'text-[10px] text-gray-500 font-mono'; } document.getElementById('lineCount1').textContent = `${origLines} → ${finalLines}`; const lineDiff = origLines - finalLines; document.getElementById('lineDiffPercent').textContent = lineDiff > 0 ? `-${lineDiff} linhas reduzidas` : `${lineDiff} linhas`; document.getElementById('gzipSize1').textContent = formatBytes(gzipBytes); document.getElementById('networkSavings1').textContent = deltaBytes > 0 ? `~${ms4G}ms (4G)` : '0 ms'; } // Update Multi Cards const origEl = document.getElementById(id === 1 ? 'multiOriginalSize1' : 'originalSize' + id); const finEl = document.getElementById(id === 1 ? 'multiFinalSize1' : 'finalSize' + id); const diffMultiEl = document.getElementById(id === 1 ? 'multiSizeDiff1' : 'sizeDiff' + id); const lineMultiEl = document.getElementById(id === 1 ? 'multiLineCount1' : 'lineCount' + id); if (origEl) origEl.textContent = formatBytes(originalBytes); if (finEl) finEl.textContent = formatBytes(finalBytes); if (diffMultiEl) { diffMultiEl.textContent = diff > 0 ? `-${diff.toFixed(1)}%` : (diff < 0 ? `+${Math.abs(diff).toFixed(1)}%` : '0%'); diffMultiEl.className = diff > 0 ? 'font-bold text-green-400' : (diff < 0 ? 'font-bold text-red-400' : 'font-bold text-gray-400'); } if (lineMultiEl) lineMultiEl.textContent = `${origLines} → ${finalLines}`; } function updateMultiStatsFromStudio(id) { const input = document.getElementById('inputCode1').value; const output = editors[id].rawCode; if (input && output) updateStats(id, input, output); } function formatBytes(bytes) { if (bytes === 0) return '0 B'; const k = 1024, sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; } // ========================================== // VISUAL DIFF VIEWER // ========================================== function renderDiff(id) { const original = editors[id].originalCode || document.getElementById('inputCode' + id).value; const modified = editors[id].rawCode; const container = document.getElementById('diffContent'); if (!original && !modified) { container.innerHTML = '
Insira e processe algum código para ver o comparador visual.
'; return; } const diffLines = computeDiffLines(original, modified); let addedCount = 0; let removedCount = 0; let html = ''; diffLines.forEach(item => { let badgeClass = 'diff-same'; let symbol = ' '; if (item.type === 'add') { badgeClass = 'diff-add'; symbol = '+'; addedCount++; } else if (item.type === 'del') { badgeClass = 'diff-del'; symbol = '-'; removedCount++; } const lineA = item.lineA !== null ? item.lineA : ''; const lineB = item.lineB !== null ? item.lineB : ''; html += `
${lineA}
${lineB}
${symbol}
${escapeHtml(item.text)}
`; }); container.innerHTML = html; document.getElementById('diffAddedCount').textContent = addedCount; document.getElementById('diffRemovedCount').textContent = removedCount; } function computeDiffLines(textA, textB) { const linesA = textA.split('\n'); const linesB = textB.split('\n'); const m = linesA.length; const n = linesB.length; if (m > 800 || n > 800) { return [{ type: 'same', lineA: 1, lineB: 1, text: '// Código muito extenso para renderizar diff interativo (> 800 linhas).' }]; } const dp = Array.from({ length: m + 1 }, () => new Int32Array(n + 1)); for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (linesA[i] === linesB[j]) { dp[i + 1][j + 1] = dp[i][j] + 1; } else { dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]); } } } let i = m, j = n; const diff = []; while (i > 0 || j > 0) { if (i > 0 && j > 0 && linesA[i - 1] === linesB[j - 1]) { diff.unshift({ type: 'same', lineA: i, lineB: j, text: linesA[i - 1] }); i--; j--; } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) { diff.unshift({ type: 'add', lineA: null, lineB: j, text: linesB[j - 1] }); j--; } else if (i > 0 && (j === 0 || dp[i][j - 1] < dp[i - 1][j])) { diff.unshift({ type: 'del', lineA: i, lineB: null, text: linesA[i - 1] }); i--; } } return diff; } function escapeHtml(str) { return str .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } // ========================================== // LIVE PREVIEW (HTML, SVG, MARKDOWN) // ========================================== function renderLivePreview() { const lang = editors[1].language || 'html'; const code = editors[1].rawCode || document.getElementById('inputCode1').value; const iframe = document.getElementById('livePreviewFrame'); const emptyState = document.getElementById('previewEmptyState'); if (!code || (lang !== 'html' && lang !== 'svg' && lang !== 'markdown')) { emptyState.classList.remove('hidden'); iframe.srcdoc = ''; return; } emptyState.classList.add('hidden'); let docContent = ''; if (lang === 'svg') { docContent = ` ${code} `; } else if (lang === 'html') { docContent = code; } else if (lang === 'markdown') { docContent = `
${escapeHtml(code)}
`; } iframe.srcdoc = docContent; } // ========================================== // FILE DOWNLOAD, COPY & SWAP // ========================================== function copyOutput(id) { const output = editors[id].rawCode; if (!output) { showToast('Nenhum resultado para copiar!', 'warning'); return; } navigator.clipboard.writeText(output).then(() => { showToast(`Código do Editor ${id} copiado!`, 'success'); }).catch(() => { showToast('Falha ao acessar área de transferência', 'error'); }); } function downloadCode(id) { const output = editors[id].rawCode; if (!output || !output.trim()) { showToast('Nenhum código para baixar!', 'warning'); return; } const lang = editors[id].language || 'javascript'; const ext = languageConfig[lang]?.ext || '.txt'; const fileNameInput = id === 1 && state.viewMode === 'studio' ? document.getElementById('fileName1').value : (document.getElementById('fileNameMulti' + id)?.value || document.getElementById('fileName' + id)?.value || 'output' + id); const fullFileName = fileNameInput.endsWith(ext) ? fileNameInput : (fileNameInput + ext); const blob = new Blob([output], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fullFileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); showToast(`Download iniciado: ${fullFileName}`, 'success'); } function swapCode(id) { const out = editors[id].rawCode; if (!out) { showToast('Nenhum resultado para inverter!', 'warning'); return; } if (id === 1 && state.viewMode === 'studio') { document.getElementById('inputCode1').value = out; } else { const multiInput = document.getElementById('inputCodeMulti' + id); if (multiInput) multiInput.value = out; document.getElementById('inputCode' + id).value = out; } editors[id].rawCode = ''; displayOutput(id, ''); detectLanguage(id); showToast(`Editor ${id}: Saída invertida para entrada!`, 'success'); } function clearEditor(id) { if (id === 1 && state.viewMode === 'studio') { document.getElementById('inputCode1').value = ''; document.getElementById('fileName1').value = 'bundle.min'; } const multiIn = document.getElementById('inputCodeMulti' + id); if (multiIn) multiIn.value = ''; const inEl = document.getElementById('inputCode' + id); if (inEl) inEl.value = ''; displayOutput(id, ''); editors[id] = { language: 'javascript', manualLanguage: null, rawCode: '', originalCode: '' }; updateStats(id, '', ''); if (id === 1) { document.getElementById('studioDetectedBadge').classList.add('hidden'); document.getElementById('diffContent').innerHTML = '
Editor limpo.
'; } showToast(`Editor ${id} limpo!`, 'info'); } // ========================================== // BATCH ZIP DOWNLOAD (JSZip) // ========================================== async function downloadAllZip() { if (!window.JSZip) { showToast('Biblioteca JSZip carregando...', 'warning'); return; } const zip = new JSZip(); let count = 0; const summary = []; [1, 2, 3].forEach(id => { const out = editors[id].rawCode; if (out && out.trim()) { const rawName = document.getElementById('fileNameMulti' + id)?.value || document.getElementById('fileName' + id)?.value || `output${id}`; const lang = editors[id].language || 'javascript'; const ext = languageConfig[lang]?.ext || '.txt'; const fileName = rawName.endsWith(ext) ? rawName : (rawName + ext); zip.file(fileName, out); count++; summary.push(`- ${fileName} (${formatBytes(new Blob([out]).size)}) [${lang.toUpperCase()}]`); } }); if (count === 0) { showToast('Nenhum código processado nos editores para baixar no ZIP!', 'warning'); return; } const manifest = `===================================================== 4U CODE OPTIMIZER - BATCH EXPORT BUNDLE ===================================================== Data: ${new Date().toLocaleString()} Total de arquivos exportados: ${count} Arquivos: ${summary.join('\n')} Gerado por 4U Code Optimizer (https://4u.ia.br/app/minifier/) =====================================================`; zip.file('README_4U_BUNDLE.txt', manifest); try { const blob = await zip.generateAsync({ type: 'blob' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `4u-code-bundle-${new Date().toISOString().slice(0, 10)}.zip`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); showToast(`ZIP gerado com sucesso (${count} arquivos)!`, 'success'); } catch (e) { showToast(`Erro ao gerar ZIP: ${e.message}`, 'error'); } } function minifyAll() { let processed = 0; [1, 2, 3].forEach(id => { const inVal = document.getElementById('inputCodeMulti' + id)?.value || document.getElementById('inputCode' + id)?.value; if (inVal && inVal.trim()) { minifyCode(id); processed++; } }); if (processed === 0) showToast('Nenhum código encontrado para minificar!', 'warning'); } function beautifyAll() { let processed = 0; [1, 2, 3].forEach(id => { const inVal = document.getElementById('inputCodeMulti' + id)?.value || document.getElementById('inputCode' + id)?.value; if (inVal && inVal.trim()) { beautifyCode(id); processed++; } }); if (processed === 0) showToast('Nenhum código encontrado para formatar!', 'warning'); } function clearAll() { [1, 2, 3].forEach(id => clearEditor(id)); showToast('Todos os editores foram limpos!', 'info'); } // ========================================== // DRAG & DROP AND CLIPBOARD // ========================================== function setupDragAndDrop() { const studioDrop = document.getElementById('studioDropZone'); attachDropZoneEvents(studioDrop, 1); [1, 2, 3].forEach(id => { const el = document.getElementById('dropZone' + id); if (el) attachDropZoneEvents(el, id); }); } function attachDropZoneEvents(dropEl, id) { if (!dropEl) return; ['dragenter', 'dragover'].forEach(name => { dropEl.addEventListener(name, (e) => { e.preventDefault(); e.stopPropagation(); dropEl.classList.add('dragover'); }); }); ['dragleave', 'drop'].forEach(name => { dropEl.addEventListener(name, (e) => { e.preventDefault(); e.stopPropagation(); dropEl.classList.remove('dragover'); }); }); dropEl.addEventListener('drop', (e) => { const files = e.dataTransfer.files; if (files.length > 0) handleFile(id, files[0]); }); } function handleFileSelect(id, e) { const files = e.target.files; if (files.length > 0) handleFile(id, files[0]); } function handleFile(id, file) { const fileName = file.name; const ext = fileName.substring(fileName.lastIndexOf('.')).toLowerCase(); const baseName = fileName.substring(0, fileName.lastIndexOf('.')); if (id === 1 && state.viewMode === 'studio') { document.getElementById('fileName1').value = baseName + '.min'; } const multiFileName = document.getElementById('fileNameMulti' + id); if (multiFileName) multiFileName.value = baseName + '.min'; if (extensionToLanguage[ext]) { const targetLang = extensionToLanguage[ext]; editors[id].manualLanguage = targetLang; editors[id].language = targetLang; if (id === 1) { document.getElementById('studioLangSelect').value = targetLang; updateLangBadge(1, targetLang); } const multiSelect = document.getElementById('langSelect' + id); if (multiSelect) multiSelect.value = targetLang; } const reader = new FileReader(); reader.onload = function(e) { const content = e.target.result; if (id === 1 && state.viewMode === 'studio') { document.getElementById('inputCode1').value = content; handleStudioInput(); } const multiIn = document.getElementById('inputCodeMulti' + id); if (multiIn) multiIn.value = content; const inEl = document.getElementById('inputCode' + id); if (inEl) inEl.value = content; detectLanguage(id); showToast(`Arquivo "${fileName}" carregado!`, 'success'); }; reader.readAsText(file); } async function pasteFromClipboard(id) { try { const text = await navigator.clipboard.readText(); if (id === 1 && state.viewMode === 'studio') { document.getElementById('inputCode1').value = text; handleStudioInput(); } else { document.getElementById('inputCodeMulti' + id).value = text; detectLanguage(id); } showToast('Conteúdo colado com sucesso!', 'success'); } catch (e) { showToast('Permissão de clipboard não concedida pelo navegador', 'warning'); } } function syncMultiInput(id) { if (id === 1) { document.getElementById('inputCode1').value = document.getElementById('inputCodeMulti1').value; } detectLanguage(id); } function syncFilename(id, val) { if (id === 1) document.getElementById('fileName1').value = val; } // ========================================== // OPTIONS MODAL & STORAGE // ========================================== function toggleSettingsModal() { const modal = document.getElementById('settingsModal'); modal.classList.toggle('hidden'); } function toggleTutorialModal() { const modal = document.getElementById('tutorialModal'); modal.classList.toggle('hidden'); } // Close modals on Escape key document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { const tut = document.getElementById('tutorialModal'); const set = document.getElementById('settingsModal'); if (tut && !tut.classList.contains('hidden')) tut.classList.add('hidden'); if (set && !set.classList.contains('hidden')) set.classList.add('hidden'); } }); function saveOptions() { state.options.removeConsole = document.getElementById('optRemoveConsole').checked; state.options.keepLicense = document.getElementById('optKeepLicense').checked; state.options.sortJsonKeys = document.getElementById('optSortJsonKeys').checked; state.options.indentSize = document.getElementById('optIndentSize').value; localStorage.setItem('4u_minifier_opts', JSON.stringify(state.options)); showToast('Preferências salvas!', 'info'); } function loadSavedOptions() { try { const saved = localStorage.getItem('4u_minifier_opts'); if (saved) { state.options = Object.assign(state.options, JSON.parse(saved)); document.getElementById('optRemoveConsole').checked = state.options.removeConsole; document.getElementById('optKeepLicense').checked = state.options.keepLicense; document.getElementById('optSortJsonKeys').checked = state.options.sortJsonKeys; document.getElementById('optIndentSize').value = state.options.indentSize; } } catch (e) {} } function saveStateToStorage() { try { const sessionData = { input1: document.getElementById('inputCode1').value, output1: editors[1].rawCode, lang1: editors[1].language }; localStorage.setItem('4u_minifier_session', JSON.stringify(sessionData)); } catch (e) {} } // ========================================== // TOAST NOTIFICATIONS // ========================================== let toastTimeout; function showToast(message, type = 'success') { const toast = document.getElementById('toast'); const toastMsg = document.getElementById('toastMessage'); const toastIcon = document.getElementById('toastIcon'); toastMsg.textContent = message; if (type === 'error') { toastIcon.className = 'w-6 h-6 rounded-full bg-rose-500/20 text-rose-400 flex items-center justify-center flex-shrink-0'; toastIcon.innerHTML = ''; } else if (type === 'warning') { toastIcon.className = 'w-6 h-6 rounded-full bg-amber-500/20 text-amber-400 flex items-center justify-center flex-shrink-0'; toastIcon.innerHTML = ''; } else { toastIcon.className = 'w-6 h-6 rounded-full bg-emerald-500/20 text-emerald-400 flex items-center justify-center flex-shrink-0'; toastIcon.innerHTML = ''; } toast.classList.remove('hidden'); clearTimeout(toastTimeout); toastTimeout = setTimeout(() => { toast.classList.add('hidden'); }, 3000); }