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

ChatHeader.tsx

332 lines13.2 KB

1import { type EnvironmentId, type ThreadId } from "@t3tools/contracts";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import { ChevronDownIcon } from "lucide-react";
9import {
10 memo,
11 useCallback,
12 useEffect,
13 useMemo,
14 useRef,
15 useState,
16 type KeyboardEvent as ReactKeyboardEvent,
17 type MouseEvent as ReactMouseEvent,
18} from "react";
19import { isTrailingDoubleClick } from "../Sidebar.logic";
20import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
21import { toastManager } from "../ui/toast";
22import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
23import { readLocalApi } from "~/localApi";
24import { threadEnvironment } from "../../state/threads";
25import { useAtomCommand } from "../../state/use-atom-command";
26import { ProjectFavicon } from "../ProjectFavicon";
27import {
28 WorkspaceBreadcrumb,
29 WorkspaceBreadcrumbItem,
30 WorkspaceBreadcrumbSeparator,
31} from "../WorkspaceBreadcrumb";
32import { cn } from "~/lib/utils";
33​
34interface ChatHeaderProps {
35 activeThreadEnvironmentId: EnvironmentId;
36 activeThreadId: ThreadId;
37 activeThreadTitle: string;
38 /** Drafts have no server thread yet, so the title carries no action menu. */
39 isServerThread: boolean;
40 activeProject: EnvironmentProject | null;
41 rightPanelOpen: boolean;
42 onNewThreadInProject: () => void;
43 onOpenProjectSettings?: (() => void) | undefined;
45​
46/**
47 * Rename commit rule shared with the sidebar's inline rename: trim, reject
48 * empty (the caller toasts), and skip the mutation when nothing changed.
49 */
50export function resolveRenameCommit(input: {
51 readonly title: string;
52 readonly originalTitle: string;
53}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } {
54 const trimmed = input.title.trim();
55 if (trimmed.length === 0) return { action: "reject-empty" };
56 if (trimmed === input.originalTitle) return { action: "noop" };
57 return { action: "commit", title: trimmed };
59​
60// How long a click on the thread title waits before opening the action menu,
61// so a double-click-to-rename can cancel it first. Only the native desktop
62// menu needs this: it swallows input while open, so the wait must cover the
63// OS double-click interval. The browser fallback menu keeps seeing DOM
64// events (the second click dismisses it and dblclick still fires), so it
65// opens immediately.
66const TITLE_MENU_OPEN_DELAY_MS = 500;
67export const ChatHeader = memo(function ChatHeader({
68 activeThreadEnvironmentId,
69 activeThreadId,
70 activeThreadTitle,
71 isServerThread,
72 activeProject,
73 rightPanelOpen,
74 onNewThreadInProject,
75 onOpenProjectSettings,
76}: ChatHeaderProps) {
77 const activeProjectName = activeProject?.title;
78 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
79 const activeThreadRef = useMemo(
80 () => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
81 [activeThreadEnvironmentId, activeThreadId],
82 );
83 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
84 reportFailure: false,
85 });
86 // Inline rename, keyed by thread: navigating away drops an in-progress
87 // rename instead of committing stale text. Cleared on thread change (not
88 // just hidden) so returning to the thread doesn't revive the old draft.
89 const [renaming, setRenaming] = useState<{
90 threadId: ThreadId;
91 environmentId: EnvironmentId;
92 title: string;
93 } | null>(null);
94 if (
95 renaming !== null &&
96 (renaming.threadId !== activeThreadId || renaming.environmentId !== activeThreadEnvironmentId)
97 ) {
98 setRenaming(null);
99 }
100 const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null;
101 const renameCommittedRef = useRef(false);
102 const startRename = useCallback(() => {
103 renameCommittedRef.current = false;
104 setRenaming({
105 threadId: activeThreadId,
106 environmentId: activeThreadEnvironmentId,
107 title: activeThreadTitle,
108 });
109 }, [activeThreadEnvironmentId, activeThreadId, activeThreadTitle]);
110 const commitRename = useCallback(
111 (title: string) => {
112 setRenaming(null);
113 const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle });
114 if (resolution.action === "reject-empty") {
115 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
116 return;
117 }
118 if (resolution.action === "noop") return;
119 void updateThreadMetadata({
120 environmentId: activeThreadEnvironmentId,
121 input: { threadId: activeThreadId, title: resolution.title },
122 }).then((result) => {
123 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
124 const error = squashAtomCommandFailure(result);
125 toastManager.add({
126 type: "error",
127 title: "Failed to rename thread",
128 description: error instanceof Error ? error.message : "An error occurred.",
129 });
130 }
131 });
132 },
133 [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata],
134 );
135 const { openMenu, closeMenu } = useThreadActionMenu({
136 threadRef: isServerThread ? activeThreadRef : null,
137 projectCwd: activeProjectCwd,
138 onStartRename: startRename,
139 });
140 const titleButtonRef = useRef<HTMLButtonElement | null>(null);
141 const titleMenuTimerRef = useRef<number | null>(null);
142 const cancelPendingTitleMenu = useCallback(() => {
143 if (titleMenuTimerRef.current === null) return;
144 clearTimeout(titleMenuTimerRef.current);
145 titleMenuTimerRef.current = null;
146 }, []);
147 // Drop a pending menu-open when the thread changes or the header unmounts,
148 // so it can never fire for a thread the user already left.
149 useEffect(
150 () => () => {
151 cancelPendingTitleMenu();
152 },
153 [activeThreadEnvironmentId, activeThreadId, cancelPendingTitleMenu],
154 );
155 const openTitleMenuNow = useCallback(() => {
156 cancelPendingTitleMenu();
157 const rect = titleButtonRef.current?.getBoundingClientRect();
158 if (!rect) return;
159 openMenu({ x: rect.left, y: rect.bottom + 4 });
160 }, [cancelPendingTitleMenu, openMenu]);
161 const openMenuFromTitle = useCallback(
162 (event: ReactMouseEvent<HTMLButtonElement>) => {
163 // The trailing click of a double-click belongs to rename, not the menu.
164 if (isTrailingDoubleClick(event.detail)) return;
165 // Keyboard activation and the explicit chevron affordance can never be
166 // the first half of a double-click, so they open without waiting.
167 const clickedChevron =
168 (event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null;
169 if (event.detail === 0 || clickedChevron || window.desktopBridge === undefined) {
170 openTitleMenuNow();
171 return;
172 }
173 // Stay pending long enough for dblclick to cancel the open before the
174 // native menu appears and swallows the second click.
175 cancelPendingTitleMenu();
176 titleMenuTimerRef.current = window.setTimeout(() => {
177 titleMenuTimerRef.current = null;
178 openTitleMenuNow();
179 }, TITLE_MENU_OPEN_DELAY_MS);
180 },
181 [cancelPendingTitleMenu, openTitleMenuNow],
182 );
183 const handleTitleDoubleClick = useCallback(
184 (event: ReactMouseEvent) => {
185 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
186 // The chevron is the explicit menu affordance; only the title text renames.
187 if ((event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null) return;
188 cancelPendingTitleMenu();
189 closeMenu();
190 startRename();
191 },
192 [cancelPendingTitleMenu, closeMenu, startRename],
193 );
194 const handleHeaderContextMenu = useCallback(
195 (event: ReactMouseEvent) => {
196 if (renamingTitle !== null) return;
197 if (!isServerThread && onOpenProjectSettings === undefined) return;
198 cancelPendingTitleMenu();
199 event.preventDefault();
200 if (!isServerThread) {
201 const api = readLocalApi();
202 if (!api) return;
203 void api.contextMenu
204 .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], {
205 x: event.clientX,
206 y: event.clientY,
207 })
208 .then((action) => {
209 if (action === "project-settings") onOpenProjectSettings?.();
210 });
211 return;
212 }
213 openMenu({ x: event.clientX, y: event.clientY });
214 },
215 [cancelPendingTitleMenu, isServerThread, onOpenProjectSettings, openMenu, renamingTitle],
216 );
217 const handleRenameKeyDown = useCallback(
218 (event: ReactKeyboardEvent<HTMLInputElement>) => {
219 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
220 if (event.key === "Enter") {
221 renameCommittedRef.current = true;
222 commitRename(event.currentTarget.value);
223 } else if (event.key === "Escape") {
224 renameCommittedRef.current = true;
225 setRenaming(null);
226 }
227 },
228 [commitRename],
229 );
230 return (
231 <div
232 className={cn(
233 "flex min-w-0 flex-1 items-center gap-2 sm:gap-3",
234 rightPanelOpen ? "pr-10" : "pr-24",
235 )}
236 onContextMenu={handleHeaderContextMenu}
237 >
238 <WorkspaceBreadcrumb
239 ariaLabel="Thread breadcrumb"
240 className="flex-1 overflow-clip [overflow-clip-margin:2px]"
241 >
242 {/* The project always leads the header: knowing which project a
243 thread lives in is priority zero, and the thread title alone
244 doesn't answer it. */}
245 {activeProject ? (
246 <>
247 <WorkspaceBreadcrumbItem className="shrink">
248 <Tooltip>
249 <TooltipTrigger
250 render={
251 <button
252 type="button"
253 aria-label={`New thread in ${activeProjectName}`}
254 onClick={onNewThreadInProject}
255 className="inline-flex min-w-0 max-w-full 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"
256 />
257 }
258 >
259 <ProjectFavicon project={activeProject} className="size-3.5" />
260 <span className="max-w-40 truncate">{activeProjectName}</span>
261 </TooltipTrigger>
262 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
263 </Tooltip>
264 </WorkspaceBreadcrumbItem>
265 <WorkspaceBreadcrumbSeparator />
266 </>
267 ) : null}
268 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
269 {renamingTitle !== null ? (
270 <input
271 autoFocus
272 aria-label="Thread title"
273 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"
274 defaultValue={renamingTitle}
275 onBlur={(event) => {
276 if (renameCommittedRef.current) return;
277 // Focus landing on a navigation button means the rename was
278 // abandoned — discard it rather than persisting a half-draft.
279 if (
280 event.relatedTarget instanceof HTMLElement &&
281 event.relatedTarget.closest("button")
282 ) {
283 setRenaming(null);
284 return;
285 }
286 commitRename(event.currentTarget.value);
287 }}
288 onFocus={(event) => event.currentTarget.select()}
289 onKeyDown={handleRenameKeyDown}
290 />
291 ) : isServerThread ? (
292 <Tooltip>
293 <TooltipTrigger
294 render={
295 <button
296 ref={titleButtonRef}
297 type="button"
298 aria-label={`Thread actions for ${activeThreadTitle}`}
299 aria-haspopup="menu"
300 onClick={openMenuFromTitle}
301 onDoubleClick={handleTitleDoubleClick}
302 onBlur={cancelPendingTitleMenu}
303 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"
304 />
305 }
306 >
307 <h2 className="min-w-0 truncate">{activeThreadTitle}</h2>
308 <ChevronDownIcon
309 aria-hidden
310 data-thread-title-chevron
311 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"
312 />
313 </TooltipTrigger>
314 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
315 </Tooltip>
316 ) : (
317 <Tooltip>
318 <TooltipTrigger
319 render={
320 <h2 aria-label={activeThreadTitle} className="min-w-0 flex-1 truncate">
321 {activeThreadTitle}
322 </h2>
323 }
324 />
325 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
326 </Tooltip>
327 )}
328 </WorkspaceBreadcrumbItem>
329 </WorkspaceBreadcrumb>
330 </div>
331 );
332});