page.tsx
13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"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>
);
}