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

useOpenPullRequest.ts

146 lines6.3 KB

1import { useNavigation, useRoute, StackActions } from "@react-navigation/native";
2import { isStandaloneIssueLink, resolveIssueLinkTarget } from "@t3tools/client-runtime/issue-links";
3import {
4 nativePullRequestDestination,
5 pullRequestCandidateForIssueLink,
6} from "../lib/pullRequestNavigation";
7import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
8import { EnvironmentId, ThreadId } from "@t3tools/contracts";
9import { useProjects, useThreadShell } from "../state/entities";
10import { tryOpenWebLink } from "../lib/openExternalUrl";
11import { appAtomRegistry } from "../state/atom-registry";
12import { environmentServerConfigsAtom } from "../state/server";
13import { issueTrackerEnvironment } from "../state/issueTrackers";
14import { composerPullRequests } from "../state/pull-requests";
15import { useAtomQueryRunner } from "../state/use-atom-query-runner";
16import { withKnownPullRequestSummary } from "../state/use-thread-pr";
17​
18let linkNavigationId = 0;
19const nextLinkNavigationId = () => ++linkNavigationId;
20​
21// Only the newest press may navigate once its lookups return, so a slow older one cannot cover it.
22let latestPress = 0;
23function takeLatestPress(): () => boolean {
24 const press = ++latestPress;
25 return () => press === latestPress;
27​
28type PullRequestContext = { readonly environmentId: string; readonly projectId: string };
29​
30// Avoid useRoute so layouts without route context can open any thread's pull requests.
31export function useNavigateToPullRequest(options?: { readonly replace?: boolean }) {
32 const navigation = useNavigation();
33 const projects = useProjects();
34 const replace = options?.replace;
35 const readPreview = useAtomQueryRunner(composerPullRequests.preview, {
36 reportFailure: false,
37 reportDefect: false,
38 });
39 const readTrackerConnections = useAtomQueryRunner(issueTrackerEnvironment.connections, {
40 reportFailure: false,
41 reportDefect: false,
42 });
43 return async (url: string, context: PullRequestContext | null) => {
44 const isLatestPress = takeLatestPress();
45 // Read at press time so a config push does not hand every link a new handler.
46 const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
47 const destination = nativePullRequestDestination(url, context, projects, (environmentId) =>
48 serverConfigs.has(environmentId),
49 );
50 if (!destination) {
51 // An issue link from the same text opens the issue; anything else leaves for the browser.
52 const environmentId = context && EnvironmentId.make(context.environmentId);
53 const issuesEnabled =
54 environmentId !== null &&
55 serverConfigs.get(environmentId)?.environment.capabilities.issues === true;
56 // Only a standalone tracker's link needs the bindings, whose read probes the tracker.
57 const connections =
58 issuesEnabled && isStandaloneIssueLink(url)
59 ? await readTrackerConnections({ environmentId, input: {} })
60 : null;
61 if (!isLatestPress()) return true;
62 const issue =
63 issuesEnabled && context !== null
64 ? resolveIssueLinkTarget({
65 url,
66 projects: projects.filter((project) => project.environmentId === environmentId),
67 preferredProjectId: context.projectId,
68 trackers: connections?._tag === "Success" ? connections.value : undefined,
69 })
70 : null;
71 if (!issue || !environmentId) return tryOpenWebLink(url, "pull-request");
72 const candidate = pullRequestCandidateForIssueLink(url, issue.ref);
73 if (candidate) {
74 const preview = await readPreview({ environmentId, input: candidate.target });
75 if (!isLatestPress()) return true;
76 if (preview._tag === "Success") {
77 const params = withKnownPullRequestSummary({
78 ...candidate.target,
79 environmentId,
80 ...(candidate.navigationUrl
81 ? { navigationUrl: candidate.navigationUrl, navigationId: nextLinkNavigationId() }
82 : {}),
83 });
84 if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));
85 else navigation.dispatch(StackActions.push("PullRequest", params));
86 return true;
87 }
88 // A dropped connection says nothing about what the link names; the browser knows.
89 if (isAtomCommandInterrupted(preview)) return tryOpenWebLink(url, "pull-request");
90 }
91 const issueParams = {
92 environmentId,
93 projectId: issue.ref.projectId,
94 tracker: issue.ref.tracker,
95 ...(issue.ref.host === undefined ? {} : { host: issue.ref.host }),
96 scope: issue.ref.scope,
97 issueKey: issue.ref.key,
98 };
99 if (replace) navigation.dispatch(StackActions.replace("Issue", issueParams));
100 else navigation.dispatch(StackActions.push("Issue", issueParams));
101 return true;
102 }
103 const params = withKnownPullRequestSummary({
104 ...destination,
105 ...(destination.navigationUrl ? { navigationId: nextLinkNavigationId() } : {}),
106 });
107 if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));
108 else navigation.dispatch(StackActions.push("PullRequest", params));
109 return true;
110 };
112​
113export function useOpenPullRequest(options?: {
114 readonly replace?: boolean;
115 readonly context?: PullRequestContext;
116}) {
117 const route = useRoute();
118 const routeContext = route.params as
119 | {
120 environmentId?: string | string[];
121 projectId?: string | string[];
122 threadId?: string | string[];
123 }
124 | undefined;
125 const first = (value: string | string[] | undefined) => {
126 const text = Array.isArray(value) ? value[0] : value;
127 return text?.trim() ? text : undefined;
128 };
129 const environmentId = options?.context?.environmentId ?? first(routeContext?.environmentId);
130 const threadId = first(routeContext?.threadId);
131 const thread = useThreadShell(
132 environmentId && threadId
133 ? { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId) }
134 : null,
135 );
136 const projectId =
137 options?.context?.projectId ?? first(routeContext?.projectId) ?? thread?.projectId;
138 const navigateToPullRequest = useNavigateToPullRequest({ replace: options?.replace });
139 return (url: string) =>
140 navigateToPullRequest(
141 url,
142 environmentId && projectId
143 ? { environmentId: String(environmentId), projectId: String(projectId) }
144 : null,
145 );