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

PullRequestDiscussionScreen.tsx

272 lines11.7 KB

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