Open History to see the last commit
1import { useAtomSet, useAtomValue } from "@effect/atom-react";
2import { Atom } from "effect/reactivity";
3import { FitSheet } from "../../../components/ui/FitSheet";
4import { SheetHeader } from "../../../components/ui/SheetHeader";
5import { Button } from "../../../components/ui/Button";
6import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
7import { T, useGT, Var } from "gt-react-native";
8import { useState } from "react";
9import { Pressable, View } from "react-native";
10import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
11
12import { SymbolView } from "../../../components/ui/AppSymbol";
13import { AppText as Text, AppTextInput as TextInput } from "../../../components/ui/AppText";
14import { cn } from "../../../lib/cn";
15import { useEnvironmentQuery } from "../../../state/query";
16import {
17 gitRepositoryTargetFromRoute,
18 type GitRepositoryRouteParams,
19} from "../../../state/thread-git-target";
20import { useThreadSelection } from "../../../state/use-thread-selection";
21import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
22import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
23import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
24import { vcsEnvironment } from "../../../state/vcs";
25
26type GitCommitSheetProps = StaticScreenProps<
27 {
28 readonly environmentId: string;
29 readonly threadId: string;
30 } & GitRepositoryRouteParams
31>;
32
33// The sheet unmounts on submit, but a reopened sheet needs to observe the action settling.
34const retainedCommitDraftAtom = Atom.make<
35 ReadonlyMap<
36 string,
37 {
38 readonly refName: string | null;
39 readonly excluded: ReadonlySet<string>;
40 readonly commitMessage: string;
41 readonly createdBranch: string | null | undefined;
42 }
43 >
44>(new Map()).pipe(Atom.keepAlive);
45
46export function GitCommitSheet(props: GitCommitSheetProps) {
47 const repository = gitRepositoryTargetFromRoute(props.route.params);
48 const gt = useGT();
49 const navigation = useNavigation();
50 const { selectedThread } = useThreadSelection();
51 const threadWorktree = useSelectedThreadWorktree();
52 const selectedThreadCwd = repository?.cwd ?? threadWorktree.selectedThreadCwd;
53 const gitState = useSelectedThreadGitState(repository);
54 const gitActions = useSelectedThreadGitActions(repository);
55 const { canWriteSourceControl, canCreateFeatureBranch } = gitActions;
56
57 const gitStatus = useEnvironmentQuery(
58 selectedThread !== null && selectedThreadCwd !== null
59 ? vcsEnvironment.status({
60 environmentId: selectedThread.environmentId,
61 input: { cwd: selectedThreadCwd },
62 })
63 : null,
64 );
65
66 const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
67 const allFiles = gitStatus.data?.workingTree?.files ?? [];
68
69 const selectionKey =
70 selectedThread !== null && selectedThreadCwd !== null
71 ? `${selectedThread.environmentId}\u0000${selectedThreadCwd}`
72 : null;
73 const retained = useAtomValue(retainedCommitDraftAtom, (entries) =>
74 selectionKey === null ? undefined : entries.get(selectionKey),
75 );
76 const setRetainedCommitDraft = useAtomSet(retainedCommitDraftAtom);
77 const [dialogCommitMessage, setDialogCommitMessage] = useState(retained?.commitMessage ?? "");
78 const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(
79 retained?.excluded ?? new Set(),
80 );
81 const [previousRetained, setPreviousRetained] = useState(retained);
82 if (previousRetained !== retained) {
83 setPreviousRetained(retained);
84 if (retained === undefined) {
85 if (previousRetained?.excluded === excludedFiles) {
86 setExcludedFiles(new Set());
87 }
88 if (previousRetained?.commitMessage === dialogCommitMessage) {
89 setDialogCommitMessage("");
90 }
91 }
92 }
93 const [selectionBranch, setSelectionBranch] = useState(
94 retained !== undefined ? retained.refName : (gitStatus.data?.refName ?? null),
95 );
96 const [consumedTransfer, setConsumedTransfer] = useState<typeof retained>();
97 const createdBranch =
98 retained !== consumedTransfer && retained?.refName === selectionBranch
99 ? retained.createdBranch
100 : undefined;
101 const busy = gitState.gitOperationLabel !== null || createdBranch === null;
102 if (gitStatus.data && selectionBranch !== gitStatus.data.refName && createdBranch !== null) {
103 setSelectionBranch(gitStatus.data.refName);
104 setConsumedTransfer(retained);
105 if (createdBranch !== gitStatus.data.refName) {
106 setExcludedFiles(new Set());
107 }
108 }
109
110 const selectedFiles = allFiles.filter((file) => !excludedFiles.has(file.path));
111 const allSelected = selectedFiles.length === allFiles.length;
112 const noneSelected = selectedFiles.length === 0;
113 const selectedInsertions = selectedFiles.reduce((sum, file) => sum + file.insertions, 0);
114 const selectedDeletions = selectedFiles.reduce((sum, file) => sum + file.deletions, 0);
115
116 const runCommitAction = async (featureBranch: boolean) => {
117 if (!canWriteSourceControl || (featureBranch && !canCreateFeatureBranch)) return;
118 const commitMessage = dialogCommitMessage.trim();
119 const submitted = {
120 refName: selectionBranch,
121 excluded: excludedFiles,
122 commitMessage: dialogCommitMessage,
123 createdBranch: featureBranch ? null : createdBranch,
124 };
125 if (selectionKey !== null) {
126 setRetainedCommitDraft((entries) => new Map(entries).set(selectionKey, submitted));
127 }
128 navigation.goBack();
129 let checkedOutBranch: string | undefined;
130 const result = await gitActions.onRunSelectedThreadGitAction({
131 action: "commit",
132 featureBranch,
133 ...(commitMessage ? { commitMessage } : {}),
134 ...(excludedFiles.size > 0 ? { filePaths: selectedFiles.map((file) => file.path) } : {}),
135 onProgress: (event) => {
136 if (event.kind === "action_failed") checkedOutBranch = event.createdBranch;
137 },
138 });
139 if (selectionKey !== null) {
140 setRetainedCommitDraft((entries) => {
141 if (entries.get(selectionKey) !== submitted) return entries;
142 const next = new Map(entries);
143 if (result?.commit.status === "created") {
144 next.delete(selectionKey);
145 } else {
146 next.set(selectionKey, {
147 ...submitted,
148 createdBranch: checkedOutBranch ?? createdBranch,
149 });
150 }
151 return next;
152 });
153 }
154 };
155
156 return (
157 <FitSheet
158 header={
159 <SheetHeader
160 title={gt`Commit changes`}
161 subtitle={[repository?.name, gitStatus.data?.refName ?? gt`(detached HEAD)`]
162 .filter(Boolean)
163 .join(" · ")}
164 onCancel={() => navigation.goBack()}
165 accessibilityLabel={gt`Cancel commit`}
166 />
167 }
168 keyboardShouldPersistTaps="handled"
169 keyboardDismissMode="on-drag"
170 automaticallyAdjustKeyboardInsets
171 contentContainerClassName="px-5 pt-4 gap-5"
172 >
173 {isDefaultRef ? (
174 <Text className="text-sm text-warning-foreground">
175 <T>You’re on the default branch. You can create a new branch when committing.</T>
176 </Text>
177 ) : null}
178 <View className="gap-2">
179 <Text className="text-sm font-t3-medium text-foreground">
180 <T>Commit message</T>
181 </Text>
182 <TextInput
183 multiline
184 accessibilityLabel={gt`Commit message`}
185 value={dialogCommitMessage}
186 onChangeText={setDialogCommitMessage}
187 placeholder={gt`Describe your changes…`}
188 textAlignVertical="top"
189 className="min-h-24 rounded-xl bg-subtle px-4 py-3 text-base"
190 />
191 <Text className="text-xs text-foreground-muted">
192 <T>Leave empty to generate a message automatically.</T>
193 </Text>
194 </View>
195 <View>
196 <View className="flex-row items-center justify-between gap-2 pb-2">
197 <View className="flex-1 gap-1">
198 <Text className="text-base font-t3-bold text-foreground">
199 <T>Changed files</T>
200 </Text>
201 <Text className="text-xs text-foreground-muted">
202 <T>
203 <Var>{selectedFiles.length}</Var> of <Var>{allFiles.length}</Var> selected · +
204 <Var>{formatDiffCount(selectedInsertions)}</Var> −
205 <Var>{formatDiffCount(selectedDeletions)}</Var>
206 </T>
207 </Text>
208 </View>
209 {allFiles.length > 0 ? (
210 <Button
211 label={
212 allSelected
213 ? gt`Deselect all`
214 : gt({ context: "selects every changed file to commit" })`Select all`
215 }
216 tone="text"
217 onPress={() =>
218 setExcludedFiles(
219 allSelected
220 ? new Set([...excludedFiles, ...allFiles.map((file) => file.path)])
221 : new Set(),
222 )
223 }
224 />
225 ) : null}
226 </View>
227 {allFiles.length === 0 ? (
228 <Text className="py-4 text-sm text-foreground-muted">
229 <T>No changed files to commit.</T>
230 </Text>
231 ) : (
232 allFiles.map((file) => {
233 const included = !excludedFiles.has(file.path);
234 const slash = file.path.lastIndexOf("/");
235 const name = file.path.slice(slash + 1);
236 const directory = slash >= 0 ? file.path.slice(0, slash) : null;
237 return (
238 <Pressable
239 key={file.path}
240 className="min-h-16 flex-row items-center gap-3 border-t border-border-subtle py-3"
241 accessibilityRole="checkbox"
242 accessibilityLabel={file.path}
243 accessibilityState={{ checked: included }}
244 onPress={() =>
245 setExcludedFiles((current) => {
246 const next = new Set(current);
247 if (next.has(file.path)) next.delete(file.path);
248 else next.add(file.path);
249 return next;
250 })
251 }
252 >
253 <View
254 className={cn(
255 "size-5 items-center justify-center rounded-full",
256 included ? "bg-primary" : "border border-input-border",
257 )}
258 >
259 {included ? (
260 <SymbolView
261 name="checkmark"
262 size={13}
263 tintColorClassName="accent-primary-foreground"
264 />
265 ) : null}
266 </View>
267 <View className="flex-1 gap-1">
268 <Text
269 numberOfLines={1}
270 ellipsizeMode="middle"
271 className="text-sm font-t3-medium text-foreground"
272 >
273 {name}
274 </Text>
275 {directory ? (
276 <Text
277 numberOfLines={1}
278 ellipsizeMode="middle"
279 className="text-xs text-foreground-muted"
280 >
281 {directory}
282 </Text>
283 ) : null}
284 </View>
285 <View className="flex-row gap-2">
286 <Text className="text-xs text-adaptive-emerald-700-300">
287 +{formatDiffCount(file.insertions)}
288 </Text>
289 <Text className="text-xs text-adaptive-rose-700-300">
290 −{formatDiffCount(file.deletions)}
291 </Text>
292 </View>
293 </Pressable>
294 );
295 })
296 )}
297 </View>
298 <View className="gap-2">
299 <Button
300 label={gt`Commit changes`}
301 icon="checkmark"
302 tone="primary"
303 fullWidth
304 disabled={!canWriteSourceControl || noneSelected || busy}
305 onPress={() => void runCommitAction(false)}
306 />
307 <Button
308 label={gt`Commit on a new branch`}
309 icon="arrow.branch"
310 tone="text"
311 fullWidth
312 disabled={!canWriteSourceControl || !canCreateFeatureBranch || noneSelected || busy}
313 onPress={() => void runCommitAction(true)}
314 />
315 </View>
316 </FitSheet>
317 );
318}