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

useOpenPullRequest.ts

59 lines2.3 KB

1import { useNavigation, useRoute, StackActions } from "@react-navigation/native";
2import { nativePullRequestDestination } from "../lib/pullRequestNavigation";
3import { useCallback } from "react";
4import { Platform } from "react-native";
5import { CommonActions } from "@react-navigation/native";
6import { androidWorkspaceNavigationState } from "../lib/android-workspace-navigation";
7import { EnvironmentId, ThreadId } from "@t3tools/contracts";
8import { useThreadShell } from "../state/entities";
9import { tryOpenExternalUrl } from "../lib/openExternalUrl";
10​
11export function useOpenPullRequest(options?: {
12 readonly replace?: boolean;
13 readonly context?: { readonly environmentId: string; readonly projectId: string };
14}) {
15 const navigation = useNavigation();
16 const route = useRoute();
17 const routeContext = route.params as
18 | {
19 environmentId?: string | string[];
20 projectId?: string | string[];
21 threadId?: string | string[];
22 }
23 | undefined;
24 const first = (value: string | string[] | undefined) => {
25 const text = Array.isArray(value) ? value[0] : value;
26 return text?.trim() ? text : undefined;
27 };
28 const environmentId = options?.context?.environmentId ?? first(routeContext?.environmentId);
29 const threadId = first(routeContext?.threadId);
30 const thread = useThreadShell(
31 environmentId && threadId
32 ? { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId) }
33 : null,
34 );
35 const projectId =
36 options?.context?.projectId ?? first(routeContext?.projectId) ?? thread?.projectId;
37 const replace = options?.replace;
38 return useCallback(
39 async (url: string) => {
40 const params = nativePullRequestDestination(
41 url,
42 environmentId && projectId
43 ? { environmentId: String(environmentId), projectId: String(projectId) }
44 : null,
45 );
46 if (!params) return tryOpenExternalUrl(url, "pull-request");
47 if (Platform.OS === "android")
48 navigation.dispatch((state) =>
49 CommonActions.reset(
50 androidWorkspaceNavigationState(state, { name: "PullRequest", params }),
51 ),
52 );
53 else if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));
54 else navigation.navigate("PullRequest", params);
55 return true;
56 },
57 [environmentId, projectId, navigation, replace],
58 );