Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AndroidWorkspaceTabsProvider.tsx

55 lines2.0 KB

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 root stack's key and state. The rail renders in the root navigator's layout, where
18 * `useNavigation()` resolves to the container ref: its dispatch goes to the focused
19 * navigator and hands that navigator's state to a callback. A tab press from inside nested
20 * Settings must reset the root stack, so the rail reads the root state here and targets
21 * the root key.
22 */
23 readonly key: string;
24 readonly getState: () => NavigationState;
25 /** Settings is derived from navigation rather than kept in the tab reducer. */
26 readonly settingsOpen: boolean;
28​
29const AndroidWorkspaceRootContext = createContext<AndroidWorkspaceRoot | null>(null);
30​
31export function useAndroidWorkspaceRoot() {
32 return use(AndroidWorkspaceRootContext);
34​
35/** Android keeps one tab controller above the root navigator and split sidebar. */
36export function AndroidWorkspaceTabsProvider(props: {
37 readonly state: NavigationState;
38 readonly children: ReactNode;
39}) {
40 const stateRef = useRef(props.state);
41 useLayoutEffect(() => {
42 stateRef.current = props.state;
43 }, [props.state]);
44 const getState = useCallback(() => stateRef.current, []);
45 const key = props.state.key;
46 const settingsOpen = Platform.OS === "android" && androidWorkspaceSettingsOpen(props.state);
47 const root = useMemo(() => ({ key, getState, settingsOpen }), [key, getState, settingsOpen]);
48 return Platform.OS === "android" ? (
49 <WorkspaceTabsProvider>
50 <AndroidWorkspaceRootContext value={root}>{props.children}</AndroidWorkspaceRootContext>
51 </WorkspaceTabsProvider>
52 ) : (
53 props.children
54 );