feat: combine review attention app badge (Closes #1324)
CI / lint (pull_request) Successful in 3m29s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m24s
CI / release-candidate (pull_request) Has been skipped

This commit is contained in:
timmy committed 2026-08-23 22:38:21 +00:00
1 parent 157703527a
commit 33c8761e80
18 files changed
+287 -89

No files matched your search

+18 -17
View File
@@ -3,12 +3,12 @@
const qs = (s, el=document) => el.querySelector(s);
const announceWork = message => qs('#my-work-action-status').textContent = message;
const fmt = (d) => new Date(d).toLocaleString();
const mobileAppBadge = createMobileAppBadge({
const appBadge = createMobileAppBadge({
control:qs('#app-badge-control'), status:qs('#app-badge-status'),
container:qs('#app-badge-setting'), navigator, storage:localStorage,
serviceWorker:navigator.serviceWorker,
});
mobileAppBadge.start();
appBadge.start();
const cardPlanning = createCardPlanning(document);
const mobileComposerViewport = createMobileComposerViewport({
viewport: window.visualViewport,
@@ -103,21 +103,22 @@
const result = await (authored ? authoredOutbox : issueOutbox).retry(item.outbox_id, activeFlushLogin);
(authored ? applyAuthoredOutboxResult : applyOutboxResult)(result);
}
let mobileQueueCounts = {};
let mobilePreparationItems = {};
let queueCounts = {};
let preparationItems = {};
const followingQueue = attachFollowing(item => {
searchPreviewReturnKind = 'following';
return searchPreview.open(item);
}, {
onCount:(count, items) => {
mobileQueueCounts.following = count;
mobileQueueCounts.followingUnavailable = false;
mobilePreparationItems.following = items.filter(item => item.has_unseen_change === true);
appBadge.reconcile('following', count, true);
queueCounts.following = count;
queueCounts.followingUnavailable = false;
preparationItems.following = items.filter(item => item.has_unseen_change === true);
mobileStartDay.render();
},
onStatus:status => {
if (status === 'loading') return;
mobileQueueCounts.followingUnavailable = status === 'error';
queueCounts.followingUnavailable = status === 'error';
mobileStartDay.render();
},
onReviewComplete:() => mobileStartDay.completePhase('following'),
@@ -166,7 +167,7 @@
selectFilter: selectMobileQueue,
firstAction: name => qs('#my-work-list .my-work-card-main, #my-work-list .draft-resume, #my-work-list .draft-continue, #my-work-list .draft-edit'),
announce: announceWork,
getCounts: () => mobileQueueCounts,
getCounts: () => queueCounts,
openFindWork: () => qs('#find-work').click(),
});
function openMobileStartDay() {
@@ -201,14 +202,14 @@
findWork: () => qs('#find-work').click(),
});
const mobileStartDay = createMobileStartDay({
getCounts: () => mobileQueueCounts,
getPhaseItems: () => mobilePreparationItems,
getCounts: () => queueCounts,
getPhaseItems: () => preparationItems,
getLogin: () => confirmedOwnerLogin,
openQueue: name => {
const sheet = qs('#mobile-queue-sheet');
if (sheet.open) sheet.close();
return name === 'find' ? qs('#find-work').click() :
name === 'following' ? (mobileQueueCounts.followingUnavailable ? followingQueue.open() :
name === 'following' ? (queueCounts.followingUnavailable ? followingQueue.open() :
followingQueue.review()) : mobileQueueLauncher.open(name);
},
onHandoff: current => {
@@ -1526,7 +1527,7 @@
},
onPagination: pagination => {
notificationPagination = pagination;
mobileAppBadge.reconcile(pagination.total, {authoritative:true});
appBadge.reconcile('updates', pagination.total, true);
const loaded = Math.min(pagination.total, pagination.page * 50);
qs('#notification-page-status').textContent = pagination.total ?
loaded + ' of ' + pagination.total + ' unread updates loaded.' : '';
@@ -3429,7 +3430,7 @@
counts.later = laterMyWork.length;
counts.draft = lastDrafts.length;
counts.delivery = draftInbox.partition(lastDrafts).actionable;
mobilePreparationItems = {
preparationItems = {
delivery:draftInbox.partition(lastDrafts).deliveries,
agenda:agendaMyWork(activeMyWork),
attention:activeMyWork.filter(item => item.needs_attention),
@@ -3450,7 +3451,7 @@
const element = qs('[data-work-count="' + filter + '"]');
if (element) element.textContent = count;
});
mobileQueueCounts = counts;
queueCounts = counts;
mobileStartDay.reconcile({
authoritative:authoritativeMyWorkRefresh,
authoritativePhases:['delivery'],
@@ -8384,8 +8385,8 @@
protectStorage:() => deviceStorage.requestPersistence(),
notificationReadiness:() => pushController?.notificationReadiness()
|| {state:'unavailable', detail:'Update notifications are unavailable.'},
appBadgeReadiness:() => mobileAppBadge.readiness(),
enableAppBadge:() => mobileAppBadge.enable(),
appBadgeReadiness:() => appBadge.readiness(),
enableAppBadge:() => appBadge.enable(),
enablePush:async () => {
const controller = await pushControllerReady;
if (!controller) return;
+1 -1
View File
@@ -215,7 +215,7 @@
<label for="keep-work-offline"><input id="keep-work-offline" type="checkbox" /> Keep My Work available offline</label>
<label for="delivery-receipts"><input id="delivery-receipts" type="checkbox" /> Notify me when queued work finishes</label>
<span class="app-badge-setting" id="app-badge-setting">
<label class="app-badge-control" for="app-badge-control"><input id="app-badge-control" type="checkbox" /> Show unread Updates on the app icon</label>
<label class="app-badge-control" for="app-badge-control"><input id="app-badge-control" type="checkbox" /> Show review attention on the app icon</label>
<span class="small" id="app-badge-status" role="status" aria-live="polite"></span>
</span>
<label class="push-update-control" for="push-updates"><input id="push-updates" type="checkbox" /> Notify me about new updates</label>
+24 -6
View File
@@ -11,9 +11,10 @@
}) {
const ENABLED_KEY = 'stackchain.app-badge.enabled.v1';
let enabled = false;
let confirmedCount = 0;
const confirmedCounts = {updates:0, following:0};
let renderedCount = null;
function available() {
return typeof navigator?.setAppBadge === 'function'
&& typeof navigator?.clearAppBadge === 'function';
@@ -29,7 +30,16 @@
}
}
async function syncCount(channel, count) {
if (!enabled) return;
try {
const registration = await serviceWorker?.ready;
registration?.active?.postMessage({type:'stackchain-app-badge-count', channel, count});
} catch (_error) { /* A later refresh can retry. */ }
}
async function render() {
const confirmedCount = Math.min(9999, confirmedCounts.updates + confirmedCounts.following);
if (!enabled || !available() || renderedCount === confirmedCount) return true;
try {
if (confirmedCount > 0) await navigator.setAppBadge(confirmedCount);
@@ -48,7 +58,13 @@
if (enabled) storage?.setItem(ENABLED_KEY, 'true');
else storage?.removeItem(ENABLED_KEY);
await syncPreference();
if (enabled) {
if (confirmedCounts.updates > 0) await syncCount('updates', confirmedCounts.updates);
if (confirmedCounts.following > 0) await syncCount('following', confirmedCounts.following);
}
if (!enabled && available()) {
confirmedCounts.updates = 0;
confirmedCounts.following = 0;
try {
await navigator.clearAppBadge();
renderedCount = null;
@@ -82,8 +98,8 @@
function readiness() {
if (!available()) return {state:'unavailable', detail:'App icon badges are unavailable in this browser.'};
return enabled
? {state:'complete', detail:'The app icon shows the confirmed unread Updates count.'}
: {state:'incomplete', detail:'Show the confirmed unread Updates count without opening Stackchain.'};
? {state:'complete', detail:'The app icon shows review attention.'}
: {state:'incomplete', detail:'Show review attention without opening Stackchain.'};
}
async function enable() {
@@ -93,9 +109,11 @@
return true;
}
async function reconcile(count, {authoritative = false} = {}) {
if (!authoritative || !Number.isSafeInteger(count) || count < 0) return false;
confirmedCount = count;
async function reconcile(channel, count, authoritative = false) {
if (!Object.hasOwn(confirmedCounts, channel)
|| authoritative !== true || !Number.isSafeInteger(count) || count < 0 || count > 9999) return false;
confirmedCounts[channel] = count;
await syncCount(channel, count);
return render();
}
+63 -13
View File
@@ -1,7 +1,7 @@
const BASE = new URL('./', self.location.href).pathname;
importScripts(BASE + 'static/private-data-registry.js');
importScripts(BASE + 'static/background-issue-sync.js');
const CACHE = 'stackchain-dashboard-shell-v136';
const CACHE = 'stackchain-dashboard-shell-v137';
const OFFLINE_LEASE_URL = new URL(BASE + '__offline-session-lease', self.location.origin).href;
const OUTAGE_STATUSES = new Set([500, 502, 503, 504]);
const NAVIGATION_TIMEOUT_MS = self.__STACKCHAIN_NAVIGATION_TIMEOUT_MS || 4000;
@@ -40,22 +40,55 @@ function createAppBadgePreference() {
});
database.close();
},
async getCounts() {
const database = await open();
const counts = {};
for (const channel of ['updates', 'following']) {
counts[channel] = await new Promise((resolve, reject) => {
const request = database.transaction(storeName, 'readonly').objectStore(storeName).get('count:' + channel);
request.onsuccess = () => resolve(Number.isSafeInteger(request.result) ? request.result : 0);
request.onerror = () => reject(request.error || new Error('App badge count unavailable.'));
});
}
database.close();
return counts;
},
async setCount(channel, count) {
const database = await open();
await new Promise((resolve, reject) => {
const transaction = database.transaction(storeName, 'readwrite');
transaction.objectStore(storeName).put(count, 'count:' + channel);
transaction.oncomplete = resolve;
transaction.onerror = () => reject(transaction.error || new Error('App badge count could not be saved.'));
transaction.onabort = transaction.onerror;
});
database.close();
},
async clearCounts() {
await this.setCount('updates', 0);
await this.setCount('following', 0);
},
};
}
const appBadgePreference = self.__STACKCHAIN_APP_BADGE_PREFERENCE || createAppBadgePreference();
let renderedBackgroundBadgeCount = null;
async function reconcileBackgroundAppBadge(count) {
if (!Number.isSafeInteger(count) || count < 0 || count > 9999
async function reconcileBackgroundAppBadge(channel, count) {
if (!['updates', 'following'].includes(channel)
|| !Number.isSafeInteger(count) || count < 0 || count > 9999
|| typeof self.registration.setAppBadge !== 'function'
|| typeof self.registration.clearAppBadge !== 'function') return false;
let enabled = false;
try { enabled = await appBadgePreference.get(); } catch (_error) { return false; }
if (!enabled || renderedBackgroundBadgeCount === count) return false;
if (!enabled) return false;
try {
if (count > 0) await self.registration.setAppBadge(count);
await appBadgePreference.setCount(channel, count);
const counts = await appBadgePreference.getCounts();
const total = Math.min(9999, counts.updates + counts.following);
if (renderedBackgroundBadgeCount === total) return false;
if (total > 0) await self.registration.setAppBadge(total);
else await self.registration.clearAppBadge();
renderedBackgroundBadgeCount = count;
renderedBackgroundBadgeCount = total;
return true;
} catch (_error) { return false; }
}
@@ -576,6 +609,21 @@ async function updateTodayLockScreen(active, running, rawActionToken = '', rawBr
}
self.addEventListener('message', event => {
if (event.data?.type === 'stackchain-app-badge-count') {
event.waitUntil((async () => {
if (!String(event.source?.url || '').startsWith(self.location.origin + BASE)) return;
const channel = event.data.channel;
const count = event.data.count;
if (!['updates', 'following'].includes(channel)
|| !Number.isSafeInteger(count) || count < 0 || count > 9999) return;
try {
if (await appBadgePreference.get()) {
await appBadgePreference.setCount(channel, count);
renderedBackgroundBadgeCount = null;
}
} catch (_error) { /* A later authoritative refresh can restore the count. */ }
})());
}
if (event.data?.type === 'stackchain-app-badge-preference') {
event.waitUntil((async () => {
if (!String(event.source?.url || '').startsWith(self.location.origin + BASE)) return;
@@ -584,6 +632,7 @@ self.addEventListener('message', event => {
await appBadgePreference.set(enabled);
renderedBackgroundBadgeCount = null;
if (!enabled && typeof self.registration.clearAppBadge === 'function') {
await appBadgePreference.clearCounts();
await self.registration.clearAppBadge();
}
} catch (_error) { /* Page preference remains authoritative on next launch. */ }
@@ -693,14 +742,15 @@ self.addEventListener('push', event => {
&& followingCount > 0
&& followingCount <= 50
) {
event.waitUntil(self.registration.showNotification(
followingCount + ' watched item' + (followingCount === 1 ? '' : 's') + ' changed',
{
event.waitUntil(Promise.all([
reconcileBackgroundAppBadge('following', followingCount),
self.registration.showNotification(
followingCount + ' watched item' + (followingCount === 1 ? '' : 's') + ' changed', {
body: 'Open Following to review the latest activity.',
tag,
data: {route},
}
));
}),
]));
return;
}
if (
@@ -711,7 +761,7 @@ self.addEventListener('push', event => {
&& updateCount <= 50
) {
event.waitUntil(Promise.all([
reconcileBackgroundAppBadge(unreadCount),
reconcileBackgroundAppBadge('updates', unreadCount),
self.registration.showNotification(updateCount + ' new work updates', {
body: 'Tap to review them in Stackchain.', tag, data: {route},
}),
@@ -736,7 +786,7 @@ self.addEventListener('push', event => {
options.data.notificationId = notificationId;
}
event.waitUntil(Promise.all([
reconcileBackgroundAppBadge(unreadCount),
reconcileBackgroundAppBadge('updates', unreadCount),
self.registration.showNotification('New work update', options),
]));
});