diff --git a/AGENTS.md b/AGENTS.md index bdffc5a..c8a55ce 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 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`). +- **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` 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 diff --git a/apps/web/src/components/app-badge.tsx b/apps/web/src/components/app-badge.tsx new file mode 100644 index 0000000..916ddb2 --- /dev/null +++ b/apps/web/src/components/app-badge.tsx @@ -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 +} diff --git a/apps/web/src/components/settings/app-badge-card.tsx b/apps/web/src/components/settings/app-badge-card.tsx new file mode 100644 index 0000000..c071175 --- /dev/null +++ b/apps/web/src/components/settings/app-badge-card.tsx @@ -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 ( + + + Indicador en el ícono + + 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. + + + + {!supported ? ( +

+ Este navegador no permite mostrar números en el ícono. En Android, Chrome solo muestra + un punto cuando la app tiene avisos. +

+ ) : !installed ? ( +

+ Abre Superlist desde su ícono (la app instalada) para activar el indicador. +

+ ) : needsPermission ? ( + <> +

+ 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. +

+ + + ) : permission === 'denied' ? ( +

+ Bloqueaste los avisos para Superlist. Actívalos en los ajustes de iOS para ver el número + en el ícono. +

+ ) : ( +

+ Activo: el número sigue a los artículos pendientes de tu lista principal. +

+ )} +
+
+ ) +} diff --git a/apps/web/src/hooks/use-app-badge.ts b/apps/web/src/hooks/use-app-badge.ts new file mode 100644 index 0000000..d0a8115 --- /dev/null +++ b/apps/web/src/hooks/use-app-badge.ts @@ -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]) +} diff --git a/apps/web/src/hooks/use-install-prompt.ts b/apps/web/src/hooks/use-install-prompt.ts index 6b2f41e..7800bb0 100644 --- a/apps/web/src/hooks/use-install-prompt.ts +++ b/apps/web/src/hooks/use-install-prompt.ts @@ -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(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, diff --git a/apps/web/src/hooks/use-list-events.ts b/apps/web/src/hooks/use-list-events.ts index 14f56a9..9eedb41 100644 --- a/apps/web/src/hooks/use-list-events.ts +++ b/apps/web/src/hooks/use-list-events.ts @@ -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]) } diff --git a/apps/web/src/lib/app-badge.test.ts b/apps/web/src/lib/app-badge.test.ts new file mode 100644 index 0000000..6db2dcb --- /dev/null +++ b/apps/web/src/lib/app-badge.test.ts @@ -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 + clearAppBadge?: () => Promise +} + +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() + }) +}) diff --git a/apps/web/src/lib/app-badge.ts b/apps/web/src/lib/app-badge.ts new file mode 100644 index 0000000..60bf225 --- /dev/null +++ b/apps/web/src/lib/app-badge.ts @@ -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 { + 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)) +} diff --git a/apps/web/src/lib/items.test.ts b/apps/web/src/lib/items.test.ts index e7c5050..c514a1f 100644 --- a/apps/web/src/lib/items.test.ts +++ b/apps/web/src/lib/items.test.ts @@ -1,7 +1,7 @@ import type { ListItem } from '@superlist/shared' import { describe, expect, it } from 'vitest' -import { quantityLabel, splitItems } from './items' +import { countPendingItems, quantityLabel, splitItems } from './items' function item(overrides: Partial): ListItem { 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', () => { it('shows quantities with a unit, litres in capitals', () => { expect(quantityLabel('2 l')).toBe('2 L') diff --git a/apps/web/src/lib/items.ts b/apps/web/src/lib/items.ts index 3280269..aba6ad2 100644 --- a/apps/web/src/lib/items.ts +++ b/apps/web/src/lib/items.ts @@ -40,6 +40,24 @@ export function splitItems(items: ListItem[], now: Date): SplitItems { 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 = 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 "×". */ const BARE_WEIGHT_FROM = 50 diff --git a/apps/web/src/lib/list-events-stream.ts b/apps/web/src/lib/list-events-stream.ts new file mode 100644 index 0000000..58abbf1 --- /dev/null +++ b/apps/web/src/lib/list-events-stream.ts @@ -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 +} + +/** + * 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() + +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) + } + } +} diff --git a/apps/web/src/lib/platform.ts b/apps/web/src/lib/platform.ts new file mode 100644 index 0000000..9c614e6 --- /dev/null +++ b/apps/web/src/lib/platform.ts @@ -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 + ) +} diff --git a/apps/web/src/routes/_authenticated/route.tsx b/apps/web/src/routes/_authenticated/route.tsx index a70df32..27e3988 100644 --- a/apps/web/src/routes/_authenticated/route.tsx +++ b/apps/web/src/routes/_authenticated/route.tsx @@ -1,4 +1,5 @@ import { createFileRoute, Outlet, redirect } from '@tanstack/react-router' +import { AppBadge } from '@/components/app-badge' import { InstallPrompt } from '@/components/install-prompt' import { AppHeader } from '@/components/layout/app-header' import { AppSidebar } from '@/components/layout/app-sidebar' @@ -37,6 +38,7 @@ function AuthenticatedLayout() { return ( + diff --git a/apps/web/src/routes/_authenticated/settings.tsx b/apps/web/src/routes/_authenticated/settings.tsx index c6072fb..6ddd0dd 100644 --- a/apps/web/src/routes/_authenticated/settings.tsx +++ b/apps/web/src/routes/_authenticated/settings.tsx @@ -4,6 +4,7 @@ import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react' import { useForm } from 'react-hook-form' import { toast } from 'sonner' import { z } from 'zod' +import { AppBadgeCard } from '@/components/settings/app-badge-card' import { PasskeysCard } from '@/components/settings/passkeys-card' import { type Theme, useTheme } from '@/components/theme-provider' import { Button } from '@/components/ui/button' @@ -24,6 +25,7 @@ function SettingsPage() {
+