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

SidebarDraftBlock.tsx

365 lines14.0 KB

1import { discardComposerDraft } from "../../lib/discardComposerDraft";
2import type { ContextMenuSource } from "@t3tools/contracts";
3import { contextMenuSourceOf } from "../../contextMenuSource";
4import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
5import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
6import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens";
7import { T, useGT, useMessages, plural, part } from "gt-react";
8import { SquarePenIcon, XIcon } from "lucide-react";
9import {
10 memo,
11 useState,
12 type CSSProperties,
13 type KeyboardEvent as ReactKeyboardEvent,
14 type MouseEvent as ReactMouseEvent,
15} from "react";
16import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
17import type { EnvironmentId } from "@t3tools/contracts";
18import { useShallow } from "zustand/react/shallow";
19import { terminalContextDisplayLabels } from "~/lib/terminalContext";
20import { cn } from "~/lib/utils";
21import { useTerminalLabelsByThreadKey } from "~/state/terminalSessions";
22import { resolveSidebarRowAccessibility } from "../Sidebar.logic";
23import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon";
24import {
25 composerDraftHasUserContent,
26 DraftId,
27 useComposerDraftStore,
28 type ComposerThreadDraftState,
29 type DraftSessionState,
30} from "../../composerDraftStore";
31import {
32 draftPenClassName,
33 draftSurfaceClassName,
34 JUMP_HINT_SLOT_CLASS_NAME,
35 JumpHintBadge,
36 sidebarCardHeightRem,
37} from "./SidebarThreadRow";
38import { SharedTooltipTrigger } from "../ui/shared-tooltip";
39import { resolveSidebarRowLines, type SidebarRowLayout } from "./sidebarRowLayout";
40​
41/**
42 * As tall as a thread card with something for every item on the layout, but never shorter than the
43 * draft's own two lines (header and preview).
44 */
45function draftCardHeightRem(layout: SidebarRowLayout): number {
46 const titleLine =
47 (["top", "middle", "bottom"] as const).find((line) =>
48 layout[line].some((token) => token.id === "title"),
49 ) ?? "middle";
50 const lines = resolveSidebarRowLines({
51 lines: layout,
52 titleLine,
53 keepLines: layout.keepLines,
54 hasContent: () => true,
55 });
56 const titleWraps = (["top", "middle", "bottom"] as const).some((line) =>
57 layout[line].some((token) => token.id === "title" && token.form === "wrap"),
58 );
59 const threadCardHeight = sidebarCardHeightRem({
60 middleFolds: lines.middle === null,
61 bottomFolds: lines.bottom === null,
62 titleLine,
63 reservesWrappedTitle: titleWraps && (titleLine === "top" || layout.keepLines.length > 0),
64 });
65 return Math.max(threadCardHeight, 60 / 16);
67​
68const EMPTY_COMPOSER_PARTS = {
69 prompt: "",
70 images: [],
71 persistedAttachments: [],
72 files: [],
73 terminalContexts: [],
74 previewAnnotations: [],
75 reviewComments: [],
76} as const;
77​
78/** Terminal labels for draft threads; an unsent draft stays listed while it has a terminal. */
79export function useDraftTerminalLabels(): ReadonlyMap<string, string> {
80 const environmentIds = useComposerDraftStore((store) => {
81 const ids = new Set<string>();
82 for (const session of Object.values(store.draftThreadsByThreadKey)) {
83 if (session.promotedTo == null) ids.add(session.environmentId);
84 }
85 return [...ids].toSorted().join("\n");
86 });
87 return useTerminalLabelsByThreadKey(
88 environmentIds === "" ? [] : (environmentIds.split("\n") as EnvironmentId[]),
89 );
91​
92export function draftTerminalLabel(
93 session: DraftSessionState,
94 terminalLabels: ReadonlyMap<string, string>,
95): string | null {
96 return terminalLabels.get(`${session.environmentId}:${session.threadId}`) ?? null;
98​
99const SidebarDraftRow = memo(function SidebarDraftRow(props: {
100 draftId: DraftId;
101 composer: ComposerThreadDraftState | null;
102 terminalLabel: string | null;
103 project: ProjectFaviconProject | null;
104 projectDisplayName: string | null;
105 isActive: boolean;
106 jumpLabel: string | null;
107 cardHeight: string;
108 onNavigate: (draftId: DraftId) => void;
109 onDiscard: (draftId: DraftId) => void;
110 onContextMenu: (
111 draftId: DraftId,
112 position: { x: number; y: number },
113 source: ContextMenuSource,
114 ) => void;
115}) {
116 const { draftId, onContextMenu, onDiscard, onNavigate } = props;
117 const composer = props.composer ?? EMPTY_COMPOSER_PARTS;
118 const gt = useGT();
119 const resolve = useMessages();
120 const terminalLabels = terminalContextDisplayLabels(composer.terminalContexts, resolve);
121 const promptPreview =
122 assistantCitationsToPlainText(
123 composerFileLinksToPlainText(
124 replaceComposerContextReferences(
125 composer.prompt,
126 (occurrence) =>
127 (occurrence.kind === "terminal"
128 ? terminalLabels.get(occurrence.contextId)
129 : undefined) ?? occurrence.label,
130 ),
131 ),
132 )
133 .trim()
134 .split("\n", 1)[0] ?? "";
135 // images mirrors persistedAttachments once rehydration finishes; before
136 // that only the persisted list is populated, hence max not sum.
137 const attachmentCount =
138 Math.max(composer.images.length, composer.persistedAttachments.length) +
139 composer.files.length +
140 composer.terminalContexts.length +
141 composer.previewAnnotations.length +
142 composer.reviewComments.length;
143 const preview =
144 promptPreview.length > 0
145 ? promptPreview
146 : attachmentCount === 0 && props.terminalLabel !== null
147 ? props.terminalLabel
148 : gt`${plural(
149 { count: attachmentCount },
150 {
151 one: part`${{ count: attachmentCount }} attachment`,
152 other: part`${{ count: attachmentCount }} attachments`,
153 },
154 )}`;
155 const accessibility = resolveSidebarRowAccessibility({
156 title: preview,
157 statusLabel: gt`Unsent draft`,
158 projectDisplayName: props.projectDisplayName,
159 isActive: props.isActive,
160 });
161 const handleActivate = () => onNavigate(draftId);
162 const handleKeyDown = (event: ReactKeyboardEvent) => {
163 // Keys targeting the nested discard button belong to the button:
164 // preventDefault here would swallow Space's synthesized click and
165 // navigate instead of discarding.
166 if ((event.target as HTMLElement).closest("button")) return;
167 if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {
168 event.preventDefault();
169 const rect = event.currentTarget.getBoundingClientRect();
170 onContextMenu(draftId, { x: rect.left, y: rect.bottom }, "keyboard");
171 } else if (event.key === "Enter" || event.key === " ") {
172 event.preventDefault();
173 onNavigate(draftId);
174 }
175 };
176 const handleContextMenu = (event: ReactMouseEvent) => {
177 event.preventDefault();
178 onContextMenu(draftId, { x: event.clientX, y: event.clientY }, contextMenuSourceOf(event));
179 };
180 const handleDiscard = (event: ReactMouseEvent) => {
181 event.preventDefault();
182 event.stopPropagation();
183 onDiscard(draftId);
184 };
185 return (
186 <li className="list-none py-0.5">
187 <div
188 role="button"
189 tabIndex={0}
190 data-sidebar-row={`draft:${draftId}`}
191 aria-label={accessibility.label}
192 aria-current={accessibility.current}
193 data-testid="sidebar-draft-row"
194 className={cn(
195 "group/sidebar-row relative w-full cursor-pointer overflow-hidden rounded-md text-left text-sidebar-foreground outline-none select-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
196 props.isActive ? "bg-sidebar-row-active" : draftSurfaceClassName,
197 )}
198 onClick={handleActivate}
199 onContextMenu={handleContextMenu}
200 onKeyDown={handleKeyDown}
201 >
202 <div
203 className="relative z-10 h-(--sidebar-card-height) px-(--sidebar-row-content-inset) py-(--sidebar-content-inset)"
204 style={{ "--sidebar-card-height": props.cardHeight } as CSSProperties}
205 >
206 <div className="flex h-5 min-w-0 items-center gap-1.5">
207 <SquarePenIcon aria-hidden className={draftPenClassName} />
208 {props.project ? (
209 <ProjectFavicon project={props.project} className="size-4 shrink-0" />
210 ) : null}
211 <span className="min-w-0 flex-1 truncate text-xs font-medium text-secondary-label">
212 {props.projectDisplayName}
213 </span>
214 <span
215 className={cn(
216 "ml-auto flex h-5 min-w-5 shrink-0 items-center justify-end",
217 props.jumpLabel && JUMP_HINT_SLOT_CLASS_NAME,
218 )}
219 >
220 <SharedTooltipTrigger
221 render={
222 <button
223 type="button"
224 aria-label={gt`Discard draft`}
225 onClick={handleDiscard}
226 className="pointer-events-none inline-flex cursor-pointer items-center rounded-md bg-transparent px-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100"
227 >
228 <XIcon className="size-3" />
229 </button>
230 }
231 label={
232 <>
233 <T>Discard draft</T>
234 </>
235 }
236 />
237 {props.jumpLabel ? <JumpHintBadge label={props.jumpLabel} /> : null}
238 </span>
239 </div>
240 <div className="mt-0.5 truncate text-sm font-medium text-foreground/90">{preview}</div>
241 </div>
242 </div>
243 </li>
244 );
245});
246​
247function listedDraftComposer(draftId: string | null): ComposerThreadDraftState | null {
248 if (draftId === null) return null;
249 const store = useComposerDraftStore.getState();
250 const session = store.draftThreadsByThreadKey[draftId];
251 const composer = store.draftsByThreadKey[draftId];
252 return session && session.promotedTo == null && composer && composerDraftHasUserContent(composer)
253 ? composer
254 : null;
256​
257/**
258 * Unsent drafts listed above the threads, newest first. The open draft keeps the
259 * row it had on arrival (frozen content), so its row and jump number stay put.
260 */
261export function useSidebarDrafts(
262 scopedProjectKeys: ReadonlySet<string> | null,
263 routeDraftId: string | null,
264 terminalLabels: ReadonlyMap<string, string>,
265): { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null } {
266 const [frozenRoute, setFrozenRoute] = useState<{
267 routeDraftId: string | null;
268 composer: ComposerThreadDraftState | null;
269 }>({ routeDraftId: null, composer: null });
270 if (frozenRoute.routeDraftId !== routeDraftId) {
271 setFrozenRoute({ routeDraftId, composer: listedDraftComposer(routeDraftId) });
272 }
273 const routeDraftComposer =
274 frozenRoute.routeDraftId === routeDraftId ? frozenRoute.composer : null;
275 const draftIds = useComposerDraftStore(
276 useShallow((store) => {
277 const listed: [string, DraftSessionState][] = [];
278 for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) {
279 if (session.promotedTo != null) continue;
280 if (
281 scopedProjectKeys !== null &&
282 !scopedProjectKeys.has(`${session.environmentId}:${session.projectId}`)
283 ) {
284 continue;
285 }
286 // Composer edits stay frozen while open; terminals come and go live.
287 const isListed =
288 draftTerminalLabel(session, terminalLabels) !== null ||
289 (draftKey === routeDraftId
290 ? routeDraftComposer !== null
291 : composerDraftHasUserContent(store.draftsByThreadKey[draftKey]));
292 if (isListed) listed.push([draftKey, session]);
293 }
294 listed.sort(([, left], [, right]) => right.createdAt.localeCompare(left.createdAt));
295 return listed.map(([draftKey]) => DraftId.make(draftKey));
296 }),
297 );
298 return { draftIds, routeDraftComposer };
300​
301export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
302 draftIds: readonly DraftId[];
303 routeDraftComposer: ComposerThreadDraftState | null;
304 terminalLabels: ReadonlyMap<string, string>;
305 jumpLabelByDraftId: ReadonlyMap<DraftId, string> | null;
306 projectByKey: ReadonlyMap<string, EnvironmentProject>;
307 projectDisplayNameByKey: ReadonlyMap<string, string>;
308 routeDraftId: string | null;
309 layout: SidebarRowLayout;
310 onNavigateToDraft: (draftId: DraftId) => void;
311 onDraftContextMenu: (
312 draftId: DraftId,
313 position: { x: number; y: number },
314 source: ContextMenuSource,
315 ) => void;
316}) {
317 const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey);
318 const draftsByThreadKey = useComposerDraftStore(
319 useShallow((store) =>
320 Object.fromEntries(
321 props.draftIds.map((draftId) => [draftId, store.draftsByThreadKey[draftId]] as const),
322 ),
323 ),
324 );
325 const drafts = props.draftIds.flatMap((draftId) => {
326 const session = draftThreadsByThreadKey[draftId];
327 const composer =
328 (draftId === props.routeDraftId ? props.routeDraftComposer : null) ??
329 draftsByThreadKey[draftId] ??
330 null;
331 return session ? [{ draftId, session, composer }] : [];
332 });
333 if (drafts.length === 0) {
334 return null;
335 }
336 const cardHeight = `${draftCardHeightRem(props.layout)}rem`;
337 return (
338 <>
339 {drafts.map(({ composer, draftId, session }) => {
340 const projectKey = `${session.environmentId}:${session.projectId}`;
341 return (
342 <SidebarDraftRow
343 key={draftId}
344 draftId={draftId}
345 composer={composer}
346 terminalLabel={draftTerminalLabel(session, props.terminalLabels)}
347 project={props.projectByKey.get(projectKey) ?? null}
348 projectDisplayName={props.projectDisplayNameByKey.get(projectKey) ?? null}
349 isActive={draftId === props.routeDraftId}
350 jumpLabel={props.jumpLabelByDraftId?.get(draftId) ?? null}
351 cardHeight={cardHeight}
352 onNavigate={props.onNavigateToDraft}
353 onDiscard={discardComposerDraft}
354 onContextMenu={props.onDraftContextMenu}
355 />
356 );
357 })}
358 <li
359 aria-hidden
360 data-testid="sidebar-draft-divider"
361 className="mx-2.5 my-1.5 h-px list-none bg-sidebar-border/60"
362 />
363 </>
364 );
365});