diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx
index 8ec6b43..c0a2a28 100644
--- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx
+++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx
@@ -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 ? (
+
+ ) : null,
+ [album, handleAlbumTrackAction, isSongFavorite, palette, playFromSong, songIds]
)
- if (album === undefined || !config) {
+ if (album === undefined || !config || !settled) {
return (
<>
+ {isFocused ? (
+
+ ) : null}
(
@@ -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={
-
+
{album.title}
push(`/artist/${album.artist.id}`)}>
-
+
{album.artist.name}
{metadata ? (
- {metadata}
+
+ {metadata}
+
) : null}
void toggleAlbumFavorite(album.id)}
hitSlop={8}
- style={[styles.iconAction, { backgroundColor: colors.muted }]}
+ style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
}
- renderItem={({ item: track, index }) => (
-
- )}
+ 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
onAction: (
track: BrowseAlbumTrack,
@@ -225,8 +247,6 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
action: MediaAction
) => Promise
}) {
- const colors = useThemeColors()
-
return (
void onAction(track, album, action)}
>
void onPlay(track.id, songIds)}
+ style={[styles.trackRow, { borderBottomColor: palette.divider }]}
+ onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
-
+
{track.track || index + 1}
{track.title}
{track.artists ? (
-
+
{track.artists.join(", ")}
) : null}
-
+
{formatDuration(track.durationSeconds)}
diff --git a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx
index 995a307..8aef17c 100644
--- a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx
+++ b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx
@@ -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: () => (
@@ -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 ? (
+
+ ) : null}
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) => (
void
onPlay: () => void
onShuffle: () => void
}) {
- const colors = useThemeColors()
-
return (
- {title}
- {ownerName}
+ {title}
+ {ownerName}
{showSubscribe ? (
@@ -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
}
/>
@@ -466,15 +475,19 @@ const PlaylistHero = memo(function PlaylistHero({
icon="play"
onPress={onPlay}
style={styles.playButton}
+ tint={{
+ background: palette.accent,
+ foreground: palette.accentForeground,
+ }}
/>
-
+
diff --git a/apps/mobile/components/player.tsx b/apps/mobile/components/player.tsx
index 93d4a59..51c6ee9 100644
--- a/apps/mobile/components/player.tsx
+++ b/apps/mobile/components/player.tsx
@@ -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
}) {
const { config } = useServerConfig()
const colors = useThemeColors()
if (!config) return null
+ const foreground = palette?.foreground ?? colors.foreground
+ const secondaryForeground =
+ palette?.secondaryForeground ?? colors.mutedForeground
+
const row = (
-
+
{song.title}
-
+
{song.artist.name} ยท {song.album.title}
-
+
{formatDuration(song.durationSeconds)}
{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
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
}) {
@@ -89,6 +101,7 @@ export const SongListRow = memo(function SongListRow({
return (
& {
loading?: boolean
icon?: React.ComponentProps["name"]
style?: StyleProp
+ /** 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"
diff --git a/apps/mobile/hooks/use-cover-background-color.ts b/apps/mobile/hooks/use-cover-background-color.ts
deleted file mode 100644
index 18b5614..0000000
--- a/apps/mobile/hooks/use-cover-background-color.ts
+++ /dev/null
@@ -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
-}
diff --git a/apps/mobile/hooks/use-cover-palette.ts b/apps/mobile/hooks/use-cover-palette.ts
new file mode 100644
index 0000000..4fd199b
--- /dev/null
+++ b/apps/mobile/hooks/use-cover-palette.ts
@@ -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()
+const pending = new Map>()
+
+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(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(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,
+ }
+}
diff --git a/apps/mobile/lib/cover-palette.ts b/apps/mobile/lib/cover-palette.ts
new file mode 100644
index 0000000..fa441fb
--- /dev/null
+++ b/apps/mobile/lib/cover-palette.ts
@@ -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("")}`
+}
diff --git a/apps/mobile/lib/persistent-cache.ts b/apps/mobile/lib/persistent-cache.ts
index 821fb32..fc63ed4 100644
--- a/apps/mobile/lib/persistent-cache.ts
+++ b/apps/mobile/lib/persistent-cache.ts
@@ -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 },
})