@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
tsx 201 lines 7.81 KB
Raw
1 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2 import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
3 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4 import { changeRequestTermKind } from "../../lib/changeRequestTerm";
5 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6 import { useAtomValue } from "@effect/atom-react";
7 import type { PullRequestComment } from "@t3tools/contracts";
8 import { AsyncResult } from "effect/reactivity";
9 import { useGT } from "gt-react-native";
10 import { useRef, useState } from "react";
11 import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
12 import { Button } from "../../components/ui/Button";
13 import { composerPullRequests } from "../../state/pull-requests";
14 import { useEnvironmentQuery } from "../../state/query";
15 import { useAtomCommand } from "../../state/use-atom-command";
16 import { PullRequestSheetContent } from "./PullRequestSheetContent";
17 import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
18 import { usePullRequestPermissions } from "./usePullRequestPermissions";
19 import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";
20 import { usePullRequestCompletions } from "./usePullRequestCompletions";
21 import { m } from "../../i18n/messages";
22
23 export type PullRequestEditParams = PullRequestParams &
24 (
25 | { readonly field: "title" | "body" }
26 | {
27 readonly field: "comment";
28 /** Carried along because a reply loaded page by page is not in the cached activity. */
29 readonly comment: Pick<PullRequestComment, "id" | "body" | "author" | "canEdit"> & {
30 readonly kind: "issue-comment" | "review-comment";
31 };
32 }
33 );
34
35 export function PullRequestEditScreen({ route }: StaticScreenProps<PullRequestEditParams>) {
36 const params = route.params;
37 const navigation = useNavigation();
38 const target = pullRequestTarget(params);
39 const detail = useEnvironmentQuery(composerPullRequests.detail(target));
40 const pr = detail.data;
41 const permissions = usePullRequestPermissions(params, pr);
42 const gt = useGT();
43 const update = useAtomCommand(composerPullRequests.update, { reportFailure: false });
44 const updateComment = useAtomCommand(composerPullRequests.updateComment, {
45 reportFailure: false,
46 });
47 const term = changeRequestTermKind(sourceControlClients.get(pr?.provider).changeRequest);
48 const original =
49 params.field === "comment"
50 ? params.comment.body
51 : params.field === "title"
52 ? (pr?.title ?? null)
53 : (pr?.body ?? null);
54 const [draft, setDraft] = useState<string | null>(null);
55 const value = draft ?? original ?? "";
56 const completions = usePullRequestCompletions({
57 environmentId: params.environmentId,
58 projectId: params.projectId,
59 value: value,
60 onChangeValue: setDraft,
61 support: params.field === "title" ? null : (pr?.capabilities ?? null),
62 });
63 const [busy, setBusy] = useState(false);
64 const [error, setError] = useState<string | null>(null);
65 const inFlight = useRef(false);
66 const allowed =
67 params.field === "comment"
68 ? permissions.canEditComment(params.comment)
69 : permissions.canEditChangeRequest;
70 const canWrite = useAtomValue(
71 (params.field === "comment"
72 ? composerPullRequests.updateComment
73 : composerPullRequests.update
74 ).permissionAtom(target.environmentId),
75 );
76 // Name the first thing in the way, so the notice says what would actually fix it.
77 const readOnlyReason =
78 !pr || allowed
79 ? null
80 : !permissions.connected
81 ? gt("Reconnect to save changes.")
82 : !canWrite
83 ? gt("This device isn't allowed to change source control on this environment.")
84 : params.field === "comment"
85 ? gt("You can't edit this comment.")
86 : gt(
87 "You can't edit this {term, select, mr {merge request} cr {change request} other {pull request}}.",
88 { term },
89 );
90 const unchanged = draft === null || draft === original;
91 const invalid = params.field === "title" && value.trim().length === 0;
92 const save = async () => {
93 if (!allowed || unchanged || invalid || inFlight.current) return;
94 inFlight.current = true;
95 setBusy(true);
96 setError(null);
97 const result =
98 params.field === "comment"
99 ? await updateComment({
100 ...target,
101 input: {
102 ...target.input,
103 commentId: params.comment.id,
104 kind: params.comment.kind,
105 body: value,
106 },
107 })
108 : await update({
109 ...target,
110 input: {
111 ...target.input,
112 ...(params.field === "title" ? { title: value.trim() } : { body: value }),
113 },
114 });
115 inFlight.current = false;
116 setBusy(false);
117 if (AsyncResult.isFailure(result)) {
118 const cause = squashAtomCommandFailure(result);
119 setError(
120 cause instanceof Error
121 ? (errorDisplayMessage(cause, m) ?? cause.message)
122 : gt("The provider refused the change."),
123 );
124 return;
125 }
126 // updateComment refreshes the activity on its own; a title or body lives on the detail.
127 if (params.field !== "comment") detail.refresh();
128 navigation.goBack();
129 };
130 const title =
131 params.field === "title"
132 ? gt("Edit title")
133 : params.field === "body"
134 ? gt("Edit description")
135 : gt("Edit comment");
136 return (
137 <PullRequestSheetContent
138 busy={busy}
139 title={title}
140 subtitle={`#${params.number} · ${params.repository}`}
141 footer={
142 <Button
143 fullWidth
144 tone="contrast"
145 label={busy ? gt("Saving…") : gt("Save")}
146 loading={busy}
147 disabled={!allowed || unchanged || invalid || original === null}
148 onPress={() => void save()}
149 />
150 }
151 >
152 <PullRequestCompletionSuggestions completions={completions} />
153 <TextInput
154 multiline={params.field !== "title"}
155 selection={completions.selection}
156 onSelectionChange={completions.onSelectionChange}
157 onBlur={completions.onBlur}
158 editable={!busy && original !== null}
159 autoFocus
160 accessibilityLabel={
161 params.field === "title"
162 ? gt(
163 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} title",
164 { term },
165 )
166 : params.field === "body"
167 ? gt(
168 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} description",
169 { term },
170 )
171 : gt("Comment", { $context: "noun, field label" })
172 }
173 placeholder={
174 params.field === "title"
175 ? gt("Title", { $context: "field placeholder" })
176 : gt("Write in Markdown…")
177 }
178 placeholderTextColorClassName="accent-foreground-muted"
179 maxLength={params.field === "title" ? 1024 : 65536}
180 value={value}
181 onChangeText={setDraft}
182 returnKeyType={params.field === "title" ? "done" : undefined}
183 onSubmitEditing={params.field === "title" ? () => void save() : undefined}
184 className={
185 params.field === "title"
186 ? "min-h-12 rounded-[20px] bg-grouped-card px-4 text-base text-foreground"
187 : "min-h-48 rounded-[20px] bg-grouped-card p-4 text-base text-foreground"
188 }
189 style={params.field === "title" ? undefined : { textAlignVertical: "top" }}
190 />
191 {readOnlyReason ? (
192 <Text className="text-xs text-foreground-muted">{readOnlyReason}</Text>
193 ) : null}
194 {error || detail.error ? (
195 <Text selectable className="text-sm text-danger-foreground">
196 {error ?? detail.error}
197 </Text>
198 ) : null}
199 </PullRequestSheetContent>
200 );
201 }