Open History to see the last commit
1import { Toolbar } from "../../components/ui/Toolbar";
2import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3import { useAtomRefresh } from "@effect/atom-react";
4import { 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 { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
28import { usePullRequestPermissions } from "./usePullRequestPermissions";
29import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
30
31export function PullRequestDiscussionScreen({
32 route,
33}: StaticScreenProps<PullRequestParams & { readonly discussionId: string }>) {
34 return (
35 <Discussion
36 key={`${pullRequestReviewKey(route.params)}:${route.params.discussionId}`}
37 params={route.params}
38 />
39 );
40}
41
42function Discussion({ params }: { params: PullRequestParams & { readonly discussionId: string } }) {
43 const target = pullRequestTarget(params);
44 const navigation = useNavigation();
45 const insets = useSafeAreaInsets();
46 const keyboardVisible = useKeyboardState((state) => state.isVisible);
47 const bottomInset = keyboardVisible ? 8 : Math.max(insets.bottom, 12);
48 const activity = useEnvironmentQuery(composerPullRequests.activity(target));
49 const detail = useEnvironmentQuery(composerPullRequests.detail(target));
50 const permissions = usePullRequestPermissions(params, detail.data);
51 const refresh = useAtomRefresh(composerPullRequests.activity(target));
52 const reply = useAtomCommand(composerPullRequests.replyToThread, { reportFailure: false });
53 const resolve = useAtomCommand(composerPullRequests.setThreadResolution, {
54 reportFailure: false,
55 });
56 const loadMore = useAtomCommand(composerPullRequests.threadComments, { reportFailure: false });
57 const thread = activity.data?.reviewThreads.find((thread) => thread.id === params.discussionId);
58 const [body, setBody] = useState("");
59 const [extra, setExtra] = useState<readonly PullRequestThreadComment[]>([]);
60 const [cursor, setCursor] = useState<string | null | undefined>();
61 const [busy, setBusy] = useState(false);
62 const pending = useRef(false);
63 const [error, setError] = useState<string | null>(null);
64 const [notice, setNotice] = useState<string | null>(null);
65 const [composerHeight, setComposerHeight] = useState(64);
66 const operation = async (run: () => Promise<AtomCommandResult<unknown, unknown> | undefined>) => {
67 if (pending.current) return;
68 pending.current = true;
69 setBusy(true);
70 setError(null);
71 setNotice(null);
72 const result = await run();
73 pending.current = false;
74 setBusy(false);
75 if (result && AsyncResult.isFailure(result)) {
76 const cause = squashAtomCommandFailure(result);
77 setError(
78 cause instanceof Error ? cause.message : "The provider could not complete this action.",
79 );
80 }
81 };
82 const post = () =>
83 operation(async () => {
84 if (!permissions.canReply || !body.trim() || !thread) return undefined;
85 const submitted = body;
86 const response = await reply({
87 ...target,
88 input: { ...target.input, threadId: thread.id, body: submitted },
89 });
90 if (AsyncResult.isFailure(response)) return response;
91 setBody((current) => (current === submitted ? "" : current));
92 setNotice("Reply posted.");
93 refresh();
94 return response;
95 });
96 const toggleResolved = () =>
97 operation(async () => {
98 if (!thread || !permissions.canResolve) return undefined;
99 const response = await resolve({
100 ...target,
101 input: { ...target.input, threadId: thread.id, resolved: !thread.isResolved },
102 });
103 if (AsyncResult.isSuccess(response)) refresh();
104 return response;
105 });
106 const nextCursor = cursor === undefined ? thread?.nextCommentsCursor : cursor;
107 const more = () =>
108 operation(async () => {
109 if (!thread || !nextCursor) return undefined;
110 const response = await loadMore({
111 ...target,
112 input: { ...target.input, threadId: thread.id, cursor: nextCursor },
113 });
114 if (AsyncResult.isFailure(response)) return response;
115 setExtra((comments) => [...comments, ...response.value.comments]);
116 setCursor(response.value.nextCursor);
117 return response;
118 });
119 const comments = [
120 ...new Map(
121 [...extra, ...(thread?.comments ?? [])].map((comment) => [comment.id, comment]),
122 ).values(),
123 ].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
124 const canReply = permissions.canReply && Boolean(thread);
125 const resolveLabel = thread?.isResolved ? "Unresolve" : "Resolve";
126 return (
127 <PullRequestMarkdownRepository
128 params={params}
129 value={detail.data?.provider === "github" ? detail.data.url : null}
130 >
131 <KeyboardAvoidingView automaticOffset behavior="height" className="flex-1 bg-screen">
132 <NativeStackScreenOptions
133 options={{ title: "Discussion", unstable_headerSubtitle: `#${params.number}` }}
134 />
135 {Platform.OS === "android" ? (
136 <AndroidScreenHeader
137 title="Discussion"
138 subtitle={`#${params.number}`}
139 onBack={() => navigation.goBack()}
140 actions={
141 permissions.canResolve && thread
142 ? [
143 {
144 accessibilityLabel: resolveLabel,
145 icon: thread.isResolved ? "arrow.uturn.backward" : "checkmark",
146 disabled: busy || activity.isPending,
147 onPress: () => void toggleResolved(),
148 },
149 ]
150 : []
151 }
152 />
153 ) : null}
154 {permissions.canResolve && thread ? (
155 <Toolbar placement="right">
156 <Toolbar.Button
157 label={resolveLabel}
158 disabled={busy || activity.isPending}
159 onPress={() => void toggleResolved()}
160 />
161 </Toolbar>
162 ) : null}
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 </View>
207 ))}
208 {nextCursor ? (
209 <Button
210 label={busy ? "Loading…" : "Load more replies"}
211 disabled={busy}
212 onPress={() => void more()}
213 />
214 ) : null}
215 {error || activity.error ? (
216 <Text selectable className="py-4 text-sm text-danger-foreground">
217 {error ?? activity.error}
218 </Text>
219 ) : null}
220 {notice ? <Text className="py-4 text-sm text-foreground-muted">{notice}</Text> : null}
221 </ScrollView>
222 </ScrollViewMarker>
223 {canReply ? (
224 <View className="absolute inset-x-4 bottom-0" style={{ paddingBottom: bottomInset }}>
225 <GlassSurface
226 chrome="none"
227 onLayout={(event) => setComposerHeight(event.nativeEvent.layout.height)}
228 className="flex-row items-end gap-1 p-1"
229 >
230 <TextInput
231 accessibilityLabel="Discussion reply"
232 multiline
233 maxLength={65536}
234 placeholder="Reply…"
235 placeholderTextColorClassName="accent-foreground-muted"
236 value={body}
237 onChangeText={setBody}
238 editable={!busy}
239 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"
240 />
241 <View>
242 <Button
243 label={busy ? "Posting…" : "Reply"}
244 tone="contrast"
245 disabled={busy || !body.trim()}
246 onPress={() => void post()}
247 />
248 </View>
249 </GlassSurface>
250 </View>
251 ) : null}
252 </KeyboardAvoidingView>
253 </PullRequestMarkdownRepository>
254 );
255}