import { useState, useCallback, useRef, useEffect, memo } from 'react' import { Button } from '@/components/ui/button' import { Download, X, Edit3, Save, X as XIcon, WrapText, Eye, Code, ExternalLink } from 'lucide-react' import type { FileInfo } from '@/types/files' import { getFileApiUrl } from '@/api/files' import { saveFileFromUrl } from '@/lib/download' import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view' import { MarkdownRenderer } from './MarkdownRenderer' const VIRTUALIZATION_THRESHOLD_BYTES = 50_000 const MARKDOWN_PREVIEW_SIZE_LIMIT = 1_000_000 const SUCCESS_TINT_BUTTON_CLASS = 'h-7 w-7 p-0 border border-success bg-success/10 text-success hover:bg-success/20 hover:text-success dark:hover:bg-success/20' const DESTRUCTIVE_TINT_BUTTON_CLASS = 'h-7 w-7 p-0 border border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 hover:text-destructive dark:hover:bg-destructive/20' interface FilePreviewProps { file: FileInfo hideHeader?: boolean isMobileModal?: boolean onCloseModal?: () => void onFileSaved?: () => void initialLineNumber?: number } export const FilePreview = memo(function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal, onFileSaved, initialLineNumber }: FilePreviewProps) { const isMarkdownFile = file.name.toLowerCase().endsWith('.md') || file.name.toLowerCase().endsWith('.mdx') || file.mimeType === 'text/markdown' const isHtmlFile = /\.html?$/i.test(file.name) || file.mimeType === 'text/html' const hasRenderedPreview = isMarkdownFile || isHtmlFile const previewLabel = isHtmlFile ? 'HTML' : 'markdown' const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview') const [editContent, setEditContent] = useState('') const [isSaving, setIsSaving] = useState(false) const [hasVirtualizedChanges, setHasVirtualizedChanges] = useState(false) const [highlightedLine, setHighlightedLine] = useState(initialLineNumber) const [lineWrap, setLineWrap] = useState(true) const [renderedPreview, setRenderedPreview] = useState(hasRenderedPreview) const [isLoadingAllContent, setIsLoadingAllContent] = useState(false) const [fullContentLoaded, setFullContentLoaded] = useState(false) const [fullContent, setFullContent] = useState(null) const [localMdContent, setLocalMdContent] = useState(null) const virtualizedRef = useRef(null) const contentRef = useRef(null) const shouldVirtualize = file.size > VIRTUALIZATION_THRESHOLD_BYTES && !file.mimeType?.startsWith('image/') const isMarkdownTooLarge = file.size > MARKDOWN_PREVIEW_SIZE_LIMIT const showHtmlPreview = isHtmlFile && renderedPreview && viewMode !== 'edit' const rawFileUrl = getFileApiUrl(file.path, { params: { raw: true } }) useEffect(() => { setFullContentLoaded(false) setRenderedPreview(hasRenderedPreview) setFullContent(null) setLocalMdContent(null) }, [file.path, hasRenderedPreview]) useEffect(() => { if (shouldVirtualize && isMarkdownFile && renderedPreview && !isMarkdownTooLarge && !fullContentLoaded) { const loadContent = async () => { if (!virtualizedRef.current) return setIsLoadingAllContent(true) try { await virtualizedRef.current.loadAll() setFullContentLoaded(true) } catch { setFullContentLoaded(false) } finally { setIsLoadingAllContent(false) } } const timer = setTimeout(loadContent, 0) return () => clearTimeout(timer) } }, [shouldVirtualize, isMarkdownFile, renderedPreview, isMarkdownTooLarge, fullContentLoaded]) useEffect(() => { if (initialLineNumber && contentRef.current && !shouldVirtualize) { const lineHeight = 20 const scrollPosition = (initialLineNumber - 1) * lineHeight setHighlightedLine(initialLineNumber) setTimeout(() => { contentRef.current?.scrollTo({ top: scrollPosition, behavior: 'smooth' }) }, 100) setTimeout(() => { setHighlightedLine(undefined) }, 3000) } }, [initialLineNumber, shouldVirtualize, file.content]) const formatFileSize = (bytes: number) => { if (bytes === 0) return '0 Bytes' const k = 1024 const sizes = ['Bytes', 'KB', 'MB', 'GB'] const i = Math.floor(Math.log(bytes) / Math.log(k)) return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i] } const formatDate = (date: Date) => { return new Date(date).toLocaleString() } const handleDownload = () => { void saveFileFromUrl(getFileApiUrl(file.path, { params: { download: true } }), file.name) } const decodeBase64 = (base64: string): string => { try { const binaryString = atob(base64) const bytes = new Uint8Array(binaryString.length) for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i) } return new TextDecoder('utf-8').decode(bytes) } catch { throw new Error('Failed to decode base64 content') } } const saveFileContent = useCallback(async (content: string) => { const response = await fetch(getFileApiUrl(file.path), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'file', content }), }) if (!response.ok) { throw new Error(`Save failed: ${response.statusText}`) } const event = new CustomEvent('fileSaved', { detail: { path: file.path, content } }) window.dispatchEvent(event) onFileSaved?.() }, [file.path, onFileSaved]) const handleEdit = () => { if (shouldVirtualize) { setViewMode('edit') const event = new CustomEvent('editModeChange', { detail: { isEditing: true } }) window.dispatchEvent(event) return } try { const textContent = file.content ? decodeBase64(file.content) : '' const content = localMdContent ?? textContent setEditContent(content) setViewMode('edit') const event = new CustomEvent('editModeChange', { detail: { isEditing: true } }) window.dispatchEvent(event) } catch (err) { console.error('Failed to load content for editing:', err) } } const handleSave = async () => { setIsSaving(true) try { await saveFileContent(editContent) if (isMarkdownFile) { setLocalMdContent(editContent) } setViewMode('preview') const editEvent = new CustomEvent('editModeChange', { detail: { isEditing: false } }) window.dispatchEvent(editEvent) } catch (err) { console.error('Failed to save file:', err) } finally { setIsSaving(false) } } const handleCancel = () => { setEditContent('') setViewMode('preview') setHasVirtualizedChanges(false) const event = new CustomEvent('editModeChange', { detail: { isEditing: false } }) window.dispatchEvent(event) } const handleVirtualizedSaveStateChange = useCallback((hasChanges: boolean) => { setHasVirtualizedChanges(hasChanges) }, []) const handleVirtualizedSave = useCallback(() => { setViewMode('preview') const editEvent = new CustomEvent('editModeChange', { detail: { isEditing: false } }) window.dispatchEvent(editEvent) const event = new CustomEvent('fileSaved', { detail: { path: file.path } }) window.dispatchEvent(event) onFileSaved?.() }, [file.path, onFileSaved]) const persistMarkdownContent = useCallback(async (content: string, setContent: (content: string) => void) => { setContent(content) setEditContent(content) setIsSaving(true) try { await saveFileContent(content) } catch (err) { console.error('Failed to save markdown checkbox change:', err) } finally { setIsSaving(false) } }, [saveFileContent]) const handleFullMarkdownContentChange = useCallback((content: string) => { void persistMarkdownContent(content, setFullContent) }, [persistMarkdownContent]) const handleLocalMarkdownContentChange = useCallback((content: string) => { void persistMarkdownContent(content, setLocalMdContent) }, [persistMarkdownContent]) const isTextFile = file.mimeType?.startsWith('text/') || ['application/json', 'application/xml', 'text/javascript', 'text/typescript'].includes(file.mimeType || '') const renderContent = () => { if (file.mimeType?.startsWith('image/')) { return (
{file.name}
) } if (showHtmlPreview) { return (