Files
otunes/apps/mobile/hooks/use-cover-background-color.ts
T
joshuafhigginsandremhelper 3c721d9584 feat: optimize cover image delivery (#16)
- Add sized, resized WebP cover responses
- Request appropriately sized artwork in mobile

---------

Co-authored-by: Rem Helper <remhelper@abunchofknowitalls.com>
Reviewed-on: https://git.abunchofknowitalls.com/joshuafhiggins/otunes/pulls/16
2026-08-19 11:42:31 -04:00

59 lines
1.3 KiB
TypeScript

import { useEffect, useState } from "react"
import { getColors, type ImageColorsResult } from "react-native-image-colors"
import { withCoverImageSize } from "@/lib/urls"
function prominentColor(result: ImageColorsResult): string {
switch (result.platform) {
case "ios":
return result.primary || result.background
case "android":
return result.vibrant || result.dominant || result.average
case "web":
return result.vibrant || result.dominant
}
}
export function useCoverBackgroundColor(
uri: string,
hasCover: boolean,
fallback: string,
) {
const [backgroundColor, setBackgroundColor] = useState(fallback)
useEffect(() => {
let cancelled = false
if (!hasCover) {
setBackgroundColor(fallback)
return
}
setBackgroundColor(fallback)
const colorSourceUri = withCoverImageSize(uri, 64)
void getColors(colorSourceUri, {
fallback,
cache: true,
key: colorSourceUri,
quality: "low",
pixelSpacing: 8,
})
.then((result) => {
if (!cancelled) {
setBackgroundColor(prominentColor(result))
}
})
.catch(() => {
if (!cancelled) {
setBackgroundColor(fallback)
}
})
return () => {
cancelled = true
}
}, [fallback, hasCover, uri])
return backgroundColor
}