Compare commits

..
22 changed files with 244 additions and 959 deletions

No files matched your search

+21 -10
View File
@@ -77,39 +77,44 @@ const QUEUE_ACTIONS: MediaAction[] = ["play-next", "play-last", "shuffle"]
const MEDIA_ACTION_ITEMS: {
action: MediaAction
label: (favorited: boolean | undefined, playlistLabel: string) => string
label: (
countSuffix: string,
favorited: boolean | undefined,
playlistLabel: string
) => string
image: NonNullable<MenuAction["image"]> & string
destructive?: boolean
}[] = [
{
action: "playlist",
label: (_favorited, playlistLabel) => playlistLabel,
label: (countSuffix, _favorited, playlistLabel) =>
`${playlistLabel}${countSuffix}`,
image: "text.badge.plus",
},
{
action: "download",
label: () => "Download",
label: (countSuffix) => `Download${countSuffix}`,
image: "arrow.down.circle",
},
{
action: "remove-download",
label: () => "Remove Download",
label: (countSuffix) => `Remove Download${countSuffix}`,
image: "xmark.circle",
destructive: true,
},
{
action: "play-next",
label: () => "Play Next",
label: (countSuffix) => `Play Next${countSuffix}`,
image: "text.line.first.and.arrowtriangle.forward",
},
{
action: "play-last",
label: () => "Play Last",
label: (countSuffix) => `Play Last${countSuffix}`,
image: "text.line.last.and.arrowtriangle.forward",
},
{
action: "shuffle",
label: () => "Shuffle",
label: (countSuffix) => `Shuffle${countSuffix}`,
image: "shuffle",
},
{
@@ -129,7 +134,8 @@ const MEDIA_ACTION_ITEMS: {
},
{
action: "favorite",
label: (favorited) => (favorited ? "Unfavorite" : "Favorite"),
label: (countSuffix, favorited) =>
`${favorited ? "Unfavorite" : "Favorite"}${countSuffix}`,
image: "star",
},
{
@@ -200,7 +206,12 @@ function isActionIncluded(
export function buildMediaMenuActions(
config: Omit<MediaMenuConfig, "onAction">
): MenuAction[] {
const { favorited, playlistLabel = "Add to Playlist" } = config
const {
selectedCount = 1,
favorited,
playlistLabel = "Add to Playlist",
} = config
const countSuffix = selectedCount > 1 ? ` (${selectedCount})` : ""
const actions: MenuAction[] = []
@@ -219,7 +230,7 @@ export function buildMediaMenuActions(
actions.push({
id: item.action,
title: item.label(favorited, playlistLabel),
title: item.label(countSuffix, favorited, playlistLabel),
image: item.action === "favorite" && favorited ? "star.fill" : item.image,
...(item.destructive ? { attributes: { destructive: true } } : {}),
})
-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>
}
+22 -14
View File
@@ -198,8 +198,7 @@ function optionDetail(option: SizedDownloadOption, songCount: number) {
return `${included} of ${songCount} songs, ${option.fallbackCount} in High`
}
/** Centered popup asking which quality to download a target at. */
function DownloadQualityPopup({
function DownloadQualitySheet({
pending,
onClose,
onPick,
@@ -215,7 +214,7 @@ function DownloadQualityPopup({
return (
<Modal
visible={pending !== null}
animationType="fade"
animationType="slide"
transparent
onRequestClose={onClose}
>
@@ -223,11 +222,14 @@ function DownloadQualityPopup({
<Pressable style={styles.overlay} onPress={onClose}>
<Pressable
style={[
styles.popup,
styles.sheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<View
style={[styles.grabber, { backgroundColor: colors.border }]}
/>
<Text style={[styles.title, { color: colors.foreground }]}>
Download Quality
</Text>
@@ -431,7 +433,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
<DownloadsContext.Provider value={value}>
{children}
{queue ? <DownloadSync queue={queue} /> : null}
<DownloadQualityPopup
<DownloadQualitySheet
pending={pending}
onClose={() => setPending(null)}
onPick={handlePick}
@@ -443,17 +445,23 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
const styles = StyleSheet.create({
overlay: {
flex: 1,
backgroundColor: "rgba(0,0,0,0.6)",
justifyContent: "center",
alignItems: "center",
padding: 24,
backgroundColor: "rgba(0,0,0,0.45)",
justifyContent: "flex-end",
},
popup: {
width: "100%",
maxWidth: 420,
borderRadius: 16,
sheet: {
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
borderWidth: 1,
padding: 16,
paddingHorizontal: 16,
paddingTop: 8,
paddingBottom: 24,
},
grabber: {
width: 36,
height: 4,
borderRadius: 2,
alignSelf: "center",
marginBottom: 12,
},
title: { fontSize: 18, fontWeight: "700" },
subtitle: { fontSize: 13, marginBottom: 4 },
+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} />}
+13 -6
View File
@@ -74,6 +74,10 @@ export function MediaMenuSeparator() {
)
}
function actionLabel(base: string, selectedCount: number) {
return selectedCount > 1 ? `${base} (${selectedCount})` : base
}
export function MediaContextMenuItems({
selectedCount,
onAction,
@@ -117,7 +121,7 @@ export function MediaContextMenuItems({
className="justify-between"
onClick={() => onAction("playlist")}
>
{playlistLabel}
{actionLabel(playlistLabel, selectedCount)}
<ListPlus />
</MediaMenuItem>
{downloaded !== undefined ? (
@@ -125,7 +129,10 @@ export function MediaContextMenuItems({
className="justify-between"
onClick={() => onAction(downloaded ? "remove-download" : "download")}
>
{downloaded ? "Remove Download" : "Download"}
{actionLabel(
downloaded ? "Remove Download" : "Download",
selectedCount
)}
{downloaded ? <CircleX /> : <ArrowDownToLine />}
</MediaMenuItem>
) : null}
@@ -134,21 +141,21 @@ export function MediaContextMenuItems({
className="justify-between"
onClick={() => onAction("play-next")}
>
Play Next
{actionLabel("Play Next", selectedCount)}
<ListStart />
</MediaMenuItem>
<MediaMenuItem
className="justify-between"
onClick={() => onAction("play-last")}
>
Play Last
{actionLabel("Play Last", selectedCount)}
<ListEnd />
</MediaMenuItem>
<MediaMenuItem
className="justify-between"
onClick={() => onAction("shuffle")}
>
Shuffle
{actionLabel("Shuffle", selectedCount)}
<Shuffle />
</MediaMenuItem>
{stationArtistId ? (
@@ -189,7 +196,7 @@ export function MediaContextMenuItems({
className="justify-between"
onClick={() => onAction("favorite")}
>
{favorited ? "Unfavorite" : "Favorite"}
{actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)}
<Star />
</MediaMenuItem>
</>
-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}
/>
)
}
-18
View File
@@ -103,11 +103,8 @@ type PlaybackContextValue = {
toggleShuffle: () => Promise<void>
cycleRepeat: () => Promise<void>
clearQueue: () => Promise<void>
clearHistory: () => Promise<void>
reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
skipToQueueIndex: (index: number) => Promise<void>
/** Plays `history[index]`, moving it and every later song back into the queue. */
skipToHistoryIndex: (index: number) => Promise<void>
skipNext: () => Promise<void>
skipPrevious: () => Promise<void>
dolbyAtmosSupported: boolean | null
@@ -1458,10 +1455,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
setIsPlaying(false)
}, [store])
const clearHistory = useCallback(async () => {
store.update(playbackQueue.clearHistory)
}, [store])
const reorderQueue = useCallback(
async (songIds: Id<"songs">[]) => {
store.update((state) => playbackQueue.reorderQueue(state, songIds))
@@ -1476,13 +1469,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
[store]
)
const skipToHistoryIndex = useCallback(
async (index: number) => {
store.update((state) => playbackQueue.skipToHistoryIndex(state, index))
},
[store]
)
const skipNext = useCallback(async () => {
const before = store.getState()
if (before.repeatEnabled === "none" && before.queue.length <= 1) {
@@ -1564,10 +1550,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
toggleShuffle,
cycleRepeat,
clearQueue,
clearHistory,
reorderQueue,
skipToQueueIndex,
skipToHistoryIndex,
skipNext,
skipPrevious,
}),
@@ -1589,10 +1573,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
toggleShuffle,
cycleRepeat,
clearQueue,
clearHistory,
reorderQueue,
skipToQueueIndex,
skipToHistoryIndex,
skipNext,
skipPrevious,
]
+118 -178
View File
@@ -5,11 +5,13 @@ import * as React from "react"
import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { usePlayback } from "@/components/playback-provider"
import { TrackCover, TrackRow } from "@/components/track-row"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Skeleton } from "@/components/ui/skeleton"
import { Spinner } from "@/components/ui/spinner"
import { useTrackSelection } from "@/hooks/use-track-selection"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong, QueueSong } from "@otunes/convex/types"
import type { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types"
import {
getContiguousSelectedIndices,
moveQueueBlock,
@@ -17,6 +19,7 @@ import {
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
import { useSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils"
import { formatDuration } from "@/lib/format-duration"
const QUEUE_INITIAL_VISIBLE_COUNT = 100
const QUEUE_PAGE_SIZE = 50
@@ -29,13 +32,11 @@ type QueueItem = {
song: QueueSelectable | null
}
/** Upcoming songs only: queue index 0 is the current song, shown on its own. */
function toSelectableQueue(
songIds: Id<"songs">[],
songs: (BrowseSong | undefined)[]
): QueueItem[] {
return songIds.slice(1).map((songId, offset) => {
const queueIndex = offset + 1
return songIds.map((songId, queueIndex) => {
const selectionId = `${songId}-${queueIndex}`
const song = songs[queueIndex]
return {
@@ -46,75 +47,57 @@ function toSelectableQueue(
})
}
/** A played song; clicking it plays it again from that point in history. */
function HistorySongRow({
song,
historyIndex,
onPlay,
}: {
song: BrowseSong | undefined
historyIndex: number
onPlay: (historyIndex: number) => void
}) {
if (!song) {
return <QueueSongRowSkeleton />
}
function HistorySongRow({ song }: { song: HistorySong }) {
return (
<li
role="button"
tabIndex={0}
className="flex cursor-pointer items-center gap-3 px-4 py-2 text-sm hover:bg-foreground/5"
onClick={() => onPlay(historyIndex)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onPlay(historyIndex)
}
}}
>
<TrackCover
albumId={song.album.id}
alt={song.album.title}
inRange={false}
/>
<PlaybackSongMeta song={song} align="start" showAlbum={false} />
<li className="relative w-full py-2 text-left text-sm opacity-60">
<div className="relative z-10 flex items-center gap-3 px-2">
<TrackCover
albumId={song.album.id}
alt={song.album.title}
inRange={false}
square
/>
<PlaybackSongMeta
song={song}
isCurrent={false}
inRange={false}
align="start"
showAlbum={false}
/>
<span className="shrink-0 text-xs text-muted-foreground tabular-nums">
{formatDuration(song.durationSeconds)}
</span>
</div>
</li>
)
}
function QueueSongRowSkeleton() {
return (
<li className="flex items-center gap-3 px-4 py-2" aria-hidden>
<Skeleton className="size-10 shrink-0 rounded" />
<li className="flex items-center gap-3 px-2 py-2" aria-hidden>
<Skeleton className="size-10 shrink-0 rounded-none" />
<div className="flex min-w-0 flex-1 flex-col gap-1.5">
<Skeleton className="h-3.5 w-3/4" />
<Skeleton className="h-3 w-1/2" />
</div>
<Skeleton className="h-3 w-8 shrink-0" />
</li>
)
}
/**
* The queue sidebar, laid out like the mobile now playing queue: history above
* (scrolled out of view at first), then the current song and the upcoming
* songs, which can be dragged to reorder. Shuffle and repeat live in the
* player bar.
*/
export function QueuePanel() {
const {
queueSongIds,
queueHistorySongIds,
queueOpen,
clearHistory,
clearQueue,
reorderQueue,
skipToQueueIndex,
skipToHistoryIndex,
} = usePlayback()
const loadMoreRef = React.useRef<HTMLDivElement>(null)
const scrollRef = React.useRef<HTMLDivElement>(null)
const currentRef = React.useRef<HTMLDivElement>(null)
const nowPlayingRef = React.useRef<HTMLElement>(null)
const [visibleCount, setVisibleCount] = React.useState(
QUEUE_INITIAL_VISIBLE_COUNT
)
@@ -124,10 +107,15 @@ export function QueuePanel() {
[queueSongIds, visibleCount]
)
const visibleQueueSongs = useSongs(visibleQueueIds)
const historySongs = useSongs(queueHistorySongIds)
const currentSong = visibleQueueSongs[0]
const historySongMetadata = useSongs(queueHistorySongIds)
const historySongs = React.useMemo(
() =>
historySongMetadata.flatMap((song, historyIndex) =>
song ? [{ ...song, historyIndex }] : []
),
[historySongMetadata]
)
const hasMore = queueSongIds.length > visibleCount
const hasUpcoming = queueSongIds.length > 1
const selectableQueue = React.useMemo(
() => toSelectableQueue(visibleQueueIds, visibleQueueSongs),
@@ -137,21 +125,17 @@ export function QueuePanel() {
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
const currentQueueSongId = queueSongIds[0]
// Keep the current song at the top as playback moves through the queue:
// jump there on open, then scroll smoothly as songs change.
const hasScrolledRef = React.useRef(false)
React.useLayoutEffect(() => {
const scroller = scrollRef.current
const current = currentRef.current
if (!queueOpen || !scroller || !current) {
React.useEffect(() => {
if (!queueOpen || queueSongIds.length === 0) {
return
}
scroller.scrollTo({
top: current.offsetTop,
behavior: hasScrolledRef.current ? "smooth" : "instant",
const frame = requestAnimationFrame(() => {
nowPlayingRef.current?.scrollIntoView({ block: "center" })
})
hasScrolledRef.current = true
}, [queueOpen, currentQueueSongId, queueHistorySongIds.length])
return () => cancelAnimationFrame(frame)
}, [queueOpen, queueSongIds.length, currentQueueSongId])
React.useEffect(() => {
if (!hasMore) {
@@ -159,8 +143,12 @@ export function QueuePanel() {
}
const sentinel = loadMoreRef.current
const root = scrollRef.current
if (!sentinel || !root) {
if (!sentinel) {
return
}
const viewport = sentinel.closest('[data-slot="scroll-area-viewport"]')
if (!viewport) {
return
}
@@ -170,7 +158,7 @@ export function QueuePanel() {
setVisibleCount((count) => count + QUEUE_PAGE_SIZE)
}
},
{ root, rootMargin: "240px" }
{ root: viewport, rootMargin: "240px" }
)
observer.observe(sentinel)
@@ -198,11 +186,6 @@ export function QueuePanel() {
[selectableQueue, skipToQueueIndex]
)
const handleHistoryPlay = React.useCallback(
(historyIndex: number) => void skipToHistoryIndex(historyIndex),
[skipToHistoryIndex]
)
const selectionPositions = React.useMemo(
() =>
getSelectionRangePositions(
@@ -257,119 +240,76 @@ export function QueuePanel() {
return (
<aside
className={cn(
"relative flex h-svh w-72 shrink-0 flex-col border-l bg-background",
"flex h-svh w-72 shrink-0 flex-col border-l bg-background",
"max-md:fixed max-md:inset-y-0 max-md:right-0 max-md:z-20 max-md:shadow-xl"
)}
>
<div
ref={scrollRef}
className="relative min-h-0 flex-1 [scrollbar-width:none] overflow-y-auto overscroll-contain"
>
{queueHistorySongIds.length > 0 ? (
<section>
<header className="flex items-center justify-between px-4 pt-3 pb-1">
<h2 className="text-base font-bold">History</h2>
<button
type="button"
className="text-sm text-muted-foreground hover:text-foreground"
onClick={() => void clearHistory()}
>
Clear
</button>
</header>
<ul className="flex flex-col">
{queueHistorySongIds.map((songId, historyIndex) => (
<HistorySongRow
key={`history-${songId}-${historyIndex}`}
song={historySongs[historyIndex]}
historyIndex={historyIndex}
onPlay={handleHistoryPlay}
/>
))}
</ul>
</section>
) : null}
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
<h1 className="text-lg font-semibold">Up Next</h1>
<Button
variant="ghost"
size="sm"
className="text-primary hover:text-primary"
onClick={() => void clearQueue()}
disabled={queueSongIds.length === 0}
>
Clear
</Button>
</header>
{/* Fills the viewport so the current song can always scroll to the top. */}
<div ref={currentRef} className="flex min-h-full flex-col">
{currentQueueSongId ? (
<div className="flex items-center gap-3 px-4 py-3">
{currentSong ? (
<>
<TrackCover
albumId={currentSong.album.id}
alt={currentSong.album.title}
inRange={false}
size="lg"
<ScrollArea className="min-h-0 flex-1">
{queueSongIds.length === 0 ? (
<p className="px-4 py-8 text-sm text-muted-foreground">
Nothing in the queue.
</p>
) : (
<>
{historySongs.length > 0 ? (
<ul className="flex flex-col border-b py-1">
{historySongs.map((song) => (
<HistorySongRow
key={`history-${song.id}-${song.historyIndex}`}
song={song}
/>
<PlaybackSongMeta
song={currentSong}
align="start"
showAlbum={false}
/>
</>
) : (
<Skeleton className="size-14 shrink-0 rounded-md" />
)}
</div>
) : null}
<header className="sticky top-0 z-20 flex items-center justify-between bg-background px-4 py-2">
<h2 className="text-base font-bold">Continue Playing</h2>
<button
type="button"
className="text-sm text-muted-foreground hover:text-foreground disabled:pointer-events-none disabled:opacity-50"
onClick={() => void clearQueue()}
disabled={queueSongIds.length === 0}
>
Clear
</button>
</header>
{hasUpcoming ? (
<>
<ul className="flex flex-col pb-8">
{selectableQueue.map((item, index) =>
item.song ? (
<TrackRow
key={item.selectionId}
variant="queue"
song={item.song}
index={index}
selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
onDragStart={setDragIndex}
onDrop={handleDrop}
/>
) : (
<QueueSongRowSkeleton key={item.selectionId} />
)
)}
))}
</ul>
{hasMore ? (
<div
ref={loadMoreRef}
className="flex items-center justify-center py-4"
aria-hidden
>
<Spinner className="size-5 text-muted-foreground" />
</div>
) : null}
</>
) : (
<p className="flex flex-1 items-center justify-center px-4 pb-24 text-center text-lg font-semibold text-muted-foreground">
Nothing else is queued.
</p>
)}
</div>
</div>
<div
aria-hidden
className="pointer-events-none absolute inset-x-0 bottom-0 h-9 bg-linear-to-b from-transparent to-background"
/>
) : null}
<ul className="flex flex-col py-1">
{selectableQueue.map((item, index) =>
item.song ? (
<TrackRow
key={item.selectionId}
ref={item.queueIndex === 0 ? nowPlayingRef : undefined}
variant="queue"
song={item.song}
index={index}
isActive={item.queueIndex === 0}
isNowPlaying={item.queueIndex === 0}
selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
onDragStart={setDragIndex}
onDrop={handleDrop}
/>
) : (
<QueueSongRowSkeleton key={item.selectionId} />
)
)}
</ul>
{hasMore ? (
<div
ref={loadMoreRef}
className="flex items-center justify-center py-4"
aria-hidden
>
<Spinner className="size-5 text-muted-foreground" />
</div>
) : null}
</>
)}
</ScrollArea>
</aside>
)
}
+12 -21
View File
@@ -3,7 +3,7 @@
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
import { ArrowDownToLine, Menu, Music2, Play, Star, Trash2 } from "lucide-react"
import { ArrowDownToLine, Music2, Play, Star, Trash2 } from "lucide-react"
import {
MediaContextMenu,
@@ -38,7 +38,7 @@ import type { DownloadSource } from "@otunes/convex/client/download-queue"
* columns (use with `LibraryTrackListHeader`).
* - `album`: favorite star, track number, title with optional credits.
* - `playlist`: cover with favorite overlay, track number, title.
* - `queue`: cover, title and artist, duration, and a reorder grip. No menu.
* - `queue`: square cover, title and artist, no menu.
*/
export type TrackRowVariant = "library" | "album" | "playlist" | "queue"
@@ -89,14 +89,13 @@ export function TrackCover({
albumId,
alt,
inRange,
size = "md",
square = false,
children,
}: {
albumId: string | undefined
alt: string
inRange: boolean
/** `lg` is the larger current-song cover in the queue. */
size?: "md" | "lg"
square?: boolean
/** Overlay shown above the cover image. */
children?: React.ReactNode
}) {
@@ -106,8 +105,8 @@ export function TrackCover({
return (
<div
className={cn(
"flex shrink-0 items-center justify-center bg-muted ring-1",
size === "lg" ? "size-14 rounded-md" : "size-10 rounded",
"flex size-10 shrink-0 items-center justify-center bg-muted ring-1",
!square && "rounded",
ringClass
)}
>
@@ -119,8 +118,8 @@ export function TrackCover({
return (
<div
className={cn(
"group/cover relative shrink-0 overflow-hidden ring-1",
size === "lg" ? "size-14 rounded-md" : "size-10 rounded",
"group/cover relative size-10 shrink-0 overflow-hidden ring-1",
!square && "rounded",
ringClass
)}
>
@@ -128,7 +127,7 @@ export function TrackCover({
src={albumCoverUrl(albumId)}
alt={alt}
fill
sizes={size === "lg" ? "56px" : "40px"}
sizes="40px"
className="object-cover"
/>
{children}
@@ -278,9 +277,7 @@ function TrackRowComponent({
const inRange = isInSelectionRange(selectionPosition)
const downloadState = useSongDownloadState(song.id, downloadCollection)
const isDownloaded = downloadState === "here"
// The queue row only shows the duration, like the mobile queue.
const showDownloaded =
variant !== "queue" && (isDownloaded || downloadState === "device")
const showDownloaded = isDownloaded || downloadState === "device"
const flush = variant === "library" || variant === "queue"
const play = () => onPlay(index)
const toggleFavorite = () => onToggleFavorite?.(song.id)
@@ -462,11 +459,12 @@ function TrackRowComponent({
break
case "queue":
content = (
<div className="relative z-10 flex items-center gap-3 pr-2 pl-4">
<div className="relative z-10 flex items-center gap-3 px-2">
<TrackCover
albumId={song.album.id}
alt={song.album.title}
inRange={inRange}
square
/>
<PlaybackSongMeta
song={song}
@@ -476,13 +474,6 @@ function TrackRowComponent({
showAlbum={false}
/>
{duration}
<Menu
aria-hidden
className={cn(
"size-4 shrink-0 cursor-grab",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
/>
</div>
)
break
+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)