diff --git a/REFACTOR_PLAN.md b/REFACTOR_PLAN.md
index e9091a2..2903772 100644
--- a/REFACTOR_PLAN.md
+++ b/REFACTOR_PLAN.md
@@ -106,6 +106,9 @@ This is a gradual destination, not a requirement to move everything at once. IPC
- [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`).
+- [x] Migrate shortcut mail-state access and preferences extension to feature APIs (`shortcuts.js`, `productivity.js`).
+- [x] Migrate additional mail-related consumers to unique local aliases to avoid classic-script lexical redeclarations.
+- [x] Add a combined-script parse test to prevent duplicate top-level lexical declarations from stopping later UI scripts.
- [ ] 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.
@@ -132,7 +135,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.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`.
+- Latest version check: `package.json` and both lockfile version fields are `0.4.18`; Android derives `versionName 0.4.18` and `versionCode 418`. The checked-in `release/` directory contains Windows artifacts through `0.4.18`, which the user confirms builds and works.
## Progress log
@@ -151,10 +154,9 @@ 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.17`, with Android build number `417`; the latest artifact observed is Windows `0.4.16`.
+- Added a build-version consistency check. Package/lockfile are `0.4.18`, with Android build number `418`; the user confirms the 0.4.18 artifact works.
- 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.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`.
+- Step 6 migrated snooze, attachment, OpenPGP mail, shortcut, and productivity state/render integrations to feature APIs; compatibility globals remain in the core shell and some cross-feature hooks. Added a combined-classic-script parse guard; the suite passes 122 tests.
- 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/account-ui.js b/account-ui.js
index 10c4875..351f581 100644
--- a/account-ui.js
+++ b/account-ui.js
@@ -1,4 +1,4 @@
-const mailUi = window.epMailFeatures.mail;
+const accountMailUi = window.epMailFeatures.mail;
async function openAccountManager(){
const root=$('#modal-root');
@@ -10,16 +10,16 @@ async function openAccountManager(){
const close=()=>root.innerHTML='';
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
- root.querySelector('#add-mail-account').onclick=()=>{close();mailUi.openMailAccount()};
+ root.querySelector('#add-mail-account').onclick=()=>{close();accountMailUi.openMailAccount()};
root.onclick=async event=>{
const switchButton=event.target.closest('[data-switch-account]');
- if(switchButton){switchButton.disabled=true;try{mailUi.connectedAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);mailUi.state.activeFolder='Inbox';mailUi.setPageOffset(0);document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';mailUi.updateAccountCard(mailUi.connectedAccount);close();await mailUi.syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
+ if(switchButton){switchButton.disabled=true;try{accountMailUi.connectedAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';accountMailUi.updateAccountCard(accountMailUi.connectedAccount);close();await accountMailUi.syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
const davButton=event.target.closest('[data-open-dav]');
if(davButton){close();openDavManager(davButton.dataset.openDav);return}
const editButton=event.target.closest('[data-edit-account]');
- if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)mailUi.openMailAccount(account);return}
+ if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
const removeButton=event.target.closest('[data-remove-account]');
- if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;mailUi.connectedAccount=active;if(active){mailUi.updateAccountCard(active);close();mailUi.state.activeFolder='Inbox';mailUi.setPageOffset(0);await mailUi.syncMailbox(false,{offset:0})}else{mailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});mailUi.state.messages.splice(0,mailUi.state.messages.length);mailUi.renderList();$('#reader-pane').innerHTML=mailUi.emptyReader();toast('Mail account removed');openAccountManager()}}catch(error){toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
+ if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();$('#reader-pane').innerHTML=accountMailUi.emptyReader();toast('Mail account removed');openAccountManager()}}catch(error){toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
};
}catch(error){toast(error.message||'Could not load mail accounts')}
}
diff --git a/attachments.js b/attachments.js
index 2c245f3..3a76ccb 100644
--- a/attachments.js
+++ b/attachments.js
@@ -1,8 +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 attachmentMailUi = window.epMailFeatures.mail;
+const selectAttachmentUi = attachmentMailUi.select;
+const selectAllAttachmentUi = attachmentMailUi.selectAll;
+const toastAttachmentUi = attachmentMailUi.toast;
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
let attachmentItems = [];
@@ -49,18 +49,18 @@ async function previewAttachment(target, details) {
}
function downloadAttachment(details) {
- if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; }
+ if (!details.uid || !window.daybreakMail?.saveAttachment) { toastAttachmentUi('Attachment download is available for connected mailbox messages'); return; }
window.daybreakMail.saveAttachment(details)
- .then(result => { if (result.saved) toast('Attachment saved'); })
- .catch(error => toast(error.message || 'Could not save attachment'));
+ .then(result => { if (result.saved) toastAttachmentUi('Attachment saved'); })
+ .catch(error => toastAttachmentUi(error.message || 'Could not save attachment'));
}
// Add a Preview button to each attachment in the reader.
-mailUi.wrapOpenMessage(baseOpenMessage => function (id) {
+attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
baseOpenMessage(id);
- const message = mailUi.state.messages.find(item => item.id === id);
+ const message = attachmentMailUi.state.messages.find(item => item.id === id);
if (!message?.uid) return;
- $$('#reader-pane .attachment').forEach(row => {
+ selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
const download = row.querySelector('.download');
if (!download || row.querySelector('.preview-attachment')) return;
const button = document.createElement('button');
@@ -75,7 +75,7 @@ mailUi.wrapOpenMessage(baseOpenMessage => function (id) {
panel = document.createElement('div');
panel.className = 'attachment-preview';
row.after(panel);
- void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || mailUi.state.activeFolder, filename: download.dataset.filename });
+ void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || attachmentMailUi.state.activeFolder, filename: download.dataset.filename });
});
download.before(button);
});
@@ -104,16 +104,16 @@ async function collectAttachments() {
}
async function openAttachmentsView() {
- if (!mailUi.connectedAccount || !window.daybreakMail) { mailUi.openMailAccount(); return; }
- const root = $('#modal-root');
+ if (!attachmentMailUi.connectedAccount || !window.daybreakMail) { attachmentMailUi.openMailAccount(); return; }
+ const root = selectAttachmentUi('#modal-root');
root.innerHTML = `
Attachments
Loading attachments…
`;
const close = () => { root.innerHTML = ''; };
root.querySelector('.modal-close').onclick = close;
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
- const list = $('#attachment-list');
+ const list = selectAttachmentUi('#attachment-list');
const render = () => {
- const text = $('#attachment-search').value.trim().toLowerCase();
- const type = $('#attachment-type').value;
+ const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
+ const type = selectAttachmentUi('#attachment-type').value;
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
list.replaceChildren();
@@ -147,16 +147,16 @@ async function openAttachmentsView() {
list.append(row);
});
};
- $('#attachment-search').oninput = render;
- $('#attachment-type').onchange = render;
+ selectAttachmentUi('#attachment-search').oninput = render;
+ selectAttachmentUi('#attachment-type').onchange = render;
try {
attachmentItems = await collectAttachments();
- if ($('#attachment-list')) render();
+ if (selectAttachmentUi('#attachment-list')) render();
} catch (error) {
- if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
+ if (selectAttachmentUi('#attachment-list')) selectAttachmentUi('#attachment-list').textContent = error.message || 'Could not load attachments.';
}
}
document.addEventListener('DOMContentLoaded', () => {
- $('#attachments-nav')?.addEventListener('click', openAttachmentsView);
+ selectAttachmentUi('#attachments-nav')?.addEventListener('click', openAttachmentsView);
});
diff --git a/mail-ui.js b/mail-ui.js
index 7e401bb..c3f342f 100644
--- a/mail-ui.js
+++ b/mail-ui.js
@@ -803,6 +803,8 @@ const mailUiApi = window.epMailUiModules.createMailUiApi({
select: $,
selectAll: $$,
toast,
+ escapeHtml: esc,
+ getApplyTheme: () => applyTheme,
setRenderList: renderer => { renderList = renderer; },
setOpenMessage: renderer => { openMessage = renderer; },
setShowCompose: renderer => { showCompose = renderer; }
diff --git a/package-lock.json b/package-lock.json
index 8648f13..187d0c1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "ep-mail",
- "version": "0.4.17",
+ "version": "0.4.18",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ep-mail",
- "version": "0.4.17",
+ "version": "0.4.18",
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
diff --git a/package.json b/package.json
index f0a5fee..703a8af 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "ep-mail",
- "version": "0.4.17",
+ "version": "0.4.18",
"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 65d80d7..0914207 100644
--- a/pgp-mail-ui.js
+++ b/pgp-mail-ui.js
@@ -1,8 +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 pgpMailUi = window.epMailFeatures.mail;
+const selectPgpMailUi = pgpMailUi.select;
+const selectAllPgpMailUi = pgpMailUi.selectAll;
+const toastPgpMailUi = pgpMailUi.toast;
const pgpApi = () => window.daybreakMail?.pgp;
function pgpAskPassphrase(title, detail) {
@@ -56,14 +56,14 @@ async function pgpAddAttachedKey(key) {
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
try {
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
- toast(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
+ toastPgpMailUi(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
} catch (error) {
- toast(error.message || 'Could not add the key');
+ toastPgpMailUi(error.message || 'Could not add the key');
}
}
function pgpRenderReaderState(message) {
- const reader = $('#reader-pane');
+ const reader = selectPgpMailUi('#reader-pane');
const header = reader.querySelector('.reader-header');
if (!header) return;
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
@@ -80,7 +80,7 @@ function pgpRenderReaderState(message) {
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
});
- const unlock = $('#pgp-unlock');
+ const unlock = selectPgpMailUi('#pgp-unlock');
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
}
@@ -91,7 +91,7 @@ async function pgpUnlockMessage(message, interactive) {
try {
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
} catch (error) {
- toast(error.message || 'Could not open this message');
+ toastPgpMailUi(error.message || 'Could not open this message');
return;
}
if (result.ok) {
@@ -99,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 (mailUi.state.activeMessage === message.id) mailUi.openMessage(message.id);
+ if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
return;
}
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
@@ -108,16 +108,16 @@ async function pgpUnlockMessage(message, interactive) {
if (passphrase === null) return;
continue;
}
- const text = $('#pgp-banner-text');
+ const text = selectPgpMailUi('#pgp-banner-text');
if (text) text.textContent = result.message;
- else toast(result.message);
+ else toastPgpMailUi(result.message);
return;
}
}
-mailUi.wrapOpenMessage(baseOpenMessage => function (id) {
+pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
baseOpenMessage(id);
- const message = mailUi.state.messages.find(item => item.id === id);
+ const message = pgpMailUi.state.messages.find(item => item.id === id);
if (!message || !pgpApi()) return;
pgpRenderReaderState(message);
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
@@ -127,30 +127,30 @@ mailUi.wrapOpenMessage(baseOpenMessage => function (id) {
});
// Compose: encrypt/sign options.
-mailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
+pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
baseShowCompose(reply, forward);
- const footer = $('#modal-root .compose-footer');
+ const footer = selectPgpMailUi('#modal-root .compose-footer');
if (!footer || !pgpApi()) return;
const box = document.createElement('div');
box.className = 'pgp-compose';
box.innerHTML = ``;
footer.prepend(box);
let touched = false;
- const encrypt = $('#pgp-encrypt');
- const sign = $('#pgp-sign');
+ const encrypt = selectPgpMailUi('#pgp-encrypt');
+ const sign = selectPgpMailUi('#pgp-sign');
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
if (touched) encrypt.dataset.touched = '1';
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
let timer = null;
const refresh = async () => {
- const to = $('#compose-to')?.value || '';
- const cc = $('#compose-cc')?.value || '';
- const hint = $('#pgp-hint');
+ const to = selectPgpMailUi('#compose-to')?.value || '';
+ const cc = selectPgpMailUi('#compose-cc')?.value || '';
+ const hint = selectPgpMailUi('#pgp-hint');
if (!hint) return;
if (!to.trim()) { hint.textContent = ''; return; }
try {
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
- if (!$('#pgp-hint')) return;
+ if (!selectPgpMailUi('#pgp-hint')) return;
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
else {
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
@@ -159,7 +159,7 @@ mailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
} catch { hint.textContent = ''; }
};
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
- ['#compose-to', '#compose-cc'].forEach(selector => $(selector)?.addEventListener('input', schedule));
+ ['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule));
sign.addEventListener('change', schedule);
schedule();
});
@@ -167,12 +167,12 @@ mailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
async function prepareSend(to, cc) {
if (!pgpApi()) return null;
- let encrypt = Boolean($('#pgp-encrypt')?.checked);
- const sign = Boolean($('#pgp-sign')?.checked);
- if (!encrypt && !sign && $('#pgp-encrypt')?.dataset.touched === '1') return null;
+ let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
+ const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
+ if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
const status = await pgpApi().checkSend({ to, cc, sign });
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
- if (!encrypt && !status.missing.length && status.recipients.length && $('#pgp-encrypt')?.dataset.touched !== '1') {
+ if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
if (!sign) return null;
} else return false;
@@ -186,7 +186,7 @@ async function prepareSend(to, cc) {
}
let passphrase = null;
if (sign) {
- if (!status.signer) { toast('Create or import an encryption key for your address before signing'); return false; }
+ if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
if (!status.signer.unlocked) {
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
if (passphrase === null) return false;
diff --git a/productivity.js b/productivity.js
index 0512f8c..1f88e2c 100644
--- a/productivity.js
+++ b/productivity.js
@@ -1,4 +1,9 @@
// Persistent profile, calendar and contact tools, plus actions for the mail UI.
+const productivityMailUi = window.epMailFeatures.mail;
+const selectProductivityUi = productivityMailUi.select;
+const selectAllProductivityUi = productivityMailUi.selectAll;
+const toastProductivityUi = productivityMailUi.toast;
+const escapeProductivityUi = productivityMailUi.escapeHtml;
const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' };
const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } };
const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value));
@@ -11,39 +16,65 @@ productWrite(productKeys.contacts, savedContacts);
let savedEvents = productRead(productKeys.events, []);
let customLabels = productRead(productKeys.labels, []);
let snoozedIds = productRead(productKeys.snoozed, []);
-function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); }
+function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=selectProductivityUi('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=selectProductivityUi('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (productivityMailUi.connectedAccount) productivityMailUi.updateAccountCard(productivityMailUi.connectedAccount); }
function openAccountSettings() {
- const root=$('#modal-root');
- root.innerHTML=`
Account Settings
This name appears in your greeting. Set sender display names separately for each mailbox.
`;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()}
-function renderContacts(){const cards=savedContacts.map((c,i)=>`
${esc(c.initials)}
${esc(c.name)}${esc(c.email)}${esc(c.note)}
`).join('');$('#contacts-view').innerHTML=`
THE PEOPLE WHO MAKE LIFE FULLER
Your people
${savedContacts.length} contacts, all in one place.
⌕
${cards||'
No contacts yet. Add someone to get started.
'}
`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}}
-function accountRuleLabels(){return [...new Set((connectedMailAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
-function renderLabels(){const box=$('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>``).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})}
-function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')}
-function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toast('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
-async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}}
-document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh†to sync, or “account†to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='
ep-mail help
Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.
';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';});
-function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()}
-const baseMessageRenderer=renderList;
-renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='
';return}baseMessageRenderer()};
-document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true);
+function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=`
${savedContacts.length} contacts, all in one place.
⌕
${cards||'
No contacts yet. Add someone to get started.
'}
`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}}
+function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
+function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>``).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})}
+function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){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='
ep-mail help
Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.
';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 ↓';});
+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;
+ if (state.activeFolder === 'Drafts') {
+ selectProductivityUi('#message-list').innerHTML = '