feat(web): show pending items on the installed app icon

Keep the Badging API count equal to the primary list's pending items, update it from optimistic changes and the list's SSE stream (shared across pages), and re-sync when the app returns to the foreground.

On iOS the badge needs notification permission, so Settings offers to enable it; Android does not support numeric web app badges.
This commit is contained in:
Jose Selesan
2026-10-29 14:20:21 -03:00
parent 7ed4d27844
commit aa170de8d1
14 changed files with 432 additions and 45 deletions

View File

@@ -0,0 +1,88 @@
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { itemsQueryOptions, usePendingDeletions } from '@/hooks/use-items'
import { useListEvents } from '@/hooks/use-list-events'
import { listsQueryOptions, pickPrimaryList } from '@/hooks/use-lists'
import { APP_BADGE_REFRESH_EVENT, setAppBadge, supportsAppBadge } from '@/lib/app-badge'
import { countPendingItems } from '@/lib/items'
import { isStandalone } from '@/lib/platform'
/**
* Keeps the number on the installed app's icon equal to the items still to buy
* in the primary list — the list the home page opens. It follows that list's SSE
* stream even from other pages, so a change made by another member updates the
* badge too, and re-syncs whenever the app comes back to the foreground (iOS
* suspends the page, and with it the stream, in the background).
*
* Only runs in the installed app: browsers show the badge nowhere else.
*/
export function useAppBadge() {
const queryClient = useQueryClient()
const active = isStandalone() && supportsAppBadge()
const { data: lists } = useQuery({ ...listsQueryOptions(), enabled: active })
const primaryList = lists ? pickPrimaryList(lists) : undefined
const listId = primaryList?.id
const { data: items } = useQuery({
...itemsQueryOptions(listId ?? ''),
enabled: active && Boolean(listId),
})
const deletingIds = usePendingDeletions()
// Permission can be granted while the app is open (see the settings card); the
// data does not change, so the effect is nudged through this event.
const [refreshToken, setRefreshToken] = useState(0)
useEffect(() => {
const refresh = () => setRefreshToken((token) => token + 1)
window.addEventListener(APP_BADGE_REFRESH_EVENT, refresh)
return () => window.removeEventListener(APP_BADGE_REFRESH_EVENT, refresh)
}, [])
useEffect(() => {
if (!active) return
// Re-run after a permission change even though the data is the same.
void refreshToken
// Lists still loading: keep whatever the badge already shows instead of
// flickering to zero (or clearing) on every launch.
if (!lists) return
if (!listId) {
void setAppBadge(0)
return
}
if (!items) return
void setAppBadge(countPendingItems(items, deletingIds))
}, [active, lists, listId, items, deletingIds, refreshToken])
// The icon outlives the page: signing out should not leave somebody else's
// pending items on it.
useEffect(() => {
if (!active) return
return () => void setAppBadge(0)
}, [active])
// Remote additions to the primary list while another page is open.
useListEvents(active ? listId : undefined)
useEffect(() => {
if (!active) return
const refresh = () => {
if (document.visibilityState !== 'visible') return
void queryClient.invalidateQueries({ queryKey: ['lists'] })
if (listId) void queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
}
document.addEventListener('visibilitychange', refresh)
window.addEventListener('online', refresh)
return () => {
document.removeEventListener('visibilitychange', refresh)
window.removeEventListener('online', refresh)
}
}, [active, listId, queryClient])
}

View File

@@ -1,5 +1,7 @@
import * as React from 'react'
import { isIos, isStandalone } from '@/lib/platform'
/**
* `beforeinstallprompt` is still non-standard, so TypeScript has no DOM type
* for it. This is the subset of the event we use.
@@ -20,23 +22,13 @@ function readDismissed() {
}
}
function isStandalone() {
if (typeof window === 'undefined') return false
const navigatorWithStandalone = navigator as Navigator & { standalone?: boolean }
return (
window.matchMedia('(display-mode: standalone)').matches ||
navigatorWithStandalone.standalone === true
)
}
function isIosSafari() {
if (typeof navigator === 'undefined') return false
const ua = navigator.userAgent
const isIos = /iphone|ipad|ipod/i.test(ua)
// On iOS only Safari can add apps to the home screen, and it never fires
// `beforeinstallprompt`, so we detect it to show manual instructions.
const isSafari = /safari/i.test(ua) && !/crios|fxios|edgios/i.test(ua)
return isIos && isSafari
const isSafari =
/safari/i.test(navigator.userAgent) && !/crios|fxios|edgios/i.test(navigator.userAgent)
return isIos() && isSafari
}
export type InstallPromptState = {
@@ -58,7 +50,7 @@ export function useInstallPrompt(): InstallPromptState {
const [deferredPrompt, setDeferredPrompt] = React.useState<BeforeInstallPromptEvent | null>(null)
const [isInstalled, setIsInstalled] = React.useState(isStandalone)
const [isDismissed, setIsDismissed] = React.useState(readDismissed)
const [isIos] = React.useState(isIosSafari)
const [isIosSafariDevice] = React.useState(isIosSafari)
React.useEffect(() => {
const onBeforeInstallPrompt = (event: Event) => {
@@ -97,7 +89,7 @@ export function useInstallPrompt(): InstallPromptState {
}, [])
const canInstall = deferredPrompt !== null
const needsManualInstructions = isIos && !deferredPrompt && !isInstalled
const needsManualInstructions = isIosSafariDevice && !deferredPrompt && !isInstalled
return {
canInstall,

View File

@@ -1,47 +1,35 @@
import { useQueryClient } from '@tanstack/react-query'
import { useEffect } from 'react'
import { apiBaseUrl } from '@/lib/api-client'
import { LIST_EVENT_TYPES, queryKeysForListEvent } from '@/lib/list-events'
import { queryKeysForListEvent } from '@/lib/list-events'
import { subscribeToListEvents } from '@/lib/list-events-stream'
/**
* Subscribes to a list's SSE stream (`GET /lists/:listId/events`) and refreshes
* the affected queries whenever another member adds or buys an item, invites
* Follows a list's SSE stream (`GET /lists/:listId/events`) and refreshes the
* affected queries whenever another member adds or buys an item, invites
* somebody or renames the list — so the page updates without a reload.
*
* The session cookie is sent via `withCredentials`. `EventSource` reconnects on
* its own; a `ready` event is emitted on every (re)connection, used here to
* reconcile anything missed while disconnected.
* reconcile anything missed while disconnected. The connection is shared with
* any other subscriber of the same list (see `list-events-stream.ts`).
*
* Pass `undefined` to follow nothing (e.g. while the primary list is unknown).
*/
export function useListEvents(listId: string) {
export function useListEvents(listId: string | undefined) {
const queryClient = useQueryClient()
useEffect(() => {
const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, {
withCredentials: true,
})
if (!listId) return
const onReady = () => {
queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
}
source.addEventListener('ready', onReady)
const listeners = LIST_EVENT_TYPES.map((type) => {
const listener = () => {
return subscribeToListEvents(listId, {
onEvent: (type) => {
for (const queryKey of queryKeysForListEvent(type, listId)) {
queryClient.invalidateQueries({ queryKey })
void queryClient.invalidateQueries({ queryKey })
}
}
source.addEventListener(type, listener)
return { type, listener }
},
onReady: () => {
void queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
},
})
return () => {
source.removeEventListener('ready', onReady)
for (const { type, listener } of listeners) source.removeEventListener(type, listener)
source.close()
}
}, [listId, queryClient])
}