Open History to see the last commit
1import { FileIcon, XIcon } from "lucide-react";
2import { memo, useEffect, useRef, useState } from "react";
3
4import { formatRelativeTimeLabel } from "../../timestampFormat";
5import { cn } from "~/lib/utils";
6import { type PromptStashEntry } from "../../promptStashStore";
7import { Command, CommandGroup, CommandItem, CommandList } from "../ui/command";
8import { Button } from "../ui/button";
9
10const SNIPPET_MAX_CHARS = 90;
11
12/** Images that did not make it into the entry, whatever the reason. */
13function missingImageCount(entry: PromptStashEntry): number {
14 return entry.droppedImageNames.length + (entry.unreadableImageNames?.length ?? 0);
15}
16
17function stashEntrySnippet(entry: PromptStashEntry): string {
18 const trimmed = entry.prompt.trim().replace(/\s+/g, " ");
19 if (trimmed.length > 0) {
20 return trimmed.length > SNIPPET_MAX_CHARS ? `${trimmed.slice(0, SNIPPET_MAX_CHARS)}…` : trimmed;
21 }
22 const imageCount = entry.attachments.length + entry.droppedImageNames.length;
23 const fileCount = entry.files?.length ?? 0;
24 const attachmentCount = imageCount + fileCount;
25 if (attachmentCount === 0) {
26 return "(empty)";
27 }
28 const label = imageCount > 0 && fileCount > 0 ? "attachment" : fileCount > 0 ? "file" : "image";
29 return `(${attachmentCount} ${label}${attachmentCount === 1 ? "" : "s"})`;
30}
31
32/**
33 * Popover listing the stashed prompts. Keyboard-first: opened by ⌘S on an
34 * empty composer, navigated with arrows, restored with Enter, dismissed
35 * with Escape. The listener runs capture-phase on window so it wins over
36 * the Lexical editor's handlers while the menu is open.
37 */
38export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
39 entries: ReadonlyArray<PromptStashEntry>;
40 stashShortcutLabel: string | null;
41 onRestore: (entry: PromptStashEntry) => void;
42 onDelete: (entry: PromptStashEntry) => void;
43 onClose: () => void;
44}) {
45 const { entries, stashShortcutLabel, onRestore, onDelete, onClose } = props;
46 const drawerRef = useRef<HTMLDivElement>(null);
47 const [highlightedId, setHighlightedId] = useState<string | null>(entries[0]?.id ?? null);
48
49 const highlightedEntry = entries.find((entry) => entry.id === highlightedId) ?? entries[0];
50
51 useEffect(() => {
52 const closeOnOutsidePointer = (event: PointerEvent) => {
53 const drawer = drawerRef.current;
54 if (
55 (drawer && event.composedPath().includes(drawer)) ||
56 (event.target instanceof Element &&
57 event.target.closest('[data-prompt-stash-badge="true"]'))
58 ) {
59 return;
60 }
61 onClose();
62 };
63 document.addEventListener("pointerdown", closeOnOutsidePointer, true);
64 return () => document.removeEventListener("pointerdown", closeOnOutsidePointer, true);
65 }, [onClose]);
66
67 useEffect(() => {
68 if (entries.length === 0) return;
69 if (!entries.some((entry) => entry.id === highlightedId)) {
70 setHighlightedId(entries[0]?.id ?? null);
71 }
72 }, [entries, highlightedId]);
73
74 useEffect(() => {
75 const handler = (event: KeyboardEvent) => {
76 if (event.key === "Escape") {
77 event.preventDefault();
78 event.stopPropagation();
79 onClose();
80 return;
81 }
82 if (event.key === "ArrowDown" || event.key === "ArrowUp") {
83 if (entries.length === 0) return;
84 event.preventDefault();
85 event.stopPropagation();
86 const currentIndex = entries.findIndex((entry) => entry.id === highlightedId);
87 const offset = event.key === "ArrowDown" ? 1 : -1;
88 const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;
89 const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;
90 setHighlightedId(entries[nextIndex]?.id ?? null);
91 return;
92 }
93 if (event.key === "Enter") {
94 // A focused control inside the row (the delete button) owns its own
95 // activation; swallowing Enter here would restore instead of delete.
96 if (event.target instanceof HTMLElement && event.target.closest("button[aria-label]")) {
97 return;
98 }
99 if (!highlightedEntry) return;
100 event.preventDefault();
101 event.stopPropagation();
102 onRestore(highlightedEntry);
103 return;
104 }
105 if (event.key === "Backspace" && (event.metaKey || event.ctrlKey)) {
106 if (!highlightedEntry) return;
107 event.preventDefault();
108 event.stopPropagation();
109 onDelete(highlightedEntry);
110 }
111 };
112 window.addEventListener("keydown", handler, true);
113 return () => window.removeEventListener("keydown", handler, true);
114 }, [entries, highlightedEntry, highlightedId, onClose, onDelete, onRestore]);
115
116 return (
117 <Command autoHighlight={false} mode="none">
118 <div
119 ref={drawerRef}
120 className="chat-composer-drawer-surface chat-composer-drawer-attached relative w-full overflow-hidden"
121 data-composer-stash-drawer="true"
122 >
123 <div className="flex h-7 items-center justify-end px-2 pt-1">
124 <Button
125 variant="ghost-muted"
126 size="icon-micro"
127 aria-label="Close stash"
128 onPointerDown={(event) => event.preventDefault()}
129 onClick={onClose}
130 >
131 <XIcon className="size-3" />
132 </Button>
133 </div>
134 <CommandList className="max-h-64 scroll-pb-6">
135 <CommandGroup>
136 {entries.length === 0 ? (
137 <p className="px-3 py-1.5 text-secondary-label text-xs">
138 Nothing stashed yet.
139 {stashShortcutLabel
140 ? ` Press ${stashShortcutLabel} with a prompt in the composer to stash it.`
141 : null}
142 </p>
143 ) : (
144 entries.map((entry) => (
145 <CommandItem
146 key={entry.id}
147 value={entry.id}
148 className={cn(
149 "group/stash relative cursor-pointer select-none gap-3 rounded-lg px-3 py-1.5! hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit",
150 highlightedId === entry.id && "bg-accent! text-accent-foreground!",
151 )}
152 onMouseMove={() => {
153 if (highlightedId !== entry.id) setHighlightedId(entry.id);
154 }}
155 onMouseDown={(event) => {
156 event.preventDefault();
157 }}
158 onClick={() => {
159 onRestore(entry);
160 }}
161 >
162 <span className="min-w-0 flex-1 truncate text-xs">
163 {stashEntrySnippet(entry)}
164 </span>
165 {entry.pendingImageCount ? (
166 <span className="shrink-0 text-[10px] text-secondary-label">
167 saving {entry.pendingImageCount} image
168 {entry.pendingImageCount === 1 ? "" : "s"}…
169 </span>
170 ) : missingImageCount(entry) > 0 ? (
171 <span className="shrink-0 text-[10px] text-warning-foreground">
172 {missingImageCount(entry)} image
173 {missingImageCount(entry) === 1 ? "" : "s"} dropped
174 </span>
175 ) : null}
176 {entry.attachments.length > 0 ? (
177 <span className="flex shrink-0 items-center -space-x-1.5">
178 {entry.attachments.slice(0, 3).map((attachment) => (
179 <img
180 key={attachment.id}
181 src={attachment.dataUrl}
182 alt=""
183 aria-hidden="true"
184 className="size-5 rounded border border-border/70 object-cover"
185 />
186 ))}
187 </span>
188 ) : null}
189 {(entry.files?.length ?? 0) > 0 ? (
190 <span className="flex shrink-0 items-center gap-1 text-secondary-label text-xs">
191 <FileIcon className="size-3.5 text-secondary-label" />
192 {entry.files!.length}
193 </span>
194 ) : null}
195 <span className="shrink-0 text-secondary-label text-xs max-sm:hidden">
196 {formatRelativeTimeLabel(entry.createdAt)}
197 </span>
198 <Button
199 variant="ghost"
200 size="icon-xs"
201 className="pointer-events-none shrink-0 [--control-icon-color:currentColor] opacity-0 shadow-none! transition-opacity pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 group-hover/stash:pointer-events-auto group-hover/stash:opacity-100 group-focus-within/stash:pointer-events-auto group-focus-within/stash:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100"
202 aria-label="Delete stashed prompt"
203 onClick={(event) => {
204 event.stopPropagation();
205 onDelete(entry);
206 }}
207 >
208 <XIcon className="size-3.5 stroke-2" />
209 </Button>
210 </CommandItem>
211 ))
212 )}
213 </CommandGroup>
214 </CommandList>
215 </div>
216 </Command>
217 );
218});