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

useHandleNewThread.ts

180 lines6.9 KB

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