fix(mobile): make album and playlist text readable on cover-art backgrounds #30

Merged
joshuafhiggins merged 2 commits from t3code/apple-music-cover-colors into main 2026-10-17 15:22:39 -04:00
8 changed files with 600 additions and 143 deletions

No files matched your search

@@ -1,5 +1,6 @@
import { Stack, useLocalSearchParams } from "expo-router"
import { memo, useEffect, useMemo } from "react"
import { Stack, useIsFocused, useLocalSearchParams } from "expo-router"
import { StatusBar } from "expo-status-bar"
import { memo, useCallback, useEffect, useMemo } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons"
@@ -17,11 +18,12 @@ import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbumDetail, BrowseAlbumTrack } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
import { formatDuration, formatMetadata } from "@/lib/format"
import { useAppNavigation } from "@/lib/app-navigation"
import { longListProps } from "@/lib/list"
@@ -46,12 +48,16 @@ export default function AlbumScreen() {
handleAlbumTrackAction,
isAlbumFavorite: isAlbumFav,
} = useMediaMenuActions()
const isFocused = useIsFocused()
const coverUri =
config && album ? albumCoverUrl(config.serverUrl, album.id) : ""
const backgroundColor = useCoverBackgroundColor(
config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : ""
const { palette, settled } = useCoverPalette(
coverUri,
album?.cover != null,
colors.background
album ? album.cover != null : album === null ? false : undefined
)
const songIds = useMemo(
() => album?.tracks.map((track) => track.id as Id<"songs">) ?? [],
[album]
)
useEffect(() => {
@@ -60,12 +66,24 @@ export default function AlbumScreen() {
}
}, [album])
const songIds = useMemo(
() => album?.tracks.map((track) => track.id) ?? [],
[album?.tracks]
const renderTrack = useCallback(
({ item, index }: { item: BrowseAlbumTrack; index: number }) =>
album ? (
<AlbumTrackRow
track={item}
index={index}
album={album}
songIds={songIds}
palette={palette}
favorited={isSongFavorite(item.id)}
onPlay={playFromSong}
onAction={handleAlbumTrackAction}
/>
) : null,
[album, handleAlbumTrackAction, isSongFavorite, palette, playFromSong, songIds]
)
if (album === undefined || !config) {
if (album === undefined || !config || !settled) {
return (
<>
<Stack.Screen
@@ -98,13 +116,18 @@ export default function AlbumScreen() {
}
const metadata = formatMetadata(album.genre, album.year)
const favorited = isAlbumFavorite(album.id)
return (
<>
{isFocused ? (
<StatusBar style={palette.isDark ? "light" : "dark"} />
) : null}
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
headerTintColor: palette.foreground,
headerRight: () => (
<MediaActionMenu
selectedCount={album.tracks.length}
@@ -122,7 +145,7 @@ export default function AlbumScreen() {
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
color={palette.foreground}
/>
</Pressable>
</MediaActionMenu>
@@ -133,9 +156,10 @@ export default function AlbumScreen() {
{...longListProps}
data={album.tracks}
keyExtractor={(track) => track.id}
style={{ flex: 1, backgroundColor }}
style={{ flex: 1, backgroundColor: palette.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
indicatorStyle={palette.isDark ? "white" : "black"}
ListHeaderComponent={
<View style={styles.hero}>
<CoverImage
@@ -143,31 +167,29 @@ export default function AlbumScreen() {
hasCover={album.cover != null}
style={styles.cover}
/>
<Text style={[styles.title, { color: colors.foreground }]}>
<Text style={[styles.title, { color: palette.foreground }]}>
{album.title}
</Text>
<Pressable onPress={() => push(`/artist/${album.artist.id}`)}>
<Text style={[styles.artist, { color: colors.mutedForeground }]}>
<Text style={[styles.artist, { color: palette.accentText }]}>
{album.artist.name}
</Text>
</Pressable>
{metadata ? (
<Text style={{ color: colors.mutedForeground }}>{metadata}</Text>
<Text style={{ color: palette.secondaryForeground }}>
{metadata}
</Text>
) : null}
<View style={styles.actions}>
<Pressable
onPress={() => void toggleAlbumFavorite(album.id)}
hitSlop={8}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Ionicons
name={isAlbumFavorite(album.id) ? "star" : "star-outline"}
name={favorited ? "star" : "star-outline"}
size={24}
color={
isAlbumFavorite(album.id)
? colors.primary
: colors.foreground
}
color={favorited ? palette.accent : palette.foreground}
/>
</Pressable>
<Button
@@ -175,30 +197,28 @@ export default function AlbumScreen() {
icon="play"
onPress={() => void playAlbum(album.id, songIds)}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playAlbumShuffled(album.id, songIds)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
<Ionicons
name="shuffle"
size={24}
color={palette.foreground}
/>
</Pressable>
</View>
</View>
}
renderItem={({ item: track, index }) => (
<AlbumTrackRow
track={track}
album={album}
index={index}
favorited={isSongFavorite(track.id)}
songIds={songIds}
onPlay={playFromSong}
onAction={handleAlbumTrackAction}
/>
)}
renderItem={renderTrack}
/>
</>
)
@@ -206,18 +226,20 @@ export default function AlbumScreen() {
const AlbumTrackRow = memo(function AlbumTrackRow({
track,
album,
index,
favorited,
album,
songIds,
palette,
favorited,
onPlay,
onAction,
}: {
track: BrowseAlbumTrack
album: BrowseAlbumDetail
index: number
favorited: boolean
album: BrowseAlbumDetail
songIds: Id<"songs">[]
palette: CoverPalette
favorited: boolean
onPlay: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
onAction: (
track: BrowseAlbumTrack,
@@ -225,8 +247,6 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
action: MediaAction
) => Promise<void>
}) {
const colors = useThemeColors()
return (
<MediaContextMenu
favorited={favorited}
@@ -242,26 +262,31 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
onAction={(action) => void onAction(track, album, action)}
>
<Pressable
style={[styles.trackRow, { borderBottomColor: colors.border }]}
onPress={() => void onPlay(track.id, songIds)}
style={[styles.trackRow, { borderBottomColor: palette.divider }]}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
<Text style={[styles.trackNumber, { color: colors.mutedForeground }]}>
<Text
style={[styles.trackNumber, { color: palette.secondaryForeground }]}
>
{track.track || index + 1}
</Text>
<View style={styles.trackMeta}>
<Text
style={[styles.trackTitle, { color: colors.foreground }]}
style={[styles.trackTitle, { color: palette.foreground }]}
numberOfLines={1}
>
{track.title}
</Text>
{track.artists ? (
<Text style={{ color: colors.mutedForeground }} numberOfLines={1}>
<Text
style={{ color: palette.secondaryForeground }}
numberOfLines={1}
>
{track.artists.join(", ")}
</Text>
) : null}
</View>
<Text style={{ color: colors.mutedForeground }}>
<Text style={{ color: palette.secondaryForeground }}>
{formatDuration(track.durationSeconds)}
</Text>
</Pressable>
@@ -1,6 +1,7 @@
import { useMutation } from "convex/react"
import { memo, useCallback, useEffect, useMemo } from "react"
import { Stack, useLocalSearchParams, useRouter } from "expo-router"
import { Stack, useIsFocused, useLocalSearchParams, useRouter } from "expo-router"
import { StatusBar } from "expo-status-bar"
import {
FlatList,
Pressable,
@@ -28,11 +29,12 @@ import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
import { longListProps } from "@/lib/list"
import { rememberSongs } from "@/lib/song-cache"
import { showError, showSuccess } from "@/lib/toast"
@@ -80,13 +82,12 @@ export default function PlaylistScreen() {
playlistId ? { playlistId } : "skip"
)
const coverUri =
config && playlist
? playlistCoverUrl(config.serverUrl, playlist.id ?? "favorites")
config && playlistId
? playlistCoverUrl(config.serverUrl, playlist?.id ?? playlistId)
: ""
const backgroundColor = useCoverBackgroundColor(
const { palette, settled } = useCoverPalette(
coverUri,
playlist?.cover != null,
colors.background
playlist ? playlist.cover != null : playlist === null ? false : undefined
)
useEffect(() => {
@@ -96,7 +97,8 @@ export default function PlaylistScreen() {
if (
playlist === undefined ||
(status === "LoadingFirstPage" && !isCached) ||
!config
!config ||
!settled
) {
return (
<>
@@ -135,7 +137,7 @@ export default function PlaylistScreen() {
songs={songs}
allSongIds={allSongIds}
coverUri={coverUri}
backgroundColor={backgroundColor}
palette={palette}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
@@ -148,18 +150,18 @@ function PlaylistContent({
songs,
allSongIds,
coverUri,
backgroundColor,
palette,
onEndReached,
}: {
playlist: BrowsePlaylistDetail
songs: BrowseSong[]
allSongIds: Id<"songs">[] | undefined
coverUri: string
backgroundColor: string
palette: CoverPalette
onEndReached: () => void
}) {
const router = useRouter()
const colors = useThemeColors()
const isFocused = useIsFocused()
const { playPlaylist, playPlaylistShuffled, playFromSong } =
usePlaybackActions()
const { isSongFavorite } = useFavorites()
@@ -254,6 +256,7 @@ function PlaylistContent({
return {
title: "",
headerLargeTitle: false,
headerTintColor: palette.foreground,
headerRight: () => (
<MediaActionMenu
selectedCount={songIds.length}
@@ -269,7 +272,7 @@ function PlaylistContent({
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
color={palette.foreground}
/>
</Pressable>
</MediaActionMenu>
@@ -277,9 +280,9 @@ function PlaylistContent({
}
}, [
canEdit,
colors.foreground,
deletePlaylist,
handlePlaylistDetailAction,
palette.foreground,
playlistId,
router,
songIds,
@@ -291,31 +294,35 @@ function PlaylistContent({
song={song}
favorited={isSongFavorite(song.id)}
removable={canEdit}
backgroundColor={backgroundColor}
palette={palette}
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
onRemove={handleRemoveSong}
/>
),
[
backgroundColor,
canEdit,
handlePlaySong,
handleRemoveSong,
handleSongMenuAction,
isSongFavorite,
palette,
]
)
return (
<>
{isFocused ? (
<StatusBar style={palette.isDark ? "light" : "dark"} />
) : null}
<Stack.Screen options={screenOptions} />
<FlatList
{...longListProps}
data={songs}
keyExtractor={songKey}
renderItem={renderItem}
style={{ flex: 1, backgroundColor }}
style={{ flex: 1, backgroundColor: palette.background }}
indicatorStyle={palette.isDark ? "white" : "black"}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic"
onEndReached={onEndReached}
@@ -326,6 +333,7 @@ function PlaylistContent({
hasCover={playlist.cover != null}
title={playlist.title}
ownerName={playlist.owner.name}
palette={palette}
isSubscribed={isSubscribed}
showSubscribe={!playlist.isOwner && playlistId !== null}
onSubscribeToggle={handleSubscribeToggle}
@@ -346,7 +354,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
song,
favorited,
removable,
backgroundColor,
palette,
onPlay,
onAction,
onRemove,
@@ -354,7 +362,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
song: BrowseSong
favorited: boolean
removable: boolean
backgroundColor: string
palette: CoverPalette
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
onRemove: (songId: Id<"songs">) => void
@@ -365,6 +373,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
song={song}
favorited={favorited}
playlistLabel={PLAYLIST_LABEL}
palette={palette}
onPlay={onPlay}
onAction={onAction}
/>
@@ -381,7 +390,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
overshootRight={false}
enableTrackpadTwoFingerGesture
containerStyle={{ backgroundColor: colors.destructive }}
childrenContainerStyle={{ backgroundColor }}
childrenContainerStyle={{ backgroundColor: palette.background }}
renderRightActions={(_progress, _translation, swipeable) => (
<Pressable
accessibilityRole="button"
@@ -414,6 +423,7 @@ const PlaylistHero = memo(function PlaylistHero({
hasCover,
title,
ownerName,
palette,
isSubscribed,
showSubscribe = false,
onSubscribeToggle,
@@ -424,19 +434,18 @@ const PlaylistHero = memo(function PlaylistHero({
hasCover: boolean
title: string
ownerName: string
palette: CoverPalette
isSubscribed?: boolean
showSubscribe?: boolean
onSubscribeToggle?: () => void
onPlay: () => void
onShuffle: () => void
}) {
const colors = useThemeColors()
return (
<View style={styles.hero}>
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
<Text style={[styles.title, { color: colors.foreground }]}>{title}</Text>
<Text style={{ color: colors.mutedForeground }}>{ownerName}</Text>
<Text style={[styles.title, { color: palette.foreground }]}>{title}</Text>
<Text style={{ color: palette.secondaryForeground }}>{ownerName}</Text>
<View style={styles.actions}>
{showSubscribe ? (
<Pressable
@@ -448,7 +457,7 @@ const PlaylistHero = memo(function PlaylistHero({
style={[
styles.iconAction,
{
backgroundColor: isSubscribed ? colors.muted : colors.primary,
backgroundColor: isSubscribed ? palette.surface : palette.accent,
},
]}
>
@@ -456,7 +465,7 @@ const PlaylistHero = memo(function PlaylistHero({
name={isSubscribed ? "checkmark" : "add"}
size={24}
color={
isSubscribed ? colors.foreground : colors.primaryForeground
isSubscribed ? palette.foreground : palette.accentForeground
}
/>
</Pressable>
@@ -466,15 +475,19 @@ const PlaylistHero = memo(function PlaylistHero({
icon="play"
onPress={onPlay}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
<Ionicons name="shuffle" size={24} color={palette.foreground} />
</Pressable>
</View>
</View>
+17 -4
View File
@@ -1,6 +1,7 @@
import { CoverImage } from "@/components/cover-image"
import { useServerConfig } from "@/contexts/server-config"
import type { BrowseSong } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
import { formatDuration } from "@/lib/format"
import { albumCoverUrl } from "@/lib/urls"
import { miniPlayerHeight, spacing, useThemeColors } from "@/lib/theme"
@@ -18,6 +19,7 @@ export const SongRow = memo(function SongRow({
onPress,
contextMenu,
trailing,
palette,
}: {
song: BrowseSong
onPress?: () => void
@@ -25,14 +27,22 @@ export const SongRow = memo(function SongRow({
onAction: MediaMenuConfig["onAction"]
}
trailing?: React.ReactNode
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
}) {
const { config } = useServerConfig()
const colors = useThemeColors()
if (!config) return null
const foreground = palette?.foreground ?? colors.foreground
const secondaryForeground =
palette?.secondaryForeground ?? colors.mutedForeground
const row = (
<Pressable
style={[styles.row, { borderBottomColor: colors.border }]}
style={[
styles.row,
{ borderBottomColor: palette?.divider ?? colors.border },
]}
onPress={onPress}
>
<CoverImage
@@ -41,14 +51,14 @@ export const SongRow = memo(function SongRow({
style={styles.rowArtwork}
/>
<View style={styles.rowMeta}>
<Text style={[styles.rowTitle, { color: colors.foreground }]} numberOfLines={1}>
<Text style={[styles.rowTitle, { color: foreground }]} numberOfLines={1}>
{song.title}
</Text>
<Text style={[styles.rowSubtitle, { color: colors.mutedForeground }]} numberOfLines={1}>
<Text style={[styles.rowSubtitle, { color: secondaryForeground }]} numberOfLines={1}>
{song.artist.name} · {song.album.title}
</Text>
</View>
<Text style={[styles.duration, { color: colors.mutedForeground }]}>
<Text style={[styles.duration, { color: secondaryForeground }]}>
{formatDuration(song.durationSeconds)}
</Text>
{trailing}
@@ -75,12 +85,14 @@ export const SongListRow = memo(function SongListRow({
song,
favorited,
playlistLabel,
palette,
onPlay,
onAction,
}: {
song: BrowseSong
favorited: boolean
playlistLabel?: string
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
}) {
@@ -89,6 +101,7 @@ export const SongListRow = memo(function SongListRow({
return (
<SongRow
song={song}
palette={palette}
onPress={handlePress}
contextMenu={{
favorited,
+9 -4
View File
@@ -20,6 +20,8 @@ type ButtonProps = Omit<PressableProps, "style"> & {
loading?: boolean
icon?: React.ComponentProps<typeof Ionicons>["name"]
style?: StyleProp<ViewStyle>
/** Overrides the variant's colors, e.g. on screens tinted by cover art. */
tint?: { background: string; foreground: string }
}
export function Button({
@@ -29,13 +31,15 @@ export function Button({
disabled,
icon,
style,
tint,
...props
}: ButtonProps) {
const colors = useThemeColors()
const isDisabled = disabled || loading
const backgroundColor =
variant === "primary"
const backgroundColor = tint
? tint.background
: variant === "primary"
? colors.primary
: variant === "secondary"
? colors.muted
@@ -43,8 +47,9 @@ export function Button({
? colors.destructive
: "transparent"
const textColor =
variant === "primary"
const textColor = tint
? tint.foreground
: variant === "primary"
? colors.primaryForeground
: variant === "destructive"
? "#fff"
@@ -1,58 +0,0 @@
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
}
+163
View File
@@ -0,0 +1,163 @@
import { useEffect, useMemo, useState } from "react"
import { getColors, type ImageColorsResult } from "react-native-image-colors"
import {
deriveCoverPalette,
themeCoverPalette,
type CoverPalette,
type CoverSwatches,
} from "@/lib/cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
export const COVER_PALETTE_WAIT_MS = 400
// image-colors substitutes this for swatches it couldn't find.
const MISSING = "#010203"
const swatchesByKey = new Map<string, CoverSwatches | null>()
const pending = new Map<string, Promise<CoverSwatches | null>>()
function cacheKey(colorSourceUri: string) {
return `palette:${colorSourceUri}`
}
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,
]),
}
}
function sameSwatches(
a: CoverSwatches | null | undefined,
b: CoverSwatches | null | undefined
) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
function cachedSwatches(key: string): CoverSwatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
return readCache<CoverSwatches>(cacheKey(key))
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = getColors(key, {
fallback: MISSING,
cache: true,
key,
quality: "low",
pixelSpacing: 4,
})
.then(toSwatches)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
/**
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
* known yet so extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/
export function useCoverPalette(
uri: string,
hasCover: boolean | undefined
): { palette: CoverPalette; settled: boolean } {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: CoverSwatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background in
// case the cover changed.
const timer =
known === undefined
? setTimeout(() => !cancelled && setWaitedKey(key), COVER_PALETTE_WAIT_MS)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches ? deriveCoverPalette(swatches, isDark) : null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key || hasCover === false || swatches !== undefined || waitedKey === key,
}
}
+296
View File
@@ -0,0 +1,296 @@
import type { ThemeColors } from "@/lib/theme"
/**
* Colors for a screen tinted by its cover art, modeled on Apple Music's
* artwork colors (`bgColor`, `textColor1`, `textColor2`).
*/
export type CoverPalette = {
background: string
foreground: string
secondaryForeground: string
accent: string
accentForeground: string
/** `accent` adjusted to be legible as body text. */
accentText: string
surface: string
divider: string
isDark: boolean
}
/**
* Raw colors sampled from the art. `background` is the color the art bleeds
* into; `text` is ordered by preference and `accent` holds candidates for the
* Play button.
*/
export type CoverSwatches = {
background: string
text: string[]
accent: string[]
}
// Best effort: `legibleBackground` only guarantees that white or black reaches
// 7:1, so on some backgrounds primary text settles for pure white or black.
const PRIMARY_MIN_CONTRAST = 10
const SECONDARY_MIN_CONTRAST = 4.5
const SECONDARY_TO_PRIMARY_CONTRAST = 0.62
const ACCENT_MIN_CONTRAST = 3
const ACCENT_MIN_CHROMA = 0.05
const ACCENT_MAX_LIGHTNESS_SHIFT = 0.25
// Backgrounds between these luminances can't reach 7:1 with white or black.
const DARK_BACKGROUND_MAX_LUMINANCE = 0.095
const LIGHT_BACKGROUND_MIN_LUMINANCE = 0.31
type Rgb = [number, number, number]
type Oklch = { l: number; c: number; h: number }
export function themeCoverPalette(theme: ThemeColors, isDark: boolean): CoverPalette {
return {
background: theme.background,
foreground: theme.foreground,
secondaryForeground: theme.mutedForeground,
accent: theme.primary,
accentForeground: theme.primaryForeground,
accentText: theme.primary,
surface: theme.muted,
divider: theme.border,
isDark,
}
}
export function deriveCoverPalette(
swatches: CoverSwatches,
schemeIsDark: boolean
): CoverPalette | null {
const source = parseHex(swatches.background)
if (!source) return null
const background = legibleBackground(source, schemeIsDark)
const lightText = prefersLightText(background)
const parsedText = swatches.text
.map(parseHex)
.filter((color): color is Rgb => color !== null)
const backgroundLuminance = luminance(background)
const sameSideText = parsedText.filter((color) =>
lightText
? luminance(color) > backgroundLuminance
: luminance(color) < backgroundLuminance
)
const textCandidates = sameSideText.length > 0 ? sameSideText : parsedText
const fallbackText: Rgb = lightText ? [255, 255, 255] : [0, 0, 0]
const foreground = withMinContrast(
textCandidates[0] ?? fallbackText,
background,
PRIMARY_MIN_CONTRAST
)
const primaryContrast = contrastRatio(foreground, background)
const secondaryTarget = Math.max(
SECONDARY_MIN_CONTRAST,
primaryContrast * SECONDARY_TO_PRIMARY_CONTRAST
)
const secondaryForeground = softenTo(
withMinContrast(
textCandidates[1] ?? foreground,
background,
SECONDARY_MIN_CONTRAST
),
background,
secondaryTarget
)
const accent = pickAccent(swatches.accent, background) ?? foreground
const accentForeground: Rgb = prefersLightText(accent)
? [255, 255, 255]
: [0, 0, 0]
return {
background: toHex(background),
foreground: toHex(foreground),
secondaryForeground: toHex(secondaryForeground),
accent: toHex(accent),
accentForeground: toHex(accentForeground),
accentText: toHex(withMinContrast(accent, background, SECONDARY_MIN_CONTRAST)),
surface: toHex(mix(foreground, background, lightText ? 0.16 : 0.1)),
divider: toHex(mix(foreground, background, lightText ? 0.2 : 0.14)),
isDark: lightText,
}
}
function legibleBackground(color: Rgb, schemeIsDark: boolean): Rgb {
const lch = toOklch(color)
// Keep the art's hue but avoid a glaring page in dark mode or a murky one in
// light mode.
const clamped = schemeIsDark
? withLightness(color, Math.min(lch.l, 0.86))
: withLightness(color, Math.max(lch.l, 0.2))
const y = luminance(clamped)
if (y <= DARK_BACKGROUND_MAX_LUMINANCE || y >= LIGHT_BACKGROUND_MIN_LUMINANCE) {
return clamped
}
const pivot = schemeIsDark ? 0.28 : 0.14
return y < pivot
? withLuminance(clamped, DARK_BACKGROUND_MAX_LUMINANCE)
: withLuminance(clamped, LIGHT_BACKGROUND_MIN_LUMINANCE)
}
function pickAccent(candidates: string[], background: Rgb): Rgb | null {
let best: Rgb | null = null
let bestChroma = ACCENT_MIN_CHROMA
for (const hex of candidates) {
const color = parseHex(hex)
if (!color) continue
const adjusted = withMinContrast(color, background, ACCENT_MIN_CONTRAST)
const before = toOklch(color)
const after = toOklch(adjusted)
// A color pushed far from its own lightness (yellow turned olive) no
// longer reads as coming from the art.
if (Math.abs(after.l - before.l) > ACCENT_MAX_LIGHTNESS_SHIFT) continue
if (after.c > bestChroma) {
best = adjusted
bestChroma = after.c
}
}
return best
}
function prefersLightText(background: Rgb) {
return contrastRatio([255, 255, 255], background) >= contrastRatio([0, 0, 0], background)
}
/** Moves `color`'s lightness away from `background` until it reaches `min`. */
function withMinContrast(color: Rgb, background: Rgb, min: number): Rgb {
if (contrastRatio(color, background) >= min) return color
const lighten = prefersLightText(background)
const start = toOklch(color).l
const extreme = lighten ? 1 : 0
if (contrastRatio(withLightness(color, extreme), background) < min) {
return lighten ? [255, 255, 255] : [0, 0, 0]
}
let near = start
let far = extreme
for (let i = 0; i < 16; i++) {
const mid = (near + far) / 2
if (contrastRatio(withLightness(color, mid), background) >= min) {
far = mid
} else {
near = mid
}
}
return withLightness(color, far)
}
/** Blends `color` toward `background` until its contrast drops to `max`. */
function softenTo(color: Rgb, background: Rgb, max: number): Rgb {
if (contrastRatio(color, background) <= max) return color
let keep = 0
let blend = 1
for (let i = 0; i < 16; i++) {
const mid = (keep + blend) / 2
if (contrastRatio(mix(color, background, mid), background) >= max) {
blend = mid
} else {
keep = mid
}
}
return mix(color, background, blend)
}
function withLuminance(color: Rgb, target: number): Rgb {
let low = 0
let high = 1
for (let i = 0; i < 16; i++) {
const mid = (low + high) / 2
if (luminance(withLightness(color, mid)) < target) {
low = mid
} else {
high = mid
}
}
return withLightness(color, target <= DARK_BACKGROUND_MAX_LUMINANCE ? low : high)
}
/** `amount` of `color` over `base`. */
function mix(color: Rgb, base: Rgb, amount: number): Rgb {
return [0, 1, 2].map((i) =>
Math.round(base[i] + (color[i] - base[i]) * amount)
) as Rgb
}
function contrastRatio(a: Rgb, b: Rgb) {
const la = luminance(a)
const lb = luminance(b)
return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)
}
function luminance([r, g, b]: Rgb) {
return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b)
}
function toLinear(channel: number) {
const c = channel / 255
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
}
function fromLinear(value: number) {
const c = value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055
return c * 255
}
function toOklch(color: Rgb): Oklch {
const [r, g, b] = color.map(toLinear)
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s
const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s
const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s
return { l: L, c: Math.hypot(A, B), h: Math.atan2(B, A) }
}
function oklchToLinear({ l: L, c, h }: Oklch): Rgb {
const A = c * Math.cos(h)
const B = c * Math.sin(h)
const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3
const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3
const s = (L - 0.0894841775 * A - 1.291485548 * B) ** 3
return [
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
]
}
/** Sets OKLCH lightness, reducing chroma as needed to stay within sRGB. */
function withLightness(color: Rgb, lightness: number): Rgb {
const lch = toOklch(color)
const l = Math.min(1, Math.max(0, lightness))
let c = lch.c
let linear = oklchToLinear({ l, c, h: lch.h })
for (let i = 0; i < 12 && !inGamut(linear); i++) {
c *= 0.8
linear = oklchToLinear({ l, c, h: lch.h })
}
return linear.map((value) =>
Math.round(Math.min(255, Math.max(0, fromLinear(value))))
) as Rgb
}
function inGamut(linear: Rgb) {
return linear.every((value) => value >= -0.0005 && value <= 1.0005)
}
function parseHex(hex: string | undefined): Rgb | null {
if (!hex) return null
const match = /^#?([0-9a-f]{6})/i.exec(hex.trim())
if (!match) return null
const value = parseInt(match[1], 16)
return [(value >> 16) & 255, (value >> 8) & 255, value & 255]
}
function toHex(color: Rgb) {
return `#${color.map((c) => c.toString(16).padStart(2, "0")).join("")}`
}
+1 -1
View File
@@ -63,5 +63,5 @@ const asyncStorageBackend: PersistentCacheBackend = {
// Android's AsyncStorage database is capped at 6 MB by default, so keep fewer
// entries than the web cache.
configurePersistentCache(asyncStorageBackend, {
maxEntriesByPrefix: { q: 200, song: 3000, files: 500 },
maxEntriesByPrefix: { q: 200, song: 3000, files: 500, palette: 500 },
})