Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ReviewCommentComposerSheet.tsx

314 lines12.7 KB

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, Pressable, 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/FilePreviewModal";
9​
10import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
11import { SymbolView } from "../../components/ui/AppSymbol";
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 <KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
133 <View
134 className="flex-1 px-5"
135 style={{
136 paddingTop: isAndroid ? insets.top + 8 : 8,
137 paddingBottom: target ? (isAndroid ? 72 : 0) : Math.max(insets.bottom, 18),
138 }}
139 >
140 <View className="flex-row items-center justify-between py-2">
141 <Pressable
142 className="bg-subtle h-12 w-12 items-center justify-center rounded-full"
143 onPress={dismissComposer}
144 >
145 <SymbolView
146 name="xmark"
147 size={18}
148 tintColorClassName={"accent-icon"}
149 type="monochrome"
150 />
151 </Pressable>
152​
153 <Text className="text-lg font-t3-bold text-foreground">Add Comment</Text>
154​
155 <View className="h-12 w-12" />
156 </View>
157​
158 {!target ? (
159 <View className="rounded-[22px] border border-border bg-card px-4 py-5">
160 <Text className="text-base font-t3-bold text-foreground">No selection</Text>
161 <Text className="mt-1 text-sm leading-normal text-foreground-muted">
162 Select a diff line or range first.
163 </Text>
164 </View>
165 ) : (
166 <View className="min-h-0 flex-1 gap-4">
167 <View className="gap-1 px-1">
168 <Text className="text-2xs font-t3-bold uppercase text-foreground-muted">
169 {selectionLabel}
170 </Text>
171 <Text
172 className="font-mono text-xs leading-snug text-foreground-muted"
173 ellipsizeMode="middle"
174 numberOfLines={2}
175 >
176 {target.filePath}
177 </Text>
178 </View>
179​
180 <View className="overflow-hidden rounded-[22px] border border-border bg-card">
181 <ScrollView
182 horizontal
183 bounces={false}
184 keyboardShouldPersistTaps="always"
185 showsHorizontalScrollIndicator={false}
186 >
187 <ScrollView
188 bounces={false}
189 scrollEnabled={selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES}
190 nestedScrollEnabled
191 keyboardShouldPersistTaps="always"
192 showsVerticalScrollIndicator={
193 selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES
194 }
195 style={{ height: previewHeight }}
196 >
197 <View style={{ minWidth: previewViewportWidth }}>
198 {selectedLines.map((line) => {
199 const lineNumber = getReviewUnifiedLineNumber(line);
200​
201 return (
202 <View
203 key={line.id}
204 className={cn("flex-row items-start", changeTone(line.change))}
205 style={{ height: codeSurface.rowHeight }}
206 >
207 <ReviewChangeBar change={line.change} height={codeSurface.rowHeight} />
208 <Text className="w-9 py-1 pr-1 text-right text-2xs font-mono text-foreground-muted">
209 {lineNumber ?? ""}
210 </Text>
211 <View className="min-w-0 flex-1 shrink-0 px-1 py-1">
212 <DiffTokenText
213 fallback={line.content}
214 tokens={highlightedLinesById[line.id] ?? null}
215 change={line.change}
216 fontSize={codeSurface.fontSize}
217 lineHeight={codeSurface.rowHeight}
218 />
219 </View>
220 </View>
221 );
222 })}
223 </View>
224 </ScrollView>
225 </ScrollView>
226 </View>
227​
228 <View className="min-h-0 flex-1 gap-2">
229 <Text className="text-sm font-t3-bold text-foreground">Comment</Text>
230 <View className="min-h-[132px] flex-1 overflow-hidden rounded-[20px] border border-border bg-card">
231 <View className="min-h-0 flex-1 px-4 pt-3.5">
232 <TextInputWrapper onPaste={handleNativePaste} style={{ flex: 1, minHeight: 0 }}>
233 <TextInput
234 autoFocus
235 multiline
236 scrollEnabled
237 placeholder="Leave a comment..."
238 textAlignVertical="top"
239 value={commentText}
240 onChangeText={setCommentText}
241 className="h-full min-h-0 flex-1 border-0 bg-transparent px-0 py-0 font-sans text-base"
242 />
243 </TextInputWrapper>
244 </View>
245 {attachments.length > 0 ? (
246 <View className="px-4 pb-3 pt-2">
247 <ComposerAttachmentStrip
248 attachments={attachments}
249 imageBorderRadius={16}
250 imageSize={60}
251 onPressPreview={setPreviewFile}
252 removeButtonPlacement="gutter"
253 onRemove={(imageId) => {
254 setAttachments((current) =>
255 current.filter((image) => image.id !== imageId),
256 );
257 }}
258 />
259 </View>
260 ) : null}
261 </View>
262 </View>
263 </View>
264 )}
265 </View>
266 {!isAndroid && target ? (
267 <View className="flex-row items-center gap-3 bg-sheet px-5 py-2">
268 <ControlPill
269 accessibilityLabel="Add image"
270 icon="plus"
271 onPress={() => void handlePickImages()}
272 />
273 <View className="flex-1" />
274 <ControlPill
275 accessibilityLabel="Comment"
276 icon="arrow.up"
277 label="Comment"
278 variant="primary"
279 disabled={!canSubmit}
280 onPress={handleSubmit}
281 />
282 </View>
283 ) : null}
284 </KeyboardAvoidingView>
285 {isAndroid && target ? (
286 <KeyboardStickyView
287 className="absolute inset-x-0 bottom-0"
288 offset={{ closed: 0, opened: 0 }}
289 >
290 <View
291 className="flex-row items-center gap-3 border-t border-border bg-sheet px-5 pt-2"
292 style={{ paddingBottom: Math.max(insets.bottom, 10) }}
293 >
294 <ControlPill
295 accessibilityLabel="Add image"
296 icon="plus"
297 onPress={() => void handlePickImages()}
298 />
299 <View className="flex-1" />
300 <ControlPill
301 accessibilityLabel="Comment"
302 icon="arrow.up"
303 label="Comment"
304 variant="primary"
305 disabled={!canSubmit}
306 onPress={handleSubmit}
307 />
308 </View>
309 </KeyboardStickyView>
310 ) : null}
311 <FilePreviewModal source={previewFile} onRequestClose={() => setPreviewFile(null)} />
312 </View>
313 );