The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { |
| 3 | parsePullRequestAnchor, |
| 4 | pullRequestAnchorMatchesUrl, |
| 5 | resolvePullRequestReviewAnchor, |
| 6 | } from "@t3tools/shared/pullRequestAnchor"; |
| 7 | import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; |
| 8 | import { useAtomRefresh } from "@effect/atom-react"; |
| 9 | import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native"; |
| 10 | import { |
| 11 | type AtomCommandResult, |
| 12 | squashAtomCommandFailure, |
| 13 | } from "@t3tools/client-runtime/state/runtime"; |
| 14 | import { AsyncResult } from "effect/reactivity"; |
| 15 | import { pullRequestConversationThreads, type PullRequestThreadComment } from "@t3tools/contracts"; |
| 16 | import { T, useGT, useMessages } from "gt-react-native"; |
| 17 | import { useRef, useState } from "react"; |
| 18 | import { ScrollView, View, type ScrollViewInstance } from "react-native"; |
| 19 | import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller"; |
| 20 | import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeScrollViewMarker"; |
| 21 | import { useSafeAreaInsets } from "react-native-safe-area-context"; |
| 22 | import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText"; |
| 23 | import { AppBar } from "../../components/ui/AppBar"; |
| 24 | import { Button } from "../../components/ui/Button"; |
| 25 | import { GlassSurface } from "../../components/ui/GlassSurface"; |
| 26 | import { compareTimestamps, relativeTime } from "../../lib/time"; |
| 27 | import { composerPullRequests } from "../../state/pull-requests"; |
| 28 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 29 | import { useEnvironmentQuery } from "../../state/query"; |
| 30 | import { PullRequestMarkdown, PullRequestMarkdownRepository } from "./PullRequestMarkdown"; |
| 31 | import { PullRequestAvatar } from "./PullRequestPresentation"; |
| 32 | import { PullRequestCommentFooter } from "./PullRequestReactions"; |
| 33 | import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; |
| 34 | import { usePullRequestPermissions } from "./usePullRequestPermissions"; |
| 35 | import { pullRequestReviewKey } from "./pullRequestReviewDrafts"; |
| 36 | import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions"; |
| 37 | import { usePullRequestCompletions } from "./usePullRequestCompletions"; |
| 38 | import { m } from "../../i18n/messages"; |
| 39 | |
| 40 | export function PullRequestDiscussionScreen({ |
| 41 | route, |
| 42 | }: StaticScreenProps<PullRequestParams & { readonly discussionId: string }>) { |
| 43 | return ( |
| 44 | <Discussion |
| 45 | key={`${pullRequestReviewKey(route.params)}:${route.params.discussionId}`} |
| 46 | params={route.params} |
| 47 | /> |
| 48 | ); |
| 49 | } |
| 50 | |
| 51 | function Discussion({ params }: { params: PullRequestParams & { readonly discussionId: string } }) { |
| 52 | const target = pullRequestTarget(params); |
| 53 | const navigation = useNavigation(); |
| 54 | const gt = useGT(); |
| 55 | const messages = useMessages(); |
| 56 | const insets = useSafeAreaInsets(); |
| 57 | const keyboardVisible = useKeyboardState((state) => state.isVisible); |
| 58 | const bottomInset = keyboardVisible ? 8 : Math.max(insets.bottom, 12); |
| 59 | const activity = useEnvironmentQuery(composerPullRequests.activity(target)); |
| 60 | const detail = useEnvironmentQuery(composerPullRequests.detail(target)); |
| 61 | const permissions = usePullRequestPermissions(params, detail.data); |
| 62 | const refresh = useAtomRefresh(composerPullRequests.activity(target)); |
| 63 | const reply = useAtomCommand(composerPullRequests.replyToThread, { reportFailure: false }); |
| 64 | const resolve = useAtomCommand(composerPullRequests.setThreadResolution, { |
| 65 | reportFailure: false, |
| 66 | }); |
| 67 | const loadMore = useAtomCommand(composerPullRequests.threadComments, { reportFailure: false }); |
| 68 | const thread = |
| 69 | activity.data && |
| 70 | pullRequestConversationThreads(activity.data).find( |
| 71 | (thread) => thread.id === params.discussionId, |
| 72 | ); |
| 73 | const filePath = thread?.path ?? null; |
| 74 | const [body, setBody] = useState(""); |
| 75 | const completions = usePullRequestCompletions({ |
| 76 | environmentId: params.environmentId, |
| 77 | projectId: params.projectId, |
| 78 | value: body, |
| 79 | onChangeValue: setBody, |
| 80 | support: detail.data?.capabilities ?? null, |
| 81 | }); |
| 82 | const [extra, setExtra] = useState<readonly PullRequestThreadComment[]>([]); |
| 83 | const [cursor, setCursor] = useState<string | null | undefined>(); |
| 84 | const [busy, setBusy] = useState(false); |
| 85 | const pending = useRef(false); |
| 86 | const [error, setError] = useState<string | null>(null); |
| 87 | const [notice, setNotice] = useState<string | null>(null); |
| 88 | const [composerHeight, setComposerHeight] = useState(64); |
| 89 | // Replies from "Load more" live only here, outside the activity an edit refreshes. After one |
| 90 | // is edited, drop the loaded pages so the next load reads the new body instead of the old one. |
| 91 | const extraEdited = useRef(false); |
| 92 | useFocusEffect(() => { |
| 93 | if (!extraEdited.current) return; |
| 94 | extraEdited.current = false; |
| 95 | setExtra([]); |
| 96 | setCursor(undefined); |
| 97 | }); |
| 98 | const operation = async (run: () => Promise<AtomCommandResult<unknown, unknown> | undefined>) => { |
| 99 | if (pending.current) return; |
| 100 | pending.current = true; |
| 101 | setBusy(true); |
| 102 | setError(null); |
| 103 | setNotice(null); |
| 104 | const result = await run(); |
| 105 | pending.current = false; |
| 106 | setBusy(false); |
| 107 | if (result && AsyncResult.isFailure(result)) { |
| 108 | const cause = squashAtomCommandFailure(result); |
| 109 | setError( |
| 110 | cause instanceof Error |
| 111 | ? (errorDisplayMessage(cause, m) ?? cause.message) |
| 112 | : gt("The provider could not complete this action."), |
| 113 | ); |
| 114 | } |
| 115 | }; |
| 116 | const post = () => |
| 117 | operation(async () => { |
| 118 | if (!permissions.canReply || !body.trim() || !thread) return undefined; |
| 119 | const submitted = body; |
| 120 | const response = await reply({ |
| 121 | ...target, |
| 122 | input: { ...target.input, threadId: thread.id, body: submitted }, |
| 123 | }); |
| 124 | if (AsyncResult.isFailure(response)) return response; |
| 125 | setBody((current) => (current === submitted ? "" : current)); |
| 126 | setNotice(gt("Reply posted.")); |
| 127 | refresh(); |
| 128 | return response; |
| 129 | }); |
| 130 | const toggleResolved = () => |
| 131 | operation(async () => { |
| 132 | if (!thread || !permissions.canResolve) return undefined; |
| 133 | const response = await resolve({ |
| 134 | ...target, |
| 135 | input: { ...target.input, threadId: thread.id, resolved: !thread.isResolved }, |
| 136 | }); |
| 137 | if (AsyncResult.isSuccess(response)) refresh(); |
| 138 | return response; |
| 139 | }); |
| 140 | const nextCursor = cursor === undefined ? thread?.nextCommentsCursor : cursor; |
| 141 | const more = () => |
| 142 | operation(async () => { |
| 143 | if (!thread || !nextCursor) return undefined; |
| 144 | const response = await loadMore({ |
| 145 | ...target, |
| 146 | input: { ...target.input, threadId: thread.id, cursor: nextCursor }, |
| 147 | }); |
| 148 | if (AsyncResult.isFailure(response)) return response; |
| 149 | setExtra((comments) => [...comments, ...response.value.comments]); |
| 150 | setCursor(response.value.nextCursor); |
| 151 | return response; |
| 152 | }); |
| 153 | const comments = [ |
| 154 | ...new Map( |
| 155 | [...extra, ...(thread?.comments ?? [])].map((comment) => [comment.id, comment]), |
| 156 | ).values(), |
| 157 | ].sort((left, right) => compareTimestamps(left.createdAt, right.createdAt)); |
| 158 | const scrollRef = useRef<ScrollViewInstance>(null); |
| 159 | const pendingTop = useRef<number | null>(null); |
| 160 | const positionedComment = useRef<string | null>(null); |
| 161 | const location = parsePullRequestAnchor(params.navigationUrl); |
| 162 | const anchor = |
| 163 | location?.kind === "timeline" |
| 164 | ? resolvePullRequestReviewAnchor(location.anchor, [], [{ comments }]) |
| 165 | : null; |
| 166 | const canReply = permissions.canReply && Boolean(thread); |
| 167 | const resolveLabel = thread?.isResolved |
| 168 | ? gt("Unresolve", { $context: "review thread" }) |
| 169 | : gt("Resolve", { $context: "review thread" }); |
| 170 | return ( |
| 171 | <PullRequestMarkdownRepository params={params} changeRequest={detail.data}> |
| 172 | <KeyboardAvoidingView |
| 173 | automaticOffset |
| 174 | behavior="height" |
| 175 | className="flex-1 bg-screen" |
| 176 | // Any touch, such as replying or loading replies, ends the wait to reposition the link. |
| 177 | onTouchStart={() => { |
| 178 | pendingTop.current = null; |
| 179 | }} |
| 180 | > |
| 181 | <AppBar |
| 182 | title={gt("Discussion")} |
| 183 | subtitle={`#${params.number}`} |
| 184 | onBack={() => navigation.goBack()} |
| 185 | actions={ |
| 186 | permissions.canResolve && thread |
| 187 | ? [ |
| 188 | { |
| 189 | accessibilityLabel: resolveLabel, |
| 190 | icon: thread.isResolved ? "arrow.uturn.backward" : "checkmark", |
| 191 | disabled: busy || activity.isPending, |
| 192 | onPress: () => void toggleResolved(), |
| 193 | }, |
| 194 | ] |
| 195 | : [] |
| 196 | } |
| 197 | /> |
| 198 | <ScrollViewMarker style={{ flex: 1 }}> |
| 199 | <ScrollView |
| 200 | ref={scrollRef} |
| 201 | onContentSizeChange={() => { |
| 202 | if (pendingTop.current === null) return; |
| 203 | scrollRef.current?.scrollTo({ y: pendingTop.current, animated: false }); |
| 204 | pendingTop.current = null; |
| 205 | }} |
| 206 | className="flex-1" |
| 207 | contentInsetAdjustmentBehavior="automatic" |
| 208 | keyboardShouldPersistTaps="handled" |
| 209 | contentContainerStyle={{ |
| 210 | padding: 20, |
| 211 | paddingBottom: canReply ? composerHeight + bottomInset + 24 : 24, |
| 212 | }} |
| 213 | > |
| 214 | {activity.isPending && !thread ? <AppActivityIndicator /> : null} |
| 215 | {thread ? ( |
| 216 | <View className="gap-2 pb-4"> |
| 217 | {thread.path === null ? null : ( |
| 218 | <Text selectable className="font-mono text-xs text-foreground-muted"> |
| 219 | {thread.path} |
| 220 | {thread.line ? `:${thread.line}` : ""} |
| 221 | </Text> |
| 222 | )} |
| 223 | <Text className="text-xs text-foreground-muted"> |
| 224 | {thread.isResolved |
| 225 | ? gt("Resolved", { $context: "review thread state" }) |
| 226 | : gt("Unresolved", { $context: "review thread state" })} |
| 227 | {thread.isOutdated |
| 228 | ? ` · ${gt("Outdated", { $context: "review thread state" })}` |
| 229 | : ""} |
| 230 | </Text> |
| 231 | {filePath === null ? null : ( |
| 232 | <Button |
| 233 | label={gt("View file diff")} |
| 234 | onPress={() => |
| 235 | navigation.navigate("PullRequestFile", { ...params, path: filePath }) |
| 236 | } |
| 237 | /> |
| 238 | )} |
| 239 | </View> |
| 240 | ) : !activity.isPending ? ( |
| 241 | <Text> |
| 242 | <T>This discussion is no longer available.</T> |
| 243 | </Text> |
| 244 | ) : null} |
| 245 | {comments.map((comment) => ( |
| 246 | <View |
| 247 | key={comment.id} |
| 248 | onLayout={(event) => { |
| 249 | if ( |
| 250 | anchor === null || |
| 251 | !pullRequestAnchorMatchesUrl(anchor, comment.url) || |
| 252 | positionedComment.current === comment.id |
| 253 | ) |
| 254 | return; |
| 255 | positionedComment.current = comment.id; |
| 256 | pendingTop.current = event.nativeEvent.layout.y; |
| 257 | scrollRef.current?.scrollTo({ y: pendingTop.current, animated: false }); |
| 258 | }} |
| 259 | className={ |
| 260 | anchor !== null && pullRequestAnchorMatchesUrl(anchor, comment.url) |
| 261 | ? "-mx-3 gap-3 rounded-2xl border border-primary bg-primary/10 px-3 py-4" |
| 262 | : "gap-3 border-b border-border-subtle py-4" |
| 263 | } |
| 264 | > |
| 265 | <View className="flex-row items-center gap-2"> |
| 266 | <PullRequestAvatar actor={comment.author} size={28} /> |
| 267 | <Text className="min-w-0 flex-1 text-sm font-t3-medium"> |
| 268 | {comment.author?.login ?? gt("Unknown author")} |
| 269 | </Text> |
| 270 | <Text className="text-2xs text-foreground-muted"> |
| 271 | {relativeTime(comment.createdAt, undefined, messages)} |
| 272 | </Text> |
| 273 | </View> |
| 274 | <PullRequestMarkdown markdown={comment.body} /> |
| 275 | <PullRequestCommentFooter |
| 276 | params={params} |
| 277 | comment={{ ...comment, kind: "review-comment" }} |
| 278 | permissions={permissions} |
| 279 | onChanged={refresh} |
| 280 | onEdit={() => { |
| 281 | if (extra.some((loaded) => loaded.id === comment.id)) |
| 282 | extraEdited.current = true; |
| 283 | }} |
| 284 | /> |
| 285 | </View> |
| 286 | ))} |
| 287 | {nextCursor ? ( |
| 288 | <Button |
| 289 | label={busy ? gt("Loading…") : gt("Load more replies")} |
| 290 | disabled={busy} |
| 291 | onPress={() => void more()} |
| 292 | /> |
| 293 | ) : null} |
| 294 | {error || activity.error ? ( |
| 295 | <Text selectable className="py-4 text-sm text-danger-foreground"> |
| 296 | {error ?? activity.error} |
| 297 | </Text> |
| 298 | ) : null} |
| 299 | {notice ? <Text className="py-4 text-sm text-foreground-muted">{notice}</Text> : null} |
| 300 | </ScrollView> |
| 301 | </ScrollViewMarker> |
| 302 | {canReply ? ( |
| 303 | <View |
| 304 | className="absolute inset-x-4 bottom-0 gap-2" |
| 305 | style={{ paddingBottom: bottomInset }} |
| 306 | > |
| 307 | <PullRequestCompletionSuggestions completions={completions} /> |
| 308 | <GlassSurface |
| 309 | chrome="none" |
| 310 | onLayout={(event) => setComposerHeight(event.nativeEvent.layout.height)} |
| 311 | className="flex-row items-end gap-1 p-1" |
| 312 | > |
| 313 | <TextInput |
| 314 | accessibilityLabel={gt("Discussion reply")} |
| 315 | selection={completions.selection} |
| 316 | onSelectionChange={completions.onSelectionChange} |
| 317 | onBlur={completions.onBlur} |
| 318 | multiline |
| 319 | maxLength={65536} |
| 320 | placeholder={gt("Reply…")} |
| 321 | placeholderTextColorClassName="accent-foreground-muted" |
| 322 | value={body} |
| 323 | onChangeText={setBody} |
| 324 | editable={!busy} |
| 325 | 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" |
| 326 | /> |
| 327 | <View> |
| 328 | <Button |
| 329 | label={busy ? gt("Posting…") : gt("Reply", { $context: "verb, button" })} |
| 330 | tone="contrast" |
| 331 | disabled={busy || !body.trim()} |
| 332 | onPress={() => void post()} |
| 333 | /> |
| 334 | </View> |
| 335 | </GlassSurface> |
| 336 | </View> |
| 337 | ) : null} |
| 338 | </KeyboardAvoidingView> |
| 339 | </PullRequestMarkdownRepository> |
| 340 | ); |
| 341 | } |