Compare commits

...
5 Commits
10 changed files with 471 additions and 85 deletions
+15 -3
View File
@@ -4,6 +4,8 @@
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
- [ ] Add Android support for the mail app.
- [x] Show the app version after **ep-mail** in the window title.
## Mail security
@@ -11,14 +13,24 @@
## Appearance and settings
- [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears.
- [x] Make **EP Wasteland** the default theme for new users.
- [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts.
- [x] Keep the display name in Account Settings and make it available while adding a mailbox.
## Account settings
- [ ] Fix the mailbox space indicator; it is not working.
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
- [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
- [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support.
- [ ] Add push mail support.
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
- [x] Add new mail notifications.
- [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup.
- [ ] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views.
- [x] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views.
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name.
- [ ] Display name must be set per account.
- [ ] Remove the display name initials from the bottom-left corner.
- [x] Display name must be set per account.
- [x] Remove the display name initials from the bottom-left corner.
+4 -2
View File
@@ -3,8 +3,8 @@ async function openAccountManager(){
try{
const data=await window.daybreakMail.listAccounts();
const accounts=data.accounts||[];
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.email)}</strong><small>${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Mail accounts</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.displayName||account.email)}</strong><small>${esc(account.email)} · ${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
const close=()=>root.innerHTML='';
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
@@ -12,6 +12,8 @@ async function openAccountManager(){
root.onclick=async event=>{
const switchButton=event.target.closest('[data-switch-account]');
if(switchButton){switchButton.disabled=true;try{connectedMailAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);activeFolder='Inbox';mailPageOffset=0;document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';updateAccountCard(connectedMailAccount);close();await syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
const davButton=event.target.closest('[data-open-dav]');
if(davButton){close();openDavManager(davButton.dataset.openDav);return}
const editButton=event.target.closest('[data-edit-account]');
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)openMailAccount(account);return}
const removeButton=event.target.closest('[data-remove-account]');
+1 -1
View File
@@ -35,4 +35,4 @@ function showDavConnect(type){
root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}};
root.querySelector('#dav-server-url').focus();
}
document.addEventListener('click',event=>{const button=event.target.closest('#caldav-settings,#caldav-sync,#carddav-settings,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();const type=button.id.startsWith('caldav')?'caldav':'carddav';if(button.id.endsWith('settings'))openDavManager(type);else syncDav(type)},true);
document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true);
+343 -31
View File
@@ -1,4 +1,4 @@
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog } = require('electron');
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor } = require('electron');
const path = require('node:path');
const fs = require('node:fs/promises');
const { ImapFlow } = require('imapflow');
@@ -10,6 +10,137 @@ const ICAL = require('ical.js');
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
const backgroundSyncIntervalMs = 2 * 60 * 1000;
const backgroundSyncConcurrency = 2;
const backgroundIdleConcurrency = 2;
let accountStoreQueue = Promise.resolve();
let backgroundSyncInProgress = false;
let backgroundSyncRequested = false;
const backgroundSyncGenerations = new Map();
const backgroundSyncFailures = new Map();
const flagSnapshots = new Map();
const idleWatchers = new Map();
function updateAccountStore(update) {
const operation = accountStoreQueue.then(async () => {
const store = (await readAccountStore()) || { accounts: [], activeId: null };
const result = await update(store);
if (store.accounts.length) await saveAccountStore(store);
else await fs.rm(credentialsPath(), { force: true });
return result;
});
accountStoreQueue = operation.catch(() => {});
return operation;
}
function sendMailSyncUpdate(update) {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed() && !window.webContents.isDestroyed()) {
window.webContents.send('mail:sync-update', update);
}
}
}
function requestBackgroundSync(accountId = null, force = false) {
if (accountId) {
backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1);
backgroundSyncFailures.delete(accountId);
flagSnapshots.delete(accountId);
}
if (force) {
for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0;
}
void reconcileIdleWatchers().catch(error => console.error('Could not reconcile IMAP IDLE watchers:', error));
if (backgroundSyncInProgress) {
if (accountId || force) backgroundSyncRequested = true;
return;
}
backgroundSyncRequested = true;
void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error));
}
function stopIdleWatcher(accountId) {
const watcher = idleWatchers.get(accountId);
if (!watcher) return;
watcher.stopped = true;
watcher.client?.close();
idleWatchers.delete(accountId);
}
function startIdleWatcher(account) {
if (idleWatchers.has(account.id)) return;
const watcher = {
generation: backgroundSyncGenerations.get(account.id) || 0,
stopped: false,
client: null
};
idleWatchers.set(account.id, watcher);
void runIdleWatcher(account.id, watcher).catch(error => {
console.error(`IMAP IDLE watcher failed for ${account.email}:`, error);
});
}
async function runIdleWatcher(accountId, watcher) {
let failures = 0;
while (!watcher.stopped && backgroundSyncGenerations.get(accountId) === watcher.generation) {
let client;
try {
const account = await readAccount(accountId);
if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
client = imapClient(account, {
autoIdleDelay: 10_000,
maxIdleTime: 25 * 60 * 1000,
socketTimeout: 30 * 60 * 1000
});
watcher.client = client;
let signalDisconnected;
const disconnected = new Promise(resolve => { signalDisconnected = resolve; });
client.on('exists', event => {
if (event.path.toLowerCase() === 'inbox' && event.count > event.prevCount) requestBackgroundSync();
});
client.on('flags', event => {
if (event.path.toLowerCase() === 'inbox') requestBackgroundSync();
});
client.on('error', error => {
if (!watcher.stopped) console.error(`IMAP IDLE connection failed for ${account.email}:`, error);
signalDisconnected();
});
client.once('close', signalDisconnected);
await client.connect();
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
await client.mailboxOpen('INBOX', { readOnly: true });
const connectedAt = Date.now();
await disconnected;
if (Date.now() - connectedAt > 60_000) failures = 0;
} catch (error) {
if (!watcher.stopped) console.error(`IMAP IDLE watcher disconnected for ${accountId}:`, error);
} finally {
if (watcher.client === client) watcher.client = null;
if (client?.usable) await client.logout().catch(() => client.close());
else client?.close();
}
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
const retryDelay = Math.min(5 * 60 * 1000, 15_000 * (2 ** Math.min(failures, 5)));
failures += 1;
await new Promise(resolve => {
const timer = setTimeout(resolve, retryDelay);
timer.unref();
});
}
}
async function reconcileIdleWatchers() {
const store = (await readAccountStore()) || { accounts: [] };
const desiredAccounts = store.accounts.slice(0, backgroundIdleConcurrency);
const desiredIds = new Set(desiredAccounts.map(account => account.id));
for (const [accountId, watcher] of idleWatchers) {
if (!desiredIds.has(accountId) || watcher.generation !== (backgroundSyncGenerations.get(accountId) || 0)) {
stopIdleWatcher(accountId);
}
}
for (const account of desiredAccounts) startIdleWatcher(account);
}
async function readDavStore() {
try {
@@ -65,13 +196,15 @@ function normalizeAccount(input) {
const password = String(input?.password || '');
const imapHost = String(input?.imapHost || '').trim();
const smtpHost = String(input?.smtpHost || '').trim();
const displayName = String(input?.displayName || '').trim().slice(0, 80);
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) {
throw new Error('Enter a valid email, password, and both mail server names.');
}
return { email, password, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
if (!displayName) throw new Error('Enter a display name for this mail account.');
return { email, password, displayName, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
}
function imapClient(account) {
function imapClient(account, options = {}) {
return new ImapFlow({
host: account.imapHost,
port: account.imapPort,
@@ -82,7 +215,8 @@ function imapClient(account) {
logger: false,
connectionTimeout: 15000,
greetingTimeout: 10000,
socketTimeout: 20000
socketTimeout: 20000,
...options
});
}
@@ -138,17 +272,17 @@ async function readAccount(accountId = null) {
}
function publicAccount(account) {
return { id: account.id, email: account.email, imapHost: account.imapHost, smtpHost: account.smtpHost };
return { id: account.id, email: account.email, displayName: account.displayName || '', imapHost: account.imapHost, smtpHost: account.smtpHost };
}
async function saveAccount(account) {
const store = (await readAccountStore()) || { accounts: [], activeId: null };
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
const saved = { ...account, id: existing?.id || randomUUID() };
store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved];
store.activeId = saved.id;
await saveAccountStore(store);
return saved;
return updateAccountStore(store => {
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
const saved = { ...existing, ...account, id: existing?.id || randomUUID() };
store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved];
store.activeId = saved.id;
return saved;
});
}
async function connectMail(account) {
@@ -245,6 +379,162 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
}
}
async function saveAccountSyncState(accountId, generation, folders) {
return updateAccountStore(store => {
const account = store.accounts.find(item => item.id === accountId);
if (!account || backgroundSyncGenerations.get(accountId) !== generation) return false;
account.syncState = account.syncState || { folders: {} };
account.syncState.folders = folders;
return true;
});
}
function backgroundFolderLabel(mailbox) {
const specialUse = String(mailbox.specialUse || '').toLowerCase();
if (specialUse === '\\sent') return 'Sent';
if (specialUse === '\\archive') return 'Archive';
if (specialUse === '\\trash') return 'Trash';
if (mailbox.path.toLowerCase() === 'inbox') return 'Inbox';
const finalPart = mailbox.path.toLowerCase().split(/[./]/).pop();
if (['sent', 'sent items', 'sent mail', 'sent messages'].includes(finalPart)) return 'Sent';
if (['archive', 'archives', 'all mail'].includes(finalPart)) return 'Archive';
if (['trash', 'deleted items', 'deleted messages'].includes(finalPart)) return 'Trash';
return mailbox.path;
}
async function syncAccountMailboxes(account) {
const generation = backgroundSyncGenerations.get(account.id) || 0;
const client = imapClient(account);
try {
await client.connect();
const mailboxes = await client.list();
const states = { ...(account.syncState?.folders || {}) };
const accountSnapshots = new Map(flagSnapshots.get(account.id) || []);
let inboxNewCount = 0;
const changedFolders = [];
for (const listedMailbox of mailboxes) {
const mailbox = await client.mailboxOpen(listedMailbox.path, { readOnly: true });
const folder = listedMailbox.path;
const label = backgroundFolderLabel(listedMailbox);
const uidValidity = String(mailbox.uidValidity);
const uidCeiling = Math.max(0, Number(mailbox.uidNext) - 1);
const oldState = states[folder];
const cursorIsValid = oldState?.uidValidity === uidValidity && Number.isInteger(oldState.lastUid);
if (!cursorIsValid) {
states[folder] = {
uidValidity,
lastUid: uidCeiling,
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : null
};
if (!mailbox.highestModseq) {
const initialFlags = await client.fetchAll('1:*', { uid: true, flags: true });
accountSnapshots.set(folder, {
uidValidity,
flags: new Map(initialFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]))
});
}
continue;
}
const previousUid = Number(oldState.lastUid);
const added = uidCeiling > previousUid
? await client.fetchAll(`${previousUid + 1}:${uidCeiling}`, { uid: true, envelope: true, flags: true }, { uid: true })
: [];
let flagsChanged = false;
if (mailbox.highestModseq && oldState.highestModseq) {
const changed = await client.fetchAll('1:*', { uid: true, flags: true, modseq: true }, {
uid: true,
changedSince: BigInt(oldState.highestModseq)
});
flagsChanged = changed.some(item => Number(item.uid) <= previousUid);
} else if (!mailbox.highestModseq) {
const currentFlags = await client.fetchAll('1:*', { uid: true, flags: true });
const nextSnapshot = new Map(currentFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]));
const previousSnapshot = accountSnapshots.get(folder);
if (previousSnapshot?.uidValidity === uidValidity) {
flagsChanged = [...previousSnapshot.flags].some(([uid, flags]) => uid <= previousUid && nextSnapshot.get(uid) !== flags);
}
accountSnapshots.set(folder, { uidValidity, flags: nextSnapshot });
}
states[folder] = {
uidValidity,
lastUid: Math.max(previousUid, uidCeiling),
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : oldState.highestModseq || null
};
if (added.length && label === 'Inbox') inboxNewCount += added.length;
if (added.length || flagsChanged) changedFolders.push(label);
}
const saved = await saveAccountSyncState(account.id, generation, states);
if (!saved || backgroundSyncGenerations.get(account.id) !== generation) {
return { newCount: 0, changedFolders: [] };
}
flagSnapshots.set(account.id, accountSnapshots);
return { newCount: inboxNewCount, changedFolders: [...new Set(changedFolders)] };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
function showNewMailNotification(account, count) {
if (!count || !Notification.isSupported()) return;
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
if (focused) return;
const notification = new Notification({
title: count === 1 ? 'New mail' : `${count} new messages`,
body: account.email
});
notification.show();
}
async function syncAccountWithBackoff(account) {
const failure = backgroundSyncFailures.get(account.id);
if (failure && Date.now() < failure.retryAt) return;
const generation = backgroundSyncGenerations.get(account.id) || 0;
try {
const result = await syncAccountMailboxes(account);
if (backgroundSyncGenerations.get(account.id) !== generation) return;
backgroundSyncFailures.delete(account.id);
if (result.newCount || result.changedFolders.length) {
const update = { accountId: account.id, newCount: result.newCount, foldersChanged: result.changedFolders };
sendMailSyncUpdate(update);
showNewMailNotification(account, result.newCount);
}
} catch (error) {
const attempts = (failure?.attempts || 0) + 1;
const retryDelay = Math.min(30 * 60 * 1000, backgroundSyncIntervalMs * (2 ** Math.min(attempts - 1, 4)));
backgroundSyncFailures.set(account.id, { attempts, retryAt: Date.now() + retryDelay });
console.error(`Background mail sync failed for ${account.email}:`, error);
if (!failure) sendMailSyncUpdate({ accountId: account.id, error: 'Background mail sync failed. Will retry automatically.' });
}
}
async function runBackgroundSync() {
if (backgroundSyncInProgress) {
backgroundSyncRequested = true;
return;
}
backgroundSyncInProgress = true;
try {
do {
backgroundSyncRequested = false;
const store = (await readAccountStore()) || { accounts: [] };
for (let index = 0; index < store.accounts.length; index += backgroundSyncConcurrency) {
await Promise.all(store.accounts.slice(index, index + backgroundSyncConcurrency).map(syncAccountWithBackoff));
}
} while (backgroundSyncRequested);
} finally {
backgroundSyncInProgress = false;
if (backgroundSyncRequested) void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error));
}
}
ipcMain.handle('app:get-version', () => app.getVersion());
ipcMain.handle('mail:get-account', async () => {
const account = await readAccount();
return account ? publicAccount(account) : null;
@@ -256,35 +546,45 @@ ipcMain.handle('mail:list-accounts', async () => {
});
ipcMain.handle('mail:select-account', async (_event, accountId) => {
const store = await readAccountStore();
const account = store?.accounts.find(item => item.id === accountId);
if (!account) throw new Error('That mail account is no longer available.');
store.activeId = account.id;
await saveAccountStore(store);
const account = await updateAccountStore(store => {
const selected = store.accounts.find(item => item.id === accountId);
if (!selected) throw new Error('That mail account is no longer available.');
store.activeId = selected.id;
return selected;
});
requestBackgroundSync();
return publicAccount(account);
});
ipcMain.handle('mail:remove-account', async (_event, accountId) => {
const store = await readAccountStore();
if (!store) return { accounts: [], activeId: null };
store.accounts = store.accounts.filter(account => account.id !== accountId);
if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null;
if (store.accounts.length) await saveAccountStore(store);
else await fs.rm(credentialsPath(), { force: true });
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
const result = await updateAccountStore(store => {
store.accounts = store.accounts.filter(account => account.id !== accountId);
if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null;
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
});
requestBackgroundSync(accountId);
requestBackgroundSync();
return result;
});
ipcMain.handle('mail:update-account', async (_event, accountId, input) => {
const store = await readAccountStore();
const existing = store?.accounts.find(account => account.id === accountId);
const existing = await readAccount(accountId);
if (!existing) throw new Error('That mail account is no longer available.');
const account = normalizeAccount({ ...existing, ...input, password: String(input?.password || '') || existing.password });
account.id = existing.id;
try {
const status = await connectMail(account);
store.accounts = store.accounts.map(item => item.id === existing.id ? account : item);
await saveAccountStore(store);
return { ...publicAccount(account), ...status };
const savedAccount = await updateAccountStore(store => {
const current = store.accounts.find(item => item.id === existing.id);
if (!current) throw new Error('That mail account is no longer available.');
const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost;
store.accounts = store.accounts.map(item => item.id === existing.id
? { ...account, syncState: endpointChanged ? undefined : current.syncState }
: item);
return store.accounts.find(item => item.id === existing.id);
});
requestBackgroundSync(existing.id);
return { ...publicAccount(savedAccount), ...status };
} catch (error) {
throw new Error(`Could not update the mailbox: ${error.message}`);
}
@@ -295,6 +595,7 @@ ipcMain.handle('mail:connect', async (_event, input) => {
try {
const status = await connectMail(account);
const saved = await saveAccount(account);
requestBackgroundSync(saved.id);
return { ok: true, ...publicAccount(saved), ...status };
} catch (error) {
throw new Error(`Could not connect to the mailbox: ${error.message}`);
@@ -391,7 +692,7 @@ ipcMain.handle('mail:send', async (_event, message) => {
if (!to) throw new Error('Add at least one recipient.');
const transport = smtpTransport(account);
const sentMessageId = `<${require('node:crypto').randomUUID()}@ep-mail.local>`;
const fromName = String(message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
const messageOptions = {
from: { name: fromName, address: account.email },
to,
@@ -603,7 +904,7 @@ function createWindow() {
height: 920,
minWidth: 920,
minHeight: 680,
title: 'ep-mail',
title: `ep-mail v${app.getVersion()}`,
backgroundColor: '#f4f5f1',
show: false,
autoHideMenuBar: true,
@@ -631,6 +932,13 @@ function createWindow() {
app.whenReady().then(() => {
app.setAppUserModelId('studio.daybreak.mail');
createWindow();
const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs);
syncTimer.unref();
requestBackgroundSync();
powerMonitor.on('suspend', () => {
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
});
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
@@ -639,3 +947,7 @@ app.whenReady().then(() => {
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('before-quit', () => {
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
});
+2
View File
@@ -1,6 +1,7 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('daybreakMail', {
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
getAccount: () => ipcRenderer.invoke('mail:get-account'),
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
@@ -9,6 +10,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details),
syncFolder: (folder, offset) => ipcRenderer.invoke('mail:sync-folder', folder, offset),
syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'),
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
send: message => ipcRenderer.invoke('mail:send', message),
-1
View File
@@ -19,7 +19,6 @@
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
<div class="rail-spacer"></div>
<button class="avatar tiny profile-button" title="Account settings" aria-label="Account settings"><span>•</span></button>
</aside>
<aside class="sidebar">
+99 -39
View File
@@ -1,26 +1,34 @@
let connectedMailAccount = null;
let mailPageOffset = 0;
let mailTotal = 0;
let mailboxSyncPromise = null;
let mailboxSyncQueued = false;
let mailboxRefreshPending = false;
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 displayName = account.displayName?.trim() || 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';
const profileButton = $('.top-avatar');
if (profileButton) {
profileButton.textContent = initials || 'M';
profileButton.title = `${displayName} <${email}>`;
profileButton.setAttribute('aria-label', `${displayName} account settings`);
}
}
function openMailAccount(existingAccount = null) {
const root = $('#modal-root');
const editing = Boolean(existingAccount);
const displayName = 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 displayName = existingAccount?.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>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><p class="account-note">This display name is saved for this mailbox and used on outgoing messages. IMAP uses STARTTLS on port 143 · SMTP uses STARTTLS on port 587.${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 close = () => { root.innerHTML = ''; };
$$('.modal-close').forEach(button => button.onclick = close);
$('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
@@ -30,6 +38,7 @@ function openMailAccount(existingAccount = null) {
const status = $('#mail-account-status');
const password = $('#mail-account-password').value;
const name = $('#mail-account-display-name').value.trim();
if (!name) { status.textContent = 'Enter a display name for this mail account.'; $('#mail-account-display-name').focus(); return; }
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; }
button.disabled = true;
button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…';
@@ -38,13 +47,13 @@ function openMailAccount(existingAccount = null) {
const details = {
email: $('#mail-account-email').value,
password,
displayName: name,
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) {
@@ -73,51 +82,102 @@ function openMailAccount(existingAccount = null) {
$('#mail-account-email').focus();
}
async function syncMailbox(showToast, options = {}) {
if (mailboxSyncPromise) {
mailboxSyncQueued = true;
return mailboxSyncPromise;
}
if (!connectedMailAccount || !window.daybreakMail) {
openMailAccount();
return;
}
const refresh = $('#refresh');
if (refresh) refresh.disabled = true;
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(() => {});
const sync = (async () => {
try {
const previouslyActiveMessage = activeMessage;
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.some(message => message.id === previouslyActiveMessage)
? previouslyActiveMessage
: messages[0]?.id;
selectedIds.clear();
const unread = messages.filter(message => message.unread).length;
const inboxCount = $('.folder[data-folder="Inbox"] .count');
if (inboxCount) inboxCount.textContent = String(unread);
const pagination = $('#pagination');
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = $('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
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;
}
else $('#reader-pane').innerHTML = emptyReader();
updateAccountCard(connectedMailAccount);
if (showToast) toast(`Synced ${messages.length} messages`);
} catch (error) {
toast(error.message || 'Could not sync the inbox');
})();
mailboxSyncPromise = sync;
try {
await sync;
} finally {
if (refresh) refresh.disabled = false;
mailboxSyncPromise = null;
if (mailboxSyncQueued) {
mailboxSyncQueued = false;
void syncMailbox(false);
}
}
}
if (window.daybreakMail) {
window.daybreakMail.getAppVersion().then(version => {
document.title = `ep-mail v${version}`;
}).catch(error => {
console.error('Could not read app version:', error);
});
window.daybreakMail.onSyncUpdate(update => {
if (update.accountId !== connectedMailAccount?.id) return;
if (update.error) {
toast(update.error);
return;
}
if (update.newCount || (update.foldersChanged || []).length) {
if (document.visibilityState === 'visible') {
syncMailbox(false, update.newCount ? { offset: 0 } : {});
}
else mailboxRefreshPending = true;
}
});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && mailboxRefreshPending) {
mailboxRefreshPending = false;
syncMailbox(false, { offset: 0 });
}
});
window.addEventListener('focus', () => {
if (connectedMailAccount) syncMailbox(false);
});
setInterval(() => {
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') {
syncMailbox(false);
}
}, 60 * 1000);
$('#account-settings').addEventListener('click', openMailAccount);
$('#account-settings').addEventListener('keydown', event => {
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); }
@@ -156,7 +216,7 @@ if (window.daybreakMail) {
cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value,
displayName: profileSettings.name
displayName: connectedMailAccount.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');
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "ep-mail",
"version": "0.1.12",
"version": "0.1.16",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ep-mail",
"version": "0.1.12",
"version": "0.1.16",
"dependencies": {
"ical.js": "^2.2.1",
"imapflow": "2.2.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ep-mail",
"version": "0.1.12",
"version": "0.1.16",
"private": true,
"description": "Eternity Project mail client",
"author": "Eternity Project",
+4 -5
View File
@@ -11,10 +11,10 @@ productWrite(productKeys.contacts, savedContacts);
let savedEvents = productRead(productKeys.events, []);
let customLabels = productRead(productKeys.labels, []);
let snoozedIds = productRead(productKeys.snoozed, []);
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; $$('.profile-button').forEach(b => b.textContent = profileSettings.name.split(/\s+/).filter(Boolean).map(x=>x[0]).join('').slice(0,2).toUpperCase() || '•'); if (connectedMailAccount) updateAccountCard(connectedMailAccount); }
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); }
function openAccountSettings() {
const root=$('#modal-root');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting and profile.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
const close=()=>root.innerHTML='';
$$('.modal-close').forEach(button=>button.onclick=close);
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
@@ -34,9 +34,9 @@ function openPreferences() {
$('#theme-select').focus();
}
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${esc(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${esc(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${esc(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${esc(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${esc(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=async()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toast('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); }
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-settings">CalDAV servers</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${esc(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${esc(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${esc(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()}
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-settings">CardDAV servers</button><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}}
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}}
function renderLabels(){const box=$('#custom-labels');if(!box)return;box.innerHTML=customLabels.map(label=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})}
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')}
function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:activeFolder,action,enabled:action==='star'?!message.star:true})}return Promise.resolve()}
@@ -47,4 +47,3 @@ const baseMessageRenderer=renderList;
renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?snoozedIds.includes(m.id):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';return}baseMessageRenderer()};
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true);