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

use-vcs-action-state.ts

177 lines5.5 KB

1import { useAtomValue } from "@effect/atom-react";
2import { secondTick } from "@t3tools/client-runtime/clock";
3import {
4 vcsActionLabelText,
5 type VcsActionState,
6 type VcsActionTarget,
7} from "@t3tools/client-runtime/state/vcs";
8import type { ScopedThreadRef } from "@t3tools/contracts";
9import { Atom } from "effect/reactivity";
10import * as Haptics from "expo-haptics";
11import { msg, useMessages } from "gt-react-native";
12import { useSyncExternalStore } from "react";
13​
14import type { MessageResolver } from "../i18n/messages";
15import { appAtomRegistry } from "./atom-registry";
16import { vcsActionManager } from "./vcs";
17​
18export function useVcsActionState(target: VcsActionTarget): VcsActionState {
19 return useAtomValue(vcsActionManager.stateAtom(target));
21​
22interface RepositoryGitAction {
23 readonly threadRef: ScopedThreadRef;
24 readonly cwd: string;
26​
27// The tracked repository a thread last ran an action in, so the thread can show its progress.
28const repositoryGitActionAtom = Atom.make<RepositoryGitAction | null>(null).pipe(
29 Atom.keepAlive,
30 Atom.withLabel("mobile:repository-git-action"),
31);
32​
33export function noteRepositoryGitAction(action: RepositoryGitAction): void {
34 appAtomRegistry.set(repositoryGitActionAtom, action);
36​
37export interface GitActionResultNotification {
38 readonly type: "success" | "error";
39 readonly title: string;
40 readonly description?: string;
41 readonly prUrl?: string;
43​
44const RESULT_DISMISS_MS = 5_000;
45​
46interface PendingGitActionResult {
47 readonly notification: GitActionResultNotification;
48 readonly timer: ReturnType<typeof setTimeout>;
50​
51const gitActionResultsAtom = Atom.make<ReadonlyMap<string, PendingGitActionResult>>(new Map()).pipe(
52 Atom.keepAlive,
53 Atom.withLabel("mobile:git-action-results"),
54);
55​
56function gitActionResultKey({ environmentId, threadId }: ScopedThreadRef): string {
57 return JSON.stringify([environmentId, threadId]);
59​
60export function showGitActionResult({
61 threadRef,
62 ...notification
63}: GitActionResultNotification & { readonly threadRef: ScopedThreadRef }): void {
64 // Best effort: devices without a haptics engine reject.
65 Haptics.notificationAsync(
66 notification.type === "success"
67 ? Haptics.NotificationFeedbackType.Success
68 : Haptics.NotificationFeedbackType.Error,
69 ).catch(() => undefined);
70 const key = gitActionResultKey(threadRef);
71 const results = new Map(appAtomRegistry.get(gitActionResultsAtom));
72 const previous = results.get(key);
73 if (previous !== undefined) clearTimeout(previous.timer);
74 results.set(key, {
75 notification,
76 timer: setTimeout(() => dismissGitActionResult(threadRef), RESULT_DISMISS_MS),
77 });
78 appAtomRegistry.set(gitActionResultsAtom, results);
80​
81export function dismissGitActionResult(threadRef: ScopedThreadRef | null): void {
82 if (threadRef === null) return;
83 const key = gitActionResultKey(threadRef);
84 const results = appAtomRegistry.get(gitActionResultsAtom);
85 const entry = results.get(key);
86 if (entry === undefined) return;
87 clearTimeout(entry.timer);
88 const next = new Map(results);
89 next.delete(key);
90 appAtomRegistry.set(gitActionResultsAtom, next);
92​
93export type GitActionProgressPhase = "idle" | "running" | "success" | "error";
94​
95export interface GitActionProgress {
96 readonly phase: GitActionProgressPhase;
97 readonly label: string | null;
98 readonly description: string | null;
99 readonly prUrl?: string;
101​
102const subscribeNever = () => () => {};
103​
104const EMPTY_PROGRESS: GitActionProgress = {
105 phase: "idle",
106 label: null,
107 description: null,
108};
109​
110function formatElapsedSeconds(
111 ms: number | null,
112 nowMs: number,
113 resolve: MessageResolver,
114): string | null {
115 if (ms === null) return null;
116 const elapsed = Math.max(0, Math.floor((nowMs - ms) / 1000));
117 if (elapsed < 2) return null;
118 return resolve(msg("Running for {elapsed}s", { elapsed: String(elapsed) }));
120​
121/** Checkout progress and the selected thread's own Git result. */
122export function useGitActionProgress(
123 target: VcsActionTarget,
124 threadRef: ScopedThreadRef | null,
125): GitActionProgress {
126 const threadFolderState = useVcsActionState(target);
127 const repositoryCwd = useAtomValue(repositoryGitActionAtom, (action) =>
128 action !== null &&
129 threadRef !== null &&
130 action.threadRef.environmentId === threadRef.environmentId &&
131 action.threadRef.threadId === threadRef.threadId
132 ? action.cwd
133 : null,
134 );
135 const repositoryState = useVcsActionState({
136 environmentId: threadRef?.environmentId ?? null,
137 cwd: repositoryCwd,
138 });
139 const actionState = repositoryState.isRunning ? repositoryState : threadFolderState;
140 const resultKey = threadRef === null ? null : gitActionResultKey(threadRef);
141 const result = useAtomValue(gitActionResultsAtom, (results) =>
142 resultKey === null ? undefined : results.get(resultKey)?.notification,
143 );
144 const resolve = useMessages();
145​
146 // Only a running action shows elapsed time, so only it subscribes to the second tick.
147 const nowMs = useSyncExternalStore(
148 actionState.isRunning ? secondTick.subscribe : subscribeNever,
149 secondTick.getSnapshot,
150 );
151​
152 if (actionState.isRunning) {
153 const description =
154 actionState.lastOutputLine ??
155 formatElapsedSeconds(
156 actionState.hookStartedAtMs ?? actionState.phaseStartedAtMs,
157 nowMs,
158 resolve,
159 );
160 return {
161 phase: "running",
162 label: vcsActionLabelText(actionState, resolve),
163 description,
164 };
165 }
166​
167 if (result) {
168 return {
169 phase: result.type,
170 label: result.title,
171 description: result.description ?? null,
172 prUrl: result.prUrl,
173 };
174 }
175​
176 return EMPTY_PROGRESS;