feat: 初始化 AstroResearch 核心系统代码及重构技术文档
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,45 @@
|
||||
# AstroResearch Dashboard / 前端仪表盘控制台
|
||||
|
||||
本模块是 AstroResearch 的前端部分,基于 **React (TypeScript) + Vite + Tailwind CSS** 构建。
|
||||
|
||||
---
|
||||
|
||||
## 1. 本地开发与调试 (Setup & Dev)
|
||||
|
||||
### 1.1 安装依赖
|
||||
确保已安装 Node.js (v18+),在当前目录下运行:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
### 1.2 启动开发服务器
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
开发服务器将默认运行在 `http://localhost:5173`。Vite 已配置了对 `http://localhost:8000` (后端) 的代理转发,跨域请求会自动路由。
|
||||
|
||||
---
|
||||
|
||||
## 2. 核心功能及文件结构 (Core Modules)
|
||||
|
||||
- `src/components/layout/`:侧边栏与基本布局组件。
|
||||
- `src/components/CitationGalaxyCanvas.tsx`:自研的 Canvas 力导向引文星系图渲染器。
|
||||
- `src/features/search/`:统一检索面板,支持跨源搜索与收藏。
|
||||
- `src/features/library/`:馆藏管理卡片,提供下载状态实时监测及重新下载操作。
|
||||
- `src/features/reader/`:左右对齐的双分栏阅读器,内置划词高亮笔记及 LLM 重新翻译触发。
|
||||
- `src/types.ts`:全局 TypeScript 静态类型定义。
|
||||
|
||||
---
|
||||
|
||||
## 3. 生产构建 (Build)
|
||||
|
||||
若需打包生成生产环境静态文件:
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
打包文件将输出至当前目录下的 `dist/`,后端 Axum 在编译时会直接将其静态托管。
|
||||
|
||||
---
|
||||
|
||||
## 4. 开发规范 (Coding Standards)
|
||||
- 本模块的详细前端开发约定,请参阅本目录下的 [前端开发规范-React篇.md](前端开发规范-React篇.md)。
|
||||
@@ -0,0 +1,22 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>dashboard</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+4675
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "dashboard",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.17.0",
|
||||
"clsx": "^2.1.1",
|
||||
"framer-motion": "^12.40.0",
|
||||
"katex": "^0.17.0",
|
||||
"lucide-react": "^1.17.0",
|
||||
"react": "^19.2.6",
|
||||
"react-dom": "^19.2.6",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-katex": "^7.0.1",
|
||||
"remark-math": "^6.0.0",
|
||||
"tailwind-merge": "^3.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@tailwindcss/typography": "^0.5.19",
|
||||
"@tailwindcss/vite": "^4.3.0",
|
||||
"@types/node": "^24.12.3",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"eslint": "^10.3.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.6.0",
|
||||
"tailwindcss": "^4.3.0",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.59.2",
|
||||
"vite": "^8.0.12"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,184 @@
|
||||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-bg);
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.base {
|
||||
width: 170px;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.framework,
|
||||
.vite {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.framework {
|
||||
z-index: 1;
|
||||
top: 34px;
|
||||
height: 28px;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
|
||||
scale(1.4);
|
||||
}
|
||||
|
||||
.vite {
|
||||
z-index: 0;
|
||||
top: 107px;
|
||||
height: 26px;
|
||||
width: auto;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
|
||||
scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
#center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 25px;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
padding: 32px 20px 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps {
|
||||
display: flex;
|
||||
border-top: 1px solid var(--border);
|
||||
text-align: left;
|
||||
|
||||
& > div {
|
||||
flex: 1 1 0;
|
||||
padding: 32px;
|
||||
@media (max-width: 1024px) {
|
||||
padding: 24px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-bottom: 16px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
#docs {
|
||||
border-right: 1px solid var(--border);
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 32px 0 0;
|
||||
|
||||
.logo {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--text-h);
|
||||
font-size: 16px;
|
||||
border-radius: 6px;
|
||||
background: var(--social-bg);
|
||||
display: flex;
|
||||
padding: 6px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-decoration: none;
|
||||
transition: box-shadow 0.3s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.button-icon {
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
margin-top: 20px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -4.5px;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&::before {
|
||||
left: 0;
|
||||
border-left-color: var(--border);
|
||||
}
|
||||
&::after {
|
||||
right: 0;
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
// dashboard/src/App.tsx
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
import { Sidebar } from './components/layout/Sidebar';
|
||||
import { SearchPanel } from './features/search/SearchPanel';
|
||||
import { LibraryPanel } from './features/library/LibraryPanel';
|
||||
import { ReaderPanel } from './features/reader/ReaderPanel';
|
||||
import { CitationPanel } from './features/citation/CitationPanel';
|
||||
import { SettingsPanel } from './features/settings/SettingsPanel';
|
||||
import type { StandardPaper, CitationNetwork, NoteRecord } from './types';
|
||||
|
||||
export default function App() {
|
||||
const [activeTab, setActiveTab] = useState<'search' | 'library' | 'reader' | 'citation' | 'settings'>('search');
|
||||
|
||||
// 共享数据状态
|
||||
const [library, setLibrary] = useState<StandardPaper[]>([]);
|
||||
const [selectedPaper, setSelectedPaper] = useState<StandardPaper | null>(null);
|
||||
|
||||
// 检索页状态
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchSource, setSearchSource] = useState<'all' | 'ads' | 'arxiv'>('all');
|
||||
const [searchResults, setSearchResults] = useState<StandardPaper[]>([]);
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [exportingList, setExportingList] = useState<string[]>([]);
|
||||
const [bibtexContent, setBibtexContent] = useState<string | null>(null);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
|
||||
// 读者页状态
|
||||
const [englishText, setEnglishText] = useState('');
|
||||
const [chineseText, setChineseText] = useState('');
|
||||
const [parsing, setParsing] = useState(false);
|
||||
const [translating, setTranslating] = useState(false);
|
||||
|
||||
// 引用星系数据状态
|
||||
const [citationNetwork, setCitationNetwork] = useState<CitationNetwork | null>(null);
|
||||
const [loadingCitations, setLoadingCitations] = useState(false);
|
||||
const [citationHistory, setCitationHistory] = useState<CitationNetwork[]>([]); // 多跳历史
|
||||
|
||||
// 笔记系统状态
|
||||
const [notes, setNotes] = useState<NoteRecord[]>([]);
|
||||
const [showNotesPanel, setShowNotesPanel] = useState(false);
|
||||
const [newNoteText, setNewNoteText] = useState('');
|
||||
const [newNoteColor, setNewNoteColor] = useState('yellow');
|
||||
const [selectedParagraphIdx, setSelectedParagraphIdx] = useState<number | null>(null);
|
||||
const [selectedText, setSelectedText] = useState('');
|
||||
|
||||
// 下载进度状态
|
||||
const [downloadingBibcodes, setDownloadingBibcodes] = useState<Record<string, boolean>>({});
|
||||
|
||||
// 1. 初始化时加载本地文献
|
||||
useEffect(() => {
|
||||
fetchLibrary();
|
||||
}, []);
|
||||
|
||||
const fetchLibrary = async () => {
|
||||
try {
|
||||
const res = await axios.get<StandardPaper[]>('/api/library');
|
||||
setLibrary(res.data);
|
||||
} catch (e) {
|
||||
console.error('加载本地文献库失败', e);
|
||||
}
|
||||
};
|
||||
|
||||
// 2. 检索文献
|
||||
const handleSearch = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!searchQuery.trim()) return;
|
||||
setSearching(true);
|
||||
setBibtexContent(null);
|
||||
try {
|
||||
const res = await axios.get<StandardPaper[]>('/api/search', {
|
||||
params: { q: searchQuery, source: searchSource, rows: 15 }
|
||||
});
|
||||
setSearchResults(res.data);
|
||||
} catch (e) {
|
||||
console.error('检索文献失败', e);
|
||||
alert('检索失败,请确认后端连接及 API 密钥配置。');
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 3. 触发文献双格式下载
|
||||
const handleDownload = async (bibcode: string, force = false) => {
|
||||
setDownloadingBibcodes(prev => ({ ...prev, [bibcode]: true }));
|
||||
try {
|
||||
const res = await axios.post<StandardPaper>('/api/download', { bibcode, force });
|
||||
// 更新库及检索列表中的状态
|
||||
setSearchResults(prev => prev.map(p => p.bibcode === bibcode ? res.data : p));
|
||||
setLibrary(prev => {
|
||||
if (prev.some(p => p.bibcode === bibcode)) {
|
||||
return prev.map(p => p.bibcode === bibcode ? res.data : p);
|
||||
} else {
|
||||
return [res.data, ...prev];
|
||||
}
|
||||
});
|
||||
if (selectedPaper?.bibcode === bibcode) {
|
||||
setSelectedPaper(res.data);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('下载文献失败', e);
|
||||
alert('文献下载失败,请检查 ADS 网络限制与网络代理!');
|
||||
} finally {
|
||||
setDownloadingBibcodes(prev => ({ ...prev, [bibcode]: false }));
|
||||
}
|
||||
};
|
||||
|
||||
// 4. 文献解析成 Markdown (优先 HTML, 其次 PDF MinerU)
|
||||
const handleParse = async (bibcode: string, force = false) => {
|
||||
setParsing(true);
|
||||
try {
|
||||
const res = await axios.post<{ markdown: string }>('/api/parse', { bibcode, force });
|
||||
setEnglishText(res.data.markdown);
|
||||
|
||||
// 更新文献状态
|
||||
setLibrary(prev => prev.map(p => p.bibcode === bibcode ? { ...p, has_markdown: true } : p));
|
||||
if (selectedPaper?.bibcode === bibcode) {
|
||||
setSelectedPaper(prev => prev ? { ...prev, has_markdown: true } : null);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('文献解析失败', e);
|
||||
alert('文献排版解析失败,请检查是否已完成 HTML/PDF 下载,并配置了 MinerU API 节点。');
|
||||
} finally {
|
||||
setParsing(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 5. 对比翻译文本 (带天文学术语修正)
|
||||
const handleTranslate = async (bibcode: string, force = false) => {
|
||||
setTranslating(true);
|
||||
try {
|
||||
const res = await axios.post<{ translation: string }>('/api/translate', { bibcode, force });
|
||||
setChineseText(res.data.translation);
|
||||
|
||||
setLibrary(prev => prev.map(p => p.bibcode === bibcode ? { ...p, has_translation: true } : p));
|
||||
if (selectedPaper?.bibcode === bibcode) {
|
||||
setSelectedPaper(prev => prev ? { ...prev, has_translation: true } : null);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('文献翻译失败', e);
|
||||
alert('翻译失败,请检查 .env 中的大模型 API 密钥与端点配置。');
|
||||
} finally {
|
||||
setTranslating(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 6. 加载文献引用关系网络
|
||||
const loadCitations = useCallback(async (bibcode: string, reset = false) => {
|
||||
setLoadingCitations(true);
|
||||
try {
|
||||
const res = await axios.get<CitationNetwork>('/api/citations', {
|
||||
params: { bibcode }
|
||||
});
|
||||
setCitationNetwork(res.data);
|
||||
setCitationHistory(prev => {
|
||||
if (reset) {
|
||||
return [res.data];
|
||||
}
|
||||
if (prev.some(net => net.bibcode === res.data.bibcode)) {
|
||||
return prev;
|
||||
}
|
||||
return [...prev, res.data];
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('加载引用拓扑失败', e);
|
||||
} finally {
|
||||
setLoadingCitations(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 7. 进入阅读器
|
||||
const openReader = async (paper: StandardPaper) => {
|
||||
setSelectedPaper(paper);
|
||||
setEnglishText('');
|
||||
setChineseText('');
|
||||
setNotes([]);
|
||||
setShowNotesPanel(false);
|
||||
setActiveTab('reader');
|
||||
|
||||
// 获取详情 (包含已有原文及翻译)
|
||||
try {
|
||||
const res = await axios.get<{ paper: StandardPaper, english_content?: string, translation_content?: string }>('/api/paper', {
|
||||
params: { bibcode: paper.bibcode }
|
||||
});
|
||||
if (res.data.english_content) {
|
||||
setEnglishText(res.data.english_content);
|
||||
}
|
||||
if (res.data.translation_content) {
|
||||
setChineseText(res.data.translation_content);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('加载文献详情失败', e);
|
||||
}
|
||||
|
||||
// 加载该文献的所有笔记
|
||||
try {
|
||||
const nRes = await axios.get<NoteRecord[]>('/api/notes', { params: { bibcode: paper.bibcode } });
|
||||
setNotes(nRes.data);
|
||||
} catch (e) {
|
||||
console.error('加载笔记失败', e);
|
||||
}
|
||||
};
|
||||
|
||||
// 8. 批量导出 BibTeX
|
||||
const handleExportBibtex = async () => {
|
||||
if (exportingList.length === 0) return;
|
||||
setExporting(true);
|
||||
try {
|
||||
const res = await axios.post<{ bibtex: string }>('/api/export', { bibcodes: exportingList });
|
||||
setBibtexContent(res.data.bibtex);
|
||||
} catch (e) {
|
||||
console.error('导出 BibTeX 失败', e);
|
||||
alert('导出 BibTeX 失败,请检查 ADS Token。');
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 批量选择引文
|
||||
const toggleExportItem = (bibcode: string) => {
|
||||
setExportingList(prev =>
|
||||
prev.includes(bibcode) ? prev.filter(b => b !== bibcode) : [...prev, bibcode]
|
||||
);
|
||||
};
|
||||
|
||||
// 笔记相关操作
|
||||
const handleCreateNote = async () => {
|
||||
if (!selectedPaper || selectedParagraphIdx === null || !newNoteText.trim()) return;
|
||||
try {
|
||||
const res = await axios.post<NoteRecord>('/api/notes', {
|
||||
bibcode: selectedPaper.bibcode,
|
||||
paragraph_index: selectedParagraphIdx,
|
||||
note_text: newNoteText.trim(),
|
||||
highlight_color: newNoteColor,
|
||||
selected_text: selectedText,
|
||||
});
|
||||
setNotes(prev => [...prev, res.data]);
|
||||
setNewNoteText('');
|
||||
setSelectedParagraphIdx(null);
|
||||
setSelectedText('');
|
||||
} catch (e) {
|
||||
console.error('保存笔记失败', e);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteNote = async (id: number) => {
|
||||
try {
|
||||
await axios.delete('/api/notes', { params: { id } });
|
||||
setNotes(prev => prev.filter(n => n.id !== id));
|
||||
} catch (e) {
|
||||
console.error('删除笔记失败', e);
|
||||
}
|
||||
};
|
||||
|
||||
// 选中文本时弹出笔记添加面板
|
||||
const handleTextSelection = (paragraphIdx: number) => {
|
||||
const sel = window.getSelection();
|
||||
if (sel && sel.toString().trim().length > 3) {
|
||||
setSelectedText(sel.toString().trim());
|
||||
setSelectedParagraphIdx(paragraphIdx);
|
||||
setShowNotesPanel(true);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden text-slate-800">
|
||||
|
||||
{/* 炫酷淡雅背景装饰 */}
|
||||
<div className="absolute inset-0 bg-[#f8fafc] z-[-10]">
|
||||
<div className="absolute top-[10%] left-[20%] w-[300px] h-[300px] bg-purple-500/5 rounded-full blur-[120px] animate-pulse-slow" />
|
||||
<div className="absolute bottom-[10%] right-[20%] w-[400px] h-[400px] bg-blue-500/5 rounded-full blur-[150px] animate-pulse-slow" style={{ animationDelay: '1.5s' }} />
|
||||
</div>
|
||||
|
||||
{/* 导航左侧栏 */}
|
||||
<Sidebar
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
selectedPaper={selectedPaper}
|
||||
loadCitations={loadCitations}
|
||||
/>
|
||||
|
||||
{/* 主工作区 */}
|
||||
<main className="flex-1 flex flex-col overflow-hidden">
|
||||
{/* 顶部状态条 */}
|
||||
<header className="h-16 border-b border-slate-200/60 px-8 flex items-center justify-between bg-white/40 backdrop-blur-md">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-emerald-500 animate-pulse" />
|
||||
<span className="text-xs text-slate-600 font-medium">后端服务连接正常</span>
|
||||
</div>
|
||||
<div className="text-xs text-slate-600">
|
||||
文献库: {library.length} 篇
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* 选项卡容器 */}
|
||||
<div className="flex-1 overflow-y-auto p-8">
|
||||
{activeTab === 'search' && (
|
||||
<SearchPanel
|
||||
searchQuery={searchQuery}
|
||||
setSearchQuery={setSearchQuery}
|
||||
searchSource={searchSource}
|
||||
setSearchSource={setSearchSource}
|
||||
searching={searching}
|
||||
handleSearch={handleSearch}
|
||||
searchResults={searchResults}
|
||||
exportingList={exportingList}
|
||||
toggleExportItem={toggleExportItem}
|
||||
handleExportBibtex={handleExportBibtex}
|
||||
exporting={exporting}
|
||||
bibtexContent={bibtexContent}
|
||||
downloadingBibcodes={downloadingBibcodes}
|
||||
handleDownload={handleDownload}
|
||||
selectedPaper={selectedPaper}
|
||||
setSelectedPaper={setSelectedPaper}
|
||||
openReader={openReader}
|
||||
setActiveTab={setActiveTab}
|
||||
loadCitations={loadCitations}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'library' && (
|
||||
<LibraryPanel
|
||||
library={library}
|
||||
fetchLibrary={fetchLibrary}
|
||||
openReader={openReader}
|
||||
setSelectedPaper={setSelectedPaper}
|
||||
setActiveTab={setActiveTab}
|
||||
loadCitations={loadCitations}
|
||||
downloadingBibcodes={downloadingBibcodes}
|
||||
handleDownload={handleDownload}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'reader' && selectedPaper && (
|
||||
<ReaderPanel
|
||||
selectedPaper={selectedPaper}
|
||||
parsing={parsing}
|
||||
handleParse={handleParse}
|
||||
translating={translating}
|
||||
handleTranslate={handleTranslate}
|
||||
showNotesPanel={showNotesPanel}
|
||||
setShowNotesPanel={setShowNotesPanel}
|
||||
notes={notes}
|
||||
englishText={englishText}
|
||||
chineseText={chineseText}
|
||||
handleTextSelection={handleTextSelection}
|
||||
selectedParagraphIdx={selectedParagraphIdx}
|
||||
setSelectedParagraphIdx={setSelectedParagraphIdx}
|
||||
selectedText={selectedText}
|
||||
setSelectedText={setSelectedText}
|
||||
newNoteColor={newNoteColor}
|
||||
setNewNoteColor={setNewNoteColor}
|
||||
newNoteText={newNoteText}
|
||||
setNewNoteText={setNewNoteText}
|
||||
handleCreateNote={handleCreateNote}
|
||||
handleDeleteNote={handleDeleteNote}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'citation' && (
|
||||
<CitationPanel
|
||||
selectedPaper={selectedPaper}
|
||||
loadingCitations={loadingCitations}
|
||||
citationNetwork={citationNetwork}
|
||||
citationHistory={citationHistory}
|
||||
loadCitations={loadCitations}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'settings' && (
|
||||
<SettingsPanel />
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,272 @@
|
||||
// dashboard/src/components/CitationGalaxyCanvas.tsx
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { CitationNetwork } from '../types';
|
||||
|
||||
interface CanvasProps {
|
||||
networks: CitationNetwork[];
|
||||
activeNetwork: CitationNetwork;
|
||||
onNodeClick: (bibcode: string) => void;
|
||||
}
|
||||
|
||||
interface Node {
|
||||
id: string;
|
||||
label: string;
|
||||
x: number;
|
||||
y: number;
|
||||
vx: number;
|
||||
vy: number;
|
||||
radius: number;
|
||||
color: string;
|
||||
type: 'center' | 'reference' | 'citation';
|
||||
}
|
||||
|
||||
interface Link {
|
||||
source: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
export function CitationGalaxyCanvas({ networks, activeNetwork, onNodeClick }: CanvasProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
// 适配高清屏幕像素比
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
canvas.width = rect.width * dpr;
|
||||
canvas.height = rect.height * dpr;
|
||||
ctx.scale(dpr, dpr);
|
||||
|
||||
// 合并所有 networks 的节点,去重,最多 50 个
|
||||
const MAX_NODES = 50;
|
||||
const allIds = new Set<string>();
|
||||
const nodes: Node[] = [];
|
||||
const links: Link[] = [];
|
||||
|
||||
networks.forEach((net, netIdx) => {
|
||||
const isActive = net.bibcode === activeNetwork.bibcode;
|
||||
// 添加中心节点
|
||||
if (!allIds.has(net.bibcode) && nodes.length < MAX_NODES) {
|
||||
allIds.add(net.bibcode);
|
||||
nodes.push({
|
||||
id: net.bibcode,
|
||||
label: net.bibcode,
|
||||
x: rect.width / 2 + (netIdx === 0 ? 0 : (Math.random() - 0.5) * 200),
|
||||
y: rect.height / 2 + (netIdx === 0 ? 0 : (Math.random() - 0.5) * 200),
|
||||
vx: 0,
|
||||
vy: 0,
|
||||
radius: isActive ? 24 : 16,
|
||||
color: isActive ? '#a855f7' : '#6366f1',
|
||||
type: 'center',
|
||||
});
|
||||
}
|
||||
|
||||
// 添加参考文献节点
|
||||
net.references.forEach((ref, idx) => {
|
||||
if (nodes.length >= MAX_NODES) return;
|
||||
if (!allIds.has(ref)) {
|
||||
allIds.add(ref);
|
||||
const angle = (idx / Math.max(1, net.references.length)) * Math.PI * 2;
|
||||
const dist = 140 + Math.random() * 30;
|
||||
const centerNode = nodes.find(n => n.id === net.bibcode);
|
||||
nodes.push({
|
||||
id: ref,
|
||||
label: ref,
|
||||
x: (centerNode?.x ?? rect.width / 2) + Math.cos(angle) * dist,
|
||||
y: (centerNode?.y ?? rect.height / 2) + Math.sin(angle) * dist,
|
||||
vx: 0,
|
||||
vy: 0,
|
||||
radius: 12,
|
||||
color: '#d97706',
|
||||
type: 'reference',
|
||||
});
|
||||
}
|
||||
if (allIds.has(ref)) {
|
||||
links.push({ source: ref, target: net.bibcode });
|
||||
}
|
||||
});
|
||||
|
||||
// 添加被引文献节点
|
||||
net.citations.forEach((cit, idx) => {
|
||||
if (nodes.length >= MAX_NODES) return;
|
||||
if (!allIds.has(cit)) {
|
||||
allIds.add(cit);
|
||||
const angle = (idx / Math.max(1, net.citations.length)) * Math.PI * 2 + Math.PI;
|
||||
const dist = 160 + Math.random() * 40;
|
||||
const centerNode = nodes.find(n => n.id === net.bibcode);
|
||||
nodes.push({
|
||||
id: cit,
|
||||
label: cit,
|
||||
x: (centerNode?.x ?? rect.width / 2) + Math.cos(angle) * dist,
|
||||
y: (centerNode?.y ?? rect.height / 2) + Math.sin(angle) * dist,
|
||||
vx: 0,
|
||||
vy: 0,
|
||||
radius: 12,
|
||||
color: '#4f46e5',
|
||||
type: 'citation',
|
||||
});
|
||||
}
|
||||
if (allIds.has(cit)) {
|
||||
links.push({ source: net.bibcode, target: cit });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let animationFrameId: number;
|
||||
let hoveredNode: Node | null = null;
|
||||
|
||||
// 经典力导向算法迭代
|
||||
const updatePhysics = () => {
|
||||
// 1. 斥力:任何两个节点之间均产生反向推力
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
for (let j = i + 1; j < nodes.length; j++) {
|
||||
let dx = nodes[j].x - nodes[i].x;
|
||||
let dy = nodes[j].y - nodes[i].y;
|
||||
let dist = Math.sqrt(dx * dx + dy * dy) || 1;
|
||||
let minDist = nodes[i].radius + nodes[j].radius + 50;
|
||||
if (dist < minDist) {
|
||||
let force = (minDist - dist) * 0.08;
|
||||
let fx = (dx / dist) * force;
|
||||
let fy = (dy / dist) * force;
|
||||
|
||||
// 节点不强行推动中心大节点
|
||||
if (nodes[i].type !== 'center' || nodes[i].id !== activeNetwork.bibcode) {
|
||||
nodes[i].vx -= fx;
|
||||
nodes[i].vy -= fy;
|
||||
}
|
||||
if (nodes[j].type !== 'center' || nodes[j].id !== activeNetwork.bibcode) {
|
||||
nodes[j].vx += fx;
|
||||
nodes[j].vy += fy;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 引力与向心力:被连线连接的节点之间产生向中心靠拢力
|
||||
links.forEach(link => {
|
||||
const sourceNode = nodes.find(n => n.id === link.source);
|
||||
const targetNode = nodes.find(n => n.id === link.target);
|
||||
if (sourceNode && targetNode) {
|
||||
let dx = targetNode.x - sourceNode.x;
|
||||
let dy = targetNode.y - sourceNode.y;
|
||||
let dist = Math.sqrt(dx * dx + dy * dy) || 1;
|
||||
let force = dist * 0.003; // 弹性系数
|
||||
let fx = (dx / dist) * force;
|
||||
let fy = (dy / dist) * force;
|
||||
|
||||
if (sourceNode.type !== 'center' || sourceNode.id !== activeNetwork.bibcode) {
|
||||
sourceNode.vx += fx;
|
||||
sourceNode.vy += fy;
|
||||
}
|
||||
if (targetNode.type !== 'center' || targetNode.id !== activeNetwork.bibcode) {
|
||||
targetNode.vx -= fx;
|
||||
targetNode.vy -= fy;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 3. 应用阻尼阻力,限制极限加速
|
||||
nodes.forEach(node => {
|
||||
if (node.id !== activeNetwork.bibcode) {
|
||||
node.x += node.vx;
|
||||
node.y += node.vy;
|
||||
node.vx *= 0.85; // 阻尼
|
||||
node.vy *= 0.85;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 画布渲染渲染循环
|
||||
const render = () => {
|
||||
updatePhysics();
|
||||
|
||||
ctx.clearRect(0, 0, rect.width, rect.height);
|
||||
|
||||
// 绘制连线
|
||||
ctx.lineWidth = 1;
|
||||
links.forEach(link => {
|
||||
const sourceNode = nodes.find(n => n.id === link.source);
|
||||
const targetNode = nodes.find(n => n.id === link.target);
|
||||
if (sourceNode && targetNode) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(sourceNode.x, sourceNode.y);
|
||||
ctx.lineTo(targetNode.x, targetNode.y);
|
||||
ctx.strokeStyle = sourceNode.type === 'reference' ? 'rgba(245, 158, 11, 0.25)' : 'rgba(129, 140, 248, 0.25)';
|
||||
ctx.stroke();
|
||||
}
|
||||
});
|
||||
|
||||
// 绘制节点
|
||||
nodes.forEach(node => {
|
||||
const isHovered = hoveredNode?.id === node.id;
|
||||
ctx.beginPath();
|
||||
ctx.arc(node.x, node.y, node.radius + (isHovered ? 4 : 0), 0, Math.PI * 2);
|
||||
ctx.fillStyle = node.color;
|
||||
ctx.fill();
|
||||
|
||||
// 绘制光晕环绕
|
||||
ctx.beginPath();
|
||||
ctx.arc(node.x, node.y, node.radius + (isHovered ? 8 : 4), 0, Math.PI * 2);
|
||||
ctx.strokeStyle = node.color + '40'; // 附加透明度光晕
|
||||
ctx.lineWidth = 2;
|
||||
ctx.stroke();
|
||||
|
||||
// 绘制 bibcode 文本说明
|
||||
ctx.fillStyle = isHovered ? '#0f172a' : '#64748b';
|
||||
ctx.font = isHovered ? 'bold 10px monospace' : '9px monospace';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(node.label, node.x, node.y + node.radius + (isHovered ? 18 : 14));
|
||||
});
|
||||
|
||||
animationFrameId = requestAnimationFrame(render);
|
||||
};
|
||||
|
||||
render();
|
||||
|
||||
// 交互鼠标监听
|
||||
const handleMouseMove = (e: MouseEvent) => {
|
||||
const mouseX = e.clientX - rect.left;
|
||||
const mouseY = e.clientY - rect.top;
|
||||
|
||||
let found: Node | null = null;
|
||||
for (const node of nodes) {
|
||||
let dx = node.x - mouseX;
|
||||
let dy = node.y - mouseY;
|
||||
let dist = Math.sqrt(dx * dx + dy * dy);
|
||||
if (dist < node.radius + 5) {
|
||||
found = node;
|
||||
break;
|
||||
}
|
||||
}
|
||||
hoveredNode = found;
|
||||
canvas.style.cursor = found ? 'pointer' : 'default';
|
||||
};
|
||||
|
||||
const handleCanvasClick = () => {
|
||||
if (hoveredNode && hoveredNode.id !== activeNetwork.bibcode) {
|
||||
onNodeClick(hoveredNode.id);
|
||||
}
|
||||
};
|
||||
|
||||
canvas.addEventListener('mousemove', handleMouseMove);
|
||||
canvas.addEventListener('click', handleCanvasClick);
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(animationFrameId);
|
||||
canvas.removeEventListener('mousemove', handleMouseMove);
|
||||
canvas.removeEventListener('click', handleCanvasClick);
|
||||
};
|
||||
}, [networks, activeNetwork, onNodeClick]);
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className="w-full h-full min-h-[450px]"
|
||||
style={{ display: 'block' }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// dashboard/src/components/layout/Sidebar.tsx
|
||||
import { Search, BookOpen, GitFork, Library, Settings } from 'lucide-react';
|
||||
import type { StandardPaper } from '../../types';
|
||||
|
||||
interface SidebarProps {
|
||||
activeTab: 'search' | 'library' | 'reader' | 'citation' | 'settings';
|
||||
setActiveTab: (tab: 'search' | 'library' | 'reader' | 'citation' | 'settings') => void;
|
||||
selectedPaper: StandardPaper | null;
|
||||
loadCitations: (bibcode: string) => void;
|
||||
}
|
||||
|
||||
export function Sidebar({ activeTab, setActiveTab, selectedPaper, loadCitations }: SidebarProps) {
|
||||
return (
|
||||
<aside className="w-64 glass border-r border-slate-200/80 flex flex-col justify-between py-6">
|
||||
<div>
|
||||
{/* Logo */}
|
||||
<div className="px-6 mb-8 flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-xl bg-gradient-to-br from-purple-500 to-indigo-600 flex items-center justify-center shadow-lg shadow-purple-500/20">
|
||||
<span className="font-extrabold text-white text-lg tracking-wider">A</span>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg font-bold text-slate-800 leading-none font-outfit">AstroResearch</h1>
|
||||
<span className="text-xs text-slate-500">天文学科研辅助系统</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 选项卡导航 */}
|
||||
<nav className="px-4 space-y-1.5">
|
||||
{[
|
||||
{ id: 'search', label: '统一检索', icon: Search },
|
||||
{ id: 'library', label: '馆藏管理', icon: Library },
|
||||
{ id: 'reader', label: '双语阅读', icon: BookOpen, disabled: !selectedPaper },
|
||||
{ id: 'citation', label: '引用星系', icon: GitFork, disabled: !selectedPaper },
|
||||
{ id: 'settings', label: '系统设置', icon: Settings },
|
||||
].map(tab => {
|
||||
const Icon = tab.icon;
|
||||
const isActive = activeTab === tab.id;
|
||||
return (
|
||||
<button
|
||||
key={tab.id}
|
||||
disabled={tab.disabled}
|
||||
onClick={() => {
|
||||
setActiveTab(tab.id as any);
|
||||
if (tab.id === 'citation' && selectedPaper) {
|
||||
loadCitations(selectedPaper.bibcode);
|
||||
}
|
||||
}}
|
||||
className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all ${
|
||||
isActive
|
||||
? 'bg-gradient-to-r from-purple-600/10 to-indigo-600/10 text-purple-600 border border-purple-500/20'
|
||||
: tab.disabled
|
||||
? 'opacity-40 cursor-not-allowed text-slate-400'
|
||||
: 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-4 h-4" />
|
||||
{tab.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* 底部当前文献卡片 */}
|
||||
{selectedPaper && (
|
||||
<div className="mx-4 p-4 rounded-xl bg-slate-100/50 border border-slate-200/80">
|
||||
<span className="text-[10px] text-purple-600 font-bold uppercase tracking-wider block mb-1">当前选定文献</span>
|
||||
<h4 className="text-xs text-slate-800 font-medium line-clamp-2 mb-2">{selectedPaper.title}</h4>
|
||||
<div className="flex items-center justify-between text-[10px] text-slate-500">
|
||||
<span>{selectedPaper.year}</span>
|
||||
<span className="truncate max-w-[100px] text-slate-400">{selectedPaper.bibcode}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// dashboard/src/features/citation/CitationPanel.tsx
|
||||
import { Loader, GitFork, RotateCcw } from 'lucide-react';
|
||||
import { CitationGalaxyCanvas } from '../../components/CitationGalaxyCanvas';
|
||||
import type { StandardPaper, CitationNetwork } from '../../types';
|
||||
|
||||
interface CitationPanelProps {
|
||||
selectedPaper: StandardPaper | null;
|
||||
loadingCitations: boolean;
|
||||
citationNetwork: CitationNetwork | null;
|
||||
citationHistory: CitationNetwork[];
|
||||
loadCitations: (bibcode: string, reset?: boolean) => void;
|
||||
}
|
||||
|
||||
export function CitationPanel({
|
||||
selectedPaper,
|
||||
loadingCitations,
|
||||
citationNetwork,
|
||||
citationHistory,
|
||||
loadCitations,
|
||||
}: CitationPanelProps) {
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto h-[calc(100vh-140px)] flex flex-col space-y-4 w-full">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-slate-800">引用星系拓扑网络</h2>
|
||||
<p className="text-xs text-slate-500">基于数据库快速检索生成的“参考文献 (References) - 核心文献 - 被引文献 (Citations)”扩散网络</p>
|
||||
</div>
|
||||
{selectedPaper && (
|
||||
<button
|
||||
onClick={() => loadCitations(selectedPaper.bibcode, true)}
|
||||
className="px-4 py-2 rounded-xl bg-slate-100 border border-slate-200 text-xs text-slate-650 hover:bg-slate-200 flex items-center gap-2"
|
||||
>
|
||||
<RotateCcw className="w-3.5 h-3.5" /> 重置星系图
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{loadingCitations ? (
|
||||
<div className="glass rounded-2xl flex-1 flex flex-col items-center justify-center text-slate-500">
|
||||
<Loader className="w-8 h-8 animate-spin text-purple-500 mb-2" />
|
||||
<p className="text-xs">正在从 SQLite 数据库提取文献层级引用数据...</p>
|
||||
</div>
|
||||
) : citationNetwork ? (
|
||||
<div className="flex-1 glass rounded-2xl border border-slate-200/80 overflow-hidden relative flex">
|
||||
{/* 可视化画布 */}
|
||||
<div className="flex-1 relative">
|
||||
<CitationGalaxyCanvas
|
||||
networks={citationHistory}
|
||||
activeNetwork={citationNetwork}
|
||||
onNodeClick={(bibcode) => {
|
||||
loadCitations(bibcode, false);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{/* 右侧关系详情面板 */}
|
||||
<div className="w-80 border-l border-slate-200 bg-white/50 p-6 space-y-6 overflow-y-auto">
|
||||
<div>
|
||||
<span className="text-[10px] text-purple-600 font-bold uppercase tracking-wider block mb-1">中心节点</span>
|
||||
<h4 className="text-sm font-semibold text-slate-800 leading-snug">{citationNetwork.title}</h4>
|
||||
<p className="text-xs text-slate-500 font-mono mt-1">{citationNetwork.bibcode}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-[10px] text-amber-700 font-bold uppercase tracking-wider block mb-2">
|
||||
参考文献 (References: {citationNetwork.references.length})
|
||||
</span>
|
||||
<div className="space-y-1 max-h-48 overflow-y-auto">
|
||||
{citationNetwork.references.length === 0 ? (
|
||||
<span className="text-xs text-slate-400 italic">暂无参考文献 bibcode 数据</span>
|
||||
) : (
|
||||
citationNetwork.references.map(bib => (
|
||||
<div
|
||||
key={bib}
|
||||
onClick={() => loadCitations(bib)}
|
||||
className="text-xs text-slate-600 hover:text-purple-600 cursor-pointer font-mono truncate py-1 hover:bg-slate-100 px-2 rounded"
|
||||
>
|
||||
{bib}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-[10px] text-indigo-700 font-bold uppercase tracking-wider block mb-2">
|
||||
被引文献 (Citations: {citationNetwork.citations.length})
|
||||
</span>
|
||||
<div className="space-y-1 max-h-48 overflow-y-auto">
|
||||
{citationNetwork.citations.length === 0 ? (
|
||||
<span className="text-xs text-slate-400 italic">暂无被引文献 bibcode 数据</span>
|
||||
) : (
|
||||
citationNetwork.citations.map(bib => (
|
||||
<div
|
||||
key={bib}
|
||||
onClick={() => loadCitations(bib)}
|
||||
className="text-xs text-slate-600 hover:text-purple-600 cursor-pointer font-mono truncate py-1 hover:bg-slate-100 px-2 rounded"
|
||||
>
|
||||
{bib}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="glass rounded-2xl flex-1 flex flex-col items-center justify-center text-slate-400">
|
||||
<GitFork className="w-12 h-12 mb-3" />
|
||||
<p className="text-xs">无法加载本篇文献的引用数据关系</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// dashboard/src/features/library/LibraryPanel.tsx
|
||||
import { Library, RotateCw, Download, Loader, RefreshCw } from 'lucide-react';
|
||||
import type { StandardPaper } from '../../types';
|
||||
|
||||
interface LibraryPanelProps {
|
||||
library: StandardPaper[];
|
||||
fetchLibrary: () => void;
|
||||
openReader: (paper: StandardPaper) => void;
|
||||
setSelectedPaper: (paper: StandardPaper | null) => void;
|
||||
setActiveTab: (tab: 'search' | 'library' | 'reader' | 'citation' | 'settings') => void;
|
||||
loadCitations: (bibcode: string) => void;
|
||||
downloadingBibcodes: Record<string, boolean>;
|
||||
handleDownload: (bibcode: string, force?: boolean) => void;
|
||||
}
|
||||
|
||||
export function LibraryPanel({
|
||||
library,
|
||||
fetchLibrary,
|
||||
openReader,
|
||||
setSelectedPaper,
|
||||
setActiveTab,
|
||||
loadCitations,
|
||||
downloadingBibcodes,
|
||||
handleDownload,
|
||||
}: LibraryPanelProps) {
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto space-y-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-slate-800">本地文献库</h2>
|
||||
<p className="text-xs text-slate-500">已同步保存在本地物理文献库中的所有数据索引</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={fetchLibrary}
|
||||
className="px-4 py-2 rounded-xl bg-slate-100 border border-slate-200 text-xs text-slate-600 hover:bg-slate-200 flex items-center gap-2"
|
||||
>
|
||||
<RotateCw className="w-3.5 h-3.5" /> 刷新库
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{library.length === 0 ? (
|
||||
<div className="glass p-12 rounded-2xl text-center">
|
||||
<Library className="w-12 h-12 text-slate-400 mx-auto mb-4" />
|
||||
<h3 className="font-bold text-slate-800 mb-1">本地文献库空空如也</h3>
|
||||
<p className="text-xs text-slate-500 mb-6">您检索到的天文学文献会在下载后自动同步到此处进行离线保存</p>
|
||||
<button
|
||||
onClick={() => setActiveTab('search')}
|
||||
className="px-6 py-2.5 rounded-xl bg-purple-600 text-white font-semibold hover:bg-purple-500 text-xs"
|
||||
>
|
||||
前往检索文献
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{library.map(paper => {
|
||||
const isDownloading = downloadingBibcodes[paper.bibcode] || false;
|
||||
return (
|
||||
<div key={paper.bibcode} className="glass p-6 rounded-2xl border border-slate-200/80 hover:border-slate-300 flex flex-col justify-between">
|
||||
<div>
|
||||
<div className="flex justify-between items-start gap-4 mb-2">
|
||||
<h3
|
||||
className="font-bold text-sm text-slate-800 line-clamp-2 hover:text-purple-600 cursor-pointer"
|
||||
onClick={() => openReader(paper)}
|
||||
>
|
||||
{paper.title}
|
||||
</h3>
|
||||
{paper.is_downloaded ? (
|
||||
<span className="px-2 py-0.5 rounded bg-emerald-50 text-emerald-600 border border-emerald-200 text-[9px] font-bold uppercase shrink-0">已下载</span>
|
||||
) : (
|
||||
<span className="px-2 py-0.5 rounded bg-amber-50 text-amber-600 border border-amber-200 text-[9px] font-bold uppercase shrink-0">未下载</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-slate-500 mb-3">
|
||||
{paper.authors.slice(0, 2).join(', ')}{paper.authors.length > 2 ? ' et al.' : ''} | {paper.year}
|
||||
</div>
|
||||
<p className="text-xs text-slate-600 line-clamp-3 leading-relaxed mb-4">{paper.abstract_text}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between border-t border-slate-200/60 pt-4 mt-auto">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
onClick={() => openReader(paper)}
|
||||
className="px-3.5 py-1.5 rounded-lg bg-purple-600 text-white text-xs hover:bg-purple-500 transition-all font-semibold"
|
||||
>
|
||||
打开阅读
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedPaper(paper);
|
||||
setActiveTab('citation');
|
||||
loadCitations(paper.bibcode);
|
||||
}}
|
||||
className="px-3.5 py-1.5 rounded-lg bg-slate-100 border border-slate-200 text-slate-600 hover:bg-slate-200 text-xs font-semibold"
|
||||
>
|
||||
引用图谱
|
||||
</button>
|
||||
{paper.is_downloaded ? (
|
||||
<button
|
||||
onClick={() => { if (confirm('确定要强制重新下载吗?这会覆盖本地文件。')) handleDownload(paper.bibcode, true); }}
|
||||
disabled={isDownloading}
|
||||
className="px-3.5 py-1.5 rounded-lg bg-slate-100 border border-slate-200 text-amber-600 hover:bg-slate-200 text-xs font-semibold flex items-center gap-1"
|
||||
>
|
||||
{isDownloading ? <Loader className="w-3 h-3 animate-spin" /> : <RefreshCw className="w-3 h-3" />}
|
||||
{isDownloading ? '下载中' : '重新下载'}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => handleDownload(paper.bibcode)}
|
||||
disabled={isDownloading}
|
||||
className="px-3.5 py-1.5 rounded-lg bg-blue-600 text-white text-xs hover:bg-blue-500 transition-all font-semibold flex items-center gap-1 shadow-lg shadow-blue-500/10"
|
||||
>
|
||||
{isDownloading ? <Loader className="w-3 h-3 animate-spin" /> : <Download className="w-3 h-3" />}
|
||||
{isDownloading ? '下载中' : '下载 PDF/HTML'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className={`w-1.5 h-1.5 rounded-full ${paper.has_markdown ? 'bg-purple-400' : 'bg-slate-350'}`} title="解析状态" />
|
||||
<span className={`w-1.5 h-1.5 rounded-full ${paper.has_translation ? 'bg-emerald-400' : 'bg-slate-350'}`} title="翻译状态" />
|
||||
<span className="text-[10px] font-mono text-slate-400">{paper.bibcode}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
// dashboard/src/features/reader/ReaderPanel.tsx
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import remarkMath from 'remark-math';
|
||||
import rehypeKatex from 'rehype-katex';
|
||||
import 'katex/dist/katex.min.css';
|
||||
import { FileText, Loader, Languages, RotateCw, Pencil, X, PlusCircle, Trash2 } from 'lucide-react';
|
||||
import type { StandardPaper, NoteRecord } from '../../types';
|
||||
|
||||
interface ReaderPanelProps {
|
||||
selectedPaper: StandardPaper;
|
||||
parsing: boolean;
|
||||
handleParse: (bibcode: string, force?: boolean) => void;
|
||||
translating: boolean;
|
||||
handleTranslate: (bibcode: string, force?: boolean) => void;
|
||||
showNotesPanel: boolean;
|
||||
setShowNotesPanel: (show: boolean) => void;
|
||||
notes: NoteRecord[];
|
||||
englishText: string;
|
||||
chineseText: string;
|
||||
handleTextSelection: (paragraphIdx: number) => void;
|
||||
selectedParagraphIdx: number | null;
|
||||
setSelectedParagraphIdx: (idx: number | null) => void;
|
||||
selectedText: string;
|
||||
setSelectedText: (text: string) => void;
|
||||
newNoteColor: string;
|
||||
setNewNoteColor: (color: string) => void;
|
||||
newNoteText: string;
|
||||
setNewNoteText: (text: string) => void;
|
||||
handleCreateNote: () => void;
|
||||
handleDeleteNote: (id: number) => void;
|
||||
}
|
||||
|
||||
const NOTE_COLORS: Record<string, { bg: string; border: string; label: string }> = {
|
||||
yellow: { bg: 'bg-yellow-500/20', border: 'border-yellow-500/40', label: '黄色' },
|
||||
green: { bg: 'bg-emerald-500/20', border: 'border-emerald-500/40', label: '绿色' },
|
||||
blue: { bg: 'bg-blue-500/20', border: 'border-blue-500/40', label: '蓝色' },
|
||||
pink: { bg: 'bg-pink-500/20', border: 'border-pink-500/40', label: '粉色' },
|
||||
};
|
||||
|
||||
export function ReaderPanel({
|
||||
selectedPaper,
|
||||
parsing,
|
||||
handleParse,
|
||||
translating,
|
||||
handleTranslate,
|
||||
showNotesPanel,
|
||||
setShowNotesPanel,
|
||||
notes,
|
||||
englishText,
|
||||
chineseText,
|
||||
handleTextSelection,
|
||||
selectedParagraphIdx,
|
||||
setSelectedParagraphIdx,
|
||||
selectedText,
|
||||
setSelectedText,
|
||||
newNoteColor,
|
||||
setNewNoteColor,
|
||||
newNoteText,
|
||||
setNewNoteText,
|
||||
handleCreateNote,
|
||||
handleDeleteNote,
|
||||
}: ReaderPanelProps) {
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto h-[calc(100vh-140px)] flex flex-col space-y-4 w-full">
|
||||
{/* 控制头部 */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-base font-bold text-slate-800 line-clamp-1 leading-snug">{selectedPaper.title}</h2>
|
||||
<div className="flex items-center gap-2 text-xs text-slate-500">
|
||||
<span>期刊: {selectedPaper.pub_journal}</span>
|
||||
<span>•</span>
|
||||
<span>Bibcode: {selectedPaper.bibcode}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{!selectedPaper.has_markdown ? (
|
||||
<button
|
||||
onClick={() => handleParse(selectedPaper.bibcode)}
|
||||
disabled={parsing}
|
||||
className="px-4 py-2 rounded-xl bg-purple-600 text-white text-xs hover:bg-purple-500 font-semibold flex items-center gap-2 shadow-lg shadow-purple-500/10"
|
||||
>
|
||||
{parsing ? <Loader className="w-3.5 h-3.5 animate-spin" /> : <FileText className="w-3.5 h-3.5" />}
|
||||
{parsing ? '提取英文正文中...' : '第一步:解析 PDF/HTML 正文'}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => { if (confirm('确定要重新解析正文吗?这会覆盖本地已解析的 Markdown。')) handleParse(selectedPaper.bibcode, true); }}
|
||||
disabled={parsing}
|
||||
className="px-4 py-2 rounded-xl bg-slate-100 border border-slate-200 text-slate-600 text-xs hover:bg-slate-200 font-semibold flex items-center gap-2"
|
||||
title="覆盖本地解析结果,重新从 HTML/PDF 转换为 Markdown"
|
||||
>
|
||||
{parsing ? <Loader className="w-3.5 h-3.5 animate-spin" /> : <RotateCw className="w-3.5 h-3.5" />}
|
||||
重新解析
|
||||
</button>
|
||||
)}
|
||||
|
||||
{selectedPaper.has_markdown && (
|
||||
<button
|
||||
onClick={() => handleTranslate(selectedPaper.bibcode)}
|
||||
disabled={translating}
|
||||
className="px-4 py-2 rounded-xl bg-emerald-600 text-white text-xs hover:bg-emerald-500 font-semibold flex items-center gap-2 shadow-lg shadow-emerald-500/10"
|
||||
>
|
||||
{translating ? <Loader className="w-3.5 h-3.5 animate-spin" /> : <Languages className="w-3.5 h-3.5" />}
|
||||
{translating ? 'LLM 学术术语修正翻译中...' : '第二步:大模型对比翻译'}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{selectedPaper.has_translation && (
|
||||
<button
|
||||
onClick={() => handleTranslate(selectedPaper.bibcode, true)}
|
||||
disabled={translating}
|
||||
className="px-4 py-2 rounded-xl bg-slate-100 border border-slate-200 text-slate-600 text-xs hover:bg-slate-200 font-semibold flex items-center gap-2"
|
||||
title="清除翻译缓存并重新生成大模型对照翻译"
|
||||
>
|
||||
{translating ? <Loader className="w-3.5 h-3.5 animate-spin" /> : <RotateCw className="w-3.5 h-3.5" />}
|
||||
重新翻译
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 并排对比阅读器 */}
|
||||
<div className="flex-1 grid gap-6 overflow-hidden w-full" style={{ gridTemplateColumns: showNotesPanel ? '1fr 1fr 320px' : '1fr 1fr' }}>
|
||||
{/* 英文正文面板 */}
|
||||
<div className="glass rounded-2xl p-6 overflow-y-auto border border-slate-200 relative flex flex-col">
|
||||
<div className="flex items-center justify-between mb-3 border-b border-slate-200/60 pb-2">
|
||||
<span className="text-[10px] text-purple-650 font-bold uppercase tracking-wider">英文解析正文 (Markdown/LaTeX)</span>
|
||||
<button
|
||||
onClick={() => setShowNotesPanel(!showNotesPanel)}
|
||||
className={`flex items-center gap-1 text-[10px] px-2 py-1 rounded-lg transition-all ${
|
||||
showNotesPanel ? 'bg-amber-100 text-amber-800 border border-amber-300' : 'text-slate-600 hover:text-slate-900 bg-slate-100 border border-slate-200'
|
||||
}`}
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
笔记 ({notes.length})
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{parsing ? (
|
||||
<div className="flex-1 flex flex-col items-center justify-center text-slate-500 space-y-2">
|
||||
<Loader className="w-8 h-8 animate-spin text-purple-500" />
|
||||
<p className="text-xs">优先解析本地 HTML 转换为 MD,回退则调用 MinerU 解析 PDF 并自动同步图床...</p>
|
||||
</div>
|
||||
) : englishText ? (
|
||||
<div className="prose prose-sm max-w-none leading-relaxed text-slate-700 prose-headings:text-purple-700 prose-strong:text-slate-900 prose-code:text-emerald-700 prose-blockquote:border-purple-500/50 prose-blockquote:text-slate-500 prose-img:max-w-full prose-img:rounded-lg">
|
||||
{englishText.split('\n\n').map((para, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
onMouseUp={() => handleTextSelection(idx)}
|
||||
className={`cursor-text relative rounded px-1 -mx-1 transition-colors ${
|
||||
notes.some(n => n.paragraph_index === idx)
|
||||
? `${NOTE_COLORS[notes.find(n => n.paragraph_index === idx)!.highlight_color]?.bg || ''} ${NOTE_COLORS[notes.find(n => n.paragraph_index === idx)!.highlight_color]?.border || ''} border`
|
||||
: 'hover:bg-slate-100'
|
||||
}`}
|
||||
>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkMath]}
|
||||
rehypePlugins={[rehypeKatex]}
|
||||
>
|
||||
{para}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 flex flex-col items-center justify-center text-slate-400">
|
||||
<FileText className="w-12 h-12 mb-3" />
|
||||
<p className="text-xs">本篇文献暂无已解析的英文 Markdown 正文</p>
|
||||
<p className="text-[11px] text-slate-500 mt-1">请点击右上方按钮开始结构化正文解析</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 中文翻译面板 */}
|
||||
<div className="glass rounded-2xl p-6 overflow-y-auto border border-slate-200 relative flex flex-col">
|
||||
<span className="text-[10px] text-emerald-700 font-bold uppercase tracking-wider block mb-3 border-b border-slate-200/60 pb-2">中文翻译 (天文学术语修正)</span>
|
||||
|
||||
{translating ? (
|
||||
<div className="flex-1 flex flex-col items-center justify-center text-slate-500 space-y-2">
|
||||
<Loader className="w-8 h-8 animate-spin text-emerald-500" />
|
||||
<p className="text-xs">加载天文学词典模糊词库映射,生成定制学术 prompt 发送至大模型...</p>
|
||||
</div>
|
||||
) : chineseText ? (
|
||||
<div className="prose prose-sm max-w-none leading-relaxed text-slate-700 prose-headings:text-emerald-700 prose-strong:text-slate-900 prose-code:text-blue-700 prose-blockquote:border-emerald-500/50 prose-img:max-w-full prose-img:rounded-lg">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkMath]}
|
||||
rehypePlugins={[rehypeKatex]}
|
||||
>
|
||||
{chineseText}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 flex flex-col items-center justify-center text-slate-400">
|
||||
<Languages className="w-12 h-12 mb-3" />
|
||||
<p className="text-xs">本篇文献暂无已缓存的翻译结果</p>
|
||||
<p className="text-[11px] text-slate-500 mt-1">需点击上方“大模型对比翻译”按钮开始翻译</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 笔记侧边栏 */}
|
||||
{showNotesPanel && (
|
||||
<div className="glass rounded-2xl border border-amber-200 bg-amber-50/20 flex flex-col overflow-hidden">
|
||||
<div className="px-5 py-4 border-b border-amber-200 flex items-center justify-between">
|
||||
<span className="text-xs text-amber-700 font-bold">段落笔记 ({notes.length})</span>
|
||||
<button onClick={() => setShowNotesPanel(false)} className="text-slate-500 hover:text-slate-800">
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 新建笔记输入区 */}
|
||||
{selectedParagraphIdx !== null && (
|
||||
<div className="px-4 py-3 border-b border-slate-200 bg-slate-50">
|
||||
<div className="text-[10px] text-slate-500 mb-2">选中段落 #{selectedParagraphIdx + 1}</div>
|
||||
{selectedText && <div className="text-[10px] text-slate-650 italic line-clamp-2 mb-2 bg-white border border-slate-200 px-2 py-1 rounded">"{selectedText}"</div>}
|
||||
{/* 高亮颜色选择 */}
|
||||
<div className="flex gap-1.5 mb-2">
|
||||
{Object.entries(NOTE_COLORS).map(([color, style]) => (
|
||||
<button
|
||||
key={color}
|
||||
onClick={() => setNewNoteColor(color)}
|
||||
className={`w-5 h-5 rounded-full border-2 transition-transform ${
|
||||
newNoteColor === color ? 'border-slate-700 scale-110' : 'border-transparent'
|
||||
} ${style.bg.replace('/20', '')}`}
|
||||
title={style.label}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<textarea
|
||||
value={newNoteText}
|
||||
onChange={e => setNewNoteText(e.target.value)}
|
||||
placeholder="输入笔记内容..."
|
||||
rows={3}
|
||||
className="w-full bg-white border border-slate-350 rounded-lg text-xs text-slate-800 placeholder-slate-400 px-3 py-2 resize-none focus:outline-none focus:border-amber-500 mb-2"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleCreateNote}
|
||||
className="flex-1 px-3 py-1.5 rounded-lg bg-amber-600 text-white text-xs hover:bg-amber-500 font-semibold flex items-center justify-center gap-1"
|
||||
>
|
||||
<PlusCircle className="w-3 h-3" /> 保存笔记
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setSelectedParagraphIdx(null); setSelectedText(''); setNewNoteText(''); }}
|
||||
className="px-3 py-1.5 rounded-lg bg-slate-150 text-slate-600 text-xs hover:bg-slate-200"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 笔记列表 */}
|
||||
<div className="flex-1 overflow-y-auto p-4 space-y-3">
|
||||
{notes.length === 0 ? (
|
||||
<div className="text-center text-slate-400 text-xs py-8">
|
||||
<Pencil className="w-8 h-8 mx-auto mb-2 opacity-40" />
|
||||
选中文字段落即可添加笔记
|
||||
</div>
|
||||
) : (
|
||||
notes.map(note => (
|
||||
<div
|
||||
key={note.id}
|
||||
className={`p-3 rounded-xl border text-xs ${NOTE_COLORS[note.highlight_color]?.bg || 'bg-slate-50'} ${NOTE_COLORS[note.highlight_color]?.border || 'border-slate-200'}`}
|
||||
>
|
||||
<div className="text-slate-500 text-[10px] mb-1">段落 #{note.paragraph_index + 1}</div>
|
||||
{note.selected_text && <div className="text-slate-600 italic line-clamp-1 mb-1 text-[10px]">"{note.selected_text}"</div>}
|
||||
<p className="text-slate-800 leading-relaxed">{note.note_text}</p>
|
||||
<div className="flex items-center justify-between mt-2">
|
||||
<span className="text-[10px] text-slate-400">{note.created_at.split('T')[0]}</span>
|
||||
<button
|
||||
onClick={() => handleDeleteNote(note.id)}
|
||||
className="text-slate-400 hover:text-red-600 transition-colors"
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// dashboard/src/features/search/SearchPanel.tsx
|
||||
import React from 'react';
|
||||
import { Search, Loader, CheckCircle, Copy, Download, RefreshCw } from 'lucide-react';
|
||||
import type { StandardPaper } from '../../types';
|
||||
|
||||
interface SearchPanelProps {
|
||||
searchQuery: string;
|
||||
setSearchQuery: (query: string) => void;
|
||||
searchSource: 'all' | 'ads' | 'arxiv';
|
||||
setSearchSource: (src: 'all' | 'ads' | 'arxiv') => void;
|
||||
searching: boolean;
|
||||
handleSearch: (e: React.FormEvent) => void;
|
||||
searchResults: StandardPaper[];
|
||||
exportingList: string[];
|
||||
toggleExportItem: (bibcode: string) => void;
|
||||
handleExportBibtex: () => void;
|
||||
exporting: boolean;
|
||||
bibtexContent: string | null;
|
||||
downloadingBibcodes: Record<string, boolean>;
|
||||
handleDownload: (bibcode: string, force?: boolean) => void;
|
||||
selectedPaper: StandardPaper | null;
|
||||
setSelectedPaper: (paper: StandardPaper | null) => void;
|
||||
openReader: (paper: StandardPaper) => void;
|
||||
setActiveTab: (tab: 'search' | 'library' | 'reader' | 'citation' | 'settings') => void;
|
||||
loadCitations: (bibcode: string, reset?: boolean) => void;
|
||||
}
|
||||
|
||||
export function SearchPanel({
|
||||
searchQuery,
|
||||
setSearchQuery,
|
||||
searchSource,
|
||||
setSearchSource,
|
||||
searching,
|
||||
handleSearch,
|
||||
searchResults,
|
||||
exportingList,
|
||||
toggleExportItem,
|
||||
handleExportBibtex,
|
||||
exporting,
|
||||
bibtexContent,
|
||||
downloadingBibcodes,
|
||||
handleDownload,
|
||||
selectedPaper,
|
||||
setSelectedPaper,
|
||||
openReader,
|
||||
setActiveTab,
|
||||
loadCitations,
|
||||
}: SearchPanelProps) {
|
||||
return (
|
||||
<div className="space-y-6 max-w-5xl mx-auto">
|
||||
{/* 搜索框 */}
|
||||
<div className="glass p-6 rounded-2xl">
|
||||
<form onSubmit={handleSearch} className="space-y-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 w-5 h-5" />
|
||||
<input
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={e => setSearchQuery(e.target.value)}
|
||||
placeholder="检索天文学文献 (支持关键字、作者、年份范围检索,如 'hot subdwarf year:2020-2023')"
|
||||
className="w-full pl-12 pr-4 py-4 rounded-xl bg-white/60 border border-slate-200 text-slate-800 placeholder-slate-400 focus:outline-none focus:border-purple-500 focus:ring-1 focus:ring-purple-500 transition-all text-sm"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={searching}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 px-5 py-2 rounded-lg bg-gradient-to-r from-purple-600 to-indigo-600 text-white text-xs font-semibold hover:from-purple-500 hover:to-indigo-500 transition-all flex items-center gap-2"
|
||||
>
|
||||
{searching ? <Loader className="w-3.5 h-3.5 animate-spin" /> : null}
|
||||
{searching ? '检索中' : '开始检索'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex gap-4">
|
||||
{[
|
||||
{ id: 'all', label: '全部数据源' },
|
||||
{ id: 'ads', label: 'NASA ADS' },
|
||||
{ id: 'arxiv', label: 'arXiv 预印本' },
|
||||
].map(src => (
|
||||
<label key={src.id} className="flex items-center gap-2 cursor-pointer text-xs">
|
||||
<input
|
||||
type="radio"
|
||||
name="searchSource"
|
||||
checked={searchSource === src.id}
|
||||
onChange={() => setSearchSource(src.id as any)}
|
||||
className="text-purple-600 focus:ring-purple-500 border-slate-300 bg-white"
|
||||
/>
|
||||
<span className={searchSource === src.id ? 'text-purple-600 font-medium' : 'text-slate-500'}>
|
||||
{src.label}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{exportingList.length > 0 && (
|
||||
<button
|
||||
onClick={handleExportBibtex}
|
||||
disabled={exporting}
|
||||
className="px-4 py-1.5 rounded-lg bg-slate-100 border border-slate-200 text-xs text-slate-600 hover:bg-slate-200 hover:text-slate-800 flex items-center gap-1.5"
|
||||
>
|
||||
{exporting ? <Loader className="w-3 h-3 animate-spin" /> : null}
|
||||
导出已选 ({exportingList.length}) BibTeX
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* BibTeX 导出结果显示 */}
|
||||
{bibtexContent && (
|
||||
<div className="glass p-6 rounded-2xl relative">
|
||||
<h3 className="text-sm font-bold text-purple-600 mb-3 flex items-center gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-emerald-500" /> BibTeX 导出成功
|
||||
</h3>
|
||||
<pre className="bg-slate-50 p-4 rounded-xl border border-slate-200 text-xs text-slate-700 font-mono overflow-x-auto whitespace-pre-wrap max-h-60">
|
||||
{bibtexContent}
|
||||
</pre>
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(bibtexContent);
|
||||
alert('已复制至剪贴板');
|
||||
}}
|
||||
className="absolute top-6 right-6 text-slate-600 hover:text-slate-900 flex items-center gap-1 text-xs bg-slate-100 px-3 py-1 rounded-lg border border-slate-200"
|
||||
>
|
||||
<Copy className="w-3 h-3" /> 复制
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 检索列表 */}
|
||||
<div className="space-y-4">
|
||||
{searchResults.map(paper => {
|
||||
const isDownloading = downloadingBibcodes[paper.bibcode] || false;
|
||||
const isSelected = selectedPaper?.bibcode === paper.bibcode;
|
||||
return (
|
||||
<div
|
||||
key={paper.bibcode}
|
||||
className={`glass p-6 rounded-2xl transition-all border ${
|
||||
isSelected ? 'border-purple-500/50 bg-purple-50/50' : 'border-slate-200/80 hover:border-slate-300'
|
||||
}`}
|
||||
>
|
||||
<div className="flex justify-between items-start gap-4 mb-2">
|
||||
<h3
|
||||
className="font-bold text-base text-slate-800 line-clamp-1 leading-snug hover:text-purple-600 cursor-pointer"
|
||||
onClick={() => openReader(paper)}
|
||||
>
|
||||
{paper.title}
|
||||
</h3>
|
||||
<div className="flex gap-2 shrink-0">
|
||||
{paper.is_downloaded ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="px-2 py-0.5 rounded bg-emerald-50 text-emerald-600 border border-emerald-200 text-[10px] font-bold uppercase">已下载</span>
|
||||
<button
|
||||
onClick={() => { if (confirm('确定要强制重新下载吗?这会覆盖本地文件。')) handleDownload(paper.bibcode, true); }}
|
||||
disabled={isDownloading}
|
||||
className="px-3 py-1 rounded bg-slate-100 border border-slate-200 text-xs text-amber-600 hover:bg-slate-200 hover:text-amber-700 flex items-center gap-1 font-semibold"
|
||||
>
|
||||
{isDownloading ? <Loader className="w-3 h-3 animate-spin" /> : <RefreshCw className="w-3 h-3" />}
|
||||
{isDownloading ? '下载中' : '重新下载'}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => handleDownload(paper.bibcode)}
|
||||
disabled={isDownloading}
|
||||
className="px-3 py-1 rounded bg-slate-100 border border-slate-200 text-xs text-slate-600 hover:bg-slate-200 hover:text-slate-900 flex items-center gap-1"
|
||||
>
|
||||
{isDownloading ? <Loader className="w-3 h-3 animate-spin" /> : <Download className="w-3 h-3" />}
|
||||
{isDownloading ? '下载中' : '下载 PDF/HTML'}
|
||||
</button>
|
||||
)}
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={exportingList.includes(paper.bibcode)}
|
||||
onChange={() => toggleExportItem(paper.bibcode)}
|
||||
className="rounded text-purple-600 border-slate-300 bg-white focus:ring-purple-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-slate-500 mb-3">
|
||||
<span className="font-medium text-slate-700">
|
||||
{paper.authors.slice(0, 3).join(', ')}{paper.authors.length > 3 ? ' et al.' : ''}
|
||||
</span>
|
||||
<span className="text-slate-300">•</span>
|
||||
<span>{paper.year}</span>
|
||||
<span className="text-slate-300">•</span>
|
||||
<span className="text-slate-500">{paper.pub_journal}</span>
|
||||
{paper.citation_count > 0 && (
|
||||
<>
|
||||
<span className="text-slate-300">•</span>
|
||||
<span className="text-amber-600 font-medium">被引: {paper.citation_count}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-slate-600 line-clamp-3 mb-4 leading-relaxed">{paper.abstract_text}</p>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => openReader(paper)}
|
||||
className="px-4 py-1.5 rounded-lg bg-gradient-to-r from-purple-50 to-indigo-50 border border-purple-200 text-xs text-purple-600 hover:from-purple-100 hover:to-indigo-100 hover:border-purple-300"
|
||||
>
|
||||
双语阅读
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedPaper(paper);
|
||||
setActiveTab('citation');
|
||||
loadCitations(paper.bibcode, true);
|
||||
}}
|
||||
className="px-4 py-1.5 rounded-lg bg-slate-100 border border-slate-200 text-xs text-slate-600 hover:bg-slate-200 hover:text-slate-900"
|
||||
>
|
||||
引用星系
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="text-[10px] text-slate-400 flex gap-4 font-mono">
|
||||
{paper.doi && <span>DOI: {paper.doi}</span>}
|
||||
<span>Bibcode: {paper.bibcode}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// dashboard/src/features/settings/SettingsPanel.tsx
|
||||
|
||||
export function SettingsPanel() {
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto space-y-6">
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-slate-800">系统设置</h2>
|
||||
<p className="text-xs text-slate-500">AstroResearch 核心系统运行参数配置</p>
|
||||
</div>
|
||||
|
||||
<div className="glass p-6 rounded-2xl space-y-6">
|
||||
<div className="border-b border-slate-200 pb-4">
|
||||
<h3 className="text-sm font-semibold text-slate-800 mb-1">配置文件 (.env) 运作模式</h3>
|
||||
<p className="text-xs text-slate-500 leading-relaxed">
|
||||
依据实施方案,所有的 API 密钥及鉴权 Token 统一保存在项目根目录下的 <code className="text-xs text-purple-650 font-semibold bg-purple-50 px-1 py-0.5 rounded">.env</code> 配置文件中,避免在数据库内泄露。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-purple-50 border border-purple-200 p-4 rounded-xl text-xs text-slate-650 leading-relaxed">
|
||||
<strong>提示</strong> 系统在后端启动时,会自动创建本地文献库物理目录并向数据库及天文学字典导入缓存。如需使用天文学中英翻译修正,请确保本地 <code className="text-xs text-purple-650 font-semibold bg-purple-50 px-1 py-0.5 rounded">/home/fmq/下载/astrodict_241020/astrodict241020_ec.txt</code> 路径文件内容完整可用。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Outfit:wght@400;500;600;700&display=swap');
|
||||
@import "tailwindcss";
|
||||
@plugin "@tailwindcss/typography";
|
||||
|
||||
:root {
|
||||
font-family: 'Inter', system-ui, -apple-system, sans-serif;
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background-color: #f8fafc;
|
||||
color: #0f172a;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* Custom premium scrollbar styling */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: #f1f5f9;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #cbd5e1;
|
||||
border-radius: 3px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: #94a3b8;
|
||||
}
|
||||
|
||||
/* Glassmorphism utility for light mode */
|
||||
.glass {
|
||||
background: rgba(255, 255, 255, 0.45);
|
||||
backdrop-filter: blur(16px);
|
||||
-webkit-backdrop-filter: blur(16px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.6);
|
||||
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.03);
|
||||
}
|
||||
|
||||
.glass-accent {
|
||||
border: 1px solid rgba(192, 132, 252, 0.2);
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes pulse-slow {
|
||||
0%, 100% { opacity: 0.4; }
|
||||
50% { opacity: 0.8; }
|
||||
}
|
||||
|
||||
.animate-pulse-slow {
|
||||
animation: pulse-slow 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
// dashboard/src/types.ts
|
||||
|
||||
export interface StandardPaper {
|
||||
bibcode: string;
|
||||
title: string;
|
||||
authors: string[];
|
||||
year: string;
|
||||
pub_journal: string;
|
||||
keywords: string[];
|
||||
abstract_text: string;
|
||||
doi: string;
|
||||
arxiv_id: string;
|
||||
citation_count: number;
|
||||
reference_count: number;
|
||||
is_downloaded: boolean;
|
||||
has_markdown: boolean;
|
||||
has_translation: boolean;
|
||||
}
|
||||
|
||||
export interface CitationNetwork {
|
||||
bibcode: string;
|
||||
title: string;
|
||||
citation_count: number;
|
||||
reference_count: number;
|
||||
references: string[];
|
||||
citations: string[];
|
||||
}
|
||||
|
||||
export interface NoteRecord {
|
||||
id: number;
|
||||
bibcode: string;
|
||||
paragraph_index: number;
|
||||
note_text: string;
|
||||
highlight_color: string;
|
||||
selected_text: string;
|
||||
created_at: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "esnext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
tailwindcss(),
|
||||
],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8000',
|
||||
changeOrigin: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,580 @@
|
||||
# 前端开发规范\-React篇
|
||||
|
||||
React 开发实践指南
|
||||
|
||||
V1\.0 \| 2026年5月 \
|
||||
|
||||
# 一、概述与总则
|
||||
|
||||
本文档旨在统一前端开发团队的技术实践标准,确保代码质量、可维护性和团队协作效率。规范覆盖 React 技术栈的核心开发场景,同时涵盖 HTML/CSS、JavaScript/TypeScript 等基础层面的通用准则。
|
||||
|
||||
## 1\.1 适用范围
|
||||
|
||||
本规范适用于所有使用 React 技术栈的前端项目,包括但不限于:
|
||||
|
||||
1. 使用 React 18\+ 的 Web 应用项目
|
||||
|
||||
2. 基于 Next\.js、Remix 等元框架的服务端渲染项目
|
||||
|
||||
3. 使用 React Native 的移动端跨平台项目(部分适用)
|
||||
|
||||
## 1\.2 规范层级
|
||||
|
||||
规范条目按强制程度分为三个层级,开发者应根据项目实际情况合理遵循:
|
||||
|
||||
|**层级**|**标识**|**说明**|
|
||||
|---|---|---|
|
||||
|必须(Must)|\[M\]|所有项目必须严格遵守,Code Review 中必检项|
|
||||
|推荐(Should)|\[S\]|强烈建议遵循,特殊场景经评估后可调整|
|
||||
|可选(May)|\[O\]|根据项目实际情况选择性采纳|
|
||||
|
||||
## 1\.3 技术栈版本要求
|
||||
|
||||
新项目应优先采用以下技术栈版本,已有项目应在迭代周期内逐步升级:
|
||||
|
||||
|**技术项**|**推荐版本**|**说明**|
|
||||
|---|---|---|
|
||||
|React|18\.x / 19\.x|使用最新稳定版|
|
||||
|TypeScript|5\.5\+|strict 模式启用|
|
||||
|Vite|6\.x|构建工具首选|
|
||||
|Next\.js|15\.x|SSR/SSG 场景|
|
||||
|Tailwind CSS|4\.x|原子化 CSS 方案|
|
||||
|ESLint|9\.x|Flat Config 格式|
|
||||
|
||||
# 二、React 开发规范
|
||||
|
||||
React 是本规范的核心关注领域。本章从组件设计、Hooks 使用、状态管理、TypeScript 类型约束和性能优化五个维度,系统性地定义 React 开发的最佳实践。
|
||||
|
||||
## 2\.1 组件设计规范
|
||||
|
||||
### 2\.1\.1 组件分类与组织
|
||||
|
||||
React 组件应按职责明确划分为以下类别,并在项目目录中保持清晰的组织结构:
|
||||
|
||||
|**组件类型**|**存放路径**|**职责说明**|
|
||||
|---|---|---|
|
||||
|Page 组件|app/ 或 pages/|路由级别的页面组件,负责数据获取和页面级布局|
|
||||
|Layout 组件|components/layout/|页面布局框架,如 Header、Sidebar、Footer|
|
||||
|UI 组件|components/ui/|基础 UI 元素,Button、Input、Modal 等纯展示组件|
|
||||
|Feature 组件|features/\*/components/|业务功能组件,与特定功能域紧耦合|
|
||||
|HOC / 工具|components/hoc/|高阶组件和渲染工具(render props)|
|
||||
|
||||
### 2\.1\.2 函数组件优先
|
||||
|
||||
自 React 16\.8 引入 Hooks 以来,函数组件已成为官方推荐的标准写法。所有新开发组件必须使用函数组件,类组件仅在维护遗留代码时允许存在。
|
||||
|
||||
```TypeScript
|
||||
// 推荐:函数组件 + Hooks
|
||||
import { useState, useCallback } from 'react';
|
||||
|
||||
interface UserCardProps {
|
||||
user: User;
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
export function UserCard({ user, onSelect }: UserCardProps) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
onSelect(user.id);
|
||||
setExpanded(prev => !prev);
|
||||
}, [onSelect, user.id]);
|
||||
|
||||
return (
|
||||
<Card onClick={handleClick}>
|
||||
<Avatar src={user.avatar} />
|
||||
<UserName>{user.name}</UserName>
|
||||
{expanded && <UserDetail user={user} />}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 2\.1\.3 Props 设计原则
|
||||
|
||||
组件的 Props 接口设计直接影响组件的可复用性和可维护性。遵循以下原则:
|
||||
|
||||
4. 单一职责:每个组件只接收其渲染所需的最小数据集合,避免传递冗余数据
|
||||
|
||||
5. 显式接口:使用 TypeScript interface 定义 Props,禁止隐式 any 类型
|
||||
|
||||
6. 默认值策略:对可选 Props 提供合理的默认值,或使用解构赋值简化处理
|
||||
|
||||
7. 事件命名:自定义事件处理器以 on 为前缀(如 onSelect、onValueChange),遵循 React 原生事件命名惯例
|
||||
|
||||
8. 避免过度透传:不要简单地将父组件的 Props 全部展开传递给子组件,应显式声明所需属性
|
||||
|
||||
### 2\.1\.4 组件文件结构
|
||||
|
||||
每个组件应按以下结构组织,确保关注点分离和可测试性:
|
||||
|
||||
```TypeScript
|
||||
// components/UserCard/index.tsx
|
||||
export { UserCard } from './UserCard';
|
||||
export type { UserCardProps } from './types';
|
||||
|
||||
// components/UserCard/UserCard.tsx
|
||||
import { useState } from 'react';
|
||||
import type { UserCardProps } from './types';
|
||||
import { useUserCard } from './useUserCard';
|
||||
import * as S from './styles';
|
||||
|
||||
export function UserCard({ user, onSelect }: UserCardProps) {
|
||||
const { expanded, handleClick } = useUserCard(user, onSelect);
|
||||
return (
|
||||
<S.Card onClick={handleClick}>...</S.Card>
|
||||
);
|
||||
}
|
||||
|
||||
// components/UserCard/types.ts
|
||||
export interface UserCardProps {
|
||||
user: User;
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
// components/UserCard/useUserCard.ts
|
||||
export function useUserCard(user: User, onSelect: (id: string) => void) {
|
||||
// 业务逻辑抽离到自定义 Hook
|
||||
}
|
||||
|
||||
// components/UserCard/styles.ts (styled-components / CSS Modules)
|
||||
```
|
||||
|
||||
## 2\.2 Hooks 使用规范
|
||||
|
||||
### 2\.2\.1 Hooks 基础规则
|
||||
|
||||
Hooks 是 React 16\.8 引入的革命性特性,必须严格遵循以下使用规则,否则可能导致不可预期的行为:
|
||||
|
||||
9. 只在最顶层调用 Hooks:不要在循环、条件判断或嵌套函数中调用 Hooks
|
||||
|
||||
10. 只在 React 函数中调用 Hooks:在函数组件或自定义 Hook 中调用,不要在普通 JavaScript 函数中调用
|
||||
|
||||
11. 以 use 开头命名:自定义 Hook 必须以 use 开头命名,以便 ESLint 插件识别
|
||||
|
||||
12. 依赖数组诚实原则:useEffect、useMemo、useCallback 的依赖数组必须完整列出所有依赖项
|
||||
|
||||
### 2\.2\.2 useEffect 最佳实践
|
||||
|
||||
useEffect 是最常用的 Hook 之一,也是最容易滥用的。遵循以下实践:
|
||||
|
||||
```JavaScript
|
||||
// 推荐:单一职责的 Effect
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
fetchUser(userId, { signal: controller.signal })
|
||||
.then(setUser)
|
||||
.catch(setError);
|
||||
return () => controller.abort();
|
||||
}, [userId]); // 依赖数组必须完整
|
||||
|
||||
// 推荐:逻辑拆分到独立 Effect
|
||||
useEffect(() => {
|
||||
// 数据获取逻辑
|
||||
}, [params]);
|
||||
|
||||
useEffect(() => {
|
||||
// DOM 操作或订阅逻辑
|
||||
return () => { /* 清理逻辑 */ };
|
||||
}, []);
|
||||
|
||||
// 禁止:缺失依赖项
|
||||
useEffect(() => {
|
||||
fetchData(page); // page 未在依赖数组中!
|
||||
}, []); // eslint-disable-line 是临时方案,应尽快修复
|
||||
```
|
||||
|
||||
### 2\.2\.3 useMemo 与 useCallback
|
||||
|
||||
性能优化 Hooks 应在有明确性能问题时使用,避免过早优化。遵循以下准则:
|
||||
|
||||
13. useMemo:用于缓存昂贵的计算结果,仅在计算成本显著高于缓存开销时使用
|
||||
|
||||
14. useCallback:用于缓存事件处理函数,主要配合 React\.memo 使用,避免子组件不必要的重渲染
|
||||
|
||||
15. 避免滥用:简单的计算和事件处理不需要 memoization,React 的渲染性能通常优于预期
|
||||
|
||||
16. 依赖数组完整性:与 useEffect 同样,必须确保依赖数组的完整性
|
||||
|
||||
```JavaScript
|
||||
// 推荐:复杂数据转换使用 useMemo
|
||||
const filteredUsers = useMemo(() => {
|
||||
return users
|
||||
.filter(u => u.active)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, 100);
|
||||
}, [users]);
|
||||
|
||||
// 推荐:配合 React.memo 使用 useCallback
|
||||
const handleSubmit = useCallback((values: FormData) => {
|
||||
api.submit(values).then(onSuccess);
|
||||
}, [onSuccess]);
|
||||
|
||||
// 禁止:对简单值使用 useMemo
|
||||
const fullName = useMemo(
|
||||
() => `$${firstName} $${lastName}`,
|
||||
[firstName, lastName] // 字符串拼接成本极低,无需缓存
|
||||
);
|
||||
```
|
||||
|
||||
## 2\.3 状态管理规范
|
||||
|
||||
### 2\.3\.1 状态管理策略
|
||||
|
||||
React 应用的状态管理应按状态的作用域和复杂度选择适当的方案,避免过度工程化:
|
||||
|
||||
|**状态类型**|**管理方案**|**适用场景**|
|
||||
|---|---|---|
|
||||
|本地 UI 状态|useState|组件内部的临时状态,如表单输入、展开/收起|
|
||||
|派生状态|useMemo / 计算|可从已有状态计算得出的值|
|
||||
|共享状态|Context / Props|跨 2\-3 层组件传递的状态|
|
||||
|全局状态|Zustand / Jotai|应用级共享状态,如用户信息、主题设置|
|
||||
|服务端状态|TanStack Query|服务器数据缓存和同步|
|
||||
|表单状态|React Hook Form|复杂表单的状态和验证管理|
|
||||
|
||||
### 2\.3\.2 Context 使用规范
|
||||
|
||||
React Context 适用于跨组件层级的数据传递,但不当使用会导致性能问题:
|
||||
|
||||
17. 拆分 Context:将高频变化和低频变化的状态拆分到独立的 Context,避免不必要的重渲染
|
||||
|
||||
18. 避免过度使用:仅在真正需要跨多级组件传递数据时使用,简单的父子组件通信仍应通过 Props
|
||||
|
||||
19. 结合 useReducer:对于复杂状态逻辑,Context 配合 useReducer 可以实现轻量级的 Redux\-like 方案
|
||||
|
||||
```TypeScript
|
||||
// 推荐:拆分 Context 避免重渲染
|
||||
const ThemeContext = createContext<Theme>('light');
|
||||
const UserContext = createContext<User | null>(null);
|
||||
|
||||
// ThemeProvider 更新时,只消费 ThemeContext 的组件重渲染
|
||||
// UserProvider 更新时,只消费 UserContext 的组件重渲染
|
||||
|
||||
// 推荐:Context + useReducer 组合
|
||||
type Action = { type: 'increment' } | { type: 'decrement' };
|
||||
const CounterContext = createContext<{
|
||||
state: number;
|
||||
dispatch: React.Dispatch<Action>;
|
||||
} | null>(null);
|
||||
```
|
||||
|
||||
### 2\.3\.3 外部状态管理(Zustand/Jotai)
|
||||
|
||||
对于中大型企业级应用,推荐使用轻量级的原子化状态管理方案,如 Zustand 或 Jotai:
|
||||
|
||||
20. Zustand:适合模块化的 Store 架构,API 极简,无 Provider 包裹问题
|
||||
|
||||
21. Jotai:适合原子化的细粒度状态管理,状态依赖自动追踪
|
||||
|
||||
22. 避免 Redux 过度使用:仅在需要 Redux DevTools 时间旅行调试、复杂中间件链时考虑 Redux Toolkit
|
||||
|
||||
## 2\.4 TypeScript 类型规范
|
||||
|
||||
### 2\.4\.1 组件 Props 类型
|
||||
|
||||
所有组件 Props 必须使用 TypeScript 接口显式定义,禁止使用 any 类型绕过类型检查:
|
||||
|
||||
```TypeScript
|
||||
// 推荐:显式 Props 接口
|
||||
interface ButtonProps {
|
||||
variant?: 'primary' | 'secondary' | 'ghost';
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
disabled?: boolean;
|
||||
loading?: boolean;
|
||||
onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function Button({
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
disabled = false,
|
||||
loading = false,
|
||||
onClick,
|
||||
children,
|
||||
}: ButtonProps) {
|
||||
// 实现...
|
||||
}
|
||||
|
||||
// 禁止:隐式 any 或缺少类型
|
||||
// function Button(props) { // 错误!props 为 any
|
||||
// return <button>{props.label}</button>;
|
||||
// }
|
||||
```
|
||||
|
||||
### 2\.4\.2 泛型组件
|
||||
|
||||
对于数据展示类组件,使用泛型实现类型安全的通用组件:
|
||||
|
||||
```TypeScript
|
||||
// 推荐:泛型表格组件
|
||||
interface DataTableProps<T> {
|
||||
data: T[];
|
||||
columns: ColumnDef<T>[];
|
||||
keyExtractor: (item: T) => string;
|
||||
onRowClick?: (item: T) => void;
|
||||
}
|
||||
|
||||
export function DataTable<T>({
|
||||
data, columns, keyExtractor, onRowClick,
|
||||
}: DataTableProps<T>) {
|
||||
return (
|
||||
<table>
|
||||
<tbody>
|
||||
{data.map(item => (
|
||||
<tr key={keyExtractor(item)}
|
||||
onClick={() => onRowClick?.(item)}>
|
||||
{columns.map(col => (
|
||||
<td key={col.key}>{col.render(item)}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 2\.4\.3 事件类型
|
||||
|
||||
React 事件处理函数应使用 React 提供的泛型事件类型,而非原生 DOM 事件类型:
|
||||
|
||||
|**事件类型**|**React 类型**|
|
||||
|---|---|
|
||||
|点击事件|React\.MouseEvent\<HTMLButtonElement\>|
|
||||
|输入事件|React\.ChangeEvent\<HTMLInputElement\>|
|
||||
|表单提交|React\.FormEvent\<HTMLFormElement\>|
|
||||
|键盘事件|React\.KeyboardEvent\<HTMLInputElement\>|
|
||||
|拖拽事件|React\.DragEvent\<HTMLDivElement\>|
|
||||
|触摸事件|React\.TouchEvent\<HTMLDivElement\>|
|
||||
|通用事件|React\.SyntheticEvent|
|
||||
|
||||
## 2\.5 性能优化规范
|
||||
|
||||
### 2\.5\.1 渲染优化
|
||||
|
||||
React 的渲染优化应从以下维度系统化地进行:
|
||||
|
||||
23. React\.memo:对纯展示组件使用 React\.memo 进行浅比较优化,避免不必要的重渲染
|
||||
|
||||
24. useMemo / useCallback:对昂贵的计算和传递给子组件的回调进行缓存
|
||||
|
||||
25. 虚拟列表:长列表使用 react\-window 或 react\-virtualized 实现虚拟滚动
|
||||
|
||||
26. 代码分割:使用 React\.lazy \+ Suspense 实现路由级别和组件级别的懒加载
|
||||
|
||||
```JavaScript
|
||||
// 推荐:React.memo + 自定义比较函数
|
||||
export const UserList = React.memo(function UserList({
|
||||
users,
|
||||
onSelect,
|
||||
}: UserListProps) {
|
||||
return (
|
||||
<ul>
|
||||
{users.map(user => (
|
||||
<UserItem key={user.id} user={user} onSelect={onSelect} />
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}, (prev, next) => prev.users === next.users);
|
||||
|
||||
// 推荐:React.lazy 代码分割
|
||||
const Dashboard = React.lazy(() => import('./Dashboard'));
|
||||
const Settings = React.lazy(() => import('./Settings'));
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Suspense fallback={<LoadingSpinner />}>
|
||||
<Routes>
|
||||
<Route path="/dashboard" element={<Dashboard />} />
|
||||
<Route path="/settings" element={<Settings />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 2\.5\.2 状态更新优化
|
||||
|
||||
状态更新方式直接影响渲染性能,应遵循以下最佳实践:
|
||||
|
||||
27. 批量更新:React 18 自动批处理所有状态更新,无需手动合并
|
||||
|
||||
28. 不可变数据:始终使用不可变更新模式,配合 useMemo/React\.memo 进行引用比较
|
||||
|
||||
29. 状态拆分:将独立变化的状态拆分为多个 useState,避免不必要的联合更新
|
||||
|
||||
30. 派生状态:优先使用 useMemo 计算派生状态,避免在状态中存储可计算的值
|
||||
|
||||
# 三、HTML/CSS 规范
|
||||
|
||||
HTML 和 CSS 是前端开发的基础,良好的标记和样式实践是构建可维护应用的前提。
|
||||
|
||||
## 3\.1 HTML 语义化
|
||||
|
||||
语义化的 HTML 不仅有利于可访问性(A11y),也有助于 SEO 和代码的可读性:
|
||||
|
||||
31. 使用恰当的语义化标签:header、nav、main、article、section、aside、footer
|
||||
|
||||
32. 表单元素必须关联 label,使用 aria\-label 或 aria\-labelledby 补充描述
|
||||
|
||||
33. 图片必须提供有意义的 alt 文本,装饰性图片使用 alt=""
|
||||
|
||||
34. 遵循标题层级顺序(h1 → h2 → h3),不要跳级使用
|
||||
|
||||
## 3\.2 CSS 架构
|
||||
|
||||
推荐采用CSS Modules,避免全局命名空间污染:
|
||||
|
||||
```JavaScript
|
||||
// 推荐:CSS Modules
|
||||
import styles from './Button.module.css';
|
||||
|
||||
export function Button({ children }) {
|
||||
return <button className={styles.button}>{children}</button>;
|
||||
}
|
||||
|
||||
/* Button.module.css */
|
||||
.button {
|
||||
padding: 8px 16px;
|
||||
border-radius: 4px;
|
||||
background: var(--color-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
background: var(--color-primary-dark);
|
||||
}
|
||||
```
|
||||
|
||||
## 3\.3 响应式设计
|
||||
|
||||
所有界面必须适配至少三种断点,采用移动优先的设计策略:
|
||||
|
||||
|**断点名**|**尺寸范围**|**适配策略**|
|
||||
|---|---|---|
|
||||
|Mobile|\< 768px|单列布局、触摸友好的交互、简化导航|
|
||||
|Tablet|768px \- 1024px|双列布局、侧边栏可收起、适配触控|
|
||||
|Desktop|\> 1024px|完整多列布局、 hover 交互、固定侧边栏|
|
||||
|
||||
# 四、JavaScript/TypeScript 通用规范
|
||||
|
||||
除 React 特定规范外,团队应遵循以下 JavaScript/TypeScript 通用编码规范。
|
||||
|
||||
## 4\.1 命名规范
|
||||
|
||||
35. 文件名:PascalCase 用于组件文件(UserCard\.tsx),camelCase 用于工具文件(formatDate\.ts)
|
||||
|
||||
36. 组件名:PascalCase,与文件名保持一致
|
||||
|
||||
37. Hook 名:以 use 开头,后跟 PascalCase(useUserData)
|
||||
|
||||
38. 常量:UPPER\_SNAKE\_CASE(MAX\_RETRY\_COUNT)
|
||||
|
||||
39. 布尔变量:使用 is、has、should 等前缀(isLoading、hasError)
|
||||
|
||||
## 4\.2 代码风格
|
||||
|
||||
统一使用 ESLint \+ Prettier 进行代码格式化和质量检查,配置文件纳入版本控制:
|
||||
|
||||
```Java
|
||||
// .eslintrc.cjs
|
||||
module.exports = {
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'@typescript-eslint/recommended',
|
||||
'plugin:react-hooks/recommended',
|
||||
],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/explicit-function-return-type': 'warn',
|
||||
'react-hooks/exhaustive-deps': 'error',
|
||||
},
|
||||
};
|
||||
|
||||
// .prettierrc
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 2,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
```
|
||||
|
||||
## 4\.3 类型安全
|
||||
|
||||
40. strict 模式:TypeScript 配置必须启用 strict: true
|
||||
|
||||
41. 禁止 any:原则上禁止使用 any 类型,必要时应使用 unknown 并配合类型收窄
|
||||
|
||||
42. 返回值类型:公共函数应显式声明返回值类型,利用类型推断的边界情况除外
|
||||
|
||||
43. 类型导出:组件 Props 接口应随组件一起导出,便于复用
|
||||
|
||||
# 五、工程化与项目结构
|
||||
|
||||
良好的项目结构和工程化配置是团队协作的基石。
|
||||
|
||||
## 5\.1 目录结构
|
||||
|
||||
推荐采用以下目录组织方式,Feature\-based 结构优先:
|
||||
|
||||
```Python
|
||||
src/
|
||||
├── app/ # 路由页面(Next.js / React Router)
|
||||
│ ├── layout.tsx
|
||||
│ ├── page.tsx
|
||||
│ └── dashboard/
|
||||
│ └── page.tsx
|
||||
├── components/ # 共享组件
|
||||
│ ├── ui/ # 基础 UI 组件(Button, Input, Modal)
|
||||
│ └── layout/ # 布局组件(Header, Sidebar, Footer)
|
||||
├── features/ # 功能模块
|
||||
│ └── auth/ # 认证功能
|
||||
│ ├── api/ # API 请求
|
||||
│ ├── components/ # 功能组件
|
||||
│ ├── hooks/ # 功能 Hooks
|
||||
│ ├── stores/ # 状态管理
|
||||
│ └── types.ts # 功能类型
|
||||
├── hooks/ # 全局共享 Hooks
|
||||
├── lib/ # 工具库和配置
|
||||
│ ├── api.ts # Axios 实例配置
|
||||
│ └── utils.ts # 通用工具函数
|
||||
├── types/ # 全局类型定义
|
||||
└── styles/ # 全局样式和主题配置
|
||||
```
|
||||
|
||||
## 5\.2 开发工作流
|
||||
|
||||
44. Git 分支策略:采用 Git Flow 或 Trunk\-based 开发,功能分支命名格式 feature/描述 或 fix/描述
|
||||
|
||||
45. 代码审查:所有代码变更必须通过 Pull Request 审查,至少 1 人 approving 后方可合并
|
||||
|
||||
46. 提交规范:遵循 Conventional Commits 规范(feat:、fix:、docs:、refactor:、test: 等前缀)
|
||||
|
||||
47. CI/CD:集成自动化测试、代码质量检查(ESLint、TypeScript 编译检查)到 CI 流水线
|
||||
|
||||
# 六、性能优化与最佳实践
|
||||
|
||||
性能优化是前端开发的重要环节,应贯穿整个开发周期。
|
||||
|
||||
## 6\.1 加载性能
|
||||
|
||||
48. 资源压缩:启用 Gzip/Brotli 压缩,图片使用 WebP/AVIF 格式
|
||||
|
||||
49. 懒加载:路由、图片、非首屏组件均使用懒加载策略
|
||||
|
||||
50. 预加载:对关键资源使用 rel=preload,对后续路由使用 rel=prefetch
|
||||
|
||||
51. Bundle 分析:定期使用 @next/bundle\-analyzer 或 webpack\-bundle\-analyzer 分析打包体积
|
||||
|
||||
## 6\.2 运行时性能
|
||||
|
||||
52. 避免频繁的状态更新:使用防抖(debounce)和节流(throttle)控制高频事件
|
||||
|
||||
53. Web Workers:将复杂计算 offload 到 Web Worker,避免阻塞主线程
|
||||
|
||||
54. 内存管理:及时清理定时器、事件监听器和订阅,防止内存泄漏
|
||||
|
||||
55. 虚拟化:长列表使用虚拟滚动,大数据集使用分页或虚拟表格
|
||||
|
||||
Reference in New Issue
Block a user