feat: 替换原题图片时与导入题目一样先裁剪,截取选中区域作为新的原题图片

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
margrop
2026-10-19 18:16:33 +08:00
parent 56d1f94b46
commit 172eea6167

View File

@@ -1,8 +1,9 @@
"use client";
import { useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { ImagePlus, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ImageCropper } from "@/components/image-cropper";
import { useLanguage } from "@/contexts/LanguageContext";
import { apiClient } from "@/lib/api-client";
import { frontendLogger } from "@/lib/frontend-logger";
@@ -15,25 +16,39 @@ interface ReplaceQuestionImageButtonProps {
onDone: (originalImageUrl: string) => void;
}
/** 选择新图片(超过 1MB 时压缩)替换原题图片 */
/**
* 替换原题图片:与导入题目一样,先选择图片并截取题目所在区域,再保存截取结果(超过 1MB 时压缩)
*/
export function ReplaceQuestionImageButton({ errorItemId, hasImage, onDone }: ReplaceQuestionImageButtonProps) {
const { t } = useLanguage();
const inputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
// 待裁剪图片的 object URL,关闭裁剪框或换图时释放
const [croppingImage, setCroppingImage] = useState<string | null>(null);
useEffect(() => () => {
if (croppingImage) URL.revokeObjectURL(croppingImage);
}, [croppingImage]);
const handleClick = () => {
if (hasImage && !confirm(t.replaceImage.confirm)) return;
inputRef.current?.click();
};
const handleFile = async (file: File | undefined) => {
const handleFile = (file: File | undefined) => {
if (!file) return;
if (!file.type.startsWith("image/")) {
alert(t.replaceImage.invalid);
return;
}
setCroppingImage(URL.createObjectURL(file));
};
const handleCropComplete = async (croppedBlob: Blob) => {
setCroppingImage(null);
setUploading(true);
try {
const file = new File([croppedBlob], "question-image.jpg", { type: croppedBlob.type || "image/jpeg" });
const imageDataUrl = await processImageFile(file);
const result = await apiClient.put<{ originalImageUrl: string }>(`/api/error-items/${errorItemId}/image`, { imageDataUrl });
onDone(result.originalImageUrl);
@@ -55,10 +70,18 @@ export function ReplaceQuestionImageButton({ errorItemId, hasImage, onDone }: Re
accept="image/png,image/jpeg,image/webp,image/gif"
className="hidden"
onChange={(e) => {
void handleFile(e.target.files?.[0]);
handleFile(e.target.files?.[0]);
e.target.value = "";
}}
/>
{croppingImage && (
<ImageCropper
imageSrc={croppingImage}
open
onClose={() => setCroppingImage(null)}
onCropComplete={handleCropComplete}
/>
)}
<Button variant="outline" size="sm" onClick={handleClick} disabled={uploading} className="flex items-center gap-2">
{uploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <ImagePlus className="h-4 w-4" />}
{uploading ? t.replaceImage.uploading : hasImage ? t.replaceImage.replace : t.replaceImage.add}