mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Add Markdown Preview to FilePreview Component (#51)
* Adding markdown preview in FilePreview * Refactor markdown rendering into reusable components * Fix: Make syntax highlighting theme-aware * Refactor: Follow project conventions for naming and CSS organization * Refactor: Use virtualization infrastructure for markdown preview - Add loadAll(), fullContent, isFullyLoaded to useVirtualizedContent hook - Expose new methods via VirtualizedTextView ref handle - Remove duplicate fetch in FilePreview, use ref methods instead - Add 1MB size limit for markdown preview with user-friendly message --------- Co-authored-by: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
This commit is contained in:
1 parent
74608a7e2a
commit
f3505de0e1
6 files changed
+220
-16
No files matched your search
@@ -1,14 +1,16 @@
|
||||
import { useState, useCallback, useRef, useEffect, memo } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Download, X, Edit3, Save, X as XIcon, WrapText } from 'lucide-react'
|
||||
import { Download, X, Edit3, Save, X as XIcon, WrapText, Eye, Code } from 'lucide-react'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view'
|
||||
import { MarkdownRenderer } from './MarkdownRenderer'
|
||||
|
||||
|
||||
const API_BASE = API_BASE_URL
|
||||
|
||||
const VIRTUALIZATION_THRESHOLD_BYTES = 8_000
|
||||
const MARKDOWN_PREVIEW_SIZE_LIMIT = 1_000_000
|
||||
|
||||
interface FilePreviewProps {
|
||||
file: FileInfo
|
||||
@@ -20,17 +22,40 @@ interface FilePreviewProps {
|
||||
}
|
||||
|
||||
export const FilePreview = memo(function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal, onFileSaved, initialLineNumber }: FilePreviewProps) {
|
||||
const isMarkdownFile = file.name.endsWith('.md') || file.name.endsWith('.mdx') || file.mimeType === 'text/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<number | undefined>(initialLineNumber)
|
||||
const [lineWrap, setLineWrap] = useState(true)
|
||||
const [markdownPreview, setMarkdownPreview] = useState(isMarkdownFile)
|
||||
const [isLoadingAllContent, setIsLoadingAllContent] = useState(false)
|
||||
const [fullContentLoaded, setFullContentLoaded] = useState(false)
|
||||
const virtualizedRef = useRef<VirtualizedTextViewHandle>(null)
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
|
||||
const shouldVirtualize = file.size > VIRTUALIZATION_THRESHOLD_BYTES && !file.mimeType?.startsWith('image/')
|
||||
const isMarkdownTooLarge = file.size > MARKDOWN_PREVIEW_SIZE_LIMIT
|
||||
|
||||
useEffect(() => {
|
||||
setFullContentLoaded(false)
|
||||
}, [file.path])
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldVirtualize && isMarkdownFile && markdownPreview && !isMarkdownTooLarge && !fullContentLoaded) {
|
||||
const loadContent = async () => {
|
||||
if (!virtualizedRef.current) return
|
||||
setIsLoadingAllContent(true)
|
||||
await virtualizedRef.current.loadAll()
|
||||
setFullContentLoaded(true)
|
||||
setIsLoadingAllContent(false)
|
||||
}
|
||||
const timer = setTimeout(loadContent, 50)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [shouldVirtualize, isMarkdownFile, markdownPreview, isMarkdownTooLarge, fullContentLoaded])
|
||||
|
||||
|
||||
|
||||
@@ -165,18 +190,43 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
}
|
||||
|
||||
if (shouldVirtualize && isTextFile) {
|
||||
const showMarkdownPreview = isMarkdownFile && markdownPreview && viewMode !== 'edit'
|
||||
const fullContent = virtualizedRef.current?.getFullContent()
|
||||
|
||||
return (
|
||||
<VirtualizedTextView
|
||||
ref={virtualizedRef}
|
||||
filePath={file.path}
|
||||
totalLines={file.totalLines}
|
||||
editable={viewMode === 'edit'}
|
||||
onSaveStateChange={handleVirtualizedSaveStateChange}
|
||||
onSave={handleVirtualizedSave}
|
||||
className="h-full"
|
||||
initialLineNumber={initialLineNumber}
|
||||
lineWrap={lineWrap}
|
||||
/>
|
||||
<>
|
||||
<div className={showMarkdownPreview && fullContentLoaded ? 'hidden' : 'h-full'}>
|
||||
<VirtualizedTextView
|
||||
ref={virtualizedRef}
|
||||
filePath={file.path}
|
||||
totalLines={file.totalLines}
|
||||
editable={viewMode === 'edit'}
|
||||
onSaveStateChange={handleVirtualizedSaveStateChange}
|
||||
onSave={handleVirtualizedSave}
|
||||
className="h-full"
|
||||
initialLineNumber={initialLineNumber}
|
||||
lineWrap={lineWrap}
|
||||
/>
|
||||
</div>
|
||||
{showMarkdownPreview && (
|
||||
<>
|
||||
{isMarkdownTooLarge ? (
|
||||
<div className="flex flex-col items-center justify-center h-32 gap-2 text-muted-foreground">
|
||||
<span>File too large for markdown preview (max 1MB)</span>
|
||||
<Button variant="outline" size="sm" onClick={() => setMarkdownPreview(false)}>
|
||||
View raw
|
||||
</Button>
|
||||
</div>
|
||||
) : isLoadingAllContent || !fullContentLoaded ? (
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<div className="w-6 h-6 border-2 border-muted-foreground border-t-transparent rounded-full animate-spin" />
|
||||
</div>
|
||||
) : fullContent ? (
|
||||
<MarkdownRenderer content={fullContent} />
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -208,6 +258,11 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMarkdownFile && markdownPreview) {
|
||||
return <MarkdownRenderer content={textContent} />
|
||||
}
|
||||
|
||||
const lines = textContent.split('\n')
|
||||
return (
|
||||
<div className={`pb-[200px] text-sm bg-muted text-foreground rounded font-mono ${
|
||||
@@ -288,7 +343,19 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 flex-shrink-0 mt-1">
|
||||
{isTextFile && (
|
||||
{isMarkdownFile && viewMode !== 'edit' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={(e) => { e.stopPropagation(); e.preventDefault(); setMarkdownPreview(!markdownPreview) }}
|
||||
className={`h-7 w-7 p-0 ${markdownPreview ? 'bg-primary text-primary-foreground' : ''}`}
|
||||
title={markdownPreview ? "Show raw markdown" : "Preview rendered markdown"}
|
||||
>
|
||||
{markdownPreview ? <Code className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isTextFile && !markdownPreview && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { Components } from 'react-markdown'
|
||||
|
||||
export const markdownComponents: Components = {
|
||||
code({ className, children, ...props }) {
|
||||
const isInline = !className || !className.includes('language-')
|
||||
if (isInline) {
|
||||
return (
|
||||
<code className={className || "bg-accent px-1.5 py-0.5 rounded text-sm text-foreground break-all"} {...props}>
|
||||
{children}
|
||||
</code>
|
||||
)
|
||||
}
|
||||
return <code className={className} {...props}>{children}</code>
|
||||
},
|
||||
pre({ children }) {
|
||||
return (
|
||||
<pre className="bg-accent p-1 rounded-lg overflow-x-auto whitespace-pre-wrap break-words border border-border my-4">
|
||||
{children}
|
||||
</pre>
|
||||
)
|
||||
},
|
||||
p({ children }) {
|
||||
return <p className="text-foreground my-0.5 md:my-1">{children}</p>
|
||||
},
|
||||
strong({ children }) {
|
||||
return <strong className="font-semibold text-foreground">{children}</strong>
|
||||
},
|
||||
ul({ children }) {
|
||||
return <ul className="list-disc text-foreground my-0.5 md:my-1">{children}</ul>
|
||||
},
|
||||
ol({ children }) {
|
||||
return <ol className="list-decimal text-foreground my-0.5 md:my-1">{children}</ol>
|
||||
},
|
||||
li({ children }) {
|
||||
return <li className="text-foreground my-0.5 md:my-1">{children}</li>
|
||||
},
|
||||
table({ children }) {
|
||||
return (
|
||||
<div className="table-wrapper">
|
||||
<table>{children}</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { memo } from 'react'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import { markdownComponents } from './MarkdownComponents'
|
||||
|
||||
interface MarkdownRendererProps {
|
||||
content: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const MarkdownRenderer = memo(function MarkdownRenderer({ content, className = '' }: MarkdownRendererProps) {
|
||||
return (
|
||||
<div className={`pb-[200px] p-4 prose prose-invert prose-enhanced max-w-none text-foreground overflow-hidden break-words leading-snug ${className}`}>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight, rehypeRaw]}
|
||||
components={markdownComponents}
|
||||
>
|
||||
{content}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -17,6 +17,9 @@ interface VirtualizedTextViewProps {
|
||||
|
||||
export interface VirtualizedTextViewHandle {
|
||||
save: () => Promise<void>
|
||||
loadAll: () => Promise<void>
|
||||
getFullContent: () => string | null
|
||||
isFullyLoaded: () => boolean
|
||||
}
|
||||
|
||||
const LINE_HEIGHT = 20
|
||||
@@ -174,6 +177,9 @@ export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, Virtual
|
||||
saveEdits,
|
||||
isSaving,
|
||||
hasUnsavedChanges,
|
||||
loadAll,
|
||||
fullContent,
|
||||
isFullyLoaded,
|
||||
} = useVirtualizedContent({
|
||||
filePath,
|
||||
chunkSize,
|
||||
@@ -389,7 +395,10 @@ export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, Virtual
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
save: handleSave,
|
||||
}), [handleSave])
|
||||
loadAll,
|
||||
getFullContent: () => fullContent,
|
||||
isFullyLoaded: () => isFullyLoaded,
|
||||
}), [handleSave, loadAll, fullContent, isFullyLoaded])
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react'
|
||||
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
|
||||
import { fetchFileRange, applyFilePatches } from '@/api/files'
|
||||
import type { PatchOperation } from '@/types/files'
|
||||
|
||||
@@ -30,6 +30,9 @@ interface UseVirtualizedContentReturn {
|
||||
isSaving: boolean
|
||||
hasUnsavedChanges: boolean
|
||||
prefetchAdjacent: (visibleStart: number, visibleEnd: number) => void
|
||||
loadAll: () => Promise<void>
|
||||
fullContent: string | null
|
||||
isFullyLoaded: boolean
|
||||
}
|
||||
|
||||
export function useVirtualizedContent({
|
||||
@@ -234,6 +237,27 @@ export function useVirtualizedContent({
|
||||
|
||||
const hasUnsavedChanges = editedLines.size > 0
|
||||
|
||||
const loadAll = useCallback(async () => {
|
||||
if (!enabled || !filePath || totalLines === 0) return
|
||||
if (isRangeLoaded(0, totalLines)) return
|
||||
await loadRange(0, totalLines)
|
||||
}, [enabled, filePath, totalLines, isRangeLoaded, loadRange])
|
||||
|
||||
const isFullyLoaded = useMemo(() => {
|
||||
if (totalLines === 0) return false
|
||||
return isRangeLoaded(0, totalLines)
|
||||
}, [totalLines, isRangeLoaded])
|
||||
|
||||
const fullContent = useMemo(() => {
|
||||
if (!isFullyLoaded || totalLines === 0) return null
|
||||
const result: string[] = []
|
||||
for (let i = 0; i < totalLines; i++) {
|
||||
const lineData = lines.get(i)
|
||||
result.push(lineData?.content ?? '')
|
||||
}
|
||||
return result.join('\n')
|
||||
}, [isFullyLoaded, totalLines, lines])
|
||||
|
||||
return {
|
||||
lines,
|
||||
totalLines,
|
||||
@@ -249,5 +273,8 @@ export function useVirtualizedContent({
|
||||
isSaving,
|
||||
hasUnsavedChanges,
|
||||
prefetchAdjacent,
|
||||
loadAll,
|
||||
fullContent,
|
||||
isFullyLoaded,
|
||||
}
|
||||
}
|
||||
@@ -308,3 +308,35 @@ body {
|
||||
font-size: 16px !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Syntax highlighting for markdown code blocks */
|
||||
@import 'highlight.js/styles/github.css' layer(highlight-light);
|
||||
@import 'highlight.js/styles/github-dark.css' layer(highlight-dark);
|
||||
|
||||
@layer highlight-light {
|
||||
:root:not(.dark) .hljs {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
padding: 0.5em;
|
||||
background: var(--color-accent);
|
||||
color: var(--color-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
@layer highlight-dark {
|
||||
.dark .hljs {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
padding: 0.5em;
|
||||
background: var(--color-accent);
|
||||
color: var(--color-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
:root:not(.dark) .hljs-dark {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.dark .hljs:not(.hljs-dark) {
|
||||
display: none;
|
||||
}
|
||||
Reference in new issue
Block a user