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

ChatHeader.tsx

414 lines16.2 KB

1import {
2 AuthOrchestrationOperateScope,
3 type EnvironmentId,
4 type ThreadId,
5} from "@t3tools/contracts";
6import { scopeThreadRef } from "@t3tools/client-runtime/environment";
7import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
8import {
9 isAtomCommandInterrupted,
10 squashAtomCommandFailure,
11} from "@t3tools/client-runtime/state/runtime";
12import { ChevronDownIcon } from "lucide-react";
13import {
14 memo,
15 useCallback,
16 useEffect,
17 useMemo,
18 useRef,
19 useState,
20 type KeyboardEvent as ReactKeyboardEvent,
21 type MouseEvent as ReactMouseEvent,
22} from "react";
23import { isTrailingDoubleClick } from "../Sidebar.logic";
24import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
25import { toastManager } from "../ui/toast";
26import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
27import { readLocalApi } from "~/localApi";
28import { threadEnvironment } from "../../state/threads";
29import { useAtomCommand } from "../../state/use-atom-command";
30import { useOrchestrationCommand } from "../../state/use-orchestration-command";
31import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
32import { ProjectFavicon } from "../ProjectFavicon";
33import {
34 WorkspaceBreadcrumb,
35 WorkspaceBreadcrumbItem,
36 WorkspaceBreadcrumbSeparator,
37 WorkspaceBreadcrumbText,
38} from "../WorkspaceBreadcrumb";
39import { observeResize } from "~/lib/observeResize";
40import { cn } from "~/lib/utils";
41import { useClientSettings } from "../../hooks/useSettings";
42​
43interface ChatHeaderProps {
44 activeThreadEnvironmentId: EnvironmentId;
45 activeThreadId: ThreadId;
46 activeThreadTitle: string;
47 isServerThread: boolean;
48 activeProject: EnvironmentProject | null;
49 parentThreadLink: { threadId: ThreadId; title: string } | null;
50 onOpenThread: (threadId: ThreadId) => void;
51 rightPanelOpen: boolean;
52 onNewThreadInProject: () => void;
53 onOpenProjectSettings?: (() => void) | undefined;
55​
56export function resolveRenameCommit(input: {
57 readonly title: string;
58 readonly originalTitle: string;
59}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } {
60 const trimmed = input.title.trim();
61 if (trimmed.length === 0) return { action: "reject-empty" };
62 if (trimmed === input.originalTitle) return { action: "noop" };
63 return { action: "commit", title: trimmed };
65​
66// How long a click on the thread title waits before opening the action menu, so
67// a double-click-to-rename can cancel it first. Only the native desktop menu
68// needs this: it swallows input while open, so the wait must cover the OS
69// double-click interval.
70const TITLE_MENU_OPEN_DELAY_MS = 500;
71export const ChatHeader = memo(function ChatHeader({
72 activeThreadEnvironmentId,
73 activeThreadId,
74 activeThreadTitle,
75 isServerThread,
76 activeProject,
77 parentThreadLink,
78 onOpenThread,
79 rightPanelOpen,
80 onNewThreadInProject,
81 onOpenProjectSettings,
82}: ChatHeaderProps) {
83 const activeProjectName = activeProject?.title;
84 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
85 const interfaceFont = useClientSettings((settings) => settings.fontFamilySans);
86 const breadcrumbContainerRef = useRef<HTMLDivElement>(null);
87 const [collapseParentTitle, setCollapseParentTitle] = useState(false);
88 const activeThreadRef = useMemo(
89 () => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
90 [activeThreadEnvironmentId, activeThreadId],
91 );
92 const canOperateThread = useEnvironmentScope(
93 activeThreadEnvironmentId,
94 AuthOrchestrationOperateScope,
95 );
96 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
97 reportFailure: false,
98 });
99 const [renaming, setRenaming] = useState<{
100 threadId: ThreadId;
101 environmentId: EnvironmentId;
102 title: string;
103 } | null>(null);
104 if (
105 renaming !== null &&
106 (renaming.threadId !== activeThreadId ||
107 renaming.environmentId !== activeThreadEnvironmentId ||
108 !canOperateThread)
109 ) {
110 setRenaming(null);
111 }
112 const renamingTitle =
113 canOperateThread &&
114 renaming?.threadId === activeThreadId &&
115 renaming.environmentId === activeThreadEnvironmentId
116 ? renaming.title
117 : null;
118 const isRenamingTitle = renamingTitle !== null;
119 useEffect(() => {
120 const list = breadcrumbContainerRef.current?.querySelector("ol");
121 if (!list || !parentThreadLink) return;
122 const measure = () => {
123 const gap = Number.parseFloat(getComputedStyle(list).columnGap) || 0;
124 const width = Array.from(list.children).reduce(
125 (total, item) => {
126 const label = item.querySelector('[data-slot="workspace-breadcrumb-text"]');
127 const ellipsis = item.querySelector("[data-parent-breadcrumb-ellipsis]");
128 return (
129 total +
130 (item.firstElementChild?.getBoundingClientRect().width ?? 0) +
131 (label && getComputedStyle(label).maxWidth === "none"
132 ? label.scrollWidth - label.clientWidth
133 : 0) -
134 (ellipsis?.getBoundingClientRect().width ?? 0)
135 );
136 },
137 gap * (list.children.length - 1),
138 );
139 setCollapseParentTitle(width > list.clientWidth);
140 };
141 measure();
142 const frame = requestAnimationFrame(measure);
143 document.fonts.addEventListener("loadingdone", measure);
144 const stopObserving = observeResize(list, measure);
145 return () => {
146 cancelAnimationFrame(frame);
147 document.fonts.removeEventListener("loadingdone", measure);
148 stopObserving();
149 };
150 }, [activeProjectName, activeThreadTitle, parentThreadLink, interfaceFont, isRenamingTitle]);
151 const renameCommittedRef = useRef(false);
152 const startRename = useCallback(() => {
153 if (
154 !isServerThread ||
155 !readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)
156 )
157 return;
158 renameCommittedRef.current = false;
159 setRenaming({
160 environmentId: activeThreadEnvironmentId,
161 threadId: activeThreadId,
162 title: activeThreadTitle,
163 });
164 }, [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, isServerThread]);
165 const commitRename = useCallback(
166 (title: string) => {
167 setRenaming(null);
168 if (!readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)) return;
169 const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle });
170 if (resolution.action === "reject-empty") {
171 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
172 return;
173 }
174 if (resolution.action === "noop") return;
175 void updateThreadMetadata({
176 environmentId: activeThreadEnvironmentId,
177 input: { threadId: activeThreadId, title: resolution.title },
178 }).then((result) => {
179 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
180 const error = squashAtomCommandFailure(result);
181 toastManager.add({
182 type: "error",
183 title: "Failed to rename thread",
184 description: error instanceof Error ? error.message : "An error occurred.",
185 });
186 }
187 });
188 },
189 [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata],
190 );
191 const { openMenu, closeMenu } = useThreadActionMenu({
192 threadRef: isServerThread ? activeThreadRef : null,
193 projectCwd: activeProjectCwd,
194 onStartRename: startRename,
195 });
196 const titleButtonRef = useRef<HTMLButtonElement | null>(null);
197 const titleMenuTimerRef = useRef<number | null>(null);
198 const cancelPendingTitleMenu = useCallback(() => {
199 if (titleMenuTimerRef.current === null) return;
200 clearTimeout(titleMenuTimerRef.current);
201 titleMenuTimerRef.current = null;
202 }, []);
203 useEffect(
204 () => () => {
205 cancelPendingTitleMenu();
206 },
207 [activeThreadEnvironmentId, activeThreadId, cancelPendingTitleMenu],
208 );
209 const openTitleMenuNow = useCallback(() => {
210 cancelPendingTitleMenu();
211 const rect = titleButtonRef.current?.getBoundingClientRect();
212 if (!rect) return;
213 openMenu({ x: rect.left, y: rect.bottom + 4 });
214 }, [cancelPendingTitleMenu, openMenu]);
215 const openMenuFromTitle = useCallback(
216 (event: ReactMouseEvent<HTMLButtonElement>) => {
217 if (isTrailingDoubleClick(event.detail)) return;
218 const clickedChevron =
219 (event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null;
220 if (event.detail === 0 || clickedChevron || window.desktopBridge === undefined) {
221 openTitleMenuNow();
222 return;
223 }
224 cancelPendingTitleMenu();
225 titleMenuTimerRef.current = window.setTimeout(() => {
226 titleMenuTimerRef.current = null;
227 openTitleMenuNow();
228 }, TITLE_MENU_OPEN_DELAY_MS);
229 },
230 [cancelPendingTitleMenu, openTitleMenuNow],
231 );
232 const handleTitleDoubleClick = useCallback(
233 (event: ReactMouseEvent) => {
234 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
235 if ((event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null) return;
236 cancelPendingTitleMenu();
237 closeMenu();
238 startRename();
239 },
240 [cancelPendingTitleMenu, closeMenu, startRename],
241 );
242 const handleHeaderContextMenu = useCallback(
243 (event: ReactMouseEvent) => {
244 if (renamingTitle !== null) return;
245 if (!isServerThread && onOpenProjectSettings === undefined) return;
246 cancelPendingTitleMenu();
247 event.preventDefault();
248 if (!isServerThread) {
249 const api = readLocalApi();
250 if (!api) return;
251 void api.contextMenu
252 .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], {
253 x: event.clientX,
254 y: event.clientY,
255 })
256 .then((action) => {
257 if (action === "project-settings") onOpenProjectSettings?.();
258 });
259 return;
260 }
261 openMenu({ x: event.clientX, y: event.clientY });
262 },
263 [cancelPendingTitleMenu, isServerThread, onOpenProjectSettings, openMenu, renamingTitle],
264 );
265 const handleRenameKeyDown = useCallback(
266 (event: ReactKeyboardEvent<HTMLInputElement>) => {
267 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
268 if (event.key === "Enter") {
269 renameCommittedRef.current = true;
270 commitRename(event.currentTarget.value);
271 } else if (event.key === "Escape") {
272 renameCommittedRef.current = true;
273 setRenaming(null);
274 }
275 },
276 [commitRename],
277 );
278 return (
279 <div
280 ref={breadcrumbContainerRef}
281 className={cn(
282 "flex min-w-0 flex-1 items-center gap-2 sm:gap-3",
283 rightPanelOpen ? "pr-10" : "pr-24",
284 )}
285 onContextMenu={handleHeaderContextMenu}
286 >
287 <WorkspaceBreadcrumb
288 ariaLabel="Thread breadcrumb"
289 className="flex-1 overflow-clip [overflow-clip-margin:2px]"
290 >
291 {activeProject ? (
292 <>
293 <WorkspaceBreadcrumbItem className="shrink">
294 <Tooltip>
295 <TooltipTrigger
296 render={
297 <button
298 type="button"
299 aria-label={`New thread in ${activeProjectName}`}
300 onClick={onNewThreadInProject}
301 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-inset focus-visible:ring-ring"
302 />
303 }
304 >
305 <ProjectFavicon project={activeProject} className="size-3.5" />
306 <WorkspaceBreadcrumbText className="max-w-40">
307 {activeProjectName}
308 </WorkspaceBreadcrumbText>
309 </TooltipTrigger>
310 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
311 </Tooltip>
312 </WorkspaceBreadcrumbItem>
313 <WorkspaceBreadcrumbSeparator>
314 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
315 </WorkspaceBreadcrumbSeparator>
316 </>
317 ) : null}
318 {parentThreadLink ? (
319 <>
320 <WorkspaceBreadcrumbItem>
321 <Tooltip>
322 <TooltipTrigger
323 render={
324 <button
325 type="button"
326 aria-label={`Open parent thread: ${parentThreadLink.title}`}
327 onClick={() => onOpenThread(parentThreadLink.threadId)}
328 className="inline-flex min-w-0 max-w-full cursor-pointer items-center rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
329 />
330 }
331 >
332 <WorkspaceBreadcrumbText
333 aria-hidden
334 className={collapseParentTitle ? "w-0" : undefined}
335 >
336 {parentThreadLink.title}
337 </WorkspaceBreadcrumbText>
338 {collapseParentTitle ? (
339 <span aria-hidden data-parent-breadcrumb-ellipsis>
340 ...
341 </span>
342 ) : null}
343 </TooltipTrigger>
344 <TooltipPopup side="top">{parentThreadLink.title}</TooltipPopup>
345 </Tooltip>
346 </WorkspaceBreadcrumbItem>
347 <WorkspaceBreadcrumbSeparator>
348 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
349 </WorkspaceBreadcrumbSeparator>
350 </>
351 ) : null}
352 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
353 {renamingTitle !== null ? (
354 <input
355 autoFocus
356 aria-label="Thread title"
357 className="min-w-0 flex-1 rounded-sm bg-transparent text-sm font-medium text-foreground outline-none ring-1 ring-inset ring-ring/50 focus:ring-ring"
358 defaultValue={renamingTitle}
359 onBlur={(event) => {
360 if (renameCommittedRef.current) return;
361 if (
362 event.relatedTarget instanceof HTMLElement &&
363 event.relatedTarget.closest("button")
364 ) {
365 setRenaming(null);
366 return;
367 }
368 commitRename(event.currentTarget.value);
369 }}
370 onFocus={(event) => event.currentTarget.select()}
371 onKeyDown={handleRenameKeyDown}
372 />
373 ) : isServerThread ? (
374 <Tooltip>
375 <TooltipTrigger
376 render={
377 <button
378 ref={titleButtonRef}
379 type="button"
380 aria-label={`Thread actions for ${activeThreadTitle}`}
381 aria-haspopup="menu"
382 onClick={openMenuFromTitle}
383 onDoubleClick={canOperateThread ? handleTitleDoubleClick : undefined}
384 onBlur={cancelPendingTitleMenu}
385 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-inset focus-visible:ring-ring"
386 />
387 }
388 >
389 <h2 className="min-w-0">
390 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
391 </h2>
392 <ChevronDownIcon
393 aria-hidden
394 data-thread-title-chevron
395 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"
396 />
397 </TooltipTrigger>
398 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
399 </Tooltip>
400 ) : (
401 <Tooltip>
402 <TooltipTrigger
403 render={<h2 aria-label={activeThreadTitle} className="min-w-0 flex-1" />}
404 >
405 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
406 </TooltipTrigger>
407 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
408 </Tooltip>
409 )}
410 </WorkspaceBreadcrumbItem>
411 </WorkspaceBreadcrumb>
412 </div>
413 );
414});