'use strict'; document.addEventListener('DOMContentLoaded', function () { initializeEmailList(); }); function initializeEmailList() { var emailItems = document.querySelectorAll('.email-item'); emailItems.forEach(function (item) { var summary = item.querySelector('.email-summary'); var downloadButton = item.querySelector('.download-icon'); if (summary) { summary.addEventListener('click', function (event) { if (event.target.closest('.download-icon')) { return; } toggleEmail(item); }); summary.addEventListener('keydown', function (event) { if ( event.key !== 'Enter' && event.key !== ' ' ) { return; } if (event.target.closest('.download-icon')) { return; } event.preventDefault(); toggleEmail(item); }); } if (downloadButton) { downloadButton.addEventListener('click', function (event) { event.stopPropagation(); var id = item.dataset.id; if (!id) { console.error('Email ID is missing'); return; } downloadEmail(event, id); }); } }); } function toggleEmail(item) { var id = item.dataset.id; if (!id) { console.error('Email ID is missing'); return; } var summary = item.querySelector('.email-summary'); var detail = item.querySelector('.email-detail'); var toggleIcon = item.querySelector('.toggle'); var iframe = item.querySelector('.email-content-frame'); if (!detail || !iframe) { console.error( 'Email UI elements are missing for:', id ); return; } var isHidden = detail.classList.contains('hidden'); if (isHidden) { detail.classList.remove('hidden'); if (toggleIcon) { toggleIcon.classList.add('rotated'); } if (summary) { summary.setAttribute( 'aria-expanded', 'true' ); } loadEmailContent( id, iframe ); } else { detail.classList.add('hidden'); if (toggleIcon) { toggleIcon.classList.remove('rotated'); } if (summary) { summary.setAttribute( 'aria-expanded', 'false' ); } } } function loadEmailContent(id, iframe) { if (iframe.dataset.loaded === 'true') { resizeIframe(iframe); return; } iframe.dataset.loading = 'true'; fetch( '/api/view?id=' + encodeURIComponent(id), { method: 'GET', credentials: 'same-origin' } ) .then(function (response) { if (!response.ok) { throw new Error( 'HTTP error ' + response.status ); } return response.text(); }) .then(function (data) { writeEmailToIframe( iframe, data ); iframe.dataset.loaded = 'true'; delete iframe.dataset.loading; resizeIframe(iframe); }) .catch(function (error) { delete iframe.dataset.loading; writeErrorToIframe( iframe, error.message ); console.error( 'Failed to load email:', id, error ); }); } function writeEmailToIframe(iframe, emailBody) { var doc = iframe.contentWindow.document; doc.open(); doc.write( '' + '' + '
' + '' + '' + '