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