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

_chat.draft.$draftId.tsx

88 lines2.7 KB

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