From cf61b0ac2548eeddadc745f3603e58d8552979a8 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:43:53 -0500 Subject: [PATCH] fix(mobile): run only the selected artwork color pipeline (#92) --- .../mobile/app/(app)/(tabs)/home/settings.tsx | 6 +- apps/mobile/hooks/cover-palette-source.ts | 142 ++++++++++++++++ apps/mobile/hooks/use-cover-palette.ts | 160 ++++-------------- apps/mobile/hooks/use-legacy-cover-palette.ts | 153 +++-------------- apps/mobile/lib/artwork-color-preference.ts | 39 +++-- 5 files changed, 216 insertions(+), 284 deletions(-) create mode 100644 apps/mobile/hooks/cover-palette-source.ts diff --git a/apps/mobile/app/(app)/(tabs)/home/settings.tsx b/apps/mobile/app/(app)/(tabs)/home/settings.tsx index 30a0cfb..d3e8d72 100644 --- a/apps/mobile/app/(app)/(tabs)/home/settings.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/settings.tsx @@ -23,7 +23,6 @@ import { useServerConfig } from "@/contexts/server-config" import { setArtworkColorsEnabled, useArtworkColorsEnabled, - useArtworkColorPreferenceLoaded, } from "@/lib/artwork-color-preference" import { initialsFromName } from "@/lib/format" import { useCachedQuery } from "@/hooks/use-cached-query" @@ -172,7 +171,6 @@ export default function SettingsScreen() { function AppearanceSection() { const enabled = useArtworkColorsEnabled() - const loaded = useArtworkColorPreferenceLoaded() const [saving, setSaving] = useState(false) return ( @@ -180,8 +178,8 @@ function AppearanceSection() { { setSaving(true) try { diff --git a/apps/mobile/hooks/cover-palette-source.ts b/apps/mobile/hooks/cover-palette-source.ts new file mode 100644 index 0000000..31e1d35 --- /dev/null +++ b/apps/mobile/hooks/cover-palette-source.ts @@ -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 = { + /** Persistent cache key for a 64px cover URI. */ + cacheKey: (colorSourceUri: string) => string + extract: (colorSourceUri: string) => Promise + 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({ + cacheKey, + extract, + derive, + isValidCache, +}: CoverPaletteSourceOptions) { + const swatchesByKey = new Map() + const pending = new Map>() + + function cachedSwatches(key: string): Swatches | null | undefined { + if (swatchesByKey.has(key)) return swatchesByKey.get(key) + const cached = readCache(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(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) +} diff --git a/apps/mobile/hooks/use-cover-palette.ts b/apps/mobile/hooks/use-cover-palette.ts index 7280c45..6cea962 100644 --- a/apps/mobile/hooks/use-cover-palette.ts +++ b/apps/mobile/hooks/use-cover-palette.ts @@ -1,147 +1,47 @@ -import { useEffect, useMemo, useState } from "react" import { - artworkColorsEnabled, + createCoverPaletteSource, + type CoverPaletteResult, +} from "@/hooks/cover-palette-source" +import { + prefetchLegacyCoverPalette, + useLegacyCoverPalette, +} from "@/hooks/use-legacy-cover-palette" +import { + loadArtworkColorsEnabled, useArtworkColorsEnabled, } from "@/lib/artwork-color-preference" -import { prefetchLegacyCoverPalette, useLegacyCoverPalette } from "@/hooks/use-legacy-cover-palette" import { extractCoverSwatches } from "@/lib/artwork-colors" +import { deriveCoverPalette, type CoverSwatches } from "@/lib/cover-palette" -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" +export { COVER_PALETTE_WAIT_MS } from "@/hooks/cover-palette-source" -// 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 - -const swatchesByKey = new Map() -const pending = new Map>() - -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(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 -} +const region = createCoverPaletteSource({ + cacheKey: (colorSourceUri) => `palette:v2:${colorSourceUri}`, + extract: extractCoverSwatches, + derive: (swatches) => deriveCoverPalette(swatches), +}) /** Warm visible artwork colors before a detail page is pushed. */ export function prefetchCoverPalette(uri: string) { - if (!artworkColorsEnabled()) { - prefetchLegacyCoverPalette(uri) - return - } - const key = withCoverImageSize(uri, 64) - if (cachedSwatches(key) !== undefined) return - void extractSwatches(key) + void loadArtworkColorsEnabled().then((enabled) => + enabled ? region.prefetch(uri) : prefetchLegacyCoverPalette(uri) + ) } /** - * 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. + * Colors for a screen tinted by `uri`'s cover art, from whichever pipeline the + * device preference selects. Nothing is extracted until the preference loads, + * and the screen stays unsettled meanwhile so it doesn't flash theme colors. */ -function useRegionCoverPalette( +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) - : 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) { +): CoverPaletteResult { const enabled = useArtworkColorsEnabled() - const region = useRegionCoverPalette(enabled ? uri : "", hasCover) - const legacy = useLegacyCoverPalette(enabled ? "" : uri, hasCover) - return enabled ? region : legacy + const current = region.usePalette(enabled === true ? uri : "", hasCover) + const legacy = useLegacyCoverPalette(enabled === false ? uri : "", hasCover) + if (enabled === undefined) { + return { palette: current.palette, settled: !uri || hasCover === false } + } + return enabled ? current : legacy } diff --git a/apps/mobile/hooks/use-legacy-cover-palette.ts b/apps/mobile/hooks/use-legacy-cover-palette.ts index 49a7350..9ea720b 100644 --- a/apps/mobile/hooks/use-legacy-cover-palette.ts +++ b/apps/mobile/hooks/use-legacy-cover-palette.ts @@ -1,29 +1,14 @@ -import { useEffect, useMemo, useState } from "react" import { getColors, type ImageColorsResult } from "react-native-image-colors" +import { createCoverPaletteSource } from "@/hooks/cover-palette-source" import { - themeCoverPalette, - type CoverPalette, -} from "@/lib/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 + deriveCoverPalette, + type LegacyCoverSwatches as CoverSwatches, +} from "@/lib/legacy-cover-palette" // 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 @@ -59,120 +44,24 @@ function toSwatches(result: ImageColorsResult): CoverSwatches | null { } } -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) - const cached = readCache(cacheKey(key)) +const legacy = createCoverPaletteSource({ + 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. - return cached && (!Array.isArray(cached.text) || !Array.isArray(cached.accent)) - ? undefined - : 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 -} + isValidCache: (cached) => + Array.isArray(cached.text) && Array.isArray(cached.accent), +}) /** Warm visible artwork colors before a detail page is pushed. */ -export function prefetchLegacyCoverPalette(uri: string) { - const key = withCoverImageSize(uri, 64) - if (cachedSwatches(key) !== undefined) return - void extractSwatches(key) -} +export const prefetchLegacyCoverPalette = legacy.prefetch -/** - * 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 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(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, - } -} +/** `react-native-image-colors` pipeline used when new artwork colors are off. */ +export const useLegacyCoverPalette = legacy.usePalette diff --git a/apps/mobile/lib/artwork-color-preference.ts b/apps/mobile/lib/artwork-color-preference.ts index 2651ddd..c59d684 100644 --- a/apps/mobile/lib/artwork-color-preference.ts +++ b/apps/mobile/lib/artwork-color-preference.ts @@ -3,8 +3,8 @@ import { useSyncExternalStore } from "react" const STORAGE_KEY = "otunes:artwork-colors" const listeners = new Set<() => void>() -let enabled = true -let loaded = false +// Undefined until storage has been read, so callers never act on a guess. +let enabled: boolean | undefined let loading: Promise | undefined function notify() { @@ -13,37 +13,40 @@ function notify() { function load() { return (loading ??= AsyncStorage.getItem(STORAGE_KEY) + .then((value) => value !== "false") + // Keep the default when local storage is unavailable. + .catch(() => true) .then((value) => { - enabled = value !== "false" - }) - .catch(() => { - // Keep the default when local storage is unavailable. - }) - .finally(() => { - loaded = true + enabled = value notify() })) } +void load() + function subscribe(listener: () => void) { listeners.add(listener) - void load() return () => { 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() { - return useSyncExternalStore(subscribe, () => loaded && enabled, () => false) + return useSyncExternalStore( + subscribe, + () => enabled, + () => undefined + ) } -export function useArtworkColorPreferenceLoaded() { - return useSyncExternalStore(subscribe, () => loaded, () => false) -} - -export function artworkColorsEnabled() { - return loaded && enabled +/** Resolves with the preference once it has loaded. */ +export async function loadArtworkColorsEnabled() { + await load() + return enabled ?? true } export async function setArtworkColorsEnabled(value: boolean) {