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

ComposerContextSheet.tsx

397 lines15.3 KB

1import { Button } from "./ui/Button";
2import * as Dialog from "./ui/Dialog";
3import { useOpenPullRequest } from "../native/useOpenPullRequest";
4import { SourceFileSurface } from "../features/files/SourceFileSurface";
5import { filePreviewKind } from "@t3tools/shared/filePreview";
6import type {
7 ComposerContextRecord,
8 ElementContextSource,
9 EnvironmentId,
10 ProjectId,
11 ScopedThreadRef,
12} from "@t3tools/contracts";
13import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
14import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
15import { videoMimeType } from "@t3tools/shared/video";
16import { Platform, Pressable, ScrollView, View } from "react-native";
17import { useSafeAreaInsets } from "react-native-safe-area-context";
18import { REVIEW_MONO_FONT_FAMILY } from "../features/review/reviewDiffRendering";
19import { ReviewCommentCard, useReviewCommentColors } from "../features/review/ReviewCommentCard";
20import {
21 composerAttachmentInlineUri,
22 isFileBackedComposerAttachment,
23 type DraftComposerAttachment,
24} from "../lib/composerImages";
25import { contextImageGallery } from "../lib/contextImageGallery";
26import { FilePreviewModal } from "./FilePreviewModal";
27import { VideoPreviewModal } from "./VideoPreviewModal";
28import { ComposerContextAttachment } from "./ComposerContextAttachment";
29import { AppText as Text } from "./ui/AppText";
30import { Sheet } from "./ui/Sheet";
31import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
32import { getMobileTerminalTheme } from "../features/terminal/terminalTheme";
33​
34function ContextField(props: { label: string; value: string | null | undefined; code?: boolean }) {
35 if (!props.value) return null;
36 return (
37 <View className="gap-1">
38 <Text className="text-xs text-foreground-muted">{props.label}</Text>
39 {props.code && (props.label === "HTML" || props.label === "Styles") ? (
40 <View
41 className="overflow-hidden rounded-xl border border-border"
42 style={{ height: Math.min(260, Math.max(100, props.value.split("\n").length * 22 + 36)) }}
43 >
44 <SourceFileSurface
45 embedded
46 contents={props.value}
47 path={props.label === "HTML" ? "element.html" : "styles.css"}
48 />
49 </View>
50 ) : (
51 <Text
52 selectable
53 className={props.code ? "text-sm text-foreground" : "text-base text-foreground"}
54 style={props.code ? { fontFamily: REVIEW_MONO_FONT_FAMILY } : undefined}
55 >
56 {props.value}
57 </Text>
58 )}
59 </View>
60 );
62​
63function ContextSource(props: { source: ElementContextSource | null }) {
64 const source = props.source;
65 if (!source) return null;
66 const location = source.fileName
67 ? `${source.fileName}${source.lineNumber !== null ? `:${source.lineNumber}${source.columnNumber !== null ? `:${source.columnNumber}` : ""}` : ""}`
68 : null;
69 return (
70 <ContextField
71 label="Source"
72 value={[source.functionName, location].filter(Boolean).join("\n")}
73 code
74 />
75 );
77​
78export function ComposerContextSheet(props: {
79 readonly label: string;
80 readonly record: ComposerContextRecord | undefined;
81 readonly onClose: () => void;
82 readonly onRemove?: () => void;
83 readonly onOpenAttachment?: () => void;
84 readonly onOpenPullRequest?: () => void;
85 readonly skillDescription?: string;
86 readonly onOpenSkill?: () => void;
87 readonly onOpenThread?: (thread: ScopedThreadRef) => void;
88 readonly environmentId?: EnvironmentId;
89 readonly projectId?: ProjectId;
90 readonly records?: ReadonlyArray<ComposerContextRecord>;
91 readonly attachments?: ReadonlyArray<DraftComposerAttachment>;
92}) {
93 const openPullRequest = useOpenPullRequest({
94 context:
95 props.environmentId && props.projectId
96 ? { environmentId: props.environmentId, projectId: props.projectId }
97 : undefined,
98 });
99 const reviewColors = useReviewCommentColors();
100 const insets = useSafeAreaInsets();
101 const { themeId, themeAppearance } = useAppearancePreferences();
102 const terminalTheme = getMobileTerminalTheme(themeId, themeAppearance);
103 const record = props.record;
104 const localAttachment =
105 record && "attachmentId" in record
106 ? props.attachments?.find((entry) => entry.id === record.attachmentId)
107 : undefined;
108 const localFile =
109 localAttachment && isFileBackedComposerAttachment(localAttachment)
110 ? localAttachment
111 : undefined;
112 if (record && !("payload" in record) && (record.kind === "image" || record.kind === "file")) {
113 const mimeType = videoMimeType(record) ?? record.mimeType;
114 const previewKind = filePreviewKind(record, { richDocuments: false });
115 const resource = {
116 _tag: "attachment" as const,
117 attachmentId: record.attachmentId,
118 fileName: record.name,
119 mimeType,
120 };
121 const remoteSource = props.environmentId
122 ? { environmentId: props.environmentId, resource }
123 : null;
124 if (videoMimeType(record)) {
125 if (localFile?.type === "file") {
126 return (
127 <VideoPreviewModal
128 source={{ type: "local", attachment: localFile }}
129 onRequestClose={props.onClose}
130 />
131 );
132 }
133 if (remoteSource && !localFile) {
134 return (
135 <VideoPreviewModal
136 source={{
137 type: "media",
138 name: record.name,
139 mimeType,
140 ...remoteSource,
141 actionsSource: { name: record.name, mimeType, ...remoteSource },
142 }}
143 onRequestClose={props.onClose}
144 />
145 );
146 }
147 } else if (record.kind === "image" || previewKind === "image" || previewKind === "pdf") {
148 const inlineUri = composerAttachmentInlineUri(localAttachment);
149 const source = localFile
150 ? { attachment: localFile }
151 : inlineUri
152 ? { uri: inlineUri }
153 : remoteSource;
154 if (source) {
155 return (
156 <FilePreviewModal
157 source={{
158 kind: record.kind === "image" || previewKind === "image" ? "image" : "pdf",
159 name: record.name,
160 ...source,
161 gallery: contextImageGallery(
162 props.records ?? [],
163 props.attachments ?? [],
164 props.environmentId,
165 ),
166 actionsSource: { name: record.name, mimeType, ...source },
167 }}
168 onRequestClose={props.onClose}
169 />
170 );
171 }
172 }
173 }
174 const attachmentRecord =
175 record && "attachmentId" in record
176 ? record
177 : record?.kind === "preview-annotation" && "screenshotContextId" in record
178 ? props.records?.find(
179 (entry) => entry.contextId === record.screenshotContextId && "attachmentId" in entry,
180 )
181 : undefined;
182 const pullRequestUrl =
183 record?.kind === "review-comment" && "pullRequest" in record
184 ? record.pullRequest?.url
185 : undefined;
186 const changeRequestTerm = (
187 (pullRequestUrl ? sourceControlClients.findByChangeRequestUrl(pullRequestUrl) : undefined) ??
188 sourceControlClients.get(undefined)
189 ).changeRequest.singular;
190 const terminal = record?.kind === "terminal" && !("payload" in record) ? record : null;
191 return (
192 <Sheet title={terminal?.terminalLabel ?? props.label} onClose={props.onClose}>
193 <ScrollView
194 nestedScrollEnabled
195 className="flex-1"
196 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
197 contentContainerStyle={{
198 paddingHorizontal: 20,
199 paddingTop: 12,
200 gap: 16,
201 paddingBottom: Math.max(20, insets.bottom),
202 }}
203 >
204 {terminal ? (
205 <Text className="text-sm text-foreground-muted">
206 Lines {terminal.lineStart}–{terminal.lineEnd}
207 </Text>
208 ) : null}
209 {!record ? (
210 <Text className="text-foreground">
211 Context unavailable. The reference was copied without its payload. Copy it again from
212 the original message or remove it.
213 </Text>
214 ) : "payload" in record ? (
215 <Text className="text-foreground">
216 This context type is not supported by this version of the app. Its payload will be
217 preserved when sent.
218 </Text>
219 ) : (
220 <>
221 {record.kind === "terminal" ? (
222 <View
223 className="overflow-hidden rounded-xl"
224 style={{ backgroundColor: terminalTheme.background }}
225 >
226 <ScrollView
227 horizontal
228 showsHorizontalScrollIndicator
229 contentContainerStyle={{ padding: 12 }}
230 >
231 <Text
232 selectable
233 className="text-sm text-foreground"
234 style={{
235 fontFamily: REVIEW_MONO_FONT_FAMILY,
236 fontSize: 13,
237 lineHeight: 20,
238 color: terminalTheme.foreground,
239 }}
240 >
241 {record.text}
242 </Text>
243 </ScrollView>
244 </View>
245 ) : null}
246 {record.kind === "review-comment" ? (
247 <>
248 {record.pullRequest ? (
249 <ContextField
250 label={`#${record.pullRequest.number} · ${record.pullRequest.isDraft ? "draft" : record.pullRequest.state}`}
251 value={`${record.pullRequest.title}\n${record.pullRequest.headBranch} → ${record.pullRequest.baseBranch}`}
252 />
253 ) : null}
254 {!record.sectionId.startsWith("pull-request:") ? (
255 <>
256 <ReviewCommentCard
257 comment={{ ...record, id: record.contextId }}
258 colors={reviewColors}
259 />
260 </>
261 ) : null}
262 </>
263 ) : null}
264 {record.kind === "preview-annotation" ? (
265 <>
266 <ContextField label="Page" value={record.pageTitle ?? record.pageUrl} />
267 <ContextField label="URL" value={record.pageUrl} />
268 <ContextField label="Comment" value={record.comment} />
269 <ContextField label="Selection" value={record.targetSummary} />
270 <ContextField label="Requested changes" value={record.styleChanges.join("\n")} />
271 {record.elements?.map(
272 (element, index) => (
273 /* oxlint-disable react/no-array-index-key -- Captured DOM elements are a fixed snapshot without persistent element IDs. */ <View
274 key={`${element.selector ?? element.tagName}:${index}`}
275 className="gap-3"
276 >
277 <ContextField
278 label="Element"
279 value={element.componentName ?? element.tagName}
280 />
281 <ContextField label="Selector" value={element.selector} code />
282 <ContextSource source={element.source} />
283 <ContextField label="HTML" value={element.htmlPreview} code />
284 <ContextField label="Styles" value={element.styles} code />
285 </View>
286 ) /* oxlint-enable react/no-array-index-key */,
287 )}
288 </>
289 ) : null}
290 {record.kind === "element" ? (
291 <>
292 <ContextField label="Page" value={record.pageUrl} />
293 <ContextField label="Element" value={record.componentName ?? record.tagName} />
294 <ContextField label="Selector" value={record.selector} code />
295 <ContextSource source={record.source} />
296 <ContextField label="HTML" value={record.htmlPreview} code />
297 <ContextField label="Styles" value={record.styles} code />
298 </>
299 ) : null}
300 {record.kind === "image" ? (
301 <ContextField
302 label="File"
303 value={`${record.mimeType} · ${formatAttachmentSize(record.sizeBytes)}`}
304 />
305 ) : null}
306 {record.kind === "mention" ? (
307 <ContextField label="Path" value={record.path} code />
308 ) : null}
309 {record.kind === "thread" ? (
310 <View className="gap-3">
311 <ContextField label="Thread" value={record.title} />
312 {props.onOpenThread ? (
313 <Button
314 label="Open thread"
315 tone="secondary"
316 onPress={() =>
317 props.onOpenThread?.({
318 environmentId: record.environmentId,
319 threadId: record.threadId,
320 })
321 }
322 fullWidth
323 />
324 ) : null}
325 </View>
326 ) : null}
327 {record.kind === "skill" ? (
328 <View className="gap-3">
329 <ContextField label="Skill" value={record.name} />
330 <ContextField
331 label="Description"
332 value={props.skillDescription ?? "No description is available for this skill."}
333 />
334 {props.onOpenSkill ? (
335 <Button
336 label="View instructions"
337 tone="secondary"
338 onPress={props.onOpenSkill}
339 fullWidth
340 />
341 ) : null}
342 </View>
343 ) : null}
344 </>
345 )}
346 {attachmentRecord && "attachmentId" in attachmentRecord ? (
347 <ComposerContextAttachment
348 key={JSON.stringify([
349 props.environmentId,
350 attachmentRecord.attachmentId,
351 props.attachments?.find((entry) => entry.id === attachmentRecord.attachmentId)
352 ?.fileUri,
353 ])}
354 record={attachmentRecord}
355 environmentId={props.environmentId}
356 attachment={props.attachments?.find(
357 (entry) => entry.id === attachmentRecord.attachmentId,
358 )}
359 />
360 ) : null}
361 {pullRequestUrl && /^https?:\/\//i.test(pullRequestUrl) ? (
362 <Pressable
363 accessibilityRole="link"
364 onPress={() => {
365 props.onClose();
366 void openPullRequest(pullRequestUrl).catch(() =>
367 Dialog.alert(`Could not open ${changeRequestTerm}`, "Try again when connected."),
368 );
369 }}
370 className="rounded-xl bg-subtle p-4"
371 >
372 <Text className="text-foreground">Open {changeRequestTerm}</Text>
373 </Pressable>
374 ) : null}
375 {props.onOpenAttachment ? (
376 <Button
377 label="Open attachment"
378 tone="secondary"
379 onPress={props.onOpenAttachment}
380 fullWidth
381 />
382 ) : null}
383 {props.onOpenPullRequest && !pullRequestUrl ? (
384 <Button
385 label={`Open ${changeRequestTerm}`}
386 tone="secondary"
387 onPress={props.onOpenPullRequest}
388 fullWidth
389 />
390 ) : null}
391 {props.onRemove ? (
392 <Button label="Remove from draft" tone="secondary" onPress={props.onRemove} fullWidth />
393 ) : null}
394 </ScrollView>
395 </Sheet>
396 );