mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-06 13:50:02 +08:00
refactor: 拆分 upload-zone 组件为子组件与 hook
- 将上传区拆分为 drag-drop-area、image-source-buttons、paste-screenshot-buttons 三个子组件 - 将文件校验、粘贴/拖拽处理、剪贴板/截图逻辑抽成 use-upload-files hook - 新增纯函数 clipboardImageToFile、extractImageFromPasteEvent、isClipboardReadSupported、isScreenshotSupported 及单元测试 - 保持对外接口 UploadZone 不变,DOM 结构与 className 完全兼容
This commit is contained in:
142
src/__tests__/unit/upload-files.test.ts
Normal file
142
src/__tests__/unit/upload-files.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import {
|
||||
clipboardImageToFile,
|
||||
extractImageFromPasteEvent,
|
||||
isClipboardReadSupported,
|
||||
isScreenshotSupported,
|
||||
} from "@/lib/use-upload-files";
|
||||
|
||||
describe("use-upload-files 纯函数", () => {
|
||||
describe("clipboardImageToFile", () => {
|
||||
it("无名字的 Blob 按类型生成文件名", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-11-04T12:00:00Z"));
|
||||
const blob = new Blob(["x"], { type: "image/png" });
|
||||
const file = clipboardImageToFile(blob);
|
||||
expect(file).toBeInstanceOf(File);
|
||||
expect(file.name).toMatch(/^clipboard-\d+\.png$/);
|
||||
expect(file.type).toBe("image/png");
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("Blob 缺少 type 时回退为 image/png", () => {
|
||||
const blob = new Blob(["x"]);
|
||||
const file = clipboardImageToFile(blob);
|
||||
expect(file.type).toBe("image/png");
|
||||
expect(file.name).toMatch(/\.png$/);
|
||||
});
|
||||
|
||||
it("带名字的 File 原样返回", () => {
|
||||
const original = new File(["x"], "pasted.png", { type: "image/png" });
|
||||
expect(clipboardImageToFile(original)).toBe(original);
|
||||
});
|
||||
|
||||
it("File 名字为空字符串时生成新名字", () => {
|
||||
const emptyName = new File(["x"], "", { type: "image/jpeg" });
|
||||
const file = clipboardImageToFile(emptyName);
|
||||
expect(file.name).toMatch(/^clipboard-\d+\.jpeg$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractImageFromPasteEvent", () => {
|
||||
const makeEvent = (items: Partial<DataTransferItem>[], target: EventTarget | null = null): ClipboardEvent =>
|
||||
({ clipboardData: { items }, target }) as unknown as ClipboardEvent;
|
||||
|
||||
it("提取第一个图片 item", () => {
|
||||
const png = new File(["x"], "a.png", { type: "image/png" });
|
||||
const event = makeEvent([
|
||||
{ kind: "string", type: "text/plain" },
|
||||
{ kind: "file", type: "image/png", getAsFile: () => png },
|
||||
]);
|
||||
expect(extractImageFromPasteEvent(event)).toBe(png);
|
||||
});
|
||||
|
||||
it("没有图片时返回 null", () => {
|
||||
const event = makeEvent([{ kind: "string", type: "text/plain" }]);
|
||||
expect(extractImageFromPasteEvent(event)).toBeNull();
|
||||
});
|
||||
|
||||
it("clipboardData 缺失时返回 null", () => {
|
||||
const event = { clipboardData: null } as unknown as ClipboardEvent;
|
||||
expect(extractImageFromPasteEvent(event)).toBeNull();
|
||||
});
|
||||
|
||||
it("目标是 INPUT 时不拦截(返回 null)", () => {
|
||||
const png = new File(["x"], "a.png", { type: "image/png" });
|
||||
const target = document.createElement("input");
|
||||
const event = makeEvent(
|
||||
[{ kind: "file", type: "image/png", getAsFile: () => png }],
|
||||
target,
|
||||
);
|
||||
expect(extractImageFromPasteEvent(event)).toBeNull();
|
||||
});
|
||||
|
||||
it("目标是 contentEditable 元素时不拦截(返回 null)", () => {
|
||||
const png = new File(["x"], "a.png", { type: "image/png" });
|
||||
const target = document.createElement("div");
|
||||
Object.defineProperty(target, "isContentEditable", { value: true });
|
||||
const event = makeEvent(
|
||||
[{ kind: "file", type: "image/png", getAsFile: () => png }],
|
||||
target,
|
||||
);
|
||||
expect(extractImageFromPasteEvent(event)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isClipboardReadSupported", () => {
|
||||
const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
value: { read: vi.fn() },
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalClipboard) {
|
||||
Object.defineProperty(navigator, "clipboard", originalClipboard);
|
||||
} else {
|
||||
// @ts-expect-error 恢复为未定义
|
||||
delete navigator.clipboard;
|
||||
}
|
||||
});
|
||||
|
||||
it("客户端且支持 clipboard.read 时返回 true", () => {
|
||||
expect(isClipboardReadSupported(true)).toBe(true);
|
||||
});
|
||||
|
||||
it("非客户端(SSR)时返回 false", () => {
|
||||
expect(isClipboardReadSupported(false)).toBe(false);
|
||||
});
|
||||
|
||||
it("缺少 clipboard API 时返回 false", () => {
|
||||
// @ts-expect-error 模拟不支持的环境
|
||||
delete navigator.clipboard;
|
||||
expect(isClipboardReadSupported(true)).toBe(false);
|
||||
});
|
||||
|
||||
it("clipboard.read 不是函数时返回 false", () => {
|
||||
Object.defineProperty(navigator, "clipboard", { value: {}, configurable: true });
|
||||
expect(isClipboardReadSupported(true)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isScreenshotSupported", () => {
|
||||
it("非客户端(SSR)时返回 false", () => {
|
||||
expect(isScreenshotSupported(false)).toBe(false);
|
||||
});
|
||||
|
||||
it("客户端但缺少 getDisplayMedia 时返回 false", () => {
|
||||
const originalMediaDevices = Object.getOwnPropertyDescriptor(navigator, "mediaDevices");
|
||||
Object.defineProperty(navigator, "mediaDevices", { value: {}, configurable: true });
|
||||
expect(isScreenshotSupported(true)).toBe(false);
|
||||
if (originalMediaDevices) {
|
||||
Object.defineProperty(navigator, "mediaDevices", originalMediaDevices);
|
||||
} else {
|
||||
// @ts-expect-error 恢复为未定义
|
||||
delete navigator.mediaDevices;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,59 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState, useEffect, useRef } from "react";
|
||||
import type { ChangeEvent } from "react";
|
||||
import { useDropzone } from "react-dropzone";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Camera, ClipboardPaste, FolderOpen, Images, Loader2, Monitor, UploadCloud } from "lucide-react";
|
||||
import { useLanguage } from "@/contexts/LanguageContext";
|
||||
import { getAndroidAppBridge } from "@/lib/android-app";
|
||||
import { frontendLogger } from "@/lib/frontend-logger";
|
||||
import { toast } from "@/lib/feedback";
|
||||
import { useIsClient } from "@/lib/use-is-client";
|
||||
|
||||
// 添加 CaptureController 类型声明
|
||||
declare global {
|
||||
interface CaptureController {
|
||||
setFocusBehavior(behavior: 'no-focus-change' | 'focus-capturing-application'): void;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
CaptureController: {
|
||||
new(): CaptureController;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拖拽区与「从文件选择」接受的类型:image/* 加常见扩展名。部分系统不认识 HEIC/HEIF 的 MIME(报告为空或 octet-stream),
|
||||
* 按扩展名放行,选择后再按文件头识别真实格式。
|
||||
*/
|
||||
const IMAGE_ACCEPT = { "image/*": [".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".heic", ".heif"] };
|
||||
|
||||
/**
|
||||
* 检测是否有摄像头:只在浏览器提供 mediaDevices 时判断(HTTP 页面和部分 WebView 不提供,此时不阻止拍照)。
|
||||
* 不请求权限,只读取设备种类。
|
||||
* 安卓 App 中拍照由原生调用系统相机应用(ACTION_IMAGE_CAPTURE),WebView 的设备枚举不代表原生相机能力,
|
||||
* 因此不据此拦截,相机不可用时由原生提示。
|
||||
*/
|
||||
function useCameraAvailability(): boolean | null {
|
||||
const [available, setAvailable] = useState<boolean | null>(null);
|
||||
useEffect(() => {
|
||||
if (getAndroidAppBridge()) return;
|
||||
if (typeof navigator === "undefined" || !navigator.mediaDevices?.enumerateDevices) return;
|
||||
let cancelled = false;
|
||||
navigator.mediaDevices.enumerateDevices()
|
||||
.then((devices) => {
|
||||
if (!cancelled) setAvailable(devices.some((device) => device.kind === "videoinput"));
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
return available;
|
||||
}
|
||||
import { useUploadZone, isScreenshotSupported } from "@/lib/use-upload-files";
|
||||
import { DragDropArea } from "./upload-zone/drag-drop-area";
|
||||
import { HiddenFileInputs, ImageSourceButtons } from "./upload-zone/image-source-buttons";
|
||||
import { PasteButton, ScreenshotButton } from "./upload-zone/paste-screenshot-buttons";
|
||||
|
||||
interface UploadZoneProps {
|
||||
onImageSelect: (file: File) => void; // 改为传递 File 对象
|
||||
@@ -61,347 +11,46 @@ interface UploadZoneProps {
|
||||
}
|
||||
|
||||
export function UploadZone({ onImageSelect, isAnalyzing }: UploadZoneProps) {
|
||||
const { t } = useLanguage();
|
||||
const [isScreenshotting, setIsScreenshotting] = useState(false);
|
||||
// 确保只在客户端渲染屏幕截图功能
|
||||
const isClient = useIsClient();
|
||||
|
||||
useEffect(() => {
|
||||
// 请求通知权限
|
||||
if ('Notification' in window && Notification.permission === 'default') {
|
||||
Notification.requestPermission();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const onDrop = useCallback(
|
||||
(acceptedFiles: File[]) => {
|
||||
const file = acceptedFiles[0];
|
||||
if (file) {
|
||||
// 直接传递 File 对象,让父组件处理压缩
|
||||
onImageSelect(file);
|
||||
}
|
||||
},
|
||||
[onImageSelect]
|
||||
);
|
||||
|
||||
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
||||
onDrop,
|
||||
accept: IMAGE_ACCEPT,
|
||||
maxFiles: 1,
|
||||
disabled: isAnalyzing,
|
||||
});
|
||||
|
||||
// 拍照、相册、文件三个独立入口:拍照用 capture 直接打开相机;相册只限图片;文件不限类型,作为相册中找不到照片时的兜底
|
||||
const hasCamera = useCameraAvailability();
|
||||
const cameraInput = useRef<HTMLInputElement>(null);
|
||||
const albumInput = useRef<HTMLInputElement>(null);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const handlePicked = (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
// 清空以便再次选择同一文件(如重拍后选同名照片)也能触发
|
||||
event.target.value = "";
|
||||
if (file) onImageSelect(file);
|
||||
};
|
||||
const openSource = (key: "camera" | "album" | "file") => {
|
||||
if (key === "camera" && hasCamera === false) {
|
||||
toast.warning(t.upload.noCamera);
|
||||
return;
|
||||
}
|
||||
({ camera: cameraInput, album: albumInput, file: fileInput })[key].current?.click();
|
||||
};
|
||||
// 将剪贴板中的图片 Blob 转为 File 并交给父组件
|
||||
const selectClipboardImage = useCallback(
|
||||
(blob: Blob) => {
|
||||
const type = blob.type || "image/png";
|
||||
const ext = type.split("/")[1] || "png";
|
||||
const file = blob instanceof File && blob.name
|
||||
? blob
|
||||
: new File([blob], `clipboard-${Date.now()}.${ext}`, { type });
|
||||
onImageSelect(file);
|
||||
},
|
||||
[onImageSelect]
|
||||
);
|
||||
|
||||
// 监听 Ctrl/Cmd+V 粘贴图片
|
||||
useEffect(() => {
|
||||
const handlePaste = (event: ClipboardEvent) => {
|
||||
if (isAnalyzing) return;
|
||||
|
||||
// 在输入框中粘贴时不拦截
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target && (target.isContentEditable || ["INPUT", "TEXTAREA"].includes(target.tagName))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const items = Array.from(event.clipboardData?.items ?? []);
|
||||
const imageItem = items.find((item) => item.kind === "file" && item.type.startsWith("image/"));
|
||||
const file = imageItem?.getAsFile();
|
||||
if (!file) return;
|
||||
|
||||
event.preventDefault();
|
||||
selectClipboardImage(file);
|
||||
};
|
||||
|
||||
window.addEventListener("paste", handlePaste);
|
||||
return () => window.removeEventListener("paste", handlePaste);
|
||||
}, [isAnalyzing, selectClipboardImage]);
|
||||
|
||||
// 检查是否支持通过按钮读取剪贴板(需要安全上下文)
|
||||
const isClipboardReadSupported = () => {
|
||||
return isClient &&
|
||||
typeof navigator !== 'undefined' &&
|
||||
!!navigator.clipboard &&
|
||||
typeof navigator.clipboard.read === 'function';
|
||||
};
|
||||
|
||||
// 点击按钮读取剪贴板图片
|
||||
const handleClipboardRead = async () => {
|
||||
if (!isClipboardReadSupported()) {
|
||||
toast.warning(t.upload.pasteNotSupported);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const clipboardItems = await navigator.clipboard.read();
|
||||
for (const item of clipboardItems) {
|
||||
const imageType = item.types.find((type) => type.startsWith("image/"));
|
||||
if (imageType) {
|
||||
const blob = await item.getType(imageType);
|
||||
selectClipboardImage(blob);
|
||||
return;
|
||||
}
|
||||
}
|
||||
toast.warning(t.upload.pasteNoImage);
|
||||
} catch (error) {
|
||||
frontendLogger.warn('[UploadZone]', 'Clipboard read failed', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
if (error instanceof Error && error.name === 'NotAllowedError') {
|
||||
toast.warning(t.upload.pastePermissionDenied);
|
||||
} else {
|
||||
toast.error(t.upload.pasteFailed);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 检查是否支持屏幕截图
|
||||
const isScreenshotSupported = () => {
|
||||
return isClient &&
|
||||
typeof navigator !== 'undefined' &&
|
||||
'mediaDevices' in navigator &&
|
||||
'getDisplayMedia' in navigator.mediaDevices;
|
||||
};
|
||||
// 屏幕截图功能
|
||||
const handleScreenshot = async () => {
|
||||
if (!isScreenshotSupported()) {
|
||||
toast.warning(t.upload.screenshotNotSupported);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsScreenshotting(true);
|
||||
|
||||
try {
|
||||
// 创建 CaptureController 来控制焦点行为
|
||||
let controller: CaptureController | undefined;
|
||||
if ('CaptureController' in window) {
|
||||
controller = new window.CaptureController();
|
||||
}
|
||||
|
||||
// 请求屏幕共享权限,优先当前标签页
|
||||
const displayMediaOptions: DisplayMediaStreamOptions & {
|
||||
preferCurrentTab?: boolean;
|
||||
controller?: CaptureController;
|
||||
} = {
|
||||
video: true,
|
||||
audio: false,
|
||||
preferCurrentTab: false, // 优先显示"此标签页"选项
|
||||
};
|
||||
|
||||
if (controller) {
|
||||
displayMediaOptions.controller = controller;
|
||||
}
|
||||
|
||||
const stream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
|
||||
|
||||
// 获取视频轨道并检查捕获类型
|
||||
const [videoTrack] = stream.getVideoTracks();
|
||||
const settings = videoTrack.getSettings();
|
||||
const displaySurface = settings.displaySurface; // 'browser' 表示标签页
|
||||
|
||||
// 如果是标签页或窗口,设置不切换焦点
|
||||
if (controller && (displaySurface === 'browser' || displaySurface === 'window')) {
|
||||
try {
|
||||
controller.setFocusBehavior('no-focus-change'); // 关键:不切换焦点到选中标签页
|
||||
frontendLogger.info('[UploadZone]', 'Screenshot focus behavior set to no-change', undefined, { sendToBackend: false });
|
||||
} catch (e) {
|
||||
frontendLogger.warn('[UploadZone]', 'Unable to set screenshot focus behavior', { error: e });
|
||||
}
|
||||
}
|
||||
|
||||
// 创建视频元素
|
||||
const video = document.createElement('video');
|
||||
video.srcObject = stream;
|
||||
video.muted = true;
|
||||
video.autoplay = true;
|
||||
video.playsInline = true;
|
||||
|
||||
// 等待视频准备并播放
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
video.onloadedmetadata = () => {
|
||||
video.play().then(() => {
|
||||
resolve();
|
||||
}).catch(reject);
|
||||
};
|
||||
video.onerror = reject;
|
||||
});
|
||||
|
||||
// 等待一帧渲染(确保稳定)
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
|
||||
// 检查视频尺寸
|
||||
if (video.videoWidth === 0 || video.videoHeight === 0) {
|
||||
throw new Error('视频没有有效尺寸');
|
||||
}
|
||||
|
||||
// 创建canvas并捕获
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = video.videoWidth;
|
||||
canvas.height = video.videoHeight;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) {
|
||||
throw new Error('无法获取canvas上下文');
|
||||
}
|
||||
|
||||
// 绘制视频帧
|
||||
ctx.drawImage(video, 0, 0);
|
||||
|
||||
// 停止屏幕共享
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
|
||||
// 转换为blob并创建文件
|
||||
canvas.toBlob((blob) => {
|
||||
if (blob) {
|
||||
const file = new File([blob], `screenshot-${Date.now()}.png`, {
|
||||
type: 'image/png'
|
||||
});
|
||||
onImageSelect(file);
|
||||
frontendLogger.info('[UploadZone]', 'Screenshot captured', undefined, { sendToBackend: false });
|
||||
} else {
|
||||
toast.error('截图转换失败');
|
||||
}
|
||||
}, 'image/png', 1.0);
|
||||
|
||||
} catch (error) {
|
||||
frontendLogger.error('[UploadZone]', 'Screenshot failed', { error });
|
||||
if (error instanceof Error) {
|
||||
if (error.name === 'NotAllowedError') {
|
||||
toast.warning(t.upload.screenshotPermissionDenied);
|
||||
} else {
|
||||
toast.error(`${t.upload.screenshotFailed}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setIsScreenshotting(false);
|
||||
}
|
||||
};
|
||||
const sources = [
|
||||
{ key: "camera" as const, icon: Camera, label: t.upload.camera, desc: t.upload.cameraDesc },
|
||||
{ key: "album" as const, icon: Images, label: t.upload.album, desc: t.upload.albumDesc },
|
||||
{ key: "file" as const, icon: FolderOpen, label: t.upload.file, desc: t.upload.fileDesc },
|
||||
];
|
||||
const zone = useUploadZone({ onImageSelect, isAnalyzing });
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 隐藏的选择器始终存在,桌面端「从文件选择」也可用 */}
|
||||
<input ref={cameraInput} type="file" accept="image/*" capture="environment" className="hidden" onChange={handlePicked} data-testid="camera-input" />
|
||||
<input ref={albumInput} type="file" accept="image/*" className="hidden" onChange={handlePicked} data-testid="album-input" />
|
||||
<input ref={fileInput} type="file" className="hidden" onChange={handlePicked} data-testid="file-input" />
|
||||
<HiddenFileInputs
|
||||
cameraInput={zone.cameraInput}
|
||||
albumInput={zone.albumInput}
|
||||
fileInput={zone.fileInput}
|
||||
handlePicked={zone.handlePicked}
|
||||
/>
|
||||
{/* 触屏设备(手机、平板)显示拍照、相册、文件三个独立入口;用 CSS 媒体查询判断,不依赖渲染时的状态 */}
|
||||
{isClient && (
|
||||
<div className="hidden grid-cols-3 gap-2 pointer-coarse:grid" data-testid="image-sources">
|
||||
{sources.map((source) => (
|
||||
<Button
|
||||
key={source.key}
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => openSource(source.key)}
|
||||
disabled={isAnalyzing}
|
||||
className="flex h-auto flex-col gap-1 py-3"
|
||||
aria-description={source.desc}
|
||||
>
|
||||
<source.icon className="h-6 w-6" />
|
||||
<span className="text-sm font-medium">{source.label}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{zone.isClient && (
|
||||
<ImageSourceButtons
|
||||
openSource={zone.openSource}
|
||||
isAnalyzing={zone.isAnalyzing}
|
||||
/>
|
||||
)}
|
||||
<Card
|
||||
{...getRootProps()}
|
||||
className={`group cursor-pointer rounded-2xl border-2 border-dashed shadow-none transition-all hover:border-primary/60 hover:bg-accent/40 ${isDragActive ? "border-primary bg-accent/60" : "border-border bg-card"
|
||||
}`}
|
||||
>
|
||||
<CardContent className="flex min-h-[260px] flex-col items-center justify-center space-y-4 py-10 text-center md:min-h-[300px]">
|
||||
<input {...getInputProps()} />
|
||||
<div className="rounded-2xl bg-accent p-4 text-primary transition-transform group-hover:scale-105">
|
||||
{isAnalyzing ? (
|
||||
<Loader2 className="h-10 w-10 animate-spin" />
|
||||
) : (
|
||||
<UploadCloud className="h-10 w-10" />
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{isAnalyzing ? t.app.analyzing : t.upload.analyze}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isAnalyzing ? t.app.analyzing : t.app.dragDrop}
|
||||
</p>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
{t.upload.support}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<DragDropArea
|
||||
getRootProps={zone.getRootProps}
|
||||
getInputProps={zone.getInputProps}
|
||||
isDragActive={zone.isDragActive}
|
||||
isAnalyzing={zone.isAnalyzing}
|
||||
/>
|
||||
<div className="flex flex-col sm:flex-row sm:flex-wrap items-stretch sm:items-start justify-center gap-4">
|
||||
{/* 剪贴板粘贴按钮 - 只在客户端渲染 */}
|
||||
{isClient && (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleClipboardRead}
|
||||
disabled={isAnalyzing}
|
||||
className="flex items-center gap-2 w-full sm:w-auto"
|
||||
>
|
||||
<ClipboardPaste className="h-4 w-4" />
|
||||
{t.upload.paste}
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
{t.upload.pasteDesc}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{/* 屏幕截图按钮 - 只在客户端渲染 */}
|
||||
{isScreenshotSupported() && (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleScreenshot}
|
||||
disabled={isAnalyzing || isScreenshotting}
|
||||
className="flex items-center gap-2 w-full sm:w-auto"
|
||||
>
|
||||
{isScreenshotting ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Monitor className="h-4 w-4" />
|
||||
)}
|
||||
{isScreenshotting ? t.common.pleaseWait : t.upload.screenshot}
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
{t.upload.screenshotDesc}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{/* 剪贴板粘贴按钮 - 只在客户端渲染 */}
|
||||
{zone.isClient && (
|
||||
<PasteButton
|
||||
onPaste={() => { void zone.handleClipboardRead(); }}
|
||||
isAnalyzing={zone.isAnalyzing}
|
||||
/>
|
||||
)}
|
||||
{/* 屏幕截图按钮 - 只在客户端渲染 */}
|
||||
{zone.isClient && isScreenshotSupported(zone.isClient) && (
|
||||
<ScreenshotButton
|
||||
onScreenshot={() => { void zone.handleScreenshot(); }}
|
||||
isAnalyzing={zone.isAnalyzing}
|
||||
isScreenshotting={zone.isScreenshotting}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
48
src/components/upload-zone/drag-drop-area.tsx
Normal file
48
src/components/upload-zone/drag-drop-area.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import type { HTMLAttributes, InputHTMLAttributes } from "react";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Loader2, UploadCloud } from "lucide-react";
|
||||
import { useLanguage } from "@/contexts/LanguageContext";
|
||||
|
||||
interface DragDropAreaProps {
|
||||
getRootProps: () => HTMLAttributes<HTMLElement>;
|
||||
getInputProps: () => InputHTMLAttributes<HTMLInputElement>;
|
||||
isDragActive: boolean;
|
||||
isAnalyzing: boolean;
|
||||
}
|
||||
|
||||
/** 拖拽/点击上传区域 */
|
||||
export function DragDropArea({ getRootProps, getInputProps, isDragActive, isAnalyzing }: DragDropAreaProps) {
|
||||
const { t } = useLanguage();
|
||||
|
||||
return (
|
||||
<Card
|
||||
{...getRootProps()}
|
||||
className={`group cursor-pointer rounded-2xl border-2 border-dashed shadow-none transition-all hover:border-primary/60 hover:bg-accent/40 ${isDragActive ? "border-primary bg-accent/60" : "border-border bg-card"
|
||||
}`}
|
||||
>
|
||||
<CardContent className="flex min-h-[260px] flex-col items-center justify-center space-y-4 py-10 text-center md:min-h-[300px]">
|
||||
<input {...getInputProps()} />
|
||||
<div className="rounded-2xl bg-accent p-4 text-primary transition-transform group-hover:scale-105">
|
||||
{isAnalyzing ? (
|
||||
<Loader2 className="h-10 w-10 animate-spin" />
|
||||
) : (
|
||||
<UploadCloud className="h-10 w-10" />
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{isAnalyzing ? t.app.analyzing : t.upload.analyze}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isAnalyzing ? t.app.analyzing : t.app.dragDrop}
|
||||
</p>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
{t.upload.support}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
58
src/components/upload-zone/image-source-buttons.tsx
Normal file
58
src/components/upload-zone/image-source-buttons.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import type { ChangeEvent, RefObject } from "react";
|
||||
import { Camera, FolderOpen, Images } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLanguage } from "@/contexts/LanguageContext";
|
||||
|
||||
interface ImageSourceButtonsProps {
|
||||
openSource: (key: "camera" | "album" | "file") => void;
|
||||
isAnalyzing: boolean;
|
||||
}
|
||||
|
||||
/** 触屏设备(手机、平板)的拍照、相册、文件三个独立入口;用 CSS 媒体查询判断,不依赖渲染时的状态 */
|
||||
export function ImageSourceButtons({ openSource, isAnalyzing }: ImageSourceButtonsProps) {
|
||||
const { t } = useLanguage();
|
||||
const sources = [
|
||||
{ key: "camera" as const, icon: Camera, label: t.upload.camera, desc: t.upload.cameraDesc },
|
||||
{ key: "album" as const, icon: Images, label: t.upload.album, desc: t.upload.albumDesc },
|
||||
{ key: "file" as const, icon: FolderOpen, label: t.upload.file, desc: t.upload.fileDesc },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="hidden grid-cols-3 gap-2 pointer-coarse:grid" data-testid="image-sources">
|
||||
{sources.map((source) => (
|
||||
<Button
|
||||
key={source.key}
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => openSource(source.key)}
|
||||
disabled={isAnalyzing}
|
||||
className="flex h-auto flex-col gap-1 py-3"
|
||||
aria-description={source.desc}
|
||||
>
|
||||
<source.icon className="h-6 w-6" />
|
||||
<span className="text-sm font-medium">{source.label}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface HiddenFileInputsProps {
|
||||
cameraInput: RefObject<HTMLInputElement | null>;
|
||||
albumInput: RefObject<HTMLInputElement | null>;
|
||||
fileInput: RefObject<HTMLInputElement | null>;
|
||||
handlePicked: (event: ChangeEvent<HTMLInputElement>) => void;
|
||||
}
|
||||
|
||||
/** 隐藏的文件选择器始终存在,桌面端「从文件选择」也可用 */
|
||||
export function HiddenFileInputs({ cameraInput, albumInput, fileInput, handlePicked }: HiddenFileInputsProps) {
|
||||
return (
|
||||
<>
|
||||
<input ref={cameraInput} type="file" accept="image/*" capture="environment" className="hidden" onChange={handlePicked} data-testid="camera-input" />
|
||||
<input ref={albumInput} type="file" accept="image/*" className="hidden" onChange={handlePicked} data-testid="album-input" />
|
||||
<input ref={fileInput} type="file" className="hidden" onChange={handlePicked} data-testid="file-input" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
64
src/components/upload-zone/paste-screenshot-buttons.tsx
Normal file
64
src/components/upload-zone/paste-screenshot-buttons.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
"use client";
|
||||
|
||||
import { ClipboardPaste, Loader2, Monitor } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLanguage } from "@/contexts/LanguageContext";
|
||||
|
||||
interface PasteButtonProps {
|
||||
onPaste: () => void;
|
||||
isAnalyzing: boolean;
|
||||
}
|
||||
|
||||
/** 剪贴板粘贴按钮 */
|
||||
export function PasteButton({ onPaste, isAnalyzing }: PasteButtonProps) {
|
||||
const { t } = useLanguage();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onPaste}
|
||||
disabled={isAnalyzing}
|
||||
className="flex items-center gap-2 w-full sm:w-auto"
|
||||
>
|
||||
<ClipboardPaste className="h-4 w-4" />
|
||||
{t.upload.paste}
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
{t.upload.pasteDesc}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ScreenshotButtonProps {
|
||||
onScreenshot: () => void;
|
||||
isAnalyzing: boolean;
|
||||
isScreenshotting: boolean;
|
||||
}
|
||||
|
||||
/** 屏幕截图按钮 */
|
||||
export function ScreenshotButton({ onScreenshot, isAnalyzing, isScreenshotting }: ScreenshotButtonProps) {
|
||||
const { t } = useLanguage();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onScreenshot}
|
||||
disabled={isAnalyzing || isScreenshotting}
|
||||
className="flex items-center gap-2 w-full sm:w-auto"
|
||||
>
|
||||
{isScreenshotting ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Monitor className="h-4 w-4" />
|
||||
)}
|
||||
{isScreenshotting ? t.common.pleaseWait : t.upload.screenshot}
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
{t.upload.screenshotDesc}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
341
src/lib/use-upload-files.ts
Normal file
341
src/lib/use-upload-files.ts
Normal file
@@ -0,0 +1,341 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState, useEffect, useRef } from "react";
|
||||
import type { ChangeEvent } from "react";
|
||||
import { useDropzone } from "react-dropzone";
|
||||
import { useLanguage } from "@/contexts/LanguageContext";
|
||||
import { getAndroidAppBridge } from "@/lib/android-app";
|
||||
import { toast } from "@/lib/feedback";
|
||||
import { useIsClient } from "@/lib/use-is-client";
|
||||
import { frontendLogger } from "@/lib/frontend-logger";
|
||||
|
||||
/**
|
||||
* 拖拽区与「从文件选择」接受的类型:image/* 加常见扩展名。部分系统不认识 HEIC/HEIF 的 MIME(报告为空或 octet-stream),
|
||||
* 按扩展名放行,选择后再按文件头识别真实格式。
|
||||
*/
|
||||
export const IMAGE_ACCEPT = { "image/*": [".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".heic", ".heif"] };
|
||||
|
||||
// 添加 CaptureController 类型声明
|
||||
declare global {
|
||||
interface CaptureController {
|
||||
setFocusBehavior(behavior: 'no-focus-change' | 'focus-capturing-application'): void;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
CaptureController: {
|
||||
new(): CaptureController;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测是否有摄像头:只在浏览器提供 mediaDevices 时判断(HTTP 页面和部分 WebView 不提供,此时不阻止拍照)。
|
||||
* 不请求权限,只读取设备种类。
|
||||
* 安卓 App 中拍照由原生调用系统相机应用(ACTION_IMAGE_CAPTURE),WebView 的设备枚举不代表原生相机能力,
|
||||
* 因此不据此拦截,相机不可用时由原生提示。
|
||||
*/
|
||||
export function useCameraAvailability(): boolean | null {
|
||||
const [available, setAvailable] = useState<boolean | null>(null);
|
||||
useEffect(() => {
|
||||
if (getAndroidAppBridge()) return;
|
||||
if (typeof navigator === "undefined" || !navigator.mediaDevices?.enumerateDevices) return;
|
||||
let cancelled = false;
|
||||
navigator.mediaDevices.enumerateDevices()
|
||||
.then((devices) => {
|
||||
if (!cancelled) setAvailable(devices.some((device) => device.kind === "videoinput"));
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
return available;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断浏览器是否支持通过按钮读取剪贴板(需要安全上下文)。
|
||||
*/
|
||||
export function isClipboardReadSupported(isClient: boolean): boolean {
|
||||
return isClient &&
|
||||
typeof navigator !== 'undefined' &&
|
||||
!!navigator.clipboard &&
|
||||
typeof navigator.clipboard.read === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断浏览器是否支持屏幕截图(getDisplayMedia)。
|
||||
*/
|
||||
export function isScreenshotSupported(isClient: boolean): boolean {
|
||||
return isClient &&
|
||||
typeof navigator !== 'undefined' &&
|
||||
'mediaDevices' in navigator &&
|
||||
'getDisplayMedia' in navigator.mediaDevices;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从粘贴事件中提取第一个图片文件;输入框中粘贴或内容不是图片时返回 null。
|
||||
*/
|
||||
export function extractImageFromPasteEvent(event: ClipboardEvent): File | null {
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target && (target.isContentEditable || ["INPUT", "TEXTAREA"].includes(target.tagName))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const items = Array.from(event.clipboardData?.items ?? []);
|
||||
const imageItem = items.find((item) => item.kind === "file" && item.type.startsWith("image/"));
|
||||
return imageItem?.getAsFile() ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将剪贴板中的图片 Blob 转为 File:带名字的 File 直接使用,其余按类型生成文件名。
|
||||
*/
|
||||
export function clipboardImageToFile(blob: Blob): File {
|
||||
const type = blob.type || "image/png";
|
||||
const ext = type.split("/")[1] || "png";
|
||||
return blob instanceof File && blob.name
|
||||
? blob
|
||||
: new File([blob], `clipboard-${Date.now()}.${ext}`, { type });
|
||||
}
|
||||
|
||||
interface UploadZoneProps {
|
||||
onImageSelect: (file: File) => void; // 改为传递 File 对象
|
||||
isAnalyzing: boolean;
|
||||
}
|
||||
|
||||
export function useUploadZone({ onImageSelect, isAnalyzing }: UploadZoneProps) {
|
||||
const { t } = useLanguage();
|
||||
const [isScreenshotting, setIsScreenshotting] = useState(false);
|
||||
// 确保只在客户端渲染屏幕截图功能
|
||||
const isClient = useIsClient();
|
||||
|
||||
useEffect(() => {
|
||||
// 请求通知权限
|
||||
if ('Notification' in window && Notification.permission === 'default') {
|
||||
Notification.requestPermission();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const onDrop = useCallback(
|
||||
(acceptedFiles: File[]) => {
|
||||
const file = acceptedFiles[0];
|
||||
if (file) {
|
||||
// 直接传递 File 对象,让父组件处理压缩
|
||||
onImageSelect(file);
|
||||
}
|
||||
},
|
||||
[onImageSelect]
|
||||
);
|
||||
|
||||
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
||||
onDrop,
|
||||
accept: IMAGE_ACCEPT,
|
||||
maxFiles: 1,
|
||||
disabled: isAnalyzing,
|
||||
});
|
||||
|
||||
// 拍照、相册、文件三个独立入口:拍照用 capture 直接打开相机;相册只限图片;文件不限类型,作为相册中找不到照片时的兜底
|
||||
const hasCamera = useCameraAvailability();
|
||||
const cameraInput = useRef<HTMLInputElement>(null);
|
||||
const albumInput = useRef<HTMLInputElement>(null);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const handlePicked = (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
// 清空以便再次选择同一文件(如重拍后选同名照片)也能触发
|
||||
event.target.value = "";
|
||||
if (file) onImageSelect(file);
|
||||
};
|
||||
const openSource = (key: "camera" | "album" | "file") => {
|
||||
if (key === "camera" && hasCamera === false) {
|
||||
toast.warning(t.upload.noCamera);
|
||||
return;
|
||||
}
|
||||
({ camera: cameraInput, album: albumInput, file: fileInput })[key].current?.click();
|
||||
};
|
||||
// 将剪贴板中的图片 Blob 转为 File 并交给父组件
|
||||
const selectClipboardImage = useCallback(
|
||||
(blob: Blob) => {
|
||||
onImageSelect(clipboardImageToFile(blob));
|
||||
},
|
||||
[onImageSelect]
|
||||
);
|
||||
|
||||
// 监听 Ctrl/Cmd+V 粘贴图片
|
||||
useEffect(() => {
|
||||
const handlePaste = (event: ClipboardEvent) => {
|
||||
if (isAnalyzing) return;
|
||||
|
||||
// 在输入框中粘贴时不拦截
|
||||
const file = extractImageFromPasteEvent(event);
|
||||
if (!file) return;
|
||||
|
||||
event.preventDefault();
|
||||
selectClipboardImage(file);
|
||||
};
|
||||
|
||||
window.addEventListener("paste", handlePaste);
|
||||
return () => window.removeEventListener("paste", handlePaste);
|
||||
}, [isAnalyzing, selectClipboardImage]);
|
||||
|
||||
// 点击按钮读取剪贴板图片
|
||||
const handleClipboardRead = async () => {
|
||||
if (!isClipboardReadSupported(isClient)) {
|
||||
toast.warning(t.upload.pasteNotSupported);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const clipboardItems = await navigator.clipboard.read();
|
||||
for (const item of clipboardItems) {
|
||||
const imageType = item.types.find((type) => type.startsWith("image/"));
|
||||
if (imageType) {
|
||||
const blob = await item.getType(imageType);
|
||||
selectClipboardImage(blob);
|
||||
return;
|
||||
}
|
||||
}
|
||||
toast.warning(t.upload.pasteNoImage);
|
||||
} catch (error) {
|
||||
frontendLogger.warn('[UploadZone]', 'Clipboard read failed', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
if (error instanceof Error && error.name === 'NotAllowedError') {
|
||||
toast.warning(t.upload.pastePermissionDenied);
|
||||
} else {
|
||||
toast.error(t.upload.pasteFailed);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 屏幕截图功能
|
||||
const handleScreenshot = async () => {
|
||||
if (!isScreenshotSupported(isClient)) {
|
||||
toast.warning(t.upload.screenshotNotSupported);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsScreenshotting(true);
|
||||
|
||||
try {
|
||||
// 创建 CaptureController 来控制焦点行为
|
||||
let controller: CaptureController | undefined;
|
||||
if ('CaptureController' in window) {
|
||||
controller = new window.CaptureController();
|
||||
}
|
||||
|
||||
// 请求屏幕共享权限,优先当前标签页
|
||||
const displayMediaOptions: DisplayMediaStreamOptions & {
|
||||
preferCurrentTab?: boolean;
|
||||
controller?: CaptureController;
|
||||
} = {
|
||||
video: true,
|
||||
audio: false,
|
||||
preferCurrentTab: false, // 优先显示"此标签页"选项
|
||||
};
|
||||
|
||||
if (controller) {
|
||||
displayMediaOptions.controller = controller;
|
||||
}
|
||||
|
||||
const stream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
|
||||
|
||||
// 获取视频轨道并检查捕获类型
|
||||
const [videoTrack] = stream.getVideoTracks();
|
||||
const settings = videoTrack.getSettings();
|
||||
const displaySurface = settings.displaySurface; // 'browser' 表示标签页
|
||||
|
||||
// 如果是标签页或窗口,设置不切换焦点
|
||||
if (controller && (displaySurface === 'browser' || displaySurface === 'window')) {
|
||||
try {
|
||||
controller.setFocusBehavior('no-focus-change'); // 关键:不切换焦点到选中标签页
|
||||
frontendLogger.info('[UploadZone]', 'Screenshot focus behavior set to no-change', undefined, { sendToBackend: false });
|
||||
} catch (e) {
|
||||
frontendLogger.warn('[UploadZone]', 'Unable to set screenshot focus behavior', { error: e });
|
||||
}
|
||||
}
|
||||
|
||||
// 创建视频元素
|
||||
const video = document.createElement('video');
|
||||
video.srcObject = stream;
|
||||
video.muted = true;
|
||||
video.autoplay = true;
|
||||
video.playsInline = true;
|
||||
|
||||
// 等待视频准备并播放
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
video.onloadedmetadata = () => {
|
||||
video.play().then(() => {
|
||||
resolve();
|
||||
}).catch(reject);
|
||||
};
|
||||
video.onerror = reject;
|
||||
});
|
||||
|
||||
// 等待一帧渲染(确保稳定)
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
|
||||
// 检查视频尺寸
|
||||
if (video.videoWidth === 0 || video.videoHeight === 0) {
|
||||
throw new Error('视频没有有效尺寸');
|
||||
}
|
||||
|
||||
// 创建canvas并捕获
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = video.videoWidth;
|
||||
canvas.height = video.videoHeight;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) {
|
||||
throw new Error('无法获取canvas上下文');
|
||||
}
|
||||
|
||||
// 绘制视频帧
|
||||
ctx.drawImage(video, 0, 0);
|
||||
|
||||
// 停止屏幕共享
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
|
||||
// 转换为blob并创建文件
|
||||
canvas.toBlob((blob) => {
|
||||
if (blob) {
|
||||
const file = new File([blob], `screenshot-${Date.now()}.png`, {
|
||||
type: 'image/png'
|
||||
});
|
||||
onImageSelect(file);
|
||||
frontendLogger.info('[UploadZone]', 'Screenshot captured', undefined, { sendToBackend: false });
|
||||
} else {
|
||||
toast.error('截图转换失败');
|
||||
}
|
||||
}, 'image/png', 1.0);
|
||||
|
||||
} catch (error) {
|
||||
frontendLogger.error('[UploadZone]', 'Screenshot failed', { error });
|
||||
if (error instanceof Error) {
|
||||
if (error.name === 'NotAllowedError') {
|
||||
toast.warning(t.upload.screenshotPermissionDenied);
|
||||
} else {
|
||||
toast.error(`${t.upload.screenshotFailed}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setIsScreenshotting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
t,
|
||||
isClient,
|
||||
isAnalyzing,
|
||||
isDragActive,
|
||||
isScreenshotting,
|
||||
hasCamera,
|
||||
getRootProps,
|
||||
getInputProps,
|
||||
cameraInput,
|
||||
albumInput,
|
||||
fileInput,
|
||||
handlePicked,
|
||||
openSource,
|
||||
handleClipboardRead,
|
||||
handleScreenshot,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user