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

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

7
.vscode/extensions.json vendored 普通文件
查看文件

@ -0,0 +1,7 @@
{
"recommendations": [
"Vue.volar",
"esbenp.prettier-vscode",
"ms-python.python"
]
}

12
.vscode/settings.json vendored 普通文件
查看文件

@ -0,0 +1,12 @@
{
"explorer.fileNesting.enabled": true,
"explorer.fileNesting.patterns": {
"tsconfig.json": "tsconfig.*.json, env.d.ts, typed-router.d.ts",
"vite.config.*": "jsconfig*, vitest.config.*, cypress.config.*, playwright.config.*",
"package.json": "package-lock.json, pnpm*, .yarnrc*, yarn*, .eslint*, eslint*, .oxlint*, oxlint*, .oxfmt*, .prettier*, prettier*, .editorconfig"
},
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/bin/python",
"python.autoComplete.extraPaths": ["${workspaceFolder}/backend"]
}

10
backend/.gitignore vendored 普通文件
查看文件

@ -0,0 +1,10 @@
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info
# Virtual environments
.venv

1
backend/.python-version 普通文件
查看文件

@ -0,0 +1 @@
3.11

172
backend/ARCHITECTURE.md 普通文件
查看文件

@ -0,0 +1,172 @@
# PhyExp 后端架构文档
## 项目概述
- **项目名称:** PhyExp Backend (Physics Experiment Backend)
- **类型:** Python FastAPI REST 服务
- **描述:** 为物理实验教学平台提供表单配置、字段验证、声速实验计算及示波器数据采集能力
## 目录结构
```
backend/
├── pyproject.toml # Python 项目配置 (uv)
├── uv.lock # 依赖锁定文件
├── .python-version # Python 版本约束
├── config/
│ └── experiments/ # 实验配置文件 (JSON)
│ ├── voice_speed.json # 声速测量实验配置
│ └── _voice_speed.json # 旧版备份
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI 应用入口, CORS, 路由注册
│ ├── models.py # 兼容性重导出 (实际定义在 schemas/)
│ ├── schemas/ # Pydantic 数据模型
│ │ ├── __init__.py # 统一导出
│ │ ├── experiment.py # 网格实验配置模型 (GridSheet, GridCell...)
│ │ └── validation.py # 验证请求/响应、测量分析模型
│ ├── api/ # REST API 路由层
│ │ ├── __init__.py
│ │ ├── form.py # GET /form, /form/list — 加载实验配置
│ │ ├── value.py # POST/GET/DELETE /value — 字段值 CRUD + 验证
│ │ ├── device.py # GET /device/status, POST /device/peak — 示波器控制
│ │ └── measurement.py # POST /measurement/{method} — 测量数据分析
│ ├── core/ # 业务逻辑层
│ │ ├── __init__.py
│ │ ├── config_loader.py # ExperimentConfigService — 加载/验证 JSON 配置
│ │ ├── dependencies.py # 服务单例 + 字段查找辅助函数
│ │ ├── measurement.py # MeasurementService — 声速实验统计算法
│ │ ├── reading_guard.py # ReadingGuardManager — 读数顺序守卫 + 容差校验
│ │ ├── session_store.py # SessionStore — 线程安全内存 KV 存储
│ │ └── validation.py # FieldValidator — 基础字段校验 (数字/正则/必填)
│ └── hardware/ # 示波器硬件交互层
│ ├── __init__.py
│ ├── oscilloscope.py # Oscilloscope — PyUSB SCPI 协议驱动
│ ├── progress.py # SCPI 命令枚举 + 执行器
│ └── service.py # OscilloscopeService — 探针/峰值/频率采集 (含模拟回退)
```
## 技术栈
| 分类 | 技术 | 版本 |
| ---------- | -------------------- | ------- |
| 框架 | FastAPI | 0.116+ |
| 数据验证 | Pydantic v2 | 2.11+ |
| 服务器 | Uvicorn | 0.35+ |
| 硬件通信 | PyUSB + libusb | 1.3+ |
| 包管理 | uv | - |
## API 端点
| 方法 | 路径 | 说明 |
| ------ | ----------------------------------- | ------------------------ |
| GET | `/` | 服务信息 + 端点列表 |
| GET | `/health` | 健康检查 |
| GET | `/form?experiment=voice_speed` | 加载实验网格配置 |
| GET | `/form/list` | 列出可用实验 |
| GET | `/form/{experiment_name}` | 按名称加载实验配置 |
| POST | `/value?experiment=...` | 验证并存储字段值 |
| GET | `/value` | 获取所有字段值 |
| GET | `/value/{field_id}` | 获取单个字段值 |
| DELETE | `/value/{field_id}` | 删除单个字段值 |
| DELETE | `/value` | 清除所有字段值 |
| GET | `/device/status` | 探针示波器状态 |
| POST | `/device/peak` | 捕获峰值 |
| POST | `/device/manual-answer` | 设置读数守卫手动答案 |
| POST | `/measurement/{method}` | 分析测量数据 (声速计算) |
## 核心架构
### 数据模型
```
ExperimentGridConfig
├── title: str
├── description?: str
└── sheets: GridSheet[]
├── id: str
├── title?: str
├── columns: int
├── columnHeaders?: str[]
├── columnWidths?: str[]
├── rowHeaders?: str[]
└── cells: GridCell[][] # 2D 矩阵
├── GridLabelCell { type: "label", content: str }
├── GridInputCell { type: "input", fieldId: str, validation?, readingGuard? }
└── GridComputedCell { type: "computed", areaId: str, expression, variables[] }
```
### 请求流程
```
POST /value { field_id, value }
→ find_field(experiment, field_id) # 从配置中查找字段定义
→ FieldValidator.validate_by_config() # 基础校验 (类型/范围/正则)
→ reading_guard_manager.validate() # 读数顺序 + 容差校验
→ session_store.set_value() # 存储到内存
→ { accept: bool, message: str }
```
### 会话管理
- 通过 `X-Session-Id` 请求头或默认 `"default"` 标识会话
- `SessionStore` 是线程安全的内存 KV 存储
- 字段值按 `{ session_id → { field_id → value } }` 组织
### 硬件交互
- `OscilloscopeService` 提供三层设备状态:`ONLINE | OFFLINE | SIMULATED`
- 连接真实示波器失败时自动回退到模拟模式
- `ReadingGuardManager` 可通过 `source: "device_peak"` 自动从示波器采集参考值
## 实验配置格式
实验配置以 JSON 文件存储在 `config/experiments/` 目录下。每个文件定义了一个实验的完整数据表结构。
### GridSheet 概念
每个实验由多个 Sheet 组成(类似 Excel 工作表),每个 Sheet 是一个二维单元格矩阵:
```json
{
"id": "table1",
"title": "表1 声源频率与介质温度",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$f/kHz$"},
{"type": "input", "fieldId": "f1", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f2", ...},
...
],
[
{"type": "label", "content": "$\\bar{f}/kHz$"},
{"type": "computed", "areaId": "frequency_avg", "expression": "(f1+f2+f3+f4+f5)/5", "format": "0.00", "colSpan": 5}
]
]
}
```
### 单元格类型
| 类型 | 用途 | 关键字段 |
| ---------- | ------------------------ | ----------------------------------- |
| `label` | 静态标签/表头 (支持 LaTeX) | `content` |
| `input` | 学生数据输入 | `fieldId`, `validation`, `readingGuard` |
| `computed` | 自动计算结果 | `areaId`, `expression`, `variables`, `format` |
## 声速实验计算
`MeasurementService` 支持三种测量方法的统计算法:
1. **驻波法 / 相位法** (`standing_wave` / `phase`)
- 取前 5 个与后 5 个读数的配对差值
- 波长 λ = 2 × mean(Δ) / 1000 [m]
- 声速 v = f × λ
- 不确定度 Δv = f × 2 × σ(Δ) / 1000
2. **时差法** (`time_diff`)
- 每对 (距离, 时间差) 独立计算速度
- v = mean(v_i)
- 不确定度 Δv = σ(v_i)

0
backend/README.md 普通文件
查看文件

65
backend/app/README.md 普通文件
查看文件

@ -0,0 +1,65 @@
# 物理实验后端(FastAPI)
该目录实现了与前端 `ExperimentForm` 对齐的后端 API,覆盖:
1. 实验配置下发(`/form`)
2. 字段值验证与会话存储(`/value`)
3. 声速实验三方法计算(`/measurement`)
## 架构概览
- `main.py`: FastAPI 入口、CORS、路由注册
- `models.py`: 与前端协议对应的 Pydantic 模型
- `api/form.py`: 实验表单配置接口
- `api/value.py`: 字段值验证与会话数据接口
- `api/measurement.py`: 驻波法/相位法/时差法计算接口
- `core/config_loader.py`: 配置文件加载与校验
- `core/validation.py`: 配置驱动字段验证
- `core/session_store.py`: 内存会话态字段存储
- `core/measurement.py`: 声速实验计算逻辑
- `../config/experiments/*.json`: 实验配置文件
## 运行
在 `backend` 目录执行:
```bash
uv run uvicorn main:app --app-dir src --reload --host 0.0.0.0 --port 8000
```
或直接:
```bash
python src/main.py
```
## 主要接口
1. `GET /form?experiment=voice_speed`
2. `GET /form/list`
3. `POST /value`
4. `GET /value`
5. `DELETE /value`
6. `POST /measurement/{standing_wave|phase|time_diff}`
7. `GET /health`
## 会话设计
- 通过请求头 `X-Session-Id` 区分不同学生/实验会话。
- 未提供时使用默认会话 `default`。
- 当前为内存存储,后续可替换为 Redis/数据库。
## 计算方法说明
- `standing_wave` / `phase`:
- 输入 `cursor_readings_mm` 至少 10 个读数。
- 使用“后五次减前五次”配对差统计平均值与不确定度。
- 依据 `frequency_hz` 计算波长与声速。
- `time_diff`:
- 输入 `distance_readings_mm` 与 `time_deltas_us`,按组计算速度并求均值与标准差。
## 下一步建议
1. 将 `oscilloscope.py` 与 OCR 能力接入 `measurement` 路由。
2. 将 `session_store` 升级为持久化存储。
3. 增加 `pytest` 接口测试覆盖边界输入。

1
backend/app/__init__.py 普通文件
查看文件

@ -0,0 +1 @@
#

查看文件

48
backend/app/api/device.py 普通文件
查看文件

@ -0,0 +1,48 @@
from __future__ import annotations
from fastapi import APIRouter, Header
from app.core.dependencies import reading_guard_manager, resolve_session_id
from app.hardware.service import oscilloscope_service
from app.models import ManualAnswerRequest
router = APIRouter(prefix="/device", tags=["device"])
@router.get("/status")
async def get_device_status():
snapshot = oscilloscope_service.probe()
return {
"status": snapshot.status,
"device_idn": snapshot.device_idn,
"peak_value": snapshot.peak_value,
"frequency_hz": snapshot.frequency_hz,
"raw_response": snapshot.raw_response,
"note": snapshot.note,
}
@router.post("/peak")
async def capture_peak_value():
snapshot = oscilloscope_service.capture_peak()
return {
"status": snapshot.status,
"peak_value": snapshot.peak_value,
"note": snapshot.note,
}
@router.post("/manual-answer")
async def set_manual_answer(
request: ManualAnswerRequest,
x_session_id: str | None = Header(default=None),
):
session_id = resolve_session_id(x_session_id)
reading_guard_manager.set_manual_answer(session_id, request.field_id, request.value)
return {
"success": True,
"session_id": session_id,
"field_id": request.field_id,
"message": "已设置该字段标准读数",
}

26
backend/app/api/form.py 普通文件
查看文件

@ -0,0 +1,26 @@
from __future__ import annotations
from fastapi import APIRouter
from app.core.dependencies import config_service
router = APIRouter(prefix="/form", tags=["form"])
@router.get("")
async def get_experiment_form(experiment: str = "voice_speed"):
config = config_service.load_validated(experiment)
return config.model_dump(by_alias=True)
@router.get("/list")
async def list_available_experiments():
experiments = config_service.list_experiments()
return {"experiments": experiments, "count": len(experiments)}
@router.get("/{experiment_name}")
async def get_specific_experiment_form(experiment_name: str):
config = config_service.load_validated(experiment_name)
return config.model_dump(by_alias=True)

查看文件

@ -0,0 +1,19 @@
from __future__ import annotations
from fastapi import APIRouter, HTTPException
from app.core.dependencies import measurement_service
from app.schemas.validation import AnalyzeMeasurementRequest, AnalyzeMeasurementResponse, MeasurementMethod
router = APIRouter(prefix="/measurement", tags=["measurement"])
@router.post("/{method}")
async def analyze_measurement(method: MeasurementMethod, payload: AnalyzeMeasurementRequest) -> AnalyzeMeasurementResponse:
try:
return measurement_service.analyze(method, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc)) from exc

72
backend/app/api/value.py 普通文件
查看文件

@ -0,0 +1,72 @@
from __future__ import annotations
from fastapi import APIRouter, Header, HTTPException, Query
from app.core.dependencies import find_field, list_fields, reading_guard_manager, resolve_session_id, session_store
from app.core.validation import FieldValidator
from app.schemas.validation import FieldValidationRequest, FieldValidationResponse
router = APIRouter(prefix="/value", tags=["value"])
@router.post("")
async def validate_field_value(
request: FieldValidationRequest,
experiment: str = Query(default="voice_speed"),
x_session_id: str | None = Header(default=None),
) -> FieldValidationResponse:
session_id = resolve_session_id(x_session_id)
field = find_field(experiment, request.field_id)
base_result = FieldValidator.validate_by_config(request.field_id, request.value, field.validation)
if not base_result.accept:
return base_result
guard_result = reading_guard_manager.validate(
session_id=session_id,
current_field=field,
current_value=request.value,
all_fields=list_fields(experiment),
)
if guard_result is not None:
guard_accept, guard_message = guard_result
if not guard_accept:
return FieldValidationResponse(accept=False, message=guard_message)
session_store.set_value(session_id, request.field_id, request.value)
return FieldValidationResponse(accept=True, message=guard_message)
session_store.set_value(session_id, request.field_id, request.value)
return base_result
@router.get("")
async def get_all_field_values(x_session_id: str | None = Header(default=None)):
session_id = resolve_session_id(x_session_id)
fields = session_store.get_all(session_id)
return {"fields": fields, "count": len(fields), "session_id": session_id}
@router.get("/{field_id}")
async def get_field_value(field_id: str, x_session_id: str | None = Header(default=None)):
session_id = resolve_session_id(x_session_id)
value = session_store.get_value(session_id, field_id)
if value is None:
raise HTTPException(status_code=404, detail=f"field '{field_id}' not found or has no value")
return {"field_id": field_id, "value": value, "session_id": session_id}
@router.delete("/{field_id}")
async def delete_field_value(field_id: str, x_session_id: str | None = Header(default=None)):
session_id = resolve_session_id(x_session_id)
ok = session_store.delete_value(session_id, field_id)
if not ok:
raise HTTPException(status_code=404, detail=f"field '{field_id}' not found")
return {"message": f"field '{field_id}' value deleted", "success": True, "session_id": session_id}
@router.delete("")
async def clear_all_field_values(x_session_id: str | None = Header(default=None)):
session_id = resolve_session_id(x_session_id)
removed_count = session_store.clear(session_id)
return {"message": f"cleared {removed_count} field values", "success": True, "session_id": session_id}

查看文件

查看文件

@ -0,0 +1,52 @@
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Dict, List
from fastapi import HTTPException
from app.schemas.experiment import ExperimentGridConfig
class ExperimentConfigService:
def __init__(self, config_root: Path):
self.config_root = config_root
def _config_path(self, experiment_name: str) -> Path:
return self.config_root / f"{experiment_name}.json"
def load_raw(self, experiment_name: str = "voice_speed") -> Dict[str, Any]:
path = self._config_path(experiment_name)
if not path.exists():
raise HTTPException(status_code=404, detail=f"experiment config '{experiment_name}' not found")
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise HTTPException(status_code=500, detail=f"experiment config format error: {exc}") from exc
def load_validated(self, experiment_name: str = "voice_speed") -> ExperimentGridConfig:
payload = self.load_raw(experiment_name)
try:
return ExperimentGridConfig(**payload)
except Exception as exc:
raise HTTPException(status_code=500, detail=f"config validation failed: {exc}") from exc
def list_experiments(self) -> List[Dict[str, str]]:
if not self.config_root.exists():
return []
result: List[Dict[str, str]] = []
for file in sorted(self.config_root.glob("*.json")):
try:
payload = json.loads(file.read_text(encoding="utf-8"))
result.append(
{
"name": file.stem,
"title": payload.get("title", file.stem),
"description": payload.get("description", ""),
}
)
except Exception:
continue
return result

查看文件

@ -0,0 +1,45 @@
from __future__ import annotations
from pathlib import Path
from typing import List, Optional
from fastapi import HTTPException
from app.core.config_loader import ExperimentConfigService
from app.core.measurement import MeasurementService
from app.core.reading_guard import reading_guard_manager
from app.core.session_store import SessionStore
from app.schemas.experiment import ExperimentGridConfig, GridInputCell
BASE_DIR = Path(__file__).resolve().parent.parent
CONFIG_ROOT = BASE_DIR.parent / "config" / "experiments"
config_service = ExperimentConfigService(config_root=CONFIG_ROOT)
session_store = SessionStore()
measurement_service = MeasurementService()
def _iter_input_cells(config: ExperimentGridConfig):
for sheet in config.sheets:
for row in sheet.cells:
for cell in row:
if isinstance(cell, GridInputCell):
yield cell
def find_field(experiment_name: str, field_id: str) -> GridInputCell:
config = config_service.load_validated(experiment_name)
for cell in _iter_input_cells(config):
if cell.fieldId == field_id:
return cell
raise HTTPException(status_code=404, detail=f"field '{field_id}' not found in experiment '{experiment_name}'")
def list_fields(experiment_name: str) -> List[GridInputCell]:
config = config_service.load_validated(experiment_name)
return list(_iter_input_cells(config))
def resolve_session_id(session_id: Optional[str]) -> str:
return session_id or "default"

查看文件

@ -0,0 +1,90 @@
from __future__ import annotations
import statistics
from typing import Dict, List
from fastapi import HTTPException
from app.schemas.validation import AnalyzeMeasurementRequest, AnalyzeMeasurementResponse, MeasurementMethod
class MeasurementService:
@staticmethod
def _theoretical_velocity(temperature_c: float | None) -> float | None:
if temperature_c is None:
return None
return 331.3 * ((1.0 + temperature_c / 273.15) ** 0.5)
@staticmethod
def _pairwise_deltas(readings_mm: List[float]) -> List[float]:
if len(readings_mm) < 10:
raise HTTPException(status_code=400, detail="standing wave / phase method requires at least 10 cursor readings")
first5 = readings_mm[:5]
last5 = readings_mm[5:10]
return [b - a for a, b in zip(first5, last5)]
def analyze(self, method: MeasurementMethod, payload: AnalyzeMeasurementRequest) -> AnalyzeMeasurementResponse:
if method in (MeasurementMethod.STANDING_WAVE, MeasurementMethod.PHASE):
return self._analyze_wave_method(method, payload)
if method == MeasurementMethod.TIME_DIFF:
return self._analyze_time_diff(payload)
raise HTTPException(status_code=400, detail="unsupported measurement method")
def _analyze_wave_method(
self,
method: MeasurementMethod,
payload: AnalyzeMeasurementRequest,
) -> AnalyzeMeasurementResponse:
if payload.frequency_hz is None:
raise HTTPException(status_code=400, detail="standing wave / phase method requires frequency_hz")
deltas = self._pairwise_deltas(payload.cursor_readings_mm)
mean_delta_mm = statistics.mean(deltas)
std_delta_mm = statistics.pstdev(deltas) if len(deltas) > 1 else 0.0
wavelength_m = (2.0 * mean_delta_mm) / 1000.0
velocity = payload.frequency_hz * wavelength_m
uncertainty = payload.frequency_hz * (2.0 * std_delta_mm / 1000.0)
return AnalyzeMeasurementResponse(
method=method,
sample_count=len(deltas),
velocity_mps=velocity,
wavelength_m=wavelength_m,
uncertainty_mps=uncertainty,
theoretical_velocity_mps=self._theoretical_velocity(payload.temperature_c),
details={
"pair_deltas_mm": deltas,
"mean_delta_mm": mean_delta_mm,
"std_delta_mm": std_delta_mm,
"note": "using pairwise difference (last 5 minus first 5)",
},
)
def _analyze_time_diff(self, payload: AnalyzeMeasurementRequest) -> AnalyzeMeasurementResponse:
distances = payload.distance_readings_mm
times = payload.time_deltas_us
if len(distances) < 1 or len(times) < 1:
raise HTTPException(status_code=400, detail="time diff method requires distance_readings_mm and time_deltas_us")
if len(distances) != len(times):
raise HTTPException(status_code=400, detail="distance_readings_mm and time_deltas_us must have same length")
velocities: List[float] = []
for d_mm, t_us in zip(distances, times):
if t_us <= 0:
raise HTTPException(status_code=400, detail="time_deltas_us must be greater than 0")
velocities.append((d_mm / 1000.0) / (t_us / 1_000_000.0))
mean_v = statistics.mean(velocities)
std_v = statistics.pstdev(velocities) if len(velocities) > 1 else 0.0
return AnalyzeMeasurementResponse(
method=MeasurementMethod.TIME_DIFF,
sample_count=len(velocities),
velocity_mps=mean_v,
uncertainty_mps=std_v,
theoretical_velocity_mps=self._theoretical_velocity(payload.temperature_c),
details={
"single_velocity_mps": velocities,
},
)

查看文件

@ -0,0 +1,127 @@
from __future__ import annotations
from dataclasses import dataclass, field
from threading import Lock
from typing import Any, Dict, List, Optional
from app.hardware.service import oscilloscope_service
from app.schemas.experiment import GridInputCell, ReadingGuardSource
@dataclass
class GuardSessionState:
strict_fields: List[str] = field(default_factory=list)
cursor: int = 0
pending_field: Optional[str] = None
pending_answer: Optional[float] = None
tolerance: float = 0.0
source: ReadingGuardSource = ReadingGuardSource.MANUAL
manual_answers: Dict[str, Any] = field(default_factory=dict)
class ReadingGuardManager:
def __init__(self) -> None:
self._lock = Lock()
self._sessions: Dict[str, GuardSessionState] = {}
def set_manual_answer(self, session_id: str, field_id: str, value: Any) -> None:
with self._lock:
state = self._sessions.setdefault(session_id, GuardSessionState())
state.manual_answers[field_id] = value
def _capture_answer(self, source: ReadingGuardSource, field_id: str, state: GuardSessionState) -> Optional[float]:
if source == ReadingGuardSource.DEVICE_PEAK:
snapshot = oscilloscope_service.capture_peak()
if snapshot.peak_value is None:
return None
return float(snapshot.peak_value)
if source == ReadingGuardSource.DEVICE_FREQUENCY:
snapshot = oscilloscope_service.capture_frequency()
if snapshot.frequency_hz is None:
return None
return float(snapshot.frequency_hz)
if source == ReadingGuardSource.MANUAL:
value = state.manual_answers.get(field_id)
if value is None:
return None
return float(value)
return None
def _ensure_initialized(self, session_id: str, fields: List[GridInputCell]) -> GuardSessionState:
state = self._sessions.setdefault(session_id, GuardSessionState())
if not state.strict_fields:
strict_fields = [
f.fieldId
for f in fields
if f.readingGuard is not None and f.readingGuard.enabled
]
state.strict_fields = strict_fields
if strict_fields:
state.pending_field = strict_fields[0]
field0 = next(f for f in fields if f.fieldId == strict_fields[0])
state.tolerance = field0.readingGuard.tolerance if field0.readingGuard else 0.0
state.source = field0.readingGuard.source if field0.readingGuard else ReadingGuardSource.MANUAL
state.pending_answer = self._capture_answer(state.source, state.pending_field, state)
return state
def _arm_next(self, state: GuardSessionState, fields_map: Dict[str, GridInputCell]) -> None:
if state.cursor >= len(state.strict_fields):
state.pending_field = None
state.pending_answer = None
return
next_field = state.strict_fields[state.cursor]
config = fields_map[next_field].readingGuard
state.pending_field = next_field
state.tolerance = config.tolerance if config else 0.0
state.source = config.source if config else ReadingGuardSource.MANUAL
state.pending_answer = self._capture_answer(state.source, next_field, state)
def validate(
self,
session_id: str,
current_field: GridInputCell,
current_value: Any,
all_fields: List[GridInputCell],
) -> Optional[tuple[bool, str]]:
state = self._ensure_initialized(session_id, all_fields)
if not state.strict_fields:
return None
if current_field.readingGuard is None or not current_field.readingGuard.enabled:
return None
if state.pending_field is None:
return True, "reading process completed"
if current_field.fieldId != state.pending_field:
return False, f"should submit field {state.pending_field}, please follow experiment reading order"
if state.pending_answer is None:
return False, "standard reading not yet captured, please retry"
try:
student_value = float(current_value)
except Exception:
return False, "reading fields must be numeric"
error = abs(student_value - state.pending_answer)
if error > state.tolerance:
return (
False,
f"reading mismatch, expected {state.pending_answer:.6g}, tolerance ±{state.tolerance:.6g}, please re-enter",
)
state.cursor += 1
fields_map = {f.fieldId: f for f in all_fields}
self._arm_next(state, fields_map)
if state.pending_field is None:
return True, "reading correct, all reading steps completed"
return True, f"reading correct, awaiting next: {state.pending_field}"
reading_guard_manager = ReadingGuardManager()

查看文件

@ -0,0 +1,34 @@
from __future__ import annotations
from threading import Lock
from typing import Any, Dict
class SessionStore:
def __init__(self) -> None:
self._lock = Lock()
self._values: Dict[str, Dict[str, Any]] = {}
def set_value(self, session_id: str, field_id: str, value: Any) -> None:
with self._lock:
self._values.setdefault(session_id, {})[field_id] = value
def get_value(self, session_id: str, field_id: str) -> Any:
return self._values.get(session_id, {}).get(field_id)
def get_all(self, session_id: str) -> Dict[str, Any]:
return dict(self._values.get(session_id, {}))
def delete_value(self, session_id: str, field_id: str) -> bool:
with self._lock:
bucket = self._values.get(session_id)
if not bucket or field_id not in bucket:
return False
del bucket[field_id]
return True
def clear(self, session_id: str) -> int:
with self._lock:
count = len(self._values.get(session_id, {}))
self._values[session_id] = {}
return count

查看文件

@ -0,0 +1,53 @@
from __future__ import annotations
import math
import re
from typing import Any
from app.schemas.experiment import ValidationConfig, ValidationType
from app.schemas.validation import FieldValidationResponse
class FieldValidator:
@staticmethod
def _as_float(value: Any) -> float:
if isinstance(value, str) and value.strip() == "":
raise ValueError("empty value")
return float(value)
@classmethod
def validate_by_config(
cls,
field_id: str,
value: Any,
config: ValidationConfig | None,
) -> FieldValidationResponse:
if config is None:
return FieldValidationResponse(accept=True, message="validation passed")
if config.required and (value is None or (isinstance(value, str) and value.strip() == "")):
return FieldValidationResponse(accept=False, message=f"field {field_id} is required")
if value is None:
return FieldValidationResponse(accept=True, message="validation passed")
if config.type == ValidationType.NUMBER:
try:
num = cls._as_float(value)
except Exception:
return FieldValidationResponse(accept=False, message="please enter a valid number")
if config.min is not None and num < config.min:
return FieldValidationResponse(accept=False, message=f"value cannot be less than {config.min}")
if config.max is not None and num > config.max:
return FieldValidationResponse(accept=False, message=f"value cannot be greater than {config.max}")
if math.isnan(num) or math.isinf(num):
return FieldValidationResponse(accept=False, message="invalid numeric value")
return FieldValidationResponse(accept=True, message="validation passed")
if config.type == ValidationType.REGEX and config.pattern is not None:
text = str(value)
if re.fullmatch(config.pattern, text) is None:
return FieldValidationResponse(accept=False, message="field format mismatch")
return FieldValidationResponse(accept=True, message="validation passed")
return FieldValidationResponse(accept=True, message="validation passed")

100
backend/app/exp.md 普通文件
查看文件

@ -0,0 +1,100 @@
# 声速测量实验
## 频率测量
通过示波器读取原始波形通道即可直接测量,
学生读数五次,取平均
## 测量温度
通过温度计测量声速,输入一次
根据公式计算理论声速
## 三个方法
### 驻波法
获取示波器两个通道的图像,主要是接受波通道
```
:MEASUrement:CH<n>:<items>?
功能描述
获取通道测量项的值。
参数
名称
类型
范围
默认值
<n>
离散型
{1|2}
1
{MAX|MIN|PKPK|VTOP|VBASe|VAMP|AVERage|
SQUAresum|CYCRms| CURSorrms|
OVERShoot|PREShoot|PERiod|
FREQuency|RTime|FTime|PWIDth|NWIDth|
<items>
离散型
--
PDUTy|NDUTy|SCREenduty|FRR|FRF|FFR|FFF|
LRR|LRF|LFR|LFF|RDELay|FDELay|RPHAse|
PPULsenum|NPULsenum|RISEedgenum|
FALLedgenum|AREA|CYCLearea|HARDfrequency}
参数注释
Items(电压)
注释
Items(时间)
注释
MAX
最大值
PERiod
周期
MIN
最小值
FREQuency
频率
PKPK
峰峰值
RTime
上升时间
VTOP
顶端值
FTime
下降时间
VBASe
底端值
PWIDth
正脉宽
VAMP
幅度
NWIDth
负脉宽
AVERage
平均值
PDUTy
正占空比
SQUAresum
均方根值
NDUTy
负占空比
CYCRms
周期均方根
SCREenduty
屏幕脉宽比
CURSorrms
游标均方根
```
用MEASure命令测量峰值,同时截图,在峰值发生下降时将前一个图(即最高点)时游标卡尺读数送入OCR获取游标卡尺读数
总共测十次,后五次减去前五次作差取平均算不确定度,在频率已知的情况下即可获取到声速
### 相位法
在表现上使用XY模式观测李萨如图形,但是在示波器端实现和前者没有区别,只是学生端看起来不一样
也测量十次
### 时差法
分析读出的波形,接着计量CH1起始点到CH2起始点的时间之差(学生端使用示波器光标模式,程序端其实是找到两个波形的起始点)
学生需要填写游标卡尺数据(程序用截图+OCR)
测十次

5
backend/app/form.json 普通文件
查看文件

@ -0,0 +1,5 @@
{
"meta":{
"author":"AI+物理实验"
}
}

查看文件

@ -0,0 +1,14 @@
from app.hardware.service import HardwareSnapshot, HardwareStatus, OscilloscopeService, oscilloscope_service
from app.hardware.oscilloscope import Oscilloscope
from app.hardware.progress import Commands, ExecuteCmdInDev, work
__all__ = [
"HardwareSnapshot",
"HardwareStatus",
"OscilloscopeService",
"oscilloscope_service",
"Oscilloscope",
"Commands",
"ExecuteCmdInDev",
"work",
]

查看文件

@ -0,0 +1,157 @@
import usb.core
import usb.util
from typing import Optional, Tuple
class Oscilloscope:
"""基于PyUSB的通用示波器SCPI协议类,支持批量端点通信"""
DEFAULT_VID = 0x5345
DEFAULT_PID = 0x1234
DEFAULT_TIMEOUT_MS = 3000
MAX_PACKET_SIZE = 512 # 通常批量端点最大包大小,实际会从设备读取
def __init__(self, vid: int = DEFAULT_VID, pid: int = DEFAULT_PID):
"""
初始化示波器对象,但不立即连接。
:param vid: USB Vendor ID
:param pid: USB Product ID
"""
self.vid = vid
self.pid = pid
self.device: Optional[usb.core.Device] = None
self.ep_out: Optional[usb.core.Endpoint] = None
self.ep_in: Optional[usb.core.Endpoint] = None
self._attached_drivers = [] # 记录分离的内核驱动接口
def connect(self) -> None:
"""连接USB设备,配置端点,准备通信"""
# 1. 查找设备
dev = usb.core.find(idVendor=self.vid, idProduct=self.pid)
if dev is None:
raise RuntimeError(f"设备未找到 (VID={self.vid:04x}, PID={self.pid:04x})")
if isinstance(dev, usb.core.Device):
self.device = dev
else:
raise TypeError("No Device Found")
# 2. 分离内核驱动(若占用)
try:
cfg = self.device.get_active_configuration()
for intf in cfg:
if self.device.is_kernel_driver_active(intf.bInterfaceNumber):
self.device.detach_kernel_driver(intf.bInterfaceNumber)
self._attached_drivers.append(intf.bInterfaceNumber)
except Exception as E:
raise E
# 3. 设置配置(通常第一个配置即可)
try:
self.device.set_configuration()
except usb.core.USBError as e:
raise RuntimeError(f"设置USB配置失败: {e}")
# 4. 获取批量输入/输出端点(默认接口0,备用设置0)
try:
intf = self.device.get_active_configuration()[(0, 0)] #type:ignore
except KeyError:
raise RuntimeError("未找到接口 (0,0)")
self.ep_out = None
self.ep_in = None
for ep in intf:
if usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_OUT and isinstance(ep, usb.core.Endpoint):
self.ep_out = ep
elif usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_IN and isinstance(ep, usb.core.Endpoint):
self.ep_in = ep
if not self.ep_out or not self.ep_in:
raise RuntimeError("未找到批量输入/输出端点")
def disconnect(self) -> None:
"""断开设备并重新附加内核驱动(如果之前分离过)"""
if self.device is None:
return
# 重新附加内核驱动
for intf_num in self._attached_drivers:
try:
self.device.attach_kernel_driver(intf_num)
except usb.core.USBError:
pass # 忽略重新附加失败
self.device = None
self.ep_out = None
self.ep_in = None
self._attached_drivers.clear()
def send_command_raw(self, cmd: bytes, timeout: int = DEFAULT_TIMEOUT_MS) -> Optional[bytes]:
"""
发送SCPI命令并返回响应数据。
:param cmd: SCPI命令字符串(会自动添加换行符)
:param timeout: 超时时间(毫秒)
:return: 响应字节数据,若失败则返回None
"""
if self.device is None or self.ep_out is None or self.ep_in is None:
raise RuntimeError("设备未连接,请先调用connect()")
# 发送命令
try:
# self.device.write(self.ep_out.bEndpointAddress, cmd_bytes, timeout=timeout)
self.device.write(self.ep_out, cmd, timeout=timeout)
# self.ep_out.write(cmd_bytes, timeout)
except usb.core.USBError as e:
print(f"发送命令失败: {e}")
return None
# 读取响应(直到超时或收到短包)
response = b''
max_packet = self.ep_in.wMaxPacketSize # type: ignore
while True:
try:
# data = self.device.read(self.ep_in.bEndpointAddress, max_packet, timeout=timeout)
data = self.device.read(self.ep_in, max_packet, timeout=timeout)
if not data:
break
response += data.tobytes()
if len(data) < max_packet:
break
except usb.core.USBError as e:
if e.errno == 110: # 超时,表示没有更多数据
break
else:
print(f"读取响应失败: {e}")
return None
return response
def send_command(self, cmd: str, timeout: int = DEFAULT_TIMEOUT_MS) -> Optional[bytes]:
"""
发送SCPI命令并返回响应数据。
:param cmd: SCPI命令字符串(会自动添加换行符)
:param timeout: 超时时间(毫秒)
:return: 响应字节数据,若失败则返回None
"""
if self.device is None or self.ep_out is None or self.ep_in is None:
raise RuntimeError("设备未连接,请先调用connect()")
# 确保命令以换行结尾
if not cmd.endswith('\n'):
cmd += '\n'
cmd_bytes = cmd.encode('ascii')
return self.send_command_raw(cmd_bytes, timeout)
# 可选:提供原始端点访问属性
@property
def out_endpoint(self) -> Optional[usb.core.Endpoint]:
return self.ep_out
@property
def in_endpoint(self) -> Optional[usb.core.Endpoint]:
return self.ep_in
# 支持上下文管理器(with语句)
def __enter__(self):
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.disconnect()

查看文件

@ -0,0 +1,56 @@
from __future__ import annotations
from enum import Enum
from multiprocessing.connection import Connection
from typing import Optional
from app.hardware.oscilloscope import Oscilloscope
class Status(Enum):
IDLE = 0
Waiting = 1
# 规范
# CH1 接原始信号
# CH2 接返回信号
class Commands(Enum):
IDN = ('*IDN?', str)
MEASU_CH1_FREQ = (':MEASUrement:CH1:FREQuency?', float)
MEASU_CH2 = (':MEASUrement:CH2:MAX?', int)
DATA_CH2 = (':DATA:WAVE:SCREen:CH2?', bytes)
def ExecuteCmdInDev(dev:Oscilloscope, cmd:Commands):
resp = dev.send_command(cmd.value[0])
ret = None
if resp:
parser = cmd.value[1]
if parser is str:
ret = resp.decode("ascii", errors="ignore")
elif parser is bytes:
ret = resp
elif parser in (int, float):
ret = parser(resp.decode("ascii", errors="ignore").strip())
else:
ret = parser(resp)
return ret
#
# 工作流程:
# 发动本线程,
# 进入空闲状态,
# 等待用户指出
def work(con:Connection):
with Oscilloscope() as OWON:
idn = ExecuteCmdInDev(OWON, Commands.IDN)
if idn:
print(idn)
peak = ExecuteCmdInDev(OWON, Commands.MEASU_CH2)
if peak is not None:
con.send({"status": Status.Waiting.name, "peak": peak, "idn": idn})
data = ExecuteCmdInDev(OWON, Commands.DATA_CH2)
if data is not None:
con.send({"status": Status.IDLE.name, "data": data})

查看文件

@ -0,0 +1,86 @@
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import Optional
from fastapi import HTTPException
from app.hardware.oscilloscope import Oscilloscope
from app.hardware.progress import Commands, ExecuteCmdInDev
class HardwareStatus(str, Enum):
ONLINE = "online"
OFFLINE = "offline"
SIMULATED = "simulated"
@dataclass
class HardwareSnapshot:
status: HardwareStatus
device_idn: Optional[str] = None
peak_value: Optional[int] = None
frequency_hz: Optional[float] = None
raw_response: Optional[str] = None
note: Optional[str] = None
class OscilloscopeService:
def __init__(self) -> None:
self._cached_status = HardwareStatus.OFFLINE
def _open_device(self) -> Oscilloscope:
try:
return Oscilloscope()
except Exception as exc:
raise HTTPException(status_code=503, detail=f"示波器初始化失败: {exc}") from exc
def probe(self) -> HardwareSnapshot:
try:
with self._open_device() as device:
idn = ExecuteCmdInDev(device, Commands.IDN)
peak_value = ExecuteCmdInDev(device, Commands.MEASU_CH2)
frequency_hz = ExecuteCmdInDev(device, Commands.MEASU_CH1_FREQ)
self._cached_status = HardwareStatus.ONLINE
return HardwareSnapshot(
status=HardwareStatus.ONLINE,
device_idn=idn if isinstance(idn, str) else None,
peak_value=peak_value if isinstance(peak_value, int) else None,
frequency_hz=frequency_hz if isinstance(frequency_hz, float) else None,
raw_response=idn if isinstance(idn, str) else None,
note="已连接真实示波器",
)
except Exception as exc:
self._cached_status = HardwareStatus.SIMULATED
return HardwareSnapshot(
status=HardwareStatus.SIMULATED,
device_idn=None,
peak_value=None,
frequency_hz=None,
raw_response=None,
note=f"示波器不可用,已切换为模拟模式: {exc}",
)
def capture_peak(self) -> HardwareSnapshot:
snapshot = self.probe()
if snapshot.status == HardwareStatus.ONLINE:
return snapshot
return HardwareSnapshot(
status=HardwareStatus.SIMULATED,
peak_value=None,
note="当前没有连接示波器,返回模拟峰值",
)
def capture_frequency(self) -> HardwareSnapshot:
snapshot = self.probe()
if snapshot.status == HardwareStatus.ONLINE:
return snapshot
return HardwareSnapshot(
status=HardwareStatus.SIMULATED,
frequency_hz=None,
note="当前没有连接示波器,无法读取实时频率",
)
oscilloscope_service = OscilloscopeService()

60
backend/app/main.py 普通文件
查看文件

@ -0,0 +1,60 @@
from __future__ import annotations
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from app.api.form import router as form_router
from app.api.device import router as device_router
from app.api.measurement import router as measurement_router
from app.api.value import router as value_router
App = FastAPI(
title="Physics Experiment Backend",
description="Backend service for experiment forms, field validation, and sound velocity calculations",
version="1.0.0",
)
App.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
App.include_router(form_router)
App.include_router(device_router)
App.include_router(value_router)
App.include_router(measurement_router)
@App.get("/")
async def root():
return {
"message": "Physics Experiment Backend",
"version": "1.0.0",
"endpoints": {
"form": ["GET /form", "GET /form/list", "GET /form/{experiment_name}"],
"value": [
"POST /value",
"GET /value",
"GET /value/{field_id}",
"DELETE /value/{field_id}",
"DELETE /value",
],
"device": ["GET /device/status", "POST /device/peak"],
"measurement": ["POST /measurement/{standing_wave|phase|time_diff}"],
"system": ["GET /health"],
},
}
@App.get("/health")
async def health_check():
return {"status": "healthy", "service": "physics-experiment-backend"}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True, log_level="info")

39
backend/app/models.py 普通文件
查看文件

@ -0,0 +1,39 @@
from app.schemas.experiment import (
ExperimentGridConfig,
GridCell,
GridComputedCell,
GridInputCell,
GridLabelCell,
GridSheet,
ReadingGuardConfig,
ReadingGuardSource,
ValidationConfig,
ValidationType,
)
from app.schemas.validation import (
AnalyzeMeasurementRequest,
AnalyzeMeasurementResponse,
FieldValidationRequest,
FieldValidationResponse,
ManualAnswerRequest,
MeasurementMethod,
)
__all__ = [
"ExperimentGridConfig",
"GridCell",
"GridComputedCell",
"GridInputCell",
"GridLabelCell",
"GridSheet",
"ReadingGuardConfig",
"ReadingGuardSource",
"ValidationConfig",
"ValidationType",
"AnalyzeMeasurementRequest",
"AnalyzeMeasurementResponse",
"FieldValidationRequest",
"FieldValidationResponse",
"ManualAnswerRequest",
"MeasurementMethod",
]

9
backend/app/out.pyi 普通文件
查看文件

@ -0,0 +1,9 @@
import numbers
def get_number(path:str) -> numbers.Number:
"""从一个图像文件中使用OCR技术提取数字并返回。"""
pass
def capture_image() -> str:
"""捕获图像并保存到文件系统中,返回图像文件的路径。"""
pass

查看文件

@ -0,0 +1,39 @@
from app.schemas.experiment import (
ExperimentGridConfig,
GridCell,
GridComputedCell,
GridInputCell,
GridLabelCell,
GridSheet,
ReadingGuardConfig,
ReadingGuardSource,
ValidationConfig,
ValidationType,
)
from app.schemas.validation import (
AnalyzeMeasurementRequest,
AnalyzeMeasurementResponse,
FieldValidationRequest,
FieldValidationResponse,
ManualAnswerRequest,
MeasurementMethod,
)
__all__ = [
"ExperimentGridConfig",
"GridCell",
"GridComputedCell",
"GridInputCell",
"GridLabelCell",
"GridSheet",
"ReadingGuardConfig",
"ReadingGuardSource",
"ValidationConfig",
"ValidationType",
"AnalyzeMeasurementRequest",
"AnalyzeMeasurementResponse",
"FieldValidationRequest",
"FieldValidationResponse",
"ManualAnswerRequest",
"MeasurementMethod",
]

查看文件

@ -0,0 +1,81 @@
from __future__ import annotations
from enum import Enum
from typing import Any, List, Literal, Optional, Union
from pydantic import BaseModel, Field
class ValidationType(str, Enum):
NUMBER = "number"
TEXT = "text"
REGEX = "regex"
class ValidationConfig(BaseModel):
type: ValidationType
min: Optional[float] = None
max: Optional[float] = None
pattern: Optional[str] = None
required: bool = False
class ReadingGuardSource(str, Enum):
DEVICE_PEAK = "device_peak"
DEVICE_FREQUENCY = "device_frequency"
MANUAL = "manual"
class ReadingGuardConfig(BaseModel):
enabled: bool = False
source: ReadingGuardSource = ReadingGuardSource.MANUAL
tolerance: float = 0.0
class GridLabelCell(BaseModel):
type: Literal["label"] = "label"
content: str
colSpan: Optional[int] = None
rowSpan: Optional[int] = None
style: Optional[str] = None
class GridInputCell(BaseModel):
type: Literal["input"] = "input"
fieldId: str
placeholder: Optional[str] = None
unit: Optional[str] = None
colSpan: Optional[int] = None
rowSpan: Optional[int] = None
validation: Optional[ValidationConfig] = None
readingGuard: Optional[ReadingGuardConfig] = None
defaultValue: Optional[Any] = None
class GridComputedCell(BaseModel):
type: Literal["computed"] = "computed"
areaId: str
expression: str
variables: List[str] = Field(default_factory=list)
format: Optional[str] = None
colSpan: Optional[int] = None
rowSpan: Optional[int] = None
GridCell = Union[GridLabelCell, GridInputCell, GridComputedCell]
class GridSheet(BaseModel):
id: str
title: Optional[str] = None
columns: int
columnHeaders: Optional[List[str]] = None
columnWidths: Optional[List[str]] = None
rowHeaders: Optional[List[str]] = None
cells: List[List[Optional[GridCell]]]
class ExperimentGridConfig(BaseModel):
title: str
description: Optional[str] = None
sheets: List[GridSheet]

查看文件

@ -0,0 +1,52 @@
from __future__ import annotations
from enum import Enum
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field, model_validator
class FieldValidationRequest(BaseModel):
field_id: str
value: Any
class FieldValidationResponse(BaseModel):
accept: bool
message: str
class ManualAnswerRequest(BaseModel):
field_id: str
value: Any
class MeasurementMethod(str, Enum):
STANDING_WAVE = "standing_wave"
PHASE = "phase"
TIME_DIFF = "time_diff"
class AnalyzeMeasurementRequest(BaseModel):
frequency_hz: Optional[float] = Field(default=None, gt=0)
temperature_c: Optional[float] = None
cursor_readings_mm: List[float] = Field(default_factory=list)
distance_readings_mm: List[float] = Field(default_factory=list)
time_deltas_us: List[float] = Field(default_factory=list)
@model_validator(mode="after")
def ensure_enough_data(self) -> "AnalyzeMeasurementRequest":
total = len(self.cursor_readings_mm) + len(self.distance_readings_mm) + len(self.time_deltas_us)
if total == 0:
raise ValueError("at least one set of measurement data required")
return self
class AnalyzeMeasurementResponse(BaseModel):
method: MeasurementMethod
sample_count: int
velocity_mps: Optional[float] = None
wavelength_m: Optional[float] = None
uncertainty_mps: Optional[float] = None
theoretical_velocity_mps: Optional[float] = None
details: Dict[str, Any] = Field(default_factory=dict)

查看文件

@ -0,0 +1,969 @@
{
"title": "超声波声速测量实验(记录表)",
"description": "按纸质实验记录单组织:基本信息、表1频率与温度、表2驻波法、表3相位法、表4时差法、表5方法比较。",
"containers": [
{
"id": "basic_info",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(3, minmax(0, 1fr))"
},
"children": [
{
"id": "basic_title",
"type": "label",
"content": "## 基本信息"
},
{
"id": "basic_break_1",
"type": "newline"
},
{
"id": "class_name",
"type": "field",
"label": "班级",
"placeholder": "例如:纳米专业2班",
"validation": {
"type": "text",
"required": true
}
},
{
"id": "student_name",
"type": "field",
"label": "姓名",
"placeholder": "请输入姓名",
"validation": {
"type": "text",
"required": true
}
},
{
"id": "student_id",
"type": "field",
"label": "学号",
"placeholder": "请输入学号",
"validation": {
"type": "regex",
"pattern": "^[0-9]{6,20}$",
"required": true
}
}
]
},
{
"id": "table1",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(5, minmax(0, 1fr))"
},
"children": [
{
"id": "table1_title",
"type": "label",
"content": "## 表1 声源频率与介质温度"
},
{
"id": "table1_break_1",
"type": "newline"
},
{
"id": "f1",
"type": "field",
"label": "$f_{1}$",
"placeholder": "36.540",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "f2",
"type": "field",
"label": "$f_{2}$",
"placeholder": "36.539",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "f3",
"type": "field",
"label": "$f_{3}$",
"placeholder": "36.540",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "f4",
"type": "field",
"label": "$f_{4}$",
"placeholder": "36.538",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "f5",
"type": "field",
"label": "$f_{5}$",
"placeholder": "36.542",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "table1_break_2",
"type": "newline"
},
{
"id": "temperature",
"type": "field",
"label": "介质温度 $t$",
"placeholder": "25.0",
"unit": "$^\\circ C$",
"validation": {
"type": "number",
"min": 0,
"max": 60,
"required": true
}
},
{
"id": "frequency_avg",
"type": "area",
"label": "平均频率 $\\bar{f}$",
"expression": "(f1+f2+f3+f4+f5)/5",
"variables": [
"f1",
"f2",
"f3",
"f4",
"f5"
],
"format": "0.000"
},
{
"id": "v0_theory",
"type": "area",
"label": "理论声速 $v_{0}$",
"expression": "331.5 + 0.6 * temperature",
"variables": [
"temperature"
],
"format": "0.00"
}
]
},
{
"id": "table2_standing",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(5, minmax(0, 1fr))"
},
"children": [
{
"id": "table2_title",
"type": "label",
"content": "## 表2 驻波法测量"
},
{
"id": "table2_break_1",
"type": "newline"
},
{
"id": "s_l0",
"type": "field",
"label": "$L_{0}$",
"placeholder": "144.02",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l1",
"type": "field",
"label": "$L_{1}$",
"placeholder": "148.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l2",
"type": "field",
"label": "$L_{2}$",
"placeholder": "153.50",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l3",
"type": "field",
"label": "$L_{3}$",
"placeholder": "158.30",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l4",
"type": "field",
"label": "$L_{4}$",
"placeholder": "163.00",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table2_break_2",
"type": "newline"
},
{
"id": "s_l5",
"type": "field",
"label": "$L_{5}$",
"placeholder": "167.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l6",
"type": "field",
"label": "$L_{6}$",
"placeholder": "172.66",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l7",
"type": "field",
"label": "$L_{7}$",
"placeholder": "177.30",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l8",
"type": "field",
"label": "$L_{8}$",
"placeholder": "182.29",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l9",
"type": "field",
"label": "$L_{9}$",
"placeholder": "186.84",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table2_break_3",
"type": "newline"
},
{
"id": "s_d1",
"type": "area",
"label": "$\\Delta L_{1}$",
"expression": "s_l5 - s_l0",
"variables": ["s_l5", "s_l0"],
"format": "0.00"
},
{
"id": "s_d2",
"type": "area",
"label": "$\\Delta L_{2}$",
"expression": "s_l6 - s_l1",
"variables": ["s_l6", "s_l1"],
"format": "0.00"
},
{
"id": "s_d3",
"type": "area",
"label": "$\\Delta L_{3}$",
"expression": "s_l7 - s_l2",
"variables": ["s_l7", "s_l2"],
"format": "0.00"
},
{
"id": "s_d4",
"type": "area",
"label": "$\\Delta L_{4}$",
"expression": "s_l8 - s_l3",
"variables": ["s_l8", "s_l3"],
"format": "0.00"
},
{
"id": "s_d5",
"type": "area",
"label": "$\\Delta L_{5}$",
"expression": "s_l9 - s_l4",
"variables": ["s_l9", "s_l4"],
"format": "0.00"
},
{
"id": "table2_break_4",
"type": "newline"
},
{
"id": "s_d_avg",
"type": "area",
"label": "$\\overline{\\Delta L}$",
"expression": "(s_d1 + s_d2 + s_d3 + s_d4 + s_d5) / 5",
"variables": ["s_d1", "s_d2", "s_d3", "s_d4", "s_d5"],
"format": "0.00"
},
{
"id": "lambda_standing",
"type": "area",
"label": "$\\lambda$",
"expression": "(2 / 5) * s_d_avg",
"variables": ["s_d_avg"],
"format": "0.00"
},
{
"id": "v_standing",
"type": "area",
"label": "声速 $v$",
"expression": "frequency_avg * lambda_standing",
"variables": ["frequency_avg", "lambda_standing"],
"format": "0.00"
},
{
"id": "err_standing",
"type": "area",
"label": "$A_{\\%}$",
"expression": "((v_standing - v0_theory) / v0_theory) * 100",
"variables": ["v_standing", "v0_theory"],
"format": "0.000"
}
]
},
{
"id": "table3_phase",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(5, minmax(0, 1fr))"
},
"children": [
{
"id": "table3_title",
"type": "label",
"content": "## 表3 相位法测量"
},
{
"id": "table3_break_1",
"type": "newline"
},
{
"id": "p_l0",
"type": "field",
"label": "$L_{0}$",
"placeholder": "182.10",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l1",
"type": "field",
"label": "$L_{1}$",
"placeholder": "191.28",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l2",
"type": "field",
"label": "$L_{2}$",
"placeholder": "196.20",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l3",
"type": "field",
"label": "$L_{3}$",
"placeholder": "201.00",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l4",
"type": "field",
"label": "$L_{4}$",
"placeholder": "205.54",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table3_break_2",
"type": "newline"
},
{
"id": "p_l5",
"type": "field",
"label": "$L_{5}$",
"placeholder": "210.40",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l6",
"type": "field",
"label": "$L_{6}$",
"placeholder": "215.22",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l7",
"type": "field",
"label": "$L_{7}$",
"placeholder": "219.96",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l8",
"type": "field",
"label": "$L_{8}$",
"placeholder": "224.68",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l9",
"type": "field",
"label": "$L_{9}$",
"placeholder": "229.40",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table3_break_3",
"type": "newline"
},
{
"id": "p_d1",
"type": "area",
"label": "$\\Delta L_{1}$",
"expression": "p_l5 - p_l0",
"variables": ["p_l5", "p_l0"],
"format": "0.00"
},
{
"id": "p_d2",
"type": "area",
"label": "$\\Delta L_{2}$",
"expression": "p_l6 - p_l1",
"variables": ["p_l6", "p_l1"],
"format": "0.00"
},
{
"id": "p_d3",
"type": "area",
"label": "$\\Delta L_{3}$",
"expression": "p_l7 - p_l2",
"variables": ["p_l7", "p_l2"],
"format": "0.00"
},
{
"id": "p_d4",
"type": "area",
"label": "$\\Delta L_{4}$",
"expression": "p_l8 - p_l3",
"variables": ["p_l8", "p_l3"],
"format": "0.00"
},
{
"id": "p_d5",
"type": "area",
"label": "$\\Delta L_{5}$",
"expression": "p_l9 - p_l4",
"variables": ["p_l9", "p_l4"],
"format": "0.00"
},
{
"id": "table3_break_4",
"type": "newline"
},
{
"id": "p_d_avg",
"type": "area",
"label": "$\\overline{\\Delta L}$",
"expression": "(p_d1 + p_d2 + p_d3 + p_d4 + p_d5) / 5",
"variables": ["p_d1", "p_d2", "p_d3", "p_d4", "p_d5"],
"format": "0.00"
},
{
"id": "lambda_phase",
"type": "area",
"label": "$\\lambda$",
"expression": "(2 / 5) * p_d_avg",
"variables": ["p_d_avg"],
"format": "0.00"
},
{
"id": "v_phase",
"type": "area",
"label": "声速 $v$",
"expression": "frequency_avg * lambda_phase",
"variables": ["frequency_avg", "lambda_phase"],
"format": "0.00"
},
{
"id": "err_phase",
"type": "area",
"label": "$A_{\\%}$",
"expression": "((v_phase - v0_theory) / v0_theory) * 100",
"variables": ["v_phase", "v0_theory"],
"format": "0.000"
}
]
},
{
"id": "table4_timediff",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(5, minmax(0, 1fr))"
},
"children": [
{
"id": "table4_title",
"type": "label",
"content": "## 表4 时差法测量"
},
{
"id": "table4_break_1",
"type": "newline"
},
{
"id": "t_l1",
"type": "field",
"label": "$L_{1}$",
"placeholder": "202.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l2",
"type": "field",
"label": "$L_{2}$",
"placeholder": "245.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l3",
"type": "field",
"label": "$L_{3}$",
"placeholder": "197.60",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l4",
"type": "field",
"label": "$L_{4}$",
"placeholder": "157.56",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l5",
"type": "field",
"label": "$L_{5}$",
"placeholder": "123.30",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table4_break_2",
"type": "newline"
},
{
"id": "t_l6",
"type": "field",
"label": "$L_{6}$",
"placeholder": "140.00",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l7",
"type": "field",
"label": "$L_{7}$",
"placeholder": "161.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l8",
"type": "field",
"label": "$L_{8}$",
"placeholder": "132.30",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l9",
"type": "field",
"label": "$L_{9}$",
"placeholder": "173.14",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l10",
"type": "field",
"label": "$L_{10}$",
"placeholder": "152.46",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table4_break_3",
"type": "newline"
},
{
"id": "t_t1",
"type": "field",
"label": "$T_{1}$",
"placeholder": "584",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t2",
"type": "field",
"label": "$T_{2}$",
"placeholder": "712",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t3",
"type": "field",
"label": "$T_{3}$",
"placeholder": "572",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t4",
"type": "field",
"label": "$T_{4}$",
"placeholder": "456",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t5",
"type": "field",
"label": "$T_{5}$",
"placeholder": "356",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "table4_break_4",
"type": "newline"
},
{
"id": "t_t6",
"type": "field",
"label": "$T_{6}$",
"placeholder": "404",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t7",
"type": "field",
"label": "$T_{7}$",
"placeholder": "472",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t8",
"type": "field",
"label": "$T_{8}$",
"placeholder": "380",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t9",
"type": "field",
"label": "$T_{9}$",
"placeholder": "500",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t10",
"type": "field",
"label": "$T_{10}$",
"placeholder": "440",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "table4_break_5",
"type": "newline"
},
{
"id": "t_dl1",
"type": "area",
"label": "$\\Delta L_{1}$",
"expression": "t_l6 - t_l1",
"variables": ["t_l6", "t_l1"],
"format": "0.00"
},
{
"id": "t_dl2",
"type": "area",
"label": "$\\Delta L_{2}$",
"expression": "t_l7 - t_l2",
"variables": ["t_l7", "t_l2"],
"format": "0.00"
},
{
"id": "t_dl3",
"type": "area",
"label": "$\\Delta L_{3}$",
"expression": "t_l8 - t_l3",
"variables": ["t_l8", "t_l3"],
"format": "0.00"
},
{
"id": "t_dl4",
"type": "area",
"label": "$\\Delta L_{4}$",
"expression": "t_l9 - t_l4",
"variables": ["t_l9", "t_l4"],
"format": "0.00"
},
{
"id": "t_dl5",
"type": "area",
"label": "$\\Delta L_{5}$",
"expression": "t_l10 - t_l5",
"variables": ["t_l10", "t_l5"],
"format": "0.00"
},
{
"id": "table4_break_6",
"type": "newline"
},
{
"id": "t_dt1",
"type": "area",
"label": "$\\Delta T_{1}$",
"expression": "t_t6 - t_t1",
"variables": ["t_t6", "t_t1"],
"format": "0.00"
},
{
"id": "t_dt2",
"type": "area",
"label": "$\\Delta T_{2}$",
"expression": "t_t7 - t_t2",
"variables": ["t_t7", "t_t2"],
"format": "0.00"
},
{
"id": "t_dt3",
"type": "area",
"label": "$\\Delta T_{3}$",
"expression": "t_t8 - t_t3",
"variables": ["t_t8", "t_t3"],
"format": "0.00"
},
{
"id": "t_dt4",
"type": "area",
"label": "$\\Delta T_{4}$",
"expression": "t_t9 - t_t4",
"variables": ["t_t9", "t_t4"],
"format": "0.00"
},
{
"id": "t_dt5",
"type": "area",
"label": "$\\Delta T_{5}$",
"expression": "t_t10 - t_t5",
"variables": ["t_t10", "t_t5"],
"format": "0.00"
},
{
"id": "table4_break_7",
"type": "newline"
},
{
"id": "t_dl_avg",
"type": "area",
"label": "$\\overline{\\Delta L}$",
"expression": "(t_dl1 + t_dl2 + t_dl3 + t_dl4 + t_dl5) / 5",
"variables": ["t_dl1", "t_dl2", "t_dl3", "t_dl4", "t_dl5"],
"format": "0.00"
},
{
"id": "t_dt_avg",
"type": "area",
"label": "$\\overline{\\Delta T}$",
"expression": "(t_dt1 + t_dt2 + t_dt3 + t_dt4 + t_dt5) / 5",
"variables": ["t_dt1", "t_dt2", "t_dt3", "t_dt4", "t_dt5"],
"format": "0.00"
},
{
"id": "v_time",
"type": "area",
"label": "声速 $v$",
"expression": "1000 * t_dl_avg / t_dt_avg",
"variables": ["t_dl_avg", "t_dt_avg"],
"format": "0.00"
},
{
"id": "err_time",
"type": "area",
"label": "$A_{\\%}$",
"expression": "((v_time - v0_theory) / v0_theory) * 100",
"variables": ["v_time", "v0_theory"],
"format": "0.000"
}
]
},
{
"id": "table5_compare",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(3, minmax(0, 1fr))"
},
"children": [
{
"id": "table5_title",
"type": "label",
"content": "## 表5 几种方法比较"
},
{
"id": "table5_break_1",
"type": "newline"
},
{
"id": "cmp_v_standing",
"type": "area",
"label": "驻波法声速 $v$",
"expression": "v_standing",
"variables": ["v_standing"],
"format": "0.00"
},
{
"id": "cmp_v_phase",
"type": "area",
"label": "相位法声速 $v$",
"expression": "v_phase",
"variables": ["v_phase"],
"format": "0.00"
},
{
"id": "cmp_v_time",
"type": "area",
"label": "时差法声速 $v$",
"expression": "v_time",
"variables": ["v_time"],
"format": "0.00"
},
{
"id": "table5_break_2",
"type": "newline"
},
{
"id": "cmp_err_standing",
"type": "area",
"label": "驻波法 $A_{\\%}$",
"expression": "err_standing",
"variables": ["err_standing"],
"format": "0.000"
},
{
"id": "cmp_err_phase",
"type": "area",
"label": "相位法 $A_{\\%}$",
"expression": "err_phase",
"variables": ["err_phase"],
"format": "0.000"
},
{
"id": "cmp_err_time",
"type": "area",
"label": "时差法 $A_{\\%}$",
"expression": "err_time",
"variables": ["err_time"],
"format": "0.000"
}
]
},
{
"id": "notes_container",
"type": "container",
"layout": "vertical",
"children": [
{
"id": "notes_title",
"type": "label",
"content": "## 实验结论"
},
{
"id": "notes_break_1",
"type": "newline"
},
{
"id": "observation",
"type": "field",
"label": "实验现象与过程记录",
"placeholder": "记录波形变化、李萨如图形变化、时差读数现象等",
"validation": {
"type": "text",
"required": true
}
},
{
"id": "conclusion",
"type": "field",
"label": "结论与误差分析",
"placeholder": "比较三种方法差异,分析系统误差和随机误差来源",
"validation": {
"type": "text",
"required": true
}
}
]
}
]
}

查看文件

@ -0,0 +1,249 @@
{
"title": "超声波声速测量实验(记录表)",
"description": "基于网格表单组织:基本信息、表1频率与温度、表2驻波法、表3相位法、表4时差法、表5方法比较。",
"sheets": [
{
"id": "basic_info",
"title": "基本信息",
"columns": 3,
"cells": [
[
{"type": "label", "content": "班级", "style": "header"},
{"type": "input", "fieldId": "class_name", "placeholder": "纳米专业2班", "validation": {"type": "text", "required": true}},
{"type": "input", "fieldId": "student_name", "placeholder": "请输入姓名", "validation": {"type": "text", "required": true}}
],
[
{"type": "label", "content": "学号", "style": "header"},
{"type": "input", "fieldId": "student_id", "placeholder": "请输入学号", "colSpan": 2, "validation": {"type": "regex", "pattern": "^[0-9]{6,20}$", "required": true}},
null
]
]
},
{
"id": "table1_frequency",
"title": "表1 声源频率与介质温度",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$f/kHz$"},
{"type": "input", "fieldId": "f1", "placeholder": "36.540", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f2", "placeholder": "36.539", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f3", "placeholder": "36.540", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f4", "placeholder": "36.538", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f5", "placeholder": "36.542", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}}
],
[
{"type": "label", "content": "$t/^\\circ C$"},
{"type": "input", "fieldId": "temperature", "placeholder": "25.0", "unit": "$^\\circ C$", "colSpan": 5, "validation": {"type": "number", "min": 0, "max": 60, "required": true}}
],
[
{"type": "label", "content": "$\\bar{f}/kHz$"},
{"type": "computed", "areaId": "frequency_avg", "expression": "(f1+f2+f3+f4+f5)/5", "variables": ["f1","f2","f3","f4","f5"], "format": "0.000", "colSpan": 5}
],
[
{"type": "label", "content": "$v_0/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v0_theory", "expression": "331.5 + 0.6 * temperature", "variables": ["temperature"], "format": "0.00", "colSpan": 5}
]
]
},
{
"id": "table2_standing",
"title": "表2 驻波法测量",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$L_i/mm$"},
{"type": "input", "fieldId": "s_l0", "placeholder": "144.02", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l1", "placeholder": "148.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l2", "placeholder": "153.50", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l3", "placeholder": "158.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l4", "placeholder": "163.00", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$L_{i+5}/mm$"},
{"type": "input", "fieldId": "s_l5", "placeholder": "167.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l6", "placeholder": "172.66", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l7", "placeholder": "177.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l8", "placeholder": "182.29", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l9", "placeholder": "186.84", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$\\Delta L_i/mm$"},
{"type": "computed", "areaId": "s_d1", "expression": "s_l5 - s_l0", "variables": ["s_l5","s_l0"], "format": "0.00"},
{"type": "computed", "areaId": "s_d2", "expression": "s_l6 - s_l1", "variables": ["s_l6","s_l1"], "format": "0.00"},
{"type": "computed", "areaId": "s_d3", "expression": "s_l7 - s_l2", "variables": ["s_l7","s_l2"], "format": "0.00"},
{"type": "computed", "areaId": "s_d4", "expression": "s_l8 - s_l3", "variables": ["s_l8","s_l3"], "format": "0.00"},
{"type": "computed", "areaId": "s_d5", "expression": "s_l9 - s_l4", "variables": ["s_l9","s_l4"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\overline{\\Delta L}/mm$"},
{"type": "computed", "areaId": "s_d_avg", "expression": "(s_d1 + s_d2 + s_d3 + s_d4 + s_d5) / 5", "variables": ["s_d1","s_d2","s_d3","s_d4","s_d5"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$\\lambda/mm$"},
{"type": "computed", "areaId": "lambda_standing", "expression": "(2 / 5) * s_d_avg", "variables": ["s_d_avg"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$v/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v_standing", "expression": "frequency_avg * lambda_standing", "variables": ["frequency_avg","lambda_standing"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$A_{\\%}$"},
{"type": "computed", "areaId": "err_standing", "expression": "((v_standing - v0_theory) / v0_theory) * 100", "variables": ["v_standing","v0_theory"], "format": "0.000", "colSpan": 5}
]
]
},
{
"id": "table3_phase",
"title": "表3 相位法测量",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$L_i/mm$"},
{"type": "input", "fieldId": "p_l0", "placeholder": "182.10", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l1", "placeholder": "191.28", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l2", "placeholder": "196.20", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l3", "placeholder": "201.00", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l4", "placeholder": "205.54", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$L_{i+5}/mm$"},
{"type": "input", "fieldId": "p_l5", "placeholder": "210.40", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l6", "placeholder": "215.22", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l7", "placeholder": "219.96", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l8", "placeholder": "224.68", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l9", "placeholder": "229.40", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$\\Delta L_i/mm$"},
{"type": "computed", "areaId": "p_d1", "expression": "p_l5 - p_l0", "variables": ["p_l5","p_l0"], "format": "0.00"},
{"type": "computed", "areaId": "p_d2", "expression": "p_l6 - p_l1", "variables": ["p_l6","p_l1"], "format": "0.00"},
{"type": "computed", "areaId": "p_d3", "expression": "p_l7 - p_l2", "variables": ["p_l7","p_l2"], "format": "0.00"},
{"type": "computed", "areaId": "p_d4", "expression": "p_l8 - p_l3", "variables": ["p_l8","p_l3"], "format": "0.00"},
{"type": "computed", "areaId": "p_d5", "expression": "p_l9 - p_l4", "variables": ["p_l9","p_l4"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\overline{\\Delta L}/mm$"},
{"type": "computed", "areaId": "p_d_avg", "expression": "(p_d1 + p_d2 + p_d3 + p_d4 + p_d5) / 5", "variables": ["p_d1","p_d2","p_d3","p_d4","p_d5"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$\\lambda/mm$"},
{"type": "computed", "areaId": "lambda_phase", "expression": "(2 / 5) * p_d_avg", "variables": ["p_d_avg"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$v/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v_phase", "expression": "frequency_avg * lambda_phase", "variables": ["frequency_avg","lambda_phase"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$A_{\\%}$"},
{"type": "computed", "areaId": "err_phase", "expression": "((v_phase - v0_theory) / v0_theory) * 100", "variables": ["v_phase","v0_theory"], "format": "0.000", "colSpan": 5}
]
]
},
{
"id": "table4_timediff",
"title": "表4 时差法测量",
"columns": 11,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
"cells": [
[
{"type": "label", "content": "$L_i/mm$"},
{"type": "input", "fieldId": "t_l1", "placeholder": "202.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l2", "placeholder": "245.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l3", "placeholder": "197.60", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l4", "placeholder": "157.56", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l5", "placeholder": "123.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l6", "placeholder": "140.00", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l7", "placeholder": "161.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l8", "placeholder": "132.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l9", "placeholder": "173.14", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l10", "placeholder": "152.46", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$T_i/\\mu s$"},
{"type": "input", "fieldId": "t_t1", "placeholder": "584", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t2", "placeholder": "712", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t3", "placeholder": "572", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t4", "placeholder": "456", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t5", "placeholder": "356", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t6", "placeholder": "404", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t7", "placeholder": "472", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t8", "placeholder": "380", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t9", "placeholder": "500", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t10", "placeholder": "440", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}}
],
[
{"type": "label", "content": "$\\Delta L_i/mm$"},
{"type": "computed", "areaId": "t_dl1", "expression": "t_l6 - t_l1", "variables": ["t_l6","t_l1"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl2", "expression": "t_l7 - t_l2", "variables": ["t_l7","t_l2"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl3", "expression": "t_l8 - t_l3", "variables": ["t_l8","t_l3"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl4", "expression": "t_l9 - t_l4", "variables": ["t_l9","t_l4"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl5", "expression": "t_l10 - t_l5", "variables": ["t_l10","t_l5"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\Delta T_i/\\mu s$"},
{"type": "computed", "areaId": "t_dt1", "expression": "t_t6 - t_t1", "variables": ["t_t6","t_t1"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt2", "expression": "t_t7 - t_t2", "variables": ["t_t7","t_t2"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt3", "expression": "t_t8 - t_t3", "variables": ["t_t8","t_t3"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt4", "expression": "t_t9 - t_t4", "variables": ["t_t9","t_t4"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt5", "expression": "t_t10 - t_t5", "variables": ["t_t10","t_t5"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\overline{\\Delta L}/mm$"},
{"type": "computed", "areaId": "t_dl_avg", "expression": "(t_dl1 + t_dl2 + t_dl3 + t_dl4 + t_dl5) / 5", "variables": ["t_dl1","t_dl2","t_dl3","t_dl4","t_dl5"], "format": "0.00", "colSpan": 10}
],
[
{"type": "label", "content": "$\\overline{\\Delta T}/\\mu s$"},
{"type": "computed", "areaId": "t_dt_avg", "expression": "(t_dt1 + t_dt2 + t_dt3 + t_dt4 + t_dt5) / 5", "variables": ["t_dt1","t_dt2","t_dt3","t_dt4","t_dt5"], "format": "0.00", "colSpan": 10}
],
[
{"type": "label", "content": "$v/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v_time", "expression": "1000 * t_dl_avg / t_dt_avg", "variables": ["t_dl_avg","t_dt_avg"], "format": "0.00", "colSpan": 10}
],
[
{"type": "label", "content": "$A_{\\%}$"},
{"type": "computed", "areaId": "err_time", "expression": "((v_time - v0_theory) / v0_theory) * 100", "variables": ["v_time","v0_theory"], "format": "0.000", "colSpan": 10}
]
]
},
{
"id": "table5_compare",
"title": "表5 几种方法比较",
"columns": 3,
"columnHeaders": ["方法", "声速 $v/(m\\cdot s^{-1})$", "相对误差 $A_{\\%}$"],
"cells": [
[
{"type": "label", "content": "驻波法"},
{"type": "computed", "areaId": "cmp_v_standing", "expression": "v_standing", "variables": ["v_standing"], "format": "0.00"},
{"type": "computed", "areaId": "cmp_err_standing", "expression": "err_standing", "variables": ["err_standing"], "format": "0.000"}
],
[
{"type": "label", "content": "相位法"},
{"type": "computed", "areaId": "cmp_v_phase", "expression": "v_phase", "variables": ["v_phase"], "format": "0.00"},
{"type": "computed", "areaId": "cmp_err_phase", "expression": "err_phase", "variables": ["err_phase"], "format": "0.000"}
],
[
{"type": "label", "content": "时差法"},
{"type": "computed", "areaId": "cmp_v_time", "expression": "v_time", "variables": ["v_time"], "format": "0.00"},
{"type": "computed", "areaId": "cmp_err_time", "expression": "err_time", "variables": ["err_time"], "format": "0.000"}
]
]
},
{
"id": "notes",
"title": "实验结论",
"columns": 1,
"cells": [
[
{"type": "input", "fieldId": "observation", "placeholder": "记录波形变化、李萨如图形变化、时差读数现象等", "validation": {"type": "text", "required": true}}
],
[
{"type": "input", "fieldId": "conclusion", "placeholder": "比较三种方法差异,分析系统误差和随机误差来源", "validation": {"type": "text", "required": true}}
]
]
}
]
}

13
backend/pyproject.toml 普通文件
查看文件

@ -0,0 +1,13 @@
[project]
name = "backend"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"fastapi[standard]>=0.116.1",
"libusb>=1.0.29.post7",
"pydantic>=2.11.3",
"pyusb>=1.3.1",
"uvicorn>=0.35.0",
]

1619
backend/uv.lock 自动生成的 普通文件

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

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 普通文件

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