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

useHandleNewThread.ts

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