Open History to see the last commit
1import type { NavigationState } from "@react-navigation/native";
2import {
3 createContext,
4 use,
5 useCallback,
6 useLayoutEffect,
7 useMemo,
8 useRef,
9 type ReactNode,
10} from "react";
11import { Platform } from "react-native";
12import { androidWorkspaceSettingsOpen } from "./android-workspace-tabs";
13import { WorkspaceTabsProvider } from "./WorkspaceTabsContext";
14
15interface AndroidWorkspaceRoot {
16 /**
17 * The rail's `useNavigation()` dispatches to the focused navigator, which may be nested Settings.
18 * Use the root stack's state and key so a tab press resets the root.
19 */
20 readonly key: string;
21 readonly getState: () => NavigationState;
22 /** Settings is derived from navigation rather than kept in the tab reducer. */
23 readonly settingsOpen: boolean;
24}
25
26const AndroidWorkspaceRootContext = createContext<AndroidWorkspaceRoot | null>(null);
27
28export function useAndroidWorkspaceRoot() {
29 return use(AndroidWorkspaceRootContext);
30}
31
32/** Android keeps one tab controller above the root navigator and split sidebar. */
33export function AndroidWorkspaceTabsProvider(props: {
34 readonly state: NavigationState;
35 readonly children: ReactNode;
36}) {
37 const stateRef = useRef(props.state);
38 useLayoutEffect(() => {
39 stateRef.current = props.state;
40 }, [props.state]);
41 const getState = useCallback(() => stateRef.current, []);
42 const key = props.state.key;
43 const settingsOpen = Platform.OS === "android" && androidWorkspaceSettingsOpen(props.state);
44 const root = useMemo(() => ({ key, getState, settingsOpen }), [key, getState, settingsOpen]);
45 return Platform.OS === "android" ? (
46 <WorkspaceTabsProvider>
47 <AndroidWorkspaceRootContext value={root}>{props.children}</AndroidWorkspaceRootContext>
48 </WorkspaceTabsProvider>
49 ) : (
50 props.children
51 );
52}