Files
otunes/apps/mobile/hooks/use-legacy-cover-palette.ts
T

68 lines
2.0 KiB
TypeScript

import { getColors, type ImageColorsResult } from "react-native-image-colors"
import { createCoverPaletteSource } from "@/hooks/cover-palette-source"
import {
deriveCoverPalette,
type LegacyCoverSwatches as CoverSwatches,
} from "@/lib/legacy-cover-palette"
// image-colors substitutes this for swatches it couldn't find.
const MISSING = "#010203"
function present(colors: (string | undefined)[]) {
return colors.filter(
(color): color is string => !!color && color.toLowerCase() !== MISSING
)
}
function toSwatches(result: ImageColorsResult): CoverSwatches | null {
if (result.platform === "ios") {
const text = present([result.primary, result.secondary, result.detail])
return result.background.toLowerCase() === MISSING
? null
: { background: result.background, text, accent: text }
}
const background = present([result.dominant, result.muted])[0]
if (!background) return null
return {
background,
text: present([
result.lightVibrant,
result.lightMuted,
result.darkVibrant,
result.darkMuted,
result.vibrant,
result.muted,
]),
accent: present([
result.vibrant,
result.lightVibrant,
result.darkVibrant,
result.muted,
]),
}
}
const legacy = createCoverPaletteSource<CoverSwatches>({
cacheKey: (colorSourceUri) => `palette:${colorSourceUri}`,
extract: (key) =>
getColors(key, {
fallback: MISSING,
cache: true,
key,
quality: "low",
pixelSpacing: 4,
}).then(toSwatches),
derive: deriveCoverPalette,
// Discard the background-only entries written by the tablet palette experiment.
isValidCache: (cached) =>
Array.isArray(cached.text) && Array.isArray(cached.accent),
})
/** Warm visible artwork colors before a detail page is pushed. */
export const prefetchLegacyCoverPalette = legacy.prefetch
/** `react-native-image-colors` pipeline used when new artwork colors are off. */
export const useLegacyCoverPalette = legacy.usePalette