Files
otunes/apps/mobile/contexts/android-tab-theme.tsx
T

251 lines
8.0 KiB
TypeScript

import {
useIsFocused,
useRoute,
useNavigation,
type NativeStackNavigationProp,
} from "expo-router"
import {
createContext,
useCallback,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
type PropsWithChildren,
} from "react"
import { Platform, StyleSheet, type HostInstance } from "react-native"
import Reanimated, {
useSharedValue,
useAnimatedStyle,
useAnimatedReaction,
useAnimatedRef,
setNativeProps,
processColor,
withTiming,
type SharedValue,
} from "react-native-reanimated"
import { themeCoverPalette, type CoverPalette } from "@/lib/cover-palette"
import { useIsDark, useThemeColors } from "@/lib/theme"
export type PaletteColor = Exclude<keyof CoverPalette, "isDark">
type PaletteColors = Pick<CoverPalette, PaletteColor> & {
selectedColor: string
}
type TabTheme = {
palette: CoverPalette
colors: SharedValue<PaletteColors>
hasArtworkPalette: boolean
setPalette: (palette: CoverPalette | null, owner: string) => void
}
const AndroidTabTheme = createContext<TabTheme | null>(null)
function useDefaultPalette() {
const theme = useThemeColors()
const isDark = useIsDark()
return useMemo(() => themeCoverPalette(theme, isDark), [theme, isDark])
}
export function ScreenPaletteProvider({ children }: PropsWithChildren) {
const defaultPalette = useDefaultPalette()
const [screen, setScreen] = useState<{
palette: CoverPalette
owner: string
} | null>(null)
const palette = screen?.palette ?? defaultPalette
const hasArtwork =
palette.background !== defaultPalette.background ||
palette.foreground !== defaultPalette.foreground ||
palette.secondaryForeground !== defaultPalette.secondaryForeground ||
palette.accent !== defaultPalette.accent
const { isDark: _defaultIsDark, ...defaultColors } = defaultPalette
const animatedColors = useSharedValue<PaletteColors>({
...defaultColors,
selectedColor: defaultPalette.accentText,
})
useLayoutEffect(() => {
const { isDark: _isDark, ...colors } = palette
animatedColors.value = withTiming(
{
...colors,
selectedColor: hasArtwork
? palette.foreground
: defaultPalette.accentText,
},
{ duration: PALETTE_FADE_MS }
)
}, [animatedColors, palette, defaultPalette, hasArtwork])
const paletteOwner = useRef<string | null>(null)
const setPalette = useCallback(
(palette: CoverPalette | null, owner: string) => {
if (!palette && paletteOwner.current !== owner) return
paletteOwner.current = palette ? owner : null
// Start on the UI thread immediately. React may defer commits while
// the native stack is animating, including transitionStart state updates.
const target = palette ?? defaultPalette
const { isDark: _isDark, ...colors } = target
animatedColors.value = withTiming(
{
...colors,
selectedColor: palette ? target.foreground : target.accentText,
},
{ duration: PALETTE_FADE_MS }
)
setScreen(palette ? { palette, owner } : null)
},
[animatedColors, defaultPalette]
)
const artworkPalette = hasArtwork ? palette : null
const value = useMemo(
() => ({
palette: artworkPalette ?? defaultPalette,
colors: animatedColors,
hasArtworkPalette: artworkPalette !== null,
setPalette,
}),
[defaultPalette, artworkPalette, setPalette, animatedColors]
)
return (
<AndroidTabTheme.Provider value={value}>
{children}
</AndroidTabTheme.Provider>
)
}
/**
* NativeTabs forwards raw screen props to its Fabric screen. Bind that host
* directly so appearance updates stay on the UI thread with the page colors.
*/
export function useAndroidNativeTabColors() {
const colors = useContext(AndroidTabTheme)?.colors
const ref = useAnimatedRef<HostInstance>()
const mounted = useSharedValue(false)
const attach = useCallback(
(host: HostInstance | null) => {
if (host) ref(host)
mounted.value = host !== null
},
[ref, mounted]
)
useAnimatedReaction(
() => ({ colors: colors?.value, mounted: mounted.value }),
({ colors: palette, mounted: ready }) => {
if (Platform.OS !== "android" || !ready || !palette) return
const normal = processColor(palette.secondaryForeground)
const selected = processColor(palette.selectedColor)
setNativeProps(ref, {
standardAppearance: {
tabBarBackgroundColor: processColor("transparent"),
tabBarItemRippleColor: selected,
tabBarItemActiveIndicatorEnabled: false,
tabBarItemTitleSmallLabelFontSize: 10,
tabBarItemTitleLargeLabelFontSize: 10,
normal: {
tabBarItemTitleFontColor: normal,
tabBarItemIconColor: normal,
},
selected: {
tabBarItemTitleFontColor: selected,
tabBarItemIconColor: selected,
},
},
})
}
)
return { ref: attach, style: { backgroundColor: "transparent" } }
}
export function useAndroidTabPalette() {
const theme = useContext(AndroidTabTheme)
const defaultPalette = useDefaultPalette()
return theme?.palette ?? defaultPalette
}
export function useAndroidTabHasArtworkPalette() {
return useContext(AndroidTabTheme)?.hasArtworkPalette ?? false
}
export function useAndroidTabBackgroundStyle() {
const theme = useContext(AndroidTabTheme)
const fallback = useDefaultPalette().background
const colors = theme?.colors
return useAnimatedStyle(() =>
Platform.OS === "android" || (Platform.OS === "ios" && Platform.isPad)
? { backgroundColor: colors?.value.background ?? fallback }
: {}
)
}
/** Color tokens share the background's UI-thread timing. */
export function useAnimatedPaletteColor(tone: PaletteColor | undefined) {
const colors = useContext(AndroidTabTheme)?.colors
return useAnimatedStyle(() =>
Platform.OS === "android" && tone && colors
? { color: colors.value[tone] }
: {}
)
}
/** Native headers draw this same UI-thread background as the page and bars. */
function AndroidArtworkBackground() {
const style = useAndroidTabBackgroundStyle()
return <Reanimated.View style={[StyleSheet.absoluteFill, style]} />
}
export function renderAndroidArtworkBackground() {
return <AndroidArtworkBackground />
}
const PALETTE_FADE_MS = 400
/** The focused artwork screen selects the shared background for page and bars. */
export function useScreenPalette(palette: CoverPalette) {
const isFocused = useIsFocused()
const isTablet = Platform.OS === "ios" && Platform.isPad
const sharesPalette =
Platform.OS === "android" || (Platform.OS === "ios" && Platform.isPad)
const owner = useRoute().key
const navigation =
useNavigation<NativeStackNavigationProp<Record<string, undefined>>>()
const [laidOut, setLaidOut] = useState(false)
const [closing, setClosing] = useState(false)
const onLayout = useCallback(() => setLaidOut(true), [])
const theme = useContext(AndroidTabTheme)
const setPalette = theme?.setPalette
useLayoutEffect(() => {
if (!sharesPalette) return
const start = navigation.addListener("transitionStart", ({ data }) => {
if (data.closing) setPalette?.(null, owner)
else setPalette?.(palette, owner)
setClosing(data.closing)
})
const cancel = navigation.addListener("gestureCancel", () => {
setPalette?.(palette, owner)
setClosing(false)
})
return () => {
start()
cancel()
}
}, [navigation, sharesPalette, setPalette, owner, palette])
const defaultPalette = useDefaultPalette()
const ready = laidOut || isTablet
const target = isFocused && ready && !closing ? palette : defaultPalette
const backgroundStyle = useAndroidTabBackgroundStyle()
useLayoutEffect(() => {
if (!sharesPalette || !setPalette || !isFocused || !ready || closing) return
setPalette(palette, owner)
return () => setPalette(null, owner)
}, [closing, ready, isFocused, owner, palette, setPalette, sharesPalette])
return {
palette: Platform.OS === "android" ? target : palette,
backgroundStyle,
onLayout: sharesPalette ? onLayout : undefined,
}
}