Open History to see the last commit
1import { BookmarkIcon, FileIcon, FileTextIcon } 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 { ComposerBanner } from "./ComposerBanner";
8
9const SNIPPET_MAX_CHARS = 90;
10
11/** Images that did not make it into the entry, whatever the reason. */
12function missingImageCount(entry: PromptStashEntry): number {
13 return entry.droppedImageNames.length + (entry.unreadableImageNames?.length ?? 0);
14}
15
16function stashEntrySnippet(entry: PromptStashEntry): string {
17 const trimmed = entry.prompt.trim().replace(/\s+/g, " ");
18 if (trimmed.length > 0) {
19 return trimmed.length > SNIPPET_MAX_CHARS ? `${trimmed.slice(0, SNIPPET_MAX_CHARS)}…` : trimmed;
20 }
21 const imageCount = entry.attachments.length + entry.droppedImageNames.length;
22 const fileCount = entry.files?.length ?? 0;
23 const attachmentCount = imageCount + fileCount;
24 if (attachmentCount === 0) {
25 return "(empty)";
26 }
27 const label = imageCount > 0 && fileCount > 0 ? "attachment" : fileCount > 0 ? "file" : "image";
28 return `(${attachmentCount} ${label}${attachmentCount === 1 ? "" : "s"})`;
29}
30
31/**
32 * Attached banner listing the stashed prompts. Keyboard-first: opened by ⌘S on an
33 * empty composer, navigated with arrows, restored with Enter, dismissed
34 * with Escape. The listener runs capture-phase on window so it wins over
35 * the Lexical editor's handlers while the menu is open.
36 */
37export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
38 entries: ReadonlyArray<PromptStashEntry>;
39 stashShortcutLabel: string | null;
40 onRestore: (entry: PromptStashEntry) => void;
41 onDelete: (entry: PromptStashEntry) => void;
42 onClose: () => void;
43}) {
44 const { entries, stashShortcutLabel, onRestore, onDelete, onClose } = props;
45 const drawerRef = useRef<HTMLDivElement>(null);
46 const [highlightedId, setHighlightedId] = useState<string | null>(entries[0]?.id ?? null);
47
48 const highlightedEntry = entries.find((entry) => entry.id === highlightedId) ?? entries[0];
49
50 useEffect(() => {
51 const closeOnOutsidePointer = (event: PointerEvent) => {
52 const drawer = drawerRef.current;
53 if (
54 (drawer && event.composedPath().includes(drawer)) ||
55 (event.target instanceof Element &&
56 event.target.closest('[data-prompt-stash-badge="true"]'))
57 ) {
58 return;
59 }
60 onClose();
61 };
62 document.addEventListener("pointerdown", closeOnOutsidePointer, true);
63 return () => document.removeEventListener("pointerdown", closeOnOutsidePointer, true);
64 }, [onClose]);
65
66 useEffect(() => {
67 const handler = (event: KeyboardEvent) => {
68 if (event.key === "Escape") {
69 event.preventDefault();
70 event.stopPropagation();
71 onClose();
72 return;
73 }
74 if (event.key === "ArrowDown" || event.key === "ArrowUp") {
75 if (entries.length === 0) return;
76 event.preventDefault();
77 event.stopPropagation();
78 const currentIndex = entries.findIndex((entry) => entry.id === highlightedEntry?.id);
79 const offset = event.key === "ArrowDown" ? 1 : -1;
80 const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;
81 const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;
82 setHighlightedId(entries[nextIndex]?.id ?? null);
83 const nextButton =
84 drawerRef.current?.querySelectorAll<HTMLButtonElement>("[data-stash-restore]")[nextIndex];
85 nextButton?.scrollIntoView({ block: "nearest" });
86 if (drawerRef.current?.contains(document.activeElement)) {
87 nextButton?.focus({ preventScroll: true });
88 }
89 return;
90 }
91 if (event.key === "Enter") {
92 // A focused control inside the row (the delete button) owns its own
93 // activation; swallowing Enter here would restore instead of delete.
94 if (event.target instanceof HTMLElement && event.target.closest("button[aria-label]")) {
95 return;
96 }
97 if (!highlightedEntry) return;
98 event.preventDefault();
99 event.stopPropagation();
100 onRestore(highlightedEntry);
101 return;
102 }
103 if (event.key === "Backspace" && (event.metaKey || event.ctrlKey)) {
104 if (!highlightedEntry) return;
105 event.preventDefault();
106 event.stopPropagation();
107 onDelete(highlightedEntry);
108 }
109 };
110 window.addEventListener("keydown", handler, true);
111 return () => window.removeEventListener("keydown", handler, true);
112 }, [entries, highlightedEntry, onClose, onDelete, onRestore]);
113
114 return (
115 <ComposerBanner.Root ref={drawerRef} data-composer-stash-drawer="true">
116 <ComposerBanner.Row
117 render={<button type="button" />}
118 aria-label="Close stash"
119 aria-expanded="true"
120 onPointerDown={(event) => event.preventDefault()}
121 onClick={onClose}
122 >
123 <ComposerBanner.Icon>
124 <BookmarkIcon />
125 </ComposerBanner.Icon>
126 <ComposerBanner.Content className="text-muted-foreground">Stash</ComposerBanner.Content>
127 <ComposerBanner.Actions>
128 <ComposerBanner.Count>{entries.length}</ComposerBanner.Count>
129 <ComposerBanner.ToggleIcon expanded />
130 </ComposerBanner.Actions>
131 </ComposerBanner.Row>
132 <ComposerBanner.Scroll>
133 <ComposerBanner.Children render={<ul />} aria-label="Stashed prompts">
134 {entries.length === 0 ? (
135 <ComposerBanner.Row render={<li />}>
136 <ComposerBanner.Icon />
137 <ComposerBanner.Content className="text-muted-foreground">
138 Nothing stashed yet.
139 {stashShortcutLabel
140 ? ` Press ${stashShortcutLabel} with a prompt in the composer to stash it.`
141 : null}
142 </ComposerBanner.Content>
143 </ComposerBanner.Row>
144 ) : (
145 entries.map((entry) => (
146 <ComposerBanner.Row
147 render={<li />}
148 key={entry.id}
149 data-stash-entry={entry.id}
150 data-highlighted={highlightedEntry?.id === entry.id || undefined}
151 className={cn(
152 "relative rounded-sm",
153 highlightedEntry?.id === entry.id && "bg-accent text-accent-foreground",
154 )}
155 onMouseMove={() => {
156 if (highlightedId !== entry.id) setHighlightedId(entry.id);
157 }}
158 onFocus={() => setHighlightedId(entry.id)}
159 >
160 <ComposerBanner.Icon>
161 <FileTextIcon />
162 </ComposerBanner.Icon>
163 <ComposerBanner.Content>
164 <button
165 type="button"
166 className="min-w-0 flex-1 cursor-pointer truncate text-left text-foreground/80 outline-none before:absolute before:inset-0 before:rounded-sm focus-visible:before:ring-2 focus-visible:before:ring-ring"
167 data-stash-restore={entry.id}
168 aria-label={`Restore stashed prompt: ${stashEntrySnippet(entry)}`}
169 onPointerDown={(event) => event.preventDefault()}
170 onClick={() => onRestore(entry)}
171 >
172 {stashEntrySnippet(entry)}
173 </button>
174 </ComposerBanner.Content>
175 <ComposerBanner.Actions>
176 {entry.pendingImageCount ? (
177 <span className="shrink-0 text-muted-foreground">
178 saving {entry.pendingImageCount} image
179 {entry.pendingImageCount === 1 ? "" : "s"}…
180 </span>
181 ) : missingImageCount(entry) > 0 ? (
182 <span className="shrink-0 text-warning-foreground">
183 {missingImageCount(entry)} image
184 {missingImageCount(entry) === 1 ? "" : "s"} dropped
185 </span>
186 ) : null}
187 {entry.attachments.length > 0 ? (
188 <span className="flex shrink-0 items-center -space-x-1.5">
189 {entry.attachments.slice(0, 3).map((attachment) => (
190 <img
191 key={attachment.id}
192 src={attachment.dataUrl}
193 alt=""
194 aria-hidden="true"
195 className="size-4 rounded border border-border/70 object-cover"
196 />
197 ))}
198 </span>
199 ) : null}
200 {(entry.files?.length ?? 0) > 0 ? (
201 <span className="flex shrink-0 items-center gap-1 text-muted-foreground">
202 <FileIcon className="size-3" aria-hidden />
203 {entry.files!.length}
204 </span>
205 ) : null}
206 <time
207 dateTime={entry.createdAt}
208 className="shrink-0 text-muted-foreground tabular-nums max-sm:hidden"
209 >
210 {formatRelativeTimeLabel(entry.createdAt)}
211 </time>
212 <ComposerBanner.Dismiss
213 className="z-10"
214 aria-label="Delete stashed prompt"
215 onPointerDown={(event) => event.preventDefault()}
216 onClick={() => onDelete(entry)}
217 />
218 </ComposerBanner.Actions>
219 </ComposerBanner.Row>
220 ))
221 )}
222 </ComposerBanner.Children>
223 </ComposerBanner.Scroll>
224 </ComposerBanner.Root>
225 );
226});