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

_chat.draft.$draftId.tsx

93 lines2.8 KB

1import { createFileRoute, useNavigate } from "@tanstack/react-router";
2import { useEffect } from "react";
3import ChatView from "../components/ChatView";
4import { resolveDraftPromotionNavigationTarget } from "../components/ChatView.logic";
5import {
6 DraftId,
7 markPromotedDraftThreadByRef,
8 useBackgroundDraftSubmissionPending,
9 useComposerDraftStore,
10} from "../composerDraftStore";
11import { SidebarInset } from "../components/ui/sidebar";
12import { waitForDraftHeroTransition } from "../components/chat/draftHeroTransition";
13import { buildThreadRouteParams } from "../threadRoutes";
14import { useThread, useThreadRefs } from "../state/entities";
15​
16function DraftChatThreadRouteView() {
17 const navigate = useNavigate();
18 const { draftId: rawDraftId } = Route.useParams();
19 const draftId = DraftId.make(rawDraftId);
20 const draftSession = useComposerDraftStore((store) => store.getDraftSession(draftId));
21 const threadRefs = useThreadRefs();
22 const inferredThreadRef = draftSession
23 ? (threadRefs.find(
24 (ref) =>
25 ref.environmentId === draftSession.environmentId &&
26 ref.threadId === draftSession.threadId,
27 ) ?? null)
28 : null;
29 const serverThreadRef = draftSession?.promotedTo ?? inferredThreadRef;
30 const serverThread = useThread(serverThreadRef);
31 const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(serverThreadRef);
32 const canonicalThreadRef = resolveDraftPromotionNavigationTarget({
33 serverThreadRef,
34 serverThread,
35 backgroundSubmissionPending,
36 });
37​
38 useEffect(() => {
39 if (!inferredThreadRef || draftSession?.promotedTo) {
40 return;
41 }
42 markPromotedDraftThreadByRef(inferredThreadRef);
43 }, [draftSession?.promotedTo, inferredThreadRef]);
44​
45 useEffect(() => {
46 if (!canonicalThreadRef) {
47 return;
48 }
49​
50 let cancelled = false;
51 void waitForDraftHeroTransition().then(() => {
52 if (cancelled) {
53 return;
54 }
55 void navigate({
56 to: "/$environmentId/$threadId",
57 params: buildThreadRouteParams(canonicalThreadRef),
58 replace: true,
59 });
60 });
61​
62 return () => {
63 cancelled = true;
64 };
65 }, [canonicalThreadRef, navigate]);
66​
67 useEffect(() => {
68 if (draftSession || canonicalThreadRef) {
69 return;
70 }
71 void navigate({ to: "/", replace: true });
72 }, [canonicalThreadRef, draftSession, navigate]);
73​
74 if (!draftSession) {
75 return null;
76 }
77​
78 return (
79 <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground md:h-dvh">
80 <ChatView
81 draftId={draftId}
82 environmentId={draftSession.environmentId}
83 threadId={draftSession.threadId}
84 routeKind="draft"
85 forceExpandedMobileComposer
86 />
87 </SidebarInset>
88 );
90​
91export const Route = createFileRoute("/_chat/draft/$draftId")({
92 component: DraftChatThreadRouteView,
93});