62 lines
1.5 KiB
TypeScript
62 lines
1.5 KiB
TypeScript
import { useRouter, useSegments, type Href } from "expo-router"
|
|
import { useCallback } from "react"
|
|
|
|
export const APP_TABS = ["home", "library", "search"] 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) => {
|
|
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,
|
|
}
|
|
}
|