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

ThreadRouteView.tsx

197 lines7.4 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 resolveThreadRouteRenderState,
23 type ThreadRouteTarget,
24} from "../threadRoutes";
25​
26/**
27 * The single chat surface behind both `/draft/$draftId` and
28 * `/$environmentId/$threadId`. Each draft gets its own ChatView instance (so
29 * a background send's state stays with the draft it came from), and that
30 * instance carries the draft through its promotion to a server thread: the
31 * thread route keeps keying by the draft id while the draft record exists,
32 * so the route swap only changes props and the timeline never paints an
33 * empty frame. Plain server threads are unkeyed, so navigating between them
34 * reuses one instance as ChatView expects.
35 *
36 * Rendered by the `_chat` layout rather than by the two leaf routes, since
37 * an element only survives a route swap when the same parent renders it.
38 */
39export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
40 const navigate = useNavigate();
41 const draftId = target.kind === "draft" ? target.draftId : null;
42 const draftSession = useComposerDraftStore((store) =>
43 draftId === null ? null : store.getDraftSession(draftId),
44 );
45 const threadRefs = useThreadRefs();
46 // The server thread this view is about: the route's own ref, or the draft's
47 // reserved ref once the server knows it.
48 const inferredThreadRef = draftSession
49 ? (threadRefs.find(
50 (ref) =>
51 ref.environmentId === draftSession.environmentId &&
52 ref.threadId === draftSession.threadId,
53 ) ?? null)
54 : null;
55 const serverThreadRef: ScopedThreadRef | null =
56 target.kind === "server" ? target.threadRef : (draftSession?.promotedTo ?? inferredThreadRef);
57 const serverThread = useThreadShell(serverThreadRef);
58 const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(
59 target.kind === "draft" ? serverThreadRef : null,
60 );
61 const canonicalThreadRef =
62 target.kind === "draft"
63 ? resolveDraftPromotionNavigationTarget({
64 serverThreadRef,
65 serverThread,
66 backgroundSubmissionPending,
67 })
68 : null;
69​
70 const shell = useEnvironmentQuery(
71 serverThreadRef === null ? null : environmentShell.stateAtom(serverThreadRef.environmentId),
72 );
73 const serverThreadShell = serverThread;
74 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
75 const bootstrapComplete = shell.data?.snapshot._tag === "Some";
76 const draftThread = useComposerDraftStore((store) =>
77 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
78 );
79 const promotedDraftId = useComposerDraftStore((store) =>
80 target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,
81 );
82 // The draft record is removed once the promoted thread has started, which
83 // is after the route swap. Latch the key so the element that carried the
84 // draft keeps its identity for as long as this thread stays on screen.
85 const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null);
86 const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null;
87 const nextChatViewKey =
88 serverThreadKey === null
89 ? null
90 : chatViewKey?.threadKey === serverThreadKey
91 ? chatViewKey
92 : promotedDraftId
93 ? { threadKey: serverThreadKey, key: promotedDraftId }
94 : null;
95 if (nextChatViewKey !== chatViewKey) {
96 setChatViewKey(nextChatViewKey);
97 }
98 const environmentHasDraftThreads = useComposerDraftStore((store) =>
99 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
100 );
101 const renderState = resolveThreadRouteRenderState({
102 bootstrapComplete,
103 serverThreadExists: serverThreadShell !== null,
104 serverThreadDeleted: serverThreadShell?.deletedAt != null,
105 draftThreadExists: draftThread !== null,
106 });
107 const serverThreadStarted = threadHasStarted(serverThreadShell);
108 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
109​
110 useEffect(() => {
111 if (!inferredThreadRef || draftSession?.promotedTo) {
112 return;
113 }
114 markPromotedDraftThreadByRef(inferredThreadRef);
115 }, [draftSession?.promotedTo, inferredThreadRef]);
116​
117 useEffect(() => {
118 if (!canonicalThreadRef) {
119 return;
120 }
121 let cancelled = false;
122 void waitForDraftHeroTransition().then(() => {
123 if (cancelled) {
124 return;
125 }
126 void navigate({
127 to: "/$environmentId/$threadId",
128 params: buildThreadRouteParams(canonicalThreadRef),
129 replace: true,
130 });
131 });
132 return () => {
133 cancelled = true;
134 };
135 }, [canonicalThreadRef, navigate]);
136​
137 useEffect(() => {
138 if (target.kind !== "draft" || draftSession || canonicalThreadRef) {
139 return;
140 }
141 void navigate({ to: "/", replace: true });
142 }, [canonicalThreadRef, draftSession, navigate, target.kind]);
143​
144 useEffect(() => {
145 if (target.kind !== "server" || !bootstrapComplete) {
146 return;
147 }
148 // Navigation already resolved onto this path, so a drop aimed here
149 // passed its landing check; once the thread reads as missing it can
150 // never be attached, release it even when there is nowhere to redirect.
151 if (renderState === "missing") {
152 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
153 clearPendingFileDropsForThread(target.threadRef);
154 if (environmentHasAnyThreads) {
155 void navigate({ to: "/", replace: true });
156 }
157 }
158 }, [bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
159​
160 useEffect(() => {
161 if (target.kind !== "server" || !serverThreadStarted || !draftThread) {
162 return;
163 }
164 finalizePromotedDraftThreadByRef(target.threadRef);
165 }, [draftThread, serverThreadStarted, target]);
166​
167 let view: React.ReactNode = null;
168 if (target.kind === "draft") {
169 if (draftSession) {
170 view = (
171 <ChatView
172 key={target.draftId}
173 draftId={target.draftId}
174 environmentId={draftSession.environmentId}
175 threadId={draftSession.threadId}
176 routeKind="draft"
177 forceExpandedMobileComposer
178 />
179 );
180 }
181 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
182 view = (
183 <ChatView
184 key={nextChatViewKey?.key}
185 environmentId={target.threadRef.environmentId}
186 threadId={target.threadRef.threadId}
187 routeKind="server"
188 />
189 );
190 }
191​
192 return (
193 <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh">
194 {view}
195 </SidebarInset>
196 );