fix(mobile): run only the selected artwork color pipeline (#92)

This commit was merged in pull request #92.
This commit is contained in:
joshuafhiggins committed 2026-11-16 21:43:53 -05:00
1 parent db29de28c0
commit cf61b0ac25
5 files changed
+216 -284

No files matched your search

@@ -23,7 +23,6 @@ import { useServerConfig } from "@/contexts/server-config"
import { import {
setArtworkColorsEnabled, setArtworkColorsEnabled,
useArtworkColorsEnabled, useArtworkColorsEnabled,
useArtworkColorPreferenceLoaded,
} from "@/lib/artwork-color-preference" } from "@/lib/artwork-color-preference"
import { initialsFromName } from "@/lib/format" import { initialsFromName } from "@/lib/format"
import { useCachedQuery } from "@/hooks/use-cached-query" import { useCachedQuery } from "@/hooks/use-cached-query"
@@ -172,7 +171,6 @@ export default function SettingsScreen() {
function AppearanceSection() { function AppearanceSection() {
const enabled = useArtworkColorsEnabled() const enabled = useArtworkColorsEnabled()
const loaded = useArtworkColorPreferenceLoaded()
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
return ( return (
@@ -180,8 +178,8 @@ function AppearanceSection() {
<SwitchRow <SwitchRow
title="New artwork colors" title="New artwork colors"
subtitle="Use the new color algorithm on this device." subtitle="Use the new color algorithm on this device."
value={enabled} value={enabled ?? false}
disabled={!loaded || saving} disabled={enabled === undefined || saving}
onValueChange={async (checked) => { onValueChange={async (checked) => {
setSaving(true) setSaving(true)
try { try {
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useMemo, useState } from "react"
import { themeCoverPalette, type CoverPalette } 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
export type CoverPaletteResult = { palette: CoverPalette; settled: boolean }
type CoverPaletteSourceOptions<Swatches> = {
/** Persistent cache key for a 64px cover URI. */
cacheKey: (colorSourceUri: string) => string
extract: (colorSourceUri: string) => Promise<Swatches | null>
derive: (swatches: Swatches, isDark: boolean) => CoverPalette | null
/** Reject persisted entries written in an older shape. */
isValidCache?: (swatches: Swatches) => boolean
}
/**
* One artwork color pipeline: an extractor and palette derivation with their
* own memory cache, persistent cache and in-flight requests.
*/
export function createCoverPaletteSource<Swatches>({
cacheKey,
extract,
derive,
isValidCache,
}: CoverPaletteSourceOptions<Swatches>) {
const swatchesByKey = new Map<string, Swatches | null>()
const pending = new Map<string, Promise<Swatches | null>>()
function cachedSwatches(key: string): Swatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
const cached = readCache<Swatches>(cacheKey(key))
return cached && isValidCache && !isValidCache(cached) ? undefined : cached
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = extract(key)
.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
}
function prefetch(uri: string) {
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
/**
* Colors for a screen tinted by `uri`'s cover art. Pass `uri` as "" to skip
* extraction. 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.
*/
function usePalette(
uri: string,
hasCover: boolean | undefined
): CoverPaletteResult {
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: Swatches | 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 ? derive(swatches, isDark) : null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key ||
hasCover === false ||
swatches !== undefined ||
waitedKey === key,
}
}
return { prefetch, usePalette }
}
function sameSwatches(a: unknown, b: unknown) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
+30 -130
View File
@@ -1,147 +1,47 @@
import { useEffect, useMemo, useState } from "react"
import { import {
artworkColorsEnabled, createCoverPaletteSource,
type CoverPaletteResult,
} from "@/hooks/cover-palette-source"
import {
prefetchLegacyCoverPalette,
useLegacyCoverPalette,
} from "@/hooks/use-legacy-cover-palette"
import {
loadArtworkColorsEnabled,
useArtworkColorsEnabled, useArtworkColorsEnabled,
} from "@/lib/artwork-color-preference" } from "@/lib/artwork-color-preference"
import { prefetchLegacyCoverPalette, useLegacyCoverPalette } from "@/hooks/use-legacy-cover-palette"
import { extractCoverSwatches } from "@/lib/artwork-colors" import { extractCoverSwatches } from "@/lib/artwork-colors"
import { deriveCoverPalette, type CoverSwatches } from "@/lib/cover-palette"
import { export { COVER_PALETTE_WAIT_MS } from "@/hooks/cover-palette-source"
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, const region = createCoverPaletteSource<CoverSwatches>({
// so rows render once with final colors instead of flashing from the theme. cacheKey: (colorSourceUri) => `palette:v2:${colorSourceUri}`,
export const COVER_PALETTE_WAIT_MS = 400 extract: extractCoverSwatches,
derive: (swatches) => deriveCoverPalette(swatches),
const swatchesByKey = new Map<string, CoverSwatches | null>() })
const pending = new Map<string, Promise<CoverSwatches | null>>()
function cacheKey(colorSourceUri: string) {
return `palette:v2:${colorSourceUri}`
}
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 = extractCoverSwatches(key)
.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
}
/** Warm visible artwork colors before a detail page is pushed. */ /** Warm visible artwork colors before a detail page is pushed. */
export function prefetchCoverPalette(uri: string) { export function prefetchCoverPalette(uri: string) {
if (!artworkColorsEnabled()) { void loadArtworkColorsEnabled().then((enabled) =>
prefetchLegacyCoverPalette(uri) enabled ? region.prefetch(uri) : prefetchLegacyCoverPalette(uri)
return )
}
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
} }
/** /**
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per * Colors for a screen tinted by `uri`'s cover art, from whichever pipeline the
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't * device preference selects. Nothing is extracted until the preference loads,
* known yet so extraction can start early. * and the screen stays unsettled meanwhile so it doesn't flash theme colors.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/ */
function useRegionCoverPalette( export function useCoverPalette(
uri: string, uri: string,
hasCover: boolean | undefined hasCover: boolean | undefined
): { palette: CoverPalette; settled: boolean } { ): CoverPaletteResult {
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)
: null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key || hasCover === false || swatches !== undefined || waitedKey === key,
}
}
/** Switch both extraction and palette derivation without mixing their caches. */
export function useCoverPalette(uri: string, hasCover: boolean | undefined) {
const enabled = useArtworkColorsEnabled() const enabled = useArtworkColorsEnabled()
const region = useRegionCoverPalette(enabled ? uri : "", hasCover) const current = region.usePalette(enabled === true ? uri : "", hasCover)
const legacy = useLegacyCoverPalette(enabled ? "" : uri, hasCover) const legacy = useLegacyCoverPalette(enabled === false ? uri : "", hasCover)
return enabled ? region : legacy if (enabled === undefined) {
return { palette: current.palette, settled: !uri || hasCover === false }
}
return enabled ? current : legacy
} }
+21 -132
View File
@@ -1,29 +1,14 @@
import { useEffect, useMemo, useState } from "react"
import { getColors, type ImageColorsResult } from "react-native-image-colors" import { getColors, type ImageColorsResult } from "react-native-image-colors"
import { createCoverPaletteSource } from "@/hooks/cover-palette-source"
import { import {
themeCoverPalette, deriveCoverPalette,
type CoverPalette, type LegacyCoverSwatches as CoverSwatches,
} from "@/lib/cover-palette" } from "@/lib/legacy-cover-palette"
import { deriveCoverPalette, type LegacyCoverSwatches as CoverSwatches } from "@/lib/legacy-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.
const COVER_PALETTE_WAIT_MS = 400
// image-colors substitutes this for swatches it couldn't find. // image-colors substitutes this for swatches it couldn't find.
const MISSING = "#010203" 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)[]) { function present(colors: (string | undefined)[]) {
return colors.filter( return colors.filter(
(color): color is string => !!color && color.toLowerCase() !== MISSING (color): color is string => !!color && color.toLowerCase() !== MISSING
@@ -59,120 +44,24 @@ function toSwatches(result: ImageColorsResult): CoverSwatches | null {
} }
} }
function sameSwatches( const legacy = createCoverPaletteSource<CoverSwatches>({
a: CoverSwatches | null | undefined, cacheKey: (colorSourceUri) => `palette:${colorSourceUri}`,
b: CoverSwatches | null | undefined extract: (key) =>
) { getColors(key, {
return a === b || JSON.stringify(a) === JSON.stringify(b) fallback: MISSING,
} cache: true,
key,
function cachedSwatches(key: string): CoverSwatches | null | undefined { quality: "low",
if (swatchesByKey.has(key)) return swatchesByKey.get(key) pixelSpacing: 4,
const cached = readCache<CoverSwatches>(cacheKey(key)) }).then(toSwatches),
derive: deriveCoverPalette,
// Discard the background-only entries written by the tablet palette experiment. // Discard the background-only entries written by the tablet palette experiment.
return cached && (!Array.isArray(cached.text) || !Array.isArray(cached.accent)) isValidCache: (cached) =>
? undefined Array.isArray(cached.text) && Array.isArray(cached.accent),
: cached })
}
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
}
/** Warm visible artwork colors before a detail page is pushed. */ /** Warm visible artwork colors before a detail page is pushed. */
export function prefetchLegacyCoverPalette(uri: string) { export const prefetchLegacyCoverPalette = legacy.prefetch
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
/** /** `react-native-image-colors` pipeline used when new artwork colors are off. */
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per export const useLegacyCoverPalette = legacy.usePalette
* 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 useLegacyCoverPalette(
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,
}
}
+21 -18
View File
@@ -3,8 +3,8 @@ import { useSyncExternalStore } from "react"
const STORAGE_KEY = "otunes:artwork-colors" const STORAGE_KEY = "otunes:artwork-colors"
const listeners = new Set<() => void>() const listeners = new Set<() => void>()
let enabled = true // Undefined until storage has been read, so callers never act on a guess.
let loaded = false let enabled: boolean | undefined
let loading: Promise<void> | undefined let loading: Promise<void> | undefined
function notify() { function notify() {
@@ -13,37 +13,40 @@ function notify() {
function load() { function load() {
return (loading ??= AsyncStorage.getItem(STORAGE_KEY) return (loading ??= AsyncStorage.getItem(STORAGE_KEY)
.then((value) => value !== "false")
// Keep the default when local storage is unavailable.
.catch(() => true)
.then((value) => { .then((value) => {
enabled = value !== "false" enabled = value
})
.catch(() => {
// Keep the default when local storage is unavailable.
})
.finally(() => {
loaded = true
notify() notify()
})) }))
} }
void load()
function subscribe(listener: () => void) { function subscribe(listener: () => void) {
listeners.add(listener) listeners.add(listener)
void load()
return () => { return () => {
listeners.delete(listener) listeners.delete(listener)
} }
} }
/** Device preference, kept outside account data and the disposable query cache. */ /**
* Device preference, kept outside account data and the disposable query cache.
* `undefined` until it has loaded.
*/
export function useArtworkColorsEnabled() { export function useArtworkColorsEnabled() {
return useSyncExternalStore(subscribe, () => loaded && enabled, () => false) return useSyncExternalStore(
subscribe,
() => enabled,
() => undefined
)
} }
export function useArtworkColorPreferenceLoaded() { /** Resolves with the preference once it has loaded. */
return useSyncExternalStore(subscribe, () => loaded, () => false) export async function loadArtworkColorsEnabled() {
} await load()
return enabled ?? true
export function artworkColorsEnabled() {
return loaded && enabled
} }
export async function setArtworkColorsEnabled(value: boolean) { export async function setArtworkColorsEnabled(value: boolean) {