Initial commit: 国土空间规划课程智能体 v1.0

单容器 Docker 架构的国土空间规划课程智能问答系统,集成 FastAPI 后端与 Next.js 前端。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-22 09:40:18 +08:00
commit ddbb79b9f6
167 changed files with 44147 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+43
View File
@@ -0,0 +1,43 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
// 启用 standalone 输出模式(用于 Docker
output: 'standalone',
experimental: {
turbo: {
rules: {
'*.svg': {
loaders: ['@svgr/webpack'],
as: '*.js',
},
},
},
},
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**',
},
],
},
async rewrites() {
// 在容器环境中,前端和后端在同一容器内,可以直接访问
const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000';
return [
{
source: '/api/:path*',
destination: `${backendUrl}/:path*`,
},
{
source: '/generated_images/:path*',
destination: `${backendUrl}/generated_images/:path*`,
},
];
},
// 禁用静态生成,避免 SSR 时使用浏览器 API 的错误
generateBuildId: async () => {
return 'build-' + Date.now();
},
};
export default nextConfig;
+87
View File
@@ -0,0 +1,87 @@
{
"name": "course-agent-web",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"build": "next build",
"check": "next lint && tsc --noEmit",
"dev": "next dev --turbo --port 8001",
"format:check": "prettier --check \"**/*.{ts,tsx,js,jsx,mdx}\" --cache",
"format:write": "prettier --write \"**/*.{ts,tsx,js,jsx,mdx}\" --cache",
"lint": "next lint",
"lint:fix": "next lint --fix",
"preview": "next build && next start --port 8001",
"start": "next start --port 8001",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@hookform/resolvers": "^5.0.1",
"@radix-ui/react-accordion": "^1.2.8",
"@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-checkbox": "^1.2.3",
"@radix-ui/react-collapsible": "^1.1.8",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-icons": "^1.3.2",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-popover": "^1.1.11",
"@radix-ui/react-radio-group": "^1.3.8",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.7",
"@radix-ui/react-slider": "^1.3.6",
"@radix-ui/react-slot": "^1.2.0",
"@radix-ui/react-switch": "^1.2.2",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-tooltip": "^1.2.0",
"@t3-oss/env-nextjs": "^0.11.0",
"@tailwindcss/typography": "^0.5.16",
"autoprefixer": "^10.4.21",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^4.1.0",
"framer-motion": "^12.23.24",
"highlight.js": "^11.11.1",
"js-cookie": "^3.0.5",
"katex": "^0.16.21",
"lucide-react": "^0.487.0",
"next": "^15.4.7",
"next-auth": "^4.24.11",
"next-themes": "^0.4.6",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-force-graph-2d": "^1.29.0",
"react-hook-form": "^7.56.1",
"react-markdown": "^10.1.0",
"react-syntax-highlighter": "^15.6.1",
"rehype-katex": "^7.0.1",
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"sonner": "^2.0.3",
"tailwind-merge": "^3.2.0",
"tw-animate-css": "^1.4.0",
"typescript": "^5.8.2",
"zod": "^3.24.3",
"zustand": "^5.0.3"
},
"devDependencies": {
"@eslint/eslintrc": "^3.3.1",
"@tailwindcss/postcss": "^4.1.14",
"@types/hast": "^3.0.4",
"@types/js-cookie": "^3.0.6",
"@types/node": "^20.14.10",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@types/react-syntax-highlighter": "^15.5.13",
"eslint": "^9.23.0",
"eslint-config-next": "^15.2.3",
"postcss": "^8.5.3",
"prettier": "^3.5.3",
"prettier-plugin-tailwindcss": "^0.6.11",
"tailwindcss": "^4.0.15",
"typescript-eslint": "^8.27.0"
},
"packageManager": "pnpm@10.6.5"
}
+7110
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
'@tailwindcss/postcss': {},
autoprefixer: {},
},
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 MiB

+394
View File
@@ -0,0 +1,394 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>p5.js 城市数据可视化</title>
<script src="https://cdn.jsdelivr.net/npm/p5@1.9.4/lib/p5.min.js"></script>
<style>
body { margin: 0; overflow: hidden; background: #0a0a1a; }
canvas { display: block; }
#info {
position: fixed; bottom: 20px; left: 50%;
transform: translateX(-50%);
color: rgba(255,255,255,0.6);
font-family: system-ui, sans-serif;
font-size: 14px;
pointer-events: none;
text-align: center;
}
</style>
</head>
<body>
<div id="info">移动鼠标查看区域数据 | 点击切换数据维度 | 按空格切换视图</div>
<script>
let buildings = [];
let roads = [];
let districts = [];
let currentMetric = 0;
let metricNames = ['人口密度', '绿化率', '容积率', '交通便利度'];
let metricColors = [
[255, 100, 100],
[100, 220, 100],
[100, 150, 255],
[255, 220, 80]
];
let camX = 0, camY = 0;
let targetCamX = 0, targetCamY = 0;
let hoveredBuilding = null;
let viewMode = 0;
let time = 0;
let particles = [];
function setup() {
createCanvas(windowWidth, windowHeight);
generateCity();
}
function generateCity() {
buildings = [];
roads = [];
districts = [];
particles = [];
// 生成道路网格
let gridSize = 100;
for (let x = -800; x <= 800; x += gridSize) {
roads.push({ x1: x, y1: -800, x2: x, y2: 800 });
}
for (let y = -800; y <= 800; y += gridSize) {
roads.push({ x1: -800, y1: y, x2: 800, y2: y });
}
// 生成主路(更宽)
for (let x = -800; x <= 800; x += gridSize * 3) {
roads.push({ x1: x, y1: -800, x2: x, y2: 800, main: true });
}
for (let y = -800; y <= 800; y += gridSize * 3) {
roads.push({ x1: -800, y1: y, x2: 800, y2: y, main: true });
}
// 生成建筑
let types = ['residential', 'commercial', 'industrial', 'park'];
let typeLabels = { residential: '住宅区', commercial: '商业区', industrial: '工业区', park: '公园绿地' };
for (let gx = -750; gx < 750; gx += gridSize) {
for (let gy = -750; gy < 750; gy += gridSize) {
let cx = gx + gridSize / 2;
let cy = gy + gridSize / 2;
let dist = sqrt(cx * cx + cy * cy);
let type;
if (dist < 200) type = 'commercial';
else if (dist < 500) type = random() > 0.2 ? 'residential' : 'park';
else type = random() > 0.3 ? 'residential' : 'industrial';
if (type === 'park') {
buildings.push({
x: cx, y: cy,
w: gridSize * 0.8, h: gridSize * 0.8,
height: 0, type: type, label: typeLabels[type],
metrics: {
pop: random(5, 20),
green: random(70, 95),
far: random(0.1, 0.3),
traffic: random(20, 40)
}
});
continue;
}
let count = floor(random(1, 5));
for (let i = 0; i < count; i++) {
let bw = random(15, gridSize * 0.4);
let bh = random(15, gridSize * 0.4);
let bx = cx + random(-gridSize * 0.3, gridSize * 0.3);
let by = cy + random(-gridSize * 0.3, gridSize * 0.3);
let bHeight;
if (type === 'commercial') bHeight = random(60, 180);
else if (type === 'residential') bHeight = random(20, 80);
else bHeight = random(15, 40);
buildings.push({
x: bx, y: by,
w: bw, h: bh,
height: bHeight,
type: type,
label: typeLabels[type],
metrics: {
pop: type === 'commercial' ? random(200, 800) : random(50, 300),
green: random(10, 40),
far: bHeight / 50,
traffic: random(30, 90)
}
});
}
}
}
// 流动粒子(代表交通)
for (let i = 0; i < 200; i++) {
particles.push({
roadIdx: floor(random(roads.length)),
t: random(1),
speed: random(0.002, 0.008),
color: [255, 220, 80, random(100, 200)]
});
}
}
function draw() {
background(10, 10, 26);
time += 0.01;
// 平滑相机
camX = lerp(camX, targetCamX, 0.05);
camY = lerp(camY, targetCamY, 0.05);
push();
translate(width / 2 + camX, height / 2 + camY);
// 绘制地面
fill(15, 15, 35);
noStroke();
rect(-800, -800, 1600, 1600);
// 绘制道路
for (let r of roads) {
if (r.main) {
stroke(40, 40, 70);
strokeWeight(4);
} else {
stroke(30, 30, 55);
strokeWeight(1);
}
line(r.x1, r.y1, r.x2, r.y2);
}
// 更新和绘制流动粒子
noStroke();
for (let p of particles) {
p.t += p.speed;
if (p.t > 1) p.t -= 1;
let r = roads[p.roadIdx];
let px = lerp(r.x1, r.x2, p.t);
let py = lerp(r.y1, r.y2, p.t);
fill(p.color);
ellipse(px, py, 3, 3);
}
hoveredBuilding = null;
// 绘制建筑
for (let b of buildings) {
let mc = metricColors[currentMetric];
let metricVal;
if (currentMetric === 0) metricVal = b.metrics.pop / 800;
else if (currentMetric === 1) metricVal = b.metrics.green / 95;
else if (currentMetric === 2) metricVal = b.metrics.far / 3.6;
else metricVal = b.metrics.traffic / 90;
metricVal = constrain(metricVal, 0, 1);
if (viewMode === 0) {
drawBuildingTop(b, mc, metricVal);
} else {
drawBuildingIso(b, mc, metricVal);
}
// 检测鼠标悬停
let mx = mouseX - width / 2 - camX;
let my = mouseY - height / 2 - camY;
if (abs(mx - b.x) < b.w / 2 + 5 && abs(my - b.y) < b.h / 2 + 5) {
hoveredBuilding = b;
}
}
pop();
// 绘制UI
drawUI();
// 绘制悬停信息
if (hoveredBuilding) {
drawTooltip(hoveredBuilding);
}
}
function drawBuildingTop(b, mc, val) {
if (b.type === 'park') {
fill(30, 100 + val * 80, 30, 150);
noStroke();
rect(b.x - b.w / 2, b.y - b.h / 2, b.w, b.h, 4);
// 树
for (let i = 0; i < 5; i++) {
let tx = b.x + random(-b.w * 0.3, b.w * 0.3);
let ty = b.y + random(-b.h * 0.3, b.h * 0.3);
fill(40, 140, 40, 180);
ellipse(tx, ty, 8, 8);
}
} else {
let pulse = sin(time * 2 + b.x * 0.01) * 0.1 + 0.9;
let alpha = 80 + val * 170;
fill(mc[0], mc[1], mc[2], alpha * pulse);
noStroke();
rect(b.x - b.w / 2, b.y - b.h / 2, b.w, b.h, 2);
// 高度阴影
fill(0, 0, 0, b.height * 0.3);
let offset = b.height * 0.1;
rect(b.x - b.w / 2 + offset, b.y - b.h / 2 + offset, b.w, b.h, 2);
}
}
function drawBuildingIso(b, mc, val) {
let h = b.height * 0.3;
if (b.type === 'park') {
fill(30, 120, 30, 150);
noStroke();
rect(b.x - b.w / 2, b.y - b.h / 2, b.w, b.h, 4);
return;
}
let alpha = 100 + val * 155;
// 右侧面
fill(mc[0] * 0.6, mc[1] * 0.6, mc[2] * 0.6, alpha);
noStroke();
beginShape();
vertex(b.x + b.w / 2, b.y - b.h / 2);
vertex(b.x + b.w / 2, b.y - b.h / 2 - h);
vertex(b.x + b.w / 2 + h * 0.4, b.y - b.h / 2 - h - h * 0.4);
vertex(b.x + b.w / 2 + h * 0.4, b.y - b.h / 2 + h * 0.4);
endShape(CLOSE);
// 正面
fill(mc[0] * 0.8, mc[1] * 0.8, mc[2] * 0.8, alpha);
beginShape();
vertex(b.x - b.w / 2, b.y - b.h / 2);
vertex(b.x - b.w / 2, b.y - b.h / 2 - h);
vertex(b.x + b.w / 2, b.y - b.h / 2 - h);
vertex(b.x + b.w / 2, b.y - b.h / 2);
endShape(CLOSE);
// 顶面
fill(mc[0], mc[1], mc[2], alpha);
beginShape();
vertex(b.x - b.w / 2, b.y - b.h / 2 - h);
vertex(b.x - b.w / 2 + h * 0.4, b.y - b.h / 2 - h - h * 0.4);
vertex(b.x + b.w / 2 + h * 0.4, b.y - b.h / 2 - h - h * 0.4);
vertex(b.x + b.w / 2, b.y - b.h / 2 - h);
endShape(CLOSE);
}
function drawUI() {
// 左上角标题
fill(255, 255, 255, 200);
noStroke();
textSize(18);
textAlign(LEFT, TOP);
textFont('system-ui');
text('城市数据可视化', 20, 20);
textSize(12);
fill(255, 255, 255, 120);
text('当前指标: ' + metricNames[currentMetric], 20, 48);
// 图例
let legendY = 80;
for (let i = 0; i < 4; i++) {
let mc = metricColors[i];
if (i === currentMetric) {
fill(mc[0], mc[1], mc[2], 255);
rect(20, legendY, 12, 12, 2);
fill(255);
textSize(13);
text(metricNames[i], 38, legendY);
} else {
fill(mc[0], mc[1], mc[2], 80);
rect(20, legendY, 12, 12, 2);
fill(150);
textSize(13);
text(metricNames[i], 38, legendY);
}
legendY += 22;
}
// 色阶条
let barX = 20, barY = height - 50, barW = 200, barH = 12;
let mc = metricColors[currentMetric];
for (let i = 0; i < barW; i++) {
let t = i / barW;
fill(mc[0] * t, mc[1] * t, mc[2] * t);
noStroke();
rect(barX + i, barY, 1, barH);
}
fill(255, 255, 255, 120);
textSize(11);
text('低', barX, barY + barH + 14);
textAlign(RIGHT, TOP);
text('高', barX + barW, barY + barH + 14);
// 建筑数量
textAlign(RIGHT, TOP);
fill(255, 255, 255, 100);
textSize(12);
text('建筑: ' + buildings.length + ' | 粒子: ' + particles.length, width - 20, 20);
text('视图: ' + (viewMode === 0 ? '俯视图' : '等轴测'), width - 20, 38);
}
function drawTooltip(b) {
let tx = mouseX + 15;
let ty = mouseY - 10;
let tw = 160;
let th = 100;
if (tx + tw > width) tx = mouseX - tw - 15;
if (ty + th > height) ty = mouseY - th - 10;
fill(20, 20, 40, 220);
stroke(80, 80, 120);
strokeWeight(1);
rect(tx, ty, tw, th, 6);
noStroke();
fill(255);
textSize(13);
textAlign(LEFT, TOP);
text(b.label, tx + 10, ty + 8);
fill(180);
textSize(11);
let keys = ['人口密度', '绿化率', '容积率', '交通便利'];
let vals = [b.metrics.pop, b.metrics.green, b.metrics.far, b.metrics.traffic];
let units = ['人/hm²', '%', '', '分'];
for (let i = 0; i < 4; i++) {
let mc = metricColors[i];
fill(mc[0], mc[1], mc[2], i === currentMetric ? 255 : 120);
text(keys[i] + ': ' + (i === 1 ? vals[i].toFixed(0) : vals[i].toFixed(1)) + units[i], tx + 10, ty + 30 + i * 17);
}
}
function mousePressed() {
currentMetric = (currentMetric + 1) % 4;
}
function keyPressed() {
if (key === ' ') {
viewMode = (viewMode + 1) % 2;
}
}
function mouseDragged() {
targetCamX += mouseX - pmouseX;
targetCamY += mouseY - pmouseY;
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
</script>
</body>
</html>
+195
View File
@@ -0,0 +1,195 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>国土空间规划课程智能体</title>
<script src="https://cdn.jsdelivr.net/npm/p5@1.9.4/lib/p5.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');
* { margin: 0; padding: 0; box-sizing: border-box; }
body { overflow: hidden; background: #0a0a1a; font-family: 'Noto Sans SC', system-ui, sans-serif; }
canvas { display: block; position: fixed; top: 0; left: 0; z-index: 0; }
#overlay {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
z-index: 1; pointer-events: none;
display: flex; flex-direction: column; justify-content: center; align-items: center;
}
#title {
font-size: 48px; font-weight: 700; color: white;
text-shadow: 0 0 40px rgba(100, 140, 255, 0.4);
margin-bottom: 12px; letter-spacing: 4px;
}
#subtitle {
font-size: 18px; font-weight: 300; color: rgba(180, 200, 255, 0.7);
margin-bottom: 40px; letter-spacing: 2px;
}
#tagline {
font-size: 14px; color: rgba(140, 160, 220, 0.5);
letter-spacing: 1px;
}
#info {
position: fixed; bottom: 20px; left: 50%;
transform: translateX(-50%);
color: rgba(255,255,255,0.3);
font-size: 12px; z-index: 2;
pointer-events: none;
}
</style>
</head>
<body>
<div id="overlay">
<div id="title">国土空间规划课程智能体</div>
<div id="subtitle">基于大模型的智能问答系统</div>
<div id="tagline">哈尔滨工业大学建筑与设计学院</div>
</div>
<div id="info">移动鼠标与知识网络互动</div>
<script>
const keywords = [
'容积率', '建筑密度', '绿地率', '控规', '总规', '详规',
'用地性质', '红线', '蓝线', '绿线', '紫线', '黄线',
'城市更新', '国土空间', '双评价', '三区三线',
'生态保护', '耕地保护', '城镇开发', '用途管制',
'空间结构', '交通规划', '基础设施', '公共服务',
'人口预测', '用地布局', '天际线', '风环境',
'海绵城市', '韧性城市', '智慧城市', '碳中和'
];
let nodes = [];
let nodeCount;
let connectDist = 150;
function setup() {
createCanvas(windowWidth, windowHeight);
nodeCount = min(floor(width * height / 12000), 80);
for (let i = 0; i < nodeCount; i++) {
nodes.push(createNode());
}
}
function createNode() {
let kw = random(keywords);
return {
x: random(width),
y: random(height),
vx: random(-0.3, 0.3),
vy: random(-0.3, 0.3),
size: textWidth(kw) || kw.length * 14,
baseSize: random(3, 6),
keyword: kw,
showText: random() > 0.5,
hue: random(200, 280),
phase: random(TWO_PI),
textAlpha: random() > 0.6 ? random(60, 150) : 0,
};
}
function draw() {
background(10, 10, 26, 30);
// 渐变背景(每帧微量覆盖)
noStroke();
fill(10, 10, 26, 25);
rect(0, 0, width, height);
// 绘制连线
for (let i = 0; i < nodes.length; i++) {
for (let j = i + 1; j < nodes.length; j++) {
let d = dist(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y);
if (d < connectDist) {
let alpha = map(d, 0, connectDist, 60, 0);
let h = (nodes[i].hue + nodes[j].hue) / 2;
stroke(h, 60, 200, alpha);
strokeWeight(0.8);
line(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y);
}
}
}
// 鼠标吸引线
for (let n of nodes) {
let d = dist(mouseX, mouseY, n.x, n.y);
if (d < 200) {
let alpha = map(d, 0, 200, 80, 0);
stroke(220, 180, 255, alpha);
strokeWeight(1);
line(mouseX, mouseY, n.x, n.y);
}
}
// 更新和绘制节点
for (let n of nodes) {
// 鼠标交互
let dm = dist(mouseX, mouseY, n.x, n.y);
if (dm < 180) {
let force = map(dm, 0, 180, 0.5, 0);
let angle = atan2(n.y - mouseY, n.x - mouseX);
n.vx += cos(angle) * force * 0.05;
n.vy += sin(angle) * force * 0.05;
}
// 运动
n.x += n.vx;
n.y += n.vy;
// 摩擦力
n.vx *= 0.99;
n.vy *= 0.99;
// 添加微小随机运动
n.vx += random(-0.02, 0.02);
n.vy += random(-0.02, 0.02);
// 边界
if (n.x < 0) { n.x = 0; n.vx *= -1; }
if (n.x > width) { n.x = width; n.vx *= -1; }
if (n.y < 0) { n.y = 0; n.vy *= -1; }
if (n.y > height) { n.y = height; n.vy *= -1; }
// 脉动效果
let pulse = sin(frameCount * 0.02 + n.phase) * 0.3 + 0.7;
// 绘制光晕
noStroke();
let glowAlpha = 20 * pulse;
fill(n.hue, 50, 200, glowAlpha);
ellipse(n.x, n.y, n.baseSize * 8, n.baseSize * 8);
fill(n.hue, 50, 200, glowAlpha * 1.5);
ellipse(n.x, n.y, n.baseSize * 4, n.baseSize * 4);
// 绘制节点
let nodeAlpha = (dm < 180) ? map(dm, 0, 180, 255, 120) : 120 * pulse;
fill(n.hue, 60, 240, nodeAlpha);
ellipse(n.x, n.y, n.baseSize * 2, n.baseSize * 2);
// 绘制关键词文字
if (n.textAlpha > 0) {
let ta = n.textAlpha * pulse;
if (dm < 180) ta = min(ta + 80, 220);
fill(n.hue, 30, 230, ta);
noStroke();
textAlign(CENTER, CENTER);
textSize(12);
textFont('Noto Sans SC');
text(n.keyword, n.x, n.y - n.baseSize * 2 - 8);
}
}
// 鼠标光标光晕
noStroke();
fill(230, 200, 255, 8);
ellipse(mouseX, mouseY, 200, 200);
fill(230, 200, 255, 15);
ellipse(mouseX, mouseY, 80, 80);
fill(230, 200, 255, 30);
ellipse(mouseX, mouseY, 20, 20);
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
</script>
</body>
</html>
+128
View File
@@ -0,0 +1,128 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>p5.js 互动图形 Demo</title>
<script src="https://cdn.jsdelivr.net/npm/p5@1.9.4/lib/p5.min.js"></script>
<style>
body { margin: 0; overflow: hidden; background: #000; }
canvas { display: block; }
#info {
position: fixed; bottom: 20px; left: 50%;
transform: translateX(-50%);
color: rgba(255,255,255,0.6);
font-family: system-ui, sans-serif;
font-size: 14px;
pointer-events: none;
text-align: center;
}
</style>
</head>
<body>
<div id="info">移动鼠标生成图形 | 点击产生爆炸 | 按空格清空画布</div>
<script>
let shapes = [];
let hueOffset = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
colorMode(HSB, 360, 100, 100, 100);
rectMode(CENTER);
}
function draw() {
background(0, 0, 0, 5);
for (let i = shapes.length - 1; i >= 0; i--) {
let s = shapes[i];
s.angle += s.rotSpeed;
s.size += s.growSpeed;
s.alpha -= s.fadeSpeed;
if (s.alpha <= 0) {
shapes.splice(i, 1);
continue;
}
push();
translate(s.x, s.y);
rotate(s.angle);
noStroke();
fill(s.hue, s.sat, s.bright, s.alpha);
if (s.type === 0) {
ellipse(0, 0, s.size, s.size);
} else if (s.type === 1) {
triangle(
0, -s.size / 2,
-s.size / 2, s.size / 2,
s.size / 2, s.size / 2
);
} else {
rect(0, 0, s.size, s.size);
}
pop();
}
hueOffset = (hueOffset + 0.5) % 360;
}
function mouseMoved() {
let hue = (hueOffset + random(-20, 20) + 360) % 360;
shapes.push({
x: mouseX + random(-15, 15),
y: mouseY + random(-15, 15),
size: random(10, 30),
angle: random(TWO_PI),
rotSpeed: random(-0.05, 0.05),
growSpeed: random(0.3, 1.2),
fadeSpeed: random(0.8, 2.0),
alpha: 80,
hue: hue,
sat: random(60, 90),
bright: random(70, 100),
type: floor(random(3))
});
if (shapes.length > 500) {
shapes.splice(0, 50);
}
}
function mousePressed() {
let count = floor(random(15, 25));
for (let i = 0; i < count; i++) {
let angle = random(TWO_PI);
let dist = random(20, 120);
let hue = (hueOffset + random(-40, 40) + 360) % 360;
shapes.push({
x: mouseX + cos(angle) * dist,
y: mouseY + sin(angle) * dist,
size: random(8, 25),
angle: angle,
rotSpeed: random(-0.08, 0.08),
growSpeed: random(0.5, 2.0),
fadeSpeed: random(1.0, 2.5),
alpha: 90,
hue: hue,
sat: random(70, 100),
bright: random(80, 100),
type: floor(random(3))
});
}
}
function keyPressed() {
if (key === ' ') {
shapes = [];
background(0);
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 517 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 517 KiB

+192
View File
@@ -0,0 +1,192 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useAuthStore } from "@/store/auth";
import { BookOpen, Eye, EyeOff, Loader2 } from "lucide-react";
import { FlickeringGrid } from "@/components/magicui/flickering-grid";
import { ThemeToggle } from "@/components/ui/theme-toggle";
const loginSchema = z.object({
username: z.string().min(1, "用户名不能为空"),
password: z.string().min(1, "密码不能为空"),
});
type LoginForm = z.infer<typeof loginSchema>;
export default function LoginPage() {
const [showPassword, setShowPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const { login, error, clearError } = useAuthStore();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<LoginForm>({
resolver: zodResolver(loginSchema),
});
const onSubmit = async (data: LoginForm) => {
setIsLoading(true);
clearError();
const success = await login(data);
if (success) {
// 登录成功后回到主页,让用户看到无缝过渡效果
router.push("/");
}
setIsLoading(false);
};
return (
<div className="min-h-screen bg-app relative overflow-hidden">
{/* 背景动画 */}
<FlickeringGrid
className="absolute inset-0 z-0 [mask-image:radial-gradient(800px_circle_at_center,white,transparent)]"
squareSize={4}
gridGap={4}
color="#60A5FA"
maxOpacity={0.1}
flickerChance={0.05}
/>
{/* 主题切换按钮 */}
<div className="absolute top-4 right-4 z-10">
<ThemeToggle />
</div>
<div className="relative z-10 flex items-center justify-center min-h-screen p-4">
<div className="w-full max-w-md">
{/* Logo和标题 */}
<div className="text-center mb-8">
<Link
href="/"
className="flex items-center justify-center space-x-3 mb-6 group cursor-pointer transition-opacity hover:opacity-80"
>
<div className="w-12 h-12 bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg group-hover:shadow-xl transition-shadow">
<BookOpen className="w-7 h-7 text-white" />
</div>
<span className="text-2xl font-bold">
</span>
</Link>
<p className="text-muted-foreground text-lg"></p>
</div>
{/* 登录表单 */}
<Card className="backdrop-blur-sm bg-card/80 border-border/50 shadow-xl">
<CardHeader>
<CardTitle className="text-2xl"></CardTitle>
<CardDescription>
访
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
{/* 错误提示 */}
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 用户名输入 */}
<div className="space-y-2">
<Label htmlFor="username"></Label>
<Input
id="username"
type="text"
placeholder="请输入用户名"
{...register("username")}
disabled={isLoading}
/>
{errors.username && (
<p className="text-sm text-red-600">{errors.username.message}</p>
)}
</div>
{/* 密码输入 */}
<div className="space-y-2">
<Label htmlFor="password"></Label>
<div className="relative">
<Input
id="password"
type={showPassword ? "text" : "password"}
placeholder="请输入密码"
{...register("password")}
disabled={isLoading}
/>
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
onClick={() => setShowPassword(!showPassword)}
disabled={isLoading}
>
{showPassword ? (
<EyeOff className="w-4 h-4" />
) : (
<Eye className="w-4 h-4" />
)}
</button>
</div>
{errors.password && (
<p className="text-sm text-red-600">{errors.password.message}</p>
)}
</div>
{/* 登录按钮 */}
<Button
type="submit"
className="w-full"
disabled={isLoading}
>
{isLoading ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
...
</>
) : (
"登录"
)}
</Button>
</form>
{/* 注册链接 */}
<div className="mt-6 text-center">
<p className="text-sm text-gray-600">
{" "}
<Link
href="/register"
className="text-blue-600 hover:text-blue-800 font-medium"
>
</Link>
</p>
</div>
</CardContent>
</Card>
{/* 快速登录提示 */}
<div className="mt-6 text-center">
<p className="text-xs text-muted-foreground">
使
</p>
</div>
</div>
</div>
</div>
);
}
+265
View File
@@ -0,0 +1,265 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useAuthStore } from "@/store/auth";
import { BookOpen, Eye, EyeOff, Loader2, CheckCircle } from "lucide-react";
import { FlickeringGrid } from "@/components/magicui/flickering-grid";
import { ThemeToggle } from "@/components/ui/theme-toggle";
const registerSchema = z.object({
username: z.string().min(3, "用户名至少3个字符").max(20, "用户名最多20个字符"),
email: z.string().email("请输入有效的邮箱地址"),
password: z.string().min(6, "密码至少6个字符"),
confirmPassword: z.string(),
full_name: z.string().optional(),
}).refine((data) => data.password === data.confirmPassword, {
message: "密码不匹配",
path: ["confirmPassword"],
});
type RegisterForm = z.infer<typeof registerSchema>;
export default function RegisterPage() {
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const { register: registerUser, error, clearError } = useAuthStore();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<RegisterForm>({
resolver: zodResolver(registerSchema),
});
const onSubmit = async (data: RegisterForm) => {
setIsLoading(true);
clearError();
const success = await registerUser({
username: data.username,
email: data.email,
password: data.password,
full_name: data.full_name,
});
if (success) {
router.push("/chat");
}
setIsLoading(false);
};
return (
<div className="min-h-screen bg-app relative overflow-hidden">
{/* 背景动画 */}
<FlickeringGrid
className="absolute inset-0 z-0 [mask-image:radial-gradient(800px_circle_at_center,white,transparent)]"
squareSize={4}
gridGap={4}
color="#60A5FA"
maxOpacity={0.1}
flickerChance={0.05}
/>
{/* 主题切换按钮 */}
<div className="absolute top-4 right-4 z-10">
<ThemeToggle />
</div>
<div className="relative z-10 flex items-center justify-center min-h-screen p-4">
<div className="w-full max-w-md">
{/* Logo和标题 */}
<div className="text-center mb-8">
<Link
href="/"
className="flex items-center justify-center space-x-3 mb-6 group cursor-pointer transition-opacity hover:opacity-80"
>
<div className="w-12 h-12 bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg group-hover:shadow-xl transition-shadow">
<BookOpen className="w-7 h-7 text-white" />
</div>
<span className="text-2xl font-bold">
</span>
</Link>
<p className="text-muted-foreground text-lg"></p>
</div>
{/* 注册表单 */}
<Card className="backdrop-blur-sm bg-card/80 border-border/50 shadow-xl">
<CardHeader>
<CardTitle className="text-2xl"></CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
{/* 错误提示 */}
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 用户名输入 */}
<div className="space-y-2">
<Label htmlFor="username"> *</Label>
<Input
id="username"
type="text"
placeholder="请输入用户名"
{...register("username")}
disabled={isLoading}
/>
{errors.username && (
<p className="text-sm text-red-600">{errors.username.message}</p>
)}
</div>
{/* 邮箱输入 */}
<div className="space-y-2">
<Label htmlFor="email"> *</Label>
<Input
id="email"
type="email"
placeholder="请输入邮箱地址"
{...register("email")}
disabled={isLoading}
/>
{errors.email && (
<p className="text-sm text-red-600">{errors.email.message}</p>
)}
</div>
{/* 姓名输入 */}
<div className="space-y-2">
<Label htmlFor="full_name"></Label>
<Input
id="full_name"
type="text"
placeholder="请输入您的姓名"
{...register("full_name")}
disabled={isLoading}
/>
{errors.full_name && (
<p className="text-sm text-red-600">{errors.full_name.message}</p>
)}
</div>
{/* 密码输入 */}
<div className="space-y-2">
<Label htmlFor="password"> *</Label>
<div className="relative">
<Input
id="password"
type={showPassword ? "text" : "password"}
placeholder="请输入密码"
{...register("password")}
disabled={isLoading}
/>
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
onClick={() => setShowPassword(!showPassword)}
disabled={isLoading}
>
{showPassword ? (
<EyeOff className="w-4 h-4" />
) : (
<Eye className="w-4 h-4" />
)}
</button>
</div>
{errors.password && (
<p className="text-sm text-red-600">{errors.password.message}</p>
)}
</div>
{/* 确认密码输入 */}
<div className="space-y-2">
<Label htmlFor="confirmPassword"> *</Label>
<div className="relative">
<Input
id="confirmPassword"
type={showConfirmPassword ? "text" : "password"}
placeholder="请再次输入密码"
{...register("confirmPassword")}
disabled={isLoading}
/>
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
disabled={isLoading}
>
{showConfirmPassword ? (
<EyeOff className="w-4 h-4" />
) : (
<Eye className="w-4 h-4" />
)}
</button>
</div>
{errors.confirmPassword && (
<p className="text-sm text-red-600">{errors.confirmPassword.message}</p>
)}
</div>
{/* 注册按钮 */}
<Button
type="submit"
className="w-full"
disabled={isLoading}
>
{isLoading ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
...
</>
) : (
<>
<CheckCircle className="w-4 h-4 mr-2" />
</>
)}
</Button>
</form>
{/* 登录链接 */}
<div className="mt-6 text-center">
<p className="text-sm text-gray-600">
{" "}
<Link
href="/login"
className="text-blue-600 hover:text-blue-800 font-medium"
>
</Link>
</p>
</div>
</CardContent>
</Card>
{/* 注册提示 */}
<div className="mt-6 text-center">
<p className="text-xs text-muted-foreground">
</p>
</div>
</div>
</div>
</div>
);
}
+419
View File
@@ -0,0 +1,419 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
BarChart3,
TrendingUp,
BookOpen,
MessageSquare,
FileText,
Calendar,
Target,
Lightbulb,
Download,
Share2
} from "lucide-react";
import LoadingSpinner from "@/components/ui/loading-spinner";
import { analyticsAPI } from "@/lib/api";
interface Statistics {
total_sessions: number;
total_messages: number;
total_documents: number;
active_days: number;
popular_questions: Array<{
question: string;
count: number;
category: string;
}>;
knowledge_coverage: Array<{
topic: string;
coverage: number;
questions: number;
}>;
learning_trends: Array<{
date: string;
messages: number;
sessions: number;
}>;
}
interface LearningReport {
user_id: number;
total_questions: number;
topics_covered: string[];
learning_progress: number;
recommendations: string[];
study_time: number;
knowledge_gaps: string[];
}
export default function AnalyticsPage() {
const router = useRouter();
const { isAuthenticated, isLoading: authLoading } = useAuthStore();
const [statistics, setStatistics] = useState<Statistics | null>(null);
const [learningReport, setLearningReport] = useState<LearningReport | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [activeTab, setActiveTab] = useState("overview");
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
return;
}
if (isAuthenticated) {
loadAnalyticsData();
}
}, [isAuthenticated, authLoading, router]);
const loadAnalyticsData = async () => {
try {
setIsLoading(true);
// 调用真实API获取完整分析数据
const response = await analyticsAPI.getFullAnalytics();
if (response.success) {
const { statistics, learning_trends, popular_questions, knowledge_coverage, learning_report } = response.data;
// 构建Statistics对象
const statisticsData: Statistics = {
total_sessions: statistics.total_sessions,
total_messages: statistics.total_messages,
total_documents: statistics.total_documents,
active_days: statistics.active_days,
popular_questions: popular_questions,
knowledge_coverage: knowledge_coverage,
learning_trends: learning_trends
};
// 构建LearningReport对象
const learningReportData: LearningReport = {
user_id: learning_report.user_id,
total_questions: learning_report.total_questions,
topics_covered: learning_report.topics_covered,
learning_progress: learning_report.learning_progress,
recommendations: learning_report.recommendations,
study_time: learning_report.study_time,
knowledge_gaps: learning_report.knowledge_gaps
};
setStatistics(statisticsData);
setLearningReport(learningReportData);
} else {
throw new Error("API返回失败");
}
} catch (err) {
console.error("加载分析数据失败:", err);
// 如果API调用失败,使用模拟数据作为后备
const mockStatistics: Statistics = {
total_sessions: 0,
total_messages: 0,
total_documents: 0,
active_days: 0,
popular_questions: [],
knowledge_coverage: [],
learning_trends: []
};
const mockLearningReport: LearningReport = {
user_id: 0,
total_questions: 0,
topics_covered: [],
learning_progress: 0,
recommendations: ["请先开始学习以获取分析数据"],
study_time: 0,
knowledge_gaps: []
};
setStatistics(mockStatistics);
setLearningReport(mockLearningReport);
} finally {
setIsLoading(false);
}
};
const formatTime = (minutes: number) => {
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return `${hours}小时${mins}分钟`;
};
if (authLoading || isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<LoadingSpinner size="lg" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<div className="min-h-screen bg-background">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* 页面头部 */}
<div className="mb-8">
<h1 className="text-3xl font-bold text-foreground mb-2"></h1>
<p className="text-muted-foreground"></p>
</div>
{/* 标签页 */}
<div className="flex space-x-1 mb-8">
{[
{ id: "overview", name: "总览", icon: BarChart3 },
{ id: "progress", name: "学习进度", icon: TrendingUp },
{ id: "knowledge", name: "知识图谱", icon: BookOpen }
].map((tab) => (
<Button
key={tab.id}
variant={activeTab === tab.id ? "default" : "outline"}
onClick={() => setActiveTab(tab.id)}
className="flex items-center"
>
<tab.icon className="w-4 h-4 mr-2" />
{tab.name}
</Button>
))}
</div>
{/* 总览标签页 */}
{activeTab === "overview" && statistics && (
<div className="space-y-6">
{/* 关键指标 */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<Card>
<CardContent className="p-6">
<div className="flex items-center">
<MessageSquare className="w-8 h-8 text-blue-600" />
<div className="ml-4">
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold text-foreground">{statistics.total_sessions}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center">
<BookOpen className="w-8 h-8 text-green-600" />
<div className="ml-4">
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold text-foreground">{statistics.total_messages}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center">
<FileText className="w-8 h-8 text-purple-600" />
<div className="ml-4">
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold text-foreground">{statistics.total_documents}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center">
<Calendar className="w-8 h-8 text-orange-600" />
<div className="ml-4">
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold text-foreground">{statistics.active_days}</p>
</div>
</div>
</CardContent>
</Card>
</div>
{/* 知识覆盖度 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{statistics.knowledge_coverage.map((item, index) => (
<div key={index} className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-sm font-medium text-foreground">{item.topic}</span>
<span className="text-sm text-muted-foreground">{item.coverage}%</span>
</div>
<div className="w-full bg-muted rounded-full h-2">
<div
className="bg-blue-600 h-2 rounded-full transition-all duration-300"
style={{ width: `${item.coverage}%` }}
/>
</div>
<div className="flex justify-between text-xs text-muted-foreground">
<span>{item.questions} </span>
<span>{item.coverage}% </span>
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* 热门问题 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3">
{statistics.popular_questions.map((item, index) => (
<div key={index} className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div className="flex-1">
<p className="text-sm font-medium text-foreground">{item.question}</p>
<p className="text-xs text-muted-foreground">{item.category}</p>
</div>
<div className="text-sm font-medium text-blue-600">{item.count} </div>
</div>
))}
</div>
</CardContent>
</Card>
</div>
)}
{/* 学习进度标签页 */}
{activeTab === "progress" && learningReport && (
<div className="space-y-6">
{/* 学习进度 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-lg font-medium text-foreground"></span>
<span className="text-2xl font-bold text-blue-600">{learningReport.learning_progress}%</span>
</div>
<div className="w-full bg-muted rounded-full h-4">
<div
className="bg-gradient-to-r from-blue-500 to-purple-600 h-4 rounded-full transition-all duration-500"
style={{ width: `${learningReport.learning_progress}%` }}
/>
</div>
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-muted-foreground"></span>
<span className="font-medium text-foreground">{formatTime(learningReport.study_time)}</span>
</div>
<div>
<span className="text-muted-foreground"></span>
<span className="font-medium text-foreground">{learningReport.total_questions}</span>
</div>
</div>
</div>
</CardContent>
</Card>
{/* 学习建议 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<Lightbulb className="w-5 h-5 mr-2" />
</CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3">
{learningReport.recommendations.map((recommendation, index) => (
<div key={index} className="flex items-start space-x-3 p-3 bg-blue-500/10 dark:bg-blue-500/20 rounded-lg">
<div className="w-2 h-2 bg-blue-600 rounded-full mt-2 flex-shrink-0" />
<p className="text-sm text-foreground">{recommendation}</p>
</div>
))}
</div>
</CardContent>
</Card>
{/* 知识缺口 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<Target className="w-5 h-5 mr-2" />
</CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3">
{learningReport.knowledge_gaps.map((gap, index) => (
<div key={index} className="flex items-start space-x-3 p-3 bg-orange-500/10 dark:bg-orange-500/20 rounded-lg">
<div className="w-2 h-2 bg-orange-600 rounded-full mt-2 flex-shrink-0" />
<p className="text-sm text-foreground">{gap}</p>
</div>
))}
</div>
</CardContent>
</Card>
</div>
)}
{/* 知识图谱标签页 */}
{activeTab === "knowledge" && (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="text-center py-12">
<BookOpen className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-medium text-foreground mb-2"></h3>
<p className="text-muted-foreground mb-4">
</p>
<Button variant="outline">
</Button>
</div>
</CardContent>
</Card>
</div>
)}
{/* 操作按钮 */}
<div className="flex justify-end space-x-4 mt-8">
<Button variant="outline" className="flex items-center">
<Download className="w-4 h-4 mr-2" />
</Button>
<Button variant="outline" className="flex items-center">
<Share2 className="w-4 h-4 mr-2" />
</Button>
</div>
</div>
</div>
);
}
+59
View File
@@ -0,0 +1,59 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import { useChatStore } from "@/store/chat";
import ChatInterface from "@/components/chat/chat-interface";
import Sidebar from "@/components/chat/sidebar";
import MobileNav from "@/components/layout/mobile-nav";
import LoadingSpinner from "@/components/ui/loading-spinner";
export default function ChatPage() {
const router = useRouter();
const { isAuthenticated, user, isLoading: authLoading } = useAuthStore();
const { loadSessions, isLoading: chatLoading } = useChatStore();
const [isInitialized, setIsInitialized] = useState(false);
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
return;
}
if (isAuthenticated && !isInitialized) {
// 加载聊天会话
loadSessions();
setIsInitialized(true);
}
}, [isAuthenticated, authLoading, isInitialized, router, loadSessions]);
if (authLoading || chatLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<LoadingSpinner size="lg" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<div className="h-[calc(100vh-4rem)] bg-background flex">
{/* 侧边栏 */}
<div className="w-80 border-r bg-card/50 flex-shrink-0">
<Sidebar />
</div>
{/* 主聊天区域 */}
<div className="flex-1 flex flex-col min-w-0">
<ChatInterface />
</div>
{/* 移动端导航 */}
<MobileNav />
</div>
);
}
+289
View File
@@ -0,0 +1,289 @@
"use client";
import { useEffect, useState } from "react";
// 禁用静态生成
export const dynamic = 'force-dynamic';
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import MobileNav from "@/components/layout/mobile-nav";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import {
Loader2,
BookOpen,
GraduationCap,
Lightbulb,
Target,
Network,
List
} from "lucide-react";
import { courseContentAPI } from "@/lib/api";
import { BookStructure } from "@/types";
import dynamicImport from "next/dynamic";
import NodeDetailDialog from "@/components/course-content/node-detail-dialog";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { FileText, ChevronRight } from "lucide-react";
// 动态导入 KnowledgeGraph 组件,禁用 SSR
const KnowledgeGraph = dynamicImport(
() => import("@/components/course-content/knowledge-graph"),
{ ssr: false }
);
export default function CourseContentPage() {
const router = useRouter();
const { isAuthenticated, isLoading: authLoading } = useAuthStore();
const [bookStructure, setBookStructure] = useState<BookStructure | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<'graph' | 'list'>('graph');
const [selectedNode, setSelectedNode] = useState<{
type: 'chapter' | 'section' | 'subsection';
id: number;
title: string;
subsections?: Array<{ id: number; title: string }>;
} | null>(null);
const [isDialogOpen, setIsDialogOpen] = useState(false);
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
return;
}
if (isAuthenticated) {
loadCourseContent();
}
}, [isAuthenticated, authLoading, router]);
const loadCourseContent = async () => {
try {
setIsLoading(true);
setError(null);
const structure = await courseContentAPI.getCourseContent();
console.log("加载的书籍结构:", structure);
console.log("章节数量:", structure?.chapters?.length || 0);
if (structure?.chapters) {
structure.chapters.forEach((chapter, index) => {
console.log(`章节 ${index + 1}:`, chapter.title, "节数:", chapter.sections?.length || 0);
});
}
setBookStructure(structure);
} catch (err) {
console.error("加载课程内容失败:", err);
setError("加载课程内容失败: " + (err instanceof Error ? err.message : String(err)));
} finally {
setIsLoading(false);
}
};
if (authLoading || isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<div className="min-h-screen bg-app pb-16 lg:pb-0">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* 页面头部 */}
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center space-x-3">
<div className="w-12 h-12 bg-gradient-to-r from-blue-600 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
<GraduationCap className="w-6 h-6 text-white" />
</div>
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground"></p>
</div>
</div>
{/* 视图切换 */}
<Tabs value={viewMode} onValueChange={(v) => setViewMode(v as 'graph' | 'list')}>
<TabsList>
<TabsTrigger value="graph" className="flex items-center space-x-2">
<Network className="w-4 h-4" />
<span className="hidden sm:inline"></span>
</TabsTrigger>
<TabsTrigger value="list" className="flex items-center space-x-2">
<List className="w-4 h-4" />
<span className="hidden sm:inline"></span>
</TabsTrigger>
</TabsList>
</Tabs>
</div>
</div>
{/* 错误提示 */}
{error && (
<Alert variant="destructive" className="mb-6">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 课程内容展示 */}
{!bookStructure ? (
<Card className="backdrop-blur-sm bg-card/80 border-border/50 shadow-xl">
<CardContent className="text-center py-12">
<BookOpen className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-medium mb-2"></h3>
<p className="text-muted-foreground">
</p>
</CardContent>
</Card>
) : (
<>
{/* 知识图谱视图 */}
{viewMode === 'graph' && (
<div className="w-full h-[calc(100vh-250px)] min-h-[600px] lg:min-h-[700px] rounded-lg border border-border bg-background overflow-hidden">
<KnowledgeGraph bookStructure={bookStructure} />
</div>
)}
{/* 列表视图 */}
{viewMode === 'list' && (
<div className="space-y-6">
{bookStructure.chapters.map((chapter) => (
<Card
key={chapter.id}
className="hover:shadow-lg transition-shadow backdrop-blur-sm bg-card/80 border-border/50"
>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-xl mb-3 flex items-center space-x-2">
<BookOpen className="w-5 h-5 text-blue-600" />
<span>{chapter.chapter_number} {chapter.title}</span>
</CardTitle>
<Button
variant="outline"
size="sm"
onClick={() => {
setSelectedNode({
type: 'chapter',
id: chapter.id,
title: chapter.title,
});
setIsDialogOpen(true);
}}
className="flex items-center space-x-2"
>
<FileText className="w-4 h-4" />
<span></span>
</Button>
</div>
</CardHeader>
<CardContent>
<Accordion type="single" collapsible className="w-full">
{chapter.sections.map((section) => (
<AccordionItem key={section.id} value={`section-${section.id}`}>
<div className="flex items-center justify-between w-full">
<AccordionTrigger className="text-base font-medium flex-1">
<span>{section.title}</span>
</AccordionTrigger>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
setSelectedNode({
type: 'section',
id: section.id,
title: section.title,
subsections: section.subsections,
});
setIsDialogOpen(true);
}}
className="mr-2 flex items-center space-x-1"
>
<FileText className="w-4 h-4" />
<span className="text-xs"></span>
</Button>
</div>
<AccordionContent>
<div className="pt-2 pl-4 space-y-2">
{section.subsections.length === 0 ? (
<p className="text-sm text-muted-foreground"></p>
) : (
<>
<p className="text-sm font-medium text-foreground mb-2">
({section.subsections.length} )
</p>
<ul className="space-y-2">
{section.subsections.map((subsection) => (
<li
key={subsection.id}
className="flex items-center justify-between group"
>
<div className="flex items-start space-x-2 flex-1">
<span className="w-1.5 h-1.5 rounded-full bg-blue-600 mt-2 flex-shrink-0" />
<span className="flex-1 text-sm text-muted-foreground">{subsection.title}</span>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => {
setSelectedNode({
type: 'subsection',
id: subsection.id,
title: subsection.title,
});
setIsDialogOpen(true);
}}
className="opacity-0 group-hover:opacity-100 transition-opacity ml-2 flex items-center space-x-1"
>
<FileText className="w-3 h-3" />
<span className="text-xs"></span>
</Button>
</li>
))}
</ul>
</>
)}
</div>
</AccordionContent>
</AccordionItem>
))}
</Accordion>
</CardContent>
</Card>
))}
</div>
)}
</>
)}
</div>
{/* 节点详情对话框 */}
{selectedNode && (
<NodeDetailDialog
open={isDialogOpen}
onOpenChange={setIsDialogOpen}
nodeType={selectedNode.type === 'subsection' ? 'section' : selectedNode.type}
nodeId={selectedNode.type === 'subsection' ? 0 : selectedNode.id} // nodeId is not used for direct subsection display
nodeTitle={selectedNode.title}
subsections={selectedNode.type === 'section' ? selectedNode.subsections : undefined}
subsectionId={selectedNode.type === 'subsection' ? selectedNode.id : undefined}
/>
)}
{/* 移动端导航 */}
<MobileNav />
</div>
);
}
+124
View File
@@ -0,0 +1,124 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { MessageSquare, Loader2, MessageCircle } from "lucide-react";
import { forumAPI } from "@/lib/api";
import type { ForumCategory, ForumPostSummary } from "@/types";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
export default function ForumHomePage() {
const [categories, setCategories] = useState<ForumCategory[]>([]);
const [categoryPosts, setCategoryPosts] = useState<Record<number, ForumPostSummary[]>>({});
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const loadCategories = async () => {
try {
setIsLoading(true);
const data = await forumAPI.getCategories();
setCategories(data);
const postsEntries = await Promise.all(
data.map(async (category) => {
try {
const posts = await forumAPI.getPosts(category.id, 10);
return [category.id, posts] as const;
} catch (err) {
console.warn(`加载分类 ${category.name} 的帖子失败:`, err);
return [category.id, []] as const;
}
})
);
setCategoryPosts(Object.fromEntries(postsEntries));
setError(null);
} catch (err) {
const message = err instanceof Error ? err.message : "加载论坛数据失败";
setError(message);
} finally {
setIsLoading(false);
}
};
loadCategories();
}, []);
return (
<div className="mit-container py-10 space-y-6">
<div className="space-y-2">
<h1 className="text-3xl font-bold flex items-center gap-2">
<MessageSquare className="h-7 w-7 text-primary" />
</h1>
<p className="text-muted-foreground">
使
</p>
</div>
{isLoading ? (
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
...
</div>
) : error ? (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
) : (
<div className="grid gap-4 md:grid-cols-2">
{categories.map((category) => (
<Card key={category.id} className="flex flex-col">
<CardHeader>
<CardTitle>{category.name}</CardTitle>
{category.description && (
<CardDescription>{category.description}</CardDescription>
)}
</CardHeader>
<CardContent className="flex flex-col gap-4 h-full">
<div className="flex items-center justify-between text-sm text-muted-foreground">
<span>{category.post_count} </span>
<Button asChild size="sm" variant="ghost" className="px-2">
<Link href={`/forum/${category.id}`}></Link>
</Button>
</div>
<div className="flex-1 space-y-3 overflow-y-auto pr-1">
{categoryPosts[category.id] && categoryPosts[category.id].length > 0 ? (
categoryPosts[category.id].map((post) => (
<Link
key={post.id}
href={`/forum/post/${post.id}`}
className="block rounded-lg border border-border/60 hover:border-primary/50 hover:bg-muted/40 transition-colors"
>
<div className="px-3 py-2">
<div className="font-medium text-foreground line-clamp-1">
{post.title}
</div>
<div className="mt-1 flex items-center text-xs text-muted-foreground gap-2">
<span>{post.author_name}</span>
<span>·</span>
<span>{new Date(new Date(post.created_at).getTime() + 8 * 60 * 60 * 1000).toLocaleString()}</span>
<span>·</span>
<span>{post.reply_count} </span>
</div>
</div>
</Link>
))
) : (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<MessageCircle className="h-4 w-4" />
</div>
)}
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
);
}
+501
View File
@@ -0,0 +1,501 @@
"use client";
import { useEffect, useState, useRef } from "react";
import { useRouter, useParams } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import { Button } from "@/components/ui/button";
import MobileNav from "@/components/layout/mobile-nav";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Upload,
FileText,
Search,
Plus,
Trash2,
Eye,
CheckCircle,
Clock,
Loader2,
BookOpen,
ArrowLeft,
Settings
} from "lucide-react";
import { formatFileSize, formatDate } from "@/lib/utils";
import { knowledgeBaseAPI } from "@/lib/api";
import { KnowledgeBaseDetail, Document } from "@/types";
export default function KnowledgeBaseDetailPage() {
const router = useRouter();
const params = useParams();
const { isAuthenticated, isLoading: authLoading } = useAuthStore();
const [knowledgeBase, setKnowledgeBase] = useState<KnowledgeBaseDetail | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [error, setError] = useState<string | null>(null);
// 上传文档对话框状态
const [isUploadDialogOpen, setIsUploadDialogOpen] = useState(false);
const [uploadFiles, setUploadFiles] = useState<File[]>([]);
const [uploadTitle, setUploadTitle] = useState("");
const [uploadDescription, setUploadDescription] = useState("");
const [isUploading, setIsUploading] = useState(false);
const [uploadProgress, setUploadProgress] = useState<{[key: string]: number}>({});
const [uploadErrors, setUploadErrors] = useState<{[key: string]: string}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const knowledgeBaseId = params.id as string;
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
return;
}
if (isAuthenticated && knowledgeBaseId) {
loadKnowledgeBase();
}
}, [isAuthenticated, authLoading, knowledgeBaseId, router]);
const loadKnowledgeBase = async () => {
try {
setIsLoading(true);
setError(null);
const kb = await knowledgeBaseAPI.getKnowledgeBase(knowledgeBaseId);
setKnowledgeBase(kb);
} catch (err) {
console.error("加载知识库失败:", err);
setError("加载知识库失败");
} finally {
setIsLoading(false);
}
};
const handleFileUpload = async () => {
if (!uploadFiles.length || !knowledgeBase) return;
try {
setIsUploading(true);
setError(null);
setUploadProgress({});
setUploadErrors({});
const uploadPromises = uploadFiles.map(async (file, index) => {
const fileId = `${file.name}-${index}`;
try {
setUploadProgress(prev => ({ ...prev, [fileId]: 0 }));
await knowledgeBaseAPI.uploadDocument(
knowledgeBaseId,
file,
file.name.replace(/\.[^/.]+$/, ""), // Use filename as title
undefined // No description for batch uploads
);
setUploadProgress(prev => ({ ...prev, [fileId]: 100 }));
} catch (err) {
console.error(`上传文件 ${file.name} 失败:`, err);
setUploadErrors(prev => ({
...prev,
[fileId]: err instanceof Error ? err.message : "上传失败"
}));
}
});
await Promise.all(uploadPromises);
// 重新加载知识库详情
await loadKnowledgeBase();
// 重置表单并关闭对话框
setUploadFiles([]);
setUploadTitle("");
setUploadDescription("");
setIsUploadDialogOpen(false);
} catch (err) {
console.error("批量上传失败:", err);
setError("批量上传失败");
} finally {
setIsUploading(false);
}
};
const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files;
if (files && files.length > 0) {
const fileArray = Array.from(files);
setUploadFiles(fileArray);
if (!uploadTitle && fileArray.length === 1) {
setUploadTitle(fileArray[0].name.replace(/\.[^/.]+$/, ""));
}
}
};
const handleDeleteDocument = async (documentId: number) => {
if (!confirm("确定要删除这个文档吗?")) return;
try {
await knowledgeBaseAPI.deleteDocument(documentId.toString());
await loadKnowledgeBase();
} catch (err) {
console.error("删除文档失败:", err);
setError("删除文档失败");
}
};
const handleViewDocument = (doc: Document) => {
// Use the file_path from the document to construct the download URL
// Since backend serves static files from /uploads, we can use the file_path directly
const fileUrl = `/api/uploads/${doc.filename}`;
window.open(fileUrl, '_blank');
};
const filteredDocuments = knowledgeBase?.documents.filter(doc =>
doc.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
doc.filename.toLowerCase().includes(searchQuery.toLowerCase())
) || [];
if (authLoading || isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
if (!knowledgeBase) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<h2 className="text-2xl font-bold mb-2"></h2>
<p className="text-muted-foreground mb-4">访</p>
<Button onClick={() => router.push("/knowledge")}>
<ArrowLeft className="w-4 h-4 mr-2" />
</Button>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-app pb-16 lg:pb-0">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* 页面头部 */}
<div className="mb-8">
<div className="flex items-center space-x-4 mb-4">
<Button
variant="outline"
onClick={() => router.push("/knowledge")}
className="flex items-center"
>
<ArrowLeft className="w-4 h-4 mr-2" />
</Button>
<div className="flex items-center space-x-4">
<BookOpen className="w-8 h-8 text-blue-600" />
<div>
<h1 className="text-2xl font-bold mb-2">{knowledgeBase.name}</h1>
<p className="text-muted-foreground">
{knowledgeBase.description || "暂无描述"}
</p>
</div>
</div>
</div>
<div className="flex items-center space-x-6 text-sm text-muted-foreground">
<div className="flex items-center space-x-2">
<Clock className="w-4 h-4" />
<span>{formatDate(knowledgeBase.created_at)}</span>
</div>
<div className="flex items-center space-x-2">
<FileText className="w-4 h-4" />
<span> {knowledgeBase.document_count} </span>
</div>
</div>
</div>
{/* 错误提示 */}
{error && (
<Alert variant="destructive" className="mb-6">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 操作栏 */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6">
<div className="flex items-center space-x-4 mb-4 sm:mb-0">
{/* 上传文档按钮 */}
<Dialog
open={isUploadDialogOpen}
onOpenChange={(open) => {
setIsUploadDialogOpen(open);
if (open) {
// Reset file input when dialog opens
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
} else {
// Reset states when dialog closes
setUploadFiles([]);
setUploadTitle("");
setUploadDescription("");
setUploadProgress({});
setUploadErrors({});
}
}}
>
<DialogTrigger asChild>
<Button className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700">
<Plus className="w-4 h-4 mr-2" />
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>"{knowledgeBase.name}"</DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="file"></Label>
<Input
ref={fileInputRef}
id="file"
type="file"
accept=".pdf,.docx,.txt,.md"
multiple
onChange={handleFileSelect}
disabled={isUploading}
/>
</div>
{/* 已选择的文件列表 */}
{uploadFiles.length > 0 && (
<div>
<Label> ({uploadFiles.length} )</Label>
<div className="mt-2 space-y-2 max-h-40 overflow-y-auto">
{uploadFiles.map((file, index) => {
const fileId = `${file.name}-${index}`;
const progress = uploadProgress[fileId] || 0;
const error = uploadErrors[fileId];
return (
<div key={fileId} className="flex items-center justify-between p-2 border rounded-md">
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-2">
<FileText className="w-4 h-4 text-blue-600 flex-shrink-0" />
<span className="text-sm truncate">{file.name}</span>
<span className="text-xs text-muted-foreground">
({(file.size / 1024 / 1024).toFixed(2)} MB)
</span>
</div>
{error && (
<div className="text-xs text-red-600 mt-1">{error}</div>
)}
{progress > 0 && progress < 100 && (
<div className="w-full bg-gray-200 rounded-full h-1 mt-1">
<div
className="bg-blue-600 h-1 rounded-full transition-all duration-300"
style={{ width: `${progress}%` }}
/>
</div>
)}
{progress === 100 && !error && (
<div className="text-xs text-green-600 mt-1"> </div>
)}
</div>
<Button
variant="ghost"
size="sm"
onClick={() => {
setUploadFiles(prev => prev.filter((_, i) => i !== index));
}}
disabled={isUploading}
className="text-red-600 hover:text-red-700"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
);
})}
</div>
</div>
)}
{/* 单文件上传时显示标题和描述字段 */}
{uploadFiles.length <= 1 && (
<>
<div>
<Label htmlFor="title"></Label>
<Input
id="title"
value={uploadTitle}
onChange={(e) => setUploadTitle(e.target.value)}
placeholder="请输入文档标题"
disabled={isUploading}
/>
</div>
<div>
<Label htmlFor="description"></Label>
<Input
id="description"
value={uploadDescription}
onChange={(e) => setUploadDescription(e.target.value)}
placeholder="请输入文档描述"
disabled={isUploading}
/>
</div>
</>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setIsUploadDialogOpen(false)}
disabled={isUploading}
>
</Button>
<Button
onClick={handleFileUpload}
disabled={!uploadFiles.length || isUploading}
>
{isUploading ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
...
</>
) : (
<>
<Upload className="w-4 h-4 mr-2" />
{uploadFiles.length}
</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
<div className="flex items-center space-x-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input
placeholder="搜索文档..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 w-64"
/>
</div>
<div className="text-sm text-muted-foreground">
{filteredDocuments.length}
</div>
</div>
</div>
{/* 文档列表 */}
{filteredDocuments.length === 0 ? (
<Card className="backdrop-blur-sm bg-card/80 border-border/50 shadow-xl">
<CardContent className="text-center py-12">
<FileText className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-medium mb-2">
{searchQuery ? "没有找到匹配的文档" : "该知识库还没有文档"}
</h3>
<p className="text-muted-foreground mb-4">
{searchQuery ? "尝试使用其他关键词搜索" : "上传您的第一个文档到此知识库"}
</p>
{!searchQuery && (
<Button onClick={() => setIsUploadDialogOpen(true)}>
<Plus className="w-4 h-4 mr-2" />
</Button>
)}
</CardContent>
</Card>
) : (
<Card className="backdrop-blur-sm bg-card/80 border-border/50 shadow-xl">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[50px]"></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredDocuments.map((doc) => (
<TableRow key={doc.id}>
<TableCell>
{doc.is_processed ? (
<CheckCircle className="w-5 h-5 text-green-600" />
) : (
<Clock className="w-5 h-5 text-yellow-600" />
)}
</TableCell>
<TableCell className="font-medium">
<div className="flex items-center space-x-2">
<FileText className="w-4 h-4 text-blue-600" />
<span>{doc.title}</span>
</div>
</TableCell>
<TableCell className="text-muted-foreground max-w-xs truncate">
{doc.description || "暂无描述"}
</TableCell>
<TableCell>{doc.file_type}</TableCell>
<TableCell>{formatFileSize(doc.file_size)}</TableCell>
<TableCell>{formatDate(doc.created_at)}</TableCell>
<TableCell className="text-right">
<div className="flex justify-end space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => handleViewDocument(doc)}
>
<Eye className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDeleteDocument(doc.id)}
className="text-red-600 hover:text-red-700"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
)}
</div>
{/* 移动端导航 */}
<MobileNav />
</div>
);
}
+318
View File
@@ -0,0 +1,318 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import { Button } from "@/components/ui/button";
import MobileNav from "@/components/layout/mobile-nav";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import {
Upload,
FileText,
Search,
Plus,
Trash2,
Eye,
CheckCircle,
Clock,
Loader2,
BookOpen,
Settings,
FolderOpen
} from "lucide-react";
import { formatFileSize, formatDate } from "@/lib/utils";
import { knowledgeBaseAPI } from "@/lib/api";
import { KnowledgeBase } from "@/types";
export default function KnowledgePage() {
const router = useRouter();
const { isAuthenticated, isLoading: authLoading } = useAuthStore();
const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [error, setError] = useState<string | null>(null);
// 创建知识库对话框状态
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [createName, setCreateName] = useState("");
const [createDescription, setCreateDescription] = useState("");
const [isCreating, setIsCreating] = useState(false);
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
return;
}
if (isAuthenticated) {
loadKnowledgeBases();
}
}, [isAuthenticated, authLoading, router]);
const loadKnowledgeBases = async () => {
try {
setIsLoading(true);
setError(null);
const bases = await knowledgeBaseAPI.getKnowledgeBases();
// 过滤掉系统知识库,只显示用户创建的知识库
const userBases = bases.filter(kb => !kb.is_system);
setKnowledgeBases(userBases);
} catch (err) {
console.error("加载知识库失败:", err);
setError("加载知识库失败");
} finally {
setIsLoading(false);
}
};
const handleCreateKnowledgeBase = async () => {
if (!createName.trim()) return;
try {
setIsCreating(true);
setError(null);
await knowledgeBaseAPI.createKnowledgeBase({
name: createName.trim(),
description: createDescription.trim() || undefined,
});
// 重新加载知识库列表
await loadKnowledgeBases();
// 重置表单并关闭对话框
setCreateName("");
setCreateDescription("");
setIsCreateDialogOpen(false);
} catch (err) {
console.error("创建知识库失败:", err);
setError("创建知识库失败");
} finally {
setIsCreating(false);
}
};
const handleDeleteKnowledgeBase = async (knowledgeBaseId: number) => {
if (!confirm("确定要删除这个知识库吗?这将删除其中的所有文档。")) return;
try {
await knowledgeBaseAPI.deleteKnowledgeBase(knowledgeBaseId.toString());
await loadKnowledgeBases();
} catch (err) {
console.error("删除知识库失败:", err);
setError("删除知识库失败");
}
};
const filteredKnowledgeBases = knowledgeBases.filter(kb =>
kb.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
(kb.description && kb.description.toLowerCase().includes(searchQuery.toLowerCase()))
);
if (authLoading || isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<div className="min-h-screen bg-app pb-16 lg:pb-0">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* 页面头部 */}
<div className="mb-8">
<h1 className="text-3xl font-bold mb-2"></h1>
<p className="text-muted-foreground"></p>
</div>
{/* 错误提示 */}
{error && (
<Alert variant="destructive" className="mb-6">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 操作栏 */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6">
<div className="flex items-center space-x-4 mb-4 sm:mb-0">
{/* 创建知识库按钮 */}
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700">
<Plus className="w-4 h-4 mr-2" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="kb-name"></Label>
<Input
id="kb-name"
value={createName}
onChange={(e) => setCreateName(e.target.value)}
placeholder="请输入知识库名称"
disabled={isCreating}
/>
</div>
<div>
<Label htmlFor="kb-description"></Label>
<Input
id="kb-description"
value={createDescription}
onChange={(e) => setCreateDescription(e.target.value)}
placeholder="请输入知识库描述"
disabled={isCreating}
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setIsCreateDialogOpen(false)}
disabled={isCreating}
>
</Button>
<Button
onClick={handleCreateKnowledgeBase}
disabled={!createName.trim() || isCreating}
>
{isCreating ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
...
</>
) : (
"创建"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
<div className="flex items-center space-x-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input
placeholder="搜索知识库..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 w-64"
/>
</div>
<div className="text-sm text-muted-foreground">
{filteredKnowledgeBases.length}
</div>
</div>
</div>
{/* 知识库列表 */}
{filteredKnowledgeBases.length === 0 ? (
<Card className="backdrop-blur-sm bg-card/80 border-border/50 shadow-xl">
<CardContent className="text-center py-12">
<BookOpen className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-medium mb-2">
{searchQuery ? "没有找到匹配的知识库" : "还没有创建知识库"}
</h3>
<p className="text-muted-foreground mb-4">
{searchQuery ? "尝试使用其他关键词搜索" : "创建您的第一个知识库来组织文档"}
</p>
{!searchQuery && (
<Button onClick={() => setIsCreateDialogOpen(true)}>
<Plus className="w-4 h-4 mr-2" />
</Button>
)}
</CardContent>
</Card>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{filteredKnowledgeBases.map((kb) => (
<Card key={kb.id} className="hover:shadow-lg transition-shadow backdrop-blur-sm bg-card/80 border-border/50">
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex items-center space-x-2">
<BookOpen className="w-5 h-5 text-blue-600" />
<div>
<CardTitle className="text-lg">{kb.name}</CardTitle>
<CardDescription className="text-sm">
{kb.description || "暂无描述"}
</CardDescription>
</div>
</div>
<div className="flex items-center space-x-1">
{kb.document_count > 0 ? (
<CheckCircle className="w-4 h-4 text-green-600" />
) : (
<Clock className="w-4 h-4 text-gray-400" />
)}
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between text-sm text-muted-foreground">
<span></span>
<span>{kb.document_count} </span>
</div>
<div className="flex justify-between text-sm text-muted-foreground">
<span></span>
<span>{formatDate(kb.created_at)}</span>
</div>
<div className="flex justify-between text-sm">
<span></span>
<span className={kb.document_count > 0 ? "text-green-600" : "text-gray-500"}>
{kb.document_count > 0 ? "已就绪" : "空知识库"}
</span>
</div>
</div>
<div className="flex space-x-2 mt-4">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => router.push(`/knowledge/${kb.id}`)}
>
<Settings className="w-4 h-4 mr-1" />
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleDeleteKnowledgeBase(kb.id)}
className="text-red-600 hover:text-red-700"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
{/* 移动端导航 */}
<MobileNav />
</div>
);
}
+21
View File
@@ -0,0 +1,21 @@
"use client";
import { useAuthStore } from "@/store/auth";
import Navbar from "@/components/home/navbar";
export default function MainLayout({
children,
}: {
children: React.ReactNode;
}) {
const { isAuthenticated, user } = useAuthStore();
return (
<div className="min-h-screen bg-background">
<Navbar isAuthenticated={isAuthenticated} user={user} />
<main className="relative">
{children}
</main>
</div>
);
}
+395
View File
@@ -0,0 +1,395 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useAuthStore } from "@/store/auth";
import MobileNav from "@/components/layout/mobile-nav";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
Loader2,
User as UserIcon,
Mail,
Calendar,
CheckCircle,
Edit2,
Save,
X,
MessageSquare,
Database,
FileText
} from "lucide-react";
import { authAPI, analyticsAPI } from "@/lib/api";
import { formatDate } from "@/lib/utils";
const profileSchema = z.object({
email: z.string().email("请输入有效的邮箱地址"),
full_name: z.string().optional(),
});
type ProfileForm = z.infer<typeof profileSchema>;
export default function ProfilePage() {
const router = useRouter();
const { isAuthenticated, isLoading: authLoading, user, setUser } = useAuthStore();
const [isLoading, setIsLoading] = useState(true);
const [isEditing, setIsEditing] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [statistics, setStatistics] = useState<{
total_sessions: number;
total_messages: number;
total_documents: number;
active_days: number;
} | null>(null);
const {
register,
handleSubmit,
formState: { errors },
reset,
setValue,
} = useForm<ProfileForm>({
resolver: zodResolver(profileSchema),
defaultValues: {
email: user?.email || "",
full_name: user?.full_name || "",
},
});
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
return;
}
if (isAuthenticated) {
loadUserData();
}
}, [isAuthenticated, authLoading, router]);
useEffect(() => {
if (user) {
setValue("email", user.email || "");
setValue("full_name", user.full_name || "");
}
}, [user, setValue]);
const loadUserData = async () => {
try {
setIsLoading(true);
setError(null);
// 加载用户信息
const userData = await authAPI.getCurrentUser();
setUser(userData);
// 加载统计数据
try {
const stats = await analyticsAPI.getStatistics();
setStatistics({
total_sessions: stats.total_sessions || 0,
total_messages: stats.total_messages || 0,
total_documents: stats.total_documents || 0,
active_days: stats.active_days || 0,
});
} catch (err) {
console.warn("加载统计数据失败:", err);
// 统计数据加载失败不影响页面显示
}
} catch (err) {
console.error("加载用户信息失败:", err);
setError("加载用户信息失败");
} finally {
setIsLoading(false);
}
};
const onSubmit = async (data: ProfileForm) => {
try {
setIsSaving(true);
setError(null);
setSuccess(null);
const updatedUser = await authAPI.updateUserInfo({
email: data.email,
full_name: data.full_name || undefined,
});
setUser(updatedUser);
setIsEditing(false);
setSuccess("个人信息更新成功");
// 3秒后清除成功消息
setTimeout(() => setSuccess(null), 3000);
} catch (err: any) {
console.error("更新用户信息失败:", err);
setError(err.message || "更新用户信息失败");
} finally {
setIsSaving(false);
}
};
const handleCancel = () => {
reset({
email: user?.email || "",
full_name: user?.full_name || "",
});
setIsEditing(false);
setError(null);
setSuccess(null);
};
if (authLoading || isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin" />
</div>
);
}
if (!isAuthenticated || !user) {
return null;
}
const initials = (user.full_name || user.username || "U").charAt(0).toUpperCase();
return (
<div className="min-h-screen bg-app pb-16 lg:pb-0">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* 页面头部 */}
<div className="mb-8">
<h1 className="text-3xl font-bold mb-2"></h1>
<p className="text-muted-foreground"></p>
</div>
{/* 错误提示 */}
{error && (
<Alert variant="destructive" className="mb-6">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 成功提示 */}
{success && (
<Alert className="mb-6 border-green-500 bg-green-50 dark:bg-green-950">
<CheckCircle className="w-4 h-4 text-green-600" />
<AlertDescription className="text-green-800 dark:text-green-200">
{success}
</AlertDescription>
</Alert>
)}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* 左侧:用户头像和基本信息 */}
<div className="lg:col-span-2 space-y-6">
{/* 用户头像卡片 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center space-x-6">
<div className="w-24 h-24 bg-gradient-to-r from-blue-600 to-purple-600 rounded-full flex items-center justify-center text-white text-3xl font-bold shadow-lg">
{initials}
</div>
<div className="flex-1">
<p className="text-sm text-muted-foreground mb-2">
使
</p>
<p className="text-xs text-muted-foreground">
</p>
</div>
</div>
</CardContent>
</Card>
{/* 基本信息卡片 */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</div>
{!isEditing && (
<Button
variant="outline"
size="sm"
onClick={() => setIsEditing(true)}
>
<Edit2 className="w-4 h-4 mr-2" />
</Button>
)}
</div>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
{/* 用户名(只读) */}
<div>
<Label htmlFor="username"></Label>
<Input
id="username"
value={user.username}
disabled
className="bg-muted"
/>
<p className="text-xs text-muted-foreground mt-1">
</p>
</div>
{/* 邮箱(可编辑) */}
<div>
<Label htmlFor="email"></Label>
<Input
id="email"
type="email"
{...register("email")}
disabled={!isEditing}
className={errors.email ? "border-red-500" : ""}
/>
{errors.email && (
<p className="text-xs text-red-500 mt-1">
{errors.email.message}
</p>
)}
</div>
{/* 真实姓名(可编辑) */}
<div>
<Label htmlFor="full_name"></Label>
<Input
id="full_name"
{...register("full_name")}
disabled={!isEditing}
placeholder="请输入您的真实姓名(可选)"
/>
</div>
{/* 注册时间(只读) */}
<div>
<Label htmlFor="created_at"></Label>
<Input
id="created_at"
value={formatDate(user.created_at)}
disabled
className="bg-muted"
/>
</div>
{/* 账户状态(只读) */}
<div>
<Label htmlFor="is_active"></Label>
<div className="flex items-center space-x-2 mt-2">
<Input
id="is_active"
value={user.is_active ? "已激活" : "未激活"}
disabled
className="bg-muted"
/>
{user.is_active && (
<CheckCircle className="w-5 h-5 text-green-600" />
)}
</div>
</div>
{/* 编辑模式下的按钮 */}
{isEditing && (
<div className="flex items-center space-x-3 pt-4">
<Button type="submit" disabled={isSaving}>
{isSaving ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
...
</>
) : (
<>
<Save className="w-4 h-4 mr-2" />
</>
)}
</Button>
<Button
type="button"
variant="outline"
onClick={handleCancel}
disabled={isSaving}
>
<X className="w-4 h-4 mr-2" />
</Button>
</div>
)}
</form>
</CardContent>
</Card>
</div>
{/* 右侧:学习统计 */}
<div className="lg:col-span-1">
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
{statistics ? (
<div className="space-y-4">
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div className="flex items-center space-x-3">
<MessageSquare className="w-5 h-5 text-blue-600" />
<span className="text-sm font-medium"></span>
</div>
<span className="text-lg font-bold">{statistics.total_sessions}</span>
</div>
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div className="flex items-center space-x-3">
<MessageSquare className="w-5 h-5 text-green-600" />
<span className="text-sm font-medium"></span>
</div>
<span className="text-lg font-bold">{statistics.total_messages}</span>
</div>
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div className="flex items-center space-x-3">
<Database className="w-5 h-5 text-purple-600" />
<span className="text-sm font-medium"></span>
</div>
<span className="text-lg font-bold">-</span>
</div>
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div className="flex items-center space-x-3">
<FileText className="w-5 h-5 text-orange-600" />
<span className="text-sm font-medium"></span>
</div>
<span className="text-lg font-bold">{statistics.total_documents}</span>
</div>
</div>
) : (
<div className="text-center py-8">
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-2 text-muted-foreground" />
<p className="text-sm text-muted-foreground">...</p>
</div>
)}
</CardContent>
</Card>
</div>
</div>
</div>
{/* 移动端导航 */}
<MobileNav />
</div>
);
}
+357
View File
@@ -0,0 +1,357 @@
"use client";
import { useState } from "react";
// 禁用静态生成
export const dynamic = 'force-dynamic';
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useAuthStore } from "@/store/auth";
import MobileNav from "@/components/layout/mobile-nav";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { ThemeToggle } from "@/components/ui/theme-toggle";
import {
Loader2,
Lock,
Eye,
EyeOff,
CheckCircle,
Shield,
Palette,
Key
} from "lucide-react";
import { authAPI } from "@/lib/api";
const passwordSchema = z.object({
old_password: z.string().min(1, "请输入当前密码"),
new_password: z.string().min(6, "密码至少6个字符"),
confirm_password: z.string().min(1, "请确认新密码"),
}).refine((data) => data.new_password === data.confirm_password, {
message: "新密码与确认密码不匹配",
path: ["confirm_password"],
});
type PasswordForm = z.infer<typeof passwordSchema>;
// 密码强度检查函数
function getPasswordStrength(password: string): {
strength: "weak" | "medium" | "strong";
label: string;
color: string;
score: number;
} {
if (!password) {
return { strength: "weak", label: "", color: "", score: 0 };
}
let score = 0;
if (password.length >= 6) score++;
if (password.length >= 8) score++;
if (/[a-z]/.test(password)) score++;
if (/[A-Z]/.test(password)) score++;
if (/[0-9]/.test(password)) score++;
if (/[^a-zA-Z0-9]/.test(password)) score++;
if (score <= 2) {
return { strength: "weak", label: "弱", color: "text-red-600", score };
} else if (score <= 4) {
return { strength: "medium", label: "中", color: "text-yellow-600", score };
} else {
return { strength: "strong", label: "强", color: "text-green-600", score };
}
}
export default function SettingsPage() {
const router = useRouter();
const { isAuthenticated, isLoading: authLoading } = useAuthStore();
const [showOldPassword, setShowOldPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors },
watch,
reset,
} = useForm<PasswordForm>({
resolver: zodResolver(passwordSchema),
});
const newPassword = watch("new_password");
const passwordStrength = getPasswordStrength(newPassword || "");
const onSubmit = async (data: PasswordForm) => {
try {
setIsSubmitting(true);
setError(null);
setSuccess(null);
await authAPI.changePassword({
old_password: data.old_password,
new_password: data.new_password,
});
setSuccess("密码修改成功");
reset();
// 3秒后清除成功消息
setTimeout(() => setSuccess(null), 3000);
} catch (err: any) {
console.error("修改密码失败:", err);
setError(err.message || "修改密码失败,请检查当前密码是否正确");
} finally {
setIsSubmitting(false);
}
};
if (authLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin" />
</div>
);
}
if (!isAuthenticated) {
router.push("/login");
return null;
}
return (
<div className="min-h-screen bg-app pb-16 lg:pb-0">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* 页面头部 */}
<div className="mb-8">
<h1 className="text-3xl font-bold mb-2"></h1>
<p className="text-muted-foreground"></p>
</div>
{/* 错误提示 */}
{error && (
<Alert variant="destructive" className="mb-6">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 成功提示 */}
{success && (
<Alert className="mb-6 border-green-500 bg-green-50 dark:bg-green-950">
<CheckCircle className="w-4 h-4 text-green-600" />
<AlertDescription className="text-green-800 dark:text-green-200">
{success}
</AlertDescription>
</Alert>
)}
<div className="space-y-6">
{/* 账户安全 */}
<Card>
<CardHeader>
<div className="flex items-center space-x-2">
<Shield className="w-5 h-5 text-blue-600" />
<CardTitle></CardTitle>
</div>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
{/* 当前密码 */}
<div>
<Label htmlFor="old_password"></Label>
<div className="relative">
<Input
id="old_password"
type={showOldPassword ? "text" : "password"}
{...register("old_password")}
className={errors.old_password ? "border-red-500" : ""}
placeholder="请输入当前密码"
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowOldPassword(!showOldPassword)}
>
{showOldPassword ? (
<EyeOff className="w-4 h-4 text-muted-foreground" />
) : (
<Eye className="w-4 h-4 text-muted-foreground" />
)}
</Button>
</div>
{errors.old_password && (
<p className="text-xs text-red-500 mt-1">
{errors.old_password.message}
</p>
)}
</div>
{/* 新密码 */}
<div>
<Label htmlFor="new_password"></Label>
<div className="relative">
<Input
id="new_password"
type={showNewPassword ? "text" : "password"}
{...register("new_password")}
className={errors.new_password ? "border-red-500" : ""}
placeholder="请输入新密码(至少6个字符)"
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowNewPassword(!showNewPassword)}
>
{showNewPassword ? (
<EyeOff className="w-4 h-4 text-muted-foreground" />
) : (
<Eye className="w-4 h-4 text-muted-foreground" />
)}
</Button>
</div>
{newPassword && (
<div className="mt-2">
<div className="flex items-center space-x-2 mb-1">
<span className="text-xs text-muted-foreground"></span>
<span className={`text-xs font-medium ${passwordStrength.color}`}>
{passwordStrength.label}
</span>
</div>
<div className="w-full bg-muted rounded-full h-2">
<div
className={`h-2 rounded-full transition-all ${
passwordStrength.strength === "weak"
? "bg-red-500 w-1/3"
: passwordStrength.strength === "medium"
? "bg-yellow-500 w-2/3"
: "bg-green-500 w-full"
}`}
/>
</div>
</div>
)}
{errors.new_password && (
<p className="text-xs text-red-500 mt-1">
{errors.new_password.message}
</p>
)}
</div>
{/* 确认新密码 */}
<div>
<Label htmlFor="confirm_password"></Label>
<div className="relative">
<Input
id="confirm_password"
type={showConfirmPassword ? "text" : "password"}
{...register("confirm_password")}
className={errors.confirm_password ? "border-red-500" : ""}
placeholder="请再次输入新密码"
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
>
{showConfirmPassword ? (
<EyeOff className="w-4 h-4 text-muted-foreground" />
) : (
<Eye className="w-4 h-4 text-muted-foreground" />
)}
</Button>
</div>
{errors.confirm_password && (
<p className="text-xs text-red-500 mt-1">
{errors.confirm_password.message}
</p>
)}
</div>
{/* 密码要求提示 */}
<div className="p-4 bg-muted/50 rounded-lg">
<p className="text-sm font-medium mb-2"></p>
<ul className="text-xs text-muted-foreground space-y-1">
<li> 6</li>
<li> </li>
<li> 使</li>
</ul>
</div>
{/* 提交按钮 */}
<div className="pt-4">
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
...
</>
) : (
<>
<Key className="w-4 h-4 mr-2" />
</>
)}
</Button>
</div>
</form>
</CardContent>
</Card>
{/* 偏好设置 */}
<Card>
<CardHeader>
<div className="flex items-center space-x-2">
<Palette className="w-5 h-5 text-purple-600" />
<CardTitle></CardTitle>
</div>
<CardDescription>使</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{/* 主题设置 */}
<div className="flex items-center justify-between p-4 border rounded-lg">
<div className="flex-1">
<div className="flex items-center space-x-2 mb-1">
<Palette className="w-4 h-4 text-muted-foreground" />
<Label className="text-base font-medium"></Label>
</div>
<p className="text-sm text-muted-foreground">
/
</p>
</div>
<ThemeToggle />
</div>
{/* 未来可添加其他偏好设置 */}
<div className="p-4 bg-muted/50 rounded-lg">
<p className="text-sm text-muted-foreground">
</p>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
{/* 移动端导航 */}
<MobileNav />
</div>
);
}
@@ -0,0 +1,697 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { motion } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Slider } from "@/components/ui/slider";
import { Loader2, Download, Copy, Upload, Edit3, Wand2, Expand, Palette, Image as ImageIcon, X } from "lucide-react";
import { imageAPI } from "@/lib/api";
import { toast } from "sonner";
interface EditResult {
id: string;
url: string;
original_filename?: string;
edit_prompt: string;
mode: string;
metadata: any;
}
interface VariationResult {
id: string;
url: string;
type: string;
metadata: any;
}
interface ConfigOption {
id: string;
name: string;
description: string;
}
export default function ImageToImagePage() {
const [selectedImage, setSelectedImage] = useState<File | null>(null);
const [imagePreview, setImagePreview] = useState<string>("");
const [editMode, setEditMode] = useState("optimize");
const [editPrompt, setEditPrompt] = useState("");
const [strength, setStrength] = useState(0.8);
const [numVariations, setNumVariations] = useState(3);
const [isProcessing, setIsProcessing] = useState(false);
const [editResult, setEditResult] = useState<EditResult | null>(null);
const [variations, setVariations] = useState<VariationResult[]>([]);
// Canvas 相关状态
const [isDrawing, setIsDrawing] = useState(false);
const [brushSize, setBrushSize] = useState(20);
const [maskData, setMaskData] = useState<string>("");
// 配置选项
const [editModes, setEditModes] = useState<ConfigOption[]>([]);
const [stylePresets, setStylePresets] = useState<ConfigOption[]>([]);
const canvasRef = useRef<HTMLCanvasElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// 加载配置选项
useEffect(() => {
const loadConfigs = async () => {
try {
const [modesData, presetsData] = await Promise.all([
imageAPI.getEditModes(),
imageAPI.getStylePresets(),
]);
setEditModes(modesData);
setStylePresets(presetsData);
} catch (error) {
console.error("加载配置失败:", error);
toast.error("加载配置失败");
}
};
loadConfigs();
}, []);
// 处理图像上传
const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
setSelectedImage(file);
const reader = new FileReader();
reader.onload = (e) => {
setImagePreview(e.target?.result as string);
};
reader.readAsDataURL(file);
}
};
// 处理拖拽上传
const handleDrop = (event: React.DragEvent) => {
event.preventDefault();
const file = event.dataTransfer.files[0];
if (file && file.type.startsWith("image/")) {
setSelectedImage(file);
const reader = new FileReader();
reader.onload = (e) => {
setImagePreview(e.target?.result as string);
};
reader.readAsDataURL(file);
}
};
const handleDragOver = (event: React.DragEvent) => {
event.preventDefault();
};
// Canvas 绘制蒙版
const handleCanvasMouseDown = (event: React.MouseEvent<HTMLCanvasElement>) => {
setIsDrawing(true);
drawOnCanvas(event);
};
const handleCanvasMouseMove = (event: React.MouseEvent<HTMLCanvasElement>) => {
if (!isDrawing) return;
drawOnCanvas(event);
};
const handleCanvasMouseUp = () => {
setIsDrawing(false);
// 导出蒙版数据
const canvas = canvasRef.current;
if (canvas) {
const dataURL = canvas.toDataURL();
setMaskData(dataURL);
}
};
const drawOnCanvas = (event: React.MouseEvent<HTMLCanvasElement>) => {
const canvas = canvasRef.current;
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
ctx.beginPath();
ctx.arc(x, y, brushSize / 2, 0, Math.PI * 2);
ctx.fill();
};
// 清除蒙版
const clearMask = () => {
const canvas = canvasRef.current;
if (canvas) {
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
setMaskData("");
}
}
};
// 图像编辑
const handleImageEdit = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
if (!editPrompt.trim()) {
toast.error("请输入编辑描述");
return;
}
setIsProcessing(true);
try {
let maskFile: File | undefined;
if (editMode === "local_edit" && maskData) {
// 将蒙版数据转换为文件
const response = await fetch(maskData);
const blob = await response.blob();
maskFile = new File([blob], "mask.png", { type: "image/png" });
}
const result = await imageAPI.imageEdit(
selectedImage,
editPrompt,
editMode,
maskFile,
strength
);
setEditResult(result);
toast.success("图像编辑完成");
} catch (error) {
console.error("图像编辑失败:", error);
toast.error("图像编辑失败,请重试");
} finally {
setIsProcessing(false);
}
};
// 生成变体
const handleGenerateVariations = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
setIsProcessing(true);
try {
const result = await imageAPI.imageVariations(selectedImage, numVariations);
setVariations(result.variations);
toast.success(`成功生成 ${result.total} 个变体`);
} catch (error) {
console.error("生成变体失败:", error);
toast.error("生成变体失败,请重试");
} finally {
setIsProcessing(false);
}
};
// 风格转换
const handleStyleTransfer = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
if (!editPrompt.trim()) {
toast.error("请输入风格描述");
return;
}
setIsProcessing(true);
try {
const result = await imageAPI.styleTransfer(selectedImage, editPrompt, strength);
setEditResult(result);
toast.success("风格转换完成");
} catch (error) {
console.error("风格转换失败:", error);
toast.error("风格转换失败,请重试");
} finally {
setIsProcessing(false);
}
};
// 图像优化
const handleOptimizeImage = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
setIsProcessing(true);
try {
const result = await imageAPI.optimizeImage(selectedImage, editPrompt || "优化图像质量,增强细节,提高清晰度", strength);
setEditResult(result);
toast.success("图像优化完成");
} catch (error) {
console.error("图像优化失败:", error);
toast.error("图像优化失败,请重试");
} finally {
setIsProcessing(false);
}
};
// 图像扩展
const handleOutpaintImage = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
if (!editPrompt.trim()) {
toast.error("请输入扩展描述");
return;
}
setIsProcessing(true);
try {
const result = await imageAPI.outpaintImage(selectedImage, editPrompt, strength);
setEditResult(result);
toast.success("图像扩展完成");
} catch (error) {
console.error("图像扩展失败:", error);
toast.error("图像扩展失败,请重试");
} finally {
setIsProcessing(false);
}
};
// 执行操作
const handleExecute = () => {
switch (editMode) {
case "optimize":
handleOptimizeImage();
break;
case "style_transfer":
handleStyleTransfer();
break;
case "local_edit":
handleImageEdit();
break;
case "outpaint":
handleOutpaintImage();
break;
default:
handleImageEdit();
}
};
const handleDownload = (imageUrl: string, imageId: string) => {
const link = document.createElement("a");
link.href = imageUrl;
link.download = `edited-image-${imageId}.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
toast.success("图像下载成功");
};
return (
<div className="min-h-screen bg-gradient-to-br from-green-50 via-white to-blue-50">
<div className="container mx-auto px-4 py-8">
{/* 页面标题 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="text-center mb-8"
>
<h1 className="text-4xl font-bold bg-gradient-to-r from-green-600 to-blue-600 bg-clip-text text-transparent mb-4">
- Image to Image
</h1>
<p className="text-lg text-gray-600 max-w-2xl mx-auto">
</p>
</motion.div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* 左侧:图像上传和编辑配置 */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5, delay: 0.1 }}
className="space-y-6"
>
{/* 图像上传 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Upload className="h-5 w-5 text-blue-600" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
{!selectedImage ? (
<div
className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer"
onClick={() => fileInputRef.current?.click()}
onDrop={handleDrop}
onDragOver={handleDragOver}
>
<Upload className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<p className="text-gray-600 mb-2"></p>
<p className="text-sm text-gray-400"> PNG, JPG, JPEG </p>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleImageUpload}
className="hidden"
/>
</div>
) : (
<div className="space-y-4">
<div className="relative">
<img
src={imagePreview}
alt="Uploaded image"
className="w-full h-64 object-cover rounded-lg"
/>
<Button
size="sm"
variant="destructive"
className="absolute top-2 right-2"
onClick={() => {
setSelectedImage(null);
setImagePreview("");
}}
>
<X className="h-4 w-4" />
</Button>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline">{selectedImage.name}</Badge>
<Badge variant="secondary">
{(selectedImage.size / 1024 / 1024).toFixed(2)} MB
</Badge>
</div>
</div>
)}
</CardContent>
</Card>
{/* 编辑配置 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Edit3 className="h-5 w-5 text-green-600" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* 编辑模式 */}
<div className="space-y-2">
<Label></Label>
<Select value={editMode} onValueChange={setEditMode}>
<SelectTrigger>
<SelectValue placeholder="选择编辑模式" />
</SelectTrigger>
<SelectContent>
{editModes.map((mode) => (
<SelectItem key={mode.id} value={mode.id}>
<div>
<div className="font-medium">{mode.name}</div>
<div className="text-sm text-gray-500">{mode.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 编辑描述 */}
<div className="space-y-2">
<Label></Label>
<Textarea
placeholder={
editMode === "optimize"
? "描述您希望如何优化图像..."
: editMode === "style_transfer"
? "描述您想要的风格,例如:水彩画风格、油画风格..."
: editMode === "local_edit"
? "描述您想要修改的内容..."
: "描述您希望如何扩展图像..."
}
value={editPrompt}
onChange={(e) => setEditPrompt(e.target.value)}
rows={3}
/>
</div>
{/* 编辑强度 */}
<div className="space-y-2">
<Label>: {Math.round(strength * 100)}%</Label>
<Slider
value={[strength]}
onValueChange={([value]) => setStrength(value)}
max={1}
min={0}
step={0.1}
className="w-full"
/>
</div>
{/* 局部编辑蒙版 */}
{editMode === "local_edit" && selectedImage && (
<div className="space-y-2">
<Label></Label>
<div className="border rounded-lg p-4">
<div className="space-y-2 mb-4">
<Label>: {brushSize}px</Label>
<Slider
value={[brushSize]}
onValueChange={([value]) => setBrushSize(value)}
max={50}
min={5}
step={5}
className="w-full"
/>
</div>
<div className="relative">
<canvas
ref={canvasRef}
width={400}
height={300}
className="border rounded cursor-crosshair w-full h-64 object-cover"
style={{ backgroundImage: `url(${imagePreview})`, backgroundSize: "cover" }}
onMouseDown={handleCanvasMouseDown}
onMouseMove={handleCanvasMouseMove}
onMouseUp={handleCanvasMouseUp}
/>
<div className="absolute top-2 right-2">
<Button size="sm" variant="outline" onClick={clearMask}>
</Button>
</div>
</div>
<p className="text-sm text-gray-500 mt-2">
</p>
</div>
</div>
)}
{/* 执行按钮 */}
<Button
onClick={handleExecute}
disabled={isProcessing || !selectedImage}
className="w-full"
size="lg"
>
{isProcessing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : (
<>
<Wand2 className="mr-2 h-4 w-4" />
</>
)}
</Button>
</CardContent>
</Card>
{/* 生成变体 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Palette className="h-5 w-5 text-purple-600" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label></Label>
<Select value={numVariations.toString()} onValueChange={(value) => setNumVariations(parseInt(value))}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 4, 5, 6].map((num) => (
<SelectItem key={num} value={num.toString()}>
{num}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button
onClick={handleGenerateVariations}
disabled={isProcessing || !selectedImage}
className="w-full"
variant="outline"
>
<Palette className="mr-2 h-4 w-4" />
</Button>
</CardContent>
</Card>
</motion.div>
{/* 右侧:结果展示 */}
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5, delay: 0.2 }}
className="space-y-6"
>
{/* 编辑结果 */}
{editResult && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Edit3 className="h-5 w-5 text-green-600" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="relative group">
<img
src={editResult.url}
alt="Edited image"
className="w-full h-64 object-cover rounded-lg"
/>
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all duration-200 rounded-lg" />
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<Button
size="sm"
variant="secondary"
onClick={() => handleDownload(editResult.url, editResult.id)}
>
<Download className="h-3 w-3" />
</Button>
</div>
</div>
<div className="space-y-2">
<div className="flex items-center gap-2">
<Badge variant="outline">{editResult.mode}</Badge>
<Badge variant="secondary">
: {Math.round((editResult.metadata?.strength || 0) * 100)}%
</Badge>
</div>
<p className="text-sm text-gray-600">{editResult.edit_prompt}</p>
</div>
</div>
</CardContent>
</Card>
)}
{/* 变体结果 */}
{variations.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Palette className="h-5 w-5 text-purple-600" />
</CardTitle>
<CardDescription>
{variations.length}
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{variations.map((variation, index) => (
<motion.div
key={variation.id}
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3, delay: index * 0.1 }}
className="group relative"
>
<div className="relative">
<img
src={variation.url}
alt={`Variation ${index + 1}`}
className="w-full h-48 object-cover rounded-lg"
/>
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all duration-200 rounded-lg" />
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<Button
size="sm"
variant="secondary"
onClick={() => handleDownload(variation.url, variation.id)}
>
<Download className="h-3 w-3" />
</Button>
</div>
</div>
<div className="mt-2">
<Badge variant="outline"> {index + 1}</Badge>
</div>
</motion.div>
))}
</div>
</CardContent>
</Card>
)}
{/* 空状态 */}
{!editResult && variations.length === 0 && (
<Card>
<CardContent className="text-center py-12">
<ImageIcon className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<p className="text-gray-500"></p>
<p className="text-sm text-gray-400"></p>
</CardContent>
</Card>
)}
</motion.div>
</div>
</div>
</div>
);
}
+964
View File
@@ -0,0 +1,964 @@
"use client";
import React, { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Slider } from "@/components/ui/slider";
import {
Image,
ImageIcon,
Wand2,
Download,
Share2,
Eye,
Loader2,
Palette,
Settings,
Sparkles,
Type,
Edit3,
ArrowRight,
Upload,
X
} from "lucide-react";
import LoadingSpinner from "@/components/ui/loading-spinner";
import { imageAPI } from "@/lib/api";
import { toast } from "sonner";
import { motion } from "framer-motion";
interface GeneratedImage {
id: string;
url: string;
prompt: string;
model: string;
metadata: any;
}
interface EditResult {
id: string;
url: string;
original_filename?: string;
edit_prompt: string;
mode: string;
metadata: any;
}
interface VariationResult {
id: string;
url: string;
type: string;
metadata: any;
}
interface ConfigOption {
id: string;
name: string;
description: string;
}
export default function SpatialPage() {
const router = useRouter();
const { isAuthenticated, isLoading: authLoading } = useAuthStore();
// Text-to-image states
const [prompt, setPrompt] = useState("");
const [model, setModel] = useState("kolors");
const [template, setTemplate] = useState("custom");
const [style, setStyle] = useState("realistic");
const [size, setSize] = useState("1024x1024");
const [numImages, setNumImages] = useState(1);
const [isGenerating, setIsGenerating] = useState(false);
const [generatedImages, setGeneratedImages] = useState<GeneratedImage[]>([]);
// Image-to-image states
const [selectedImage, setSelectedImage] = useState<File | null>(null);
const [imagePreview, setImagePreview] = useState<string>("");
const [editMode, setEditMode] = useState("optimize");
const [editPrompt, setEditPrompt] = useState("");
const [strength, setStrength] = useState(0.8);
const [numVariations, setNumVariations] = useState(3);
const [isProcessing, setIsProcessing] = useState(false);
const [editResult, setEditResult] = useState<EditResult | null>(null);
const [variations, setVariations] = useState<VariationResult[]>([]);
// Canvas states for local editing
const [isDrawing, setIsDrawing] = useState(false);
const [brushSize, setBrushSize] = useState(20);
const [maskData, setMaskData] = useState<string>("");
// Configuration options
const [models, setModels] = useState<ConfigOption[]>([]);
const [templates, setTemplates] = useState<ConfigOption[]>([]);
const [styles, setStyles] = useState<ConfigOption[]>([]);
const [sizes, setSizes] = useState<ConfigOption[]>([]);
const [editModes, setEditModes] = useState<ConfigOption[]>([]);
const [stylePresets, setStylePresets] = useState<ConfigOption[]>([]);
const canvasRef = useRef<HTMLCanvasElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
return;
}
if (isAuthenticated) {
loadConfigs();
}
}, [isAuthenticated, authLoading, router]);
const loadConfigs = async () => {
try {
const [modelsData, templatesData, stylesData, sizesData, modesData, presetsData] = await Promise.all([
imageAPI.getModels(),
imageAPI.getTemplates(),
imageAPI.getStyles(),
imageAPI.getSizes(),
imageAPI.getEditModes(),
imageAPI.getStylePresets(),
]);
setModels(modelsData);
setTemplates(templatesData);
setStyles(stylesData);
setSizes(sizesData);
setEditModes(modesData);
setStylePresets(presetsData);
} catch (error) {
console.error("加载配置失败:", error);
toast.error("加载配置失败");
}
};
// Text-to-image functions
const handleGenerate = async () => {
if (!prompt.trim()) {
toast.error("请输入图像描述");
return;
}
setIsGenerating(true);
try {
const response = await imageAPI.textToImage({
prompt,
model,
template,
style,
size,
num_images: numImages,
});
setGeneratedImages(response.images);
toast.success(`成功生成 ${response.total} 张图像`);
} catch (error) {
console.error("生成图像失败:", error);
toast.error("生成图像失败,请重试");
} finally {
setIsGenerating(false);
}
};
// Image-to-image functions
const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
setSelectedImage(file);
const reader = new FileReader();
reader.onload = (e) => {
setImagePreview(e.target?.result as string);
};
reader.readAsDataURL(file);
}
};
const handleDrop = (event: React.DragEvent) => {
event.preventDefault();
const file = event.dataTransfer.files[0];
if (file && file.type.startsWith("image/")) {
setSelectedImage(file);
const reader = new FileReader();
reader.onload = (e) => {
setImagePreview(e.target?.result as string);
};
reader.readAsDataURL(file);
}
};
const handleDragOver = (event: React.DragEvent) => {
event.preventDefault();
};
const handleExecute = () => {
switch (editMode) {
case "optimize":
handleOptimizeImage();
break;
case "style_transfer":
handleStyleTransfer();
break;
case "local_edit":
handleImageEdit();
break;
case "outpaint":
handleOutpaintImage();
break;
default:
handleImageEdit();
}
};
const handleOptimizeImage = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
setIsProcessing(true);
try {
const response = await imageAPI.optimizeImage(selectedImage, editPrompt || "优化图像质量,增强细节,提高清晰度", strength);
const result = response.result || response; // 兼容包装和非包装的响应
console.log("图像优化结果:", result);
setEditResult(result);
toast.success("图像优化完成");
} catch (error) {
console.error("图像优化失败:", error);
toast.error("图像优化失败,请重试");
} finally {
setIsProcessing(false);
}
};
const handleStyleTransfer = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
if (!editPrompt.trim()) {
toast.error("请输入风格描述");
return;
}
setIsProcessing(true);
try {
const response = await imageAPI.styleTransfer(selectedImage, editPrompt, strength);
const result = response.result || response; // 兼容包装和非包装的响应
console.log("风格转换结果:", result);
setEditResult(result);
toast.success("风格转换完成");
} catch (error) {
console.error("风格转换失败:", error);
toast.error("风格转换失败,请重试");
} finally {
setIsProcessing(false);
}
};
const handleImageEdit = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
if (!editPrompt.trim()) {
toast.error("请输入编辑描述");
return;
}
setIsProcessing(true);
try {
let maskFile: File | undefined;
if (editMode === "local_edit" && maskData) {
const response = await fetch(maskData);
const blob = await response.blob();
maskFile = new File([blob], "mask.png", { type: "image/png" });
}
const response = await imageAPI.imageEdit(
selectedImage,
editPrompt,
editMode,
maskFile,
strength
);
const result = response.result || response; // 兼容包装和非包装的响应
console.log("图像编辑结果:", result);
setEditResult(result);
toast.success("图像编辑完成");
} catch (error) {
console.error("图像编辑失败:", error);
toast.error("图像编辑失败,请重试");
} finally {
setIsProcessing(false);
}
};
const handleOutpaintImage = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
if (!editPrompt.trim()) {
toast.error("请输入扩展描述");
return;
}
setIsProcessing(true);
try {
const response = await imageAPI.outpaintImage(selectedImage, editPrompt, strength);
const result = response.result || response; // 兼容包装和非包装的响应
console.log("图像扩展结果:", result);
setEditResult(result);
toast.success("图像扩展完成");
} catch (error) {
console.error("图像扩展失败:", error);
toast.error("图像扩展失败,请重试");
} finally {
setIsProcessing(false);
}
};
const handleGenerateVariations = async () => {
if (!selectedImage) {
toast.error("请先上传图像");
return;
}
setIsProcessing(true);
try {
const result = await imageAPI.imageVariations(selectedImage, numVariations);
setVariations(result.variations);
toast.success(`成功生成 ${result.total} 个变体`);
} catch (error) {
console.error("生成变体失败:", error);
toast.error("生成变体失败,请重试");
} finally {
setIsProcessing(false);
}
};
const handleDownload = (imageUrl: string, imageId: string) => {
const link = document.createElement("a");
link.href = imageUrl;
link.download = `image-${imageId}.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
toast.success("图像下载成功");
};
if (authLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<LoadingSpinner size="lg" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<div className="min-h-screen bg-background">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* 页面头部 */}
<div className="mb-8">
<h1 className="text-3xl font-bold text-foreground mb-2"></h1>
<p className="text-muted-foreground">使AI生成国土空间规划相关的设计图和示意图</p>
</div>
{/* Tab导航 */}
<Tabs defaultValue="text-to-image" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="text-to-image" className="flex items-center gap-2">
<Type className="w-4 h-4" />
</TabsTrigger>
<TabsTrigger value="image-to-image" className="flex items-center gap-2">
<Edit3 className="w-4 h-4" />
</TabsTrigger>
</TabsList>
{/* 文生图 Tab */}
<TabsContent value="text-to-image" className="mt-6">
<div className="min-h-screen bg-background">
<div className="container mx-auto px-4 py-8">
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* 左侧:生成配置 */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5, delay: 0.1 }}
className="lg:col-span-1"
>
<Card className="sticky top-8">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Sparkles className="h-5 w-5 text-blue-600" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* 模型选择 */}
<div className="space-y-2">
<Label htmlFor="model">AI模型</Label>
<Select value={model} onValueChange={setModel}>
<SelectTrigger>
<SelectValue placeholder="选择模型" />
</SelectTrigger>
<SelectContent>
{models.map((option) => (
<SelectItem key={option.id} value={option.id}>
<div>
<div className="font-medium">{option.name}</div>
<div className="text-sm text-muted-foreground">{option.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 提示词模板 */}
<div className="space-y-2">
<Label htmlFor="template"></Label>
<Select value={template} onValueChange={setTemplate}>
<SelectTrigger>
<SelectValue placeholder="选择模板" />
</SelectTrigger>
<SelectContent>
{templates.map((option) => (
<SelectItem key={option.id} value={option.id}>
<div>
<div className="font-medium">{option.name}</div>
<div className="text-sm text-muted-foreground">{option.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 图像描述 */}
<div className="space-y-2">
<Label htmlFor="prompt"></Label>
<Textarea
id="prompt"
placeholder="描述您想要生成的图像,例如:城市中心区商业综合体规划,包含商业区、办公区、绿地..."
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={4}
className="resize-none"
/>
</div>
{/* 风格选择 */}
<div className="space-y-2">
<Label htmlFor="style"></Label>
<Select value={style} onValueChange={setStyle}>
<SelectTrigger>
<SelectValue placeholder="选择风格" />
</SelectTrigger>
<SelectContent>
{styles.map((option) => (
<SelectItem key={option.id} value={option.id}>
<div>
<div className="font-medium">{option.name}</div>
<div className="text-sm text-muted-foreground">{option.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 尺寸选择 */}
<div className="space-y-2">
<Label htmlFor="size"></Label>
<Select value={size} onValueChange={setSize}>
<SelectTrigger>
<SelectValue placeholder="选择尺寸" />
</SelectTrigger>
<SelectContent>
{sizes.map((option) => (
<SelectItem key={option.id} value={option.id}>
<div>
<div className="font-medium">{option.name}</div>
<div className="text-sm text-muted-foreground">{option.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 生成数量 */}
<div className="space-y-2">
<Label htmlFor="numImages"></Label>
<Select value={numImages.toString()} onValueChange={(value) => setNumImages(parseInt(value))}>
<SelectTrigger>
<SelectValue placeholder="选择数量" />
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 4].map((num) => (
<SelectItem key={num} value={num.toString()}>
{num}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Separator />
{/* 生成按钮 */}
<Button
onClick={handleGenerate}
disabled={isGenerating || !prompt.trim()}
className="w-full"
size="lg"
>
{isGenerating ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : (
<>
<Image className="mr-2 h-4 w-4" />
</>
)}
</Button>
</CardContent>
</Card>
</motion.div>
{/* 右侧:生成结果 */}
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5, delay: 0.2 }}
className="lg:col-span-2"
>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Image className="h-5 w-5 text-green-600" />
</CardTitle>
<CardDescription>
{generatedImages.length > 0
? `已生成 ${generatedImages.length} 张图像`
: "生成图像将显示在这里"
}
</CardDescription>
</CardHeader>
<CardContent>
{generatedImages.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{generatedImages.map((image, index) => (
<motion.div
key={image.id}
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3, delay: index * 0.1 }}
className="group relative"
>
<Card className="overflow-hidden">
<div className="aspect-square relative bg-muted">
<img
src={image.url}
alt={`Generated image ${index + 1}`}
className="w-full h-full object-cover"
loading="lazy"
/>
<div className="absolute inset-0 bg-transparent group-hover:bg-black/20 transition-all duration-200" />
</div>
<CardContent className="p-4 space-y-3">
<div className="flex items-center gap-2">
<Badge variant="outline">{image.model}</Badge>
<Badge variant="secondary">{image.metadata?.style || style}</Badge>
</div>
<p className="text-sm text-muted-foreground line-clamp-2">
{image.prompt}
</p>
<Button
variant="outline"
size="sm"
className="w-full"
onClick={() => handleDownload(image.url, image.id)}
>
<Download className="h-4 w-4 mr-2" />
</Button>
</CardContent>
</Card>
</motion.div>
))}
</div>
) : (
<div className="text-center py-12">
<Image className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-muted-foreground"></p>
<p className="text-sm text-muted-foreground/70">"生成图像"</p>
</div>
)}
</CardContent>
</Card>
</motion.div>
</div>
</div>
</div>
</TabsContent>
{/* 图生图 Tab */}
<TabsContent value="image-to-image" className="mt-6">
<div className="min-h-screen bg-background">
<div className="container mx-auto px-4 py-8">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* 左侧:图像上传和编辑配置 */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5, delay: 0.1 }}
className="space-y-6"
>
{/* 图像上传 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Upload className="h-5 w-5 text-blue-600" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
{!selectedImage ? (
<div
className="border-2 border-dashed border-border rounded-lg p-8 text-center hover:border-primary transition-colors cursor-pointer"
onClick={() => fileInputRef.current?.click()}
onDrop={handleDrop}
onDragOver={handleDragOver}
>
<Upload className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-foreground mb-2"></p>
<p className="text-sm text-muted-foreground"> PNG, JPG, JPEG </p>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleImageUpload}
className="hidden"
/>
</div>
) : (
<div className="space-y-4">
<div className="relative">
{imagePreview ? (
<img
src={imagePreview}
alt="Uploaded image"
className="w-full h-64 object-cover rounded-lg"
/>
) : (
<div className="w-full h-64 bg-muted border-2 border-dashed border-border rounded-lg flex items-center justify-center">
<div className="text-center">
<ImageIcon className="h-8 w-8 text-muted-foreground mx-auto mb-2" />
<p className="text-sm text-muted-foreground"></p>
</div>
</div>
)}
<Button
size="sm"
variant="destructive"
className="absolute top-2 right-2"
onClick={() => {
setSelectedImage(null);
setImagePreview("");
}}
>
<X className="h-4 w-4" />
</Button>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline">{selectedImage.name}</Badge>
<Badge variant="secondary">
{(selectedImage.size / 1024 / 1024).toFixed(2)} MB
</Badge>
</div>
</div>
)}
</CardContent>
</Card>
{/* 编辑配置 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Edit3 className="h-5 w-5 text-green-600" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* 编辑模式 */}
<div className="space-y-2">
<Label></Label>
<Select value={editMode} onValueChange={setEditMode}>
<SelectTrigger>
<SelectValue placeholder="选择编辑模式" />
</SelectTrigger>
<SelectContent>
{editModes.map((mode) => (
<SelectItem key={mode.id} value={mode.id}>
<div>
<div className="font-medium">{mode.name}</div>
<div className="text-sm text-gray-500">{mode.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 编辑描述 */}
<div className="space-y-2">
<Label></Label>
<Textarea
placeholder={
editMode === "optimize"
? "描述您希望如何优化图像..."
: editMode === "style_transfer"
? "描述您想要的风格,例如:水彩画风格、油画风格..."
: editMode === "local_edit"
? "描述您想要修改的内容..."
: "描述您希望如何扩展图像..."
}
value={editPrompt}
onChange={(e) => setEditPrompt(e.target.value)}
rows={3}
/>
</div>
{/* 编辑强度 */}
<div className="space-y-2">
<Label>: {Math.round(strength * 100)}%</Label>
<Slider
value={[strength]}
onValueChange={([value]) => setStrength(value)}
max={1}
min={0}
step={0.1}
className="w-full"
/>
</div>
{/* 执行按钮 */}
<Button
onClick={handleExecute}
disabled={isProcessing || !selectedImage}
className="w-full"
size="lg"
>
{isProcessing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : (
<>
<Wand2 className="mr-2 h-4 w-4" />
</>
)}
</Button>
</CardContent>
</Card>
{/* 生成变体 - 暂时禁用,因为API不支持 */}
{/* <Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Palette className="h-5 w-5 text-purple-600" />
生成变体
</CardTitle>
<CardDescription>
基于原图生成多个变体
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>变体数量</Label>
<Select value={numVariations.toString()} onValueChange={(value) => setNumVariations(parseInt(value))}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 4, 5, 6].map((num) => (
<SelectItem key={num} value={num.toString()}>
{num} 个变体
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button
onClick={handleGenerateVariations}
disabled={isProcessing || !selectedImage}
className="w-full"
variant="outline"
>
<Palette className="mr-2 h-4 w-4" />
生成变体
</Button>
</CardContent>
</Card> */}
</motion.div>
{/* 右侧:结果展示 */}
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5, delay: 0.2 }}
className="space-y-6"
>
{/* 编辑结果 */}
{editResult && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Edit3 className="h-5 w-5 text-green-600" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="relative group bg-muted rounded-lg overflow-hidden">
<img
src={editResult.url}
alt="Edited image"
className="w-full h-64 object-contain"
loading="lazy"
/>
<div className="absolute inset-0 bg-transparent group-hover:bg-black/20 transition-all duration-200" />
</div>
<div className="space-y-3">
<div className="flex items-center gap-2">
<Badge variant="outline">{editResult.mode}</Badge>
<Badge variant="secondary">
: {Math.round((editResult.metadata?.strength || 0) * 100)}%
</Badge>
</div>
<p className="text-sm text-muted-foreground">{editResult.edit_prompt}</p>
<Button
variant="outline"
size="sm"
className="w-full"
onClick={() => handleDownload(editResult.url, editResult.id)}
>
<Download className="h-4 w-4 mr-2" />
</Button>
</div>
</div>
</CardContent>
</Card>
)}
{/* 变体结果 - 暂时禁用 */}
{/* {variations.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Palette className="h-5 w-5 text-purple-600" />
图像变体
</CardTitle>
<CardDescription>
生成了 {variations.length} 个变体
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{variations.map((variation, index) => (
<motion.div
key={variation.id}
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3, delay: index * 0.1 }}
className="group relative"
>
<Card className="overflow-hidden">
<div className="relative bg-muted">
<img
src={variation.url}
alt={`Variation ${index + 1}`}
className="w-full h-48 object-cover"
loading="lazy"
/>
<div className="absolute inset-0 bg-transparent group-hover:bg-black/20 transition-all duration-200" />
</div>
<CardContent className="p-4 space-y-3">
<div className="flex items-center gap-2">
<Badge variant="outline">变体 {index + 1}</Badge>
</div>
<Button
variant="outline"
size="sm"
className="w-full"
onClick={() => handleDownload(variation.url, variation.id)}
>
<Download className="h-4 w-4 mr-2" />
下载图片
</Button>
</CardContent>
</Card>
</motion.div>
))}
</div>
</CardContent>
</Card>
)} */}
{/* 空状态 */}
{!editResult && (
<Card>
<CardContent className="text-center py-12">
<Image className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-muted-foreground"></p>
<p className="text-sm text-muted-foreground/70"></p>
</CardContent>
</Card>
)}
</motion.div>
</div>
</div>
</div>
</TabsContent>
</Tabs>
</div>
</div>
);
}
@@ -0,0 +1,378 @@
"use client";
import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Loader2, Download, Copy, RefreshCw, Sparkles, Image as ImageIcon } from "lucide-react";
import { imageAPI } from "@/lib/api";
import { toast } from "sonner";
interface GeneratedImage {
id: string;
url: string;
prompt: string;
model: string;
metadata: any;
}
interface ConfigOption {
id: string;
name: string;
description: string;
}
export default function TextToImagePage() {
const [prompt, setPrompt] = useState("");
const [model, setModel] = useState("kolors");
const [template, setTemplate] = useState("custom");
const [style, setStyle] = useState("realistic");
const [size, setSize] = useState("1024x1024");
const [numImages, setNumImages] = useState(1);
const [isGenerating, setIsGenerating] = useState(false);
const [generatedImages, setGeneratedImages] = useState<GeneratedImage[]>([]);
// 配置选项
const [models, setModels] = useState<ConfigOption[]>([]);
const [templates, setTemplates] = useState<ConfigOption[]>([]);
const [styles, setStyles] = useState<ConfigOption[]>([]);
const [sizes, setSizes] = useState<ConfigOption[]>([]);
// 加载配置选项
useEffect(() => {
const loadConfigs = async () => {
try {
const [modelsData, templatesData, stylesData, sizesData] = await Promise.all([
imageAPI.getModels(),
imageAPI.getTemplates(),
imageAPI.getStyles(),
imageAPI.getSizes(),
]);
setModels(modelsData);
setTemplates(templatesData);
setStyles(stylesData);
setSizes(sizesData);
} catch (error) {
console.error("加载配置失败:", error);
toast.error("加载配置失败");
}
};
loadConfigs();
}, []);
const handleGenerate = async () => {
if (!prompt.trim()) {
toast.error("请输入图像描述");
return;
}
setIsGenerating(true);
try {
const response = await imageAPI.textToImage({
prompt,
model,
template,
style,
size,
num_images: numImages,
});
setGeneratedImages(response.images);
toast.success(`成功生成 ${response.total} 张图像`);
} catch (error) {
console.error("生成图像失败:", error);
toast.error("生成图像失败,请重试");
} finally {
setIsGenerating(false);
}
};
const handleDownload = (imageUrl: string, imageId: string) => {
const link = document.createElement("a");
link.href = imageUrl;
link.download = `generated-image-${imageId}.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
toast.success("图像下载成功");
};
const handleCopyPrompt = (prompt: string) => {
navigator.clipboard.writeText(prompt);
toast.success("提示词已复制到剪贴板");
};
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
<div className="container mx-auto px-4 py-8">
{/* 页面标题 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="text-center mb-8"
>
<h1 className="text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-4">
- Text to Image
</h1>
<p className="text-lg text-gray-600 max-w-2xl mx-auto">
使AI模型
</p>
</motion.div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* 左侧:生成配置 */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5, delay: 0.1 }}
className="lg:col-span-1"
>
<Card className="sticky top-8">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Sparkles className="h-5 w-5 text-blue-600" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* 模型选择 */}
<div className="space-y-2">
<Label htmlFor="model">AI模型</Label>
<Select value={model} onValueChange={setModel}>
<SelectTrigger>
<SelectValue placeholder="选择模型" />
</SelectTrigger>
<SelectContent>
{models.map((option) => (
<SelectItem key={option.id} value={option.id}>
<div>
<div className="font-medium">{option.name}</div>
<div className="text-sm text-gray-500">{option.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 提示词模板 */}
<div className="space-y-2">
<Label htmlFor="template"></Label>
<Select value={template} onValueChange={setTemplate}>
<SelectTrigger>
<SelectValue placeholder="选择模板" />
</SelectTrigger>
<SelectContent>
{templates.map((option) => (
<SelectItem key={option.id} value={option.id}>
<div>
<div className="font-medium">{option.name}</div>
<div className="text-sm text-gray-500">{option.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 图像描述 */}
<div className="space-y-2">
<Label htmlFor="prompt"></Label>
<Textarea
id="prompt"
placeholder="描述您想要生成的图像,例如:城市中心区商业综合体规划,包含商业区、办公区、绿地..."
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={4}
className="resize-none"
/>
</div>
{/* 风格选择 */}
<div className="space-y-2">
<Label htmlFor="style"></Label>
<Select value={style} onValueChange={setStyle}>
<SelectTrigger>
<SelectValue placeholder="选择风格" />
</SelectTrigger>
<SelectContent>
{styles.map((option) => (
<SelectItem key={option.id} value={option.id}>
<div>
<div className="font-medium">{option.name}</div>
<div className="text-sm text-gray-500">{option.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 尺寸选择 */}
<div className="space-y-2">
<Label htmlFor="size"></Label>
<Select value={size} onValueChange={setSize}>
<SelectTrigger>
<SelectValue placeholder="选择尺寸" />
</SelectTrigger>
<SelectContent>
{sizes.map((option) => (
<SelectItem key={option.id} value={option.id}>
<div>
<div className="font-medium">{option.name}</div>
<div className="text-sm text-gray-500">{option.description}</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 生成数量 */}
<div className="space-y-2">
<Label htmlFor="numImages"></Label>
<Select value={numImages.toString()} onValueChange={(value) => setNumImages(parseInt(value))}>
<SelectTrigger>
<SelectValue placeholder="选择数量" />
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 4].map((num) => (
<SelectItem key={num} value={num.toString()}>
{num}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Separator />
{/* 生成按钮 */}
<Button
onClick={handleGenerate}
disabled={isGenerating || !prompt.trim()}
className="w-full"
size="lg"
>
{isGenerating ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : (
<>
<ImageIcon className="mr-2 h-4 w-4" />
</>
)}
</Button>
</CardContent>
</Card>
</motion.div>
{/* 右侧:生成结果 */}
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5, delay: 0.2 }}
className="lg:col-span-2"
>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ImageIcon className="h-5 w-5 text-green-600" />
</CardTitle>
<CardDescription>
{generatedImages.length > 0
? `已生成 ${generatedImages.length} 张图像`
: "生成图像将显示在这里"
}
</CardDescription>
</CardHeader>
<CardContent>
{generatedImages.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{generatedImages.map((image, index) => (
<motion.div
key={image.id}
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3, delay: index * 0.1 }}
className="group relative"
>
<Card className="overflow-hidden">
<div className="aspect-square relative">
<img
src={image.url}
alt={`Generated image ${index + 1}`}
className="w-full h-full object-cover"
/>
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all duration-200" />
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<div className="flex gap-1">
<Button
size="sm"
variant="secondary"
onClick={() => handleDownload(image.url, image.id)}
>
<Download className="h-3 w-3" />
</Button>
<Button
size="sm"
variant="secondary"
onClick={() => handleCopyPrompt(image.prompt)}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
</div>
<CardContent className="p-4">
<div className="space-y-2">
<div className="flex items-center gap-2">
<Badge variant="outline">{image.model}</Badge>
<Badge variant="secondary">{image.metadata?.style || style}</Badge>
</div>
<p className="text-sm text-gray-600 line-clamp-2">
{image.prompt}
</p>
</div>
</CardContent>
</Card>
</motion.div>
))}
</div>
) : (
<div className="text-center py-12">
<ImageIcon className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<p className="text-gray-500"></p>
<p className="text-sm text-gray-400">"生成图像"</p>
</div>
)}
</CardContent>
</Card>
</motion.div>
</div>
</div>
</div>
);
}
+229
View File
@@ -0,0 +1,229 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { knowledgeBaseAPI } from "@/lib/api";
import { KnowledgeBase } from "@/types";
import { BookOpen, CheckCircle, Clock, Loader2 } from "lucide-react";
export default function TestKnowledgeBasePage() {
const router = useRouter();
const { isAuthenticated, isLoading: authLoading } = useAuthStore();
const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [testResults, setTestResults] = useState<string[]>([]);
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
return;
}
if (isAuthenticated) {
loadKnowledgeBases();
}
}, [isAuthenticated, authLoading, router]);
const loadKnowledgeBases = async () => {
try {
setIsLoading(true);
setError(null);
const bases = await knowledgeBaseAPI.getKnowledgeBases();
setKnowledgeBases(bases);
addTestResult("✅ 成功加载知识库列表");
} catch (err) {
console.error("加载知识库失败:", err);
setError("加载知识库失败");
addTestResult("❌ 加载知识库失败");
} finally {
setIsLoading(false);
}
};
const addTestResult = (result: string) => {
setTestResults(prev => [...prev, `${new Date().toLocaleTimeString()}: ${result}`]);
};
const testCreateKnowledgeBase = async () => {
try {
addTestResult("🔄 开始创建测试知识库...");
const newKB = await knowledgeBaseAPI.createKnowledgeBase({
name: `测试知识库_${Date.now()}`,
description: "这是一个测试知识库"
});
addTestResult(`✅ 成功创建知识库: ${newKB.name}`);
await loadKnowledgeBases();
} catch (err) {
console.error("创建知识库失败:", err);
addTestResult("❌ 创建知识库失败");
}
};
const testDeleteKnowledgeBase = async (kbId: number) => {
try {
addTestResult(`🔄 开始删除知识库 ${kbId}...`);
await knowledgeBaseAPI.deleteKnowledgeBase(kbId.toString());
addTestResult(`✅ 成功删除知识库 ${kbId}`);
await loadKnowledgeBases();
} catch (err) {
console.error("删除知识库失败:", err);
addTestResult(`❌ 删除知识库失败: ${kbId}`);
}
};
if (authLoading || isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<div className="min-h-screen bg-app pb-16 lg:pb-0">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* 页面头部 */}
<div className="mb-8">
<h1 className="text-3xl font-bold mb-2"></h1>
<p className="text-muted-foreground">API调用</p>
</div>
{/* 错误提示 */}
{error && (
<Alert variant="destructive" className="mb-6">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 测试操作 */}
<Card className="mb-8 backdrop-blur-sm bg-card/80 border-border/50 shadow-xl">
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="flex space-x-4">
<Button onClick={testCreateKnowledgeBase}>
</Button>
<Button onClick={loadKnowledgeBases} variant="outline">
</Button>
</div>
</CardContent>
</Card>
{/* 测试结果 */}
<Card className="mb-8 backdrop-blur-sm bg-card/80 border-border/50 shadow-xl">
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2 max-h-64 overflow-y-auto">
{testResults.length === 0 ? (
<p className="text-muted-foreground"></p>
) : (
testResults.map((result, index) => (
<div key={index} className="text-sm font-mono">
{result}
</div>
))
)}
</div>
</CardContent>
</Card>
{/* 知识库列表 */}
<Card className="backdrop-blur-sm bg-card/80 border-border/50 shadow-xl">
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
{knowledgeBases.length === 0 ? (
<div className="text-center py-8">
<BookOpen className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-medium mb-2"></h3>
<p className="text-muted-foreground">"创建测试知识库"</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{knowledgeBases.map((kb) => (
<Card key={kb.id} className="hover:shadow-lg transition-shadow">
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex items-center space-x-2">
<BookOpen className="w-5 h-5 text-blue-600" />
<div>
<CardTitle className="text-lg">{kb.name}</CardTitle>
<CardDescription className="text-sm">
{kb.description || "暂无描述"}
</CardDescription>
</div>
</div>
<div className="flex items-center space-x-1">
{kb.document_count > 0 ? (
<CheckCircle className="w-4 h-4 text-green-600" />
) : (
<Clock className="w-4 h-4 text-gray-400" />
)}
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between text-sm text-muted-foreground">
<span></span>
<span>{kb.document_count} </span>
</div>
<div className="flex justify-between text-sm text-muted-foreground">
<span></span>
<span>{new Date(new Date(kb.created_at).getTime() + 8 * 60 * 60 * 1000).toLocaleDateString("zh-CN")}</span>
</div>
<div className="flex justify-between text-sm">
<span></span>
<span className={kb.document_count > 0 ? "text-green-600" : "text-gray-500"}>
{kb.document_count > 0 ? "已就绪" : "空知识库"}
</span>
</div>
</div>
<div className="flex space-x-2 mt-4">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => router.push(`/knowledge/${kb.id}`)}
>
</Button>
<Button
variant="outline"
size="sm"
onClick={() => testDeleteKnowledgeBase(kb.id)}
className="text-red-600 hover:text-red-700"
>
</Button>
</div>
</CardContent>
</Card>
))}
</div>
)}
</CardContent>
</Card>
</div>
</div>
);
}
+218
View File
@@ -0,0 +1,218 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { forumAPI } from "@/lib/api";
import type { ForumCategory, ForumPostSummary } from "@/types";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Loader2, MessageCircle } from "lucide-react";
import { useAuthStore } from "@/store/auth";
export default function ForumCategoryPage() {
const params = useParams();
const router = useRouter();
const categoryId = Number(params?.categoryId);
const [categories, setCategories] = useState<ForumCategory[]>([]);
const [posts, setPosts] = useState<ForumPostSummary[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const [submitError, setSubmitError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const { isAuthenticated } = useAuthStore();
const currentCategory = useMemo(
() => categories.find((cat) => cat.id === categoryId),
[categories, categoryId]
);
useEffect(() => {
if (!categoryId) {
setError("无效的分类编号");
setIsLoading(false);
return;
}
const loadData = async () => {
try {
setIsLoading(true);
const [cats, postList] = await Promise.all([
forumAPI.getCategories(),
forumAPI.getPosts(categoryId),
]);
setCategories(cats);
setPosts(postList);
setError(null);
} catch (err) {
const message = err instanceof Error ? err.message : "加载帖子失败";
setError(message);
} finally {
setIsLoading(false);
}
};
loadData();
}, [categoryId]);
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
if (!title.trim() || !content.trim()) {
setSubmitError("标题和内容不能为空");
return;
}
try {
setIsSubmitting(true);
setSubmitError(null);
await forumAPI.createPost(categoryId, {
title: title.trim(),
content: content.trim(),
});
setTitle("");
setContent("");
const updatedPosts = await forumAPI.getPosts(categoryId);
setPosts(updatedPosts);
} catch (err) {
const message = err instanceof Error ? err.message : "发布帖子失败";
setSubmitError(message);
} finally {
setIsSubmitting(false);
}
};
return (
<div className="min-h-screen bg-app py-10">
<div className="max-w-5xl mx-auto px-4 space-y-6">
<Button variant="ghost" onClick={() => router.push("/forum")} className="px-0">
</Button>
<div className="space-y-2">
<h1 className="text-2xl font-semibold flex items-center gap-2">
<MessageCircle className="h-6 w-6 text-primary" />
{currentCategory ? currentCategory.name : "论坛分类"}
</h1>
{currentCategory?.description && (
<p className="text-muted-foreground">{currentCategory.description}</p>
)}
</div>
{isLoading ? (
<div className="flex items-center justify-center gap-2 text-muted-foreground py-20">
<Loader2 className="h-4 w-4 animate-spin" />
...
</div>
) : error ? (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
) : (
<div className="grid gap-6 lg:grid-cols-[2fr,3fr]">
<div className="space-y-4">
{isAuthenticated ? (
<Card className="shadow-md">
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
{submitError && (
<Alert variant="destructive">
<AlertDescription>{submitError}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<label className="text-sm font-medium text-foreground/80"></label>
<Input
value={title}
onChange={(event) => setTitle(event.target.value)}
placeholder="写一个简洁的标题"
maxLength={200}
disabled={isSubmitting}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-foreground/80"></label>
<Textarea
value={content}
onChange={(event) => setContent(event.target.value)}
placeholder="详细描述你的想法或问题..."
rows={8}
className="min-h-[220px] resize-none"
disabled={isSubmitting}
/>
</div>
<div className="text-right">
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
...
</>
) : (
"发布帖子"
)}
</Button>
</div>
</form>
</CardContent>
</Card>
) : (
<Alert>
<AlertDescription>
<Link href="/login" className="underline ml-1">
</Link>
<Link href="/register" className="underline ml-1">
</Link>
</AlertDescription>
</Alert>
)}
</div>
<div className="space-y-3">
{posts.length === 0 ? (
<Card className="shadow-sm">
<CardContent className="py-6 text-sm text-muted-foreground text-center">
</CardContent>
</Card>
) : (
posts.map((post) => (
<Card key={post.id} className="shadow-sm transition hover:shadow-lg">
<CardHeader>
<CardTitle className="text-lg">
<Link href={`/forum/post/${post.id}`} className="hover:underline">
{post.title}
</Link>
</CardTitle>
<CardDescription>
{post.author_name} · {post.reply_count} ·{" "}
{new Date(new Date(post.created_at).getTime() + 8 * 60 * 60 * 1000).toLocaleString()}
</CardDescription>
</CardHeader>
</Card>
))
)}
</div>
</div>
)}
</div>
</div>
);
}
+189
View File
@@ -0,0 +1,189 @@
"use client";
import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { forumAPI } from "@/lib/api";
import type { ForumPostDetail } from "@/types";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Loader2, MessageCircleReply } from "lucide-react";
import { useAuthStore } from "@/store/auth";
export default function ForumPostPage() {
const params = useParams();
const router = useRouter();
const postId = Number(params?.postId);
const [post, setPost] = useState<ForumPostDetail | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [replyContent, setReplyContent] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const { isAuthenticated } = useAuthStore();
useEffect(() => {
if (!postId) {
setError("无效的帖子编号");
setIsLoading(false);
return;
}
const loadPost = async () => {
try {
setIsLoading(true);
const detail = await forumAPI.getPost(postId);
setPost(detail);
setError(null);
} catch (err) {
const message = err instanceof Error ? err.message : "加载帖子详情失败";
setError(message);
} finally {
setIsLoading(false);
}
};
loadPost();
}, [postId]);
const handleReply = async (event: React.FormEvent) => {
event.preventDefault();
if (!replyContent.trim()) {
setSubmitError("回复内容不能为空");
return;
}
try {
setIsSubmitting(true);
setSubmitError(null);
await forumAPI.createReply(postId, replyContent.trim());
setReplyContent("");
const detail = await forumAPI.getPost(postId);
setPost(detail);
} catch (err) {
const message = err instanceof Error ? err.message : "回复失败";
setSubmitError(message);
} finally {
setIsSubmitting(false);
}
};
return (
<div className="min-h-screen bg-app py-10">
<div className="max-w-4xl mx-auto px-4 space-y-6">
<Button variant="ghost" onClick={() => router.back()} className="px-0">
</Button>
{isLoading ? (
<div className="flex items-center justify-center gap-2 text-muted-foreground py-20">
<Loader2 className="h-4 w-4 animate-spin" />
...
</div>
) : error ? (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
) : post ? (
<div className="space-y-6">
<Card className="shadow-md">
<CardHeader>
<CardTitle className="text-2xl font-semibold">{post.title}</CardTitle>
<p className="text-sm text-muted-foreground">
{post.author_name} ·{" "}
{new Date(new Date(post.created_at).getTime() + 8 * 60 * 60 * 1000).toLocaleString()}
</p>
</CardHeader>
<CardContent className="whitespace-pre-wrap leading-relaxed text-foreground/90">
{post.content}
</CardContent>
</Card>
<section className="space-y-4">
<h2 className="text-lg font-medium flex items-center gap-2">
<MessageCircleReply className="h-5 w-5 text-primary" />
{post.replies.length}
</h2>
{post.replies.length === 0 ? (
<Card className="text-sm text-muted-foreground">
<CardContent className="py-4">
</CardContent>
</Card>
) : (
post.replies.map((reply) => (
<Card key={reply.id} className="shadow-sm">
<CardHeader className="pb-2">
<div className="text-sm font-medium text-foreground">{reply.author_name}</div>
<div className="text-xs text-muted-foreground">
{new Date(new Date(reply.created_at).getTime() + 8 * 60 * 60 * 1000).toLocaleString()}
</div>
</CardHeader>
<CardContent className="text-sm whitespace-pre-wrap leading-relaxed">
{reply.content}
</CardContent>
</Card>
))
)}
</section>
<Card className="shadow-sm">
<CardContent className="py-6">
{isAuthenticated ? (
<form onSubmit={handleReply} className="space-y-4">
{submitError && (
<Alert variant="destructive">
<AlertDescription>{submitError}</AlertDescription>
</Alert>
)}
<Textarea
value={replyContent}
onChange={(event) => setReplyContent(event.target.value)}
placeholder="写下你的想法..."
rows={5}
className="resize-none"
disabled={isSubmitting}
/>
<div className="text-right">
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
...
</>
) : (
"提交回复"
)}
</Button>
</div>
</form>
) : (
<Alert>
<AlertDescription>
<Link href="/login" className="underline mx-1">
</Link>
<Link href="/register" className="underline ml-1">
</Link>
</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
</div>
) : null}
</div>
</div>
);
}
+332
View File
@@ -0,0 +1,332 @@
@import "tailwindcss";
@import "tw-animate-css";
@plugin "@tailwindcss/typography";
@custom-variant dark (&:is(.dark *));
@theme {
--font-sans:
ui-sans-serif, system-ui, sans-serif,
"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
--animate-fade-in: fade-in 1s;
@keyframes fade-in {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
--animate-spotlight: spotlight 2s ease 0.75s 1 forwards;
@keyframes spotlight {
0% {
opacity: 0;
transform: translate(-72%, -62%) scale(0.5);
}
to {
opacity: 1;
transform: translate(-50%, -40%) scale(1);
}
}
}
@theme inline {
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-app: var(--app-background);
--color-brand: var(--brand);
--animate-aurora: aurora 8s ease-in-out infinite alternate;
@keyframes aurora {
0% {
background-position: 0% 50%;
transform: rotate(-5deg) scale(0.9);
}
25% {
background-position: 50% 100%;
transform: rotate(5deg) scale(1.1);
}
50% {
background-position: 100% 50%;
transform: rotate(-3deg) scale(0.95);
}
75% {
background-position: 50% 0%;
transform: rotate(3deg) scale(1.05);
}
100% {
background-position: 0% 50%;
transform: rotate(-5deg) scale(0.9);
}
}
--animate-shine: shine var(--duration) infinite linear;
@keyframes shine {
0% {
background-position: 0% 0%;
}
50% {
background-position: 100% 100%;
}
to {
background-position: 0% 0%;
}
}
}
:root {
--radius: 0.625rem;
--app-background: #ffffff;
/* MIT 风格配色 - 简洁的灰度系统 */
--background: #ffffff;
--foreground: #000000;
--card: #ffffff;
--card-foreground: #000000;
--popover: #ffffff;
--popover-foreground: #000000;
--primary: #2563eb;
--primary-foreground: #ffffff;
--secondary: #f5f5f5;
--secondary-foreground: #000000;
--muted: #f5f5f5;
--muted-foreground: #6b7280;
--accent: #f3f4f6;
--accent-foreground: #111827;
--destructive: #dc2626;
--destructive-foreground: #ffffff;
--border: #e5e7eb;
--input: #ffffff;
--ring: #2563eb;
--chart-1: #2563eb;
--chart-2: #059669;
--chart-3: #dc2626;
--chart-4: #7c3aed;
--chart-5: #ea580c;
--brand: #2563eb;
}
.dark {
--app-background: #111827;
/* 深色模式保持同样的简洁风格 */
--background: #111827;
--foreground: #f9fafb;
--card: #1f2937;
--card-foreground: #f9fafb;
--popover: #1f2937;
--popover-foreground: #f9fafb;
--primary: #3b82f6;
--primary-foreground: #ffffff;
--secondary: #374151;
--secondary-foreground: #f9fafb;
--muted: #1f2937;
--muted-foreground: #9ca3af;
--accent: #374151;
--accent-foreground: #f9fafb;
--destructive: #ef4444;
--destructive-foreground: #ffffff;
--border: #374151;
--input: #1f2937;
--ring: #3b82f6;
--chart-1: #3b82f6;
--chart-2: #10b981;
--chart-3: #ef4444;
--chart-4: #8b5cf6;
--chart-5: #f97316;
--brand: #3b82f6;
}
@layer base {
* {
border-color: hsl(var(--border));
}
body {
background-color: hsl(var(--app-background));
color: hsl(var(--foreground));
font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
line-height: 1.6;
}
/* MIT 风格的字体层次 */
h1 {
font-size: 2.5rem;
font-weight: 700;
line-height: 1.2;
letter-spacing: -0.025em;
}
h2 {
font-size: 2rem;
font-weight: 600;
line-height: 1.3;
letter-spacing: -0.025em;
}
h3 {
font-size: 1.5rem;
font-weight: 600;
line-height: 1.4;
}
h4 {
font-size: 1.25rem;
font-weight: 500;
line-height: 1.5;
}
h5 {
font-size: 1.125rem;
font-weight: 500;
line-height: 1.5;
}
h6 {
font-size: 1rem;
font-weight: 500;
line-height: 1.5;
}
small {
font-size: 0.875rem;
line-height: 1.4;
}
}
/* MIT 风格实用工具类 */
@layer utilities {
/* 移动端优化 */
.mobile-safe-area {
padding-top: env(safe-area-inset-top);
padding-bottom: env(safe-area-inset-bottom);
}
.text-balance {
text-wrap: balance;
}
/* MIT 风格布局 */
.mit-container {
max-width: 80rem; /* 1280px */
margin-left: auto;
margin-right: auto;
padding-left: 1rem;
padding-right: 1rem;
}
@media (min-width: 640px) {
.mit-container {
padding-left: 1.5rem;
padding-right: 1.5rem;
}
}
@media (min-width: 1024px) {
.mit-container {
padding-left: 2rem;
padding-right: 2rem;
}
}
/* MIT 风格卡片 */
.mit-card {
background-color: hsl(var(--card));
border: 1px solid hsl(var(--border));
border-radius: 0.5rem;
padding: 1.5rem;
transition: all 0.2s ease-in-out;
}
.mit-card:hover {
transform: translateY(-2px);
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}
/* MIT 风格网格 */
.mit-grid {
display: grid;
gap: 1.5rem;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}
@media (min-width: 768px) {
.mit-grid {
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
}
}
@media (min-width: 1024px) {
.mit-grid {
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
}
}
/* MIT 风格按钮 */
.mit-button {
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 0.375rem;
font-size: 0.875rem;
font-weight: 500;
transition: all 0.2s ease-in-out;
cursor: pointer;
border: none;
outline: none;
}
.mit-button-primary {
background-color: hsl(var(--primary));
color: hsl(var(--primary-foreground));
padding: 0.5rem 1rem;
}
.mit-button-primary:hover {
background-color: hsl(var(--primary) / 0.9);
}
.mit-button-secondary {
background-color: hsl(var(--secondary));
color: hsl(var(--secondary-foreground));
padding: 0.5rem 1rem;
}
.mit-button-secondary:hover {
background-color: hsl(var(--secondary) / 0.8);
}
}
input,
textarea {
outline: none;
}
[role="button"],
button {
cursor: pointer;
}
+52
View File
@@ -0,0 +1,52 @@
import type { Metadata, Viewport } from "next";
import { Inter } from "next/font/google";
import { ThemeProvider } from "next-themes";
import { Toaster } from "sonner";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "国土空间规划课程智能体",
description: "基于大模型的国土空间规划课程智能问答系统",
keywords: ["国土空间规划", "智能问答", "AI", "教育"],
authors: [{ name: "哈尔滨工业大学建筑与设计学院 国土空间与区域发展研究所" }],
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="zh-CN" suppressHydrationWarning>
<body className={inter.className}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
<Toaster
position="top-right"
expand={true}
richColors={true}
closeButton={true}
/>
</ThemeProvider>
</body>
</html>
);
}
+23
View File
@@ -0,0 +1,23 @@
"use client";
import { useEffect } from "react";
import { useAuthStore } from "@/store/auth";
import { useRouter } from "next/navigation";
import LoadingSpinner from "@/components/ui/loading-spinner";
import HomePageContent from "@/components/home/home-page-content";
export default function HomePage() {
const { isAuthenticated, isLoading } = useAuthStore();
const router = useRouter();
// 如果正在加载认证状态,显示加载动画
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<LoadingSpinner size="lg" />
</div>
);
}
return <HomePageContent />;
}
+422
View File
@@ -0,0 +1,422 @@
"use client";
import { useState, useRef, useEffect } from "react";
import { useChatStore } from "@/store/chat";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Send, Loader2, Bot, User, StopCircle, ArrowDown, Paperclip } from "lucide-react";
import MessageList from "./message-list";
import QuickQuestions from "./quick-questions";
import ModeSelector, { ChatMode } from "./mode-selector";
import ModelSelector from "./model-selector";
import KnowledgeSelector, { KnowledgeBase } from "./knowledge-selector";
import { cn } from "@/lib/utils";
import { knowledgeBaseAPI } from "@/lib/api";
export default function ChatInterface() {
const [inputMessage, setInputMessage] = useState("");
const [isComposing, setIsComposing] = useState(false);
const [chatMode, setChatMode] = useState<ChatMode>("normal");
const [selectedModel, setSelectedModel] = useState("deepseek-ai/DeepSeek-V3");
const [selectedKnowledgeBases, setSelectedKnowledgeBases] = useState<string[]>([]);
const [systemKnowledgeBases, setSystemKnowledgeBases] = useState<KnowledgeBase[]>([]);
const [userKnowledgeBases, setUserKnowledgeBases] = useState<KnowledgeBase[]>([]);
const inputRef = useRef<HTMLInputElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const {
currentSession,
messages,
isLoading,
isStreaming,
sendMessage,
streamMessage,
stopGeneration,
createSession,
selectSession,
} = useChatStore();
// 调试日志
useEffect(() => {
console.log("[DEBUG-CHAT-INTERFACE] 组件状态:", {
currentSession: currentSession?.id,
messagesCount: messages.length,
isLoading,
isStreaming,
messages: messages.map(m => ({ id: m.id, role: m.role, contentLength: m.content.length }))
});
}, [currentSession, messages, isLoading, isStreaming]);
// 自动滚动到底部
useEffect(() => {
messagesEndRef.current?.scrollIntoView({
behavior: isStreaming ? "auto" : "smooth"
});
}, [messages, isStreaming]);
// 加载知识库(区分系统知识库和用户知识库)
useEffect(() => {
const loadKnowledgeBases = async () => {
try {
const bases = await knowledgeBaseAPI.getKnowledgeBases();
console.log("[DEBUG] 加载的知识库:", bases.map(kb => ({
id: kb.id,
name: kb.name,
is_system: kb.is_system
})));
// 转换为KnowledgeSelector需要的格式
const formattedBases: KnowledgeBase[] = bases.map(kb => ({
id: kb.id.toString(),
name: kb.name,
description: kb.description || "",
documentCount: kb.document_count,
enabled: true, // 默认启用
isSystem: kb.is_system === true, // 明确检查是否为 true
}));
// 分离系统知识库和用户知识库
const systemBases = formattedBases.filter(kb => kb.isSystem === true);
const userBases = formattedBases.filter(kb => kb.isSystem !== true);
console.log("[DEBUG] 系统知识库:", systemBases.map(kb => ({ id: kb.id, name: kb.name })));
console.log("[DEBUG] 用户知识库:", userBases.map(kb => ({ id: kb.id, name: kb.name })));
setSystemKnowledgeBases(systemBases);
setUserKnowledgeBases(userBases);
} catch (error) {
console.error("加载知识库失败:", error);
}
};
loadKnowledgeBases();
}, []);
const handleSendMessage = async () => {
if (!inputMessage.trim() || isLoading || isStreaming) return;
const message = inputMessage.trim();
setInputMessage("");
console.log("[DEBUG-CHAT] 发送消息:", {
message: message,
chatMode: chatMode,
selectedKnowledgeBases: selectedKnowledgeBases,
selectedModel: selectedModel,
currentSession: currentSession?.id
});
// 如果没有当前会话,先创建一个新会话
if (!currentSession) {
const newSession = await createSession("新对话");
if (newSession) {
await selectSession(newSession.id);
}
}
// 使用流式发送,传递聊天模式、选中的知识库ID和模型ID
await streamMessage(message, chatMode, selectedKnowledgeBases, selectedModel);
};
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
};
const handleQuickQuestion = async (question: string) => {
setInputMessage(question);
// 聚焦到输入框
setTimeout(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, 100);
};
// Debug logging
console.log("[CHAT-INTERFACE] Current state:", {
hasSession: !!currentSession,
sessionId: currentSession?.id,
messagesCount: messages.length
});
if (!currentSession) {
return (
<div className="flex-1 flex flex-col bg-background h-full">
{/* 上部:欢迎内容区域 - 使用 flex-1 + 可滚动 */}
<div className="flex-1 overflow-y-auto">
<div className="h-full flex items-center justify-center p-6">
<div className="text-center max-w-2xl px-4">
<div className="w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg">
<Bot className="w-8 h-8 text-white" />
</div>
<h3 className="text-2xl font-bold text-foreground mb-2">
使
</h3>
<p className="text-muted-foreground mb-6">
</p>
<QuickQuestions onSelect={handleQuickQuestion} />
</div>
</div>
</div>
{/* 底部:输入区域 - 不使用 sticky,直接作为 flex 子元素 */}
<div className="border-t border-border bg-card p-4 lg:p-6 flex-shrink-0">
{/* 功能选择器 */}
<div className="mb-4 space-y-3">
<div className="flex items-center space-x-2">
<ModeSelector mode={chatMode} onModeChange={setChatMode} />
<ModelSelector
selectedModel={selectedModel}
onModelChange={setSelectedModel}
className="flex-shrink-0"
/>
<KnowledgeSelector
selectedBases={selectedKnowledgeBases}
onBasesChange={setSelectedKnowledgeBases}
systemKnowledgeBases={systemKnowledgeBases}
userKnowledgeBases={userKnowledgeBases}
className="flex-shrink-0"
/>
<Button
variant="outline"
size="sm"
className="h-9 px-3 flex-shrink-0"
title="上传附件"
>
<Paperclip className="w-4 h-4" />
</Button>
</div>
</div>
{/* 输入框和发送按钮 */}
<div className="flex items-end space-x-3">
<div className="flex-1">
<div className="relative">
<Input
ref={inputRef}
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
onKeyPress={handleKeyPress}
onCompositionStart={() => setIsComposing(true)}
onCompositionEnd={() => setIsComposing(false)}
placeholder="输入您的问题..."
disabled={isLoading || isStreaming}
className={cn(
"min-h-[48px] resize-none touch-manipulation pr-12 rounded-xl",
"border-border/50 bg-background/80 backdrop-blur-sm",
"focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500/50",
"transition-all duration-200"
)}
/>
{isStreaming && (
<div className="absolute right-3 top-1/2 -translate-y-1/2">
<div className="flex items-center gap-1">
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" />
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }} />
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }} />
</div>
</div>
)}
</div>
</div>
<Button
onClick={handleSendMessage}
disabled={!inputMessage.trim() || isLoading || isStreaming}
size="icon"
className={cn(
"h-12 w-12 flex-shrink-0 touch-manipulation rounded-xl",
"bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700",
"shadow-lg hover:shadow-xl transition-all duration-200",
"disabled:opacity-50 disabled:cursor-not-allowed"
)}
>
{isLoading || isStreaming ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
<Send className="w-5 h-5" />
)}
</Button>
</div>
{/* 输入提示 */}
<div className="mt-3 flex items-center justify-between text-xs text-muted-foreground">
<span className="hidden sm:block"> Enter Shift + Enter </span>
<span className="sm:hidden"></span>
{isStreaming && (
<span className="flex items-center gap-1 text-blue-600">
<div className="w-1.5 h-1.5 bg-blue-500 rounded-full animate-pulse" />
...
</span>
)}
</div>
</div>
</div>
);
}
return (
<div className="flex-1 flex flex-col bg-background h-full">
{/* 聊天头部 - 不需要 sticky,作为 flex 子元素自然在顶部 */}
<div className="border-b border-border bg-card p-4 lg:p-6 flex-shrink-0">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg flex items-center justify-center flex-shrink-0 shadow-sm">
<Bot className="w-5 h-5 text-white" />
</div>
<div className="flex-1 min-w-0">
<h2 className="text-lg font-semibold text-foreground truncate">
{currentSession.title}
</h2>
</div>
</div>
{/* 操作按钮 */}
<div className="flex items-center gap-2">
{isStreaming && (
<Button
variant="outline"
size="sm"
onClick={stopGeneration}
className="text-red-600 hover:text-red-700 hover:bg-red-50"
>
<StopCircle className="w-4 h-4 mr-2" />
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })}
className="opacity-60 hover:opacity-100"
>
<ArrowDown className="w-4 h-4" />
</Button>
</div>
</div>
</div>
{/* 消息列表 - 使用 flex-1 占据剩余空间 + 可滚动 */}
<div className="flex-1 overflow-y-auto">
{messages.length === 0 ? (
<div className="h-full flex items-center justify-center p-6">
<div className="text-center max-w-2xl">
<div className="w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg">
<Bot className="w-8 h-8 text-white" />
</div>
<h3 className="text-2xl font-bold text-foreground mb-2">
</h3>
<p className="text-muted-foreground mb-6 max-w-lg mx-auto">
</p>
<QuickQuestions onSelect={handleQuickQuestion} />
</div>
</div>
) : (
<>
<MessageList messages={messages} />
<div ref={messagesEndRef} />
</>
)}
</div>
{/* 输入区域 - 不需要 sticky,作为 flex 子元素自然在底部 */}
<div className="border-t border-border bg-card p-4 lg:p-6 flex-shrink-0">
{/* 功能选择器 */}
<div className="mb-4 space-y-3">
<div className="flex items-center space-x-2">
<ModeSelector mode={chatMode} onModeChange={setChatMode} />
<ModelSelector
selectedModel={selectedModel}
onModelChange={setSelectedModel}
className="flex-shrink-0"
/>
<KnowledgeSelector
selectedBases={selectedKnowledgeBases}
onBasesChange={setSelectedKnowledgeBases}
systemKnowledgeBases={systemKnowledgeBases}
userKnowledgeBases={userKnowledgeBases}
className="flex-shrink-0"
/>
<Button
variant="outline"
size="sm"
className="h-9 px-3 flex-shrink-0"
title="上传附件"
>
<Paperclip className="w-4 h-4" />
</Button>
</div>
</div>
{/* 输入框和发送按钮 */}
<div className="flex items-end space-x-3">
<div className="flex-1">
<div className="relative">
<Input
ref={inputRef}
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
onKeyPress={handleKeyPress}
onCompositionStart={() => setIsComposing(true)}
onCompositionEnd={() => setIsComposing(false)}
placeholder="输入您的问题..."
disabled={isLoading || isStreaming}
className={cn(
"min-h-[48px] resize-none touch-manipulation pr-12 rounded-xl",
"border-border/50 bg-background/80 backdrop-blur-sm",
"focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500/50",
"transition-all duration-200"
)}
/>
{isStreaming && (
<div className="absolute right-3 top-1/2 -translate-y-1/2">
<div className="flex items-center gap-1">
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" />
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }} />
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }} />
</div>
</div>
)}
</div>
</div>
<Button
onClick={handleSendMessage}
disabled={!inputMessage.trim() || isLoading || isStreaming}
size="icon"
className={cn(
"h-12 w-12 flex-shrink-0 touch-manipulation rounded-xl",
"bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700",
"shadow-lg hover:shadow-xl transition-all duration-200",
"disabled:opacity-50 disabled:cursor-not-allowed"
)}
>
{isLoading || isStreaming ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
<Send className="w-5 h-5" />
)}
</Button>
</div>
{/* 输入提示 */}
<div className="mt-3 flex items-center justify-between text-xs text-muted-foreground">
<span className="hidden sm:block"> Enter Shift + Enter </span>
<span className="sm:hidden"></span>
{isStreaming && (
<span className="flex items-center gap-1 text-blue-600">
<div className="w-1.5 h-1.5 bg-blue-500 rounded-full animate-pulse" />
...
</span>
)}
</div>
</div>
</div>
);
}
+128
View File
@@ -0,0 +1,128 @@
"use client";
import { useState } from "react";
import { Download, FileText, FileJson, File } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { useChatStore } from "@/store/chat";
import { toast } from "sonner";
interface ExportDialogProps {
sessionId: number;
sessionTitle: string;
children: React.ReactNode;
onClose?: () => void;
}
export default function ExportDialog({ sessionId, sessionTitle, children, onClose }: ExportDialogProps) {
const [open, setOpen] = useState(false);
const [format, setFormat] = useState("json");
const [isExporting, setIsExporting] = useState(false);
const { exportSession } = useChatStore();
const handleClose = () => {
setOpen(false);
onClose?.();
};
const handleExport = async () => {
setIsExporting(true);
try {
await exportSession(sessionId, format);
handleClose();
toast.success("导出成功");
} catch (error) {
toast.error("导出失败");
} finally {
setIsExporting(false);
}
};
const formatOptions = [
{
value: "json",
label: "JSON 格式",
description: "完整的结构化数据,包含所有元数据",
icon: FileJson,
},
{
value: "markdown",
label: "Markdown 格式",
description: "可读性好的文本格式,适合分享",
icon: FileText,
},
{
value: "pdf",
label: "PDF 格式",
description: "适合打印和正式文档",
icon: File,
},
];
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children}
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
"{sessionTitle}"
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<RadioGroup value={format} onValueChange={setFormat}>
{formatOptions.map((option) => {
const Icon = option.icon;
return (
<div key={option.value} className="flex items-start space-x-3">
<RadioGroupItem value={option.value} id={option.value} />
<div className="flex-1">
<Label htmlFor={option.value} className="flex items-center gap-2 cursor-pointer">
<Icon className="h-4 w-4" />
<span className="font-medium">{option.label}</span>
</Label>
<p className="text-sm text-gray-500 mt-1">
{option.description}
</p>
</div>
</div>
);
})}
</RadioGroup>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleClose}>
</Button>
<Button onClick={handleExport} disabled={isExporting}>
{isExporting ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2" />
...
</>
) : (
<>
<Download className="h-4 w-4 mr-2" />
</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,259 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSeparator,
DropdownMenuCheckboxItem,
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import { ChevronDown, Database, FileText, BookOpen, Scale } from "lucide-react";
import { cn } from "@/lib/utils";
// 系统知识库图标映射
const getSystemKnowledgeBaseIcon = (name: string) => {
if (name.includes("法律法规")) return Scale;
if (name.includes("原理")) return BookOpen;
if (name.includes("案例")) return FileText;
return Database;
};
export interface KnowledgeBase {
id: string;
name: string;
description: string;
documentCount: number;
enabled: boolean;
isSystem?: boolean; // 是否为系统知识库
icon?: React.ComponentType<{ className?: string }>;
}
interface KnowledgeSelectorProps {
selectedBases: string[];
onBasesChange: (baseIds: string[]) => void;
systemKnowledgeBases?: KnowledgeBase[]; // 系统知识库列表(从后端动态加载)
userKnowledgeBases?: KnowledgeBase[]; // 用户的知识库列表
className?: string;
}
export default function KnowledgeSelector({
selectedBases,
onBasesChange,
systemKnowledgeBases = [],
userKnowledgeBases = [],
className
}: KnowledgeSelectorProps) {
const [isOpen, setIsOpen] = useState(false);
// 为系统知识库添加图标(如果还没有的话)
const systemBasesWithIcons = systemKnowledgeBases.map(kb => ({
...kb,
icon: kb.icon || getSystemKnowledgeBaseIcon(kb.name),
isSystem: true,
}));
// 合并系统知识库和用户知识库
const allKnowledgeBases = [
...systemBasesWithIcons,
...userKnowledgeBases.map(kb => ({
...kb,
isSystem: false, // 用户知识库标记为非系统
}))
];
const enabledBases = allKnowledgeBases.filter(base => base.enabled);
const selectedCount = selectedBases.length;
const totalEnabled = enabledBases.length;
const handleToggleBase = (baseId: string) => {
const newSelectedBases = selectedBases.includes(baseId)
? selectedBases.filter(id => id !== baseId)
: [...selectedBases, baseId];
onBasesChange(newSelectedBases);
};
const handleSelectAll = () => {
const allEnabledIds = enabledBases.map(base => base.id);
onBasesChange(allEnabledIds);
};
const handleSelectNone = () => {
onBasesChange([]);
};
return (
<DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className={cn(
"h-9 px-3 text-sm font-medium",
"border-border/50 bg-background/80 hover:bg-muted/50",
"transition-all duration-200",
className
)}
>
<Database className="w-4 h-4 mr-2" />
<span className="hidden sm:inline">
{selectedCount > 0 && `(${selectedCount})`}
</span>
<span className="sm:hidden">
{selectedCount > 0 && `(${selectedCount})`}
</span>
<ChevronDown className="w-3 h-3 ml-1 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-72">
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
</div>
<DropdownMenuSeparator />
{/* 快速操作 */}
<div className="px-2 py-1.5">
<div className="flex space-x-2">
<Button
variant="ghost"
size="sm"
onClick={handleSelectAll}
className="h-7 px-2 text-xs"
>
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleSelectNone}
className="h-7 px-2 text-xs"
>
</Button>
</div>
</div>
<DropdownMenuSeparator />
{/* 系统知识库 */}
{systemBasesWithIcons.length > 0 && (
<div className="px-2 py-1">
<div className="text-xs font-medium text-muted-foreground mb-2 flex items-center">
<Database className="w-3 h-3 mr-1" />
</div>
{systemBasesWithIcons.map((base) => {
const BaseIcon = base.icon || Database;
const isSelected = selectedBases.includes(base.id);
const isDisabled = !base.enabled;
return (
<DropdownMenuCheckboxItem
key={base.id}
checked={isSelected}
onCheckedChange={() => handleToggleBase(base.id)}
disabled={isDisabled}
className={cn(
"flex items-start space-x-3 p-3 cursor-pointer",
isDisabled && "opacity-50 cursor-not-allowed"
)}
>
<BaseIcon className="w-4 h-4 mt-0.5 flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-2">
<span className="font-medium text-sm">{base.name}</span>
{isSelected && (
<Badge variant="secondary" className="text-xs">
</Badge>
)}
{isDisabled && (
<Badge variant="outline" className="text-xs">
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground mt-0.5">
{base.description}
</p>
<div className="flex items-center space-x-1 mt-1">
<span className="text-xs text-muted-foreground">
{base.documentCount}
</span>
</div>
</div>
</DropdownMenuCheckboxItem>
);
})}
</div>
)}
{/* 用户知识库 */}
{userKnowledgeBases.length > 0 && (
<>
<DropdownMenuSeparator />
<div className="px-2 py-1">
<div className="text-xs font-medium text-muted-foreground mb-2 flex items-center">
<FileText className="w-3 h-3 mr-1" />
</div>
{userKnowledgeBases.map((base) => {
const isSelected = selectedBases.includes(base.id);
const isDisabled = !base.enabled;
return (
<DropdownMenuCheckboxItem
key={base.id}
checked={isSelected}
onCheckedChange={() => handleToggleBase(base.id)}
disabled={isDisabled}
className={cn(
"flex items-start space-x-3 p-3 cursor-pointer",
isDisabled && "opacity-50 cursor-not-allowed"
)}
>
<BookOpen className="w-4 h-4 mt-0.5 flex-shrink-0 text-green-500" />
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-2">
<span className="font-medium text-sm">{base.name}</span>
{isSelected && (
<Badge variant="secondary" className="text-xs">
</Badge>
)}
{isDisabled && (
<Badge variant="outline" className="text-xs">
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground mt-0.5">
{base.description}
</p>
<div className="flex items-center space-x-1 mt-1">
<span className="text-xs text-muted-foreground">
{base.documentCount}
</span>
</div>
</div>
</DropdownMenuCheckboxItem>
);
})}
</div>
</>
)}
{selectedCount > 0 && (
<>
<DropdownMenuSeparator />
<div className="px-2 py-1.5 text-xs text-muted-foreground text-center">
{selectedCount}
</div>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
);
}
+298
View File
@@ -0,0 +1,298 @@
"use client";
import { ChatMessage, ThinkingStep } from "@/types";
import { User, Bot, MoreVertical, ThumbsUp, ThumbsDown, Copy, Edit, RotateCcw, Trash2, Loader2, CheckCircle2, FileSearch, Brain, Sparkles } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { tomorrow } from "react-syntax-highlighter/dist/esm/styles/prism";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useChatStore } from "@/store/chat";
import SourceReferences from "./source-references";
import { useState } from "react";
import { toast } from "sonner";
interface MessageItemProps {
message: ChatMessage;
}
// 思考过程组件
const ThinkingProcess = ({ thinking }: { thinking: ThinkingStep[] }) => {
if (!thinking || thinking.length === 0) return null;
const getStageIcon = (stage: string) => {
switch (stage) {
case 'understanding': return <Brain className="h-4 w-4" />;
case 'retrieving': return <FileSearch className="h-4 w-4 animate-spin" />;
case 'retrieved': return <CheckCircle2 className="h-4 w-4 text-green-500" />;
case 'generating': return <Sparkles className="h-4 w-4 animate-pulse" />;
default: return <Loader2 className="h-4 w-4" />;
}
};
return (
<div className="mb-3 space-y-2 text-sm text-muted-foreground bg-muted/50 rounded-lg p-3">
{thinking.map((step, index) => (
<div key={index} className="flex items-center gap-2">
{getStageIcon(step.stage)}
<span>{step.message}</span>
{step.time && (
<span className="text-xs">({step.time}s)</span>
)}
</div>
))}
</div>
);
};
export default function MessageItem({ message }: MessageItemProps) {
const isUser = message.role === "user";
const isAssistant = message.role === "assistant";
const { editMessage, regenerateMessage, feedbackMessage, isStreaming } = useChatStore();
const [isEditing, setIsEditing] = useState(false);
const [editContent, setEditContent] = useState(message.content);
// 添加调试信息
console.log(`[DEBUG-MESSAGE] 渲染消息 ${message.id}:`, {
role: message.role,
contentLength: message.content.length,
contentPreview: message.content.substring(0, 50) + "..."
});
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(message.content);
toast.success("已复制到剪贴板");
} catch (error) {
toast.error("复制失败");
}
};
const handleEdit = () => {
setIsEditing(true);
};
const handleSaveEdit = async () => {
try {
await editMessage(message.id, editContent);
setIsEditing(false);
toast.success("消息已更新");
} catch (error) {
toast.error("编辑失败");
}
};
const handleCancelEdit = () => {
setEditContent(message.content);
setIsEditing(false);
};
const handleRegenerate = async () => {
try {
await regenerateMessage(message.id);
toast.success("正在重新生成回复");
} catch (error) {
toast.error("重新生成失败");
}
};
const handleFeedback = async (feedback: "like" | "dislike") => {
try {
await feedbackMessage(message.id, feedback);
toast.success("感谢您的反馈");
} catch (error) {
toast.error("反馈提交失败");
}
};
return (
<div className={`flex gap-3 p-4 ${isAssistant ? 'justify-start' : 'justify-end'}`}>
{isAssistant && (
<div className="flex-shrink-0">
<div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-blue-800 rounded-lg flex items-center justify-center shadow-sm">
<Bot className="w-4 h-4 text-white" />
</div>
</div>
)}
<div className={`flex-1 max-w-[80%] ${isAssistant ? '' : 'flex justify-end'}`}>
<div className={`mit-card ${isAssistant ? 'bg-card' : 'bg-primary text-primary-foreground'}`}>
{isEditing ? (
<div className="space-y-2">
<textarea
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
className="w-full p-2 border rounded resize-none"
rows={3}
/>
<div className="flex gap-2">
<Button size="sm" onClick={handleSaveEdit}>
</Button>
<Button size="sm" variant="outline" onClick={handleCancelEdit}>
</Button>
</div>
</div>
) : (
<>
{/* 思考过程组件 */}
{isAssistant && message.thinking && (
<ThinkingProcess thinking={message.thinking} />
)}
{/* 消息内容 */}
<div className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
code({ node, inline, className, children, ...props }: any) {
const match = /language-(\w+)/.exec(className || "");
return !inline && match ? (
<SyntaxHighlighter
style={tomorrow}
language={match[1]}
PreTag="div"
className="rounded-md"
{...props}
>
{String(children).replace(/\n$/, "")}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>
{children}
</code>
);
},
table: ({ children }) => (
<div className="overflow-x-auto">
<table className="min-w-full border-collapse border border-border">
{children}
</table>
</div>
),
th: ({ children }) => (
<th className="border border-border bg-muted px-3 py-2 text-left font-medium">
{children}
</th>
),
td: ({ children }) => (
<td className="border border-border px-3 py-2">
{children}
</td>
),
}}
>
{message.content}
</ReactMarkdown>
</div>
{/* 知识来源 */}
{isAssistant && message.metadata?.sources && message.metadata.sources.length > 0 && (
<div className="mt-4 pt-4 border-t border-border">
<SourceReferences sources={message.metadata.sources} maxSources={5} />
</div>
)}
</>
)}
</div>
{/* 操作按钮 */}
<div className={`flex items-center gap-1 mt-2 opacity-0 group-hover:opacity-100 transition-opacity ${
isAssistant ? "flex-row" : "flex-row-reverse"
}`}>
{/* 复制按钮 */}
<Button
size="sm"
variant="ghost"
onClick={handleCopy}
className="h-7 w-7 p-0 hover:bg-muted/50"
>
<Copy className="h-3 w-3" />
</Button>
{/* 用户消息操作 */}
{isUser && (
<Button
size="sm"
variant="ghost"
onClick={handleEdit}
className="h-7 w-7 p-0 hover:bg-muted/50"
>
<Edit className="h-3 w-3" />
</Button>
)}
{/* 助手消息操作 */}
{isAssistant && (
<>
<Button
size="sm"
variant="ghost"
onClick={handleRegenerate}
className="h-7 w-7 p-0 hover:bg-muted/50"
>
<RotateCcw className="h-3 w-3" />
</Button>
{/* 反馈按钮 */}
<div className="flex gap-1">
<Button
size="sm"
variant="ghost"
onClick={() => handleFeedback("like")}
className={`h-7 w-7 p-0 hover:bg-muted/50 ${
message.feedback === "like" ? "text-green-600" : ""
}`}
>
<ThumbsUp className="h-3 w-3" />
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => handleFeedback("dislike")}
className={`h-7 w-7 p-0 hover:bg-muted/50 ${
message.feedback === "dislike" ? "text-red-600" : ""
}`}
>
<ThumbsDown className="h-3 w-3" />
</Button>
</div>
</>
)}
</div>
{/* 时间戳和编辑标记 */}
<div className={`text-xs text-muted-foreground mt-1 ${
isUser ? "text-right" : "text-left"
}`}>
{message.created_at ? formatDistanceToNow(
new Date(new Date(message.created_at).getTime() + 8 * 60 * 60 * 1000),
{
addSuffix: true,
locale: zhCN
}) : '未知时间'}
{message.edited && (
<span className="ml-1 text-muted-foreground">()</span>
)}
</div>
</div>
{!isAssistant && (
<div className="flex-shrink-0">
<div className="w-8 h-8 bg-gradient-to-r from-gray-600 to-gray-800 rounded-lg flex items-center justify-center shadow-sm">
<User className="w-4 h-4 text-white" />
</div>
</div>
)}
</div>
);
}
+24
View File
@@ -0,0 +1,24 @@
"use client";
import { ChatMessage } from "@/types";
import MessageItem from "./message-item";
interface MessageListProps {
messages: ChatMessage[];
}
export default function MessageList({ messages }: MessageListProps) {
return (
<div className="space-y-4 p-4">
{messages.map((message) => (
<MessageItem key={message.id} message={message} />
))}
</div>
);
}
+73
View File
@@ -0,0 +1,73 @@
"use client";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ChevronDown, MessageSquare, Database } from "lucide-react";
export type ChatMode = "normal" | "rag";
interface ModeSelectorProps {
mode: ChatMode;
onModeChange: (mode: ChatMode) => void;
}
const modeConfig = {
normal: {
label: "普通对话",
icon: MessageSquare,
description: "基础AI对话"
},
rag: {
label: "知识库检索",
icon: Database,
description: "基于国土空间规划知识库"
}
};
export default function ModeSelector({ mode, onModeChange }: ModeSelectorProps) {
const currentMode = modeConfig[mode];
const Icon = currentMode.icon;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="gap-2">
<Icon className="h-4 w-4" />
<span>{currentMode.label}</span>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
{Object.entries(modeConfig).map(([key, config]) => {
const ModeIcon = config.icon;
return (
<DropdownMenuItem
key={key}
onClick={() => onModeChange(key as ChatMode)}
className="gap-2"
>
<ModeIcon className="h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">{config.label}</span>
<span className="text-xs text-muted-foreground">
{config.description}
</span>
</div>
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}
+121
View File
@@ -0,0 +1,121 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import { ChevronDown, Cpu, Zap, Sparkles } from "lucide-react";
import { cn } from "@/lib/utils";
export interface ModelOption {
id: string;
name: string;
description: string;
provider: string;
icon?: React.ComponentType<{ className?: string }>;
}
interface ModelSelectorProps {
selectedModel: string;
onModelChange: (modelId: string) => void;
className?: string;
}
const models: ModelOption[] = [
{
id: "deepseek-ai/DeepSeek-V3",
name: "DeepSeek-V3",
description: "DeepSeek 最新版本,强大的推理能力",
provider: "DeepSeek",
icon: Sparkles,
},
{
id: "Qwen/QwQ-32B",
name: "QwQ-32B",
description: "Qwen 量子化模型,高效推理",
provider: "Qwen",
icon: Zap,
},
];
export default function ModelSelector({
selectedModel,
onModelChange,
className
}: ModelSelectorProps) {
const [isOpen, setIsOpen] = useState(false);
const selectedModelData = models.find(model => model.id === selectedModel) || models[0];
const IconComponent = selectedModelData.icon || Cpu;
return (
<DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className={cn(
"h-9 px-3 text-sm font-medium",
"border-border/50 bg-background/80 hover:bg-muted/50",
"transition-all duration-200",
className
)}
>
<IconComponent className="w-4 h-4 mr-2" />
<span className="hidden sm:inline">{selectedModelData.name}</span>
<span className="sm:hidden">{selectedModelData.name.split(' ')[0]}</span>
<ChevronDown className="w-3 h-3 ml-1 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-64">
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
AI模型
</div>
<DropdownMenuSeparator />
{models.map((model) => {
const ModelIcon = model.icon || Cpu;
const isSelected = model.id === selectedModel;
return (
<DropdownMenuItem
key={model.id}
onClick={() => {
onModelChange(model.id);
setIsOpen(false);
}}
className={cn(
"flex items-start space-x-3 p-3 cursor-pointer",
isSelected && "bg-muted/50"
)}
>
<ModelIcon className="w-4 h-4 mt-0.5 flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-2">
<span className="font-medium text-sm">{model.name}</span>
{isSelected && (
<Badge variant="secondary" className="text-xs">
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground mt-0.5">
{model.description}
</p>
<div className="flex items-center space-x-1 mt-1">
<span className="text-xs text-muted-foreground">
{model.provider}
</span>
</div>
</div>
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,47 @@
"use client";
import { Button } from "@/components/ui/button";
import { MessageSquare } from "lucide-react";
interface QuickQuestionsProps {
onSelect: (question: string) => void;
}
const quickQuestions = [
"什么是国土空间规划?",
"国土空间规划的主要原则是什么?",
"如何进行国土空间规划编制?",
"国土空间规划与城市规划的区别?",
"国土空间规划中的三区三线是什么?",
"如何评价国土空间规划的合理性?",
];
export default function QuickQuestions({ onSelect }: QuickQuestionsProps) {
return (
<div className="space-y-4">
<div className="text-sm text-muted-foreground text-center">
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 max-w-4xl mx-auto">
{quickQuestions.map((question, index) => (
<Button
key={index}
variant="outline"
size="sm"
className="justify-start text-left h-auto p-4 hover:bg-muted/50 transition-colors"
onClick={() => onSelect(question)}
>
<MessageSquare className="w-4 h-4 mr-3 flex-shrink-0" />
<span className="text-sm leading-relaxed">{question}</span>
</Button>
))}
</div>
</div>
);
}
+334
View File
@@ -0,0 +1,334 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import { useChatStore } from "@/store/chat";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Plus,
MessageSquare,
Menu,
X,
Edit2,
Trash2,
Download,
MoreVertical,
Search,
Calendar,
Clock,
ChevronRight
} from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { toast } from "sonner";
import ExportDialog from "./export-dialog";
export default function Sidebar() {
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const [editingSession, setEditingSession] = useState<number | null>(null);
const [editTitle, setEditTitle] = useState("");
const [deleteSessionId, setDeleteSessionId] = useState<number | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const [openDropdownId, setOpenDropdownId] = useState<number | null>(null);
const router = useRouter();
const { sessions, currentSession, selectSession, createSession, renameSession, deleteSession } = useChatStore();
// 过滤会话(按创建时间排序)
const filteredSessions = () => {
if (!searchQuery) {
return sessions.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
}
return sessions
.filter(session =>
session.title.toLowerCase().includes(searchQuery.toLowerCase())
)
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
};
const handleNewChat = async () => {
const newSession = await createSession("新对话");
if (newSession) {
selectSession(newSession.id);
}
};
const handleSelectSession = async (sessionId: number) => {
await selectSession(sessionId);
setIsMobileMenuOpen(false);
};
const handleRenameSession = (sessionId: number, currentTitle: string) => {
setEditingSession(sessionId);
setEditTitle(currentTitle);
};
const handleSaveRename = async () => {
if (editingSession && editTitle.trim()) {
try {
await renameSession(editingSession, editTitle.trim());
setEditingSession(null);
setEditTitle("");
toast.success("会话重命名成功");
} catch (error) {
toast.error("重命名失败");
}
}
};
const handleCancelRename = () => {
setEditingSession(null);
setEditTitle("");
};
const handleDeleteSession = (sessionId: number) => {
setDeleteSessionId(sessionId);
};
const handleConfirmDelete = async () => {
if (deleteSessionId) {
try {
await deleteSession(deleteSessionId);
setDeleteSessionId(null);
toast.success("会话已删除");
} catch (error) {
toast.error("删除失败");
}
}
};
const handleCancelDelete = () => {
setDeleteSessionId(null);
};
const renderSessionItem = (session: any) => {
return (
<div
key={session.id}
className={`group relative flex items-center gap-3 px-3 py-2 rounded-lg cursor-pointer transition-all hover:bg-muted/50 ${
currentSession?.id === session.id ? 'bg-muted border border-border' : ''
}`}
onClick={() => handleSelectSession(session.id)}
>
<MessageSquare className="w-4 h-4 text-muted-foreground flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-foreground truncate">
{session.title}
</div>
<div className="text-xs text-muted-foreground">
{session.created_at ? (() => {
const rawDate = new Date(session.created_at);
const date = new Date(rawDate.getTime() + 8 * 60 * 60 * 1000);
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
if (date >= today) {
// 今天:只显示时间
return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', timeZone: 'Asia/Shanghai' });
} else {
// 昨天及更早:显示日期+时间
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
timeZone: 'Asia/Shanghai'
});
}
})() : '未知时间'}
</div>
</div>
{/* 操作按钮 */}
<DropdownMenu
open={openDropdownId === session.id}
onOpenChange={(open) => setOpenDropdownId(open ? session.id : null)}
>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="opacity-0 group-hover:opacity-100 transition-opacity h-6 w-6 p-0"
onClick={(e) => e.stopPropagation()}
>
<MoreVertical className="w-3 h-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
<DropdownMenuItem
onSelect={() => {
handleRenameSession(session.id, session.title);
}}
>
<Edit2 className="w-4 h-4 mr-2" />
</DropdownMenuItem>
<ExportDialog
sessionId={session.id}
sessionTitle={session.title}
onClose={() => setOpenDropdownId(null)}
>
<DropdownMenuItem onSelect={(e) => e.preventDefault()}>
<Download className="w-4 h-4 mr-2" />
</DropdownMenuItem>
</ExportDialog>
<DropdownMenuItem
onSelect={() => {
handleDeleteSession(session.id);
}}
className="text-destructive"
>
<Trash2 className="w-4 h-4 mr-2" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
);
};
return (
<>
{/* 移动端菜单按钮 */}
<div className="lg:hidden fixed top-4 left-4 z-50">
<Button
variant="outline"
size="icon"
onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
>
{isMobileMenuOpen ? <X className="w-4 h-4" /> : <Menu className="w-4 h-4" />}
</Button>
</div>
{/* 侧边栏 */}
<div className={`
fixed lg:static inset-y-0 left-0 z-40 w-80 max-w-[85vw] bg-card/50 backdrop-blur-sm border-r border-border transform transition-transform duration-300 ease-in-out mobile-safe-area lg:h-full
${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'}
`}>
<div className="flex flex-col h-full">
{/* 头部 */}
<div className="p-4 border-b">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold text-foreground"></h2>
<Button
onClick={handleNewChat}
size="sm"
className="h-8 px-3"
>
<Plus className="w-4 h-4 mr-1" />
</Button>
</div>
{/* 搜索框 */}
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="搜索对话..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9"
/>
</div>
</div>
{/* 会话列表 */}
<ScrollArea className="flex-1 px-2">
<div className="py-4">
<div className="space-y-1">
{filteredSessions().map(renderSessionItem)}
</div>
{sessions.length === 0 && (
<div className="text-center py-8">
<MessageSquare className="w-12 h-12 text-muted-foreground mx-auto mb-3" />
<p className="text-sm text-muted-foreground mb-2"></p>
<p className="text-xs text-muted-foreground"></p>
</div>
)}
</div>
</ScrollArea>
</div>
</div>
{/* 移动端遮罩 */}
{isMobileMenuOpen && (
<div
className="lg:hidden fixed inset-0 bg-black bg-opacity-50 z-30"
onClick={() => setIsMobileMenuOpen(false)}
/>
)}
{/* 重命名对话框 */}
<Dialog open={!!editingSession} onOpenChange={handleCancelRename}>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div className="py-4">
<Input
value={editTitle}
onChange={(e) => setEditTitle(e.target.value)}
placeholder="输入新的会话名称"
onKeyPress={(e) => {
if (e.key === 'Enter' && editTitle.trim()) {
handleSaveRename();
}
}}
autoFocus
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancelRename}>
</Button>
<Button onClick={handleSaveRename} disabled={!editTitle.trim()}>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 删除确认对话框 */}
<Dialog open={!!deleteSessionId} onOpenChange={() => setDeleteSessionId(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={handleCancelDelete}>
</Button>
<Button variant="destructive" onClick={handleConfirmDelete}>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,117 @@
"use client";
import { FileText, ExternalLink, Star, Database, Globe } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
interface SourceReference {
title: string;
filename?: string;
page?: number;
score?: number;
preview: string;
url?: string;
source_type?: "web" | "rag";
}
interface SourceReferencesProps {
sources: SourceReference[];
maxSources?: number;
}
export default function SourceReferences({ sources, maxSources = 5 }: SourceReferencesProps) {
if (!sources || sources.length === 0) {
return null;
}
const displaySources = sources.slice(0, maxSources);
const ragSources = displaySources.filter(s => s.source_type !== "web");
const webSources = displaySources.filter(s => s.source_type === "web");
return (
<div className="mt-4 space-y-3">
{ragSources.length > 0 && (
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm text-blue-600">
<Database className="h-4 w-4" />
<span> ({ragSources.length})</span>
</div>
<div className="space-y-2">
{ragSources.map((source, index) => (
<Card key={index} className="border border-blue-200 bg-blue-50/30 hover:border-blue-300 transition-colors">
<CardHeader className="pb-2">
<div className="flex items-start justify-between">
<CardTitle className="text-sm font-medium line-clamp-2">
{source.title}
</CardTitle>
{source.score != null && source.score > 0 && source.score < 1 && (
<div className="flex items-center gap-1 ml-2">
<Star className="h-3 w-3 text-yellow-500" />
<span className="text-xs text-gray-500">
{(source.score * 100).toFixed(1)}%
</span>
</div>
)}
</div>
<div className="text-xs text-gray-500">
{source.filename}
{source.page && ` • 第 ${source.page}`}
</div>
</CardHeader>
<CardContent className="pt-0">
<p className="text-xs text-gray-600 line-clamp-2">
{source.preview}
</p>
</CardContent>
</Card>
))}
</div>
</div>
)}
{webSources.length > 0 && (
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm text-green-600">
<Globe className="h-4 w-4" />
<span> ({webSources.length})</span>
</div>
<div className="space-y-2">
{webSources.map((source, index) => (
<Card key={index} className="border border-green-200 bg-green-50/30 hover:border-green-300 transition-colors">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium line-clamp-2">
{source.title}
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<p className="text-xs text-gray-600 line-clamp-2 mb-2">
{source.preview}
</p>
{source.url && (
<Button
size="sm"
variant="outline"
className="h-6 text-xs"
onClick={() => window.open(source.url, '_blank')}
>
<ExternalLink className="h-3 w-3 mr-1" />
</Button>
)}
</CardContent>
</Card>
))}
</div>
</div>
)}
{sources.length > maxSources && (
<div className="text-xs text-gray-500 text-center">
{sources.length - maxSources}
</div>
)}
</div>
);
}
@@ -0,0 +1,403 @@
"use client";
import { useMemo, useRef, useCallback, useState, useEffect } from "react";
import ForceGraph2D from "react-force-graph-2d";
import { BookStructure, Chapter, Section, Subsection } from "@/types";
import { Button } from "@/components/ui/button";
import { RotateCcw, ZoomIn, ZoomOut } from "lucide-react";
import NodeDetailDialog from "./node-detail-dialog";
interface GraphNode {
id: string;
name: string;
type: 'root' | 'chapter' | 'section';
nodeId?: number; // 节点在数据库中的ID
nodeType?: 'chapter' | 'section'; // 用于详情对话框
sectionData?: { subsections: Array<{ id: number; title: string }> }; // 存储节的小节(知识点)数据
val?: number;
color?: string;
fx?: number;
fy?: number;
x?: number; // 初始x位置
y?: number; // 初始y位置
_fullLabel?: string; // 完整标签用于tooltip
}
interface GraphLink {
source: string;
target: string;
type: 'root-chapter' | 'chapter-section';
}
interface GraphData {
nodes: GraphNode[];
links: GraphLink[];
}
interface KnowledgeGraphProps {
bookStructure: BookStructure;
onNodeClick?: (node: GraphNode) => void;
}
// 标签尺寸配置(分级字体大小,不限制宽度)
const LABEL_CONFIG = {
root: {
fontSize: 18,
padding: 8,
},
chapter: {
fontSize: 15,
padding: 6,
},
section: {
fontSize: 13,
padding: 5,
},
};
export default function KnowledgeGraph({ bookStructure, onNodeClick }: KnowledgeGraphProps) {
const graphRef = useRef<any>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [selectedNode, setSelectedNode] = useState<GraphNode | null>(null);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [dimensions, setDimensions] = useState({ width: 1200, height: 800 });
// 响应式尺寸计算
useEffect(() => {
const updateDimensions = () => {
if (containerRef.current) {
const rect = containerRef.current.getBoundingClientRect();
setDimensions({
width: rect.width,
height: Math.max(600, rect.height),
});
}
};
if (typeof window !== 'undefined') {
updateDimensions();
window.addEventListener('resize', updateDimensions);
return () => window.removeEventListener('resize', updateDimensions);
}
}, []);
// 将书籍结构数据转换为图谱数据
const graphData: GraphData = useMemo(() => {
const nodes: GraphNode[] = [];
const links: GraphLink[] = [];
// 调试信息
console.log("知识图谱数据:", bookStructure);
console.log("章节数量:", bookStructure?.chapters?.length || 0);
// 创建根节点(书籍,固定在中心)
const rootNode: GraphNode = {
id: 'root',
name: bookStructure.book.title,
type: 'root',
val: 25, // 增大根节点
color: '#3b82f6', // 蓝色
fx: 0, // 固定x坐标
fy: 0, // 固定y坐标
_fullLabel: bookStructure.book.title, // 存储完整标签用于tooltip
};
nodes.push(rootNode);
// 检查是否有章节数据
if (!bookStructure.chapters || bookStructure.chapters.length === 0) {
console.warn("警告: 没有章节数据");
return { nodes, links };
}
// 章节颜色配置
const chapterColors = [
'#8b5cf6', // 紫色
'#ec4899', // 粉色
'#f59e0b', // 橙色
'#10b981', // 绿色
'#06b6d4', // 青色
'#ef4444', // 红色
];
// 为每个章节创建节点和连接
const chapterCount = bookStructure.chapters.length;
const chapterAngleStep = (2 * Math.PI) / chapterCount;
bookStructure.chapters.forEach((chapter, chapterIndex) => {
console.log(`处理章节 ${chapterIndex + 1}:`, chapter.title, "节数量:", chapter.sections?.length || 0);
const chapterNodeId = `chapter-${chapter.id}`;
const chapterColor = chapterColors[chapterIndex % chapterColors.length];
// 计算章节节点的初始位置(圆形分布)
const chapterRadius = 400;
const angle = chapterIndex * chapterAngleStep;
const initialX = Math.cos(angle) * chapterRadius;
const initialY = Math.sin(angle) * chapterRadius;
// 创建章节节点
const chapterNode: GraphNode = {
id: chapterNodeId,
name: chapter.title,
type: 'chapter',
nodeId: chapter.id,
nodeType: 'chapter',
val: 18, // 章节节点大小
color: chapterColor,
_fullLabel: chapter.title,
x: initialX,
y: initialY,
};
nodes.push(chapterNode);
// 连接根节点到章节节点
links.push({
source: 'root',
target: chapterNodeId,
type: 'root-chapter',
});
// 检查是否有节数据
if (!chapter.sections || chapter.sections.length === 0) {
console.warn(`章节 ${chapter.title} 没有节数据`);
return;
}
// 为每个节创建节点
const sectionCount = chapter.sections.length;
const sectionAngleStep = sectionCount > 1 ? (2 * Math.PI) / sectionCount : 0;
chapter.sections.forEach((section, sectionIndex) => {
const sectionNodeId = `section-${section.id}`;
// 计算节节点的初始位置(围绕章节节点)
const sectionRadius = 250;
const sectionAngle = sectionAngleStep * sectionIndex;
const sectionX = initialX + Math.cos(angle + sectionAngle) * sectionRadius;
const sectionY = initialY + Math.sin(angle + sectionAngle) * sectionRadius;
// 创建节节点(包含小节数据,用于点击后展开)
const sectionNode: GraphNode = {
id: sectionNodeId,
name: section.title,
type: 'section',
nodeId: section.id,
nodeType: 'section',
sectionData: {
subsections: section.subsections || []
},
val: 12, // 节节点大小
color: chapterColor + 'CC', // 添加透明度
_fullLabel: section.title,
x: sectionX,
y: sectionY,
};
nodes.push(sectionNode);
// 连接章节节点到节节点
links.push({
source: chapterNodeId,
target: sectionNodeId,
type: 'chapter-section',
});
// 注意:小节(知识点)不在图谱中直接展示,点击节节点后在对话框中展开
});
});
console.log("图谱节点数量:", nodes.length, "链接数量:", links.length);
return { nodes, links };
}, [bookStructure]);
// 节点点击处理
const handleNodeClick = useCallback((node: GraphNode) => {
// 只有非根节点才能点击查看详情
if (node.type !== 'root' && node.nodeId && node.nodeType) {
setSelectedNode(node);
setIsDialogOpen(true);
}
if (onNodeClick) {
onNodeClick(node);
}
}, [onNodeClick]);
// 重置视图
const handleResetView = useCallback(() => {
if (graphRef.current) {
graphRef.current.zoomToFit(400, 20);
graphRef.current.centerAt(0, 0, 1000);
}
}, []);
// 放大
const handleZoomIn = useCallback(() => {
if (graphRef.current) {
const currentZoom = graphRef.current.zoom() || 1;
graphRef.current.zoom(currentZoom * 1.2, 200);
}
}, []);
// 缩小
const handleZoomOut = useCallback(() => {
if (graphRef.current) {
const currentZoom = graphRef.current.zoom() || 1;
graphRef.current.zoom(currentZoom * 0.8, 200);
}
}, []);
return (
<div ref={containerRef} className="relative w-full h-full">
{/* 控制按钮 */}
<div className="absolute top-4 right-4 z-10 flex flex-col space-y-2">
<Button
variant="outline"
size="icon"
onClick={handleZoomIn}
className="bg-background/80 backdrop-blur-sm"
title="放大"
>
<ZoomIn className="w-4 h-4" />
</Button>
<Button
variant="outline"
size="icon"
onClick={handleZoomOut}
className="bg-background/80 backdrop-blur-sm"
title="缩小"
>
<ZoomOut className="w-4 h-4" />
</Button>
<Button
variant="outline"
size="icon"
onClick={handleResetView}
className="bg-background/80 backdrop-blur-sm"
title="重置视图"
>
<RotateCcw className="w-4 h-4" />
</Button>
</div>
{/* 知识图谱 */}
<ForceGraph2D
ref={graphRef}
graphData={graphData}
nodeLabel={(node: any) => node._fullLabel || node.name}
nodeColor={(node: any) => node.color || '#3b82f6'}
nodeVal={(node: any) => node.val || 8}
nodeRelSize={6}
// 碰撞检测和力衰减优化
d3AlphaDecay={0.02}
d3AlphaMin={0.005}
cooldownTicks={200}
linkColor={(link: any) => {
if (link.type === 'root-chapter') {
return '#64748b'; // 灰色
}
return link.source.color || '#94a3b8'; // 使用章节颜色
}}
linkWidth={(link: any) => {
if (link.type === 'root-chapter') {
return 3;
}
return 2;
}}
linkDirectionalArrowLength={6}
linkDirectionalArrowRelPos={1}
linkCurvature={0.15}
onNodeClick={(node: any) => handleNodeClick(node)}
onNodeDragEnd={(node: any) => {
// 保持根节点固定
if (node.id !== 'root') {
node.fx = node.x;
node.fy = node.y;
}
}}
onNodeHover={(node: any) => {
if (typeof document !== 'undefined') {
if (node) {
document.body.style.cursor = 'pointer';
} else {
document.body.style.cursor = 'default';
}
}
}}
onEngineStop={() => {
if (graphRef.current) {
// 确保根节点在中心
graphRef.current.centerAt(0, 0, 1000);
graphRef.current.zoomToFit(400, 30);
}
}}
nodeCanvasObject={(node: any, ctx: CanvasRenderingContext2D, globalScale: number) => {
const label = node.name;
// 获取分级标签配置(只使用字体大小和padding,不限制宽度)
const config = LABEL_CONFIG[node.type as 'root' | 'chapter' | 'section'] || LABEL_CONFIG.section;
const fontSize = Math.max(9, config.fontSize / globalScale);
const padding = config.padding / globalScale;
// 设置字体
ctx.font = `bold ${fontSize}px "Microsoft YaHei", "SimHei", "Arial", sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// 测量完整文本尺寸(不截断)
const textWidth = ctx.measureText(label).width;
const textHeight = fontSize;
// 计算标签位置(在节点下方,根据节点大小调整间距)
const nodeRadius = node.val || 8;
const labelY = node.y + nodeRadius + textHeight / 2 + padding * 2;
const labelX = node.x;
// 计算背景尺寸(完全根据实际文本宽度,不限制)
const bgWidth = textWidth + padding * 2;
const bgHeight = textHeight + padding * 2;
const radius = Math.max(2, 4 / globalScale);
// 背景色(根据节点类型调整透明度)
const bgAlpha = node.type === 'knowledge' ? 0.92 : 0.95;
ctx.fillStyle = `rgba(255, 255, 255, ${bgAlpha})`;
ctx.strokeStyle = node.color || '#3b82f6';
ctx.lineWidth = Math.max(1, 1.5 / globalScale);
// 绘制圆角矩形背景
const x = labelX - bgWidth / 2;
const y = labelY - textHeight / 2 - padding;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + bgWidth - radius, y);
ctx.quadraticCurveTo(x + bgWidth, y, x + bgWidth, y + radius);
ctx.lineTo(x + bgWidth, y + bgHeight - radius);
ctx.quadraticCurveTo(x + bgWidth, y + bgHeight, x + bgWidth - radius, y + bgHeight);
ctx.lineTo(x + radius, y + bgHeight);
ctx.quadraticCurveTo(x, y + bgHeight, x, y + bgHeight - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.fill();
ctx.stroke();
// 绘制完整文本(使用节点颜色,不截断)
ctx.fillStyle = node.color || '#3b82f6';
ctx.fillText(label, labelX, labelY);
}}
width={dimensions.width}
height={dimensions.height}
/>
{/* 节点详情对话框 */}
{selectedNode && selectedNode.nodeId && selectedNode.nodeType && (
<NodeDetailDialog
open={isDialogOpen}
onOpenChange={setIsDialogOpen}
nodeType={selectedNode.nodeType}
nodeId={selectedNode.nodeId}
nodeTitle={selectedNode.name}
subsections={selectedNode.sectionData?.subsections}
/>
)}
</div>
);
}
@@ -0,0 +1,357 @@
"use client";
import { useState, useEffect } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Loader2, BookOpen, FileText, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { courseContentAPI } from "@/lib/api";
interface Subsection {
id: number;
title: string;
}
interface NodeDetailDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
nodeType: "chapter" | "section";
nodeId: number;
nodeTitle: string;
subsections?: Subsection[]; // 节节点的小节(知识点)列表
subsectionId?: number; // 如果指定,直接显示该小节的内容
}
export default function NodeDetailDialog({
open,
onOpenChange,
nodeType,
nodeId,
nodeTitle,
subsections,
subsectionId,
}: NodeDetailDialogProps) {
const [content, setContent] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedSubsection, setSelectedSubsection] = useState<number | null>(subsectionId || null);
const [subsectionContent, setSubsectionContent] = useState<string | null>(null);
const [loadingSubsection, setLoadingSubsection] = useState(false);
const loadContent = async () => {
setIsLoading(true);
setError(null);
try {
console.log("加载内容 - nodeType:", nodeType, "nodeId:", nodeId);
let result;
switch (nodeType) {
case "chapter":
result = await courseContentAPI.getChapterContent(nodeId);
break;
case "section":
result = await courseContentAPI.getSectionContent(nodeId);
break;
default:
throw new Error("未知的节点类型");
}
console.log("内容加载成功,长度:", result.content?.length || 0);
setContent(result.content);
} catch (err: any) {
console.error("加载内容失败:", err);
setError(err.message || "加载内容失败");
} finally {
setIsLoading(false);
}
};
const handleSubsectionClick = async (subsectionId: number) => {
if (selectedSubsection === subsectionId && subsectionContent) {
// 如果已选中且已加载,则关闭
setSelectedSubsection(null);
setSubsectionContent(null);
return;
}
setSelectedSubsection(subsectionId);
setLoadingSubsection(true);
setSubsectionContent(null);
try {
const result = await courseContentAPI.getSubsectionContent(subsectionId);
setSubsectionContent(result.content);
} catch (err: any) {
console.error("加载小节内容失败:", err);
setError(err.message || "加载小节内容失败");
} finally {
setLoadingSubsection(false);
}
};
useEffect(() => {
if (open) {
console.log("对话框打开 - nodeType:", nodeType, "nodeId:", nodeId, "subsectionId:", subsectionId, "subsections:", subsections?.length || 0);
// 如果指定了subsectionId,直接加载小节内容
if (subsectionId) {
console.log("直接加载小节内容,ID:", subsectionId);
setSelectedSubsection(subsectionId);
setLoadingSubsection(true);
setSubsectionContent(null);
setError(null);
courseContentAPI.getSubsectionContent(subsectionId)
.then((result) => {
console.log("小节内容加载成功,长度:", result.content?.length || 0);
setSubsectionContent(result.content);
})
.catch((err: any) => {
console.error("加载小节内容失败:", err);
setError(err.message || "加载小节内容失败");
})
.finally(() => {
setLoadingSubsection(false);
});
} else if (nodeId && nodeId > 0) {
// 否则加载章节或节内容(nodeId必须大于0)
console.log("加载章节/节内容,ID:", nodeId);
loadContent();
} else {
// 如果既没有subsectionId也没有有效的nodeId,显示错误
console.warn("无效的节点ID - nodeId:", nodeId, "subsectionId:", subsectionId);
setError("无效的节点ID");
}
} else {
// 关闭对话框时重置状态
setContent(null);
setError(null);
setSelectedSubsection(subsectionId || null);
setSubsectionContent(null);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, nodeId, subsectionId]);
const getTypeLabel = () => {
if (subsectionId) {
return "小节(知识点)";
}
switch (nodeType) {
case "chapter":
return "章节";
case "section":
return "节";
default:
return "节点";
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[85vh] overflow-hidden flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center space-x-2">
{nodeType === "chapter" ? (
<BookOpen className="w-5 h-5" />
) : (
<FileText className="w-5 h-5" />
)}
<span>{nodeTitle}</span>
</DialogTitle>
<DialogDescription>{getTypeLabel()}</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto mt-4">
{/* 如果指定了subsectionId,直接显示小节内容 */}
{subsectionId ? (
<>
{loadingSubsection && (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
<span className="ml-2 text-muted-foreground">...</span>
</div>
)}
{error && !loadingSubsection && (
<div className="text-center py-12">
<p className="text-destructive">{error}</p>
</div>
)}
{subsectionContent && !loadingSubsection && !error && (
<div className="prose prose-sm max-w-none dark:prose-invert prose-table:overflow-x-auto text-sm text-foreground leading-relaxed">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
table: ({ children }) => (
<div className="overflow-x-auto my-4">
<table className="min-w-full border-collapse border border-border">
{children}
</table>
</div>
),
thead: ({ children }) => (
<thead className="bg-muted">{children}</thead>
),
tbody: ({ children }) => <tbody>{children}</tbody>,
tr: ({ children }) => (
<tr className="border-b border-border">{children}</tr>
),
th: ({ children }) => (
<th className="border border-border px-4 py-2 text-left font-semibold">
{children}
</th>
),
td: ({ children }) => (
<td className="border border-border px-4 py-2">
{children}
</td>
),
}}
>
{subsectionContent}
</ReactMarkdown>
</div>
)}
</>
) : (
<>
{isLoading && (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
<span className="ml-2 text-muted-foreground">...</span>
</div>
)}
{error && !isLoading && (
<div className="text-center py-12">
<p className="text-destructive">{error}</p>
</div>
)}
{/* 显示章节/节内容 */}
{content && !isLoading && !error && (
<div className="space-y-4">
{/* 主要内容 */}
<div className="prose prose-sm max-w-none dark:prose-invert prose-table:overflow-x-auto text-sm text-foreground leading-relaxed">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
table: ({ children }) => (
<div className="overflow-x-auto my-4">
<table className="min-w-full border-collapse border border-border">
{children}
</table>
</div>
),
thead: ({ children }) => (
<thead className="bg-muted">{children}</thead>
),
tbody: ({ children }) => <tbody>{children}</tbody>,
tr: ({ children }) => (
<tr className="border-b border-border">{children}</tr>
),
th: ({ children }) => (
<th className="border border-border px-4 py-2 text-left font-semibold">
{children}
</th>
),
td: ({ children }) => (
<td className="border border-border px-4 py-2">
{children}
</td>
),
}}
>
{content}
</ReactMarkdown>
</div>
{/* 如果是节节点,显示小节(知识点)列表 */}
{nodeType === "section" && subsections && subsections.length > 0 && (
<div className="mt-6 pt-6 border-t border-border">
<h3 className="text-lg font-semibold mb-4 flex items-center space-x-2">
<FileText className="w-5 h-5" />
<span> ({subsections.length} )</span>
</h3>
<div className="space-y-2">
{subsections.map((subsection) => (
<div key={subsection.id} className="border border-border rounded-lg overflow-hidden">
<Button
variant="ghost"
className="w-full justify-between text-left h-auto py-3 px-4"
onClick={() => handleSubsectionClick(subsection.id)}
>
<span className="flex-1 text-sm">{subsection.title}</span>
<ChevronRight
className={`w-4 h-4 transition-transform ${
selectedSubsection === subsection.id ? "rotate-90" : ""
}`}
/>
</Button>
{selectedSubsection === subsection.id && (
<div className="px-4 pb-4 pt-2 border-t border-border bg-muted/50">
{loadingSubsection ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
<span className="ml-2 text-sm text-muted-foreground">...</span>
</div>
) : subsectionContent ? (
<div className="prose prose-sm max-w-none dark:prose-invert prose-table:overflow-x-auto text-sm text-foreground leading-relaxed pt-2">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
table: ({ children }) => (
<div className="overflow-x-auto my-4">
<table className="min-w-full border-collapse border border-border">
{children}
</table>
</div>
),
thead: ({ children }) => (
<thead className="bg-muted">{children}</thead>
),
tbody: ({ children }) => <tbody>{children}</tbody>,
tr: ({ children }) => (
<tr className="border-b border-border">{children}</tr>
),
th: ({ children }) => (
<th className="border border-border px-4 py-2 text-left font-semibold">
{children}
</th>
),
td: ({ children }) => (
<td className="border border-border px-4 py-2">
{children}
</td>
),
}}
>
{subsectionContent}
</ReactMarkdown>
</div>
) : null}
</div>
)}
</div>
))}
</div>
</div>
)}
</div>
)}
</>
)}
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,148 @@
"use client";
import Link from "next/link";
import { motion } from "framer-motion";
import {
MessageSquare,
BookOpen,
Image,
BarChart3,
ArrowRight,
CheckCircle
} from "lucide-react";
import { BentoCard, BentoGrid } from "@/components/magicui/bento-grid";
import { User } from "@/types";
import { cn } from "@/lib/utils";
interface FeaturesSectionProps {
isAuthenticated: boolean;
user: User | null;
}
export default function FeaturesSection({ isAuthenticated, user }: FeaturesSectionProps) {
const features = [
{
Icon: MessageSquare,
name: "智能问答",
description: "基于大模型的智能问答系统,支持多轮对话和上下文理解",
href: isAuthenticated ? "/chat" : "#",
cta: isAuthenticated ? "开始对话" : "了解更多",
className: "lg:col-start-1 lg:col-end-2 lg:row-start-1 lg:row-end-3",
stats: isAuthenticated ? { count: 0, label: "次对话" } : undefined,
},
{
Icon: BookOpen,
name: "知识库管理",
description: "多模态知识库,支持文档上传、向量化和智能检索",
href: isAuthenticated ? "/knowledge" : "#",
cta: isAuthenticated ? "管理文档" : "了解更多",
className: "lg:col-start-1 lg:col-end-2 lg:row-start-3 lg:row-end-4",
stats: isAuthenticated ? { count: 0, label: "个文档" } : undefined,
},
{
Icon: Image,
name: "空间出图",
description: "结合空间规划知识的图像生成和分析功能",
href: isAuthenticated ? "/spatial" : "#",
cta: isAuthenticated ? "生成图像" : "了解更多",
className: "lg:col-start-2 lg:col-end-3 lg:row-start-1 lg:row-end-2",
stats: isAuthenticated ? { count: 0, label: "张图片" } : undefined,
},
{
Icon: BarChart3,
name: "学习分析",
description: "学习数据统计和可视化,帮助了解学习进度",
href: isAuthenticated ? "/analytics" : "#",
cta: isAuthenticated ? "查看分析" : "了解更多",
className: "lg:col-start-2 lg:col-end-3 lg:row-start-2 lg:row-end-3",
stats: isAuthenticated ? { count: 0, label: "个报告" } : undefined,
},
];
return (
<section className="py-24 sm:py-32">
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<div className="mx-auto max-w-2xl text-center">
<h2 className="text-base font-semibold leading-7 text-primary">
{isAuthenticated ? "功能模块" : "核心功能"}
</h2>
<p className="mt-2 text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
{isAuthenticated ? "选择您需要的功能" : "强大的AI学习助手"}
</p>
<p className="mt-6 text-lg leading-8 text-gray-600">
{isAuthenticated
? "点击下方卡片开始使用各项功能"
: "基于先进的大模型技术,为您提供专业的国土空间规划学习体验"
}
</p>
</div>
<div className="mx-auto mt-16 max-w-2xl sm:mt-20 lg:mt-24 lg:max-w-none">
<BentoGrid className="grid grid-cols-1 lg:grid-cols-3 gap-4">
{features.map((feature) => {
if (isAuthenticated) {
// 登录状态:使用自定义卡片
return (
<Link key={feature.name} href={feature.href} className="block h-full">
<motion.div
className={cn(
"group relative col-span-3 flex flex-col justify-between overflow-hidden rounded-xl h-full",
"bg-background [box-shadow:0_0_0_1px_rgba(0,0,0,.03),0_2px_4px_rgba(0,0,0,.05),0_12px_24px_rgba(0,0,0,.05)]",
"dark:bg-background transform-gpu dark:[box-shadow:0_-20px_80px_-20px_#ffffff1f_inset] dark:[border:1px_solid_rgba(255,255,255,.1)]",
feature.className
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
transition={{ duration: 0.2 }}
>
<div className="z-10 flex transform-gpu flex-col gap-1 p-6 transition-all duration-300 group-hover:-translate-y-5">
<feature.Icon className="h-12 w-12 origin-left transform-gpu text-neutral-700 transition-all duration-300 ease-in-out group-hover:scale-75 dark:text-neutral-300" />
<h3 className="text-xl font-semibold text-neutral-700 dark:text-neutral-300">
{feature.name}
</h3>
<p className="max-w-lg text-neutral-400">{feature.description}</p>
{feature.stats && (
<div className="flex items-center text-sm text-gray-500 mt-4">
<span className="font-medium">
{feature.stats.count} {feature.stats.label}
</span>
</div>
)}
</div>
<motion.div
className="pointer-events-none absolute bottom-0 flex w-full translate-y-10 transform-gpu flex-row items-center p-4 opacity-0 transition-all duration-300 group-hover:translate-y-0 group-hover:opacity-100"
whileHover={{ x: 4 }}
transition={{ duration: 0.2 }}
>
<span className="flex items-center text-sm font-medium text-neutral-700 dark:text-neutral-300 pointer-events-auto">
{feature.cta}
<ArrowRight className="ms-2 h-4 w-4" />
</span>
</motion.div>
<div className="pointer-events-none absolute inset-0 transform-gpu transition-all duration-300 group-hover:bg-black/[.03] group-hover:dark:bg-neutral-800/10" />
</motion.div>
</Link>
);
} else {
// 未登录状态:使用标准 BentoCard
return (
<BentoCard
key={feature.name}
className={feature.className}
Icon={feature.Icon}
name={feature.name}
description={feature.description}
cta={feature.cta}
href={feature.href}
/>
);
}
})}
</BentoGrid>
</div>
</div>
</section>
);
}
+159
View File
@@ -0,0 +1,159 @@
"use client";
import Link from "next/link";
import { BookOpen, Mail, Phone, MapPin, MessageCircle } from "lucide-react";
export default function Footer() {
const currentYear = new Date().getFullYear();
const footerLinks = {
quickLinks: [
{ name: "首页", href: "/" },
{ name: "智能问答", href: "/chat" },
{ name: "知识库管理", href: "/knowledge" },
{ name: "空间出图", href: "/spatial" },
{ name: "学习分析", href: "/analytics" },
],
resources: [
{ name: "课程大纲", href: "#" },
{ name: "线上讲座", href: "#" },
{ name: "资料下载", href: "#" },
{ name: "案例分析", href: "#" },
{ name: "交流论坛", href: "#" },
],
};
const contactInfo = [
{ icon: Mail, text: "contact@HIT-agent.com", href: "mailto:contact@HIT-agent.com" },
{ icon: Phone, text: "0451-8641-2114", href: "tel:0451-8641-2114" },
{ icon: MapPin, text: "哈尔滨市南岗区西大直街92号", href: "#" },
];
return (
<footer className="relative border-t bg-slate-900 dark:bg-slate-950 text-slate-300">
<div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
{/* Main Footer Content */}
<div className="py-12 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
{/* Brand Column */}
<div className="lg:col-span-1">
<div className="flex items-center space-x-2 mb-4">
<div className="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
<BookOpen className="w-6 h-6 text-white" />
</div>
<span className="text-lg font-bold text-white">
</span>
</div>
<p className="text-sm text-slate-400 mb-6 max-w-xs">
</p>
{/* Social Links */}
<div className="flex items-center gap-3">
<Link
href="#"
className="w-9 h-9 rounded-lg bg-slate-800 hover:bg-slate-700 flex items-center justify-center transition-colors"
aria-label="微信"
>
<MessageCircle className="w-4 h-4" />
</Link>
<Link
href="#"
className="w-9 h-9 rounded-lg bg-slate-800 hover:bg-slate-700 flex items-center justify-center transition-colors"
aria-label="微博"
>
<MessageCircle className="w-4 h-4" />
</Link>
<Link
href="#"
className="w-9 h-9 rounded-lg bg-slate-800 hover:bg-slate-700 flex items-center justify-center transition-colors"
aria-label="通知"
>
<MessageCircle className="w-4 h-4" />
</Link>
</div>
</div>
{/* Quick Links */}
<div>
<h4 className="font-semibold mb-4 text-white"></h4>
<ul className="space-y-3">
{footerLinks.quickLinks.map((link) => (
<li key={link.name}>
<Link
href={link.href}
className="text-sm text-slate-400 hover:text-white transition-colors"
>
{link.name}
</Link>
</li>
))}
</ul>
</div>
{/* Resources Links */}
<div>
<h4 className="font-semibold mb-4 text-white"></h4>
<ul className="space-y-3">
{footerLinks.resources.map((link) => (
<li key={link.name}>
<Link
href={link.href}
className="text-sm text-slate-400 hover:text-white transition-colors"
>
{link.name}
</Link>
</li>
))}
</ul>
</div>
{/* Contact Info */}
<div>
<h4 className="font-semibold mb-4 text-white"></h4>
<ul className="space-y-3">
{contactInfo.map((contact, index) => (
<li key={index}>
{contact.href !== "#" ? (
<a
href={contact.href}
className="text-sm text-slate-400 hover:text-white transition-colors flex items-start gap-2"
>
<contact.icon className="w-4 h-4 mt-0.5 flex-shrink-0" />
<span>{contact.text}</span>
</a>
) : (
<div className="text-sm text-slate-400 flex items-start gap-2">
<contact.icon className="w-4 h-4 mt-0.5 flex-shrink-0" />
<span>{contact.text}</span>
</div>
)}
</li>
))}
</ul>
</div>
</div>
{/* Bottom Bar */}
<div className="py-6 border-t border-slate-800">
<div className="flex flex-col md:flex-row justify-between items-center gap-4">
<div className="text-sm text-slate-400">
© {currentYear}
</div>
<div className="flex items-center gap-6 text-sm text-slate-400">
<Link href="#" className="hover:text-white transition-colors">
</Link>
<Link href="#" className="hover:text-white transition-colors">
使
</Link>
<Link href="#" className="hover:text-white transition-colors">
</Link>
</div>
</div>
</div>
</div>
</footer>
);
}
+130
View File
@@ -0,0 +1,130 @@
"use client";
import Link from "next/link";
import { motion } from "framer-motion";
import { Button } from "@/components/ui/button";
import { AuroraText } from "@/components/magicui/aurora-text";
import { User } from "@/types";
import { MessageSquare, FileText, Image, BarChart3, ArrowRight } from "lucide-react";
interface HeroSectionProps {
isAuthenticated: boolean;
user: User | null;
}
export default function HeroSection({ isAuthenticated, user }: HeroSectionProps) {
const features = [
{
name: "智能问答",
href: "/chat",
icon: MessageSquare,
description: "基于大模型的智能问答系统,专业知识即时解答",
color: "from-blue-500 to-blue-600"
},
{
name: "知识库管理",
href: "/knowledge",
icon: FileText,
description: "多模态知识库,文档上传与智能检索",
color: "from-green-500 to-green-600"
},
{
name: "空间出图",
href: "/spatial",
icon: Image,
description: "结合空间规划的AI图像生成与分析",
color: "from-purple-500 to-purple-600"
},
{
name: "学习分析",
href: "/analytics",
icon: BarChart3,
description: "学习数据统计,追踪您的学习进度",
color: "from-orange-500 to-orange-600"
},
];
return (
<section className="flex min-h-[90vh] w-full flex-col items-center justify-center py-20 relative">
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
{/* 描述区域 */}
<motion.div
className="text-center mb-16"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.6 }}
>
<p className="text-lg leading-8 text-gray-600 max-w-2xl mx-auto">
</p>
{!isAuthenticated && (
<div className="mt-10 flex items-center justify-center gap-x-6">
<Button size="lg" asChild>
<Link href="/register">使</Link>
</Button>
<Button variant="outline" size="lg" asChild>
<Link href="/login"></Link>
</Button>
</div>
)}
</motion.div>
{/* 功能卡片 - 登录后显示 */}
{isAuthenticated && (
<motion.div
className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6"
initial={{ opacity: 0, y: 40 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.6, delay: 0.2 }}
>
{features.map((feature, index) => (
<Link
key={feature.name}
href={feature.href}
className="block group"
>
<motion.div
className="relative p-6 rounded-2xl bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 hover:border-blue-300 dark:hover:border-blue-700 hover:shadow-xl transition-all duration-300"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay: 0.3 + index * 0.1 }}
whileHover={{ y: -8, scale: 1.02 }}
>
{/* 图标 */}
<div className={`w-14 h-14 rounded-xl bg-gradient-to-r ${feature.color} flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300`}>
<feature.icon className="w-7 h-7 text-white" />
</div>
{/* 标题 */}
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
{feature.name}
</h3>
{/* 描述 */}
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
{feature.description}
</p>
{/* 箭头 */}
<div className="flex items-center text-sm font-medium text-blue-600 dark:text-blue-400">
<span>使</span>
<ArrowRight className="ml-2 w-4 h-4 group-hover:translate-x-2 transition-transform duration-300" />
</div>
{/* 装饰性背景 */}
<div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-blue-50/50 to-purple-50/50 dark:from-blue-950/20 dark:to-purple-950/20 opacity-0 group-hover:opacity-100 transition-opacity duration-300 -z-10" />
</motion.div>
</Link>
))}
</motion.div>
)}
</div>
</section>
);
}
@@ -0,0 +1,275 @@
"use client";
import { useState, useEffect } from "react";
import { useAuthStore } from "@/store/auth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import Navbar from "./navbar";
import { MessageSquare, Database, Image, BookOpen, Users, Award, ArrowRight, Mail, Phone, MapPin, GraduationCap } from "lucide-react";
import Link from "next/link";
import { analyticsAPI } from "@/lib/api";
export default function HomePageContent() {
const { isAuthenticated, user } = useAuthStore();
const [stats, setStats] = useState([
{ label: "活跃用户", value: "1,200+" },
{ label: "知识文档", value: "5,000+" },
{ label: "问答对话", value: "50,000+" },
{ label: "生成图像", value: "10,000+" }
]);
const [isLoadingStats, setIsLoadingStats] = useState(true);
useEffect(() => {
const loadPlatformStats = async () => {
try {
setIsLoadingStats(true);
const data = await analyticsAPI.getPlatformStats();
// 格式化数字,添加千分位分隔符
const formatNumber = (num: number) => {
if (num >= 10000) {
return `${(num / 10000).toFixed(1)}万+`;
} else if (num >= 1000) {
return `${(num / 1000).toFixed(1)}千+`;
}
return `${num}+`;
};
setStats([
{ label: "活跃用户", value: formatNumber(data.active_users) },
{ label: "知识文档", value: formatNumber(data.knowledge_documents) },
{ label: "问答对话", value: formatNumber(data.qa_dialogues) },
{ label: "生成图像", value: formatNumber(data.generated_images) }
]);
} catch (error: any) {
console.warn("加载平台统计数据失败,使用默认值:", error?.message || error);
// 保持默认值,不显示错误给用户
// 如果后端API不可用,继续显示默认的占位数据
} finally {
setIsLoadingStats(false);
}
};
loadPlatformStats();
}, []);
const features = [
{
icon: GraduationCap,
title: "课程内容",
description: "查看和管理国土空间规划课程内容,获取系统化的学习资源",
href: "/course-content"
},
{
icon: MessageSquare,
title: "智能问答",
description: "基于RAG技术的智能对话系统,提供专业准确的国土空间规划知识解答",
href: "/chat"
},
{
icon: Database,
title: "知识库",
description: "构建和管理专业知识库,支持多种文档格式的智能处理和分析",
href: "/knowledge"
},
{
icon: Users,
title: "论坛社区",
description: "参与系统优化建议与课程反馈的讨论,与同伴交流学习经验",
href: "/forum"
},
{
icon: Image,
title: "空间设计",
description: "AI驱动的空间规划图像生成,支持多种设计风格和规划类型",
href: "/spatial"
}
];
return (
<div className="min-h-screen bg-background">
{/* 导航栏 */}
<Navbar isAuthenticated={isAuthenticated} user={user} />
{/* Hero 区域 - 全屏背景 */}
<section className="relative min-h-screen flex items-center justify-center border-b border-border overflow-hidden w-full">
{/* 背景图片 - 充满整个屏幕 */}
<div className="absolute inset-0 z-0 w-full h-full">
<img
src="/heilongjiang-spatial-planning.png"
alt="黑龙江国土空间规划"
className="w-full h-full object-cover"
/>
{/* 渐变遮罩,确保文字可读性 */}
<div className="absolute inset-0 bg-gradient-to-b from-background/40 via-background/30 to-background/50"></div>
</div>
{/* 内容 */}
<div className="relative z-10 max-w-4xl mx-auto px-4 text-center w-full">
<h1 className="text-5xl font-bold text-foreground mb-6 drop-shadow-lg">
</h1>
<p className="text-xl text-foreground mb-8 leading-relaxed drop-shadow-md">
AI技术的智能学习平台
</p>
<div className="flex flex-col sm:flex-row gap-4 justify-center">
{isAuthenticated ? (
<Button asChild size="lg" className="h-12 px-8">
<Link href="/chat">
<ArrowRight className="ml-2 h-4 w-4" />
</Link>
</Button>
) : (
<>
<Button asChild size="lg" className="h-12 px-8">
<Link href="/register"></Link>
</Button>
<Button asChild variant="outline" size="lg" className="h-12 px-8">
<Link href="/login"></Link>
</Button>
</>
)}
</div>
</div>
</section>
{/* 主要内容 */}
<main className="mit-container">
{/* 功能特性 */}
<section className="py-12 mt-0">
<div className="text-center mb-12">
<h2 className="text-3xl font-bold text-foreground mb-4"></h2>
<p className="text-lg text-muted-foreground">
AI技术
</p>
</div>
<div className="mit-grid">
{features.map((feature, index) => (
<Card key={index} className="group cursor-pointer hover:scale-105 transition-transform duration-200">
<CardHeader>
<div className="w-16 h-16 bg-primary/10 rounded-lg flex items-center justify-center mb-4 group-hover:bg-primary/20 transition-colors">
<feature.icon className="w-8 h-8 text-primary" />
</div>
<CardTitle className="text-xl">{feature.title}</CardTitle>
<CardDescription className="text-base leading-relaxed">
{feature.description}
</CardDescription>
</CardHeader>
</Card>
))}
</div>
</section>
</main>
{/* 统计数据 */}
<section className="border-y bg-muted/50 py-16">
<div className="mit-container">
<div className="text-center mb-12">
<h2 className="text-3xl font-bold text-foreground mb-4"></h2>
<p className="text-lg text-muted-foreground">
</p>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-8">
{stats.map((stat, index) => (
<div key={index} className="text-center">
<div className="text-3xl font-bold text-primary mb-2">
{isLoadingStats ? "..." : stat.value}
</div>
<div className="text-sm text-muted-foreground">{stat.label}</div>
</div>
))}
</div>
</div>
</section>
{/* 统一封底区域 */}
<footer className="border-t bg-card/50">
<div className="mit-container">
{/* 主要内容区域 - 三列布局(中间留空) */}
<div className="py-12 border-b border-border/50">
<div className="grid grid-cols-1 lg:grid-cols-[2fr_2fr_1fr] gap-8 lg:gap-12">
{/* 第一列:关于项目 */}
<div>
<h2 className="text-2xl font-bold text-foreground mb-4"></h2>
<p className="text-muted-foreground leading-relaxed mb-6">
AI技术的智能学习平台RAG技术AI能力
</p>
<div className="flex flex-col sm:flex-row gap-3">
<Button asChild variant="outline" size="sm">
<a href="https://tsp.spacekg.com/#/" target="_blank" rel="noopener noreferrer">
<BookOpen className="mr-2 h-4 w-4" />
</a>
</Button>
<Button asChild variant="outline" size="sm">
<a href="https://homepage.hit.edu.cn/wusongtao" target="_blank" rel="noopener noreferrer">
<Users className="mr-2 h-4 w-4" />
</a>
</Button>
</div>
</div>
{/* 第二列:空白(用于增加间距) */}
<div className="hidden lg:block"></div>
{/* 第三列:联系我们 */}
<div>
<h3 className="text-lg font-semibold text-foreground mb-4"></h3>
<ul className="space-y-3">
<li className="flex items-start gap-3">
<Mail className="w-5 h-5 text-muted-foreground mt-0.5 flex-shrink-0" />
<div>
<p className="text-sm text-muted-foreground"></p>
<a href="mailto:contact@hit-agent.com" className="text-sm text-foreground hover:text-primary transition-colors">
contact@hit-agent.com
</a>
</div>
</li>
<li className="flex items-start gap-3">
<Phone className="w-5 h-5 text-muted-foreground mt-0.5 flex-shrink-0" />
<div>
<p className="text-sm text-muted-foreground"></p>
<a href="tel:+86-451-86412114" className="text-sm text-foreground hover:text-primary transition-colors">
+86-451-86412114
</a>
</div>
</li>
<li className="flex items-start gap-3">
<MapPin className="w-5 h-5 text-muted-foreground mt-0.5 flex-shrink-0" />
<div>
<p className="text-sm text-muted-foreground"></p>
<p className="text-sm text-foreground">
西92
</p>
</div>
</li>
</ul>
</div>
</div>
</div>
{/* Footer信息部分 */}
<div className="py-8">
<div className="text-center">
<div className="flex items-center justify-center gap-2 mb-3">
<div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-blue-800 rounded-lg flex items-center justify-center">
<BookOpen className="w-4 h-4 text-white" />
</div>
<span className="text-lg font-semibold"></span>
</div>
<p className="text-xs text-muted-foreground">
Copyright © {new Date().getFullYear()}
</p>
</div>
</div>
</div>
</footer>
</div>
);
}
+151
View File
@@ -0,0 +1,151 @@
"use client";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { ThemeToggle } from "@/components/ui/theme-toggle";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useAuthStore } from "@/store/auth";
import { BookOpen, LogOut, User as UserIcon, Settings, ChevronDown, MessageSquare, Database, Image, TrendingUp, GraduationCap } from "lucide-react";
import { User } from "@/types";
interface NavbarProps {
isAuthenticated: boolean;
user: User | null;
}
export default function Navbar({ isAuthenticated, user }: NavbarProps) {
const { logout } = useAuthStore();
return (
<nav className="border-b bg-background/95 backdrop-blur-sm sticky top-0 z-50">
<div className="mit-container">
<div className="flex justify-between items-center h-16">
{/* Logo 和标题 */}
<Link href="/" className="flex items-center space-x-3 hover:opacity-80 transition-opacity cursor-pointer">
<div className="w-10 h-10 bg-gradient-to-r from-blue-600 to-blue-800 rounded-lg flex items-center justify-center shadow-sm">
<BookOpen className="w-6 h-6 text-white" />
</div>
<div className="flex flex-col">
<span className="text-lg font-semibold text-foreground">
</span>
<span className="text-xs text-muted-foreground">
Spatial Planning Course Agent
</span>
</div>
</Link>
{/* 导航链接 */}
{isAuthenticated && (
<div className="hidden md:flex items-center space-x-1">
<Link href="/course-content">
<Button variant="ghost" className="flex items-center space-x-2 px-3 py-2 hover:bg-muted/50">
<GraduationCap className="w-4 h-4" />
<span className="text-sm"></span>
</Button>
</Link>
<Link href="/chat">
<Button variant="ghost" className="flex items-center space-x-2 px-3 py-2 hover:bg-muted/50">
<MessageSquare className="w-4 h-4" />
<span className="text-sm"></span>
</Button>
</Link>
<Link href="/knowledge">
<Button variant="ghost" className="flex items-center space-x-2 px-3 py-2 hover:bg-muted/50">
<Database className="w-4 h-4" />
<span className="text-sm"></span>
</Button>
</Link>
<Link href="/spatial">
<Button variant="ghost" className="flex items-center space-x-2 px-3 py-2 hover:bg-muted/50">
<Image className="w-4 h-4" />
<span className="text-sm"></span>
</Button>
</Link>
</div>
)}
<div className="flex items-center space-x-3">
<ThemeToggle />
<Link href="/forum">
<Button variant="outline" size="sm">
</Button>
</Link>
{isAuthenticated && user ? (
// 登录后状态 - 用户下拉菜单
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="flex items-center space-x-2 px-3 hover:bg-muted/50">
<Avatar className="w-8 h-8">
<AvatarFallback className="bg-gradient-to-r from-blue-600 to-blue-800 text-white text-sm font-medium">
{user.full_name?.[0] || user.username[0] || "U"}
</AvatarFallback>
</Avatar>
<div className="hidden sm:block text-left">
<div className="text-sm font-medium text-foreground">
{user.full_name || user.username}
</div>
<div className="text-xs text-muted-foreground">
{user.email}
</div>
</div>
<ChevronDown className="w-4 h-4 text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<div className="px-2 py-1.5">
<div className="font-medium text-sm">{user.full_name || user.username}</div>
<div className="text-xs text-muted-foreground">{user.email}</div>
</div>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link href="/analytics" className="flex items-center cursor-pointer">
<TrendingUp className="w-4 h-4 mr-2" />
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href="/profile" className="flex items-center cursor-pointer">
<UserIcon className="w-4 h-4 mr-2" />
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href="/settings" className="flex items-center cursor-pointer">
<Settings className="w-4 h-4 mr-2" />
</Link>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={logout} className="text-destructive cursor-pointer">
<LogOut className="w-4 h-4 mr-2" />
退
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : (
// 未登录状态
<div className="flex items-center space-x-2">
<Button variant="ghost" asChild>
<Link href="/login"></Link>
</Button>
<Button asChild>
<Link href="/register"></Link>
</Button>
</div>
)}
</div>
</div>
</div>
</nav>
);
}
+75
View File
@@ -0,0 +1,75 @@
"use client";
import { NumberTicker } from "@/components/magicui/number-ticker";
import { User } from "@/types";
interface StatsSectionProps {
isAuthenticated: boolean;
user: User | null;
}
export default function StatsSection({ isAuthenticated, user }: StatsSectionProps) {
// 未登录状态 - 全局统计
const globalStats = [
{ label: "智能问答", value: 1000, description: "问题解答" },
{ label: "知识库", value: 50, description: "专业文档" },
{ label: "用户", value: 500, description: "活跃用户" },
{ label: "准确率", value: 95, description: "回答准确率", suffix: "%" },
];
// 登录后状态 - 个人统计(模拟数据,实际应该从API获取)
const personalStats = [
{ label: "我的问答", value: 0, description: "已提问" },
{ label: "我的文档", value: 0, description: "已上传" },
{ label: "学习时长", value: 0, description: "分钟" },
{ label: "知识点", value: 0, description: "已掌握", suffix: "%" },
];
const stats = isAuthenticated ? personalStats : globalStats;
return (
<section className="py-24 sm:py-32 bg-gray-50">
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<div className="mx-auto max-w-2xl text-center">
<h2 className="text-base font-semibold leading-7 text-primary">
{isAuthenticated ? "学习统计" : "平台数据"}
</h2>
<p className="mt-2 text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
{isAuthenticated ? "您的学习成果" : "值得信赖的数据"}
</p>
<p className="mt-6 text-lg leading-8 text-gray-600">
{isAuthenticated
? "跟踪您的学习进度,见证知识积累的过程"
: "基于真实用户数据,展示平台的专业性和可靠性"
}
</p>
</div>
<div className="mx-auto mt-16 max-w-2xl sm:mt-20 lg:mt-24 lg:max-w-none">
<dl className="grid grid-cols-1 gap-x-8 gap-y-16 text-center lg:grid-cols-4">
{stats.map((stat) => (
<div key={stat.label} className="mx-auto flex max-w-xs flex-col gap-y-4">
<dt className="text-base leading-7 text-gray-600">
{stat.label}
</dt>
<dd className="order-first text-3xl font-semibold tracking-tight text-gray-900 sm:text-5xl">
<NumberTicker value={stat.value} />
{stat.suffix}
</dd>
<dd className="text-sm leading-6 text-gray-500">
{stat.description}
</dd>
</div>
))}
</dl>
</div>
</div>
</section>
);
}
+389
View File
@@ -0,0 +1,389 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
BookOpen,
MessageSquare,
Image,
BarChart3,
ArrowRight,
CheckCircle,
Users,
Zap,
Brain,
Database,
Mail,
Phone,
MapPin
} from "lucide-react";
import { FlickeringGrid } from "@/components/magicui/flickering-grid";
import { AuroraText } from "@/components/magicui/aurora-text";
import { NumberTicker } from "@/components/magicui/number-ticker";
import { BentoCard, BentoGrid } from "@/components/magicui/bento-grid";
import { ThemeToggle } from "@/components/ui/theme-toggle";
export default function LandingPage() {
const [isHovered, setIsHovered] = useState<string | null>(null);
const features = [
{
icon: MessageSquare,
name: "智能问答",
description: "基于大模型的智能问答系统,支持多轮对话和上下文理解",
href: "#",
cta: "了解更多",
className: "lg:col-start-1 lg:col-end-2 lg:row-start-1 lg:row-end-3",
},
{
icon: BookOpen,
name: "知识库管理",
description: "多模态知识库,支持文档上传、向量化和智能检索",
href: "#",
cta: "了解更多",
className: "lg:col-start-1 lg:col-end-2 lg:row-start-3 lg:row-end-4",
},
{
icon: Image,
name: "空间出图",
description: "结合空间规划知识的图像生成和分析功能",
href: "#",
cta: "了解更多",
className: "lg:col-start-2 lg:col-end-3 lg:row-start-1 lg:row-end-2",
},
{
icon: BarChart3,
name: "学习分析",
description: "学习数据统计和可视化,帮助了解学习进度",
href: "#",
cta: "了解更多",
className: "lg:col-start-2 lg:col-end-3 lg:row-start-2 lg:row-end-3",
},
];
const stats = [
{ label: "智能问答", value: 1000, description: "问题解答" },
{ label: "知识库", value: 50, description: "专业文档" },
{ label: "用户", value: 500, description: "活跃用户" },
{ label: "准确率", value: 95, description: "回答准确率", suffix: "%" },
];
return (
<div className="min-h-screen bg-app">
{/* 导航栏 */}
<nav className="border-b bg-background/80 backdrop-blur-sm sticky top-0 z-50">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between items-center h-16">
<div className="flex items-center space-x-3">
<div className="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
<BookOpen className="w-6 h-6 text-white" />
</div>
<span className="text-xl font-bold">
</span>
</div>
<div className="flex items-center space-x-4">
<ThemeToggle />
<Button variant="ghost" asChild>
<Link href="/login"></Link>
</Button>
<Button asChild>
<Link href="/register"></Link>
</Button>
</div>
</div>
</div>
</nav>
{/* 主要内容 */}
<main>
{/* 英雄区域 */}
<section className="flex h-[90vh] w-full flex-col items-center justify-center pb-15 relative">
<FlickeringGrid
className="absolute inset-0 z-0 [mask-image:radial-gradient(800px_circle_at_center,white,transparent)]"
squareSize={4}
gridGap={4}
color="#60A5FA"
maxOpacity={0.133}
flickerChance={0.1}
/>
<div className="relative z-10 flex flex-col items-center justify-center gap-12 px-4">
<div className="inline-flex items-center px-4 py-2 rounded-full bg-secondary/50 backdrop-blur-sm border border-border mb-4">
<span className="text-sm font-medium">🚀 AI驱动的智能学习平台</span>
</div>
<h1 className="text-center text-4xl font-bold md:text-6xl">
<span className="bg-gradient-to-r from-foreground via-foreground/80 to-foreground/60 bg-clip-text text-transparent">
{" "}
</span>
<AuroraText></AuroraText>
<br />
<span className="text-3xl md:text-5xl"></span>
</h1>
<p className="max-w-4xl p-2 text-center text-sm opacity-85 md:text-xl text-muted-foreground">
</p>
<div className="flex flex-col sm:flex-row gap-6 justify-center">
<Button size="lg" className="text-lg" asChild>
<Link href="/register">
<span className="flex items-center">
<ArrowRight className="ml-2 w-5 h-5" />
</span>
</Link>
</Button>
<Button variant="outline" size="lg" className="text-lg" asChild>
<Link href="/login"></Link>
</Button>
</div>
</div>
</section>
{/* 统计数据 */}
<section className="py-20 bg-secondary/30">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="grid grid-cols-2 lg:grid-cols-4 gap-6 lg:gap-8">
{stats.map((stat, index) => (
<div
key={index}
className="group text-center p-6 rounded-2xl bg-card backdrop-blur-sm border hover:shadow-lg transition-all duration-300 hover:scale-105"
>
<div className="text-3xl sm:text-4xl font-bold mb-2 group-hover:text-primary transition-colors">
<NumberTicker value={stat.value} />
{stat.suffix || '+'}
</div>
<div className="text-sm sm:text-base font-semibold mb-1">
{stat.label}
</div>
<div className="text-xs sm:text-sm text-muted-foreground">
{stat.description}
</div>
</div>
))}
</div>
</div>
</section>
{/* 核心功能 - Bento Grid */}
<section className="py-24">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center mb-20">
<h2 className="text-4xl font-bold mb-6">
</h2>
<p className="text-xl text-muted-foreground max-w-3xl mx-auto">
AI技术
</p>
</div>
<BentoGrid className="lg:grid-cols-2 lg:grid-rows-3">
{features.map((feature) => (
<BentoCard
key={feature.name}
Icon={feature.icon}
name={feature.name}
description={feature.description}
href={feature.href}
cta={feature.cta}
className={feature.className}
/>
))}
</BentoGrid>
</div>
</section>
{/* 技术优势 */}
<section className="py-24 bg-secondary/30">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16 items-center">
<div>
<h2 className="text-4xl font-bold mb-8">
</h2>
<div className="space-y-6">
<div className="flex items-start space-x-4 p-6 rounded-2xl bg-card backdrop-blur-sm border hover:shadow-md transition-all duration-300">
<div className="w-12 h-12 bg-gradient-to-r from-green-500 to-emerald-500 rounded-xl flex items-center justify-center flex-shrink-0">
<Brain className="w-6 h-6 text-white" />
</div>
<div>
<h3 className="text-xl font-bold mb-3">
</h3>
<p className="text-muted-foreground leading-relaxed">
Qwen3-30B模型
</p>
</div>
</div>
<div className="flex items-start space-x-4 p-6 rounded-2xl bg-card backdrop-blur-sm border hover:shadow-md transition-all duration-300">
<div className="w-12 h-12 bg-gradient-to-r from-blue-500 to-cyan-500 rounded-xl flex items-center justify-center flex-shrink-0">
<Database className="w-6 h-6 text-white" />
</div>
<div>
<h3 className="text-xl font-bold mb-3">
RAG知识检索
</h3>
<p className="text-muted-foreground leading-relaxed">
</p>
</div>
</div>
<div className="flex items-start space-x-4 p-6 rounded-2xl bg-card backdrop-blur-sm border hover:shadow-md transition-all duration-300">
<div className="w-12 h-12 bg-gradient-to-r from-purple-500 to-pink-500 rounded-xl flex items-center justify-center flex-shrink-0">
<Image className="w-6 h-6 text-white" />
</div>
<div>
<h3 className="text-xl font-bold mb-3">
</h3>
<p className="text-muted-foreground leading-relaxed">
</p>
</div>
</div>
</div>
</div>
<div className="relative">
<div className="bg-gradient-to-br from-blue-600 via-purple-600 to-pink-600 rounded-3xl p-8 lg:p-12 text-white shadow-2xl">
<div className="flex items-center space-x-4 mb-8">
<div className="w-16 h-16 bg-white/20 rounded-2xl flex items-center justify-center">
<Zap className="w-8 h-8" />
</div>
<h3 className="text-3xl font-bold">AI驱动</h3>
</div>
<p className="text-xl mb-8 leading-relaxed opacity-90">
AI技术
</p>
<div className="flex items-center space-x-4 text-lg">
<Users className="w-6 h-6" />
<span className="font-semibold">500+ </span>
</div>
</div>
</div>
</div>
</div>
</section>
{/* CTA区域 */}
<section className="py-24 bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 relative overflow-hidden">
<div className="max-w-4xl mx-auto text-center px-4 sm:px-6 lg:px-8 relative z-10">
<h2 className="text-4xl sm:text-5xl font-bold text-white mb-6">
</h2>
<p className="text-xl text-white/90 mb-12 max-w-2xl mx-auto">
AI驱动的国土空间规划学习平台
</p>
<div className="flex flex-col sm:flex-row gap-6 justify-center">
<Button size="lg" className="w-full sm:w-auto bg-white text-blue-600 hover:bg-white/90 px-8 py-4 text-lg font-semibold shadow-2xl" asChild>
<Link href="/register">
<span className="flex items-center">
<ArrowRight className="ml-2 w-5 h-5" />
</span>
</Link>
</Button>
<Button size="lg" variant="outline" className="w-full sm:w-auto text-white border-white/30 hover:bg-white/10 px-8 py-4 text-lg font-semibold" asChild>
<Link href="/login"></Link>
</Button>
</div>
</div>
</section>
</main>
{/* 统一封底区域 */}
<footer className="bg-card text-foreground border-t">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
{/* 主要内容区域 - 三列布局(中间留空) */}
<div className="py-12 border-b border-border/50">
<div className="grid grid-cols-1 lg:grid-cols-[2fr_2fr_1fr] gap-8 lg:gap-12">
{/* 第一列:关于项目 */}
<div>
<h2 className="text-2xl font-bold text-foreground mb-4"></h2>
<p className="text-muted-foreground leading-relaxed mb-6">
AI技术的智能学习平台RAG技术AI能力
</p>
<div className="flex flex-col sm:flex-row gap-3">
<Button asChild variant="outline" size="sm">
<a href="https://tsp.spacekg.com/#/" target="_blank" rel="noopener noreferrer">
<BookOpen className="mr-2 h-4 w-4" />
</a>
</Button>
<Button asChild variant="outline" size="sm">
<a href="https://homepage.hit.edu.cn/wusongtao" target="_blank" rel="noopener noreferrer">
<Users className="mr-2 h-4 w-4" />
</a>
</Button>
</div>
</div>
{/* 第二列:展示图片 */}
<div className="hidden lg:flex items-center justify-center">
<div className="relative w-full max-w-xs">
<img
src="/heilongjiang-spatial-planning.png"
alt="黑龙江国土空间规划"
className="w-full h-auto rounded-lg shadow-lg object-cover"
/>
</div>
</div>
{/* 第三列:联系我们 */}
<div>
<h3 className="text-lg font-semibold text-foreground mb-4"></h3>
<ul className="space-y-3">
<li className="flex items-start gap-3">
<Mail className="w-5 h-5 text-muted-foreground mt-0.5 flex-shrink-0" />
<div>
<p className="text-sm text-muted-foreground"></p>
<a href="mailto:contact@hit-agent.com" className="text-sm text-foreground hover:text-primary transition-colors">
contact@hit-agent.com
</a>
</div>
</li>
<li className="flex items-start gap-3">
<Phone className="w-5 h-5 text-muted-foreground mt-0.5 flex-shrink-0" />
<div>
<p className="text-sm text-muted-foreground"></p>
<a href="tel:+86-451-86412114" className="text-sm text-foreground hover:text-primary transition-colors">
+86-451-86412114
</a>
</div>
</li>
<li className="flex items-start gap-3">
<MapPin className="w-5 h-5 text-muted-foreground mt-0.5 flex-shrink-0" />
<div>
<p className="text-sm text-muted-foreground"></p>
<p className="text-sm text-foreground">
西92
</p>
</div>
</li>
</ul>
</div>
</div>
</div>
{/* Footer信息部分 */}
<div className="py-8">
<div className="text-center">
<div className="flex items-center justify-center gap-2 mb-3">
<div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-blue-800 rounded-lg flex items-center justify-center">
<BookOpen className="w-4 h-4 text-white" />
</div>
<span className="text-lg font-semibold"></span>
</div>
<p className="text-xs text-muted-foreground">
Copyright © {new Date().getFullYear()}
</p>
</div>
</div>
</div>
</footer>
</div>
);
}
+169
View File
@@ -0,0 +1,169 @@
"use client";
import { useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import { Button } from "@/components/ui/button";
import {
MessageSquare,
BookOpen,
Image,
Settings,
Menu,
X,
User,
LogOut,
GraduationCap,
TrendingUp
} from "lucide-react";
const navItems = [
{ id: "course-content", name: "课程内容", icon: GraduationCap, href: "/course-content" },
{ id: "chat", name: "对话", icon: MessageSquare, href: "/chat" },
{ id: "knowledge", name: "知识库", icon: BookOpen, href: "/knowledge" },
{ id: "spatial", name: "空间出图", icon: Image, href: "/spatial" },
];
export default function MobileNav() {
const [isOpen, setIsOpen] = useState(false);
const router = useRouter();
const pathname = usePathname();
const { user, logout } = useAuthStore();
const handleNavClick = (href: string) => {
router.push(href);
setIsOpen(false);
};
const handleLogout = () => {
logout();
router.push("/");
setIsOpen(false);
};
return (
<>
{/* 移动端导航栏 */}
<div className="lg:hidden fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 mobile-safe-area z-50">
<div className="flex items-center justify-around py-2">
{navItems.map((item) => {
const isActive = pathname === item.href;
return (
<Button
key={item.id}
variant={isActive ? "default" : "ghost"}
size="sm"
onClick={() => handleNavClick(item.href)}
className={`flex flex-col items-center space-y-1 px-3 py-2 ${
isActive ? "text-white" : "text-gray-600"
}`}
>
<item.icon className="w-5 h-5" />
<span className="text-xs">{item.name}</span>
</Button>
);
})}
</div>
</div>
{/* 移动端菜单按钮 */}
<div className="lg:hidden fixed top-4 right-4 z-50">
<Button
variant="outline"
size="icon"
onClick={() => setIsOpen(!isOpen)}
className="bg-white shadow-lg"
>
{isOpen ? <X className="w-4 h-4" /> : <Menu className="w-4 h-4" />}
</Button>
</div>
{/* 移动端侧边菜单 */}
{isOpen && (
<div className="lg:hidden fixed inset-0 z-40">
{/* 遮罩 */}
<div
className="absolute inset-0 bg-black bg-opacity-50"
onClick={() => setIsOpen(false)}
/>
{/* 菜单内容 */}
<div className="absolute right-0 top-0 h-full w-80 max-w-[85vw] bg-white shadow-xl mobile-safe-area">
<div className="flex flex-col h-full">
{/* 用户信息 */}
<div className="p-6 border-b border-gray-200">
<div className="flex items-center space-x-3">
<div className="w-12 h-12 bg-gray-200 rounded-full flex items-center justify-center">
<User className="w-6 h-6 text-gray-600" />
</div>
<div className="flex-1 min-w-0">
<p className="text-lg font-medium text-gray-900 truncate">
{user?.full_name || user?.username}
</p>
<p className="text-sm text-gray-500 truncate">
{user?.email}
</p>
</div>
</div>
</div>
{/* 导航菜单 */}
<div className="flex-1 p-6">
<nav className="space-y-2">
{navItems.map((item) => {
const isActive = pathname === item.href;
return (
<Button
key={item.id}
variant={isActive ? "default" : "ghost"}
onClick={() => handleNavClick(item.href)}
className="w-full justify-start"
>
<item.icon className="w-5 h-5 mr-3" />
{item.name}
</Button>
);
})}
</nav>
</div>
{/* 底部操作 */}
<div className="p-6 border-t border-gray-200 space-y-2">
<Button
variant="ghost"
onClick={() => handleNavClick("/analytics")}
className="w-full justify-start"
>
<TrendingUp className="w-5 h-5 mr-3" />
</Button>
<Button
variant="ghost"
onClick={() => handleNavClick("/settings")}
className="w-full justify-start"
>
<Settings className="w-5 h-5 mr-3" />
</Button>
<Button
variant="ghost"
onClick={handleLogout}
className="w-full justify-start text-red-600 hover:text-red-700 hover:bg-red-50"
>
<LogOut className="w-5 h-5 mr-3" />
退
</Button>
</div>
</div>
</div>
</div>
)}
</>
);
}
@@ -0,0 +1,50 @@
"use client";
import React, { memo } from "react";
interface AuroraTextProps {
children: React.ReactNode;
className?: string;
colors?: string[];
speed?: number;
}
export const AuroraText = memo(
({
children,
className = "",
colors = ["#FF0080", "#7928CA", "#0070F3", "#38bdf8"],
speed = 1,
}: AuroraTextProps) => {
const gradientStyle = {
backgroundImage: `linear-gradient(135deg, ${colors.join(", ")}, ${
colors[0]
})`,
WebkitBackgroundClip: "text",
WebkitTextFillColor: "transparent",
animationDuration: `${10 / speed}s`,
};
return (
<span className={`relative inline-block ${className}`}>
<span className="sr-only">{children}</span>
<span
className="relative animate-aurora bg-[length:200%_auto] bg-clip-text text-transparent"
style={gradientStyle}
aria-hidden="true"
>
{children}
</span>
</span>
);
},
);
AuroraText.displayName = "AuroraText";
+83
View File
@@ -0,0 +1,83 @@
import { ArrowRightIcon } from "@radix-ui/react-icons";
import type { ComponentPropsWithoutRef, ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
interface BentoGridProps extends ComponentPropsWithoutRef<"div"> {
children: ReactNode;
className?: string;
}
interface BentoCardProps extends ComponentPropsWithoutRef<"div"> {
name: string;
className: string;
background?: ReactNode;
Icon: React.ElementType;
description: string;
href: string;
cta: string;
}
const BentoGrid = ({ children, className, ...props }: BentoGridProps) => {
return (
<div
className={cn("grid w-full auto-rows-auto grid-cols-2 gap-4", className)}
{...props}
>
{children}
</div>
);
};
const BentoCard = ({
name,
className,
background,
Icon,
description,
href,
cta,
...props
}: BentoCardProps) => (
<div
key={name}
className={cn(
"group relative col-span-3 flex flex-col justify-between overflow-hidden rounded-xl",
// light styles
"bg-background [box-shadow:0_0_0_1px_rgba(0,0,0,.03),0_2px_4px_rgba(0,0,0,.05),0_12px_24px_rgba(0,0,0,.05)]",
// dark styles
"dark:bg-background transform-gpu dark:[box-shadow:0_-20px_80px_-20px_#ffffff1f_inset] dark:[border:1px_solid_rgba(255,255,255,.1)]",
className,
)}
{...props}
>
{background && <div>{background}</div>}
<div className="z-10 flex transform-gpu flex-col gap-1 p-6 transition-all duration-300 group-hover:-translate-y-5">
<Icon className="h-12 w-12 origin-left transform-gpu text-neutral-700 transition-all duration-300 ease-in-out group-hover:scale-75 dark:text-neutral-300" />
<h3 className="text-xl font-semibold text-neutral-700 dark:text-neutral-300">
{name}
</h3>
<p className="max-w-lg text-neutral-400">{description}</p>
</div>
<div
className={cn(
"pointer-events-none absolute bottom-0 flex w-full translate-y-10 transform-gpu flex-row items-center p-4 opacity-0 transition-all duration-300 group-hover:translate-y-0 group-hover:opacity-100",
)}
>
<Button variant="ghost" asChild size="sm" className="pointer-events-auto">
<a href={href}>
<span className="flex items-center">
{cta}
<ArrowRightIcon className="ms-2 h-4 w-4 rtl:rotate-180" />
</span>
</a>
</Button>
</div>
<div className="pointer-events-none absolute inset-0 transform-gpu transition-all duration-300 group-hover:bg-black/[.03] group-hover:dark:bg-neutral-800/10" />
</div>
);
export { BentoCard, BentoGrid };
@@ -0,0 +1,200 @@
"use client";
import { cn } from "@/lib/utils";
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
interface FlickeringGridProps extends React.HTMLAttributes<HTMLDivElement> {
squareSize?: number;
gridGap?: number;
flickerChance?: number;
color?: string;
width?: number;
height?: number;
className?: string;
maxOpacity?: number;
}
export const FlickeringGrid: React.FC<FlickeringGridProps> = ({
squareSize = 4,
gridGap = 6,
flickerChance = 0.3,
color = "rgb(0, 0, 0)",
width,
height,
className,
maxOpacity = 0.3,
...props
}) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [isInView, setIsInView] = useState(false);
const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 });
const memoizedColor = useMemo(() => {
const toRGBA = (color: string) => {
if (typeof window === "undefined") {
return `rgba(0, 0, 0,`;
}
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 1;
const ctx = canvas.getContext("2d");
if (!ctx) return "rgba(255, 0, 0,";
ctx.fillStyle = color;
ctx.fillRect(0, 0, 1, 1);
const [r, g, b] = Array.from(ctx.getImageData(0, 0, 1, 1).data);
return `rgba(${r}, ${g}, ${b},`;
};
return toRGBA(color);
}, [color]);
const setupCanvas = useCallback(
(canvas: HTMLCanvasElement, width: number, height: number) => {
const dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
const cols = Math.floor(width / (squareSize + gridGap));
const rows = Math.floor(height / (squareSize + gridGap));
const squares = new Float32Array(cols * rows);
for (let i = 0; i < squares.length; i++) {
squares[i] = Math.random() * maxOpacity;
}
return { cols, rows, squares, dpr };
},
[squareSize, gridGap, maxOpacity],
);
const updateSquares = useCallback(
(squares: Float32Array, deltaTime: number) => {
for (let i = 0; i < squares.length; i++) {
if (Math.random() < flickerChance * deltaTime) {
squares[i] = Math.random() * maxOpacity;
}
}
},
[flickerChance, maxOpacity],
);
const drawGrid = useCallback(
(
ctx: CanvasRenderingContext2D,
width: number,
height: number,
cols: number,
rows: number,
squares: Float32Array,
dpr: number,
) => {
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "transparent";
ctx.fillRect(0, 0, width, height);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
const opacity = squares[i * rows + j];
ctx.fillStyle = `${memoizedColor}${opacity})`;
ctx.fillRect(
i * (squareSize + gridGap) * dpr,
j * (squareSize + gridGap) * dpr,
squareSize * dpr,
squareSize * dpr,
);
}
}
},
[memoizedColor, squareSize, gridGap],
);
useEffect(() => {
const canvas = canvasRef.current;
const container = containerRef.current;
if (!canvas || !container) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
let animationFrameId: number;
let gridParams: ReturnType<typeof setupCanvas>;
const updateCanvasSize = () => {
const newWidth = width || container.clientWidth;
const newHeight = height || container.clientHeight;
setCanvasSize({ width: newWidth, height: newHeight });
gridParams = setupCanvas(canvas, newWidth, newHeight);
};
updateCanvasSize();
let lastTime = 0;
const animate = (time: number) => {
if (!isInView) return;
const deltaTime = (time - lastTime) / 1000;
lastTime = time;
updateSquares(gridParams.squares, deltaTime);
drawGrid(
ctx,
canvas.width,
canvas.height,
gridParams.cols,
gridParams.rows,
gridParams.squares,
gridParams.dpr,
);
animationFrameId = requestAnimationFrame(animate);
};
const resizeObserver = new ResizeObserver(() => {
updateCanvasSize();
});
resizeObserver.observe(container);
const intersectionObserver = new IntersectionObserver(
([entry]) => {
setIsInView(entry!.isIntersecting);
},
{ threshold: 0 },
);
intersectionObserver.observe(canvas);
if (isInView) {
animationFrameId = requestAnimationFrame(animate);
}
return () => {
cancelAnimationFrame(animationFrameId);
resizeObserver.disconnect();
intersectionObserver.disconnect();
};
}, [setupCanvas, updateSquares, drawGrid, width, height, isInView]);
return (
<div
ref={containerRef}
className={cn(`h-full w-full ${className}`)}
{...props}
>
<canvas
ref={canvasRef}
className="pointer-events-none"
style={{
width: canvasSize.width,
height: canvasSize.height,
}}
/>
</div>
);
};
@@ -0,0 +1,68 @@
"use client";
import { useInView, useMotionValue, useSpring } from "framer-motion";
import { type ComponentPropsWithoutRef, useEffect, useRef } from "react";
import { cn } from "@/lib/utils";
interface NumberTickerProps extends ComponentPropsWithoutRef<"span"> {
value: number;
startValue?: number;
direction?: "up" | "down";
delay?: number;
decimalPlaces?: number;
}
export function NumberTicker({
value,
startValue = 0,
direction = "up",
delay = 0,
className,
decimalPlaces = 0,
...props
}: NumberTickerProps) {
const ref = useRef<HTMLSpanElement>(null);
const motionValue = useMotionValue(direction === "down" ? value : startValue);
const springValue = useSpring(motionValue, {
damping: 60,
stiffness: 100,
});
const isInView = useInView(ref, { once: true, margin: "0px" });
useEffect(() => {
if (isInView) {
const timer = setTimeout(() => {
motionValue.set(direction === "down" ? startValue : value);
}, delay * 1000);
return () => clearTimeout(timer);
}
}, [motionValue, isInView, delay, value, direction, startValue]);
useEffect(
() =>
springValue.on("change", (latest) => {
if (ref.current) {
ref.current.textContent = Intl.NumberFormat("en-US", {
minimumFractionDigits: decimalPlaces,
maximumFractionDigits: decimalPlaces,
}).format(Number(latest.toFixed(decimalPlaces)));
}
}),
[springValue, decimalPlaces],
);
return (
<span
ref={ref}
className={cn(
"inline-block tracking-wider tabular-nums",
className,
)}
{...props}
>
{startValue}
</span>
);
}
+59
View File
@@ -0,0 +1,59 @@
"use client"
import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const Accordion = AccordionPrimitive.Root
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border-b", className)}
{...props}
/>
))
AccordionItem.displayName = "AccordionItem"
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
))
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
))
AccordionContent.displayName = AccordionPrimitive.Content.displayName
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
+64
View File
@@ -0,0 +1,64 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };
+56
View File
@@ -0,0 +1,56 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }
+42
View File
@@ -0,0 +1,42 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
+93
View File
@@ -0,0 +1,93 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"mit-button inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "mit-button-primary",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary: "mit-button-secondary",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-8 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
loading?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, loading = false, disabled, children, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
if (asChild) {
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
>
{children}
</Comp>
);
}
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
disabled={disabled || loading}
{...props}
>
{loading && (
<svg
className="mr-2 h-4 w-4 animate-spin"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
)}
{children}
</Comp>
);
}
);
Button.displayName = "Button";
export { Button, buttonVariants };
+84
View File
@@ -0,0 +1,84 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"mit-card",
className
)}
{...props}
/>
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn(
"text-xl font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
));
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
+128
View File
@@ -0,0 +1,128 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
+206
View File
@@ -0,0 +1,206 @@
"use client";
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
);
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
};
+30
View File
@@ -0,0 +1,30 @@
import * as React from "react";
import { cn } from "@/lib/utils";
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = "Input";
export { Input };
+26
View File
@@ -0,0 +1,26 @@
"use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };
+48
View File
@@ -0,0 +1,48 @@
import { cn } from "@/lib/utils";
interface LoadingSpinnerProps {
size?: "sm" | "md" | "lg";
className?: string;
}
export default function LoadingSpinner({
size = "md",
className
}: LoadingSpinnerProps) {
const sizeClasses = {
sm: "h-4 w-4",
md: "h-8 w-8",
lg: "h-12 w-12",
};
return (
<div className={cn("flex items-center justify-center", className)}>
<svg
className={cn("animate-spin text-primary", sizeClasses[size])}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
</div>
);
}
+50
View File
@@ -0,0 +1,50 @@
"use client";
import * as React from "react";
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Root
className={cn("grid gap-2", className)}
{...props}
ref={ref}
/>
);
});
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName;
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
});
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;
export { RadioGroup, RadioGroupItem };
+48
View File
@@ -0,0 +1,48 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }
+166
View File
@@ -0,0 +1,166 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}
+37
View File
@@ -0,0 +1,37 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }
+34
View File
@@ -0,0 +1,34 @@
"use client"
import * as React from "react"
import * as SliderPrimitive from "@radix-ui/react-slider"
import { cn } from "@/lib/utils"
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn(
"relative flex w-full touch-none select-none items-center",
className
)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
export { Slider }
+117
View File
@@ -0,0 +1,117 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}
+55
View File
@@ -0,0 +1,55 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
+30
View File
@@ -0,0 +1,30 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Textarea.displayName = "Textarea"
export { Textarea }
+40
View File
@@ -0,0 +1,40 @@
"use client";
import * as React from "react";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
import { Button } from "@/components/ui/button";
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return (
<Button variant="ghost" size="icon" className="w-9 h-9">
<Sun className="h-4 w-4" />
</Button>
);
}
return (
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
className="w-9 h-9"
>
{theme === "light" ? (
<Moon className="h-4 w-4" />
) : (
<Sun className="h-4 w-4" />
)}
</Button>
);
}
+1082
View File
File diff suppressed because it is too large Load Diff
+84
View File
@@ -0,0 +1,84 @@
import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { z } from "zod";
const loginSchema = z.object({
username: z.string().min(1, "用户名不能为空"),
password: z.string().min(1, "密码不能为空"),
});
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
username: { label: "用户名", type: "text" },
password: { label: "密码", type: "password" },
},
async authorize(credentials) {
if (!credentials) return null;
try {
const validatedFields = loginSchema.safeParse(credentials);
if (!validatedFields.success) {
return null;
}
const { username, password } = validatedFields.data;
// 调用后端API进行认证
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username, password }),
});
if (!response.ok) {
return null;
}
const user = await response.json();
return {
id: user.id.toString(),
username: user.username,
email: user.email,
name: user.full_name || user.username,
};
} catch (error) {
console.error("认证错误:", error);
return null;
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.username = (user as any).username;
token.email = user.email;
}
return token;
},
async session({ session, token }) {
if (token && session.user) {
(session.user as any).id = token.id as string;
(session.user as any).username = token.username as string;
(session.user as any).email = token.email as string;
}
return session;
},
},
pages: {
signIn: "/login",
error: "/login",
},
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
};
+135
View File
@@ -0,0 +1,135 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function formatDate(date: string | Date) {
let d: Date;
if (typeof date === 'string') {
// 如果字符串不包含时区信息(没有Z或+/-XX:XX),添加Z表示UTC
if (!date.includes('Z') && !date.match(/[+-]\d{2}:\d{2}$/)) {
d = new Date(date + 'Z');
} else {
d = new Date(date);
}
} else {
d = date;
}
// 明确指定使用北京时区(Asia/Shanghai = UTC+8
return d.toLocaleString("zh-CN", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
timeZone: "Asia/Shanghai",
});
}
export function formatFileSize(bytes: number) {
if (bytes === 0) return "0 Bytes";
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}
export function truncateText(text: string, maxLength: number) {
if (text.length <= maxLength) return text;
return text.slice(0, maxLength) + "...";
}
export function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let timeout: NodeJS.Timeout;
return (...args: Parameters<T>) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
}
export function throttle<T extends (...args: any[]) => any>(
func: T,
limit: number
): (...args: Parameters<T>) => void {
let inThrottle: boolean;
return (...args: Parameters<T>) => {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
export function generateId(): string {
return Math.random().toString(36).substr(2, 9);
}
export function isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
export function isValidUrl(url: string): boolean {
try {
new URL(url);
return true;
} catch {
return false;
}
}
export function copyToClipboard(text: string): Promise<void> {
if (navigator.clipboard) {
return navigator.clipboard.writeText(text);
} else {
// Fallback for older browsers
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
document.body.removeChild(textArea);
return Promise.resolve();
}
}
export function downloadFile(url: string, filename: string) {
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
export function getInitials(name: string): string {
return name
.split(" ")
.map((word) => word.charAt(0))
.join("")
.toUpperCase()
.slice(0, 2);
}
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+164
View File
@@ -0,0 +1,164 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { User, LoginCredentials, RegisterData } from "@/types";
import { authAPI } from "@/lib/api";
interface AuthState {
user: User | null;
token: string | null;
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
}
interface AuthActions {
login: (credentials: LoginCredentials) => Promise<boolean>;
register: (data: RegisterData) => Promise<boolean>;
logout: () => void;
setUser: (user: User) => void;
setToken: (token: string) => void;
setLoading: (loading: boolean) => void;
setError: (error: string | null) => void;
clearError: () => void;
refreshUser: () => Promise<void>;
}
type AuthStore = AuthState & AuthActions;
export const useAuthStore = create<AuthStore>()(
persist(
(set, get) => ({
// 初始状态
user: null,
token: null,
isAuthenticated: false,
isLoading: false,
error: null,
// 登录
login: async (credentials: LoginCredentials) => {
set({ isLoading: true, error: null });
try {
const response = await authAPI.login(credentials.username, credentials.password);
// 保存token
localStorage.setItem("auth_token", response.access_token);
// 获取用户信息
const user = await authAPI.getCurrentUser();
set({
user,
token: response.access_token,
isAuthenticated: true,
isLoading: false,
error: null,
});
return true;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "登录失败";
set({
error: errorMessage,
isLoading: false,
isAuthenticated: false,
});
return false;
}
},
// 注册
register: async (data: RegisterData) => {
set({ isLoading: true, error: null });
try {
const user = await authAPI.register(data);
set({
user,
isAuthenticated: true,
isLoading: false,
error: null,
});
return true;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "注册失败";
set({
error: errorMessage,
isLoading: false,
isAuthenticated: false,
});
return false;
}
},
// 登出
logout: () => {
localStorage.removeItem("auth_token");
set({
user: null,
token: null,
isAuthenticated: false,
error: null,
});
},
// 设置用户
setUser: (user: User) => {
set({ user, isAuthenticated: true });
},
// 设置token
setToken: (token: string) => {
localStorage.setItem("auth_token", token);
set({ token, isAuthenticated: true });
},
// 设置加载状态
setLoading: (loading: boolean) => {
set({ isLoading: loading });
},
// 设置错误
setError: (error: string | null) => {
set({ error });
},
// 清除错误
clearError: () => {
set({ error: null });
},
// 刷新用户信息
refreshUser: async () => {
const { token } = get();
if (!token) return;
try {
const user = await authAPI.getCurrentUser();
set({ user });
} catch (error) {
console.error("刷新用户信息失败:", error);
// 如果token无效,清除认证状态
get().logout();
}
},
}),
{
name: "auth-storage",
partialize: (state) => ({
user: state.user,
token: state.token,
isAuthenticated: state.isAuthenticated,
}),
}
)
);
+474
View File
@@ -0,0 +1,474 @@
import { create } from "zustand";
import { ChatSession, ChatMessage, SourceInfo, ThinkingStep } from "@/types";
import { chatAPI } from "@/lib/api";
interface ChatState {
sessions: ChatSession[];
currentSession: ChatSession | null;
messages: ChatMessage[];
isLoading: boolean;
isStreaming: boolean;
error: string | null;
abortController: AbortController | null;
}
interface ChatActions {
// 会话管理
loadSessions: () => Promise<void>;
createSession: (title: string) => Promise<ChatSession | null>;
selectSession: (sessionId: number) => Promise<void>;
deleteSession: (sessionId: number) => Promise<void>;
renameSession: (sessionId: number, newTitle: string) => Promise<void>;
exportSession: (sessionId: number, format?: string) => Promise<void>;
// 消息管理
loadMessages: (sessionId: number) => Promise<void>;
sendMessage: (message: string) => Promise<void>;
streamMessage: (message: string, mode?: string, knowledgeBaseIds?: string[], model?: string) => Promise<void>;
addMessage: (message: ChatMessage) => void;
updateMessage: (messageId: number, content: string) => void;
editMessage: (messageId: number, newContent: string) => Promise<void>;
regenerateMessage: (messageId: number) => Promise<void>;
feedbackMessage: (messageId: number, feedback: "like" | "dislike") => Promise<void>;
stopGeneration: () => void;
// 状态管理
setLoading: (loading: boolean) => void;
setStreaming: (streaming: boolean) => void;
setError: (error: string | null) => void;
clearError: () => void;
clearMessages: () => void;
}
type ChatStore = ChatState & ChatActions;
export const useChatStore = create<ChatStore>((set, get) => ({
// 初始状态
sessions: [],
currentSession: null,
messages: [],
isLoading: false,
isStreaming: false,
error: null,
abortController: null,
// 加载会话列表
loadSessions: async () => {
set({ isLoading: true, error: null });
try {
const sessions = await chatAPI.getSessions();
set({ sessions, isLoading: false });
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "加载会话失败";
set({ error: errorMessage, isLoading: false });
}
},
// 创建新会话
createSession: async (title: string) => {
try {
// 直接调用创建会话API
const response = await chatAPI.createSession(title);
const newSession: ChatSession = {
id: response.id,
title: response.title,
created_at: response.created_at,
updated_at: response.updated_at || response.created_at,
message_count: response.message_count || 0,
};
set((state) => ({
sessions: [newSession, ...state.sessions],
currentSession: newSession,
messages: [],
}));
return newSession;
} catch (error) {
console.error("创建会话失败:", error);
return null;
}
},
// 选择会话
selectSession: async (sessionId: number) => {
set({ isLoading: true, error: null });
try {
const session = get().sessions.find(s => s.id === sessionId);
if (!session) {
throw new Error("会话不存在");
}
set({ currentSession: session });
await get().loadMessages(sessionId);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "选择会话失败";
set({ error: errorMessage, isLoading: false });
}
},
// 删除会话
deleteSession: async (sessionId: number) => {
try {
await chatAPI.deleteSession(sessionId);
set((state) => ({
sessions: state.sessions.filter(s => s.id !== sessionId),
currentSession: state.currentSession?.id === sessionId ? null : state.currentSession,
messages: state.currentSession?.id === sessionId ? [] : state.messages,
}));
} catch (error) {
console.error("删除会话失败:", error);
const errorMessage = error instanceof Error ? error.message : "删除会话失败";
set({ error: errorMessage });
}
},
// 重命名会话
renameSession: async (sessionId: number, newTitle: string) => {
try {
await chatAPI.renameSession(sessionId, newTitle);
set((state) => ({
sessions: state.sessions.map(s =>
s.id === sessionId ? { ...s, title: newTitle } : s
),
currentSession: state.currentSession?.id === sessionId
? { ...state.currentSession, title: newTitle }
: state.currentSession,
}));
} catch (error) {
console.error("重命名会话失败:", error);
const errorMessage = error instanceof Error ? error.message : "重命名会话失败";
set({ error: errorMessage });
}
},
// 导出会话
exportSession: async (sessionId: number, format: string = "json") => {
try {
const exportData = await chatAPI.exportSession(sessionId, format);
// 创建下载链接
const blob = new Blob([JSON.stringify(exportData, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${exportData.title || `session-${sessionId}`}.${format}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (error) {
console.error("导出会话失败:", error);
const errorMessage = error instanceof Error ? error.message : "导出会话失败";
set({ error: errorMessage });
}
},
// 加载消息
loadMessages: async (sessionId: number) => {
try {
const messages = await chatAPI.getSessionMessages(sessionId);
set({ messages, isLoading: false });
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "加载消息失败";
set({ error: errorMessage, isLoading: false });
}
},
// 发送消息(非流式)
sendMessage: async (message: string) => {
const { currentSession } = get();
if (!currentSession) return;
set({ isLoading: true, error: null });
// 添加用户消息
const userMessage: ChatMessage = {
id: Date.now(),
role: "user",
content: message,
created_at: new Date().toISOString(),
};
set((state) => ({
messages: [...state.messages, userMessage],
}));
try {
const response = await chatAPI.sendMessage(message, currentSession.id);
// 添加助手回复
const assistantMessage: ChatMessage = {
id: response.message_id,
role: "assistant",
content: response.answer,
created_at: new Date().toISOString(),
metadata: { sources: response.sources },
};
set((state) => ({
messages: [...state.messages, assistantMessage],
isLoading: false,
}));
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "发送消息失败";
set({ error: errorMessage, isLoading: false });
}
},
// 流式发送消息
streamMessage: async (message: string, mode: string = "normal", knowledgeBaseIds?: string[], model?: string) => {
const { currentSession } = get();
if (!currentSession) return;
// 创建新的 AbortController
const abortController = new AbortController();
console.log("[DEBUG-CHAT] 开始流式发送:", {
message: message,
sessionId: currentSession.id,
knowledgeBaseIds: knowledgeBaseIds
});
set({ isStreaming: true, error: null, abortController });
// 添加用户消息
const userMessage: ChatMessage = {
id: Date.now(),
role: "user",
content: message,
created_at: new Date().toISOString(),
};
set((state) => ({
messages: [...state.messages, userMessage],
}));
// 创建助手消息占位符
const assistantMessage: ChatMessage = {
id: Date.now() + 1,
role: "assistant",
content: "",
created_at: new Date().toISOString(),
};
set((state) => ({
messages: [...state.messages, assistantMessage],
}));
let chunkCount = 0;
let totalChars = 0;
let thinkingSteps: ThinkingStep[] = [];
try {
await chatAPI.streamMessage(
message,
currentSession.id,
mode, // 传递实际选择的模式
knowledgeBaseIds,
abortController.signal, // 新增参数
(chunk: string) => {
// 解析chunk
try {
const data = JSON.parse(chunk);
if (data.type === 'thinking') {
// 处理思考过程
thinkingSteps.push({
stage: data.stage,
message: data.message,
doc_count: data.doc_count,
time: data.time
});
// 立即更新思考过程到UI
requestAnimationFrame(() => {
set((state) => ({
messages: state.messages.map(msg =>
msg.id === assistantMessage.id
? { ...msg, thinking: [...thinkingSteps] }
: msg
),
}));
});
} else if (data.type === 'chunk') {
// 处理内容chunk
chunkCount++;
totalChars += data.content.length;
console.log(`[DEBUG-STREAM] 接收并显示chunk ${chunkCount}:`, data.content);
requestAnimationFrame(() => {
set((state) => ({
messages: state.messages.map(msg =>
msg.id === assistantMessage.id
? { ...msg, content: msg.content + data.content }
: msg
),
}));
});
}
} catch (e) {
// 向后兼容:纯文本chunk
chunkCount++;
totalChars += chunk.length;
console.log(`[DEBUG-STREAM] 接收并显示chunk ${chunkCount}:`, chunk);
requestAnimationFrame(() => {
set((state) => ({
messages: state.messages.map(msg =>
msg.id === assistantMessage.id
? { ...msg, content: msg.content + chunk }
: msg
),
}));
});
}
},
(sessionId: number) => {
// 流式完成,直接处理
console.log(`[DEBUG-STREAM] 流式完成 - 总chunk数: ${chunkCount}, 总字符数: ${totalChars}`);
set({ isStreaming: false, abortController: null });
// 刷新会话列表以确保新会话显示在顶部
get().loadSessions();
},
(error: string) => {
// 流式错误
console.log("[DEBUG-STREAM] 流式错误:", error);
set({ error, isStreaming: false, abortController: null });
},
undefined, // onStatus
undefined, // onThinking
undefined, // onThinkingContent
model // 传递模型ID
);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "发送消息失败";
set({ error: errorMessage, isStreaming: false, abortController: null });
}
},
// 添加消息
addMessage: (message: ChatMessage) => {
set((state) => ({
messages: [...state.messages, message],
}));
},
// 更新消息
updateMessage: (messageId: number, content: string) => {
set((state) => ({
messages: state.messages.map(msg =>
msg.id === messageId ? { ...msg, content } : msg
),
}));
},
// 设置加载状态
setLoading: (loading: boolean) => {
set({ isLoading: loading });
},
// 设置流式状态
setStreaming: (streaming: boolean) => {
set({ isStreaming: streaming });
},
// 设置错误
setError: (error: string | null) => {
set({ error });
},
// 清除错误
clearError: () => {
set({ error: null });
},
// 清除消息
clearMessages: () => {
set({ messages: [] });
},
// 编辑消息
editMessage: async (messageId: number, newContent: string) => {
try {
await chatAPI.editMessage(messageId, newContent);
set((state) => ({
messages: state.messages.map(msg =>
msg.id === messageId ? { ...msg, content: newContent, edited: true } : msg
),
}));
} catch (error) {
console.error("编辑消息失败:", error);
const errorMessage = error instanceof Error ? error.message : "编辑消息失败";
set({ error: errorMessage });
}
},
// 重新生成消息
regenerateMessage: async (messageId: number) => {
try {
set({ isLoading: true, error: null });
const response = await chatAPI.regenerateMessage(messageId);
// 删除该消息之后的所有消息
const messageIndex = get().messages.findIndex(msg => msg.id === messageId);
if (messageIndex !== -1) {
set((state) => ({
messages: state.messages.slice(0, messageIndex + 1),
}));
}
// 添加新的助手回复
const newMessage: ChatMessage = {
id: response.new_message_id,
role: "assistant",
content: response.content,
created_at: new Date().toISOString(),
};
set((state) => ({
messages: [...state.messages, newMessage],
isLoading: false,
}));
} catch (error) {
console.error("重新生成消息失败:", error);
const errorMessage = error instanceof Error ? error.message : "重新生成消息失败";
set({ error: errorMessage, isLoading: false });
}
},
// 反馈消息
feedbackMessage: async (messageId: number, feedback: "like" | "dislike") => {
try {
await chatAPI.feedbackMessage(messageId, feedback);
set((state) => ({
messages: state.messages.map(msg =>
msg.id === messageId ? { ...msg, feedback } : msg
),
}));
} catch (error) {
console.error("反馈消息失败:", error);
const errorMessage = error instanceof Error ? error.message : "反馈消息失败";
set({ error: errorMessage });
}
},
// 停止生成
stopGeneration: () => {
const { abortController } = get();
// 如果存在 AbortController,调用 abort 中止请求
if (abortController) {
abortController.abort();
console.log("[DEBUG-STOP] 已中止流式请求");
}
// 清理状态
set({ isStreaming: false, abortController: null });
},
}));
+350
View File
@@ -0,0 +1,350 @@
// 用户相关类型
export interface User {
id: number;
username: string;
email: string;
full_name?: string;
is_active: boolean;
created_at: string;
}
// 认证相关类型
export interface LoginCredentials {
username: string;
password: string;
}
export interface RegisterData {
username: string;
email: string;
password: string;
full_name?: string;
}
export interface AuthToken {
access_token: string;
token_type: string;
}
// 论坛相关类型
export interface ForumCategory {
id: number;
slug: string;
name: string;
description?: string | null;
post_count: number;
}
export interface ForumPostSummary {
id: number;
title: string;
author_name: string;
created_at: string;
reply_count: number;
}
export interface ForumReply {
id: number;
content: string;
author_name: string;
created_at: string;
}
export interface ForumPostDetail {
id: number;
title: string;
content: string;
author_name: string;
created_at: string;
replies: ForumReply[];
}
// 聊天相关类型
export interface ChatSession {
id: number;
title: string;
created_at: string;
updated_at: string;
message_count: number;
}
export interface ThinkingStep {
stage: 'understanding' | 'retrieving' | 'retrieved' | 'generating';
message: string;
doc_count?: number;
time?: number;
}
export interface ChatMessage {
id: number;
role: "user" | "assistant" | "system";
content: string;
created_at: string;
thinking?: ThinkingStep[]; // 新增:思考过程
metadata?: {
sources?: SourceInfo[];
mode?: string;
[key: string]: any;
};
feedback?: string;
edited?: boolean;
regenerated_from?: number;
}
export interface SourceInfo {
title: string;
filename?: string;
page?: number;
score?: number;
preview: string;
url?: string;
source_type?: "web" | "rag";
}
export interface ChatResponse {
answer: string;
sources: SourceInfo[];
session_id: number;
message_id: number;
}
// 课程内容相关类型(旧版本,向后兼容)
export interface CourseModule {
id: number;
module_name: string;
core_knowledge_points: string;
digitalization_necessity: string;
expanded_knowledge_points: string[];
display_order: number;
}
// 书籍结构相关类型
export interface Book {
id: number;
title: string;
description?: string;
}
export interface Subsection {
id: number;
subsection_number: number;
title: string;
display_order: number;
}
export interface Section {
id: number;
section_number: number;
title: string;
display_order: number;
subsections: Subsection[]; // 小节(知识点)列表
}
export interface Chapter {
id: number;
chapter_number: number;
title: string;
display_order: number;
sections: Section[]; // 节列表
}
export interface BookStructure {
book: Book;
chapters: Chapter[];
}
// 知识库相关类型
export interface KnowledgeBase {
id: number;
name: string;
description?: string;
user_id: number;
document_count: number;
created_at: string;
updated_at: string;
is_system?: boolean; // 是否为系统知识库
}
export interface KnowledgeBaseDetail extends KnowledgeBase {
documents: Document[];
}
export interface KnowledgeBaseCreate {
name: string;
description?: string;
}
// 文档相关类型
export interface Document {
id: number;
filename: string;
title: string;
description?: string; // 新增:文档描述
file_size: number;
file_type: string;
is_processed: boolean;
is_public: boolean;
knowledge_base_id?: number; // 新增:所属知识库ID
created_at: string;
updated_at: string;
}
export interface DocumentUpload {
file: File;
title?: string;
description?: string;
knowledge_base_id: number; // 新增:必须指定知识库
}
// 分析相关类型
export interface Statistics {
total_sessions: number;
total_messages: number;
popular_questions: Array<{
question: string;
count: number;
}>;
knowledge_coverage: Array<{
topic: string;
coverage: number;
}>;
}
export interface LearningReport {
user_id: number;
total_questions: number;
topics_covered: string[];
learning_progress: number;
recommendations: string[];
}
// UI相关类型
export interface LoadingState {
isLoading: boolean;
message?: string;
}
export interface ErrorState {
hasError: boolean;
message?: string;
code?: string;
}
// 表单相关类型
export interface FormField {
name: string;
label: string;
type: "text" | "email" | "password" | "textarea" | "select";
placeholder?: string;
required?: boolean;
validation?: {
min?: number;
max?: number;
pattern?: string;
message?: string;
};
}
// 主题相关类型
export type Theme = "light" | "dark" | "system";
// 响应式相关类型
export type Breakpoint = "sm" | "md" | "lg" | "xl" | "2xl";
// 组件Props类型
export interface BaseComponentProps {
className?: string;
children?: React.ReactNode;
}
export interface ButtonProps extends BaseComponentProps {
variant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link";
size?: "default" | "sm" | "lg" | "icon";
disabled?: boolean;
loading?: boolean;
onClick?: () => void;
}
export interface InputProps extends BaseComponentProps {
type?: "text" | "email" | "password" | "number" | "tel" | "url";
placeholder?: string;
value?: string;
onChange?: (value: string) => void;
onBlur?: () => void;
onFocus?: () => void;
disabled?: boolean;
required?: boolean;
error?: string;
}
// 图像生成相关类型
export interface ImageGenerationRequest {
prompt: string;
style?: string;
size?: string;
quality?: string;
num_images?: number;
}
export interface GeneratedImage {
id: string;
url: string;
prompt: string;
style: string;
size: string;
created_at: string;
metadata: {
original_prompt: string;
enhanced_prompt: string;
generation_time: number;
model: string;
[key: string]: any;
};
}
export interface ImageAnalysisRequest {
image_url?: string;
analysis_type: "spatial_planning" | "urban_design" | "landscape_analysis";
}
export interface ImageAnalysisResponse {
id: string;
analysis_type: string;
results: {
description: string;
key_features: string[];
recommendations: string[];
technical_notes: string[];
};
confidence_score: number;
created_at: string;
}
export interface ImageStyle {
id: string;
name: string;
description: string;
}
export interface ImageSize {
id: string;
name: string;
description: string;
}
// API响应类型
export interface ApiResponse<T = any> {
success: boolean;
data?: T;
error?: string;
message?: string;
}
export interface PaginatedResponse<T> {
items: T[];
total: number;
page: number;
page_size: number;
has_next: boolean;
has_prev: boolean;
}
+119
View File
@@ -0,0 +1,119 @@
import type { Config } from "tailwindcss";
const config: Config = {
darkMode: "class",
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
screens: {
'xs': '475px',
'sm': '640px',
'md': '768px',
'lg': '1024px',
'xl': '1280px',
'2xl': '1536px',
},
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
spacing: {
'18': '4.5rem',
'88': '22rem',
'128': '32rem',
},
fontSize: {
'2xs': ['0.625rem', { lineHeight: '0.75rem' }],
'3xl': ['1.875rem', { lineHeight: '2.25rem' }],
'4xl': ['2.25rem', { lineHeight: '2.5rem' }],
'5xl': ['3rem', { lineHeight: '1' }],
'6xl': ['3.75rem', { lineHeight: '1' }],
'7xl': ['4.5rem', { lineHeight: '1' }],
'8xl': ['6rem', { lineHeight: '1' }],
'9xl': ['8rem', { lineHeight: '1' }],
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" },
},
"fade-in": {
"0%": { opacity: "0", transform: "translateY(10px)" },
"100%": { opacity: "1", transform: "translateY(0)" },
},
"slide-in": {
"0%": { transform: "translateX(-100%)" },
"100%": { transform: "translateX(0)" },
},
"mit-fade-in": {
"0%": { opacity: "0", transform: "translateY(20px)" },
"100%": { opacity: "1", transform: "translateY(0)" },
},
"mit-slide-up": {
"0%": { opacity: "0", transform: "translateY(30px)" },
"100%": { opacity: "1", transform: "translateY(0)" },
},
"mit-scale-in": {
"0%": { opacity: "0", transform: "scale(0.95)" },
"100%": { opacity: "1", transform: "scale(1)" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
"fade-in": "fade-in 0.3s ease-out",
"slide-in": "slide-in 0.3s ease-out",
"mit-fade-in": "mit-fade-in 0.4s ease-out",
"mit-slide-up": "mit-slide-up 0.5s ease-out",
"mit-scale-in": "mit-scale-in 0.3s ease-out",
},
},
},
plugins: [require("@tailwindcss/typography")],
};
export default config;
+62
View File
@@ -0,0 +1,62 @@
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"es6"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
],
"@/components/*": [
"./src/components/*"
],
"@/lib/*": [
"./src/lib/*"
],
"@/hooks/*": [
"./src/hooks/*"
],
"@/store/*": [
"./src/store/*"
],
"@/types/*": [
"./src/types/*"
]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}