feat: Take Screenshot in claim form uploads; Claim Again sends only the form's attachments
- Shared screenshot crop dialog (useScreenshotAttach) used by appointment attachments and the claim form's upload zone (allowScreenshot). - Claim Again no longer merges appointment files into the submit or relinks them to the claim, so an attachment removed in the form stays removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,21 +1,10 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import ReactCrop, { Crop, PixelCrop, centerCrop, makeAspectCrop } from "react-image-crop";
|
|
||||||
import "react-image-crop/dist/ReactCrop.css";
|
|
||||||
import { Paperclip, Image as ImageIcon, Camera, Loader2, Check, RotateCcw, FileText, Trash2 } from "lucide-react";
|
import { Paperclip, Image as ImageIcon, Camera, Loader2, Check, RotateCcw, FileText, Trash2 } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import { apiRequest } from "@/lib/queryClient";
|
import { apiRequest } from "@/lib/queryClient";
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
import { useScreenCapture } from "@/hooks/use-screen-capture";
|
|
||||||
import { ServerAttachmentsPickerModal } from "@/components/file-upload/server-attachments-picker-modal";
|
import { ServerAttachmentsPickerModal } from "@/components/file-upload/server-attachments-picker-modal";
|
||||||
import {
|
import { useScreenshotAttach } from "@/components/file-upload/screenshot-crop-dialog";
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogFooter,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
|
|
||||||
interface AppointmentAttachmentsProps {
|
interface AppointmentAttachmentsProps {
|
||||||
appointmentId: number;
|
appointmentId: number;
|
||||||
@@ -51,28 +40,6 @@ async function deleteAppointmentAttachment(appointmentId: number, fileId: number
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getCroppedDataUrl(image: HTMLImageElement, crop: PixelCrop): string {
|
|
||||||
const scaleX = image.naturalWidth / image.width;
|
|
||||||
const scaleY = image.naturalHeight / image.height;
|
|
||||||
|
|
||||||
const canvas = document.createElement("canvas");
|
|
||||||
canvas.width = crop.width * scaleX;
|
|
||||||
canvas.height = crop.height * scaleY;
|
|
||||||
const ctx = canvas.getContext("2d");
|
|
||||||
ctx?.drawImage(
|
|
||||||
image,
|
|
||||||
crop.x * scaleX,
|
|
||||||
crop.y * scaleY,
|
|
||||||
crop.width * scaleX,
|
|
||||||
crop.height * scaleY,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
canvas.width,
|
|
||||||
canvas.height
|
|
||||||
);
|
|
||||||
return canvas.toDataURL("image/png");
|
|
||||||
}
|
|
||||||
|
|
||||||
async function uploadAppointmentAttachment(
|
async function uploadAppointmentAttachment(
|
||||||
appointmentId: number,
|
appointmentId: number,
|
||||||
patientId: number,
|
patientId: number,
|
||||||
@@ -93,15 +60,6 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment
|
|||||||
const [items, setItems] = useState<AttachmentItem[]>([]);
|
const [items, setItems] = useState<AttachmentItem[]>([]);
|
||||||
const [pickerOpen, setPickerOpen] = useState(false);
|
const [pickerOpen, setPickerOpen] = useState(false);
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
const { capture, isCapturing, countdown } = useScreenCapture();
|
|
||||||
|
|
||||||
// Crop dialog state, shown after a screenshot is captured
|
|
||||||
const [screenshotDataUrl, setScreenshotDataUrl] = useState<string | null>(null);
|
|
||||||
const [screenshotFileName, setScreenshotFileName] = useState("");
|
|
||||||
const [crop, setCrop] = useState<Crop>();
|
|
||||||
const [completedCrop, setCompletedCrop] = useState<PixelCrop>();
|
|
||||||
const imgRef = useRef<HTMLImageElement | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
if (appointmentId) {
|
if (appointmentId) {
|
||||||
@@ -114,25 +72,6 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment
|
|||||||
};
|
};
|
||||||
}, [appointmentId]);
|
}, [appointmentId]);
|
||||||
|
|
||||||
const handleImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
|
|
||||||
imgRef.current = e.currentTarget;
|
|
||||||
const { width, height } = e.currentTarget;
|
|
||||||
const fullCrop = centerCrop(
|
|
||||||
makeAspectCrop({ unit: "%", width: 100 }, width / height, width, height),
|
|
||||||
width,
|
|
||||||
height
|
|
||||||
);
|
|
||||||
setCrop(fullCrop);
|
|
||||||
setCompletedCrop({ unit: "px", x: 0, y: 0, width, height });
|
|
||||||
};
|
|
||||||
|
|
||||||
const closeCropDialog = () => {
|
|
||||||
setScreenshotDataUrl(null);
|
|
||||||
setScreenshotFileName("");
|
|
||||||
setCrop(undefined);
|
|
||||||
setCompletedCrop(undefined);
|
|
||||||
};
|
|
||||||
|
|
||||||
const runUpload = async (file: File) => {
|
const runUpload = async (file: File) => {
|
||||||
if (!patientId) {
|
if (!patientId) {
|
||||||
toast({ title: "Missing patient", description: "Cannot attach files without a patient.", variant: "destructive" });
|
toast({ title: "Missing patient", description: "Cannot attach files without a patient.", variant: "destructive" });
|
||||||
@@ -190,39 +129,12 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment
|
|||||||
files.forEach((file) => void runUpload(file));
|
files.forEach((file) => void runUpload(file));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleScreenshot = async () => {
|
const {
|
||||||
try {
|
takeScreenshot: handleScreenshot,
|
||||||
const dataUrl = await capture();
|
isCapturing,
|
||||||
setScreenshotDataUrl(dataUrl);
|
countdown,
|
||||||
setScreenshotFileName(`screenshot_${Date.now()}`);
|
dialog: screenshotDialog,
|
||||||
} catch (err: any) {
|
} = useScreenshotAttach((file) => void runUpload(file));
|
||||||
toast({
|
|
||||||
title: "Screenshot failed",
|
|
||||||
description: err?.message ?? "Screen capture failed.",
|
|
||||||
variant: "destructive",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRetakeScreenshot = async () => {
|
|
||||||
closeCropDialog();
|
|
||||||
await handleScreenshot();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSaveScreenshot = async () => {
|
|
||||||
if (!screenshotDataUrl) return;
|
|
||||||
const croppedDataUrl =
|
|
||||||
completedCrop && imgRef.current
|
|
||||||
? getCroppedDataUrl(imgRef.current, completedCrop)
|
|
||||||
: screenshotDataUrl;
|
|
||||||
const response = await fetch(croppedDataUrl);
|
|
||||||
const blob = await response.blob();
|
|
||||||
const safeName =
|
|
||||||
screenshotFileName.trim().replace(/[/\\?%*:|"<>]/g, "-") || `screenshot_${Date.now()}`;
|
|
||||||
const file = new File([blob], `${safeName}.png`, { type: "image/png" });
|
|
||||||
closeCropDialog();
|
|
||||||
void runUpload(file);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2 rounded-md border p-3">
|
<div className="space-y-2 rounded-md border p-3">
|
||||||
@@ -319,54 +231,7 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment
|
|||||||
onFilesSelected={handleServerFilesSelected}
|
onFilesSelected={handleServerFilesSelected}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Dialog open={!!screenshotDataUrl} onOpenChange={(open) => !open && closeCropDialog()}>
|
{screenshotDialog}
|
||||||
<DialogContent className="max-w-2xl">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Crop screenshot</DialogTitle>
|
|
||||||
</DialogHeader>
|
|
||||||
{screenshotDataUrl && (
|
|
||||||
<div className="space-y-3">
|
|
||||||
<ReactCrop
|
|
||||||
crop={crop}
|
|
||||||
onChange={(_, percentCrop) => setCrop(percentCrop)}
|
|
||||||
onComplete={(pixelCrop) => setCompletedCrop(pixelCrop)}
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src={screenshotDataUrl}
|
|
||||||
alt="Captured screenshot"
|
|
||||||
onLoad={handleImageLoad}
|
|
||||||
className="w-full rounded-lg border object-contain max-h-96"
|
|
||||||
/>
|
|
||||||
</ReactCrop>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Drag the corners to crop, or leave as-is to attach the full screenshot.
|
|
||||||
</p>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label htmlFor="appointment-screenshot-filename">File name</Label>
|
|
||||||
<div className="flex items-center gap-1">
|
|
||||||
<Input
|
|
||||||
id="appointment-screenshot-filename"
|
|
||||||
value={screenshotFileName}
|
|
||||||
onChange={(e) => setScreenshotFileName(e.target.value)}
|
|
||||||
placeholder="screenshot"
|
|
||||||
/>
|
|
||||||
<span className="text-sm text-muted-foreground">.png</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<DialogFooter>
|
|
||||||
<Button type="button" variant="outline" onClick={handleRetakeScreenshot} disabled={isCapturing}>
|
|
||||||
<RotateCcw className="h-4 w-4 mr-2" />
|
|
||||||
Retake
|
|
||||||
</Button>
|
|
||||||
<Button type="button" onClick={handleSaveScreenshot}>
|
|
||||||
<Check className="h-4 w-4 mr-2" />
|
|
||||||
Attach
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1064,11 +1064,15 @@ export function ClaimForm({
|
|||||||
for (const f of carriedClaimFiles) {
|
for (const f of carriedClaimFiles) {
|
||||||
byFilename.set(f.filename, { filename: f.filename, mimeType: f.mimeType ?? "", ...(f.filePath ? { filePath: f.filePath } : {}) });
|
byFilename.set(f.filename, { filename: f.filename, mimeType: f.mimeType ?? "", ...(f.filePath ? { filePath: f.filePath } : {}) });
|
||||||
}
|
}
|
||||||
for (const f of existingAppointmentFiles) byFilename.set(f.filename, f);
|
// Claim Again: the form's attachment list is final, so an appointment file the user
|
||||||
|
// removed from it isn't added back
|
||||||
|
if (!claimAgainSource) {
|
||||||
|
for (const f of existingAppointmentFiles) byFilename.set(f.filename, f);
|
||||||
|
}
|
||||||
for (const f of newFiles) byFilename.set(f.filename, f);
|
for (const f of newFiles) byFilename.set(f.filename, f);
|
||||||
return Array.from(byFilename.values());
|
return Array.from(byFilename.values());
|
||||||
},
|
},
|
||||||
[existingAppointmentFiles, carriedClaimFiles],
|
[existingAppointmentFiles, carriedClaimFiles, claimAgainSource],
|
||||||
);
|
);
|
||||||
// MH and CCA send file contents to the portal, so the backend reads these from disk by id
|
// MH and CCA send file contents to the portal, so the backend reads these from disk by id
|
||||||
const carriedClaimFileIds = carriedClaimFiles
|
const carriedClaimFileIds = carriedClaimFiles
|
||||||
@@ -1175,7 +1179,7 @@ export function ClaimForm({
|
|||||||
// submission already supplied its own files — otherwise files saved directly on the
|
// submission already supplied its own files — otherwise files saved directly on the
|
||||||
// appointment (e.g. a screenshot attached via the Schedule editor) would never reach
|
// appointment (e.g. a screenshot attached via the Schedule editor) would never reach
|
||||||
// the insurance upload at all.
|
// the insurance upload at all.
|
||||||
skipAppointmentAttachmentMerge: !!autoSubmit && !!uploadedFiles?.length,
|
skipAppointmentAttachmentMerge: (!!autoSubmit && !!uploadedFiles?.length) || !!claimAgainSource,
|
||||||
});
|
});
|
||||||
|
|
||||||
// 5. Close form
|
// 5. Close form
|
||||||
@@ -1312,7 +1316,7 @@ export function ClaimForm({
|
|||||||
insuranceSiteKey: "CCA",
|
insuranceSiteKey: "CCA",
|
||||||
claimId: createdClaim.id,
|
claimId: createdClaim.id,
|
||||||
carriedClaimFileIds,
|
carriedClaimFileIds,
|
||||||
skipAppointmentAttachmentMerge: !!autoSubmit && !!uploadedFiles?.length,
|
skipAppointmentAttachmentMerge: (!!autoSubmit && !!uploadedFiles?.length) || !!claimAgainSource,
|
||||||
});
|
});
|
||||||
|
|
||||||
onClose();
|
onClose();
|
||||||
@@ -2913,6 +2917,7 @@ export function ClaimForm({
|
|||||||
acceptedFileTypes="application/pdf,image/jpeg,image/jpg,image/png,image/webp"
|
acceptedFileTypes="application/pdf,image/jpeg,image/jpg,image/png,image/webp"
|
||||||
maxFiles={10}
|
maxFiles={10}
|
||||||
patientId={patientId}
|
patientId={patientId}
|
||||||
|
allowScreenshot
|
||||||
/>
|
/>
|
||||||
{form.uploadedFiles.length > 0 && (
|
{form.uploadedFiles.length > 0 && (
|
||||||
<ul className="text-sm text-gray-700 list-disc ml-6">
|
<ul className="text-sm text-gray-700 list-disc ml-6">
|
||||||
@@ -3551,6 +3556,7 @@ export function ClaimForm({
|
|||||||
acceptedFileTypes="application/pdf,image/jpeg,image/jpg,image/png,image/webp"
|
acceptedFileTypes="application/pdf,image/jpeg,image/jpg,image/png,image/webp"
|
||||||
maxFiles={10}
|
maxFiles={10}
|
||||||
patientId={patientId}
|
patientId={patientId}
|
||||||
|
allowScreenshot
|
||||||
/>
|
/>
|
||||||
{form.uploadedFiles.length > 0 && (
|
{form.uploadedFiles.length > 0 && (
|
||||||
<ul className="text-sm text-gray-700 list-disc ml-6">
|
<ul className="text-sm text-gray-700 list-disc ml-6">
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ import React, {
|
|||||||
forwardRef,
|
forwardRef,
|
||||||
useImperativeHandle,
|
useImperativeHandle,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { Upload, X, FilePlus } from "lucide-react";
|
import { Upload, X, FilePlus, Camera, Loader2 } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { ServerAttachmentsPickerModal } from "@/components/file-upload/server-attachments-picker-modal";
|
import { ServerAttachmentsPickerModal } from "@/components/file-upload/server-attachments-picker-modal";
|
||||||
|
import { useScreenshotAttach } from "@/components/file-upload/screenshot-crop-dialog";
|
||||||
|
|
||||||
export type MultipleFileUploadZoneHandle = {
|
export type MultipleFileUploadZoneHandle = {
|
||||||
getFiles: () => File[];
|
getFiles: () => File[];
|
||||||
@@ -29,6 +30,8 @@ interface FileUploadZoneProps {
|
|||||||
// OPTIONAL: when set, shows a "Choose from Server" option listing this patient's
|
// OPTIONAL: when set, shows a "Choose from Server" option listing this patient's
|
||||||
// previously saved Cloud Storage attachments (e.g. Copy Agent screenshots)
|
// previously saved Cloud Storage attachments (e.g. Copy Agent screenshots)
|
||||||
patientId?: number;
|
patientId?: number;
|
||||||
|
// OPTIONAL: shows a "Take Screenshot" button that captures, crops and adds a PNG
|
||||||
|
allowScreenshot?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MultipleFileUploadZone = forwardRef<
|
export const MultipleFileUploadZone = forwardRef<
|
||||||
@@ -44,6 +47,7 @@ export const MultipleFileUploadZone = forwardRef<
|
|||||||
maxFileSizeMB = 10, // default fallback per-file size (MB)
|
maxFileSizeMB = 10, // default fallback per-file size (MB)
|
||||||
maxFileSizeByType, // optional per-type overrides, e.g. { "application/pdf": 10, "image/*": 2 }
|
maxFileSizeByType, // optional per-type overrides, e.g. { "application/pdf": 10, "image/*": 2 }
|
||||||
patientId,
|
patientId,
|
||||||
|
allowScreenshot = false,
|
||||||
},
|
},
|
||||||
ref
|
ref
|
||||||
) => {
|
) => {
|
||||||
@@ -307,6 +311,44 @@ export const MultipleFileUploadZone = forwardRef<
|
|||||||
notify(newFiles);
|
notify(newFiles);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const screenshot = useScreenshotAttach((file) => handleFiles([file]));
|
||||||
|
|
||||||
|
const screenshotButton = allowScreenshot ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={screenshot.isCapturing}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
void screenshot.takeScreenshot();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{screenshot.isCapturing ? (
|
||||||
|
screenshot.countdown != null ? (
|
||||||
|
<span className="mr-2 w-4 text-center">{screenshot.countdown}</span>
|
||||||
|
) : (
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<Camera className="mr-2 h-4 w-4" />
|
||||||
|
)}
|
||||||
|
Take Screenshot
|
||||||
|
</Button>
|
||||||
|
) : null;
|
||||||
|
|
||||||
|
const serverButton = patientId ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setIsServerPickerOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Choose from Server
|
||||||
|
</Button>
|
||||||
|
) : null;
|
||||||
|
|
||||||
// expose imperative handle to parent
|
// expose imperative handle to parent
|
||||||
useImperativeHandle(
|
useImperativeHandle(
|
||||||
ref,
|
ref,
|
||||||
@@ -384,6 +426,12 @@ export const MultipleFileUploadZone = forwardRef<
|
|||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
{(serverButton || screenshotButton) && (
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{serverButton}
|
||||||
|
{screenshotButton}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{/* prominent per-type size badges */}
|
{/* prominent per-type size badges */}
|
||||||
<div className="flex flex-wrap gap-2 justify-center mt-2">
|
<div className="flex flex-wrap gap-2 justify-center mt-2">
|
||||||
{parsedAccept.map((t) => {
|
{parsedAccept.map((t) => {
|
||||||
@@ -456,18 +504,8 @@ export const MultipleFileUploadZone = forwardRef<
|
|||||||
>
|
>
|
||||||
Choose from This Computer
|
Choose from This Computer
|
||||||
</Button>
|
</Button>
|
||||||
{patientId ? (
|
{serverButton}
|
||||||
<Button
|
{screenshotButton}
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
setIsServerPickerOpen(true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Choose from Server
|
|
||||||
</Button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -481,6 +519,8 @@ export const MultipleFileUploadZone = forwardRef<
|
|||||||
onFilesSelected={(files) => handleFiles(files)}
|
onFilesSelected={(files) => handleFiles(files)}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{allowScreenshot ? screenshot.dialog : null}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import { useRef, useState } from "react";
|
||||||
|
import ReactCrop, { Crop, PixelCrop, centerCrop, makeAspectCrop } from "react-image-crop";
|
||||||
|
import "react-image-crop/dist/ReactCrop.css";
|
||||||
|
import { Check, RotateCcw } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
import { useScreenCapture } from "@/hooks/use-screen-capture";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogFooter,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
|
||||||
|
function getCroppedDataUrl(image: HTMLImageElement, crop: PixelCrop): string {
|
||||||
|
const scaleX = image.naturalWidth / image.width;
|
||||||
|
const scaleY = image.naturalHeight / image.height;
|
||||||
|
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = crop.width * scaleX;
|
||||||
|
canvas.height = crop.height * scaleY;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
ctx?.drawImage(
|
||||||
|
image,
|
||||||
|
crop.x * scaleX,
|
||||||
|
crop.y * scaleY,
|
||||||
|
crop.width * scaleX,
|
||||||
|
crop.height * scaleY,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
canvas.width,
|
||||||
|
canvas.height
|
||||||
|
);
|
||||||
|
return canvas.toDataURL("image/png");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Take a screenshot, let the user crop and name it, then hand back a PNG File.
|
||||||
|
* Returns `takeScreenshot` to start a capture, the capture state for the button,
|
||||||
|
* and `dialog` to render once somewhere in the caller.
|
||||||
|
*/
|
||||||
|
export function useScreenshotAttach(onAttach: (file: File) => void) {
|
||||||
|
const { capture, isCapturing, countdown } = useScreenCapture();
|
||||||
|
const [dataUrl, setDataUrl] = useState<string | null>(null);
|
||||||
|
const [fileName, setFileName] = useState("");
|
||||||
|
const [crop, setCrop] = useState<Crop>();
|
||||||
|
const [completedCrop, setCompletedCrop] = useState<PixelCrop>();
|
||||||
|
const imgRef = useRef<HTMLImageElement | null>(null);
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
setDataUrl(null);
|
||||||
|
setFileName("");
|
||||||
|
setCrop(undefined);
|
||||||
|
setCompletedCrop(undefined);
|
||||||
|
};
|
||||||
|
|
||||||
|
const takeScreenshot = async () => {
|
||||||
|
try {
|
||||||
|
const url = await capture();
|
||||||
|
setDataUrl(url);
|
||||||
|
setFileName(`screenshot_${Date.now()}`);
|
||||||
|
} catch (err: any) {
|
||||||
|
toast({
|
||||||
|
title: "Screenshot failed",
|
||||||
|
description: err?.message ?? "Screen capture failed.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
|
||||||
|
imgRef.current = e.currentTarget;
|
||||||
|
const { width, height } = e.currentTarget;
|
||||||
|
setCrop(
|
||||||
|
centerCrop(makeAspectCrop({ unit: "%", width: 100 }, width / height, width, height), width, height)
|
||||||
|
);
|
||||||
|
setCompletedCrop({ unit: "px", x: 0, y: 0, width, height });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRetake = async () => {
|
||||||
|
close();
|
||||||
|
await takeScreenshot();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAttach = async () => {
|
||||||
|
if (!dataUrl) return;
|
||||||
|
const croppedDataUrl =
|
||||||
|
completedCrop && imgRef.current ? getCroppedDataUrl(imgRef.current, completedCrop) : dataUrl;
|
||||||
|
const blob = await (await fetch(croppedDataUrl)).blob();
|
||||||
|
const safeName = fileName.trim().replace(/[/\\?%*:|"<>]/g, "-") || `screenshot_${Date.now()}`;
|
||||||
|
const file = new File([blob], `${safeName}.png`, { type: "image/png" });
|
||||||
|
close();
|
||||||
|
onAttach(file);
|
||||||
|
};
|
||||||
|
|
||||||
|
const dialog = (
|
||||||
|
<Dialog open={!!dataUrl} onOpenChange={(open) => !open && close()}>
|
||||||
|
<DialogContent className="max-w-2xl" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Crop screenshot</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
{dataUrl && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<ReactCrop
|
||||||
|
crop={crop}
|
||||||
|
onChange={(_, percentCrop) => setCrop(percentCrop)}
|
||||||
|
onComplete={(pixelCrop) => setCompletedCrop(pixelCrop)}
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={dataUrl}
|
||||||
|
alt="Captured screenshot"
|
||||||
|
onLoad={handleImageLoad}
|
||||||
|
className="w-full rounded-lg border object-contain max-h-96"
|
||||||
|
/>
|
||||||
|
</ReactCrop>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Drag the corners to crop, or leave as-is to attach the full screenshot.
|
||||||
|
</p>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="screenshot-filename">File name</Label>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Input
|
||||||
|
id="screenshot-filename"
|
||||||
|
value={fileName}
|
||||||
|
onChange={(e) => setFileName(e.target.value)}
|
||||||
|
placeholder="screenshot"
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-muted-foreground">.png</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<DialogFooter>
|
||||||
|
<Button type="button" variant="outline" onClick={handleRetake} disabled={isCapturing}>
|
||||||
|
<RotateCcw className="h-4 w-4 mr-2" />
|
||||||
|
Retake
|
||||||
|
</Button>
|
||||||
|
<Button type="button" onClick={handleAttach}>
|
||||||
|
<Check className="h-4 w-4 mr-2" />
|
||||||
|
Attach
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
|
||||||
|
return { takeScreenshot, isCapturing, countdown, dialog };
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user