Files
ep-mail-client/mail-ui.js
T
2026-10-06 00:22:47 +03:00

178 lines
9.5 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.
let connectedMailAccount = null;
let mailPageOffset = 0;
let mailTotal = 0;
function updateAccountCard(account) {
const card = $('#account-settings');
if (!card) return;
const email = account.email || '';
const localName = (email.split('@')[0] || 'Mail account').replace(/[._-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase());
const displayName = profileSettings.name.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}>`;
card.querySelector('.online-dot').style.background = '#70ad7b';
}
function openMailAccount(existingAccount = null) {
const root = $('#modal-root');
const editing = Boolean(existingAccount);
const displayName = profileSettings.name || '';
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${esc(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name"></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><p class="account-note">IMAP uses STARTTLS on port 143 · SMTP uses STARTTLS on port 587.${editing ? ' Leave the password empty to keep the saved password.' : ' Your display name is also used as the sender name.'}</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 close = () => { root.innerHTML = ''; };
$$('.modal-close').forEach(button => button.onclick = close);
$('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
$('#disconnect-mail').onclick = close;
$('#connect-mail').onclick = async () => {
const button = $('#connect-mail');
const status = $('#mail-account-status');
const password = $('#mail-account-password').value;
const name = $('#mail-account-display-name').value.trim();
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; }
button.disabled = true;
button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…';
status.textContent = editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.';
try {
const details = {
email: $('#mail-account-email').value,
password,
imapHost: $('#mail-account-imap').value,
smtpHost: $('#mail-account-smtp').value
};
const account = editing
? await window.daybreakMail.updateAccount(existingAccount.id, details)
: await window.daybreakMail.connect(details);
if (name) setProfileName(name);
if (editing) {
const accountList = await window.daybreakMail.listAccounts();
if (accountList.activeId === account.id) {
connectedMailAccount = account;
updateAccountCard(account);
mailPageOffset = 0;
close();
await syncMailbox(false, { offset: 0 });
} else {
close();
}
toast('Mailbox settings updated');
} else {
connectedMailAccount = account;
updateAccountCard(account);
close();
toast('Mailbox connected securely');
await syncMailbox(true);
}
} catch (error) {
status.textContent = error.message || 'Could not connect. Check the account details and try again.';
button.disabled = false;
button.textContent = editing ? 'Save & reconnect' : 'Test & connect';
}
};
$('#mail-account-email').focus();
}
async function syncMailbox(showToast, options = {}) {
if (!connectedMailAccount || !window.daybreakMail) {
openMailAccount();
return;
}
const refresh = $('#refresh');
if (refresh) refresh.disabled = true;
try {
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
const result = await window.daybreakMail.syncFolder(activeFolder, offset);
if (options.append) messages.push(...result.messages);
else messages.splice(0, messages.length, ...result.messages);
messages.forEach(message => {
try {
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
message.tags = [...new Set([...(message.tags || []), ...localTags])];
} catch {}
});
if (!options.append) mailPageOffset = offset;
mailTotal = result.total;
activeMessage = messages[0]?.id;
selectedIds.clear();
const unread = messages.filter(message => message.unread).length;
const inboxCount = $('.folder[data-folder="Inbox"] .count');
if (inboxCount) inboxCount.textContent = String(unread);
const pagination = $('#pagination');
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = $('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
renderList();
if (activeMessage) {
openMessage(activeMessage);
const current = messages.find(message => message.id === activeMessage);
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: activeFolder, action: 'unread', enabled: false }).catch(() => {});
}
else $('#reader-pane').innerHTML = emptyReader();
updateAccountCard(connectedMailAccount);
if (showToast) toast(`Synced ${messages.length} messages`);
} catch (error) {
toast(error.message || 'Could not sync the inbox');
} finally {
if (refresh) refresh.disabled = false;
}
}
if (window.daybreakMail) {
$('#account-settings').addEventListener('click', openMailAccount);
$('#account-settings').addEventListener('keydown', event => {
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); }
});
$('#settings-button').onclick = () => openPreferences();
$('#refresh').onclick = () => syncMailbox(true);
$$('.folder').forEach(button => button.addEventListener('click', () => {
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred'].includes(button.dataset.folder)) {
mailPageOffset = 0;
syncMailbox(false, { offset: 0 });
}
}));
$('#previous-page').onclick = () => {
if (mailPageOffset <= 0) return;
mailPageOffset = Math.max(0, mailPageOffset - 20);
syncMailbox(false, { offset: mailPageOffset });
};
$('#next-page').onclick = () => {
if (mailPageOffset + 20 >= mailTotal) return;
mailPageOffset += 20;
syncMailbox(false, { offset: mailPageOffset });
};
$('#load-more').onclick = () => syncMailbox(false, { append: true });
document.addEventListener('click', async event => {
const sendButton = event.target.closest('#send');
if (!sendButton || !connectedMailAccount) return;
event.preventDefault();
event.stopImmediatePropagation();
const recipient = $('#compose-to').value.trim();
if (!recipient) { $('#compose-to').focus(); toast('Add a recipient to send your message'); return; }
sendButton.disabled = true;
sendButton.textContent = 'Sending…';
try {
const result = await window.daybreakMail.send({
to: recipient,
cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value,
displayName: profileSettings.name
});
$('#modal-root').innerHTML = '';
toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
} catch (error) {
sendButton.disabled = false;
sendButton.textContent = 'Send ↗';
toast(error.message || 'Message could not be sent');
}
}, true);
window.daybreakMail.getAccount().then(account => {
if (!account) return;
connectedMailAccount = account;
updateAccountCard(account);
syncMailbox(false);
}).catch(() => {});
}