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

PullRequestDiscussionScreen.tsx

317 lines13.4 KB

1import {
2 parsePullRequestAnchor,
3 pullRequestAnchorMatchesUrl,
4 resolvePullRequestReviewAnchor,
5} from "@t3tools/shared/pullRequestAnchor";
6import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
7import { useAtomRefresh } from "@effect/atom-react";
8import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native";
9import {
10 type AtomCommandResult,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13import { AsyncResult } from "effect/reactivity";
14import type { PullRequestThreadComment } from "@t3tools/contracts";
15import { useRef, useState } from "react";
16import { ScrollView, View, type ScrollViewInstance } from "react-native";
17import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
18import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeScrollViewMarker";
19import { useSafeAreaInsets } from "react-native-safe-area-context";
20import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
21import { AppBar } from "../../components/ui/AppBar";
22import { Button } from "../../components/ui/Button";
23import { GlassSurface } from "../../components/ui/GlassSurface";
24import { relativeTime } from "../../lib/time";
25import { composerPullRequests } from "../../state/pull-requests";
26import { useAtomCommand } from "../../state/use-atom-command";
27import { useEnvironmentQuery } from "../../state/query";
28import { PullRequestMarkdown, PullRequestMarkdownRepository } from "./PullRequestMarkdown";
29import { PullRequestAvatar } from "./PullRequestPresentation";
30import { PullRequestCommentFooter } from "./PullRequestReactions";
31import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
32import { usePullRequestPermissions } from "./usePullRequestPermissions";
33import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
34import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";
35import { usePullRequestCompletions } from "./usePullRequestCompletions";
36​
37export function PullRequestDiscussionScreen({
38 route,
39}: StaticScreenProps<PullRequestParams & { readonly discussionId: string }>) {
40 return (
41 <Discussion
42 key={`${pullRequestReviewKey(route.params)}:${route.params.discussionId}`}
43 params={route.params}
44 />
45 );
47​
48function Discussion({ params }: { params: PullRequestParams & { readonly discussionId: string } }) {
49 const target = pullRequestTarget(params);
50 const navigation = useNavigation();
51 const insets = useSafeAreaInsets();
52 const keyboardVisible = useKeyboardState((state) => state.isVisible);
53 const bottomInset = keyboardVisible ? 8 : Math.max(insets.bottom, 12);
54 const activity = useEnvironmentQuery(composerPullRequests.activity(target));
55 const detail = useEnvironmentQuery(composerPullRequests.detail(target));
56 const permissions = usePullRequestPermissions(params, detail.data);
57 const refresh = useAtomRefresh(composerPullRequests.activity(target));
58 const reply = useAtomCommand(composerPullRequests.replyToThread, { reportFailure: false });
59 const resolve = useAtomCommand(composerPullRequests.setThreadResolution, {
60 reportFailure: false,
61 });
62 const loadMore = useAtomCommand(composerPullRequests.threadComments, { reportFailure: false });
63 const thread = activity.data?.reviewThreads.find((thread) => thread.id === params.discussionId);
64 const [body, setBody] = useState("");
65 const completions = usePullRequestCompletions({
66 environmentId: params.environmentId,
67 projectId: params.projectId,
68 value: body,
69 onChangeValue: setBody,
70 support: detail.data?.capabilities ?? null,
71 });
72 const [extra, setExtra] = useState<readonly PullRequestThreadComment[]>([]);
73 const [cursor, setCursor] = useState<string | null | undefined>();
74 const [busy, setBusy] = useState(false);
75 const pending = useRef(false);
76 const [error, setError] = useState<string | null>(null);
77 const [notice, setNotice] = useState<string | null>(null);
78 const [composerHeight, setComposerHeight] = useState(64);
79 // Replies from "Load more" live only here, outside the activity an edit refreshes. After one
80 // is edited, drop the loaded pages so the next load reads the new body instead of the old one.
81 const extraEdited = useRef(false);
82 useFocusEffect(() => {
83 if (!extraEdited.current) return;
84 extraEdited.current = false;
85 setExtra([]);
86 setCursor(undefined);
87 });
88 const operation = async (run: () => Promise<AtomCommandResult<unknown, unknown> | undefined>) => {
89 if (pending.current) return;
90 pending.current = true;
91 setBusy(true);
92 setError(null);
93 setNotice(null);
94 const result = await run();
95 pending.current = false;
96 setBusy(false);
97 if (result && AsyncResult.isFailure(result)) {
98 const cause = squashAtomCommandFailure(result);
99 setError(
100 cause instanceof Error ? cause.message : "The provider could not complete this action.",
101 );
102 }
103 };
104 const post = () =>
105 operation(async () => {
106 if (!permissions.canReply || !body.trim() || !thread) return undefined;
107 const submitted = body;
108 const response = await reply({
109 ...target,
110 input: { ...target.input, threadId: thread.id, body: submitted },
111 });
112 if (AsyncResult.isFailure(response)) return response;
113 setBody((current) => (current === submitted ? "" : current));
114 setNotice("Reply posted.");
115 refresh();
116 return response;
117 });
118 const toggleResolved = () =>
119 operation(async () => {
120 if (!thread || !permissions.canResolve) return undefined;
121 const response = await resolve({
122 ...target,
123 input: { ...target.input, threadId: thread.id, resolved: !thread.isResolved },
124 });
125 if (AsyncResult.isSuccess(response)) refresh();
126 return response;
127 });
128 const nextCursor = cursor === undefined ? thread?.nextCommentsCursor : cursor;
129 const more = () =>
130 operation(async () => {
131 if (!thread || !nextCursor) return undefined;
132 const response = await loadMore({
133 ...target,
134 input: { ...target.input, threadId: thread.id, cursor: nextCursor },
135 });
136 if (AsyncResult.isFailure(response)) return response;
137 setExtra((comments) => [...comments, ...response.value.comments]);
138 setCursor(response.value.nextCursor);
139 return response;
140 });
141 const comments = [
142 ...new Map(
143 [...extra, ...(thread?.comments ?? [])].map((comment) => [comment.id, comment]),
144 ).values(),
145 ].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
146 const scrollRef = useRef<ScrollViewInstance>(null);
147 const pendingTop = useRef<number | null>(null);
148 const positionedComment = useRef<string | null>(null);
149 const location = parsePullRequestAnchor(params.navigationUrl);
150 const anchor =
151 location?.kind === "timeline"
152 ? resolvePullRequestReviewAnchor(location.anchor, [], [{ comments }])
153 : null;
154 const canReply = permissions.canReply && Boolean(thread);
155 const resolveLabel = thread?.isResolved ? "Unresolve" : "Resolve";
156 return (
157 <PullRequestMarkdownRepository params={params} changeRequest={detail.data}>
158 <KeyboardAvoidingView
159 automaticOffset
160 behavior="height"
161 className="flex-1 bg-screen"
162 // Any touch, such as replying or loading replies, ends the wait to reposition the link.
163 onTouchStart={() => {
164 pendingTop.current = null;
165 }}
166 >
167 <AppBar
168 title="Discussion"
169 subtitle={`#${params.number}`}
170 onBack={() => navigation.goBack()}
171 actions={
172 permissions.canResolve && thread
173 ? [
174 {
175 accessibilityLabel: resolveLabel,
176 icon: thread.isResolved ? "arrow.uturn.backward" : "checkmark",
177 disabled: busy || activity.isPending,
178 onPress: () => void toggleResolved(),
179 },
180 ]
181 : []
182 }
183 />
184 <ScrollViewMarker style={{ flex: 1 }}>
185 <ScrollView
186 ref={scrollRef}
187 onContentSizeChange={() => {
188 if (pendingTop.current === null) return;
189 scrollRef.current?.scrollTo({ y: pendingTop.current, animated: false });
190 pendingTop.current = null;
191 }}
192 className="flex-1"
193 contentInsetAdjustmentBehavior="automatic"
194 keyboardShouldPersistTaps="handled"
195 contentContainerStyle={{
196 padding: 20,
197 paddingBottom: canReply ? composerHeight + bottomInset + 24 : 24,
198 }}
199 >
200 {activity.isPending && !thread ? <AppActivityIndicator /> : null}
201 {thread ? (
202 <View className="gap-2 pb-4">
203 <Text selectable className="font-mono text-xs text-foreground-muted">
204 {thread.path}
205 {thread.line ? `:${thread.line}` : ""}
206 </Text>
207 <Text className="text-xs text-foreground-muted">
208 {thread.isResolved ? "Resolved" : "Unresolved"}
209 {thread.isOutdated ? " · Outdated" : ""}
210 </Text>
211 <Button
212 label="View file diff"
213 onPress={() =>
214 navigation.navigate("PullRequestFile", { ...params, path: thread.path })
215 }
216 />
217 </View>
218 ) : !activity.isPending ? (
219 <Text>This discussion is no longer available.</Text>
220 ) : null}
221 {comments.map((comment) => (
222 <View
223 key={comment.id}
224 onLayout={(event) => {
225 if (
226 anchor === null ||
227 !pullRequestAnchorMatchesUrl(anchor, comment.url) ||
228 positionedComment.current === comment.id
229 )
230 return;
231 positionedComment.current = comment.id;
232 pendingTop.current = event.nativeEvent.layout.y;
233 scrollRef.current?.scrollTo({ y: pendingTop.current, animated: false });
234 }}
235 className={
236 anchor !== null && pullRequestAnchorMatchesUrl(anchor, comment.url)
237 ? "-mx-3 gap-3 rounded-2xl border border-primary bg-primary/10 px-3 py-4"
238 : "gap-3 border-b border-border-subtle py-4"
239 }
240 >
241 <View className="flex-row items-center gap-2">
242 <PullRequestAvatar actor={comment.author} size={28} />
243 <Text className="min-w-0 flex-1 text-sm font-t3-medium">
244 {comment.author?.login ?? "Unknown author"}
245 </Text>
246 <Text className="text-2xs text-foreground-muted">
247 {relativeTime(comment.createdAt)}
248 </Text>
249 </View>
250 <PullRequestMarkdown markdown={comment.body} />
251 <PullRequestCommentFooter
252 params={params}
253 comment={{ ...comment, kind: "review-comment" }}
254 permissions={permissions}
255 onChanged={refresh}
256 onEdit={() => {
257 if (extra.some((loaded) => loaded.id === comment.id))
258 extraEdited.current = true;
259 }}
260 />
261 </View>
262 ))}
263 {nextCursor ? (
264 <Button
265 label={busy ? "Loading…" : "Load more replies"}
266 disabled={busy}
267 onPress={() => void more()}
268 />
269 ) : null}
270 {error || activity.error ? (
271 <Text selectable className="py-4 text-sm text-danger-foreground">
272 {error ?? activity.error}
273 </Text>
274 ) : null}
275 {notice ? <Text className="py-4 text-sm text-foreground-muted">{notice}</Text> : null}
276 </ScrollView>
277 </ScrollViewMarker>
278 {canReply ? (
279 <View
280 className="absolute inset-x-4 bottom-0 gap-2"
281 style={{ paddingBottom: bottomInset }}
282 >
283 <PullRequestCompletionSuggestions completions={completions} />
284 <GlassSurface
285 chrome="none"
286 onLayout={(event) => setComposerHeight(event.nativeEvent.layout.height)}
287 className="flex-row items-end gap-1 p-1"
288 >
289 <TextInput
290 accessibilityLabel="Discussion reply"
291 selection={completions.selection}
292 onSelectionChange={completions.onSelectionChange}
293 onBlur={completions.onBlur}
294 multiline
295 maxLength={65536}
296 placeholder="Reply…"
297 placeholderTextColorClassName="accent-foreground-muted"
298 value={body}
299 onChangeText={setBody}
300 editable={!busy}
301 className="max-h-36 min-h-12 min-w-0 flex-1 rounded-[24px] border-0 bg-transparent px-4 py-3 text-base text-foreground"
302 />
303 <View>
304 <Button
305 label={busy ? "Posting…" : "Reply"}
306 tone="contrast"
307 disabled={busy || !body.trim()}
308 onPress={() => void post()}
309 />
310 </View>
311 </GlassSurface>
312 </View>
313 ) : null}
314 </KeyboardAvoidingView>
315 </PullRequestMarkdownRepository>
316 );