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

ThreadRouteView.tsx

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