(() => {
const rendererState = window.epMailState;
const appShell = window.epMailShell;
const selectMailUi = appShell.select;
const selectAllMailUi = appShell.selectAll;
const escapeMailUi = appShell.escapeHtml;
const toastMailUi = appShell.toast;
const mailFeatureState = {
connectedAccount: null,
pageOffset: 0,
total: 0,
syncPromise: null,
syncQueued: false,
refreshPending: false,
folderBeforeSearch: null,
customFolders: [],
selectedDraftIds: new Set()
};
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);
}
appShell.wrapOpenMessage(originalOpenMessage => function (id) {
originalOpenMessage(id);
const message = rendererState.messages.find(item => item.id === id);
if (!message) return;
const senderReasons = suspiciousSenderReasons(message);
const links = messageLinks(message);
const warnings = [];
if (senderReasons.length) {
warnings.push(`Sender details may be misleading ${senderReasons.map(reason => `${escapeMailUi(reason)} `).join('')} Sender names and addresses can be forged. Verify the sender through a trusted channel. `);
}
const linkCards = links.map((link, index) => `
${link.reasons.length ? 'Potentially unsafe link' : 'External link'} ${escapeMailUi(link.host)}
${link.reasons.length ? `${escapeMailUi(link.reasons.join('; '))} ` : ''}
Review & open
`).join('');
const reader = selectMailUi('#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', `Links in this message ${links.some(link => link.reasons.length) ? 'Some links show warning signs. Every link requires confirmation before it opens.
' : ''}${linkCards} `);
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) {
toastMailUi(error.message || 'Could not open this link');
} finally {
button.disabled = false;
}
};
});
}
});
function renderCustomFolders() {
const box = selectMailUi('#custom-folders');
if (!box) return;
box.replaceChildren(...mailFeatureState.customFolders.map(folder => {
const button = document.createElement('button');
button.className = 'folder custom-folder';
button.dataset.folder = folder.id;
button.classList.toggle('active', rendererState.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 (selectMailUi('#filter-folder').value) { selectMailUi('#filter-folder').value = ''; mailFeatureState.folderBeforeSearch = null; }
rendererState.activeFolder = folder.id;
selectAllMailUi('.folder').forEach(item => item.classList.toggle('active', item === button));
selectMailUi('#sidebar-title').textContent = folder.name;
selectMailUi('#crumb-current').textContent = folder.name;
mailFeatureState.pageOffset = 0;
void syncMailbox(false, { offset: 0 });
});
return button;
}));
}
async function loadCustomFolders() {
if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
try {
mailFeatureState.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'], ...mailFeatureState.customFolders.map(folder => [folder.id, folder.name])];
if (!options.some(([value]) => value === selected)) {
options.push([selected, String(selected).replace(/^[^:]*:/, '') || selected]);
}
return '' +
options.map(([value, name]) => '' + escapeMailUi(name) + ' ').join('') + ' ';
}
// 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 = '';
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 (!mailFeatureState.connectedAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; }
const name = await askText('New mail folder', 'Name');
if (!name) return;
try {
const result = await window.daybreakMail.createFolder(name);
mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
renderCustomFolders();
toastMailUi(`Folder “${result.folder?.name || name}” created`);
} catch (error) {
toastMailUi(error.message || 'Could not create the folder');
}
}
function updateAccountCard(account) {
const card = selectMailUi('#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 = selectMailUi('.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 = selectMailUi('#modal-root');
const editing = Boolean(existingAccount);
const displayName = existingAccount?.displayName || window.epMailFeatures.productivity?.profileName || '';
const ruleMarkup = (existingAccount?.rules || []).map(rule => `
${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`${label} `).join('')}
${rule.action==='move'
? `${ruleFolderSelect(rule.value)}`
: ` `}
Remove
`).join('');
root.innerHTML = `${editing ? 'Edit mailbox' : 'Add a mailbox'} ×
`;
const close = () => { root.innerHTML = ''; };
selectAllMailUi('.modal-close').forEach(button => button.onclick = close);
selectMailUi('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
selectMailUi('#disconnect-mail').onclick = close;
const addRuleRow = rule => {
const row = document.createElement('div');
row.className = 'mail-rule-row';
row.innerHTML = `Archive Move to folder Apply label Flag Remove `;
row.querySelector('.mail-rule-action').value = rule?.action || 'archive';
selectMailUi('#mail-rule-list').append(row);
};
selectMailUi('#add-mail-rule').onclick = () => addRuleRow();
selectMailUi('#mail-rule-list').onclick = event => {
if (event.target.closest('.remove-mail-rule')) event.target.closest('.mail-rule-row').remove();
};
selectMailUi('#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 = ` `;
}
row.querySelector('.mail-rule-value').disabled = event.target.value === 'flag';
};
selectMailUi('#connect-mail').onclick = async () => {
const button = selectMailUi('#connect-mail');
const status = selectMailUi('#mail-account-status');
const password = selectMailUi('#mail-account-password').value;
const name = selectMailUi('#mail-account-display-name').value.trim();
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#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: selectMailUi('#mail-account-email').value,
password,
displayName: name,
imapHost: selectMailUi('#mail-account-imap').value,
smtpHost: selectMailUi('#mail-account-smtp').value,
signature: selectMailUi('#mail-account-signature').value,
notificationsEnabled: selectMailUi('#mail-account-notifications').checked,
syncIntervalMinutes: Number(selectMailUi('#mail-account-sync-interval').value),
rules: [...selectMailUi('#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) {
mailFeatureState.connectedAccount = account;
updateAccountCard(account);
mailFeatureState.pageOffset = 0;
close();
await syncMailbox(false, { offset: 0 });
} else {
close();
}
toastMailUi('Mailbox settings updated');
} else {
mailFeatureState.connectedAccount = account;
updateAccountCard(account);
close();
toastMailUi('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';
}
};
selectMailUi('#mail-account-email').focus();
}
function mailSearchFilters() {
return {
query: selectMailUi('#search').value.trim(),
sender: selectMailUi('#filter-sender').value.trim(),
subject: selectMailUi('#filter-subject').value.trim(),
after: selectMailUi('#filter-after').value,
before: selectMailUi('#filter-before').value,
hasAttachments: selectMailUi('#filter-attachments').checked,
folder: selectMailUi('#filter-folder').value
};
}
async function deleteSelectedDrafts() {
const ids = rendererState.messages.map(message => String(message.id)).filter(id => mailFeatureState.selectedDraftIds.has(id));
if (!ids.length) { toastMailUi('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);
mailFeatureState.selectedDraftIds.clear();
toastMailUi(`${ids.length} draft${ids.length === 1 ? '' : 's'} deleted`);
await syncMailbox(false);
} catch (error) { toastMailUi(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 (rendererState.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 = rendererState.messages.map(message => String(message.id));
const all = ids.length && ids.every(id => mailFeatureState.selectedDraftIds.has(id));
ids.forEach(id => all ? mailFeatureState.selectedDraftIds.delete(id) : mailFeatureState.selectedDraftIds.add(id));
renderDrafts(rendererState.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)));
[...mailFeatureState.selectedDraftIds].forEach(id => { if (!present.has(id)) mailFeatureState.selectedDraftIds.delete(id); });
rendererState.messages.splice(0, rendererState.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
})));
selectMailUi('#message-list').innerHTML = rendererState.messages.length ? rendererState.messages.map(message => `
${message.initials}
${escapeMailUi(message.email)}
${escapeMailUi(message.subject)}
${escapeMailUi(message.snippet)}
${escapeMailUi(message.date)} ⌫
`).join('') :
'✎
No saved drafts Drafts are saved on this device and available offline.
Compose a draft ';
const start = selectMailUi('#start-draft');
if (start) start.onclick = () => appShell.showCompose();
selectAllMailUi('.message').forEach(row => row.onclick = event => {
const draft = rendererState.messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (event.target.closest('.row-check')) {
event.stopPropagation();
const id = row.dataset.id;
mailFeatureState.selectedDraftIds.has(id) ? mailFeatureState.selectedDraftIds.delete(id) : mailFeatureState.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(() => { toastMailUi('Draft deleted'); return syncMailbox(false); })
.catch(error => toastMailUi(error.message || 'Could not delete the draft'));
return;
}
if (draft) appShell.showCompose(null, false, draft);
});
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
selectMailUi('#pagination').textContent = `${rendererState.messages.length} drafts`;
selectMailUi('#load-more').classList.add('hidden');
}
function setupDraftComposer() {
appShell.wrapShowCompose((original) => (reply, forward = false, draft = null) => {
original(reply, forward);
const root = selectMailUi('#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 => toastMailUi(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) {
toastMailUi(error.message || 'Could not add the selected files');
} finally {
attachmentInput.value = '';
attachButton.disabled = false;
}
};
renderAttachments();
if (draft) {
selectMailUi('#compose-to').value = draft.to || '';
selectMailUi('#compose-cc').value = draft.cc || '';
selectMailUi('#compose-subject').value = draft.subject || '';
selectMailUi('#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, selectMailUi('#send'));
let saveTimer;
let closed = false;
const persist = async () => {
if (closed || !selectMailUi('#compose-to')) return;
const values = {
id: modal.dataset.draftId || window.crypto.randomUUID(),
to: selectMailUi('#compose-to').value,
cc: selectMailUi('#compose-cc').value,
subject: selectMailUi('#compose-subject').value,
text: selectMailUi('#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();
toastMailUi('Draft saved on this device');
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toastMailUi(error.message || 'Could not save draft'); }
};
modal.addEventListener('input', () => {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => persist().catch(error => toastMailUi(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 (rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toastMailUi(error.message || 'Could not save draft'));
closed = true;
}, true);
root.querySelector('.modal-close')?.addEventListener('click', () => {
clearTimeout(saveTimer);
persist().then(() => { if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toastMailUi(error.message || 'Could not save draft'));
closed = true;
}, true);
selectMailUi('#discard').onclick = async () => {
clearTimeout(saveTimer);
closed = true;
try {
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
root.innerHTML = '';
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toastMailUi(error.message || 'Could not delete draft'); }
};
selectMailUi('#send').addEventListener('click', () => {
clearTimeout(saveTimer);
closed = true;
}, true);
});
}
async function syncMailbox(showToast, options = {}) {
if (mailFeatureState.syncPromise) {
mailFeatureState.syncQueued = true;
return mailFeatureState.syncPromise;
}
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
openMailAccount();
return;
}
const refresh = selectMailUi('#refresh');
if (refresh) refresh.disabled = true;
const sync = (async () => {
try {
if (rendererState.activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts();
renderDrafts(result.drafts || []);
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
return;
}
const previouslyActiveMessage = rendererState.activeMessage;
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
const result = await window.daybreakMail.syncFolder(rendererState.activeFolder, offset, mailSearchFilters());
if (options.append) rendererState.messages.push(...result.messages);
else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
rendererState.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) mailFeatureState.pageOffset = offset;
mailFeatureState.total = result.total;
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
? previouslyActiveMessage
: rendererState.messages[0]?.id;
rendererState.selectedIds.clear();
const unread = rendererState.messages.filter(message => message.unread).length;
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
if (inboxCount) inboxCount.textContent = String(unread);
const pagination = selectMailUi('#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 = selectMailUi('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.pageOffset + rendererState.messages.length >= result.total);
rendererState.query = '';
appShell.renderList();
if (rendererState.activeMessage) {
appShell.openMessage(rendererState.activeMessage);
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {});
}
else selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
updateAccountCard(mailFeatureState.connectedAccount);
const status = selectMailUi('#mail-status');
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
} catch (error) {
toastMailUi(error.message || 'Could not sync the inbox');
} finally {
if (refresh) refresh.disabled = false;
}
})();
mailFeatureState.syncPromise = sync;
try {
await sync;
} finally {
mailFeatureState.syncPromise = null;
if (mailFeatureState.syncQueued) {
mailFeatureState.syncQueued = 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'];
selectMailUi('#search-filters-toggle').onclick = () => {
const panel = selectMailUi('#search-filters');
const expanded = panel.classList.toggle('hidden') === false;
selectMailUi('#search-filters-toggle').setAttribute('aria-expanded', String(expanded));
};
selectMailUi('#clear-search-filters').onclick = () => {
selectMailUi('#filter-folder').value = '';
selectMailUi('#filter-sender').value = '';
selectMailUi('#filter-subject').value = '';
selectMailUi('#filter-after').value = '';
selectMailUi('#filter-before').value = '';
selectMailUi('#filter-attachments').checked = false;
selectMailUi('#search').value = '';
rendererState.activeFolder = mailFeatureState.folderBeforeSearch || rendererState.activeFolder;
mailFeatureState.folderBeforeSearch = null;
selectAllMailUi('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === rendererState.activeFolder));
selectMailUi('#sidebar-title').textContent = rendererState.activeFolder;
selectMailUi('#crumb-current').textContent = rendererState.activeFolder;
rendererState.query = '';
appShell.renderList();
mailFeatureState.pageOffset = 0;
void syncMailbox(false, { offset: 0 });
};
for (const selector of searchControls) {
selectMailUi(selector).addEventListener(selector === '#search' ? 'input' : 'change', () => {
if (selector === '#filter-folder' && selectMailUi('#filter-folder').value) {
if (!mailFeatureState.folderBeforeSearch) mailFeatureState.folderBeforeSearch = rendererState.activeFolder;
rendererState.activeFolder = selectMailUi('#filter-folder').value;
selectAllMailUi('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === rendererState.activeFolder));
selectMailUi('#sidebar-title').textContent = rendererState.activeFolder;
selectMailUi('#crumb-current').textContent = rendererState.activeFolder;
}
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
mailFeatureState.pageOffset = 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 !== mailFeatureState.connectedAccount?.id) return;
if (update.error) {
toastMailUi(update.error);
return;
}
if (update.newCount || (update.foldersChanged || []).length) {
if (document.visibilityState === 'visible') {
syncMailbox(false, update.newCount ? { offset: 0 } : {});
}
else mailFeatureState.refreshPending = true;
}
});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) {
mailFeatureState.refreshPending = false;
syncMailbox(false, { offset: 0 });
}
});
window.addEventListener('focus', () => {
if (mailFeatureState.connectedAccount) syncMailbox(false);
});
window.addEventListener('online', () => {
if (mailFeatureState.connectedAccount) syncMailbox(false, { offset: 0 });
});
setInterval(() => {
if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') {
syncMailbox(false);
}
}, 60 * 1000);
selectMailUi('#account-settings').addEventListener('click', openMailAccount);
selectMailUi('#account-settings').addEventListener('keydown', event => {
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); }
});
selectMailUi('#refresh').onclick = () => syncMailbox(true);
selectMailUi('#add-folder').addEventListener('click', createMailFolder);
selectAllMailUi('.folder').forEach(button => button.addEventListener('click', () => {
if (selectMailUi('#filter-folder').value) {
selectMailUi('#filter-folder').value = '';
mailFeatureState.folderBeforeSearch = null;
}
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Drafts'].includes(button.dataset.folder)) {
mailFeatureState.pageOffset = 0;
syncMailbox(false, { offset: 0 });
}
}));
selectMailUi('#previous-page').onclick = () => {
if (mailFeatureState.pageOffset <= 0) return;
mailFeatureState.pageOffset = Math.max(0, mailFeatureState.pageOffset - 20);
syncMailbox(false, { offset: mailFeatureState.pageOffset });
};
selectMailUi('#next-page').onclick = () => {
if (mailFeatureState.pageOffset + 20 >= mailFeatureState.total) return;
mailFeatureState.pageOffset += 20;
syncMailbox(false, { offset: mailFeatureState.pageOffset });
};
selectMailUi('#load-more').onclick = () => syncMailbox(false, { append: true });
document.addEventListener('click', async event => {
const sendButton = event.target.closest('#send');
if (!sendButton || !mailFeatureState.connectedAccount) return;
event.preventDefault();
event.stopImmediatePropagation();
const recipient = selectMailUi('#compose-to').value.trim();
if (!recipient) { selectMailUi('#compose-to').focus(); toastMailUi('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, selectMailUi('#compose-cc').value)
: null;
if (pgp === false) {
sendButton.disabled = false;
sendButton.textContent = 'Send ↗';
return;
}
const result = await window.daybreakMail.send({
to: recipient,
cc: selectMailUi('#compose-cc').value,
subject: selectMailUi('#compose-subject').value.trim(),
text: selectMailUi('#compose-body').value,
attachments: selectMailUi('#modal-root .compose-modal')?._composeAttachments || [],
displayName: mailFeatureState.connectedAccount.displayName || window.epMailFeatures.productivity?.profileName || '',
...(pgp ? { pgp } : {})
});
if (result.failed) {
sendButton.disabled = false;
sendButton.textContent = 'Send ↗';
toastMailUi(result.message || 'Message could not be encrypted');
return;
}
if (result.queued) {
const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
selectMailUi('#modal-root').innerHTML = '';
toastMailUi('Offline: message queued and will send when connected');
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
return;
}
const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
selectMailUi('#modal-root').innerHTML = '';
toastMailUi(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
if (rendererState.activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) {
sendButton.disabled = false;
sendButton.textContent = 'Send ↗';
toastMailUi(error.message || 'Message could not be sent');
}
}, true);
window.daybreakMail.getAccount().then(account => {
if (!account) return;
mailFeatureState.connectedAccount = account;
updateAccountCard(account);
syncMailbox(false);
}).catch(() => {});
}
const mailUiApi = window.epMailUiModules.createMailUiApi({
state: window.epMailState,
getConnectedAccount: () => mailFeatureState.connectedAccount,
setConnectedAccount: account => { mailFeatureState.connectedAccount = account; },
setPageOffset: offset => { mailFeatureState.pageOffset = offset; },
syncMailbox,
updateAccountCard,
getRenderList: () => appShell.renderList,
getOpenMessage: () => appShell.openMessage,
getShowCompose: () => appShell.showCompose,
baseRenderList: appShell.baseRenderList,
emptyReader: appShell.emptyReader,
openMailAccount,
select: selectMailUi,
selectAll: selectAllMailUi,
toast: toastMailUi,
escapeHtml: escapeMailUi,
getApplyTheme: () => appShell.applyTheme,
setRenderList: renderer => appShell.wrapRenderList(() => renderer),
setOpenMessage: renderer => appShell.wrapOpenMessage(() => renderer),
setShowCompose: renderer => appShell.wrapShowCompose(() => renderer)
});
window.epMailFeatures = window.epMailFeatures || {};
window.epMailFeatures.mail = mailUiApi;
})();