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

ThreadRouteView.tsx

183 lines6.6 KB

1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import type { ScopedThreadRef } from "@t3tools/contracts";
3import { useNavigate } from "@tanstack/react-router";
4import { useEffect, useState } from "react";
5​
6import ChatView from "./ChatView";
7import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic";
8import { waitForDraftHeroTransition } from "./chat/draftHeroTransition";
9import { SidebarInset } from "./ui/sidebar";
10import {
11 finalizePromotedDraftThreadByRef,
12 markPromotedDraftThreadByRef,
13 useBackgroundDraftSubmissionPending,
14 useComposerDraftStore,
15} from "../composerDraftStore";
16import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
17import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities";
18import { useEnvironmentShellStatus } from "../state/shell";
19import {
20 buildThreadRouteParams,
21 isThreadRouteSnapshotAuthoritative,
22 resolveThreadRouteRenderState,
23 type ThreadRouteTarget,
24} from "../threadRoutes";
25​
26/**
27 * Plain server threads are unkeyed, so navigating between them reuses one instance as ChatView
28 * expects. Rendered by the `_chat` layout rather than by the two leaf routes, since an element
29 * only survives a route swap when the same parent renders it.
30 */
31export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
32 const navigate = useNavigate();
33 const draftId = target.kind === "draft" ? target.draftId : null;
34 const draftSession = useComposerDraftStore((store) =>
35 draftId === null ? null : store.getDraftSession(draftId),
36 );
37 const threadRefs = useThreadRefs();
38 // Promotion can begin before the server creates the reserved thread.
39 const inferredThreadRef = draftSession
40 ? (threadRefs.find(
41 (ref) =>
42 ref.environmentId === draftSession.environmentId &&
43 ref.threadId === draftSession.threadId,
44 ) ?? null)
45 : null;
46 const serverThreadRef: ScopedThreadRef | null =
47 target.kind === "server" ? target.threadRef : inferredThreadRef;
48 const serverThread = useQuietThreadShell(serverThreadRef);
49 const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(
50 target.kind === "draft" ? serverThreadRef : null,
51 );
52 const canonicalThreadRef =
53 target.kind === "draft"
54 ? resolveDraftPromotionNavigationTarget({
55 serverThreadRef,
56 serverThread,
57 backgroundSubmissionPending,
58 })
59 : null;
60​
61 const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
62 const serverThreadShell = serverThread;
63 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
64 const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
65 const draftThread = useComposerDraftStore((store) =>
66 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
67 );
68 const promotedDraftId = useComposerDraftStore((store) =>
69 target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,
70 );
71 // The draft record is removed once the promoted thread has started, which
72 // is after the route swap. Latch the key so the element that carried the
73 // draft keeps its identity for as long as this thread stays on screen.
74 const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null);
75 const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null;
76 const nextChatViewKey =
77 serverThreadKey === null
78 ? null
79 : chatViewKey?.threadKey === serverThreadKey
80 ? chatViewKey
81 : promotedDraftId
82 ? { threadKey: serverThreadKey, key: promotedDraftId }
83 : null;
84 if (nextChatViewKey !== chatViewKey) {
85 setChatViewKey(nextChatViewKey);
86 }
87 const environmentHasDraftThreads = useComposerDraftStore((store) =>
88 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
89 );
90 const renderState = resolveThreadRouteRenderState({
91 bootstrapComplete,
92 serverThreadExists: serverThreadShell !== null,
93 serverThreadDeleted: serverThreadShell?.deletedAt != null,
94 draftThreadExists: draftThread !== null,
95 });
96 const serverThreadStarted = threadHasStarted(serverThreadShell);
97 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
98​
99 useEffect(() => {
100 if (!inferredThreadRef || draftSession?.promotedTo) {
101 return;
102 }
103 markPromotedDraftThreadByRef(inferredThreadRef);
104 }, [draftSession?.promotedTo, inferredThreadRef]);
105​
106 useEffect(() => {
107 if (!canonicalThreadRef) {
108 return;
109 }
110 let cancelled = false;
111 void waitForDraftHeroTransition().then(() => {
112 if (cancelled) {
113 return;
114 }
115 void navigate({
116 to: "/$environmentId/$threadId",
117 params: buildThreadRouteParams(canonicalThreadRef),
118 replace: true,
119 });
120 });
121 return () => {
122 cancelled = true;
123 };
124 }, [canonicalThreadRef, navigate]);
125​
126 useEffect(() => {
127 if (target.kind !== "draft" || draftSession || canonicalThreadRef) {
128 return;
129 }
130 void navigate({ to: "/", replace: true });
131 }, [canonicalThreadRef, draftSession, navigate, target.kind]);
132​
133 useEffect(() => {
134 if (target.kind !== "server" || !bootstrapComplete) {
135 return;
136 }
137 if (renderState === "missing") {
138 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
139 clearPendingFileDropsForThread(target.threadRef);
140 if (environmentHasAnyThreads) {
141 void navigate({ to: "/", replace: true });
142 }
143 }
144 }, [bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
145​
146 useEffect(() => {
147 if (target.kind !== "server" || !serverThreadStarted || !draftThread) {
148 return;
149 }
150 finalizePromotedDraftThreadByRef(target.threadRef);
151 }, [draftThread, serverThreadStarted, target]);
152​
153 let view: React.ReactNode = null;
154 if (target.kind === "draft") {
155 if (draftSession) {
156 view = (
157 <ChatView
158 key={target.draftId}
159 draftId={target.draftId}
160 environmentId={draftSession.environmentId}
161 threadId={draftSession.threadId}
162 routeKind="draft"
163 forceExpandedMobileComposer
164 />
165 );
166 }
167 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
168 view = (
169 <ChatView
170 key={nextChatViewKey?.key}
171 environmentId={target.threadRef.environmentId}
172 threadId={target.threadRef.threadId}
173 routeKind="server"
174 />
175 );
176 }
177​
178 return (
179 <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh">
180 {view}
181 </SidebarInset>
182 );