Files
ep-mail-client/mail-ui.js
T

944 lines
54 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
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(`<section class="mail-safety-warning" role="alert"><strong>Sender details may be misleading</strong><ul>${senderReasons.map(reason => `<li>${escapeMailUi(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>${escapeMailUi(link.host)}</span>
${link.reasons.length ? `<small>${escapeMailUi(link.reasons.join('; '))}</small>` : ''}</div>
<button type="button" class="mail-link-open" data-mail-link="${index}">Review &amp; open</button>
</div>`).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', `<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) {
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 '<select class="mail-rule-value" aria-label="Destination folder">' +
options.map(([value, name]) => '<option value="' + escapeMailUi(value) + '"' + (value === selected ? ' selected' : '') + '>' + escapeMailUi(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 (!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 => `
<div class="mail-rule-row">
<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${escapeMailUi(rule.senderContains || '')}">
<input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${escapeMailUi(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="${escapeMailUi(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">Credentials are stored encrypted. Choose the server's advertised TLS mode and ports.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(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="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password / app 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="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>IMAP port</span><input id="mail-account-imap-port" type="number" inputmode="numeric" min="1" max="65535" value="${existingAccount?.imapPort || (existingAccount?.authMethod === 'oauth2' ? 993 : 143)}"></label><label class="compose-line mail-security-option"><span>IMAP implicit SSL/TLS (usually port 993)</span><input id="mail-account-imap-secure" type="checkbox"${existingAccount?.imapSecure ? ' checked' : ''}></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>SMTP port</span><input id="mail-account-smtp-port" type="number" inputmode="numeric" min="1" max="65535" value="${existingAccount?.smtpPort || 587}"></label><label class="compose-line mail-security-option"><span>SMTP implicit SSL/TLS (usually port 465)</span><input id="mail-account-smtp-secure" type="checkbox"${existingAccount?.smtpSecure ? ' checked' : ''}></label><p class="account-note">For IMAP port 143 and SMTP port 587, leave implicit SSL/TLS off to use required STARTTLS. Common Gmail settings are IMAP SSL/TLS on port 993 and SMTP STARTTLS on port 587; use an app password if required by your provider.</p><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">${escapeMailUi(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 &amp; reconnect' : 'Test &amp; connect'}</button></div></div></div>`;
const authMethodRow = document.createElement('label');
authMethodRow.className = 'compose-line';
authMethodRow.innerHTML = '<span>Sign-in method</span><select id="mail-account-auth-method" class="settings-select"><option value="password">App password</option><option value="oauth2">OAuth2</option></select>';
const emailRow = selectMailUi('#mail-account-email').closest('.compose-line');
emailRow.after(authMethodRow);
const oauthProviderRow = document.createElement('label');
oauthProviderRow.className = 'compose-line';
oauthProviderRow.innerHTML = '<span>Provider</span><select id="mail-account-oauth-provider" class="settings-select"><option value="google">Google</option><option value="microsoft">Microsoft</option></select>';
authMethodRow.after(oauthProviderRow);
const reauthorizeRow = document.createElement('label');
reauthorizeRow.className = 'compose-line';
reauthorizeRow.innerHTML = '<span>Sign in again</span><input id="mail-account-reauthorize" type="checkbox">';
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 = `<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${escapeMailUi(rule?.senderContains || '')}"><input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${escapeMailUi(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="${escapeMailUi(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';
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 = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`;
}
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 => `
<div class="message" data-id="${escapeMailUi(message.id)}"><input class="row-check" type="checkbox" aria-label="Select draft"${mailFeatureState.selectedDraftIds.has(String(message.id)) ? ' checked' : ''}><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${escapeMailUi(message.email)}</div><div class="subject">${escapeMailUi(message.subject)}</div><div class="snippet">${escapeMailUi(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${escapeMailUi(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 = 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 () => {
let showingCachedMessages = false;
try {
if (rendererState.activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts();
renderDrafts(result.drafts || []);
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.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
const filters = mailSearchFilters();
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId;
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;
appShell.renderList();
showingCachedMessages = true;
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Showing saved messages — syncing';
}
} catch (error) {
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) 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
: 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 ? 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.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 (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 (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.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;
})();