Upload at 2026-01-01T09:09:44Z

This commit is contained in:
Nomo Bot
2026-01-01 09:09:44 +00:00
commit fdd9497773
36 changed files with 10277 additions and 0 deletions

41
.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

122
DEPLOYMENT_GUIDE.md Normal file
View File

@@ -0,0 +1,122 @@
# Vercel部署指南
## 快速部署步骤
### 方法一通过Vercel CLI推荐
1. **安装Vercel CLI**
```bash
npm i -g vercel
```
2. **登录Vercel**
```bash
vercel login
```
3. **在项目目录中部署**
```bash
cd ai-chat-nextjs
vercel
```
4. **按照提示操作**
- 选择账户/团队
- 确认项目名称
- 确认项目设置
### 方法二通过GitHub集成推荐
1. **访问 [Vercel Dashboard](https://vercel.com/dashboard)**
2. **点击 "New Project"**
3. **导入GitHub仓库**
- 选择 `https://github.com/EagleFandel/test.git`
- 选择 `ai-chat-nextjs` 目录作为根目录
4. **配置项目设置**
- **Framework Preset**: Next.js
- **Root Directory**: `ai-chat-nextjs`
- **Build Command**: `npm run build`
- **Output Directory**: `.next`
## 环境变量配置
在Vercel Dashboard中配置以下环境变量
### 必需的环境变量:
```
INFINI_AI_API_KEY=your_actual_api_key_here
INFINI_AI_BASE_URL=https://cloud.infini-ai.com/maas/v1
INFINI_AI_MODEL=deepseek-v3.2-exp
```
### 可选的环境变量:
```
NEXT_PUBLIC_APP_NAME=AI聊天助手
NEXT_PUBLIC_APP_VERSION=1.0.0
NODE_ENV=production
```
## 部署配置优化
项目已包含优化的 `vercel.json` 配置:
```json
{
"functions": {
"src/app/api/*/route.ts": {
"maxDuration": 30
}
},
"rewrites": [
{
"source": "/api/:path*",
"destination": "/api/:path*"
}
]
}
```
## 部署后验证
1. **检查部署状态**访问Vercel提供的部署URL
2. **测试聊天功能**:发送测试消息
3. **检查API端点**:访问 `https://your-app.vercel.app/api/chat`
4. **查看日志**在Vercel Dashboard中查看函数日志
## 常见问题解决
### 1. API密钥错误
- 确保在Vercel Dashboard中正确设置了 `INFINI_AI_API_KEY`
- 检查API密钥是否有效
### 2. 构建失败
- 检查依赖是否正确安装
- 查看构建日志中的错误信息
### 3. API超时
- 检查 `vercel.json` 中的 `maxDuration` 设置
- 考虑优化API调用逻辑
### 4. 环境变量不生效
- 确保环境变量名称正确
- 重新部署以应用新的环境变量
## 自动部署
配置完成后每次推送到GitHub的main分支都会自动触发Vercel部署。
## 监控和日志
- **实时日志**Vercel Dashboard > Functions > View Function Logs
- **分析数据**Vercel Dashboard > Analytics
- **性能监控**Vercel Dashboard > Speed Insights
## 域名配置(可选)
1. 在Vercel Dashboard中点击项目
2. 进入 "Settings" > "Domains"
3. 添加自定义域名
4. 按照提示配置DNS记录

144
README.md Normal file
View File

@@ -0,0 +1,144 @@
# AI聊天助手 - Next.js版本
基于Next.js 16构建的现代AI聊天应用集成了Infini AI的DeepSeek-v3.2-exp模型。
## 🚀 快速开始
### 本地开发
1. **克隆项目**
```bash
git clone https://github.com/EagleFandel/test.git
cd test/ai-chat-nextjs
```
2. **安装依赖**
```bash
npm install
```
3. **配置环境变量**
```bash
cp .env.example .env.local
# 编辑 .env.local 添加你的API密钥
```
4. **启动开发服务器**
```bash
npm run dev
```
访问 [http://localhost:3000](http://localhost:3000) 查看应用。
### 部署到Vercel
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/EagleFandel/test&project-name=ai-chat-nextjs&repository-name=ai-chat-nextjs&root-directory=ai-chat-nextjs)
或者按照 [部署指南](./DEPLOYMENT_GUIDE.md) 手动部署。
## ✨ 功能特性
- 🤖 **AI智能对话**集成DeepSeek-v3.2-exp模型
- 🎨 **现代UI设计**:响应式设计,支持深色/浅色主题
- 🔄 **智能降级**API不可用时自动切换到备用响应
-**高性能**基于Next.js 16和React 19
- 📱 **移动友好**:完美适配各种设备
- 🛡️ **类型安全**完整的TypeScript支持
- 🎯 **错误处理**:完善的错误捕获和用户提示
## 🛠️ 技术栈
- **框架**Next.js 16
- **UI库**React 19
- **样式**Tailwind CSS 4
- **动画**Framer Motion
- **图标**Lucide React
- **语言**TypeScript
- **部署**Vercel
## 📁 项目结构
```
ai-chat-nextjs/
├── src/
│ ├── app/ # App Router
│ │ ├── api/chat/ # API路由
│ │ ├── globals.css # 全局样式
│ │ └── page.tsx # 主页面
│ ├── components/ # React组件
│ ├── hooks/ # 自定义Hooks
│ ├── types/ # TypeScript类型
│ └── utils/ # 工具函数
├── public/ # 静态资源
├── .env.example # 环境变量示例
└── vercel.json # Vercel配置
```
## 🔧 环境变量
创建 `.env.local` 文件并配置以下变量:
```env
# Infini AI配置
INFINI_AI_API_KEY=your_api_key_here
INFINI_AI_BASE_URL=https://cloud.infini-ai.com/maas/v1
INFINI_AI_MODEL=deepseek-v3.2-exp
# 应用配置
NEXT_PUBLIC_APP_NAME=AI聊天助手
NEXT_PUBLIC_APP_VERSION=1.0.0
```
## 🚀 部署
### Vercel推荐
1. Fork这个仓库
2. 在 [Vercel](https://vercel.com) 中导入项目
3. 设置根目录为 `ai-chat-nextjs`
4. 配置环境变量
5. 部署!
### 其他平台
项目支持部署到任何支持Next.js的平台
- Netlify
- Railway
- Render
- AWS Amplify
## 📖 API文档
### POST /api/chat
发送消息到AI助手。
**请求体**
```json
{
"message": "你好,请介绍一下自己"
}
```
**响应**
```json
{
"message": "AI助手的回复内容",
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
## 🤝 贡献
欢迎提交Issue和Pull Request
## 📄 许可证
MIT License
## 🔗 相关链接
- [Next.js文档](https://nextjs.org/docs)
- [Vercel部署指南](https://vercel.com/docs)
- [Tailwind CSS](https://tailwindcss.com)
- [Infini AI](https://cloud.infini-ai.com)

123
VERCEL_ENV_SETUP.md Normal file
View File

@@ -0,0 +1,123 @@
# Vercel环境变量配置指南
## 🎯 快速配置清单
在Vercel Dashboard中配置以下环境变量
### 必需的环境变量
| 变量名 | 值 | 环境 | 说明 |
|--------|----|----|------|
| `INFINI_AI_API_KEY` | `你的真实API密钥` | Production, Preview | Infini AI的API密钥 |
| `INFINI_AI_BASE_URL` | `https://cloud.infini-ai.com/maas/v1` | Production, Preview | API基础URL |
| `INFINI_AI_MODEL` | `deepseek-v3.2-exp` | Production, Preview | 使用的AI模型 |
### 可选的环境变量
| 变量名 | 值 | 环境 | 说明 |
|--------|----|----|------|
| `NEXT_PUBLIC_APP_NAME` | `AI聊天助手` | Production, Preview | 应用名称 |
| `NEXT_PUBLIC_APP_VERSION` | `1.0.0` | Production, Preview | 应用版本 |
| `NODE_ENV` | `production` | Production | Node.js环境 |
## 📍 详细配置步骤
### 步骤1访问项目设置
1. 登录 [vercel.com](https://vercel.com)
2. 在Dashboard中找到你的项目
3. 点击项目名称
4. 点击顶部的 "Settings" 标签
### 步骤2进入环境变量页面
- 在左侧菜单中点击 "Environment Variables"
- 或者URL直接访问`https://vercel.com/你的用户名/项目名/settings/environment-variables`
### 步骤3添加环境变量
对于每个环境变量:
1. **点击 "Add New"**
2. **填写信息**
- Name: 变量名(如 `INFINI_AI_API_KEY`
- Value: 变量值如你的API密钥
- Environments: 选择 `Production``Preview`
3. **点击 "Save"**
### 步骤4重新部署
添加环境变量后:
1. 回到项目主页
2. 点击 "Deployments" 标签
3. 点击最新部署右侧的三个点
4. 选择 "Redeploy"
5. 确认重新部署
## 🔍 验证配置
### 检查环境变量是否生效:
1. **访问API端点**
```
https://你的项目域名.vercel.app/api/chat
```
2. **查看响应**
应该返回类似:
```json
{
"status": "ok",
"message": "AI聊天API正在运行",
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
3. **测试聊天功能**
- 访问应用主页
- 发送测试消息
- 检查是否收到AI回复
### 查看日志:
1. **进入Functions页面**
- 项目Dashboard > Functions
- 点击 `/api/chat` 函数
2. **查看日志**
- 点击 "View Function Logs"
- 检查是否有错误信息
## ⚠️ 常见问题
### 问题1API密钥无效
**症状**收到401 Unauthorized错误
**解决**
- 检查API密钥是否正确
- 确认API密钥有效期
- 重新生成API密钥
### 问题2环境变量不生效
**症状**:应用仍使用默认值
**解决**
- 确认变量名拼写正确
- 检查是否选择了正确的环境
- 重新部署应用
### 问题3部署失败
**症状**:构建或部署过程中出错
**解决**
- 检查构建日志
- 确认所有依赖正确安装
- 检查代码语法错误
## 🔐 安全提示
1. **不要在代码中硬编码API密钥**
2. **定期更换API密钥**
3. **只在必要的环境中设置敏感变量**
4. **使用Preview环境测试配置**
## 📞 获取帮助
如果遇到问题:
1. 查看Vercel官方文档
2. 检查项目的构建日志
3. 查看函数执行日志
4. 联系Vercel支持团队

18
eslint.config.mjs Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

31
next.config.ts Normal file
View File

@@ -0,0 +1,31 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
reactCompiler: true,
// Vercel优化配置
experimental: {
// 启用服务器组件优化
serverComponentsExternalPackages: [],
},
// 输出配置
output: 'standalone',
// 图片优化
images: {
domains: [],
formats: ['image/webp', 'image/avif'],
},
// 压缩配置
compress: true,
// 环境变量配置
env: {
CUSTOM_KEY: process.env.CUSTOM_KEY,
},
};
export default nextConfig;

7964
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

35
package.json Normal file
View File

@@ -0,0 +1,35 @@
{
"name": "ai-chat-nextjs",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@types/prismjs": "^1.26.5",
"@types/react-syntax-highlighter": "^15.5.13",
"fast-check": "^4.4.0",
"framer-motion": "^12.23.26",
"lucide-react": "^0.562.0",
"next": "16.1.0",
"prismjs": "^1.30.0",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-markdown": "^10.1.0",
"react-syntax-highlighter": "^16.1.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0",
"eslint": "^9",
"eslint-config-next": "16.1.0",
"tailwindcss": "^4",
"typescript": "^5"
}
}

7
postcss.config.mjs Normal file
View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

1
public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
public/vercel.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
public/window.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

126
src/app/api/chat/route.ts Normal file
View File

@@ -0,0 +1,126 @@
import { NextRequest, NextResponse } from 'next/server';
// Infini AI API配置
const INFINI_AI_BASE_URL = process.env.INFINI_AI_BASE_URL || 'https://cloud.infini-ai.com/maas/v1';
const INFINI_AI_API_KEY = process.env.INFINI_AI_API_KEY;
const INFINI_AI_MODEL = process.env.INFINI_AI_MODEL || 'deepseek-v3.2-exp';
// 调用Infini AI API
async function generateAIResponse(message: string): Promise<string> {
if (!INFINI_AI_API_KEY) {
throw new Error('INFINI_AI_API_KEY 环境变量未设置');
}
const url = `${INFINI_AI_BASE_URL}/chat/completions`;
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${INFINI_AI_API_KEY}`,
},
body: JSON.stringify({
model: INFINI_AI_MODEL,
messages: [
{
role: 'user',
content: message
}
]
})
};
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
}
const data = await response.json();
// 检查响应格式
if (data.choices && data.choices.length > 0 && data.choices[0].message) {
return data.choices[0].message.content;
} else {
throw new Error('API响应格式不正确');
}
} catch (error) {
console.error('Infini AI API调用失败:', error);
throw error;
}
}
// 备用模拟响应当API不可用时
async function generateFallbackResponse(message: string): Promise<string> {
// 模拟网络延迟
await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 2000));
const responses = [
`我理解你说的"${message}"。这是一个很有趣的话题!`,
`关于"${message}",我可以为你提供一些见解...`,
`你提到的"${message}"让我想到了几个相关的观点。`,
`这是一个很好的问题关于"${message}"。让我来详细解释一下。`,
`我注意到你对"${message}"很感兴趣。这确实是一个值得探讨的主题。`,
];
// 如果包含代码相关关键词,返回代码示例
if (message.toLowerCase().includes('代码') || message.toLowerCase().includes('code') || message.toLowerCase().includes('编程')) {
return `关于编程,这里是一个简单的例子:
\`\`\`javascript
function greet(name) {
return \`Hello, \${name}!\`;
}
console.log(greet('World'));
\`\`\`
这个函数演示了基本的JavaScript语法。你还有其他编程相关的问题吗`;
}
return responses[Math.floor(Math.random() * responses.length)];
}
export async function POST(request: NextRequest) {
try {
const { message } = await request.json();
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return NextResponse.json(
{ error: '消息内容不能为空' },
{ status: 400 }
);
}
let response: string;
try {
// 尝试调用Infini AI API
response = await generateAIResponse(message.trim());
} catch (error) {
console.warn('Infini AI API不可用使用备用响应:', error);
// 如果API调用失败使用备用响应
response = await generateFallbackResponse(message.trim());
}
return NextResponse.json({
message: response,
timestamp: new Date().toISOString(),
});
} catch (error) {
console.error('Chat API error:', error);
return NextResponse.json(
{ error: '服务器内部错误' },
{ status: 500 }
);
}
}
export async function GET() {
return NextResponse.json({
status: 'ok',
message: 'AI聊天API正在运行',
timestamp: new Date().toISOString(),
});
}

View File

@@ -0,0 +1,13 @@
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({
status: 'healthy',
timestamp: new Date().toISOString(),
version: '1.0.0',
services: {
chat: 'operational',
database: 'not_configured', // 将来可以添加数据库状态检查
},
});
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

275
src/app/globals.css Normal file
View File

@@ -0,0 +1,275 @@
@import "tailwindcss";
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
/* Light theme variables */
--color-bg-primary: #ffffff;
--color-bg-secondary: #f9fafb;
--color-bg-tertiary: #f3f4f6;
--color-text-primary: #111827;
--color-text-secondary: #6b7280;
--color-text-tertiary: #9ca3af;
--color-border-primary: #e5e7eb;
--color-border-secondary: #d1d5db;
--color-accent: #0ea5e9;
--color-accent-hover: #0284c7;
--color-success: #22c55e;
--color-warning: #f59e0b;
--color-error: #ef4444;
/* Chat specific colors */
--color-user-bubble: #0ea5e9;
--color-user-text: #ffffff;
--color-ai-bubble: #ffffff;
--color-ai-text: #1f2937;
--color-input-bg: #ffffff;
--color-input-border: #d1d5db;
--color-input-focus: #0ea5e9;
/* Shadows */
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
--shadow-soft: 0 2px 15px -3px rgba(0, 0, 0, 0.07), 0 10px 20px -2px rgba(0, 0, 0, 0.04);
}
/* Dark theme */
.dark {
--color-bg-primary: #111827;
--color-bg-secondary: #1f2937;
--color-bg-tertiary: #374151;
--color-text-primary: #f9fafb;
--color-text-secondary: #d1d5db;
--color-text-tertiary: #9ca3af;
--color-border-primary: #374151;
--color-border-secondary: #4b5563;
--color-accent: #38bdf8;
--color-accent-hover: #0ea5e9;
--color-success: #4ade80;
--color-warning: #fbbf24;
--color-error: #f87171;
/* Chat specific colors for dark mode */
--color-user-bubble: #0ea5e9;
--color-user-text: #ffffff;
--color-ai-bubble: #374151;
--color-ai-text: #f9fafb;
--color-input-bg: #374151;
--color-input-border: #4b5563;
--color-input-focus: #38bdf8;
/* Dark shadows */
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4), 0 2px 4px -1px rgba(0, 0, 0, 0.3);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.4), 0 4px 6px -2px rgba(0, 0, 0, 0.3);
--shadow-soft: 0 2px 15px -3px rgba(0, 0, 0, 0.3), 0 10px 20px -2px rgba(0, 0, 0, 0.2);
}
body {
margin: 0;
min-height: 100vh;
background-color: var(--color-bg-secondary);
color: var(--color-text-primary);
transition: background-color 0.3s ease, color 0.3s ease;
}
/* Custom scrollbar styles */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: var(--color-bg-tertiary);
}
::-webkit-scrollbar-thumb {
background: var(--color-text-tertiary);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--color-text-secondary);
}
/* Custom utility classes */
@layer utilities {
.bg-theme-primary {
background-color: var(--color-bg-primary);
}
.bg-theme-secondary {
background-color: var(--color-bg-secondary);
}
.bg-theme-tertiary {
background-color: var(--color-bg-tertiary);
}
.text-theme-primary {
color: var(--color-text-primary);
}
.text-theme-secondary {
color: var(--color-text-secondary);
}
.text-theme-tertiary {
color: var(--color-text-tertiary);
}
.border-theme-primary {
border-color: var(--color-border-primary);
}
.border-theme-secondary {
border-color: var(--color-border-secondary);
}
.shadow-theme-sm {
box-shadow: var(--shadow-sm);
}
.shadow-theme-md {
box-shadow: var(--shadow-md);
}
.shadow-theme-lg {
box-shadow: var(--shadow-lg);
}
.shadow-theme-soft {
box-shadow: var(--shadow-soft);
}
.user-bubble {
background-color: var(--color-user-bubble);
color: var(--color-user-text);
}
.ai-bubble {
background-color: var(--color-ai-bubble);
color: var(--color-ai-text);
border: 1px solid var(--color-border-primary);
}
.input-theme {
background-color: var(--color-input-bg);
border-color: var(--color-input-border);
color: var(--color-text-primary);
}
.input-theme:focus {
border-color: var(--color-input-focus);
box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1);
}
}
/* Animation improvements */
@layer utilities {
.animate-slide-in-user {
animation: slideInRight 0.3s ease-out;
}
.animate-slide-in-ai {
animation: slideInLeft 0.3s ease-out;
}
.animate-bounce-gentle {
animation: bounceGentle 2s infinite;
}
.animate-pulse-soft {
animation: pulseSoft 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
.animate-typing {
animation: typing 1.4s ease-in-out infinite;
}
.animate-fade-in {
animation: fadeIn 0.3s ease-out;
}
.animate-slide-up {
animation: slideUp 0.3s ease-out;
}
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes slideInLeft {
from {
opacity: 0;
transform: translateX(-20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes bounceGentle {
0%, 20%, 50%, 80%, 100% {
transform: translateY(0);
}
40% {
transform: translateY(-10px);
}
60% {
transform: translateY(-5px);
}
}
@keyframes pulseSoft {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.7;
}
}
@keyframes typing {
0%, 60%, 100% {
transform: translateY(0);
}
30% {
transform: translateY(-10px);
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}

29
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,29 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({
subsets: ["latin"],
variable: "--font-inter",
});
export const metadata: Metadata = {
title: "AI聊天助手",
description: "智能AI聊天助手支持代码高亮、主题切换和响应式设计",
keywords: ["AI", "聊天", "助手", "人工智能", "对话"],
authors: [{ name: "AI Chat Team" }],
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="zh-CN" suppressHydrationWarning>
<body className={`${inter.variable} font-sans antialiased`}>
{children}
</body>
</html>
);
}

14
src/app/page.tsx Normal file
View File

@@ -0,0 +1,14 @@
'use client';
import { ChatProvider } from '@/hooks/ChatContext';
import { ChatContainer } from '@/components/ChatContainer';
export default function Home() {
return (
<ChatProvider>
<main className="h-screen">
<ChatContainer />
</main>
</ChatProvider>
);
}

6
src/app/viewport.ts Normal file
View File

@@ -0,0 +1,6 @@
import type { Viewport } from 'next'
export const viewport: Viewport = {
width: 'device-width',
initialScale: 1,
}

View File

@@ -0,0 +1,138 @@
'use client';
import type { ChatContainerProps } from '../types';
import { MessageList } from './MessageList';
import { MessageInput } from './MessageInput';
import { useChatState, useChatActions } from '../hooks/ChatContext';
import { useTheme } from '../hooks/useTheme';
import { useResponsive } from '../hooks/useResponsive';
import { MessageCircle, RotateCcw, AlertCircle, Sun, Moon, Monitor } from 'lucide-react';
export function ChatContainer({ className = '' }: ChatContainerProps) {
const { session, isTyping, isLoading, error } = useChatState();
const { sendMessage, clearChat } = useChatActions();
const { theme, toggleTheme } = useTheme();
const { isMobile } = useResponsive();
const handleSendMessage = async (content: string) => {
await sendMessage(content);
};
const handleClearChat = () => {
if (session.messages.length > 0) {
const confirmed = window.confirm('确定要清除所有聊天记录吗?');
if (confirmed) {
clearChat();
}
}
};
const getThemeIcon = () => {
switch (theme) {
case 'light':
return <Sun size={18} />;
case 'dark':
return <Moon size={18} />;
case 'system':
return <Monitor size={18} />;
default:
return <Sun size={18} />;
}
};
const getThemeLabel = () => {
switch (theme) {
case 'light':
return '浅色模式';
case 'dark':
return '深色模式';
case 'system':
return '跟随系统';
default:
return '浅色模式';
}
};
return (
<div className={`flex flex-col h-screen bg-theme-primary transition-colors duration-300 ${className}`}>
{/* 头部 */}
<div className="flex items-center justify-between p-3 sm:p-4 border-b border-theme-primary bg-theme-primary shadow-theme-sm">
<div className="flex items-center space-x-2 sm:space-x-3">
<div className={`w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-primary-500 flex items-center justify-center shadow-theme-md ${
isTyping ? 'animate-pulse-soft' : ''
}`}>
<MessageCircle size={isMobile ? 16 : 20} className="text-white" />
</div>
<div>
<h1 className="text-base sm:text-lg font-semibold text-theme-primary">
{isMobile ? 'AI助手' : 'AI聊天助手'}
</h1>
<p className="text-xs sm:text-sm text-theme-secondary">
{isTyping ? 'AI正在输入...' : '在线'}
</p>
</div>
</div>
<div className="flex items-center space-x-1 sm:space-x-2">
{/* 主题切换按钮 */}
<button
onClick={toggleTheme}
className="p-2 text-theme-secondary hover:text-theme-primary hover:bg-theme-tertiary rounded-full transition-all duration-200 group"
title={getThemeLabel()}
>
<div className="group-hover:scale-110 transition-transform duration-200">
{getThemeIcon()}
</div>
</button>
{/* 清除聊天按钮 */}
{session.messages.length > 0 && (
<button
onClick={handleClearChat}
className="p-2 text-theme-secondary hover:text-theme-primary hover:bg-theme-tertiary rounded-full transition-all duration-200 group"
title="清除聊天记录"
>
<div className="group-hover:rotate-180 transition-transform duration-300">
<RotateCcw size={18} />
</div>
</button>
)}
</div>
</div>
{/* 错误提示 */}
{error && (
<div className={`mx-3 sm:mx-4 mt-3 sm:mt-4 p-3 bg-error-50 dark:bg-error-900/20 border border-error-200 dark:border-error-800 rounded-xl flex items-start space-x-2 animate-slide-up ${
isMobile ? 'text-sm' : ''
}`}>
<AlertCircle size={16} className="text-error-500 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<span className="text-error-700 dark:text-error-300 font-medium"></span>
<p className="text-error-600 dark:text-error-400 text-sm mt-1">{error}</p>
</div>
</div>
)}
{/* 消息列表 */}
<MessageList messages={session.messages} isTyping={isTyping} />
{/* 输入区域 */}
<div className={`border-t border-theme-primary bg-theme-primary ${
isMobile ? 'p-3' : 'p-4'
}`}>
<MessageInput
onSendMessage={handleSendMessage}
disabled={isLoading}
placeholder={isMobile ? "输入消息..." : "输入消息,按回车发送..."}
/>
{/* 移动端提示 */}
{isMobile && (
<div className="mt-2 text-xs text-theme-tertiary text-center">
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,138 @@
'use client';
import type { MessageBubbleProps } from '../types';
import { formatTimestamp, linkifyText, hasCodeBlock, extractCodeLanguage } from '../utils/helpers';
import { useResponsive } from '../hooks/useResponsive';
import { User, Bot } from 'lucide-react';
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneLight, oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { useTheme } from '../hooks/useTheme';
export function MessageBubble({ message, isUser }: MessageBubbleProps) {
const { isMobile } = useResponsive();
const { resolvedTheme } = useTheme();
const bubbleClasses = isUser
? 'user-bubble shadow-theme-md'
: 'ai-bubble shadow-theme-soft';
const containerClasses = isUser
? 'flex justify-end'
: 'flex justify-start';
const avatarClasses = isUser
? 'bg-primary-600 text-white shadow-theme-sm'
: 'bg-theme-tertiary text-theme-secondary shadow-theme-sm';
const animationClass = isUser ? 'animate-slide-in-user' : 'animate-slide-in-ai';
const maxWidth = isMobile ? 'max-w-[85%]' : 'max-w-[75%]';
const spacing = isMobile ? 'space-x-2' : 'space-x-3';
const padding = isMobile ? 'px-3 py-2' : 'px-4 py-3';
const avatarSize = isMobile ? 'w-7 h-7' : 'w-8 h-8';
const iconSize = isMobile ? 14 : 16;
return (
<div className={`${containerClasses} mb-3 sm:mb-4 ${animationClass}`}>
<div className={`flex ${maxWidth} items-start ${spacing}`}>
{!isUser && (
<div className={`flex-shrink-0 ${avatarSize} rounded-full flex items-center justify-center ${avatarClasses} transition-colors duration-300`}>
<Bot size={iconSize} />
</div>
)}
<div className={`rounded-2xl ${padding} ${bubbleClasses} transition-all duration-300 hover:shadow-theme-lg`}>
<div className={`${isMobile ? 'text-sm' : 'text-sm'}`}>
{message.type === 'code' || hasCodeBlock(message.content) ? (
<ReactMarkdown
components={{
code({ node, inline, className, children, ...props }: any) {
const match = /language-(\w+)/.exec(className || '');
const language = match ? match[1] : extractCodeLanguage(message.content);
return !inline ? (
<div className="my-2 first:mt-0 last:mb-0">
<SyntaxHighlighter
style={resolvedTheme === 'dark' ? oneDark : oneLight}
language={language}
PreTag="div"
className="!rounded-lg !bg-theme-tertiary !text-theme-primary !text-xs sm:!text-sm overflow-x-auto"
customStyle={{
margin: 0,
padding: isMobile ? '0.75rem' : '1rem',
fontSize: isMobile ? '0.75rem' : '0.875rem',
}}
{...props}
>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
</div>
) : (
<code className="bg-theme-tertiary text-theme-primary px-1.5 py-0.5 rounded text-xs font-mono" {...props}>
{children}
</code>
);
},
p({ children }) {
return <p className="mb-2 last:mb-0 leading-relaxed">{children}</p>;
},
a({ href, children }) {
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className={`underline hover:no-underline transition-colors duration-200 ${
isUser
? 'text-blue-100 hover:text-white'
: 'text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300'
}`}
>
{children}
</a>
);
},
ul({ children }) {
return <ul className="list-disc list-inside mb-2 last:mb-0 space-y-1">{children}</ul>;
},
ol({ children }) {
return <ol className="list-decimal list-inside mb-2 last:mb-0 space-y-1">{children}</ol>;
},
blockquote({ children }) {
return (
<blockquote className="border-l-4 border-theme-secondary pl-4 my-2 italic text-theme-secondary">
{children}
</blockquote>
);
},
}}
>
{message.content}
</ReactMarkdown>
) : (
<div
className="leading-relaxed"
dangerouslySetInnerHTML={{
__html: linkifyText(message.content),
}}
/>
)}
</div>
<div className={`${isMobile ? 'text-xs' : 'text-xs'} mt-2 opacity-75 ${
isUser ? 'text-blue-100' : 'text-theme-tertiary'
}`}>
{formatTimestamp(message.timestamp)}
</div>
</div>
{isUser && (
<div className={`flex-shrink-0 ${avatarSize} rounded-full flex items-center justify-center ${avatarClasses} transition-colors duration-300`}>
<User size={iconSize} />
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,126 @@
'use client';
import { useState, useRef, useEffect } from 'react';
import type { MessageInputProps } from '../types';
import { Send, Loader2 } from 'lucide-react';
import { isValidMessageContent } from '../utils/validation';
import { useResponsive } from '../hooks/useResponsive';
export function MessageInput({ onSendMessage, disabled, placeholder = "输入消息..." }: MessageInputProps) {
const [message, setMessage] = useState('');
const [isComposing, setIsComposing] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const { isMobile } = useResponsive();
// 自动调整文本框高度
useEffect(() => {
const textarea = textareaRef.current;
if (textarea) {
textarea.style.height = 'auto';
const maxHeight = isMobile ? 100 : 120;
textarea.style.height = `${Math.min(textarea.scrollHeight, maxHeight)}px`;
}
}, [message, isMobile]);
// 聚焦到输入框
useEffect(() => {
if (!disabled && textareaRef.current) {
textareaRef.current.focus();
}
}, [disabled]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
sendMessage();
};
const sendMessage = () => {
if (!isValidMessageContent(message) || disabled) {
return;
}
onSendMessage(message.trim());
setMessage('');
// 重置文本框高度
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
// 处理中文输入法
if (isComposing) return;
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
};
const handleCompositionStart = () => {
setIsComposing(true);
};
const handleCompositionEnd = () => {
setIsComposing(false);
};
const isMessageValid = isValidMessageContent(message);
const buttonSize = isMobile ? 'w-10 h-10' : 'w-12 h-12';
const iconSize = isMobile ? 18 : 20;
const minHeight = isMobile ? '44px' : '48px';
return (
<div className="w-full">
<form onSubmit={handleSubmit} className={`flex items-end ${isMobile ? 'space-x-2' : 'space-x-3'}`}>
<div className="flex-1 relative">
<textarea
ref={textareaRef}
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyDown={handleKeyDown}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
placeholder={placeholder}
disabled={disabled}
rows={1}
className={`w-full resize-none rounded-2xl input-theme focus:input-theme transition-all duration-200 ${
isMobile ? 'px-3 py-2.5 pr-10 text-sm' : 'px-4 py-3 pr-12 text-sm'
} disabled:opacity-50 disabled:cursor-not-allowed shadow-theme-sm focus:shadow-theme-md`}
style={{
minHeight,
maxHeight: isMobile ? '100px' : '120px'
}}
/>
{/* 字符计数 */}
{message.length > 0 && (
<div className={`absolute ${isMobile ? 'bottom-1 right-8' : 'bottom-1 right-12'} text-xs text-theme-tertiary`}>
{message.length}
</div>
)}
</div>
<button
type="submit"
disabled={!isMessageValid || disabled}
className={`flex-shrink-0 ${buttonSize} rounded-full bg-primary-500 text-white flex items-center justify-center hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-primary-200 disabled:bg-theme-tertiary disabled:cursor-not-allowed transition-all duration-200 shadow-theme-md hover:shadow-theme-lg disabled:shadow-theme-sm transform hover:scale-105 active:scale-95`}
>
{disabled ? (
<Loader2 size={iconSize} className="animate-spin" />
) : (
<Send size={iconSize} />
)}
</button>
</form>
{/* 提示文本 - 仅在桌面端显示 */}
{!isMobile && (
<div className="mt-2 text-xs text-theme-tertiary text-center">
Enter Shift + Enter
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,80 @@
'use client';
import { useEffect, useRef } from 'react';
import type { MessageListProps } from '../types';
import { MessageBubble } from './MessageBubble';
import { TypingIndicator } from './TypingIndicator';
import { useResponsive } from '../hooks/useResponsive';
export function MessageList({ messages, isTyping }: MessageListProps) {
const messagesEndRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const { isMobile } = useResponsive();
// 自动滚动到底部
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
// 当有新消息或打字状态改变时滚动到底部
useEffect(() => {
scrollToBottom();
}, [messages, isTyping]);
const padding = isMobile ? 'p-3' : 'p-4';
const spacing = isMobile ? 'space-y-3' : 'space-y-4';
return (
<div
ref={containerRef}
className={`flex-1 overflow-y-auto ${padding} ${spacing} bg-theme-secondary transition-colors duration-300`}
style={{ scrollBehavior: 'smooth' }}
>
{messages.length === 0 ? (
<div className="flex items-center justify-center h-full">
<div className="text-center text-theme-secondary max-w-sm mx-auto">
<div className={`${isMobile ? 'text-4xl' : 'text-6xl'} mb-4 animate-bounce-gentle`}>🤖</div>
<h3 className={`${isMobile ? 'text-base' : 'text-lg'} font-medium mb-2 text-theme-primary`}>
使AI聊天助手
</h3>
<p className={`${isMobile ? 'text-sm' : 'text-sm'} text-theme-secondary`}>
{isMobile ? '发送消息开始对话' : '发送消息开始对话吧!'}
</p>
<div className="mt-6 space-y-2">
<div className={`inline-block px-3 py-1.5 bg-theme-tertiary rounded-full text-xs text-theme-secondary ${
isMobile ? 'mx-1' : 'mx-2'
}`}>
💬
</div>
<div className={`inline-block px-3 py-1.5 bg-theme-tertiary rounded-full text-xs text-theme-secondary ${
isMobile ? 'mx-1' : 'mx-2'
}`}>
💻
</div>
{!isMobile && (
<div className="inline-block px-3 py-1.5 bg-theme-tertiary rounded-full text-xs text-theme-secondary mx-2">
🔗
</div>
)}
</div>
</div>
</div>
) : (
<>
{messages.map((message) => (
<MessageBubble
key={message.id}
message={message}
isUser={message.sender === 'user'}
/>
))}
<TypingIndicator visible={isTyping} />
</>
)}
{/* 滚动锚点 */}
<div ref={messagesEndRef} />
</div>
);
}

View File

@@ -0,0 +1,39 @@
'use client';
import type { TypingIndicatorProps } from '../types';
import { useResponsive } from '../hooks/useResponsive';
import { Bot } from 'lucide-react';
export function TypingIndicator({ visible }: TypingIndicatorProps) {
const { isMobile } = useResponsive();
if (!visible) return null;
const avatarSize = isMobile ? 'w-7 h-7' : 'w-8 h-8';
const iconSize = isMobile ? 14 : 16;
const spacing = isMobile ? 'space-x-2' : 'space-x-3';
const padding = isMobile ? 'px-3 py-2' : 'px-4 py-3';
return (
<div className="flex justify-start mb-3 sm:mb-4 animate-fade-in animate-slide-in-ai">
<div className={`flex max-w-[85%] sm:max-w-[75%] items-start ${spacing}`}>
<div className={`flex-shrink-0 ${avatarSize} rounded-full flex items-center justify-center bg-theme-tertiary text-theme-secondary shadow-theme-sm transition-colors duration-300`}>
<Bot size={iconSize} />
</div>
<div className={`ai-bubble ${padding} shadow-theme-soft transition-all duration-300`}>
<div className="flex items-center space-x-2">
<div className="flex space-x-1">
<div className="w-2 h-2 bg-theme-secondary rounded-full animate-typing"></div>
<div className="w-2 h-2 bg-theme-secondary rounded-full animate-typing" style={{ animationDelay: '0.2s' }}></div>
<div className="w-2 h-2 bg-theme-secondary rounded-full animate-typing" style={{ animationDelay: '0.4s' }}></div>
</div>
<span className={`${isMobile ? 'text-xs' : 'text-sm'} text-theme-secondary`}>
AI正在输入...
</span>
</div>
</div>
</div>
</div>
);
}

134
src/hooks/ChatContext.tsx Normal file
View File

@@ -0,0 +1,134 @@
'use client';
import React, { createContext, useContext, useReducer, useCallback, useEffect } from 'react';
import type { ChatContextType } from '../types';
import { chatReducer, initialChatState } from './useChatReducer';
import { isValidMessageContent } from '../utils/validation';
import { delay } from '../utils/helpers';
// 创建上下文
const ChatContext = createContext<ChatContextType | null>(null);
// 真实的AI服务 - 调用API路由
const aiService = {
async sendMessage(message: string): Promise<string> {
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || '发送消息失败');
}
const data = await response.json();
return data.message;
},
isConnected(): boolean {
return true;
}
};
// 聊天提供者组件
export function ChatProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(chatReducer, initialChatState);
// 发送消息函数
const sendMessage = useCallback(async (content: string) => {
// 验证消息内容
if (!isValidMessageContent(content)) {
dispatch({
type: 'SET_ERROR',
payload: { error: '消息内容不能为空' }
});
return;
}
try {
// 发送用户消息
dispatch({
type: 'SEND_MESSAGE',
payload: { content }
});
// 显示打字指示器
dispatch({
type: 'SET_TYPING',
payload: { isTyping: true }
});
// 调用AI服务
const aiResponse = await aiService.sendMessage(content);
// 接收AI回复
dispatch({
type: 'RECEIVE_MESSAGE',
payload: { content: aiResponse }
});
} catch (error) {
dispatch({
type: 'SET_ERROR',
payload: { error: '发送消息失败,请重试' }
});
}
}, []);
// 清除聊天记录
const clearChat = useCallback(() => {
dispatch({ type: 'CLEAR_CHAT' });
}, []);
// 从本地存储加载会话(后续实现)
useEffect(() => {
// 这里将来会从本地存储加载会话
// const savedSession = storageService.loadSession();
// if (savedSession) {
// dispatch({ type: 'LOAD_SESSION', payload: { session: savedSession } });
// }
}, []);
// 保存会话到本地存储(后续实现)
useEffect(() => {
// 这里将来会保存会话到本地存储
// storageService.saveSession(state.session);
}, [state.session]);
const contextValue: ChatContextType = {
state,
dispatch,
sendMessage,
clearChat,
};
return (
<ChatContext.Provider value={contextValue}>
{children}
</ChatContext.Provider>
);
}
// 使用聊天上下文的Hook
export function useChatContext(): ChatContextType {
const context = useContext(ChatContext);
if (!context) {
throw new Error('useChatContext must be used within a ChatProvider');
}
return context;
}
// 便捷的状态和动作Hooks
export function useChatState() {
const { state } = useChatContext();
return state;
}
export function useChatActions() {
const { sendMessage, clearChat } = useChatContext();
return { sendMessage, clearChat };
}

117
src/hooks/useChatReducer.ts Normal file
View File

@@ -0,0 +1,117 @@
import type { ChatState, ChatAction, Message, ChatSession } from '../types';
import { generateId } from '../utils/helpers';
import { detectMessageType } from '../utils/validation';
// 初始状态
export const initialChatState: ChatState = {
session: {
id: generateId(),
messages: [],
createdAt: new Date(),
updatedAt: new Date(),
},
isTyping: false,
isLoading: false,
error: null,
};
// 聊天状态reducer
export function chatReducer(state: ChatState, action: ChatAction): ChatState {
switch (action.type) {
case 'SEND_MESSAGE': {
const newMessage: Message = {
id: generateId(),
content: action.payload.content,
sender: 'user',
timestamp: new Date(),
type: detectMessageType(action.payload.content),
};
const updatedSession: ChatSession = {
...state.session,
messages: [...state.session.messages, newMessage],
updatedAt: new Date(),
};
return {
...state,
session: updatedSession,
isLoading: true,
error: null,
};
}
case 'RECEIVE_MESSAGE': {
const newMessage: Message = {
id: generateId(),
content: action.payload.content,
sender: 'ai',
timestamp: new Date(),
type: detectMessageType(action.payload.content),
};
const updatedSession: ChatSession = {
...state.session,
messages: [...state.session.messages, newMessage],
updatedAt: new Date(),
};
return {
...state,
session: updatedSession,
isTyping: false,
isLoading: false,
error: null,
};
}
case 'SET_TYPING':
return {
...state,
isTyping: action.payload.isTyping,
};
case 'SET_LOADING':
return {
...state,
isLoading: action.payload.isLoading,
};
case 'SET_ERROR':
return {
...state,
error: action.payload.error,
isLoading: false,
isTyping: false,
};
case 'CLEAR_CHAT': {
const newSession: ChatSession = {
id: generateId(),
messages: [],
createdAt: new Date(),
updatedAt: new Date(),
};
return {
...state,
session: newSession,
isTyping: false,
isLoading: false,
error: null,
};
}
case 'LOAD_SESSION':
return {
...state,
session: action.payload.session,
isTyping: false,
isLoading: false,
error: null,
};
default:
return state;
}
}

100
src/hooks/useResponsive.ts Normal file
View File

@@ -0,0 +1,100 @@
import { useState, useEffect } from 'react';
type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
interface BreakpointValues {
xs: number;
sm: number;
md: number;
lg: number;
xl: number;
'2xl': number;
}
const breakpoints: BreakpointValues = {
xs: 475,
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
'2xl': 1536,
};
export function useResponsive() {
const [windowSize, setWindowSize] = useState({
width: 1024, // 服务器端默认值
height: 768,
});
const [currentBreakpoint, setCurrentBreakpoint] = useState<Breakpoint>('lg');
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
// 客户端挂载后设置真实的窗口大小
if (typeof window !== 'undefined') {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
}, []);
useEffect(() => {
// 检查是否在浏览器环境且已挂载
if (typeof window === 'undefined' || !mounted) return;
function handleResize() {
const width = window.innerWidth;
const height = window.innerHeight;
setWindowSize({ width, height });
// 确定当前断点
let breakpoint: Breakpoint = 'xs';
if (width >= breakpoints['2xl']) breakpoint = '2xl';
else if (width >= breakpoints.xl) breakpoint = 'xl';
else if (width >= breakpoints.lg) breakpoint = 'lg';
else if (width >= breakpoints.md) breakpoint = 'md';
else if (width >= breakpoints.sm) breakpoint = 'sm';
else if (width >= breakpoints.xs) breakpoint = 'xs';
setCurrentBreakpoint(breakpoint);
}
// 初始化
handleResize();
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [mounted]);
// 检查是否匹配特定断点
const isBreakpoint = (breakpoint: Breakpoint) => {
return windowSize.width >= breakpoints[breakpoint];
};
// 检查是否在断点范围内
const isBetween = (min: Breakpoint, max: Breakpoint) => {
return windowSize.width >= breakpoints[min] && windowSize.width < breakpoints[max];
};
// 便捷的断点检查
const isMobile = windowSize.width < breakpoints.md;
const isTablet = windowSize.width >= breakpoints.md && windowSize.width < breakpoints.lg;
const isDesktop = windowSize.width >= breakpoints.lg;
const isLargeScreen = windowSize.width >= breakpoints.xl;
return {
windowSize,
currentBreakpoint,
isBreakpoint,
isBetween,
isMobile,
isTablet,
isDesktop,
isLargeScreen,
breakpoints,
};
}

96
src/hooks/useTheme.ts Normal file
View File

@@ -0,0 +1,96 @@
import { useState, useEffect } from 'react';
type Theme = 'light' | 'dark' | 'system';
export function useTheme() {
const [theme, setTheme] = useState<Theme>('light'); // 服务器端默认值
const [resolvedTheme, setResolvedTheme] = useState<'light' | 'dark'>('light');
const [mounted, setMounted] = useState(false);
// 客户端挂载后设置正确的主题
useEffect(() => {
setMounted(true);
// 从localStorage获取保存的主题默认为system
const savedTheme = localStorage.getItem('theme') as Theme;
setTheme(savedTheme || 'system');
}, []);
useEffect(() => {
// 检查是否在浏览器环境
if (typeof window === 'undefined' || !mounted) return;
const root = window.document.documentElement;
// 移除之前的主题类
root.classList.remove('light', 'dark');
let effectiveTheme: 'light' | 'dark';
if (theme === 'system') {
// 检测系统主题偏好
const systemTheme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
effectiveTheme = systemTheme;
} else {
effectiveTheme = theme;
}
// 应用主题
root.classList.add(effectiveTheme);
setResolvedTheme(effectiveTheme);
// 保存到localStorage
localStorage.setItem('theme', theme);
}, [theme, mounted]);
// 监听系统主题变化
useEffect(() => {
if (typeof window === 'undefined' || theme !== 'system' || !window.matchMedia || !mounted) return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
setResolvedTheme(systemTheme);
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, [theme, mounted]);
const toggleTheme = () => {
setTheme(current => {
switch (current) {
case 'light':
return 'dark';
case 'dark':
return 'system';
case 'system':
return 'light';
default:
return 'light';
}
});
};
// 在客户端挂载前返回默认值,避免水合错误
if (!mounted) {
return {
theme: 'light' as Theme,
resolvedTheme: 'light' as 'light' | 'dark',
setTheme: () => {},
toggleTheme: () => {},
};
}
return {
theme,
resolvedTheme,
setTheme,
toggleTheme,
};
}

79
src/types/index.ts Normal file
View File

@@ -0,0 +1,79 @@
// 消息类型定义
export interface Message {
id: string;
content: string;
sender: 'user' | 'ai';
timestamp: Date;
type: 'text' | 'code' | 'error';
}
// 聊天会话类型定义
export interface ChatSession {
id: string;
messages: Message[];
createdAt: Date;
updatedAt: Date;
}
// 聊天状态类型定义
export interface ChatState {
session: ChatSession;
isTyping: boolean;
isLoading: boolean;
error: string | null;
}
// 聊天动作类型定义
export type ChatAction =
| { type: 'SEND_MESSAGE'; payload: { content: string } }
| { type: 'RECEIVE_MESSAGE'; payload: { content: string } }
| { type: 'SET_TYPING'; payload: { isTyping: boolean } }
| { type: 'SET_LOADING'; payload: { isLoading: boolean } }
| { type: 'SET_ERROR'; payload: { error: string | null } }
| { type: 'CLEAR_CHAT' }
| { type: 'LOAD_SESSION'; payload: { session: ChatSession } };
// 组件Props接口
export interface ChatContainerProps {
className?: string;
}
export interface MessageListProps {
messages: Message[];
isTyping: boolean;
}
export interface MessageBubbleProps {
message: Message;
isUser: boolean;
}
export interface MessageInputProps {
onSendMessage: (content: string) => void;
disabled: boolean;
placeholder?: string;
}
export interface TypingIndicatorProps {
visible: boolean;
}
// 服务接口
export interface ChatService {
sendMessage(message: string): Promise<string>;
isConnected(): boolean;
}
export interface StorageService {
saveSession(session: ChatSession): void;
loadSession(): ChatSession | null;
clearSession(): void;
}
// 上下文类型
export interface ChatContextType {
state: ChatState;
dispatch: React.Dispatch<ChatAction>;
sendMessage: (content: string) => Promise<void>;
clearChat: () => void;
}

107
src/utils/helpers.ts Normal file
View File

@@ -0,0 +1,107 @@
/**
* 生成唯一ID
* @returns 唯一标识符
*/
export function generateId(): string {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
/**
* 格式化时间戳
* @param date 日期对象
* @returns 格式化的时间字符串
*/
export function formatTimestamp(date: Date): string {
const now = new Date();
const diff = now.getTime() - date.getTime();
// 小于1分钟显示"刚刚"
if (diff < 60000) {
return '刚刚';
}
// 小于1小时显示分钟
if (diff < 3600000) {
const minutes = Math.floor(diff / 60000);
return `${minutes}分钟前`;
}
// 小于24小时显示小时
if (diff < 86400000) {
const hours = Math.floor(diff / 3600000);
return `${hours}小时前`;
}
// 超过24小时显示具体时间
return date.toLocaleString('zh-CN', {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
/**
* 检测文本中的URL
* @param text 文本内容
* @returns URL数组
*/
export function detectUrls(text: string): string[] {
const urlRegex = /(https?:\/\/[^\s]+)/g;
return text.match(urlRegex) || [];
}
/**
* 将文本中的URL转换为链接
* @param text 文本内容
* @returns 包含链接的HTML字符串
*/
export function linkifyText(text: string): string {
const urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, '<a href="$1" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:text-blue-800 underline">$1</a>');
}
/**
* 检测代码块
* @param text 文本内容
* @returns 是否包含代码块
*/
export function hasCodeBlock(text: string): boolean {
return text.includes('```') || text.includes('`');
}
/**
* 提取代码块语言
* @param text 文本内容
* @returns 代码语言
*/
export function extractCodeLanguage(text: string): string {
const match = text.match(/```(\w+)/);
return match ? match[1] : 'text';
}
/**
* 延迟函数
* @param ms 延迟毫秒数
* @returns Promise
*/
export function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* 防抖函数
* @param func 要防抖的函数
* @param wait 等待时间
* @returns 防抖后的函数
*/
export function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let timeout: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
}

73
src/utils/validation.ts Normal file
View File

@@ -0,0 +1,73 @@
import type { Message, ChatSession } from '../types';
/**
* 验证消息内容是否有效
* @param content 消息内容
* @returns 是否有效
*/
export function isValidMessageContent(content: string): boolean {
// 检查是否为空或只包含空白字符
return content.trim().length > 0;
}
/**
* 验证消息对象是否有效
* @param message 消息对象
* @returns 是否有效
*/
export function isValidMessage(message: any): message is Message {
return (
typeof message === 'object' &&
message !== null &&
typeof message.id === 'string' &&
typeof message.content === 'string' &&
(message.sender === 'user' || message.sender === 'ai') &&
message.timestamp instanceof Date &&
(message.type === 'text' || message.type === 'code' || message.type === 'error')
);
}
/**
* 验证聊天会话是否有效
* @param session 聊天会话对象
* @returns 是否有效
*/
export function isValidChatSession(session: any): session is ChatSession {
return (
typeof session === 'object' &&
session !== null &&
typeof session.id === 'string' &&
Array.isArray(session.messages) &&
session.messages.every(isValidMessage) &&
session.createdAt instanceof Date &&
session.updatedAt instanceof Date
);
}
/**
* 清理和标准化消息内容
* @param content 原始消息内容
* @returns 清理后的消息内容
*/
export function sanitizeMessageContent(content: string): string {
return content.trim().replace(/\s+/g, ' ');
}
/**
* 检测消息内容类型
* @param content 消息内容
* @returns 消息类型
*/
export function detectMessageType(content: string): 'text' | 'code' | 'error' {
// 检测代码块
if (content.includes('```') || content.includes('`')) {
return 'code';
}
// 检测错误消息
if (content.toLowerCase().includes('error') || content.toLowerCase().includes('错误')) {
return 'error';
}
return 'text';
}

50
test-api.js Normal file
View File

@@ -0,0 +1,50 @@
// 测试Infini AI API连接
const API_KEY = 'your_actual_api_key_here'; // 替换为你的真实API密钥
const BASE_URL = 'https://cloud.infini-ai.com/maas/v1';
const MODEL = 'deepseek-v3.2-exp';
async function testAPI() {
console.log('测试Infini AI API连接...');
const url = `${BASE_URL}/chat/completions`;
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
},
body: JSON.stringify({
model: MODEL,
messages: [
{
role: 'user',
content: '你好,请简单介绍一下自己'
}
]
})
};
try {
console.log('发送请求到:', url);
console.log('使用模型:', MODEL);
const response = await fetch(url, options);
console.log('响应状态:', response.status, response.statusText);
if (!response.ok) {
const errorText = await response.text();
console.error('API错误响应:', errorText);
return;
}
const data = await response.json();
console.log('API响应成功!');
console.log('AI回复:', data.choices?.[0]?.message?.content || '无回复内容');
} catch (error) {
console.error('API调用失败:', error.message);
}
}
testAPI();

34
tsconfig.json Normal file
View File

@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}

13
vercel.json Normal file
View File

@@ -0,0 +1,13 @@
{
"functions": {
"src/app/api/*/route.ts": {
"maxDuration": 30
}
},
"rewrites": [
{
"source": "/api/:path*",
"destination": "/api/:path*"
}
]
}