Open History to see the last commit
1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
3import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4import { changeRequestTermKind } from "../../lib/changeRequestTerm";
5import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6import { useAtomValue } from "@effect/atom-react";
7import type { PullRequestComment } from "@t3tools/contracts";
8import { AsyncResult } from "effect/reactivity";
9import { useGT, select } from "gt-react-native";
10import { useRef, useState } from "react";
11import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
12import { Button } from "../../components/ui/Button";
13import { composerPullRequests } from "../../state/pull-requests";
14import { useEnvironmentQuery } from "../../state/query";
15import { useAtomCommand } from "../../state/use-atom-command";
16import { PullRequestSheetContent } from "./PullRequestSheetContent";
17import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
18import { usePullRequestPermissions } from "./usePullRequestPermissions";
19import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";
20import { usePullRequestCompletions } from "./usePullRequestCompletions";
21import { m } from "../../i18n/messages";
22
23export 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
35export 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`You can't edit this ${select(
87 { term },
88 {
89 mr: "merge request",
90 cr: "change request",
91 other: "pull request",
92 },
93 )}.`;
94 const unchanged = draft === null || draft === original;
95 const invalid = params.field === "title" && value.trim().length === 0;
96 const save = async () => {
97 if (!allowed || unchanged || invalid || inFlight.current) return;
98 inFlight.current = true;
99 setBusy(true);
100 setError(null);
101 const result =
102 params.field === "comment"
103 ? await updateComment({
104 ...target,
105 input: {
106 ...target.input,
107 commentId: params.comment.id,
108 kind: params.comment.kind,
109 body: value,
110 },
111 })
112 : await update({
113 ...target,
114 input: {
115 ...target.input,
116 ...(params.field === "title" ? { title: value.trim() } : { body: value }),
117 },
118 });
119 inFlight.current = false;
120 setBusy(false);
121 if (AsyncResult.isFailure(result)) {
122 const cause = squashAtomCommandFailure(result);
123 setError(
124 cause instanceof Error
125 ? (errorDisplayMessage(cause, m) ?? cause.message)
126 : gt`The provider refused the change.`,
127 );
128 return;
129 }
130 // updateComment refreshes the activity on its own; a title or body lives on the detail.
131 if (params.field !== "comment") detail.refresh();
132 if (navigation.isFocused()) navigation.goBack();
133 };
134 const title =
135 params.field === "title"
136 ? gt`Edit title`
137 : params.field === "body"
138 ? gt`Edit description`
139 : gt`Edit comment`;
140 return (
141 <PullRequestSheetContent
142 busy={busy}
143 title={title}
144 subtitle={`#${params.number} · ${params.repository}`}
145 footer={
146 <Button
147 fullWidth
148 tone="contrast"
149 label={busy ? gt`Saving…` : gt`Save`}
150 loading={busy}
151 disabled={!allowed || unchanged || invalid || original === null}
152 onPress={() => void save()}
153 />
154 }
155 >
156 <PullRequestCompletionSuggestions completions={completions} />
157 <TextInput
158 multiline={params.field !== "title"}
159 selection={completions.selection}
160 onSelectionChange={completions.onSelectionChange}
161 onBlur={completions.onBlur}
162 editable={!busy && original !== null}
163 autoFocus
164 accessibilityLabel={
165 params.field === "title"
166 ? gt`${select(
167 { term },
168 {
169 mr: "Merge request",
170 cr: "Change request",
171 other: "Pull request",
172 },
173 )} title`
174 : params.field === "body"
175 ? gt`${select(
176 { term },
177 {
178 mr: "Merge request",
179 cr: "Change request",
180 other: "Pull request",
181 },
182 )} description`
183 : gt({ context: "noun, field label" })`Comment`
184 }
185 placeholder={
186 params.field === "title"
187 ? gt({ context: "field placeholder" })`Title`
188 : gt`Write in Markdown…`
189 }
190 placeholderTextColorClassName="accent-foreground-muted"
191 maxLength={params.field === "title" ? 1024 : 65536}
192 value={value}
193 onChangeText={setDraft}
194 returnKeyType={params.field === "title" ? "done" : undefined}
195 onSubmitEditing={params.field === "title" ? () => void save() : undefined}
196 className={
197 params.field === "title"
198 ? "min-h-12 rounded-[20px] bg-grouped-card px-4 text-base text-foreground"
199 : "min-h-48 rounded-[20px] bg-grouped-card p-4 text-base text-foreground"
200 }
201 style={params.field === "title" ? undefined : { textAlignVertical: "top" }}
202 />
203 {readOnlyReason ? (
204 <Text className="text-xs text-foreground-muted">{readOnlyReason}</Text>
205 ) : null}
206 {error || detail.error ? (
207 <Text selectable className="text-sm text-danger-foreground">
208 {error ?? detail.error}
209 </Text>
210 ) : null}
211 </PullRequestSheetContent>
212 );
213}