From 84a63441efe674b3c0abd896822997155c106cf8 Mon Sep 17 00:00:00 2001 From: Tero Date: Fri, 16 Oct 2026 20:31:59 +0300 Subject: [PATCH] Refractoring Stage 6.5 Migrated the snooze, attachment, and OpenPGP mail UI to the explicit mail feature API. --- REFACTOR_PLAN.md | 9 ++++--- attachments.js | 17 ++++++------ mail-ui.js | 16 +++++++++--- package-lock.json | 4 +-- package.json | 2 +- pgp-mail-ui.js | 28 ++++++++++---------- renderer-mail-api.js | 18 +++++++++++-- snooze-ui.js | 44 +++++++++++++++----------------- tests/renderer-mail-api.test.cjs | 25 ++++++++++++++++-- www/attachments.js | 17 ++++++------ www/mail-ui.js | 16 +++++++++--- www/pgp-mail-ui.js | 28 ++++++++++---------- www/renderer-mail-api.js | 18 +++++++++++-- www/snooze-ui.js | 44 +++++++++++++++----------------- 14 files changed, 178 insertions(+), 108 deletions(-) diff --git a/REFACTOR_PLAN.md b/REFACTOR_PLAN.md index 7f71f1c..e9091a2 100644 --- a/REFACTOR_PLAN.md +++ b/REFACTOR_PLAN.md @@ -104,6 +104,8 @@ This is a gradual destination, not a requirement to move everything at once. IPC - [x] Extract mail HTML sanitization and remote-image approval checks into a dedicated renderer API (`mail-content-security.js`). - [x] Add an explicit mail feature API and migrate the account manager to it (`renderer-mail-api.js`, `account-ui.js`). - [x] Migrate snooze UI state/sync access to the mail feature API (`snooze-ui.js`). +- [x] Migrate attachment UI state, selectors, and message hooks to the mail feature API (`attachments.js`). +- [x] Migrate OpenPGP mail UI reader/compose hooks to the mail feature API (`pgp-mail-ui.js`). - [ ] Migrate remaining mail-related consumers and remove transitional global dependencies. - Replace hidden globals and script-order dependencies with imports or passed dependencies. - Keep root web assets canonical and generated copies out of hand-edited workflows. @@ -130,7 +132,7 @@ This is a gradual destination, not a requirement to move everything at once. IPC - Electron Builder and the desktop Actions artifact name derive from `package.json`. - Android `versionName` derives from the same package version. Its current `versionCode` mapping is `major * 10000 + minor * 100 + patch`; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions. - `scripts/build-all.ps1` uses the package version for APK naming. Before a release, bump once with `npm run bump:build`, verify the lockfile and computed Android version code, and build every target without another bump. -- Latest version check: `package.json` and both lockfile version fields are `0.4.16`; Android derives `versionName 0.4.16` and `versionCode 416`. `release/` contains Windows artifacts through `0.4.15`; the `0.4.16` artifact has not been built yet. +- Latest version check: `package.json` and both lockfile version fields are `0.4.17`; Android derives `versionName 0.4.17` and `versionCode 417`. The user reports that the current artifact builds and works; the checked-in `release/` directory contains Windows artifacts through `0.4.16`. ## Progress log @@ -149,9 +151,10 @@ This is a gradual destination, not a requirement to move everything at once. IPC - Step 5 moved OpenPGP handler registration and message-source fetching into a feature module and added registration/schema coverage. - Step 5 moved DAV handler registration into a feature module and added registration/schema coverage; the full suite passes 110 tests. - Step 5 grouped mail/account handlers in `desktop/ipc/mail.cjs`; all 114 tests pass and the remaining app-version handler stays in the Electron shell. -- Added a build-version consistency check. Package/lockfile are now `0.4.16`, with Android build number `416`; the latest artifact observed is Windows `0.4.15`. +- Added a build-version consistency check. Package/lockfile are now `0.4.17`, with Android build number `417`; the latest artifact observed is Windows `0.4.16`. - Step 5 grouped mail/account handlers and added a release-version consistency test; current package/lockfile/Android version alignment was checked and documented. - Step 6 added `renderer-state.js`, extracted the mail HTML security API, and introduced `renderer-mail-api.js`; `account-ui.js` now uses that explicit API instead of several mail globals. Transitional aliases remain for other classic scripts. -- Step 6's renderer API slice passes 121 tests. The `0.4.16` artifact has not been built as part of this renderer change. +- Step 6's renderer API slice passes 121 tests. The `0.4.17` artifact has not been built as part of this renderer change. +- Step 6 also migrated snooze and attachment UI state/sync/reader integrations to the mail feature API; 121 tests pass. The latest built artifact observed is `0.4.16`. - The current IPC/DAV validation changes pass the full suite: 108 tests. - While work continued, `package.json` and `package-lock.json` reflected a version bump to `0.4.6`; those changes were preserved. diff --git a/attachments.js b/attachments.js index a4b1ae4..2c245f3 100644 --- a/attachments.js +++ b/attachments.js @@ -1,4 +1,8 @@ // Attachment previews and a dedicated view for finding and managing attachments across mailboxes. +const mailUi = window.epMailFeatures.mail; +const $ = mailUi.select; +const $$ = mailUi.selectAll; +const toast = mailUi.toast; const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash']; let attachmentItems = []; @@ -52,11 +56,9 @@ function downloadAttachment(details) { } // Add a Preview button to each attachment in the reader. -if (typeof openMessage === 'function') { - const baseOpenMessage = openMessage; - openMessage = function (id) { +mailUi.wrapOpenMessage(baseOpenMessage => function (id) { baseOpenMessage(id); - const message = messages.find(item => item.id === id); + const message = mailUi.state.messages.find(item => item.id === id); if (!message?.uid) return; $$('#reader-pane .attachment').forEach(row => { const download = row.querySelector('.download'); @@ -73,12 +75,11 @@ if (typeof openMessage === 'function') { panel = document.createElement('div'); panel.className = 'attachment-preview'; row.after(panel); - void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename }); + void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || mailUi.state.activeFolder, filename: download.dataset.filename }); }); download.before(button); }); - }; -} + }); async function collectAttachments() { const items = []; @@ -103,7 +104,7 @@ async function collectAttachments() { } async function openAttachmentsView() { - if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; } + if (!mailUi.connectedAccount || !window.daybreakMail) { mailUi.openMailAccount(); return; } const root = $('#modal-root'); root.innerHTML = ``; const close = () => { root.innerHTML = ''; }; diff --git a/mail-ui.js b/mail-ui.js index 3c738ec..7e401bb 100644 --- a/mail-ui.js +++ b/mail-ui.js @@ -735,7 +735,9 @@ if (window.daybreakMail) { sendButton.disabled = true; sendButton.textContent = 'Sending…'; try { - const pgp = window.pgpPrepareSend ? await window.pgpPrepareSend(recipient, $('#compose-cc').value) : null; + const pgp = window.epMailFeatures.pgp?.prepareSend + ? await window.epMailFeatures.pgp.prepareSend(recipient, $('#compose-cc').value) + : null; if (pgp === false) { sendButton.disabled = false; sendButton.textContent = 'Send ↗'; @@ -794,8 +796,16 @@ const mailUiApi = window.epMailUiModules.createMailUiApi({ updateAccountCard, getRenderList: () => renderList, getOpenMessage: () => openMessage, + getShowCompose: () => showCompose, baseRenderList: renderList, emptyReader, - openMailAccount + openMailAccount, + select: $, + selectAll: $$, + toast, + setRenderList: renderer => { renderList = renderer; }, + setOpenMessage: renderer => { openMessage = renderer; }, + setShowCompose: renderer => { showCompose = renderer; } }); -window.epMailFeatures = Object.freeze({ ...(window.epMailFeatures || {}), mail: mailUiApi }); +window.epMailFeatures = window.epMailFeatures || {}; +window.epMailFeatures.mail = mailUiApi; diff --git a/package-lock.json b/package-lock.json index bb63e02..8648f13 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.4.16", + "version": "0.4.17", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.4.16", + "version": "0.4.17", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index 7cb3bb1..f0a5fee 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.4.16", + "version": "0.4.17", "private": true, "description": "Eternity Project mail client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", diff --git a/pgp-mail-ui.js b/pgp-mail-ui.js index 3b2ce73..65d80d7 100644 --- a/pgp-mail-ui.js +++ b/pgp-mail-ui.js @@ -1,4 +1,8 @@ // Reading and sending OpenPGP mail (desktop). Inert where there is no key store. +const mailUi = window.epMailFeatures.mail; +const $ = mailUi.select; +const $$ = mailUi.selectAll; +const toast = mailUi.toast; const pgpApi = () => window.daybreakMail?.pgp; function pgpAskPassphrase(title, detail) { @@ -95,7 +99,7 @@ async function pgpUnlockMessage(message, interactive) { body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size, snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys } }); - if (activeMessage === message.id) openMessage(message.id); + if (mailUi.state.activeMessage === message.id) mailUi.openMessage(message.id); return; } if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') { @@ -111,24 +115,19 @@ async function pgpUnlockMessage(message, interactive) { } } -if (typeof openMessage === 'function') { - const baseOpenMessage = openMessage; - openMessage = function (id) { +mailUi.wrapOpenMessage(baseOpenMessage => function (id) { baseOpenMessage(id); - const message = messages.find(item => item.id === id); + const message = mailUi.state.messages.find(item => item.id === id); if (!message || !pgpApi()) return; pgpRenderReaderState(message); if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { message.pgpAutoTried = true; void pgpUnlockMessage(message, false); } - }; -} + }); // Compose: encrypt/sign options. -if (typeof showCompose === 'function') { - const baseShowCompose = showCompose; - showCompose = function (reply, forward = false) { +mailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) { baseShowCompose(reply, forward); const footer = $('#modal-root .compose-footer'); if (!footer || !pgpApi()) return; @@ -163,11 +162,10 @@ if (typeof showCompose === 'function') { ['#compose-to', '#compose-cc'].forEach(selector => $(selector)?.addEventListener('input', schedule)); sign.addEventListener('change', schedule); schedule(); - }; -} + }); // Called by the send handler. Returns null (plain mail), false (cancelled) or send options. -window.pgpPrepareSend = async function pgpPrepareSend(to, cc) { +async function prepareSend(to, cc) { if (!pgpApi()) return null; let encrypt = Boolean($('#pgp-encrypt')?.checked); const sign = Boolean($('#pgp-sign')?.checked); @@ -195,4 +193,6 @@ window.pgpPrepareSend = async function pgpPrepareSend(to, cc) { } } return { encrypt, sign, passphrase }; -}; +} + +window.epMailFeatures.pgp = Object.freeze({ prepareSend }); diff --git a/renderer-mail-api.js b/renderer-mail-api.js index d65456e..4c5e2ea 100644 --- a/renderer-mail-api.js +++ b/renderer-mail-api.js @@ -8,9 +8,16 @@ updateAccountCard, getRenderList, getOpenMessage, + getShowCompose, baseRenderList, emptyReader, - openMailAccount + openMailAccount, + select, + selectAll, + toast, + setRenderList, + setOpenMessage, + setShowCompose }) { return Object.freeze({ state, @@ -21,9 +28,16 @@ updateAccountCard, get renderList() { return getRenderList(); }, get openMessage() { return getOpenMessage(); }, + get showCompose() { return getShowCompose(); }, baseRenderList, emptyReader, - openMailAccount + openMailAccount, + select, + selectAll, + toast, + wrapRenderList(decorator) { setRenderList(decorator(getRenderList())); }, + wrapOpenMessage(decorator) { setOpenMessage(decorator(getOpenMessage())); }, + wrapShowCompose(decorator) { setShowCompose(decorator(getShowCompose())); } }); } diff --git a/snooze-ui.js b/snooze-ui.js index efc52df..d843a94 100644 --- a/snooze-ui.js +++ b/snooze-ui.js @@ -16,10 +16,10 @@ function nextMorning(daysAhead) { function openSnoozeDialog(items) { const eligible = items.filter(message => message?.uid && mailUi.connectedAccount); if (!eligible.length) { - toast('Snoozing is available for messages in a connected mailbox.'); + mailUi.toast('Snoozing is available for messages in a connected mailbox.'); return; } - const root = $('#modal-root'); + const root = mailUi.select('#modal-root'); const tomorrow = nextMorning(1); const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000); root.innerHTML = ``; @@ -31,7 +31,7 @@ function openSnoozeDialog(items) { const schedule = async dueAt => { if (!Number.isFinite(dueAt) || dueAt <= Date.now()) { - $('#snooze-status').textContent = 'Choose a reminder time in the future.'; + mailUi.select('#snooze-status').textContent = 'Choose a reminder time in the future.'; return; } const buttons = [...root.querySelectorAll('button')]; @@ -49,11 +49,11 @@ function openSnoozeDialog(items) { }); } close(); - toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`); + mailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`); mailUi.state.selectedIds.clear(); await mailUi.syncMailbox(false, { offset: 0 }); } catch (error) { - $('#snooze-status').textContent = error.message || 'Could not set the reminder.'; + mailUi.select('#snooze-status').textContent = error.message || 'Could not set the reminder.'; buttons.forEach(button => { button.disabled = false; }); } }; @@ -61,8 +61,8 @@ function openSnoozeDialog(items) { 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(); + mailUi.select('#snooze-custom').onclick = () => schedule(new Date(mailUi.select('#snooze-custom-time').value).getTime()); + mailUi.select('#snooze-custom-time').focus(); } function unsnoozeMessage(message) { @@ -72,13 +72,13 @@ function unsnoozeMessage(message) { sourceFolder, dueAt: null }).then(async () => { - toast('Message returned to its mailbox'); + mailUi.toast('Message returned to its mailbox'); await mailUi.syncMailbox(false, { offset: 0 }); - }).catch(error => toast(error.message || 'Could not return the message')); + }).catch(error => mailUi.toast(error.message || 'Could not return the message')); } function showMessageActions(message) { - const root = $('#modal-root'); + const root = mailUi.select('#modal-root'); root.innerHTML = ``; root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; }); root.querySelector('.modal-overlay').onclick = event => { @@ -86,8 +86,7 @@ function showMessageActions(message) { }; } -const renderListBeforeSnooze = mailUi.renderList; -renderList = function () { +mailUi.wrapRenderList(renderListBeforeSnooze => function () { if (mailUi.state.activeFolder === 'Snoozed') { const originalMessages = mailUi.state.messages.slice(); const snoozedMessages = mailUi.state.messages.filter(message => message.snoozedUntil); @@ -103,7 +102,7 @@ renderList = function () { message.deleted = deleted; }); mailUi.state.messages.splice(0, mailUi.state.messages.length, ...originalMessages); - for (const row of $$('.message')) { + for (const row of mailUi.selectAll('.message')) { const message = mailUi.state.messages.find(item => item.id === Number(row.dataset.id)); if (!message?.snoozedUntil) continue; const due = new Date(message.snoozedUntil); @@ -113,21 +112,20 @@ renderList = function () { } return; } - renderListBeforeSnooze(); -}; + return renderListBeforeSnooze(); +}); -const openMessageBeforeSnooze = mailUi.openMessage; -openMessage = function (id) { +mailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) { openMessageBeforeSnooze(id); const message = mailUi.state.messages.find(item => item.id === id); - const tools = $('.reader-tools'); + const tools = mailUi.select('.reader-tools'); if (!message || !tools) return; const snoozed = mailUi.state.activeFolder === 'Snoozed'; tools.insertAdjacentHTML('afterbegin', ``); -}; +}); document.addEventListener('DOMContentLoaded', () => { - $('#mark-unread').insertAdjacentHTML('afterend', ''); + mailUi.select('#mark-unread').insertAdjacentHTML('afterend', ''); if (window.daybreakMail?.checkSnoozeReminders) { const checkReminders = () => window.daybreakMail.checkSnoozeReminders() .catch(error => console.error('Could not check mail reminders:', error)); @@ -146,7 +144,7 @@ document.addEventListener('click', event => { event.stopImmediatePropagation(); if (action) { const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage); - $('#modal-root').innerHTML = ''; + mailUi.select('#modal-root').innerHTML = ''; if (!message) return; if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]); else if (action.dataset.messageAction === 'label') addMessageLabel(message); @@ -156,8 +154,8 @@ document.addEventListener('click', event => { if (type === 'unread') message.unread = true; if (type === 'inbox') message.archived = false; mailUi.renderList(); - toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox'); - }).catch(error => toast(error.message || 'Could not update the message')); + mailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox'); + }).catch(error => mailUi.toast(error.message || 'Could not update the message')); } return; } diff --git a/tests/renderer-mail-api.test.cjs b/tests/renderer-mail-api.test.cjs index fdd5332..8b62259 100644 --- a/tests/renderer-mail-api.test.cjs +++ b/tests/renderer-mail-api.test.cjs @@ -14,9 +14,16 @@ test('mail feature API exposes explicit state and account/sync UI actions', () = updateAccountCard: value => calls.push(['card', value]), getRenderList: () => () => calls.push(['render']), getOpenMessage: () => () => calls.push(['open']), + getShowCompose: () => () => calls.push(['compose']), baseRenderList: () => calls.push(['base-render']), emptyReader: () => '', - openMailAccount: value => calls.push(['open-account', value]) + openMailAccount: value => calls.push(['open-account', value]), + select: selector => selector, + selectAll: selector => [selector], + toast: value => calls.push(['toast', value]), + setRenderList: renderer => { calls.push(['set-render-list', renderer]); }, + setOpenMessage: renderer => { calls.push(['set-open-message', renderer]); }, + setShowCompose: renderer => { calls.push(['set-show-compose', renderer]); } }; const api = createMailUiApi({ state, @@ -34,10 +41,18 @@ test('mail feature API exposes explicit state and account/sync UI actions', () = api.updateAccountCard(api.connectedAccount); api.renderList(); api.openMessage(1); + api.showCompose(); api.baseRenderList(); assert.equal(api.emptyReader(), ''); + assert.equal(api.select('selector'), 'selector'); + assert.deepEqual(api.selectAll('selector'), ['selector']); + api.wrapRenderList(base => () => { calls.push(['wrapped-render']); return base(); }); + api.wrapOpenMessage(base => () => { calls.push(['wrapped-open']); return base(); }); + api.wrapShowCompose(base => () => { calls.push(['wrapped-compose']); return base(); }); api.openMailAccount(); - assert.deepEqual(calls.map(call => call[0]), ['offset', 'sync', 'card', 'render', 'open', 'base-render', 'open-account']); + assert.deepEqual(calls.map(call => call[0]), [ + 'offset', 'sync', 'card', 'render', 'open', 'compose', 'base-render', 'set-render-list', 'set-open-message', 'set-show-compose', 'open-account' + ]); assert.equal(Object.isFrozen(api), true); }); @@ -45,8 +60,14 @@ test('account and snooze UI consume the explicit mail API instead of selected le const root = path.resolve(__dirname, '..'); const accountUi = fs.readFileSync(path.join(root, 'account-ui.js'), 'utf8'); const snoozeUi = fs.readFileSync(path.join(root, 'snooze-ui.js'), 'utf8'); + const attachmentUi = fs.readFileSync(path.join(root, 'attachments.js'), 'utf8'); + const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8'); assert.match(accountUi, /window\.epMailFeatures\.mail/); assert.match(snoozeUi, /window\.epMailFeatures\.mail/); + assert.match(attachmentUi, /window\.epMailFeatures\.mail/); + assert.match(pgpMailUi, /window\.epMailFeatures\.mail/); assert.doesNotMatch(accountUi, /\bconnectedMailAccount\b|\bmailPageOffset\b|(? function (id) { baseOpenMessage(id); - const message = messages.find(item => item.id === id); + const message = mailUi.state.messages.find(item => item.id === id); if (!message?.uid) return; $$('#reader-pane .attachment').forEach(row => { const download = row.querySelector('.download'); @@ -73,12 +75,11 @@ if (typeof openMessage === 'function') { panel = document.createElement('div'); panel.className = 'attachment-preview'; row.after(panel); - void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename }); + void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || mailUi.state.activeFolder, filename: download.dataset.filename }); }); download.before(button); }); - }; -} + }); async function collectAttachments() { const items = []; @@ -103,7 +104,7 @@ async function collectAttachments() { } async function openAttachmentsView() { - if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; } + if (!mailUi.connectedAccount || !window.daybreakMail) { mailUi.openMailAccount(); return; } const root = $('#modal-root'); root.innerHTML = ``; const close = () => { root.innerHTML = ''; }; diff --git a/www/mail-ui.js b/www/mail-ui.js index 3c738ec..7e401bb 100644 --- a/www/mail-ui.js +++ b/www/mail-ui.js @@ -735,7 +735,9 @@ if (window.daybreakMail) { sendButton.disabled = true; sendButton.textContent = 'Sending…'; try { - const pgp = window.pgpPrepareSend ? await window.pgpPrepareSend(recipient, $('#compose-cc').value) : null; + const pgp = window.epMailFeatures.pgp?.prepareSend + ? await window.epMailFeatures.pgp.prepareSend(recipient, $('#compose-cc').value) + : null; if (pgp === false) { sendButton.disabled = false; sendButton.textContent = 'Send ↗'; @@ -794,8 +796,16 @@ const mailUiApi = window.epMailUiModules.createMailUiApi({ updateAccountCard, getRenderList: () => renderList, getOpenMessage: () => openMessage, + getShowCompose: () => showCompose, baseRenderList: renderList, emptyReader, - openMailAccount + openMailAccount, + select: $, + selectAll: $$, + toast, + setRenderList: renderer => { renderList = renderer; }, + setOpenMessage: renderer => { openMessage = renderer; }, + setShowCompose: renderer => { showCompose = renderer; } }); -window.epMailFeatures = Object.freeze({ ...(window.epMailFeatures || {}), mail: mailUiApi }); +window.epMailFeatures = window.epMailFeatures || {}; +window.epMailFeatures.mail = mailUiApi; diff --git a/www/pgp-mail-ui.js b/www/pgp-mail-ui.js index 3b2ce73..65d80d7 100644 --- a/www/pgp-mail-ui.js +++ b/www/pgp-mail-ui.js @@ -1,4 +1,8 @@ // Reading and sending OpenPGP mail (desktop). Inert where there is no key store. +const mailUi = window.epMailFeatures.mail; +const $ = mailUi.select; +const $$ = mailUi.selectAll; +const toast = mailUi.toast; const pgpApi = () => window.daybreakMail?.pgp; function pgpAskPassphrase(title, detail) { @@ -95,7 +99,7 @@ async function pgpUnlockMessage(message, interactive) { body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size, snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys } }); - if (activeMessage === message.id) openMessage(message.id); + if (mailUi.state.activeMessage === message.id) mailUi.openMessage(message.id); return; } if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') { @@ -111,24 +115,19 @@ async function pgpUnlockMessage(message, interactive) { } } -if (typeof openMessage === 'function') { - const baseOpenMessage = openMessage; - openMessage = function (id) { +mailUi.wrapOpenMessage(baseOpenMessage => function (id) { baseOpenMessage(id); - const message = messages.find(item => item.id === id); + const message = mailUi.state.messages.find(item => item.id === id); if (!message || !pgpApi()) return; pgpRenderReaderState(message); if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { message.pgpAutoTried = true; void pgpUnlockMessage(message, false); } - }; -} + }); // Compose: encrypt/sign options. -if (typeof showCompose === 'function') { - const baseShowCompose = showCompose; - showCompose = function (reply, forward = false) { +mailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) { baseShowCompose(reply, forward); const footer = $('#modal-root .compose-footer'); if (!footer || !pgpApi()) return; @@ -163,11 +162,10 @@ if (typeof showCompose === 'function') { ['#compose-to', '#compose-cc'].forEach(selector => $(selector)?.addEventListener('input', schedule)); sign.addEventListener('change', schedule); schedule(); - }; -} + }); // Called by the send handler. Returns null (plain mail), false (cancelled) or send options. -window.pgpPrepareSend = async function pgpPrepareSend(to, cc) { +async function prepareSend(to, cc) { if (!pgpApi()) return null; let encrypt = Boolean($('#pgp-encrypt')?.checked); const sign = Boolean($('#pgp-sign')?.checked); @@ -195,4 +193,6 @@ window.pgpPrepareSend = async function pgpPrepareSend(to, cc) { } } return { encrypt, sign, passphrase }; -}; +} + +window.epMailFeatures.pgp = Object.freeze({ prepareSend }); diff --git a/www/renderer-mail-api.js b/www/renderer-mail-api.js index d65456e..4c5e2ea 100644 --- a/www/renderer-mail-api.js +++ b/www/renderer-mail-api.js @@ -8,9 +8,16 @@ updateAccountCard, getRenderList, getOpenMessage, + getShowCompose, baseRenderList, emptyReader, - openMailAccount + openMailAccount, + select, + selectAll, + toast, + setRenderList, + setOpenMessage, + setShowCompose }) { return Object.freeze({ state, @@ -21,9 +28,16 @@ updateAccountCard, get renderList() { return getRenderList(); }, get openMessage() { return getOpenMessage(); }, + get showCompose() { return getShowCompose(); }, baseRenderList, emptyReader, - openMailAccount + openMailAccount, + select, + selectAll, + toast, + wrapRenderList(decorator) { setRenderList(decorator(getRenderList())); }, + wrapOpenMessage(decorator) { setOpenMessage(decorator(getOpenMessage())); }, + wrapShowCompose(decorator) { setShowCompose(decorator(getShowCompose())); } }); } diff --git a/www/snooze-ui.js b/www/snooze-ui.js index efc52df..d843a94 100644 --- a/www/snooze-ui.js +++ b/www/snooze-ui.js @@ -16,10 +16,10 @@ function nextMorning(daysAhead) { function openSnoozeDialog(items) { const eligible = items.filter(message => message?.uid && mailUi.connectedAccount); if (!eligible.length) { - toast('Snoozing is available for messages in a connected mailbox.'); + mailUi.toast('Snoozing is available for messages in a connected mailbox.'); return; } - const root = $('#modal-root'); + const root = mailUi.select('#modal-root'); const tomorrow = nextMorning(1); const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000); root.innerHTML = ``; @@ -31,7 +31,7 @@ function openSnoozeDialog(items) { const schedule = async dueAt => { if (!Number.isFinite(dueAt) || dueAt <= Date.now()) { - $('#snooze-status').textContent = 'Choose a reminder time in the future.'; + mailUi.select('#snooze-status').textContent = 'Choose a reminder time in the future.'; return; } const buttons = [...root.querySelectorAll('button')]; @@ -49,11 +49,11 @@ function openSnoozeDialog(items) { }); } close(); - toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`); + mailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`); mailUi.state.selectedIds.clear(); await mailUi.syncMailbox(false, { offset: 0 }); } catch (error) { - $('#snooze-status').textContent = error.message || 'Could not set the reminder.'; + mailUi.select('#snooze-status').textContent = error.message || 'Could not set the reminder.'; buttons.forEach(button => { button.disabled = false; }); } }; @@ -61,8 +61,8 @@ function openSnoozeDialog(items) { 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(); + mailUi.select('#snooze-custom').onclick = () => schedule(new Date(mailUi.select('#snooze-custom-time').value).getTime()); + mailUi.select('#snooze-custom-time').focus(); } function unsnoozeMessage(message) { @@ -72,13 +72,13 @@ function unsnoozeMessage(message) { sourceFolder, dueAt: null }).then(async () => { - toast('Message returned to its mailbox'); + mailUi.toast('Message returned to its mailbox'); await mailUi.syncMailbox(false, { offset: 0 }); - }).catch(error => toast(error.message || 'Could not return the message')); + }).catch(error => mailUi.toast(error.message || 'Could not return the message')); } function showMessageActions(message) { - const root = $('#modal-root'); + const root = mailUi.select('#modal-root'); root.innerHTML = ``; root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; }); root.querySelector('.modal-overlay').onclick = event => { @@ -86,8 +86,7 @@ function showMessageActions(message) { }; } -const renderListBeforeSnooze = mailUi.renderList; -renderList = function () { +mailUi.wrapRenderList(renderListBeforeSnooze => function () { if (mailUi.state.activeFolder === 'Snoozed') { const originalMessages = mailUi.state.messages.slice(); const snoozedMessages = mailUi.state.messages.filter(message => message.snoozedUntil); @@ -103,7 +102,7 @@ renderList = function () { message.deleted = deleted; }); mailUi.state.messages.splice(0, mailUi.state.messages.length, ...originalMessages); - for (const row of $$('.message')) { + for (const row of mailUi.selectAll('.message')) { const message = mailUi.state.messages.find(item => item.id === Number(row.dataset.id)); if (!message?.snoozedUntil) continue; const due = new Date(message.snoozedUntil); @@ -113,21 +112,20 @@ renderList = function () { } return; } - renderListBeforeSnooze(); -}; + return renderListBeforeSnooze(); +}); -const openMessageBeforeSnooze = mailUi.openMessage; -openMessage = function (id) { +mailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) { openMessageBeforeSnooze(id); const message = mailUi.state.messages.find(item => item.id === id); - const tools = $('.reader-tools'); + const tools = mailUi.select('.reader-tools'); if (!message || !tools) return; const snoozed = mailUi.state.activeFolder === 'Snoozed'; tools.insertAdjacentHTML('afterbegin', ``); -}; +}); document.addEventListener('DOMContentLoaded', () => { - $('#mark-unread').insertAdjacentHTML('afterend', ''); + mailUi.select('#mark-unread').insertAdjacentHTML('afterend', ''); if (window.daybreakMail?.checkSnoozeReminders) { const checkReminders = () => window.daybreakMail.checkSnoozeReminders() .catch(error => console.error('Could not check mail reminders:', error)); @@ -146,7 +144,7 @@ document.addEventListener('click', event => { event.stopImmediatePropagation(); if (action) { const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage); - $('#modal-root').innerHTML = ''; + mailUi.select('#modal-root').innerHTML = ''; if (!message) return; if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]); else if (action.dataset.messageAction === 'label') addMessageLabel(message); @@ -156,8 +154,8 @@ document.addEventListener('click', event => { if (type === 'unread') message.unread = true; if (type === 'inbox') message.archived = false; mailUi.renderList(); - toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox'); - }).catch(error => toast(error.message || 'Could not update the message')); + mailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox'); + }).catch(error => mailUi.toast(error.message || 'Could not update the message')); } return; }