Files
otunes/apps/mobile/lib/app-navigation.ts
T
joshuafhigginsandClaude Opus 5.5 Verified 2c6709d2ac fix(mobile): open library albums in the library tab
Album cards built their link from a global active-tab ref read at render
time. Cards on the library page could render before the ref caught up with
the tab switch, so their links pointed at the home tab. Each tab stack now
provides its own tab through context, and navigation resolves against it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 02:00:36 -05:00

96 lines
2.4 KiB
TypeScript

import { useRouter, useSegments, type Href } from "expo-router"
import { createContext, use, useCallback } from "react"
import { tabletSections } from "@/lib/tablet-navigation"
export const APP_TABS = [
"home",
"library",
"search",
...tabletSections.map((section) => section.group),
] as const
export type AppTab = (typeof APP_TABS)[number]
const TAB_SET = new Set<string>(APP_TABS)
const activeSegmentsRef: { current: string[] } = { current: [] }
export function getActiveTab(segments: string[]): AppTab {
for (const segment of segments) {
if (TAB_SET.has(segment)) {
return segment as AppTab
}
}
return "home"
}
export function tabPath(tab: AppTab, path: string): Href {
const normalized = path.startsWith("/") ? path : `/${path}`
return `/(app)/(tabs)/${tab}${normalized}` as Href
}
/**
* The tab whose stack a screen lives in. Each tab stack layout provides it so
* links resolve against the screen's own tab, even when the global segments
* ref has not caught up with a tab switch yet.
*/
export const TabStackContext = createContext<AppTab | undefined>(undefined)
function getActiveTabFromRef(): AppTab {
return getActiveTab(activeSegmentsRef.current)
}
/** Mount once in the app shell so navigation helpers can read the active tab without re-rendering consumers. */
export function AppNavigationSync() {
const segments = useSegments()
activeSegmentsRef.current = segments as string[]
return null
}
/** Tab-aware navigation: paths resolve inside the caller's tab stack, falling back to the active tab outside one. */
export function useAppNavigation() {
const router = useRouter()
const stackTab = use(TabStackContext)
const currentTab = useCallback(
() => stackTab ?? getActiveTabFromRef(),
[stackTab]
)
const push = useCallback(
(path: string) => {
if (activeSegmentsRef.current.includes("player")) {
// Leave the root player modal before navigating into the library stack.
router.dismiss()
router.navigate(tabPath("library", path))
return
}
router.push(tabPath(currentTab(), path))
},
[router, currentTab]
)
const replace = useCallback(
(path: string) => {
router.replace(tabPath(currentTab(), path))
},
[router, currentTab]
)
const href = useCallback(
(path: string) => tabPath(currentTab(), path),
[currentTab]
)
return {
get tab() {
return currentTab()
},
href,
push,
replace,
}
}