page.tsx 13.3 KB
"use client";

import { useState, useEffect, useMemo } from "react";
import { ChevronRight, ChevronDown, Folder, FolderOpen, FileText, Search, BookOpen, Loader2, Download, Check } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { cn } from "@/lib/utils";
import FrontmatterCard from "@/components/FrontmatterCard";
import { parseFrontmatter } from "@/lib/frontmatter";

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "/api";

interface TreeNodeData {
  name: string;
  type: "dir" | "file";
  path: string;
  children?: TreeNodeData[];
}

const sortTreeData = (nodes: TreeNodeData[]): TreeNodeData[] => {
  const sorted = [...nodes].sort((a, b) => {
    if (a.type !== b.type) return a.type === "dir" ? -1 : 1;
    const aIsBottom = a.name === "index.md" || a.name === "log.md";
    const bIsBottom = b.name === "index.md" || b.name === "log.md";
    if (aIsBottom && !bIsBottom) return 1;
    if (!aIsBottom && bIsBottom) return -1;
    return a.name.localeCompare(b.name);
  });
  return sorted.map(node => ({
    ...node,
    children: node.children ? sortTreeData(node.children) : undefined
  }));
};

const filterTree = (nodes: TreeNodeData[], query: string): TreeNodeData[] => {
  if (!query) return nodes;
  const lowerQuery = query.toLowerCase();

  return nodes.map(node => {
    if (node.type === "dir") {
      const filteredChildren = filterTree(node.children || [], query);
      if (filteredChildren.length > 0 || node.name.toLowerCase().includes(lowerQuery)) {
        return { ...node, children: filteredChildren };
      }
      return null;
    } else {
      if (node.name.toLowerCase().includes(lowerQuery)) {
        return node;
      }
      return null;
    }
  }).filter(Boolean) as TreeNodeData[];
};

export default function WikiRepoPage() {
  const [treeData, setTreeData] = useState<TreeNodeData[]>([]);
  const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
  const [selectedFile, setSelectedFile] = useState<string | null>(null);
  const [fileContent, setFileContent] = useState<string>("");
  const [isLoadingTree, setIsLoadingTree] = useState(true);
  const [isLoadingFile, setIsLoadingFile] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedForDownload, setSelectedForDownload] = useState<Set<string>>(new Set());

  const fetchTree = async () => {
    setIsLoadingTree(true);
    try {
      const res = await fetch(`${API_BASE}/wiki/tree`);
      const data = await res.json();
      setTreeData(sortTreeData(data.tree));
    } catch {
      console.error("Failed to fetch tree");
    } finally {
      setIsLoadingTree(false);
    }
  };

  useEffect(() => {
    Promise.resolve().then(() => {
      void fetchTree();
    });
  }, []);

  const fetchFile = async (path: string) => {
    setIsLoadingFile(true);
    setSelectedFile(path);
    setFileContent("");
    try {
      const res = await fetch(`${API_BASE}/wiki/file?path=${encodeURIComponent(path)}`);
      if (res.ok) {
        const data = await res.json();
        setFileContent(data.content);
      } else {
        setFileContent("无法加载文件内容。");
      }
    } catch {
      setFileContent("文件加载失败,请检查网络。");
    } finally {
      setIsLoadingFile(false);
    }
  };

  const toggleFolder = (path: string) => {
    setExpandedFolders(prev => {
      const next = new Set(prev);
      if (next.has(path)) next.delete(path);
      else next.add(path);
      return next;
    });
  };

  const toggleSelectForDownload = (path: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedForDownload(prev => {
      const next = new Set(prev);
      if (next.has(path)) next.delete(path);
      else next.add(path);
      return next;
    });
  };

  const handleBatchDownload = async () => {
    if (selectedForDownload.size === 0) return;
    try {
      const res = await fetch(`${API_BASE}/wiki/download_batch`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ paths: Array.from(selectedForDownload) })
      });
      if (!res.ok) throw new Error("下载失败");
      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "wiki_export.zip";
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    } catch {
      alert("批量下载失败,请检查网络");
    }
  };

  const handleSingleDownload = (path: string) => {
    window.open(`${API_BASE}/wiki/download?path=${encodeURIComponent(path)}`, "_blank");
  };

  const filteredTreeData = useMemo(() => filterTree(treeData, searchQuery), [treeData, searchQuery]);

  const handleSearchChange = (val: string) => {
    setSearchQuery(val);
    if (val) {
      const newExpanded = new Set(expandedFolders);
      const filtered = filterTree(treeData, val);
      const expandAll = (nodes: TreeNodeData[], paths: Set<string>) => {
        nodes.forEach(node => {
          if (node.type === "dir") {
            paths.add(node.path);
            if (node.children) expandAll(node.children, paths);
          }
        });
      };
      expandAll(filtered, newExpanded);
      setExpandedFolders(newExpanded);
    }
  };

  const renderTree = (nodes: TreeNodeData[], level = 0) => {
    return nodes.map((node) => {
      const isExpanded = expandedFolders.has(node.path);
      const isSelected = selectedFile === node.path;
      const isDir = node.type === "dir";

      return (
        <div key={node.path} className="flex flex-col">
          <div
            className={cn(
              "flex items-center gap-1.5 py-1.5 px-2 rounded-lg cursor-pointer transition-colors text-sm font-medium select-none my-0.5 group",
              isSelected ? "bg-blue-100 text-blue-700" : "hover:bg-slate-200 text-slate-700"
            )}
            style={{ paddingLeft: `${level * 12 + 8}px` }}
            onClick={() => isDir ? toggleFolder(node.path) : fetchFile(node.path)}
          >
            {isDir ? (
              <span className="text-slate-400">
                {isExpanded ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
              </span>
            ) : (
              <button
                onClick={(e) => toggleSelectForDownload(node.path, e)}
                className={cn(
                  "w-3.5 h-3.5 border rounded flex items-center justify-center transition-all shrink-0",
                  selectedForDownload.has(node.path) ? "bg-blue-600 border-blue-600 text-white" : "bg-white border-slate-300 group-hover:border-slate-400"
                )}
              >
                {selectedForDownload.has(node.path) && <Check className="w-2.5 h-2.5" />}
              </button>
            )}
            {isDir ? (
              <span className={cn("transition-colors", isExpanded ? "text-blue-600" : "text-blue-400")}>
                {isExpanded ? <FolderOpen className="w-4 h-4" /> : <Folder className="w-4 h-4" />}
              </span>
            ) : (
              <span className="text-slate-400">
                <FileText className="w-4 h-4" />
              </span>
            )}
            <span className="truncate">{node.name}</span>
          </div>
          {isDir && isExpanded && node.children && (
            <div className="flex flex-col animate-in fade-in slide-in-from-top-1 duration-200">
              {renderTree(node.children, level + 1)}
            </div>
          )}
        </div>
      );
    });
  };

  return (
    <div className="flex h-full w-full bg-slate-50 overflow-hidden">
      {/* Left Column: Explorer */}
      <div className="w-72 bg-[#F8FAFC] border-r border-slate-200 flex flex-col shrink-0">
        <div className="p-5 border-b border-slate-200 bg-white shadow-sm z-10 flex flex-col gap-3">
          <div className="flex items-center justify-between">
            <h2 className="text-sm font-bold text-slate-800 uppercase tracking-widest">Wiki 知识库</h2>
            {selectedForDownload.size > 0 && (
              <button
                onClick={handleBatchDownload}
                className="text-xs font-bold bg-blue-50 text-blue-600 px-3 py-1.5 rounded-lg flex items-center gap-1.5 hover:bg-blue-100 transition shadow-sm"
              >
                <Download className="w-3 h-3" /> 下载 ({selectedForDownload.size})
              </button>
            )}
          </div>
          <div className="relative group">
            <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-blue-500 transition-colors" />
            <input
              type="text"
              placeholder="搜索目录..."
              value={searchQuery}
              onChange={(e) => handleSearchChange(e.target.value)}
              className="w-full pl-9 pr-3 py-2 bg-slate-100 border border-transparent rounded-xl text-sm outline-none focus:bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 transition-all"
            />
          </div>
        </div>
        <div className="flex-1 overflow-y-auto p-3 custom-scrollbar">
          {isLoadingTree ? (
            <div className="flex items-center justify-center h-32 text-slate-400">
              <Loader2 className="w-6 h-6 animate-spin" />
            </div>
          ) : filteredTreeData.length > 0 ? (
            renderTree(filteredTreeData)
          ) : (
            <div className="p-8 text-center text-sm text-slate-500">
              目录为空
            </div>
          )}
        </div>
      </div>

      {/* Right Column: Preview */}
      <div className="flex-1 bg-white flex flex-col min-w-0 overflow-hidden">
        {selectedFile ? (
          <>
            <header className="px-8 py-5 border-b border-slate-100 bg-white/80 backdrop-blur-md flex items-center justify-between shrink-0">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-blue-50 text-blue-600 rounded-xl shadow-sm">
                  <FileText className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-slate-800">
                    {selectedFile.split('/').pop()}
                  </h3>
                  <p className="text-xs text-slate-400 font-medium mt-0.5">
                    {selectedFile}
                  </p>
                </div>
              </div>
              <button
                onClick={() => handleSingleDownload(selectedFile)}
                className="flex items-center gap-2 px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-bold text-sm transition-colors"
              >
                <Download className="w-4 h-4" /> 下载
              </button>
            </header>
            <div className="flex-1 overflow-y-auto p-8 lg:p-12 custom-scrollbar bg-[#FAFAFA]">
              {isLoadingFile ? (
                <div className="flex flex-col items-center justify-center h-full text-slate-400 space-y-4">
                  <Loader2 className="w-8 h-8 animate-spin text-blue-500" />
                  <p className="text-sm font-medium">加载中...</p>
                </div>
              ) : (
                <div className="max-w-5xl mx-auto bg-white p-8 md:p-12 rounded-3xl shadow-sm border border-slate-100">
                  {(() => {
                    const { data, body } = parseFrontmatter(fileContent);
                    return (
                      <>
                        {data && <FrontmatterCard data={data} />}
                        <article className="prose prose-slate prose-blue max-w-none prose-headings:font-bold prose-h1:text-3xl prose-h2:text-2xl prose-h3:text-xl prose-a:text-blue-600 hover:prose-a:text-blue-500 prose-img:rounded-2xl prose-img:shadow-md prose-pre:bg-slate-900 prose-pre:rounded-xl prose-table:text-sm">
                          <ReactMarkdown remarkPlugins={[remarkGfm]}>
                            {body}
                          </ReactMarkdown>
                        </article>
                      </>
                    );
                  })()}
                </div>
              )}
            </div>
          </>
        ) : (
          <div className="flex flex-col items-center justify-center h-full text-slate-400 space-y-5 bg-[#FAFAFA]">
            <div className="w-24 h-24 bg-white rounded-full flex items-center justify-center shadow-sm border border-slate-100 animate-in zoom-in-50 duration-500">
              <BookOpen className="w-10 h-10 text-blue-200" />
            </div>
            <div className="text-center animate-in fade-in slide-in-from-bottom-2 duration-500 delay-100">
              <h3 className="text-xl font-bold text-slate-700">选择文件以预览</h3>
              <p className="text-sm text-slate-500 mt-2">在左侧文件树中点击文件进行阅读,仅支持只读模式</p>
            </div>
          </div>
        )}
      </div>

      <style jsx global>{`
        .custom-scrollbar::-webkit-scrollbar {
          width: 6px;
          height: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: transparent;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #CBD5E1;
          border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: #94A3B8;
        }
      `}</style>
    </div>
  );
}