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