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

ComposerStashMenu.tsx

371 lines15.3 KB

1import { msg, T, useGT, useMessages, Var, plural, part } 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;
15const COMPOSER_TEXTBOX_SELECTOR = 'textarea, [role="textbox"]';
16const snippetGraphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
17​
18// A stash action can close the menu before the held key stops repeating.
19function suppressHeldKey(key: "Backspace" | "Enter", composerForm: HTMLFormElement | null) {
20 const heldKey = new AbortController();
21 const capture = { capture: true, signal: heldKey.signal };
22 const onKey = (event: KeyboardEvent) => {
23 if (event.key !== key) return;
24 // A fresh press also clears the listener if the browser missed the keyup.
25 if (event.type === "keyup" || !event.repeat) {
26 heldKey.abort();
27 return;
28 }
29 if (!(event.target instanceof Node && composerForm?.contains(event.target))) return;
30 event.preventDefault();
31 event.stopPropagation();
32 };
33 window.addEventListener("keydown", onKey, capture);
34 window.addEventListener("keyup", onKey, capture);
35 window.addEventListener("blur", () => heldKey.abort(), { signal: heldKey.signal });
37​
38function missingImageCount(entry: PromptStashEntry): number {
39 return entry.droppedImageNames.length + (entry.unreadableImageNames?.length ?? 0);
41​
42export function stashEntrySnippet(entry: PromptStashEntry, resolve: MessageResolver = m): string {
43 const trimmed = assistantCitationsToPlainText(
44 composerFileLinksToPlainText(
45 replaceComposerContextReferences(entry.prompt, (reference) => reference.label),
46 ),
47 )
48 .trim()
49 .replace(/\s+/g, " ");
50 if (trimmed.length > 0) {
51 if (trimmed.length <= SNIPPET_MAX_CHARS) return trimmed;
52 const end =
53 snippetGraphemes.segment(trimmed).containing(SNIPPET_MAX_CHARS)?.index ?? SNIPPET_MAX_CHARS;
54 return `${trimmed.slice(0, end).trimEnd()}…`;
55 }
56 const imageCount =
57 entry.attachments.length + missingImageCount(entry) + (entry.pendingImageCount ?? 0);
58 const fileCount = entry.files?.length ?? 0;
59 const attachmentCount = imageCount + fileCount;
60 if (attachmentCount === 0) {
61 return resolve(msg("(empty)"));
62 }
63 if (imageCount > 0 && fileCount > 0) {
64 return resolve(
65 msg`${plural(
66 { count: attachmentCount },
67 {
68 one: part`(${{ count: attachmentCount }} attachment)`,
69 other: part`(${{ count: attachmentCount }} attachments)`,
70 },
71 )}`,
72 );
73 }
74 return fileCount > 0
75 ? resolve(
76 msg`${plural(
77 { count: attachmentCount },
78 {
79 one: part`(${{ count: attachmentCount }} file)`,
80 other: part`(${{ count: attachmentCount }} files)`,
81 },
82 )}`,
83 )
84 : resolve(
85 msg`${plural(
86 { count: attachmentCount },
87 {
88 one: part`(${{ count: attachmentCount }} image)`,
89 other: part`(${{ count: attachmentCount }} images)`,
90 },
91 )}`,
92 );
94​
95/** Window capture gives the open menu priority over composer key handlers. */
96export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
97 entries: ReadonlyArray<PromptStashEntry>;
98 stashShortcutLabel: string | null;
99 composerFormRef: RefObject<HTMLFormElement | null>;
100 onRestore: (entry: PromptStashEntry) => void;
101 onDelete: (entry: PromptStashEntry) => void;
102 onClose: () => void;
103}) {
104 const { entries, stashShortcutLabel, composerFormRef, onRestore, onDelete, onClose } = props;
105 const gt = useGT();
106 const m = useMessages();
107 const [highlightedId, setHighlightedId] = useState<string | null>(entries[0]?.id ?? null);
108​
109 const highlightedEntry = entries.find((entry) => entry.id === highlightedId) ?? entries[0];
110 const drawerRef = useRef<HTMLDivElement>(null);
111 const focusBeforeOpenRef = useRef<HTMLElement | null>(null);
112​
113 // Both listeners read entries, highlight and callbacks at event time, so they subscribe
114 // once for the menu's lifetime instead of on every highlight change.
115 const closeOnOutsidePointer = useEffectEvent((event: PointerEvent) => {
116 const drawer = drawerRef.current;
117 if (
118 (drawer && event.composedPath().includes(drawer)) ||
119 (event.target instanceof Element && event.target.closest('[data-prompt-stash-badge="true"]'))
120 ) {
121 return;
122 }
123 onClose();
124 });
125​
126 const handleKeyDown = useEffectEvent((event: KeyboardEvent) => {
127 if (event.isComposing || event.keyCode === 229) return;
128 const drawer = drawerRef.current;
129 if (!drawer) return;
130 const target = event.target;
131 if (
132 !(target instanceof Node) ||
133 (target !== document.body &&
134 !(target instanceof Element && target.closest('[data-prompt-stash-badge="true"]')) &&
135 !drawer.contains(target) &&
136 !composerFormRef.current?.querySelector(COMPOSER_TEXTBOX_SELECTOR)?.contains(target))
137 ) {
138 return;
139 }
140 if (event.key === "Escape") {
141 event.preventDefault();
142 event.stopPropagation();
143 onClose();
144 const focusBeforeOpen = focusBeforeOpenRef.current;
145 if (focusBeforeOpen?.isConnected) focusBeforeOpen.focus({ preventScroll: true });
146 return;
147 }
148 if (event.key === "ArrowDown" || event.key === "ArrowUp") {
149 if (entries.length === 0) return;
150 if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey) return;
151 event.preventDefault();
152 event.stopPropagation();
153 const currentIndex = entries.findIndex((entry) => entry.id === highlightedEntry?.id);
154 const offset = event.key === "ArrowDown" ? 1 : -1;
155 const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;
156 const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;
157 setHighlightedId(entries[nextIndex]?.id ?? null);
158 const nextButton =
159 drawer.querySelectorAll<HTMLButtonElement>("[data-stash-restore]")[nextIndex];
160 nextButton?.scrollIntoView({ block: "nearest" });
161 if (drawer.contains(document.activeElement)) {
162 nextButton?.focus({ preventScroll: true });
163 }
164 return;
165 }
166 if (event.key === "Enter") {
167 if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey) {
168 // A focused restore button would otherwise fire its native click.
169 if (
170 target instanceof Element &&
171 drawer.contains(target) &&
172 target.closest("[data-stash-restore]")
173 ) {
174 event.preventDefault();
175 }
176 return;
177 }
178 // Enter on a restore button follows the highlight, which can move without focus.
179 if (
180 drawer.contains(target) &&
181 target instanceof Element &&
182 target.closest("button[aria-label]:not([data-stash-restore])")
183 ) {
184 return;
185 }
186 if (!highlightedEntry) return;
187 event.preventDefault();
188 event.stopPropagation();
189 if (event.repeat) return;
190 suppressHeldKey("Enter", composerFormRef.current);
191 onRestore(highlightedEntry);
192 return;
193 }
194 if (event.key === "Backspace" && (event.metaKey || event.ctrlKey)) {
195 if (!highlightedEntry) return;
196 event.preventDefault();
197 event.stopPropagation();
198 if (event.repeat) return;
199 suppressHeldKey("Backspace", composerFormRef.current);
200 onDelete(highlightedEntry);
201 }
202 });
203​
204 const focusOnOpen = useEffectEvent(() => {
205 const drawer = drawerRef.current;
206 const active = document.activeElement;
207 if (!drawer || !active || active === document.body || drawer.contains(active)) return;
208 // StrictMode replays this effect after focus has moved, so keep the first opener.
209 if (active instanceof HTMLElement && !focusBeforeOpenRef.current) {
210 focusBeforeOpenRef.current = active;
211 }
212 if (active.closest('[data-prompt-stash-badge="true"], [role="dialog"], [role="alertdialog"]')) {
213 return;
214 }
215 const textbox = composerFormRef.current?.querySelector<HTMLElement>(COMPOSER_TEXTBOX_SELECTOR);
216 if (textbox?.contains(active)) return;
217 const disabledSelector =
218 ':disabled, [aria-disabled="true"], [aria-readonly="true"], [contenteditable="false"]';
219 if (textbox && !textbox.matches(disabledSelector)) textbox.focus({ preventScroll: true });
220 if (!textbox?.contains(document.activeElement)) drawer.focus({ preventScroll: true });
221 });
222​
223 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves initial focus when opened from outside the composer and subscribes capture-phase listeners
224 useEffect(() => {
225 focusOnOpen();
226 const onPointerDown = (event: PointerEvent) => closeOnOutsidePointer(event);
227 const onKeyDown = (event: KeyboardEvent) => handleKeyDown(event);
228 document.addEventListener("pointerdown", onPointerDown, true);
229 window.addEventListener("keydown", onKeyDown, true);
230 return () => {
231 document.removeEventListener("pointerdown", onPointerDown, true);
232 window.removeEventListener("keydown", onKeyDown, true);
233 };
234 }, []);
235​
236 return (
237 <ComposerBanner.Root
238 ref={drawerRef}
239 tabIndex={-1}
240 className="flex min-h-0 flex-col focus:outline-none after:shrink-0"
241 data-composer-stash-drawer="true"
242 >
243 <ComposerBanner.Row
244 render={<button type="button" />}
245 aria-label={gt`Close stash`}
246 aria-expanded="true"
247 onPointerDown={(event) => event.preventDefault()}
248 onClick={onClose}
249 >
250 <ComposerBanner.Icon>
251 <BookmarkIcon />
252 </ComposerBanner.Icon>
253 <ComposerBanner.Content className="text-muted-foreground">
254 {gt({ context: "noun, saved prompts set aside for later" })`Stash`}
255 </ComposerBanner.Content>
256 <ComposerBanner.Actions>
257 <ComposerBanner.Count>{entries.length}</ComposerBanner.Count>
258 <ComposerBanner.ToggleIcon expanded />
259 </ComposerBanner.Actions>
260 </ComposerBanner.Row>
261 <ComposerBanner.Scroll className="flex flex-col">
262 <ComposerBanner.Children render={<ul role="list" />} aria-label={gt`Stashed prompts`}>
263 {entries.length === 0 ? (
264 <ComposerBanner.Row render={<li />}>
265 <ComposerBanner.Icon />
266 <ComposerBanner.Content className="text-muted-foreground">
267 <T>Nothing stashed yet.</T>
268 {stashShortcutLabel ? (
269 <>
270 {" "}
271 <T>
272 Press <Var>{stashShortcutLabel}</Var> with a prompt in the composer to stash
273 it.
274 </T>
275 </>
276 ) : null}
277 </ComposerBanner.Content>
278 </ComposerBanner.Row>
279 ) : (
280 entries.map((entry) => (
281 <ComposerBanner.Row
282 render={<li />}
283 key={entry.id}
284 data-stash-entry={entry.id}
285 data-highlighted={highlightedEntry?.id === entry.id || undefined}
286 className={cn(
287 "relative rounded-sm",
288 highlightedEntry?.id === entry.id && "bg-accent text-accent-foreground",
289 )}
290 onMouseMove={() => {
291 if (highlightedId !== entry.id) setHighlightedId(entry.id);
292 }}
293 onFocus={() => setHighlightedId(entry.id)}
294 >
295 <ComposerBanner.Icon>
296 <FileTextIcon />
297 </ComposerBanner.Icon>
298 <ComposerBanner.Content>
299 <button
300 type="button"
301 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"
302 data-stash-restore={entry.id}
303 aria-label={gt`Restore stashed prompt: ${{ snippet: stashEntrySnippet(entry, m) }}`}
304 onPointerDown={(event) => event.preventDefault()}
305 onClick={() => onRestore(entry)}
306 >
307 {stashEntrySnippet(entry, m)}
308 </button>
309 </ComposerBanner.Content>
310 <ComposerBanner.Actions>
311 {entry.pendingImageCount ? (
312 <span className="shrink-0 text-muted-foreground">
313 {gt`${plural(
314 { count: entry.pendingImageCount },
315 {
316 one: part`saving ${{ count: entry.pendingImageCount }} image…`,
317 other: part`saving ${{ count: entry.pendingImageCount }} images…`,
318 },
319 )}`}
320 </span>
321 ) : missingImageCount(entry) > 0 ? (
322 <span className="shrink-0 text-warning-foreground">
323 {gt`${plural(
324 { count: missingImageCount(entry) },
325 {
326 one: part`${{ count: missingImageCount(entry) }} image dropped`,
327 other: part`${{ count: missingImageCount(entry) }} images dropped`,
328 },
329 )}`}
330 </span>
331 ) : null}
332 {entry.attachments.length > 0 ? (
333 <span className="flex shrink-0 items-center -space-x-1.5">
334 {entry.attachments.slice(0, 3).map((attachment) => (
335 <img
336 key={attachment.id}
337 src={attachment.dataUrl}
338 alt=""
339 aria-hidden="true"
340 className="size-4 rounded border border-border/70 object-cover"
341 />
342 ))}
343 </span>
344 ) : null}
345 {(entry.files?.length ?? 0) > 0 ? (
346 <span className="flex shrink-0 items-center gap-1 text-muted-foreground">
347 <FileIcon className="size-3" aria-hidden />
348 {entry.files!.length}
349 </span>
350 ) : null}
351 <time
352 dateTime={entry.createdAt}
353 className="shrink-0 text-muted-foreground tabular-nums max-sm:hidden"
354 >
355 <RelativeTime timestamp={entry.createdAt} />
356 </time>
357 <ComposerBanner.Dismiss
358 className="z-10"
359 aria-label={gt`Delete stashed prompt`}
360 onPointerDown={(event) => event.preventDefault()}
361 onClick={() => onDelete(entry)}
362 />
363 </ComposerBanner.Actions>
364 </ComposerBanner.Row>
365 ))
366 )}
367 </ComposerBanner.Children>
368 </ComposerBanner.Scroll>
369 </ComposerBanner.Root>
370 );
371});