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

ChatHeader.tsx

415 lines16.1 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 { toastManager } from "../ui/toast";
28import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
29import { readLocalApi } from "~/localApi";
30import { threadEnvironment } from "../../state/threads";
31import { canShareWithGuestAtom } from "./guestShareAvailability";
32import { useAtomValue } from "@effect/atom-react";
33import { useOrchestrationCommand } from "../../state/use-orchestration-command";
34import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
35import { ProjectFavicon } from "../ProjectFavicon";
36import {
37 WorkspaceBreadcrumb,
38 WorkspaceBreadcrumbItem,
39 WorkspaceBreadcrumbSeparator,
40 WorkspaceBreadcrumbText,
41} from "../WorkspaceBreadcrumb";
42import { observeResize } from "~/lib/observeResize";
43import { cn } from "~/lib/utils";
44import { textDirection } from "~/textDirection";
45import { useClientSettings } from "../../hooks/useSettings";
46import { GuestShareIndicator } from "./GuestShareControls";
47import { SharedTooltipTrigger } from "../ui/shared-tooltip";
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 // 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 <SharedTooltipTrigger
270 render={
271 <button
272 type="button"
273 aria-label={gt("New thread in {project}", { project: activeProjectName })}
274 onClick={onNewThreadInProject}
275 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"
276 />
277 }
278 label={
279 <>
280 <T>
281 New thread in <Var>{activeProjectName}</Var>
282 </T>
283 </>
284 }
285 >
286 <ProjectFavicon project={activeProject} className="size-3.5" />
287 <MiddleTruncate
288 data-slot="workspace-breadcrumb-text"
289 value={activeProjectName ?? ""}
290 showTitle={false}
291 variant="cap-aligned"
292 />
293 </SharedTooltipTrigger>
294 </WorkspaceBreadcrumbItem>
295 <WorkspaceBreadcrumbSeparator>
296 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
297 </WorkspaceBreadcrumbSeparator>
298 </>
299 ) : null}
300 {parentThreadLink ? (
301 <>
302 <WorkspaceBreadcrumbItem>
303 <SharedTooltipTrigger
304 render={
305 <button
306 type="button"
307 aria-label={gt("Open parent thread: {title}", {
308 title: parentThreadLink.title,
309 })}
310 onClick={() => onOpenThread(parentThreadLink.threadId)}
311 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"
312 />
313 }
314 label={parentThreadLink.title}
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 </SharedTooltipTrigger>
328 </WorkspaceBreadcrumbItem>
329 <WorkspaceBreadcrumbSeparator>
330 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
331 </WorkspaceBreadcrumbSeparator>
332 </>
333 ) : null}
334 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
335 {renamingTitle !== null ? (
336 <input
337 autoFocus
338 dir="auto"
339 aria-label={gt("Thread title")}
340 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"
341 defaultValue={renamingTitle}
342 onBlur={(event) => {
343 if (renameCommittedRef.current) return;
344 if (
345 event.relatedTarget instanceof HTMLElement &&
346 event.relatedTarget.closest("button")
347 ) {
348 setRenaming(null);
349 return;
350 }
351 commitRename(event.currentTarget.value);
352 }}
353 onFocus={(event) => event.currentTarget.select()}
354 onKeyDown={handleRenameKeyDown}
355 />
356 ) : isServerThread ? (
357 <SharedTooltipTrigger
358 render={
359 <button
360 type="button"
361 aria-label={gt("Thread actions for {title}", { title: activeThreadTitle })}
362 aria-haspopup="menu"
363 onClick={openMenuFromTitle}
364 onDoubleClick={canOperateThread ? handleTitleDoubleClick : undefined}
365 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"
366 />
367 }
368 label={activeThreadTitle}
369 >
370 <h2 className="min-w-0" dir={textDirection(activeThreadTitle)}>
371 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
372 </h2>
373 <ChevronDownIcon
374 aria-hidden
375 data-thread-title-chevron
376 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"
377 />
378 </SharedTooltipTrigger>
379 ) : (
380 <SharedTooltipTrigger
381 render={
382 <h2
383 aria-label={activeThreadTitle}
384 className="min-w-0 flex-1"
385 dir={textDirection(activeThreadTitle)}
386 />
387 }
388 label={activeThreadTitle}
389 >
390 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
391 </SharedTooltipTrigger>
392 )}
393 {renamingTitle === null && activeThreadLinkOrigin ? (
394 <SharedTooltipTrigger
395 render={<Badge variant="info" size="sm" />}
396 label={
397 <>
398 <T>
399 Started by an agent on <Var>{activeThreadLinkOrigin}</Var> through a linked
400 environment.
401 </T>
402 </>
403 }
404 >
405 <T>
406 From <Var>{activeThreadLinkOrigin}</Var>
407 </T>
408 </SharedTooltipTrigger>
409 ) : null}
410 </WorkspaceBreadcrumbItem>
411 </WorkspaceBreadcrumb>
412 {isServerThread ? <GuestShareIndicator threadRef={activeThreadRef} /> : null}
413 </div>
414 );
415});