(function() { var form = document.getElementById('newemail-form'); if (!form) return; function post(path, params) { return fetch(path, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(params || {}).toString() }).then(function(r) { return r.json(); }); } function navigateTo(url) { var a = document.createElement('a'); a.href = url; document.body.appendChild(a); a.click(); document.body.removeChild(a); } var body = document.getElementById('newemail-body'); var toolbar = document.getElementById('newemail-toolbar'); toolbar.addEventListener('click', function(e) { var btn = e.target.closest('button'); if (!btn) return; body.focus(); var cmd = btn.getAttribute('data-cmd'); if (cmd === 'createLink') { var url = window.prompt('Link URL:'); if (url) document.execCommand('createLink', false, url); } else { document.execCommand(cmd, false, null); } }); var errorDiv = document.getElementById('newemail-error'); var sendBtn = document.getElementById('newemail-send-btn'); var cancelBtn = document.getElementById('newemail-cancel-btn'); cancelBtn.addEventListener('click', function() { navigateTo('/admin/email'); }); sendBtn.addEventListener('click', function() { var to = document.getElementById('newemail-to').value.trim(); var subject = document.getElementById('newemail-subject').value.trim(); var html = body.innerHTML.trim(); errorDiv.textContent = ''; if (!to) { errorDiv.textContent = 'A recipient address is required.'; return; } if (!html) { errorDiv.textContent = 'The message body is empty.'; return; } sendBtn.classList.add('newemail-sending'); post('/email/send', { to: to, subject: subject, body: html }) .then(function(res) { sendBtn.classList.remove('newemail-sending'); if (!res.ok) { errorDiv.textContent = res.error || 'Could not send the message.'; return; } navigateTo('/admin/email'); }) .catch(function() { sendBtn.classList.remove('newemail-sending'); errorDiv.textContent = 'Could not send the message.'; }); }); })();