feat(product-source): 光湖知识库模块 v0.1.0 — Git 驱动的完整知识库系统

铸渊 2026-08-08 开发,冰朔架构决策:
- Git 是底层引擎,不依赖任何数据库(PostgreSQL/Redis/ORM)
- Agent 直达底层,中间不隔第三方服务
- 拆解 Outline v0.80.2 为参考样本,光湖自己实现全部能力

技术栈:
- 后端:Express v5 + simple-git + gray-matter(Git 操作层)
- 前端:Vite + React 19 + TypeScript + marked
- 存储:Markdown 文件 + Git 仓库(commit=版本历史,diff=对比)

功能清单(全部可用):
- 文档 CRUD(创建/读取/更新/删除/移动)
- 文档树导航(文件夹层级)
- Markdown 编辑器(编辑/预览双栏)
- 全文搜索(防抖 + 下拉结果)
- 版本历史(git log)
- 版本 diff 对比(选择两个 commit 对比)

API 端点(Agent 和 UI 共用):
- GET/POST/PUT/DELETE /api/docs/{*path}
- GET /api/tree
- GET /api/history/{*path}
- GET /api/version/:hash/{*path}
- GET /api/diff/{*path}?from=&to=
- GET /api/search?q=
- POST /api/move
- GET /api/health
This commit is contained in:
冰朔 2026-08-08 07:09:54 +08:00
commit ecfeca40e2
16 changed files with 5970 additions and 0 deletions

View file

@ -0,0 +1,7 @@
node_modules/
dist/
dist-server/
kb-data/
*.tsbuildinfo
.DS_Store
._*

View file

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>光湖知识库</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>📖</text></svg>" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,37 @@
{
"name": "guanghu-knowledge-base",
"version": "0.1.0",
"description": "光湖知识库模块 — Git 驱动的文档管理系统",
"type": "module",
"scripts": {
"dev": "concurrently \"npm run dev:server\" \"npm run dev:client\"",
"dev:server": "tsx watch server/index.ts",
"dev:client": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"start": "NODE_ENV=production node dist-server/index.js"
},
"dependencies": {
"express": "^5.1.0",
"cors": "^2.8.5",
"simple-git": "^3.27.0",
"gray-matter": "^4.0.3",
"marked": "^15.0.0",
"diff": "^7.0.0"
},
"devDependencies": {
"@types/express": "^5.0.0",
"@types/cors": "^2.8.17",
"@types/diff": "^6.0.0",
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.0",
"concurrently": "^9.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tsx": "^4.19.0",
"typescript": "^5.7.0",
"vite": "^6.2.0"
}
}

View file

@ -0,0 +1,367 @@
/**
* · Git
*
* = Git
* = Markdown + frontmatter
* = git logdiff = git diff = grep
*/
import simpleGit, { SimpleGit, LogResult } from 'simple-git';
import matter from 'gray-matter';
import { diffLines } from 'diff';
import path from 'path';
import fs from 'fs/promises';
import fsSync from 'fs';
// ─── 类型定义 ───
export interface DocMeta {
id: string; // 文件路径即 ID相对 docs/ 目录)
title: string;
slug: string;
parentPath: string; // 父目录路径
createdAt: string;
updatedAt: string;
author: string;
tags: string[];
}
export interface DocContent {
meta: DocMeta;
body: string; // Markdown 正文(不含 frontmatter
}
export interface DocTreeNode {
name: string;
path: string;
type: 'folder' | 'document';
children?: DocTreeNode[];
}
export interface VersionEntry {
hash: string;
shortHash: string;
author: string;
date: string;
message: string;
}
export interface SearchResult {
path: string;
title: string;
snippet: string;
line: number;
}
export interface DiffResult {
additions: number;
deletions: number;
hunks: { oldStart: number; newStart: number; lines: string[] }[];
}
// ─── Git 引擎 ───
export class GitEngine {
private git: SimpleGit;
private docsDir: string;
private repoPath: string;
constructor(repoPath: string) {
this.repoPath = repoPath;
this.docsDir = path.join(repoPath, 'docs');
// simple-git 要求目录先存在,先同步创建
fsSync.mkdirSync(repoPath, { recursive: true });
this.git = simpleGit(repoPath);
}
/** 初始化仓库(如果不存在则创建) */
async init(): Promise<void> {
const repoRoot = path.dirname(this.docsDir);
try {
await fs.access(path.join(repoRoot, '.git'));
} catch {
await this.git.init();
await fs.mkdir(this.docsDir, { recursive: true });
// 写入初始 README
await fs.writeFile(
path.join(this.docsDir, 'README.md'),
'---\ntitle: 欢迎\nauthor: system\n---\n\n# 光湖知识库\n\n这是你的知识库根目录。\n'
);
await this.git.add('.');
await this.git.commit('init: 初始化光湖知识库');
}
// 确保 docs 目录存在
await fs.mkdir(this.docsDir, { recursive: true });
}
// ─── 文档 CRUD ───
/** 读取文档 */
async getDoc(docPath: string): Promise<DocContent> {
const fullPath = this.resolvePath(docPath);
const raw = await fs.readFile(fullPath, 'utf-8');
const { data, content } = matter(raw);
return {
meta: {
id: docPath,
title: (data.title as string) || path.basename(docPath, '.md'),
slug: path.basename(docPath, '.md'),
parentPath: path.dirname(docPath),
createdAt: (data.createdAt as string) || new Date().toISOString(),
updatedAt: (data.updatedAt as string) || new Date().toISOString(),
author: (data.author as string) || 'anonymous',
tags: (data.tags as string[]) || [],
},
body: content.trim(),
};
}
/** 创建文档 */
async createDoc(docPath: string, title: string, body: string, author = 'anonymous'): Promise<DocContent> {
const fullPath = this.resolvePath(docPath);
await fs.mkdir(path.dirname(fullPath), { recursive: true });
const now = new Date().toISOString();
const frontmatter = matter.stringify(body, {
title,
author,
createdAt: now,
updatedAt: now,
tags: [],
});
await fs.writeFile(fullPath, frontmatter);
await this.git.add(fullPath);
await this.git.commit(`create: ${title}`, [fullPath]);
return this.getDoc(docPath);
}
/** 更新文档 */
async updateDoc(docPath: string, title: string, body: string, author = 'anonymous'): Promise<DocContent> {
const fullPath = this.resolvePath(docPath);
const now = new Date().toISOString();
// 读取旧的 frontmatter 保留 createdAt
let createdAt = now;
try {
const old = await fs.readFile(fullPath, 'utf-8');
const oldData = matter(old);
createdAt = (oldData.data.createdAt as string) || now;
} catch { /* 新文件 */ }
const frontmatter = matter.stringify(body, {
title,
author,
createdAt,
updatedAt: now,
tags: [],
});
await fs.writeFile(fullPath, frontmatter);
await this.git.add(fullPath);
await this.git.commit(`update: ${title}`, [fullPath]);
return this.getDoc(docPath);
}
/** 删除文档 */
async deleteDoc(docPath: string): Promise<void> {
const fullPath = this.resolvePath(docPath);
await fs.rm(fullPath, { force: true });
await this.git.rm(fullPath);
await this.git.commit(`delete: ${docPath}`);
}
/** 重命名/移动文档 */
async moveDoc(oldPath: string, newPath: string): Promise<void> {
const fullOld = this.resolvePath(oldPath);
const fullNew = this.resolvePath(newPath);
await fs.mkdir(path.dirname(fullNew), { recursive: true });
await fs.rename(fullOld, fullNew);
await this.git.rm(fullOld);
await this.git.add(fullNew);
await this.git.commit(`move: ${oldPath}${newPath}`);
}
// ─── 文档树 ───
/** 构建文档树 */
async getTree(): Promise<DocTreeNode[]> {
return this.buildTree(this.docsDir, '');
}
private async buildTree(dirPath: string, relativePath: string): Promise<DocTreeNode[]> {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
const nodes: DocTreeNode[] = [];
// 排序:文件夹在前,文件在后
const sorted = entries
.filter(e => !e.name.startsWith('.') && !e.name.startsWith('_'))
.sort((a, b) => {
if (a.isDirectory() && !b.isDirectory()) return -1;
if (!a.isDirectory() && b.isDirectory()) return 1;
return a.name.localeCompare(b.name);
});
for (const entry of sorted) {
const childRelPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
const childFullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
const children = await this.buildTree(childFullPath, childRelPath);
nodes.push({
name: entry.name,
path: childRelPath,
type: 'folder',
children,
});
} else if (entry.name.endsWith('.md')) {
// 读取标题
let title = path.basename(entry.name, '.md');
try {
const raw = await fs.readFile(childFullPath, 'utf-8');
const { data } = matter(raw);
title = (data.title as string) || title;
} catch { /* 忽略 */ }
nodes.push({
name: title,
path: childRelPath,
type: 'document',
});
}
}
return nodes;
}
// ─── 版本历史 ───
/** 获取文档版本历史 */
async getHistory(docPath: string, maxCount = 50): Promise<VersionEntry[]> {
const fullPath = docPath ? this.resolvePath(docPath) : '.';
const log: LogResult = await this.git.log({
file: fullPath,
maxCount,
});
return log.all.map(entry => ({
hash: entry.hash,
shortHash: entry.hash.substring(0, 7),
author: entry.author_name,
date: entry.date,
message: entry.message,
}));
}
/** 获取某次提交的文档内容 */
async getDocAtVersion(docPath: string, commitHash: string): Promise<string> {
const relToRepo = `docs/${docPath}`;
const content = await this.git.show([`${commitHash}:${relToRepo}`]);
const { content: body } = matter(content);
return body.trim();
}
/** 对比两个版本 */
async diffVersions(docPath: string, fromHash: string, toHash: string): Promise<DiffResult> {
const relToRepo = `docs/${docPath}`;
const [fromContent, toContent] = await Promise.all([
this.git.show([`${fromHash}:${relToRepo}`]).catch(() => ''),
this.git.show([`${toHash}:${relToRepo}`]).catch(() => ''),
]);
const fromBody = fromContent ? matter(fromContent).content : '';
const toBody = toContent ? matter(toContent).content : '';
const diffs = diffLines(fromBody, toBody);
let additions = 0;
let deletions = 0;
const hunks: DiffResult['hunks'] = [];
let currentLines: string[] = [];
for (const part of diffs) {
if (part.added) {
const lines = part.value.split('\n').filter(l => l !== '');
additions += lines.length;
lines.forEach(l => currentLines.push(`+ ${l}`));
} else if (part.removed) {
const lines = part.value.split('\n').filter(l => l !== '');
deletions += lines.length;
lines.forEach(l => currentLines.push(`- ${l}`));
} else {
if (currentLines.length > 0) {
hunks.push({ oldStart: 0, newStart: 0, lines: [...currentLines] });
currentLines = [];
}
// 保留上下文最多3行
const lines = part.value.split('\n').filter(l => l !== '');
const ctx = lines.slice(-3);
ctx.forEach(l => currentLines.push(` ${l}`));
}
}
if (currentLines.length > 0) {
hunks.push({ oldStart: 0, newStart: 0, lines: currentLines });
}
return { additions, deletions, hunks };
}
// ─── 搜索 ───
/** 全文搜索(基于文件内容 grep */
async search(query: string): Promise<SearchResult[]> {
const results: SearchResult[] = [];
const queryLower = query.toLowerCase();
await this.searchDir(this.docsDir, '', queryLower, results);
return results.slice(0, 50); // 最多 50 条
}
private async searchDir(
dirPath: string,
relativePath: string,
query: string,
results: SearchResult[]
): Promise<void> {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith('.')) continue;
const childRelPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
const childFullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
await this.searchDir(childFullPath, childRelPath, query, results);
} else if (entry.name.endsWith('.md')) {
try {
const raw = await fs.readFile(childFullPath, 'utf-8');
const { data, content } = matter(raw);
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].toLowerCase().includes(query)) {
results.push({
path: childRelPath,
title: (data.title as string) || path.basename(entry.name, '.md'),
snippet: lines[i].trim().substring(0, 200),
line: i + 1,
});
break; // 每个文件只取第一个匹配
}
}
} catch { /* 忽略不可读文件 */ }
}
}
}
// ─── 辅助 ───
private resolvePath(docPath: string): string {
// 安全检查:防止路径穿越
const normalized = path.normalize(docPath).replace(/^(\.\.\/?)+/, '');
return path.join(this.docsDir, normalized);
}
}

View file

@ -0,0 +1,195 @@
/**
* · API
*
* Express + Git REST API
* Agent
*/
import express from 'express';
import cors from 'cors';
import { GitEngine } from './git-engine.js';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// ─── 配置 ───
const PORT = parseInt(process.env.KB_PORT || '3890', 10);
const REPO_PATH = process.env.KB_REPO_PATH || path.resolve(__dirname, '../kb-data');
// ─── 初始化 ───
const app = express();
const engine = new GitEngine(REPO_PATH);
app.use(cors());
app.use(express.json({ limit: '10mb' }));
// Express v5 的 {*param} 返回数组,工具函数统一转字符串
const p = (v: unknown): string => Array.isArray(v) ? v.join('/') : String(v);
// ─── 健康检查 ───
app.get('/api/health', (_req, res) => {
res.json({
module: 'guanghu-knowledge-base',
version: '0.1.0',
engine: 'git',
repo: REPO_PATH,
status: 'online',
time: new Date().toISOString(),
});
});
// ─── 文档树 ───
app.get('/api/tree', async (_req, res) => {
try {
const tree = await engine.getTree();
res.json({ ok: true, tree });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
// ─── 文档 CRUD ───
// 读取文档
app.get('/api/docs/{*docPath}', async (req, res) => {
try {
const docPath = p(req.params.docPath);
const doc = await engine.getDoc(docPath);
res.json({ ok: true, doc });
} catch (err: any) {
res.status(404).json({ ok: false, error: `文档不存在: ${p(req.params.docPath)}` });
}
});
// 创建文档
app.post('/api/docs/{*docPath}', async (req, res) => {
try {
const docPath = p(req.params.docPath);
const { title, body, author } = req.body;
if (!title || !body) {
return res.status(400).json({ ok: false, error: 'title 和 body 必填' });
}
const doc = await engine.createDoc(docPath, title, body, author);
res.status(201).json({ ok: true, doc });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
// 更新文档
app.put('/api/docs/{*docPath}', async (req, res) => {
try {
const docPath = p(req.params.docPath);
const { title, body, author } = req.body;
if (!title || !body) {
return res.status(400).json({ ok: false, error: 'title 和 body 必填' });
}
const doc = await engine.updateDoc(docPath, title, body, author);
res.json({ ok: true, doc });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
// 删除文档
app.delete('/api/docs/{*docPath}', async (req, res) => {
try {
const docPath = p(req.params.docPath);
await engine.deleteDoc(docPath);
res.json({ ok: true, message: `已删除: ${docPath}` });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
// 重命名/移动文档
app.post('/api/move', async (req, res) => {
try {
const { oldPath, newPath } = req.body;
if (!oldPath || !newPath) {
return res.status(400).json({ ok: false, error: 'oldPath 和 newPath 必填' });
}
await engine.moveDoc(oldPath, newPath);
res.json({ ok: true, message: `${oldPath}${newPath}` });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
// ─── 版本历史 ───
app.get('/api/history/{*docPath}', async (req, res) => {
try {
const docPath = p(req.params.docPath);
const maxCount = parseInt(req.query.max?.toString() || '50', 10);
const history = await engine.getHistory(docPath, maxCount);
res.json({ ok: true, history });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
// 获取某版本内容
app.get('/api/version/:hash/{*docPath}', async (req, res) => {
try {
const { hash } = req.params;
const docPath = p(req.params.docPath);
const content = await engine.getDocAtVersion(docPath, hash);
res.json({ ok: true, content });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
// 版本对比
app.get('/api/diff/{*docPath}', async (req, res) => {
try {
const docPath = p(req.params.docPath);
const { from, to } = req.query;
if (!from || !to) {
return res.status(400).json({ ok: false, error: 'from 和 to (commit hash) 必填' });
}
const diff = await engine.diffVersions(docPath, from.toString(), to.toString());
res.json({ ok: true, diff });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
// ─── 搜索 ───
app.get('/api/search', async (req, res) => {
try {
const query = req.query.q?.toString();
if (!query) {
return res.status(400).json({ ok: false, error: 'q 参数必填' });
}
const results = await engine.search(query);
res.json({ ok: true, results, count: results.length });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
// ─── 启动 ───
async function start() {
await engine.init();
app.listen(PORT, () => {
console.log(`光湖知识库 API 已启动: http://localhost:${PORT}`);
console.log(`仓库路径: ${REPO_PATH}`);
});
}
start().catch(err => {
console.error('启动失败:', err);
process.exit(1);
});
export default app;

View file

@ -0,0 +1,174 @@
import { useState, useEffect, useCallback } from 'react';
import { api, DocTreeNode, DocContent } from './api';
import { DocTree } from './components/DocTree';
import { Editor } from './components/Editor';
import { SearchBar } from './components/SearchBar';
import { VersionHistory } from './components/VersionHistory';
type View = 'editor' | 'history';
export default function App() {
const [tree, setTree] = useState<DocTreeNode[]>([]);
const [currentDoc, setCurrentDoc] = useState<DocContent | null>(null);
const [currentPath, setCurrentPath] = useState<string>('');
const [view, setView] = useState<View>('editor');
const [sidebarOpen, setSidebarOpen] = useState(true);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const refreshTree = useCallback(async () => {
try {
const t = await api.getTree();
setTree(t);
} catch (err: any) {
setError(`加载文档树失败: ${err.message}`);
}
}, []);
const openDoc = useCallback(async (docPath: string) => {
setLoading(true);
setError(null);
try {
const doc = await api.getDoc(docPath);
setCurrentDoc(doc);
setCurrentPath(docPath);
setView('editor');
} catch (err: any) {
setError(`加载文档失败: ${err.message}`);
} finally {
setLoading(false);
}
}, []);
const saveDoc = useCallback(async (title: string, body: string) => {
if (!currentPath) return;
setLoading(true);
try {
const doc = await api.updateDoc(currentPath, title, body);
setCurrentDoc(doc);
await refreshTree();
} catch (err: any) {
setError(`保存失败: ${err.message}`);
} finally {
setLoading(false);
}
}, [currentPath, refreshTree]);
const createDoc = useCallback(async (parentPath: string) => {
const name = prompt('文档文件名(不含 .md');
if (!name) return;
const title = prompt('文档标题:') || name;
const docPath = parentPath ? `${parentPath}/${name}.md` : `${name}.md`;
try {
const doc = await api.createDoc(docPath, title, `# ${title}\n\n在这里开始写作...\n`);
setCurrentDoc(doc);
setCurrentPath(docPath);
await refreshTree();
} catch (err: any) {
setError(`创建失败: ${err.message}`);
}
}, [refreshTree]);
const deleteDoc = useCallback(async () => {
if (!currentPath) return;
if (!confirm(`确认删除 ${currentPath}`)) return;
try {
await api.deleteDoc(currentPath);
setCurrentDoc(null);
setCurrentPath('');
await refreshTree();
} catch (err: any) {
setError(`删除失败: ${err.message}`);
}
}, [currentPath, refreshTree]);
useEffect(() => {
refreshTree();
}, [refreshTree]);
return (
<div className="kb-app">
{/* 顶栏 */}
<header className="kb-header">
<div className="kb-header-left">
<button
className="kb-btn-icon"
onClick={() => setSidebarOpen(!sidebarOpen)}
title={sidebarOpen ? '收起侧栏' : '展开侧栏'}
>
{sidebarOpen ? '◀' : '▶'}
</button>
<h1 className="kb-title"></h1>
</div>
<div className="kb-header-center">
<SearchBar onSelect={openDoc} />
</div>
<div className="kb-header-right">
{currentDoc && (
<>
<button
className={`kb-btn-tab ${view === 'editor' ? 'active' : ''}`}
onClick={() => setView('editor')}
>
</button>
<button
className={`kb-btn-tab ${view === 'history' ? 'active' : ''}`}
onClick={() => setView('history')}
>
</button>
<button className="kb-btn-icon kb-btn-danger" onClick={deleteDoc} title="删除">
🗑
</button>
</>
)}
</div>
</header>
{/* 主体 */}
<div className="kb-body">
{/* 侧栏 */}
{sidebarOpen && (
<aside className="kb-sidebar">
<div className="kb-sidebar-actions">
<button className="kb-btn-small" onClick={() => createDoc('')}>
+
</button>
</div>
<DocTree
nodes={tree}
currentPath={currentPath}
onSelect={openDoc}
onCreate={createDoc}
/>
</aside>
)}
{/* 内容区 */}
<main className="kb-content">
{error && (
<div className="kb-error">
{error}
<button onClick={() => setError(null)}></button>
</div>
)}
{loading && <div className="kb-loading">...</div>}
{!currentDoc && !loading && (
<div className="kb-empty">
<div className="kb-empty-icon">📖</div>
<p></p>
<p className="kb-empty-hint">+ </p>
</div>
)}
{currentDoc && view === 'editor' && (
<Editor doc={currentDoc} onSave={saveDoc} />
)}
{currentDoc && view === 'history' && (
<VersionHistory docPath={currentPath} />
)}
</main>
</div>
</div>
);
}

View file

@ -0,0 +1,116 @@
/**
* · API
* Agent UI
*/
const BASE = '/api';
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
headers: { 'Content-Type': 'application/json' },
...options,
});
const data = await res.json();
if (!data.ok) throw new Error(data.error || '请求失败');
return data as T;
}
// ─── 类型(与 server 保持一致) ───
export interface DocMeta {
id: string;
title: string;
slug: string;
parentPath: string;
createdAt: string;
updatedAt: string;
author: string;
tags: string[];
}
export interface DocContent {
meta: DocMeta;
body: string;
}
export interface DocTreeNode {
name: string;
path: string;
type: 'folder' | 'document';
children?: DocTreeNode[];
}
export interface VersionEntry {
hash: string;
shortHash: string;
author: string;
date: string;
message: string;
}
export interface SearchResult {
path: string;
title: string;
snippet: string;
line: number;
}
export interface DiffResult {
additions: number;
deletions: number;
hunks: { oldStart: number; newStart: number; lines: string[] }[];
}
// ─── API 方法 ───
export const api = {
/** 获取文档树 */
getTree: () =>
request<{ ok: true; tree: DocTreeNode[] }>('/tree').then(d => d.tree),
/** 读取文档 */
getDoc: (path: string) =>
request<{ ok: true; doc: DocContent }>(`/docs/${path}`).then(d => d.doc),
/** 创建文档 */
createDoc: (path: string, title: string, body: string, author = 'anonymous') =>
request<{ ok: true; doc: DocContent }>(`/docs/${path}`, {
method: 'POST',
body: JSON.stringify({ title, body, author }),
}).then(d => d.doc),
/** 更新文档 */
updateDoc: (path: string, title: string, body: string, author = 'anonymous') =>
request<{ ok: true; doc: DocContent }>(`/docs/${path}`, {
method: 'PUT',
body: JSON.stringify({ title, body, author }),
}).then(d => d.doc),
/** 删除文档 */
deleteDoc: (path: string) =>
request<{ ok: true }>(`/docs/${path}`, { method: 'DELETE' }),
/** 移动文档 */
moveDoc: (oldPath: string, newPath: string) =>
request<{ ok: true }>('/move', {
method: 'POST',
body: JSON.stringify({ oldPath, newPath }),
}),
/** 获取版本历史 */
getHistory: (path: string, max = 50) =>
request<{ ok: true; history: VersionEntry[] }>(`/history/${path}?max=${max}`).then(d => d.history),
/** 获取某版本内容 */
getDocAtVersion: (path: string, hash: string) =>
request<{ ok: true; content: string }>(`/version/${hash}/${path}`).then(d => d.content),
/** 版本对比 */
diffVersions: (path: string, from: string, to: string) =>
request<{ ok: true; diff: DiffResult }>(`/diff/${path}?from=${from}&to=${to}`).then(d => d.diff),
/** 搜索 */
search: (query: string) =>
request<{ ok: true; results: SearchResult[]; count: number }>(`/search?q=${encodeURIComponent(query)}`)
.then(d => d.results),
};

View file

@ -0,0 +1,87 @@
import { useState } from 'react';
import { DocTreeNode } from '../api';
interface Props {
nodes: DocTreeNode[];
currentPath: string;
onSelect: (path: string) => void;
onCreate: (parentPath: string) => void;
depth?: number;
}
export function DocTree({ nodes, currentPath, onSelect, onCreate, depth = 0 }: Props) {
return (
<div className="kb-tree" style={{ paddingLeft: depth > 0 ? 16 : 0 }}>
{nodes.map(node => (
<TreeNode
key={node.path}
node={node}
currentPath={currentPath}
onSelect={onSelect}
onCreate={onCreate}
depth={depth}
/>
))}
</div>
);
}
function TreeNode({
node,
currentPath,
onSelect,
onCreate,
depth,
}: {
node: DocTreeNode;
currentPath: string;
onSelect: (path: string) => void;
onCreate: (parentPath: string) => void;
depth: number;
}) {
const [expanded, setExpanded] = useState(depth < 2);
const isActive = node.path === currentPath;
if (node.type === 'folder') {
return (
<div className="kb-tree-folder">
<div
className={`kb-tree-item kb-tree-folder-header ${expanded ? 'expanded' : ''}`}
onClick={() => setExpanded(!expanded)}
>
<span className="kb-tree-icon">{expanded ? '📂' : '📁'}</span>
<span className="kb-tree-name">{node.name}</span>
<button
className="kb-tree-add"
onClick={e => {
e.stopPropagation();
onCreate(node.path);
}}
title="在此文件夹下新建文档"
>
+
</button>
</div>
{expanded && node.children && (
<DocTree
nodes={node.children}
currentPath={currentPath}
onSelect={onSelect}
onCreate={onCreate}
depth={depth + 1}
/>
)}
</div>
);
}
return (
<div
className={`kb-tree-item kb-tree-doc ${isActive ? 'active' : ''}`}
onClick={() => onSelect(node.path)}
>
<span className="kb-tree-icon">📄</span>
<span className="kb-tree-name">{node.name}</span>
</div>
);
}

View file

@ -0,0 +1,105 @@
import { useState, useEffect, useMemo } from 'react';
import { DocContent } from '../api';
import { marked } from 'marked';
interface Props {
doc: DocContent;
onSave: (title: string, body: string) => void;
}
export function Editor({ doc, onSave }: Props) {
const [editing, setEditing] = useState(false);
const [title, setTitle] = useState(doc.meta.title);
const [body, setBody] = useState(doc.body);
// 切换文档时重置
useEffect(() => {
setTitle(doc.meta.title);
setBody(doc.body);
setEditing(false);
}, [doc.meta.id]);
const rendered = useMemo(() => {
try {
return marked(body, { async: false }) as string;
} catch {
return '<p>渲染失败</p>';
}
}, [body]);
const handleSave = () => {
onSave(title, body);
setEditing(false);
};
const handleCancel = () => {
setTitle(doc.meta.title);
setBody(doc.body);
setEditing(false);
};
return (
<div className="kb-editor">
{/* 元信息栏 */}
<div className="kb-editor-meta">
<span className="kb-editor-path">{doc.meta.id}</span>
<span className="kb-editor-date">
{new Date(doc.meta.updatedAt).toLocaleString('zh-CN')}
</span>
<span className="kb-editor-author">by {doc.meta.author}</span>
</div>
{/* 标题 */}
{editing ? (
<input
className="kb-editor-title-input"
value={title}
onChange={e => setTitle(e.target.value)}
placeholder="文档标题"
/>
) : (
<h1 className="kb-editor-title" onClick={() => setEditing(true)}>
{doc.meta.title}
</h1>
)}
{/* 操作栏 */}
<div className="kb-editor-toolbar">
{editing ? (
<>
<button className="kb-btn-primary" onClick={handleSave}></button>
<button className="kb-btn-secondary" onClick={handleCancel}></button>
</>
) : (
<button className="kb-btn-primary" onClick={() => setEditing(true)}></button>
)}
</div>
{/* 内容区 */}
{editing ? (
<div className="kb-editor-edit-pane">
<textarea
className="kb-editor-textarea"
value={body}
onChange={e => setBody(e.target.value)}
placeholder="用 Markdown 写作..."
spellCheck={false}
/>
<div className="kb-editor-preview-pane">
<div
className="kb-markdown-render"
dangerouslySetInnerHTML={{ __html: rendered }}
/>
</div>
</div>
) : (
<div className="kb-editor-read-pane">
<div
className="kb-markdown-render"
dangerouslySetInnerHTML={{ __html: rendered }}
/>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,99 @@
import { useState, useRef, useEffect } from 'react';
import { api, SearchResult } from '../api';
interface Props {
onSelect: (path: string) => void;
}
export function SearchBar({ onSelect }: Props) {
const [query, setQuery] = useState('');
const [results, setResults] = useState<SearchResult[]>([]);
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout>>();
const containerRef = useRef<HTMLDivElement>(null);
// 防抖搜索
useEffect(() => {
if (!query.trim()) {
setResults([]);
setOpen(false);
return;
}
clearTimeout(timerRef.current);
timerRef.current = setTimeout(async () => {
setLoading(true);
try {
const r = await api.search(query);
setResults(r);
setOpen(true);
} catch {
setResults([]);
} finally {
setLoading(false);
}
}, 300);
return () => clearTimeout(timerRef.current);
}, [query]);
// 点击外部关闭
useEffect(() => {
const handler = (e: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setOpen(false);
}
};
document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler);
}, []);
return (
<div className="kb-search" ref={containerRef}>
<div className="kb-search-input-wrap">
<span className="kb-search-icon">🔍</span>
<input
className="kb-search-input"
type="text"
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="搜索文档..."
onFocus={() => results.length > 0 && setOpen(true)}
/>
{query && (
<button className="kb-search-clear" onClick={() => { setQuery(''); setResults([]); setOpen(false); }}>
</button>
)}
{loading && <span className="kb-search-loading">...</span>}
</div>
{open && results.length > 0 && (
<div className="kb-search-dropdown">
{results.map((r, i) => (
<div
key={`${r.path}-${i}`}
className="kb-search-result"
onClick={() => {
onSelect(r.path);
setOpen(false);
setQuery('');
}}
>
<div className="kb-search-result-title">{r.title}</div>
<div className="kb-search-result-path">{r.path}</div>
<div className="kb-search-result-snippet">{r.snippet}</div>
</div>
))}
</div>
)}
{open && results.length === 0 && !loading && query && (
<div className="kb-search-dropdown">
<div className="kb-search-empty"></div>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,154 @@
import { useState, useEffect } from 'react';
import { api, VersionEntry, DiffResult } from '../api';
interface Props {
docPath: string;
}
export function VersionHistory({ docPath }: Props) {
const [history, setHistory] = useState<VersionEntry[]>([]);
const [loading, setLoading] = useState(true);
const [selected, setSelected] = useState<[string, string] | null>(null);
const [diff, setDiff] = useState<DiffResult | null>(null);
const [versionContent, setVersionContent] = useState<string | null>(null);
const [viewingHash, setViewingHash] = useState<string | null>(null);
useEffect(() => {
loadHistory();
setSelected(null);
setDiff(null);
setVersionContent(null);
setViewingHash(null);
}, [docPath]);
const loadHistory = async () => {
setLoading(true);
try {
const h = await api.getHistory(docPath);
setHistory(h);
} catch {
setHistory([]);
} finally {
setLoading(false);
}
};
const handleSelectForDiff = (hash: string) => {
if (!selected) {
setSelected([hash, hash]);
} else if (selected[0] === selected[1]) {
// 选第二个点
const sorted = [selected[0], hash].sort((a, b) => {
const ai = history.findIndex(h => h.hash === a);
const bi = history.findIndex(h => h.hash === b);
return ai - bi;
});
setSelected([sorted[1], sorted[0]]); // [newer, older]
loadDiff(sorted[1], sorted[0]);
} else {
// 重新开始选择
setSelected([hash, hash]);
setDiff(null);
}
};
const loadDiff = async (from: string, to: string) => {
try {
const d = await api.diffVersions(docPath, from, to);
setDiff(d);
} catch {
setDiff(null);
}
};
const viewVersion = async (hash: string) => {
setViewingHash(hash);
try {
const content = await api.getDocAtVersion(docPath, hash);
setVersionContent(content);
} catch {
setVersionContent('加载失败');
}
};
if (loading) return <div className="kb-history-loading">...</div>;
return (
<div className="kb-history">
<h2 className="kb-history-title"></h2>
<p className="kb-history-hint">
</p>
<div className="kb-history-list">
{history.map(entry => {
const isSelected = selected && (selected[0] === entry.hash || selected[1] === entry.hash);
return (
<div
key={entry.hash}
className={`kb-history-entry ${isSelected ? 'selected' : ''}`}
>
<div className="kb-history-entry-main" onClick={() => handleSelectForDiff(entry.hash)}>
<span className="kb-history-hash">{entry.shortHash}</span>
<span className="kb-history-message">{entry.message}</span>
<span className="kb-history-date">
{new Date(entry.date).toLocaleString('zh-CN')}
</span>
<span className="kb-history-author">{entry.author}</span>
</div>
<button
className="kb-btn-small"
onClick={() => viewVersion(entry.hash)}
>
</button>
</div>
);
})}
</div>
{/* 版本内容预览 */}
{viewingHash && versionContent !== null && (
<div className="kb-history-preview">
<div className="kb-history-preview-header">
<span> {viewingHash.substring(0, 7)}</span>
<button onClick={() => { setViewingHash(null); setVersionContent(null); }}></button>
</div>
<pre className="kb-history-preview-content">{versionContent}</pre>
</div>
)}
{/* Diff 视图 */}
{diff && selected && (
<div className="kb-history-diff">
<div className="kb-history-diff-header">
<span>
: {selected[1].substring(0, 7)} {selected[0].substring(0, 7)}
</span>
<span className="kb-history-diff-stats">
+{diff.additions} / -{diff.deletions}
</span>
<button onClick={() => { setSelected(null); setDiff(null); }}></button>
</div>
<div className="kb-history-diff-body">
{diff.hunks.map((hunk, i) => (
<div key={i} className="kb-diff-hunk">
{hunk.lines.map((line, j) => (
<div
key={j}
className={`kb-diff-line ${
line.startsWith('+') ? 'add' :
line.startsWith('-') ? 'del' : 'ctx'
}`}
>
{line}
</div>
))}
</div>
))}
</div>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './styles/app.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);

View file

@ -0,0 +1,746 @@
/*
光湖知识库 · 主样式
设计基线简洁深色主题阅读友好
*/
:root {
--kb-bg: #0d1117;
--kb-bg-secondary: #161b22;
--kb-bg-tertiary: #21262d;
--kb-border: #30363d;
--kb-text: #e6edf3;
--kb-text-muted: #8b949e;
--kb-accent: #58a6ff;
--kb-accent-hover: #79c0ff;
--kb-danger: #f85149;
--kb-success: #3fb950;
--kb-warning: #d29922;
--kb-font-mono: 'SF Mono', 'Fira Code', 'Cascadia Code', monospace;
--kb-font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
--kb-sidebar-width: 280px;
--kb-header-height: 52px;
--kb-radius: 6px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: var(--kb-font-sans);
background: var(--kb-bg);
color: var(--kb-text);
line-height: 1.6;
overflow: hidden;
}
/* ─── 布局 ─── */
.kb-app {
display: flex;
flex-direction: column;
height: 100vh;
}
.kb-header {
height: var(--kb-header-height);
display: flex;
align-items: center;
padding: 0 16px;
border-bottom: 1px solid var(--kb-border);
background: var(--kb-bg-secondary);
gap: 12px;
flex-shrink: 0;
}
.kb-header-left {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.kb-header-center {
flex: 1;
display: flex;
justify-content: center;
}
.kb-header-right {
display: flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
}
.kb-title {
font-size: 16px;
font-weight: 600;
color: var(--kb-text);
white-space: nowrap;
}
.kb-body {
display: flex;
flex: 1;
overflow: hidden;
}
/* ─── 侧栏 ─── */
.kb-sidebar {
width: var(--kb-sidebar-width);
border-right: 1px solid var(--kb-border);
background: var(--kb-bg-secondary);
display: flex;
flex-direction: column;
overflow: hidden;
flex-shrink: 0;
}
.kb-sidebar-actions {
padding: 12px;
border-bottom: 1px solid var(--kb-border);
}
/* ─── 文档树 ─── */
.kb-tree {
overflow-y: auto;
padding: 8px 0;
flex: 1;
}
.kb-tree-item {
display: flex;
align-items: center;
padding: 6px 12px;
cursor: pointer;
gap: 6px;
font-size: 13px;
transition: background 0.15s;
position: relative;
}
.kb-tree-item:hover {
background: var(--kb-bg-tertiary);
}
.kb-tree-item.active {
background: var(--kb-bg-tertiary);
color: var(--kb-accent);
}
.kb-tree-icon {
font-size: 14px;
flex-shrink: 0;
}
.kb-tree-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.kb-tree-add {
display: none;
background: none;
border: 1px solid var(--kb-border);
color: var(--kb-text-muted);
border-radius: 3px;
width: 20px;
height: 20px;
cursor: pointer;
font-size: 12px;
line-height: 1;
}
.kb-tree-folder-header:hover .kb-tree-add {
display: flex;
align-items: center;
justify-content: center;
}
.kb-tree-add:hover {
color: var(--kb-accent);
border-color: var(--kb-accent);
}
/* ─── 内容区 ─── */
.kb-content {
flex: 1;
overflow-y: auto;
padding: 0;
}
/* ─── 编辑器 ─── */
.kb-editor {
max-width: 900px;
margin: 0 auto;
padding: 24px 32px;
}
.kb-editor-meta {
display: flex;
gap: 16px;
font-size: 12px;
color: var(--kb-text-muted);
margin-bottom: 12px;
padding-bottom: 12px;
border-bottom: 1px solid var(--kb-border);
}
.kb-editor-title {
font-size: 28px;
font-weight: 700;
margin-bottom: 12px;
cursor: pointer;
line-height: 1.3;
}
.kb-editor-title:hover {
color: var(--kb-accent);
}
.kb-editor-title-input {
width: 100%;
font-size: 28px;
font-weight: 700;
background: var(--kb-bg-tertiary);
border: 1px solid var(--kb-border);
color: var(--kb-text);
padding: 8px 12px;
border-radius: var(--kb-radius);
margin-bottom: 12px;
}
.kb-editor-toolbar {
display: flex;
gap: 8px;
margin-bottom: 16px;
}
.kb-editor-edit-pane {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
min-height: 500px;
}
.kb-editor-textarea {
width: 100%;
min-height: 500px;
background: var(--kb-bg-tertiary);
border: 1px solid var(--kb-border);
color: var(--kb-text);
padding: 16px;
border-radius: var(--kb-radius);
font-family: var(--kb-font-mono);
font-size: 14px;
line-height: 1.7;
resize: vertical;
outline: none;
}
.kb-editor-textarea:focus {
border-color: var(--kb-accent);
}
.kb-editor-preview-pane,
.kb-editor-read-pane {
overflow-y: auto;
}
.kb-editor-read-pane {
padding: 0;
}
/* ─── Markdown 渲染 ─── */
.kb-markdown-render {
font-size: 15px;
line-height: 1.8;
color: var(--kb-text);
}
.kb-markdown-render h1 { font-size: 2em; margin: 1em 0 0.5em; border-bottom: 1px solid var(--kb-border); padding-bottom: 0.3em; }
.kb-markdown-render h2 { font-size: 1.5em; margin: 1em 0 0.5em; border-bottom: 1px solid var(--kb-border); padding-bottom: 0.3em; }
.kb-markdown-render h3 { font-size: 1.25em; margin: 1em 0 0.5em; }
.kb-markdown-render p { margin: 0.8em 0; }
.kb-markdown-render ul, .kb-markdown-render ol { margin: 0.8em 0; padding-left: 2em; }
.kb-markdown-render li { margin: 0.3em 0; }
.kb-markdown-render blockquote {
border-left: 3px solid var(--kb-accent);
padding: 0.5em 1em;
margin: 1em 0;
background: var(--kb-bg-tertiary);
color: var(--kb-text-muted);
}
.kb-markdown-render code {
background: var(--kb-bg-tertiary);
padding: 2px 6px;
border-radius: 3px;
font-family: var(--kb-font-mono);
font-size: 0.9em;
}
.kb-markdown-render pre {
background: var(--kb-bg-tertiary);
padding: 16px;
border-radius: var(--kb-radius);
overflow-x: auto;
margin: 1em 0;
}
.kb-markdown-render pre code {
background: none;
padding: 0;
}
.kb-markdown-render table {
border-collapse: collapse;
width: 100%;
margin: 1em 0;
}
.kb-markdown-render th, .kb-markdown-render td {
border: 1px solid var(--kb-border);
padding: 8px 12px;
text-align: left;
}
.kb-markdown-render th {
background: var(--kb-bg-tertiary);
font-weight: 600;
}
.kb-markdown-render a {
color: var(--kb-accent);
text-decoration: none;
}
.kb-markdown-render a:hover {
text-decoration: underline;
}
.kb-markdown-render img {
max-width: 100%;
border-radius: var(--kb-radius);
}
.kb-markdown-render hr {
border: none;
border-top: 1px solid var(--kb-border);
margin: 2em 0;
}
/* ─── 搜索 ─── */
.kb-search {
position: relative;
width: 100%;
max-width: 480px;
}
.kb-search-input-wrap {
display: flex;
align-items: center;
background: var(--kb-bg-tertiary);
border: 1px solid var(--kb-border);
border-radius: var(--kb-radius);
padding: 0 10px;
gap: 6px;
}
.kb-search-input-wrap:focus-within {
border-color: var(--kb-accent);
}
.kb-search-icon {
font-size: 14px;
flex-shrink: 0;
}
.kb-search-input {
flex: 1;
background: none;
border: none;
color: var(--kb-text);
padding: 8px 0;
font-size: 14px;
outline: none;
}
.kb-search-input::placeholder {
color: var(--kb-text-muted);
}
.kb-search-clear {
background: none;
border: none;
color: var(--kb-text-muted);
cursor: pointer;
font-size: 14px;
padding: 2px 4px;
}
.kb-search-loading {
color: var(--kb-text-muted);
font-size: 12px;
}
.kb-search-dropdown {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: var(--kb-bg-secondary);
border: 1px solid var(--kb-border);
border-radius: var(--kb-radius);
margin-top: 4px;
max-height: 360px;
overflow-y: auto;
z-index: 100;
box-shadow: 0 8px 24px rgba(0,0,0,0.4);
}
.kb-search-result {
padding: 10px 14px;
cursor: pointer;
border-bottom: 1px solid var(--kb-border);
}
.kb-search-result:last-child {
border-bottom: none;
}
.kb-search-result:hover {
background: var(--kb-bg-tertiary);
}
.kb-search-result-title {
font-weight: 600;
font-size: 14px;
margin-bottom: 2px;
}
.kb-search-result-path {
font-size: 11px;
color: var(--kb-text-muted);
margin-bottom: 4px;
}
.kb-search-result-snippet {
font-size: 12px;
color: var(--kb-text-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.kb-search-empty {
padding: 16px;
text-align: center;
color: var(--kb-text-muted);
font-size: 13px;
}
/* ─── 版本历史 ─── */
.kb-history {
max-width: 900px;
margin: 0 auto;
padding: 24px 32px;
}
.kb-history-title {
font-size: 22px;
margin-bottom: 8px;
}
.kb-history-hint {
color: var(--kb-text-muted);
font-size: 13px;
margin-bottom: 20px;
}
.kb-history-list {
display: flex;
flex-direction: column;
gap: 4px;
}
.kb-history-entry {
display: flex;
align-items: center;
padding: 10px 14px;
border-radius: var(--kb-radius);
background: var(--kb-bg-secondary);
border: 1px solid var(--kb-border);
gap: 8px;
}
.kb-history-entry.selected {
border-color: var(--kb-accent);
background: var(--kb-bg-tertiary);
}
.kb-history-entry-main {
flex: 1;
display: flex;
align-items: center;
gap: 12px;
cursor: pointer;
font-size: 13px;
}
.kb-history-hash {
font-family: var(--kb-font-mono);
font-size: 12px;
color: var(--kb-accent);
background: var(--kb-bg-tertiary);
padding: 2px 6px;
border-radius: 3px;
flex-shrink: 0;
}
.kb-history-message {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.kb-history-date {
color: var(--kb-text-muted);
font-size: 12px;
flex-shrink: 0;
}
.kb-history-author {
color: var(--kb-text-muted);
font-size: 12px;
flex-shrink: 0;
}
.kb-history-preview,
.kb-history-diff {
margin-top: 20px;
border: 1px solid var(--kb-border);
border-radius: var(--kb-radius);
overflow: hidden;
}
.kb-history-preview-header,
.kb-history-diff-header {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 14px;
background: var(--kb-bg-tertiary);
border-bottom: 1px solid var(--kb-border);
font-size: 13px;
}
.kb-history-preview-header button,
.kb-history-diff-header button {
margin-left: auto;
}
.kb-history-preview-content {
padding: 16px;
font-family: var(--kb-font-mono);
font-size: 13px;
line-height: 1.6;
white-space: pre-wrap;
overflow-x: auto;
max-height: 400px;
}
.kb-history-diff-stats {
font-family: var(--kb-font-mono);
font-size: 12px;
color: var(--kb-success);
}
.kb-diff-hunk {
border-bottom: 1px solid var(--kb-border);
}
.kb-diff-line {
padding: 2px 14px;
font-family: var(--kb-font-mono);
font-size: 13px;
line-height: 1.6;
white-space: pre;
}
.kb-diff-line.add {
background: rgba(63, 185, 80, 0.15);
color: var(--kb-success);
}
.kb-diff-line.del {
background: rgba(248, 81, 73, 0.15);
color: var(--kb-danger);
}
.kb-diff-line.ctx {
color: var(--kb-text-muted);
}
/* ─── 通用按钮 ─── */
.kb-btn-icon {
background: none;
border: none;
color: var(--kb-text-muted);
cursor: pointer;
font-size: 16px;
padding: 4px 8px;
border-radius: var(--kb-radius);
}
.kb-btn-icon:hover {
color: var(--kb-text);
background: var(--kb-bg-tertiary);
}
.kb-btn-danger:hover {
color: var(--kb-danger) !important;
}
.kb-btn-primary {
background: var(--kb-accent);
color: #fff;
border: none;
padding: 6px 16px;
border-radius: var(--kb-radius);
cursor: pointer;
font-size: 13px;
font-weight: 500;
}
.kb-btn-primary:hover {
background: var(--kb-accent-hover);
}
.kb-btn-secondary {
background: var(--kb-bg-tertiary);
color: var(--kb-text);
border: 1px solid var(--kb-border);
padding: 6px 16px;
border-radius: var(--kb-radius);
cursor: pointer;
font-size: 13px;
}
.kb-btn-secondary:hover {
border-color: var(--kb-text-muted);
}
.kb-btn-small {
background: var(--kb-bg-tertiary);
color: var(--kb-text-muted);
border: 1px solid var(--kb-border);
padding: 4px 10px;
border-radius: var(--kb-radius);
cursor: pointer;
font-size: 12px;
white-space: nowrap;
}
.kb-btn-small:hover {
color: var(--kb-text);
border-color: var(--kb-text-muted);
}
.kb-btn-tab {
background: none;
border: none;
color: var(--kb-text-muted);
cursor: pointer;
padding: 6px 12px;
border-radius: var(--kb-radius);
font-size: 13px;
}
.kb-btn-tab:hover {
background: var(--kb-bg-tertiary);
color: var(--kb-text);
}
.kb-btn-tab.active {
background: var(--kb-bg-tertiary);
color: var(--kb-accent);
font-weight: 600;
}
/* ─── 空状态 / 错误 / 加载 ─── */
.kb-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
color: var(--kb-text-muted);
gap: 8px;
}
.kb-empty-icon {
font-size: 48px;
margin-bottom: 8px;
}
.kb-empty-hint {
font-size: 13px;
}
.kb-error {
background: rgba(248, 81, 73, 0.1);
border: 1px solid var(--kb-danger);
color: var(--kb-danger);
padding: 10px 16px;
margin: 16px;
border-radius: var(--kb-radius);
display: flex;
align-items: center;
justify-content: space-between;
font-size: 13px;
}
.kb-error button {
background: none;
border: none;
color: var(--kb-danger);
cursor: pointer;
font-size: 16px;
}
.kb-loading {
padding: 24px;
text-align: center;
color: var(--kb-text-muted);
}
.kb-history-loading {
padding: 24px;
color: var(--kb-text-muted);
}
/* ─── 滚动条 ─── */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--kb-border);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--kb-text-muted);
}

View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"outDir": "./dist",
"rootDir": ".",
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@server/*": ["./server/*"]
}
},
"include": ["src/**/*", "server/**/*"],
"exclude": ["node_modules", "dist"]
}

View file

@ -0,0 +1,25 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
port: 5180,
proxy: {
'/api': {
target: 'http://localhost:3890',
changeOrigin: true,
},
},
},
build: {
outDir: 'dist',
sourcemap: true,
},
});