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

ChatHeader.tsx

419 lines16.5 KB

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