Skip to content

Email for professionals and teams

Show the unread inbox count as a PWA app icon badge (#160)

Colin Williams2e1fd849bc5b
diff --git a/public/sw.js b/public/sw.js
index 6c918fb..4134e82 100644
--- a/public/sw.js
+++ b/public/sw.js
@@ -6,6 +6,19 @@ const DEFAULT_NOTIFICATION = {
url: "/inbox",
};
+async function syncAppBadge() {
+ if (!("setAppBadge" in self.navigator)) return;
+ try {
+ const response = await fetch("/api/messages/counts", { credentials: "include" });
+ if (!response.ok) return;
+ const unread = (await response.json())?.counts?.folders?.inbox?.unread;
+ if (typeof unread !== "number") return;
+ await (unread > 0 ? self.navigator.setAppBadge(unread) : self.navigator.clearAppBadge());
+ } catch {
+ // Leave the badge as it was when the network is down or the API rejects outside an installed app.
+ }
+}
+
self.addEventListener("push", (event) => {
event.waitUntil(
(async () => {
@@ -19,13 +32,16 @@ self.addEventListener("push", (event) => {
// Keep the generic notification if a provider delivers an empty or malformed payload.
}
- await self.registration.showNotification(payload.title, {
- body: payload.body,
- icon: payload.icon,
- badge: payload.badge,
- tag: payload.tag,
- data: { url: payload.url },
- });
+ await Promise.all([
+ self.registration.showNotification(payload.title, {
+ body: payload.body,
+ icon: payload.icon,
+ badge: payload.badge,
+ tag: payload.tag,
+ data: { url: payload.url },
+ }),
+ syncAppBadge(),
+ ]);
})(),
);
});
diff --git a/src/app/(dashboard)/layout.tsx b/src/app/(dashboard)/layout.tsx
index b0dbdfa..ded5fa1 100644
--- a/src/app/(dashboard)/layout.tsx
+++ b/src/app/(dashboard)/layout.tsx
@@ -24,6 +24,7 @@ import clsx from "clsx";
import { useDashboardState } from "./dashboard-state";
import { useAssistantAvailability } from "./use-assistant-availability";
import { RouteTitle } from "@/components/route-title";
+import { useAppBadge } from "@/hooks/use-app-badge";
export default function DashboardLayout({
children,
@@ -34,6 +35,7 @@ export default function DashboardLayout({
const { assistantOpen, setAssistantOpen, assistantFullSize, setAssistantFullSize } = useDashboardState();
const assistantEnabled = useAssistantAvailability();
const assistantVisible = assistantEnabled === true && assistantOpen;
+ useAppBadge();
useEffect(() => {
if (assistantEnabled === false && (assistantOpen || assistantFullSize)) {
diff --git a/src/components/providers.tsx b/src/components/providers.tsx
index 3a44240..65a02e4 100644
--- a/src/components/providers.tsx
+++ b/src/components/providers.tsx
@@ -13,6 +13,7 @@ import { clearMessageClientState } from "@/hooks/utils";
import { clearMessageDetailCache } from "@/lib/messages/detail-cache";
import { clearCurrentUserCache } from "@/hooks/use-current-user";
import { AUTH_SESSION_CHANGED_EVENT } from "@/lib/auth/client";
+import type { AuthSessionChangedDetail } from "@/lib/auth/client-types";
export function Providers({ children, initialBranding }: { children: React.ReactNode; initialBranding?: Branding }) {
const realtime = useMessagePolling();
@@ -32,12 +33,16 @@ export function Providers({ children, initialBranding }: { children: React.React
);
useEffect(() => {
- function resetUserScopedState() {
+ function resetUserScopedState(event: Event) {
client.clear();
clearMailboxClientState();
clearMessageClientState();
clearMessageDetailCache();
clearCurrentUserCache();
+ // The dashboard layout outlives an account switch, so its all-mailbox counts (the app badge) would keep the old account's number.
+ if ((event as CustomEvent<AuthSessionChangedDetail>).detail?.authenticated) {
+ window.dispatchEvent(new Event("mailflare:message-counts-changed"));
+ }
}
window.addEventListener(AUTH_SESSION_CHANGED_EVENT, resetUserScopedState);
diff --git a/src/hooks/use-app-badge.ts b/src/hooks/use-app-badge.ts
new file mode 100644
index 0000000..107ff86
--- /dev/null
+++ b/src/hooks/use-app-badge.ts
@@ -0,0 +1,16 @@
+import { useEffect, useState } from "react";
+import { setAppBadgeCount } from "@/lib/push/app-badge";
+import { useMessageCounts } from "./use-message-counts";
+
+export function useAppBadge() {
+ const [supported] = useState(() => typeof navigator !== "undefined" && "setAppBadge" in navigator);
+ const { counts, isLoading } = useMessageCounts(null, supported);
+ const [placeholderCounts] = useState(counts);
+ const unread = counts.folders.inbox.unread;
+ // The placeholder (before the first load, or after a failed one) must not clear a badge the service worker set.
+ const known = !isLoading && counts !== placeholderCounts;
+
+ useEffect(() => {
+ if (known) setAppBadgeCount(unread);
+ }, [known, unread]);
+}
diff --git a/src/lib/auth/logout.ts b/src/lib/auth/logout.ts
index 74f653c..e68e997 100644
--- a/src/lib/auth/logout.ts
+++ b/src/lib/auth/logout.ts
@@ -1,4 +1,5 @@
import { authFetch, clearClientSessionToken, setClientSessionToken } from "@/lib/auth/client";
+import { setAppBadgeCount } from "@/lib/push/app-badge";
/** Returns true when another signed-in account on this browser took over. */
export async function logoutClientSession(): Promise<boolean> {
@@ -13,6 +14,7 @@ export async function logoutClientSession(): Promise<boolean> {
// Local logout must complete even when the server request is unavailable.
} finally {
clearClientSessionToken();
+ setAppBadgeCount(0);
}
if (!nextToken) return false;
setClientSessionToken(nextToken);
diff --git a/src/lib/push/app-badge.ts b/src/lib/push/app-badge.ts
new file mode 100644
index 0000000..a9e9c4f
--- /dev/null
+++ b/src/lib/push/app-badge.ts
@@ -0,0 +1,6 @@
+export function setAppBadgeCount(count: number): void {
+ if (!("setAppBadge" in navigator)) return;
+ // Browsers reject outside an installed app; the badge is cosmetic, so ignore it.
+ const update = count > 0 ? navigator.setAppBadge(count) : navigator.clearAppBadge();
+ void update.catch(() => {});
+}
diff --git a/tests/pwa-app-badge.test.mjs b/tests/pwa-app-badge.test.mjs
new file mode 100644
index 0000000..405d90f
--- /dev/null
+++ b/tests/pwa-app-badge.test.mjs
@@ -0,0 +1,95 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import vm from "node:vm";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const source = readFileSync(join(root, "public/sw.js"), "utf8");
+
+function countsResponse(unread) {
+ return new Response(JSON.stringify({ counts: { folders: { inbox: { total: 10, unread } } } }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+async function push({ fetchImpl, visible = false }) {
+ const listeners = new Map();
+ const calls = { fetch: [], notifications: [], badge: [] };
+ const self = {
+ addEventListener: (type, listener) => listeners.set(type, listener),
+ location: { origin: "https://mail.example.com" },
+ clients: { matchAll: async () => [{ visibilityState: visible ? "visible" : "hidden" }] },
+ registration: {
+ showNotification: async (title, options) => {
+ calls.notifications.push({ title, options });
+ },
+ },
+ navigator: {
+ setAppBadge: async (count) => {
+ calls.badge.push(["set", count]);
+ },
+ clearAppBadge: async () => {
+ calls.badge.push(["clear"]);
+ },
+ },
+ };
+ const fetch = async (url, init) => {
+ calls.fetch.push({ url, init });
+ return fetchImpl();
+ };
+ vm.runInNewContext(source, { self, fetch, URL, Promise });
+
+ let pending;
+ listeners.get("push")({
+ data: { json: () => ({ title: "Ada", body: "Lunch?" }) },
+ waitUntil: (promise) => {
+ pending = promise;
+ },
+ });
+ await pending;
+ return calls;
+}
+
+test("a hidden push sets the badge to the all-mailbox inbox unread count", async () => {
+ const calls = await push({ fetchImpl: () => countsResponse(7) });
+ assert.deepEqual(calls.badge, [["set", 7]]);
+ assert.equal(calls.fetch.length, 1);
+ assert.equal(calls.fetch[0].url, "/api/messages/counts");
+ assert.equal(calls.fetch[0].init.credentials, "include");
+ assert.equal(calls.notifications.length, 1);
+ assert.equal(calls.notifications[0].title, "Ada");
+});
+
+test("a zero unread count clears the badge", async () => {
+ const calls = await push({ fetchImpl: () => countsResponse(0) });
+ assert.deepEqual(calls.badge, [["clear"]]);
+ assert.equal(calls.notifications.length, 1);
+});
+
+test("an unauthorized counts response leaves the badge untouched", async () => {
+ const calls = await push({ fetchImpl: () => new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }) });
+ assert.equal(calls.fetch.length, 1);
+ assert.deepEqual(calls.badge, []);
+ assert.equal(calls.notifications.length, 1);
+});
+
+test("a failed counts fetch leaves the badge untouched", async () => {
+ const calls = await push({
+ fetchImpl: () => {
+ throw new TypeError("Failed to fetch");
+ },
+ });
+ assert.equal(calls.fetch.length, 1);
+ assert.deepEqual(calls.badge, []);
+ assert.equal(calls.notifications.length, 1);
+});
+
+test("a visible window skips the notification, the fetch and the badge", async () => {
+ const calls = await push({ fetchImpl: () => countsResponse(3), visible: true });
+ assert.deepEqual(calls.fetch, []);
+ assert.deepEqual(calls.badge, []);
+ assert.deepEqual(calls.notifications, []);
+});