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