Open History to see the last commit
1import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime";
2import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef } from "@t3tools/contracts";
3import { useParams, useRouter } from "@tanstack/react-router";
4import { useCallback, useMemo } from "react";
5import { useShallow } from "zustand/react/shallow";
6import {
7 type DraftThreadEnvMode,
8 type DraftThreadState,
9 useComposerDraftStore,
10} from "../composerDraftStore";
11import { newDraftId, newThreadId } from "../lib/utils";
12import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
13import { deriveLogicalProjectKey } from "../logicalProject";
14import { selectProjectsAcrossEnvironments, useStore } from "../store";
15import { createThreadSelectorByRef } from "../storeSelectors";
16import { resolveThreadRouteTarget } from "../threadRoutes";
17import { useUiStateStore } from "../uiStateStore";
18
19export function useHandleNewThread() {
20 const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
21 const projectOrder = useUiStateStore((store) => store.projectOrder);
22 const router = useRouter();
23 const routeTarget = useParams({
24 strict: false,
25 select: (params) => resolveThreadRouteTarget(params),
26 });
27 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
28 const activeThread = useStore(
29 useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]),
30 );
31 const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
32 const activeDraftThread = useComposerDraftStore(() =>
33 routeTarget
34 ? routeTarget.kind === "server"
35 ? getDraftThread(routeTarget.threadRef)
36 : useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
37 : null,
38 );
39 const orderedProjects = useMemo(() => {
40 return orderItemsByPreferredIds({
41 items: projects,
42 preferredIds: projectOrder,
43 getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
44 });
45 }, [projectOrder, projects]);
46 const getCurrentRouteTarget = useCallback(() => {
47 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
48 return resolveThreadRouteTarget(currentRouteParams);
49 }, [router]);
50
51 const handleNewThread = useCallback(
52 (
53 projectRef: ScopedProjectRef,
54 options?: {
55 branch?: string | null;
56 worktreePath?: string | null;
57 envMode?: DraftThreadEnvMode;
58 },
59 ): Promise<void> => {
60 const {
61 getDraftSessionByLogicalProjectKey,
62 getDraftSession,
63 getDraftThread,
64 applyStickyState,
65 setDraftThreadContext,
66 setLogicalProjectDraftThreadId,
67 } = useComposerDraftStore.getState();
68 const currentRouteTarget = getCurrentRouteTarget();
69 const project = projects.find(
70 (candidate) =>
71 candidate.id === projectRef.projectId &&
72 candidate.environmentId === projectRef.environmentId,
73 );
74 const logicalProjectKey = project
75 ? deriveLogicalProjectKey(project)
76 : scopedProjectKey(projectRef);
77 const hasBranchOption = options?.branch !== undefined;
78 const hasWorktreePathOption = options?.worktreePath !== undefined;
79 const hasEnvModeOption = options?.envMode !== undefined;
80 const storedDraftThread = getDraftSessionByLogicalProjectKey(logicalProjectKey);
81 const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
82 ? currentRouteTarget.kind === "server"
83 ? getDraftThread(currentRouteTarget.threadRef)
84 : getDraftSession(currentRouteTarget.draftId)
85 : null;
86 if (storedDraftThread) {
87 return (async () => {
88 if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
89 setDraftThreadContext(storedDraftThread.draftId, {
90 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
91 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
92 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
93 });
94 }
95 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, storedDraftThread.draftId, {
96 threadId: storedDraftThread.threadId,
97 });
98 if (
99 currentRouteTarget?.kind === "draft" &&
100 currentRouteTarget.draftId === storedDraftThread.draftId
101 ) {
102 return;
103 }
104 await router.navigate({
105 to: "/draft/$draftId",
106 params: { draftId: storedDraftThread.draftId },
107 });
108 })();
109 }
110
111 if (
112 latestActiveDraftThread &&
113 currentRouteTarget?.kind === "draft" &&
114 latestActiveDraftThread.logicalProjectKey === logicalProjectKey
115 ) {
116 if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
117 setDraftThreadContext(currentRouteTarget.draftId, {
118 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
119 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
120 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
121 });
122 }
123 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, currentRouteTarget.draftId, {
124 threadId: latestActiveDraftThread.threadId,
125 createdAt: latestActiveDraftThread.createdAt,
126 runtimeMode: latestActiveDraftThread.runtimeMode,
127 interactionMode: latestActiveDraftThread.interactionMode,
128 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
129 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
130 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
131 });
132 return Promise.resolve();
133 }
134
135 const draftId = newDraftId();
136 const threadId = newThreadId();
137 const createdAt = new Date().toISOString();
138 return (async () => {
139 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
140 threadId,
141 createdAt,
142 branch: options?.branch ?? null,
143 worktreePath: options?.worktreePath ?? null,
144 envMode: options?.envMode ?? "local",
145 runtimeMode: DEFAULT_RUNTIME_MODE,
146 });
147 applyStickyState(draftId);
148
149 await router.navigate({
150 to: "/draft/$draftId",
151 params: { draftId },
152 });
153 })();
154 },
155 [getCurrentRouteTarget, router, projects],
156 );
157
158 return {
159 activeDraftThread,
160 activeThread,
161 defaultProjectRef: orderedProjects[0]
162 ? scopeProjectRef(orderedProjects[0].environmentId, orderedProjects[0].id)
163 : null,
164 handleNewThread,
165 routeThreadRef,
166 };
167}