refactor: 在旧的PhyExp基础上进行重构,采用了monorepo结构,分为frontend和backend两个子项目

这个提交包含在:
2026-05-23 18:15:31 +08:00
当前提交 41813abe48
共有 87 个文件被更改,包括 13257 次插入 和 0 次删除

39
frontend/.gitignore vendored 普通文件
查看文件

@ -0,0 +1,39 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.tsbuildinfo
.eslintcache
# Cypress
/cypress/videos/
/cypress/screenshots/
# Vitest
__screenshots__/
# Vite
*.timestamp-*-*.mjs

6
frontend/.prettierrc.json 普通文件
查看文件

@ -0,0 +1,6 @@
{
"$schema": "https://json.schemastore.org/prettierrc",
"semi": false,
"singleQuote": true,
"printWidth": 100
}

228
frontend/ARCHITECTURE.md 普通文件
查看文件

@ -0,0 +1,228 @@
# AI+ 物理实验平台 (PhyExp) — 前端架构文档
## 项目概述
- **项目名称:** `phyexp` (AI+ Physical Experiment Platform)
- **类型:** Vue 3 SPA (单页应用),TypeScript,Vite 构建
- **描述:** 交互式物理实验教学平台,支持分阶段实验流程(预习 → 测验 → 实验 → 考试 → 总结)、AI 助教对话、LaTeX 数学公式渲染、实验数据 PDF 导出
## 目录结构
```
frontend/
├── .gitignore
├── .prettierrc.json # Prettier 格式化配置 (无分号, 单引号, 100字符宽)
├── env.d.ts # Vite 客户端类型声明
├── index.html # SPA 入口 HTML
├── package.json # 依赖与脚本
├── tsconfig.json # 根 TSConfig (项目引用)
├── tsconfig.app.json # 应用 TSConfig (extends @vue/tsconfig)
├── tsconfig.node.json # Node 侧 TSConfig (extends @tsconfig/node24)
├── vite.config.ts # Vite 构建配置
├── dist/ # 构建产物
├── public/
│ └── favicon.ico
└── src/
├── main.ts # 应用入口:创建 Vue 实例,挂载 Pinia + Router
├── App.vue # 根组件:<RouterView /> + <DebugPanel />
├── helper.ts # URL 查询解析 + 实验配置加载
├── assets/ # 静态资源与 JSON 配置
│ ├── experiences.json # 实验定义注册表
│ ├── question.schema.json # 试题 JSON Schema
│ └── VoiceSpeed/ # 声速实验数据
│ ├── question.json # 默认试题
│ ├── prelearn.json # 预习资料
│ └── image.jpeg # 封面图片
├── components/
│ ├── AIChatSidebar.vue # AI 助教聊天侧边栏/浮动窗口
│ ├── DebugPanel.vue # 调试面板 (localStorage DEBUG=true)
│ ├── QuestionTable.vue # 试题渲染组件
│ └── experiment/
│ ├── ExperimentForm.vue # 实验表单 (状态管理 + AI 评价上下文)
│ ├── ExperimentGrid.vue # Excel风格网格表格容器
│ ├── ExperimentGridCell.vue # 网格单元格 (label/input/computed, 背景色验证)
│ └── ExperimentPrintTable.vue # PDF 导出打印表格
├── composables/
│ ├── useDevice.ts # 设备检测与响应式适配
│ └── useDraggable.ts # 通用拖拽功能
├── pages/
│ ├── StudentLogin.vue # 学生登录页
│ ├── ExperienceFrame.vue # 实验流程框架 (阶段导航器)
│ ├── ExperienceSwitch.vue # 实验选择页
│ ├── LearnPage.vue # 预习页 (视频 + AI 助手)
│ ├── QuizPage.vue # 测验页
│ ├── ExperimentPage.vue # 实验数据记录页
│ └── AnswerSummary.vue # 测验结果 + AI 错题分析
├── router/
│ └── index.ts # Vue Router 配置 (hash 模式)
├── stores/
│ ├── experiment.ts # Pinia store: 实验表单数据与验证
│ ├── student.ts # Pinia store: 学生认证信息
│ └── counter.ts # 示例 store
├── types/
│ ├── experiment.ts # 实验表单类型定义
│ ├── question.ts # 试题类型定义
│ └── experience.ts # 实验/阶段类型定义
└── utils/
├── aiClient.ts # AI 聊天客户端 (SSE streaming + REST)
├── aiEvalContext.ts # AI 评价上下文 (provide/inject)
├── calculation.ts # 数学表达式计算 (mathjs + LaTeX 转换)
├── device.ts # 设备检测工具
├── latex.ts # LaTeX 渲染 (KaTeX)
├── markdown.ts # Markdown → HTML 渲染
└── pdfExport.ts # HTML → PDF 导出 (html2canvas + jsPDF)
```
## 技术栈
| 分类 | 技术 | 版本 |
| ---------- | -------------------------------- | ------- |
| 框架 | Vue | 3.5 |
| 语言 | TypeScript | 5.9 |
| 构建工具 | Vite | 7 |
| 状态管理 | Pinia | 3 |
| 路由 | Vue Router (hash 模式) | 5 |
| 数学渲染 | KaTeX | 0.16 |
| 数学计算 | mathjs | 15 |
| PDF 导出 | html2canvas + jsPDF | 1.4 / 3 |
| AI 通信 | REST + SSE (Server-Sent Events) | - |
## 路由设计
| 路径 | 组件 | 说明 |
| ---------------- | ----------------- | ---------------------------------------- |
| `/` | redirect → /login | 根路径重定向 |
| `/login` | StudentLogin | 学生登录页 |
| `/exp?expid=...` | ExperienceFrame | 实验主框架(驱动多阶段流程) |
| `/select` | ExperienceSwitch | 实验选择页 |
| `/:pathMatch(.*)*` | redirect → /login | 404 兜底重定向 |
**认证守卫:** `router.beforeEach` 检查 `localStorage.PhyExp.StudentInfo`,未登录则重定向到 `/login`。
## 核心架构
### 数据流
```
Login → StudentStore (Pinia + localStorage)
→ ExperienceSwitch → ExperienceFrame (加载 experiences.json)
→ 阶段导航 (learn → quiz → experiment → exam → report)
├── LearnPage: 视频 + AIChatSidebar (streaming SSE, teacherType='question')
├── QuizPage: QuestionTable[] → AnswerSummary (AI 批改, teacherType='grader')
└── ExperimentPage: ExperimentForm
├── ExperimentGrid → Excel风格网格布局
│ └── ExperimentGridCell (label | input | computed)
│ ├── 背景色表示验证状态 (绿=通过, 红=失败, 黄=未验证)
│ └── LaTeX 渲染标签和公式
└── AIEvalContext (provide/inject)
└── 悬浮 tooltip 评价 (teacherType='data_eval')
```
### 组件层级依赖
```
App.vue
├── <RouterView />
│ ├── StudentLogin → useStudentStore
│ ├── ExperienceFrame → h() 动态渲染阶段组件
│ │ ├── LearnPage → AIChatSidebar
│ │ ├── QuizPage → QuestionTable[] → AnswerSummary
│ │ └── ExperimentPage
│ │ ├── ExperimentForm (provide AIEvalContext)
│ │ │ └── ExperimentGrid[] (每个 Sheet 一个网格)
│ │ │ └── ExperimentGridCell (label/input/computed)
│ │ ├── ExperimentPrintTable (隐藏 PDF 渲染)
│ │ └── AIChatSidebar (浮动模式)
│ └── ExperienceSwitch
└── DebugPanel (全局挂载,DEBUG=true 时可见)
```
### AI 通信模式
| 场景 | 函数 | teacherType | 通信方式 |
| ------------------ | ------------ | ----------- | -------- |
| AI 助教聊天 | `streamChat` | `question` | SSE 流式 |
| 实验数据字段评价 | `chatOnce` | `data_eval` | REST |
| 测验错题分析 | `chatOnce` | `grader` | REST |
**API 端点:** `{baseUrl}/api/chat`(baseUrl 从 `/config.json` 或 `window.__AI_BASE_URL__` 获取)
**请求格式:** `{ teacher_type, messages, stream }`
**SSE 格式:** `data: {"choices":[{"delta":{"content":"..."}}]}`
### 状态管理 (Pinia Store)
| Store | 职责 |
| ------------------ | ------------------------------------------ |
| `useExperimentStore` | 实验表单数据、字段验证、区域计算、依赖图 |
| `useStudentStore` | 学生认证信息、登录持久化 |
## 实验表单类型体系
```
ExperimentGridConfig
├── title: string
├── description?: string
└── sheets: GridSheet[]
├── id: string
├── title?: string
├── columns: number
├── columnHeaders?: string[]
└── cells: GridCell[][]
├── GridLabelCell { type: 'label', content: string (支持 LaTeX) }
├── GridInputCell { type: 'input', fieldId, placeholder?, unit?, validation?, readingGuard? }
└── GridComputedCell { type: 'computed', areaId, expression, variables[], format? }
```
### 单元格验证状态
| 状态 | 背景色 | 含义 |
| ---- | ------ | ---- |
| 空白未填写 | `#ffffff` (白色) | 尚未输入 |
| 已填写未验证 | `#fff3cd` (黄色) | 等待验证 |
| 验证通过 | `#d4edda` (绿色) | 数据合格 |
| 验证失败 | `#f8d7da` (红色) | 数据不合格 |
## 调试面板
通过设置 `localStorage.DEBUG = 'true'` 启用。功能包括:
- **实验导航:** 列出所有可用实验,点击跳转
- **跳过阶段限制:** 勾选后无视 `Experience.skipable`,可自由点击阶段标签
- **AI 设置:** 查看/修改 AI Provider URL
- **AI 日志:** 查看最近 100 条 AI 请求/响应/错误记录,展开查看完整内容
## 拖拽系统
`useDraggable.ts` 提供两个 composable:
| Composable | 用途 | 返回 |
| ----------------------- | ----------------------------- | ---------------------- |
| `useDraggable(ref, opts)` | 元素拖拽(如调试面板、AI窗口) | `{ x, y, style, onPointerDown }` |
| `useDraggableTrigger(opts)` | 可拖动的浮动触发按钮 | `{ elRef, style, hasMoved, onPointerDown }` |
选项包括:`initialX/Y`(初始位置)、`handleSelector`(拖拽手柄选择器)、`boundary`(窗口边界约束)、`disabled`(禁用拖拽)。
## 设备适配
`useDevice.ts` 提供三级设备检测(mobile/tablet/desktop),断点:
- MOBILE: ≤ 480px
- TABLET: ≤ 768px
- DESKTOP: ≤ 1024px
- LARGE_DESKTOP: ≤ 1440px
`useExperimentDeviceAdapter()` 针对实验页面提供定制化的字段 padding、区域 margin、按钮尺寸和网格列数。
## Math/LaTeX 处理
- **LaTeX 渲染:** `utils/latex.ts` 使用 KaTeX,支持 `$...$` 行内和 `$$...$$` 块级公式
- **表达式计算:** `utils/calculation.ts` 将 LaTeX 表达式(`\frac`、`\sqrt` 等)转换为 mathjs 语法后求值
- **Markdown + LaTeX:** `utils/markdown.ts` 结合两者,先保护 LaTeX 块再渲染 Markdown,最后恢复
## PDF 导出
`utils/pdfExport.ts` 使用 html2canvas 截取 DOM 元素为图像,再用 jsPDF 生成 A4 格式 PDF,支持多页自动分页。
`ExperimentPage.vue` 在屏幕外(`left: -100000px`)渲染多份 `ExperimentPrintTable`,供 PDF 导出使用。

42
frontend/README.md 普通文件
查看文件

@ -0,0 +1,42 @@
# frontend
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
## Recommended Browser Setup
- Chromium-based browsers (Chrome, Edge, Brave, etc.):
- [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
- [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters)
- Firefox:
- [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/)
- [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/)
## Type Support for `.vue` Imports in TS
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
## Customize configuration
See [Vite Configuration Reference](https://vite.dev/config/).
## Project Setup
```sh
yarn
```
### Compile and Hot-Reload for Development
```sh
yarn dev
```
### Type-Check, Compile and Minify for Production
```sh
yarn build
```

1
frontend/env.d.ts vendored 普通文件
查看文件

@ -0,0 +1 @@
/// <reference types="vite/client" />

13
frontend/index.html 普通文件
查看文件

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

40
frontend/package.json 普通文件
查看文件

@ -0,0 +1,40 @@
{
"name": "phyexp",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build",
"format": "prettier --write --experimental-cli src/"
},
"dependencies": {
"html2canvas": "^1.4.1",
"jspdf": "^3.0.4",
"katex": "^0.16.45",
"mathjs": "^15.2.0",
"pinia": "^3.0.4",
"vue": "^3.5.30",
"vue-router": "^5.0.3"
},
"devDependencies": {
"@tsconfig/node24": "^24.0.4",
"@types/katex": "^0.16.8",
"@types/mathjs": "^9.4.2",
"@types/node": "^24.12.0",
"@vitejs/plugin-vue": "^6.0.4",
"@vue/tsconfig": "^0.9.0",
"npm-run-all2": "^8.0.4",
"prettier": "3.8.1",
"typescript": "~5.9.3",
"vite": "^7.3.1",
"vite-plugin-vue-devtools": "^8.0.7",
"vue-tsc": "^3.2.5"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
}

二进制
frontend/public/favicon.ico 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 4.2 KiB

8
frontend/src/App.vue 普通文件
查看文件

@ -0,0 +1,8 @@
<script setup lang="ts">
import DebugPanel from '@/components/DebugPanel.vue'
</script>
<template>
<RouterView />
<DebugPanel />
</template>

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 78 KiB

查看文件

@ -0,0 +1,21 @@
{
"meta": {
"author": "AI+声速测量实验 项目组",
"title": "预习资源"
},
"course": [
{
"type": "text",
"value": "这是一段文本"
},
{
"type": "file",
"name": "测试.pdf",
"URL": "https://git.jamaccao.cn/LeRoBot/PhyExp/raw/branch/master/index.html"
},
{
"type": "movie",
"URL": "https://git.jamaccao.cn/LeRoBot/PhyExp/raw/branch/master/index.html"
}
]
}

查看文件

@ -0,0 +1,55 @@
{
"$schema": "https://git.jamaccao.cn/LeRoBot/PhyExp/raw/branch/master/src/assets/question.schema.json",
"meta": {
"author": "DeepSeek",
"title": "声速测量实验 示例题目"
},
"questions": [
{
"type": "单选题",
"question": "在声速测量实验中,利用共振干涉法(驻波法)测量声速时,换能器接收端信号幅值出现极大值的位置对应于什么条件?",
"choices": [
"接收端与发射端之间的距离为半波长的整数倍",
"接收端与发射端之间的距离为波长的整数倍",
"接收端与发射端之间的距离为四分之一波长的奇数倍",
"接收端与发射端之间的距离与波长无关"
],
"answer": 0
},
{
"type": "多选题",
"question": "以下哪些因素会影响声速在空气中的测量结果?",
"choices": ["环境温度", "环境湿度", "大气压强", "超声波的频率"],
"answer": [0, 1, 2]
},
{
"type": "填空题",
"question": "在空气中,声速与温度的关系近似为 v = v0 √(1 + t/273),其中 v0 是 0℃ 时的声速,约为 ______ m/s。实验中常采用 ______ 法或 ______ 法来测量声速。",
"choices": [],
"answer": ["331", "共振干涉", "相位比较"]
},
{
"type": "单选题",
"question": "使用相位比较法测量声速时,李萨如图形从斜率为正的直线变为斜率为负的直线,对应声波传播距离变化了多少?",
"choices": ["λ/2", "λ/4", "λ", "λ/8"],
"answer": 0
},
{
"type": "简答题",
"question": "简述在声速测量实验中,如何判断接收换能器是否与发射换能器严格平行?如果未严格平行会对测量结果产生什么影响?",
"choices": [],
"answer": null
},
{
"type": "多选题",
"question": "在共振干涉法测量声速实验中,下列操作正确的是?",
"choices": [
"移动接收端时,应缓慢旋转测微头,避免回程误差",
"记录信号幅值最大时游标卡尺的读数",
"利用相邻极大值之间的距离计算波长",
"直接读取信号发生器上的频率作为超声波的频率"
],
"answer": [0, 2]
}
]
}

查看文件

@ -0,0 +1,40 @@
{
"experiences": {
"声速测量": {
"title": "声速测量实验",
"author": "AI+声速测量实验 团队",
"id": "cn.edu.muc.lxy.phyexp.voicespeed",
"image": "https://git.jamaccao.cn/LeRoBot/PhyExp/raw/branch/master/src/assets/VoiceSpeed/image.jpeg",
"stage": [
{
"name": "预习",
"type": "learn",
"resource": {
"course": "https://git.jamaccao.cn/LeRoBot/PhyExp/raw/branch/master/src/assets/VoiceSpeed/prelearn.json"
}
},
{
"name": "测验",
"type": "quiz",
"resource": {}
},
{
"name": "实验",
"type": "experiment",
"resource": {
"provider": "http://localhost:8000/form",
"validation_url": "http://localhost:8000/value"
}
},
{
"name": "考试",
"type": "exam"
},
{
"name": "总结",
"type": "report"
}
]
}
}
}

查看文件

@ -0,0 +1,87 @@
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "题目规范",
"description": "智能物理实验平台 预设题目规范",
"type": "object",
"properties": {
"meta": {
"type": "object",
"description": "关于本套题目组的元信息",
"properties": {
"author": {
"oneOf": [
{
"description": "单一作者",
"type": "string"
},
{
"description": "多作者题目合集",
"type": "array",
"items": {
"type": "string"
}
}
]
},
"title": {
"type": "string",
"description": "题目合集名称"
}
}
},
"questions": {
"description": "题目合集",
"type": "array",
"items": {
"description": "单一题目",
"type": "object",
"properties": {
"type": {
"description": "题目类型",
"type": "string",
"enum": ["单选题", "多选题", "填空题", "简答题"],
"default": "单选题"
},
"question": {
"description": "题目内容",
"type": "string"
},
"choices": {
"description": "选择题的选项",
"type": "array",
"items": {
"type": "string"
}
},
"answer": {
"description": "对题目的作答",
"anyOf": [
{
"type": "integer",
"description": "单选题答案,从0开始数"
},
{
"type": "array",
"items": {
"type": "integer"
},
"description": "多选题答案"
},
{
"type": "array",
"items": {
"type": "string"
},
"description": "填空题答案"
},
{
"type": "null",
"description": "简答题无标准答案"
}
]
}
}
}
}
}
}

查看文件

@ -0,0 +1,472 @@
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { streamChat, extractJsonBlock, safeParseJson, type ChatMessage as ApiChatMessage } from '@/utils/aiClient'
import { renderMarkdownWithLatex } from '@/utils/markdown'
import { useDraggable } from '@/composables/useDraggable'
const props = defineProps<{
isOpen: boolean
courseContent?: string
glossaryContent?: string
floating?: boolean
cellContext?: string
inspectActive?: boolean
onToggleInspect?: () => void
onClearCellContext?: () => void
}>()
const emit = defineEmits(['close'])
type ChatMessage = {
id: number
text: string
sender: 'user' | 'ai'
html?: string
raw?: string
status?: 'streaming' | 'done' | 'error'
}
const messages = ref<ChatMessage[]>([
{ id: 1, text: '你好!我是AI助教,有什么可以帮助你的吗?', sender: 'ai', status: 'done' },
])
const newMessage = ref('')
const sending = ref(false)
const errorText = ref('')
const panelRef = ref<HTMLElement | null>(null)
const isFloatingDisabled = computed(() => !props.floating)
const { style: floatingStyle, onPointerDown } = useDraggable(panelRef, {
initialX: window.innerWidth - 420,
initialY: 60,
boundary: 'window',
handleSelector: '.chat-header',
disabled: isFloatingDisabled,
})
const panelStyle = computed(() => {
if (props.floating) {
return floatingStyle.value
}
return {}
})
const truncateText = (text: string, maxLength: number) => {
if (text.length <= maxLength) return text
return `${text.slice(0, maxLength)}...`
}
const buildContext = () => {
const parts: string[] = []
if (props.courseContent) {
parts.push(`【预习材料】\n${truncateText(props.courseContent, 2000)}`)
}
if (props.glossaryContent) {
parts.push(`【术语表】\n${truncateText(props.glossaryContent, 2000)}`)
}
if (props.cellContext) {
parts.push(`【选中的单元格信息】\n${props.cellContext}`)
}
return parts.join('\n\n')
}
const buildUserContent = (question: string) => {
const context = buildContext()
const instruction = '请用中文、语气严谨但鼓励的方式回答。'
if (context) {
return `${instruction}\n${context}\n\n学生问题:${question}`
}
return `${instruction}\n学生问题:${question}`
}
const buildHistory = (): ApiChatMessage[] => {
return messages.value
.filter((message) => message.status !== 'streaming')
.map((message) => ({
role: (message.sender === 'user' ? 'user' : 'assistant') as ApiChatMessage['role'],
content: message.raw || message.text,
}))
}
const formatQaResponse = (rawText: string) => {
const jsonBlock = extractJsonBlock(rawText)
if (jsonBlock) {
const parsed = safeParseJson<Record<string, any>>(jsonBlock)
if (parsed.value) {
const payload = parsed.value
const sections: string[] = []
if (payload.core_concept) {
sections.push(`**核心概念**:${payload.core_concept}`)
}
if (payload.direct_answer) {
sections.push(`**直接回答**:${payload.direct_answer}`)
}
if (payload.understanding) {
sections.push(`**理解提示**:${payload.understanding}`)
}
if (payload.deep_dive) {
sections.push(`**深入说明**:${payload.deep_dive}`)
}
if (Array.isArray(payload.practical_tips) && payload.practical_tips.length > 0) {
const tips = payload.practical_tips.map((item: string) => `- ${item}`).join('\n')
sections.push(`**实验提示**\n${tips}`)
}
if (Array.isArray(payload.self_check_questions) && payload.self_check_questions.length > 0) {
const checks = payload.self_check_questions
.map((item: { question?: string; hint?: string }, index: number) => {
const q = item.question || `自检问题 ${index + 1}`
const hint = item.hint ? `(提示:${item.hint})` : ''
return `- ${q}${hint}`
})
.join('\n')
sections.push(`**自检问题**\n${checks}`)
}
const markdown = sections.join('\n\n') || '已收到AI回复,但内容为空。'
return { html: renderMarkdownWithLatex(markdown), text: markdown, raw: rawText }
}
}
return { html: renderMarkdownWithLatex(rawText), text: rawText || 'AI未返回可解析的内容。', raw: rawText }
}
const sendMessage = () => {
const trimmed = newMessage.value.trim()
if (!trimmed || sending.value) return
errorText.value = ''
const history = buildHistory()
messages.value.push({ id: Date.now(), text: trimmed, sender: 'user' })
newMessage.value = ''
sending.value = true
const aiMessage: ChatMessage = {
id: Date.now() + 1,
text: 'AI正在输入...',
sender: 'ai',
status: 'streaming',
}
messages.value.push(aiMessage)
const aiIndex = messages.value.length - 1
const userContent = buildUserContent(trimmed)
const requestMessages: ApiChatMessage[] = [...history, { role: 'user' as const, content: userContent }]
streamChat(
{
teacherType: 'question',
messages: requestMessages,
stream: true,
},
(_token, fullText) => {
const target = messages.value[aiIndex]
if (target) {
target.text = fullText
}
},
)
.then((fullText) => {
const target = messages.value[aiIndex]
if (!target) return
const formatted = formatQaResponse(fullText)
target.text = formatted.text
target.html = formatted.html
target.raw = formatted.raw
target.status = 'done'
})
.catch((error) => {
const target = messages.value[aiIndex]
if (target) {
target.text = 'AI请求失败,请稍后重试。'
target.status = 'error'
}
errorText.value = error instanceof Error ? error.message : 'AI请求失败'
})
.finally(() => {
sending.value = false
})
}
watch(() => props.isOpen, (newVal) => {
if (newVal) {}
})
</script>
<template>
<div
v-show="!floating || isOpen"
ref="panelRef"
class="chat-sidebar"
:class="{ open: isOpen, floating: floating }"
:style="panelStyle"
@pointerdown="onPointerDown"
>
<div class="chat-header">
<h3>AI 助教</h3>
<div class="chat-header-actions">
<button
v-if="onToggleInspect"
class="inspect-btn"
:class="{ active: inspectActive }"
@pointerdown.stop
@click="onToggleInspect()"
:title="inspectActive ? '退出单元格选择' : '选择实验表格单元格'"
>
{{ inspectActive ? '退出选择' : '🔍 单元格' }}
</button>
<button class="close-btn" @pointerdown.stop @click="$emit('close')">&times;</button>
</div>
</div>
<div v-if="cellContext" class="cell-context-bar">
<div class="cell-context-header">
<span class="cell-context-label">已选中单元格:</span>
<button
v-if="onClearCellContext"
class="context-clear-btn"
@click="onClearCellContext()"
>
&times;
</button>
</div>
<pre class="cell-context-text">{{ cellContext }}</pre>
</div>
<div class="chat-messages">
<div v-if="errorText" class="chat-error">{{ errorText }}</div>
<div v-if="inspectActive" class="inspect-hint">
🔍 点击实验表格中的任意单元格将其信息添加到AI上下文
</div>
<div
v-for="message in messages"
:key="message.id"
class="message"
:class="[message.sender]"
>
<div
v-if="message.sender === 'ai' && message.html && message.status === 'done'"
v-html="message.html"
></div>
<div v-else>{{ message.text }}</div>
</div>
</div>
<div class="chat-input">
<input
v-model="newMessage"
@keyup.enter="sendMessage"
placeholder="输入你的问题..."
:disabled="sending"
/>
<button @click="sendMessage" :disabled="sending">发送</button>
</div>
</div>
</template>
<style scoped>
.chat-sidebar {
position: fixed;
right: -400px;
top: 0;
width: 380px;
height: 100%;
background-color: white;
box-shadow: -5px 0 15px rgba(0, 0, 0, 0.1);
transition: right 0.4s ease-in-out;
display: flex;
flex-direction: column;
z-index: 1001;
}
.chat-sidebar.open {
right: 0;
}
.chat-sidebar.floating {
right: auto;
top: auto;
height: 520px;
border-radius: 12px;
overflow: hidden;
transition: none;
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.2);
}
.chat-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.8rem 1.2rem;
background-color: #007bff;
color: white;
}
.chat-header h3 {
margin: 0;
font-size: 1.1rem;
}
.chat-header-actions {
display: flex;
align-items: center;
gap: 6px;
}
.chat-sidebar.floating .chat-header {
cursor: grab;
user-select: none;
}
.chat-sidebar.floating .chat-header:active {
cursor: grabbing;
}
.inspect-btn {
background: rgba(255,255,255,0.25);
border: 1px solid rgba(255,255,255,0.5);
color: white;
padding: 3px 10px;
border-radius: 14px;
cursor: pointer;
font-size: 0.8rem;
font-weight: 600;
white-space: nowrap;
transition: background 0.2s;
}
.inspect-btn:hover {
background: rgba(255,255,255,0.4);
}
.inspect-btn.active {
background: rgba(255,255,255,0.5);
border-color: white;
}
.close-btn {
background: none;
border: none;
color: white;
font-size: 1.6rem;
cursor: pointer;
padding: 0;
line-height: 1;
}
.cell-context-bar {
background: #e8f5e9;
border-bottom: 1px solid #c8e6c9;
padding: 0.5rem 0.8rem;
max-height: 140px;
overflow-y: auto;
}
.cell-context-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.cell-context-label {
font-size: 0.75rem;
font-weight: 600;
color: #2e7d32;
}
.context-clear-btn {
background: none;
border: none;
color: #888;
font-size: 1.2rem;
cursor: pointer;
padding: 0 4px;
line-height: 1;
}
.context-clear-btn:hover {
color: #333;
}
.cell-context-text {
margin: 0;
font-size: 0.75rem;
color: #333;
white-space: pre-wrap;
font-family: monospace;
}
.inspect-hint {
background: #e3f2fd;
color: #1565c0;
padding: 0.5rem 0.8rem;
border-radius: 8px;
font-size: 0.8rem;
text-align: center;
}
.chat-messages {
flex-grow: 1;
padding: 1rem;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.8rem;
}
.chat-error {
background-color: #fff1f0;
color: #c71d1d;
border: 1px solid #ffd5d5;
padding: 0.6rem 0.8rem;
border-radius: 8px;
font-size: 0.9rem;
}
.message {
padding: 0.8rem 1rem;
border-radius: 10px;
max-width: 85%;
word-wrap: break-word;
}
.message.ai {
background-color: #f1f1f1;
align-self: flex-start;
}
.message.user {
background-color: #dcf8c6;
align-self: flex-end;
}
.chat-input {
display: flex;
padding: 1rem;
border-top: 1px solid #eee;
}
.chat-input input {
flex-grow: 1;
border: 1px solid #ddd;
border-radius: 20px;
padding: 0.8rem 1rem;
margin-right: 0.5rem;
}
.chat-input button {
background-color: #007bff;
color: white;
border: none;
border-radius: 20px;
padding: 0.8rem 1.2rem;
cursor: pointer;
font-weight: 600;
}
.chat-input button:hover {
background-color: #0056b3;
}
</style>

查看文件

@ -0,0 +1,457 @@
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useDraggable } from '@/composables/useDraggable'
import { aiLogs, clearAiLogs, getBaseUrl, setBaseUrl, type AiLogEntry } from '@/utils/aiClient'
const isVisible = ref(false)
const panelRef = ref<HTMLElement | null>(null)
const debugEnabled = ref(false)
const { style: panelStyle, onPointerDown } = useDraggable(panelRef, {
initialX: 100,
initialY: 100,
boundary: 'window',
handleSelector: '.debug-header',
})
type DebugExperience = {
id: string
title: string
author: string
image: string
}
const experiences = ref<DebugExperience[]>([])
const skipStageCheck = ref(false)
const aiProviderUrl = ref(getBaseUrl() || '')
const aiLogExpanded = ref<number | null>(null)
watch(skipStageCheck, (val) => {
;(window as any).__DEBUG_SKIP_STAGE__ = val
})
const saveAiProvider = () => {
const trimmed = aiProviderUrl.value.trim()
setBaseUrl(trimmed || null)
}
const loadExperiences = async () => {
try {
const response = await fetch('/src/assets/experiences.json')
if (!response.ok) return
const data = await response.json()
if (data?.experiences) {
experiences.value = Object.values(data.experiences) as DebugExperience[]
}
} catch {
try {
const response = await fetch('/assets/experiences.json')
if (!response.ok) return
const data = await response.json()
if (data?.experiences) {
experiences.value = Object.values(data.experiences) as DebugExperience[]
}
} catch {
experiences.value = []
}
}
}
const togglePanel = () => {
if (!isVisible.value) {
loadExperiences()
aiProviderUrl.value = getBaseUrl() || ''
}
isVisible.value = !isVisible.value
}
const toggleLogExpand = (id: number) => {
aiLogExpanded.value = aiLogExpanded.value === id ? null : id
}
const formatLogPreview = (entry: AiLogEntry): string => {
if (entry.type === 'error') return entry.error || 'Unknown error'
if (entry.type === 'request') return (entry.payload || '').slice(0, 100)
return (entry.body || '').slice(0, 100)
}
const formatTime = (ts: number): string => {
const d = new Date(ts)
return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`
}
onMounted(() => {
debugEnabled.value = localStorage.getItem('DEBUG') === 'true'
skipStageCheck.value = !!(window as any).__DEBUG_SKIP_STAGE__
if (debugEnabled.value) {
loadExperiences()
}
})
const navToExperience = (id: string) => {
window.location.hash = `#/exp?expid=${encodeURIComponent(id)}`
}
</script>
<template>
<div v-if="debugEnabled">
<button
v-if="!isVisible"
class="debug-trigger"
@click="togglePanel"
>
🔧 调试
</button>
<div
ref="panelRef"
v-show="isVisible"
class="debug-panel"
:style="panelStyle"
@pointerdown="onPointerDown"
>
<div class="debug-header">
<span>调试面板</span>
<button class="debug-close" @click="isVisible = false">&times;</button>
</div>
<div class="debug-body">
<div class="debug-section">
<h4>实验导航</h4>
<label class="debug-checkbox">
<input type="checkbox" v-model="skipStageCheck" />
跳过阶段限制(无视 skipable)
</label>
<div v-if="experiences.length === 0" class="debug-empty">暂无实验项目</div>
<div
v-for="exp in experiences"
:key="exp.id"
class="debug-item"
@click="navToExperience(exp.id)"
>
<div class="debug-item-title">{{ exp.title }}</div>
<div class="debug-item-id">{{ exp.id }}</div>
</div>
</div>
<div class="debug-section">
<h4>AI 设置</h4>
<div class="debug-field">
<label>Provider URL</label>
<div class="debug-input-row">
<input
v-model="aiProviderUrl"
placeholder="例如 http://localhost:8000"
class="debug-input"
/>
<button class="debug-btn debug-btn-sm" @click="saveAiProvider">保存</button>
</div>
</div>
<div class="debug-ai-logs">
<div class="debug-logs-header">
<span>AI 请求/响应日志({{ aiLogs.length }})</span>
<button v-if="aiLogs.length" class="debug-btn debug-btn-sm" @click="clearAiLogs">清空</button>
</div>
<div v-if="aiLogs.length === 0" class="debug-empty">暂无日志</div>
<div
v-for="entry in aiLogs"
:key="entry.id"
class="debug-log-entry"
:class="entry.type"
>
<div class="debug-log-summary" @click="toggleLogExpand(entry.id)">
<span class="debug-log-badge">{{ entry.type === 'error' ? '❌' : entry.type === 'request' ? '📤' : '📥' }}</span>
<span class="debug-log-type">{{ entry.teacherType }}</span>
<span class="debug-log-time">{{ formatTime(entry.timestamp) }}</span>
<span class="debug-log-preview">{{ formatLogPreview(entry) }}</span>
</div>
<div v-if="aiLogExpanded === entry.id" class="debug-log-detail">
<div class="debug-log-meta">端点: {{ entry.endpoint }}</div>
<div v-if="entry.status" class="debug-log-meta">状态: {{ entry.status }}</div>
<pre class="debug-log-body">{{ entry.payload || entry.body || entry.error }}</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.debug-trigger {
position: fixed;
left: 1rem;
bottom: 1rem;
z-index: 9999;
background: #6c757d;
color: white;
border: none;
border-radius: 50px;
padding: 0.6rem 1.2rem;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
transition: all 0.2s ease;
}
.debug-trigger:hover {
background: #5a6268;
transform: scale(1.05);
}
.debug-panel {
position: fixed;
width: 380px;
max-height: 550px;
background: white;
border-radius: 12px;
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.2);
z-index: 10000;
display: flex;
flex-direction: column;
overflow: hidden;
}
.debug-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem 1rem;
background: #343a40;
color: white;
font-weight: 600;
cursor: grab;
user-select: none;
flex-shrink: 0;
}
.debug-header:active {
cursor: grabbing;
}
.debug-close {
background: none;
border: none;
color: white;
font-size: 1.5rem;
cursor: pointer;
padding: 0;
line-height: 1;
}
.debug-body {
padding: 0.75rem 1rem;
overflow-y: auto;
flex: 1;
}
.debug-section {
margin-bottom: 1rem;
}
.debug-section h4 {
margin: 0 0 0.5rem 0;
font-size: 0.9rem;
color: #333;
font-weight: 700;
border-bottom: 1px solid #eee;
padding-bottom: 0.3rem;
}
.debug-checkbox {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 0.85rem;
color: #555;
margin-bottom: 0.5rem;
cursor: pointer;
}
.debug-checkbox input {
margin: 0;
}
.debug-empty {
color: #999;
font-size: 0.85rem;
padding: 0.5rem 0;
}
.debug-item {
padding: 0.6rem 0.75rem;
border: 1px solid #e9ecef;
border-radius: 8px;
margin-bottom: 0.4rem;
cursor: pointer;
transition: all 0.15s ease;
}
.debug-item:hover {
background: #f8f9fa;
border-color: #007bff;
}
.debug-item-title {
font-weight: 600;
font-size: 0.9rem;
color: #333;
}
.debug-item-id {
font-size: 0.75rem;
color: #888;
margin-top: 0.15rem;
}
.debug-field {
margin-bottom: 0.6rem;
}
.debug-field label {
display: block;
font-size: 0.8rem;
color: #666;
margin-bottom: 0.25rem;
font-weight: 600;
}
.debug-input-row {
display: flex;
gap: 0.4rem;
}
.debug-input {
flex: 1;
padding: 0.35rem 0.5rem;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 0.85rem;
outline: none;
}
.debug-input:focus {
border-color: #007bff;
}
.debug-btn {
background: #007bff;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: 600;
transition: background 0.15s ease;
}
.debug-btn:hover {
background: #0056b3;
}
.debug-btn-sm {
padding: 0.35rem 0.6rem;
font-size: 0.8rem;
}
.debug-ai-logs {
margin-top: 0.75rem;
}
.debug-logs-header {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.8rem;
color: #666;
font-weight: 600;
margin-bottom: 0.4rem;
}
.debug-log-entry {
border: 1px solid #eee;
border-radius: 6px;
margin-bottom: 0.3rem;
overflow: hidden;
font-size: 0.78rem;
}
.debug-log-entry.request {
border-left: 3px solid #007bff;
}
.debug-log-entry.response {
border-left: 3px solid #28a745;
}
.debug-log-entry.error {
border-left: 3px solid #dc3545;
}
.debug-log-summary {
display: flex;
align-items: center;
gap: 0.4rem;
padding: 0.35rem 0.5rem;
cursor: pointer;
background: #fafafa;
}
.debug-log-summary:hover {
background: #f0f0f0;
}
.debug-log-badge {
font-size: 0.75rem;
flex-shrink: 0;
}
.debug-log-type {
font-weight: 600;
color: #333;
flex-shrink: 0;
}
.debug-log-time {
color: #999;
font-size: 0.7rem;
flex-shrink: 0;
}
.debug-log-preview {
color: #888;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.debug-log-detail {
padding: 0.4rem 0.5rem;
background: #f8f9fa;
border-top: 1px solid #eee;
}
.debug-log-meta {
font-size: 0.75rem;
color: #666;
margin-bottom: 0.2rem;
}
.debug-log-body {
margin: 0;
font-size: 0.75rem;
white-space: pre-wrap;
word-break: break-all;
max-height: 160px;
overflow-y: auto;
background: #fff;
border: 1px solid #eee;
border-radius: 4px;
padding: 0.4rem;
color: #333;
}
</style>

查看文件

@ -0,0 +1,441 @@
<script lang="ts">
import { defineComponent, type PropType } from 'vue'
import { type QuestionType } from '@/types/question'
type answerStatus = 'right' | 'wrong' | 'part' | 'blank' | 'waiting'
export default defineComponent({
props: {
question: {
type: Object as PropType<QuestionType>,
required: true,
},
doAnswer: {
type: Function as any,
required: false,
},
},
data() {
return {
choice: '', // 单选
choices: [] as number[], // 多选
answers: [] as string[], // 填空
answer: '', // 简答
enabled: true, // 是否可编辑
corret: null as boolean | null, // 正确
optionStatus: [] as Array<'correct' | 'wrong' | ''>, // 每个选项的状态
fillStatuses: [] as Array<boolean>, // 每个填空的状态
essayStatus: { isCorrect: null as boolean | null, correctAnswer: '' }, // 简答题状态
}
},
methods: {
calc(): [number, answerStatus] {
this.enabled = false
let score = 0
let fullScore = 0
let status: answerStatus = 'wrong'
switch (this.question.type) {
case '单选题': {
fullScore = 10
const correctAnswer = this.question.answer
const userChoice = this.choice
const isCorrect = userChoice !== '' && Number(userChoice) === correctAnswer
score = isCorrect ? fullScore : 0
this.corret = isCorrect
status = isCorrect ? 'right' : 'wrong'
// 设置每个选项的样式标记
const choicesLen = this.question.choices.length
const statuses = new Array(choicesLen).fill('') as Array<'correct' | 'wrong' | ''>
// 正确选项永远标绿
statuses[correctAnswer] = 'correct'
// 如果用户选错,把用户选的选项标红
if (!isCorrect && userChoice !== '') {
statuses[Number(userChoice)] = 'wrong'
}
this.optionStatus = statuses
break
}
case '多选题': {
fullScore = 12
const correctAnswers: number[] = this.question.answer
const userChoices: number[] = this.choices
const correctSet = new Set(correctAnswers)
const userSet = new Set(userChoices)
let hasWrong = false
for (const choice of userChoices) {
if (!correctSet.has(choice)) {
hasWrong = true
break
}
}
if (hasWrong) {
// 多选(选择了错误选项)得0分
score = 0
this.corret = false
status = 'wrong'
} else {
// 只有正确选项(可能少选)
const unitScore = fullScore / correctAnswers.length
let correctSelectedCount = 0
for (const ans of correctAnswers) {
if (userSet.has(ans)) correctSelectedCount++
}
score = correctSelectedCount * unitScore
score = Math.round(score * 100) / 100
this.corret = score === fullScore
status = this.corret ? 'right' : score == 0 ? 'wrong' : 'part'
}
// 设置每个选项的样式标记(正确选项标绿,错误选项标红)
const totalOptions = this.question.choices.length
const statuses = new Array(totalOptions).fill('') as Array<'correct' | 'wrong' | ''>
for (let i = 0; i < totalOptions; i++) {
if (correctSet.has(i)) {
statuses[i] = 'correct' // 正确答案永远标绿
} else if (userSet.has(i) && !correctSet.has(i)) {
statuses[i] = 'wrong' // 用户错误选择的选项标红
}
}
this.optionStatus = statuses
break
}
case '填空题': {
const standardAnswer = this.question.answer
const userAnswer = this.answers
let fullScore = standardAnswer.length * 5
for (const i in standardAnswer) {
let right = standardAnswer[i]?.trim() == userAnswer[i]?.trim()
this.fillStatuses[i] = right
score += right ? 5 : 0
}
status = fullScore == score ? 'right' : score == 0 ? 'wrong' : 'part'
break
}
case '简答题': {
const hasAnswer = this.answer.trim().length > 0
this.essayStatus = {
isCorrect: hasAnswer ? null : false,
correctAnswer: '',
}
status = hasAnswer ? 'waiting' : 'blank'
break
}
}
return [score, status]
},
getAnswer() {
switch (this.question.type) {
case '单选题':
return this.choice
case '多选题':
return this.choices
case '填空题':
return this.answers
case '简答题':
return this.answer
default:
return null
}
},
},
})
</script>
<template>
<div class="QuestionArea" @focusin="doAnswer">
<!-- 题目头部:包含题型标签 + 题目文本 -->
<div class="question-header">
<span class="question-type-tag">{{ question.type }}</span>
<span
class="question-text"
:class="{
'text-green-600': corret === true,
'text-red-600': corret === false
}"
>
{{ question.question }}
</span>
</div>
<!-- 单选题 -->
<div class="options-group" v-if="question.type === '单选题'">
<div
class="option-item"
v-for="(c, i) in question.choices"
:key="i"
>
<label class="option-label">
<input
type="radio"
v-model="choice"
:value="i"
:disabled="!enabled"
class="option-radio"
/>
<span
class="option-content"
:class="{
'correct-option': optionStatus[i] === 'correct',
'wrong-option': optionStatus[i] === 'wrong',
}"
>
{{ c }}
</span>
</label>
</div>
</div>
<!-- 多选题 -->
<div class="options-group" v-if="question.type === '多选题'">
<div
class="option-item"
v-for="(c, i) in question.choices"
:key="i"
>
<label class="option-label">
<input
type="checkbox"
v-model="choices"
:value="i"
:disabled="!enabled"
class="option-checkbox"
/>
<span
class="option-content"
:class="{
'correct-option': optionStatus[i] === 'correct',
'wrong-option': optionStatus[i] === 'wrong',
}"
>
{{ c }}
</span>
</label>
</div>
</div>
<!-- 填空题 -->
<div class="fill-group" v-if="question.type === '填空题'">
<div class="fill-item" v-for="(c, i) in question.answer" :key="i">
<span class="fill-label">({{ i + 1 }})</span>
<input
type="text"
v-model="answers[i]"
:disabled="!enabled"
class="fill-input"
:class="{
'correct-input': fillStatuses[i] == true,
'wrong-input': fillStatuses[i] == false,
}"
/>
<!-- 错误时显示正确答案(绿色) -->
<span v-if="fillStatuses[i] == false" class="correct-hint">
(正确答案:{{ question.answer[i] }})
</span>
</div>
</div>
<!-- 简答题 -->
<div class="essay-group" v-if="question.type === '简答题'">
<textarea
v-model="answer"
:disabled="!enabled"
class="essay-textarea"
:class="{
'correct-input': essayStatus.isCorrect === true,
'wrong-input': essayStatus.isCorrect === false && !enabled,
}"
placeholder="请输入你的答案..."
></textarea>
<!-- 错误时显示正确答案(绿色) -->
<div
v-if="essayStatus.isCorrect === false && !enabled && essayStatus.correctAnswer"
class="correct-hint essay-hint"
>
参考答案:{{ essayStatus.correctAnswer }}
</div>
</div>
</div>
</template>
<style scoped>
/* 基础容器样式 */
.QuestionArea {
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 24px;
margin-bottom: 20px;
background-color: #ffffff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
}
.QuestionArea:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
transform: translateY(-2px);
}
/* 题目头部样式 */
.question-header {
display: flex;
align-items: flex-start;
margin-bottom: 20px;
gap: 12px;
}
.question-type-tag {
background-color: #007bff;
color: white;
padding: 4px 10px;
border-radius: 15px;
font-size: 0.8rem;
font-weight: bold;
flex-shrink: 0;
}
.question-text {
font-size: 1.1rem;
line-height: 1.6;
color: #333;
}
.text-green-600 {
color: #16a34a;
}
.text-red-600 {
color: #dc2626;
}
/* 选项组通用样式 */
.options-group {
display: flex;
flex-direction: column;
gap: 12px;
}
.option-item {
display: block;
}
.option-label {
display: flex;
align-items: center;
padding: 14px;
border: 1px solid #e0e0e0;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s ease;
}
.option-label:hover {
background-color: #f8f9fa;
border-color: #007bff;
}
.option-radio,
.option-checkbox {
margin-right: 12px;
width: 18px;
height: 18px;
}
.option-content {
font-size: 1rem;
color: #555;
}
/* 答案状态样式 */
.correct-option {
color: #28a745;
font-weight: bold;
}
.wrong-option {
color: #dc3545;
text-decoration: line-through;
}
.option-label:has(.correct-option) {
background-color: #e9f7ef;
border-color: #28a745;
}
.option-label:has(.wrong-option) {
background-color: #fbe9e7;
border-color: #dc3545;
}
/* 填空题样式 */
.fill-group {
display: flex;
flex-direction: column;
gap: 15px;
}
.fill-item {
display: flex;
align-items: center;
gap: 10px;
}
.fill-label {
font-weight: bold;
}
.fill-input {
padding: 10px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 1rem;
flex-grow: 1;
}
.correct-input {
border-color: #28a745;
background-color: #e9f7ef;
}
.wrong-input {
border-color: #dc3545;
background-color: #fbe9e7;
}
.correct-hint {
color: #28a745;
font-size: 0.9rem;
}
/* 简答题样式 */
.essay-group {
display: flex;
flex-direction: column;
gap: 10px;
}
.essay-textarea {
padding: 12px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 1rem;
min-height: 120px;
resize: vertical;
}
.essay-hint {
background-color: #e9f7ef;
padding: 10px;
border-radius: 6px;
}
/* 禁用状态样式 */
input:disabled,
textarea:disabled {
cursor: not-allowed;
opacity: 0.9;
}
</style>

查看文件

@ -0,0 +1,301 @@
<script setup lang="ts">
import { computed, watch, provide } from 'vue'
import type { ExperimentGridConfig, GridInputCell } from '@/types/experiment'
import ExperimentGrid from './ExperimentGrid.vue'
import { useExperimentStore } from '@/stores/experiment'
import { useStudentStore } from '@/stores/student'
import { storeToRefs } from 'pinia'
import { chatOnce, extractJsonBlock, safeParseJson } from '@/utils/aiClient'
import { AIEvalContextKey, type ConfigSummary, type AIEvalFocus, type AIEvalResult } from '@/utils/aiEvalContext'
const props = defineProps<{
config: ExperimentGridConfig
validationUrl?: string
cellInspectMode?: boolean
}>()
const emit = defineEmits<{
'field-update': [fieldId: string, value: any]
'field-validate': [fieldId: string]
'all-validated': []
'cell-inspect': [info: { sheetTitle?: string; cellType: string; label: string; value: any; unit?: string; validation?: any }]
}>()
const experimentStore = useExperimentStore()
const studentStore = useStudentStore()
const { StudentInfo } = storeToRefs(studentStore)
experimentStore.setConfig(props.config, props.validationUrl)
const fieldData = computed(() => experimentStore.data)
const areaResults = computed(() => experimentStore.areaResults)
const allFieldsValidated = computed(() => experimentStore.allFieldsValidated)
const dataVersion = computed(() => experimentStore.dataVersion)
const configSummary = computed<ConfigSummary>(() => {
const fields: ConfigSummary['fields'] = []
const areas: ConfigSummary['areas'] = []
props.config.sheets.forEach((sheet) => {
sheet.cells.forEach((row) => {
row.forEach((cell) => {
if (!cell) return
if (cell.type === 'input') {
const inp = cell as GridInputCell
fields.push({
id: inp.fieldId,
label: inp.fieldId,
unit: inp.unit,
validation: inp.validation,
})
}
if (cell.type === 'computed') {
areas.push({
id: cell.areaId,
label: cell.areaId,
expression: cell.expression,
variables: cell.variables,
format: cell.format,
})
}
})
})
})
return {
title: props.config.title,
description: props.config.description,
fields,
areas,
}
})
const evalCache = new Map<string, { version: number; result: AIEvalResult }>()
const formatDataEvalResponse = (rawText: string): AIEvalResult => {
const jsonBlock = extractJsonBlock(rawText)
if (jsonBlock) {
const parsed = safeParseJson<Record<string, any>>(jsonBlock)
if (parsed.value) {
const payload = parsed.value
const sections: string[] = []
if (payload.grade && payload.grade_description) {
sections.push(`**评级**:${payload.grade}(${payload.grade_description})`)
}
if (payload.metrics?.relative_error_percent !== undefined) {
sections.push(`**相对误差**:${payload.metrics.relative_error_percent}%`)
}
if (payload.metrics?.data_quality_assessment) {
sections.push(`**数据质量**:${payload.metrics.data_quality_assessment}`)
}
if (payload.teacher_comments) {
sections.push(`**点评**:${payload.teacher_comments}`)
}
if (Array.isArray(payload.improvement_suggestions) && payload.improvement_suggestions.length > 0) {
const suggestions = payload.improvement_suggestions
.map((item: any) => `- ${item.issue || ''}:${item.suggestion || ''}`)
.join('\n')
sections.push(`**改进建议**\n${suggestions}`)
}
return { rawText, displayText: sections.join('\n\n') || rawText, parsed: payload }
}
}
return { rawText, displayText: rawText || 'AI未返回可解析的评价结果。', parsed: null }
}
const requestEvaluation = async (focus: AIEvalFocus): Promise<AIEvalResult> => {
const cacheKey = `${focus.type}:${focus.id}`
const cached = evalCache.get(cacheKey)
if (cached && cached.version === dataVersion.value) {
return cached.result
}
const payload = {
student_id: String(StudentInfo.value?.SID ?? ''),
student_name: String(StudentInfo.value?.Name ?? ''),
focus_field: focus,
field_values: fieldData.value,
area_results: areaResults.value,
config_summary: configSummary.value,
}
const userContent = [
'请用中文、语气严谨但鼓励的方式评价以下实验数据。',
'请输出符合JSON Schema的结果,避免额外文本。',
'',
JSON.stringify(payload, null, 2),
].join('\n')
const rawText = await chatOnce({
teacherType: 'data_eval',
messages: [{ role: 'user', content: userContent }],
stream: false,
})
const result = formatDataEvalResponse(rawText)
evalCache.set(cacheKey, { version: dataVersion.value, result })
return result
}
provide(AIEvalContextKey, {
configSummary,
fieldData,
areaResults,
dataVersion,
studentInfo: StudentInfo,
requestEvaluation,
})
const handleFieldUpdate = (fieldId: string, value: any) => {
experimentStore.setFieldValue(fieldId, value)
emit('field-update', fieldId, value)
}
const handleFieldValidate = async (fieldId: string) => {
await experimentStore.validateField(fieldId)
emit('field-validate', fieldId)
if (experimentStore.allFieldsValidated) {
emit('all-validated')
}
}
watch(allFieldsValidated, (newValue) => {
if (newValue) {
emit('all-validated')
}
})
</script>
<template>
<div class="experiment-form">
<div class="form-header">
<h2 class="form-title">{{ config.title }}</h2>
<p v-if="config.description" class="form-description">{{ config.description }}</p>
</div>
<div class="form-sheets">
<ExperimentGrid
v-for="sheet in config.sheets"
:key="sheet.id"
:sheet="sheet"
:field-data="fieldData"
:area-results="areaResults"
:on-field-update="handleFieldUpdate"
:on-field-validate="handleFieldValidate"
:cell-inspect-mode="cellInspectMode"
:on-cell-inspect="(info: any) => emit('cell-inspect', info)"
/>
</div>
<div class="form-status">
<div class="status-indicator" :class="{ 'all-valid': allFieldsValidated }">
<span class="status-icon">
<svg v-if="allFieldsValidated" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M20 6L9 17L4 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<svg v-else width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="currentColor" stroke-width="2"/>
<path d="M12 6V12L16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</span>
{{ allFieldsValidated ? '所有字段已验证' : '请完成所有字段验证' }}
</div>
<div class="progress">
<div class="progress-bar">
<div
class="progress-fill"
:style="{ width: `${experimentStore.allInputCount > 0 ? (experimentStore.validatedCount / experimentStore.allInputCount) * 100 : 0}%` }"
></div>
</div>
<span class="progress-text">
{{ experimentStore.validatedCount }} / {{ experimentStore.allInputCount }} 字段
</span>
</div>
</div>
</div>
</template>
<style scoped>
.experiment-form {
width: 100%;
}
.form-header {
margin-bottom: 2rem;
text-align: center;
padding-bottom: 1.25rem;
border-bottom: 2px solid #333;
}
.form-title {
font-size: 1.5rem;
font-weight: 700;
color: #1a1a1a;
margin-bottom: 0.4rem;
letter-spacing: 0.02em;
}
.form-description {
font-size: 0.95rem;
color: #666;
}
.form-sheets {
display: flex;
flex-direction: column;
gap: 2rem;
}
.form-status {
margin-top: 2rem;
padding: 0.75rem 1rem;
border-top: 1px solid #dee2e6;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.9rem;
}
.status-indicator {
font-weight: 600;
display: flex;
align-items: center;
gap: 0.4rem;
color: #555;
}
.status-indicator.all-valid {
color: #28a745;
}
.progress {
display: flex;
align-items: center;
gap: 0.6rem;
width: 220px;
}
.progress-bar {
height: 6px;
background: #e9ecef;
border-radius: 3px;
overflow: hidden;
flex-grow: 1;
}
.progress-fill {
height: 100%;
background: #333;
border-radius: 3px;
transition: width 0.5s ease;
}
.progress-text {
font-size: 0.8rem;
color: #888;
white-space: nowrap;
}
</style>

查看文件

@ -0,0 +1,198 @@
<script setup lang="ts">
import { computed, inject } from 'vue'
import type { GridSheet, GridCell, GridInputCell } from '@/types/experiment'
import ExperimentGridCell from './ExperimentGridCell.vue'
import { AIEvalContextKey } from '@/utils/aiEvalContext'
const props = defineProps<{
sheet: GridSheet
fieldData: Record<string, { value: any; validated: boolean; validationResult?: { accept: boolean; message: string } }>
areaResults: Record<string, { value: any; formatted: string; error?: string }>
onFieldUpdate: (fieldId: string, value: any) => void
onFieldValidate: (fieldId: string) => void
cellInspectMode?: boolean
onCellInspect?: (info: { sheetTitle?: string; cellType: string; label: string; value: any; unit?: string; validation?: any }) => void
}>()
const aiContext = inject(AIEvalContextKey, null)
const effectiveRows = computed(() => {
const rows = props.sheet.cells
return { rows }
})
function getCellValue(cell: GridCell) {
if (!cell) return null
if (cell.type === 'input') {
return props.fieldData[cell.fieldId]?.value ?? null
}
return null
}
function getCellValidated(cell: GridCell) {
if (!cell || cell.type !== 'input') return false
return props.fieldData[cell.fieldId]?.validated ?? false
}
function getCellValidationResult(cell: GridCell) {
if (!cell || cell.type !== 'input') return undefined
return props.fieldData[cell.fieldId]?.validationResult
}
function getCellAreaResult(cell: GridCell) {
if (!cell || cell.type !== 'computed') return undefined
return props.areaResults[cell.areaId]
}
function onCellInput(fieldId: string, value: any) {
props.onFieldUpdate(fieldId, value)
}
function onCellBlur(fieldId: string) {
props.onFieldValidate(fieldId)
}
function handleCellInspect(cell: GridCell) {
if (!props.onCellInspect || !cell) return
let label = ''
let value: any = undefined
let unit: string | undefined
let validation: any = undefined
let cellType = cell.type
if (cell.type === 'input') {
const inp = cell as GridInputCell
label = inp.fieldId
value = props.fieldData[inp.fieldId]?.value
unit = inp.unit
validation = inp.validation
} else if (cell.type === 'computed') {
label = cell.areaId
value = props.areaResults[cell.areaId]?.formatted
} else if (cell.type === 'label') {
label = cell.content
}
props.onCellInspect({
sheetTitle: props.sheet.title,
cellType,
label,
value,
unit,
validation,
})
}
const isFirstRowHeader = computed(() => {
return props.sheet.columnHeaders && props.sheet.columnHeaders.length > 0
})
</script>
<template>
<div class="grid-sheet">
<div v-if="sheet.title" class="sheet-title" v-html="sheet.title" />
<div class="grid-wrapper">
<table class="grid-table">
<thead v-if="isFirstRowHeader">
<tr>
<th class="grid-row-header-th"></th>
<th
v-for="(header, hi) in sheet.columnHeaders"
:key="hi"
class="grid-header-cell"
>
<span v-html="header" />
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in effectiveRows.rows" :key="ri" class="grid-row">
<td
v-for="(cell, ci) in row"
:key="ci"
class="grid-cell-wrapper"
:class="{
'cell-colspan': (cell?.colSpan ?? 1) > 1,
}"
:colspan="cell?.colSpan ?? 1"
:rowspan="cell?.rowSpan ?? 1"
>
<ExperimentGridCell
v-if="cell"
:cell="cell"
:value="getCellValue(cell)"
:validated="getCellValidated(cell)"
:validation-result="getCellValidationResult(cell)"
:area-result="getCellAreaResult(cell)"
:inspect-mode="cellInspectMode"
@input="(val: any) => onCellInput((cell as GridInputCell).fieldId, val)"
@blur="() => onCellBlur((cell as GridInputCell).fieldId)"
@inspect="handleCellInspect(cell)"
/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<style scoped>
.grid-sheet {
margin-bottom: 2rem;
}
.sheet-title {
font-size: 1.1rem;
font-weight: 700;
color: #1a1a1a;
margin-bottom: 0.5rem;
padding-left: 2px;
}
.grid-wrapper {
overflow-x: auto;
}
.grid-table {
width: 100%;
border-collapse: collapse;
border: 2px solid #333;
table-layout: auto;
}
.grid-row-header-th {
width: 1%;
white-space: nowrap;
background: #eef1f5;
border: 1px solid #d0d4da;
padding: 6px 8px;
min-width: 50px;
}
.grid-header-cell {
background: #eef1f5;
border: 1px solid #d0d4da;
padding: 4px 6px;
font-weight: 700;
font-size: 0.8rem;
text-align: center;
color: #333;
white-space: nowrap;
}
.grid-row {
border: none;
}
.grid-cell-wrapper {
border: 1px solid #d0d4da;
padding: 0;
vertical-align: middle;
}
.grid-cell-wrapper:first-child {
min-width: 70px;
}
</style>

查看文件

@ -0,0 +1,336 @@
<script setup lang="ts">
import { ref, computed, watch, inject, onBeforeUnmount } from 'vue'
import type { GridCell, GridInputCell, GridComputedCell, GridLabelCell } from '@/types/experiment'
import { renderTextWithLatex } from '@/utils/latex'
import { renderMarkdownWithLatex } from '@/utils/markdown'
import { AIEvalContextKey } from '@/utils/aiEvalContext'
const props = defineProps<{
cell: GridCell
value?: any
validated?: boolean
validationResult?: { accept: boolean; message: string }
areaResult?: { value: any; formatted: string; error?: string }
inspectMode?: boolean
}>()
const emit = defineEmits<{
input: [value: any]
blur: []
inspect: []
}>()
const isInput = computed(() => props.cell?.type === 'input')
const isComputed = computed(() => props.cell?.type === 'computed')
const isLabel = computed(() => props.cell?.type === 'label')
const inputCell = computed(() => (isInput.value ? (props.cell as GridInputCell) : null))
const computedCell = computed(() => (isComputed.value ? (props.cell as GridComputedCell) : null))
const labelCell = computed(() => (isLabel.value ? (props.cell as GridLabelCell) : null))
const internalValue = ref(props.value ?? '')
const isFocused = ref(false)
const isHovering = ref(false)
const aiContext = inject(AIEvalContextKey, null)
const tooltipVisible = ref(false)
const tooltipLoading = ref(false)
const tooltipHtml = ref('')
const tooltipError = ref('')
let hoverTimer: number | null = null
const hasValue = computed(() => {
return props.value !== null && props.value !== undefined && props.value !== ''
})
watch(() => props.value, (newVal) => {
internalValue.value = newVal ?? ''
})
const bgColor = computed(() => {
if (isLabel.value) return 'transparent'
if (!isInput.value) return 'transparent'
if (isFocused.value) return '#e8f0fe'
if (props.validated && props.validationResult?.accept) {
return '#d4edda'
}
if (props.validated && props.validationResult && !props.validationResult.accept) {
return '#f8d7da'
}
if (props.value !== null && props.value !== undefined && props.value !== '') {
return '#fff3cd'
}
return '#ffffff'
})
const labelBgColor = computed(() => {
if (!isLabel.value) return 'transparent'
if (labelCell.value?.style === 'header') return '#eef1f5'
return '#f8f9fa'
})
const labelHtml = computed(() => {
if (!isLabel.value || !labelCell.value) return ''
return renderTextWithLatex(labelCell.value.content)
})
const unitHtml = computed(() => {
if (!isInput.value || !inputCell.value?.unit) return ''
return renderTextWithLatex(inputCell.value.unit)
})
const hasError = computed(() => {
if (isComputed.value && props.areaResult?.error) return true
return false
})
function handleInput(event: Event) {
const target = event.target as HTMLInputElement
const val = target.value
internalValue.value = val
emit('input', val)
}
function handleBlur() {
isFocused.value = false
if (isInput.value) {
emit('blur')
}
}
function handleFocus() {
isFocused.value = true
tooltipVisible.value = false
clearHoverTimer()
}
function clearHoverTimer() {
if (hoverTimer !== null) {
window.clearTimeout(hoverTimer)
hoverTimer = null
}
}
function handleMouseEnter() {
isHovering.value = true
if (props.inspectMode) return
if (!aiContext || !hasValue.value || isFocused.value) return
clearHoverTimer()
hoverTimer = window.setTimeout(async () => {
if (!hasValue.value || isFocused.value) return
tooltipVisible.value = true
tooltipError.value = ''
tooltipHtml.value = ''
tooltipLoading.value = true
try {
const focusInfo = {
type: isInput.value ? 'field' as const : 'area' as const,
id: isInput.value ? (inputCell.value?.fieldId ?? '') : (computedCell.value?.areaId ?? ''),
label: isInput.value ? (inputCell.value?.fieldId ?? '') : (computedCell.value?.areaId ?? ''),
value: props.value ?? props.areaResult?.value,
unit: inputCell.value?.unit,
formatted: props.areaResult?.formatted,
}
const result = await aiContext.requestEvaluation(focusInfo)
tooltipHtml.value = renderMarkdownWithLatex(result.displayText)
} catch (error) {
tooltipError.value = error instanceof Error ? error.message : 'AI评价失败'
tooltipHtml.value = renderMarkdownWithLatex('AI评价失败,请稍后再试。')
} finally {
tooltipLoading.value = false
}
}, 600)
}
function handleMouseLeave() {
isHovering.value = false
clearHoverTimer()
tooltipVisible.value = false
}
function handleClick() {
if (props.inspectMode) {
emit('inspect')
}
}
onBeforeUnmount(() => {
clearHoverTimer()
})
</script>
<template>
<div
class="grid-cell"
:class="{
'cell-label': isLabel,
'cell-input': isInput,
'cell-computed': isComputed,
'cell-focused': isFocused,
'cell-inspect-mode': inspectMode,
'cell-inspect-hover': inspectMode && isHovering,
}"
:style="{
backgroundColor: isLabel ? labelBgColor : isInput ? bgColor : isComputed ? (areaResult?.error ? '#f8d7da' : '#f0fff4') : 'transparent',
}"
@mouseenter="handleMouseEnter"
@mouseleave="handleMouseLeave"
@click="handleClick"
>
<template v-if="isLabel">
<span class="label-text" v-html="labelHtml" />
</template>
<template v-else-if="isInput">
<input
class="cell-input-field"
:value="internalValue"
:placeholder="inputCell?.placeholder || ''"
@input="handleInput"
@blur="handleBlur"
@focus="handleFocus"
/>
<span v-if="unitHtml" class="cell-unit" v-html="unitHtml" />
</template>
<template v-else-if="isComputed">
<span v-if="areaResult?.error" class="computed-error">错误</span>
<span v-else-if="areaResult?.value != null" class="computed-value">
{{ areaResult?.formatted }}
</span>
<span v-else class="computed-pending">--</span>
</template>
<div
v-if="tooltipVisible && !isFocused"
class="ai-tooltip"
@mouseenter="clearHoverTimer"
@mouseleave="handleMouseLeave"
>
<div v-if="tooltipLoading" class="ai-tooltip-loading">AI正在评价...</div>
<div v-else-if="tooltipError" class="ai-tooltip-error">{{ tooltipError }}</div>
<div v-else v-html="tooltipHtml"></div>
</div>
</div>
</template>
<style scoped>
.grid-cell {
display: flex;
align-items: center;
justify-content: center;
min-height: 32px;
padding: 3px 6px;
gap: 3px;
font-size: 0.85rem;
transition: background-color 0.2s ease;
position: relative;
}
.cell-label {
justify-content: flex-start;
font-weight: 600;
color: #1a1a1a;
white-space: nowrap;
padding: 3px 10px;
}
.cell-input {
gap: 3px;
}
.cell-computed {
font-family: monospace;
font-weight: 600;
}
.cell-focused {
outline: 2px solid #4a90d9;
outline-offset: -1px;
}
.cell-inspect-mode {
cursor: pointer;
}
.cell-inspect-hover {
outline: 2px dashed #007bff;
outline-offset: -1px;
}
.label-text {
display: inline-block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cell-input-field {
border: none;
outline: none;
width: 100%;
font-size: 0.85rem;
font-family: inherit;
background: transparent;
text-align: center;
min-width: 0;
}
.cell-input-field::placeholder {
color: #bbb;
font-size: 0.75rem;
}
.cell-unit {
font-size: 0.75rem;
color: #666;
white-space: nowrap;
flex-shrink: 0;
}
.computed-value {
color: #155724;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.computed-error {
color: #dc3545;
}
.computed-pending {
color: #aaa;
}
.ai-tooltip {
position: absolute;
right: 0;
top: calc(100% + 4px);
width: min(320px, 85vw);
background: #ffffff;
border: 1px solid #d9d9d9;
border-radius: 8px;
padding: 0.7rem 0.85rem;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
z-index: 20;
font-size: 0.82rem;
line-height: 1.5;
pointer-events: auto;
}
.ai-tooltip-loading {
color: #555;
}
.ai-tooltip-error {
color: #c71d1d;
font-weight: 600;
}
</style>

查看文件

@ -0,0 +1,118 @@
<script setup lang="ts">
import type { GridSheet, ExperimentData, AreaCalculationResult, GridCell, GridInputCell, GridComputedCell } from '@/types/experiment'
import { renderTextWithLatex } from '@/utils/latex'
const props = defineProps<{
sheet: GridSheet
fieldData: ExperimentData
areaResults: Record<string, AreaCalculationResult>
}>()
function formatValue(value: unknown): string {
if (value === null || value === undefined) return ''
if (typeof value === 'number') return Number.isFinite(value) ? String(value) : ''
return String(value)
}
function resolveFieldValue(cell: GridCell): string {
if (!cell || cell.type !== 'input') return ''
const inp = cell as GridInputCell
return formatValue(props.fieldData[inp.fieldId]?.value)
}
function resolveAreaValue(cell: GridCell): string {
if (!cell || cell.type !== 'computed') return ''
const comp = cell as GridComputedCell
const formatted = props.areaResults[comp.areaId]?.formatted
if (!formatted || formatted === '等待计算...' || formatted === '等待输入...') return ''
return formatted
}
function renderLabel(content: string): string {
return renderTextWithLatex(content)
}
</script>
<template>
<div class="print-container">
<table class="print-table">
<thead v-if="sheet.columnHeaders && sheet.columnHeaders.length > 0">
<tr>
<th class="print-header-cell">项目</th>
<th
v-for="(header, hi) in sheet.columnHeaders"
:key="hi"
class="print-header-cell"
>
<span v-html="renderLabel(header)" />
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in sheet.cells" :key="ri" class="print-row">
<td
v-for="(cell, ci) in row"
:key="ci"
class="print-cell"
:class="{
'print-cell-label': cell?.type === 'label',
'print-cell-input': cell?.type === 'input',
'print-cell-computed': cell?.type === 'computed',
}"
:colspan="cell?.colSpan ?? 1"
>
<template v-if="cell?.type === 'label'">
<span v-html="renderLabel(cell.content)" />
</template>
<template v-else-if="cell?.type === 'input'">
{{ resolveFieldValue(cell) }}
</template>
<template v-else-if="cell?.type === 'computed'">
{{ resolveAreaValue(cell) }}
</template>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.print-container {
width: 100%;
}
.print-table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
.print-table th,
.print-table td {
border: 1px solid #d5d5d5;
padding: 5px 6px;
vertical-align: middle;
word-break: break-word;
}
.print-table th {
background: #f2f4f7;
font-weight: 600;
text-align: center;
}
.print-header-cell {
text-align: center;
}
.print-cell {
text-align: center;
}
.print-cell-label {
text-align: left;
font-weight: 600;
background: #f8f9fb;
}
</style>

查看文件

@ -0,0 +1,267 @@
import { ref, onMounted, onUnmounted } from 'vue'
import {
detectDevice,
getDeviceType,
isMobile,
isDesktop,
isTablet,
isTouchDevice,
isPortrait,
getScreenWidth,
getScreenHeight,
getPixelRatio,
getResponsiveFontSize,
getResponsiveSpacing,
getResponsiveMaxWidth,
onResize,
onOrientationChange,
getDeviceClasses,
applyDeviceStyles,
DeviceType,
BREAKPOINTS,
} from '@/utils/device'
/**
* 设备检测的Vue组合式函数
*/
export function useDevice() {
const deviceInfo = ref(detectDevice())
const deviceClasses = ref<string[]>(getDeviceClasses())
// 更新设备信息
const updateDeviceInfo = () => {
deviceInfo.value = detectDevice()
deviceClasses.value = getDeviceClasses()
}
// 监听窗口大小变化
const cleanupResize = onResize(updateDeviceInfo)
// 监听设备方向变化
const cleanupOrientation = onOrientationChange((isPortrait) => {
updateDeviceInfo()
})
// 组件挂载时应用设备样式
onMounted(() => {
// 可以在这里应用到特定的元素
// 例如:applyDeviceStyles(document.body)
})
// 组件卸载时清理监听器
onUnmounted(() => {
cleanupResize()
cleanupOrientation()
})
// 响应式工具函数
const responsiveFontSize = (baseSize: number) => getResponsiveFontSize(baseSize)
const responsiveSpacing = (baseSpacing: number) => getResponsiveSpacing(baseSpacing)
const responsiveMaxWidth = () => getResponsiveMaxWidth()
// 设备类型检查
const isDeviceType = (type: DeviceType) => deviceInfo.value.type === type
const isMobileDevice = () => isMobile()
const isDesktopDevice = () => isDesktop()
const isTabletDevice = () => isTablet()
return {
// 设备信息
deviceInfo,
deviceClasses,
// 设备类型
deviceType: deviceInfo.value.type,
isMobile: isMobileDevice,
isDesktop: isDesktopDevice,
isTablet: isTabletDevice,
isTouchDevice: () => isTouchDevice(),
isPortrait: () => isPortrait(),
// 屏幕信息
screenWidth: () => getScreenWidth(),
screenHeight: () => getScreenHeight(),
pixelRatio: () => getPixelRatio(),
// 断点信息
breakpoints: BREAKPOINTS,
// 响应式工具
responsiveFontSize,
responsiveSpacing,
responsiveMaxWidth,
// 设备类型检查
isDeviceType,
// 更新函数
updateDeviceInfo,
// 应用样式
applyDeviceStyles: (element: HTMLElement) => applyDeviceStyles(element),
}
}
/**
* 设备特定的样式提供者
*/
export function useDeviceStyles() {
const { deviceInfo, deviceClasses } = useDevice()
// 根据设备类型生成样式对象
const getStyles = () => {
const styles: Record<string, any> = {}
const { type, screenWidth } = deviceInfo.value
// 基础样式
styles.deviceType = type
// 根据设备类型调整字体大小
switch (type) {
case DeviceType.MOBILE:
styles.fontSize = '14px'
styles.spacing = '8px'
styles.containerPadding = '12px'
break
case DeviceType.TABLET:
styles.fontSize = '15px'
styles.spacing = '12px'
styles.containerPadding = '16px'
break
case DeviceType.DESKTOP:
styles.fontSize = '16px'
styles.spacing = '16px'
styles.containerPadding = '20px'
break
default:
styles.fontSize = '16px'
styles.spacing = '16px'
styles.containerPadding = '20px'
}
// 根据屏幕宽度调整布局
if (screenWidth < BREAKPOINTS.MOBILE) {
styles.layout = 'vertical'
styles.columns = 1
styles.maxWidth = '100%'
} else if (screenWidth < BREAKPOINTS.TABLET) {
styles.layout = 'vertical'
styles.columns = 1
styles.maxWidth = '100%'
} else if (screenWidth < BREAKPOINTS.DESKTOP) {
styles.layout = screenWidth > 600 ? 'grid' : 'vertical'
styles.columns = screenWidth > 600 ? 2 : 1
styles.maxWidth = '90%'
} else {
styles.layout = 'grid'
styles.columns = 3
styles.maxWidth = '1200px'
}
// 触摸设备优化
if (deviceInfo.value.isTouchDevice) {
styles.touchOptimized = true
styles.minTouchSize = '44px'
styles.inputPadding = '12px'
} else {
styles.touchOptimized = false
styles.minTouchSize = 'auto'
styles.inputPadding = '8px'
}
return styles
}
// 获取CSS变量
const getCSSVariables = () => {
const styles = getStyles()
const vars: Record<string, string> = {}
Object.entries(styles).forEach(([key, value]) => {
if (typeof value === 'string' || typeof value === 'number') {
const varName = `--device-${key.replace(/([A-Z])/g, '-$1').toLowerCase()}`
vars[varName] = String(value)
}
})
return vars
}
// 应用CSS变量到元素
const applyCSSVariables = (element: HTMLElement) => {
const vars = getCSSVariables()
Object.entries(vars).forEach(([key, value]) => {
element.style.setProperty(key, value)
})
}
return {
deviceInfo,
deviceClasses,
getStyles,
getCSSVariables,
applyCSSVariables,
}
}
/**
* 实验页面的设备适配
*/
export function useExperimentDeviceAdapter() {
const { deviceInfo, getStyles, applyCSSVariables } = useDeviceStyles()
// 实验页面特定的设备适配
const getExperimentStyles = () => {
const baseStyles = getStyles()
const { type, screenWidth, isTouchDevice } = deviceInfo.value
const experimentStyles = {
...baseStyles,
// 实验字段样式
fieldPadding: isTouchDevice ? '14px' : '10px',
fieldMargin: type === DeviceType.MOBILE ? '8px 0' : '12px 0',
fieldBorderRadius: type === DeviceType.MOBILE ? '8px' : '12px',
// 计算区域样式
areaPadding: type === DeviceType.MOBILE ? '16px' : '20px',
areaMargin: type === DeviceType.MOBILE ? '12px 0' : '16px 0',
resultFontSize: type === DeviceType.MOBILE ? '1.2rem' : '1.5rem',
// 按钮样式
buttonPadding: isTouchDevice ? '14px 28px' : '10px 24px',
buttonFontSize: type === DeviceType.MOBILE ? '1rem' : '1.1rem',
// 布局调整
containerGap: type === DeviceType.MOBILE ? '16px' : '24px',
sectionSpacing: type === DeviceType.MOBILE ? '20px' : '32px',
// 响应式列数
gridColumns: Math.min(
type === DeviceType.MOBILE ? 1 : type === DeviceType.TABLET ? 2 : 3,
Math.floor(screenWidth / 300),
),
}
return experimentStyles
}
// 应用到实验页面
const applyToExperimentPage = (element: HTMLElement) => {
applyCSSVariables(element)
// 添加实验特定的设备类
const { type } = deviceInfo.value
element.classList.add(`experiment-${type}`)
if (deviceInfo.value.isTouchDevice) {
element.classList.add('experiment-touch')
}
}
return {
deviceInfo,
getExperimentStyles,
applyToExperimentPage,
}
}

查看文件

@ -0,0 +1,150 @@
import { ref, computed, onMounted, onBeforeUnmount, type Ref } from 'vue'
const INTERACTIVE_SELECTOR = 'button, input, textarea, select, a, [role="button"]'
function isInteractiveTarget(el: EventTarget | null): boolean {
if (!el || !(el instanceof HTMLElement)) return false
return el.closest(INTERACTIVE_SELECTOR) !== null
}
export function useDraggable(
targetRef: Ref<HTMLElement | null>,
options?: {
initialX?: number
initialY?: number
handleSelector?: string
boundary?: 'window' | 'parent'
disabled?: Ref<boolean>
},
) {
const x = ref(options?.initialX ?? 0)
const y = ref(options?.initialY ?? 0)
const isDragging = ref(false)
let startX = 0
let startY = 0
const style = computed(() => ({
position: 'fixed' as const,
left: `${x.value}px`,
top: `${y.value}px`,
}))
const onPointerDown = (e: PointerEvent) => {
if (options?.disabled?.value) return
const el = targetRef.value
if (!el) return
if (isInteractiveTarget(e.target)) return
if (options?.handleSelector) {
const target = e.target as HTMLElement
const handle = target.closest(options.handleSelector)
if (!handle || !el.contains(handle)) return
}
isDragging.value = true
startX = e.clientX - x.value
startY = e.clientY - y.value
el.setPointerCapture(e.pointerId)
}
const onPointerMove = (e: PointerEvent) => {
if (!isDragging.value || !targetRef.value) return
const el = targetRef.value
let newX = e.clientX - startX
let newY = e.clientY - startY
if (options?.boundary === 'window') {
const rect = el.getBoundingClientRect()
newX = Math.max(0, Math.min(newX, window.innerWidth - rect.width))
newY = Math.max(0, Math.min(newY, window.innerHeight - rect.height))
}
x.value = newX
y.value = newY
}
const onPointerUp = () => {
isDragging.value = false
}
onMounted(() => {
document.addEventListener('pointermove', onPointerMove)
document.addEventListener('pointerup', onPointerUp)
})
onBeforeUnmount(() => {
document.removeEventListener('pointermove', onPointerMove)
document.removeEventListener('pointerup', onPointerUp)
})
return { x, y, isDragging, style, onPointerDown }
}
export function useDraggableTrigger(options?: {
initialX?: number
initialY?: number
}) {
const elRef = ref<HTMLElement | null>(null)
const savedX = ref(options?.initialX ?? 0)
const savedY = ref(options?.initialY ?? 0)
const isDragging = ref(false)
const hasMoved = ref(false)
let startX = 0
let startY = 0
let origX = 0
let origY = 0
const onPointerDown = (e: PointerEvent) => {
const el = elRef.value
if (!el) return
e.preventDefault()
isDragging.value = true
hasMoved.value = false
origX = savedX.value
origY = savedY.value
startX = e.clientX - savedX.value
startY = e.clientY - savedY.value
el.setPointerCapture(e.pointerId)
}
const onPointerMove = (e: PointerEvent) => {
if (!isDragging.value || !elRef.value) return
const newX = e.clientX - startX
const newY = e.clientY - startY
if (Math.abs(newX - origX) > 3 || Math.abs(newY - origY) > 3) {
hasMoved.value = true
}
savedX.value = newX
savedY.value = newY
}
const onPointerUp = () => {
isDragging.value = false
}
onMounted(() => {
document.addEventListener('pointermove', onPointerMove)
document.addEventListener('pointerup', onPointerUp)
})
onBeforeUnmount(() => {
document.removeEventListener('pointermove', onPointerMove)
document.removeEventListener('pointerup', onPointerUp)
})
const style = computed(() => ({
position: 'fixed' as const,
left: `${savedX.value}px`,
top: `${savedY.value}px`,
cursor: isDragging.value ? 'grabbing' : 'grab',
userSelect: 'none' as const,
}))
return { elRef, style, isDragging, hasMoved, onPointerDown }
}

14
frontend/src/helper.ts 普通文件
查看文件

@ -0,0 +1,14 @@
import type { ExperienceSets } from './types/experience'
export const URLQuery = new Map(new URLSearchParams(window.location.search))
export const ExperienceLoader = (): Promise<ExperienceSets> => {
const provider = URLQuery.get('exp_provider')
if (provider) {
return fetch(decodeURIComponent(provider))
.then((res) => res.json())
.catch(() => import('@/assets/experiences.json').then((m) => m.default))
} else {
return import('@/assets/experiences.json').then((m) => m.default)
}
}

12
frontend/src/main.ts 普通文件
查看文件

@ -0,0 +1,12 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')

查看文件

@ -0,0 +1,317 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { chatOnce, extractJsonBlock, safeParseJson } from '@/utils/aiClient'
import { renderMarkdownWithLatex } from '@/utils/markdown'
const props = defineProps({
summaryData: {
type: Object,
required: true,
},
})
const aiAnalysis = ref('AI正在分析您的错题...')
const aiHtml = ref('')
const aiLoading = ref(false)
const aiError = ref('')
let lastSignature = ''
const choiceLabel = (index: number) => String.fromCharCode(65 + index)
const formatOptions = (choices?: string[]) => {
if (!choices || choices.length === 0) return ''
return choices.map((choice, index) => `${choiceLabel(index)}. ${choice}`).join(' ')
}
const formatAnswer = (question: any, answer: unknown) => {
if (!question) return String(answer ?? '')
if (question.type === '单选题') {
const idx = Number(answer)
if (!Number.isNaN(idx)) {
return `${choiceLabel(idx)}${question.choices?.[idx] ? ` (${question.choices[idx]})` : ''}`
}
}
if (question.type === '多选题') {
const indices = Array.isArray(answer) ? answer : []
return indices
.map((idx: number) => `${choiceLabel(idx)}${question.choices?.[idx] ? ` (${question.choices[idx]})` : ''}`)
.join('、')
}
if (question.type === '填空题') {
return Array.isArray(answer) ? answer.join(' / ') : String(answer ?? '')
}
return String(answer ?? '')
}
const buildWrongQuestionText = (wrongQuestions: { index: number; question?: any; userAnswer: unknown; correctAnswer: unknown }[]) => {
if (!wrongQuestions.length) return ''
return wrongQuestions
.map((item, index) => {
const question = item.question
const options = formatOptions(question?.choices)
const userAnswer = formatAnswer(question, item.userAnswer)
const correctAnswer = formatAnswer(question, item.correctAnswer)
return [
`题目 ${index + 1}: ${question?.question || ''}`,
options ? `选项: ${options}` : '',
`你的答案: ${userAnswer}`,
`正确答案: ${correctAnswer}`,
]
.filter(Boolean)
.join('\n')
})
.join('\n\n')
}
const formatGraderResponse = (rawText: string) => {
const jsonBlock = extractJsonBlock(rawText)
if (jsonBlock) {
const parsed = safeParseJson<Record<string, any>>(jsonBlock)
if (parsed.value) {
const payload = parsed.value
const feedback = payload.feedback?.feedback_content || {}
const sections: string[] = []
if (payload.feedback?.correctness_feedback) {
sections.push(`**总体判断**:${payload.feedback.correctness_feedback}`)
}
if (feedback.diagnosis) {
sections.push(`**诊断**:${feedback.diagnosis}`)
}
if (feedback.error_explanation) {
const explanation =
typeof feedback.error_explanation === 'string'
? feedback.error_explanation
: JSON.stringify(feedback.error_explanation)
sections.push(`**原因分析**:${explanation}`)
}
if (Array.isArray(feedback.knowledge_points_evaluated) && feedback.knowledge_points_evaluated.length > 0) {
const points = feedback.knowledge_points_evaluated.map((item: string) => `- ${item}`).join('\n')
sections.push(`**涉及知识点**\n${points}`)
}
if (Array.isArray(feedback.improvement_suggestions) && feedback.improvement_suggestions.length > 0) {
const suggestions = feedback.improvement_suggestions.map((item: string) => `- ${item}`).join('\n')
sections.push(`**改进建议**\n${suggestions}`)
}
if (Array.isArray(feedback.extension_questions) && feedback.extension_questions.length > 0) {
const questions = feedback.extension_questions.map((item: string) => `- ${item}`).join('\n')
sections.push(`**拓展问题**\n${questions}`)
}
const markdown = sections.join('\n\n') || rawText
return renderMarkdownWithLatex(markdown)
}
}
return renderMarkdownWithLatex(rawText)
}
const requestAnalysis = async () => {
if (!props.summaryData) return
const wrongQuestions = props.summaryData.wrongQuestions || []
if (wrongQuestions.length === 0) {
aiAnalysis.value = '没有错题,表现很棒!继续保持。'
aiHtml.value = renderMarkdownWithLatex(aiAnalysis.value)
return
}
const signature = JSON.stringify(wrongQuestions.map((item: any) => ({
index: item.index,
userAnswer: item.userAnswer,
correctAnswer: item.correctAnswer,
})))
if (signature === lastSignature) return
lastSignature = signature
aiLoading.value = true
aiError.value = ''
aiAnalysis.value = 'AI正在分析您的错题...'
aiHtml.value = renderMarkdownWithLatex(aiAnalysis.value)
const wrongText = buildWrongQuestionText(wrongQuestions)
const userContent = [
'请用中文、语气严谨但鼓励的方式输出错题综合评价。',
'请按单题评估的JSON结构输出,question_id填"wrong-set",question_type填"summary"。',
'question_text包含错题列表,standard_answer填"见每题正确答案",student_answer填"见每题作答"。',
'',
'错题列表:',
wrongText,
].join('\n')
try {
const rawText = await chatOnce({
teacherType: 'grader',
messages: [{ role: 'user', content: userContent }],
stream: false,
})
aiHtml.value = formatGraderResponse(rawText)
aiAnalysis.value = rawText
} catch (error) {
aiError.value = error instanceof Error ? error.message : 'AI分析失败'
aiAnalysis.value = 'AI分析失败,请稍后重试。'
aiHtml.value = renderMarkdownWithLatex(aiAnalysis.value)
} finally {
aiLoading.value = false
}
}
watch(
() => props.summaryData,
() => {
requestAnalysis()
},
{ immediate: true },
)
</script>
<template>
<div class="summary-page">
<h1>答题总结</h1>
<div v-if="summaryData" class="summary-content">
<div class="score-card">
<h2>本次得分</h2>
<p class="score">{{ summaryData.score }}</p>
</div>
<div class="ai-analysis">
<h2>AI 错题分析</h2>
<p v-if="aiError" class="ai-error">{{ aiError }}</p>
<div v-if="aiHtml" v-html="aiHtml"></div>
<p v-else>{{ aiAnalysis }}</p>
<p v-if="aiLoading" class="ai-loading">AI 正在生成,请稍候...</p>
</div>
<div class="wrong-questions-section">
<h2>错题回顾</h2>
<div v-for="(item, index) in summaryData.wrongQuestions" :key="index" class="wrong-question">
<p><strong>题目 {{ item.index + 1 }}:</strong> {{ item.question.question }}</p>
<p><strong>你的答案:</strong> <span class="user-answer">{{ item.userAnswer }}</span></p>
<p><strong>正确答案:</strong> <span class="correct-answer">{{ item.correctAnswer }}</span></p>
</div>
</div>
</div>
<div v-else>
<p>没有找到答题数据。</p>
</div>
</div>
</template>
<style scoped>
.summary-page {
padding: 2rem;
background-color: #f4f6f8;
min-height: 100%;
}
h1 {
text-align: center;
margin-bottom: 2rem;
font-size: 2rem;
color: #333;
}
.summary-content {
max-width: 800px;
margin: 0 auto;
background: #fff;
padding: 2rem;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0,0,0,0.08);
}
.score-card {
text-align: center;
padding: 2rem;
background: linear-gradient(135deg, #007bff, #0056b3);
color: white;
border-radius: 12px;
margin-bottom: 2rem;
}
.score-card h2 {
font-size: 1.5rem;
margin-bottom: 1rem;
}
.score-card .score {
font-size: 3rem;
font-weight: bold;
}
.ai-analysis {
background-color: #e6f7ff;
border-left: 4px solid #007bff;
padding: 1.5rem;
margin-bottom: 2rem;
border-radius: 8px;
}
.ai-error {
color: #c71d1d;
font-weight: 600;
margin-bottom: 0.75rem;
}
.ai-loading {
margin-top: 0.75rem;
font-size: 0.95rem;
color: #555;
}
.ai-analysis h2 {
font-size: 1.3rem;
margin-bottom: 1rem;
color: #0056b3;
}
.ai-analysis p {
font-size: 1rem;
line-height: 1.6;
}
.wrong-questions-section h2 {
font-size: 1.3rem;
margin-bottom: 1.5rem;
padding-bottom: 1rem;
border-bottom: 1px solid #eee;
}
.wrong-question {
margin-bottom: 1.5rem;
padding: 1.5rem;
border: 1px solid #e0e0e0;
border-radius: 8px;
background: #fafafa;
}
.wrong-question p {
margin-bottom: 0.8rem;
line-height: 1.6;
}
.wrong-question strong {
color: #333;
}
.user-answer {
color: #f5222d;
}
.correct-answer {
color: #52c41a;
}
</style>

查看文件

@ -0,0 +1,184 @@
<script setup lang="ts">
import { ref, type Ref, h, type VNode, type Component, watch, onMounted } from 'vue'
import { useStudentStore } from '@/stores/student'
import QuizPage from './QuizPage.vue'
import LearnPage from './LearnPage.vue'
import ExperimentPage from './ExperimentPage.vue'
import type { ExperienceType } from '@/types/experience'
import { URLQuery, ExperienceLoader } from '@/helper'
import router from '@/router'
const TypeMapping: Map<string, Component> = new Map([
['quiz', QuizPage as Component],
['learn', LearnPage as Component],
['experiment', ExperimentPage as Component],
])
const defaultExperience = {
title: '默认实验',
id: 'cn.jamaccao.phyexp.default',
stage: [],
}
const experiencesMap = ref<Map<string, ExperienceType>>(new Map())
const Experience = ref<ExperienceType>(defaultExperience)
const loaded = ref(false)
const ExpID = (() => {
return URLQuery.get('expid')
? (URLQuery.get('expid') as string)
: 'cn.edu.muc.lxy.phyexp.voicespeed'
})()
const { StudentInfo } = useStudentStore()
const Process = ref(0)
const VPages: VNode[] = []
const View: Ref<VNode | undefined> = ref(undefined)
const StageStatus: { score: number; comment: string }[] = []
watch(Process, (n) => {
View.value = VPages[n]
})
const SwitchStage = (index: number) => {
if ((window as any).__DEBUG_SKIP_STAGE__ || Experience.value.skipable) {
Process.value = index
}
}
const nextPageFunction = (score: number = 0, comment: string = '') => {
StageStatus[Process.value] = { score, comment }
console.log(StageStatus)
Process.value += 1
}
const LoadExperience = (exp: ExperienceType) => {
// 清空原有页面
VPages.length = 0
exp.stage.forEach((stage, index) => {
VPages[index] = h(
TypeMapping.has(stage.type) ? (TypeMapping.get(stage.type) as Component) : LearnPage,
{
...stage.resource,
...{
NextPage: nextPageFunction,
},
},
)
})
// 重置视图
View.value = VPages[Process.value] || VPages[0]
}
// 加载实验数据
const loadData = async () => {
try {
// 从远程获取实验数据合集,exp_provider定义URL
const data = await ExperienceLoader()
const map = new Map<string, ExperienceType>()
if (data && data.experiences) {
Object.entries(data.experiences).forEach(([, value]) => {
map.set(value.id, value)
})
}
experiencesMap.value = map
let currentExp = experiencesMap.value.get(ExpID)
if (!currentExp) {
currentExp = defaultExperience
}
Experience.value = currentExp
LoadExperience(currentExp)
loaded.value = true
} catch (error) {
console.error('Failed to load experiences:', error)
Experience.value = defaultExperience
LoadExperience(defaultExperience)
loaded.value = true
}
}
onMounted(() => {
loadData()
})
</script>
<template>
<div id="frame-container">
<div id="TopBar">
<div class="topbar-item" id="student-info">
姓名:<a @click="router.push('/login')">{{ StudentInfo.Name }}</a
><br />学号:{{ StudentInfo.SID }}
</div>
<div class="topbar-item" id="experience-title">
<a @click="router.push('/select')">{{ Experience.title }}</a>
</div>
<div class="topbar-item" id="experience-stage">
<div
v-for="(V, index) in Experience.stage"
:active="index == Process"
@click="SwitchStage(index)"
class="stage-items"
>
{{ V.name }}
</div>
</div>
</div>
<hr style="color: #000; width: 100%; margin: 0" />
<div id="main-container" v-if="loaded">
<KeepAlive>
<component :is="View" :key="Process" />
</KeepAlive>
</div>
</div>
</template>
<style scoped>
#TopBar {
display: grid;
grid-template-columns: repeat(7, 1fr);
flex-shrink: 0; /* 固定高度,不被压缩 */
padding: 1rem;
}
#experience-stage {
grid-column: 7 / 8;
text-align: right;
}
#main-container {
flex: 1; /* 占据剩余所有空间 */
padding: 1rem;
overflow-y: auto; /* 如果内容过多,内部滚动,不影响整体布局 */
}
#frame-container {
display: flex;
flex-direction: column;
height: 100vh; /* 直接占满视口高度 */
overflow: hidden; /* 防止内容溢出,让内部滚动 */
}
#student-info {
grid-column: 1 / 1;
}
#experience-title {
grid-column: 2 / 7;
font-size: 2rem;
text-align: center;
}
.stage-items[active='true'] {
color: red;
}
.stage-items {
background-color: #3b97ff;
border: #3b97ff solid 2px;
border-radius: 5px;
display: inline-block;
padding: 0.1rem;
margin: 0.4rem;
color: white;
}
</style>

查看文件

@ -0,0 +1,23 @@
<script lang="ts">
import { ExperienceLoader } from '@/helper'
import { defineComponent, ref, type Ref } from 'vue'
import { type ExperienceMap } from '@/types/experience'
export default defineComponent({
setup() {
const experiences: Ref<ExperienceMap> = ref({})
ExperienceLoader().then((v) => {
experiences.value = v.experiences
})
return {
experiences,
}
},
})
</script>
<template>
<span v-for="(exp, name) in experiences">
{{ name }}
<img :src="exp.image" />
</span>
</template>

查看文件

@ -0,0 +1,530 @@
<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import ExperimentForm from '@/components/experiment/ExperimentForm.vue'
import ExperimentPrintTable from '@/components/experiment/ExperimentPrintTable.vue'
import AIChatSidebar from '@/components/AIChatSidebar.vue'
import type { ExperimentGridConfig, GridSheet } from '@/types/experiment'
import { useExperimentDeviceAdapter } from '@/composables/useDevice'
import { useExperimentStore } from '@/stores/experiment'
import { storeToRefs } from 'pinia'
import { exportElementToPdf } from '@/utils/pdfExport'
import { useDraggableTrigger } from '@/composables/useDraggable'
const props = defineProps<{
provider?: string
validation_url?: string
NextPage?: Function
}>()
const emit = defineEmits<{
complete: [score: number, comment: string]
}>()
const loading = ref(true)
const error = ref<string | null>(null)
const formConfig = ref<ExperimentGridConfig | null>(null)
const allValidated = ref(false)
const exporting = ref(false)
const exportError = ref('')
const isChatOpen = ref(false)
const cellInspectMode = ref(false)
const selectedCellContext = ref<string>('')
const { elRef: triggerRef, style: triggerStyle, hasMoved, onPointerDown } = useDraggableTrigger({
initialX: window.innerWidth - 130,
initialY: window.innerHeight - 70,
})
const toggleChat = (e?: MouseEvent) => {
if (e && hasMoved.value) {
hasMoved.value = false
return
}
isChatOpen.value = !isChatOpen.value
}
const toggleCellInspect = () => {
cellInspectMode.value = !cellInspectMode.value
if (!cellInspectMode.value) {
selectedCellContext.value = ''
}
if (!isChatOpen.value) {
isChatOpen.value = true
}
}
const handleCellInspect = (info: { sheetTitle?: string; cellType: string; label: string; value: any; unit?: string; validation?: any }) => {
const parts: string[] = []
if (info.sheetTitle) parts.push(`【${info.sheetTitle}】`)
parts.push(`单元格类型: ${info.cellType}`)
parts.push(`标识: ${info.label}`)
if (info.value != null) parts.push(`当前值: ${info.value}`)
if (info.unit) parts.push(`单位: ${info.unit}`)
if (info.validation) {
parts.push(`校验规则: ${JSON.stringify(info.validation)}`)
}
selectedCellContext.value = parts.join('\n')
}
const clearCellContext = () => {
selectedCellContext.value = ''
}
const deviceAdapter = useExperimentDeviceAdapter()
const deviceInfo = deviceAdapter.deviceInfo
const experimentStyles = computed(() => deviceAdapter.getExperimentStyles())
const experimentStore = useExperimentStore()
const { data: fieldData, areaResults } = storeToRefs(experimentStore)
const pageStyleVars = computed(() => ({
'--experiment-page-padding': experimentStyles.value.areaPadding,
'--experiment-content-padding': experimentStyles.value.areaPadding,
'--experiment-gap': experimentStyles.value.containerGap,
'--continue-button-padding': experimentStyles.value.buttonPadding,
'--continue-button-font-size': experimentStyles.value.buttonFontSize,
}))
const deviceLabel = computed(() => {
switch (deviceInfo.value.type) {
case 'mobile': return '移动端'
case 'tablet': return '平板端'
case 'desktop': return '桌面端'
default: return '未知设备'
}
})
const continueButtonText = computed(() => (allValidated.value ? '继续' : '请完成所有字段验证'))
const getSheetById = (sheetId: string): GridSheet | null => {
return formConfig.value?.sheets.find((s) => s.id === sheetId) || null
}
const table1Sheet = computed(() => getSheetById('table1_frequency'))
const table2Sheet = computed(() => getSheetById('table2_standing'))
const table3Sheet = computed(() => getSheetById('table3_phase'))
const table4Sheet = computed(() => getSheetById('table4_timediff'))
const canExport = computed(() => {
return Boolean(table1Sheet.value && table2Sheet.value && table3Sheet.value && table4Sheet.value)
})
const sheetTable2 = ref<HTMLElement | null>(null)
const sheetTable3 = ref<HTMLElement | null>(null)
const sheetTable4 = ref<HTMLElement | null>(null)
const exportLabel = computed(() => (exporting.value ? '导出中...' : '导出PDF'))
const loadFormConfig = async () => {
if (!props.provider) {
error.value = '未提供实验配置URL'
loading.value = false
return
}
try {
loading.value = true
error.value = null
const response = await fetch(props.provider)
if (!response.ok) throw new Error(`加载配置失败: ${response.status}`)
const config = await response.json()
if (!config.title || !Array.isArray(config.sheets)) {
throw new Error('无效的实验配置格式')
}
formConfig.value = config
} catch (err) {
error.value = err instanceof Error ? err.message : '加载配置失败'
console.error('加载实验配置失败:', err)
} finally {
loading.value = false
}
}
const handleFieldUpdate = (fieldId: string, value: any) => {
console.log('字段更新:', fieldId, value)
}
const handleFieldValidate = (fieldId: string) => {
console.log('字段验证:', fieldId)
}
const handleAllValidated = () => {
console.log('所有字段已验证')
allValidated.value = true
}
const handleContinue = () => {
if (props.NextPage) {
props.NextPage(100, '实验数据记录完成')
} else {
emit('complete', 100, '实验数据记录完成')
}
}
const handleExport = async () => {
if (!canExport.value || exporting.value) return
exporting.value = true
exportError.value = ''
try {
await nextTick()
if (sheetTable2.value) {
await exportElementToPdf(sheetTable2.value, '超声波声速测量_表1+表2.pdf')
}
if (sheetTable3.value) {
await exportElementToPdf(sheetTable3.value, '超声波声速测量_表1+表3.pdf')
}
if (sheetTable4.value) {
await exportElementToPdf(sheetTable4.value, '超声波声速测量_表1+表4.pdf')
}
} catch (err) {
exportError.value = err instanceof Error ? err.message : '导出失败'
} finally {
exporting.value = false
}
}
onMounted(() => {
loadFormConfig()
const pageElement = document.querySelector('.experiment-page') as HTMLElement
if (pageElement) {
deviceAdapter.applyToExperimentPage(pageElement)
}
})
watch(
() => props.provider,
() => {
if (props.provider) {
loadFormConfig()
}
},
)
</script>
<template>
<div class="experiment-page">
<div v-if="loading" class="loading-container">
<div class="loading-spinner"></div>
<p>加载实验配置中...</p>
</div>
<div v-else-if="error" class="error-container">
<div class="error-icon">⚠️</div>
<h3>加载失败</h3>
<p>{{ error }}</p>
<button @click="loadFormConfig" class="retry-button">重试</button>
</div>
<div v-else-if="formConfig" class="experiment-content" :class="deviceInfo.type" :style="pageStyleVars">
<div class="a4-paper">
<div class="device-info" v-if="deviceInfo.type !== 'desktop'">
<span class="device-badge">{{ deviceLabel }}</span>
<span class="screen-info">{{ deviceInfo.screenWidth }}×{{ deviceInfo.screenHeight }}</span>
</div>
<ExperimentForm
:config="formConfig"
:validation-url="validation_url"
:cell-inspect-mode="cellInspectMode"
@field-update="handleFieldUpdate"
@field-validate="handleFieldValidate"
@all-validated="handleAllValidated"
@cell-inspect="handleCellInspect"
/>
<div class="action-bar">
<button
@click="handleContinue"
:disabled="!allValidated"
class="continue-button"
:class="{ disabled: !allValidated }"
>
{{ continueButtonText }}
</button>
<button
v-if="canExport"
class="export-button"
:disabled="exporting"
@click="handleExport"
>
{{ exportLabel }}
</button>
<span v-if="exportError" class="export-error">{{ exportError }}</span>
</div>
</div>
</div>
<div v-else class="no-config">
<p>未找到实验配置</p>
</div>
<div v-if="canExport" class="pdf-sheets" aria-hidden="true">
<div ref="sheetTable2" class="pdf-sheet">
<div class="pdf-header">
<div class="pdf-title">超声波声速测量实验(记录表)</div>
<div class="pdf-subtitle">表1 + 表2 驻波法</div>
</div>
<ExperimentPrintTable
v-if="table1Sheet"
:sheet="table1Sheet"
:field-data="fieldData"
:area-results="areaResults"
/>
<ExperimentPrintTable
v-if="table2Sheet"
:sheet="table2Sheet"
:field-data="fieldData"
:area-results="areaResults"
/>
</div>
<div ref="sheetTable3" class="pdf-sheet">
<div class="pdf-header">
<div class="pdf-title">超声波声速测量实验(记录表)</div>
<div class="pdf-subtitle">表1 + 表3 相位法</div>
</div>
<ExperimentPrintTable
v-if="table1Sheet"
:sheet="table1Sheet"
:field-data="fieldData"
:area-results="areaResults"
/>
<ExperimentPrintTable
v-if="table3Sheet"
:sheet="table3Sheet"
:field-data="fieldData"
:area-results="areaResults"
/>
</div>
<div ref="sheetTable4" class="pdf-sheet">
<div class="pdf-header">
<div class="pdf-title">超声波声速测量实验(记录表)</div>
<div class="pdf-subtitle">表1 + 表4 时差法</div>
</div>
<ExperimentPrintTable
v-if="table1Sheet"
:sheet="table1Sheet"
:field-data="fieldData"
:area-results="areaResults"
/>
<ExperimentPrintTable
v-if="table4Sheet"
:sheet="table4Sheet"
:field-data="fieldData"
:area-results="areaResults"
/>
</div>
</div>
<div
v-if="!isChatOpen"
ref="triggerRef"
class="ai-chat-trigger"
:style="triggerStyle"
@pointerdown="onPointerDown"
@click="toggleChat"
>
<span class="icon">🤖</span>
<span class="text">AI 助教</span>
</div>
<AIChatSidebar
:is-open="isChatOpen"
:floating="true"
:cell-context="selectedCellContext"
:inspect-active="cellInspectMode"
:on-toggle-inspect="toggleCellInspect"
:on-clear-cell-context="clearCellContext"
@close="isChatOpen = false"
/>
</div>
</template>
<style scoped>
.experiment-page {
min-height: 100%;
padding: 1.5rem;
display: flex;
flex-direction: column;
align-items: center;
background-color: #e8ecf1;
box-sizing: border-box;
}
.experiment-content {
width: 100%;
max-width: 1100px;
}
.a4-paper {
background: #fff;
box-shadow: 0 2px 8px rgba(0,0,0,0.08), 0 8px 32px rgba(0,0,0,0.06);
border-radius: 2px;
padding: 2rem 2rem;
min-height: 100%;
box-sizing: border-box;
}
.loading-container, .error-container, .no-config {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 3rem;
text-align: center;
background-color: #fff;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
width: 100%;
max-width: 600px;
margin: auto;
}
.loading-spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #007bff;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 1rem;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.error-icon { font-size: 3rem; margin-bottom: 1rem; color: #dc3545; }
.retry-button {
padding: 0.8rem 1.5rem;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
.retry-button:hover { background-color: #0056b3; }
.device-info {
display: flex;
align-items: center;
justify-content: center;
gap: 1rem;
margin-bottom: 1.5rem;
padding: 0.5rem;
background: #f8f9fa;
border-radius: 4px;
font-size: 0.85rem;
color: #555;
}
.device-badge {
padding: 0.3rem 0.6rem;
background: #007bff;
color: white;
border-radius: 4px;
font-weight: 600;
font-size: 0.8rem;
}
.action-bar {
margin-top: 2.5rem;
padding-top: 1.5rem;
border-top: 1px solid #dee2e6;
display: flex;
justify-content: center;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.continue-button {
padding: 0.75rem 2.5rem;
font-size: 1rem;
font-weight: 600;
background: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: all 0.2s ease;
}
.continue-button:disabled {
background: #adb5bd;
cursor: not-allowed;
}
.continue-button:hover:not(:disabled) { background: #218838; }
.export-button {
padding: 0.6rem 1.25rem;
border-radius: 4px;
border: 1px solid #0b5ed7;
background-color: #f0f6ff;
color: #0b5ed7;
font-weight: 600;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.2s ease;
}
.export-button:hover:not(:disabled) { background-color: #e3efff; }
.export-button:disabled { cursor: not-allowed; opacity: 0.6; }
.export-error { color: #c71d1d; font-size: 0.9rem; }
.pdf-sheets {
position: fixed;
left: -100000px;
top: 0;
width: 210mm;
pointer-events: none;
}
.pdf-sheet {
width: 210mm;
min-height: 297mm;
padding: 10mm 10mm 12mm;
box-sizing: border-box;
background: #ffffff;
color: #111;
display: flex;
flex-direction: column;
gap: 12px;
}
.pdf-header {
text-align: center;
margin-bottom: 4px;
}
.pdf-title { font-size: 16px; font-weight: 700; }
.pdf-subtitle { font-size: 13px; color: #333; margin-top: 4px; }
.ai-chat-trigger {
background-color: #007bff;
color: white;
border-radius: 50px;
padding: 1rem;
cursor: grab;
display: flex;
align-items: center;
box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
transition: box-shadow 0.3s ease, transform 0.3s ease;
z-index: 1000;
user-select: none;
}
.ai-chat-trigger:hover { box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4); }
.ai-chat-trigger .icon { font-size: 1.5rem; margin-right: 0.5rem; }
.ai-chat-trigger .text { font-size: 1rem; font-weight: 600; }
</style>

查看文件

@ -0,0 +1,246 @@
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import AIChatSidebar from '@/components/AIChatSidebar.vue'
import { useDraggableTrigger } from '@/composables/useDraggable'
const props = defineProps<{
NextPage: Function
course: string
}>()
const isChatOpen = ref(false)
const videoSrc = '/videos/preview.mp4'
const prelearnContent = ref('')
const glossaryContent = ref('')
const { elRef, style: triggerStyle, hasMoved, onPointerDown } = useDraggableTrigger({
initialX: window.innerWidth - 130,
initialY: window.innerHeight - 70,
})
const toggleChat = (e?: MouseEvent) => {
if (e && hasMoved.value) {
hasMoved.value = false
return
}
isChatOpen.value = !isChatOpen.value
}
const truncateText = (text: string, maxLength: number) => {
if (text.length <= maxLength) return text
return `${text.slice(0, maxLength)}...`
}
const formatPrelearnContent = (data: any): string => {
if (!data || !Array.isArray(data.course)) return ''
const lines: string[] = []
if (data.meta?.title) {
lines.push(`预习资料: ${data.meta.title}`)
}
data.course.forEach((item: any, index: number) => {
if (!item || !item.type) return
if (item.type === 'text' && item.value) {
lines.push(item.value)
return
}
if (item.type === 'file') {
const name = item.name || `资料${index + 1}`
const url = item.URL ? `(${item.URL})` : ''
lines.push(`资料: ${name} ${url}`)
return
}
if (item.type === 'movie' && item.URL) {
lines.push(`视频: ${item.URL}`)
}
})
return lines.join('\n')
}
const loadPrelearn = async () => {
if (!props.course) {
prelearnContent.value = ''
return
}
try {
const response = await fetch(props.course)
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
const data = await response.json()
const formatted = formatPrelearnContent(data)
prelearnContent.value = truncateText(formatted, 2000)
} catch (error) {
console.warn('加载预习资料失败', error)
prelearnContent.value = ''
}
}
const loadGlossary = async () => {
try {
const response = await fetch('/physics-glossary.md')
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
const text = await response.text()
glossaryContent.value = truncateText(text, 2000)
} catch (error) {
console.warn('加载术语表失败', error)
glossaryContent.value = ''
}
}
onMounted(() => {
loadPrelearn()
loadGlossary()
})
watch(
() => props.course,
() => {
loadPrelearn()
},
)
</script>
<template>
<div class="learn-page">
<div class="video-container">
<h2>实验预习视频</h2>
<video controls>
<source :src="videoSrc" type="video/mp4" />
您的浏览器不支持视频播放。
</video>
<p class="video-placeholder">
请将 <code>public/videos/preview.mp4</code> 替换为您的视频文件,或在 <code>videoSrc</code> 中配置视频URL。
</p>
</div>
<div class="main-content">
<button class="continue-button" @click="NextPage(100, '1')">完成预习,进入下一阶段</button>
</div>
<div
v-if="!isChatOpen"
ref="elRef"
class="ai-chat-trigger"
:style="triggerStyle"
@pointerdown="onPointerDown"
@click="toggleChat"
>
<span class="icon">🤖</span>
<span class="text">AI 助教</span>
</div>
<AIChatSidebar
:is-open="isChatOpen"
:course-content="prelearnContent"
:glossary-content="glossaryContent"
:floating="true"
@close="isChatOpen = false"
/>
</div>
</template>
<style scoped>
.learn-page {
display: flex;
flex-direction: column;
align-items: center;
padding: 2rem;
background-color: #f4f6f8;
min-height: 100%;
box-sizing: border-box;
}
.video-container {
width: 100%;
max-width: 800px;
background-color: white;
border-radius: 12px;
padding: 2rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
margin-bottom: 2rem;
}
.video-container h2 {
font-size: 1.5rem;
font-weight: 600;
color: #333;
margin-bottom: 1.5rem;
text-align: center;
}
video {
width: 100%;
border-radius: 8px;
}
.video-placeholder {
margin-top: 1rem;
text-align: center;
font-size: 0.9rem;
color: #888;
background-color: #f0f0f0;
padding: 0.5rem;
border-radius: 4px;
}
.main-content {
width: 100%;
max-width: 800px;
text-align: center;
}
.continue-button {
padding: 0.8rem 2rem;
font-size: 1rem;
font-weight: 600;
background-color: #007bff;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
}
.continue-button:hover {
background-color: #0056b3;
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(0, 123, 255, 0.2);
}
.ai-chat-trigger {
background-color: #007bff;
color: white;
border-radius: 50px;
padding: 1rem;
cursor: grab;
display: flex;
align-items: center;
box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
transition: box-shadow 0.3s ease, transform 0.3s ease;
z-index: 1000;
user-select: none;
}
.ai-chat-trigger:hover {
box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4);
}
.ai-chat-trigger .icon {
font-size: 1.5rem;
margin-right: 0.5rem;
}
.ai-chat-trigger .text {
font-size: 1rem;
font-weight: 600;
}
</style>

查看文件

@ -0,0 +1,274 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import QuestionTable from '@/components/QuestionTable.vue'
import type { QuestionFileSchema, QuestionType } from '@/types/question'
import DefaultQuestion from '@/assets/VoiceSpeed/question.json'
import AnswerSummary from '@/pages/AnswerSummary.vue'
type AnswerStatus = 'right' | 'wrong' | 'part' | 'blank' | 'waiting'
type WrongQuestionItem = {
index: number
question: QuestionType
userAnswer: unknown
correctAnswer: unknown
status: AnswerStatus
}
type SummaryData = {
score: number
wrongQuestions: WrongQuestionItem[]
}
const props = defineProps<{
question?: string
NextPage?: Function
}>()
const Questions = ref<QuestionType[]>([])
const Statuses = ref<AnswerStatus[]>([])
const submitLabel = ref('提交')
const score = ref(0)
const submitted = ref(false)
const summaryData = ref<SummaryData | null>(null)
const QuestionRefs = ref<InstanceType<typeof QuestionTable>[]>([])
const submit = () => {
if (submitted.value) {
if (props.NextPage) {
props.NextPage(score.value, '测验完成')
}
return
}
score.value = 0
const newStatuses: AnswerStatus[] = new Array(Questions.value.length).fill('blank')
const wrongQuestions: WrongQuestionItem[] = []
QuestionRefs.value.forEach((comp, index) => {
if (comp) {
const [compScore, status] = comp.calc()
score.value += compScore
newStatuses[index] = status
if (status !== 'right') {
const question = Questions.value[index]
if (!question) return
wrongQuestions.push({
index,
question,
userAnswer: comp.getAnswer(),
correctAnswer:
question.type === '简答题' ? '(待批改/无标准答案)' : (question.answer as unknown),
status,
})
}
}
})
Statuses.value = newStatuses
summaryData.value = { score: score.value, wrongQuestions }
submitted.value = true
submitLabel.value = '继续实验'
}
const answerAction = (index: number) => {
return () => {
if (!submitted.value) {
Statuses.value[index] = 'waiting'
}
}
}
const loadQuestions = async () => {
let questionObject: QuestionFileSchema = DefaultQuestion as QuestionFileSchema
if (props.question) {
try {
const res = await fetch(props.question)
if (!res.ok) {
throw new Error(`HTTP ${res.status}`)
}
questionObject = (await res.json()) as QuestionFileSchema
} catch (error) {
console.warn('加载远程题目失败,已回退本地题库', error)
}
}
Questions.value = questionObject.questions
Statuses.value = new Array(Questions.value.length).fill('blank')
}
onMounted(() => {
loadQuestions()
})
</script>
<template>
<div id="quiz-page">
<div v-if="!submitted">
<div id="test-container">
<div id="test-areas">
<QuestionTable
v-for="(k, i) in Questions"
:key="`question-${i}`"
:question="k"
:do-answer="answerAction(i)"
ref="QuestionRefs"
/>
</div>
<div id="status-area">
<h3 id="status-title">答题卡</h3>
<div id="status-grid">
<div
v-for="(s, i) in Statuses"
:key="`status-${i}`"
:status="s"
class="question-status"
>
{{ i + 1 }}
</div>
</div>
</div>
</div>
</div>
<AnswerSummary v-if="summaryData" :summaryData="summaryData" />
<div id="action-bar">
<button id="submit-btn" @click="submit">{{ submitLabel }}</button>
<label v-if="!submitted" id="score-display">得分: {{ score }}</label>
</div>
</div>
</template>
<style scoped>
#quiz-page {
padding: 2rem;
background-color: #f4f6f8;
min-height: 100%;
}
#test-container {
display: grid;
grid-template-columns: minmax(0, 1fr) 280px;
gap: 2rem;
align-items: flex-start;
}
#test-areas {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
#status-area {
position: sticky;
top: 2rem;
background: white;
border-radius: 12px;
padding: 1.5rem;
box-shadow: 0 4px 20px rgba(0,0,0,0.08);
}
#status-title {
font-size: 1.2rem;
font-weight: 600;
margin-bottom: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid #eee;
}
#status-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
gap: 0.75rem;
}
.question-status {
display: flex;
justify-content: center;
align-items: center;
height: 40px;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
border: 2px solid transparent;
}
.question-status:hover {
transform: translateY(-2px);
}
[status='blank'] {
background-color: #f0f0f0;
color: #888;
border-color: #e0e0e0;
}
[status='waiting'] {
background-color: #e6f7ff;
color: #007bff;
border-color: #91d5ff;
}
[status='right'] {
background-color: #f6ffed;
color: #52c41a;
border-color: #b7eb8f;
}
[status='wrong'] {
background-color: #fff1f0;
color: #f5222d;
border-color: #ffa39e;
}
[status='part'] {
background-color: #fffbe6;
color: #faad14;
border-color: #ffe58f;
}
#action-bar {
position: sticky;
bottom: 1rem;
max-width: 800px;
margin: 2rem auto 0;
display: flex;
align-items: center;
gap: 1.5rem;
padding: 1rem 1.5rem;
border-radius: 12px;
background-color: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(10px);
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
border: 1px solid #e0e0e0;
z-index: 10;
}
#submit-btn {
padding: 0.8rem 2rem;
font-size: 1rem;
font-weight: 600;
background-color: #007bff;
color: white;
}
#submit-btn:hover {
background-color: #0056b3;
}
#score-display {
font-size: 1.1rem;
font-weight: 600;
color: #333;
}
@media (max-width: 900px) {
#test-container {
grid-template-columns: 1fr;
}
#status-area {
position: static;
margin-top: 2rem;
}
}
</style>

查看文件

@ -0,0 +1,154 @@
<script lang="ts" setup>
import { ref } from 'vue'
import { useStudentStore } from '@/stores/student'
import router from '@/router'
const InputSID = ref(0)
const InputName = ref('')
const UserInfo = useStudentStore()
const TipsRef = ref('')
const DoLogin = async () => {
const [result, status] = await UserInfo.doLogin(InputSID.value, InputName.value)
if (result) {
router.push({
path: '/exp',
})
} else {
TipsRef.value = status ? (status as string) : '登录失败'
}
}
</script>
<template>
<div class="login-page">
<div class="login-container">
<div class="login-box">
<h1 class="title">AI+ 物理实验平台</h1>
<p class="subtitle">欢迎登录</p>
<div class="input-group">
<label for="name">姓名</label>
<input type="text" id="name" v-model="InputName" placeholder="请输入您的姓名" />
</div>
<div class="input-group">
<label for="sid">学号</label>
<input type="number" id="sid" v-model="InputSID" placeholder="请输入您的学号" />
</div>
<p class="tips" v-if="TipsRef">{{ TipsRef }}</p>
<button class="login-button" @click="DoLogin">登 录</button>
</div>
<div class="branding">
<p>Powered by AI Technology</p>
</div>
</div>
</div>
</template>
<style scoped>
.login-page {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
font-family: 'Helvetica Neue', Arial, sans-serif;
}
.login-container {
background-color: white;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
overflow: hidden;
width: 400px;
max-width: 90%;
transition: transform 0.3s ease;
}
.login-container:hover {
transform: translateY(-5px);
}
.login-box {
padding: 40px;
text-align: center;
}
.title {
font-size: 2rem;
font-weight: bold;
color: #333;
margin-bottom: 10px;
}
.subtitle {
font-size: 1rem;
color: #777;
margin-bottom: 30px;
}
.input-group {
margin-bottom: 20px;
text-align: left;
}
.input-group label {
display: block;
font-size: 0.9rem;
color: #555;
margin-bottom: 8px;
font-weight: 600;
}
.input-group input {
width: 100%;
padding: 12px 15px;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 1rem;
transition: border-color 0.3s ease, box-shadow 0.3s ease;
box-sizing: border-box;
}
.input-group input:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}
.tips {
color: #e74c3c;
margin-bottom: 20px;
font-size: 0.9rem;
}
.login-button {
width: 100%;
padding: 15px;
border: none;
border-radius: 8px;
background: linear-gradient(90deg, #007bff, #0056b3);
color: white;
font-size: 1.1rem;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(0, 123, 255, 0.2);
}
.login-button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 123, 255, 0.3);
}
.login-button:active {
transform: translateY(0);
box-shadow: 0 2px 10px rgba(0, 123, 255, 0.2);
}
.branding {
background-color: #f8f9fa;
padding: 15px;
text-align: center;
font-size: 0.8rem;
color: #aaa;
border-top: 1px solid #eee;
}
</style>

查看文件

@ -0,0 +1,61 @@
import { createRouter, createWebHashHistory } from 'vue-router'
import StudentLogin from '@/pages/StudentLogin.vue'
import ExperienceFrame from '@/pages/ExperienceFrame.vue'
import ExperienceSwitch from '@/pages/ExperienceSwitch.vue'
import AnswerSummary from '@/pages/AnswerSummary.vue'
const AUTH_STORAGE_KEY = 'PhyExp.StudentInfo'
const hasStoredLogin = () => {
if (typeof window === 'undefined') return false
try {
const raw = window.localStorage.getItem(AUTH_STORAGE_KEY)
if (!raw) return false
const parsed = JSON.parse(raw) as { Name?: string; SID?: number }
return Boolean(parsed?.Name) && Boolean(parsed?.SID)
} catch {
return false
}
}
const router = createRouter({
history: createWebHashHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
redirect: '/login',
},
{
path: '/login',
component: StudentLogin,
},
{
path: '/exp',
component: ExperienceFrame,
},
// ...existing code...
{
path: '/select',
component: ExperienceSwitch,
},
// {
// path: '/summary',
// name: 'AnswerSummary',
// component: AnswerSummary,
// },
{
path: '/:pathMatch(.*)*',
// ...existing code...
redirect: '/login',
},
],
})
router.beforeEach((to) => {
if (to.path === '/login') return true
if (!hasStoredLogin()) return '/login'
return true
})
export default router

查看文件

@ -0,0 +1,12 @@
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})

查看文件

@ -0,0 +1,366 @@
import { ref, computed, type Ref } from 'vue'
import { defineStore } from 'pinia'
import type {
ExperimentGridConfig,
ExperimentData,
ExperimentFieldData,
FieldValidationResponse,
AreaCalculationResult,
GridCell,
GridInputCell,
GridComputedCell,
} from '@/types/experiment'
import { calculateExpression, formatNumber } from '@/utils/calculation'
export const useExperimentStore = defineStore('experiment', () => {
const config: Ref<ExperimentGridConfig | null> = ref(null)
const data: Ref<ExperimentData> = ref({})
const areaResults: Ref<Record<string, AreaCalculationResult>> = ref({})
const loading = ref(false)
const error: Ref<string | null> = ref(null)
const currentField: Ref<string | null> = ref(null)
const validationUrl: Ref<string | null> = ref(null)
const dataVersion = ref(0)
const allFieldsValidated = computed(() => {
return Object.values(data.value).every((field) => field.validated)
})
const allInputFields = computed(() => {
if (!config.value) return []
const fields: GridInputCell[] = []
config.value.sheets.forEach((sheet) => {
sheet.cells.forEach((row) => {
row.forEach((cell) => {
if (cell && cell.type === 'input') {
fields.push(cell as GridInputCell)
}
})
})
})
return fields
})
const allInputCount = computed(() => allInputFields.value.length)
const validatedCount = computed(() => {
return Object.values(data.value).filter((f) => f.validated).length
})
const fieldValues = computed(() => {
const values: Record<string, any> = {}
Object.entries(data.value).forEach(([fieldId, fieldData]) => {
values[fieldId] = fieldData.value
})
return values
})
function findInputCell(fieldId: string): GridInputCell | null {
if (!config.value) return null
for (const sheet of config.value.sheets) {
for (const row of sheet.cells) {
for (const cell of row) {
if (cell && cell.type === 'input' && cell.fieldId === fieldId) {
return cell as GridInputCell
}
}
}
}
return null
}
function findComputedCell(areaId: string): GridComputedCell | null {
if (!config.value) return null
for (const sheet of config.value.sheets) {
for (const row of sheet.cells) {
for (const cell of row) {
if (cell && cell.type === 'computed' && cell.areaId === areaId) {
return cell as GridComputedCell
}
}
}
}
return null
}
function getDependentAreas(sourceId: string): string[] {
if (!config.value) return []
const dependentAreas: string[] = []
config.value.sheets.forEach((sheet) => {
sheet.cells.forEach((row) => {
row.forEach((cell) => {
if (cell && cell.type === 'computed') {
const comp = cell as GridComputedCell
if (comp.variables.includes(sourceId)) {
dependentAreas.push(comp.areaId)
}
}
})
})
})
return dependentAreas
}
function getAllDependentAreas(sourceId: string): string[] {
const directDependents = getDependentAreas(sourceId)
const allDependents = new Set<string>(directDependents)
const findIndirectDependents = (areaId: string) => {
const dependents = getDependentAreas(areaId)
dependents.forEach((dependentId) => {
if (!allDependents.has(dependentId)) {
allDependents.add(dependentId)
findIndirectDependents(dependentId)
}
})
}
directDependents.forEach((areaId) => {
findIndirectDependents(areaId)
})
return Array.from(allDependents)
}
const setConfig = (newConfig: ExperimentGridConfig, url?: string) => {
config.value = newConfig
if (url) validationUrl.value = url
data.value = {}
areaResults.value = {}
newConfig.sheets.forEach((sheet) => {
sheet.cells.forEach((row) => {
row.forEach((cell) => {
if (!cell) return
if (cell.type === 'input') {
const inputCell = cell as GridInputCell
data.value[inputCell.fieldId] = {
value: inputCell.defaultValue || null,
validated: false,
lastUpdated: new Date(),
}
} else if (cell.type === 'computed') {
const compCell = cell as GridComputedCell
areaResults.value[compCell.areaId] = {
value: null,
formatted: '等待计算...',
error: undefined,
}
}
})
})
})
}
const setFieldValue = (fieldId: string, value: any) => {
if (!data.value[fieldId]) {
data.value[fieldId] = {
value,
validated: false,
lastUpdated: new Date(),
}
} else {
data.value[fieldId].value = value
data.value[fieldId].validated = false
data.value[fieldId].lastUpdated = new Date()
}
currentField.value = fieldId
const dependentAreas = getAllDependentAreas(fieldId)
if (dependentAreas.length > 0) {
dependentAreas.forEach((areaId) => {
if (areaResults.value[areaId] && areaResults.value[areaId].value !== null) {
areaResults.value[areaId] = {
value: null,
formatted: '等待输入...',
error: undefined,
}
}
})
}
updateAreaCalculations()
dataVersion.value += 1
}
const validateField = async (fieldId: string): Promise<FieldValidationResponse> => {
if (!validationUrl.value) {
const response: FieldValidationResponse = { accept: true, message: '验证通过' }
if (data.value[fieldId]) {
data.value[fieldId].validationResult = response
data.value[fieldId].validated = true
}
return response
}
try {
const fieldData = data.value[fieldId]
if (!fieldData) throw new Error(`字段 ${fieldId} 不存在`)
const response = await fetch(validationUrl.value, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ field_id: fieldId, value: fieldData.value }),
})
if (!response.ok) throw new Error(`HTTP错误: ${response.status}`)
const result: FieldValidationResponse = await response.json()
if (data.value[fieldId]) {
data.value[fieldId].validationResult = result
data.value[fieldId].validated = result.accept
}
dataVersion.value += 1
if (result.accept) {
updateAreaCalculations()
}
return result
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : '未知错误'
console.error(`验证字段 ${fieldId} 失败:`, err)
const response: FieldValidationResponse = {
accept: false,
message: `验证请求失败: ${errorMessage}`,
}
if (data.value[fieldId]) {
data.value[fieldId].validationResult = response
data.value[fieldId].validated = false
}
dataVersion.value += 1
return response
}
}
const updateAreaCalculations = () => {
if (!config.value) return
const visitedAreas = new Set<string>()
const calculateArea = (areaId: string): boolean => {
if (visitedAreas.has(areaId)) return false
visitedAreas.add(areaId)
const areaConfig = findComputedCell(areaId)
if (!areaConfig) return false
try {
let allVarsReady = true
const variables: Record<string, any> = {}
areaConfig.variables.forEach((varId) => {
if (data.value[varId] && data.value[varId].validated && data.value[varId].value !== null) {
variables[varId] = data.value[varId].value
} else if (areaResults.value[varId] && areaResults.value[varId].value !== null) {
variables[varId] = areaResults.value[varId].value
} else {
const isArea = findComputedCell(varId) !== null
if (isArea) {
calculateArea(varId)
const updatedResult = areaResults.value[varId]
if (updatedResult && updatedResult.value !== null) {
variables[varId] = updatedResult.value
} else {
allVarsReady = false
}
} else {
allVarsReady = false
}
}
})
if (!allVarsReady) {
if (!areaResults.value[areaId] || areaResults.value[areaId].value !== null) {
areaResults.value[areaId] = {
value: null,
formatted: '等待输入...',
error: undefined,
}
}
return false
}
const result = calculateExpression(areaConfig.expression, variables)
const formatted = formatNumber(result, areaConfig.format || '')
const currentResult = areaResults.value[areaId]
if (!currentResult || currentResult.value !== result || currentResult.formatted !== formatted) {
areaResults.value[areaId] = { value: result, formatted, error: undefined }
const dependentAreas = getDependentAreas(areaId)
dependentAreas.forEach((dependentAreaId) => {
if (!visitedAreas.has(dependentAreaId)) {
calculateArea(dependentAreaId)
}
})
return true
}
return false
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err)
if (!areaResults.value[areaId] || areaResults.value[areaId].error !== errorMessage) {
areaResults.value[areaId] = { value: null, formatted: '计算错误', error: errorMessage }
}
return false
}
}
const allAreas = Object.keys(areaResults.value)
allAreas.forEach((areaId) => calculateArea(areaId))
}
const resetExperiment = () => {
config.value = null
data.value = {}
areaResults.value = {}
loading.value = false
error.value = null
currentField.value = null
validationUrl.value = null
dataVersion.value = 0
}
const loadConfigFromUrl = async (url: string, validationEndpoint?: string) => {
loading.value = true
error.value = null
try {
const response = await fetch(url)
if (!response.ok) throw new Error(`加载配置失败: ${response.status}`)
const configData: ExperimentGridConfig = await response.json()
setConfig(configData, validationEndpoint)
} catch (err) {
error.value = err instanceof Error ? err.message : '加载配置失败'
console.error('加载实验配置失败:', err)
} finally {
loading.value = false
}
}
return {
config,
data,
areaResults,
loading,
error,
currentField,
dataVersion,
allFieldsValidated,
fieldValues,
allInputFields,
allInputCount,
validatedCount,
setConfig,
setFieldValue,
validateField,
updateAreaCalculations,
resetExperiment,
loadConfigFromUrl,
findInputCell,
findComputedCell,
getDependentAreas,
getAllDependentAreas,
}
})

查看文件

@ -0,0 +1,65 @@
import { ref, computed, type Ref } from 'vue'
import { defineStore } from 'pinia'
export interface StudentInfo {
Name: String
SID: Number
}
interface POSTAuthProvider {
Type: 'POST'
URL: string
}
interface DefaultAuthProvider {
Type: 'Default'
}
type AuthProvider = POSTAuthProvider | DefaultAuthProvider
let AP: AuthProvider = {
Type: 'Default',
}
fetch('./config.json').then(async (v) => {
const Configure = await v.json()
AP = Configure['AuthProvider']
})
export const useStudentStore = defineStore('student', () => {
const LSID = 'PhyExp.StudentInfo'
let SI = window.localStorage.getItem(LSID)
const __raw: Ref<StudentInfo> = ref({
Name: '测试学生',
SID: 123456,
})
const doLogin = async (SID: Number, Name: String) => {
console.log(AP)
var Result = false
let msg = ''
switch (AP.Type) {
case 'Default':
__raw.value.Name = Name
__raw.value.SID = SID
Result = true
break
case 'POST':
try {
const SD = await (
await fetch(AP.URL, {
method: 'POST',
body: JSON.stringify({ SID: SID, Name: Name }),
})
).json()
if (SD.status == 'success') {
}
} catch (e) {
Result = false
msg = new String(e).toString()
}
}
if (Result) window.localStorage.setItem(LSID, JSON.stringify(__raw.value))
return [Result, msg]
}
return { doLogin, StudentInfo: __raw }
})

查看文件

@ -0,0 +1,19 @@
export interface ExperienceType {
title: string
id: string
author?: string
image?: string
skipable?: boolean
stage: {
name: string
type: string
resource?: any
}[]
}
export interface ExperienceMap {
[nickname: string]: ExperienceType
}
export interface ExperienceSets {
experiences: ExperienceMap
}

查看文件

@ -0,0 +1,83 @@
export interface ReadingGuardConfig {
enabled?: boolean
source?: 'device_peak' | 'device_frequency' | 'manual'
tolerance?: number
}
export interface ValidationConfig {
type: 'number' | 'text' | 'regex'
min?: number
max?: number
pattern?: string
required?: boolean
}
export interface GridLabelCell {
type: 'label'
content: string
colSpan?: number
rowSpan?: number
style?: string
}
export interface GridInputCell {
type: 'input'
fieldId: string
placeholder?: string
unit?: string
colSpan?: number
rowSpan?: number
validation?: ValidationConfig
readingGuard?: ReadingGuardConfig
defaultValue?: any
}
export interface GridComputedCell {
type: 'computed'
areaId: string
expression: string
variables: string[]
format?: string
colSpan?: number
rowSpan?: number
}
export type GridCell = GridLabelCell | GridInputCell | GridComputedCell | null
export interface GridSheet {
id: string
title?: string
columns: number
columnHeaders?: string[]
columnWidths?: string[]
rowHeaders?: string[]
cells: GridCell[][]
}
export interface ExperimentGridConfig {
title: string
description?: string
sheets: GridSheet[]
}
export interface FieldValidationResponse {
accept: boolean
message: string
}
export interface ExperimentFieldData {
value: any
validated: boolean
validationResult?: FieldValidationResponse
lastUpdated?: Date
}
export interface ExperimentData {
[fieldId: string]: ExperimentFieldData
}
export interface AreaCalculationResult {
value: any
formatted: string
error?: string
}

查看文件

@ -0,0 +1,38 @@
interface QuestionT_ChoiceOne {
type: '单选题'
question: string
choices: string[]
answer: number
}
interface QuestionT_MultiChoices {
type: '多选题'
question: string
choices: string[]
answer: number[]
}
interface QuestionT_FillBlank {
type: '填空题'
question: string
choices?: string[]
answer: string[]
}
interface QuestionT_Answer {
type: '简答题'
question: string
choices?: string[]
answer: null
}
export type QuestionType =
| QuestionT_ChoiceOne
| QuestionT_MultiChoices
| QuestionT_FillBlank
| QuestionT_Answer
export interface QuestionFileSchema {
meta: Record<string, unknown>
questions: QuestionType[]
}

查看文件

@ -0,0 +1,297 @@
type ChatRole = 'user' | 'assistant' | 'system'
export type ChatMessage = {
role: ChatRole
content: string
}
export type TeacherType = 'question' | 'grader' | 'data_eval'
type ChatRequest = {
teacherType: TeacherType
messages: ChatMessage[]
stream?: boolean
signal?: AbortSignal
}
let cachedBaseUrl: string | null = null
let baseUrlAttempted = false
let baseUrlPromise: Promise<string> | null = null
export type AiLogEntry = {
id: number
timestamp: number
type: 'request' | 'response' | 'error'
endpoint: string
teacherType: string
payload?: string
body?: string
status?: number
error?: string
}
let logIdCounter = 0
export const aiLogs: AiLogEntry[] = []
export const maxAiLogs = 100
const addLog = (entry: Omit<AiLogEntry, 'id' | 'timestamp'>) => {
aiLogs.unshift({ ...entry, id: ++logIdCounter, timestamp: Date.now() })
if (aiLogs.length > maxAiLogs) {
aiLogs.length = maxAiLogs
}
}
export const clearAiLogs = () => {
aiLogs.length = 0
}
export const getBaseUrl = (): string | null => cachedBaseUrl
export const setBaseUrl = (url: string | null) => {
cachedBaseUrl = url
if (url) {
;(window as { __AI_BASE_URL__?: string }).__AI_BASE_URL__ = url
} else {
baseUrlAttempted = false
cachedBaseUrl = null
delete (window as { __AI_BASE_URL__?: string }).__AI_BASE_URL__
}
}
const normalizeBaseUrl = (value: string): string => {
if (!value) return ''
return value.endsWith('/') ? value.slice(0, -1) : value
}
const resolveBaseUrl = async (): Promise<string> => {
if (cachedBaseUrl !== null) return cachedBaseUrl
const globalValue = (window as { __AI_BASE_URL__?: string }).__AI_BASE_URL__
const normalizedGlobal = normalizeBaseUrl(globalValue || '')
if (normalizedGlobal) {
cachedBaseUrl = normalizedGlobal
return cachedBaseUrl
}
if (baseUrlAttempted) return ''
if (!baseUrlPromise) {
baseUrlPromise = (async () => {
baseUrlAttempted = true
try {
const response = await fetch('/config.json', { cache: 'no-store' })
if (!response.ok) return ''
const data = (await response.json()) as { AIProvider?: { entrypoint?: string } }
const entrypoint = normalizeBaseUrl(data?.AIProvider?.entrypoint || '')
if (entrypoint) {
cachedBaseUrl = entrypoint
;(window as { __AI_BASE_URL__?: string }).__AI_BASE_URL__ = entrypoint
return entrypoint
}
} catch {
return ''
}
return ''
})().finally(() => {
baseUrlPromise = null
})
}
return baseUrlPromise
}
const buildEndpoint = async (): Promise<string> => {
const baseUrl = await resolveBaseUrl()
return baseUrl ? `${baseUrl}/api/chat` : '/api/chat'
}
const parseSseLine = (line: string): string => {
const trimmed = line.trim()
if (!trimmed.startsWith('data:')) return ''
const payload = trimmed.slice(5).trim()
if (!payload || payload === '[DONE]') return ''
try {
const data = JSON.parse(payload)
const content = data?.choices?.[0]?.delta?.content ?? data?.content ?? ''
return typeof content === 'string' ? content : ''
} catch {
return ''
}
}
export const streamChat = async (
request: ChatRequest,
onToken?: (token: string, fullText: string) => void,
): Promise<string> => {
const endpoint = await buildEndpoint()
const body = {
teacher_type: request.teacherType,
messages: request.messages,
stream: true,
}
addLog({
type: 'request',
endpoint,
teacherType: request.teacherType,
payload: JSON.stringify(body),
})
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: request.signal,
})
if (!response.ok || !response.body) {
const err = new Error(`AI request failed: ${response.status}`)
addLog({
type: 'error',
endpoint,
teacherType: request.teacherType,
status: response.status,
error: err.message,
})
throw err
}
const reader = response.body.getReader()
const decoder = new TextDecoder('utf-8')
let buffer = ''
let fullText = ''
while (true) {
const { value, done } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
const token = parseSseLine(line)
if (token) {
fullText += token
if (onToken) onToken(token, fullText)
}
}
}
if (buffer) {
const token = parseSseLine(buffer)
if (token) {
fullText += token
if (onToken) onToken(token, fullText)
}
}
addLog({
type: 'response',
endpoint,
teacherType: request.teacherType,
body: fullText.slice(0, 2000),
status: response.status,
})
return fullText
} catch (err) {
if (!(err instanceof Error) || !err.message.startsWith('AI request failed')) {
addLog({
type: 'error',
endpoint,
teacherType: request.teacherType,
error: err instanceof Error ? err.message : String(err),
})
}
throw err
}
}
export const chatOnce = async (request: ChatRequest): Promise<string> => {
const endpoint = await buildEndpoint()
const body = {
teacher_type: request.teacherType,
messages: request.messages,
stream: false,
}
addLog({
type: 'request',
endpoint,
teacherType: request.teacherType,
payload: JSON.stringify(body),
})
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: request.signal,
})
if (!response.ok) {
const err = new Error(`AI request failed: ${response.status}`)
addLog({
type: 'error',
endpoint,
teacherType: request.teacherType,
status: response.status,
error: err.message,
})
throw err
}
const data = await response.json()
const text = data?.response ?? ''
const result = typeof text === 'string' ? text : ''
addLog({
type: 'response',
endpoint,
teacherType: request.teacherType,
body: result.slice(0, 2000),
status: response.status,
})
return result
} catch (err) {
if (!(err instanceof Error) || !err.message.startsWith('AI request failed')) {
addLog({
type: 'error',
endpoint,
teacherType: request.teacherType,
error: err instanceof Error ? err.message : String(err),
})
}
throw err
}
}
export const extractJsonBlock = (text: string): string | null => {
if (!text) return null
const fenced = /```json\s*([\s\S]*?)```/i.exec(text)
if (fenced && fenced[1]) {
return fenced[1].trim()
}
const brace = /\{[\s\S]*\}/.exec(text)
if (brace && brace[0]) {
return brace[0].trim()
}
return null
}
export const safeParseJson = <T>(text: string): { value: T | null; error?: string } => {
try {
return { value: JSON.parse(text) as T }
} catch (error) {
return { value: null, error: error instanceof Error ? error.message : 'Invalid JSON' }
}
}

查看文件

@ -0,0 +1,53 @@
import type { InjectionKey, Ref } from 'vue'
import type { ExperimentData, AreaCalculationResult } from '@/types/experiment'
import type { StudentInfo } from '@/stores/student'
export type ConfigSummary = {
title: string
description?: string
fields: Array<{
id: string
label: string
unit?: string
validation?: {
type: string
min?: number
max?: number
pattern?: string
required?: boolean
}
}>
areas: Array<{
id: string
label: string
expression: string
variables: string[]
format?: string
}>
}
export type AIEvalFocus = {
type: 'field' | 'area'
id: string
label: string
value: unknown
unit?: string
formatted?: string
}
export type AIEvalResult = {
rawText: string
displayText: string
parsed: unknown | null
}
export type AIEvalContext = {
configSummary: Ref<ConfigSummary>
fieldData: Ref<ExperimentData>
areaResults: Ref<Record<string, AreaCalculationResult>>
dataVersion: Ref<number>
studentInfo: Ref<StudentInfo>
requestEvaluation: (focus: AIEvalFocus) => Promise<AIEvalResult>
}
export const AIEvalContextKey: InjectionKey<AIEvalContext> = Symbol('AIEvalContext')

查看文件

@ -0,0 +1,239 @@
import { create, all, type FactoryFunctionMap } from 'mathjs'
// 创建mathjs实例
const math = create(all as FactoryFunctionMap)
/**
* 格式化数字
* @param value 数值
* @param format 格式字符串,如 "0.00", "0.000e+0"
* @returns 格式化后的字符串
*/
export function formatNumber(value: any, format: string): string {
if (value === null || value === undefined) {
return 'N/A'
}
if (typeof value !== 'number') {
return String(value)
}
if (!format) {
// 默认格式:保留3位有效数字
return value.toPrecision(3)
}
try {
// 简单的格式处理
if (format.includes('e')) {
const match = format.match(/\d+/)
return value.toExponential(parseInt(match?.[0] || '2'))
}
if (format.includes('.')) {
const parts = format.split('.')
const decimalPlaces = parts[1]?.length || 2
return value.toFixed(decimalPlaces)
}
return String(value)
} catch (error) {
console.error('数字格式化错误:', error)
return String(value)
}
}
/**
* 将LaTeX表达式转换为math.js可识别的表达式
* @param latexExpression LaTeX表达式
* @returns 转换后的表达式
*/
function convertLatexToMathJS(latexExpression: string): string {
let expression = latexExpression
// 1. 移除$符号和等号左边的部分(只保留表达式)
expression = expression.replace(/\$/g, '')
// 如果包含等号,只取等号右边的部分
if (expression.includes('=')) {
const parts = expression.split('=')
if (parts.length > 1) {
const lastPart = parts[parts.length - 1]
if (lastPart !== undefined) {
expression = lastPart.trim()
}
}
}
// 2. 处理\frac{a}{b} -> (a)/(b)
// 需要递归处理嵌套的\frac
let lastExpression = ''
while (expression !== lastExpression) {
lastExpression = expression
const fracRegex = /\\frac\{([^{}]+|(?:\{[^{}]*\})*)\}\{([^{}]+|(?:\{[^{}]*\})*)\}/g
expression = expression.replace(fracRegex, '($1)/($2)')
}
// 确保分数中的数字被正确解析(如 1/2 -> 1/2,而不是整数除法)
// math.js会正确处理分数
// 3. 处理\sqrt{a} -> sqrt(a)
const sqrtRegex = /\\sqrt\{([^{}]+|(?:\{[^{}]*\})*)\}/g
expression = expression.replace(sqrtRegex, 'sqrt($1)')
// 4. 处理\sqrt[n]{a} -> nthRoot(a, n)
const nthRootRegex = /\\sqrt\[([^\]]+)\]\{([^{}]+|(?:\{[^{}]*\})*)\}/g
expression = expression.replace(nthRootRegex, 'nthRoot($2, $1)')
// 5. 替换希腊字母(移除反斜杠)
const greekLetters = [
'alpha',
'beta',
'gamma',
'delta',
'epsilon',
'zeta',
'eta',
'theta',
'iota',
'kappa',
'lambda',
'mu',
'nu',
'xi',
'omicron',
'rho',
'sigma',
'tau',
'upsilon',
'phi',
'chi',
'psi',
'omega',
]
greekLetters.forEach((letter) => {
expression = expression.replace(new RegExp(`\\\\${letter}\\b`, 'g'), letter)
})
// 6. 替换其他数学符号
// 使用单词边界确保只替换完整的LaTeX命令
const symbolReplacements: Record<string, string> = {
'\\\\pi\\b': 'pi',
'\\\\times\\b': '*',
'\\\\cdot\\b': '*',
'\\\\div\\b': '/',
'\\\\pm\\b': 'plusminus',
'\\\\mp\\b': 'minusplus',
'\\\\approx\\b': '~',
'\\\\neq\\b': '!=',
'\\\\leq\\b': '<=',
'\\\\geq\\b': '>=',
'\\\\infty\\b': 'Infinity',
'\\\\sum\\b': 'sum',
'\\\\prod\\b': 'prod',
'\\\\int\\b': 'integrate',
}
Object.entries(symbolReplacements).forEach(([latex, mathjs]) => {
expression = expression.replace(new RegExp(latex, 'g'), mathjs)
})
// 7. 处理大括号(移除它们)
expression = expression.replace(/\{/g, '(').replace(/\}/g, ')')
// 8. 处理LaTeX中的下划线转义(\_ -> _)
expression = expression.replace(/\\_/g, '_')
// 9. 处理下标(如 v_{1} -> v1)
expression = expression.replace(/([a-zA-Z])_\{(\d+)\}/g, '$1$2')
expression = expression.replace(/([a-zA-Z])_(\d+)/g, '$1$2')
// 9. 处理度数符号
expression = expression.replace(/^\circ/g, 'deg')
// 10. 清理多余的空格
expression = expression.trim()
return expression
}
/**
* 计算数学表达式
* @param expression 数学表达式字符串(支持LaTeX)
* @param variables 变量映射
* @returns 计算结果
*/
export function calculateExpression(expression: string, variables: Record<string, any> = {}): any {
try {
// 将LaTeX转换为math.js表达式
const mathjsExpression = convertLatexToMathJS(expression)
// 准备变量,确保变量名与表达式中的一致
const preparedVariables: Record<string, any> = {}
Object.entries(variables).forEach(([key, value]) => {
// 变量名可能包含下标,如v_1,在表达式中可能是v1
// 这里我们保持原样,让math.js处理
preparedVariables[key] = value
})
// 编译并计算表达式
const compiled = math.compile(mathjsExpression)
return compiled.evaluate(preparedVariables)
} catch (error) {
console.error('表达式计算错误:', error)
console.error('原始表达式:', expression)
console.error('转换后表达式:', convertLatexToMathJS(expression))
console.error('变量:', variables)
throw new Error(`计算错误: ${error instanceof Error ? error.message : String(error)}`)
}
}
/**
* 检查字段依赖是否满足
* @param dependencies 依赖的字段ID数组
* @param fieldData 字段数据
* @returns 是否满足依赖
*/
export function checkDependencies(
dependencies: string[],
fieldData: Record<string, { validated: boolean }>,
): boolean {
if (!dependencies || dependencies.length === 0) {
return true
}
return dependencies.every((depId) => {
const depData = fieldData[depId]
return depData && depData.validated
})
}
/**
* 验证数值范围
* @param value 数值
* @param min 最小值
* @param max 最大值
* @returns 是否在范围内
*/
export function validateNumberRange(value: number, min?: number, max?: number): boolean {
if (min !== undefined && value < min) return false
if (max !== undefined && value > max) return false
return true
}
/**
* 验证正则表达式
* @param value 字符串值
* @param pattern 正则表达式模式
* @returns 是否匹配
*/
export function validateRegex(value: string, pattern: string): boolean {
try {
const regex = new RegExp(pattern)
return regex.test(value)
} catch (error) {
console.error('正则表达式错误:', error)
return false
}
}

354
frontend/src/utils/device.ts 普通文件
查看文件

@ -0,0 +1,354 @@
/**
* 设备检测和适配工具
*/
// 设备类型枚举
export enum DeviceType {
DESKTOP = 'desktop',
TABLET = 'tablet',
MOBILE = 'mobile',
UNKNOWN = 'unknown',
}
// 屏幕尺寸断点
export const BREAKPOINTS = {
MOBILE: 480,
TABLET: 768,
DESKTOP: 1024,
LARGE_DESKTOP: 1440,
} as const
// 设备信息接口
export interface DeviceInfo {
type: DeviceType
screenWidth: number
screenHeight: number
isTouchDevice: boolean
isPortrait: boolean
pixelRatio: number
userAgent: string
}
// 全局设备信息
let deviceInfo: DeviceInfo | null = null
/**
* 检测设备信息
*/
export function detectDevice(): DeviceInfo {
if (deviceInfo) {
return deviceInfo
}
const { userAgent } = navigator
const screenWidth = window.innerWidth
const screenHeight = window.innerHeight
const pixelRatio = window.devicePixelRatio || 1
// 检测是否为触摸设备
const isTouchDevice =
'ontouchstart' in window ||
navigator.maxTouchPoints > 0 ||
(navigator as any).msMaxTouchPoints > 0
// 检测屏幕方向
const isPortrait = screenHeight > screenWidth
// 根据屏幕宽度和设备特征确定设备类型
let type: DeviceType = DeviceType.UNKNOWN
if (screenWidth < BREAKPOINTS.MOBILE) {
type = DeviceType.MOBILE
} else if (screenWidth < BREAKPOINTS.TABLET) {
// 检查是否为平板(基于用户代理和屏幕尺寸)
const isTablet = /(tablet|ipad|playbook|silk)|(android(?!.*mobile))/i.test(userAgent)
type = isTablet ? DeviceType.TABLET : DeviceType.MOBILE
} else if (screenWidth < BREAKPOINTS.DESKTOP) {
type = DeviceType.TABLET
} else {
type = DeviceType.DESKTOP
}
// 特殊处理:大屏手机可能被误判为平板
if (type === DeviceType.TABLET && isTouchDevice && screenWidth <= 900) {
// 检查用户代理是否为手机
const isMobileUA = /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
userAgent,
)
if (isMobileUA) {
type = DeviceType.MOBILE
}
}
deviceInfo = {
type,
screenWidth,
screenHeight,
isTouchDevice,
isPortrait,
pixelRatio,
userAgent,
}
return deviceInfo
}
/**
* 获取设备类型
*/
export function getDeviceType(): DeviceType {
return detectDevice().type
}
/**
* 检查是否为移动设备
*/
export function isMobile(): boolean {
const type = getDeviceType()
return type === DeviceType.MOBILE || type === DeviceType.TABLET
}
/**
* 检查是否为桌面设备
*/
export function isDesktop(): boolean {
return getDeviceType() === DeviceType.DESKTOP
}
/**
* 检查是否为平板设备
*/
export function isTablet(): boolean {
return getDeviceType() === DeviceType.TABLET
}
/**
* 检查是否为触摸设备
*/
export function isTouchDevice(): boolean {
return detectDevice().isTouchDevice
}
/**
* 检查是否为竖屏模式
*/
export function isPortrait(): boolean {
return detectDevice().isPortrait
}
/**
* 获取屏幕宽度
*/
export function getScreenWidth(): number {
return detectDevice().screenWidth
}
/**
* 获取屏幕高度
*/
export function getScreenHeight(): number {
return detectDevice().screenHeight
}
/**
* 获取像素比
*/
export function getPixelRatio(): number {
return detectDevice().pixelRatio
}
/**
* 根据设备类型获取合适的字体大小
*/
export function getResponsiveFontSize(baseSize: number): number {
const deviceType = getDeviceType()
switch (deviceType) {
case DeviceType.MOBILE:
return baseSize * 0.9
case DeviceType.TABLET:
return baseSize * 0.95
case DeviceType.DESKTOP:
return baseSize
default:
return baseSize
}
}
/**
* 根据设备类型获取合适的间距
*/
export function getResponsiveSpacing(baseSpacing: number): number {
const deviceType = getDeviceType()
switch (deviceType) {
case DeviceType.MOBILE:
return baseSpacing * 0.8
case DeviceType.TABLET:
return baseSpacing * 0.9
case DeviceType.DESKTOP:
return baseSpacing
default:
return baseSpacing
}
}
/**
* 根据设备类型获取合适的容器最大宽度
*/
export function getResponsiveMaxWidth(): string {
const deviceType = getDeviceType()
switch (deviceType) {
case DeviceType.MOBILE:
return '100%'
case DeviceType.TABLET:
return '90%'
case DeviceType.DESKTOP:
return '1200px'
default:
return '100%'
}
}
/**
* 监听窗口大小变化
*/
export function onResize(callback: (deviceInfo: DeviceInfo) => void): () => void {
const handleResize = () => {
// 重置设备信息缓存
deviceInfo = null
const newDeviceInfo = detectDevice()
callback(newDeviceInfo)
}
window.addEventListener('resize', handleResize)
// 返回清理函数
return () => {
window.removeEventListener('resize', handleResize)
}
}
/**
* 监听设备方向变化
*/
export function onOrientationChange(callback: (isPortrait: boolean) => void): () => void {
const handleOrientationChange = () => {
deviceInfo = null
const { isPortrait } = detectDevice()
callback(isPortrait)
}
window.addEventListener('orientationchange', handleOrientationChange)
window.addEventListener('resize', handleOrientationChange)
// 返回清理函数
return () => {
window.removeEventListener('orientationchange', handleOrientationChange)
window.removeEventListener('resize', handleOrientationChange)
}
}
/**
* 获取设备特定的CSS类名
*/
export function getDeviceClasses(): string[] {
const deviceInfo = detectDevice()
const classes: string[] = []
// 设备类型类
classes.push(`device-${deviceInfo.type}`)
// 触摸设备类
if (deviceInfo.isTouchDevice) {
classes.push('touch-device')
} else {
classes.push('non-touch-device')
}
// 屏幕方向类
if (deviceInfo.isPortrait) {
classes.push('portrait')
} else {
classes.push('landscape')
}
// 屏幕尺寸类
if (deviceInfo.screenWidth < BREAKPOINTS.MOBILE) {
classes.push('screen-xs')
} else if (deviceInfo.screenWidth < BREAKPOINTS.TABLET) {
classes.push('screen-sm')
} else if (deviceInfo.screenWidth < BREAKPOINTS.DESKTOP) {
classes.push('screen-md')
} else if (deviceInfo.screenWidth < BREAKPOINTS.LARGE_DESKTOP) {
classes.push('screen-lg')
} else {
classes.push('screen-xl')
}
return classes
}
/**
* 应用设备特定的样式到元素
*/
export function applyDeviceStyles(element: HTMLElement): void {
const classes = getDeviceClasses()
classes.forEach((className) => {
element.classList.add(className)
})
}
/**
* 检查是否支持特定的CSS特性
*/
export function supportsCSSFeature(feature: string): boolean {
const style = document.createElement('div').style
// 检查各种前缀
const prefixes = ['', '-webkit-', '-moz-', '-ms-', '-o-']
for (const prefix of prefixes) {
const prefixedFeature = prefix + feature
if (prefixedFeature in style) {
return true
}
}
return false
}
/**
* 检查是否支持特定的JavaScript API
*/
export function supportsJSFeature(feature: string): boolean {
switch (feature) {
case 'touch':
return 'ontouchstart' in window
case 'geolocation':
return 'geolocation' in navigator
case 'localStorage':
return 'localStorage' in window
case 'sessionStorage':
return 'sessionStorage' in window
case 'serviceWorker':
return 'serviceWorker' in navigator
case 'pushManager':
return 'PushManager' in window
case 'notifications':
return 'Notification' in window
case 'webgl':
try {
const canvas = document.createElement('canvas')
return !!(
window.WebGLRenderingContext &&
(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))
)
} catch {
return false
}
default:
return false
}
}

98
frontend/src/utils/latex.ts 普通文件
查看文件

@ -0,0 +1,98 @@
import katex from 'katex'
import 'katex/dist/katex.min.css'
/**
* 渲染LaTeX字符串为HTML
* @param latex LaTeX字符串
* @param displayMode 是否为块级公式
* @returns 渲染后的HTML字符串
*/
export function renderLatex(latex: string, displayMode: boolean = false): string {
try {
return katex.renderToString(latex, {
displayMode,
throwOnError: false,
errorColor: '#cc0000',
})
} catch (error) {
console.error('LaTeX渲染错误:', error)
return `<span class="latex-error" style="color: red;">LaTeX错误: ${latex}</span>`
}
}
/**
* 从文本中提取LaTeX表达式
* @param text 包含LaTeX的文本
* @returns 提取后的LaTeX表达式数组
*/
export function extractLatexExpressions(text: string): Array<{
expression: string
isInline: boolean
start: number
end: number
}> {
const expressions: Array<{
expression: string
isInline: boolean
start: number
end: number
}> = []
// 匹配内联LaTeX: $...$
const inlineRegex = /\$([^$]+)\$/g
let match: RegExpExecArray | null
while ((match = inlineRegex.exec(text)) !== null) {
expressions.push({
expression: match[1] || '',
isInline: true,
start: match.index,
end: match.index + (match[0]?.length || 0),
})
}
// 匹配块级LaTeX: $$...$$
const blockRegex = /\$\$([^$]+)\$\$/g
while ((match = blockRegex.exec(text)) !== null) {
expressions.push({
expression: match[1] || '',
isInline: false,
start: match.index,
end: match.index + (match[0]?.length || 0),
})
}
return expressions
}
/**
* 将包含LaTeX的文本转换为HTML
* @param text 包含LaTeX的文本
* @returns 转换后的HTML字符串
*/
export function renderTextWithLatex(text: string): string {
const expressions = extractLatexExpressions(text)
if (expressions.length === 0) {
return text
}
let result = ''
let lastIndex = 0
expressions.forEach((expr) => {
// 添加表达式前的普通文本
result += text.substring(lastIndex, expr.start)
// 渲染LaTeX表达式
result += renderLatex(expr.expression, !expr.isInline)
lastIndex = expr.end
})
// 添加剩余的普通文本
if (lastIndex < text.length) {
result += text.substring(lastIndex)
}
return result
}

查看文件

@ -0,0 +1,104 @@
/**
* 简单的Markdown到HTML转换器
* 支持基本Markdown语法和LaTeX内联
*/
import { renderLatex } from './latex'
type LatexToken = {
key: string
expression: string
isDisplay: boolean
}
function protectLatex(text: string): { text: string; tokens: LatexToken[] } {
const tokens: LatexToken[] = []
let index = 0
const protectedText = text.replace(
/\$\$([\s\S]+?)\$\$|\$([^$\n]+?)\$/g,
(_, blockExpr, inlineExpr) => {
const isDisplay = blockExpr !== undefined
const expression = (isDisplay ? blockExpr : inlineExpr) || ''
const key = `__LATEX_TOKEN_${index}__`
tokens.push({ key, expression, isDisplay })
index += 1
return key
},
)
return { text: protectedText, tokens }
}
function restoreLatex(text: string, tokens: LatexToken[]): string {
return tokens.reduce((acc, token) => {
return acc.replaceAll(token.key, renderLatex(token.expression, token.isDisplay))
}, text)
}
/**
* 将Markdown文本转换为HTML
* @param text Markdown文本
* @returns HTML字符串
*/
export function renderMarkdown(text: string): string {
if (!text) return ''
let html = text
// 1. 处理标题
html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>')
html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>')
html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>')
// 2. 处理粗体
html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
html = html.replace(/__(.*?)__/g, '<strong>$1</strong>')
// 3. 处理斜体
html = html.replace(/\*(.*?)\*/g, '<em>$1</em>')
html = html.replace(/_(.*?)_/g, '<em>$1</em>')
// 4. 处理删除线
html = html.replace(/~~(.*?)~~/g, '<del>$1</del>')
// 5. 处理代码
html = html.replace(/`([^`]+)`/g, '<code>$1</code>')
// 6. 处理换行(将两个换行转换为段落)
html = html.replace(/\n\n+/g, '</p><p>')
// 7. 处理单换行(转换为<br>)
html = html.replace(/\n/g, '<br>')
// 8. 包装在段落中(如果没有被其他块级元素包装)
if (
!html.startsWith('<h1') &&
!html.startsWith('<h2') &&
!html.startsWith('<h3') &&
!html.startsWith('<p>') &&
!html.startsWith('<div>')
) {
html = `<p>${html}</p>`
}
return html
}
/**
* 将包含Markdown和LaTeX的文本转换为HTML
* @param text 包含Markdown和LaTeX的文本
* @returns 转换后的HTML字符串
*/
export function renderMarkdownWithLatex(text: string): string {
if (!text) return ''
// 先保护LaTeX片段,避免Markdown规则(尤其是下划线斜体)破坏公式
const protectedResult = protectLatex(text)
// 再做Markdown转换
const html = renderMarkdown(protectedResult.text)
// 最后恢复并直接渲染LaTeX
return restoreLatex(html, protectedResult.tokens)
}

查看文件

@ -0,0 +1,86 @@
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
type PdfExportOptions = {
marginMm?: number
scale?: number
backgroundColor?: string
autoScale?: boolean
minScale?: number
allowMultiPage?: boolean
}
const getDefaultOptions = (): Required<PdfExportOptions> => ({
marginMm: 10,
scale: 2,
backgroundColor: '#ffffff',
autoScale: true,
minScale: 0.75,
allowMultiPage: true,
})
export const exportElementToPdf = async (
element: HTMLElement,
filename: string,
options?: PdfExportOptions,
): Promise<void> => {
const merged = { ...getDefaultOptions(), ...(options || {}) }
const rect = element.getBoundingClientRect()
if (rect.width === 0 || rect.height === 0) {
throw new Error('导出区域为空,请检查表格是否渲染完成。')
}
const canvas = await html2canvas(element, {
scale: merged.scale,
useCORS: true,
backgroundColor: merged.backgroundColor,
logging: false,
})
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4',
})
const pageWidth = pdf.internal.pageSize.getWidth()
const pageHeight = pdf.internal.pageSize.getHeight()
const margin = merged.marginMm
const contentWidth = pageWidth - margin * 2
const contentHeight = pageHeight - margin * 2
const imgData = canvas.toDataURL('image/png')
let imgWidth = contentWidth
let imgHeight = (canvas.height * imgWidth) / canvas.width
if (merged.autoScale && imgHeight > contentHeight) {
const scaleToFit = contentHeight / imgHeight
if (scaleToFit >= merged.minScale) {
imgWidth *= scaleToFit
imgHeight *= scaleToFit
}
}
const x = (pageWidth - imgWidth) / 2
if (imgHeight <= contentHeight || !merged.allowMultiPage) {
pdf.addImage(imgData, 'PNG', x, margin, imgWidth, imgHeight, undefined, 'FAST')
pdf.save(filename)
return
}
let heightLeft = imgHeight
let position = margin
pdf.addImage(imgData, 'PNG', x, position, imgWidth, imgHeight, undefined, 'FAST')
heightLeft -= contentHeight
while (heightLeft > 0) {
pdf.addPage()
position = margin - (imgHeight - heightLeft)
pdf.addImage(imgData, 'PNG', x, position, imgWidth, imgHeight, undefined, 'FAST')
heightLeft -= contentHeight
}
pdf.save(filename)
}

18
frontend/tsconfig.app.json 普通文件
查看文件

@ -0,0 +1,18 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
// Extra safety for array and object lookups, but may have false positives.
"noUncheckedIndexedAccess": true,
// Path mapping for cleaner imports.
"paths": {
"@/*": ["./src/*"]
},
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
// Specified here to keep it out of the root directory.
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
}
}

11
frontend/tsconfig.json 普通文件
查看文件

@ -0,0 +1,11 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.json"
}
]
}

27
frontend/tsconfig.node.json 普通文件
查看文件

@ -0,0 +1,27 @@
// TSConfig for modules that run in Node.js environment via either transpilation or type-stripping.
{
"extends": "@tsconfig/node24/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"playwright.config.*",
"eslint.config.*"
],
"compilerOptions": {
// Most tools use transpilation instead of Node.js's native type-stripping.
// Bundler mode provides a smoother developer experience.
"module": "preserve",
"moduleResolution": "bundler",
// Include Node.js types and avoid accidentally including other `@types/*` packages.
"types": ["node"],
// Disable emitting output during `vue-tsc --build`, which is used for type-checking only.
"noEmit": true,
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
// Specified here to keep it out of the root directory.
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
}
}

18
frontend/vite.config.ts 普通文件
查看文件

@ -0,0 +1,18 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
vueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
})

1852
frontend/yarn.lock 普通文件

文件差异内容过多而无法显示 加载差异