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

ChatHeader.tsx

341 lines12.9 KB

1import {
2 type EnvironmentId,
3 type EditorId,
4 type ProjectScript,
5 type ResolvedKeybindingsConfig,
6 type ThreadId,
7} from "@t3tools/contracts";
8import { scopeThreadRef } from "@t3tools/client-runtime/environment";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13import type { ChangeRequestStateLike } from "@t3tools/client-runtime/state/thread-settled";
14import { ChevronDownIcon } from "lucide-react";
15import {
16 memo,
17 useCallback,
18 useMemo,
19 useRef,
20 useState,
21 type KeyboardEvent as ReactKeyboardEvent,
22 type MouseEvent as ReactMouseEvent,
23} from "react";
24import GitActionsControl from "../GitActionsControl";
25import { type DraftId } from "~/composerDraftStore";
26import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
27import { toastManager } from "../ui/toast";
28import ProjectScriptsControl, {
29 type NewProjectScriptInput,
30 type ProjectScriptActionResult,
31} from "../ProjectScriptsControl";
32import { OpenInPicker } from "./OpenInPicker";
33import { usePrimaryEnvironmentId } from "../../state/environments";
34import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts";
35import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
36import { threadEnvironment } from "../../state/threads";
37import { useAtomCommand } from "../../state/use-atom-command";
38import { ProjectFavicon } from "../ProjectFavicon";
39import {
40 WorkspaceBreadcrumb,
41 WorkspaceBreadcrumbItem,
42 WorkspaceBreadcrumbSeparator,
43} from "../WorkspaceBreadcrumb";
44import { cn } from "~/lib/utils";
45​
46interface ChatHeaderProps {
47 activeThreadEnvironmentId: EnvironmentId;
48 activeThreadId: ThreadId;
49 draftId?: DraftId;
50 activeThreadTitle: string;
51 /** Drafts have no server thread yet, so the title carries no action menu. */
52 isServerThread: boolean;
53 /** PR state feeding the settled classification, resolved by ChatView. */
54 changeRequestState: ChangeRequestStateLike | null;
55 activeProjectName: string | undefined;
56 activeProjectCwd: string | null;
57 activeProjectFaviconPath: string | null;
58 openInCwd: string | null;
59 activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
60 preferredScriptId: string | null;
61 keybindings: ResolvedKeybindingsConfig;
62 availableEditors: ReadonlyArray<EditorId>;
63 rightPanelOpen: boolean;
64 gitCwd: string | null;
65 readonly onOpenPullRequest?: ((number: number) => void) | undefined;
66 onNewThreadInProject: () => void;
67 onRunProjectScript: (script: ProjectScript) => void;
68 onAddProjectScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
69 onUpdateProjectScript: (
70 scriptId: string,
71 input: NewProjectScriptInput,
72 ) => Promise<ProjectScriptActionResult>;
73 onDeleteProjectScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
75​
76/**
77 * Rename commit rule shared with the sidebar's inline rename: trim, reject
78 * empty (the caller toasts), and skip the mutation when nothing changed.
79 */
80export function resolveRenameCommit(input: {
81 readonly title: string;
82 readonly originalTitle: string;
83}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } {
84 const trimmed = input.title.trim();
85 if (trimmed.length === 0) return { action: "reject-empty" };
86 if (trimmed === input.originalTitle) return { action: "noop" };
87 return { action: "commit", title: trimmed };
89​
90export function shouldShowOpenInPicker(input: {
91 readonly activeProjectName: string | undefined;
92 readonly activeThreadEnvironmentId: EnvironmentId;
93 readonly primaryEnvironmentId: EnvironmentId | null;
94}): boolean {
95 return (
96 Boolean(input.activeProjectName) &&
97 input.primaryEnvironmentId !== null &&
98 input.activeThreadEnvironmentId === input.primaryEnvironmentId
99 );
101​
102export const ChatHeader = memo(function ChatHeader({
103 activeThreadEnvironmentId,
104 activeThreadId,
105 draftId,
106 activeThreadTitle,
107 isServerThread,
108 changeRequestState,
109 activeProjectName,
110 activeProjectCwd,
111 activeProjectFaviconPath,
112 openInCwd,
113 activeProjectScripts,
114 preferredScriptId,
115 keybindings,
116 availableEditors,
117 rightPanelOpen,
118 gitCwd,
119 onOpenPullRequest,
120 onNewThreadInProject,
121 onRunProjectScript,
122 onAddProjectScript,
123 onUpdateProjectScript,
124 onDeleteProjectScript,
125}: ChatHeaderProps) {
126 const primaryEnvironmentId = usePrimaryEnvironmentId();
127 const fileScripts = useT3ProjectFileScripts(
128 activeThreadEnvironmentId,
129 activeProjectScripts ? activeProjectCwd : null,
130 );
131 const showOpenInPicker = shouldShowOpenInPicker({
132 activeProjectName,
133 activeThreadEnvironmentId,
134 primaryEnvironmentId,
135 });
136 const activeThreadRef = useMemo(
137 () => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
138 [activeThreadEnvironmentId, activeThreadId],
139 );
140 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
141 reportFailure: false,
142 });
143 // Inline rename, keyed by thread: navigating away drops an in-progress
144 // rename instead of committing stale text. Cleared on thread change (not
145 // just hidden) so returning to the thread doesn't revive the old draft.
146 const [renaming, setRenaming] = useState<{ threadId: ThreadId; title: string } | null>(null);
147 if (renaming !== null && renaming.threadId !== activeThreadId) {
148 setRenaming(null);
149 }
150 const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null;
151 const renameCommittedRef = useRef(false);
152 const startRename = useCallback(() => {
153 renameCommittedRef.current = false;
154 setRenaming({ threadId: activeThreadId, title: activeThreadTitle });
155 }, [activeThreadId, activeThreadTitle]);
156 const commitRename = useCallback(
157 (title: string) => {
158 setRenaming(null);
159 const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle });
160 if (resolution.action === "reject-empty") {
161 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
162 return;
163 }
164 if (resolution.action === "noop") return;
165 void updateThreadMetadata({
166 environmentId: activeThreadEnvironmentId,
167 input: { threadId: activeThreadId, title: resolution.title },
168 }).then((result) => {
169 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
170 const error = squashAtomCommandFailure(result);
171 toastManager.add({
172 type: "error",
173 title: "Failed to rename thread",
174 description: error instanceof Error ? error.message : "An error occurred.",
175 });
176 }
177 });
178 },
179 [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata],
180 );
181 const { openMenu } = useThreadActionMenu({
182 threadRef: isServerThread ? activeThreadRef : null,
183 projectCwd: activeProjectCwd,
184 changeRequestState,
185 onStartRename: startRename,
186 });
187 const titleButtonRef = useRef<HTMLButtonElement | null>(null);
188 const openMenuFromTitle = useCallback(() => {
189 const rect = titleButtonRef.current?.getBoundingClientRect();
190 if (!rect) return;
191 openMenu({ x: rect.left, y: rect.bottom + 4 });
192 }, [openMenu]);
193 const handleHeaderContextMenu = useCallback(
194 (event: ReactMouseEvent) => {
195 if (!isServerThread || renamingTitle !== null) return;
196 // The right-side controls (git, scripts, open-in) keep their own
197 // behavior; only the breadcrumb area opens the thread menu.
198 if ((event.target as HTMLElement).closest("[data-chat-header-actions]")) return;
199 event.preventDefault();
200 openMenu({ x: event.clientX, y: event.clientY });
201 },
202 [isServerThread, openMenu, renamingTitle],
203 );
204 const handleRenameKeyDown = useCallback(
205 (event: ReactKeyboardEvent<HTMLInputElement>) => {
206 if (event.key === "Enter") {
207 renameCommittedRef.current = true;
208 commitRename(event.currentTarget.value);
209 } else if (event.key === "Escape") {
210 renameCommittedRef.current = true;
211 setRenaming(null);
212 }
213 },
214 [commitRename],
215 );
216 return (
217 <div
218 className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3"
219 onContextMenu={handleHeaderContextMenu}
220 >
221 <WorkspaceBreadcrumb ariaLabel="Thread breadcrumb" className="flex-1">
222 {/* The project always leads the header: knowing which project a
223 thread lives in is priority zero, and the thread title alone
224 doesn't answer it. */}
225 {activeProjectName ? (
226 <>
227 <WorkspaceBreadcrumbItem>
228 <Tooltip>
229 <TooltipTrigger
230 render={
231 <button
232 type="button"
233 aria-label={`New thread in ${activeProjectName}`}
234 onClick={onNewThreadInProject}
235 className="inline-flex min-w-0 cursor-pointer items-center gap-1.5 rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
236 />
237 }
238 >
239 <ProjectFavicon
240 environmentId={activeThreadEnvironmentId}
241 cwd={activeProjectCwd ?? ""}
242 faviconPath={activeProjectFaviconPath}
243 className="size-3.5"
244 />
245 <span className="max-w-40 truncate">{activeProjectName}</span>
246 </TooltipTrigger>
247 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
248 </Tooltip>
249 </WorkspaceBreadcrumbItem>
250 <WorkspaceBreadcrumbSeparator />
251 </>
252 ) : null}
253 <WorkspaceBreadcrumbItem current className="flex-1">
254 {renamingTitle !== null ? (
255 <input
256 autoFocus
257 aria-label="Thread title"
258 className="min-w-0 flex-1 rounded-sm bg-transparent text-sm font-medium text-foreground outline-none ring-1 ring-ring/50 focus:ring-ring"
259 defaultValue={renamingTitle}
260 onBlur={(event) => {
261 if (renameCommittedRef.current) return;
262 commitRename(event.currentTarget.value);
263 }}
264 onFocus={(event) => event.currentTarget.select()}
265 onKeyDown={handleRenameKeyDown}
266 />
267 ) : isServerThread ? (
268 <Tooltip>
269 <TooltipTrigger
270 render={
271 <button
272 ref={titleButtonRef}
273 type="button"
274 aria-label={`Thread actions for ${activeThreadTitle}`}
275 aria-haspopup="menu"
276 onClick={openMenuFromTitle}
277 className="group/thread-title inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
278 />
279 }
280 >
281 <h2 className="min-w-0 truncate">{activeThreadTitle}</h2>
282 <ChevronDownIcon
283 aria-hidden
284 className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/thread-title:opacity-100 group-focus-visible/thread-title:opacity-100"
285 />
286 </TooltipTrigger>
287 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
288 </Tooltip>
289 ) : (
290 <Tooltip>
291 <TooltipTrigger
292 render={
293 <h2 aria-label={activeThreadTitle} className="min-w-0 flex-1 truncate">
294 {activeThreadTitle}
295 </h2>
296 }
297 />
298 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
299 </Tooltip>
300 )}
301 </WorkspaceBreadcrumbItem>
302 </WorkspaceBreadcrumb>
303 <div
304 data-chat-header-actions
305 className={cn(
306 "flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3",
307 rightPanelOpen ? "pr-0" : "pr-16",
308 )}
309 >
310 {activeProjectScripts && (
311 <ProjectScriptsControl
312 scripts={activeProjectScripts}
313 fileScripts={fileScripts}
314 keybindings={keybindings}
315 preferredScriptId={preferredScriptId}
316 onRunScript={onRunProjectScript}
317 onAddScript={onAddProjectScript}
318 onUpdateScript={onUpdateProjectScript}
319 onDeleteScript={onDeleteProjectScript}
320 />
321 )}
322 {showOpenInPicker && (
323 <OpenInPicker
324 environmentId={activeThreadEnvironmentId}
325 keybindings={keybindings}
326 availableEditors={availableEditors}
327 openInCwd={openInCwd}
328 />
329 )}
330 {activeProjectName && (
331 <GitActionsControl
332 gitCwd={gitCwd}
333 activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
334 onOpenPullRequest={onOpenPullRequest}
335 {...(draftId ? { draftId } : {})}
336 />
337 )}
338 </div>
339 </div>
340 );
341});