Compare commits
2
Commits
V0.5.16
...
89c45fcf63
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89c45fcf63 | ||
|
|
d7b6e31518 |
@@ -27,7 +27,11 @@ npm run android:apk
|
||||
|
||||
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail <version>.apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification sender/subject details are hidden by default; enabling them in Settings still keeps lock-screen previews redacted. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
|
||||
|
||||
On Android, previously cached folder messages appear while the mailbox refreshes; a folder without cached messages still needs to load from the server. The app stays in the message list until you select a message; returning to the list does not automatically reopen the newest message.
|
||||
On Android, previously cached folder messages appear while the mailbox refreshes; a folder without cached messages still needs to load from the server. Folder discovery and message actions run separately from cached-folder loading. The app stays in the message list until you select a message; returning to the list does not automatically reopen the newest message.
|
||||
|
||||
In connected IMAP folders, scrolling to the end of the message list loads the next page automatically. The **Load more** button remains available as a manual fallback.
|
||||
|
||||
After upgrading from an older Android build, close and reopen ep-mail once if it still shows the previous interface. This lets the updated offline app shell take control without clearing account data.
|
||||
|
||||
## Run on Windows or Linux
|
||||
|
||||
|
||||
@@ -339,7 +339,7 @@ internal object AndroidAccountVault {
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun cacheMessages(id: String, folder: String, messages: JSONArray) {
|
||||
fun cacheMessages(id: String, folder: String, messages: JSONArray, replace: Boolean = false) {
|
||||
val store = read()
|
||||
val accounts = store.optJSONArray("accounts") ?: return
|
||||
for (index in 0 until accounts.length()) {
|
||||
@@ -348,16 +348,18 @@ internal object AndroidAccountVault {
|
||||
val cache = account.optJSONObject("mailCache") ?: JSONObject()
|
||||
val previous = cache.optJSONArray(folder) ?: JSONArray()
|
||||
val merged = LinkedHashMap<String, JSONObject>()
|
||||
if (!replace) {
|
||||
for (itemIndex in 0 until previous.length()) {
|
||||
val item = previous.optJSONObject(itemIndex) ?: continue
|
||||
merged[item.optString("uid", item.optString("id"))] = item
|
||||
}
|
||||
}
|
||||
for (itemIndex in 0 until messages.length()) {
|
||||
val item = messages.optJSONObject(itemIndex) ?: continue
|
||||
merged[item.optString("uid", item.optString("id"))] = item
|
||||
}
|
||||
cache.put(folder, JSONArray().apply {
|
||||
merged.values.toList().takeLast(30).forEach { put(it) }
|
||||
merged.values.sortedByDescending { it.optLong("timestamp") }.take(30).forEach { put(it) }
|
||||
})
|
||||
account.put("mailCache", cache)
|
||||
write(store)
|
||||
|
||||
@@ -182,7 +182,7 @@ internal object AndroidMailService {
|
||||
result.put(value)
|
||||
cached.put(value)
|
||||
}
|
||||
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached)
|
||||
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached, replace = offset <= 0)
|
||||
JSONObject().put("messages", result).put("total", total)
|
||||
.put("start", first).put("end", end).put("folder", requestedFolder)
|
||||
} finally {
|
||||
|
||||
@@ -26,6 +26,8 @@ class EpMailPlugin : Plugin() {
|
||||
private var syncReceiver: BroadcastReceiver? = null
|
||||
private var wipeDialogShowing = false
|
||||
private val mailboxExecutor = Executors.newFixedThreadPool(3)
|
||||
private val folderListExecutor = Executors.newFixedThreadPool(2)
|
||||
private val mailActionExecutor = Executors.newSingleThreadExecutor()
|
||||
private val outboxExecutor = Executors.newSingleThreadExecutor()
|
||||
|
||||
override fun load() {
|
||||
@@ -62,6 +64,8 @@ class EpMailPlugin : Plugin() {
|
||||
|
||||
override fun handleOnDestroy() {
|
||||
mailboxExecutor.shutdown()
|
||||
folderListExecutor.shutdown()
|
||||
mailActionExecutor.shutdown()
|
||||
outboxExecutor.shutdown()
|
||||
syncReceiver?.let {
|
||||
try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {}
|
||||
@@ -484,9 +488,15 @@ class EpMailPlugin : Plugin() {
|
||||
try {
|
||||
val account = AndroidAccountVault.account()
|
||||
?: throw IllegalStateException("Add a mail account before listing folders.")
|
||||
folderListExecutor.execute {
|
||||
try {
|
||||
call.resolve(AndroidMailService.listFolders(account).toJSObject())
|
||||
} catch (error: Exception) {
|
||||
call.resolve(JSObject().put("folders", org.json.JSONArray()).put("offline", true))
|
||||
call.reject(error.message ?: "Could not list mail folders.")
|
||||
}
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
call.reject(error.message ?: "Could not list mail folders.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,18 +570,28 @@ class EpMailPlugin : Plugin() {
|
||||
try {
|
||||
val account = AndroidAccountVault.account()
|
||||
?: throw IllegalStateException("Add a mail account before changing messages.")
|
||||
call.resolve(AndroidMailService.updateMessage(account, call.data).toJSObject())
|
||||
val input = JSONObject(call.data.toString())
|
||||
mailActionExecutor.execute {
|
||||
try {
|
||||
call.resolve(AndroidMailService.updateMessage(account, input).toJSObject())
|
||||
} catch (error: Exception) {
|
||||
val account = AndroidAccountVault.account()
|
||||
if (account != null && isConnectivityFailure(error)) {
|
||||
if (isConnectivityFailure(error)) {
|
||||
try {
|
||||
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
|
||||
.put("id", UUID.randomUUID().toString())
|
||||
.put("type", "action")
|
||||
.put("data", JSONObject(call.data.toString())))
|
||||
.put("data", input))
|
||||
call.resolve(JSObject().put("ok", true).put("queued", true))
|
||||
} catch (queueError: Exception) {
|
||||
call.reject(queueError.message ?: "Could not queue the message action.")
|
||||
}
|
||||
} else call.reject(error.message ?: "Could not update the message.")
|
||||
}
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
call.reject(error.message ?: "Could not update the message.")
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun setSnooze(call: PluginCall) {
|
||||
|
||||
+83
-9
@@ -8,7 +8,9 @@ const toastMailUi = appShell.toast;
|
||||
const mailFeatureState = {
|
||||
connectedAccount: null,
|
||||
pageOffset: 0,
|
||||
nextOffset: 0,
|
||||
total: 0,
|
||||
autoLoadBlocked: false,
|
||||
syncPromise: null,
|
||||
syncQueued: false,
|
||||
syncMailboxKey: null,
|
||||
@@ -16,6 +18,8 @@ const mailFeatureState = {
|
||||
refreshPending: false,
|
||||
folderBeforeSearch: null,
|
||||
customFolders: [],
|
||||
folderLoad: null,
|
||||
foldersAccountId: null,
|
||||
selectedDraftIds: new Set()
|
||||
};
|
||||
|
||||
@@ -144,10 +148,23 @@ function renderCustomFolders() {
|
||||
|
||||
async function loadCustomFolders() {
|
||||
if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
|
||||
const accountId = mailFeatureState.connectedAccount.id;
|
||||
if (mailFeatureState.folderLoad?.accountId === accountId) return mailFeatureState.folderLoad.promise;
|
||||
const request = { accountId };
|
||||
mailFeatureState.folderLoad = request;
|
||||
request.promise = (async () => {
|
||||
try {
|
||||
mailFeatureState.customFolders = (await window.daybreakMail.listFolders()).folders || [];
|
||||
const result = await window.daybreakMail.listFolders();
|
||||
if (mailFeatureState.folderLoad !== request || mailFeatureState.connectedAccount?.id !== accountId) return;
|
||||
mailFeatureState.customFolders = result.folders || [];
|
||||
renderCustomFolders();
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
if (mailFeatureState.folderLoad === request) console.error('Could not load mail folders:', error);
|
||||
} finally {
|
||||
if (mailFeatureState.folderLoad === request) mailFeatureState.folderLoad = null;
|
||||
}
|
||||
})();
|
||||
return request.promise;
|
||||
}
|
||||
|
||||
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
|
||||
@@ -185,6 +202,7 @@ async function createMailFolder() {
|
||||
if (!name) return;
|
||||
try {
|
||||
const result = await window.daybreakMail.createFolder(name);
|
||||
mailFeatureState.folderLoad = null;
|
||||
mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
|
||||
renderCustomFolders();
|
||||
toastMailUi(`Folder “${result.folder?.name || name}” created`);
|
||||
@@ -194,6 +212,13 @@ async function createMailFolder() {
|
||||
}
|
||||
|
||||
function updateAccountCard(account) {
|
||||
const accountId = mailFeatureState.connectedAccount?.id || null;
|
||||
if (mailFeatureState.foldersAccountId !== accountId) {
|
||||
mailFeatureState.foldersAccountId = accountId;
|
||||
mailFeatureState.folderLoad = null;
|
||||
mailFeatureState.customFolders = [];
|
||||
renderCustomFolders();
|
||||
}
|
||||
const card = selectMailUi('#account-settings');
|
||||
if (!card) return;
|
||||
const email = account.email || '';
|
||||
@@ -665,14 +690,20 @@ async function syncMailbox(showToast, options = {}) {
|
||||
}
|
||||
const refresh = selectMailUi('#refresh');
|
||||
if (refresh) refresh.disabled = true;
|
||||
const loadMoreButton = selectMailUi('#load-more');
|
||||
if (loadMoreButton) loadMoreButton.disabled = true;
|
||||
const request = {};
|
||||
mailFeatureState.syncRequest = request;
|
||||
mailFeatureState.syncMailboxKey = mailboxKey;
|
||||
let syncSucceeded = false;
|
||||
const sync = (async () => {
|
||||
let showingCachedMessages = false;
|
||||
try {
|
||||
if (isAndroid && mailFeatureState.displayedMailboxKey !== mailboxKey) {
|
||||
mailFeatureState.displayedMailboxKey = mailboxKey;
|
||||
mailFeatureState.nextOffset = 0;
|
||||
mailFeatureState.total = 0;
|
||||
mailFeatureState.autoLoadBlocked = false;
|
||||
rendererState.messages.splice(0, rendererState.messages.length);
|
||||
rendererState.activeMessage = null;
|
||||
rendererState.selectedIds.clear();
|
||||
@@ -686,12 +717,13 @@ async function syncMailbox(showToast, options = {}) {
|
||||
const result = await window.daybreakMail.listDrafts();
|
||||
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||
renderDrafts(result.drafts || []);
|
||||
mailFeatureState.autoLoadBlocked = true;
|
||||
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
|
||||
return;
|
||||
}
|
||||
const folder = rendererState.activeFolder;
|
||||
const accountId = mailFeatureState.connectedAccount.id;
|
||||
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
|
||||
const offset = options.offset ?? (options.append ? mailFeatureState.nextOffset : mailFeatureState.pageOffset);
|
||||
const filters = mailSearchFilters();
|
||||
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId &&
|
||||
(!isAndroid || mailFeatureState.syncRequest === request);
|
||||
@@ -702,7 +734,9 @@ async function syncMailbox(showToast, options = {}) {
|
||||
rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages);
|
||||
rendererState.activeMessage = null;
|
||||
mailFeatureState.pageOffset = offset;
|
||||
mailFeatureState.nextOffset = offset + cached.messages.length;
|
||||
mailFeatureState.total = cached.total;
|
||||
mailFeatureState.autoLoadBlocked = true;
|
||||
const pagination = selectMailUi('#pagination');
|
||||
if (pagination) pagination.textContent = cached.total ? `${cached.start}–${cached.end} of ${cached.total} saved messages` : '0 saved messages';
|
||||
const loadMore = selectMailUi('#load-more');
|
||||
@@ -721,8 +755,16 @@ async function syncMailbox(showToast, options = {}) {
|
||||
const result = await window.daybreakMail.syncFolder(folder, offset, filters);
|
||||
if (!isCurrentMailbox()) return;
|
||||
const previouslyActiveMessage = rendererState.activeMessage;
|
||||
if (options.append) rendererState.messages.push(...result.messages);
|
||||
else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
|
||||
if (options.append) {
|
||||
const existing = new Set(rendererState.messages.map(message => JSON.stringify([message.sourceFolder || folder, message.uid || message.id])));
|
||||
for (const message of result.messages) {
|
||||
const key = JSON.stringify([message.sourceFolder || folder, message.uid || message.id]);
|
||||
if (!existing.has(key)) {
|
||||
rendererState.messages.push(message);
|
||||
existing.add(key);
|
||||
}
|
||||
}
|
||||
} else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
|
||||
rendererState.messages.forEach(message => {
|
||||
try {
|
||||
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
|
||||
@@ -731,6 +773,14 @@ async function syncMailbox(showToast, options = {}) {
|
||||
});
|
||||
if (!options.append) mailFeatureState.pageOffset = offset;
|
||||
mailFeatureState.total = result.total;
|
||||
const hasSearch = Boolean(filters.query || filters.sender || filters.subject || filters.after || filters.before || filters.hasAttachments);
|
||||
const isSequencePage = !result.offline && folder !== 'Snoozed' && !hasSearch;
|
||||
const consumed = isSequencePage && result.start > 0 && result.end >= result.start
|
||||
? result.end - result.start + 1
|
||||
: result.messages.length;
|
||||
mailFeatureState.nextOffset = offset + consumed;
|
||||
mailFeatureState.autoLoadBlocked = consumed === 0 || (options.append && result.messages.length === 0);
|
||||
syncSucceeded = true;
|
||||
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
|
||||
? previouslyActiveMessage
|
||||
: window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id;
|
||||
@@ -739,11 +789,14 @@ async function syncMailbox(showToast, options = {}) {
|
||||
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
|
||||
if (inboxCount) inboxCount.textContent = String(unread);
|
||||
const pagination = selectMailUi('#pagination');
|
||||
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
|
||||
if (pagination) pagination.textContent = result.total ? `${options.append ? mailFeatureState.pageOffset + 1 : result.start}–${options.append ? Math.min(mailFeatureState.nextOffset, result.total) : result.end} of ${result.total}` : '0 messages';
|
||||
const loadMore = selectMailUi('#load-more');
|
||||
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.pageOffset + rendererState.messages.length >= result.total);
|
||||
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.nextOffset >= result.total || consumed === 0);
|
||||
rendererState.query = '';
|
||||
const messageList = selectMailUi('#message-list');
|
||||
const scrollTop = options.append ? messageList.scrollTop : 0;
|
||||
appShell.renderList();
|
||||
if (options.append) messageList.scrollTop = scrollTop;
|
||||
if (rendererState.activeMessage) {
|
||||
appShell.openMessage(rendererState.activeMessage);
|
||||
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
|
||||
@@ -758,13 +811,18 @@ async function syncMailbox(showToast, options = {}) {
|
||||
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
|
||||
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
|
||||
} catch (error) {
|
||||
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||
if (options.append) mailFeatureState.autoLoadBlocked = true;
|
||||
if (showingCachedMessages) {
|
||||
const status = selectMailUi('#mail-status');
|
||||
if (status) status.textContent = 'Could not sync — showing saved messages';
|
||||
}
|
||||
toastMailUi(error.message || 'Could not sync the inbox');
|
||||
} finally {
|
||||
if (refresh && (!isAndroid || mailFeatureState.syncRequest === request)) refresh.disabled = false;
|
||||
if (!isAndroid || mailFeatureState.syncRequest === request) {
|
||||
if (refresh) refresh.disabled = false;
|
||||
if (loadMoreButton) loadMoreButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
})();
|
||||
@@ -778,10 +836,23 @@ async function syncMailbox(showToast, options = {}) {
|
||||
if (mailFeatureState.syncQueued) {
|
||||
mailFeatureState.syncQueued = false;
|
||||
void syncMailbox(false);
|
||||
} else if (syncSucceeded) {
|
||||
maybeLoadMoreMessages();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function maybeLoadMoreMessages() {
|
||||
const list = selectMailUi('#message-list');
|
||||
if (!list || !mailFeatureState.connectedAccount || mailFeatureState.syncPromise ||
|
||||
mailFeatureState.autoLoadBlocked || rendererState.activeFolder === 'Drafts' ||
|
||||
mailFeatureState.nextOffset >= mailFeatureState.total || !list.clientHeight ||
|
||||
document.body.classList.contains('reader-open') ||
|
||||
rendererState.activeView !== 'mail') return;
|
||||
if (list.scrollHeight - list.scrollTop - list.clientHeight > 120) return;
|
||||
void syncMailbox(false, { append: true });
|
||||
}
|
||||
|
||||
if (window.daybreakMail) {
|
||||
setupDraftComposer();
|
||||
let searchTimer;
|
||||
@@ -886,7 +957,10 @@ if (window.daybreakMail) {
|
||||
mailFeatureState.pageOffset += 20;
|
||||
syncMailbox(false, { offset: mailFeatureState.pageOffset });
|
||||
};
|
||||
selectMailUi('#load-more').onclick = () => syncMailbox(false, { append: true });
|
||||
selectMailUi('#load-more').onclick = () => {
|
||||
if (!mailFeatureState.syncPromise) void syncMailbox(false, { append: true });
|
||||
};
|
||||
selectMailUi('#message-list').addEventListener('scroll', maybeLoadMoreMessages, { passive: true });
|
||||
document.addEventListener('click', async event => {
|
||||
const sendButton = event.target.closest('#send');
|
||||
if (!sendButton || !mailFeatureState.connectedAccount) return;
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.5.16",
|
||||
"version": "0.5.18",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ep-mail",
|
||||
"version": "0.5.16",
|
||||
"version": "0.5.18",
|
||||
"dependencies": {
|
||||
"@capacitor/android": "^8.5.2",
|
||||
"@capacitor/core": "^8.5.2",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.5.16",
|
||||
"version": "0.5.18",
|
||||
"private": true,
|
||||
"description": "Eternity Project mail client",
|
||||
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
||||
|
||||
+25
-2
@@ -1,5 +1,28 @@
|
||||
const CACHE='ep-mail-v19';
|
||||
const CACHE='ep-mail-v20';
|
||||
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
|
||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
|
||||
self.addEventListener('fetch',event=>{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'))))});
|
||||
self.addEventListener('fetch', event => {
|
||||
const request = event.request;
|
||||
if (request.method !== 'GET' || new URL(request.url).origin !== location.origin) return;
|
||||
event.respondWith((async () => {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(request, { cache: 'no-cache' });
|
||||
} catch (error) {
|
||||
const cached = await caches.match(request) ||
|
||||
(request.mode === 'navigate' ? await caches.match('./index.html') : null);
|
||||
if (cached) return cached;
|
||||
throw error;
|
||||
}
|
||||
if (response.ok) {
|
||||
try {
|
||||
const cache = await caches.open(CACHE);
|
||||
await cache.put(request, response.clone());
|
||||
} catch (error) {
|
||||
console.error('Could not update offline app cache:', error);
|
||||
}
|
||||
}
|
||||
return response;
|
||||
})());
|
||||
});
|
||||
|
||||
@@ -16,7 +16,7 @@ function deferred() {
|
||||
|
||||
function harness({ platform = 'android', cached, sync }) {
|
||||
const messages = [];
|
||||
const state = { messages, activeMessage: null, activeFolder: 'Inbox', selectedIds: new Set(), query: '' };
|
||||
const state = { messages, activeMessage: null, activeFolder: 'Inbox', activeView: 'mail', selectedIds: new Set(), query: '' };
|
||||
const feature = { connectedAccount: { id: 'account' }, pageOffset: 0, syncPromise: null, syncQueued: false, displayedMailboxKey: JSON.stringify(['account', 'Inbox']) };
|
||||
const elements = new Map();
|
||||
const opened = [];
|
||||
@@ -31,7 +31,7 @@ function harness({ platform = 'android', cached, sync }) {
|
||||
if (cached) bridge.getCachedFolder = cached;
|
||||
const context = {
|
||||
window: { daybreakMail: bridge },
|
||||
document: { body: { classList: { remove: value => classes.delete(value) } } },
|
||||
document: { body: { classList: { remove: value => classes.delete(value), contains: value => classes.has(value) } } },
|
||||
rendererState: state,
|
||||
mailFeatureState: feature,
|
||||
selectMailUi: selector => {
|
||||
@@ -200,6 +200,188 @@ test('switching accounts never displays the previous account’s messages', asyn
|
||||
assert.deepEqual(ui.state.messages.map(message => message.id), [2]);
|
||||
});
|
||||
|
||||
test('scrolling to the end appends one page and retains the scroll position', async () => {
|
||||
const next = deferred();
|
||||
const offsets = [];
|
||||
const ui = harness({ sync: (_folder, offset) => {
|
||||
offsets.push(offset);
|
||||
return next.promise;
|
||||
} });
|
||||
ui.state.messages.push(...result([1, 2]).messages);
|
||||
ui.feature.total = 5;
|
||||
ui.feature.nextOffset = 2;
|
||||
const list = ui.context.selectMailUi('#message-list');
|
||||
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 700 });
|
||||
ui.context.appShell.renderList = () => { list.scrollTop = 0; };
|
||||
ui.context.maybeLoadMoreMessages();
|
||||
ui.context.maybeLoadMoreMessages();
|
||||
assert.deepEqual(offsets, [2]);
|
||||
list.scrollHeight = 1400;
|
||||
next.resolve({ messages: result([3, 4]).messages, total: 5, start: 2, end: 3 });
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3, 4]);
|
||||
assert.equal(list.scrollTop, 700);
|
||||
assert.deepEqual(offsets, [2]);
|
||||
});
|
||||
|
||||
test('short lists continue loading until the viewport is filled', async () => {
|
||||
let calls = 0;
|
||||
const ui = harness({ sync: async () => {
|
||||
calls++;
|
||||
return calls === 1
|
||||
? { messages: result([1]).messages, total: 3, start: 3, end: 3 }
|
||||
: { messages: result([2, 3]).messages, total: 3, start: 1, end: 2 };
|
||||
} });
|
||||
const list = ui.context.selectMailUi('#message-list');
|
||||
Object.assign(list, { clientHeight: 300, scrollHeight: 300, scrollTop: 0 });
|
||||
await ui.context.syncMailbox(false, { offset: 0 });
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(calls, 2);
|
||||
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3]);
|
||||
});
|
||||
|
||||
test('an appended page does not duplicate messages returned by a shifting mailbox', async () => {
|
||||
const ui = harness({ sync: async () => ({ messages: result([2, 3, 3]).messages, total: 4, start: 1, end: 3 }) });
|
||||
ui.state.messages.push(...result([1, 2]).messages);
|
||||
ui.feature.total = 4;
|
||||
ui.feature.nextOffset = 2;
|
||||
await ui.context.syncMailbox(false, { append: true });
|
||||
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3]);
|
||||
});
|
||||
|
||||
test('automatic loading waits for the list bottom and stops at the last page', () => {
|
||||
let calls = 0;
|
||||
const ui = harness({ sync: async () => { calls++; return result([]); } });
|
||||
ui.feature.total = 40;
|
||||
ui.feature.nextOffset = 20;
|
||||
const list = ui.context.selectMailUi('#message-list');
|
||||
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 100 });
|
||||
ui.context.maybeLoadMoreMessages();
|
||||
assert.equal(calls, 0);
|
||||
list.scrollTop = 700;
|
||||
ui.feature.nextOffset = 40;
|
||||
ui.context.maybeLoadMoreMessages();
|
||||
assert.equal(calls, 0);
|
||||
ui.feature.nextOffset = 20;
|
||||
ui.state.activeFolder = 'Drafts';
|
||||
ui.context.maybeLoadMoreMessages();
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
test('pagination advances over snoozed messages and stops automatic loading on empty pages', async () => {
|
||||
const offsets = [];
|
||||
const ui = harness({ sync: async (_folder, offset) => {
|
||||
offsets.push(offset);
|
||||
if (offset === 0) return { messages: result([1]).messages, total: 45, start: 26, end: 45 };
|
||||
return { messages: [], total: 45, start: 6, end: 25 };
|
||||
} });
|
||||
await ui.context.syncMailbox(false, { offset: 0 });
|
||||
assert.equal(ui.feature.nextOffset, 20);
|
||||
await ui.context.syncMailbox(false, { append: true });
|
||||
assert.deepEqual(offsets, [0, 20]);
|
||||
assert.equal(ui.feature.nextOffset, 40);
|
||||
assert.equal(ui.feature.autoLoadBlocked, true);
|
||||
});
|
||||
|
||||
test('automatic pagination stops after a failed or empty fetch', async () => {
|
||||
let calls = 0;
|
||||
const ui = harness({ sync: async () => { calls++; throw new Error('Offline'); } });
|
||||
ui.feature.total = 40;
|
||||
ui.feature.nextOffset = 20;
|
||||
const list = ui.context.selectMailUi('#message-list');
|
||||
Object.assign(list, { clientHeight: 300, scrollHeight: 300, scrollTop: 0 });
|
||||
ui.context.maybeLoadMoreMessages();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
ui.context.maybeLoadMoreMessages();
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(ui.feature.autoLoadBlocked, true);
|
||||
assert.deepEqual(ui.toasts, ['Offline']);
|
||||
});
|
||||
|
||||
test('offline cached pages can load automatically and stop at the cached total', async () => {
|
||||
let calls = 0;
|
||||
const ui = harness({ sync: async (_folder, offset) => {
|
||||
calls++;
|
||||
return offset === 0
|
||||
? { messages: result([1]).messages, total: 2, start: 1, end: 1, offline: true }
|
||||
: { messages: result([2]).messages, total: 2, start: 2, end: 2, offline: true };
|
||||
} });
|
||||
const list = ui.context.selectMailUi('#message-list');
|
||||
Object.assign(list, { clientHeight: 300, scrollHeight: 300, scrollTop: 0 });
|
||||
await ui.context.syncMailbox(false);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(calls, 2);
|
||||
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2]);
|
||||
});
|
||||
|
||||
test('Android cache keeps newest messages when loading older pages', () => {
|
||||
const vault = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidAccountVault.kt'), 'utf8');
|
||||
const service = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8');
|
||||
assert.match(vault, /sortedByDescending \{ it\.optLong\("timestamp"\) \}\.take\(30\)/);
|
||||
assert.match(service, /cacheMessages\(account\.optString\("id"\), requestedFolder, cached, replace = offset <= 0\)/);
|
||||
});
|
||||
|
||||
test('folder discovery deduplicates concurrent requests and ignores the previous account', async () => {
|
||||
const first = deferred();
|
||||
const second = deferred();
|
||||
let calls = 0;
|
||||
const feature = { connectedAccount: { id: 'one' }, customFolders: [] };
|
||||
const renders = [];
|
||||
const context = {
|
||||
mailFeatureState: feature,
|
||||
window: { daybreakMail: { listFolders: () => [first, second][calls++].promise } },
|
||||
renderCustomFolders: () => renders.push(feature.customFolders.map(folder => folder.id)),
|
||||
console
|
||||
};
|
||||
const start = source.indexOf('async function loadCustomFolders()');
|
||||
const end = source.indexOf('\n// Destination options', start);
|
||||
vm.runInNewContext(`${source.slice(start, end)}\nthis.loadCustomFolders = loadCustomFolders`, context);
|
||||
const pending = context.loadCustomFolders();
|
||||
const duplicate = context.loadCustomFolders();
|
||||
assert.equal(calls, 1);
|
||||
feature.connectedAccount = { id: 'two' };
|
||||
const current = context.loadCustomFolders();
|
||||
assert.equal(calls, 2);
|
||||
second.resolve({ folders: [{ id: 'new' }] });
|
||||
await current;
|
||||
first.resolve({ folders: [{ id: 'old' }] });
|
||||
await Promise.all([pending, duplicate]);
|
||||
assert.deepEqual(feature.customFolders.map(folder => folder.id), ['new']);
|
||||
assert.deepEqual(renders, [['new']]);
|
||||
});
|
||||
|
||||
test('folder discovery reports errors and allows retry', async () => {
|
||||
let calls = 0;
|
||||
const errors = [];
|
||||
const feature = { connectedAccount: { id: 'one' }, customFolders: [] };
|
||||
const context = {
|
||||
mailFeatureState: feature,
|
||||
window: { daybreakMail: { listFolders: async () => {
|
||||
if (++calls === 1) throw new Error('Unavailable');
|
||||
return { folders: [{ id: 'retried' }] };
|
||||
} } },
|
||||
renderCustomFolders() {},
|
||||
console: { error: (...args) => errors.push(args) }
|
||||
};
|
||||
const start = source.indexOf('async function loadCustomFolders()');
|
||||
const end = source.indexOf('\n// Destination options', start);
|
||||
vm.runInNewContext(`${source.slice(start, end)}\nthis.loadCustomFolders = loadCustomFolders`, context);
|
||||
await context.loadCustomFolders();
|
||||
await context.loadCustomFolders();
|
||||
assert.equal(errors.length, 1);
|
||||
assert.equal(feature.customFolders[0].id, 'retried');
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('Android folder discovery and message actions do not run on the Capacitor plugin thread', () => {
|
||||
const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8');
|
||||
const list = plugin.slice(plugin.indexOf('fun listFolders('), plugin.indexOf('fun createFolder('));
|
||||
const action = plugin.slice(plugin.indexOf('fun updateMessage('), plugin.indexOf('fun setSnooze('));
|
||||
assert.ok(list.indexOf('folderListExecutor.execute') < list.indexOf('AndroidMailService.listFolders(account)'));
|
||||
assert.ok(action.indexOf('mailActionExecutor.execute') < action.indexOf('AndroidMailService.updateMessage(account, input)'));
|
||||
assert.match(action, /enqueueMailOperation/);
|
||||
});
|
||||
|
||||
test('Android startup theme uses the EP vector on supported splash screens', () => {
|
||||
const styles = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'values', 'styles.xml'), 'utf8');
|
||||
const icon = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'drawable', 'ep_splash_icon.xml'), 'utf8');
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
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 source = fs.readFileSync(path.join(__dirname, '..', 'service-worker.js'), 'utf8');
|
||||
|
||||
function harness({ network, cached }) {
|
||||
const handlers = {};
|
||||
const writes = [];
|
||||
const context = {
|
||||
URL,
|
||||
location: { origin: 'https://localhost' },
|
||||
self: { addEventListener: (type, handler) => { handlers[type] = handler; } },
|
||||
caches: {
|
||||
match: async request => cached.get(typeof request === 'string' ? request : request.url),
|
||||
open: async () => ({ put: async (request, response) => writes.push([request.url, response]) })
|
||||
},
|
||||
fetch: network
|
||||
};
|
||||
vm.runInNewContext(source, context);
|
||||
return {
|
||||
writes,
|
||||
async request(request) {
|
||||
let response;
|
||||
const pending = [];
|
||||
handlers.fetch({
|
||||
request,
|
||||
respondWith(value) { response = value; },
|
||||
waitUntil(value) { pending.push(value); }
|
||||
});
|
||||
if (!response) return { intercepted: false };
|
||||
const result = await response;
|
||||
await Promise.all(pending);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
test('new Android app assets replace old cached scripts', async () => {
|
||||
const request = { method: 'GET', url: 'https://localhost/mail-ui.js', mode: 'same-origin' };
|
||||
const fresh = { ok: true, clone() { return this; } };
|
||||
const old = { old: true };
|
||||
const ui = harness({ network: async () => fresh, cached: new Map([[request.url, old]]) });
|
||||
assert.equal(await ui.request(request), fresh);
|
||||
assert.deepEqual(ui.writes, [[request.url, fresh]]);
|
||||
assert.notEqual(source.match(/const CACHE\s*=\s*['"]([^'"]+)/)[1], 'ep-mail-v19');
|
||||
});
|
||||
|
||||
test('offline requests use cached assets and missing assets fail explicitly', async () => {
|
||||
const request = { method: 'GET', url: 'https://localhost/mail-ui.js', mode: 'same-origin' };
|
||||
const old = { old: true };
|
||||
const offline = async () => { throw new Error('offline'); };
|
||||
const ui = harness({ network: offline, cached: new Map([[request.url, old]]) });
|
||||
assert.equal(await ui.request(request), old);
|
||||
const missing = harness({ network: offline, cached: new Map() });
|
||||
await assert.rejects(missing.request(request), /offline/);
|
||||
});
|
||||
|
||||
test('network failures for navigation use the cached app shell', async () => {
|
||||
const request = { method: 'GET', url: 'https://localhost/', mode: 'navigate' };
|
||||
const shell = { shell: true };
|
||||
const ui = harness({
|
||||
network: async () => { throw new Error('offline'); },
|
||||
cached: new Map([['./index.html', shell]])
|
||||
});
|
||||
assert.equal(await ui.request(request), shell);
|
||||
});
|
||||
|
||||
test('HTTP error responses are not stored or replaced with cached content', async () => {
|
||||
const request = { method: 'GET', url: 'https://localhost/mail-ui.js', mode: 'same-origin' };
|
||||
const failed = { ok: false, status: 404 };
|
||||
const ui = harness({ network: async () => failed, cached: new Map([[request.url, { old: true }]]) });
|
||||
assert.equal(await ui.request(request), failed);
|
||||
assert.deepEqual(ui.writes, []);
|
||||
});
|
||||
|
||||
test('cross-origin and non-GET requests are not intercepted', async () => {
|
||||
const ui = harness({ network: async () => { throw new Error('unexpected fetch'); }, cached: new Map() });
|
||||
assert.deepEqual(await ui.request({ method: 'GET', url: 'https://other.example/image.png' }), { intercepted: false });
|
||||
assert.deepEqual(await ui.request({ method: 'POST', url: 'https://localhost/mail-ui.js' }), { intercepted: false });
|
||||
});
|
||||
+83
-9
@@ -8,7 +8,9 @@ const toastMailUi = appShell.toast;
|
||||
const mailFeatureState = {
|
||||
connectedAccount: null,
|
||||
pageOffset: 0,
|
||||
nextOffset: 0,
|
||||
total: 0,
|
||||
autoLoadBlocked: false,
|
||||
syncPromise: null,
|
||||
syncQueued: false,
|
||||
syncMailboxKey: null,
|
||||
@@ -16,6 +18,8 @@ const mailFeatureState = {
|
||||
refreshPending: false,
|
||||
folderBeforeSearch: null,
|
||||
customFolders: [],
|
||||
folderLoad: null,
|
||||
foldersAccountId: null,
|
||||
selectedDraftIds: new Set()
|
||||
};
|
||||
|
||||
@@ -144,10 +148,23 @@ function renderCustomFolders() {
|
||||
|
||||
async function loadCustomFolders() {
|
||||
if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
|
||||
const accountId = mailFeatureState.connectedAccount.id;
|
||||
if (mailFeatureState.folderLoad?.accountId === accountId) return mailFeatureState.folderLoad.promise;
|
||||
const request = { accountId };
|
||||
mailFeatureState.folderLoad = request;
|
||||
request.promise = (async () => {
|
||||
try {
|
||||
mailFeatureState.customFolders = (await window.daybreakMail.listFolders()).folders || [];
|
||||
const result = await window.daybreakMail.listFolders();
|
||||
if (mailFeatureState.folderLoad !== request || mailFeatureState.connectedAccount?.id !== accountId) return;
|
||||
mailFeatureState.customFolders = result.folders || [];
|
||||
renderCustomFolders();
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
if (mailFeatureState.folderLoad === request) console.error('Could not load mail folders:', error);
|
||||
} finally {
|
||||
if (mailFeatureState.folderLoad === request) mailFeatureState.folderLoad = null;
|
||||
}
|
||||
})();
|
||||
return request.promise;
|
||||
}
|
||||
|
||||
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
|
||||
@@ -185,6 +202,7 @@ async function createMailFolder() {
|
||||
if (!name) return;
|
||||
try {
|
||||
const result = await window.daybreakMail.createFolder(name);
|
||||
mailFeatureState.folderLoad = null;
|
||||
mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
|
||||
renderCustomFolders();
|
||||
toastMailUi(`Folder “${result.folder?.name || name}” created`);
|
||||
@@ -194,6 +212,13 @@ async function createMailFolder() {
|
||||
}
|
||||
|
||||
function updateAccountCard(account) {
|
||||
const accountId = mailFeatureState.connectedAccount?.id || null;
|
||||
if (mailFeatureState.foldersAccountId !== accountId) {
|
||||
mailFeatureState.foldersAccountId = accountId;
|
||||
mailFeatureState.folderLoad = null;
|
||||
mailFeatureState.customFolders = [];
|
||||
renderCustomFolders();
|
||||
}
|
||||
const card = selectMailUi('#account-settings');
|
||||
if (!card) return;
|
||||
const email = account.email || '';
|
||||
@@ -665,14 +690,20 @@ async function syncMailbox(showToast, options = {}) {
|
||||
}
|
||||
const refresh = selectMailUi('#refresh');
|
||||
if (refresh) refresh.disabled = true;
|
||||
const loadMoreButton = selectMailUi('#load-more');
|
||||
if (loadMoreButton) loadMoreButton.disabled = true;
|
||||
const request = {};
|
||||
mailFeatureState.syncRequest = request;
|
||||
mailFeatureState.syncMailboxKey = mailboxKey;
|
||||
let syncSucceeded = false;
|
||||
const sync = (async () => {
|
||||
let showingCachedMessages = false;
|
||||
try {
|
||||
if (isAndroid && mailFeatureState.displayedMailboxKey !== mailboxKey) {
|
||||
mailFeatureState.displayedMailboxKey = mailboxKey;
|
||||
mailFeatureState.nextOffset = 0;
|
||||
mailFeatureState.total = 0;
|
||||
mailFeatureState.autoLoadBlocked = false;
|
||||
rendererState.messages.splice(0, rendererState.messages.length);
|
||||
rendererState.activeMessage = null;
|
||||
rendererState.selectedIds.clear();
|
||||
@@ -686,12 +717,13 @@ async function syncMailbox(showToast, options = {}) {
|
||||
const result = await window.daybreakMail.listDrafts();
|
||||
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||
renderDrafts(result.drafts || []);
|
||||
mailFeatureState.autoLoadBlocked = true;
|
||||
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
|
||||
return;
|
||||
}
|
||||
const folder = rendererState.activeFolder;
|
||||
const accountId = mailFeatureState.connectedAccount.id;
|
||||
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
|
||||
const offset = options.offset ?? (options.append ? mailFeatureState.nextOffset : mailFeatureState.pageOffset);
|
||||
const filters = mailSearchFilters();
|
||||
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId &&
|
||||
(!isAndroid || mailFeatureState.syncRequest === request);
|
||||
@@ -702,7 +734,9 @@ async function syncMailbox(showToast, options = {}) {
|
||||
rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages);
|
||||
rendererState.activeMessage = null;
|
||||
mailFeatureState.pageOffset = offset;
|
||||
mailFeatureState.nextOffset = offset + cached.messages.length;
|
||||
mailFeatureState.total = cached.total;
|
||||
mailFeatureState.autoLoadBlocked = true;
|
||||
const pagination = selectMailUi('#pagination');
|
||||
if (pagination) pagination.textContent = cached.total ? `${cached.start}–${cached.end} of ${cached.total} saved messages` : '0 saved messages';
|
||||
const loadMore = selectMailUi('#load-more');
|
||||
@@ -721,8 +755,16 @@ async function syncMailbox(showToast, options = {}) {
|
||||
const result = await window.daybreakMail.syncFolder(folder, offset, filters);
|
||||
if (!isCurrentMailbox()) return;
|
||||
const previouslyActiveMessage = rendererState.activeMessage;
|
||||
if (options.append) rendererState.messages.push(...result.messages);
|
||||
else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
|
||||
if (options.append) {
|
||||
const existing = new Set(rendererState.messages.map(message => JSON.stringify([message.sourceFolder || folder, message.uid || message.id])));
|
||||
for (const message of result.messages) {
|
||||
const key = JSON.stringify([message.sourceFolder || folder, message.uid || message.id]);
|
||||
if (!existing.has(key)) {
|
||||
rendererState.messages.push(message);
|
||||
existing.add(key);
|
||||
}
|
||||
}
|
||||
} else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
|
||||
rendererState.messages.forEach(message => {
|
||||
try {
|
||||
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
|
||||
@@ -731,6 +773,14 @@ async function syncMailbox(showToast, options = {}) {
|
||||
});
|
||||
if (!options.append) mailFeatureState.pageOffset = offset;
|
||||
mailFeatureState.total = result.total;
|
||||
const hasSearch = Boolean(filters.query || filters.sender || filters.subject || filters.after || filters.before || filters.hasAttachments);
|
||||
const isSequencePage = !result.offline && folder !== 'Snoozed' && !hasSearch;
|
||||
const consumed = isSequencePage && result.start > 0 && result.end >= result.start
|
||||
? result.end - result.start + 1
|
||||
: result.messages.length;
|
||||
mailFeatureState.nextOffset = offset + consumed;
|
||||
mailFeatureState.autoLoadBlocked = consumed === 0 || (options.append && result.messages.length === 0);
|
||||
syncSucceeded = true;
|
||||
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
|
||||
? previouslyActiveMessage
|
||||
: window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id;
|
||||
@@ -739,11 +789,14 @@ async function syncMailbox(showToast, options = {}) {
|
||||
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
|
||||
if (inboxCount) inboxCount.textContent = String(unread);
|
||||
const pagination = selectMailUi('#pagination');
|
||||
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
|
||||
if (pagination) pagination.textContent = result.total ? `${options.append ? mailFeatureState.pageOffset + 1 : result.start}–${options.append ? Math.min(mailFeatureState.nextOffset, result.total) : result.end} of ${result.total}` : '0 messages';
|
||||
const loadMore = selectMailUi('#load-more');
|
||||
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.pageOffset + rendererState.messages.length >= result.total);
|
||||
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.nextOffset >= result.total || consumed === 0);
|
||||
rendererState.query = '';
|
||||
const messageList = selectMailUi('#message-list');
|
||||
const scrollTop = options.append ? messageList.scrollTop : 0;
|
||||
appShell.renderList();
|
||||
if (options.append) messageList.scrollTop = scrollTop;
|
||||
if (rendererState.activeMessage) {
|
||||
appShell.openMessage(rendererState.activeMessage);
|
||||
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
|
||||
@@ -758,13 +811,18 @@ async function syncMailbox(showToast, options = {}) {
|
||||
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
|
||||
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
|
||||
} catch (error) {
|
||||
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||
if (options.append) mailFeatureState.autoLoadBlocked = true;
|
||||
if (showingCachedMessages) {
|
||||
const status = selectMailUi('#mail-status');
|
||||
if (status) status.textContent = 'Could not sync — showing saved messages';
|
||||
}
|
||||
toastMailUi(error.message || 'Could not sync the inbox');
|
||||
} finally {
|
||||
if (refresh && (!isAndroid || mailFeatureState.syncRequest === request)) refresh.disabled = false;
|
||||
if (!isAndroid || mailFeatureState.syncRequest === request) {
|
||||
if (refresh) refresh.disabled = false;
|
||||
if (loadMoreButton) loadMoreButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
})();
|
||||
@@ -778,10 +836,23 @@ async function syncMailbox(showToast, options = {}) {
|
||||
if (mailFeatureState.syncQueued) {
|
||||
mailFeatureState.syncQueued = false;
|
||||
void syncMailbox(false);
|
||||
} else if (syncSucceeded) {
|
||||
maybeLoadMoreMessages();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function maybeLoadMoreMessages() {
|
||||
const list = selectMailUi('#message-list');
|
||||
if (!list || !mailFeatureState.connectedAccount || mailFeatureState.syncPromise ||
|
||||
mailFeatureState.autoLoadBlocked || rendererState.activeFolder === 'Drafts' ||
|
||||
mailFeatureState.nextOffset >= mailFeatureState.total || !list.clientHeight ||
|
||||
document.body.classList.contains('reader-open') ||
|
||||
rendererState.activeView !== 'mail') return;
|
||||
if (list.scrollHeight - list.scrollTop - list.clientHeight > 120) return;
|
||||
void syncMailbox(false, { append: true });
|
||||
}
|
||||
|
||||
if (window.daybreakMail) {
|
||||
setupDraftComposer();
|
||||
let searchTimer;
|
||||
@@ -886,7 +957,10 @@ if (window.daybreakMail) {
|
||||
mailFeatureState.pageOffset += 20;
|
||||
syncMailbox(false, { offset: mailFeatureState.pageOffset });
|
||||
};
|
||||
selectMailUi('#load-more').onclick = () => syncMailbox(false, { append: true });
|
||||
selectMailUi('#load-more').onclick = () => {
|
||||
if (!mailFeatureState.syncPromise) void syncMailbox(false, { append: true });
|
||||
};
|
||||
selectMailUi('#message-list').addEventListener('scroll', maybeLoadMoreMessages, { passive: true });
|
||||
document.addEventListener('click', async event => {
|
||||
const sendButton = event.target.closest('#send');
|
||||
if (!sendButton || !mailFeatureState.connectedAccount) return;
|
||||
|
||||
+25
-2
@@ -1,5 +1,28 @@
|
||||
const CACHE='ep-mail-v19';
|
||||
const CACHE='ep-mail-v20';
|
||||
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
|
||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
|
||||
self.addEventListener('fetch',event=>{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'))))});
|
||||
self.addEventListener('fetch', event => {
|
||||
const request = event.request;
|
||||
if (request.method !== 'GET' || new URL(request.url).origin !== location.origin) return;
|
||||
event.respondWith((async () => {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(request, { cache: 'no-cache' });
|
||||
} catch (error) {
|
||||
const cached = await caches.match(request) ||
|
||||
(request.mode === 'navigate' ? await caches.match('./index.html') : null);
|
||||
if (cached) return cached;
|
||||
throw error;
|
||||
}
|
||||
if (response.ok) {
|
||||
try {
|
||||
const cache = await caches.open(CACHE);
|
||||
await cache.put(request, response.clone());
|
||||
} catch (error) {
|
||||
console.error('Could not update offline app cache:', error);
|
||||
}
|
||||
}
|
||||
return response;
|
||||
})());
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user