From bb34eedb44e4d35ab06903c576cda55f269c6bb0 Mon Sep 17 00:00:00 2001 From: Tero Date: Tue, 17 Nov 2026 22:46:11 +0200 Subject: [PATCH] Add conversation threads and prepare 0.6.0 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 4 + SIGNING.md | 143 ++++++++++++++++++ TODO.md | 2 +- .../daybreak/mail/AndroidMailService.kt | 11 ++ .../java/studio/daybreak/mail/EpMailPlugin.kt | 2 + app.js | 49 +++++- conversation-threads.js | 47 ++++++ desktop/ipc/mail.cjs | 6 + desktop/mail/send-service.cjs | 3 + desktop/main.cjs | 3 + desktop/pgp-mail.cjs | 7 +- desktop/security/ipc-arguments.cjs | 5 +- index.html | 1 + mail-ui.js | 7 +- package-lock.json | 4 +- package.json | 3 +- platform-bridge.js | 2 + productivity.js | 2 +- scripts/android-pgp.js | 2 + scripts/prepare-android-web.cjs | 1 + service-worker.js | 4 +- styles.css | 3 + tests/android-pgp.test.cjs | 6 +- tests/conversation-threads.test.cjs | 37 +++++ tests/conversation-ui.test.cjs | 43 ++++++ tests/draft-composer.test.cjs | 19 ++- tests/ipc-arguments.test.cjs | 1 + tests/mail-send-service.test.cjs | 14 ++ tests/pgp-mail.test.cjs | 7 +- tests/renderer-bootstrap.test.cjs | 2 +- www/app.js | 49 +++++- www/conversation-threads.js | 47 ++++++ www/index.html | 1 + www/mail-ui.js | 7 +- www/platform-bridge.js | 2 + www/productivity.js | 2 +- www/service-worker.js | 4 +- www/styles.css | 3 + 38 files changed, 532 insertions(+), 23 deletions(-) create mode 100644 SIGNING.md create mode 100644 conversation-threads.js create mode 100644 tests/conversation-threads.test.cjs create mode 100644 tests/conversation-ui.test.cjs create mode 100644 www/conversation-threads.js diff --git a/README.md b/README.md index ac72a20..7d370c6 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,10 @@ An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and E The Electron app runs in its own window. On Windows, ep-mail also shows its icon in the notification area beside the clock; click it to open the app, or right-click for Open and Quit. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser. On desktop and Android, incoming HTML is sanitized before display; external HTTPS images stay blocked until you explicitly load them for that message. Loading remote images can disclose your network address and message-open timing to their hosts. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. Windows builds use the app icon for the executable, window, and shortcuts. If Windows continues showing an old icon for an existing taskbar pin, unpin ep-mail, install or launch the updated build, then pin it again from the updated shortcut. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. On Windows, `npm run build` runs `scripts\build.ps1`, building the Android debug APK and Windows portable executable. For all targets, run `npm run build:all`: it also builds the Windows installer and uses the default WSL distribution to build the Linux AppImage and Debian package. To select a distribution, run `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-all.ps1 -WslDistribution Ubuntu`. WSL needs Linux Node.js, npm and tar, plus the usual Electron packaging prerequisites and network access to install the locked dependencies. Linux builds use a temporary Linux filesystem workspace, then copy both packages into `release\`. Both build scripts preserve the legacy `ep-mail .apk` copy of the debug APK; it is **not a signed release APK** and will overwrite a same-named signed APK. Use `npm run android:release-apk` afterwards when a signed release is needed. + +See [SIGNING.md](./SIGNING.md) for private Android and Windows signing, verification, key backups, and the Android debug-to-release transition. + +The message list groups related messages using Message-ID, References, and In-Reply-To headers. Expand or collapse each conversation to access its individual messages; collapsing deselects hidden messages, and bulk selection applies to visible rows. Grouping covers only the messages currently loaded in the selected folder or search results, not other folders or unloaded pages. Older offline cache entries gain threading information when refreshed. 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. diff --git a/SIGNING.md b/SIGNING.md new file mode 100644 index 0000000..2327bec --- /dev/null +++ b/SIGNING.md @@ -0,0 +1,143 @@ +# Signing ep-mail builds + +This guide covers privately distributed Android APKs and Windows executables built on Windows. Neither Google Play nor the Microsoft Store is required. Signing identifies the key used to produce an artifact and detects subsequent changes; it does not by itself prove the application is safe. + +Android OpenPGP remains experimental and is not independently security reviewed. Signing the application does not change that status. + +## Keep signing keys safe + +- Keep private keys, keystores, PFX files, and passwords outside the repository and release artifacts. Never commit them or paste passwords into chat, issues, logs, or scripts. +- Restrict access to the files and store passwords separately in a password manager. Keep a secure backup of each private key and its password. +- Exchange and verify public certificate fingerprints through a separate trusted channel before trusting a certificate or installing an artifact. +- Run the PowerShell commands below from the repository root unless stated otherwise. Environment variables set here last only for the current PowerShell session, but are available to child processes during the build. + +## Android: create a release signing key + +Android accepts a self-signed app certificate; a paid certificate and Google Play account are unnecessary. Install the Android SDK and JDK 21 as described in the [README](./README.md). + +Choose a secure directory outside the repository. Create it with appropriate access restrictions before proceeding. The following example uses Android Studio's JDK and prompts for the keystore password and certificate details: + +```powershell +$env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr" +$env:ANDROID_HOME = Join-Path $env:LOCALAPPDATA "Android\Sdk" + +& "$env:JAVA_HOME\bin\keytool.exe" -genkeypair -v ` + -keystore "C:\secure\ep-mail-android.p12" -storetype PKCS12 ` + -alias ep-mail -keyalg RSA -keysize 3072 -validity 10000 +``` + +Replace `C:\secure` with your secured directory. Do not overwrite or recreate an existing production keystore. With PKCS12, use the same password for the keystore and key entry. Back up the keystore and password securely; losing the key prevents ordinary in-place updates of apps signed with it. Record the alias and public certificate SHA-256 fingerprint: + +```powershell +& "$env:JAVA_HOME\bin\keytool.exe" -list -v ` + -keystore "C:\secure\ep-mail-android.p12" -storetype PKCS12 -alias ep-mail +``` + +### Build and verify + +In the same PowerShell session, configure the existing release build. The password prompt avoids entering the password as a command-line argument, although the environment variables contain plaintext for the duration of the build session. + +```powershell +$env:EP_MAIL_ANDROID_STORE_FILE = "C:\secure\ep-mail-android.p12" +$env:EP_MAIL_ANDROID_KEY_ALIAS = "ep-mail" +$env:EP_MAIL_ANDROID_STORE_PASSWORD = Read-Host "Keystore password" -AsSecureString | + ForEach-Object { [System.Net.NetworkCredential]::new("", $_).Password } +$env:EP_MAIL_ANDROID_KEY_PASSWORD = $env:EP_MAIL_ANDROID_STORE_PASSWORD + +npm run android:release-apk +``` + +The output is `release\ep-mail .apk`. Confirm the build succeeded before using it. Verify the signature and certificate fingerprint using the Android SDK build-tools version installed on your machine, replacing the example version if necessary: + +```powershell +$version = (Get-Content package.json -Raw | ConvertFrom-Json).version +$apksigner = Join-Path $env:ANDROID_HOME "build-tools\36.0.0\apksigner.bat" +& $apksigner verify --verbose --print-certs "release\ep-mail $version.apk" +``` + +Compare the displayed signer SHA-256 fingerprint with the fingerprint recorded from the keystore. Afterwards, remove the password variables from the session: + +```powershell +Remove-Item Env:\EP_MAIL_ANDROID_STORE_PASSWORD, Env:\EP_MAIL_ANDROID_KEY_PASSWORD +``` + +**Build order matters:** `npm run build` and `npm run build:all` build a debug APK and overwrite `release\ep-mail .apk` with a debug-signed copy. Run `npm run android:release-apk` **after** those commands, then verify the resulting APK. The `-debug.apk` remains a debug build. + +### Moving from the existing debug app + +Android normally requires the installed app and its update to have the same signing certificate. A new release key will not match the currently installed debug key, so `adb install -r` will fail rather than replace it. + +Before uninstalling, securely back up any private OpenPGP keys and revocation certificates, local-only drafts and other local data you need; ensure account settings can be recreated. Uninstalling removes the app's local data. After verifying your backups, uninstall the debug app using Android's app settings and install the verified release APK: + +```powershell +& "$env:ANDROID_HOME\platform-tools\adb.exe" install "release\ep-mail $version.apk" +``` + +Future builds signed with the same release key can normally be installed with `adb install -r`. Keep the same package ID and use an appropriate version code for upgrades; do not assume that a different signing key will update the app. + +## Windows: self-signed certificate for internal use + +For private machines you control, a self-signed code-signing certificate is an option without buying a certificate. This does **not** make the publisher publicly trusted and does not guarantee that Microsoft Defender SmartScreen will stop warning. An unsigned build is also an option if these trust changes are not wanted. + +The example below creates an exportable certificate in the current user's personal certificate store and exports a password-protected private-key PFX plus a public-only CER. Use a securely permissioned directory outside the repository and a name appropriate for your project. Do not replace an existing key without a plan for distributing and trusting the new public certificate. + +```powershell +$cert = New-SelfSignedCertificate -Type CodeSigningCert ` + -Subject "CN=ep-mail Internal" -CertStoreLocation "Cert:\CurrentUser\My" ` + -KeyAlgorithm RSA -KeyLength 3072 -HashAlgorithm SHA256 ` + -KeyExportPolicy Exportable -NotAfter (Get-Date).AddYears(5) + +$pfxPassword = Read-Host "Choose a PFX password" -AsSecureString +Export-PfxCertificate -Cert $cert -FilePath "C:\secure\ep-mail-windows.pfx" -Password $pfxPassword +Export-Certificate -Cert $cert -FilePath "C:\secure\ep-mail-windows.cer" +$cert | Format-List Subject, Thumbprint, NotBefore, NotAfter +``` + +Back up the PFX and password securely. The CER is the public certificate: share it only with people who need to verify your builds, and verify its fingerprint independently. Renew or replace the certificate before expiry; use a trusted timestamp when signing so signature validity can be evaluated after expiry. Timestamping requires network access. + +### Build and verify + +Electron-builder accepts a PFX and password from the environment: + +```powershell +$env:WIN_CSC_LINK = "C:\secure\ep-mail-windows.pfx" +$env:WIN_CSC_KEY_PASSWORD = Read-Host "PFX password" -AsSecureString | + ForEach-Object { [System.Net.NetworkCredential]::new("", $_).Password } +npm run dist:win +``` + +This builds the portable executable and installer in `release\`. `npm run build:all` also builds both Windows targets and uses these signing variables when supplied. Check the build output for signing errors; a build without credentials can otherwise produce unsigned artifacts. Verify **both** outputs: + +```powershell +$version = (Get-Content package.json -Raw | ConvertFrom-Json).version +Get-AuthenticodeSignature "release\ep-mail $version.exe" | + Format-List Status, StatusMessage, SignerCertificate, TimeStamperCertificate +Get-AuthenticodeSignature "release\ep-mail Setup $version.exe" | + Format-List Status, StatusMessage, SignerCertificate, TimeStamperCertificate +Remove-Item Env:\WIN_CSC_KEY_PASSWORD +``` + +Compare each signer certificate fingerprint with the independently verified certificate. `Status` may indicate an untrusted chain until the public certificate is trusted on the verifying machine; a missing signer, invalid signature, or unexpected fingerprint must not be treated as success. A timestamp is distinct from the signer certificate; inspect its presence and validity as well. + +### Trust the public certificate on a private machine + +Only do this on machines you control, after independently verifying the CER fingerprint. Importing a root certificate changes trust for the current user, not just for ep-mail: software signed by a trusted key may also be trusted. Protect and distribute the key accordingly. Never import the PFX on machines that only need to verify builds. + +```powershell +$publicCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\secure\ep-mail-windows.cer") +$publicCert | Format-List Subject, Thumbprint, NotBefore, NotAfter +# Proceed only after checking the thumbprint through a separate trusted channel. +Import-Certificate -FilePath "C:\secure\ep-mail-windows.cer" -CertStoreLocation "Cert:\CurrentUser\Root" +Import-Certificate -FilePath "C:\secure\ep-mail-windows.cer" -CertStoreLocation "Cert:\CurrentUser\TrustedPublisher" +``` + +Re-run `Get-AuthenticodeSignature` on each artifact and confirm a `Valid` status, the expected signer and the timestamp. Trust is per user with these commands; other users or machines require their own trust configuration. If the certificate is compromised or no longer needed, remove its entries from those stores and stop trusting or distributing builds signed by the compromised key. + +For distribution to machines where manually installing trust is impractical, use a certificate from a publicly trusted code-signing provider instead. Such certificates have costs and provider-specific requirements; a valid signature does not guarantee SmartScreen reputation. + +## References + +- [Android app signing](https://developer.android.com/studio/publish/app-signing) +- [Android apksigner](https://developer.android.com/tools/apksigner) +- [electron-builder Windows code signing](https://www.electron.build/docs/features/code-signing/code-signing-win/) +- [Microsoft: New-SelfSignedCertificate](https://learn.microsoft.com/en-us/powershell/module/pki/new-selfsignedcertificate) diff --git a/TODO.md b/TODO.md index a1006ca..a65c08c 100644 --- a/TODO.md +++ b/TODO.md @@ -15,7 +15,7 @@ - [ ] Add a configurable Undo Send delay and scheduled sending. - [x] Improve mail search with sender, subject, date, folder, and attachment filters. - [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns. -- [ ] Group related messages into conversations, with controls to expand or collapse threads. +- [x] Group related messages into conversations, with controls to expand or collapse threads. - [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes. - [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search. - [x] Warn about suspicious sender addresses and links; require confirmation before opening external links. diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt index b953203..dcf90bc 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -166,6 +166,9 @@ internal object AndroidMailService { add(FetchProfile.Item.FLAGS) add(FetchProfile.Item.CONTENT_INFO) add(UIDFolder.FetchProfileItem.UID) + add("Message-ID") + add("In-Reply-To") + add("References") } folder.fetch(batch.toTypedArray(), profile) val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray() @@ -380,6 +383,11 @@ internal object AndroidMailService { message.sentDate = Date() message.saveChanges() input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) } + val idPattern = Regex("<[\\x21-\\x3b\\x3d\\x3f-\\x7e]+@[\\x21-\\x3b\\x3d\\x3f-\\x7e]+>") + val parent = idPattern.find(input.optString("inReplyTo").take(254))?.value + val references = idPattern.findAll(input.optString("references").take(900)).map { it.value }.toList() + if (parent != null) message.setHeader("In-Reply-To", parent) + if (references.isNotEmpty()) message.setHeader("References", references.joinToString(" ")) } val transport = session.getTransport("smtp") @@ -750,6 +758,9 @@ internal object AndroidMailService { .put("sender", senderName) .put("email", senderEmail) .put("subject", subject) + .put("messageId", message.getHeader("Message-ID")?.joinToString(" ") ?: "") + .put("inReplyTo", message.getHeader("In-Reply-To")?.joinToString(" ") ?: "") + .put("references", message.getHeader("References")?.joinToString(" ") ?: "") .put("snippet", snippet) .put("encrypted", encrypted) .put("signed", signed) diff --git a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt index d2ffcc2..2e74750 100644 --- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -830,6 +830,8 @@ class EpMailPlugin : Plugin() { .put("cc", input.optString("cc").take(4000)) .put("subject", input.optString("subject").take(998)) .put("text", input.optString("text").take(500000)) + .put("inReplyTo", input.optString("inReplyTo").take(254)) + .put("references", input.optString("references").take(900)) .put("attachments", input.optJSONArray("attachments") ?: JSONArray()) .put("updatedAt", System.currentTimeMillis()) AndroidAccountVault.saveDraft(account.optString("id"), draft) diff --git a/app.js b/app.js index 76bbdd9..80c2663 100644 --- a/app.js +++ b/app.js @@ -18,7 +18,54 @@ function returnToMessageList() { if (readerListPosition?.folder === state.activeFolder) $('#message-list').scrollTop = readerListPosition.scrollTop; readerListPosition = null; } -function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`
${m.initials}
${esc(m.sender)}
${esc(m.subject)}
${esc(m.snippet)}
${esc(m.time)}
`).join(''):`
⌕

No messages here

Try another folder or search.

`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}} +const collapsedThreads = new Set(); +function renderList() { + const rows = state.messages.filter(m => { + if (state.activeFolder === 'Starred' && !m.star) return false; + if (state.activeFolder === 'Inbox' && m.archived) return false; + if (state.activeFolder === 'Archive' && !m.archived) return false; + if (state.activeFolder === 'Trash' && !m.deleted) return false; + if (state.activeFolder === 'Sent' && !m.sent) return false; + if (state.activeFolder === 'Drafts' || state.activeFolder === 'Snoozed') return false; + if (m.deleted && state.activeFolder !== 'Trash') return false; + return !state.query || `${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase()); + }); + const groups = window.epMailConversationThreads.groupMessages(rows); + const scope = `${window.epMailFeatures?.mail?.connectedAccount?.id || ''}:${state.activeFolder}:`; + const keyFor = message => scope + (window.epMailConversationThreads.messageIds(message.messageId)[0] || `uid:${message.sourceFolder || ''}:${message.id}`); + const rowHtml = m => `
${m.initials}
${esc(m.sender)}
${esc(m.subject)}
${esc(m.snippet)}
${esc(m.time)}
`; + $('#message-list').innerHTML = rows.length ? groups.map((group, index) => { + if (group.length === 1) return rowHtml(group[0]); + const collapsed = group.some(message => collapsedThreads.has(keyFor(message))); + if (collapsed) group.slice(1).forEach(message => state.selectedIds.delete(message.id)); + const unread = group.filter(message => message.unread).length; + return `
${rowHtml(group[0])}
${group.slice(1).map(rowHtml).join('')}
`; + }).join('') : `
⌕

No messages here

Try another folder or search.

`; + $$('.conversation-toggle').forEach(button => button.addEventListener('click', () => { + const group = groups[Number(button.dataset.thread)]; + const collapsing = button.getAttribute('aria-expanded') === 'true'; + group.forEach(message => collapsing ? collapsedThreads.add(keyFor(message)) : collapsedThreads.delete(keyFor(message))); + if (collapsing) group.slice(1).forEach(message => state.selectedIds.delete(message.id)); + const scrollTop = $('#message-list').scrollTop; + renderList(); + $('#message-list').scrollTop = scrollTop; + })); + $$('.message').forEach(row => row.addEventListener('click', e => { + if (e.target.closest('.row-check')) { + const id = +row.dataset.id; + state.selectedIds.has(id) ? state.selectedIds.delete(id) : state.selectedIds.add(id); + return; + } + if (e.target.closest('.star')) { + const m = state.messages.find(x => x.id === +row.dataset.id); + m.star = !m.star; + renderList(); + return; + } + openMessage(+row.dataset.id); + })); + if (!rows.length) { document.body.classList.remove('reader-open'); $('#reader-pane').innerHTML = emptyReader(); } +} function openMessage(id){ state.activeMessage=id; const m=state.messages.find(x=>x.id===id); diff --git a/conversation-threads.js b/conversation-threads.js new file mode 100644 index 0000000..5d2a243 --- /dev/null +++ b/conversation-threads.js @@ -0,0 +1,47 @@ +(function installConversationThreads(root, factory) { + const api = factory(); + if (typeof module === 'object' && module.exports) module.exports = api; + else root.epMailConversationThreads = api; +})(typeof window === 'undefined' ? globalThis : window, function () { + function messageIds(value) { + const text = Array.isArray(value) ? value.join(' ') : String(value || ''); + return [...new Set((text.match(/<[\x21-\x3b\x3d\x3f-\x7e]+@[\x21-\x3b\x3d\x3f-\x7e]+>/g) || []) + .filter(id => id.length <= 254))]; + } + + function replyHeaders(message) { + const inReplyTo = messageIds(message?.messageId)[0] || ''; + if (!inReplyTo) return { inReplyTo: '', references: '' }; + const ids = [...new Set([...messageIds(message.references), inReplyTo])]; + while (ids.join(' ').length > 900 && ids.length > 1) ids.splice(1, 1); + return { inReplyTo, references: ids.join(' ') }; + } + + function groupMessages(messages) { + const parents = messages.map((_, index) => index); + const find = index => { + while (parents[index] !== index) { + parents[index] = parents[parents[index]]; + index = parents[index]; + } + return index; + }; + const owners = new Map(); + messages.forEach((message, index) => { + const ids = [...messageIds(message.messageId), ...messageIds(message.inReplyTo), ...messageIds(message.references)]; + for (const id of new Set(ids)) { + if (owners.has(id)) parents[find(index)] = find(owners.get(id)); + else owners.set(id, index); + } + }); + const groups = new Map(); + messages.forEach((message, index) => { + const root = find(index); + if (!groups.has(root)) groups.set(root, []); + groups.get(root).push(message); + }); + return [...groups.values()]; + } + + return { messageIds, replyHeaders, groupMessages }; +}); diff --git a/desktop/ipc/mail.cjs b/desktop/ipc/mail.cjs index 49b73ca..cd1fa50 100644 --- a/desktop/ipc/mail.cjs +++ b/desktop/ipc/mail.cjs @@ -202,6 +202,8 @@ registerIpcHandler('mail:save-draft', async (_event, input) => { cc: String(input?.cc || '').slice(0, 4000), subject: String(input?.subject || '').slice(0, 998), text: String(input?.text || '').slice(0, 500000), + inReplyTo: String(input?.inReplyTo || '').slice(0, 254), + references: String(input?.references || '').slice(0, 900), attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)), updatedAt: Date.now() }; @@ -341,6 +343,8 @@ registerIpcHandler('mail:send', async (event, message) => { text: message.text, displayName: message.displayName, messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`, + inReplyTo: message.inReplyTo, + references: message.references, attachments: message.attachments }; const attachments = normalizeOutgoingAttachments(message?.attachments); @@ -376,6 +380,8 @@ registerIpcHandler('mail:send', async (event, message) => { subject: String(queuedMessage.subject || '(no subject)').slice(0, 998), text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body, messageId: queuedMessage.messageId, + inReplyTo: queuedMessage.inReplyTo, + references: queuedMessage.references, encrypt: Boolean(pgpOptions.encrypt), sign: Boolean(pgpOptions.sign), passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null, diff --git a/desktop/mail/send-service.cjs b/desktop/mail/send-service.cjs index 16d60c6..b8b8e44 100644 --- a/desktop/mail/send-service.cjs +++ b/desktop/mail/send-service.cjs @@ -1,6 +1,7 @@ const { randomUUID } = require('node:crypto'); const nodemailer = require('nodemailer'); const { normalizeOutgoingAttachments } = require('../mail-attachments.cjs'); +const { messageIds } = require('../../conversation-threads.js'); function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTransport = nodemailer.createTransport }) { async function sendMailNow(account, message) { @@ -19,6 +20,8 @@ function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTr subject: String(message.subject || '(no subject)').slice(0, 998), text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body, messageId: sentMessageId, + inReplyTo: messageIds(message.inReplyTo)[0] || undefined, + references: messageIds(message.references), attachments: attachments.map(file => ({ filename: file.filename, contentType: file.contentType, diff --git a/desktop/main.cjs b/desktop/main.cjs index 322213d..c9bfd04 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -344,6 +344,9 @@ async function toUiMessage(item, folder) { sender: sender?.name || sender?.address || 'Unknown sender', email: sender?.address || '', subject: parsed.subject || '(no subject)', + messageId: parsed.messageId || '', + inReplyTo: parsed.inReplyTo || '', + references: parsed.references || [], snippet: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180), encrypted, pgpSignatures, diff --git a/desktop/pgp-mail.cjs b/desktop/pgp-mail.cjs index 87577af..309b31e 100644 --- a/desktop/pgp-mail.cjs +++ b/desktop/pgp-mail.cjs @@ -267,7 +267,7 @@ function createPgpMail({ keyStore, cache }) { }, // Builds a complete RFC 3156 message. Returns { raw, envelope }. - async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) { + async build({ from, to, cc, subject, text, messageId, inReplyTo, references, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) { const toList = parseAddresses(to); const ccList = parseAddresses(cc); if (!toList.length) throw new Error('Add at least one recipient.'); @@ -290,6 +290,9 @@ function createPgpMail({ keyStore, cache }) { } await cache.remember(signerEntry.fingerprint, secret); } + const { messageIds } = require('../conversation-threads.js'); + const parentIds = messageIds(inReplyTo).slice(0, 1); + const referenceIds = messageIds(references); const headers = [ `From: ${formatAddress(from)}`, `To: ${toList.map(formatAddress).join(', ')}`, @@ -297,6 +300,8 @@ function createPgpMail({ keyStore, cache }) { `Subject: ${encodeHeader(subject || '(no subject)')}`, `Date: ${date.toUTCString().replace('GMT', '+0000')}`, `Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`, + ...parentIds.map(id => `In-Reply-To: ${id}`), + ...(referenceIds.length ? [`References: ${referenceIds.join(' ')}`] : []), 'MIME-Version: 1.0' ]; const inner = await innerEntity(text, attachments); diff --git a/desktop/security/ipc-arguments.cjs b/desktop/security/ipc-arguments.cjs index dbf8417..11edc37 100644 --- a/desktop/security/ipc-arguments.cjs +++ b/desktop/security/ipc-arguments.cjs @@ -53,6 +53,7 @@ const objectFieldSchemas = { 'mail:create-folder': [{ name: str(100) }], 'mail:save-draft': [{ id: str(256), to: str(4000), cc: str(4000), subject: str(998), text: str(500_000), + inReplyTo: str(254), references: str(900), attachments: array(record(attachmentFields)) }], 'mail:set-snooze': [{ @@ -67,7 +68,7 @@ const objectFieldSchemas = { 'mail:preview-attachment': [{ uid: num({ integer: true, min: 1 }), folder: str(256), filename: str(1000) }], 'mail:send': [{ to: str(4000), cc: str(4000), subject: str(998), text: str(500_000), displayName: str(80), - messageId: str(998), attachments: array(record(attachmentFields)), + messageId: str(998), inReplyTo: str(254), references: str(900), attachments: array(record(attachmentFields)), pgp: record({ encrypt: bool(), sign: bool(), passphrase: str(4096, { nullable: true }) }, { nullable: true }) }], 'pgp:generate': [{ name: str(200), email: str(320), passphrase: str(4096), accountId: str(256, { nullable: true }) }], @@ -115,7 +116,7 @@ const positionalFieldSchemas = { 'pgp:remove-key-server': { 0: str(256) } }; -const sendMessageFields = new Set(['to', 'cc', 'subject', 'text', 'displayName', 'messageId', 'attachments', 'pgp']); +const sendMessageFields = new Set(['to', 'cc', 'subject', 'text', 'displayName', 'messageId', 'inReplyTo', 'references', 'attachments', 'pgp']); const schemas = { 'app:get-version': [], diff --git a/index.html b/index.html index 4616172..5ce5887 100644 --- a/index.html +++ b/index.html @@ -65,6 +65,7 @@
+ diff --git a/mail-ui.js b/mail-ui.js index 9289d8c..ef96174 100644 --- a/mail-ui.js +++ b/mail-ui.js @@ -529,6 +529,9 @@ function setupDraftComposer() { const modal = root.querySelector('.compose-modal'); if (!modal) return; modal.dataset.draftId = draft?.id || ''; + modal._replyHeaders = draft + ? { inReplyTo: draft.inReplyTo || '', references: draft.references || '' } + : reply && !forward ? window.epMailConversationThreads.replyHeaders(reply) : { inReplyTo: '', references: '' }; let attachments = Array.isArray(draft?.attachments) ? draft.attachments : []; modal._composeAttachments = attachments; const fields = modal.querySelector('.compose-fields'); @@ -630,7 +633,8 @@ function setupDraftComposer() { cc: modal.querySelector('#compose-cc').value, subject: modal.querySelector('#compose-subject').value, text: modal.querySelector('#compose-body').value, - attachments: [...attachments] + attachments: [...attachments], + ...modal._replyHeaders }; if (!modal.dataset.draftId && ![values.to, values.cc, values.subject, values.text].some(value => value.trim()) && !values.attachments.length) return Promise.resolve(false); values.id = modal.dataset.draftId || window.crypto.randomUUID(); @@ -1053,6 +1057,7 @@ if (window.daybreakMail) { text: selectMailUi('#compose-body').value, attachments: selectMailUi('#modal-root .compose-modal')?._composeAttachments || [], displayName: mailFeatureState.connectedAccount.displayName || window.epMailFeatures.productivity?.profileName || '', + ...(selectMailUi('#modal-root .compose-modal')?._replyHeaders || {}), ...(pgp ? { pgp } : {}) }); if (result.failed) { diff --git a/package-lock.json b/package-lock.json index fd20929..b42bda8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.5.23", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.5.23", + "version": "0.6.0", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index 00f139a..777b6ed 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.5.23", + "version": "0.6.0", "private": true, "description": "Eternity Project mail client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", @@ -46,6 +46,7 @@ "styles.css", "branding.css", "renderer-state.js", + "conversation-threads.js", "mail-content-security.js", "renderer-mail-api.js", "app.js", diff --git a/platform-bridge.js b/platform-bridge.js index e564697..4c77097 100644 --- a/platform-bridge.js +++ b/platform-bridge.js @@ -10859,6 +10859,8 @@ ${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []); `Subject: ${encodeHeader(message.subject || "(no subject)")}`, `Date: ${(/* @__PURE__ */ new Date()).toUTCString().replace("GMT", "+0000")}`, `Message-ID: ${safeHeader(message.messageId || `<${crypto.randomUUID()}@ep-mail.local>`, 200)}`, + ...message.inReplyTo ? [`In-Reply-To: ${safeHeader(message.inReplyTo, 254)}`] : [], + ...message.references ? [`References: ${safeHeader(message.references, 900)}`] : [], "MIME-Version: 1.0" ]; let contentType; diff --git a/productivity.js b/productivity.js index 63b41e0..bc285fd 100644 --- a/productivity.js +++ b/productivity.js @@ -59,7 +59,7 @@ function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')} function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()} async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('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);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}} -document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.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'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';}); +document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message').filter(row=>!row.closest('[hidden]'));const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.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'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#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);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()} productivityMailUi.wrapRenderList(baseMessageRenderer => function () { const state = productivityMailUi.state; diff --git a/scripts/android-pgp.js b/scripts/android-pgp.js index 234b17e..04762dc 100644 --- a/scripts/android-pgp.js +++ b/scripts/android-pgp.js @@ -405,6 +405,8 @@ export function createAndroidPgp({ EpMail, getAccount, confirm = globalThis.conf `Subject: ${encodeHeader(message.subject || '(no subject)')}`, `Date: ${new Date().toUTCString().replace('GMT', '+0000')}`, `Message-ID: ${safeHeader(message.messageId || `<${crypto.randomUUID()}@ep-mail.local>`, 200)}`, + ...(message.inReplyTo ? [`In-Reply-To: ${safeHeader(message.inReplyTo, 254)}`] : []), + ...(message.references ? [`References: ${safeHeader(message.references, 900)}`] : []), 'MIME-Version: 1.0' ]; let contentType; diff --git a/scripts/prepare-android-web.cjs b/scripts/prepare-android-web.cjs index 2bbfb41..55ec4dd 100644 --- a/scripts/prepare-android-web.cjs +++ b/scripts/prepare-android-web.cjs @@ -10,6 +10,7 @@ const assets = [ 'branding.css', 'platform-bridge-loader.js', 'renderer-state.js', + 'conversation-threads.js', 'mail-content-security.js', 'renderer-mail-api.js', 'app.js', diff --git a/service-worker.js b/service-worker.js index c9d2d85..e8726e8 100644 --- a/service-worker.js +++ b/service-worker.js @@ -1,5 +1,5 @@ -const CACHE='ep-mail-v22'; -const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; +const CACHE='ep-mail-v23'; +const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./conversation-threads.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-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)).then(()=>self.skipWaiting()))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim()))); self.addEventListener('fetch', event => { diff --git a/styles.css b/styles.css index 2c83c4f..c86d351 100644 --- a/styles.css +++ b/styles.css @@ -235,3 +235,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c} .reader-pane{padding-bottom:10px} } @media(max-width:1000px),(max-height:500px) and (orientation:landscape) and (max-width:1200px){.sidebar{overflow:hidden}#mail-nav{display:flex;flex-direction:row;align-items:center;height:42px;min-height:0;max-height:42px;flex:none;overflow-x:auto;overflow-y:hidden;align-content:normal}#mail-nav .folder{height:34px;align-self:center}} +.conversation-toggle{display:block;width:100%;padding:8px 12px;border:0;border-bottom:1px solid var(--border,#ddd);background:transparent;color:inherit;text-align:left;font:inherit;font-size:.8rem;font-weight:600;cursor:pointer} +.conversation-toggle:focus-visible{outline:2px solid currentColor;outline-offset:-2px} +.conversation-replies .message{padding-left:22px} diff --git a/tests/android-pgp.test.cjs b/tests/android-pgp.test.cjs index e39d9b1..969f3b8 100644 --- a/tests/android-pgp.test.cjs +++ b/tests/android-pgp.test.cjs @@ -88,7 +88,9 @@ test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient ke const built = await sender.api.buildOutgoing({ to: 'Bob ', cc: '', subject: 'Secret note', text: 'hello from Android', - messageId: '', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' }, + messageId: '', inReplyTo: '', + references: ' ', + pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' }, attachments: [ { filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') }, { filename: 'charlie.asc', contentType: 'application/pgp-keys', contentBase64: Buffer.from(await thirdParty.api.exportPublic(charlie.key.fingerprint)).toString('base64') } @@ -97,6 +99,8 @@ test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient ke assert.ok(built.rawBase64); saveMimeFixture('encrypted-signed', built.rawBase64); const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8'); + assert.match(raw, /\r\nIn-Reply-To: \r\n/); + assert.match(raw, /\r\nReferences: \r\n/); assert.match(raw, /multipart\/encrypted; protocol="application\/pgp-encrypted"/i); assert.doesNotMatch(raw, /hello from Android|private attachment/); recipient.setMessage({ rawBase64: built.rawBase64 }); diff --git a/tests/conversation-threads.test.cjs b/tests/conversation-threads.test.cjs new file mode 100644 index 0000000..1534ebe --- /dev/null +++ b/tests/conversation-threads.test.cjs @@ -0,0 +1,37 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { groupMessages, messageIds, replyHeaders } = require('../conversation-threads.js'); + +test('groups linked messages transitively in the original order, including absent ancestors', () => { + const messages = [ + { id: 1, messageId: '', references: '' }, + { id: 2, messageId: '', subject: 'Same subject' }, + { id: 3, messageId: '', inReplyTo: '' }, + { id: 4, messageId: '', references: ['', ''] } + ]; + assert.deepEqual(groupMessages(messages).map(group => group.map(message => message.id)), [[1, 3, 4], [2]]); +}); + +test('messages without reference headers do not group by subject or invalid IDs', () => { + const messages = [ + { id: 1, subject: 'Hello', messageId: 'not-an-id' }, + { id: 2, subject: 'Re: Hello', inReplyTo: 'not-an-id' } + ]; + assert.deepEqual(groupMessages(messages).map(group => group.length), [1, 1]); + assert.deepEqual(messageIds('\r\nBcc: '), ['', '']); + assert.deepEqual(messageIds(`<${'a'.repeat(255)}@example>`), []); +}); + +test('reply headers retain the parent and bounded ancestry', () => { + assert.deepEqual(replyHeaders({ messageId: '', references: ['', ''] }), { + inReplyTo: '', references: ' ' + }); + assert.deepEqual(replyHeaders({ references: '' }), { inReplyTo: '', references: '' }); + const result = replyHeaders({ + messageId: '', + references: Array.from({ length: 100 }, (_, i) => `<${i}@example.test>`) + }); + assert.ok(result.references.length <= 900); + assert.ok(result.references.startsWith('<0@example.test>')); + assert.ok(result.references.endsWith('')); +}); diff --git a/tests/conversation-ui.test.cjs b/tests/conversation-ui.test.cjs new file mode 100644 index 0000000..4100fae --- /dev/null +++ b/tests/conversation-ui.test.cjs @@ -0,0 +1,43 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const path = require('node:path'); +const threads = require('../conversation-threads.js'); + +test('conversation toggle hides older messages, clears their selection and preserves scroll', () => { + const source = fs.readFileSync(path.join(__dirname, '..', 'app.js'), 'utf8'); + const code = source.slice(source.indexOf('const collapsedThreads = new Set();'), source.indexOf('function openMessage(id)')); + const list = { innerHTML: '', scrollTop: 42 }; + const state = { + activeFolder: 'Inbox', query: '', activeMessage: null, selectedIds: new Set([1, 2]), + messages: [ + { id: 1, messageId: '', inReplyTo: '', subject: 'Re: Topic', unread: true }, + { id: 2, messageId: '', subject: 'Topic' } + ] + }; + let handler; + const context = { + state, window: { epMailConversationThreads: threads }, + document: { body: { classList: { remove() {} } } }, + esc: value => String(value).replace(/&/g, '&').replace(/ selector === '#message-list' ? list : {}, + $$: selector => selector === '.conversation-toggle' ? [{ + dataset: { thread: '0' }, + getAttribute: () => list.innerHTML.includes('aria-expanded="true"') ? 'true' : 'false', + addEventListener(_type, callback) { handler = callback; } + }] : [], + emptyReader: () => '', openMessage() {} + }; + vm.runInNewContext(`${code}\nrenderList();`, context); + assert.match(list.innerHTML, /aria-expanded="true"/); + assert.match(list.innerHTML, /2 messages · 1 unread/); + handler(); + assert.match(list.innerHTML, /aria-expanded="false"/); + assert.match(list.innerHTML, /class="conversation-replies" hidden/); + assert.deepEqual([...state.selectedIds], [1]); + assert.equal(list.scrollTop, 42); + handler(); + assert.match(list.innerHTML, /aria-expanded="true"/); + assert.doesNotMatch(list.innerHTML, /class="conversation-replies" hidden/); +}); diff --git a/tests/draft-composer.test.cjs b/tests/draft-composer.test.cjs index ee51088..07179e1 100644 --- a/tests/draft-composer.test.cjs +++ b/tests/draft-composer.test.cjs @@ -9,7 +9,7 @@ const mailSource = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8'); const pgpSource = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8'); const setupSource = mailSource.slice(mailSource.indexOf('function setupDraftComposer()'), mailSource.indexOf('\nasync function syncMailbox(')); -function harness(initialDraft = null) { +function harness(initialDraft = null, reply = null, forward = false) { const saved = []; const deleted = []; const toasts = []; @@ -40,7 +40,7 @@ function harness(initialDraft = null) { appShell: { wrapShowCompose(fn) { wrapped = fn(() => {}); } }, selectMailUi: selector => selector === '#modal-root' ? modalRoot : elements.get(selector), document: { createElement: node }, - window: { crypto: { randomUUID: () => 'new-id' }, daybreakMail: { + window: { epMailConversationThreads: require('../conversation-threads.js'), crypto: { randomUUID: () => 'new-id' }, daybreakMail: { saveDraft: values => saveDraft(values), async deleteDraft(id) { deleted.push(id); } } }, @@ -52,7 +52,7 @@ function harness(initialDraft = null) { btoa: value => Buffer.from(value, 'binary').toString('base64') }; vm.runInNewContext(`${setupSource}\nsetupDraftComposer();`, context); - wrapped(null, false, initialDraft); + wrapped(reply, forward, initialDraft); return { modal, modalRoot, elements, saved, deleted, toasts, setSave(fn) { saveDraft = fn; }, @@ -85,6 +85,19 @@ test('reopening a draft restores fields, attachments, and its identity', () => { assert.equal(h.elements.get('.modal-head span').textContent, 'Edit draft'); }); +test('reply draft preserves thread headers when saved and restored; forwards do not inherit them', async () => { + const h = harness(null, { messageId: '', references: '' }); + h.elements.get('#compose-body').value = 'Reply'; + h.modal.dispatch('input'); + await h.runTimers(); + assert.equal(h.saved[0].inReplyTo, ''); + assert.equal(h.saved[0].references, ' '); + const restored = harness(h.saved[0]); + assert.equal(restored.modal._replyHeaders.inReplyTo, ''); + const forward = harness(null, { messageId: '' }, true); + assert.equal(forward.modal._replyHeaders.inReplyTo, ''); +}); + test('blank and whitespace-only new messages are not saved on close or manual save', async () => { const h = harness(); h.elements.get('#compose-body').value = ' \n '; diff --git a/tests/ipc-arguments.test.cjs b/tests/ipc-arguments.test.cjs index 30d32f6..4ec4162 100644 --- a/tests/ipc-arguments.test.cjs +++ b/tests/ipc-arguments.test.cjs @@ -71,6 +71,7 @@ test('validates channel-specific field shapes, limits, and enums', () => { test('prevents renderer-supplied raw SMTP messages while accepting standard compose fields', () => { assert.doesNotThrow(() => validateIpcArguments('mail:send', [{ to: 'friend@example.test', cc: '', subject: 'Hello', text: 'Body', + inReplyTo: '', references: ' ', attachments: [{ filename: 'note.txt', contentBase64: 'aGVsbG8=' }], pgp: { encrypt: true, sign: false, passphrase: null } }])); diff --git a/tests/mail-send-service.test.cjs b/tests/mail-send-service.test.cjs index 02adfd4..b4d1ea4 100644 --- a/tests/mail-send-service.test.cjs +++ b/tests/mail-send-service.test.cjs @@ -82,6 +82,20 @@ test('reports Sent-copy failures without retrying a message accepted by SMTP', a assert.equal(calls.appended.length, 0); }); +test('preserves reply headers in the SMTP message and Sent copy', async () => { + const { sendMailNow, calls } = makeSender(); + await sendMailNow({ email: 'sender@example.com' }, { + to: 'recipient@example.com', + inReplyTo: '', + references: ' ' + }); + assert.equal(calls.smtp[0].inReplyTo, ''); + assert.deepEqual(calls.smtp[0].references, ['', '']); + const saved = JSON.parse(calls.appended[0].content.toString()); + assert.equal(saved.inReplyTo, calls.smtp[0].inReplyTo); + assert.deepEqual(saved.references, calls.smtp[0].references); +}); + test('closes SMTP transport and reports send failures', async () => { const { sendMailNow, calls } = makeSender({ smtpFails: true }); await assert.rejects( diff --git a/tests/pgp-mail.test.cjs b/tests/pgp-mail.test.cjs index 211ce88..d9f0bed 100644 --- a/tests/pgp-mail.test.cjs +++ b/tests/pgp-mail.test.cjs @@ -32,11 +32,16 @@ test('encrypts and signs for a recipient and the sender can read the copy', asyn const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); await exchange(alice, bob); - const { raw, envelope } = await alice.mail.build(sendOptions(alice, 'Bob ', { encrypt: true, sign: true, passphrase: alice.passphrase })); + const { raw, envelope } = await alice.mail.build(sendOptions(alice, 'Bob ', { + encrypt: true, sign: true, passphrase: alice.passphrase, + inReplyTo: '', references: ' ' + })); assert.deepEqual(envelope.to, ['bob@example.com']); assert.ok(!raw.toString('latin1').includes('Top secret')); const parsed = await simpleParser(raw); assert.equal(parsed.subject, 'Héllo secrèt'); + assert.equal(parsed.inReplyTo, ''); + assert.deepEqual(parsed.references, ['', '']); assert.equal(detect(parsed), 'encrypted-mime'); await assert.rejects(() => bob.mail.decrypt(parsed), error => error.code === 'PASSPHRASE_REQUIRED'); await assert.rejects(() => bob.mail.decrypt(parsed, { passphrase: 'wrong wrong' }), error => error.code === 'BAD_PASSPHRASE'); diff --git a/tests/renderer-bootstrap.test.cjs b/tests/renderer-bootstrap.test.cjs index 7a4ab29..8821846 100644 --- a/tests/renderer-bootstrap.test.cjs +++ b/tests/renderer-bootstrap.test.cjs @@ -55,7 +55,7 @@ test('desktop, Android web generation, and offline cache include renderer suppor const buildFiles = require(path.join(root, 'package.json')).build.files; const androidAssets = read('scripts/prepare-android-web.cjs'); const worker = read('service-worker.js'); - for (const file of ['renderer-state.js', 'mail-content-security.js', 'renderer-mail-api.js', 'platform-bridge-loader.js']) { + for (const file of ['renderer-state.js', 'conversation-threads.js', 'mail-content-security.js', 'renderer-mail-api.js', 'platform-bridge-loader.js']) { assert.ok(buildFiles.includes(file), `Electron package is missing ${file}`); assert.ok(androidAssets.includes(`'${file}'`), `Android web generator is missing ${file}`); assert.ok(worker.includes(`'./${file}'`), `service worker is missing ${file}`); diff --git a/www/app.js b/www/app.js index 76bbdd9..80c2663 100644 --- a/www/app.js +++ b/www/app.js @@ -18,7 +18,54 @@ function returnToMessageList() { if (readerListPosition?.folder === state.activeFolder) $('#message-list').scrollTop = readerListPosition.scrollTop; readerListPosition = null; } -function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`
${m.initials}
${esc(m.sender)}
${esc(m.subject)}
${esc(m.snippet)}
${esc(m.time)}
`).join(''):`
⌕

No messages here

Try another folder or search.

`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}} +const collapsedThreads = new Set(); +function renderList() { + const rows = state.messages.filter(m => { + if (state.activeFolder === 'Starred' && !m.star) return false; + if (state.activeFolder === 'Inbox' && m.archived) return false; + if (state.activeFolder === 'Archive' && !m.archived) return false; + if (state.activeFolder === 'Trash' && !m.deleted) return false; + if (state.activeFolder === 'Sent' && !m.sent) return false; + if (state.activeFolder === 'Drafts' || state.activeFolder === 'Snoozed') return false; + if (m.deleted && state.activeFolder !== 'Trash') return false; + return !state.query || `${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase()); + }); + const groups = window.epMailConversationThreads.groupMessages(rows); + const scope = `${window.epMailFeatures?.mail?.connectedAccount?.id || ''}:${state.activeFolder}:`; + const keyFor = message => scope + (window.epMailConversationThreads.messageIds(message.messageId)[0] || `uid:${message.sourceFolder || ''}:${message.id}`); + const rowHtml = m => `
${m.initials}
${esc(m.sender)}
${esc(m.subject)}
${esc(m.snippet)}
${esc(m.time)}
`; + $('#message-list').innerHTML = rows.length ? groups.map((group, index) => { + if (group.length === 1) return rowHtml(group[0]); + const collapsed = group.some(message => collapsedThreads.has(keyFor(message))); + if (collapsed) group.slice(1).forEach(message => state.selectedIds.delete(message.id)); + const unread = group.filter(message => message.unread).length; + return `
${rowHtml(group[0])}
${group.slice(1).map(rowHtml).join('')}
`; + }).join('') : `
⌕

No messages here

Try another folder or search.

`; + $$('.conversation-toggle').forEach(button => button.addEventListener('click', () => { + const group = groups[Number(button.dataset.thread)]; + const collapsing = button.getAttribute('aria-expanded') === 'true'; + group.forEach(message => collapsing ? collapsedThreads.add(keyFor(message)) : collapsedThreads.delete(keyFor(message))); + if (collapsing) group.slice(1).forEach(message => state.selectedIds.delete(message.id)); + const scrollTop = $('#message-list').scrollTop; + renderList(); + $('#message-list').scrollTop = scrollTop; + })); + $$('.message').forEach(row => row.addEventListener('click', e => { + if (e.target.closest('.row-check')) { + const id = +row.dataset.id; + state.selectedIds.has(id) ? state.selectedIds.delete(id) : state.selectedIds.add(id); + return; + } + if (e.target.closest('.star')) { + const m = state.messages.find(x => x.id === +row.dataset.id); + m.star = !m.star; + renderList(); + return; + } + openMessage(+row.dataset.id); + })); + if (!rows.length) { document.body.classList.remove('reader-open'); $('#reader-pane').innerHTML = emptyReader(); } +} function openMessage(id){ state.activeMessage=id; const m=state.messages.find(x=>x.id===id); diff --git a/www/conversation-threads.js b/www/conversation-threads.js new file mode 100644 index 0000000..5d2a243 --- /dev/null +++ b/www/conversation-threads.js @@ -0,0 +1,47 @@ +(function installConversationThreads(root, factory) { + const api = factory(); + if (typeof module === 'object' && module.exports) module.exports = api; + else root.epMailConversationThreads = api; +})(typeof window === 'undefined' ? globalThis : window, function () { + function messageIds(value) { + const text = Array.isArray(value) ? value.join(' ') : String(value || ''); + return [...new Set((text.match(/<[\x21-\x3b\x3d\x3f-\x7e]+@[\x21-\x3b\x3d\x3f-\x7e]+>/g) || []) + .filter(id => id.length <= 254))]; + } + + function replyHeaders(message) { + const inReplyTo = messageIds(message?.messageId)[0] || ''; + if (!inReplyTo) return { inReplyTo: '', references: '' }; + const ids = [...new Set([...messageIds(message.references), inReplyTo])]; + while (ids.join(' ').length > 900 && ids.length > 1) ids.splice(1, 1); + return { inReplyTo, references: ids.join(' ') }; + } + + function groupMessages(messages) { + const parents = messages.map((_, index) => index); + const find = index => { + while (parents[index] !== index) { + parents[index] = parents[parents[index]]; + index = parents[index]; + } + return index; + }; + const owners = new Map(); + messages.forEach((message, index) => { + const ids = [...messageIds(message.messageId), ...messageIds(message.inReplyTo), ...messageIds(message.references)]; + for (const id of new Set(ids)) { + if (owners.has(id)) parents[find(index)] = find(owners.get(id)); + else owners.set(id, index); + } + }); + const groups = new Map(); + messages.forEach((message, index) => { + const root = find(index); + if (!groups.has(root)) groups.set(root, []); + groups.get(root).push(message); + }); + return [...groups.values()]; + } + + return { messageIds, replyHeaders, groupMessages }; +}); diff --git a/www/index.html b/www/index.html index 4616172..5ce5887 100644 --- a/www/index.html +++ b/www/index.html @@ -65,6 +65,7 @@
+ diff --git a/www/mail-ui.js b/www/mail-ui.js index 9289d8c..ef96174 100644 --- a/www/mail-ui.js +++ b/www/mail-ui.js @@ -529,6 +529,9 @@ function setupDraftComposer() { const modal = root.querySelector('.compose-modal'); if (!modal) return; modal.dataset.draftId = draft?.id || ''; + modal._replyHeaders = draft + ? { inReplyTo: draft.inReplyTo || '', references: draft.references || '' } + : reply && !forward ? window.epMailConversationThreads.replyHeaders(reply) : { inReplyTo: '', references: '' }; let attachments = Array.isArray(draft?.attachments) ? draft.attachments : []; modal._composeAttachments = attachments; const fields = modal.querySelector('.compose-fields'); @@ -630,7 +633,8 @@ function setupDraftComposer() { cc: modal.querySelector('#compose-cc').value, subject: modal.querySelector('#compose-subject').value, text: modal.querySelector('#compose-body').value, - attachments: [...attachments] + attachments: [...attachments], + ...modal._replyHeaders }; if (!modal.dataset.draftId && ![values.to, values.cc, values.subject, values.text].some(value => value.trim()) && !values.attachments.length) return Promise.resolve(false); values.id = modal.dataset.draftId || window.crypto.randomUUID(); @@ -1053,6 +1057,7 @@ if (window.daybreakMail) { text: selectMailUi('#compose-body').value, attachments: selectMailUi('#modal-root .compose-modal')?._composeAttachments || [], displayName: mailFeatureState.connectedAccount.displayName || window.epMailFeatures.productivity?.profileName || '', + ...(selectMailUi('#modal-root .compose-modal')?._replyHeaders || {}), ...(pgp ? { pgp } : {}) }); if (result.failed) { diff --git a/www/platform-bridge.js b/www/platform-bridge.js index e564697..4c77097 100644 --- a/www/platform-bridge.js +++ b/www/platform-bridge.js @@ -10859,6 +10859,8 @@ ${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []); `Subject: ${encodeHeader(message.subject || "(no subject)")}`, `Date: ${(/* @__PURE__ */ new Date()).toUTCString().replace("GMT", "+0000")}`, `Message-ID: ${safeHeader(message.messageId || `<${crypto.randomUUID()}@ep-mail.local>`, 200)}`, + ...message.inReplyTo ? [`In-Reply-To: ${safeHeader(message.inReplyTo, 254)}`] : [], + ...message.references ? [`References: ${safeHeader(message.references, 900)}`] : [], "MIME-Version: 1.0" ]; let contentType; diff --git a/www/productivity.js b/www/productivity.js index 63b41e0..bc285fd 100644 --- a/www/productivity.js +++ b/www/productivity.js @@ -59,7 +59,7 @@ function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')} function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()} async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('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);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}} -document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.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'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';}); +document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message').filter(row=>!row.closest('[hidden]'));const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.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'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#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);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()} productivityMailUi.wrapRenderList(baseMessageRenderer => function () { const state = productivityMailUi.state; diff --git a/www/service-worker.js b/www/service-worker.js index c9d2d85..e8726e8 100644 --- a/www/service-worker.js +++ b/www/service-worker.js @@ -1,5 +1,5 @@ -const CACHE='ep-mail-v22'; -const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; +const CACHE='ep-mail-v23'; +const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./conversation-threads.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-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)).then(()=>self.skipWaiting()))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim()))); self.addEventListener('fetch', event => { diff --git a/www/styles.css b/www/styles.css index 2c83c4f..c86d351 100644 --- a/www/styles.css +++ b/www/styles.css @@ -235,3 +235,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c} .reader-pane{padding-bottom:10px} } @media(max-width:1000px),(max-height:500px) and (orientation:landscape) and (max-width:1200px){.sidebar{overflow:hidden}#mail-nav{display:flex;flex-direction:row;align-items:center;height:42px;min-height:0;max-height:42px;flex:none;overflow-x:auto;overflow-y:hidden;align-content:normal}#mail-nav .folder{height:34px;align-self:center}} +.conversation-toggle{display:block;width:100%;padding:8px 12px;border:0;border-bottom:1px solid var(--border,#ddd);background:transparent;color:inherit;text-align:left;font:inherit;font-size:.8rem;font-weight:600;cursor:pointer} +.conversation-toggle:focus-visible{outline:2px solid currentColor;outline-offset:-2px} +.conversation-replies .message{padding-left:22px}