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

82 lines
1.9 KiB
TypeScript

import { useRouter, useSegments, type Href } from "expo-router"
import { 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
}
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
}
export function useAppNavigation() {
const router = useRouter()
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(getActiveTabFromRef(), path))
},
[router]
)
const replace = useCallback(
(path: string) => {
router.replace(tabPath(getActiveTabFromRef(), path))
},
[router]
)
const href = useCallback(
(path: string) => tabPath(getActiveTabFromRef(), path),
[]
)
return {
get tab() {
return getActiveTabFromRef()
},
href,
push,
replace,
}
}