import { shouldReplayLinkingUrl } from './linkingReplay'; import * as React from 'react'; import { StateNavigator } from 'navigation'; import { type BaseScreen, type FluentParams, type FluentScreen, generatePath, getPathFromUrl, getRootKeyFromPath, getScreenKey, getSharedElementsForState, makeVariablesNavigationFriendly, type Root, type RootChildBottomTabs, rootKeyAndPaths, } from './navigationUtils'; import { defaultTheme, type ThemeSettings } from './theme'; import { Platform, useColorScheme } from 'react-native'; import { NavigationHandler } from 'navigation-react'; import NavigationStack from './navigation/NavigationStack'; import BottomTabsStack from './BottomTabsStack'; import RidgeNavigationContext from './contexts/RidgeNavigationContext'; import NavigationStackWrapper from './NavigationStackWrapper'; import type { PreloadableComponent } from './lazy'; import { OptimizedContextProvider } from './contexts/OptimizedContext'; import getHistoryManager from './navigation/historyManager'; import BottomTabBadgeProvider from './contexts/BottomTabBadgeProvider'; import BottomTabIndexProvider from './contexts/BottomTabIndexProvider'; import HiddenNavbarWithSwipeBack from './HiddenNavbarWithSwipeBack'; import BottomTabRefreshProvider from './contexts/BottomTabRefreshProvider'; import { useNavigationUrl } from './useNavigationUrl'; import { getRootPreloadScreens } from './rootPreloadPolicy'; import { NavigationBackGestureProvider } from './contexts/RidgeNavigationContext'; import { getPreloadReady } from './Preloader'; import { whenAllReady } from './screenReadiness'; import { NavigationTransitionProvider } from './navigationTransition'; export default function NavigationProvider({ screens, navigationRoot, SuspenseContainer, themeSettings, children, initialRootKey, basePath, pendingMs, }: { screens: ScreenItems; navigationRoot: Root; SuspenseContainer: any; themeSettings?: ThemeSettings; children?: any; initialRootKey: string; basePath?: string; /** * Web: how long a navigation keeps the current screen while the next one * loads its code and preloaded data. After this the next screen commits and * shows its own Suspense fallback. Default 1000 ms. */ pendingMs?: number; }) { const { setGoToUrl, goToUrl, initialDefaultUrl } = useNavigationUrl({ navigationRoot, initialRootKey, basePath, }); const colorScheme = useColorScheme(); const theme = React.useMemo( () => (themeSettings || defaultTheme)[ colorScheme === 'dark' ? 'dark' : 'light' ], [colorScheme, themeSettings] ); const preloadedCache = React.useRef>({}); // When each path was last preloaded, shared by every Link so two links to // the same screen (or repeated hovers) do not preload it twice. const preloadedAt = React.useRef>({}); const loadedElements = React.useRef(new WeakSet()); const preloadScreen = React.useCallback( (screen: T, params: any) => { try { const result = screen.preload(params); const path = generatePath(screen.path, params); preloadedCache.current[path] = result; preloadedAt.current[path] = Date.now(); return result; } catch (error) { console.log( '[react-native-ridge-navigation] error while preloading screen', screen, params, error ); } return undefined; }, [] ); const preloadElement = React.useCallback( async (screen: T) => { try { const element = screen.element as PreloadableComponent; const loaded = await element?.preload?.(); if (element) { loadedElements.current.add(element); } return loaded; } catch (error) { console.log( '[react-native-ridge-navigation] error while preloading element', screen, error ); } return undefined; }, [] ); const whenScreenReady = React.useCallback( (screen: T, params: any, preloaded: any) => { const element = screen.element as PreloadableComponent | undefined; const elementReady = !element?.preload || loadedElements.current.has(element) ? null : preloadElement(screen); return whenAllReady([ elementReady, getPreloadReady({ preloaded, params, screen }), ]); }, [preloadElement] ); const preloadRoot = React.useCallback( (rootKey: string) => { const root = navigationRoot[rootKey]; if (!root) { console.log( '[react-native-ridge-navigation] No root found for key', rootKey ); return; } getRootPreloadScreens(root, { // Native tab stacks mount eagerly. Preload every root screen before // those mounted scenes read their route data; web remains URL-aware. includeAllTabs: root.type === 'bottomTabs' && Platform.OS !== 'web', }).forEach((screen) => { preloadElement(screen); preloadScreen(screen, {}); }); }, [navigationRoot, preloadElement, preloadScreen] ); const rootNavigator = React.useMemo(() => { const navigators = Object.entries(navigationRoot) .map(([rootKey, root]) => { switch (root.type) { case 'bottomTabs': // on the web we don't have a nested stack because we want to preserve the history // on native, we need to nest the stack for bottom tabs return [ { key: rootKey, route: rootKey, trackCrumbTrail: false, preload: () => preloadRoot(rootKey), preloadId: rootKey, renderScene: () => Platform.OS === 'web' ? null : ( ), }, ...root.children .map((tab) => { return screens.map((screen) => { // we don't want the child path segment in the url const isTheSame = tab.child.path === screen.path; return { key: getScreenKey(rootKey, tab, screen.path), route: makeVariablesNavigationFriendly( getScreenKey(rootKey, tab, screen.path) ), renderScene: () => ( ), trackCrumbTrail: !isTheSame, screen, preloadId: screen.path, }; }); }) .flat(2), ]; case 'normal': return [ { key: rootKey, route: rootKey, trackCrumbTrail: false, renderScene: () => ( ), screen: root.child, preload: () => preloadRoot(rootKey), preloadId: root.child.path, }, ...screens.map((screen) => ({ key: rootKeyAndPaths(rootKey, screen.path), route: makeVariablesNavigationFriendly( rootKeyAndPaths(rootKey, screen.path) ), renderScene: () => ( ), trackCrumbTrail: true, screen, preloadId: screen.path, })), ]; } }) .flat(); return new StateNavigator(navigators, getHistoryManager(basePath)); }, [SuspenseContainer, basePath, navigationRoot, preloadRoot, screens]); const preloadLink = React.useCallback( (url: string) => { const { state, data, crumbs } = rootNavigator.parseLink(url); state?.preload?.(); if (state.screen) { preloadElement(state.screen); preloadScreen(state.screen, data); } crumbs.forEach((crumb) => { crumb.state?.preload?.(); if (crumb.state.screen) { preloadElement(crumb.state.screen); preloadScreen(crumb.state.screen, crumb.data); } }); }, [preloadElement, preloadScreen, rootNavigator] ); const openUrl = React.useCallback( (uri: string, change: boolean, fallback?: boolean) => { try { const path = getPathFromUrl(uri); const rootKey = getRootKeyFromPath(path)!; const root = navigationRoot[rootKey]; const rootType = root?.type; const isBottomTabs = rootType === 'bottomTabs'; const isNative = Platform.OS !== 'web'; if (isNative && isBottomTabs) { preloadRoot(rootKey); preloadLink(uri); rootNavigator.start(rootKey); } else { preloadLink(uri); rootNavigator.navigateLink(uri); } } catch (e) { console.log( `[react-native-ridge-navigation] can't convert deep link to the right stack: ${uri}`, e, { fallback, change, } ); if (!fallback && !change) { console.debug( '[react-native-ridge-navigation] there is no app started yet, lets go to the default url}', { defaultUrl: initialDefaultUrl } ); // setTimeout(() => { openUrl(initialDefaultUrl, false, true); // }, 1000); } } }, // eslint-disable-next-line react-hooks/exhaustive-deps [] ); const fluent = React.useCallback( (fluentParams: FluentParams, ...fluentScreens: FluentScreen[]) => { let root = navigationRoot[fluentParams.rootKey]!; const tab = fluentParams.tab || (root as RootChildBottomTabs)?.children?.[0]; let fluentNavigator = createHistorylessClone(rootNavigator) .fluent() .navigate( root.type === 'bottomTabs' ? getScreenKey(fluentParams.rootKey, tab) : fluentParams.rootKey ); fluentScreens.forEach((fluentScreen) => { fluentNavigator = fluentNavigator.navigate( root.type === 'bottomTabs' ? getScreenKey(fluentParams.rootKey, tab, fluentScreen.screen.path) : rootKeyAndPaths(fluentParams.rootKey, fluentScreen.screen.path), fluentScreen.params ); }); const url = fluentNavigator.url; if (process.env.NODE_ENV === 'development') { console.log( `[react-native-ridge-navigation] fluent navigation to ${url}` ); } setGoToUrl(url); }, [navigationRoot, rootNavigator, setGoToUrl] ); const [navigationReady, setNavigationReady] = React.useState(false); const firstTime = React.useRef(true); React.useEffect(() => { if (goToUrl) { if (firstTime.current) { openUrl(goToUrl, false); firstTime.current = false; setNavigationReady(true); } else { const timerId = setTimeout(() => { // Expo Linking also reports URLs written by this navigator; see // shouldReplayLinkingUrl for when such an event is stale. if ( !shouldReplayLinkingUrl({ isWeb: Platform.OS === 'web', eventUrl: goToUrl, currentHistoryUrl: Platform.OS === 'web' ? rootNavigator.historyManager.getCurrentUrl() : undefined, currentStateUrl: rootNavigator.stateContext.url, }) ) { return; } openUrl(goToUrl, true); }, 50); return () => { clearTimeout(timerId); }; } return undefined; } if (firstTime.current && initialDefaultUrl) { openUrl(initialDefaultUrl, false, true); firstTime.current = false; setNavigationReady(true); } return undefined; }, [goToUrl, initialDefaultUrl, openUrl, rootNavigator]); if (!navigationReady) { return null; } return ( {children && ( {children} )} theme.layout.backgroundColor} sharedElements={getSharedElementsForState} // unmountStyle={() => ''} renderScene={(state, data) => { return ( ); }} /> ); } function createHistorylessClone(navigator: StateNavigator) { const clone = new StateNavigator(navigator); clone.historyManager.disabled = true; clone.historyManager.stop(); return clone; } const OptimizedRenderScene = React.memo( ({ renderScene }: { renderScene: () => any }) => { return renderScene(); } );