import { useEffect, useState, useCallback, useRef, useMemo } from "react"; import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import remarkFrontmatter from "remark-frontmatter"; import rehypeRaw from "rehype-raw"; import { fetchFile, saveFile, resolveWikilink, ConflictResult } from "../api"; import { PencilSimple, FloppyDisk, X, Check, WarningCircle, CaretRight, ArrowUp, Copy, Warning, ArrowsClockwise, PenNib, Cube } from "@phosphor-icons/react"; import { PluginSlot } from "../plugins/PluginSlot"; import { SensitiveText } from "./SensitiveMask"; import { useLocale } from "../hooks/useLocale"; import { lazy, Suspense } from "react"; import { renderMermaid, THEMES } from "beautiful-mermaid"; import { useMarkdownTheme } from "../themes"; import { applyThemeStyles, cleanInlineStyles } from "../themes/apply"; import mermaid from "mermaid"; const MarkdownEditor = lazy(() => import("./MarkdownEditor").then(m => ({ default: m.MarkdownEditor }))); // Initialize mermaid for different styles function initMermaid(isDark: boolean, handDrawn: boolean) { mermaid.initialize({ startOnLoad: false, securityLevel: "loose", theme: isDark ? "dark" : "default", look: handDrawn ? "handDrawn" : "classic", fontFamily: handDrawn ? "Virgil, Segoe Print, Bradley Hand, Chilanka, TSCu_Comic, casual, cursive" : "Inter, sans-serif", }); } type MermaidStyle = "normal" | "handDrawn"; /** Mermaid diagram renderer with style toggle */ function MermaidBlock({ code }: { code: string }) { const [svg, setSvg] = useState(""); const [error, setError] = useState(""); const [style, setStyle] = useState("normal"); const containerRef = useRef(null); useEffect(() => { const isDark = document.documentElement.classList.contains("dark"); // Generate unique ID for each render to avoid conflicts const renderId = `mermaid-${Math.random().toString(36).slice(2)}`; if (style === "handDrawn") { // Use native mermaid with hand-drawn look initMermaid(isDark, true); console.log("[Mermaid] Rendering hand-drawn style with ID:", renderId); mermaid.render(renderId, code) .then((result) => { console.log("[Mermaid] Render success, svg length:", result.svg?.length); setSvg(result.svg); setError(""); }) .catch((e) => { console.error("[Mermaid] Render failed:", e); setError(e.message || "Failed to render diagram"); setSvg(""); }); } else { // Use beautiful-mermaid for normal style const baseTheme = isDark ? THEMES["github-dark"] : THEMES["github-light"]; const theme = { ...baseTheme, bg: "transparent" }; renderMermaid(code, theme) .then((result) => { setSvg(typeof result === "string" ? result : (result as any).svg || String(result)); setError(""); }) .catch((e) => { setError(e.message || "Failed to render diagram"); setSvg(""); }); } }, [code, style]); if (error) { return (
โš  Mermaid render error: {error}
{code}
); } if (!svg) { return
Rendering diagram...
; } return (
{/* Style toggle button */}
); } /** Extract YAML front matter and return { meta, body } */ interface FrontMatterResult { meta: Record | null; metadata: Record | null; body: string; } function parseFrontMatter(raw: string): FrontMatterResult { const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/); if (!match) return { meta: null, metadata: null, body: raw }; const yamlBlock = match[1]; const body = match[2]; const meta: Record = {}; let metadata: Record | null = null; for (const line of yamlBlock.split("\n")) { const idx = line.indexOf(":"); if (idx > 0) { const key = line.slice(0, idx).trim(); const val = line.slice(idx + 1).trim().replace(/^['"]|['"]$/g, ""); if (!key || !val) continue; if (key === "metadata") { try { metadata = JSON.parse(val); } catch { meta[key] = val; } } else { meta[key] = val; } } } return { meta: Object.keys(meta).length ? meta : null, metadata, body }; } /** Recursively wrap string children with SensitiveText and WikiLinks */ function maskChildren(children: React.ReactNode, onOpenFile?: (path: string) => void): React.ReactNode { if (typeof children === "string") { // Check for wikilinks first if (children.includes("[[")) { const parts = processWikiLinks(children, onOpenFile); return parts.map((part, i) => typeof part === "string" ? {part} : part ); } return {children}; } if (Array.isArray(children)) return children.map((c, i) => typeof c === "string" ? ( c.includes("[[") ? ( {processWikiLinks(c, onOpenFile).map((part, j) => typeof part === "string" ? {part} : part )} ) : {c} ) : c ); return children; } /** Shiki highlighter singleton */ import { createHighlighter, type Highlighter } from "shiki"; let highlighterPromise: Promise | null = null; function getHighlighter(): Promise { if (!highlighterPromise) { highlighterPromise = createHighlighter({ themes: ["github-dark", "github-light"], langs: ["bash", "javascript", "typescript", "python", "json", "yaml", "markdown", "css", "html", "go", "rust", "sql", "diff", "dockerfile", "toml", "ini", "tsx", "jsx", "java", "c", "cpp", "shell", "ruby", "php", "swift", "kotlin"], }); } return highlighterPromise; } /** Code block with copy button */ function CodeBlock({ className, children, ...props }: any) { const { t } = useLocale(); const [copied, setCopied] = useState(false); const [html, setHtml] = useState(""); const match = /language-(\w+)/.exec(className || ""); const text = String(children).replace(/\n$/, ""); const isBlock = !!match || text.includes("\n"); const isDark = document.documentElement.classList.contains("dark"); useEffect(() => { if (!isBlock || !match) return; if (match[1] === "mermaid") return; let cancelled = false; getHighlighter().then((hl) => { if (cancelled) return; const lang = hl.getLoadedLanguages().includes(match[1] as any) ? match[1] : "text"; const result = hl.codeToHtml(text, { lang, theme: isDark ? "github-dark" : "github-light", }); setHtml(result); }); return () => { cancelled = true; }; }, [text, match?.[1], isDark, isBlock]); if (!isBlock) { if (typeof children === "string") { return {children}; } return {children}; } // Mermaid diagrams if (match && match[1] === "mermaid") { return ; } // Plain text code blocks (no language) - use simple
 for uniform background
  if (!match) {
    return (
      
          {text}
        
); } return (
{html ? (
) : (
          {text}
        
)}
); } /** Breadcrumb path */ function Breadcrumb({ path, hasChanges, onNavigate }: { path: string; hasChanges: boolean; onNavigate?: (dir: string) => void }) { const parts = path.split("/"); return ( {hasChanges && "โ— "} {parts.map((part, i) => { const isLast = i === parts.length - 1; const dir = parts.slice(0, i + 1).join("/"); return ( {i > 0 && } {isLast ? ( {part} ) : ( )} ); })} ); } /** WikiLink component: renders [[xxx]] as clickable link */ function WikiLink({ target, onOpenFile }: { target: string; onOpenFile?: (path: string) => void }) { const [resolved, setResolved] = useState<{ found: boolean; path: string | null } | null>(null); useEffect(() => { resolveWikilink(target).then(setResolved).catch(() => setResolved({ found: false, path: null })); }, [target]); const handleClick = (e: React.MouseEvent) => { e.preventDefault(); if (resolved?.found && resolved.path && onOpenFile) { onOpenFile(resolved.path); } }; if (!resolved) return [[{target}]]; if (resolved.found) { return ( {target} ); } return ( {target} ); } /** Process text to replace [[xxx]] with WikiLink components */ function processWikiLinks(text: string, onOpenFile?: (path: string) => void): React.ReactNode[] { const parts: React.ReactNode[] = []; const regex = /\[\[([^\]]+)\]\]/g; let lastIndex = 0; let match; while ((match = regex.exec(text)) !== null) { if (match.index > lastIndex) { parts.push(text.slice(lastIndex, match.index)); } parts.push(); lastIndex = regex.lastIndex; } if (lastIndex < text.length) { parts.push(text.slice(lastIndex)); } return parts; } interface FileViewerProps { filePath: string; refreshKey?: number; onNavigate?: (dir: string) => void; onOpenFile?: (path: string) => void; } export function FileViewer({ filePath, refreshKey, onNavigate, onOpenFile }: FileViewerProps) { const { t } = useLocale(); const [content, setContent] = useState(""); const [editContent, setEditContent] = useState(""); const [mtime, setMtime] = useState(""); const [editing, setEditing] = useState(false); const [loading, setLoading] = useState(true); const [toast, setToast] = useState(""); const [conflict, setConflict] = useState(null); const contentRef = useRef(null); const [showScrollTop, setShowScrollTop] = useState(false); const { current: mdTheme } = useMarkdownTheme(); useEffect(() => { setLoading(true); setEditing(false); fetchFile(filePath) .then((data) => { setContent(data.content); setEditContent(data.content); setMtime(data.mtime); }) .catch(() => showToast(t("file.failedToLoad"))) .finally(() => setLoading(false)); }, [filePath, refreshKey]); // Auto-refresh every 10s when not editing (for when WebSocket is unavailable) useEffect(() => { if (editing) return; const interval = setInterval(() => { fetchFile(filePath).then((data) => { if (data.mtime !== mtime) { setContent(data.content); setEditContent(data.content); setMtime(data.mtime); } }).catch(() => {}); }, 10000); return () => clearInterval(interval); }, [filePath, editing, mtime]); const [refreshing, setRefreshing] = useState(false); const handleRefresh = useCallback(() => { setRefreshing(true); fetchFile(filePath) .then((data) => { setContent(data.content); setEditContent(data.content); setMtime(data.mtime); showToast(t("file.reloaded") || "Refreshed"); }) .catch(() => showToast(t("file.failedToLoad"))) .finally(() => setRefreshing(false)); }, [filePath]); const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(""), 2000); }; const hasChanges = editing && editContent !== content; const handleSave = useCallback(async (force = false) => { try { const result = await saveFile(filePath, editContent, force ? undefined : mtime); if ("error" in result && result.error === "conflict") { setConflict(result as ConflictResult); return; } if ("ok" in result && result.ok) { setContent(editContent); setMtime(result.mtime); setEditing(false); setConflict(null); showToast(t("file.saved")); } } catch { showToast(t("file.saveFailed")); } }, [filePath, editContent, mtime]); const handleConflictOverwrite = useCallback(() => { handleSave(true); }, [handleSave]); const handleConflictReload = useCallback(() => { if (conflict) { setContent(conflict.serverContent); setEditContent(conflict.serverContent); setMtime(conflict.serverMtime); setConflict(null); showToast(t("file.reloaded")); } }, [conflict]); const handleCancel = () => { if (hasChanges && !confirm(t("file.discardChanges"))) return; setEditContent(content); setEditing(false); }; const [isDark, setIsDark] = useState(() => document.documentElement.classList.contains("dark")); useEffect(() => { const obs = new MutationObserver(() => setIsDark(document.documentElement.classList.contains("dark"))); obs.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }); return () => obs.disconnect(); }, []); const handleEdit = () => { setEditing(true); }; useEffect(() => { const handler = (e: BeforeUnloadEvent) => { if (hasChanges) e.preventDefault(); }; window.addEventListener("beforeunload", handler); return () => window.removeEventListener("beforeunload", handler); }, [hasChanges]); const frontMatter = useMemo(() => parseFrontMatter(content), [content]); // Apply markdown theme useEffect(() => { if (!contentRef.current || editing) return; const article = contentRef.current.querySelector(".markdown-body"); if (!article || (!mdTheme.styles && !mdTheme.darkStyles)) { cleanInlineStyles(article); return; } applyThemeStyles(article as HTMLElement, mdTheme); }, [content, mdTheme, editing, refreshKey, isDark]); const fileStats = useMemo(() => { const bytes = new Blob([content]).size; const words = content.trim() ? content.trim().split(/\s+/).length : 0; const sizeStr = bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`; return { sizeStr, words }; }, [content]); const handleScroll = useCallback((e: React.UIEvent) => { setShowScrollTop(e.currentTarget.scrollTop > 300); }, []); const scrollToTop = () => { contentRef.current?.scrollTo({ top: 0, behavior: "smooth" }); }; if (loading) { return (
{t("file.loading")}
); } return (
{/* Toolbar */}
{new Date(mtime).toLocaleString()}
{fileStats.sizeStr} ยท {fileStats.words} {t("file.words")}
{editing ? ( <> ) : ( <> )}
{/* Content */}
{editing ? ( Loading editor...
}> ) : (
{(frontMatter.meta || frontMatter.metadata) && (() => { const md = frontMatter.metadata; const cb = md?.clawdbot || md?.openclaw; const emoji = cb?.emoji || "๐Ÿงฉ"; const requires = cb?.requires; const extraMeta = frontMatter.meta ? Object.entries(frontMatter.meta).filter(([k]) => k !== "name" && k !== "description") : []; return (
{/* Header */}
{frontMatter.meta?.name && (
{emoji}

{frontMatter.meta.name}

)}
{frontMatter.meta?.description && (

{frontMatter.meta.description}

)}
{/* Tags: extra fields + requires */} {(extraMeta.length > 0 || requires) && (
{extraMeta.map(([k, v]) => ( {k}: {v} ))} {requires?.skills?.map((s: string) => ( ๐Ÿ”— {s} ))} {requires?.tools?.map((t: string) => ( ๐Ÿ”ง {t} ))} {requires?.secrets?.map((s: string) => ( ๐Ÿ”‘ {s} ))}
)}
); })()} {children}; }, code: CodeBlock, // Mask in plain text nodes within paragraphs p({ children }) { return

{maskChildren(children, onOpenFile)}

; }, li({ children }) { return
  • {maskChildren(children, onOpenFile)}
  • ; }, td({ children }) { return {maskChildren(children, onOpenFile)}; }, }} >{content}
    )}
    {/* Scroll to top */} {showScrollTop && !editing && ( )} {/* Conflict Dialog */} {conflict && (

    {t("file.conflictTitle")}

    {t("file.conflictDesc")}

    {t("file.conflictTime")}: {new Date(conflict.serverMtime).toLocaleString()}

    )} {/* Toast */} {toast &&
    {toast}
    }
    ); }