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

useRightPanelActions.ts

347 lines13.6 KB

1import type { ToolCallDiffTarget } from "../../diffPanelStore";
2import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
3import type { ThreadPreviewState } from "../../previewStateStore";
4import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
5import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
6import { useStableCallback } from "../../hooks/useStableCallback";
7import { type ScopedThreadRef, type RunId } from "@t3tools/contracts";
8import { scopedThreadKey } from "@t3tools/client-runtime/environment";
9import { useEffect } from "react";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13} from "@t3tools/client-runtime/state/runtime";
14import { useDiffPanelStore } from "../../diffPanelStore";
15import { type ThreadPanelPresentation } from "../../rightPanelLayout";
16import {
17 selectThreadPanelOpen,
18 type RightPanelSurface,
19 useRightPanelStore,
20} from "../../rightPanelStore";
21import { requestWorkspaceContentFocus, requestWorkspaceFocus } from "../../lib/workspaceFocus";
22import { setActivePreviewTab } from "../../previewStateStore";
23import { isBrowserSettingsReadError } from "../../browser/openFileInPreview";
24import { addBrowserSurface } from "../preview/addBrowserSurface";
25import { focusActivePanelTerminal, focusTerminal } from "../../lib/terminalFocus";
26import { subscribePreviewAction } from "../preview/previewActionBus";
27import { floatDeviceSurface } from "../preview/agentOpenedPreviews";
28import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../../previewMiniPlayerStore";
29import type { threadPullRequestPanelTarget } from "../pullRequest/pullRequestDetail.logic";
30import type { useDeviceState } from "../../state/device";
31import { stackedThreadToast, toastManager } from "../ui/toast";
32import { openDeviceSetupDialog } from "./ChatOverlayHosts";
33import { previewEnvironment } from "../../state/preview";
34import { useAtomCommand } from "../../state/use-atom-command";
35import type { ChatShortcutCommands } from "./useChatShortcuts";
36interface RightPanelActionsInput {
37 readonly activeThreadRef: ScopedThreadRef | null;
38 readonly activeProject: EnvironmentProject | null;
39 readonly activeRightPanelSurface: RightPanelSurface | null;
40 readonly activePreviewState: ThreadPreviewState;
41 readonly deviceState: ReturnType<typeof useDeviceState>["state"];
42 readonly deviceStateLoaded: boolean;
43 readonly pullRequestPanelTarget: ReturnType<typeof threadPullRequestPanelTarget> | null;
44 readonly threadPanelPresentation: ThreadPanelPresentation;
45 readonly isServerThread: boolean;
46 /** A side chat pane; the main view already answers preview bus actions. */
47 readonly embedded: boolean;
48 readonly isGitRepo: boolean;
49 readonly browserAvailable: boolean;
50 readonly canOperatePreview: boolean;
51 readonly diffOpen: boolean;
52 readonly previewPanelOpen: boolean;
53 readonly rightPanelOpen: boolean;
54 readonly canMaximizeRightPanel: boolean;
55 readonly rightPanelMaximized: boolean;
56 readonly supportsPullRequests: boolean;
57 readonly pullRequestsSurfaceAvailable: boolean;
58 readonly gitCwd: string | null;
59 readonly activeProjectCwd: string | null;
60 readonly onDiffPanelOpen: (() => void) | undefined;
61 readonly closeRightPanelSurface: (surface: RightPanelSurface) => void;
63​
64/**
65 * Opening, closing, and arranging the right panel's surfaces: browser, diff, files, pull
66 * requests, device, and terminal tabs.
67 */
68export function useRightPanelActions(input: RightPanelActionsInput) {
69 const {
70 closeRightPanelSurface,
71 activeThreadRef,
72 activeProject,
73 activeRightPanelSurface,
74 activePreviewState,
75 deviceState,
76 deviceStateLoaded,
77 pullRequestPanelTarget,
78 threadPanelPresentation,
79 isServerThread,
80 embedded,
81 isGitRepo,
82 browserAvailable,
83 canOperatePreview,
84 diffOpen,
85 previewPanelOpen,
86 rightPanelOpen,
87 canMaximizeRightPanel,
88 rightPanelMaximized,
89 supportsPullRequests,
90 pullRequestsSurfaceAvailable,
91 gitCwd,
92 activeProjectCwd,
93 onDiffPanelOpen,
94 } = input;
95​
96 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
97 const onToggleDiff = () => {
98 if (!isServerThread) {
99 return;
100 }
101 if (!diffOpen) {
102 onDiffPanelOpen?.();
103 }
104 if (activeThreadRef) {
105 useRightPanelStore.getState().toggle(activeThreadRef, "diff");
106 }
107 };
108 const onToggleDiffStable = useStableCallback(onToggleDiff);
109 const createBrowserSurface = (profileId?: string) => {
110 if (!activeThreadRef || !canOperatePreview) return;
111 void addBrowserSurface({
112 threadRef: activeThreadRef,
113 openPreview,
114 ...(profileId === undefined ? {} : { profileId }),
115 }).then((result) => {
116 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
117 const error = squashAtomCommandFailure(result);
118 if (isBrowserSettingsReadError(error)) {
119 toastManager.add(
120 stackedThreadToast({
121 type: "error",
122 title: "Unable to open browser",
123 description: error.message,
124 }),
125 );
126 }
127 });
128 };
129 const createBrowserSurfaceStable = useStableCallback(createBrowserSurface);
130 const addDiffSurface = () => {
131 if (!activeThreadRef || !isServerThread || !isGitRepo) return;
132 useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch");
133 useRightPanelStore.getState().open(activeThreadRef, "diff");
134 onDiffPanelOpen?.();
135 };
136 const addDiffSurfaceStable = useStableCallback(addDiffSurface);
137 const openChangesFromThreadPanel = () => {
138 addDiffSurface();
139 };
140 const openChangesFromThreadPanelStable = useStableCallback(openChangesFromThreadPanel);
141 const addFilesSurface = () => {
142 if (!activeThreadRef || !activeProject) return;
143 useRightPanelStore.getState().open(activeThreadRef, "files");
144 };
145 const addFilesSurfaceStable = useStableCallback(addFilesSurface);
146 const addPullRequestsSurface = () => {
147 if (!activeThreadRef || !pullRequestsSurfaceAvailable) return;
148 useRightPanelStore.getState().open(activeThreadRef, "pull-requests");
149 };
150 const addPullRequestsSurfaceStable = useStableCallback(addPullRequestsSurface);
151 const addDeviceSurface = () => {
152 if (!activeThreadRef) return;
153 if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") {
154 openDeviceSetupDialog(scopedThreadKey(activeThreadRef));
155 return;
156 }
157 useRightPanelStore.getState().open(activeThreadRef, "device");
158 };
159 const addDeviceSurfaceStable = useStableCallback(addDeviceSurface);
160 const openFileSurface = (relativePath: string) => {
161 if (!activeThreadRef || !activeProject) return;
162 useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
163 };
164 const openFileSurfaceStable = useStableCallback(openFileSurface);
165 const closePreviewPanel = () => {
166 if (activeThreadRef) {
167 if (activeRightPanelSurface?.kind === "preview" && activeRightPanelSurface.resourceId) {
168 usePreviewMiniPlayerStore
169 .getState()
170 .open(activeThreadRef, browserMiniPlayerSource(activeRightPanelSurface.resourceId));
171 } else if (activeRightPanelSurface?.kind === "device" && activeRightPanelSurface.target) {
172 floatDeviceSurface(
173 activeThreadRef,
174 { kind: "device", ...activeRightPanelSurface.target },
175 deviceStateLoaded ? deviceState : null,
176 );
177 }
178 useRightPanelStore.getState().setMaximized(activeThreadRef, false);
179 useRightPanelStore.getState().close(activeThreadRef);
180 }
181 };
182 const closePreviewPanelStable = useStableCallback(closePreviewPanel);
183 const togglePreviewPanel = () => {
184 if (!activeThreadRef || !browserAvailable) return;
185 if (previewPanelOpen) {
186 closePreviewPanel();
187 return;
188 }
189 if (!canOperatePreview) return;
190 const activeTabId = activePreviewState.activeTabId;
191 if (activeTabId) {
192 useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId);
193 } else {
194 createBrowserSurface();
195 }
196 };
197 const togglePreviewPanelStable = useStableCallback(togglePreviewPanel);
198 const activateRightPanelSurface = (surface: RightPanelSurface) => {
199 if (!activeThreadRef) return;
200 useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id);
201 if (surface.kind === "preview" && surface.resourceId) {
202 setActivePreviewTab(activeThreadRef, surface.resourceId);
203 }
204 if (surface.kind === "terminal") {
205 focusTerminal(activeThreadRef, surface.activeTerminalId);
206 }
207 if (surface.kind === "side-chat") {
208 requestWorkspaceFocus({
209 area: "panel",
210 selector: `[data-side-chat-pane="${CSS.escape(surface.threadId)}"] [data-workspace-area="composer"] [contenteditable="true"]`,
211 });
212 }
213 if (surface.kind === "diff" && !diffOpen) {
214 onDiffPanelOpen?.();
215 }
216 };
217 const activateRightPanelSurfaceStable = useStableCallback(activateRightPanelSurface);
218 const toggleRightPanel = () => {
219 if (!activeThreadRef) return;
220 if (rightPanelOpen) {
221 closePreviewPanel();
222 return;
223 }
224 useRightPanelStore.getState().toggleVisibility(activeThreadRef);
225 focusActivePanelTerminal(activeThreadRef);
226 };
227 const toggleRightPanelStable = useStableCallback(toggleRightPanel);
228 const toggleThreadPanel = () => {
229 if (!activeThreadRef) return;
230 const store = useRightPanelStore.getState();
231 if (threadPanelPresentation === "inline") {
232 const open = selectThreadPanelOpen(
233 store.threadPanelVisibilityByThreadKey,
234 activeThreadRef,
235 "inline",
236 );
237 if (!open) requestWorkspaceFocus({ area: "details" });
238 else if (document.activeElement?.closest('[data-workspace-area="details"]'))
239 requestWorkspaceContentFocus();
240 }
241 store.toggleThreadPanel(activeThreadRef, threadPanelPresentation);
242 };
243 const toggleThreadPanelStable = useStableCallback(toggleThreadPanel);
244 const toggleRightPanelMaximized = () => {
245 if (!canMaximizeRightPanel || !activeThreadRef) return;
246 if (!rightPanelMaximized) requestWorkspaceFocus({ area: "panel" });
247 useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized);
248 };
249 const toggleRightPanelMaximizedStable = useStableCallback(toggleRightPanelMaximized);
250 const moveRightPanelSurface = (surfaceId: string, toIndex: number) => {
251 if (activeThreadRef)
252 useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex);
253 };
254 const moveRightPanelSurfaceStable = useStableCallback(moveRightPanelSurface);
255 const copyRightPanelFilePath = (relativePath: string) => {
256 if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
257 toastManager.add(
258 stackedThreadToast({
259 type: "error",
260 title: "Failed to copy path",
261 description: "Clipboard API unavailable.",
262 }),
263 );
264 return;
265 }
266​
267 const clipboardPath = formatFilePathForClipboard(
268 relativePath,
269 resolvePathLinkTarget(relativePath, gitCwd ?? activeProjectCwd ?? ""),
270 );
271 void navigator.clipboard.writeText(clipboardPath).then(undefined, (error) => {
272 toastManager.add(
273 stackedThreadToast({
274 type: "error",
275 title: "Failed to copy path",
276 description: error instanceof Error ? error.message : "An error occurred.",
277 }),
278 );
279 });
280 };
281 const copyRightPanelFilePathStable = useStableCallback(copyRightPanelFilePath);
282 const addPullRequestSurface = () => {
283 if (!supportsPullRequests || activeThreadRef === null || pullRequestPanelTarget === null)
284 return;
285 useRightPanelStore.getState().openPullRequest(activeThreadRef, pullRequestPanelTarget);
286 };
287 const addPullRequestSurfaceStable = useStableCallback(addPullRequestSurface);
288 const onOpenTurnDiff = (runId: RunId, filePath?: string) => {
289 if (!isServerThread || !activeThreadRef) return;
290 useDiffPanelStore.getState().selectTurn(activeThreadRef, runId, filePath);
291 useRightPanelStore.getState().open(activeThreadRef, "diff");
292 onDiffPanelOpen?.();
293 };
294 const onOpenToolDiffStable = useStableCallback((target: ToolCallDiffTarget) => {
295 if (!isServerThread || !activeThreadRef) return;
296 useDiffPanelStore.getState().selectToolCall(activeThreadRef, target);
297 useRightPanelStore.getState().open(activeThreadRef, "diff");
298 onDiffPanelOpen?.();
299 });
300 const onOpenTurnDiffStable = useStableCallback(onOpenTurnDiff);
301 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the preview action bus to toggle the preview panel
302 useEffect(
303 () =>
304 embedded
305 ? undefined
306 : subscribePreviewAction((action) => {
307 if (action === "toggle-panel") togglePreviewPanelStable();
308 }),
309 [embedded, togglePreviewPanelStable],
310 );
311​
312 const shortcuts = {
313 "rightPanel.toggle": () => toggleRightPanel(),
314 "rightPanel.toggleMaximized": ({ event }) => {
315 if (!event.repeat) toggleRightPanelMaximized();
316 },
317 "threadPanel.toggle": () => toggleThreadPanel(),
318 "rightPanel.close": ({ event }) => {
319 if (!activeRightPanelSurface) return false;
320 if (!event.repeat) closeRightPanelSurface(activeRightPanelSurface);
321 },
322 "diff.toggle": () => onToggleDiff(),
323 } satisfies ChatShortcutCommands;
324​
325 return {
326 shortcuts,
327 activateRightPanelSurfaceStable,
328 addDeviceSurfaceStable,
329 addDiffSurfaceStable,
330 addFilesSurfaceStable,
331 addPullRequestSurfaceStable,
332 addPullRequestsSurfaceStable,
333 closePreviewPanelStable,
334 copyRightPanelFilePathStable,
335 createBrowserSurface,
336 createBrowserSurfaceStable,
337 moveRightPanelSurfaceStable,
338 onOpenToolDiffStable,
339 onOpenTurnDiffStable,
340 onToggleDiffStable,
341 openChangesFromThreadPanelStable,
342 openFileSurfaceStable,
343 toggleRightPanelMaximizedStable,
344 toggleRightPanelStable,
345 toggleThreadPanelStable,
346 };