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

home-thread-navigation.ts

71 lines2.3 KB

1import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2import {
3 CommonActions,
4 StackActions,
5 useNavigation,
6 type NavigationState,
7} from "@react-navigation/native";
8import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
9import { useCallback, useEffect, useRef } from "react";
10​
11type ThreadSelection = Pick<EnvironmentThreadShell, "environmentId" | "id">;
12​
13export function createHomeThreadNavigationAction(input: {
14 readonly state: Pick<NavigationState, "index" | "routes">;
15 readonly dismissingRouteKey: string | null;
16 readonly thread: ThreadSelection;
17}) {
18 const currentRoute = input.state.routes[input.state.index];
19 const params = {
20 environmentId: input.thread.environmentId,
21 threadId: input.thread.id,
22 };
23​
24 // Native swipe-back pops the outgoing route after its animation. Reusing
25 // that key would also discard this selection when the dismissal arrives.
26 if (input.dismissingRouteKey !== null && currentRoute?.key === input.dismissingRouteKey) {
27 return StackActions.push("Thread", params);
28 }
29​
30 return CommonActions.navigate("Thread", params);
32​
33export function useHomeThreadSelection() {
34 const navigation =
35 useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList, "Home">>();
36 const dismissingRouteKey = useRef<string | null>(null);
37​
38 useEffect(() => {
39 const clear = () => {
40 dismissingRouteKey.current = null;
41 };
42 // This listener belongs to Home, so swipe-back is its opening transition.
43 // Thread's closing event is targeted at the outgoing Thread route.
44 const removeTransitionStart = navigation.addListener("transitionStart", ({ data }) => {
45 const state = navigation.getState();
46 const currentRoute = state.routes[state.index];
47 dismissingRouteKey.current =
48 !data.closing && currentRoute?.name === "Thread" ? currentRoute.key : null;
49 });
50 const removeFocus = navigation.addListener("focus", clear);
51​
52 return () => {
53 clear();
54 removeTransitionStart();
55 removeFocus();
56 };
57 }, [navigation]);
58​
59 return useCallback(
60 (thread: ThreadSelection) => {
61 navigation.dispatch((state) =>
62 createHomeThreadNavigationAction({
63 state,
64 dismissingRouteKey: dismissingRouteKey.current,
65 thread,
66 }),
67 );
68 },
69 [navigation],
70 );