Add Snooze messages until a chosen time and show a follow-up reminder when they return. Bump version V0.1.17

This commit is contained in:
2026-10-07 00:55:14 +03:00
parent 520056d27c
commit a1b8bca066
25 changed files with 796 additions and 59 deletions
+2 -2
View File
@@ -1,12 +1,12 @@
# ep-mail # ep-mail
An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, archive and trash actions, compose/reply/forward, contacts, and a month calendar. An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, snooze reminders, archive and trash actions, compose/reply/forward, contacts, and a month calendar.
## Desktop app ## Desktop app
The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. The app uses required STARTTLS for IMAP port 143 and SMTP port 587 and stores the password encrypted through the operating system credential store. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. The app uses required STARTTLS for IMAP port 143 and SMTP port 587 and stores the password encrypted through the operating system credential store. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
## Android app ## Android app
+11
View File
@@ -5,8 +5,19 @@
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation. - [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. - [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. - [ ] Add Android support for the mail app.
- [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution.
- [x] Show the app version after **ep-mail** in the window title. - [x] Show the app version after **ep-mail** in the window title.
## Mail workflow
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
- [ ] Add Undo Send and scheduled sending.
- [ ] Improve mail search with sender, subject, date, folder, and attachment filters.
- [ ] Add offline reading and drafts, with queued actions when connectivity returns.
- [ ] Add user-configurable rules to sort, archive, label, or flag messages automatically.
- [ ] Add per-account signatures, notification preferences, and sync settings.
- [ ] Block remote images by default and let users load them per message.
## Mail security ## Mail security
- [ ] Add support for encrypting and decrypting mail with private/public keys or a suitable standard. Decide on the encryption format, key storage and exchange flow, and compatibility requirements before implementation. - [ ] Add support for encrypting and decrypting mail with private/public keys or a suitable standard. Decide on the encryption format, key storage and exchange flow, and compatibility requirements before implementation.
@@ -132,6 +132,61 @@ internal object AndroidAccountVault {
} }
} }
@Synchronized
fun setSnooze(id: String, uid: Long, folder: String, dueAt: Long?, subject: String) {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val previous = account.optJSONArray("snoozedMessages") ?: JSONArray()
val updated = JSONArray()
for (itemIndex in 0 until previous.length()) {
val item = previous.getJSONObject(itemIndex)
if (item.optLong("uid") != uid || item.optString("folder") != folder) updated.put(item)
}
if (dueAt != null) {
updated.put(JSONObject()
.put("uid", uid)
.put("folder", folder)
.put("dueAt", dueAt)
.put("subject", subject.take(200)))
}
account.put("snoozedMessages", updated)
write(store)
return
}
}
@Synchronized
fun takeDueSnoozes(id: String, now: Long): JSONArray {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return JSONArray()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val previous = account.optJSONArray("snoozedMessages") ?: JSONArray()
val remaining = JSONArray()
val due = JSONArray()
for (itemIndex in 0 until previous.length()) {
val item = previous.getJSONObject(itemIndex)
if (item.optLong("dueAt") <= now) {
due.put(JSONObject(item.toString())
.put("accountId", id)
.put("email", account.optString("email")))
} else {
remaining.put(item)
}
}
if (due.length() > 0) {
account.put("snoozedMessages", remaining)
write(store)
}
return due
}
return JSONArray()
}
fun publicAccounts(accounts: JSONArray = this.accounts()): JSONArray { fun publicAccounts(accounts: JSONArray = this.accounts()): JSONArray {
val result = JSONArray() val result = JSONArray()
for (index in 0 until accounts.length()) { for (index in 0 until accounts.length()) {
@@ -57,8 +57,9 @@ internal object AndroidMailService {
JSONObject().put("mailbox", "INBOX").put("messages", count) JSONObject().put("mailbox", "INBOX").put("messages", count)
} }
fun sync(account: JSONObject, requestedFolder: String, offset: Int): JSONObject = fun sync(account: JSONObject, requestedFolder: String, offset: Int): JSONObject {
withStore(account) { _, store -> if (requestedFolder == "Snoozed") return syncSnoozed(account, offset)
return withStore(account) { _, store ->
val folder = resolveFolder(store, requestedFolder) val folder = resolveFolder(store, requestedFolder)
if (folder == null) return@withStore JSONObject() if (folder == null) return@withStore JSONObject()
.put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder) .put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder)
@@ -73,7 +74,15 @@ internal object AndroidMailService {
val first = (end - 19).coerceAtLeast(1) val first = (end - 19).coerceAtLeast(1)
val result = JSONArray() val result = JSONArray()
val batch = folder.getMessages(first, end).reversed() val batch = folder.getMessages(first, end).reversed()
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
for (message in batch) { for (message in batch) {
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
val isSnoozed = (0 until snoozed.length()).any { index ->
val item = snoozed.getJSONObject(index)
item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
item.optLong("dueAt") > System.currentTimeMillis()
}
if (isSnoozed) continue
result.put(messageJson(folder, message, requestedFolder)) result.put(messageJson(folder, message, requestedFolder))
} }
JSONObject().put("messages", result).put("total", total) JSONObject().put("messages", result).put("total", total)
@@ -82,13 +91,44 @@ internal object AndroidMailService {
folder.close(false) folder.close(false)
} }
} }
}
private fun syncSnoozed(account: JSONObject, offset: Int): JSONObject =
withStore(account) { _, store ->
val snoozes = account.optJSONArray("snoozedMessages") ?: JSONArray()
val pending = (0 until snoozes.length())
.map { snoozes.getJSONObject(it) }
.filter { it.optLong("dueAt") > System.currentTimeMillis() }
.sortedBy { it.optLong("dueAt") }
val page = pending.drop(offset.coerceAtLeast(0)).take(20)
val messages = JSONArray()
for (snooze in page) {
val sourceFolder = snooze.optString("folder", "Inbox")
val folder = resolveFolder(store, sourceFolder) ?: continue
folder.open(Folder.READ_ONLY)
try {
val message = (folder as? UIDFolder)?.getMessageByUID(snooze.optLong("uid")) ?: continue
messages.put(messageJson(folder, message, "Snoozed")
.put("sourceFolder", sourceFolder)
.put("snoozedUntil", snooze.optLong("dueAt")))
} finally {
folder.close(false)
}
}
JSONObject()
.put("messages", messages)
.put("total", pending.size)
.put("start", if (page.isEmpty()) 0 else offset + 1)
.put("end", offset + messages.length())
.put("folder", "Snoozed")
}
fun updateMessage(account: JSONObject, input: JSONObject): JSONObject = fun updateMessage(account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store -> withStore(account) { _, store ->
val uid = input.optLong("uid") val uid = input.optLong("uid")
require(uid > 0) { "That message could not be identified." } require(uid > 0) { "That message could not be identified." }
val action = input.optString("action") val action = input.optString("action")
require(action in setOf("star", "unread", "archive", "delete")) { "That mail action is not supported." } require(action in setOf("star", "unread", "archive", "delete", "inbox")) { "That mail action is not supported." }
val source = resolveFolder(store, input.optString("folder", "Inbox")) val source = resolveFolder(store, input.optString("folder", "Inbox"))
?: throw IllegalStateException("That mail folder could not be found.") ?: throw IllegalStateException("That mail folder could not be found.")
var expungeDeleted = false var expungeDeleted = false
@@ -99,18 +139,38 @@ internal object AndroidMailService {
when (action) { when (action) {
"star" -> message.setFlag(Flags.Flag.FLAGGED, input.optBoolean("enabled")) "star" -> message.setFlag(Flags.Flag.FLAGGED, input.optBoolean("enabled"))
"unread" -> message.setFlag(Flags.Flag.SEEN, !input.optBoolean("enabled")) "unread" -> message.setFlag(Flags.Flag.SEEN, !input.optBoolean("enabled"))
"archive", "delete" -> { "archive", "delete", "inbox" -> {
expungeDeleted = true val targetName = when (action) {
val targetName = if (action == "archive") "Archive" else "Trash" "archive" -> "Archive"
"delete" -> "Trash"
else -> "Inbox"
}
val target = resolveFolder(store, targetName) ?: store.getFolder(targetName) val target = resolveFolder(store, targetName) ?: store.getFolder(targetName)
if (!target.exists()) target.create(Folder.HOLDS_MESSAGES) if (!target.exists()) target.create(Folder.HOLDS_MESSAGES)
if (source.fullName == target.fullName) {
if (action == "delete") {
expungeDeleted = true
message.setFlag(Flags.Flag.DELETED, true)
}
} else {
expungeDeleted = true
source.copyMessages(arrayOf(message), target) source.copyMessages(arrayOf(message), target)
message.setFlag(Flags.Flag.DELETED, true) message.setFlag(Flags.Flag.DELETED, true)
} }
} }
}
} finally { } finally {
source.close(expungeDeleted) source.close(expungeDeleted)
} }
if (action == "archive" || action == "delete" || action == "inbox") {
AndroidAccountVault.setSnooze(
account.optString("id"),
uid,
input.optString("folder", "Inbox"),
null,
""
)
}
JSONObject().put("ok", true) JSONObject().put("ok", true)
} }
@@ -159,6 +159,49 @@ class EpMailPlugin : Plugin() {
} }
} }
@PluginMethod
fun setSnooze(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before setting a reminder.")
val uid = call.getLong("uid") ?: throw IllegalArgumentException("That message could not be identified.")
require(uid > 0) { "That message could not be identified." }
val folder = call.getString("sourceFolder") ?: call.getString("folder") ?: "Inbox"
require(folder in setOf("Inbox", "Sent", "Archive", "Trash")) { "That mailbox cannot be snoozed." }
val dueAt = call.getLong("dueAt")
if (dueAt != null && dueAt <= System.currentTimeMillis()) {
throw IllegalArgumentException("Choose a reminder time in the future.")
}
AndroidAccountVault.setSnooze(
account.optString("id"),
uid,
folder,
dueAt,
call.getString("subject").orEmpty()
)
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("foldersChanged", JSONArray().put("Snoozed").put(folder))
context.sendBroadcast(Intent(MailIdleService.ACTION_MAIL_SYNC)
.setPackage(context.packageName)
.putExtra(MailIdleService.EXTRA_SYNC_UPDATE, update.toString()))
MailIdleService.start(context)
call.resolve(JSObject().put("ok", true).put("snoozed", dueAt != null))
} catch (error: Exception) {
call.reject(error.message ?: "Could not set the reminder.")
}
}
@PluginMethod
fun checkSnoozeReminders(call: PluginCall) {
try {
MailIdleService.checkSnoozeReminders(context)
call.resolve()
} catch (error: Exception) {
call.reject(error.message ?: "Could not check mail reminders.")
}
}
@PluginMethod @PluginMethod
fun saveAttachment(call: PluginCall) { fun saveAttachment(call: PluginCall) {
try { try {
@@ -14,6 +14,7 @@ class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worke
override fun doWork(): Result { override fun doWork(): Result {
return try { return try {
AndroidAccountVault.initialize(applicationContext) AndroidAccountVault.initialize(applicationContext)
MailIdleService.checkSnoozeReminders(applicationContext)
val accounts = AndroidAccountVault.accounts() val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) { for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index) val account = accounts.getJSONObject(index)
@@ -181,6 +181,21 @@ class MailIdleService : Service() {
MailFallbackWorker.cancel(context) MailFallbackWorker.cancel(context)
} }
fun checkSnoozeReminders(context: Context) {
AndroidAccountVault.initialize(context)
val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
val reminders = AndroidAccountVault.takeDueSnoozes(
account.optString("id"),
System.currentTimeMillis()
)
for (reminderIndex in 0 until reminders.length()) {
notifySnoozeReminder(context, account, reminders.getJSONObject(reminderIndex))
}
}
}
fun notifyNewMail(context: Context, account: JSONObject, count: Int) { fun notifyNewMail(context: Context, account: JSONObject, count: Int) {
if (count <= 0) return if (count <= 0) return
val appContext = context.applicationContext val appContext = context.applicationContext
@@ -223,5 +238,54 @@ class MailIdleService : Service() {
android.util.Log.w(TAG, "Notification permission is unavailable", error) android.util.Log.w(TAG, "Notification permission is unavailable", error)
} }
} }
fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) {
val appContext = context.applicationContext
val email = account.optString("email")
val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
manager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"Mail reminders",
NotificationManager.IMPORTANCE_DEFAULT
))
}
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle("Mail reminder")
.setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" })
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(appPendingIntentFor(appContext))
.build()
try {
NotificationManagerCompat.from(appContext).notify(
(email + reminder.optLong("uid")).hashCode(),
notification
)
} catch (error: SecurityException) {
android.util.Log.w(TAG, "Reminder notification permission is unavailable", error)
}
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("snoozeReminder", true)
.put("foldersChanged", org.json.JSONArray()
.put("Snoozed")
.put(reminder.optString("folder", "Inbox")))
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
.setPackage(appContext.packageName)
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
}
private fun appPendingIntentFor(context: Context): PendingIntent {
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
?: Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
return PendingIntent.getActivity(
context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
} }
} }
+147 -7
View File
@@ -13,9 +13,11 @@ const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-account
const backgroundSyncIntervalMs = 2 * 60 * 1000; const backgroundSyncIntervalMs = 2 * 60 * 1000;
const backgroundSyncConcurrency = 2; const backgroundSyncConcurrency = 2;
const backgroundIdleConcurrency = 2; const backgroundIdleConcurrency = 2;
const snoozeCheckIntervalMs = 30 * 1000;
let accountStoreQueue = Promise.resolve(); let accountStoreQueue = Promise.resolve();
let backgroundSyncInProgress = false; let backgroundSyncInProgress = false;
let backgroundSyncRequested = false; let backgroundSyncRequested = false;
let snoozeReminderCheckInProgress = false;
const backgroundSyncGenerations = new Map(); const backgroundSyncGenerations = new Map();
const backgroundSyncFailures = new Map(); const backgroundSyncFailures = new Map();
const flagSnapshots = new Map(); const flagSnapshots = new Map();
@@ -41,6 +43,48 @@ function sendMailSyncUpdate(update) {
} }
} }
async function checkSnoozeReminders() {
if (snoozeReminderCheckInProgress) return;
snoozeReminderCheckInProgress = true;
try {
const current = await readAccountStore();
if (!current?.accounts.some(account =>
(account.snoozedMessages || []).some(item => Number(item.dueAt) <= Date.now())
)) return;
const due = await updateAccountStore(store => {
const reminders = [];
for (const account of store.accounts) {
const snoozes = account.snoozedMessages || [];
const remaining = [];
for (const item of snoozes) {
if (Number(item.dueAt) <= Date.now()) reminders.push({ accountId: account.id, email: account.email, ...item });
else remaining.push(item);
}
account.snoozedMessages = remaining;
}
return reminders;
});
for (const reminder of due) {
if (Notification.isSupported()) {
new Notification({
title: 'Mail reminder',
body: `${reminder.subject || 'A message'}${reminder.email ? ` · ${reminder.email}` : ''}`
}).show();
}
sendMailSyncUpdate({
accountId: reminder.accountId,
snoozeReminder: true,
snoozedFolder: reminder.folder,
foldersChanged: ['Snoozed', reminder.folder]
});
}
} catch (error) {
console.error('Could not process snooze reminders:', error);
} finally {
snoozeReminderCheckInProgress = false;
}
}
function requestBackgroundSync(accountId = null, force = false) { function requestBackgroundSync(accountId = null, force = false) {
if (accountId) { if (accountId) {
backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1); backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1);
@@ -326,6 +370,7 @@ async function folderPath(client, folder, createIfMissing = false) {
} }
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) { async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
const client = imapClient(account); const client = imapClient(account);
try { try {
await client.connect(); await client.connect();
@@ -342,15 +387,27 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
internalDate: true, internalDate: true,
source: true source: true
}); });
const snoozed = new Set((account.snoozedMessages || [])
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
.map(item => Number(item.uid)));
const messages = []; const messages = [];
for (const item of fetched.reverse()) { for (const item of fetched.reverse()) {
if (!item.source) continue; if (!item.source || snoozed.has(Number(item.uid))) continue;
messages.push(await toUiMessage(item, folder));
}
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
async function toUiMessage(item, folder) {
const parsed = await simpleParser(item.source); const parsed = await simpleParser(item.source);
const sender = parsed.from?.value?.[0]; const sender = parsed.from?.value?.[0];
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim(); const bodyText = String(parsed.text || '').replace(/\r/g, '').trim();
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.']; const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
const date = parsed.date || item.internalDate || new Date(); const date = parsed.date || item.internalDate || new Date();
messages.push({ return {
id: Number(item.uid), id: Number(item.uid),
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(), initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
color: '#dce6df', color: '#dce6df',
@@ -371,12 +428,42 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })), attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
attachment: parsed.attachments?.[0]?.filename || null, attachment: parsed.attachments?.[0]?.filename || null,
size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : '' size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : ''
};
}
async function fetchSnoozedMailbox(account, offset, limit) {
const now = Date.now();
const pending = (account.snoozedMessages || [])
.filter(item => Number(item.dueAt) > now)
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
const client = imapClient(account);
const messages = [];
try {
await client.connect();
for (const snooze of selected) {
const sourceFolder = String(snooze.folder || 'Inbox');
const mailboxPath = await folderPath(client, sourceFolder);
if (!mailboxPath) continue;
const lock = await client.getMailboxLock(mailboxPath);
try {
const item = await client.fetchOne(Number(snooze.uid), {
uid: true, envelope: true, flags: true, internalDate: true, source: true
}, { uid: true });
if (!item?.source) continue;
messages.push({
...await toUiMessage(item, 'Snoozed'),
sourceFolder,
snoozedUntil: Number(snooze.dueAt)
}); });
} finally {
lock.release();
}
} }
return { messages, total: mailbox.exists, start: first, end: Math.min(end, mailbox.exists), folder };
} finally { } finally {
if (client.usable) await client.logout().catch(() => {}); if (client.usable) await client.logout().catch(() => {});
} }
return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
} }
async function saveAccountSyncState(accountId, generation, folders) { async function saveAccountSyncState(accountId, generation, folders) {
@@ -579,7 +666,11 @@ ipcMain.handle('mail:update-account', async (_event, accountId, input) => {
if (!current) throw new Error('That mail account is no longer available.'); if (!current) throw new Error('That mail account is no longer available.');
const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost; const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost;
store.accounts = store.accounts.map(item => item.id === existing.id store.accounts = store.accounts.map(item => item.id === existing.id
? { ...account, syncState: endpointChanged ? undefined : current.syncState } ? {
...account,
syncState: endpointChanged ? undefined : current.syncState,
snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || [])
}
: item); : item);
return store.accounts.find(item => item.id === existing.id); return store.accounts.find(item => item.id === existing.id);
}); });
@@ -610,6 +701,39 @@ ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0) =
return fetchMailbox(account, folder, offset); return fetchMailbox(account, folder, offset);
}); });
ipcMain.handle('mail:set-snooze', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before setting a reminder.');
const uid = Number(input?.uid);
const folder = String(input?.sourceFolder || input?.folder || 'Inbox');
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.');
const dueAt = input?.dueAt == null ? null : Number(input.dueAt);
if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) {
throw new Error('Choose a reminder time in the future.');
}
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) throw new Error('That mail account is no longer available.');
const snoozes = saved.snoozedMessages || [];
const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder));
if (dueAt != null) {
remaining.push({
uid,
folder,
dueAt,
subject: String(input.subject || '').slice(0, 200)
});
}
saved.snoozedMessages = remaining;
});
sendMailSyncUpdate({
accountId: account.id,
foldersChanged: ['Snoozed', folder]
});
return { ok: true, snoozed: dueAt != null };
});
ipcMain.handle('mail:update-message', async (_event, input) => { ipcMain.handle('mail:update-message', async (_event, input) => {
const account = await readAccount(); const account = await readAccount();
if (!account) throw new Error('Add a mail account before changing messages.'); if (!account) throw new Error('Add a mail account before changing messages.');
@@ -617,7 +741,7 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
const folder = String(input?.folder || 'Inbox'); const folder = String(input?.folder || 'Inbox');
const action = String(input?.action || ''); const action = String(input?.action || '');
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.'); if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
if (!['star', 'unread', 'archive', 'delete'].includes(action)) throw new Error('That mail action is not supported.'); if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
const client = imapClient(account); const client = imapClient(account);
try { try {
await client.connect(); await client.connect();
@@ -634,13 +758,26 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
} else { } else {
const target = action === 'archive' const target = action === 'archive'
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive') ? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
: await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash'); : action === 'delete'
if (action === 'delete' && sourcePath === target) await client.messageDelete(uid, { uid: true }); ? await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash')
: 'INBOX';
if ((action === 'delete' || action === 'inbox') && sourcePath === target) {
if (action === 'delete') await client.messageDelete(uid, { uid: true });
}
else await client.messageMove(uid, target, { uid: true }); else await client.messageMove(uid, target, { uid: true });
} }
} finally { } finally {
lock.release(); lock.release();
} }
if (action === 'archive' || action === 'delete' || action === 'inbox') {
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (saved) {
saved.snoozedMessages = (saved.snoozedMessages || [])
.filter(item => Number(item.uid) !== uid || item.folder !== folder);
}
});
}
return { ok: true }; return { ok: true };
} finally { } finally {
if (client.usable) await client.logout().catch(() => {}); if (client.usable) await client.logout().catch(() => {});
@@ -934,6 +1071,9 @@ app.whenReady().then(() => {
createWindow(); createWindow();
const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs); const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs);
syncTimer.unref(); syncTimer.unref();
const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs);
snoozeTimer.unref();
void checkSnoozeReminders();
requestBackgroundSync(); requestBackgroundSync();
powerMonitor.on('suspend', () => { powerMonitor.on('suspend', () => {
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId); for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
+1
View File
@@ -12,6 +12,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'), syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'),
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)), onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
updateMessage: details => ipcRenderer.invoke('mail:update-message', details), updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details), saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
send: message => ipcRenderer.invoke('mail:send', message), send: message => ipcRenderer.invoke('mail:send', message),
disconnect: id => ipcRenderer.invoke('mail:disconnect', id), disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
+1
View File
@@ -65,6 +65,7 @@
<script src="platform-bridge.js"></script> <script src="platform-bridge.js"></script>
<script src="mail-ui.js"></script> <script src="mail-ui.js"></script>
<script src="productivity.js"></script> <script src="productivity.js"></script>
<script src="snooze-ui.js"></script>
<script src="account-ui.js"></script> <script src="account-ui.js"></script>
<script src="dav-ui.js"></script> <script src="dav-ui.js"></script>
</body> </body>
+1 -1
View File
@@ -122,7 +122,7 @@ async function syncMailbox(showToast, options = {}) {
if (activeMessage) { if (activeMessage) {
openMessage(activeMessage); openMessage(activeMessage);
const current = messages.find(message => message.id === 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(() => {}); if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || activeFolder, action: 'unread', enabled: false }).catch(() => {});
} }
else $('#reader-pane').innerHTML = emptyReader(); else $('#reader-pane').innerHTML = emptyReader();
updateAccountCard(connectedMailAccount); updateAccountCard(connectedMailAccount);
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.1.16", "version": "0.1.17",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.1.16", "version": "0.1.17",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.1.16", "version": "0.1.17",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"author": "Eternity Project", "author": "Eternity Project",
@@ -46,6 +46,7 @@
"logo-ep-wasteland.svg", "logo-ep-wasteland.svg",
"manifest.webmanifest", "manifest.webmanifest",
"service-worker.js", "service-worker.js",
"snooze-ui.js",
"desktop/**/*" "desktop/**/*"
], ],
"directories": { "directories": {
+2
View File
@@ -523,6 +523,8 @@
syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }), syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }),
onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback), onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback),
updateMessage: (details) => EpMail.updateMessage(details), updateMessage: (details) => EpMail.updateMessage(details),
setSnooze: (details) => EpMail.setSnooze(details),
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
saveAttachment: (details) => EpMail.saveAttachment(details), saveAttachment: (details) => EpMail.saveAttachment(details),
send: (message) => EpMail.send(message), send: (message) => EpMail.send(message),
disconnect: (id) => EpMail.removeAccount({ id }), disconnect: (id) => EpMail.removeAccount({ id }),
+1 -3
View File
@@ -10,7 +10,6 @@ let savedContacts = productRead(productKeys.contacts, []).filter(contact => !gen
productWrite(productKeys.contacts, savedContacts); productWrite(productKeys.contacts, savedContacts);
let savedEvents = productRead(productKeys.events, []); let savedEvents = productRead(productKeys.events, []);
let customLabels = productRead(productKeys.labels, []); 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'; 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() { function openAccountSettings() {
const root=$('#modal-root'); const root=$('#modal-root');
@@ -39,11 +38,10 @@ function showContact(index){const existing=Number.isInteger(index)?savedContacts
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 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 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 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()} function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||activeFolder,action,enabled:action==='star'?!message.star:true})}return Promise.resolve()}
async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}} async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}}
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';}); document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';});
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()} function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()}
const baseMessageRenderer=renderList; 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()}; 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); 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);
+2
View File
@@ -15,6 +15,8 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
syncInbox: () => EpMail.syncFolder({ folder: 'Inbox', offset: 0 }), syncInbox: () => EpMail.syncFolder({ folder: 'Inbox', offset: 0 }),
onSyncUpdate: callback => EpMail.addListener('mailSyncUpdate', callback), onSyncUpdate: callback => EpMail.addListener('mailSyncUpdate', callback),
updateMessage: details => EpMail.updateMessage(details), updateMessage: details => EpMail.updateMessage(details),
setSnooze: details => EpMail.setSnooze(details),
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
saveAttachment: details => EpMail.saveAttachment(details), saveAttachment: details => EpMail.saveAttachment(details),
send: message => EpMail.send(message), send: message => EpMail.send(message),
disconnect: id => EpMail.removeAccount({ id }), disconnect: id => EpMail.removeAccount({ id }),
+2 -1
View File
@@ -17,7 +17,8 @@ const assets = [
'logo-ep-daylight.svg', 'logo-ep-daylight.svg',
'logo-ep-wasteland.svg', 'logo-ep-wasteland.svg',
'manifest.webmanifest', 'manifest.webmanifest',
'service-worker.js' 'service-worker.js',
'snooze-ui.js'
]; ];
async function prepare() { async function prepare() {
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v2'; const CACHE='ep-mail-v3';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
+178
View File
@@ -0,0 +1,178 @@
function localDateTimeValue(date) {
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
return local.toISOString().slice(0, 16);
}
function nextMorning(daysAhead) {
const date = new Date();
date.setDate(date.getDate() + daysAhead);
date.setHours(9, 0, 0, 0);
if (date <= new Date()) date.setDate(date.getDate() + 1);
return date;
}
function openSnoozeDialog(items) {
const eligible = items.filter(message => message?.uid && connectedMailAccount);
if (!eligible.length) {
toast('Snoozing is available for messages in a connected mailbox.');
return;
}
const root = $('#modal-root');
const tomorrow = nextMorning(1);
const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000);
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</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();
};
const schedule = async dueAt => {
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
$('#snooze-status').textContent = 'Choose a reminder time in the future.';
return;
}
const buttons = [...root.querySelectorAll('button')];
buttons.forEach(button => { button.disabled = true; });
try {
for (const message of eligible) {
const sourceFolder = message.sourceFolder ||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(activeFolder) ? activeFolder : 'Inbox');
await window.daybreakMail.setSnooze({
uid: message.uid,
folder: sourceFolder,
sourceFolder,
dueAt,
subject: message.subject
});
}
close();
toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
selectedIds.clear();
await syncMailbox(false, { offset: 0 });
} catch (error) {
$('#snooze-status').textContent = error.message || 'Could not set the reminder.';
buttons.forEach(button => { button.disabled = false; });
}
};
root.querySelectorAll('[data-snooze-at]').forEach(button => {
button.onclick = () => schedule(Number(button.dataset.snoozeAt));
});
$('#snooze-custom').onclick = () => schedule(new Date($('#snooze-custom-time').value).getTime());
$('#snooze-custom-time').focus();
}
function unsnoozeMessage(message) {
const sourceFolder = message.sourceFolder || 'Inbox';
window.daybreakMail.setSnooze({
uid: message.uid,
sourceFolder,
dueAt: null
}).then(async () => {
toast('Message returned to its mailbox');
await syncMailbox(false, { offset: 0 });
}).catch(error => toast(error.message || 'Could not return the message'));
}
function showMessageActions(message) {
const root = $('#modal-root');
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`;
root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; });
root.querySelector('.modal-overlay').onclick = event => {
if (event.target.classList.contains('modal-overlay')) root.innerHTML = '';
};
}
const renderListBeforeSnooze = renderList;
renderList = function () {
if (activeFolder === 'Snoozed') {
const originalMessages = messages.slice();
const snoozedMessages = messages.filter(message => message.snoozedUntil);
messages.splice(0, messages.length, ...snoozedMessages);
const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]);
snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; });
const folder = activeFolder;
activeFolder = 'Inbox';
baseMessageRenderer();
activeFolder = folder;
originalFlags.forEach(([message, archived, deleted]) => {
message.archived = archived;
message.deleted = deleted;
});
messages.splice(0, messages.length, ...originalMessages);
for (const row of $$('.message')) {
const message = messages.find(item => item.id === Number(row.dataset.id));
if (!message?.snoozedUntil) continue;
const due = new Date(message.snoozedUntil);
row.title = `Reminder ${due.toLocaleString()}`;
const snippet = row.querySelector('.snippet');
if (snippet) snippet.textContent = `Reminder · ${due.toLocaleString()} · ${message.snippet}`;
}
return;
}
renderListBeforeSnooze();
};
const openMessageBeforeSnooze = openMessage;
openMessage = function (id) {
openMessageBeforeSnooze(id);
const message = messages.find(item => item.id === id);
const tools = $('.reader-tools');
if (!message || !tools) return;
const snoozed = activeFolder === 'Snoozed';
tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`);
};
document.addEventListener('DOMContentLoaded', () => {
$('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
if (window.daybreakMail?.checkSnoozeReminders) {
const checkReminders = () => window.daybreakMail.checkSnoozeReminders()
.catch(error => console.error('Could not check mail reminders:', error));
void checkReminders();
setInterval(checkReminders, 60 * 1000);
}
});
document.addEventListener('click', event => {
const action = event.target.closest('[data-message-action]');
const more = event.target.closest('.reader-tools button[title="More"]');
const snooze = event.target.closest('#reader-snooze, #snooze-selected');
const unsnooze = event.target.closest('#reader-unsnooze');
if (!more && !snooze && !unsnooze && !action) return;
event.preventDefault();
event.stopImmediatePropagation();
if (action) {
const message = messages.find(item => item.id === activeMessage);
$('#modal-root').innerHTML = '';
if (!message) return;
if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]);
else if (action.dataset.messageAction === 'label') addMessageLabel(message);
else {
const type = action.dataset.messageAction;
messageAction(message, type).then(() => {
if (type === 'unread') message.unread = true;
if (type === 'inbox') message.archived = false;
renderList();
toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
}).catch(error => toast(error.message || 'Could not update the message'));
}
return;
}
if (unsnooze) {
const message = messages.find(item => item.id === activeMessage);
if (message) unsnoozeMessage(message);
return;
}
if (snooze?.id === 'snooze-selected') {
openSnoozeDialog(messages.filter(message => selectedIds.has(message.id)));
return;
}
if (more) {
const message = messages.find(item => item.id === activeMessage);
if (message) showMessageActions(message);
return;
}
const message = messages.find(item => item.id === activeMessage);
if (message) openSnoozeDialog([message]);
}, true);
+1
View File
@@ -65,6 +65,7 @@
<script src="platform-bridge.js"></script> <script src="platform-bridge.js"></script>
<script src="mail-ui.js"></script> <script src="mail-ui.js"></script>
<script src="productivity.js"></script> <script src="productivity.js"></script>
<script src="snooze-ui.js"></script>
<script src="account-ui.js"></script> <script src="account-ui.js"></script>
<script src="dav-ui.js"></script> <script src="dav-ui.js"></script>
</body> </body>
+1 -1
View File
@@ -122,7 +122,7 @@ async function syncMailbox(showToast, options = {}) {
if (activeMessage) { if (activeMessage) {
openMessage(activeMessage); openMessage(activeMessage);
const current = messages.find(message => message.id === 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(() => {}); if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || activeFolder, action: 'unread', enabled: false }).catch(() => {});
} }
else $('#reader-pane').innerHTML = emptyReader(); else $('#reader-pane').innerHTML = emptyReader();
updateAccountCard(connectedMailAccount); updateAccountCard(connectedMailAccount);
+2
View File
@@ -523,6 +523,8 @@
syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }), syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }),
onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback), onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback),
updateMessage: (details) => EpMail.updateMessage(details), updateMessage: (details) => EpMail.updateMessage(details),
setSnooze: (details) => EpMail.setSnooze(details),
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
saveAttachment: (details) => EpMail.saveAttachment(details), saveAttachment: (details) => EpMail.saveAttachment(details),
send: (message) => EpMail.send(message), send: (message) => EpMail.send(message),
disconnect: (id) => EpMail.removeAccount({ id }), disconnect: (id) => EpMail.removeAccount({ id }),
+1 -3
View File
@@ -10,7 +10,6 @@ let savedContacts = productRead(productKeys.contacts, []).filter(contact => !gen
productWrite(productKeys.contacts, savedContacts); productWrite(productKeys.contacts, savedContacts);
let savedEvents = productRead(productKeys.events, []); let savedEvents = productRead(productKeys.events, []);
let customLabels = productRead(productKeys.labels, []); 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'; 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() { function openAccountSettings() {
const root=$('#modal-root'); const root=$('#modal-root');
@@ -39,11 +38,10 @@ function showContact(index){const existing=Number.isInteger(index)?savedContacts
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 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 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 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()} function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||activeFolder,action,enabled:action==='star'?!message.star:true})}return Promise.resolve()}
async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}} async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}}
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';}); document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';});
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()} function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()}
const baseMessageRenderer=renderList; 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()}; 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); 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);
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v2'; const CACHE='ep-mail-v3';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
+178
View File
@@ -0,0 +1,178 @@
function localDateTimeValue(date) {
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
return local.toISOString().slice(0, 16);
}
function nextMorning(daysAhead) {
const date = new Date();
date.setDate(date.getDate() + daysAhead);
date.setHours(9, 0, 0, 0);
if (date <= new Date()) date.setDate(date.getDate() + 1);
return date;
}
function openSnoozeDialog(items) {
const eligible = items.filter(message => message?.uid && connectedMailAccount);
if (!eligible.length) {
toast('Snoozing is available for messages in a connected mailbox.');
return;
}
const root = $('#modal-root');
const tomorrow = nextMorning(1);
const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000);
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</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();
};
const schedule = async dueAt => {
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
$('#snooze-status').textContent = 'Choose a reminder time in the future.';
return;
}
const buttons = [...root.querySelectorAll('button')];
buttons.forEach(button => { button.disabled = true; });
try {
for (const message of eligible) {
const sourceFolder = message.sourceFolder ||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(activeFolder) ? activeFolder : 'Inbox');
await window.daybreakMail.setSnooze({
uid: message.uid,
folder: sourceFolder,
sourceFolder,
dueAt,
subject: message.subject
});
}
close();
toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
selectedIds.clear();
await syncMailbox(false, { offset: 0 });
} catch (error) {
$('#snooze-status').textContent = error.message || 'Could not set the reminder.';
buttons.forEach(button => { button.disabled = false; });
}
};
root.querySelectorAll('[data-snooze-at]').forEach(button => {
button.onclick = () => schedule(Number(button.dataset.snoozeAt));
});
$('#snooze-custom').onclick = () => schedule(new Date($('#snooze-custom-time').value).getTime());
$('#snooze-custom-time').focus();
}
function unsnoozeMessage(message) {
const sourceFolder = message.sourceFolder || 'Inbox';
window.daybreakMail.setSnooze({
uid: message.uid,
sourceFolder,
dueAt: null
}).then(async () => {
toast('Message returned to its mailbox');
await syncMailbox(false, { offset: 0 });
}).catch(error => toast(error.message || 'Could not return the message'));
}
function showMessageActions(message) {
const root = $('#modal-root');
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`;
root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; });
root.querySelector('.modal-overlay').onclick = event => {
if (event.target.classList.contains('modal-overlay')) root.innerHTML = '';
};
}
const renderListBeforeSnooze = renderList;
renderList = function () {
if (activeFolder === 'Snoozed') {
const originalMessages = messages.slice();
const snoozedMessages = messages.filter(message => message.snoozedUntil);
messages.splice(0, messages.length, ...snoozedMessages);
const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]);
snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; });
const folder = activeFolder;
activeFolder = 'Inbox';
baseMessageRenderer();
activeFolder = folder;
originalFlags.forEach(([message, archived, deleted]) => {
message.archived = archived;
message.deleted = deleted;
});
messages.splice(0, messages.length, ...originalMessages);
for (const row of $$('.message')) {
const message = messages.find(item => item.id === Number(row.dataset.id));
if (!message?.snoozedUntil) continue;
const due = new Date(message.snoozedUntil);
row.title = `Reminder ${due.toLocaleString()}`;
const snippet = row.querySelector('.snippet');
if (snippet) snippet.textContent = `Reminder · ${due.toLocaleString()} · ${message.snippet}`;
}
return;
}
renderListBeforeSnooze();
};
const openMessageBeforeSnooze = openMessage;
openMessage = function (id) {
openMessageBeforeSnooze(id);
const message = messages.find(item => item.id === id);
const tools = $('.reader-tools');
if (!message || !tools) return;
const snoozed = activeFolder === 'Snoozed';
tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`);
};
document.addEventListener('DOMContentLoaded', () => {
$('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
if (window.daybreakMail?.checkSnoozeReminders) {
const checkReminders = () => window.daybreakMail.checkSnoozeReminders()
.catch(error => console.error('Could not check mail reminders:', error));
void checkReminders();
setInterval(checkReminders, 60 * 1000);
}
});
document.addEventListener('click', event => {
const action = event.target.closest('[data-message-action]');
const more = event.target.closest('.reader-tools button[title="More"]');
const snooze = event.target.closest('#reader-snooze, #snooze-selected');
const unsnooze = event.target.closest('#reader-unsnooze');
if (!more && !snooze && !unsnooze && !action) return;
event.preventDefault();
event.stopImmediatePropagation();
if (action) {
const message = messages.find(item => item.id === activeMessage);
$('#modal-root').innerHTML = '';
if (!message) return;
if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]);
else if (action.dataset.messageAction === 'label') addMessageLabel(message);
else {
const type = action.dataset.messageAction;
messageAction(message, type).then(() => {
if (type === 'unread') message.unread = true;
if (type === 'inbox') message.archived = false;
renderList();
toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
}).catch(error => toast(error.message || 'Could not update the message'));
}
return;
}
if (unsnooze) {
const message = messages.find(item => item.id === activeMessage);
if (message) unsnoozeMessage(message);
return;
}
if (snooze?.id === 'snooze-selected') {
openSnoozeDialog(messages.filter(message => selectedIds.has(message.id)));
return;
}
if (more) {
const message = messages.find(item => item.id === activeMessage);
if (message) showMessageActions(message);
return;
}
const message = messages.find(item => item.id === activeMessage);
if (message) openSnoozeDialog([message]);
}, true);