(() => {
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,
nextOffset: 0,
total: 0,
autoLoadBlocked: false,
syncPromise: null,
syncQueued: false,
syncMailboxKey: null,
displayedMailboxKey: null,
refreshPending: false,
folderBeforeSearch: null,
customFolders: [],
folderLoad: null,
foldersAccountId: null,
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;
const accountId = mailFeatureState.connectedAccount.id;
if (mailFeatureState.folderLoad?.accountId === accountId) return mailFeatureState.folderLoad.promise;
const request = { accountId };
mailFeatureState.folderLoad = request;
request.promise = (async () => {
try {
const result = await window.daybreakMail.listFolders();
if (mailFeatureState.folderLoad !== request || mailFeatureState.connectedAccount?.id !== accountId) return;
mailFeatureState.customFolders = result.folders || [];
renderCustomFolders();
} catch (error) {
if (mailFeatureState.folderLoad === request) console.error('Could not load mail folders:', error);
} finally {
if (mailFeatureState.folderLoad === request) mailFeatureState.folderLoad = null;
}
})();
return request.promise;
}
// 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.folderLoad = null;
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 accountId = mailFeatureState.connectedAccount?.id || null;
if (mailFeatureState.foldersAccountId !== accountId) {
mailFeatureState.foldersAccountId = accountId;
mailFeatureState.folderLoad = null;
mailFeatureState.customFolders = [];
renderCustomFolders();
}
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 authMethodRow = document.createElement('label');
authMethodRow.className = 'compose-line';
authMethodRow.innerHTML = 'Sign-in method App password OAuth2 ';
const emailRow = selectMailUi('#mail-account-email').closest('.compose-line');
emailRow.after(authMethodRow);
const oauthProviderRow = document.createElement('label');
oauthProviderRow.className = 'compose-line';
oauthProviderRow.innerHTML = 'Provider Google Microsoft ';
authMethodRow.after(oauthProviderRow);
const reauthorizeRow = document.createElement('label');
reauthorizeRow.className = 'compose-line';
reauthorizeRow.innerHTML = 'Sign in again ';
oauthProviderRow.after(reauthorizeRow);
const authMethodSelect = selectMailUi('#mail-account-auth-method');
const oauthProviderSelect = selectMailUi('#mail-account-oauth-provider');
let configuredOAuthProviders = null;
const oauthMethodOption = [...authMethodSelect.options].find(option => option.value === 'oauth2');
if (oauthMethodOption) oauthMethodOption.disabled = existingAccount?.authMethod !== 'oauth2';
const passwordRow = selectMailUi('#mail-account-password').closest('.compose-line');
const imapRow = selectMailUi('#mail-account-imap').closest('.compose-line');
const imapPortRow = selectMailUi('#mail-account-imap-port').closest('.compose-line');
const imapSecureRow = selectMailUi('#mail-account-imap-secure').closest('.compose-line');
const smtpRow = selectMailUi('#mail-account-smtp').closest('.compose-line');
const smtpPortRow = selectMailUi('#mail-account-smtp-port').closest('.compose-line');
const smtpSecureRow = selectMailUi('#mail-account-smtp-secure').closest('.compose-line');
const authNote = selectMailUi('#modal-root .compose-fields > .account-note');
authMethodSelect.value = existingAccount?.authMethod === 'oauth2' ? 'oauth2' : 'password';
if (existingAccount?.oauthProvider) oauthProviderSelect.value = existingAccount.oauthProvider;
const setProviderServers = () => {
const servers = oauthProviderSelect.value === 'google'
? { imap: 'imap.gmail.com', smtp: 'smtp.gmail.com' }
: { imap: 'outlook.office365.com', smtp: 'smtp.office365.com' };
selectMailUi('#mail-account-imap').value = servers.imap;
selectMailUi('#mail-account-imap-port').value = '993';
selectMailUi('#mail-account-imap-secure').checked = true;
selectMailUi('#mail-account-smtp').value = servers.smtp;
selectMailUi('#mail-account-smtp-port').value = '587';
selectMailUi('#mail-account-smtp-secure').checked = false;
};
const updateAuthFields = () => {
const oauth = authMethodSelect.value === 'oauth2';
if (oauth) setProviderServers();
oauthProviderRow.hidden = !oauth;
reauthorizeRow.hidden = !oauth || !editing;
passwordRow.hidden = oauth;
imapRow.hidden = oauth;
imapPortRow.hidden = oauth;
imapSecureRow.hidden = oauth;
smtpRow.hidden = oauth;
smtpPortRow.hidden = oauth;
smtpSecureRow.hidden = oauth;
authNote.textContent = oauth
? 'Sign in in your browser. Configure the provider client ID in the desktop environment; OAuth refresh tokens are stored in encrypted credential storage.'
: configuredOAuthProviders && configuredOAuthProviders.size === 0
? 'Password sign-in is available. To enable OAuth2, configure EP_MAIL_GOOGLE_OAUTH_CLIENT_ID and/or EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID, then restart ep-mail.'
: 'Credentials are stored encrypted. Connections require verified TLS.';
selectMailUi('#mail-account-password').placeholder = editing && existingAccount?.authMethod !== 'oauth2'
? 'Leave blank to keep current password' : 'Enter mailbox password';
};
authMethodSelect.onchange = updateAuthFields;
oauthProviderSelect.onchange = setProviderServers;
updateAuthFields();
if (typeof window.daybreakMail?.listOAuthProviders === 'function') {
window.daybreakMail.listOAuthProviders().then(providers => {
const configured = new Set((providers || []).filter(provider => provider.configured).map(provider => provider.id));
configuredOAuthProviders = configured;
for (const option of oauthProviderSelect.options) option.disabled = !configured.has(option.value) && !(editing && existingAccount?.oauthProvider === option.value);
if (oauthMethodOption) oauthMethodOption.disabled = configured.size === 0 && !(editing && existingAccount?.authMethod === 'oauth2');
if (!existingAccount?.oauthProvider && !configured.has(oauthProviderSelect.value)) {
const available = [...configured][0];
if (available) oauthProviderSelect.value = available;
}
if (authMethodSelect.value === 'oauth2' && oauthProviderSelect.selectedOptions[0]?.disabled) authMethodSelect.value = 'password';
updateAuthFields();
}).catch(() => {});
} else {
authMethodRow.hidden = true;
oauthProviderRow.hidden = true;
}
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 authMethod = authMethodSelect.value;
const oauthProvider = oauthProviderSelect.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 (authMethod === 'password' && !password && (!editing || existingAccount?.authMethod === 'oauth2')) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
const imapPort = Number(selectMailUi('#mail-account-imap-port').value);
const smtpPort = Number(selectMailUi('#mail-account-smtp-port').value);
if (authMethod === 'password' && (![imapPort, smtpPort].every(port => Number.isInteger(port) && port >= 1 && port <= 65535))) {
status.textContent = 'Enter valid IMAP and SMTP ports (1–65535).';
return;
}
button.disabled = true;
const reauthorizeOAuth = authMethod === 'oauth2' && editing && selectMailUi('#mail-account-reauthorize').checked;
button.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth) ? 'Starting OAuth2 sign-in…' : editing ? 'Checking updated settings…' : 'Checking secure connections…';
status.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth)
? 'Opening your browser for secure provider sign-in…'
: 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,
authMethod,
...(authMethod === 'oauth2' ? { oauthProvider } : {}),
...(editing && authMethod === 'oauth2' ? { reauthorizeOAuth } : {}),
displayName: name,
imapHost: selectMailUi('#mail-account-imap').value,
imapPort,
imapSecure: selectMailUi('#mail-account-imap-secure').checked,
smtpHost: selectMailUi('#mail-account-smtp').value,
smtpPort,
smtpSecure: selectMailUi('#mail-account-smtp-secure').checked,
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(authMethod === 'oauth2' ? 'OAuth2 mailbox connected securely' : '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 = authMethod === 'oauth2' ? 'Authorize & connect' : 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 = {}) {
const isAndroid = window.daybreakMail?.platform === 'android';
const mailboxKey = JSON.stringify([mailFeatureState.connectedAccount?.id, rendererState.activeFolder]);
if (mailFeatureState.syncPromise) {
if (!isAndroid || mailFeatureState.syncMailboxKey === mailboxKey) {
mailFeatureState.syncQueued = true;
return mailFeatureState.syncPromise;
}
mailFeatureState.syncQueued = false;
}
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
openMailAccount();
return;
}
const refresh = selectMailUi('#refresh');
if (refresh) refresh.disabled = true;
const loadMoreButton = selectMailUi('#load-more');
if (loadMoreButton) loadMoreButton.disabled = true;
const request = {};
mailFeatureState.syncRequest = request;
mailFeatureState.syncMailboxKey = mailboxKey;
let syncSucceeded = false;
const sync = (async () => {
let showingCachedMessages = false;
try {
if (isAndroid && mailFeatureState.displayedMailboxKey !== mailboxKey) {
mailFeatureState.displayedMailboxKey = mailboxKey;
mailFeatureState.nextOffset = 0;
mailFeatureState.total = 0;
mailFeatureState.autoLoadBlocked = false;
rendererState.messages.splice(0, rendererState.messages.length);
rendererState.activeMessage = null;
rendererState.selectedIds.clear();
document.body.classList.remove('reader-open');
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
appShell.renderList();
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Loading folder…';
}
if (rendererState.activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts();
if (isAndroid && mailFeatureState.syncRequest !== request) return;
renderDrafts(result.drafts || []);
mailFeatureState.autoLoadBlocked = true;
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
return;
}
const folder = rendererState.activeFolder;
const accountId = mailFeatureState.connectedAccount.id;
const offset = options.offset ?? (options.append ? mailFeatureState.nextOffset : mailFeatureState.pageOffset);
const filters = mailSearchFilters();
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId &&
(!isAndroid || mailFeatureState.syncRequest === request);
if (window.daybreakMail.getCachedFolder && !options.append && offset === 0 && !rendererState.messages.length) {
try {
const cached = await window.daybreakMail.getCachedFolder(folder, offset, filters);
if (cached && isCurrentMailbox()) {
rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages);
rendererState.activeMessage = null;
mailFeatureState.pageOffset = offset;
mailFeatureState.nextOffset = offset + cached.messages.length;
mailFeatureState.total = cached.total;
mailFeatureState.autoLoadBlocked = true;
const pagination = selectMailUi('#pagination');
if (pagination) pagination.textContent = cached.total ? `${cached.start}–${cached.end} of ${cached.total} saved messages` : '0 saved messages';
const loadMore = selectMailUi('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', cached.messages.length >= cached.total);
appShell.renderList();
showingCachedMessages = true;
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Showing saved messages — syncing';
}
} catch (error) {
if (isAndroid && mailFeatureState.syncRequest !== request) return;
console.error('Could not load cached messages:', error);
}
}
if (!isCurrentMailbox()) return;
const result = await window.daybreakMail.syncFolder(folder, offset, filters);
if (!isCurrentMailbox()) return;
const previouslyActiveMessage = rendererState.activeMessage;
if (options.append) {
const existing = new Set(rendererState.messages.map(message => JSON.stringify([message.sourceFolder || folder, message.uid || message.id])));
for (const message of result.messages) {
const key = JSON.stringify([message.sourceFolder || folder, message.uid || message.id]);
if (!existing.has(key)) {
rendererState.messages.push(message);
existing.add(key);
}
}
} 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;
const hasSearch = Boolean(filters.query || filters.sender || filters.subject || filters.after || filters.before || filters.hasAttachments);
const isSequencePage = !result.offline && folder !== 'Snoozed' && !hasSearch;
const consumed = isSequencePage && result.start > 0 && result.end >= result.start
? result.end - result.start + 1
: result.messages.length;
mailFeatureState.nextOffset = offset + consumed;
mailFeatureState.autoLoadBlocked = consumed === 0 || (options.append && result.messages.length === 0);
syncSucceeded = true;
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
? previouslyActiveMessage
: window.daybreakMail.platform === 'android' ? null : 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 ? mailFeatureState.pageOffset + 1 : result.start}–${options.append ? Math.min(mailFeatureState.nextOffset, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = selectMailUi('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.nextOffset >= result.total || consumed === 0);
rendererState.query = '';
const messageList = selectMailUi('#message-list');
const scrollTop = options.append ? messageList.scrollTop : 0;
appShell.renderList();
if (options.append) messageList.scrollTop = scrollTop;
if (rendererState.activeMessage) {
appShell.openMessage(rendererState.activeMessage);
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
if (current?.uid && window.daybreakMail.platform !== 'android') window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {});
}
else {
document.body.classList.remove('reader-open');
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) {
if (isAndroid && mailFeatureState.syncRequest !== request) return;
if (options.append) mailFeatureState.autoLoadBlocked = true;
if (showingCachedMessages) {
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Could not sync — showing saved messages';
}
toastMailUi(error.message || 'Could not sync the inbox');
} finally {
if (!isAndroid || mailFeatureState.syncRequest === request) {
if (refresh) refresh.disabled = false;
if (loadMoreButton) loadMoreButton.disabled = false;
}
}
})();
mailFeatureState.syncPromise = sync;
try {
await sync;
} finally {
if (mailFeatureState.syncPromise !== sync) return;
mailFeatureState.syncPromise = null;
mailFeatureState.syncMailboxKey = null;
if (mailFeatureState.syncQueued) {
mailFeatureState.syncQueued = false;
void syncMailbox(false);
} else if (syncSucceeded) {
maybeLoadMoreMessages();
}
}
}
function maybeLoadMoreMessages() {
const list = selectMailUi('#message-list');
if (!list || !mailFeatureState.connectedAccount || mailFeatureState.syncPromise ||
mailFeatureState.autoLoadBlocked || rendererState.activeFolder === 'Drafts' ||
mailFeatureState.nextOffset >= mailFeatureState.total || !list.clientHeight ||
document.body.classList.contains('reader-open') ||
rendererState.activeView !== 'mail') return;
if (list.scrollHeight - list.scrollTop - list.clientHeight > 120) return;
void syncMailbox(false, { append: true });
}
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 = () => {
if (!mailFeatureState.syncPromise) void syncMailbox(false, { append: true });
};
selectMailUi('#message-list').addEventListener('scroll', maybeLoadMoreMessages, { passive: 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.epMailFeatures.modules.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.mail = mailUiApi;
})();