814 lines
40 KiB
JavaScript
814 lines
40 KiB
JavaScript
let connectedMailAccount = null;
|
||
let mailPageOffset = 0;
|
||
let mailTotal = 0;
|
||
let mailboxSyncPromise = null;
|
||
let mailboxSyncQueued = false;
|
||
let mailboxRefreshPending = false;
|
||
let folderBeforeSearch = null;
|
||
|
||
const senderBrandDomains = {
|
||
amazon: ['amazon.com', 'amazon.co.uk'],
|
||
apple: ['apple.com', 'icloud.com'],
|
||
google: ['google.com', 'gmail.com'],
|
||
microsoft: ['microsoft.com', 'outlook.com', 'live.com'],
|
||
paypal: ['paypal.com']
|
||
};
|
||
|
||
function suspiciousSenderReasons(message) {
|
||
const email = String(message.email || '').trim().toLowerCase();
|
||
const domain = email.split('@').pop() || '';
|
||
if (!domain) return [];
|
||
const reasons = [];
|
||
if (domain.includes('xn--')) reasons.push('The sender address uses an internationalized domain that may imitate another domain.');
|
||
const name = String(message.sender || '').toLowerCase();
|
||
for (const [brand, domains] of Object.entries(senderBrandDomains)) {
|
||
const brandName = new RegExp(`^(?:the\\s+)?${brand}(?:\\s+(?:customer\\s+service|support|security|account|billing|team|payments?|services?))*$`, 'i');
|
||
if (brandName.test(name) && !domains.some(allowed => domain === allowed || domain.endsWith(`.${allowed}`))) {
|
||
reasons.push(`The display name mentions ${brand}, but the sender domain is ${domain}.`);
|
||
}
|
||
}
|
||
if (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(name) && name.split('@').pop() !== domain) {
|
||
reasons.push('The address-like display name does not match the actual sender domain.');
|
||
}
|
||
return [...new Set(reasons)];
|
||
}
|
||
|
||
function inspectMailLink(raw) {
|
||
const cleaned = String(raw).replace(/[.,!?;:)\]}>"']+$/g, '');
|
||
let parsed;
|
||
try { parsed = new URL(cleaned); } catch { return null; }
|
||
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) return null;
|
||
const host = parsed.hostname.toLowerCase();
|
||
const reasons = [];
|
||
if (parsed.protocol === 'http:') reasons.push('unencrypted HTTP connection');
|
||
if (host.includes('xn--')) reasons.push('internationalized domain that may imitate another address');
|
||
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(host) || host.startsWith('[')) reasons.push('IP-address destination instead of a named website');
|
||
if (['bit.ly', 't.co', 'tinyurl.com', 'is.gd', 'lnkd.in'].includes(host)) reasons.push('shortened link hides its final destination');
|
||
for (const [brand, domains] of Object.entries(senderBrandDomains)) {
|
||
const mentionsBrand = new RegExp(`(^|[.-])${brand.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}([.-]|$)`, 'i').test(host);
|
||
if (mentionsBrand && !domains.some(domain => host === domain || host.endsWith(`.${domain}`))) {
|
||
reasons.push(`hostname mentions ${brand} without using its usual domain`);
|
||
}
|
||
}
|
||
return { url: parsed.href, host, reasons };
|
||
}
|
||
|
||
function messageLinks(message) {
|
||
const bodyLinks = (message.body || []).join('\n').match(/https?:\/\/[^\s<>"']+/gi) || [];
|
||
const declaredLinks = Array.isArray(message.links) ? message.links : [];
|
||
return [...new Set([...bodyLinks, ...declaredLinks])]
|
||
.map(inspectMailLink)
|
||
.filter(Boolean)
|
||
.slice(0, 30);
|
||
}
|
||
|
||
const originalOpenMessage = openMessage;
|
||
openMessage = function (id) {
|
||
originalOpenMessage(id);
|
||
const message = messages.find(item => item.id === id);
|
||
if (!message) return;
|
||
const senderReasons = suspiciousSenderReasons(message);
|
||
const links = messageLinks(message);
|
||
const warnings = [];
|
||
if (senderReasons.length) {
|
||
warnings.push(`<section class="mail-safety-warning" role="alert"><strong>Sender details may be misleading</strong><ul>${senderReasons.map(reason => `<li>${esc(reason)}</li>`).join('')}</ul><small>Sender names and addresses can be forged. Verify the sender through a trusted channel.</small></section>`);
|
||
}
|
||
const linkCards = links.map((link, index) => `
|
||
<div class="mail-link-row ${link.reasons.length ? 'mail-link-risky' : ''}">
|
||
<div><strong>${link.reasons.length ? 'Potentially unsafe link' : 'External link'}</strong><span>${esc(link.host)}</span>
|
||
${link.reasons.length ? `<small>${esc(link.reasons.join('; '))}</small>` : ''}</div>
|
||
<button type="button" class="mail-link-open" data-mail-link="${index}">Review & open</button>
|
||
</div>`).join('');
|
||
const reader = $('#reader-pane');
|
||
const header = reader.querySelector('.reader-header');
|
||
if (warnings.length && header) header.insertAdjacentHTML('afterend', warnings.join(''));
|
||
const replyBar = reader.querySelector('.reply-bar');
|
||
if (links.length && replyBar) {
|
||
replyBar.insertAdjacentHTML('beforebegin', `<section class="mail-links"><h3>Links in this message</h3>${links.some(link => link.reasons.length) ? '<p class="mail-safety-intro">Some links show warning signs. Every link requires confirmation before it opens.</p>' : ''}${linkCards}</section>`);
|
||
reader.querySelectorAll('[data-mail-link]').forEach(button => {
|
||
button.onclick = async () => {
|
||
const link = links[Number(button.dataset.mailLink)];
|
||
if (!link) return;
|
||
button.disabled = true;
|
||
try {
|
||
await window.daybreakMail.openExternal(link.url);
|
||
} catch (error) {
|
||
toast(error.message || 'Could not open this link');
|
||
} finally {
|
||
button.disabled = false;
|
||
}
|
||
};
|
||
});
|
||
}
|
||
};
|
||
|
||
let customFolders = [];
|
||
|
||
function renderCustomFolders() {
|
||
const box = $('#custom-folders');
|
||
if (!box) return;
|
||
box.replaceChildren(...customFolders.map(folder => {
|
||
const button = document.createElement('button');
|
||
button.className = 'folder custom-folder';
|
||
button.dataset.folder = folder.id;
|
||
button.classList.toggle('active', activeFolder === folder.id);
|
||
const glyph = document.createElement('span');
|
||
glyph.className = 'nav-glyph';
|
||
glyph.textContent = '▭';
|
||
const label = document.createElement('span');
|
||
label.textContent = folder.name;
|
||
button.title = folder.path;
|
||
button.append(glyph, label);
|
||
button.addEventListener('click', () => {
|
||
if ($('#filter-folder').value) { $('#filter-folder').value = ''; folderBeforeSearch = null; }
|
||
activeFolder = folder.id;
|
||
$$('.folder').forEach(item => item.classList.toggle('active', item === button));
|
||
$('#sidebar-title').textContent = folder.name;
|
||
$('#crumb-current').textContent = folder.name;
|
||
mailPageOffset = 0;
|
||
void syncMailbox(false, { offset: 0 });
|
||
});
|
||
return button;
|
||
}));
|
||
}
|
||
|
||
async function loadCustomFolders() {
|
||
if (!connectedMailAccount || !window.daybreakMail?.listFolders) return;
|
||
try {
|
||
customFolders = (await window.daybreakMail.listFolders()).folders || [];
|
||
renderCustomFolders();
|
||
} catch {}
|
||
}
|
||
|
||
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
|
||
function ruleFolderSelect(selected = 'Inbox') {
|
||
const options = [['Inbox', 'Inbox'], ['Archive', 'Archive'], ['Trash', 'Trash'], ...customFolders.map(folder => [folder.id, folder.name])];
|
||
if (!options.some(([value]) => value === selected)) {
|
||
options.push([selected, String(selected).replace(/^[^:]*:/, '') || selected]);
|
||
}
|
||
return '<select class="mail-rule-value" aria-label="Destination folder">' +
|
||
options.map(([value, name]) => '<option value="' + esc(value) + '"' + (value === selected ? ' selected' : '') + '>' + esc(name) + '</option>').join('') + '</select>';
|
||
}
|
||
|
||
// window.prompt() is not available in Electron, so ask for text in an in-app dialog.
|
||
function askText(title, label, placeholder = '') {
|
||
return new Promise(resolve => {
|
||
const overlay = document.createElement('div');
|
||
overlay.className = 'modal-overlay pgp-prompt';
|
||
overlay.innerHTML = '<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><label class="compose-line"><span></span><input type="text" maxlength="200"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">OK</button></div></form>';
|
||
overlay.querySelector('.modal-head span').textContent = title;
|
||
overlay.querySelector('.compose-line span').textContent = label;
|
||
const input = overlay.querySelector('input');
|
||
input.placeholder = placeholder;
|
||
const finish = value => { overlay.remove(); resolve(value); };
|
||
overlay.querySelector('form').onsubmit = event => { event.preventDefault(); finish(input.value.trim() || null); };
|
||
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
||
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
||
document.body.append(overlay);
|
||
input.focus();
|
||
});
|
||
}
|
||
|
||
async function createMailFolder() {
|
||
if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; }
|
||
const name = await askText('New mail folder', 'Name');
|
||
if (!name) return;
|
||
try {
|
||
const result = await window.daybreakMail.createFolder(name);
|
||
customFolders = result.folders || customFolders;
|
||
renderCustomFolders();
|
||
toast(`Folder “${result.folder?.name || name}” created`);
|
||
} catch (error) {
|
||
toast(error.message || 'Could not create the folder');
|
||
}
|
||
}
|
||
|
||
function updateAccountCard(account) {
|
||
const card = $('#account-settings');
|
||
if (!card) return;
|
||
const email = account.email || '';
|
||
const localName = (email.split('@')[0] || 'Mail account').replace(/[._-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase());
|
||
const displayName = account.displayName?.trim() || window.epMailFeatures.productivity?.profileName?.trim() || localName;
|
||
const initials = displayName.split(/\s+/).filter(Boolean).map(part => part[0]).join('').slice(0, 2);
|
||
card.querySelector('.account-avatar').textContent = initials || 'M';
|
||
card.querySelector('.account-info strong').textContent = displayName;
|
||
card.querySelector('.account-info span').textContent = email;
|
||
card.title = `${displayName} <${email}>`;
|
||
if (typeof renderLabels === 'function') renderLabels();
|
||
void loadCustomFolders();
|
||
card.querySelector('.online-dot').style.background = '#70ad7b';
|
||
const profileButton = $('.top-avatar');
|
||
if (profileButton) {
|
||
profileButton.textContent = initials || 'M';
|
||
profileButton.title = `${displayName} <${email}>`;
|
||
profileButton.setAttribute('aria-label', `${displayName} account settings`);
|
||
}
|
||
}
|
||
function openMailAccount(existingAccount = null) {
|
||
const root = $('#modal-root');
|
||
const editing = Boolean(existingAccount);
|
||
const displayName = existingAccount?.displayName || window.epMailFeatures.productivity?.profileName || '';
|
||
const ruleMarkup = (existingAccount?.rules || []).map(rule => `
|
||
<div class="mail-rule-row">
|
||
<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${esc(rule.senderContains || '')}">
|
||
<input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${esc(rule.subjectContains || '')}">
|
||
<select class="mail-rule-action" aria-label="Rule action">
|
||
${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')}
|
||
</select>
|
||
${rule.action==='move'
|
||
? `${ruleFolderSelect(rule.value)}`
|
||
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
|
||
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
||
</div>`).join('');
|
||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${esc(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${esc(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
||
const close = () => { root.innerHTML = ''; };
|
||
$$('.modal-close').forEach(button => button.onclick = close);
|
||
$('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
|
||
$('#disconnect-mail').onclick = close;
|
||
const addRuleRow = rule => {
|
||
const row = document.createElement('div');
|
||
row.className = 'mail-rule-row';
|
||
row.innerHTML = `<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${esc(rule?.senderContains || '')}"><input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${esc(rule?.subjectContains || '')}"><select class="mail-rule-action" aria-label="Rule action"><option value="archive">Archive</option><option value="move">Move to folder</option><option value="label">Apply label</option><option value="flag">Flag</option></select><input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule?.value || '')}"><button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>`;
|
||
row.querySelector('.mail-rule-action').value = rule?.action || 'archive';
|
||
$('#mail-rule-list').append(row);
|
||
};
|
||
$('#add-mail-rule').onclick = () => addRuleRow();
|
||
$('#mail-rule-list').onclick = event => {
|
||
if (event.target.closest('.remove-mail-rule')) event.target.closest('.mail-rule-row').remove();
|
||
};
|
||
$('#mail-rule-list').onchange = event => {
|
||
if (!event.target.matches('.mail-rule-action')) return;
|
||
const row = event.target.closest('.mail-rule-row');
|
||
const value = row.querySelector('.mail-rule-value');
|
||
if (event.target.value === 'move') {
|
||
const selected = value.value || 'Inbox';
|
||
value.outerHTML = ruleFolderSelect(selected);
|
||
} else if (value.tagName === 'SELECT') {
|
||
value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`;
|
||
}
|
||
row.querySelector('.mail-rule-value').disabled = event.target.value === 'flag';
|
||
};
|
||
$('#connect-mail').onclick = async () => {
|
||
const button = $('#connect-mail');
|
||
const status = $('#mail-account-status');
|
||
const password = $('#mail-account-password').value;
|
||
const name = $('#mail-account-display-name').value.trim();
|
||
if (!name) { status.textContent = 'Enter a display name for this mail account.'; $('#mail-account-display-name').focus(); return; }
|
||
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; }
|
||
button.disabled = true;
|
||
button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
||
status.textContent = editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.';
|
||
try {
|
||
const details = {
|
||
email: $('#mail-account-email').value,
|
||
password,
|
||
displayName: name,
|
||
imapHost: $('#mail-account-imap').value,
|
||
smtpHost: $('#mail-account-smtp').value,
|
||
signature: $('#mail-account-signature').value,
|
||
notificationsEnabled: $('#mail-account-notifications').checked,
|
||
syncIntervalMinutes: Number($('#mail-account-sync-interval').value),
|
||
rules: [...$('#mail-rule-list').querySelectorAll('.mail-rule-row')].map(row => ({
|
||
senderContains: row.querySelector('.mail-rule-sender').value,
|
||
subjectContains: row.querySelector('.mail-rule-subject').value,
|
||
action: row.querySelector('.mail-rule-action').value,
|
||
value: row.querySelector('.mail-rule-value').value
|
||
}))
|
||
};
|
||
const account = editing
|
||
? await window.daybreakMail.updateAccount(existingAccount.id, details)
|
||
: await window.daybreakMail.connect(details);
|
||
if (editing) {
|
||
const accountList = await window.daybreakMail.listAccounts();
|
||
if (accountList.activeId === account.id) {
|
||
connectedMailAccount = account;
|
||
updateAccountCard(account);
|
||
mailPageOffset = 0;
|
||
close();
|
||
await syncMailbox(false, { offset: 0 });
|
||
} else {
|
||
close();
|
||
}
|
||
toast('Mailbox settings updated');
|
||
} else {
|
||
connectedMailAccount = account;
|
||
updateAccountCard(account);
|
||
close();
|
||
toast('Mailbox connected securely');
|
||
await syncMailbox(true);
|
||
}
|
||
} catch (error) {
|
||
status.textContent = error.message || 'Could not connect. Check the account details and try again.';
|
||
button.disabled = false;
|
||
button.textContent = editing ? 'Save & reconnect' : 'Test & connect';
|
||
}
|
||
};
|
||
$('#mail-account-email').focus();
|
||
}
|
||
function mailSearchFilters() {
|
||
return {
|
||
query: $('#search').value.trim(),
|
||
sender: $('#filter-sender').value.trim(),
|
||
subject: $('#filter-subject').value.trim(),
|
||
after: $('#filter-after').value,
|
||
before: $('#filter-before').value,
|
||
hasAttachments: $('#filter-attachments').checked,
|
||
folder: $('#filter-folder').value
|
||
};
|
||
}
|
||
|
||
const selectedDraftIds = new Set();
|
||
|
||
async function deleteSelectedDrafts() {
|
||
const ids = messages.map(message => String(message.id)).filter(id => selectedDraftIds.has(id));
|
||
if (!ids.length) { toast('Select one or more drafts first'); return; }
|
||
if (!confirm(`Delete ${ids.length} selected draft${ids.length === 1 ? '' : 's'}?`)) return;
|
||
try {
|
||
for (const id of ids) await window.daybreakMail.deleteDraft(id);
|
||
selectedDraftIds.clear();
|
||
toast(`${ids.length} draft${ids.length === 1 ? '' : 's'} deleted`);
|
||
await syncMailbox(false);
|
||
} catch (error) { toast(error.message || 'Could not delete the drafts'); }
|
||
}
|
||
|
||
// In the Drafts folder the shared toolbar acts on drafts, which use string ids.
|
||
document.addEventListener('click', event => {
|
||
if (activeFolder !== 'Drafts') return;
|
||
const button = event.target.closest('#select-all, #delete-selected, #archive-selected, #mark-unread');
|
||
if (!button) return;
|
||
event.stopImmediatePropagation();
|
||
if (button.id === 'select-all') {
|
||
const ids = messages.map(message => String(message.id));
|
||
const all = ids.length && ids.every(id => selectedDraftIds.has(id));
|
||
ids.forEach(id => all ? selectedDraftIds.delete(id) : selectedDraftIds.add(id));
|
||
renderDrafts(messages.map(message => message.draft));
|
||
} else if (button.id === 'delete-selected') void deleteSelectedDrafts();
|
||
}, true);
|
||
|
||
function renderDrafts(drafts) {
|
||
const present = new Set(drafts.map(draft => String(draft.id)));
|
||
[...selectedDraftIds].forEach(id => { if (!present.has(id)) selectedDraftIds.delete(id); });
|
||
messages.splice(0, messages.length, ...drafts.map(draft => ({
|
||
id: draft.id,
|
||
sender: 'Draft',
|
||
email: draft.to || 'No recipient',
|
||
subject: draft.subject || '(no subject)',
|
||
snippet: String(draft.text || '').replace(/\s+/g, ' ').slice(0, 180) || 'No message text',
|
||
date: new Date(draft.updatedAt || Date.now()).toLocaleString(),
|
||
tags: ['Drafts'],
|
||
initials: 'D',
|
||
color: '#dce6df',
|
||
draft
|
||
})));
|
||
$('#message-list').innerHTML = messages.length ? messages.map(message => `
|
||
<div class="message" data-id="${esc(message.id)}"><input class="row-check" type="checkbox" aria-label="Select draft"${selectedDraftIds.has(String(message.id)) ? ' checked' : ''}><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
|
||
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div>
|
||
<div class="message-meta"><span class="time">${esc(message.date)}</span><button type="button" class="icon-button draft-delete" title="Delete draft" aria-label="Delete draft">⌫</button></div></div>`).join('') :
|
||
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
|
||
const start = $('#start-draft');
|
||
if (start) start.onclick = () => showCompose();
|
||
$$('.message').forEach(row => row.onclick = event => {
|
||
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft;
|
||
if (event.target.closest('.row-check')) {
|
||
event.stopPropagation();
|
||
const id = row.dataset.id;
|
||
selectedDraftIds.has(id) ? selectedDraftIds.delete(id) : selectedDraftIds.add(id);
|
||
return;
|
||
}
|
||
if (event.target.closest('.draft-delete')) {
|
||
event.stopPropagation();
|
||
if (!draft || !confirm('Delete this draft?')) return;
|
||
window.daybreakMail.deleteDraft(draft.id)
|
||
.then(() => { toast('Draft deleted'); return syncMailbox(false); })
|
||
.catch(error => toast(error.message || 'Could not delete the draft'));
|
||
return;
|
||
}
|
||
if (draft) showCompose(null, false, draft);
|
||
});
|
||
$('#reader-pane').innerHTML = emptyReader();
|
||
$('#pagination').textContent = `${messages.length} drafts`;
|
||
$('#load-more').classList.add('hidden');
|
||
}
|
||
|
||
function setupDraftComposer() {
|
||
const original = window.showCompose;
|
||
window.showCompose = (reply, forward = false, draft = null) => {
|
||
original(reply, forward);
|
||
const root = $('#modal-root');
|
||
const modal = root.querySelector('.compose-modal');
|
||
if (!modal) return;
|
||
modal.dataset.draftId = draft?.id || '';
|
||
let attachments = Array.isArray(draft?.attachments) ? draft.attachments : [];
|
||
modal._composeAttachments = attachments;
|
||
const fields = modal.querySelector('.compose-fields');
|
||
const attachmentRow = document.createElement('div');
|
||
attachmentRow.className = 'compose-line';
|
||
const attachmentLabel = document.createElement('span');
|
||
attachmentLabel.textContent = 'Attachments';
|
||
const attachmentControls = document.createElement('div');
|
||
attachmentControls.className = 'compose-attachments';
|
||
const attachmentInput = document.createElement('input');
|
||
attachmentInput.type = 'file';
|
||
attachmentInput.multiple = true;
|
||
attachmentInput.accept = '*/*';
|
||
attachmentInput.hidden = true;
|
||
attachmentInput.setAttribute('aria-label', 'Choose files to attach');
|
||
const attachButton = document.createElement('button');
|
||
attachButton.type = 'button';
|
||
attachButton.className = 'discard';
|
||
attachButton.textContent = 'Attach files…';
|
||
const attachmentList = document.createElement('div');
|
||
attachmentList.className = 'attachment-list';
|
||
attachmentList.setAttribute('aria-live', 'polite');
|
||
attachmentControls.append(attachButton, attachmentInput);
|
||
attachmentRow.append(attachmentLabel, attachmentControls);
|
||
fields.append(attachmentRow, attachmentList);
|
||
attachButton.onclick = () => attachmentInput.click();
|
||
const renderAttachments = () => {
|
||
attachmentList.replaceChildren();
|
||
attachments.forEach((file, index) => {
|
||
const row = document.createElement('div');
|
||
row.className = 'attachment-row';
|
||
const name = document.createElement('strong');
|
||
name.textContent = file.filename;
|
||
const size = document.createElement('small');
|
||
size.textContent = `${((file.size || 0) / 1048576).toFixed(2)} MB`;
|
||
const remove = document.createElement('button');
|
||
remove.type = 'button';
|
||
remove.className = 'discard';
|
||
remove.textContent = 'Remove';
|
||
remove.setAttribute('aria-label', `Remove ${file.filename}`);
|
||
remove.onclick = () => {
|
||
attachments.splice(index, 1);
|
||
renderAttachments();
|
||
void persist().catch(error => toast(error.message || 'Could not save the draft'));
|
||
};
|
||
row.append(name, size, remove);
|
||
attachmentList.append(row);
|
||
});
|
||
};
|
||
attachmentInput.onchange = async () => {
|
||
attachButton.disabled = true;
|
||
try {
|
||
const selected = [];
|
||
for (const file of attachmentInput.files) {
|
||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||
let binary = '';
|
||
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
|
||
binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
|
||
}
|
||
selected.push({
|
||
filename: file.name,
|
||
contentType: file.type || 'application/octet-stream',
|
||
size: file.size,
|
||
contentBase64: btoa(binary)
|
||
});
|
||
}
|
||
attachments.push(...selected);
|
||
renderAttachments();
|
||
await persist();
|
||
} catch (error) {
|
||
toast(error.message || 'Could not add the selected files');
|
||
} finally {
|
||
attachmentInput.value = '';
|
||
attachButton.disabled = false;
|
||
}
|
||
};
|
||
renderAttachments();
|
||
if (draft) {
|
||
$('#compose-to').value = draft.to || '';
|
||
$('#compose-cc').value = draft.cc || '';
|
||
$('#compose-subject').value = draft.subject || '';
|
||
$('#compose-body').value = draft.text || '';
|
||
modal.querySelector('.modal-head span').textContent = 'Edit draft';
|
||
}
|
||
const save = document.createElement('button');
|
||
save.type = 'button';
|
||
save.className = 'discard';
|
||
save.id = 'save-draft';
|
||
save.textContent = 'Save draft';
|
||
modal.querySelector('.compose-footer').insertBefore(save, $('#send'));
|
||
let saveTimer;
|
||
let closed = false;
|
||
const persist = async () => {
|
||
if (closed || !$('#compose-to')) return;
|
||
const values = {
|
||
id: modal.dataset.draftId || window.crypto.randomUUID(),
|
||
to: $('#compose-to').value,
|
||
cc: $('#compose-cc').value,
|
||
subject: $('#compose-subject').value,
|
||
text: $('#compose-body').value,
|
||
attachments
|
||
};
|
||
if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return;
|
||
modal.dataset.draftId = values.id;
|
||
const result = await window.daybreakMail.saveDraft(values);
|
||
modal.dataset.draftId = result.id;
|
||
};
|
||
save.onclick = async () => {
|
||
try {
|
||
await persist();
|
||
toast('Draft saved on this device');
|
||
if (activeFolder === 'Drafts') void syncMailbox(false);
|
||
} catch (error) { toast(error.message || 'Could not save draft'); }
|
||
};
|
||
modal.addEventListener('input', () => {
|
||
clearTimeout(saveTimer);
|
||
saveTimer = setTimeout(() => persist().catch(error => toast(error.message || 'Could not save draft')), 700);
|
||
});
|
||
modal.querySelector('.modal-overlay')?.addEventListener('click', event => {
|
||
if (!event.target.classList.contains('modal-overlay')) return;
|
||
clearTimeout(saveTimer);
|
||
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
|
||
.catch(error => toast(error.message || 'Could not save draft'));
|
||
closed = true;
|
||
}, true);
|
||
root.querySelector('.modal-close')?.addEventListener('click', () => {
|
||
clearTimeout(saveTimer);
|
||
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
|
||
.catch(error => toast(error.message || 'Could not save draft'));
|
||
closed = true;
|
||
}, true);
|
||
$('#discard').onclick = async () => {
|
||
clearTimeout(saveTimer);
|
||
closed = true;
|
||
try {
|
||
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
|
||
root.innerHTML = '';
|
||
if (activeFolder === 'Drafts') void syncMailbox(false);
|
||
} catch (error) { toast(error.message || 'Could not delete draft'); }
|
||
};
|
||
$('#send').addEventListener('click', () => {
|
||
clearTimeout(saveTimer);
|
||
closed = true;
|
||
}, true);
|
||
};
|
||
}
|
||
|
||
async function syncMailbox(showToast, options = {}) {
|
||
if (mailboxSyncPromise) {
|
||
mailboxSyncQueued = true;
|
||
return mailboxSyncPromise;
|
||
}
|
||
if (!connectedMailAccount || !window.daybreakMail) {
|
||
openMailAccount();
|
||
return;
|
||
}
|
||
const refresh = $('#refresh');
|
||
if (refresh) refresh.disabled = true;
|
||
const sync = (async () => {
|
||
try {
|
||
if (activeFolder === 'Drafts') {
|
||
const result = await window.daybreakMail.listDrafts();
|
||
renderDrafts(result.drafts || []);
|
||
if (showToast) toast(`${result.drafts.length} saved drafts`);
|
||
return;
|
||
}
|
||
const previouslyActiveMessage = activeMessage;
|
||
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
|
||
const result = await window.daybreakMail.syncFolder(activeFolder, offset, mailSearchFilters());
|
||
if (options.append) messages.push(...result.messages);
|
||
else messages.splice(0, messages.length, ...result.messages);
|
||
messages.forEach(message => {
|
||
try {
|
||
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
|
||
message.tags = [...new Set([...(message.tags || []), ...localTags])];
|
||
} catch {}
|
||
});
|
||
if (!options.append) mailPageOffset = offset;
|
||
mailTotal = result.total;
|
||
activeMessage = messages.some(message => message.id === previouslyActiveMessage)
|
||
? previouslyActiveMessage
|
||
: messages[0]?.id;
|
||
selectedIds.clear();
|
||
const unread = messages.filter(message => message.unread).length;
|
||
const inboxCount = $('.folder[data-folder="Inbox"] .count');
|
||
if (inboxCount) inboxCount.textContent = String(unread);
|
||
const pagination = $('#pagination');
|
||
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
|
||
const loadMore = $('#load-more');
|
||
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
|
||
query = '';
|
||
renderList();
|
||
if (activeMessage) {
|
||
openMessage(activeMessage);
|
||
const current = messages.find(message => message.id === activeMessage);
|
||
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || activeFolder, action: 'unread', enabled: false }).catch(() => {});
|
||
}
|
||
else $('#reader-pane').innerHTML = emptyReader();
|
||
updateAccountCard(connectedMailAccount);
|
||
const status = $('#mail-status');
|
||
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
|
||
if (showToast) toast(`Synced ${messages.length} messages`);
|
||
} catch (error) {
|
||
toast(error.message || 'Could not sync the inbox');
|
||
} finally {
|
||
if (refresh) refresh.disabled = false;
|
||
}
|
||
|
||
})();
|
||
mailboxSyncPromise = sync;
|
||
try {
|
||
await sync;
|
||
} finally {
|
||
mailboxSyncPromise = null;
|
||
if (mailboxSyncQueued) {
|
||
mailboxSyncQueued = false;
|
||
void syncMailbox(false);
|
||
}
|
||
}
|
||
}
|
||
|
||
if (window.daybreakMail) {
|
||
setupDraftComposer();
|
||
let searchTimer;
|
||
const searchControls = ['#search', '#filter-folder', '#filter-sender', '#filter-subject', '#filter-after', '#filter-before', '#filter-attachments'];
|
||
$('#search-filters-toggle').onclick = () => {
|
||
const panel = $('#search-filters');
|
||
const expanded = panel.classList.toggle('hidden') === false;
|
||
$('#search-filters-toggle').setAttribute('aria-expanded', String(expanded));
|
||
};
|
||
$('#clear-search-filters').onclick = () => {
|
||
$('#filter-folder').value = '';
|
||
$('#filter-sender').value = '';
|
||
$('#filter-subject').value = '';
|
||
$('#filter-after').value = '';
|
||
$('#filter-before').value = '';
|
||
$('#filter-attachments').checked = false;
|
||
$('#search').value = '';
|
||
activeFolder = folderBeforeSearch || activeFolder;
|
||
folderBeforeSearch = null;
|
||
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
|
||
$('#sidebar-title').textContent = activeFolder;
|
||
$('#crumb-current').textContent = activeFolder;
|
||
query = '';
|
||
renderList();
|
||
mailPageOffset = 0;
|
||
void syncMailbox(false, { offset: 0 });
|
||
};
|
||
for (const selector of searchControls) {
|
||
$(selector).addEventListener(selector === '#search' ? 'input' : 'change', () => {
|
||
if (selector === '#filter-folder' && $('#filter-folder').value) {
|
||
if (!folderBeforeSearch) folderBeforeSearch = activeFolder;
|
||
activeFolder = $('#filter-folder').value;
|
||
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
|
||
$('#sidebar-title').textContent = activeFolder;
|
||
$('#crumb-current').textContent = activeFolder;
|
||
}
|
||
clearTimeout(searchTimer);
|
||
searchTimer = setTimeout(() => {
|
||
mailPageOffset = 0;
|
||
void syncMailbox(false, { offset: 0 });
|
||
}, selector === '#search' ? 350 : 0);
|
||
});
|
||
}
|
||
window.daybreakMail.getAppVersion().then(version => {
|
||
document.title = `ep-mail v${version}`;
|
||
}).catch(error => {
|
||
console.error('Could not read app version:', error);
|
||
});
|
||
window.daybreakMail.onSyncUpdate(update => {
|
||
if (update.accountId !== connectedMailAccount?.id) return;
|
||
if (update.error) {
|
||
toast(update.error);
|
||
return;
|
||
}
|
||
if (update.newCount || (update.foldersChanged || []).length) {
|
||
if (document.visibilityState === 'visible') {
|
||
syncMailbox(false, update.newCount ? { offset: 0 } : {});
|
||
}
|
||
else mailboxRefreshPending = true;
|
||
}
|
||
});
|
||
document.addEventListener('visibilitychange', () => {
|
||
if (document.visibilityState === 'visible' && mailboxRefreshPending) {
|
||
mailboxRefreshPending = false;
|
||
syncMailbox(false, { offset: 0 });
|
||
}
|
||
});
|
||
window.addEventListener('focus', () => {
|
||
if (connectedMailAccount) syncMailbox(false);
|
||
});
|
||
window.addEventListener('online', () => {
|
||
if (connectedMailAccount) syncMailbox(false, { offset: 0 });
|
||
});
|
||
setInterval(() => {
|
||
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') {
|
||
syncMailbox(false);
|
||
}
|
||
}, 60 * 1000);
|
||
$('#account-settings').addEventListener('click', openMailAccount);
|
||
$('#account-settings').addEventListener('keydown', event => {
|
||
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); }
|
||
});
|
||
$('#settings-button').onclick = () => openPreferences();
|
||
$('#refresh').onclick = () => syncMailbox(true);
|
||
$('#add-folder').addEventListener('click', createMailFolder);
|
||
$$('.folder').forEach(button => button.addEventListener('click', () => {
|
||
if ($('#filter-folder').value) {
|
||
$('#filter-folder').value = '';
|
||
folderBeforeSearch = null;
|
||
}
|
||
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Drafts'].includes(button.dataset.folder)) {
|
||
mailPageOffset = 0;
|
||
syncMailbox(false, { offset: 0 });
|
||
}
|
||
}));
|
||
$('#previous-page').onclick = () => {
|
||
if (mailPageOffset <= 0) return;
|
||
mailPageOffset = Math.max(0, mailPageOffset - 20);
|
||
syncMailbox(false, { offset: mailPageOffset });
|
||
};
|
||
$('#next-page').onclick = () => {
|
||
if (mailPageOffset + 20 >= mailTotal) return;
|
||
mailPageOffset += 20;
|
||
syncMailbox(false, { offset: mailPageOffset });
|
||
};
|
||
$('#load-more').onclick = () => syncMailbox(false, { append: true });
|
||
document.addEventListener('click', async event => {
|
||
const sendButton = event.target.closest('#send');
|
||
if (!sendButton || !connectedMailAccount) return;
|
||
event.preventDefault();
|
||
event.stopImmediatePropagation();
|
||
const recipient = $('#compose-to').value.trim();
|
||
if (!recipient) { $('#compose-to').focus(); toast('Add a recipient to send your message'); return; }
|
||
sendButton.disabled = true;
|
||
sendButton.textContent = 'Sending…';
|
||
try {
|
||
const pgp = window.epMailFeatures.pgp?.prepareSend
|
||
? await window.epMailFeatures.pgp.prepareSend(recipient, $('#compose-cc').value)
|
||
: null;
|
||
if (pgp === false) {
|
||
sendButton.disabled = false;
|
||
sendButton.textContent = 'Send ↗';
|
||
return;
|
||
}
|
||
const result = await window.daybreakMail.send({
|
||
to: recipient,
|
||
cc: $('#compose-cc').value,
|
||
subject: $('#compose-subject').value.trim(),
|
||
text: $('#compose-body').value,
|
||
attachments: $('#modal-root .compose-modal')?._composeAttachments || [],
|
||
displayName: connectedMailAccount.displayName || window.epMailFeatures.productivity?.profileName || '',
|
||
...(pgp ? { pgp } : {})
|
||
});
|
||
if (result.failed) {
|
||
sendButton.disabled = false;
|
||
sendButton.textContent = 'Send ↗';
|
||
toast(result.message || 'Message could not be encrypted');
|
||
return;
|
||
}
|
||
if (result.queued) {
|
||
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
|
||
if (draftId) await window.daybreakMail.deleteDraft(draftId);
|
||
$('#modal-root').innerHTML = '';
|
||
toast('Offline: message queued and will send when connected');
|
||
if (activeFolder === 'Drafts') void syncMailbox(false);
|
||
return;
|
||
}
|
||
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
|
||
if (draftId) await window.daybreakMail.deleteDraft(draftId);
|
||
$('#modal-root').innerHTML = '';
|
||
toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
|
||
if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
|
||
if (activeFolder === 'Drafts') void syncMailbox(false);
|
||
} catch (error) {
|
||
sendButton.disabled = false;
|
||
sendButton.textContent = 'Send ↗';
|
||
toast(error.message || 'Message could not be sent');
|
||
}
|
||
}, true);
|
||
|
||
window.daybreakMail.getAccount().then(account => {
|
||
if (!account) return;
|
||
connectedMailAccount = account;
|
||
updateAccountCard(account);
|
||
syncMailbox(false);
|
||
}).catch(() => {});
|
||
}
|
||
|
||
const mailUiApi = window.epMailUiModules.createMailUiApi({
|
||
state: window.epMailState,
|
||
getConnectedAccount: () => connectedMailAccount,
|
||
setConnectedAccount: account => { connectedMailAccount = account; },
|
||
setPageOffset: offset => { mailPageOffset = offset; },
|
||
syncMailbox,
|
||
updateAccountCard,
|
||
getRenderList: () => renderList,
|
||
getOpenMessage: () => openMessage,
|
||
getShowCompose: () => showCompose,
|
||
baseRenderList: renderList,
|
||
emptyReader,
|
||
openMailAccount,
|
||
select: $,
|
||
selectAll: $$,
|
||
toast,
|
||
escapeHtml: esc,
|
||
getApplyTheme: () => applyTheme,
|
||
setRenderList: renderer => { renderList = renderer; },
|
||
setOpenMessage: renderer => { openMessage = renderer; },
|
||
setShowCompose: renderer => { showCompose = renderer; }
|
||
});
|
||
window.epMailFeatures = window.epMailFeatures || {};
|
||
window.epMailFeatures.mail = mailUiApi;
|