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 params={params} changeRequest={detail.data}>
128 <KeyboardAvoidingView automaticOffset behavior="height" className="flex-1 bg-screen">
129 <NativeStackScreenOptions
130 options={{ title: "Discussion", unstable_headerSubtitle: `#${params.number}` }}
131 />
132 {Platform.OS === "android" ? (
133 <AndroidScreenHeader
134 title="Discussion"
135 subtitle={`#${params.number}`}
136 onBack={() => navigation.goBack()}
137 actions={
138 permissions.canResolve && thread
139 ? [
140 {
141 accessibilityLabel: resolveLabel,
142 icon: thread.isResolved ? "arrow.uturn.backward" : "checkmark",
143 disabled: busy || activity.isPending,
144 onPress: () => void toggleResolved(),
145 },
146 ]
147 : []
148 }
149 />
150 ) : null}
151 {permissions.canResolve && thread ? (
152 <Toolbar placement="right">
153 <Toolbar.Button
154 label={resolveLabel}
155 disabled={busy || activity.isPending}
156 onPress={() => void toggleResolved()}
157 />
158 </Toolbar>
159 ) : null}
160 <ScrollViewMarker style={{ flex: 1 }}>
161 <ScrollView
162 className="flex-1"
163 contentInsetAdjustmentBehavior="automatic"
164 keyboardShouldPersistTaps="handled"
165 contentContainerStyle={{
166 padding: 20,
167 paddingBottom: canReply ? composerHeight + bottomInset + 24 : 24,
168 }}
169 >
170 {activity.isPending && !thread ? <AppActivityIndicator /> : null}
171 {thread ? (
172 <View className="gap-2 pb-4">
173 <Text selectable className="font-mono text-xs text-foreground-muted">
174 {thread.path}
175 {thread.line ? `:${thread.line}` : ""}
176 </Text>
177 <Text className="text-xs text-foreground-muted">
178 {thread.isResolved ? "Resolved" : "Unresolved"}
179 {thread.isOutdated ? " · Outdated" : ""}
180 </Text>
181 <Button
182 label="View file diff"
183 onPress={() =>
184 navigation.navigate("PullRequestFile", { ...params, path: thread.path })
185 }
186 />
187 </View>
188 ) : !activity.isPending ? (
189 <Text>This discussion is no longer available.</Text>
190 ) : null}
191 {comments.map((comment) => (
192 <View key={comment.id} className="gap-3 border-b border-border-subtle py-4">
193 <View className="flex-row items-center gap-2">
194 <PullRequestAvatar actor={comment.author} size={28} />
195 <Text className="min-w-0 flex-1 text-sm font-t3-medium">
196 {comment.author?.login ?? "Unknown author"}
197 </Text>
198 <Text className="text-2xs text-foreground-muted">
199 {relativeTime(comment.createdAt)}
200 </Text>
201 </View>
202 <PullRequestMarkdown markdown={comment.body} />
203 </View>
204 ))}
205 {nextCursor ? (
206 <Button
207 label={busy ? "Loading…" : "Load more replies"}
208 disabled={busy}
209 onPress={() => void more()}
210 />
211 ) : null}
212 {error || activity.error ? (
213 <Text selectable className="py-4 text-sm text-danger-foreground">
214 {error ?? activity.error}
215 </Text>
216 ) : null}
217 {notice ? <Text className="py-4 text-sm text-foreground-muted">{notice}</Text> : null}
218 </ScrollView>
219 </ScrollViewMarker>
220 {canReply ? (
221 <View className="absolute inset-x-4 bottom-0" style={{ paddingBottom: bottomInset }}>
222 <GlassSurface
223 chrome="none"
224 onLayout={(event) => setComposerHeight(event.nativeEvent.layout.height)}
225 className="flex-row items-end gap-1 p-1"
226 >
227 <TextInput
228 accessibilityLabel="Discussion reply"
229 multiline
230 maxLength={65536}
231 placeholder="Reply…"
232 placeholderTextColorClassName="accent-foreground-muted"
233 value={body}
234 onChangeText={setBody}
235 editable={!busy}
236 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"
237 />
238 <View>
239 <Button
240 label={busy ? "Posting…" : "Reply"}
241 tone="contrast"
242 disabled={busy || !body.trim()}
243 onPress={() => void post()}
244 />
245 </View>
246 </GlassSurface>
247 </View>
248 ) : null}
249 </KeyboardAvoidingView>
250 </PullRequestMarkdownRepository>
251 );
252}