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

PullRequestDiscussionScreen.tsx

272 lines11.6 KB

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