Open History to see the last commit
1import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
2import { TextInputWrapper } from "expo-paste-input";
3import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4import { useCallback, useEffect, useMemo, useState } from "react";
5import {
6 Platform,
7 Pressable,
8 ScrollView,
9 View,
10 useColorScheme,
11 useWindowDimensions,
12} from "react-native";
13import { KeyboardAvoidingView, KeyboardStickyView } from "react-native-keyboard-controller";
14import { useSafeAreaInsets } from "react-native-safe-area-context";
15import ImageViewing from "react-native-image-viewing";
16
17import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
18import { SymbolView } from "../../components/AppSymbol";
19import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
20import { ControlPill } from "../../components/ControlPill";
21import { cn } from "../../lib/cn";
22import type { DraftComposerImageAttachment } from "../../lib/composerImages";
23import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
24import { useThemeColor } from "../../lib/useThemeColor";
25import { useNativePaste } from "../../lib/useNativePaste";
26import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
27import { appendReviewCommentToDraft } from "../../state/use-thread-composer-state";
28import {
29 clearReviewCommentTarget,
30 formatReviewCommentContext,
31 getReviewUnifiedLineNumber,
32 getSelectedReviewCommentLines,
33 useReviewCommentTarget,
34} from "./reviewCommentSelection";
35import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
36import { changeTone, DiffTokenText, ReviewChangeBar } from "./reviewDiffRendering";
37import {
38 highlightReviewSelectedLines,
39 type ReviewDiffTheme,
40 type ReviewHighlightedToken,
41} from "./shikiReviewHighlighter";
42
43const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
44
45type ReviewCommentComposerSheetProps = StaticScreenProps<{
46 readonly environmentId: EnvironmentId;
47 readonly threadId: ThreadId;
48}>;
49
50export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProps) {
51 const isAndroid = Platform.OS === "android";
52 const navigation = useNavigation();
53 const insets = useSafeAreaInsets();
54 const { width } = useWindowDimensions();
55 const colorScheme = useColorScheme();
56 const iconTint = String(useThemeColor("--color-icon"));
57 const target = useReviewCommentTarget();
58 const { codeSurface } = useAppearanceCodeSurface();
59 const { environmentId, threadId } = props.route.params;
60 const [commentText, setCommentText] = useState("");
61 const [highlightedLinesById, setHighlightedLinesById] = useState<
62 Record<string, ReadonlyArray<ReviewHighlightedToken>>
63 >({});
64 const [attachments, setAttachments] = useState<ReadonlyArray<DraftComposerImageAttachment>>([]);
65 const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
66
67 const selectedLines = useMemo(
68 () => (target ? getSelectedReviewCommentLines(target) : []),
69 [target],
70 );
71 const firstLine = selectedLines[0] ?? null;
72 const lastLine = selectedLines[selectedLines.length - 1] ?? null;
73 const firstNumber = firstLine ? getReviewUnifiedLineNumber(firstLine) : null;
74 const lastNumber = lastLine ? getReviewUnifiedLineNumber(lastLine) : null;
75 const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;
76 const canSubmit =
77 commentText.trim().length > 0 && target !== null && !!environmentId && !!threadId;
78 const selectionLabel =
79 selectedLines.length === 1
80 ? firstNumber !== null
81 ? `Line ${firstNumber}`
82 : "File comment"
83 : firstNumber !== null && lastNumber !== null
84 ? `Lines ${firstNumber}-${lastNumber}`
85 : `${selectedLines.length} lines selected`;
86 const previewHeight = Math.max(
87 Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * codeSurface.rowHeight,
88 codeSurface.rowHeight,
89 );
90 const previewViewportWidth = Math.max(width - 40, 280);
91 const dismissComposer = useCallback(() => {
92 clearReviewCommentTarget();
93 navigation.goBack();
94 }, [navigation]);
95 const handleNativePaste = useNativePaste((uris) => {
96 void (async () => {
97 try {
98 const images = await convertPastedImagesToAttachments({
99 uris,
100 existingCount: attachments.length,
101 });
102 if (images.length > 0) {
103 setAttachments((current) => [...current, ...images]);
104 }
105 } catch (error) {
106 console.error("[review comment] error converting pasted images", error);
107 }
108 })();
109 });
110
111 useEffect(() => {
112 if (!target || selectedLines.length === 0) {
113 setHighlightedLinesById({});
114 return;
115 }
116
117 let cancelled = false;
118 void highlightReviewSelectedLines({
119 filePath: target.filePath,
120 lines: selectedLines,
121 theme: selectedTheme,
122 })
123 .then((next) => {
124 if (!cancelled) {
125 setHighlightedLinesById(next);
126 }
127 })
128 .catch(() => {
129 if (!cancelled) {
130 setHighlightedLinesById({});
131 }
132 });
133
134 return () => {
135 cancelled = true;
136 };
137 }, [selectedLines, selectedTheme, target]);
138
139 async function handlePickImages(): Promise<void> {
140 const result = await pickComposerImages({ existingCount: attachments.length });
141 if (result.images.length > 0) {
142 setAttachments((current) => [...current, ...result.images]);
143 }
144 if (result.error) {
145 setPendingConnectionError(result.error);
146 }
147 }
148
149 const handleSubmit = useCallback(() => {
150 if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
151 return;
152 }
153
154 appendReviewCommentToDraft({
155 environmentId,
156 threadId,
157 text: formatReviewCommentContext(target, commentText),
158 attachments,
159 });
160 setAttachments([]);
161 dismissComposer();
162 }, [attachments, commentText, dismissComposer, environmentId, target, threadId]);
163
164 return (
165 <View className="flex-1">
166 <KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
167 <View
168 className="flex-1 px-5"
169 style={{
170 paddingTop: isAndroid ? insets.top + 8 : 8,
171 paddingBottom: target ? (isAndroid ? 72 : 0) : Math.max(insets.bottom, 18),
172 }}
173 >
174 <View className="flex-row items-center justify-between py-2">
175 <Pressable
176 className="bg-subtle h-12 w-12 items-center justify-center rounded-full"
177 onPress={dismissComposer}
178 >
179 <SymbolView name="xmark" size={18} tintColor={iconTint} type="monochrome" />
180 </Pressable>
181
182 <Text className="text-lg font-t3-bold text-foreground">Add Comment</Text>
183
184 <View className="h-12 w-12" />
185 </View>
186
187 {!target ? (
188 <View className="rounded-[22px] border border-border bg-card px-4 py-5">
189 <Text className="text-base font-t3-bold text-foreground">No selection</Text>
190 <Text className="mt-1 text-sm leading-normal text-foreground-muted">
191 Select a diff line or range first.
192 </Text>
193 </View>
194 ) : (
195 <View className="min-h-0 flex-1 gap-4">
196 <View className="gap-1 px-1">
197 <Text className="text-2xs font-t3-bold uppercase text-foreground-muted">
198 {selectionLabel}
199 </Text>
200 <Text
201 className="font-mono text-xs leading-snug text-foreground-muted"
202 ellipsizeMode="middle"
203 numberOfLines={2}
204 >
205 {target.filePath}
206 </Text>
207 </View>
208
209 <View className="overflow-hidden rounded-[22px] border border-border bg-card">
210 <ScrollView
211 horizontal
212 bounces={false}
213 keyboardShouldPersistTaps="always"
214 showsHorizontalScrollIndicator={false}
215 >
216 <ScrollView
217 bounces={false}
218 scrollEnabled={selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES}
219 nestedScrollEnabled
220 keyboardShouldPersistTaps="always"
221 showsVerticalScrollIndicator={
222 selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES
223 }
224 style={{ height: previewHeight }}
225 >
226 <View style={{ minWidth: previewViewportWidth }}>
227 {selectedLines.map((line) => {
228 const lineNumber = getReviewUnifiedLineNumber(line);
229
230 return (
231 <View
232 key={line.id}
233 className={cn("flex-row items-start", changeTone(line.change))}
234 style={{ height: codeSurface.rowHeight }}
235 >
236 <ReviewChangeBar change={line.change} height={codeSurface.rowHeight} />
237 <Text className="w-9 py-1 pr-1 text-right text-2xs font-mono text-foreground-muted">
238 {lineNumber ?? ""}
239 </Text>
240 <View className="min-w-0 flex-1 shrink-0 px-1 py-1">
241 <DiffTokenText
242 fallback={line.content}
243 tokens={highlightedLinesById[line.id] ?? null}
244 change={line.change}
245 fontSize={codeSurface.fontSize}
246 lineHeight={codeSurface.rowHeight}
247 />
248 </View>
249 </View>
250 );
251 })}
252 </View>
253 </ScrollView>
254 </ScrollView>
255 </View>
256
257 <View className="min-h-0 flex-1 gap-2">
258 <Text className="text-sm font-t3-bold text-foreground">Comment</Text>
259 <View className="min-h-[132px] flex-1 overflow-hidden rounded-[20px] border border-border bg-card">
260 <View className="min-h-0 flex-1 px-4 pt-3.5">
261 <TextInputWrapper onPaste={handleNativePaste} style={{ flex: 1, minHeight: 0 }}>
262 <TextInput
263 autoFocus
264 multiline
265 scrollEnabled
266 placeholder="Leave a comment..."
267 textAlignVertical="top"
268 value={commentText}
269 onChangeText={setCommentText}
270 className="h-full min-h-0 flex-1 border-0 bg-transparent px-0 py-0 font-sans text-base"
271 />
272 </TextInputWrapper>
273 </View>
274 {attachments.length > 0 ? (
275 <View className="px-4 pb-3 pt-2">
276 <ComposerAttachmentStrip
277 attachments={attachments}
278 imageBorderRadius={16}
279 imageSize={60}
280 onPressImage={setPreviewImageUri}
281 removeButtonPlacement="gutter"
282 onRemove={(imageId) => {
283 setAttachments((current) =>
284 current.filter((image) => image.id !== imageId),
285 );
286 }}
287 />
288 </View>
289 ) : null}
290 </View>
291 </View>
292 </View>
293 )}
294 </View>
295 {!isAndroid && target ? (
296 <View className="flex-row items-center gap-3 bg-sheet px-5 py-2">
297 <ControlPill
298 accessibilityLabel="Add image"
299 icon="plus"
300 onPress={() => void handlePickImages()}
301 />
302 <View className="flex-1" />
303 <ControlPill
304 accessibilityLabel="Comment"
305 icon="arrow.up"
306 label="Comment"
307 variant="primary"
308 disabled={!canSubmit}
309 onPress={handleSubmit}
310 />
311 </View>
312 ) : null}
313 </KeyboardAvoidingView>
314 {isAndroid && target ? (
315 <KeyboardStickyView
316 className="absolute inset-x-0 bottom-0"
317 offset={{ closed: 0, opened: 0 }}
318 >
319 <View
320 className="flex-row items-center gap-3 border-t border-border bg-sheet px-5 pt-2"
321 style={{ paddingBottom: Math.max(insets.bottom, 10) }}
322 >
323 <ControlPill
324 accessibilityLabel="Add image"
325 icon="plus"
326 onPress={() => void handlePickImages()}
327 />
328 <View className="flex-1" />
329 <ControlPill
330 accessibilityLabel="Comment"
331 icon="arrow.up"
332 label="Comment"
333 variant="primary"
334 disabled={!canSubmit}
335 onPress={handleSubmit}
336 />
337 </View>
338 </KeyboardStickyView>
339 ) : null}
340 <ImageViewing
341 images={previewImageUri ? [{ uri: previewImageUri }] : []}
342 imageIndex={0}
343 visible={previewImageUri !== null}
344 onRequestClose={() => setPreviewImageUri(null)}
345 swipeToCloseEnabled
346 doubleTapToZoomEnabled
347 />
348 </View>
349 );
350}