diff --git a/src/App.tsx b/src/App.tsx index 1dc21328..69bbd12d 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -248,7 +248,10 @@ function App() { const handlePaletteOpenFile = useCallback( (path: string) => { const name = path.split(/[\\/]/).pop() ?? path - layoutStore.openFilePreview({ path, name, directory: currentDirectory }) + layoutStore.openFileTab( + { path, name, directory: currentDirectory, serverId: serverStore.getActiveServerId() }, + 'right', + ) }, [currentDirectory], ) diff --git a/src/components/BottomPanel.tsx b/src/components/BottomPanel.tsx index f41d6974..9af18609 100644 --- a/src/components/BottomPanel.tsx +++ b/src/components/BottomPanel.tsx @@ -15,6 +15,7 @@ const SessionChangesPanel = lazy(() => ) const ContextPanel = lazy(() => import('./ContextPanel').then(module => ({ default: module.ContextPanel }))) const FileExplorer = lazy(() => import('./FileExplorer').then(module => ({ default: module.FileExplorer }))) +const FileViewer = lazy(() => import('./FileViewer').then(module => ({ default: module.FileViewer }))) const McpPanel = lazy(() => import('./McpPanel').then(module => ({ default: module.McpPanel }))) const SkillPanel = lazy(() => import('./SkillPanel').then(module => ({ default: module.SkillPanel }))) const WorktreePanel = lazy(() => import('./WorktreePanel').then(module => ({ default: module.WorktreePanel }))) @@ -84,7 +85,6 @@ export const BottomPanel = memo(function BottomPanel({ directory, serverId, term @@ -115,6 +115,13 @@ export const BottomPanel = memo(function BottomPanel({ directory, serverId, term ) : null} + {/* 打开的文件保持挂载:切走再切回来,编辑态与滚动位置都还在 */} +
+ }> + + +
+ {activeTab.type === 'terminal' ? ( }> @@ -206,7 +213,6 @@ const TerminalContent = memo(function TerminalContent({ activeTab }: TerminalCon interface FilesContentProps { activeTab: PanelTab directory?: string - isPanelResizing?: boolean sessionId?: string | null serverId?: string } @@ -214,7 +220,6 @@ interface FilesContentProps { const FilesContent = memo(function FilesContent({ activeTab, directory, - isPanelResizing = false, sessionId, serverId, }: FilesContentProps) { @@ -229,10 +234,7 @@ const FilesContent = memo(function FilesContent({ panelTabId={tab.id} directory={directory} serverId={serverId} - previewFile={tab.previewFile ?? null} - previewFiles={tab.previewFiles ?? []} position="bottom" - isPanelResizing={isPanelResizing} sessionId={sessionId} /> @@ -241,6 +243,42 @@ const FilesContent = memo(function FilesContent({ ) }) +interface FileContentProps { + activeTab: PanelTab + serverId?: string + sessionId?: string | null + isPanelResizing?: boolean +} + +/** 打开的文件:每个文件一个标签页,内容整页展示 */ +const FileContent = memo(function FileContent({ + activeTab, + serverId, + sessionId, + isPanelResizing = false, +}: FileContentProps) { + const { panelTabs } = useLayoutStore() + const fileTabs = panelTabs.filter(t => t.position === 'bottom' && t.type === 'file') + + return ( + <> + {fileTabs.map(tab => ( +
+ {tab.previewFile && ( + + )} +
+ ))} + + ) +}) + interface ChangesContentProps { activeTab: PanelTab directory?: string diff --git a/src/components/FileExplorer.test.tsx b/src/components/FileExplorer.test.tsx index e1c5d65f..c565d927 100644 --- a/src/components/FileExplorer.test.tsx +++ b/src/components/FileExplorer.test.tsx @@ -1,6 +1,7 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' import { FileExplorer } from './FileExplorer' +import { layoutStore } from '../store/layoutStore' import type { DesktopPlatform } from '../utils/tauri' const { @@ -21,16 +22,6 @@ vi.mock('../hooks', () => ({ useFileExplorer: (options?: unknown) => useFileExplorerMock(options), })) -vi.mock('../hooks/useVerticalSplitResize', () => ({ - useVerticalSplitResize: () => ({ - splitHeight: 200, - isResizing: false, - resetSplitHeight: vi.fn(), - handleResizeStart: vi.fn(), - handleTouchResizeStart: vi.fn(), - }), -})) - vi.mock('../utils/tauri', () => ({ isTauri: () => isTauriMock(), isTauriMobile: () => isTauriMobileMock(), @@ -66,22 +57,36 @@ describe('FileExplorer', () => { expandedPaths: new Set(), toggleExpand: vi.fn(), refresh: vi.fn(), - previewContent: null, - previewLoading: false, - previewError: null, - loadPreview: vi.fn(), - clearPreview: vi.fn(), + effectiveDirectory: 'C:/repo', fileStatus: new Map(), }) }) + it('opens a file in a new panel tab instead of pushing a preview from the bottom', () => { + const openFileTab = vi.spyOn(layoutStore, 'openFileTab') + + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: 'app.ts' })) + + expect(openFileTab).toHaveBeenCalledWith( + { path: 'src/app.ts', name: 'app.ts', directory: 'C:/repo', serverId: 'server-1' }, + 'right', + ) + }) + it('reveals the selected file in the system explorer from the context menu', async () => { render( , ) @@ -101,8 +106,6 @@ describe('FileExplorer', () => { , ) @@ -118,8 +121,6 @@ describe('FileExplorer', () => { , ) diff --git a/src/components/FileExplorer.tsx b/src/components/FileExplorer.tsx index 9cd65d35..9602a97c 100644 --- a/src/components/FileExplorer.tsx +++ b/src/components/FileExplorer.tsx @@ -1,53 +1,29 @@ // ============================================ -// FileExplorer - 文件浏览器组件 -// 包含文件树和文件预览两个区域,支持拖拽调整高度 -// 性能优化:使用 CSS 变量 + requestAnimationFrame 处理 resize +// FileExplorer - 文件目录树 // ============================================ +// +// 只负责目录树:展开/折叠、搜索、右键(在系统文件管理器里显示)。 +// 点击文件不再"从下面顶开预览",而是在面板标签栏里开一个新标签(全高展示), +// 内容由 FileViewer 负责。 -import { memo, useCallback, useMemo, useEffect, useRef, useState, type PointerEvent, type ReactNode } from 'react' +import { memo, useCallback, useEffect, useMemo, useRef, useState, type PointerEvent } from 'react' import { createPortal } from 'react-dom' import { useTranslation } from 'react-i18next' import { useFileExplorer, type FileTreeNode } from '../hooks' -import { useVerticalSplitResize } from '../hooks/useVerticalSplitResize' -import { layoutStore, previewMatchesDirectory, type PreviewFile } from '../store/layoutStore' +import { layoutStore, useLayoutStore, type PanelPosition } from '../store/layoutStore' import { ChevronRightIcon, ChevronDownIcon, RetryIcon, AlertCircleIcon, - DownloadIcon, - MaximizeIcon, SearchIcon, CloseIcon, - PencilIcon, - CheckIcon, } from './Icons' -import { CodePreview } from './CodePreview' -import { setFileEditorDirty } from '../store/unsavedFileStore' -import { EditConfirmDialog } from './EditConfirmDialog' -import { hashBytes } from '../utils/textEncoding' -import { HtmlFilePreviewFrame } from './HtmlFilePreviewFrame' -import { PreviewTabsBar, type PreviewTabsBarItem } from './PreviewTabsBar' -import { MarkdownRenderer } from './MarkdownRenderer' -import { useFullscreenLayer } from '../contexts' import { getMaterialIconUrl } from '../utils/materialIcons' -import { detectLanguage } from '../utils/languageUtils' -import { - getPreviewCategory, - isTextualMedia, - buildBytesDataUrl, - buildTextDataUrl, - formatMimeType, - type PreviewCategory, -} from '../utils/mimeUtils' -import { getMimeFromPath } from '../features/chat/input/inputUtils' -import { downloadFileContent } from '../utils/downloadUtils' -import { searchFiles } from '../api/file' -import type { FileContent } from '../api/types' -import { startInternalDrag } from '../lib/internalDragCore' import { toAbsolutePath } from '../features/mention' import { getDesktopPlatform, isTauri, isTauriMobile } from '../utils/tauri' -import type { TargetLineRange } from './codeMirrorReadonlyExtensions' +import { startInternalDrag } from '../lib/internalDragCore' +import { searchFiles } from '../api/file' function canRevealInSystemExplorer(): boolean { return isTauri() && !isTauriMobile() @@ -69,34 +45,13 @@ async function revealPathInSystemExplorer(absolutePath: string) { await revealItemInDir(absolutePath) } -// 常量 -const MIN_TREE_HEIGHT = 100 -const MIN_PREVIEW_HEIGHT = 150 - -const MARKDOWN_MIME_TYPES = new Set(['text/markdown', 'text/x-markdown', 'text/md', 'application/markdown']) -const HTML_MIME_TYPES = new Set(['text/html', 'application/xhtml+xml']) - -function isMarkdownPreview(language: string, mimeType?: string): boolean { - if (language === 'markdown' || language === 'mdx') return true - if (!mimeType) return false - return MARKDOWN_MIME_TYPES.has(mimeType.split(';', 1)[0].toLowerCase()) -} - -function isHtmlPreview(language: string, mimeType?: string): boolean { - if (language === 'html') return true - if (!mimeType) return false - return HTML_MIME_TYPES.has(mimeType.split(';', 1)[0].toLowerCase()) -} - interface FileExplorerProps { panelTabId: string directory?: string /** 数据所属服务器(右侧面板跟随焦点 session 时传入;缺省用活动服务器) */ serverId?: string - previewFile: PreviewFile | null - previewFiles: PreviewFile[] - position?: 'bottom' | 'right' - isPanelResizing?: boolean + /** 点击文件时在哪个面板开标签 */ + position?: PanelPosition sessionId?: string | null } @@ -104,15 +59,10 @@ export const FileExplorer = memo(function FileExplorer({ panelTabId, directory, serverId, - previewFile, - previewFiles, position = 'right', - isPanelResizing = false, sessionId, }: FileExplorerProps) { const { t } = useTranslation(['components', 'common']) - const containerRef = useRef(null) - const treeRef = useRef(null) const fileContextMenuRef = useRef(null) const searchRequestIdRef = useRef(0) const [searchQuery, setSearchQuery] = useState('') @@ -122,22 +72,6 @@ export const FileExplorer = memo(function FileExplorer({ const canRevealFiles = canRevealInSystemExplorer() const revealInSystemExplorerLabel = useMemo(() => getRevealInSystemExplorerLabel(t), [t]) const [searchError, setSearchError] = useState(null) - const { - splitHeight: treeHeight, - isResizing, - resetSplitHeight, - handleResizeStart, - handleTouchResizeStart, - } = useVerticalSplitResize({ - containerRef, - primaryRef: treeRef, - cssVariableName: '--tree-height', - minPrimaryHeight: MIN_TREE_HEIGHT, - minSecondaryHeight: MIN_PREVIEW_HEIGHT, - }) - - // 综合 resize 状态 - 外部面板 resize 或内部 resize - const isAnyResizing = isPanelResizing || isResizing const { tree, @@ -145,60 +79,37 @@ export const FileExplorer = memo(function FileExplorer({ error, expandedPaths, toggleExpand, - previewContent, - previewLoading, - previewError, - loadPreview, - savePreview, - externalChange, - clearExternalChange, - clearPreview, effectiveDirectory, fileStatus, refresh, } = useFileExplorer({ directory, autoLoad: true, sessionId: sessionId || undefined, serverId, consumerId: `file-explorer-${panelTabId}` }) - // 预览状态按工作区作用域(官方 session tab 作用域的等价物): - // 面板 tab 里的 previewFiles 是全局列表,这里只取属于当前工作区的部分; - // 切工作区后另一个工作区的预览不再串过来,切回时恢复该工作区最近打开的预览。 - const scopedPreviewFiles = useMemo( - () => previewFiles.filter(file => previewMatchesDirectory(file, effectiveDirectory)), - [previewFiles, effectiveDirectory], - ) - const scopedPreviewFile = useMemo(() => { - if (previewFile && previewMatchesDirectory(previewFile, effectiveDirectory)) return previewFile - return scopedPreviewFiles[scopedPreviewFiles.length - 1] ?? null - }, [previewFile, scopedPreviewFiles, effectiveDirectory]) - - // 当 previewFile 改变时加载预览 - useEffect(() => { - if (scopedPreviewFile) { - loadPreview(scopedPreviewFile.path) - } else { - clearPreview() + // 已打开的文件(在别的标签页里):在目录树里标出来 + const { panelTabs } = useLayoutStore() + const openFilePaths = useMemo(() => { + const paths = new Set() + for (const tab of panelTabs) { + if (tab.type !== 'file' || !tab.previewFile) continue + if ((tab.previewFile.directory ?? '') !== (effectiveDirectory ?? '')) continue + if ((tab.previewFile.serverId ?? '') !== (serverId ?? '')) continue + paths.add(tab.previewFile.path) } - }, [scopedPreviewFile, loadPreview, clearPreview]) + return paths + }, [effectiveDirectory, panelTabs, serverId]) - const handleRefresh = useCallback(async () => { - await refresh() - if (scopedPreviewFile) { - await loadPreview(scopedPreviewFile.path) - } - }, [loadPreview, scopedPreviewFile, refresh]) - - // 处理文件点击 + // 处理文件点击:在标签栏开一个新标签 const handleFileClick = useCallback( (node: FileTreeNode) => { if (node.type === 'directory') { toggleExpand(node.path) } else { - layoutStore.openFilePreview( - { path: node.path, name: node.name, directory: effectiveDirectory }, + layoutStore.openFileTab( + { path: node.path, name: node.name, directory: effectiveDirectory, serverId }, position, ) } }, - [toggleExpand, position, effectiveDirectory], + [toggleExpand, position, effectiveDirectory, serverId], ) const resolveAbsolutePath = useCallback( @@ -249,40 +160,6 @@ export const FileExplorer = memo(function FileExplorer({ } }, [fileContextMenu]) - // 关闭预览 - const handleClosePreview = useCallback(() => { - layoutStore.closeAllFilePreviews(panelTabId) - resetSplitHeight() - }, [panelTabId, resetSplitHeight]) - - // 激活/关闭/重排预览 tab:path 在当前工作区的可见列表里唯一, - // 从可见列表取回目录身份再交给 store(跨工作区同路径不撞) - const handleActivatePreview = useCallback( - (path: string) => { - const file = scopedPreviewFiles.find(item => item.path === path) - layoutStore.activateFilePreview(panelTabId, path, file?.directory) - }, - [panelTabId, scopedPreviewFiles], - ) - - const handleClosePreviewTab = useCallback( - (path: string) => { - const file = scopedPreviewFiles.find(item => item.path === path) - layoutStore.closeFilePreview(panelTabId, path, file?.directory) - }, - [panelTabId, scopedPreviewFiles], - ) - - const handleReorderPreviewTabs = useCallback( - (draggedPath: string, targetPath: string) => { - const directory = scopedPreviewFiles.find(item => item.path === draggedPath)?.directory - layoutStore.reorderFilePreviews(panelTabId, draggedPath, targetPath, directory) - }, - [panelTabId, scopedPreviewFiles], - ) - - // 是否显示预览 - const showPreview = Boolean(scopedPreviewFile) || previewLoading || Boolean(previewError) const trimmedSearchQuery = searchQuery.trim() const isSearching = trimmedSearchQuery.length > 0 @@ -322,9 +199,9 @@ export const FileExplorer = memo(function FileExplorer({ const handleFileResultClick = useCallback( (path: string) => { const name = path.split(/[/\\]/).pop() || path - layoutStore.openFilePreview({ path, name, directory: effectiveDirectory }, position) + layoutStore.openFileTab({ path, name, directory: effectiveDirectory, serverId }, position) }, - [position, effectiveDirectory], + [position, effectiveDirectory, serverId], ) const handleSearchQueryChange = useCallback((value: string) => { @@ -356,98 +233,86 @@ export const FileExplorer = memo(function FileExplorer({ } return ( -
- {/* File Tree - 使用 CSS 变量控制高度 */} -
- {/* Tree Header */} -
-
- - handleSearchQueryChange(e.target.value)} - placeholder={t('fileExplorer.searchFiles')} - aria-label={t('fileExplorer.searchFiles')} - autoComplete="off" - className="w-full bg-bg-200/40 hover:bg-bg-200/60 focus:bg-bg-000 border border-transparent focus:border-border-200 rounded-lg py-1 pl-[30px] pr-7 text-[length:var(--fs-xs)] text-text-100 placeholder:text-text-400/70 focus-visible:ring-1 focus-visible:ring-border-200 focus-visible:ring-inset transition-all" - /> - {searchQuery && ( - - )} -
- -
-
- - {/* Tree Content */} -
- {isSearching ? ( - - ) : isLoading && tree.length === 0 ? ( -
- {t('common:loading')} -
- ) : error ? ( -
- - {error} -
- ) : tree.length === 0 ? ( -
- {t('fileExplorer.noFilesFound')} -
- ) : ( -
- {tree.map(node => ( - - ))} -
+
+ {/* Tree Header */} +
+
+ + handleSearchQueryChange(e.target.value)} + placeholder={t('fileExplorer.searchFiles')} + aria-label={t('fileExplorer.searchFiles')} + autoComplete="off" + className="w-full bg-bg-200/40 hover:bg-bg-200/60 focus:bg-bg-000 border border-transparent focus:border-border-200 rounded-lg py-1 pl-[30px] pr-7 text-[length:var(--fs-xs)] text-text-100 placeholder:text-text-400/70 focus-visible:ring-1 focus-visible:ring-border-200 focus-visible:ring-inset transition-all" + /> + {searchQuery && ( + )}
+ +
+
+ + {/* Tree Content */} +
+ {isSearching ? ( + + ) : isLoading && tree.length === 0 ? ( +
+ {t('common:loading')} +
+ ) : error ? ( +
+ + {error} +
+ ) : tree.length === 0 ? ( +
+ {t('fileExplorer.noFilesFound')} +
+ ) : ( +
+ {tree.map(node => ( + + ))} +
+ )}
{fileContextMenu && @@ -467,47 +332,6 @@ export const FileExplorer = memo(function FileExplorer({
, document.body, )} - - {/* Resize Handle - 与标签栏同色 */} - {showPreview && ( -
- )} - - {/* Preview Area */} - {showPreview && ( -
- { - await loadPreview(reloadPath, true) - }} - isLoading={previewLoading} - error={previewError} - onClose={handleClosePreview} - onActivatePreview={handleActivatePreview} - onClosePreview={handleClosePreviewTab} - onReorderPreview={handleReorderPreviewTabs} - isResizing={isAnyResizing} - directory={directory} - /> -
- )}
) }) @@ -628,6 +452,8 @@ interface FileTreeItemProps { depth: number expandedPaths: Set fileStatus: Map + /** 已在其它标签页打开的文件 */ + openFilePaths: Set onClick: (node: FileTreeNode) => void onContextMenu?: (event: React.MouseEvent, path: string, absolute?: string) => void } @@ -637,6 +463,7 @@ const FileTreeItem = memo(function FileTreeItem({ depth, expandedPaths, fileStatus, + openFilePaths, onClick, onContextMenu, }: FileTreeItemProps) { @@ -644,6 +471,7 @@ const FileTreeItem = memo(function FileTreeItem({ const isDirectory = node.type === 'directory' // node.path 可能用反斜杠(Windows),statusMap key 统一用正斜杠 const status = fileStatus.get(node.path) || fileStatus.get(node.path.replace(/\\/g, '/')) + const isOpen = openFilePaths.has(node.path) // 状态颜色 const statusColor = useMemo(() => { @@ -684,7 +512,7 @@ const FileTreeItem = memo(function FileTreeItem({ className={` w-full flex items-center gap-1 px-2 py-0.5 text-left cursor-default select-none hover:bg-bg-200/50 transition-colors text-[length:var(--fs-sm)] - text-text-300 + ${isOpen ? 'text-accent-main-100' : 'text-text-300'} `} style={{ paddingLeft: `${depth * 12 + 8}px` }} > @@ -731,6 +559,7 @@ const FileTreeItem = memo(function FileTreeItem({ depth={depth + 1} expandedPaths={expandedPaths} fileStatus={fileStatus} + openFilePaths={openFilePaths} onClick={onClick} onContextMenu={onContextMenu} /> @@ -740,1113 +569,3 @@ const FileTreeItem = memo(function FileTreeItem({
) }) - -// ============================================ -// File Preview -// ============================================ - -interface FilePreviewProps { - previewFiles: PreviewFile[] - path: string | null - targetLine?: number - targetKey?: string - targetRanges?: readonly TargetLineRange[] - content: FileContent | null - isLoading: boolean - error: string | null - onClose: () => void - onActivatePreview: (path: string) => void - onClosePreview: (path: string) => void - onReorderPreview: (draggedPath: string, targetPath: string) => void - /** 保存(需求三:基线比对 + 保真写回);未提供则不可编辑保存 */ - onSave?: (path: string, text: string, baselineHash?: string, force?: boolean, unifyEol?: boolean) => Promise - /** 冲突时"重新载入":绕过缓存从磁盘重读 */ - onReload?: (path: string) => Promise | void - /** 正在预览的文件被外部改动过(agent / 别的编辑器) */ - externalChange?: { path: string } | null - onClearExternalChange?: () => void - isResizing?: boolean - directory?: string -} - -function FilePreview({ - previewFiles, - path, - targetLine, - targetKey, - targetRanges, - content, - isLoading, - error, - onClose, - onActivatePreview, - onClosePreview, - onReorderPreview, - onSave, - onReload, - externalChange, - onClearExternalChange, - isResizing = false, - directory, -}: FilePreviewProps) { - const { t } = useTranslation(['components', 'common']) - const scrollRef = useRef(null) - - // ============================================ - // 编辑模式(需求三,交互对齐 PiUI) - // - // 显式进入编辑态:铅笔 → ✓ 保存 / ✕ 取消。dirty = 草稿与磁盘内容不同; - // 保存失败在内容区顶部给横幅,冲突(STALE_REVISION)额外给"重新载入 / 覆盖"。 - // ============================================ - const [isEditing, setIsEditing] = useState(false) - const [draft, setDraft] = useState('') - const [isSaving, setIsSaving] = useState(false) - const [saveError, setSaveError] = useState(null) - const [saveConflict, setSaveConflict] = useState(false) - - /** 上次保存因混合行尾被拒(显示"按多数行尾统一"兜底按钮) */ - const [mixEolFallback, setMixEolFallback] = useState(false) - /** 进入编辑时的基线指纹:保存前用它判断磁盘是否被别人改过 */ - const [baselineHash, setBaselineHash] = useState() - - const originalText = content && !content.isBinary ? content.content : '' - - const beginEditing = useCallback(() => { - if (!content || content.isBinary) return - setDraft(content.content) - setSaveError(null) - setSaveConflict(false) - setBaselineHash(content.bytes ? hashBytes(content.bytes) : undefined) - setIsEditing(true) - }, [content]) - - const cancelEditing = useCallback(() => { - setIsEditing(false) - setDraft('') - setSaveError(null) - setSaveConflict(false) - }, []) - - const saveEditing = useCallback( - async (force = false, unifyEol = false) => { - if (!path || isSaving || !onSave) return - setIsSaving(true) - setSaveError(null) - try { - await onSave(path, draft, baselineHash, force, unifyEol) - setIsEditing(false) - setSaveConflict(false) - setMixEolFallback(false) - } catch (failure) { - setSaveError(failure instanceof Error ? failure.message : t('fileExplorer.saveFailed')) - setMixEolFallback(Boolean(failure && typeof failure === 'object' && 'code' in failure && failure.code === 'MIXED_EOL')) - setSaveConflict( - Boolean(failure && typeof failure === 'object' && 'code' in failure && failure.code === 'STALE_REVISION'), - ) - } finally { - setIsSaving(false) - } - }, - [baselineHash, draft, isSaving, onSave, path, t], - ) - - const isDirty = isEditing && draft !== originalText - - /** - * 二次确认:写盘前、丢改动前都先让人看一眼 diff(防误触)。 - * run 是"确认后才执行"的动作,所以切 tab / 关 tab 也能挂进来。 - */ - const [confirmState, setConfirmState] = useState<{ mode: 'save' | 'discard'; conflict?: boolean; run: () => void } | null>( - null, - ) - const requestSave = useCallback( - (force: boolean) => { - if (!isDirty && !force) return - setConfirmState({ mode: 'save', conflict: force || saveConflict, run: () => void saveEditing(force) }) - }, - [isDirty, saveConflict, saveEditing], - ) - const requestDiscard = useCallback( - (run: () => void) => { - if (!isDirty) { - run() - return - } - setConfirmState({ mode: 'discard', run }) - }, - [isDirty], - ) - - /** 外部改动的一次性轻提示(几秒后自己消失,不打断输入) */ - const [externalNotice, setExternalNotice] = useState(null) - useEffect(() => { - if (!externalChange || externalChange.path !== path) return - if (isDirty) { - // 我在改、磁盘也变了:不覆盖草稿,标成冲突,保存时基线比对会再确认一次 - setSaveConflict(true) - setSaveError(t('fileExplorer.saveConflict')) - } else { - setExternalNotice(t('fileExplorer.externalUpdated')) - } - onClearExternalChange?.() - }, [externalChange, isDirty, onClearExternalChange, path, t]) - - useEffect(() => { - if (!externalNotice) return - const timer = window.setTimeout(() => setExternalNotice(null), 4000) - return () => window.clearTimeout(timer) - }, [externalNotice]) - - // 应用级脏标记(关窗/离开前拦一道) - useEffect(() => { - if (!path) return - // editorId 带目录:不同工作区可能有同名文件,只按相对路径会串号 - const editorId = `${directory ?? ""}::${path}` - setFileEditorDirty(editorId, isDirty) - return () => setFileEditorDirty(editorId, false) - }, [directory, isDirty, path]) - - useEffect(() => { - if (!isDirty) return - const beforeUnload = (event: BeforeUnloadEvent) => event.preventDefault() - window.addEventListener('beforeunload', beforeUnload) - return () => window.removeEventListener('beforeunload', beforeUnload) - }, [isDirty]) - - // Ctrl/Cmd+S 保存(编辑器自身不绑,避免和输入框抢) - useEffect(() => { - if (!isEditing) return - const onKeyDown = (event: KeyboardEvent) => { - if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { - event.preventDefault() - requestSave(false) - } - } - window.addEventListener('keydown', onKeyDown) - return () => window.removeEventListener('keydown', onKeyDown) - }, [isEditing, requestSave]) - - // 获取文件名 - const fileName = path?.split(/[/\\]/).pop() || 'Untitled' - const language = path ? detectLanguage(path) : 'text' - - // 下载当前文件 - const handleDownload = useCallback(() => { - if (content) { - downloadFileContent(content, fileName) - } - }, [content, fileName]) - - const previewTabItems = useMemo( - () => - previewFiles.map(file => ({ - id: file.path, - title: file.path, - closeTitle: `${t('common:close')} ${file.name}`, - iconPath: file.path, - label: ( - - {file.path === path && isDirty && ( - - ● - - )} - {file.path === path && saveConflict && ⚠} - {file.name} - - ), - })), - [isDirty, path, previewFiles, saveConflict, t], - ) - - // 处理内容类型分发 - const displayContent = useMemo(() => { - if (!content) return null - - // v2 的 file.read 只返回原始字节:没有 mimeType,也没有 base64 encoding。 - // MIME 由路径推断,二进制与否用解码结果判断。 - const mimeType = getMimeFromPath(content.path) - const isBinary = content.isBinary - const category = getPreviewCategory(mimeType) - - if (isHtmlPreview(language, mimeType)) { - return { - type: 'html' as const, - text: content.content, - } - } - - if (isMarkdownPreview(language, mimeType)) { - return { - type: 'markdown' as const, - text: content.content, - } - } - - // 文本型可渲染媒体(如 SVG)— 同时提供渲染和源码 - if (isTextualMedia(mimeType)) { - return { - type: 'textMedia' as const, - text: content.content, - dataUrl: buildTextDataUrl(mimeType, content.content), - category: category!, - mimeType, - } - } - - // 二进制 + 可预览的媒体类型:从原始字节构造 data URL - if (isBinary && category) { - return { - type: 'media' as const, - category, - dataUrl: buildBytesDataUrl(mimeType, content.bytes), - mimeType, - } - } - - // 二进制 + 不可预览 - if (isBinary) { - return { - type: 'binary' as const, - mimeType: mimeType || 'application/octet-stream', - } - } - - // diff 渲染交给 Changes 面板,Files 预览只显示文件内容 - // if (content.patch && content.patch.hunks.length > 0) { - // return { - // type: 'diff' as const, - // hunks: content.patch.hunks, - // } - // } - - // 显示文件内容 - return { - type: 'text' as const, - text: content.content, - } - }, [content, language]) - - // 全屏内容 - const fullscreenContent = useMemo((): ReactNode => { - if (!displayContent) return null - switch (displayContent.type) { - case 'media': - return ( - - ) - case 'binary': - return - case 'textMedia': - return ( - - ) - case 'markdown': - return ( - - ) - case 'html': - return ( - - ) - case 'text': - return ( - - ) - default: - return null - } - }, [directory, displayContent, fileName, handleDownload, language, path, targetKey, targetLine, targetRanges]) - - const fullscreenHeaderRight = useMemo( - () => - content ? ( - - ) : null, - [content, fileName, handleDownload, t], - ) - - const fullscreenLayer = useMemo( - () => - fullscreenContent - ? { - id: `file-preview:${path || fileName}`, - title: fileName, - headerRight: fullscreenHeaderRight, - content: fullscreenContent, - deferContent: displayContent?.type === 'html', - } - : null, - [displayContent?.type, fileName, fullscreenContent, fullscreenHeaderRight, path], - ) - const { isOpen: isFullscreenOpen, open: openFullscreen } = useFullscreenLayer(fullscreenLayer) - - return ( -
- requestDiscard(() => onActivatePreview(nextPath))} - onClose={closePath => requestDiscard(() => onClosePreview(closePath))} - onCloseAll={() => requestDiscard(() => onClose())} - onReorder={onReorderPreview} - tabWidthClassName="w-auto max-w-none min-w-max" - rightActions={ - content ? ( - <> - {!content.isBinary && - (isEditing ? ( - <> - - - - ) : ( - - ))} - - - - ) : null - } - /> - - setConfirmState(null)} - onConfirm={() => { - const pending = confirmState - setConfirmState(null) - pending?.run() - }} - /> - - {/* Preview Content */} -
- {externalNotice && ( -
- {externalNotice} -
- )} - {isLoading ? ( -
- {t('common:loading')} -
- ) : error ? ( -
- - {error} -
- ) : isEditing ? ( - // 编辑态优先于"预览类型"分发:md / html / svg 这类带预览的文件, - // 进编辑态要直接切到源码编辑(而不是继续渲染预览) -
- {saveError && ( -
- {saveError} - {mixEolFallback && ( - - )} - {saveConflict && ( - - - - - )} -
- )} -
- -
-
- ) : displayContent?.type === 'media' ? ( - - ) : displayContent?.type === 'binary' ? ( - - ) : displayContent?.type === 'textMedia' ? ( - - ) : displayContent?.type === 'markdown' ? ( - - ) : displayContent?.type === 'html' ? ( - isFullscreenOpen ? null : ( - - ) - ) : // diff 渲染已移至 Changes 面板 - // ) : displayContent?.type === 'diff' ? ( - // - displayContent?.type === 'text' && !isEditing ? ( - - ) : displayContent?.type === 'text' ? null : ( -
- {t('common:noContent')} -
- )} -
-
- ) -} - -// ============================================ -// Media Preview - 路由到具体渲染器 -// ============================================ - -interface MediaPreviewProps { - category: PreviewCategory - dataUrl: string - mimeType: string - fileName: string -} - -function MediaPreview({ category, dataUrl, mimeType, fileName }: MediaPreviewProps) { - switch (category) { - case 'image': - return - case 'audio': - return ( -
-
{formatMimeType(mimeType)}
-
- ) - case 'video': - return ( -
-
- ) - case 'pdf': - return