Compare commits

..
16 changed files with 58 additions and 712 deletions

No files matched your search

-109
View File
@@ -1,109 +0,0 @@
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 (
<View
style={[
StyleSheet.absoluteFill,
styles.overlay,
{ backgroundColor: routerColors.background },
]}
>
<Ionicons
name="cloud-offline-outline"
size={28}
color={colors.mutedForeground}
/>
<Text style={[styles.title, { color: routerColors.text }]}>
No connection
</Text>
<Text style={[styles.body, { color: colors.mutedForeground }]}>
Your downloads still play.
</Text>
<Pressable
accessibilityRole="link"
hitSlop={spacing.sm}
onPress={() => push("/downloads")}
>
<Text style={[styles.link, { color: colors.primary }]}>
Go to Downloads
</Text>
</Pressable>
</View>
)
}
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 },
})
+5 -42
View File
@@ -5,46 +5,16 @@ 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}
<OfflineOverlay route={route} />
</>
)
}
/** Apply sidebar insets natively, before Yoga measures the content pane. */
export function TabScreenContent({
route,
children,
}: {
route: ScreenRoute
children: ReactNode
}) {
export function TabScreenContent({ children }: { children: ReactNode }) {
const backgroundStyle = useTabletBackgroundStyle()
if (Platform.OS !== "ios" || !Platform.isPad) {
return <ScreenBody route={route}>{children}</ScreenBody>
}
if (Platform.OS !== "ios" || !Platform.isPad) return <>{children}</>
return (
<Animated.View style={[{ flex: 1 }, backgroundStyle]}>
<SafeAreaView edges={["left", "right"]} style={{ flex: 1 }}>
<ScreenBody route={route}>{children}</ScreenBody>
{children}
</SafeAreaView>
<TabletSidebar />
<TabletPlayerLayoutSync />
@@ -52,13 +22,6 @@ export function TabScreenContent({
)
}
/** `screenLayout` for every tab stack. */
export function renderTabScreenContent({
route,
children,
}: {
route: ScreenRoute
children: ReactNode
}) {
return <TabScreenContent route={route}>{children}</TabScreenContent>
export function renderTabScreenContent({ children }: { children: ReactNode }) {
return <TabScreenContent>{children}</TabScreenContent>
}
+3 -5
View File
@@ -44,9 +44,7 @@ final class TabletSidebarView: ExpoView {
let onPlaylistPress = EventDispatcher()
var playlists: [SidebarPlaylist] = []
private let selectionProxy = SidebarSelectionProxy()
/// Playlist rows by identifier. Typed loosely because stored properties
/// can't be gated to iOS 18, where `UITab` arrives; values are always `UITab`.
private var playlistTabs: [String: NSObject] = [:]
private var playlistTabs: [String: UITab] = [:]
private var coverImages: [String: UIImage] = [:]
private var coverTasks: [String: URLSessionDataTask] = [:]
var accountName = ""
@@ -203,7 +201,7 @@ extension TabletSidebarView {
var rows: [UITab] = []
for playlist in playlists {
let identifier = playlistTabPrefix + playlist.id
let tab = playlistTabs[identifier] as? UITab ?? UITab(
let tab = playlistTabs[identifier] ?? UITab(
title: playlist.title, image: nil, identifier: identifier,
viewControllerProvider: { _ in UIViewController() })
playlistTabs[identifier] = tab
@@ -235,7 +233,7 @@ extension TabletSidebarView {
guard let self else { return }
self.coverTasks[url] = nil
self.coverImages[url] = roundedIcon(image)
if let tab = self.playlistTabs[identifier] as? UITab { tab.image = self.coverImages[url] }
if let tab = self.playlistTabs[identifier] { tab.image = self.coverImages[url] }
}
}
coverTasks[url] = task
-1
View File
@@ -37,7 +37,6 @@
"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",
+1 -4
View File
@@ -1,7 +1,6 @@
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"
@@ -25,9 +24,7 @@ export default function AppLayout({
<div className="flex min-h-svh min-w-0 flex-1">
<SidebarInset className="min-w-0 flex-1">
<Suspense>
<ScrollRestoration>
<OfflineGate>{children}</OfflineGate>
</ScrollRestoration>
<ScrollRestoration>{children}</ScrollRestoration>
</Suspense>
</SidebarInset>
<LazyQueuePanel />
+5 -27
View File
@@ -48,8 +48,6 @@ 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(() =>
@@ -65,13 +63,7 @@ const library = [
{ title: "Albums", path: "/library/albums", icon: Disc3 },
{ title: "Artists", path: "/library/artists", icon: Mic },
{ title: "Songs", path: "/library/songs", icon: Music2 },
// Opens offline, so it uses OfflineLink.
{
title: "Downloads",
path: DOWNLOADS_PATH,
icon: ArrowDownToLine,
worksOffline: true,
},
{ title: "Downloads", path: "/library/downloads", icon: ArrowDownToLine },
]
export function AppSidebar() {
@@ -91,7 +83,6 @@ export function AppSidebar() {
await signOut()
resetPlaybackStores()
await clearPersistentCache()
await clearOfflinePages()
router.push("/signin")
}
@@ -169,23 +160,10 @@ export function AppSidebar() {
}
asChild
>
{item.worksOffline ? (
<OfflineLink
href={item.path}
onClick={() => setOpenMobile(false)}
>
<item.icon />
<span>{item.title}</span>
</OfflineLink>
) : (
<Link
href={item.path}
onClick={() => setOpenMobile(false)}
>
<item.icon />
<span>{item.title}</span>
</Link>
)}
<Link href={item.path} onClick={() => setOpenMobile(false)}>
<item.icon />
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
@@ -21,12 +21,8 @@ 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"
@@ -282,27 +278,6 @@ 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
@@ -354,7 +329,6 @@ export function DownloadsProvider({ children }: { children: React.ReactNode }) {
<DownloadsContext.Provider value={value}>
{children}
<DownloadSync />
<OfflinePagesSync />
<DownloadQualityDialog
pending={pending}
onClose={() => setPending(null)}
+18 -10
View File
@@ -2,24 +2,32 @@
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 { OfflineLink } from "@/components/offline-gate"
import { useDownloadsVersion } from "@/hooks/use-downloads"
import {
FROM_DOWNLOADS_PARAM,
useDownloadsVersion,
} from "@/hooks/use-downloads"
import { albumGridClassName } from "@/lib/album-grid-classes"
import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
import {
downloadedCollectionPath,
downloadQueue,
OTHER_DOWNLOADS_PATH,
} from "@/lib/downloads"
import { downloadQueue } 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 (
@@ -55,7 +63,7 @@ function DownloadCard({
cover: React.ReactNode
}) {
return (
<OfflineLink href={href} className="group flex flex-col gap-2">
<Link href={href} className="group flex flex-col gap-2">
<div className="relative aspect-square overflow-hidden rounded-lg ring-1 ring-foreground/10">
{cover}
</div>
@@ -67,7 +75,7 @@ function DownloadCard({
{subtitle}
</p>
</div>
</OfflineLink>
</Link>
)
}
@@ -130,7 +138,7 @@ export function DownloadsView() {
{rows.map(({ collection, bytes }) => (
<DownloadCard
key={`${collection.kind}:${collection.id}`}
href={downloadedCollectionPath(collection)}
href={collectionHref(collection)}
title={collection.title}
subtitle={`${collection.kind === "album" ? "Album" : "Playlist"} · ${formatBytes(bytes)}`}
cover={<CollectionCover collection={collection} />}
-101
View File
@@ -1,101 +0,0 @@
"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 (
<div className="flex h-svh flex-col">
<PageHeader />
<div className="flex flex-1 flex-col items-center justify-center gap-2 p-6 pb-28 text-center">
<WifiOff className="mb-1 size-7 text-muted-foreground" />
<p className="text-sm font-medium">No connection</p>
<p className="text-sm text-muted-foreground">
Your downloads still play.
</p>
<OfflineLink
href={DOWNLOADS_PATH}
className="text-sm underline underline-offset-4"
>
Go to Downloads
</OfflineLink>
</div>
</div>
)
}
/**
* 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<typeof Link> & { href: string }) {
const offline = useIsOffline()
const pathname = usePathname()
const fallback = useRef<ReturnType<typeof setTimeout>>(undefined)
// Any completed navigation, or leaving the page, cancels the fallback.
useEffect(() => () => clearTimeout(fallback.current), [pathname])
return (
<Link
href={href}
prefetch
onClick={(event) => {
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}
/>
)
}
+2 -1
View File
@@ -73,7 +73,8 @@ export function useIsCollectionDownloaded(ref: CollectionRef) {
const noopSubscribe = () => () => {}
export { FROM_DOWNLOADS_PARAM } from "@/lib/downloads"
/** Search param marking album and playlist pages opened from Downloads. */
export const FROM_DOWNLOADS_PARAM = "from=downloads"
/**
* True on album and playlist pages opened from Downloads, where playback uses
+3 -42
View File
@@ -1,7 +1,5 @@
import {
createDownloadQueue,
FAVORITES_ID,
type DownloadedCollection,
type DownloadedCover,
type DownloadedSong,
type DownloadIndex,
@@ -31,50 +29,13 @@ function coverPath({ kind, id }: DownloadedCover) {
return `/api/${kind}/${id}/cover`
}
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.
*/
/** Lets downloaded covers show offline. */
export function registerDownloadsServiceWorker() {
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 })
)
void navigator.serviceWorker
?.register("/downloads-sw.js", { scope: "/" })
.catch(() => {})
}
/** Forgets saved pages, on sign-out. */
export async function clearOfflinePages() {
await globalThis.caches?.delete(OFFLINE_PAGE_CACHE).catch(() => false)
}
let database: Promise<IDBDatabase> | null = null
function openDatabase() {
-3
View File
@@ -5,9 +5,6 @@ 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: {
+21 -220
View File
@@ -1,74 +1,14 @@
// 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.
// Serves covers of downloaded music when the network fails, so they show
// offline. Everything else, and every request that succeeds online, passes
// through untouched. Covers are saved by lib/downloads.ts.
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"
const COVER_PATH = /^\/api\/(album|playlist)\/[^/]+\/cover$/
self.addEventListener("install", (event) => {
self.skipWaiting()
event.waitUntil(
caches.open(PLACEHOLDER_CACHE).then((cache) => cache.add(PLACEHOLDER_PATH))
)
})
self.addEventListener("install", () => self.skipWaiting())
self.addEventListener("activate", (event) =>
event.waitUntil(Promise.all([self.clients.claim(), pruneStatic()]))
event.waitUntil(self.clients.claim())
)
/** 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
@@ -79,163 +19,24 @@ 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) {
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
}
const cache = await caches.open(COVER_CACHE)
return cache.match(key)
}
self.addEventListener("fetch", (event) => {
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 (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
}
)
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))
}
)
})
-103
View File
@@ -1,103 +0,0 @@
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<ConnectionClient, ConnectivityStore>()
/**
* 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<typeof setTimeout> | 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,
}
}
-4
View File
@@ -39,10 +39,6 @@
"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"
-14
View File
@@ -330,9 +330,6 @@ 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)
@@ -4286,12 +4283,6 @@ 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:
@@ -11265,11 +11256,6 @@ 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)