The best way to control Claude Code, Codex and more from any computer or phone

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