Open History to see the last commit
1import { useNavigation, useRoute, StackActions } from "@react-navigation/native";
2import { nativePullRequestDestination } from "../lib/pullRequestNavigation";
3import { useCallback } from "react";
4import { Platform } from "react-native";
5import { resetAndroidWorkspace } from "../lib/android-workspace-navigation";
6import { EnvironmentId, ThreadId } from "@t3tools/contracts";
7import { useThreadShell } from "../state/entities";
8import { tryOpenExternalUrl } from "../lib/openExternalUrl";
9
10type PullRequestContext = { readonly environmentId: string; readonly projectId: string };
11
12// Route-free so navigator layouts such as the workspace sidebar, which have no
13// route context for useRoute, can open pull requests for any thread.
14export function useNavigateToPullRequest(options?: { readonly replace?: boolean }) {
15 const navigation = useNavigation();
16 const replace = options?.replace;
17 return useCallback(
18 async (url: string, context: PullRequestContext | null) => {
19 const params = nativePullRequestDestination(url, context);
20 if (!params) return tryOpenExternalUrl(url, "pull-request");
21 if (Platform.OS === "android")
22 resetAndroidWorkspace(navigation, { name: "PullRequest", params });
23 else if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));
24 else navigation.navigate("PullRequest", params);
25 return true;
26 },
27 [navigation, replace],
28 );
29}
30
31export function useOpenPullRequest(options?: {
32 readonly replace?: boolean;
33 readonly context?: PullRequestContext;
34}) {
35 const route = useRoute();
36 const routeContext = route.params as
37 | {
38 environmentId?: string | string[];
39 projectId?: string | string[];
40 threadId?: string | string[];
41 }
42 | undefined;
43 const first = (value: string | string[] | undefined) => {
44 const text = Array.isArray(value) ? value[0] : value;
45 return text?.trim() ? text : undefined;
46 };
47 const environmentId = options?.context?.environmentId ?? first(routeContext?.environmentId);
48 const threadId = first(routeContext?.threadId);
49 const thread = useThreadShell(
50 environmentId && threadId
51 ? { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId) }
52 : null,
53 );
54 const projectId =
55 options?.context?.projectId ?? first(routeContext?.projectId) ?? thread?.projectId;
56 const navigateToPullRequest = useNavigateToPullRequest({ replace: options?.replace });
57 return useCallback(
58 (url: string) =>
59 navigateToPullRequest(
60 url,
61 environmentId && projectId
62 ? { environmentId: String(environmentId), projectId: String(projectId) }
63 : null,
64 ),
65 [environmentId, projectId, navigateToPullRequest],
66 );
67}