91 lines
2.5 KiB
TypeScript
91 lines
2.5 KiB
TypeScript
"use client"
|
|
|
|
import { useMemo, useSyncExternalStore } from "react"
|
|
|
|
import type {
|
|
CollectionRef,
|
|
DownloadSource,
|
|
SongDownloadState,
|
|
} from "@otunes/convex/client/download-queue"
|
|
import { downloadQueue } from "@/lib/downloads"
|
|
|
|
/** Re-renders on every download change. Prefer the narrower hooks in lists. */
|
|
export function useDownloadsVersion() {
|
|
return useSyncExternalStore(
|
|
downloadQueue.subscribe,
|
|
downloadQueue.getVersion,
|
|
() => 0
|
|
)
|
|
}
|
|
|
|
/**
|
|
* A song's download state as seen from `from` (see `downloadState`). Only
|
|
* re-renders when that state changes.
|
|
*/
|
|
export function useSongDownloadState(
|
|
songId: string,
|
|
from?: DownloadSource
|
|
): SongDownloadState {
|
|
return useSyncExternalStore(
|
|
downloadQueue.subscribe,
|
|
() => downloadQueue.downloadState(songId, from),
|
|
() => "none"
|
|
)
|
|
}
|
|
|
|
/** True when every song is downloaded. Re-renders only when that flips. */
|
|
export function useAreSongsDownloaded(songIds: readonly string[]) {
|
|
return useSyncExternalStore(
|
|
downloadQueue.subscribe,
|
|
() =>
|
|
songIds.length > 0 &&
|
|
songIds.every((songId) => downloadQueue.getDownloaded(songId)),
|
|
() => false
|
|
)
|
|
}
|
|
|
|
/** A downloaded album or playlist and how far along its songs are. */
|
|
export function useCollectionDownload(
|
|
ref: CollectionRef,
|
|
songIds?: readonly string[]
|
|
) {
|
|
const version = useDownloadsVersion()
|
|
const { kind, id } = ref
|
|
return useMemo(() => {
|
|
const collection = downloadQueue.getCollection({ kind, id })
|
|
return {
|
|
collection,
|
|
status: downloadQueue.status(songIds ?? collection?.songIds ?? []),
|
|
}
|
|
// version invalidates the lookup when downloads change.
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [kind, id, songIds, version])
|
|
}
|
|
|
|
/** Whether an album or playlist is downloaded, for menus that list many. */
|
|
export function useIsCollectionDownloaded(ref: CollectionRef) {
|
|
return useSyncExternalStore(
|
|
downloadQueue.subscribe,
|
|
() => downloadQueue.getCollection(ref) !== undefined,
|
|
() => false
|
|
)
|
|
}
|
|
|
|
const noopSubscribe = () => () => {}
|
|
|
|
/** 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
|
|
* the downloads whatever their quality.
|
|
*/
|
|
export function useOpenedFromDownloads() {
|
|
return useSyncExternalStore(
|
|
noopSubscribe,
|
|
() =>
|
|
new URLSearchParams(window.location.search).get("from") === "downloads",
|
|
() => false
|
|
)
|
|
}
|