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

@@ -281,6 +281,14 @@ apps/web/src/
hook (`use-list-events.ts`) reuses it, so the browser calls `/api/*` on the current origin: Vite proxies it hook (`use-list-events.ts`) reuses it, so the browser calls `/api/*` on the current origin: Vite proxies it
to `:4100` in dev and nginx does in production. `VITE_API_URL` is an optional override for a separate API to `:4100` in dev and nginx does in production. `VITE_API_URL` is an optional override for a separate API
origin, and `auth-client.ts` defaults `baseURL` to `window.location.origin` (BetterAuth appends `/api/auth`). origin, and `auth-client.ts` defaults `baseURL` to `window.location.origin` (BetterAuth appends `/api/auth`).
- **Icon badge**: the installed PWA shows the pending items of the primary list on its icon through the Badging
API (`lib/app-badge.ts`). `hooks/use-app-badge.ts`, mounted by the authenticated layout, follows that list's
SSE stream even from other pages (the shared `lib/list-events-stream.ts` avoids opening a second stream) and
re-syncs on foreground. It only runs in standalone mode; iOS additionally needs notification permission,
requested from the settings card (`components/settings/app-badge-card.tsx`) because WebKit only grants
badging alongside notifications. Chrome on Android does not support numeric badges (notifications show a
dot), so this is a progressive enhancement. Updating the badge while the app is closed would need Web Push,
which is not implemented.
- **Forms: React Hook Form + Zod** (`zodResolver`). Render errors with the shadcn `Field`/`FieldError` - **Forms: React Hook Form + Zod** (`zodResolver`). Render errors with the shadcn `Field`/`FieldError`
components — this registry version ships `field` instead of the older `form` component. components — this registry version ships `field` instead of the older `form` component.
- **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them - **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them

View File

@@ -0,0 +1,10 @@
import { useAppBadge } from '@/hooks/use-app-badge'
/**
* Keeps the installed app's icon badge in sync with the primary list. It renders
* nothing: the icon lives outside the page.
*/
export function AppBadge() {
useAppBadge()
return null
}

View File

@@ -0,0 +1,76 @@
import { BellRingIcon } from 'lucide-react'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { refreshAppBadge, supportsAppBadge } from '@/lib/app-badge'
import { isIos, isStandalone } from '@/lib/platform'
type Permission = NotificationPermission | 'unsupported'
function readPermission(): Permission {
return typeof Notification === 'undefined' ? 'unsupported' : Notification.permission
}
/**
* Explains the icon badge and, on iOS, asks for the notification permission the
* system requires before showing it. Elsewhere the badge works without asking.
*/
export function AppBadgeCard() {
const [permission, setPermission] = useState(readPermission)
const supported = supportsAppBadge()
const installed = isStandalone()
const needsPermission = supported && installed && isIos() && permission === 'default'
const enable = async () => {
if (typeof Notification === 'undefined') return
const result = await Notification.requestPermission()
setPermission(result)
if (result === 'granted') refreshAppBadge()
}
return (
<Card>
<CardHeader>
<CardTitle>Indicador en el ícono</CardTitle>
<CardDescription>
Muestra cuántos artículos quedan por comprar en tu lista principal, en el ícono de la app
instalada. Se actualiza solo cuando agregas o compras artículos, aquí o desde otro móvil.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{!supported ? (
<p className="text-muted-foreground text-sm">
Este navegador no permite mostrar números en el ícono. En Android, Chrome solo muestra
un punto cuando la app tiene avisos.
</p>
) : !installed ? (
<p className="text-muted-foreground text-sm">
Abre Superlist desde su ícono (la app instalada) para activar el indicador.
</p>
) : needsPermission ? (
<>
<p className="text-muted-foreground text-sm">
En iPhone y iPad, el sistema pide permiso de avisos para mostrar el número en el
ícono. No enviamos notificaciones: solo usamos el permiso para el indicador.
</p>
<Button size="sm" className="self-start" onClick={enable}>
<BellRingIcon className="size-4" />
Activar indicador
</Button>
</>
) : permission === 'denied' ? (
<p className="text-muted-foreground text-sm">
Bloqueaste los avisos para Superlist. Actívalos en los ajustes de iOS para ver el número
en el ícono.
</p>
) : (
<p className="text-muted-foreground text-sm">
Activo: el número sigue a los artículos pendientes de tu lista principal.
</p>
)}
</CardContent>
</Card>
)
}

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

View File

@@ -1,47 +1,35 @@
import { useQueryClient } from '@tanstack/react-query' import { useQueryClient } from '@tanstack/react-query'
import { useEffect } from 'react' import { useEffect } from 'react'
import { queryKeysForListEvent } from '@/lib/list-events'
import { apiBaseUrl } from '@/lib/api-client' import { subscribeToListEvents } from '@/lib/list-events-stream'
import { LIST_EVENT_TYPES, queryKeysForListEvent } from '@/lib/list-events'
/** /**
* Subscribes to a list's SSE stream (`GET /lists/:listId/events`) and refreshes * Follows a list's SSE stream (`GET /lists/:listId/events`) and refreshes the
* the affected queries whenever another member adds or buys an item, invites * affected queries whenever another member adds or buys an item, invites
* somebody or renames the list — so the page updates without a reload. * somebody or renames the list — so the page updates without a reload.
* *
* The session cookie is sent via `withCredentials`. `EventSource` reconnects on * The session cookie is sent via `withCredentials`. `EventSource` reconnects on
* its own; a `ready` event is emitted on every (re)connection, used here to * 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() const queryClient = useQueryClient()
useEffect(() => { useEffect(() => {
const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, { if (!listId) return
withCredentials: true,
})
const onReady = () => { return subscribeToListEvents(listId, {
queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }) onEvent: (type) => {
}
source.addEventListener('ready', onReady)
const listeners = LIST_EVENT_TYPES.map((type) => {
const listener = () => {
for (const queryKey of queryKeysForListEvent(type, listId)) { for (const queryKey of queryKeysForListEvent(type, listId)) {
queryClient.invalidateQueries({ queryKey }) void queryClient.invalidateQueries({ queryKey })
} }
} },
onReady: () => {
source.addEventListener(type, listener) void queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
return { type, listener } },
}) })
return () => {
source.removeEventListener('ready', onReady)
for (const { type, listener } of listeners) source.removeEventListener(type, listener)
source.close()
}
}, [listId, queryClient]) }, [listId, queryClient])
} }

View File

@@ -0,0 +1,56 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { setAppBadge, supportsAppBadge } from './app-badge'
type BadgingNavigator = Navigator & {
setAppBadge?: (contents?: number) => Promise<void>
clearAppBadge?: () => Promise<void>
}
const badging = navigator as BadgingNavigator
afterEach(() => {
Reflect.deleteProperty(badging, 'setAppBadge')
Reflect.deleteProperty(badging, 'clearAppBadge')
})
describe('supportsAppBadge', () => {
it('is false when the browser has no Badging API', () => {
expect(supportsAppBadge()).toBe(false)
})
it('is true when setAppBadge is available', () => {
badging.setAppBadge = () => Promise.resolve()
expect(supportsAppBadge()).toBe(true)
})
})
describe('setAppBadge', () => {
it('shows the count on the icon', async () => {
const set = vi.fn(() => Promise.resolve())
badging.setAppBadge = set
badging.clearAppBadge = () => Promise.resolve()
await setAppBadge(4)
expect(set).toHaveBeenCalledWith(4)
})
it('clears the badge when nothing is pending', async () => {
const clear = vi.fn(() => Promise.resolve())
badging.setAppBadge = () => Promise.resolve()
badging.clearAppBadge = clear
await setAppBadge(0)
expect(clear).toHaveBeenCalledOnce()
})
it('ignores a rejected call (not installed, permission denied)', async () => {
badging.setAppBadge = () => Promise.reject(new Error('NotAllowedError'))
badging.clearAppBadge = () => Promise.resolve()
await expect(setAppBadge(2)).resolves.toBeUndefined()
})
})

View File

@@ -0,0 +1,39 @@
/**
* Name of the window event used to ask `useAppBadge` for a fresh sync (for
* example right after the user grants notification permission, which the
* effect cannot observe on its own).
*/
export const APP_BADGE_REFRESH_EVENT = 'superlist:app-badge-refresh'
/** Whether this browser can show a badge on the installed app's icon. */
export function supportsAppBadge(): boolean {
return typeof navigator !== 'undefined' && 'setAppBadge' in navigator
}
/**
* Writes `count` on the icon of the installed app (Badging API). Zero removes
* the badge. Browsers without support, calls made from a tab instead of the
* installed app, and platforms where the permission is missing (iOS needs
* notifications allowed) reject the promise; the badge simply stays as it was.
*/
export function setAppBadge(count: number): Promise<void> {
if (!supportsAppBadge()) return Promise.resolve()
const value = Math.max(0, Math.trunc(count))
const request =
value > 0
? navigator.setAppBadge(value)
: navigator.clearAppBadge
? navigator.clearAppBadge()
: Promise.resolve()
return request.catch(() => {
// Not installed, permission denied or document not fully active: a badge is
// a hint, never something worth breaking a render or logging an error for.
})
}
/** Asks the badge sync to run again, even when no data changed. */
export function refreshAppBadge() {
if (typeof window !== 'undefined') window.dispatchEvent(new Event(APP_BADGE_REFRESH_EVENT))
}

View File

@@ -1,7 +1,7 @@
import type { ListItem } from '@superlist/shared' import type { ListItem } from '@superlist/shared'
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { quantityLabel, splitItems } from './items' import { countPendingItems, quantityLabel, splitItems } from './items'
function item(overrides: Partial<ListItem>): ListItem { function item(overrides: Partial<ListItem>): ListItem {
return { return {
@@ -86,6 +86,28 @@ describe('splitItems', () => {
}) })
}) })
describe('countPendingItems', () => {
it('counts only the items still to buy', () => {
const items = [
item({ id: 'a' }),
item({ id: 'b' }),
item({ id: 'c', completed: true, boughtAt: new Date(2026, 9, 15, 9, 0).toISOString() }),
]
expect(countPendingItems(items)).toBe(2)
})
it('ignores items that are already hidden by a pending deletion', () => {
const items = [item({ id: 'a' }), item({ id: 'b' })]
expect(countPendingItems(items, new Set(['b']))).toBe(1)
})
it('is zero for an empty list', () => {
expect(countPendingItems([])).toBe(0)
})
})
describe('quantityLabel', () => { describe('quantityLabel', () => {
it('shows quantities with a unit, litres in capitals', () => { it('shows quantities with a unit, litres in capitals', () => {
expect(quantityLabel('2 l')).toBe('2 L') expect(quantityLabel('2 l')).toBe('2 L')

View File

@@ -40,6 +40,24 @@ export function splitItems(items: ListItem[], now: Date): SplitItems {
return { pending, boughtToday } return { pending, boughtToday }
} }
/**
* How many items are still to buy. `hidden` holds ids that are already gone
* from the UI (a deletion waiting for undo), so a row the user no longer sees
* never counts.
*/
export function countPendingItems(
items: ListItem[],
hidden: ReadonlySet<string> = new Set(),
): number {
let count = 0
for (const item of items) {
if (!item.completed && !hidden.has(item.id)) count++
}
return count
}
/** Bare amounts from here up are weights ("400 de jamón"), not counts: no "×". */ /** Bare amounts from here up are weights ("400 de jamón"), not counts: no "×". */
const BARE_WEIGHT_FROM = 50 const BARE_WEIGHT_FROM = 50

View File

@@ -0,0 +1,66 @@
import type { ListEventType } from '@superlist/shared'
import { apiBaseUrl } from './api-client'
import { LIST_EVENT_TYPES } from './list-events'
type Subscriber = {
onEvent: (type: ListEventType) => void
onReady: () => void
}
type Stream = {
source: EventSource
subscribers: Set<Subscriber>
}
/**
* One `EventSource` per list, shared by every hook that needs it: the item list
* and the app badge both follow the primary list, and opening two streams to the
* same endpoint would only duplicate requests and invalidations.
*/
const streams = new Map<string, Stream>()
function createStream(listId: string): Stream {
const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, {
withCredentials: true,
})
const stream: Stream = { source, subscribers: new Set() }
for (const type of LIST_EVENT_TYPES) {
source.addEventListener(type, () => {
for (const subscriber of stream.subscribers) subscriber.onEvent(type)
})
}
// Emitted on every (re)connection: anything missed while disconnected has to
// be fetched again.
source.addEventListener('ready', () => {
for (const subscriber of stream.subscribers) subscriber.onReady()
})
return stream
}
/**
* Follows a list's stream while at least one subscriber exists. The connection
* opens with the first one and closes with the last; returns the unsubscribe.
*/
export function subscribeToListEvents(listId: string, subscriber: Subscriber): () => void {
let stream = streams.get(listId)
if (!stream) {
stream = createStream(listId)
streams.set(listId, stream)
}
stream.subscribers.add(subscriber)
return () => {
stream.subscribers.delete(subscriber)
if (stream.subscribers.size === 0) {
stream.source.close()
streams.delete(listId)
}
}
}

View File

@@ -0,0 +1,20 @@
/** iOS or iPadOS (which reports a desktop Mac user agent). */
export function isIos() {
if (typeof navigator === 'undefined') return false
return (
/iphone|ipad|ipod/i.test(navigator.userAgent) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
)
}
/** The app is running as an installed PWA instead of in a browser tab. */
export 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
)
}

View File

@@ -1,4 +1,5 @@
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router' import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'
import { AppBadge } from '@/components/app-badge'
import { InstallPrompt } from '@/components/install-prompt' import { InstallPrompt } from '@/components/install-prompt'
import { AppHeader } from '@/components/layout/app-header' import { AppHeader } from '@/components/layout/app-header'
import { AppSidebar } from '@/components/layout/app-sidebar' import { AppSidebar } from '@/components/layout/app-sidebar'
@@ -37,6 +38,7 @@ function AuthenticatedLayout() {
return ( return (
<SidebarProvider> <SidebarProvider>
<AppBadge />
<AppSidebar /> <AppSidebar />
<SidebarInset> <SidebarInset>
<AppHeader /> <AppHeader />

View File

@@ -4,6 +4,7 @@ import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
import { useForm } from 'react-hook-form' import { useForm } from 'react-hook-form'
import { toast } from 'sonner' import { toast } from 'sonner'
import { z } from 'zod' import { z } from 'zod'
import { AppBadgeCard } from '@/components/settings/app-badge-card'
import { PasskeysCard } from '@/components/settings/passkeys-card' import { PasskeysCard } from '@/components/settings/passkeys-card'
import { type Theme, useTheme } from '@/components/theme-provider' import { type Theme, useTheme } from '@/components/theme-provider'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
@@ -24,6 +25,7 @@ function SettingsPage() {
<div className="mx-auto grid w-full max-w-2xl gap-4 md:gap-6"> <div className="mx-auto grid w-full max-w-2xl gap-4 md:gap-6">
<ProfileCard /> <ProfileCard />
<PasskeysCard /> <PasskeysCard />
<AppBadgeCard />
<AppearanceCard /> <AppearanceCard />
<Card> <Card>