feat: add .mmd/.mermaid file viewer with rendered diagram toggle (#597)

Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com>
This commit is contained in:
Ramzi
2026-04-14 19:26:55 -07:00
committed by GitHub
co-authored by Jinwoo-H
parent 3b897d255d
commit fb5afc3aab
6 changed files with 513 additions and 6 deletions
@@ -240,6 +240,26 @@
font-size: 0.85em;
margin-bottom: 0.5em;
}
/* Full-file mermaid diagram viewer — used when opening .mmd/.mermaid files
in diagram mode. Centers the rendered SVG and adds padding so diagrams
don't press against viewport edges. */
.mermaid-viewer {
background: var(--color-background, transparent);
}
.mermaid-viewer-canvas {
display: flex;
align-items: flex-start;
justify-content: center;
min-height: 100%;
padding: 32px 24px;
}
.mermaid-viewer-canvas .mermaid-block {
width: 100%;
}
.mermaid-viewer-canvas .mermaid-block svg {
width: 100%;
height: auto;
}
.markdown-body ul,
.markdown-body ol {
@@ -16,6 +16,7 @@ const RichMarkdownEditor = lazy(() => import('./RichMarkdownEditor'))
const MarkdownPreview = lazy(() => import('./MarkdownPreview'))
const ImageViewer = lazy(() => import('./ImageViewer'))
const ImageDiffViewer = lazy(() => import('./ImageDiffViewer'))
const MermaidViewer = lazy(() => import('./MermaidViewer'))
const richMarkdownSizeEncoder = new TextEncoder()
// Why: encodeInto() with a pre-allocated buffer avoids creating a new
@@ -40,6 +41,7 @@ export function EditorContent({
worktreeEntries,
resolvedLanguage,
isMarkdown,
isMermaid,
mdViewMode,
sideBySide,
pendingEditorReveal,
@@ -55,6 +57,7 @@ export function EditorContent({
worktreeEntries: GitStatusEntry[]
resolvedLanguage: string
isMarkdown: boolean
isMermaid: boolean
mdViewMode: MarkdownViewMode
sideBySide: boolean
pendingEditorReveal: {
@@ -282,7 +285,17 @@ export function EditorContent({
<div className="flex flex-1 min-h-0 flex-col">
{activeFile.conflict && <ConflictBanner file={activeFile} entry={activeConflictEntry} />}
<div className="min-h-0 flex-1 relative">
{isMarkdown ? renderMarkdownContent(fc) : renderMonacoEditor(fc)}
{isMarkdown ? (
renderMarkdownContent(fc)
) : isMermaid && mdViewMode === 'rich' ? (
<MermaidViewer
key={activeFile.id}
content={editBuffers[activeFile.id] ?? fc.content}
filePath={activeFile.filePath}
/>
) : (
renderMonacoEditor(fc)
)}
</div>
</div>
)
@@ -151,6 +151,10 @@ function EditorPanelInner({
// last active.
scrollTopCache.delete(`${prevFile.filePath}:rich`)
scrollTopCache.delete(`${prevFile.filePath}:preview`)
// Why: mermaid files use a mode-scoped cache key just like markdown.
// Without this, a reopened .mmd file would restore a stale scroll
// position from the previous session even if the content changed.
scrollTopCache.delete(`${prevFile.filePath}:mermaid-diagram`)
cursorPositionCache.delete(prevFile.filePath)
deleteCacheEntriesByPrefix(cursorPositionCache, `${prevFile.filePath}::`)
break
@@ -599,10 +603,13 @@ function EditorPanelInner({
)
const isMarkdown = resolvedLanguage === 'markdown'
const mdViewMode: MarkdownViewMode =
isMarkdown && activeFile.mode === 'edit'
? (markdownViewMode[activeFile.id] ?? 'rich')
: 'source'
const isMermaid = resolvedLanguage === 'mermaid'
// Why: mermaid files reuse the same per-file view mode store as markdown.
// Both default to 'rich' (rendered view) and fall back to 'source' (Monaco).
const hasViewModeToggle = (isMarkdown || isMermaid) && activeFile.mode === 'edit'
const mdViewMode: MarkdownViewMode = hasViewModeToggle
? (markdownViewMode[activeFile.id] ?? 'rich')
: 'source'
const handleOpenDiffTargetFile = (): void => {
if (!openFileState.canOpen) {
@@ -731,7 +738,7 @@ function EditorPanelInner({
</Tooltip>
</TooltipProvider>
)}
{isMarkdown && activeFile.mode === 'edit' && (
{hasViewModeToggle && (
<MarkdownViewToggle
mode={mdViewMode}
onChange={(mode) => setMarkdownViewMode(activeFile.id, mode)}
@@ -749,6 +756,7 @@ function EditorPanelInner({
worktreeEntries={worktreeEntries}
resolvedLanguage={resolvedLanguage}
isMarkdown={isMarkdown}
isMermaid={isMermaid}
mdViewMode={mdViewMode}
sideBySide={sideBySide}
pendingEditorReveal={pendingEditorReveal}
@@ -0,0 +1,104 @@
import React, { useLayoutEffect, useRef } from 'react'
import { useAppStore } from '@/store'
import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache'
import MermaidBlock from './MermaidBlock'
type MermaidViewerProps = {
content: string
filePath: string
}
// Why: MermaidViewer is the full-file counterpart to MermaidBlock (which
// renders fenced mermaid blocks inside markdown). When a user opens a .mmd
// or .mermaid file in diagram mode, the entire file content is the diagram
// source — no markdown wrapper, no frontmatter, just mermaid syntax.
export default function MermaidViewer({
content,
filePath
}: MermaidViewerProps): React.JSX.Element {
const rootRef = useRef<HTMLDivElement>(null)
const settings = useAppStore((s) => s.settings)
const isDark =
settings?.theme === 'dark' ||
(settings?.theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)
// Why: Each viewing mode (source vs diagram) produces different DOM heights.
// Mode-scoped keys prevent restoring a source-mode scroll position in diagram
// mode (same reasoning as MarkdownPreview's scrollCacheKey).
const scrollCacheKey = `${filePath}:mermaid-diagram`
useLayoutEffect(() => {
const container = rootRef.current
if (!container) {
return
}
let throttleTimer: ReturnType<typeof setTimeout> | null = null
const onScroll = (): void => {
if (throttleTimer !== null) {
clearTimeout(throttleTimer)
}
throttleTimer = setTimeout(() => {
setWithLRU(scrollTopCache, scrollCacheKey, container.scrollTop)
throttleTimer = null
}, 150)
}
container.addEventListener('scroll', onScroll, { passive: true })
return () => {
// Why: guard against writing 0 when the SVG has not rendered yet (e.g.,
// StrictMode double-mount or quick tab switch before mermaid.render()
// completes). Without this, a valid cached position gets clobbered.
if (container.scrollHeight > container.clientHeight || container.scrollTop > 0) {
setWithLRU(scrollTopCache, scrollCacheKey, container.scrollTop)
}
if (throttleTimer !== null) {
clearTimeout(throttleTimer)
}
container.removeEventListener('scroll', onScroll)
}
}, [scrollCacheKey])
useLayoutEffect(() => {
const container = rootRef.current
const targetScrollTop = scrollTopCache.get(scrollCacheKey)
if (!container || targetScrollTop === undefined) {
return
}
let frameId = 0
let attempts = 0
// Why: mermaid.render() is async, so the SVG may not exist on the first
// frame. Retry up to 30 frames (~500ms) to match MarkdownPreview's pattern.
const tryRestore = (): void => {
const maxScrollTop = Math.max(0, container.scrollHeight - container.clientHeight)
const nextScrollTop = Math.min(targetScrollTop, maxScrollTop)
container.scrollTop = nextScrollTop
if (Math.abs(container.scrollTop - targetScrollTop) <= 1 || maxScrollTop >= targetScrollTop) {
return
}
attempts += 1
if (attempts < 30) {
frameId = window.requestAnimationFrame(tryRestore)
}
}
tryRestore()
return () => window.cancelAnimationFrame(frameId)
}, [scrollCacheKey, content])
return (
<div ref={rootRef} className="mermaid-viewer h-full min-h-0 overflow-auto scrollbar-editor">
<div className="mermaid-viewer-canvas">
{/* Why: DOMPurify's SVG profile strips <foreignObject> elements that
mermaid uses for HTML labels. Force SVG-native <text> labels so
they survive sanitization — same fix as the markdown preview path. */}
<MermaidBlock content={content.trim()} isDark={isDark} htmlLabels={false} />
</div>
</div>
)
}
+2
View File
@@ -18,6 +18,8 @@ const EXT_TO_LANGUAGE: Record<string, string> = {
'.jsonc': 'json',
'.md': 'markdown',
'.mdx': 'markdown',
'.mmd': 'mermaid',
'.mermaid': 'mermaid',
'.css': 'css',
'.scss': 'scss',
'.less': 'less',