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

useOpenPullRequest.ts

68 lines2.8 KB

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 { useProjects, 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 projects = useProjects();
17 const replace = options?.replace;
18 return useCallback(
19 async (url: string, context: PullRequestContext | null) => {
20 const params = nativePullRequestDestination(url, context, projects);
21 if (!params) return tryOpenExternalUrl(url, "pull-request");
22 if (Platform.OS === "android")
23 resetAndroidWorkspace(navigation, { name: "PullRequest", params });
24 else if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));
25 else navigation.navigate("PullRequest", params);
26 return true;
27 },
28 [navigation, projects, replace],
29 );
31​
32export function useOpenPullRequest(options?: {
33 readonly replace?: boolean;
34 readonly context?: PullRequestContext;
35}) {
36 const route = useRoute();
37 const routeContext = route.params as
38 | {
39 environmentId?: string | string[];
40 projectId?: string | string[];
41 threadId?: string | string[];
42 }
43 | undefined;
44 const first = (value: string | string[] | undefined) => {
45 const text = Array.isArray(value) ? value[0] : value;
46 return text?.trim() ? text : undefined;
47 };
48 const environmentId = options?.context?.environmentId ?? first(routeContext?.environmentId);
49 const threadId = first(routeContext?.threadId);
50 const thread = useThreadShell(
51 environmentId && threadId
52 ? { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId) }
53 : null,
54 );
55 const projectId =
56 options?.context?.projectId ?? first(routeContext?.projectId) ?? thread?.projectId;
57 const navigateToPullRequest = useNavigateToPullRequest({ replace: options?.replace });
58 return useCallback(
59 (url: string) =>
60 navigateToPullRequest(
61 url,
62 environmentId && projectId
63 ? { environmentId: String(environmentId), projectId: String(projectId) }
64 : null,
65 ),
66 [environmentId, projectId, navigateToPullRequest],
67 );