feat: interactive task list checkboxes in markdown preview (#267)

* feat: interactive task list checkboxes in markdown preview

* fix: persist markdown checkbox toggles

* fix: sync optimistic markdown checkbox state

* fix: align markdown checkbox preview state

* fix: prevent "0" rendering in file browser header when repoId is 0
This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-06 22:11:49 -04:00
1 parent ac3cfc32f9
commit 95ae584f6a
4 files changed
+141 -23

No files matched your search

@@ -42,6 +42,15 @@ interface UploadProgress {
cancelled: boolean
}
const encodeBase64 = (content: string) => {
const bytes = new TextEncoder().encode(content)
let binary = ''
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i])
}
return btoa(binary)
}
async function readFileEntry(entry: FileSystemFileEntry): Promise<File> {
return new Promise((resolve, reject) => {
entry.file(resolve, reject)
@@ -440,15 +449,27 @@ useEffect(() => {
}, [basePath, loadFiles])
useEffect(() => {
const handleFileSaved = (event: CustomEvent<{ path: string; content: string }>) => {
const handleFileSaved = (event: CustomEvent<{ path: string; content?: string }>) => {
if (selectedFile && selectedFile.path === event.detail.path) {
if (event.detail.content !== undefined) {
const nextFile = {
...selectedFile,
content: encodeBase64(event.detail.content),
size: new Blob([event.detail.content]).size,
lastModified: new Date(),
}
setSelectedFile(nextFile)
onFileSelect?.(nextFile)
return
}
handleFileSelect(selectedFile)
}
}
window.addEventListener('fileSaved', handleFileSaved as EventListener)
return () => window.removeEventListener('fileSaved', handleFileSaved as EventListener)
}, [selectedFile, handleFileSelect])
}, [selectedFile, handleFileSelect, onFileSelect])
useEffect(() => {
if (!isPreviewModalOpen) return
@@ -156,7 +156,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose
<PathDisplay path={displayPath} maxSegments={4} className="truncate" />
</div>
<div className="flex items-center gap-2">
{repoId && !isEditing && (
{repoId != null && !isEditing && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
@@ -32,6 +32,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
const [isLoadingAllContent, setIsLoadingAllContent] = useState(false)
const [fullContentLoaded, setFullContentLoaded] = useState(false)
const [fullContent, setFullContent] = useState<string | null>(null)
const [localMdContent, setLocalMdContent] = useState<string | null>(null)
const virtualizedRef = useRef<VirtualizedTextViewHandle>(null)
const contentRef = useRef<HTMLDivElement>(null)
@@ -42,6 +43,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
setFullContentLoaded(false)
setMarkdownPreview(isMarkdownFile)
setFullContent(null)
setLocalMdContent(null)
}, [file.path, isMarkdownFile])
useEffect(() => {
@@ -113,6 +115,22 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
}
}
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')
@@ -122,7 +140,8 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
}
try {
const content = file.content ? decodeBase64(file.content) : ''
const textContent = file.content ? decodeBase64(file.content) : ''
const content = localMdContent ?? textContent
setEditContent(content)
setViewMode('edit')
const event = new CustomEvent('editModeChange', { detail: { isEditing: true } })
@@ -135,22 +154,13 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
const handleSave = async () => {
setIsSaving(true)
try {
const response = await fetch(getFileApiUrl(file.path), {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'file', content: editContent }),
})
if (!response.ok) {
throw new Error(`Save failed: ${response.statusText}`)
await saveFileContent(editContent)
if (isMarkdownFile) {
setLocalMdContent(editContent)
}
setViewMode('preview')
const editEvent = new CustomEvent('editModeChange', { detail: { isEditing: false } })
window.dispatchEvent(editEvent)
const event = new CustomEvent('fileSaved', { detail: { path: file.path, content: editContent } })
window.dispatchEvent(event)
onFileSaved?.()
} catch (err) {
console.error('Failed to save file:', err)
} finally {
@@ -179,6 +189,27 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
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 || '')
@@ -228,7 +259,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
<div className="w-6 h-6 border-2 border-muted-foreground border-t-transparent rounded-full animate-spin" />
</div>
) : fullContent ? (
<MarkdownRenderer content={fullContent} />
<MarkdownRenderer content={fullContent} onContentChange={handleFullMarkdownContentChange} />
) : null}
</>
)}
@@ -257,7 +288,8 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
try {
const textContent = decodeBase64(file.content)
if (!textContent) {
const displayContent = isMarkdownFile ? localMdContent ?? textContent : textContent
if (!displayContent) {
return (
<div className="text-center text-muted-foreground py-8">
Empty file - click Edit to add content
@@ -266,10 +298,10 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
}
if (isMarkdownFile && markdownPreview) {
return <MarkdownRenderer content={textContent} />
return <MarkdownRenderer content={displayContent} onContentChange={handleLocalMarkdownContentChange} />
}
const lines = textContent.split('\n')
const lines = displayContent.split('\n')
return (
<div className={`pb-[200px] text-sm bg-muted text-foreground rounded font-mono ${
lineWrap ? 'overflow-x-hidden' : 'overflow-x-auto'
@@ -1,22 +1,87 @@
import { memo } from 'react'
import { memo, useMemo, useCallback } 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'
import type { Components } from 'react-markdown'
interface MarkdownRendererProps {
content: string
className?: string
onContentChange?: (newContent: string) => void
}
export const MarkdownRenderer = memo(function MarkdownRenderer({ content, className = '' }: MarkdownRendererProps) {
interface TaskItem {
lineIndex: number
checked: boolean
}
function parseTaskItems(content: string): TaskItem[] {
const items: TaskItem[] = []
const lines = content.split('\n')
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(/^(\s*[-*+]\s+)\[([ xX])\]/i)
if (match) {
items.push({ lineIndex: i, checked: match[2].toLowerCase() === 'x' })
}
}
return items
}
export const MarkdownRenderer = memo(function MarkdownRenderer({ content, className = '', onContentChange }: MarkdownRendererProps) {
const taskItems = useMemo(() => parseTaskItems(content), [content])
const handleToggle = useCallback((taskItem: TaskItem) => {
if (!onContentChange) return
const lines = content.split('\n')
const line = lines[taskItem.lineIndex]
const newLine = line.replace(
/^(\s*[-*+]\s+)\[([ xX])\]/i,
(_, prefix: string, checked: string) => `${prefix}[${checked.toLowerCase() === 'x' ? ' ' : 'x'}]`,
)
if (newLine !== line) {
lines[taskItem.lineIndex] = newLine
onContentChange(lines.join('\n'))
}
}, [content, onContentChange])
const handleInputToggle = useCallback((input: HTMLInputElement) => {
const inputs = Array.from(input.closest('.prose')?.querySelectorAll('input[type="checkbox"]') ?? [])
const taskItem = taskItems[inputs.indexOf(input)]
if (taskItem) {
handleToggle(taskItem)
}
}, [handleToggle, taskItems])
const components: Components = {
...markdownComponents,
input(props) {
const { type, checked, disabled, ...rest } = props
delete (rest as Record<string, unknown>).node
if (type === 'checkbox') {
return (
<input
type="checkbox"
checked={Boolean(checked)}
onChange={(event) => handleInputToggle(event.currentTarget)}
className="cursor-pointer accent-primary"
{...rest}
/>
)
}
return <input type={type} checked={checked} disabled={disabled} {...rest} />
},
}
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}
components={components}
>
{content}
</ReactMarkdown>