Files
otunes/apps/mobile/lib/app-navigation.ts
T

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,
}
}