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

useHandleNewThread.ts

181 lines7.0 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 latestActiveDraftThread.promotedTo == null
92 ) {
93 if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
94 setDraftThreadContext(currentRouteTarget.draftId, {
95 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
96 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
97 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
98 });
99 }
100 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, currentRouteTarget.draftId, {
101 threadId: latestActiveDraftThread.threadId,
102 createdAt: latestActiveDraftThread.createdAt,
103 runtimeMode: latestActiveDraftThread.runtimeMode,
104 interactionMode: latestActiveDraftThread.interactionMode,
105 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
106 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
107 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
108 });
109 return Promise.resolve();
110 }
111​
112 const draftId = newDraftId();
113 const threadId = newThreadId();
114 const createdAt = new Date().toISOString();
115 return (async () => {
116 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
117 threadId,
118 createdAt,
119 branch: options?.branch ?? null,
120 worktreePath: options?.worktreePath ?? null,
121 envMode: options?.envMode ?? "local",
122 runtimeMode: DEFAULT_RUNTIME_MODE,
123 });
124 applyStickyState(draftId);
125​
126 await router.navigate({
127 to: "/draft/$draftId",
128 params: { draftId },
129 });
130 })();
131 },
132 [getCurrentRouteTarget, router, projects],
133 );
135​
136export function useNewThreadHandler() {
137 const handleNewThread = useNewThreadState();
138​
139 return {
140 handleNewThread,
141 };
143​
144export function useHandleNewThread() {
145 const projectOrder = useUiStateStore((store) => store.projectOrder);
146 const routeTarget = useParams({
147 strict: false,
148 select: (params) => resolveThreadRouteTarget(params),
149 });
150 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
151 const activeThread = useStore(
152 useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]),
153 );
154 const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
155 const activeDraftThread = useComposerDraftStore(() =>
156 routeTarget
157 ? routeTarget.kind === "server"
158 ? getDraftThread(routeTarget.threadRef)
159 : useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
160 : null,
161 );
162 const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
163 const orderedProjects = useMemo(() => {
164 return orderItemsByPreferredIds({
165 items: projects,
166 preferredIds: projectOrder,
167 getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
168 });
169 }, [projectOrder, projects]);
170 const handleNewThread = useNewThreadState();
171​
172 return {
173 activeDraftThread,
174 activeThread,
175 defaultProjectRef: orderedProjects[0]
176 ? scopeProjectRef(orderedProjects[0].environmentId, orderedProjects[0].id)
177 : null,
178 handleNewThread,
179 routeThreadRef,
180 };