Open History to see the last commit
1import { useRouter } from "@tanstack/react-router";
2import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import type { ScopedProjectRef } from "@t3tools/contracts";
4import { useCallback } from "react";
5
6import { useComposerDraftStore } from "../composerDraftStore";
7import { resolveThreadRouteTarget } from "../threadRoutes";
8import { releaseProjectDraftUploads } from "../lib/composerDraftUploads";
9import { projectEnvironment } from "../state/projects";
10import { useAtomCommand } from "../state/use-atom-command";
11import { stackedThreadToast, toastManager } from "../components/ui/toast";
12
13/**
14 * Removes a project whose clone never landed. The server clears the empty
15 * folder along with the clone, so there is nothing to confirm: no threads
16 * exist yet and the draft is the only thing lost, which the user is looking
17 * at when they click.
18 */
19export function useRemoveClonedProject() {
20 const router = useRouter();
21 const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
22
23 return useCallback(
24 async (projectRef: ScopedProjectRef) => {
25 const draftStore = useComposerDraftStore.getState();
26 const result = await deleteProject({
27 environmentId: projectRef.environmentId,
28 // Not forced: a project whose clone never landed has no threads, and
29 // if one appeared in the meantime the server refuses rather than
30 // silently deleting it.
31 input: { projectId: projectRef.projectId },
32 });
33 if (result._tag === "Failure") {
34 const error = squashAtomCommandFailure(result);
35 toastManager.add(
36 stackedThreadToast({
37 type: "error",
38 title: "Failed to remove project",
39 description: error instanceof Error ? error.message : "An error occurred.",
40 }),
41 );
42 return false;
43 }
44 // Read the route after the await: the user may have moved on while the
45 // delete was in flight, and only a draft of this project needs to go.
46 const routeParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
47 const routeTarget = resolveThreadRouteTarget(routeParams);
48 const viewingDraft =
49 routeTarget?.kind === "draft" ? draftStore.getDraftSession(routeTarget.draftId) : null;
50 const viewingThisProject =
51 viewingDraft?.environmentId === projectRef.environmentId &&
52 viewingDraft.projectId === projectRef.projectId;
53 releaseProjectDraftUploads(projectRef);
54 const projectDraft = draftStore.getDraftThreadByProjectRef(projectRef);
55 if (projectDraft) draftStore.clearDraftThread(projectDraft.draftId);
56 draftStore.clearProjectDraftThreadId(projectRef);
57 if (viewingThisProject) void router.navigate({ to: "/", replace: true });
58 return true;
59 },
60 [deleteProject, router],
61 );
62}