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

ProjectCloneToastCoordinator.tsx

227 lines7.6 KB

1import { useParams } from "@tanstack/react-router";
2import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3import {
4 type AtomCommandResult,
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import {
9 projectCloneDisplayName,
10 projectCloneProgressSummary,
11 type EnvironmentId,
12 type ProjectCloneSnapshot,
13 type ProjectId,
14} from "@t3tools/contracts";
15import { useEffect, useRef } from "react";
16​
17import { useNewThreadHandler } from "../hooks/useHandleNewThread";
18import { useRemoveClonedProject } from "../hooks/useRemoveClonedProject";
19import { useEnvironments } from "../state/environments";
20import {
21 isProjectCloneToastSilenced,
22 silenceProjectCloneToasts,
23 useEnvironmentProjectClones,
24} from "../state/projectClones";
25import { sourceControlEnvironment } from "../state/sourceControl";
26import { useAtomCommand } from "../state/use-atom-command";
27import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
28import { toastManager } from "./ui/toast";
29import { stackedThreadToast } from "./ui/toastHelpers";
30​
31export function ProjectCloneToastCoordinator() {
32 const { environments } = useEnvironments();
33 return environments.map((environment) => (
34 <EnvironmentCloneToasts
35 key={environment.environmentId}
36 environmentId={environment.environmentId}
37 />
38 ));
40​
41interface TrackedToast {
42 readonly toastId: ReturnType<typeof toastManager.add>;
43 readonly renderedKey: string;
44 readonly phase: ProjectCloneSnapshot["phase"];
46​
47function renderKey(clone: ProjectCloneSnapshot): string {
48 return `${clone.phase}:${clone.stage}:${clone.percent ?? ""}:${clone.detail ?? ""}:${clone.stalled === true}:${clone.error ?? ""}`;
50​
51async function runCloneAction(
52 title: string,
53 action: () => Promise<AtomCommandResult<unknown, unknown>>,
54) {
55 const result = await action();
56 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
57 const error = squashAtomCommandFailure(result);
58 toastManager.add(
59 stackedThreadToast({
60 type: "error",
61 title,
62 description: error instanceof Error ? error.message : "An error occurred.",
63 }),
64 );
65 }
67​
68function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentId }) {
69 const clones = useEnvironmentProjectClones(environmentId);
70 const handleNewThread = useNewThreadHandler();
71 const { draftId: routeDraftId } = useParams({ strict: false });
72 const cancelClone = useAtomCommand(sourceControlEnvironment.cancelProjectClone, {
73 reportFailure: false,
74 });
75 const retryClone = useAtomCommand(sourceControlEnvironment.retryProjectClone, {
76 reportFailure: false,
77 });
78 const removeClonedProject = useRemoveClonedProject();
79 const toasts = useRef(new Map<ProjectId, TrackedToast>());
80​
81 const isViewingProjectDraft = (projectId: ProjectId) => {
82 if (!routeDraftId) return false;
83 const draft = useComposerDraftStore.getState().getDraftSession(routeDraftId as DraftId);
84 return draft?.environmentId === environmentId && draft.projectId === projectId;
85 };
86​
87 const openProject = (projectId: ProjectId) => {
88 void handleNewThread(scopeProjectRef(environmentId, projectId));
89 };
90​
91 useEffect(() => {
92 const seen = new Set<ProjectId>();
93 for (const clone of clones) {
94 seen.add(clone.projectId);
95 const key = renderKey(clone);
96 const tracked = toasts.current.get(clone.projectId);
97 const name = projectCloneDisplayName(clone);
98 const closeToast = () => {
99 const current = toasts.current.get(clone.projectId);
100 if (!current) return;
101 toastManager.close(current.toastId);
102 toasts.current.delete(clone.projectId);
103 };
104 const ref = { environmentId, projectId: clone.projectId };
105 if (isViewingProjectDraft(clone.projectId)) {
106 silenceProjectCloneToasts(ref);
107 closeToast();
108 continue;
109 }
110 if (tracked?.renderedKey === key) continue;
111 if (
112 isProjectCloneToastSilenced(ref) &&
113 (clone.phase === "running" || clone.phase === "done")
114 ) {
115 closeToast();
116 continue;
117 }
118​
119 if (clone.phase === "running") {
120 const options = stackedThreadToast({
121 type: "loading",
122 title: `Cloning ${name}`,
123 description: projectCloneProgressSummary(clone),
124 timeout: 0,
125 actionProps: {
126 children: "Cancel",
127 onClick: () => {
128 void runCloneAction("Failed to cancel clone", () =>
129 cancelClone({ environmentId, input: { projectId: clone.projectId } }),
130 );
131 },
132 },
133 data: { hideCopyButton: true },
134 });
135 if (tracked) {
136 toastManager.update(tracked.toastId, options);
137 toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" });
138 } else {
139 const toastId = toastManager.add(options);
140 toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" });
141 }
142 continue;
143 }
144​
145 if (clone.phase === "done") {
146 const options = stackedThreadToast({
147 type: "success",
148 title: `Cloned ${name}`,
149 description: clone.destinationPath,
150 timeout: 8_000,
151 actionProps: {
152 children: "Open project",
153 onClick: () => {
154 closeToast();
155 openProject(clone.projectId);
156 },
157 },
158 data: { hideCopyButton: true },
159 });
160 if (tracked) {
161 toastManager.update(tracked.toastId, options);
162 toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" });
163 } else {
164 const toastId = toastManager.add(options);
165 toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" });
166 }
167 continue;
168 }
169​
170 const cancelled = clone.phase === "cancelled";
171 const options = stackedThreadToast({
172 type: cancelled ? "info" : "error",
173 title: cancelled ? `Cancelled cloning ${name}` : `Failed to clone ${name}`,
174 description: cancelled ? clone.destinationPath : (clone.error ?? "The clone failed."),
175 timeout: 0,
176 actionProps: {
177 children: "Retry",
178 onClick: () => {
179 void runCloneAction("Failed to retry clone", () =>
180 retryClone({ environmentId, input: { projectId: clone.projectId } }),
181 );
182 },
183 },
184 data: {
185 ...(cancelled ? { hideCopyButton: true } : {}),
186 secondaryActionProps: {
187 children: "Remove project",
188 onClick: () => {
189 void removeClonedProject({ environmentId, projectId: clone.projectId });
190 },
191 },
192 },
193 });
194 if (tracked) {
195 toastManager.update(tracked.toastId, options);
196 toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase });
197 } else {
198 const toastId = toastManager.add(options);
199 toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase });
200 }
201 }
202​
203 for (const [projectId, tracked] of toasts.current) {
204 if (seen.has(projectId)) continue;
205 if (tracked.phase !== "done") toastManager.close(tracked.toastId);
206 toasts.current.delete(projectId);
207 }
208 }, [
209 cancelClone,
210 clones,
211 environmentId,
212 isViewingProjectDraft,
213 openProject,
214 removeClonedProject,
215 retryClone,
216 ]);
217​
218 useEffect(
219 () => () => {
220 for (const tracked of toasts.current.values()) toastManager.close(tracked.toastId);
221 toasts.current.clear();
222 },
223 [],
224 );
225​
226 return null;