import { t } from "../lib/console-text"; import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type ClipboardEvent, } from "react"; import { CameraIcon, ImagePlusIcon, MessageSquareIcon, ThumbsDownIcon, ThumbsUpIcon, XIcon, } from "lucide-react"; import type { OpenGeniClient } from "@opengeni/sdk"; import type { CreateFeedbackRequest, FeedbackContext, FeedbackSentiment } from "@opengeni/sdk"; import { Button } from "../../ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../../ui/dialog"; import { Label } from "../../ui/label"; import { Textarea } from "../../ui/textarea"; import { userErrorText } from "../../ui/api-error"; import { feedbackDialogCopy, feedbackSentimentLabel, feedbackSubmission, } from "../../session-feedback-model"; import { FEEDBACK_SCREENSHOT_MAX_COUNT, captureScreen, prepareFeedbackImage, screenCaptureKind, untilGone, type FeedbackImage, } from "../lib/feedback-capture"; type FeedbackClient = Pick; /** Screenshots in a report: taking, adding, pasting and removing them. */ function useFeedbackImages() { const [images, setImages] = useState([]); const imagesRef = useRef(images); imagesRef.current = images; useEffect( () => () => imagesRef.current.forEach((image) => URL.revokeObjectURL(image.previewUrl)), [], ); const add = useCallback(async (blobs: ReadonlyArray<{ blob: Blob; name: string }>) => { const room = FEEDBACK_SCREENSHOT_MAX_COUNT - imagesRef.current.length; const prepared = await Promise.all( blobs.slice(0, Math.max(room, 0)).map(({ blob, name }) => prepareFeedbackImage(blob, name)), ); const ready = prepared.filter((image): image is FeedbackImage => image !== null); setImages((current) => { const kept = [...current, ...ready].slice(0, FEEDBACK_SCREENSHOT_MAX_COUNT); ready .filter((image) => !kept.includes(image)) .forEach((image) => URL.revokeObjectURL(image.previewUrl)); return kept; }); return ready.length === Math.min(blobs.length, Math.max(room, 0)); }, []); const remove = useCallback((id: string) => { setImages((current) => { current .filter((image) => image.id === id) .forEach((image) => URL.revokeObjectURL(image.previewUrl)); return current.filter((image) => image.id !== id); }); }, []); const clear = useCallback(() => { setImages((current) => { current.forEach((image) => URL.revokeObjectURL(image.previewUrl)); return []; }); }, []); return { images, add, remove, clear }; } export function FeedbackDialog(props: { client: FeedbackClient; workspaceId: string; sessionId?: string | undefined; turnId?: string | undefined; sentiment?: FeedbackSentiment | undefined; open: boolean; onOpenChange: (open: boolean) => void; onSubmitted?: ((sentiment: FeedbackSentiment | undefined) => void) | undefined; /** * Facts about the app sent with the report (web or desktop, versions, page, * recent errors), read when it is sent. See webFeedbackContext. */ reportContext?: (() => FeedbackContext) | undefined; /** * Let the person attach screenshots. The desktop app takes one of the page * as the dialog opens; browsers take one when asked, and every app can add * or paste an image. */ screenshots?: boolean | undefined; }) { const [comment, setComment] = useState(""); const [busy, setBusy] = useState(false); const [submissionError, setError] = useState(null); const [imageNote, setImageNote] = useState(null); // The dialog steps out of view while a screenshot is taken. const [capturing, setCapturing] = useState(false); const pending = useRef(null); const submitting = useRef(false); const fieldId = useId(); const fileInput = useRef(null); const copy = feedbackDialogCopy(t, props); const { images, add, remove, clear } = useFeedbackImages(); const captureKind = props.screenshots ? screenCaptureKind() : null; const full = images.length >= FEEDBACK_SCREENSHOT_MAX_COUNT; const takeScreenshot = useCallback( async (options: { waitFor: string }) => { setImageNote(null); setCapturing(true); try { await untilGone(options.waitFor); const shot = await captureScreen(); if (shot.kind === "ok") { const added = await add([{ blob: shot.blob, name: "Screenshot" }]); if (!added) setImageNote("Couldn't use that screenshot. You can add or paste one instead."); } else if (shot.kind === "failed") { setImageNote("Couldn't take a screenshot. You can add or paste one instead."); } } finally { setCapturing(false); } }, [add], ); // The desktop app attaches a still of the page as the dialog opens, taken // once the menu that opened it is gone. It can be removed like any other. // A layout effect, so the dialog never shows before stepping aside. const opened = useRef(false); useLayoutEffect(() => { if (!props.open) { opened.current = false; return; } if (opened.current) return; opened.current = true; if (captureKind === "window" && images.length === 0) void takeScreenshot({ waitFor: '[role="menu"]' }); // oxlint-disable-next-line react-hooks/exhaustive-deps -- only as the dialog opens }, [props.open]); async function addFiles(files: ReadonlyArray) { const pictures = files.filter((file) => file.type.startsWith("image/")); if (pictures.length === 0) return; setImageNote(null); const added = await add(pictures.map((file) => ({ blob: file, name: file.name || "Image" }))); if (!added) setImageNote("Some images couldn't be added. Use PNG or JPEG, up to three."); } function onPaste(event: ClipboardEvent) { if (!props.screenshots || full) return; const files = Array.from(event.clipboardData.files).filter((file) => file.type.startsWith("image/"), ); if (files.length === 0) return; event.preventDefault(); void addFiles(files); } async function submit() { if (submitting.current) return; pending.current = feedbackSubmission( { sessionId: props.sessionId, turnId: props.turnId, sentiment: props.sentiment, comment: comment || undefined, ...(props.reportContext ? { context: props.reportContext() } : {}), ...(images.length > 0 ? { screenshots: images.map((image) => image.upload) } : {}), }, pending.current, () => crypto.randomUUID(), ); submitting.current = true; setBusy(true); setError(null); try { await props.client.createFeedback(props.workspaceId, pending.current!); pending.current = null; setComment(""); clear(); setImageNote(null); props.onSubmitted?.(props.sentiment); props.onOpenChange(false); } catch (error) { setError(`Couldn't send feedback. ${userErrorText(error, "Try again.")}`); } finally { submitting.current = false; setBusy(false); } } return ( { if (!busy && !capturing) props.onOpenChange(open); }} > {copy.title} {copy.description} {props.sentiment ? (

{feedbackSentimentLabel(t, props.sentiment)}

) : null}