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

SidebarDraftBlock.tsx

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