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

PullRequestEditScreen.tsx

169 lines6.4 KB

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