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

chatRouteCommands.ts

180 lines7.4 KB

1import { AuthPreviewOperateScope, type EnvironmentId } from "@t3tools/contracts";
2import type { AnyRouter } from "@tanstack/react-router";
3​
4import { stackedThreadToast, toastManager } from "~/components/ui/toast";
5import { isPreviewAvailableFor } from "../browser/previewRuntime";
6import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
7import { useComposerDraftStore } from "../composerDraftStore";
8import { dispatchPreviewAction, type PreviewAction } from "../components/preview/previewActionBus";
9import { isAppModalPage } from "../components/sidebar/mainAppLocation";
10import { createNewThreadHandler, resolveDefaultProjectRef } from "../hooks/useHandleNewThread";
11import { createScratchProjectActions } from "../hooks/useScratchProject";
12import { getClientSettings } from "../hooks/useSettings";
13import { startNewThreadFromContext } from "../lib/chatThreadActions";
14import { selectProjectGroupingSettings } from "@t3tools/client-runtime/state/project-grouping";
15import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
16import { appAtomRegistry } from "../rpc/atomRegistry";
17import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
18import { readProjects, readThreadShell } from "../state/entities";
19import { environmentPresentations } from "../state/presentation";
20import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";
21import { readEnvironmentScope } from "../state/session";
22import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
23import { useThreadSelectionStore } from "../threadSelectionStore";
24import { resolveThreadRouteTarget } from "../threadRoutes";
25import { useUiStateStore } from "../uiStateStore";
26import { type CommandHandler, registerCommands } from "./dispatcher";
27​
28const CHAT_ROUTE_ID = "/_chat";
29​
30/**
31 * New-thread and preview commands, live while a chat route is showing and no
32 * modal page (Settings, Usage) covers it. Everything is read at event time, so
33 * the scope is registered once instead of re-registering on every store change.
34 */
35export function installChatRouteCommands(router: AnyRouter): () => void {
36 const handleNewThread = createNewThreadHandler(router);
37 const scratch = createScratchProjectActions({
38 environments: () =>
39 [...appAtomRegistry.get(environmentPresentations.presentationsAtom)].map(
40 ([environmentId, presentation]) => ({ ...presentation, environmentId }),
41 ),
42 primaryEnvironmentId: () => appAtomRegistry.get(primaryEnvironmentIdAtom),
43 registry: appAtomRegistry,
44 handleNewThread,
45 });
46​
47 const readRouteTarget = () => resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
48 const readRouteThreadRef = () => {
49 const target = readRouteTarget();
50 return target?.kind === "server" ? target.threadRef : null;
51 };
52 const readPreviewOpen = () => {
53 const threadRef = readRouteThreadRef();
54 // Store-only on purpose: the URL-aware arbitration lives in ChatView's
55 // preview toggle, which the action bus reaches.
56 return threadRef
57 ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, threadRef) === "preview"
58 : false;
59 };
60 const readThreadContext = () => {
61 const target = readRouteTarget();
62 const drafts = useComposerDraftStore.getState();
63 const activeThread = target?.kind === "server" ? readThreadShell(target.threadRef) : null;
64 const activeDraftThread = target
65 ? target.kind === "server"
66 ? drafts.getDraftThread(target.threadRef)
67 : drafts.getDraftSession(target.draftId)
68 : null;
69 return {
70 activeDraftThread,
71 activeThread: activeThread ?? undefined,
72 defaultProjectRef: resolveDefaultProjectRef(
73 readProjects(),
74 useUiStateStore.getState().projectOrder,
75 ),
76 handleNewThread,
77 };
78 };
79 const readProjectGroupCount = () =>
80 buildSidebarProjectSnapshots({
81 projects: readProjects(),
82 settings: selectProjectGroupingSettings(getClientSettings()),
83 primaryEnvironmentId: appAtomRegistry.get(primaryEnvironmentIdAtom),
84 resolveEnvironmentLabel: () => null,
85 }).length;
86 const canOperatePreview = (environmentId: EnvironmentId) =>
87 readEnvironmentScope(environmentId, AuthPreviewOperateScope);
88​
89 const claim = (event: KeyboardEvent) => {
90 event.preventDefault();
91 event.stopPropagation();
92 };
93​
94 const startNewLocal: CommandHandler = (event) => {
95 claim(event);
96 void startNewThreadFromContext(readThreadContext());
97 };
98​
99 const previewCommand =
100 (action: PreviewAction): CommandHandler =>
101 (event) => {
102 claim(event);
103 const threadRef = readRouteThreadRef();
104 if (threadRef && canOperatePreview(threadRef.environmentId)) dispatchPreviewAction(action);
105 };
106​
107 return registerCommands(
108 {
109 "chat.newLocal": startNewLocal,
110 "chat.newWithoutProject": (event) => {
111 const { activeThread, activeDraftThread } = readThreadContext();
112 const environmentId = scratch.scratchEnvironmentId(
113 activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null,
114 );
115 if (environmentId === null) return;
116 claim(event);
117 void scratch.startScratchThread(environmentId);
118 },
119 "chat.new": (event) => {
120 // The boring sidebar's folders already show the context, so it starts in
121 // the current project like the legacy sidebar did.
122 const { boringSidebarEnabled, legacySidebarEnabled } = getClientSettings();
123 if (!boringSidebarEnabled && !legacySidebarEnabled && readProjectGroupCount() > 1) {
124 claim(event);
125 openCommandPalette({ open: "new-thread-in" });
126 return;
127 }
128 startNewLocal(event);
129 },
130 "preview.toggle": (event) => {
131 claim(event);
132 const threadRef = readRouteThreadRef();
133 if (!threadRef || (!canOperatePreview(threadRef.environmentId) && !readPreviewOpen())) {
134 return;
135 }
136 if (!isPreviewAvailableFor(threadRef.environmentId)) {
137 toastManager.add(
138 stackedThreadToast({
139 type: "info",
140 title: "Preview is desktop-only",
141 description: "Open T3 Code in the desktop app to use the in-app preview.",
142 }),
143 );
144 return;
145 }
146 dispatchPreviewAction("toggle-panel");
147 },
148 "preview.refresh": previewCommand("refresh"),
149 "preview.focusUrl": previewCommand("focus-url"),
150 "preview.zoomIn": previewCommand("zoom-in"),
151 "preview.zoomOut": previewCommand("zoom-out"),
152 "preview.resetZoom": previewCommand("reset-zoom"),
153 },
154 {
155 when: () =>
156 router.state.matches.some((match) => match.routeId === CHAT_ROUTE_ID) &&
157 !router.state.matches.some((match) => isAppModalPage(match.pathname)) &&
158 !isCommandPaletteOpen(),
159 context: () => {
160 const threadRef = readRouteThreadRef();
161 return {
162 terminalOpen: threadRef
163 ? selectThreadTerminalUiState(
164 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
165 threadRef,
166 ).terminalOpen
167 : false,
168 previewOpen: readPreviewOpen(),
169 };
170 },
171 onKeyDown: (event) => {
172 if (event.key !== "Escape") return false;
173 const selection = useThreadSelectionStore.getState();
174 if (selection.selectedThreadKeys.size === 0) return false;
175 event.preventDefault();
176 selection.clearSelection();
177 },
178 },
179 );