document.addEventListener('DOMContentLoaded', () => { // --- 1. DOM REFERENCES --- const qrContainer = document.getElementById('qr-container'); const downloadBtn = document.getElementById('btn-download'); const stickyWrapper = document.querySelector('.sticky-wrapper'); // Gauge Elements const capMeter = document.getElementById('capacity-meter'); const capBar = document.getElementById('capacity-bar'); const capText = document.getElementById('capacity-text'); const capLabel = document.getElementById('capacity-label'); // Inputs const modeSelector = document.getElementById('mode-selector'); const optEcc = document.getElementById('opt-ecc'); const optSize = document.getElementById('opt-size'); const optFg = document.getElementById('opt-fg'); const optBg = document.getElementById('opt-bg'); const hexFg = document.getElementById('hex-fg'); const hexBg = document.getElementById('hex-bg'); const fmtRadios = document.getElementsByName('opt-fmt'); let debounceTimer; // --- 2. STATE GETTERS (Pure Functions) --- function getFormat() { for (const r of fmtRadios) { if (r.checked) return r.value; } return 'png'; } function getDataString() { const mode = modeSelector.value; if (mode === 'text') { return document.getElementById('inp-text').value; } else if (mode === 'wifi') { const ssid = document.getElementById('inp-wifi-ssid').value; const pass = document.getElementById('inp-wifi-pass').value; const type = document.getElementById('inp-wifi-type').value; // Note: Even if empty, we return the structure so the logic can decide if (!ssid) return ''; const cleanSSID = ssid.replace(/([\\;,:])/g, '\\$1'); const cleanPass = pass.replace(/([\\;,:])/g, '\\$1'); return `WIFI:S:${cleanSSID};T:${type};P:${cleanPass};;`; } else if (mode === 'email') { const to = document.getElementById('inp-email-to').value; const sub = document.getElementById('inp-email-sub').value; const body = document.getElementById('inp-email-body').value; if (!to) return ''; return `mailto:${to}?subject=${encodeURIComponent(sub)}&body=${encodeURIComponent(body)}`; } return ''; } // --- 3. RENDER HELPERS --- function generateSVGString(modules, size, fg, bg) { const count = modules.length; const modSize = size / count; let pathData = ''; for (let r = 0; r < count; r++) { for (let c = 0; c < count; c++) { if (modules[r][c]) { const x = c * modSize; const y = r * modSize; pathData += `M${x},${y}h${modSize}v${modSize}h-${modSize}z`; } } } return ` `; } function renderError(title, subtitle) { qrContainer.innerHTML = `
ERROR: ${title}
${subtitle}
`; downloadBtn.disabled = true; downloadBtn.textContent = "GENERATION FAILED"; stickyWrapper.classList.add('has-error'); } // --- 4. CORE LOGIC --- // A. Capacity Gauge (Fast / Instant) function updateCapacityUI(textData) { if (!textData) { capMeter.style.display = 'none'; return; } const blob = new Blob([textData]); const bytes = blob.size; // Limits based on Version 40 (Byte Mode) const maxCapacityMap = { 'L': 2950, 'M': 2328, 'Q': 1660, 'H': 1270 }; const maxBytes = maxCapacityMap[optEcc.value] || 1270; const raw_usage = Math.round((bytes / maxBytes) * 100); const usage = Math.min(100, raw_usage); if (usage > 50) { capMeter.style.display = 'block'; capBar.style.width = `${usage}%`; capText.textContent = `${usage}% (${bytes} / ${maxBytes} B)`; if (raw_usage <= 100) { capLabel.textContent = 'CAPACITY'; } else { capLabel.textContent = 'OVER CAPACITY'; } if (usage > 90) { capBar.style.backgroundColor = 'red'; capText.style.color = 'red'; capLabel.style.color = 'red'; } else { capBar.style.backgroundColor = '#000'; capText.style.color = '#000'; capLabel.style.color = '#000'; } } else { capMeter.style.display = 'none'; } } // B. The Main Renderer (Stateless: Flush and Rebuild) function renderQR() { // 1. Gather State const textData = getDataString(); const format = getFormat(); const ecc = QRCode.CorrectLevel[optEcc.value]; const colorDark = optFg.value; const colorLight = optBg.value; hexFg.textContent = colorDark; hexBg.textContent = colorLight; // 2. Reset DOM qrContainer.innerHTML = ''; stickyWrapper.classList.remove('has-error'); // 3. Handle Empty State if (!textData || textData.trim() === '') { downloadBtn.disabled = true; downloadBtn.textContent = `DOWNLOAD ${format.toUpperCase()}`; return; } downloadBtn.textContent = `DOWNLOAD ${format.toUpperCase()}`; // 4. Validate Size let size = parseInt(optSize.value) || 256; if (size < 64) size = 64; if (size > 4000) size = 4000; // 5. Generate try { const instance = new QRCode(qrContainer, { text: textData, width: size, height: size, colorDark : colorDark, colorLight : colorLight, correctLevel : ecc }); // 6. Post-Process if (format === 'svg') { const modules = instance._oQRCode.modules; const nodes = qrContainer.childNodes; for(let i=0; i= because sometimes overhead pushes it over even if bytes == maxBytes) if (bytes >= maxBytes) { renderError( "CAPACITY EXCEEDED", "REDUCE TEXT OR LOWER ECC LEVEL" ); } else { // If usage is low but it crashed, it's a real bug (e.g. invalid char code). // Show the specific error for debugging. console.error(e); // Keep looking at console for devs renderError( "UNKNOWN ERROR", `CODE: ${e.name || 'Except'} // ${e.message || 'Check Console'}` ); } } } // --- 5. EVENT ORCHESTRATION --- function handleUpdate(immediate = false) { const text = getDataString(); // Always update gauge immediately updateCapacityUI(text); // Debounce the heavy rendering clearTimeout(debounceTimer); if (immediate) { renderQR(); } else { debounceTimer = setTimeout(renderQR, 300); } } // --- 6. LISTENERS --- // Configuration Inputs (Colors, ECC, Size) -> Trigger Rebuild [optEcc, optSize, optFg, optBg].forEach(el => { el.addEventListener('input', () => handleUpdate(false)); }); // Format Change -> Trigger Rebuild (Instant) fmtRadios.forEach(r => r.addEventListener('change', () => handleUpdate(true))); // Mode Switch -> Change Form & Rebuild modeSelector.addEventListener('change', (e) => { const newMode = e.target.value; document.querySelectorAll('.input-form').forEach(f => f.classList.remove('active')); document.getElementById(`form-${newMode}`).classList.add('active'); handleUpdate(true); }); // Data Entry -> Debounced Rebuild document.querySelectorAll('.input-form').forEach(form => { form.addEventListener('input', () => handleUpdate(false)); }); // Download Handler downloadBtn.addEventListener('click', () => { const format = getFormat(); if (format === 'png') { const img = qrContainer.querySelector('img'); if (img && img.src) { const link = document.createElement('a'); link.href = img.src; link.download = `qr-manifesto-${Date.now()}.png`; document.body.appendChild(link); link.click(); link.remove(); } } else { const svgEl = qrContainer.querySelector('svg'); if (svgEl) { const serializer = new XMLSerializer(); const svgString = serializer.serializeToString(svgEl); const blob = new Blob([svgString], {type: 'image/svg+xml;charset=utf-8'}); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `qr-manifesto-${Date.now()}.svg`; document.body.appendChild(link); link.click(); link.remove(); } } }); // Initial Render handleUpdate(true); });