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

GuestPage.tsx

746 lines27.3 KB

1import {
2 GUEST_MESSAGE_MAX_LENGTH,
3 GUEST_HISTORY_ROUTE,
4 GUEST_NAME_MAX_LENGTH,
5 GUEST_ROUTE_PREFIX,
6 GUEST_SHARE_PARAM,
7 GuestMessageId,
8 type GuestRedeemRequest,
9 type GuestShareView,
10 type GuestThreadModel,
11 OrchestrationV2ThreadHistoryPage,
12 type OrchestrationV2ThreadProjection,
13 type ThreadGuestMessage,
14 type ThreadGuestMessageStatus,
15} from "@t3tools/contracts";
16import * as Option from "effect/Option";
17import * as Schema from "effect/Schema";
18import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
19import { ArrowUpIcon, PaperclipIcon, XIcon } from "lucide-react";
20import {
21 useEffect,
22 useReducer,
23 useRef,
24 useState,
25 type ClipboardEvent,
26 type FormEvent,
27 type KeyboardEvent,
28} from "react";
29import { msg, T, useGT, useMessages } from "gt-react";
30​
31import { m } from "~/i18n/messages";
32​
33import { useDeadlinePassed } from "~/hooks/useDeadline";
34import { useNowMinute } from "~/hooks/useNowMinute";
35import { useStableCallback } from "~/hooks/useStableCallback";
36import { useTheme } from "~/hooks/useTheme";
37import { cn } from "~/lib/utils";
38import { ComposerControl, ComposerControlIcon } from "../chat/ComposerControl";
39import type { ExpandedImagePreview } from "../chat/ExpandedImagePreview";
40import { GuestMessageAttachments } from "../chat/GuestMessageAttachments";
41import { HostImageUrlContext } from "../chat/hostImageUrl";
42import { PierreEntryIcon } from "../chat/PierreEntryIcon";
43import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle";
44import type { MessagesTimelineHistoryControls } from "../chat/MessagesTimeline";
45import { ReadOnlyThreadTimeline } from "../chat/ReadOnlyThreadTimeline";
46import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
47import { getDisplayModelName, getTriggerDisplayModelName } from "../chat/providerIconUtils";
48import type { TimelineRow } from "../chat/timelineRowContext";
49import { GuestHtmlRender } from "./GuestHtmlRender";
50import { Button } from "../ui/button";
51import { Input } from "../ui/input";
52import {
53 applyGuestStreamEvent,
54 formatGuestExpiry,
55 guestAttachmentUrl,
56 guestMediaUrl,
57 createGuestAttachmentUrls,
58 guestFilesProblem,
59 initialGuestStreamState,
60 inviteShareId,
61 type GuestStreamState,
62 parseGuestStreamEvent,
63 unplacedGuestMessages,
64} from "./guestStream.logic";
65import { guestTurnItemSource } from "./guestTurnItemSource";
66​
67interface GuestEntry {
68 /** Unspent invite from the URL hash, if this load came from a link. */
69 readonly credential: string | null;
70 readonly shareId: string | null;
72​
73let capturedEntry: GuestEntry | null = null;
74​
75// A reload keeps the tab's session, so it keeps which messages still wait for a row too.
76const AWAITING_ROWS_KEY = "t3:guest-awaiting-rows";
77const AWAITING_ROWS_LIMIT = 50;
78​
79function readAwaitingRowIds(): ReadonlySet<GuestMessageId> {
80 try {
81 const stored: unknown = JSON.parse(sessionStorage.getItem(AWAITING_ROWS_KEY) ?? "[]");
82 return new Set(
83 Array.isArray(stored)
84 ? stored.filter((id) => typeof id === "string").map((id) => GuestMessageId.make(id))
85 : [],
86 );
87 } catch {
88 return new Set();
89 }
91​
92function writeAwaitingRowIds(ids: ReadonlySet<GuestMessageId>) {
93 try {
94 sessionStorage.setItem(AWAITING_ROWS_KEY, JSON.stringify([...ids].slice(-AWAITING_ROWS_LIMIT)));
95 } catch {}
97​
98/**
99 * The invite credential travels in the URL hash so it never reaches a server log. It is read
100 * once and removed from history, so it lives only in memory. Opening the page never redeems it:
101 * only submitting a name does, so a reload before that leaves the link usable.
102 */
103function takeGuestEntry(): GuestEntry {
104 if (capturedEntry === null) {
105 // A malformed fragment is an invalid link, not a crash.
106 let credential = "";
107 try {
108 credential = decodeURIComponent(window.location.hash.slice(1)).trim();
109 } catch {}
110 const shareId =
111 credential !== ""
112 ? inviteShareId(credential)
113 : new URLSearchParams(window.location.search).get(GUEST_SHARE_PARAM);
114 // The share stays in the URL, so a reload or bookmark finds this browser's session for it.
115 window.history.replaceState(
116 window.history.state,
117 "",
118 shareId === null
119 ? window.location.pathname
120 : `${window.location.pathname}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,
121 );
122 capturedEntry = { credential: credential === "" ? null : credential, shareId };
123 }
124 return capturedEntry;
126​
127const decodeErrorBody = Schema.decodeUnknownOption(Schema.Struct({ message: Schema.String }));
128const decodeHistoryPage = Schema.decodeUnknownOption(
129 Schema.toCodecJson(OrchestrationV2ThreadHistoryPage),
130);
131​
132/** Resolves to the page, or to a message the guest can read. */
133async function fetchGuestHistoryPage(
134 shareId: string,
135 cursor: string,
136): Promise<OrchestrationV2ThreadHistoryPage | string> {
137 const failed = m(msg("Could not load earlier turns. Try again."));
138 try {
139 const response = await fetch(
140 `${GUEST_HISTORY_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&cursor=${encodeURIComponent(cursor)}`,
141 );
142 const json: unknown = await response.json().catch(() => null);
143 if (!response.ok) {
144 return Option.match(decodeErrorBody(json), {
145 onNone: () => failed,
146 onSome: ({ message }) => message,
147 });
148 }
149 return Option.getOrElse(decodeHistoryPage(json), () => failed);
150 } catch {
151 return m(msg("Could not reach the server."));
152 }
154​
155/** Resolves to null on success, or to a message the guest can read. */
156async function postGuest(
157 path: "redeem" | `messages?${string}`,
158 body: typeof GuestRedeemRequest.Encoded | FormData,
159): Promise<string | null> {
160 try {
161 const response = await fetch(
162 `${GUEST_ROUTE_PREFIX}/${path}`,
163 body instanceof FormData
164 ? { method: "POST", body }
165 : {
166 method: "POST",
167 headers: { "content-type": "application/json" },
168 body: JSON.stringify(body),
169 },
170 );
171 if (response.ok) return null;
172 const json: unknown = await response.json().catch(() => null);
173 return Option.match(decodeErrorBody(json), {
174 onNone: () => m(msg("Something went wrong. Try again.")),
175 onSome: ({ message }) => message,
176 });
177 } catch {
178 return m(msg("Could not reach the server."));
179 }
181​
182const STATUS_LABEL: Record<ThreadGuestMessageStatus, string> = {
183 pending: msg("Waiting for approval"),
184 sent: msg("Sent", { $context: "message status" }),
185 dismissed: msg("Not sent"),
186};
187​
188/** Same column as the owner's timeline, so both views wrap text at the same width. */
189const LANE = "chat-content-lane px-4";
190​
191type GuestAccess = "checking" | "session" | "name" | "none";
192​
193export function GuestPage() {
194 const gt = useGT();
195 const [{ credential, shareId }] = useState(takeGuestEntry);
196 // A browser that already joined this share goes straight back in, even from the spent link.
197 // Sessions are per share, so one for another link never stands in for this one.
198 const [access, setAccess] = useState<GuestAccess>(shareId === null ? "none" : "checking");
199 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fetches whether this browser already has a guest session and ignores the answer after cleanup
200 useEffect(() => {
201 if (shareId === null) return;
202 let live = true;
203 void fetch(`${GUEST_ROUTE_PREFIX}/session?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`)
204 .then(
205 (response): GuestAccess =>
206 response.ok ? "session" : credential !== null ? "name" : "none",
207 // Offline: an invite still needs the name form; without one, the stream reports what
208 // it finds once the network is back.
209 (): GuestAccess => (credential !== null ? "name" : "session"),
210 )
211 .then((next) => {
212 if (live) setAccess(next);
213 });
214 return () => {
215 live = false;
216 };
217 }, [credential, shareId]);
218 // Pasting another guest link into this tab changes only the hash, which does not reload the
219 // page; reload so the new invite is read instead of the one already captured.
220 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hashchange listener reloads the page when another guest link is pasted into this tab
221 useEffect(() => {
222 const onHashChange = () => {
223 if (window.location.hash !== "") window.location.reload();
224 };
225 window.addEventListener("hashchange", onHashChange);
226 return () => window.removeEventListener("hashchange", onHashChange);
227 }, []);
228​
229 return (
230 <div className="flex h-dvh flex-col bg-background text-foreground">
231 {access === "checking" ? (
232 <Notice title={gt("Connecting...")} />
233 ) : access === "name" && credential !== null ? (
234 <NameForm
235 credential={credential}
236 onJoined={() => {
237 // The invite is spent; a remount must open the session, not the name form again.
238 capturedEntry = { credential: null, shareId };
239 setAccess("session");
240 }}
241 />
242 ) : access === "session" && shareId !== null ? (
243 <GuestSession shareId={shareId} />
244 ) : (
245 <Notice
246 title={gt("This link has ended or is not valid")}
247 detail={gt("Ask the owner for a new link. Each link works in one browser.")}
248 />
249 )}
250 </div>
251 );
253​
254function GuestSession({ shareId }: { readonly shareId: string }) {
255 const gt = useGT();
256 const [stream, dispatch] = useReducer(applyGuestStreamEvent, null, () => ({
257 ...initialGuestStreamState,
258 awaitingRowIds: readAwaitingRowIds(),
259 }));
260 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- persists the awaiting row ids to sessionStorage so a reload keeps them
261 useEffect(() => writeAwaitingRowIds(stream.awaitingRowIds), [stream.awaitingRowIds]);
262 // EventSource closes for good only on a non-200 response, which the guest routes send for a
263 // missing, invalid, or ended session. Network drops reconnect on their own.
264 const [rejected, setRejected] = useState(false);
265​
266 const [historyLoad, setHistoryLoad] = useState<{
267 readonly cursor: string;
268 readonly error: string | null;
269 } | null>(null);
270 const historyCursor = stream.historyCursor;
271 // A load for an older cursor is stale: a page or a reconnect snapshot moved the cursor on.
272 const currentLoad = historyLoad?.cursor === historyCursor ? historyLoad : null;
273 const loadingHistory = currentLoad !== null && currentLoad.error === null;
274 const historyError = currentLoad?.error ?? null;
275 const loadEarlier = async () => {
276 if (historyCursor === null || loadingHistory) return;
277 setHistoryLoad({ cursor: historyCursor, error: null });
278 const result = await fetchGuestHistoryPage(shareId, historyCursor);
279 if (typeof result === "string") setHistoryLoad({ cursor: historyCursor, error: result });
280 else dispatch({ type: "history-page", cursor: historyCursor, page: result });
281 };
282 const historyControls: MessagesTimelineHistoryControls | undefined =
283 historyCursor === null
284 ? undefined
285 : {
286 hasMoreHistory: true,
287 loading: loadingHistory,
288 error: historyError,
289 onLoadEarlier: () => void loadEarlier(),
290 };
291​
292 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sets document.title to the shared thread's title
293 useEffect(() => {
294 if (stream.view) document.title = stream.view.title;
295 }, [stream.view]);
296​
297 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the guest EventSource stream and closes it on cleanup
298 useEffect(() => {
299 const source = new EventSource(
300 `${GUEST_ROUTE_PREFIX}/stream?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,
301 );
302 source.addEventListener("message", (message) => {
303 const event = parseGuestStreamEvent(message.data);
304 if (event === null) return;
305 dispatch(event);
306 if (event.type === "ended") source.close();
307 });
308 source.addEventListener("error", () => {
309 if (source.readyState === EventSource.CLOSED) setRejected(true);
310 });
311 return () => source.close();
312 }, [shareId]);
313​
314 if (stream.ended || (rejected && stream.view !== null)) {
315 return (
316 <Notice
317 title={gt("This link has ended")}
318 detail={gt("The owner stopped sharing this thread.")}
319 />
320 );
321 }
322 if (stream.view !== null) {
323 if (stream.projection === null) return <Notice title={gt("Connecting...")} />;
324 return (
325 <GuestThread
326 view={stream.view}
327 projection={stream.projection}
328 awaitingRowIds={stream.awaitingRowIds}
329 historyControls={historyControls}
330 />
331 );
332 }
333 if (!rejected) return <Notice title={gt("Connecting...")} />;
334 return (
335 <Notice
336 title={gt("This link has ended or is not valid")}
337 detail={gt("Ask the owner for a new link. Each link works in one browser.")}
338 />
339 );
341​
342function Notice({ title, detail }: { readonly title: string; readonly detail?: string }) {
343 return (
344 <div className="m-auto flex max-w-sm flex-col gap-1 p-6 text-center">
345 <p className="text-sm font-medium">{title}</p>
346 {detail ? <p className="text-xs text-muted-foreground">{detail}</p> : null}
347 </div>
348 );
350​
351function NameForm({
352 credential,
353 onJoined,
354}: {
355 readonly credential: string;
356 readonly onJoined: () => void;
357}) {
358 const gt = useGT();
359 const [name, setName] = useState("");
360 const [submitting, setSubmitting] = useState(false);
361 const [error, setError] = useState<string | null>(null);
362 const submit = async (event: FormEvent) => {
363 event.preventDefault();
364 const trimmed = name.trim();
365 if (trimmed === "" || submitting) return;
366 setSubmitting(true);
367 const failure = await postGuest("redeem", { credential, name: trimmed });
368 setSubmitting(false);
369 if (failure === null) onJoined();
370 else setError(failure);
371 };
372 return (
373 <form className="m-auto flex w-full max-w-xs flex-col gap-3 p-6" onSubmit={submit}>
374 <h1 className="text-base font-medium">
375 <T>Join a shared thread</T>
376 </h1>
377 <label className="flex flex-col gap-1.5 text-sm" htmlFor="guest-name">
378 {gt("Your name")}
379 <Input
380 id="guest-name"
381 autoFocus
382 autoComplete="name"
383 maxLength={GUEST_NAME_MAX_LENGTH}
384 value={name}
385 onChange={(event) => setName(event.target.value)}
386 />
387 </label>
388 {error !== null ? (
389 <p role="alert" className="text-sm text-destructive">
390 {error}
391 </p>
392 ) : null}
393 <Button type="submit" disabled={submitting || name.trim() === ""}>
394 <T context="verb, join a shared thread">Join</T>
395 </Button>
396 <p className="text-xs text-muted-foreground">
397 <T>The owner sees your name and approves each message before the agent gets it.</T>
398 </p>
399 </form>
400 );
402​
403/** The owner's timeline, read-only, with the guest's own messages and composer below it. */
404function GuestThread({
405 view: { shareId, title, expiresAt, messages, model },
406 projection,
407 awaitingRowIds,
408 historyControls,
409}: {
410 readonly view: GuestShareView;
411 readonly projection: OrchestrationV2ThreadProjection;
412 readonly awaitingRowIds: GuestStreamState["awaitingRowIds"];
413 readonly historyControls: MessagesTimelineHistoryControls | undefined;
414}) {
415 // Files load through the guest route.
416 const [attachmentUrls] = useState(() => createGuestAttachmentUrls(shareId));
417 // Expanded rows read detail and command output through the guest routes.
418 const [turnItemSource] = useState(() => guestTurnItemSource(shareId));
419 const openFile = useStableCallback((file: { readonly id: string }) =>
420 openInNewTab(guestAttachmentUrl(shareId, file.id)),
421 );
422 const hostImageUrl = useStableCallback((path: string) => guestMediaUrl(shareId, path));
423 const renderHtmlRender = useStableCallback(
424 (row: Extract<TimelineRow, { kind: "html-render" }>) => (
425 <GuestHtmlRender itemId={row.id} reference={row.htmlRender} shareId={shareId} />
426 ),
427 );
428 return (
429 <>
430 <header className="flex shrink-0 items-center gap-3 border-b border-border px-4 py-2.5">
431 <h1 className="min-w-0 flex-1 truncate text-sm font-medium">{title}</h1>
432 <ExpiryLabel expiresAt={expiresAt} />
433 </header>
434 <HostImageUrlContext value={hostImageUrl}>
435 <ReadOnlyThreadTimeline
436 // No ":" so the timeline finds no environment thread behind the key.
437 threadKey={`guest-${shareId}`}
438 projection={projection}
439 historyControls={historyControls}
440 turnItemSource={turnItemSource}
441 attachmentUrls={attachmentUrls}
442 onImageExpand={openExpandedImage}
443 onFileOpen={openFile}
444 renderHtmlRender={renderHtmlRender}
445 renderFooter={(items) => {
446 const unplaced = unplacedGuestMessages(messages, items, awaitingRowIds);
447 return unplaced.length === 0 ? null : (
448 <ol className="chat-content-lane flex flex-col gap-4 pb-4">
449 {unplaced.map((message) => (
450 <li key={message.id}>
451 <UnplacedGuestMessage shareId={shareId} message={message} />
452 </li>
453 ))}
454 </ol>
455 );
456 }}
457 >
458 {({ scrollToEnd }) => (
459 <div className={cn(LANE, "shrink-0 pb-4")}>
460 <GuestComposer shareId={shareId} model={model} onSent={scrollToEnd} />
461 </div>
462 )}
463 </ReadOnlyThreadTimeline>
464 </HostImageUrlContext>
465 </>
466 );
468​
469function ExpiryLabel({ expiresAt }: { readonly expiresAt: string }) {
470 const expired = useDeadlinePassed(Date.parse(expiresAt));
471 const nowMinute = useNowMinute();
472 const m = useMessages();
473 return (
474 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
475 {expired ? m(msg("Expired")) : formatGuestExpiry(expiresAt, Date.parse(`${nowMinute}Z`), m)}
476 </span>
477 );
479​
480const BUBBLE =
481 "flex min-w-0 max-w-[80%] flex-col gap-2 rounded-2xl p-3 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]";
482​
483const openInNewTab = (url: string) => window.open(url, "_blank", "noopener,noreferrer");
484/** Guests have no image viewer; the browser shows the picture in its own tab. */
485const openExpandedImage = (preview: ExpandedImagePreview) => {
486 const src = preview.images[preview.index]?.src;
487 if (src) openInNewTab(src);
488};
489​
490/** A guest message the owner has not sent yet, or chose not to send. */
491function UnplacedGuestMessage({
492 shareId,
493 message,
494}: {
495 readonly shareId: GuestShareView["shareId"];
496 readonly message: ThreadGuestMessage;
497}) {
498 // A dismissed message's files are deleted, so only their names remain.
499 const served = message.status !== "dismissed";
500 const gt = useGT();
501 const m = useMessages();
502 const url = (attachment: { readonly id: string }) => guestAttachmentUrl(shareId, attachment.id);
503 return (
504 <div className="flex flex-col items-end gap-1">
505 <GuestMessageName name={gt("You", { $context: "the guest's own messages" })} />
506 <div
507 className={cn(
508 BUBBLE,
509 guestBubbleClassName(message.status !== "sent"),
510 message.status === "dismissed" ? "text-muted-foreground" : "text-message-foreground",
511 )}
512 >
513 <GuestMessageAttachments
514 attachments={message.attachments ?? []}
515 imageUrl={(attachment) => (served ? url(attachment) : undefined)}
516 onOpenImage={(attachment) => openInNewTab(url(attachment))}
517 {...(served ? { fileHref: url } : {})}
518 />
519 {message.text ? <span>{message.text}</span> : null}
520 </div>
521 <p className="me-1 text-2xs text-muted-foreground">{m(STATUS_LABEL[message.status])}</p>
522 </div>
523 );
525​
526/** The thread's model, labeled as the owner's composer labels it, with no way to change it. */
527function GuestModelLabel({ model }: { readonly model: GuestThreadModel }) {
528 const label = getTriggerDisplayModelName({ slug: model.name, ...model }, model.driver);
529 const fullLabel = getDisplayModelName({ slug: model.name, ...model });
530 const gt = useGT();
531 return (
532 <ComposerControl
533 render={<span />}
534 aria-label={gt("Model: {model}", { model: fullLabel })}
535 className="pointer-events-none min-w-0 shrink"
536 >
537 {model.driver === null ? null : (
538 <ProviderInstanceIcon
539 driverKind={model.driver}
540 displayName={label}
541 className="size-4"
542 iconClassName="size-4"
543 />
544 )}
545 <span className="min-w-0 truncate" data-chat-provider-model-picker-label="true">
546 {label}
547 </span>
548 </ComposerControl>
549 );
551​
552interface StagedFile {
553 readonly key: string;
554 readonly file: File;
556​
557/** A staged image's thumbnail; its object URL lives as long as the element. */
558function StagedImage({ file }: { readonly file: File }) {
559 return (
560 <img
561 alt={file.name}
562 className="size-full object-cover"
563 ref={(image) => {
564 if (!image) return;
565 const url = URL.createObjectURL(file);
566 image.src = url;
567 return () => URL.revokeObjectURL(url);
568 }}
569 />
570 );
572​
573function GuestComposer({
574 shareId,
575 model,
576 onSent,
577}: {
578 readonly shareId: GuestShareView["shareId"];
579 readonly model: GuestThreadModel;
580 /** The guest's own message comes into view even if they had scrolled up, as the owner's does. */
581 readonly onSent: () => void;
582}) {
583 const gt = useGT();
584 const m = useMessages();
585 const [text, setText] = useState("");
586 const [files, setFiles] = useState<ReadonlyArray<StagedFile>>([]);
587 const [sending, setSending] = useState(false);
588 const [error, setError] = useState<string | null>(null);
589 const fileInputRef = useRef<HTMLInputElement>(null);
590 const nextFileKey = useRef(0);
591 const { resolvedTheme } = useTheme();
592 const addFiles = (added: ReadonlyArray<File>) => {
593 if (added.length === 0) return;
594 const next = [
595 ...files,
596 ...added.map((file) => ({ key: `staged-${nextFileKey.current++}`, file })),
597 ];
598 const problem = guestFilesProblem(
599 next.map((staged) => staged.file),
600 m,
601 );
602 setError(problem);
603 if (problem === null) setFiles(next);
604 };
605 const send = async () => {
606 const trimmed = text.trim();
607 if ((trimmed === "" && files.length === 0) || sending) return;
608 setSending(true);
609 const sentFiles = files;
610 const form = new FormData();
611 form.append("shareId", shareId);
612 form.append("text", trimmed);
613 for (const staged of sentFiles) form.append("file", staged.file, staged.file.name);
614 const failure = await postGuest(
615 `messages?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,
616 form,
617 );
618 setSending(false);
619 setError(failure);
620 // Keep anything typed or attached while the request was in flight.
621 if (failure === null) {
622 onSent();
623 setText((current) => (current.trim() === trimmed ? "" : current));
624 setFiles((current) => current.filter((staged) => !sentFiles.includes(staged)));
625 }
626 };
627 const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
628 // Same as the app composer: Enter sends, Shift+Enter adds a line, IME composition is left alone.
629 if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
630 event.preventDefault();
631 void send();
632 }
633 };
634 // As in the app composer: pasted images attach, and other files attach when no text came along.
635 const onPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
636 const pasted = Array.from(event.clipboardData.files);
637 const hasImage = pasted.some((file) => file.type.startsWith("image/"));
638 if (pasted.length === 0 || (!hasImage && event.clipboardData.getData("text/plain") !== "")) {
639 return;
640 }
641 event.preventDefault();
642 addFiles(pasted);
643 };
644 return (
645 <form
646 className="flex flex-col gap-2 rounded-3xl border border-border bg-card px-4 pt-3 pb-2.5 shadow-composer dark:shadow-composer-dark"
647 onSubmit={(event) => {
648 event.preventDefault();
649 void send();
650 }}
651 onDragOver={(event) => {
652 if (event.dataTransfer.types.includes("Files")) event.preventDefault();
653 }}
654 onDrop={(event) => {
655 if (event.dataTransfer.files.length === 0) return;
656 event.preventDefault();
657 addFiles(Array.from(event.dataTransfer.files));
658 }}
659 >
660 {files.length > 0 ? (
661 <ul className="flex flex-wrap gap-2" aria-label={gt("Attached files")}>
662 {files.map((staged) => (
663 <li
664 key={staged.key}
665 className="flex h-14 min-w-0 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background/70 pe-1"
666 >
667 {staged.file.type.startsWith("image/") ? (
668 <span className="size-14 shrink-0">
669 <StagedImage file={staged.file} />
670 </span>
671 ) : (
672 <span className="flex min-w-0 items-center gap-2 ps-2 text-sm">
673 <PierreEntryIcon pathValue={staged.file.name} kind="file" theme={resolvedTheme} />
674 <span className="max-w-40 truncate">{staged.file.name}</span>
675 <span className="shrink-0 text-xs text-muted-foreground">
676 {formatAttachmentSize(staged.file.size, m)}
677 </span>
678 </span>
679 )}
680 <Button
681 size="icon-xs"
682 variant="ghost-muted"
683 aria-label={gt("Remove {name}", { name: staged.file.name })}
684 onClick={() => {
685 setError(null);
686 setFiles((current) => current.filter((candidate) => candidate !== staged));
687 }}
688 >
689 <XIcon />
690 </Button>
691 </li>
692 ))}
693 </ul>
694 ) : null}
695 <textarea
696 aria-label={gt("Message", { $context: "message input" })}
697 placeholder={gt("Message", { $context: "message input" })}
698 rows={2}
699 maxLength={GUEST_MESSAGE_MAX_LENGTH}
700 value={text}
701 onChange={(event) => setText(event.target.value)}
702 onKeyDown={onKeyDown}
703 onPaste={onPaste}
704 className="max-h-60 min-h-12 w-full resize-none bg-transparent text-sm outline-none field-sizing-content placeholder:text-placeholder"
705 />
706 <div className="flex items-center gap-3">
707 <input
708 ref={fileInputRef}
709 type="file"
710 multiple
711 hidden
712 aria-label={gt("Files to attach")}
713 onChange={(event) => {
714 addFiles(Array.from(event.target.files ?? []));
715 // The same file can be picked again after it is removed.
716 event.target.value = "";
717 }}
718 />
719 <ComposerControl
720 aria-label={gt("Attach files")}
721 onClick={() => fileInputRef.current?.click()}
722 >
723 <ComposerControlIcon icon={PaperclipIcon} />
724 </ComposerControl>
725 <GuestModelLabel model={model} />
726 {error !== null ? (
727 <p role="alert" className="min-w-0 flex-1 text-xs text-destructive">
728 {error}
729 </p>
730 ) : (
731 <p className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
732 <T>The owner approves each message</T>
733 </p>
734 )}
735 <button
736 type="submit"
737 aria-label={gt("Send", { $context: "verb, sends the message" })}
738 disabled={sending || (text.trim() === "" && files.length === 0)}
739 className="flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-message-action text-message-action-foreground shadow-xs hover:bg-message-action-hover focus-visible:outline-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-64"
740 >
741 <ArrowUpIcon aria-hidden className="size-4" />
742 </button>
743 </div>
744 </form>
745 );