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