Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5529a8f18f |
@@ -31,4 +31,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
|
||||
|
||||
## Current scope
|
||||
|
||||
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**.
|
||||
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash.
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
- [x] Improve mail search with sender, subject, date, folder, and attachment filters.
|
||||
- [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
|
||||
- [ ] Group related messages into conversations, with controls to expand or collapse threads.
|
||||
- [ ] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
|
||||
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
|
||||
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
|
||||
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
|
||||
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
|
||||
|
||||
@@ -345,6 +345,40 @@ internal object AndroidMailService {
|
||||
}
|
||||
}
|
||||
|
||||
fun previewAttachment(account: JSONObject, input: JSONObject): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
|
||||
?: throw IllegalStateException("That mail folder could not be found.")
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val message = (folder as? UIDFolder)?.getMessageByUID(input.optLong("uid"))
|
||||
?: throw IllegalStateException("The message is no longer available.")
|
||||
val filename = input.optString("filename")
|
||||
val part = findAttachment(message, filename)
|
||||
?: throw IllegalStateException("No attachment was found in this message.")
|
||||
val mimeType = part.contentType.substringBefore(';').trim().lowercase(Locale.ROOT)
|
||||
val none = JSONObject().put("kind", "none")
|
||||
.put("reason", "No preview is available for this file type. Download it to open it.")
|
||||
if (Regex("image/(png|jpe?g|gif|webp|bmp|svg\\+xml)").matches(mimeType)) {
|
||||
val bytes = part.inputStream.use { it.readBytes() }
|
||||
if (bytes.size > 5 * 1048576) {
|
||||
none.put("reason", "This image is too large to preview. Download it instead.")
|
||||
} else {
|
||||
JSONObject().put("kind", "image").put(
|
||||
"dataUrl", "data:$mimeType;base64," + android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
|
||||
)
|
||||
}
|
||||
} else if (mimeType.startsWith("text/") || mimeType == "application/json" || mimeType == "application/xml") {
|
||||
val bytes = part.inputStream.use { it.readBytes() }
|
||||
JSONObject().put("kind", "text")
|
||||
.put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8))
|
||||
.put("truncated", bytes.size > 100000)
|
||||
} else none
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun checkForNewMail(account: JSONObject): Int {
|
||||
flushOutbox(account)
|
||||
return withStore(account) { _, store ->
|
||||
|
||||
@@ -248,6 +248,17 @@ class EpMailPlugin : Plugin() {
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun previewAttachment(call: PluginCall) {
|
||||
try {
|
||||
val account = AndroidAccountVault.account()
|
||||
?: throw IllegalStateException("Add a mail account before previewing attachments.")
|
||||
call.resolve(AndroidMailService.previewAttachment(account, JSONObject(call.data.toString())).toJSObject())
|
||||
} catch (error: Exception) {
|
||||
call.reject(error.message ?: "Could not preview the attachment.")
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun openExternal(call: PluginCall) {
|
||||
val raw = call.getString("url").orEmpty()
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
||||
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||
let attachmentItems = [];
|
||||
|
||||
function attachmentKind(filename) {
|
||||
const ext = String(filename).toLowerCase().split('.').pop();
|
||||
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
||||
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
||||
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
||||
return 'Other';
|
||||
}
|
||||
|
||||
function attachmentSize(size) {
|
||||
if (!size) return '';
|
||||
if (typeof size === 'string') return size;
|
||||
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
async function previewAttachment(target, details) {
|
||||
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
||||
target.textContent = 'Previews are available for connected mailbox messages.';
|
||||
return;
|
||||
}
|
||||
target.textContent = 'Loading preview…';
|
||||
try {
|
||||
const result = await window.daybreakMail.previewAttachment(details);
|
||||
target.replaceChildren();
|
||||
if (result.kind === 'image') {
|
||||
const image = document.createElement('img');
|
||||
image.className = 'attachment-preview-image';
|
||||
image.alt = details.filename;
|
||||
image.src = result.dataUrl;
|
||||
target.append(image);
|
||||
} else if (result.kind === 'text') {
|
||||
const pre = document.createElement('pre');
|
||||
pre.className = 'attachment-preview-text';
|
||||
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
||||
target.append(pre);
|
||||
} else {
|
||||
target.textContent = result.reason || 'No preview is available for this file type.';
|
||||
}
|
||||
} catch (error) {
|
||||
target.textContent = error.message || 'Could not load the preview.';
|
||||
}
|
||||
}
|
||||
|
||||
function downloadAttachment(details) {
|
||||
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('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'));
|
||||
}
|
||||
|
||||
// Add a Preview button to each attachment in the reader.
|
||||
if (typeof openMessage === 'function') {
|
||||
const baseOpenMessage = openMessage;
|
||||
openMessage = function (id) {
|
||||
baseOpenMessage(id);
|
||||
const message = messages.find(item => item.id === id);
|
||||
if (!message?.uid) return;
|
||||
$$('#reader-pane .attachment').forEach(row => {
|
||||
const download = row.querySelector('.download');
|
||||
if (!download || row.querySelector('.preview-attachment')) return;
|
||||
const button = document.createElement('button');
|
||||
button.className = 'preview-attachment icon-button';
|
||||
button.title = 'Preview';
|
||||
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
||||
button.textContent = '👁';
|
||||
button.addEventListener('click', event => {
|
||||
event.stopPropagation();
|
||||
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
||||
if (panel) { panel.remove(); return; }
|
||||
panel = document.createElement('div');
|
||||
panel.className = 'attachment-preview';
|
||||
row.after(panel);
|
||||
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
|
||||
});
|
||||
download.before(button);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
async function collectAttachments() {
|
||||
const items = [];
|
||||
for (const folder of attachmentFolders) {
|
||||
let offset = 0;
|
||||
for (let page = 0; page < 5; page += 1) {
|
||||
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
||||
for (const message of result.messages || []) {
|
||||
for (const file of message.attachments || []) {
|
||||
items.push({
|
||||
uid: message.uid, folder, filename: file.filename, size: file.size,
|
||||
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
||||
kind: attachmentKind(file.filename)
|
||||
});
|
||||
}
|
||||
}
|
||||
offset += (result.messages || []).length;
|
||||
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
||||
}
|
||||
}
|
||||
return items.sort((a, b) => b.timestamp - a.timestamp);
|
||||
}
|
||||
|
||||
async function openAttachmentsView() {
|
||||
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
|
||||
const root = $('#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 render = () => {
|
||||
const text = $('#attachment-search').value.trim().toLowerCase();
|
||||
const type = $('#attachment-type').value;
|
||||
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
||||
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
||||
list.replaceChildren();
|
||||
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
||||
shown.forEach(item => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'attachment-row';
|
||||
const info = document.createElement('div');
|
||||
info.className = 'attachment-row-info';
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = item.filename;
|
||||
const meta = document.createElement('small');
|
||||
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
||||
info.append(name, meta);
|
||||
const preview = document.createElement('button');
|
||||
preview.className = 'discard';
|
||||
preview.textContent = 'Preview';
|
||||
const save = document.createElement('button');
|
||||
save.className = 'discard';
|
||||
save.textContent = 'Download';
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'attachment-preview';
|
||||
panel.hidden = true;
|
||||
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
||||
preview.onclick = () => {
|
||||
panel.hidden = !panel.hidden;
|
||||
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
||||
};
|
||||
save.onclick = () => downloadAttachment(details);
|
||||
row.append(info, preview, save, panel);
|
||||
list.append(row);
|
||||
});
|
||||
};
|
||||
$('#attachment-search').oninput = render;
|
||||
$('#attachment-type').onchange = render;
|
||||
try {
|
||||
attachmentItems = await collectAttachments();
|
||||
if ($('#attachment-list')) render();
|
||||
} catch (error) {
|
||||
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||
});
|
||||
@@ -1169,6 +1169,43 @@ ipcMain.handle('mail:save-attachment', async (event, input) => {
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:preview-attachment', async (_event, input) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before previewing attachments.');
|
||||
const uid = Number(input?.uid);
|
||||
const folder = String(input?.folder || 'Inbox');
|
||||
const filename = String(input?.filename || 'attachment');
|
||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||
const client = imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const mailboxPath = await folderPath(client, folder);
|
||||
if (!mailboxPath) throw new Error('That mail folder could not be found.');
|
||||
const lock = await client.getMailboxLock(mailboxPath);
|
||||
try {
|
||||
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
|
||||
if (!item?.source) throw new Error('The message is no longer available.');
|
||||
const parsed = await simpleParser(item.source);
|
||||
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename);
|
||||
if (!attachment) throw new Error('No attachment was found in this message.');
|
||||
const mimeType = String(attachment.contentType || '').toLowerCase().split(';')[0];
|
||||
const size = attachment.content.length;
|
||||
if (/^image\/(png|jpe?g|gif|webp|bmp|svg\+xml)$/.test(mimeType)) {
|
||||
if (size > 5 * 1048576) return { kind: 'none', reason: 'This image is too large to preview. Download it instead.' };
|
||||
return { kind: 'image', dataUrl: `data:${mimeType};base64,${attachment.content.toString('base64')}` };
|
||||
}
|
||||
if (mimeType.startsWith('text/') || ['application/json', 'application/xml'].includes(mimeType)) {
|
||||
return { kind: 'text', text: attachment.content.subarray(0, 100000).toString('utf8'), truncated: size > 100000 };
|
||||
}
|
||||
return { kind: 'none', reason: 'No preview is available for this file type. Download it to open it.' };
|
||||
} finally {
|
||||
lock.release();
|
||||
}
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:open-external', async (event, rawUrl) => {
|
||||
let target;
|
||||
try {
|
||||
|
||||
@@ -18,6 +18,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
||||
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
|
||||
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
|
||||
setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
|
||||
previewAttachment: details => ipcRenderer.invoke('mail:preview-attachment', details),
|
||||
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
|
||||
openExternal: url => ipcRenderer.invoke('mail:open-external', url),
|
||||
send: message => ipcRenderer.invoke('mail:send', message),
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
|
||||
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
|
||||
</nav>
|
||||
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
||||
<div id="custom-folders" class="folder-nav"></div>
|
||||
<div class="sidebar-divider"></div>
|
||||
@@ -71,5 +72,6 @@
|
||||
<script src="account-ui.js"></script>
|
||||
<script src="dav-ui.js"></script>
|
||||
<script src="shortcuts.js"></script>
|
||||
<script src="attachments.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ep-mail",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.2",
|
||||
"dependencies": {
|
||||
"@capacitor/android": "^8.5.2",
|
||||
"@capacitor/core": "^8.5.2",
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.2",
|
||||
"private": true,
|
||||
"description": "Eternity Project mail client",
|
||||
"author": "Eternity Project",
|
||||
@@ -42,6 +42,7 @@
|
||||
"account-ui.js",
|
||||
"dav-ui.js",
|
||||
"shortcuts.js",
|
||||
"attachments.js",
|
||||
"icon.svg",
|
||||
"logo-ep-daylight.svg",
|
||||
"logo-ep-wasteland.svg",
|
||||
|
||||
@@ -530,6 +530,7 @@
|
||||
updateMessage: (details) => EpMail.updateMessage(details),
|
||||
setSnooze: (details) => EpMail.setSnooze(details),
|
||||
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
|
||||
previewAttachment: (details) => EpMail.previewAttachment(details),
|
||||
saveAttachment: (details) => EpMail.saveAttachment(details),
|
||||
openExternal: (url) => EpMail.openExternal({ url }),
|
||||
send: (message) => EpMail.send(message),
|
||||
|
||||
@@ -22,6 +22,7 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
||||
updateMessage: details => EpMail.updateMessage(details),
|
||||
setSnooze: details => EpMail.setSnooze(details),
|
||||
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
|
||||
previewAttachment: details => EpMail.previewAttachment(details),
|
||||
saveAttachment: details => EpMail.saveAttachment(details),
|
||||
openExternal: url => EpMail.openExternal({ url }),
|
||||
send: message => EpMail.send(message),
|
||||
|
||||
@@ -14,6 +14,7 @@ const assets = [
|
||||
'account-ui.js',
|
||||
'dav-ui.js',
|
||||
'shortcuts.js',
|
||||
'attachments.js',
|
||||
'icon.svg',
|
||||
'logo-ep-daylight.svg',
|
||||
'logo-ep-wasteland.svg',
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
const CACHE='ep-mail-v4';
|
||||
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
const CACHE='ep-mail-v5';
|
||||
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
|
||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
|
||||
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
||||
|
||||
@@ -127,3 +127,4 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
||||
|
||||
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.shortcut-settings h3{margin:16px 0 4px;font-size:13px}.shortcut-settings code{font-family:monospace}.shortcut-input{text-transform:none}.shortcut-settings #reset-shortcuts{margin-top:8px}
|
||||
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
||||
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||
let attachmentItems = [];
|
||||
|
||||
function attachmentKind(filename) {
|
||||
const ext = String(filename).toLowerCase().split('.').pop();
|
||||
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
||||
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
||||
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
||||
return 'Other';
|
||||
}
|
||||
|
||||
function attachmentSize(size) {
|
||||
if (!size) return '';
|
||||
if (typeof size === 'string') return size;
|
||||
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
async function previewAttachment(target, details) {
|
||||
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
||||
target.textContent = 'Previews are available for connected mailbox messages.';
|
||||
return;
|
||||
}
|
||||
target.textContent = 'Loading preview…';
|
||||
try {
|
||||
const result = await window.daybreakMail.previewAttachment(details);
|
||||
target.replaceChildren();
|
||||
if (result.kind === 'image') {
|
||||
const image = document.createElement('img');
|
||||
image.className = 'attachment-preview-image';
|
||||
image.alt = details.filename;
|
||||
image.src = result.dataUrl;
|
||||
target.append(image);
|
||||
} else if (result.kind === 'text') {
|
||||
const pre = document.createElement('pre');
|
||||
pre.className = 'attachment-preview-text';
|
||||
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
||||
target.append(pre);
|
||||
} else {
|
||||
target.textContent = result.reason || 'No preview is available for this file type.';
|
||||
}
|
||||
} catch (error) {
|
||||
target.textContent = error.message || 'Could not load the preview.';
|
||||
}
|
||||
}
|
||||
|
||||
function downloadAttachment(details) {
|
||||
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('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'));
|
||||
}
|
||||
|
||||
// Add a Preview button to each attachment in the reader.
|
||||
if (typeof openMessage === 'function') {
|
||||
const baseOpenMessage = openMessage;
|
||||
openMessage = function (id) {
|
||||
baseOpenMessage(id);
|
||||
const message = messages.find(item => item.id === id);
|
||||
if (!message?.uid) return;
|
||||
$$('#reader-pane .attachment').forEach(row => {
|
||||
const download = row.querySelector('.download');
|
||||
if (!download || row.querySelector('.preview-attachment')) return;
|
||||
const button = document.createElement('button');
|
||||
button.className = 'preview-attachment icon-button';
|
||||
button.title = 'Preview';
|
||||
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
||||
button.textContent = '👁';
|
||||
button.addEventListener('click', event => {
|
||||
event.stopPropagation();
|
||||
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
||||
if (panel) { panel.remove(); return; }
|
||||
panel = document.createElement('div');
|
||||
panel.className = 'attachment-preview';
|
||||
row.after(panel);
|
||||
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
|
||||
});
|
||||
download.before(button);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
async function collectAttachments() {
|
||||
const items = [];
|
||||
for (const folder of attachmentFolders) {
|
||||
let offset = 0;
|
||||
for (let page = 0; page < 5; page += 1) {
|
||||
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
||||
for (const message of result.messages || []) {
|
||||
for (const file of message.attachments || []) {
|
||||
items.push({
|
||||
uid: message.uid, folder, filename: file.filename, size: file.size,
|
||||
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
||||
kind: attachmentKind(file.filename)
|
||||
});
|
||||
}
|
||||
}
|
||||
offset += (result.messages || []).length;
|
||||
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
||||
}
|
||||
}
|
||||
return items.sort((a, b) => b.timestamp - a.timestamp);
|
||||
}
|
||||
|
||||
async function openAttachmentsView() {
|
||||
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
|
||||
const root = $('#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 render = () => {
|
||||
const text = $('#attachment-search').value.trim().toLowerCase();
|
||||
const type = $('#attachment-type').value;
|
||||
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
||||
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
||||
list.replaceChildren();
|
||||
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
||||
shown.forEach(item => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'attachment-row';
|
||||
const info = document.createElement('div');
|
||||
info.className = 'attachment-row-info';
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = item.filename;
|
||||
const meta = document.createElement('small');
|
||||
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
||||
info.append(name, meta);
|
||||
const preview = document.createElement('button');
|
||||
preview.className = 'discard';
|
||||
preview.textContent = 'Preview';
|
||||
const save = document.createElement('button');
|
||||
save.className = 'discard';
|
||||
save.textContent = 'Download';
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'attachment-preview';
|
||||
panel.hidden = true;
|
||||
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
||||
preview.onclick = () => {
|
||||
panel.hidden = !panel.hidden;
|
||||
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
||||
};
|
||||
save.onclick = () => downloadAttachment(details);
|
||||
row.append(info, preview, save, panel);
|
||||
list.append(row);
|
||||
});
|
||||
};
|
||||
$('#attachment-search').oninput = render;
|
||||
$('#attachment-type').onchange = render;
|
||||
try {
|
||||
attachmentItems = await collectAttachments();
|
||||
if ($('#attachment-list')) render();
|
||||
} catch (error) {
|
||||
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||
});
|
||||
@@ -33,6 +33,7 @@
|
||||
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
|
||||
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
|
||||
</nav>
|
||||
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
||||
<div id="custom-folders" class="folder-nav"></div>
|
||||
<div class="sidebar-divider"></div>
|
||||
@@ -71,5 +72,6 @@
|
||||
<script src="account-ui.js"></script>
|
||||
<script src="dav-ui.js"></script>
|
||||
<script src="shortcuts.js"></script>
|
||||
<script src="attachments.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -530,6 +530,7 @@
|
||||
updateMessage: (details) => EpMail.updateMessage(details),
|
||||
setSnooze: (details) => EpMail.setSnooze(details),
|
||||
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
|
||||
previewAttachment: (details) => EpMail.previewAttachment(details),
|
||||
saveAttachment: (details) => EpMail.saveAttachment(details),
|
||||
openExternal: (url) => EpMail.openExternal({ url }),
|
||||
send: (message) => EpMail.send(message),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const CACHE='ep-mail-v4';
|
||||
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
const CACHE='ep-mail-v5';
|
||||
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
|
||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
|
||||
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
||||
|
||||
@@ -127,3 +127,4 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
||||
|
||||
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.shortcut-settings h3{margin:16px 0 4px;font-size:13px}.shortcut-settings code{font-family:monospace}.shortcut-input{text-transform:none}.shortcut-settings #reset-shortcuts{margin-top:8px}
|
||||
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
|
||||
|
||||
Reference in New Issue
Block a user