From e5d6beb7819f080b3954288d5cbbb66f882a4f95 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Thu, 19 Nov 2026 19:18:37 -0500 Subject: [PATCH] feat: no connection screen on web and mobile - Replace page content with a no-connection screen linking to Downloads when the network or server is unreachable; Downloads and the player stay usable - Detect it from the Convex socket plus Next's useOffline on web and expo-network on mobile, and recover on reconnect - Keep pages and app code in the service worker so reloads and launches work offline instead of showing the browser's offline page Co-Authored-By: Claude Opus 5.5 --- apps/mobile/components/offline-overlay.tsx | 109 +++++++++ apps/mobile/components/tab-screen-content.tsx | 47 +++- apps/mobile/package.json | 1 + apps/web/app/(app)/layout.tsx | 5 +- apps/web/components/app-sidebar.tsx | 32 ++- apps/web/components/downloads-provider.tsx | 26 ++ apps/web/components/downloads-view.tsx | 28 +-- apps/web/components/offline-gate.tsx | 101 ++++++++ apps/web/hooks/use-downloads.ts | 3 +- apps/web/lib/downloads.ts | 45 +++- apps/web/next.config.ts | 3 + apps/web/public/downloads-sw.js | 231 ++++++++++++++++-- packages/convex/client/connectivity.ts | 103 ++++++++ packages/convex/package.json | 4 + pnpm-lock.yaml | 14 ++ 15 files changed, 697 insertions(+), 55 deletions(-) create mode 100644 apps/mobile/components/offline-overlay.tsx create mode 100644 apps/web/components/offline-gate.tsx create mode 100644 packages/convex/client/connectivity.ts diff --git a/apps/mobile/components/offline-overlay.tsx b/apps/mobile/components/offline-overlay.tsx new file mode 100644 index 0000000..0dcfa4a --- /dev/null +++ b/apps/mobile/components/offline-overlay.tsx @@ -0,0 +1,109 @@ +import { Ionicons } from "@expo/vector-icons" +import { + connectivityStore, + type PlatformNetwork, +} from "@otunes/convex/client/connectivity" +import { useConvex } from "convex/react" +import { + addNetworkStateListener, + getNetworkStateAsync, + type NetworkState, +} from "expo-network" +import { useTheme } from "expo-router" +import { useContext, useSyncExternalStore } from "react" +import { Pressable, StyleSheet, Text, View } from "react-native" + +import { useAppNavigation } from "@/lib/app-navigation" +import { TabletSectionContext } from "@/lib/tablet-navigation" +import { spacing, useThemeColors } from "@/lib/theme" + +let deviceOnline = true + +/** The device's network state. Unknown reachability counts as online. */ +const deviceNetwork: PlatformNetwork = { + isOnline: () => deviceOnline, + subscribe(onChange) { + const apply = (state: NetworkState) => { + deviceOnline = + state.isConnected !== false && state.isInternetReachable !== false + onChange() + } + const subscription = addNetworkStateListener(apply) + void getNetworkStateAsync().then(apply) + return () => subscription.remove() + }, +} + +/** True while the device has no network or the server can't be reached. */ +export function useIsOffline() { + const store = connectivityStore(useConvex(), deviceNetwork) + return useSyncExternalStore(store.subscribe, store.getSnapshot) +} + +type ScreenRoute = { name: string; params?: object } + +/** Downloads screens, and albums and playlists opened from them, stay usable offline. */ +function worksOffline(route: ScreenRoute, tabletSection: string | undefined) { + if (route.name.startsWith("downloads/")) return true + if (route.name === "index" && tabletSection === "downloads") return true + // Settings stays reachable so an unreachable server can be changed. + if (route.name === "settings") return true + return (route.params as { from?: string } | undefined)?.from === "downloads" +} + +/** + * Covers a tab screen with a no-connection message while offline. The screen + * stays mounted underneath so it picks up where it was once the server is back. + */ +export function OfflineOverlay({ route }: { route: ScreenRoute }) { + const offline = useIsOffline() + const tabletSection = useContext(TabletSectionContext)?.name + const { push } = useAppNavigation() + const { colors: routerColors } = useTheme() + const colors = useThemeColors() + + if (!offline || worksOffline(route, tabletSection)) return null + + return ( + + + + No connection + + + Your downloads still play. + + push("/downloads")} + > + + Go to Downloads + + + + ) +} + +const styles = StyleSheet.create({ + overlay: { + alignItems: "center", + justifyContent: "center", + gap: spacing.sm, + padding: spacing.lg, + }, + title: { fontSize: 17, fontWeight: "600", marginTop: spacing.xs }, + body: { fontSize: 15, textAlign: "center" }, + link: { fontSize: 15, fontWeight: "600", marginTop: spacing.xs }, +}) diff --git a/apps/mobile/components/tab-screen-content.tsx b/apps/mobile/components/tab-screen-content.tsx index a5e8a3f..e1634af 100644 --- a/apps/mobile/components/tab-screen-content.tsx +++ b/apps/mobile/components/tab-screen-content.tsx @@ -5,16 +5,46 @@ import type { ReactNode } from "react" import { useTabletBackgroundStyle } from "@/contexts/android-tab-theme" import { TabletPlayerLayoutSync } from "@/contexts/tablet-player-layout" +import { OfflineOverlay } from "@/components/offline-overlay" import { TabletSidebar } from "@/components/tablet-sidebar" +type ScreenRoute = { name: string; params?: object } + +/** + * Screen content with the no-connection overlay layered on top. A fragment + * keeps the scroll view as the screen's first subview for large titles. + */ +function ScreenBody({ + route, + children, +}: { + route: ScreenRoute + children: ReactNode +}) { + return ( + <> + {children} + + + ) +} + /** Apply sidebar insets natively, before Yoga measures the content pane. */ -export function TabScreenContent({ children }: { children: ReactNode }) { +export function TabScreenContent({ + route, + children, +}: { + route: ScreenRoute + children: ReactNode +}) { const backgroundStyle = useTabletBackgroundStyle() - if (Platform.OS !== "ios" || !Platform.isPad) return <>{children} + if (Platform.OS !== "ios" || !Platform.isPad) { + return {children} + } return ( - {children} + {children} @@ -22,6 +52,13 @@ export function TabScreenContent({ children }: { children: ReactNode }) { ) } -export function renderTabScreenContent({ children }: { children: ReactNode }) { - return {children} +/** `screenLayout` for every tab stack. */ +export function renderTabScreenContent({ + route, + children, +}: { + route: ScreenRoute + children: ReactNode +}) { + return {children} } diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 7044fb1..94ed4c5 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -37,6 +37,7 @@ "expo-image-picker": "~58.0.10", "expo-linking": "~58.0.14", "expo-navigation-bar": "~58.0.4", + "expo-network": "~58.0.5", "expo-router": "~58.0.25", "expo-secure-store": "~58.0.2", "expo-sharing": "~58.0.20", diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index b685f85..02a758a 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -1,6 +1,7 @@ import { AddToPlaylistProvider } from "@/components/add-to-playlist-provider" import { DownloadsProvider } from "@/components/downloads-provider" import { FavoritesProvider } from "@/components/favorites-provider" +import { OfflineGate } from "@/components/offline-gate" import { PlaybackProvider } from "@/components/playback-provider" import { PlayerBar } from "@/components/player-bar" import { LazyQueuePanel } from "@/components/lazy-queue-panel" @@ -24,7 +25,9 @@ export default function AppLayout({
- {children} + + {children} + diff --git a/apps/web/components/app-sidebar.tsx b/apps/web/components/app-sidebar.tsx index ed30562..e8c9729 100644 --- a/apps/web/components/app-sidebar.tsx +++ b/apps/web/components/app-sidebar.tsx @@ -48,6 +48,8 @@ import { playlistCoverUrl } from "@/lib/cover-urls" import { useCachedQuery } from "@/hooks/use-cached-query" import { useMounted } from "@/hooks/use-mounted" import { clearPersistentCache } from "@/lib/persistent-cache" +import { clearOfflinePages, DOWNLOADS_PATH } from "@/lib/downloads" +import { OfflineLink } from "@/components/offline-gate" import { resetPlaybackStores } from "@otunes/convex/client/playback-store" const OptionsModal = dynamic(() => @@ -63,7 +65,13 @@ const library = [ { title: "Albums", path: "/library/albums", icon: Disc3 }, { title: "Artists", path: "/library/artists", icon: Mic }, { title: "Songs", path: "/library/songs", icon: Music2 }, - { title: "Downloads", path: "/library/downloads", icon: ArrowDownToLine }, + // Opens offline, so it uses OfflineLink. + { + title: "Downloads", + path: DOWNLOADS_PATH, + icon: ArrowDownToLine, + worksOffline: true, + }, ] export function AppSidebar() { @@ -83,6 +91,7 @@ export function AppSidebar() { await signOut() resetPlaybackStores() await clearPersistentCache() + await clearOfflinePages() router.push("/signin") } @@ -160,10 +169,23 @@ export function AppSidebar() { } asChild > - setOpenMobile(false)}> - - {item.title} - + {item.worksOffline ? ( + setOpenMobile(false)} + > + + {item.title} + + ) : ( + setOpenMobile(false)} + > + + {item.title} + + )} ))} diff --git a/apps/web/components/downloads-provider.tsx b/apps/web/components/downloads-provider.tsx index 5a775b9..802c119 100644 --- a/apps/web/components/downloads-provider.tsx +++ b/apps/web/components/downloads-provider.tsx @@ -21,8 +21,12 @@ import { useDownloadsVersion } from "@/hooks/use-downloads" import { downloadQueue, readRememberedDownloadQuality, + DOWNLOADS_PATH, + downloadedCollectionPath, + OTHER_DOWNLOADS_PATH, registerDownloadsServiceWorker, requestPersistentStorage, + saveDownloadPagesForOffline, writeRememberedDownloadQuality, } from "@/lib/downloads" import { api } from "@otunes/convex/_generated/api" @@ -278,6 +282,27 @@ function useFailureToasts() { }, []) } +/** Keeps Downloads and each downloaded collection's page saved for offline. */ +function OfflinePagesSync() { + useDownloadsVersion() + const collectionPaths = downloadQueue + .collections() + .map(downloadedCollectionPath) + const hasOtherSongs = downloadQueue.otherSongIds().length > 0 + // A string, so the effect reruns only when the saved set changes. + const pathsKey = collectionPaths.join("\n") + + React.useEffect(() => { + if (!pathsKey && !hasOtherSongs) return + saveDownloadPagesForOffline([ + DOWNLOADS_PATH, + OTHER_DOWNLOADS_PATH, + ...(pathsKey ? pathsKey.split("\n") : []), + ]) + }, [pathsKey, hasOtherSongs]) + return null +} + export function DownloadsProvider({ children }: { children: React.ReactNode }) { const [pending, setPending] = React.useState<{ target: DownloadTarget @@ -329,6 +354,7 @@ export function DownloadsProvider({ children }: { children: React.ReactNode }) { {children} + setPending(null)} diff --git a/apps/web/components/downloads-view.tsx b/apps/web/components/downloads-view.tsx index 14d3c99..0612424 100644 --- a/apps/web/components/downloads-view.tsx +++ b/apps/web/components/downloads-view.tsx @@ -2,32 +2,24 @@ import * as React from "react" import Image from "next/image" -import Link from "next/link" import { Star } from "lucide-react" import { FAVORITES_DOWNLOAD_ID } from "@/components/downloads-provider" import { PageHeader } from "@/components/library-skeletons" -import { - FROM_DOWNLOADS_PARAM, - useDownloadsVersion, -} from "@/hooks/use-downloads" +import { OfflineLink } from "@/components/offline-gate" +import { useDownloadsVersion } from "@/hooks/use-downloads" import { albumGridClassName } from "@/lib/album-grid-classes" import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls" -import { downloadQueue } from "@/lib/downloads" +import { + downloadedCollectionPath, + downloadQueue, + OTHER_DOWNLOADS_PATH, +} from "@/lib/downloads" import type { DownloadedCollection } from "@otunes/convex/client/download-queue" import { formatBytes } from "@otunes/convex/download-quality" -export const OTHER_DOWNLOADS_PATH = "/library/downloads/other" export const OTHER_DOWNLOADS_TITLE = "Other Downloaded Songs" -function collectionHref({ kind, id }: DownloadedCollection) { - if (kind === "album") return `/album/${id}?${FROM_DOWNLOADS_PARAM}` - if (id === FAVORITES_DOWNLOAD_ID) { - return `/playlist/favorites?${FROM_DOWNLOADS_PARAM}` - } - return `/playlist/${id}?${FROM_DOWNLOADS_PARAM}` -} - function CollectionCover({ collection }: { collection: DownloadedCollection }) { if (collection.id === FAVORITES_DOWNLOAD_ID) { return ( @@ -63,7 +55,7 @@ function DownloadCard({ cover: React.ReactNode }) { return ( - +
{cover}
@@ -75,7 +67,7 @@ function DownloadCard({ {subtitle}

- + ) } @@ -138,7 +130,7 @@ export function DownloadsView() { {rows.map(({ collection, bytes }) => ( } diff --git a/apps/web/components/offline-gate.tsx b/apps/web/components/offline-gate.tsx new file mode 100644 index 0000000..da429bd --- /dev/null +++ b/apps/web/components/offline-gate.tsx @@ -0,0 +1,101 @@ +"use client" + +import { connectivityStore } from "@otunes/convex/client/connectivity" +import { useConvex } from "convex/react" +import { WifiOff } from "lucide-react" +import Link from "next/link" +import { usePathname, useSearchParams } from "next/navigation" +import { useOffline } from "next/offline" +import { useEffect, useRef, useSyncExternalStore } from "react" + +import { PageHeader } from "@/components/library-skeletons" +import { DOWNLOADS_PATH } from "@/lib/downloads" + +/** How long an offline navigation may wait before loading the page in full. */ +const STALLED_NAVIGATION_MS = 1_500 + +/** + * True while the browser is offline or the server can't be reached. Next's + * `useOffline` covers the network and the web server (it needs + * `experimental.useOffline`); the shared store covers the Convex backend. + */ +export function useIsOffline() { + const nextOffline = useOffline() + const store = connectivityStore(useConvex()) + const convexOffline = useSyncExternalStore( + store.subscribe, + store.getSnapshot, + () => false + ) + return nextOffline || convexOffline +} + +/** + * Replaces page content with a no-connection message while offline. Downloads + * pages, and albums and playlists opened from them, keep rendering so offline + * playback stays reachable. Needs a Suspense boundary for `useSearchParams`. + */ +export function OfflineGate({ children }: { children: React.ReactNode }) { + const offline = useIsOffline() + const pathname = usePathname() + const fromDownloads = useSearchParams().get("from") === "downloads" + const isDownloadsPage = + pathname === DOWNLOADS_PATH || pathname.startsWith(`${DOWNLOADS_PATH}/`) + + if (!offline || isDownloadsPage || fromDownloads) return children + + return ( +
+ +
+ +

No connection

+

+ Your downloads still play. +

+ + Go to Downloads + +
+
+ ) +} + +/** + * A fully prefetched link for pages that work offline. Offline, a page that + * was never prefetched would wait for the connection, so after a moment it + * loads in full instead and the service worker serves its saved copy. + */ +export function OfflineLink({ + href, + onClick, + ...props +}: React.ComponentProps & { href: string }) { + const offline = useIsOffline() + const pathname = usePathname() + const fallback = useRef>(undefined) + + // Any completed navigation, or leaving the page, cancels the fallback. + useEffect(() => () => clearTimeout(fallback.current), [pathname]) + + return ( + { + onClick?.(event) + if (!offline || event.defaultPrevented) return + if (event.metaKey || event.ctrlKey || event.shiftKey) return + clearTimeout(fallback.current) + fallback.current = setTimeout( + () => window.location.assign(href), + STALLED_NAVIGATION_MS + ) + }} + {...props} + /> + ) +} diff --git a/apps/web/hooks/use-downloads.ts b/apps/web/hooks/use-downloads.ts index 72862ec..1df201a 100644 --- a/apps/web/hooks/use-downloads.ts +++ b/apps/web/hooks/use-downloads.ts @@ -73,8 +73,7 @@ export function useIsCollectionDownloaded(ref: CollectionRef) { const noopSubscribe = () => () => {} -/** Search param marking album and playlist pages opened from Downloads. */ -export const FROM_DOWNLOADS_PARAM = "from=downloads" +export { FROM_DOWNLOADS_PARAM } from "@/lib/downloads" /** * True on album and playlist pages opened from Downloads, where playback uses diff --git a/apps/web/lib/downloads.ts b/apps/web/lib/downloads.ts index 4f7f89f..caa18dc 100644 --- a/apps/web/lib/downloads.ts +++ b/apps/web/lib/downloads.ts @@ -1,5 +1,7 @@ import { createDownloadQueue, + FAVORITES_ID, + type DownloadedCollection, type DownloadedCover, type DownloadedSong, type DownloadIndex, @@ -29,13 +31,50 @@ function coverPath({ kind, id }: DownloadedCover) { return `/api/${kind}/${id}/cover` } -/** Lets downloaded covers show offline. */ +export const DOWNLOADS_PATH = "/library/downloads" +export const OTHER_DOWNLOADS_PATH = "/library/downloads/other" + +/** Search param marking album and playlist pages opened from Downloads. */ +export const FROM_DOWNLOADS_PARAM = "from=downloads" + +export function downloadedCollectionPath({ kind, id }: DownloadedCollection) { + if (kind === "album") return `/album/${id}?${FROM_DOWNLOADS_PARAM}` + if (id === FAVORITES_ID) return `/playlist/favorites?${FROM_DOWNLOADS_PARAM}` + return `/playlist/${id}?${FROM_DOWNLOADS_PARAM}` +} + +// Saved pages are specific to the signed-in user (public/downloads-sw.js). +const OFFLINE_PAGE_CACHE = "otunes-offline-pages" + +/** + * Lets downloaded covers show offline. In production builds the worker also + * keeps pages and app code so the app opens offline. + */ export function registerDownloadsServiceWorker() { - void navigator.serviceWorker - ?.register("/downloads-sw.js", { scope: "/" }) + const url = + process.env.NODE_ENV === "production" + ? "/downloads-sw.js?offline-app" + : "/downloads-sw.js" + void navigator.serviceWorker?.register(url, { scope: "/" }).catch(() => {}) +} + +/** + * Saves the Downloads pages and every downloaded album and playlist page, so + * they open even after a reload or launch without a connection. + */ +export function saveDownloadPagesForOffline(paths: string[]) { + void navigator.serviceWorker?.ready + .then((registration) => + registration.active?.postMessage({ type: "save-pages", paths }) + ) .catch(() => {}) } +/** Forgets saved pages, on sign-out. */ +export async function clearOfflinePages() { + await globalThis.caches?.delete(OFFLINE_PAGE_CACHE).catch(() => false) +} + let database: Promise | null = null function openDatabase() { diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 0cb8c5b..384ef1a 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -5,6 +5,9 @@ const nextConfig: NextConfig = { output: "standalone", outputFileTracingRoot: path.join(__dirname, "../../"), experimental: { + // Failed navigations wait for the connection instead of reloading the + // page, which would show the browser's offline page and stop playback. + useOffline: true, // App pages render their data from the client cache, so reusing a visited // page's server payload is safe and skips a round trip on revisits. staleTimes: { diff --git a/apps/web/public/downloads-sw.js b/apps/web/public/downloads-sw.js index cea9d79..2c9627c 100644 --- a/apps/web/public/downloads-sw.js +++ b/apps/web/public/downloads-sw.js @@ -1,11 +1,29 @@ -// Serves covers of downloaded music when the network fails, so they show -// offline; any other cover falls back to the placeholder the server would send -// for a missing cover. Everything else, and every request that succeeds -// online, passes through untouched. Covers are saved by lib/downloads.ts. +// Keeps the app usable offline: +// - Pages: network first, then the last good copy of each page. A page never +// saved falls back to Downloads, which lib/downloads.ts saves ahead of time +// with "save-pages". +// - App code (/_next/static): saved on first load and served from the saved +// copy. Names change on every deploy, so a saved copy is never stale. Code +// unused for a month is deleted, so old deploys don't pile up. +// - Covers of downloaded music, saved by lib/downloads.ts, served only when +// the network fails. Any other cover falls back to the placeholder the +// server would send for a missing cover. +// Pages and app code are only handled in production builds (`?offline-app`), +// where app code is content-hashed. const COVER_CACHE = "otunes-download-covers" const PLACEHOLDER_CACHE = "otunes-placeholders" const PLACEHOLDER_PATH = "/placeholder-album.svg" +const PAGE_CACHE = "otunes-offline-pages" +const STATIC_CACHE = "otunes-offline-static" const COVER_PATH = /^\/api\/(album|playlist|artist)\/[^/]+\/cover$/ +const DOWNLOADS_PATH = "/library/downloads" +const AUTH_PATHS = new Set(["/signin", "/signup"]) +const PUBLIC_FILE = /\.(svg|png|ico|webmanifest)$/ +const STATIC_REFERENCE = /static\/(?:chunks|css|media)\/[^"'\\\s)]+/g +const OFFLINE_APP = new URL(self.location.href).searchParams.has("offline-app") +const DAY_MS = 24 * 60 * 60 * 1000 +const STATIC_MAX_UNUSED_MS = 30 * DAY_MS +const USED_AT_HEADER = "X-Otunes-Used-At" self.addEventListener("install", (event) => { self.skipWaiting() @@ -14,9 +32,43 @@ self.addEventListener("install", (event) => { ) }) self.addEventListener("activate", (event) => - event.waitUntil(self.clients.claim()) + event.waitUntil(Promise.all([self.clients.claim(), pruneStatic()])) ) +/** Saves app code stamped with when it was last used. */ +async function putStatic(key, response) { + const headers = new Headers(response.headers) + headers.set(USED_AT_HEADER, String(Date.now())) + const cache = await caches.open(STATIC_CACHE) + await cache.put( + key, + new Response(await response.blob(), { + status: response.status, + statusText: response.statusText, + headers, + }) + ) +} + +function usedAt(response) { + return Number(response.headers.get(USED_AT_HEADER)) || 0 +} + +let lastPrune = 0 + +/** Deletes app code unused for a month. Runs at most once a day. */ +async function pruneStatic() { + if (!OFFLINE_APP || Date.now() - lastPrune < DAY_MS) return + lastPrune = Date.now() + const cache = await caches.open(STATIC_CACHE) + for (const request of await cache.keys()) { + const response = await cache.match(request) + if (response && Date.now() - usedAt(response) > STATIC_MAX_UNUSED_MS) { + await cache.delete(request) + } + } +} + /** The saved cover's key for a cover request, also through `/_next/image`. */ function coverKey(url) { if (url.origin !== self.location.origin) return null @@ -27,26 +79,163 @@ function coverKey(url) { return COVER_PATH.test(url.pathname) ? url.pathname : null } +/** One key per page, whatever the request's headers. */ +function pageKey(url) { + return url.pathname + url.search +} + +/** Chunk paths show up both URL-encoded and raw, so keys use the raw form. */ +function staticKey(url) { + try { + return decodeURI(url.pathname) + } catch { + return url.pathname + } +} + +async function saved(cacheName, key) { + const cache = await caches.open(cacheName) + return cache.match(key, { ignoreVary: true, ignoreSearch: false }) +} + +function isSavablePage(response, url) { + return ( + response.ok && + !response.redirected && + !AUTH_PATHS.has(url.pathname) && + (response.headers.get("Content-Type") ?? "").includes("text/html") + ) +} + +async function savePage(url, response) { + const cache = await caches.open(PAGE_CACHE) + await cache.put(pageKey(url), response) +} + +/** Saves the app code a page references, so it renders offline. */ +async function saveStaticReferences(html) { + const cache = await caches.open(STATIC_CACHE) + const paths = new Set( + Array.from(html.matchAll(STATIC_REFERENCE), ([path]) => `/_next/${path}`) + ) + await Promise.all( + [...paths].map(async (path) => { + const key = staticKey(new URL(path, self.location.origin)) + if (await cache.match(key)) return + const response = await fetch(path).catch(() => null) + if (response?.ok) await putStatic(key, response) + }) + ) +} + +async function handlePage(request, url) { + void pruneStatic() + try { + const response = await fetch(request) + if (isSavablePage(response, url)) await savePage(url, response.clone()) + return response + } catch (error) { + const page = await saved(PAGE_CACHE, pageKey(url)) + if (page) return page + if (url.pathname !== DOWNLOADS_PATH && (await saved(PAGE_CACHE, DOWNLOADS_PATH))) { + return Response.redirect(DOWNLOADS_PATH, 302) + } + throw error + } +} + +async function handleStatic(request, url) { + const key = staticKey(url) + const cached = await saved(STATIC_CACHE, key) + if (cached) { + // Refresh the stamp at most daily, so code in use is never pruned. + if (Date.now() - usedAt(cached) > DAY_MS) { + void putStatic(key, cached.clone()) + } + return cached + } + const response = await fetch(request) + if (response.ok) await putStatic(key, response.clone()) + return response +} + /** The saved cover, else the placeholder. */ async function savedCover(key) { - const saved = await (await caches.open(COVER_CACHE)).match(key) - if (saved) return saved - return (await caches.open(PLACEHOLDER_CACHE)).match(PLACEHOLDER_PATH) + return ( + (await saved(COVER_CACHE, key)) ?? + (await saved(PLACEHOLDER_CACHE, PLACEHOLDER_PATH)) + ) +} + +async function handleCover(request, key) { + try { + const response = await fetch(request) + return response.ok ? response : ((await savedCover(key)) ?? response) + } catch (error) { + const cover = await savedCover(key) + if (cover) return cover + throw error + } +} + +/** Network first for public files, saved as app code for offline. */ +async function handlePublicFile(request, key) { + try { + const response = await fetch(request) + if (response.ok) await putStatic(key, response.clone()) + return response + } catch (error) { + const copy = await saved(STATIC_CACHE, key) + if (copy) return copy + throw error + } } self.addEventListener("fetch", (event) => { - if (event.request.method !== "GET") return - const key = coverKey(new URL(event.request.url)) - if (!key) return - event.respondWith( - fetch(event.request).then( - async (response) => - response.ok ? response : ((await savedCover(key)) ?? response), - async (error) => { - const saved = await savedCover(key) - if (saved) return saved - throw error - } + const { request } = event + if (request.method !== "GET") return + const url = new URL(request.url) + if (url.origin !== self.location.origin) return + + if (OFFLINE_APP && request.mode === "navigate") { + event.respondWith(handlePage(request, url)) + return + } + if (OFFLINE_APP && url.pathname.startsWith("/_next/static/")) { + event.respondWith(handleStatic(request, url)) + return + } + const cover = coverKey(url) + if (cover) { + event.respondWith(handleCover(request, cover)) + return + } + if (OFFLINE_APP && PUBLIC_FILE.test(url.pathname)) { + event.respondWith(handlePublicFile(request, url.pathname)) + } +}) + +/** Saves pages not saved yet, with their app code, while online. */ +async function savePages(paths) { + const cache = await caches.open(PAGE_CACHE) + for (const path of paths) { + const url = new URL(path, self.location.origin) + if (await cache.match(pageKey(url), { ignoreVary: true })) continue + const response = await fetch(url, { credentials: "same-origin" }).catch( + () => null ) - ) + if (!response || !isSavablePage(response, url)) continue + await savePage(url, response.clone()) + await saveStaticReferences(await response.text()) + } +} + +self.addEventListener("message", (event) => { + if ( + OFFLINE_APP && + event.data?.type === "save-pages" && + Array.isArray(event.data.paths) + ) { + event.waitUntil(savePages(event.data.paths)) + } }) diff --git a/packages/convex/client/connectivity.ts b/packages/convex/client/connectivity.ts new file mode 100644 index 0000000..96c7b1f --- /dev/null +++ b/packages/convex/client/connectivity.ts @@ -0,0 +1,103 @@ +import type { ConnectionState } from "convex/browser" + +/** The part of `ConvexReactClient` connectivity needs. */ +export type ConnectionClient = { + connectionState(): ConnectionState + subscribeToConnectionState(cb: (state: ConnectionState) => void): () => void +} + +/** A platform reachability signal, such as `navigator.onLine` on web. */ +export type PlatformNetwork = { + isOnline(): boolean + subscribe(onChange: () => void): () => void +} + +/** Shaped for `useSyncExternalStore`; the snapshot is true while offline. */ +export type ConnectivityStore = { + subscribe(onChange: () => void): () => void + getSnapshot(): boolean +} + +/** How long the socket may stay down before the app counts as offline. */ +const DISCONNECT_GRACE_MS = 5_000 + +const stores = new WeakMap() + +/** + * Returns the shared offline store for a Convex client. The app is offline + * when the platform reports no network, or when the server socket has stayed + * closed past a short grace period (server down, requests timing out). It + * comes back online as soon as the socket reconnects. + */ +export function connectivityStore( + client: ConnectionClient, + network?: PlatformNetwork +): ConnectivityStore { + let store = stores.get(client) + if (!store) { + store = createConnectivityStore(client, network) + stores.set(client, store) + } + return store +} + +function createConnectivityStore( + client: ConnectionClient, + network: PlatformNetwork | undefined +): ConnectivityStore { + const listeners = new Set<() => void>() + let offline = false + let graceTimer: ReturnType | undefined + let stop: (() => void) | undefined + + function setOffline(next: boolean) { + if (next === offline) return + offline = next + for (const listener of listeners) listener() + } + + function clearGrace() { + clearTimeout(graceTimer) + graceTimer = undefined + } + + function update() { + if (network && !network.isOnline()) { + clearGrace() + setOffline(true) + } else if (client.connectionState().isWebSocketConnected) { + clearGrace() + setOffline(false) + } else if (!offline && graceTimer === undefined) { + graceTimer = setTimeout(() => { + graceTimer = undefined + setOffline(true) + }, DISCONNECT_GRACE_MS) + } + } + + function start() { + const stopClient = client.subscribeToConnectionState(update) + const stopNetwork = network?.subscribe(update) + update() + return () => { + stopClient() + stopNetwork?.() + clearGrace() + } + } + + return { + subscribe(onChange) { + listeners.add(onChange) + stop ??= start() + return () => { + listeners.delete(onChange) + if (listeners.size > 0) return + stop?.() + stop = undefined + } + }, + getSnapshot: () => offline, + } +} diff --git a/packages/convex/package.json b/packages/convex/package.json index 5a6ebb6..b1e5cd3 100644 --- a/packages/convex/package.json +++ b/packages/convex/package.json @@ -39,6 +39,10 @@ "types": "./client/cached-query.ts", "default": "./client/cached-query.ts" }, + "./client/connectivity": { + "types": "./client/connectivity.ts", + "default": "./client/connectivity.ts" + }, "./client/download-queue": { "types": "./client/download-queue.ts", "default": "./client/download-queue.ts" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0dff66e..cbf6cd5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -330,6 +330,9 @@ importers: expo-navigation-bar: specifier: ~58.0.4 version: 58.0.4(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1) + expo-network: + specifier: ~58.0.5 + version: 58.0.5(expo@58.0.17)(react@19.3.0) expo-router: specifier: ~58.0.25 version: 58.0.25(patch_hash=9a20fd2b8a07da2435e76bf21a7242492a103d3e3d43b1a20165c290c494ae8c)(1020a30be8093793eba026e7c3f3ca8b) @@ -4283,6 +4286,12 @@ packages: react: '*' react-native: '*' + expo-network@58.0.5: + resolution: {integrity: sha512-/0F4WsFgJK9/wBzVd8ai/tUHpOROG3dbI4Azu89PQZnC7uohmm7/ruwK5VaTBumPh3hBMANXnww3WFAaMA1gOA==} + peerDependencies: + expo: '*' + react: '*' + expo-router@58.0.25: resolution: {integrity: sha512-sFumF6yUbxcSfiYcd+5vJjjIbVN0wo5X0F9SEnoNlmmvzoI9jD6k9dcSMnoe5ywquWonUEAdcHcpfsa087/8sQ==} peerDependencies: @@ -11256,6 +11265,11 @@ snapshots: transitivePeerDependencies: - supports-color + expo-network@58.0.5(expo@58.0.17)(react@19.3.0): + dependencies: + expo: 58.0.17(@babel/core@7.29.7(supports-color@8.1.1))(@expo/dom-webview@58.0.2)(@expo/metro-runtime@58.0.15)(expo-router@58.0.25)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1)(typescript@6.0.3) + react: 19.3.0 + expo-router@58.0.25(patch_hash=9a20fd2b8a07da2435e76bf21a7242492a103d3e3d43b1a20165c290c494ae8c)(1020a30be8093793eba026e7c3f3ca8b): dependencies: '@expo/log-box': 58.0.13(@expo/dom-webview@58.0.2)(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0) -- 2.54.1