Refractoring Stage 6.6 Migrated productivity.js and shortcuts.js mail-state access and render/preferences hooks to the mail feature API.
This commit is contained in:
+6
-4
@@ -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.
|
||||
|
||||
+5
-5
@@ -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')}
|
||||
}
|
||||
|
||||
+21
-21
@@ -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 = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`;
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -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; }
|
||||
|
||||
Generated
+2
-2
@@ -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",
|
||||
|
||||
+1
-1
@@ -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",
|
||||
|
||||
+28
-28
@@ -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 = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label><small id="pgp-hint"></small>`;
|
||||
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;
|
||||
|
||||
+57
-26
@@ -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=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
||||
const root=selectProductivityUi('#modal-root');
|
||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${escapeProductivityUi(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
||||
const close=()=>root.innerHTML='';
|
||||
$$('.modal-close').forEach(button=>button.onclick=close);
|
||||
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||
$('#save-profile').onclick=()=>{const name=$('#profile-name').value.trim();if(!name){toast('Enter your display name');return}setProfileName(name);close();toast('Account settings saved')};
|
||||
$('#profile-name').focus();
|
||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||
selectProductivityUi('#save-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')};
|
||||
selectProductivityUi('#profile-name').focus();
|
||||
}
|
||||
function openPreferences() {
|
||||
const root=$('#modal-root');
|
||||
const root=selectProductivityUi('#modal-root');
|
||||
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
||||
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
||||
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save appearance</button></div></div></div>`;
|
||||
const close=()=>root.innerHTML='';
|
||||
$$('.modal-close').forEach(button=>button.onclick=close);
|
||||
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||
$('#save-appearance').onclick=()=>{applyTheme($('#theme-select').value);close();toast('Appearance saved')};
|
||||
$('#theme-select').focus();
|
||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||
selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Appearance saved')};
|
||||
selectProductivityUi('#theme-select').focus();
|
||||
}
|
||||
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${esc(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${esc(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${esc(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${esc(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${esc(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=async()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toast('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); }
|
||||
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
||||
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${esc(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${esc(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${esc(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()}
|
||||
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}}
|
||||
function 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=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})}
|
||||
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')}
|
||||
function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder: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='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';});
|
||||
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()}
|
||||
const baseMessageRenderer=renderList;
|
||||
renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels,...accountRuleLabels()].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?Boolean(m.snoozedUntil):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';return}baseMessageRenderer()};
|
||||
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true);
|
||||
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=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${escapeProductivityUi(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${escapeProductivityUi(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${escapeProductivityUi(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${escapeProductivityUi(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${escapeProductivityUi(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); }
|
||||
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);selectProductivityUi('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${escapeProductivityUi(e.title)}</strong><small>${escapeProductivityUi(e.time||'All day')}${e.with?` · with ${escapeProductivityUi(e.with)}`:''}${e.place?` · ${escapeProductivityUi(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;selectProductivityUi('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));selectProductivityUi('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};selectProductivityUi('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};selectProductivityUi('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};selectProductivityUi('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
||||
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=selectProductivityUi('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${escapeProductivityUi(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${escapeProductivityUi(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${escapeProductivityUi(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#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){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()}
|
||||
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${escapeProductivityUi(c.color)}">${escapeProductivityUi(c.initials)}</div><div><strong>${escapeProductivityUi(c.name)}</strong><span>${escapeProductivityUi(c.email)}</span><small>${escapeProductivityUi(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${escapeProductivityUi(c.name)}">···</button><button class="contact-email" data-email="${escapeProductivityUi(c.email)}" aria-label="Email ${escapeProductivityUi(c.name)}">↗</button></article>`).join('');selectProductivityUi('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;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=>`<button class="label-link" data-label="${escapeProductivityUi(label)}"><i class="label-dot dot-blue"></i>${escapeProductivityUi(label)}</button>`).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='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';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 = '<div class="reader-empty"><div><div class="empty-icon">?</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
|
||||
selectProductivityUi('#start-draft').onclick = () => productivityMailUi.showCompose();
|
||||
selectProductivityUi('#reader-pane').innerHTML = productivityMailUi.emptyReader();
|
||||
return;
|
||||
}
|
||||
if (state.activeFolder === 'Snoozed' || ['Design', 'Travel', 'Personal', ...customLabels, ...accountRuleLabels()].includes(state.activeFolder)) {
|
||||
const folder = state.activeFolder;
|
||||
const original = state.messages.slice();
|
||||
const keep = state.messages.filter(message => folder === 'Snoozed' ? Boolean(message.snoozedUntil) : (message.tags || []).includes(folder));
|
||||
state.messages.splice(0, state.messages.length, ...keep);
|
||||
state.activeFolder = 'Inbox';
|
||||
baseMessageRenderer();
|
||||
state.activeFolder = folder;
|
||||
state.messages.splice(0, state.messages.length, ...original);
|
||||
if (!keep.length) selectProductivityUi('#message-list').innerHTML = '<div class="reader-empty"><div><div class="empty-icon">?</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';
|
||||
return;
|
||||
}
|
||||
return baseMessageRenderer();
|
||||
});
|
||||
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toastProductivityUi('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:productivityMailUi.state.activeFolder,filename}).then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true);
|
||||
|
||||
window.epMailFeatures.productivity = Object.freeze({
|
||||
wrapOpenPreferences(decorator) {
|
||||
openPreferences = decorator(openPreferences);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
select,
|
||||
selectAll,
|
||||
toast,
|
||||
escapeHtml,
|
||||
getApplyTheme,
|
||||
setRenderList,
|
||||
setOpenMessage,
|
||||
setShowCompose
|
||||
@@ -35,6 +37,8 @@
|
||||
select,
|
||||
selectAll,
|
||||
toast,
|
||||
escapeHtml,
|
||||
get applyTheme() { return getApplyTheme(); },
|
||||
wrapRenderList(decorator) { setRenderList(decorator(getRenderList())); },
|
||||
wrapOpenMessage(decorator) { setOpenMessage(decorator(getOpenMessage())); },
|
||||
wrapShowCompose(decorator) { setShowCompose(decorator(getShowCompose())); }
|
||||
|
||||
+24
-21
@@ -1,14 +1,19 @@
|
||||
// Configurable keyboard shortcuts for common mail actions.
|
||||
const shortcutMailUi = window.epMailFeatures.mail;
|
||||
const shortcutProductivityUi = window.epMailFeatures.productivity;
|
||||
const selectShortcutUi = shortcutMailUi.select;
|
||||
const toastShortcutUi = shortcutMailUi.toast;
|
||||
const escapeShortcutUi = shortcutMailUi.escapeHtml;
|
||||
const shortcutStorageKey = 'daybreak-shortcuts';
|
||||
const shortcutActions = [
|
||||
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() },
|
||||
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() },
|
||||
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() },
|
||||
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() },
|
||||
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() },
|
||||
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() },
|
||||
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() },
|
||||
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() },
|
||||
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => selectShortcutUi('#compose')?.click() },
|
||||
{ id: 'search', label: 'Search', fallback: '/', run: () => selectShortcutUi('#search')?.focus() },
|
||||
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => selectShortcutUi('#refresh')?.click() },
|
||||
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => selectShortcutUi('#reader-archive')?.click() },
|
||||
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => selectShortcutUi('#reader-delete')?.click() },
|
||||
{ id: 'star', label: 'Star message', fallback: 's', run: () => selectShortcutUi('#reader-star')?.click() },
|
||||
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => selectShortcutUi('#reply')?.click() },
|
||||
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => selectShortcutUi('#forward')?.click() },
|
||||
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
|
||||
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
|
||||
];
|
||||
@@ -39,16 +44,17 @@ function eventShortcut(event) {
|
||||
}
|
||||
|
||||
function moveMessageSelection(step) {
|
||||
const messages = shortcutMailUi.state.messages;
|
||||
if (!messages.length) return;
|
||||
const index = messages.findIndex(message => message.id === activeMessage);
|
||||
const index = messages.findIndex(message => message.id === shortcutMailUi.state.activeMessage);
|
||||
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
|
||||
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
|
||||
if (next) { shortcutMailUi.openMessage(next.id); selectShortcutUi(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
|
||||
const target = event.target;
|
||||
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return;
|
||||
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || selectShortcutUi('#modal-root')?.children.length) return;
|
||||
const pressed = eventShortcut(event);
|
||||
if (!pressed) return;
|
||||
const shortcuts = loadShortcuts();
|
||||
@@ -58,18 +64,16 @@ document.addEventListener('keydown', event => {
|
||||
action.run();
|
||||
});
|
||||
|
||||
if (typeof openPreferences === 'function') {
|
||||
const baseOpenPreferences = openPreferences;
|
||||
openPreferences = function () {
|
||||
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
|
||||
baseOpenPreferences();
|
||||
const fields = $('#modal-root .compose-fields');
|
||||
const save = $('#save-appearance');
|
||||
const fields = selectShortcutUi('#modal-root .compose-fields');
|
||||
const save = selectShortcutUi('#save-appearance');
|
||||
if (!fields || !save) return;
|
||||
const shortcuts = loadShortcuts();
|
||||
const section = document.createElement('div');
|
||||
section.className = 'shortcut-settings';
|
||||
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
||||
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
||||
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${escapeShortcutUi(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
||||
fields.append(section);
|
||||
section.addEventListener('keydown', event => {
|
||||
const input = event.target.closest('.shortcut-input');
|
||||
@@ -79,7 +83,7 @@ if (typeof openPreferences === 'function') {
|
||||
const combo = eventShortcut(event);
|
||||
if (combo) input.value = combo;
|
||||
});
|
||||
$('#reset-shortcuts').onclick = () => {
|
||||
selectShortcutUi('#reset-shortcuts').onclick = () => {
|
||||
section.querySelectorAll('.shortcut-input').forEach(input => {
|
||||
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
||||
});
|
||||
@@ -91,12 +95,11 @@ if (typeof openPreferences === 'function') {
|
||||
for (const input of section.querySelectorAll('.shortcut-input')) {
|
||||
const value = normalizeShortcut(input.value);
|
||||
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
||||
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
||||
if (value && used.has(value)) { toastShortcutUi(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
||||
if (value) used.set(value, label);
|
||||
values[input.dataset.action] = value;
|
||||
}
|
||||
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
||||
baseSave?.call(save, event);
|
||||
};
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
+42
-42
@@ -1,4 +1,4 @@
|
||||
const mailUi = window.epMailFeatures.mail;
|
||||
const snoozeMailUi = window.epMailFeatures.mail;
|
||||
|
||||
function localDateTimeValue(date) {
|
||||
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
|
||||
@@ -14,12 +14,12 @@ function nextMorning(daysAhead) {
|
||||
}
|
||||
|
||||
function openSnoozeDialog(items) {
|
||||
const eligible = items.filter(message => message?.uid && mailUi.connectedAccount);
|
||||
const eligible = items.filter(message => message?.uid && snoozeMailUi.connectedAccount);
|
||||
if (!eligible.length) {
|
||||
mailUi.toast('Snoozing is available for messages in a connected mailbox.');
|
||||
snoozeMailUi.toast('Snoozing is available for messages in a connected mailbox.');
|
||||
return;
|
||||
}
|
||||
const root = mailUi.select('#modal-root');
|
||||
const root = snoozeMailUi.select('#modal-root');
|
||||
const tomorrow = nextMorning(1);
|
||||
const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000);
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</button></div></div></div>`;
|
||||
@@ -31,7 +31,7 @@ function openSnoozeDialog(items) {
|
||||
|
||||
const schedule = async dueAt => {
|
||||
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
|
||||
mailUi.select('#snooze-status').textContent = 'Choose a reminder time in the future.';
|
||||
snoozeMailUi.select('#snooze-status').textContent = 'Choose a reminder time in the future.';
|
||||
return;
|
||||
}
|
||||
const buttons = [...root.querySelectorAll('button')];
|
||||
@@ -39,7 +39,7 @@ function openSnoozeDialog(items) {
|
||||
try {
|
||||
for (const message of eligible) {
|
||||
const sourceFolder = message.sourceFolder ||
|
||||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(mailUi.state.activeFolder) ? mailUi.state.activeFolder : 'Inbox');
|
||||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(snoozeMailUi.state.activeFolder) ? snoozeMailUi.state.activeFolder : 'Inbox');
|
||||
await window.daybreakMail.setSnooze({
|
||||
uid: message.uid,
|
||||
folder: sourceFolder,
|
||||
@@ -49,11 +49,11 @@ function openSnoozeDialog(items) {
|
||||
});
|
||||
}
|
||||
close();
|
||||
mailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
||||
mailUi.state.selectedIds.clear();
|
||||
await mailUi.syncMailbox(false, { offset: 0 });
|
||||
snoozeMailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
||||
snoozeMailUi.state.selectedIds.clear();
|
||||
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||
} catch (error) {
|
||||
mailUi.select('#snooze-status').textContent = error.message || 'Could not set the reminder.';
|
||||
snoozeMailUi.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));
|
||||
});
|
||||
mailUi.select('#snooze-custom').onclick = () => schedule(new Date(mailUi.select('#snooze-custom-time').value).getTime());
|
||||
mailUi.select('#snooze-custom-time').focus();
|
||||
snoozeMailUi.select('#snooze-custom').onclick = () => schedule(new Date(snoozeMailUi.select('#snooze-custom-time').value).getTime());
|
||||
snoozeMailUi.select('#snooze-custom-time').focus();
|
||||
}
|
||||
|
||||
function unsnoozeMessage(message) {
|
||||
@@ -72,13 +72,13 @@ function unsnoozeMessage(message) {
|
||||
sourceFolder,
|
||||
dueAt: null
|
||||
}).then(async () => {
|
||||
mailUi.toast('Message returned to its mailbox');
|
||||
await mailUi.syncMailbox(false, { offset: 0 });
|
||||
}).catch(error => mailUi.toast(error.message || 'Could not return the message'));
|
||||
snoozeMailUi.toast('Message returned to its mailbox');
|
||||
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||
}).catch(error => snoozeMailUi.toast(error.message || 'Could not return the message'));
|
||||
}
|
||||
|
||||
function showMessageActions(message) {
|
||||
const root = mailUi.select('#modal-root');
|
||||
const root = snoozeMailUi.select('#modal-root');
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`;
|
||||
root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; });
|
||||
root.querySelector('.modal-overlay').onclick = event => {
|
||||
@@ -86,24 +86,24 @@ function showMessageActions(message) {
|
||||
};
|
||||
}
|
||||
|
||||
mailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
||||
if (mailUi.state.activeFolder === 'Snoozed') {
|
||||
const originalMessages = mailUi.state.messages.slice();
|
||||
const snoozedMessages = mailUi.state.messages.filter(message => message.snoozedUntil);
|
||||
mailUi.state.messages.splice(0, mailUi.state.messages.length, ...snoozedMessages);
|
||||
snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
||||
if (snoozeMailUi.state.activeFolder === 'Snoozed') {
|
||||
const originalMessages = snoozeMailUi.state.messages.slice();
|
||||
const snoozedMessages = snoozeMailUi.state.messages.filter(message => message.snoozedUntil);
|
||||
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...snoozedMessages);
|
||||
const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]);
|
||||
snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; });
|
||||
const folder = mailUi.state.activeFolder;
|
||||
mailUi.state.activeFolder = 'Inbox';
|
||||
mailUi.baseRenderList();
|
||||
mailUi.state.activeFolder = folder;
|
||||
const folder = snoozeMailUi.state.activeFolder;
|
||||
snoozeMailUi.state.activeFolder = 'Inbox';
|
||||
snoozeMailUi.baseRenderList();
|
||||
snoozeMailUi.state.activeFolder = folder;
|
||||
originalFlags.forEach(([message, archived, deleted]) => {
|
||||
message.archived = archived;
|
||||
message.deleted = deleted;
|
||||
});
|
||||
mailUi.state.messages.splice(0, mailUi.state.messages.length, ...originalMessages);
|
||||
for (const row of mailUi.selectAll('.message')) {
|
||||
const message = mailUi.state.messages.find(item => item.id === Number(row.dataset.id));
|
||||
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...originalMessages);
|
||||
for (const row of snoozeMailUi.selectAll('.message')) {
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === Number(row.dataset.id));
|
||||
if (!message?.snoozedUntil) continue;
|
||||
const due = new Date(message.snoozedUntil);
|
||||
row.title = `Reminder ${due.toLocaleString()}`;
|
||||
@@ -115,17 +115,17 @@ mailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
||||
return renderListBeforeSnooze();
|
||||
});
|
||||
|
||||
mailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) {
|
||||
snoozeMailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) {
|
||||
openMessageBeforeSnooze(id);
|
||||
const message = mailUi.state.messages.find(item => item.id === id);
|
||||
const tools = mailUi.select('.reader-tools');
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === id);
|
||||
const tools = snoozeMailUi.select('.reader-tools');
|
||||
if (!message || !tools) return;
|
||||
const snoozed = mailUi.state.activeFolder === 'Snoozed';
|
||||
const snoozed = snoozeMailUi.state.activeFolder === 'Snoozed';
|
||||
tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`);
|
||||
});
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
mailUi.select('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
|
||||
snoozeMailUi.select('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
|
||||
if (window.daybreakMail?.checkSnoozeReminders) {
|
||||
const checkReminders = () => window.daybreakMail.checkSnoozeReminders()
|
||||
.catch(error => console.error('Could not check mail reminders:', error));
|
||||
@@ -143,8 +143,8 @@ document.addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (action) {
|
||||
const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage);
|
||||
mailUi.select('#modal-root').innerHTML = '';
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||
snoozeMailUi.select('#modal-root').innerHTML = '';
|
||||
if (!message) return;
|
||||
if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]);
|
||||
else if (action.dataset.messageAction === 'label') addMessageLabel(message);
|
||||
@@ -153,26 +153,26 @@ document.addEventListener('click', event => {
|
||||
messageAction(message, type).then(() => {
|
||||
if (type === 'unread') message.unread = true;
|
||||
if (type === 'inbox') message.archived = false;
|
||||
mailUi.renderList();
|
||||
mailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
||||
}).catch(error => mailUi.toast(error.message || 'Could not update the message'));
|
||||
snoozeMailUi.renderList();
|
||||
snoozeMailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
||||
}).catch(error => snoozeMailUi.toast(error.message || 'Could not update the message'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (unsnooze) {
|
||||
const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage);
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||
if (message) unsnoozeMessage(message);
|
||||
return;
|
||||
}
|
||||
if (snooze?.id === 'snooze-selected') {
|
||||
openSnoozeDialog(mailUi.state.messages.filter(message => mailUi.state.selectedIds.has(message.id)));
|
||||
openSnoozeDialog(snoozeMailUi.state.messages.filter(message => snoozeMailUi.state.selectedIds.has(message.id)));
|
||||
return;
|
||||
}
|
||||
if (more) {
|
||||
const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage);
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||
if (message) showMessageActions(message);
|
||||
return;
|
||||
}
|
||||
const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage);
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||
if (message) openSnoozeDialog([message]);
|
||||
}, true);
|
||||
|
||||
@@ -2,6 +2,7 @@ const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const read = file => fs.readFileSync(path.join(root, file), 'utf8');
|
||||
@@ -27,3 +28,10 @@ test('desktop, Android web generation, and offline cache include renderer suppor
|
||||
assert.ok(worker.includes(`'./${file}'`), `service worker is missing ${file}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('classic renderer scripts have no duplicate global lexical declarations', () => {
|
||||
const html = read('index.html');
|
||||
const scripts = [...html.matchAll(/<script src="([^"]+)"/g)].map(match => match[1]);
|
||||
const source = scripts.map(script => read(script)).join('\n');
|
||||
assert.doesNotThrow(() => new vm.Script(source, { filename: 'renderer-classic-scripts.js' }));
|
||||
});
|
||||
|
||||
@@ -62,12 +62,18 @@ test('account and snooze UI consume the explicit mail API instead of selected le
|
||||
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');
|
||||
const shortcutsUi = fs.readFileSync(path.join(root, 'shortcuts.js'), 'utf8');
|
||||
const productivityUi = fs.readFileSync(path.join(root, 'productivity.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.match(shortcutsUi, /window\.epMailFeatures\.mail/);
|
||||
assert.match(shortcutsUi, /window\.epMailFeatures\.productivity/);
|
||||
assert.doesNotMatch(accountUi, /\bconnectedMailAccount\b|\bmailPageOffset\b|(?<!\.)\bsyncMailbox\s*\(/);
|
||||
assert.doesNotMatch(snoozeUi, /\bconnectedMailAccount\b|(?<!\.)\bactiveFolder\b|(?<!\.)\bselectedIds\b|(?<!\.)\bsyncMailbox\s*\(/);
|
||||
assert.doesNotMatch(attachmentUi, /\bconnectedMailAccount\b|(?<!\.)\bactiveFolder\b|(?<!\.)\bmessages\.find/);
|
||||
assert.doesNotMatch(pgpMailUi, /(?<!\.)\bmessages\.find|(?<!\.)\bactiveMessage\b|window\.pgpPrepareSend/);
|
||||
assert.match(productivityUi, /window\.epMailFeatures\.productivity/);
|
||||
assert.doesNotMatch(shortcutsUi, /(?<!\.)\bactiveMessage\b|(?<!\.)\bopenMessage\s*\(/);
|
||||
});
|
||||
|
||||
+5
-5
@@ -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')}
|
||||
}
|
||||
|
||||
+21
-21
@@ -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 = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`;
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -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; }
|
||||
|
||||
+28
-28
@@ -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 = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label><small id="pgp-hint"></small>`;
|
||||
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;
|
||||
|
||||
+57
-26
@@ -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=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
||||
const root=selectProductivityUi('#modal-root');
|
||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${escapeProductivityUi(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
||||
const close=()=>root.innerHTML='';
|
||||
$$('.modal-close').forEach(button=>button.onclick=close);
|
||||
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||
$('#save-profile').onclick=()=>{const name=$('#profile-name').value.trim();if(!name){toast('Enter your display name');return}setProfileName(name);close();toast('Account settings saved')};
|
||||
$('#profile-name').focus();
|
||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||
selectProductivityUi('#save-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')};
|
||||
selectProductivityUi('#profile-name').focus();
|
||||
}
|
||||
function openPreferences() {
|
||||
const root=$('#modal-root');
|
||||
const root=selectProductivityUi('#modal-root');
|
||||
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
||||
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
||||
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save appearance</button></div></div></div>`;
|
||||
const close=()=>root.innerHTML='';
|
||||
$$('.modal-close').forEach(button=>button.onclick=close);
|
||||
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||
$('#save-appearance').onclick=()=>{applyTheme($('#theme-select').value);close();toast('Appearance saved')};
|
||||
$('#theme-select').focus();
|
||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||
selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Appearance saved')};
|
||||
selectProductivityUi('#theme-select').focus();
|
||||
}
|
||||
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${esc(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${esc(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${esc(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${esc(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${esc(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=async()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toast('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); }
|
||||
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
||||
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${esc(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${esc(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${esc(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()}
|
||||
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}}
|
||||
function 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=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})}
|
||||
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')}
|
||||
function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder: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='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';});
|
||||
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()}
|
||||
const baseMessageRenderer=renderList;
|
||||
renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels,...accountRuleLabels()].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?Boolean(m.snoozedUntil):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';return}baseMessageRenderer()};
|
||||
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true);
|
||||
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=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${escapeProductivityUi(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${escapeProductivityUi(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${escapeProductivityUi(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${escapeProductivityUi(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${escapeProductivityUi(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); }
|
||||
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);selectProductivityUi('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${escapeProductivityUi(e.title)}</strong><small>${escapeProductivityUi(e.time||'All day')}${e.with?` · with ${escapeProductivityUi(e.with)}`:''}${e.place?` · ${escapeProductivityUi(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;selectProductivityUi('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));selectProductivityUi('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};selectProductivityUi('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};selectProductivityUi('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};selectProductivityUi('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
||||
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=selectProductivityUi('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${escapeProductivityUi(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${escapeProductivityUi(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${escapeProductivityUi(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#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){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()}
|
||||
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${escapeProductivityUi(c.color)}">${escapeProductivityUi(c.initials)}</div><div><strong>${escapeProductivityUi(c.name)}</strong><span>${escapeProductivityUi(c.email)}</span><small>${escapeProductivityUi(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${escapeProductivityUi(c.name)}">···</button><button class="contact-email" data-email="${escapeProductivityUi(c.email)}" aria-label="Email ${escapeProductivityUi(c.name)}">↗</button></article>`).join('');selectProductivityUi('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;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=>`<button class="label-link" data-label="${escapeProductivityUi(label)}"><i class="label-dot dot-blue"></i>${escapeProductivityUi(label)}</button>`).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='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';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 = '<div class="reader-empty"><div><div class="empty-icon">?</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
|
||||
selectProductivityUi('#start-draft').onclick = () => productivityMailUi.showCompose();
|
||||
selectProductivityUi('#reader-pane').innerHTML = productivityMailUi.emptyReader();
|
||||
return;
|
||||
}
|
||||
if (state.activeFolder === 'Snoozed' || ['Design', 'Travel', 'Personal', ...customLabels, ...accountRuleLabels()].includes(state.activeFolder)) {
|
||||
const folder = state.activeFolder;
|
||||
const original = state.messages.slice();
|
||||
const keep = state.messages.filter(message => folder === 'Snoozed' ? Boolean(message.snoozedUntil) : (message.tags || []).includes(folder));
|
||||
state.messages.splice(0, state.messages.length, ...keep);
|
||||
state.activeFolder = 'Inbox';
|
||||
baseMessageRenderer();
|
||||
state.activeFolder = folder;
|
||||
state.messages.splice(0, state.messages.length, ...original);
|
||||
if (!keep.length) selectProductivityUi('#message-list').innerHTML = '<div class="reader-empty"><div><div class="empty-icon">?</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';
|
||||
return;
|
||||
}
|
||||
return baseMessageRenderer();
|
||||
});
|
||||
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toastProductivityUi('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:productivityMailUi.state.activeFolder,filename}).then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true);
|
||||
|
||||
window.epMailFeatures.productivity = Object.freeze({
|
||||
wrapOpenPreferences(decorator) {
|
||||
openPreferences = decorator(openPreferences);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
select,
|
||||
selectAll,
|
||||
toast,
|
||||
escapeHtml,
|
||||
getApplyTheme,
|
||||
setRenderList,
|
||||
setOpenMessage,
|
||||
setShowCompose
|
||||
@@ -35,6 +37,8 @@
|
||||
select,
|
||||
selectAll,
|
||||
toast,
|
||||
escapeHtml,
|
||||
get applyTheme() { return getApplyTheme(); },
|
||||
wrapRenderList(decorator) { setRenderList(decorator(getRenderList())); },
|
||||
wrapOpenMessage(decorator) { setOpenMessage(decorator(getOpenMessage())); },
|
||||
wrapShowCompose(decorator) { setShowCompose(decorator(getShowCompose())); }
|
||||
|
||||
+24
-21
@@ -1,14 +1,19 @@
|
||||
// Configurable keyboard shortcuts for common mail actions.
|
||||
const shortcutMailUi = window.epMailFeatures.mail;
|
||||
const shortcutProductivityUi = window.epMailFeatures.productivity;
|
||||
const selectShortcutUi = shortcutMailUi.select;
|
||||
const toastShortcutUi = shortcutMailUi.toast;
|
||||
const escapeShortcutUi = shortcutMailUi.escapeHtml;
|
||||
const shortcutStorageKey = 'daybreak-shortcuts';
|
||||
const shortcutActions = [
|
||||
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() },
|
||||
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() },
|
||||
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() },
|
||||
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() },
|
||||
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() },
|
||||
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() },
|
||||
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() },
|
||||
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() },
|
||||
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => selectShortcutUi('#compose')?.click() },
|
||||
{ id: 'search', label: 'Search', fallback: '/', run: () => selectShortcutUi('#search')?.focus() },
|
||||
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => selectShortcutUi('#refresh')?.click() },
|
||||
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => selectShortcutUi('#reader-archive')?.click() },
|
||||
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => selectShortcutUi('#reader-delete')?.click() },
|
||||
{ id: 'star', label: 'Star message', fallback: 's', run: () => selectShortcutUi('#reader-star')?.click() },
|
||||
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => selectShortcutUi('#reply')?.click() },
|
||||
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => selectShortcutUi('#forward')?.click() },
|
||||
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
|
||||
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
|
||||
];
|
||||
@@ -39,16 +44,17 @@ function eventShortcut(event) {
|
||||
}
|
||||
|
||||
function moveMessageSelection(step) {
|
||||
const messages = shortcutMailUi.state.messages;
|
||||
if (!messages.length) return;
|
||||
const index = messages.findIndex(message => message.id === activeMessage);
|
||||
const index = messages.findIndex(message => message.id === shortcutMailUi.state.activeMessage);
|
||||
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
|
||||
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
|
||||
if (next) { shortcutMailUi.openMessage(next.id); selectShortcutUi(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
|
||||
const target = event.target;
|
||||
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return;
|
||||
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || selectShortcutUi('#modal-root')?.children.length) return;
|
||||
const pressed = eventShortcut(event);
|
||||
if (!pressed) return;
|
||||
const shortcuts = loadShortcuts();
|
||||
@@ -58,18 +64,16 @@ document.addEventListener('keydown', event => {
|
||||
action.run();
|
||||
});
|
||||
|
||||
if (typeof openPreferences === 'function') {
|
||||
const baseOpenPreferences = openPreferences;
|
||||
openPreferences = function () {
|
||||
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
|
||||
baseOpenPreferences();
|
||||
const fields = $('#modal-root .compose-fields');
|
||||
const save = $('#save-appearance');
|
||||
const fields = selectShortcutUi('#modal-root .compose-fields');
|
||||
const save = selectShortcutUi('#save-appearance');
|
||||
if (!fields || !save) return;
|
||||
const shortcuts = loadShortcuts();
|
||||
const section = document.createElement('div');
|
||||
section.className = 'shortcut-settings';
|
||||
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
||||
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
||||
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${escapeShortcutUi(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
||||
fields.append(section);
|
||||
section.addEventListener('keydown', event => {
|
||||
const input = event.target.closest('.shortcut-input');
|
||||
@@ -79,7 +83,7 @@ if (typeof openPreferences === 'function') {
|
||||
const combo = eventShortcut(event);
|
||||
if (combo) input.value = combo;
|
||||
});
|
||||
$('#reset-shortcuts').onclick = () => {
|
||||
selectShortcutUi('#reset-shortcuts').onclick = () => {
|
||||
section.querySelectorAll('.shortcut-input').forEach(input => {
|
||||
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
||||
});
|
||||
@@ -91,12 +95,11 @@ if (typeof openPreferences === 'function') {
|
||||
for (const input of section.querySelectorAll('.shortcut-input')) {
|
||||
const value = normalizeShortcut(input.value);
|
||||
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
||||
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
||||
if (value && used.has(value)) { toastShortcutUi(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
||||
if (value) used.set(value, label);
|
||||
values[input.dataset.action] = value;
|
||||
}
|
||||
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
||||
baseSave?.call(save, event);
|
||||
};
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
+42
-42
@@ -1,4 +1,4 @@
|
||||
const mailUi = window.epMailFeatures.mail;
|
||||
const snoozeMailUi = window.epMailFeatures.mail;
|
||||
|
||||
function localDateTimeValue(date) {
|
||||
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
|
||||
@@ -14,12 +14,12 @@ function nextMorning(daysAhead) {
|
||||
}
|
||||
|
||||
function openSnoozeDialog(items) {
|
||||
const eligible = items.filter(message => message?.uid && mailUi.connectedAccount);
|
||||
const eligible = items.filter(message => message?.uid && snoozeMailUi.connectedAccount);
|
||||
if (!eligible.length) {
|
||||
mailUi.toast('Snoozing is available for messages in a connected mailbox.');
|
||||
snoozeMailUi.toast('Snoozing is available for messages in a connected mailbox.');
|
||||
return;
|
||||
}
|
||||
const root = mailUi.select('#modal-root');
|
||||
const root = snoozeMailUi.select('#modal-root');
|
||||
const tomorrow = nextMorning(1);
|
||||
const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000);
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</button></div></div></div>`;
|
||||
@@ -31,7 +31,7 @@ function openSnoozeDialog(items) {
|
||||
|
||||
const schedule = async dueAt => {
|
||||
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
|
||||
mailUi.select('#snooze-status').textContent = 'Choose a reminder time in the future.';
|
||||
snoozeMailUi.select('#snooze-status').textContent = 'Choose a reminder time in the future.';
|
||||
return;
|
||||
}
|
||||
const buttons = [...root.querySelectorAll('button')];
|
||||
@@ -39,7 +39,7 @@ function openSnoozeDialog(items) {
|
||||
try {
|
||||
for (const message of eligible) {
|
||||
const sourceFolder = message.sourceFolder ||
|
||||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(mailUi.state.activeFolder) ? mailUi.state.activeFolder : 'Inbox');
|
||||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(snoozeMailUi.state.activeFolder) ? snoozeMailUi.state.activeFolder : 'Inbox');
|
||||
await window.daybreakMail.setSnooze({
|
||||
uid: message.uid,
|
||||
folder: sourceFolder,
|
||||
@@ -49,11 +49,11 @@ function openSnoozeDialog(items) {
|
||||
});
|
||||
}
|
||||
close();
|
||||
mailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
||||
mailUi.state.selectedIds.clear();
|
||||
await mailUi.syncMailbox(false, { offset: 0 });
|
||||
snoozeMailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
||||
snoozeMailUi.state.selectedIds.clear();
|
||||
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||
} catch (error) {
|
||||
mailUi.select('#snooze-status').textContent = error.message || 'Could not set the reminder.';
|
||||
snoozeMailUi.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));
|
||||
});
|
||||
mailUi.select('#snooze-custom').onclick = () => schedule(new Date(mailUi.select('#snooze-custom-time').value).getTime());
|
||||
mailUi.select('#snooze-custom-time').focus();
|
||||
snoozeMailUi.select('#snooze-custom').onclick = () => schedule(new Date(snoozeMailUi.select('#snooze-custom-time').value).getTime());
|
||||
snoozeMailUi.select('#snooze-custom-time').focus();
|
||||
}
|
||||
|
||||
function unsnoozeMessage(message) {
|
||||
@@ -72,13 +72,13 @@ function unsnoozeMessage(message) {
|
||||
sourceFolder,
|
||||
dueAt: null
|
||||
}).then(async () => {
|
||||
mailUi.toast('Message returned to its mailbox');
|
||||
await mailUi.syncMailbox(false, { offset: 0 });
|
||||
}).catch(error => mailUi.toast(error.message || 'Could not return the message'));
|
||||
snoozeMailUi.toast('Message returned to its mailbox');
|
||||
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||
}).catch(error => snoozeMailUi.toast(error.message || 'Could not return the message'));
|
||||
}
|
||||
|
||||
function showMessageActions(message) {
|
||||
const root = mailUi.select('#modal-root');
|
||||
const root = snoozeMailUi.select('#modal-root');
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`;
|
||||
root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; });
|
||||
root.querySelector('.modal-overlay').onclick = event => {
|
||||
@@ -86,24 +86,24 @@ function showMessageActions(message) {
|
||||
};
|
||||
}
|
||||
|
||||
mailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
||||
if (mailUi.state.activeFolder === 'Snoozed') {
|
||||
const originalMessages = mailUi.state.messages.slice();
|
||||
const snoozedMessages = mailUi.state.messages.filter(message => message.snoozedUntil);
|
||||
mailUi.state.messages.splice(0, mailUi.state.messages.length, ...snoozedMessages);
|
||||
snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
||||
if (snoozeMailUi.state.activeFolder === 'Snoozed') {
|
||||
const originalMessages = snoozeMailUi.state.messages.slice();
|
||||
const snoozedMessages = snoozeMailUi.state.messages.filter(message => message.snoozedUntil);
|
||||
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...snoozedMessages);
|
||||
const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]);
|
||||
snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; });
|
||||
const folder = mailUi.state.activeFolder;
|
||||
mailUi.state.activeFolder = 'Inbox';
|
||||
mailUi.baseRenderList();
|
||||
mailUi.state.activeFolder = folder;
|
||||
const folder = snoozeMailUi.state.activeFolder;
|
||||
snoozeMailUi.state.activeFolder = 'Inbox';
|
||||
snoozeMailUi.baseRenderList();
|
||||
snoozeMailUi.state.activeFolder = folder;
|
||||
originalFlags.forEach(([message, archived, deleted]) => {
|
||||
message.archived = archived;
|
||||
message.deleted = deleted;
|
||||
});
|
||||
mailUi.state.messages.splice(0, mailUi.state.messages.length, ...originalMessages);
|
||||
for (const row of mailUi.selectAll('.message')) {
|
||||
const message = mailUi.state.messages.find(item => item.id === Number(row.dataset.id));
|
||||
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...originalMessages);
|
||||
for (const row of snoozeMailUi.selectAll('.message')) {
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === Number(row.dataset.id));
|
||||
if (!message?.snoozedUntil) continue;
|
||||
const due = new Date(message.snoozedUntil);
|
||||
row.title = `Reminder ${due.toLocaleString()}`;
|
||||
@@ -115,17 +115,17 @@ mailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
||||
return renderListBeforeSnooze();
|
||||
});
|
||||
|
||||
mailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) {
|
||||
snoozeMailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) {
|
||||
openMessageBeforeSnooze(id);
|
||||
const message = mailUi.state.messages.find(item => item.id === id);
|
||||
const tools = mailUi.select('.reader-tools');
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === id);
|
||||
const tools = snoozeMailUi.select('.reader-tools');
|
||||
if (!message || !tools) return;
|
||||
const snoozed = mailUi.state.activeFolder === 'Snoozed';
|
||||
const snoozed = snoozeMailUi.state.activeFolder === 'Snoozed';
|
||||
tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`);
|
||||
});
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
mailUi.select('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
|
||||
snoozeMailUi.select('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
|
||||
if (window.daybreakMail?.checkSnoozeReminders) {
|
||||
const checkReminders = () => window.daybreakMail.checkSnoozeReminders()
|
||||
.catch(error => console.error('Could not check mail reminders:', error));
|
||||
@@ -143,8 +143,8 @@ document.addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (action) {
|
||||
const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage);
|
||||
mailUi.select('#modal-root').innerHTML = '';
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||
snoozeMailUi.select('#modal-root').innerHTML = '';
|
||||
if (!message) return;
|
||||
if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]);
|
||||
else if (action.dataset.messageAction === 'label') addMessageLabel(message);
|
||||
@@ -153,26 +153,26 @@ document.addEventListener('click', event => {
|
||||
messageAction(message, type).then(() => {
|
||||
if (type === 'unread') message.unread = true;
|
||||
if (type === 'inbox') message.archived = false;
|
||||
mailUi.renderList();
|
||||
mailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
||||
}).catch(error => mailUi.toast(error.message || 'Could not update the message'));
|
||||
snoozeMailUi.renderList();
|
||||
snoozeMailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
||||
}).catch(error => snoozeMailUi.toast(error.message || 'Could not update the message'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (unsnooze) {
|
||||
const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage);
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||
if (message) unsnoozeMessage(message);
|
||||
return;
|
||||
}
|
||||
if (snooze?.id === 'snooze-selected') {
|
||||
openSnoozeDialog(mailUi.state.messages.filter(message => mailUi.state.selectedIds.has(message.id)));
|
||||
openSnoozeDialog(snoozeMailUi.state.messages.filter(message => snoozeMailUi.state.selectedIds.has(message.id)));
|
||||
return;
|
||||
}
|
||||
if (more) {
|
||||
const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage);
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||
if (message) showMessageActions(message);
|
||||
return;
|
||||
}
|
||||
const message = mailUi.state.messages.find(item => item.id === mailUi.state.activeMessage);
|
||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||
if (message) openSnoozeDialog([message]);
|
||||
}, true);
|
||||
|
||||
Reference in New Issue
Block a user