实现跨边界拖拽功能:支持从浏览器拖拽文件到系统
主要改进: - 使用 File System Access API 实现真正的跨应用边界文件传输 - 支持拖拽到窗口外自动触发系统保存对话框 - 智能路径记忆功能,记住用户上次选择的保存位置 - 多文件自动打包为 ZIP 格式 - 现代浏览器优先使用新 API,旧浏览器降级到传统下载 - 完整的视觉反馈和进度显示 技术实现: - 新增 useDragToSystemDesktop hook 处理系统级拖拽 - 扩展 Electron 主进程支持拖拽临时文件管理 - 集成 JSZip 库支持多文件打包 - 使用 IndexedDB 存储用户偏好的保存路径 - 优化文件管理器拖拽事件处理链 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -13,7 +13,8 @@ import {
|
||||
RefreshCw,
|
||||
Clipboard,
|
||||
Eye,
|
||||
Share
|
||||
Share,
|
||||
ExternalLink
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -47,6 +48,7 @@ interface ContextMenuProps {
|
||||
onPaste?: () => void;
|
||||
onPreview?: (file: FileItem) => void;
|
||||
hasClipboard?: boolean;
|
||||
onDragToDesktop?: () => void;
|
||||
}
|
||||
|
||||
interface MenuItem {
|
||||
@@ -77,7 +79,8 @@ export function FileManagerContextMenu({
|
||||
onRefresh,
|
||||
onPaste,
|
||||
onPreview,
|
||||
hasClipboard = false
|
||||
hasClipboard = false,
|
||||
onDragToDesktop
|
||||
}: ContextMenuProps) {
|
||||
const { t } = useTranslation();
|
||||
const [menuPosition, setMenuPosition] = useState({ x, y });
|
||||
@@ -204,6 +207,19 @@ export function FileManagerContextMenu({
|
||||
});
|
||||
}
|
||||
|
||||
// 拖拽到桌面菜单项(支持浏览器和桌面应用)
|
||||
if (hasFiles && onDragToDesktop) {
|
||||
const isModernBrowser = 'showSaveFilePicker' in window;
|
||||
menuItems.push({
|
||||
icon: <ExternalLink className="w-4 h-4" />,
|
||||
label: isMultipleFiles
|
||||
? `保存 ${files.length} 个文件到系统`
|
||||
: "保存到系统",
|
||||
action: () => onDragToDesktop(),
|
||||
shortcut: isModernBrowser ? "选择位置保存" : "下载到默认位置"
|
||||
});
|
||||
}
|
||||
|
||||
menuItems.push({ separator: true } as MenuItem);
|
||||
|
||||
if (isSingleFile && onRename) {
|
||||
|
||||
@@ -70,6 +70,8 @@ interface FileManagerGridProps {
|
||||
onUndo?: () => void;
|
||||
onFileDrop?: (draggedFiles: FileItem[], targetFile: FileItem) => void;
|
||||
onFileDiff?: (file1: FileItem, file2: FileItem) => void;
|
||||
onSystemDragStart?: (files: FileItem[]) => void;
|
||||
onSystemDragEnd?: (e: DragEvent) => void;
|
||||
}
|
||||
|
||||
const getFileIcon = (file: FileItem, viewMode: 'grid' | 'list' = 'grid') => {
|
||||
@@ -165,7 +167,9 @@ export function FileManagerGrid({
|
||||
onPaste,
|
||||
onUndo,
|
||||
onFileDrop,
|
||||
onFileDiff
|
||||
onFileDiff,
|
||||
onSystemDragStart,
|
||||
onSystemDragEnd
|
||||
}: FileManagerGridProps) {
|
||||
const { t } = useTranslation();
|
||||
const gridRef = useRef<HTMLDivElement>(null);
|
||||
@@ -227,6 +231,9 @@ export function FileManagerGrid({
|
||||
files: filesToDrag.map(f => f.path)
|
||||
};
|
||||
e.dataTransfer.setData('text/plain', JSON.stringify(dragData));
|
||||
|
||||
// 触发系统级拖拽开始
|
||||
onSystemDragStart?.(filesToDrag);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
};
|
||||
|
||||
@@ -280,9 +287,12 @@ export function FileManagerGrid({
|
||||
setDraggedFiles([]);
|
||||
};
|
||||
|
||||
const handleFileDragEnd = () => {
|
||||
const handleFileDragEnd = (e: React.DragEvent) => {
|
||||
setDraggedFiles([]);
|
||||
setDragOverTarget(null);
|
||||
|
||||
// 触发系统级拖拽结束检测
|
||||
onSystemDragEnd?.(e.nativeEvent);
|
||||
};
|
||||
|
||||
const [isSelecting, setIsSelecting] = useState(false);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import React, { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { FileManagerGrid } from "./FileManagerGrid";
|
||||
import { FileManagerContextMenu } from "./FileManagerContextMenu";
|
||||
import { useFileSelection } from "./hooks/useFileSelection";
|
||||
@@ -6,6 +6,9 @@ import { useDragAndDrop } from "./hooks/useDragAndDrop";
|
||||
import { WindowManager, useWindowManager } from "./components/WindowManager";
|
||||
import { FileWindow } from "./components/FileWindow";
|
||||
import { DiffWindow } from "./components/DiffWindow";
|
||||
import { useDragToDesktop } from "../../../hooks/useDragToDesktop";
|
||||
import { useDragToSystemDesktop } from "../../../hooks/useDragToSystemDesktop";
|
||||
import { DragIndicator } from "../../../components/DragIndicator";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { toast } from "sonner";
|
||||
@@ -110,6 +113,18 @@ function FileManagerContent({ initialHost, onClose }: FileManagerModernProps) {
|
||||
maxFileSize: 100 // 100MB
|
||||
});
|
||||
|
||||
// 拖拽到桌面功能
|
||||
const dragToDesktop = useDragToDesktop({
|
||||
sshSessionId: sshSessionId || '',
|
||||
sshHost: currentHost!
|
||||
});
|
||||
|
||||
// 系统级拖拽到桌面功能(新方案)
|
||||
const systemDrag = useDragToSystemDesktop({
|
||||
sshSessionId: sshSessionId || '',
|
||||
sshHost: currentHost!
|
||||
});
|
||||
|
||||
// 初始化SSH连接
|
||||
useEffect(() => {
|
||||
if (currentHost) {
|
||||
@@ -124,6 +139,41 @@ function FileManagerContent({ initialHost, onClose }: FileManagerModernProps) {
|
||||
}
|
||||
}, [sshSessionId, currentPath]);
|
||||
|
||||
// 文件拖拽到外部处理
|
||||
const handleFileDragStart = useCallback((files: FileItem[]) => {
|
||||
// 记录当前拖拽的文件
|
||||
systemDrag.startDragToSystem(files, {
|
||||
enableToast: true,
|
||||
onSuccess: () => {
|
||||
clearSelection();
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('拖拽失败:', error);
|
||||
}
|
||||
});
|
||||
}, [systemDrag, clearSelection]);
|
||||
|
||||
const handleFileDragEnd = useCallback((e: DragEvent) => {
|
||||
// 检查是否拖拽到窗口外
|
||||
const margin = 50;
|
||||
const isOutside = (
|
||||
e.clientX < margin ||
|
||||
e.clientX > window.innerWidth - margin ||
|
||||
e.clientY < margin ||
|
||||
e.clientY > window.innerHeight - margin
|
||||
);
|
||||
|
||||
if (isOutside) {
|
||||
// 延迟执行,避免与其他事件冲突
|
||||
setTimeout(() => {
|
||||
systemDrag.handleDragEnd(e);
|
||||
}, 100);
|
||||
} else {
|
||||
// 取消拖拽
|
||||
systemDrag.cancelDragToSystem();
|
||||
}
|
||||
}, [systemDrag]);
|
||||
|
||||
async function initializeSSHConnection() {
|
||||
if (!currentHost) return;
|
||||
|
||||
@@ -1055,6 +1105,39 @@ function FileManagerContent({ initialHost, onClose }: FileManagerModernProps) {
|
||||
toast.success(`正在对比文件: ${file1.name} 与 ${file2.name}`);
|
||||
}
|
||||
|
||||
// 拖拽到桌面处理函数
|
||||
async function handleDragToDesktop(files: FileItem[]) {
|
||||
if (!currentHost || !sshSessionId) {
|
||||
toast.error(t("fileManager.noSSHConnection"));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 优先使用新的系统级拖拽方案
|
||||
if (systemDrag.isFileSystemAPISupported) {
|
||||
await systemDrag.handleDragToSystem(files, {
|
||||
enableToast: true,
|
||||
onSuccess: () => {
|
||||
console.log('系统级拖拽成功');
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('系统级拖拽失败:', error);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// 降级到Electron方案
|
||||
if (files.length === 1) {
|
||||
await dragToDesktop.dragFileToDesktop(files[0]);
|
||||
} else if (files.length > 1) {
|
||||
await dragToDesktop.dragFilesToDesktop(files);
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('拖拽到桌面失败:', error);
|
||||
toast.error(`拖拽失败: ${error.message || '未知错误'}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 过滤文件并添加新建的临时项目
|
||||
let filteredFiles = files.filter(file =>
|
||||
file.name.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
@@ -1205,6 +1288,8 @@ function FileManagerContent({ initialHost, onClose }: FileManagerModernProps) {
|
||||
onUndo={handleUndo}
|
||||
onFileDrop={handleFileDrop}
|
||||
onFileDiff={handleFileDiff}
|
||||
onSystemDragStart={handleFileDragStart}
|
||||
onSystemDragEnd={handleFileDragEnd}
|
||||
/>
|
||||
|
||||
{/* 右键菜单 */}
|
||||
@@ -1234,6 +1319,31 @@ function FileManagerContent({ initialHost, onClose }: FileManagerModernProps) {
|
||||
onNewFile={handleCreateNewFile}
|
||||
onRefresh={() => loadDirectory(currentPath)}
|
||||
hasClipboard={!!clipboard}
|
||||
onDragToDesktop={() => handleDragToDesktop(contextMenu.files)}
|
||||
/>
|
||||
|
||||
{/* 拖拽到桌面指示器 */}
|
||||
<DragIndicator
|
||||
isVisible={
|
||||
dragToDesktop.isDownloading ||
|
||||
dragToDesktop.isDragging ||
|
||||
systemDrag.isDownloading ||
|
||||
systemDrag.isDragging
|
||||
}
|
||||
isDragging={
|
||||
systemDrag.isDragging || dragToDesktop.isDragging
|
||||
}
|
||||
isDownloading={
|
||||
systemDrag.isDownloading || dragToDesktop.isDownloading
|
||||
}
|
||||
progress={
|
||||
systemDrag.isDownloading || systemDrag.isDragging
|
||||
? systemDrag.progress
|
||||
: dragToDesktop.progress
|
||||
}
|
||||
fileName={selectedFiles.length === 1 ? selectedFiles[0]?.name : undefined}
|
||||
fileCount={selectedFiles.length}
|
||||
error={systemDrag.error || dragToDesktop.error}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
140
src/ui/components/DragIndicator.tsx
Normal file
140
src/ui/components/DragIndicator.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
import React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Download,
|
||||
FileDown,
|
||||
FolderDown,
|
||||
Loader2,
|
||||
CheckCircle,
|
||||
AlertCircle
|
||||
} from 'lucide-react';
|
||||
|
||||
interface DragIndicatorProps {
|
||||
isVisible: boolean;
|
||||
isDragging: boolean;
|
||||
isDownloading: boolean;
|
||||
progress: number;
|
||||
fileName?: string;
|
||||
fileCount?: number;
|
||||
error?: string | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function DragIndicator({
|
||||
isVisible,
|
||||
isDragging,
|
||||
isDownloading,
|
||||
progress,
|
||||
fileName,
|
||||
fileCount = 1,
|
||||
error,
|
||||
className
|
||||
}: DragIndicatorProps) {
|
||||
if (!isVisible) return null;
|
||||
|
||||
const getIcon = () => {
|
||||
if (error) {
|
||||
return <AlertCircle className="w-6 h-6 text-red-500" />;
|
||||
}
|
||||
|
||||
if (isDragging) {
|
||||
return <CheckCircle className="w-6 h-6 text-green-500" />;
|
||||
}
|
||||
|
||||
if (isDownloading) {
|
||||
return <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />;
|
||||
}
|
||||
|
||||
if (fileCount > 1) {
|
||||
return <FolderDown className="w-6 h-6 text-blue-500" />;
|
||||
}
|
||||
|
||||
return <FileDown className="w-6 h-6 text-blue-500" />;
|
||||
};
|
||||
|
||||
const getStatusText = () => {
|
||||
if (error) {
|
||||
return `错误: ${error}`;
|
||||
}
|
||||
|
||||
if (isDragging) {
|
||||
return `正在拖拽${fileName ? ` ${fileName}` : ''}到桌面...`;
|
||||
}
|
||||
|
||||
if (isDownloading) {
|
||||
return `正在准备拖拽${fileName ? ` ${fileName}` : ''}...`;
|
||||
}
|
||||
|
||||
return `准备拖拽${fileCount > 1 ? ` ${fileCount} 个文件` : fileName ? ` ${fileName}` : ''}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"fixed top-4 right-4 z-50 min-w-[300px] max-w-[400px]",
|
||||
"bg-dark-bg border border-dark-border rounded-lg shadow-lg",
|
||||
"p-4 transition-all duration-300 ease-in-out",
|
||||
isVisible ? "opacity-100 translate-x-0" : "opacity-0 translate-x-full",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* 图标 */}
|
||||
<div className="flex-shrink-0 mt-0.5">
|
||||
{getIcon()}
|
||||
</div>
|
||||
|
||||
{/* 内容 */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{/* 标题 */}
|
||||
<div className="text-sm font-medium text-foreground mb-2">
|
||||
{fileCount > 1 ? '批量拖拽到桌面' : '拖拽到桌面'}
|
||||
</div>
|
||||
|
||||
{/* 状态文字 */}
|
||||
<div className={cn(
|
||||
"text-xs mb-3",
|
||||
error ? "text-red-500" :
|
||||
isDragging ? "text-green-500" :
|
||||
"text-muted-foreground"
|
||||
)}>
|
||||
{getStatusText()}
|
||||
</div>
|
||||
|
||||
{/* 进度条 */}
|
||||
{(isDownloading || isDragging) && !error && (
|
||||
<div className="w-full bg-dark-border rounded-full h-2 mb-2">
|
||||
<div
|
||||
className={cn(
|
||||
"h-2 rounded-full transition-all duration-300",
|
||||
isDragging ? "bg-green-500" : "bg-blue-500"
|
||||
)}
|
||||
style={{ width: `${Math.max(5, progress)}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 进度百分比 */}
|
||||
{(isDownloading || isDragging) && !error && (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{progress.toFixed(0)}%
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 拖拽提示 */}
|
||||
{isDragging && !error && (
|
||||
<div className="text-xs text-green-500 mt-2 flex items-center gap-1">
|
||||
<Download className="w-3 h-3" />
|
||||
现在可以拖拽到桌面任意位置
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 动画效果的背景 */}
|
||||
{isDragging && !error && (
|
||||
<div className="absolute inset-0 rounded-lg bg-green-500/5 animate-pulse" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
281
src/ui/hooks/useDragToDesktop.ts
Normal file
281
src/ui/hooks/useDragToDesktop.ts
Normal file
@@ -0,0 +1,281 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { downloadSSHFile } from '@/ui/main-axios';
|
||||
import type { FileItem, SSHHost } from '../../types/index.js';
|
||||
|
||||
interface DragToDesktopState {
|
||||
isDragging: boolean;
|
||||
isDownloading: boolean;
|
||||
progress: number;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface UseDragToDesktopProps {
|
||||
sshSessionId: string;
|
||||
sshHost: SSHHost;
|
||||
}
|
||||
|
||||
interface DragToDesktopOptions {
|
||||
enableToast?: boolean;
|
||||
onSuccess?: () => void;
|
||||
onError?: (error: string) => void;
|
||||
}
|
||||
|
||||
export function useDragToDesktop({ sshSessionId, sshHost }: UseDragToDesktopProps) {
|
||||
const [state, setState] = useState<DragToDesktopState>({
|
||||
isDragging: false,
|
||||
isDownloading: false,
|
||||
progress: 0,
|
||||
error: null
|
||||
});
|
||||
|
||||
// 检查是否在Electron环境中
|
||||
const isElectron = () => {
|
||||
return typeof window !== 'undefined' &&
|
||||
window.electronAPI &&
|
||||
window.electronAPI.isElectron;
|
||||
};
|
||||
|
||||
// 拖拽单个文件到桌面
|
||||
const dragFileToDesktop = useCallback(async (
|
||||
file: FileItem,
|
||||
options: DragToDesktopOptions = {}
|
||||
) => {
|
||||
const { enableToast = true, onSuccess, onError } = options;
|
||||
|
||||
if (!isElectron()) {
|
||||
const error = '拖拽到桌面功能仅在桌面应用中可用';
|
||||
if (enableToast) toast.error(error);
|
||||
onError?.(error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (file.type !== 'file') {
|
||||
const error = '只能拖拽文件到桌面';
|
||||
if (enableToast) toast.error(error);
|
||||
onError?.(error);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
setState(prev => ({ ...prev, isDownloading: true, progress: 0, error: null }));
|
||||
|
||||
// 下载文件内容
|
||||
const response = await downloadSSHFile(sshSessionId, file.path);
|
||||
|
||||
if (!response?.content) {
|
||||
throw new Error('无法获取文件内容');
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, progress: 50 }));
|
||||
|
||||
// 创建临时文件
|
||||
const tempResult = await window.electronAPI.createTempFile({
|
||||
fileName: file.name,
|
||||
content: response.content,
|
||||
encoding: 'base64'
|
||||
});
|
||||
|
||||
if (!tempResult.success) {
|
||||
throw new Error(tempResult.error || '创建临时文件失败');
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, progress: 80, isDragging: true }));
|
||||
|
||||
// 开始拖拽
|
||||
const dragResult = await window.electronAPI.startDragToDesktop({
|
||||
tempId: tempResult.tempId,
|
||||
fileName: file.name
|
||||
});
|
||||
|
||||
if (!dragResult.success) {
|
||||
throw new Error(dragResult.error || '开始拖拽失败');
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, progress: 100 }));
|
||||
|
||||
if (enableToast) {
|
||||
toast.success(`正在拖拽 ${file.name} 到桌面`);
|
||||
}
|
||||
|
||||
onSuccess?.();
|
||||
|
||||
// 延迟清理临时文件(给用户时间完成拖拽)
|
||||
setTimeout(async () => {
|
||||
await window.electronAPI.cleanupTempFile(tempResult.tempId);
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isDragging: false,
|
||||
isDownloading: false,
|
||||
progress: 0
|
||||
}));
|
||||
}, 10000); // 10秒后清理
|
||||
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
console.error('拖拽到桌面失败:', error);
|
||||
const errorMessage = error.message || '拖拽失败';
|
||||
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isDownloading: false,
|
||||
isDragging: false,
|
||||
progress: 0,
|
||||
error: errorMessage
|
||||
}));
|
||||
|
||||
if (enableToast) {
|
||||
toast.error(`拖拽失败: ${errorMessage}`);
|
||||
}
|
||||
|
||||
onError?.(errorMessage);
|
||||
return false;
|
||||
}
|
||||
}, [sshSessionId, sshHost]);
|
||||
|
||||
// 拖拽多个文件到桌面(批量操作)
|
||||
const dragFilesToDesktop = useCallback(async (
|
||||
files: FileItem[],
|
||||
options: DragToDesktopOptions = {}
|
||||
) => {
|
||||
const { enableToast = true, onSuccess, onError } = options;
|
||||
|
||||
if (!isElectron()) {
|
||||
const error = '拖拽到桌面功能仅在桌面应用中可用';
|
||||
if (enableToast) toast.error(error);
|
||||
onError?.(error);
|
||||
return false;
|
||||
}
|
||||
|
||||
const fileList = files.filter(f => f.type === 'file');
|
||||
if (fileList.length === 0) {
|
||||
const error = '没有可拖拽的文件';
|
||||
if (enableToast) toast.error(error);
|
||||
onError?.(error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fileList.length === 1) {
|
||||
return dragFileToDesktop(fileList[0], options);
|
||||
}
|
||||
|
||||
try {
|
||||
setState(prev => ({ ...prev, isDownloading: true, progress: 0, error: null }));
|
||||
|
||||
// 批量下载文件
|
||||
const downloadPromises = fileList.map(file =>
|
||||
downloadSSHFile(sshSessionId, file.path)
|
||||
);
|
||||
|
||||
const responses = await Promise.all(downloadPromises);
|
||||
setState(prev => ({ ...prev, progress: 40 }));
|
||||
|
||||
// 创建临时文件夹结构
|
||||
const folderName = `Files_${Date.now()}`;
|
||||
const filesData = fileList.map((file, index) => ({
|
||||
relativePath: file.name,
|
||||
content: responses[index]?.content || '',
|
||||
encoding: 'base64'
|
||||
}));
|
||||
|
||||
const tempResult = await window.electronAPI.createTempFolder({
|
||||
folderName,
|
||||
files: filesData
|
||||
});
|
||||
|
||||
if (!tempResult.success) {
|
||||
throw new Error(tempResult.error || '创建临时文件夹失败');
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, progress: 80, isDragging: true }));
|
||||
|
||||
// 开始拖拽文件夹
|
||||
const dragResult = await window.electronAPI.startDragToDesktop({
|
||||
tempId: tempResult.tempId,
|
||||
fileName: folderName
|
||||
});
|
||||
|
||||
if (!dragResult.success) {
|
||||
throw new Error(dragResult.error || '开始拖拽失败');
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, progress: 100 }));
|
||||
|
||||
if (enableToast) {
|
||||
toast.success(`正在拖拽 ${fileList.length} 个文件到桌面`);
|
||||
}
|
||||
|
||||
onSuccess?.();
|
||||
|
||||
// 延迟清理临时文件夹
|
||||
setTimeout(async () => {
|
||||
await window.electronAPI.cleanupTempFile(tempResult.tempId);
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isDragging: false,
|
||||
isDownloading: false,
|
||||
progress: 0
|
||||
}));
|
||||
}, 15000); // 15秒后清理
|
||||
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
console.error('批量拖拽到桌面失败:', error);
|
||||
const errorMessage = error.message || '批量拖拽失败';
|
||||
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isDownloading: false,
|
||||
isDragging: false,
|
||||
progress: 0,
|
||||
error: errorMessage
|
||||
}));
|
||||
|
||||
if (enableToast) {
|
||||
toast.error(`批量拖拽失败: ${errorMessage}`);
|
||||
}
|
||||
|
||||
onError?.(errorMessage);
|
||||
return false;
|
||||
}
|
||||
}, [sshSessionId, sshHost, dragFileToDesktop]);
|
||||
|
||||
// 拖拽文件夹到桌面
|
||||
const dragFolderToDesktop = useCallback(async (
|
||||
folder: FileItem,
|
||||
options: DragToDesktopOptions = {}
|
||||
) => {
|
||||
const { enableToast = true, onSuccess, onError } = options;
|
||||
|
||||
if (!isElectron()) {
|
||||
const error = '拖拽到桌面功能仅在桌面应用中可用';
|
||||
if (enableToast) toast.error(error);
|
||||
onError?.(error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (folder.type !== 'directory') {
|
||||
const error = '只能拖拽文件夹类型';
|
||||
if (enableToast) toast.error(error);
|
||||
onError?.(error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (enableToast) {
|
||||
toast.info('文件夹拖拽功能开发中...');
|
||||
}
|
||||
|
||||
// TODO: 实现文件夹递归下载和拖拽
|
||||
// 这需要额外的API来递归获取文件夹内容
|
||||
|
||||
return false;
|
||||
}, [sshSessionId, sshHost]);
|
||||
|
||||
return {
|
||||
...state,
|
||||
isElectron: isElectron(),
|
||||
dragFileToDesktop,
|
||||
dragFilesToDesktop,
|
||||
dragFolderToDesktop
|
||||
};
|
||||
}
|
||||
309
src/ui/hooks/useDragToSystemDesktop.ts
Normal file
309
src/ui/hooks/useDragToSystemDesktop.ts
Normal file
@@ -0,0 +1,309 @@
|
||||
import { useState, useCallback, useRef } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { downloadSSHFile } from '@/ui/main-axios';
|
||||
import type { FileItem, SSHHost } from '../../types/index.js';
|
||||
|
||||
interface DragToSystemState {
|
||||
isDragging: boolean;
|
||||
isDownloading: boolean;
|
||||
progress: number;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface UseDragToSystemProps {
|
||||
sshSessionId: string;
|
||||
sshHost: SSHHost;
|
||||
}
|
||||
|
||||
interface DragToSystemOptions {
|
||||
enableToast?: boolean;
|
||||
onSuccess?: () => void;
|
||||
onError?: (error: string) => void;
|
||||
}
|
||||
|
||||
export function useDragToSystemDesktop({ sshSessionId, sshHost }: UseDragToSystemProps) {
|
||||
const [state, setState] = useState<DragToSystemState>({
|
||||
isDragging: false,
|
||||
isDownloading: false,
|
||||
progress: 0,
|
||||
error: null
|
||||
});
|
||||
|
||||
const dragDataRef = useRef<{ files: FileItem[], options: DragToSystemOptions } | null>(null);
|
||||
|
||||
// 目录记忆功能
|
||||
const getLastSaveDirectory = async () => {
|
||||
try {
|
||||
if ('indexedDB' in window) {
|
||||
const request = indexedDB.open('termix-dirs', 1);
|
||||
return new Promise((resolve) => {
|
||||
request.onsuccess = () => {
|
||||
const db = request.result;
|
||||
const transaction = db.transaction(['directories'], 'readonly');
|
||||
const store = transaction.objectStore('directories');
|
||||
const getRequest = store.get('lastSaveDir');
|
||||
getRequest.onsuccess = () => resolve(getRequest.result?.handle || null);
|
||||
};
|
||||
request.onerror = () => resolve(null);
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains('directories')) {
|
||||
db.createObjectStore('directories');
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('无法获取上次保存目录:', error);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const saveLastDirectory = async (fileHandle: any) => {
|
||||
try {
|
||||
if ('indexedDB' in window && fileHandle.getParent) {
|
||||
const dirHandle = await fileHandle.getParent();
|
||||
const request = indexedDB.open('termix-dirs', 1);
|
||||
request.onsuccess = () => {
|
||||
const db = request.result;
|
||||
const transaction = db.transaction(['directories'], 'readwrite');
|
||||
const store = transaction.objectStore('directories');
|
||||
store.put({ handle: dirHandle }, 'lastSaveDir');
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('无法保存目录记录:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 检查File System Access API支持
|
||||
const isFileSystemAPISupported = () => {
|
||||
return 'showSaveFilePicker' in window;
|
||||
};
|
||||
|
||||
// 检查拖拽是否离开窗口边界
|
||||
const isDraggedOutsideWindow = (e: DragEvent) => {
|
||||
const margin = 50; // 增加容差边距
|
||||
return (
|
||||
e.clientX < margin ||
|
||||
e.clientX > window.innerWidth - margin ||
|
||||
e.clientY < margin ||
|
||||
e.clientY > window.innerHeight - margin
|
||||
);
|
||||
};
|
||||
|
||||
// 创建文件blob
|
||||
const createFileBlob = async (file: FileItem): Promise<Blob> => {
|
||||
const response = await downloadSSHFile(sshSessionId, file.path);
|
||||
if (!response?.content) {
|
||||
throw new Error(`无法获取文件 ${file.name} 的内容`);
|
||||
}
|
||||
|
||||
// base64转换为blob
|
||||
const binaryString = atob(response.content);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
|
||||
return new Blob([bytes]);
|
||||
};
|
||||
|
||||
// 创建ZIP文件(用于多文件下载)
|
||||
const createZipBlob = async (files: FileItem[]): Promise<Blob> => {
|
||||
// 这里需要一个轻量级的zip库,先用简单方案
|
||||
const JSZip = (await import('jszip')).default;
|
||||
const zip = new JSZip();
|
||||
|
||||
for (const file of files) {
|
||||
const blob = await createFileBlob(file);
|
||||
zip.file(file.name, blob);
|
||||
}
|
||||
|
||||
return await zip.generateAsync({ type: 'blob' });
|
||||
};
|
||||
|
||||
// 使用File System Access API保存文件
|
||||
const saveFileWithSystemAPI = async (blob: Blob, suggestedName: string) => {
|
||||
try {
|
||||
// 获取上次保存的目录句柄
|
||||
const lastDirHandle = await getLastSaveDirectory();
|
||||
|
||||
const fileHandle = await (window as any).showSaveFilePicker({
|
||||
suggestedName,
|
||||
startIn: lastDirHandle || 'desktop', // 优先使用上次目录,否则桌面
|
||||
types: [
|
||||
{
|
||||
description: '文件',
|
||||
accept: {
|
||||
'*/*': ['.txt', '.jpg', '.png', '.pdf', '.zip', '.tar', '.gz']
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
// 保存当前目录句柄以便下次使用
|
||||
await saveLastDirectory(fileHandle);
|
||||
|
||||
const writable = await fileHandle.createWritable();
|
||||
await writable.write(blob);
|
||||
await writable.close();
|
||||
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
if (error.name === 'AbortError') {
|
||||
return false; // 用户取消
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// 降级方案:传统下载
|
||||
const fallbackDownload = (blob: Blob, fileName: string) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = fileName;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
// 处理拖拽到系统桌面
|
||||
const handleDragToSystem = useCallback(async (
|
||||
files: FileItem[],
|
||||
options: DragToSystemOptions = {}
|
||||
) => {
|
||||
const { enableToast = true, onSuccess, onError } = options;
|
||||
|
||||
if (files.length === 0) {
|
||||
const error = '没有可拖拽的文件';
|
||||
if (enableToast) toast.error(error);
|
||||
onError?.(error);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 过滤出文件类型
|
||||
const fileList = files.filter(f => f.type === 'file');
|
||||
if (fileList.length === 0) {
|
||||
const error = '只能拖拽文件到桌面';
|
||||
if (enableToast) toast.error(error);
|
||||
onError?.(error);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
setState(prev => ({ ...prev, isDownloading: true, progress: 0, error: null }));
|
||||
|
||||
let blob: Blob;
|
||||
let fileName: string;
|
||||
|
||||
if (fileList.length === 1) {
|
||||
// 单文件
|
||||
blob = await createFileBlob(fileList[0]);
|
||||
fileName = fileList[0].name;
|
||||
setState(prev => ({ ...prev, progress: 70 }));
|
||||
} else {
|
||||
// 多文件打包成ZIP
|
||||
blob = await createZipBlob(fileList);
|
||||
fileName = `files_${Date.now()}.zip`;
|
||||
setState(prev => ({ ...prev, progress: 70 }));
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, progress: 90 }));
|
||||
|
||||
// 优先使用File System Access API
|
||||
if (isFileSystemAPISupported()) {
|
||||
const saved = await saveFileWithSystemAPI(blob, fileName);
|
||||
if (!saved) {
|
||||
// 用户取消了
|
||||
setState(prev => ({ ...prev, isDownloading: false, progress: 0 }));
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// 降级到传统下载
|
||||
fallbackDownload(blob, fileName);
|
||||
if (enableToast) {
|
||||
toast.info('由于浏览器限制,文件将下载到默认下载目录');
|
||||
}
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, progress: 100 }));
|
||||
|
||||
if (enableToast) {
|
||||
toast.success(
|
||||
fileList.length === 1
|
||||
? `${fileName} 已保存到指定位置`
|
||||
: `${fileList.length} 个文件已打包保存`
|
||||
);
|
||||
}
|
||||
|
||||
onSuccess?.();
|
||||
|
||||
// 重置状态
|
||||
setTimeout(() => {
|
||||
setState(prev => ({ ...prev, isDownloading: false, progress: 0 }));
|
||||
}, 1000);
|
||||
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
console.error('拖拽到桌面失败:', error);
|
||||
const errorMessage = error.message || '保存失败';
|
||||
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isDownloading: false,
|
||||
progress: 0,
|
||||
error: errorMessage
|
||||
}));
|
||||
|
||||
if (enableToast) {
|
||||
toast.error(`保存失败: ${errorMessage}`);
|
||||
}
|
||||
|
||||
onError?.(errorMessage);
|
||||
return false;
|
||||
}
|
||||
}, [sshSessionId]);
|
||||
|
||||
// 开始拖拽(记录拖拽数据)
|
||||
const startDragToSystem = useCallback((files: FileItem[], options: DragToSystemOptions = {}) => {
|
||||
dragDataRef.current = { files, options };
|
||||
setState(prev => ({ ...prev, isDragging: true, error: null }));
|
||||
}, []);
|
||||
|
||||
// 结束拖拽检测
|
||||
const handleDragEnd = useCallback((e: DragEvent) => {
|
||||
if (!dragDataRef.current) return;
|
||||
|
||||
const { files, options } = dragDataRef.current;
|
||||
|
||||
// 检查是否拖拽到窗口外
|
||||
if (isDraggedOutsideWindow(e)) {
|
||||
// 延迟执行,避免与其他拖拽事件冲突
|
||||
setTimeout(() => {
|
||||
handleDragToSystem(files, options);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
// 清理拖拽状态
|
||||
dragDataRef.current = null;
|
||||
setState(prev => ({ ...prev, isDragging: false }));
|
||||
}, [handleDragToSystem]);
|
||||
|
||||
// 取消拖拽
|
||||
const cancelDragToSystem = useCallback(() => {
|
||||
dragDataRef.current = null;
|
||||
setState(prev => ({ ...prev, isDragging: false, error: null }));
|
||||
}, []);
|
||||
|
||||
return {
|
||||
...state,
|
||||
isFileSystemAPISupported: isFileSystemAPISupported(),
|
||||
startDragToSystem,
|
||||
handleDragEnd,
|
||||
cancelDragToSystem,
|
||||
handleDragToSystem // 直接调用版本
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user