Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ComposerStashMenu.tsx

289 lines11.9 KB

1import { msg, T, useGT, useMessages, Var } from "gt-react";
2import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react";
3import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react";
4import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
5import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
6import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens";
7​
8import { RelativeTime } from "../RelativeTime";
9import { m, type MessageResolver } from "~/i18n/messages";
10import { cn } from "~/lib/utils";
11import { type PromptStashEntry } from "../../promptStashStore";
12import { ComposerBanner } from "./ComposerBanner";
13​
14const SNIPPET_MAX_CHARS = 90;
15​
16function missingImageCount(entry: PromptStashEntry): number {
17 return entry.droppedImageNames.length + (entry.unreadableImageNames?.length ?? 0);
19​
20export function stashEntrySnippet(entry: PromptStashEntry, resolve: MessageResolver = m): string {
21 const trimmed = assistantCitationsToPlainText(
22 composerFileLinksToPlainText(
23 replaceComposerContextReferences(entry.prompt, (reference) => reference.label),
24 ),
25 )
26 .trim()
27 .replace(/\s+/g, " ");
28 if (trimmed.length > 0) {
29 if (trimmed.length <= SNIPPET_MAX_CHARS) return trimmed;
30 // Never end on a lone high surrogate, the first half of an emoji.
31 const last = trimmed.charCodeAt(SNIPPET_MAX_CHARS - 1);
32 const end = last >= 0xd800 && last <= 0xdbff ? SNIPPET_MAX_CHARS - 1 : SNIPPET_MAX_CHARS;
33 return `${trimmed.slice(0, end)}…`;
34 }
35 const imageCount = entry.attachments.length + entry.droppedImageNames.length;
36 const fileCount = entry.files?.length ?? 0;
37 const attachmentCount = imageCount + fileCount;
38 if (attachmentCount === 0) {
39 return resolve(msg("(empty)"));
40 }
41 if (imageCount > 0 && fileCount > 0) {
42 return resolve(
43 msg("{count, plural, one {({count} attachment)} other {({count} attachments)}}", {
44 count: attachmentCount,
45 }),
46 );
47 }
48 return fileCount > 0
49 ? resolve(
50 msg("{count, plural, one {({count} file)} other {({count} files)}}", {
51 count: attachmentCount,
52 }),
53 )
54 : resolve(
55 msg("{count, plural, one {({count} image)} other {({count} images)}}", {
56 count: attachmentCount,
57 }),
58 );
60​
61/** Window capture gives the open menu priority over composer key handlers. */
62export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
63 entries: ReadonlyArray<PromptStashEntry>;
64 stashShortcutLabel: string | null;
65 composerFormRef: RefObject<HTMLFormElement | null>;
66 onRestore: (entry: PromptStashEntry) => void;
67 onDelete: (entry: PromptStashEntry) => void;
68 onClose: () => void;
69}) {
70 const { entries, stashShortcutLabel, composerFormRef, onRestore, onDelete, onClose } = props;
71 const gt = useGT();
72 const m = useMessages();
73 const [highlightedId, setHighlightedId] = useState<string | null>(entries[0]?.id ?? null);
74​
75 const highlightedEntry = entries.find((entry) => entry.id === highlightedId) ?? entries[0];
76 const drawerRef = useRef<HTMLDivElement>(null);
77​
78 // Both listeners read entries, highlight and callbacks at event time, so they subscribe
79 // once for the menu's lifetime instead of on every highlight change.
80 const closeOnOutsidePointer = useEffectEvent((event: PointerEvent) => {
81 const drawer = drawerRef.current;
82 if (
83 (drawer && event.composedPath().includes(drawer)) ||
84 (event.target instanceof Element && event.target.closest('[data-prompt-stash-badge="true"]'))
85 ) {
86 return;
87 }
88 onClose();
89 });
90​
91 const handleKeyDown = useEffectEvent((event: KeyboardEvent) => {
92 if (event.isComposing || event.keyCode === 229) return;
93 const drawer = drawerRef.current;
94 if (!drawer) return;
95 const target = event.target;
96 if (
97 !(target instanceof Node) ||
98 (target !== document.body &&
99 !(target instanceof Element && target.closest('[data-prompt-stash-badge="true"]')) &&
100 !drawer.contains(target) &&
101 !composerFormRef.current?.querySelector('textarea, [role="textbox"]')?.contains(target))
102 ) {
103 return;
104 }
105 if (event.key === "Escape") {
106 event.preventDefault();
107 event.stopPropagation();
108 onClose();
109 return;
110 }
111 if (event.key === "ArrowDown" || event.key === "ArrowUp") {
112 if (entries.length === 0) return;
113 event.preventDefault();
114 event.stopPropagation();
115 const currentIndex = entries.findIndex((entry) => entry.id === highlightedEntry?.id);
116 const offset = event.key === "ArrowDown" ? 1 : -1;
117 const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;
118 const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;
119 setHighlightedId(entries[nextIndex]?.id ?? null);
120 const nextButton =
121 drawer.querySelectorAll<HTMLButtonElement>("[data-stash-restore]")[nextIndex];
122 nextButton?.scrollIntoView({ block: "nearest" });
123 if (drawer.contains(document.activeElement)) {
124 nextButton?.focus({ preventScroll: true });
125 }
126 return;
127 }
128 if (event.key === "Enter") {
129 // Let the delete button handle Enter instead of restoring its row.
130 if (event.target instanceof HTMLElement && event.target.closest("button[aria-label]")) {
131 return;
132 }
133 if (!highlightedEntry) return;
134 event.preventDefault();
135 event.stopPropagation();
136 onRestore(highlightedEntry);
137 return;
138 }
139 if (event.key === "Backspace" && (event.metaKey || event.ctrlKey)) {
140 if (!highlightedEntry) return;
141 event.preventDefault();
142 event.stopPropagation();
143 onDelete(highlightedEntry);
144 }
145 });
146​
147 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes capture-phase pointerdown and keydown listeners for outside close and keyboard navigation
148 useEffect(() => {
149 const onPointerDown = (event: PointerEvent) => closeOnOutsidePointer(event);
150 const onKeyDown = (event: KeyboardEvent) => handleKeyDown(event);
151 document.addEventListener("pointerdown", onPointerDown, true);
152 window.addEventListener("keydown", onKeyDown, true);
153 return () => {
154 document.removeEventListener("pointerdown", onPointerDown, true);
155 window.removeEventListener("keydown", onKeyDown, true);
156 };
157 }, []);
158​
159 return (
160 <ComposerBanner.Root
161 ref={drawerRef}
162 className="flex min-h-0 flex-col after:shrink-0"
163 data-composer-stash-drawer="true"
164 >
165 <ComposerBanner.Row
166 render={<button type="button" />}
167 aria-label={gt("Close stash")}
168 aria-expanded="true"
169 onPointerDown={(event) => event.preventDefault()}
170 onClick={onClose}
171 >
172 <ComposerBanner.Icon>
173 <BookmarkIcon />
174 </ComposerBanner.Icon>
175 <ComposerBanner.Content className="text-muted-foreground">
176 {gt("Stash", { $context: "noun, saved prompts set aside for later" })}
177 </ComposerBanner.Content>
178 <ComposerBanner.Actions>
179 <ComposerBanner.Count>{entries.length}</ComposerBanner.Count>
180 <ComposerBanner.ToggleIcon expanded />
181 </ComposerBanner.Actions>
182 </ComposerBanner.Row>
183 <ComposerBanner.Scroll className="flex flex-col">
184 <ComposerBanner.Children render={<ul role="list" />} aria-label={gt("Stashed prompts")}>
185 {entries.length === 0 ? (
186 <ComposerBanner.Row render={<li />}>
187 <ComposerBanner.Icon />
188 <ComposerBanner.Content className="text-muted-foreground">
189 <T>Nothing stashed yet.</T>
190 {stashShortcutLabel ? (
191 <>
192 {" "}
193 <T>
194 Press <Var>{stashShortcutLabel}</Var> with a prompt in the composer to stash
195 it.
196 </T>
197 </>
198 ) : null}
199 </ComposerBanner.Content>
200 </ComposerBanner.Row>
201 ) : (
202 entries.map((entry) => (
203 <ComposerBanner.Row
204 render={<li />}
205 key={entry.id}
206 data-stash-entry={entry.id}
207 data-highlighted={highlightedEntry?.id === entry.id || undefined}
208 className={cn(
209 "relative rounded-sm",
210 highlightedEntry?.id === entry.id && "bg-accent text-accent-foreground",
211 )}
212 onMouseMove={() => {
213 if (highlightedId !== entry.id) setHighlightedId(entry.id);
214 }}
215 onFocus={() => setHighlightedId(entry.id)}
216 >
217 <ComposerBanner.Icon>
218 <FileTextIcon />
219 </ComposerBanner.Icon>
220 <ComposerBanner.Content>
221 <button
222 type="button"
223 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-inset focus-visible:before:ring-ring"
224 data-stash-restore={entry.id}
225 aria-label={gt("Restore stashed prompt: {snippet}", {
226 snippet: stashEntrySnippet(entry, m),
227 })}
228 onPointerDown={(event) => event.preventDefault()}
229 onClick={() => onRestore(entry)}
230 >
231 {stashEntrySnippet(entry, m)}
232 </button>
233 </ComposerBanner.Content>
234 <ComposerBanner.Actions>
235 {entry.pendingImageCount ? (
236 <span className="shrink-0 text-muted-foreground">
237 {gt(
238 "{count, plural, one {saving {count} image…} other {saving {count} images…}}",
239 { count: entry.pendingImageCount },
240 )}
241 </span>
242 ) : missingImageCount(entry) > 0 ? (
243 <span className="shrink-0 text-warning-foreground">
244 {gt(
245 "{count, plural, one {{count} image dropped} other {{count} images dropped}}",
246 { count: missingImageCount(entry) },
247 )}
248 </span>
249 ) : null}
250 {entry.attachments.length > 0 ? (
251 <span className="flex shrink-0 items-center -space-x-1.5">
252 {entry.attachments.slice(0, 3).map((attachment) => (
253 <img
254 key={attachment.id}
255 src={attachment.dataUrl}
256 alt=""
257 aria-hidden="true"
258 className="size-4 rounded border border-border/70 object-cover"
259 />
260 ))}
261 </span>
262 ) : null}
263 {(entry.files?.length ?? 0) > 0 ? (
264 <span className="flex shrink-0 items-center gap-1 text-muted-foreground">
265 <FileIcon className="size-3" aria-hidden />
266 {entry.files!.length}
267 </span>
268 ) : null}
269 <time
270 dateTime={entry.createdAt}
271 className="shrink-0 text-muted-foreground tabular-nums max-sm:hidden"
272 >
273 <RelativeTime timestamp={entry.createdAt} />
274 </time>
275 <ComposerBanner.Dismiss
276 className="z-10"
277 aria-label={gt("Delete stashed prompt")}
278 onPointerDown={(event) => event.preventDefault()}
279 onClick={() => onDelete(entry)}
280 />
281 </ComposerBanner.Actions>
282 </ComposerBanner.Row>
283 ))
284 )}
285 </ComposerBanner.Children>
286 </ComposerBanner.Scroll>
287 </ComposerBanner.Root>
288 );
289});