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